diff --git a/dg-ui/.gitignore b/dg-ui/.gitignore new file mode 100644 index 0000000..80aab8e --- /dev/null +++ b/dg-ui/.gitignore @@ -0,0 +1,7 @@ +# Generated by Cargo +# will have compiled files and executables +/target +.DS_Store + +# These are backup files generated by rustfmt +**/*.rs.bk diff --git a/hot-dog/AGENTS.md b/dg-ui/AGENTS.md similarity index 100% rename from hot-dog/AGENTS.md rename to dg-ui/AGENTS.md diff --git a/dg-ui/Cargo.lock b/dg-ui/Cargo.lock new file mode 100644 index 0000000..ceb1e00 --- /dev/null +++ b/dg-ui/Cargo.lock @@ -0,0 +1,6480 @@ +# This file is automatically @generated by Cargo. +# It is not intended for manual editing. +version = 4 + +[[package]] +name = "adler2" +version = "2.0.1" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "320119579fcad9c21884f5c4861d16174d0e06250625266f50fe6898340abefa" + +[[package]] +name = "aho-corasick" +version = "1.1.5" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "c982642fa9e8606056828ee9a8505737230110bb1099153c79efe865c59d12ba" +dependencies = [ + "memchr", +] + +[[package]] +name = "aligned" +version = "0.4.3" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "ee4508988c62edf04abd8d92897fca0c2995d907ce1dfeaf369dac3716a40685" +dependencies = [ + "as-slice", +] + +[[package]] +name = "aligned-vec" +version = "0.6.4" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "dc890384c8602f339876ded803c97ad529f3842aba97f6392b3dba0dd171769b" +dependencies = [ + "equator", +] + +[[package]] +name = "anyhow" +version = "1.0.105" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "2cb931c189b85683d69a5cfad41d4d418671e1ac413dd209f3f2fc31e3cfd902" + +[[package]] +name = "arbitrary" +version = "1.5.0" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "3bc62ac97cc33321f50863d514c3bc38a453947a8f9e781137e47c7401020aed" + +[[package]] +name = "arg_enum_proc_macro" +version = "0.3.4" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "0ae92a5119aa49cdbcf6b9f893fe4e1d98b04ccbf82ee0584ad948a44a734dea" +dependencies = [ + "proc-macro2", + "quote", + "syn 2.0.119", +] + +[[package]] +name = "arrayvec" +version = "0.7.8" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "d3fb67a6e08acf24fdeccbac2cb6ac4305825bd1f117462e0e6f2f193345ad56" + +[[package]] +name = "as-slice" +version = "0.2.1" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "516b6b4f0e40d50dcda9365d53964ec74560ad4284da2e7fc97122cd83174516" +dependencies = [ + "stable_deref_trait", +] + +[[package]] +name = "async-stream" +version = "0.3.6" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "0b5a71a6f37880a80d1d7f19efd781e4b5de42c88f0722cc13bcb6cc2cfe8476" +dependencies = [ + "async-stream-impl", + "futures-core", + "pin-project-lite", +] + +[[package]] +name = "async-stream-impl" +version = "0.3.6" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "c7c24de15d275a1ecfd47a380fb4d5ec9bfe0933f309ed5e705b775596a3574d" +dependencies = [ + "proc-macro2", + "quote", + "syn 2.0.119", +] + +[[package]] +name = "async-trait" +version = "0.1.92" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "82f6aeea286b8eb4dd3431a1be1b59d290ace00f5bfd8e2a159bc2a05e2c1667" +dependencies = [ + "proc-macro2", + "quote", + "syn 3.0.10", +] + +[[package]] +name = "async-tungstenite" +version = "0.31.0" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "ee88b4c88ac8c9ea446ad43498955750a4bbe64c4392f21ccfe5d952865e318f" +dependencies = [ + "atomic-waker", + "futures-core", + "futures-io", + "futures-task", + "futures-util", + "log", + "pin-project-lite", + "tungstenite 0.27.0", +] + +[[package]] +name = "atk" +version = "0.18.2" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "241b621213072e993be4f6f3a9e4b45f65b7e6faad43001be957184b7bb1824b" +dependencies = [ + "atk-sys", + "glib", + "libc", +] + +[[package]] +name = "atk-sys" +version = "0.18.2" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "c5e48b684b0ca77d2bbadeef17424c2ea3c897d44d566a1617e7e8f30614d086" +dependencies = [ + "glib-sys", + "gobject-sys", + "libc", + "system-deps", +] + +[[package]] +name = "atomic-waker" +version = "1.1.2" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "1505bd5d3d116872e7271a6d4e16d81d0c8570876c8de68093a09ac269d8aac0" + +[[package]] +name = "autocfg" +version = "1.5.1" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "f2032f911046de80f0a198e0901378627c33f59ea0ac00e363d481118bd70a53" + +[[package]] +name = "av-scenechange" +version = "0.14.1" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "0f321d77c20e19b92c39e7471cf986812cbb46659d2af674adc4331ef3f18394" +dependencies = [ + "aligned", + "anyhow", + "arg_enum_proc_macro", + "arrayvec", + "log", + "num-rational", + "num-traits", + "pastey", + "rayon", + "thiserror 2.0.21", + "v_frame", + "y4m", +] + +[[package]] +name = "av1-grain" +version = "0.2.5" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "8cfddb07216410377231960af4fcab838eaa12e013417781b78bd95ee22077f8" +dependencies = [ + "anyhow", + "arrayvec", + "log", + "nom", + "num-rational", + "v_frame", +] + +[[package]] +name = "avif-serialize" +version = "0.8.9" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "e7178fe5f7d460b13895ebb9dcb28a3a6216d2df2574a0806cb51b555d297f38" +dependencies = [ + "arrayvec", +] + +[[package]] +name = "axum" +version = "0.8.9" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "31b698c5f9a010f6573133b09e0de5408834d0c82f8d7475a89fc1867a71cd90" +dependencies = [ + "axum-core", + "bytes", + "form_urlencoded", + "futures-util", + "http", + "http-body", + "http-body-util", + "itoa", + "matchit", + "memchr", + "mime", + "multer", + "percent-encoding", + "pin-project-lite", + "serde_core", + "serde_json", + "serde_path_to_error", + "serde_urlencoded", + "sync_wrapper", + "tower", + "tower-layer", + "tower-service", +] + +[[package]] +name = "axum-core" +version = "0.5.6" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "08c78f31d7b1291f7ee735c1c6780ccde7785daae9a9206026862dab7d8792d1" +dependencies = [ + "bytes", + "futures-core", + "http", + "http-body", + "http-body-util", + "mime", + "pin-project-lite", + "sync_wrapper", + "tower-layer", + "tower-service", +] + +[[package]] +name = "base64" +version = "0.22.1" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "72b3254f16251a8381aa12e40e3c4d2f0199f8c6508fbecb9d91f575e0fbb8c6" + +[[package]] +name = "base64" +version = "0.23.1" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "ac07cdecf99051d9a5238b80f35af32cdeba5b336e55d957b318b50137e18da5" + +[[package]] +name = "bit_field" +version = "0.10.4" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "cb2907cc03d08cdb1c6724ad0670ce67c4a71e1c45a6d7635224011714cfc4b1" + +[[package]] +name = "bitflags" +version = "1.3.2" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "bef38d45163c2f1dde094a7dfd33ccf595c92905c8f8f4fdc18d06fb1037718a" + +[[package]] +name = "bitflags" +version = "2.13.2" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "3ded4057c258ba199e2d26386d3af3780957ecaee6c4ef4041c6b4b8b97c0b06" +dependencies = [ + "serde_core", +] + +[[package]] +name = "bitstream-io" +version = "4.10.0" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "7eff00be299a18769011411c9def0d827e8f2d7bf0c3dbf53633147a8867fd1f" +dependencies = [ + "no_std_io2", +] + +[[package]] +name = "block" +version = "0.1.6" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "0d8c1fef690941d3e7788d328517591fecc684c084084702d6ff1641e993699a" + +[[package]] +name = "block-buffer" +version = "0.10.4" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "3078c7629b62d3f0439517fa394996acacc5cbc91c5a20d8c658e77abd503a71" +dependencies = [ + "generic-array", +] + +[[package]] +name = "block2" +version = "0.6.2" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "cdeb9d870516001442e364c5220d3574d2da8dc765554b4a617230d33fa58ef5" +dependencies = [ + "objc2", +] + +[[package]] +name = "built" +version = "0.8.1" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "5c0e531d93d39c34eef561e929e8a7f86d77a5af08aac4f6d6e39976c51858e9" + +[[package]] +name = "bumpalo" +version = "3.20.4" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "87a0cf66fd1eb2fb7b822cb78370d82303750809bc6ba855f3f58e517d3238db" + +[[package]] +name = "bytemuck" +version = "1.25.2" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "95832e849adfb21180ccb6826a99da14e5d266ae5c2e668e1602cf234f153797" + +[[package]] +name = "byteorder" +version = "1.5.0" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "1fd0f2584146f6f2ef48085050886acf353beff7305ebd1ae69500e27c67f64b" + +[[package]] +name = "byteorder-lite" +version = "0.1.0" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "8f1fe948ff07f4bd06c30984e69f5b4899c516a3ef74f34df92a2df2ab535495" + +[[package]] +name = "bytes" +version = "1.12.2" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "776dfebd015e2d8732c684a2c71003674ccb49457b539b9e82151ba38e96dd7c" +dependencies = [ + "serde", +] + +[[package]] +name = "cairo-rs" +version = "0.18.5" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "8ca26ef0159422fb77631dc9d17b102f253b876fe1586b03b803e63a309b4ee2" +dependencies = [ + "bitflags 2.13.2", + "cairo-sys-rs", + "glib", + "libc", + "once_cell", + "thiserror 1.0.69", +] + +[[package]] +name = "cairo-sys-rs" +version = "0.18.2" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "685c9fa8e590b8b3d678873528d83411db17242a73fccaed827770ea0fedda51" +dependencies = [ + "glib-sys", + "libc", + "system-deps", +] + +[[package]] +name = "cc" +version = "1.11.3" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "02f0e023adb368345ce0ca6cdfc0f24a06554468d0e8503e14a0841de79bfa69" +dependencies = [ + "find-msvc-tools", + "jobserver", + "libc", + "shlex", +] + +[[package]] +name = "cesu8" +version = "1.1.0" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "6d43a04d8753f35258c91f8ec639f792891f748a1edbd759cf1dcea3382ad83c" + +[[package]] +name = "cfb" +version = "0.7.3" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "d38f2da7a0a2c4ccf0065be06397cc26a81f4e528be095826eee9d4adbb8c60f" +dependencies = [ + "byteorder", + "fnv", + "uuid", +] + +[[package]] +name = "cfg-expr" +version = "0.15.8" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "d067ad48b8650848b989a59a86c6c36a995d02d2bf778d45c3c5d57bc2718f02" +dependencies = [ + "smallvec", + "target-lexicon", +] + +[[package]] +name = "cfg-if" +version = "1.0.5" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "4e7648175b45a9a48536d676f68d918270699102aa8dab5496df06904c914600" + +[[package]] +name = "cfg_aliases" +version = "0.2.2" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "f079e83a288787bcd14a6aea84cee5c87a67c5a3e660c30f557a3d24761b3527" + +[[package]] +name = "chacha20" +version = "0.10.2" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "65c35e4b699c7e15ccbe7ee35c005e4fc0a278d22238a2857e6ce2dadeda1b06" +dependencies = [ + "cfg-if", + "cpufeatures 0.3.1", + "rand_core 0.10.1", +] + +[[package]] +name = "charset" +version = "0.1.5" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "f1f927b07c74ba84c7e5fe4db2baeb3e996ab2688992e39ac68ce3220a677c7e" +dependencies = [ + "base64 0.22.1", + "encoding_rs", +] + +[[package]] +name = "ciborium" +version = "0.2.2" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "42e69ffd6f0917f5c029256a24d0161db17cea3997d185db0d35926308770f0e" +dependencies = [ + "ciborium-io", + "ciborium-ll", + "serde", +] + +[[package]] +name = "ciborium-io" +version = "0.2.2" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "05afea1e0a06c9be33d539b876f1ce3692f4afea2cb41f740e7743225ed1c757" + +[[package]] +name = "ciborium-ll" +version = "0.2.2" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "57663b653d948a338bfb3eeba9bb2fd5fcfaecb9e199e87e1eda4d9e8b240fd9" +dependencies = [ + "ciborium-io", + "half", +] + +[[package]] +name = "cocoa" +version = "0.26.1" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "ad36507aeb7e16159dfe68db81ccc27571c3ccd4b76fb2fb72fc59e7a4b1b64c" +dependencies = [ + "bitflags 2.13.2", + "block", + "cocoa-foundation", + "core-foundation", + "core-graphics 0.24.0", + "foreign-types 0.5.0", + "libc", + "objc", +] + +[[package]] +name = "cocoa-foundation" +version = "0.2.1" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "81411967c50ee9a1fc11365f8c585f863a22a9697c89239c452292c40ba79b0d" +dependencies = [ + "bitflags 2.13.2", + "block", + "core-foundation", + "core-graphics-types", + "objc", +] + +[[package]] +name = "color_quant" +version = "1.1.0" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "3d7b894f5411737b7867f4827955924d7c254fc9f4d91a6aad6b097804b1018b" + +[[package]] +name = "combine" +version = "4.6.9" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "4356eba6976435498d05a311ee9fc486da3bc81c200d3f0d7dd9703b41913f92" +dependencies = [ + "bytes", + "memchr", +] + +[[package]] +name = "const-serialize" +version = "0.7.2" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "ad7154afa56de2f290e3c82c2c6dc4f5b282b6870903f56ef3509aba95866edc" +dependencies = [ + "const-serialize-macro 0.7.2", +] + +[[package]] +name = "const-serialize" +version = "0.8.0-alpha.0" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "9e42cd5aabba86f128b3763da1fec1491c0f728ce99245062cd49b6f9e6d235b" +dependencies = [ + "const-serialize 0.7.2", + "const-serialize-macro 0.8.0-alpha.3", + "serde", +] + +[[package]] +name = "const-serialize-macro" +version = "0.7.2" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "4f160aad86b4343e8d4e261fee9965c3005b2fd6bc117d172ab65948779e4acf" +dependencies = [ + "proc-macro2", + "quote", + "syn 2.0.119", +] + +[[package]] +name = "const-serialize-macro" +version = "0.8.0-alpha.3" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "b7d372d7ea4c50890f188c72a08782d5c98bc8c7cc9dc4343b61d8ba8e20c26b" +dependencies = [ + "proc-macro2", + "quote", + "syn 2.0.119", +] + +[[package]] +name = "const-str" +version = "0.7.1" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "b0664d2867b4a32697dfe655557f5c3b187e9b605b38612a748e5ec99811d160" + +[[package]] +name = "const_format" +version = "0.2.37" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "a3decb4d6965448659923544a634a0571ba44cede4e11ef15a5a317126840454" +dependencies = [ + "const_format_proc_macros", + "konst", +] + +[[package]] +name = "const_format_proc_macros" +version = "0.2.37" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "941b570269a642506f08cb5b688c04bfa6cfd41a26f8bcdc49db8fd00c0ab659" +dependencies = [ + "proc-macro2", + "quote", + "unicode-xid", +] + +[[package]] +name = "content_disposition" +version = "0.4.0" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "ebc14a88e1463ddd193906285abe5c360c7e8564e05ccc5d501755f7fbc9ca9c" +dependencies = [ + "charset", +] + +[[package]] +name = "convert_case" +version = "0.4.0" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "6245d59a3e82a7fc217c5828a6692dbc6dfb63a0c8c90495621f7b9d79704a0e" + +[[package]] +name = "convert_case" +version = "0.8.0" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "baaaa0ecca5b51987b9423ccdc971514dd8b0bb7b4060b983d3664dad3f1f89f" +dependencies = [ + "unicode-segmentation", +] + +[[package]] +name = "convert_case" +version = "0.10.0" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "633458d4ef8c78b72454de2d54fd6ab2e60f9e02be22f3c6104cdc8a4e0fceb9" +dependencies = [ + "unicode-segmentation", +] + +[[package]] +name = "cookie" +version = "0.18.3" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "d55f2d6c30eeec7d5c6f98bd4395d4abb1895629eab97ee6522d340623615f8a" +dependencies = [ + "percent-encoding", + "time", + "version_check", +] + +[[package]] +name = "cookie_store" +version = "0.22.1" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "15b2c103cf610ec6cae3da84a766285b42fd16aad564758459e6ecf128c75206" +dependencies = [ + "cookie", + "document-features", + "idna", + "log", + "publicsuffix", + "serde", + "serde_derive", + "serde_json", + "time", + "url", +] + +[[package]] +name = "core-foundation" +version = "0.10.1" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "b2a6cd9ae233e7f62ba4e9353e81a88df7fc8a5987b8d445b4d90c879bd156f6" +dependencies = [ + "core-foundation-sys", + "libc", +] + +[[package]] +name = "core-foundation-sys" +version = "0.8.7" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "773648b94d0e5d620f64f280777445740e61fe701025087ec8b57f45c791888b" + +[[package]] +name = "core-graphics" +version = "0.24.0" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "fa95a34622365fa5bbf40b20b75dba8dfa8c94c734aea8ac9a5ca38af14316f1" +dependencies = [ + "bitflags 2.13.2", + "core-foundation", + "core-graphics-types", + "foreign-types 0.5.0", + "libc", +] + +[[package]] +name = "core-graphics" +version = "0.25.0" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "064badf302c3194842cf2c5d61f56cc88e54a759313879cdf03abdd27d0c3b97" +dependencies = [ + "bitflags 2.13.2", + "core-foundation", + "core-graphics-types", + "foreign-types 0.5.0", + "libc", +] + +[[package]] +name = "core-graphics-types" +version = "0.2.0" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "3d44a101f213f6c4cdc1853d4b78aef6db6bdfa3468798cc1d9912f4735013eb" +dependencies = [ + "bitflags 2.13.2", + "core-foundation", + "libc", +] + +[[package]] +name = "core_detect" +version = "1.0.0" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "7f8f80099a98041a3d1622845c271458a2d73e688351bf3cb999266764b81d48" + +[[package]] +name = "cpufeatures" +version = "0.2.17" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "59ed5838eebb26a2bb2e58f6d5b5316989ae9d08bab10e0e6d103e656d1b0280" +dependencies = [ + "libc", +] + +[[package]] +name = "cpufeatures" +version = "0.3.1" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "5ca28b0ae3115b884660db4118d803791fd6756b6e88f39c0f3f7859060d7566" +dependencies = [ + "libc", +] + +[[package]] +name = "crc32fast" +version = "1.5.6" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "fd9ae8fcb3ea71b0b26338b4ffb13006bb175de8fd07921089a906ce7e5e6945" +dependencies = [ + "cfg-if", +] + +[[package]] +name = "crossbeam-channel" +version = "0.5.17" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "98b0cc327b5bc766e7fda9c9260cc0fa81b43a8e240440422dff70788e3f9ef1" +dependencies = [ + "crossbeam-utils", +] + +[[package]] +name = "crossbeam-deque" +version = "0.8.8" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "622f3fc73690be383c7214310406f28a90e6edeadc3cea882f9d71e495b9711a" +dependencies = [ + "crossbeam-epoch", + "crossbeam-utils", +] + +[[package]] +name = "crossbeam-epoch" +version = "0.9.21" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "dc74980687109a3b14c72fd458107bf0baa1da1a1a805e178d15501ba9b86d9d" +dependencies = [ + "crossbeam-utils", +] + +[[package]] +name = "crossbeam-utils" +version = "0.8.23" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "a31eee39dddec8330830986fcd7625edb5a24ec90ea038215273bbc3adb08ac6" + +[[package]] +name = "crunchy" +version = "0.2.4" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "460fbee9c2c2f33933d720630a6a0bac33ba7053db5344fac858d4b8952d77d5" + +[[package]] +name = "crypto-common" +version = "0.1.7" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "78c8292055d1c1df0cce5d180393dc8cce0abec0a7102adb6c7b1eef6016d60a" +dependencies = [ + "generic-array", + "typenum", +] + +[[package]] +name = "cssparser" +version = "0.29.6" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "f93d03419cb5950ccfd3daf3ff1c7a36ace64609a1a8746d493df1ca0afde0fa" +dependencies = [ + "cssparser-macros", + "dtoa-short", + "itoa", + "matches", + "phf 0.10.1", + "proc-macro2", + "quote", + "smallvec", + "syn 1.0.109", +] + +[[package]] +name = "cssparser-macros" +version = "0.6.1" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "13b588ba4ac1a99f7f2964d24b3d896ddc6bf847ee3855dbd4366f058cfcd331" +dependencies = [ + "quote", + "syn 2.0.119", +] + +[[package]] +name = "darling" +version = "0.21.3" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "9cdf337090841a411e2a7f3deb9187445851f91b309c0c0a29e05f74a00a48c0" +dependencies = [ + "darling_core", + "darling_macro", +] + +[[package]] +name = "darling_core" +version = "0.21.3" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "1247195ecd7e3c85f83c8d2a366e4210d588e802133e1e355180a9870b517ea4" +dependencies = [ + "fnv", + "ident_case", + "proc-macro2", + "quote", + "syn 2.0.119", +] + +[[package]] +name = "darling_macro" +version = "0.21.3" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "d38308df82d1080de0afee5d069fa14b0326a88c14f15c5ccda35b4a6c414c81" +dependencies = [ + "darling_core", + "quote", + "syn 2.0.119", +] + +[[package]] +name = "data-encoding" +version = "2.11.1" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "4583a4551df46e2792f82ceeac45e850d2e2d5debba0b91f102385cda5b11f06" + +[[package]] +name = "deranged" +version = "0.5.9" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "9e9de72ce2ad1f90dc62fa25f0f430ef85eb4b0d8fa0be4f30373bc40a21d28e" + +[[package]] +name = "derive_more" +version = "0.99.20" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "6edb4b64a43d977b8e99788fe3a04d483834fba1215a7e02caa415b626497f7f" +dependencies = [ + "convert_case 0.4.0", + "proc-macro2", + "quote", + "rustc_version", + "syn 2.0.119", +] + +[[package]] +name = "derive_more" +version = "2.1.1" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "d751e9e49156b02b44f9c1815bcb94b984cdcc4396ecc32521c739452808b134" +dependencies = [ + "derive_more-impl", +] + +[[package]] +name = "derive_more-impl" +version = "2.1.1" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "799a97264921d8623a957f6c3b9011f3b5492f557bbb7a5a19b7fa6d06ba8dcb" +dependencies = [ + "convert_case 0.10.0", + "proc-macro2", + "quote", + "rustc_version", + "syn 2.0.119", + "unicode-xid", +] + +[[package]] +name = "dg-ui" +version = "0.1.0" +dependencies = [ + "dioxus", +] + +[[package]] +name = "digest" +version = "0.10.7" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "9ed9a281f7bc9b7576e61468ba615a66a5c8cfdff42420a70aa82701a3b1e292" +dependencies = [ + "block-buffer", + "crypto-common", +] + +[[package]] +name = "dioxus" +version = "0.7.10" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "9320593eda4f01858f046698b42441603d2af5fcb62a6c1f9046a0c2eebd6d9b" +dependencies = [ + "dioxus-asset-resolver", + "dioxus-cli-config", + "dioxus-config-macro", + "dioxus-config-macros", + "dioxus-core", + "dioxus-core-macro", + "dioxus-desktop", + "dioxus-devtools", + "dioxus-document", + "dioxus-fullstack", + "dioxus-history", + "dioxus-hooks", + "dioxus-html", + "dioxus-logger", + "dioxus-signals", + "dioxus-stores", + "dioxus-web", + "manganis", + "subsecond", + "warnings", +] + +[[package]] +name = "dioxus-asset-resolver" +version = "0.7.10" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "84235ff0e272f15d4537603cdd50df6d45d50e51bb96326dbc0bdfd01d825226" +dependencies = [ + "dioxus-cli-config", + "http", + "infer", + "jni 0.21.1", + "js-sys", + "ndk", + "ndk-context", + "ndk-sys", + "percent-encoding", + "thiserror 2.0.21", + "tokio", + "wasm-bindgen-futures", + "web-sys", +] + +[[package]] +name = "dioxus-cli-config" +version = "0.7.10" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "322d10f47effebd85ee0662a2cb083ff920d40dd6295a4afd8cfa4f9bc2e05c6" +dependencies = [ + "wasm-bindgen", +] + +[[package]] +name = "dioxus-config-macro" +version = "0.7.10" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "9f3a906c8219e94fa48189a793c760a4e3193cbb7791f799e9d37633fe41161d" +dependencies = [ + "proc-macro2", + "quote", +] + +[[package]] +name = "dioxus-config-macros" +version = "0.7.10" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "20de015bc89c20f4ffc7b4f849943420308365fa66f991250b5c075261990a21" + +[[package]] +name = "dioxus-core" +version = "0.7.10" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "1b232228ada232c0adc151e41ebd9ef70cc04683db097fa0dc6015979fa01722" +dependencies = [ + "anyhow", + "const_format", + "dioxus-core-types", + "futures-channel", + "futures-util", + "generational-box", + "longest-increasing-subsequence", + "rustc-hash 2.1.3", + "rustversion", + "serde", + "slab", + "slotmap", + "subsecond", + "tracing", +] + +[[package]] +name = "dioxus-core-macro" +version = "0.7.10" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "6256a68462222f0600f5fd7d9542cbd9f299bc19355d900f7827dd3fc9e09fdb" +dependencies = [ + "convert_case 0.8.0", + "dioxus-rsx", + "proc-macro2", + "quote", + "syn 2.0.119", +] + +[[package]] +name = "dioxus-core-types" +version = "0.7.10" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "96007ed6cbad951dfed82d83c581aabd95bc591f351f5666d454ddbe7845b324" + +[[package]] +name = "dioxus-desktop" +version = "0.7.10" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "236deb81f1a04de704fb80cf7838c65607441c76914de2e036709540c540a39d" +dependencies = [ + "anyhow", + "async-trait", + "base64 0.22.1", + "bytes", + "cocoa", + "core-foundation", + "dioxus-asset-resolver", + "dioxus-cli-config", + "dioxus-core", + "dioxus-devtools", + "dioxus-document", + "dioxus-history", + "dioxus-hooks", + "dioxus-html", + "dioxus-interpreter-js", + "dioxus-signals", + "dunce", + "futures-channel", + "futures-util", + "generational-box", + "global-hotkey", + "image", + "infer", + "jni 0.21.1", + "lazy-js-bundle", + "libc", + "muda", + "ndk", + "ndk-context", + "ndk-sys", + "objc", + "objc_id", + "percent-encoding", + "rand 0.9.5", + "rfd", + "rustc-hash 2.1.3", + "serde", + "serde_json", + "signal-hook", + "slab", + "subtle", + "tao", + "thiserror 2.0.21", + "tokio", + "tracing", + "tray-icon", + "tungstenite 0.28.0", + "webbrowser", + "wry", +] + +[[package]] +name = "dioxus-devtools" +version = "0.7.10" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "434cebb282b3f820a341582ebfd37dab907d5a25c3eeafd87802468afcd2a959" +dependencies = [ + "dioxus-cli-config", + "dioxus-core", + "dioxus-devtools-types", + "dioxus-signals", + "serde", + "serde_json", + "subsecond", + "thiserror 2.0.21", + "tracing", + "tungstenite 0.28.0", +] + +[[package]] +name = "dioxus-devtools-types" +version = "0.7.10" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "dfd6f3475e38c93be245a664a9ce11679a8f2b99832620705cf7837f42aa39ce" +dependencies = [ + "dioxus-core", + "serde", + "subsecond-types", +] + +[[package]] +name = "dioxus-document" +version = "0.7.10" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "2f6fadd5c6d886b48b762820abae1a08142a2159f8a1136c0466b4b4ed9f547e" +dependencies = [ + "dioxus-core", + "dioxus-core-macro", + "dioxus-core-types", + "dioxus-html", + "futures-channel", + "futures-util", + "generational-box", + "lazy-js-bundle", + "serde", + "serde_json", + "tracing", +] + +[[package]] +name = "dioxus-fullstack" +version = "0.7.10" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "a91d5acabd1470145bcf164cab9fd2edcf2e4fba0fa6fb0fd6dca23079fcc169" +dependencies = [ + "anyhow", + "async-stream", + "async-tungstenite", + "axum", + "axum-core", + "base64 0.22.1", + "bytes", + "ciborium", + "const-str", + "const_format", + "content_disposition", + "derive_more 2.1.1", + "dioxus-asset-resolver", + "dioxus-cli-config", + "dioxus-core", + "dioxus-fullstack-core", + "dioxus-fullstack-macro", + "dioxus-hooks", + "dioxus-html", + "dioxus-signals", + "form_urlencoded", + "futures", + "futures-channel", + "futures-util", + "gloo-net", + "headers", + "http", + "http-body", + "http-body-util", + "js-sys", + "mime", + "pin-project", + "reqwest", + "rustversion", + "send_wrapper", + "serde", + "serde_json", + "serde_qs", + "serde_urlencoded", + "thiserror 2.0.21", + "tokio-util", + "tracing", + "tungstenite 0.27.0", + "url", + "wasm-bindgen", + "wasm-bindgen-futures", + "wasm-streams", + "web-sys", + "xxhash-rust", +] + +[[package]] +name = "dioxus-fullstack-core" +version = "0.7.10" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "0011e9bca8da2ae6bf02ba9ef93ba6c5fa539e402de3aeb316ad86ca77c59079" +dependencies = [ + "anyhow", + "axum-core", + "base64 0.22.1", + "ciborium", + "dioxus-core", + "dioxus-document", + "dioxus-history", + "dioxus-hooks", + "dioxus-signals", + "futures-channel", + "futures-util", + "generational-box", + "http", + "inventory", + "parking_lot", + "serde", + "serde_json", + "thiserror 2.0.21", + "tokio", + "tracing", +] + +[[package]] +name = "dioxus-fullstack-macro" +version = "0.7.10" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "681f39665de36af7bb724b1cc0ca9c2b7c36a2b93febf1b2911716479eac3db0" +dependencies = [ + "const_format", + "convert_case 0.8.0", + "proc-macro2", + "quote", + "syn 2.0.119", + "xxhash-rust", +] + +[[package]] +name = "dioxus-history" +version = "0.7.10" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "2404b77d4441e694a5e93afb5c9a729efb26a3f6920f769cfe6cfedf5c7ac210" +dependencies = [ + "dioxus-core", + "tracing", +] + +[[package]] +name = "dioxus-hooks" +version = "0.7.10" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "9d3807a1bc039299cd37ad85f1c56ae7088210e8a38e3e877f01034d68c15fbb" +dependencies = [ + "dioxus-core", + "dioxus-signals", + "futures-channel", + "futures-util", + "generational-box", + "rustversion", + "slab", + "tracing", +] + +[[package]] +name = "dioxus-html" +version = "0.7.10" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "40b9a85679c4dfd8699407a9ad5041a6a4fe6be0ee386353951cd03b57a12030" +dependencies = [ + "async-trait", + "bytes", + "dioxus-core", + "dioxus-core-macro", + "dioxus-core-types", + "dioxus-hooks", + "dioxus-html-internal-macro", + "enumset", + "euclid", + "futures-channel", + "futures-util", + "generational-box", + "keyboard-types", + "lazy-js-bundle", + "rustversion", + "serde", + "serde_json", + "serde_repr", + "tracing", +] + +[[package]] +name = "dioxus-html-internal-macro" +version = "0.7.10" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "500282dad5b62e91f93e127cbf41c587bf1c457d52514a75f3ff2a55fd0ea9f6" +dependencies = [ + "convert_case 0.8.0", + "proc-macro2", + "quote", + "syn 2.0.119", +] + +[[package]] +name = "dioxus-interpreter-js" +version = "0.7.10" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "faa22cc3431e7efdbae28069542a1763c977d5edbe4d4fbfb0b7667b9c9966e9" +dependencies = [ + "dioxus-core", + "dioxus-core-types", + "dioxus-html", + "js-sys", + "lazy-js-bundle", + "rustc-hash 2.1.3", + "serde", + "sledgehammer_bindgen", + "sledgehammer_utils", + "wasm-bindgen", + "wasm-bindgen-futures", + "web-sys", +] + +[[package]] +name = "dioxus-logger" +version = "0.7.10" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "0f36b2dac4df8c747431f77f2a6644dd033ea98e7f8ac80271ff47fd4ba8a548" +dependencies = [ + "dioxus-cli-config", + "tracing", + "tracing-subscriber", + "tracing-wasm", +] + +[[package]] +name = "dioxus-rsx" +version = "0.7.10" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "aea662c9e13a91279d8acbc0d02a80430c7081704c20e8c791e4c4a151268596" +dependencies = [ + "proc-macro2", + "proc-macro2-diagnostics", + "quote", + "rustversion", + "syn 2.0.119", +] + +[[package]] +name = "dioxus-signals" +version = "0.7.10" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "95d85e36fcaf7abdc986836801bf248776da7d5961f5fac65fdbf5ed491afb4f" +dependencies = [ + "dioxus-core", + "futures-channel", + "futures-util", + "generational-box", + "parking_lot", + "rustc-hash 2.1.3", + "tracing", + "warnings", +] + +[[package]] +name = "dioxus-stores" +version = "0.7.10" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "15eaa9f2ccc5ce962d056515e61345c846a54b13a2b880cf7e8ac93faa53a178" +dependencies = [ + "dioxus-core", + "dioxus-signals", + "dioxus-stores-macro", + "generational-box", +] + +[[package]] +name = "dioxus-stores-macro" +version = "0.7.10" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "a13bd8a693d7042544fa3ac79698a08783bbc698d1ed257e88c5d4059e9ac476" +dependencies = [ + "convert_case 0.8.0", + "proc-macro2", + "quote", + "syn 2.0.119", +] + +[[package]] +name = "dioxus-web" +version = "0.7.10" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "481093233d789c5ffbdde66e7970e803b01a199a7ab0c0f8ef84c65d30b7384f" +dependencies = [ + "dioxus-cli-config", + "dioxus-core", + "dioxus-core-types", + "dioxus-devtools", + "dioxus-document", + "dioxus-history", + "dioxus-html", + "dioxus-interpreter-js", + "dioxus-signals", + "futures-channel", + "futures-util", + "generational-box", + "gloo-timers", + "js-sys", + "lazy-js-bundle", + "rustc-hash 2.1.3", + "send_wrapper", + "serde", + "serde-wasm-bindgen", + "serde_json", + "tracing", + "wasm-bindgen", + "wasm-bindgen-futures", + "wasm-streams", + "web-sys", +] + +[[package]] +name = "dirs" +version = "6.0.0" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "c3e8aa94d75141228480295a7d0e7feb620b1a5ad9f12bc40be62411e38cce4e" +dependencies = [ + "dirs-sys", +] + +[[package]] +name = "dirs-sys" +version = "0.5.0" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "e01a3366d27ee9890022452ee61b2b63a67e6f13f58900b651ff5665f0bb1fab" +dependencies = [ + "libc", + "option-ext", + "redox_users", + "windows-sys 0.61.2", +] + +[[package]] +name = "dispatch2" +version = "0.3.1" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "1e0e367e4e7da84520dedcac1901e4da967309406d1e51017ae1abfb97adbd38" +dependencies = [ + "bitflags 2.13.2", + "block2", + "libc", + "objc2", +] + +[[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 = "dlopen2" +version = "0.8.2" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "5e2c5bd4158e66d1e215c49b837e11d62f3267b30c92f1d171c4d3105e3dc4d4" +dependencies = [ + "dlopen2_derive", + "libc", + "once_cell", + "winapi", +] + +[[package]] +name = "dlopen2_derive" +version = "0.4.3" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "0fbbb781877580993a8707ec48672673ec7b81eeba04cfd2310bd28c08e47c8f" +dependencies = [ + "proc-macro2", + "quote", + "syn 2.0.119", +] + +[[package]] +name = "document-features" +version = "0.2.12" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "d4b8a88685455ed29a21542a33abd9cb6510b6b129abadabdcef0f4c55bc8f61" +dependencies = [ + "litrs", +] + +[[package]] +name = "dpi" +version = "0.1.2" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "d8b14ccef22fc6f5a8f4d7d768562a182c04ce9a3b3157b91390b52ddfdf1a76" + +[[package]] +name = "dtoa" +version = "1.0.11" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "4c3cf4824e2d5f025c7b531afcb2325364084a16806f6d47fbc1f5fbd9960590" + +[[package]] +name = "dtoa-short" +version = "0.3.5" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "cd1511a7b6a56299bd043a9c167a6d2bfb37bf84a6dfceaba651168adfb43c87" +dependencies = [ + "dtoa", +] + +[[package]] +name = "dunce" +version = "1.0.5" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "92773504d58c093f6de2459af4af33faa518c13451eb8f2b5698ed3d36e7c813" + +[[package]] +name = "either" +version = "1.19.0" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "0e9c71c2167ca323c882b99918929403426e2373ea17242ff5653e0d5e1058be" + +[[package]] +name = "encoding_rs" +version = "0.8.44" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "89253175e704ab869b04f9db224d38630e0211a53841a79181deae0889e169f5" +dependencies = [ + "cfg-if", + "core_detect", + "multiversion_no_op", + "rustversion", + "scopeguard", + "simdutf8", +] + +[[package]] +name = "enumset" +version = "1.1.15" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "2e6bd2d7c76d078cd7a460fa169f778c42c026fe16d90e37d7a45d37181bdce5" +dependencies = [ + "enumset_derive", +] + +[[package]] +name = "enumset_derive" +version = "0.15.1" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "f60587c2044cabd91c4d4c73e3912e9f1ea7d76905f31c7eec51869305dae044" +dependencies = [ + "darling", + "proc-macro2", + "quote", + "syn 2.0.119", +] + +[[package]] +name = "equator" +version = "0.4.2" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "4711b213838dfee0117e3be6ac926007d7f433d7bbe33595975d4190cb07e6fc" +dependencies = [ + "equator-macro", +] + +[[package]] +name = "equator-macro" +version = "0.4.2" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "44f23cf4b44bfce11a86ace86f8a73ffdec849c9fd00a386a53d278bd9e81fb3" +dependencies = [ + "proc-macro2", + "quote", + "syn 2.0.119", +] + +[[package]] +name = "equivalent" +version = "1.0.3" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "00d174d5400e5e8fd687ad1049e2f578285fa914201b1af7e8b112a4546bd826" + +[[package]] +name = "errno" +version = "0.3.15" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "e35d6e78f4cebb90e51d543db8fe41528851d6deeef6ef21ebd4bfdc1e784776" +dependencies = [ + "libc", + "windows-sys 0.61.2", +] + +[[package]] +name = "euclid" +version = "0.22.14" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "f1a05365e3b1c6d1650318537c7460c6923f1abdd272ad6842baa2b509957a06" +dependencies = [ + "num-traits", + "serde", +] + +[[package]] +name = "exr" +version = "1.74.3" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "cb29d0be702adf92c645d9b2f93472906ba83d400e59f98adb3770ce5c18c2f6" +dependencies = [ + "bit_field", + "half", + "lebe", + "miniz_oxide 0.8.9", + "multiversion", + "rayon-core", + "smallvec", + "zune-inflate", +] + +[[package]] +name = "fastrand" +version = "2.5.0" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "da7c62ceae207dd37ea5b845da6a0696c799f85e97da1ab5b7910be3c1c80223" + +[[package]] +name = "fax" +version = "0.2.7" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "caf1079563223d5d59d83c85886a56e586cfd5c1a26292e971a0fa266531ac5a" + +[[package]] +name = "fdeflate" +version = "0.3.7" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "1e6853b52649d4ac5c0bd02320cddc5ba956bdb407c4b75a2c6b75bf51500f8c" +dependencies = [ + "simd-adler32", +] + +[[package]] +name = "field-offset" +version = "0.3.6" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "38e2275cc4e4fc009b0669731a1e5ab7ebf11f469eaede2bab9309a5b4d6057f" +dependencies = [ + "memoffset", + "rustc_version", +] + +[[package]] +name = "find-msvc-tools" +version = "0.1.15" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "1c66915cc5391097de7a2b0b972e8505aa33c0df401fd3a6811dbdb32881ba48" + +[[package]] +name = "flate2" +version = "1.1.11" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "626d4928326b646e70f65ed36fc7cf9f206bdb68a0019ee7c6b4709da4e084c4" +dependencies = [ + "crc32fast", + "miniz_oxide 0.9.1", + "zlib-rs", +] + +[[package]] +name = "fnv" +version = "1.0.7" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "3f9eec918d3f24069decb9af1554cad7c880e2da24a9afd88aca000531ab82c1" + +[[package]] +name = "foreign-types" +version = "0.3.2" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "f6f339eb8adc052cd2ca78910fda869aefa38d22d5cb648e6485e4d3fc06f3b1" +dependencies = [ + "foreign-types-shared 0.1.1", +] + +[[package]] +name = "foreign-types" +version = "0.5.0" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "d737d9aa519fb7b749cbc3b962edcf310a8dd1f4b67c91c4f83975dbdd17d965" +dependencies = [ + "foreign-types-macros", + "foreign-types-shared 0.3.1", +] + +[[package]] +name = "foreign-types-macros" +version = "0.2.4" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "ea5190182e6915eb873ddbc16e23b711b6eb1f9c00a0d0a3a91b5f6228475225" +dependencies = [ + "proc-macro2", + "quote", + "syn 3.0.10", +] + +[[package]] +name = "foreign-types-shared" +version = "0.1.1" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "00b0228411908ca8685dba7fc2cdd70ec9990a6e753e89b6ac91a84c40fbaf4b" + +[[package]] +name = "foreign-types-shared" +version = "0.3.1" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "aa9a19cbb55df58761df49b23516a86d432839add4af60fc256da840f66ed35b" + +[[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 = "futf" +version = "0.1.5" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "df420e2e84819663797d1ec6544b13c5be84629e7bb00dc960d6917db2987843" +dependencies = [ + "mac", + "new_debug_unreachable", +] + +[[package]] +name = "futures" +version = "0.3.34" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "9a31d2a3fbaaeb2af2368bbdd904aa8e812d3c04a1ee10d3171f52d556e5d0a3" +dependencies = [ + "futures-channel", + "futures-core", + "futures-executor", + "futures-io", + "futures-sink", + "futures-task", + "futures-util", +] + +[[package]] +name = "futures-channel" +version = "0.3.34" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "b1f9e3d69d39e4862ffed03ed071a76f9a13ba1d9109d355b0f0aa6b15e393c4" +dependencies = [ + "futures-core", + "futures-sink", +] + +[[package]] +name = "futures-core" +version = "0.3.34" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "92d699e522242e69e3003b94ecc1f960f3a5e015aa7c5d7486e65ad01dd94f5e" + +[[package]] +name = "futures-executor" +version = "0.3.34" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "031b47cf1a3c6cc8bc2fc76cd437f521619387907d469316e7c0bc278f1f5432" +dependencies = [ + "futures-core", + "futures-task", + "futures-util", +] + +[[package]] +name = "futures-io" +version = "0.3.34" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "53c0fa8157de1303bfffdaa1cc2a673bfffb60102f76b0ef4441659124373fed" + +[[package]] +name = "futures-macro" +version = "0.3.34" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "9fb9654ba8355388abeb8dcb4fc62f511300867002afc858860463bdd9fe0c44" +dependencies = [ + "proc-macro2", + "quote", + "syn 3.0.10", +] + +[[package]] +name = "futures-sink" +version = "0.3.34" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "1944426bf7d03f1d14f708785e4b33efd750b36d48a157b836b3efc15ede8e1d" + +[[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-channel", + "futures-core", + "futures-io", + "futures-macro", + "futures-sink", + "futures-task", + "memchr", + "pin-project-lite", + "slab", +] + +[[package]] +name = "fxhash" +version = "0.2.1" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "c31b6d751ae2c7f11320402d34e41349dd1016f8d5d45e48c4312bc8625af50c" +dependencies = [ + "byteorder", +] + +[[package]] +name = "gdk" +version = "0.18.2" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "d9f245958c627ac99d8e529166f9823fb3b838d1d41fd2b297af3075093c2691" +dependencies = [ + "cairo-rs", + "gdk-pixbuf", + "gdk-sys", + "gio", + "glib", + "libc", + "pango", +] + +[[package]] +name = "gdk-pixbuf" +version = "0.18.5" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "50e1f5f1b0bfb830d6ccc8066d18db35c487b1b2b1e8589b5dfe9f07e8defaec" +dependencies = [ + "gdk-pixbuf-sys", + "gio", + "glib", + "libc", + "once_cell", +] + +[[package]] +name = "gdk-pixbuf-sys" +version = "0.18.0" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "3f9839ea644ed9c97a34d129ad56d38a25e6756f99f3a88e15cd39c20629caf7" +dependencies = [ + "gio-sys", + "glib-sys", + "gobject-sys", + "libc", + "system-deps", +] + +[[package]] +name = "gdk-sys" +version = "0.18.2" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "5c2d13f38594ac1e66619e188c6d5a1adb98d11b2fcf7894fc416ad76aa2f3f7" +dependencies = [ + "cairo-sys-rs", + "gdk-pixbuf-sys", + "gio-sys", + "glib-sys", + "gobject-sys", + "libc", + "pango-sys", + "pkg-config", + "system-deps", +] + +[[package]] +name = "gdkwayland-sys" +version = "0.18.2" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "140071d506d223f7572b9f09b5e155afbd77428cd5cc7af8f2694c41d98dfe69" +dependencies = [ + "gdk-sys", + "glib-sys", + "gobject-sys", + "libc", + "pkg-config", + "system-deps", +] + +[[package]] +name = "gdkx11-sys" +version = "0.18.2" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "6e2e7445fe01ac26f11601db260dd8608fe172514eb63b3b5e261ea6b0f4428d" +dependencies = [ + "gdk-sys", + "glib-sys", + "libc", + "system-deps", + "x11", +] + +[[package]] +name = "generational-box" +version = "0.7.10" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "b8b2dc9b873cd1a8adb80aa5dcef9a8205f781a8a313d5ffb867248cb3bcb764" +dependencies = [ + "parking_lot", + "tracing", +] + +[[package]] +name = "generic-array" +version = "0.14.7" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "85649ca51fd72272d7821adaf274ad91c288277713d9c18820d8499a7ff69e9a" +dependencies = [ + "typenum", + "version_check", +] + +[[package]] +name = "gethostname" +version = "1.1.0" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "1bd49230192a3797a9a4d6abe9b3eed6f7fa4c8a8a4947977c6f80025f92cbd8" +dependencies = [ + "rustix", + "windows-link 0.2.1", +] + +[[package]] +name = "getrandom" +version = "0.1.16" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "8fc3cb4d91f53b50155bdcfd23f6a4c39ae1969c2ae85982b135750cccaf5fce" +dependencies = [ + "cfg-if", + "libc", + "wasi 0.9.0+wasi-snapshot-preview1", +] + +[[package]] +name = "getrandom" +version = "0.2.17" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "ff2abc00be7fca6ebc474524697ae276ad847ad0a6b3faa4bcb027e9a4614ad0" +dependencies = [ + "cfg-if", + "js-sys", + "libc", + "wasi 0.11.1+wasi-snapshot-preview1", + "wasm-bindgen", +] + +[[package]] +name = "getrandom" +version = "0.3.4" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "899def5c37c4fd7b2664648c28120ecec138e4d395b459e5ca34f9cce2dd77fd" +dependencies = [ + "cfg-if", + "libc", + "r-efi 5.3.0", + "wasip2", +] + +[[package]] +name = "getrandom" +version = "0.4.3" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "300e883d756b2e4ec94e02791f39b04b522276138852cfc41d9fb7e904106099" +dependencies = [ + "cfg-if", + "js-sys", + "libc", + "r-efi 6.0.0", + "rand_core 0.10.1", + "wasm-bindgen", +] + +[[package]] +name = "gif" +version = "0.14.2" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "ee8cfcc411d9adbbaba82fb72661cc1bcca13e8bba98b364e62b2dba8f960159" +dependencies = [ + "color_quant", + "weezl", +] + +[[package]] +name = "gio" +version = "0.18.4" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "d4fc8f532f87b79cbc51a79748f16a6828fb784be93145a322fa14d06d354c73" +dependencies = [ + "futures-channel", + "futures-core", + "futures-io", + "futures-util", + "gio-sys", + "glib", + "libc", + "once_cell", + "pin-project-lite", + "smallvec", + "thiserror 1.0.69", +] + +[[package]] +name = "gio-sys" +version = "0.18.1" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "37566df850baf5e4cb0dfb78af2e4b9898d817ed9263d1090a2df958c64737d2" +dependencies = [ + "glib-sys", + "gobject-sys", + "libc", + "system-deps", + "winapi", +] + +[[package]] +name = "glib" +version = "0.18.5" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "233daaf6e83ae6a12a52055f568f9d7cf4671dabb78ff9560ab6da230ce00ee5" +dependencies = [ + "bitflags 2.13.2", + "futures-channel", + "futures-core", + "futures-executor", + "futures-task", + "futures-util", + "gio-sys", + "glib-macros", + "glib-sys", + "gobject-sys", + "libc", + "memchr", + "once_cell", + "smallvec", + "thiserror 1.0.69", +] + +[[package]] +name = "glib-macros" +version = "0.18.5" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "0bb0228f477c0900c880fd78c8759b95c7636dbd7842707f49e132378aa2acdc" +dependencies = [ + "heck 0.4.1", + "proc-macro-crate 2.0.2", + "proc-macro-error", + "proc-macro2", + "quote", + "syn 2.0.119", +] + +[[package]] +name = "glib-sys" +version = "0.18.1" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "063ce2eb6a8d0ea93d2bf8ba1957e78dbab6be1c2220dd3daca57d5a9d869898" +dependencies = [ + "libc", + "system-deps", +] + +[[package]] +name = "global-hotkey" +version = "0.7.0" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "b9247516746aa8e53411a0db9b62b0e24efbcf6a76e0ba73e5a91b512ddabed7" +dependencies = [ + "crossbeam-channel", + "keyboard-types", + "objc2", + "objc2-app-kit", + "once_cell", + "thiserror 2.0.21", + "windows-sys 0.59.0", + "x11rb", + "xkeysym", +] + +[[package]] +name = "gloo-net" +version = "0.6.0" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "c06f627b1a58ca3d42b45d6104bf1e1a03799df472df00988b6ba21accc10580" +dependencies = [ + "futures-channel", + "futures-core", + "futures-sink", + "gloo-utils", + "http", + "js-sys", + "pin-project", + "serde", + "serde_json", + "thiserror 1.0.69", + "wasm-bindgen", + "wasm-bindgen-futures", + "web-sys", +] + +[[package]] +name = "gloo-timers" +version = "0.3.0" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "bbb143cf96099802033e0d4f4963b19fd2e0b728bcf076cd9cf7f6634f092994" +dependencies = [ + "futures-channel", + "futures-core", + "js-sys", + "wasm-bindgen", +] + +[[package]] +name = "gloo-utils" +version = "0.2.0" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "0b5555354113b18c547c1d3a98fbf7fb32a9ff4f6fa112ce823a21641a0ba3aa" +dependencies = [ + "js-sys", + "serde", + "serde_json", + "wasm-bindgen", + "web-sys", +] + +[[package]] +name = "gobject-sys" +version = "0.18.0" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "0850127b514d1c4a4654ead6dedadb18198999985908e6ffe4436f53c785ce44" +dependencies = [ + "glib-sys", + "libc", + "system-deps", +] + +[[package]] +name = "gtk" +version = "0.18.2" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "fd56fb197bfc42bd5d2751f4f017d44ff59fbb58140c6b49f9b3b2bdab08506a" +dependencies = [ + "atk", + "cairo-rs", + "field-offset", + "futures-channel", + "gdk", + "gdk-pixbuf", + "gio", + "glib", + "gtk-sys", + "gtk3-macros", + "libc", + "pango", + "pkg-config", +] + +[[package]] +name = "gtk-sys" +version = "0.18.2" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "8f29a1c21c59553eb7dd40e918be54dccd60c52b049b75119d5d96ce6b624414" +dependencies = [ + "atk-sys", + "cairo-sys-rs", + "gdk-pixbuf-sys", + "gdk-sys", + "gio-sys", + "glib-sys", + "gobject-sys", + "libc", + "pango-sys", + "system-deps", +] + +[[package]] +name = "gtk3-macros" +version = "0.18.2" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "52ff3c5b21f14f0736fed6dcfc0bfb4225ebf5725f3c0209edeec181e4d73e9d" +dependencies = [ + "proc-macro-crate 1.3.1", + "proc-macro-error", + "proc-macro2", + "quote", + "syn 2.0.119", +] + +[[package]] +name = "half" +version = "2.7.1" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "6ea2d84b969582b4b1864a92dc5d27cd2b77b622a8d79306834f1be5ba20d84b" +dependencies = [ + "cfg-if", + "crunchy", + "zerocopy", +] + +[[package]] +name = "hashbrown" +version = "0.17.2" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "735eaa21a6a5ffb2e84362faaeb90c05ba8e19797ca30428478cb6ea3a4921bc" + +[[package]] +name = "headers" +version = "0.4.2" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "fc2700e3fe555c3310aa7286cac6167449f2c87e0eb58769c9208a1c58a1d106" +dependencies = [ + "base64 0.22.1", + "bytes", + "headers-core", + "http", + "httpdate", + "mime", + "sha1", +] + +[[package]] +name = "headers-core" +version = "0.3.0" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "54b4a22553d4242c49fddb9ba998a99962b5cc6f22cb5a3482bec22522403ce4" +dependencies = [ + "http", +] + +[[package]] +name = "heck" +version = "0.4.1" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "95505c38b4572b2d910cecb0281560f54b440a19336cbbcb27bf6ce6adc6f5a8" + +[[package]] +name = "heck" +version = "0.5.0" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "2304e00983f87ffb38b55b444b5e3b60a884b5d30c0fca7d82fe33449bbe55ea" + +[[package]] +name = "html5ever" +version = "0.29.1" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "3b7410cae13cbc75623c98ac4cbfd1f0bedddf3227afc24f370cf0f50a44a11c" +dependencies = [ + "log", + "mac", + "markup5ever", + "match_token", +] + +[[package]] +name = "http" +version = "1.5.0" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "918d3568bebf352712bc2ef3d46a8bcf1a75b373be6539de198e9105cbbf9ce0" +dependencies = [ + "bytes", + "itoa", +] + +[[package]] +name = "http-body" +version = "1.1.0" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "ca2a8f2913ee65f60facd6a5905613afaa448497a0230cc41ce022d93290bc2c" +dependencies = [ + "bytes", + "http", +] + +[[package]] +name = "http-body-util" +version = "0.1.5" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "23169fe34a5fbcdd3f3862e78fb9b6fccd5f02a6dc6f732547005d45631ce71c" +dependencies = [ + "bytes", + "futures-core", + "http", + "http-body", + "pin-project-lite", +] + +[[package]] +name = "httparse" +version = "1.10.1" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "6dbf3de79e51f3d586ab4cb9d5c3e2c14aa28ed23d180cf89b4df0454a69cc87" + +[[package]] +name = "httpdate" +version = "1.0.3" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "df3b46402a9d5adb4c86a0cf463f42e19994e3ee891101b1841f30a545cb49a9" + +[[package]] +name = "hyper" +version = "1.13.0" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "229c6ff5584df4c6becbfe00567128bac768c8cd32ebc8a8366bd81ed072e8f3" +dependencies = [ + "atomic-waker", + "bytes", + "futures-core", + "http", + "http-body", + "httparse", + "itoa", + "pin-project-lite", + "smallvec", + "tokio", + "want", +] + +[[package]] +name = "hyper-rustls" +version = "0.27.10" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "dfa8e654703247911e29c23fbeaa261834bd9bb74efba2f9acddc37bfb127f53" +dependencies = [ + "http", + "hyper", + "hyper-util", + "rustls", + "tokio", + "tokio-rustls", + "tower-service", + "webpki-roots", +] + +[[package]] +name = "hyper-util" +version = "0.1.21" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "ddc03d96684f9226b8a787cdb71488417b53ab5ea8fdb1dac946cb9431cc8bff" +dependencies = [ + "base64 0.23.1", + "bytes", + "futures-channel", + "futures-util", + "http", + "http-body", + "httparse", + "hyper", + "ipnet", + "libc", + "percent-encoding", + "pin-project-lite", + "socket2", + "tokio", + "tower-service", + "tracing", +] + +[[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_locale_core" +version = "2.4.0" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "25d29b57c17c6528d0dc4c2141cfa2d08200465acb537a3909c8b9b8a4a984c0" +dependencies = [ + "displaydoc", + "litemap", + "tinystr", + "writeable", + "zerovec", +] + +[[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", + "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_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", + "writeable", + "yoke", + "zerofrom", + "zerotrie", + "zerovec", +] + +[[package]] +name = "ident_case" +version = "1.0.1" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "b9e0384b61958566e926dc50660321d12159025e767c18e043daf26b70104c39" + +[[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.2.2" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "cb68373c0d6620ef8105e855e7745e18b0d00d3bdb07fb532e434244cdb9a714" +dependencies = [ + "icu_normalizer", + "icu_properties", +] + +[[package]] +name = "image" +version = "0.25.10" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "85ab80394333c02fe689eaf900ab500fbd0c2213da414687ebf995a65d5a6104" +dependencies = [ + "bytemuck", + "byteorder-lite", + "color_quant", + "exr", + "gif", + "image-webp", + "moxcms", + "num-traits", + "png 0.18.1", + "qoi", + "ravif", + "rayon", + "rgb", + "tiff", + "zune-core", + "zune-jpeg", +] + +[[package]] +name = "image-webp" +version = "0.2.4" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "525e9ff3e1a4be2fbea1fdf0e98686a6d98b4d8f937e1bf7402245af1909e8c3" +dependencies = [ + "byteorder-lite", + "quick-error", +] + +[[package]] +name = "imgref" +version = "1.12.3" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "6e44b0a4eaa4c82f441d50a963f2d5f05a787240aeee097597033e72accfd22f" + +[[package]] +name = "indexmap" +version = "2.14.2" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "cc4e190f5d26ca7051642629da2c52fc03bde85a03197c99408dcd291734c855" +dependencies = [ + "equivalent", + "hashbrown", +] + +[[package]] +name = "infer" +version = "0.19.0" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "a588916bfdfd92e71cacef98a63d9b1f0d74d6599980d11894290e7ddefffcf7" +dependencies = [ + "cfb", +] + +[[package]] +name = "interpolate_name" +version = "0.2.4" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "c34819042dc3d3971c46c2190835914dfbe0c3c13f61449b2997f4e9722dfa60" +dependencies = [ + "proc-macro2", + "quote", + "syn 2.0.119", +] + +[[package]] +name = "inventory" +version = "0.3.25" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "6928282826c822ad91bf1c9a1cb90a30ba1c26770749929b4656cd6be829cd7c" +dependencies = [ + "rustversion", +] + +[[package]] +name = "ipnet" +version = "2.12.2" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "791930b43c0d5973160d90a8f3894509f2b273430f5c5c73b668636d0287c5c0" + +[[package]] +name = "itertools" +version = "0.14.0" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "2b192c782037fadd9cfa75548310488aabdbf3d2da73885b31bd0abd03351285" +dependencies = [ + "either", +] + +[[package]] +name = "itoa" +version = "1.0.19" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "3bd1574e617a9a6c1f8f8181bd7e841e1f20e4277607ef28945765188d6284d4" + +[[package]] +name = "javascriptcore-rs" +version = "1.1.2" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "ca5671e9ffce8ffba57afc24070e906da7fc4b1ba66f2cabebf61bf2ea257fcc" +dependencies = [ + "bitflags 1.3.2", + "glib", + "javascriptcore-rs-sys", +] + +[[package]] +name = "javascriptcore-rs-sys" +version = "1.1.1" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "af1be78d14ffa4b75b66df31840478fef72b51f8c2465d4ca7c194da9f7a5124" +dependencies = [ + "glib-sys", + "gobject-sys", + "libc", + "system-deps", +] + +[[package]] +name = "jni" +version = "0.21.1" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "1a87aa2bb7d2af34197c04845522473242e1aa17c12f4935d5856491a7fb8c97" +dependencies = [ + "cesu8", + "cfg-if", + "combine", + "jni-sys 0.3.1", + "log", + "thiserror 1.0.69", + "walkdir", + "windows-sys 0.45.0", +] + +[[package]] +name = "jni" +version = "0.22.4" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "5efd9a482cf3a427f00d6b35f14332adc7902ce91efb778580e180ff90fa3498" +dependencies = [ + "cfg-if", + "combine", + "jni-macros", + "jni-sys 0.4.1", + "log", + "simd_cesu8", + "thiserror 2.0.21", + "walkdir", + "windows-link 0.2.1", +] + +[[package]] +name = "jni-macros" +version = "0.22.4" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "a00109accc170f0bdb141fed3e393c565b6f5e072365c3bd58f5b062591560a3" +dependencies = [ + "proc-macro2", + "quote", + "rustc_version", + "simd_cesu8", + "syn 2.0.119", +] + +[[package]] +name = "jni-sys" +version = "0.3.1" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "41a652e1f9b6e0275df1f15b32661cf0d4b78d4d87ddec5e0c3c20f097433258" +dependencies = [ + "jni-sys 0.4.1", +] + +[[package]] +name = "jni-sys" +version = "0.4.1" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "c6377a88cb3910bee9b0fa88d4f42e1d2da8e79915598f65fb0c7ee14c878af2" +dependencies = [ + "jni-sys-macros", +] + +[[package]] +name = "jni-sys-macros" +version = "0.4.1" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "38c0b942f458fe50cdac086d2f946512305e5631e720728f2a61aabcd47a6264" +dependencies = [ + "quote", + "syn 2.0.119", +] + +[[package]] +name = "jobserver" +version = "0.1.35" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "1c00acbd29eabad4a2392fa0e921c874934dbbf4194312ad20f04a0ed67a3cb3" +dependencies = [ + "getrandom 0.4.3", + "libc", +] + +[[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 = "keyboard-types" +version = "0.7.0" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "b750dcadc39a09dbadd74e118f6dd6598df77fa01df0cfcdc52c28dece74528a" +dependencies = [ + "bitflags 2.13.2", + "serde", + "unicode-segmentation", +] + +[[package]] +name = "konst" +version = "0.2.20" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "128133ed7824fcd73d6e7b17957c5eb7bacb885649bd8c69708b2331a10bcefb" +dependencies = [ + "konst_macro_rules", +] + +[[package]] +name = "konst_macro_rules" +version = "0.2.19" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "a4933f3f57a8e9d9da04db23fb153356ecaf00cbd14aee46279c33dc80925c37" + +[[package]] +name = "kuchikiki" +version = "0.8.8-speedreader" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "02cb977175687f33fa4afa0c95c112b987ea1443e5a51c8f8ff27dc618270cc2" +dependencies = [ + "cssparser", + "html5ever", + "indexmap", + "selectors", +] + +[[package]] +name = "lazy-js-bundle" +version = "0.7.10" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "51cdaa5abc885e2d606e6985281ace220778bde190be20aab1ec2346ed8bd1fa" + +[[package]] +name = "lazy_static" +version = "1.5.1" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "20870f649af7073d53e38067b2a84312175d56ea15217e1b15bc83506ec50afb" + +[[package]] +name = "lebe" +version = "0.5.3" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "7a79a3332a6609480d7d0c9eab957bca6b455b91bb84e66d19f5ff66294b85b8" + +[[package]] +name = "libappindicator" +version = "0.9.0" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "03589b9607c868cc7ae54c0b2a22c8dc03dd41692d48f2d7df73615c6a95dc0a" +dependencies = [ + "glib", + "gtk", + "gtk-sys", + "libappindicator-sys", + "log", +] + +[[package]] +name = "libappindicator-sys" +version = "0.9.0" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "6e9ec52138abedcc58dc17a7c6c0c00a2bdb4f3427c7f63fa97fd0d859155caf" +dependencies = [ + "gtk-sys", + "libloading 0.7.4", + "once_cell", +] + +[[package]] +name = "libc" +version = "0.2.191" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "65cd87c9a6d60536580b316ad985726104730a5151c99845f2490428ef91240a" + +[[package]] +name = "libfuzzer-sys" +version = "0.4.13" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "a9fd2f41a1cba099f79a0b6b6c35656cf7c03351a7bae8ff0f28f25270f929d2" +dependencies = [ + "arbitrary", + "cc", +] + +[[package]] +name = "libloading" +version = "0.7.4" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "b67380fd3b2fbe7527a606e18729d21c6f3951633d0500574c4dc22d2d638b9f" +dependencies = [ + "cfg-if", + "winapi", +] + +[[package]] +name = "libloading" +version = "0.8.9" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "d7c4b02199fee7c5d21a5ae7d8cfa79a6ef5bb2fc834d6e9058e89c825efdc55" +dependencies = [ + "cfg-if", + "windows-link 0.2.1", +] + +[[package]] +name = "libredox" +version = "0.1.25" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "61ff90caf6077a803a240f62fdbe88645a890bbca49ef8174c3cb0404362171d" +dependencies = [ + "libc", +] + +[[package]] +name = "libxdo" +version = "0.6.0" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "00333b8756a3d28e78def82067a377de7fa61b24909000aeaa2b446a948d14db" +dependencies = [ + "libxdo-sys", +] + +[[package]] +name = "libxdo-sys" +version = "0.11.0" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "db23b9e7e2b7831bbd8aac0bbeeeb7b68cbebc162b227e7052e8e55829a09212" +dependencies = [ + "libc", + "x11", +] + +[[package]] +name = "linux-raw-sys" +version = "0.12.1" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "32a66949e030da00e8c7d4434b251670a91556f4144941d37452769c25d58a53" + +[[package]] +name = "litemap" +version = "0.8.3" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "47d9d19d1d6efa0109d2f65ff4c85cddd50bd572e5a00127ab10987290bcefae" + +[[package]] +name = "litrs" +version = "1.1.0" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "02b614978e47ce529faee66579f2b2fe19c94aa96d910a6a9a8043b2b02d8175" + +[[package]] +name = "lock_api" +version = "0.4.14" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "224399e74b87b5f3557511d98dff8b14089b3dadafcab6bb93eab67d3aace965" +dependencies = [ + "scopeguard", +] + +[[package]] +name = "log" +version = "0.4.35" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "5d15f86d12da44cd8d4ec3c73984537eb7f4cadcb9776a575a0a8a05ca11005c" + +[[package]] +name = "longest-increasing-subsequence" +version = "0.1.0" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "b3bd0dd2cd90571056fdb71f6275fada10131182f84899f4b2a916e565d81d86" + +[[package]] +name = "loop9" +version = "0.1.5" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "0fae87c125b03c1d2c0150c90365d7d6bcc53fb73a9acaef207d2d065860f062" +dependencies = [ + "imgref", +] + +[[package]] +name = "lru-slab" +version = "0.1.3" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "4050469837a6ff301cd14c1f8f24f88549e6d548f24f64e2148eb0f72cebc51f" + +[[package]] +name = "mac" +version = "0.1.1" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "c41e0c4fef86961ac6d6f8a82609f55f31b05e4fce149ac5710e439df7619ba4" + +[[package]] +name = "macro-string" +version = "0.1.4" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "1b27834086c65ec3f9387b096d66e99f221cf081c2b738042aa252bcd41204e3" +dependencies = [ + "proc-macro2", + "quote", + "syn 2.0.119", +] + +[[package]] +name = "malloc_buf" +version = "0.0.6" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "62bb907fe88d54d8d9ce32a3cceab4218ed2f6b7d35617cafe9adf84e43919cb" +dependencies = [ + "libc", +] + +[[package]] +name = "manganis" +version = "0.7.10" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "1ed2af894a724a0b6e521f9efe84f98cfdc74a4de6828efef77ffd3b1679fd52" +dependencies = [ + "const-serialize 0.7.2", + "const-serialize 0.8.0-alpha.0", + "jni 0.21.1", + "manganis-core", + "manganis-macro", + "ndk-context", + "objc2", + "thiserror 2.0.21", +] + +[[package]] +name = "manganis-core" +version = "0.7.10" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "e258c71b137bf48deaffb48b8a8a2f994af9e5c3ca201daa20d41e26b379da11" +dependencies = [ + "const-serialize 0.7.2", + "const-serialize 0.8.0-alpha.0", + "dioxus-cli-config", + "dioxus-core-types", + "serde", + "winnow 0.7.15", +] + +[[package]] +name = "manganis-macro" +version = "0.7.10" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "0abae8346bbf637e6d21ac3831863bd5a98657517f5cd2d69d651046b95e7ce9" +dependencies = [ + "dunce", + "macro-string", + "manganis-core", + "proc-macro2", + "quote", + "syn 2.0.119", +] + +[[package]] +name = "markup5ever" +version = "0.14.1" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "c7a7213d12e1864c0f002f52c2923d4556935a43dec5e71355c2760e0f6e7a18" +dependencies = [ + "log", + "phf 0.11.3", + "phf_codegen 0.11.3", + "string_cache", + "string_cache_codegen", + "tendril", +] + +[[package]] +name = "match_token" +version = "0.1.0" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "88a9689d8d44bf9964484516275f5cd4c9b59457a6940c1d5d0ecbb94510a36b" +dependencies = [ + "proc-macro2", + "quote", + "syn 2.0.119", +] + +[[package]] +name = "matchers" +version = "0.2.0" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "d1525a2a28c7f4fa0fc98bb91ae755d1e2d1505079e05539e35bc876b5d65ae9" +dependencies = [ + "regex-automata", +] + +[[package]] +name = "matches" +version = "0.1.10" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "2532096657941c2fea9c289d370a250971c689d4f143798ff67113ec042024a5" + +[[package]] +name = "matchit" +version = "0.8.4" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "47e1ffaa40ddd1f3ed91f717a33c8c0ee23fff369e3aa8772b9605cc1d22f4c3" + +[[package]] +name = "maybe-rayon" +version = "0.1.1" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "8ea1f30cedd69f0a2954655f7188c6a834246d2bcf1e315e2ac40c4b24dc9519" +dependencies = [ + "cfg-if", + "rayon", +] + +[[package]] +name = "memchr" +version = "2.8.3" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "cf8baf1c55e62ffcace7a9f06f4bd9cd3f0c4beb022d3b367256b91b87513d98" + +[[package]] +name = "memfd" +version = "0.6.6" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "57804b2c9b69967f1536a56f86297e367a33b19e98852ed624b84551cdbc0d90" +dependencies = [ + "rustix", +] + +[[package]] +name = "memmap2" +version = "0.9.12" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "6b0ca1155a9ecc25aa12e8313a119f32edf0255fea2f44839c4ac0a12b2ac157" +dependencies = [ + "libc", +] + +[[package]] +name = "memoffset" +version = "0.9.1" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "488016bfae457b036d996092f6cb448677611ce4449e970ceaf42695203f218a" +dependencies = [ + "autocfg", +] + +[[package]] +name = "mime" +version = "0.3.18" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "d5848f5a9e8117cf94f2f90faac24a87ff81600ff8628c1e3deaab572e76bfa1" + +[[package]] +name = "mime_guess" +version = "2.0.5" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "f7c44f8e672c00fe5308fa235f821cb4198414e1c77935c1ab6948d3fd78550e" +dependencies = [ + "mime", + "unicase", +] + +[[package]] +name = "miniz_oxide" +version = "0.8.9" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "1fa76a2c86f704bdb222d66965fb3d63269ce38518b83cb0575fca855ebb6316" +dependencies = [ + "adler2", + "simd-adler32", +] + +[[package]] +name = "miniz_oxide" +version = "0.9.1" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "b63fbc4a50860e98e7b2aa7804ded1db5cbc3aff9193adaff57a6931bf7c4b4c" +dependencies = [ + "adler2", + "simd-adler32", +] + +[[package]] +name = "mio" +version = "1.2.5" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "20521a903f02b0a573cd6840e9d0a5a0cc043d361fe924092cd70f8556cc9c4a" +dependencies = [ + "libc", + "wasi 0.11.1+wasi-snapshot-preview1", + "windows-sys 0.61.2", +] + +[[package]] +name = "moxcms" +version = "0.8.1" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "bb85c154ba489f01b25c0d36ae69a87e4a1c73a72631fc6c0eb6dde34a73e44b" +dependencies = [ + "num-traits", + "pxfm", +] + +[[package]] +name = "muda" +version = "0.17.2" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "7c9fec5a4e89860383d778d10563a605838f8f0b2f9303868937e5ff32e86177" +dependencies = [ + "crossbeam-channel", + "dpi", + "gtk", + "keyboard-types", + "libxdo", + "objc2", + "objc2-app-kit", + "objc2-core-foundation", + "objc2-foundation", + "once_cell", + "png 0.17.16", + "thiserror 2.0.21", + "windows-sys 0.60.2", +] + +[[package]] +name = "multer" +version = "3.1.0" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "83e87776546dc87511aa5ee218730c92b666d7264ab6ed41f9d215af9cd5224b" +dependencies = [ + "bytes", + "encoding_rs", + "futures-util", + "http", + "httparse", + "memchr", + "mime", + "spin", + "version_check", +] + +[[package]] +name = "multiversion" +version = "0.8.1" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "eb8a68be21d0755f83bfe47e79b896cc732687cf1903f0e50585e8d6ecc53076" +dependencies = [ + "multiversion-macros", + "target-features", +] + +[[package]] +name = "multiversion-macros" +version = "0.8.1" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "a05e0c3c3e4edaa21d87c645852ed0b0c3663752bcc6ec43353bd6189dce35e1" +dependencies = [ + "proc-macro2", + "quote", + "syn 2.0.119", + "target-features", +] + +[[package]] +name = "multiversion_no_op" +version = "1.0.0" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "743fb55ba31b18fb1ecef6bdc9aa2743314978ac084044301a7eee33fb99a20d" + +[[package]] +name = "native-tls" +version = "0.2.18" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "465500e14ea162429d264d44189adc38b199b62b1c21eea9f69e4b73cb03bbf2" +dependencies = [ + "libc", + "log", + "openssl", + "openssl-probe", + "openssl-sys", + "schannel", + "security-framework", + "security-framework-sys", + "tempfile", +] + +[[package]] +name = "ndk" +version = "0.9.0" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "c3f42e7bbe13d351b6bead8286a43aac9534b82bd3cc43e47037f012ebfd62d4" +dependencies = [ + "bitflags 2.13.2", + "jni-sys 0.3.1", + "log", + "ndk-sys", + "num_enum", + "raw-window-handle 0.6.2", + "thiserror 1.0.69", +] + +[[package]] +name = "ndk-context" +version = "0.1.1" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "27b02d87554356db9e9a873add8782d4ea6e3e58ea071a9adb9a2e8ddb884a8b" + +[[package]] +name = "ndk-sys" +version = "0.6.0+11769913" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "ee6cda3051665f1fb8d9e08fc35c96d5a244fb1be711a03b71118828afc9a873" +dependencies = [ + "jni-sys 0.3.1", +] + +[[package]] +name = "new_debug_unreachable" +version = "1.0.6" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "650eef8c711430f1a879fdd01d4745a7deea475becfb90269c06775983bbf086" + +[[package]] +name = "no_std_io2" +version = "0.9.4" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "418abd1b6d34fbf6cae440dc874771b0525a604428704c76e48b29a5e67b8003" +dependencies = [ + "memchr", +] + +[[package]] +name = "nodrop" +version = "0.1.14" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "72ef4a56884ca558e5ddb05a1d1e7e1bfd9a68d9ed024c21704cc98872dae1bb" + +[[package]] +name = "nom" +version = "8.0.0" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "df9761775871bdef83bee530e60050f7e54b1105350d6884eb0fb4f46c2f9405" +dependencies = [ + "memchr", +] + +[[package]] +name = "noop_proc_macro" +version = "0.3.0" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "0676bb32a98c1a483ce53e500a81ad9c3d5b3f7c920c28c24e9cb0980d0b5bc8" + +[[package]] +name = "num-bigint" +version = "0.4.8" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "c89e69e7e0f03bea5ef08013795c25018e101932225a656383bd384495ecc367" +dependencies = [ + "num-integer", + "num-traits", +] + +[[package]] +name = "num-conv" +version = "0.2.2" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "521739c6d2bac4aa25192232afe6841231376b2b26d4d9fae5ecf8ca5772e441" + +[[package]] +name = "num-derive" +version = "0.4.2" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "ed3955f1a9c7c0c15e092f9c887db08b1fc683305fdf6eb6684f22555355e202" +dependencies = [ + "proc-macro2", + "quote", + "syn 2.0.119", +] + +[[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-rational" +version = "0.4.2" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "f83d14da390562dca69fc84082e73e548e1ad308d24accdedd2720017cb37824" +dependencies = [ + "num-bigint", + "num-integer", + "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 = "num_enum" +version = "0.7.6" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "5d0bca838442ec211fa11de3a8b0e0e8f3a4522575b5c4c06ed722e005036f26" +dependencies = [ + "num_enum_derive", + "rustversion", +] + +[[package]] +name = "num_enum_derive" +version = "0.7.6" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "680998035259dcfcafe653688bf2aa6d3e2dc05e98be6ab46afb089dc84f1df8" +dependencies = [ + "proc-macro-crate 3.5.0", + "proc-macro2", + "quote", + "syn 2.0.119", +] + +[[package]] +name = "objc" +version = "0.2.7" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "915b1b472bc21c53464d6c8461c9d3af805ba1ef837e1cac254428f4a77177b1" +dependencies = [ + "malloc_buf", +] + +[[package]] +name = "objc2" +version = "0.6.5" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "08849bbd4767dfae9457696856ae1c84fe4e0281bbe4a7abff2d0e06fb7981f8" +dependencies = [ + "objc2-encode", + "objc2-exception-helper", +] + +[[package]] +name = "objc2-app-kit" +version = "0.3.2" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "d49e936b501e5c5bf01fda3a9452ff86dc3ea98ad5f283e1455153142d97518c" +dependencies = [ + "bitflags 2.13.2", + "block2", + "objc2", + "objc2-core-foundation", + "objc2-foundation", +] + +[[package]] +name = "objc2-core-foundation" +version = "0.3.2" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "2a180dd8642fa45cdb7dd721cd4c11b1cadd4929ce112ebd8b9f5803cc79d536" +dependencies = [ + "bitflags 2.13.2", + "dispatch2", + "objc2", +] + +[[package]] +name = "objc2-core-graphics" +version = "0.3.2" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "e022c9d066895efa1345f8e33e584b9f958da2fd4cd116792e15e07e4720a807" +dependencies = [ + "bitflags 2.13.2", + "objc2-core-foundation", +] + +[[package]] +name = "objc2-encode" +version = "4.1.0" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "ef25abbcd74fb2609453eb695bd2f860d389e457f67dc17cafc8b8cbc89d0c33" + +[[package]] +name = "objc2-exception-helper" +version = "0.1.1" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "c7a1c5fbb72d7735b076bb47b578523aedc40f3c439bea6dfd595c089d79d98a" +dependencies = [ + "cc", +] + +[[package]] +name = "objc2-foundation" +version = "0.3.2" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "e3e0adef53c21f888deb4fa59fc59f7eb17404926ee8a6f59f5df0fd7f9f3272" +dependencies = [ + "bitflags 2.13.2", + "block2", + "objc2", + "objc2-core-foundation", +] + +[[package]] +name = "objc2-ui-kit" +version = "0.3.2" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "d87d638e33c06f577498cbcc50491496a3ed4246998a7fbba7ccb98b1e7eab22" +dependencies = [ + "bitflags 2.13.2", + "objc2", + "objc2-core-foundation", + "objc2-foundation", +] + +[[package]] +name = "objc2-web-kit" +version = "0.3.2" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "b2e5aaab980c433cf470df9d7af96a7b46a9d892d521a2cbbb2f8a4c16751e7f" +dependencies = [ + "bitflags 2.13.2", + "block2", + "objc2", + "objc2-app-kit", + "objc2-core-foundation", + "objc2-foundation", +] + +[[package]] +name = "objc_id" +version = "0.1.1" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "c92d4ddb4bd7b50d730c215ff871754d0da6b2178849f8a2a2ab69712d0c073b" +dependencies = [ + "objc", +] + +[[package]] +name = "once_cell" +version = "1.21.4" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "9f7c3e4beb33f85d45ae3e3a1792185706c8e16d043238c593331cc7cd313b50" + +[[package]] +name = "openssl" +version = "0.10.82" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "4de8111e94a56adca7ebfe6c365b6d42f99deb69b74b6becacd4204e2f193aa2" +dependencies = [ + "bitflags 2.13.2", + "cfg-if", + "foreign-types 0.3.2", + "libc", + "openssl-macros", + "openssl-sys", +] + +[[package]] +name = "openssl-macros" +version = "0.1.1" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "a948666b637a0f465e8564c73e89d4dde00d72d4d473cc972f390fc3dcee7d9c" +dependencies = [ + "proc-macro2", + "quote", + "syn 2.0.119", +] + +[[package]] +name = "openssl-probe" +version = "0.2.2" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "7e036b411754132fd6b74e94b74e9a13c5cf606fa93d1885c35860d3060820b1" + +[[package]] +name = "openssl-sys" +version = "0.9.118" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "19c413d6ec9ebaf5e1c829d355cb3e9f783778d700f135be0921d52fce3c60ae" +dependencies = [ + "cc", + "libc", + "pkg-config", + "vcpkg", +] + +[[package]] +name = "option-ext" +version = "0.2.0" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "04744f49eae99ab78e0d5c0b603ab218f515ea8cfe5a456d7629ad883a3b6e7d" + +[[package]] +name = "pango" +version = "0.18.3" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "7ca27ec1eb0457ab26f3036ea52229edbdb74dee1edd29063f5b9b010e7ebee4" +dependencies = [ + "gio", + "glib", + "libc", + "once_cell", + "pango-sys", +] + +[[package]] +name = "pango-sys" +version = "0.18.0" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "436737e391a843e5933d6d9aa102cb126d501e815b83601365a948a518555dc5" +dependencies = [ + "glib-sys", + "gobject-sys", + "libc", + "system-deps", +] + +[[package]] +name = "parking_lot" +version = "0.12.5" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "93857453250e3077bd71ff98b6a65ea6621a19bb0f559a85248955ac12c45a1a" +dependencies = [ + "lock_api", + "parking_lot_core", +] + +[[package]] +name = "parking_lot_core" +version = "0.9.12" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "2621685985a2ebf1c516881c026032ac7deafcda1a2c9b7850dc81e3dfcb64c1" +dependencies = [ + "cfg-if", + "libc", + "redox_syscall", + "smallvec", + "windows-link 0.2.1", +] + +[[package]] +name = "paste" +version = "1.0.15" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "57c0d7b74b563b49d38dae00a0c37d4d6de9b432382b2892f0574ddcae73fd0a" + +[[package]] +name = "pastey" +version = "0.1.1" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "35fb2e5f958ec131621fdd531e9fc186ed768cbe395337403ae56c17a74c68ec" + +[[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.8.0" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "3dfb61232e34fcb633f43d12c58f83c1df82962dcdfa565a4e866ffc17dafe12" +dependencies = [ + "phf_shared 0.8.0", +] + +[[package]] +name = "phf" +version = "0.10.1" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "fabbf1ead8a5bcbc20f5f8b939ee3f5b0f6f281b6ad3468b84656b658b455259" +dependencies = [ + "phf_macros", + "phf_shared 0.10.0", + "proc-macro-hack", +] + +[[package]] +name = "phf" +version = "0.11.3" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "1fd6780a80ae0c52cc120a26a1a42c1ae51b247a253e4e06113d23d2c2edd078" +dependencies = [ + "phf_shared 0.11.3", +] + +[[package]] +name = "phf_codegen" +version = "0.8.0" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "cbffee61585b0411840d3ece935cce9cb6321f01c45477d30066498cd5e1a815" +dependencies = [ + "phf_generator 0.8.0", + "phf_shared 0.8.0", +] + +[[package]] +name = "phf_codegen" +version = "0.11.3" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "aef8048c789fa5e851558d709946d6d79a8ff88c0440c587967f8e94bfb1216a" +dependencies = [ + "phf_generator 0.11.3", + "phf_shared 0.11.3", +] + +[[package]] +name = "phf_generator" +version = "0.8.0" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "17367f0cc86f2d25802b2c26ee58a7b23faeccf78a396094c13dced0d0182526" +dependencies = [ + "phf_shared 0.8.0", + "rand 0.7.3", +] + +[[package]] +name = "phf_generator" +version = "0.10.0" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "5d5285893bb5eb82e6aaf5d59ee909a06a16737a8970984dd7746ba9283498d6" +dependencies = [ + "phf_shared 0.10.0", + "rand 0.8.8", +] + +[[package]] +name = "phf_generator" +version = "0.11.3" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "3c80231409c20246a13fddb31776fb942c38553c51e871f8cbd687a4cfb5843d" +dependencies = [ + "phf_shared 0.11.3", + "rand 0.8.8", +] + +[[package]] +name = "phf_macros" +version = "0.10.0" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "58fdf3184dd560f160dd73922bea2d5cd6e8f064bf4b13110abd81b03697b4e0" +dependencies = [ + "phf_generator 0.10.0", + "phf_shared 0.10.0", + "proc-macro-hack", + "proc-macro2", + "quote", + "syn 1.0.109", +] + +[[package]] +name = "phf_shared" +version = "0.8.0" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "c00cf8b9eafe68dde5e9eaa2cef8ee84a9336a47d566ec55ca16589633b65af7" +dependencies = [ + "siphasher 0.3.11", +] + +[[package]] +name = "phf_shared" +version = "0.10.0" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "b6796ad771acdc0123d2a88dc428b5e38ef24456743ddb1744ed628f9815c096" +dependencies = [ + "siphasher 0.3.11", +] + +[[package]] +name = "phf_shared" +version = "0.11.3" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "67eabc2ef2a60eb7faa00097bd1ffdb5bd28e62bf39990626a582201b7a754e5" +dependencies = [ + "siphasher 1.0.4", +] + +[[package]] +name = "pin-project" +version = "1.2.0" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "a6c2123f4708bbd422630a6dae7c03f678b1ce1f1c99e4c4b3beac69c8174cc9" +dependencies = [ + "pin-project-internal", +] + +[[package]] +name = "pin-project-internal" +version = "1.2.0" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "358938fd6df944c1e44bb328b60fb275f13c804aac47ba26a1165d45a3f87756" +dependencies = [ + "proc-macro2", + "quote", + "syn 3.0.10", +] + +[[package]] +name = "pin-project-lite" +version = "0.2.18" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "c938015719552d665fd0553b90d96cd7ff58e83e4c061ca99e6bb78865a72752" + +[[package]] +name = "pkg-config" +version = "0.3.34" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "f6b464fbc74e149a392436b17d523f769e057cb6877f6a5c4618bc6f11800548" + +[[package]] +name = "png" +version = "0.17.16" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "82151a2fc869e011c153adc57cf2789ccb8d9906ce52c0b39a6b5697749d7526" +dependencies = [ + "bitflags 1.3.2", + "crc32fast", + "fdeflate", + "flate2", + "miniz_oxide 0.8.9", +] + +[[package]] +name = "png" +version = "0.18.1" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "60769b8b31b2a9f263dae2776c37b1b28ae246943cf719eb6946a1db05128a61" +dependencies = [ + "bitflags 2.13.2", + "crc32fast", + "fdeflate", + "flate2", + "miniz_oxide 0.8.9", +] + +[[package]] +name = "pollster" +version = "0.4.0" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "2f3a9f18d041e6d0e102a0a46750538147e5e8992d3b4873aaafee2520b00ce3" + +[[package]] +name = "potential_utf" +version = "0.1.6" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "d83eb9bc6d8e5cf568e7a1101d60ee05e81ed50ea106026f3d18deeb046d7661" +dependencies = [ + "zerovec", +] + +[[package]] +name = "powerfmt" +version = "0.2.1" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "4a6394b9e965e73d0a289ee54f589087e2c676aedf60885baf52c76b771e4958" + +[[package]] +name = "ppv-lite86" +version = "0.2.21" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "85eae3c4ed2f50dcfe72643da4befc30deadb458a9b590d720cde2f2b1e97da9" +dependencies = [ + "zerocopy", +] + +[[package]] +name = "precomputed-hash" +version = "0.1.1" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "925383efa346730478fb4838dbe9137d2a47675ad789c546d150a6e1dd4ab31c" + +[[package]] +name = "proc-macro-crate" +version = "1.3.1" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "7f4c021e1093a56626774e81216a4ce732a735e5bad4868a03f3ed65ca0c3919" +dependencies = [ + "once_cell", + "toml_edit 0.19.15", +] + +[[package]] +name = "proc-macro-crate" +version = "2.0.2" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "b00f26d3400549137f92511a46ac1cd8ce37cb5598a96d382381458b992a5d24" +dependencies = [ + "toml_datetime 0.6.3", + "toml_edit 0.20.2", +] + +[[package]] +name = "proc-macro-crate" +version = "3.5.0" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "e67ba7e9b2b56446f1d419b1d807906278ffa1a658a8a5d8a39dcb1f5a78614f" +dependencies = [ + "toml_edit 0.25.20+spec-1.1.0", +] + +[[package]] +name = "proc-macro-error" +version = "1.0.4" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "da25490ff9892aab3fcf7c36f08cfb902dd3e71ca0f9f9517bea02a73a5ce38c" +dependencies = [ + "proc-macro-error-attr", + "proc-macro2", + "quote", + "syn 1.0.109", + "version_check", +] + +[[package]] +name = "proc-macro-error-attr" +version = "1.0.4" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "a1be40180e52ecc98ad80b184934baf3d0d29f979574e439af5a55274b35f869" +dependencies = [ + "proc-macro2", + "quote", + "version_check", +] + +[[package]] +name = "proc-macro-hack" +version = "0.5.20+deprecated" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "dc375e1527247fe1a97d8b7156678dfe7c1af2fc075c9a4db3690ecd2a148068" + +[[package]] +name = "proc-macro2" +version = "1.0.107" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "985e7ec9bb745e6ce6535b544d84d6cd6f7ad8bd711c398938ae983b91a766d9" +dependencies = [ + "unicode-ident", +] + +[[package]] +name = "proc-macro2-diagnostics" +version = "0.10.1" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "af066a9c399a26e020ada66a034357a868728e72cd426f3adcd35f80d88d88c8" +dependencies = [ + "proc-macro2", + "quote", + "syn 2.0.119", + "version_check", +] + +[[package]] +name = "profiling" +version = "1.0.18" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "3d595e54a326bc53c1c197b32d295e14b169e3cfeaa8dc82b529f947fba6bcf5" +dependencies = [ + "profiling-procmacros", +] + +[[package]] +name = "profiling-procmacros" +version = "1.0.18" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "4488a4a36b9a4ba6b9334a32a39971f77c1436ec82c38707bce707699cc3bbcb" +dependencies = [ + "quote", + "syn 2.0.119", +] + +[[package]] +name = "psl-types" +version = "2.0.11" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "33cb294fe86a74cbcf50d4445b37da762029549ebeea341421c7c70370f86cac" + +[[package]] +name = "publicsuffix" +version = "2.3.0" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "6f42ea446cab60335f76979ec15e12619a2165b5ae2c12166bef27d283a9fadf" +dependencies = [ + "idna", + "psl-types", +] + +[[package]] +name = "pxfm" +version = "0.1.30" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "d55d956fa96f5ec02be2e13af0e20391a5aa83d6a074e3ad368959d0fab299ea" + +[[package]] +name = "qoi" +version = "0.4.1" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "7f6d64c71eb498fe9eae14ce4ec935c555749aef511cca85b5568910d6e48001" +dependencies = [ + "bytemuck", +] + +[[package]] +name = "quick-error" +version = "2.0.1" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "a993555f31e5a609f617c12db6250dedcac1b0a85076912c436e6fc9b2c8e6a3" + +[[package]] +name = "quinn" +version = "0.11.12" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "4051e23e9185c255a7e33ef59cdbca87a22d359052eecd22fc6b901fb37d9d11" +dependencies = [ + "bytes", + "cfg_aliases", + "pin-project-lite", + "quinn-proto", + "quinn-udp", + "rustc-hash 2.1.3", + "rustls", + "socket2", + "thiserror 2.0.21", + "tokio", + "tracing", + "web-time", +] + +[[package]] +name = "quinn-proto" +version = "0.11.19" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "0e750cca55fe4f0439a15d0bb529da9651e79993e8e72c61a899a36d462befbe" +dependencies = [ + "bytes", + "getrandom 0.4.3", + "lru-slab", + "rand 0.10.4", + "rand_pcg 0.10.3", + "ring", + "rustc-hash 2.1.3", + "rustls", + "rustls-pki-types", + "slab", + "thiserror 2.0.21", + "tinyvec", + "tracing", + "web-time", +] + +[[package]] +name = "quinn-udp" +version = "0.5.16" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "af66907df18639dcf4db56ca65490cabc4b27a97dbadd96f2926cca73298f016" +dependencies = [ + "cfg_aliases", + "libc", + "once_cell", + "socket2", + "tracing", + "windows-sys 0.61.2", +] + +[[package]] +name = "quote" +version = "1.0.47" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "1fbf4db142a473a8d80c26bbf18454ed458bf8d26c8219c331daecfdbd079001" +dependencies = [ + "proc-macro2", +] + +[[package]] +name = "r-efi" +version = "5.3.0" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "69cdb34c158ceb288df11e18b4bd39de994f6657d83847bdffdbd7f346754b0f" + +[[package]] +name = "r-efi" +version = "6.0.0" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "f8dcc9c7d52a811697d2151c701e0d08956f92b0e24136cf4cf27b57a6a0d9bf" + +[[package]] +name = "rand" +version = "0.7.3" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "6a6b1679d49b24bbfe0c803429aa1874472f50d9b363131f0e89fc356b544d03" +dependencies = [ + "getrandom 0.1.16", + "libc", + "rand_chacha 0.2.2", + "rand_core 0.5.1", + "rand_hc", + "rand_pcg 0.2.1", +] + +[[package]] +name = "rand" +version = "0.8.8" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "e058c7de0b26af77780c769414d6257830bb240f3c38477dbc2c16e5f54d6d4c" +dependencies = [ + "libc", + "rand_chacha 0.3.1", + "rand_core 0.6.4", +] + +[[package]] +name = "rand" +version = "0.9.5" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "b9ef1d0d795eb7d84685bca4f72f3649f064e6641543d3a8c415898726a57b41" +dependencies = [ + "rand_chacha 0.9.0", + "rand_core 0.9.5", +] + +[[package]] +name = "rand" +version = "0.10.4" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "8f6fa277c67e6ea590466f04c3fe82cb509f0864fe470643e5570de9514a9b11" +dependencies = [ + "chacha20", + "getrandom 0.4.3", + "rand_core 0.10.1", +] + +[[package]] +name = "rand_chacha" +version = "0.2.2" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "f4c8ed856279c9737206bf725bf36935d8666ead7aa69b52be55af369d193402" +dependencies = [ + "ppv-lite86", + "rand_core 0.5.1", +] + +[[package]] +name = "rand_chacha" +version = "0.3.1" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "e6c10a63a0fa32252be49d21e7709d4d4baf8d231c2dbce1eaa8141b9b127d88" +dependencies = [ + "ppv-lite86", + "rand_core 0.6.4", +] + +[[package]] +name = "rand_chacha" +version = "0.9.0" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "d3022b5f1df60f26e1ffddd6c66e8aa15de382ae63b3a0c1bfc0e4d3e3f325cb" +dependencies = [ + "ppv-lite86", + "rand_core 0.9.5", +] + +[[package]] +name = "rand_core" +version = "0.5.1" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "90bde5296fc891b0cef12a6d03ddccc162ce7b2aff54160af9338f8d40df6d19" +dependencies = [ + "getrandom 0.1.16", +] + +[[package]] +name = "rand_core" +version = "0.6.4" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "ec0be4795e2f6a28069bec0b5ff3e2ac9bafc99e6a9a7dc3547996c5c816922c" +dependencies = [ + "getrandom 0.2.17", +] + +[[package]] +name = "rand_core" +version = "0.9.5" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "76afc826de14238e6e8c374ddcc1fa19e374fd8dd986b0d2af0d02377261d83c" +dependencies = [ + "getrandom 0.3.4", +] + +[[package]] +name = "rand_core" +version = "0.10.1" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "63b8176103e19a2643978565ca18b50549f6101881c443590420e4dc998a3c69" + +[[package]] +name = "rand_hc" +version = "0.2.0" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "ca3129af7b92a17112d59ad498c6f81eaf463253766b90396d39ea7a39d6613c" +dependencies = [ + "rand_core 0.5.1", +] + +[[package]] +name = "rand_pcg" +version = "0.2.1" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "16abd0c1b639e9eb4d7c50c0b8100b0d0f849be2349829c740fe8e6eb4816429" +dependencies = [ + "rand_core 0.5.1", +] + +[[package]] +name = "rand_pcg" +version = "0.10.3" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "eb95882a1e14462c69aea9984bb261293ccfe6022ef8de0eda18bd5afb0052df" +dependencies = [ + "rand_core 0.10.1", +] + +[[package]] +name = "rav1e" +version = "0.8.1" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "43b6dd56e85d9483277cde964fd1bdb0428de4fec5ebba7540995639a21cb32b" +dependencies = [ + "aligned-vec", + "arbitrary", + "arg_enum_proc_macro", + "arrayvec", + "av-scenechange", + "av1-grain", + "bitstream-io", + "built", + "cfg-if", + "interpolate_name", + "itertools", + "libc", + "libfuzzer-sys", + "log", + "maybe-rayon", + "new_debug_unreachable", + "noop_proc_macro", + "num-derive", + "num-traits", + "paste", + "profiling", + "rand 0.9.5", + "rand_chacha 0.9.0", + "simd_helpers", + "thiserror 2.0.21", + "v_frame", + "wasm-bindgen", +] + +[[package]] +name = "ravif" +version = "0.13.0" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "e52310197d971b0f5be7fe6b57530dcd27beb35c1b013f29d66c1ad73fbbcc45" +dependencies = [ + "avif-serialize", + "imgref", + "loop9", + "quick-error", + "rav1e", + "rayon", + "rgb", +] + +[[package]] +name = "raw-window-handle" +version = "0.5.2" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "f2ff9a1f06a88b01621b7ae906ef0211290d1c8a168a15542486a8f61c0833b9" + +[[package]] +name = "raw-window-handle" +version = "0.6.2" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "20675572f6f24e9e76ef639bc5552774ed45f1c30e2951e1e99c59888861c539" + +[[package]] +name = "rayon" +version = "1.12.0" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "fb39b166781f92d482534ef4b4b1b2568f42613b53e5b6c160e24cfbfa30926d" +dependencies = [ + "either", + "rayon-core", +] + +[[package]] +name = "rayon-core" +version = "1.13.0" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "22e18b0f0062d30d4230b2e85ff77fdfe4326feb054b9783a3460d8435c8ab91" +dependencies = [ + "crossbeam-deque", + "crossbeam-utils", +] + +[[package]] +name = "redox_syscall" +version = "0.5.18" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "ed2bf2547551a7053d6fdfafda3f938979645c44812fbfcda098faae3f1a362d" +dependencies = [ + "bitflags 2.13.2", +] + +[[package]] +name = "redox_users" +version = "0.5.3" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "60dc65c0ff1a7ae1294b0c67b9f14baf70b644404010370171787bfac1038fc0" +dependencies = [ + "libredox", + "thiserror 2.0.21", +] + +[[package]] +name = "regex-automata" +version = "0.4.19" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "41d60ef07df457506a0a1a2073112eb4aae5733dbd2813c3da77d1b0fd441158" +dependencies = [ + "aho-corasick", + "memchr", + "regex-syntax", +] + +[[package]] +name = "regex-syntax" +version = "0.8.12" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "d902046e6a28a1e4c3cab97258a0ce11e994903f01c2d97a9447a0b3df85f4f6" + +[[package]] +name = "reqwest" +version = "0.12.28" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "eddd3ca559203180a307f12d114c268abf583f59b03cb906fd0b3ff8646c1147" +dependencies = [ + "base64 0.22.1", + "bytes", + "cookie", + "cookie_store", + "futures-core", + "futures-util", + "http", + "http-body", + "http-body-util", + "hyper", + "hyper-rustls", + "hyper-util", + "js-sys", + "log", + "mime_guess", + "percent-encoding", + "pin-project-lite", + "quinn", + "rustls", + "rustls-pki-types", + "serde", + "serde_json", + "serde_urlencoded", + "sync_wrapper", + "tokio", + "tokio-rustls", + "tokio-util", + "tower", + "tower-http", + "tower-service", + "url", + "wasm-bindgen", + "wasm-bindgen-futures", + "wasm-streams", + "web-sys", + "webpki-roots", +] + +[[package]] +name = "rfd" +version = "0.17.2" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "20dafead71c16a34e1ff357ddefc8afc11e7d51d6d2b9fbd07eaa48e3e540220" +dependencies = [ + "block2", + "dispatch2", + "js-sys", + "libc", + "log", + "objc2", + "objc2-app-kit", + "objc2-core-foundation", + "objc2-foundation", + "percent-encoding", + "pollster", + "raw-window-handle 0.6.2", + "wasm-bindgen", + "wasm-bindgen-futures", + "web-sys", + "windows-sys 0.61.2", +] + +[[package]] +name = "rgb" +version = "0.8.53" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "47b34b781b31e5d73e9fbc8689c70551fd1ade9a19e3e28cfec8580a79290cc4" + +[[package]] +name = "ring" +version = "0.17.14" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "a4689e6c2294d81e88dc6261c768b63bc4fcdb852be6d1352498b114f61383b7" +dependencies = [ + "cc", + "cfg-if", + "getrandom 0.2.17", + "libc", + "untrusted", + "windows-sys 0.52.0", +] + +[[package]] +name = "rustc-hash" +version = "1.1.0" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "08d43f7aa6b08d49f382cde6a7982047c3426db949b1424bc4b7ec9ae12c6ce2" + +[[package]] +name = "rustc-hash" +version = "2.1.3" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "6b1e7f9a428571be2dc5bc0505c13fb6bf936822b894ec87abf8a08a4e51742d" + +[[package]] +name = "rustc_version" +version = "0.4.1" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "cfcb3a22ef46e85b45de6ee7e79d063319ebb6594faafcf1c225ea92ab6e9b92" +dependencies = [ + "semver", +] + +[[package]] +name = "rustix" +version = "1.1.6" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "e5e76742e5294153d4dde1207dbec5bdd81eef6fabdc0d2118babadabfd858aa" +dependencies = [ + "bitflags 2.13.2", + "errno", + "libc", + "linux-raw-sys", + "windows-sys 0.61.2", +] + +[[package]] +name = "rustls" +version = "0.23.46" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "48e13bd8c0e9365c43cfa5c9e8f9ad49d3c8444926c9aac819e0e4dc503c8fdf" +dependencies = [ + "once_cell", + "ring", + "rustls-pki-types", + "rustls-webpki", + "subtle", + "zeroize", +] + +[[package]] +name = "rustls-pki-types" +version = "1.16.0" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "102f35f7de7b06d8c61f1cff6592f5253e0dea431c74867aad5dfd70f44663fb" +dependencies = [ + "web-time", + "zeroize", +] + +[[package]] +name = "rustls-webpki" +version = "0.103.17" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "e3a0760a887c14823fca5a1c970b01d47c328c696c0c64829d1df50e8f853fd5" +dependencies = [ + "ring", + "rustls-pki-types", + "untrusted", +] + +[[package]] +name = "rustversion" +version = "1.0.23" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "cf54715a573b99ac80df0bc206da022bcd442c974952c7b9720069370852e21f" + +[[package]] +name = "ryu" +version = "1.0.23" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "9774ba4a74de5f7b1c1451ed6cd5285a32eddb5cccb8cc655a4e50009e06477f" + +[[package]] +name = "same-file" +version = "1.0.6" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "93fc1dc3aaa9bfed95e02e6eadabb4baf7e3078b0bd1b4d7b6b0b68378900502" +dependencies = [ + "winapi-util", +] + +[[package]] +name = "schannel" +version = "0.1.30" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "9cb23c424d8ee841bb4d813677ca237e2a610067d594fec130f87d6093495ab5" +dependencies = [ + "windows-sys 0.61.2", +] + +[[package]] +name = "scopeguard" +version = "1.2.0" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "94143f37725109f92c262ed2cf5e59bce7498c01bcc1502d7b9afe439a4e9f49" + +[[package]] +name = "security-framework" +version = "3.7.0" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "b7f4bc775c73d9a02cde8bf7b2ec4c9d12743edf609006c7facc23998404cd1d" +dependencies = [ + "bitflags 2.13.2", + "core-foundation", + "core-foundation-sys", + "libc", + "security-framework-sys", +] + +[[package]] +name = "security-framework-sys" +version = "2.17.0" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "6ce2691df843ecc5d231c0b14ece2acc3efb62c0a398c7e1d875f3983ce020e3" +dependencies = [ + "core-foundation-sys", + "libc", +] + +[[package]] +name = "selectors" +version = "0.24.0" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "0c37578180969d00692904465fb7f6b3d50b9a2b952b87c23d0e2e5cb5013416" +dependencies = [ + "bitflags 1.3.2", + "cssparser", + "derive_more 0.99.20", + "fxhash", + "log", + "phf 0.8.0", + "phf_codegen 0.8.0", + "precomputed-hash", + "servo_arc", + "smallvec", +] + +[[package]] +name = "semver" +version = "1.0.28" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "8a7852d02fc848982e0c167ef163aaff9cd91dc640ba85e263cb1ce46fae51cd" + +[[package]] +name = "send_wrapper" +version = "0.6.0" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "cd0b0ec5f1c1ca621c432a25813d8d60c88abe6d3e08a3eb9cf37d97a0fe3d73" +dependencies = [ + "futures-core", +] + +[[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-wasm-bindgen" +version = "0.6.5" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "8302e169f0eddcc139c70f139d19d6467353af16f9fce27e8c30158036a1e16b" +dependencies = [ + "js-sys", + "serde", + "wasm-bindgen", +] + +[[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 = [ + "itoa", + "memchr", + "serde", + "serde_core", + "zmij", +] + +[[package]] +name = "serde_path_to_error" +version = "0.1.20" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "10a9ff822e371bb5403e391ecd83e182e0e77ba7f6fe0160b795797109d1b457" +dependencies = [ + "itoa", + "serde", + "serde_core", +] + +[[package]] +name = "serde_qs" +version = "0.15.0" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "f3faaf9e727533a19351a43cc5a8de957372163c7d35cc48c90b75cdda13c352" +dependencies = [ + "percent-encoding", + "serde", + "thiserror 2.0.21", +] + +[[package]] +name = "serde_repr" +version = "0.1.21" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "8d3b1629de253c70a0508c3899572da79ca359fdab27c7920ff00406df418906" +dependencies = [ + "proc-macro2", + "quote", + "syn 3.0.10", +] + +[[package]] +name = "serde_spanned" +version = "0.6.9" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "bf41e0cfaf7226dca15e8197172c295a782857fcb97fad1808a166870dee75a3" +dependencies = [ + "serde", +] + +[[package]] +name = "serde_urlencoded" +version = "0.7.1" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "d3491c14715ca2294c4d6a88f15e84739788c1d030eed8c110436aafdaa2f3fd" +dependencies = [ + "form_urlencoded", + "itoa", + "ryu", + "serde", +] + +[[package]] +name = "servo_arc" +version = "0.2.0" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "d52aa42f8fdf0fed91e5ce7f23d8138441002fa31dca008acf47e6fd4721f741" +dependencies = [ + "nodrop", + "stable_deref_trait", +] + +[[package]] +name = "sha1" +version = "0.10.7" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "a978451301f4db1d02937a4ab3ccce137717b81826e79b7d49ffe3244a13c3b8" +dependencies = [ + "cfg-if", + "cpufeatures 0.2.17", + "digest", +] + +[[package]] +name = "sha2" +version = "0.10.9" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "a7507d819769d01a365ab707794a4084392c824f54a7a6a7862f8c3d0892b283" +dependencies = [ + "cfg-if", + "cpufeatures 0.2.17", + "digest", +] + +[[package]] +name = "sharded-slab" +version = "0.1.7" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "f40ca3c46823713e0d4209592e8d6e826aa57e928f09752619fc696c499637f6" +dependencies = [ + "lazy_static", +] + +[[package]] +name = "shlex" +version = "2.0.1" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "f8fadd59c855ef2080decdef8ff161eb6661b86933c9d82e5ba29dc602a55aba" + +[[package]] +name = "signal-hook" +version = "0.3.18" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "d881a16cf4426aa584979d30bd82cb33429027e42122b169753d6ef1085ed6e2" +dependencies = [ + "libc", + "signal-hook-registry", +] + +[[package]] +name = "signal-hook-registry" +version = "1.4.8" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "c4db69cba1110affc0e9f7bcd48bbf87b3f4fc7c61fc9155afd4c469eb3d6c1b" +dependencies = [ + "errno", + "libc", +] + +[[package]] +name = "simd-adler32" +version = "0.3.10" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "3a219298ac11a56ea9a6d2120044824d6f01aeb034955e7af7bc16858527deea" + +[[package]] +name = "simd_cesu8" +version = "1.2.0" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "11031e251abf8611c80f460e19dbdeb54a66db918e49c65a7065b46ac7aec520" +dependencies = [ + "rustc_version", + "simdutf8", +] + +[[package]] +name = "simd_helpers" +version = "0.1.1" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "f48ea32978b7ad365bd1ecce83827746d5d50dc006a8c85112b7acc3c716e3e7" + +[[package]] +name = "simdutf8" +version = "0.1.5" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "e3a9fe34e3e7a50316060351f37187a3f546bce95496156754b601a5fa71b76e" + +[[package]] +name = "siphasher" +version = "0.3.11" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "38b58827f4464d87d377d175e90bf58eb00fd8716ff0a62f80356b5e61555d0d" + +[[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 = "sledgehammer_bindgen" +version = "0.6.0" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "49e83e178d176459c92bc129cfd0958afac3ced925471b889b3a75546cfc4133" +dependencies = [ + "sledgehammer_bindgen_macro", + "wasm-bindgen", +] + +[[package]] +name = "sledgehammer_bindgen_macro" +version = "0.6.5" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "bb251b407f50028476a600541542b605bb864d35d9ee1de4f6cab45d88475e6d" +dependencies = [ + "quote", + "syn 2.0.119", +] + +[[package]] +name = "sledgehammer_utils" +version = "0.3.1" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "debdd4b83524961983cea3c55383b3910fd2f24fd13a188f5b091d2d504a61ae" +dependencies = [ + "rustc-hash 1.1.0", +] + +[[package]] +name = "slotmap" +version = "1.1.1" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "bdd58c3c93c3d278ca835519292445cb4b0d4dc59ccfdf7ceadaab3f8aeb4038" +dependencies = [ + "serde", + "version_check", +] + +[[package]] +name = "smallvec" +version = "1.16.6" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "3244542535d5de959d90ec55d1b5ff0fd2bb7b1310223907d5f11932847f7b59" + +[[package]] +name = "socket2" +version = "0.6.5" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "c3d1e2c7f27f8d4cb10542a02c49005dbd6e93095799d6f3be745fae9f8fedd4" +dependencies = [ + "libc", + "windows-sys 0.61.2", +] + +[[package]] +name = "soup3" +version = "0.5.0" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "471f924a40f31251afc77450e781cb26d55c0b650842efafc9c6cbd2f7cc4f9f" +dependencies = [ + "futures-channel", + "gio", + "glib", + "libc", + "soup3-sys", +] + +[[package]] +name = "soup3-sys" +version = "0.5.0" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "7ebe8950a680a12f24f15ebe1bf70db7af98ad242d9db43596ad3108aab86c27" +dependencies = [ + "gio-sys", + "glib-sys", + "gobject-sys", + "libc", + "system-deps", +] + +[[package]] +name = "spin" +version = "0.9.9" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "3763264f6b73151db08c50ff20d7d8a0b8796e021cdea7ceedad07b80155fa0e" + +[[package]] +name = "stable_deref_trait" +version = "1.2.1" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "6ce2be8dc25455e1f91df71bfa12ad37d7af1092ae736f3a6cd0e37bc7810596" + +[[package]] +name = "string_cache" +version = "0.8.9" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "bf776ba3fa74f83bf4b63c3dcbbf82173db2632ed8452cb2d891d33f459de70f" +dependencies = [ + "new_debug_unreachable", + "parking_lot", + "phf_shared 0.11.3", + "precomputed-hash", + "serde", +] + +[[package]] +name = "string_cache_codegen" +version = "0.5.4" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "c711928715f1fe0fe509c53b43e993a9a557babc2d0a3567d0a3006f1ac931a0" +dependencies = [ + "phf_generator 0.11.3", + "phf_shared 0.11.3", + "proc-macro2", + "quote", +] + +[[package]] +name = "subsecond" +version = "0.7.10" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "d350d5788fa94d560d92269266a50efc77b036bfca6675e420b64df7b3211f37" +dependencies = [ + "js-sys", + "libc", + "libloading 0.8.9", + "memfd", + "memmap2", + "serde", + "subsecond-types", + "thiserror 2.0.21", + "wasm-bindgen", + "wasm-bindgen-futures", + "web-sys", +] + +[[package]] +name = "subsecond-types" +version = "0.7.10" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "dcf32d66269b5fbb8558334e8d22b657b2f7af0dd2ef56c231541099a862e464" +dependencies = [ + "serde", +] + +[[package]] +name = "subtle" +version = "2.6.1" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "13c2bddecc57b384dee18652358fb23172facb8a2c51ccc10d74c157bdea3292" + +[[package]] +name = "syn" +version = "1.0.109" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "72b64191b275b66ffe2469e8af2c1cfe3bafa67b529ead792a6d0160888b4237" +dependencies = [ + "proc-macro2", + "quote", + "unicode-ident", +] + +[[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 = "sync_wrapper" +version = "1.0.2" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "0bf256ce5efdfa370213c1dabab5935a12e49f2c58d15e9eac2870d3b4f27263" +dependencies = [ + "futures-core", +] + +[[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 = "system-deps" +version = "6.2.2" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "a3e535eb8dded36d55ec13eddacd30dec501792ff23a0b1682c38601b8cf2349" +dependencies = [ + "cfg-expr", + "heck 0.5.0", + "pkg-config", + "toml", + "version-compare", +] + +[[package]] +name = "tao" +version = "0.34.8" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "9103edf55f2da3c82aea4c7fab7c4241032bfeea0e71fa557d98e00e7ce7cc20" +dependencies = [ + "bitflags 2.13.2", + "block2", + "core-foundation", + "core-graphics 0.25.0", + "crossbeam-channel", + "dispatch2", + "dlopen2", + "dpi", + "gdkwayland-sys", + "gdkx11-sys", + "gtk", + "jni 0.21.1", + "libc", + "log", + "ndk", + "ndk-context", + "ndk-sys", + "objc2", + "objc2-app-kit", + "objc2-foundation", + "once_cell", + "parking_lot", + "raw-window-handle 0.5.2", + "raw-window-handle 0.6.2", + "tao-macros", + "unicode-segmentation", + "url", + "windows", + "windows-core", + "windows-version", + "x11-dl", +] + +[[package]] +name = "tao-macros" +version = "0.1.4" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "5f7eeb6d99155545da6150a1795945f16ac9c178deb2a5f2e74d776107bd5849" +dependencies = [ + "proc-macro2", + "quote", + "syn 2.0.119", +] + +[[package]] +name = "target-features" +version = "0.1.6" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "c1bbb9f3c5c463a01705937a24fdabc5047929ac764b2d5b9cf681c1f5041ed5" + +[[package]] +name = "target-lexicon" +version = "0.12.16" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "61c41af27dd6d1e27b1b16b489db798443478cef1f06a660c96db617ba5de3b1" + +[[package]] +name = "tempfile" +version = "3.27.0" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "32497e9a4c7b38532efcdebeef879707aa9f794296a4f0244f6f69e9bc8574bd" +dependencies = [ + "fastrand", + "getrandom 0.4.3", + "once_cell", + "rustix", + "windows-sys 0.61.2", +] + +[[package]] +name = "tendril" +version = "0.4.3" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "d24a120c5fc464a3458240ee02c299ebcb9d67b5249c8848b09d639dca8d7bb0" +dependencies = [ + "futf", + "mac", + "utf-8", +] + +[[package]] +name = "thiserror" +version = "1.0.69" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "b6aaf5339b578ea85b50e080feb250a3e8ae8cfcdff9a461c9ec2904bc923f52" +dependencies = [ + "thiserror-impl 1.0.69", +] + +[[package]] +name = "thiserror" +version = "2.0.21" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "09e52cb86a36cede5cb101bf8908837b3e4c6e5e59fe7fd85c23fb56200d189e" +dependencies = [ + "thiserror-impl 2.0.21", +] + +[[package]] +name = "thiserror-impl" +version = "1.0.69" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "4fee6c4efc90059e10f81e6d42c60a18f76588c3d74cb83a0b242a2b6c7504c1" +dependencies = [ + "proc-macro2", + "quote", + "syn 2.0.119", +] + +[[package]] +name = "thiserror-impl" +version = "2.0.21" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "fe5197923287db20a58125f0bc85c062f7f2c892de97b18c356f9efb14b28524" +dependencies = [ + "proc-macro2", + "quote", + "syn 3.0.10", +] + +[[package]] +name = "thread_local" +version = "1.1.10" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "1ad99c4c6d32803332c548b1af0540b357b3f5fc0be8f6c6bfe8b2e6ae784070" +dependencies = [ + "cfg-if", +] + +[[package]] +name = "tiff" +version = "0.11.3" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "b63feaf3343d35b6ca4d50483f94843803b0f51634937cc2ec519fc32232bc52" +dependencies = [ + "fax", + "flate2", + "half", + "quick-error", + "weezl", + "zune-jpeg", +] + +[[package]] +name = "time" +version = "0.3.55" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "cdb87b95ec50ddfa440816d227a17b2ccbdda963a316a727fda0fc4334f7d134" +dependencies = [ + "deranged", + "num-conv", + "powerfmt", + "serde_core", + "time-core", + "time-macros", +] + +[[package]] +name = "time-core" +version = "0.1.9" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "9e1c906769ad99c88eaa54e728060edef082f8e358ff32030cb7c7d315e81109" + +[[package]] +name = "time-macros" +version = "0.2.32" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "7e689342a48d2ea927c87ea50cabf8594854bf940e9310208848d680d668ed85" +dependencies = [ + "num-conv", + "time-core", +] + +[[package]] +name = "tinystr" +version = "0.8.5" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "abc840c238154d58f9e86b2792261edfde565a17696e1cda1a449de27979801a" +dependencies = [ + "displaydoc", + "zerovec", +] + +[[package]] +name = "tinyvec" +version = "1.13.3" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "fd3ca314f692efd6c868f8408f53fe444634a845f96c028b97d35f6a1f79f0ee" + +[[package]] +name = "tokio" +version = "1.54.1" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "b52fd3255258d26fac7264ab5a76b53c13367136dc011d3d6ad4f8ed070396a3" +dependencies = [ + "bytes", + "libc", + "mio", + "pin-project-lite", + "socket2", + "tokio-macros", + "windows-sys 0.61.2", +] + +[[package]] +name = "tokio-macros" +version = "2.7.2" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "78773a2a397f451582ce068015985c33193cf6dea8b74d2a639fe457b2f07b0e" +dependencies = [ + "proc-macro2", + "quote", + "syn 3.0.10", +] + +[[package]] +name = "tokio-rustls" +version = "0.26.6" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "c9cc2678c2cdd569ef8215e2afd7954ada2ae20b4fdd2c5fe6139a3b02d105db" +dependencies = [ + "rustls", + "tokio", +] + +[[package]] +name = "tokio-util" +version = "0.7.20" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "e464cf451ba96ebfc6f9b6542f17ee8b8956e33f1e40d9690624e59d7a7f8a4b" +dependencies = [ + "bytes", + "futures-core", + "futures-io", + "futures-sink", + "futures-util", + "libc", + "pin-project-lite", + "tokio", +] + +[[package]] +name = "toml" +version = "0.8.2" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "185d8ab0dfbb35cf1399a6344d8484209c088f75f8f68230da55d48d95d43e3d" +dependencies = [ + "serde", + "serde_spanned", + "toml_datetime 0.6.3", + "toml_edit 0.20.2", +] + +[[package]] +name = "toml_datetime" +version = "0.6.3" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "7cda73e2f1397b1262d6dfdcef8aafae14d1de7748d66822d3bfeeb6d03e5e4b" +dependencies = [ + "serde", +] + +[[package]] +name = "toml_datetime" +version = "1.1.3+spec-1.1.0" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "173f25c883cd2176a2d8212155638c0a60d484a9d84546d270866f40f56b6e49" +dependencies = [ + "serde_core", +] + +[[package]] +name = "toml_edit" +version = "0.19.15" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "1b5bb770da30e5cbfde35a2d7b9b8a2c4b8ef89548a7a6aeab5c9a576e3e7421" +dependencies = [ + "indexmap", + "toml_datetime 0.6.3", + "winnow 0.5.40", +] + +[[package]] +name = "toml_edit" +version = "0.20.2" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "396e4d48bbb2b7554c944bde63101b5ae446cff6ec4a24227428f15eb72ef338" +dependencies = [ + "indexmap", + "serde", + "serde_spanned", + "toml_datetime 0.6.3", + "winnow 0.5.40", +] + +[[package]] +name = "toml_edit" +version = "0.25.20+spec-1.1.0" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "e76360e201d6dbd6583e17795ba71a88f47365a9139c8450a7979c32303b8e73" +dependencies = [ + "indexmap", + "toml_datetime 1.1.3+spec-1.1.0", + "toml_parser", + "winnow 1.0.5", +] + +[[package]] +name = "toml_parser" +version = "1.1.6+spec-1.1.0" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "e6769c452d71ba30696c6b37770c439a9cc9110f47f7d5cdbeda79840ef5ea31" +dependencies = [ + "winnow 1.0.5", +] + +[[package]] +name = "tower" +version = "0.5.3" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "ebe5ef63511595f1344e2d5cfa636d973292adc0eec1f0ad45fae9f0851ab1d4" +dependencies = [ + "futures-core", + "futures-util", + "pin-project-lite", + "sync_wrapper", + "tokio", + "tower-layer", + "tower-service", +] + +[[package]] +name = "tower-http" +version = "0.6.11" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "4cfcf7e2740e6fc6d4d688b4ef00650406bb94adf4731e43c096c3a19fe40840" +dependencies = [ + "bitflags 2.13.2", + "bytes", + "futures-util", + "http", + "http-body", + "pin-project-lite", + "tower", + "tower-layer", + "tower-service", + "url", +] + +[[package]] +name = "tower-layer" +version = "0.3.3" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "121c2a6cda46980bb0fcd1647ffaf6cd3fc79a013de288782836f6df9c48780e" + +[[package]] +name = "tower-service" +version = "0.3.3" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "8df9b6e13f2d32c91b9bd719c00d1958837bc7dec474d94952798cc8e69eeec3" + +[[package]] +name = "tracing" +version = "0.1.44" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "63e71662fa4b2a2c3a26f570f037eb95bb1f85397f3cd8076caed2f026a6d100" +dependencies = [ + "pin-project-lite", + "tracing-attributes", + "tracing-core", +] + +[[package]] +name = "tracing-attributes" +version = "0.1.31" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "7490cfa5ec963746568740651ac6781f701c9c5ea257c58e057f3ba8cf69e8da" +dependencies = [ + "proc-macro2", + "quote", + "syn 2.0.119", +] + +[[package]] +name = "tracing-core" +version = "0.1.36" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "db97caf9d906fbde555dd62fa95ddba9eecfd14cb388e4f491a66d74cd5fb79a" +dependencies = [ + "once_cell", +] + +[[package]] +name = "tracing-subscriber" +version = "0.3.23" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "cb7f578e5945fb242538965c2d0b04418d38ec25c79d160cd279bf0731c8d319" +dependencies = [ + "matchers", + "once_cell", + "regex-automata", + "sharded-slab", + "thread_local", + "tracing", + "tracing-core", +] + +[[package]] +name = "tracing-wasm" +version = "0.2.1" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "4575c663a174420fa2d78f4108ff68f65bf2fbb7dd89f33749b6e826b3626e07" +dependencies = [ + "tracing", + "tracing-subscriber", + "wasm-bindgen", +] + +[[package]] +name = "tray-icon" +version = "0.21.3" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "a5e85aa143ceb072062fc4d6356c1b520a51d636e7bc8e77ec94be3608e5e80c" +dependencies = [ + "crossbeam-channel", + "dirs", + "libappindicator", + "muda", + "objc2", + "objc2-app-kit", + "objc2-core-foundation", + "objc2-core-graphics", + "objc2-foundation", + "once_cell", + "png 0.17.16", + "thiserror 2.0.21", + "windows-sys 0.60.2", +] + +[[package]] +name = "try-lock" +version = "0.2.5" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "e421abadd41a4225275504ea4d6566923418b7f05506fbc9c0fe86ba7396114b" + +[[package]] +name = "tungstenite" +version = "0.27.0" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "eadc29d668c91fcc564941132e17b28a7ceb2f3ebf0b9dae3e03fd7a6748eb0d" +dependencies = [ + "bytes", + "data-encoding", + "http", + "httparse", + "log", + "rand 0.9.5", + "sha1", + "thiserror 2.0.21", + "utf-8", +] + +[[package]] +name = "tungstenite" +version = "0.28.0" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "8628dcc84e5a09eb3d8423d6cb682965dea9133204e8fb3efee74c2a0c259442" +dependencies = [ + "bytes", + "data-encoding", + "http", + "httparse", + "log", + "native-tls", + "rand 0.9.5", + "rustls", + "sha1", + "thiserror 2.0.21", + "utf-8", +] + +[[package]] +name = "typenum" +version = "1.20.1" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "b6f5e870be6c3b371b77fe0ee0bafb859fa4964b4404c27de1d380043c4dda20" + +[[package]] +name = "unicase" +version = "2.10.0" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "357cc3acc6a036009fd6c973ed009037c732d60d0b4f6c673e9041497482a28f" + +[[package]] +name = "unicode-ident" +version = "1.0.27" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "a2c754d6c33795a1c324727428e5a7dedb5b06195f9890bdbcba760d3e246563" + +[[package]] +name = "unicode-segmentation" +version = "1.13.3" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "c6f5d3c3b1bf09027a88a6bc961fc00497d651009560b5463668dc81b0fa87a8" + +[[package]] +name = "unicode-xid" +version = "0.2.6" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "ebc1c04c71510c7f702b52b7c350734c9ff1295c464a03335b00bb84fc54f853" + +[[package]] +name = "untrusted" +version = "0.9.0" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "8ecb6da28b8a351d773b68d5825ac39017e680750f980f3a1a85cd8dd28a47c1" + +[[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 = "utf-8" +version = "0.7.6" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "09cc8ee72d2a9becf2f2febe0205bbed8fc6615b7cb429ad062dc7b7ddd036a9" + +[[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 = "uuid" +version = "1.29.3" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "3c14b15dffa2f4bd712103e857140aa04a4f2ff6e955c77d7eb8e53ee02a3b64" +dependencies = [ + "js-sys", + "wasm-bindgen", +] + +[[package]] +name = "v_frame" +version = "0.3.9" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "666b7727c8875d6ab5db9533418d7c764233ac9c0cff1d469aec8fa127597be2" +dependencies = [ + "aligned-vec", + "num-traits", + "wasm-bindgen", +] + +[[package]] +name = "vcpkg" +version = "0.2.15" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "accd4ea62f7bb7a82fe23066fb0957d48ef677f6eeb8215f372f52e48bb32426" + +[[package]] +name = "version-compare" +version = "0.2.1" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "03c2856837ef78f57382f06b2b8563a2f512f7185d732608fd9176cb3b8edf0e" + +[[package]] +name = "version_check" +version = "0.9.5" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "0b928f33d975fc6ad9f86c8f283853ad26bdd5b10b7f1542aa2fa15e2289105a" + +[[package]] +name = "walkdir" +version = "2.5.1" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "b42e295b7452c4604982280d8586001fcad9b8b201cac67bca9771e7a7475403" +dependencies = [ + "same-file", + "winapi-util", +] + +[[package]] +name = "want" +version = "0.3.2" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "ec4cdd0dd910afe868b7ef477227d8d538b46b3075031afee8a9f2acb0a2ed0b" +dependencies = [ + "try-lock", +] + +[[package]] +name = "warnings" +version = "0.2.1" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "64f68998838dab65727c9b30465595c6f7c953313559371ca8bf31759b3680ad" +dependencies = [ + "pin-project", + "tracing", + "warnings-macro", +] + +[[package]] +name = "warnings-macro" +version = "0.2.0" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "59195a1db0e95b920366d949ba5e0d3fc0e70b67c09be15ce5abb790106b0571" +dependencies = [ + "proc-macro2", + "quote", + "syn 2.0.119", +] + +[[package]] +name = "wasi" +version = "0.9.0+wasi-snapshot-preview1" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "cccddf32554fecc6acb585f82a32a72e28b48f8c4c1883ddfeeeaa96f7d8e519" + +[[package]] +name = "wasi" +version = "0.11.1+wasi-snapshot-preview1" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "ccf3ec651a847eb01de73ccad15eb7d99f80485de043efb2f370cd654f4ea44b" + +[[package]] +name = "wasip2" +version = "1.0.4+wasi-0.2.12" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "b67efb37e106e55ce722a510d6b5f9c17f083e5fc79afc2badeb12cc313d9487" +dependencies = [ + "wit-bindgen", +] + +[[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-futures" +version = "0.4.80" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "5e14e0327cb5368ad60ccb22d04a9827a693c95a926d8d125e9fa39e0baec501" +dependencies = [ + "js-sys", + "tokio", + "wasm-bindgen", +] + +[[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 = "wasm-streams" +version = "0.4.2" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "15053d8d85c7eccdbefef60f06769760a563c7f0a9d6902a13d35c7800b0ad65" +dependencies = [ + "futures-util", + "js-sys", + "wasm-bindgen", + "wasm-bindgen-futures", + "web-sys", +] + +[[package]] +name = "web-sys" +version = "0.3.107" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "d7d179596ff5ec0f6de4db64d54011bde6289cc49603d3a6e4ce3f329207ab88" +dependencies = [ + "js-sys", + "wasm-bindgen", +] + +[[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 = "webbrowser" +version = "1.2.7" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "73e91ccd4698f2647d6137e8eb17a3f1dcfd63810be9029fb2398f507279b95b" +dependencies = [ + "jni 0.22.4", + "log", + "ndk-context", + "objc2", + "objc2-app-kit", + "objc2-foundation", + "url", + "web-sys", +] + +[[package]] +name = "webkit2gtk" +version = "2.0.1" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "76b1bc1e54c581da1e9f179d0b38512ba358fb1af2d634a1affe42e37172361a" +dependencies = [ + "bitflags 1.3.2", + "cairo-rs", + "gdk", + "gdk-sys", + "gio", + "gio-sys", + "glib", + "glib-sys", + "gobject-sys", + "gtk", + "gtk-sys", + "javascriptcore-rs", + "libc", + "once_cell", + "soup3", + "webkit2gtk-sys", +] + +[[package]] +name = "webkit2gtk-sys" +version = "2.0.1" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "62daa38afc514d1f8f12b8693d30d5993ff77ced33ce30cd04deebc267a6d57c" +dependencies = [ + "bitflags 1.3.2", + "cairo-sys-rs", + "gdk-sys", + "gio-sys", + "glib-sys", + "gobject-sys", + "gtk-sys", + "javascriptcore-rs-sys", + "libc", + "pkg-config", + "soup3-sys", + "system-deps", +] + +[[package]] +name = "webpki-roots" +version = "1.0.12" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "7265c9301c16a8711c992c2d8da90ee77ef54b1ed51482d6dfeb00dc756b1297" +dependencies = [ + "rustls-pki-types", +] + +[[package]] +name = "webview2-com" +version = "0.38.2" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "7130243a7a5b33c54a444e54842e6a9e133de08b5ad7b5861cd8ed9a6a5bc96a" +dependencies = [ + "webview2-com-macros", + "webview2-com-sys", + "windows", + "windows-core", + "windows-implement", + "windows-interface", +] + +[[package]] +name = "webview2-com-macros" +version = "0.8.1" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "67a921c1b6914c367b2b823cd4cde6f96beec77d30a939c8199bb377cf9b9b54" +dependencies = [ + "proc-macro2", + "quote", + "syn 2.0.119", +] + +[[package]] +name = "webview2-com-sys" +version = "0.38.2" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "381336cfffd772377d291702245447a5251a2ffa5bad679c99e61bc48bacbf9c" +dependencies = [ + "thiserror 2.0.21", + "windows", + "windows-core", +] + +[[package]] +name = "weezl" +version = "0.1.12" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "a28ac98ddc8b9274cb41bb4d9d4d5c425b6020c50c46f25559911905610b4a88" + +[[package]] +name = "winapi" +version = "0.3.9" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "5c839a674fcd7a98952e593242ea400abe93992746761e38641405d28b00f419" +dependencies = [ + "winapi-i686-pc-windows-gnu", + "winapi-x86_64-pc-windows-gnu", +] + +[[package]] +name = "winapi-i686-pc-windows-gnu" +version = "0.4.0" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "ac3b87c63620426dd9b991e5ce0329eff545bccbbb34f3be09ff6fb6ab51b7b6" + +[[package]] +name = "winapi-util" +version = "0.1.11" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "c2a7b1c03c876122aa43f3020e6c3c3ee5c05081c9a00739faf7503aeba10d22" +dependencies = [ + "windows-sys 0.61.2", +] + +[[package]] +name = "winapi-x86_64-pc-windows-gnu" +version = "0.4.0" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "712e227841d057c1ee1cd2fb22fa7e5a5461ae8e48fa2ca79ec42cfc1931183f" + +[[package]] +name = "windows" +version = "0.61.3" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "9babd3a767a4c1aef6900409f85f5d53ce2544ccdfaa86dad48c91782c6d6893" +dependencies = [ + "windows-collections", + "windows-core", + "windows-future", + "windows-link 0.1.3", + "windows-numerics", +] + +[[package]] +name = "windows-collections" +version = "0.2.0" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "3beeceb5e5cfd9eb1d76b381630e82c4241ccd0d27f1a39ed41b2760b255c5e8" +dependencies = [ + "windows-core", +] + +[[package]] +name = "windows-core" +version = "0.61.2" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "c0fdd3ddb90610c7638aa2b3a3ab2904fb9e5cdbecc643ddb3647212781c4ae3" +dependencies = [ + "windows-implement", + "windows-interface", + "windows-link 0.1.3", + "windows-result", + "windows-strings", +] + +[[package]] +name = "windows-future" +version = "0.2.1" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "fc6a41e98427b19fe4b73c550f060b59fa592d7d686537eebf9385621bfbad8e" +dependencies = [ + "windows-core", + "windows-link 0.1.3", + "windows-threading", +] + +[[package]] +name = "windows-implement" +version = "0.60.2" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "053e2e040ab57b9dc951b72c264860db7eb3b0200ba345b4e4c3b14f67855ddf" +dependencies = [ + "proc-macro2", + "quote", + "syn 2.0.119", +] + +[[package]] +name = "windows-interface" +version = "0.59.3" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "3f316c4a2570ba26bbec722032c4099d8c8bc095efccdc15688708623367e358" +dependencies = [ + "proc-macro2", + "quote", + "syn 2.0.119", +] + +[[package]] +name = "windows-link" +version = "0.1.3" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "5e6ad25900d524eaabdbbb96d20b4311e1e7ae1699af4fb28c17ae66c80d798a" + +[[package]] +name = "windows-link" +version = "0.2.1" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "f0805222e57f7521d6a62e36fa9163bc891acd422f971defe97d64e70d0a4fe5" + +[[package]] +name = "windows-numerics" +version = "0.2.0" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "9150af68066c4c5c07ddc0ce30421554771e528bde427614c61038bc2c92c2b1" +dependencies = [ + "windows-core", + "windows-link 0.1.3", +] + +[[package]] +name = "windows-result" +version = "0.3.4" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "56f42bd332cc6c8eac5af113fc0c1fd6a8fd2aa08a0119358686e5160d0586c6" +dependencies = [ + "windows-link 0.1.3", +] + +[[package]] +name = "windows-strings" +version = "0.4.2" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "56e6c93f3a0c3b36176cb1327a4958a0353d5d166c2a35cb268ace15e91d3b57" +dependencies = [ + "windows-link 0.1.3", +] + +[[package]] +name = "windows-sys" +version = "0.45.0" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "75283be5efb2831d37ea142365f009c02ec203cd29a3ebecbc093d52315b66d0" +dependencies = [ + "windows-targets 0.42.2", +] + +[[package]] +name = "windows-sys" +version = "0.52.0" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "282be5f36a8ce781fad8c8ae18fa3f9beff57ec1b52cb3de0789201425d9a33d" +dependencies = [ + "windows-targets 0.52.6", +] + +[[package]] +name = "windows-sys" +version = "0.59.0" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "1e38bc4d79ed67fd075bcc251a1c39b32a1776bbe92e5bef1f0bf1f8c531853b" +dependencies = [ + "windows-targets 0.52.6", +] + +[[package]] +name = "windows-sys" +version = "0.60.2" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "f2f500e4d28234f72040990ec9d39e3a6b950f9f22d3dba18416c35882612bcb" +dependencies = [ + "windows-targets 0.53.5", +] + +[[package]] +name = "windows-sys" +version = "0.61.2" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "ae137229bcbd6cdf0f7b80a31df61766145077ddf49416a728b02cb3921ff3fc" +dependencies = [ + "windows-link 0.2.1", +] + +[[package]] +name = "windows-targets" +version = "0.42.2" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "8e5180c00cd44c9b1c88adb3693291f1cd93605ded80c250a75d472756b4d071" +dependencies = [ + "windows_aarch64_gnullvm 0.42.2", + "windows_aarch64_msvc 0.42.2", + "windows_i686_gnu 0.42.2", + "windows_i686_msvc 0.42.2", + "windows_x86_64_gnu 0.42.2", + "windows_x86_64_gnullvm 0.42.2", + "windows_x86_64_msvc 0.42.2", +] + +[[package]] +name = "windows-targets" +version = "0.52.6" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "9b724f72796e036ab90c1021d4780d4d3d648aca59e491e6b98e725b84e99973" +dependencies = [ + "windows_aarch64_gnullvm 0.52.6", + "windows_aarch64_msvc 0.52.6", + "windows_i686_gnu 0.52.6", + "windows_i686_gnullvm 0.52.6", + "windows_i686_msvc 0.52.6", + "windows_x86_64_gnu 0.52.6", + "windows_x86_64_gnullvm 0.52.6", + "windows_x86_64_msvc 0.52.6", +] + +[[package]] +name = "windows-targets" +version = "0.53.5" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "4945f9f551b88e0d65f3db0bc25c33b8acea4d9e41163edf90dcd0b19f9069f3" +dependencies = [ + "windows-link 0.2.1", + "windows_aarch64_gnullvm 0.53.1", + "windows_aarch64_msvc 0.53.1", + "windows_i686_gnu 0.53.1", + "windows_i686_gnullvm 0.53.1", + "windows_i686_msvc 0.53.1", + "windows_x86_64_gnu 0.53.1", + "windows_x86_64_gnullvm 0.53.1", + "windows_x86_64_msvc 0.53.1", +] + +[[package]] +name = "windows-threading" +version = "0.1.0" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "b66463ad2e0ea3bbf808b7f1d371311c80e115c0b71d60efc142cafbcfb057a6" +dependencies = [ + "windows-link 0.1.3", +] + +[[package]] +name = "windows-version" +version = "0.1.7" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "e4060a1da109b9d0326b7262c8e12c84df67cc0dbc9e33cf49e01ccc2eb63631" +dependencies = [ + "windows-link 0.2.1", +] + +[[package]] +name = "windows_aarch64_gnullvm" +version = "0.42.2" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "597a5118570b68bc08d8d59125332c54f1ba9d9adeedeef5b99b02ba2b0698f8" + +[[package]] +name = "windows_aarch64_gnullvm" +version = "0.52.6" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "32a4622180e7a0ec044bb555404c800bc9fd9ec262ec147edd5989ccd0c02cd3" + +[[package]] +name = "windows_aarch64_gnullvm" +version = "0.53.1" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "a9d8416fa8b42f5c947f8482c43e7d89e73a173cead56d044f6a56104a6d1b53" + +[[package]] +name = "windows_aarch64_msvc" +version = "0.42.2" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "e08e8864a60f06ef0d0ff4ba04124db8b0fb3be5776a5cd47641e942e58c4d43" + +[[package]] +name = "windows_aarch64_msvc" +version = "0.52.6" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "09ec2a7bb152e2252b53fa7803150007879548bc709c039df7627cabbd05d469" + +[[package]] +name = "windows_aarch64_msvc" +version = "0.53.1" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "b9d782e804c2f632e395708e99a94275910eb9100b2114651e04744e9b125006" + +[[package]] +name = "windows_i686_gnu" +version = "0.42.2" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "c61d927d8da41da96a81f029489353e68739737d3beca43145c8afec9a31a84f" + +[[package]] +name = "windows_i686_gnu" +version = "0.52.6" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "8e9b5ad5ab802e97eb8e295ac6720e509ee4c243f69d781394014ebfe8bbfa0b" + +[[package]] +name = "windows_i686_gnu" +version = "0.53.1" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "960e6da069d81e09becb0ca57a65220ddff016ff2d6af6a223cf372a506593a3" + +[[package]] +name = "windows_i686_gnullvm" +version = "0.52.6" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "0eee52d38c090b3caa76c563b86c3a4bd71ef1a819287c19d586d7334ae8ed66" + +[[package]] +name = "windows_i686_gnullvm" +version = "0.53.1" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "fa7359d10048f68ab8b09fa71c3daccfb0e9b559aed648a8f95469c27057180c" + +[[package]] +name = "windows_i686_msvc" +version = "0.42.2" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "44d840b6ec649f480a41c8d80f9c65108b92d89345dd94027bfe06ac444d1060" + +[[package]] +name = "windows_i686_msvc" +version = "0.52.6" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "240948bc05c5e7c6dabba28bf89d89ffce3e303022809e73deaefe4f6ec56c66" + +[[package]] +name = "windows_i686_msvc" +version = "0.53.1" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "1e7ac75179f18232fe9c285163565a57ef8d3c89254a30685b57d83a38d326c2" + +[[package]] +name = "windows_x86_64_gnu" +version = "0.42.2" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "8de912b8b8feb55c064867cf047dda097f92d51efad5b491dfb98f6bbb70cb36" + +[[package]] +name = "windows_x86_64_gnu" +version = "0.52.6" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "147a5c80aabfbf0c7d901cb5895d1de30ef2907eb21fbbab29ca94c5b08b1a78" + +[[package]] +name = "windows_x86_64_gnu" +version = "0.53.1" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "9c3842cdd74a865a8066ab39c8a7a473c0778a3f29370b5fd6b4b9aa7df4a499" + +[[package]] +name = "windows_x86_64_gnullvm" +version = "0.42.2" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "26d41b46a36d453748aedef1486d5c7a85db22e56aff34643984ea85514e94a3" + +[[package]] +name = "windows_x86_64_gnullvm" +version = "0.52.6" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "24d5b23dc417412679681396f2b49f3de8c1473deb516bd34410872eff51ed0d" + +[[package]] +name = "windows_x86_64_gnullvm" +version = "0.53.1" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "0ffa179e2d07eee8ad8f57493436566c7cc30ac536a3379fdf008f47f6bb7ae1" + +[[package]] +name = "windows_x86_64_msvc" +version = "0.42.2" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "9aec5da331524158c6d1a4ac0ab1541149c0b9505fde06423b02f5ef0106b9f0" + +[[package]] +name = "windows_x86_64_msvc" +version = "0.52.6" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "589f6da84c646204747d1270a2a5661ea66ed1cced2631d546fdfb155959f9ec" + +[[package]] +name = "windows_x86_64_msvc" +version = "0.53.1" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "d6bbff5f0aada427a1e5a6da5f1f98158182f26556f345ac9e04d36d0ebed650" + +[[package]] +name = "winnow" +version = "0.5.40" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "f593a95398737aeed53e489c785df13f3618e41dbcd6718c6addbf1395aa6876" +dependencies = [ + "memchr", +] + +[[package]] +name = "winnow" +version = "0.7.15" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "df79d97927682d2fd8adb29682d1140b343be4ac0f08fd68b7765d9c059d3945" +dependencies = [ + "memchr", +] + +[[package]] +name = "winnow" +version = "1.0.5" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "8c3b93199df0ab874cdf0c6a94f0a0dc3423fe41f1cafb62b8bd7b1deb277aef" +dependencies = [ + "memchr", +] + +[[package]] +name = "wit-bindgen" +version = "0.57.1" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "1ebf944e87a7c253233ad6766e082e3cd714b5d03812acc24c318f549614536e" + +[[package]] +name = "writeable" +version = "0.6.4" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "3ad82d2a33cdc9674dc7465672f271e096168fcdbe0f799d9e6db8c5892679dc" + +[[package]] +name = "wry" +version = "0.53.5" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "728b7d4c8ec8d81cab295e0b5b8a4c263c0d41a785fb8f8c4df284e5411140a2" +dependencies = [ + "base64 0.22.1", + "block2", + "cookie", + "crossbeam-channel", + "dirs", + "dpi", + "dunce", + "gtk", + "html5ever", + "http", + "javascriptcore-rs", + "jni 0.21.1", + "kuchikiki", + "libc", + "ndk", + "objc2", + "objc2-app-kit", + "objc2-core-foundation", + "objc2-foundation", + "objc2-ui-kit", + "objc2-web-kit", + "once_cell", + "percent-encoding", + "raw-window-handle 0.6.2", + "sha2", + "soup3", + "tao-macros", + "thiserror 2.0.21", + "url", + "webkit2gtk", + "webkit2gtk-sys", + "webview2-com", + "windows", + "windows-core", + "windows-version", +] + +[[package]] +name = "x11" +version = "2.21.0" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "502da5464ccd04011667b11c435cb992822c2c0dbde1770c988480d312a0db2e" +dependencies = [ + "libc", + "pkg-config", +] + +[[package]] +name = "x11-dl" +version = "2.21.0" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "38735924fedd5314a6e548792904ed8c6de6636285cb9fec04d5b1db85c1516f" +dependencies = [ + "libc", + "once_cell", + "pkg-config", +] + +[[package]] +name = "x11rb" +version = "0.13.2" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "9993aa5be5a26815fe2c3eacfc1fde061fc1a1f094bf1ad2a18bf9c495dd7414" +dependencies = [ + "gethostname", + "rustix", + "x11rb-protocol", +] + +[[package]] +name = "x11rb-protocol" +version = "0.13.2" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "ea6fc2961e4ef194dcbfe56bb845534d0dc8098940c7e5c012a258bfec6701bd" + +[[package]] +name = "xkeysym" +version = "0.2.1" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "b9cc00251562a284751c9973bace760d86c0276c471b4be569fe6b068ee97a56" + +[[package]] +name = "xxhash-rust" +version = "0.8.21" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "40de123dbb523ebcc00d61ec01840ad192578afc378d859f3429caa38308fad5" + +[[package]] +name = "y4m" +version = "0.8.0" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "7a5a4b21e1a62b67a2970e6831bc091d7b87e119e7f9791aef9702e3bef04448" + +[[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 = "zerocopy" +version = "0.8.64" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "ed43f3060383c64b000f3c630550aebdfa9d3b76d48de32390483dd2cc7e0865" +dependencies = [ + "zerocopy-derive", +] + +[[package]] +name = "zerocopy-derive" +version = "0.8.64" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "a5cbd820fe3e35fb38c83b6dc7e6b1618bc46e0cd10073ae94e8d52dc468d8b9" +dependencies = [ + "proc-macro2", + "quote", + "syn 2.0.119", +] + +[[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 = "zeroize" +version = "1.9.2" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "85ccff8a4805aba1eaa4cd4afcd49f7557dd2cf5fd79ffc37f8959466effc5aa" + +[[package]] +name = "zerotrie" +version = "0.2.5" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "4ea269c3bd32f0a32c321907a2ae912ba6f4649bb0fc764a15627e99a7095a3f" +dependencies = [ + "displaydoc", + "yoke", + "zerofrom", +] + +[[package]] +name = "zerovec" +version = "0.11.9" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "f58a2799cfe9a1670c7ea8edbd52ef8edb93cb37a7f83bf31ba9e35d9dae6a40" +dependencies = [ + "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 = "zlib-rs" +version = "0.6.9" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "aa76918995d776d9dd34d371030be228d021137449771493d56e29f77e4148ac" + +[[package]] +name = "zmij" +version = "1.0.23" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "29666d0abbfad1e3dc4dcf6144730dd3a3ab225bbbdac83319345b1b44ccfc1b" + +[[package]] +name = "zune-core" +version = "0.5.3" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "d56377fd46368984a170bc5aac5567e52ca5da874caa60bea39fcbca78fb658b" + +[[package]] +name = "zune-inflate" +version = "0.2.54" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "73ab332fe2f6680068f3582b16a24f90ad7096d5d39b974d1c0aff0125116f02" +dependencies = [ + "simd-adler32", +] + +[[package]] +name = "zune-jpeg" +version = "0.5.15" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "27bc9d5b815bc103f142aa054f561d9187d191692ec7c2d1e2b4737f8dbd7296" +dependencies = [ + "zune-core", +] diff --git a/dg-ui/Cargo.toml b/dg-ui/Cargo.toml new file mode 100644 index 0000000..3cfe9eb --- /dev/null +++ b/dg-ui/Cargo.toml @@ -0,0 +1,16 @@ +[package] +name = "dg-ui" +version = "0.1.0" +authors = ["folinhilo "] +edition = "2021" + +# See more keys and their definitions at https://doc.rust-lang.org/cargo/reference/manifest.html + +[dependencies] +dioxus = { version = "0.7.1", features = [] } + +[features] +default = ["web"] +web = ["dioxus/web"] +desktop = ["dioxus/desktop"] +mobile = ["dioxus/mobile"] diff --git a/dg-ui/Dioxus.toml b/dg-ui/Dioxus.toml new file mode 100644 index 0000000..81a5c30 --- /dev/null +++ b/dg-ui/Dioxus.toml @@ -0,0 +1,21 @@ +[application] + +[web.app] + +# HTML title tag content +title = "dg-ui" + +# include `assets` in web platform +[web.resource] + +# Additional CSS style files +style = [] + +# Additional JavaScript files +script = [] + +[web.resource.dev] + +# Javascript code file +# serve: [dev-server] only +script = [] diff --git a/dg-ui/README.md b/dg-ui/README.md new file mode 100644 index 0000000..321bbb9 --- /dev/null +++ b/dg-ui/README.md @@ -0,0 +1,51 @@ +# Development + +Your new bare-bones project includes minimal organization with a single `main.rs` file and a few assets. + +``` +project/ +├─ assets/ # Any assets that are used by the app should be placed here +├─ src/ +│ ├─ main.rs # main.rs is the entry point to your application and currently contains all components for the app +├─ Cargo.toml # The Cargo.toml file defines the dependencies and feature flags for your project +``` + +### Automatic Tailwind (Dioxus 0.7+) + +As of Dioxus 0.7, there no longer is a need to manually install tailwind. Simply `dx serve` and you're good to go! + +Automatic tailwind is supported by checking for a file called `tailwind.css` in your app's manifest directory (next to Cargo.toml). To customize the file, use the dioxus.toml: + +```toml +[application] +tailwind_input = "my.css" +tailwind_output = "assets/out.css" # also customize the location of the out file! +``` + +### Tailwind Manual Install + +To use tailwind plugins or manually customize tailwind, you can can install the Tailwind CLI and use it directly. + +### Tailwind +1. Install npm: https://docs.npmjs.com/downloading-and-installing-node-js-and-npm +2. Install the Tailwind CSS CLI: https://tailwindcss.com/docs/installation/tailwind-cli +3. Run the following command in the root of the project to start the Tailwind CSS compiler: + +```bash +npx @tailwindcss/cli -i ./input.css -o ./assets/tailwind.css --watch +``` + +### Serving Your App + +Run the following command in the root of your project to start developing with the default platform: + +```bash +dx serve +``` + +To run for a different platform, use the `--platform platform` flag. E.g. +```bash +dx serve --platform desktop +``` + + diff --git a/dg-ui/assets/main.css b/dg-ui/assets/main.css new file mode 100644 index 0000000..139597f --- /dev/null +++ b/dg-ui/assets/main.css @@ -0,0 +1,2 @@ + + diff --git a/dg-ui/assets/tailwind.css b/dg-ui/assets/tailwind.css new file mode 100644 index 0000000..e69de29 diff --git a/hot-dog/clippy.toml b/dg-ui/clippy.toml similarity index 100% rename from hot-dog/clippy.toml rename to dg-ui/clippy.toml diff --git a/dg-ui/node_modules/.bin/jiti b/dg-ui/node_modules/.bin/jiti new file mode 100644 index 0000000..45fd83d --- /dev/null +++ b/dg-ui/node_modules/.bin/jiti @@ -0,0 +1,33 @@ +#!/bin/sh +basedir=$(dirname "$(echo "$0" | sed -e 's,\\,/,g')") +basedir_win="$basedir" + +case `uname -a` in + *CYGWIN*|*MINGW*|*MSYS*) + if command -v cygpath > /dev/null 2>&1; then + basedir_win=`cygpath -w "$basedir"` + fi + ;; + *WSL2*) + if command -v wslpath > /dev/null 2>&1; then + basedir_win="$(wslpath -w "$basedir" 2> /dev/null)" + if [ $? -ne 0 ] || [ -z "$basedir_win" ]; then + echo "Error: wslpath failed to convert path. WSL environment may be misconfigured." >&2 + exit 1 + fi + fi + ;; +esac + +PROG_EXE="$basedir/node.exe" +if ! [ -x "$PROG_EXE" ]; then + PROG_EXE="$basedir/node" + if ! [ -x "$PROG_EXE" ]; then + PROG_EXE=node + if ! [ -x "$PROG_EXE" ]; then + PROG_EXE=node.exe + fi + fi +fi + +exec "$PROG_EXE" "$basedir_win/../jiti/lib/jiti-cli.mjs" "$@" diff --git a/dg-ui/node_modules/.bin/jiti.cmd b/dg-ui/node_modules/.bin/jiti.cmd new file mode 100644 index 0000000..9a91f4a --- /dev/null +++ b/dg-ui/node_modules/.bin/jiti.cmd @@ -0,0 +1,16 @@ +@ECHO off +GOTO start +:find_dp0 +SET dp0=%~dp0 +EXIT /b +:start +SETLOCAL +CALL :find_dp0 + +IF EXIST "%dp0%\node.exe" ( + SET "_prog=%dp0%\node.exe" +) ELSE ( + SET "_prog=node" +) + +endLocal & goto #_undefined_# 2>NUL || title %COMSPEC% & set PATHEXT=%PATHEXT:;.JS;=;% & "%_prog%" "%dp0%\..\jiti\lib\jiti-cli.mjs" %* diff --git a/dg-ui/node_modules/.bin/jiti.ps1 b/dg-ui/node_modules/.bin/jiti.ps1 new file mode 100644 index 0000000..baf5345 --- /dev/null +++ b/dg-ui/node_modules/.bin/jiti.ps1 @@ -0,0 +1,28 @@ +#!/usr/bin/env pwsh +$basedir=Split-Path $MyInvocation.MyCommand.Definition -Parent + +$exe="" +if ($PSVersionTable.PSVersion -lt "6.0" -or $IsWindows) { + # Fix case when both the Windows and Linux builds of Node + # are installed in the same directory + $exe=".exe" +} +$ret=0 +if (Test-Path "$basedir/node$exe") { + # Support pipeline input + if ($MyInvocation.ExpectingInput) { + $input | & "$basedir/node$exe" "$basedir/../jiti/lib/jiti-cli.mjs" $args + } else { + & "$basedir/node$exe" "$basedir/../jiti/lib/jiti-cli.mjs" $args + } + $ret=$LASTEXITCODE +} else { + # Support pipeline input + if ($MyInvocation.ExpectingInput) { + $input | & "node$exe" "$basedir/../jiti/lib/jiti-cli.mjs" $args + } else { + & "node$exe" "$basedir/../jiti/lib/jiti-cli.mjs" $args + } + $ret=$LASTEXITCODE +} +exit $ret diff --git a/dg-ui/node_modules/.bin/tailwindcss b/dg-ui/node_modules/.bin/tailwindcss new file mode 100644 index 0000000..d031483 --- /dev/null +++ b/dg-ui/node_modules/.bin/tailwindcss @@ -0,0 +1,33 @@ +#!/bin/sh +basedir=$(dirname "$(echo "$0" | sed -e 's,\\,/,g')") +basedir_win="$basedir" + +case `uname -a` in + *CYGWIN*|*MINGW*|*MSYS*) + if command -v cygpath > /dev/null 2>&1; then + basedir_win=`cygpath -w "$basedir"` + fi + ;; + *WSL2*) + if command -v wslpath > /dev/null 2>&1; then + basedir_win="$(wslpath -w "$basedir" 2> /dev/null)" + if [ $? -ne 0 ] || [ -z "$basedir_win" ]; then + echo "Error: wslpath failed to convert path. WSL environment may be misconfigured." >&2 + exit 1 + fi + fi + ;; +esac + +PROG_EXE="$basedir/node.exe" +if ! [ -x "$PROG_EXE" ]; then + PROG_EXE="$basedir/node" + if ! [ -x "$PROG_EXE" ]; then + PROG_EXE=node + if ! [ -x "$PROG_EXE" ]; then + PROG_EXE=node.exe + fi + fi +fi + +exec "$PROG_EXE" "$basedir_win/../@tailwindcss/cli/dist/index.mjs" "$@" diff --git a/dg-ui/node_modules/.bin/tailwindcss.cmd b/dg-ui/node_modules/.bin/tailwindcss.cmd new file mode 100644 index 0000000..7ca5235 --- /dev/null +++ b/dg-ui/node_modules/.bin/tailwindcss.cmd @@ -0,0 +1,16 @@ +@ECHO off +GOTO start +:find_dp0 +SET dp0=%~dp0 +EXIT /b +:start +SETLOCAL +CALL :find_dp0 + +IF EXIST "%dp0%\node.exe" ( + SET "_prog=%dp0%\node.exe" +) ELSE ( + SET "_prog=node" +) + +endLocal & goto #_undefined_# 2>NUL || title %COMSPEC% & set PATHEXT=%PATHEXT:;.JS;=;% & "%_prog%" "%dp0%\..\@tailwindcss\cli\dist\index.mjs" %* diff --git a/dg-ui/node_modules/.bin/tailwindcss.ps1 b/dg-ui/node_modules/.bin/tailwindcss.ps1 new file mode 100644 index 0000000..66d83e7 --- /dev/null +++ b/dg-ui/node_modules/.bin/tailwindcss.ps1 @@ -0,0 +1,28 @@ +#!/usr/bin/env pwsh +$basedir=Split-Path $MyInvocation.MyCommand.Definition -Parent + +$exe="" +if ($PSVersionTable.PSVersion -lt "6.0" -or $IsWindows) { + # Fix case when both the Windows and Linux builds of Node + # are installed in the same directory + $exe=".exe" +} +$ret=0 +if (Test-Path "$basedir/node$exe") { + # Support pipeline input + if ($MyInvocation.ExpectingInput) { + $input | & "$basedir/node$exe" "$basedir/../@tailwindcss/cli/dist/index.mjs" $args + } else { + & "$basedir/node$exe" "$basedir/../@tailwindcss/cli/dist/index.mjs" $args + } + $ret=$LASTEXITCODE +} else { + # Support pipeline input + if ($MyInvocation.ExpectingInput) { + $input | & "node$exe" "$basedir/../@tailwindcss/cli/dist/index.mjs" $args + } else { + & "node$exe" "$basedir/../@tailwindcss/cli/dist/index.mjs" $args + } + $ret=$LASTEXITCODE +} +exit $ret diff --git a/dg-ui/node_modules/.package-lock.json b/dg-ui/node_modules/.package-lock.json new file mode 100644 index 0000000..0658b1a --- /dev/null +++ b/dg-ui/node_modules/.package-lock.json @@ -0,0 +1,444 @@ +{ + "name": "dg-ui", + "lockfileVersion": 3, + "requires": true, + "packages": { + "node_modules/@jridgewell/gen-mapping": { + "version": "0.3.13", + "resolved": "https://registry.npmjs.org/@jridgewell/gen-mapping/-/gen-mapping-0.3.13.tgz", + "integrity": "sha512-2kkt/7niJ6MgEPxF0bYdQ6etZaA+fQvDcLKckhy1yIQOzaoKjBBjSj63/aLVjYE3qhRt5dvM+uUyfCg6UKCBbA==", + "license": "MIT", + "dependencies": { + "@jridgewell/sourcemap-codec": "^1.5.0", + "@jridgewell/trace-mapping": "^0.3.24" + } + }, + "node_modules/@jridgewell/remapping": { + "version": "2.3.5", + "resolved": "https://registry.npmjs.org/@jridgewell/remapping/-/remapping-2.3.5.tgz", + "integrity": "sha512-LI9u/+laYG4Ds1TDKSJW2YPrIlcVYOwi2fUC6xB43lueCjgxV4lffOCZCtYFiH6TNOX+tQKXx97T4IKHbhyHEQ==", + "license": "MIT", + "dependencies": { + "@jridgewell/gen-mapping": "^0.3.5", + "@jridgewell/trace-mapping": "^0.3.24" + } + }, + "node_modules/@jridgewell/resolve-uri": { + "version": "3.1.3", + "resolved": "https://registry.npmjs.org/@jridgewell/resolve-uri/-/resolve-uri-3.1.3.tgz", + "integrity": "sha512-lhTtjtoEArWBjismtfS761S9Hlyn+nIZqOZVYoZ1Xn82PMNMVnk+jj/NhC4fAXGTs7ydONcJiR5vyQBTMDu27g==", + "license": "MIT", + "engines": { + "node": ">=6.0.0" + } + }, + "node_modules/@jridgewell/sourcemap-codec": { + "version": "1.6.0", + "resolved": "https://registry.npmjs.org/@jridgewell/sourcemap-codec/-/sourcemap-codec-1.6.0.tgz", + "integrity": "sha512-T7jf+5zgsZHwNJ4lvQ7/aezbyk0nNX+zJVWpmHA7VYsEx7a7qr5Rg5IbtJFqkgze5Y2sruq1RUY8Q837Od7iFw==", + "license": "MIT" + }, + "node_modules/@jridgewell/trace-mapping": { + "version": "0.3.31", + "resolved": "https://registry.npmjs.org/@jridgewell/trace-mapping/-/trace-mapping-0.3.31.tgz", + "integrity": "sha512-zzNR+SdQSDJzc8joaeP8QQoCQr8NuYx2dIIytl1QeBEZHJ9uW6hebsrYgbz8hJwUQao3TWCMtmfV8Nu1twOLAw==", + "license": "MIT", + "dependencies": { + "@jridgewell/resolve-uri": "^3.1.0", + "@jridgewell/sourcemap-codec": "^1.4.14" + } + }, + "node_modules/@parcel/watcher": { + "version": "2.6.0", + "resolved": "https://registry.npmjs.org/@parcel/watcher/-/watcher-2.6.0.tgz", + "integrity": "sha512-7FNeNl8NCE7aINx7WXiKQrPYZWC/hvrTsmk6zmxbI7LTXE7hVek/n8AfVgpe2y82zl3w0HvCHN0bVKMBoJcC0w==", + "hasInstallScript": true, + "license": "MIT", + "dependencies": { + "detect-libc": "^2.0.3", + "is-glob": "^4.0.3", + "node-addon-api": "^7.0.0", + "picomatch": "^4.0.4" + }, + "engines": { + "node": ">= 10.0.0" + }, + "funding": { + "type": "opencollective", + "url": "https://opencollective.com/parcel" + }, + "optionalDependencies": { + "@parcel/watcher-android-arm64": "2.6.0", + "@parcel/watcher-darwin-arm64": "2.6.0", + "@parcel/watcher-darwin-x64": "2.6.0", + "@parcel/watcher-freebsd-x64": "2.6.0", + "@parcel/watcher-linux-arm-glibc": "2.6.0", + "@parcel/watcher-linux-arm-musl": "2.6.0", + "@parcel/watcher-linux-arm64-glibc": "2.6.0", + "@parcel/watcher-linux-arm64-musl": "2.6.0", + "@parcel/watcher-linux-x64-glibc": "2.6.0", + "@parcel/watcher-linux-x64-musl": "2.6.0", + "@parcel/watcher-win32-arm64": "2.6.0", + "@parcel/watcher-win32-x64": "2.6.0" + } + }, + "node_modules/@parcel/watcher-win32-x64": { + "version": "2.6.0", + "resolved": "https://registry.npmjs.org/@parcel/watcher-win32-x64/-/watcher-win32-x64-2.6.0.tgz", + "integrity": "sha512-cA+/pXV2YkfxlIcXOQ5fSWqAzzPyD78/x5qbK/I0vUkrlYHA8TIz+MXjAbGouguKVSI4bOmkTSJ1/poVSsgt+A==", + "cpu": [ + "x64" + ], + "license": "MIT", + "optional": true, + "os": [ + "win32" + ], + "engines": { + "node": ">= 10.0.0" + }, + "funding": { + "type": "opencollective", + "url": "https://opencollective.com/parcel" + } + }, + "node_modules/@tailwindcss/cli": { + "version": "4.3.5", + "resolved": "https://registry.npmjs.org/@tailwindcss/cli/-/cli-4.3.5.tgz", + "integrity": "sha512-+evrrLZEgNPDXgdIxD6Zfc23WhSYZQeGwniO5u9M4zC92kbEtIjKd8l2QWeO7du8kl4gF8z7YArnUGHG4y2Jzg==", + "license": "MIT", + "dependencies": { + "@parcel/watcher": "2.6.0", + "@tailwindcss/node": "4.3.5", + "@tailwindcss/oxide": "4.3.5", + "enhanced-resolve": "^5.24.5", + "mri": "^1.2.0", + "picocolors": "^1.1.1", + "tailwindcss": "4.3.5" + }, + "bin": { + "tailwindcss": "dist/index.mjs" + } + }, + "node_modules/@tailwindcss/node": { + "version": "4.3.5", + "resolved": "https://registry.npmjs.org/@tailwindcss/node/-/node-4.3.5.tgz", + "integrity": "sha512-yT53FzV4ke0cr/BguDxhWMpm5MJu1O2muzk+tKw6lKHjODAsYArBbWwFbJiaksfzFv1tpkO9QHGzmfs1hJT66g==", + "license": "MIT", + "dependencies": { + "@jridgewell/remapping": "^2.3.5", + "enhanced-resolve": "^5.24.5", + "jiti": "^2.7.0", + "lightningcss": "1.33.0", + "magic-string": "^1.1.0", + "source-map-js": "^1.2.1", + "tailwindcss": "4.3.5" + } + }, + "node_modules/@tailwindcss/oxide": { + "version": "4.3.5", + "resolved": "https://registry.npmjs.org/@tailwindcss/oxide/-/oxide-4.3.5.tgz", + "integrity": "sha512-PynqGLZsZvwM9tqD/CUxkOIfyd6K5elZ2MooauzJryP/UqXYgi3yYbtt3N0Xe+MHV/eFKPFQCEfIKAqlAS1CBg==", + "license": "MIT", + "engines": { + "node": ">= 20" + }, + "optionalDependencies": { + "@tailwindcss/oxide-android-arm64": "4.3.5", + "@tailwindcss/oxide-darwin-arm64": "4.3.5", + "@tailwindcss/oxide-darwin-x64": "4.3.5", + "@tailwindcss/oxide-freebsd-x64": "4.3.5", + "@tailwindcss/oxide-linux-arm-gnueabihf": "4.3.5", + "@tailwindcss/oxide-linux-arm64-gnu": "4.3.5", + "@tailwindcss/oxide-linux-arm64-musl": "4.3.5", + "@tailwindcss/oxide-linux-x64-gnu": "4.3.5", + "@tailwindcss/oxide-linux-x64-musl": "4.3.5", + "@tailwindcss/oxide-wasm32-wasi": "4.3.5", + "@tailwindcss/oxide-win32-arm64-msvc": "4.3.5", + "@tailwindcss/oxide-win32-x64-msvc": "4.3.5" + } + }, + "node_modules/@tailwindcss/oxide-wasm32-wasi": { + "version": "4.3.5", + "resolved": "https://registry.npmjs.org/@tailwindcss/oxide-wasm32-wasi/-/oxide-wasm32-wasi-4.3.5.tgz", + "integrity": "sha512-OJhFmlEfdzMr+avACdi40RPtnkW0B6hXyxL/8r+tnEHBWZji36CYRjEXrrvgBmaYsD3oEOBqwYFRKsYvzFe7Bw==", + "bundleDependencies": [ + "@napi-rs/wasm-runtime", + "@emnapi/core", + "@emnapi/runtime", + "@tybys/wasm-util", + "@emnapi/wasi-threads", + "tslib" + ], + "license": "MIT", + "optional": true, + "dependencies": { + "@emnapi/core": "^1.11.3", + "@emnapi/runtime": "^1.11.3", + "@emnapi/wasi-threads": "^1.2.3", + "@napi-rs/wasm-runtime": "^1.2.2", + "@tybys/wasm-util": "^0.10.3", + "tslib": "^2.8.1" + }, + "engines": { + "node": "^20.19.0 || ^22.13.0 || >=23.5.0" + } + }, + "node_modules/@tailwindcss/oxide-wasm32-wasi/node_modules/@emnapi/core": { + "version": "1.11.3", + "inBundle": true, + "license": "MIT", + "optional": true, + "dependencies": { + "@emnapi/wasi-threads": "1.2.3", + "tslib": "^2.4.0" + } + }, + "node_modules/@tailwindcss/oxide-wasm32-wasi/node_modules/@emnapi/runtime": { + "version": "1.11.3", + "inBundle": true, + "license": "MIT", + "optional": true, + "dependencies": { + "tslib": "^2.4.0" + } + }, + "node_modules/@tailwindcss/oxide-wasm32-wasi/node_modules/@emnapi/wasi-threads": { + "version": "1.2.3", + "inBundle": true, + "license": "MIT", + "optional": true, + "dependencies": { + "tslib": "^2.4.0" + } + }, + "node_modules/@tailwindcss/oxide-wasm32-wasi/node_modules/@napi-rs/wasm-runtime": { + "version": "1.2.2", + "inBundle": true, + "license": "MIT", + "optional": true, + "dependencies": { + "@tybys/wasm-util": "^0.10.3" + }, + "engines": { + "node": "^20.19.0 || ^22.13.0 || >=23.5.0" + }, + "funding": { + "type": "github", + "url": "https://github.com/sponsors/Brooooooklyn" + }, + "peerDependencies": { + "@emnapi/core": "^1.7.1 || ^2.0.0-alpha.3", + "@emnapi/runtime": "^1.7.1 || ^2.0.0-alpha.3" + } + }, + "node_modules/@tailwindcss/oxide-wasm32-wasi/node_modules/@tybys/wasm-util": { + "version": "0.10.3", + "inBundle": true, + "license": "MIT", + "optional": true, + "dependencies": { + "tslib": "^2.4.0" + } + }, + "node_modules/@tailwindcss/oxide-wasm32-wasi/node_modules/tslib": { + "version": "2.8.1", + "inBundle": true, + "license": "0BSD", + "optional": true + }, + "node_modules/@tailwindcss/oxide-win32-x64-msvc": { + "version": "4.3.5", + "resolved": "https://registry.npmjs.org/@tailwindcss/oxide-win32-x64-msvc/-/oxide-win32-x64-msvc-4.3.5.tgz", + "integrity": "sha512-XiKFfIy1RWe7qK4WqByxNW7Oz1/nkOy8o/BWhHminyV1PmpUd8Eedj5v2A8h2kpqeVlz6xRnwk9Fr/ZXNLcZfg==", + "cpu": [ + "x64" + ], + "license": "MIT", + "optional": true, + "os": [ + "win32" + ], + "engines": { + "node": ">= 20" + } + }, + "node_modules/detect-libc": { + "version": "2.1.2", + "resolved": "https://registry.npmjs.org/detect-libc/-/detect-libc-2.1.2.tgz", + "integrity": "sha512-Btj2BOOO83o3WyH59e8MgXsxEQVcarkUOpEYrubB0urwnN10yQ364rsiByU11nZlqWYZm05i/of7io4mzihBtQ==", + "license": "Apache-2.0", + "engines": { + "node": ">=8" + } + }, + "node_modules/enhanced-resolve": { + "version": "5.27.0", + "resolved": "https://registry.npmjs.org/enhanced-resolve/-/enhanced-resolve-5.27.0.tgz", + "integrity": "sha512-Do6BB2xzlcc/odFg+XEYyneAx4T/WfywO71yw9ePS2tVfRsf7JVR4mUeELadIeHzixkzbG5DpluiEFPi2WGfYQ==", + "license": "MIT", + "dependencies": { + "graceful-fs": "^4.2.4", + "tapable": "^2.3.3" + }, + "engines": { + "node": ">=10.13.0" + } + }, + "node_modules/graceful-fs": { + "version": "4.2.12", + "resolved": "https://registry.npmjs.org/graceful-fs/-/graceful-fs-4.2.12.tgz", + "integrity": "sha512-iuyGF2E4oafQfPsRrG2wtY2ILupMhvtdrhzrxB+0VcjsPpSPttpfYdjnGFGsTi5MaJFjI1jOKHPQ6UTbTj9TAw==", + "license": "BlueOak-1.0.0" + }, + "node_modules/is-extglob": { + "version": "2.1.1", + "resolved": "https://registry.npmjs.org/is-extglob/-/is-extglob-2.1.1.tgz", + "integrity": "sha512-SbKbANkN603Vi4jEZv49LeVJMn4yGwsbzZworEoyEiutsN3nJYdbO36zfhGJ6QEDpOZIFkDtnq5JRxmvl3jsoQ==", + "license": "MIT", + "engines": { + "node": ">=0.10.0" + } + }, + "node_modules/is-glob": { + "version": "4.0.3", + "resolved": "https://registry.npmjs.org/is-glob/-/is-glob-4.0.3.tgz", + "integrity": "sha512-xelSayHH36ZgE7ZWhli7pW34hNbNl8Ojv5KVmkJD4hBdD3th8Tfk9vYasLM+mXWOZhFkgZfxhLSnrwRr4elSSg==", + "license": "MIT", + "dependencies": { + "is-extglob": "^2.1.1" + }, + "engines": { + "node": ">=0.10.0" + } + }, + "node_modules/jiti": { + "version": "2.7.0", + "resolved": "https://registry.npmjs.org/jiti/-/jiti-2.7.0.tgz", + "integrity": "sha512-AC/7JofJvZGrrneWNaEnJeOLUx+JlGt7tNa0wZiRPT4MY1wmfKjt2+6O2p2uz2+skll8OZZmJMNqeke7kKbNgQ==", + "license": "MIT", + "bin": { + "jiti": "lib/jiti-cli.mjs" + } + }, + "node_modules/lightningcss": { + "version": "1.33.0", + "resolved": "https://registry.npmjs.org/lightningcss/-/lightningcss-1.33.0.tgz", + "integrity": "sha512-WkUDrojuJs0xkgGf2udWxa3yGBRxPtxUkB79i6aCZLRgc7PM8fZe9TosfPDcvEpQZbuFASnHYmRLBLUbmLOIIA==", + "license": "MPL-2.0", + "dependencies": { + "detect-libc": "^2.0.3" + }, + "engines": { + "node": ">= 12.0.0" + }, + "funding": { + "type": "opencollective", + "url": "https://opencollective.com/parcel" + }, + "optionalDependencies": { + "lightningcss-android-arm64": "1.33.0", + "lightningcss-darwin-arm64": "1.33.0", + "lightningcss-darwin-x64": "1.33.0", + "lightningcss-freebsd-x64": "1.33.0", + "lightningcss-linux-arm-gnueabihf": "1.33.0", + "lightningcss-linux-arm64-gnu": "1.33.0", + "lightningcss-linux-arm64-musl": "1.33.0", + "lightningcss-linux-x64-gnu": "1.33.0", + "lightningcss-linux-x64-musl": "1.33.0", + "lightningcss-win32-arm64-msvc": "1.33.0", + "lightningcss-win32-x64-msvc": "1.33.0" + } + }, + "node_modules/lightningcss-win32-x64-msvc": { + "version": "1.33.0", + "resolved": "https://registry.npmjs.org/lightningcss-win32-x64-msvc/-/lightningcss-win32-x64-msvc-1.33.0.tgz", + "integrity": "sha512-OlEICDx/Xl0FqSp4bry8zFnCvGpig3Gl4gCquvYwHuqJKEC1+n9NgDniFvqHGmMv1ZkqDJrDqKKSykTDX+ehuA==", + "cpu": [ + "x64" + ], + "license": "MPL-2.0", + "optional": true, + "os": [ + "win32" + ], + "engines": { + "node": ">= 12.0.0" + }, + "funding": { + "type": "opencollective", + "url": "https://opencollective.com/parcel" + } + }, + "node_modules/magic-string": { + "version": "1.4.5", + "resolved": "https://registry.npmjs.org/magic-string/-/magic-string-1.4.5.tgz", + "integrity": "sha512-oLLC2+YvQUfAa+vxoufE/yc1icb87M9iXIRqAoR/2EhE/8cb3SF/+Gi0c2By1B+5Vz2e2vQtUvHiu1+63Znh+w==", + "license": "MIT", + "dependencies": { + "@jridgewell/sourcemap-codec": "^1.6.0" + } + }, + "node_modules/mri": { + "version": "1.2.0", + "resolved": "https://registry.npmjs.org/mri/-/mri-1.2.0.tgz", + "integrity": "sha512-tzzskb3bG8LvYGFF/mDTpq3jpI6Q9wc3LEmBaghu+DdCssd1FakN7Bc0hVNmEyGq1bq3RgfkCb3cmQLpNPOroA==", + "license": "MIT", + "engines": { + "node": ">=4" + } + }, + "node_modules/node-addon-api": { + "version": "7.1.1", + "resolved": "https://registry.npmjs.org/node-addon-api/-/node-addon-api-7.1.1.tgz", + "integrity": "sha512-5m3bsyrjFWE1xf7nz7YXdN4udnVtXK6/Yfgn5qnahL6bCkf2yKt4k3nuTKAtT4r3IG8JNR2ncsIMdZuAzJjHQQ==", + "license": "MIT" + }, + "node_modules/picocolors": { + "version": "1.1.1", + "resolved": "https://registry.npmjs.org/picocolors/-/picocolors-1.1.1.tgz", + "integrity": "sha512-xceH2snhtb5M9liqDsmEw56le376mTZkEX/jEb/RxNFyegNul7eNslCXP9FDj/Lcu0X8KEyMceP2ntpaHrDEVA==", + "license": "ISC" + }, + "node_modules/picomatch": { + "version": "4.0.7", + "resolved": "https://registry.npmjs.org/picomatch/-/picomatch-4.0.7.tgz", + "integrity": "sha512-qcJu88Q2IWqJsDD529JKMdwGm/dvInW4HvQnRwiH9JtihJvzGOscDtHE3x1pBKeUOTysQ8kVmLnJ2kJu7yhcGA==", + "license": "MIT", + "engines": { + "node": ">=12" + }, + "funding": { + "url": "https://github.com/sponsors/jonschlinkert" + } + }, + "node_modules/source-map-js": { + "version": "1.2.4", + "resolved": "https://registry.npmjs.org/source-map-js/-/source-map-js-1.2.4.tgz", + "integrity": "sha512-J7ZjMvHd9O1fcT/5V09QWaaSl2BbWx3F6O08spde82Namf9UB0GxRVIPiNbVsdKkoizHiSpTodo3vp2bAy91MA==", + "license": "BSD-3-Clause", + "engines": { + "node": ">=6.0.0" + } + }, + "node_modules/tailwindcss": { + "version": "4.3.5", + "resolved": "https://registry.npmjs.org/tailwindcss/-/tailwindcss-4.3.5.tgz", + "integrity": "sha512-FcQk9BuffmEHJP2G0XmB2SplU1aLTI7j07Kunk+U74Ny+XiWOtzXz9aujFZ/avntw1e2cOv/3PkgzflQ7gX2vQ==", + "license": "MIT" + }, + "node_modules/tapable": { + "version": "2.3.4", + "resolved": "https://registry.npmjs.org/tapable/-/tapable-2.3.4.tgz", + "integrity": "sha512-NHFiWnAbMJxNNpBwiO7jJVGDuqMxT9/oV8v57RR+fgBQShkJil5inGD8/xWy0hjLyHQyX1tu27QANhlz3KBqCg==", + "license": "MIT", + "engines": { + "node": ">=6" + }, + "funding": { + "type": "opencollective", + "url": "https://opencollective.com/webpack" + } + } + } +} diff --git a/dg-ui/node_modules/@jridgewell/gen-mapping/LICENSE b/dg-ui/node_modules/@jridgewell/gen-mapping/LICENSE new file mode 100644 index 0000000..1f6ce94 --- /dev/null +++ b/dg-ui/node_modules/@jridgewell/gen-mapping/LICENSE @@ -0,0 +1,19 @@ +Copyright 2024 Justin Ridgewell + +Permission is hereby granted, free of charge, to any person obtaining a copy +of this software and associated documentation files (the "Software"), to deal +in the Software without restriction, including without limitation the rights +to use, copy, modify, merge, publish, distribute, sublicense, and/or sell +copies of the Software, and to permit persons to whom the Software is +furnished to do so, subject to the following conditions: + +The above copyright notice and this permission notice shall be included in +all copies or substantial portions of the Software. + +THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR +IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, +FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE +AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER +LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, +OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE +SOFTWARE. diff --git a/dg-ui/node_modules/@jridgewell/gen-mapping/README.md b/dg-ui/node_modules/@jridgewell/gen-mapping/README.md new file mode 100644 index 0000000..93692b1 --- /dev/null +++ b/dg-ui/node_modules/@jridgewell/gen-mapping/README.md @@ -0,0 +1,227 @@ +# @jridgewell/gen-mapping + +> Generate source maps + +`gen-mapping` allows you to generate a source map during transpilation or minification. +With a source map, you're able to trace the original location in the source file, either in Chrome's +DevTools or using a library like [`@jridgewell/trace-mapping`][trace-mapping]. + +You may already be familiar with the [`source-map`][source-map] package's `SourceMapGenerator`. This +provides the same `addMapping` and `setSourceContent` API. + +## Installation + +```sh +npm install @jridgewell/gen-mapping +``` + +## Usage + +```typescript +import { GenMapping, addMapping, setSourceContent, toEncodedMap, toDecodedMap } from '@jridgewell/gen-mapping'; + +const map = new GenMapping({ + file: 'output.js', + sourceRoot: 'https://example.com/', +}); + +setSourceContent(map, 'input.js', `function foo() {}`); + +addMapping(map, { + // Lines start at line 1, columns at column 0. + generated: { line: 1, column: 0 }, + source: 'input.js', + original: { line: 1, column: 0 }, +}); + +addMapping(map, { + generated: { line: 1, column: 9 }, + source: 'input.js', + original: { line: 1, column: 9 }, + name: 'foo', +}); + +assert.deepEqual(toDecodedMap(map), { + version: 3, + file: 'output.js', + names: ['foo'], + sourceRoot: 'https://example.com/', + sources: ['input.js'], + sourcesContent: ['function foo() {}'], + mappings: [ + [ [0, 0, 0, 0], [9, 0, 0, 9, 0] ] + ], +}); + +assert.deepEqual(toEncodedMap(map), { + version: 3, + file: 'output.js', + names: ['foo'], + sourceRoot: 'https://example.com/', + sources: ['input.js'], + sourcesContent: ['function foo() {}'], + mappings: 'AAAA,SAASA', +}); +``` + +### Smaller Sourcemaps + +Not everything needs to be added to a sourcemap, and needless markings can cause signficantly +larger file sizes. `gen-mapping` exposes `maybeAddSegment`/`maybeAddMapping` APIs that will +intelligently determine if this marking adds useful information. If not, the marking will be +skipped. + +```typescript +import { maybeAddMapping } from '@jridgewell/gen-mapping'; + +const map = new GenMapping(); + +// Adding a sourceless marking at the beginning of a line isn't useful. +maybeAddMapping(map, { + generated: { line: 1, column: 0 }, +}); + +// Adding a new source marking is useful. +maybeAddMapping(map, { + generated: { line: 1, column: 0 }, + source: 'input.js', + original: { line: 1, column: 0 }, +}); + +// But adding another marking pointing to the exact same original location isn't, even if the +// generated column changed. +maybeAddMapping(map, { + generated: { line: 1, column: 9 }, + source: 'input.js', + original: { line: 1, column: 0 }, +}); + +assert.deepEqual(toEncodedMap(map), { + version: 3, + names: [], + sources: ['input.js'], + sourcesContent: [null], + mappings: 'AAAA', +}); +``` + +## Benchmarks + +``` +node v18.0.0 + +amp.js.map +Memory Usage: +gen-mapping: addSegment 5852872 bytes +gen-mapping: addMapping 7716042 bytes +source-map-js 6143250 bytes +source-map-0.6.1 6124102 bytes +source-map-0.8.0 6121173 bytes +Smallest memory usage is gen-mapping: addSegment + +Adding speed: +gen-mapping: addSegment x 441 ops/sec ±2.07% (90 runs sampled) +gen-mapping: addMapping x 350 ops/sec ±2.40% (86 runs sampled) +source-map-js: addMapping x 169 ops/sec ±2.42% (80 runs sampled) +source-map-0.6.1: addMapping x 167 ops/sec ±2.56% (80 runs sampled) +source-map-0.8.0: addMapping x 168 ops/sec ±2.52% (80 runs sampled) +Fastest is gen-mapping: addSegment + +Generate speed: +gen-mapping: decoded output x 150,824,370 ops/sec ±0.07% (102 runs sampled) +gen-mapping: encoded output x 663 ops/sec ±0.22% (98 runs sampled) +source-map-js: encoded output x 197 ops/sec ±0.45% (84 runs sampled) +source-map-0.6.1: encoded output x 198 ops/sec ±0.33% (85 runs sampled) +source-map-0.8.0: encoded output x 197 ops/sec ±0.06% (93 runs sampled) +Fastest is gen-mapping: decoded output + + +*** + + +babel.min.js.map +Memory Usage: +gen-mapping: addSegment 37578063 bytes +gen-mapping: addMapping 37212897 bytes +source-map-js 47638527 bytes +source-map-0.6.1 47690503 bytes +source-map-0.8.0 47470188 bytes +Smallest memory usage is gen-mapping: addMapping + +Adding speed: +gen-mapping: addSegment x 31.05 ops/sec ±8.31% (43 runs sampled) +gen-mapping: addMapping x 29.83 ops/sec ±7.36% (51 runs sampled) +source-map-js: addMapping x 20.73 ops/sec ±6.22% (38 runs sampled) +source-map-0.6.1: addMapping x 20.03 ops/sec ±10.51% (38 runs sampled) +source-map-0.8.0: addMapping x 19.30 ops/sec ±8.27% (37 runs sampled) +Fastest is gen-mapping: addSegment + +Generate speed: +gen-mapping: decoded output x 381,379,234 ops/sec ±0.29% (96 runs sampled) +gen-mapping: encoded output x 95.15 ops/sec ±2.98% (72 runs sampled) +source-map-js: encoded output x 15.20 ops/sec ±7.41% (33 runs sampled) +source-map-0.6.1: encoded output x 16.36 ops/sec ±10.46% (31 runs sampled) +source-map-0.8.0: encoded output x 16.06 ops/sec ±6.45% (31 runs sampled) +Fastest is gen-mapping: decoded output + + +*** + + +preact.js.map +Memory Usage: +gen-mapping: addSegment 416247 bytes +gen-mapping: addMapping 419824 bytes +source-map-js 1024619 bytes +source-map-0.6.1 1146004 bytes +source-map-0.8.0 1113250 bytes +Smallest memory usage is gen-mapping: addSegment + +Adding speed: +gen-mapping: addSegment x 13,755 ops/sec ±0.15% (98 runs sampled) +gen-mapping: addMapping x 13,013 ops/sec ±0.11% (101 runs sampled) +source-map-js: addMapping x 4,564 ops/sec ±0.21% (98 runs sampled) +source-map-0.6.1: addMapping x 4,562 ops/sec ±0.11% (99 runs sampled) +source-map-0.8.0: addMapping x 4,593 ops/sec ±0.11% (100 runs sampled) +Fastest is gen-mapping: addSegment + +Generate speed: +gen-mapping: decoded output x 379,864,020 ops/sec ±0.23% (93 runs sampled) +gen-mapping: encoded output x 14,368 ops/sec ±4.07% (82 runs sampled) +source-map-js: encoded output x 5,261 ops/sec ±0.21% (99 runs sampled) +source-map-0.6.1: encoded output x 5,124 ops/sec ±0.58% (99 runs sampled) +source-map-0.8.0: encoded output x 5,434 ops/sec ±0.33% (96 runs sampled) +Fastest is gen-mapping: decoded output + + +*** + + +react.js.map +Memory Usage: +gen-mapping: addSegment 975096 bytes +gen-mapping: addMapping 1102981 bytes +source-map-js 2918836 bytes +source-map-0.6.1 2885435 bytes +source-map-0.8.0 2874336 bytes +Smallest memory usage is gen-mapping: addSegment + +Adding speed: +gen-mapping: addSegment x 4,772 ops/sec ±0.15% (100 runs sampled) +gen-mapping: addMapping x 4,456 ops/sec ±0.13% (97 runs sampled) +source-map-js: addMapping x 1,618 ops/sec ±0.24% (97 runs sampled) +source-map-0.6.1: addMapping x 1,622 ops/sec ±0.12% (99 runs sampled) +source-map-0.8.0: addMapping x 1,631 ops/sec ±0.12% (100 runs sampled) +Fastest is gen-mapping: addSegment + +Generate speed: +gen-mapping: decoded output x 379,107,695 ops/sec ±0.07% (99 runs sampled) +gen-mapping: encoded output x 5,421 ops/sec ±1.60% (89 runs sampled) +source-map-js: encoded output x 2,113 ops/sec ±1.81% (98 runs sampled) +source-map-0.6.1: encoded output x 2,126 ops/sec ±0.10% (100 runs sampled) +source-map-0.8.0: encoded output x 2,176 ops/sec ±0.39% (98 runs sampled) +Fastest is gen-mapping: decoded output +``` + +[source-map]: https://www.npmjs.com/package/source-map +[trace-mapping]: https://github.com/jridgewell/sourcemaps/tree/main/packages/trace-mapping diff --git a/dg-ui/node_modules/@jridgewell/gen-mapping/dist/gen-mapping.mjs b/dg-ui/node_modules/@jridgewell/gen-mapping/dist/gen-mapping.mjs new file mode 100644 index 0000000..bbb0cac --- /dev/null +++ b/dg-ui/node_modules/@jridgewell/gen-mapping/dist/gen-mapping.mjs @@ -0,0 +1,292 @@ +// src/set-array.ts +var SetArray = class { + constructor() { + this._indexes = { __proto__: null }; + this.array = []; + } +}; +function cast(set) { + return set; +} +function get(setarr, key) { + return cast(setarr)._indexes[key]; +} +function put(setarr, key) { + const index = get(setarr, key); + if (index !== void 0) return index; + const { array, _indexes: indexes } = cast(setarr); + const length = array.push(key); + return indexes[key] = length - 1; +} +function remove(setarr, key) { + const index = get(setarr, key); + if (index === void 0) return; + const { array, _indexes: indexes } = cast(setarr); + for (let i = index + 1; i < array.length; i++) { + const k = array[i]; + array[i - 1] = k; + indexes[k]--; + } + indexes[key] = void 0; + array.pop(); +} + +// src/gen-mapping.ts +import { + encode +} from "@jridgewell/sourcemap-codec"; +import { TraceMap, decodedMappings } from "@jridgewell/trace-mapping"; + +// src/sourcemap-segment.ts +var COLUMN = 0; +var SOURCES_INDEX = 1; +var SOURCE_LINE = 2; +var SOURCE_COLUMN = 3; +var NAMES_INDEX = 4; + +// src/gen-mapping.ts +var NO_NAME = -1; +var GenMapping = class { + constructor({ file, sourceRoot } = {}) { + this._names = new SetArray(); + this._sources = new SetArray(); + this._sourcesContent = []; + this._mappings = []; + this.file = file; + this.sourceRoot = sourceRoot; + this._ignoreList = new SetArray(); + } +}; +function cast2(map) { + return map; +} +function addSegment(map, genLine, genColumn, source, sourceLine, sourceColumn, name, content) { + return addSegmentInternal( + false, + map, + genLine, + genColumn, + source, + sourceLine, + sourceColumn, + name, + content + ); +} +function addMapping(map, mapping) { + return addMappingInternal(false, map, mapping); +} +var maybeAddSegment = (map, genLine, genColumn, source, sourceLine, sourceColumn, name, content) => { + return addSegmentInternal( + true, + map, + genLine, + genColumn, + source, + sourceLine, + sourceColumn, + name, + content + ); +}; +var maybeAddMapping = (map, mapping) => { + return addMappingInternal(true, map, mapping); +}; +function setSourceContent(map, source, content) { + const { + _sources: sources, + _sourcesContent: sourcesContent + // _originalScopes: originalScopes, + } = cast2(map); + const index = put(sources, source); + sourcesContent[index] = content; +} +function setIgnore(map, source, ignore = true) { + const { + _sources: sources, + _sourcesContent: sourcesContent, + _ignoreList: ignoreList + // _originalScopes: originalScopes, + } = cast2(map); + const index = put(sources, source); + if (index === sourcesContent.length) sourcesContent[index] = null; + if (ignore) put(ignoreList, index); + else remove(ignoreList, index); +} +function toDecodedMap(map) { + const { + _mappings: mappings, + _sources: sources, + _sourcesContent: sourcesContent, + _names: names, + _ignoreList: ignoreList + // _originalScopes: originalScopes, + // _generatedRanges: generatedRanges, + } = cast2(map); + removeEmptyFinalLines(mappings); + return { + version: 3, + file: map.file || void 0, + names: names.array, + sourceRoot: map.sourceRoot || void 0, + sources: sources.array, + sourcesContent, + mappings, + // originalScopes, + // generatedRanges, + ignoreList: ignoreList.array + }; +} +function toEncodedMap(map) { + const decoded = toDecodedMap(map); + return Object.assign({}, decoded, { + // originalScopes: decoded.originalScopes.map((os) => encodeOriginalScopes(os)), + // generatedRanges: encodeGeneratedRanges(decoded.generatedRanges as GeneratedRange[]), + mappings: encode(decoded.mappings) + }); +} +function fromMap(input) { + const map = new TraceMap(input); + const gen = new GenMapping({ file: map.file, sourceRoot: map.sourceRoot }); + putAll(cast2(gen)._names, map.names); + putAll(cast2(gen)._sources, map.sources); + cast2(gen)._sourcesContent = map.sourcesContent || map.sources.map(() => null); + cast2(gen)._mappings = decodedMappings(map); + if (map.ignoreList) putAll(cast2(gen)._ignoreList, map.ignoreList); + return gen; +} +function allMappings(map) { + const out = []; + const { _mappings: mappings, _sources: sources, _names: names } = cast2(map); + for (let i = 0; i < mappings.length; i++) { + const line = mappings[i]; + for (let j = 0; j < line.length; j++) { + const seg = line[j]; + const generated = { line: i + 1, column: seg[COLUMN] }; + let source = void 0; + let original = void 0; + let name = void 0; + if (seg.length !== 1) { + source = sources.array[seg[SOURCES_INDEX]]; + original = { line: seg[SOURCE_LINE] + 1, column: seg[SOURCE_COLUMN] }; + if (seg.length === 5) name = names.array[seg[NAMES_INDEX]]; + } + out.push({ generated, source, original, name }); + } + } + return out; +} +function addSegmentInternal(skipable, map, genLine, genColumn, source, sourceLine, sourceColumn, name, content) { + const { + _mappings: mappings, + _sources: sources, + _sourcesContent: sourcesContent, + _names: names + // _originalScopes: originalScopes, + } = cast2(map); + const line = getIndex(mappings, genLine); + const index = getColumnIndex(line, genColumn); + if (!source) { + if (skipable && skipSourceless(line, index)) return; + return insert(line, index, [genColumn]); + } + assert(sourceLine); + assert(sourceColumn); + const sourcesIndex = put(sources, source); + const namesIndex = name ? put(names, name) : NO_NAME; + if (sourcesIndex === sourcesContent.length) sourcesContent[sourcesIndex] = content != null ? content : null; + if (skipable && skipSource(line, index, sourcesIndex, sourceLine, sourceColumn, namesIndex)) { + return; + } + return insert( + line, + index, + name ? [genColumn, sourcesIndex, sourceLine, sourceColumn, namesIndex] : [genColumn, sourcesIndex, sourceLine, sourceColumn] + ); +} +function assert(_val) { +} +function getIndex(arr, index) { + for (let i = arr.length; i <= index; i++) { + arr[i] = []; + } + return arr[index]; +} +function getColumnIndex(line, genColumn) { + let index = line.length; + for (let i = index - 1; i >= 0; index = i--) { + const current = line[i]; + if (genColumn >= current[COLUMN]) break; + } + return index; +} +function insert(array, index, value) { + for (let i = array.length; i > index; i--) { + array[i] = array[i - 1]; + } + array[index] = value; +} +function removeEmptyFinalLines(mappings) { + const { length } = mappings; + let len = length; + for (let i = len - 1; i >= 0; len = i, i--) { + if (mappings[i].length > 0) break; + } + if (len < length) mappings.length = len; +} +function putAll(setarr, array) { + for (let i = 0; i < array.length; i++) put(setarr, array[i]); +} +function skipSourceless(line, index) { + if (index === 0) return true; + const prev = line[index - 1]; + return prev.length === 1; +} +function skipSource(line, index, sourcesIndex, sourceLine, sourceColumn, namesIndex) { + if (index === 0) return false; + const prev = line[index - 1]; + if (prev.length === 1) return false; + return sourcesIndex === prev[SOURCES_INDEX] && sourceLine === prev[SOURCE_LINE] && sourceColumn === prev[SOURCE_COLUMN] && namesIndex === (prev.length === 5 ? prev[NAMES_INDEX] : NO_NAME); +} +function addMappingInternal(skipable, map, mapping) { + const { generated, source, original, name, content } = mapping; + if (!source) { + return addSegmentInternal( + skipable, + map, + generated.line - 1, + generated.column, + null, + null, + null, + null, + null + ); + } + assert(original); + return addSegmentInternal( + skipable, + map, + generated.line - 1, + generated.column, + source, + original.line - 1, + original.column, + name, + content + ); +} +export { + GenMapping, + addMapping, + addSegment, + allMappings, + fromMap, + maybeAddMapping, + maybeAddSegment, + setIgnore, + setSourceContent, + toDecodedMap, + toEncodedMap +}; +//# sourceMappingURL=gen-mapping.mjs.map diff --git a/dg-ui/node_modules/@jridgewell/gen-mapping/dist/gen-mapping.mjs.map b/dg-ui/node_modules/@jridgewell/gen-mapping/dist/gen-mapping.mjs.map new file mode 100644 index 0000000..4e37e45 --- /dev/null +++ b/dg-ui/node_modules/@jridgewell/gen-mapping/dist/gen-mapping.mjs.map @@ -0,0 +1,6 @@ +{ + "version": 3, + "sources": ["../src/set-array.ts", "../src/gen-mapping.ts", "../src/sourcemap-segment.ts"], + "mappings": ";AAUO,IAAM,WAAN,MAAoC;AAAA,EAIzC,cAAc;AACZ,SAAK,WAAW,EAAE,WAAW,KAAK;AAClC,SAAK,QAAQ,CAAC;AAAA,EAChB;AACF;AAWA,SAAS,KAAoB,KAAgC;AAC3D,SAAO;AACT;AAKO,SAAS,IAAmB,QAAqB,KAA4B;AAClF,SAAO,KAAK,MAAM,EAAE,SAAS,GAAG;AAClC;AAMO,SAAS,IAAmB,QAAqB,KAAgB;AAEtE,QAAM,QAAQ,IAAI,QAAQ,GAAG;AAC7B,MAAI,UAAU,OAAW,QAAO;AAEhC,QAAM,EAAE,OAAO,UAAU,QAAQ,IAAI,KAAK,MAAM;AAEhD,QAAM,SAAS,MAAM,KAAK,GAAG;AAC7B,SAAQ,QAAQ,GAAG,IAAI,SAAS;AAClC;AAgBO,SAAS,OAAsB,QAAqB,KAAc;AACvE,QAAM,QAAQ,IAAI,QAAQ,GAAG;AAC7B,MAAI,UAAU,OAAW;AAEzB,QAAM,EAAE,OAAO,UAAU,QAAQ,IAAI,KAAK,MAAM;AAChD,WAAS,IAAI,QAAQ,GAAG,IAAI,MAAM,QAAQ,KAAK;AAC7C,UAAM,IAAI,MAAM,CAAC;AACjB,UAAM,IAAI,CAAC,IAAI;AACf,YAAQ,CAAC;AAAA,EACX;AACA,UAAQ,GAAG,IAAI;AACf,QAAM,IAAI;AACZ;;;AChFA;AAAA,EACE;AAAA,OAGK;AACP,SAAS,UAAU,uBAAuB;;;ACKnC,IAAM,SAAS;AACf,IAAM,gBAAgB;AACtB,IAAM,cAAc;AACpB,IAAM,gBAAgB;AACtB,IAAM,cAAc;;;ADsB3B,IAAM,UAAU;AAKT,IAAM,aAAN,MAAiB;AAAA,EAWtB,YAAY,EAAE,MAAM,WAAW,IAAa,CAAC,GAAG;AAC9C,SAAK,SAAS,IAAI,SAAS;AAC3B,SAAK,WAAW,IAAI,SAAS;AAC7B,SAAK,kBAAkB,CAAC;AACxB,SAAK,YAAY,CAAC;AAGlB,SAAK,OAAO;AACZ,SAAK,aAAa;AAClB,SAAK,cAAc,IAAI,SAAS;AAAA,EAClC;AACF;AAgBA,SAASA,MAAK,KAAyB;AACrC,SAAO;AACT;AAoCO,SAAS,WACd,KACA,SACA,WACA,QACA,YACA,cACA,MACA,SACM;AACN,SAAO;AAAA,IACL;AAAA,IACA;AAAA,IACA;AAAA,IACA;AAAA,IACA;AAAA,IACA;AAAA,IACA;AAAA,IACA;AAAA,IACA;AAAA,EACF;AACF;AAoCO,SAAS,WACd,KACA,SAOM;AACN,SAAO,mBAAmB,OAAO,KAAK,OAAmD;AAC3F;AAOO,IAAM,kBAAqC,CAChD,KACA,SACA,WACA,QACA,YACA,cACA,MACA,YACG;AACH,SAAO;AAAA,IACL;AAAA,IACA;AAAA,IACA;AAAA,IACA;AAAA,IACA;AAAA,IACA;AAAA,IACA;AAAA,IACA;AAAA,IACA;AAAA,EACF;AACF;AAOO,IAAM,kBAAqC,CAAC,KAAK,YAAY;AAClE,SAAO,mBAAmB,MAAM,KAAK,OAAmD;AAC1F;AAKO,SAAS,iBAAiB,KAAiB,QAAgB,SAA8B;AAC9F,QAAM;AAAA,IACJ,UAAU;AAAA,IACV,iBAAiB;AAAA;AAAA,EAEnB,IAAIA,MAAK,GAAG;AACZ,QAAM,QAAQ,IAAI,SAAS,MAAM;AACjC,iBAAe,KAAK,IAAI;AAE1B;AAEO,SAAS,UAAU,KAAiB,QAAgB,SAAS,MAAM;AACxE,QAAM;AAAA,IACJ,UAAU;AAAA,IACV,iBAAiB;AAAA,IACjB,aAAa;AAAA;AAAA,EAEf,IAAIA,MAAK,GAAG;AACZ,QAAM,QAAQ,IAAI,SAAS,MAAM;AACjC,MAAI,UAAU,eAAe,OAAQ,gBAAe,KAAK,IAAI;AAE7D,MAAI,OAAQ,KAAI,YAAY,KAAK;AAAA,MAC5B,QAAO,YAAY,KAAK;AAC/B;AAMO,SAAS,aAAa,KAAmC;AAC9D,QAAM;AAAA,IACJ,WAAW;AAAA,IACX,UAAU;AAAA,IACV,iBAAiB;AAAA,IACjB,QAAQ;AAAA,IACR,aAAa;AAAA;AAAA;AAAA,EAGf,IAAIA,MAAK,GAAG;AACZ,wBAAsB,QAAQ;AAE9B,SAAO;AAAA,IACL,SAAS;AAAA,IACT,MAAM,IAAI,QAAQ;AAAA,IAClB,OAAO,MAAM;AAAA,IACb,YAAY,IAAI,cAAc;AAAA,IAC9B,SAAS,QAAQ;AAAA,IACjB;AAAA,IACA;AAAA;AAAA;AAAA,IAGA,YAAY,WAAW;AAAA,EACzB;AACF;AAMO,SAAS,aAAa,KAAmC;AAC9D,QAAM,UAAU,aAAa,GAAG;AAChC,SAAO,OAAO,OAAO,CAAC,GAAG,SAAS;AAAA;AAAA;AAAA,IAGhC,UAAU,OAAO,QAAQ,QAAgC;AAAA,EAC3D,CAAC;AACH;AAKO,SAAS,QAAQ,OAAmC;AACzD,QAAM,MAAM,IAAI,SAAS,KAAK;AAC9B,QAAM,MAAM,IAAI,WAAW,EAAE,MAAM,IAAI,MAAM,YAAY,IAAI,WAAW,CAAC;AAEzE,SAAOA,MAAK,GAAG,EAAE,QAAQ,IAAI,KAAK;AAClC,SAAOA,MAAK,GAAG,EAAE,UAAU,IAAI,OAAmB;AAClD,EAAAA,MAAK,GAAG,EAAE,kBAAkB,IAAI,kBAAkB,IAAI,QAAQ,IAAI,MAAM,IAAI;AAC5E,EAAAA,MAAK,GAAG,EAAE,YAAY,gBAAgB,GAAG;AAEzC,MAAI,IAAI,WAAY,QAAOA,MAAK,GAAG,EAAE,aAAa,IAAI,UAAU;AAEhE,SAAO;AACT;AAMO,SAAS,YAAY,KAA4B;AACtD,QAAM,MAAiB,CAAC;AACxB,QAAM,EAAE,WAAW,UAAU,UAAU,SAAS,QAAQ,MAAM,IAAIA,MAAK,GAAG;AAE1E,WAAS,IAAI,GAAG,IAAI,SAAS,QAAQ,KAAK;AACxC,UAAM,OAAO,SAAS,CAAC;AACvB,aAAS,IAAI,GAAG,IAAI,KAAK,QAAQ,KAAK;AACpC,YAAM,MAAM,KAAK,CAAC;AAElB,YAAM,YAAY,EAAE,MAAM,IAAI,GAAG,QAAQ,IAAI,MAAM,EAAE;AACrD,UAAI,SAA6B;AACjC,UAAI,WAA4B;AAChC,UAAI,OAA2B;AAE/B,UAAI,IAAI,WAAW,GAAG;AACpB,iBAAS,QAAQ,MAAM,IAAI,aAAa,CAAC;AACzC,mBAAW,EAAE,MAAM,IAAI,WAAW,IAAI,GAAG,QAAQ,IAAI,aAAa,EAAE;AAEpE,YAAI,IAAI,WAAW,EAAG,QAAO,MAAM,MAAM,IAAI,WAAW,CAAC;AAAA,MAC3D;AAEA,UAAI,KAAK,EAAE,WAAW,QAAQ,UAAU,KAAK,CAAY;AAAA,IAC3D;AAAA,EACF;AAEA,SAAO;AACT;AAGA,SAAS,mBACP,UACA,KACA,SACA,WACA,QACA,YACA,cACA,MACA,SACM;AACN,QAAM;AAAA,IACJ,WAAW;AAAA,IACX,UAAU;AAAA,IACV,iBAAiB;AAAA,IACjB,QAAQ;AAAA;AAAA,EAEV,IAAIA,MAAK,GAAG;AACZ,QAAM,OAAO,SAAS,UAAU,OAAO;AACvC,QAAM,QAAQ,eAAe,MAAM,SAAS;AAE5C,MAAI,CAAC,QAAQ;AACX,QAAI,YAAY,eAAe,MAAM,KAAK,EAAG;AAC7C,WAAO,OAAO,MAAM,OAAO,CAAC,SAAS,CAAC;AAAA,EACxC;AAIA,SAAe,UAAU;AACzB,SAAe,YAAY;AAE3B,QAAM,eAAe,IAAI,SAAS,MAAM;AACxC,QAAM,aAAa,OAAO,IAAI,OAAO,IAAI,IAAI;AAC7C,MAAI,iBAAiB,eAAe,OAAQ,gBAAe,YAAY,IAAI,4BAAW;AAGtF,MAAI,YAAY,WAAW,MAAM,OAAO,cAAc,YAAY,cAAc,UAAU,GAAG;AAC3F;AAAA,EACF;AAEA,SAAO;AAAA,IACL;AAAA,IACA;AAAA,IACA,OACI,CAAC,WAAW,cAAc,YAAY,cAAc,UAAU,IAC9D,CAAC,WAAW,cAAc,YAAY,YAAY;AAAA,EACxD;AACF;AAEA,SAAS,OAAU,MAAkC;AAErD;AAEA,SAAS,SAAY,KAAY,OAAoB;AACnD,WAAS,IAAI,IAAI,QAAQ,KAAK,OAAO,KAAK;AACxC,QAAI,CAAC,IAAI,CAAC;AAAA,EACZ;AACA,SAAO,IAAI,KAAK;AAClB;AAEA,SAAS,eAAe,MAA0B,WAA2B;AAC3E,MAAI,QAAQ,KAAK;AACjB,WAAS,IAAI,QAAQ,GAAG,KAAK,GAAG,QAAQ,KAAK;AAC3C,UAAM,UAAU,KAAK,CAAC;AACtB,QAAI,aAAa,QAAQ,MAAM,EAAG;AAAA,EACpC;AACA,SAAO;AACT;AAEA,SAAS,OAAU,OAAY,OAAe,OAAU;AACtD,WAAS,IAAI,MAAM,QAAQ,IAAI,OAAO,KAAK;AACzC,UAAM,CAAC,IAAI,MAAM,IAAI,CAAC;AAAA,EACxB;AACA,QAAM,KAAK,IAAI;AACjB;AAEA,SAAS,sBAAsB,UAAgC;AAC7D,QAAM,EAAE,OAAO,IAAI;AACnB,MAAI,MAAM;AACV,WAAS,IAAI,MAAM,GAAG,KAAK,GAAG,MAAM,GAAG,KAAK;AAC1C,QAAI,SAAS,CAAC,EAAE,SAAS,EAAG;AAAA,EAC9B;AACA,MAAI,MAAM,OAAQ,UAAS,SAAS;AACtC;AAEA,SAAS,OAAkC,QAAqB,OAAY;AAC1E,WAAS,IAAI,GAAG,IAAI,MAAM,QAAQ,IAAK,KAAI,QAAQ,MAAM,CAAC,CAAC;AAC7D;AAEA,SAAS,eAAe,MAA0B,OAAwB;AAGxE,MAAI,UAAU,EAAG,QAAO;AAExB,QAAM,OAAO,KAAK,QAAQ,CAAC;AAI3B,SAAO,KAAK,WAAW;AACzB;AAEA,SAAS,WACP,MACA,OACA,cACA,YACA,cACA,YACS;AAET,MAAI,UAAU,EAAG,QAAO;AAExB,QAAM,OAAO,KAAK,QAAQ,CAAC;AAG3B,MAAI,KAAK,WAAW,EAAG,QAAO;AAI9B,SACE,iBAAiB,KAAK,aAAa,KACnC,eAAe,KAAK,WAAW,KAC/B,iBAAiB,KAAK,aAAa,KACnC,gBAAgB,KAAK,WAAW,IAAI,KAAK,WAAW,IAAI;AAE5D;AAEA,SAAS,mBACP,UACA,KACA,SAOA;AACA,QAAM,EAAE,WAAW,QAAQ,UAAU,MAAM,QAAQ,IAAI;AACvD,MAAI,CAAC,QAAQ;AACX,WAAO;AAAA,MACL;AAAA,MACA;AAAA,MACA,UAAU,OAAO;AAAA,MACjB,UAAU;AAAA,MACV;AAAA,MACA;AAAA,MACA;AAAA,MACA;AAAA,MACA;AAAA,IACF;AAAA,EACF;AACA,SAAY,QAAQ;AACpB,SAAO;AAAA,IACL;AAAA,IACA;AAAA,IACA,UAAU,OAAO;AAAA,IACjB,UAAU;AAAA,IACV;AAAA,IACA,SAAS,OAAO;AAAA,IAChB,SAAS;AAAA,IACT;AAAA,IACA;AAAA,EACF;AACF;", + "names": ["cast"] +} diff --git a/dg-ui/node_modules/@jridgewell/gen-mapping/dist/gen-mapping.umd.js b/dg-ui/node_modules/@jridgewell/gen-mapping/dist/gen-mapping.umd.js new file mode 100644 index 0000000..cb84af5 --- /dev/null +++ b/dg-ui/node_modules/@jridgewell/gen-mapping/dist/gen-mapping.umd.js @@ -0,0 +1,358 @@ +(function (global, factory) { + if (typeof exports === 'object' && typeof module !== 'undefined') { + factory(module, require('@jridgewell/sourcemap-codec'), require('@jridgewell/trace-mapping')); + module.exports = def(module); + } else if (typeof define === 'function' && define.amd) { + define(['module', '@jridgewell/sourcemap-codec', '@jridgewell/trace-mapping'], function(mod) { + factory.apply(this, arguments); + mod.exports = def(mod); + }); + } else { + const mod = { exports: {} }; + factory(mod, global.sourcemapCodec, global.traceMapping); + global = typeof globalThis !== 'undefined' ? globalThis : global || self; + global.genMapping = def(mod); + } + function def(m) { return 'default' in m.exports ? m.exports.default : m.exports; } +})(this, (function (module, require_sourcemapCodec, require_traceMapping) { +"use strict"; +var __create = Object.create; +var __defProp = Object.defineProperty; +var __getOwnPropDesc = Object.getOwnPropertyDescriptor; +var __getOwnPropNames = Object.getOwnPropertyNames; +var __getProtoOf = Object.getPrototypeOf; +var __hasOwnProp = Object.prototype.hasOwnProperty; +var __commonJS = (cb, mod) => function __require() { + return mod || (0, cb[__getOwnPropNames(cb)[0]])((mod = { exports: {} }).exports, mod), mod.exports; +}; +var __export = (target, all) => { + for (var name in all) + __defProp(target, name, { get: all[name], enumerable: true }); +}; +var __copyProps = (to, from, except, desc) => { + if (from && typeof from === "object" || typeof from === "function") { + for (let key of __getOwnPropNames(from)) + if (!__hasOwnProp.call(to, key) && key !== except) + __defProp(to, key, { get: () => from[key], enumerable: !(desc = __getOwnPropDesc(from, key)) || desc.enumerable }); + } + return to; +}; +var __toESM = (mod, isNodeMode, target) => (target = mod != null ? __create(__getProtoOf(mod)) : {}, __copyProps( + // If the importer is in node compatibility mode or this is not an ESM + // file that has been converted to a CommonJS file using a Babel- + // compatible transform (i.e. "__esModule" has not been set), then set + // "default" to the CommonJS "module.exports" for node compatibility. + isNodeMode || !mod || !mod.__esModule ? __defProp(target, "default", { value: mod, enumerable: true }) : target, + mod +)); +var __toCommonJS = (mod) => __copyProps(__defProp({}, "__esModule", { value: true }), mod); + +// umd:@jridgewell/sourcemap-codec +var require_sourcemap_codec = __commonJS({ + "umd:@jridgewell/sourcemap-codec"(exports, module2) { + module2.exports = require_sourcemapCodec; + } +}); + +// umd:@jridgewell/trace-mapping +var require_trace_mapping = __commonJS({ + "umd:@jridgewell/trace-mapping"(exports, module2) { + module2.exports = require_traceMapping; + } +}); + +// src/gen-mapping.ts +var gen_mapping_exports = {}; +__export(gen_mapping_exports, { + GenMapping: () => GenMapping, + addMapping: () => addMapping, + addSegment: () => addSegment, + allMappings: () => allMappings, + fromMap: () => fromMap, + maybeAddMapping: () => maybeAddMapping, + maybeAddSegment: () => maybeAddSegment, + setIgnore: () => setIgnore, + setSourceContent: () => setSourceContent, + toDecodedMap: () => toDecodedMap, + toEncodedMap: () => toEncodedMap +}); +module.exports = __toCommonJS(gen_mapping_exports); + +// src/set-array.ts +var SetArray = class { + constructor() { + this._indexes = { __proto__: null }; + this.array = []; + } +}; +function cast(set) { + return set; +} +function get(setarr, key) { + return cast(setarr)._indexes[key]; +} +function put(setarr, key) { + const index = get(setarr, key); + if (index !== void 0) return index; + const { array, _indexes: indexes } = cast(setarr); + const length = array.push(key); + return indexes[key] = length - 1; +} +function remove(setarr, key) { + const index = get(setarr, key); + if (index === void 0) return; + const { array, _indexes: indexes } = cast(setarr); + for (let i = index + 1; i < array.length; i++) { + const k = array[i]; + array[i - 1] = k; + indexes[k]--; + } + indexes[key] = void 0; + array.pop(); +} + +// src/gen-mapping.ts +var import_sourcemap_codec = __toESM(require_sourcemap_codec()); +var import_trace_mapping = __toESM(require_trace_mapping()); + +// src/sourcemap-segment.ts +var COLUMN = 0; +var SOURCES_INDEX = 1; +var SOURCE_LINE = 2; +var SOURCE_COLUMN = 3; +var NAMES_INDEX = 4; + +// src/gen-mapping.ts +var NO_NAME = -1; +var GenMapping = class { + constructor({ file, sourceRoot } = {}) { + this._names = new SetArray(); + this._sources = new SetArray(); + this._sourcesContent = []; + this._mappings = []; + this.file = file; + this.sourceRoot = sourceRoot; + this._ignoreList = new SetArray(); + } +}; +function cast2(map) { + return map; +} +function addSegment(map, genLine, genColumn, source, sourceLine, sourceColumn, name, content) { + return addSegmentInternal( + false, + map, + genLine, + genColumn, + source, + sourceLine, + sourceColumn, + name, + content + ); +} +function addMapping(map, mapping) { + return addMappingInternal(false, map, mapping); +} +var maybeAddSegment = (map, genLine, genColumn, source, sourceLine, sourceColumn, name, content) => { + return addSegmentInternal( + true, + map, + genLine, + genColumn, + source, + sourceLine, + sourceColumn, + name, + content + ); +}; +var maybeAddMapping = (map, mapping) => { + return addMappingInternal(true, map, mapping); +}; +function setSourceContent(map, source, content) { + const { + _sources: sources, + _sourcesContent: sourcesContent + // _originalScopes: originalScopes, + } = cast2(map); + const index = put(sources, source); + sourcesContent[index] = content; +} +function setIgnore(map, source, ignore = true) { + const { + _sources: sources, + _sourcesContent: sourcesContent, + _ignoreList: ignoreList + // _originalScopes: originalScopes, + } = cast2(map); + const index = put(sources, source); + if (index === sourcesContent.length) sourcesContent[index] = null; + if (ignore) put(ignoreList, index); + else remove(ignoreList, index); +} +function toDecodedMap(map) { + const { + _mappings: mappings, + _sources: sources, + _sourcesContent: sourcesContent, + _names: names, + _ignoreList: ignoreList + // _originalScopes: originalScopes, + // _generatedRanges: generatedRanges, + } = cast2(map); + removeEmptyFinalLines(mappings); + return { + version: 3, + file: map.file || void 0, + names: names.array, + sourceRoot: map.sourceRoot || void 0, + sources: sources.array, + sourcesContent, + mappings, + // originalScopes, + // generatedRanges, + ignoreList: ignoreList.array + }; +} +function toEncodedMap(map) { + const decoded = toDecodedMap(map); + return Object.assign({}, decoded, { + // originalScopes: decoded.originalScopes.map((os) => encodeOriginalScopes(os)), + // generatedRanges: encodeGeneratedRanges(decoded.generatedRanges as GeneratedRange[]), + mappings: (0, import_sourcemap_codec.encode)(decoded.mappings) + }); +} +function fromMap(input) { + const map = new import_trace_mapping.TraceMap(input); + const gen = new GenMapping({ file: map.file, sourceRoot: map.sourceRoot }); + putAll(cast2(gen)._names, map.names); + putAll(cast2(gen)._sources, map.sources); + cast2(gen)._sourcesContent = map.sourcesContent || map.sources.map(() => null); + cast2(gen)._mappings = (0, import_trace_mapping.decodedMappings)(map); + if (map.ignoreList) putAll(cast2(gen)._ignoreList, map.ignoreList); + return gen; +} +function allMappings(map) { + const out = []; + const { _mappings: mappings, _sources: sources, _names: names } = cast2(map); + for (let i = 0; i < mappings.length; i++) { + const line = mappings[i]; + for (let j = 0; j < line.length; j++) { + const seg = line[j]; + const generated = { line: i + 1, column: seg[COLUMN] }; + let source = void 0; + let original = void 0; + let name = void 0; + if (seg.length !== 1) { + source = sources.array[seg[SOURCES_INDEX]]; + original = { line: seg[SOURCE_LINE] + 1, column: seg[SOURCE_COLUMN] }; + if (seg.length === 5) name = names.array[seg[NAMES_INDEX]]; + } + out.push({ generated, source, original, name }); + } + } + return out; +} +function addSegmentInternal(skipable, map, genLine, genColumn, source, sourceLine, sourceColumn, name, content) { + const { + _mappings: mappings, + _sources: sources, + _sourcesContent: sourcesContent, + _names: names + // _originalScopes: originalScopes, + } = cast2(map); + const line = getIndex(mappings, genLine); + const index = getColumnIndex(line, genColumn); + if (!source) { + if (skipable && skipSourceless(line, index)) return; + return insert(line, index, [genColumn]); + } + assert(sourceLine); + assert(sourceColumn); + const sourcesIndex = put(sources, source); + const namesIndex = name ? put(names, name) : NO_NAME; + if (sourcesIndex === sourcesContent.length) sourcesContent[sourcesIndex] = content != null ? content : null; + if (skipable && skipSource(line, index, sourcesIndex, sourceLine, sourceColumn, namesIndex)) { + return; + } + return insert( + line, + index, + name ? [genColumn, sourcesIndex, sourceLine, sourceColumn, namesIndex] : [genColumn, sourcesIndex, sourceLine, sourceColumn] + ); +} +function assert(_val) { +} +function getIndex(arr, index) { + for (let i = arr.length; i <= index; i++) { + arr[i] = []; + } + return arr[index]; +} +function getColumnIndex(line, genColumn) { + let index = line.length; + for (let i = index - 1; i >= 0; index = i--) { + const current = line[i]; + if (genColumn >= current[COLUMN]) break; + } + return index; +} +function insert(array, index, value) { + for (let i = array.length; i > index; i--) { + array[i] = array[i - 1]; + } + array[index] = value; +} +function removeEmptyFinalLines(mappings) { + const { length } = mappings; + let len = length; + for (let i = len - 1; i >= 0; len = i, i--) { + if (mappings[i].length > 0) break; + } + if (len < length) mappings.length = len; +} +function putAll(setarr, array) { + for (let i = 0; i < array.length; i++) put(setarr, array[i]); +} +function skipSourceless(line, index) { + if (index === 0) return true; + const prev = line[index - 1]; + return prev.length === 1; +} +function skipSource(line, index, sourcesIndex, sourceLine, sourceColumn, namesIndex) { + if (index === 0) return false; + const prev = line[index - 1]; + if (prev.length === 1) return false; + return sourcesIndex === prev[SOURCES_INDEX] && sourceLine === prev[SOURCE_LINE] && sourceColumn === prev[SOURCE_COLUMN] && namesIndex === (prev.length === 5 ? prev[NAMES_INDEX] : NO_NAME); +} +function addMappingInternal(skipable, map, mapping) { + const { generated, source, original, name, content } = mapping; + if (!source) { + return addSegmentInternal( + skipable, + map, + generated.line - 1, + generated.column, + null, + null, + null, + null, + null + ); + } + assert(original); + return addSegmentInternal( + skipable, + map, + generated.line - 1, + generated.column, + source, + original.line - 1, + original.column, + name, + content + ); +} +})); +//# sourceMappingURL=gen-mapping.umd.js.map diff --git a/dg-ui/node_modules/@jridgewell/gen-mapping/dist/gen-mapping.umd.js.map b/dg-ui/node_modules/@jridgewell/gen-mapping/dist/gen-mapping.umd.js.map new file mode 100644 index 0000000..b13750b --- /dev/null +++ b/dg-ui/node_modules/@jridgewell/gen-mapping/dist/gen-mapping.umd.js.map @@ -0,0 +1,6 @@ +{ + "version": 3, + "sources": ["umd:@jridgewell/sourcemap-codec", "umd:@jridgewell/trace-mapping", "../src/gen-mapping.ts", "../src/set-array.ts", "../src/sourcemap-segment.ts"], + "mappings": ";;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;AAAA;AAAA,6CAAAA,SAAA;AAAA,IAAAA,QAAO,UAAU;AAAA;AAAA;;;ACAjB;AAAA,2CAAAC,SAAA;AAAA,IAAAA,QAAO,UAAU;AAAA;AAAA;;;ACAjB;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;;;ACUO,IAAM,WAAN,MAAoC;AAAA,EAIzC,cAAc;AACZ,SAAK,WAAW,EAAE,WAAW,KAAK;AAClC,SAAK,QAAQ,CAAC;AAAA,EAChB;AACF;AAWA,SAAS,KAAoB,KAAgC;AAC3D,SAAO;AACT;AAKO,SAAS,IAAmB,QAAqB,KAA4B;AAClF,SAAO,KAAK,MAAM,EAAE,SAAS,GAAG;AAClC;AAMO,SAAS,IAAmB,QAAqB,KAAgB;AAEtE,QAAM,QAAQ,IAAI,QAAQ,GAAG;AAC7B,MAAI,UAAU,OAAW,QAAO;AAEhC,QAAM,EAAE,OAAO,UAAU,QAAQ,IAAI,KAAK,MAAM;AAEhD,QAAM,SAAS,MAAM,KAAK,GAAG;AAC7B,SAAQ,QAAQ,GAAG,IAAI,SAAS;AAClC;AAgBO,SAAS,OAAsB,QAAqB,KAAc;AACvE,QAAM,QAAQ,IAAI,QAAQ,GAAG;AAC7B,MAAI,UAAU,OAAW;AAEzB,QAAM,EAAE,OAAO,UAAU,QAAQ,IAAI,KAAK,MAAM;AAChD,WAAS,IAAI,QAAQ,GAAG,IAAI,MAAM,QAAQ,KAAK;AAC7C,UAAM,IAAI,MAAM,CAAC;AACjB,UAAM,IAAI,CAAC,IAAI;AACf,YAAQ,CAAC;AAAA,EACX;AACA,UAAQ,GAAG,IAAI;AACf,QAAM,IAAI;AACZ;;;ADhFA,6BAIO;AACP,2BAA0C;;;AEKnC,IAAM,SAAS;AACf,IAAM,gBAAgB;AACtB,IAAM,cAAc;AACpB,IAAM,gBAAgB;AACtB,IAAM,cAAc;;;AFsB3B,IAAM,UAAU;AAKT,IAAM,aAAN,MAAiB;AAAA,EAWtB,YAAY,EAAE,MAAM,WAAW,IAAa,CAAC,GAAG;AAC9C,SAAK,SAAS,IAAI,SAAS;AAC3B,SAAK,WAAW,IAAI,SAAS;AAC7B,SAAK,kBAAkB,CAAC;AACxB,SAAK,YAAY,CAAC;AAGlB,SAAK,OAAO;AACZ,SAAK,aAAa;AAClB,SAAK,cAAc,IAAI,SAAS;AAAA,EAClC;AACF;AAgBA,SAASC,MAAK,KAAyB;AACrC,SAAO;AACT;AAoCO,SAAS,WACd,KACA,SACA,WACA,QACA,YACA,cACA,MACA,SACM;AACN,SAAO;AAAA,IACL;AAAA,IACA;AAAA,IACA;AAAA,IACA;AAAA,IACA;AAAA,IACA;AAAA,IACA;AAAA,IACA;AAAA,IACA;AAAA,EACF;AACF;AAoCO,SAAS,WACd,KACA,SAOM;AACN,SAAO,mBAAmB,OAAO,KAAK,OAAmD;AAC3F;AAOO,IAAM,kBAAqC,CAChD,KACA,SACA,WACA,QACA,YACA,cACA,MACA,YACG;AACH,SAAO;AAAA,IACL;AAAA,IACA;AAAA,IACA;AAAA,IACA;AAAA,IACA;AAAA,IACA;AAAA,IACA;AAAA,IACA;AAAA,IACA;AAAA,EACF;AACF;AAOO,IAAM,kBAAqC,CAAC,KAAK,YAAY;AAClE,SAAO,mBAAmB,MAAM,KAAK,OAAmD;AAC1F;AAKO,SAAS,iBAAiB,KAAiB,QAAgB,SAA8B;AAC9F,QAAM;AAAA,IACJ,UAAU;AAAA,IACV,iBAAiB;AAAA;AAAA,EAEnB,IAAIA,MAAK,GAAG;AACZ,QAAM,QAAQ,IAAI,SAAS,MAAM;AACjC,iBAAe,KAAK,IAAI;AAE1B;AAEO,SAAS,UAAU,KAAiB,QAAgB,SAAS,MAAM;AACxE,QAAM;AAAA,IACJ,UAAU;AAAA,IACV,iBAAiB;AAAA,IACjB,aAAa;AAAA;AAAA,EAEf,IAAIA,MAAK,GAAG;AACZ,QAAM,QAAQ,IAAI,SAAS,MAAM;AACjC,MAAI,UAAU,eAAe,OAAQ,gBAAe,KAAK,IAAI;AAE7D,MAAI,OAAQ,KAAI,YAAY,KAAK;AAAA,MAC5B,QAAO,YAAY,KAAK;AAC/B;AAMO,SAAS,aAAa,KAAmC;AAC9D,QAAM;AAAA,IACJ,WAAW;AAAA,IACX,UAAU;AAAA,IACV,iBAAiB;AAAA,IACjB,QAAQ;AAAA,IACR,aAAa;AAAA;AAAA;AAAA,EAGf,IAAIA,MAAK,GAAG;AACZ,wBAAsB,QAAQ;AAE9B,SAAO;AAAA,IACL,SAAS;AAAA,IACT,MAAM,IAAI,QAAQ;AAAA,IAClB,OAAO,MAAM;AAAA,IACb,YAAY,IAAI,cAAc;AAAA,IAC9B,SAAS,QAAQ;AAAA,IACjB;AAAA,IACA;AAAA;AAAA;AAAA,IAGA,YAAY,WAAW;AAAA,EACzB;AACF;AAMO,SAAS,aAAa,KAAmC;AAC9D,QAAM,UAAU,aAAa,GAAG;AAChC,SAAO,OAAO,OAAO,CAAC,GAAG,SAAS;AAAA;AAAA;AAAA,IAGhC,cAAU,+BAAO,QAAQ,QAAgC;AAAA,EAC3D,CAAC;AACH;AAKO,SAAS,QAAQ,OAAmC;AACzD,QAAM,MAAM,IAAI,8BAAS,KAAK;AAC9B,QAAM,MAAM,IAAI,WAAW,EAAE,MAAM,IAAI,MAAM,YAAY,IAAI,WAAW,CAAC;AAEzE,SAAOA,MAAK,GAAG,EAAE,QAAQ,IAAI,KAAK;AAClC,SAAOA,MAAK,GAAG,EAAE,UAAU,IAAI,OAAmB;AAClD,EAAAA,MAAK,GAAG,EAAE,kBAAkB,IAAI,kBAAkB,IAAI,QAAQ,IAAI,MAAM,IAAI;AAC5E,EAAAA,MAAK,GAAG,EAAE,gBAAY,sCAAgB,GAAG;AAEzC,MAAI,IAAI,WAAY,QAAOA,MAAK,GAAG,EAAE,aAAa,IAAI,UAAU;AAEhE,SAAO;AACT;AAMO,SAAS,YAAY,KAA4B;AACtD,QAAM,MAAiB,CAAC;AACxB,QAAM,EAAE,WAAW,UAAU,UAAU,SAAS,QAAQ,MAAM,IAAIA,MAAK,GAAG;AAE1E,WAAS,IAAI,GAAG,IAAI,SAAS,QAAQ,KAAK;AACxC,UAAM,OAAO,SAAS,CAAC;AACvB,aAAS,IAAI,GAAG,IAAI,KAAK,QAAQ,KAAK;AACpC,YAAM,MAAM,KAAK,CAAC;AAElB,YAAM,YAAY,EAAE,MAAM,IAAI,GAAG,QAAQ,IAAI,MAAM,EAAE;AACrD,UAAI,SAA6B;AACjC,UAAI,WAA4B;AAChC,UAAI,OAA2B;AAE/B,UAAI,IAAI,WAAW,GAAG;AACpB,iBAAS,QAAQ,MAAM,IAAI,aAAa,CAAC;AACzC,mBAAW,EAAE,MAAM,IAAI,WAAW,IAAI,GAAG,QAAQ,IAAI,aAAa,EAAE;AAEpE,YAAI,IAAI,WAAW,EAAG,QAAO,MAAM,MAAM,IAAI,WAAW,CAAC;AAAA,MAC3D;AAEA,UAAI,KAAK,EAAE,WAAW,QAAQ,UAAU,KAAK,CAAY;AAAA,IAC3D;AAAA,EACF;AAEA,SAAO;AACT;AAGA,SAAS,mBACP,UACA,KACA,SACA,WACA,QACA,YACA,cACA,MACA,SACM;AACN,QAAM;AAAA,IACJ,WAAW;AAAA,IACX,UAAU;AAAA,IACV,iBAAiB;AAAA,IACjB,QAAQ;AAAA;AAAA,EAEV,IAAIA,MAAK,GAAG;AACZ,QAAM,OAAO,SAAS,UAAU,OAAO;AACvC,QAAM,QAAQ,eAAe,MAAM,SAAS;AAE5C,MAAI,CAAC,QAAQ;AACX,QAAI,YAAY,eAAe,MAAM,KAAK,EAAG;AAC7C,WAAO,OAAO,MAAM,OAAO,CAAC,SAAS,CAAC;AAAA,EACxC;AAIA,SAAe,UAAU;AACzB,SAAe,YAAY;AAE3B,QAAM,eAAe,IAAI,SAAS,MAAM;AACxC,QAAM,aAAa,OAAO,IAAI,OAAO,IAAI,IAAI;AAC7C,MAAI,iBAAiB,eAAe,OAAQ,gBAAe,YAAY,IAAI,4BAAW;AAGtF,MAAI,YAAY,WAAW,MAAM,OAAO,cAAc,YAAY,cAAc,UAAU,GAAG;AAC3F;AAAA,EACF;AAEA,SAAO;AAAA,IACL;AAAA,IACA;AAAA,IACA,OACI,CAAC,WAAW,cAAc,YAAY,cAAc,UAAU,IAC9D,CAAC,WAAW,cAAc,YAAY,YAAY;AAAA,EACxD;AACF;AAEA,SAAS,OAAU,MAAkC;AAErD;AAEA,SAAS,SAAY,KAAY,OAAoB;AACnD,WAAS,IAAI,IAAI,QAAQ,KAAK,OAAO,KAAK;AACxC,QAAI,CAAC,IAAI,CAAC;AAAA,EACZ;AACA,SAAO,IAAI,KAAK;AAClB;AAEA,SAAS,eAAe,MAA0B,WAA2B;AAC3E,MAAI,QAAQ,KAAK;AACjB,WAAS,IAAI,QAAQ,GAAG,KAAK,GAAG,QAAQ,KAAK;AAC3C,UAAM,UAAU,KAAK,CAAC;AACtB,QAAI,aAAa,QAAQ,MAAM,EAAG;AAAA,EACpC;AACA,SAAO;AACT;AAEA,SAAS,OAAU,OAAY,OAAe,OAAU;AACtD,WAAS,IAAI,MAAM,QAAQ,IAAI,OAAO,KAAK;AACzC,UAAM,CAAC,IAAI,MAAM,IAAI,CAAC;AAAA,EACxB;AACA,QAAM,KAAK,IAAI;AACjB;AAEA,SAAS,sBAAsB,UAAgC;AAC7D,QAAM,EAAE,OAAO,IAAI;AACnB,MAAI,MAAM;AACV,WAAS,IAAI,MAAM,GAAG,KAAK,GAAG,MAAM,GAAG,KAAK;AAC1C,QAAI,SAAS,CAAC,EAAE,SAAS,EAAG;AAAA,EAC9B;AACA,MAAI,MAAM,OAAQ,UAAS,SAAS;AACtC;AAEA,SAAS,OAAkC,QAAqB,OAAY;AAC1E,WAAS,IAAI,GAAG,IAAI,MAAM,QAAQ,IAAK,KAAI,QAAQ,MAAM,CAAC,CAAC;AAC7D;AAEA,SAAS,eAAe,MAA0B,OAAwB;AAGxE,MAAI,UAAU,EAAG,QAAO;AAExB,QAAM,OAAO,KAAK,QAAQ,CAAC;AAI3B,SAAO,KAAK,WAAW;AACzB;AAEA,SAAS,WACP,MACA,OACA,cACA,YACA,cACA,YACS;AAET,MAAI,UAAU,EAAG,QAAO;AAExB,QAAM,OAAO,KAAK,QAAQ,CAAC;AAG3B,MAAI,KAAK,WAAW,EAAG,QAAO;AAI9B,SACE,iBAAiB,KAAK,aAAa,KACnC,eAAe,KAAK,WAAW,KAC/B,iBAAiB,KAAK,aAAa,KACnC,gBAAgB,KAAK,WAAW,IAAI,KAAK,WAAW,IAAI;AAE5D;AAEA,SAAS,mBACP,UACA,KACA,SAOA;AACA,QAAM,EAAE,WAAW,QAAQ,UAAU,MAAM,QAAQ,IAAI;AACvD,MAAI,CAAC,QAAQ;AACX,WAAO;AAAA,MACL;AAAA,MACA;AAAA,MACA,UAAU,OAAO;AAAA,MACjB,UAAU;AAAA,MACV;AAAA,MACA;AAAA,MACA;AAAA,MACA;AAAA,MACA;AAAA,IACF;AAAA,EACF;AACA,SAAY,QAAQ;AACpB,SAAO;AAAA,IACL;AAAA,IACA;AAAA,IACA,UAAU,OAAO;AAAA,IACjB,UAAU;AAAA,IACV;AAAA,IACA,SAAS,OAAO;AAAA,IAChB,SAAS;AAAA,IACT;AAAA,IACA;AAAA,EACF;AACF;", + "names": ["module", "module", "cast"] +} diff --git a/dg-ui/node_modules/@jridgewell/gen-mapping/dist/types/gen-mapping.d.ts b/dg-ui/node_modules/@jridgewell/gen-mapping/dist/types/gen-mapping.d.ts new file mode 100644 index 0000000..9ba936e --- /dev/null +++ b/dg-ui/node_modules/@jridgewell/gen-mapping/dist/types/gen-mapping.d.ts @@ -0,0 +1,88 @@ +import type { SourceMapInput } from '@jridgewell/trace-mapping'; +import type { DecodedSourceMap, EncodedSourceMap, Pos, Mapping } from './types'; +export type { DecodedSourceMap, EncodedSourceMap, Mapping }; +export type Options = { + file?: string | null; + sourceRoot?: string | null; +}; +/** + * Provides the state to generate a sourcemap. + */ +export declare class GenMapping { + private _names; + private _sources; + private _sourcesContent; + private _mappings; + private _ignoreList; + file: string | null | undefined; + sourceRoot: string | null | undefined; + constructor({ file, sourceRoot }?: Options); +} +/** + * A low-level API to associate a generated position with an original source position. Line and + * column here are 0-based, unlike `addMapping`. + */ +export declare function addSegment(map: GenMapping, genLine: number, genColumn: number, source?: null, sourceLine?: null, sourceColumn?: null, name?: null, content?: null): void; +export declare function addSegment(map: GenMapping, genLine: number, genColumn: number, source: string, sourceLine: number, sourceColumn: number, name?: null, content?: string | null): void; +export declare function addSegment(map: GenMapping, genLine: number, genColumn: number, source: string, sourceLine: number, sourceColumn: number, name: string, content?: string | null): void; +/** + * A high-level API to associate a generated position with an original source position. Line is + * 1-based, but column is 0-based, due to legacy behavior in `source-map` library. + */ +export declare function addMapping(map: GenMapping, mapping: { + generated: Pos; + source?: null; + original?: null; + name?: null; + content?: null; +}): void; +export declare function addMapping(map: GenMapping, mapping: { + generated: Pos; + source: string; + original: Pos; + name?: null; + content?: string | null; +}): void; +export declare function addMapping(map: GenMapping, mapping: { + generated: Pos; + source: string; + original: Pos; + name: string; + content?: string | null; +}): void; +/** + * Same as `addSegment`, but will only add the segment if it generates useful information in the + * resulting map. This only works correctly if segments are added **in order**, meaning you should + * not add a segment with a lower generated line/column than one that came before. + */ +export declare const maybeAddSegment: typeof addSegment; +/** + * Same as `addMapping`, but will only add the mapping if it generates useful information in the + * resulting map. This only works correctly if mappings are added **in order**, meaning you should + * not add a mapping with a lower generated line/column than one that came before. + */ +export declare const maybeAddMapping: typeof addMapping; +/** + * Adds/removes the content of the source file to the source map. + */ +export declare function setSourceContent(map: GenMapping, source: string, content: string | null): void; +export declare function setIgnore(map: GenMapping, source: string, ignore?: boolean): void; +/** + * Returns a sourcemap object (with decoded mappings) suitable for passing to a library that expects + * a sourcemap, or to JSON.stringify. + */ +export declare function toDecodedMap(map: GenMapping): DecodedSourceMap; +/** + * Returns a sourcemap object (with encoded mappings) suitable for passing to a library that expects + * a sourcemap, or to JSON.stringify. + */ +export declare function toEncodedMap(map: GenMapping): EncodedSourceMap; +/** + * Constructs a new GenMapping, using the already present mappings of the input. + */ +export declare function fromMap(input: SourceMapInput): GenMapping; +/** + * Returns an array of high-level mapping objects for every recorded segment, which could then be + * passed to the `source-map` library. + */ +export declare function allMappings(map: GenMapping): Mapping[]; diff --git a/dg-ui/node_modules/@jridgewell/gen-mapping/dist/types/set-array.d.ts b/dg-ui/node_modules/@jridgewell/gen-mapping/dist/types/set-array.d.ts new file mode 100644 index 0000000..6ed4354 --- /dev/null +++ b/dg-ui/node_modules/@jridgewell/gen-mapping/dist/types/set-array.d.ts @@ -0,0 +1,32 @@ +type Key = string | number | symbol; +/** + * SetArray acts like a `Set` (allowing only one occurrence of a string `key`), but provides the + * index of the `key` in the backing array. + * + * This is designed to allow synchronizing a second array with the contents of the backing array, + * like how in a sourcemap `sourcesContent[i]` is the source content associated with `source[i]`, + * and there are never duplicates. + */ +export declare class SetArray { + private _indexes; + array: readonly T[]; + constructor(); +} +/** + * Gets the index associated with `key` in the backing array, if it is already present. + */ +export declare function get(setarr: SetArray, key: T): number | undefined; +/** + * Puts `key` into the backing array, if it is not already present. Returns + * the index of the `key` in the backing array. + */ +export declare function put(setarr: SetArray, key: T): number; +/** + * Pops the last added item out of the SetArray. + */ +export declare function pop(setarr: SetArray): void; +/** + * Removes the key, if it exists in the set. + */ +export declare function remove(setarr: SetArray, key: T): void; +export {}; diff --git a/dg-ui/node_modules/@jridgewell/gen-mapping/dist/types/sourcemap-segment.d.ts b/dg-ui/node_modules/@jridgewell/gen-mapping/dist/types/sourcemap-segment.d.ts new file mode 100644 index 0000000..aa19fb5 --- /dev/null +++ b/dg-ui/node_modules/@jridgewell/gen-mapping/dist/types/sourcemap-segment.d.ts @@ -0,0 +1,12 @@ +type GeneratedColumn = number; +type SourcesIndex = number; +type SourceLine = number; +type SourceColumn = number; +type NamesIndex = number; +export type SourceMapSegment = [GeneratedColumn] | [GeneratedColumn, SourcesIndex, SourceLine, SourceColumn] | [GeneratedColumn, SourcesIndex, SourceLine, SourceColumn, NamesIndex]; +export declare const COLUMN = 0; +export declare const SOURCES_INDEX = 1; +export declare const SOURCE_LINE = 2; +export declare const SOURCE_COLUMN = 3; +export declare const NAMES_INDEX = 4; +export {}; diff --git a/dg-ui/node_modules/@jridgewell/gen-mapping/dist/types/types.d.ts b/dg-ui/node_modules/@jridgewell/gen-mapping/dist/types/types.d.ts new file mode 100644 index 0000000..8eb90fb --- /dev/null +++ b/dg-ui/node_modules/@jridgewell/gen-mapping/dist/types/types.d.ts @@ -0,0 +1,43 @@ +import type { SourceMapSegment } from './sourcemap-segment'; +export interface SourceMapV3 { + file?: string | null; + names: readonly string[]; + sourceRoot?: string; + sources: readonly (string | null)[]; + sourcesContent?: readonly (string | null)[]; + version: 3; + ignoreList?: readonly number[]; +} +export interface EncodedSourceMap extends SourceMapV3 { + mappings: string; +} +export interface DecodedSourceMap extends SourceMapV3 { + mappings: readonly SourceMapSegment[][]; +} +export interface Pos { + line: number; + column: number; +} +export interface OriginalPos extends Pos { + source: string; +} +export interface BindingExpressionRange { + start: Pos; + expression: string; +} +export type Mapping = { + generated: Pos; + source: undefined; + original: undefined; + name: undefined; +} | { + generated: Pos; + source: string; + original: Pos; + name: string; +} | { + generated: Pos; + source: string; + original: Pos; + name: undefined; +}; diff --git a/dg-ui/node_modules/@jridgewell/gen-mapping/package.json b/dg-ui/node_modules/@jridgewell/gen-mapping/package.json new file mode 100644 index 0000000..036f9b7 --- /dev/null +++ b/dg-ui/node_modules/@jridgewell/gen-mapping/package.json @@ -0,0 +1,67 @@ +{ + "name": "@jridgewell/gen-mapping", + "version": "0.3.13", + "description": "Generate source maps", + "keywords": [ + "source", + "map" + ], + "main": "dist/gen-mapping.umd.js", + "module": "dist/gen-mapping.mjs", + "types": "types/gen-mapping.d.cts", + "files": [ + "dist", + "src", + "types" + ], + "exports": { + ".": [ + { + "import": { + "types": "./types/gen-mapping.d.mts", + "default": "./dist/gen-mapping.mjs" + }, + "default": { + "types": "./types/gen-mapping.d.cts", + "default": "./dist/gen-mapping.umd.js" + } + }, + "./dist/gen-mapping.umd.js" + ], + "./package.json": "./package.json" + }, + "scripts": { + "benchmark": "run-s build:code benchmark:*", + "benchmark:install": "cd benchmark && npm install", + "benchmark:only": "node --expose-gc benchmark/index.js", + "build": "run-s -n build:code build:types", + "build:code": "node ../../esbuild.mjs gen-mapping.ts", + "build:types": "run-s build:types:force build:types:emit build:types:mts", + "build:types:force": "rimraf tsconfig.build.tsbuildinfo", + "build:types:emit": "tsc --project tsconfig.build.json", + "build:types:mts": "node ../../mts-types.mjs", + "clean": "run-s -n clean:code clean:types", + "clean:code": "tsc --build --clean tsconfig.build.json", + "clean:types": "rimraf dist types", + "test": "run-s -n test:types test:only test:format", + "test:format": "prettier --check '{src,test}/**/*.ts'", + "test:only": "mocha", + "test:types": "eslint '{src,test}/**/*.ts'", + "lint": "run-s -n lint:types lint:format", + "lint:format": "npm run test:format -- --write", + "lint:types": "npm run test:types -- --fix", + "prepublishOnly": "npm run-s -n build test" + }, + "homepage": "https://github.com/jridgewell/sourcemaps/tree/main/packages/gen-mapping", + "repository": { + "type": "git", + "url": "git+https://github.com/jridgewell/sourcemaps.git", + "directory": "packages/gen-mapping" + }, + "author": "Justin Ridgewell ", + "license": "MIT", + "dependencies": { + "@jridgewell/sourcemap-codec": "^1.5.0", + "@jridgewell/trace-mapping": "^0.3.24" + } +} diff --git a/dg-ui/node_modules/@jridgewell/gen-mapping/src/gen-mapping.ts b/dg-ui/node_modules/@jridgewell/gen-mapping/src/gen-mapping.ts new file mode 100644 index 0000000..ecc878c --- /dev/null +++ b/dg-ui/node_modules/@jridgewell/gen-mapping/src/gen-mapping.ts @@ -0,0 +1,614 @@ +import { SetArray, put, remove } from './set-array'; +import { + encode, + // encodeGeneratedRanges, + // encodeOriginalScopes +} from '@jridgewell/sourcemap-codec'; +import { TraceMap, decodedMappings } from '@jridgewell/trace-mapping'; + +import { + COLUMN, + SOURCES_INDEX, + SOURCE_LINE, + SOURCE_COLUMN, + NAMES_INDEX, +} from './sourcemap-segment'; + +import type { SourceMapInput } from '@jridgewell/trace-mapping'; +// import type { OriginalScope, GeneratedRange } from '@jridgewell/sourcemap-codec'; +import type { SourceMapSegment } from './sourcemap-segment'; +import type { + DecodedSourceMap, + EncodedSourceMap, + Pos, + Mapping, + // BindingExpressionRange, + // OriginalPos, + // OriginalScopeInfo, + // GeneratedRangeInfo, +} from './types'; + +export type { DecodedSourceMap, EncodedSourceMap, Mapping }; + +export type Options = { + file?: string | null; + sourceRoot?: string | null; +}; + +const NO_NAME = -1; + +/** + * Provides the state to generate a sourcemap. + */ +export class GenMapping { + declare private _names: SetArray; + declare private _sources: SetArray; + declare private _sourcesContent: (string | null)[]; + declare private _mappings: SourceMapSegment[][]; + // private declare _originalScopes: OriginalScope[][]; + // private declare _generatedRanges: GeneratedRange[]; + declare private _ignoreList: SetArray; + declare file: string | null | undefined; + declare sourceRoot: string | null | undefined; + + constructor({ file, sourceRoot }: Options = {}) { + this._names = new SetArray(); + this._sources = new SetArray(); + this._sourcesContent = []; + this._mappings = []; + // this._originalScopes = []; + // this._generatedRanges = []; + this.file = file; + this.sourceRoot = sourceRoot; + this._ignoreList = new SetArray(); + } +} + +interface PublicMap { + _names: GenMapping['_names']; + _sources: GenMapping['_sources']; + _sourcesContent: GenMapping['_sourcesContent']; + _mappings: GenMapping['_mappings']; + // _originalScopes: GenMapping['_originalScopes']; + // _generatedRanges: GenMapping['_generatedRanges']; + _ignoreList: GenMapping['_ignoreList']; +} + +/** + * Typescript doesn't allow friend access to private fields, so this just casts the map into a type + * with public access modifiers. + */ +function cast(map: unknown): PublicMap { + return map as any; +} + +/** + * A low-level API to associate a generated position with an original source position. Line and + * column here are 0-based, unlike `addMapping`. + */ +export function addSegment( + map: GenMapping, + genLine: number, + genColumn: number, + source?: null, + sourceLine?: null, + sourceColumn?: null, + name?: null, + content?: null, +): void; +export function addSegment( + map: GenMapping, + genLine: number, + genColumn: number, + source: string, + sourceLine: number, + sourceColumn: number, + name?: null, + content?: string | null, +): void; +export function addSegment( + map: GenMapping, + genLine: number, + genColumn: number, + source: string, + sourceLine: number, + sourceColumn: number, + name: string, + content?: string | null, +): void; +export function addSegment( + map: GenMapping, + genLine: number, + genColumn: number, + source?: string | null, + sourceLine?: number | null, + sourceColumn?: number | null, + name?: string | null, + content?: string | null, +): void { + return addSegmentInternal( + false, + map, + genLine, + genColumn, + source, + sourceLine, + sourceColumn, + name, + content, + ); +} + +/** + * A high-level API to associate a generated position with an original source position. Line is + * 1-based, but column is 0-based, due to legacy behavior in `source-map` library. + */ +export function addMapping( + map: GenMapping, + mapping: { + generated: Pos; + source?: null; + original?: null; + name?: null; + content?: null; + }, +): void; +export function addMapping( + map: GenMapping, + mapping: { + generated: Pos; + source: string; + original: Pos; + name?: null; + content?: string | null; + }, +): void; +export function addMapping( + map: GenMapping, + mapping: { + generated: Pos; + source: string; + original: Pos; + name: string; + content?: string | null; + }, +): void; +export function addMapping( + map: GenMapping, + mapping: { + generated: Pos; + source?: string | null; + original?: Pos | null; + name?: string | null; + content?: string | null; + }, +): void { + return addMappingInternal(false, map, mapping as Parameters[2]); +} + +/** + * Same as `addSegment`, but will only add the segment if it generates useful information in the + * resulting map. This only works correctly if segments are added **in order**, meaning you should + * not add a segment with a lower generated line/column than one that came before. + */ +export const maybeAddSegment: typeof addSegment = ( + map, + genLine, + genColumn, + source, + sourceLine, + sourceColumn, + name, + content, +) => { + return addSegmentInternal( + true, + map, + genLine, + genColumn, + source, + sourceLine, + sourceColumn, + name, + content, + ); +}; + +/** + * Same as `addMapping`, but will only add the mapping if it generates useful information in the + * resulting map. This only works correctly if mappings are added **in order**, meaning you should + * not add a mapping with a lower generated line/column than one that came before. + */ +export const maybeAddMapping: typeof addMapping = (map, mapping) => { + return addMappingInternal(true, map, mapping as Parameters[2]); +}; + +/** + * Adds/removes the content of the source file to the source map. + */ +export function setSourceContent(map: GenMapping, source: string, content: string | null): void { + const { + _sources: sources, + _sourcesContent: sourcesContent, + // _originalScopes: originalScopes, + } = cast(map); + const index = put(sources, source); + sourcesContent[index] = content; + // if (index === originalScopes.length) originalScopes[index] = []; +} + +export function setIgnore(map: GenMapping, source: string, ignore = true) { + const { + _sources: sources, + _sourcesContent: sourcesContent, + _ignoreList: ignoreList, + // _originalScopes: originalScopes, + } = cast(map); + const index = put(sources, source); + if (index === sourcesContent.length) sourcesContent[index] = null; + // if (index === originalScopes.length) originalScopes[index] = []; + if (ignore) put(ignoreList, index); + else remove(ignoreList, index); +} + +/** + * Returns a sourcemap object (with decoded mappings) suitable for passing to a library that expects + * a sourcemap, or to JSON.stringify. + */ +export function toDecodedMap(map: GenMapping): DecodedSourceMap { + const { + _mappings: mappings, + _sources: sources, + _sourcesContent: sourcesContent, + _names: names, + _ignoreList: ignoreList, + // _originalScopes: originalScopes, + // _generatedRanges: generatedRanges, + } = cast(map); + removeEmptyFinalLines(mappings); + + return { + version: 3, + file: map.file || undefined, + names: names.array, + sourceRoot: map.sourceRoot || undefined, + sources: sources.array, + sourcesContent, + mappings, + // originalScopes, + // generatedRanges, + ignoreList: ignoreList.array, + }; +} + +/** + * Returns a sourcemap object (with encoded mappings) suitable for passing to a library that expects + * a sourcemap, or to JSON.stringify. + */ +export function toEncodedMap(map: GenMapping): EncodedSourceMap { + const decoded = toDecodedMap(map); + return Object.assign({}, decoded, { + // originalScopes: decoded.originalScopes.map((os) => encodeOriginalScopes(os)), + // generatedRanges: encodeGeneratedRanges(decoded.generatedRanges as GeneratedRange[]), + mappings: encode(decoded.mappings as SourceMapSegment[][]), + }); +} + +/** + * Constructs a new GenMapping, using the already present mappings of the input. + */ +export function fromMap(input: SourceMapInput): GenMapping { + const map = new TraceMap(input); + const gen = new GenMapping({ file: map.file, sourceRoot: map.sourceRoot }); + + putAll(cast(gen)._names, map.names); + putAll(cast(gen)._sources, map.sources as string[]); + cast(gen)._sourcesContent = map.sourcesContent || map.sources.map(() => null); + cast(gen)._mappings = decodedMappings(map) as GenMapping['_mappings']; + // TODO: implement originalScopes/generatedRanges + if (map.ignoreList) putAll(cast(gen)._ignoreList, map.ignoreList); + + return gen; +} + +/** + * Returns an array of high-level mapping objects for every recorded segment, which could then be + * passed to the `source-map` library. + */ +export function allMappings(map: GenMapping): Mapping[] { + const out: Mapping[] = []; + const { _mappings: mappings, _sources: sources, _names: names } = cast(map); + + for (let i = 0; i < mappings.length; i++) { + const line = mappings[i]; + for (let j = 0; j < line.length; j++) { + const seg = line[j]; + + const generated = { line: i + 1, column: seg[COLUMN] }; + let source: string | undefined = undefined; + let original: Pos | undefined = undefined; + let name: string | undefined = undefined; + + if (seg.length !== 1) { + source = sources.array[seg[SOURCES_INDEX]]; + original = { line: seg[SOURCE_LINE] + 1, column: seg[SOURCE_COLUMN] }; + + if (seg.length === 5) name = names.array[seg[NAMES_INDEX]]; + } + + out.push({ generated, source, original, name } as Mapping); + } + } + + return out; +} + +// This split declaration is only so that terser can elminiate the static initialization block. +function addSegmentInternal( + skipable: boolean, + map: GenMapping, + genLine: number, + genColumn: number, + source: S, + sourceLine: S extends string ? number : null | undefined, + sourceColumn: S extends string ? number : null | undefined, + name: S extends string ? string | null | undefined : null | undefined, + content: S extends string ? string | null | undefined : null | undefined, +): void { + const { + _mappings: mappings, + _sources: sources, + _sourcesContent: sourcesContent, + _names: names, + // _originalScopes: originalScopes, + } = cast(map); + const line = getIndex(mappings, genLine); + const index = getColumnIndex(line, genColumn); + + if (!source) { + if (skipable && skipSourceless(line, index)) return; + return insert(line, index, [genColumn]); + } + + // Sigh, TypeScript can't figure out sourceLine and sourceColumn aren't nullish if source + // isn't nullish. + assert(sourceLine); + assert(sourceColumn); + + const sourcesIndex = put(sources, source); + const namesIndex = name ? put(names, name) : NO_NAME; + if (sourcesIndex === sourcesContent.length) sourcesContent[sourcesIndex] = content ?? null; + // if (sourcesIndex === originalScopes.length) originalScopes[sourcesIndex] = []; + + if (skipable && skipSource(line, index, sourcesIndex, sourceLine, sourceColumn, namesIndex)) { + return; + } + + return insert( + line, + index, + name + ? [genColumn, sourcesIndex, sourceLine, sourceColumn, namesIndex] + : [genColumn, sourcesIndex, sourceLine, sourceColumn], + ); +} + +function assert(_val: unknown): asserts _val is T { + // noop. +} + +function getIndex(arr: T[][], index: number): T[] { + for (let i = arr.length; i <= index; i++) { + arr[i] = []; + } + return arr[index]; +} + +function getColumnIndex(line: SourceMapSegment[], genColumn: number): number { + let index = line.length; + for (let i = index - 1; i >= 0; index = i--) { + const current = line[i]; + if (genColumn >= current[COLUMN]) break; + } + return index; +} + +function insert(array: T[], index: number, value: T) { + for (let i = array.length; i > index; i--) { + array[i] = array[i - 1]; + } + array[index] = value; +} + +function removeEmptyFinalLines(mappings: SourceMapSegment[][]) { + const { length } = mappings; + let len = length; + for (let i = len - 1; i >= 0; len = i, i--) { + if (mappings[i].length > 0) break; + } + if (len < length) mappings.length = len; +} + +function putAll(setarr: SetArray, array: T[]) { + for (let i = 0; i < array.length; i++) put(setarr, array[i]); +} + +function skipSourceless(line: SourceMapSegment[], index: number): boolean { + // The start of a line is already sourceless, so adding a sourceless segment to the beginning + // doesn't generate any useful information. + if (index === 0) return true; + + const prev = line[index - 1]; + // If the previous segment is also sourceless, then adding another sourceless segment doesn't + // genrate any new information. Else, this segment will end the source/named segment and point to + // a sourceless position, which is useful. + return prev.length === 1; +} + +function skipSource( + line: SourceMapSegment[], + index: number, + sourcesIndex: number, + sourceLine: number, + sourceColumn: number, + namesIndex: number, +): boolean { + // A source/named segment at the start of a line gives position at that genColumn + if (index === 0) return false; + + const prev = line[index - 1]; + + // If the previous segment is sourceless, then we're transitioning to a source. + if (prev.length === 1) return false; + + // If the previous segment maps to the exact same source position, then this segment doesn't + // provide any new position information. + return ( + sourcesIndex === prev[SOURCES_INDEX] && + sourceLine === prev[SOURCE_LINE] && + sourceColumn === prev[SOURCE_COLUMN] && + namesIndex === (prev.length === 5 ? prev[NAMES_INDEX] : NO_NAME) + ); +} + +function addMappingInternal( + skipable: boolean, + map: GenMapping, + mapping: { + generated: Pos; + source: S; + original: S extends string ? Pos : null | undefined; + name: S extends string ? string | null | undefined : null | undefined; + content: S extends string ? string | null | undefined : null | undefined; + }, +) { + const { generated, source, original, name, content } = mapping; + if (!source) { + return addSegmentInternal( + skipable, + map, + generated.line - 1, + generated.column, + null, + null, + null, + null, + null, + ); + } + assert(original); + return addSegmentInternal( + skipable, + map, + generated.line - 1, + generated.column, + source as string, + original.line - 1, + original.column, + name, + content, + ); +} + +/* +export function addOriginalScope( + map: GenMapping, + data: { + start: Pos; + end: Pos; + source: string; + kind: string; + name?: string; + variables?: string[]; + }, +): OriginalScopeInfo { + const { start, end, source, kind, name, variables } = data; + const { + _sources: sources, + _sourcesContent: sourcesContent, + _originalScopes: originalScopes, + _names: names, + } = cast(map); + const index = put(sources, source); + if (index === sourcesContent.length) sourcesContent[index] = null; + if (index === originalScopes.length) originalScopes[index] = []; + + const kindIndex = put(names, kind); + const scope: OriginalScope = name + ? [start.line - 1, start.column, end.line - 1, end.column, kindIndex, put(names, name)] + : [start.line - 1, start.column, end.line - 1, end.column, kindIndex]; + if (variables) { + scope.vars = variables.map((v) => put(names, v)); + } + const len = originalScopes[index].push(scope); + return [index, len - 1, variables]; +} +*/ + +// Generated Ranges +/* +export function addGeneratedRange( + map: GenMapping, + data: { + start: Pos; + isScope: boolean; + originalScope?: OriginalScopeInfo; + callsite?: OriginalPos; + }, +): GeneratedRangeInfo { + const { start, isScope, originalScope, callsite } = data; + const { + _originalScopes: originalScopes, + _sources: sources, + _sourcesContent: sourcesContent, + _generatedRanges: generatedRanges, + } = cast(map); + + const range: GeneratedRange = [ + start.line - 1, + start.column, + 0, + 0, + originalScope ? originalScope[0] : -1, + originalScope ? originalScope[1] : -1, + ]; + if (originalScope?.[2]) { + range.bindings = originalScope[2].map(() => [[-1]]); + } + if (callsite) { + const index = put(sources, callsite.source); + if (index === sourcesContent.length) sourcesContent[index] = null; + if (index === originalScopes.length) originalScopes[index] = []; + range.callsite = [index, callsite.line - 1, callsite.column]; + } + if (isScope) range.isScope = true; + generatedRanges.push(range); + + return [range, originalScope?.[2]]; +} + +export function setEndPosition(range: GeneratedRangeInfo, pos: Pos) { + range[0][2] = pos.line - 1; + range[0][3] = pos.column; +} + +export function addBinding( + map: GenMapping, + range: GeneratedRangeInfo, + variable: string, + expression: string | BindingExpressionRange, +) { + const { _names: names } = cast(map); + const bindings = (range[0].bindings ||= []); + const vars = range[1]; + + const index = vars!.indexOf(variable); + const binding = getIndex(bindings, index); + + if (typeof expression === 'string') binding[0] = [put(names, expression)]; + else { + const { start } = expression; + binding.push([put(names, expression.expression), start.line - 1, start.column]); + } +} +*/ diff --git a/dg-ui/node_modules/@jridgewell/gen-mapping/src/set-array.ts b/dg-ui/node_modules/@jridgewell/gen-mapping/src/set-array.ts new file mode 100644 index 0000000..a2a73a5 --- /dev/null +++ b/dg-ui/node_modules/@jridgewell/gen-mapping/src/set-array.ts @@ -0,0 +1,82 @@ +type Key = string | number | symbol; + +/** + * SetArray acts like a `Set` (allowing only one occurrence of a string `key`), but provides the + * index of the `key` in the backing array. + * + * This is designed to allow synchronizing a second array with the contents of the backing array, + * like how in a sourcemap `sourcesContent[i]` is the source content associated with `source[i]`, + * and there are never duplicates. + */ +export class SetArray { + declare private _indexes: Record; + declare array: readonly T[]; + + constructor() { + this._indexes = { __proto__: null } as any; + this.array = []; + } +} + +interface PublicSet { + array: T[]; + _indexes: SetArray['_indexes']; +} + +/** + * Typescript doesn't allow friend access to private fields, so this just casts the set into a type + * with public access modifiers. + */ +function cast(set: SetArray): PublicSet { + return set as any; +} + +/** + * Gets the index associated with `key` in the backing array, if it is already present. + */ +export function get(setarr: SetArray, key: T): number | undefined { + return cast(setarr)._indexes[key]; +} + +/** + * Puts `key` into the backing array, if it is not already present. Returns + * the index of the `key` in the backing array. + */ +export function put(setarr: SetArray, key: T): number { + // The key may or may not be present. If it is present, it's a number. + const index = get(setarr, key); + if (index !== undefined) return index; + + const { array, _indexes: indexes } = cast(setarr); + + const length = array.push(key); + return (indexes[key] = length - 1); +} + +/** + * Pops the last added item out of the SetArray. + */ +export function pop(setarr: SetArray): void { + const { array, _indexes: indexes } = cast(setarr); + if (array.length === 0) return; + + const last = array.pop()!; + indexes[last] = undefined; +} + +/** + * Removes the key, if it exists in the set. + */ +export function remove(setarr: SetArray, key: T): void { + const index = get(setarr, key); + if (index === undefined) return; + + const { array, _indexes: indexes } = cast(setarr); + for (let i = index + 1; i < array.length; i++) { + const k = array[i]; + array[i - 1] = k; + indexes[k]!--; + } + indexes[key] = undefined; + array.pop(); +} diff --git a/dg-ui/node_modules/@jridgewell/gen-mapping/src/sourcemap-segment.ts b/dg-ui/node_modules/@jridgewell/gen-mapping/src/sourcemap-segment.ts new file mode 100644 index 0000000..fb296dd --- /dev/null +++ b/dg-ui/node_modules/@jridgewell/gen-mapping/src/sourcemap-segment.ts @@ -0,0 +1,16 @@ +type GeneratedColumn = number; +type SourcesIndex = number; +type SourceLine = number; +type SourceColumn = number; +type NamesIndex = number; + +export type SourceMapSegment = + | [GeneratedColumn] + | [GeneratedColumn, SourcesIndex, SourceLine, SourceColumn] + | [GeneratedColumn, SourcesIndex, SourceLine, SourceColumn, NamesIndex]; + +export const COLUMN = 0; +export const SOURCES_INDEX = 1; +export const SOURCE_LINE = 2; +export const SOURCE_COLUMN = 3; +export const NAMES_INDEX = 4; diff --git a/dg-ui/node_modules/@jridgewell/gen-mapping/src/types.ts b/dg-ui/node_modules/@jridgewell/gen-mapping/src/types.ts new file mode 100644 index 0000000..b087f70 --- /dev/null +++ b/dg-ui/node_modules/@jridgewell/gen-mapping/src/types.ts @@ -0,0 +1,61 @@ +// import type { GeneratedRange, OriginalScope } from '@jridgewell/sourcemap-codec'; +import type { SourceMapSegment } from './sourcemap-segment'; + +export interface SourceMapV3 { + file?: string | null; + names: readonly string[]; + sourceRoot?: string; + sources: readonly (string | null)[]; + sourcesContent?: readonly (string | null)[]; + version: 3; + ignoreList?: readonly number[]; +} + +export interface EncodedSourceMap extends SourceMapV3 { + mappings: string; + // originalScopes: string[]; + // generatedRanges: string; +} + +export interface DecodedSourceMap extends SourceMapV3 { + mappings: readonly SourceMapSegment[][]; + // originalScopes: readonly OriginalScope[][]; + // generatedRanges: readonly GeneratedRange[]; +} + +export interface Pos { + line: number; // 1-based + column: number; // 0-based +} + +export interface OriginalPos extends Pos { + source: string; +} + +export interface BindingExpressionRange { + start: Pos; + expression: string; +} + +// export type OriginalScopeInfo = [number, number, string[] | undefined]; +// export type GeneratedRangeInfo = [GeneratedRange, string[] | undefined]; + +export type Mapping = + | { + generated: Pos; + source: undefined; + original: undefined; + name: undefined; + } + | { + generated: Pos; + source: string; + original: Pos; + name: string; + } + | { + generated: Pos; + source: string; + original: Pos; + name: undefined; + }; diff --git a/dg-ui/node_modules/@jridgewell/gen-mapping/types/gen-mapping.d.cts b/dg-ui/node_modules/@jridgewell/gen-mapping/types/gen-mapping.d.cts new file mode 100644 index 0000000..7618d85 --- /dev/null +++ b/dg-ui/node_modules/@jridgewell/gen-mapping/types/gen-mapping.d.cts @@ -0,0 +1,89 @@ +import type { SourceMapInput } from '@jridgewell/trace-mapping'; +import type { DecodedSourceMap, EncodedSourceMap, Pos, Mapping } from './types.cts'; +export type { DecodedSourceMap, EncodedSourceMap, Mapping }; +export type Options = { + file?: string | null; + sourceRoot?: string | null; +}; +/** + * Provides the state to generate a sourcemap. + */ +export declare class GenMapping { + private _names; + private _sources; + private _sourcesContent; + private _mappings; + private _ignoreList; + file: string | null | undefined; + sourceRoot: string | null | undefined; + constructor({ file, sourceRoot }?: Options); +} +/** + * A low-level API to associate a generated position with an original source position. Line and + * column here are 0-based, unlike `addMapping`. + */ +export declare function addSegment(map: GenMapping, genLine: number, genColumn: number, source?: null, sourceLine?: null, sourceColumn?: null, name?: null, content?: null): void; +export declare function addSegment(map: GenMapping, genLine: number, genColumn: number, source: string, sourceLine: number, sourceColumn: number, name?: null, content?: string | null): void; +export declare function addSegment(map: GenMapping, genLine: number, genColumn: number, source: string, sourceLine: number, sourceColumn: number, name: string, content?: string | null): void; +/** + * A high-level API to associate a generated position with an original source position. Line is + * 1-based, but column is 0-based, due to legacy behavior in `source-map` library. + */ +export declare function addMapping(map: GenMapping, mapping: { + generated: Pos; + source?: null; + original?: null; + name?: null; + content?: null; +}): void; +export declare function addMapping(map: GenMapping, mapping: { + generated: Pos; + source: string; + original: Pos; + name?: null; + content?: string | null; +}): void; +export declare function addMapping(map: GenMapping, mapping: { + generated: Pos; + source: string; + original: Pos; + name: string; + content?: string | null; +}): void; +/** + * Same as `addSegment`, but will only add the segment if it generates useful information in the + * resulting map. This only works correctly if segments are added **in order**, meaning you should + * not add a segment with a lower generated line/column than one that came before. + */ +export declare const maybeAddSegment: typeof addSegment; +/** + * Same as `addMapping`, but will only add the mapping if it generates useful information in the + * resulting map. This only works correctly if mappings are added **in order**, meaning you should + * not add a mapping with a lower generated line/column than one that came before. + */ +export declare const maybeAddMapping: typeof addMapping; +/** + * Adds/removes the content of the source file to the source map. + */ +export declare function setSourceContent(map: GenMapping, source: string, content: string | null): void; +export declare function setIgnore(map: GenMapping, source: string, ignore?: boolean): void; +/** + * Returns a sourcemap object (with decoded mappings) suitable for passing to a library that expects + * a sourcemap, or to JSON.stringify. + */ +export declare function toDecodedMap(map: GenMapping): DecodedSourceMap; +/** + * Returns a sourcemap object (with encoded mappings) suitable for passing to a library that expects + * a sourcemap, or to JSON.stringify. + */ +export declare function toEncodedMap(map: GenMapping): EncodedSourceMap; +/** + * Constructs a new GenMapping, using the already present mappings of the input. + */ +export declare function fromMap(input: SourceMapInput): GenMapping; +/** + * Returns an array of high-level mapping objects for every recorded segment, which could then be + * passed to the `source-map` library. + */ +export declare function allMappings(map: GenMapping): Mapping[]; +//# sourceMappingURL=gen-mapping.d.ts.map \ No newline at end of file diff --git a/dg-ui/node_modules/@jridgewell/gen-mapping/types/gen-mapping.d.cts.map b/dg-ui/node_modules/@jridgewell/gen-mapping/types/gen-mapping.d.cts.map new file mode 100644 index 0000000..8a2b183 --- /dev/null +++ b/dg-ui/node_modules/@jridgewell/gen-mapping/types/gen-mapping.d.cts.map @@ -0,0 +1 @@ +{"version":3,"file":"gen-mapping.d.ts","sourceRoot":"","sources":["../src/gen-mapping.ts"],"names":[],"mappings":"AAgBA,OAAO,KAAK,EAAE,cAAc,EAAE,MAAM,2BAA2B,CAAC;AAGhE,OAAO,KAAK,EACV,gBAAgB,EAChB,gBAAgB,EAChB,GAAG,EACH,OAAO,EAKR,MAAM,SAAS,CAAC;AAEjB,YAAY,EAAE,gBAAgB,EAAE,gBAAgB,EAAE,OAAO,EAAE,CAAC;AAE5D,MAAM,MAAM,OAAO,GAAG;IACpB,IAAI,CAAC,EAAE,MAAM,GAAG,IAAI,CAAC;IACrB,UAAU,CAAC,EAAE,MAAM,GAAG,IAAI,CAAC;CAC5B,CAAC;AAIF;;GAEG;AACH,qBAAa,UAAU;IACrB,QAAgB,MAAM,CAAmB;IACzC,QAAgB,QAAQ,CAAmB;IAC3C,QAAgB,eAAe,CAAoB;IACnD,QAAgB,SAAS,CAAuB;IAGhD,QAAgB,WAAW,CAAmB;IACtC,IAAI,EAAE,MAAM,GAAG,IAAI,GAAG,SAAS,CAAC;IAChC,UAAU,EAAE,MAAM,GAAG,IAAI,GAAG,SAAS,CAAC;gBAElC,EAAE,IAAI,EAAE,UAAU,EAAE,GAAE,OAAY;CAW/C;AAoBD;;;GAGG;AACH,wBAAgB,UAAU,CACxB,GAAG,EAAE,UAAU,EACf,OAAO,EAAE,MAAM,EACf,SAAS,EAAE,MAAM,EACjB,MAAM,CAAC,EAAE,IAAI,EACb,UAAU,CAAC,EAAE,IAAI,EACjB,YAAY,CAAC,EAAE,IAAI,EACnB,IAAI,CAAC,EAAE,IAAI,EACX,OAAO,CAAC,EAAE,IAAI,GACb,IAAI,CAAC;AACR,wBAAgB,UAAU,CACxB,GAAG,EAAE,UAAU,EACf,OAAO,EAAE,MAAM,EACf,SAAS,EAAE,MAAM,EACjB,MAAM,EAAE,MAAM,EACd,UAAU,EAAE,MAAM,EAClB,YAAY,EAAE,MAAM,EACpB,IAAI,CAAC,EAAE,IAAI,EACX,OAAO,CAAC,EAAE,MAAM,GAAG,IAAI,GACtB,IAAI,CAAC;AACR,wBAAgB,UAAU,CACxB,GAAG,EAAE,UAAU,EACf,OAAO,EAAE,MAAM,EACf,SAAS,EAAE,MAAM,EACjB,MAAM,EAAE,MAAM,EACd,UAAU,EAAE,MAAM,EAClB,YAAY,EAAE,MAAM,EACpB,IAAI,EAAE,MAAM,EACZ,OAAO,CAAC,EAAE,MAAM,GAAG,IAAI,GACtB,IAAI,CAAC;AAwBR;;;GAGG;AACH,wBAAgB,UAAU,CACxB,GAAG,EAAE,UAAU,EACf,OAAO,EAAE;IACP,SAAS,EAAE,GAAG,CAAC;IACf,MAAM,CAAC,EAAE,IAAI,CAAC;IACd,QAAQ,CAAC,EAAE,IAAI,CAAC;IAChB,IAAI,CAAC,EAAE,IAAI,CAAC;IACZ,OAAO,CAAC,EAAE,IAAI,CAAC;CAChB,GACA,IAAI,CAAC;AACR,wBAAgB,UAAU,CACxB,GAAG,EAAE,UAAU,EACf,OAAO,EAAE;IACP,SAAS,EAAE,GAAG,CAAC;IACf,MAAM,EAAE,MAAM,CAAC;IACf,QAAQ,EAAE,GAAG,CAAC;IACd,IAAI,CAAC,EAAE,IAAI,CAAC;IACZ,OAAO,CAAC,EAAE,MAAM,GAAG,IAAI,CAAC;CACzB,GACA,IAAI,CAAC;AACR,wBAAgB,UAAU,CACxB,GAAG,EAAE,UAAU,EACf,OAAO,EAAE;IACP,SAAS,EAAE,GAAG,CAAC;IACf,MAAM,EAAE,MAAM,CAAC;IACf,QAAQ,EAAE,GAAG,CAAC;IACd,IAAI,EAAE,MAAM,CAAC;IACb,OAAO,CAAC,EAAE,MAAM,GAAG,IAAI,CAAC;CACzB,GACA,IAAI,CAAC;AAcR;;;;GAIG;AACH,eAAO,MAAM,eAAe,EAAE,OAAO,UAqBpC,CAAC;AAEF;;;;GAIG;AACH,eAAO,MAAM,eAAe,EAAE,OAAO,UAEpC,CAAC;AAEF;;GAEG;AACH,wBAAgB,gBAAgB,CAAC,GAAG,EAAE,UAAU,EAAE,MAAM,EAAE,MAAM,EAAE,OAAO,EAAE,MAAM,GAAG,IAAI,GAAG,IAAI,CAS9F;AAED,wBAAgB,SAAS,CAAC,GAAG,EAAE,UAAU,EAAE,MAAM,EAAE,MAAM,EAAE,MAAM,UAAO,QAYvE;AAED;;;GAGG;AACH,wBAAgB,YAAY,CAAC,GAAG,EAAE,UAAU,GAAG,gBAAgB,CAwB9D;AAED;;;GAGG;AACH,wBAAgB,YAAY,CAAC,GAAG,EAAE,UAAU,GAAG,gBAAgB,CAO9D;AAED;;GAEG;AACH,wBAAgB,OAAO,CAAC,KAAK,EAAE,cAAc,GAAG,UAAU,CAYzD;AAED;;;GAGG;AACH,wBAAgB,WAAW,CAAC,GAAG,EAAE,UAAU,GAAG,OAAO,EAAE,CA0BtD"} \ No newline at end of file diff --git a/dg-ui/node_modules/@jridgewell/gen-mapping/types/gen-mapping.d.mts b/dg-ui/node_modules/@jridgewell/gen-mapping/types/gen-mapping.d.mts new file mode 100644 index 0000000..bbc0d89 --- /dev/null +++ b/dg-ui/node_modules/@jridgewell/gen-mapping/types/gen-mapping.d.mts @@ -0,0 +1,89 @@ +import type { SourceMapInput } from '@jridgewell/trace-mapping'; +import type { DecodedSourceMap, EncodedSourceMap, Pos, Mapping } from './types.mts'; +export type { DecodedSourceMap, EncodedSourceMap, Mapping }; +export type Options = { + file?: string | null; + sourceRoot?: string | null; +}; +/** + * Provides the state to generate a sourcemap. + */ +export declare class GenMapping { + private _names; + private _sources; + private _sourcesContent; + private _mappings; + private _ignoreList; + file: string | null | undefined; + sourceRoot: string | null | undefined; + constructor({ file, sourceRoot }?: Options); +} +/** + * A low-level API to associate a generated position with an original source position. Line and + * column here are 0-based, unlike `addMapping`. + */ +export declare function addSegment(map: GenMapping, genLine: number, genColumn: number, source?: null, sourceLine?: null, sourceColumn?: null, name?: null, content?: null): void; +export declare function addSegment(map: GenMapping, genLine: number, genColumn: number, source: string, sourceLine: number, sourceColumn: number, name?: null, content?: string | null): void; +export declare function addSegment(map: GenMapping, genLine: number, genColumn: number, source: string, sourceLine: number, sourceColumn: number, name: string, content?: string | null): void; +/** + * A high-level API to associate a generated position with an original source position. Line is + * 1-based, but column is 0-based, due to legacy behavior in `source-map` library. + */ +export declare function addMapping(map: GenMapping, mapping: { + generated: Pos; + source?: null; + original?: null; + name?: null; + content?: null; +}): void; +export declare function addMapping(map: GenMapping, mapping: { + generated: Pos; + source: string; + original: Pos; + name?: null; + content?: string | null; +}): void; +export declare function addMapping(map: GenMapping, mapping: { + generated: Pos; + source: string; + original: Pos; + name: string; + content?: string | null; +}): void; +/** + * Same as `addSegment`, but will only add the segment if it generates useful information in the + * resulting map. This only works correctly if segments are added **in order**, meaning you should + * not add a segment with a lower generated line/column than one that came before. + */ +export declare const maybeAddSegment: typeof addSegment; +/** + * Same as `addMapping`, but will only add the mapping if it generates useful information in the + * resulting map. This only works correctly if mappings are added **in order**, meaning you should + * not add a mapping with a lower generated line/column than one that came before. + */ +export declare const maybeAddMapping: typeof addMapping; +/** + * Adds/removes the content of the source file to the source map. + */ +export declare function setSourceContent(map: GenMapping, source: string, content: string | null): void; +export declare function setIgnore(map: GenMapping, source: string, ignore?: boolean): void; +/** + * Returns a sourcemap object (with decoded mappings) suitable for passing to a library that expects + * a sourcemap, or to JSON.stringify. + */ +export declare function toDecodedMap(map: GenMapping): DecodedSourceMap; +/** + * Returns a sourcemap object (with encoded mappings) suitable for passing to a library that expects + * a sourcemap, or to JSON.stringify. + */ +export declare function toEncodedMap(map: GenMapping): EncodedSourceMap; +/** + * Constructs a new GenMapping, using the already present mappings of the input. + */ +export declare function fromMap(input: SourceMapInput): GenMapping; +/** + * Returns an array of high-level mapping objects for every recorded segment, which could then be + * passed to the `source-map` library. + */ +export declare function allMappings(map: GenMapping): Mapping[]; +//# sourceMappingURL=gen-mapping.d.ts.map \ No newline at end of file diff --git a/dg-ui/node_modules/@jridgewell/gen-mapping/types/gen-mapping.d.mts.map b/dg-ui/node_modules/@jridgewell/gen-mapping/types/gen-mapping.d.mts.map new file mode 100644 index 0000000..8a2b183 --- /dev/null +++ b/dg-ui/node_modules/@jridgewell/gen-mapping/types/gen-mapping.d.mts.map @@ -0,0 +1 @@ +{"version":3,"file":"gen-mapping.d.ts","sourceRoot":"","sources":["../src/gen-mapping.ts"],"names":[],"mappings":"AAgBA,OAAO,KAAK,EAAE,cAAc,EAAE,MAAM,2BAA2B,CAAC;AAGhE,OAAO,KAAK,EACV,gBAAgB,EAChB,gBAAgB,EAChB,GAAG,EACH,OAAO,EAKR,MAAM,SAAS,CAAC;AAEjB,YAAY,EAAE,gBAAgB,EAAE,gBAAgB,EAAE,OAAO,EAAE,CAAC;AAE5D,MAAM,MAAM,OAAO,GAAG;IACpB,IAAI,CAAC,EAAE,MAAM,GAAG,IAAI,CAAC;IACrB,UAAU,CAAC,EAAE,MAAM,GAAG,IAAI,CAAC;CAC5B,CAAC;AAIF;;GAEG;AACH,qBAAa,UAAU;IACrB,QAAgB,MAAM,CAAmB;IACzC,QAAgB,QAAQ,CAAmB;IAC3C,QAAgB,eAAe,CAAoB;IACnD,QAAgB,SAAS,CAAuB;IAGhD,QAAgB,WAAW,CAAmB;IACtC,IAAI,EAAE,MAAM,GAAG,IAAI,GAAG,SAAS,CAAC;IAChC,UAAU,EAAE,MAAM,GAAG,IAAI,GAAG,SAAS,CAAC;gBAElC,EAAE,IAAI,EAAE,UAAU,EAAE,GAAE,OAAY;CAW/C;AAoBD;;;GAGG;AACH,wBAAgB,UAAU,CACxB,GAAG,EAAE,UAAU,EACf,OAAO,EAAE,MAAM,EACf,SAAS,EAAE,MAAM,EACjB,MAAM,CAAC,EAAE,IAAI,EACb,UAAU,CAAC,EAAE,IAAI,EACjB,YAAY,CAAC,EAAE,IAAI,EACnB,IAAI,CAAC,EAAE,IAAI,EACX,OAAO,CAAC,EAAE,IAAI,GACb,IAAI,CAAC;AACR,wBAAgB,UAAU,CACxB,GAAG,EAAE,UAAU,EACf,OAAO,EAAE,MAAM,EACf,SAAS,EAAE,MAAM,EACjB,MAAM,EAAE,MAAM,EACd,UAAU,EAAE,MAAM,EAClB,YAAY,EAAE,MAAM,EACpB,IAAI,CAAC,EAAE,IAAI,EACX,OAAO,CAAC,EAAE,MAAM,GAAG,IAAI,GACtB,IAAI,CAAC;AACR,wBAAgB,UAAU,CACxB,GAAG,EAAE,UAAU,EACf,OAAO,EAAE,MAAM,EACf,SAAS,EAAE,MAAM,EACjB,MAAM,EAAE,MAAM,EACd,UAAU,EAAE,MAAM,EAClB,YAAY,EAAE,MAAM,EACpB,IAAI,EAAE,MAAM,EACZ,OAAO,CAAC,EAAE,MAAM,GAAG,IAAI,GACtB,IAAI,CAAC;AAwBR;;;GAGG;AACH,wBAAgB,UAAU,CACxB,GAAG,EAAE,UAAU,EACf,OAAO,EAAE;IACP,SAAS,EAAE,GAAG,CAAC;IACf,MAAM,CAAC,EAAE,IAAI,CAAC;IACd,QAAQ,CAAC,EAAE,IAAI,CAAC;IAChB,IAAI,CAAC,EAAE,IAAI,CAAC;IACZ,OAAO,CAAC,EAAE,IAAI,CAAC;CAChB,GACA,IAAI,CAAC;AACR,wBAAgB,UAAU,CACxB,GAAG,EAAE,UAAU,EACf,OAAO,EAAE;IACP,SAAS,EAAE,GAAG,CAAC;IACf,MAAM,EAAE,MAAM,CAAC;IACf,QAAQ,EAAE,GAAG,CAAC;IACd,IAAI,CAAC,EAAE,IAAI,CAAC;IACZ,OAAO,CAAC,EAAE,MAAM,GAAG,IAAI,CAAC;CACzB,GACA,IAAI,CAAC;AACR,wBAAgB,UAAU,CACxB,GAAG,EAAE,UAAU,EACf,OAAO,EAAE;IACP,SAAS,EAAE,GAAG,CAAC;IACf,MAAM,EAAE,MAAM,CAAC;IACf,QAAQ,EAAE,GAAG,CAAC;IACd,IAAI,EAAE,MAAM,CAAC;IACb,OAAO,CAAC,EAAE,MAAM,GAAG,IAAI,CAAC;CACzB,GACA,IAAI,CAAC;AAcR;;;;GAIG;AACH,eAAO,MAAM,eAAe,EAAE,OAAO,UAqBpC,CAAC;AAEF;;;;GAIG;AACH,eAAO,MAAM,eAAe,EAAE,OAAO,UAEpC,CAAC;AAEF;;GAEG;AACH,wBAAgB,gBAAgB,CAAC,GAAG,EAAE,UAAU,EAAE,MAAM,EAAE,MAAM,EAAE,OAAO,EAAE,MAAM,GAAG,IAAI,GAAG,IAAI,CAS9F;AAED,wBAAgB,SAAS,CAAC,GAAG,EAAE,UAAU,EAAE,MAAM,EAAE,MAAM,EAAE,MAAM,UAAO,QAYvE;AAED;;;GAGG;AACH,wBAAgB,YAAY,CAAC,GAAG,EAAE,UAAU,GAAG,gBAAgB,CAwB9D;AAED;;;GAGG;AACH,wBAAgB,YAAY,CAAC,GAAG,EAAE,UAAU,GAAG,gBAAgB,CAO9D;AAED;;GAEG;AACH,wBAAgB,OAAO,CAAC,KAAK,EAAE,cAAc,GAAG,UAAU,CAYzD;AAED;;;GAGG;AACH,wBAAgB,WAAW,CAAC,GAAG,EAAE,UAAU,GAAG,OAAO,EAAE,CA0BtD"} \ No newline at end of file diff --git a/dg-ui/node_modules/@jridgewell/gen-mapping/types/set-array.d.cts b/dg-ui/node_modules/@jridgewell/gen-mapping/types/set-array.d.cts new file mode 100644 index 0000000..5d8cda3 --- /dev/null +++ b/dg-ui/node_modules/@jridgewell/gen-mapping/types/set-array.d.cts @@ -0,0 +1,33 @@ +type Key = string | number | symbol; +/** + * SetArray acts like a `Set` (allowing only one occurrence of a string `key`), but provides the + * index of the `key` in the backing array. + * + * This is designed to allow synchronizing a second array with the contents of the backing array, + * like how in a sourcemap `sourcesContent[i]` is the source content associated with `source[i]`, + * and there are never duplicates. + */ +export declare class SetArray { + private _indexes; + array: readonly T[]; + constructor(); +} +/** + * Gets the index associated with `key` in the backing array, if it is already present. + */ +export declare function get(setarr: SetArray, key: T): number | undefined; +/** + * Puts `key` into the backing array, if it is not already present. Returns + * the index of the `key` in the backing array. + */ +export declare function put(setarr: SetArray, key: T): number; +/** + * Pops the last added item out of the SetArray. + */ +export declare function pop(setarr: SetArray): void; +/** + * Removes the key, if it exists in the set. + */ +export declare function remove(setarr: SetArray, key: T): void; +export {}; +//# sourceMappingURL=set-array.d.ts.map \ No newline at end of file diff --git a/dg-ui/node_modules/@jridgewell/gen-mapping/types/set-array.d.cts.map b/dg-ui/node_modules/@jridgewell/gen-mapping/types/set-array.d.cts.map new file mode 100644 index 0000000..c52b8bc --- /dev/null +++ b/dg-ui/node_modules/@jridgewell/gen-mapping/types/set-array.d.cts.map @@ -0,0 +1 @@ +{"version":3,"file":"set-array.d.ts","sourceRoot":"","sources":["../src/set-array.ts"],"names":[],"mappings":"AAAA,KAAK,GAAG,GAAG,MAAM,GAAG,MAAM,GAAG,MAAM,CAAC;AAEpC;;;;;;;GAOG;AACH,qBAAa,QAAQ,CAAC,CAAC,SAAS,GAAG,GAAG,GAAG;IACvC,QAAgB,QAAQ,CAAgC;IAChD,KAAK,EAAE,SAAS,CAAC,EAAE,CAAC;;CAM7B;AAeD;;GAEG;AACH,wBAAgB,GAAG,CAAC,CAAC,SAAS,GAAG,EAAE,MAAM,EAAE,QAAQ,CAAC,CAAC,CAAC,EAAE,GAAG,EAAE,CAAC,GAAG,MAAM,GAAG,SAAS,CAElF;AAED;;;GAGG;AACH,wBAAgB,GAAG,CAAC,CAAC,SAAS,GAAG,EAAE,MAAM,EAAE,QAAQ,CAAC,CAAC,CAAC,EAAE,GAAG,EAAE,CAAC,GAAG,MAAM,CAStE;AAED;;GAEG;AACH,wBAAgB,GAAG,CAAC,CAAC,SAAS,GAAG,EAAE,MAAM,EAAE,QAAQ,CAAC,CAAC,CAAC,GAAG,IAAI,CAM5D;AAED;;GAEG;AACH,wBAAgB,MAAM,CAAC,CAAC,SAAS,GAAG,EAAE,MAAM,EAAE,QAAQ,CAAC,CAAC,CAAC,EAAE,GAAG,EAAE,CAAC,GAAG,IAAI,CAYvE"} \ No newline at end of file diff --git a/dg-ui/node_modules/@jridgewell/gen-mapping/types/set-array.d.mts b/dg-ui/node_modules/@jridgewell/gen-mapping/types/set-array.d.mts new file mode 100644 index 0000000..5d8cda3 --- /dev/null +++ b/dg-ui/node_modules/@jridgewell/gen-mapping/types/set-array.d.mts @@ -0,0 +1,33 @@ +type Key = string | number | symbol; +/** + * SetArray acts like a `Set` (allowing only one occurrence of a string `key`), but provides the + * index of the `key` in the backing array. + * + * This is designed to allow synchronizing a second array with the contents of the backing array, + * like how in a sourcemap `sourcesContent[i]` is the source content associated with `source[i]`, + * and there are never duplicates. + */ +export declare class SetArray { + private _indexes; + array: readonly T[]; + constructor(); +} +/** + * Gets the index associated with `key` in the backing array, if it is already present. + */ +export declare function get(setarr: SetArray, key: T): number | undefined; +/** + * Puts `key` into the backing array, if it is not already present. Returns + * the index of the `key` in the backing array. + */ +export declare function put(setarr: SetArray, key: T): number; +/** + * Pops the last added item out of the SetArray. + */ +export declare function pop(setarr: SetArray): void; +/** + * Removes the key, if it exists in the set. + */ +export declare function remove(setarr: SetArray, key: T): void; +export {}; +//# sourceMappingURL=set-array.d.ts.map \ No newline at end of file diff --git a/dg-ui/node_modules/@jridgewell/gen-mapping/types/set-array.d.mts.map b/dg-ui/node_modules/@jridgewell/gen-mapping/types/set-array.d.mts.map new file mode 100644 index 0000000..c52b8bc --- /dev/null +++ b/dg-ui/node_modules/@jridgewell/gen-mapping/types/set-array.d.mts.map @@ -0,0 +1 @@ +{"version":3,"file":"set-array.d.ts","sourceRoot":"","sources":["../src/set-array.ts"],"names":[],"mappings":"AAAA,KAAK,GAAG,GAAG,MAAM,GAAG,MAAM,GAAG,MAAM,CAAC;AAEpC;;;;;;;GAOG;AACH,qBAAa,QAAQ,CAAC,CAAC,SAAS,GAAG,GAAG,GAAG;IACvC,QAAgB,QAAQ,CAAgC;IAChD,KAAK,EAAE,SAAS,CAAC,EAAE,CAAC;;CAM7B;AAeD;;GAEG;AACH,wBAAgB,GAAG,CAAC,CAAC,SAAS,GAAG,EAAE,MAAM,EAAE,QAAQ,CAAC,CAAC,CAAC,EAAE,GAAG,EAAE,CAAC,GAAG,MAAM,GAAG,SAAS,CAElF;AAED;;;GAGG;AACH,wBAAgB,GAAG,CAAC,CAAC,SAAS,GAAG,EAAE,MAAM,EAAE,QAAQ,CAAC,CAAC,CAAC,EAAE,GAAG,EAAE,CAAC,GAAG,MAAM,CAStE;AAED;;GAEG;AACH,wBAAgB,GAAG,CAAC,CAAC,SAAS,GAAG,EAAE,MAAM,EAAE,QAAQ,CAAC,CAAC,CAAC,GAAG,IAAI,CAM5D;AAED;;GAEG;AACH,wBAAgB,MAAM,CAAC,CAAC,SAAS,GAAG,EAAE,MAAM,EAAE,QAAQ,CAAC,CAAC,CAAC,EAAE,GAAG,EAAE,CAAC,GAAG,IAAI,CAYvE"} \ No newline at end of file diff --git a/dg-ui/node_modules/@jridgewell/gen-mapping/types/sourcemap-segment.d.cts b/dg-ui/node_modules/@jridgewell/gen-mapping/types/sourcemap-segment.d.cts new file mode 100644 index 0000000..6886295 --- /dev/null +++ b/dg-ui/node_modules/@jridgewell/gen-mapping/types/sourcemap-segment.d.cts @@ -0,0 +1,13 @@ +type GeneratedColumn = number; +type SourcesIndex = number; +type SourceLine = number; +type SourceColumn = number; +type NamesIndex = number; +export type SourceMapSegment = [GeneratedColumn] | [GeneratedColumn, SourcesIndex, SourceLine, SourceColumn] | [GeneratedColumn, SourcesIndex, SourceLine, SourceColumn, NamesIndex]; +export declare const COLUMN = 0; +export declare const SOURCES_INDEX = 1; +export declare const SOURCE_LINE = 2; +export declare const SOURCE_COLUMN = 3; +export declare const NAMES_INDEX = 4; +export {}; +//# sourceMappingURL=sourcemap-segment.d.ts.map \ No newline at end of file diff --git a/dg-ui/node_modules/@jridgewell/gen-mapping/types/sourcemap-segment.d.cts.map b/dg-ui/node_modules/@jridgewell/gen-mapping/types/sourcemap-segment.d.cts.map new file mode 100644 index 0000000..23cdc45 --- /dev/null +++ b/dg-ui/node_modules/@jridgewell/gen-mapping/types/sourcemap-segment.d.cts.map @@ -0,0 +1 @@ +{"version":3,"file":"sourcemap-segment.d.ts","sourceRoot":"","sources":["../src/sourcemap-segment.ts"],"names":[],"mappings":"AAAA,KAAK,eAAe,GAAG,MAAM,CAAC;AAC9B,KAAK,YAAY,GAAG,MAAM,CAAC;AAC3B,KAAK,UAAU,GAAG,MAAM,CAAC;AACzB,KAAK,YAAY,GAAG,MAAM,CAAC;AAC3B,KAAK,UAAU,GAAG,MAAM,CAAC;AAEzB,MAAM,MAAM,gBAAgB,GACxB,CAAC,eAAe,CAAC,GACjB,CAAC,eAAe,EAAE,YAAY,EAAE,UAAU,EAAE,YAAY,CAAC,GACzD,CAAC,eAAe,EAAE,YAAY,EAAE,UAAU,EAAE,YAAY,EAAE,UAAU,CAAC,CAAC;AAE1E,eAAO,MAAM,MAAM,IAAI,CAAC;AACxB,eAAO,MAAM,aAAa,IAAI,CAAC;AAC/B,eAAO,MAAM,WAAW,IAAI,CAAC;AAC7B,eAAO,MAAM,aAAa,IAAI,CAAC;AAC/B,eAAO,MAAM,WAAW,IAAI,CAAC"} \ No newline at end of file diff --git a/dg-ui/node_modules/@jridgewell/gen-mapping/types/sourcemap-segment.d.mts b/dg-ui/node_modules/@jridgewell/gen-mapping/types/sourcemap-segment.d.mts new file mode 100644 index 0000000..6886295 --- /dev/null +++ b/dg-ui/node_modules/@jridgewell/gen-mapping/types/sourcemap-segment.d.mts @@ -0,0 +1,13 @@ +type GeneratedColumn = number; +type SourcesIndex = number; +type SourceLine = number; +type SourceColumn = number; +type NamesIndex = number; +export type SourceMapSegment = [GeneratedColumn] | [GeneratedColumn, SourcesIndex, SourceLine, SourceColumn] | [GeneratedColumn, SourcesIndex, SourceLine, SourceColumn, NamesIndex]; +export declare const COLUMN = 0; +export declare const SOURCES_INDEX = 1; +export declare const SOURCE_LINE = 2; +export declare const SOURCE_COLUMN = 3; +export declare const NAMES_INDEX = 4; +export {}; +//# sourceMappingURL=sourcemap-segment.d.ts.map \ No newline at end of file diff --git a/dg-ui/node_modules/@jridgewell/gen-mapping/types/sourcemap-segment.d.mts.map b/dg-ui/node_modules/@jridgewell/gen-mapping/types/sourcemap-segment.d.mts.map new file mode 100644 index 0000000..23cdc45 --- /dev/null +++ b/dg-ui/node_modules/@jridgewell/gen-mapping/types/sourcemap-segment.d.mts.map @@ -0,0 +1 @@ +{"version":3,"file":"sourcemap-segment.d.ts","sourceRoot":"","sources":["../src/sourcemap-segment.ts"],"names":[],"mappings":"AAAA,KAAK,eAAe,GAAG,MAAM,CAAC;AAC9B,KAAK,YAAY,GAAG,MAAM,CAAC;AAC3B,KAAK,UAAU,GAAG,MAAM,CAAC;AACzB,KAAK,YAAY,GAAG,MAAM,CAAC;AAC3B,KAAK,UAAU,GAAG,MAAM,CAAC;AAEzB,MAAM,MAAM,gBAAgB,GACxB,CAAC,eAAe,CAAC,GACjB,CAAC,eAAe,EAAE,YAAY,EAAE,UAAU,EAAE,YAAY,CAAC,GACzD,CAAC,eAAe,EAAE,YAAY,EAAE,UAAU,EAAE,YAAY,EAAE,UAAU,CAAC,CAAC;AAE1E,eAAO,MAAM,MAAM,IAAI,CAAC;AACxB,eAAO,MAAM,aAAa,IAAI,CAAC;AAC/B,eAAO,MAAM,WAAW,IAAI,CAAC;AAC7B,eAAO,MAAM,aAAa,IAAI,CAAC;AAC/B,eAAO,MAAM,WAAW,IAAI,CAAC"} \ No newline at end of file diff --git a/dg-ui/node_modules/@jridgewell/gen-mapping/types/types.d.cts b/dg-ui/node_modules/@jridgewell/gen-mapping/types/types.d.cts new file mode 100644 index 0000000..58da00a --- /dev/null +++ b/dg-ui/node_modules/@jridgewell/gen-mapping/types/types.d.cts @@ -0,0 +1,44 @@ +import type { SourceMapSegment } from './sourcemap-segment.cts'; +export interface SourceMapV3 { + file?: string | null; + names: readonly string[]; + sourceRoot?: string; + sources: readonly (string | null)[]; + sourcesContent?: readonly (string | null)[]; + version: 3; + ignoreList?: readonly number[]; +} +export interface EncodedSourceMap extends SourceMapV3 { + mappings: string; +} +export interface DecodedSourceMap extends SourceMapV3 { + mappings: readonly SourceMapSegment[][]; +} +export interface Pos { + line: number; + column: number; +} +export interface OriginalPos extends Pos { + source: string; +} +export interface BindingExpressionRange { + start: Pos; + expression: string; +} +export type Mapping = { + generated: Pos; + source: undefined; + original: undefined; + name: undefined; +} | { + generated: Pos; + source: string; + original: Pos; + name: string; +} | { + generated: Pos; + source: string; + original: Pos; + name: undefined; +}; +//# sourceMappingURL=types.d.ts.map \ No newline at end of file diff --git a/dg-ui/node_modules/@jridgewell/gen-mapping/types/types.d.cts.map b/dg-ui/node_modules/@jridgewell/gen-mapping/types/types.d.cts.map new file mode 100644 index 0000000..159e734 --- /dev/null +++ b/dg-ui/node_modules/@jridgewell/gen-mapping/types/types.d.cts.map @@ -0,0 +1 @@ +{"version":3,"file":"types.d.ts","sourceRoot":"","sources":["../src/types.ts"],"names":[],"mappings":"AACA,OAAO,KAAK,EAAE,gBAAgB,EAAE,MAAM,qBAAqB,CAAC;AAE5D,MAAM,WAAW,WAAW;IAC1B,IAAI,CAAC,EAAE,MAAM,GAAG,IAAI,CAAC;IACrB,KAAK,EAAE,SAAS,MAAM,EAAE,CAAC;IACzB,UAAU,CAAC,EAAE,MAAM,CAAC;IACpB,OAAO,EAAE,SAAS,CAAC,MAAM,GAAG,IAAI,CAAC,EAAE,CAAC;IACpC,cAAc,CAAC,EAAE,SAAS,CAAC,MAAM,GAAG,IAAI,CAAC,EAAE,CAAC;IAC5C,OAAO,EAAE,CAAC,CAAC;IACX,UAAU,CAAC,EAAE,SAAS,MAAM,EAAE,CAAC;CAChC;AAED,MAAM,WAAW,gBAAiB,SAAQ,WAAW;IACnD,QAAQ,EAAE,MAAM,CAAC;CAGlB;AAED,MAAM,WAAW,gBAAiB,SAAQ,WAAW;IACnD,QAAQ,EAAE,SAAS,gBAAgB,EAAE,EAAE,CAAC;CAGzC;AAED,MAAM,WAAW,GAAG;IAClB,IAAI,EAAE,MAAM,CAAC;IACb,MAAM,EAAE,MAAM,CAAC;CAChB;AAED,MAAM,WAAW,WAAY,SAAQ,GAAG;IACtC,MAAM,EAAE,MAAM,CAAC;CAChB;AAED,MAAM,WAAW,sBAAsB;IACrC,KAAK,EAAE,GAAG,CAAC;IACX,UAAU,EAAE,MAAM,CAAC;CACpB;AAKD,MAAM,MAAM,OAAO,GACf;IACE,SAAS,EAAE,GAAG,CAAC;IACf,MAAM,EAAE,SAAS,CAAC;IAClB,QAAQ,EAAE,SAAS,CAAC;IACpB,IAAI,EAAE,SAAS,CAAC;CACjB,GACD;IACE,SAAS,EAAE,GAAG,CAAC;IACf,MAAM,EAAE,MAAM,CAAC;IACf,QAAQ,EAAE,GAAG,CAAC;IACd,IAAI,EAAE,MAAM,CAAC;CACd,GACD;IACE,SAAS,EAAE,GAAG,CAAC;IACf,MAAM,EAAE,MAAM,CAAC;IACf,QAAQ,EAAE,GAAG,CAAC;IACd,IAAI,EAAE,SAAS,CAAC;CACjB,CAAC"} \ No newline at end of file diff --git a/dg-ui/node_modules/@jridgewell/gen-mapping/types/types.d.mts b/dg-ui/node_modules/@jridgewell/gen-mapping/types/types.d.mts new file mode 100644 index 0000000..e9837eb --- /dev/null +++ b/dg-ui/node_modules/@jridgewell/gen-mapping/types/types.d.mts @@ -0,0 +1,44 @@ +import type { SourceMapSegment } from './sourcemap-segment.mts'; +export interface SourceMapV3 { + file?: string | null; + names: readonly string[]; + sourceRoot?: string; + sources: readonly (string | null)[]; + sourcesContent?: readonly (string | null)[]; + version: 3; + ignoreList?: readonly number[]; +} +export interface EncodedSourceMap extends SourceMapV3 { + mappings: string; +} +export interface DecodedSourceMap extends SourceMapV3 { + mappings: readonly SourceMapSegment[][]; +} +export interface Pos { + line: number; + column: number; +} +export interface OriginalPos extends Pos { + source: string; +} +export interface BindingExpressionRange { + start: Pos; + expression: string; +} +export type Mapping = { + generated: Pos; + source: undefined; + original: undefined; + name: undefined; +} | { + generated: Pos; + source: string; + original: Pos; + name: string; +} | { + generated: Pos; + source: string; + original: Pos; + name: undefined; +}; +//# sourceMappingURL=types.d.ts.map \ No newline at end of file diff --git a/dg-ui/node_modules/@jridgewell/gen-mapping/types/types.d.mts.map b/dg-ui/node_modules/@jridgewell/gen-mapping/types/types.d.mts.map new file mode 100644 index 0000000..159e734 --- /dev/null +++ b/dg-ui/node_modules/@jridgewell/gen-mapping/types/types.d.mts.map @@ -0,0 +1 @@ +{"version":3,"file":"types.d.ts","sourceRoot":"","sources":["../src/types.ts"],"names":[],"mappings":"AACA,OAAO,KAAK,EAAE,gBAAgB,EAAE,MAAM,qBAAqB,CAAC;AAE5D,MAAM,WAAW,WAAW;IAC1B,IAAI,CAAC,EAAE,MAAM,GAAG,IAAI,CAAC;IACrB,KAAK,EAAE,SAAS,MAAM,EAAE,CAAC;IACzB,UAAU,CAAC,EAAE,MAAM,CAAC;IACpB,OAAO,EAAE,SAAS,CAAC,MAAM,GAAG,IAAI,CAAC,EAAE,CAAC;IACpC,cAAc,CAAC,EAAE,SAAS,CAAC,MAAM,GAAG,IAAI,CAAC,EAAE,CAAC;IAC5C,OAAO,EAAE,CAAC,CAAC;IACX,UAAU,CAAC,EAAE,SAAS,MAAM,EAAE,CAAC;CAChC;AAED,MAAM,WAAW,gBAAiB,SAAQ,WAAW;IACnD,QAAQ,EAAE,MAAM,CAAC;CAGlB;AAED,MAAM,WAAW,gBAAiB,SAAQ,WAAW;IACnD,QAAQ,EAAE,SAAS,gBAAgB,EAAE,EAAE,CAAC;CAGzC;AAED,MAAM,WAAW,GAAG;IAClB,IAAI,EAAE,MAAM,CAAC;IACb,MAAM,EAAE,MAAM,CAAC;CAChB;AAED,MAAM,WAAW,WAAY,SAAQ,GAAG;IACtC,MAAM,EAAE,MAAM,CAAC;CAChB;AAED,MAAM,WAAW,sBAAsB;IACrC,KAAK,EAAE,GAAG,CAAC;IACX,UAAU,EAAE,MAAM,CAAC;CACpB;AAKD,MAAM,MAAM,OAAO,GACf;IACE,SAAS,EAAE,GAAG,CAAC;IACf,MAAM,EAAE,SAAS,CAAC;IAClB,QAAQ,EAAE,SAAS,CAAC;IACpB,IAAI,EAAE,SAAS,CAAC;CACjB,GACD;IACE,SAAS,EAAE,GAAG,CAAC;IACf,MAAM,EAAE,MAAM,CAAC;IACf,QAAQ,EAAE,GAAG,CAAC;IACd,IAAI,EAAE,MAAM,CAAC;CACd,GACD;IACE,SAAS,EAAE,GAAG,CAAC;IACf,MAAM,EAAE,MAAM,CAAC;IACf,QAAQ,EAAE,GAAG,CAAC;IACd,IAAI,EAAE,SAAS,CAAC;CACjB,CAAC"} \ No newline at end of file diff --git a/dg-ui/node_modules/@jridgewell/remapping/LICENSE b/dg-ui/node_modules/@jridgewell/remapping/LICENSE new file mode 100644 index 0000000..1f6ce94 --- /dev/null +++ b/dg-ui/node_modules/@jridgewell/remapping/LICENSE @@ -0,0 +1,19 @@ +Copyright 2024 Justin Ridgewell + +Permission is hereby granted, free of charge, to any person obtaining a copy +of this software and associated documentation files (the "Software"), to deal +in the Software without restriction, including without limitation the rights +to use, copy, modify, merge, publish, distribute, sublicense, and/or sell +copies of the Software, and to permit persons to whom the Software is +furnished to do so, subject to the following conditions: + +The above copyright notice and this permission notice shall be included in +all copies or substantial portions of the Software. + +THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR +IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, +FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE +AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER +LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, +OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE +SOFTWARE. diff --git a/dg-ui/node_modules/@jridgewell/remapping/README.md b/dg-ui/node_modules/@jridgewell/remapping/README.md new file mode 100644 index 0000000..6d092d7 --- /dev/null +++ b/dg-ui/node_modules/@jridgewell/remapping/README.md @@ -0,0 +1,218 @@ +# @jridgewell/remapping + +> Remap sequential sourcemaps through transformations to point at the original source code + +Remapping allows you to take the sourcemaps generated through transforming your code and "remap" +them to the original source locations. Think "my minified code, transformed with babel and bundled +with webpack", all pointing to the correct location in your original source code. + +With remapping, none of your source code transformations need to be aware of the input's sourcemap, +they only need to generate an output sourcemap. This greatly simplifies building custom +transformations (think a find-and-replace). + +## Installation + +```sh +npm install @jridgewell/remapping +``` + +## Usage + +```typescript +function remapping( + map: SourceMap | SourceMap[], + loader: (file: string, ctx: LoaderContext) => (SourceMap | null | undefined), + options?: { excludeContent: boolean, decodedMappings: boolean } +): SourceMap; + +// LoaderContext gives the loader the importing sourcemap, tree depth, the ability to override the +// "source" location (where child sources are resolved relative to, or the location of original +// source), and the ability to override the "content" of an original source for inclusion in the +// output sourcemap. +type LoaderContext = { + readonly importer: string; + readonly depth: number; + source: string; + content: string | null | undefined; +} +``` + +`remapping` takes the final output sourcemap, and a `loader` function. For every source file pointer +in the sourcemap, the `loader` will be called with the resolved path. If the path itself represents +a transformed file (it has a sourcmap associated with it), then the `loader` should return that +sourcemap. If not, the path will be treated as an original, untransformed source code. + +```js +// Babel transformed "helloworld.js" into "transformed.js" +const transformedMap = JSON.stringify({ + file: 'transformed.js', + // 1st column of 2nd line of output file translates into the 1st source + // file, line 3, column 2 + mappings: ';CAEE', + sources: ['helloworld.js'], + version: 3, +}); + +// Uglify minified "transformed.js" into "transformed.min.js" +const minifiedTransformedMap = JSON.stringify({ + file: 'transformed.min.js', + // 0th column of 1st line of output file translates into the 1st source + // file, line 2, column 1. + mappings: 'AACC', + names: [], + sources: ['transformed.js'], + version: 3, +}); + +const remapped = remapping( + minifiedTransformedMap, + (file, ctx) => { + + // The "transformed.js" file is an transformed file. + if (file === 'transformed.js') { + // The root importer is empty. + console.assert(ctx.importer === ''); + // The depth in the sourcemap tree we're currently loading. + // The root `minifiedTransformedMap` is depth 0, and its source children are depth 1, etc. + console.assert(ctx.depth === 1); + + return transformedMap; + } + + // Loader will be called to load transformedMap's source file pointers as well. + console.assert(file === 'helloworld.js'); + // `transformed.js`'s sourcemap points into `helloworld.js`. + console.assert(ctx.importer === 'transformed.js'); + // This is a source child of `transformed`, which is a source child of `minifiedTransformedMap`. + console.assert(ctx.depth === 2); + return null; + } +); + +console.log(remapped); +// { +// file: 'transpiled.min.js', +// mappings: 'AAEE', +// sources: ['helloworld.js'], +// version: 3, +// }; +``` + +In this example, `loader` will be called twice: + +1. `"transformed.js"`, the first source file pointer in the `minifiedTransformedMap`. We return the + associated sourcemap for it (its a transformed file, after all) so that sourcemap locations can + be traced through it into the source files it represents. +2. `"helloworld.js"`, our original, unmodified source code. This file does not have a sourcemap, so + we return `null`. + +The `remapped` sourcemap now points from `transformed.min.js` into locations in `helloworld.js`. If +you were to read the `mappings`, it says "0th column of the first line output line points to the 1st +column of the 2nd line of the file `helloworld.js`". + +### Multiple transformations of a file + +As a convenience, if you have multiple single-source transformations of a file, you may pass an +array of sourcemap files in the order of most-recent transformation sourcemap first. Note that this +changes the `importer` and `depth` of each call to our loader. So our above example could have been +written as: + +```js +const remapped = remapping( + [minifiedTransformedMap, transformedMap], + () => null +); + +console.log(remapped); +// { +// file: 'transpiled.min.js', +// mappings: 'AAEE', +// sources: ['helloworld.js'], +// version: 3, +// }; +``` + +### Advanced control of the loading graph + +#### `source` + +The `source` property can overridden to any value to change the location of the current load. Eg, +for an original source file, it allows us to change the location to the original source regardless +of what the sourcemap source entry says. And for transformed files, it allows us to change the +relative resolving location for child sources of the loaded sourcemap. + +```js +const remapped = remapping( + minifiedTransformedMap, + (file, ctx) => { + + if (file === 'transformed.js') { + // We pretend the transformed.js file actually exists in the 'src/' directory. When the nested + // source files are loaded, they will now be relative to `src/`. + ctx.source = 'src/transformed.js'; + return transformedMap; + } + + console.assert(file === 'src/helloworld.js'); + // We could futher change the source of this original file, eg, to be inside a nested directory + // itself. This will be reflected in the remapped sourcemap. + ctx.source = 'src/nested/transformed.js'; + return null; + } +); + +console.log(remapped); +// { +// …, +// sources: ['src/nested/helloworld.js'], +// }; +``` + + +#### `content` + +The `content` property can be overridden when we encounter an original source file. Eg, this allows +you to manually provide the source content of the original file regardless of whether the +`sourcesContent` field is present in the parent sourcemap. It can also be set to `null` to remove +the source content. + +```js +const remapped = remapping( + minifiedTransformedMap, + (file, ctx) => { + + if (file === 'transformed.js') { + // transformedMap does not include a `sourcesContent` field, so usually the remapped sourcemap + // would not include any `sourcesContent` values. + return transformedMap; + } + + console.assert(file === 'helloworld.js'); + // We can read the file to provide the source content. + ctx.content = fs.readFileSync(file, 'utf8'); + return null; + } +); + +console.log(remapped); +// { +// …, +// sourcesContent: [ +// 'console.log("Hello world!")', +// ], +// }; +``` + +### Options + +#### excludeContent + +By default, `excludeContent` is `false`. Passing `{ excludeContent: true }` will exclude the +`sourcesContent` field from the returned sourcemap. This is mainly useful when you want to reduce +the size out the sourcemap. + +#### decodedMappings + +By default, `decodedMappings` is `false`. Passing `{ decodedMappings: true }` will leave the +`mappings` field in a [decoded state](https://github.com/rich-harris/sourcemap-codec) instead of +encoding into a VLQ string. diff --git a/dg-ui/node_modules/@jridgewell/remapping/dist/remapping.mjs b/dg-ui/node_modules/@jridgewell/remapping/dist/remapping.mjs new file mode 100644 index 0000000..8b7009c --- /dev/null +++ b/dg-ui/node_modules/@jridgewell/remapping/dist/remapping.mjs @@ -0,0 +1,144 @@ +// src/build-source-map-tree.ts +import { TraceMap } from "@jridgewell/trace-mapping"; + +// src/source-map-tree.ts +import { GenMapping, maybeAddSegment, setIgnore, setSourceContent } from "@jridgewell/gen-mapping"; +import { traceSegment, decodedMappings } from "@jridgewell/trace-mapping"; +var SOURCELESS_MAPPING = /* @__PURE__ */ SegmentObject("", -1, -1, "", null, false); +var EMPTY_SOURCES = []; +function SegmentObject(source, line, column, name, content, ignore) { + return { source, line, column, name, content, ignore }; +} +function Source(map, sources, source, content, ignore) { + return { + map, + sources, + source, + content, + ignore + }; +} +function MapSource(map, sources) { + return Source(map, sources, "", null, false); +} +function OriginalSource(source, content, ignore) { + return Source(null, EMPTY_SOURCES, source, content, ignore); +} +function traceMappings(tree) { + const gen = new GenMapping({ file: tree.map.file }); + const { sources: rootSources, map } = tree; + const rootNames = map.names; + const rootMappings = decodedMappings(map); + for (let i = 0; i < rootMappings.length; i++) { + const segments = rootMappings[i]; + for (let j = 0; j < segments.length; j++) { + const segment = segments[j]; + const genCol = segment[0]; + let traced = SOURCELESS_MAPPING; + if (segment.length !== 1) { + const source2 = rootSources[segment[1]]; + traced = originalPositionFor( + source2, + segment[2], + segment[3], + segment.length === 5 ? rootNames[segment[4]] : "" + ); + if (traced == null) continue; + } + const { column, line, name, content, source, ignore } = traced; + maybeAddSegment(gen, i, genCol, source, line, column, name); + if (source && content != null) setSourceContent(gen, source, content); + if (ignore) setIgnore(gen, source, true); + } + } + return gen; +} +function originalPositionFor(source, line, column, name) { + if (!source.map) { + return SegmentObject(source.source, line, column, name, source.content, source.ignore); + } + const segment = traceSegment(source.map, line, column); + if (segment == null) return null; + if (segment.length === 1) return SOURCELESS_MAPPING; + return originalPositionFor( + source.sources[segment[1]], + segment[2], + segment[3], + segment.length === 5 ? source.map.names[segment[4]] : name + ); +} + +// src/build-source-map-tree.ts +function asArray(value) { + if (Array.isArray(value)) return value; + return [value]; +} +function buildSourceMapTree(input, loader) { + const maps = asArray(input).map((m) => new TraceMap(m, "")); + const map = maps.pop(); + for (let i = 0; i < maps.length; i++) { + if (maps[i].sources.length > 1) { + throw new Error( + `Transformation map ${i} must have exactly one source file. +Did you specify these with the most recent transformation maps first?` + ); + } + } + let tree = build(map, loader, "", 0); + for (let i = maps.length - 1; i >= 0; i--) { + tree = MapSource(maps[i], [tree]); + } + return tree; +} +function build(map, loader, importer, importerDepth) { + const { resolvedSources, sourcesContent, ignoreList } = map; + const depth = importerDepth + 1; + const children = resolvedSources.map((sourceFile, i) => { + const ctx = { + importer, + depth, + source: sourceFile || "", + content: void 0, + ignore: void 0 + }; + const sourceMap = loader(ctx.source, ctx); + const { source, content, ignore } = ctx; + if (sourceMap) return build(new TraceMap(sourceMap, source), loader, source, depth); + const sourceContent = content !== void 0 ? content : sourcesContent ? sourcesContent[i] : null; + const ignored = ignore !== void 0 ? ignore : ignoreList ? ignoreList.includes(i) : false; + return OriginalSource(source, sourceContent, ignored); + }); + return MapSource(map, children); +} + +// src/source-map.ts +import { toDecodedMap, toEncodedMap } from "@jridgewell/gen-mapping"; +var SourceMap = class { + constructor(map, options) { + const out = options.decodedMappings ? toDecodedMap(map) : toEncodedMap(map); + this.version = out.version; + this.file = out.file; + this.mappings = out.mappings; + this.names = out.names; + this.ignoreList = out.ignoreList; + this.sourceRoot = out.sourceRoot; + this.sources = out.sources; + if (!options.excludeContent) { + this.sourcesContent = out.sourcesContent; + } + } + toString() { + return JSON.stringify(this); + } +}; + +// src/remapping.ts +function remapping(input, loader, options) { + const opts = typeof options === "object" ? options : { excludeContent: !!options, decodedMappings: false }; + const tree = buildSourceMapTree(input, loader); + return new SourceMap(traceMappings(tree), opts); +} +export { + remapping as default +}; +//# sourceMappingURL=remapping.mjs.map diff --git a/dg-ui/node_modules/@jridgewell/remapping/dist/remapping.mjs.map b/dg-ui/node_modules/@jridgewell/remapping/dist/remapping.mjs.map new file mode 100644 index 0000000..66801e6 --- /dev/null +++ b/dg-ui/node_modules/@jridgewell/remapping/dist/remapping.mjs.map @@ -0,0 +1,6 @@ +{ + "version": 3, + "sources": ["../src/build-source-map-tree.ts", "../src/source-map-tree.ts", "../src/source-map.ts", "../src/remapping.ts"], + "mappings": ";AAAA,SAAS,gBAAgB;;;ACAzB,SAAS,YAAY,iBAAiB,WAAW,wBAAwB;AACzE,SAAS,cAAc,uBAAuB;AA+B9C,IAAM,qBAAqC,8BAAc,IAAI,IAAI,IAAI,IAAI,MAAM,KAAK;AACpF,IAAM,gBAA2B,CAAC;AAElC,SAAS,cACP,QACA,MACA,QACA,MACA,SACA,QACwB;AACxB,SAAO,EAAE,QAAQ,MAAM,QAAQ,MAAM,SAAS,OAAO;AACvD;AAgBA,SAAS,OACP,KACA,SACA,QACA,SACA,QACS;AACT,SAAO;AAAA,IACL;AAAA,IACA;AAAA,IACA;AAAA,IACA;AAAA,IACA;AAAA,EACF;AACF;AAMO,SAAS,UAAU,KAAe,SAA+B;AACtE,SAAO,OAAO,KAAK,SAAS,IAAI,MAAM,KAAK;AAC7C;AAMO,SAAS,eACd,QACA,SACA,QACgB;AAChB,SAAO,OAAO,MAAM,eAAe,QAAQ,SAAS,MAAM;AAC5D;AAMO,SAAS,cAAc,MAA6B;AAGzD,QAAM,MAAM,IAAI,WAAW,EAAE,MAAM,KAAK,IAAI,KAAK,CAAC;AAClD,QAAM,EAAE,SAAS,aAAa,IAAI,IAAI;AACtC,QAAM,YAAY,IAAI;AACtB,QAAM,eAAe,gBAAgB,GAAG;AAExC,WAAS,IAAI,GAAG,IAAI,aAAa,QAAQ,KAAK;AAC5C,UAAM,WAAW,aAAa,CAAC;AAE/B,aAAS,IAAI,GAAG,IAAI,SAAS,QAAQ,KAAK;AACxC,YAAM,UAAU,SAAS,CAAC;AAC1B,YAAM,SAAS,QAAQ,CAAC;AACxB,UAAI,SAAwC;AAI5C,UAAI,QAAQ,WAAW,GAAG;AACxB,cAAMA,UAAS,YAAY,QAAQ,CAAC,CAAC;AACrC,iBAAS;AAAA,UACPA;AAAA,UACA,QAAQ,CAAC;AAAA,UACT,QAAQ,CAAC;AAAA,UACT,QAAQ,WAAW,IAAI,UAAU,QAAQ,CAAC,CAAC,IAAI;AAAA,QACjD;AAIA,YAAI,UAAU,KAAM;AAAA,MACtB;AAEA,YAAM,EAAE,QAAQ,MAAM,MAAM,SAAS,QAAQ,OAAO,IAAI;AAExD,sBAAgB,KAAK,GAAG,QAAQ,QAAQ,MAAM,QAAQ,IAAI;AAC1D,UAAI,UAAU,WAAW,KAAM,kBAAiB,KAAK,QAAQ,OAAO;AACpE,UAAI,OAAQ,WAAU,KAAK,QAAQ,IAAI;AAAA,IACzC;AAAA,EACF;AAEA,SAAO;AACT;AAMO,SAAS,oBACd,QACA,MACA,QACA,MAC+B;AAC/B,MAAI,CAAC,OAAO,KAAK;AACf,WAAO,cAAc,OAAO,QAAQ,MAAM,QAAQ,MAAM,OAAO,SAAS,OAAO,MAAM;AAAA,EACvF;AAEA,QAAM,UAAU,aAAa,OAAO,KAAK,MAAM,MAAM;AAGrD,MAAI,WAAW,KAAM,QAAO;AAG5B,MAAI,QAAQ,WAAW,EAAG,QAAO;AAEjC,SAAO;AAAA,IACL,OAAO,QAAQ,QAAQ,CAAC,CAAC;AAAA,IACzB,QAAQ,CAAC;AAAA,IACT,QAAQ,CAAC;AAAA,IACT,QAAQ,WAAW,IAAI,OAAO,IAAI,MAAM,QAAQ,CAAC,CAAC,IAAI;AAAA,EACxD;AACF;;;ADpKA,SAAS,QAAW,OAAqB;AACvC,MAAI,MAAM,QAAQ,KAAK,EAAG,QAAO;AACjC,SAAO,CAAC,KAAK;AACf;AAae,SAAR,mBACL,OACA,QACe;AACf,QAAM,OAAO,QAAQ,KAAK,EAAE,IAAI,CAAC,MAAM,IAAI,SAAS,GAAG,EAAE,CAAC;AAC1D,QAAM,MAAM,KAAK,IAAI;AAErB,WAAS,IAAI,GAAG,IAAI,KAAK,QAAQ,KAAK;AACpC,QAAI,KAAK,CAAC,EAAE,QAAQ,SAAS,GAAG;AAC9B,YAAM,IAAI;AAAA,QACR,sBAAsB,CAAC;AAAA;AAAA,MAEzB;AAAA,IACF;AAAA,EACF;AAEA,MAAI,OAAO,MAAM,KAAK,QAAQ,IAAI,CAAC;AACnC,WAAS,IAAI,KAAK,SAAS,GAAG,KAAK,GAAG,KAAK;AACzC,WAAO,UAAU,KAAK,CAAC,GAAG,CAAC,IAAI,CAAC;AAAA,EAClC;AACA,SAAO;AACT;AAEA,SAAS,MACP,KACA,QACA,UACA,eACe;AACf,QAAM,EAAE,iBAAiB,gBAAgB,WAAW,IAAI;AAExD,QAAM,QAAQ,gBAAgB;AAC9B,QAAM,WAAW,gBAAgB,IAAI,CAAC,YAA2B,MAAuB;AAKtF,UAAM,MAAqB;AAAA,MACzB;AAAA,MACA;AAAA,MACA,QAAQ,cAAc;AAAA,MACtB,SAAS;AAAA,MACT,QAAQ;AAAA,IACV;AAIA,UAAM,YAAY,OAAO,IAAI,QAAQ,GAAG;AAExC,UAAM,EAAE,QAAQ,SAAS,OAAO,IAAI;AAGpC,QAAI,UAAW,QAAO,MAAM,IAAI,SAAS,WAAW,MAAM,GAAG,QAAQ,QAAQ,KAAK;AAMlF,UAAM,gBACJ,YAAY,SAAY,UAAU,iBAAiB,eAAe,CAAC,IAAI;AACzE,UAAM,UAAU,WAAW,SAAY,SAAS,aAAa,WAAW,SAAS,CAAC,IAAI;AACtF,WAAO,eAAe,QAAQ,eAAe,OAAO;AAAA,EACtD,CAAC;AAED,SAAO,UAAU,KAAK,QAAQ;AAChC;;;AExFA,SAAS,cAAc,oBAAoB;AAS3C,IAAqB,YAArB,MAA+B;AAAA,EAU7B,YAAY,KAAiB,SAAkB;AAC7C,UAAM,MAAM,QAAQ,kBAAkB,aAAa,GAAG,IAAI,aAAa,GAAG;AAC1E,SAAK,UAAU,IAAI;AACnB,SAAK,OAAO,IAAI;AAChB,SAAK,WAAW,IAAI;AACpB,SAAK,QAAQ,IAAI;AACjB,SAAK,aAAa,IAAI;AACtB,SAAK,aAAa,IAAI;AAEtB,SAAK,UAAU,IAAI;AACnB,QAAI,CAAC,QAAQ,gBAAgB;AAC3B,WAAK,iBAAiB,IAAI;AAAA,IAC5B;AAAA,EACF;AAAA,EAEA,WAAmB;AACjB,WAAO,KAAK,UAAU,IAAI;AAAA,EAC5B;AACF;;;ACLe,SAAR,UACL,OACA,QACA,SACW;AACX,QAAM,OACJ,OAAO,YAAY,WAAW,UAAU,EAAE,gBAAgB,CAAC,CAAC,SAAS,iBAAiB,MAAM;AAC9F,QAAM,OAAO,mBAAmB,OAAO,MAAM;AAC7C,SAAO,IAAI,UAAU,cAAc,IAAI,GAAG,IAAI;AAChD;", + "names": ["source"] +} diff --git a/dg-ui/node_modules/@jridgewell/remapping/dist/remapping.umd.js b/dg-ui/node_modules/@jridgewell/remapping/dist/remapping.umd.js new file mode 100644 index 0000000..077eb4d --- /dev/null +++ b/dg-ui/node_modules/@jridgewell/remapping/dist/remapping.umd.js @@ -0,0 +1,212 @@ +(function (global, factory) { + if (typeof exports === 'object' && typeof module !== 'undefined') { + factory(module, require('@jridgewell/gen-mapping'), require('@jridgewell/trace-mapping')); + module.exports = def(module); + } else if (typeof define === 'function' && define.amd) { + define(['module', '@jridgewell/gen-mapping', '@jridgewell/trace-mapping'], function(mod) { + factory.apply(this, arguments); + mod.exports = def(mod); + }); + } else { + const mod = { exports: {} }; + factory(mod, global.genMapping, global.traceMapping); + global = typeof globalThis !== 'undefined' ? globalThis : global || self; + global.remapping = def(mod); + } + function def(m) { return 'default' in m.exports ? m.exports.default : m.exports; } +})(this, (function (module, require_genMapping, require_traceMapping) { +"use strict"; +var __create = Object.create; +var __defProp = Object.defineProperty; +var __getOwnPropDesc = Object.getOwnPropertyDescriptor; +var __getOwnPropNames = Object.getOwnPropertyNames; +var __getProtoOf = Object.getPrototypeOf; +var __hasOwnProp = Object.prototype.hasOwnProperty; +var __commonJS = (cb, mod) => function __require() { + return mod || (0, cb[__getOwnPropNames(cb)[0]])((mod = { exports: {} }).exports, mod), mod.exports; +}; +var __export = (target, all) => { + for (var name in all) + __defProp(target, name, { get: all[name], enumerable: true }); +}; +var __copyProps = (to, from, except, desc) => { + if (from && typeof from === "object" || typeof from === "function") { + for (let key of __getOwnPropNames(from)) + if (!__hasOwnProp.call(to, key) && key !== except) + __defProp(to, key, { get: () => from[key], enumerable: !(desc = __getOwnPropDesc(from, key)) || desc.enumerable }); + } + return to; +}; +var __toESM = (mod, isNodeMode, target) => (target = mod != null ? __create(__getProtoOf(mod)) : {}, __copyProps( + // If the importer is in node compatibility mode or this is not an ESM + // file that has been converted to a CommonJS file using a Babel- + // compatible transform (i.e. "__esModule" has not been set), then set + // "default" to the CommonJS "module.exports" for node compatibility. + isNodeMode || !mod || !mod.__esModule ? __defProp(target, "default", { value: mod, enumerable: true }) : target, + mod +)); +var __toCommonJS = (mod) => __copyProps(__defProp({}, "__esModule", { value: true }), mod); + +// umd:@jridgewell/trace-mapping +var require_trace_mapping = __commonJS({ + "umd:@jridgewell/trace-mapping"(exports, module2) { + module2.exports = require_traceMapping; + } +}); + +// umd:@jridgewell/gen-mapping +var require_gen_mapping = __commonJS({ + "umd:@jridgewell/gen-mapping"(exports, module2) { + module2.exports = require_genMapping; + } +}); + +// src/remapping.ts +var remapping_exports = {}; +__export(remapping_exports, { + default: () => remapping +}); +module.exports = __toCommonJS(remapping_exports); + +// src/build-source-map-tree.ts +var import_trace_mapping2 = __toESM(require_trace_mapping()); + +// src/source-map-tree.ts +var import_gen_mapping = __toESM(require_gen_mapping()); +var import_trace_mapping = __toESM(require_trace_mapping()); +var SOURCELESS_MAPPING = /* @__PURE__ */ SegmentObject("", -1, -1, "", null, false); +var EMPTY_SOURCES = []; +function SegmentObject(source, line, column, name, content, ignore) { + return { source, line, column, name, content, ignore }; +} +function Source(map, sources, source, content, ignore) { + return { + map, + sources, + source, + content, + ignore + }; +} +function MapSource(map, sources) { + return Source(map, sources, "", null, false); +} +function OriginalSource(source, content, ignore) { + return Source(null, EMPTY_SOURCES, source, content, ignore); +} +function traceMappings(tree) { + const gen = new import_gen_mapping.GenMapping({ file: tree.map.file }); + const { sources: rootSources, map } = tree; + const rootNames = map.names; + const rootMappings = (0, import_trace_mapping.decodedMappings)(map); + for (let i = 0; i < rootMappings.length; i++) { + const segments = rootMappings[i]; + for (let j = 0; j < segments.length; j++) { + const segment = segments[j]; + const genCol = segment[0]; + let traced = SOURCELESS_MAPPING; + if (segment.length !== 1) { + const source2 = rootSources[segment[1]]; + traced = originalPositionFor( + source2, + segment[2], + segment[3], + segment.length === 5 ? rootNames[segment[4]] : "" + ); + if (traced == null) continue; + } + const { column, line, name, content, source, ignore } = traced; + (0, import_gen_mapping.maybeAddSegment)(gen, i, genCol, source, line, column, name); + if (source && content != null) (0, import_gen_mapping.setSourceContent)(gen, source, content); + if (ignore) (0, import_gen_mapping.setIgnore)(gen, source, true); + } + } + return gen; +} +function originalPositionFor(source, line, column, name) { + if (!source.map) { + return SegmentObject(source.source, line, column, name, source.content, source.ignore); + } + const segment = (0, import_trace_mapping.traceSegment)(source.map, line, column); + if (segment == null) return null; + if (segment.length === 1) return SOURCELESS_MAPPING; + return originalPositionFor( + source.sources[segment[1]], + segment[2], + segment[3], + segment.length === 5 ? source.map.names[segment[4]] : name + ); +} + +// src/build-source-map-tree.ts +function asArray(value) { + if (Array.isArray(value)) return value; + return [value]; +} +function buildSourceMapTree(input, loader) { + const maps = asArray(input).map((m) => new import_trace_mapping2.TraceMap(m, "")); + const map = maps.pop(); + for (let i = 0; i < maps.length; i++) { + if (maps[i].sources.length > 1) { + throw new Error( + `Transformation map ${i} must have exactly one source file. +Did you specify these with the most recent transformation maps first?` + ); + } + } + let tree = build(map, loader, "", 0); + for (let i = maps.length - 1; i >= 0; i--) { + tree = MapSource(maps[i], [tree]); + } + return tree; +} +function build(map, loader, importer, importerDepth) { + const { resolvedSources, sourcesContent, ignoreList } = map; + const depth = importerDepth + 1; + const children = resolvedSources.map((sourceFile, i) => { + const ctx = { + importer, + depth, + source: sourceFile || "", + content: void 0, + ignore: void 0 + }; + const sourceMap = loader(ctx.source, ctx); + const { source, content, ignore } = ctx; + if (sourceMap) return build(new import_trace_mapping2.TraceMap(sourceMap, source), loader, source, depth); + const sourceContent = content !== void 0 ? content : sourcesContent ? sourcesContent[i] : null; + const ignored = ignore !== void 0 ? ignore : ignoreList ? ignoreList.includes(i) : false; + return OriginalSource(source, sourceContent, ignored); + }); + return MapSource(map, children); +} + +// src/source-map.ts +var import_gen_mapping2 = __toESM(require_gen_mapping()); +var SourceMap = class { + constructor(map, options) { + const out = options.decodedMappings ? (0, import_gen_mapping2.toDecodedMap)(map) : (0, import_gen_mapping2.toEncodedMap)(map); + this.version = out.version; + this.file = out.file; + this.mappings = out.mappings; + this.names = out.names; + this.ignoreList = out.ignoreList; + this.sourceRoot = out.sourceRoot; + this.sources = out.sources; + if (!options.excludeContent) { + this.sourcesContent = out.sourcesContent; + } + } + toString() { + return JSON.stringify(this); + } +}; + +// src/remapping.ts +function remapping(input, loader, options) { + const opts = typeof options === "object" ? options : { excludeContent: !!options, decodedMappings: false }; + const tree = buildSourceMapTree(input, loader); + return new SourceMap(traceMappings(tree), opts); +} +})); +//# sourceMappingURL=remapping.umd.js.map diff --git a/dg-ui/node_modules/@jridgewell/remapping/dist/remapping.umd.js.map b/dg-ui/node_modules/@jridgewell/remapping/dist/remapping.umd.js.map new file mode 100644 index 0000000..d5e0786 --- /dev/null +++ b/dg-ui/node_modules/@jridgewell/remapping/dist/remapping.umd.js.map @@ -0,0 +1,6 @@ +{ + "version": 3, + "sources": ["umd:@jridgewell/trace-mapping", "umd:@jridgewell/gen-mapping", "../src/remapping.ts", "../src/build-source-map-tree.ts", "../src/source-map-tree.ts", "../src/source-map.ts"], + "mappings": ";;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;AAAA;AAAA,2CAAAA,SAAA;AAAA,IAAAA,QAAO,UAAU;AAAA;AAAA;;;ACAjB;AAAA,yCAAAC,SAAA;AAAA,IAAAA,QAAO,UAAU;AAAA;AAAA;;;ACAjB;AAAA;AAAA;AAAA;AAAA;;;ACAA,IAAAC,wBAAyB;;;ACAzB,yBAAyE;AACzE,2BAA8C;AA+B9C,IAAM,qBAAqC,8BAAc,IAAI,IAAI,IAAI,IAAI,MAAM,KAAK;AACpF,IAAM,gBAA2B,CAAC;AAElC,SAAS,cACP,QACA,MACA,QACA,MACA,SACA,QACwB;AACxB,SAAO,EAAE,QAAQ,MAAM,QAAQ,MAAM,SAAS,OAAO;AACvD;AAgBA,SAAS,OACP,KACA,SACA,QACA,SACA,QACS;AACT,SAAO;AAAA,IACL;AAAA,IACA;AAAA,IACA;AAAA,IACA;AAAA,IACA;AAAA,EACF;AACF;AAMO,SAAS,UAAU,KAAe,SAA+B;AACtE,SAAO,OAAO,KAAK,SAAS,IAAI,MAAM,KAAK;AAC7C;AAMO,SAAS,eACd,QACA,SACA,QACgB;AAChB,SAAO,OAAO,MAAM,eAAe,QAAQ,SAAS,MAAM;AAC5D;AAMO,SAAS,cAAc,MAA6B;AAGzD,QAAM,MAAM,IAAI,8BAAW,EAAE,MAAM,KAAK,IAAI,KAAK,CAAC;AAClD,QAAM,EAAE,SAAS,aAAa,IAAI,IAAI;AACtC,QAAM,YAAY,IAAI;AACtB,QAAM,mBAAe,sCAAgB,GAAG;AAExC,WAAS,IAAI,GAAG,IAAI,aAAa,QAAQ,KAAK;AAC5C,UAAM,WAAW,aAAa,CAAC;AAE/B,aAAS,IAAI,GAAG,IAAI,SAAS,QAAQ,KAAK;AACxC,YAAM,UAAU,SAAS,CAAC;AAC1B,YAAM,SAAS,QAAQ,CAAC;AACxB,UAAI,SAAwC;AAI5C,UAAI,QAAQ,WAAW,GAAG;AACxB,cAAMC,UAAS,YAAY,QAAQ,CAAC,CAAC;AACrC,iBAAS;AAAA,UACPA;AAAA,UACA,QAAQ,CAAC;AAAA,UACT,QAAQ,CAAC;AAAA,UACT,QAAQ,WAAW,IAAI,UAAU,QAAQ,CAAC,CAAC,IAAI;AAAA,QACjD;AAIA,YAAI,UAAU,KAAM;AAAA,MACtB;AAEA,YAAM,EAAE,QAAQ,MAAM,MAAM,SAAS,QAAQ,OAAO,IAAI;AAExD,8CAAgB,KAAK,GAAG,QAAQ,QAAQ,MAAM,QAAQ,IAAI;AAC1D,UAAI,UAAU,WAAW,KAAM,0CAAiB,KAAK,QAAQ,OAAO;AACpE,UAAI,OAAQ,mCAAU,KAAK,QAAQ,IAAI;AAAA,IACzC;AAAA,EACF;AAEA,SAAO;AACT;AAMO,SAAS,oBACd,QACA,MACA,QACA,MAC+B;AAC/B,MAAI,CAAC,OAAO,KAAK;AACf,WAAO,cAAc,OAAO,QAAQ,MAAM,QAAQ,MAAM,OAAO,SAAS,OAAO,MAAM;AAAA,EACvF;AAEA,QAAM,cAAU,mCAAa,OAAO,KAAK,MAAM,MAAM;AAGrD,MAAI,WAAW,KAAM,QAAO;AAG5B,MAAI,QAAQ,WAAW,EAAG,QAAO;AAEjC,SAAO;AAAA,IACL,OAAO,QAAQ,QAAQ,CAAC,CAAC;AAAA,IACzB,QAAQ,CAAC;AAAA,IACT,QAAQ,CAAC;AAAA,IACT,QAAQ,WAAW,IAAI,OAAO,IAAI,MAAM,QAAQ,CAAC,CAAC,IAAI;AAAA,EACxD;AACF;;;ADpKA,SAAS,QAAW,OAAqB;AACvC,MAAI,MAAM,QAAQ,KAAK,EAAG,QAAO;AACjC,SAAO,CAAC,KAAK;AACf;AAae,SAAR,mBACL,OACA,QACe;AACf,QAAM,OAAO,QAAQ,KAAK,EAAE,IAAI,CAAC,MAAM,IAAI,+BAAS,GAAG,EAAE,CAAC;AAC1D,QAAM,MAAM,KAAK,IAAI;AAErB,WAAS,IAAI,GAAG,IAAI,KAAK,QAAQ,KAAK;AACpC,QAAI,KAAK,CAAC,EAAE,QAAQ,SAAS,GAAG;AAC9B,YAAM,IAAI;AAAA,QACR,sBAAsB,CAAC;AAAA;AAAA,MAEzB;AAAA,IACF;AAAA,EACF;AAEA,MAAI,OAAO,MAAM,KAAK,QAAQ,IAAI,CAAC;AACnC,WAAS,IAAI,KAAK,SAAS,GAAG,KAAK,GAAG,KAAK;AACzC,WAAO,UAAU,KAAK,CAAC,GAAG,CAAC,IAAI,CAAC;AAAA,EAClC;AACA,SAAO;AACT;AAEA,SAAS,MACP,KACA,QACA,UACA,eACe;AACf,QAAM,EAAE,iBAAiB,gBAAgB,WAAW,IAAI;AAExD,QAAM,QAAQ,gBAAgB;AAC9B,QAAM,WAAW,gBAAgB,IAAI,CAAC,YAA2B,MAAuB;AAKtF,UAAM,MAAqB;AAAA,MACzB;AAAA,MACA;AAAA,MACA,QAAQ,cAAc;AAAA,MACtB,SAAS;AAAA,MACT,QAAQ;AAAA,IACV;AAIA,UAAM,YAAY,OAAO,IAAI,QAAQ,GAAG;AAExC,UAAM,EAAE,QAAQ,SAAS,OAAO,IAAI;AAGpC,QAAI,UAAW,QAAO,MAAM,IAAI,+BAAS,WAAW,MAAM,GAAG,QAAQ,QAAQ,KAAK;AAMlF,UAAM,gBACJ,YAAY,SAAY,UAAU,iBAAiB,eAAe,CAAC,IAAI;AACzE,UAAM,UAAU,WAAW,SAAY,SAAS,aAAa,WAAW,SAAS,CAAC,IAAI;AACtF,WAAO,eAAe,QAAQ,eAAe,OAAO;AAAA,EACtD,CAAC;AAED,SAAO,UAAU,KAAK,QAAQ;AAChC;;;AExFA,IAAAC,sBAA2C;AAS3C,IAAqB,YAArB,MAA+B;AAAA,EAU7B,YAAY,KAAiB,SAAkB;AAC7C,UAAM,MAAM,QAAQ,sBAAkB,kCAAa,GAAG,QAAI,kCAAa,GAAG;AAC1E,SAAK,UAAU,IAAI;AACnB,SAAK,OAAO,IAAI;AAChB,SAAK,WAAW,IAAI;AACpB,SAAK,QAAQ,IAAI;AACjB,SAAK,aAAa,IAAI;AACtB,SAAK,aAAa,IAAI;AAEtB,SAAK,UAAU,IAAI;AACnB,QAAI,CAAC,QAAQ,gBAAgB;AAC3B,WAAK,iBAAiB,IAAI;AAAA,IAC5B;AAAA,EACF;AAAA,EAEA,WAAmB;AACjB,WAAO,KAAK,UAAU,IAAI;AAAA,EAC5B;AACF;;;AHLe,SAAR,UACL,OACA,QACA,SACW;AACX,QAAM,OACJ,OAAO,YAAY,WAAW,UAAU,EAAE,gBAAgB,CAAC,CAAC,SAAS,iBAAiB,MAAM;AAC9F,QAAM,OAAO,mBAAmB,OAAO,MAAM;AAC7C,SAAO,IAAI,UAAU,cAAc,IAAI,GAAG,IAAI;AAChD;", + "names": ["module", "module", "import_trace_mapping", "source", "import_gen_mapping"] +} diff --git a/dg-ui/node_modules/@jridgewell/remapping/package.json b/dg-ui/node_modules/@jridgewell/remapping/package.json new file mode 100644 index 0000000..ed00441 --- /dev/null +++ b/dg-ui/node_modules/@jridgewell/remapping/package.json @@ -0,0 +1,71 @@ +{ + "name": "@jridgewell/remapping", + "version": "2.3.5", + "description": "Remap sequential sourcemaps through transformations to point at the original source code", + "keywords": [ + "source", + "map", + "remap" + ], + "main": "dist/remapping.umd.js", + "module": "dist/remapping.mjs", + "types": "types/remapping.d.cts", + "files": [ + "dist", + "src", + "types" + ], + "exports": { + ".": [ + { + "import": { + "types": "./types/remapping.d.mts", + "default": "./dist/remapping.mjs" + }, + "default": { + "types": "./types/remapping.d.cts", + "default": "./dist/remapping.umd.js" + } + }, + "./dist/remapping.umd.js" + ], + "./package.json": "./package.json" + }, + "scripts": { + "benchmark": "run-s build:code benchmark:*", + "benchmark:install": "cd benchmark && npm install", + "benchmark:only": "node --expose-gc benchmark/index.js", + "build": "run-s -n build:code build:types", + "build:code": "node ../../esbuild.mjs remapping.ts", + "build:types": "run-s build:types:force build:types:emit build:types:mts", + "build:types:force": "rimraf tsconfig.build.tsbuildinfo", + "build:types:emit": "tsc --project tsconfig.build.json", + "build:types:mts": "node ../../mts-types.mjs", + "clean": "run-s -n clean:code clean:types", + "clean:code": "tsc --build --clean tsconfig.build.json", + "clean:types": "rimraf dist types", + "test": "run-s -n test:types test:only test:format", + "test:format": "prettier --check '{src,test}/**/*.ts'", + "test:only": "mocha", + "test:types": "eslint '{src,test}/**/*.ts'", + "lint": "run-s -n lint:types lint:format", + "lint:format": "npm run test:format -- --write", + "lint:types": "npm run test:types -- --fix", + "prepublishOnly": "npm run-s -n build test" + }, + "homepage": "https://github.com/jridgewell/sourcemaps/tree/main/packages/remapping", + "repository": { + "type": "git", + "url": "git+https://github.com/jridgewell/sourcemaps.git", + "directory": "packages/remapping" + }, + "author": "Justin Ridgewell ", + "license": "MIT", + "dependencies": { + "@jridgewell/gen-mapping": "^0.3.5", + "@jridgewell/trace-mapping": "^0.3.24" + }, + "devDependencies": { + "source-map": "0.6.1" + } +} diff --git a/dg-ui/node_modules/@jridgewell/remapping/src/build-source-map-tree.ts b/dg-ui/node_modules/@jridgewell/remapping/src/build-source-map-tree.ts new file mode 100644 index 0000000..3e0262b --- /dev/null +++ b/dg-ui/node_modules/@jridgewell/remapping/src/build-source-map-tree.ts @@ -0,0 +1,89 @@ +import { TraceMap } from '@jridgewell/trace-mapping'; + +import { OriginalSource, MapSource } from './source-map-tree'; + +import type { Sources, MapSource as MapSourceType } from './source-map-tree'; +import type { SourceMapInput, SourceMapLoader, LoaderContext } from './types'; + +function asArray(value: T | T[]): T[] { + if (Array.isArray(value)) return value; + return [value]; +} + +/** + * Recursively builds a tree structure out of sourcemap files, with each node + * being either an `OriginalSource` "leaf" or a `SourceMapTree` composed of + * `OriginalSource`s and `SourceMapTree`s. + * + * Every sourcemap is composed of a collection of source files and mappings + * into locations of those source files. When we generate a `SourceMapTree` for + * the sourcemap, we attempt to load each source file's own sourcemap. If it + * does not have an associated sourcemap, it is considered an original, + * unmodified source file. + */ +export default function buildSourceMapTree( + input: SourceMapInput | SourceMapInput[], + loader: SourceMapLoader, +): MapSourceType { + const maps = asArray(input).map((m) => new TraceMap(m, '')); + const map = maps.pop()!; + + for (let i = 0; i < maps.length; i++) { + if (maps[i].sources.length > 1) { + throw new Error( + `Transformation map ${i} must have exactly one source file.\n` + + 'Did you specify these with the most recent transformation maps first?', + ); + } + } + + let tree = build(map, loader, '', 0); + for (let i = maps.length - 1; i >= 0; i--) { + tree = MapSource(maps[i], [tree]); + } + return tree; +} + +function build( + map: TraceMap, + loader: SourceMapLoader, + importer: string, + importerDepth: number, +): MapSourceType { + const { resolvedSources, sourcesContent, ignoreList } = map; + + const depth = importerDepth + 1; + const children = resolvedSources.map((sourceFile: string | null, i: number): Sources => { + // The loading context gives the loader more information about why this file is being loaded + // (eg, from which importer). It also allows the loader to override the location of the loaded + // sourcemap/original source, or to override the content in the sourcesContent field if it's + // an unmodified source file. + const ctx: LoaderContext = { + importer, + depth, + source: sourceFile || '', + content: undefined, + ignore: undefined, + }; + + // Use the provided loader callback to retrieve the file's sourcemap. + // TODO: We should eventually support async loading of sourcemap files. + const sourceMap = loader(ctx.source, ctx); + + const { source, content, ignore } = ctx; + + // If there is a sourcemap, then we need to recurse into it to load its source files. + if (sourceMap) return build(new TraceMap(sourceMap, source), loader, source, depth); + + // Else, it's an unmodified source file. + // The contents of this unmodified source file can be overridden via the loader context, + // allowing it to be explicitly null or a string. If it remains undefined, we fall back to + // the importing sourcemap's `sourcesContent` field. + const sourceContent = + content !== undefined ? content : sourcesContent ? sourcesContent[i] : null; + const ignored = ignore !== undefined ? ignore : ignoreList ? ignoreList.includes(i) : false; + return OriginalSource(source, sourceContent, ignored); + }); + + return MapSource(map, children); +} diff --git a/dg-ui/node_modules/@jridgewell/remapping/src/remapping.ts b/dg-ui/node_modules/@jridgewell/remapping/src/remapping.ts new file mode 100644 index 0000000..c0f8b0d --- /dev/null +++ b/dg-ui/node_modules/@jridgewell/remapping/src/remapping.ts @@ -0,0 +1,42 @@ +import buildSourceMapTree from './build-source-map-tree'; +import { traceMappings } from './source-map-tree'; +import SourceMap from './source-map'; + +import type { SourceMapInput, SourceMapLoader, Options } from './types'; +export type { + SourceMapSegment, + EncodedSourceMap, + EncodedSourceMap as RawSourceMap, + DecodedSourceMap, + SourceMapInput, + SourceMapLoader, + LoaderContext, + Options, +} from './types'; +export type { SourceMap }; + +/** + * Traces through all the mappings in the root sourcemap, through the sources + * (and their sourcemaps), all the way back to the original source location. + * + * `loader` will be called every time we encounter a source file. If it returns + * a sourcemap, we will recurse into that sourcemap to continue the trace. If + * it returns a falsey value, that source file is treated as an original, + * unmodified source file. + * + * Pass `excludeContent` to exclude any self-containing source file content + * from the output sourcemap. + * + * Pass `decodedMappings` to receive a SourceMap with decoded (instead of + * VLQ encoded) mappings. + */ +export default function remapping( + input: SourceMapInput | SourceMapInput[], + loader: SourceMapLoader, + options?: boolean | Options, +): SourceMap { + const opts = + typeof options === 'object' ? options : { excludeContent: !!options, decodedMappings: false }; + const tree = buildSourceMapTree(input, loader); + return new SourceMap(traceMappings(tree), opts); +} diff --git a/dg-ui/node_modules/@jridgewell/remapping/src/source-map-tree.ts b/dg-ui/node_modules/@jridgewell/remapping/src/source-map-tree.ts new file mode 100644 index 0000000..935240f --- /dev/null +++ b/dg-ui/node_modules/@jridgewell/remapping/src/source-map-tree.ts @@ -0,0 +1,172 @@ +import { GenMapping, maybeAddSegment, setIgnore, setSourceContent } from '@jridgewell/gen-mapping'; +import { traceSegment, decodedMappings } from '@jridgewell/trace-mapping'; + +import type { TraceMap } from '@jridgewell/trace-mapping'; + +export type SourceMapSegmentObject = { + column: number; + line: number; + name: string; + source: string; + content: string | null; + ignore: boolean; +}; + +export type OriginalSource = { + map: null; + sources: Sources[]; + source: string; + content: string | null; + ignore: boolean; +}; + +export type MapSource = { + map: TraceMap; + sources: Sources[]; + source: string; + content: null; + ignore: false; +}; + +export type Sources = OriginalSource | MapSource; + +const SOURCELESS_MAPPING = /* #__PURE__ */ SegmentObject('', -1, -1, '', null, false); +const EMPTY_SOURCES: Sources[] = []; + +function SegmentObject( + source: string, + line: number, + column: number, + name: string, + content: string | null, + ignore: boolean, +): SourceMapSegmentObject { + return { source, line, column, name, content, ignore }; +} + +function Source( + map: TraceMap, + sources: Sources[], + source: '', + content: null, + ignore: false, +): MapSource; +function Source( + map: null, + sources: Sources[], + source: string, + content: string | null, + ignore: boolean, +): OriginalSource; +function Source( + map: TraceMap | null, + sources: Sources[], + source: string | '', + content: string | null, + ignore: boolean, +): Sources { + return { + map, + sources, + source, + content, + ignore, + } as any; +} + +/** + * MapSource represents a single sourcemap, with the ability to trace mappings into its child nodes + * (which may themselves be SourceMapTrees). + */ +export function MapSource(map: TraceMap, sources: Sources[]): MapSource { + return Source(map, sources, '', null, false); +} + +/** + * A "leaf" node in the sourcemap tree, representing an original, unmodified source file. Recursive + * segment tracing ends at the `OriginalSource`. + */ +export function OriginalSource( + source: string, + content: string | null, + ignore: boolean, +): OriginalSource { + return Source(null, EMPTY_SOURCES, source, content, ignore); +} + +/** + * traceMappings is only called on the root level SourceMapTree, and begins the process of + * resolving each mapping in terms of the original source files. + */ +export function traceMappings(tree: MapSource): GenMapping { + // TODO: Eventually support sourceRoot, which has to be removed because the sources are already + // fully resolved. We'll need to make sources relative to the sourceRoot before adding them. + const gen = new GenMapping({ file: tree.map.file }); + const { sources: rootSources, map } = tree; + const rootNames = map.names; + const rootMappings = decodedMappings(map); + + for (let i = 0; i < rootMappings.length; i++) { + const segments = rootMappings[i]; + + for (let j = 0; j < segments.length; j++) { + const segment = segments[j]; + const genCol = segment[0]; + let traced: SourceMapSegmentObject | null = SOURCELESS_MAPPING; + + // 1-length segments only move the current generated column, there's no source information + // to gather from it. + if (segment.length !== 1) { + const source = rootSources[segment[1]]; + traced = originalPositionFor( + source, + segment[2], + segment[3], + segment.length === 5 ? rootNames[segment[4]] : '', + ); + + // If the trace is invalid, then the trace ran into a sourcemap that doesn't contain a + // respective segment into an original source. + if (traced == null) continue; + } + + const { column, line, name, content, source, ignore } = traced; + + maybeAddSegment(gen, i, genCol, source, line, column, name); + if (source && content != null) setSourceContent(gen, source, content); + if (ignore) setIgnore(gen, source, true); + } + } + + return gen; +} + +/** + * originalPositionFor is only called on children SourceMapTrees. It recurses down into its own + * child SourceMapTrees, until we find the original source map. + */ +export function originalPositionFor( + source: Sources, + line: number, + column: number, + name: string, +): SourceMapSegmentObject | null { + if (!source.map) { + return SegmentObject(source.source, line, column, name, source.content, source.ignore); + } + + const segment = traceSegment(source.map, line, column); + + // If we couldn't find a segment, then this doesn't exist in the sourcemap. + if (segment == null) return null; + // 1-length segments only move the current generated column, there's no source information + // to gather from it. + if (segment.length === 1) return SOURCELESS_MAPPING; + + return originalPositionFor( + source.sources[segment[1]], + segment[2], + segment[3], + segment.length === 5 ? source.map.names[segment[4]] : name, + ); +} diff --git a/dg-ui/node_modules/@jridgewell/remapping/src/source-map.ts b/dg-ui/node_modules/@jridgewell/remapping/src/source-map.ts new file mode 100644 index 0000000..5156086 --- /dev/null +++ b/dg-ui/node_modules/@jridgewell/remapping/src/source-map.ts @@ -0,0 +1,38 @@ +import { toDecodedMap, toEncodedMap } from '@jridgewell/gen-mapping'; + +import type { GenMapping } from '@jridgewell/gen-mapping'; +import type { DecodedSourceMap, EncodedSourceMap, Options } from './types'; + +/** + * A SourceMap v3 compatible sourcemap, which only includes fields that were + * provided to it. + */ +export default class SourceMap { + declare file?: string | null; + declare mappings: EncodedSourceMap['mappings'] | DecodedSourceMap['mappings']; + declare sourceRoot?: string; + declare names: string[]; + declare sources: (string | null)[]; + declare sourcesContent?: (string | null)[]; + declare version: 3; + declare ignoreList: number[] | undefined; + + constructor(map: GenMapping, options: Options) { + const out = options.decodedMappings ? toDecodedMap(map) : toEncodedMap(map); + this.version = out.version; // SourceMap spec says this should be first. + this.file = out.file; + this.mappings = out.mappings as SourceMap['mappings']; + this.names = out.names as SourceMap['names']; + this.ignoreList = out.ignoreList as SourceMap['ignoreList']; + this.sourceRoot = out.sourceRoot; + + this.sources = out.sources as SourceMap['sources']; + if (!options.excludeContent) { + this.sourcesContent = out.sourcesContent as SourceMap['sourcesContent']; + } + } + + toString(): string { + return JSON.stringify(this); + } +} diff --git a/dg-ui/node_modules/@jridgewell/remapping/src/types.ts b/dg-ui/node_modules/@jridgewell/remapping/src/types.ts new file mode 100644 index 0000000..384961d --- /dev/null +++ b/dg-ui/node_modules/@jridgewell/remapping/src/types.ts @@ -0,0 +1,27 @@ +import type { SourceMapInput } from '@jridgewell/trace-mapping'; + +export type { + SourceMapSegment, + DecodedSourceMap, + EncodedSourceMap, +} from '@jridgewell/trace-mapping'; + +export type { SourceMapInput }; + +export type LoaderContext = { + readonly importer: string; + readonly depth: number; + source: string; + content: string | null | undefined; + ignore: boolean | undefined; +}; + +export type SourceMapLoader = ( + file: string, + ctx: LoaderContext, +) => SourceMapInput | null | undefined | void; + +export type Options = { + excludeContent?: boolean; + decodedMappings?: boolean; +}; diff --git a/dg-ui/node_modules/@jridgewell/remapping/types/build-source-map-tree.d.cts b/dg-ui/node_modules/@jridgewell/remapping/types/build-source-map-tree.d.cts new file mode 100644 index 0000000..e089aea --- /dev/null +++ b/dg-ui/node_modules/@jridgewell/remapping/types/build-source-map-tree.d.cts @@ -0,0 +1,15 @@ +import type { MapSource as MapSourceType } from './source-map-tree.cts'; +import type { SourceMapInput, SourceMapLoader } from './types.cts'; +/** + * Recursively builds a tree structure out of sourcemap files, with each node + * being either an `OriginalSource` "leaf" or a `SourceMapTree` composed of + * `OriginalSource`s and `SourceMapTree`s. + * + * Every sourcemap is composed of a collection of source files and mappings + * into locations of those source files. When we generate a `SourceMapTree` for + * the sourcemap, we attempt to load each source file's own sourcemap. If it + * does not have an associated sourcemap, it is considered an original, + * unmodified source file. + */ +export = function buildSourceMapTree(input: SourceMapInput | SourceMapInput[], loader: SourceMapLoader): MapSourceType; +//# sourceMappingURL=build-source-map-tree.d.ts.map \ No newline at end of file diff --git a/dg-ui/node_modules/@jridgewell/remapping/types/build-source-map-tree.d.cts.map b/dg-ui/node_modules/@jridgewell/remapping/types/build-source-map-tree.d.cts.map new file mode 100644 index 0000000..38e4290 --- /dev/null +++ b/dg-ui/node_modules/@jridgewell/remapping/types/build-source-map-tree.d.cts.map @@ -0,0 +1 @@ +{"version":3,"file":"build-source-map-tree.d.ts","sourceRoot":"","sources":["../src/build-source-map-tree.ts"],"names":[],"mappings":"AAIA,OAAO,KAAK,EAAW,SAAS,IAAI,aAAa,EAAE,MAAM,mBAAmB,CAAC;AAC7E,OAAO,KAAK,EAAE,cAAc,EAAE,eAAe,EAAiB,MAAM,SAAS,CAAC;AAO9E;;;;;;;;;;GAUG;AACH,MAAM,CAAC,OAAO,UAAU,kBAAkB,CACxC,KAAK,EAAE,cAAc,GAAG,cAAc,EAAE,EACxC,MAAM,EAAE,eAAe,GACtB,aAAa,CAkBf"} \ No newline at end of file diff --git a/dg-ui/node_modules/@jridgewell/remapping/types/build-source-map-tree.d.mts b/dg-ui/node_modules/@jridgewell/remapping/types/build-source-map-tree.d.mts new file mode 100644 index 0000000..746ac5f --- /dev/null +++ b/dg-ui/node_modules/@jridgewell/remapping/types/build-source-map-tree.d.mts @@ -0,0 +1,15 @@ +import type { MapSource as MapSourceType } from './source-map-tree.mts'; +import type { SourceMapInput, SourceMapLoader } from './types.mts'; +/** + * Recursively builds a tree structure out of sourcemap files, with each node + * being either an `OriginalSource` "leaf" or a `SourceMapTree` composed of + * `OriginalSource`s and `SourceMapTree`s. + * + * Every sourcemap is composed of a collection of source files and mappings + * into locations of those source files. When we generate a `SourceMapTree` for + * the sourcemap, we attempt to load each source file's own sourcemap. If it + * does not have an associated sourcemap, it is considered an original, + * unmodified source file. + */ +export default function buildSourceMapTree(input: SourceMapInput | SourceMapInput[], loader: SourceMapLoader): MapSourceType; +//# sourceMappingURL=build-source-map-tree.d.ts.map \ No newline at end of file diff --git a/dg-ui/node_modules/@jridgewell/remapping/types/build-source-map-tree.d.mts.map b/dg-ui/node_modules/@jridgewell/remapping/types/build-source-map-tree.d.mts.map new file mode 100644 index 0000000..38e4290 --- /dev/null +++ b/dg-ui/node_modules/@jridgewell/remapping/types/build-source-map-tree.d.mts.map @@ -0,0 +1 @@ +{"version":3,"file":"build-source-map-tree.d.ts","sourceRoot":"","sources":["../src/build-source-map-tree.ts"],"names":[],"mappings":"AAIA,OAAO,KAAK,EAAW,SAAS,IAAI,aAAa,EAAE,MAAM,mBAAmB,CAAC;AAC7E,OAAO,KAAK,EAAE,cAAc,EAAE,eAAe,EAAiB,MAAM,SAAS,CAAC;AAO9E;;;;;;;;;;GAUG;AACH,MAAM,CAAC,OAAO,UAAU,kBAAkB,CACxC,KAAK,EAAE,cAAc,GAAG,cAAc,EAAE,EACxC,MAAM,EAAE,eAAe,GACtB,aAAa,CAkBf"} \ No newline at end of file diff --git a/dg-ui/node_modules/@jridgewell/remapping/types/remapping.d.cts b/dg-ui/node_modules/@jridgewell/remapping/types/remapping.d.cts new file mode 100644 index 0000000..2022784 --- /dev/null +++ b/dg-ui/node_modules/@jridgewell/remapping/types/remapping.d.cts @@ -0,0 +1,21 @@ +import SourceMap from './source-map.cts'; +import type { SourceMapInput, SourceMapLoader, Options } from './types.cts'; +export type { SourceMapSegment, EncodedSourceMap, EncodedSourceMap as RawSourceMap, DecodedSourceMap, SourceMapInput, SourceMapLoader, LoaderContext, Options, } from './types.cts'; +export type { SourceMap }; +/** + * Traces through all the mappings in the root sourcemap, through the sources + * (and their sourcemaps), all the way back to the original source location. + * + * `loader` will be called every time we encounter a source file. If it returns + * a sourcemap, we will recurse into that sourcemap to continue the trace. If + * it returns a falsey value, that source file is treated as an original, + * unmodified source file. + * + * Pass `excludeContent` to exclude any self-containing source file content + * from the output sourcemap. + * + * Pass `decodedMappings` to receive a SourceMap with decoded (instead of + * VLQ encoded) mappings. + */ +export = function remapping(input: SourceMapInput | SourceMapInput[], loader: SourceMapLoader, options?: boolean | Options): SourceMap; +//# sourceMappingURL=remapping.d.ts.map \ No newline at end of file diff --git a/dg-ui/node_modules/@jridgewell/remapping/types/remapping.d.cts.map b/dg-ui/node_modules/@jridgewell/remapping/types/remapping.d.cts.map new file mode 100644 index 0000000..9f2fd0e --- /dev/null +++ b/dg-ui/node_modules/@jridgewell/remapping/types/remapping.d.cts.map @@ -0,0 +1 @@ +{"version":3,"file":"remapping.d.ts","sourceRoot":"","sources":["../src/remapping.ts"],"names":[],"mappings":"AAEA,OAAO,SAAS,MAAM,cAAc,CAAC;AAErC,OAAO,KAAK,EAAE,cAAc,EAAE,eAAe,EAAE,OAAO,EAAE,MAAM,SAAS,CAAC;AACxE,YAAY,EACV,gBAAgB,EAChB,gBAAgB,EAChB,gBAAgB,IAAI,YAAY,EAChC,gBAAgB,EAChB,cAAc,EACd,eAAe,EACf,aAAa,EACb,OAAO,GACR,MAAM,SAAS,CAAC;AACjB,YAAY,EAAE,SAAS,EAAE,CAAC;AAE1B;;;;;;;;;;;;;;GAcG;AACH,MAAM,CAAC,OAAO,UAAU,SAAS,CAC/B,KAAK,EAAE,cAAc,GAAG,cAAc,EAAE,EACxC,MAAM,EAAE,eAAe,EACvB,OAAO,CAAC,EAAE,OAAO,GAAG,OAAO,GAC1B,SAAS,CAKX"} \ No newline at end of file diff --git a/dg-ui/node_modules/@jridgewell/remapping/types/remapping.d.mts b/dg-ui/node_modules/@jridgewell/remapping/types/remapping.d.mts new file mode 100644 index 0000000..95c4066 --- /dev/null +++ b/dg-ui/node_modules/@jridgewell/remapping/types/remapping.d.mts @@ -0,0 +1,21 @@ +import SourceMap from './source-map.mts'; +import type { SourceMapInput, SourceMapLoader, Options } from './types.mts'; +export type { SourceMapSegment, EncodedSourceMap, EncodedSourceMap as RawSourceMap, DecodedSourceMap, SourceMapInput, SourceMapLoader, LoaderContext, Options, } from './types.mts'; +export type { SourceMap }; +/** + * Traces through all the mappings in the root sourcemap, through the sources + * (and their sourcemaps), all the way back to the original source location. + * + * `loader` will be called every time we encounter a source file. If it returns + * a sourcemap, we will recurse into that sourcemap to continue the trace. If + * it returns a falsey value, that source file is treated as an original, + * unmodified source file. + * + * Pass `excludeContent` to exclude any self-containing source file content + * from the output sourcemap. + * + * Pass `decodedMappings` to receive a SourceMap with decoded (instead of + * VLQ encoded) mappings. + */ +export default function remapping(input: SourceMapInput | SourceMapInput[], loader: SourceMapLoader, options?: boolean | Options): SourceMap; +//# sourceMappingURL=remapping.d.ts.map \ No newline at end of file diff --git a/dg-ui/node_modules/@jridgewell/remapping/types/remapping.d.mts.map b/dg-ui/node_modules/@jridgewell/remapping/types/remapping.d.mts.map new file mode 100644 index 0000000..9f2fd0e --- /dev/null +++ b/dg-ui/node_modules/@jridgewell/remapping/types/remapping.d.mts.map @@ -0,0 +1 @@ +{"version":3,"file":"remapping.d.ts","sourceRoot":"","sources":["../src/remapping.ts"],"names":[],"mappings":"AAEA,OAAO,SAAS,MAAM,cAAc,CAAC;AAErC,OAAO,KAAK,EAAE,cAAc,EAAE,eAAe,EAAE,OAAO,EAAE,MAAM,SAAS,CAAC;AACxE,YAAY,EACV,gBAAgB,EAChB,gBAAgB,EAChB,gBAAgB,IAAI,YAAY,EAChC,gBAAgB,EAChB,cAAc,EACd,eAAe,EACf,aAAa,EACb,OAAO,GACR,MAAM,SAAS,CAAC;AACjB,YAAY,EAAE,SAAS,EAAE,CAAC;AAE1B;;;;;;;;;;;;;;GAcG;AACH,MAAM,CAAC,OAAO,UAAU,SAAS,CAC/B,KAAK,EAAE,cAAc,GAAG,cAAc,EAAE,EACxC,MAAM,EAAE,eAAe,EACvB,OAAO,CAAC,EAAE,OAAO,GAAG,OAAO,GAC1B,SAAS,CAKX"} \ No newline at end of file diff --git a/dg-ui/node_modules/@jridgewell/remapping/types/source-map-tree.d.cts b/dg-ui/node_modules/@jridgewell/remapping/types/source-map-tree.d.cts new file mode 100644 index 0000000..440f65b --- /dev/null +++ b/dg-ui/node_modules/@jridgewell/remapping/types/source-map-tree.d.cts @@ -0,0 +1,46 @@ +import { GenMapping } from '@jridgewell/gen-mapping'; +import type { TraceMap } from '@jridgewell/trace-mapping'; +export type SourceMapSegmentObject = { + column: number; + line: number; + name: string; + source: string; + content: string | null; + ignore: boolean; +}; +export type OriginalSource = { + map: null; + sources: Sources[]; + source: string; + content: string | null; + ignore: boolean; +}; +export type MapSource = { + map: TraceMap; + sources: Sources[]; + source: string; + content: null; + ignore: false; +}; +export type Sources = OriginalSource | MapSource; +/** + * MapSource represents a single sourcemap, with the ability to trace mappings into its child nodes + * (which may themselves be SourceMapTrees). + */ +export declare function MapSource(map: TraceMap, sources: Sources[]): MapSource; +/** + * A "leaf" node in the sourcemap tree, representing an original, unmodified source file. Recursive + * segment tracing ends at the `OriginalSource`. + */ +export declare function OriginalSource(source: string, content: string | null, ignore: boolean): OriginalSource; +/** + * traceMappings is only called on the root level SourceMapTree, and begins the process of + * resolving each mapping in terms of the original source files. + */ +export declare function traceMappings(tree: MapSource): GenMapping; +/** + * originalPositionFor is only called on children SourceMapTrees. It recurses down into its own + * child SourceMapTrees, until we find the original source map. + */ +export declare function originalPositionFor(source: Sources, line: number, column: number, name: string): SourceMapSegmentObject | null; +//# sourceMappingURL=source-map-tree.d.ts.map \ No newline at end of file diff --git a/dg-ui/node_modules/@jridgewell/remapping/types/source-map-tree.d.cts.map b/dg-ui/node_modules/@jridgewell/remapping/types/source-map-tree.d.cts.map new file mode 100644 index 0000000..e7cbfb9 --- /dev/null +++ b/dg-ui/node_modules/@jridgewell/remapping/types/source-map-tree.d.cts.map @@ -0,0 +1 @@ +{"version":3,"file":"source-map-tree.d.ts","sourceRoot":"","sources":["../src/source-map-tree.ts"],"names":[],"mappings":"AAAA,OAAO,EAAE,UAAU,EAAgD,MAAM,yBAAyB,CAAC;AAGnG,OAAO,KAAK,EAAE,QAAQ,EAAE,MAAM,2BAA2B,CAAC;AAE1D,MAAM,MAAM,sBAAsB,GAAG;IACnC,MAAM,EAAE,MAAM,CAAC;IACf,IAAI,EAAE,MAAM,CAAC;IACb,IAAI,EAAE,MAAM,CAAC;IACb,MAAM,EAAE,MAAM,CAAC;IACf,OAAO,EAAE,MAAM,GAAG,IAAI,CAAC;IACvB,MAAM,EAAE,OAAO,CAAC;CACjB,CAAC;AAEF,MAAM,MAAM,cAAc,GAAG;IAC3B,GAAG,EAAE,IAAI,CAAC;IACV,OAAO,EAAE,OAAO,EAAE,CAAC;IACnB,MAAM,EAAE,MAAM,CAAC;IACf,OAAO,EAAE,MAAM,GAAG,IAAI,CAAC;IACvB,MAAM,EAAE,OAAO,CAAC;CACjB,CAAC;AAEF,MAAM,MAAM,SAAS,GAAG;IACtB,GAAG,EAAE,QAAQ,CAAC;IACd,OAAO,EAAE,OAAO,EAAE,CAAC;IACnB,MAAM,EAAE,MAAM,CAAC;IACf,OAAO,EAAE,IAAI,CAAC;IACd,MAAM,EAAE,KAAK,CAAC;CACf,CAAC;AAEF,MAAM,MAAM,OAAO,GAAG,cAAc,GAAG,SAAS,CAAC;AA8CjD;;;GAGG;AACH,wBAAgB,SAAS,CAAC,GAAG,EAAE,QAAQ,EAAE,OAAO,EAAE,OAAO,EAAE,GAAG,SAAS,CAEtE;AAED;;;GAGG;AACH,wBAAgB,cAAc,CAC5B,MAAM,EAAE,MAAM,EACd,OAAO,EAAE,MAAM,GAAG,IAAI,EACtB,MAAM,EAAE,OAAO,GACd,cAAc,CAEhB;AAED;;;GAGG;AACH,wBAAgB,aAAa,CAAC,IAAI,EAAE,SAAS,GAAG,UAAU,CAyCzD;AAED;;;GAGG;AACH,wBAAgB,mBAAmB,CACjC,MAAM,EAAE,OAAO,EACf,IAAI,EAAE,MAAM,EACZ,MAAM,EAAE,MAAM,EACd,IAAI,EAAE,MAAM,GACX,sBAAsB,GAAG,IAAI,CAmB/B"} \ No newline at end of file diff --git a/dg-ui/node_modules/@jridgewell/remapping/types/source-map-tree.d.mts b/dg-ui/node_modules/@jridgewell/remapping/types/source-map-tree.d.mts new file mode 100644 index 0000000..440f65b --- /dev/null +++ b/dg-ui/node_modules/@jridgewell/remapping/types/source-map-tree.d.mts @@ -0,0 +1,46 @@ +import { GenMapping } from '@jridgewell/gen-mapping'; +import type { TraceMap } from '@jridgewell/trace-mapping'; +export type SourceMapSegmentObject = { + column: number; + line: number; + name: string; + source: string; + content: string | null; + ignore: boolean; +}; +export type OriginalSource = { + map: null; + sources: Sources[]; + source: string; + content: string | null; + ignore: boolean; +}; +export type MapSource = { + map: TraceMap; + sources: Sources[]; + source: string; + content: null; + ignore: false; +}; +export type Sources = OriginalSource | MapSource; +/** + * MapSource represents a single sourcemap, with the ability to trace mappings into its child nodes + * (which may themselves be SourceMapTrees). + */ +export declare function MapSource(map: TraceMap, sources: Sources[]): MapSource; +/** + * A "leaf" node in the sourcemap tree, representing an original, unmodified source file. Recursive + * segment tracing ends at the `OriginalSource`. + */ +export declare function OriginalSource(source: string, content: string | null, ignore: boolean): OriginalSource; +/** + * traceMappings is only called on the root level SourceMapTree, and begins the process of + * resolving each mapping in terms of the original source files. + */ +export declare function traceMappings(tree: MapSource): GenMapping; +/** + * originalPositionFor is only called on children SourceMapTrees. It recurses down into its own + * child SourceMapTrees, until we find the original source map. + */ +export declare function originalPositionFor(source: Sources, line: number, column: number, name: string): SourceMapSegmentObject | null; +//# sourceMappingURL=source-map-tree.d.ts.map \ No newline at end of file diff --git a/dg-ui/node_modules/@jridgewell/remapping/types/source-map-tree.d.mts.map b/dg-ui/node_modules/@jridgewell/remapping/types/source-map-tree.d.mts.map new file mode 100644 index 0000000..e7cbfb9 --- /dev/null +++ b/dg-ui/node_modules/@jridgewell/remapping/types/source-map-tree.d.mts.map @@ -0,0 +1 @@ +{"version":3,"file":"source-map-tree.d.ts","sourceRoot":"","sources":["../src/source-map-tree.ts"],"names":[],"mappings":"AAAA,OAAO,EAAE,UAAU,EAAgD,MAAM,yBAAyB,CAAC;AAGnG,OAAO,KAAK,EAAE,QAAQ,EAAE,MAAM,2BAA2B,CAAC;AAE1D,MAAM,MAAM,sBAAsB,GAAG;IACnC,MAAM,EAAE,MAAM,CAAC;IACf,IAAI,EAAE,MAAM,CAAC;IACb,IAAI,EAAE,MAAM,CAAC;IACb,MAAM,EAAE,MAAM,CAAC;IACf,OAAO,EAAE,MAAM,GAAG,IAAI,CAAC;IACvB,MAAM,EAAE,OAAO,CAAC;CACjB,CAAC;AAEF,MAAM,MAAM,cAAc,GAAG;IAC3B,GAAG,EAAE,IAAI,CAAC;IACV,OAAO,EAAE,OAAO,EAAE,CAAC;IACnB,MAAM,EAAE,MAAM,CAAC;IACf,OAAO,EAAE,MAAM,GAAG,IAAI,CAAC;IACvB,MAAM,EAAE,OAAO,CAAC;CACjB,CAAC;AAEF,MAAM,MAAM,SAAS,GAAG;IACtB,GAAG,EAAE,QAAQ,CAAC;IACd,OAAO,EAAE,OAAO,EAAE,CAAC;IACnB,MAAM,EAAE,MAAM,CAAC;IACf,OAAO,EAAE,IAAI,CAAC;IACd,MAAM,EAAE,KAAK,CAAC;CACf,CAAC;AAEF,MAAM,MAAM,OAAO,GAAG,cAAc,GAAG,SAAS,CAAC;AA8CjD;;;GAGG;AACH,wBAAgB,SAAS,CAAC,GAAG,EAAE,QAAQ,EAAE,OAAO,EAAE,OAAO,EAAE,GAAG,SAAS,CAEtE;AAED;;;GAGG;AACH,wBAAgB,cAAc,CAC5B,MAAM,EAAE,MAAM,EACd,OAAO,EAAE,MAAM,GAAG,IAAI,EACtB,MAAM,EAAE,OAAO,GACd,cAAc,CAEhB;AAED;;;GAGG;AACH,wBAAgB,aAAa,CAAC,IAAI,EAAE,SAAS,GAAG,UAAU,CAyCzD;AAED;;;GAGG;AACH,wBAAgB,mBAAmB,CACjC,MAAM,EAAE,OAAO,EACf,IAAI,EAAE,MAAM,EACZ,MAAM,EAAE,MAAM,EACd,IAAI,EAAE,MAAM,GACX,sBAAsB,GAAG,IAAI,CAmB/B"} \ No newline at end of file diff --git a/dg-ui/node_modules/@jridgewell/remapping/types/source-map.d.cts b/dg-ui/node_modules/@jridgewell/remapping/types/source-map.d.cts new file mode 100644 index 0000000..fdb7eed --- /dev/null +++ b/dg-ui/node_modules/@jridgewell/remapping/types/source-map.d.cts @@ -0,0 +1,19 @@ +import type { GenMapping } from '@jridgewell/gen-mapping'; +import type { DecodedSourceMap, EncodedSourceMap, Options } from './types.cts'; +/** + * A SourceMap v3 compatible sourcemap, which only includes fields that were + * provided to it. + */ +export = class SourceMap { + file?: string | null; + mappings: EncodedSourceMap['mappings'] | DecodedSourceMap['mappings']; + sourceRoot?: string; + names: string[]; + sources: (string | null)[]; + sourcesContent?: (string | null)[]; + version: 3; + ignoreList: number[] | undefined; + constructor(map: GenMapping, options: Options); + toString(): string; +} +//# sourceMappingURL=source-map.d.ts.map \ No newline at end of file diff --git a/dg-ui/node_modules/@jridgewell/remapping/types/source-map.d.cts.map b/dg-ui/node_modules/@jridgewell/remapping/types/source-map.d.cts.map new file mode 100644 index 0000000..593daf8 --- /dev/null +++ b/dg-ui/node_modules/@jridgewell/remapping/types/source-map.d.cts.map @@ -0,0 +1 @@ +{"version":3,"file":"source-map.d.ts","sourceRoot":"","sources":["../src/source-map.ts"],"names":[],"mappings":"AAEA,OAAO,KAAK,EAAE,UAAU,EAAE,MAAM,yBAAyB,CAAC;AAC1D,OAAO,KAAK,EAAE,gBAAgB,EAAE,gBAAgB,EAAE,OAAO,EAAE,MAAM,SAAS,CAAC;AAE3E;;;GAGG;AACH,MAAM,CAAC,OAAO,OAAO,SAAS;IACpB,IAAI,CAAC,EAAE,MAAM,GAAG,IAAI,CAAC;IACrB,QAAQ,EAAE,gBAAgB,CAAC,UAAU,CAAC,GAAG,gBAAgB,CAAC,UAAU,CAAC,CAAC;IACtE,UAAU,CAAC,EAAE,MAAM,CAAC;IACpB,KAAK,EAAE,MAAM,EAAE,CAAC;IAChB,OAAO,EAAE,CAAC,MAAM,GAAG,IAAI,CAAC,EAAE,CAAC;IAC3B,cAAc,CAAC,EAAE,CAAC,MAAM,GAAG,IAAI,CAAC,EAAE,CAAC;IACnC,OAAO,EAAE,CAAC,CAAC;IACX,UAAU,EAAE,MAAM,EAAE,GAAG,SAAS,CAAC;gBAE7B,GAAG,EAAE,UAAU,EAAE,OAAO,EAAE,OAAO;IAe7C,QAAQ,IAAI,MAAM;CAGnB"} \ No newline at end of file diff --git a/dg-ui/node_modules/@jridgewell/remapping/types/source-map.d.mts b/dg-ui/node_modules/@jridgewell/remapping/types/source-map.d.mts new file mode 100644 index 0000000..52ebba2 --- /dev/null +++ b/dg-ui/node_modules/@jridgewell/remapping/types/source-map.d.mts @@ -0,0 +1,19 @@ +import type { GenMapping } from '@jridgewell/gen-mapping'; +import type { DecodedSourceMap, EncodedSourceMap, Options } from './types.mts'; +/** + * A SourceMap v3 compatible sourcemap, which only includes fields that were + * provided to it. + */ +export default class SourceMap { + file?: string | null; + mappings: EncodedSourceMap['mappings'] | DecodedSourceMap['mappings']; + sourceRoot?: string; + names: string[]; + sources: (string | null)[]; + sourcesContent?: (string | null)[]; + version: 3; + ignoreList: number[] | undefined; + constructor(map: GenMapping, options: Options); + toString(): string; +} +//# sourceMappingURL=source-map.d.ts.map \ No newline at end of file diff --git a/dg-ui/node_modules/@jridgewell/remapping/types/source-map.d.mts.map b/dg-ui/node_modules/@jridgewell/remapping/types/source-map.d.mts.map new file mode 100644 index 0000000..593daf8 --- /dev/null +++ b/dg-ui/node_modules/@jridgewell/remapping/types/source-map.d.mts.map @@ -0,0 +1 @@ +{"version":3,"file":"source-map.d.ts","sourceRoot":"","sources":["../src/source-map.ts"],"names":[],"mappings":"AAEA,OAAO,KAAK,EAAE,UAAU,EAAE,MAAM,yBAAyB,CAAC;AAC1D,OAAO,KAAK,EAAE,gBAAgB,EAAE,gBAAgB,EAAE,OAAO,EAAE,MAAM,SAAS,CAAC;AAE3E;;;GAGG;AACH,MAAM,CAAC,OAAO,OAAO,SAAS;IACpB,IAAI,CAAC,EAAE,MAAM,GAAG,IAAI,CAAC;IACrB,QAAQ,EAAE,gBAAgB,CAAC,UAAU,CAAC,GAAG,gBAAgB,CAAC,UAAU,CAAC,CAAC;IACtE,UAAU,CAAC,EAAE,MAAM,CAAC;IACpB,KAAK,EAAE,MAAM,EAAE,CAAC;IAChB,OAAO,EAAE,CAAC,MAAM,GAAG,IAAI,CAAC,EAAE,CAAC;IAC3B,cAAc,CAAC,EAAE,CAAC,MAAM,GAAG,IAAI,CAAC,EAAE,CAAC;IACnC,OAAO,EAAE,CAAC,CAAC;IACX,UAAU,EAAE,MAAM,EAAE,GAAG,SAAS,CAAC;gBAE7B,GAAG,EAAE,UAAU,EAAE,OAAO,EAAE,OAAO;IAe7C,QAAQ,IAAI,MAAM;CAGnB"} \ No newline at end of file diff --git a/dg-ui/node_modules/@jridgewell/remapping/types/types.d.cts b/dg-ui/node_modules/@jridgewell/remapping/types/types.d.cts new file mode 100644 index 0000000..eeb320f --- /dev/null +++ b/dg-ui/node_modules/@jridgewell/remapping/types/types.d.cts @@ -0,0 +1,16 @@ +import type { SourceMapInput } from '@jridgewell/trace-mapping'; +export type { SourceMapSegment, DecodedSourceMap, EncodedSourceMap, } from '@jridgewell/trace-mapping'; +export type { SourceMapInput }; +export type LoaderContext = { + readonly importer: string; + readonly depth: number; + source: string; + content: string | null | undefined; + ignore: boolean | undefined; +}; +export type SourceMapLoader = (file: string, ctx: LoaderContext) => SourceMapInput | null | undefined | void; +export type Options = { + excludeContent?: boolean; + decodedMappings?: boolean; +}; +//# sourceMappingURL=types.d.ts.map \ No newline at end of file diff --git a/dg-ui/node_modules/@jridgewell/remapping/types/types.d.cts.map b/dg-ui/node_modules/@jridgewell/remapping/types/types.d.cts.map new file mode 100644 index 0000000..4f8647e --- /dev/null +++ b/dg-ui/node_modules/@jridgewell/remapping/types/types.d.cts.map @@ -0,0 +1 @@ +{"version":3,"file":"types.d.ts","sourceRoot":"","sources":["../src/types.ts"],"names":[],"mappings":"AAAA,OAAO,KAAK,EAAE,cAAc,EAAE,MAAM,2BAA2B,CAAC;AAEhE,YAAY,EACV,gBAAgB,EAChB,gBAAgB,EAChB,gBAAgB,GACjB,MAAM,2BAA2B,CAAC;AAEnC,YAAY,EAAE,cAAc,EAAE,CAAC;AAE/B,MAAM,MAAM,aAAa,GAAG;IAC1B,QAAQ,CAAC,QAAQ,EAAE,MAAM,CAAC;IAC1B,QAAQ,CAAC,KAAK,EAAE,MAAM,CAAC;IACvB,MAAM,EAAE,MAAM,CAAC;IACf,OAAO,EAAE,MAAM,GAAG,IAAI,GAAG,SAAS,CAAC;IACnC,MAAM,EAAE,OAAO,GAAG,SAAS,CAAC;CAC7B,CAAC;AAEF,MAAM,MAAM,eAAe,GAAG,CAC5B,IAAI,EAAE,MAAM,EACZ,GAAG,EAAE,aAAa,KACf,cAAc,GAAG,IAAI,GAAG,SAAS,GAAG,IAAI,CAAC;AAE9C,MAAM,MAAM,OAAO,GAAG;IACpB,cAAc,CAAC,EAAE,OAAO,CAAC;IACzB,eAAe,CAAC,EAAE,OAAO,CAAC;CAC3B,CAAC"} \ No newline at end of file diff --git a/dg-ui/node_modules/@jridgewell/remapping/types/types.d.mts b/dg-ui/node_modules/@jridgewell/remapping/types/types.d.mts new file mode 100644 index 0000000..eeb320f --- /dev/null +++ b/dg-ui/node_modules/@jridgewell/remapping/types/types.d.mts @@ -0,0 +1,16 @@ +import type { SourceMapInput } from '@jridgewell/trace-mapping'; +export type { SourceMapSegment, DecodedSourceMap, EncodedSourceMap, } from '@jridgewell/trace-mapping'; +export type { SourceMapInput }; +export type LoaderContext = { + readonly importer: string; + readonly depth: number; + source: string; + content: string | null | undefined; + ignore: boolean | undefined; +}; +export type SourceMapLoader = (file: string, ctx: LoaderContext) => SourceMapInput | null | undefined | void; +export type Options = { + excludeContent?: boolean; + decodedMappings?: boolean; +}; +//# sourceMappingURL=types.d.ts.map \ No newline at end of file diff --git a/dg-ui/node_modules/@jridgewell/remapping/types/types.d.mts.map b/dg-ui/node_modules/@jridgewell/remapping/types/types.d.mts.map new file mode 100644 index 0000000..4f8647e --- /dev/null +++ b/dg-ui/node_modules/@jridgewell/remapping/types/types.d.mts.map @@ -0,0 +1 @@ +{"version":3,"file":"types.d.ts","sourceRoot":"","sources":["../src/types.ts"],"names":[],"mappings":"AAAA,OAAO,KAAK,EAAE,cAAc,EAAE,MAAM,2BAA2B,CAAC;AAEhE,YAAY,EACV,gBAAgB,EAChB,gBAAgB,EAChB,gBAAgB,GACjB,MAAM,2BAA2B,CAAC;AAEnC,YAAY,EAAE,cAAc,EAAE,CAAC;AAE/B,MAAM,MAAM,aAAa,GAAG;IAC1B,QAAQ,CAAC,QAAQ,EAAE,MAAM,CAAC;IAC1B,QAAQ,CAAC,KAAK,EAAE,MAAM,CAAC;IACvB,MAAM,EAAE,MAAM,CAAC;IACf,OAAO,EAAE,MAAM,GAAG,IAAI,GAAG,SAAS,CAAC;IACnC,MAAM,EAAE,OAAO,GAAG,SAAS,CAAC;CAC7B,CAAC;AAEF,MAAM,MAAM,eAAe,GAAG,CAC5B,IAAI,EAAE,MAAM,EACZ,GAAG,EAAE,aAAa,KACf,cAAc,GAAG,IAAI,GAAG,SAAS,GAAG,IAAI,CAAC;AAE9C,MAAM,MAAM,OAAO,GAAG;IACpB,cAAc,CAAC,EAAE,OAAO,CAAC;IACzB,eAAe,CAAC,EAAE,OAAO,CAAC;CAC3B,CAAC"} \ No newline at end of file diff --git a/dg-ui/node_modules/@jridgewell/resolve-uri/LICENSE b/dg-ui/node_modules/@jridgewell/resolve-uri/LICENSE new file mode 100644 index 0000000..0a81b2a --- /dev/null +++ b/dg-ui/node_modules/@jridgewell/resolve-uri/LICENSE @@ -0,0 +1,19 @@ +Copyright 2019 Justin Ridgewell + +Permission is hereby granted, free of charge, to any person obtaining a copy +of this software and associated documentation files (the "Software"), to deal +in the Software without restriction, including without limitation the rights +to use, copy, modify, merge, publish, distribute, sublicense, and/or sell +copies of the Software, and to permit persons to whom the Software is +furnished to do so, subject to the following conditions: + +The above copyright notice and this permission notice shall be included in +all copies or substantial portions of the Software. + +THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR +IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, +FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE +AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER +LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, +OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE +SOFTWARE. \ No newline at end of file diff --git a/dg-ui/node_modules/@jridgewell/resolve-uri/README.md b/dg-ui/node_modules/@jridgewell/resolve-uri/README.md new file mode 100644 index 0000000..cd6ec31 --- /dev/null +++ b/dg-ui/node_modules/@jridgewell/resolve-uri/README.md @@ -0,0 +1,40 @@ +# @jridgewell/resolve-uri + +> Resolve a URI relative to an optional base URI + +Resolve any combination of absolute URIs, protocol-relative URIs, absolute paths, or relative paths. + +## Installation + +```sh +npm install @jridgewell/resolve-uri +``` + +## Usage + +```typescript +function resolve(input: string, base?: string): string; +``` + +```js +import resolve from '@jridgewell/resolve-uri'; + +resolve('foo', 'https://example.com'); // => 'https://example.com/foo' +``` + +| Input | Base | Resolution | Explanation | +|-----------------------|-------------------------|--------------------------------|--------------------------------------------------------------| +| `https://example.com` | _any_ | `https://example.com/` | Input is normalized only | +| `//example.com` | `https://base.com/` | `https://example.com/` | Input inherits the base's protocol | +| `//example.com` | _rest_ | `//example.com/` | Input is normalized only | +| `/example` | `https://base.com/` | `https://base.com/example` | Input inherits the base's origin | +| `/example` | `//base.com/` | `//base.com/example` | Input inherits the base's host and remains protocol relative | +| `/example` | _rest_ | `/example` | Input is normalized only | +| `example` | `https://base.com/dir/` | `https://base.com/dir/example` | Input is joined with the base | +| `example` | `https://base.com/file` | `https://base.com/example` | Input is joined with the base without its file | +| `example` | `//base.com/dir/` | `//base.com/dir/example` | Input is joined with the base's last directory | +| `example` | `//base.com/file` | `//base.com/example` | Input is joined with the base without its file | +| `example` | `/base/dir/` | `/base/dir/example` | Input is joined with the base's last directory | +| `example` | `/base/file` | `/base/example` | Input is joined with the base without its file | +| `example` | `base/dir/` | `base/dir/example` | Input is joined with the base's last directory | +| `example` | `base/file` | `base/example` | Input is joined with the base without its file | diff --git a/dg-ui/node_modules/@jridgewell/resolve-uri/dist/resolve-uri.mjs b/dg-ui/node_modules/@jridgewell/resolve-uri/dist/resolve-uri.mjs new file mode 100644 index 0000000..31641de --- /dev/null +++ b/dg-ui/node_modules/@jridgewell/resolve-uri/dist/resolve-uri.mjs @@ -0,0 +1,232 @@ +// Matches the scheme of a URL, eg "http://" +const schemeRegex = /^[\w+.-]+:\/\//; +/** + * Matches the parts of a URL: + * 1. Scheme, including ":", guaranteed. + * 2. User/password, including "@", optional. + * 3. Host, including brackets around IP literals, guaranteed. + * 4. Port, including ":", optional. + * 5. Path, including "/", optional. + * 6. Query, including "?", optional. + * 7. Hash, including "#", optional. + */ +const urlRegex = /^([\w+.-]+:)\/\/([^@/#?]*@)?(\[[^\]]+\]|[^:/#?]*)(:\d+)?(\/[^#?]*)?(\?[^#]*)?(#.*)?/; +/** + * File URLs are weird. They dont' need the regular `//` in the scheme, they may or may not start + * with a leading `/`, they can have a domain (but only if they don't start with a Windows drive). + * + * 1. Host, optional. + * 2. Path, which may include "/", guaranteed. + * 3. Query, including "?", optional. + * 4. Hash, including "#", optional. + */ +const fileRegex = /^file:(?:\/\/((?![a-z]:)[^/#?]*)?)?(\/?[^#?]*)(\?[^#]*)?(#.*)?/i; +function isAbsoluteUrl(input) { + return schemeRegex.test(input); +} +function isSchemeRelativeUrl(input) { + return input.startsWith('//'); +} +function isAbsolutePath(input) { + return input.startsWith('/'); +} +function isFileUrl(input) { + return input.startsWith('file:'); +} +function isRelative(input) { + return /^[.?#]/.test(input); +} +function parseAbsoluteUrl(input) { + const match = urlRegex.exec(input); + return makeUrl(match[1], match[2] || '', match[3], match[4] || '', match[5] || '/', match[6] || '', match[7] || ''); +} +function parseFileUrl(input) { + const match = fileRegex.exec(input); + const path = match[2]; + return makeUrl('file:', '', match[1] || '', '', isAbsolutePath(path) ? path : '/' + path, match[3] || '', match[4] || ''); +} +function makeUrl(scheme, user, host, port, path, query, hash) { + return { + scheme, + user, + host, + port, + path, + query, + hash, + type: 7 /* Absolute */, + }; +} +function parseUrl(input) { + if (isSchemeRelativeUrl(input)) { + const url = parseAbsoluteUrl('http:' + input); + url.scheme = ''; + url.type = 6 /* SchemeRelative */; + return url; + } + if (isAbsolutePath(input)) { + const url = parseAbsoluteUrl('http://foo.com' + input); + url.scheme = ''; + url.host = ''; + url.type = 5 /* AbsolutePath */; + return url; + } + if (isFileUrl(input)) + return parseFileUrl(input); + if (isAbsoluteUrl(input)) + return parseAbsoluteUrl(input); + const url = parseAbsoluteUrl('http://foo.com/' + input); + url.scheme = ''; + url.host = ''; + url.type = input + ? input.startsWith('?') + ? 3 /* Query */ + : input.startsWith('#') + ? 2 /* Hash */ + : 4 /* RelativePath */ + : 1 /* Empty */; + return url; +} +function stripPathFilename(path) { + // If a path ends with a parent directory "..", then it's a relative path with excess parent + // paths. It's not a file, so we can't strip it. + if (path.endsWith('/..')) + return path; + const index = path.lastIndexOf('/'); + return path.slice(0, index + 1); +} +function mergePaths(url, base) { + normalizePath(base, base.type); + // If the path is just a "/", then it was an empty path to begin with (remember, we're a relative + // path). + if (url.path === '/') { + url.path = base.path; + } + else { + // Resolution happens relative to the base path's directory, not the file. + url.path = stripPathFilename(base.path) + url.path; + } +} +/** + * The path can have empty directories "//", unneeded parents "foo/..", or current directory + * "foo/.". We need to normalize to a standard representation. + */ +function normalizePath(url, type) { + const rel = type <= 4 /* RelativePath */; + const pieces = url.path.split('/'); + // We need to preserve the first piece always, so that we output a leading slash. The item at + // pieces[0] is an empty string. + let pointer = 1; + // Positive is the number of real directories we've output, used for popping a parent directory. + // Eg, "foo/bar/.." will have a positive 2, and we can decrement to be left with just "foo". + let positive = 0; + // We need to keep a trailing slash if we encounter an empty directory (eg, splitting "foo/" will + // generate `["foo", ""]` pieces). And, if we pop a parent directory. But once we encounter a + // real directory, we won't need to append, unless the other conditions happen again. + let addTrailingSlash = false; + for (let i = 1; i < pieces.length; i++) { + const piece = pieces[i]; + // An empty directory, could be a trailing slash, or just a double "//" in the path. + if (!piece) { + addTrailingSlash = true; + continue; + } + // If we encounter a real directory, then we don't need to append anymore. + addTrailingSlash = false; + // A current directory, which we can always drop. + if (piece === '.') + continue; + // A parent directory, we need to see if there are any real directories we can pop. Else, we + // have an excess of parents, and we'll need to keep the "..". + if (piece === '..') { + if (positive) { + addTrailingSlash = true; + positive--; + pointer--; + } + else if (rel) { + // If we're in a relativePath, then we need to keep the excess parents. Else, in an absolute + // URL, protocol relative URL, or an absolute path, we don't need to keep excess. + pieces[pointer++] = piece; + } + continue; + } + // We've encountered a real directory. Move it to the next insertion pointer, which accounts for + // any popped or dropped directories. + pieces[pointer++] = piece; + positive++; + } + let path = ''; + for (let i = 1; i < pointer; i++) { + path += '/' + pieces[i]; + } + if (!path || (addTrailingSlash && !path.endsWith('/..'))) { + path += '/'; + } + url.path = path; +} +/** + * Attempts to resolve `input` URL/path relative to `base`. + */ +function resolve(input, base) { + if (!input && !base) + return ''; + const url = parseUrl(input); + let inputType = url.type; + if (base && inputType !== 7 /* Absolute */) { + const baseUrl = parseUrl(base); + const baseType = baseUrl.type; + switch (inputType) { + case 1 /* Empty */: + url.hash = baseUrl.hash; + // fall through + case 2 /* Hash */: + url.query = baseUrl.query; + // fall through + case 3 /* Query */: + case 4 /* RelativePath */: + mergePaths(url, baseUrl); + // fall through + case 5 /* AbsolutePath */: + // The host, user, and port are joined, you can't copy one without the others. + url.user = baseUrl.user; + url.host = baseUrl.host; + url.port = baseUrl.port; + // fall through + case 6 /* SchemeRelative */: + // The input doesn't have a schema at least, so we need to copy at least that over. + url.scheme = baseUrl.scheme; + } + if (baseType > inputType) + inputType = baseType; + } + normalizePath(url, inputType); + const queryHash = url.query + url.hash; + switch (inputType) { + // This is impossible, because of the empty checks at the start of the function. + // case UrlType.Empty: + case 2 /* Hash */: + case 3 /* Query */: + return queryHash; + case 4 /* RelativePath */: { + // The first char is always a "/", and we need it to be relative. + const path = url.path.slice(1); + if (!path) + return queryHash || '.'; + if (isRelative(base || input) && !isRelative(path)) { + // If base started with a leading ".", or there is no base and input started with a ".", + // then we need to ensure that the relative path starts with a ".". We don't know if + // relative starts with a "..", though, so check before prepending. + return './' + path + queryHash; + } + return path + queryHash; + } + case 5 /* AbsolutePath */: + return url.path + queryHash; + default: + return url.scheme + '//' + url.user + url.host + url.port + url.path + queryHash; + } +} + +export { resolve as default }; +//# sourceMappingURL=resolve-uri.mjs.map diff --git a/dg-ui/node_modules/@jridgewell/resolve-uri/dist/resolve-uri.mjs.map b/dg-ui/node_modules/@jridgewell/resolve-uri/dist/resolve-uri.mjs.map new file mode 100644 index 0000000..691e1d4 --- /dev/null +++ b/dg-ui/node_modules/@jridgewell/resolve-uri/dist/resolve-uri.mjs.map @@ -0,0 +1 @@ +{"version":3,"file":"resolve-uri.mjs","sources":["../src/resolve-uri.ts"],"sourcesContent":["// Matches the scheme of a URL, eg \"http://\"\nconst schemeRegex = /^[\\w+.-]+:\\/\\//;\n\n/**\n * Matches the parts of a URL:\n * 1. Scheme, including \":\", guaranteed.\n * 2. User/password, including \"@\", optional.\n * 3. Host, including brackets around IP literals, guaranteed.\n * 4. Port, including \":\", optional.\n * 5. Path, including \"/\", optional.\n * 6. Query, including \"?\", optional.\n * 7. Hash, including \"#\", optional.\n */\nconst urlRegex =\n /^([\\w+.-]+:)\\/\\/([^@/#?]*@)?(\\[[^\\]]+\\]|[^:/#?]*)(:\\d+)?(\\/[^#?]*)?(\\?[^#]*)?(#.*)?/;\n\n/**\n * File URLs are weird. They dont' need the regular `//` in the scheme, they may or may not start\n * with a leading `/`, they can have a domain (but only if they don't start with a Windows drive).\n *\n * 1. Host, optional.\n * 2. Path, which may include \"/\", guaranteed.\n * 3. Query, including \"?\", optional.\n * 4. Hash, including \"#\", optional.\n */\nconst fileRegex = /^file:(?:\\/\\/((?![a-z]:)[^/#?]*)?)?(\\/?[^#?]*)(\\?[^#]*)?(#.*)?/i;\n\ntype Url = {\n scheme: string;\n user: string;\n host: string;\n port: string;\n path: string;\n query: string;\n hash: string;\n type: UrlType;\n};\n\nconst enum UrlType {\n Empty = 1,\n Hash = 2,\n Query = 3,\n RelativePath = 4,\n AbsolutePath = 5,\n SchemeRelative = 6,\n Absolute = 7,\n}\n\nfunction isAbsoluteUrl(input: string): boolean {\n return schemeRegex.test(input);\n}\n\nfunction isSchemeRelativeUrl(input: string): boolean {\n return input.startsWith('//');\n}\n\nfunction isAbsolutePath(input: string): boolean {\n return input.startsWith('/');\n}\n\nfunction isFileUrl(input: string): boolean {\n return input.startsWith('file:');\n}\n\nfunction isRelative(input: string): boolean {\n return /^[.?#]/.test(input);\n}\n\nfunction parseAbsoluteUrl(input: string): Url {\n const match = urlRegex.exec(input)!;\n return makeUrl(\n match[1],\n match[2] || '',\n match[3],\n match[4] || '',\n match[5] || '/',\n match[6] || '',\n match[7] || '',\n );\n}\n\nfunction parseFileUrl(input: string): Url {\n const match = fileRegex.exec(input)!;\n const path = match[2];\n return makeUrl(\n 'file:',\n '',\n match[1] || '',\n '',\n isAbsolutePath(path) ? path : '/' + path,\n match[3] || '',\n match[4] || '',\n );\n}\n\nfunction makeUrl(\n scheme: string,\n user: string,\n host: string,\n port: string,\n path: string,\n query: string,\n hash: string,\n): Url {\n return {\n scheme,\n user,\n host,\n port,\n path,\n query,\n hash,\n type: UrlType.Absolute,\n };\n}\n\nfunction parseUrl(input: string): Url {\n if (isSchemeRelativeUrl(input)) {\n const url = parseAbsoluteUrl('http:' + input);\n url.scheme = '';\n url.type = UrlType.SchemeRelative;\n return url;\n }\n\n if (isAbsolutePath(input)) {\n const url = parseAbsoluteUrl('http://foo.com' + input);\n url.scheme = '';\n url.host = '';\n url.type = UrlType.AbsolutePath;\n return url;\n }\n\n if (isFileUrl(input)) return parseFileUrl(input);\n\n if (isAbsoluteUrl(input)) return parseAbsoluteUrl(input);\n\n const url = parseAbsoluteUrl('http://foo.com/' + input);\n url.scheme = '';\n url.host = '';\n url.type = input\n ? input.startsWith('?')\n ? UrlType.Query\n : input.startsWith('#')\n ? UrlType.Hash\n : UrlType.RelativePath\n : UrlType.Empty;\n return url;\n}\n\nfunction stripPathFilename(path: string): string {\n // If a path ends with a parent directory \"..\", then it's a relative path with excess parent\n // paths. It's not a file, so we can't strip it.\n if (path.endsWith('/..')) return path;\n const index = path.lastIndexOf('/');\n return path.slice(0, index + 1);\n}\n\nfunction mergePaths(url: Url, base: Url) {\n normalizePath(base, base.type);\n\n // If the path is just a \"/\", then it was an empty path to begin with (remember, we're a relative\n // path).\n if (url.path === '/') {\n url.path = base.path;\n } else {\n // Resolution happens relative to the base path's directory, not the file.\n url.path = stripPathFilename(base.path) + url.path;\n }\n}\n\n/**\n * The path can have empty directories \"//\", unneeded parents \"foo/..\", or current directory\n * \"foo/.\". We need to normalize to a standard representation.\n */\nfunction normalizePath(url: Url, type: UrlType) {\n const rel = type <= UrlType.RelativePath;\n const pieces = url.path.split('/');\n\n // We need to preserve the first piece always, so that we output a leading slash. The item at\n // pieces[0] is an empty string.\n let pointer = 1;\n\n // Positive is the number of real directories we've output, used for popping a parent directory.\n // Eg, \"foo/bar/..\" will have a positive 2, and we can decrement to be left with just \"foo\".\n let positive = 0;\n\n // We need to keep a trailing slash if we encounter an empty directory (eg, splitting \"foo/\" will\n // generate `[\"foo\", \"\"]` pieces). And, if we pop a parent directory. But once we encounter a\n // real directory, we won't need to append, unless the other conditions happen again.\n let addTrailingSlash = false;\n\n for (let i = 1; i < pieces.length; i++) {\n const piece = pieces[i];\n\n // An empty directory, could be a trailing slash, or just a double \"//\" in the path.\n if (!piece) {\n addTrailingSlash = true;\n continue;\n }\n\n // If we encounter a real directory, then we don't need to append anymore.\n addTrailingSlash = false;\n\n // A current directory, which we can always drop.\n if (piece === '.') continue;\n\n // A parent directory, we need to see if there are any real directories we can pop. Else, we\n // have an excess of parents, and we'll need to keep the \"..\".\n if (piece === '..') {\n if (positive) {\n addTrailingSlash = true;\n positive--;\n pointer--;\n } else if (rel) {\n // If we're in a relativePath, then we need to keep the excess parents. Else, in an absolute\n // URL, protocol relative URL, or an absolute path, we don't need to keep excess.\n pieces[pointer++] = piece;\n }\n continue;\n }\n\n // We've encountered a real directory. Move it to the next insertion pointer, which accounts for\n // any popped or dropped directories.\n pieces[pointer++] = piece;\n positive++;\n }\n\n let path = '';\n for (let i = 1; i < pointer; i++) {\n path += '/' + pieces[i];\n }\n if (!path || (addTrailingSlash && !path.endsWith('/..'))) {\n path += '/';\n }\n url.path = path;\n}\n\n/**\n * Attempts to resolve `input` URL/path relative to `base`.\n */\nexport default function resolve(input: string, base: string | undefined): string {\n if (!input && !base) return '';\n\n const url = parseUrl(input);\n let inputType = url.type;\n\n if (base && inputType !== UrlType.Absolute) {\n const baseUrl = parseUrl(base);\n const baseType = baseUrl.type;\n\n switch (inputType) {\n case UrlType.Empty:\n url.hash = baseUrl.hash;\n // fall through\n\n case UrlType.Hash:\n url.query = baseUrl.query;\n // fall through\n\n case UrlType.Query:\n case UrlType.RelativePath:\n mergePaths(url, baseUrl);\n // fall through\n\n case UrlType.AbsolutePath:\n // The host, user, and port are joined, you can't copy one without the others.\n url.user = baseUrl.user;\n url.host = baseUrl.host;\n url.port = baseUrl.port;\n // fall through\n\n case UrlType.SchemeRelative:\n // The input doesn't have a schema at least, so we need to copy at least that over.\n url.scheme = baseUrl.scheme;\n }\n if (baseType > inputType) inputType = baseType;\n }\n\n normalizePath(url, inputType);\n\n const queryHash = url.query + url.hash;\n switch (inputType) {\n // This is impossible, because of the empty checks at the start of the function.\n // case UrlType.Empty:\n\n case UrlType.Hash:\n case UrlType.Query:\n return queryHash;\n\n case UrlType.RelativePath: {\n // The first char is always a \"/\", and we need it to be relative.\n const path = url.path.slice(1);\n\n if (!path) return queryHash || '.';\n\n if (isRelative(base || input) && !isRelative(path)) {\n // If base started with a leading \".\", or there is no base and input started with a \".\",\n // then we need to ensure that the relative path starts with a \".\". We don't know if\n // relative starts with a \"..\", though, so check before prepending.\n return './' + path + queryHash;\n }\n\n return path + queryHash;\n }\n\n case UrlType.AbsolutePath:\n return url.path + queryHash;\n\n default:\n return url.scheme + '//' + url.user + url.host + url.port + url.path + queryHash;\n }\n}\n"],"names":[],"mappings":"AAAA;AACA,MAAM,WAAW,GAAG,gBAAgB,CAAC;AAErC;;;;;;;;;;AAUA,MAAM,QAAQ,GACZ,qFAAqF,CAAC;AAExF;;;;;;;;;AASA,MAAM,SAAS,GAAG,iEAAiE,CAAC;AAuBpF,SAAS,aAAa,CAAC,KAAa;IAClC,OAAO,WAAW,CAAC,IAAI,CAAC,KAAK,CAAC,CAAC;AACjC,CAAC;AAED,SAAS,mBAAmB,CAAC,KAAa;IACxC,OAAO,KAAK,CAAC,UAAU,CAAC,IAAI,CAAC,CAAC;AAChC,CAAC;AAED,SAAS,cAAc,CAAC,KAAa;IACnC,OAAO,KAAK,CAAC,UAAU,CAAC,GAAG,CAAC,CAAC;AAC/B,CAAC;AAED,SAAS,SAAS,CAAC,KAAa;IAC9B,OAAO,KAAK,CAAC,UAAU,CAAC,OAAO,CAAC,CAAC;AACnC,CAAC;AAED,SAAS,UAAU,CAAC,KAAa;IAC/B,OAAO,QAAQ,CAAC,IAAI,CAAC,KAAK,CAAC,CAAC;AAC9B,CAAC;AAED,SAAS,gBAAgB,CAAC,KAAa;IACrC,MAAM,KAAK,GAAG,QAAQ,CAAC,IAAI,CAAC,KAAK,CAAE,CAAC;IACpC,OAAO,OAAO,CACZ,KAAK,CAAC,CAAC,CAAC,EACR,KAAK,CAAC,CAAC,CAAC,IAAI,EAAE,EACd,KAAK,CAAC,CAAC,CAAC,EACR,KAAK,CAAC,CAAC,CAAC,IAAI,EAAE,EACd,KAAK,CAAC,CAAC,CAAC,IAAI,GAAG,EACf,KAAK,CAAC,CAAC,CAAC,IAAI,EAAE,EACd,KAAK,CAAC,CAAC,CAAC,IAAI,EAAE,CACf,CAAC;AACJ,CAAC;AAED,SAAS,YAAY,CAAC,KAAa;IACjC,MAAM,KAAK,GAAG,SAAS,CAAC,IAAI,CAAC,KAAK,CAAE,CAAC;IACrC,MAAM,IAAI,GAAG,KAAK,CAAC,CAAC,CAAC,CAAC;IACtB,OAAO,OAAO,CACZ,OAAO,EACP,EAAE,EACF,KAAK,CAAC,CAAC,CAAC,IAAI,EAAE,EACd,EAAE,EACF,cAAc,CAAC,IAAI,CAAC,GAAG,IAAI,GAAG,GAAG,GAAG,IAAI,EACxC,KAAK,CAAC,CAAC,CAAC,IAAI,EAAE,EACd,KAAK,CAAC,CAAC,CAAC,IAAI,EAAE,CACf,CAAC;AACJ,CAAC;AAED,SAAS,OAAO,CACd,MAAc,EACd,IAAY,EACZ,IAAY,EACZ,IAAY,EACZ,IAAY,EACZ,KAAa,EACb,IAAY;IAEZ,OAAO;QACL,MAAM;QACN,IAAI;QACJ,IAAI;QACJ,IAAI;QACJ,IAAI;QACJ,KAAK;QACL,IAAI;QACJ,IAAI;KACL,CAAC;AACJ,CAAC;AAED,SAAS,QAAQ,CAAC,KAAa;IAC7B,IAAI,mBAAmB,CAAC,KAAK,CAAC,EAAE;QAC9B,MAAM,GAAG,GAAG,gBAAgB,CAAC,OAAO,GAAG,KAAK,CAAC,CAAC;QAC9C,GAAG,CAAC,MAAM,GAAG,EAAE,CAAC;QAChB,GAAG,CAAC,IAAI,0BAA0B;QAClC,OAAO,GAAG,CAAC;KACZ;IAED,IAAI,cAAc,CAAC,KAAK,CAAC,EAAE;QACzB,MAAM,GAAG,GAAG,gBAAgB,CAAC,gBAAgB,GAAG,KAAK,CAAC,CAAC;QACvD,GAAG,CAAC,MAAM,GAAG,EAAE,CAAC;QAChB,GAAG,CAAC,IAAI,GAAG,EAAE,CAAC;QACd,GAAG,CAAC,IAAI,wBAAwB;QAChC,OAAO,GAAG,CAAC;KACZ;IAED,IAAI,SAAS,CAAC,KAAK,CAAC;QAAE,OAAO,YAAY,CAAC,KAAK,CAAC,CAAC;IAEjD,IAAI,aAAa,CAAC,KAAK,CAAC;QAAE,OAAO,gBAAgB,CAAC,KAAK,CAAC,CAAC;IAEzD,MAAM,GAAG,GAAG,gBAAgB,CAAC,iBAAiB,GAAG,KAAK,CAAC,CAAC;IACxD,GAAG,CAAC,MAAM,GAAG,EAAE,CAAC;IAChB,GAAG,CAAC,IAAI,GAAG,EAAE,CAAC;IACd,GAAG,CAAC,IAAI,GAAG,KAAK;UACZ,KAAK,CAAC,UAAU,CAAC,GAAG,CAAC;;cAEnB,KAAK,CAAC,UAAU,CAAC,GAAG,CAAC;;;wBAGT;IAClB,OAAO,GAAG,CAAC;AACb,CAAC;AAED,SAAS,iBAAiB,CAAC,IAAY;;;IAGrC,IAAI,IAAI,CAAC,QAAQ,CAAC,KAAK,CAAC;QAAE,OAAO,IAAI,CAAC;IACtC,MAAM,KAAK,GAAG,IAAI,CAAC,WAAW,CAAC,GAAG,CAAC,CAAC;IACpC,OAAO,IAAI,CAAC,KAAK,CAAC,CAAC,EAAE,KAAK,GAAG,CAAC,CAAC,CAAC;AAClC,CAAC;AAED,SAAS,UAAU,CAAC,GAAQ,EAAE,IAAS;IACrC,aAAa,CAAC,IAAI,EAAE,IAAI,CAAC,IAAI,CAAC,CAAC;;;IAI/B,IAAI,GAAG,CAAC,IAAI,KAAK,GAAG,EAAE;QACpB,GAAG,CAAC,IAAI,GAAG,IAAI,CAAC,IAAI,CAAC;KACtB;SAAM;;QAEL,GAAG,CAAC,IAAI,GAAG,iBAAiB,CAAC,IAAI,CAAC,IAAI,CAAC,GAAG,GAAG,CAAC,IAAI,CAAC;KACpD;AACH,CAAC;AAED;;;;AAIA,SAAS,aAAa,CAAC,GAAQ,EAAE,IAAa;IAC5C,MAAM,GAAG,GAAG,IAAI,yBAAyB;IACzC,MAAM,MAAM,GAAG,GAAG,CAAC,IAAI,CAAC,KAAK,CAAC,GAAG,CAAC,CAAC;;;IAInC,IAAI,OAAO,GAAG,CAAC,CAAC;;;IAIhB,IAAI,QAAQ,GAAG,CAAC,CAAC;;;;IAKjB,IAAI,gBAAgB,GAAG,KAAK,CAAC;IAE7B,KAAK,IAAI,CAAC,GAAG,CAAC,EAAE,CAAC,GAAG,MAAM,CAAC,MAAM,EAAE,CAAC,EAAE,EAAE;QACtC,MAAM,KAAK,GAAG,MAAM,CAAC,CAAC,CAAC,CAAC;;QAGxB,IAAI,CAAC,KAAK,EAAE;YACV,gBAAgB,GAAG,IAAI,CAAC;YACxB,SAAS;SACV;;QAGD,gBAAgB,GAAG,KAAK,CAAC;;QAGzB,IAAI,KAAK,KAAK,GAAG;YAAE,SAAS;;;QAI5B,IAAI,KAAK,KAAK,IAAI,EAAE;YAClB,IAAI,QAAQ,EAAE;gBACZ,gBAAgB,GAAG,IAAI,CAAC;gBACxB,QAAQ,EAAE,CAAC;gBACX,OAAO,EAAE,CAAC;aACX;iBAAM,IAAI,GAAG,EAAE;;;gBAGd,MAAM,CAAC,OAAO,EAAE,CAAC,GAAG,KAAK,CAAC;aAC3B;YACD,SAAS;SACV;;;QAID,MAAM,CAAC,OAAO,EAAE,CAAC,GAAG,KAAK,CAAC;QAC1B,QAAQ,EAAE,CAAC;KACZ;IAED,IAAI,IAAI,GAAG,EAAE,CAAC;IACd,KAAK,IAAI,CAAC,GAAG,CAAC,EAAE,CAAC,GAAG,OAAO,EAAE,CAAC,EAAE,EAAE;QAChC,IAAI,IAAI,GAAG,GAAG,MAAM,CAAC,CAAC,CAAC,CAAC;KACzB;IACD,IAAI,CAAC,IAAI,KAAK,gBAAgB,IAAI,CAAC,IAAI,CAAC,QAAQ,CAAC,KAAK,CAAC,CAAC,EAAE;QACxD,IAAI,IAAI,GAAG,CAAC;KACb;IACD,GAAG,CAAC,IAAI,GAAG,IAAI,CAAC;AAClB,CAAC;AAED;;;SAGwB,OAAO,CAAC,KAAa,EAAE,IAAwB;IACrE,IAAI,CAAC,KAAK,IAAI,CAAC,IAAI;QAAE,OAAO,EAAE,CAAC;IAE/B,MAAM,GAAG,GAAG,QAAQ,CAAC,KAAK,CAAC,CAAC;IAC5B,IAAI,SAAS,GAAG,GAAG,CAAC,IAAI,CAAC;IAEzB,IAAI,IAAI,IAAI,SAAS,uBAAuB;QAC1C,MAAM,OAAO,GAAG,QAAQ,CAAC,IAAI,CAAC,CAAC;QAC/B,MAAM,QAAQ,GAAG,OAAO,CAAC,IAAI,CAAC;QAE9B,QAAQ,SAAS;YACf;gBACE,GAAG,CAAC,IAAI,GAAG,OAAO,CAAC,IAAI,CAAC;;YAG1B;gBACE,GAAG,CAAC,KAAK,GAAG,OAAO,CAAC,KAAK,CAAC;;YAG5B,mBAAmB;YACnB;gBACE,UAAU,CAAC,GAAG,EAAE,OAAO,CAAC,CAAC;;YAG3B;;gBAEE,GAAG,CAAC,IAAI,GAAG,OAAO,CAAC,IAAI,CAAC;gBACxB,GAAG,CAAC,IAAI,GAAG,OAAO,CAAC,IAAI,CAAC;gBACxB,GAAG,CAAC,IAAI,GAAG,OAAO,CAAC,IAAI,CAAC;;YAG1B;;gBAEE,GAAG,CAAC,MAAM,GAAG,OAAO,CAAC,MAAM,CAAC;SAC/B;QACD,IAAI,QAAQ,GAAG,SAAS;YAAE,SAAS,GAAG,QAAQ,CAAC;KAChD;IAED,aAAa,CAAC,GAAG,EAAE,SAAS,CAAC,CAAC;IAE9B,MAAM,SAAS,GAAG,GAAG,CAAC,KAAK,GAAG,GAAG,CAAC,IAAI,CAAC;IACvC,QAAQ,SAAS;;;QAIf,kBAAkB;QAClB;YACE,OAAO,SAAS,CAAC;QAEnB,2BAA2B;;YAEzB,MAAM,IAAI,GAAG,GAAG,CAAC,IAAI,CAAC,KAAK,CAAC,CAAC,CAAC,CAAC;YAE/B,IAAI,CAAC,IAAI;gBAAE,OAAO,SAAS,IAAI,GAAG,CAAC;YAEnC,IAAI,UAAU,CAAC,IAAI,IAAI,KAAK,CAAC,IAAI,CAAC,UAAU,CAAC,IAAI,CAAC,EAAE;;;;gBAIlD,OAAO,IAAI,GAAG,IAAI,GAAG,SAAS,CAAC;aAChC;YAED,OAAO,IAAI,GAAG,SAAS,CAAC;SACzB;QAED;YACE,OAAO,GAAG,CAAC,IAAI,GAAG,SAAS,CAAC;QAE9B;YACE,OAAO,GAAG,CAAC,MAAM,GAAG,IAAI,GAAG,GAAG,CAAC,IAAI,GAAG,GAAG,CAAC,IAAI,GAAG,GAAG,CAAC,IAAI,GAAG,GAAG,CAAC,IAAI,GAAG,SAAS,CAAC;KACpF;AACH;;;;"} \ No newline at end of file diff --git a/dg-ui/node_modules/@jridgewell/resolve-uri/dist/resolve-uri.umd.js b/dg-ui/node_modules/@jridgewell/resolve-uri/dist/resolve-uri.umd.js new file mode 100644 index 0000000..d1d7204 --- /dev/null +++ b/dg-ui/node_modules/@jridgewell/resolve-uri/dist/resolve-uri.umd.js @@ -0,0 +1,240 @@ +(function (global, factory) { + typeof exports === 'object' && typeof module !== 'undefined' ? module.exports = factory() : + typeof define === 'function' && define.amd ? define(factory) : + (global = typeof globalThis !== 'undefined' ? globalThis : global || self, global.resolveURI = factory()); +})(this, (function () { 'use strict'; + + // Matches the scheme of a URL, eg "http://" + const schemeRegex = /^[\w+.-]+:\/\//; + /** + * Matches the parts of a URL: + * 1. Scheme, including ":", guaranteed. + * 2. User/password, including "@", optional. + * 3. Host, including brackets around IP literals, guaranteed. + * 4. Port, including ":", optional. + * 5. Path, including "/", optional. + * 6. Query, including "?", optional. + * 7. Hash, including "#", optional. + */ + const urlRegex = /^([\w+.-]+:)\/\/([^@/#?]*@)?(\[[^\]]+\]|[^:/#?]*)(:\d+)?(\/[^#?]*)?(\?[^#]*)?(#.*)?/; + /** + * File URLs are weird. They dont' need the regular `//` in the scheme, they may or may not start + * with a leading `/`, they can have a domain (but only if they don't start with a Windows drive). + * + * 1. Host, optional. + * 2. Path, which may include "/", guaranteed. + * 3. Query, including "?", optional. + * 4. Hash, including "#", optional. + */ + const fileRegex = /^file:(?:\/\/((?![a-z]:)[^/#?]*)?)?(\/?[^#?]*)(\?[^#]*)?(#.*)?/i; + function isAbsoluteUrl(input) { + return schemeRegex.test(input); + } + function isSchemeRelativeUrl(input) { + return input.startsWith('//'); + } + function isAbsolutePath(input) { + return input.startsWith('/'); + } + function isFileUrl(input) { + return input.startsWith('file:'); + } + function isRelative(input) { + return /^[.?#]/.test(input); + } + function parseAbsoluteUrl(input) { + const match = urlRegex.exec(input); + return makeUrl(match[1], match[2] || '', match[3], match[4] || '', match[5] || '/', match[6] || '', match[7] || ''); + } + function parseFileUrl(input) { + const match = fileRegex.exec(input); + const path = match[2]; + return makeUrl('file:', '', match[1] || '', '', isAbsolutePath(path) ? path : '/' + path, match[3] || '', match[4] || ''); + } + function makeUrl(scheme, user, host, port, path, query, hash) { + return { + scheme, + user, + host, + port, + path, + query, + hash, + type: 7 /* Absolute */, + }; + } + function parseUrl(input) { + if (isSchemeRelativeUrl(input)) { + const url = parseAbsoluteUrl('http:' + input); + url.scheme = ''; + url.type = 6 /* SchemeRelative */; + return url; + } + if (isAbsolutePath(input)) { + const url = parseAbsoluteUrl('http://foo.com' + input); + url.scheme = ''; + url.host = ''; + url.type = 5 /* AbsolutePath */; + return url; + } + if (isFileUrl(input)) + return parseFileUrl(input); + if (isAbsoluteUrl(input)) + return parseAbsoluteUrl(input); + const url = parseAbsoluteUrl('http://foo.com/' + input); + url.scheme = ''; + url.host = ''; + url.type = input + ? input.startsWith('?') + ? 3 /* Query */ + : input.startsWith('#') + ? 2 /* Hash */ + : 4 /* RelativePath */ + : 1 /* Empty */; + return url; + } + function stripPathFilename(path) { + // If a path ends with a parent directory "..", then it's a relative path with excess parent + // paths. It's not a file, so we can't strip it. + if (path.endsWith('/..')) + return path; + const index = path.lastIndexOf('/'); + return path.slice(0, index + 1); + } + function mergePaths(url, base) { + normalizePath(base, base.type); + // If the path is just a "/", then it was an empty path to begin with (remember, we're a relative + // path). + if (url.path === '/') { + url.path = base.path; + } + else { + // Resolution happens relative to the base path's directory, not the file. + url.path = stripPathFilename(base.path) + url.path; + } + } + /** + * The path can have empty directories "//", unneeded parents "foo/..", or current directory + * "foo/.". We need to normalize to a standard representation. + */ + function normalizePath(url, type) { + const rel = type <= 4 /* RelativePath */; + const pieces = url.path.split('/'); + // We need to preserve the first piece always, so that we output a leading slash. The item at + // pieces[0] is an empty string. + let pointer = 1; + // Positive is the number of real directories we've output, used for popping a parent directory. + // Eg, "foo/bar/.." will have a positive 2, and we can decrement to be left with just "foo". + let positive = 0; + // We need to keep a trailing slash if we encounter an empty directory (eg, splitting "foo/" will + // generate `["foo", ""]` pieces). And, if we pop a parent directory. But once we encounter a + // real directory, we won't need to append, unless the other conditions happen again. + let addTrailingSlash = false; + for (let i = 1; i < pieces.length; i++) { + const piece = pieces[i]; + // An empty directory, could be a trailing slash, or just a double "//" in the path. + if (!piece) { + addTrailingSlash = true; + continue; + } + // If we encounter a real directory, then we don't need to append anymore. + addTrailingSlash = false; + // A current directory, which we can always drop. + if (piece === '.') + continue; + // A parent directory, we need to see if there are any real directories we can pop. Else, we + // have an excess of parents, and we'll need to keep the "..". + if (piece === '..') { + if (positive) { + addTrailingSlash = true; + positive--; + pointer--; + } + else if (rel) { + // If we're in a relativePath, then we need to keep the excess parents. Else, in an absolute + // URL, protocol relative URL, or an absolute path, we don't need to keep excess. + pieces[pointer++] = piece; + } + continue; + } + // We've encountered a real directory. Move it to the next insertion pointer, which accounts for + // any popped or dropped directories. + pieces[pointer++] = piece; + positive++; + } + let path = ''; + for (let i = 1; i < pointer; i++) { + path += '/' + pieces[i]; + } + if (!path || (addTrailingSlash && !path.endsWith('/..'))) { + path += '/'; + } + url.path = path; + } + /** + * Attempts to resolve `input` URL/path relative to `base`. + */ + function resolve(input, base) { + if (!input && !base) + return ''; + const url = parseUrl(input); + let inputType = url.type; + if (base && inputType !== 7 /* Absolute */) { + const baseUrl = parseUrl(base); + const baseType = baseUrl.type; + switch (inputType) { + case 1 /* Empty */: + url.hash = baseUrl.hash; + // fall through + case 2 /* Hash */: + url.query = baseUrl.query; + // fall through + case 3 /* Query */: + case 4 /* RelativePath */: + mergePaths(url, baseUrl); + // fall through + case 5 /* AbsolutePath */: + // The host, user, and port are joined, you can't copy one without the others. + url.user = baseUrl.user; + url.host = baseUrl.host; + url.port = baseUrl.port; + // fall through + case 6 /* SchemeRelative */: + // The input doesn't have a schema at least, so we need to copy at least that over. + url.scheme = baseUrl.scheme; + } + if (baseType > inputType) + inputType = baseType; + } + normalizePath(url, inputType); + const queryHash = url.query + url.hash; + switch (inputType) { + // This is impossible, because of the empty checks at the start of the function. + // case UrlType.Empty: + case 2 /* Hash */: + case 3 /* Query */: + return queryHash; + case 4 /* RelativePath */: { + // The first char is always a "/", and we need it to be relative. + const path = url.path.slice(1); + if (!path) + return queryHash || '.'; + if (isRelative(base || input) && !isRelative(path)) { + // If base started with a leading ".", or there is no base and input started with a ".", + // then we need to ensure that the relative path starts with a ".". We don't know if + // relative starts with a "..", though, so check before prepending. + return './' + path + queryHash; + } + return path + queryHash; + } + case 5 /* AbsolutePath */: + return url.path + queryHash; + default: + return url.scheme + '//' + url.user + url.host + url.port + url.path + queryHash; + } + } + + return resolve; + +})); +//# sourceMappingURL=resolve-uri.umd.js.map diff --git a/dg-ui/node_modules/@jridgewell/resolve-uri/dist/resolve-uri.umd.js.map b/dg-ui/node_modules/@jridgewell/resolve-uri/dist/resolve-uri.umd.js.map new file mode 100644 index 0000000..09641c7 --- /dev/null +++ b/dg-ui/node_modules/@jridgewell/resolve-uri/dist/resolve-uri.umd.js.map @@ -0,0 +1 @@ +{"version":3,"file":"resolve-uri.umd.js","sources":["../src/resolve-uri.ts"],"sourcesContent":["// Matches the scheme of a URL, eg \"http://\"\nconst schemeRegex = /^[\\w+.-]+:\\/\\//;\n\n/**\n * Matches the parts of a URL:\n * 1. Scheme, including \":\", guaranteed.\n * 2. User/password, including \"@\", optional.\n * 3. Host, including brackets around IP literals, guaranteed.\n * 4. Port, including \":\", optional.\n * 5. Path, including \"/\", optional.\n * 6. Query, including \"?\", optional.\n * 7. Hash, including \"#\", optional.\n */\nconst urlRegex =\n /^([\\w+.-]+:)\\/\\/([^@/#?]*@)?(\\[[^\\]]+\\]|[^:/#?]*)(:\\d+)?(\\/[^#?]*)?(\\?[^#]*)?(#.*)?/;\n\n/**\n * File URLs are weird. They dont' need the regular `//` in the scheme, they may or may not start\n * with a leading `/`, they can have a domain (but only if they don't start with a Windows drive).\n *\n * 1. Host, optional.\n * 2. Path, which may include \"/\", guaranteed.\n * 3. Query, including \"?\", optional.\n * 4. Hash, including \"#\", optional.\n */\nconst fileRegex = /^file:(?:\\/\\/((?![a-z]:)[^/#?]*)?)?(\\/?[^#?]*)(\\?[^#]*)?(#.*)?/i;\n\ntype Url = {\n scheme: string;\n user: string;\n host: string;\n port: string;\n path: string;\n query: string;\n hash: string;\n type: UrlType;\n};\n\nconst enum UrlType {\n Empty = 1,\n Hash = 2,\n Query = 3,\n RelativePath = 4,\n AbsolutePath = 5,\n SchemeRelative = 6,\n Absolute = 7,\n}\n\nfunction isAbsoluteUrl(input: string): boolean {\n return schemeRegex.test(input);\n}\n\nfunction isSchemeRelativeUrl(input: string): boolean {\n return input.startsWith('//');\n}\n\nfunction isAbsolutePath(input: string): boolean {\n return input.startsWith('/');\n}\n\nfunction isFileUrl(input: string): boolean {\n return input.startsWith('file:');\n}\n\nfunction isRelative(input: string): boolean {\n return /^[.?#]/.test(input);\n}\n\nfunction parseAbsoluteUrl(input: string): Url {\n const match = urlRegex.exec(input)!;\n return makeUrl(\n match[1],\n match[2] || '',\n match[3],\n match[4] || '',\n match[5] || '/',\n match[6] || '',\n match[7] || '',\n );\n}\n\nfunction parseFileUrl(input: string): Url {\n const match = fileRegex.exec(input)!;\n const path = match[2];\n return makeUrl(\n 'file:',\n '',\n match[1] || '',\n '',\n isAbsolutePath(path) ? path : '/' + path,\n match[3] || '',\n match[4] || '',\n );\n}\n\nfunction makeUrl(\n scheme: string,\n user: string,\n host: string,\n port: string,\n path: string,\n query: string,\n hash: string,\n): Url {\n return {\n scheme,\n user,\n host,\n port,\n path,\n query,\n hash,\n type: UrlType.Absolute,\n };\n}\n\nfunction parseUrl(input: string): Url {\n if (isSchemeRelativeUrl(input)) {\n const url = parseAbsoluteUrl('http:' + input);\n url.scheme = '';\n url.type = UrlType.SchemeRelative;\n return url;\n }\n\n if (isAbsolutePath(input)) {\n const url = parseAbsoluteUrl('http://foo.com' + input);\n url.scheme = '';\n url.host = '';\n url.type = UrlType.AbsolutePath;\n return url;\n }\n\n if (isFileUrl(input)) return parseFileUrl(input);\n\n if (isAbsoluteUrl(input)) return parseAbsoluteUrl(input);\n\n const url = parseAbsoluteUrl('http://foo.com/' + input);\n url.scheme = '';\n url.host = '';\n url.type = input\n ? input.startsWith('?')\n ? UrlType.Query\n : input.startsWith('#')\n ? UrlType.Hash\n : UrlType.RelativePath\n : UrlType.Empty;\n return url;\n}\n\nfunction stripPathFilename(path: string): string {\n // If a path ends with a parent directory \"..\", then it's a relative path with excess parent\n // paths. It's not a file, so we can't strip it.\n if (path.endsWith('/..')) return path;\n const index = path.lastIndexOf('/');\n return path.slice(0, index + 1);\n}\n\nfunction mergePaths(url: Url, base: Url) {\n normalizePath(base, base.type);\n\n // If the path is just a \"/\", then it was an empty path to begin with (remember, we're a relative\n // path).\n if (url.path === '/') {\n url.path = base.path;\n } else {\n // Resolution happens relative to the base path's directory, not the file.\n url.path = stripPathFilename(base.path) + url.path;\n }\n}\n\n/**\n * The path can have empty directories \"//\", unneeded parents \"foo/..\", or current directory\n * \"foo/.\". We need to normalize to a standard representation.\n */\nfunction normalizePath(url: Url, type: UrlType) {\n const rel = type <= UrlType.RelativePath;\n const pieces = url.path.split('/');\n\n // We need to preserve the first piece always, so that we output a leading slash. The item at\n // pieces[0] is an empty string.\n let pointer = 1;\n\n // Positive is the number of real directories we've output, used for popping a parent directory.\n // Eg, \"foo/bar/..\" will have a positive 2, and we can decrement to be left with just \"foo\".\n let positive = 0;\n\n // We need to keep a trailing slash if we encounter an empty directory (eg, splitting \"foo/\" will\n // generate `[\"foo\", \"\"]` pieces). And, if we pop a parent directory. But once we encounter a\n // real directory, we won't need to append, unless the other conditions happen again.\n let addTrailingSlash = false;\n\n for (let i = 1; i < pieces.length; i++) {\n const piece = pieces[i];\n\n // An empty directory, could be a trailing slash, or just a double \"//\" in the path.\n if (!piece) {\n addTrailingSlash = true;\n continue;\n }\n\n // If we encounter a real directory, then we don't need to append anymore.\n addTrailingSlash = false;\n\n // A current directory, which we can always drop.\n if (piece === '.') continue;\n\n // A parent directory, we need to see if there are any real directories we can pop. Else, we\n // have an excess of parents, and we'll need to keep the \"..\".\n if (piece === '..') {\n if (positive) {\n addTrailingSlash = true;\n positive--;\n pointer--;\n } else if (rel) {\n // If we're in a relativePath, then we need to keep the excess parents. Else, in an absolute\n // URL, protocol relative URL, or an absolute path, we don't need to keep excess.\n pieces[pointer++] = piece;\n }\n continue;\n }\n\n // We've encountered a real directory. Move it to the next insertion pointer, which accounts for\n // any popped or dropped directories.\n pieces[pointer++] = piece;\n positive++;\n }\n\n let path = '';\n for (let i = 1; i < pointer; i++) {\n path += '/' + pieces[i];\n }\n if (!path || (addTrailingSlash && !path.endsWith('/..'))) {\n path += '/';\n }\n url.path = path;\n}\n\n/**\n * Attempts to resolve `input` URL/path relative to `base`.\n */\nexport default function resolve(input: string, base: string | undefined): string {\n if (!input && !base) return '';\n\n const url = parseUrl(input);\n let inputType = url.type;\n\n if (base && inputType !== UrlType.Absolute) {\n const baseUrl = parseUrl(base);\n const baseType = baseUrl.type;\n\n switch (inputType) {\n case UrlType.Empty:\n url.hash = baseUrl.hash;\n // fall through\n\n case UrlType.Hash:\n url.query = baseUrl.query;\n // fall through\n\n case UrlType.Query:\n case UrlType.RelativePath:\n mergePaths(url, baseUrl);\n // fall through\n\n case UrlType.AbsolutePath:\n // The host, user, and port are joined, you can't copy one without the others.\n url.user = baseUrl.user;\n url.host = baseUrl.host;\n url.port = baseUrl.port;\n // fall through\n\n case UrlType.SchemeRelative:\n // The input doesn't have a schema at least, so we need to copy at least that over.\n url.scheme = baseUrl.scheme;\n }\n if (baseType > inputType) inputType = baseType;\n }\n\n normalizePath(url, inputType);\n\n const queryHash = url.query + url.hash;\n switch (inputType) {\n // This is impossible, because of the empty checks at the start of the function.\n // case UrlType.Empty:\n\n case UrlType.Hash:\n case UrlType.Query:\n return queryHash;\n\n case UrlType.RelativePath: {\n // The first char is always a \"/\", and we need it to be relative.\n const path = url.path.slice(1);\n\n if (!path) return queryHash || '.';\n\n if (isRelative(base || input) && !isRelative(path)) {\n // If base started with a leading \".\", or there is no base and input started with a \".\",\n // then we need to ensure that the relative path starts with a \".\". We don't know if\n // relative starts with a \"..\", though, so check before prepending.\n return './' + path + queryHash;\n }\n\n return path + queryHash;\n }\n\n case UrlType.AbsolutePath:\n return url.path + queryHash;\n\n default:\n return url.scheme + '//' + url.user + url.host + url.port + url.path + queryHash;\n }\n}\n"],"names":[],"mappings":";;;;;;IAAA;IACA,MAAM,WAAW,GAAG,gBAAgB,CAAC;IAErC;;;;;;;;;;IAUA,MAAM,QAAQ,GACZ,qFAAqF,CAAC;IAExF;;;;;;;;;IASA,MAAM,SAAS,GAAG,iEAAiE,CAAC;IAuBpF,SAAS,aAAa,CAAC,KAAa;QAClC,OAAO,WAAW,CAAC,IAAI,CAAC,KAAK,CAAC,CAAC;IACjC,CAAC;IAED,SAAS,mBAAmB,CAAC,KAAa;QACxC,OAAO,KAAK,CAAC,UAAU,CAAC,IAAI,CAAC,CAAC;IAChC,CAAC;IAED,SAAS,cAAc,CAAC,KAAa;QACnC,OAAO,KAAK,CAAC,UAAU,CAAC,GAAG,CAAC,CAAC;IAC/B,CAAC;IAED,SAAS,SAAS,CAAC,KAAa;QAC9B,OAAO,KAAK,CAAC,UAAU,CAAC,OAAO,CAAC,CAAC;IACnC,CAAC;IAED,SAAS,UAAU,CAAC,KAAa;QAC/B,OAAO,QAAQ,CAAC,IAAI,CAAC,KAAK,CAAC,CAAC;IAC9B,CAAC;IAED,SAAS,gBAAgB,CAAC,KAAa;QACrC,MAAM,KAAK,GAAG,QAAQ,CAAC,IAAI,CAAC,KAAK,CAAE,CAAC;QACpC,OAAO,OAAO,CACZ,KAAK,CAAC,CAAC,CAAC,EACR,KAAK,CAAC,CAAC,CAAC,IAAI,EAAE,EACd,KAAK,CAAC,CAAC,CAAC,EACR,KAAK,CAAC,CAAC,CAAC,IAAI,EAAE,EACd,KAAK,CAAC,CAAC,CAAC,IAAI,GAAG,EACf,KAAK,CAAC,CAAC,CAAC,IAAI,EAAE,EACd,KAAK,CAAC,CAAC,CAAC,IAAI,EAAE,CACf,CAAC;IACJ,CAAC;IAED,SAAS,YAAY,CAAC,KAAa;QACjC,MAAM,KAAK,GAAG,SAAS,CAAC,IAAI,CAAC,KAAK,CAAE,CAAC;QACrC,MAAM,IAAI,GAAG,KAAK,CAAC,CAAC,CAAC,CAAC;QACtB,OAAO,OAAO,CACZ,OAAO,EACP,EAAE,EACF,KAAK,CAAC,CAAC,CAAC,IAAI,EAAE,EACd,EAAE,EACF,cAAc,CAAC,IAAI,CAAC,GAAG,IAAI,GAAG,GAAG,GAAG,IAAI,EACxC,KAAK,CAAC,CAAC,CAAC,IAAI,EAAE,EACd,KAAK,CAAC,CAAC,CAAC,IAAI,EAAE,CACf,CAAC;IACJ,CAAC;IAED,SAAS,OAAO,CACd,MAAc,EACd,IAAY,EACZ,IAAY,EACZ,IAAY,EACZ,IAAY,EACZ,KAAa,EACb,IAAY;QAEZ,OAAO;YACL,MAAM;YACN,IAAI;YACJ,IAAI;YACJ,IAAI;YACJ,IAAI;YACJ,KAAK;YACL,IAAI;YACJ,IAAI;SACL,CAAC;IACJ,CAAC;IAED,SAAS,QAAQ,CAAC,KAAa;QAC7B,IAAI,mBAAmB,CAAC,KAAK,CAAC,EAAE;YAC9B,MAAM,GAAG,GAAG,gBAAgB,CAAC,OAAO,GAAG,KAAK,CAAC,CAAC;YAC9C,GAAG,CAAC,MAAM,GAAG,EAAE,CAAC;YAChB,GAAG,CAAC,IAAI,0BAA0B;YAClC,OAAO,GAAG,CAAC;SACZ;QAED,IAAI,cAAc,CAAC,KAAK,CAAC,EAAE;YACzB,MAAM,GAAG,GAAG,gBAAgB,CAAC,gBAAgB,GAAG,KAAK,CAAC,CAAC;YACvD,GAAG,CAAC,MAAM,GAAG,EAAE,CAAC;YAChB,GAAG,CAAC,IAAI,GAAG,EAAE,CAAC;YACd,GAAG,CAAC,IAAI,wBAAwB;YAChC,OAAO,GAAG,CAAC;SACZ;QAED,IAAI,SAAS,CAAC,KAAK,CAAC;YAAE,OAAO,YAAY,CAAC,KAAK,CAAC,CAAC;QAEjD,IAAI,aAAa,CAAC,KAAK,CAAC;YAAE,OAAO,gBAAgB,CAAC,KAAK,CAAC,CAAC;QAEzD,MAAM,GAAG,GAAG,gBAAgB,CAAC,iBAAiB,GAAG,KAAK,CAAC,CAAC;QACxD,GAAG,CAAC,MAAM,GAAG,EAAE,CAAC;QAChB,GAAG,CAAC,IAAI,GAAG,EAAE,CAAC;QACd,GAAG,CAAC,IAAI,GAAG,KAAK;cACZ,KAAK,CAAC,UAAU,CAAC,GAAG,CAAC;;kBAEnB,KAAK,CAAC,UAAU,CAAC,GAAG,CAAC;;;4BAGT;QAClB,OAAO,GAAG,CAAC;IACb,CAAC;IAED,SAAS,iBAAiB,CAAC,IAAY;;;QAGrC,IAAI,IAAI,CAAC,QAAQ,CAAC,KAAK,CAAC;YAAE,OAAO,IAAI,CAAC;QACtC,MAAM,KAAK,GAAG,IAAI,CAAC,WAAW,CAAC,GAAG,CAAC,CAAC;QACpC,OAAO,IAAI,CAAC,KAAK,CAAC,CAAC,EAAE,KAAK,GAAG,CAAC,CAAC,CAAC;IAClC,CAAC;IAED,SAAS,UAAU,CAAC,GAAQ,EAAE,IAAS;QACrC,aAAa,CAAC,IAAI,EAAE,IAAI,CAAC,IAAI,CAAC,CAAC;;;QAI/B,IAAI,GAAG,CAAC,IAAI,KAAK,GAAG,EAAE;YACpB,GAAG,CAAC,IAAI,GAAG,IAAI,CAAC,IAAI,CAAC;SACtB;aAAM;;YAEL,GAAG,CAAC,IAAI,GAAG,iBAAiB,CAAC,IAAI,CAAC,IAAI,CAAC,GAAG,GAAG,CAAC,IAAI,CAAC;SACpD;IACH,CAAC;IAED;;;;IAIA,SAAS,aAAa,CAAC,GAAQ,EAAE,IAAa;QAC5C,MAAM,GAAG,GAAG,IAAI,yBAAyB;QACzC,MAAM,MAAM,GAAG,GAAG,CAAC,IAAI,CAAC,KAAK,CAAC,GAAG,CAAC,CAAC;;;QAInC,IAAI,OAAO,GAAG,CAAC,CAAC;;;QAIhB,IAAI,QAAQ,GAAG,CAAC,CAAC;;;;QAKjB,IAAI,gBAAgB,GAAG,KAAK,CAAC;QAE7B,KAAK,IAAI,CAAC,GAAG,CAAC,EAAE,CAAC,GAAG,MAAM,CAAC,MAAM,EAAE,CAAC,EAAE,EAAE;YACtC,MAAM,KAAK,GAAG,MAAM,CAAC,CAAC,CAAC,CAAC;;YAGxB,IAAI,CAAC,KAAK,EAAE;gBACV,gBAAgB,GAAG,IAAI,CAAC;gBACxB,SAAS;aACV;;YAGD,gBAAgB,GAAG,KAAK,CAAC;;YAGzB,IAAI,KAAK,KAAK,GAAG;gBAAE,SAAS;;;YAI5B,IAAI,KAAK,KAAK,IAAI,EAAE;gBAClB,IAAI,QAAQ,EAAE;oBACZ,gBAAgB,GAAG,IAAI,CAAC;oBACxB,QAAQ,EAAE,CAAC;oBACX,OAAO,EAAE,CAAC;iBACX;qBAAM,IAAI,GAAG,EAAE;;;oBAGd,MAAM,CAAC,OAAO,EAAE,CAAC,GAAG,KAAK,CAAC;iBAC3B;gBACD,SAAS;aACV;;;YAID,MAAM,CAAC,OAAO,EAAE,CAAC,GAAG,KAAK,CAAC;YAC1B,QAAQ,EAAE,CAAC;SACZ;QAED,IAAI,IAAI,GAAG,EAAE,CAAC;QACd,KAAK,IAAI,CAAC,GAAG,CAAC,EAAE,CAAC,GAAG,OAAO,EAAE,CAAC,EAAE,EAAE;YAChC,IAAI,IAAI,GAAG,GAAG,MAAM,CAAC,CAAC,CAAC,CAAC;SACzB;QACD,IAAI,CAAC,IAAI,KAAK,gBAAgB,IAAI,CAAC,IAAI,CAAC,QAAQ,CAAC,KAAK,CAAC,CAAC,EAAE;YACxD,IAAI,IAAI,GAAG,CAAC;SACb;QACD,GAAG,CAAC,IAAI,GAAG,IAAI,CAAC;IAClB,CAAC;IAED;;;aAGwB,OAAO,CAAC,KAAa,EAAE,IAAwB;QACrE,IAAI,CAAC,KAAK,IAAI,CAAC,IAAI;YAAE,OAAO,EAAE,CAAC;QAE/B,MAAM,GAAG,GAAG,QAAQ,CAAC,KAAK,CAAC,CAAC;QAC5B,IAAI,SAAS,GAAG,GAAG,CAAC,IAAI,CAAC;QAEzB,IAAI,IAAI,IAAI,SAAS,uBAAuB;YAC1C,MAAM,OAAO,GAAG,QAAQ,CAAC,IAAI,CAAC,CAAC;YAC/B,MAAM,QAAQ,GAAG,OAAO,CAAC,IAAI,CAAC;YAE9B,QAAQ,SAAS;gBACf;oBACE,GAAG,CAAC,IAAI,GAAG,OAAO,CAAC,IAAI,CAAC;;gBAG1B;oBACE,GAAG,CAAC,KAAK,GAAG,OAAO,CAAC,KAAK,CAAC;;gBAG5B,mBAAmB;gBACnB;oBACE,UAAU,CAAC,GAAG,EAAE,OAAO,CAAC,CAAC;;gBAG3B;;oBAEE,GAAG,CAAC,IAAI,GAAG,OAAO,CAAC,IAAI,CAAC;oBACxB,GAAG,CAAC,IAAI,GAAG,OAAO,CAAC,IAAI,CAAC;oBACxB,GAAG,CAAC,IAAI,GAAG,OAAO,CAAC,IAAI,CAAC;;gBAG1B;;oBAEE,GAAG,CAAC,MAAM,GAAG,OAAO,CAAC,MAAM,CAAC;aAC/B;YACD,IAAI,QAAQ,GAAG,SAAS;gBAAE,SAAS,GAAG,QAAQ,CAAC;SAChD;QAED,aAAa,CAAC,GAAG,EAAE,SAAS,CAAC,CAAC;QAE9B,MAAM,SAAS,GAAG,GAAG,CAAC,KAAK,GAAG,GAAG,CAAC,IAAI,CAAC;QACvC,QAAQ,SAAS;;;YAIf,kBAAkB;YAClB;gBACE,OAAO,SAAS,CAAC;YAEnB,2BAA2B;;gBAEzB,MAAM,IAAI,GAAG,GAAG,CAAC,IAAI,CAAC,KAAK,CAAC,CAAC,CAAC,CAAC;gBAE/B,IAAI,CAAC,IAAI;oBAAE,OAAO,SAAS,IAAI,GAAG,CAAC;gBAEnC,IAAI,UAAU,CAAC,IAAI,IAAI,KAAK,CAAC,IAAI,CAAC,UAAU,CAAC,IAAI,CAAC,EAAE;;;;oBAIlD,OAAO,IAAI,GAAG,IAAI,GAAG,SAAS,CAAC;iBAChC;gBAED,OAAO,IAAI,GAAG,SAAS,CAAC;aACzB;YAED;gBACE,OAAO,GAAG,CAAC,IAAI,GAAG,SAAS,CAAC;YAE9B;gBACE,OAAO,GAAG,CAAC,MAAM,GAAG,IAAI,GAAG,GAAG,CAAC,IAAI,GAAG,GAAG,CAAC,IAAI,GAAG,GAAG,CAAC,IAAI,GAAG,GAAG,CAAC,IAAI,GAAG,SAAS,CAAC;SACpF;IACH;;;;;;;;"} \ No newline at end of file diff --git a/dg-ui/node_modules/@jridgewell/resolve-uri/dist/types/resolve-uri.d.ts b/dg-ui/node_modules/@jridgewell/resolve-uri/dist/types/resolve-uri.d.ts new file mode 100644 index 0000000..b7f0b3b --- /dev/null +++ b/dg-ui/node_modules/@jridgewell/resolve-uri/dist/types/resolve-uri.d.ts @@ -0,0 +1,4 @@ +/** + * Attempts to resolve `input` URL/path relative to `base`. + */ +export default function resolve(input: string, base: string | undefined): string; diff --git a/dg-ui/node_modules/@jridgewell/resolve-uri/package.json b/dg-ui/node_modules/@jridgewell/resolve-uri/package.json new file mode 100644 index 0000000..8d69ed3 --- /dev/null +++ b/dg-ui/node_modules/@jridgewell/resolve-uri/package.json @@ -0,0 +1,69 @@ +{ + "name": "@jridgewell/resolve-uri", + "version": "3.1.3", + "description": "Resolve a URI relative to an optional base URI", + "keywords": [ + "resolve", + "uri", + "url", + "path" + ], + "author": "Justin Ridgewell ", + "license": "MIT", + "repository": "https://github.com/jridgewell/resolve-uri", + "main": "dist/resolve-uri.umd.js", + "module": "dist/resolve-uri.mjs", + "types": "dist/types/resolve-uri.d.ts", + "exports": { + ".": [ + { + "types": "./dist/types/resolve-uri.d.ts", + "browser": "./dist/resolve-uri.umd.js", + "require": "./dist/resolve-uri.umd.js", + "import": "./dist/resolve-uri.mjs" + }, + "./dist/resolve-uri.umd.js" + ], + "./package.json": "./package.json" + }, + "files": [ + "dist" + ], + "engines": { + "node": ">=6.0.0" + }, + "scripts": { + "prebuild": "rm -rf dist", + "build": "run-s -n build:*", + "build:rollup": "rollup -c rollup.config.js", + "build:ts": "tsc --project tsconfig.build.json", + "lint": "run-s -n lint:*", + "lint:prettier": "npm run test:lint:prettier -- --write", + "lint:ts": "npm run test:lint:ts -- --fix", + "pretest": "run-s build:rollup", + "test": "run-s -n test:lint test:only", + "test:debug": "mocha --inspect-brk", + "test:lint": "run-s -n test:lint:*", + "test:lint:prettier": "prettier --check '{src,test}/**/*.ts'", + "test:lint:ts": "eslint '{src,test}/**/*.ts'", + "test:only": "mocha", + "test:coverage": "c8 mocha", + "test:watch": "mocha --watch", + "prepublishOnly": "npm run preversion", + "preversion": "run-s test build" + }, + "devDependencies": { + "@jridgewell/resolve-uri-latest": "npm:@jridgewell/resolve-uri@*", + "@rollup/plugin-typescript": "8.3.0", + "@typescript-eslint/eslint-plugin": "5.10.0", + "@typescript-eslint/parser": "5.10.0", + "c8": "7.11.0", + "eslint": "8.7.0", + "eslint-config-prettier": "8.3.0", + "mocha": "9.2.0", + "npm-run-all": "4.1.5", + "prettier": "2.5.1", + "rollup": "2.66.0", + "typescript": "4.5.5" + } +} diff --git a/dg-ui/node_modules/@jridgewell/sourcemap-codec/LICENSE b/dg-ui/node_modules/@jridgewell/sourcemap-codec/LICENSE new file mode 100644 index 0000000..1f6ce94 --- /dev/null +++ b/dg-ui/node_modules/@jridgewell/sourcemap-codec/LICENSE @@ -0,0 +1,19 @@ +Copyright 2024 Justin Ridgewell + +Permission is hereby granted, free of charge, to any person obtaining a copy +of this software and associated documentation files (the "Software"), to deal +in the Software without restriction, including without limitation the rights +to use, copy, modify, merge, publish, distribute, sublicense, and/or sell +copies of the Software, and to permit persons to whom the Software is +furnished to do so, subject to the following conditions: + +The above copyright notice and this permission notice shall be included in +all copies or substantial portions of the Software. + +THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR +IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, +FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE +AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER +LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, +OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE +SOFTWARE. diff --git a/dg-ui/node_modules/@jridgewell/sourcemap-codec/README.md b/dg-ui/node_modules/@jridgewell/sourcemap-codec/README.md new file mode 100644 index 0000000..b3e0708 --- /dev/null +++ b/dg-ui/node_modules/@jridgewell/sourcemap-codec/README.md @@ -0,0 +1,264 @@ +# @jridgewell/sourcemap-codec + +Encode/decode the `mappings` property of a [sourcemap](https://docs.google.com/document/d/1U1RGAehQwRypUTovF1KRlpiOFze0b-_2gc6fAH0KY0k/edit). + + +## Why? + +Sourcemaps are difficult to generate and manipulate, because the `mappings` property – the part that actually links the generated code back to the original source – is encoded using an obscure method called [Variable-length quantity](https://en.wikipedia.org/wiki/Variable-length_quantity). On top of that, each segment in the mapping contains offsets rather than absolute indices, which means that you can't look at a segment in isolation – you have to understand the whole sourcemap. + +This package makes the process slightly easier. + + +## Installation + +```bash +npm install @jridgewell/sourcemap-codec +``` + + +## Usage + +```js +import { encode, decode } from '@jridgewell/sourcemap-codec'; + +var decoded = decode( ';EAEEA,EAAE,EAAC,CAAE;ECQY,UACC' ); + +assert.deepEqual( decoded, [ + // the first line (of the generated code) has no mappings, + // as shown by the starting semi-colon (which separates lines) + [], + + // the second line contains four (comma-separated) segments + [ + // segments are encoded as you'd expect: + // [ generatedCodeColumn, sourceIndex, sourceCodeLine, sourceCodeColumn, nameIndex ] + + // i.e. the first segment begins at column 2, and maps back to the second column + // of the second line (both zero-based) of the 0th source, and uses the 0th + // name in the `map.names` array + [ 2, 0, 2, 2, 0 ], + + // the remaining segments are 4-length rather than 5-length, + // because they don't map a name + [ 4, 0, 2, 4 ], + [ 6, 0, 2, 5 ], + [ 7, 0, 2, 7 ] + ], + + // the final line contains two segments + [ + [ 2, 1, 10, 19 ], + [ 12, 1, 11, 20 ] + ] +]); + +var encoded = encode( decoded ); +assert.equal( encoded, ';EAEEA,EAAE,EAAC,CAAE;ECQY,UACC' ); +``` + +## Benchmarks + +``` +node v20.10.0 + +amp.js.map - 45120 segments + +Decode Memory Usage: +local code 5815135 bytes +@jridgewell/sourcemap-codec 1.4.15 5868160 bytes +sourcemap-codec 5492584 bytes +source-map-0.6.1 13569984 bytes +source-map-0.8.0 6390584 bytes +chrome dev tools 8011136 bytes +Smallest memory usage is sourcemap-codec + +Decode speed: +decode: local code x 492 ops/sec ±1.22% (90 runs sampled) +decode: @jridgewell/sourcemap-codec 1.4.15 x 499 ops/sec ±1.16% (89 runs sampled) +decode: sourcemap-codec x 376 ops/sec ±1.66% (89 runs sampled) +decode: source-map-0.6.1 x 34.99 ops/sec ±0.94% (48 runs sampled) +decode: source-map-0.8.0 x 351 ops/sec ±0.07% (95 runs sampled) +chrome dev tools x 165 ops/sec ±0.91% (86 runs sampled) +Fastest is decode: @jridgewell/sourcemap-codec 1.4.15 + +Encode Memory Usage: +local code 444248 bytes +@jridgewell/sourcemap-codec 1.4.15 623024 bytes +sourcemap-codec 8696280 bytes +source-map-0.6.1 8745176 bytes +source-map-0.8.0 8736624 bytes +Smallest memory usage is local code + +Encode speed: +encode: local code x 796 ops/sec ±0.11% (97 runs sampled) +encode: @jridgewell/sourcemap-codec 1.4.15 x 795 ops/sec ±0.25% (98 runs sampled) +encode: sourcemap-codec x 231 ops/sec ±0.83% (86 runs sampled) +encode: source-map-0.6.1 x 166 ops/sec ±0.57% (86 runs sampled) +encode: source-map-0.8.0 x 203 ops/sec ±0.45% (88 runs sampled) +Fastest is encode: local code,encode: @jridgewell/sourcemap-codec 1.4.15 + + +*** + + +babel.min.js.map - 347793 segments + +Decode Memory Usage: +local code 35424960 bytes +@jridgewell/sourcemap-codec 1.4.15 35424696 bytes +sourcemap-codec 36033464 bytes +source-map-0.6.1 62253704 bytes +source-map-0.8.0 43843920 bytes +chrome dev tools 45111400 bytes +Smallest memory usage is @jridgewell/sourcemap-codec 1.4.15 + +Decode speed: +decode: local code x 38.18 ops/sec ±5.44% (52 runs sampled) +decode: @jridgewell/sourcemap-codec 1.4.15 x 38.36 ops/sec ±5.02% (52 runs sampled) +decode: sourcemap-codec x 34.05 ops/sec ±4.45% (47 runs sampled) +decode: source-map-0.6.1 x 4.31 ops/sec ±2.76% (15 runs sampled) +decode: source-map-0.8.0 x 55.60 ops/sec ±0.13% (73 runs sampled) +chrome dev tools x 16.94 ops/sec ±3.78% (46 runs sampled) +Fastest is decode: source-map-0.8.0 + +Encode Memory Usage: +local code 2606016 bytes +@jridgewell/sourcemap-codec 1.4.15 2626440 bytes +sourcemap-codec 21152576 bytes +source-map-0.6.1 25023928 bytes +source-map-0.8.0 25256448 bytes +Smallest memory usage is local code + +Encode speed: +encode: local code x 127 ops/sec ±0.18% (83 runs sampled) +encode: @jridgewell/sourcemap-codec 1.4.15 x 128 ops/sec ±0.26% (83 runs sampled) +encode: sourcemap-codec x 29.31 ops/sec ±2.55% (53 runs sampled) +encode: source-map-0.6.1 x 18.85 ops/sec ±3.19% (36 runs sampled) +encode: source-map-0.8.0 x 19.34 ops/sec ±1.97% (36 runs sampled) +Fastest is encode: @jridgewell/sourcemap-codec 1.4.15 + + +*** + + +preact.js.map - 1992 segments + +Decode Memory Usage: +local code 261696 bytes +@jridgewell/sourcemap-codec 1.4.15 244296 bytes +sourcemap-codec 302816 bytes +source-map-0.6.1 939176 bytes +source-map-0.8.0 336 bytes +chrome dev tools 587368 bytes +Smallest memory usage is source-map-0.8.0 + +Decode speed: +decode: local code x 17,782 ops/sec ±0.32% (97 runs sampled) +decode: @jridgewell/sourcemap-codec 1.4.15 x 17,863 ops/sec ±0.40% (100 runs sampled) +decode: sourcemap-codec x 12,453 ops/sec ±0.27% (101 runs sampled) +decode: source-map-0.6.1 x 1,288 ops/sec ±1.05% (96 runs sampled) +decode: source-map-0.8.0 x 9,289 ops/sec ±0.27% (101 runs sampled) +chrome dev tools x 4,769 ops/sec ±0.18% (100 runs sampled) +Fastest is decode: @jridgewell/sourcemap-codec 1.4.15 + +Encode Memory Usage: +local code 262944 bytes +@jridgewell/sourcemap-codec 1.4.15 25544 bytes +sourcemap-codec 323048 bytes +source-map-0.6.1 507808 bytes +source-map-0.8.0 507480 bytes +Smallest memory usage is @jridgewell/sourcemap-codec 1.4.15 + +Encode speed: +encode: local code x 24,207 ops/sec ±0.79% (95 runs sampled) +encode: @jridgewell/sourcemap-codec 1.4.15 x 24,288 ops/sec ±0.48% (96 runs sampled) +encode: sourcemap-codec x 6,761 ops/sec ±0.21% (100 runs sampled) +encode: source-map-0.6.1 x 5,374 ops/sec ±0.17% (99 runs sampled) +encode: source-map-0.8.0 x 5,633 ops/sec ±0.32% (99 runs sampled) +Fastest is encode: @jridgewell/sourcemap-codec 1.4.15,encode: local code + + +*** + + +react.js.map - 5726 segments + +Decode Memory Usage: +local code 678816 bytes +@jridgewell/sourcemap-codec 1.4.15 678816 bytes +sourcemap-codec 816400 bytes +source-map-0.6.1 2288864 bytes +source-map-0.8.0 721360 bytes +chrome dev tools 1012512 bytes +Smallest memory usage is local code + +Decode speed: +decode: local code x 6,178 ops/sec ±0.19% (98 runs sampled) +decode: @jridgewell/sourcemap-codec 1.4.15 x 6,261 ops/sec ±0.22% (100 runs sampled) +decode: sourcemap-codec x 4,472 ops/sec ±0.90% (99 runs sampled) +decode: source-map-0.6.1 x 449 ops/sec ±0.31% (95 runs sampled) +decode: source-map-0.8.0 x 3,219 ops/sec ±0.13% (100 runs sampled) +chrome dev tools x 1,743 ops/sec ±0.20% (99 runs sampled) +Fastest is decode: @jridgewell/sourcemap-codec 1.4.15 + +Encode Memory Usage: +local code 140960 bytes +@jridgewell/sourcemap-codec 1.4.15 159808 bytes +sourcemap-codec 969304 bytes +source-map-0.6.1 930520 bytes +source-map-0.8.0 930248 bytes +Smallest memory usage is local code + +Encode speed: +encode: local code x 8,013 ops/sec ±0.19% (100 runs sampled) +encode: @jridgewell/sourcemap-codec 1.4.15 x 7,989 ops/sec ±0.20% (101 runs sampled) +encode: sourcemap-codec x 2,472 ops/sec ±0.21% (99 runs sampled) +encode: source-map-0.6.1 x 2,200 ops/sec ±0.17% (99 runs sampled) +encode: source-map-0.8.0 x 2,220 ops/sec ±0.37% (99 runs sampled) +Fastest is encode: local code + + +*** + + +vscode.map - 2141001 segments + +Decode Memory Usage: +local code 198955264 bytes +@jridgewell/sourcemap-codec 1.4.15 199175352 bytes +sourcemap-codec 199102688 bytes +source-map-0.6.1 386323432 bytes +source-map-0.8.0 244116432 bytes +chrome dev tools 293734280 bytes +Smallest memory usage is local code + +Decode speed: +decode: local code x 3.90 ops/sec ±22.21% (15 runs sampled) +decode: @jridgewell/sourcemap-codec 1.4.15 x 3.95 ops/sec ±23.53% (15 runs sampled) +decode: sourcemap-codec x 3.82 ops/sec ±17.94% (14 runs sampled) +decode: source-map-0.6.1 x 0.61 ops/sec ±7.81% (6 runs sampled) +decode: source-map-0.8.0 x 9.54 ops/sec ±0.28% (28 runs sampled) +chrome dev tools x 2.18 ops/sec ±10.58% (10 runs sampled) +Fastest is decode: source-map-0.8.0 + +Encode Memory Usage: +local code 13509880 bytes +@jridgewell/sourcemap-codec 1.4.15 13537648 bytes +sourcemap-codec 32540104 bytes +source-map-0.6.1 127531040 bytes +source-map-0.8.0 127535312 bytes +Smallest memory usage is local code + +Encode speed: +encode: local code x 20.10 ops/sec ±0.19% (38 runs sampled) +encode: @jridgewell/sourcemap-codec 1.4.15 x 20.26 ops/sec ±0.32% (38 runs sampled) +encode: sourcemap-codec x 5.44 ops/sec ±1.64% (18 runs sampled) +encode: source-map-0.6.1 x 2.30 ops/sec ±4.79% (10 runs sampled) +encode: source-map-0.8.0 x 2.46 ops/sec ±6.53% (10 runs sampled) +Fastest is encode: @jridgewell/sourcemap-codec 1.4.15 +``` + +# License + +MIT diff --git a/dg-ui/node_modules/@jridgewell/sourcemap-codec/dist/sourcemap-codec.mjs b/dg-ui/node_modules/@jridgewell/sourcemap-codec/dist/sourcemap-codec.mjs new file mode 100644 index 0000000..4e10070 --- /dev/null +++ b/dg-ui/node_modules/@jridgewell/sourcemap-codec/dist/sourcemap-codec.mjs @@ -0,0 +1,467 @@ +// src/vlq.ts +var comma = ",".charCodeAt(0); +var semicolon = ";".charCodeAt(0); +var chars = "ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789+/"; +var intToChar = new Uint8Array(64); +var charToInt = new Uint8Array(128); +for (let i = 0; i < chars.length; i++) { + const c = chars.charCodeAt(i); + intToChar[i] = c; + charToInt[c] = i; +} +function decodeInteger(reader) { + let value = 0; + let shift = 0; + let integer = 0; + do { + const c = reader.next(); + integer = charToInt[c]; + value |= (integer & 31) << shift; + shift += 5; + } while (integer & 32); + return value; +} +function decodeSign(num) { + return num & 1 ? -2147483648 | -(num >>> 1) : num >>> 1; +} +function encodeInteger(builder, num) { + do { + let clamped = num & 31; + num >>>= 5; + if (num > 0) clamped |= 32; + builder.write(intToChar[clamped]); + } while (num > 0); +} +function encodeSign(num) { + return num < 0 ? -num << 1 | 1 : num << 1; +} +function hasMoreVlq(reader, max) { + if (reader.pos >= max) return false; + return reader.peek() !== comma; +} + +// src/strings.ts +var bufLength = 1024 * 16; +var td = typeof TextDecoder !== "undefined" ? /* @__PURE__ */ new TextDecoder() : typeof Buffer !== "undefined" ? { + decode(buf) { + const out = Buffer.from(buf.buffer, buf.byteOffset, buf.byteLength); + return out.toString(); + } +} : { + decode(buf) { + let out = ""; + for (let i = 0; i < buf.length; i++) { + out += String.fromCharCode(buf[i]); + } + return out; + } +}; +var StringWriter = class { + constructor() { + this.pos = 0; + this.out = ""; + this.buffer = new Uint8Array(bufLength); + } + write(v) { + const { buffer } = this; + buffer[this.pos++] = v; + if (this.pos === bufLength) { + this.out += td.decode(buffer); + this.pos = 0; + } + } + flush() { + const { buffer, out, pos } = this; + return pos > 0 ? out + td.decode(buffer.subarray(0, pos)) : out; + } +}; +var StringReader = class { + constructor(buffer) { + this.pos = 0; + this.buffer = buffer; + } + next() { + return this.buffer.charCodeAt(this.pos++); + } + peek() { + return this.buffer.charCodeAt(this.pos); + } + indexOf(char) { + const { buffer, pos } = this; + const idx = buffer.indexOf(char, pos); + return idx === -1 ? buffer.length : idx; + } +}; + +// src/scopes.ts +var EMPTY = []; +function decodeOriginalScopes(input) { + const { length } = input; + const reader = new StringReader(input); + const scopes = []; + const stack = []; + let line = 0; + for (; reader.pos < length; reader.pos++) { + line += decodeSign(decodeInteger(reader)); + const column = decodeSign(decodeInteger(reader)); + if (!hasMoreVlq(reader, length)) { + const last = stack.pop(); + last[2] = line; + last[3] = column; + continue; + } + const kind = decodeSign(decodeInteger(reader)); + const fields = decodeSign(decodeInteger(reader)); + const hasName = fields & 1; + const scope = hasName ? [line, column, 0, 0, kind, decodeSign(decodeInteger(reader))] : [line, column, 0, 0, kind]; + let vars = EMPTY; + if (hasMoreVlq(reader, length)) { + vars = []; + do { + const varsIndex = decodeSign(decodeInteger(reader)); + vars.push(varsIndex); + } while (hasMoreVlq(reader, length)); + } + scope.vars = vars; + scopes.push(scope); + stack.push(scope); + } + return scopes; +} +function encodeOriginalScopes(scopes) { + const writer = new StringWriter(); + for (let i = 0; i < scopes.length; ) { + i = _encodeOriginalScopes(scopes, i, writer, [0]); + } + return writer.flush(); +} +function _encodeOriginalScopes(scopes, index, writer, state) { + const scope = scopes[index]; + const { 0: startLine, 1: startColumn, 2: endLine, 3: endColumn, 4: kind, vars } = scope; + if (index > 0) writer.write(comma); + encodeInteger(writer, encodeSign(startLine - state[0])); + state[0] = startLine; + encodeInteger(writer, encodeSign(startColumn)); + encodeInteger(writer, encodeSign(kind)); + const fields = scope.length === 6 ? 1 : 0; + encodeInteger(writer, encodeSign(fields)); + if (scope.length === 6) encodeInteger(writer, encodeSign(scope[5])); + for (const v of vars) { + encodeInteger(writer, encodeSign(v)); + } + for (index++; index < scopes.length; ) { + const next = scopes[index]; + const { 0: l, 1: c } = next; + if (l > endLine || l === endLine && c >= endColumn) { + break; + } + index = _encodeOriginalScopes(scopes, index, writer, state); + } + writer.write(comma); + encodeInteger(writer, encodeSign(endLine - state[0])); + state[0] = endLine; + encodeInteger(writer, encodeSign(endColumn)); + return index; +} +function decodeGeneratedRanges(input) { + const { length } = input; + const reader = new StringReader(input); + const ranges = []; + const stack = []; + let genLine = 0; + let definitionSourcesIndex = 0; + let definitionScopeIndex = 0; + let callsiteSourcesIndex = 0; + let callsiteLine = 0; + let callsiteColumn = 0; + let bindingLine = 0; + let bindingColumn = 0; + do { + const semi = reader.indexOf(";"); + let genColumn = 0; + for (; reader.pos < semi; reader.pos++) { + genColumn += decodeSign(decodeInteger(reader)); + if (!hasMoreVlq(reader, semi)) { + const last = stack.pop(); + last[2] = genLine; + last[3] = genColumn; + continue; + } + const fields = decodeSign(decodeInteger(reader)); + const hasDefinition = fields & 1; + const hasCallsite = fields & 2; + const hasScope = fields & 4; + let callsite = null; + let bindings = EMPTY; + let range; + if (hasDefinition) { + const defSourcesIndex = definitionSourcesIndex + decodeSign(decodeInteger(reader)); + definitionScopeIndex = decodeSign(decodeInteger(reader)) + (definitionSourcesIndex === defSourcesIndex ? definitionScopeIndex : 0); + definitionSourcesIndex = defSourcesIndex; + range = [genLine, genColumn, 0, 0, defSourcesIndex, definitionScopeIndex]; + } else { + range = [genLine, genColumn, 0, 0]; + } + range.isScope = !!hasScope; + if (hasCallsite) { + const prevCsi = callsiteSourcesIndex; + const prevLine = callsiteLine; + callsiteSourcesIndex += decodeSign(decodeInteger(reader)); + const sameSource = prevCsi === callsiteSourcesIndex; + callsiteLine = (sameSource ? callsiteLine : 0) + decodeSign(decodeInteger(reader)); + callsiteColumn = (sameSource && prevLine === callsiteLine ? callsiteColumn : 0) + decodeSign(decodeInteger(reader)); + callsite = [callsiteSourcesIndex, callsiteLine, callsiteColumn]; + } + range.callsite = callsite; + if (hasMoreVlq(reader, semi)) { + bindings = []; + do { + bindingLine = genLine; + bindingColumn = genColumn; + const expressionsCount = decodeSign(decodeInteger(reader)); + let expressionRanges; + if (expressionsCount < -1) { + expressionRanges = [[decodeSign(decodeInteger(reader))]]; + for (let i = -1; i > expressionsCount; i--) { + const prevBl = bindingLine; + bindingLine += decodeSign(decodeInteger(reader)); + bindingColumn = (bindingLine === prevBl ? bindingColumn : 0) + decodeSign(decodeInteger(reader)); + const expression = decodeSign(decodeInteger(reader)); + expressionRanges.push([expression, bindingLine, bindingColumn]); + } + } else { + expressionRanges = [[expressionsCount]]; + } + bindings.push(expressionRanges); + } while (hasMoreVlq(reader, semi)); + } + range.bindings = bindings; + ranges.push(range); + stack.push(range); + } + genLine++; + reader.pos = semi + 1; + } while (reader.pos < length); + return ranges; +} +function encodeGeneratedRanges(ranges) { + if (ranges.length === 0) return ""; + const writer = new StringWriter(); + for (let i = 0; i < ranges.length; ) { + i = _encodeGeneratedRanges(ranges, i, writer, [0, 0, 0, 0, 0, 0, 0]); + } + return writer.flush(); +} +function _encodeGeneratedRanges(ranges, index, writer, state) { + const range = ranges[index]; + const { + 0: startLine, + 1: startColumn, + 2: endLine, + 3: endColumn, + isScope, + callsite, + bindings + } = range; + if (state[0] < startLine) { + catchupLine(writer, state[0], startLine); + state[0] = startLine; + state[1] = 0; + } else if (index > 0) { + writer.write(comma); + } + encodeInteger(writer, encodeSign(range[1] - state[1])); + state[1] = range[1]; + const fields = (range.length === 6 ? 1 : 0) | (callsite ? 2 : 0) | (isScope ? 4 : 0); + encodeInteger(writer, encodeSign(fields)); + if (range.length === 6) { + const { 4: sourcesIndex, 5: scopesIndex } = range; + if (sourcesIndex !== state[2]) { + state[3] = 0; + } + encodeInteger(writer, encodeSign(sourcesIndex - state[2])); + state[2] = sourcesIndex; + encodeInteger(writer, encodeSign(scopesIndex - state[3])); + state[3] = scopesIndex; + } + if (callsite) { + const { 0: sourcesIndex, 1: callLine, 2: callColumn } = range.callsite; + if (sourcesIndex !== state[4]) { + state[5] = 0; + state[6] = 0; + } else if (callLine !== state[5]) { + state[6] = 0; + } + encodeInteger(writer, encodeSign(sourcesIndex - state[4])); + state[4] = sourcesIndex; + encodeInteger(writer, encodeSign(callLine - state[5])); + state[5] = callLine; + encodeInteger(writer, encodeSign(callColumn - state[6])); + state[6] = callColumn; + } + if (bindings) { + for (const binding of bindings) { + if (binding.length > 1) encodeInteger(writer, encodeSign(-binding.length)); + const expression = binding[0][0]; + encodeInteger(writer, encodeSign(expression)); + let bindingStartLine = startLine; + let bindingStartColumn = startColumn; + for (let i = 1; i < binding.length; i++) { + const expRange = binding[i]; + encodeInteger(writer, encodeSign(expRange[1] - bindingStartLine)); + bindingStartLine = expRange[1]; + encodeInteger(writer, encodeSign(expRange[2] - bindingStartColumn)); + bindingStartColumn = expRange[2]; + encodeInteger(writer, encodeSign(expRange[0])); + } + } + } + for (index++; index < ranges.length; ) { + const next = ranges[index]; + const { 0: l, 1: c } = next; + if (l > endLine || l === endLine && c >= endColumn) { + break; + } + index = _encodeGeneratedRanges(ranges, index, writer, state); + } + if (state[0] < endLine) { + catchupLine(writer, state[0], endLine); + state[0] = endLine; + state[1] = 0; + } else { + writer.write(comma); + } + encodeInteger(writer, encodeSign(endColumn - state[1])); + state[1] = endColumn; + return index; +} +function catchupLine(writer, lastLine, line) { + do { + writer.write(semicolon); + } while (++lastLine < line); +} + +// src/range-mappings.ts +function decodeRangeMappings(input) { + const { length } = input; + const reader = new StringReader(input); + const rangeMappings = []; + do { + const semi = reader.indexOf(";"); + const indices = []; + let index = 0; + while (reader.pos < semi) { + index += decodeInteger(reader); + indices.push(index); + } + rangeMappings.push(indices); + reader.pos = semi + 1; + } while (reader.pos <= length); + return rangeMappings; +} +function encodeRangeMappings(decoded) { + if (decoded.length === 0) return ""; + const writer = new StringWriter(); + for (let i = 0; i < decoded.length; i++) { + const indices = decoded[i]; + if (i > 0) writer.write(semicolon); + let index = 0; + for (let j = 0; j < indices.length; j++) { + const offset = indices[j]; + encodeInteger(writer, offset - index); + index = offset; + } + } + return writer.flush(); +} + +// src/sourcemap-codec.ts +function decode(mappings) { + const { length } = mappings; + const reader = new StringReader(mappings); + const decoded = []; + let genColumn = 0; + let sourcesIndex = 0; + let sourceLine = 0; + let sourceColumn = 0; + let namesIndex = 0; + do { + const semi = reader.indexOf(";"); + const line = []; + let sorted = true; + let lastCol = 0; + genColumn = 0; + while (reader.pos < semi) { + let seg; + genColumn += decodeSign(decodeInteger(reader)); + if (genColumn < lastCol) sorted = false; + lastCol = genColumn; + if (hasMoreVlq(reader, semi)) { + sourcesIndex += decodeSign(decodeInteger(reader)); + sourceLine += decodeSign(decodeInteger(reader)); + sourceColumn += decodeSign(decodeInteger(reader)); + if (hasMoreVlq(reader, semi)) { + namesIndex += decodeSign(decodeInteger(reader)); + seg = [genColumn, sourcesIndex, sourceLine, sourceColumn, namesIndex]; + } else { + seg = [genColumn, sourcesIndex, sourceLine, sourceColumn]; + } + } else { + seg = [genColumn]; + } + line.push(seg); + reader.pos++; + } + if (!sorted) sort(line); + decoded.push(line); + reader.pos = semi + 1; + } while (reader.pos <= length); + return decoded; +} +function sort(line) { + line.sort(sortComparator); +} +function sortComparator(a, b) { + return a[0] - b[0]; +} +function encode(decoded) { + const writer = new StringWriter(); + let sourcesIndex = 0; + let sourceLine = 0; + let sourceColumn = 0; + let namesIndex = 0; + for (let i = 0; i < decoded.length; i++) { + const line = decoded[i]; + if (i > 0) writer.write(semicolon); + if (line.length === 0) continue; + let genColumn = 0; + for (let j = 0; j < line.length; j++) { + const segment = line[j]; + if (j > 0) writer.write(comma); + encodeInteger(writer, encodeSign(segment[0] - genColumn)); + genColumn = segment[0]; + if (segment.length === 1) continue; + encodeInteger(writer, encodeSign(segment[1] - sourcesIndex)); + encodeInteger(writer, encodeSign(segment[2] - sourceLine)); + encodeInteger(writer, encodeSign(segment[3] - sourceColumn)); + sourcesIndex = segment[1]; + sourceLine = segment[2]; + sourceColumn = segment[3]; + if (segment.length === 4) continue; + encodeInteger(writer, encodeSign(segment[4] - namesIndex)); + namesIndex = segment[4]; + } + } + return writer.flush(); +} +export { + decode, + decodeGeneratedRanges, + decodeOriginalScopes, + decodeRangeMappings, + encode, + encodeGeneratedRanges, + encodeOriginalScopes, + encodeRangeMappings +}; +//# sourceMappingURL=sourcemap-codec.mjs.map diff --git a/dg-ui/node_modules/@jridgewell/sourcemap-codec/dist/sourcemap-codec.mjs.map b/dg-ui/node_modules/@jridgewell/sourcemap-codec/dist/sourcemap-codec.mjs.map new file mode 100644 index 0000000..ed642a6 --- /dev/null +++ b/dg-ui/node_modules/@jridgewell/sourcemap-codec/dist/sourcemap-codec.mjs.map @@ -0,0 +1,6 @@ +{ + "version": 3, + "sources": ["../src/vlq.ts", "../src/strings.ts", "../src/scopes.ts", "../src/range-mappings.ts", "../src/sourcemap-codec.ts"], + "mappings": ";AAEO,IAAM,QAAQ,IAAI,WAAW,CAAC;AAC9B,IAAM,YAAY,IAAI,WAAW,CAAC;AAEzC,IAAM,QAAQ;AACd,IAAM,YAAY,IAAI,WAAW,EAAE;AACnC,IAAM,YAAY,IAAI,WAAW,GAAG;AAEpC,SAAS,IAAI,GAAG,IAAI,MAAM,QAAQ,KAAK;AACrC,QAAM,IAAI,MAAM,WAAW,CAAC;AAC5B,YAAU,CAAC,IAAI;AACf,YAAU,CAAC,IAAI;AACjB;AAEO,SAAS,cAAc,QAA8B;AAC1D,MAAI,QAAQ;AACZ,MAAI,QAAQ;AACZ,MAAI,UAAU;AAEd,KAAG;AACD,UAAM,IAAI,OAAO,KAAK;AACtB,cAAU,UAAU,CAAC;AACrB,cAAU,UAAU,OAAO;AAC3B,aAAS;AAAA,EACX,SAAS,UAAU;AAEnB,SAAO;AACT;AAEO,SAAS,WAAW,KAAqB;AAC9C,SAAO,MAAM,IAAI,cAAc,EAAE,QAAQ,KAAK,QAAQ;AACxD;AAEO,SAAS,cAAc,SAAuB,KAAa;AAChE,KAAG;AACD,QAAI,UAAU,MAAM;AACpB,aAAS;AACT,QAAI,MAAM,EAAG,YAAW;AACxB,YAAQ,MAAM,UAAU,OAAO,CAAC;AAAA,EAClC,SAAS,MAAM;AACjB;AAEO,SAAS,WAAW,KAAqB;AAC9C,SAAO,MAAM,IAAK,CAAC,OAAO,IAAK,IAAI,OAAO;AAC5C;AAEO,SAAS,WAAW,QAAsB,KAAa;AAC5D,MAAI,OAAO,OAAO,IAAK,QAAO;AAC9B,SAAO,OAAO,KAAK,MAAM;AAC3B;;;AClDA,IAAM,YAAY,OAAO;AAGzB,IAAM,KACJ,OAAO,gBAAgB,cACH,oBAAI,YAAY,IAChC,OAAO,WAAW,cAChB;AAAA,EACE,OAAO,KAAyB;AAC9B,UAAM,MAAM,OAAO,KAAK,IAAI,QAAQ,IAAI,YAAY,IAAI,UAAU;AAClE,WAAO,IAAI,SAAS;AAAA,EACtB;AACF,IACA;AAAA,EACE,OAAO,KAAyB;AAC9B,QAAI,MAAM;AACV,aAAS,IAAI,GAAG,IAAI,IAAI,QAAQ,KAAK;AACnC,aAAO,OAAO,aAAa,IAAI,CAAC,CAAC;AAAA,IACnC;AACA,WAAO;AAAA,EACT;AACF;AAED,IAAM,eAAN,MAAmB;AAAA,EAAnB;AACL,eAAM;AACN,SAAQ,MAAM;AACd,SAAQ,SAAS,IAAI,WAAW,SAAS;AAAA;AAAA,EAEzC,MAAM,GAAiB;AACrB,UAAM,EAAE,OAAO,IAAI;AACnB,WAAO,KAAK,KAAK,IAAI;AACrB,QAAI,KAAK,QAAQ,WAAW;AAC1B,WAAK,OAAO,GAAG,OAAO,MAAM;AAC5B,WAAK,MAAM;AAAA,IACb;AAAA,EACF;AAAA,EAEA,QAAgB;AACd,UAAM,EAAE,QAAQ,KAAK,IAAI,IAAI;AAC7B,WAAO,MAAM,IAAI,MAAM,GAAG,OAAO,OAAO,SAAS,GAAG,GAAG,CAAC,IAAI;AAAA,EAC9D;AACF;AAEO,IAAM,eAAN,MAAmB;AAAA,EAIxB,YAAY,QAAgB;AAH5B,eAAM;AAIJ,SAAK,SAAS;AAAA,EAChB;AAAA,EAEA,OAAe;AACb,WAAO,KAAK,OAAO,WAAW,KAAK,KAAK;AAAA,EAC1C;AAAA,EAEA,OAAe;AACb,WAAO,KAAK,OAAO,WAAW,KAAK,GAAG;AAAA,EACxC;AAAA,EAEA,QAAQ,MAAsB;AAC5B,UAAM,EAAE,QAAQ,IAAI,IAAI;AACxB,UAAM,MAAM,OAAO,QAAQ,MAAM,GAAG;AACpC,WAAO,QAAQ,KAAK,OAAO,SAAS;AAAA,EACtC;AACF;;;ACrDA,IAAM,QAAe,CAAC;AA+Bf,SAAS,qBAAqB,OAAgC;AACnE,QAAM,EAAE,OAAO,IAAI;AACnB,QAAM,SAAS,IAAI,aAAa,KAAK;AACrC,QAAM,SAA0B,CAAC;AACjC,QAAM,QAAyB,CAAC;AAChC,MAAI,OAAO;AAEX,SAAO,OAAO,MAAM,QAAQ,OAAO,OAAO;AACxC,YAAQ,WAAW,cAAc,MAAM,CAAC;AACxC,UAAM,SAAS,WAAW,cAAc,MAAM,CAAC;AAE/C,QAAI,CAAC,WAAW,QAAQ,MAAM,GAAG;AAC/B,YAAM,OAAO,MAAM,IAAI;AACvB,WAAK,CAAC,IAAI;AACV,WAAK,CAAC,IAAI;AACV;AAAA,IACF;AAEA,UAAM,OAAO,WAAW,cAAc,MAAM,CAAC;AAC7C,UAAM,SAAS,WAAW,cAAc,MAAM,CAAC;AAC/C,UAAM,UAAU,SAAS;AAEzB,UAAM,QACJ,UACI,CAAC,MAAM,QAAQ,GAAG,GAAG,MAAM,WAAW,cAAc,MAAM,CAAC,CAAC,IAC5D,CAAC,MAAM,QAAQ,GAAG,GAAG,IAAI;AAG/B,QAAI,OAAc;AAClB,QAAI,WAAW,QAAQ,MAAM,GAAG;AAC9B,aAAO,CAAC;AACR,SAAG;AACD,cAAM,YAAY,WAAW,cAAc,MAAM,CAAC;AAClD,aAAK,KAAK,SAAS;AAAA,MACrB,SAAS,WAAW,QAAQ,MAAM;AAAA,IACpC;AACA,UAAM,OAAO;AAEb,WAAO,KAAK,KAAK;AACjB,UAAM,KAAK,KAAK;AAAA,EAClB;AAEA,SAAO;AACT;AAEO,SAAS,qBAAqB,QAAiC;AACpE,QAAM,SAAS,IAAI,aAAa;AAEhC,WAAS,IAAI,GAAG,IAAI,OAAO,UAAU;AACnC,QAAI,sBAAsB,QAAQ,GAAG,QAAQ,CAAC,CAAC,CAAC;AAAA,EAClD;AAEA,SAAO,OAAO,MAAM;AACtB;AAEA,SAAS,sBACP,QACA,OACA,QACA,OAGQ;AACR,QAAM,QAAQ,OAAO,KAAK;AAC1B,QAAM,EAAE,GAAG,WAAW,GAAG,aAAa,GAAG,SAAS,GAAG,WAAW,GAAG,MAAM,KAAK,IAAI;AAElF,MAAI,QAAQ,EAAG,QAAO,MAAM,KAAK;AAEjC,gBAAc,QAAQ,WAAW,YAAY,MAAM,CAAC,CAAC,CAAC;AACtD,QAAM,CAAC,IAAI;AACX,gBAAc,QAAQ,WAAW,WAAW,CAAC;AAC7C,gBAAc,QAAQ,WAAW,IAAI,CAAC;AAEtC,QAAM,SAAS,MAAM,WAAW,IAAI,IAAS;AAC7C,gBAAc,QAAQ,WAAW,MAAM,CAAC;AACxC,MAAI,MAAM,WAAW,EAAG,eAAc,QAAQ,WAAW,MAAM,CAAC,CAAC,CAAC;AAElE,aAAW,KAAK,MAAM;AACpB,kBAAc,QAAQ,WAAW,CAAC,CAAC;AAAA,EACrC;AAEA,OAAK,SAAS,QAAQ,OAAO,UAAU;AACrC,UAAM,OAAO,OAAO,KAAK;AACzB,UAAM,EAAE,GAAG,GAAG,GAAG,EAAE,IAAI;AACvB,QAAI,IAAI,WAAY,MAAM,WAAW,KAAK,WAAY;AACpD;AAAA,IACF;AACA,YAAQ,sBAAsB,QAAQ,OAAO,QAAQ,KAAK;AAAA,EAC5D;AAEA,SAAO,MAAM,KAAK;AAClB,gBAAc,QAAQ,WAAW,UAAU,MAAM,CAAC,CAAC,CAAC;AACpD,QAAM,CAAC,IAAI;AACX,gBAAc,QAAQ,WAAW,SAAS,CAAC;AAE3C,SAAO;AACT;AAEO,SAAS,sBAAsB,OAAiC;AACrE,QAAM,EAAE,OAAO,IAAI;AACnB,QAAM,SAAS,IAAI,aAAa,KAAK;AACrC,QAAM,SAA2B,CAAC;AAClC,QAAM,QAA0B,CAAC;AAEjC,MAAI,UAAU;AACd,MAAI,yBAAyB;AAC7B,MAAI,uBAAuB;AAC3B,MAAI,uBAAuB;AAC3B,MAAI,eAAe;AACnB,MAAI,iBAAiB;AACrB,MAAI,cAAc;AAClB,MAAI,gBAAgB;AAEpB,KAAG;AACD,UAAM,OAAO,OAAO,QAAQ,GAAG;AAC/B,QAAI,YAAY;AAEhB,WAAO,OAAO,MAAM,MAAM,OAAO,OAAO;AACtC,mBAAa,WAAW,cAAc,MAAM,CAAC;AAE7C,UAAI,CAAC,WAAW,QAAQ,IAAI,GAAG;AAC7B,cAAM,OAAO,MAAM,IAAI;AACvB,aAAK,CAAC,IAAI;AACV,aAAK,CAAC,IAAI;AACV;AAAA,MACF;AAEA,YAAM,SAAS,WAAW,cAAc,MAAM,CAAC;AAC/C,YAAM,gBAAgB,SAAS;AAC/B,YAAM,cAAc,SAAS;AAC7B,YAAM,WAAW,SAAS;AAE1B,UAAI,WAA4B;AAChC,UAAI,WAAsB;AAC1B,UAAI;AACJ,UAAI,eAAe;AACjB,cAAM,kBAAkB,yBAAyB,WAAW,cAAc,MAAM,CAAC;AACjF,+BACE,WAAW,cAAc,MAAM,CAAC,KAC/B,2BAA2B,kBAAkB,uBAAuB;AAEvE,iCAAyB;AACzB,gBAAQ,CAAC,SAAS,WAAW,GAAG,GAAG,iBAAiB,oBAAoB;AAAA,MAC1E,OAAO;AACL,gBAAQ,CAAC,SAAS,WAAW,GAAG,CAAC;AAAA,MACnC;AAEA,YAAM,UAAU,CAAC,CAAC;AAElB,UAAI,aAAa;AACf,cAAM,UAAU;AAChB,cAAM,WAAW;AACjB,gCAAwB,WAAW,cAAc,MAAM,CAAC;AACxD,cAAM,aAAa,YAAY;AAC/B,wBAAgB,aAAa,eAAe,KAAK,WAAW,cAAc,MAAM,CAAC;AACjF,0BACG,cAAc,aAAa,eAAe,iBAAiB,KAC5D,WAAW,cAAc,MAAM,CAAC;AAElC,mBAAW,CAAC,sBAAsB,cAAc,cAAc;AAAA,MAChE;AACA,YAAM,WAAW;AAEjB,UAAI,WAAW,QAAQ,IAAI,GAAG;AAC5B,mBAAW,CAAC;AACZ,WAAG;AACD,wBAAc;AACd,0BAAgB;AAChB,gBAAM,mBAAmB,WAAW,cAAc,MAAM,CAAC;AACzD,cAAI;AACJ,cAAI,mBAAmB,IAAI;AACzB,+BAAmB,CAAC,CAAC,WAAW,cAAc,MAAM,CAAC,CAAC,CAAC;AACvD,qBAAS,IAAI,IAAI,IAAI,kBAAkB,KAAK;AAC1C,oBAAM,SAAS;AACf,6BAAe,WAAW,cAAc,MAAM,CAAC;AAC/C,+BACG,gBAAgB,SAAS,gBAAgB,KAAK,WAAW,cAAc,MAAM,CAAC;AACjF,oBAAM,aAAa,WAAW,cAAc,MAAM,CAAC;AACnD,+BAAiB,KAAK,CAAC,YAAY,aAAa,aAAa,CAAC;AAAA,YAChE;AAAA,UACF,OAAO;AACL,+BAAmB,CAAC,CAAC,gBAAgB,CAAC;AAAA,UACxC;AACA,mBAAS,KAAK,gBAAgB;AAAA,QAChC,SAAS,WAAW,QAAQ,IAAI;AAAA,MAClC;AACA,YAAM,WAAW;AAEjB,aAAO,KAAK,KAAK;AACjB,YAAM,KAAK,KAAK;AAAA,IAClB;AAEA;AACA,WAAO,MAAM,OAAO;AAAA,EACtB,SAAS,OAAO,MAAM;AAEtB,SAAO;AACT;AAEO,SAAS,sBAAsB,QAAkC;AACtE,MAAI,OAAO,WAAW,EAAG,QAAO;AAEhC,QAAM,SAAS,IAAI,aAAa;AAEhC,WAAS,IAAI,GAAG,IAAI,OAAO,UAAU;AACnC,QAAI,uBAAuB,QAAQ,GAAG,QAAQ,CAAC,GAAG,GAAG,GAAG,GAAG,GAAG,GAAG,CAAC,CAAC;AAAA,EACrE;AAEA,SAAO,OAAO,MAAM;AACtB;AAEA,SAAS,uBACP,QACA,OACA,QACA,OASQ;AACR,QAAM,QAAQ,OAAO,KAAK;AAC1B,QAAM;AAAA,IACJ,GAAG;AAAA,IACH,GAAG;AAAA,IACH,GAAG;AAAA,IACH,GAAG;AAAA,IACH;AAAA,IACA;AAAA,IACA;AAAA,EACF,IAAI;AAEJ,MAAI,MAAM,CAAC,IAAI,WAAW;AACxB,gBAAY,QAAQ,MAAM,CAAC,GAAG,SAAS;AACvC,UAAM,CAAC,IAAI;AACX,UAAM,CAAC,IAAI;AAAA,EACb,WAAW,QAAQ,GAAG;AACpB,WAAO,MAAM,KAAK;AAAA,EACpB;AAEA,gBAAc,QAAQ,WAAW,MAAM,CAAC,IAAI,MAAM,CAAC,CAAC,CAAC;AACrD,QAAM,CAAC,IAAI,MAAM,CAAC;AAElB,QAAM,UACH,MAAM,WAAW,IAAI,IAAS,MAAM,WAAW,IAAS,MAAM,UAAU,IAAS;AACpF,gBAAc,QAAQ,WAAW,MAAM,CAAC;AAExC,MAAI,MAAM,WAAW,GAAG;AACtB,UAAM,EAAE,GAAG,cAAc,GAAG,YAAY,IAAI;AAC5C,QAAI,iBAAiB,MAAM,CAAC,GAAG;AAC7B,YAAM,CAAC,IAAI;AAAA,IACb;AACA,kBAAc,QAAQ,WAAW,eAAe,MAAM,CAAC,CAAC,CAAC;AACzD,UAAM,CAAC,IAAI;AACX,kBAAc,QAAQ,WAAW,cAAc,MAAM,CAAC,CAAC,CAAC;AACxD,UAAM,CAAC,IAAI;AAAA,EACb;AAEA,MAAI,UAAU;AACZ,UAAM,EAAE,GAAG,cAAc,GAAG,UAAU,GAAG,WAAW,IAAI,MAAM;AAC9D,QAAI,iBAAiB,MAAM,CAAC,GAAG;AAC7B,YAAM,CAAC,IAAI;AACX,YAAM,CAAC,IAAI;AAAA,IACb,WAAW,aAAa,MAAM,CAAC,GAAG;AAChC,YAAM,CAAC,IAAI;AAAA,IACb;AACA,kBAAc,QAAQ,WAAW,eAAe,MAAM,CAAC,CAAC,CAAC;AACzD,UAAM,CAAC,IAAI;AACX,kBAAc,QAAQ,WAAW,WAAW,MAAM,CAAC,CAAC,CAAC;AACrD,UAAM,CAAC,IAAI;AACX,kBAAc,QAAQ,WAAW,aAAa,MAAM,CAAC,CAAC,CAAC;AACvD,UAAM,CAAC,IAAI;AAAA,EACb;AAEA,MAAI,UAAU;AACZ,eAAW,WAAW,UAAU;AAC9B,UAAI,QAAQ,SAAS,EAAG,eAAc,QAAQ,WAAW,CAAC,QAAQ,MAAM,CAAC;AACzE,YAAM,aAAa,QAAQ,CAAC,EAAE,CAAC;AAC/B,oBAAc,QAAQ,WAAW,UAAU,CAAC;AAC5C,UAAI,mBAAmB;AACvB,UAAI,qBAAqB;AACzB,eAAS,IAAI,GAAG,IAAI,QAAQ,QAAQ,KAAK;AACvC,cAAM,WAAW,QAAQ,CAAC;AAC1B,sBAAc,QAAQ,WAAW,SAAS,CAAC,IAAK,gBAAgB,CAAC;AACjE,2BAAmB,SAAS,CAAC;AAC7B,sBAAc,QAAQ,WAAW,SAAS,CAAC,IAAK,kBAAkB,CAAC;AACnE,6BAAqB,SAAS,CAAC;AAC/B,sBAAc,QAAQ,WAAW,SAAS,CAAC,CAAE,CAAC;AAAA,MAChD;AAAA,IACF;AAAA,EACF;AAEA,OAAK,SAAS,QAAQ,OAAO,UAAU;AACrC,UAAM,OAAO,OAAO,KAAK;AACzB,UAAM,EAAE,GAAG,GAAG,GAAG,EAAE,IAAI;AACvB,QAAI,IAAI,WAAY,MAAM,WAAW,KAAK,WAAY;AACpD;AAAA,IACF;AACA,YAAQ,uBAAuB,QAAQ,OAAO,QAAQ,KAAK;AAAA,EAC7D;AAEA,MAAI,MAAM,CAAC,IAAI,SAAS;AACtB,gBAAY,QAAQ,MAAM,CAAC,GAAG,OAAO;AACrC,UAAM,CAAC,IAAI;AACX,UAAM,CAAC,IAAI;AAAA,EACb,OAAO;AACL,WAAO,MAAM,KAAK;AAAA,EACpB;AACA,gBAAc,QAAQ,WAAW,YAAY,MAAM,CAAC,CAAC,CAAC;AACtD,QAAM,CAAC,IAAI;AAEX,SAAO;AACT;AAEA,SAAS,YAAY,QAAsB,UAAkB,MAAc;AACzE,KAAG;AACD,WAAO,MAAM,SAAS;AAAA,EACxB,SAAS,EAAE,WAAW;AACxB;;;ACtWO,SAAS,oBAAoB,OAA8B;AAChE,QAAM,EAAE,OAAO,IAAI;AACnB,QAAM,SAAS,IAAI,aAAa,KAAK;AACrC,QAAM,gBAA+B,CAAC;AAEtC,KAAG;AACD,UAAM,OAAO,OAAO,QAAQ,GAAG;AAC/B,UAAM,UAA0B,CAAC;AACjC,QAAI,QAAQ;AAEZ,WAAO,OAAO,MAAM,MAAM;AACxB,eAAS,cAAc,MAAM;AAC7B,cAAQ,KAAK,KAAK;AAAA,IACpB;AAEA,kBAAc,KAAK,OAAO;AAC1B,WAAO,MAAM,OAAO;AAAA,EACtB,SAAS,OAAO,OAAO;AAEvB,SAAO;AACT;AAEO,SAAS,oBAAoB,SAAgC;AAClE,MAAI,QAAQ,WAAW,EAAG,QAAO;AAEjC,QAAM,SAAS,IAAI,aAAa;AAEhC,WAAS,IAAI,GAAG,IAAI,QAAQ,QAAQ,KAAK;AACvC,UAAM,UAAU,QAAQ,CAAC;AACzB,QAAI,IAAI,EAAG,QAAO,MAAM,SAAS;AAEjC,QAAI,QAAQ;AACZ,aAAS,IAAI,GAAG,IAAI,QAAQ,QAAQ,KAAK;AACvC,YAAM,SAAS,QAAQ,CAAC;AACxB,oBAAc,QAAQ,SAAS,KAAK;AACpC,cAAQ;AAAA,IACV;AAAA,EACF;AAEA,SAAO,OAAO,MAAM;AACtB;;;ACjBO,SAAS,OAAO,UAAqC;AAC1D,QAAM,EAAE,OAAO,IAAI;AACnB,QAAM,SAAS,IAAI,aAAa,QAAQ;AACxC,QAAM,UAA6B,CAAC;AACpC,MAAI,YAAY;AAChB,MAAI,eAAe;AACnB,MAAI,aAAa;AACjB,MAAI,eAAe;AACnB,MAAI,aAAa;AAEjB,KAAG;AACD,UAAM,OAAO,OAAO,QAAQ,GAAG;AAC/B,UAAM,OAAsB,CAAC;AAC7B,QAAI,SAAS;AACb,QAAI,UAAU;AACd,gBAAY;AAEZ,WAAO,OAAO,MAAM,MAAM;AACxB,UAAI;AAEJ,mBAAa,WAAW,cAAc,MAAM,CAAC;AAC7C,UAAI,YAAY,QAAS,UAAS;AAClC,gBAAU;AAEV,UAAI,WAAW,QAAQ,IAAI,GAAG;AAC5B,wBAAgB,WAAW,cAAc,MAAM,CAAC;AAChD,sBAAc,WAAW,cAAc,MAAM,CAAC;AAC9C,wBAAgB,WAAW,cAAc,MAAM,CAAC;AAEhD,YAAI,WAAW,QAAQ,IAAI,GAAG;AAC5B,wBAAc,WAAW,cAAc,MAAM,CAAC;AAC9C,gBAAM,CAAC,WAAW,cAAc,YAAY,cAAc,UAAU;AAAA,QACtE,OAAO;AACL,gBAAM,CAAC,WAAW,cAAc,YAAY,YAAY;AAAA,QAC1D;AAAA,MACF,OAAO;AACL,cAAM,CAAC,SAAS;AAAA,MAClB;AAEA,WAAK,KAAK,GAAG;AACb,aAAO;AAAA,IACT;AAEA,QAAI,CAAC,OAAQ,MAAK,IAAI;AACtB,YAAQ,KAAK,IAAI;AACjB,WAAO,MAAM,OAAO;AAAA,EACtB,SAAS,OAAO,OAAO;AAEvB,SAAO;AACT;AAEA,SAAS,KAAK,MAA0B;AACtC,OAAK,KAAK,cAAc;AAC1B;AAEA,SAAS,eAAe,GAAqB,GAA6B;AACxE,SAAO,EAAE,CAAC,IAAI,EAAE,CAAC;AACnB;AAIO,SAAS,OAAO,SAA8C;AACnE,QAAM,SAAS,IAAI,aAAa;AAChC,MAAI,eAAe;AACnB,MAAI,aAAa;AACjB,MAAI,eAAe;AACnB,MAAI,aAAa;AAEjB,WAAS,IAAI,GAAG,IAAI,QAAQ,QAAQ,KAAK;AACvC,UAAM,OAAO,QAAQ,CAAC;AACtB,QAAI,IAAI,EAAG,QAAO,MAAM,SAAS;AACjC,QAAI,KAAK,WAAW,EAAG;AAEvB,QAAI,YAAY;AAEhB,aAAS,IAAI,GAAG,IAAI,KAAK,QAAQ,KAAK;AACpC,YAAM,UAAU,KAAK,CAAC;AACtB,UAAI,IAAI,EAAG,QAAO,MAAM,KAAK;AAE7B,oBAAc,QAAQ,WAAW,QAAQ,CAAC,IAAI,SAAS,CAAC;AACxD,kBAAY,QAAQ,CAAC;AAErB,UAAI,QAAQ,WAAW,EAAG;AAC1B,oBAAc,QAAQ,WAAW,QAAQ,CAAC,IAAI,YAAY,CAAC;AAC3D,oBAAc,QAAQ,WAAW,QAAQ,CAAC,IAAI,UAAU,CAAC;AACzD,oBAAc,QAAQ,WAAW,QAAQ,CAAC,IAAI,YAAY,CAAC;AAC3D,qBAAe,QAAQ,CAAC;AACxB,mBAAa,QAAQ,CAAC;AACtB,qBAAe,QAAQ,CAAC;AAExB,UAAI,QAAQ,WAAW,EAAG;AAC1B,oBAAc,QAAQ,WAAW,QAAQ,CAAC,IAAI,UAAU,CAAC;AACzD,mBAAa,QAAQ,CAAC;AAAA,IACxB;AAAA,EACF;AAEA,SAAO,OAAO,MAAM;AACtB;", + "names": [] +} diff --git a/dg-ui/node_modules/@jridgewell/sourcemap-codec/dist/sourcemap-codec.umd.js b/dg-ui/node_modules/@jridgewell/sourcemap-codec/dist/sourcemap-codec.umd.js new file mode 100644 index 0000000..a4f5e30 --- /dev/null +++ b/dg-ui/node_modules/@jridgewell/sourcemap-codec/dist/sourcemap-codec.umd.js @@ -0,0 +1,508 @@ +(function (global, factory) { + if (typeof exports === 'object' && typeof module !== 'undefined') { + factory(module); + module.exports = def(module); + } else if (typeof define === 'function' && define.amd) { + define(['module'], function(mod) { + factory.apply(this, arguments); + mod.exports = def(mod); + }); + } else { + const mod = { exports: {} }; + factory(mod); + global = typeof globalThis !== 'undefined' ? globalThis : global || self; + global.sourcemapCodec = def(mod); + } + function def(m) { return 'default' in m.exports ? m.exports.default : m.exports; } +})(this, (function (module) { +"use strict"; +var __defProp = Object.defineProperty; +var __getOwnPropDesc = Object.getOwnPropertyDescriptor; +var __getOwnPropNames = Object.getOwnPropertyNames; +var __hasOwnProp = Object.prototype.hasOwnProperty; +var __export = (target, all) => { + for (var name in all) + __defProp(target, name, { get: all[name], enumerable: true }); +}; +var __copyProps = (to, from, except, desc) => { + if (from && typeof from === "object" || typeof from === "function") { + for (let key of __getOwnPropNames(from)) + if (!__hasOwnProp.call(to, key) && key !== except) + __defProp(to, key, { get: () => from[key], enumerable: !(desc = __getOwnPropDesc(from, key)) || desc.enumerable }); + } + return to; +}; +var __toCommonJS = (mod) => __copyProps(__defProp({}, "__esModule", { value: true }), mod); + +// src/sourcemap-codec.ts +var sourcemap_codec_exports = {}; +__export(sourcemap_codec_exports, { + decode: () => decode, + decodeGeneratedRanges: () => decodeGeneratedRanges, + decodeOriginalScopes: () => decodeOriginalScopes, + decodeRangeMappings: () => decodeRangeMappings, + encode: () => encode, + encodeGeneratedRanges: () => encodeGeneratedRanges, + encodeOriginalScopes: () => encodeOriginalScopes, + encodeRangeMappings: () => encodeRangeMappings +}); +module.exports = __toCommonJS(sourcemap_codec_exports); + +// src/vlq.ts +var comma = ",".charCodeAt(0); +var semicolon = ";".charCodeAt(0); +var chars = "ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789+/"; +var intToChar = new Uint8Array(64); +var charToInt = new Uint8Array(128); +for (let i = 0; i < chars.length; i++) { + const c = chars.charCodeAt(i); + intToChar[i] = c; + charToInt[c] = i; +} +function decodeInteger(reader) { + let value = 0; + let shift = 0; + let integer = 0; + do { + const c = reader.next(); + integer = charToInt[c]; + value |= (integer & 31) << shift; + shift += 5; + } while (integer & 32); + return value; +} +function decodeSign(num) { + return num & 1 ? -2147483648 | -(num >>> 1) : num >>> 1; +} +function encodeInteger(builder, num) { + do { + let clamped = num & 31; + num >>>= 5; + if (num > 0) clamped |= 32; + builder.write(intToChar[clamped]); + } while (num > 0); +} +function encodeSign(num) { + return num < 0 ? -num << 1 | 1 : num << 1; +} +function hasMoreVlq(reader, max) { + if (reader.pos >= max) return false; + return reader.peek() !== comma; +} + +// src/strings.ts +var bufLength = 1024 * 16; +var td = typeof TextDecoder !== "undefined" ? /* @__PURE__ */ new TextDecoder() : typeof Buffer !== "undefined" ? { + decode(buf) { + const out = Buffer.from(buf.buffer, buf.byteOffset, buf.byteLength); + return out.toString(); + } +} : { + decode(buf) { + let out = ""; + for (let i = 0; i < buf.length; i++) { + out += String.fromCharCode(buf[i]); + } + return out; + } +}; +var StringWriter = class { + constructor() { + this.pos = 0; + this.out = ""; + this.buffer = new Uint8Array(bufLength); + } + write(v) { + const { buffer } = this; + buffer[this.pos++] = v; + if (this.pos === bufLength) { + this.out += td.decode(buffer); + this.pos = 0; + } + } + flush() { + const { buffer, out, pos } = this; + return pos > 0 ? out + td.decode(buffer.subarray(0, pos)) : out; + } +}; +var StringReader = class { + constructor(buffer) { + this.pos = 0; + this.buffer = buffer; + } + next() { + return this.buffer.charCodeAt(this.pos++); + } + peek() { + return this.buffer.charCodeAt(this.pos); + } + indexOf(char) { + const { buffer, pos } = this; + const idx = buffer.indexOf(char, pos); + return idx === -1 ? buffer.length : idx; + } +}; + +// src/scopes.ts +var EMPTY = []; +function decodeOriginalScopes(input) { + const { length } = input; + const reader = new StringReader(input); + const scopes = []; + const stack = []; + let line = 0; + for (; reader.pos < length; reader.pos++) { + line += decodeSign(decodeInteger(reader)); + const column = decodeSign(decodeInteger(reader)); + if (!hasMoreVlq(reader, length)) { + const last = stack.pop(); + last[2] = line; + last[3] = column; + continue; + } + const kind = decodeSign(decodeInteger(reader)); + const fields = decodeSign(decodeInteger(reader)); + const hasName = fields & 1; + const scope = hasName ? [line, column, 0, 0, kind, decodeSign(decodeInteger(reader))] : [line, column, 0, 0, kind]; + let vars = EMPTY; + if (hasMoreVlq(reader, length)) { + vars = []; + do { + const varsIndex = decodeSign(decodeInteger(reader)); + vars.push(varsIndex); + } while (hasMoreVlq(reader, length)); + } + scope.vars = vars; + scopes.push(scope); + stack.push(scope); + } + return scopes; +} +function encodeOriginalScopes(scopes) { + const writer = new StringWriter(); + for (let i = 0; i < scopes.length; ) { + i = _encodeOriginalScopes(scopes, i, writer, [0]); + } + return writer.flush(); +} +function _encodeOriginalScopes(scopes, index, writer, state) { + const scope = scopes[index]; + const { 0: startLine, 1: startColumn, 2: endLine, 3: endColumn, 4: kind, vars } = scope; + if (index > 0) writer.write(comma); + encodeInteger(writer, encodeSign(startLine - state[0])); + state[0] = startLine; + encodeInteger(writer, encodeSign(startColumn)); + encodeInteger(writer, encodeSign(kind)); + const fields = scope.length === 6 ? 1 : 0; + encodeInteger(writer, encodeSign(fields)); + if (scope.length === 6) encodeInteger(writer, encodeSign(scope[5])); + for (const v of vars) { + encodeInteger(writer, encodeSign(v)); + } + for (index++; index < scopes.length; ) { + const next = scopes[index]; + const { 0: l, 1: c } = next; + if (l > endLine || l === endLine && c >= endColumn) { + break; + } + index = _encodeOriginalScopes(scopes, index, writer, state); + } + writer.write(comma); + encodeInteger(writer, encodeSign(endLine - state[0])); + state[0] = endLine; + encodeInteger(writer, encodeSign(endColumn)); + return index; +} +function decodeGeneratedRanges(input) { + const { length } = input; + const reader = new StringReader(input); + const ranges = []; + const stack = []; + let genLine = 0; + let definitionSourcesIndex = 0; + let definitionScopeIndex = 0; + let callsiteSourcesIndex = 0; + let callsiteLine = 0; + let callsiteColumn = 0; + let bindingLine = 0; + let bindingColumn = 0; + do { + const semi = reader.indexOf(";"); + let genColumn = 0; + for (; reader.pos < semi; reader.pos++) { + genColumn += decodeSign(decodeInteger(reader)); + if (!hasMoreVlq(reader, semi)) { + const last = stack.pop(); + last[2] = genLine; + last[3] = genColumn; + continue; + } + const fields = decodeSign(decodeInteger(reader)); + const hasDefinition = fields & 1; + const hasCallsite = fields & 2; + const hasScope = fields & 4; + let callsite = null; + let bindings = EMPTY; + let range; + if (hasDefinition) { + const defSourcesIndex = definitionSourcesIndex + decodeSign(decodeInteger(reader)); + definitionScopeIndex = decodeSign(decodeInteger(reader)) + (definitionSourcesIndex === defSourcesIndex ? definitionScopeIndex : 0); + definitionSourcesIndex = defSourcesIndex; + range = [genLine, genColumn, 0, 0, defSourcesIndex, definitionScopeIndex]; + } else { + range = [genLine, genColumn, 0, 0]; + } + range.isScope = !!hasScope; + if (hasCallsite) { + const prevCsi = callsiteSourcesIndex; + const prevLine = callsiteLine; + callsiteSourcesIndex += decodeSign(decodeInteger(reader)); + const sameSource = prevCsi === callsiteSourcesIndex; + callsiteLine = (sameSource ? callsiteLine : 0) + decodeSign(decodeInteger(reader)); + callsiteColumn = (sameSource && prevLine === callsiteLine ? callsiteColumn : 0) + decodeSign(decodeInteger(reader)); + callsite = [callsiteSourcesIndex, callsiteLine, callsiteColumn]; + } + range.callsite = callsite; + if (hasMoreVlq(reader, semi)) { + bindings = []; + do { + bindingLine = genLine; + bindingColumn = genColumn; + const expressionsCount = decodeSign(decodeInteger(reader)); + let expressionRanges; + if (expressionsCount < -1) { + expressionRanges = [[decodeSign(decodeInteger(reader))]]; + for (let i = -1; i > expressionsCount; i--) { + const prevBl = bindingLine; + bindingLine += decodeSign(decodeInteger(reader)); + bindingColumn = (bindingLine === prevBl ? bindingColumn : 0) + decodeSign(decodeInteger(reader)); + const expression = decodeSign(decodeInteger(reader)); + expressionRanges.push([expression, bindingLine, bindingColumn]); + } + } else { + expressionRanges = [[expressionsCount]]; + } + bindings.push(expressionRanges); + } while (hasMoreVlq(reader, semi)); + } + range.bindings = bindings; + ranges.push(range); + stack.push(range); + } + genLine++; + reader.pos = semi + 1; + } while (reader.pos < length); + return ranges; +} +function encodeGeneratedRanges(ranges) { + if (ranges.length === 0) return ""; + const writer = new StringWriter(); + for (let i = 0; i < ranges.length; ) { + i = _encodeGeneratedRanges(ranges, i, writer, [0, 0, 0, 0, 0, 0, 0]); + } + return writer.flush(); +} +function _encodeGeneratedRanges(ranges, index, writer, state) { + const range = ranges[index]; + const { + 0: startLine, + 1: startColumn, + 2: endLine, + 3: endColumn, + isScope, + callsite, + bindings + } = range; + if (state[0] < startLine) { + catchupLine(writer, state[0], startLine); + state[0] = startLine; + state[1] = 0; + } else if (index > 0) { + writer.write(comma); + } + encodeInteger(writer, encodeSign(range[1] - state[1])); + state[1] = range[1]; + const fields = (range.length === 6 ? 1 : 0) | (callsite ? 2 : 0) | (isScope ? 4 : 0); + encodeInteger(writer, encodeSign(fields)); + if (range.length === 6) { + const { 4: sourcesIndex, 5: scopesIndex } = range; + if (sourcesIndex !== state[2]) { + state[3] = 0; + } + encodeInteger(writer, encodeSign(sourcesIndex - state[2])); + state[2] = sourcesIndex; + encodeInteger(writer, encodeSign(scopesIndex - state[3])); + state[3] = scopesIndex; + } + if (callsite) { + const { 0: sourcesIndex, 1: callLine, 2: callColumn } = range.callsite; + if (sourcesIndex !== state[4]) { + state[5] = 0; + state[6] = 0; + } else if (callLine !== state[5]) { + state[6] = 0; + } + encodeInteger(writer, encodeSign(sourcesIndex - state[4])); + state[4] = sourcesIndex; + encodeInteger(writer, encodeSign(callLine - state[5])); + state[5] = callLine; + encodeInteger(writer, encodeSign(callColumn - state[6])); + state[6] = callColumn; + } + if (bindings) { + for (const binding of bindings) { + if (binding.length > 1) encodeInteger(writer, encodeSign(-binding.length)); + const expression = binding[0][0]; + encodeInteger(writer, encodeSign(expression)); + let bindingStartLine = startLine; + let bindingStartColumn = startColumn; + for (let i = 1; i < binding.length; i++) { + const expRange = binding[i]; + encodeInteger(writer, encodeSign(expRange[1] - bindingStartLine)); + bindingStartLine = expRange[1]; + encodeInteger(writer, encodeSign(expRange[2] - bindingStartColumn)); + bindingStartColumn = expRange[2]; + encodeInteger(writer, encodeSign(expRange[0])); + } + } + } + for (index++; index < ranges.length; ) { + const next = ranges[index]; + const { 0: l, 1: c } = next; + if (l > endLine || l === endLine && c >= endColumn) { + break; + } + index = _encodeGeneratedRanges(ranges, index, writer, state); + } + if (state[0] < endLine) { + catchupLine(writer, state[0], endLine); + state[0] = endLine; + state[1] = 0; + } else { + writer.write(comma); + } + encodeInteger(writer, encodeSign(endColumn - state[1])); + state[1] = endColumn; + return index; +} +function catchupLine(writer, lastLine, line) { + do { + writer.write(semicolon); + } while (++lastLine < line); +} + +// src/range-mappings.ts +function decodeRangeMappings(input) { + const { length } = input; + const reader = new StringReader(input); + const rangeMappings = []; + do { + const semi = reader.indexOf(";"); + const indices = []; + let index = 0; + while (reader.pos < semi) { + index += decodeInteger(reader); + indices.push(index); + } + rangeMappings.push(indices); + reader.pos = semi + 1; + } while (reader.pos <= length); + return rangeMappings; +} +function encodeRangeMappings(decoded) { + if (decoded.length === 0) return ""; + const writer = new StringWriter(); + for (let i = 0; i < decoded.length; i++) { + const indices = decoded[i]; + if (i > 0) writer.write(semicolon); + let index = 0; + for (let j = 0; j < indices.length; j++) { + const offset = indices[j]; + encodeInteger(writer, offset - index); + index = offset; + } + } + return writer.flush(); +} + +// src/sourcemap-codec.ts +function decode(mappings) { + const { length } = mappings; + const reader = new StringReader(mappings); + const decoded = []; + let genColumn = 0; + let sourcesIndex = 0; + let sourceLine = 0; + let sourceColumn = 0; + let namesIndex = 0; + do { + const semi = reader.indexOf(";"); + const line = []; + let sorted = true; + let lastCol = 0; + genColumn = 0; + while (reader.pos < semi) { + let seg; + genColumn += decodeSign(decodeInteger(reader)); + if (genColumn < lastCol) sorted = false; + lastCol = genColumn; + if (hasMoreVlq(reader, semi)) { + sourcesIndex += decodeSign(decodeInteger(reader)); + sourceLine += decodeSign(decodeInteger(reader)); + sourceColumn += decodeSign(decodeInteger(reader)); + if (hasMoreVlq(reader, semi)) { + namesIndex += decodeSign(decodeInteger(reader)); + seg = [genColumn, sourcesIndex, sourceLine, sourceColumn, namesIndex]; + } else { + seg = [genColumn, sourcesIndex, sourceLine, sourceColumn]; + } + } else { + seg = [genColumn]; + } + line.push(seg); + reader.pos++; + } + if (!sorted) sort(line); + decoded.push(line); + reader.pos = semi + 1; + } while (reader.pos <= length); + return decoded; +} +function sort(line) { + line.sort(sortComparator); +} +function sortComparator(a, b) { + return a[0] - b[0]; +} +function encode(decoded) { + const writer = new StringWriter(); + let sourcesIndex = 0; + let sourceLine = 0; + let sourceColumn = 0; + let namesIndex = 0; + for (let i = 0; i < decoded.length; i++) { + const line = decoded[i]; + if (i > 0) writer.write(semicolon); + if (line.length === 0) continue; + let genColumn = 0; + for (let j = 0; j < line.length; j++) { + const segment = line[j]; + if (j > 0) writer.write(comma); + encodeInteger(writer, encodeSign(segment[0] - genColumn)); + genColumn = segment[0]; + if (segment.length === 1) continue; + encodeInteger(writer, encodeSign(segment[1] - sourcesIndex)); + encodeInteger(writer, encodeSign(segment[2] - sourceLine)); + encodeInteger(writer, encodeSign(segment[3] - sourceColumn)); + sourcesIndex = segment[1]; + sourceLine = segment[2]; + sourceColumn = segment[3]; + if (segment.length === 4) continue; + encodeInteger(writer, encodeSign(segment[4] - namesIndex)); + namesIndex = segment[4]; + } + } + return writer.flush(); +} +})); +//# sourceMappingURL=sourcemap-codec.umd.js.map diff --git a/dg-ui/node_modules/@jridgewell/sourcemap-codec/dist/sourcemap-codec.umd.js.map b/dg-ui/node_modules/@jridgewell/sourcemap-codec/dist/sourcemap-codec.umd.js.map new file mode 100644 index 0000000..c65e6f0 --- /dev/null +++ b/dg-ui/node_modules/@jridgewell/sourcemap-codec/dist/sourcemap-codec.umd.js.map @@ -0,0 +1,6 @@ +{ + "version": 3, + "sources": ["../src/sourcemap-codec.ts", "../src/vlq.ts", "../src/strings.ts", "../src/scopes.ts", "../src/range-mappings.ts"], + "mappings": ";;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;;;ACEO,IAAM,QAAQ,IAAI,WAAW,CAAC;AAC9B,IAAM,YAAY,IAAI,WAAW,CAAC;AAEzC,IAAM,QAAQ;AACd,IAAM,YAAY,IAAI,WAAW,EAAE;AACnC,IAAM,YAAY,IAAI,WAAW,GAAG;AAEpC,SAAS,IAAI,GAAG,IAAI,MAAM,QAAQ,KAAK;AACrC,QAAM,IAAI,MAAM,WAAW,CAAC;AAC5B,YAAU,CAAC,IAAI;AACf,YAAU,CAAC,IAAI;AACjB;AAEO,SAAS,cAAc,QAA8B;AAC1D,MAAI,QAAQ;AACZ,MAAI,QAAQ;AACZ,MAAI,UAAU;AAEd,KAAG;AACD,UAAM,IAAI,OAAO,KAAK;AACtB,cAAU,UAAU,CAAC;AACrB,cAAU,UAAU,OAAO;AAC3B,aAAS;AAAA,EACX,SAAS,UAAU;AAEnB,SAAO;AACT;AAEO,SAAS,WAAW,KAAqB;AAC9C,SAAO,MAAM,IAAI,cAAc,EAAE,QAAQ,KAAK,QAAQ;AACxD;AAEO,SAAS,cAAc,SAAuB,KAAa;AAChE,KAAG;AACD,QAAI,UAAU,MAAM;AACpB,aAAS;AACT,QAAI,MAAM,EAAG,YAAW;AACxB,YAAQ,MAAM,UAAU,OAAO,CAAC;AAAA,EAClC,SAAS,MAAM;AACjB;AAEO,SAAS,WAAW,KAAqB;AAC9C,SAAO,MAAM,IAAK,CAAC,OAAO,IAAK,IAAI,OAAO;AAC5C;AAEO,SAAS,WAAW,QAAsB,KAAa;AAC5D,MAAI,OAAO,OAAO,IAAK,QAAO;AAC9B,SAAO,OAAO,KAAK,MAAM;AAC3B;;;AClDA,IAAM,YAAY,OAAO;AAGzB,IAAM,KACJ,OAAO,gBAAgB,cACH,oBAAI,YAAY,IAChC,OAAO,WAAW,cAChB;AAAA,EACE,OAAO,KAAyB;AAC9B,UAAM,MAAM,OAAO,KAAK,IAAI,QAAQ,IAAI,YAAY,IAAI,UAAU;AAClE,WAAO,IAAI,SAAS;AAAA,EACtB;AACF,IACA;AAAA,EACE,OAAO,KAAyB;AAC9B,QAAI,MAAM;AACV,aAAS,IAAI,GAAG,IAAI,IAAI,QAAQ,KAAK;AACnC,aAAO,OAAO,aAAa,IAAI,CAAC,CAAC;AAAA,IACnC;AACA,WAAO;AAAA,EACT;AACF;AAED,IAAM,eAAN,MAAmB;AAAA,EAAnB;AACL,eAAM;AACN,SAAQ,MAAM;AACd,SAAQ,SAAS,IAAI,WAAW,SAAS;AAAA;AAAA,EAEzC,MAAM,GAAiB;AACrB,UAAM,EAAE,OAAO,IAAI;AACnB,WAAO,KAAK,KAAK,IAAI;AACrB,QAAI,KAAK,QAAQ,WAAW;AAC1B,WAAK,OAAO,GAAG,OAAO,MAAM;AAC5B,WAAK,MAAM;AAAA,IACb;AAAA,EACF;AAAA,EAEA,QAAgB;AACd,UAAM,EAAE,QAAQ,KAAK,IAAI,IAAI;AAC7B,WAAO,MAAM,IAAI,MAAM,GAAG,OAAO,OAAO,SAAS,GAAG,GAAG,CAAC,IAAI;AAAA,EAC9D;AACF;AAEO,IAAM,eAAN,MAAmB;AAAA,EAIxB,YAAY,QAAgB;AAH5B,eAAM;AAIJ,SAAK,SAAS;AAAA,EAChB;AAAA,EAEA,OAAe;AACb,WAAO,KAAK,OAAO,WAAW,KAAK,KAAK;AAAA,EAC1C;AAAA,EAEA,OAAe;AACb,WAAO,KAAK,OAAO,WAAW,KAAK,GAAG;AAAA,EACxC;AAAA,EAEA,QAAQ,MAAsB;AAC5B,UAAM,EAAE,QAAQ,IAAI,IAAI;AACxB,UAAM,MAAM,OAAO,QAAQ,MAAM,GAAG;AACpC,WAAO,QAAQ,KAAK,OAAO,SAAS;AAAA,EACtC;AACF;;;ACrDA,IAAM,QAAe,CAAC;AA+Bf,SAAS,qBAAqB,OAAgC;AACnE,QAAM,EAAE,OAAO,IAAI;AACnB,QAAM,SAAS,IAAI,aAAa,KAAK;AACrC,QAAM,SAA0B,CAAC;AACjC,QAAM,QAAyB,CAAC;AAChC,MAAI,OAAO;AAEX,SAAO,OAAO,MAAM,QAAQ,OAAO,OAAO;AACxC,YAAQ,WAAW,cAAc,MAAM,CAAC;AACxC,UAAM,SAAS,WAAW,cAAc,MAAM,CAAC;AAE/C,QAAI,CAAC,WAAW,QAAQ,MAAM,GAAG;AAC/B,YAAM,OAAO,MAAM,IAAI;AACvB,WAAK,CAAC,IAAI;AACV,WAAK,CAAC,IAAI;AACV;AAAA,IACF;AAEA,UAAM,OAAO,WAAW,cAAc,MAAM,CAAC;AAC7C,UAAM,SAAS,WAAW,cAAc,MAAM,CAAC;AAC/C,UAAM,UAAU,SAAS;AAEzB,UAAM,QACJ,UACI,CAAC,MAAM,QAAQ,GAAG,GAAG,MAAM,WAAW,cAAc,MAAM,CAAC,CAAC,IAC5D,CAAC,MAAM,QAAQ,GAAG,GAAG,IAAI;AAG/B,QAAI,OAAc;AAClB,QAAI,WAAW,QAAQ,MAAM,GAAG;AAC9B,aAAO,CAAC;AACR,SAAG;AACD,cAAM,YAAY,WAAW,cAAc,MAAM,CAAC;AAClD,aAAK,KAAK,SAAS;AAAA,MACrB,SAAS,WAAW,QAAQ,MAAM;AAAA,IACpC;AACA,UAAM,OAAO;AAEb,WAAO,KAAK,KAAK;AACjB,UAAM,KAAK,KAAK;AAAA,EAClB;AAEA,SAAO;AACT;AAEO,SAAS,qBAAqB,QAAiC;AACpE,QAAM,SAAS,IAAI,aAAa;AAEhC,WAAS,IAAI,GAAG,IAAI,OAAO,UAAU;AACnC,QAAI,sBAAsB,QAAQ,GAAG,QAAQ,CAAC,CAAC,CAAC;AAAA,EAClD;AAEA,SAAO,OAAO,MAAM;AACtB;AAEA,SAAS,sBACP,QACA,OACA,QACA,OAGQ;AACR,QAAM,QAAQ,OAAO,KAAK;AAC1B,QAAM,EAAE,GAAG,WAAW,GAAG,aAAa,GAAG,SAAS,GAAG,WAAW,GAAG,MAAM,KAAK,IAAI;AAElF,MAAI,QAAQ,EAAG,QAAO,MAAM,KAAK;AAEjC,gBAAc,QAAQ,WAAW,YAAY,MAAM,CAAC,CAAC,CAAC;AACtD,QAAM,CAAC,IAAI;AACX,gBAAc,QAAQ,WAAW,WAAW,CAAC;AAC7C,gBAAc,QAAQ,WAAW,IAAI,CAAC;AAEtC,QAAM,SAAS,MAAM,WAAW,IAAI,IAAS;AAC7C,gBAAc,QAAQ,WAAW,MAAM,CAAC;AACxC,MAAI,MAAM,WAAW,EAAG,eAAc,QAAQ,WAAW,MAAM,CAAC,CAAC,CAAC;AAElE,aAAW,KAAK,MAAM;AACpB,kBAAc,QAAQ,WAAW,CAAC,CAAC;AAAA,EACrC;AAEA,OAAK,SAAS,QAAQ,OAAO,UAAU;AACrC,UAAM,OAAO,OAAO,KAAK;AACzB,UAAM,EAAE,GAAG,GAAG,GAAG,EAAE,IAAI;AACvB,QAAI,IAAI,WAAY,MAAM,WAAW,KAAK,WAAY;AACpD;AAAA,IACF;AACA,YAAQ,sBAAsB,QAAQ,OAAO,QAAQ,KAAK;AAAA,EAC5D;AAEA,SAAO,MAAM,KAAK;AAClB,gBAAc,QAAQ,WAAW,UAAU,MAAM,CAAC,CAAC,CAAC;AACpD,QAAM,CAAC,IAAI;AACX,gBAAc,QAAQ,WAAW,SAAS,CAAC;AAE3C,SAAO;AACT;AAEO,SAAS,sBAAsB,OAAiC;AACrE,QAAM,EAAE,OAAO,IAAI;AACnB,QAAM,SAAS,IAAI,aAAa,KAAK;AACrC,QAAM,SAA2B,CAAC;AAClC,QAAM,QAA0B,CAAC;AAEjC,MAAI,UAAU;AACd,MAAI,yBAAyB;AAC7B,MAAI,uBAAuB;AAC3B,MAAI,uBAAuB;AAC3B,MAAI,eAAe;AACnB,MAAI,iBAAiB;AACrB,MAAI,cAAc;AAClB,MAAI,gBAAgB;AAEpB,KAAG;AACD,UAAM,OAAO,OAAO,QAAQ,GAAG;AAC/B,QAAI,YAAY;AAEhB,WAAO,OAAO,MAAM,MAAM,OAAO,OAAO;AACtC,mBAAa,WAAW,cAAc,MAAM,CAAC;AAE7C,UAAI,CAAC,WAAW,QAAQ,IAAI,GAAG;AAC7B,cAAM,OAAO,MAAM,IAAI;AACvB,aAAK,CAAC,IAAI;AACV,aAAK,CAAC,IAAI;AACV;AAAA,MACF;AAEA,YAAM,SAAS,WAAW,cAAc,MAAM,CAAC;AAC/C,YAAM,gBAAgB,SAAS;AAC/B,YAAM,cAAc,SAAS;AAC7B,YAAM,WAAW,SAAS;AAE1B,UAAI,WAA4B;AAChC,UAAI,WAAsB;AAC1B,UAAI;AACJ,UAAI,eAAe;AACjB,cAAM,kBAAkB,yBAAyB,WAAW,cAAc,MAAM,CAAC;AACjF,+BACE,WAAW,cAAc,MAAM,CAAC,KAC/B,2BAA2B,kBAAkB,uBAAuB;AAEvE,iCAAyB;AACzB,gBAAQ,CAAC,SAAS,WAAW,GAAG,GAAG,iBAAiB,oBAAoB;AAAA,MAC1E,OAAO;AACL,gBAAQ,CAAC,SAAS,WAAW,GAAG,CAAC;AAAA,MACnC;AAEA,YAAM,UAAU,CAAC,CAAC;AAElB,UAAI,aAAa;AACf,cAAM,UAAU;AAChB,cAAM,WAAW;AACjB,gCAAwB,WAAW,cAAc,MAAM,CAAC;AACxD,cAAM,aAAa,YAAY;AAC/B,wBAAgB,aAAa,eAAe,KAAK,WAAW,cAAc,MAAM,CAAC;AACjF,0BACG,cAAc,aAAa,eAAe,iBAAiB,KAC5D,WAAW,cAAc,MAAM,CAAC;AAElC,mBAAW,CAAC,sBAAsB,cAAc,cAAc;AAAA,MAChE;AACA,YAAM,WAAW;AAEjB,UAAI,WAAW,QAAQ,IAAI,GAAG;AAC5B,mBAAW,CAAC;AACZ,WAAG;AACD,wBAAc;AACd,0BAAgB;AAChB,gBAAM,mBAAmB,WAAW,cAAc,MAAM,CAAC;AACzD,cAAI;AACJ,cAAI,mBAAmB,IAAI;AACzB,+BAAmB,CAAC,CAAC,WAAW,cAAc,MAAM,CAAC,CAAC,CAAC;AACvD,qBAAS,IAAI,IAAI,IAAI,kBAAkB,KAAK;AAC1C,oBAAM,SAAS;AACf,6BAAe,WAAW,cAAc,MAAM,CAAC;AAC/C,+BACG,gBAAgB,SAAS,gBAAgB,KAAK,WAAW,cAAc,MAAM,CAAC;AACjF,oBAAM,aAAa,WAAW,cAAc,MAAM,CAAC;AACnD,+BAAiB,KAAK,CAAC,YAAY,aAAa,aAAa,CAAC;AAAA,YAChE;AAAA,UACF,OAAO;AACL,+BAAmB,CAAC,CAAC,gBAAgB,CAAC;AAAA,UACxC;AACA,mBAAS,KAAK,gBAAgB;AAAA,QAChC,SAAS,WAAW,QAAQ,IAAI;AAAA,MAClC;AACA,YAAM,WAAW;AAEjB,aAAO,KAAK,KAAK;AACjB,YAAM,KAAK,KAAK;AAAA,IAClB;AAEA;AACA,WAAO,MAAM,OAAO;AAAA,EACtB,SAAS,OAAO,MAAM;AAEtB,SAAO;AACT;AAEO,SAAS,sBAAsB,QAAkC;AACtE,MAAI,OAAO,WAAW,EAAG,QAAO;AAEhC,QAAM,SAAS,IAAI,aAAa;AAEhC,WAAS,IAAI,GAAG,IAAI,OAAO,UAAU;AACnC,QAAI,uBAAuB,QAAQ,GAAG,QAAQ,CAAC,GAAG,GAAG,GAAG,GAAG,GAAG,GAAG,CAAC,CAAC;AAAA,EACrE;AAEA,SAAO,OAAO,MAAM;AACtB;AAEA,SAAS,uBACP,QACA,OACA,QACA,OASQ;AACR,QAAM,QAAQ,OAAO,KAAK;AAC1B,QAAM;AAAA,IACJ,GAAG;AAAA,IACH,GAAG;AAAA,IACH,GAAG;AAAA,IACH,GAAG;AAAA,IACH;AAAA,IACA;AAAA,IACA;AAAA,EACF,IAAI;AAEJ,MAAI,MAAM,CAAC,IAAI,WAAW;AACxB,gBAAY,QAAQ,MAAM,CAAC,GAAG,SAAS;AACvC,UAAM,CAAC,IAAI;AACX,UAAM,CAAC,IAAI;AAAA,EACb,WAAW,QAAQ,GAAG;AACpB,WAAO,MAAM,KAAK;AAAA,EACpB;AAEA,gBAAc,QAAQ,WAAW,MAAM,CAAC,IAAI,MAAM,CAAC,CAAC,CAAC;AACrD,QAAM,CAAC,IAAI,MAAM,CAAC;AAElB,QAAM,UACH,MAAM,WAAW,IAAI,IAAS,MAAM,WAAW,IAAS,MAAM,UAAU,IAAS;AACpF,gBAAc,QAAQ,WAAW,MAAM,CAAC;AAExC,MAAI,MAAM,WAAW,GAAG;AACtB,UAAM,EAAE,GAAG,cAAc,GAAG,YAAY,IAAI;AAC5C,QAAI,iBAAiB,MAAM,CAAC,GAAG;AAC7B,YAAM,CAAC,IAAI;AAAA,IACb;AACA,kBAAc,QAAQ,WAAW,eAAe,MAAM,CAAC,CAAC,CAAC;AACzD,UAAM,CAAC,IAAI;AACX,kBAAc,QAAQ,WAAW,cAAc,MAAM,CAAC,CAAC,CAAC;AACxD,UAAM,CAAC,IAAI;AAAA,EACb;AAEA,MAAI,UAAU;AACZ,UAAM,EAAE,GAAG,cAAc,GAAG,UAAU,GAAG,WAAW,IAAI,MAAM;AAC9D,QAAI,iBAAiB,MAAM,CAAC,GAAG;AAC7B,YAAM,CAAC,IAAI;AACX,YAAM,CAAC,IAAI;AAAA,IACb,WAAW,aAAa,MAAM,CAAC,GAAG;AAChC,YAAM,CAAC,IAAI;AAAA,IACb;AACA,kBAAc,QAAQ,WAAW,eAAe,MAAM,CAAC,CAAC,CAAC;AACzD,UAAM,CAAC,IAAI;AACX,kBAAc,QAAQ,WAAW,WAAW,MAAM,CAAC,CAAC,CAAC;AACrD,UAAM,CAAC,IAAI;AACX,kBAAc,QAAQ,WAAW,aAAa,MAAM,CAAC,CAAC,CAAC;AACvD,UAAM,CAAC,IAAI;AAAA,EACb;AAEA,MAAI,UAAU;AACZ,eAAW,WAAW,UAAU;AAC9B,UAAI,QAAQ,SAAS,EAAG,eAAc,QAAQ,WAAW,CAAC,QAAQ,MAAM,CAAC;AACzE,YAAM,aAAa,QAAQ,CAAC,EAAE,CAAC;AAC/B,oBAAc,QAAQ,WAAW,UAAU,CAAC;AAC5C,UAAI,mBAAmB;AACvB,UAAI,qBAAqB;AACzB,eAAS,IAAI,GAAG,IAAI,QAAQ,QAAQ,KAAK;AACvC,cAAM,WAAW,QAAQ,CAAC;AAC1B,sBAAc,QAAQ,WAAW,SAAS,CAAC,IAAK,gBAAgB,CAAC;AACjE,2BAAmB,SAAS,CAAC;AAC7B,sBAAc,QAAQ,WAAW,SAAS,CAAC,IAAK,kBAAkB,CAAC;AACnE,6BAAqB,SAAS,CAAC;AAC/B,sBAAc,QAAQ,WAAW,SAAS,CAAC,CAAE,CAAC;AAAA,MAChD;AAAA,IACF;AAAA,EACF;AAEA,OAAK,SAAS,QAAQ,OAAO,UAAU;AACrC,UAAM,OAAO,OAAO,KAAK;AACzB,UAAM,EAAE,GAAG,GAAG,GAAG,EAAE,IAAI;AACvB,QAAI,IAAI,WAAY,MAAM,WAAW,KAAK,WAAY;AACpD;AAAA,IACF;AACA,YAAQ,uBAAuB,QAAQ,OAAO,QAAQ,KAAK;AAAA,EAC7D;AAEA,MAAI,MAAM,CAAC,IAAI,SAAS;AACtB,gBAAY,QAAQ,MAAM,CAAC,GAAG,OAAO;AACrC,UAAM,CAAC,IAAI;AACX,UAAM,CAAC,IAAI;AAAA,EACb,OAAO;AACL,WAAO,MAAM,KAAK;AAAA,EACpB;AACA,gBAAc,QAAQ,WAAW,YAAY,MAAM,CAAC,CAAC,CAAC;AACtD,QAAM,CAAC,IAAI;AAEX,SAAO;AACT;AAEA,SAAS,YAAY,QAAsB,UAAkB,MAAc;AACzE,KAAG;AACD,WAAO,MAAM,SAAS;AAAA,EACxB,SAAS,EAAE,WAAW;AACxB;;;ACtWO,SAAS,oBAAoB,OAA8B;AAChE,QAAM,EAAE,OAAO,IAAI;AACnB,QAAM,SAAS,IAAI,aAAa,KAAK;AACrC,QAAM,gBAA+B,CAAC;AAEtC,KAAG;AACD,UAAM,OAAO,OAAO,QAAQ,GAAG;AAC/B,UAAM,UAA0B,CAAC;AACjC,QAAI,QAAQ;AAEZ,WAAO,OAAO,MAAM,MAAM;AACxB,eAAS,cAAc,MAAM;AAC7B,cAAQ,KAAK,KAAK;AAAA,IACpB;AAEA,kBAAc,KAAK,OAAO;AAC1B,WAAO,MAAM,OAAO;AAAA,EACtB,SAAS,OAAO,OAAO;AAEvB,SAAO;AACT;AAEO,SAAS,oBAAoB,SAAgC;AAClE,MAAI,QAAQ,WAAW,EAAG,QAAO;AAEjC,QAAM,SAAS,IAAI,aAAa;AAEhC,WAAS,IAAI,GAAG,IAAI,QAAQ,QAAQ,KAAK;AACvC,UAAM,UAAU,QAAQ,CAAC;AACzB,QAAI,IAAI,EAAG,QAAO,MAAM,SAAS;AAEjC,QAAI,QAAQ;AACZ,aAAS,IAAI,GAAG,IAAI,QAAQ,QAAQ,KAAK;AACvC,YAAM,SAAS,QAAQ,CAAC;AACxB,oBAAc,QAAQ,SAAS,KAAK;AACpC,cAAQ;AAAA,IACV;AAAA,EACF;AAEA,SAAO,OAAO,MAAM;AACtB;;;AJjBO,SAAS,OAAO,UAAqC;AAC1D,QAAM,EAAE,OAAO,IAAI;AACnB,QAAM,SAAS,IAAI,aAAa,QAAQ;AACxC,QAAM,UAA6B,CAAC;AACpC,MAAI,YAAY;AAChB,MAAI,eAAe;AACnB,MAAI,aAAa;AACjB,MAAI,eAAe;AACnB,MAAI,aAAa;AAEjB,KAAG;AACD,UAAM,OAAO,OAAO,QAAQ,GAAG;AAC/B,UAAM,OAAsB,CAAC;AAC7B,QAAI,SAAS;AACb,QAAI,UAAU;AACd,gBAAY;AAEZ,WAAO,OAAO,MAAM,MAAM;AACxB,UAAI;AAEJ,mBAAa,WAAW,cAAc,MAAM,CAAC;AAC7C,UAAI,YAAY,QAAS,UAAS;AAClC,gBAAU;AAEV,UAAI,WAAW,QAAQ,IAAI,GAAG;AAC5B,wBAAgB,WAAW,cAAc,MAAM,CAAC;AAChD,sBAAc,WAAW,cAAc,MAAM,CAAC;AAC9C,wBAAgB,WAAW,cAAc,MAAM,CAAC;AAEhD,YAAI,WAAW,QAAQ,IAAI,GAAG;AAC5B,wBAAc,WAAW,cAAc,MAAM,CAAC;AAC9C,gBAAM,CAAC,WAAW,cAAc,YAAY,cAAc,UAAU;AAAA,QACtE,OAAO;AACL,gBAAM,CAAC,WAAW,cAAc,YAAY,YAAY;AAAA,QAC1D;AAAA,MACF,OAAO;AACL,cAAM,CAAC,SAAS;AAAA,MAClB;AAEA,WAAK,KAAK,GAAG;AACb,aAAO;AAAA,IACT;AAEA,QAAI,CAAC,OAAQ,MAAK,IAAI;AACtB,YAAQ,KAAK,IAAI;AACjB,WAAO,MAAM,OAAO;AAAA,EACtB,SAAS,OAAO,OAAO;AAEvB,SAAO;AACT;AAEA,SAAS,KAAK,MAA0B;AACtC,OAAK,KAAK,cAAc;AAC1B;AAEA,SAAS,eAAe,GAAqB,GAA6B;AACxE,SAAO,EAAE,CAAC,IAAI,EAAE,CAAC;AACnB;AAIO,SAAS,OAAO,SAA8C;AACnE,QAAM,SAAS,IAAI,aAAa;AAChC,MAAI,eAAe;AACnB,MAAI,aAAa;AACjB,MAAI,eAAe;AACnB,MAAI,aAAa;AAEjB,WAAS,IAAI,GAAG,IAAI,QAAQ,QAAQ,KAAK;AACvC,UAAM,OAAO,QAAQ,CAAC;AACtB,QAAI,IAAI,EAAG,QAAO,MAAM,SAAS;AACjC,QAAI,KAAK,WAAW,EAAG;AAEvB,QAAI,YAAY;AAEhB,aAAS,IAAI,GAAG,IAAI,KAAK,QAAQ,KAAK;AACpC,YAAM,UAAU,KAAK,CAAC;AACtB,UAAI,IAAI,EAAG,QAAO,MAAM,KAAK;AAE7B,oBAAc,QAAQ,WAAW,QAAQ,CAAC,IAAI,SAAS,CAAC;AACxD,kBAAY,QAAQ,CAAC;AAErB,UAAI,QAAQ,WAAW,EAAG;AAC1B,oBAAc,QAAQ,WAAW,QAAQ,CAAC,IAAI,YAAY,CAAC;AAC3D,oBAAc,QAAQ,WAAW,QAAQ,CAAC,IAAI,UAAU,CAAC;AACzD,oBAAc,QAAQ,WAAW,QAAQ,CAAC,IAAI,YAAY,CAAC;AAC3D,qBAAe,QAAQ,CAAC;AACxB,mBAAa,QAAQ,CAAC;AACtB,qBAAe,QAAQ,CAAC;AAExB,UAAI,QAAQ,WAAW,EAAG;AAC1B,oBAAc,QAAQ,WAAW,QAAQ,CAAC,IAAI,UAAU,CAAC;AACzD,mBAAa,QAAQ,CAAC;AAAA,IACxB;AAAA,EACF;AAEA,SAAO,OAAO,MAAM;AACtB;", + "names": [] +} diff --git a/dg-ui/node_modules/@jridgewell/sourcemap-codec/package.json b/dg-ui/node_modules/@jridgewell/sourcemap-codec/package.json new file mode 100644 index 0000000..a84412b --- /dev/null +++ b/dg-ui/node_modules/@jridgewell/sourcemap-codec/package.json @@ -0,0 +1,64 @@ +{ + "name": "@jridgewell/sourcemap-codec", + "version": "1.6.0", + "description": "Encode/decode sourcemap mappings", + "keywords": [ + "sourcemap", + "vlq" + ], + "main": "dist/sourcemap-codec.umd.js", + "module": "dist/sourcemap-codec.mjs", + "types": "types/sourcemap-codec.d.cts", + "files": [ + "dist", + "src", + "types" + ], + "exports": { + ".": [ + { + "import": { + "types": "./types/sourcemap-codec.d.mts", + "default": "./dist/sourcemap-codec.mjs" + }, + "default": { + "types": "./types/sourcemap-codec.d.cts", + "default": "./dist/sourcemap-codec.umd.js" + } + }, + "./dist/sourcemap-codec.umd.js" + ], + "./package.json": "./package.json" + }, + "scripts": { + "benchmark": "run-s build:code benchmark:*", + "benchmark:install": "cd benchmark && npm install", + "benchmark:only": "node --expose-gc benchmark/index.js", + "build": "run-s -n build:code build:types", + "build:code": "node ../../esbuild.mjs sourcemap-codec.ts", + "build:types": "run-s build:types:force build:types:emit build:types:mts", + "build:types:force": "rimraf tsconfig.build.tsbuildinfo", + "build:types:emit": "tsc --project tsconfig.build.json", + "build:types:mts": "node ../../mts-types.mjs", + "clean": "run-s -n clean:code clean:types", + "clean:code": "tsc --build --clean tsconfig.build.json", + "clean:types": "rimraf dist types", + "test": "run-s -n test:types test:only test:format", + "test:format": "prettier --check '{src,test}/**/*.ts'", + "test:only": "mocha", + "test:types": "eslint '{src,test}/**/*.ts'", + "test:watch": "mocha --watch", + "lint": "run-s -n lint:types lint:format", + "lint:format": "npm run test:format -- --write", + "lint:types": "npm run test:types -- --fix", + "prepublishOnly": "npm run-s -n build test" + }, + "homepage": "https://github.com/jridgewell/sourcemaps/tree/main/packages/sourcemap-codec", + "repository": { + "type": "git", + "url": "git+https://github.com/jridgewell/sourcemaps.git", + "directory": "packages/sourcemap-codec" + }, + "author": "Justin Ridgewell ", + "license": "MIT" +} diff --git a/dg-ui/node_modules/@jridgewell/sourcemap-codec/src/range-mappings.ts b/dg-ui/node_modules/@jridgewell/sourcemap-codec/src/range-mappings.ts new file mode 100644 index 0000000..710d124 --- /dev/null +++ b/dg-ui/node_modules/@jridgewell/sourcemap-codec/src/range-mappings.ts @@ -0,0 +1,47 @@ +import { StringReader, StringWriter } from './strings'; +import { decodeInteger, encodeInteger, semicolon } from './vlq'; + +export type MappingIndex = number; +export type RangeMappings = MappingIndex[][]; + +export function decodeRangeMappings(input: string): RangeMappings { + const { length } = input; + const reader = new StringReader(input); + const rangeMappings: RangeMappings = []; + + do { + const semi = reader.indexOf(';'); + const indices: MappingIndex[] = []; + let index = 0; + + while (reader.pos < semi) { + index += decodeInteger(reader); + indices.push(index); + } + + rangeMappings.push(indices); + reader.pos = semi + 1; + } while (reader.pos <= length); + + return rangeMappings; +} + +export function encodeRangeMappings(decoded: RangeMappings): string { + if (decoded.length === 0) return ''; + + const writer = new StringWriter(); + + for (let i = 0; i < decoded.length; i++) { + const indices = decoded[i]; + if (i > 0) writer.write(semicolon); + + let index = 0; + for (let j = 0; j < indices.length; j++) { + const offset = indices[j]; + encodeInteger(writer, offset - index); + index = offset; + } + } + + return writer.flush(); +} diff --git a/dg-ui/node_modules/@jridgewell/sourcemap-codec/src/scopes.ts b/dg-ui/node_modules/@jridgewell/sourcemap-codec/src/scopes.ts new file mode 100644 index 0000000..9e8d4d5 --- /dev/null +++ b/dg-ui/node_modules/@jridgewell/sourcemap-codec/src/scopes.ts @@ -0,0 +1,365 @@ +import { StringReader, StringWriter } from './strings'; +import { + comma, + decodeInteger, + decodeSign, + encodeInteger, + encodeSign, + hasMoreVlq, + semicolon, +} from './vlq'; + +const EMPTY: any[] = []; + +type Line = number; +type Column = number; +type Kind = number; +type Name = number; +type Var = number; +type SourcesIndex = number; +type ScopesIndex = number; + +type Mix = (A & O) | (B & O); + +export type OriginalScope = Mix< + [Line, Column, Line, Column, Kind], + [Line, Column, Line, Column, Kind, Name], + { vars: Var[] } +>; + +export type GeneratedRange = Mix< + [Line, Column, Line, Column], + [Line, Column, Line, Column, SourcesIndex, ScopesIndex], + { + callsite: CallSite | null; + bindings: Binding[]; + isScope: boolean; + } +>; +export type CallSite = [SourcesIndex, Line, Column]; +type Binding = BindingExpressionRange[]; +export type BindingExpressionRange = [Name] | [Name, Line, Column]; + +export function decodeOriginalScopes(input: string): OriginalScope[] { + const { length } = input; + const reader = new StringReader(input); + const scopes: OriginalScope[] = []; + const stack: OriginalScope[] = []; + let line = 0; + + for (; reader.pos < length; reader.pos++) { + line += decodeSign(decodeInteger(reader)); + const column = decodeSign(decodeInteger(reader)); + + if (!hasMoreVlq(reader, length)) { + const last = stack.pop()!; + last[2] = line; + last[3] = column; + continue; + } + + const kind = decodeSign(decodeInteger(reader)); + const fields = decodeSign(decodeInteger(reader)); + const hasName = fields & 0b0001; + + const scope: OriginalScope = ( + hasName + ? [line, column, 0, 0, kind, decodeSign(decodeInteger(reader))] + : [line, column, 0, 0, kind] + ) as OriginalScope; + + let vars: Var[] = EMPTY; + if (hasMoreVlq(reader, length)) { + vars = []; + do { + const varsIndex = decodeSign(decodeInteger(reader)); + vars.push(varsIndex); + } while (hasMoreVlq(reader, length)); + } + scope.vars = vars; + + scopes.push(scope); + stack.push(scope); + } + + return scopes; +} + +export function encodeOriginalScopes(scopes: OriginalScope[]): string { + const writer = new StringWriter(); + + for (let i = 0; i < scopes.length; ) { + i = _encodeOriginalScopes(scopes, i, writer, [0]); + } + + return writer.flush(); +} + +function _encodeOriginalScopes( + scopes: OriginalScope[], + index: number, + writer: StringWriter, + state: [ + number, // GenColumn + ], +): number { + const scope = scopes[index]; + const { 0: startLine, 1: startColumn, 2: endLine, 3: endColumn, 4: kind, vars } = scope; + + if (index > 0) writer.write(comma); + + encodeInteger(writer, encodeSign(startLine - state[0])); + state[0] = startLine; + encodeInteger(writer, encodeSign(startColumn)); + encodeInteger(writer, encodeSign(kind)); + + const fields = scope.length === 6 ? 0b0001 : 0; + encodeInteger(writer, encodeSign(fields)); + if (scope.length === 6) encodeInteger(writer, encodeSign(scope[5])); + + for (const v of vars) { + encodeInteger(writer, encodeSign(v)); + } + + for (index++; index < scopes.length; ) { + const next = scopes[index]; + const { 0: l, 1: c } = next; + if (l > endLine || (l === endLine && c >= endColumn)) { + break; + } + index = _encodeOriginalScopes(scopes, index, writer, state); + } + + writer.write(comma); + encodeInteger(writer, encodeSign(endLine - state[0])); + state[0] = endLine; + encodeInteger(writer, encodeSign(endColumn)); + + return index; +} + +export function decodeGeneratedRanges(input: string): GeneratedRange[] { + const { length } = input; + const reader = new StringReader(input); + const ranges: GeneratedRange[] = []; + const stack: GeneratedRange[] = []; + + let genLine = 0; + let definitionSourcesIndex = 0; + let definitionScopeIndex = 0; + let callsiteSourcesIndex = 0; + let callsiteLine = 0; + let callsiteColumn = 0; + let bindingLine = 0; + let bindingColumn = 0; + + do { + const semi = reader.indexOf(';'); + let genColumn = 0; + + for (; reader.pos < semi; reader.pos++) { + genColumn += decodeSign(decodeInteger(reader)); + + if (!hasMoreVlq(reader, semi)) { + const last = stack.pop()!; + last[2] = genLine; + last[3] = genColumn; + continue; + } + + const fields = decodeSign(decodeInteger(reader)); + const hasDefinition = fields & 0b0001; + const hasCallsite = fields & 0b0010; + const hasScope = fields & 0b0100; + + let callsite: CallSite | null = null; + let bindings: Binding[] = EMPTY; + let range: GeneratedRange; + if (hasDefinition) { + const defSourcesIndex = definitionSourcesIndex + decodeSign(decodeInteger(reader)); + definitionScopeIndex = + decodeSign(decodeInteger(reader)) + + (definitionSourcesIndex === defSourcesIndex ? definitionScopeIndex : 0); + + definitionSourcesIndex = defSourcesIndex; + range = [genLine, genColumn, 0, 0, defSourcesIndex, definitionScopeIndex] as GeneratedRange; + } else { + range = [genLine, genColumn, 0, 0] as GeneratedRange; + } + + range.isScope = !!hasScope; + + if (hasCallsite) { + const prevCsi = callsiteSourcesIndex; + const prevLine = callsiteLine; + callsiteSourcesIndex += decodeSign(decodeInteger(reader)); + const sameSource = prevCsi === callsiteSourcesIndex; + callsiteLine = (sameSource ? callsiteLine : 0) + decodeSign(decodeInteger(reader)); + callsiteColumn = + (sameSource && prevLine === callsiteLine ? callsiteColumn : 0) + + decodeSign(decodeInteger(reader)); + + callsite = [callsiteSourcesIndex, callsiteLine, callsiteColumn]; + } + range.callsite = callsite; + + if (hasMoreVlq(reader, semi)) { + bindings = []; + do { + bindingLine = genLine; + bindingColumn = genColumn; + const expressionsCount = decodeSign(decodeInteger(reader)); + let expressionRanges: BindingExpressionRange[]; + if (expressionsCount < -1) { + expressionRanges = [[decodeSign(decodeInteger(reader))]]; + for (let i = -1; i > expressionsCount; i--) { + const prevBl = bindingLine; + bindingLine += decodeSign(decodeInteger(reader)); + bindingColumn = + (bindingLine === prevBl ? bindingColumn : 0) + decodeSign(decodeInteger(reader)); + const expression = decodeSign(decodeInteger(reader)); + expressionRanges.push([expression, bindingLine, bindingColumn]); + } + } else { + expressionRanges = [[expressionsCount]]; + } + bindings.push(expressionRanges); + } while (hasMoreVlq(reader, semi)); + } + range.bindings = bindings; + + ranges.push(range); + stack.push(range); + } + + genLine++; + reader.pos = semi + 1; + } while (reader.pos < length); + + return ranges; +} + +export function encodeGeneratedRanges(ranges: GeneratedRange[]): string { + if (ranges.length === 0) return ''; + + const writer = new StringWriter(); + + for (let i = 0; i < ranges.length; ) { + i = _encodeGeneratedRanges(ranges, i, writer, [0, 0, 0, 0, 0, 0, 0]); + } + + return writer.flush(); +} + +function _encodeGeneratedRanges( + ranges: GeneratedRange[], + index: number, + writer: StringWriter, + state: [ + number, // GenLine + number, // GenColumn + number, // DefSourcesIndex + number, // DefScopesIndex + number, // CallSourcesIndex + number, // CallLine + number, // CallColumn + ], +): number { + const range = ranges[index]; + const { + 0: startLine, + 1: startColumn, + 2: endLine, + 3: endColumn, + isScope, + callsite, + bindings, + } = range; + + if (state[0] < startLine) { + catchupLine(writer, state[0], startLine); + state[0] = startLine; + state[1] = 0; + } else if (index > 0) { + writer.write(comma); + } + + encodeInteger(writer, encodeSign(range[1] - state[1])); + state[1] = range[1]; + + const fields = + (range.length === 6 ? 0b0001 : 0) | (callsite ? 0b0010 : 0) | (isScope ? 0b0100 : 0); + encodeInteger(writer, encodeSign(fields)); + + if (range.length === 6) { + const { 4: sourcesIndex, 5: scopesIndex } = range; + if (sourcesIndex !== state[2]) { + state[3] = 0; + } + encodeInteger(writer, encodeSign(sourcesIndex - state[2])); + state[2] = sourcesIndex; + encodeInteger(writer, encodeSign(scopesIndex - state[3])); + state[3] = scopesIndex; + } + + if (callsite) { + const { 0: sourcesIndex, 1: callLine, 2: callColumn } = range.callsite!; + if (sourcesIndex !== state[4]) { + state[5] = 0; + state[6] = 0; + } else if (callLine !== state[5]) { + state[6] = 0; + } + encodeInteger(writer, encodeSign(sourcesIndex - state[4])); + state[4] = sourcesIndex; + encodeInteger(writer, encodeSign(callLine - state[5])); + state[5] = callLine; + encodeInteger(writer, encodeSign(callColumn - state[6])); + state[6] = callColumn; + } + + if (bindings) { + for (const binding of bindings) { + if (binding.length > 1) encodeInteger(writer, encodeSign(-binding.length)); + const expression = binding[0][0]; + encodeInteger(writer, encodeSign(expression)); + let bindingStartLine = startLine; + let bindingStartColumn = startColumn; + for (let i = 1; i < binding.length; i++) { + const expRange = binding[i]; + encodeInteger(writer, encodeSign(expRange[1]! - bindingStartLine)); + bindingStartLine = expRange[1]!; + encodeInteger(writer, encodeSign(expRange[2]! - bindingStartColumn)); + bindingStartColumn = expRange[2]!; + encodeInteger(writer, encodeSign(expRange[0]!)); + } + } + } + + for (index++; index < ranges.length; ) { + const next = ranges[index]; + const { 0: l, 1: c } = next; + if (l > endLine || (l === endLine && c >= endColumn)) { + break; + } + index = _encodeGeneratedRanges(ranges, index, writer, state); + } + + if (state[0] < endLine) { + catchupLine(writer, state[0], endLine); + state[0] = endLine; + state[1] = 0; + } else { + writer.write(comma); + } + encodeInteger(writer, encodeSign(endColumn - state[1])); + state[1] = endColumn; + + return index; +} + +function catchupLine(writer: StringWriter, lastLine: number, line: number) { + do { + writer.write(semicolon); + } while (++lastLine < line); +} diff --git a/dg-ui/node_modules/@jridgewell/sourcemap-codec/src/sourcemap-codec.ts b/dg-ui/node_modules/@jridgewell/sourcemap-codec/src/sourcemap-codec.ts new file mode 100644 index 0000000..dd02c6f --- /dev/null +++ b/dg-ui/node_modules/@jridgewell/sourcemap-codec/src/sourcemap-codec.ts @@ -0,0 +1,127 @@ +import { + comma, + decodeInteger, + decodeSign, + encodeInteger, + encodeSign, + hasMoreVlq, + semicolon, +} from './vlq'; +import { StringWriter, StringReader } from './strings'; + +export { + decodeOriginalScopes, + encodeOriginalScopes, + decodeGeneratedRanges, + encodeGeneratedRanges, +} from './scopes'; +export type { OriginalScope, GeneratedRange, CallSite, BindingExpressionRange } from './scopes'; + +export { decodeRangeMappings, encodeRangeMappings } from './range-mappings'; +export type { MappingIndex, RangeMappings } from './range-mappings'; + +export type SourceMapSegment = + | [number] + | [number, number, number, number] + | [number, number, number, number, number]; +export type SourceMapLine = SourceMapSegment[]; +export type SourceMapMappings = SourceMapLine[]; + +export function decode(mappings: string): SourceMapMappings { + const { length } = mappings; + const reader = new StringReader(mappings); + const decoded: SourceMapMappings = []; + let genColumn = 0; + let sourcesIndex = 0; + let sourceLine = 0; + let sourceColumn = 0; + let namesIndex = 0; + + do { + const semi = reader.indexOf(';'); + const line: SourceMapLine = []; + let sorted = true; + let lastCol = 0; + genColumn = 0; + + while (reader.pos < semi) { + let seg: SourceMapSegment; + + genColumn += decodeSign(decodeInteger(reader)); + if (genColumn < lastCol) sorted = false; + lastCol = genColumn; + + if (hasMoreVlq(reader, semi)) { + sourcesIndex += decodeSign(decodeInteger(reader)); + sourceLine += decodeSign(decodeInteger(reader)); + sourceColumn += decodeSign(decodeInteger(reader)); + + if (hasMoreVlq(reader, semi)) { + namesIndex += decodeSign(decodeInteger(reader)); + seg = [genColumn, sourcesIndex, sourceLine, sourceColumn, namesIndex]; + } else { + seg = [genColumn, sourcesIndex, sourceLine, sourceColumn]; + } + } else { + seg = [genColumn]; + } + + line.push(seg); + reader.pos++; + } + + if (!sorted) sort(line); + decoded.push(line); + reader.pos = semi + 1; + } while (reader.pos <= length); + + return decoded; +} + +function sort(line: SourceMapSegment[]) { + line.sort(sortComparator); +} + +function sortComparator(a: SourceMapSegment, b: SourceMapSegment): number { + return a[0] - b[0]; +} + +export function encode(decoded: SourceMapMappings): string; +export function encode(decoded: Readonly): string; +export function encode(decoded: Readonly): string { + const writer = new StringWriter(); + let sourcesIndex = 0; + let sourceLine = 0; + let sourceColumn = 0; + let namesIndex = 0; + + for (let i = 0; i < decoded.length; i++) { + const line = decoded[i]; + if (i > 0) writer.write(semicolon); + if (line.length === 0) continue; + + let genColumn = 0; + + for (let j = 0; j < line.length; j++) { + const segment = line[j]; + if (j > 0) writer.write(comma); + + encodeInteger(writer, encodeSign(segment[0] - genColumn)); + genColumn = segment[0]; + + if (segment.length === 1) continue; + encodeInteger(writer, encodeSign(segment[1] - sourcesIndex)); + encodeInteger(writer, encodeSign(segment[2] - sourceLine)); + encodeInteger(writer, encodeSign(segment[3] - sourceColumn)); + sourcesIndex = segment[1]; + sourceLine = segment[2]; + sourceColumn = segment[3]; + + if (segment.length === 4) continue; + encodeInteger(writer, encodeSign(segment[4] - namesIndex)); + namesIndex = segment[4]; + } + } + + return writer.flush(); +} diff --git a/dg-ui/node_modules/@jridgewell/sourcemap-codec/src/strings.ts b/dg-ui/node_modules/@jridgewell/sourcemap-codec/src/strings.ts new file mode 100644 index 0000000..d161965 --- /dev/null +++ b/dg-ui/node_modules/@jridgewell/sourcemap-codec/src/strings.ts @@ -0,0 +1,65 @@ +const bufLength = 1024 * 16; + +// Provide a fallback for older environments. +const td = + typeof TextDecoder !== 'undefined' + ? /* #__PURE__ */ new TextDecoder() + : typeof Buffer !== 'undefined' + ? { + decode(buf: Uint8Array): string { + const out = Buffer.from(buf.buffer, buf.byteOffset, buf.byteLength); + return out.toString(); + }, + } + : { + decode(buf: Uint8Array): string { + let out = ''; + for (let i = 0; i < buf.length; i++) { + out += String.fromCharCode(buf[i]); + } + return out; + }, + }; + +export class StringWriter { + pos = 0; + private out = ''; + private buffer = new Uint8Array(bufLength); + + write(v: number): void { + const { buffer } = this; + buffer[this.pos++] = v; + if (this.pos === bufLength) { + this.out += td.decode(buffer); + this.pos = 0; + } + } + + flush(): string { + const { buffer, out, pos } = this; + return pos > 0 ? out + td.decode(buffer.subarray(0, pos)) : out; + } +} + +export class StringReader { + pos = 0; + declare private buffer: string; + + constructor(buffer: string) { + this.buffer = buffer; + } + + next(): number { + return this.buffer.charCodeAt(this.pos++); + } + + peek(): number { + return this.buffer.charCodeAt(this.pos); + } + + indexOf(char: string): number { + const { buffer, pos } = this; + const idx = buffer.indexOf(char, pos); + return idx === -1 ? buffer.length : idx; + } +} diff --git a/dg-ui/node_modules/@jridgewell/sourcemap-codec/src/vlq.ts b/dg-ui/node_modules/@jridgewell/sourcemap-codec/src/vlq.ts new file mode 100644 index 0000000..e2f047e --- /dev/null +++ b/dg-ui/node_modules/@jridgewell/sourcemap-codec/src/vlq.ts @@ -0,0 +1,51 @@ +import type { StringReader, StringWriter } from './strings'; + +export const comma = ','.charCodeAt(0); +export const semicolon = ';'.charCodeAt(0); + +const chars = 'ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789+/'; +const intToChar = new Uint8Array(64); // 64 possible chars. +const charToInt = new Uint8Array(128); // z is 122 in ASCII + +for (let i = 0; i < chars.length; i++) { + const c = chars.charCodeAt(i); + intToChar[i] = c; + charToInt[c] = i; +} + +export function decodeInteger(reader: StringReader): number { + let value = 0; + let shift = 0; + let integer = 0; + + do { + const c = reader.next(); + integer = charToInt[c]; + value |= (integer & 31) << shift; + shift += 5; + } while (integer & 32); + + return value; +} + +export function decodeSign(num: number): number { + return num & 1 ? -0x80000000 | -(num >>> 1) : num >>> 1; +} + +export function encodeInteger(builder: StringWriter, num: number) { + do { + let clamped = num & 0b011111; + num >>>= 5; + if (num > 0) clamped |= 0b100000; + builder.write(intToChar[clamped]); + } while (num > 0); +} + +export function encodeSign(num: number): number { + return num < 0 ? (-num << 1) | 1 : num << 1; +} + +export function hasMoreVlq(reader: StringReader, max: number) { + if (reader.pos >= max) return false; + return reader.peek() !== comma; +} diff --git a/dg-ui/node_modules/@jridgewell/sourcemap-codec/types/range-mappings.d.cts b/dg-ui/node_modules/@jridgewell/sourcemap-codec/types/range-mappings.d.cts new file mode 100644 index 0000000..8826f64 --- /dev/null +++ b/dg-ui/node_modules/@jridgewell/sourcemap-codec/types/range-mappings.d.cts @@ -0,0 +1,5 @@ +export type MappingIndex = number; +export type RangeMappings = MappingIndex[][]; +export declare function decodeRangeMappings(input: string): RangeMappings; +export declare function encodeRangeMappings(decoded: RangeMappings): string; +//# sourceMappingURL=range-mappings.d.ts.map \ No newline at end of file diff --git a/dg-ui/node_modules/@jridgewell/sourcemap-codec/types/range-mappings.d.cts.map b/dg-ui/node_modules/@jridgewell/sourcemap-codec/types/range-mappings.d.cts.map new file mode 100644 index 0000000..1418bb6 --- /dev/null +++ b/dg-ui/node_modules/@jridgewell/sourcemap-codec/types/range-mappings.d.cts.map @@ -0,0 +1 @@ +{"version":3,"file":"range-mappings.d.ts","sourceRoot":"","sources":["../src/range-mappings.ts"],"names":[],"mappings":"AAGA,MAAM,MAAM,YAAY,GAAG,MAAM,CAAC;AAClC,MAAM,MAAM,aAAa,GAAG,YAAY,EAAE,EAAE,CAAC;AAE7C,wBAAgB,mBAAmB,CAAC,KAAK,EAAE,MAAM,GAAG,aAAa,CAoBhE;AAED,wBAAgB,mBAAmB,CAAC,OAAO,EAAE,aAAa,GAAG,MAAM,CAkBlE"} \ No newline at end of file diff --git a/dg-ui/node_modules/@jridgewell/sourcemap-codec/types/range-mappings.d.mts b/dg-ui/node_modules/@jridgewell/sourcemap-codec/types/range-mappings.d.mts new file mode 100644 index 0000000..8826f64 --- /dev/null +++ b/dg-ui/node_modules/@jridgewell/sourcemap-codec/types/range-mappings.d.mts @@ -0,0 +1,5 @@ +export type MappingIndex = number; +export type RangeMappings = MappingIndex[][]; +export declare function decodeRangeMappings(input: string): RangeMappings; +export declare function encodeRangeMappings(decoded: RangeMappings): string; +//# sourceMappingURL=range-mappings.d.ts.map \ No newline at end of file diff --git a/dg-ui/node_modules/@jridgewell/sourcemap-codec/types/range-mappings.d.mts.map b/dg-ui/node_modules/@jridgewell/sourcemap-codec/types/range-mappings.d.mts.map new file mode 100644 index 0000000..1418bb6 --- /dev/null +++ b/dg-ui/node_modules/@jridgewell/sourcemap-codec/types/range-mappings.d.mts.map @@ -0,0 +1 @@ +{"version":3,"file":"range-mappings.d.ts","sourceRoot":"","sources":["../src/range-mappings.ts"],"names":[],"mappings":"AAGA,MAAM,MAAM,YAAY,GAAG,MAAM,CAAC;AAClC,MAAM,MAAM,aAAa,GAAG,YAAY,EAAE,EAAE,CAAC;AAE7C,wBAAgB,mBAAmB,CAAC,KAAK,EAAE,MAAM,GAAG,aAAa,CAoBhE;AAED,wBAAgB,mBAAmB,CAAC,OAAO,EAAE,aAAa,GAAG,MAAM,CAkBlE"} \ No newline at end of file diff --git a/dg-ui/node_modules/@jridgewell/sourcemap-codec/types/scopes.d.cts b/dg-ui/node_modules/@jridgewell/sourcemap-codec/types/scopes.d.cts new file mode 100644 index 0000000..c583c75 --- /dev/null +++ b/dg-ui/node_modules/@jridgewell/sourcemap-codec/types/scopes.d.cts @@ -0,0 +1,50 @@ +type Line = number; +type Column = number; +type Kind = number; +type Name = number; +type Var = number; +type SourcesIndex = number; +type ScopesIndex = number; +type Mix = (A & O) | (B & O); +export type OriginalScope = Mix<[ + Line, + Column, + Line, + Column, + Kind +], [ + Line, + Column, + Line, + Column, + Kind, + Name +], { + vars: Var[]; +}>; +export type GeneratedRange = Mix<[ + Line, + Column, + Line, + Column +], [ + Line, + Column, + Line, + Column, + SourcesIndex, + ScopesIndex +], { + callsite: CallSite | null; + bindings: Binding[]; + isScope: boolean; +}>; +export type CallSite = [SourcesIndex, Line, Column]; +type Binding = BindingExpressionRange[]; +export type BindingExpressionRange = [Name] | [Name, Line, Column]; +export declare function decodeOriginalScopes(input: string): OriginalScope[]; +export declare function encodeOriginalScopes(scopes: OriginalScope[]): string; +export declare function decodeGeneratedRanges(input: string): GeneratedRange[]; +export declare function encodeGeneratedRanges(ranges: GeneratedRange[]): string; +export {}; +//# sourceMappingURL=scopes.d.ts.map \ No newline at end of file diff --git a/dg-ui/node_modules/@jridgewell/sourcemap-codec/types/scopes.d.cts.map b/dg-ui/node_modules/@jridgewell/sourcemap-codec/types/scopes.d.cts.map new file mode 100644 index 0000000..96f3603 --- /dev/null +++ b/dg-ui/node_modules/@jridgewell/sourcemap-codec/types/scopes.d.cts.map @@ -0,0 +1 @@ +{"version":3,"file":"scopes.d.ts","sourceRoot":"","sources":["../src/scopes.ts"],"names":[],"mappings":"AAaA,KAAK,IAAI,GAAG,MAAM,CAAC;AACnB,KAAK,MAAM,GAAG,MAAM,CAAC;AACrB,KAAK,IAAI,GAAG,MAAM,CAAC;AACnB,KAAK,IAAI,GAAG,MAAM,CAAC;AACnB,KAAK,GAAG,GAAG,MAAM,CAAC;AAClB,KAAK,YAAY,GAAG,MAAM,CAAC;AAC3B,KAAK,WAAW,GAAG,MAAM,CAAC;AAE1B,KAAK,GAAG,CAAC,CAAC,EAAE,CAAC,EAAE,CAAC,IAAI,CAAC,CAAC,GAAG,CAAC,CAAC,GAAG,CAAC,CAAC,GAAG,CAAC,CAAC,CAAC;AAEtC,MAAM,MAAM,aAAa,GAAG,GAAG,CAC7B;IAAC,IAAI;IAAE,MAAM;IAAE,IAAI;IAAE,MAAM;IAAE,IAAI;CAAC,EAClC;IAAC,IAAI;IAAE,MAAM;IAAE,IAAI;IAAE,MAAM;IAAE,IAAI;IAAE,IAAI;CAAC,EACxC;IAAE,IAAI,EAAE,GAAG,EAAE,CAAA;CAAE,CAChB,CAAC;AAEF,MAAM,MAAM,cAAc,GAAG,GAAG,CAC9B;IAAC,IAAI;IAAE,MAAM;IAAE,IAAI;IAAE,MAAM;CAAC,EAC5B;IAAC,IAAI;IAAE,MAAM;IAAE,IAAI;IAAE,MAAM;IAAE,YAAY;IAAE,WAAW;CAAC,EACvD;IACE,QAAQ,EAAE,QAAQ,GAAG,IAAI,CAAC;IAC1B,QAAQ,EAAE,OAAO,EAAE,CAAC;IACpB,OAAO,EAAE,OAAO,CAAC;CAClB,CACF,CAAC;AACF,MAAM,MAAM,QAAQ,GAAG,CAAC,YAAY,EAAE,IAAI,EAAE,MAAM,CAAC,CAAC;AACpD,KAAK,OAAO,GAAG,sBAAsB,EAAE,CAAC;AACxC,MAAM,MAAM,sBAAsB,GAAG,CAAC,IAAI,CAAC,GAAG,CAAC,IAAI,EAAE,IAAI,EAAE,MAAM,CAAC,CAAC;AAEnE,wBAAgB,oBAAoB,CAAC,KAAK,EAAE,MAAM,GAAG,aAAa,EAAE,CA2CnE;AAED,wBAAgB,oBAAoB,CAAC,MAAM,EAAE,aAAa,EAAE,GAAG,MAAM,CAQpE;AA6CD,wBAAgB,qBAAqB,CAAC,KAAK,EAAE,MAAM,GAAG,cAAc,EAAE,CAmGrE;AAED,wBAAgB,qBAAqB,CAAC,MAAM,EAAE,cAAc,EAAE,GAAG,MAAM,CAUtE"} \ No newline at end of file diff --git a/dg-ui/node_modules/@jridgewell/sourcemap-codec/types/scopes.d.mts b/dg-ui/node_modules/@jridgewell/sourcemap-codec/types/scopes.d.mts new file mode 100644 index 0000000..c583c75 --- /dev/null +++ b/dg-ui/node_modules/@jridgewell/sourcemap-codec/types/scopes.d.mts @@ -0,0 +1,50 @@ +type Line = number; +type Column = number; +type Kind = number; +type Name = number; +type Var = number; +type SourcesIndex = number; +type ScopesIndex = number; +type Mix = (A & O) | (B & O); +export type OriginalScope = Mix<[ + Line, + Column, + Line, + Column, + Kind +], [ + Line, + Column, + Line, + Column, + Kind, + Name +], { + vars: Var[]; +}>; +export type GeneratedRange = Mix<[ + Line, + Column, + Line, + Column +], [ + Line, + Column, + Line, + Column, + SourcesIndex, + ScopesIndex +], { + callsite: CallSite | null; + bindings: Binding[]; + isScope: boolean; +}>; +export type CallSite = [SourcesIndex, Line, Column]; +type Binding = BindingExpressionRange[]; +export type BindingExpressionRange = [Name] | [Name, Line, Column]; +export declare function decodeOriginalScopes(input: string): OriginalScope[]; +export declare function encodeOriginalScopes(scopes: OriginalScope[]): string; +export declare function decodeGeneratedRanges(input: string): GeneratedRange[]; +export declare function encodeGeneratedRanges(ranges: GeneratedRange[]): string; +export {}; +//# sourceMappingURL=scopes.d.ts.map \ No newline at end of file diff --git a/dg-ui/node_modules/@jridgewell/sourcemap-codec/types/scopes.d.mts.map b/dg-ui/node_modules/@jridgewell/sourcemap-codec/types/scopes.d.mts.map new file mode 100644 index 0000000..96f3603 --- /dev/null +++ b/dg-ui/node_modules/@jridgewell/sourcemap-codec/types/scopes.d.mts.map @@ -0,0 +1 @@ +{"version":3,"file":"scopes.d.ts","sourceRoot":"","sources":["../src/scopes.ts"],"names":[],"mappings":"AAaA,KAAK,IAAI,GAAG,MAAM,CAAC;AACnB,KAAK,MAAM,GAAG,MAAM,CAAC;AACrB,KAAK,IAAI,GAAG,MAAM,CAAC;AACnB,KAAK,IAAI,GAAG,MAAM,CAAC;AACnB,KAAK,GAAG,GAAG,MAAM,CAAC;AAClB,KAAK,YAAY,GAAG,MAAM,CAAC;AAC3B,KAAK,WAAW,GAAG,MAAM,CAAC;AAE1B,KAAK,GAAG,CAAC,CAAC,EAAE,CAAC,EAAE,CAAC,IAAI,CAAC,CAAC,GAAG,CAAC,CAAC,GAAG,CAAC,CAAC,GAAG,CAAC,CAAC,CAAC;AAEtC,MAAM,MAAM,aAAa,GAAG,GAAG,CAC7B;IAAC,IAAI;IAAE,MAAM;IAAE,IAAI;IAAE,MAAM;IAAE,IAAI;CAAC,EAClC;IAAC,IAAI;IAAE,MAAM;IAAE,IAAI;IAAE,MAAM;IAAE,IAAI;IAAE,IAAI;CAAC,EACxC;IAAE,IAAI,EAAE,GAAG,EAAE,CAAA;CAAE,CAChB,CAAC;AAEF,MAAM,MAAM,cAAc,GAAG,GAAG,CAC9B;IAAC,IAAI;IAAE,MAAM;IAAE,IAAI;IAAE,MAAM;CAAC,EAC5B;IAAC,IAAI;IAAE,MAAM;IAAE,IAAI;IAAE,MAAM;IAAE,YAAY;IAAE,WAAW;CAAC,EACvD;IACE,QAAQ,EAAE,QAAQ,GAAG,IAAI,CAAC;IAC1B,QAAQ,EAAE,OAAO,EAAE,CAAC;IACpB,OAAO,EAAE,OAAO,CAAC;CAClB,CACF,CAAC;AACF,MAAM,MAAM,QAAQ,GAAG,CAAC,YAAY,EAAE,IAAI,EAAE,MAAM,CAAC,CAAC;AACpD,KAAK,OAAO,GAAG,sBAAsB,EAAE,CAAC;AACxC,MAAM,MAAM,sBAAsB,GAAG,CAAC,IAAI,CAAC,GAAG,CAAC,IAAI,EAAE,IAAI,EAAE,MAAM,CAAC,CAAC;AAEnE,wBAAgB,oBAAoB,CAAC,KAAK,EAAE,MAAM,GAAG,aAAa,EAAE,CA2CnE;AAED,wBAAgB,oBAAoB,CAAC,MAAM,EAAE,aAAa,EAAE,GAAG,MAAM,CAQpE;AA6CD,wBAAgB,qBAAqB,CAAC,KAAK,EAAE,MAAM,GAAG,cAAc,EAAE,CAmGrE;AAED,wBAAgB,qBAAqB,CAAC,MAAM,EAAE,cAAc,EAAE,GAAG,MAAM,CAUtE"} \ No newline at end of file diff --git a/dg-ui/node_modules/@jridgewell/sourcemap-codec/types/sourcemap-codec.d.cts b/dg-ui/node_modules/@jridgewell/sourcemap-codec/types/sourcemap-codec.d.cts new file mode 100644 index 0000000..2fdeab8 --- /dev/null +++ b/dg-ui/node_modules/@jridgewell/sourcemap-codec/types/sourcemap-codec.d.cts @@ -0,0 +1,11 @@ +export { decodeOriginalScopes, encodeOriginalScopes, decodeGeneratedRanges, encodeGeneratedRanges, } from './scopes.cts'; +export type { OriginalScope, GeneratedRange, CallSite, BindingExpressionRange } from './scopes.cts'; +export { decodeRangeMappings, encodeRangeMappings } from './range-mappings.cts'; +export type { MappingIndex, RangeMappings } from './range-mappings.cts'; +export type SourceMapSegment = [number] | [number, number, number, number] | [number, number, number, number, number]; +export type SourceMapLine = SourceMapSegment[]; +export type SourceMapMappings = SourceMapLine[]; +export declare function decode(mappings: string): SourceMapMappings; +export declare function encode(decoded: SourceMapMappings): string; +export declare function encode(decoded: Readonly): string; +//# sourceMappingURL=sourcemap-codec.d.ts.map \ No newline at end of file diff --git a/dg-ui/node_modules/@jridgewell/sourcemap-codec/types/sourcemap-codec.d.cts.map b/dg-ui/node_modules/@jridgewell/sourcemap-codec/types/sourcemap-codec.d.cts.map new file mode 100644 index 0000000..e0d67e3 --- /dev/null +++ b/dg-ui/node_modules/@jridgewell/sourcemap-codec/types/sourcemap-codec.d.cts.map @@ -0,0 +1 @@ +{"version":3,"file":"sourcemap-codec.d.ts","sourceRoot":"","sources":["../src/sourcemap-codec.ts"],"names":[],"mappings":"AAWA,OAAO,EACL,oBAAoB,EACpB,oBAAoB,EACpB,qBAAqB,EACrB,qBAAqB,GACtB,MAAM,UAAU,CAAC;AAClB,YAAY,EAAE,aAAa,EAAE,cAAc,EAAE,QAAQ,EAAE,sBAAsB,EAAE,MAAM,UAAU,CAAC;AAEhG,OAAO,EAAE,mBAAmB,EAAE,mBAAmB,EAAE,MAAM,kBAAkB,CAAC;AAC5E,YAAY,EAAE,YAAY,EAAE,aAAa,EAAE,MAAM,kBAAkB,CAAC;AAEpE,MAAM,MAAM,gBAAgB,GACxB,CAAC,MAAM,CAAC,GACR,CAAC,MAAM,EAAE,MAAM,EAAE,MAAM,EAAE,MAAM,CAAC,GAChC,CAAC,MAAM,EAAE,MAAM,EAAE,MAAM,EAAE,MAAM,EAAE,MAAM,CAAC,CAAC;AAC7C,MAAM,MAAM,aAAa,GAAG,gBAAgB,EAAE,CAAC;AAC/C,MAAM,MAAM,iBAAiB,GAAG,aAAa,EAAE,CAAC;AAEhD,wBAAgB,MAAM,CAAC,QAAQ,EAAE,MAAM,GAAG,iBAAiB,CAiD1D;AAUD,wBAAgB,MAAM,CAAC,OAAO,EAAE,iBAAiB,GAAG,MAAM,CAAC;AAC3D,wBAAgB,MAAM,CAAC,OAAO,EAAE,QAAQ,CAAC,iBAAiB,CAAC,GAAG,MAAM,CAAC"} \ No newline at end of file diff --git a/dg-ui/node_modules/@jridgewell/sourcemap-codec/types/sourcemap-codec.d.mts b/dg-ui/node_modules/@jridgewell/sourcemap-codec/types/sourcemap-codec.d.mts new file mode 100644 index 0000000..2f0e519 --- /dev/null +++ b/dg-ui/node_modules/@jridgewell/sourcemap-codec/types/sourcemap-codec.d.mts @@ -0,0 +1,11 @@ +export { decodeOriginalScopes, encodeOriginalScopes, decodeGeneratedRanges, encodeGeneratedRanges, } from './scopes.mts'; +export type { OriginalScope, GeneratedRange, CallSite, BindingExpressionRange } from './scopes.mts'; +export { decodeRangeMappings, encodeRangeMappings } from './range-mappings.mts'; +export type { MappingIndex, RangeMappings } from './range-mappings.mts'; +export type SourceMapSegment = [number] | [number, number, number, number] | [number, number, number, number, number]; +export type SourceMapLine = SourceMapSegment[]; +export type SourceMapMappings = SourceMapLine[]; +export declare function decode(mappings: string): SourceMapMappings; +export declare function encode(decoded: SourceMapMappings): string; +export declare function encode(decoded: Readonly): string; +//# sourceMappingURL=sourcemap-codec.d.ts.map \ No newline at end of file diff --git a/dg-ui/node_modules/@jridgewell/sourcemap-codec/types/sourcemap-codec.d.mts.map b/dg-ui/node_modules/@jridgewell/sourcemap-codec/types/sourcemap-codec.d.mts.map new file mode 100644 index 0000000..e0d67e3 --- /dev/null +++ b/dg-ui/node_modules/@jridgewell/sourcemap-codec/types/sourcemap-codec.d.mts.map @@ -0,0 +1 @@ +{"version":3,"file":"sourcemap-codec.d.ts","sourceRoot":"","sources":["../src/sourcemap-codec.ts"],"names":[],"mappings":"AAWA,OAAO,EACL,oBAAoB,EACpB,oBAAoB,EACpB,qBAAqB,EACrB,qBAAqB,GACtB,MAAM,UAAU,CAAC;AAClB,YAAY,EAAE,aAAa,EAAE,cAAc,EAAE,QAAQ,EAAE,sBAAsB,EAAE,MAAM,UAAU,CAAC;AAEhG,OAAO,EAAE,mBAAmB,EAAE,mBAAmB,EAAE,MAAM,kBAAkB,CAAC;AAC5E,YAAY,EAAE,YAAY,EAAE,aAAa,EAAE,MAAM,kBAAkB,CAAC;AAEpE,MAAM,MAAM,gBAAgB,GACxB,CAAC,MAAM,CAAC,GACR,CAAC,MAAM,EAAE,MAAM,EAAE,MAAM,EAAE,MAAM,CAAC,GAChC,CAAC,MAAM,EAAE,MAAM,EAAE,MAAM,EAAE,MAAM,EAAE,MAAM,CAAC,CAAC;AAC7C,MAAM,MAAM,aAAa,GAAG,gBAAgB,EAAE,CAAC;AAC/C,MAAM,MAAM,iBAAiB,GAAG,aAAa,EAAE,CAAC;AAEhD,wBAAgB,MAAM,CAAC,QAAQ,EAAE,MAAM,GAAG,iBAAiB,CAiD1D;AAUD,wBAAgB,MAAM,CAAC,OAAO,EAAE,iBAAiB,GAAG,MAAM,CAAC;AAC3D,wBAAgB,MAAM,CAAC,OAAO,EAAE,QAAQ,CAAC,iBAAiB,CAAC,GAAG,MAAM,CAAC"} \ No newline at end of file diff --git a/dg-ui/node_modules/@jridgewell/sourcemap-codec/types/strings.d.cts b/dg-ui/node_modules/@jridgewell/sourcemap-codec/types/strings.d.cts new file mode 100644 index 0000000..62faceb --- /dev/null +++ b/dg-ui/node_modules/@jridgewell/sourcemap-codec/types/strings.d.cts @@ -0,0 +1,16 @@ +export declare class StringWriter { + pos: number; + private out; + private buffer; + write(v: number): void; + flush(): string; +} +export declare class StringReader { + pos: number; + private buffer; + constructor(buffer: string); + next(): number; + peek(): number; + indexOf(char: string): number; +} +//# sourceMappingURL=strings.d.ts.map \ No newline at end of file diff --git a/dg-ui/node_modules/@jridgewell/sourcemap-codec/types/strings.d.cts.map b/dg-ui/node_modules/@jridgewell/sourcemap-codec/types/strings.d.cts.map new file mode 100644 index 0000000..d3602da --- /dev/null +++ b/dg-ui/node_modules/@jridgewell/sourcemap-codec/types/strings.d.cts.map @@ -0,0 +1 @@ +{"version":3,"file":"strings.d.ts","sourceRoot":"","sources":["../src/strings.ts"],"names":[],"mappings":"AAuBA,qBAAa,YAAY;IACvB,GAAG,SAAK;IACR,OAAO,CAAC,GAAG,CAAM;IACjB,OAAO,CAAC,MAAM,CAA6B;IAE3C,KAAK,CAAC,CAAC,EAAE,MAAM,GAAG,IAAI;IAStB,KAAK,IAAI,MAAM;CAIhB;AAED,qBAAa,YAAY;IACvB,GAAG,SAAK;IACR,QAAgB,MAAM,CAAS;gBAEnB,MAAM,EAAE,MAAM;IAI1B,IAAI,IAAI,MAAM;IAId,IAAI,IAAI,MAAM;IAId,OAAO,CAAC,IAAI,EAAE,MAAM,GAAG,MAAM;CAK9B"} \ No newline at end of file diff --git a/dg-ui/node_modules/@jridgewell/sourcemap-codec/types/strings.d.mts b/dg-ui/node_modules/@jridgewell/sourcemap-codec/types/strings.d.mts new file mode 100644 index 0000000..62faceb --- /dev/null +++ b/dg-ui/node_modules/@jridgewell/sourcemap-codec/types/strings.d.mts @@ -0,0 +1,16 @@ +export declare class StringWriter { + pos: number; + private out; + private buffer; + write(v: number): void; + flush(): string; +} +export declare class StringReader { + pos: number; + private buffer; + constructor(buffer: string); + next(): number; + peek(): number; + indexOf(char: string): number; +} +//# sourceMappingURL=strings.d.ts.map \ No newline at end of file diff --git a/dg-ui/node_modules/@jridgewell/sourcemap-codec/types/strings.d.mts.map b/dg-ui/node_modules/@jridgewell/sourcemap-codec/types/strings.d.mts.map new file mode 100644 index 0000000..d3602da --- /dev/null +++ b/dg-ui/node_modules/@jridgewell/sourcemap-codec/types/strings.d.mts.map @@ -0,0 +1 @@ +{"version":3,"file":"strings.d.ts","sourceRoot":"","sources":["../src/strings.ts"],"names":[],"mappings":"AAuBA,qBAAa,YAAY;IACvB,GAAG,SAAK;IACR,OAAO,CAAC,GAAG,CAAM;IACjB,OAAO,CAAC,MAAM,CAA6B;IAE3C,KAAK,CAAC,CAAC,EAAE,MAAM,GAAG,IAAI;IAStB,KAAK,IAAI,MAAM;CAIhB;AAED,qBAAa,YAAY;IACvB,GAAG,SAAK;IACR,QAAgB,MAAM,CAAS;gBAEnB,MAAM,EAAE,MAAM;IAI1B,IAAI,IAAI,MAAM;IAId,IAAI,IAAI,MAAM;IAId,OAAO,CAAC,IAAI,EAAE,MAAM,GAAG,MAAM;CAK9B"} \ No newline at end of file diff --git a/dg-ui/node_modules/@jridgewell/sourcemap-codec/types/vlq.d.cts b/dg-ui/node_modules/@jridgewell/sourcemap-codec/types/vlq.d.cts new file mode 100644 index 0000000..b2ba433 --- /dev/null +++ b/dg-ui/node_modules/@jridgewell/sourcemap-codec/types/vlq.d.cts @@ -0,0 +1,9 @@ +import type { StringReader, StringWriter } from './strings.cts'; +export declare const comma: number; +export declare const semicolon: number; +export declare function decodeInteger(reader: StringReader): number; +export declare function decodeSign(num: number): number; +export declare function encodeInteger(builder: StringWriter, num: number): void; +export declare function encodeSign(num: number): number; +export declare function hasMoreVlq(reader: StringReader, max: number): boolean; +//# sourceMappingURL=vlq.d.ts.map \ No newline at end of file diff --git a/dg-ui/node_modules/@jridgewell/sourcemap-codec/types/vlq.d.cts.map b/dg-ui/node_modules/@jridgewell/sourcemap-codec/types/vlq.d.cts.map new file mode 100644 index 0000000..b9dd843 --- /dev/null +++ b/dg-ui/node_modules/@jridgewell/sourcemap-codec/types/vlq.d.cts.map @@ -0,0 +1 @@ +{"version":3,"file":"vlq.d.ts","sourceRoot":"","sources":["../src/vlq.ts"],"names":[],"mappings":"AAAA,OAAO,KAAK,EAAE,YAAY,EAAE,YAAY,EAAE,MAAM,WAAW,CAAC;AAE5D,eAAO,MAAM,KAAK,QAAoB,CAAC;AACvC,eAAO,MAAM,SAAS,QAAoB,CAAC;AAY3C,wBAAgB,aAAa,CAAC,MAAM,EAAE,YAAY,GAAG,MAAM,CAa1D;AAED,wBAAgB,UAAU,CAAC,GAAG,EAAE,MAAM,GAAG,MAAM,CAE9C;AAED,wBAAgB,aAAa,CAAC,OAAO,EAAE,YAAY,EAAE,GAAG,EAAE,MAAM,QAO/D;AAED,wBAAgB,UAAU,CAAC,GAAG,EAAE,MAAM,GAAG,MAAM,CAE9C;AAED,wBAAgB,UAAU,CAAC,MAAM,EAAE,YAAY,EAAE,GAAG,EAAE,MAAM,WAG3D"} \ No newline at end of file diff --git a/dg-ui/node_modules/@jridgewell/sourcemap-codec/types/vlq.d.mts b/dg-ui/node_modules/@jridgewell/sourcemap-codec/types/vlq.d.mts new file mode 100644 index 0000000..30bdc61 --- /dev/null +++ b/dg-ui/node_modules/@jridgewell/sourcemap-codec/types/vlq.d.mts @@ -0,0 +1,9 @@ +import type { StringReader, StringWriter } from './strings.mts'; +export declare const comma: number; +export declare const semicolon: number; +export declare function decodeInteger(reader: StringReader): number; +export declare function decodeSign(num: number): number; +export declare function encodeInteger(builder: StringWriter, num: number): void; +export declare function encodeSign(num: number): number; +export declare function hasMoreVlq(reader: StringReader, max: number): boolean; +//# sourceMappingURL=vlq.d.ts.map \ No newline at end of file diff --git a/dg-ui/node_modules/@jridgewell/sourcemap-codec/types/vlq.d.mts.map b/dg-ui/node_modules/@jridgewell/sourcemap-codec/types/vlq.d.mts.map new file mode 100644 index 0000000..b9dd843 --- /dev/null +++ b/dg-ui/node_modules/@jridgewell/sourcemap-codec/types/vlq.d.mts.map @@ -0,0 +1 @@ +{"version":3,"file":"vlq.d.ts","sourceRoot":"","sources":["../src/vlq.ts"],"names":[],"mappings":"AAAA,OAAO,KAAK,EAAE,YAAY,EAAE,YAAY,EAAE,MAAM,WAAW,CAAC;AAE5D,eAAO,MAAM,KAAK,QAAoB,CAAC;AACvC,eAAO,MAAM,SAAS,QAAoB,CAAC;AAY3C,wBAAgB,aAAa,CAAC,MAAM,EAAE,YAAY,GAAG,MAAM,CAa1D;AAED,wBAAgB,UAAU,CAAC,GAAG,EAAE,MAAM,GAAG,MAAM,CAE9C;AAED,wBAAgB,aAAa,CAAC,OAAO,EAAE,YAAY,EAAE,GAAG,EAAE,MAAM,QAO/D;AAED,wBAAgB,UAAU,CAAC,GAAG,EAAE,MAAM,GAAG,MAAM,CAE9C;AAED,wBAAgB,UAAU,CAAC,MAAM,EAAE,YAAY,EAAE,GAAG,EAAE,MAAM,WAG3D"} \ No newline at end of file diff --git a/dg-ui/node_modules/@jridgewell/trace-mapping/LICENSE b/dg-ui/node_modules/@jridgewell/trace-mapping/LICENSE new file mode 100644 index 0000000..1f6ce94 --- /dev/null +++ b/dg-ui/node_modules/@jridgewell/trace-mapping/LICENSE @@ -0,0 +1,19 @@ +Copyright 2024 Justin Ridgewell + +Permission is hereby granted, free of charge, to any person obtaining a copy +of this software and associated documentation files (the "Software"), to deal +in the Software without restriction, including without limitation the rights +to use, copy, modify, merge, publish, distribute, sublicense, and/or sell +copies of the Software, and to permit persons to whom the Software is +furnished to do so, subject to the following conditions: + +The above copyright notice and this permission notice shall be included in +all copies or substantial portions of the Software. + +THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR +IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, +FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE +AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER +LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, +OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE +SOFTWARE. diff --git a/dg-ui/node_modules/@jridgewell/trace-mapping/README.md b/dg-ui/node_modules/@jridgewell/trace-mapping/README.md new file mode 100644 index 0000000..9fc0ed0 --- /dev/null +++ b/dg-ui/node_modules/@jridgewell/trace-mapping/README.md @@ -0,0 +1,348 @@ +# @jridgewell/trace-mapping + +> Trace the original position through a source map + +`trace-mapping` allows you to take the line and column of an output file and trace it to the +original location in the source file through a source map. + +You may already be familiar with the [`source-map`][source-map] package's `SourceMapConsumer`. This +provides the same `originalPositionFor` and `generatedPositionFor` API, without requiring WASM. + +## Installation + +```sh +npm install @jridgewell/trace-mapping +``` + +## Usage + +```typescript +import { + TraceMap, + originalPositionFor, + generatedPositionFor, + sourceContentFor, + isIgnored, +} from '@jridgewell/trace-mapping'; + +const tracer = new TraceMap({ + version: 3, + sources: ['input.js'], + sourcesContent: ['content of input.js'], + names: ['foo'], + mappings: 'KAyCIA', + ignoreList: [], +}); + +// Lines start at line 1, columns at column 0. +const traced = originalPositionFor(tracer, { line: 1, column: 5 }); +assert.deepEqual(traced, { + source: 'input.js', + line: 42, + column: 4, + name: 'foo', +}); + +const content = sourceContentFor(tracer, traced.source); +assert.strictEqual(content, 'content for input.js'); + +const generated = generatedPositionFor(tracer, { + source: 'input.js', + line: 42, + column: 4, +}); +assert.deepEqual(generated, { + line: 1, + column: 5, +}); + +const ignored = isIgnored(tracer, 'input.js'); +assert.equal(ignored, false); +``` + +We also provide a lower level API to get the actual segment that matches our line and column. Unlike +`originalPositionFor`, `traceSegment` uses a 0-base for `line`: + +```typescript +import { traceSegment } from '@jridgewell/trace-mapping'; + +// line is 0-base. +const traced = traceSegment(tracer, /* line */ 0, /* column */ 5); + +// Segments are [outputColumn, sourcesIndex, sourceLine, sourceColumn, namesIndex] +// Again, line is 0-base and so is sourceLine +assert.deepEqual(traced, [5, 0, 41, 4, 0]); +``` + +### SectionedSourceMaps + +The sourcemap spec defines a special `sections` field that's designed to handle concatenation of +output code with associated sourcemaps. This type of sourcemap is rarely used (no major build tool +produces it), but if you are hand coding a concatenation you may need it. We provide an `AnyMap` +helper that can receive either a regular sourcemap or a `SectionedSourceMap` and returns a +`TraceMap` instance: + +```typescript +import { AnyMap } from '@jridgewell/trace-mapping'; +const fooOutput = 'foo'; +const barOutput = 'bar'; +const output = [fooOutput, barOutput].join('\n'); + +const sectioned = new AnyMap({ + version: 3, + sections: [ + { + // 0-base line and column + offset: { line: 0, column: 0 }, + // fooOutput's sourcemap + map: { + version: 3, + sources: ['foo.js'], + names: ['foo'], + mappings: 'AAAAA', + }, + }, + { + // barOutput's sourcemap will not affect the first line, only the second + offset: { line: 1, column: 0 }, + map: { + version: 3, + sources: ['bar.js'], + names: ['bar'], + mappings: 'AAAAA', + }, + }, + ], +}); + +const traced = originalPositionFor(sectioned, { + line: 2, + column: 0, +}); + +assert.deepEqual(traced, { + source: 'bar.js', + line: 1, + column: 0, + name: 'bar', +}); +``` + +## Benchmarks + +``` +node v20.10.0 + +amp.js.map - 45120 segments + +Memory Usage: +trace-mapping decoded 414164 bytes +trace-mapping encoded 6274352 bytes +source-map-js 10968904 bytes +source-map-0.6.1 17587160 bytes +source-map-0.8.0 8812155 bytes +Chrome dev tools 8672912 bytes +Smallest memory usage is trace-mapping decoded + +Init speed: +trace-mapping: decoded JSON input x 205 ops/sec ±0.19% (88 runs sampled) +trace-mapping: encoded JSON input x 405 ops/sec ±1.47% (88 runs sampled) +trace-mapping: decoded Object input x 4,645 ops/sec ±0.15% (98 runs sampled) +trace-mapping: encoded Object input x 458 ops/sec ±1.63% (91 runs sampled) +source-map-js: encoded Object input x 75.48 ops/sec ±1.64% (67 runs sampled) +source-map-0.6.1: encoded Object input x 39.37 ops/sec ±1.44% (53 runs sampled) +Chrome dev tools: encoded Object input x 150 ops/sec ±1.76% (79 runs sampled) +Fastest is trace-mapping: decoded Object input + +Trace speed (random): +trace-mapping: decoded originalPositionFor x 44,946 ops/sec ±0.16% (99 runs sampled) +trace-mapping: encoded originalPositionFor x 37,995 ops/sec ±1.81% (89 runs sampled) +source-map-js: encoded originalPositionFor x 9,230 ops/sec ±1.36% (93 runs sampled) +source-map-0.6.1: encoded originalPositionFor x 8,057 ops/sec ±0.84% (96 runs sampled) +source-map-0.8.0: encoded originalPositionFor x 28,198 ops/sec ±1.12% (91 runs sampled) +Chrome dev tools: encoded originalPositionFor x 46,276 ops/sec ±1.35% (95 runs sampled) +Fastest is Chrome dev tools: encoded originalPositionFor + +Trace speed (ascending): +trace-mapping: decoded originalPositionFor x 204,406 ops/sec ±0.19% (97 runs sampled) +trace-mapping: encoded originalPositionFor x 196,695 ops/sec ±0.24% (99 runs sampled) +source-map-js: encoded originalPositionFor x 11,948 ops/sec ±0.94% (99 runs sampled) +source-map-0.6.1: encoded originalPositionFor x 10,730 ops/sec ±0.36% (100 runs sampled) +source-map-0.8.0: encoded originalPositionFor x 51,427 ops/sec ±0.21% (98 runs sampled) +Chrome dev tools: encoded originalPositionFor x 162,615 ops/sec ±0.18% (98 runs sampled) +Fastest is trace-mapping: decoded originalPositionFor + + +*** + + +babel.min.js.map - 347793 segments + +Memory Usage: +trace-mapping decoded 18504 bytes +trace-mapping encoded 35428008 bytes +source-map-js 51676808 bytes +source-map-0.6.1 63367136 bytes +source-map-0.8.0 43158400 bytes +Chrome dev tools 50721552 bytes +Smallest memory usage is trace-mapping decoded + +Init speed: +trace-mapping: decoded JSON input x 17.82 ops/sec ±6.35% (35 runs sampled) +trace-mapping: encoded JSON input x 31.57 ops/sec ±7.50% (43 runs sampled) +trace-mapping: decoded Object input x 867 ops/sec ±0.74% (94 runs sampled) +trace-mapping: encoded Object input x 33.83 ops/sec ±7.66% (46 runs sampled) +source-map-js: encoded Object input x 6.58 ops/sec ±3.31% (20 runs sampled) +source-map-0.6.1: encoded Object input x 4.23 ops/sec ±3.43% (15 runs sampled) +Chrome dev tools: encoded Object input x 22.14 ops/sec ±3.79% (41 runs sampled) +Fastest is trace-mapping: decoded Object input + +Trace speed (random): +trace-mapping: decoded originalPositionFor x 78,234 ops/sec ±1.48% (29 runs sampled) +trace-mapping: encoded originalPositionFor x 60,761 ops/sec ±1.35% (21 runs sampled) +source-map-js: encoded originalPositionFor x 51,448 ops/sec ±2.17% (89 runs sampled) +source-map-0.6.1: encoded originalPositionFor x 47,221 ops/sec ±1.99% (15 runs sampled) +source-map-0.8.0: encoded originalPositionFor x 84,002 ops/sec ±1.45% (27 runs sampled) +Chrome dev tools: encoded originalPositionFor x 106,457 ops/sec ±1.38% (37 runs sampled) +Fastest is Chrome dev tools: encoded originalPositionFor + +Trace speed (ascending): +trace-mapping: decoded originalPositionFor x 930,943 ops/sec ±0.25% (99 runs sampled) +trace-mapping: encoded originalPositionFor x 843,545 ops/sec ±0.34% (97 runs sampled) +source-map-js: encoded originalPositionFor x 114,510 ops/sec ±1.37% (36 runs sampled) +source-map-0.6.1: encoded originalPositionFor x 87,412 ops/sec ±0.72% (92 runs sampled) +source-map-0.8.0: encoded originalPositionFor x 197,709 ops/sec ±0.89% (59 runs sampled) +Chrome dev tools: encoded originalPositionFor x 688,983 ops/sec ±0.33% (98 runs sampled) +Fastest is trace-mapping: decoded originalPositionFor + + +*** + + +preact.js.map - 1992 segments + +Memory Usage: +trace-mapping decoded 33136 bytes +trace-mapping encoded 254240 bytes +source-map-js 837488 bytes +source-map-0.6.1 961928 bytes +source-map-0.8.0 54384 bytes +Chrome dev tools 709680 bytes +Smallest memory usage is trace-mapping decoded + +Init speed: +trace-mapping: decoded JSON input x 3,709 ops/sec ±0.13% (99 runs sampled) +trace-mapping: encoded JSON input x 6,447 ops/sec ±0.22% (101 runs sampled) +trace-mapping: decoded Object input x 83,062 ops/sec ±0.23% (100 runs sampled) +trace-mapping: encoded Object input x 14,980 ops/sec ±0.28% (100 runs sampled) +source-map-js: encoded Object input x 2,544 ops/sec ±0.16% (99 runs sampled) +source-map-0.6.1: encoded Object input x 1,221 ops/sec ±0.37% (97 runs sampled) +Chrome dev tools: encoded Object input x 4,241 ops/sec ±0.39% (93 runs sampled) +Fastest is trace-mapping: decoded Object input + +Trace speed (random): +trace-mapping: decoded originalPositionFor x 91,028 ops/sec ±0.14% (94 runs sampled) +trace-mapping: encoded originalPositionFor x 84,348 ops/sec ±0.26% (98 runs sampled) +source-map-js: encoded originalPositionFor x 26,998 ops/sec ±0.23% (98 runs sampled) +source-map-0.6.1: encoded originalPositionFor x 18,049 ops/sec ±0.26% (100 runs sampled) +source-map-0.8.0: encoded originalPositionFor x 41,916 ops/sec ±0.28% (98 runs sampled) +Chrome dev tools: encoded originalPositionFor x 88,616 ops/sec ±0.14% (98 runs sampled) +Fastest is trace-mapping: decoded originalPositionFor + +Trace speed (ascending): +trace-mapping: decoded originalPositionFor x 319,960 ops/sec ±0.16% (100 runs sampled) +trace-mapping: encoded originalPositionFor x 302,153 ops/sec ±0.18% (100 runs sampled) +source-map-js: encoded originalPositionFor x 35,574 ops/sec ±0.19% (100 runs sampled) +source-map-0.6.1: encoded originalPositionFor x 19,943 ops/sec ±0.12% (101 runs sampled) +source-map-0.8.0: encoded originalPositionFor x 54,648 ops/sec ±0.20% (99 runs sampled) +Chrome dev tools: encoded originalPositionFor x 278,319 ops/sec ±0.17% (102 runs sampled) +Fastest is trace-mapping: decoded originalPositionFor + + +*** + + +react.js.map - 5726 segments + +Memory Usage: +trace-mapping decoded 10872 bytes +trace-mapping encoded 681512 bytes +source-map-js 2563944 bytes +source-map-0.6.1 2150864 bytes +source-map-0.8.0 88680 bytes +Chrome dev tools 1149576 bytes +Smallest memory usage is trace-mapping decoded + +Init speed: +trace-mapping: decoded JSON input x 1,887 ops/sec ±0.28% (99 runs sampled) +trace-mapping: encoded JSON input x 4,749 ops/sec ±0.48% (97 runs sampled) +trace-mapping: decoded Object input x 74,236 ops/sec ±0.11% (99 runs sampled) +trace-mapping: encoded Object input x 5,752 ops/sec ±0.38% (100 runs sampled) +source-map-js: encoded Object input x 806 ops/sec ±0.19% (97 runs sampled) +source-map-0.6.1: encoded Object input x 418 ops/sec ±0.33% (94 runs sampled) +Chrome dev tools: encoded Object input x 1,524 ops/sec ±0.57% (92 runs sampled) +Fastest is trace-mapping: decoded Object input + +Trace speed (random): +trace-mapping: decoded originalPositionFor x 620,201 ops/sec ±0.33% (96 runs sampled) +trace-mapping: encoded originalPositionFor x 579,548 ops/sec ±0.35% (97 runs sampled) +source-map-js: encoded originalPositionFor x 230,983 ops/sec ±0.62% (54 runs sampled) +source-map-0.6.1: encoded originalPositionFor x 158,145 ops/sec ±0.80% (46 runs sampled) +source-map-0.8.0: encoded originalPositionFor x 343,801 ops/sec ±0.55% (96 runs sampled) +Chrome dev tools: encoded originalPositionFor x 659,649 ops/sec ±0.49% (98 runs sampled) +Fastest is Chrome dev tools: encoded originalPositionFor + +Trace speed (ascending): +trace-mapping: decoded originalPositionFor x 2,368,079 ops/sec ±0.32% (98 runs sampled) +trace-mapping: encoded originalPositionFor x 2,134,039 ops/sec ±2.72% (87 runs sampled) +source-map-js: encoded originalPositionFor x 290,120 ops/sec ±2.49% (82 runs sampled) +source-map-0.6.1: encoded originalPositionFor x 187,613 ops/sec ±0.86% (49 runs sampled) +source-map-0.8.0: encoded originalPositionFor x 479,569 ops/sec ±0.65% (96 runs sampled) +Chrome dev tools: encoded originalPositionFor x 2,048,414 ops/sec ±0.24% (98 runs sampled) +Fastest is trace-mapping: decoded originalPositionFor + + +*** + + +vscode.map - 2141001 segments + +Memory Usage: +trace-mapping decoded 5206584 bytes +trace-mapping encoded 208370336 bytes +source-map-js 278493008 bytes +source-map-0.6.1 391564048 bytes +source-map-0.8.0 257508787 bytes +Chrome dev tools 291053000 bytes +Smallest memory usage is trace-mapping decoded + +Init speed: +trace-mapping: decoded JSON input x 1.63 ops/sec ±33.88% (9 runs sampled) +trace-mapping: encoded JSON input x 3.29 ops/sec ±36.13% (13 runs sampled) +trace-mapping: decoded Object input x 103 ops/sec ±0.93% (77 runs sampled) +trace-mapping: encoded Object input x 5.42 ops/sec ±28.54% (19 runs sampled) +source-map-js: encoded Object input x 1.07 ops/sec ±13.84% (7 runs sampled) +source-map-0.6.1: encoded Object input x 0.60 ops/sec ±2.43% (6 runs sampled) +Chrome dev tools: encoded Object input x 2.61 ops/sec ±22.00% (11 runs sampled) +Fastest is trace-mapping: decoded Object input + +Trace speed (random): +trace-mapping: decoded originalPositionFor x 257,019 ops/sec ±0.97% (93 runs sampled) +trace-mapping: encoded originalPositionFor x 179,163 ops/sec ±0.83% (92 runs sampled) +source-map-js: encoded originalPositionFor x 73,337 ops/sec ±1.35% (87 runs sampled) +source-map-0.6.1: encoded originalPositionFor x 38,797 ops/sec ±1.66% (88 runs sampled) +source-map-0.8.0: encoded originalPositionFor x 107,758 ops/sec ±1.94% (45 runs sampled) +Chrome dev tools: encoded originalPositionFor x 188,550 ops/sec ±1.85% (79 runs sampled) +Fastest is trace-mapping: decoded originalPositionFor + +Trace speed (ascending): +trace-mapping: decoded originalPositionFor x 447,621 ops/sec ±3.64% (94 runs sampled) +trace-mapping: encoded originalPositionFor x 323,698 ops/sec ±5.20% (88 runs sampled) +source-map-js: encoded originalPositionFor x 78,387 ops/sec ±1.69% (89 runs sampled) +source-map-0.6.1: encoded originalPositionFor x 41,016 ops/sec ±3.01% (25 runs sampled) +source-map-0.8.0: encoded originalPositionFor x 124,204 ops/sec ±0.90% (92 runs sampled) +Chrome dev tools: encoded originalPositionFor x 230,087 ops/sec ±2.61% (93 runs sampled) +Fastest is trace-mapping: decoded originalPositionFor +``` + +[source-map]: https://www.npmjs.com/package/source-map diff --git a/dg-ui/node_modules/@jridgewell/trace-mapping/dist/trace-mapping.mjs b/dg-ui/node_modules/@jridgewell/trace-mapping/dist/trace-mapping.mjs new file mode 100644 index 0000000..73a95c7 --- /dev/null +++ b/dg-ui/node_modules/@jridgewell/trace-mapping/dist/trace-mapping.mjs @@ -0,0 +1,493 @@ +// src/trace-mapping.ts +import { encode, decode } from "@jridgewell/sourcemap-codec"; + +// src/resolve.ts +import resolveUri from "@jridgewell/resolve-uri"; + +// src/strip-filename.ts +function stripFilename(path) { + if (!path) return ""; + const index = path.lastIndexOf("/"); + return path.slice(0, index + 1); +} + +// src/resolve.ts +function resolver(mapUrl, sourceRoot) { + const from = stripFilename(mapUrl); + const prefix = sourceRoot ? sourceRoot + "/" : ""; + return (source) => resolveUri(prefix + (source || ""), from); +} + +// src/sourcemap-segment.ts +var COLUMN = 0; +var SOURCES_INDEX = 1; +var SOURCE_LINE = 2; +var SOURCE_COLUMN = 3; +var NAMES_INDEX = 4; +var REV_GENERATED_LINE = 1; +var REV_GENERATED_COLUMN = 2; + +// src/sort.ts +function maybeSort(mappings, owned) { + const unsortedIndex = nextUnsortedSegmentLine(mappings, 0); + if (unsortedIndex === mappings.length) return mappings; + if (!owned) mappings = mappings.slice(); + for (let i = unsortedIndex; i < mappings.length; i = nextUnsortedSegmentLine(mappings, i + 1)) { + mappings[i] = sortSegments(mappings[i], owned); + } + return mappings; +} +function nextUnsortedSegmentLine(mappings, start) { + for (let i = start; i < mappings.length; i++) { + if (!isSorted(mappings[i])) return i; + } + return mappings.length; +} +function isSorted(line) { + for (let j = 1; j < line.length; j++) { + if (line[j][COLUMN] < line[j - 1][COLUMN]) { + return false; + } + } + return true; +} +function sortSegments(line, owned) { + if (!owned) line = line.slice(); + return line.sort(sortComparator); +} +function sortComparator(a, b) { + return a[COLUMN] - b[COLUMN]; +} + +// src/by-source.ts +function buildBySources(decoded, memos) { + const sources = memos.map(() => []); + for (let i = 0; i < decoded.length; i++) { + const line = decoded[i]; + for (let j = 0; j < line.length; j++) { + const seg = line[j]; + if (seg.length === 1) continue; + const sourceIndex2 = seg[SOURCES_INDEX]; + const sourceLine = seg[SOURCE_LINE]; + const sourceColumn = seg[SOURCE_COLUMN]; + const source = sources[sourceIndex2]; + const segs = source[sourceLine] || (source[sourceLine] = []); + segs.push([sourceColumn, i, seg[COLUMN]]); + } + } + for (let i = 0; i < sources.length; i++) { + const source = sources[i]; + for (let j = 0; j < source.length; j++) { + const line = source[j]; + if (line) line.sort(sortComparator); + } + } + return sources; +} + +// src/binary-search.ts +var found = false; +function binarySearch(haystack, needle, low, high) { + while (low <= high) { + const mid = low + (high - low >> 1); + const cmp = haystack[mid][COLUMN] - needle; + if (cmp === 0) { + found = true; + return mid; + } + if (cmp < 0) { + low = mid + 1; + } else { + high = mid - 1; + } + } + found = false; + return low - 1; +} +function upperBound(haystack, needle, index) { + for (let i = index + 1; i < haystack.length; index = i++) { + if (haystack[i][COLUMN] !== needle) break; + } + return index; +} +function lowerBound(haystack, needle, index) { + for (let i = index - 1; i >= 0; index = i--) { + if (haystack[i][COLUMN] !== needle) break; + } + return index; +} +function memoizedState() { + return { + lastKey: -1, + lastNeedle: -1, + lastIndex: -1 + }; +} +function memoizedBinarySearch(haystack, needle, state, key) { + const { lastKey, lastNeedle, lastIndex } = state; + let low = 0; + let high = haystack.length - 1; + if (key === lastKey) { + if (needle === lastNeedle) { + found = lastIndex !== -1 && haystack[lastIndex][COLUMN] === needle; + return lastIndex; + } + if (needle >= lastNeedle) { + low = lastIndex === -1 ? 0 : lastIndex; + } else { + high = lastIndex; + } + } + state.lastKey = key; + state.lastNeedle = needle; + return state.lastIndex = binarySearch(haystack, needle, low, high); +} + +// src/types.ts +function parse(map) { + return typeof map === "string" ? JSON.parse(map) : map; +} + +// src/flatten-map.ts +var FlattenMap = function(map, mapUrl) { + const parsed = parse(map); + if (!("sections" in parsed)) { + return new TraceMap(parsed, mapUrl); + } + const mappings = []; + const sources = []; + const sourcesContent = []; + const names = []; + const ignoreList = []; + recurse( + parsed, + mapUrl, + mappings, + sources, + sourcesContent, + names, + ignoreList, + 0, + 0, + Infinity, + Infinity + ); + const joined = { + version: 3, + file: parsed.file, + names, + sources, + sourcesContent, + mappings, + ignoreList + }; + return presortedDecodedMap(joined); +}; +function recurse(input, mapUrl, mappings, sources, sourcesContent, names, ignoreList, lineOffset, columnOffset, stopLine, stopColumn) { + const { sections } = input; + for (let i = 0; i < sections.length; i++) { + const { map, offset } = sections[i]; + let sl = stopLine; + let sc = stopColumn; + if (i + 1 < sections.length) { + const nextOffset = sections[i + 1].offset; + sl = Math.min(stopLine, lineOffset + nextOffset.line); + if (sl === stopLine) { + sc = Math.min(stopColumn, columnOffset + nextOffset.column); + } else if (sl < stopLine) { + sc = columnOffset + nextOffset.column; + } + } + addSection( + map, + mapUrl, + mappings, + sources, + sourcesContent, + names, + ignoreList, + lineOffset + offset.line, + columnOffset + offset.column, + sl, + sc + ); + } +} +function addSection(input, mapUrl, mappings, sources, sourcesContent, names, ignoreList, lineOffset, columnOffset, stopLine, stopColumn) { + const parsed = parse(input); + if ("sections" in parsed) return recurse(...arguments); + const map = new TraceMap(parsed, mapUrl); + const sourcesOffset = sources.length; + const namesOffset = names.length; + const decoded = decodedMappings(map); + const { resolvedSources, sourcesContent: contents, ignoreList: ignores } = map; + append(sources, resolvedSources); + append(names, map.names); + if (contents) append(sourcesContent, contents); + else for (let i = 0; i < resolvedSources.length; i++) sourcesContent.push(null); + if (ignores) for (let i = 0; i < ignores.length; i++) ignoreList.push(ignores[i] + sourcesOffset); + for (let i = 0; i < decoded.length; i++) { + const lineI = lineOffset + i; + if (lineI > stopLine) return; + const out = getLine(mappings, lineI); + const cOffset = i === 0 ? columnOffset : 0; + const line = decoded[i]; + for (let j = 0; j < line.length; j++) { + const seg = line[j]; + const column = cOffset + seg[COLUMN]; + if (lineI === stopLine && column >= stopColumn) return; + if (seg.length === 1) { + out.push([column]); + continue; + } + const sourcesIndex = sourcesOffset + seg[SOURCES_INDEX]; + const sourceLine = seg[SOURCE_LINE]; + const sourceColumn = seg[SOURCE_COLUMN]; + out.push( + seg.length === 4 ? [column, sourcesIndex, sourceLine, sourceColumn] : [column, sourcesIndex, sourceLine, sourceColumn, namesOffset + seg[NAMES_INDEX]] + ); + } + } +} +function append(arr, other) { + for (let i = 0; i < other.length; i++) arr.push(other[i]); +} +function getLine(arr, index) { + for (let i = arr.length; i <= index; i++) arr[i] = []; + return arr[index]; +} + +// src/trace-mapping.ts +var LINE_GTR_ZERO = "`line` must be greater than 0 (lines start at line 1)"; +var COL_GTR_EQ_ZERO = "`column` must be greater than or equal to 0 (columns start at column 0)"; +var LEAST_UPPER_BOUND = -1; +var GREATEST_LOWER_BOUND = 1; +var TraceMap = class { + constructor(map, mapUrl) { + const isString = typeof map === "string"; + if (!isString && map._decodedMemo) return map; + const parsed = parse(map); + const { version, file, names, sourceRoot, sources, sourcesContent } = parsed; + this.version = version; + this.file = file; + this.names = names || []; + this.sourceRoot = sourceRoot; + this.sources = sources; + this.sourcesContent = sourcesContent; + this.ignoreList = parsed.ignoreList || parsed.x_google_ignoreList || void 0; + const resolve = resolver(mapUrl, sourceRoot); + this.resolvedSources = sources.map(resolve); + const { mappings } = parsed; + if (typeof mappings === "string") { + this._encoded = mappings; + this._decoded = void 0; + } else if (Array.isArray(mappings)) { + this._encoded = void 0; + this._decoded = maybeSort(mappings, isString); + } else if (parsed.sections) { + throw new Error(`TraceMap passed sectioned source map, please use FlattenMap export instead`); + } else { + throw new Error(`invalid source map: ${JSON.stringify(parsed)}`); + } + this._decodedMemo = memoizedState(); + this._bySources = void 0; + this._bySourceMemos = void 0; + } +}; +function cast(map) { + return map; +} +function encodedMappings(map) { + var _a, _b; + return (_b = (_a = cast(map))._encoded) != null ? _b : _a._encoded = encode(cast(map)._decoded); +} +function decodedMappings(map) { + var _a; + return (_a = cast(map))._decoded || (_a._decoded = decode(cast(map)._encoded)); +} +function traceSegment(map, line, column) { + const decoded = decodedMappings(map); + if (line >= decoded.length) return null; + const segments = decoded[line]; + const index = traceSegmentInternal( + segments, + cast(map)._decodedMemo, + line, + column, + GREATEST_LOWER_BOUND + ); + return index === -1 ? null : segments[index]; +} +function originalPositionFor(map, needle) { + let { line, column, bias } = needle; + line--; + if (line < 0) throw new Error(LINE_GTR_ZERO); + if (column < 0) throw new Error(COL_GTR_EQ_ZERO); + const decoded = decodedMappings(map); + if (line >= decoded.length) return OMapping(null, null, null, null); + const segments = decoded[line]; + const index = traceSegmentInternal( + segments, + cast(map)._decodedMemo, + line, + column, + bias || GREATEST_LOWER_BOUND + ); + if (index === -1) return OMapping(null, null, null, null); + const segment = segments[index]; + if (segment.length === 1) return OMapping(null, null, null, null); + const { names, resolvedSources } = map; + return OMapping( + resolvedSources[segment[SOURCES_INDEX]], + segment[SOURCE_LINE] + 1, + segment[SOURCE_COLUMN], + segment.length === 5 ? names[segment[NAMES_INDEX]] : null + ); +} +function generatedPositionFor(map, needle) { + const { source, line, column, bias } = needle; + return generatedPosition(map, source, line, column, bias || GREATEST_LOWER_BOUND, false); +} +function allGeneratedPositionsFor(map, needle) { + const { source, line, column, bias } = needle; + return generatedPosition(map, source, line, column, bias || LEAST_UPPER_BOUND, true); +} +function eachMapping(map, cb) { + const decoded = decodedMappings(map); + const { names, resolvedSources } = map; + for (let i = 0; i < decoded.length; i++) { + const line = decoded[i]; + for (let j = 0; j < line.length; j++) { + const seg = line[j]; + const generatedLine = i + 1; + const generatedColumn = seg[0]; + let source = null; + let originalLine = null; + let originalColumn = null; + let name = null; + if (seg.length !== 1) { + source = resolvedSources[seg[1]]; + originalLine = seg[2] + 1; + originalColumn = seg[3]; + } + if (seg.length === 5) name = names[seg[4]]; + cb({ + generatedLine, + generatedColumn, + source, + originalLine, + originalColumn, + name + }); + } + } +} +function sourceIndex(map, source) { + const { sources, resolvedSources } = map; + let index = sources.indexOf(source); + if (index === -1) index = resolvedSources.indexOf(source); + return index; +} +function sourceContentFor(map, source) { + const { sourcesContent } = map; + if (sourcesContent == null) return null; + const index = sourceIndex(map, source); + return index === -1 ? null : sourcesContent[index]; +} +function isIgnored(map, source) { + const { ignoreList } = map; + if (ignoreList == null) return false; + const index = sourceIndex(map, source); + return index === -1 ? false : ignoreList.includes(index); +} +function presortedDecodedMap(map, mapUrl) { + const tracer = new TraceMap(clone(map, []), mapUrl); + cast(tracer)._decoded = map.mappings; + return tracer; +} +function decodedMap(map) { + return clone(map, decodedMappings(map)); +} +function encodedMap(map) { + return clone(map, encodedMappings(map)); +} +function clone(map, mappings) { + return { + version: map.version, + file: map.file, + names: map.names, + sourceRoot: map.sourceRoot, + sources: map.sources, + sourcesContent: map.sourcesContent, + mappings, + ignoreList: map.ignoreList || map.x_google_ignoreList + }; +} +function OMapping(source, line, column, name) { + return { source, line, column, name }; +} +function GMapping(line, column) { + return { line, column }; +} +function traceSegmentInternal(segments, memo, line, column, bias) { + let index = memoizedBinarySearch(segments, column, memo, line); + if (found) { + index = (bias === LEAST_UPPER_BOUND ? upperBound : lowerBound)(segments, column, index); + } else if (bias === LEAST_UPPER_BOUND) index++; + if (index === -1 || index === segments.length) return -1; + return index; +} +function sliceGeneratedPositions(segments, memo, line, column, bias) { + let min = traceSegmentInternal(segments, memo, line, column, GREATEST_LOWER_BOUND); + if (!found && bias === LEAST_UPPER_BOUND) min++; + if (min === -1 || min === segments.length) return []; + const matchedColumn = found ? column : segments[min][COLUMN]; + if (!found) min = lowerBound(segments, matchedColumn, min); + const max = upperBound(segments, matchedColumn, min); + const result = []; + for (; min <= max; min++) { + const segment = segments[min]; + result.push(GMapping(segment[REV_GENERATED_LINE] + 1, segment[REV_GENERATED_COLUMN])); + } + return result; +} +function generatedPosition(map, source, line, column, bias, all) { + var _a, _b; + line--; + if (line < 0) throw new Error(LINE_GTR_ZERO); + if (column < 0) throw new Error(COL_GTR_EQ_ZERO); + const { sources, resolvedSources } = map; + let sourceIndex2 = sources.indexOf(source); + if (sourceIndex2 === -1) sourceIndex2 = resolvedSources.indexOf(source); + if (sourceIndex2 === -1) return all ? [] : GMapping(null, null); + const bySourceMemos = (_a = cast(map))._bySourceMemos || (_a._bySourceMemos = sources.map(memoizedState)); + const generated = (_b = cast(map))._bySources || (_b._bySources = buildBySources(decodedMappings(map), bySourceMemos)); + const segments = generated[sourceIndex2][line]; + if (segments == null) return all ? [] : GMapping(null, null); + const memo = bySourceMemos[sourceIndex2]; + if (all) return sliceGeneratedPositions(segments, memo, line, column, bias); + const index = traceSegmentInternal(segments, memo, line, column, bias); + if (index === -1) return GMapping(null, null); + const segment = segments[index]; + return GMapping(segment[REV_GENERATED_LINE] + 1, segment[REV_GENERATED_COLUMN]); +} +export { + FlattenMap as AnyMap, + FlattenMap, + GREATEST_LOWER_BOUND, + LEAST_UPPER_BOUND, + TraceMap, + allGeneratedPositionsFor, + decodedMap, + decodedMappings, + eachMapping, + encodedMap, + encodedMappings, + generatedPositionFor, + isIgnored, + originalPositionFor, + presortedDecodedMap, + sourceContentFor, + traceSegment +}; +//# sourceMappingURL=trace-mapping.mjs.map diff --git a/dg-ui/node_modules/@jridgewell/trace-mapping/dist/trace-mapping.mjs.map b/dg-ui/node_modules/@jridgewell/trace-mapping/dist/trace-mapping.mjs.map new file mode 100644 index 0000000..a789581 --- /dev/null +++ b/dg-ui/node_modules/@jridgewell/trace-mapping/dist/trace-mapping.mjs.map @@ -0,0 +1,6 @@ +{ + "version": 3, + "sources": ["../src/trace-mapping.ts", "../src/resolve.ts", "../src/strip-filename.ts", "../src/sourcemap-segment.ts", "../src/sort.ts", "../src/by-source.ts", "../src/binary-search.ts", "../src/types.ts", "../src/flatten-map.ts"], + "mappings": ";AAAA,SAAS,QAAQ,cAAc;;;ACA/B,OAAO,gBAAgB;;;ACGR,SAAR,cAA+B,MAAyC;AAC7E,MAAI,CAAC,KAAM,QAAO;AAClB,QAAM,QAAQ,KAAK,YAAY,GAAG;AAClC,SAAO,KAAK,MAAM,GAAG,QAAQ,CAAC;AAChC;;;ADHe,SAAR,SACL,QACA,YACS;AACT,QAAM,OAAO,cAAc,MAAM;AAIjC,QAAM,SAAS,aAAa,aAAa,MAAM;AAE/C,SAAO,CAAC,WAAW,WAAW,UAAU,UAAU,KAAK,IAAI;AAC7D;;;AEAO,IAAM,SAAS;AACf,IAAM,gBAAgB;AACtB,IAAM,cAAc;AACpB,IAAM,gBAAgB;AACtB,IAAM,cAAc;AAEpB,IAAM,qBAAqB;AAC3B,IAAM,uBAAuB;;;AClBrB,SAAR,UACL,UACA,OACsB;AACtB,QAAM,gBAAgB,wBAAwB,UAAU,CAAC;AACzD,MAAI,kBAAkB,SAAS,OAAQ,QAAO;AAI9C,MAAI,CAAC,MAAO,YAAW,SAAS,MAAM;AAEtC,WAAS,IAAI,eAAe,IAAI,SAAS,QAAQ,IAAI,wBAAwB,UAAU,IAAI,CAAC,GAAG;AAC7F,aAAS,CAAC,IAAI,aAAa,SAAS,CAAC,GAAG,KAAK;AAAA,EAC/C;AACA,SAAO;AACT;AAEA,SAAS,wBAAwB,UAAgC,OAAuB;AACtF,WAAS,IAAI,OAAO,IAAI,SAAS,QAAQ,KAAK;AAC5C,QAAI,CAAC,SAAS,SAAS,CAAC,CAAC,EAAG,QAAO;AAAA,EACrC;AACA,SAAO,SAAS;AAClB;AAEA,SAAS,SAAS,MAAmC;AACnD,WAAS,IAAI,GAAG,IAAI,KAAK,QAAQ,KAAK;AACpC,QAAI,KAAK,CAAC,EAAE,MAAM,IAAI,KAAK,IAAI,CAAC,EAAE,MAAM,GAAG;AACzC,aAAO;AAAA,IACT;AAAA,EACF;AACA,SAAO;AACT;AAEA,SAAS,aAAa,MAA0B,OAAoC;AAClF,MAAI,CAAC,MAAO,QAAO,KAAK,MAAM;AAC9B,SAAO,KAAK,KAAK,cAAc;AACjC;AAEO,SAAS,eAA4D,GAAM,GAAc;AAC9F,SAAO,EAAE,MAAM,IAAI,EAAE,MAAM;AAC7B;;;ACnCe,SAAR,eACL,SACA,OACU;AACV,QAAM,UAAoB,MAAM,IAAI,MAAM,CAAC,CAAC;AAE5C,WAAS,IAAI,GAAG,IAAI,QAAQ,QAAQ,KAAK;AACvC,UAAM,OAAO,QAAQ,CAAC;AACtB,aAAS,IAAI,GAAG,IAAI,KAAK,QAAQ,KAAK;AACpC,YAAM,MAAM,KAAK,CAAC;AAClB,UAAI,IAAI,WAAW,EAAG;AAEtB,YAAMA,eAAc,IAAI,aAAa;AACrC,YAAM,aAAa,IAAI,WAAW;AAClC,YAAM,eAAe,IAAI,aAAa;AAEtC,YAAM,SAAS,QAAQA,YAAW;AAClC,YAAM,OAAQ,4CAAuB,CAAC;AACtC,WAAK,KAAK,CAAC,cAAc,GAAG,IAAI,MAAM,CAAC,CAAC;AAAA,IAC1C;AAAA,EACF;AAEA,WAAS,IAAI,GAAG,IAAI,QAAQ,QAAQ,KAAK;AACvC,UAAM,SAAS,QAAQ,CAAC;AACxB,aAAS,IAAI,GAAG,IAAI,OAAO,QAAQ,KAAK;AACtC,YAAM,OAAO,OAAO,CAAC;AACrB,UAAI,KAAM,MAAK,KAAK,cAAc;AAAA,IACpC;AAAA,EACF;AAEA,SAAO;AACT;;;AC/BO,IAAI,QAAQ;AAkBZ,SAAS,aACd,UACA,QACA,KACA,MACQ;AACR,SAAO,OAAO,MAAM;AAClB,UAAM,MAAM,OAAQ,OAAO,OAAQ;AACnC,UAAM,MAAM,SAAS,GAAG,EAAE,MAAM,IAAI;AAEpC,QAAI,QAAQ,GAAG;AACb,cAAQ;AACR,aAAO;AAAA,IACT;AAEA,QAAI,MAAM,GAAG;AACX,YAAM,MAAM;AAAA,IACd,OAAO;AACL,aAAO,MAAM;AAAA,IACf;AAAA,EACF;AAEA,UAAQ;AACR,SAAO,MAAM;AACf;AAEO,SAAS,WACd,UACA,QACA,OACQ;AACR,WAAS,IAAI,QAAQ,GAAG,IAAI,SAAS,QAAQ,QAAQ,KAAK;AACxD,QAAI,SAAS,CAAC,EAAE,MAAM,MAAM,OAAQ;AAAA,EACtC;AACA,SAAO;AACT;AAEO,SAAS,WACd,UACA,QACA,OACQ;AACR,WAAS,IAAI,QAAQ,GAAG,KAAK,GAAG,QAAQ,KAAK;AAC3C,QAAI,SAAS,CAAC,EAAE,MAAM,MAAM,OAAQ;AAAA,EACtC;AACA,SAAO;AACT;AAEO,SAAS,gBAA2B;AACzC,SAAO;AAAA,IACL,SAAS;AAAA,IACT,YAAY;AAAA,IACZ,WAAW;AAAA,EACb;AACF;AAMO,SAAS,qBACd,UACA,QACA,OACA,KACQ;AACR,QAAM,EAAE,SAAS,YAAY,UAAU,IAAI;AAE3C,MAAI,MAAM;AACV,MAAI,OAAO,SAAS,SAAS;AAC7B,MAAI,QAAQ,SAAS;AACnB,QAAI,WAAW,YAAY;AACzB,cAAQ,cAAc,MAAM,SAAS,SAAS,EAAE,MAAM,MAAM;AAC5D,aAAO;AAAA,IACT;AAEA,QAAI,UAAU,YAAY;AAExB,YAAM,cAAc,KAAK,IAAI;AAAA,IAC/B,OAAO;AACL,aAAO;AAAA,IACT;AAAA,EACF;AACA,QAAM,UAAU;AAChB,QAAM,aAAa;AAEnB,SAAQ,MAAM,YAAY,aAAa,UAAU,QAAQ,KAAK,IAAI;AACpE;;;ACHO,SAAS,MAAS,KAA4B;AACnD,SAAO,OAAO,QAAQ,WAAW,KAAK,MAAM,GAAG,IAAK;AACtD;;;ACvFO,IAAM,aAAyB,SAAU,KAAK,QAAQ;AAC3D,QAAM,SAAS,MAAM,GAA8B;AAEnD,MAAI,EAAE,cAAc,SAAS;AAC3B,WAAO,IAAI,SAAS,QAA2D,MAAM;AAAA,EACvF;AAEA,QAAM,WAAiC,CAAC;AACxC,QAAM,UAAoB,CAAC;AAC3B,QAAM,iBAAoC,CAAC;AAC3C,QAAM,QAAkB,CAAC;AACzB,QAAM,aAAuB,CAAC;AAE9B;AAAA,IACE;AAAA,IACA;AAAA,IACA;AAAA,IACA;AAAA,IACA;AAAA,IACA;AAAA,IACA;AAAA,IACA;AAAA,IACA;AAAA,IACA;AAAA,IACA;AAAA,EACF;AAEA,QAAM,SAA2B;AAAA,IAC/B,SAAS;AAAA,IACT,MAAM,OAAO;AAAA,IACb;AAAA,IACA;AAAA,IACA;AAAA,IACA;AAAA,IACA;AAAA,EACF;AAEA,SAAO,oBAAoB,MAAM;AACnC;AAEA,SAAS,QACP,OACA,QACA,UACA,SACA,gBACA,OACA,YACA,YACA,cACA,UACA,YACA;AACA,QAAM,EAAE,SAAS,IAAI;AACrB,WAAS,IAAI,GAAG,IAAI,SAAS,QAAQ,KAAK;AACxC,UAAM,EAAE,KAAK,OAAO,IAAI,SAAS,CAAC;AAElC,QAAI,KAAK;AACT,QAAI,KAAK;AACT,QAAI,IAAI,IAAI,SAAS,QAAQ;AAC3B,YAAM,aAAa,SAAS,IAAI,CAAC,EAAE;AACnC,WAAK,KAAK,IAAI,UAAU,aAAa,WAAW,IAAI;AAEpD,UAAI,OAAO,UAAU;AACnB,aAAK,KAAK,IAAI,YAAY,eAAe,WAAW,MAAM;AAAA,MAC5D,WAAW,KAAK,UAAU;AACxB,aAAK,eAAe,WAAW;AAAA,MACjC;AAAA,IACF;AAEA;AAAA,MACE;AAAA,MACA;AAAA,MACA;AAAA,MACA;AAAA,MACA;AAAA,MACA;AAAA,MACA;AAAA,MACA,aAAa,OAAO;AAAA,MACpB,eAAe,OAAO;AAAA,MACtB;AAAA,MACA;AAAA,IACF;AAAA,EACF;AACF;AAEA,SAAS,WACP,OACA,QACA,UACA,SACA,gBACA,OACA,YACA,YACA,cACA,UACA,YACA;AACA,QAAM,SAAS,MAAM,KAAK;AAC1B,MAAI,cAAc,OAAQ,QAAO,QAAQ,GAAI,SAAmD;AAEhG,QAAM,MAAM,IAAI,SAAS,QAAQ,MAAM;AACvC,QAAM,gBAAgB,QAAQ;AAC9B,QAAM,cAAc,MAAM;AAC1B,QAAM,UAAU,gBAAgB,GAAG;AACnC,QAAM,EAAE,iBAAiB,gBAAgB,UAAU,YAAY,QAAQ,IAAI;AAE3E,SAAO,SAAS,eAAe;AAC/B,SAAO,OAAO,IAAI,KAAK;AAEvB,MAAI,SAAU,QAAO,gBAAgB,QAAQ;AAAA,MACxC,UAAS,IAAI,GAAG,IAAI,gBAAgB,QAAQ,IAAK,gBAAe,KAAK,IAAI;AAE9E,MAAI,QAAS,UAAS,IAAI,GAAG,IAAI,QAAQ,QAAQ,IAAK,YAAW,KAAK,QAAQ,CAAC,IAAI,aAAa;AAEhG,WAAS,IAAI,GAAG,IAAI,QAAQ,QAAQ,KAAK;AACvC,UAAM,QAAQ,aAAa;AAM3B,QAAI,QAAQ,SAAU;AAItB,UAAM,MAAM,QAAQ,UAAU,KAAK;AAGnC,UAAM,UAAU,MAAM,IAAI,eAAe;AAEzC,UAAM,OAAO,QAAQ,CAAC;AACtB,aAAS,IAAI,GAAG,IAAI,KAAK,QAAQ,KAAK;AACpC,YAAM,MAAM,KAAK,CAAC;AAClB,YAAM,SAAS,UAAU,IAAI,MAAM;AAInC,UAAI,UAAU,YAAY,UAAU,WAAY;AAEhD,UAAI,IAAI,WAAW,GAAG;AACpB,YAAI,KAAK,CAAC,MAAM,CAAC;AACjB;AAAA,MACF;AAEA,YAAM,eAAe,gBAAgB,IAAI,aAAa;AACtD,YAAM,aAAa,IAAI,WAAW;AAClC,YAAM,eAAe,IAAI,aAAa;AACtC,UAAI;AAAA,QACF,IAAI,WAAW,IACX,CAAC,QAAQ,cAAc,YAAY,YAAY,IAC/C,CAAC,QAAQ,cAAc,YAAY,cAAc,cAAc,IAAI,WAAW,CAAC;AAAA,MACrF;AAAA,IACF;AAAA,EACF;AACF;AAEA,SAAS,OAAU,KAAU,OAAY;AACvC,WAAS,IAAI,GAAG,IAAI,MAAM,QAAQ,IAAK,KAAI,KAAK,MAAM,CAAC,CAAC;AAC1D;AAEA,SAAS,QAAW,KAAY,OAAoB;AAClD,WAAS,IAAI,IAAI,QAAQ,KAAK,OAAO,IAAK,KAAI,CAAC,IAAI,CAAC;AACpD,SAAO,IAAI,KAAK;AAClB;;;ARhHA,IAAM,gBAAgB;AACtB,IAAM,kBAAkB;AAEjB,IAAM,oBAAoB;AAC1B,IAAM,uBAAuB;AAI7B,IAAM,WAAN,MAAoC;AAAA,EAkBzC,YAAY,KAAyB,QAAwB;AAC3D,UAAM,WAAW,OAAO,QAAQ;AAChC,QAAI,CAAC,YAAa,IAAyC,aAAc,QAAO;AAEhF,UAAM,SAAS,MAAM,GAAwC;AAE7D,UAAM,EAAE,SAAS,MAAM,OAAO,YAAY,SAAS,eAAe,IAAI;AACtE,SAAK,UAAU;AACf,SAAK,OAAO;AACZ,SAAK,QAAQ,SAAS,CAAC;AACvB,SAAK,aAAa;AAClB,SAAK,UAAU;AACf,SAAK,iBAAiB;AACtB,SAAK,aAAa,OAAO,cAAe,OAAkB,uBAAuB;AAEjF,UAAM,UAAU,SAAS,QAAQ,UAAU;AAC3C,SAAK,kBAAkB,QAAQ,IAAI,OAAO;AAE1C,UAAM,EAAE,SAAS,IAAI;AACrB,QAAI,OAAO,aAAa,UAAU;AAChC,WAAK,WAAW;AAChB,WAAK,WAAW;AAAA,IAClB,WAAW,MAAM,QAAQ,QAAQ,GAAG;AAClC,WAAK,WAAW;AAChB,WAAK,WAAW,UAAU,UAAU,QAAQ;AAAA,IAC9C,WAAY,OAAyC,UAAU;AAC7D,YAAM,IAAI,MAAM,4EAA4E;AAAA,IAC9F,OAAO;AACL,YAAM,IAAI,MAAM,uBAAuB,KAAK,UAAU,MAAM,CAAC,EAAE;AAAA,IACjE;AAEA,SAAK,eAAe,cAAc;AAClC,SAAK,aAAa;AAClB,SAAK,iBAAiB;AAAA,EACxB;AACF;AAMA,SAAS,KAAK,KAAyB;AACrC,SAAO;AACT;AAKO,SAAS,gBAAgB,KAA6C;AAzJ7E;AA0JE,UAAQ,gBAAK,GAAG,GAAE,aAAV,eAAU,WAAa,OAAO,KAAK,GAAG,EAAE,QAAS;AAC3D;AAKO,SAAS,gBAAgB,KAAuD;AAhKvF;AAiKE,UAAQ,UAAK,GAAG,GAAE,aAAV,GAAU,WAAa,OAAO,KAAK,GAAG,EAAE,QAAS;AAC3D;AAMO,SAAS,aACd,KACA,MACA,QACmC;AACnC,QAAM,UAAU,gBAAgB,GAAG;AAInC,MAAI,QAAQ,QAAQ,OAAQ,QAAO;AAEnC,QAAM,WAAW,QAAQ,IAAI;AAC7B,QAAM,QAAQ;AAAA,IACZ;AAAA,IACA,KAAK,GAAG,EAAE;AAAA,IACV;AAAA,IACA;AAAA,IACA;AAAA,EACF;AAEA,SAAO,UAAU,KAAK,OAAO,SAAS,KAAK;AAC7C;AAOO,SAAS,oBACd,KACA,QAC0C;AAC1C,MAAI,EAAE,MAAM,QAAQ,KAAK,IAAI;AAC7B;AACA,MAAI,OAAO,EAAG,OAAM,IAAI,MAAM,aAAa;AAC3C,MAAI,SAAS,EAAG,OAAM,IAAI,MAAM,eAAe;AAE/C,QAAM,UAAU,gBAAgB,GAAG;AAInC,MAAI,QAAQ,QAAQ,OAAQ,QAAO,SAAS,MAAM,MAAM,MAAM,IAAI;AAElE,QAAM,WAAW,QAAQ,IAAI;AAC7B,QAAM,QAAQ;AAAA,IACZ;AAAA,IACA,KAAK,GAAG,EAAE;AAAA,IACV;AAAA,IACA;AAAA,IACA,QAAQ;AAAA,EACV;AAEA,MAAI,UAAU,GAAI,QAAO,SAAS,MAAM,MAAM,MAAM,IAAI;AAExD,QAAM,UAAU,SAAS,KAAK;AAC9B,MAAI,QAAQ,WAAW,EAAG,QAAO,SAAS,MAAM,MAAM,MAAM,IAAI;AAEhE,QAAM,EAAE,OAAO,gBAAgB,IAAI;AACnC,SAAO;AAAA,IACL,gBAAgB,QAAQ,aAAa,CAAC;AAAA,IACtC,QAAQ,WAAW,IAAI;AAAA,IACvB,QAAQ,aAAa;AAAA,IACrB,QAAQ,WAAW,IAAI,MAAM,QAAQ,WAAW,CAAC,IAAI;AAAA,EACvD;AACF;AAKO,SAAS,qBACd,KACA,QAC4C;AAC5C,QAAM,EAAE,QAAQ,MAAM,QAAQ,KAAK,IAAI;AACvC,SAAO,kBAAkB,KAAK,QAAQ,MAAM,QAAQ,QAAQ,sBAAsB,KAAK;AACzF;AAKO,SAAS,yBAAyB,KAAe,QAA0C;AAChG,QAAM,EAAE,QAAQ,MAAM,QAAQ,KAAK,IAAI;AAEvC,SAAO,kBAAkB,KAAK,QAAQ,MAAM,QAAQ,QAAQ,mBAAmB,IAAI;AACrF;AAKO,SAAS,YAAY,KAAe,IAA0C;AACnF,QAAM,UAAU,gBAAgB,GAAG;AACnC,QAAM,EAAE,OAAO,gBAAgB,IAAI;AAEnC,WAAS,IAAI,GAAG,IAAI,QAAQ,QAAQ,KAAK;AACvC,UAAM,OAAO,QAAQ,CAAC;AACtB,aAAS,IAAI,GAAG,IAAI,KAAK,QAAQ,KAAK;AACpC,YAAM,MAAM,KAAK,CAAC;AAElB,YAAM,gBAAgB,IAAI;AAC1B,YAAM,kBAAkB,IAAI,CAAC;AAC7B,UAAI,SAAS;AACb,UAAI,eAAe;AACnB,UAAI,iBAAiB;AACrB,UAAI,OAAO;AACX,UAAI,IAAI,WAAW,GAAG;AACpB,iBAAS,gBAAgB,IAAI,CAAC,CAAC;AAC/B,uBAAe,IAAI,CAAC,IAAI;AACxB,yBAAiB,IAAI,CAAC;AAAA,MACxB;AACA,UAAI,IAAI,WAAW,EAAG,QAAO,MAAM,IAAI,CAAC,CAAC;AAEzC,SAAG;AAAA,QACD;AAAA,QACA;AAAA,QACA;AAAA,QACA;AAAA,QACA;AAAA,QACA;AAAA,MACF,CAAgB;AAAA,IAClB;AAAA,EACF;AACF;AAEA,SAAS,YAAY,KAAe,QAAwB;AAC1D,QAAM,EAAE,SAAS,gBAAgB,IAAI;AACrC,MAAI,QAAQ,QAAQ,QAAQ,MAAM;AAClC,MAAI,UAAU,GAAI,SAAQ,gBAAgB,QAAQ,MAAM;AACxD,SAAO;AACT;AAKO,SAAS,iBAAiB,KAAe,QAA+B;AAC7E,QAAM,EAAE,eAAe,IAAI;AAC3B,MAAI,kBAAkB,KAAM,QAAO;AACnC,QAAM,QAAQ,YAAY,KAAK,MAAM;AACrC,SAAO,UAAU,KAAK,OAAO,eAAe,KAAK;AACnD;AAKO,SAAS,UAAU,KAAe,QAAyB;AAChE,QAAM,EAAE,WAAW,IAAI;AACvB,MAAI,cAAc,KAAM,QAAO;AAC/B,QAAM,QAAQ,YAAY,KAAK,MAAM;AACrC,SAAO,UAAU,KAAK,QAAQ,WAAW,SAAS,KAAK;AACzD;AAMO,SAAS,oBAAoB,KAAuB,QAA2B;AACpF,QAAM,SAAS,IAAI,SAAS,MAAM,KAAK,CAAC,CAAC,GAAG,MAAM;AAClD,OAAK,MAAM,EAAE,WAAW,IAAI;AAC5B,SAAO;AACT;AAMO,SAAS,WACd,KACkF;AAClF,SAAO,MAAM,KAAK,gBAAgB,GAAG,CAAC;AACxC;AAMO,SAAS,WAAW,KAAiC;AAC1D,SAAO,MAAM,KAAK,gBAAgB,GAAG,CAAC;AACxC;AAEA,SAAS,MACP,KACA,UACwD;AACxD,SAAO;AAAA,IACL,SAAS,IAAI;AAAA,IACb,MAAM,IAAI;AAAA,IACV,OAAO,IAAI;AAAA,IACX,YAAY,IAAI;AAAA,IAChB,SAAS,IAAI;AAAA,IACb,gBAAgB,IAAI;AAAA,IACpB;AAAA,IACA,YAAY,IAAI,cAAe,IAAe;AAAA,EAChD;AACF;AASA,SAAS,SACP,QACA,MACA,QACA,MAC0C;AAC1C,SAAO,EAAE,QAAQ,MAAM,QAAQ,KAAK;AACtC;AAIA,SAAS,SACP,MACA,QAC4C;AAC5C,SAAO,EAAE,MAAM,OAAO;AACxB;AAgBA,SAAS,qBACP,UACA,MACA,MACA,QACA,MACQ;AACR,MAAI,QAAQ,qBAAqB,UAAU,QAAQ,MAAM,IAAI;AAC7D,MAAI,OAAS;AACX,aAAS,SAAS,oBAAoB,aAAa,YAAY,UAAU,QAAQ,KAAK;AAAA,EACxF,WAAW,SAAS,kBAAmB;AAEvC,MAAI,UAAU,MAAM,UAAU,SAAS,OAAQ,QAAO;AACtD,SAAO;AACT;AAEA,SAAS,wBACP,UACA,MACA,MACA,QACA,MACoB;AACpB,MAAI,MAAM,qBAAqB,UAAU,MAAM,MAAM,QAAQ,oBAAoB;AAQjF,MAAI,CAAC,SAAW,SAAS,kBAAmB;AAE5C,MAAI,QAAQ,MAAM,QAAQ,SAAS,OAAQ,QAAO,CAAC;AAKnD,QAAM,gBAAgB,QAAU,SAAS,SAAS,GAAG,EAAE,MAAM;AAG7D,MAAI,CAAC,MAAS,OAAM,WAAW,UAAU,eAAe,GAAG;AAC3D,QAAM,MAAM,WAAW,UAAU,eAAe,GAAG;AAEnD,QAAM,SAAS,CAAC;AAChB,SAAO,OAAO,KAAK,OAAO;AACxB,UAAM,UAAU,SAAS,GAAG;AAC5B,WAAO,KAAK,SAAS,QAAQ,kBAAkB,IAAI,GAAG,QAAQ,oBAAoB,CAAC,CAAC;AAAA,EACtF;AACA,SAAO;AACT;AAkBA,SAAS,kBACP,KACA,QACA,MACA,QACA,MACA,KACiE;AA5dnE;AA6dE;AACA,MAAI,OAAO,EAAG,OAAM,IAAI,MAAM,aAAa;AAC3C,MAAI,SAAS,EAAG,OAAM,IAAI,MAAM,eAAe;AAE/C,QAAM,EAAE,SAAS,gBAAgB,IAAI;AACrC,MAAIC,eAAc,QAAQ,QAAQ,MAAM;AACxC,MAAIA,iBAAgB,GAAI,CAAAA,eAAc,gBAAgB,QAAQ,MAAM;AACpE,MAAIA,iBAAgB,GAAI,QAAO,MAAM,CAAC,IAAI,SAAS,MAAM,IAAI;AAE7D,QAAM,iBAAiB,UAAK,GAAG,GAAE,mBAAV,GAAU,iBAAmB,QAAQ,IAAI,aAAa;AAC7E,QAAM,aAAa,UAAK,GAAG,GAAE,eAAV,GAAU,aAAe,eAAe,gBAAgB,GAAG,GAAG,aAAa;AAE9F,QAAM,WAAW,UAAUA,YAAW,EAAE,IAAI;AAC5C,MAAI,YAAY,KAAM,QAAO,MAAM,CAAC,IAAI,SAAS,MAAM,IAAI;AAE3D,QAAM,OAAO,cAAcA,YAAW;AAEtC,MAAI,IAAK,QAAO,wBAAwB,UAAU,MAAM,MAAM,QAAQ,IAAI;AAE1E,QAAM,QAAQ,qBAAqB,UAAU,MAAM,MAAM,QAAQ,IAAI;AACrE,MAAI,UAAU,GAAI,QAAO,SAAS,MAAM,IAAI;AAE5C,QAAM,UAAU,SAAS,KAAK;AAC9B,SAAO,SAAS,QAAQ,kBAAkB,IAAI,GAAG,QAAQ,oBAAoB,CAAC;AAChF;", + "names": ["sourceIndex", "sourceIndex"] +} diff --git a/dg-ui/node_modules/@jridgewell/trace-mapping/dist/trace-mapping.umd.js b/dg-ui/node_modules/@jridgewell/trace-mapping/dist/trace-mapping.umd.js new file mode 100644 index 0000000..0387ae3 --- /dev/null +++ b/dg-ui/node_modules/@jridgewell/trace-mapping/dist/trace-mapping.umd.js @@ -0,0 +1,559 @@ +(function (global, factory) { + if (typeof exports === 'object' && typeof module !== 'undefined') { + factory(module, require('@jridgewell/resolve-uri'), require('@jridgewell/sourcemap-codec')); + module.exports = def(module); + } else if (typeof define === 'function' && define.amd) { + define(['module', '@jridgewell/resolve-uri', '@jridgewell/sourcemap-codec'], function(mod) { + factory.apply(this, arguments); + mod.exports = def(mod); + }); + } else { + const mod = { exports: {} }; + factory(mod, global.resolveURI, global.sourcemapCodec); + global = typeof globalThis !== 'undefined' ? globalThis : global || self; + global.traceMapping = def(mod); + } + function def(m) { return 'default' in m.exports ? m.exports.default : m.exports; } +})(this, (function (module, require_resolveURI, require_sourcemapCodec) { +"use strict"; +var __create = Object.create; +var __defProp = Object.defineProperty; +var __getOwnPropDesc = Object.getOwnPropertyDescriptor; +var __getOwnPropNames = Object.getOwnPropertyNames; +var __getProtoOf = Object.getPrototypeOf; +var __hasOwnProp = Object.prototype.hasOwnProperty; +var __commonJS = (cb, mod) => function __require() { + return mod || (0, cb[__getOwnPropNames(cb)[0]])((mod = { exports: {} }).exports, mod), mod.exports; +}; +var __export = (target, all) => { + for (var name in all) + __defProp(target, name, { get: all[name], enumerable: true }); +}; +var __copyProps = (to, from, except, desc) => { + if (from && typeof from === "object" || typeof from === "function") { + for (let key of __getOwnPropNames(from)) + if (!__hasOwnProp.call(to, key) && key !== except) + __defProp(to, key, { get: () => from[key], enumerable: !(desc = __getOwnPropDesc(from, key)) || desc.enumerable }); + } + return to; +}; +var __toESM = (mod, isNodeMode, target) => (target = mod != null ? __create(__getProtoOf(mod)) : {}, __copyProps( + // If the importer is in node compatibility mode or this is not an ESM + // file that has been converted to a CommonJS file using a Babel- + // compatible transform (i.e. "__esModule" has not been set), then set + // "default" to the CommonJS "module.exports" for node compatibility. + isNodeMode || !mod || !mod.__esModule ? __defProp(target, "default", { value: mod, enumerable: true }) : target, + mod +)); +var __toCommonJS = (mod) => __copyProps(__defProp({}, "__esModule", { value: true }), mod); + +// umd:@jridgewell/sourcemap-codec +var require_sourcemap_codec = __commonJS({ + "umd:@jridgewell/sourcemap-codec"(exports, module2) { + module2.exports = require_sourcemapCodec; + } +}); + +// umd:@jridgewell/resolve-uri +var require_resolve_uri = __commonJS({ + "umd:@jridgewell/resolve-uri"(exports, module2) { + module2.exports = require_resolveURI; + } +}); + +// src/trace-mapping.ts +var trace_mapping_exports = {}; +__export(trace_mapping_exports, { + AnyMap: () => FlattenMap, + FlattenMap: () => FlattenMap, + GREATEST_LOWER_BOUND: () => GREATEST_LOWER_BOUND, + LEAST_UPPER_BOUND: () => LEAST_UPPER_BOUND, + TraceMap: () => TraceMap, + allGeneratedPositionsFor: () => allGeneratedPositionsFor, + decodedMap: () => decodedMap, + decodedMappings: () => decodedMappings, + eachMapping: () => eachMapping, + encodedMap: () => encodedMap, + encodedMappings: () => encodedMappings, + generatedPositionFor: () => generatedPositionFor, + isIgnored: () => isIgnored, + originalPositionFor: () => originalPositionFor, + presortedDecodedMap: () => presortedDecodedMap, + sourceContentFor: () => sourceContentFor, + traceSegment: () => traceSegment +}); +module.exports = __toCommonJS(trace_mapping_exports); +var import_sourcemap_codec = __toESM(require_sourcemap_codec()); + +// src/resolve.ts +var import_resolve_uri = __toESM(require_resolve_uri()); + +// src/strip-filename.ts +function stripFilename(path) { + if (!path) return ""; + const index = path.lastIndexOf("/"); + return path.slice(0, index + 1); +} + +// src/resolve.ts +function resolver(mapUrl, sourceRoot) { + const from = stripFilename(mapUrl); + const prefix = sourceRoot ? sourceRoot + "/" : ""; + return (source) => (0, import_resolve_uri.default)(prefix + (source || ""), from); +} + +// src/sourcemap-segment.ts +var COLUMN = 0; +var SOURCES_INDEX = 1; +var SOURCE_LINE = 2; +var SOURCE_COLUMN = 3; +var NAMES_INDEX = 4; +var REV_GENERATED_LINE = 1; +var REV_GENERATED_COLUMN = 2; + +// src/sort.ts +function maybeSort(mappings, owned) { + const unsortedIndex = nextUnsortedSegmentLine(mappings, 0); + if (unsortedIndex === mappings.length) return mappings; + if (!owned) mappings = mappings.slice(); + for (let i = unsortedIndex; i < mappings.length; i = nextUnsortedSegmentLine(mappings, i + 1)) { + mappings[i] = sortSegments(mappings[i], owned); + } + return mappings; +} +function nextUnsortedSegmentLine(mappings, start) { + for (let i = start; i < mappings.length; i++) { + if (!isSorted(mappings[i])) return i; + } + return mappings.length; +} +function isSorted(line) { + for (let j = 1; j < line.length; j++) { + if (line[j][COLUMN] < line[j - 1][COLUMN]) { + return false; + } + } + return true; +} +function sortSegments(line, owned) { + if (!owned) line = line.slice(); + return line.sort(sortComparator); +} +function sortComparator(a, b) { + return a[COLUMN] - b[COLUMN]; +} + +// src/by-source.ts +function buildBySources(decoded, memos) { + const sources = memos.map(() => []); + for (let i = 0; i < decoded.length; i++) { + const line = decoded[i]; + for (let j = 0; j < line.length; j++) { + const seg = line[j]; + if (seg.length === 1) continue; + const sourceIndex2 = seg[SOURCES_INDEX]; + const sourceLine = seg[SOURCE_LINE]; + const sourceColumn = seg[SOURCE_COLUMN]; + const source = sources[sourceIndex2]; + const segs = source[sourceLine] || (source[sourceLine] = []); + segs.push([sourceColumn, i, seg[COLUMN]]); + } + } + for (let i = 0; i < sources.length; i++) { + const source = sources[i]; + for (let j = 0; j < source.length; j++) { + const line = source[j]; + if (line) line.sort(sortComparator); + } + } + return sources; +} + +// src/binary-search.ts +var found = false; +function binarySearch(haystack, needle, low, high) { + while (low <= high) { + const mid = low + (high - low >> 1); + const cmp = haystack[mid][COLUMN] - needle; + if (cmp === 0) { + found = true; + return mid; + } + if (cmp < 0) { + low = mid + 1; + } else { + high = mid - 1; + } + } + found = false; + return low - 1; +} +function upperBound(haystack, needle, index) { + for (let i = index + 1; i < haystack.length; index = i++) { + if (haystack[i][COLUMN] !== needle) break; + } + return index; +} +function lowerBound(haystack, needle, index) { + for (let i = index - 1; i >= 0; index = i--) { + if (haystack[i][COLUMN] !== needle) break; + } + return index; +} +function memoizedState() { + return { + lastKey: -1, + lastNeedle: -1, + lastIndex: -1 + }; +} +function memoizedBinarySearch(haystack, needle, state, key) { + const { lastKey, lastNeedle, lastIndex } = state; + let low = 0; + let high = haystack.length - 1; + if (key === lastKey) { + if (needle === lastNeedle) { + found = lastIndex !== -1 && haystack[lastIndex][COLUMN] === needle; + return lastIndex; + } + if (needle >= lastNeedle) { + low = lastIndex === -1 ? 0 : lastIndex; + } else { + high = lastIndex; + } + } + state.lastKey = key; + state.lastNeedle = needle; + return state.lastIndex = binarySearch(haystack, needle, low, high); +} + +// src/types.ts +function parse(map) { + return typeof map === "string" ? JSON.parse(map) : map; +} + +// src/flatten-map.ts +var FlattenMap = function(map, mapUrl) { + const parsed = parse(map); + if (!("sections" in parsed)) { + return new TraceMap(parsed, mapUrl); + } + const mappings = []; + const sources = []; + const sourcesContent = []; + const names = []; + const ignoreList = []; + recurse( + parsed, + mapUrl, + mappings, + sources, + sourcesContent, + names, + ignoreList, + 0, + 0, + Infinity, + Infinity + ); + const joined = { + version: 3, + file: parsed.file, + names, + sources, + sourcesContent, + mappings, + ignoreList + }; + return presortedDecodedMap(joined); +}; +function recurse(input, mapUrl, mappings, sources, sourcesContent, names, ignoreList, lineOffset, columnOffset, stopLine, stopColumn) { + const { sections } = input; + for (let i = 0; i < sections.length; i++) { + const { map, offset } = sections[i]; + let sl = stopLine; + let sc = stopColumn; + if (i + 1 < sections.length) { + const nextOffset = sections[i + 1].offset; + sl = Math.min(stopLine, lineOffset + nextOffset.line); + if (sl === stopLine) { + sc = Math.min(stopColumn, columnOffset + nextOffset.column); + } else if (sl < stopLine) { + sc = columnOffset + nextOffset.column; + } + } + addSection( + map, + mapUrl, + mappings, + sources, + sourcesContent, + names, + ignoreList, + lineOffset + offset.line, + columnOffset + offset.column, + sl, + sc + ); + } +} +function addSection(input, mapUrl, mappings, sources, sourcesContent, names, ignoreList, lineOffset, columnOffset, stopLine, stopColumn) { + const parsed = parse(input); + if ("sections" in parsed) return recurse(...arguments); + const map = new TraceMap(parsed, mapUrl); + const sourcesOffset = sources.length; + const namesOffset = names.length; + const decoded = decodedMappings(map); + const { resolvedSources, sourcesContent: contents, ignoreList: ignores } = map; + append(sources, resolvedSources); + append(names, map.names); + if (contents) append(sourcesContent, contents); + else for (let i = 0; i < resolvedSources.length; i++) sourcesContent.push(null); + if (ignores) for (let i = 0; i < ignores.length; i++) ignoreList.push(ignores[i] + sourcesOffset); + for (let i = 0; i < decoded.length; i++) { + const lineI = lineOffset + i; + if (lineI > stopLine) return; + const out = getLine(mappings, lineI); + const cOffset = i === 0 ? columnOffset : 0; + const line = decoded[i]; + for (let j = 0; j < line.length; j++) { + const seg = line[j]; + const column = cOffset + seg[COLUMN]; + if (lineI === stopLine && column >= stopColumn) return; + if (seg.length === 1) { + out.push([column]); + continue; + } + const sourcesIndex = sourcesOffset + seg[SOURCES_INDEX]; + const sourceLine = seg[SOURCE_LINE]; + const sourceColumn = seg[SOURCE_COLUMN]; + out.push( + seg.length === 4 ? [column, sourcesIndex, sourceLine, sourceColumn] : [column, sourcesIndex, sourceLine, sourceColumn, namesOffset + seg[NAMES_INDEX]] + ); + } + } +} +function append(arr, other) { + for (let i = 0; i < other.length; i++) arr.push(other[i]); +} +function getLine(arr, index) { + for (let i = arr.length; i <= index; i++) arr[i] = []; + return arr[index]; +} + +// src/trace-mapping.ts +var LINE_GTR_ZERO = "`line` must be greater than 0 (lines start at line 1)"; +var COL_GTR_EQ_ZERO = "`column` must be greater than or equal to 0 (columns start at column 0)"; +var LEAST_UPPER_BOUND = -1; +var GREATEST_LOWER_BOUND = 1; +var TraceMap = class { + constructor(map, mapUrl) { + const isString = typeof map === "string"; + if (!isString && map._decodedMemo) return map; + const parsed = parse(map); + const { version, file, names, sourceRoot, sources, sourcesContent } = parsed; + this.version = version; + this.file = file; + this.names = names || []; + this.sourceRoot = sourceRoot; + this.sources = sources; + this.sourcesContent = sourcesContent; + this.ignoreList = parsed.ignoreList || parsed.x_google_ignoreList || void 0; + const resolve = resolver(mapUrl, sourceRoot); + this.resolvedSources = sources.map(resolve); + const { mappings } = parsed; + if (typeof mappings === "string") { + this._encoded = mappings; + this._decoded = void 0; + } else if (Array.isArray(mappings)) { + this._encoded = void 0; + this._decoded = maybeSort(mappings, isString); + } else if (parsed.sections) { + throw new Error(`TraceMap passed sectioned source map, please use FlattenMap export instead`); + } else { + throw new Error(`invalid source map: ${JSON.stringify(parsed)}`); + } + this._decodedMemo = memoizedState(); + this._bySources = void 0; + this._bySourceMemos = void 0; + } +}; +function cast(map) { + return map; +} +function encodedMappings(map) { + var _a, _b; + return (_b = (_a = cast(map))._encoded) != null ? _b : _a._encoded = (0, import_sourcemap_codec.encode)(cast(map)._decoded); +} +function decodedMappings(map) { + var _a; + return (_a = cast(map))._decoded || (_a._decoded = (0, import_sourcemap_codec.decode)(cast(map)._encoded)); +} +function traceSegment(map, line, column) { + const decoded = decodedMappings(map); + if (line >= decoded.length) return null; + const segments = decoded[line]; + const index = traceSegmentInternal( + segments, + cast(map)._decodedMemo, + line, + column, + GREATEST_LOWER_BOUND + ); + return index === -1 ? null : segments[index]; +} +function originalPositionFor(map, needle) { + let { line, column, bias } = needle; + line--; + if (line < 0) throw new Error(LINE_GTR_ZERO); + if (column < 0) throw new Error(COL_GTR_EQ_ZERO); + const decoded = decodedMappings(map); + if (line >= decoded.length) return OMapping(null, null, null, null); + const segments = decoded[line]; + const index = traceSegmentInternal( + segments, + cast(map)._decodedMemo, + line, + column, + bias || GREATEST_LOWER_BOUND + ); + if (index === -1) return OMapping(null, null, null, null); + const segment = segments[index]; + if (segment.length === 1) return OMapping(null, null, null, null); + const { names, resolvedSources } = map; + return OMapping( + resolvedSources[segment[SOURCES_INDEX]], + segment[SOURCE_LINE] + 1, + segment[SOURCE_COLUMN], + segment.length === 5 ? names[segment[NAMES_INDEX]] : null + ); +} +function generatedPositionFor(map, needle) { + const { source, line, column, bias } = needle; + return generatedPosition(map, source, line, column, bias || GREATEST_LOWER_BOUND, false); +} +function allGeneratedPositionsFor(map, needle) { + const { source, line, column, bias } = needle; + return generatedPosition(map, source, line, column, bias || LEAST_UPPER_BOUND, true); +} +function eachMapping(map, cb) { + const decoded = decodedMappings(map); + const { names, resolvedSources } = map; + for (let i = 0; i < decoded.length; i++) { + const line = decoded[i]; + for (let j = 0; j < line.length; j++) { + const seg = line[j]; + const generatedLine = i + 1; + const generatedColumn = seg[0]; + let source = null; + let originalLine = null; + let originalColumn = null; + let name = null; + if (seg.length !== 1) { + source = resolvedSources[seg[1]]; + originalLine = seg[2] + 1; + originalColumn = seg[3]; + } + if (seg.length === 5) name = names[seg[4]]; + cb({ + generatedLine, + generatedColumn, + source, + originalLine, + originalColumn, + name + }); + } + } +} +function sourceIndex(map, source) { + const { sources, resolvedSources } = map; + let index = sources.indexOf(source); + if (index === -1) index = resolvedSources.indexOf(source); + return index; +} +function sourceContentFor(map, source) { + const { sourcesContent } = map; + if (sourcesContent == null) return null; + const index = sourceIndex(map, source); + return index === -1 ? null : sourcesContent[index]; +} +function isIgnored(map, source) { + const { ignoreList } = map; + if (ignoreList == null) return false; + const index = sourceIndex(map, source); + return index === -1 ? false : ignoreList.includes(index); +} +function presortedDecodedMap(map, mapUrl) { + const tracer = new TraceMap(clone(map, []), mapUrl); + cast(tracer)._decoded = map.mappings; + return tracer; +} +function decodedMap(map) { + return clone(map, decodedMappings(map)); +} +function encodedMap(map) { + return clone(map, encodedMappings(map)); +} +function clone(map, mappings) { + return { + version: map.version, + file: map.file, + names: map.names, + sourceRoot: map.sourceRoot, + sources: map.sources, + sourcesContent: map.sourcesContent, + mappings, + ignoreList: map.ignoreList || map.x_google_ignoreList + }; +} +function OMapping(source, line, column, name) { + return { source, line, column, name }; +} +function GMapping(line, column) { + return { line, column }; +} +function traceSegmentInternal(segments, memo, line, column, bias) { + let index = memoizedBinarySearch(segments, column, memo, line); + if (found) { + index = (bias === LEAST_UPPER_BOUND ? upperBound : lowerBound)(segments, column, index); + } else if (bias === LEAST_UPPER_BOUND) index++; + if (index === -1 || index === segments.length) return -1; + return index; +} +function sliceGeneratedPositions(segments, memo, line, column, bias) { + let min = traceSegmentInternal(segments, memo, line, column, GREATEST_LOWER_BOUND); + if (!found && bias === LEAST_UPPER_BOUND) min++; + if (min === -1 || min === segments.length) return []; + const matchedColumn = found ? column : segments[min][COLUMN]; + if (!found) min = lowerBound(segments, matchedColumn, min); + const max = upperBound(segments, matchedColumn, min); + const result = []; + for (; min <= max; min++) { + const segment = segments[min]; + result.push(GMapping(segment[REV_GENERATED_LINE] + 1, segment[REV_GENERATED_COLUMN])); + } + return result; +} +function generatedPosition(map, source, line, column, bias, all) { + var _a, _b; + line--; + if (line < 0) throw new Error(LINE_GTR_ZERO); + if (column < 0) throw new Error(COL_GTR_EQ_ZERO); + const { sources, resolvedSources } = map; + let sourceIndex2 = sources.indexOf(source); + if (sourceIndex2 === -1) sourceIndex2 = resolvedSources.indexOf(source); + if (sourceIndex2 === -1) return all ? [] : GMapping(null, null); + const bySourceMemos = (_a = cast(map))._bySourceMemos || (_a._bySourceMemos = sources.map(memoizedState)); + const generated = (_b = cast(map))._bySources || (_b._bySources = buildBySources(decodedMappings(map), bySourceMemos)); + const segments = generated[sourceIndex2][line]; + if (segments == null) return all ? [] : GMapping(null, null); + const memo = bySourceMemos[sourceIndex2]; + if (all) return sliceGeneratedPositions(segments, memo, line, column, bias); + const index = traceSegmentInternal(segments, memo, line, column, bias); + if (index === -1) return GMapping(null, null); + const segment = segments[index]; + return GMapping(segment[REV_GENERATED_LINE] + 1, segment[REV_GENERATED_COLUMN]); +} +})); +//# sourceMappingURL=trace-mapping.umd.js.map diff --git a/dg-ui/node_modules/@jridgewell/trace-mapping/dist/trace-mapping.umd.js.map b/dg-ui/node_modules/@jridgewell/trace-mapping/dist/trace-mapping.umd.js.map new file mode 100644 index 0000000..68b0c77 --- /dev/null +++ b/dg-ui/node_modules/@jridgewell/trace-mapping/dist/trace-mapping.umd.js.map @@ -0,0 +1,6 @@ +{ + "version": 3, + "sources": ["umd:@jridgewell/sourcemap-codec", "umd:@jridgewell/resolve-uri", "../src/trace-mapping.ts", "../src/resolve.ts", "../src/strip-filename.ts", "../src/sourcemap-segment.ts", "../src/sort.ts", "../src/by-source.ts", "../src/binary-search.ts", "../src/types.ts", "../src/flatten-map.ts"], + "mappings": ";;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;AAAA;AAAA,6CAAAA,SAAA;AAAA,IAAAA,QAAO,UAAU;AAAA;AAAA;;;ACAjB;AAAA,yCAAAC,SAAA;AAAA,IAAAA,QAAO,UAAU;AAAA;AAAA;;;ACAjB;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA,6BAA+B;;;ACA/B,yBAAuB;;;ACGR,SAAR,cAA+B,MAAyC;AAC7E,MAAI,CAAC,KAAM,QAAO;AAClB,QAAM,QAAQ,KAAK,YAAY,GAAG;AAClC,SAAO,KAAK,MAAM,GAAG,QAAQ,CAAC;AAChC;;;ADHe,SAAR,SACL,QACA,YACS;AACT,QAAM,OAAO,cAAc,MAAM;AAIjC,QAAM,SAAS,aAAa,aAAa,MAAM;AAE/C,SAAO,CAAC,eAAW,mBAAAC,SAAW,UAAU,UAAU,KAAK,IAAI;AAC7D;;;AEAO,IAAM,SAAS;AACf,IAAM,gBAAgB;AACtB,IAAM,cAAc;AACpB,IAAM,gBAAgB;AACtB,IAAM,cAAc;AAEpB,IAAM,qBAAqB;AAC3B,IAAM,uBAAuB;;;AClBrB,SAAR,UACL,UACA,OACsB;AACtB,QAAM,gBAAgB,wBAAwB,UAAU,CAAC;AACzD,MAAI,kBAAkB,SAAS,OAAQ,QAAO;AAI9C,MAAI,CAAC,MAAO,YAAW,SAAS,MAAM;AAEtC,WAAS,IAAI,eAAe,IAAI,SAAS,QAAQ,IAAI,wBAAwB,UAAU,IAAI,CAAC,GAAG;AAC7F,aAAS,CAAC,IAAI,aAAa,SAAS,CAAC,GAAG,KAAK;AAAA,EAC/C;AACA,SAAO;AACT;AAEA,SAAS,wBAAwB,UAAgC,OAAuB;AACtF,WAAS,IAAI,OAAO,IAAI,SAAS,QAAQ,KAAK;AAC5C,QAAI,CAAC,SAAS,SAAS,CAAC,CAAC,EAAG,QAAO;AAAA,EACrC;AACA,SAAO,SAAS;AAClB;AAEA,SAAS,SAAS,MAAmC;AACnD,WAAS,IAAI,GAAG,IAAI,KAAK,QAAQ,KAAK;AACpC,QAAI,KAAK,CAAC,EAAE,MAAM,IAAI,KAAK,IAAI,CAAC,EAAE,MAAM,GAAG;AACzC,aAAO;AAAA,IACT;AAAA,EACF;AACA,SAAO;AACT;AAEA,SAAS,aAAa,MAA0B,OAAoC;AAClF,MAAI,CAAC,MAAO,QAAO,KAAK,MAAM;AAC9B,SAAO,KAAK,KAAK,cAAc;AACjC;AAEO,SAAS,eAA4D,GAAM,GAAc;AAC9F,SAAO,EAAE,MAAM,IAAI,EAAE,MAAM;AAC7B;;;ACnCe,SAAR,eACL,SACA,OACU;AACV,QAAM,UAAoB,MAAM,IAAI,MAAM,CAAC,CAAC;AAE5C,WAAS,IAAI,GAAG,IAAI,QAAQ,QAAQ,KAAK;AACvC,UAAM,OAAO,QAAQ,CAAC;AACtB,aAAS,IAAI,GAAG,IAAI,KAAK,QAAQ,KAAK;AACpC,YAAM,MAAM,KAAK,CAAC;AAClB,UAAI,IAAI,WAAW,EAAG;AAEtB,YAAMC,eAAc,IAAI,aAAa;AACrC,YAAM,aAAa,IAAI,WAAW;AAClC,YAAM,eAAe,IAAI,aAAa;AAEtC,YAAM,SAAS,QAAQA,YAAW;AAClC,YAAM,OAAQ,4CAAuB,CAAC;AACtC,WAAK,KAAK,CAAC,cAAc,GAAG,IAAI,MAAM,CAAC,CAAC;AAAA,IAC1C;AAAA,EACF;AAEA,WAAS,IAAI,GAAG,IAAI,QAAQ,QAAQ,KAAK;AACvC,UAAM,SAAS,QAAQ,CAAC;AACxB,aAAS,IAAI,GAAG,IAAI,OAAO,QAAQ,KAAK;AACtC,YAAM,OAAO,OAAO,CAAC;AACrB,UAAI,KAAM,MAAK,KAAK,cAAc;AAAA,IACpC;AAAA,EACF;AAEA,SAAO;AACT;;;AC/BO,IAAI,QAAQ;AAkBZ,SAAS,aACd,UACA,QACA,KACA,MACQ;AACR,SAAO,OAAO,MAAM;AAClB,UAAM,MAAM,OAAQ,OAAO,OAAQ;AACnC,UAAM,MAAM,SAAS,GAAG,EAAE,MAAM,IAAI;AAEpC,QAAI,QAAQ,GAAG;AACb,cAAQ;AACR,aAAO;AAAA,IACT;AAEA,QAAI,MAAM,GAAG;AACX,YAAM,MAAM;AAAA,IACd,OAAO;AACL,aAAO,MAAM;AAAA,IACf;AAAA,EACF;AAEA,UAAQ;AACR,SAAO,MAAM;AACf;AAEO,SAAS,WACd,UACA,QACA,OACQ;AACR,WAAS,IAAI,QAAQ,GAAG,IAAI,SAAS,QAAQ,QAAQ,KAAK;AACxD,QAAI,SAAS,CAAC,EAAE,MAAM,MAAM,OAAQ;AAAA,EACtC;AACA,SAAO;AACT;AAEO,SAAS,WACd,UACA,QACA,OACQ;AACR,WAAS,IAAI,QAAQ,GAAG,KAAK,GAAG,QAAQ,KAAK;AAC3C,QAAI,SAAS,CAAC,EAAE,MAAM,MAAM,OAAQ;AAAA,EACtC;AACA,SAAO;AACT;AAEO,SAAS,gBAA2B;AACzC,SAAO;AAAA,IACL,SAAS;AAAA,IACT,YAAY;AAAA,IACZ,WAAW;AAAA,EACb;AACF;AAMO,SAAS,qBACd,UACA,QACA,OACA,KACQ;AACR,QAAM,EAAE,SAAS,YAAY,UAAU,IAAI;AAE3C,MAAI,MAAM;AACV,MAAI,OAAO,SAAS,SAAS;AAC7B,MAAI,QAAQ,SAAS;AACnB,QAAI,WAAW,YAAY;AACzB,cAAQ,cAAc,MAAM,SAAS,SAAS,EAAE,MAAM,MAAM;AAC5D,aAAO;AAAA,IACT;AAEA,QAAI,UAAU,YAAY;AAExB,YAAM,cAAc,KAAK,IAAI;AAAA,IAC/B,OAAO;AACL,aAAO;AAAA,IACT;AAAA,EACF;AACA,QAAM,UAAU;AAChB,QAAM,aAAa;AAEnB,SAAQ,MAAM,YAAY,aAAa,UAAU,QAAQ,KAAK,IAAI;AACpE;;;ACHO,SAAS,MAAS,KAA4B;AACnD,SAAO,OAAO,QAAQ,WAAW,KAAK,MAAM,GAAG,IAAK;AACtD;;;ACvFO,IAAM,aAAyB,SAAU,KAAK,QAAQ;AAC3D,QAAM,SAAS,MAAM,GAA8B;AAEnD,MAAI,EAAE,cAAc,SAAS;AAC3B,WAAO,IAAI,SAAS,QAA2D,MAAM;AAAA,EACvF;AAEA,QAAM,WAAiC,CAAC;AACxC,QAAM,UAAoB,CAAC;AAC3B,QAAM,iBAAoC,CAAC;AAC3C,QAAM,QAAkB,CAAC;AACzB,QAAM,aAAuB,CAAC;AAE9B;AAAA,IACE;AAAA,IACA;AAAA,IACA;AAAA,IACA;AAAA,IACA;AAAA,IACA;AAAA,IACA;AAAA,IACA;AAAA,IACA;AAAA,IACA;AAAA,IACA;AAAA,EACF;AAEA,QAAM,SAA2B;AAAA,IAC/B,SAAS;AAAA,IACT,MAAM,OAAO;AAAA,IACb;AAAA,IACA;AAAA,IACA;AAAA,IACA;AAAA,IACA;AAAA,EACF;AAEA,SAAO,oBAAoB,MAAM;AACnC;AAEA,SAAS,QACP,OACA,QACA,UACA,SACA,gBACA,OACA,YACA,YACA,cACA,UACA,YACA;AACA,QAAM,EAAE,SAAS,IAAI;AACrB,WAAS,IAAI,GAAG,IAAI,SAAS,QAAQ,KAAK;AACxC,UAAM,EAAE,KAAK,OAAO,IAAI,SAAS,CAAC;AAElC,QAAI,KAAK;AACT,QAAI,KAAK;AACT,QAAI,IAAI,IAAI,SAAS,QAAQ;AAC3B,YAAM,aAAa,SAAS,IAAI,CAAC,EAAE;AACnC,WAAK,KAAK,IAAI,UAAU,aAAa,WAAW,IAAI;AAEpD,UAAI,OAAO,UAAU;AACnB,aAAK,KAAK,IAAI,YAAY,eAAe,WAAW,MAAM;AAAA,MAC5D,WAAW,KAAK,UAAU;AACxB,aAAK,eAAe,WAAW;AAAA,MACjC;AAAA,IACF;AAEA;AAAA,MACE;AAAA,MACA;AAAA,MACA;AAAA,MACA;AAAA,MACA;AAAA,MACA;AAAA,MACA;AAAA,MACA,aAAa,OAAO;AAAA,MACpB,eAAe,OAAO;AAAA,MACtB;AAAA,MACA;AAAA,IACF;AAAA,EACF;AACF;AAEA,SAAS,WACP,OACA,QACA,UACA,SACA,gBACA,OACA,YACA,YACA,cACA,UACA,YACA;AACA,QAAM,SAAS,MAAM,KAAK;AAC1B,MAAI,cAAc,OAAQ,QAAO,QAAQ,GAAI,SAAmD;AAEhG,QAAM,MAAM,IAAI,SAAS,QAAQ,MAAM;AACvC,QAAM,gBAAgB,QAAQ;AAC9B,QAAM,cAAc,MAAM;AAC1B,QAAM,UAAU,gBAAgB,GAAG;AACnC,QAAM,EAAE,iBAAiB,gBAAgB,UAAU,YAAY,QAAQ,IAAI;AAE3E,SAAO,SAAS,eAAe;AAC/B,SAAO,OAAO,IAAI,KAAK;AAEvB,MAAI,SAAU,QAAO,gBAAgB,QAAQ;AAAA,MACxC,UAAS,IAAI,GAAG,IAAI,gBAAgB,QAAQ,IAAK,gBAAe,KAAK,IAAI;AAE9E,MAAI,QAAS,UAAS,IAAI,GAAG,IAAI,QAAQ,QAAQ,IAAK,YAAW,KAAK,QAAQ,CAAC,IAAI,aAAa;AAEhG,WAAS,IAAI,GAAG,IAAI,QAAQ,QAAQ,KAAK;AACvC,UAAM,QAAQ,aAAa;AAM3B,QAAI,QAAQ,SAAU;AAItB,UAAM,MAAM,QAAQ,UAAU,KAAK;AAGnC,UAAM,UAAU,MAAM,IAAI,eAAe;AAEzC,UAAM,OAAO,QAAQ,CAAC;AACtB,aAAS,IAAI,GAAG,IAAI,KAAK,QAAQ,KAAK;AACpC,YAAM,MAAM,KAAK,CAAC;AAClB,YAAM,SAAS,UAAU,IAAI,MAAM;AAInC,UAAI,UAAU,YAAY,UAAU,WAAY;AAEhD,UAAI,IAAI,WAAW,GAAG;AACpB,YAAI,KAAK,CAAC,MAAM,CAAC;AACjB;AAAA,MACF;AAEA,YAAM,eAAe,gBAAgB,IAAI,aAAa;AACtD,YAAM,aAAa,IAAI,WAAW;AAClC,YAAM,eAAe,IAAI,aAAa;AACtC,UAAI;AAAA,QACF,IAAI,WAAW,IACX,CAAC,QAAQ,cAAc,YAAY,YAAY,IAC/C,CAAC,QAAQ,cAAc,YAAY,cAAc,cAAc,IAAI,WAAW,CAAC;AAAA,MACrF;AAAA,IACF;AAAA,EACF;AACF;AAEA,SAAS,OAAU,KAAU,OAAY;AACvC,WAAS,IAAI,GAAG,IAAI,MAAM,QAAQ,IAAK,KAAI,KAAK,MAAM,CAAC,CAAC;AAC1D;AAEA,SAAS,QAAW,KAAY,OAAoB;AAClD,WAAS,IAAI,IAAI,QAAQ,KAAK,OAAO,IAAK,KAAI,CAAC,IAAI,CAAC;AACpD,SAAO,IAAI,KAAK;AAClB;;;ARhHA,IAAM,gBAAgB;AACtB,IAAM,kBAAkB;AAEjB,IAAM,oBAAoB;AAC1B,IAAM,uBAAuB;AAI7B,IAAM,WAAN,MAAoC;AAAA,EAkBzC,YAAY,KAAyB,QAAwB;AAC3D,UAAM,WAAW,OAAO,QAAQ;AAChC,QAAI,CAAC,YAAa,IAAyC,aAAc,QAAO;AAEhF,UAAM,SAAS,MAAM,GAAwC;AAE7D,UAAM,EAAE,SAAS,MAAM,OAAO,YAAY,SAAS,eAAe,IAAI;AACtE,SAAK,UAAU;AACf,SAAK,OAAO;AACZ,SAAK,QAAQ,SAAS,CAAC;AACvB,SAAK,aAAa;AAClB,SAAK,UAAU;AACf,SAAK,iBAAiB;AACtB,SAAK,aAAa,OAAO,cAAe,OAAkB,uBAAuB;AAEjF,UAAM,UAAU,SAAS,QAAQ,UAAU;AAC3C,SAAK,kBAAkB,QAAQ,IAAI,OAAO;AAE1C,UAAM,EAAE,SAAS,IAAI;AACrB,QAAI,OAAO,aAAa,UAAU;AAChC,WAAK,WAAW;AAChB,WAAK,WAAW;AAAA,IAClB,WAAW,MAAM,QAAQ,QAAQ,GAAG;AAClC,WAAK,WAAW;AAChB,WAAK,WAAW,UAAU,UAAU,QAAQ;AAAA,IAC9C,WAAY,OAAyC,UAAU;AAC7D,YAAM,IAAI,MAAM,4EAA4E;AAAA,IAC9F,OAAO;AACL,YAAM,IAAI,MAAM,uBAAuB,KAAK,UAAU,MAAM,CAAC,EAAE;AAAA,IACjE;AAEA,SAAK,eAAe,cAAc;AAClC,SAAK,aAAa;AAClB,SAAK,iBAAiB;AAAA,EACxB;AACF;AAMA,SAAS,KAAK,KAAyB;AACrC,SAAO;AACT;AAKO,SAAS,gBAAgB,KAA6C;AAzJ7E;AA0JE,UAAQ,gBAAK,GAAG,GAAE,aAAV,eAAU,eAAa,+BAAO,KAAK,GAAG,EAAE,QAAS;AAC3D;AAKO,SAAS,gBAAgB,KAAuD;AAhKvF;AAiKE,UAAQ,UAAK,GAAG,GAAE,aAAV,GAAU,eAAa,+BAAO,KAAK,GAAG,EAAE,QAAS;AAC3D;AAMO,SAAS,aACd,KACA,MACA,QACmC;AACnC,QAAM,UAAU,gBAAgB,GAAG;AAInC,MAAI,QAAQ,QAAQ,OAAQ,QAAO;AAEnC,QAAM,WAAW,QAAQ,IAAI;AAC7B,QAAM,QAAQ;AAAA,IACZ;AAAA,IACA,KAAK,GAAG,EAAE;AAAA,IACV;AAAA,IACA;AAAA,IACA;AAAA,EACF;AAEA,SAAO,UAAU,KAAK,OAAO,SAAS,KAAK;AAC7C;AAOO,SAAS,oBACd,KACA,QAC0C;AAC1C,MAAI,EAAE,MAAM,QAAQ,KAAK,IAAI;AAC7B;AACA,MAAI,OAAO,EAAG,OAAM,IAAI,MAAM,aAAa;AAC3C,MAAI,SAAS,EAAG,OAAM,IAAI,MAAM,eAAe;AAE/C,QAAM,UAAU,gBAAgB,GAAG;AAInC,MAAI,QAAQ,QAAQ,OAAQ,QAAO,SAAS,MAAM,MAAM,MAAM,IAAI;AAElE,QAAM,WAAW,QAAQ,IAAI;AAC7B,QAAM,QAAQ;AAAA,IACZ;AAAA,IACA,KAAK,GAAG,EAAE;AAAA,IACV;AAAA,IACA;AAAA,IACA,QAAQ;AAAA,EACV;AAEA,MAAI,UAAU,GAAI,QAAO,SAAS,MAAM,MAAM,MAAM,IAAI;AAExD,QAAM,UAAU,SAAS,KAAK;AAC9B,MAAI,QAAQ,WAAW,EAAG,QAAO,SAAS,MAAM,MAAM,MAAM,IAAI;AAEhE,QAAM,EAAE,OAAO,gBAAgB,IAAI;AACnC,SAAO;AAAA,IACL,gBAAgB,QAAQ,aAAa,CAAC;AAAA,IACtC,QAAQ,WAAW,IAAI;AAAA,IACvB,QAAQ,aAAa;AAAA,IACrB,QAAQ,WAAW,IAAI,MAAM,QAAQ,WAAW,CAAC,IAAI;AAAA,EACvD;AACF;AAKO,SAAS,qBACd,KACA,QAC4C;AAC5C,QAAM,EAAE,QAAQ,MAAM,QAAQ,KAAK,IAAI;AACvC,SAAO,kBAAkB,KAAK,QAAQ,MAAM,QAAQ,QAAQ,sBAAsB,KAAK;AACzF;AAKO,SAAS,yBAAyB,KAAe,QAA0C;AAChG,QAAM,EAAE,QAAQ,MAAM,QAAQ,KAAK,IAAI;AAEvC,SAAO,kBAAkB,KAAK,QAAQ,MAAM,QAAQ,QAAQ,mBAAmB,IAAI;AACrF;AAKO,SAAS,YAAY,KAAe,IAA0C;AACnF,QAAM,UAAU,gBAAgB,GAAG;AACnC,QAAM,EAAE,OAAO,gBAAgB,IAAI;AAEnC,WAAS,IAAI,GAAG,IAAI,QAAQ,QAAQ,KAAK;AACvC,UAAM,OAAO,QAAQ,CAAC;AACtB,aAAS,IAAI,GAAG,IAAI,KAAK,QAAQ,KAAK;AACpC,YAAM,MAAM,KAAK,CAAC;AAElB,YAAM,gBAAgB,IAAI;AAC1B,YAAM,kBAAkB,IAAI,CAAC;AAC7B,UAAI,SAAS;AACb,UAAI,eAAe;AACnB,UAAI,iBAAiB;AACrB,UAAI,OAAO;AACX,UAAI,IAAI,WAAW,GAAG;AACpB,iBAAS,gBAAgB,IAAI,CAAC,CAAC;AAC/B,uBAAe,IAAI,CAAC,IAAI;AACxB,yBAAiB,IAAI,CAAC;AAAA,MACxB;AACA,UAAI,IAAI,WAAW,EAAG,QAAO,MAAM,IAAI,CAAC,CAAC;AAEzC,SAAG;AAAA,QACD;AAAA,QACA;AAAA,QACA;AAAA,QACA;AAAA,QACA;AAAA,QACA;AAAA,MACF,CAAgB;AAAA,IAClB;AAAA,EACF;AACF;AAEA,SAAS,YAAY,KAAe,QAAwB;AAC1D,QAAM,EAAE,SAAS,gBAAgB,IAAI;AACrC,MAAI,QAAQ,QAAQ,QAAQ,MAAM;AAClC,MAAI,UAAU,GAAI,SAAQ,gBAAgB,QAAQ,MAAM;AACxD,SAAO;AACT;AAKO,SAAS,iBAAiB,KAAe,QAA+B;AAC7E,QAAM,EAAE,eAAe,IAAI;AAC3B,MAAI,kBAAkB,KAAM,QAAO;AACnC,QAAM,QAAQ,YAAY,KAAK,MAAM;AACrC,SAAO,UAAU,KAAK,OAAO,eAAe,KAAK;AACnD;AAKO,SAAS,UAAU,KAAe,QAAyB;AAChE,QAAM,EAAE,WAAW,IAAI;AACvB,MAAI,cAAc,KAAM,QAAO;AAC/B,QAAM,QAAQ,YAAY,KAAK,MAAM;AACrC,SAAO,UAAU,KAAK,QAAQ,WAAW,SAAS,KAAK;AACzD;AAMO,SAAS,oBAAoB,KAAuB,QAA2B;AACpF,QAAM,SAAS,IAAI,SAAS,MAAM,KAAK,CAAC,CAAC,GAAG,MAAM;AAClD,OAAK,MAAM,EAAE,WAAW,IAAI;AAC5B,SAAO;AACT;AAMO,SAAS,WACd,KACkF;AAClF,SAAO,MAAM,KAAK,gBAAgB,GAAG,CAAC;AACxC;AAMO,SAAS,WAAW,KAAiC;AAC1D,SAAO,MAAM,KAAK,gBAAgB,GAAG,CAAC;AACxC;AAEA,SAAS,MACP,KACA,UACwD;AACxD,SAAO;AAAA,IACL,SAAS,IAAI;AAAA,IACb,MAAM,IAAI;AAAA,IACV,OAAO,IAAI;AAAA,IACX,YAAY,IAAI;AAAA,IAChB,SAAS,IAAI;AAAA,IACb,gBAAgB,IAAI;AAAA,IACpB;AAAA,IACA,YAAY,IAAI,cAAe,IAAe;AAAA,EAChD;AACF;AASA,SAAS,SACP,QACA,MACA,QACA,MAC0C;AAC1C,SAAO,EAAE,QAAQ,MAAM,QAAQ,KAAK;AACtC;AAIA,SAAS,SACP,MACA,QAC4C;AAC5C,SAAO,EAAE,MAAM,OAAO;AACxB;AAgBA,SAAS,qBACP,UACA,MACA,MACA,QACA,MACQ;AACR,MAAI,QAAQ,qBAAqB,UAAU,QAAQ,MAAM,IAAI;AAC7D,MAAI,OAAS;AACX,aAAS,SAAS,oBAAoB,aAAa,YAAY,UAAU,QAAQ,KAAK;AAAA,EACxF,WAAW,SAAS,kBAAmB;AAEvC,MAAI,UAAU,MAAM,UAAU,SAAS,OAAQ,QAAO;AACtD,SAAO;AACT;AAEA,SAAS,wBACP,UACA,MACA,MACA,QACA,MACoB;AACpB,MAAI,MAAM,qBAAqB,UAAU,MAAM,MAAM,QAAQ,oBAAoB;AAQjF,MAAI,CAAC,SAAW,SAAS,kBAAmB;AAE5C,MAAI,QAAQ,MAAM,QAAQ,SAAS,OAAQ,QAAO,CAAC;AAKnD,QAAM,gBAAgB,QAAU,SAAS,SAAS,GAAG,EAAE,MAAM;AAG7D,MAAI,CAAC,MAAS,OAAM,WAAW,UAAU,eAAe,GAAG;AAC3D,QAAM,MAAM,WAAW,UAAU,eAAe,GAAG;AAEnD,QAAM,SAAS,CAAC;AAChB,SAAO,OAAO,KAAK,OAAO;AACxB,UAAM,UAAU,SAAS,GAAG;AAC5B,WAAO,KAAK,SAAS,QAAQ,kBAAkB,IAAI,GAAG,QAAQ,oBAAoB,CAAC,CAAC;AAAA,EACtF;AACA,SAAO;AACT;AAkBA,SAAS,kBACP,KACA,QACA,MACA,QACA,MACA,KACiE;AA5dnE;AA6dE;AACA,MAAI,OAAO,EAAG,OAAM,IAAI,MAAM,aAAa;AAC3C,MAAI,SAAS,EAAG,OAAM,IAAI,MAAM,eAAe;AAE/C,QAAM,EAAE,SAAS,gBAAgB,IAAI;AACrC,MAAIC,eAAc,QAAQ,QAAQ,MAAM;AACxC,MAAIA,iBAAgB,GAAI,CAAAA,eAAc,gBAAgB,QAAQ,MAAM;AACpE,MAAIA,iBAAgB,GAAI,QAAO,MAAM,CAAC,IAAI,SAAS,MAAM,IAAI;AAE7D,QAAM,iBAAiB,UAAK,GAAG,GAAE,mBAAV,GAAU,iBAAmB,QAAQ,IAAI,aAAa;AAC7E,QAAM,aAAa,UAAK,GAAG,GAAE,eAAV,GAAU,aAAe,eAAe,gBAAgB,GAAG,GAAG,aAAa;AAE9F,QAAM,WAAW,UAAUA,YAAW,EAAE,IAAI;AAC5C,MAAI,YAAY,KAAM,QAAO,MAAM,CAAC,IAAI,SAAS,MAAM,IAAI;AAE3D,QAAM,OAAO,cAAcA,YAAW;AAEtC,MAAI,IAAK,QAAO,wBAAwB,UAAU,MAAM,MAAM,QAAQ,IAAI;AAE1E,QAAM,QAAQ,qBAAqB,UAAU,MAAM,MAAM,QAAQ,IAAI;AACrE,MAAI,UAAU,GAAI,QAAO,SAAS,MAAM,IAAI;AAE5C,QAAM,UAAU,SAAS,KAAK;AAC9B,SAAO,SAAS,QAAQ,kBAAkB,IAAI,GAAG,QAAQ,oBAAoB,CAAC;AAChF;", + "names": ["module", "module", "resolveUri", "sourceIndex", "sourceIndex"] +} diff --git a/dg-ui/node_modules/@jridgewell/trace-mapping/package.json b/dg-ui/node_modules/@jridgewell/trace-mapping/package.json new file mode 100644 index 0000000..9d3a1c0 --- /dev/null +++ b/dg-ui/node_modules/@jridgewell/trace-mapping/package.json @@ -0,0 +1,67 @@ +{ + "name": "@jridgewell/trace-mapping", + "version": "0.3.31", + "description": "Trace the original position through a source map", + "keywords": [ + "source", + "map" + ], + "main": "dist/trace-mapping.umd.js", + "module": "dist/trace-mapping.mjs", + "types": "types/trace-mapping.d.cts", + "files": [ + "dist", + "src", + "types" + ], + "exports": { + ".": [ + { + "import": { + "types": "./types/trace-mapping.d.mts", + "default": "./dist/trace-mapping.mjs" + }, + "default": { + "types": "./types/trace-mapping.d.cts", + "default": "./dist/trace-mapping.umd.js" + } + }, + "./dist/trace-mapping.umd.js" + ], + "./package.json": "./package.json" + }, + "scripts": { + "benchmark": "run-s build:code benchmark:*", + "benchmark:install": "cd benchmark && npm install", + "benchmark:only": "node --expose-gc benchmark/index.mjs", + "build": "run-s -n build:code build:types", + "build:code": "node ../../esbuild.mjs trace-mapping.ts", + "build:types": "run-s build:types:force build:types:emit build:types:mts", + "build:types:force": "rimraf tsconfig.build.tsbuildinfo", + "build:types:emit": "tsc --project tsconfig.build.json", + "build:types:mts": "node ../../mts-types.mjs", + "clean": "run-s -n clean:code clean:types", + "clean:code": "tsc --build --clean tsconfig.build.json", + "clean:types": "rimraf dist types", + "test": "run-s -n test:types test:only test:format", + "test:format": "prettier --check '{src,test}/**/*.ts'", + "test:only": "mocha", + "test:types": "eslint '{src,test}/**/*.ts'", + "lint": "run-s -n lint:types lint:format", + "lint:format": "npm run test:format -- --write", + "lint:types": "npm run test:types -- --fix", + "prepublishOnly": "npm run-s -n build test" + }, + "homepage": "https://github.com/jridgewell/sourcemaps/tree/main/packages/trace-mapping", + "repository": { + "type": "git", + "url": "git+https://github.com/jridgewell/sourcemaps.git", + "directory": "packages/trace-mapping" + }, + "author": "Justin Ridgewell ", + "license": "MIT", + "dependencies": { + "@jridgewell/resolve-uri": "^3.1.0", + "@jridgewell/sourcemap-codec": "^1.4.14" + } +} diff --git a/dg-ui/node_modules/@jridgewell/trace-mapping/src/binary-search.ts b/dg-ui/node_modules/@jridgewell/trace-mapping/src/binary-search.ts new file mode 100644 index 0000000..c1144ad --- /dev/null +++ b/dg-ui/node_modules/@jridgewell/trace-mapping/src/binary-search.ts @@ -0,0 +1,115 @@ +import type { SourceMapSegment, ReverseSegment } from './sourcemap-segment'; +import { COLUMN } from './sourcemap-segment'; + +export type MemoState = { + lastKey: number; + lastNeedle: number; + lastIndex: number; +}; + +export let found = false; + +/** + * A binary search implementation that returns the index if a match is found. + * If no match is found, then the left-index (the index associated with the item that comes just + * before the desired index) is returned. To maintain proper sort order, a splice would happen at + * the next index: + * + * ```js + * const array = [1, 3]; + * const needle = 2; + * const index = binarySearch(array, needle, (item, needle) => item - needle); + * + * assert.equal(index, 0); + * array.splice(index + 1, 0, needle); + * assert.deepEqual(array, [1, 2, 3]); + * ``` + */ +export function binarySearch( + haystack: SourceMapSegment[] | ReverseSegment[], + needle: number, + low: number, + high: number, +): number { + while (low <= high) { + const mid = low + ((high - low) >> 1); + const cmp = haystack[mid][COLUMN] - needle; + + if (cmp === 0) { + found = true; + return mid; + } + + if (cmp < 0) { + low = mid + 1; + } else { + high = mid - 1; + } + } + + found = false; + return low - 1; +} + +export function upperBound( + haystack: SourceMapSegment[] | ReverseSegment[], + needle: number, + index: number, +): number { + for (let i = index + 1; i < haystack.length; index = i++) { + if (haystack[i][COLUMN] !== needle) break; + } + return index; +} + +export function lowerBound( + haystack: SourceMapSegment[] | ReverseSegment[], + needle: number, + index: number, +): number { + for (let i = index - 1; i >= 0; index = i--) { + if (haystack[i][COLUMN] !== needle) break; + } + return index; +} + +export function memoizedState(): MemoState { + return { + lastKey: -1, + lastNeedle: -1, + lastIndex: -1, + }; +} + +/** + * This overly complicated beast is just to record the last tested line/column and the resulting + * index, allowing us to skip a few tests if mappings are monotonically increasing. + */ +export function memoizedBinarySearch( + haystack: SourceMapSegment[] | ReverseSegment[], + needle: number, + state: MemoState, + key: number, +): number { + const { lastKey, lastNeedle, lastIndex } = state; + + let low = 0; + let high = haystack.length - 1; + if (key === lastKey) { + if (needle === lastNeedle) { + found = lastIndex !== -1 && haystack[lastIndex][COLUMN] === needle; + return lastIndex; + } + + if (needle >= lastNeedle) { + // lastIndex may be -1 if the previous needle was not found. + low = lastIndex === -1 ? 0 : lastIndex; + } else { + high = lastIndex; + } + } + state.lastKey = key; + state.lastNeedle = needle; + + return (state.lastIndex = binarySearch(haystack, needle, low, high)); +} diff --git a/dg-ui/node_modules/@jridgewell/trace-mapping/src/by-source.ts b/dg-ui/node_modules/@jridgewell/trace-mapping/src/by-source.ts new file mode 100644 index 0000000..1da6af0 --- /dev/null +++ b/dg-ui/node_modules/@jridgewell/trace-mapping/src/by-source.ts @@ -0,0 +1,41 @@ +import { COLUMN, SOURCES_INDEX, SOURCE_LINE, SOURCE_COLUMN } from './sourcemap-segment'; +import { sortComparator } from './sort'; + +import type { ReverseSegment, SourceMapSegment } from './sourcemap-segment'; + +export type Source = ReverseSegment[][]; + +// Rebuilds the original source files, with mappings that are ordered by source line/column instead +// of generated line/column. +export default function buildBySources( + decoded: readonly SourceMapSegment[][], + memos: unknown[], +): Source[] { + const sources: Source[] = memos.map(() => []); + + for (let i = 0; i < decoded.length; i++) { + const line = decoded[i]; + for (let j = 0; j < line.length; j++) { + const seg = line[j]; + if (seg.length === 1) continue; + + const sourceIndex = seg[SOURCES_INDEX]; + const sourceLine = seg[SOURCE_LINE]; + const sourceColumn = seg[SOURCE_COLUMN]; + + const source = sources[sourceIndex]; + const segs = (source[sourceLine] ||= []); + segs.push([sourceColumn, i, seg[COLUMN]]); + } + } + + for (let i = 0; i < sources.length; i++) { + const source = sources[i]; + for (let j = 0; j < source.length; j++) { + const line = source[j]; + if (line) line.sort(sortComparator); + } + } + + return sources; +} diff --git a/dg-ui/node_modules/@jridgewell/trace-mapping/src/flatten-map.ts b/dg-ui/node_modules/@jridgewell/trace-mapping/src/flatten-map.ts new file mode 100644 index 0000000..61ac40c --- /dev/null +++ b/dg-ui/node_modules/@jridgewell/trace-mapping/src/flatten-map.ts @@ -0,0 +1,192 @@ +import { TraceMap, presortedDecodedMap, decodedMappings } from './trace-mapping'; +import { + COLUMN, + SOURCES_INDEX, + SOURCE_LINE, + SOURCE_COLUMN, + NAMES_INDEX, +} from './sourcemap-segment'; +import { parse } from './types'; + +import type { + DecodedSourceMap, + DecodedSourceMapXInput, + EncodedSourceMapXInput, + SectionedSourceMapXInput, + SectionedSourceMapInput, + SectionXInput, + Ro, +} from './types'; +import type { SourceMapSegment } from './sourcemap-segment'; + +type FlattenMap = { + new (map: Ro, mapUrl?: string | null): TraceMap; + (map: Ro, mapUrl?: string | null): TraceMap; +}; + +export const FlattenMap: FlattenMap = function (map, mapUrl) { + const parsed = parse(map as SectionedSourceMapInput); + + if (!('sections' in parsed)) { + return new TraceMap(parsed as DecodedSourceMapXInput | EncodedSourceMapXInput, mapUrl); + } + + const mappings: SourceMapSegment[][] = []; + const sources: string[] = []; + const sourcesContent: (string | null)[] = []; + const names: string[] = []; + const ignoreList: number[] = []; + + recurse( + parsed, + mapUrl, + mappings, + sources, + sourcesContent, + names, + ignoreList, + 0, + 0, + Infinity, + Infinity, + ); + + const joined: DecodedSourceMap = { + version: 3, + file: parsed.file, + names, + sources, + sourcesContent, + mappings, + ignoreList, + }; + + return presortedDecodedMap(joined); +} as FlattenMap; + +function recurse( + input: SectionedSourceMapXInput, + mapUrl: string | null | undefined, + mappings: SourceMapSegment[][], + sources: string[], + sourcesContent: (string | null)[], + names: string[], + ignoreList: number[], + lineOffset: number, + columnOffset: number, + stopLine: number, + stopColumn: number, +) { + const { sections } = input; + for (let i = 0; i < sections.length; i++) { + const { map, offset } = sections[i]; + + let sl = stopLine; + let sc = stopColumn; + if (i + 1 < sections.length) { + const nextOffset = sections[i + 1].offset; + sl = Math.min(stopLine, lineOffset + nextOffset.line); + + if (sl === stopLine) { + sc = Math.min(stopColumn, columnOffset + nextOffset.column); + } else if (sl < stopLine) { + sc = columnOffset + nextOffset.column; + } + } + + addSection( + map, + mapUrl, + mappings, + sources, + sourcesContent, + names, + ignoreList, + lineOffset + offset.line, + columnOffset + offset.column, + sl, + sc, + ); + } +} + +function addSection( + input: SectionXInput['map'], + mapUrl: string | null | undefined, + mappings: SourceMapSegment[][], + sources: string[], + sourcesContent: (string | null)[], + names: string[], + ignoreList: number[], + lineOffset: number, + columnOffset: number, + stopLine: number, + stopColumn: number, +) { + const parsed = parse(input); + if ('sections' in parsed) return recurse(...(arguments as unknown as Parameters)); + + const map = new TraceMap(parsed, mapUrl); + const sourcesOffset = sources.length; + const namesOffset = names.length; + const decoded = decodedMappings(map); + const { resolvedSources, sourcesContent: contents, ignoreList: ignores } = map; + + append(sources, resolvedSources); + append(names, map.names); + + if (contents) append(sourcesContent, contents); + else for (let i = 0; i < resolvedSources.length; i++) sourcesContent.push(null); + + if (ignores) for (let i = 0; i < ignores.length; i++) ignoreList.push(ignores[i] + sourcesOffset); + + for (let i = 0; i < decoded.length; i++) { + const lineI = lineOffset + i; + + // We can only add so many lines before we step into the range that the next section's map + // controls. When we get to the last line, then we'll start checking the segments to see if + // they've crossed into the column range. But it may not have any columns that overstep, so we + // still need to check that we don't overstep lines, too. + if (lineI > stopLine) return; + + // The out line may already exist in mappings (if we're continuing the line started by a + // previous section). Or, we may have jumped ahead several lines to start this section. + const out = getLine(mappings, lineI); + // On the 0th loop, the section's column offset shifts us forward. On all other lines (since the + // map can be multiple lines), it doesn't. + const cOffset = i === 0 ? columnOffset : 0; + + const line = decoded[i]; + for (let j = 0; j < line.length; j++) { + const seg = line[j]; + const column = cOffset + seg[COLUMN]; + + // If this segment steps into the column range that the next section's map controls, we need + // to stop early. + if (lineI === stopLine && column >= stopColumn) return; + + if (seg.length === 1) { + out.push([column]); + continue; + } + + const sourcesIndex = sourcesOffset + seg[SOURCES_INDEX]; + const sourceLine = seg[SOURCE_LINE]; + const sourceColumn = seg[SOURCE_COLUMN]; + out.push( + seg.length === 4 + ? [column, sourcesIndex, sourceLine, sourceColumn] + : [column, sourcesIndex, sourceLine, sourceColumn, namesOffset + seg[NAMES_INDEX]], + ); + } + } +} + +function append(arr: T[], other: T[]) { + for (let i = 0; i < other.length; i++) arr.push(other[i]); +} + +function getLine(arr: T[][], index: number): T[] { + for (let i = arr.length; i <= index; i++) arr[i] = []; + return arr[index]; +} diff --git a/dg-ui/node_modules/@jridgewell/trace-mapping/src/resolve.ts b/dg-ui/node_modules/@jridgewell/trace-mapping/src/resolve.ts new file mode 100644 index 0000000..30bfa3b --- /dev/null +++ b/dg-ui/node_modules/@jridgewell/trace-mapping/src/resolve.ts @@ -0,0 +1,16 @@ +import resolveUri from '@jridgewell/resolve-uri'; +import stripFilename from './strip-filename'; + +type Resolve = (source: string | null) => string; +export default function resolver( + mapUrl: string | null | undefined, + sourceRoot: string | undefined, +): Resolve { + const from = stripFilename(mapUrl); + // The sourceRoot is always treated as a directory, if it's not empty. + // https://github.com/mozilla/source-map/blob/8cb3ee57/lib/util.js#L327 + // https://github.com/chromium/chromium/blob/da4adbb3/third_party/blink/renderer/devtools/front_end/sdk/SourceMap.js#L400-L401 + const prefix = sourceRoot ? sourceRoot + '/' : ''; + + return (source) => resolveUri(prefix + (source || ''), from); +} diff --git a/dg-ui/node_modules/@jridgewell/trace-mapping/src/sort.ts b/dg-ui/node_modules/@jridgewell/trace-mapping/src/sort.ts new file mode 100644 index 0000000..5d016cb --- /dev/null +++ b/dg-ui/node_modules/@jridgewell/trace-mapping/src/sort.ts @@ -0,0 +1,45 @@ +import { COLUMN } from './sourcemap-segment'; + +import type { ReverseSegment, SourceMapSegment } from './sourcemap-segment'; + +export default function maybeSort( + mappings: SourceMapSegment[][], + owned: boolean, +): SourceMapSegment[][] { + const unsortedIndex = nextUnsortedSegmentLine(mappings, 0); + if (unsortedIndex === mappings.length) return mappings; + + // If we own the array (meaning we parsed it from JSON), then we're free to directly mutate it. If + // not, we do not want to modify the consumer's input array. + if (!owned) mappings = mappings.slice(); + + for (let i = unsortedIndex; i < mappings.length; i = nextUnsortedSegmentLine(mappings, i + 1)) { + mappings[i] = sortSegments(mappings[i], owned); + } + return mappings; +} + +function nextUnsortedSegmentLine(mappings: SourceMapSegment[][], start: number): number { + for (let i = start; i < mappings.length; i++) { + if (!isSorted(mappings[i])) return i; + } + return mappings.length; +} + +function isSorted(line: SourceMapSegment[]): boolean { + for (let j = 1; j < line.length; j++) { + if (line[j][COLUMN] < line[j - 1][COLUMN]) { + return false; + } + } + return true; +} + +function sortSegments(line: SourceMapSegment[], owned: boolean): SourceMapSegment[] { + if (!owned) line = line.slice(); + return line.sort(sortComparator); +} + +export function sortComparator(a: T, b: T): number { + return a[COLUMN] - b[COLUMN]; +} diff --git a/dg-ui/node_modules/@jridgewell/trace-mapping/src/sourcemap-segment.ts b/dg-ui/node_modules/@jridgewell/trace-mapping/src/sourcemap-segment.ts new file mode 100644 index 0000000..94f1b6a --- /dev/null +++ b/dg-ui/node_modules/@jridgewell/trace-mapping/src/sourcemap-segment.ts @@ -0,0 +1,23 @@ +type GeneratedColumn = number; +type SourcesIndex = number; +type SourceLine = number; +type SourceColumn = number; +type NamesIndex = number; + +type GeneratedLine = number; + +export type SourceMapSegment = + | [GeneratedColumn] + | [GeneratedColumn, SourcesIndex, SourceLine, SourceColumn] + | [GeneratedColumn, SourcesIndex, SourceLine, SourceColumn, NamesIndex]; + +export type ReverseSegment = [SourceColumn, GeneratedLine, GeneratedColumn]; + +export const COLUMN = 0; +export const SOURCES_INDEX = 1; +export const SOURCE_LINE = 2; +export const SOURCE_COLUMN = 3; +export const NAMES_INDEX = 4; + +export const REV_GENERATED_LINE = 1; +export const REV_GENERATED_COLUMN = 2; diff --git a/dg-ui/node_modules/@jridgewell/trace-mapping/src/strip-filename.ts b/dg-ui/node_modules/@jridgewell/trace-mapping/src/strip-filename.ts new file mode 100644 index 0000000..2c88980 --- /dev/null +++ b/dg-ui/node_modules/@jridgewell/trace-mapping/src/strip-filename.ts @@ -0,0 +1,8 @@ +/** + * Removes everything after the last "/", but leaves the slash. + */ +export default function stripFilename(path: string | undefined | null): string { + if (!path) return ''; + const index = path.lastIndexOf('/'); + return path.slice(0, index + 1); +} diff --git a/dg-ui/node_modules/@jridgewell/trace-mapping/src/trace-mapping.ts b/dg-ui/node_modules/@jridgewell/trace-mapping/src/trace-mapping.ts new file mode 100644 index 0000000..0b793d5 --- /dev/null +++ b/dg-ui/node_modules/@jridgewell/trace-mapping/src/trace-mapping.ts @@ -0,0 +1,502 @@ +import { encode, decode } from '@jridgewell/sourcemap-codec'; + +import resolver from './resolve'; +import maybeSort from './sort'; +import buildBySources from './by-source'; +import { + memoizedState, + memoizedBinarySearch, + upperBound, + lowerBound, + found as bsFound, +} from './binary-search'; +import { + COLUMN, + SOURCES_INDEX, + SOURCE_LINE, + SOURCE_COLUMN, + NAMES_INDEX, + REV_GENERATED_LINE, + REV_GENERATED_COLUMN, +} from './sourcemap-segment'; +import { parse } from './types'; + +import type { SourceMapSegment, ReverseSegment } from './sourcemap-segment'; +import type { + SourceMapV3, + DecodedSourceMap, + EncodedSourceMap, + InvalidOriginalMapping, + OriginalMapping, + InvalidGeneratedMapping, + GeneratedMapping, + SourceMapInput, + Needle, + SourceNeedle, + SourceMap, + EachMapping, + Bias, + XInput, + SectionedSourceMap, + Ro, +} from './types'; +import type { Source } from './by-source'; +import type { MemoState } from './binary-search'; + +export type { SourceMapSegment } from './sourcemap-segment'; +export type { + SourceMap, + DecodedSourceMap, + EncodedSourceMap, + Section, + SectionedSourceMap, + SourceMapV3, + Bias, + EachMapping, + GeneratedMapping, + InvalidGeneratedMapping, + InvalidOriginalMapping, + Needle, + OriginalMapping, + OriginalMapping as Mapping, + SectionedSourceMapInput, + SourceMapInput, + SourceNeedle, + XInput, + EncodedSourceMapXInput, + DecodedSourceMapXInput, + SectionedSourceMapXInput, + SectionXInput, +} from './types'; + +interface PublicMap { + _encoded: TraceMap['_encoded']; + _decoded: TraceMap['_decoded']; + _decodedMemo: TraceMap['_decodedMemo']; + _bySources: TraceMap['_bySources']; + _bySourceMemos: TraceMap['_bySourceMemos']; +} + +const LINE_GTR_ZERO = '`line` must be greater than 0 (lines start at line 1)'; +const COL_GTR_EQ_ZERO = '`column` must be greater than or equal to 0 (columns start at column 0)'; + +export const LEAST_UPPER_BOUND = -1; +export const GREATEST_LOWER_BOUND = 1; + +export { FlattenMap, FlattenMap as AnyMap } from './flatten-map'; + +export class TraceMap implements SourceMap { + declare version: SourceMapV3['version']; + declare file: SourceMapV3['file']; + declare names: SourceMapV3['names']; + declare sourceRoot: SourceMapV3['sourceRoot']; + declare sources: SourceMapV3['sources']; + declare sourcesContent: SourceMapV3['sourcesContent']; + declare ignoreList: SourceMapV3['ignoreList']; + + declare resolvedSources: string[]; + declare private _encoded: string | undefined; + + declare private _decoded: SourceMapSegment[][] | undefined; + declare private _decodedMemo: MemoState; + + declare private _bySources: Source[] | undefined; + declare private _bySourceMemos: MemoState[] | undefined; + + constructor(map: Ro, mapUrl?: string | null) { + const isString = typeof map === 'string'; + if (!isString && (map as unknown as { _decodedMemo: any })._decodedMemo) return map as TraceMap; + + const parsed = parse(map as Exclude); + + const { version, file, names, sourceRoot, sources, sourcesContent } = parsed; + this.version = version; + this.file = file; + this.names = names || []; + this.sourceRoot = sourceRoot; + this.sources = sources; + this.sourcesContent = sourcesContent; + this.ignoreList = parsed.ignoreList || (parsed as XInput).x_google_ignoreList || undefined; + + const resolve = resolver(mapUrl, sourceRoot); + this.resolvedSources = sources.map(resolve); + + const { mappings } = parsed; + if (typeof mappings === 'string') { + this._encoded = mappings; + this._decoded = undefined; + } else if (Array.isArray(mappings)) { + this._encoded = undefined; + this._decoded = maybeSort(mappings, isString); + } else if ((parsed as unknown as SectionedSourceMap).sections) { + throw new Error(`TraceMap passed sectioned source map, please use FlattenMap export instead`); + } else { + throw new Error(`invalid source map: ${JSON.stringify(parsed)}`); + } + + this._decodedMemo = memoizedState(); + this._bySources = undefined; + this._bySourceMemos = undefined; + } +} + +/** + * Typescript doesn't allow friend access to private fields, so this just casts the map into a type + * with public access modifiers. + */ +function cast(map: unknown): PublicMap { + return map as any; +} + +/** + * Returns the encoded (VLQ string) form of the SourceMap's mappings field. + */ +export function encodedMappings(map: TraceMap): EncodedSourceMap['mappings'] { + return (cast(map)._encoded ??= encode(cast(map)._decoded!)); +} + +/** + * Returns the decoded (array of lines of segments) form of the SourceMap's mappings field. + */ +export function decodedMappings(map: TraceMap): Readonly { + return (cast(map)._decoded ||= decode(cast(map)._encoded!)); +} + +/** + * A low-level API to find the segment associated with a generated line/column (think, from a + * stack trace). Line and column here are 0-based, unlike `originalPositionFor`. + */ +export function traceSegment( + map: TraceMap, + line: number, + column: number, +): Readonly | null { + const decoded = decodedMappings(map); + + // It's common for parent source maps to have pointers to lines that have no + // mapping (like a "//# sourceMappingURL=") at the end of the child file. + if (line >= decoded.length) return null; + + const segments = decoded[line]; + const index = traceSegmentInternal( + segments, + cast(map)._decodedMemo, + line, + column, + GREATEST_LOWER_BOUND, + ); + + return index === -1 ? null : segments[index]; +} + +/** + * A higher-level API to find the source/line/column associated with a generated line/column + * (think, from a stack trace). Line is 1-based, but column is 0-based, due to legacy behavior in + * `source-map` library. + */ +export function originalPositionFor( + map: TraceMap, + needle: Needle, +): OriginalMapping | InvalidOriginalMapping { + let { line, column, bias } = needle; + line--; + if (line < 0) throw new Error(LINE_GTR_ZERO); + if (column < 0) throw new Error(COL_GTR_EQ_ZERO); + + const decoded = decodedMappings(map); + + // It's common for parent source maps to have pointers to lines that have no + // mapping (like a "//# sourceMappingURL=") at the end of the child file. + if (line >= decoded.length) return OMapping(null, null, null, null); + + const segments = decoded[line]; + const index = traceSegmentInternal( + segments, + cast(map)._decodedMemo, + line, + column, + bias || GREATEST_LOWER_BOUND, + ); + + if (index === -1) return OMapping(null, null, null, null); + + const segment = segments[index]; + if (segment.length === 1) return OMapping(null, null, null, null); + + const { names, resolvedSources } = map; + return OMapping( + resolvedSources[segment[SOURCES_INDEX]], + segment[SOURCE_LINE] + 1, + segment[SOURCE_COLUMN], + segment.length === 5 ? names[segment[NAMES_INDEX]] : null, + ); +} + +/** + * Finds the generated line/column position of the provided source/line/column source position. + */ +export function generatedPositionFor( + map: TraceMap, + needle: SourceNeedle, +): GeneratedMapping | InvalidGeneratedMapping { + const { source, line, column, bias } = needle; + return generatedPosition(map, source, line, column, bias || GREATEST_LOWER_BOUND, false); +} + +/** + * Finds all generated line/column positions of the provided source/line/column source position. + */ +export function allGeneratedPositionsFor(map: TraceMap, needle: SourceNeedle): GeneratedMapping[] { + const { source, line, column, bias } = needle; + // SourceMapConsumer uses LEAST_UPPER_BOUND for some reason, so we follow suit. + return generatedPosition(map, source, line, column, bias || LEAST_UPPER_BOUND, true); +} + +/** + * Iterates each mapping in generated position order. + */ +export function eachMapping(map: TraceMap, cb: (mapping: EachMapping) => void): void { + const decoded = decodedMappings(map); + const { names, resolvedSources } = map; + + for (let i = 0; i < decoded.length; i++) { + const line = decoded[i]; + for (let j = 0; j < line.length; j++) { + const seg = line[j]; + + const generatedLine = i + 1; + const generatedColumn = seg[0]; + let source = null; + let originalLine = null; + let originalColumn = null; + let name = null; + if (seg.length !== 1) { + source = resolvedSources[seg[1]]; + originalLine = seg[2] + 1; + originalColumn = seg[3]; + } + if (seg.length === 5) name = names[seg[4]]; + + cb({ + generatedLine, + generatedColumn, + source, + originalLine, + originalColumn, + name, + } as EachMapping); + } + } +} + +function sourceIndex(map: TraceMap, source: string): number { + const { sources, resolvedSources } = map; + let index = sources.indexOf(source); + if (index === -1) index = resolvedSources.indexOf(source); + return index; +} + +/** + * Retrieves the source content for a particular source, if its found. Returns null if not. + */ +export function sourceContentFor(map: TraceMap, source: string): string | null { + const { sourcesContent } = map; + if (sourcesContent == null) return null; + const index = sourceIndex(map, source); + return index === -1 ? null : sourcesContent[index]; +} + +/** + * Determines if the source is marked to ignore by the source map. + */ +export function isIgnored(map: TraceMap, source: string): boolean { + const { ignoreList } = map; + if (ignoreList == null) return false; + const index = sourceIndex(map, source); + return index === -1 ? false : ignoreList.includes(index); +} + +/** + * A helper that skips sorting of the input map's mappings array, which can be expensive for larger + * maps. + */ +export function presortedDecodedMap(map: DecodedSourceMap, mapUrl?: string): TraceMap { + const tracer = new TraceMap(clone(map, []), mapUrl); + cast(tracer)._decoded = map.mappings; + return tracer; +} + +/** + * Returns a sourcemap object (with decoded mappings) suitable for passing to a library that expects + * a sourcemap, or to JSON.stringify. + */ +export function decodedMap( + map: TraceMap, +): Omit & { mappings: readonly SourceMapSegment[][] } { + return clone(map, decodedMappings(map)); +} + +/** + * Returns a sourcemap object (with encoded mappings) suitable for passing to a library that expects + * a sourcemap, or to JSON.stringify. + */ +export function encodedMap(map: TraceMap): EncodedSourceMap { + return clone(map, encodedMappings(map)); +} + +function clone( + map: TraceMap | DecodedSourceMap, + mappings: T, +): T extends string ? EncodedSourceMap : DecodedSourceMap { + return { + version: map.version, + file: map.file, + names: map.names, + sourceRoot: map.sourceRoot, + sources: map.sources, + sourcesContent: map.sourcesContent, + mappings, + ignoreList: map.ignoreList || (map as XInput).x_google_ignoreList, + } as any; +} + +function OMapping(source: null, line: null, column: null, name: null): InvalidOriginalMapping; +function OMapping( + source: string, + line: number, + column: number, + name: string | null, +): OriginalMapping; +function OMapping( + source: string | null, + line: number | null, + column: number | null, + name: string | null, +): OriginalMapping | InvalidOriginalMapping { + return { source, line, column, name } as any; +} + +function GMapping(line: null, column: null): InvalidGeneratedMapping; +function GMapping(line: number, column: number): GeneratedMapping; +function GMapping( + line: number | null, + column: number | null, +): GeneratedMapping | InvalidGeneratedMapping { + return { line, column } as any; +} + +function traceSegmentInternal( + segments: SourceMapSegment[], + memo: MemoState, + line: number, + column: number, + bias: Bias, +): number; +function traceSegmentInternal( + segments: ReverseSegment[], + memo: MemoState, + line: number, + column: number, + bias: Bias, +): number; +function traceSegmentInternal( + segments: SourceMapSegment[] | ReverseSegment[], + memo: MemoState, + line: number, + column: number, + bias: Bias, +): number { + let index = memoizedBinarySearch(segments, column, memo, line); + if (bsFound) { + index = (bias === LEAST_UPPER_BOUND ? upperBound : lowerBound)(segments, column, index); + } else if (bias === LEAST_UPPER_BOUND) index++; + + if (index === -1 || index === segments.length) return -1; + return index; +} + +function sliceGeneratedPositions( + segments: ReverseSegment[], + memo: MemoState, + line: number, + column: number, + bias: Bias, +): GeneratedMapping[] { + let min = traceSegmentInternal(segments, memo, line, column, GREATEST_LOWER_BOUND); + + // We ignored the bias when tracing the segment so that we're guarnateed to find the first (in + // insertion order) segment that matched. Even if we did respect the bias when tracing, we would + // still need to call `lowerBound()` to find the first segment, which is slower than just looking + // for the GREATEST_LOWER_BOUND to begin with. The only difference that matters for us is when the + // binary search didn't match, in which case GREATEST_LOWER_BOUND just needs to increment to + // match LEAST_UPPER_BOUND. + if (!bsFound && bias === LEAST_UPPER_BOUND) min++; + + if (min === -1 || min === segments.length) return []; + + // We may have found the segment that started at an earlier column. If this is the case, then we + // need to slice all generated segments that match _that_ column, because all such segments span + // to our desired column. + const matchedColumn = bsFound ? column : segments[min][COLUMN]; + + // The binary search is not guaranteed to find the lower bound when a match wasn't found. + if (!bsFound) min = lowerBound(segments, matchedColumn, min); + const max = upperBound(segments, matchedColumn, min); + + const result = []; + for (; min <= max; min++) { + const segment = segments[min]; + result.push(GMapping(segment[REV_GENERATED_LINE] + 1, segment[REV_GENERATED_COLUMN])); + } + return result; +} + +function generatedPosition( + map: TraceMap, + source: string, + line: number, + column: number, + bias: Bias, + all: false, +): GeneratedMapping | InvalidGeneratedMapping; +function generatedPosition( + map: TraceMap, + source: string, + line: number, + column: number, + bias: Bias, + all: true, +): GeneratedMapping[]; +function generatedPosition( + map: TraceMap, + source: string, + line: number, + column: number, + bias: Bias, + all: boolean, +): GeneratedMapping | InvalidGeneratedMapping | GeneratedMapping[] { + line--; + if (line < 0) throw new Error(LINE_GTR_ZERO); + if (column < 0) throw new Error(COL_GTR_EQ_ZERO); + + const { sources, resolvedSources } = map; + let sourceIndex = sources.indexOf(source); + if (sourceIndex === -1) sourceIndex = resolvedSources.indexOf(source); + if (sourceIndex === -1) return all ? [] : GMapping(null, null); + + const bySourceMemos = (cast(map)._bySourceMemos ||= sources.map(memoizedState)); + const generated = (cast(map)._bySources ||= buildBySources(decodedMappings(map), bySourceMemos)); + + const segments = generated[sourceIndex][line]; + if (segments == null) return all ? [] : GMapping(null, null); + + const memo = bySourceMemos[sourceIndex]; + + if (all) return sliceGeneratedPositions(segments, memo, line, column, bias); + + const index = traceSegmentInternal(segments, memo, line, column, bias); + if (index === -1) return GMapping(null, null); + + const segment = segments[index]; + return GMapping(segment[REV_GENERATED_LINE] + 1, segment[REV_GENERATED_COLUMN]); +} diff --git a/dg-ui/node_modules/@jridgewell/trace-mapping/src/types.ts b/dg-ui/node_modules/@jridgewell/trace-mapping/src/types.ts new file mode 100644 index 0000000..730a61f --- /dev/null +++ b/dg-ui/node_modules/@jridgewell/trace-mapping/src/types.ts @@ -0,0 +1,114 @@ +import type { SourceMapSegment } from './sourcemap-segment'; +import type { GREATEST_LOWER_BOUND, LEAST_UPPER_BOUND, TraceMap } from './trace-mapping'; + +export interface SourceMapV3 { + file?: string | null; + names: string[]; + sourceRoot?: string; + sources: (string | null)[]; + sourcesContent?: (string | null)[]; + version: 3; + ignoreList?: number[]; +} + +export interface EncodedSourceMap extends SourceMapV3 { + mappings: string; +} + +export interface DecodedSourceMap extends SourceMapV3 { + mappings: SourceMapSegment[][]; +} + +export interface Section { + offset: { line: number; column: number }; + map: EncodedSourceMap | DecodedSourceMap | SectionedSourceMap; +} + +export interface SectionedSourceMap { + file?: string | null; + sections: Section[]; + version: 3; +} + +export type OriginalMapping = { + source: string | null; + line: number; + column: number; + name: string | null; +}; + +export type InvalidOriginalMapping = { + source: null; + line: null; + column: null; + name: null; +}; + +export type GeneratedMapping = { + line: number; + column: number; +}; +export type InvalidGeneratedMapping = { + line: null; + column: null; +}; + +export type Bias = typeof GREATEST_LOWER_BOUND | typeof LEAST_UPPER_BOUND; + +export type XInput = { x_google_ignoreList?: SourceMapV3['ignoreList'] }; +export type EncodedSourceMapXInput = EncodedSourceMap & XInput; +export type DecodedSourceMapXInput = DecodedSourceMap & XInput; +export type SectionedSourceMapXInput = Omit & { + sections: SectionXInput[]; +}; +export type SectionXInput = Omit & { + map: SectionedSourceMapInput; +}; + +export type SourceMapInput = string | EncodedSourceMapXInput | DecodedSourceMapXInput | TraceMap; +export type SectionedSourceMapInput = SourceMapInput | SectionedSourceMapXInput; + +export type Needle = { line: number; column: number; bias?: Bias }; +export type SourceNeedle = { source: string; line: number; column: number; bias?: Bias }; + +export type EachMapping = + | { + generatedLine: number; + generatedColumn: number; + source: null; + originalLine: null; + originalColumn: null; + name: null; + } + | { + generatedLine: number; + generatedColumn: number; + source: string | null; + originalLine: number; + originalColumn: number; + name: string | null; + }; + +export abstract class SourceMap { + declare version: SourceMapV3['version']; + declare file: SourceMapV3['file']; + declare names: SourceMapV3['names']; + declare sourceRoot: SourceMapV3['sourceRoot']; + declare sources: SourceMapV3['sources']; + declare sourcesContent: SourceMapV3['sourcesContent']; + declare resolvedSources: SourceMapV3['sources']; + declare ignoreList: SourceMapV3['ignoreList']; +} + +export type Ro = + T extends Array + ? V[] | Readonly | RoArray | Readonly> + : T extends object + ? T | Readonly | RoObject | Readonly> + : T; +type RoArray = Ro[]; +type RoObject = { [K in keyof T]: T[K] | Ro }; + +export function parse(map: T): Exclude { + return typeof map === 'string' ? JSON.parse(map) : (map as Exclude); +} diff --git a/dg-ui/node_modules/@jridgewell/trace-mapping/types/binary-search.d.cts b/dg-ui/node_modules/@jridgewell/trace-mapping/types/binary-search.d.cts new file mode 100644 index 0000000..b7bb85c --- /dev/null +++ b/dg-ui/node_modules/@jridgewell/trace-mapping/types/binary-search.d.cts @@ -0,0 +1,33 @@ +import type { SourceMapSegment, ReverseSegment } from './sourcemap-segment.cts'; +export type MemoState = { + lastKey: number; + lastNeedle: number; + lastIndex: number; +}; +export declare let found: boolean; +/** + * A binary search implementation that returns the index if a match is found. + * If no match is found, then the left-index (the index associated with the item that comes just + * before the desired index) is returned. To maintain proper sort order, a splice would happen at + * the next index: + * + * ```js + * const array = [1, 3]; + * const needle = 2; + * const index = binarySearch(array, needle, (item, needle) => item - needle); + * + * assert.equal(index, 0); + * array.splice(index + 1, 0, needle); + * assert.deepEqual(array, [1, 2, 3]); + * ``` + */ +export declare function binarySearch(haystack: SourceMapSegment[] | ReverseSegment[], needle: number, low: number, high: number): number; +export declare function upperBound(haystack: SourceMapSegment[] | ReverseSegment[], needle: number, index: number): number; +export declare function lowerBound(haystack: SourceMapSegment[] | ReverseSegment[], needle: number, index: number): number; +export declare function memoizedState(): MemoState; +/** + * This overly complicated beast is just to record the last tested line/column and the resulting + * index, allowing us to skip a few tests if mappings are monotonically increasing. + */ +export declare function memoizedBinarySearch(haystack: SourceMapSegment[] | ReverseSegment[], needle: number, state: MemoState, key: number): number; +//# sourceMappingURL=binary-search.d.ts.map \ No newline at end of file diff --git a/dg-ui/node_modules/@jridgewell/trace-mapping/types/binary-search.d.cts.map b/dg-ui/node_modules/@jridgewell/trace-mapping/types/binary-search.d.cts.map new file mode 100644 index 0000000..648e84c --- /dev/null +++ b/dg-ui/node_modules/@jridgewell/trace-mapping/types/binary-search.d.cts.map @@ -0,0 +1 @@ +{"version":3,"file":"binary-search.d.ts","sourceRoot":"","sources":["../src/binary-search.ts"],"names":[],"mappings":"AAAA,OAAO,KAAK,EAAE,gBAAgB,EAAE,cAAc,EAAE,MAAM,qBAAqB,CAAC;AAG5E,MAAM,MAAM,SAAS,GAAG;IACtB,OAAO,EAAE,MAAM,CAAC;IAChB,UAAU,EAAE,MAAM,CAAC;IACnB,SAAS,EAAE,MAAM,CAAC;CACnB,CAAC;AAEF,eAAO,IAAI,KAAK,SAAQ,CAAC;AAEzB;;;;;;;;;;;;;;;GAeG;AACH,wBAAgB,YAAY,CAC1B,QAAQ,EAAE,gBAAgB,EAAE,GAAG,cAAc,EAAE,EAC/C,MAAM,EAAE,MAAM,EACd,GAAG,EAAE,MAAM,EACX,IAAI,EAAE,MAAM,GACX,MAAM,CAmBR;AAED,wBAAgB,UAAU,CACxB,QAAQ,EAAE,gBAAgB,EAAE,GAAG,cAAc,EAAE,EAC/C,MAAM,EAAE,MAAM,EACd,KAAK,EAAE,MAAM,GACZ,MAAM,CAKR;AAED,wBAAgB,UAAU,CACxB,QAAQ,EAAE,gBAAgB,EAAE,GAAG,cAAc,EAAE,EAC/C,MAAM,EAAE,MAAM,EACd,KAAK,EAAE,MAAM,GACZ,MAAM,CAKR;AAED,wBAAgB,aAAa,IAAI,SAAS,CAMzC;AAED;;;GAGG;AACH,wBAAgB,oBAAoB,CAClC,QAAQ,EAAE,gBAAgB,EAAE,GAAG,cAAc,EAAE,EAC/C,MAAM,EAAE,MAAM,EACd,KAAK,EAAE,SAAS,EAChB,GAAG,EAAE,MAAM,GACV,MAAM,CAsBR"} \ No newline at end of file diff --git a/dg-ui/node_modules/@jridgewell/trace-mapping/types/binary-search.d.mts b/dg-ui/node_modules/@jridgewell/trace-mapping/types/binary-search.d.mts new file mode 100644 index 0000000..19e1e6b --- /dev/null +++ b/dg-ui/node_modules/@jridgewell/trace-mapping/types/binary-search.d.mts @@ -0,0 +1,33 @@ +import type { SourceMapSegment, ReverseSegment } from './sourcemap-segment.mts'; +export type MemoState = { + lastKey: number; + lastNeedle: number; + lastIndex: number; +}; +export declare let found: boolean; +/** + * A binary search implementation that returns the index if a match is found. + * If no match is found, then the left-index (the index associated with the item that comes just + * before the desired index) is returned. To maintain proper sort order, a splice would happen at + * the next index: + * + * ```js + * const array = [1, 3]; + * const needle = 2; + * const index = binarySearch(array, needle, (item, needle) => item - needle); + * + * assert.equal(index, 0); + * array.splice(index + 1, 0, needle); + * assert.deepEqual(array, [1, 2, 3]); + * ``` + */ +export declare function binarySearch(haystack: SourceMapSegment[] | ReverseSegment[], needle: number, low: number, high: number): number; +export declare function upperBound(haystack: SourceMapSegment[] | ReverseSegment[], needle: number, index: number): number; +export declare function lowerBound(haystack: SourceMapSegment[] | ReverseSegment[], needle: number, index: number): number; +export declare function memoizedState(): MemoState; +/** + * This overly complicated beast is just to record the last tested line/column and the resulting + * index, allowing us to skip a few tests if mappings are monotonically increasing. + */ +export declare function memoizedBinarySearch(haystack: SourceMapSegment[] | ReverseSegment[], needle: number, state: MemoState, key: number): number; +//# sourceMappingURL=binary-search.d.ts.map \ No newline at end of file diff --git a/dg-ui/node_modules/@jridgewell/trace-mapping/types/binary-search.d.mts.map b/dg-ui/node_modules/@jridgewell/trace-mapping/types/binary-search.d.mts.map new file mode 100644 index 0000000..648e84c --- /dev/null +++ b/dg-ui/node_modules/@jridgewell/trace-mapping/types/binary-search.d.mts.map @@ -0,0 +1 @@ +{"version":3,"file":"binary-search.d.ts","sourceRoot":"","sources":["../src/binary-search.ts"],"names":[],"mappings":"AAAA,OAAO,KAAK,EAAE,gBAAgB,EAAE,cAAc,EAAE,MAAM,qBAAqB,CAAC;AAG5E,MAAM,MAAM,SAAS,GAAG;IACtB,OAAO,EAAE,MAAM,CAAC;IAChB,UAAU,EAAE,MAAM,CAAC;IACnB,SAAS,EAAE,MAAM,CAAC;CACnB,CAAC;AAEF,eAAO,IAAI,KAAK,SAAQ,CAAC;AAEzB;;;;;;;;;;;;;;;GAeG;AACH,wBAAgB,YAAY,CAC1B,QAAQ,EAAE,gBAAgB,EAAE,GAAG,cAAc,EAAE,EAC/C,MAAM,EAAE,MAAM,EACd,GAAG,EAAE,MAAM,EACX,IAAI,EAAE,MAAM,GACX,MAAM,CAmBR;AAED,wBAAgB,UAAU,CACxB,QAAQ,EAAE,gBAAgB,EAAE,GAAG,cAAc,EAAE,EAC/C,MAAM,EAAE,MAAM,EACd,KAAK,EAAE,MAAM,GACZ,MAAM,CAKR;AAED,wBAAgB,UAAU,CACxB,QAAQ,EAAE,gBAAgB,EAAE,GAAG,cAAc,EAAE,EAC/C,MAAM,EAAE,MAAM,EACd,KAAK,EAAE,MAAM,GACZ,MAAM,CAKR;AAED,wBAAgB,aAAa,IAAI,SAAS,CAMzC;AAED;;;GAGG;AACH,wBAAgB,oBAAoB,CAClC,QAAQ,EAAE,gBAAgB,EAAE,GAAG,cAAc,EAAE,EAC/C,MAAM,EAAE,MAAM,EACd,KAAK,EAAE,SAAS,EAChB,GAAG,EAAE,MAAM,GACV,MAAM,CAsBR"} \ No newline at end of file diff --git a/dg-ui/node_modules/@jridgewell/trace-mapping/types/by-source.d.cts b/dg-ui/node_modules/@jridgewell/trace-mapping/types/by-source.d.cts new file mode 100644 index 0000000..da49693 --- /dev/null +++ b/dg-ui/node_modules/@jridgewell/trace-mapping/types/by-source.d.cts @@ -0,0 +1,4 @@ +import type { ReverseSegment, SourceMapSegment } from './sourcemap-segment.cts'; +export type Source = ReverseSegment[][]; +export = function buildBySources(decoded: readonly SourceMapSegment[][], memos: unknown[]): Source[]; +//# sourceMappingURL=by-source.d.ts.map \ No newline at end of file diff --git a/dg-ui/node_modules/@jridgewell/trace-mapping/types/by-source.d.cts.map b/dg-ui/node_modules/@jridgewell/trace-mapping/types/by-source.d.cts.map new file mode 100644 index 0000000..32d2a7a --- /dev/null +++ b/dg-ui/node_modules/@jridgewell/trace-mapping/types/by-source.d.cts.map @@ -0,0 +1 @@ +{"version":3,"file":"by-source.d.ts","sourceRoot":"","sources":["../src/by-source.ts"],"names":[],"mappings":"AAGA,OAAO,KAAK,EAAE,cAAc,EAAE,gBAAgB,EAAE,MAAM,qBAAqB,CAAC;AAE5E,MAAM,MAAM,MAAM,GAAG,cAAc,EAAE,EAAE,CAAC;AAIxC,MAAM,CAAC,OAAO,UAAU,cAAc,CACpC,OAAO,EAAE,SAAS,gBAAgB,EAAE,EAAE,EACtC,KAAK,EAAE,OAAO,EAAE,GACf,MAAM,EAAE,CA4BV"} \ No newline at end of file diff --git a/dg-ui/node_modules/@jridgewell/trace-mapping/types/by-source.d.mts b/dg-ui/node_modules/@jridgewell/trace-mapping/types/by-source.d.mts new file mode 100644 index 0000000..f361049 --- /dev/null +++ b/dg-ui/node_modules/@jridgewell/trace-mapping/types/by-source.d.mts @@ -0,0 +1,4 @@ +import type { ReverseSegment, SourceMapSegment } from './sourcemap-segment.mts'; +export type Source = ReverseSegment[][]; +export default function buildBySources(decoded: readonly SourceMapSegment[][], memos: unknown[]): Source[]; +//# sourceMappingURL=by-source.d.ts.map \ No newline at end of file diff --git a/dg-ui/node_modules/@jridgewell/trace-mapping/types/by-source.d.mts.map b/dg-ui/node_modules/@jridgewell/trace-mapping/types/by-source.d.mts.map new file mode 100644 index 0000000..32d2a7a --- /dev/null +++ b/dg-ui/node_modules/@jridgewell/trace-mapping/types/by-source.d.mts.map @@ -0,0 +1 @@ +{"version":3,"file":"by-source.d.ts","sourceRoot":"","sources":["../src/by-source.ts"],"names":[],"mappings":"AAGA,OAAO,KAAK,EAAE,cAAc,EAAE,gBAAgB,EAAE,MAAM,qBAAqB,CAAC;AAE5E,MAAM,MAAM,MAAM,GAAG,cAAc,EAAE,EAAE,CAAC;AAIxC,MAAM,CAAC,OAAO,UAAU,cAAc,CACpC,OAAO,EAAE,SAAS,gBAAgB,EAAE,EAAE,EACtC,KAAK,EAAE,OAAO,EAAE,GACf,MAAM,EAAE,CA4BV"} \ No newline at end of file diff --git a/dg-ui/node_modules/@jridgewell/trace-mapping/types/flatten-map.d.cts b/dg-ui/node_modules/@jridgewell/trace-mapping/types/flatten-map.d.cts new file mode 100644 index 0000000..433d849 --- /dev/null +++ b/dg-ui/node_modules/@jridgewell/trace-mapping/types/flatten-map.d.cts @@ -0,0 +1,9 @@ +import { TraceMap } from './trace-mapping.cts'; +import type { SectionedSourceMapInput, Ro } from './types.cts'; +type FlattenMap = { + new (map: Ro, mapUrl?: string | null): TraceMap; + (map: Ro, mapUrl?: string | null): TraceMap; +}; +export declare const FlattenMap: FlattenMap; +export {}; +//# sourceMappingURL=flatten-map.d.ts.map \ No newline at end of file diff --git a/dg-ui/node_modules/@jridgewell/trace-mapping/types/flatten-map.d.cts.map b/dg-ui/node_modules/@jridgewell/trace-mapping/types/flatten-map.d.cts.map new file mode 100644 index 0000000..994b208 --- /dev/null +++ b/dg-ui/node_modules/@jridgewell/trace-mapping/types/flatten-map.d.cts.map @@ -0,0 +1 @@ +{"version":3,"file":"flatten-map.d.ts","sourceRoot":"","sources":["../src/flatten-map.ts"],"names":[],"mappings":"AAAA,OAAO,EAAE,QAAQ,EAAwC,MAAM,iBAAiB,CAAC;AAUjF,OAAO,KAAK,EAKV,uBAAuB,EAEvB,EAAE,EACH,MAAM,SAAS,CAAC;AAGjB,KAAK,UAAU,GAAG;IAChB,KAAK,GAAG,EAAE,EAAE,CAAC,uBAAuB,CAAC,EAAE,MAAM,CAAC,EAAE,MAAM,GAAG,IAAI,GAAG,QAAQ,CAAC;IACzE,CAAC,GAAG,EAAE,EAAE,CAAC,uBAAuB,CAAC,EAAE,MAAM,CAAC,EAAE,MAAM,GAAG,IAAI,GAAG,QAAQ,CAAC;CACtE,CAAC;AAEF,eAAO,MAAM,UAAU,EAAE,UAsCV,CAAC"} \ No newline at end of file diff --git a/dg-ui/node_modules/@jridgewell/trace-mapping/types/flatten-map.d.mts b/dg-ui/node_modules/@jridgewell/trace-mapping/types/flatten-map.d.mts new file mode 100644 index 0000000..444a1be --- /dev/null +++ b/dg-ui/node_modules/@jridgewell/trace-mapping/types/flatten-map.d.mts @@ -0,0 +1,9 @@ +import { TraceMap } from './trace-mapping.mts'; +import type { SectionedSourceMapInput, Ro } from './types.mts'; +type FlattenMap = { + new (map: Ro, mapUrl?: string | null): TraceMap; + (map: Ro, mapUrl?: string | null): TraceMap; +}; +export declare const FlattenMap: FlattenMap; +export {}; +//# sourceMappingURL=flatten-map.d.ts.map \ No newline at end of file diff --git a/dg-ui/node_modules/@jridgewell/trace-mapping/types/flatten-map.d.mts.map b/dg-ui/node_modules/@jridgewell/trace-mapping/types/flatten-map.d.mts.map new file mode 100644 index 0000000..994b208 --- /dev/null +++ b/dg-ui/node_modules/@jridgewell/trace-mapping/types/flatten-map.d.mts.map @@ -0,0 +1 @@ +{"version":3,"file":"flatten-map.d.ts","sourceRoot":"","sources":["../src/flatten-map.ts"],"names":[],"mappings":"AAAA,OAAO,EAAE,QAAQ,EAAwC,MAAM,iBAAiB,CAAC;AAUjF,OAAO,KAAK,EAKV,uBAAuB,EAEvB,EAAE,EACH,MAAM,SAAS,CAAC;AAGjB,KAAK,UAAU,GAAG;IAChB,KAAK,GAAG,EAAE,EAAE,CAAC,uBAAuB,CAAC,EAAE,MAAM,CAAC,EAAE,MAAM,GAAG,IAAI,GAAG,QAAQ,CAAC;IACzE,CAAC,GAAG,EAAE,EAAE,CAAC,uBAAuB,CAAC,EAAE,MAAM,CAAC,EAAE,MAAM,GAAG,IAAI,GAAG,QAAQ,CAAC;CACtE,CAAC;AAEF,eAAO,MAAM,UAAU,EAAE,UAsCV,CAAC"} \ No newline at end of file diff --git a/dg-ui/node_modules/@jridgewell/trace-mapping/types/resolve.d.cts b/dg-ui/node_modules/@jridgewell/trace-mapping/types/resolve.d.cts new file mode 100644 index 0000000..62aeedb --- /dev/null +++ b/dg-ui/node_modules/@jridgewell/trace-mapping/types/resolve.d.cts @@ -0,0 +1,4 @@ +type Resolve = (source: string | null) => string; +export = function resolver(mapUrl: string | null | undefined, sourceRoot: string | undefined): Resolve; +export {}; +//# sourceMappingURL=resolve.d.ts.map \ No newline at end of file diff --git a/dg-ui/node_modules/@jridgewell/trace-mapping/types/resolve.d.cts.map b/dg-ui/node_modules/@jridgewell/trace-mapping/types/resolve.d.cts.map new file mode 100644 index 0000000..9f155ac --- /dev/null +++ b/dg-ui/node_modules/@jridgewell/trace-mapping/types/resolve.d.cts.map @@ -0,0 +1 @@ +{"version":3,"file":"resolve.d.ts","sourceRoot":"","sources":["../src/resolve.ts"],"names":[],"mappings":"AAGA,KAAK,OAAO,GAAG,CAAC,MAAM,EAAE,MAAM,GAAG,IAAI,KAAK,MAAM,CAAC;AACjD,MAAM,CAAC,OAAO,UAAU,QAAQ,CAC9B,MAAM,EAAE,MAAM,GAAG,IAAI,GAAG,SAAS,EACjC,UAAU,EAAE,MAAM,GAAG,SAAS,GAC7B,OAAO,CAQT"} \ No newline at end of file diff --git a/dg-ui/node_modules/@jridgewell/trace-mapping/types/resolve.d.mts b/dg-ui/node_modules/@jridgewell/trace-mapping/types/resolve.d.mts new file mode 100644 index 0000000..e2798a1 --- /dev/null +++ b/dg-ui/node_modules/@jridgewell/trace-mapping/types/resolve.d.mts @@ -0,0 +1,4 @@ +type Resolve = (source: string | null) => string; +export default function resolver(mapUrl: string | null | undefined, sourceRoot: string | undefined): Resolve; +export {}; +//# sourceMappingURL=resolve.d.ts.map \ No newline at end of file diff --git a/dg-ui/node_modules/@jridgewell/trace-mapping/types/resolve.d.mts.map b/dg-ui/node_modules/@jridgewell/trace-mapping/types/resolve.d.mts.map new file mode 100644 index 0000000..9f155ac --- /dev/null +++ b/dg-ui/node_modules/@jridgewell/trace-mapping/types/resolve.d.mts.map @@ -0,0 +1 @@ +{"version":3,"file":"resolve.d.ts","sourceRoot":"","sources":["../src/resolve.ts"],"names":[],"mappings":"AAGA,KAAK,OAAO,GAAG,CAAC,MAAM,EAAE,MAAM,GAAG,IAAI,KAAK,MAAM,CAAC;AACjD,MAAM,CAAC,OAAO,UAAU,QAAQ,CAC9B,MAAM,EAAE,MAAM,GAAG,IAAI,GAAG,SAAS,EACjC,UAAU,EAAE,MAAM,GAAG,SAAS,GAC7B,OAAO,CAQT"} \ No newline at end of file diff --git a/dg-ui/node_modules/@jridgewell/trace-mapping/types/sort.d.cts b/dg-ui/node_modules/@jridgewell/trace-mapping/types/sort.d.cts new file mode 100644 index 0000000..aa14c12 --- /dev/null +++ b/dg-ui/node_modules/@jridgewell/trace-mapping/types/sort.d.cts @@ -0,0 +1,4 @@ +import type { ReverseSegment, SourceMapSegment } from './sourcemap-segment.cts'; +export = function maybeSort(mappings: SourceMapSegment[][], owned: boolean): SourceMapSegment[][]; +export declare function sortComparator(a: T, b: T): number; +//# sourceMappingURL=sort.d.ts.map \ No newline at end of file diff --git a/dg-ui/node_modules/@jridgewell/trace-mapping/types/sort.d.cts.map b/dg-ui/node_modules/@jridgewell/trace-mapping/types/sort.d.cts.map new file mode 100644 index 0000000..48b8e67 --- /dev/null +++ b/dg-ui/node_modules/@jridgewell/trace-mapping/types/sort.d.cts.map @@ -0,0 +1 @@ +{"version":3,"file":"sort.d.ts","sourceRoot":"","sources":["../src/sort.ts"],"names":[],"mappings":"AAEA,OAAO,KAAK,EAAE,cAAc,EAAE,gBAAgB,EAAE,MAAM,qBAAqB,CAAC;AAE5E,MAAM,CAAC,OAAO,UAAU,SAAS,CAC/B,QAAQ,EAAE,gBAAgB,EAAE,EAAE,EAC9B,KAAK,EAAE,OAAO,GACb,gBAAgB,EAAE,EAAE,CAYtB;AAuBD,wBAAgB,cAAc,CAAC,CAAC,SAAS,gBAAgB,GAAG,cAAc,EAAE,CAAC,EAAE,CAAC,EAAE,CAAC,EAAE,CAAC,GAAG,MAAM,CAE9F"} \ No newline at end of file diff --git a/dg-ui/node_modules/@jridgewell/trace-mapping/types/sort.d.mts b/dg-ui/node_modules/@jridgewell/trace-mapping/types/sort.d.mts new file mode 100644 index 0000000..c5b94e6 --- /dev/null +++ b/dg-ui/node_modules/@jridgewell/trace-mapping/types/sort.d.mts @@ -0,0 +1,4 @@ +import type { ReverseSegment, SourceMapSegment } from './sourcemap-segment.mts'; +export default function maybeSort(mappings: SourceMapSegment[][], owned: boolean): SourceMapSegment[][]; +export declare function sortComparator(a: T, b: T): number; +//# sourceMappingURL=sort.d.ts.map \ No newline at end of file diff --git a/dg-ui/node_modules/@jridgewell/trace-mapping/types/sort.d.mts.map b/dg-ui/node_modules/@jridgewell/trace-mapping/types/sort.d.mts.map new file mode 100644 index 0000000..48b8e67 --- /dev/null +++ b/dg-ui/node_modules/@jridgewell/trace-mapping/types/sort.d.mts.map @@ -0,0 +1 @@ +{"version":3,"file":"sort.d.ts","sourceRoot":"","sources":["../src/sort.ts"],"names":[],"mappings":"AAEA,OAAO,KAAK,EAAE,cAAc,EAAE,gBAAgB,EAAE,MAAM,qBAAqB,CAAC;AAE5E,MAAM,CAAC,OAAO,UAAU,SAAS,CAC/B,QAAQ,EAAE,gBAAgB,EAAE,EAAE,EAC9B,KAAK,EAAE,OAAO,GACb,gBAAgB,EAAE,EAAE,CAYtB;AAuBD,wBAAgB,cAAc,CAAC,CAAC,SAAS,gBAAgB,GAAG,cAAc,EAAE,CAAC,EAAE,CAAC,EAAE,CAAC,EAAE,CAAC,GAAG,MAAM,CAE9F"} \ No newline at end of file diff --git a/dg-ui/node_modules/@jridgewell/trace-mapping/types/sourcemap-segment.d.cts b/dg-ui/node_modules/@jridgewell/trace-mapping/types/sourcemap-segment.d.cts new file mode 100644 index 0000000..8d3cabc --- /dev/null +++ b/dg-ui/node_modules/@jridgewell/trace-mapping/types/sourcemap-segment.d.cts @@ -0,0 +1,17 @@ +type GeneratedColumn = number; +type SourcesIndex = number; +type SourceLine = number; +type SourceColumn = number; +type NamesIndex = number; +type GeneratedLine = number; +export type SourceMapSegment = [GeneratedColumn] | [GeneratedColumn, SourcesIndex, SourceLine, SourceColumn] | [GeneratedColumn, SourcesIndex, SourceLine, SourceColumn, NamesIndex]; +export type ReverseSegment = [SourceColumn, GeneratedLine, GeneratedColumn]; +export declare const COLUMN = 0; +export declare const SOURCES_INDEX = 1; +export declare const SOURCE_LINE = 2; +export declare const SOURCE_COLUMN = 3; +export declare const NAMES_INDEX = 4; +export declare const REV_GENERATED_LINE = 1; +export declare const REV_GENERATED_COLUMN = 2; +export {}; +//# sourceMappingURL=sourcemap-segment.d.ts.map \ No newline at end of file diff --git a/dg-ui/node_modules/@jridgewell/trace-mapping/types/sourcemap-segment.d.cts.map b/dg-ui/node_modules/@jridgewell/trace-mapping/types/sourcemap-segment.d.cts.map new file mode 100644 index 0000000..0c94a46 --- /dev/null +++ b/dg-ui/node_modules/@jridgewell/trace-mapping/types/sourcemap-segment.d.cts.map @@ -0,0 +1 @@ +{"version":3,"file":"sourcemap-segment.d.ts","sourceRoot":"","sources":["../src/sourcemap-segment.ts"],"names":[],"mappings":"AAAA,KAAK,eAAe,GAAG,MAAM,CAAC;AAC9B,KAAK,YAAY,GAAG,MAAM,CAAC;AAC3B,KAAK,UAAU,GAAG,MAAM,CAAC;AACzB,KAAK,YAAY,GAAG,MAAM,CAAC;AAC3B,KAAK,UAAU,GAAG,MAAM,CAAC;AAEzB,KAAK,aAAa,GAAG,MAAM,CAAC;AAE5B,MAAM,MAAM,gBAAgB,GACxB,CAAC,eAAe,CAAC,GACjB,CAAC,eAAe,EAAE,YAAY,EAAE,UAAU,EAAE,YAAY,CAAC,GACzD,CAAC,eAAe,EAAE,YAAY,EAAE,UAAU,EAAE,YAAY,EAAE,UAAU,CAAC,CAAC;AAE1E,MAAM,MAAM,cAAc,GAAG,CAAC,YAAY,EAAE,aAAa,EAAE,eAAe,CAAC,CAAC;AAE5E,eAAO,MAAM,MAAM,IAAI,CAAC;AACxB,eAAO,MAAM,aAAa,IAAI,CAAC;AAC/B,eAAO,MAAM,WAAW,IAAI,CAAC;AAC7B,eAAO,MAAM,aAAa,IAAI,CAAC;AAC/B,eAAO,MAAM,WAAW,IAAI,CAAC;AAE7B,eAAO,MAAM,kBAAkB,IAAI,CAAC;AACpC,eAAO,MAAM,oBAAoB,IAAI,CAAC"} \ No newline at end of file diff --git a/dg-ui/node_modules/@jridgewell/trace-mapping/types/sourcemap-segment.d.mts b/dg-ui/node_modules/@jridgewell/trace-mapping/types/sourcemap-segment.d.mts new file mode 100644 index 0000000..8d3cabc --- /dev/null +++ b/dg-ui/node_modules/@jridgewell/trace-mapping/types/sourcemap-segment.d.mts @@ -0,0 +1,17 @@ +type GeneratedColumn = number; +type SourcesIndex = number; +type SourceLine = number; +type SourceColumn = number; +type NamesIndex = number; +type GeneratedLine = number; +export type SourceMapSegment = [GeneratedColumn] | [GeneratedColumn, SourcesIndex, SourceLine, SourceColumn] | [GeneratedColumn, SourcesIndex, SourceLine, SourceColumn, NamesIndex]; +export type ReverseSegment = [SourceColumn, GeneratedLine, GeneratedColumn]; +export declare const COLUMN = 0; +export declare const SOURCES_INDEX = 1; +export declare const SOURCE_LINE = 2; +export declare const SOURCE_COLUMN = 3; +export declare const NAMES_INDEX = 4; +export declare const REV_GENERATED_LINE = 1; +export declare const REV_GENERATED_COLUMN = 2; +export {}; +//# sourceMappingURL=sourcemap-segment.d.ts.map \ No newline at end of file diff --git a/dg-ui/node_modules/@jridgewell/trace-mapping/types/sourcemap-segment.d.mts.map b/dg-ui/node_modules/@jridgewell/trace-mapping/types/sourcemap-segment.d.mts.map new file mode 100644 index 0000000..0c94a46 --- /dev/null +++ b/dg-ui/node_modules/@jridgewell/trace-mapping/types/sourcemap-segment.d.mts.map @@ -0,0 +1 @@ +{"version":3,"file":"sourcemap-segment.d.ts","sourceRoot":"","sources":["../src/sourcemap-segment.ts"],"names":[],"mappings":"AAAA,KAAK,eAAe,GAAG,MAAM,CAAC;AAC9B,KAAK,YAAY,GAAG,MAAM,CAAC;AAC3B,KAAK,UAAU,GAAG,MAAM,CAAC;AACzB,KAAK,YAAY,GAAG,MAAM,CAAC;AAC3B,KAAK,UAAU,GAAG,MAAM,CAAC;AAEzB,KAAK,aAAa,GAAG,MAAM,CAAC;AAE5B,MAAM,MAAM,gBAAgB,GACxB,CAAC,eAAe,CAAC,GACjB,CAAC,eAAe,EAAE,YAAY,EAAE,UAAU,EAAE,YAAY,CAAC,GACzD,CAAC,eAAe,EAAE,YAAY,EAAE,UAAU,EAAE,YAAY,EAAE,UAAU,CAAC,CAAC;AAE1E,MAAM,MAAM,cAAc,GAAG,CAAC,YAAY,EAAE,aAAa,EAAE,eAAe,CAAC,CAAC;AAE5E,eAAO,MAAM,MAAM,IAAI,CAAC;AACxB,eAAO,MAAM,aAAa,IAAI,CAAC;AAC/B,eAAO,MAAM,WAAW,IAAI,CAAC;AAC7B,eAAO,MAAM,aAAa,IAAI,CAAC;AAC/B,eAAO,MAAM,WAAW,IAAI,CAAC;AAE7B,eAAO,MAAM,kBAAkB,IAAI,CAAC;AACpC,eAAO,MAAM,oBAAoB,IAAI,CAAC"} \ No newline at end of file diff --git a/dg-ui/node_modules/@jridgewell/trace-mapping/types/strip-filename.d.cts b/dg-ui/node_modules/@jridgewell/trace-mapping/types/strip-filename.d.cts new file mode 100644 index 0000000..8b3c0e9 --- /dev/null +++ b/dg-ui/node_modules/@jridgewell/trace-mapping/types/strip-filename.d.cts @@ -0,0 +1,5 @@ +/** + * Removes everything after the last "/", but leaves the slash. + */ +export = function stripFilename(path: string | undefined | null): string; +//# sourceMappingURL=strip-filename.d.ts.map \ No newline at end of file diff --git a/dg-ui/node_modules/@jridgewell/trace-mapping/types/strip-filename.d.cts.map b/dg-ui/node_modules/@jridgewell/trace-mapping/types/strip-filename.d.cts.map new file mode 100644 index 0000000..17a25da --- /dev/null +++ b/dg-ui/node_modules/@jridgewell/trace-mapping/types/strip-filename.d.cts.map @@ -0,0 +1 @@ +{"version":3,"file":"strip-filename.d.ts","sourceRoot":"","sources":["../src/strip-filename.ts"],"names":[],"mappings":"AAAA;;GAEG;AACH,MAAM,CAAC,OAAO,UAAU,aAAa,CAAC,IAAI,EAAE,MAAM,GAAG,SAAS,GAAG,IAAI,GAAG,MAAM,CAI7E"} \ No newline at end of file diff --git a/dg-ui/node_modules/@jridgewell/trace-mapping/types/strip-filename.d.mts b/dg-ui/node_modules/@jridgewell/trace-mapping/types/strip-filename.d.mts new file mode 100644 index 0000000..cbbaee0 --- /dev/null +++ b/dg-ui/node_modules/@jridgewell/trace-mapping/types/strip-filename.d.mts @@ -0,0 +1,5 @@ +/** + * Removes everything after the last "/", but leaves the slash. + */ +export default function stripFilename(path: string | undefined | null): string; +//# sourceMappingURL=strip-filename.d.ts.map \ No newline at end of file diff --git a/dg-ui/node_modules/@jridgewell/trace-mapping/types/strip-filename.d.mts.map b/dg-ui/node_modules/@jridgewell/trace-mapping/types/strip-filename.d.mts.map new file mode 100644 index 0000000..17a25da --- /dev/null +++ b/dg-ui/node_modules/@jridgewell/trace-mapping/types/strip-filename.d.mts.map @@ -0,0 +1 @@ +{"version":3,"file":"strip-filename.d.ts","sourceRoot":"","sources":["../src/strip-filename.ts"],"names":[],"mappings":"AAAA;;GAEG;AACH,MAAM,CAAC,OAAO,UAAU,aAAa,CAAC,IAAI,EAAE,MAAM,GAAG,SAAS,GAAG,IAAI,GAAG,MAAM,CAI7E"} \ No newline at end of file diff --git a/dg-ui/node_modules/@jridgewell/trace-mapping/types/trace-mapping.d.cts b/dg-ui/node_modules/@jridgewell/trace-mapping/types/trace-mapping.d.cts new file mode 100644 index 0000000..a40f305 --- /dev/null +++ b/dg-ui/node_modules/@jridgewell/trace-mapping/types/trace-mapping.d.cts @@ -0,0 +1,80 @@ +import type { SourceMapSegment } from './sourcemap-segment.cts'; +import type { SourceMapV3, DecodedSourceMap, EncodedSourceMap, InvalidOriginalMapping, OriginalMapping, InvalidGeneratedMapping, GeneratedMapping, SourceMapInput, Needle, SourceNeedle, SourceMap, EachMapping, Ro } from './types.cts'; +export type { SourceMapSegment } from './sourcemap-segment.cts'; +export type { SourceMap, DecodedSourceMap, EncodedSourceMap, Section, SectionedSourceMap, SourceMapV3, Bias, EachMapping, GeneratedMapping, InvalidGeneratedMapping, InvalidOriginalMapping, Needle, OriginalMapping, OriginalMapping as Mapping, SectionedSourceMapInput, SourceMapInput, SourceNeedle, XInput, EncodedSourceMapXInput, DecodedSourceMapXInput, SectionedSourceMapXInput, SectionXInput, } from './types.cts'; +export declare const LEAST_UPPER_BOUND = -1; +export declare const GREATEST_LOWER_BOUND = 1; +export { FlattenMap, FlattenMap as AnyMap } from './flatten-map.cts'; +export declare class TraceMap implements SourceMap { + version: SourceMapV3['version']; + file: SourceMapV3['file']; + names: SourceMapV3['names']; + sourceRoot: SourceMapV3['sourceRoot']; + sources: SourceMapV3['sources']; + sourcesContent: SourceMapV3['sourcesContent']; + ignoreList: SourceMapV3['ignoreList']; + resolvedSources: string[]; + private _encoded; + private _decoded; + private _decodedMemo; + private _bySources; + private _bySourceMemos; + constructor(map: Ro, mapUrl?: string | null); +} +/** + * Returns the encoded (VLQ string) form of the SourceMap's mappings field. + */ +export declare function encodedMappings(map: TraceMap): EncodedSourceMap['mappings']; +/** + * Returns the decoded (array of lines of segments) form of the SourceMap's mappings field. + */ +export declare function decodedMappings(map: TraceMap): Readonly; +/** + * A low-level API to find the segment associated with a generated line/column (think, from a + * stack trace). Line and column here are 0-based, unlike `originalPositionFor`. + */ +export declare function traceSegment(map: TraceMap, line: number, column: number): Readonly | null; +/** + * A higher-level API to find the source/line/column associated with a generated line/column + * (think, from a stack trace). Line is 1-based, but column is 0-based, due to legacy behavior in + * `source-map` library. + */ +export declare function originalPositionFor(map: TraceMap, needle: Needle): OriginalMapping | InvalidOriginalMapping; +/** + * Finds the generated line/column position of the provided source/line/column source position. + */ +export declare function generatedPositionFor(map: TraceMap, needle: SourceNeedle): GeneratedMapping | InvalidGeneratedMapping; +/** + * Finds all generated line/column positions of the provided source/line/column source position. + */ +export declare function allGeneratedPositionsFor(map: TraceMap, needle: SourceNeedle): GeneratedMapping[]; +/** + * Iterates each mapping in generated position order. + */ +export declare function eachMapping(map: TraceMap, cb: (mapping: EachMapping) => void): void; +/** + * Retrieves the source content for a particular source, if its found. Returns null if not. + */ +export declare function sourceContentFor(map: TraceMap, source: string): string | null; +/** + * Determines if the source is marked to ignore by the source map. + */ +export declare function isIgnored(map: TraceMap, source: string): boolean; +/** + * A helper that skips sorting of the input map's mappings array, which can be expensive for larger + * maps. + */ +export declare function presortedDecodedMap(map: DecodedSourceMap, mapUrl?: string): TraceMap; +/** + * Returns a sourcemap object (with decoded mappings) suitable for passing to a library that expects + * a sourcemap, or to JSON.stringify. + */ +export declare function decodedMap(map: TraceMap): Omit & { + mappings: readonly SourceMapSegment[][]; +}; +/** + * Returns a sourcemap object (with encoded mappings) suitable for passing to a library that expects + * a sourcemap, or to JSON.stringify. + */ +export declare function encodedMap(map: TraceMap): EncodedSourceMap; +//# sourceMappingURL=trace-mapping.d.ts.map \ No newline at end of file diff --git a/dg-ui/node_modules/@jridgewell/trace-mapping/types/trace-mapping.d.cts.map b/dg-ui/node_modules/@jridgewell/trace-mapping/types/trace-mapping.d.cts.map new file mode 100644 index 0000000..b5a874c --- /dev/null +++ b/dg-ui/node_modules/@jridgewell/trace-mapping/types/trace-mapping.d.cts.map @@ -0,0 +1 @@ +{"version":3,"file":"trace-mapping.d.ts","sourceRoot":"","sources":["../src/trace-mapping.ts"],"names":[],"mappings":"AAuBA,OAAO,KAAK,EAAE,gBAAgB,EAAkB,MAAM,qBAAqB,CAAC;AAC5E,OAAO,KAAK,EACV,WAAW,EACX,gBAAgB,EAChB,gBAAgB,EAChB,sBAAsB,EACtB,eAAe,EACf,uBAAuB,EACvB,gBAAgB,EAChB,cAAc,EACd,MAAM,EACN,YAAY,EACZ,SAAS,EACT,WAAW,EAIX,EAAE,EACH,MAAM,SAAS,CAAC;AAIjB,YAAY,EAAE,gBAAgB,EAAE,MAAM,qBAAqB,CAAC;AAC5D,YAAY,EACV,SAAS,EACT,gBAAgB,EAChB,gBAAgB,EAChB,OAAO,EACP,kBAAkB,EAClB,WAAW,EACX,IAAI,EACJ,WAAW,EACX,gBAAgB,EAChB,uBAAuB,EACvB,sBAAsB,EACtB,MAAM,EACN,eAAe,EACf,eAAe,IAAI,OAAO,EAC1B,uBAAuB,EACvB,cAAc,EACd,YAAY,EACZ,MAAM,EACN,sBAAsB,EACtB,sBAAsB,EACtB,wBAAwB,EACxB,aAAa,GACd,MAAM,SAAS,CAAC;AAajB,eAAO,MAAM,iBAAiB,KAAK,CAAC;AACpC,eAAO,MAAM,oBAAoB,IAAI,CAAC;AAEtC,OAAO,EAAE,UAAU,EAAE,UAAU,IAAI,MAAM,EAAE,MAAM,eAAe,CAAC;AAEjE,qBAAa,QAAS,YAAW,SAAS;IAChC,OAAO,EAAE,WAAW,CAAC,SAAS,CAAC,CAAC;IAChC,IAAI,EAAE,WAAW,CAAC,MAAM,CAAC,CAAC;IAC1B,KAAK,EAAE,WAAW,CAAC,OAAO,CAAC,CAAC;IAC5B,UAAU,EAAE,WAAW,CAAC,YAAY,CAAC,CAAC;IACtC,OAAO,EAAE,WAAW,CAAC,SAAS,CAAC,CAAC;IAChC,cAAc,EAAE,WAAW,CAAC,gBAAgB,CAAC,CAAC;IAC9C,UAAU,EAAE,WAAW,CAAC,YAAY,CAAC,CAAC;IAEtC,eAAe,EAAE,MAAM,EAAE,CAAC;IAClC,QAAgB,QAAQ,CAAqB;IAE7C,QAAgB,QAAQ,CAAmC;IAC3D,QAAgB,YAAY,CAAY;IAExC,QAAgB,UAAU,CAAuB;IACjD,QAAgB,cAAc,CAA0B;gBAE5C,GAAG,EAAE,EAAE,CAAC,cAAc,CAAC,EAAE,MAAM,CAAC,EAAE,MAAM,GAAG,IAAI;CAmC5D;AAUD;;GAEG;AACH,wBAAgB,eAAe,CAAC,GAAG,EAAE,QAAQ,GAAG,gBAAgB,CAAC,UAAU,CAAC,CAE3E;AAED;;GAEG;AACH,wBAAgB,eAAe,CAAC,GAAG,EAAE,QAAQ,GAAG,QAAQ,CAAC,gBAAgB,CAAC,UAAU,CAAC,CAAC,CAErF;AAED;;;GAGG;AACH,wBAAgB,YAAY,CAC1B,GAAG,EAAE,QAAQ,EACb,IAAI,EAAE,MAAM,EACZ,MAAM,EAAE,MAAM,GACb,QAAQ,CAAC,gBAAgB,CAAC,GAAG,IAAI,CAiBnC;AAED;;;;GAIG;AACH,wBAAgB,mBAAmB,CACjC,GAAG,EAAE,QAAQ,EACb,MAAM,EAAE,MAAM,GACb,eAAe,GAAG,sBAAsB,CAiC1C;AAED;;GAEG;AACH,wBAAgB,oBAAoB,CAClC,GAAG,EAAE,QAAQ,EACb,MAAM,EAAE,YAAY,GACnB,gBAAgB,GAAG,uBAAuB,CAG5C;AAED;;GAEG;AACH,wBAAgB,wBAAwB,CAAC,GAAG,EAAE,QAAQ,EAAE,MAAM,EAAE,YAAY,GAAG,gBAAgB,EAAE,CAIhG;AAED;;GAEG;AACH,wBAAgB,WAAW,CAAC,GAAG,EAAE,QAAQ,EAAE,EAAE,EAAE,CAAC,OAAO,EAAE,WAAW,KAAK,IAAI,GAAG,IAAI,CAgCnF;AASD;;GAEG;AACH,wBAAgB,gBAAgB,CAAC,GAAG,EAAE,QAAQ,EAAE,MAAM,EAAE,MAAM,GAAG,MAAM,GAAG,IAAI,CAK7E;AAED;;GAEG;AACH,wBAAgB,SAAS,CAAC,GAAG,EAAE,QAAQ,EAAE,MAAM,EAAE,MAAM,GAAG,OAAO,CAKhE;AAED;;;GAGG;AACH,wBAAgB,mBAAmB,CAAC,GAAG,EAAE,gBAAgB,EAAE,MAAM,CAAC,EAAE,MAAM,GAAG,QAAQ,CAIpF;AAED;;;GAGG;AACH,wBAAgB,UAAU,CACxB,GAAG,EAAE,QAAQ,GACZ,IAAI,CAAC,gBAAgB,EAAE,UAAU,CAAC,GAAG;IAAE,QAAQ,EAAE,SAAS,gBAAgB,EAAE,EAAE,CAAA;CAAE,CAElF;AAED;;;GAGG;AACH,wBAAgB,UAAU,CAAC,GAAG,EAAE,QAAQ,GAAG,gBAAgB,CAE1D"} \ No newline at end of file diff --git a/dg-ui/node_modules/@jridgewell/trace-mapping/types/trace-mapping.d.mts b/dg-ui/node_modules/@jridgewell/trace-mapping/types/trace-mapping.d.mts new file mode 100644 index 0000000..bc2ff0f --- /dev/null +++ b/dg-ui/node_modules/@jridgewell/trace-mapping/types/trace-mapping.d.mts @@ -0,0 +1,80 @@ +import type { SourceMapSegment } from './sourcemap-segment.mts'; +import type { SourceMapV3, DecodedSourceMap, EncodedSourceMap, InvalidOriginalMapping, OriginalMapping, InvalidGeneratedMapping, GeneratedMapping, SourceMapInput, Needle, SourceNeedle, SourceMap, EachMapping, Ro } from './types.mts'; +export type { SourceMapSegment } from './sourcemap-segment.mts'; +export type { SourceMap, DecodedSourceMap, EncodedSourceMap, Section, SectionedSourceMap, SourceMapV3, Bias, EachMapping, GeneratedMapping, InvalidGeneratedMapping, InvalidOriginalMapping, Needle, OriginalMapping, OriginalMapping as Mapping, SectionedSourceMapInput, SourceMapInput, SourceNeedle, XInput, EncodedSourceMapXInput, DecodedSourceMapXInput, SectionedSourceMapXInput, SectionXInput, } from './types.mts'; +export declare const LEAST_UPPER_BOUND = -1; +export declare const GREATEST_LOWER_BOUND = 1; +export { FlattenMap, FlattenMap as AnyMap } from './flatten-map.mts'; +export declare class TraceMap implements SourceMap { + version: SourceMapV3['version']; + file: SourceMapV3['file']; + names: SourceMapV3['names']; + sourceRoot: SourceMapV3['sourceRoot']; + sources: SourceMapV3['sources']; + sourcesContent: SourceMapV3['sourcesContent']; + ignoreList: SourceMapV3['ignoreList']; + resolvedSources: string[]; + private _encoded; + private _decoded; + private _decodedMemo; + private _bySources; + private _bySourceMemos; + constructor(map: Ro, mapUrl?: string | null); +} +/** + * Returns the encoded (VLQ string) form of the SourceMap's mappings field. + */ +export declare function encodedMappings(map: TraceMap): EncodedSourceMap['mappings']; +/** + * Returns the decoded (array of lines of segments) form of the SourceMap's mappings field. + */ +export declare function decodedMappings(map: TraceMap): Readonly; +/** + * A low-level API to find the segment associated with a generated line/column (think, from a + * stack trace). Line and column here are 0-based, unlike `originalPositionFor`. + */ +export declare function traceSegment(map: TraceMap, line: number, column: number): Readonly | null; +/** + * A higher-level API to find the source/line/column associated with a generated line/column + * (think, from a stack trace). Line is 1-based, but column is 0-based, due to legacy behavior in + * `source-map` library. + */ +export declare function originalPositionFor(map: TraceMap, needle: Needle): OriginalMapping | InvalidOriginalMapping; +/** + * Finds the generated line/column position of the provided source/line/column source position. + */ +export declare function generatedPositionFor(map: TraceMap, needle: SourceNeedle): GeneratedMapping | InvalidGeneratedMapping; +/** + * Finds all generated line/column positions of the provided source/line/column source position. + */ +export declare function allGeneratedPositionsFor(map: TraceMap, needle: SourceNeedle): GeneratedMapping[]; +/** + * Iterates each mapping in generated position order. + */ +export declare function eachMapping(map: TraceMap, cb: (mapping: EachMapping) => void): void; +/** + * Retrieves the source content for a particular source, if its found. Returns null if not. + */ +export declare function sourceContentFor(map: TraceMap, source: string): string | null; +/** + * Determines if the source is marked to ignore by the source map. + */ +export declare function isIgnored(map: TraceMap, source: string): boolean; +/** + * A helper that skips sorting of the input map's mappings array, which can be expensive for larger + * maps. + */ +export declare function presortedDecodedMap(map: DecodedSourceMap, mapUrl?: string): TraceMap; +/** + * Returns a sourcemap object (with decoded mappings) suitable for passing to a library that expects + * a sourcemap, or to JSON.stringify. + */ +export declare function decodedMap(map: TraceMap): Omit & { + mappings: readonly SourceMapSegment[][]; +}; +/** + * Returns a sourcemap object (with encoded mappings) suitable for passing to a library that expects + * a sourcemap, or to JSON.stringify. + */ +export declare function encodedMap(map: TraceMap): EncodedSourceMap; +//# sourceMappingURL=trace-mapping.d.ts.map \ No newline at end of file diff --git a/dg-ui/node_modules/@jridgewell/trace-mapping/types/trace-mapping.d.mts.map b/dg-ui/node_modules/@jridgewell/trace-mapping/types/trace-mapping.d.mts.map new file mode 100644 index 0000000..b5a874c --- /dev/null +++ b/dg-ui/node_modules/@jridgewell/trace-mapping/types/trace-mapping.d.mts.map @@ -0,0 +1 @@ +{"version":3,"file":"trace-mapping.d.ts","sourceRoot":"","sources":["../src/trace-mapping.ts"],"names":[],"mappings":"AAuBA,OAAO,KAAK,EAAE,gBAAgB,EAAkB,MAAM,qBAAqB,CAAC;AAC5E,OAAO,KAAK,EACV,WAAW,EACX,gBAAgB,EAChB,gBAAgB,EAChB,sBAAsB,EACtB,eAAe,EACf,uBAAuB,EACvB,gBAAgB,EAChB,cAAc,EACd,MAAM,EACN,YAAY,EACZ,SAAS,EACT,WAAW,EAIX,EAAE,EACH,MAAM,SAAS,CAAC;AAIjB,YAAY,EAAE,gBAAgB,EAAE,MAAM,qBAAqB,CAAC;AAC5D,YAAY,EACV,SAAS,EACT,gBAAgB,EAChB,gBAAgB,EAChB,OAAO,EACP,kBAAkB,EAClB,WAAW,EACX,IAAI,EACJ,WAAW,EACX,gBAAgB,EAChB,uBAAuB,EACvB,sBAAsB,EACtB,MAAM,EACN,eAAe,EACf,eAAe,IAAI,OAAO,EAC1B,uBAAuB,EACvB,cAAc,EACd,YAAY,EACZ,MAAM,EACN,sBAAsB,EACtB,sBAAsB,EACtB,wBAAwB,EACxB,aAAa,GACd,MAAM,SAAS,CAAC;AAajB,eAAO,MAAM,iBAAiB,KAAK,CAAC;AACpC,eAAO,MAAM,oBAAoB,IAAI,CAAC;AAEtC,OAAO,EAAE,UAAU,EAAE,UAAU,IAAI,MAAM,EAAE,MAAM,eAAe,CAAC;AAEjE,qBAAa,QAAS,YAAW,SAAS;IAChC,OAAO,EAAE,WAAW,CAAC,SAAS,CAAC,CAAC;IAChC,IAAI,EAAE,WAAW,CAAC,MAAM,CAAC,CAAC;IAC1B,KAAK,EAAE,WAAW,CAAC,OAAO,CAAC,CAAC;IAC5B,UAAU,EAAE,WAAW,CAAC,YAAY,CAAC,CAAC;IACtC,OAAO,EAAE,WAAW,CAAC,SAAS,CAAC,CAAC;IAChC,cAAc,EAAE,WAAW,CAAC,gBAAgB,CAAC,CAAC;IAC9C,UAAU,EAAE,WAAW,CAAC,YAAY,CAAC,CAAC;IAEtC,eAAe,EAAE,MAAM,EAAE,CAAC;IAClC,QAAgB,QAAQ,CAAqB;IAE7C,QAAgB,QAAQ,CAAmC;IAC3D,QAAgB,YAAY,CAAY;IAExC,QAAgB,UAAU,CAAuB;IACjD,QAAgB,cAAc,CAA0B;gBAE5C,GAAG,EAAE,EAAE,CAAC,cAAc,CAAC,EAAE,MAAM,CAAC,EAAE,MAAM,GAAG,IAAI;CAmC5D;AAUD;;GAEG;AACH,wBAAgB,eAAe,CAAC,GAAG,EAAE,QAAQ,GAAG,gBAAgB,CAAC,UAAU,CAAC,CAE3E;AAED;;GAEG;AACH,wBAAgB,eAAe,CAAC,GAAG,EAAE,QAAQ,GAAG,QAAQ,CAAC,gBAAgB,CAAC,UAAU,CAAC,CAAC,CAErF;AAED;;;GAGG;AACH,wBAAgB,YAAY,CAC1B,GAAG,EAAE,QAAQ,EACb,IAAI,EAAE,MAAM,EACZ,MAAM,EAAE,MAAM,GACb,QAAQ,CAAC,gBAAgB,CAAC,GAAG,IAAI,CAiBnC;AAED;;;;GAIG;AACH,wBAAgB,mBAAmB,CACjC,GAAG,EAAE,QAAQ,EACb,MAAM,EAAE,MAAM,GACb,eAAe,GAAG,sBAAsB,CAiC1C;AAED;;GAEG;AACH,wBAAgB,oBAAoB,CAClC,GAAG,EAAE,QAAQ,EACb,MAAM,EAAE,YAAY,GACnB,gBAAgB,GAAG,uBAAuB,CAG5C;AAED;;GAEG;AACH,wBAAgB,wBAAwB,CAAC,GAAG,EAAE,QAAQ,EAAE,MAAM,EAAE,YAAY,GAAG,gBAAgB,EAAE,CAIhG;AAED;;GAEG;AACH,wBAAgB,WAAW,CAAC,GAAG,EAAE,QAAQ,EAAE,EAAE,EAAE,CAAC,OAAO,EAAE,WAAW,KAAK,IAAI,GAAG,IAAI,CAgCnF;AASD;;GAEG;AACH,wBAAgB,gBAAgB,CAAC,GAAG,EAAE,QAAQ,EAAE,MAAM,EAAE,MAAM,GAAG,MAAM,GAAG,IAAI,CAK7E;AAED;;GAEG;AACH,wBAAgB,SAAS,CAAC,GAAG,EAAE,QAAQ,EAAE,MAAM,EAAE,MAAM,GAAG,OAAO,CAKhE;AAED;;;GAGG;AACH,wBAAgB,mBAAmB,CAAC,GAAG,EAAE,gBAAgB,EAAE,MAAM,CAAC,EAAE,MAAM,GAAG,QAAQ,CAIpF;AAED;;;GAGG;AACH,wBAAgB,UAAU,CACxB,GAAG,EAAE,QAAQ,GACZ,IAAI,CAAC,gBAAgB,EAAE,UAAU,CAAC,GAAG;IAAE,QAAQ,EAAE,SAAS,gBAAgB,EAAE,EAAE,CAAA;CAAE,CAElF;AAED;;;GAGG;AACH,wBAAgB,UAAU,CAAC,GAAG,EAAE,QAAQ,GAAG,gBAAgB,CAE1D"} \ No newline at end of file diff --git a/dg-ui/node_modules/@jridgewell/trace-mapping/types/types.d.cts b/dg-ui/node_modules/@jridgewell/trace-mapping/types/types.d.cts new file mode 100644 index 0000000..729c2c3 --- /dev/null +++ b/dg-ui/node_modules/@jridgewell/trace-mapping/types/types.d.cts @@ -0,0 +1,107 @@ +import type { SourceMapSegment } from './sourcemap-segment.cts'; +import type { GREATEST_LOWER_BOUND, LEAST_UPPER_BOUND, TraceMap } from './trace-mapping.cts'; +export interface SourceMapV3 { + file?: string | null; + names: string[]; + sourceRoot?: string; + sources: (string | null)[]; + sourcesContent?: (string | null)[]; + version: 3; + ignoreList?: number[]; +} +export interface EncodedSourceMap extends SourceMapV3 { + mappings: string; +} +export interface DecodedSourceMap extends SourceMapV3 { + mappings: SourceMapSegment[][]; +} +export interface Section { + offset: { + line: number; + column: number; + }; + map: EncodedSourceMap | DecodedSourceMap | SectionedSourceMap; +} +export interface SectionedSourceMap { + file?: string | null; + sections: Section[]; + version: 3; +} +export type OriginalMapping = { + source: string | null; + line: number; + column: number; + name: string | null; +}; +export type InvalidOriginalMapping = { + source: null; + line: null; + column: null; + name: null; +}; +export type GeneratedMapping = { + line: number; + column: number; +}; +export type InvalidGeneratedMapping = { + line: null; + column: null; +}; +export type Bias = typeof GREATEST_LOWER_BOUND | typeof LEAST_UPPER_BOUND; +export type XInput = { + x_google_ignoreList?: SourceMapV3['ignoreList']; +}; +export type EncodedSourceMapXInput = EncodedSourceMap & XInput; +export type DecodedSourceMapXInput = DecodedSourceMap & XInput; +export type SectionedSourceMapXInput = Omit & { + sections: SectionXInput[]; +}; +export type SectionXInput = Omit & { + map: SectionedSourceMapInput; +}; +export type SourceMapInput = string | EncodedSourceMapXInput | DecodedSourceMapXInput | TraceMap; +export type SectionedSourceMapInput = SourceMapInput | SectionedSourceMapXInput; +export type Needle = { + line: number; + column: number; + bias?: Bias; +}; +export type SourceNeedle = { + source: string; + line: number; + column: number; + bias?: Bias; +}; +export type EachMapping = { + generatedLine: number; + generatedColumn: number; + source: null; + originalLine: null; + originalColumn: null; + name: null; +} | { + generatedLine: number; + generatedColumn: number; + source: string | null; + originalLine: number; + originalColumn: number; + name: string | null; +}; +export declare abstract class SourceMap { + version: SourceMapV3['version']; + file: SourceMapV3['file']; + names: SourceMapV3['names']; + sourceRoot: SourceMapV3['sourceRoot']; + sources: SourceMapV3['sources']; + sourcesContent: SourceMapV3['sourcesContent']; + resolvedSources: SourceMapV3['sources']; + ignoreList: SourceMapV3['ignoreList']; +} +export type Ro = T extends Array ? V[] | Readonly | RoArray | Readonly> : T extends object ? T | Readonly | RoObject | Readonly> : T; +type RoArray = Ro[]; +type RoObject = { + [K in keyof T]: T[K] | Ro; +}; +export declare function parse(map: T): Exclude; +export {}; +//# sourceMappingURL=types.d.ts.map \ No newline at end of file diff --git a/dg-ui/node_modules/@jridgewell/trace-mapping/types/types.d.cts.map b/dg-ui/node_modules/@jridgewell/trace-mapping/types/types.d.cts.map new file mode 100644 index 0000000..9224783 --- /dev/null +++ b/dg-ui/node_modules/@jridgewell/trace-mapping/types/types.d.cts.map @@ -0,0 +1 @@ +{"version":3,"file":"types.d.ts","sourceRoot":"","sources":["../src/types.ts"],"names":[],"mappings":"AAAA,OAAO,KAAK,EAAE,gBAAgB,EAAE,MAAM,qBAAqB,CAAC;AAC5D,OAAO,KAAK,EAAE,oBAAoB,EAAE,iBAAiB,EAAE,QAAQ,EAAE,MAAM,iBAAiB,CAAC;AAEzF,MAAM,WAAW,WAAW;IAC1B,IAAI,CAAC,EAAE,MAAM,GAAG,IAAI,CAAC;IACrB,KAAK,EAAE,MAAM,EAAE,CAAC;IAChB,UAAU,CAAC,EAAE,MAAM,CAAC;IACpB,OAAO,EAAE,CAAC,MAAM,GAAG,IAAI,CAAC,EAAE,CAAC;IAC3B,cAAc,CAAC,EAAE,CAAC,MAAM,GAAG,IAAI,CAAC,EAAE,CAAC;IACnC,OAAO,EAAE,CAAC,CAAC;IACX,UAAU,CAAC,EAAE,MAAM,EAAE,CAAC;CACvB;AAED,MAAM,WAAW,gBAAiB,SAAQ,WAAW;IACnD,QAAQ,EAAE,MAAM,CAAC;CAClB;AAED,MAAM,WAAW,gBAAiB,SAAQ,WAAW;IACnD,QAAQ,EAAE,gBAAgB,EAAE,EAAE,CAAC;CAChC;AAED,MAAM,WAAW,OAAO;IACtB,MAAM,EAAE;QAAE,IAAI,EAAE,MAAM,CAAC;QAAC,MAAM,EAAE,MAAM,CAAA;KAAE,CAAC;IACzC,GAAG,EAAE,gBAAgB,GAAG,gBAAgB,GAAG,kBAAkB,CAAC;CAC/D;AAED,MAAM,WAAW,kBAAkB;IACjC,IAAI,CAAC,EAAE,MAAM,GAAG,IAAI,CAAC;IACrB,QAAQ,EAAE,OAAO,EAAE,CAAC;IACpB,OAAO,EAAE,CAAC,CAAC;CACZ;AAED,MAAM,MAAM,eAAe,GAAG;IAC5B,MAAM,EAAE,MAAM,GAAG,IAAI,CAAC;IACtB,IAAI,EAAE,MAAM,CAAC;IACb,MAAM,EAAE,MAAM,CAAC;IACf,IAAI,EAAE,MAAM,GAAG,IAAI,CAAC;CACrB,CAAC;AAEF,MAAM,MAAM,sBAAsB,GAAG;IACnC,MAAM,EAAE,IAAI,CAAC;IACb,IAAI,EAAE,IAAI,CAAC;IACX,MAAM,EAAE,IAAI,CAAC;IACb,IAAI,EAAE,IAAI,CAAC;CACZ,CAAC;AAEF,MAAM,MAAM,gBAAgB,GAAG;IAC7B,IAAI,EAAE,MAAM,CAAC;IACb,MAAM,EAAE,MAAM,CAAC;CAChB,CAAC;AACF,MAAM,MAAM,uBAAuB,GAAG;IACpC,IAAI,EAAE,IAAI,CAAC;IACX,MAAM,EAAE,IAAI,CAAC;CACd,CAAC;AAEF,MAAM,MAAM,IAAI,GAAG,OAAO,oBAAoB,GAAG,OAAO,iBAAiB,CAAC;AAE1E,MAAM,MAAM,MAAM,GAAG;IAAE,mBAAmB,CAAC,EAAE,WAAW,CAAC,YAAY,CAAC,CAAA;CAAE,CAAC;AACzE,MAAM,MAAM,sBAAsB,GAAG,gBAAgB,GAAG,MAAM,CAAC;AAC/D,MAAM,MAAM,sBAAsB,GAAG,gBAAgB,GAAG,MAAM,CAAC;AAC/D,MAAM,MAAM,wBAAwB,GAAG,IAAI,CAAC,kBAAkB,EAAE,UAAU,CAAC,GAAG;IAC5E,QAAQ,EAAE,aAAa,EAAE,CAAC;CAC3B,CAAC;AACF,MAAM,MAAM,aAAa,GAAG,IAAI,CAAC,OAAO,EAAE,KAAK,CAAC,GAAG;IACjD,GAAG,EAAE,uBAAuB,CAAC;CAC9B,CAAC;AAEF,MAAM,MAAM,cAAc,GAAG,MAAM,GAAG,sBAAsB,GAAG,sBAAsB,GAAG,QAAQ,CAAC;AACjG,MAAM,MAAM,uBAAuB,GAAG,cAAc,GAAG,wBAAwB,CAAC;AAEhF,MAAM,MAAM,MAAM,GAAG;IAAE,IAAI,EAAE,MAAM,CAAC;IAAC,MAAM,EAAE,MAAM,CAAC;IAAC,IAAI,CAAC,EAAE,IAAI,CAAA;CAAE,CAAC;AACnE,MAAM,MAAM,YAAY,GAAG;IAAE,MAAM,EAAE,MAAM,CAAC;IAAC,IAAI,EAAE,MAAM,CAAC;IAAC,MAAM,EAAE,MAAM,CAAC;IAAC,IAAI,CAAC,EAAE,IAAI,CAAA;CAAE,CAAC;AAEzF,MAAM,MAAM,WAAW,GACnB;IACE,aAAa,EAAE,MAAM,CAAC;IACtB,eAAe,EAAE,MAAM,CAAC;IACxB,MAAM,EAAE,IAAI,CAAC;IACb,YAAY,EAAE,IAAI,CAAC;IACnB,cAAc,EAAE,IAAI,CAAC;IACrB,IAAI,EAAE,IAAI,CAAC;CACZ,GACD;IACE,aAAa,EAAE,MAAM,CAAC;IACtB,eAAe,EAAE,MAAM,CAAC;IACxB,MAAM,EAAE,MAAM,GAAG,IAAI,CAAC;IACtB,YAAY,EAAE,MAAM,CAAC;IACrB,cAAc,EAAE,MAAM,CAAC;IACvB,IAAI,EAAE,MAAM,GAAG,IAAI,CAAC;CACrB,CAAC;AAEN,8BAAsB,SAAS;IACrB,OAAO,EAAE,WAAW,CAAC,SAAS,CAAC,CAAC;IAChC,IAAI,EAAE,WAAW,CAAC,MAAM,CAAC,CAAC;IAC1B,KAAK,EAAE,WAAW,CAAC,OAAO,CAAC,CAAC;IAC5B,UAAU,EAAE,WAAW,CAAC,YAAY,CAAC,CAAC;IACtC,OAAO,EAAE,WAAW,CAAC,SAAS,CAAC,CAAC;IAChC,cAAc,EAAE,WAAW,CAAC,gBAAgB,CAAC,CAAC;IAC9C,eAAe,EAAE,WAAW,CAAC,SAAS,CAAC,CAAC;IACxC,UAAU,EAAE,WAAW,CAAC,YAAY,CAAC,CAAC;CAC/C;AAED,MAAM,MAAM,EAAE,CAAC,CAAC,IACd,CAAC,SAAS,KAAK,CAAC,MAAM,CAAC,CAAC,GACpB,CAAC,EAAE,GAAG,QAAQ,CAAC,CAAC,EAAE,CAAC,GAAG,OAAO,CAAC,CAAC,CAAC,GAAG,QAAQ,CAAC,OAAO,CAAC,CAAC,CAAC,CAAC,GACvD,CAAC,SAAS,MAAM,GACd,CAAC,GAAG,QAAQ,CAAC,CAAC,CAAC,GAAG,QAAQ,CAAC,CAAC,CAAC,GAAG,QAAQ,CAAC,QAAQ,CAAC,CAAC,CAAC,CAAC,GACrD,CAAC,CAAC;AACV,KAAK,OAAO,CAAC,CAAC,IAAI,EAAE,CAAC,CAAC,CAAC,EAAE,CAAC;AAC1B,KAAK,QAAQ,CAAC,CAAC,IAAI;KAAG,CAAC,IAAI,MAAM,CAAC,GAAG,CAAC,CAAC,CAAC,CAAC,GAAG,EAAE,CAAC,CAAC,CAAC,CAAC,CAAC,CAAC;CAAE,CAAC;AAEvD,wBAAgB,KAAK,CAAC,CAAC,EAAE,GAAG,EAAE,CAAC,GAAG,OAAO,CAAC,CAAC,EAAE,MAAM,CAAC,CAEnD"} \ No newline at end of file diff --git a/dg-ui/node_modules/@jridgewell/trace-mapping/types/types.d.mts b/dg-ui/node_modules/@jridgewell/trace-mapping/types/types.d.mts new file mode 100644 index 0000000..a26d186 --- /dev/null +++ b/dg-ui/node_modules/@jridgewell/trace-mapping/types/types.d.mts @@ -0,0 +1,107 @@ +import type { SourceMapSegment } from './sourcemap-segment.mts'; +import type { GREATEST_LOWER_BOUND, LEAST_UPPER_BOUND, TraceMap } from './trace-mapping.mts'; +export interface SourceMapV3 { + file?: string | null; + names: string[]; + sourceRoot?: string; + sources: (string | null)[]; + sourcesContent?: (string | null)[]; + version: 3; + ignoreList?: number[]; +} +export interface EncodedSourceMap extends SourceMapV3 { + mappings: string; +} +export interface DecodedSourceMap extends SourceMapV3 { + mappings: SourceMapSegment[][]; +} +export interface Section { + offset: { + line: number; + column: number; + }; + map: EncodedSourceMap | DecodedSourceMap | SectionedSourceMap; +} +export interface SectionedSourceMap { + file?: string | null; + sections: Section[]; + version: 3; +} +export type OriginalMapping = { + source: string | null; + line: number; + column: number; + name: string | null; +}; +export type InvalidOriginalMapping = { + source: null; + line: null; + column: null; + name: null; +}; +export type GeneratedMapping = { + line: number; + column: number; +}; +export type InvalidGeneratedMapping = { + line: null; + column: null; +}; +export type Bias = typeof GREATEST_LOWER_BOUND | typeof LEAST_UPPER_BOUND; +export type XInput = { + x_google_ignoreList?: SourceMapV3['ignoreList']; +}; +export type EncodedSourceMapXInput = EncodedSourceMap & XInput; +export type DecodedSourceMapXInput = DecodedSourceMap & XInput; +export type SectionedSourceMapXInput = Omit & { + sections: SectionXInput[]; +}; +export type SectionXInput = Omit & { + map: SectionedSourceMapInput; +}; +export type SourceMapInput = string | EncodedSourceMapXInput | DecodedSourceMapXInput | TraceMap; +export type SectionedSourceMapInput = SourceMapInput | SectionedSourceMapXInput; +export type Needle = { + line: number; + column: number; + bias?: Bias; +}; +export type SourceNeedle = { + source: string; + line: number; + column: number; + bias?: Bias; +}; +export type EachMapping = { + generatedLine: number; + generatedColumn: number; + source: null; + originalLine: null; + originalColumn: null; + name: null; +} | { + generatedLine: number; + generatedColumn: number; + source: string | null; + originalLine: number; + originalColumn: number; + name: string | null; +}; +export declare abstract class SourceMap { + version: SourceMapV3['version']; + file: SourceMapV3['file']; + names: SourceMapV3['names']; + sourceRoot: SourceMapV3['sourceRoot']; + sources: SourceMapV3['sources']; + sourcesContent: SourceMapV3['sourcesContent']; + resolvedSources: SourceMapV3['sources']; + ignoreList: SourceMapV3['ignoreList']; +} +export type Ro = T extends Array ? V[] | Readonly | RoArray | Readonly> : T extends object ? T | Readonly | RoObject | Readonly> : T; +type RoArray = Ro[]; +type RoObject = { + [K in keyof T]: T[K] | Ro; +}; +export declare function parse(map: T): Exclude; +export {}; +//# sourceMappingURL=types.d.ts.map \ No newline at end of file diff --git a/dg-ui/node_modules/@jridgewell/trace-mapping/types/types.d.mts.map b/dg-ui/node_modules/@jridgewell/trace-mapping/types/types.d.mts.map new file mode 100644 index 0000000..9224783 --- /dev/null +++ b/dg-ui/node_modules/@jridgewell/trace-mapping/types/types.d.mts.map @@ -0,0 +1 @@ +{"version":3,"file":"types.d.ts","sourceRoot":"","sources":["../src/types.ts"],"names":[],"mappings":"AAAA,OAAO,KAAK,EAAE,gBAAgB,EAAE,MAAM,qBAAqB,CAAC;AAC5D,OAAO,KAAK,EAAE,oBAAoB,EAAE,iBAAiB,EAAE,QAAQ,EAAE,MAAM,iBAAiB,CAAC;AAEzF,MAAM,WAAW,WAAW;IAC1B,IAAI,CAAC,EAAE,MAAM,GAAG,IAAI,CAAC;IACrB,KAAK,EAAE,MAAM,EAAE,CAAC;IAChB,UAAU,CAAC,EAAE,MAAM,CAAC;IACpB,OAAO,EAAE,CAAC,MAAM,GAAG,IAAI,CAAC,EAAE,CAAC;IAC3B,cAAc,CAAC,EAAE,CAAC,MAAM,GAAG,IAAI,CAAC,EAAE,CAAC;IACnC,OAAO,EAAE,CAAC,CAAC;IACX,UAAU,CAAC,EAAE,MAAM,EAAE,CAAC;CACvB;AAED,MAAM,WAAW,gBAAiB,SAAQ,WAAW;IACnD,QAAQ,EAAE,MAAM,CAAC;CAClB;AAED,MAAM,WAAW,gBAAiB,SAAQ,WAAW;IACnD,QAAQ,EAAE,gBAAgB,EAAE,EAAE,CAAC;CAChC;AAED,MAAM,WAAW,OAAO;IACtB,MAAM,EAAE;QAAE,IAAI,EAAE,MAAM,CAAC;QAAC,MAAM,EAAE,MAAM,CAAA;KAAE,CAAC;IACzC,GAAG,EAAE,gBAAgB,GAAG,gBAAgB,GAAG,kBAAkB,CAAC;CAC/D;AAED,MAAM,WAAW,kBAAkB;IACjC,IAAI,CAAC,EAAE,MAAM,GAAG,IAAI,CAAC;IACrB,QAAQ,EAAE,OAAO,EAAE,CAAC;IACpB,OAAO,EAAE,CAAC,CAAC;CACZ;AAED,MAAM,MAAM,eAAe,GAAG;IAC5B,MAAM,EAAE,MAAM,GAAG,IAAI,CAAC;IACtB,IAAI,EAAE,MAAM,CAAC;IACb,MAAM,EAAE,MAAM,CAAC;IACf,IAAI,EAAE,MAAM,GAAG,IAAI,CAAC;CACrB,CAAC;AAEF,MAAM,MAAM,sBAAsB,GAAG;IACnC,MAAM,EAAE,IAAI,CAAC;IACb,IAAI,EAAE,IAAI,CAAC;IACX,MAAM,EAAE,IAAI,CAAC;IACb,IAAI,EAAE,IAAI,CAAC;CACZ,CAAC;AAEF,MAAM,MAAM,gBAAgB,GAAG;IAC7B,IAAI,EAAE,MAAM,CAAC;IACb,MAAM,EAAE,MAAM,CAAC;CAChB,CAAC;AACF,MAAM,MAAM,uBAAuB,GAAG;IACpC,IAAI,EAAE,IAAI,CAAC;IACX,MAAM,EAAE,IAAI,CAAC;CACd,CAAC;AAEF,MAAM,MAAM,IAAI,GAAG,OAAO,oBAAoB,GAAG,OAAO,iBAAiB,CAAC;AAE1E,MAAM,MAAM,MAAM,GAAG;IAAE,mBAAmB,CAAC,EAAE,WAAW,CAAC,YAAY,CAAC,CAAA;CAAE,CAAC;AACzE,MAAM,MAAM,sBAAsB,GAAG,gBAAgB,GAAG,MAAM,CAAC;AAC/D,MAAM,MAAM,sBAAsB,GAAG,gBAAgB,GAAG,MAAM,CAAC;AAC/D,MAAM,MAAM,wBAAwB,GAAG,IAAI,CAAC,kBAAkB,EAAE,UAAU,CAAC,GAAG;IAC5E,QAAQ,EAAE,aAAa,EAAE,CAAC;CAC3B,CAAC;AACF,MAAM,MAAM,aAAa,GAAG,IAAI,CAAC,OAAO,EAAE,KAAK,CAAC,GAAG;IACjD,GAAG,EAAE,uBAAuB,CAAC;CAC9B,CAAC;AAEF,MAAM,MAAM,cAAc,GAAG,MAAM,GAAG,sBAAsB,GAAG,sBAAsB,GAAG,QAAQ,CAAC;AACjG,MAAM,MAAM,uBAAuB,GAAG,cAAc,GAAG,wBAAwB,CAAC;AAEhF,MAAM,MAAM,MAAM,GAAG;IAAE,IAAI,EAAE,MAAM,CAAC;IAAC,MAAM,EAAE,MAAM,CAAC;IAAC,IAAI,CAAC,EAAE,IAAI,CAAA;CAAE,CAAC;AACnE,MAAM,MAAM,YAAY,GAAG;IAAE,MAAM,EAAE,MAAM,CAAC;IAAC,IAAI,EAAE,MAAM,CAAC;IAAC,MAAM,EAAE,MAAM,CAAC;IAAC,IAAI,CAAC,EAAE,IAAI,CAAA;CAAE,CAAC;AAEzF,MAAM,MAAM,WAAW,GACnB;IACE,aAAa,EAAE,MAAM,CAAC;IACtB,eAAe,EAAE,MAAM,CAAC;IACxB,MAAM,EAAE,IAAI,CAAC;IACb,YAAY,EAAE,IAAI,CAAC;IACnB,cAAc,EAAE,IAAI,CAAC;IACrB,IAAI,EAAE,IAAI,CAAC;CACZ,GACD;IACE,aAAa,EAAE,MAAM,CAAC;IACtB,eAAe,EAAE,MAAM,CAAC;IACxB,MAAM,EAAE,MAAM,GAAG,IAAI,CAAC;IACtB,YAAY,EAAE,MAAM,CAAC;IACrB,cAAc,EAAE,MAAM,CAAC;IACvB,IAAI,EAAE,MAAM,GAAG,IAAI,CAAC;CACrB,CAAC;AAEN,8BAAsB,SAAS;IACrB,OAAO,EAAE,WAAW,CAAC,SAAS,CAAC,CAAC;IAChC,IAAI,EAAE,WAAW,CAAC,MAAM,CAAC,CAAC;IAC1B,KAAK,EAAE,WAAW,CAAC,OAAO,CAAC,CAAC;IAC5B,UAAU,EAAE,WAAW,CAAC,YAAY,CAAC,CAAC;IACtC,OAAO,EAAE,WAAW,CAAC,SAAS,CAAC,CAAC;IAChC,cAAc,EAAE,WAAW,CAAC,gBAAgB,CAAC,CAAC;IAC9C,eAAe,EAAE,WAAW,CAAC,SAAS,CAAC,CAAC;IACxC,UAAU,EAAE,WAAW,CAAC,YAAY,CAAC,CAAC;CAC/C;AAED,MAAM,MAAM,EAAE,CAAC,CAAC,IACd,CAAC,SAAS,KAAK,CAAC,MAAM,CAAC,CAAC,GACpB,CAAC,EAAE,GAAG,QAAQ,CAAC,CAAC,EAAE,CAAC,GAAG,OAAO,CAAC,CAAC,CAAC,GAAG,QAAQ,CAAC,OAAO,CAAC,CAAC,CAAC,CAAC,GACvD,CAAC,SAAS,MAAM,GACd,CAAC,GAAG,QAAQ,CAAC,CAAC,CAAC,GAAG,QAAQ,CAAC,CAAC,CAAC,GAAG,QAAQ,CAAC,QAAQ,CAAC,CAAC,CAAC,CAAC,GACrD,CAAC,CAAC;AACV,KAAK,OAAO,CAAC,CAAC,IAAI,EAAE,CAAC,CAAC,CAAC,EAAE,CAAC;AAC1B,KAAK,QAAQ,CAAC,CAAC,IAAI;KAAG,CAAC,IAAI,MAAM,CAAC,GAAG,CAAC,CAAC,CAAC,CAAC,GAAG,EAAE,CAAC,CAAC,CAAC,CAAC,CAAC,CAAC;CAAE,CAAC;AAEvD,wBAAgB,KAAK,CAAC,CAAC,EAAE,GAAG,EAAE,CAAC,GAAG,OAAO,CAAC,CAAC,EAAE,MAAM,CAAC,CAEnD"} \ No newline at end of file diff --git a/dg-ui/node_modules/@parcel/watcher-win32-x64/LICENSE b/dg-ui/node_modules/@parcel/watcher-win32-x64/LICENSE new file mode 100644 index 0000000..7fb9bc9 --- /dev/null +++ b/dg-ui/node_modules/@parcel/watcher-win32-x64/LICENSE @@ -0,0 +1,21 @@ +MIT License + +Copyright (c) 2017-present Devon Govett + +Permission is hereby granted, free of charge, to any person obtaining a copy +of this software and associated documentation files (the "Software"), to deal +in the Software without restriction, including without limitation the rights +to use, copy, modify, merge, publish, distribute, sublicense, and/or sell +copies of the Software, and to permit persons to whom the Software is +furnished to do so, subject to the following conditions: + +The above copyright notice and this permission notice shall be included in all +copies or substantial portions of the Software. + +THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR +IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, +FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE +AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER +LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, +OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE +SOFTWARE. diff --git a/dg-ui/node_modules/@parcel/watcher-win32-x64/README.md b/dg-ui/node_modules/@parcel/watcher-win32-x64/README.md new file mode 100644 index 0000000..7620831 --- /dev/null +++ b/dg-ui/node_modules/@parcel/watcher-win32-x64/README.md @@ -0,0 +1 @@ +This is the win32-x64 build of @parcel/watcher. See https://github.com/parcel-bundler/watcher for details. \ No newline at end of file diff --git a/dg-ui/node_modules/@parcel/watcher-win32-x64/package.json b/dg-ui/node_modules/@parcel/watcher-win32-x64/package.json new file mode 100644 index 0000000..02faaf2 --- /dev/null +++ b/dg-ui/node_modules/@parcel/watcher-win32-x64/package.json @@ -0,0 +1,30 @@ +{ + "name": "@parcel/watcher-win32-x64", + "version": "2.6.0", + "main": "watcher.node", + "repository": { + "type": "git", + "url": "https://github.com/parcel-bundler/watcher.git" + }, + "description": "A native C++ Node module for querying and subscribing to filesystem events. Used by Parcel 2.", + "license": "MIT", + "publishConfig": { + "access": "public" + }, + "funding": { + "type": "opencollective", + "url": "https://opencollective.com/parcel" + }, + "files": [ + "watcher.node" + ], + "engines": { + "node": ">= 10.0.0" + }, + "os": [ + "win32" + ], + "cpu": [ + "x64" + ] +} diff --git a/dg-ui/node_modules/@parcel/watcher-win32-x64/watcher.node b/dg-ui/node_modules/@parcel/watcher-win32-x64/watcher.node new file mode 100644 index 0000000..1cc5150 Binary files /dev/null and b/dg-ui/node_modules/@parcel/watcher-win32-x64/watcher.node differ diff --git a/dg-ui/node_modules/@parcel/watcher/LICENSE b/dg-ui/node_modules/@parcel/watcher/LICENSE new file mode 100644 index 0000000..7fb9bc9 --- /dev/null +++ b/dg-ui/node_modules/@parcel/watcher/LICENSE @@ -0,0 +1,21 @@ +MIT License + +Copyright (c) 2017-present Devon Govett + +Permission is hereby granted, free of charge, to any person obtaining a copy +of this software and associated documentation files (the "Software"), to deal +in the Software without restriction, including without limitation the rights +to use, copy, modify, merge, publish, distribute, sublicense, and/or sell +copies of the Software, and to permit persons to whom the Software is +furnished to do so, subject to the following conditions: + +The above copyright notice and this permission notice shall be included in all +copies or substantial portions of the Software. + +THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR +IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, +FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE +AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER +LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, +OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE +SOFTWARE. diff --git a/dg-ui/node_modules/@parcel/watcher/README.md b/dg-ui/node_modules/@parcel/watcher/README.md new file mode 100644 index 0000000..28e74f0 --- /dev/null +++ b/dg-ui/node_modules/@parcel/watcher/README.md @@ -0,0 +1,136 @@ +# @parcel/watcher + +A native C++ Node module for querying and subscribing to filesystem events. Used by [Parcel 2](https://github.com/parcel-bundler/parcel). + +## Features + +- **Watch** - subscribe to realtime recursive directory change notifications when files or directories are created, updated, or deleted. +- **Query** - performantly query for historical change events in a directory, even when your program is not running. +- **Native** - implemented in C++ for performance and low-level integration with the operating system. +- **Cross platform** - includes backends for macOS, Linux, Windows, FreeBSD, and Watchman. +- **Performant** - events are throttled in C++ so the JavaScript thread is not overwhelmed during large filesystem changes (e.g. `git checkout` or `npm install`). +- **Scalable** - tens of thousands of files can be watched or queried at once with good performance. + +## Example + +```javascript +const watcher = require('@parcel/watcher'); +const path = require('path'); + +// Subscribe to events +let subscription = await watcher.subscribe(process.cwd(), (err, events) => { + console.log(events); +}); + +// later on... +await subscription.unsubscribe(); + +// Get events since some saved snapshot in the past +let snapshotPath = path.join(process.cwd(), 'snapshot.txt'); +let events = await watcher.getEventsSince(process.cwd(), snapshotPath); + +// Save a snapshot for later +await watcher.writeSnapshot(process.cwd(), snapshotPath); +``` + +## Watching + +`@parcel/watcher` supports subscribing to realtime notifications of changes in a directory. It works recursively, so changes in sub-directories will also be emitted. + +Events are throttled and coalesced for performance during large changes like `git checkout` or `npm install`, and a single notification will be emitted with all of the events at the end. + +Only one notification will be emitted per file. For example, if a file was both created and updated since the last event, you'll get only a `create` event. If a file is both created and deleted, you will not be notifed of that file. Renames cause two events: a `delete` for the old name, and a `create` for the new name. + +```javascript +let subscription = await watcher.subscribe(process.cwd(), (err, events) => { + console.log(events); +}); +``` + +Events have two properties: + +- `type` - the event type: `create`, `update`, or `delete`. +- `path` - the absolute path to the file or directory. + +To unsubscribe from change notifications, call the `unsubscribe` method on the returned subscription object. + +```javascript +await subscription.unsubscribe(); +``` + +`@parcel/watcher` has the following watcher backends, listed in priority order: + +- [FSEvents](https://developer.apple.com/documentation/coreservices/file_system_events) on macOS +- [Watchman](https://facebook.github.io/watchman/) if installed +- [inotify](http://man7.org/linux/man-pages/man7/inotify.7.html) on Linux +- [ReadDirectoryChangesW](https://msdn.microsoft.com/en-us/library/windows/desktop/aa365465%28v%3Dvs.85%29.aspx) on Windows +- [kqueue](https://man.freebsd.org/cgi/man.cgi?kqueue) on FreeBSD, or as an alternative to FSEvents on macOS + +You can specify the exact backend you wish to use by passing the `backend` option. If that backend is not available on the current platform, the default backend will be used instead. See below for the list of backend names that can be passed to the options. + +## Querying + +`@parcel/watcher` also supports querying for historical changes made in a directory, even when your program is not running. This makes it easy to invalidate a cache and re-build only the files that have changed, for example. It can be **significantly** faster than traversing the entire filesystem to determine what files changed, depending on the platform. + +In order to query for historical changes, you first need a previous snapshot to compare to. This can be saved to a file with the `writeSnapshot` function, e.g. just before your program exits. + +```javascript +await watcher.writeSnapshot(dirPath, snapshotPath); +``` + +When your program starts up, you can query for changes that have occurred since that snapshot using the `getEventsSince` function. + +```javascript +let events = await watcher.getEventsSince(dirPath, snapshotPath); +``` + +The events returned are exactly the same as the events that would be passed to the `subscribe` callback (see above). + +`@parcel/watcher` has the following watcher backends, listed in priority order: + +- [FSEvents](https://developer.apple.com/documentation/coreservices/file_system_events) on macOS +- [Watchman](https://facebook.github.io/watchman/) if installed +- [fts](http://man7.org/linux/man-pages/man3/fts.3.html) (brute force) on Linux and FreeBSD +- [FindFirstFile](https://docs.microsoft.com/en-us/windows/desktop/api/fileapi/nf-fileapi-findfirstfilea) (brute force) on Windows + +The FSEvents (macOS) and Watchman backends are significantly more performant than the brute force backends used by default on Linux and Windows, for example returning results in miliseconds instead of seconds for large directory trees. This is because a background daemon monitoring filesystem changes on those platforms allows us to query cached data rather than traversing the filesystem manually (brute force). + +macOS has good performance with FSEvents by default. For the best performance on other platforms, install [Watchman](https://facebook.github.io/watchman/) and it will be used by `@parcel/watcher` automatically. + +You can specify the exact backend you wish to use by passing the `backend` option. If that backend is not available on the current platform, the default backend will be used instead. See below for the list of backend names that can be passed to the options. + +## Options + +All of the APIs in `@parcel/watcher` support the following options, which are passed as an object as the last function argument. + +- `ignore` - an array of paths or glob patterns to ignore. uses [`is-glob`](https://github.com/micromatch/is-glob) to distinguish paths from globs. glob patterns are parsed with [`picomatch`](https://github.com/micromatch/picomatch) (see [features](https://github.com/micromatch/picomatch#globbing-features)). + - paths can be relative or absolute and can either be files or directories. No events will be emitted about these files or directories or their children. + - glob patterns match on relative paths from the root that is watched. No events will be emitted for matching paths. +- `backend` - the name of an explicitly chosen backend to use. Allowed options are `"fs-events"`, `"watchman"`, `"inotify"`, `"kqueue"`, `"windows"`, or `"brute-force"` (only for querying). If the specified backend is not available on the current platform, the default backend will be used instead. + +## WASM + +The `@parcel/watcher-wasm` package can be used in place of `@parcel/watcher` on unsupported platforms. It relies on the Node `fs` module, so in non-Node environments such as browsers, an `fs` polyfill will be needed. + +**Note**: the WASM implementation is significantly less efficient than the native implementations because it must crawl the file system to watch each directory individually. Use the native `@parcel/watcher` package wherever possible. + +```js +import {subscribe} from '@parcel/watcher-wasm'; + +// Use the module as documented above. +subscribe(/* ... */); +``` + +## Who is using this? + +- [Parcel 2](https://parceljs.org/) +- [VSCode](https://code.visualstudio.com/updates/v1_62#_file-watching-changes) +- [Tailwind CSS Intellisense](https://github.com/tailwindlabs/tailwindcss-intellisense) +- [Gatsby Cloud](https://twitter.com/chatsidhartha/status/1435647412828196867) +- [Nx](https://nx.dev) +- [Nuxt](https://nuxt.com) +- [Meteor](https://github.com/meteor/meteor) + +## License + +MIT diff --git a/dg-ui/node_modules/@parcel/watcher/binding.gyp b/dg-ui/node_modules/@parcel/watcher/binding.gyp new file mode 100644 index 0000000..3c12d52 --- /dev/null +++ b/dg-ui/node_modules/@parcel/watcher/binding.gyp @@ -0,0 +1,109 @@ +{ + "targets": [ + { + "target_name": "watcher", + "defines": [ "NAPI_DISABLE_CPP_EXCEPTIONS" ], + "sources": [ "src/binding.cc", "src/Watcher.cc", "src/Backend.cc", "src/DirTree.cc", "src/Glob.cc", "src/Debounce.cc" ], + "include_dirs" : [" unknown; + export interface AsyncSubscription { + unsubscribe(): Promise; + } + export interface Event { + path: FilePath; + type: EventType; + } + export function getEventsSince( + dir: FilePath, + snapshot: FilePath, + opts?: Options, + ): Promise; + export function subscribe( + dir: FilePath, + fn: SubscribeCallback, + opts?: Options, + ): Promise; + export function unsubscribe( + dir: FilePath, + fn: SubscribeCallback, + opts?: Options, + ): Promise; + export function writeSnapshot( + dir: FilePath, + snapshot: FilePath, + opts?: Options, + ): Promise; +} + +export = ParcelWatcher; diff --git a/dg-ui/node_modules/@parcel/watcher/index.js b/dg-ui/node_modules/@parcel/watcher/index.js new file mode 100644 index 0000000..78ee744 --- /dev/null +++ b/dg-ui/node_modules/@parcel/watcher/index.js @@ -0,0 +1,44 @@ +const {createWrapper} = require('./wrapper'); + +let name = `@parcel/watcher-${process.platform}-${process.arch}`; +if (process.platform === 'linux') { + const {MUSL, familySync} = require('detect-libc'); + const family = familySync(); + if (family === MUSL) { + name += '-musl'; + } else { + name += '-glibc'; + } +} + +let binding; +try { + binding = require(name); +} catch (err) { + handleError(err); + try { + binding = require('./build/Release/watcher.node'); + } catch (err) { + handleError(err); + try { + binding = require('./build/Debug/watcher.node'); + } catch (err) { + handleError(err); + throw new Error( + `No prebuild or local build of @parcel/watcher found. Tried ${name}. Please ensure it is installed (don't use --no-optional when installing with npm). Otherwise it is possible we don't support your platform yet. If this is the case, please report an issue to https://github.com/parcel-bundler/watcher.`, + ); + } + } +} + +function handleError(err) { + if (err?.code !== 'MODULE_NOT_FOUND') { + throw err; + } +} + +const wrapper = createWrapper(binding); +exports.writeSnapshot = wrapper.writeSnapshot; +exports.getEventsSince = wrapper.getEventsSince; +exports.subscribe = wrapper.subscribe; +exports.unsubscribe = wrapper.unsubscribe; diff --git a/dg-ui/node_modules/@parcel/watcher/index.js.flow b/dg-ui/node_modules/@parcel/watcher/index.js.flow new file mode 100644 index 0000000..1b6e150 --- /dev/null +++ b/dg-ui/node_modules/@parcel/watcher/index.js.flow @@ -0,0 +1,45 @@ +// @flow +declare type FilePath = string; +declare type GlobPattern = string; + +export type BackendType = + | 'fs-events' + | 'watchman' + | 'inotify' + | 'windows' + | 'brute-force'; +export type EventType = 'create' | 'update' | 'delete'; +export interface Options { + ignore?: Array; + backend?: BackendType; +} +export type SubscribeCallback = (err: ?Error, events: Array) => mixed; +export interface AsyncSubscription { + unsubscribe(): Promise; +} +export interface Event { + path: FilePath; + type: EventType; +} +declare module.exports: { + getEventsSince( + dir: FilePath, + snapshot: FilePath, + opts?: Options, + ): Promise>, + subscribe( + dir: FilePath, + fn: SubscribeCallback, + opts?: Options, + ): Promise, + unsubscribe( + dir: FilePath, + fn: SubscribeCallback, + opts?: Options, + ): Promise, + writeSnapshot( + dir: FilePath, + snapshot: FilePath, + opts?: Options, + ): Promise, +}; diff --git a/dg-ui/node_modules/@parcel/watcher/package.json b/dg-ui/node_modules/@parcel/watcher/package.json new file mode 100644 index 0000000..dbdfab2 --- /dev/null +++ b/dg-ui/node_modules/@parcel/watcher/package.json @@ -0,0 +1,87 @@ +{ + "name": "@parcel/watcher", + "version": "2.6.0", + "main": "index.js", + "types": "index.d.ts", + "repository": { + "type": "git", + "url": "https://github.com/parcel-bundler/watcher.git" + }, + "description": "A native C++ Node module for querying and subscribing to filesystem events. Used by Parcel 2.", + "license": "MIT", + "publishConfig": { + "access": "public" + }, + "funding": { + "type": "opencollective", + "url": "https://opencollective.com/parcel" + }, + "files": [ + "index.js", + "index.js.flow", + "index.d.ts", + "wrapper.js", + "package.json", + "README.md", + "LICENSE", + "src", + "scripts/build-from-source.js", + "binding.gyp" + ], + "scripts": { + "prebuild": "prebuildify --napi --strip --tag-libc", + "format": "prettier --write \"./**/*.{js,mjs,json,md,ts,flow}\"", + "build": "node-gyp rebuild", + "install": "node scripts/build-from-source.js", + "test": "mocha" + }, + "engines": { + "node": ">= 10.0.0" + }, + "husky": { + "hooks": { + "pre-commit": "lint-staged" + } + }, + "lint-staged": { + "*.{js,mjs,json,md,ts,flow}": [ + "prettier --write", + "git add" + ] + }, + "dependencies": { + "detect-libc": "^2.0.3", + "is-glob": "^4.0.3", + "node-addon-api": "^7.0.0", + "picomatch": "^4.0.4" + }, + "devDependencies": { + "esbuild": "^0.19.8", + "fs-extra": "^10.0.0", + "husky": "^7.0.2", + "lint-staged": "^11.1.2", + "mocha": "^9.1.1", + "napi-wasm": "^1.1.0", + "prebuildify": "^6.0.1", + "prettier": "^2.3.2" + }, + "binary": { + "napi_versions": [ + 3 + ] + }, + "optionalDependencies": { + "@parcel/watcher-darwin-x64": "2.6.0", + "@parcel/watcher-darwin-arm64": "2.6.0", + "@parcel/watcher-win32-x64": "2.6.0", + "@parcel/watcher-win32-arm64": "2.6.0", + "@parcel/watcher-linux-x64-glibc": "2.6.0", + "@parcel/watcher-linux-x64-musl": "2.6.0", + "@parcel/watcher-linux-arm64-glibc": "2.6.0", + "@parcel/watcher-linux-arm64-musl": "2.6.0", + "@parcel/watcher-linux-arm-glibc": "2.6.0", + "@parcel/watcher-linux-arm-musl": "2.6.0", + "@parcel/watcher-android-arm64": "2.6.0", + "@parcel/watcher-freebsd-x64": "2.6.0" + } +} diff --git a/dg-ui/node_modules/@parcel/watcher/scripts/build-from-source.js b/dg-ui/node_modules/@parcel/watcher/scripts/build-from-source.js new file mode 100644 index 0000000..170a91a --- /dev/null +++ b/dg-ui/node_modules/@parcel/watcher/scripts/build-from-source.js @@ -0,0 +1,16 @@ +#!/usr/bin/env node + +const {spawn} = require('child_process'); + +if (process.env.npm_config_build_from_source === 'true') { + build(); +} + +function build() { + spawn('node-gyp', ['rebuild'], {stdio: 'inherit', shell: true}).on( + 'exit', + function (code) { + process.exit(code); + }, + ); +} diff --git a/dg-ui/node_modules/@parcel/watcher/src/Backend.cc b/dg-ui/node_modules/@parcel/watcher/src/Backend.cc new file mode 100644 index 0000000..09a53d5 --- /dev/null +++ b/dg-ui/node_modules/@parcel/watcher/src/Backend.cc @@ -0,0 +1,186 @@ +#ifdef FS_EVENTS +#include "macos/FSEventsBackend.hh" +#endif +#ifdef WATCHMAN +#include "watchman/WatchmanBackend.hh" +#endif +#ifdef WINDOWS +#include "windows/WindowsBackend.hh" +#endif +#ifdef INOTIFY +#include "linux/InotifyBackend.hh" +#endif +#ifdef KQUEUE +#include "kqueue/KqueueBackend.hh" +#endif +#ifdef __wasm32__ +#include "wasm/WasmBackend.hh" +#endif +#include "shared/BruteForceBackend.hh" + +#include "Backend.hh" +#include + +static std::unordered_map>& getSharedBackends() { + static std::unordered_map>* sharedBackends = + new std::unordered_map>(); + return *sharedBackends; +} + +std::shared_ptr getBackend(std::string backend) { + // Use FSEvents on macOS by default. + // Use watchman by default if available on other platforms. + // Fall back to brute force. + #ifdef FS_EVENTS + if (backend == "fs-events" || backend == "default") { + return std::make_shared(); + } + #endif + #ifdef WATCHMAN + if ((backend == "watchman" || backend == "default") && WatchmanBackend::checkAvailable()) { + return std::make_shared(); + } + #endif + #ifdef WINDOWS + if (backend == "windows" || backend == "default") { + return std::make_shared(); + } + #endif + #ifdef INOTIFY + if (backend == "inotify" || backend == "default") { + return std::make_shared(); + } + #endif + #ifdef KQUEUE + if (backend == "kqueue" || backend == "default") { + return std::make_shared(); + } + #endif + #ifdef __wasm32__ + if (backend == "wasm" || backend == "default") { + return std::make_shared(); + } + #endif + if (backend == "brute-force" || backend == "default") { + return std::make_shared(); + } + + return nullptr; +} + +std::shared_ptr Backend::getShared(std::string backend) { + auto found = getSharedBackends().find(backend); + if (found != getSharedBackends().end()) { + return found->second; + } + + auto result = getBackend(backend); + if (!result) { + return getShared("default"); + } + + result->run(); + getSharedBackends().emplace(backend, result); + return result; +} + +void removeShared(Backend *backend) { + for (auto it = getSharedBackends().begin(); it != getSharedBackends().end(); it++) { + if (it->second.get() == backend) { + getSharedBackends().erase(it); + break; + } + } + + // Free up memory. + if (getSharedBackends().size() == 0) { + getSharedBackends().rehash(0); + } +} + +void Backend::run() { + #ifndef __wasm32__ + mThread = std::thread([this] () { + try { + start(); + } catch (std::exception &err) { + handleError(err); + } + }); + + if (mThread.joinable()) { + mStartedSignal.wait(); + } + #else + try { + start(); + } catch (std::exception &err) { + handleError(err); + } + #endif +} + +void Backend::notifyStarted() { + mStartedSignal.notify(); +} + +void Backend::start() { + notifyStarted(); +} + +Backend::~Backend() { + #ifndef __wasm32__ + // Wait for thread to stop + if (mThread.joinable()) { + // If the backend is being destroyed from the thread itself, detach, otherwise join. + if (mThread.get_id() == std::this_thread::get_id()) { + mThread.detach(); + } else { + mThread.join(); + } + } + #endif +} + +void Backend::watch(WatcherRef watcher) { + std::unique_lock lock(mMutex); + auto res = mSubscriptions.find(watcher); + if (res == mSubscriptions.end()) { + try { + this->subscribe(watcher); + mSubscriptions.insert(watcher); + } catch (std::exception&) { + unref(); + throw; + } + } +} + +void Backend::unwatch(WatcherRef watcher) { + std::unique_lock lock(mMutex); + size_t deleted = mSubscriptions.erase(watcher); + if (deleted > 0) { + this->unsubscribe(watcher); + unref(); + } +} + +void Backend::unref() { + if (mSubscriptions.size() == 0) { + removeShared(this); + } +} + +void Backend::handleWatcherError(WatcherError &err) { + unwatch(err.mWatcher); + err.mWatcher->notifyError(err); +} + +void Backend::handleError(std::exception &err) { + std::unique_lock lock(mMutex); + for (auto it = mSubscriptions.begin(); it != mSubscriptions.end(); it++) { + (*it)->notifyError(err); + } + + removeShared(this); +} diff --git a/dg-ui/node_modules/@parcel/watcher/src/Backend.hh b/dg-ui/node_modules/@parcel/watcher/src/Backend.hh new file mode 100644 index 0000000..d673bd1 --- /dev/null +++ b/dg-ui/node_modules/@parcel/watcher/src/Backend.hh @@ -0,0 +1,37 @@ +#ifndef BACKEND_H +#define BACKEND_H + +#include "Event.hh" +#include "Watcher.hh" +#include "Signal.hh" +#include + +class Backend { +public: + virtual ~Backend(); + void run(); + void notifyStarted(); + + virtual void start(); + virtual void writeSnapshot(WatcherRef watcher, std::string *snapshotPath) = 0; + virtual void getEventsSince(WatcherRef watcher, std::string *snapshotPath) = 0; + virtual void subscribe(WatcherRef watcher) = 0; + virtual void unsubscribe(WatcherRef watcher) = 0; + + static std::shared_ptr getShared(std::string backend); + + void watch(WatcherRef watcher); + void unwatch(WatcherRef watcher); + void unref(); + void handleWatcherError(WatcherError &err); + + std::mutex mMutex; + std::thread mThread; +private: + std::unordered_set mSubscriptions; + Signal mStartedSignal; + + void handleError(std::exception &err); +}; + +#endif diff --git a/dg-ui/node_modules/@parcel/watcher/src/Debounce.cc b/dg-ui/node_modules/@parcel/watcher/src/Debounce.cc new file mode 100644 index 0000000..be07e78 --- /dev/null +++ b/dg-ui/node_modules/@parcel/watcher/src/Debounce.cc @@ -0,0 +1,113 @@ +#include "Debounce.hh" + +#ifdef __wasm32__ +extern "C" void on_timeout(void *ctx) { + Debounce *debounce = (Debounce *)ctx; + debounce->notify(); +} +#endif + +std::shared_ptr Debounce::getShared() { + static std::weak_ptr sharedInstance; + std::shared_ptr shared = sharedInstance.lock(); + if (!shared) { + shared = std::make_shared(); + sharedInstance = shared; + } + + return shared; +} + +Debounce::Debounce() { + mRunning = true; + #ifndef __wasm32__ + mThread = std::thread([this] () { + loop(); + }); + #endif +} + +Debounce::~Debounce() { + mRunning = false; + #ifndef __wasm32__ + mWaitSignal.notify(); + mThread.join(); + #endif +} + +void Debounce::add(void *key, std::function cb) { + std::unique_lock lock(mMutex); + mCallbacks.emplace(key, cb); +} + +void Debounce::remove(void *key) { + std::unique_lock lock(mMutex); + mCallbacks.erase(key); +} + +void Debounce::trigger() { + std::unique_lock lock(mMutex); + #ifdef __wasm32__ + notifyIfReady(); + #else + mWaitSignal.notify(); + #endif +} + +#ifndef __wasm32__ +void Debounce::loop() { + while (mRunning) { + mWaitSignal.wait(); + if (!mRunning) { + break; + } + + notifyIfReady(); + } +} +#endif + +void Debounce::notifyIfReady() { + if (!mRunning) { + return; + } + + // If we haven't seen an event in more than the maximum wait time, notify callbacks immediately + // to ensure that we don't wait forever. Otherwise, wait for the minimum wait time and batch + // subsequent fast changes. This also means the first file change in a batch is notified immediately, + // separately from the rest of the batch. This seems like an acceptable tradeoff if the common case + // is that only a single file was updated at a time. + auto time = std::chrono::steady_clock::now(); + if ((time - mLastTime) > std::chrono::milliseconds(MAX_WAIT_TIME)) { + mLastTime = time; + notify(); + } else { + wait(); + } +} + +void Debounce::wait() { + #ifdef __wasm32__ + clear_timeout(mTimeout); + mTimeout = set_timeout(MIN_WAIT_TIME, this); + #else + auto status = mWaitSignal.waitFor(std::chrono::milliseconds(MIN_WAIT_TIME)); + if (mRunning && (status == std::cv_status::timeout)) { + notify(); + } + #endif +} + +void Debounce::notify() { + std::unique_lock lock(mMutex); + + mLastTime = std::chrono::steady_clock::now(); + for (auto it = mCallbacks.begin(); it != mCallbacks.end(); it++) { + auto cb = it->second; + cb(); + } + + #ifndef __wasm32__ + mWaitSignal.reset(); + #endif +} diff --git a/dg-ui/node_modules/@parcel/watcher/src/Debounce.hh b/dg-ui/node_modules/@parcel/watcher/src/Debounce.hh new file mode 100644 index 0000000..a17fdef --- /dev/null +++ b/dg-ui/node_modules/@parcel/watcher/src/Debounce.hh @@ -0,0 +1,49 @@ +#ifndef DEBOUNCE_H +#define DEBOUNCE_H + +#include +#include +#include +#include "Signal.hh" + +#define MIN_WAIT_TIME 50 +#define MAX_WAIT_TIME 500 + +#ifdef __wasm32__ +extern "C" { + int set_timeout(int ms, void *ctx); + void clear_timeout(int timeout); + void on_timeout(void *ctx); +}; +#endif + +class Debounce { +public: + static std::shared_ptr getShared(); + + Debounce(); + ~Debounce(); + + void add(void *key, std::function cb); + void remove(void *key); + void trigger(); + void notify(); + +private: + bool mRunning; + std::mutex mMutex; + #ifdef __wasm32__ + int mTimeout; + #else + Signal mWaitSignal; + std::thread mThread; + #endif + std::unordered_map> mCallbacks; + std::chrono::time_point mLastTime; + + void loop(); + void notifyIfReady(); + void wait(); +}; + +#endif diff --git a/dg-ui/node_modules/@parcel/watcher/src/DirTree.cc b/dg-ui/node_modules/@parcel/watcher/src/DirTree.cc new file mode 100644 index 0000000..b7eddd8 --- /dev/null +++ b/dg-ui/node_modules/@parcel/watcher/src/DirTree.cc @@ -0,0 +1,164 @@ +#include "DirTree.hh" +#include + +// "Meyer's singleton", construction is ordered by use, likewise (reverse) for destruction. +// https://stackoverflow.com/a/17713799 +// https://laristra.github.io/flecsi/src/developer-guide/patterns/meyers_singleton.html +static std::mutex& mDirCacheMutex() { + static std::mutex mutex; + return mutex; +} + +static std::unordered_map>& dirTreeCache() { + static std::unordered_map> cache; + return cache; +} + +struct DirTreeDeleter { + void operator()(DirTree *tree) { + std::lock_guard lock(mDirCacheMutex()); + std::unordered_map> &cache = dirTreeCache(); + cache.erase(tree->root); + delete tree; + + // Free up memory. + if (cache.size() == 0) { + cache.rehash(0); + } + } +}; + +std::shared_ptr DirTree::getCached(std::string root) { + std::lock_guard lock(mDirCacheMutex()); + std::unordered_map> &cache = dirTreeCache(); + + auto found = cache.find(root); + std::shared_ptr tree; + + // Use cached tree, or create an empty one. + if (found != cache.end()) { + tree = found->second.lock(); + } else { + tree = std::shared_ptr(new DirTree(root), DirTreeDeleter()); + cache.emplace(root, tree); + } + + return tree; +} + +DirTree::DirTree(std::string root, FILE *f) : root(root), isComplete(true) { + size_t size; + if (fscanf(f, "%zu", &size)) { + for (size_t i = 0; i < size; i++) { + DirEntry entry(f); + entries.emplace(entry.path, entry); + } + } +} + +// Internal find method that has no lock +DirEntry *DirTree::_find(std::string path) { + auto found = entries.find(path); + if (found == entries.end()) { + return NULL; + } + + return &found->second; +} + +DirEntry *DirTree::add(std::string path, uint64_t mtime, bool isDir) { + std::lock_guard lock(mDirCacheMutex()); + + DirEntry entry(path, mtime, isDir); + auto it = entries.emplace(entry.path, entry); + return &it.first->second; +} + +DirEntry *DirTree::find(std::string path) { + std::lock_guard lock(mDirCacheMutex()); + return _find(path); +} + +DirEntry *DirTree::update(std::string path, uint64_t mtime) { + std::lock_guard lock(mDirCacheMutex()); + + DirEntry *found = _find(path); + if (found) { + found->mtime = mtime; + } + + return found; +} + +void DirTree::remove(std::string path) { + std::lock_guard lock(mDirCacheMutex()); + + DirEntry *found = _find(path); + + // Remove all sub-entries if this is a directory + if (found && found->isDir) { + std::string pathStart = path + DIR_SEP; + for (auto it = entries.begin(); it != entries.end();) { + if (it->first.rfind(pathStart, 0) == 0) { + it = entries.erase(it); + } else { + it++; + } + } + } + + entries.erase(path); +} + +void DirTree::write(FILE *f) { + std::lock_guard lock(mDirCacheMutex()); + + fprintf(f, "%zu\n", entries.size()); + for (auto it = entries.begin(); it != entries.end(); it++) { + it->second.write(f); + } +} + +void DirTree::getChanges(DirTree *snapshot, EventList &events) { + std::lock_guard lock(mDirCacheMutex()); + std::lock_guard snapshotLock(snapshot->mMutex); + + for (auto it = entries.begin(); it != entries.end(); it++) { + auto found = snapshot->entries.find(it->first); + if (found == snapshot->entries.end()) { + events.create(it->second.path); + } else if (found->second.mtime != it->second.mtime && !found->second.isDir && !it->second.isDir) { + events.update(it->second.path); + } + } + + for (auto it = snapshot->entries.begin(); it != snapshot->entries.end(); it++) { + size_t count = entries.count(it->first); + if (count == 0) { + events.remove(it->second.path); + } + } +} + +DirEntry::DirEntry(std::string p, uint64_t t, bool d) { + path = p; + mtime = t; + isDir = d; + state = NULL; +} + +DirEntry::DirEntry(FILE *f) { + size_t size; + if (fscanf(f, "%zu", &size)) { + path.resize(size); + if (fread(&path[0], sizeof(char), size, f)) { + int d = 0; + fscanf(f, "%" PRIu64 " %d\n", &mtime, &d); + isDir = d == 1; + } + } +} + +void DirEntry::write(FILE *f) const { + fprintf(f, "%zu%s%" PRIu64 " %d\n", path.size(), path.c_str(), mtime, isDir); +} diff --git a/dg-ui/node_modules/@parcel/watcher/src/DirTree.hh b/dg-ui/node_modules/@parcel/watcher/src/DirTree.hh new file mode 100644 index 0000000..328f469 --- /dev/null +++ b/dg-ui/node_modules/@parcel/watcher/src/DirTree.hh @@ -0,0 +1,50 @@ +#ifndef DIR_TREE_H +#define DIR_TREE_H + +#include +#include +#include +#include "Event.hh" + +#ifdef _WIN32 +#define DIR_SEP "\\" +#else +#define DIR_SEP "/" +#endif + +struct DirEntry { + std::string path; + uint64_t mtime; + bool isDir; + mutable void *state; + + DirEntry(std::string p, uint64_t t, bool d); + DirEntry(FILE *f); + void write(FILE *f) const; + bool operator==(const DirEntry &other) const { + return path == other.path; + } +}; + +class DirTree { +public: + static std::shared_ptr getCached(std::string root); + DirTree(std::string root) : root(root), isComplete(false) {} + DirTree(std::string root, FILE *f); + DirEntry *add(std::string path, uint64_t mtime, bool isDir); + DirEntry *find(std::string path); + DirEntry *update(std::string path, uint64_t mtime); + void remove(std::string path); + void write(FILE *f); + void getChanges(DirTree *snapshot, EventList &events); + + std::mutex mMutex; + std::string root; + bool isComplete; + std::unordered_map entries; + +private: + DirEntry *_find(std::string path); +}; + +#endif diff --git a/dg-ui/node_modules/@parcel/watcher/src/Event.hh b/dg-ui/node_modules/@parcel/watcher/src/Event.hh new file mode 100644 index 0000000..8d09712 --- /dev/null +++ b/dg-ui/node_modules/@parcel/watcher/src/Event.hh @@ -0,0 +1,109 @@ +#ifndef EVENT_H +#define EVENT_H + +#include +#include +#include "wasm/include.h" +#include +#include +#include +#include + +using namespace Napi; + +struct Event { + std::string path; + bool isCreated; + bool isDeleted; + Event(std::string path) : path(path), isCreated(false), isDeleted(false) {} + + Value toJS(const Env& env) { + EscapableHandleScope scope(env); + Object res = Object::New(env); + std::string type = isCreated ? "create" : isDeleted ? "delete" : "update"; + res.Set(String::New(env, "path"), String::New(env, path.c_str())); + res.Set(String::New(env, "type"), String::New(env, type.c_str())); + return scope.Escape(res); + } +}; + +class EventList { +public: + void create(std::string path) { + std::lock_guard l(mMutex); + Event *event = internalUpdate(path); + if (event->isDeleted) { + // Assume update event when rapidly removed and created + // https://github.com/parcel-bundler/watcher/issues/72 + event->isDeleted = false; + } else { + event->isCreated = true; + } + } + + Event *update(std::string path) { + std::lock_guard l(mMutex); + return internalUpdate(path); + } + + void remove(std::string path) { + std::lock_guard l(mMutex); + Event *event = internalUpdate(path); + event->isDeleted = true; + } + + size_t size() { + std::lock_guard l(mMutex); + return mEvents.size(); + } + + std::vector getEvents() { + std::lock_guard l(mMutex); + std::vector eventsCloneVector; + for(auto it = mEvents.begin(); it != mEvents.end(); ++it) { + if (!(it->second.isCreated && it->second.isDeleted)) { + eventsCloneVector.push_back(it->second); + } + } + return eventsCloneVector; + } + + void clear() { + std::lock_guard l(mMutex); + mEvents.clear(); + mError.reset(); + } + + void error(std::string err) { + std::lock_guard l(mMutex); + if (!mError.has_value()) { + mError.emplace(err); + } + } + + bool hasError() { + std::lock_guard l(mMutex); + return mError.has_value(); + } + + std::string getError() { + std::lock_guard l(mMutex); + return mError.value_or(""); + } + +private: + mutable std::mutex mMutex; + std::map mEvents; + std::optional mError; + Event *internalUpdate(std::string path) { + auto found = mEvents.find(path); + if (found == mEvents.end()) { + auto it = mEvents.emplace(path, Event(path)); + return &it.first->second; + } + + return &found->second; + } +}; + +#endif diff --git a/dg-ui/node_modules/@parcel/watcher/src/Glob.cc b/dg-ui/node_modules/@parcel/watcher/src/Glob.cc new file mode 100644 index 0000000..a4a1722 --- /dev/null +++ b/dg-ui/node_modules/@parcel/watcher/src/Glob.cc @@ -0,0 +1,22 @@ +#include "Glob.hh" + +#ifdef __wasm32__ +extern "C" bool wasm_regex_match(const char *s, const char *regex); +#endif + +Glob::Glob(std::string raw) { + mRaw = raw; + mHash = std::hash()(raw); + #ifndef __wasm32__ + mRegex = std::regex(raw); + #endif +} + +bool Glob::isIgnored(std::string relative_path) const { + // Use native JS regex engine for wasm to reduce binary size. + #ifdef __wasm32__ + return wasm_regex_match(relative_path.c_str(), mRaw.c_str()); + #else + return std::regex_match(relative_path, mRegex); + #endif +} diff --git a/dg-ui/node_modules/@parcel/watcher/src/Glob.hh b/dg-ui/node_modules/@parcel/watcher/src/Glob.hh new file mode 100644 index 0000000..b5fc375 --- /dev/null +++ b/dg-ui/node_modules/@parcel/watcher/src/Glob.hh @@ -0,0 +1,34 @@ +#ifndef GLOB_H +#define GLOB_H + +#include +#include + +struct Glob { + std::size_t mHash; + std::string mRaw; + #ifndef __wasm32__ + std::regex mRegex; + #endif + + Glob(std::string raw); + + bool operator==(const Glob &other) const { + return mHash == other.mHash && mRaw == other.mRaw; + } + + bool isIgnored(std::string relative_path) const; +}; + +namespace std +{ + template <> + struct hash + { + size_t operator()(const Glob& g) const { + return g.mHash; + } + }; +} + +#endif diff --git a/dg-ui/node_modules/@parcel/watcher/src/PromiseRunner.hh b/dg-ui/node_modules/@parcel/watcher/src/PromiseRunner.hh new file mode 100644 index 0000000..4ca3bb6 --- /dev/null +++ b/dg-ui/node_modules/@parcel/watcher/src/PromiseRunner.hh @@ -0,0 +1,101 @@ +#ifndef PROMISE_RUNNER_H +#define PROMISE_RUNNER_H + +#include +#include "wasm/include.h" +#include + +using namespace Napi; + +class PromiseRunner { +public: + const Env env; + Promise::Deferred deferred; + + PromiseRunner(Env env) : env(env), deferred(Promise::Deferred::New(env)) { + napi_status status = napi_create_async_work(env, nullptr, env.Undefined(), + onExecute, onWorkComplete, this, &work); + if (status != napi_ok) { + work = nullptr; + const napi_extended_error_info *error_info = 0; + napi_get_last_error_info(env, &error_info); + if (error_info->error_message) { + Error::New(env, error_info->error_message).ThrowAsJavaScriptException(); + } else { + Error::New(env).ThrowAsJavaScriptException(); + } + } + } + + virtual ~PromiseRunner() {} + + Value queue() { + if (work) { + napi_status status = napi_queue_async_work(env, work); + if (status != napi_ok) { + onError(Error::New(env)); + } + } + + return deferred.Promise(); + } + +private: + napi_async_work work; + std::string error; + + static void onExecute(napi_env env, void *this_pointer) { + PromiseRunner* self = (PromiseRunner*) this_pointer; + try { + self->execute(); + } catch (std::exception &err) { + self->error = err.what(); + } + } + + static void onWorkComplete(napi_env env, napi_status status, void *this_pointer) { + PromiseRunner* self = (PromiseRunner*) this_pointer; + if (status != napi_cancelled) { + HandleScope scope(self->env); + if (status == napi_ok) { + status = napi_delete_async_work(self->env, self->work); + if (status == napi_ok) { + if (self->error.size() == 0) { + self->onOK(); + } else { + self->onError(Error::New(self->env, self->error)); + } + delete self; + return; + } + } + } + + // fallthrough for error handling + const napi_extended_error_info *error_info = 0; + napi_get_last_error_info(env, &error_info); + if (error_info->error_message){ + self->onError(Error::New(env, error_info->error_message)); + } else { + self->onError(Error::New(env)); + } + delete self; + } + + virtual void execute() {} + virtual Value getResult() { + return env.Null(); + } + + void onOK() { + HandleScope scope(env); + Value result = getResult(); + deferred.Resolve(result); + } + + void onError(const Error &e) { + deferred.Reject(e.Value()); + } +}; + +#endif diff --git a/dg-ui/node_modules/@parcel/watcher/src/Signal.hh b/dg-ui/node_modules/@parcel/watcher/src/Signal.hh new file mode 100644 index 0000000..e577319 --- /dev/null +++ b/dg-ui/node_modules/@parcel/watcher/src/Signal.hh @@ -0,0 +1,46 @@ +#ifndef SIGNAL_H +#define SIGNAL_H + +#include +#include + +class Signal { +public: + Signal() : mFlag(false), mWaiting(false) {} + void wait() { + std::unique_lock lock(mMutex); + while (!mFlag) { + mWaiting = true; + mCond.wait(lock); + } + } + + std::cv_status waitFor(std::chrono::milliseconds ms) { + std::unique_lock lock(mMutex); + return mCond.wait_for(lock, ms); + } + + void notify() { + std::unique_lock lock(mMutex); + mFlag = true; + mCond.notify_all(); + } + + void reset() { + std::unique_lock lock(mMutex); + mFlag = false; + mWaiting = false; + } + + bool isWaiting() { + return mWaiting; + } + +private: + bool mFlag; + bool mWaiting; + std::mutex mMutex; + std::condition_variable mCond; +}; + +#endif diff --git a/dg-ui/node_modules/@parcel/watcher/src/Watcher.cc b/dg-ui/node_modules/@parcel/watcher/src/Watcher.cc new file mode 100644 index 0000000..a58ff37 --- /dev/null +++ b/dg-ui/node_modules/@parcel/watcher/src/Watcher.cc @@ -0,0 +1,241 @@ +#include "Watcher.hh" +#include + +using namespace Napi; + +struct WatcherHash { + std::size_t operator() (WatcherRef const &k) const { + return std::hash()(k->mDir); + } +}; + +struct WatcherCompare { + size_t operator() (WatcherRef const &a, WatcherRef const &b) const { + return *a == *b; + } +}; + +static std::unordered_set& getSharedWatchers() { + static std::unordered_set* sharedWatchers = + new std::unordered_set(); + return *sharedWatchers; +} + +WatcherRef Watcher::getShared(std::string dir, std::unordered_set ignorePaths, std::unordered_set ignoreGlobs) { + WatcherRef watcher = std::make_shared(dir, ignorePaths, ignoreGlobs); + auto found = getSharedWatchers().find(watcher); + if (found != getSharedWatchers().end()) { + return *found; + } + + getSharedWatchers().insert(watcher); + return watcher; +} + +void removeShared(Watcher *watcher) { + for (auto it = getSharedWatchers().begin(); it != getSharedWatchers().end(); it++) { + if (it->get() == watcher) { + getSharedWatchers().erase(it); + break; + } + } + + // Free up memory. + if (getSharedWatchers().size() == 0) { + getSharedWatchers().rehash(0); + } +} + +Watcher::Watcher(std::string dir, std::unordered_set ignorePaths, std::unordered_set ignoreGlobs) + : mDir(dir), + mIgnorePaths(ignorePaths), + mIgnoreGlobs(ignoreGlobs) { + mDebounce = Debounce::getShared(); + mDebounce->add(this, [this] () { + triggerCallbacks(); + }); + } + +Watcher::~Watcher() { + mDebounce->remove(this); +} + +void Watcher::wait() { + std::unique_lock lk(mMutex); + mCond.wait(lk); +} + +void Watcher::notify() { + std::unique_lock lk(mMutex); + mCond.notify_all(); + + if (mCallbacks.size() > 0 && mEvents.size() > 0) { + // We must release our lock before calling into the debouncer + // to avoid a deadlock: the debouncer thread itself will require + // our lock from its thread when calling into `triggerCallbacks` + // while holding its own debouncer lock. + lk.unlock(); + mDebounce->trigger(); + } +} + +struct CallbackData { + std::string error; + std::vector events; + CallbackData(std::string error, std::vector events) : error(error), events(events) {} +}; + +Value callbackEventsToJS(const Env &env, std::vector &events) { + EscapableHandleScope scope(env); + Array arr = Array::New(env, events.size()); + uint32_t currentEventIndex = 0; + for (auto eventIterator = events.begin(); eventIterator != events.end(); eventIterator++) { + arr.Set(currentEventIndex++, eventIterator->toJS(env)); + } + return scope.Escape(arr); +} + +void callJSFunction(Napi::Env env, Function jsCallback, CallbackData *data) { + HandleScope scope(env); + auto err = data->error.size() > 0 ? Error::New(env, data->error).Value() : env.Null(); + auto events = callbackEventsToJS(env, data->events); + jsCallback.Call({err, events}); + delete data; + + // Throw errors from the callback as fatal exceptions + // If we don't handle these node segfaults... + if (env.IsExceptionPending()) { + Napi::Error err = env.GetAndClearPendingException(); + napi_fatal_exception(env, err.Value()); + } +} + +void Watcher::notifyError(std::exception &err) { + std::unique_lock lk(mMutex); + for (auto it = mCallbacks.begin(); it != mCallbacks.end(); it++) { + CallbackData *data = new CallbackData(err.what(), {}); + it->tsfn.BlockingCall(data, callJSFunction); + } + + clearCallbacks(); +} + +// This function is called from the debounce thread. +void Watcher::triggerCallbacks() { + std::unique_lock lk(mMutex); + if (mCallbacks.size() > 0 && (mEvents.size() > 0 || mEvents.hasError())) { + auto error = mEvents.getError(); + auto events = mEvents.getEvents(); + mEvents.clear(); + + for (auto it = mCallbacks.begin(); it != mCallbacks.end(); it++) { + it->tsfn.BlockingCall(new CallbackData(error, events), callJSFunction); + } + } +} + +// This should be called from the JavaScript thread. +bool Watcher::watch(Function callback) { + std::unique_lock lk(mMutex); + + auto it = findCallback(callback); + if (it != mCallbacks.end()) { + return false; + } + + auto tsfn = ThreadSafeFunction::New( + callback.Env(), + callback, + "Watcher callback", + 0, // Unlimited queue + 1 // Initial thread count + ); + + mCallbacks.push_back(Callback { + tsfn, + Napi::Persistent(callback), + std::this_thread::get_id() + }); + + return true; +} + +// This should be called from the JavaScript thread. +std::vector::iterator Watcher::findCallback(Function callback) { + for (auto it = mCallbacks.begin(); it != mCallbacks.end(); it++) { + // Only consider callbacks created by the same thread, or V8 will panic. + if (it->threadId == std::this_thread::get_id() && it->ref.Value() == callback) { + return it; + } + } + + return mCallbacks.end(); +} + +// This should be called from the JavaScript thread. +bool Watcher::unwatch(Function callback) { + std::unique_lock lk(mMutex); + + bool removed = false; + auto it = findCallback(callback); + if (it != mCallbacks.end()) { + it->tsfn.Release(); + it->ref.Unref(); + mCallbacks.erase(it); + removed = true; + } + + if (removed && mCallbacks.size() == 0) { + unref(); + return true; + } + + return false; +} + +void Watcher::unref() { + if (mCallbacks.size() == 0) { + removeShared(this); + } +} + +void Watcher::destroy() { + std::unique_lock lk(mMutex); + clearCallbacks(); +} + +// Private because it doesn't lock. +void Watcher::clearCallbacks() { + for (auto it = mCallbacks.begin(); it != mCallbacks.end(); it++) { + it->tsfn.Release(); + it->ref.Unref(); + } + + mCallbacks.clear(); + unref(); +} + +bool Watcher::isIgnored(std::string path) { + for (auto it = mIgnorePaths.begin(); it != mIgnorePaths.end(); it++) { + auto dir = *it + DIR_SEP; + if (*it == path || path.compare(0, dir.size(), dir) == 0) { + return true; + } + } + + auto basePath = mDir + DIR_SEP; + + if (path.rfind(basePath, 0) != 0) { + return false; + } + + auto relativePath = path.substr(basePath.size()); + + for (auto it = mIgnoreGlobs.begin(); it != mIgnoreGlobs.end(); it++) { + if (it->isIgnored(relativePath)) { + return true; + } + } + + return false; +} diff --git a/dg-ui/node_modules/@parcel/watcher/src/Watcher.hh b/dg-ui/node_modules/@parcel/watcher/src/Watcher.hh new file mode 100644 index 0000000..f89e9f5 --- /dev/null +++ b/dg-ui/node_modules/@parcel/watcher/src/Watcher.hh @@ -0,0 +1,73 @@ +#ifndef WATCHER_H +#define WATCHER_H + +#include +#include +#include +#include +#include "Glob.hh" +#include "Event.hh" +#include "Debounce.hh" +#include "DirTree.hh" +#include "Signal.hh" + +using namespace Napi; + +struct Watcher; +using WatcherRef = std::shared_ptr; + +struct Callback { + Napi::ThreadSafeFunction tsfn; + Napi::FunctionReference ref; + std::thread::id threadId; +}; + +class WatcherState { +public: + virtual ~WatcherState() = default; +}; + +struct Watcher { + std::string mDir; + std::unordered_set mIgnorePaths; + std::unordered_set mIgnoreGlobs; + EventList mEvents; + std::shared_ptr state; + + Watcher(std::string dir, std::unordered_set ignorePaths, std::unordered_set ignoreGlobs); + ~Watcher(); + + bool operator==(const Watcher &other) const { + return mDir == other.mDir && mIgnorePaths == other.mIgnorePaths && mIgnoreGlobs == other.mIgnoreGlobs; + } + + void wait(); + void notify(); + void notifyError(std::exception &err); + bool watch(Function callback); + bool unwatch(Function callback); + void unref(); + bool isIgnored(std::string path); + void destroy(); + + static WatcherRef getShared(std::string dir, std::unordered_set ignorePaths, std::unordered_set ignoreGlobs); + +private: + std::mutex mMutex; + std::condition_variable mCond; + std::vector mCallbacks; + std::shared_ptr mDebounce; + + std::vector::iterator findCallback(Function callback); + void clearCallbacks(); + void triggerCallbacks(); +}; + +class WatcherError : public std::runtime_error { +public: + WatcherRef mWatcher; + WatcherError(std::string msg, WatcherRef watcher) : std::runtime_error(msg), mWatcher(watcher) {} + WatcherError(const char *msg, WatcherRef watcher) : std::runtime_error(msg), mWatcher(watcher) {} +}; + +#endif diff --git a/dg-ui/node_modules/@parcel/watcher/src/binding.cc b/dg-ui/node_modules/@parcel/watcher/src/binding.cc new file mode 100644 index 0000000..057b61b --- /dev/null +++ b/dg-ui/node_modules/@parcel/watcher/src/binding.cc @@ -0,0 +1,268 @@ +#include +#include +#include "wasm/include.h" +#include +#include "Glob.hh" +#include "Event.hh" +#include "Backend.hh" +#include "Watcher.hh" +#include "PromiseRunner.hh" + +using namespace Napi; + +std::unordered_set getIgnorePaths(Env env, Value opts) { + std::unordered_set result; + + if (opts.IsObject()) { + Value v = opts.As().Get(String::New(env, "ignorePaths")); + if (v.IsArray()) { + Array items = v.As(); + for (size_t i = 0; i < items.Length(); i++) { + Value item = items.Get(Number::New(env, static_cast(i))); + if (item.IsString()) { + result.insert(std::string(item.As().Utf8Value().c_str())); + } + } + } + } + + return result; +} + +std::unordered_set getIgnoreGlobs(Env env, Value opts) { + std::unordered_set result; + + if (opts.IsObject()) { + Value v = opts.As().Get(String::New(env, "ignoreGlobs")); + if (v.IsArray()) { + Array items = v.As(); + for (size_t i = 0; i < items.Length(); i++) { + Value item = items.Get(Number::New(env, static_cast(i))); + if (item.IsString()) { + auto key = item.As().Utf8Value(); + try { + result.emplace(key); + } catch (const std::regex_error& e) { + Error::New(env, e.what()).ThrowAsJavaScriptException(); + } + } + } + } + } + + return result; +} + +std::shared_ptr getBackend(Env env, Value opts) { + Value b = opts.As().Get(String::New(env, "backend")); + std::string backendName; + if (b.IsString()) { + backendName = std::string(b.As().Utf8Value().c_str()); + } + + return Backend::getShared(backendName); +} + +class WriteSnapshotRunner : public PromiseRunner { +public: + WriteSnapshotRunner(Env env, Value dir, Value snap, Value opts) + : PromiseRunner(env), + snapshotPath(std::string(snap.As().Utf8Value().c_str())) { + watcher = Watcher::getShared( + std::string(dir.As().Utf8Value().c_str()), + getIgnorePaths(env, opts), + getIgnoreGlobs(env, opts) + ); + + backend = getBackend(env, opts); + } + + ~WriteSnapshotRunner() { + watcher->unref(); + backend->unref(); + } +private: + std::shared_ptr backend; + WatcherRef watcher; + std::string snapshotPath; + + void execute() override { + backend->writeSnapshot(watcher, &snapshotPath); + } +}; + +class GetEventsSinceRunner : public PromiseRunner { +public: + GetEventsSinceRunner(Env env, Value dir, Value snap, Value opts) + : PromiseRunner(env), + snapshotPath(std::string(snap.As().Utf8Value().c_str())) { + watcher = std::make_shared( + std::string(dir.As().Utf8Value().c_str()), + getIgnorePaths(env, opts), + getIgnoreGlobs(env, opts) + ); + + backend = getBackend(env, opts); + } + + ~GetEventsSinceRunner() { + watcher->unref(); + backend->unref(); + } +private: + std::shared_ptr backend; + WatcherRef watcher; + std::string snapshotPath; + + void execute() override { + backend->getEventsSince(watcher, &snapshotPath); + if (watcher->mEvents.hasError()) { + throw std::runtime_error(watcher->mEvents.getError()); + } + } + + Value getResult() override { + std::vector events = watcher->mEvents.getEvents(); + Array eventsArray = Array::New(env, events.size()); + uint32_t i = 0; + for (auto it = events.begin(); it != events.end(); it++) { + eventsArray.Set(i++, it->toJS(env)); + } + return eventsArray; + } +}; + +template +Value queueSnapshotWork(const CallbackInfo& info) { + Env env = info.Env(); + if (info.Length() < 1 || !info[0].IsString()) { + TypeError::New(env, "Expected a string").ThrowAsJavaScriptException(); + return env.Null(); + } + + if (info.Length() < 2 || !info[1].IsString()) { + TypeError::New(env, "Expected a string").ThrowAsJavaScriptException(); + return env.Null(); + } + + if (info.Length() >= 3 && !info[2].IsObject()) { + TypeError::New(env, "Expected an object").ThrowAsJavaScriptException(); + return env.Null(); + } + + Runner *runner = new Runner(info.Env(), info[0], info[1], info[2]); + return runner->queue(); +} + +Value writeSnapshot(const CallbackInfo& info) { + return queueSnapshotWork(info); +} + +Value getEventsSince(const CallbackInfo& info) { + return queueSnapshotWork(info); +} + +class SubscribeRunner : public PromiseRunner { +public: + SubscribeRunner(Env env, Value dir, Value fn, Value opts) : PromiseRunner(env) { + watcher = Watcher::getShared( + std::string(dir.As().Utf8Value().c_str()), + getIgnorePaths(env, opts), + getIgnoreGlobs(env, opts) + ); + + backend = getBackend(env, opts); + watcher->watch(fn.As()); + } + +private: + WatcherRef watcher; + std::shared_ptr backend; + FunctionReference callback; + + void execute() override { + try { + backend->watch(watcher); + } catch (std::exception&) { + watcher->destroy(); + throw; + } + } +}; + +class UnsubscribeRunner : public PromiseRunner { +public: + UnsubscribeRunner(Env env, Value dir, Value fn, Value opts) : PromiseRunner(env) { + watcher = Watcher::getShared( + std::string(dir.As().Utf8Value().c_str()), + getIgnorePaths(env, opts), + getIgnoreGlobs(env, opts) + ); + + backend = getBackend(env, opts); + shouldUnwatch = watcher->unwatch(fn.As()); + } + +private: + WatcherRef watcher; + std::shared_ptr backend; + bool shouldUnwatch; + + void execute() override { + if (shouldUnwatch) { + backend->unwatch(watcher); + } + } +}; + +template +Value queueSubscriptionWork(const CallbackInfo& info) { + Env env = info.Env(); + if (info.Length() < 1 || !info[0].IsString()) { + TypeError::New(env, "Expected a string").ThrowAsJavaScriptException(); + return env.Null(); + } + + if (info.Length() < 2 || !info[1].IsFunction()) { + TypeError::New(env, "Expected a function").ThrowAsJavaScriptException(); + return env.Null(); + } + + if (info.Length() >= 3 && !info[2].IsObject()) { + TypeError::New(env, "Expected an object").ThrowAsJavaScriptException(); + return env.Null(); + } + + Runner *runner = new Runner(info.Env(), info[0], info[1], info[2]); + return runner->queue(); +} + +Value subscribe(const CallbackInfo& info) { + return queueSubscriptionWork(info); +} + +Value unsubscribe(const CallbackInfo& info) { + return queueSubscriptionWork(info); +} + +Object Init(Env env, Object exports) { + exports.Set( + String::New(env, "writeSnapshot"), + Function::New(env, writeSnapshot) + ); + exports.Set( + String::New(env, "getEventsSince"), + Function::New(env, getEventsSince) + ); + exports.Set( + String::New(env, "subscribe"), + Function::New(env, subscribe) + ); + exports.Set( + String::New(env, "unsubscribe"), + Function::New(env, unsubscribe) + ); + return exports; +} + +NODE_API_MODULE(watcher, Init) diff --git a/dg-ui/node_modules/@parcel/watcher/src/kqueue/KqueueBackend.cc b/dg-ui/node_modules/@parcel/watcher/src/kqueue/KqueueBackend.cc new file mode 100644 index 0000000..2991c32 --- /dev/null +++ b/dg-ui/node_modules/@parcel/watcher/src/kqueue/KqueueBackend.cc @@ -0,0 +1,306 @@ +#include +#include +#include +#include +#include +#include +#include +#include "KqueueBackend.hh" + +#if __APPLE__ +#define st_mtim st_mtimespec +#endif + +#if !defined(O_EVTONLY) +#define O_EVTONLY O_RDONLY +#endif + +#define CONVERT_TIME(ts) ((uint64_t)ts.tv_sec * 1000000000 + ts.tv_nsec) + +void KqueueBackend::start() { + if ((mKqueue = kqueue()) < 0) { + throw std::runtime_error(std::string("Unable to open kqueue: ") + strerror(errno)); + } + + // Create a pipe that we will write to when we want to end the thread. + int err = pipe(mPipe); + if (err == -1) { + throw std::runtime_error(std::string("Unable to open pipe: ") + strerror(errno)); + } + + // Subscribe kqueue to this pipe. + struct kevent ev; + EV_SET( + &ev, + mPipe[0], + EVFILT_READ, + EV_ADD | EV_CLEAR, + 0, + 0, + 0 + ); + + if (kevent(mKqueue, &ev, 1, NULL, 0, 0)) { + close(mPipe[0]); + close(mPipe[1]); + throw std::runtime_error(std::string("Unable to watch pipe: ") + strerror(errno)); + } + + notifyStarted(); + + struct kevent events[128]; + + while (true) { + int event_count = kevent(mKqueue, NULL, 0, events, 128, 0); + if (event_count < 0 || events[0].flags == EV_ERROR) { + throw std::runtime_error(std::string("kevent error: ") + strerror(errno)); + } + + // Track all of the watchers that are touched so we can notify them at the end of the events. + std::unordered_set watchers; + + for (int i = 0; i < event_count; i++) { + int flags = events[i].fflags; + int fd = events[i].ident; + if (fd == mPipe[0]) { + // pipe was written to. break out of the loop. + goto done; + } + + auto it = mFdToEntry.find(fd); + if (it == mFdToEntry.end()) { + // If fd wasn't in our map, we may have already stopped watching it. Ignore the event. + continue; + } + + DirEntry *entry = it->second; + + if (flags & NOTE_WRITE && entry && entry->isDir) { + // If a write occurred on a directory, we have to diff the contents of that + // directory to determine what file was added/deleted. + compareDir(fd, entry->path, watchers); + } else { + std::vector subs = findSubscriptions(entry->path); + for (auto it = subs.begin(); it != subs.end(); it++) { + KqueueSubscription *sub = *it; + watchers.insert(sub->watcher); + if (flags & (NOTE_DELETE | NOTE_RENAME | NOTE_REVOKE)) { + sub->watcher->mEvents.remove(sub->path); + sub->tree->remove(sub->path); + mFdToEntry.erase((int)(size_t)entry->state); + mSubscriptions.erase(sub->path); + } else if (flags & (NOTE_WRITE | NOTE_ATTRIB | NOTE_EXTEND)) { + struct stat st; + lstat(sub->path.c_str(), &st); + if (entry->mtime != CONVERT_TIME(st.st_mtim)) { + entry->mtime = CONVERT_TIME(st.st_mtim); + sub->watcher->mEvents.update(sub->path); + } + } + } + } + } + + for (auto it = watchers.begin(); it != watchers.end(); it++) { + (*it)->notify(); + } + } + +done: + close(mPipe[0]); + close(mPipe[1]); + mEndedSignal.notify(); +} + +KqueueBackend::~KqueueBackend() { + write(mPipe[1], "X", 1); + mEndedSignal.wait(); +} + +void KqueueBackend::subscribe(WatcherRef watcher) { + // Build a full directory tree recursively, and watch each directory. + std::shared_ptr tree = getTree(watcher); + + for (auto it = tree->entries.begin(); it != tree->entries.end(); it++) { + bool success = watchDir(watcher, it->second.path, tree); + if (!success) { + throw WatcherError(std::string("error watching " + watcher->mDir + ": " + strerror(errno)), watcher); + } + } +} + +bool KqueueBackend::watchDir(WatcherRef watcher, std::string path, std::shared_ptr tree) { + if (watcher->isIgnored(path)) { + return false; + } + + DirEntry *entry = tree->find(path); + if (!entry) { + return false; + } + + KqueueSubscription sub = { + .watcher = watcher, + .path = path, + .tree = tree + }; + + if (!entry->state) { + int fd = open(path.c_str(), O_EVTONLY); + if (fd <= 0) { + return false; + } + + struct kevent event; + EV_SET( + &event, + fd, + EVFILT_VNODE, + EV_ADD | EV_CLEAR | EV_ENABLE, + NOTE_DELETE | NOTE_WRITE | NOTE_EXTEND | NOTE_ATTRIB | NOTE_RENAME | NOTE_REVOKE, + 0, + 0 + ); + + if (kevent(mKqueue, &event, 1, NULL, 0, 0)) { + close(fd); + return false; + } + + entry->state = (void *)(size_t)fd; + mFdToEntry.emplace(fd, entry); + } + + sub.fd = (int)(size_t)entry->state; + mSubscriptions.emplace(path, sub); + return true; +} + +std::vector KqueueBackend::findSubscriptions(std::string &path) { + // Find the subscriptions affected by this path. + // Copy pointers to them into a vector so that modifying mSubscriptions doesn't invalidate the iterator. + auto range = mSubscriptions.equal_range(path); + std::vector subs; + for (auto it = range.first; it != range.second; it++) { + subs.push_back(&it->second); + } + + return subs; +} + +bool KqueueBackend::compareDir(int fd, std::string &path, std::unordered_set &watchers) { + // macOS doesn't support fdclosedir, so we have to duplicate the file descriptor + // to ensure the closedir doesn't also stop watching. + #if __APPLE__ + fd = dup(fd); + #endif + + DIR *dir = fdopendir(fd); + if (dir == NULL) { + return false; + } + + // fdopendir doesn't rewind to the beginning. + rewinddir(dir); + + std::vector subs = findSubscriptions(path); + std::string dirStart = path + DIR_SEP; + + std::unordered_set> trees; + for (auto it = subs.begin(); it != subs.end(); it++) { + trees.emplace((*it)->tree); + } + + std::unordered_set entries; + struct dirent *entry; + while ((entry = readdir(dir))) { + if (strcmp(entry->d_name, ".") == 0 || strcmp(entry->d_name, "..") == 0) { + continue; + } + + std::string fullpath = dirStart + entry->d_name; + entries.emplace(fullpath); + + for (auto it = trees.begin(); it != trees.end(); it++) { + std::shared_ptr tree = *it; + if (!tree->find(fullpath)) { + struct stat st; + fstatat(fd, entry->d_name, &st, AT_SYMLINK_NOFOLLOW); + tree->add(fullpath, CONVERT_TIME(st.st_mtim), S_ISDIR(st.st_mode)); + + // Notify all watchers with the same tree. + for (auto i = subs.begin(); i != subs.end(); i++) { + KqueueSubscription *sub = *i; + if (sub->tree == tree) { + if (sub->watcher->isIgnored(fullpath)) { + continue; + } + + sub->watcher->mEvents.create(fullpath); + watchers.emplace(sub->watcher); + + bool success = watchDir(sub->watcher, fullpath, sub->tree); + if (!success) { + sub->tree->remove(fullpath); + return false; + } + } + } + } + } + } + + for (auto it = trees.begin(); it != trees.end(); it++) { + std::shared_ptr tree = *it; + for (auto entry = tree->entries.begin(); entry != tree->entries.end();) { + + if ( + entry->first.rfind(dirStart, 0) == 0 && + entry->first.find(DIR_SEP, dirStart.length()) == std::string::npos && + entries.count(entry->first) == 0 + ) { + // Notify all watchers with the same tree. + for (auto i = subs.begin(); i != subs.end(); i++) { + if ((*i)->tree == tree) { + KqueueSubscription *sub = *i; + if (!sub->watcher->isIgnored(entry->first)) { + sub->watcher->mEvents.remove(entry->first); + watchers.emplace(sub->watcher); + } + } + } + + mFdToEntry.erase((int)(size_t)entry->second.state); + mSubscriptions.erase(entry->first); + entry = tree->entries.erase(entry); + } else { + entry++; + } + } + } + + #if __APPLE__ + closedir(dir); + #else + fdclosedir(dir); + #endif + + return true; +} + +void KqueueBackend::unsubscribe(WatcherRef watcher) { + // Find any subscriptions pointing to this watcher, and remove them. + for (auto it = mSubscriptions.begin(); it != mSubscriptions.end();) { + if (it->second.watcher.get() == watcher.get()) { + if (mSubscriptions.count(it->first) == 1) { + // Closing the file descriptor automatically unwatches it in the kqueue. + close(it->second.fd); + mFdToEntry.erase(it->second.fd); + } + + it = mSubscriptions.erase(it); + } else { + it++; + } + } +} diff --git a/dg-ui/node_modules/@parcel/watcher/src/kqueue/KqueueBackend.hh b/dg-ui/node_modules/@parcel/watcher/src/kqueue/KqueueBackend.hh new file mode 100644 index 0000000..3c6a9cd --- /dev/null +++ b/dg-ui/node_modules/@parcel/watcher/src/kqueue/KqueueBackend.hh @@ -0,0 +1,35 @@ +#ifndef KQUEUE_H +#define KQUEUE_H + +#include +#include +#include "../shared/BruteForceBackend.hh" +#include "../DirTree.hh" +#include "../Signal.hh" + +struct KqueueSubscription { + WatcherRef watcher; + std::string path; + std::shared_ptr tree; + int fd; +}; + +class KqueueBackend : public BruteForceBackend { +public: + void start() override; + ~KqueueBackend(); + void subscribe(WatcherRef watcher) override; + void unsubscribe(WatcherRef watcher) override; +private: + int mKqueue; + int mPipe[2]; + std::unordered_multimap mSubscriptions; + std::unordered_map mFdToEntry; + Signal mEndedSignal; + + bool watchDir(WatcherRef watcher, std::string path, std::shared_ptr tree); + bool compareDir(int fd, std::string &dir, std::unordered_set &watchers); + std::vector findSubscriptions(std::string &path); +}; + +#endif diff --git a/dg-ui/node_modules/@parcel/watcher/src/linux/InotifyBackend.cc b/dg-ui/node_modules/@parcel/watcher/src/linux/InotifyBackend.cc new file mode 100644 index 0000000..949f498 --- /dev/null +++ b/dg-ui/node_modules/@parcel/watcher/src/linux/InotifyBackend.cc @@ -0,0 +1,236 @@ +#include +#include +#include +#include +#include +#include "InotifyBackend.hh" + +#define INOTIFY_MASK \ + IN_ATTRIB | IN_CREATE | IN_DELETE | \ + IN_DELETE_SELF | IN_MODIFY | IN_MOVE_SELF | IN_MOVED_FROM | \ + IN_MOVED_TO | IN_DONT_FOLLOW | IN_ONLYDIR | IN_EXCL_UNLINK +#define BUFFER_SIZE 8192 +#define CONVERT_TIME(ts) ((uint64_t)ts.tv_sec * 1000000000 + ts.tv_nsec) + +void InotifyBackend::start() { + // Create a pipe that we will write to when we want to end the thread. + int err = pipe2(mPipe, O_CLOEXEC | O_NONBLOCK); + if (err == -1) { + throw std::runtime_error(std::string("Unable to open pipe: ") + strerror(errno)); + } + + // Init inotify file descriptor. + mInotify = inotify_init1(IN_NONBLOCK | IN_CLOEXEC); + if (mInotify == -1) { + throw std::runtime_error(std::string("Unable to initialize inotify: ") + strerror(errno)); + } + + pollfd pollfds[2]; + pollfds[0].fd = mPipe[0]; + pollfds[0].events = POLLIN; + pollfds[0].revents = 0; + pollfds[1].fd = mInotify; + pollfds[1].events = POLLIN; + pollfds[1].revents = 0; + + notifyStarted(); + + // Loop until we get an event from the pipe. + while (true) { + int result = poll(pollfds, 2, 500); + if (result < 0) { + throw std::runtime_error(std::string("Unable to poll: ") + strerror(errno)); + } + + if (pollfds[0].revents) { + break; + } + + if (pollfds[1].revents) { + handleEvents(); + } + } + + close(mPipe[0]); + close(mPipe[1]); + close(mInotify); + + mEndedSignal.notify(); +} + +InotifyBackend::~InotifyBackend() { + write(mPipe[1], "X", 1); + mEndedSignal.wait(); +} + +// This function is called by Backend::watch which takes a lock on mMutex +void InotifyBackend::subscribe(WatcherRef watcher) { + // Build a full directory tree recursively, and watch each directory. + std::shared_ptr tree = getTree(watcher); + + for (auto it = tree->entries.begin(); it != tree->entries.end(); it++) { + if (it->second.isDir) { + bool success = watchDir(watcher, it->second.path, tree); + if (!success) { + throw WatcherError(std::string("inotify_add_watch on '") + it->second.path + std::string("' failed: ") + strerror(errno), watcher); + } + } + } +} + +bool InotifyBackend::watchDir(WatcherRef watcher, std::string path, std::shared_ptr tree) { + int wd = inotify_add_watch(mInotify, path.c_str(), INOTIFY_MASK); + if (wd == -1) { + return false; + } + + std::shared_ptr sub = std::make_shared(); + sub->tree = tree; + sub->path = path; + sub->watcher = watcher; + mSubscriptions.emplace(wd, sub); + + return true; +} + +void InotifyBackend::handleEvents() { + char buf[BUFFER_SIZE] __attribute__ ((aligned(__alignof__(struct inotify_event))));; + struct inotify_event *event; + + // Track all of the watchers that are touched so we can notify them at the end of the events. + std::unordered_set watchers; + + while (true) { + int n = read(mInotify, &buf, BUFFER_SIZE); + if (n < 0) { + if (errno == EAGAIN || errno == EWOULDBLOCK) { + break; + } + + throw std::runtime_error(std::string("Error reading from inotify: ") + strerror(errno)); + } + + if (n == 0) { + break; + } + + for (char *ptr = buf; ptr < buf + n; ptr += sizeof(*event) + event->len) { + event = (struct inotify_event *)ptr; + + if ((event->mask & IN_Q_OVERFLOW) == IN_Q_OVERFLOW) { + // overflow + continue; + } + + handleEvent(event, watchers); + } + } + + for (auto it = watchers.begin(); it != watchers.end(); it++) { + (*it)->notify(); + } +} + +void InotifyBackend::handleEvent(struct inotify_event *event, std::unordered_set &watchers) { + std::unique_lock lock(mMutex); + + // Find the subscriptions for this watch descriptor + auto range = mSubscriptions.equal_range(event->wd); + std::unordered_set> set; + for (auto it = range.first; it != range.second; it++) { + set.insert(it->second); + } + + for (auto it = set.begin(); it != set.end(); it++) { + if (handleSubscription(event, *it)) { + watchers.insert((*it)->watcher); + } + } +} + +bool InotifyBackend::handleSubscription(struct inotify_event *event, std::shared_ptr sub) { + // Build full path and check if its in our ignore list. + std::shared_ptr watcher = sub->watcher; + std::string path = std::string(sub->path); + bool isDir = event->mask & IN_ISDIR; + + if (event->len > 0) { + path += "/" + std::string(event->name); + } + + if (watcher->isIgnored(path)) { + return false; + } + + // If this is a create, check if it's a directory and start watching if it is. + // In any case, keep the directory tree up to date. + if (event->mask & (IN_CREATE | IN_MOVED_TO)) { + watcher->mEvents.create(path); + + struct stat st; + // Use lstat to avoid resolving symbolic links that we cannot watch anyway + // https://github.com/parcel-bundler/watcher/issues/76 + if (lstat(path.c_str(), &st) != 0) { + return false; + } + DirEntry *entry = sub->tree->add(path, CONVERT_TIME(st.st_mtim), S_ISDIR(st.st_mode)); + + if (entry->isDir) { + bool success = watchDir(watcher, path, sub->tree); + if (!success) { + sub->tree->remove(path); + return false; + } + } + } else if (event->mask & (IN_MODIFY | IN_ATTRIB)) { + watcher->mEvents.update(path); + + struct stat st; + if (stat(path.c_str(), &st) != 0) { + return false; + } + sub->tree->update(path, CONVERT_TIME(st.st_mtim)); + } else if (event->mask & (IN_DELETE | IN_DELETE_SELF | IN_MOVED_FROM | IN_MOVE_SELF)) { + bool isSelfEvent = (event->mask & (IN_DELETE_SELF | IN_MOVE_SELF)); + // Ignore delete/move self events unless this is the recursive watch root + if (isSelfEvent && path != watcher->mDir) { + return false; + } + + // If the entry being deleted/moved is a directory, remove it from the list of subscriptions + // XXX: self events don't have the IN_ISDIR mask + if (isSelfEvent || isDir) { + for (auto it = mSubscriptions.begin(); it != mSubscriptions.end();) { + if (it->second->path == path) { + it = mSubscriptions.erase(it); + } else { + ++it; + } + } + } + + watcher->mEvents.remove(path); + sub->tree->remove(path); + } + + return true; +} + +// This function is called by Backend::unwatch which takes a lock on mMutex +void InotifyBackend::unsubscribe(WatcherRef watcher) { + // Find any subscriptions pointing to this watcher, and remove them. + for (auto it = mSubscriptions.begin(); it != mSubscriptions.end();) { + if (it->second->watcher.get() == watcher.get()) { + if (mSubscriptions.count(it->first) == 1) { + int err = inotify_rm_watch(mInotify, it->first); + if (err == -1) { + throw WatcherError(std::string("Unable to remove watcher: ") + strerror(errno), watcher); + } + } + + it = mSubscriptions.erase(it); + } else { + it++; + } + } +} diff --git a/dg-ui/node_modules/@parcel/watcher/src/linux/InotifyBackend.hh b/dg-ui/node_modules/@parcel/watcher/src/linux/InotifyBackend.hh new file mode 100644 index 0000000..f34cd1f --- /dev/null +++ b/dg-ui/node_modules/@parcel/watcher/src/linux/InotifyBackend.hh @@ -0,0 +1,34 @@ +#ifndef INOTIFY_H +#define INOTIFY_H + +#include +#include +#include "../shared/BruteForceBackend.hh" +#include "../DirTree.hh" +#include "../Signal.hh" + +struct InotifySubscription { + std::shared_ptr tree; + std::string path; + WatcherRef watcher; +}; + +class InotifyBackend : public BruteForceBackend { +public: + void start() override; + ~InotifyBackend(); + void subscribe(WatcherRef watcher) override; + void unsubscribe(WatcherRef watcher) override; +private: + int mPipe[2]; + int mInotify; + std::unordered_multimap> mSubscriptions; + Signal mEndedSignal; + + bool watchDir(WatcherRef watcher, std::string path, std::shared_ptr tree); + void handleEvents(); + void handleEvent(struct inotify_event *event, std::unordered_set &watchers); + bool handleSubscription(struct inotify_event *event, std::shared_ptr sub); +}; + +#endif diff --git a/dg-ui/node_modules/@parcel/watcher/src/macos/FSEventsBackend.cc b/dg-ui/node_modules/@parcel/watcher/src/macos/FSEventsBackend.cc new file mode 100644 index 0000000..cfda962 --- /dev/null +++ b/dg-ui/node_modules/@parcel/watcher/src/macos/FSEventsBackend.cc @@ -0,0 +1,338 @@ +#include +#include +#include +#include +#include +#include "../Event.hh" +#include "../Backend.hh" +#include "./FSEventsBackend.hh" +#include "../Watcher.hh" + +#define CONVERT_TIME(ts) ((uint64_t)ts.tv_sec * 1000000000 + ts.tv_nsec) +#define IGNORED_FLAGS (kFSEventStreamEventFlagItemIsHardlink | kFSEventStreamEventFlagItemIsLastHardlink | kFSEventStreamEventFlagItemIsSymlink | kFSEventStreamEventFlagItemIsDir | kFSEventStreamEventFlagItemIsFile) + +void stopStream(FSEventStreamRef stream, CFRunLoopRef runLoop) { + FSEventStreamStop(stream); + FSEventStreamUnscheduleFromRunLoop(stream, runLoop, kCFRunLoopDefaultMode); + FSEventStreamInvalidate(stream); + FSEventStreamRelease(stream); +} + +// macOS has a case insensitive file system by default. In order to detect +// file renames that only affect case, we need to get the canonical path +// and compare it with the input path to determine if a file was created or deleted. +bool pathExists(char *path) { + int fd = open(path, O_RDONLY | O_SYMLINK); + if (fd == -1) { + return false; + } + + char buf[PATH_MAX]; + if (fcntl(fd, F_GETPATH, buf) == -1) { + close(fd); + return false; + } + + bool res = strncmp(path, buf, PATH_MAX) == 0; + close(fd); + return res; +} + +class State: public WatcherState { +public: + FSEventStreamRef stream; + std::shared_ptr tree; + uint64_t since; +}; + +void FSEventsCallback( + ConstFSEventStreamRef streamRef, + void *clientCallBackInfo, + size_t numEvents, + void *eventPaths, + const FSEventStreamEventFlags eventFlags[], + const FSEventStreamEventId eventIds[] +) { + char **paths = (char **)eventPaths; + std::shared_ptr& watcher = *static_cast *>(clientCallBackInfo); + + EventList& list = watcher->mEvents; + if (watcher->state == nullptr) { + return; + } + + auto stateGuard = watcher->state; + auto* state = static_cast(stateGuard.get()); + uint64_t since = state->since; + bool deletedRoot = false; + + for (size_t i = 0; i < numEvents; ++i) { + bool isCreated = (eventFlags[i] & kFSEventStreamEventFlagItemCreated) == kFSEventStreamEventFlagItemCreated; + bool isRemoved = (eventFlags[i] & kFSEventStreamEventFlagItemRemoved) == kFSEventStreamEventFlagItemRemoved; + bool isModified = (eventFlags[i] & kFSEventStreamEventFlagItemModified) == kFSEventStreamEventFlagItemModified || + (eventFlags[i] & kFSEventStreamEventFlagItemInodeMetaMod) == kFSEventStreamEventFlagItemInodeMetaMod || + (eventFlags[i] & kFSEventStreamEventFlagItemFinderInfoMod) == kFSEventStreamEventFlagItemFinderInfoMod || + (eventFlags[i] & kFSEventStreamEventFlagItemChangeOwner) == kFSEventStreamEventFlagItemChangeOwner || + (eventFlags[i] & kFSEventStreamEventFlagItemXattrMod) == kFSEventStreamEventFlagItemXattrMod; + bool isRenamed = (eventFlags[i] & kFSEventStreamEventFlagItemRenamed) == kFSEventStreamEventFlagItemRenamed; + bool isDone = (eventFlags[i] & kFSEventStreamEventFlagHistoryDone) == kFSEventStreamEventFlagHistoryDone; + bool isDir = (eventFlags[i] & kFSEventStreamEventFlagItemIsDir) == kFSEventStreamEventFlagItemIsDir; + + + if (eventFlags[i] & kFSEventStreamEventFlagMustScanSubDirs) { + if (eventFlags[i] & kFSEventStreamEventFlagUserDropped) { + list.error("Events were dropped by the FSEvents client. File system must be re-scanned."); + } else if (eventFlags[i] & kFSEventStreamEventFlagKernelDropped) { + list.error("Events were dropped by the kernel. File system must be re-scanned."); + } else { + list.error("Too many events. File system must be re-scanned."); + } + } + + if (isDone) { + watcher->notify(); + break; + } + + auto ignoredFlags = IGNORED_FLAGS; + if (__builtin_available(macOS 10.13, *)) { + ignoredFlags |= kFSEventStreamEventFlagItemCloned; + } + + // If we don't care about any of the flags that are set, ignore this event. + if ((eventFlags[i] & ~ignoredFlags) == 0) { + continue; + } + + // FSEvents exclusion paths only apply to files, not directories. + if (watcher->isIgnored(paths[i])) { + continue; + } + + // Handle unambiguous events first + if (isCreated && !(isRemoved || isModified || isRenamed)) { + state->tree->add(paths[i], 0, isDir); + list.create(paths[i]); + } else if (isRemoved && !(isCreated || isModified || isRenamed)) { + state->tree->remove(paths[i]); + list.remove(paths[i]); + if (paths[i] == watcher->mDir) { + deletedRoot = true; + } + } else if (isModified && !(isCreated || isRemoved || isRenamed)) { + struct stat file; + if (stat(paths[i], &file)) { + continue; + } + + // Ignore if mtime is the same as the last event. + // This prevents duplicate events from being emitted. + // If tv_nsec is zero, the file system probably only has second-level + // granularity so allow the even through in that case. + uint64_t mtime = CONVERT_TIME(file.st_mtimespec); + DirEntry *entry = state->tree->find(paths[i]); + if (entry && mtime == entry->mtime && file.st_mtimespec.tv_nsec != 0) { + continue; + } + + if (entry) { + // Update mtime. + entry->mtime = mtime; + } else { + // Add to tree if this path has not been discovered yet. + state->tree->add(paths[i], mtime, S_ISDIR(file.st_mode)); + } + + list.update(paths[i]); + } else { + // If multiple flags were set, then we need to call `stat` to determine if the file really exists. + // This helps disambiguate creates, updates, and deletes. + struct stat file; + if (stat(paths[i], &file) || !pathExists(paths[i])) { + // File does not exist, so we have to assume it was removed. This is not exact since the + // flags set by fsevents get coalesced together (e.g. created & deleted), so there is no way to + // know whether the create and delete both happened since our snapshot (in which case + // we'd rather ignore this event completely). This will result in some extra delete events + // being emitted for files we don't know about, but that is the best we can do. + state->tree->remove(paths[i]); + list.remove(paths[i]); + if (paths[i] == watcher->mDir) { + deletedRoot = true; + } + continue; + } + + // If the file was modified, and existed before, then this is an update, otherwise a create. + uint64_t ctime = CONVERT_TIME(file.st_birthtimespec); + uint64_t mtime = CONVERT_TIME(file.st_mtimespec); + DirEntry *entry = !since ? state->tree->find(paths[i]) : NULL; + if (entry && entry->mtime == mtime && file.st_mtimespec.tv_nsec != 0) { + continue; + } + + // Some mounted file systems report a creation time of 0/unix epoch which we special case. + if (isModified && (entry || (ctime <= since && ctime != 0))) { + state->tree->update(paths[i], mtime); + list.update(paths[i]); + } else { + state->tree->add(paths[i], mtime, S_ISDIR(file.st_mode)); + list.create(paths[i]); + } + } + } + + if (!since) { + watcher->notify(); + } + + // Stop watching if the root directory was deleted. + if (deletedRoot) { + stopStream((FSEventStreamRef)streamRef, CFRunLoopGetCurrent()); + watcher->state = nullptr; + } +} + +void checkWatcher(WatcherRef watcher) { + struct stat file; + if (stat(watcher->mDir.c_str(), &file)) { + throw WatcherError(strerror(errno), watcher); + } + + if (!S_ISDIR(file.st_mode)) { + throw WatcherError(strerror(ENOTDIR), watcher); + } +} + +void FSEventsBackend::startStream(WatcherRef watcher, FSEventStreamEventId id) { + checkWatcher(watcher); + + CFAbsoluteTime latency = 0.001; + CFStringRef fileWatchPath = CFStringCreateWithCString( + NULL, + watcher->mDir.c_str(), + kCFStringEncodingUTF8 + ); + + CFArrayRef pathsToWatch = CFArrayCreate( + NULL, + (const void **)&fileWatchPath, + 1, + NULL + ); + + // Make a watcher reference we can pass into the callback. This ensures bumped ref-count. + std::shared_ptr* callbackWatcher = new std::shared_ptr (watcher); + FSEventStreamContext callbackInfo {0, static_cast (callbackWatcher), nullptr, nullptr, nullptr}; + FSEventStreamRef stream = FSEventStreamCreate( + NULL, + &FSEventsCallback, + &callbackInfo, + pathsToWatch, + id, + latency, + kFSEventStreamCreateFlagFileEvents + ); + + CFMutableArrayRef exclusions = CFArrayCreateMutable(NULL, watcher->mIgnorePaths.size(), NULL); + for (auto it = watcher->mIgnorePaths.begin(); it != watcher->mIgnorePaths.end(); it++) { + CFStringRef path = CFStringCreateWithCString( + NULL, + it->c_str(), + kCFStringEncodingUTF8 + ); + + CFArrayAppendValue(exclusions, (const void *)path); + } + + FSEventStreamSetExclusionPaths(stream, exclusions); + + FSEventStreamScheduleWithRunLoop(stream, mRunLoop, kCFRunLoopDefaultMode); + bool started = FSEventStreamStart(stream); + + CFRelease(pathsToWatch); + CFRelease(fileWatchPath); + + if (!started) { + FSEventStreamRelease(stream); + throw WatcherError("Error starting FSEvents stream", watcher); + } + + auto stateGuard = watcher->state; + State* s = static_cast(stateGuard.get()); + s->tree = std::make_shared(watcher->mDir); + s->stream = stream; +} + +void FSEventsBackend::start() { + mRunLoop = CFRunLoopGetCurrent(); + CFRetain(mRunLoop); + + // Unlock once run loop has started. + CFRunLoopPerformBlock(mRunLoop, kCFRunLoopDefaultMode, ^ { + notifyStarted(); + }); + + CFRunLoopWakeUp(mRunLoop); + CFRunLoopRun(); +} + +FSEventsBackend::~FSEventsBackend() { + std::unique_lock lock(mMutex); + CFRunLoopStop(mRunLoop); + CFRelease(mRunLoop); +} + +void FSEventsBackend::writeSnapshot(WatcherRef watcher, std::string *snapshotPath) { + std::unique_lock lock(mMutex); + checkWatcher(watcher); + + FSEventStreamEventId id = FSEventsGetCurrentEventId(); + std::ofstream ofs(*snapshotPath); + ofs << id; + ofs << "\n"; + + struct timespec now; + clock_gettime(CLOCK_REALTIME, &now); + ofs << CONVERT_TIME(now); +} + +void FSEventsBackend::getEventsSince(WatcherRef watcher, std::string *snapshotPath) { + std::unique_lock lock(mMutex); + std::ifstream ifs(*snapshotPath); + if (ifs.fail()) { + return; + } + + FSEventStreamEventId id; + uint64_t since; + ifs >> id; + ifs >> since; + + auto s = std::make_shared(); + s->since = since; + watcher->state = s; + + startStream(watcher, id); + watcher->wait(); + stopStream(s->stream, mRunLoop); + + watcher->state = nullptr; +} + +// This function is called by Backend::watch which takes a lock on mMutex +void FSEventsBackend::subscribe(WatcherRef watcher) { + auto s = std::make_shared(); + s->since = 0; + watcher->state = s; + startStream(watcher, kFSEventStreamEventIdSinceNow); +} + +// This function is called by Backend::unwatch which takes a lock on mMutex +void FSEventsBackend::unsubscribe(WatcherRef watcher) { + auto stateGuard = watcher->state; + State* s = static_cast(stateGuard.get()); + if (s != nullptr) { + stopStream(s->stream, mRunLoop); + watcher->state = nullptr; + } +} diff --git a/dg-ui/node_modules/@parcel/watcher/src/macos/FSEventsBackend.hh b/dg-ui/node_modules/@parcel/watcher/src/macos/FSEventsBackend.hh new file mode 100644 index 0000000..57ded66 --- /dev/null +++ b/dg-ui/node_modules/@parcel/watcher/src/macos/FSEventsBackend.hh @@ -0,0 +1,20 @@ +#ifndef FS_EVENTS_H +#define FS_EVENTS_H + +#include +#include "../Backend.hh" + +class FSEventsBackend : public Backend { +public: + void start() override; + ~FSEventsBackend(); + void writeSnapshot(WatcherRef watcher, std::string *snapshotPath) override; + void getEventsSince(WatcherRef watcher, std::string *snapshotPath) override; + void subscribe(WatcherRef watcher) override; + void unsubscribe(WatcherRef watcher) override; +private: + void startStream(WatcherRef watcher, FSEventStreamEventId id); + CFRunLoopRef mRunLoop; +}; + +#endif diff --git a/dg-ui/node_modules/@parcel/watcher/src/shared/BruteForceBackend.cc b/dg-ui/node_modules/@parcel/watcher/src/shared/BruteForceBackend.cc new file mode 100644 index 0000000..0e9b84f --- /dev/null +++ b/dg-ui/node_modules/@parcel/watcher/src/shared/BruteForceBackend.cc @@ -0,0 +1,41 @@ +#include +#include "../DirTree.hh" +#include "../Event.hh" +#include "./BruteForceBackend.hh" + +std::shared_ptr BruteForceBackend::getTree(WatcherRef watcher, bool shouldRead) { + auto tree = DirTree::getCached(watcher->mDir); + + // If the tree is not complete, read it if needed. + if (!tree->isComplete && shouldRead) { + readTree(watcher, tree); + tree->isComplete = true; + } + + return tree; +} + +void BruteForceBackend::writeSnapshot(WatcherRef watcher, std::string *snapshotPath) { + std::unique_lock lock(mMutex); + auto tree = getTree(watcher); + FILE *f = fopen(snapshotPath->c_str(), "w"); + if (!f) { + throw std::runtime_error(std::string("Unable to open snapshot file: ") + strerror(errno)); + } + + tree->write(f); + fclose(f); +} + +void BruteForceBackend::getEventsSince(WatcherRef watcher, std::string *snapshotPath) { + std::unique_lock lock(mMutex); + FILE *f = fopen(snapshotPath->c_str(), "r"); + if (!f) { + throw std::runtime_error(std::string("Unable to open snapshot file: ") + strerror(errno)); + } + + DirTree snapshot{watcher->mDir, f}; + auto now = getTree(watcher); + now->getChanges(&snapshot, watcher->mEvents); + fclose(f); +} diff --git a/dg-ui/node_modules/@parcel/watcher/src/shared/BruteForceBackend.hh b/dg-ui/node_modules/@parcel/watcher/src/shared/BruteForceBackend.hh new file mode 100644 index 0000000..de7a73d --- /dev/null +++ b/dg-ui/node_modules/@parcel/watcher/src/shared/BruteForceBackend.hh @@ -0,0 +1,25 @@ +#ifndef BRUTE_FORCE_H +#define BRUTE_FORCE_H + +#include "../Backend.hh" +#include "../DirTree.hh" +#include "../Watcher.hh" + +class BruteForceBackend : public Backend { +public: + void writeSnapshot(WatcherRef watcher, std::string *snapshotPath) override; + void getEventsSince(WatcherRef watcher, std::string *snapshotPath) override; + void subscribe(WatcherRef watcher) override { + throw "Brute force backend doesn't support subscriptions."; + } + + void unsubscribe(WatcherRef watcher) override { + throw "Brute force backend doesn't support subscriptions."; + } + + std::shared_ptr getTree(WatcherRef watcher, bool shouldRead = true); +private: + void readTree(WatcherRef watcher, std::shared_ptr tree); +}; + +#endif diff --git a/dg-ui/node_modules/@parcel/watcher/src/unix/fts.cc b/dg-ui/node_modules/@parcel/watcher/src/unix/fts.cc new file mode 100644 index 0000000..d50c3e4 --- /dev/null +++ b/dg-ui/node_modules/@parcel/watcher/src/unix/fts.cc @@ -0,0 +1,50 @@ +#include + +// weird error on linux +#ifdef __THROW +#undef __THROW +#endif +#define __THROW + +#include +#include +#include "../DirTree.hh" +#include "../shared/BruteForceBackend.hh" + +#define CONVERT_TIME(ts) ((uint64_t)ts.tv_sec * 1000000000 + ts.tv_nsec) +#if __APPLE__ +#define st_mtim st_mtimespec +#endif + +void BruteForceBackend::readTree(WatcherRef watcher, std::shared_ptr tree) { + char *paths[2] {(char *)watcher->mDir.c_str(), NULL}; + FTS *fts = fts_open(paths, FTS_NOCHDIR | FTS_PHYSICAL, NULL); + if (!fts) { + throw WatcherError(strerror(errno), watcher); + } + + FTSENT *node; + bool isRoot = true; + + while ((node = fts_read(fts)) != NULL) { + if (node->fts_errno) { + fts_close(fts); + throw WatcherError(strerror(node->fts_errno), watcher); + } + + if (isRoot && !(node->fts_info & FTS_D)) { + fts_close(fts); + throw WatcherError(strerror(ENOTDIR), watcher); + } + + if (watcher->isIgnored(std::string(node->fts_path))) { + fts_set(fts, node, FTS_SKIP); + continue; + } + + tree->add(node->fts_path, CONVERT_TIME(node->fts_statp->st_mtim), (node->fts_info & FTS_D) == FTS_D); + isRoot = false; + } + + fts_close(fts); +} diff --git a/dg-ui/node_modules/@parcel/watcher/src/unix/legacy.cc b/dg-ui/node_modules/@parcel/watcher/src/unix/legacy.cc new file mode 100644 index 0000000..60490c6 --- /dev/null +++ b/dg-ui/node_modules/@parcel/watcher/src/unix/legacy.cc @@ -0,0 +1,77 @@ +#include + +// weird error on linux +#ifdef __THROW +#undef __THROW +#endif +#define __THROW + +#ifdef _LIBC +# include +#else +# include +#endif +#include +#include +#include + +#include "../DirTree.hh" +#include "../shared/BruteForceBackend.hh" + +#define CONVERT_TIME(ts) ((uint64_t)ts.tv_sec * 1000000000 + ts.tv_nsec) +#if __APPLE__ +#define st_mtim st_mtimespec +#endif +#define ISDOT(a) (a[0] == '.' && (!a[1] || (a[1] == '.' && !a[2]))) + +void iterateDir(WatcherRef watcher, const std::shared_ptr tree, const char *relative, int parent_fd, const std::string &dirname) { + int open_flags = (O_RDONLY | O_CLOEXEC | O_DIRECTORY | O_NOCTTY | O_NONBLOCK | O_NOFOLLOW); + int new_fd = openat(parent_fd, relative, open_flags); + if (new_fd == -1) { + if (errno == EACCES) { + return; // ignore insufficient permissions + } + + throw WatcherError(strerror(errno), watcher); + } + + struct stat rootAttributes; + fstatat(new_fd, ".", &rootAttributes, AT_SYMLINK_NOFOLLOW); + tree->add(dirname, CONVERT_TIME(rootAttributes.st_mtim), true); + + if (DIR *dir = fdopendir(new_fd)) { + while (struct dirent *ent = (errno = 0, readdir(dir))) { + if (ISDOT(ent->d_name)) continue; + + std::string fullPath = dirname + "/" + ent->d_name; + + if (!watcher->isIgnored(fullPath)) { + struct stat attrib; + fstatat(new_fd, ent->d_name, &attrib, AT_SYMLINK_NOFOLLOW); + bool isDir = ent->d_type == DT_DIR; + + if (isDir) { + iterateDir(watcher, tree, ent->d_name, new_fd, fullPath); + } else { + tree->add(fullPath, CONVERT_TIME(attrib.st_mtim), isDir); + } + } + } + + closedir(dir); + } else { + close(new_fd); + } + + if (errno) { + throw WatcherError(strerror(errno), watcher); + } +} + +void BruteForceBackend::readTree(WatcherRef watcher, std::shared_ptr tree) { + int fd = open(watcher->mDir.c_str(), O_RDONLY); + if (fd) { + iterateDir(watcher, tree, ".", fd, watcher->mDir); + close(fd); + } +} diff --git a/dg-ui/node_modules/@parcel/watcher/src/wasm/WasmBackend.cc b/dg-ui/node_modules/@parcel/watcher/src/wasm/WasmBackend.cc new file mode 100644 index 0000000..9514109 --- /dev/null +++ b/dg-ui/node_modules/@parcel/watcher/src/wasm/WasmBackend.cc @@ -0,0 +1,132 @@ +#include +#include "WasmBackend.hh" + +#define CONVERT_TIME(ts) ((uint64_t)ts.tv_sec * 1000000000 + ts.tv_nsec) + +void WasmBackend::start() { + notifyStarted(); +} + +void WasmBackend::subscribe(WatcherRef watcher) { + // Build a full directory tree recursively, and watch each directory. + std::shared_ptr tree = getTree(watcher); + + for (auto it = tree->entries.begin(); it != tree->entries.end(); it++) { + if (it->second.isDir) { + watchDir(watcher, it->second.path, tree); + } + } +} + +void WasmBackend::watchDir(WatcherRef watcher, std::string path, std::shared_ptr tree) { + int wd = wasm_backend_add_watch(path.c_str(), (void *)this); + std::shared_ptr sub = std::make_shared(); + sub->tree = tree; + sub->path = path; + sub->watcher = watcher; + mSubscriptions.emplace(wd, sub); +} + +extern "C" void wasm_backend_event_handler(void *backend, int wd, int type, char *filename) { + WasmBackend *b = (WasmBackend *)(backend); + b->handleEvent(wd, type, filename); +} + +void WasmBackend::handleEvent(int wd, int type, char *filename) { + // Find the subscriptions for this watch descriptor + auto range = mSubscriptions.equal_range(wd); + std::unordered_set> set; + for (auto it = range.first; it != range.second; it++) { + set.insert(it->second); + } + + for (auto it = set.begin(); it != set.end(); it++) { + if (handleSubscription(type, filename, *it)) { + (*it)->watcher->notify(); + } + } +} + +bool WasmBackend::handleSubscription(int type, char *filename, std::shared_ptr sub) { + // Build full path and check if its in our ignore list. + WatcherRef watcher = sub->watcher; + std::string path = std::string(sub->path); + + if (filename[0] != '\0') { + path += "/" + std::string(filename); + } + + if (watcher->isIgnored(path)) { + return false; + } + + if (type == 1) { + struct stat st; + stat(path.c_str(), &st); + sub->tree->update(path, CONVERT_TIME(st.st_mtim)); + watcher->mEvents.update(path); + } else if (type == 2) { + // Determine if this is a create or delete depending on if the file exists or not. + struct stat st; + if (lstat(path.c_str(), &st)) { + // If the entry being deleted/moved is a directory, remove it from the list of subscriptions + DirEntry *entry = sub->tree->find(path); + if (!entry) { + return false; + } + + if (entry->isDir) { + std::string pathStart = path + DIR_SEP; + for (auto it = mSubscriptions.begin(); it != mSubscriptions.end();) { + if (it->second->path == path || it->second->path.rfind(pathStart, 0) == 0) { + wasm_backend_remove_watch(it->first); + it = mSubscriptions.erase(it); + } else { + ++it; + } + } + + // Remove all sub-entries + for (auto it = sub->tree->entries.begin(); it != sub->tree->entries.end();) { + if (it->first.rfind(pathStart, 0) == 0) { + watcher->mEvents.remove(it->first); + it = sub->tree->entries.erase(it); + } else { + it++; + } + } + } + + watcher->mEvents.remove(path); + sub->tree->remove(path); + } else if (sub->tree->find(path)) { + sub->tree->update(path, CONVERT_TIME(st.st_mtim)); + watcher->mEvents.update(path); + } else { + watcher->mEvents.create(path); + + // If this is a create, check if it's a directory and start watching if it is. + DirEntry *entry = sub->tree->add(path, CONVERT_TIME(st.st_mtim), S_ISDIR(st.st_mode)); + if (entry->isDir) { + watchDir(watcher, path, sub->tree); + } + } + } + + return true; +} + +void WasmBackend::unsubscribe(WatcherRef watcher) { + // Find any subscriptions pointing to this watcher, and remove them. + for (auto it = mSubscriptions.begin(); it != mSubscriptions.end();) { + if (it->second->watcher.get() == watcher.get()) { + if (mSubscriptions.count(it->first) == 1) { + wasm_backend_remove_watch(it->first); + } + + it = mSubscriptions.erase(it); + } else { + it++; + } + } +} diff --git a/dg-ui/node_modules/@parcel/watcher/src/wasm/WasmBackend.hh b/dg-ui/node_modules/@parcel/watcher/src/wasm/WasmBackend.hh new file mode 100644 index 0000000..9facac8 --- /dev/null +++ b/dg-ui/node_modules/@parcel/watcher/src/wasm/WasmBackend.hh @@ -0,0 +1,34 @@ +#ifndef WASM_H +#define WASM_H + +#include +#include "../shared/BruteForceBackend.hh" +#include "../DirTree.hh" + +extern "C" { + int wasm_backend_add_watch(const char *filename, void *backend); + void wasm_backend_remove_watch(int wd); + void wasm_backend_event_handler(void *backend, int wd, int type, char *filename); +}; + +struct WasmSubscription { + std::shared_ptr tree; + std::string path; + WatcherRef watcher; +}; + +class WasmBackend : public BruteForceBackend { +public: + void start() override; + void subscribe(WatcherRef watcher) override; + void unsubscribe(WatcherRef watcher) override; + void handleEvent(int wd, int type, char *filename); +private: + int mWasm; + std::unordered_multimap> mSubscriptions; + + void watchDir(WatcherRef watcher, std::string path, std::shared_ptr tree); + bool handleSubscription(int type, char *filename, std::shared_ptr sub); +}; + +#endif diff --git a/dg-ui/node_modules/@parcel/watcher/src/wasm/include.h b/dg-ui/node_modules/@parcel/watcher/src/wasm/include.h new file mode 100644 index 0000000..60e4d65 --- /dev/null +++ b/dg-ui/node_modules/@parcel/watcher/src/wasm/include.h @@ -0,0 +1,74 @@ +/* +Copyright Node.js contributors. All rights reserved. + +Permission is hereby granted, free of charge, to any person obtaining a copy +of this software and associated documentation files (the "Software"), to +deal in the Software without restriction, including without limitation the +rights to use, copy, modify, merge, publish, distribute, sublicense, and/or +sell copies of the Software, and to permit persons to whom the Software is +furnished to do so, subject to the following conditions: + +The above copyright notice and this permission notice shall be included in +all copies or substantial portions of the Software. + +THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR +IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, +FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE +AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER +LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING +FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS +IN THE SOFTWARE. +*/ + +// Node does not include the headers for these functions when compiling for WASM, so add them here. +#ifdef __wasm32__ +extern "C" { +NAPI_EXTERN napi_status NAPI_CDECL +napi_create_threadsafe_function(napi_env env, + napi_value func, + napi_value async_resource, + napi_value async_resource_name, + size_t max_queue_size, + size_t initial_thread_count, + void* thread_finalize_data, + napi_finalize thread_finalize_cb, + void* context, + napi_threadsafe_function_call_js call_js_cb, + napi_threadsafe_function* result); + +NAPI_EXTERN napi_status NAPI_CDECL napi_get_threadsafe_function_context( + napi_threadsafe_function func, void** result); + +NAPI_EXTERN napi_status NAPI_CDECL +napi_call_threadsafe_function(napi_threadsafe_function func, + void* data, + napi_threadsafe_function_call_mode is_blocking); + +NAPI_EXTERN napi_status NAPI_CDECL +napi_acquire_threadsafe_function(napi_threadsafe_function func); + +NAPI_EXTERN napi_status NAPI_CDECL napi_release_threadsafe_function( + napi_threadsafe_function func, napi_threadsafe_function_release_mode mode); + +NAPI_EXTERN napi_status NAPI_CDECL +napi_unref_threadsafe_function(napi_env env, napi_threadsafe_function func); + +NAPI_EXTERN napi_status NAPI_CDECL +napi_ref_threadsafe_function(napi_env env, napi_threadsafe_function func); + +NAPI_EXTERN napi_status NAPI_CDECL +napi_create_async_work(napi_env env, + napi_value async_resource, + napi_value async_resource_name, + napi_async_execute_callback execute, + napi_async_complete_callback complete, + void* data, + napi_async_work* result); +NAPI_EXTERN napi_status NAPI_CDECL napi_delete_async_work(napi_env env, + napi_async_work work); +NAPI_EXTERN napi_status NAPI_CDECL napi_queue_async_work(napi_env env, + napi_async_work work); +NAPI_EXTERN napi_status NAPI_CDECL napi_cancel_async_work(napi_env env, + napi_async_work work); +} +#endif diff --git a/dg-ui/node_modules/@parcel/watcher/src/watchman/BSER.cc b/dg-ui/node_modules/@parcel/watcher/src/watchman/BSER.cc new file mode 100644 index 0000000..82390dd --- /dev/null +++ b/dg-ui/node_modules/@parcel/watcher/src/watchman/BSER.cc @@ -0,0 +1,302 @@ +#include +#include "./BSER.hh" + +BSERType decodeType(std::istream &iss) { + int8_t type; + iss.read(reinterpret_cast(&type), sizeof(type)); + return (BSERType) type; +} + +void expectType(std::istream &iss, BSERType expected) { + BSERType got = decodeType(iss); + if (got != expected) { + throw std::runtime_error("Unexpected BSER type"); + } +} + +void encodeType(std::ostream &oss, BSERType type) { + int8_t t = (int8_t)type; + oss.write(reinterpret_cast(&t), sizeof(t)); +} + +template +class Value : public BSERValue { +public: + T value; + Value(T val) { + value = val; + } + + Value() {} +}; + +class BSERInteger : public Value { +public: + BSERInteger(int64_t value) : Value(value) {} + BSERInteger(std::istream &iss) { + int8_t int8; + int16_t int16; + int32_t int32; + int64_t int64; + + BSERType type = decodeType(iss); + + switch (type) { + case BSER_INT8: + iss.read(reinterpret_cast(&int8), sizeof(int8)); + value = int8; + break; + case BSER_INT16: + iss.read(reinterpret_cast(&int16), sizeof(int16)); + value = int16; + break; + case BSER_INT32: + iss.read(reinterpret_cast(&int32), sizeof(int32)); + value = int32; + break; + case BSER_INT64: + iss.read(reinterpret_cast(&int64), sizeof(int64)); + value = int64; + break; + default: + throw std::runtime_error("Invalid BSER int type"); + } + } + + int64_t intValue() override { + return value; + } + + void encode(std::ostream &oss) override { + if (value <= INT8_MAX) { + encodeType(oss, BSER_INT8); + int8_t v = (int8_t)value; + oss.write(reinterpret_cast(&v), sizeof(v)); + } else if (value <= INT16_MAX) { + encodeType(oss, BSER_INT16); + int16_t v = (int16_t)value; + oss.write(reinterpret_cast(&v), sizeof(v)); + } else if (value <= INT32_MAX) { + encodeType(oss, BSER_INT32); + int32_t v = (int32_t)value; + oss.write(reinterpret_cast(&v), sizeof(v)); + } else { + encodeType(oss, BSER_INT64); + oss.write(reinterpret_cast(&value), sizeof(value)); + } + } +}; + +class BSERArray : public Value { +public: + BSERArray() : Value() {} + BSERArray(BSER::Array value) : Value(value) {} + BSERArray(std::istream &iss) { + expectType(iss, BSER_ARRAY); + int64_t len = BSERInteger(iss).intValue(); + for (int64_t i = 0; i < len; i++) { + value.push_back(BSER(iss)); + } + } + + BSER::Array arrayValue() override { + return value; + } + + void encode(std::ostream &oss) override { + encodeType(oss, BSER_ARRAY); + BSERInteger(value.size()).encode(oss); + for (auto it = value.begin(); it != value.end(); it++) { + it->encode(oss); + } + } +}; + +class BSERString : public Value { +public: + BSERString(std::string value) : Value(value) {} + BSERString(std::istream &iss) { + expectType(iss, BSER_STRING); + int64_t len = BSERInteger(iss).intValue(); + value.resize(len); + iss.read(&value[0], len); + } + + std::string stringValue() override { + return value; + } + + void encode(std::ostream &oss) override { + encodeType(oss, BSER_STRING); + BSERInteger(value.size()).encode(oss); + oss << value; + } +}; + +class BSERObject : public Value { +public: + BSERObject() : Value() {} + BSERObject(BSER::Object value) : Value(value) {} + BSERObject(std::istream &iss) { + expectType(iss, BSER_OBJECT); + int64_t len = BSERInteger(iss).intValue(); + for (int64_t i = 0; i < len; i++) { + auto key = BSERString(iss).stringValue(); + auto val = BSER(iss); + value.emplace(key, val); + } + } + + BSER::Object objectValue() override { + return value; + } + + void encode(std::ostream &oss) override { + encodeType(oss, BSER_OBJECT); + BSERInteger(value.size()).encode(oss); + for (auto it = value.begin(); it != value.end(); it++) { + BSERString(it->first).encode(oss); + it->second.encode(oss); + } + } +}; + +class BSERDouble : public Value { +public: + BSERDouble(double value) : Value(value) {} + BSERDouble(std::istream &iss) { + expectType(iss, BSER_REAL); + iss.read(reinterpret_cast(&value), sizeof(value)); + } + + double doubleValue() override { + return value; + } + + void encode(std::ostream &oss) override { + encodeType(oss, BSER_REAL); + oss.write(reinterpret_cast(&value), sizeof(value)); + } +}; + +class BSERBoolean : public Value { +public: + BSERBoolean(bool value) : Value(value) {} + bool boolValue() override { return value; } + void encode(std::ostream &oss) override { + int8_t t = value == true ? static_cast(BSER_BOOL_TRUE) : static_cast(BSER_BOOL_FALSE); + oss.write(reinterpret_cast(&t), sizeof(t)); + } +}; + +class BSERNull : public Value { +public: + BSERNull() : Value(false) {} + void encode(std::ostream &oss) override { + encodeType(oss, BSER_NULL); + } +}; + +std::shared_ptr decodeTemplate(std::istream &iss) { + expectType(iss, BSER_TEMPLATE); + auto keys = BSERArray(iss).arrayValue(); + auto len = BSERInteger(iss).intValue(); + std::shared_ptr arr = std::make_shared(); + for (int64_t i = 0; i < len; i++) { + BSER::Object obj; + for (auto it = keys.begin(); it != keys.end(); it++) { + if (iss.peek() == 0x0c) { + iss.ignore(1); + continue; + } + + auto val = BSER(iss); + obj.emplace(it->stringValue(), val); + } + arr->value.push_back(obj); + } + return arr; +} + +BSER::BSER(std::istream &iss) { + BSERType type = decodeType(iss); + iss.unget(); + + switch (type) { + case BSER_ARRAY: + m_ptr = std::make_shared(iss); + break; + case BSER_OBJECT: + m_ptr = std::make_shared(iss); + break; + case BSER_STRING: + m_ptr = std::make_shared(iss); + break; + case BSER_INT8: + case BSER_INT16: + case BSER_INT32: + case BSER_INT64: + m_ptr = std::make_shared(iss); + break; + case BSER_REAL: + m_ptr = std::make_shared(iss); + break; + case BSER_BOOL_TRUE: + iss.ignore(1); + m_ptr = std::make_shared(true); + break; + case BSER_BOOL_FALSE: + iss.ignore(1); + m_ptr = std::make_shared(false); + break; + case BSER_NULL: + iss.ignore(1); + m_ptr = std::make_shared(); + break; + case BSER_TEMPLATE: + m_ptr = decodeTemplate(iss); + break; + default: + throw std::runtime_error("unknown BSER type"); + } +} + +BSER::BSER() : m_ptr(std::make_shared()) {} +BSER::BSER(BSER::Array value) : m_ptr(std::make_shared(value)) {} +BSER::BSER(BSER::Object value) : m_ptr(std::make_shared(value)) {} +BSER::BSER(const char *value) : m_ptr(std::make_shared(value)) {} +BSER::BSER(std::string value) : m_ptr(std::make_shared(value)) {} +BSER::BSER(int64_t value) : m_ptr(std::make_shared(value)) {} +BSER::BSER(double value) : m_ptr(std::make_shared(value)) {} +BSER::BSER(bool value) : m_ptr(std::make_shared(value)) {} + +BSER::Array BSER::arrayValue() { return m_ptr->arrayValue(); } +BSER::Object BSER::objectValue() { return m_ptr->objectValue(); } +std::string BSER::stringValue() { return m_ptr->stringValue(); } +int64_t BSER::intValue() { return m_ptr->intValue(); } +double BSER::doubleValue() { return m_ptr->doubleValue(); } +bool BSER::boolValue() { return m_ptr->boolValue(); } +void BSER::encode(std::ostream &oss) { + m_ptr->encode(oss); +} + +int64_t BSER::decodeLength(std::istream &iss) { + char pdu[2]; + if (!iss.read(pdu, 2) || pdu[0] != 0 || pdu[1] != 1) { + throw std::runtime_error("Invalid BSER"); + } + + return BSERInteger(iss).intValue(); +} + +std::string BSER::encode() { + std::ostringstream oss(std::ios_base::binary); + encode(oss); + + std::ostringstream res(std::ios_base::binary); + res.write("\x00\x01", 2); + + BSERInteger(oss.str().size()).encode(res); + res << oss.str(); + return res.str(); +} diff --git a/dg-ui/node_modules/@parcel/watcher/src/watchman/BSER.hh b/dg-ui/node_modules/@parcel/watcher/src/watchman/BSER.hh new file mode 100644 index 0000000..6bd2025 --- /dev/null +++ b/dg-ui/node_modules/@parcel/watcher/src/watchman/BSER.hh @@ -0,0 +1,69 @@ +#ifndef BSER_H +#define BSER_H + +#include +#include +#include +#include +#include + +enum BSERType { + BSER_ARRAY = 0x00, + BSER_OBJECT = 0x01, + BSER_STRING = 0x02, + BSER_INT8 = 0x03, + BSER_INT16 = 0x04, + BSER_INT32 = 0x05, + BSER_INT64 = 0x06, + BSER_REAL = 0x07, + BSER_BOOL_TRUE = 0x08, + BSER_BOOL_FALSE = 0x09, + BSER_NULL = 0x0a, + BSER_TEMPLATE = 0x0b +}; + +class BSERValue; + +class BSER { +public: + typedef std::vector Array; + typedef std::unordered_map Object; + + BSER(); + BSER(BSER::Array value); + BSER(BSER::Object value); + BSER(std::string value); + BSER(const char *value); + BSER(int64_t value); + BSER(double value); + BSER(bool value); + BSER(std::istream &iss); + + BSER::Array arrayValue(); + BSER::Object objectValue(); + std::string stringValue(); + int64_t intValue(); + double doubleValue(); + bool boolValue(); + void encode(std::ostream &oss); + + static int64_t decodeLength(std::istream &iss); + std::string encode(); +private: + std::shared_ptr m_ptr; +}; + +class BSERValue { +protected: + friend class BSER; + virtual BSER::Array arrayValue() { return BSER::Array(); } + virtual BSER::Object objectValue() { return BSER::Object(); } + virtual std::string stringValue() { return std::string(); } + virtual int64_t intValue() { return 0; } + virtual double doubleValue() { return 0; } + virtual bool boolValue() { return false; } + virtual void encode(std::ostream &oss) {} + virtual ~BSERValue() {} +}; + +#endif diff --git a/dg-ui/node_modules/@parcel/watcher/src/watchman/IPC.hh b/dg-ui/node_modules/@parcel/watcher/src/watchman/IPC.hh new file mode 100644 index 0000000..94aa62f --- /dev/null +++ b/dg-ui/node_modules/@parcel/watcher/src/watchman/IPC.hh @@ -0,0 +1,175 @@ +#ifndef IPC_H +#define IPC_H + +#include +#include + +#ifdef _WIN32 +#include +#include +#else +#include +#include +#include +#endif + +class IPC { +public: + IPC(std::string path) { + mStopped = false; + #ifdef _WIN32 + while (true) { + mPipe = CreateFile( + path.data(), // pipe name + GENERIC_READ | GENERIC_WRITE, // read and write access + 0, // no sharing + NULL, // default security attributes + OPEN_EXISTING, // opens existing pipe + FILE_FLAG_OVERLAPPED, // attributes + NULL // no template file + ); + + if (mPipe != INVALID_HANDLE_VALUE) { + break; + } + + if (GetLastError() != ERROR_PIPE_BUSY) { + throw std::runtime_error("Could not open pipe"); + } + + // Wait for pipe to become available if it is busy + if (!WaitNamedPipe(path.data(), 30000)) { + throw std::runtime_error("Error waiting for pipe"); + } + } + + mReader = CreateEvent(NULL, true, false, NULL); + mWriter = CreateEvent(NULL, true, false, NULL); + #else + struct sockaddr_un addr; + memset(&addr, 0, sizeof(addr)); + addr.sun_family = AF_UNIX; + strncpy(addr.sun_path, path.c_str(), sizeof(addr.sun_path) - 1); + + mSock = socket(AF_UNIX, SOCK_STREAM, 0); + if (connect(mSock, (struct sockaddr *) &addr, sizeof(struct sockaddr_un))) { + throw std::runtime_error("Error connecting to socket"); + } + #endif + } + + ~IPC() { + mStopped = true; + #ifdef _WIN32 + CancelIo(mPipe); + CloseHandle(mPipe); + CloseHandle(mReader); + CloseHandle(mWriter); + #else + shutdown(mSock, SHUT_RDWR); + #endif + } + + void write(std::string buf) { + #ifdef _WIN32 + OVERLAPPED overlapped; + overlapped.hEvent = mWriter; + bool success = WriteFile( + mPipe, // pipe handle + buf.data(), // message + static_cast(buf.size()), // message length + NULL, // bytes written + &overlapped // overlapped + ); + + if (mStopped) { + return; + } + + if (!success) { + if (GetLastError() != ERROR_IO_PENDING) { + throw std::runtime_error("Write error"); + } + } + + DWORD written; + success = GetOverlappedResult(mPipe, &overlapped, &written, true); + if (!success) { + throw std::runtime_error("GetOverlappedResult failed"); + } + + if (written != buf.size()) { + throw std::runtime_error("Wrong number of bytes written"); + } + #else + int r = 0; + for (unsigned int i = 0; i != buf.size(); i += r) { + r = ::write(mSock, &buf[i], buf.size() - i); + if (r == -1) { + if (errno == EAGAIN) { + r = 0; + } else if (mStopped) { + return; + } else { + throw std::runtime_error("Write error"); + } + } + } + #endif + } + + int read(char *buf, size_t len) { + #ifdef _WIN32 + OVERLAPPED overlapped; + overlapped.hEvent = mReader; + bool success = ReadFile( + mPipe, // pipe handle + buf, // buffer to receive reply + static_cast(len), // size of buffer + NULL, // number of bytes read + &overlapped // overlapped + ); + + if (!success && !mStopped) { + if (GetLastError() != ERROR_IO_PENDING) { + throw std::runtime_error("Read error"); + } + } + + DWORD read = 0; + success = GetOverlappedResult(mPipe, &overlapped, &read, true); + if (!success && !mStopped) { + throw std::runtime_error("GetOverlappedResult failed"); + } + + return read; + #else + int r = ::read(mSock, buf, len); + if (r == 0 && !mStopped) { + throw std::runtime_error("Socket ended unexpectedly"); + } + + if (r < 0) { + if (mStopped) { + return 0; + } + + throw std::runtime_error(strerror(errno)); + } + + return r; + #endif + } + +private: + bool mStopped; + #ifdef _WIN32 + HANDLE mPipe; + HANDLE mReader; + HANDLE mWriter; + #else + int mSock; + #endif +}; + +#endif diff --git a/dg-ui/node_modules/@parcel/watcher/src/watchman/WatchmanBackend.cc b/dg-ui/node_modules/@parcel/watcher/src/watchman/WatchmanBackend.cc new file mode 100644 index 0000000..a442f16 --- /dev/null +++ b/dg-ui/node_modules/@parcel/watcher/src/watchman/WatchmanBackend.cc @@ -0,0 +1,342 @@ +#include +#include +#include +#include +#include "../DirTree.hh" +#include "../Event.hh" +#include "./BSER.hh" +#include "./WatchmanBackend.hh" + +#ifdef _WIN32 +#include "../windows/win_utils.hh" +#define S_ISDIR(mode) ((mode & _S_IFDIR) == _S_IFDIR) +#define popen _popen +#define pclose _pclose +#else +#include +#define normalizePath(dir) dir +#endif + +template +BSER readBSER(T &&do_read) { + std::stringstream oss; + char buffer[256]; + size_t r; + int64_t len = -1; + do { + // Start by reading a minimal amount of data in order to decode the length. + // After that, attempt to read the remaining length, up to the buffer size. + r = do_read(buffer, len == -1 ? 20 : (len < 256 ? len : 256)); + oss << std::string(buffer, r); + + if (len == -1) { + uint64_t l = BSER::decodeLength(oss); + len = l + oss.tellg(); + } + + len -= r; + } while (len > 0); + + return BSER(oss); +} + +std::string getSockPath() { + auto var = getenv("WATCHMAN_SOCK"); + if (var && *var) { + return std::string(var); + } + +#ifdef _WIN32 + FILE *fp = popen("watchman --output-encoding=bser get-sockname", "r"); +#else + FILE *fp = popen("watchman --output-encoding=bser get-sockname 2>/dev/null", "r"); +#endif + if (fp == NULL || errno == ECHILD) { + throw std::runtime_error("Failed to execute watchman"); + } + + BSER b = readBSER([fp] (char *buf, size_t len) { + return fread(buf, sizeof(char), len, fp); + }); + + pclose(fp); + + auto objValue = b.objectValue(); + auto foundSockname = objValue.find("sockname"); + if (foundSockname == objValue.end()) { + throw std::runtime_error("sockname not found"); + } + return foundSockname->second.stringValue(); +} + +std::unique_ptr watchmanConnect() { + std::string path = getSockPath(); + return std::unique_ptr(new IPC(path)); +} + +BSER watchmanRead(IPC *ipc) { + return readBSER([ipc] (char *buf, size_t len) { + return ipc->read(buf, len); + }); +} + +BSER::Object WatchmanBackend::watchmanRequest(BSER b) { + std::string cmd = b.encode(); + mIPC->write(cmd); + mRequestSignal.notify(); + + mResponseSignal.wait(); + mResponseSignal.reset(); + + if (!mError.empty()) { + std::runtime_error err = std::runtime_error(mError); + mError = std::string(); + throw err; + } + + return mResponse; +} + +void WatchmanBackend::watchmanWatch(std::string dir) { + std::vector cmd; + cmd.push_back("watch"); + cmd.push_back(normalizePath(dir)); + watchmanRequest(cmd); +} + +bool WatchmanBackend::checkAvailable() { + try { + watchmanConnect(); + return true; + } catch (std::exception&) { + return false; + } +} + +void handleFiles(WatcherRef watcher, BSER::Object obj) { + auto found = obj.find("files"); + if (found == obj.end()) { + throw WatcherError("Error reading changes from watchman", watcher); + } + + auto files = found->second.arrayValue(); + for (auto it = files.begin(); it != files.end(); it++) { + auto file = it->objectValue(); + auto name = file.find("name")->second.stringValue(); + #ifdef _WIN32 + std::replace(name.begin(), name.end(), '/', '\\'); + #endif + auto mode = file.find("mode")->second.intValue(); + auto isNew = file.find("new")->second.boolValue(); + auto exists = file.find("exists")->second.boolValue(); + auto path = watcher->mDir + DIR_SEP + name; + if (watcher->isIgnored(path)) { + continue; + } + + if (isNew && exists) { + watcher->mEvents.create(path); + } else if (exists && !S_ISDIR(mode)) { + watcher->mEvents.update(path); + } else if (!isNew && !exists) { + watcher->mEvents.remove(path); + } + } +} + +void WatchmanBackend::handleSubscription(BSER::Object obj) { + std::unique_lock lock(mMutex); + auto subscription = obj.find("subscription")->second.stringValue(); + auto it = mSubscriptions.find(subscription); + if (it == mSubscriptions.end()) { + return; + } + + auto watcher = it->second; + try { + handleFiles(watcher, obj); + watcher->notify(); + } catch (WatcherError &err) { + handleWatcherError(err); + } +} + +void WatchmanBackend::start() { + mIPC = watchmanConnect(); + notifyStarted(); + + while (true) { + // If there are no subscriptions we are reading, wait for a request. + if (mSubscriptions.size() == 0) { + mRequestSignal.wait(); + mRequestSignal.reset(); + } + + // Break out of loop if we are stopped. + if (mStopped) { + break; + } + + // Attempt to read from the socket. + // If there is an error and we are stopped, break. + BSER b; + try { + b = watchmanRead(&*mIPC); + } catch (std::exception &err) { + if (mStopped) { + break; + } else if (mResponseSignal.isWaiting()) { + mError = err.what(); + mResponseSignal.notify(); + } else { + // Throwing causes the backend to be destroyed, but we never reach the code below to notify the signal + mEndedSignal.notify(); + throw; + } + } + + auto obj = b.objectValue(); + auto error = obj.find("error"); + if (error != obj.end()) { + mError = error->second.stringValue(); + mResponseSignal.notify(); + continue; + } + + // If this message is for a subscription, handle it, otherwise notify the request. + auto subscription = obj.find("subscription"); + if (subscription != obj.end()) { + handleSubscription(obj); + } else { + mResponse = obj; + mResponseSignal.notify(); + } + } + + mEndedSignal.notify(); +} + +WatchmanBackend::~WatchmanBackend() { + // Mark the watcher as stopped, close the socket, and trigger the lock. + // This will cause the read loop to be broken and the thread to exit. + mStopped = true; + mIPC.reset(); + mRequestSignal.notify(); + + // If not ended yet, wait. + mEndedSignal.wait(); +} + +std::string WatchmanBackend::clock(WatcherRef watcher) { + BSER::Array cmd; + cmd.push_back("clock"); + cmd.push_back(normalizePath(watcher->mDir)); + + BSER::Object obj = watchmanRequest(cmd); + auto found = obj.find("clock"); + if (found == obj.end()) { + throw WatcherError("Error reading clock from watchman", watcher); + } + + return found->second.stringValue(); +} + +void WatchmanBackend::writeSnapshot(WatcherRef watcher, std::string *snapshotPath) { + std::unique_lock lock(mMutex); + watchmanWatch(watcher->mDir); + + std::ofstream ofs(*snapshotPath); + ofs << clock(watcher); +} + +void WatchmanBackend::getEventsSince(WatcherRef watcher, std::string *snapshotPath) { + std::unique_lock lock(mMutex); + std::ifstream ifs(*snapshotPath); + if (ifs.fail()) { + return; + } + + watchmanWatch(watcher->mDir); + + std::string clock; + ifs >> clock; + + BSER::Array cmd; + cmd.push_back("since"); + cmd.push_back(normalizePath(watcher->mDir)); + cmd.push_back(clock); + + BSER::Object obj = watchmanRequest(cmd); + handleFiles(watcher, obj); +} + +std::string getId(WatcherRef watcher) { + std::ostringstream id; + id << "parcel-"; + id << static_cast(watcher.get()); + return id.str(); +} + +// This function is called by Backend::watch which takes a lock on mMutex +void WatchmanBackend::subscribe(WatcherRef watcher) { + watchmanWatch(watcher->mDir); + + std::string id = getId(watcher); + BSER::Array cmd; + cmd.push_back("subscribe"); + cmd.push_back(normalizePath(watcher->mDir)); + cmd.push_back(id); + + BSER::Array fields; + fields.push_back("name"); + fields.push_back("mode"); + fields.push_back("exists"); + fields.push_back("new"); + + BSER::Object opts; + opts.emplace("fields", fields); + opts.emplace("since", clock(watcher)); + + if (watcher->mIgnorePaths.size() > 0) { + BSER::Array ignore; + BSER::Array anyOf; + anyOf.push_back("anyof"); + + for (auto it = watcher->mIgnorePaths.begin(); it != watcher->mIgnorePaths.end(); it++) { + std::string pathStart = watcher->mDir + DIR_SEP; + if (it->rfind(pathStart, 0) == 0) { + auto relative = it->substr(pathStart.size()); + BSER::Array dirname; + dirname.push_back("dirname"); + dirname.push_back(relative); + anyOf.push_back(dirname); + } + } + + ignore.push_back("not"); + ignore.push_back(anyOf); + + opts.emplace("expression", ignore); + } + + cmd.push_back(opts); + watchmanRequest(cmd); + + mSubscriptions.emplace(id, watcher); + mRequestSignal.notify(); +} + +// This function is called by Backend::unwatch which takes a lock on mMutex +void WatchmanBackend::unsubscribe(WatcherRef watcher) { + std::string id = getId(watcher); + auto erased = mSubscriptions.erase(id); + + if (erased) { + BSER::Array cmd; + cmd.push_back("unsubscribe"); + cmd.push_back(normalizePath(watcher->mDir)); + cmd.push_back(id); + + watchmanRequest(cmd); + } +} diff --git a/dg-ui/node_modules/@parcel/watcher/src/watchman/WatchmanBackend.hh b/dg-ui/node_modules/@parcel/watcher/src/watchman/WatchmanBackend.hh new file mode 100644 index 0000000..699cded --- /dev/null +++ b/dg-ui/node_modules/@parcel/watcher/src/watchman/WatchmanBackend.hh @@ -0,0 +1,35 @@ +#ifndef WATCHMAN_H +#define WATCHMAN_H + +#include "../Backend.hh" +#include "./BSER.hh" +#include "../Signal.hh" +#include "./IPC.hh" + +class WatchmanBackend : public Backend { +public: + static bool checkAvailable(); + void start() override; + WatchmanBackend() : mStopped(false) {}; + ~WatchmanBackend(); + void writeSnapshot(WatcherRef watcher, std::string *snapshotPath) override; + void getEventsSince(WatcherRef watcher, std::string *snapshotPath) override; + void subscribe(WatcherRef watcher) override; + void unsubscribe(WatcherRef watcher) override; +private: + std::unique_ptr mIPC; + Signal mRequestSignal; + Signal mResponseSignal; + BSER::Object mResponse; + std::string mError; + std::unordered_map mSubscriptions; + bool mStopped; + Signal mEndedSignal; + + std::string clock(WatcherRef watcher); + void watchmanWatch(std::string dir); + BSER::Object watchmanRequest(BSER cmd); + void handleSubscription(BSER::Object obj); +}; + +#endif diff --git a/dg-ui/node_modules/@parcel/watcher/src/windows/WindowsBackend.cc b/dg-ui/node_modules/@parcel/watcher/src/windows/WindowsBackend.cc new file mode 100644 index 0000000..eabce1e --- /dev/null +++ b/dg-ui/node_modules/@parcel/watcher/src/windows/WindowsBackend.cc @@ -0,0 +1,282 @@ +#include +#include +#include "../DirTree.hh" +#include "../shared/BruteForceBackend.hh" +#include "./WindowsBackend.hh" +#include "./win_utils.hh" + +#define DEFAULT_BUF_SIZE 1024 * 1024 +#define NETWORK_BUF_SIZE 64 * 1024 +#define CONVERT_TIME(ft) ULARGE_INTEGER{ft.dwLowDateTime, ft.dwHighDateTime}.QuadPart + +void BruteForceBackend::readTree(WatcherRef watcher, std::shared_ptr tree) { + std::stack directories; + + directories.push(watcher->mDir); + + while (!directories.empty()) { + HANDLE hFind = INVALID_HANDLE_VALUE; + + std::string path = directories.top(); + std::string spec = path + "\\*"; + directories.pop(); + + WIN32_FIND_DATA ffd; + hFind = FindFirstFile(spec.c_str(), &ffd); + + if (hFind == INVALID_HANDLE_VALUE) { + if (path == watcher->mDir) { + FindClose(hFind); + throw WatcherError("Error opening directory", watcher); + } + + tree->remove(path); + continue; + } + + do { + if (strcmp(ffd.cFileName, ".") != 0 && strcmp(ffd.cFileName, "..") != 0) { + std::string fullPath = path + "\\" + ffd.cFileName; + if (watcher->isIgnored(fullPath)) { + continue; + } + + tree->add(fullPath, CONVERT_TIME(ffd.ftLastWriteTime), ffd.dwFileAttributes & FILE_ATTRIBUTE_DIRECTORY); + if (ffd.dwFileAttributes & FILE_ATTRIBUTE_DIRECTORY) { + directories.push(fullPath); + } + } + } while (FindNextFile(hFind, &ffd) != 0); + + FindClose(hFind); + } +} + +void WindowsBackend::start() { + mRunning = true; + notifyStarted(); + + while (mRunning) { + SleepEx(INFINITE, true); + } +} + +WindowsBackend::~WindowsBackend() { + // Mark as stopped, and queue a noop function in the thread to break the loop + mRunning = false; + QueueUserAPC([](__in ULONG_PTR) {}, mThread.native_handle(), (ULONG_PTR)this); +} + +class Subscription: public WatcherState { +public: + Subscription(WindowsBackend *backend, WatcherRef watcher, std::shared_ptr tree) { + mRunning = true; + mBackend = backend; + mWatcher = watcher; + mTree = tree; + ZeroMemory(&mOverlapped, sizeof(OVERLAPPED)); + mOverlapped.hEvent = this; + mReadBuffer.resize(DEFAULT_BUF_SIZE); + mWriteBuffer.resize(DEFAULT_BUF_SIZE); + + mDirectoryHandle = CreateFileW( + utf8ToUtf16(watcher->mDir).data(), + FILE_LIST_DIRECTORY, + FILE_SHARE_READ | FILE_SHARE_WRITE | FILE_SHARE_DELETE, + NULL, + OPEN_EXISTING, + FILE_FLAG_BACKUP_SEMANTICS | FILE_FLAG_OVERLAPPED, + NULL + ); + + if (mDirectoryHandle == INVALID_HANDLE_VALUE) { + throw WatcherError("Invalid handle", mWatcher); + } + + // Ensure that the path is a directory + BY_HANDLE_FILE_INFORMATION info; + bool success = GetFileInformationByHandle( + mDirectoryHandle, + &info + ); + + if (!success) { + throw WatcherError("Could not get file information", mWatcher); + } + + if (!(info.dwFileAttributes & FILE_ATTRIBUTE_DIRECTORY)) { + throw WatcherError("Not a directory", mWatcher); + } + } + + virtual ~Subscription() { + stop(); + } + + void run() { + try { + poll(); + } catch (WatcherError &err) { + mBackend->handleWatcherError(err); + } + } + + void stop() { + if (mRunning) { + mRunning = false; + CancelIo(mDirectoryHandle); + CloseHandle(mDirectoryHandle); + } + } + + void poll() { + if (!mRunning) { + return; + } + + // Asynchronously wait for changes. + int success = ReadDirectoryChangesW( + mDirectoryHandle, + mWriteBuffer.data(), + static_cast(mWriteBuffer.size()), + TRUE, // recursive + FILE_NOTIFY_CHANGE_FILE_NAME | FILE_NOTIFY_CHANGE_DIR_NAME | FILE_NOTIFY_CHANGE_ATTRIBUTES + | FILE_NOTIFY_CHANGE_SIZE | FILE_NOTIFY_CHANGE_LAST_WRITE, + NULL, + &mOverlapped, + [](DWORD errorCode, DWORD numBytes, LPOVERLAPPED overlapped) { + auto subscription = reinterpret_cast(overlapped->hEvent); + try { + subscription->processEvents(errorCode); + } catch (WatcherError &err) { + subscription->mBackend->handleWatcherError(err); + } + } + ); + + if (!success) { + throw WatcherError("Failed to read changes", mWatcher); + } + } + + void processEvents(DWORD errorCode) { + if (!mRunning) { + return; + } + + switch (errorCode) { + case ERROR_OPERATION_ABORTED: + return; + case ERROR_INVALID_PARAMETER: + // resize buffers to network size (64kb), and try again + mReadBuffer.resize(NETWORK_BUF_SIZE); + mWriteBuffer.resize(NETWORK_BUF_SIZE); + poll(); + return; + case ERROR_NOTIFY_ENUM_DIR: + throw WatcherError("Buffer overflow. Some events may have been lost.", mWatcher); + case ERROR_ACCESS_DENIED: { + // This can happen if the watched directory is deleted. Check if that is the case, + // and if so emit a delete event. Otherwise, fall through to default error case. + DWORD attrs = GetFileAttributesW(utf8ToUtf16(mWatcher->mDir).data()); + bool isDir = attrs != INVALID_FILE_ATTRIBUTES && (attrs & FILE_ATTRIBUTE_DIRECTORY); + if (!isDir) { + mWatcher->mEvents.remove(mWatcher->mDir); + mTree->remove(mWatcher->mDir); + mWatcher->notify(); + stop(); + return; + } + } + default: + if (errorCode != ERROR_SUCCESS) { + throw WatcherError("Unknown error", mWatcher); + } + } + + // Swap read and write buffers, and poll again + std::swap(mWriteBuffer, mReadBuffer); + poll(); + + // Read change events + BYTE *base = mReadBuffer.data(); + while (true) { + PFILE_NOTIFY_INFORMATION info = (PFILE_NOTIFY_INFORMATION)base; + processEvent(info); + + if (info->NextEntryOffset == 0) { + break; + } + + base += info->NextEntryOffset; + } + + mWatcher->notify(); + } + + void processEvent(PFILE_NOTIFY_INFORMATION info) { + std::string path = mWatcher->mDir + "\\" + utf16ToUtf8(info->FileName, info->FileNameLength / sizeof(WCHAR)); + if (mWatcher->isIgnored(path)) { + return; + } + + switch (info->Action) { + case FILE_ACTION_ADDED: + case FILE_ACTION_RENAMED_NEW_NAME: { + WIN32_FILE_ATTRIBUTE_DATA data; + if (GetFileAttributesExW(utf8ToUtf16(path).data(), GetFileExInfoStandard, &data)) { + mWatcher->mEvents.create(path); + mTree->add(path, CONVERT_TIME(data.ftLastWriteTime), data.dwFileAttributes & FILE_ATTRIBUTE_DIRECTORY); + } + break; + } + case FILE_ACTION_MODIFIED: { + WIN32_FILE_ATTRIBUTE_DATA data; + if (GetFileAttributesExW(utf8ToUtf16(path).data(), GetFileExInfoStandard, &data)) { + mTree->update(path, CONVERT_TIME(data.ftLastWriteTime)); + if (!(data.dwFileAttributes & FILE_ATTRIBUTE_DIRECTORY)) { + mWatcher->mEvents.update(path); + } + } + break; + } + case FILE_ACTION_REMOVED: + case FILE_ACTION_RENAMED_OLD_NAME: + mWatcher->mEvents.remove(path); + mTree->remove(path); + break; + } + } + +private: + WindowsBackend *mBackend; + std::shared_ptr mWatcher; + std::shared_ptr mTree; + bool mRunning; + HANDLE mDirectoryHandle; + std::vector mReadBuffer; + std::vector mWriteBuffer; + OVERLAPPED mOverlapped; +}; + +// This function is called by Backend::watch which takes a lock on mMutex +void WindowsBackend::subscribe(WatcherRef watcher) { + // Create a subscription for this watcher + auto sub = std::make_shared(this, watcher, getTree(watcher, false)); + watcher->state = sub; + + // Queue polling for this subscription in the correct thread. + bool success = QueueUserAPC([](__in ULONG_PTR ptr) { + Subscription *sub = (Subscription *)ptr; + sub->run(); + }, mThread.native_handle(), (ULONG_PTR)sub.get()); + + if (!success) { + throw std::runtime_error("Unable to queue APC"); + } +} + +// This function is called by Backend::unwatch which takes a lock on mMutex +void WindowsBackend::unsubscribe(WatcherRef watcher) { + watcher->state = nullptr; +} diff --git a/dg-ui/node_modules/@parcel/watcher/src/windows/WindowsBackend.hh b/dg-ui/node_modules/@parcel/watcher/src/windows/WindowsBackend.hh new file mode 100644 index 0000000..d679782 --- /dev/null +++ b/dg-ui/node_modules/@parcel/watcher/src/windows/WindowsBackend.hh @@ -0,0 +1,18 @@ +#ifndef WINDOWS_H +#define WINDOWS_H + +#include +#include +#include "../shared/BruteForceBackend.hh" + +class WindowsBackend : public BruteForceBackend { +public: + void start() override; + ~WindowsBackend(); + void subscribe(WatcherRef watcher) override; + void unsubscribe(WatcherRef watcher) override; +private: + bool mRunning; +}; + +#endif diff --git a/dg-ui/node_modules/@parcel/watcher/src/windows/win_utils.cc b/dg-ui/node_modules/@parcel/watcher/src/windows/win_utils.cc new file mode 100644 index 0000000..62a1e59 --- /dev/null +++ b/dg-ui/node_modules/@parcel/watcher/src/windows/win_utils.cc @@ -0,0 +1,44 @@ +#include "./win_utils.hh" + +std::wstring utf8ToUtf16(std::string input) { + unsigned int len = MultiByteToWideChar(CP_UTF8, 0, input.c_str(), -1, NULL, 0); + WCHAR *output = new WCHAR[len]; + MultiByteToWideChar(CP_UTF8, 0, input.c_str(), -1, output, len); + std::wstring res(output); + delete[] output; + return res; +} + +std::string utf16ToUtf8(const WCHAR *input, DWORD length) { + unsigned int len = WideCharToMultiByte(CP_UTF8, 0, input, length, NULL, 0, NULL, NULL); + char *output = new char[len + 1]; + WideCharToMultiByte(CP_UTF8, 0, input, length, output, len, NULL, NULL); + output[len] = '\0'; + std::string res(output); + delete[] output; + return res; +} + +std::string normalizePath(std::string path) { + // Prevent truncation to MAX_PATH characters by adding the \\?\ prefix + std::wstring p = utf8ToUtf16("\\\\?\\" + path); + + // Get the required length for the output + DWORD len = GetLongPathNameW(p.data(), NULL, 0); + if (!len) { + return path; + } + + // Allocate output array and get long path + WCHAR *output = new WCHAR[len]; + len = GetLongPathNameW(p.data(), output, len); + if (!len) { + delete[] output; + return path; + } + + // Convert back to utf8 + std::string res = utf16ToUtf8(output + 4, len - 4); + delete[] output; + return res; +} diff --git a/dg-ui/node_modules/@parcel/watcher/src/windows/win_utils.hh b/dg-ui/node_modules/@parcel/watcher/src/windows/win_utils.hh new file mode 100644 index 0000000..9178d1b --- /dev/null +++ b/dg-ui/node_modules/@parcel/watcher/src/windows/win_utils.hh @@ -0,0 +1,11 @@ +#ifndef WIN_UTILS_H +#define WIN_UTILS_H + +#include +#include + +std::wstring utf8ToUtf16(std::string input); +std::string utf16ToUtf8(const WCHAR *input, DWORD length); +std::string normalizePath(std::string path); + +#endif diff --git a/dg-ui/node_modules/@parcel/watcher/wrapper.js b/dg-ui/node_modules/@parcel/watcher/wrapper.js new file mode 100644 index 0000000..0b7d3e2 --- /dev/null +++ b/dg-ui/node_modules/@parcel/watcher/wrapper.js @@ -0,0 +1,88 @@ +const path = require('path'); +const picomatch = require('picomatch'); +const isGlob = require('is-glob'); + +function normalizeOptions(dir, opts = {}) { + const {ignore, ...rest} = opts; + + if (Array.isArray(ignore)) { + opts = {...rest}; + + for (const value of ignore) { + if (value instanceof RegExp) { + if (value.flags !== '') { + throw new Error( + `RegExp ignore patterns must not have flags (got /${value.source}/${value.flags}). Flags are not supported by the native matcher.`, + ); + } + if (!opts.ignoreGlobs) { + opts.ignoreGlobs = []; + } + // The native backend uses std::regex_match (full-string match), but + // callers expect JS .test() semantics (substring search). Wrapping the + // source in ^[\\s\\S]*(?:…)[\\s\\S]*$ achieves that. The (?:…) group + // isolates the source so leading/trailing | in the source stays contained. + opts.ignoreGlobs.push(`^[\\s\\S]*(?:${value.source})[\\s\\S]*$`); + } else if (isGlob(value)) { + if (!opts.ignoreGlobs) { + opts.ignoreGlobs = []; + } + + const regex = picomatch.makeRe(value, { + // We set `dot: true` to workaround an issue with the + // regular expression on Linux where the resulting + // negative lookahead `(?!(\\/|^)` was never matching + // in some cases. See also https://bit.ly/3UZlQDm + dot: true, + windows: process.platform === 'win32', + }); + opts.ignoreGlobs.push(regex.source); + } else { + if (!opts.ignorePaths) { + opts.ignorePaths = []; + } + + opts.ignorePaths.push(path.resolve(dir, value)); + } + } + } + + return opts; +} + +exports.createWrapper = (binding) => { + return { + writeSnapshot(dir, snapshot, opts) { + return binding.writeSnapshot( + path.resolve(dir), + path.resolve(snapshot), + normalizeOptions(dir, opts), + ); + }, + getEventsSince(dir, snapshot, opts) { + return binding.getEventsSince( + path.resolve(dir), + path.resolve(snapshot), + normalizeOptions(dir, opts), + ); + }, + async subscribe(dir, fn, opts) { + dir = path.resolve(dir); + opts = normalizeOptions(dir, opts); + await binding.subscribe(dir, fn, opts); + + return { + unsubscribe() { + return binding.unsubscribe(dir, fn, opts); + }, + }; + }, + unsubscribe(dir, fn, opts) { + return binding.unsubscribe( + path.resolve(dir), + fn, + normalizeOptions(dir, opts), + ); + }, + }; +}; diff --git a/dg-ui/node_modules/@tailwindcss/cli/LICENSE b/dg-ui/node_modules/@tailwindcss/cli/LICENSE new file mode 100644 index 0000000..d6a8229 --- /dev/null +++ b/dg-ui/node_modules/@tailwindcss/cli/LICENSE @@ -0,0 +1,21 @@ +MIT License + +Copyright (c) Tailwind Labs, Inc. + +Permission is hereby granted, free of charge, to any person obtaining a copy +of this software and associated documentation files (the "Software"), to deal +in the Software without restriction, including without limitation the rights +to use, copy, modify, merge, publish, distribute, sublicense, and/or sell +copies of the Software, and to permit persons to whom the Software is +furnished to do so, subject to the following conditions: + +The above copyright notice and this permission notice shall be included in all +copies or substantial portions of the Software. + +THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR +IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, +FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE +AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER +LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, +OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE +SOFTWARE. diff --git a/dg-ui/node_modules/@tailwindcss/cli/README.md b/dg-ui/node_modules/@tailwindcss/cli/README.md new file mode 100644 index 0000000..5f53260 --- /dev/null +++ b/dg-ui/node_modules/@tailwindcss/cli/README.md @@ -0,0 +1,36 @@ +

+ + + + + Tailwind CSS + + +

+ +

+ A utility-first CSS framework for rapidly building custom user interfaces. +

+ +

+ Build Status + Total Downloads + Latest Release + License +

+ +--- + +## Documentation + +For full documentation, visit [tailwindcss.com](https://tailwindcss.com). + +## Community + +For help, discussion about best practices, or feature ideas: + +[Discuss Tailwind CSS on GitHub](https://github.com/tailwindlabs/tailwindcss/discussions) + +## Contributing + +If you're interested in contributing to Tailwind CSS, please read our [contributing docs](https://github.com/tailwindlabs/tailwindcss/blob/main/.github/CONTRIBUTING.md) **before submitting a pull request**. diff --git a/dg-ui/node_modules/@tailwindcss/cli/dist/index.mjs b/dg-ui/node_modules/@tailwindcss/cli/dist/index.mjs new file mode 100644 index 0000000..5953e4c --- /dev/null +++ b/dg-ui/node_modules/@tailwindcss/cli/dist/index.mjs @@ -0,0 +1,28 @@ +#!/usr/bin/env node +var ye=(e,t)=>(t=Symbol[e])?t:Symbol.for("Symbol."+e),Se=e=>{throw TypeError(e)};var J=(e,t,n)=>{if(t!=null){typeof t!="object"&&typeof t!="function"&&Se("Object expected");var i,r;n&&(i=t[ye("asyncDispose")]),i===void 0&&(i=t[ye("dispose")],n&&(r=i)),typeof i!="function"&&Se("Object not disposable"),r&&(i=function(){try{r.call(this)}catch(s){return Promise.reject(s)}}),e.push([n,i,t])}else n&&e.push([n]);return t},Q=(e,t,n)=>{var i=typeof SuppressedError=="function"?SuppressedError:function(o,a,l,c){return c=Error(l),c.name="SuppressedError",c.error=o,c.suppressed=a,c},r=o=>t=n?new i(o,t,"An error was suppressed during disposal"):(n=!0,o),s=o=>{for(;o=e.pop();)try{var a=o[1]&&o[1].call(o[2]);if(o[0])return Promise.resolve(a).then(s,l=>(r(l),s()))}catch(l){r(l)}if(n)throw t};return s()};import Je from"mri";function k(e,t=process.argv.slice(2)){for(let[r,s]of t.entries())s==="-"&&(t[r]="__IO_DEFAULT_VALUE__");let n=Je(t);for(let r in n){let s=n[r];r!=="_"&&Array.isArray(s)&&(s=s[s.length-1]),s==="__IO_DEFAULT_VALUE__"&&(s="-"),n[r]=s}let i={_:n._};for(let[r,{type:s,alias:o,default:a=s==="boolean"?!1:null}]of Object.entries(e)){if(i[r]=a,o){let l=o.slice(1);n[l]!==void 0&&(i[r]=Ce(n[l],s))}{let l=r.slice(2);n[l]!==void 0&&(i[r]=Ce(n[l],s))}}return i}function Ce(e,t){switch(t){case"string":return X(e);case"boolean":return H(e);case"number":return Z(e);case"boolean | string":return H(e)??X(e);case"number | string":return Z(e)??X(e);case"boolean | number":return H(e)??Z(e);case"boolean | number | string":return H(e)??Z(e)??X(e);default:throw new Error(`Unhandled type: ${t}`)}}function H(e){if(e===!0||e===!1)return e;if(e==="true")return!0;if(e==="false")return!1}function Z(e){if(typeof e=="number")return e;{let t=Number(e);if(!Number.isNaN(t))return t}}function X(e){return`${e}`}import{compile as it,env as rt,Instrumentation as pe,optimize as st,toSourceMap as M}from"@tailwindcss/node";import{clearRequireCache as Ee}from"@tailwindcss/node/require-cache";import{Scanner as ot}from"@tailwindcss/oxide";import{existsSync as lt}from"fs";import j from"fs/promises";import C from"path";var I=class{#e=new Set([]);queueMacrotask(t){let n=setTimeout(t,0);return this.add(()=>{clearTimeout(n)})}add(t){return this.#e.add(t),()=>{this.#e.delete(t),t()}}async dispose(){for(let t of this.#e)await t();this.#e.clear()}};import Xe from"fs";import $e from"path";import{stripVTControlCharacters as et}from"util";import $ from"picocolors";import xe from"enhanced-resolve";import Qe from"fs";import{createRequire as He}from"module";var Ze=He(import.meta.url).resolve;function Te(e){if(typeof globalThis.__tw_resolve=="function"){let t=globalThis.__tw_resolve(e);if(t)return t}return Ze(e)}var Wt=xe.ResolverFactory.createResolver({fileSystem:new xe.CachedInputFileSystem(Qe,4e3),useSyncFileSystemCalls:!0,extensions:[".css"],mainFields:["style"],conditionNames:["style"]});function _e(e){let t=typeof e=="number"?BigInt(e):e;return t<1000n?`${t}ns`:(t/=1000n,t<1000n?`${t}\xB5s`:(t/=1000n,t<1000n?`${t}ms`:(t/=1000n,t<60n?`${t}s`:(t/=60n,t<60n?`${t}m`:(t/=60n,t<24n?`${t}h`:(t/=24n,`${t}d`))))))}var ee={indent:2};function te(){return`${$.italic($.bold($.blue("\u2248")))} tailwindcss ${$.blue(`v${tt()}`)}`}function F(e){return`${$.dim($.blue("`"))}${$.blue(e)}${$.dim($.blue("`"))}`}function ne(e,t=process.cwd(),{preferAbsoluteIfShorter:n=!0}={}){let i=$e.relative(t,e);return i.startsWith("..")||(i=`.${$e.sep}${i}`),n&&i.length>e.length?e:i}function z(e,t){let n=e.split(" "),i=[],r="",s=0;for(let o of n){let a=et(o).length;s>0&&s+a+1>t&&(i.push(r),r="",s=0),r+=(s?" ":"")+o,s+=a+(s?1:0)}return s&&i.push(r),i}function O(e){let t=_e(e);return e<=50*1e6?$.green(t):e<=300*1e6?$.blue(t):e<=1e3*1e6?$.yellow(t):$.red(t)}function W(e,t=0){return`${" ".repeat(t+ee.indent)}${e}`}function T(e=""){process.stderr.write(`${e} +`)}function ie(e=""){process.stdout.write(`${e} +`)}function tt(){if(typeof globalThis.__tw_version=="string")return globalThis.__tw_version;let{version:e}=JSON.parse(Xe.readFileSync(Te("tailwindcss/package.json"),"utf-8"));return e}import re from"fs/promises";import nt from"path";function se(){return new Promise((e,t)=>{let n="";process.stdin.on("data",i=>{n+=i}),process.stdin.on("end",()=>e(n)),process.stdin.on("error",i=>t(i))})}async function ce(e,t){if(!await re.stat(e).then(i=>i.isCharacterDevice()||i.isFIFO()).catch(()=>!1))try{if(await re.readFile(e,"utf8")===t)return}catch{}await re.mkdir(nt.dirname(e),{recursive:!0}),await re.writeFile(e,t,"utf8")}var de=String.raw,u=rt.DEBUG,at=250;function U(){return{"--input":{type:"string",description:"Input file",alias:"-i"},"--output":{type:"string",description:"Output file",alias:"-o",default:"-"},"--watch":{type:"boolean | string",description:"Watch for changes and rebuild as needed, and use `always` to keep watching when stdin is closed",alias:"-w",values:["always"]},"--poll":{type:"boolean | number",description:"Use polling instead of filesystem events when watching",default:!1,values:["ms"]},"--minify":{type:"boolean",description:"Optimize and minify the output",alias:"-m"},"--optimize":{type:"boolean",description:"Optimize the output without minifying"},"--cwd":{type:"string",description:"The current working directory",default:"."},"--map":{type:"boolean | string",description:"Generate a source map",default:!1},"--silent":{type:"boolean",description:"Suppress non-error output"}}}function fe(e){let t=new Set;function n(i,r){let s=" ".repeat(r),o=(process.stderr.columns??1/0)-2*(r+1),a=[`${s}${ct(r===0?"Error:":"Caused by:")}`,`${s}${G("\u250C")}`];for(let l of`${i}`.split(` +`)){let c=z(l,o);c.length===0&&(c=[""]);for(let m of c)a.push(`${s}${G("\u2502")} ${m}`)}return a.push(`${s}${G("\u2514")}`),typeof i=="object"&&i!==null&&"cause"in i&&i.cause!=null&&(t.add(i).has(i.cause)||a.push(...n(i.cause,r+1))),a}return n(e,0).join(` +`)}async function oe(e){try{return await e()}catch(t){T(fe(t)),process.exit(1)}}async function me(e){var be=[];try{e["--silent"]||T(te());e["--silent"]||T();let t=J(be,new pe);u&&t.start("[@tailwindcss/cli] (initial build)");let n=C.resolve(e["--cwd"]);e["--output"]&&e["--output"]!=="-"&&(e["--output"]=C.resolve(n,e["--output"]));e["--input"]&&e["--input"]!=="-"&&(e["--input"]=C.resolve(n,e["--input"]),lt(e["--input"])||(T(`Specified input file ${F(ne(e["--input"]))} does not exist.`),process.exit(1)));e["--input"]===e["--output"]&&e["--input"]!=="-"&&(T(`Specified input file ${F(ne(e["--input"]))} and output file ${F(ne(e["--output"]))} are identical.`),process.exit(1));e["--map"]==="-"&&(T("Use --map without a value to inline the source map."),process.exit(1));e["--poll"]===void 0&&(T("Use --poll with a non-zero value in milliseconds."),process.exit(1));let i=e["--poll"]===!0?at:e["--poll"];i!==!1&&i<=0&&(T("Specified polling interval must be a positive number."),process.exit(1));e["--map"]&&e["--map"]!==!0&&(e["--map"]=C.resolve(n,e["--map"]));let r=process.hrtime.bigint();let s=e["--input"]?e["--input"]==="-"?await se():await j.readFile(e["--input"],"utf-8"):de` + @import 'tailwindcss'; + `;let o={css:"",optimizedCss:"",output:null};async function a(_,S,g,d){let h=_;if(g["--minify"]||g["--optimize"])if(_!==o.css){u&&d.start("Optimize CSS");let p=st(_,{file:g["--input"]??"input.css",minify:g["--minify"]??!1,map:S?.raw??void 0});u&&d.end("Optimize CSS"),o.css=_,o.optimizedCss=p.code,p.map&&(S=M(p.map)),h=p.code}else h=o.optimizedCss;if(S){if(g["--map"]===!0)h+=` +`,h+=S.inline;else if(typeof g["--map"]=="string"){let p=g["--output"]&&g["--output"]!=="-"?C.dirname(C.resolve(g["--output"])):process.cwd(),E=C.resolve(g["--map"]),B=C.relative(p,E);h+=` +`,h+=S.comment(B),u&&d.start("Write source map"),await ce(g["--map"],S.raw),u&&d.end("Write source map")}}let x=h!==o.output;return u&&d.start("Write output"),g["--output"]&&g["--output"]!=="-"?await ce(g["--output"],h):x&&ie(h),u&&d.end("Write output"),o.output=h,x}let l=e["--input"]&&e["--input"]!=="-"?C.resolve(e["--input"]):null;let c=l?C.dirname(l):process.cwd();let m=l?[l]:[];let b=m;async function w(_,S){u&&S.start("Setup compiler");let g=await it(_,{from:e["--output"]?l??"stdin.css":void 0,base:c,onDependency(x){m.push(x)}}),d=(g.root==="none"?[]:g.root===null?[{base:n,pattern:"**/*",negated:!1}]:[{...g.root,negated:!1}]).concat(g.sources);d.push({base:C.dirname(process.execPath),pattern:C.basename(process.execPath),negated:!0}),l!==null&&d.push({base:C.dirname(l),pattern:C.basename(l),negated:!1});let h=new ot({sources:d});return u&&S.end("Setup compiler"),[g,h]}let[f,y]=await oe(()=>w(s,t));let R=[];e["--watch"]&&i===!1&&(await oe(()=>Ae()),R.push(await Re(await Oe(y),async function _(S){try{var g=[];try{if(S.length===1&&S[0]===e["--output"])return;let p=J(g,new pe);u&&p.start("[@tailwindcss/cli] (watcher)");let E=process.hrtime.bigint();let B=m;let P=ve(S,B);let N="";let D=null;if(P.kind==="full"){let L=e["--input"]?e["--input"]==="-"?await se():await j.readFile(e["--input"],"utf-8"):de` + @import 'tailwindcss'; + `;Ee(B),b=m.slice(),m=l?[l]:[],[f,y]=await w(L,p),b=m.slice(),u&&p.start("Scan for candidates");let v=y.scan();u&&p.end("Scan for candidates"),u&&p.start("Setup new watchers");let Ve=await Re(await Oe(y),_);u&&p.end("Setup new watchers"),u&&p.start("Cleanup old watchers"),await Promise.all(R.splice(0).map(qe=>qe())),u&&p.end("Cleanup old watchers"),R.push(Ve),u&&p.start("Build CSS"),N=f.build(v),u&&p.end("Build CSS"),e["--map"]&&(u&&p.start("Build Source Map"),D=M(f.buildSourceMap()),u&&p.end("Build Source Map"))}else if(P.kind==="incremental"){u&&p.start("Scan for candidates");let L=y.scanFiles(P.changedFiles);if(u&&p.end("Scan for candidates"),L.length<=0){let v=process.hrtime.bigint();e["--silent"]||T(`Done in ${O(v-E)}`);return}u&&p.start("Build CSS"),N=f.build(L),u&&p.end("Build CSS"),e["--map"]&&(u&&p.start("Build Source Map"),D=M(f.buildSourceMap()),u&&p.end("Build Source Map"))}await a(N,D,e,p);let ue=process.hrtime.bigint();e["--silent"]||T(`Done in ${O(ue-E)}`)}catch(d){var h=d,x=!0}finally{Q(g,h,x)}}catch(p){m=b,T(fe(p));let E=process.hrtime.bigint();e["--silent"]||T(`Done in ${O(E-r)}`)}})),e["--watch"]!=="always"&&process.stdin.on("end",()=>{Promise.all(R.map(_=>_())).then(()=>process.exit(0),()=>process.exit(1))}),process.stdin.resume());u&&t.start("Scan for candidates");let ae=y.scan();u&&t.end("Scan for candidates");u&&t.start("Build CSS");let V=await oe(()=>f.build(ae));u&&t.end("Build CSS");let q=null;e["--map"]&&(u&&t.start("Build Source Map"),q=await oe(()=>M(f.buildSourceMap())),u&&t.end("Build Source Map"));await a(V,q,e,t);let We=process.hrtime.bigint();e["--silent"]||T(`Done in ${O(We-r)}`);if(e["--watch"]&&i!==!1){let S=function(d){e["--silent"]||process.stderr.write("\r\x1B[2K"),T(d),e["--silent"]||process.stderr.write(`\r\x1B[2K${G("Polling for changes\u2026")}`)};var Pt=S;let _=()=>{};async function g(d){Ee(m),b=m.slice(),m=l?[l]:[];let h=e["--input"]?e["--input"]==="-"?await se():await j.readFile(e["--input"],"utf-8"):de` + @import 'tailwindcss'; + `;[f,y]=await w(h,d),b=m.slice(),u&&d.start("Scan for candidates");let x=y.scan();u&&d.end("Scan for candidates"),u&&d.start("Build CSS");let p=f.build(x);u&&d.end("Build CSS");let E=null;e["--map"]&&(u&&d.start("Build Source Map"),E=M(f.buildSourceMap()),u&&d.end("Build Source Map")),await a(p,E,e,d)}if(!e["--silent"]){let h=function(){d||(d=!0,process.stderr.write("\r\x1B[2K\x1B[?25h"),process.off("exit",h),process.off("SIGINT",x),process.off("SIGTERM",p))},x=function(){h(),process.exit(130)},p=function(){h(),process.exit(143)};var Nt=h,Lt=x,kt=p;let d=!1;process.stderr.write("\x1B[?25l"),process.on("exit",h),process.on("SIGINT",x),process.on("SIGTERM",p),_=h,R.push(async()=>_())}R.push(ut(async()=>{var N=[];try{let d=J(N,new pe);u&&d.start("Scan for candidates");let h=y.scan();u&&d.end("Scan for candidates");let x=y.scannedFiles.filter(v=>v!==e["--output"]&&v!==e["--map"]);if(x.length<=0)return;let p=process.hrtime.bigint();let E=ve(x,m);if(E.kind==="full"){try{await g(d)}catch(v){m=b,S(fe(v))}e["--silent"]||S(`Done in ${O(process.hrtime.bigint()-p)}`);return}if(h.length<=0){e["--silent"]||S(`Done in ${O(process.hrtime.bigint()-p)}`);return}u&&d.start("Build CSS");let B=f.build(h);u&&d.end("Build CSS");let P=null;e["--map"]&&(u&&d.start("Build Source Map"),P=M(f.buildSourceMap()),u&&d.end("Build Source Map"));await a(B,P,e,d);e["--silent"]||S(`Done in ${O(process.hrtime.bigint()-p)}`)}catch(D){var ue=D,L=!0}finally{Q(N,ue,L)}},i)),e["--watch"]!=="always"&&process.stdin.on("end",()=>{Promise.all(R.map(d=>d())).then(()=>process.exit(0),()=>process.exit(1))}),process.stdin.resume(),e["--silent"]||process.stderr.write(`\r\x1B[2K${G("Polling for changes\u2026")}`)}}catch(Ge){var Ke=Ge,Ye=!0}finally{Q(be,Ke,Ye)}}async function Ae(){try{return(await import("@parcel/watcher")).default}catch(e){throw new Error("Failed to load the file watcher. Your platform may not be supported by `@parcel/watcher`. As a workaround, you can use polling instead by passing the `--watch --poll` flags.",{cause:e})}}async function Re(e,t){let n=await Ae();e=e.sort((l,c)=>l.length-c.length);let i=[];for(let l=0;l!i.includes(l));let r=new I,s=new Set,o=new I;async function a(){await o.dispose(),o.queueMacrotask(()=>{t(Array.from(s)),s.clear()})}for(let l of e){let{unsubscribe:c}=await n.subscribe(l,async(m,b)=>{if(m){console.error(m);return}await Promise.all(b.map(async w=>{if(w.type==="delete"){s.add(w.path);return}let f=null;try{f=await j.lstat(w.path)}catch{}!f?.isFile()&&!f?.isSymbolicLink()||s.add(w.path)})),await a()});r.add(c)}return async()=>{await r.dispose(),await o.dispose()}}function ve(e,t){let n=[];for(let i of e){if(t.includes(i))return{kind:"full"};n.push({file:i,extension:C.extname(i).slice(1)})}return{kind:"incremental",changedFiles:n}}function ut(e,t){let n=!1,i=null;async function r(){if(!n)try{await e()}catch(s){console.error(s)}finally{n||(i=setTimeout(r,t))}}return i=setTimeout(r,t),async()=>{n=!0,i&&clearTimeout(i)}}async function Oe(e){let t=(await Promise.all(e.normalizedSources.map(async n=>{let i=C.resolve(n.base),r=await j.realpath(i).catch(()=>i);return j.stat(r).then(s=>s.isDirectory()?[r]:[]).catch(()=>[])}))).flat(1);return Array.from(new Set(t))}function G(e){return`\x1B[2m${e}\x1B[22m`}function ct(e){return`\x1B[31m${e}\x1B[39m`}import{__unstable__loadDesignSystem as Pe}from"@tailwindcss/node";import{Console as dt}from"console";import ft from"fs/promises";import Ne from"path";import{createInterface as mt}from"readline";function he(e,t){let n=e.length,i=t.length,r=n=48&&o<=57&&a>=48&&a<=57){let l=s,c=s+1,m=s,b=s+1;for(o=e.charCodeAt(c);o>=48&&o<=57;)o=e.charCodeAt(++c);for(a=t.charCodeAt(b);a>=48&&a<=57;)a=t.charCodeAt(++b);let w=e.slice(l,c),f=t.slice(m,b),y=Number(w)-Number(f);if(y)return y;if(wf)return 1;continue}if(o!==a)return o-a}return e.length-t.length}var le=new Uint8Array(256);function Be(e,t){let n=0,i=[],r=0,s=e.length,o=t.charCodeAt(0);for(let a=0;a0&&l===le[n-1]&&n--;break}}return i.push(e.slice(r)),i}import A from"picocolors";function K({render:e=!0,invalid:t,usage:n,options:i}){let r=process.stdout.columns??80,s=[],o=e?ie:(a="")=>{s.push(a)};if(o(te()),t&&(o(),o(`${A.dim("Invalid command:")} ${t}`)),n&&n.length>0){o(),o(A.dim("Usage:"));for(let[a,l]of n.entries()){let c=l.slice(0,l.indexOf("[")),m=l.slice(l.indexOf("["));m=m.replace(/\[.*?\]/g,f=>A.dim(f));let w=z(m,r-ee.indent-c.length-1);w.length>1&&a!==0&&o(),o(W(`${c}${w.shift()}`));for(let f of w)o(W(f,c.length))}}if(i){let a=0;for(let{alias:b}of Object.values(i))b&&(a=Math.max(a,b.length));let l=[],c=0;for(let[b,{alias:w,values:f}]of Object.entries(i)){f?.length&&(b+=`[=${f.join(", ")}]`);let y=[w&&`${w.padStart(a)}`,w?b:" ".repeat(a+2)+b].filter(Boolean).join(", ");l.push(y),c=Math.max(c,y.length)}o(),o(A.dim("Options:"));let m=8;for(let{description:b,default:w=null}of Object.values(i)){let f=l.shift(),y=m+(c-f.length),R=2,ae=r-f.length-y-R-ee.indent,V=z(w!==null?`${b} ${A.dim(`[default:\u202F${F(`${w}`)}]`)}`:b,ae);o(W(`${A.blue(f)} ${A.dim(A.gray("\xB7")).repeat(y)} ${V.shift()}`));for(let q of V)o(W(`${" ".repeat(f.length+y+R)}${q}`))}}if(!e)return s.join(` +`)}var ht=String.raw;function ge(){return"tailwindcss canonicalize [classes...]"}function gt(){return"tailwindcss canonicalize --css input.css [classes...]"}function wt(){return"tailwindcss canonicalize --stream [--css input.css]"}function Fe(){return{"--css":{type:"string",description:'CSS entry file used to load the Tailwind design system (defaults to `@import "tailwindcss";`)'},"--format":{type:"string",description:"Output format",default:"text",values:["text","json","jsonl"]},"--stream":{type:"boolean",description:"Read candidate groups from stdin line by line and write results to stdout",default:!1}}}var Me={"--help":{type:"boolean",description:"Display usage information",alias:"-h",default:!1}};async function je({argv:e=process.argv.slice(2),cwd:t=process.cwd(),stdin:n=null,stdinIsTTY:i=process.stdin.isTTY,stdoutIsTTY:r=process.stdout.isTTY}={}){try{let s=k({...Fe(),...Me},e),o=Tt(s["--format"]??"text");if(r&&e.length===0||s["--help"])return{exitCode:0,stdout:Ue()??"",stderr:""};if(s["--stream"])return await Le(()=>bt({css:s["--css"],cwd:t,format:o,input:process.stdin,output:process.stdout})),{exitCode:0,stdout:"",stderr:""};let a=s._.length>0?s._:await yt({stdin:n,stdinIsTTY:i});if(a.length===0)return _t("No candidate groups provided");let l=await Le(()=>Ct({css:s["--css"],cwd:t,inputs:a}));return{exitCode:0,stdout:xt(l,o),stderr:""}}catch(s){return{exitCode:1,stdout:"",stderr:s instanceof Error?s.message:String(s)}}}async function bt({css:e,cwd:t,format:n,input:i,output:r}){let s=await De(e,t),o=mt({input:i}),a=!0;n==="json"&&r.write("[");for await(let l of o){let c=Ie(s,l);switch(n){case"text":{r.write(c.output+` +`);break}case"jsonl":{r.write(JSON.stringify(c)+` +`);break}case"json":{a?r.write(` +`):r.write(`, +`),r.write(Rt(JSON.stringify(c,null,2),2)),a=!1;break}}}n==="json"&&r.write(a?"]":` +]`)}function yt({stdin:e,stdinIsTTY:t}){return e!==null?Promise.resolve(ke(e)):t?Promise.resolve([]):St().then(ke)}async function St(){return new Promise((e,t)=>{let n="";process.stdin.on("data",i=>{n+=i}),process.stdin.on("end",()=>e(n)),process.stdin.on("error",i=>t(i))})}async function Ct({css:e,cwd:t=process.cwd(),inputs:n}){let i=await De(e,t);return n.map(r=>Ie(i,r))}function xt(e,t){switch(t){case"json":return JSON.stringify(e,null,2);case"jsonl":return e.map(n=>JSON.stringify(n)).join(` +`);case"text":return e.map(n=>n.output).join(` +`)}}function Ue(){return K({render:!1,usage:[ge(),gt(),wt()],options:{...Fe(),...Me}})}async function De(e,t){if(e===null)return Pe(ht` + @import 'tailwindcss'; + `,{base:t});let n=Ne.resolve(t,e),i=await ft.readFile(n,"utf8");return Pe(i,{base:Ne.dirname(n)})}async function Le(e){let t=globalThis.console;globalThis.console=new dt({stdout:process.stderr,stderr:process.stderr});try{return await e()}finally{globalThis.console=t}}function ke(e){return e.split(/\r?\n/g).map(t=>t.trim()).filter(t=>t.length>0)}function Tt(e){if(e==="text"||e==="json"||e==="jsonl")return e;throw new Error(`Invalid value for --format: ${e}`)}function _t(e){return{exitCode:1,stdout:Ue()??"",stderr:e}}function $t(e){let t=e.trim();return t.length===0?[]:Be(t," ").map(n=>n.trim()).filter(n=>n.length>0)}function Et(e,t){let n=$t(t);return n=e.canonicalizeCandidates(n,{collapse:!0,logicalToPhysical:!0}),vt(e.getClassOrder(n)).join(" ")}function Ie(e,t){let n=Et(e,t);return{input:t,output:n,changed:n!==t}}function Rt(e,t){let n=" ".repeat(t);return e.split(` +`).map(i=>n+i).join(` +`)}function vt(e){return e.slice().sort(([t,n],[i,r])=>n===r?he(t,i):n===null?-1:r===null?1:Ot(n-r)||he(t,i)).map(([t])=>t)}function Ot(e){return e>0n?1:e===0n?0:-1}var Y={"--help":{type:"boolean",description:"Display usage information",alias:"-h"}};function we(e="tailwindcss"){return`${e} [--input input.css] [--output output.css] [--watch] [--poll=ms] [options\u2026]`}function ze({invalid:e}={}){K({invalid:e,usage:[we("tailwindcss"),we("tailwindcss build"),ge()],commands:{build:"Build your CSS",canonicalize:"Canonicalize candidate lists"},options:{...U(),...Y}})}async function Bt(){let e=process.argv.slice(2),t=e[0],n=k({...U(),...Y},e);if(t==="build"){let r=k({...U(),...Y},e.slice(1));(process.stdout.isTTY&&e.length===1||r["--help"])&&(K({usage:[we("tailwindcss build")],options:{...U(),...Y}}),process.exit(0)),await me(r);return}if(t==="canonicalize"){let r=await je({argv:e.slice(1)});r.stdout.length>0&&process.stdout.write(`${r.stdout} +`),r.stderr.length>0&&process.stderr.write(`${r.stderr} +`),process.exitCode=r.exitCode;return}(process.stdout.isTTY&&t===void 0||n["--help"])&&(ze(),process.exit(0)),t&&!t.startsWith("-")&&(ze({invalid:t}),process.exit(1));let i=k({...U(),...Y});await me(i)}await Bt(); diff --git a/dg-ui/node_modules/@tailwindcss/cli/package.json b/dg-ui/node_modules/@tailwindcss/cli/package.json new file mode 100644 index 0000000..785b094 --- /dev/null +++ b/dg-ui/node_modules/@tailwindcss/cli/package.json @@ -0,0 +1,40 @@ +{ + "name": "@tailwindcss/cli", + "version": "4.3.5", + "description": "A utility-first CSS framework for rapidly building custom user interfaces.", + "license": "MIT", + "repository": { + "type": "git", + "url": "https://github.com/tailwindlabs/tailwindcss.git", + "directory": "packages/@tailwindcss-cli" + }, + "bugs": "https://github.com/tailwindlabs/tailwindcss/issues", + "homepage": "https://tailwindcss.com", + "bin": { + "tailwindcss": "./dist/index.mjs" + }, + "exports": { + "./package.json": "./package.json" + }, + "files": [ + "dist" + ], + "publishConfig": { + "provenance": true, + "access": "public" + }, + "dependencies": { + "@parcel/watcher": "2.6.0", + "enhanced-resolve": "^5.24.5", + "mri": "^1.2.0", + "picocolors": "^1.1.1", + "@tailwindcss/node": "4.3.5", + "@tailwindcss/oxide": "4.3.5", + "tailwindcss": "4.3.5" + }, + "scripts": { + "lint": "tsc --noEmit", + "build": "tsup-node", + "dev": "pnpm run build -- --watch" + } +} \ No newline at end of file diff --git a/dg-ui/node_modules/@tailwindcss/node/LICENSE b/dg-ui/node_modules/@tailwindcss/node/LICENSE new file mode 100644 index 0000000..d6a8229 --- /dev/null +++ b/dg-ui/node_modules/@tailwindcss/node/LICENSE @@ -0,0 +1,21 @@ +MIT License + +Copyright (c) Tailwind Labs, Inc. + +Permission is hereby granted, free of charge, to any person obtaining a copy +of this software and associated documentation files (the "Software"), to deal +in the Software without restriction, including without limitation the rights +to use, copy, modify, merge, publish, distribute, sublicense, and/or sell +copies of the Software, and to permit persons to whom the Software is +furnished to do so, subject to the following conditions: + +The above copyright notice and this permission notice shall be included in all +copies or substantial portions of the Software. + +THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR +IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, +FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE +AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER +LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, +OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE +SOFTWARE. diff --git a/dg-ui/node_modules/@tailwindcss/node/README.md b/dg-ui/node_modules/@tailwindcss/node/README.md new file mode 100644 index 0000000..5f53260 --- /dev/null +++ b/dg-ui/node_modules/@tailwindcss/node/README.md @@ -0,0 +1,36 @@ +

+ + + + + Tailwind CSS + + +

+ +

+ A utility-first CSS framework for rapidly building custom user interfaces. +

+ +

+ Build Status + Total Downloads + Latest Release + License +

+ +--- + +## Documentation + +For full documentation, visit [tailwindcss.com](https://tailwindcss.com). + +## Community + +For help, discussion about best practices, or feature ideas: + +[Discuss Tailwind CSS on GitHub](https://github.com/tailwindlabs/tailwindcss/discussions) + +## Contributing + +If you're interested in contributing to Tailwind CSS, please read our [contributing docs](https://github.com/tailwindlabs/tailwindcss/blob/main/.github/CONTRIBUTING.md) **before submitting a pull request**. diff --git a/dg-ui/node_modules/@tailwindcss/node/dist/esm-cache.loader.d.mts b/dg-ui/node_modules/@tailwindcss/node/dist/esm-cache.loader.d.mts new file mode 100644 index 0000000..66006c6 --- /dev/null +++ b/dg-ui/node_modules/@tailwindcss/node/dist/esm-cache.loader.d.mts @@ -0,0 +1,6 @@ +import { ResolveHook, ResolveHookSync } from 'node:module'; + +declare let resolve: ResolveHook; +declare let resolveSync: ResolveHookSync; + +export { resolve, resolveSync }; diff --git a/dg-ui/node_modules/@tailwindcss/node/dist/esm-cache.loader.mjs b/dg-ui/node_modules/@tailwindcss/node/dist/esm-cache.loader.mjs new file mode 100644 index 0000000..e444dfe --- /dev/null +++ b/dg-ui/node_modules/@tailwindcss/node/dist/esm-cache.loader.mjs @@ -0,0 +1 @@ +import{isBuiltin as a}from"module";var u=async(r,e,o)=>{let t=await o(r,e);return l(e,t)},i=(r,e,o)=>{let t=o(r,e);return l(e,t)};function l(r,e){try{if(e.url===import.meta.url||a(e.url)||!r.parentURL)return e;let t=new URL(r.parentURL).searchParams.get("id");if(t===null)return e;let n=new URL(e.url);return n.searchParams.set("id",t),{...e,url:`${n}`}}catch{return e}}export{u as resolve,i as resolveSync}; diff --git a/dg-ui/node_modules/@tailwindcss/node/dist/index.d.mts b/dg-ui/node_modules/@tailwindcss/node/dist/index.d.mts new file mode 100644 index 0000000..2b71f9f --- /dev/null +++ b/dg-ui/node_modules/@tailwindcss/node/dist/index.d.mts @@ -0,0 +1,239 @@ +import * as tailwindcss from 'tailwindcss'; +import { Polyfills, __unstable__loadDesignSystem as __unstable__loadDesignSystem$1, Features } from 'tailwindcss'; +export { Features, Polyfills } from 'tailwindcss'; + +declare const DEBUG: boolean; + +declare const env_DEBUG: typeof DEBUG; +declare namespace env { + export { env_DEBUG as DEBUG }; +} + +/** + * The source code for one or more nodes in the AST + * + * This generally corresponds to a stylesheet + */ +interface Source { + /** + * The path to the file that contains the referenced source code + * + * If this references the *output* source code, this is `null`. + */ + file: string | null; + /** + * The referenced source code + */ + code: string; +} +/** + * The file and offsets within it that this node covers + * + * This can represent either: + * - A location in the original CSS which caused this node to be created + * - A location in the output CSS where this node resides + */ +type SourceLocation = [source: Source, start: number, end: number]; + +/** + * Line offset tables are the key to generating our source maps. They allow us + * to store indexes with our AST nodes and later convert them into positions as + * when given the source that the indexes refer to. + */ +/** + * A position in source code + * + * https://tc39.es/ecma426/#sec-position-record-type + */ +interface Position { + /** The line number, one-based */ + line: number; + /** The column/character number, one-based */ + column: number; +} + +interface OriginalPosition extends Position { + source: DecodedSource; +} +/** + * A "decoded" sourcemap + * + * @see https://tc39.es/ecma426/#decoded-source-map-record + */ +interface DecodedSourceMap { + file: string | null; + sources: DecodedSource[]; + mappings: DecodedMapping[]; +} +/** + * A "decoded" source + * + * @see https://tc39.es/ecma426/#decoded-source-record + */ +interface DecodedSource { + url: string | null; + content: string | null; + ignore: boolean; +} +/** + * A "decoded" mapping + * + * @see https://tc39.es/ecma426/#decoded-mapping-record + */ +interface DecodedMapping { + originalPosition: OriginalPosition | null; + generatedPosition: Position; + name: string | null; +} + +type StyleRule = { + kind: 'rule'; + selector: string; + nodes: AstNode[]; + src?: SourceLocation; + dst?: SourceLocation; +}; +type AtRule = { + kind: 'at-rule'; + name: string; + params: string; + nodes: AstNode[]; + src?: SourceLocation; + dst?: SourceLocation; +}; +type Declaration = { + kind: 'declaration'; + property: string; + value: string | undefined; + important: boolean; + src?: SourceLocation; + dst?: SourceLocation; +}; +type Comment = { + kind: 'comment'; + value: string; + src?: SourceLocation; + dst?: SourceLocation; +}; +type Context = { + kind: 'context'; + context: Record; + nodes: AstNode[]; + src?: undefined; + dst?: undefined; +}; +type AtRoot = { + kind: 'at-root'; + nodes: AstNode[]; + src?: undefined; + dst?: undefined; +}; +type AstNode = StyleRule | AtRule | Declaration | Comment | Context | AtRoot; + +type Resolver = (id: string, base: string) => Promise; +interface CompileOptions { + base: string; + from?: string; + onDependency: (path: string) => void; + shouldRewriteUrls?: boolean; + polyfills?: Polyfills; + customCssResolver?: Resolver; + customJsResolver?: Resolver; +} +declare function compileAst(ast: AstNode[], options: CompileOptions): Promise<{ + sources: { + base: string; + pattern: string; + negated: boolean; + }[]; + root: "none" | { + base: string; + pattern: string; + } | null; + features: Features; + build(candidates: string[]): AstNode[]; +}>; +declare function compile(css: string, options: CompileOptions): Promise<{ + sources: { + base: string; + pattern: string; + negated: boolean; + }[]; + root: "none" | { + base: string; + pattern: string; + } | null; + features: Features; + build(candidates: string[]): string; + buildSourceMap(): tailwindcss.DecodedSourceMap; +}>; +declare function __unstable__loadDesignSystem(css: string, { base }: { + base: string; +}): ReturnType; +declare function loadModule(id: string, base: string, onDependency: (path: string) => void, customJsResolver?: Resolver): Promise<{ + path: string; + base: string; + module: any; +}>; + +declare class Instrumentation implements Disposable { + #private; + private shouldReport; + private defaultFlush; + constructor(shouldReport?: boolean, defaultFlush?: (message: string) => undefined); + hit(label: string): void; + start(label: string): void; + end(label: string): void; + track(label: string): { + [Symbol.dispose]: () => void; + [Symbol.asyncDispose]: () => void; + }; + span(label: string, fn: () => T): T; + reset(): void; + report(flush?: (message: string) => undefined): void; + [Symbol.dispose](): void; +} + +declare function normalizePath(originalPath: string): string; + +interface OptimizeOptions { + /** + * The file being transformed + */ + file?: string; + /** + * Enabled minified output + */ + minify?: boolean; + /** + * The output source map before optimization + * + * If omitted a resulting source map will not be available + */ + map?: string; +} +interface TransformResult { + code: string; + map: string | undefined; +} +declare function optimize(input: string, { file, minify, map }?: OptimizeOptions): TransformResult; + +interface SourceMap { + readonly raw: string; + readonly inline: string; + comment(url: string): string; +} +declare function toSourceMap(map: DecodedSourceMap | string): SourceMap; + +/** + * Rewrites the URLs of each declaration in the AST from being relative to the + * folder `base` returns for it to being relative to `root`. Declarations for + * which `base` returns `null` are left as-is. + */ +declare function rewriteUrlsInAst({ ast, base, root, }: { + ast: AstNode[]; + base: (node: Declaration) => string | null; + root: string; +}): Promise; + +export { type CompileOptions, type DecodedSource, type DecodedSourceMap, Instrumentation, type OptimizeOptions, type Resolver, type SourceMap, type TransformResult, __unstable__loadDesignSystem, compile, compileAst, env, loadModule, normalizePath, optimize, rewriteUrlsInAst, toSourceMap }; diff --git a/dg-ui/node_modules/@tailwindcss/node/dist/index.d.ts b/dg-ui/node_modules/@tailwindcss/node/dist/index.d.ts new file mode 100644 index 0000000..2b71f9f --- /dev/null +++ b/dg-ui/node_modules/@tailwindcss/node/dist/index.d.ts @@ -0,0 +1,239 @@ +import * as tailwindcss from 'tailwindcss'; +import { Polyfills, __unstable__loadDesignSystem as __unstable__loadDesignSystem$1, Features } from 'tailwindcss'; +export { Features, Polyfills } from 'tailwindcss'; + +declare const DEBUG: boolean; + +declare const env_DEBUG: typeof DEBUG; +declare namespace env { + export { env_DEBUG as DEBUG }; +} + +/** + * The source code for one or more nodes in the AST + * + * This generally corresponds to a stylesheet + */ +interface Source { + /** + * The path to the file that contains the referenced source code + * + * If this references the *output* source code, this is `null`. + */ + file: string | null; + /** + * The referenced source code + */ + code: string; +} +/** + * The file and offsets within it that this node covers + * + * This can represent either: + * - A location in the original CSS which caused this node to be created + * - A location in the output CSS where this node resides + */ +type SourceLocation = [source: Source, start: number, end: number]; + +/** + * Line offset tables are the key to generating our source maps. They allow us + * to store indexes with our AST nodes and later convert them into positions as + * when given the source that the indexes refer to. + */ +/** + * A position in source code + * + * https://tc39.es/ecma426/#sec-position-record-type + */ +interface Position { + /** The line number, one-based */ + line: number; + /** The column/character number, one-based */ + column: number; +} + +interface OriginalPosition extends Position { + source: DecodedSource; +} +/** + * A "decoded" sourcemap + * + * @see https://tc39.es/ecma426/#decoded-source-map-record + */ +interface DecodedSourceMap { + file: string | null; + sources: DecodedSource[]; + mappings: DecodedMapping[]; +} +/** + * A "decoded" source + * + * @see https://tc39.es/ecma426/#decoded-source-record + */ +interface DecodedSource { + url: string | null; + content: string | null; + ignore: boolean; +} +/** + * A "decoded" mapping + * + * @see https://tc39.es/ecma426/#decoded-mapping-record + */ +interface DecodedMapping { + originalPosition: OriginalPosition | null; + generatedPosition: Position; + name: string | null; +} + +type StyleRule = { + kind: 'rule'; + selector: string; + nodes: AstNode[]; + src?: SourceLocation; + dst?: SourceLocation; +}; +type AtRule = { + kind: 'at-rule'; + name: string; + params: string; + nodes: AstNode[]; + src?: SourceLocation; + dst?: SourceLocation; +}; +type Declaration = { + kind: 'declaration'; + property: string; + value: string | undefined; + important: boolean; + src?: SourceLocation; + dst?: SourceLocation; +}; +type Comment = { + kind: 'comment'; + value: string; + src?: SourceLocation; + dst?: SourceLocation; +}; +type Context = { + kind: 'context'; + context: Record; + nodes: AstNode[]; + src?: undefined; + dst?: undefined; +}; +type AtRoot = { + kind: 'at-root'; + nodes: AstNode[]; + src?: undefined; + dst?: undefined; +}; +type AstNode = StyleRule | AtRule | Declaration | Comment | Context | AtRoot; + +type Resolver = (id: string, base: string) => Promise; +interface CompileOptions { + base: string; + from?: string; + onDependency: (path: string) => void; + shouldRewriteUrls?: boolean; + polyfills?: Polyfills; + customCssResolver?: Resolver; + customJsResolver?: Resolver; +} +declare function compileAst(ast: AstNode[], options: CompileOptions): Promise<{ + sources: { + base: string; + pattern: string; + negated: boolean; + }[]; + root: "none" | { + base: string; + pattern: string; + } | null; + features: Features; + build(candidates: string[]): AstNode[]; +}>; +declare function compile(css: string, options: CompileOptions): Promise<{ + sources: { + base: string; + pattern: string; + negated: boolean; + }[]; + root: "none" | { + base: string; + pattern: string; + } | null; + features: Features; + build(candidates: string[]): string; + buildSourceMap(): tailwindcss.DecodedSourceMap; +}>; +declare function __unstable__loadDesignSystem(css: string, { base }: { + base: string; +}): ReturnType; +declare function loadModule(id: string, base: string, onDependency: (path: string) => void, customJsResolver?: Resolver): Promise<{ + path: string; + base: string; + module: any; +}>; + +declare class Instrumentation implements Disposable { + #private; + private shouldReport; + private defaultFlush; + constructor(shouldReport?: boolean, defaultFlush?: (message: string) => undefined); + hit(label: string): void; + start(label: string): void; + end(label: string): void; + track(label: string): { + [Symbol.dispose]: () => void; + [Symbol.asyncDispose]: () => void; + }; + span(label: string, fn: () => T): T; + reset(): void; + report(flush?: (message: string) => undefined): void; + [Symbol.dispose](): void; +} + +declare function normalizePath(originalPath: string): string; + +interface OptimizeOptions { + /** + * The file being transformed + */ + file?: string; + /** + * Enabled minified output + */ + minify?: boolean; + /** + * The output source map before optimization + * + * If omitted a resulting source map will not be available + */ + map?: string; +} +interface TransformResult { + code: string; + map: string | undefined; +} +declare function optimize(input: string, { file, minify, map }?: OptimizeOptions): TransformResult; + +interface SourceMap { + readonly raw: string; + readonly inline: string; + comment(url: string): string; +} +declare function toSourceMap(map: DecodedSourceMap | string): SourceMap; + +/** + * Rewrites the URLs of each declaration in the AST from being relative to the + * folder `base` returns for it to being relative to `root`. Declarations for + * which `base` returns `null` are left as-is. + */ +declare function rewriteUrlsInAst({ ast, base, root, }: { + ast: AstNode[]; + base: (node: Declaration) => string | null; + root: string; +}): Promise; + +export { type CompileOptions, type DecodedSource, type DecodedSourceMap, Instrumentation, type OptimizeOptions, type Resolver, type SourceMap, type TransformResult, __unstable__loadDesignSystem, compile, compileAst, env, loadModule, normalizePath, optimize, rewriteUrlsInAst, toSourceMap }; diff --git a/dg-ui/node_modules/@tailwindcss/node/dist/index.js b/dg-ui/node_modules/@tailwindcss/node/dist/index.js new file mode 100644 index 0000000..bf6861c --- /dev/null +++ b/dg-ui/node_modules/@tailwindcss/node/dist/index.js @@ -0,0 +1,18 @@ +"use strict";var Yt=Object.create;var ce=Object.defineProperty;var Ht=Object.getOwnPropertyDescriptor;var Gt=Object.getOwnPropertyNames;var qt=Object.getPrototypeOf,Zt=Object.prototype.hasOwnProperty;var Ge=(e,r)=>{for(var t in r)ce(e,t,{get:r[t],enumerable:!0})},qe=(e,r,t,n)=>{if(r&&typeof r=="object"||typeof r=="function")for(let i of Gt(r))!Zt.call(e,i)&&i!==t&&ce(e,i,{get:()=>r[i],enumerable:!(n=Ht(r,i))||n.enumerable});return e};var V=(e,r,t)=>(t=e!=null?Yt(qt(e)):{},qe(r||!e||!e.__esModule?ce(t,"default",{value:e,enumerable:!0}):t,e)),Qt=e=>qe(ce({},"__esModule",{value:!0}),e);var En={};Ge(En,{Features:()=>_.Features,Instrumentation:()=>He,Polyfills:()=>_.Polyfills,__unstable__loadDesignSystem:()=>vn,compile:()=>hn,compileAst:()=>gn,env:()=>fe,loadModule:()=>Be,normalizePath:()=>ye,optimize:()=>An,rewriteUrlsInAst:()=>Me,toSourceMap:()=>$n});module.exports=Qt(En);var se=V(require("module")),Bt=require("url");var fe={};Ge(fe,{DEBUG:()=>Ce});var Ce=Jt(process.env.DEBUG);function Jt(e){if(typeof e=="boolean")return e;if(e===void 0)return!1;if(e==="true"||e==="1")return!0;if(e==="false"||e==="0")return!1;if(e==="*")return!0;let r=e.split(",").map(t=>t.split(":")[0]);return r.includes("-tailwindcss")?!1:!!r.includes("tailwindcss")}var Ze=require("module"),er={};var Qe=(e,r,t)=>{let n=t(e,r);return Xt(r,n)};function Xt(e,r){try{if(r.url===er.url||(0,Ze.isBuiltin)(r.url)||!e.parentURL)return r;let n=new URL(e.parentURL).searchParams.get("id");if(n===null)return r;let i=new URL(r.url);return i.searchParams.set("id",n),{...r,url:`${i}`}}catch{return r}}var B=V(require("enhanced-resolve")),Ut=require("jiti"),xe=V(require("fs")),We=V(require("fs/promises")),Z=V(require("path")),Fe=require("url"),_=require("tailwindcss");var pe=V(require("fs/promises")),Y=V(require("path")),tr=[/import[\s\S]*?['"](.{3,}?)['"]/gi,/import[\s\S]*from[\s\S]*?['"](.{3,}?)['"]/gi,/export[\s\S]*from[\s\S]*?['"](.{3,}?)['"]/gi,/require\(['"`](.+)['"`]\)/gi],rr=[".js",".cjs",".mjs"],nr=["",".js",".cjs",".mjs",".ts",".cts",".mts",".jsx",".tsx"],ir=["",".ts",".cts",".mts",".tsx",".js",".cjs",".mjs",".jsx"];async function or(e,r){for(let t of r){let n=`${e}${t}`;if((await pe.default.stat(n).catch(()=>null))?.isFile())return n}for(let t of r){let n=`${e}/index${t}`;if(await pe.default.access(n).then(()=>!0,()=>!1))return n}return null}async function Je(e,r,t,n){let i=rr.includes(n)?nr:ir,l=await or(Y.default.resolve(t,r),i);if(l===null||e.has(l))return;e.add(l),t=Y.default.dirname(l),n=Y.default.extname(l);let o=await pe.default.readFile(l,"utf-8"),s=[];for(let a of tr)for(let u of o.matchAll(a))u[1].startsWith(".")&&s.push(Je(e,u[1],t,n));await Promise.all(s)}async function Xe(e){let r=new Set;return await Je(r,e,Y.default.dirname(e),Y.default.extname(e)),Array.from(r)}var ze=V(require("path"));function z(e){return{kind:"word",value:e}}function lr(e,r){return{kind:"function",value:e,nodes:r}}function ar(e){return{kind:"separator",value:e}}function C(e){let r="";for(let t of e)switch(t.kind){case"word":case"separator":{r+=t.value;break}case"function":r+=t.value+"("+C(t.nodes)+")"}return r}var et=92,sr=41,tt=58,rt=44,ur=34,nt=61,it=62,ot=60,lt=10,cr=40,fr=39,pr=47,at=32,st=9;function b(e){e=e.replaceAll(`\r +`,` +`);let r=[],t=[],n=null,i="",l;for(let o=0;o0){let u=z(i);n?n.nodes.push(u):r.push(u),i=""}let a=z(e[o]);n?n.nodes.push(a):r.push(a);break}case tt:case rt:case nt:case it:case ot:case lt:case at:case st:{if(i.length>0){let f=z(i);n?n.nodes.push(f):r.push(f),i=""}let a=o,u=o+1;for(;u0){let u=z(i);a?.nodes.push(u),i=""}t.length>0?n=t[t.length-1]:n=null;break}default:i+=String.fromCharCode(s)}}return i.length>0&&r.push(z(i)),r}var h=class extends Map{constructor(t){super();this.factory=t}factory;get(t){let n=super.get(t);return n===void 0&&(n=this.factory(t,this),this.set(t,n)),n}};var Dn=new Uint8Array(256);var de=new Uint8Array(256);function w(e,r){let t=0,n=[],i=0,l=e.length,o=r.charCodeAt(0);for(let s=0;s0&&a===de[t-1]&&t--;break}}return n.push(e.slice(i)),n}var Se=(o=>(o[o.Continue=0]="Continue",o[o.Skip=1]="Skip",o[o.Stop=2]="Stop",o[o.Replace=3]="Replace",o[o.ReplaceSkip=4]="ReplaceSkip",o[o.ReplaceStop=5]="ReplaceStop",o))(Se||{}),v={Continue:{kind:0},Skip:{kind:1},Stop:{kind:2},Replace:e=>({kind:3,nodes:Array.isArray(e)?e:[e]}),ReplaceSkip:e=>({kind:4,nodes:Array.isArray(e)?e:[e]}),ReplaceStop:e=>({kind:5,nodes:Array.isArray(e)?e:[e]})};function g(e,r){typeof r=="function"?ut(e,r):ut(e,r.enter,r.exit)}function ut(e,r=()=>v.Continue,t=()=>v.Continue){let n={value:[e,0,null],prev:null},i={parent:null,depth:0,index:0,siblings:e,path(){let l=[],o=n;for(;o;){let s=o.value[2];s&&l.push(s),o=o.prev}return l.reverse(),l}};for(;n!==null;){let l=n.value,o=l[0],s=l[1],a=l[2];if(s>=o.length){n=n.prev,i.depth-=1;continue}if(i.parent=a,i.siblings=o,s>=0){i.index=s;let c=o[s],d=r(c,i)??v.Continue;switch(d.kind){case 0:{c.nodes&&c.nodes.length>0&&(i.depth+=1,n={value:[c.nodes,0,c],prev:n}),l[1]=~s;continue}case 2:return;case 1:{l[1]=~s;continue}case 3:{o.splice(s,1,...d.nodes);continue}case 5:{o.splice(s,1,...d.nodes);return}case 4:{o.splice(s,1,...d.nodes),l[1]+=d.nodes.length;continue}default:throw new Error(`Invalid \`WalkAction.${Se[d.kind]??`Unknown(${d.kind})`}\` in enter.`)}}let u=~s;i.index=u;let p=o[u],f=t(p,i)??v.Continue;switch(f.kind){case 0:l[1]=u+1;continue;case 2:return;case 3:{o.splice(u,1,...f.nodes),l[1]=u+f.nodes.length;continue}case 5:{o.splice(u,1,...f.nodes);return}case 4:{o.splice(u,1,...f.nodes),l[1]=u+f.nodes.length;continue}default:throw new Error(`Invalid \`WalkAction.${Se[f.kind]??`Unknown(${f.kind})`}\` in exit.`)}}}var Yn=new h(e=>{let r=b(e),t=new Set,n=new Set(["~",">","+","-","*","/"]);return g(r,(i,l)=>{if(i.kind==="word"&&n.has(i.value)){let o=l.index;if(o===-1)return;let s=l.siblings[o-1];if(s?.kind!=="separator"||s.value!==" ")return;let a=l.siblings[o+1];if(a?.kind!=="separator"||a.value!==" ")return;let u=l.siblings[o-2];if(u&&n.has(u.value))return;let p=l.siblings[o+2];if(p&&n.has(p.value))return;t.add(s),t.add(a)}else if(i.kind==="separator"&&i.value.length>0&&i.value.trim()==="")(l.siblings[0]===i||l.siblings[l.siblings.length-1]===i)&&t.add(i);else if(i.kind==="separator"&&i.value.trim()===",")i.value=",";else if(i.kind==="function"&&i.value.startsWith("--")){let o=l.index;if(o<=0)return;let s=l.siblings[o-1];if(s?.kind==="separator"&&s.value===",")return;let a=l.siblings[o-2];return a&&!n.has(a.value)?void 0:v.ReplaceSkip({kind:"function",value:"",nodes:[i]})}}),t.size>0&&g(r,i=>{if(t.has(i))return t.delete(i),v.ReplaceSkip([])}),$e(r),C(r)});var Hn=new h(e=>{let r=b(e);return r.length===3&&r[0].kind==="word"&&r[0].value==="&"&&r[1].kind==="separator"&&r[1].value===":"&&r[2].kind==="function"&&r[2].value==="is"?C(r[2].nodes):e});function $e(e){for(let r of e)switch(r.kind){case"function":{if(r.value==="url"||r.value.endsWith("_url")){r.value=X(r.value);break}if(r.value==="var"||r.value.endsWith("_var")||r.value==="theme"||r.value.endsWith("_theme")){r.value=X(r.value);for(let t=0;t{let r=b(e);return r.length===1&&r[0].kind==="function"&&r[0].value==="var"});function mr(e){throw new Error(`Unexpected value: ${e}`)}function X(e){return e.replaceAll("_",String.raw`\_`).replaceAll(" ","_")}var gr=/^(?[-+]?(?:\d*\.)?\d+)(?[a-z]+|%)?$/i,H=new h(e=>{let r=gr.exec(e);if(!r)return null;let t=r.groups?.value;if(t===void 0)return null;let n=Number(t);if(Number.isNaN(n))return null;let i=r.groups?.unit;return i===void 0?[n,null]:[n,i]});var D=/[+-]?\d*\.?\d+(?:[eE][+-]?\d+)?/,li=new RegExp(`^${D.source}$`);var ai=new RegExp(`^${D.source}%$`);var si=new RegExp(`^${D.source}\\s*/\\s*${D.source}$`);var hr=["cm","mm","Q","in","pc","pt","px","em","ex","ch","cap","ic","rem","rex","rch","rcap","ric","lh","rlh","vw","vh","vmin","vmax","vb","vi","svw","svh","svi","svb","svmin","svmax","lvw","lvh","lvi","lvb","lvmin","lvmax","dvw","dvh","dvi","dvb","dvmin","dvmax","cqw","cqh","cqi","cqb","cqmin","cqmax"],ui=new RegExp(`^${D.source}(${hr.join("|")})$`);var vr=["deg","rad","grad","turn"],ci=new RegExp(`^${D.source}(${vr.join("|")})$`);var fi=new RegExp(`^${D.source} +${D.source} +${D.source}$`);function S(e){let r=Number(e);return Number.isInteger(r)&&r>=0&&String(r)===String(e)}function ee(e,r){if(r===null)return e;let t=Number(r);return Number.isNaN(t)||(r=`${t*100}%`),r==="100%"?e:`color-mix(in oklab, ${e} ${r}, transparent)`}var br={"--alpha":yr,"--spacing":xr,"--theme":Ar,theme:Cr};function yr(e,r,t,...n){let[i,l]=w(t,"/").map(o=>o.trim());if(!i||!l)throw new Error(`The --alpha(\u2026) function requires a color and an alpha value, e.g.: \`--alpha(${i||"var(--my-color)"} / ${l||"50%"})\``);if(n.length>0)throw new Error(`The --alpha(\u2026) function only accepts one argument, e.g.: \`--alpha(${i||"var(--my-color)"} / ${l||"50%"})\``);return ee(i,l)}function xr(e,r,t,...n){if(!t)throw new Error("The --spacing(\u2026) function requires an argument, but received none.");if(n.length>0)throw new Error(`The --spacing(\u2026) function only accepts a single argument, but received ${n.length+1}.`);let i=e.theme.resolve(null,["--spacing"]);if(!i)throw new Error("The --spacing(\u2026) function requires that the `--spacing` theme variable exists, but it was not found.");let l=H.get(t);if(l){if(l[0]===0)return"0px";if(l[0]===1)return i}return`calc(${i} * ${t})`}function Ar(e,r,t,...n){if(!t.startsWith("--"))throw new Error("The --theme(\u2026) function can only be used with CSS variables from your theme.");let i=!1;t.endsWith(" inline")&&(i=!0,t=t.slice(0,-7)),r.kind==="at-rule"&&(i=!0);let l=e.resolveThemeValue(t,i);if(!l){if(n.length>0)return n.join(", ");throw new Error(`Could not resolve value for theme function: \`theme(${t})\`. Consider checking if the variable name is correct or provide a fallback value to silence this error.`)}if(n.length===0)return l;let o=n.join(", ");if(o==="initial")return l;if(l==="initial")return o;if(l.startsWith("var(")||l.startsWith("theme(")||l.startsWith("--theme(")){let s=b(l);return $r(s,o),C(s)}return l}function Cr(e,r,t,...n){t=Sr(t);let i=e.resolveThemeValue(t);if(!i&&n.length>0)return n.join(", ");if(!i)throw new Error(`Could not resolve value for theme function: \`theme(${t})\`. Consider checking if the path is correct or provide a fallback value to silence this error.`);return i}var Ui=new RegExp(Object.keys(br).map(e=>`${e}\\(`).join("|"));function Sr(e){if(e[0]!=="'"&&e[0]!=='"')return e;let r="",t=e[0];for(let n=1;n{if(t.kind==="function"&&!(t.value!=="var"&&t.value!=="theme"&&t.value!=="--theme"))if(t.nodes.length===1)t.nodes.push({kind:"word",value:`, ${r}`});else{let n=t.nodes[t.nodes.length-1];n.kind==="word"&&n.value==="initial"&&(n.value=r)}})}function M(e,r="top",t="right",n="bottom",i="left"){return mt(`${e}-${r}`,`${e}-${t}`,`${e}-${n}`,`${e}-${i}`)}function mt(e="top",r="right",t="bottom",n="left"){return{1:[[e,0],[r,0],[t,0],[n,0]],2:[[e,0],[r,1],[t,0],[n,1]],3:[[e,0],[r,1],[t,2],[n,1]],4:[[e,0],[r,1],[t,2],[n,3]]}}function $(e,r){return{1:[[e,0],[r,0]],2:[[e,0],[r,1]]}}var eo={inset:mt(),margin:M("margin"),padding:M("padding"),"scroll-margin":M("scroll-margin"),"scroll-padding":M("scroll-padding"),"border-width":M("border","top-width","right-width","bottom-width","left-width"),"border-style":M("border","top-style","right-style","bottom-style","left-style"),"border-color":M("border","top-color","right-color","bottom-color","left-color"),gap:$("row-gap","column-gap"),overflow:$("overflow-x","overflow-y"),"overscroll-behavior":$("overscroll-behavior-x","overscroll-behavior-y")},to={"inset-block":$("top","bottom"),"inset-inline":$("left","right"),"margin-block":$("margin-top","margin-bottom"),"margin-inline":$("margin-left","margin-right"),"padding-block":$("padding-top","padding-bottom"),"padding-inline":$("padding-left","padding-right"),"scroll-margin-block":$("scroll-margin-top","scroll-margin-bottom"),"scroll-margin-inline":$("scroll-margin-left","scroll-margin-right"),"scroll-padding-block":$("scroll-padding-top","scroll-padding-bottom"),"scroll-padding-inline":$("scroll-padding-left","scroll-padding-right")};var Vr=1536,Oo=Vr/16;var Yo=new h(e=>{let r=[];return g(b(e),t=>{if(!(t.kind!=="function"||t.value!=="var"))return g(t.nodes,n=>{n.kind!=="word"||n.value[0]!=="-"||n.value[1]!=="-"||r.push(n.value)}),v.Skip}),r});function Re(e){let r=[0];for(let i=0;i0;){let a=(o|0)>>1,u=l+a;r[u]<=i?(l=u+1,o=o-a-1):o=a}l-=1;let s=i-r[l];return{line:l+1,column:s}}function n({line:i,column:l}){i-=1,i=Math.min(Math.max(i,0),r.length-1);let o=r[i],s=r[i+1]??o;return Math.min(Math.max(o+l,0),s)}return{find:t,findOffset:n}}var we=92,ge=47,he=42,bt=34,yt=39,zr=58,ke=59,N=10,ie=13,G=32,q=9,xt=123,Pe=125,De=40,At=41,Kr=91,Mr=93,j=45,Oe=64,Ct=33,Fr=60,jr=62,P=class e extends Error{loc;constructor(r,t){if(t){let n=t[0],i=Re(n.code).find(t[1]);r=`${n.file}:${i.line}:${i.column+1}: ${r}`}super(r),this.name="CssSyntaxError",this.loc=t,Error.captureStackTrace&&Error.captureStackTrace(this,e)}};function le(e,r){let t=r?.from?{file:r.from,code:e}:null;e[0]==="\uFEFF"&&(e=" "+e.slice(1));let n=[],i=[],l=[],o=null,s=null,a="",u="",p=0,f;for(let c=0;c0&&e[x]===m[m.length-1]&&(m=m.slice(0,-1));f!==G&&f!==q&&f!==N&&f!==ie&&(ue=x+1-y)}a.length===0&&(a=e.slice(y),c=e.length);let Q=ve(a,k,ue);if(!Q)throw new P("Invalid custom property, expected a value",t?[t,y,c]:null);t&&(Q.src=[t,y,c],Q.dst=[t,y,c]),o?o.nodes.push(Q):n.push(Q),a=""}else if(d===ke&&a.charCodeAt(0)===Oe)s=oe(a),t&&(s.src=[t,p,c],s.dst=[t,p,c]),o?o.nodes.push(s):n.push(s),a="",s=null;else if(d===ke&&u[u.length-1]!==")"){let m=ve(a);if(!m){if(a.length===0)continue;throw new P(`Invalid declaration: \`${a.trim()}\``,t?[t,p,c]:null)}t&&(m.src=[t,p,c],m.dst=[t,p,c]),o?o.nodes.push(m):n.push(m),a=""}else if(d===xt&&u[u.length-1]!==")")u+="}",s=I(a.trim()),t&&(s.src=[t,p,c],s.dst=[t,p,c]),o&&o.nodes.push(s),l.push(o),o=s,a="",s=null;else if(d===Pe&&u[u.length-1]!==")"){if(u==="")throw new P("Missing opening {",t?[t,c,c]:null);if(u=u.slice(0,-1),a.length>0)if(a.charCodeAt(0)===Oe)s=oe(a),t&&(s.src=[t,p,c],s.dst=[t,p,c]),o?o.nodes.push(s):n.push(s),a="",s=null;else{let y=a.indexOf(":");if(o){let k=ve(a,y);if(!k)throw new P(`Invalid declaration: \`${a.trim()}\``,t?[t,p,c]:null);t&&(k.src=[t,p,c],k.dst=[t,p,c]),o.nodes.push(k)}}let m=l.pop()??null;m===null&&o&&n.push(o),o=m,a="",s=null}else if(d===De)u+=")",a+="(";else if(d===At){if(u[u.length-1]!==")")throw new P("Missing opening (",t?[t,c,c]:null);u=u.slice(0,-1),a+=")"}else{if(a.length===0&&(d===G||d===N||d===q))continue;a===""&&(p=c),a+=String.fromCharCode(d)}}}if(a.charCodeAt(0)===Oe){let c=oe(a);t&&(c.src=[t,p,e.length],c.dst=[t,p,e.length]),n.push(c)}else if(a.length>0&&u.length===0){let c=ve(a);c&&(t&&(c.src=[t,p,e.length],c.dst=[t,p,e.length]),o?o.nodes.push(c):n.push(c))}if(u.length>0&&o){if(o.kind==="rule")throw new P(`Missing closing } at ${o.selector}`,o.src?[o.src[0],o.src[1],o.src[1]]:null);if(o.kind==="at-rule")throw new P(`Missing closing } at ${o.name} ${o.params}`,o.src?[o.src[0],o.src[1],o.src[1]]:null)}return i.length>0?i.concat(n):n}function oe(e,r=[]){let t=e,n="";for(let i=5;i{if(S(e.value))return e.value}),A=W(e=>{if(S(e.value))return`${e.value}%`}),U=W(e=>{if(S(e.value))return`${e.value}px`}),Et=W(e=>{if(S(e.value))return`${e.value}ms`}),be=W(e=>{if(S(e.value))return`${e.value}deg`}),Gr=W(e=>{if(e.fraction===null)return;let[r,t]=w(e.fraction,"/");if(!(!S(r)||!S(t)))return e.fraction}),Tt=W(e=>{if(S(Number(e.value)))return`repeat(${e.value}, minmax(0, 1fr))`}),qr={accentColor:({theme:e})=>e("colors"),animation:{none:"none",spin:"spin 1s linear infinite",ping:"ping 1s cubic-bezier(0, 0, 0.2, 1) infinite",pulse:"pulse 2s cubic-bezier(0.4, 0, 0.6, 1) infinite",bounce:"bounce 1s infinite"},aria:{busy:'busy="true"',checked:'checked="true"',disabled:'disabled="true"',expanded:'expanded="true"',hidden:'hidden="true"',pressed:'pressed="true"',readonly:'readonly="true"',required:'required="true"',selected:'selected="true"'},aspectRatio:{auto:"auto",square:"1 / 1",video:"16 / 9",...Gr},backdropBlur:({theme:e})=>e("blur"),backdropBrightness:({theme:e})=>({...e("brightness"),...A}),backdropContrast:({theme:e})=>({...e("contrast"),...A}),backdropGrayscale:({theme:e})=>({...e("grayscale"),...A}),backdropHueRotate:({theme:e})=>({...e("hueRotate"),...be}),backdropInvert:({theme:e})=>({...e("invert"),...A}),backdropOpacity:({theme:e})=>({...e("opacity"),...A}),backdropSaturate:({theme:e})=>({...e("saturate"),...A}),backdropSepia:({theme:e})=>({...e("sepia"),...A}),backgroundColor:({theme:e})=>e("colors"),backgroundImage:{none:"none","gradient-to-t":"linear-gradient(to top, var(--tw-gradient-stops))","gradient-to-tr":"linear-gradient(to top right, var(--tw-gradient-stops))","gradient-to-r":"linear-gradient(to right, var(--tw-gradient-stops))","gradient-to-br":"linear-gradient(to bottom right, var(--tw-gradient-stops))","gradient-to-b":"linear-gradient(to bottom, var(--tw-gradient-stops))","gradient-to-bl":"linear-gradient(to bottom left, var(--tw-gradient-stops))","gradient-to-l":"linear-gradient(to left, var(--tw-gradient-stops))","gradient-to-tl":"linear-gradient(to top left, var(--tw-gradient-stops))"},backgroundOpacity:({theme:e})=>e("opacity"),backgroundPosition:{bottom:"bottom",center:"center",left:"left","left-bottom":"left bottom","left-top":"left top",right:"right","right-bottom":"right bottom","right-top":"right top",top:"top"},backgroundSize:{auto:"auto",cover:"cover",contain:"contain"},blur:{0:"0",none:"",sm:"4px",DEFAULT:"8px",md:"12px",lg:"16px",xl:"24px","2xl":"40px","3xl":"64px"},borderColor:({theme:e})=>({DEFAULT:"currentcolor",...e("colors")}),borderOpacity:({theme:e})=>e("opacity"),borderRadius:{none:"0px",sm:"0.125rem",DEFAULT:"0.25rem",md:"0.375rem",lg:"0.5rem",xl:"0.75rem","2xl":"1rem","3xl":"1.5rem",full:"9999px"},borderSpacing:({theme:e})=>e("spacing"),borderWidth:{DEFAULT:"1px",0:"0px",2:"2px",4:"4px",8:"8px",...U},boxShadow:{sm:"0 1px 2px 0 rgb(0 0 0 / 0.05)",DEFAULT:"0 1px 3px 0 rgb(0 0 0 / 0.1), 0 1px 2px -1px rgb(0 0 0 / 0.1)",md:"0 4px 6px -1px rgb(0 0 0 / 0.1), 0 2px 4px -2px rgb(0 0 0 / 0.1)",lg:"0 10px 15px -3px rgb(0 0 0 / 0.1), 0 4px 6px -4px rgb(0 0 0 / 0.1)",xl:"0 20px 25px -5px rgb(0 0 0 / 0.1), 0 8px 10px -6px rgb(0 0 0 / 0.1)","2xl":"0 25px 50px -12px rgb(0 0 0 / 0.25)",inner:"inset 0 2px 4px 0 rgb(0 0 0 / 0.05)",none:"none"},boxShadowColor:({theme:e})=>e("colors"),brightness:{0:"0",50:".5",75:".75",90:".9",95:".95",100:"1",105:"1.05",110:"1.1",125:"1.25",150:"1.5",200:"2",...A},caretColor:({theme:e})=>e("colors"),colors:()=>({...Le}),columns:{auto:"auto",1:"1",2:"2",3:"3",4:"4",5:"5",6:"6",7:"7",8:"8",9:"9",10:"10",11:"11",12:"12","3xs":"16rem","2xs":"18rem",xs:"20rem",sm:"24rem",md:"28rem",lg:"32rem",xl:"36rem","2xl":"42rem","3xl":"48rem","4xl":"56rem","5xl":"64rem","6xl":"72rem","7xl":"80rem",...O},container:{},content:{none:"none"},contrast:{0:"0",50:".5",75:".75",100:"1",125:"1.25",150:"1.5",200:"2",...A},cursor:{auto:"auto",default:"default",pointer:"pointer",wait:"wait",text:"text",move:"move",help:"help","not-allowed":"not-allowed",none:"none","context-menu":"context-menu",progress:"progress",cell:"cell",crosshair:"crosshair","vertical-text":"vertical-text",alias:"alias",copy:"copy","no-drop":"no-drop",grab:"grab",grabbing:"grabbing","all-scroll":"all-scroll","col-resize":"col-resize","row-resize":"row-resize","n-resize":"n-resize","e-resize":"e-resize","s-resize":"s-resize","w-resize":"w-resize","ne-resize":"ne-resize","nw-resize":"nw-resize","se-resize":"se-resize","sw-resize":"sw-resize","ew-resize":"ew-resize","ns-resize":"ns-resize","nesw-resize":"nesw-resize","nwse-resize":"nwse-resize","zoom-in":"zoom-in","zoom-out":"zoom-out"},divideColor:({theme:e})=>e("borderColor"),divideOpacity:({theme:e})=>e("borderOpacity"),divideWidth:({theme:e})=>({...e("borderWidth"),...U}),dropShadow:{sm:"0 1px 1px rgb(0 0 0 / 0.05)",DEFAULT:["0 1px 2px rgb(0 0 0 / 0.1)","0 1px 1px rgb(0 0 0 / 0.06)"],md:["0 4px 3px rgb(0 0 0 / 0.07)","0 2px 2px rgb(0 0 0 / 0.06)"],lg:["0 10px 8px rgb(0 0 0 / 0.04)","0 4px 3px rgb(0 0 0 / 0.1)"],xl:["0 20px 13px rgb(0 0 0 / 0.03)","0 8px 5px rgb(0 0 0 / 0.08)"],"2xl":"0 25px 25px rgb(0 0 0 / 0.15)",none:"0 0 #0000"},fill:({theme:e})=>e("colors"),flex:{1:"1 1 0%",auto:"1 1 auto",initial:"0 1 auto",none:"none"},flexBasis:({theme:e})=>({auto:"auto","1/2":"50%","1/3":"33.333333%","2/3":"66.666667%","1/4":"25%","2/4":"50%","3/4":"75%","1/5":"20%","2/5":"40%","3/5":"60%","4/5":"80%","1/6":"16.666667%","2/6":"33.333333%","3/6":"50%","4/6":"66.666667%","5/6":"83.333333%","1/12":"8.333333%","2/12":"16.666667%","3/12":"25%","4/12":"33.333333%","5/12":"41.666667%","6/12":"50%","7/12":"58.333333%","8/12":"66.666667%","9/12":"75%","10/12":"83.333333%","11/12":"91.666667%",full:"100%",...e("spacing")}),flexGrow:{0:"0",DEFAULT:"1",...O},flexShrink:{0:"0",DEFAULT:"1",...O},fontFamily:{sans:["-apple-system","BlinkMacSystemFont",'"Segoe UI"',"Roboto",'"Helvetica Neue"','"Noto Sans"',"Arial","sans-serif",'"Apple Color Emoji"','"Segoe UI Emoji"','"Segoe UI Symbol"','"Noto Color Emoji"'],serif:["ui-serif","Georgia","Cambria",'"Times New Roman"',"Times","serif"],mono:["ui-monospace","SFMono-Regular","Menlo","Monaco","Consolas",'"Liberation Mono"','"Courier New"',"monospace"]},fontSize:{xs:["0.75rem",{lineHeight:"1rem"}],sm:["0.875rem",{lineHeight:"1.25rem"}],base:["1rem",{lineHeight:"1.5rem"}],lg:["1.125rem",{lineHeight:"1.75rem"}],xl:["1.25rem",{lineHeight:"1.75rem"}],"2xl":["1.5rem",{lineHeight:"2rem"}],"3xl":["1.875rem",{lineHeight:"2.25rem"}],"4xl":["2.25rem",{lineHeight:"2.5rem"}],"5xl":["3rem",{lineHeight:"1"}],"6xl":["3.75rem",{lineHeight:"1"}],"7xl":["4.5rem",{lineHeight:"1"}],"8xl":["6rem",{lineHeight:"1"}],"9xl":["8rem",{lineHeight:"1"}]},fontWeight:{thin:"100",extralight:"200",light:"300",normal:"400",medium:"500",semibold:"600",bold:"700",extrabold:"800",black:"900"},gap:({theme:e})=>e("spacing"),gradientColorStops:({theme:e})=>e("colors"),gradientColorStopPositions:{"0%":"0%","5%":"5%","10%":"10%","15%":"15%","20%":"20%","25%":"25%","30%":"30%","35%":"35%","40%":"40%","45%":"45%","50%":"50%","55%":"55%","60%":"60%","65%":"65%","70%":"70%","75%":"75%","80%":"80%","85%":"85%","90%":"90%","95%":"95%","100%":"100%",...A},grayscale:{0:"0",DEFAULT:"100%",...A},gridAutoColumns:{auto:"auto",min:"min-content",max:"max-content",fr:"minmax(0, 1fr)"},gridAutoRows:{auto:"auto",min:"min-content",max:"max-content",fr:"minmax(0, 1fr)"},gridColumn:{auto:"auto","span-1":"span 1 / span 1","span-2":"span 2 / span 2","span-3":"span 3 / span 3","span-4":"span 4 / span 4","span-5":"span 5 / span 5","span-6":"span 6 / span 6","span-7":"span 7 / span 7","span-8":"span 8 / span 8","span-9":"span 9 / span 9","span-10":"span 10 / span 10","span-11":"span 11 / span 11","span-12":"span 12 / span 12","span-full":"1 / -1"},gridColumnEnd:{auto:"auto",1:"1",2:"2",3:"3",4:"4",5:"5",6:"6",7:"7",8:"8",9:"9",10:"10",11:"11",12:"12",13:"13",...O},gridColumnStart:{auto:"auto",1:"1",2:"2",3:"3",4:"4",5:"5",6:"6",7:"7",8:"8",9:"9",10:"10",11:"11",12:"12",13:"13",...O},gridRow:{auto:"auto","span-1":"span 1 / span 1","span-2":"span 2 / span 2","span-3":"span 3 / span 3","span-4":"span 4 / span 4","span-5":"span 5 / span 5","span-6":"span 6 / span 6","span-7":"span 7 / span 7","span-8":"span 8 / span 8","span-9":"span 9 / span 9","span-10":"span 10 / span 10","span-11":"span 11 / span 11","span-12":"span 12 / span 12","span-full":"1 / -1"},gridRowEnd:{auto:"auto",1:"1",2:"2",3:"3",4:"4",5:"5",6:"6",7:"7",8:"8",9:"9",10:"10",11:"11",12:"12",13:"13",...O},gridRowStart:{auto:"auto",1:"1",2:"2",3:"3",4:"4",5:"5",6:"6",7:"7",8:"8",9:"9",10:"10",11:"11",12:"12",13:"13",...O},gridTemplateColumns:{none:"none",subgrid:"subgrid",1:"repeat(1, minmax(0, 1fr))",2:"repeat(2, minmax(0, 1fr))",3:"repeat(3, minmax(0, 1fr))",4:"repeat(4, minmax(0, 1fr))",5:"repeat(5, minmax(0, 1fr))",6:"repeat(6, minmax(0, 1fr))",7:"repeat(7, minmax(0, 1fr))",8:"repeat(8, minmax(0, 1fr))",9:"repeat(9, minmax(0, 1fr))",10:"repeat(10, minmax(0, 1fr))",11:"repeat(11, minmax(0, 1fr))",12:"repeat(12, minmax(0, 1fr))",...Tt},gridTemplateRows:{none:"none",subgrid:"subgrid",1:"repeat(1, minmax(0, 1fr))",2:"repeat(2, minmax(0, 1fr))",3:"repeat(3, minmax(0, 1fr))",4:"repeat(4, minmax(0, 1fr))",5:"repeat(5, minmax(0, 1fr))",6:"repeat(6, minmax(0, 1fr))",7:"repeat(7, minmax(0, 1fr))",8:"repeat(8, minmax(0, 1fr))",9:"repeat(9, minmax(0, 1fr))",10:"repeat(10, minmax(0, 1fr))",11:"repeat(11, minmax(0, 1fr))",12:"repeat(12, minmax(0, 1fr))",...Tt},height:({theme:e})=>({auto:"auto","1/2":"50%","1/3":"33.333333%","2/3":"66.666667%","1/4":"25%","2/4":"50%","3/4":"75%","1/5":"20%","2/5":"40%","3/5":"60%","4/5":"80%","1/6":"16.666667%","2/6":"33.333333%","3/6":"50%","4/6":"66.666667%","5/6":"83.333333%",full:"100%",screen:"100vh",svh:"100svh",lvh:"100lvh",dvh:"100dvh",min:"min-content",max:"max-content",fit:"fit-content",...e("spacing")}),hueRotate:{0:"0deg",15:"15deg",30:"30deg",60:"60deg",90:"90deg",180:"180deg",...be},inset:({theme:e})=>({auto:"auto","1/2":"50%","1/3":"33.333333%","2/3":"66.666667%","1/4":"25%","2/4":"50%","3/4":"75%",full:"100%",...e("spacing")}),invert:{0:"0",DEFAULT:"100%",...A},keyframes:{spin:{to:{transform:"rotate(360deg)"}},ping:{"75%, 100%":{transform:"scale(2)",opacity:"0"}},pulse:{"50%":{opacity:".5"}},bounce:{"0%, 100%":{transform:"translateY(-25%)",animationTimingFunction:"cubic-bezier(0.8,0,1,1)"},"50%":{transform:"none",animationTimingFunction:"cubic-bezier(0,0,0.2,1)"}}},letterSpacing:{tighter:"-0.05em",tight:"-0.025em",normal:"0em",wide:"0.025em",wider:"0.05em",widest:"0.1em"},lineHeight:{none:"1",tight:"1.25",snug:"1.375",normal:"1.5",relaxed:"1.625",loose:"2",3:".75rem",4:"1rem",5:"1.25rem",6:"1.5rem",7:"1.75rem",8:"2rem",9:"2.25rem",10:"2.5rem"},listStyleType:{none:"none",disc:"disc",decimal:"decimal"},listStyleImage:{none:"none"},margin:({theme:e})=>({auto:"auto",...e("spacing")}),lineClamp:{1:"1",2:"2",3:"3",4:"4",5:"5",6:"6",...O},maxHeight:({theme:e})=>({none:"none",full:"100%",screen:"100vh",svh:"100svh",lvh:"100lvh",dvh:"100dvh",min:"min-content",max:"max-content",fit:"fit-content",...e("spacing")}),maxWidth:({theme:e})=>({none:"none",xs:"20rem",sm:"24rem",md:"28rem",lg:"32rem",xl:"36rem","2xl":"42rem","3xl":"48rem","4xl":"56rem","5xl":"64rem","6xl":"72rem","7xl":"80rem",full:"100%",min:"min-content",max:"max-content",fit:"fit-content",prose:"65ch",...e("spacing")}),minHeight:({theme:e})=>({full:"100%",screen:"100vh",svh:"100svh",lvh:"100lvh",dvh:"100dvh",min:"min-content",max:"max-content",fit:"fit-content",...e("spacing")}),minWidth:({theme:e})=>({full:"100%",min:"min-content",max:"max-content",fit:"fit-content",...e("spacing")}),objectPosition:{bottom:"bottom",center:"center",left:"left","left-bottom":"left bottom","left-top":"left top",right:"right","right-bottom":"right bottom","right-top":"right top",top:"top"},opacity:{0:"0",5:"0.05",10:"0.1",15:"0.15",20:"0.2",25:"0.25",30:"0.3",35:"0.35",40:"0.4",45:"0.45",50:"0.5",55:"0.55",60:"0.6",65:"0.65",70:"0.7",75:"0.75",80:"0.8",85:"0.85",90:"0.9",95:"0.95",100:"1",...A},order:{first:"-9999",last:"9999",none:"0",1:"1",2:"2",3:"3",4:"4",5:"5",6:"6",7:"7",8:"8",9:"9",10:"10",11:"11",12:"12",...O},outlineColor:({theme:e})=>e("colors"),outlineOffset:{0:"0px",1:"1px",2:"2px",4:"4px",8:"8px",...U},outlineWidth:{0:"0px",1:"1px",2:"2px",4:"4px",8:"8px",...U},padding:({theme:e})=>e("spacing"),placeholderColor:({theme:e})=>e("colors"),placeholderOpacity:({theme:e})=>e("opacity"),ringColor:({theme:e})=>({DEFAULT:"currentcolor",...e("colors")}),ringOffsetColor:({theme:e})=>e("colors"),ringOffsetWidth:{0:"0px",1:"1px",2:"2px",4:"4px",8:"8px",...U},ringOpacity:({theme:e})=>({DEFAULT:"0.5",...e("opacity")}),ringWidth:{DEFAULT:"3px",0:"0px",1:"1px",2:"2px",4:"4px",8:"8px",...U},rotate:{0:"0deg",1:"1deg",2:"2deg",3:"3deg",6:"6deg",12:"12deg",45:"45deg",90:"90deg",180:"180deg",...be},saturate:{0:"0",50:".5",100:"1",150:"1.5",200:"2",...A},scale:{0:"0",50:".5",75:".75",90:".9",95:".95",100:"1",105:"1.05",110:"1.1",125:"1.25",150:"1.5",...A},screens:{sm:"40rem",md:"48rem",lg:"64rem",xl:"80rem","2xl":"96rem"},scrollMargin:({theme:e})=>e("spacing"),scrollPadding:({theme:e})=>e("spacing"),sepia:{0:"0",DEFAULT:"100%",...A},skew:{0:"0deg",1:"1deg",2:"2deg",3:"3deg",6:"6deg",12:"12deg",...be},space:({theme:e})=>e("spacing"),spacing:{px:"1px",0:"0px",.5:"0.125rem",1:"0.25rem",1.5:"0.375rem",2:"0.5rem",2.5:"0.625rem",3:"0.75rem",3.5:"0.875rem",4:"1rem",5:"1.25rem",6:"1.5rem",7:"1.75rem",8:"2rem",9:"2.25rem",10:"2.5rem",11:"2.75rem",12:"3rem",14:"3.5rem",16:"4rem",20:"5rem",24:"6rem",28:"7rem",32:"8rem",36:"9rem",40:"10rem",44:"11rem",48:"12rem",52:"13rem",56:"14rem",60:"15rem",64:"16rem",72:"18rem",80:"20rem",96:"24rem"},stroke:({theme:e})=>({none:"none",...e("colors")}),strokeWidth:{0:"0",1:"1",2:"2",...O},supports:{},data:{},textColor:({theme:e})=>e("colors"),textDecorationColor:({theme:e})=>e("colors"),textDecorationThickness:{auto:"auto","from-font":"from-font",0:"0px",1:"1px",2:"2px",4:"4px",8:"8px",...U},textIndent:({theme:e})=>e("spacing"),textOpacity:({theme:e})=>e("opacity"),textUnderlineOffset:{auto:"auto",0:"0px",1:"1px",2:"2px",4:"4px",8:"8px",...U},transformOrigin:{center:"center",top:"top","top-right":"top right",right:"right","bottom-right":"bottom right",bottom:"bottom","bottom-left":"bottom left",left:"left","top-left":"top left"},transitionDelay:{0:"0s",75:"75ms",100:"100ms",150:"150ms",200:"200ms",300:"300ms",500:"500ms",700:"700ms",1e3:"1000ms",...Et},transitionDuration:{DEFAULT:"150ms",0:"0s",75:"75ms",100:"100ms",150:"150ms",200:"200ms",300:"300ms",500:"500ms",700:"700ms",1e3:"1000ms",...Et},transitionProperty:{none:"none",all:"all",DEFAULT:"color, background-color, border-color, outline-color, text-decoration-color, fill, stroke, opacity, box-shadow, transform, filter, backdrop-filter",colors:"color, background-color, border-color, outline-color, text-decoration-color, fill, stroke",opacity:"opacity",shadow:"box-shadow",transform:"transform"},transitionTimingFunction:{DEFAULT:"cubic-bezier(0.4, 0, 0.2, 1)",linear:"linear",in:"cubic-bezier(0.4, 0, 1, 1)",out:"cubic-bezier(0, 0, 0.2, 1)","in-out":"cubic-bezier(0.4, 0, 0.2, 1)"},translate:({theme:e})=>({"1/2":"50%","1/3":"33.333333%","2/3":"66.666667%","1/4":"25%","2/4":"50%","3/4":"75%",full:"100%",...e("spacing")}),size:({theme:e})=>({auto:"auto","1/2":"50%","1/3":"33.333333%","2/3":"66.666667%","1/4":"25%","2/4":"50%","3/4":"75%","1/5":"20%","2/5":"40%","3/5":"60%","4/5":"80%","1/6":"16.666667%","2/6":"33.333333%","3/6":"50%","4/6":"66.666667%","5/6":"83.333333%","1/12":"8.333333%","2/12":"16.666667%","3/12":"25%","4/12":"33.333333%","5/12":"41.666667%","6/12":"50%","7/12":"58.333333%","8/12":"66.666667%","9/12":"75%","10/12":"83.333333%","11/12":"91.666667%",full:"100%",min:"min-content",max:"max-content",fit:"fit-content",...e("spacing")}),width:({theme:e})=>({auto:"auto","1/2":"50%","1/3":"33.333333%","2/3":"66.666667%","1/4":"25%","2/4":"50%","3/4":"75%","1/5":"20%","2/5":"40%","3/5":"60%","4/5":"80%","1/6":"16.666667%","2/6":"33.333333%","3/6":"50%","4/6":"66.666667%","5/6":"83.333333%","1/12":"8.333333%","2/12":"16.666667%","3/12":"25%","4/12":"33.333333%","5/12":"41.666667%","6/12":"50%","7/12":"58.333333%","8/12":"66.666667%","9/12":"75%","10/12":"83.333333%","11/12":"91.666667%",full:"100%",screen:"100vw",svw:"100svw",lvw:"100lvw",dvw:"100dvw",min:"min-content",max:"max-content",fit:"fit-content",...e("spacing")}),willChange:{auto:"auto",scroll:"scroll-position",contents:"contents",transform:"transform"},zIndex:{auto:"auto",0:"0",10:"10",20:"20",30:"30",40:"40",50:"50",...O}};var Qr=64;function K(e,r=[]){return{kind:"rule",selector:e,nodes:r}}function T(e,r="",t=[]){return{kind:"at-rule",name:e,params:r,nodes:t}}function I(e,r=[]){return e.charCodeAt(0)===Qr?oe(e,r):K(e,r)}function R(e,r,t=!1){return{kind:"declaration",property:e,value:r,important:t}}function Ue(e){return{kind:"comment",value:e}}function F(e,r){let t=0,n={file:null,code:""};function i(o,s=0){let a="",u=" ".repeat(s);if(o.kind==="declaration"){if(a+=`${u}${o.property}: ${o.value}${o.important?" !important":""}; +`,r){t+=u.length;let p=t;t+=o.property.length,t+=2,t+=o.value?.length??0,o.important&&(t+=11);let f=t;t+=2,o.dst=[n,p,f]}}else if(o.kind==="rule"){if(a+=`${u}${o.selector} { +`,r){t+=u.length;let p=t;t+=o.selector.length,t+=1;let f=t;o.dst=[n,p,f],t+=2}for(let p of o.nodes)a+=i(p,s+1);a+=`${u}} +`,r&&(t+=u.length,t+=2)}else if(o.kind==="at-rule"){if(o.nodes.length===0){let p=`${u}${o.name} ${o.params}; +`;if(r){t+=u.length;let f=t;t+=o.name.length,t+=1,t+=o.params.length;let c=t;t+=2,o.dst=[n,f,c]}return p}if(a+=`${u}${o.name}${o.params?` ${o.params} `:" "}{ +`,r){t+=u.length;let p=t;t+=o.name.length,o.params&&(t+=1,t+=o.params.length),t+=1;let f=t;o.dst=[n,p,f],t+=2}for(let p of o.nodes)a+=i(p,s+1);a+=`${u}} +`,r&&(t+=u.length,t+=2)}else if(o.kind==="comment"){if(a+=`${u}/*${o.value}*/ +`,r){t+=u.length;let p=t;t+=2+o.value.length+2;let f=t;o.dst=[n,p,f],t+=1}}else if(o.kind==="context"||o.kind==="at-root")return"";return a}let l="";for(let o of e)l+=i(o,0);return n.code=l,l}function Jr(e,r){if(typeof e!="string")throw new TypeError("expected path to be a string");if(e==="\\"||e==="/")return"/";var t=e.length;if(t<=1)return e;var n="";if(t>4&&e[3]==="\\"){var i=e[2];(i==="?"||i===".")&&e.slice(0,2)==="\\\\"&&(e=e.slice(2),n="//")}var l=e.split(/[/\\]+/);return r!==!1&&l[l.length-1]===""&&l.pop(),n+l.join("/")}function ye(e){let r=Jr(e);return e.startsWith("\\\\")&&r.startsWith("/")&&!r.startsWith("//")?`/${r}`:r}var Ke=/(?[\w-]+\([^)]*\)|"[^"]*"|'[^']*'|[^,]\S*[^,])\s*(?:\s(?\w[^,]+))?(?:,|$)/g,on=/(?en.test(e),sn=e=>tn.test(e);async function Vt({css:e,base:r,root:t}){if(!e.includes("url(")&&!e.includes("image-set("))return e;let n=le(e);return await Me({ast:n,base:()=>r,root:t}),F(n)}async function Me({ast:e,base:r,root:t}){let n=[];g(e,i=>{if(i.kind!=="declaration"||!i.value)return;let l=Ke.test(i.value),o=Nt.test(i.value);if(l||o){let s=r(i);if(s===null)return;let a=o?cn:Rt;n.push(a(i.value,u=>un(u,s,t)).then(u=>{i.value=u}))}}),n.length&&await Promise.all(n)}function un(e,r,t){if(e[0]==="/")return e;let n=ze.posix.join(ye(r),e),i=ze.posix.relative(ye(t),n);return i.startsWith(".")||(i="./"+i),i}function Rt(e,r){return Ot(e,Ke,async t=>{let[n,i]=t;return await Pt(i.trim(),n,r)})}async function cn(e,r){return await Ot(e,Nt,async t=>{let[,n]=t;return await pn(n,async({url:l})=>Ke.test(l)?await Rt(l,r):Xr.test(l)?l:await Pt(l,l,r))})}async function Pt(e,r,t,n="url"){let i="",l=e[0];if((l==='"'||l==="'")&&(i=l,e=e.slice(1,-1)),fn(e))return r;let o=await t(e);return i===""&&o!==encodeURI(o)&&(i='"'),i==="'"&&o.includes("'")&&(i='"'),i==='"'&&o.includes('"')&&(o=o.replace(on,'\\"')),`${n}(${i}${o}${i})`}function fn(e,r){return sn(e)||an(e)||!e[0]||!e[0].match(/[.a-zA-Z0-9_]/)||rn.test(e)}function pn(e,r){return Promise.all(dn(e).map(async({url:t,descriptor:n})=>({url:await r({url:t,descriptor:n}),descriptor:n}))).then(mn)}function dn(e){let r=e.trim().replace(ln," ").replace(/\r?\n/,"").replace(/,\s+/,", ").replaceAll(/\s+/g," ").matchAll(nn);return Array.from(r,({groups:t})=>({url:t?.url?.trim()??"",descriptor:t?.descriptor?.trim()??""})).filter(({url:t})=>!!t)}function mn(e){return e.map(({url:r,descriptor:t})=>r+(t?` ${t}`:"")).join(", ")}async function Ot(e,r,t){let n,i=e,l="";for(;n=r.exec(i);)l+=i.slice(0,n.index),l+=await t(n),i=i.slice(n.index+n[0].length);return l+=i,l}var xn={};function Lt({base:e,from:r,polyfills:t,onDependency:n,shouldRewriteUrls:i,customCssResolver:l,customJsResolver:o}){return{base:e,polyfills:t,from:r,async loadModule(s,a){return Be(s,a,n,o)},async loadStylesheet(s,a){let u=await Kt(s,a,n,l);return i&&(u.content=await Vt({css:u.content,root:e,base:u.base})),u}}}async function zt(e){if(e.root&&e.root!=="none"){let r=/[*{]/,t=[];for(let i of e.root.pattern.split("/")){if(r.test(i))break;t.push(i)}if(!await We.default.stat(Z.default.resolve(e.root.base,t.join("/"))).then(i=>i.isDirectory()).catch(()=>!1))throw new Error(`The \`source(${e.root.pattern})\` does not exist or is not a directory.`)}}async function gn(e,r){let t=await(0,_.compileAst)(e,Lt(r));return await zt(t),t}async function hn(e,r){let t=await(0,_.compile)(e,Lt(r));return await zt(t),t}async function vn(e,{base:r}){return(0,_.__unstable__loadDesignSystem)(e,{base:r,async loadModule(t,n){return Be(t,n,()=>{})},async loadStylesheet(t,n){return Kt(t,n,()=>{})}})}async function Be(e,r,t,n){if(e[0]!=="."){let s=await It(e,r,n);if(!s)throw new Error(`Could not resolve '${e}' from '${r}'`);let a=await Dt((0,Fe.pathToFileURL)(s).href);return{path:s,base:Z.default.dirname(s),module:a.default??a}}let i=await It(e,r,n);if(!i)throw new Error(`Could not resolve '${e}' from '${r}'`);let[l,o]=await Promise.all([Dt((0,Fe.pathToFileURL)(i).href+"?id="+Date.now()),Xe(i)]);for(let s of o)t(s);return{path:i,base:Z.default.dirname(i),module:l.default??l}}async function Kt(e,r,t,n){let i=await wn(e,r,n);if(!i)throw new Error(`Could not resolve '${e}' from '${r}'`);t(i);let l=await We.default.readFile(i,"utf-8");return{path:i,base:Z.default.dirname(i),content:l}}var _t=null;async function Dt(e){if(typeof globalThis.__tw_load=="function"){let r=await globalThis.__tw_load(e);if(r)return r}try{return await import(e)}catch{return _t??=(0,Ut.createJiti)(xn.url,{moduleCache:!1,fsCache:!1}),await _t.import(e)}}var Ye=["node_modules",...process.env.NODE_PATH?[...process.env.NODE_PATH.split(Z.default.delimiter)]:[]],kn=B.default.ResolverFactory.createResolver({fileSystem:new B.default.CachedInputFileSystem(xe.default,4e3),useSyncFileSystemCalls:!0,extensions:[".css"],mainFields:["style"],conditionNames:["style"],modules:Ye});async function wn(e,r,t){if(typeof globalThis.__tw_resolve=="function"){let n=globalThis.__tw_resolve(e,r);if(n)return Promise.resolve(n)}if(t){let n=await t(e,r);if(n)return n}return je(kn,e,r)}var bn=B.default.ResolverFactory.createResolver({fileSystem:new B.default.CachedInputFileSystem(xe.default,4e3),useSyncFileSystemCalls:!0,extensions:[".js",".json",".node",".ts"],conditionNames:["node","import"],modules:Ye}),yn=B.default.ResolverFactory.createResolver({fileSystem:new B.default.CachedInputFileSystem(xe.default,4e3),useSyncFileSystemCalls:!0,extensions:[".js",".json",".node",".ts"],conditionNames:["node","require"],modules:Ye});async function It(e,r,t){if(typeof globalThis.__tw_resolve=="function"){let n=globalThis.__tw_resolve(e,r);if(n)return Promise.resolve(n)}if(t){let n=await t(e,r);if(n)return n}return je(bn,e,r).catch(()=>je(yn,e,r))}function je(e,r,t){return new Promise((n,i)=>e.resolve({},t,r,{},(l,o)=>{if(l)return i(l);n(o)}))}Symbol.dispose??=Symbol("Symbol.dispose");Symbol.asyncDispose??=Symbol("Symbol.asyncDispose");var He=class{constructor(r=Ce,t=n=>{process.stderr.write(`${n} +`)}){this.shouldReport=r;this.defaultFlush=t}shouldReport;defaultFlush;#r=new h(()=>({value:0}));#t=new h(()=>({value:0n}));#e=[];hit(r){this.#r.get(r).value++}start(r){let t=this.#e.map(i=>i.label).join("//"),n=`${t}${t.length===0?"":"//"}${r}`;this.#r.get(n).value++,this.#t.get(n),this.#e.push({id:n,label:r,namespace:t,value:process.hrtime.bigint()})}end(r){let t=process.hrtime.bigint();if(this.#e[this.#e.length-1].label!==r)throw new Error(`Mismatched timer label: \`${r}\`, expected \`${this.#e[this.#e.length-1].label}\``);let n=this.#e.pop(),i=t-n.value;this.#t.get(n.id).value+=i}track(r){this.start(r);let t=!1;return{[Symbol.dispose]:()=>{t||(this.end(r),t=!0)},[Symbol.asyncDispose]:()=>{t||(this.end(r),t=!0)}}}span(r,t){this.start(r);let n=!1;try{let i=t();return n=i&&typeof i.then=="function",n?i.finally(()=>this.end(r)):i}finally{n||this.end(r)}}reset(){this.#r.clear(),this.#t.clear(),this.#e.splice(0)}report(r=this.defaultFlush){let t=[],n=!1;for(let o=this.#e.length-1;o>=0;o--)this.end(this.#e[o].label);for(let[o,{value:s}]of this.#r.entries()){if(this.#t.has(o))continue;t.length===0&&(n=!0,t.push("Hits:"));let a=o.split("//").length;t.push(`${" ".repeat(a)}${o} ${Ae(Mt(`\xD7 ${s}`))}`)}this.#t.size>0&&n&&t.push(` +Timers:`);let i=-1/0,l=new Map;for(let[o,{value:s}]of this.#t){let a=`${(Number(s)/1e6).toFixed(2)}ms`;l.set(o,a),i=Math.max(i,a.length)}for(let o of this.#t.keys()){let s=o.split("//").length;t.push(`${Ae(`[${l.get(o).padStart(i," ")}]`)}${" ".repeat(s-1)}${s===1?" ":Ae(" \u21B3 ")}${o.split("//").pop()} ${this.#r.get(o).value===1?"":Ae(Mt(`\xD7 ${this.#r.get(o).value}`))}`.trimEnd())}r(` +${t.join(` +`)} +`),this.reset()}[Symbol.dispose](){this.shouldReport&&this.report()}};function Ae(e){return`\x1B[2m${e}\x1B[22m`}function Mt(e){return`\x1B[34m${e}\x1B[39m`}var Ft=V(require("@jridgewell/remapping")),L=require("lightningcss"),jt=V(require("magic-string"));function An(e,{file:r="input.css",minify:t=!1,map:n}={}){function i(a,u){return(0,L.transform)({filename:r,code:a,minify:t,sourceMap:typeof u<"u",inputSourceMap:u,drafts:{customMedia:!0},nonStandard:{deepSelectorCombinator:!0},include:L.Features.Nesting|L.Features.MediaQueries,exclude:L.Features.LogicalProperties|L.Features.DirSelector|L.Features.LightDark,targets:{safari:16<<16|1024,ios_saf:16<<16|1024,firefox:8388608,chrome:7274496},errorRecovery:!0})}let l=i(Buffer.from(e),n);if(n=l.map?.toString(),l.warnings=l.warnings.filter(a=>!/'(deep|slotted|global|ng-deep|host-context)' is not recognized as a valid pseudo-/.test(a.message)),l.warnings.length>0){let a=e.split(` +`),u=[`Found ${l.warnings.length} ${l.warnings.length===1?"warning":"warnings"} while optimizing generated CSS:`];for(let[p,f]of l.warnings.entries()){u.push(""),l.warnings.length>1&&u.push(`Issue #${p+1}:`);let c=2,d=Math.max(0,f.loc.line-c-1),m=Math.min(a.length,f.loc.line+c),y=a.slice(d,m).map((k,ue)=>d+ue+1===f.loc.line?`${ae("\u2502")} ${k}`:ae(`\u2502 ${k}`));y.splice(f.loc.line-d,0,`${ae("\u2506")}${" ".repeat(f.loc.column-1)} ${Cn(`${ae("^--")} ${f.message}`)}`,`${ae("\u2506")}`),u.push(...y)}u.push(""),console.warn(u.join(` +`))}l=i(l.code,n),n=l.map?.toString();let o=l.code.toString(),s=new jt.default(o);if(s.replaceAll("@media not (","@media not all and ("),n!==void 0&&s.hasChanged()){let a=s.generateMap({source:"original",hires:"boundary"}).toString();n=(0,Ft.default)([a,n],()=>null).toString()}return o=s.toString(),{code:o,map:n}}function ae(e){return`\x1B[2m${e}\x1B[22m`}function Cn(e){return`\x1B[33m${e}\x1B[39m`}var Wt=require("source-map-js");function Sn(e){let r=new Wt.SourceMapGenerator,t=1,n=new h(i=>({url:i?.url??``,content:i?.content??""}));for(let i of e.mappings){let l=n.get(i.originalPosition?.source??null);r.addMapping({generated:i.generatedPosition,original:i.originalPosition,source:l.url,name:i.name}),r.setSourceContent(l.url,l.content)}return r.toString()}function $n(e){let r=typeof e=="string"?e:Sn(e);function t(n){return`/*# sourceMappingURL=${n} */ +`}return{raw:r,get inline(){let n=Buffer.from(r,"utf-8").toString("base64");return t(`data:application/json;base64,${n}`)},comment:t}}process.versions.bun||(se.registerHooks?se.registerHooks({resolve:Qe}):se.register?.((0,Bt.pathToFileURL)(require.resolve("@tailwindcss/node/esm-cache-loader"))));0&&(module.exports={Features,Instrumentation,Polyfills,__unstable__loadDesignSystem,compile,compileAst,env,loadModule,normalizePath,optimize,rewriteUrlsInAst,toSourceMap}); diff --git a/dg-ui/node_modules/@tailwindcss/node/dist/index.mjs b/dg-ui/node_modules/@tailwindcss/node/dist/index.mjs new file mode 100644 index 0000000..a50b7c6 --- /dev/null +++ b/dg-ui/node_modules/@tailwindcss/node/dist/index.mjs @@ -0,0 +1,18 @@ +var Dt=Object.defineProperty;var It=(e,r)=>{for(var t in r)Dt(e,t,{get:r[t],enumerable:!0})};import*as F from"module";import{pathToFileURL as mn}from"url";var ke={};It(ke,{DEBUG:()=>ve});var ve=Ut(process.env.DEBUG);function Ut(e){if(typeof e=="boolean")return e;if(e===void 0)return!1;if(e==="true"||e==="1")return!0;if(e==="false"||e==="0")return!1;if(e==="*")return!0;let r=e.split(",").map(t=>t.split(":")[0]);return r.includes("-tailwindcss")?!1:!!r.includes("tailwindcss")}import{isBuiltin as Lt}from"module";var Ke=(e,r,t)=>{let n=t(e,r);return zt(r,n)};function zt(e,r){try{if(r.url===import.meta.url||Lt(r.url)||!e.parentURL)return r;let n=new URL(e.parentURL).searchParams.get("id");if(n===null)return r;let i=new URL(r.url);return i.searchParams.set("id",n),{...r,url:`${i}`}}catch{return r}}import Y from"enhanced-resolve";import{createJiti as Xr}from"jiti";import Le from"fs";import Tt from"fs/promises";import ie from"path";import{pathToFileURL as Ct}from"url";import{__unstable__loadDesignSystem as en,compile as tn,compileAst as rn,Features as mu,Polyfills as gu}from"tailwindcss";import we from"fs/promises";import q from"path";var Kt=[/import[\s\S]*?['"](.{3,}?)['"]/gi,/import[\s\S]*from[\s\S]*?['"](.{3,}?)['"]/gi,/export[\s\S]*from[\s\S]*?['"](.{3,}?)['"]/gi,/require\(['"`](.+)['"`]\)/gi],Mt=[".js",".cjs",".mjs"],Ft=["",".js",".cjs",".mjs",".ts",".cts",".mts",".jsx",".tsx"],jt=["",".ts",".cts",".mts",".tsx",".js",".cjs",".mjs",".jsx"];async function Wt(e,r){for(let t of r){let n=`${e}${t}`;if((await we.stat(n).catch(()=>null))?.isFile())return n}for(let t of r){let n=`${e}/index${t}`;if(await we.access(n).then(()=>!0,()=>!1))return n}return null}async function Me(e,r,t,n){let i=Mt.includes(n)?Ft:jt,l=await Wt(q.resolve(t,r),i);if(l===null||e.has(l))return;e.add(l),t=q.dirname(l),n=q.extname(l);let o=await we.readFile(l,"utf-8"),s=[];for(let a of Kt)for(let u of o.matchAll(a))u[1].startsWith(".")&&s.push(Me(e,u[1],t,n));await Promise.all(s)}async function Fe(e){let r=new Set;return await Me(r,e,q.dirname(e),q.extname(e)),Array.from(r)}import*as De from"path";function I(e){return{kind:"word",value:e}}function Bt(e,r){return{kind:"function",value:e,nodes:r}}function Yt(e){return{kind:"separator",value:e}}function C(e){let r="";for(let t of e)switch(t.kind){case"word":case"separator":{r+=t.value;break}case"function":r+=t.value+"("+C(t.nodes)+")"}return r}var je=92,Ht=41,We=58,Be=44,Gt=34,Ye=61,He=62,Ge=60,qe=10,qt=40,Zt=39,Qt=47,Ze=32,Qe=9;function b(e){e=e.replaceAll(`\r +`,` +`);let r=[],t=[],n=null,i="",l;for(let o=0;o0){let u=I(i);n?n.nodes.push(u):r.push(u),i=""}let a=I(e[o]);n?n.nodes.push(a):r.push(a);break}case We:case Be:case Ye:case He:case Ge:case qe:case Ze:case Qe:{if(i.length>0){let f=I(i);n?n.nodes.push(f):r.push(f),i=""}let a=o,u=o+1;for(;u0){let u=I(i);a?.nodes.push(u),i=""}t.length>0?n=t[t.length-1]:n=null;break}default:i+=String.fromCharCode(s)}}return i.length>0&&r.push(I(i)),r}var h=class extends Map{constructor(t){super();this.factory=t}factory;get(t){let n=super.get(t);return n===void 0&&(n=this.factory(t,this),this.set(t,n)),n}};var Sn=new Uint8Array(256);var se=new Uint8Array(256);function w(e,r){let t=0,n=[],i=0,l=e.length,o=r.charCodeAt(0);for(let s=0;s0&&a===se[t-1]&&t--;break}}return n.push(e.slice(i)),n}var be=(o=>(o[o.Continue=0]="Continue",o[o.Skip=1]="Skip",o[o.Stop=2]="Stop",o[o.Replace=3]="Replace",o[o.ReplaceSkip=4]="ReplaceSkip",o[o.ReplaceStop=5]="ReplaceStop",o))(be||{}),v={Continue:{kind:0},Skip:{kind:1},Stop:{kind:2},Replace:e=>({kind:3,nodes:Array.isArray(e)?e:[e]}),ReplaceSkip:e=>({kind:4,nodes:Array.isArray(e)?e:[e]}),ReplaceStop:e=>({kind:5,nodes:Array.isArray(e)?e:[e]})};function g(e,r){typeof r=="function"?Je(e,r):Je(e,r.enter,r.exit)}function Je(e,r=()=>v.Continue,t=()=>v.Continue){let n={value:[e,0,null],prev:null},i={parent:null,depth:0,index:0,siblings:e,path(){let l=[],o=n;for(;o;){let s=o.value[2];s&&l.push(s),o=o.prev}return l.reverse(),l}};for(;n!==null;){let l=n.value,o=l[0],s=l[1],a=l[2];if(s>=o.length){n=n.prev,i.depth-=1;continue}if(i.parent=a,i.siblings=o,s>=0){i.index=s;let c=o[s],d=r(c,i)??v.Continue;switch(d.kind){case 0:{c.nodes&&c.nodes.length>0&&(i.depth+=1,n={value:[c.nodes,0,c],prev:n}),l[1]=~s;continue}case 2:return;case 1:{l[1]=~s;continue}case 3:{o.splice(s,1,...d.nodes);continue}case 5:{o.splice(s,1,...d.nodes);return}case 4:{o.splice(s,1,...d.nodes),l[1]+=d.nodes.length;continue}default:throw new Error(`Invalid \`WalkAction.${be[d.kind]??`Unknown(${d.kind})`}\` in enter.`)}}let u=~s;i.index=u;let p=o[u],f=t(p,i)??v.Continue;switch(f.kind){case 0:l[1]=u+1;continue;case 2:return;case 3:{o.splice(u,1,...f.nodes),l[1]=u+f.nodes.length;continue}case 5:{o.splice(u,1,...f.nodes);return}case 4:{o.splice(u,1,...f.nodes),l[1]=u+f.nodes.length;continue}default:throw new Error(`Invalid \`WalkAction.${be[f.kind]??`Unknown(${f.kind})`}\` in exit.`)}}}var In=new h(e=>{let r=b(e),t=new Set,n=new Set(["~",">","+","-","*","/"]);return g(r,(i,l)=>{if(i.kind==="word"&&n.has(i.value)){let o=l.index;if(o===-1)return;let s=l.siblings[o-1];if(s?.kind!=="separator"||s.value!==" ")return;let a=l.siblings[o+1];if(a?.kind!=="separator"||a.value!==" ")return;let u=l.siblings[o-2];if(u&&n.has(u.value))return;let p=l.siblings[o+2];if(p&&n.has(p.value))return;t.add(s),t.add(a)}else if(i.kind==="separator"&&i.value.length>0&&i.value.trim()==="")(l.siblings[0]===i||l.siblings[l.siblings.length-1]===i)&&t.add(i);else if(i.kind==="separator"&&i.value.trim()===",")i.value=",";else if(i.kind==="function"&&i.value.startsWith("--")){let o=l.index;if(o<=0)return;let s=l.siblings[o-1];if(s?.kind==="separator"&&s.value===",")return;let a=l.siblings[o-2];return a&&!n.has(a.value)?void 0:v.ReplaceSkip({kind:"function",value:"",nodes:[i]})}}),t.size>0&&g(r,i=>{if(t.has(i))return t.delete(i),v.ReplaceSkip([])}),ye(r),C(r)});var Un=new h(e=>{let r=b(e);return r.length===3&&r[0].kind==="word"&&r[0].value==="&"&&r[1].kind==="separator"&&r[1].value===":"&&r[2].kind==="function"&&r[2].value==="is"?C(r[2].nodes):e});function ye(e){for(let r of e)switch(r.kind){case"function":{if(r.value==="url"||r.value.endsWith("_url")){r.value=Z(r.value);break}if(r.value==="var"||r.value.endsWith("_var")||r.value==="theme"||r.value.endsWith("_theme")){r.value=Z(r.value);for(let t=0;t{let r=b(e);return r.length===1&&r[0].kind==="function"&&r[0].value==="var"});function Xt(e){throw new Error(`Unexpected value: ${e}`)}function Z(e){return e.replaceAll("_",String.raw`\_`).replaceAll(" ","_")}var er=/^(?[-+]?(?:\d*\.)?\d+)(?[a-z]+|%)?$/i,j=new h(e=>{let r=er.exec(e);if(!r)return null;let t=r.groups?.value;if(t===void 0)return null;let n=Number(t);if(Number.isNaN(n))return null;let i=r.groups?.unit;return i===void 0?[n,null]:[n,i]});var O=/[+-]?\d*\.?\d+(?:[eE][+-]?\d+)?/,Zn=new RegExp(`^${O.source}$`);var Qn=new RegExp(`^${O.source}%$`);var Jn=new RegExp(`^${O.source}\\s*/\\s*${O.source}$`);var tr=["cm","mm","Q","in","pc","pt","px","em","ex","ch","cap","ic","rem","rex","rch","rcap","ric","lh","rlh","vw","vh","vmin","vmax","vb","vi","svw","svh","svi","svb","svmin","svmax","lvw","lvh","lvi","lvb","lvmin","lvmax","dvw","dvh","dvi","dvb","dvmin","dvmax","cqw","cqh","cqi","cqb","cqmin","cqmax"],Xn=new RegExp(`^${O.source}(${tr.join("|")})$`);var rr=["deg","rad","grad","turn"],ei=new RegExp(`^${O.source}(${rr.join("|")})$`);var ti=new RegExp(`^${O.source} +${O.source} +${O.source}$`);function S(e){let r=Number(e);return Number.isInteger(r)&&r>=0&&String(r)===String(e)}function Q(e,r){if(r===null)return e;let t=Number(r);return Number.isNaN(t)||(r=`${t*100}%`),r==="100%"?e:`color-mix(in oklab, ${e} ${r}, transparent)`}var or={"--alpha":lr,"--spacing":ar,"--theme":sr,theme:ur};function lr(e,r,t,...n){let[i,l]=w(t,"/").map(o=>o.trim());if(!i||!l)throw new Error(`The --alpha(\u2026) function requires a color and an alpha value, e.g.: \`--alpha(${i||"var(--my-color)"} / ${l||"50%"})\``);if(n.length>0)throw new Error(`The --alpha(\u2026) function only accepts one argument, e.g.: \`--alpha(${i||"var(--my-color)"} / ${l||"50%"})\``);return Q(i,l)}function ar(e,r,t,...n){if(!t)throw new Error("The --spacing(\u2026) function requires an argument, but received none.");if(n.length>0)throw new Error(`The --spacing(\u2026) function only accepts a single argument, but received ${n.length+1}.`);let i=e.theme.resolve(null,["--spacing"]);if(!i)throw new Error("The --spacing(\u2026) function requires that the `--spacing` theme variable exists, but it was not found.");let l=j.get(t);if(l){if(l[0]===0)return"0px";if(l[0]===1)return i}return`calc(${i} * ${t})`}function sr(e,r,t,...n){if(!t.startsWith("--"))throw new Error("The --theme(\u2026) function can only be used with CSS variables from your theme.");let i=!1;t.endsWith(" inline")&&(i=!0,t=t.slice(0,-7)),r.kind==="at-rule"&&(i=!0);let l=e.resolveThemeValue(t,i);if(!l){if(n.length>0)return n.join(", ");throw new Error(`Could not resolve value for theme function: \`theme(${t})\`. Consider checking if the variable name is correct or provide a fallback value to silence this error.`)}if(n.length===0)return l;let o=n.join(", ");if(o==="initial")return l;if(l==="initial")return o;if(l.startsWith("var(")||l.startsWith("theme(")||l.startsWith("--theme(")){let s=b(l);return fr(s,o),C(s)}return l}function ur(e,r,t,...n){t=cr(t);let i=e.resolveThemeValue(t);if(!i&&n.length>0)return n.join(", ");if(!i)throw new Error(`Could not resolve value for theme function: \`theme(${t})\`. Consider checking if the path is correct or provide a fallback value to silence this error.`);return i}var Ei=new RegExp(Object.keys(or).map(e=>`${e}\\(`).join("|"));function cr(e){if(e[0]!=="'"&&e[0]!=='"')return e;let r="",t=e[0];for(let n=1;n{if(t.kind==="function"&&!(t.value!=="var"&&t.value!=="theme"&&t.value!=="--theme"))if(t.nodes.length===1)t.nodes.push({kind:"word",value:`, ${r}`});else{let n=t.nodes[t.nodes.length-1];n.kind==="word"&&n.value==="initial"&&(n.value=r)}})}function L(e,r="top",t="right",n="bottom",i="left"){return nt(`${e}-${r}`,`${e}-${t}`,`${e}-${n}`,`${e}-${i}`)}function nt(e="top",r="right",t="bottom",n="left"){return{1:[[e,0],[r,0],[t,0],[n,0]],2:[[e,0],[r,1],[t,0],[n,1]],3:[[e,0],[r,1],[t,2],[n,1]],4:[[e,0],[r,1],[t,2],[n,3]]}}function $(e,r){return{1:[[e,0],[r,0]],2:[[e,0],[r,1]]}}var Wi={inset:nt(),margin:L("margin"),padding:L("padding"),"scroll-margin":L("scroll-margin"),"scroll-padding":L("scroll-padding"),"border-width":L("border","top-width","right-width","bottom-width","left-width"),"border-style":L("border","top-style","right-style","bottom-style","left-style"),"border-color":L("border","top-color","right-color","bottom-color","left-color"),gap:$("row-gap","column-gap"),overflow:$("overflow-x","overflow-y"),"overscroll-behavior":$("overscroll-behavior-x","overscroll-behavior-y")},Bi={"inset-block":$("top","bottom"),"inset-inline":$("left","right"),"margin-block":$("margin-top","margin-bottom"),"margin-inline":$("margin-left","margin-right"),"padding-block":$("padding-top","padding-bottom"),"padding-inline":$("padding-left","padding-right"),"scroll-margin-block":$("scroll-margin-top","scroll-margin-bottom"),"scroll-margin-inline":$("scroll-margin-left","scroll-margin-right"),"scroll-padding-block":$("scroll-padding-top","scroll-padding-bottom"),"scroll-padding-inline":$("scroll-padding-left","scroll-padding-right")};var gr=1536,Ao=gr/16;var Io=new h(e=>{let r=[];return g(b(e),t=>{if(!(t.kind!=="function"||t.value!=="var"))return g(t.nodes,n=>{n.kind!=="word"||n.value[0]!=="-"||n.value[1]!=="-"||r.push(n.value)}),v.Skip}),r});function $e(e){let r=[0];for(let i=0;i0;){let a=(o|0)>>1,u=l+a;r[u]<=i?(l=u+1,o=o-a-1):o=a}l-=1;let s=i-r[l];return{line:l+1,column:s}}function n({line:i,column:l}){i-=1,i=Math.min(Math.max(i,0),r.length-1);let o=r[i],s=r[i+1]??o;return Math.min(Math.max(o+l,0),s)}return{find:t,findOffset:n}}var me=92,ce=47,fe=42,ut=34,ct=39,Cr=58,de=59,N=10,te=13,W=32,B=9,ft=123,Ee=125,Ve=40,pt=41,Sr=91,$r=93,K=45,Te=64,dt=33,Er=60,Tr=62,R=class e extends Error{loc;constructor(r,t){if(t){let n=t[0],i=$e(n.code).find(t[1]);r=`${n.file}:${i.line}:${i.column+1}: ${r}`}super(r),this.name="CssSyntaxError",this.loc=t,Error.captureStackTrace&&Error.captureStackTrace(this,e)}};function ne(e,r){let t=r?.from?{file:r.from,code:e}:null;e[0]==="\uFEFF"&&(e=" "+e.slice(1));let n=[],i=[],l=[],o=null,s=null,a="",u="",p=0,f;for(let c=0;c0&&e[x]===m[m.length-1]&&(m=m.slice(0,-1));f!==W&&f!==B&&f!==N&&f!==te&&(ae=x+1-y)}a.length===0&&(a=e.slice(y),c=e.length);let H=pe(a,k,ae);if(!H)throw new R("Invalid custom property, expected a value",t?[t,y,c]:null);t&&(H.src=[t,y,c],H.dst=[t,y,c]),o?o.nodes.push(H):n.push(H),a=""}else if(d===de&&a.charCodeAt(0)===Te)s=re(a),t&&(s.src=[t,p,c],s.dst=[t,p,c]),o?o.nodes.push(s):n.push(s),a="",s=null;else if(d===de&&u[u.length-1]!==")"){let m=pe(a);if(!m){if(a.length===0)continue;throw new R(`Invalid declaration: \`${a.trim()}\``,t?[t,p,c]:null)}t&&(m.src=[t,p,c],m.dst=[t,p,c]),o?o.nodes.push(m):n.push(m),a=""}else if(d===ft&&u[u.length-1]!==")")u+="}",s=_(a.trim()),t&&(s.src=[t,p,c],s.dst=[t,p,c]),o&&o.nodes.push(s),l.push(o),o=s,a="",s=null;else if(d===Ee&&u[u.length-1]!==")"){if(u==="")throw new R("Missing opening {",t?[t,c,c]:null);if(u=u.slice(0,-1),a.length>0)if(a.charCodeAt(0)===Te)s=re(a),t&&(s.src=[t,p,c],s.dst=[t,p,c]),o?o.nodes.push(s):n.push(s),a="",s=null;else{let y=a.indexOf(":");if(o){let k=pe(a,y);if(!k)throw new R(`Invalid declaration: \`${a.trim()}\``,t?[t,p,c]:null);t&&(k.src=[t,p,c],k.dst=[t,p,c]),o.nodes.push(k)}}let m=l.pop()??null;m===null&&o&&n.push(o),o=m,a="",s=null}else if(d===Ve)u+=")",a+="(";else if(d===pt){if(u[u.length-1]!==")")throw new R("Missing opening (",t?[t,c,c]:null);u=u.slice(0,-1),a+=")"}else{if(a.length===0&&(d===W||d===N||d===B))continue;a===""&&(p=c),a+=String.fromCharCode(d)}}}if(a.charCodeAt(0)===Te){let c=re(a);t&&(c.src=[t,p,e.length],c.dst=[t,p,e.length]),n.push(c)}else if(a.length>0&&u.length===0){let c=pe(a);c&&(t&&(c.src=[t,p,e.length],c.dst=[t,p,e.length]),o?o.nodes.push(c):n.push(c))}if(u.length>0&&o){if(o.kind==="rule")throw new R(`Missing closing } at ${o.selector}`,o.src?[o.src[0],o.src[1],o.src[1]]:null);if(o.kind==="at-rule")throw new R(`Missing closing } at ${o.name} ${o.params}`,o.src?[o.src[0],o.src[1],o.src[1]]:null)}return i.length>0?i.concat(n):n}function re(e,r=[]){let t=e,n="";for(let i=5;i{if(S(e.value))return e.value}),A=M(e=>{if(S(e.value))return`${e.value}%`}),D=M(e=>{if(S(e.value))return`${e.value}px`}),ht=M(e=>{if(S(e.value))return`${e.value}ms`}),ge=M(e=>{if(S(e.value))return`${e.value}deg`}),Or=M(e=>{if(e.fraction===null)return;let[r,t]=w(e.fraction,"/");if(!(!S(r)||!S(t)))return e.fraction}),vt=M(e=>{if(S(Number(e.value)))return`repeat(${e.value}, minmax(0, 1fr))`}),_r={accentColor:({theme:e})=>e("colors"),animation:{none:"none",spin:"spin 1s linear infinite",ping:"ping 1s cubic-bezier(0, 0, 0.2, 1) infinite",pulse:"pulse 2s cubic-bezier(0.4, 0, 0.6, 1) infinite",bounce:"bounce 1s infinite"},aria:{busy:'busy="true"',checked:'checked="true"',disabled:'disabled="true"',expanded:'expanded="true"',hidden:'hidden="true"',pressed:'pressed="true"',readonly:'readonly="true"',required:'required="true"',selected:'selected="true"'},aspectRatio:{auto:"auto",square:"1 / 1",video:"16 / 9",...Or},backdropBlur:({theme:e})=>e("blur"),backdropBrightness:({theme:e})=>({...e("brightness"),...A}),backdropContrast:({theme:e})=>({...e("contrast"),...A}),backdropGrayscale:({theme:e})=>({...e("grayscale"),...A}),backdropHueRotate:({theme:e})=>({...e("hueRotate"),...ge}),backdropInvert:({theme:e})=>({...e("invert"),...A}),backdropOpacity:({theme:e})=>({...e("opacity"),...A}),backdropSaturate:({theme:e})=>({...e("saturate"),...A}),backdropSepia:({theme:e})=>({...e("sepia"),...A}),backgroundColor:({theme:e})=>e("colors"),backgroundImage:{none:"none","gradient-to-t":"linear-gradient(to top, var(--tw-gradient-stops))","gradient-to-tr":"linear-gradient(to top right, var(--tw-gradient-stops))","gradient-to-r":"linear-gradient(to right, var(--tw-gradient-stops))","gradient-to-br":"linear-gradient(to bottom right, var(--tw-gradient-stops))","gradient-to-b":"linear-gradient(to bottom, var(--tw-gradient-stops))","gradient-to-bl":"linear-gradient(to bottom left, var(--tw-gradient-stops))","gradient-to-l":"linear-gradient(to left, var(--tw-gradient-stops))","gradient-to-tl":"linear-gradient(to top left, var(--tw-gradient-stops))"},backgroundOpacity:({theme:e})=>e("opacity"),backgroundPosition:{bottom:"bottom",center:"center",left:"left","left-bottom":"left bottom","left-top":"left top",right:"right","right-bottom":"right bottom","right-top":"right top",top:"top"},backgroundSize:{auto:"auto",cover:"cover",contain:"contain"},blur:{0:"0",none:"",sm:"4px",DEFAULT:"8px",md:"12px",lg:"16px",xl:"24px","2xl":"40px","3xl":"64px"},borderColor:({theme:e})=>({DEFAULT:"currentcolor",...e("colors")}),borderOpacity:({theme:e})=>e("opacity"),borderRadius:{none:"0px",sm:"0.125rem",DEFAULT:"0.25rem",md:"0.375rem",lg:"0.5rem",xl:"0.75rem","2xl":"1rem","3xl":"1.5rem",full:"9999px"},borderSpacing:({theme:e})=>e("spacing"),borderWidth:{DEFAULT:"1px",0:"0px",2:"2px",4:"4px",8:"8px",...D},boxShadow:{sm:"0 1px 2px 0 rgb(0 0 0 / 0.05)",DEFAULT:"0 1px 3px 0 rgb(0 0 0 / 0.1), 0 1px 2px -1px rgb(0 0 0 / 0.1)",md:"0 4px 6px -1px rgb(0 0 0 / 0.1), 0 2px 4px -2px rgb(0 0 0 / 0.1)",lg:"0 10px 15px -3px rgb(0 0 0 / 0.1), 0 4px 6px -4px rgb(0 0 0 / 0.1)",xl:"0 20px 25px -5px rgb(0 0 0 / 0.1), 0 8px 10px -6px rgb(0 0 0 / 0.1)","2xl":"0 25px 50px -12px rgb(0 0 0 / 0.25)",inner:"inset 0 2px 4px 0 rgb(0 0 0 / 0.05)",none:"none"},boxShadowColor:({theme:e})=>e("colors"),brightness:{0:"0",50:".5",75:".75",90:".9",95:".95",100:"1",105:"1.05",110:"1.1",125:"1.25",150:"1.5",200:"2",...A},caretColor:({theme:e})=>e("colors"),colors:()=>({...Oe}),columns:{auto:"auto",1:"1",2:"2",3:"3",4:"4",5:"5",6:"6",7:"7",8:"8",9:"9",10:"10",11:"11",12:"12","3xs":"16rem","2xs":"18rem",xs:"20rem",sm:"24rem",md:"28rem",lg:"32rem",xl:"36rem","2xl":"42rem","3xl":"48rem","4xl":"56rem","5xl":"64rem","6xl":"72rem","7xl":"80rem",...P},container:{},content:{none:"none"},contrast:{0:"0",50:".5",75:".75",100:"1",125:"1.25",150:"1.5",200:"2",...A},cursor:{auto:"auto",default:"default",pointer:"pointer",wait:"wait",text:"text",move:"move",help:"help","not-allowed":"not-allowed",none:"none","context-menu":"context-menu",progress:"progress",cell:"cell",crosshair:"crosshair","vertical-text":"vertical-text",alias:"alias",copy:"copy","no-drop":"no-drop",grab:"grab",grabbing:"grabbing","all-scroll":"all-scroll","col-resize":"col-resize","row-resize":"row-resize","n-resize":"n-resize","e-resize":"e-resize","s-resize":"s-resize","w-resize":"w-resize","ne-resize":"ne-resize","nw-resize":"nw-resize","se-resize":"se-resize","sw-resize":"sw-resize","ew-resize":"ew-resize","ns-resize":"ns-resize","nesw-resize":"nesw-resize","nwse-resize":"nwse-resize","zoom-in":"zoom-in","zoom-out":"zoom-out"},divideColor:({theme:e})=>e("borderColor"),divideOpacity:({theme:e})=>e("borderOpacity"),divideWidth:({theme:e})=>({...e("borderWidth"),...D}),dropShadow:{sm:"0 1px 1px rgb(0 0 0 / 0.05)",DEFAULT:["0 1px 2px rgb(0 0 0 / 0.1)","0 1px 1px rgb(0 0 0 / 0.06)"],md:["0 4px 3px rgb(0 0 0 / 0.07)","0 2px 2px rgb(0 0 0 / 0.06)"],lg:["0 10px 8px rgb(0 0 0 / 0.04)","0 4px 3px rgb(0 0 0 / 0.1)"],xl:["0 20px 13px rgb(0 0 0 / 0.03)","0 8px 5px rgb(0 0 0 / 0.08)"],"2xl":"0 25px 25px rgb(0 0 0 / 0.15)",none:"0 0 #0000"},fill:({theme:e})=>e("colors"),flex:{1:"1 1 0%",auto:"1 1 auto",initial:"0 1 auto",none:"none"},flexBasis:({theme:e})=>({auto:"auto","1/2":"50%","1/3":"33.333333%","2/3":"66.666667%","1/4":"25%","2/4":"50%","3/4":"75%","1/5":"20%","2/5":"40%","3/5":"60%","4/5":"80%","1/6":"16.666667%","2/6":"33.333333%","3/6":"50%","4/6":"66.666667%","5/6":"83.333333%","1/12":"8.333333%","2/12":"16.666667%","3/12":"25%","4/12":"33.333333%","5/12":"41.666667%","6/12":"50%","7/12":"58.333333%","8/12":"66.666667%","9/12":"75%","10/12":"83.333333%","11/12":"91.666667%",full:"100%",...e("spacing")}),flexGrow:{0:"0",DEFAULT:"1",...P},flexShrink:{0:"0",DEFAULT:"1",...P},fontFamily:{sans:["-apple-system","BlinkMacSystemFont",'"Segoe UI"',"Roboto",'"Helvetica Neue"','"Noto Sans"',"Arial","sans-serif",'"Apple Color Emoji"','"Segoe UI Emoji"','"Segoe UI Symbol"','"Noto Color Emoji"'],serif:["ui-serif","Georgia","Cambria",'"Times New Roman"',"Times","serif"],mono:["ui-monospace","SFMono-Regular","Menlo","Monaco","Consolas",'"Liberation Mono"','"Courier New"',"monospace"]},fontSize:{xs:["0.75rem",{lineHeight:"1rem"}],sm:["0.875rem",{lineHeight:"1.25rem"}],base:["1rem",{lineHeight:"1.5rem"}],lg:["1.125rem",{lineHeight:"1.75rem"}],xl:["1.25rem",{lineHeight:"1.75rem"}],"2xl":["1.5rem",{lineHeight:"2rem"}],"3xl":["1.875rem",{lineHeight:"2.25rem"}],"4xl":["2.25rem",{lineHeight:"2.5rem"}],"5xl":["3rem",{lineHeight:"1"}],"6xl":["3.75rem",{lineHeight:"1"}],"7xl":["4.5rem",{lineHeight:"1"}],"8xl":["6rem",{lineHeight:"1"}],"9xl":["8rem",{lineHeight:"1"}]},fontWeight:{thin:"100",extralight:"200",light:"300",normal:"400",medium:"500",semibold:"600",bold:"700",extrabold:"800",black:"900"},gap:({theme:e})=>e("spacing"),gradientColorStops:({theme:e})=>e("colors"),gradientColorStopPositions:{"0%":"0%","5%":"5%","10%":"10%","15%":"15%","20%":"20%","25%":"25%","30%":"30%","35%":"35%","40%":"40%","45%":"45%","50%":"50%","55%":"55%","60%":"60%","65%":"65%","70%":"70%","75%":"75%","80%":"80%","85%":"85%","90%":"90%","95%":"95%","100%":"100%",...A},grayscale:{0:"0",DEFAULT:"100%",...A},gridAutoColumns:{auto:"auto",min:"min-content",max:"max-content",fr:"minmax(0, 1fr)"},gridAutoRows:{auto:"auto",min:"min-content",max:"max-content",fr:"minmax(0, 1fr)"},gridColumn:{auto:"auto","span-1":"span 1 / span 1","span-2":"span 2 / span 2","span-3":"span 3 / span 3","span-4":"span 4 / span 4","span-5":"span 5 / span 5","span-6":"span 6 / span 6","span-7":"span 7 / span 7","span-8":"span 8 / span 8","span-9":"span 9 / span 9","span-10":"span 10 / span 10","span-11":"span 11 / span 11","span-12":"span 12 / span 12","span-full":"1 / -1"},gridColumnEnd:{auto:"auto",1:"1",2:"2",3:"3",4:"4",5:"5",6:"6",7:"7",8:"8",9:"9",10:"10",11:"11",12:"12",13:"13",...P},gridColumnStart:{auto:"auto",1:"1",2:"2",3:"3",4:"4",5:"5",6:"6",7:"7",8:"8",9:"9",10:"10",11:"11",12:"12",13:"13",...P},gridRow:{auto:"auto","span-1":"span 1 / span 1","span-2":"span 2 / span 2","span-3":"span 3 / span 3","span-4":"span 4 / span 4","span-5":"span 5 / span 5","span-6":"span 6 / span 6","span-7":"span 7 / span 7","span-8":"span 8 / span 8","span-9":"span 9 / span 9","span-10":"span 10 / span 10","span-11":"span 11 / span 11","span-12":"span 12 / span 12","span-full":"1 / -1"},gridRowEnd:{auto:"auto",1:"1",2:"2",3:"3",4:"4",5:"5",6:"6",7:"7",8:"8",9:"9",10:"10",11:"11",12:"12",13:"13",...P},gridRowStart:{auto:"auto",1:"1",2:"2",3:"3",4:"4",5:"5",6:"6",7:"7",8:"8",9:"9",10:"10",11:"11",12:"12",13:"13",...P},gridTemplateColumns:{none:"none",subgrid:"subgrid",1:"repeat(1, minmax(0, 1fr))",2:"repeat(2, minmax(0, 1fr))",3:"repeat(3, minmax(0, 1fr))",4:"repeat(4, minmax(0, 1fr))",5:"repeat(5, minmax(0, 1fr))",6:"repeat(6, minmax(0, 1fr))",7:"repeat(7, minmax(0, 1fr))",8:"repeat(8, minmax(0, 1fr))",9:"repeat(9, minmax(0, 1fr))",10:"repeat(10, minmax(0, 1fr))",11:"repeat(11, minmax(0, 1fr))",12:"repeat(12, minmax(0, 1fr))",...vt},gridTemplateRows:{none:"none",subgrid:"subgrid",1:"repeat(1, minmax(0, 1fr))",2:"repeat(2, minmax(0, 1fr))",3:"repeat(3, minmax(0, 1fr))",4:"repeat(4, minmax(0, 1fr))",5:"repeat(5, minmax(0, 1fr))",6:"repeat(6, minmax(0, 1fr))",7:"repeat(7, minmax(0, 1fr))",8:"repeat(8, minmax(0, 1fr))",9:"repeat(9, minmax(0, 1fr))",10:"repeat(10, minmax(0, 1fr))",11:"repeat(11, minmax(0, 1fr))",12:"repeat(12, minmax(0, 1fr))",...vt},height:({theme:e})=>({auto:"auto","1/2":"50%","1/3":"33.333333%","2/3":"66.666667%","1/4":"25%","2/4":"50%","3/4":"75%","1/5":"20%","2/5":"40%","3/5":"60%","4/5":"80%","1/6":"16.666667%","2/6":"33.333333%","3/6":"50%","4/6":"66.666667%","5/6":"83.333333%",full:"100%",screen:"100vh",svh:"100svh",lvh:"100lvh",dvh:"100dvh",min:"min-content",max:"max-content",fit:"fit-content",...e("spacing")}),hueRotate:{0:"0deg",15:"15deg",30:"30deg",60:"60deg",90:"90deg",180:"180deg",...ge},inset:({theme:e})=>({auto:"auto","1/2":"50%","1/3":"33.333333%","2/3":"66.666667%","1/4":"25%","2/4":"50%","3/4":"75%",full:"100%",...e("spacing")}),invert:{0:"0",DEFAULT:"100%",...A},keyframes:{spin:{to:{transform:"rotate(360deg)"}},ping:{"75%, 100%":{transform:"scale(2)",opacity:"0"}},pulse:{"50%":{opacity:".5"}},bounce:{"0%, 100%":{transform:"translateY(-25%)",animationTimingFunction:"cubic-bezier(0.8,0,1,1)"},"50%":{transform:"none",animationTimingFunction:"cubic-bezier(0,0,0.2,1)"}}},letterSpacing:{tighter:"-0.05em",tight:"-0.025em",normal:"0em",wide:"0.025em",wider:"0.05em",widest:"0.1em"},lineHeight:{none:"1",tight:"1.25",snug:"1.375",normal:"1.5",relaxed:"1.625",loose:"2",3:".75rem",4:"1rem",5:"1.25rem",6:"1.5rem",7:"1.75rem",8:"2rem",9:"2.25rem",10:"2.5rem"},listStyleType:{none:"none",disc:"disc",decimal:"decimal"},listStyleImage:{none:"none"},margin:({theme:e})=>({auto:"auto",...e("spacing")}),lineClamp:{1:"1",2:"2",3:"3",4:"4",5:"5",6:"6",...P},maxHeight:({theme:e})=>({none:"none",full:"100%",screen:"100vh",svh:"100svh",lvh:"100lvh",dvh:"100dvh",min:"min-content",max:"max-content",fit:"fit-content",...e("spacing")}),maxWidth:({theme:e})=>({none:"none",xs:"20rem",sm:"24rem",md:"28rem",lg:"32rem",xl:"36rem","2xl":"42rem","3xl":"48rem","4xl":"56rem","5xl":"64rem","6xl":"72rem","7xl":"80rem",full:"100%",min:"min-content",max:"max-content",fit:"fit-content",prose:"65ch",...e("spacing")}),minHeight:({theme:e})=>({full:"100%",screen:"100vh",svh:"100svh",lvh:"100lvh",dvh:"100dvh",min:"min-content",max:"max-content",fit:"fit-content",...e("spacing")}),minWidth:({theme:e})=>({full:"100%",min:"min-content",max:"max-content",fit:"fit-content",...e("spacing")}),objectPosition:{bottom:"bottom",center:"center",left:"left","left-bottom":"left bottom","left-top":"left top",right:"right","right-bottom":"right bottom","right-top":"right top",top:"top"},opacity:{0:"0",5:"0.05",10:"0.1",15:"0.15",20:"0.2",25:"0.25",30:"0.3",35:"0.35",40:"0.4",45:"0.45",50:"0.5",55:"0.55",60:"0.6",65:"0.65",70:"0.7",75:"0.75",80:"0.8",85:"0.85",90:"0.9",95:"0.95",100:"1",...A},order:{first:"-9999",last:"9999",none:"0",1:"1",2:"2",3:"3",4:"4",5:"5",6:"6",7:"7",8:"8",9:"9",10:"10",11:"11",12:"12",...P},outlineColor:({theme:e})=>e("colors"),outlineOffset:{0:"0px",1:"1px",2:"2px",4:"4px",8:"8px",...D},outlineWidth:{0:"0px",1:"1px",2:"2px",4:"4px",8:"8px",...D},padding:({theme:e})=>e("spacing"),placeholderColor:({theme:e})=>e("colors"),placeholderOpacity:({theme:e})=>e("opacity"),ringColor:({theme:e})=>({DEFAULT:"currentcolor",...e("colors")}),ringOffsetColor:({theme:e})=>e("colors"),ringOffsetWidth:{0:"0px",1:"1px",2:"2px",4:"4px",8:"8px",...D},ringOpacity:({theme:e})=>({DEFAULT:"0.5",...e("opacity")}),ringWidth:{DEFAULT:"3px",0:"0px",1:"1px",2:"2px",4:"4px",8:"8px",...D},rotate:{0:"0deg",1:"1deg",2:"2deg",3:"3deg",6:"6deg",12:"12deg",45:"45deg",90:"90deg",180:"180deg",...ge},saturate:{0:"0",50:".5",100:"1",150:"1.5",200:"2",...A},scale:{0:"0",50:".5",75:".75",90:".9",95:".95",100:"1",105:"1.05",110:"1.1",125:"1.25",150:"1.5",...A},screens:{sm:"40rem",md:"48rem",lg:"64rem",xl:"80rem","2xl":"96rem"},scrollMargin:({theme:e})=>e("spacing"),scrollPadding:({theme:e})=>e("spacing"),sepia:{0:"0",DEFAULT:"100%",...A},skew:{0:"0deg",1:"1deg",2:"2deg",3:"3deg",6:"6deg",12:"12deg",...ge},space:({theme:e})=>e("spacing"),spacing:{px:"1px",0:"0px",.5:"0.125rem",1:"0.25rem",1.5:"0.375rem",2:"0.5rem",2.5:"0.625rem",3:"0.75rem",3.5:"0.875rem",4:"1rem",5:"1.25rem",6:"1.5rem",7:"1.75rem",8:"2rem",9:"2.25rem",10:"2.5rem",11:"2.75rem",12:"3rem",14:"3.5rem",16:"4rem",20:"5rem",24:"6rem",28:"7rem",32:"8rem",36:"9rem",40:"10rem",44:"11rem",48:"12rem",52:"13rem",56:"14rem",60:"15rem",64:"16rem",72:"18rem",80:"20rem",96:"24rem"},stroke:({theme:e})=>({none:"none",...e("colors")}),strokeWidth:{0:"0",1:"1",2:"2",...P},supports:{},data:{},textColor:({theme:e})=>e("colors"),textDecorationColor:({theme:e})=>e("colors"),textDecorationThickness:{auto:"auto","from-font":"from-font",0:"0px",1:"1px",2:"2px",4:"4px",8:"8px",...D},textIndent:({theme:e})=>e("spacing"),textOpacity:({theme:e})=>e("opacity"),textUnderlineOffset:{auto:"auto",0:"0px",1:"1px",2:"2px",4:"4px",8:"8px",...D},transformOrigin:{center:"center",top:"top","top-right":"top right",right:"right","bottom-right":"bottom right",bottom:"bottom","bottom-left":"bottom left",left:"left","top-left":"top left"},transitionDelay:{0:"0s",75:"75ms",100:"100ms",150:"150ms",200:"200ms",300:"300ms",500:"500ms",700:"700ms",1e3:"1000ms",...ht},transitionDuration:{DEFAULT:"150ms",0:"0s",75:"75ms",100:"100ms",150:"150ms",200:"200ms",300:"300ms",500:"500ms",700:"700ms",1e3:"1000ms",...ht},transitionProperty:{none:"none",all:"all",DEFAULT:"color, background-color, border-color, outline-color, text-decoration-color, fill, stroke, opacity, box-shadow, transform, filter, backdrop-filter",colors:"color, background-color, border-color, outline-color, text-decoration-color, fill, stroke",opacity:"opacity",shadow:"box-shadow",transform:"transform"},transitionTimingFunction:{DEFAULT:"cubic-bezier(0.4, 0, 0.2, 1)",linear:"linear",in:"cubic-bezier(0.4, 0, 1, 1)",out:"cubic-bezier(0, 0, 0.2, 1)","in-out":"cubic-bezier(0.4, 0, 0.2, 1)"},translate:({theme:e})=>({"1/2":"50%","1/3":"33.333333%","2/3":"66.666667%","1/4":"25%","2/4":"50%","3/4":"75%",full:"100%",...e("spacing")}),size:({theme:e})=>({auto:"auto","1/2":"50%","1/3":"33.333333%","2/3":"66.666667%","1/4":"25%","2/4":"50%","3/4":"75%","1/5":"20%","2/5":"40%","3/5":"60%","4/5":"80%","1/6":"16.666667%","2/6":"33.333333%","3/6":"50%","4/6":"66.666667%","5/6":"83.333333%","1/12":"8.333333%","2/12":"16.666667%","3/12":"25%","4/12":"33.333333%","5/12":"41.666667%","6/12":"50%","7/12":"58.333333%","8/12":"66.666667%","9/12":"75%","10/12":"83.333333%","11/12":"91.666667%",full:"100%",min:"min-content",max:"max-content",fit:"fit-content",...e("spacing")}),width:({theme:e})=>({auto:"auto","1/2":"50%","1/3":"33.333333%","2/3":"66.666667%","1/4":"25%","2/4":"50%","3/4":"75%","1/5":"20%","2/5":"40%","3/5":"60%","4/5":"80%","1/6":"16.666667%","2/6":"33.333333%","3/6":"50%","4/6":"66.666667%","5/6":"83.333333%","1/12":"8.333333%","2/12":"16.666667%","3/12":"25%","4/12":"33.333333%","5/12":"41.666667%","6/12":"50%","7/12":"58.333333%","8/12":"66.666667%","9/12":"75%","10/12":"83.333333%","11/12":"91.666667%",full:"100%",screen:"100vw",svw:"100svw",lvw:"100lvw",dvw:"100dvw",min:"min-content",max:"max-content",fit:"fit-content",...e("spacing")}),willChange:{auto:"auto",scroll:"scroll-position",contents:"contents",transform:"transform"},zIndex:{auto:"auto",0:"0",10:"10",20:"20",30:"30",40:"40",50:"50",...P}};var Ir=64;function U(e,r=[]){return{kind:"rule",selector:e,nodes:r}}function T(e,r="",t=[]){return{kind:"at-rule",name:e,params:r,nodes:t}}function _(e,r=[]){return e.charCodeAt(0)===Ir?re(e,r):U(e,r)}function V(e,r,t=!1){return{kind:"declaration",property:e,value:r,important:t}}function Pe(e){return{kind:"comment",value:e}}function z(e,r){let t=0,n={file:null,code:""};function i(o,s=0){let a="",u=" ".repeat(s);if(o.kind==="declaration"){if(a+=`${u}${o.property}: ${o.value}${o.important?" !important":""}; +`,r){t+=u.length;let p=t;t+=o.property.length,t+=2,t+=o.value?.length??0,o.important&&(t+=11);let f=t;t+=2,o.dst=[n,p,f]}}else if(o.kind==="rule"){if(a+=`${u}${o.selector} { +`,r){t+=u.length;let p=t;t+=o.selector.length,t+=1;let f=t;o.dst=[n,p,f],t+=2}for(let p of o.nodes)a+=i(p,s+1);a+=`${u}} +`,r&&(t+=u.length,t+=2)}else if(o.kind==="at-rule"){if(o.nodes.length===0){let p=`${u}${o.name} ${o.params}; +`;if(r){t+=u.length;let f=t;t+=o.name.length,t+=1,t+=o.params.length;let c=t;t+=2,o.dst=[n,f,c]}return p}if(a+=`${u}${o.name}${o.params?` ${o.params} `:" "}{ +`,r){t+=u.length;let p=t;t+=o.name.length,o.params&&(t+=1,t+=o.params.length),t+=1;let f=t;o.dst=[n,p,f],t+=2}for(let p of o.nodes)a+=i(p,s+1);a+=`${u}} +`,r&&(t+=u.length,t+=2)}else if(o.kind==="comment"){if(a+=`${u}/*${o.value}*/ +`,r){t+=u.length;let p=t;t+=2+o.value.length+2;let f=t;o.dst=[n,p,f],t+=1}}else if(o.kind==="context"||o.kind==="at-root")return"";return a}let l="";for(let o of e)l+=i(o,0);return n.code=l,l}function Ur(e,r){if(typeof e!="string")throw new TypeError("expected path to be a string");if(e==="\\"||e==="/")return"/";var t=e.length;if(t<=1)return e;var n="";if(t>4&&e[3]==="\\"){var i=e[2];(i==="?"||i===".")&&e.slice(0,2)==="\\\\"&&(e=e.slice(2),n="//")}var l=e.split(/[/\\]+/);return r!==!1&&l[l.length-1]===""&&l.pop(),n+l.join("/")}function _e(e){let r=Ur(e);return e.startsWith("\\\\")&&r.startsWith("/")&&!r.startsWith("//")?`/${r}`:r}var Ie=/(?[\w-]+\([^)]*\)|"[^"]*"|'[^']*'|[^,]\S*[^,])\s*(?:\s(?\w[^,]+))?(?:,|$)/g,jr=/(?zr.test(e),Yr=e=>Kr.test(e);async function wt({css:e,base:r,root:t}){if(!e.includes("url(")&&!e.includes("image-set("))return e;let n=ne(e);return await bt({ast:n,base:()=>r,root:t}),z(n)}async function bt({ast:e,base:r,root:t}){let n=[];g(e,i=>{if(i.kind!=="declaration"||!i.value)return;let l=Ie.test(i.value),o=kt.test(i.value);if(l||o){let s=r(i);if(s===null)return;let a=o?Gr:yt;n.push(a(i.value,u=>Hr(u,s,t)).then(u=>{i.value=u}))}}),n.length&&await Promise.all(n)}function Hr(e,r,t){if(e[0]==="/")return e;let n=De.posix.join(_e(r),e),i=De.posix.relative(_e(t),n);return i.startsWith(".")||(i="./"+i),i}function yt(e,r){return At(e,Ie,async t=>{let[n,i]=t;return await xt(i.trim(),n,r)})}async function Gr(e,r){return await At(e,kt,async t=>{let[,n]=t;return await Zr(n,async({url:l})=>Ie.test(l)?await yt(l,r):Lr.test(l)?l:await xt(l,l,r))})}async function xt(e,r,t,n="url"){let i="",l=e[0];if((l==='"'||l==="'")&&(i=l,e=e.slice(1,-1)),qr(e))return r;let o=await t(e);return i===""&&o!==encodeURI(o)&&(i='"'),i==="'"&&o.includes("'")&&(i='"'),i==='"'&&o.includes('"')&&(o=o.replace(jr,'\\"')),`${n}(${i}${o}${i})`}function qr(e,r){return Yr(e)||Br(e)||!e[0]||!e[0].match(/[.a-zA-Z0-9_]/)||Mr.test(e)}function Zr(e,r){return Promise.all(Qr(e).map(async({url:t,descriptor:n})=>({url:await r({url:t,descriptor:n}),descriptor:n}))).then(Jr)}function Qr(e){let r=e.trim().replace(Wr," ").replace(/\r?\n/,"").replace(/,\s+/,", ").replaceAll(/\s+/g," ").matchAll(Fr);return Array.from(r,({groups:t})=>({url:t?.url?.trim()??"",descriptor:t?.descriptor?.trim()??""})).filter(({url:t})=>!!t)}function Jr(e){return e.map(({url:r,descriptor:t})=>r+(t?` ${t}`:"")).join(", ")}async function At(e,r,t){let n,i=e,l="";for(;n=r.exec(i);)l+=i.slice(0,n.index),l+=await t(n),i=i.slice(n.index+n[0].length);return l+=i,l}function Nt({base:e,from:r,polyfills:t,onDependency:n,shouldRewriteUrls:i,customCssResolver:l,customJsResolver:o}){return{base:e,polyfills:t,from:r,async loadModule(s,a){return Rt(s,a,n,o)},async loadStylesheet(s,a){let u=await Pt(s,a,n,l);return i&&(u.content=await wt({css:u.content,root:e,base:u.base})),u}}}async function Vt(e){if(e.root&&e.root!=="none"){let r=/[*{]/,t=[];for(let i of e.root.pattern.split("/")){if(r.test(i))break;t.push(i)}if(!await Tt.stat(ie.resolve(e.root.base,t.join("/"))).then(i=>i.isDirectory()).catch(()=>!1))throw new Error(`The \`source(${e.root.pattern})\` does not exist or is not a directory.`)}}async function ku(e,r){let t=await rn(e,Nt(r));return await Vt(t),t}async function wu(e,r){let t=await tn(e,Nt(r));return await Vt(t),t}async function bu(e,{base:r}){return en(e,{base:r,async loadModule(t,n){return Rt(t,n,()=>{})},async loadStylesheet(t,n){return Pt(t,n,()=>{})}})}async function Rt(e,r,t,n){if(e[0]!=="."){let s=await Et(e,r,n);if(!s)throw new Error(`Could not resolve '${e}' from '${r}'`);let a=await $t(Ct(s).href);return{path:s,base:ie.dirname(s),module:a.default??a}}let i=await Et(e,r,n);if(!i)throw new Error(`Could not resolve '${e}' from '${r}'`);let[l,o]=await Promise.all([$t(Ct(i).href+"?id="+Date.now()),Fe(i)]);for(let s of o)t(s);return{path:i,base:ie.dirname(i),module:l.default??l}}async function Pt(e,r,t,n){let i=await on(e,r,n);if(!i)throw new Error(`Could not resolve '${e}' from '${r}'`);t(i);let l=await Tt.readFile(i,"utf-8");return{path:i,base:ie.dirname(i),content:l}}var St=null;async function $t(e){if(typeof globalThis.__tw_load=="function"){let r=await globalThis.__tw_load(e);if(r)return r}try{return await import(e)}catch{return St??=Xr(import.meta.url,{moduleCache:!1,fsCache:!1}),await St.import(e)}}var ze=["node_modules",...process.env.NODE_PATH?[...process.env.NODE_PATH.split(ie.delimiter)]:[]],nn=Y.ResolverFactory.createResolver({fileSystem:new Y.CachedInputFileSystem(Le,4e3),useSyncFileSystemCalls:!0,extensions:[".css"],mainFields:["style"],conditionNames:["style"],modules:ze});async function on(e,r,t){if(typeof globalThis.__tw_resolve=="function"){let n=globalThis.__tw_resolve(e,r);if(n)return Promise.resolve(n)}if(t){let n=await t(e,r);if(n)return n}return Ue(nn,e,r)}var ln=Y.ResolverFactory.createResolver({fileSystem:new Y.CachedInputFileSystem(Le,4e3),useSyncFileSystemCalls:!0,extensions:[".js",".json",".node",".ts"],conditionNames:["node","import"],modules:ze}),an=Y.ResolverFactory.createResolver({fileSystem:new Y.CachedInputFileSystem(Le,4e3),useSyncFileSystemCalls:!0,extensions:[".js",".json",".node",".ts"],conditionNames:["node","require"],modules:ze});async function Et(e,r,t){if(typeof globalThis.__tw_resolve=="function"){let n=globalThis.__tw_resolve(e,r);if(n)return Promise.resolve(n)}if(t){let n=await t(e,r);if(n)return n}return Ue(ln,e,r).catch(()=>Ue(an,e,r))}function Ue(e,r,t){return new Promise((n,i)=>e.resolve({},t,r,{},(l,o)=>{if(l)return i(l);n(o)}))}Symbol.dispose??=Symbol("Symbol.dispose");Symbol.asyncDispose??=Symbol("Symbol.asyncDispose");var Ot=class{constructor(r=ve,t=n=>{process.stderr.write(`${n} +`)}){this.shouldReport=r;this.defaultFlush=t}shouldReport;defaultFlush;#r=new h(()=>({value:0}));#t=new h(()=>({value:0n}));#e=[];hit(r){this.#r.get(r).value++}start(r){let t=this.#e.map(i=>i.label).join("//"),n=`${t}${t.length===0?"":"//"}${r}`;this.#r.get(n).value++,this.#t.get(n),this.#e.push({id:n,label:r,namespace:t,value:process.hrtime.bigint()})}end(r){let t=process.hrtime.bigint();if(this.#e[this.#e.length-1].label!==r)throw new Error(`Mismatched timer label: \`${r}\`, expected \`${this.#e[this.#e.length-1].label}\``);let n=this.#e.pop(),i=t-n.value;this.#t.get(n.id).value+=i}track(r){this.start(r);let t=!1;return{[Symbol.dispose]:()=>{t||(this.end(r),t=!0)},[Symbol.asyncDispose]:()=>{t||(this.end(r),t=!0)}}}span(r,t){this.start(r);let n=!1;try{let i=t();return n=i&&typeof i.then=="function",n?i.finally(()=>this.end(r)):i}finally{n||this.end(r)}}reset(){this.#r.clear(),this.#t.clear(),this.#e.splice(0)}report(r=this.defaultFlush){let t=[],n=!1;for(let o=this.#e.length-1;o>=0;o--)this.end(this.#e[o].label);for(let[o,{value:s}]of this.#r.entries()){if(this.#t.has(o))continue;t.length===0&&(n=!0,t.push("Hits:"));let a=o.split("//").length;t.push(`${" ".repeat(a)}${o} ${he(_t(`\xD7 ${s}`))}`)}this.#t.size>0&&n&&t.push(` +Timers:`);let i=-1/0,l=new Map;for(let[o,{value:s}]of this.#t){let a=`${(Number(s)/1e6).toFixed(2)}ms`;l.set(o,a),i=Math.max(i,a.length)}for(let o of this.#t.keys()){let s=o.split("//").length;t.push(`${he(`[${l.get(o).padStart(i," ")}]`)}${" ".repeat(s-1)}${s===1?" ":he(" \u21B3 ")}${o.split("//").pop()} ${this.#r.get(o).value===1?"":he(_t(`\xD7 ${this.#r.get(o).value}`))}`.trimEnd())}r(` +${t.join(` +`)} +`),this.reset()}[Symbol.dispose](){this.shouldReport&&this.report()}};function he(e){return`\x1B[2m${e}\x1B[22m`}function _t(e){return`\x1B[34m${e}\x1B[39m`}import sn from"@jridgewell/remapping";import{Features as oe,transform as un}from"lightningcss";import cn from"magic-string";function Eu(e,{file:r="input.css",minify:t=!1,map:n}={}){function i(a,u){return un({filename:r,code:a,minify:t,sourceMap:typeof u<"u",inputSourceMap:u,drafts:{customMedia:!0},nonStandard:{deepSelectorCombinator:!0},include:oe.Nesting|oe.MediaQueries,exclude:oe.LogicalProperties|oe.DirSelector|oe.LightDark,targets:{safari:16<<16|1024,ios_saf:16<<16|1024,firefox:8388608,chrome:7274496},errorRecovery:!0})}let l=i(Buffer.from(e),n);if(n=l.map?.toString(),l.warnings=l.warnings.filter(a=>!/'(deep|slotted|global|ng-deep|host-context)' is not recognized as a valid pseudo-/.test(a.message)),l.warnings.length>0){let a=e.split(` +`),u=[`Found ${l.warnings.length} ${l.warnings.length===1?"warning":"warnings"} while optimizing generated CSS:`];for(let[p,f]of l.warnings.entries()){u.push(""),l.warnings.length>1&&u.push(`Issue #${p+1}:`);let c=2,d=Math.max(0,f.loc.line-c-1),m=Math.min(a.length,f.loc.line+c),y=a.slice(d,m).map((k,ae)=>d+ae+1===f.loc.line?`${le("\u2502")} ${k}`:le(`\u2502 ${k}`));y.splice(f.loc.line-d,0,`${le("\u2506")}${" ".repeat(f.loc.column-1)} ${fn(`${le("^--")} ${f.message}`)}`,`${le("\u2506")}`),u.push(...y)}u.push(""),console.warn(u.join(` +`))}l=i(l.code,n),n=l.map?.toString();let o=l.code.toString(),s=new cn(o);if(s.replaceAll("@media not (","@media not all and ("),n!==void 0&&s.hasChanged()){let a=s.generateMap({source:"original",hires:"boundary"}).toString();n=sn([a,n],()=>null).toString()}return o=s.toString(),{code:o,map:n}}function le(e){return`\x1B[2m${e}\x1B[22m`}function fn(e){return`\x1B[33m${e}\x1B[39m`}import{SourceMapGenerator as pn}from"source-map-js";function dn(e){let r=new pn,t=1,n=new h(i=>({url:i?.url??``,content:i?.content??""}));for(let i of e.mappings){let l=n.get(i.originalPosition?.source??null);r.addMapping({generated:i.generatedPosition,original:i.originalPosition,source:l.url,name:i.name}),r.setSourceContent(l.url,l.content)}return r.toString()}function Ru(e){let r=typeof e=="string"?e:dn(e);function t(n){return`/*# sourceMappingURL=${n} */ +`}return{raw:r,get inline(){let n=Buffer.from(r,"utf-8").toString("base64");return t(`data:application/json;base64,${n}`)},comment:t}}if(!process.versions.bun)if(F.registerHooks)F.registerHooks({resolve:Ke});else{let e=F.createRequire(import.meta.url);F.register?.(mn(e.resolve("@tailwindcss/node/esm-cache-loader")))}export{mu as Features,Ot as Instrumentation,gu as Polyfills,bu as __unstable__loadDesignSystem,wu as compile,ku as compileAst,ke as env,Rt as loadModule,_e as normalizePath,Eu as optimize,bt as rewriteUrlsInAst,Ru as toSourceMap}; diff --git a/dg-ui/node_modules/@tailwindcss/node/dist/require-cache.d.ts b/dg-ui/node_modules/@tailwindcss/node/dist/require-cache.d.ts new file mode 100644 index 0000000..de970b9 --- /dev/null +++ b/dg-ui/node_modules/@tailwindcss/node/dist/require-cache.d.ts @@ -0,0 +1,3 @@ +declare function clearRequireCache(files: string[]): void; + +export { clearRequireCache }; diff --git a/dg-ui/node_modules/@tailwindcss/node/dist/require-cache.js b/dg-ui/node_modules/@tailwindcss/node/dist/require-cache.js new file mode 100644 index 0000000..398995f --- /dev/null +++ b/dg-ui/node_modules/@tailwindcss/node/dist/require-cache.js @@ -0,0 +1 @@ +"use strict";var i=Object.defineProperty;var a=Object.getOwnPropertyDescriptor;var f=Object.getOwnPropertyNames;var l=Object.prototype.hasOwnProperty;var n=(r,e)=>{for(var t in e)i(r,t,{get:e[t],enumerable:!0})},u=(r,e,t,o)=>{if(e&&typeof e=="object"||typeof e=="function")for(let c of f(e))!l.call(r,c)&&c!==t&&i(r,c,{get:()=>e[c],enumerable:!(o=a(e,c))||o.enumerable});return r};var h=r=>u(i({},"__esModule",{value:!0}),r);var d={};n(d,{clearRequireCache:()=>q});module.exports=h(d);function q(r){for(let e of r)delete require.cache[e]}0&&(module.exports={clearRequireCache}); diff --git a/dg-ui/node_modules/@tailwindcss/node/package.json b/dg-ui/node_modules/@tailwindcss/node/package.json new file mode 100644 index 0000000..47f200b --- /dev/null +++ b/dg-ui/node_modules/@tailwindcss/node/package.json @@ -0,0 +1,48 @@ +{ + "name": "@tailwindcss/node", + "version": "4.3.5", + "description": "A utility-first CSS framework for rapidly building custom user interfaces.", + "license": "MIT", + "repository": { + "type": "git", + "url": "https://github.com/tailwindlabs/tailwindcss.git", + "directory": "packages/@tailwindcss-node" + }, + "bugs": "https://github.com/tailwindlabs/tailwindcss/issues", + "homepage": "https://tailwindcss.com", + "files": [ + "dist/" + ], + "publishConfig": { + "provenance": true, + "access": "public" + }, + "exports": { + ".": { + "types": "./dist/index.d.ts", + "import": "./dist/index.mjs", + "require": "./dist/index.js" + }, + "./require-cache": { + "types": "./dist/require-cache.d.ts", + "default": "./dist/require-cache.js" + }, + "./esm-cache-loader": { + "types": "./dist/esm-cache.loader.d.mts", + "default": "./dist/esm-cache.loader.mjs" + } + }, + "dependencies": { + "@jridgewell/remapping": "^2.3.5", + "enhanced-resolve": "^5.24.5", + "jiti": "^2.7.0", + "lightningcss": "1.33.0", + "magic-string": "^1.1.0", + "source-map-js": "^1.2.1", + "tailwindcss": "4.3.5" + }, + "scripts": { + "build": "tsup-node", + "dev": "pnpm run build -- --watch" + } +} \ No newline at end of file diff --git a/dg-ui/node_modules/@tailwindcss/oxide-wasm32-wasi/README.md b/dg-ui/node_modules/@tailwindcss/oxide-wasm32-wasi/README.md new file mode 100644 index 0000000..2a53681 --- /dev/null +++ b/dg-ui/node_modules/@tailwindcss/oxide-wasm32-wasi/README.md @@ -0,0 +1,3 @@ +# `@tailwindcss/oxide-wasm32-wasi` + +This is the **wasm32-wasip1-threads** build of `@tailwindcss/oxide` diff --git a/dg-ui/node_modules/@tailwindcss/oxide-wasm32-wasi/node_modules/@emnapi/core/LICENSE b/dg-ui/node_modules/@tailwindcss/oxide-wasm32-wasi/node_modules/@emnapi/core/LICENSE new file mode 100644 index 0000000..05a5944 --- /dev/null +++ b/dg-ui/node_modules/@tailwindcss/oxide-wasm32-wasi/node_modules/@emnapi/core/LICENSE @@ -0,0 +1,21 @@ +MIT License + +Copyright (c) 2021-present Toyobayashi + +Permission is hereby granted, free of charge, to any person obtaining a copy +of this software and associated documentation files (the "Software"), to deal +in the Software without restriction, including without limitation the rights +to use, copy, modify, merge, publish, distribute, sublicense, and/or sell +copies of the Software, and to permit persons to whom the Software is +furnished to do so, subject to the following conditions: + +The above copyright notice and this permission notice shall be included in all +copies or substantial portions of the Software. + +THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR +IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, +FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE +AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER +LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, +OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE +SOFTWARE. diff --git a/dg-ui/node_modules/@tailwindcss/oxide-wasm32-wasi/node_modules/@emnapi/core/README.md b/dg-ui/node_modules/@tailwindcss/oxide-wasm32-wasi/node_modules/@emnapi/core/README.md new file mode 100644 index 0000000..c98dddc --- /dev/null +++ b/dg-ui/node_modules/@tailwindcss/oxide-wasm32-wasi/node_modules/@emnapi/core/README.md @@ -0,0 +1 @@ +See [https://github.com/toyobayashi/emnapi](https://github.com/toyobayashi/emnapi) diff --git a/dg-ui/node_modules/@tailwindcss/oxide-wasm32-wasi/node_modules/@emnapi/core/dist/emnapi-core.cjs.js b/dg-ui/node_modules/@tailwindcss/oxide-wasm32-wasi/node_modules/@emnapi/core/dist/emnapi-core.cjs.js new file mode 100644 index 0000000..051ac11 --- /dev/null +++ b/dg-ui/node_modules/@tailwindcss/oxide-wasm32-wasi/node_modules/@emnapi/core/dist/emnapi-core.cjs.js @@ -0,0 +1,7746 @@ +var wasiThreads = require('@emnapi/wasi-threads'); + +const _WebAssembly = typeof WebAssembly !== 'undefined' + ? WebAssembly + : typeof WXWebAssembly !== 'undefined' + ? WXWebAssembly + : undefined; +function validateImports(imports) { + if (imports && typeof imports !== 'object') { + throw new TypeError('imports must be an object or undefined'); + } + return true; +} +function load(wasmInput, imports) { + if (!wasmInput) + throw new TypeError('Invalid wasm source'); + validateImports(imports); + imports = imports !== null && imports !== void 0 ? imports : {}; + try { + const then = typeof wasmInput === 'object' && wasmInput !== null && 'then' in wasmInput ? wasmInput.then : undefined; + if (typeof then === 'function') { + return then.call(wasmInput, (input) => load(input, imports)); + } + } + catch (_) { } + if (wasmInput instanceof ArrayBuffer || ArrayBuffer.isView(wasmInput)) { + return _WebAssembly.instantiate(wasmInput, imports); + } + if (wasmInput instanceof _WebAssembly.Module) { + return _WebAssembly.instantiate(wasmInput, imports).then((instance) => { + return { instance, module: wasmInput }; + }); + } + if (typeof Response !== 'undefined' && wasmInput instanceof Response) { + return wasmInput.arrayBuffer().then(buffer => { + return _WebAssembly.instantiate(buffer, imports); + }); + } + const inputIsString = typeof wasmInput === 'string'; + if (inputIsString || (typeof URL !== 'undefined' && wasmInput instanceof URL)) { + if (inputIsString && typeof wx !== 'undefined' && typeof __wxConfig !== 'undefined') { + return _WebAssembly.instantiate(wasmInput, imports); + } + if (typeof fetch !== 'function') { + throw new TypeError('wasm source can not be a string or URL in this environment'); + } + if (typeof _WebAssembly.instantiateStreaming === 'function') { + try { + return _WebAssembly.instantiateStreaming(fetch(wasmInput), imports).catch(() => { + return load(fetch(wasmInput), imports); + }); + } + catch (_) { + return load(fetch(wasmInput), imports); + } + } + else { + return load(fetch(wasmInput), imports); + } + } + throw new TypeError('Invalid wasm source'); +} +function loadSync(wasmInput, imports) { + if (!wasmInput) + throw new TypeError('Invalid wasm source'); + validateImports(imports); + imports = imports !== null && imports !== void 0 ? imports : {}; + let module; + if ((wasmInput instanceof ArrayBuffer) || ArrayBuffer.isView(wasmInput)) { + module = new _WebAssembly.Module(wasmInput); + } + else if (wasmInput instanceof WebAssembly.Module) { + module = wasmInput; + } + else { + throw new TypeError('Invalid wasm source'); + } + const instance = new _WebAssembly.Instance(module, imports); + const source = { instance, module }; + return source; +} + +function createNapiModule(options) { + var napiModule = (function () { + var ENVIRONMENT_IS_NODE = typeof process === 'object' && process !== null && typeof process.versions === 'object' && process.versions !== null && typeof process.versions.node === 'string'; + var ENVIRONMENT_IS_PTHREAD = Boolean(options.childThread); + var waitThreadStart = typeof options.waitThreadStart === 'number' ? options.waitThreadStart : Boolean(options.waitThreadStart); + var wasmInstance; + var wasmMemory; + var wasmTable; + var _malloc; + var _free; + function abort(msg) { + if (typeof _WebAssembly.RuntimeError === 'function') { + throw new _WebAssembly.RuntimeError(msg); + } + throw Error(msg); + } + var napiModule = { + imports: { + env: {}, + napi: {}, + emnapi: {} + }, + exports: {}, + emnapi: {}, + loaded: false, + filename: '', + childThread: ENVIRONMENT_IS_PTHREAD, + initWorker: undefined, + waitThreadStart: waitThreadStart, + PThread: undefined, + init: function (options) { + if (napiModule.loaded) + return napiModule.exports; + if (!options) + throw new TypeError('Invalid napi init options'); + var instance = options.instance; + if (!(instance === null || instance === void 0 ? void 0 : instance.exports)) + throw new TypeError('Invalid wasm instance'); + wasmInstance = instance; + var exports = instance.exports; + var module = options.module; + var memory = options.memory || exports.memory; + var table = options.table || exports.__indirect_function_table; + if (!(module instanceof _WebAssembly.Module)) + throw new TypeError('Invalid wasm module'); + if (!(memory instanceof _WebAssembly.Memory)) + throw new TypeError('Invalid wasm memory'); + if (!(table instanceof _WebAssembly.Table)) + throw new TypeError('Invalid wasm table'); + wasmMemory = memory; + wasmTable = table; + if (typeof exports.malloc !== 'function') + throw new TypeError('malloc is not exported'); + if (typeof exports.free !== 'function') + throw new TypeError('free is not exported'); + _malloc = exports.malloc; + _free = exports.free; + if (!napiModule.childThread) { + var moduleApiVersion = 8; + var node_api_module_get_api_version_v1 = instance.exports.node_api_module_get_api_version_v1; + if (typeof node_api_module_get_api_version_v1 === 'function') { + moduleApiVersion = node_api_module_get_api_version_v1(); + } + var envObject = napiModule.envObject || (napiModule.envObject = emnapiCtx.createEnv(napiModule.filename, moduleApiVersion, function (cb) { return (wasmTable.get(cb)); }, function (cb) { return (wasmTable.get(cb)); }, abort, emnapiNodeBinding)); + var scope_1 = emnapiCtx.openScope(envObject); + try { + envObject.callIntoModule(function (_envObject) { + var exports = napiModule.exports; + var exportsHandle = scope_1.add(exports); + var napi_register_wasm_v1 = instance.exports.napi_register_wasm_v1; + var napiValue = napi_register_wasm_v1(_envObject.id, exportsHandle.id); + napiModule.exports = (!napiValue) ? exports : emnapiCtx.handleStore.get(napiValue).value; + }); + } + catch (e) { + if (e !== 'unwind') { + throw e; + } + } + finally { + emnapiCtx.closeScope(envObject, scope_1); + } + napiModule.loaded = true; + delete napiModule.envObject; + return napiModule.exports; + } + } + }; + var emnapiCtx; + var emnapiNodeBinding; + var onCreateWorker = undefined; + var err; + if (!ENVIRONMENT_IS_PTHREAD) { + var context = options.context; + if (typeof context !== 'object' || context === null) { + throw new TypeError("Invalid `options.context`. Use `import { getDefaultContext } from '@emnapi/runtime'`"); + } + emnapiCtx = context; + } + else { + emnapiCtx = options === null || options === void 0 ? void 0 : options.context; + var postMsg = typeof options.postMessage === 'function' + ? options.postMessage + : typeof postMessage === 'function' + ? postMessage + : undefined; + if (typeof postMsg !== 'function') { + throw new TypeError('No postMessage found'); + } + napiModule.postMessage = postMsg; + } + if (typeof options.filename === 'string') { + napiModule.filename = options.filename; + } + if (typeof options.onCreateWorker === 'function') { + onCreateWorker = options.onCreateWorker; + } + if (typeof options.print === 'function') { + options.print; + } + else { + console.log.bind(console); + } + if (typeof options.printErr === 'function') { + err = options.printErr; + } + else { + err = console.warn.bind(console); + } + if ('nodeBinding' in options) { + var nodeBinding = options.nodeBinding; + if (typeof nodeBinding !== 'object' || nodeBinding === null) { + throw new TypeError('Invalid `options.nodeBinding`. Use @emnapi/node-binding package'); + } + emnapiNodeBinding = nodeBinding; + } + var emnapiAsyncWorkPoolSize = 0; + if ('asyncWorkPoolSize' in options) { + if (typeof options.asyncWorkPoolSize !== 'number') { + throw new TypeError('options.asyncWorkPoolSize must be a integer'); + } + emnapiAsyncWorkPoolSize = options.asyncWorkPoolSize >> 0; + if (emnapiAsyncWorkPoolSize > 1024) { + emnapiAsyncWorkPoolSize = 1024; + } + else if (emnapiAsyncWorkPoolSize < -1024) { + emnapiAsyncWorkPoolSize = -1024; + } + } + var singleThreadAsyncWork = ENVIRONMENT_IS_PTHREAD ? false : (emnapiAsyncWorkPoolSize <= 0); + function _emnapi_async_work_pool_size() { + return Math.abs(emnapiAsyncWorkPoolSize); + } + napiModule.imports.env._emnapi_async_work_pool_size = _emnapi_async_work_pool_size; + function emnapiAddSendListener(worker) { + if (!worker) + return false; + if (worker._emnapiSendListener) + return true; + var handler = function (e) { + var data = ENVIRONMENT_IS_NODE ? e : e.data; + var __emnapi__ = data.__emnapi__; + if (__emnapi__ && __emnapi__.type === 'async-send') { + if (ENVIRONMENT_IS_PTHREAD) { + var postMessage_1 = napiModule.postMessage; + postMessage_1({ __emnapi__: __emnapi__ }); + } + else { + var callback = __emnapi__.payload.callback; + (wasmTable.get(callback))(__emnapi__.payload.data); + } + } + }; + var dispose = function () { + if (ENVIRONMENT_IS_NODE) { + worker.off('message', handler); + } + else { + worker.removeEventListener('message', handler, false); + } + delete worker._emnapiSendListener; + }; + worker._emnapiSendListener = { handler: handler, dispose: dispose }; + if (ENVIRONMENT_IS_NODE) { + worker.on('message', handler); + } + else { + worker.addEventListener('message', handler, false); + } + return true; + } + napiModule.emnapi.addSendListener = emnapiAddSendListener; + var PThread = new wasiThreads.ThreadManager(ENVIRONMENT_IS_PTHREAD + ? { + printErr: err, + childThread: true + } + : { + printErr: err, + beforeLoad: function (worker) { + emnapiAddSendListener(worker); + }, + reuseWorker: options.reuseWorker, + onCreateWorker: onCreateWorker + }); + napiModule.PThread = PThread; + function napi_set_last_error(env, error_code, engine_error_code, engine_reserved) { + var envObject = emnapiCtx.envStore.get(env); + return envObject.setLastError(error_code, engine_error_code, engine_reserved); + } + function napi_clear_last_error(env) { + var envObject = emnapiCtx.envStore.get(env); + return envObject.clearLastError(); + } + function _emnapi_get_node_version(major, minor, patch) { + major >>>= 0; + minor >>>= 0; + patch >>>= 0; + var versions = (typeof process === 'object' && process !== null && + typeof process.versions === 'object' && process.versions !== null && + typeof process.versions.node === 'string') + ? process.versions.node.split('.').map(function (n) { return Number(n); }) + : [0, 0, 0]; + var HEAP_DATA_VIEW = new DataView(wasmMemory.buffer), GET_HEAP_DATA_VIEW = function () { return HEAP_DATA_VIEW.buffer === wasmMemory.buffer ? HEAP_DATA_VIEW : (HEAP_DATA_VIEW = new DataView(wasmMemory.buffer)); }; + GET_HEAP_DATA_VIEW().setUint32(major, versions[0], true); + GET_HEAP_DATA_VIEW().setUint32(minor, versions[1], true); + GET_HEAP_DATA_VIEW().setUint32(patch, versions[2], true); + } + function _emnapi_runtime_keepalive_push() { + } + function _emnapi_runtime_keepalive_pop() { + } + function _emnapi_set_immediate(callback, data) { + emnapiCtx.feature.setImmediate(function () { + (wasmTable.get(callback))(data); + }); + } + function _emnapi_next_tick(callback, data) { + Promise.resolve().then(function () { + (wasmTable.get(callback))(data); + }); + } + function _emnapi_callback_into_module(forceUncaught, env, callback, data, close_scope_if_throw) { + var envObject = emnapiCtx.envStore.get(env); + var scope = emnapiCtx.openScope(envObject); + try { + envObject.callbackIntoModule(Boolean(forceUncaught), function () { + (wasmTable.get(callback))(env, data); + }); + } + catch (err) { + emnapiCtx.closeScope(envObject, scope); + if (close_scope_if_throw) { + emnapiCtx.closeScope(envObject); + } + throw err; + } + emnapiCtx.closeScope(envObject, scope); + } + function _emnapi_call_finalizer(forceUncaught, env, callback, data, hint) { + var envObject = emnapiCtx.envStore.get(env); + callback >>>= 0; + envObject.callFinalizerInternal(forceUncaught, callback, data, hint); + } + function _emnapi_ctx_increase_waiting_request_counter() { + emnapiCtx.increaseWaitingRequestCounter(); + } + function _emnapi_ctx_decrease_waiting_request_counter() { + emnapiCtx.decreaseWaitingRequestCounter(); + } + function _emnapi_is_main_runtime_thread() { + return ENVIRONMENT_IS_PTHREAD ? 0 : 1; + } + function _emnapi_is_main_browser_thread() { + return (typeof window !== 'undefined' && typeof document !== 'undefined' && !ENVIRONMENT_IS_NODE) ? 1 : 0; + } + function _emnapi_unwind() { + throw 'unwind'; + } + function _emnapi_get_now() { + return performance.timeOrigin + performance.now(); + } + function $emnapiSetValueI64(result, numberValue) { + var tempDouble; + var tempI64 = [ + numberValue >>> 0, + (tempDouble = numberValue, +Math.abs(tempDouble) >= 1 ? tempDouble > 0 ? (Math.min(+Math.floor(tempDouble / 4294967296), 4294967295) | 0) >>> 0 : ~~+Math.ceil((tempDouble - +(~~tempDouble >>> 0)) / 4294967296) >>> 0 : 0) + ]; + var HEAP_DATA_VIEW = new DataView(wasmMemory.buffer), GET_HEAP_DATA_VIEW = function () { return HEAP_DATA_VIEW.buffer === wasmMemory.buffer ? HEAP_DATA_VIEW : (HEAP_DATA_VIEW = new DataView(wasmMemory.buffer)); }; + GET_HEAP_DATA_VIEW().setInt32(result, tempI64[0], true); + GET_HEAP_DATA_VIEW().setInt32(result + 4, tempI64[1], true); + } + function _emnapi_open_handle_scope() { + return emnapiCtx.openScope().id; + } + function _emnapi_close_handle_scope(_scope) { + return emnapiCtx.closeScope(); + } + var utilMod = Object.freeze({ + __proto__: null, + $emnapiSetValueI64: $emnapiSetValueI64, + _emnapi_call_finalizer: _emnapi_call_finalizer, + _emnapi_callback_into_module: _emnapi_callback_into_module, + _emnapi_close_handle_scope: _emnapi_close_handle_scope, + _emnapi_ctx_decrease_waiting_request_counter: _emnapi_ctx_decrease_waiting_request_counter, + _emnapi_ctx_increase_waiting_request_counter: _emnapi_ctx_increase_waiting_request_counter, + _emnapi_get_node_version: _emnapi_get_node_version, + _emnapi_get_now: _emnapi_get_now, + _emnapi_is_main_browser_thread: _emnapi_is_main_browser_thread, + _emnapi_is_main_runtime_thread: _emnapi_is_main_runtime_thread, + _emnapi_next_tick: _emnapi_next_tick, + _emnapi_open_handle_scope: _emnapi_open_handle_scope, + _emnapi_runtime_keepalive_pop: _emnapi_runtime_keepalive_pop, + _emnapi_runtime_keepalive_push: _emnapi_runtime_keepalive_push, + _emnapi_set_immediate: _emnapi_set_immediate, + _emnapi_unwind: _emnapi_unwind, + napi_clear_last_error: napi_clear_last_error, + napi_set_last_error: napi_set_last_error + }); + function emnapiGetWorkerByPthreadPtr(pthreadPtr) { + var view = new DataView(wasmMemory.buffer); + var tidOffset = 20; + var tid = view.getInt32(pthreadPtr + tidOffset, true); + var worker = PThread.pthreads[tid]; + return worker; + } + function _emnapi_worker_ref(pthreadPtr) { + if (ENVIRONMENT_IS_PTHREAD) + return; + pthreadPtr >>>= 0; + var worker = emnapiGetWorkerByPthreadPtr(pthreadPtr); + if (worker && typeof worker.ref === 'function') { + worker.ref(); + } + } + function _emnapi_worker_unref(pthreadPtr) { + if (ENVIRONMENT_IS_PTHREAD) + return; + pthreadPtr >>>= 0; + var worker = emnapiGetWorkerByPthreadPtr(pthreadPtr); + if (worker && typeof worker.unref === 'function') { + worker.unref(); + } + } + function _emnapi_async_send_js(type, callback, data) { + if (ENVIRONMENT_IS_PTHREAD) { + var postMessage_1 = napiModule.postMessage; + postMessage_1({ + __emnapi__: { + type: 'async-send', + payload: { + callback: callback, + data: data + } + } + }); + } + else { + switch (type) { + case 0: + _emnapi_set_immediate(callback, data); + break; + case 1: + _emnapi_next_tick(callback, data); + break; + } + } + } + var uvThreadpoolReadyResolve; + var uvThreadpoolReady = new Promise(function (resolve) { + uvThreadpoolReadyResolve = function () { + uvThreadpoolReady.ready = true; + resolve(); + }; + }); + uvThreadpoolReady.ready = false; + function _emnapi_after_uvthreadpool_ready(callback, q, type) { + if (uvThreadpoolReady.ready) { + (wasmTable.get(callback))(q, type); + } + else { + uvThreadpoolReady.then(function () { + (wasmTable.get(callback))(q, type); + }); + } + } + function _emnapi_tell_js_uvthreadpool(threads, size) { + var p = []; + var HEAP_DATA_VIEW = new DataView(wasmMemory.buffer), GET_HEAP_DATA_VIEW = function () { return HEAP_DATA_VIEW.buffer === wasmMemory.buffer ? HEAP_DATA_VIEW : (HEAP_DATA_VIEW = new DataView(wasmMemory.buffer)); }; + var _loop_1 = function (i) { + var pthreadPtr = GET_HEAP_DATA_VIEW().getUint32(threads + i * 4, true); + var worker = emnapiGetWorkerByPthreadPtr(pthreadPtr); + p.push(new Promise(function (resolve) { + var handler = function (e) { + var data = ENVIRONMENT_IS_NODE ? e : e.data; + var __emnapi__ = data.__emnapi__; + if (__emnapi__ && __emnapi__.type === 'async-thread-ready') { + resolve(); + if (worker && typeof worker.unref === 'function') { + worker.unref(); + } + if (ENVIRONMENT_IS_NODE) { + worker.off('message', handler); + } + else { + worker.removeEventListener('message', handler); + } + } + }; + if (ENVIRONMENT_IS_NODE) { + worker.on('message', handler); + } + else { + worker.addEventListener('message', handler); + } + })); + }; + for (var i = 0; i < size; i++) { + _loop_1(i); + } + Promise.all(p).then(uvThreadpoolReadyResolve); + } + function _emnapi_emit_async_thread_ready() { + if (!ENVIRONMENT_IS_PTHREAD) + return; + var postMessage = napiModule.postMessage; + postMessage({ + __emnapi__: { + type: 'async-thread-ready', + payload: {} + } + }); + } + var asyncMod = Object.freeze({ + __proto__: null, + _emnapi_after_uvthreadpool_ready: _emnapi_after_uvthreadpool_ready, + _emnapi_async_send_js: _emnapi_async_send_js, + _emnapi_emit_async_thread_ready: _emnapi_emit_async_thread_ready, + _emnapi_tell_js_uvthreadpool: _emnapi_tell_js_uvthreadpool, + _emnapi_worker_ref: _emnapi_worker_ref, + _emnapi_worker_unref: _emnapi_worker_unref + }); + function napi_adjust_external_memory(env, change_in_bytes, adjusted_value) { + if (!env) + return 1; + var envObject = emnapiCtx.envStore.get(env); + if (!adjusted_value) + return envObject.setLastError(1); + var adjusted_memory = emnapiCtx.adjustAmountOfExternalAllocatedMemory(change_in_bytes); + adjusted_value >>>= 0; + if (emnapiCtx.feature.supportBigInt) { + var HEAP_DATA_VIEW = new DataView(wasmMemory.buffer), GET_HEAP_DATA_VIEW = function () { return HEAP_DATA_VIEW.buffer === wasmMemory.buffer ? HEAP_DATA_VIEW : (HEAP_DATA_VIEW = new DataView(wasmMemory.buffer)); }; + GET_HEAP_DATA_VIEW().setBigInt64(adjusted_value, BigInt(adjusted_memory), true); + } + else { + $emnapiSetValueI64(adjusted_value, Number(adjusted_memory)); + } + return envObject.clearLastError(); + } + var memoryMod = Object.freeze({ + __proto__: null, + napi_adjust_external_memory: napi_adjust_external_memory + }); + var emnapiAWST = { + idGen: {}, + values: [undefined], + queued: new Set(), + pending: [], + init: function () { + var idGen = { + nextId: 1, + list: [], + generate: function () { + var id; + if (idGen.list.length) { + id = idGen.list.shift(); + } + else { + id = idGen.nextId; + idGen.nextId++; + } + return id; + }, + reuse: function (id) { + idGen.list.push(id); + } + }; + emnapiAWST.idGen = idGen; + emnapiAWST.values = [undefined]; + emnapiAWST.queued = new Set(); + emnapiAWST.pending = []; + }, + create: function (env, resource, resourceName, execute, complete, data) { + var asyncId = 0; + var triggerAsyncId = 0; + if (emnapiNodeBinding) { + var asyncContext = emnapiNodeBinding.node.emitAsyncInit(resource, resourceName, -1); + asyncId = asyncContext.asyncId; + triggerAsyncId = asyncContext.triggerAsyncId; + } + var id = emnapiAWST.idGen.generate(); + emnapiAWST.values[id] = { + env: env, + id: id, + resource: resource, + asyncId: asyncId, + triggerAsyncId: triggerAsyncId, + status: 0, + execute: execute, + complete: complete, + data: data + }; + return id; + }, + callComplete: function (work, status) { + var complete = work.complete; + var env = work.env; + var data = work.data; + var callback = function () { + if (!complete) + return; + var envObject = emnapiCtx.envStore.get(env); + var scope = emnapiCtx.openScope(envObject); + try { + envObject.callbackIntoModule(true, function () { + (wasmTable.get(complete))(env, status, data); + }); + } + finally { + emnapiCtx.closeScope(envObject, scope); + } + }; + if (emnapiNodeBinding) { + emnapiNodeBinding.node.makeCallback(work.resource, callback, [], { + asyncId: work.asyncId, + triggerAsyncId: work.triggerAsyncId + }); + } + else { + callback(); + } + }, + queue: function (id) { + var work = emnapiAWST.values[id]; + if (!work) + return; + if (work.status === 0) { + work.status = 1; + if (emnapiAWST.queued.size >= (Math.abs(emnapiAsyncWorkPoolSize) || 4)) { + emnapiAWST.pending.push(id); + return; + } + emnapiAWST.queued.add(id); + var env_1 = work.env; + var data_1 = work.data; + var execute = work.execute; + work.status = 2; + emnapiCtx.feature.setImmediate(function () { + (wasmTable.get(execute))(env_1, data_1); + emnapiAWST.queued.delete(id); + work.status = 3; + emnapiCtx.feature.setImmediate(function () { + emnapiAWST.callComplete(work, 0); + }); + if (emnapiAWST.pending.length > 0) { + var nextWorkId = emnapiAWST.pending.shift(); + emnapiAWST.values[nextWorkId].status = 0; + emnapiAWST.queue(nextWorkId); + } + }); + } + }, + cancel: function (id) { + var index = emnapiAWST.pending.indexOf(id); + if (index !== -1) { + var work_1 = emnapiAWST.values[id]; + if (work_1 && (work_1.status === 1)) { + work_1.status = 4; + emnapiAWST.pending.splice(index, 1); + emnapiCtx.feature.setImmediate(function () { + emnapiAWST.callComplete(work_1, 11); + }); + return 0; + } + else { + return 9; + } + } + return 9; + }, + remove: function (id) { + var work = emnapiAWST.values[id]; + if (!work) + return; + if (emnapiNodeBinding) { + emnapiNodeBinding.node.emitAsyncDestroy({ + asyncId: work.asyncId, + triggerAsyncId: work.triggerAsyncId + }); + } + emnapiAWST.values[id] = undefined; + emnapiAWST.idGen.reuse(id); + } + }; + function _emnapi_node_emit_async_init(async_resource, async_resource_name, trigger_async_id, result) { + if (!emnapiNodeBinding) + return; + var resource = emnapiCtx.handleStore.get(async_resource).value; + var resource_name = emnapiCtx.handleStore.get(async_resource_name).value; + var asyncContext = emnapiNodeBinding.node.emitAsyncInit(resource, resource_name, trigger_async_id); + var asyncId = asyncContext.asyncId; + var triggerAsyncId = asyncContext.triggerAsyncId; + if (result) { + result >>>= 0; + var HEAP_DATA_VIEW = new DataView(wasmMemory.buffer), GET_HEAP_DATA_VIEW = function () { return HEAP_DATA_VIEW.buffer === wasmMemory.buffer ? HEAP_DATA_VIEW : (HEAP_DATA_VIEW = new DataView(wasmMemory.buffer)); }; + GET_HEAP_DATA_VIEW().setFloat64(result, asyncId, true); + GET_HEAP_DATA_VIEW().setFloat64(result + 8, triggerAsyncId, true); + } + } + function _emnapi_node_emit_async_destroy(async_id, trigger_async_id) { + if (!emnapiNodeBinding) + return; + emnapiNodeBinding.node.emitAsyncDestroy({ + asyncId: async_id, + triggerAsyncId: trigger_async_id + }); + } + function _emnapi_node_make_callback(env, async_resource, cb, argv, size, async_id, trigger_async_id, result) { + var i = 0; + var v; + if (!emnapiNodeBinding) + return; + var resource = emnapiCtx.handleStore.get(async_resource).value; + var callback = emnapiCtx.handleStore.get(cb).value; + argv >>>= 0; + size >>>= 0; + size = size >>> 0; + var arr = Array(size); + var HEAP_DATA_VIEW = new DataView(wasmMemory.buffer), GET_HEAP_DATA_VIEW = function () { return HEAP_DATA_VIEW.buffer === wasmMemory.buffer ? HEAP_DATA_VIEW : (HEAP_DATA_VIEW = new DataView(wasmMemory.buffer)); }; + for (; i < size; i++) { + var argVal = GET_HEAP_DATA_VIEW().getUint32(argv + i * 4, true); + arr[i] = emnapiCtx.handleStore.get(argVal).value; + } + var ret = emnapiNodeBinding.node.makeCallback(resource, callback, arr, { + asyncId: async_id, + triggerAsyncId: trigger_async_id + }); + if (result) { + result >>>= 0; + var envObject = emnapiCtx.envStore.get(env); + v = envObject.ensureHandleId(ret); + GET_HEAP_DATA_VIEW().setUint32(result, v, true); + } + } + function _emnapi_async_init_js(async_resource, async_resource_name, result) { + if (!emnapiNodeBinding) { + return 9; + } + var resource; + if (async_resource) { + resource = Object(emnapiCtx.handleStore.get(async_resource).value); + } + var name = emnapiCtx.handleStore.get(async_resource_name).value; + var ret = emnapiNodeBinding.napi.asyncInit(resource, name); + if (ret.status !== 0) + return ret.status; + var numberValue = ret.value; + if (!((numberValue >= (BigInt(-1) * (BigInt(1) << BigInt(63)))) && (numberValue < (BigInt(1) << BigInt(63))))) { + numberValue = numberValue & ((BigInt(1) << BigInt(64)) - BigInt(1)); + if (numberValue >= (BigInt(1) << BigInt(63))) { + numberValue = numberValue - (BigInt(1) << BigInt(64)); + } + } + var low = Number(numberValue & BigInt(0xffffffff)); + var high = Number(numberValue >> BigInt(32)); + result >>>= 0; + var HEAP_DATA_VIEW = new DataView(wasmMemory.buffer), GET_HEAP_DATA_VIEW = function () { return HEAP_DATA_VIEW.buffer === wasmMemory.buffer ? HEAP_DATA_VIEW : (HEAP_DATA_VIEW = new DataView(wasmMemory.buffer)); }; + GET_HEAP_DATA_VIEW().setInt32(result, low, true); + GET_HEAP_DATA_VIEW().setInt32(result + 4, high, true); + return 0; + } + function _emnapi_async_destroy_js(async_context) { + if (!emnapiNodeBinding) { + return 9; + } + async_context >>>= 0; + var HEAP_DATA_VIEW = new DataView(wasmMemory.buffer), GET_HEAP_DATA_VIEW = function () { return HEAP_DATA_VIEW.buffer === wasmMemory.buffer ? HEAP_DATA_VIEW : (HEAP_DATA_VIEW = new DataView(wasmMemory.buffer)); }; + var low = GET_HEAP_DATA_VIEW().getInt32(async_context, true); + var high = GET_HEAP_DATA_VIEW().getInt32(async_context + 4, true); + var pointer = BigInt(low >>> 0) | (BigInt(high) << BigInt(32)); + var ret = emnapiNodeBinding.napi.asyncDestroy(pointer); + if (ret.status !== 0) + return ret.status; + return 0; + } + function napi_open_callback_scope(env, ignored, async_context_handle, result) { + throw new Error('napi_open_callback_scope has not been implemented yet'); + } + function napi_close_callback_scope(env, scope) { + throw new Error('napi_close_callback_scope has not been implemented yet'); + } + function napi_make_callback(env, async_context, recv, func, argc, argv, result) { + var i = 0; + var v; + if (!env) + return 1; + var envObject = emnapiCtx.envStore.get(env); + envObject.checkGCAccess(); + if (!envObject.tryCatch.isEmpty()) + return envObject.setLastError(10); + if (!envObject.canCallIntoJs()) + return envObject.setLastError(envObject.moduleApiVersion >= 10 ? 23 : 10); + envObject.clearLastError(); + try { + if (!emnapiNodeBinding) { + return envObject.setLastError(9); + } + if (!recv) + return envObject.setLastError(1); + if (argc > 0) { + if (!argv) + return envObject.setLastError(1); + } + var v8recv = Object(emnapiCtx.handleStore.get(recv).value); + var v8func = emnapiCtx.handleStore.get(func).value; + if (typeof v8func !== 'function') { + return envObject.setLastError(1); + } + async_context >>>= 0; + var HEAP_DATA_VIEW = new DataView(wasmMemory.buffer), GET_HEAP_DATA_VIEW = function () { return HEAP_DATA_VIEW.buffer === wasmMemory.buffer ? HEAP_DATA_VIEW : (HEAP_DATA_VIEW = new DataView(wasmMemory.buffer)); }; + var low = GET_HEAP_DATA_VIEW().getInt32(async_context, true); + var high = GET_HEAP_DATA_VIEW().getInt32(async_context + 4, true); + var ctx = BigInt(low >>> 0) | (BigInt(high) << BigInt(32)); + argv >>>= 0; + argc >>>= 0; + argc = argc >>> 0; + var arr = Array(argc); + for (; i < argc; i++) { + var argVal = GET_HEAP_DATA_VIEW().getUint32(argv + i * 4, true); + arr[i] = emnapiCtx.handleStore.get(argVal).value; + } + var ret = emnapiNodeBinding.napi.makeCallback(ctx, v8recv, v8func, arr); + if (ret.error) { + throw ret.error; + } + if (ret.status !== 0) + return envObject.setLastError(ret.status); + if (result) { + result >>>= 0; + v = envObject.ensureHandleId(ret.value); + GET_HEAP_DATA_VIEW().setUint32(result, v, true); + } + return envObject.getReturnStatus(); + } + catch (err) { + envObject.tryCatch.setError(err); + return envObject.setLastError(10); + } + } + function _emnapi_env_check_gc_access(env) { + var envObject = emnapiCtx.envStore.get(env); + envObject.checkGCAccess(); + } + var nodeMod = Object.freeze({ + __proto__: null, + _emnapi_async_destroy_js: _emnapi_async_destroy_js, + _emnapi_async_init_js: _emnapi_async_init_js, + _emnapi_env_check_gc_access: _emnapi_env_check_gc_access, + _emnapi_node_emit_async_destroy: _emnapi_node_emit_async_destroy, + _emnapi_node_emit_async_init: _emnapi_node_emit_async_init, + _emnapi_node_make_callback: _emnapi_node_make_callback, + napi_close_callback_scope: napi_close_callback_scope, + napi_make_callback: napi_make_callback, + napi_open_callback_scope: napi_open_callback_scope + }); + var emnapiTSFN = { + _liveSet: {}, + offset: { + __size__: 0, + resource: 0, + async_id: 0, + trigger_async_id: 0, + queue_size: 0, + is_some: 0, + queue: 0, + async_pending: 0, + async_u_fd: 0, + thread_count: 0, + state: 0, + dispatch_state: 0, + context: 0, + max_queue_size: 0, + ref: 0, + env: 0, + finalize_data: 0, + finalize_cb: 0, + call_js_cb: 0, + handles_closing: 0, + async_ref: 0, + mutex: 0, + cond: 0 + }, + init: function () { + emnapiTSFN._liveSet = new Set(); + emnapiTSFN.offset.__size__ = 184; + emnapiTSFN.offset.resource = 0; + emnapiTSFN.offset.async_id = 8; + emnapiTSFN.offset.trigger_async_id = 16; + emnapiTSFN.offset.queue_size = 60; + emnapiTSFN.offset.is_some = 24; + emnapiTSFN.offset.queue = 64; + emnapiTSFN.offset.async_pending = 132; + emnapiTSFN.offset.async_u_fd = 96; + emnapiTSFN.offset.thread_count = 136; + emnapiTSFN.offset.state = 140; + emnapiTSFN.offset.dispatch_state = 144; + emnapiTSFN.offset.context = 148; + emnapiTSFN.offset.max_queue_size = 152; + emnapiTSFN.offset.ref = 156; + emnapiTSFN.offset.env = 160; + emnapiTSFN.offset.finalize_data = 164; + emnapiTSFN.offset.finalize_cb = 168; + emnapiTSFN.offset.call_js_cb = 172; + emnapiTSFN.offset.handles_closing = 176; + emnapiTSFN.offset.async_ref = 180; + emnapiTSFN.offset.mutex = 32; + emnapiTSFN.offset.cond = 56; + emnapiTSFN.offset.mutex = emnapiTSFN.offset.mutex + 4; + if (typeof PThread !== 'undefined') { + PThread.unusedWorkers.forEach(emnapiTSFN.addListener); + Object.values(PThread.pthreads).forEach(emnapiTSFN.addListener); + var __original_getNewWorker_1 = PThread.getNewWorker; + PThread.getNewWorker = function () { + var r = __original_getNewWorker_1.apply(this, arguments); + emnapiTSFN.addListener(r); + return r; + }; + } + }, + addListener: function (worker) { + if (!worker) + return false; + if (worker._emnapiTSFNListener) + return true; + var handler = function (e) { + var data = ENVIRONMENT_IS_NODE ? e : e.data; + var __emnapi__ = data.__emnapi__; + if (__emnapi__) { + var type = __emnapi__.type; + var payload = __emnapi__.payload; + if (type === 'tsfn-send') { + var pendng = payload.tsfn + emnapiTSFN.offset.async_pending; + if (Atomics.load(new Int32Array(emnapiTSFN.ensureBufferFor(pendng + 4)), pendng >>> 2) !== 0) { + emnapiTSFN.enqueue(payload.tsfn); + } + } + } + }; + var dispose = function () { + if (ENVIRONMENT_IS_NODE) { + worker.off('message', handler); + } + else { + worker.removeEventListener('message', handler, false); + } + delete worker._emnapiTSFNListener; + }; + worker._emnapiTSFNListener = { handler: handler, dispose: dispose }; + if (ENVIRONMENT_IS_NODE) { + worker.on('message', handler); + } + else { + worker.addEventListener('message', handler, false); + } + return true; + }, + ensureBufferFor: function (end) { + var buffer = wasmMemory.buffer; + if (end > buffer.byteLength) { + wasmMemory.grow(0); + buffer = wasmMemory.buffer; + } + return buffer; + }, + initQueue: function (func) { + var size = 2 * 4; + var queue = _malloc(size); + if (!queue) + return false; + queue >>>= 0; + new Uint8Array(emnapiTSFN.ensureBufferFor(queue + size), queue, size).fill(0); + emnapiTSFN.storeSizeTypeValue(func + emnapiTSFN.offset.queue, queue, false); + return true; + }, + destroyQueue: function (func) { + var queue = emnapiTSFN.loadSizeTypeValue(func + emnapiTSFN.offset.queue, false); + if (queue) { + var node = emnapiTSFN.loadSizeTypeValue(queue, false); + while (node !== 0) { + var next = emnapiTSFN.loadSizeTypeValue(node + 4, false); + _free(node); + node = next; + } + _free(queue); + } + }, + pushQueue: function (func, data) { + var queue = emnapiTSFN.loadSizeTypeValue(func + emnapiTSFN.offset.queue, false); + var head = emnapiTSFN.loadSizeTypeValue(queue, false); + var tail = emnapiTSFN.loadSizeTypeValue(queue + 4, false); + var size = 2 * 4; + var node = _malloc(size); + if (!node) + throw new Error('OOM'); + node >>>= 0; + emnapiTSFN.storeSizeTypeValue(node, data, false); + emnapiTSFN.storeSizeTypeValue(node + 4, 0, false); + if (head === 0 && tail === 0) { + emnapiTSFN.storeSizeTypeValue(queue, node, false); + emnapiTSFN.storeSizeTypeValue(queue + 4, node, false); + } + else { + emnapiTSFN.storeSizeTypeValue(tail + 4, node, false); + emnapiTSFN.storeSizeTypeValue(queue + 4, node, false); + } + emnapiTSFN.addQueueSize(func); + }, + shiftQueue: function (func) { + var queue = emnapiTSFN.loadSizeTypeValue(func + emnapiTSFN.offset.queue, false); + var head = emnapiTSFN.loadSizeTypeValue(queue, false); + if (head === 0) + return 0; + var node = head; + var next = emnapiTSFN.loadSizeTypeValue(head + 4, false); + emnapiTSFN.storeSizeTypeValue(queue, next, false); + if (next === 0) { + emnapiTSFN.storeSizeTypeValue(queue + 4, 0, false); + } + emnapiTSFN.storeSizeTypeValue(node + 4, 0, false); + var value = emnapiTSFN.loadSizeTypeValue(node, false); + _free(node); + emnapiTSFN.subQueueSize(func); + return value; + }, + push: function (func, data, mode) { + var mutex = emnapiTSFN.getMutex(func); + var cond = emnapiTSFN.getCond(func); + var waitCondition = function () { + var queueSize = emnapiTSFN.getQueueSize(func); + var maxSize = emnapiTSFN.getMaxQueueSize(func); + return queueSize >= maxSize && maxSize > 0 && emnapiTSFN.getState(func) === 0; + }; + var isBrowserMain = typeof window !== 'undefined' && typeof document !== 'undefined' && !ENVIRONMENT_IS_NODE; + var shouldDelete = false; + var ret = mutex.execute(function () { + while (waitCondition()) { + if (mode === 0) { + return 15; + } + if (isBrowserMain) { + return 21; + } + cond.wait(); + } + if (emnapiTSFN.getState(func) === 0) { + emnapiTSFN.pushQueue(func, data); + emnapiTSFN.send(func); + return 0; + } + if (emnapiTSFN.getThreadCount(func) === 0) { + return 1; + } + emnapiTSFN.subThreadCount(func); + if (!(emnapiTSFN.getState(func) === 2 && emnapiTSFN.getThreadCount(func) === 0)) { + return 16; + } + shouldDelete = true; + return 16; + }); + if (shouldDelete) { + emnapiTSFN.destroy(func); + } + return ret; + }, + getMutex: function (func) { + var index = func + emnapiTSFN.offset.mutex; + var mutex = { + lock: function () { + var isBrowserMain = typeof window !== 'undefined' && typeof document !== 'undefined' && !ENVIRONMENT_IS_NODE; + var i32a = new Int32Array(emnapiTSFN.ensureBufferFor(index + 4), index, 1); + if (isBrowserMain) { + while (true) { + var oldValue = Atomics.compareExchange(i32a, 0, 0, 10); + if (oldValue === 0) { + return; + } + } + } + else { + while (true) { + var oldValue = Atomics.compareExchange(i32a, 0, 0, 10); + if (oldValue === 0) { + return; + } + Atomics.wait(i32a, 0, 10); + } + } + }, + unlock: function () { + var i32a = new Int32Array(emnapiTSFN.ensureBufferFor(index + 4), index, 1); + var oldValue = Atomics.compareExchange(i32a, 0, 10, 0); + if (oldValue !== 10) { + throw new Error('Tried to unlock while not holding the mutex'); + } + Atomics.notify(i32a, 0, 1); + }, + execute: function (fn) { + mutex.lock(); + try { + return fn(); + } + finally { + mutex.unlock(); + } + } + }; + return mutex; + }, + getCond: function (func) { + var index = func + emnapiTSFN.offset.cond; + var mutex = emnapiTSFN.getMutex(func); + var cond = { + wait: function () { + var i32a = new Int32Array(emnapiTSFN.ensureBufferFor(index + 4), index, 1); + var value = Atomics.load(i32a, 0); + mutex.unlock(); + Atomics.wait(i32a, 0, value); + mutex.lock(); + }, + signal: function () { + var i32a = new Int32Array(emnapiTSFN.ensureBufferFor(index + 4), index, 1); + Atomics.add(i32a, 0, 1); + Atomics.notify(i32a, 0, 1); + } + }; + return cond; + }, + getQueueSize: function (func) { + return emnapiTSFN.loadSizeTypeValue(func + emnapiTSFN.offset.queue_size, true); + }, + addQueueSize: function (func) { + var offset = emnapiTSFN.offset.queue_size; + var arr, index; + arr = new Uint32Array(emnapiTSFN.ensureBufferFor(func + offset + 4)); + index = (func + offset) >>> 2; + Atomics.add(arr, index, 1); + }, + subQueueSize: function (func) { + var offset = emnapiTSFN.offset.queue_size; + var arr, index; + arr = new Uint32Array(emnapiTSFN.ensureBufferFor(func + offset + 4)); + index = (func + offset) >>> 2; + Atomics.sub(arr, index, 1); + }, + getThreadCount: function (func) { + return emnapiTSFN.loadSizeTypeValue(func + emnapiTSFN.offset.thread_count, true); + }, + addThreadCount: function (func) { + var offset = emnapiTSFN.offset.thread_count; + var arr, index; + arr = new Uint32Array(emnapiTSFN.ensureBufferFor(func + offset + 4)); + index = (func + offset) >>> 2; + Atomics.add(arr, index, 1); + }, + subThreadCount: function (func) { + var offset = emnapiTSFN.offset.thread_count; + var arr, index; + arr = new Uint32Array(emnapiTSFN.ensureBufferFor(func + offset + 4)); + index = (func + offset) >>> 2; + Atomics.sub(arr, index, 1); + }, + getState: function (func) { + return Atomics.load(new Int32Array(emnapiTSFN.ensureBufferFor(func + emnapiTSFN.offset.state + 4)), (func + emnapiTSFN.offset.state) >>> 2); + }, + setState: function (func, value) { + Atomics.store(new Int32Array(emnapiTSFN.ensureBufferFor(func + emnapiTSFN.offset.state + 4)), (func + emnapiTSFN.offset.state) >>> 2, value); + }, + getHandlesClosing: function (func) { + return Atomics.load(new Int8Array(emnapiTSFN.ensureBufferFor(func + emnapiTSFN.offset.handles_closing + 1)), (func + emnapiTSFN.offset.handles_closing)); + }, + setHandlesClosing: function (func, value) { + Atomics.store(new Int8Array(emnapiTSFN.ensureBufferFor(func + emnapiTSFN.offset.handles_closing + 1)), (func + emnapiTSFN.offset.handles_closing), value); + }, + getDispatchState: function (func) { + return Atomics.load(new Uint32Array(emnapiTSFN.ensureBufferFor(func + emnapiTSFN.offset.dispatch_state + 4)), (func + emnapiTSFN.offset.dispatch_state) >>> 2); + }, + getContext: function (func) { + return emnapiTSFN.loadSizeTypeValue(func + emnapiTSFN.offset.context, false); + }, + getMaxQueueSize: function (func) { + return emnapiTSFN.loadSizeTypeValue(func + emnapiTSFN.offset.max_queue_size, true); + }, + getEnv: function (func) { + return emnapiTSFN.loadSizeTypeValue(func + emnapiTSFN.offset.env, false); + }, + getCallJSCb: function (func) { + return emnapiTSFN.loadSizeTypeValue(func + emnapiTSFN.offset.call_js_cb, false); + }, + getRef: function (func) { + return emnapiTSFN.loadSizeTypeValue(func + emnapiTSFN.offset.ref, false); + }, + getResource: function (func) { + return emnapiTSFN.loadSizeTypeValue(func + emnapiTSFN.offset.resource, false); + }, + getFinalizeCb: function (func) { + return emnapiTSFN.loadSizeTypeValue(func + emnapiTSFN.offset.finalize_cb, false); + }, + getFinalizeData: function (func) { + return emnapiTSFN.loadSizeTypeValue(func + emnapiTSFN.offset.finalize_data, false); + }, + loadSizeTypeValue: function (offset, unsigned) { + var ret; + var arr; + if (unsigned) { + arr = new Uint32Array(emnapiTSFN.ensureBufferFor(offset + 4)); + ret = Atomics.load(arr, offset >>> 2); + return ret; + } + else { + arr = new Int32Array(emnapiTSFN.ensureBufferFor(offset + 4)); + ret = Atomics.load(arr, offset >>> 2); + return ret; + } + }, + storeSizeTypeValue: function (offset, value, unsigned) { + var arr; + if (unsigned) { + arr = new Uint32Array(emnapiTSFN.ensureBufferFor(offset + 4)); + Atomics.store(arr, offset >>> 2, value); + return undefined; + } + else { + arr = new Int32Array(emnapiTSFN.ensureBufferFor(offset + 4)); + Atomics.store(arr, offset >>> 2, value >>> 0); + return undefined; + } + }, + releaseResources: function (func) { + if (emnapiTSFN.getState(func) !== 2) { + emnapiTSFN.setState(func, 2); + var env = emnapiTSFN.getEnv(func); + var envObject = emnapiCtx.envStore.get(env); + var ref = emnapiTSFN.getRef(func); + if (ref) { + emnapiCtx.refStore.get(ref).dispose(); + } + var resource = emnapiTSFN.getResource(func); + emnapiCtx.refStore.get(resource).dispose(); + emnapiTSFN.ensureBufferFor(func + emnapiTSFN.offset.is_some + 1); + var HEAP_DATA_VIEW = new DataView(wasmMemory.buffer), GET_HEAP_DATA_VIEW = function () { return HEAP_DATA_VIEW.buffer === wasmMemory.buffer ? HEAP_DATA_VIEW : (HEAP_DATA_VIEW = new DataView(wasmMemory.buffer)); }; + GET_HEAP_DATA_VIEW().setInt8(func + emnapiTSFN.offset.is_some, 0, true); + emnapiCtx.removeCleanupHook(envObject, emnapiTSFN.cleanup, func); + envObject.unref(); + var asyncRefAddress = func + emnapiTSFN.offset.async_ref; + var asyncRefOffset = asyncRefAddress >>> 2; + var arr = new Uint32Array(emnapiTSFN.ensureBufferFor(asyncRefAddress + 4)); + if (Atomics.load(arr, asyncRefOffset) > 0) { + Atomics.store(arr, asyncRefOffset, 0); + emnapiCtx.decreaseWaitingRequestCounter(); + } + if (emnapiNodeBinding) { + var view = new DataView(emnapiTSFN.ensureBufferFor(func + emnapiTSFN.offset.trigger_async_id + 8)); + var asyncId = view.getFloat64(func + emnapiTSFN.offset.async_id, true); + var triggerAsyncId = view.getFloat64(func + emnapiTSFN.offset.trigger_async_id, true); + _emnapi_node_emit_async_destroy(asyncId, triggerAsyncId); + } + } + }, + destroy: function (func) { + emnapiTSFN._liveSet.delete(func); + emnapiTSFN.destroyQueue(func); + emnapiTSFN.releaseResources(func); + _free(func); + }, + emptyQueue: function (func) { + var drainQueue = []; + emnapiTSFN.getMutex(func).execute(function () { + while (emnapiTSFN.getQueueSize(func) > 0) { + drainQueue.push(emnapiTSFN.shiftQueue(func)); + } + }); + var callJsCb = emnapiTSFN.getCallJSCb(func); + var context = emnapiTSFN.getContext(func); + var data; + for (var i = 0; i < drainQueue.length; i++) { + data = drainQueue[i]; + if (callJsCb) { + (wasmTable.get(callJsCb))(0, 0, context, data); + } + } + }, + maybeDelete: function (func) { + var shouldDelete = false; + emnapiTSFN.getMutex(func).execute(function () { + if (emnapiTSFN.getThreadCount(func) > 0) { + emnapiTSFN.releaseResources(func); + } + else { + shouldDelete = true; + } + }); + if (shouldDelete) { + emnapiTSFN.destroy(func); + } + }, + finalize: function (func) { + var env = emnapiTSFN.getEnv(func); + var envObject = emnapiCtx.envStore.get(env); + emnapiCtx.openScope(envObject); + var finalize = emnapiTSFN.getFinalizeCb(func); + var data = emnapiTSFN.getFinalizeData(func); + var context = emnapiTSFN.getContext(func); + var f = function () { + envObject.callFinalizerInternal(0, finalize, data, context); + }; + try { + emnapiTSFN.emptyQueue(func); + if (finalize) { + if (emnapiNodeBinding) { + var resource = emnapiTSFN.getResource(func); + var resource_value = emnapiCtx.refStore.get(resource).get(); + var resourceObject = emnapiCtx.handleStore.get(resource_value).value; + var view = new DataView(emnapiTSFN.ensureBufferFor(func + emnapiTSFN.offset.trigger_async_id + 8)); + var asyncId = view.getFloat64(func + emnapiTSFN.offset.async_id, true); + var triggerAsyncId = view.getFloat64(func + emnapiTSFN.offset.trigger_async_id, true); + emnapiNodeBinding.node.makeCallback(resourceObject, f, [], { + asyncId: asyncId, + triggerAsyncId: triggerAsyncId + }); + } + else { + f(); + } + } + emnapiTSFN.maybeDelete(func); + } + finally { + emnapiCtx.closeScope(envObject); + } + }, + cleanup: function (func) { + emnapiTSFN.closeHandlesAndMaybeDelete(func, 1); + }, + closeHandlesAndMaybeDelete: function (func, set_closing) { + var env = emnapiTSFN.getEnv(func); + var envObject = emnapiCtx.envStore.get(env); + emnapiCtx.openScope(envObject); + try { + if (set_closing) { + emnapiTSFN.getMutex(func).execute(function () { + emnapiTSFN.setState(func, 1); + if (emnapiTSFN.getMaxQueueSize(func) > 0) { + emnapiTSFN.getCond(func).signal(); + } + }); + } + if (emnapiTSFN.getHandlesClosing(func)) { + return; + } + emnapiTSFN.setHandlesClosing(func, 1); + Atomics.store(new Int32Array(emnapiTSFN.ensureBufferFor(func + emnapiTSFN.offset.async_pending + 4)), (func + emnapiTSFN.offset.async_pending) >>> 2, 1); + emnapiCtx.feature.setImmediate(function () { + emnapiTSFN.finalize(func); + }); + } + finally { + emnapiCtx.closeScope(envObject); + } + }, + dispatchOne: function (func) { + var data = 0; + var popped_value = false; + var has_more = false; + var mutex = emnapiTSFN.getMutex(func); + var cond = emnapiTSFN.getCond(func); + mutex.execute(function () { + if (emnapiTSFN.getState(func) === 0) { + var size = emnapiTSFN.getQueueSize(func); + if (size > 0) { + data = emnapiTSFN.shiftQueue(func); + popped_value = true; + var maxQueueSize = emnapiTSFN.getMaxQueueSize(func); + if (size === maxQueueSize && maxQueueSize > 0) { + cond.signal(); + } + size--; + } + if (size === 0) { + if (emnapiTSFN.getThreadCount(func) === 0) { + emnapiTSFN.setState(func, 1); + if (emnapiTSFN.getMaxQueueSize(func) > 0) { + cond.signal(); + } + emnapiTSFN.closeHandlesAndMaybeDelete(func, 0); + } + } + else { + has_more = true; + } + } + else { + emnapiTSFN.closeHandlesAndMaybeDelete(func, 0); + } + }); + if (popped_value) { + var env = emnapiTSFN.getEnv(func); + var envObject_1 = emnapiCtx.envStore.get(env); + emnapiCtx.openScope(envObject_1); + var f = function () { + envObject_1.callbackIntoModule(false, function () { + var callJsCb = emnapiTSFN.getCallJSCb(func); + var ref = emnapiTSFN.getRef(func); + var js_callback = ref ? emnapiCtx.refStore.get(ref).get() : 0; + if (callJsCb) { + var context = emnapiTSFN.getContext(func); + (wasmTable.get(callJsCb))(env, js_callback, context, data); + } + else { + var jsCallback = js_callback ? emnapiCtx.handleStore.get(js_callback).value : null; + if (typeof jsCallback === 'function') { + jsCallback(); + } + } + }); + }; + try { + if (emnapiNodeBinding) { + var resource = emnapiTSFN.getResource(func); + var resource_value = emnapiCtx.refStore.get(resource).get(); + var resourceObject = emnapiCtx.handleStore.get(resource_value).value; + var view = new DataView(emnapiTSFN.ensureBufferFor(func + emnapiTSFN.offset.trigger_async_id + 8)); + emnapiNodeBinding.node.makeCallback(resourceObject, f, [], { + asyncId: view.getFloat64(func + emnapiTSFN.offset.async_id, true), + triggerAsyncId: view.getFloat64(func + emnapiTSFN.offset.trigger_async_id, true) + }); + } + else { + f(); + } + } + finally { + emnapiCtx.closeScope(envObject_1); + } + } + return has_more; + }, + dispatch: function (func) { + var has_more = true; + var iterations_left = 1000; + var dispatchStateAddress = func + emnapiTSFN.offset.dispatch_state; + var index = dispatchStateAddress >>> 2; + while (has_more && --iterations_left !== 0) { + Atomics.store(new Uint32Array(emnapiTSFN.ensureBufferFor(dispatchStateAddress + 4)), index, 1); + try { + has_more = emnapiTSFN.dispatchOne(func); + } + catch (err) { + if (emnapiTSFN._liveSet.has(func)) { + Atomics.exchange(new Uint32Array(emnapiTSFN.ensureBufferFor(dispatchStateAddress + 4)), index, 0); + emnapiTSFN.send(func); + } + throw err; + } + if (Atomics.exchange(new Uint32Array(emnapiTSFN.ensureBufferFor(dispatchStateAddress + 4)), index, 0) !== 1) { + has_more = true; + } + } + if (has_more) { + emnapiTSFN.send(func); + } + }, + enqueue: function (func) { + var pending = func + emnapiTSFN.offset.async_pending; + var scheduled = func + emnapiTSFN.offset.async_u_fd; + var end = Math.max(pending, scheduled) + 4; + var state = function () { return new Int32Array(emnapiTSFN.ensureBufferFor(end)); }; + if (Atomics.exchange(state(), scheduled >>> 2, 1) !== 0) { + return; + } + emnapiCtx.feature.setImmediate(function () { + if (!emnapiTSFN._liveSet.has(func)) { + return; + } + if (Atomics.load(state(), pending >>> 2) === 0) { + Atomics.store(state(), scheduled >>> 2, 0); + return; + } + emnapiCtx.feature.setImmediate(function () { + if (!emnapiTSFN._liveSet.has(func)) { + return; + } + try { + if (Atomics.exchange(state(), pending >>> 2, 0) === 0) { + return; + } + emnapiTSFN.dispatch(func); + } + finally { + if (emnapiTSFN._liveSet.has(func)) { + Atomics.store(state(), scheduled >>> 2, 0); + if (Atomics.load(state(), pending >>> 2) !== 0) { + emnapiTSFN.enqueue(func); + } + } + } + }); + }); + }, + send: function (func) { + var dispatchStateAddress = func + emnapiTSFN.offset.dispatch_state; + var current_state = Atomics.or(new Uint32Array(emnapiTSFN.ensureBufferFor(dispatchStateAddress + 4)), dispatchStateAddress >>> 2, 1 << 1); + if ((current_state & 1) === 1) { + return; + } + var pendng = func + emnapiTSFN.offset.async_pending; + if (Atomics.load(new Int32Array(emnapiTSFN.ensureBufferFor(pendng + 4)), pendng >>> 2) !== 0) { + return; + } + if (Atomics.exchange(new Int32Array(emnapiTSFN.ensureBufferFor(pendng + 4)), pendng >>> 2, 1) === 0) { + if ((typeof ENVIRONMENT_IS_PTHREAD !== 'undefined') && ENVIRONMENT_IS_PTHREAD) { + postMessage({ + __emnapi__: { + type: 'tsfn-send', + payload: { + tsfn: func + } + } + }); + } + else { + emnapiTSFN.enqueue(func); + } + } + } + }; + function napi_create_threadsafe_function(env, func, async_resource, async_resource_name, max_queue_size, initial_thread_count, thread_finalize_data, thread_finalize_cb, context, call_js_cb, result) { + if (!env) + return 1; + var envObject = emnapiCtx.envStore.get(env); + envObject.checkGCAccess(); + if (!async_resource_name) + return envObject.setLastError(1); + max_queue_size >>>= 0; + initial_thread_count >>>= 0; + env >>>= 0; + thread_finalize_data >>>= 0; + thread_finalize_cb >>>= 0; + context >>>= 0; + call_js_cb >>>= 0; + max_queue_size = max_queue_size >>> 0; + initial_thread_count = initial_thread_count >>> 0; + if (initial_thread_count === 0) { + return envObject.setLastError(1); + } + if (!result) + return envObject.setLastError(1); + var ref = 0; + func >>>= 0; + if (!func) { + if (!call_js_cb) + return envObject.setLastError(1); + } + else { + var funcValue = emnapiCtx.handleStore.get(func).value; + if (typeof funcValue !== 'function') { + return envObject.setLastError(1); + } + ref = emnapiCtx.createReference(envObject, func, 1, 1).id; + } + var asyncResourceObject; + if (async_resource) { + asyncResourceObject = emnapiCtx.handleStore.get(async_resource).value; + if (asyncResourceObject == null) { + return envObject.setLastError(2); + } + asyncResourceObject = Object(asyncResourceObject); + } + else { + asyncResourceObject = {}; + } + var resource = envObject.ensureHandleId(asyncResourceObject); + var asyncResourceName = emnapiCtx.handleStore.get(async_resource_name).value; + if (typeof asyncResourceName === 'symbol') { + return envObject.setLastError(3); + } + asyncResourceName = String(asyncResourceName); + var resource_name = envObject.ensureHandleId(asyncResourceName); + var sizeofTSFN = emnapiTSFN.offset.__size__; + var tsfn = _malloc(sizeofTSFN); + if (!tsfn) + return envObject.setLastError(9); + tsfn >>>= 0; + new Uint8Array(emnapiTSFN.ensureBufferFor(tsfn + sizeofTSFN)).subarray(tsfn, tsfn + sizeofTSFN).fill(0); + var resourceRef = emnapiCtx.createReference(envObject, resource, 1, 1); + var resource_ = resourceRef.id; + var HEAP_DATA_VIEW = new DataView(wasmMemory.buffer), GET_HEAP_DATA_VIEW = function () { return HEAP_DATA_VIEW.buffer === wasmMemory.buffer ? HEAP_DATA_VIEW : (HEAP_DATA_VIEW = new DataView(wasmMemory.buffer)); }; + GET_HEAP_DATA_VIEW().setUint32(tsfn + emnapiTSFN.offset.resource, resource_, true); + if (!emnapiTSFN.initQueue(tsfn)) { + _free(tsfn); + resourceRef.dispose(); + return envObject.setLastError(9); + } + _emnapi_node_emit_async_init(resource, resource_name, -1, tsfn + emnapiTSFN.offset.async_id); + GET_HEAP_DATA_VIEW().setInt8(tsfn + emnapiTSFN.offset.is_some, 1, true); + GET_HEAP_DATA_VIEW().setUint32(tsfn + emnapiTSFN.offset.thread_count, initial_thread_count, true); + GET_HEAP_DATA_VIEW().setUint32(tsfn + emnapiTSFN.offset.context, context, true); + GET_HEAP_DATA_VIEW().setUint32(tsfn + emnapiTSFN.offset.max_queue_size, max_queue_size, true); + GET_HEAP_DATA_VIEW().setUint32(tsfn + emnapiTSFN.offset.ref, ref, true); + GET_HEAP_DATA_VIEW().setUint32(tsfn + emnapiTSFN.offset.env, env, true); + GET_HEAP_DATA_VIEW().setUint32(tsfn + emnapiTSFN.offset.finalize_data, thread_finalize_data, true); + GET_HEAP_DATA_VIEW().setUint32(tsfn + emnapiTSFN.offset.finalize_cb, thread_finalize_cb, true); + GET_HEAP_DATA_VIEW().setUint32(tsfn + emnapiTSFN.offset.call_js_cb, call_js_cb, true); + emnapiCtx.addCleanupHook(envObject, emnapiTSFN.cleanup, tsfn); + emnapiTSFN._liveSet.add(tsfn); + envObject.ref(); + emnapiCtx.increaseWaitingRequestCounter(); + GET_HEAP_DATA_VIEW().setUint32(tsfn + emnapiTSFN.offset.async_ref, 1, true); + result >>>= 0; + GET_HEAP_DATA_VIEW().setUint32(result, tsfn, true); + return envObject.clearLastError(); + } + function napi_get_threadsafe_function_context(func, result) { + if (!func || !result) { + abort(); + return 1; + } + func >>>= 0; + result >>>= 0; + var context = emnapiTSFN.getContext(func); + var HEAP_DATA_VIEW = new DataView(wasmMemory.buffer), GET_HEAP_DATA_VIEW = function () { return HEAP_DATA_VIEW.buffer === wasmMemory.buffer ? HEAP_DATA_VIEW : (HEAP_DATA_VIEW = new DataView(wasmMemory.buffer)); }; + GET_HEAP_DATA_VIEW().setUint32(result, context, true); + return 0; + } + function napi_call_threadsafe_function(func, data, mode) { + if (!func) { + abort(); + return 1; + } + func >>>= 0; + data >>>= 0; + return emnapiTSFN.push(func, data, mode); + } + function napi_acquire_threadsafe_function(func) { + if (!func) { + abort(); + return 1; + } + func >>>= 0; + var mutex = emnapiTSFN.getMutex(func); + return mutex.execute(function () { + if (emnapiTSFN.getState(func) === 0) { + emnapiTSFN.addThreadCount(func); + return 0; + } + return 16; + }); + } + function napi_release_threadsafe_function(func, mode) { + if (!func) { + abort(); + return 1; + } + func >>>= 0; + var mutex = emnapiTSFN.getMutex(func); + var cond = emnapiTSFN.getCond(func); + var shouldDelete = false; + var ret = mutex.execute(function () { + if (emnapiTSFN.getThreadCount(func) === 0) { + return 1; + } + emnapiTSFN.subThreadCount(func); + if (emnapiTSFN.getThreadCount(func) === 0 || mode === 1) { + if (emnapiTSFN.getState(func) === 0) { + if (mode === 1) { + emnapiTSFN.setState(func, 1); + } + if (emnapiTSFN.getState(func) === 1 && emnapiTSFN.getMaxQueueSize(func) > 0) { + cond.signal(); + } + emnapiTSFN.send(func); + } + } + if (!(emnapiTSFN.getState(func) === 2 && emnapiTSFN.getThreadCount(func) === 0)) { + return 0; + } + shouldDelete = true; + return 0; + }); + if (shouldDelete) { + emnapiTSFN.destroy(func); + } + return ret; + } + function napi_unref_threadsafe_function(env, func) { + if (!func) { + abort(); + return 1; + } + func >>>= 0; + var asyncRefAddress = func + emnapiTSFN.offset.async_ref; + var asyncRefOffset = asyncRefAddress >>> 2; + var arr = new Uint32Array(emnapiTSFN.ensureBufferFor(asyncRefAddress + 4)); + var currentValue = Atomics.load(arr, asyncRefOffset); + if (currentValue > 0) { + Atomics.store(arr, asyncRefOffset, currentValue - 1); + if (currentValue === 1) { + emnapiCtx.decreaseWaitingRequestCounter(); + } + } + return 0; + } + function napi_ref_threadsafe_function(env, func) { + if (!func) { + abort(); + return 1; + } + func >>>= 0; + var asyncRefAddress = func + emnapiTSFN.offset.async_ref; + var asyncRefOffset = asyncRefAddress >>> 2; + var arr = new Uint32Array(emnapiTSFN.ensureBufferFor(asyncRefAddress + 4)); + var currentValue = Atomics.load(arr, asyncRefOffset); + if (!currentValue) { + emnapiCtx.increaseWaitingRequestCounter(); + } + Atomics.store(arr, asyncRefOffset, currentValue + 1); + return 0; + } + var emnapiAWMT = { + pool: [], + workerReady: null, + globalAddress: 0, + globalOffset: { + idle_threads: 0, + q: 1 * 4, + next: 1 * 4, + prev: 2 * 4, + mutex: 3 * 4, + cond: 4 * 4, + exit_message: 5 * 4, + end: 7 * 4 + }, + offset: { + resource: 0, + async_id: 8, + trigger_async_id: 16, + env: 24, + status: 1 * 4 + 24, + queue: 2 * 4 + 24, + queue_next: 2 * 4 + 24, + queue_prev: 3 * 4 + 24, + data: 4 * 4 + 24, + execute: 5 * 4 + 24, + complete: 6 * 4 + 24, + end: 7 * 4 + 24 + }, + ensureBufferFor: function (end) { + var buffer = wasmMemory.buffer; + if (end > buffer.byteLength) { + wasmMemory.grow(0); + buffer = wasmMemory.buffer; + } + return buffer; + }, + init: function () { + emnapiAWMT.pool = []; + emnapiAWMT.workerReady = null; + if (typeof PThread !== 'undefined') { + PThread.unusedWorkers.forEach(emnapiAWMT.addListener); + Object.values(PThread.pthreads).forEach(emnapiAWMT.addListener); + var __original_getNewWorker_1 = PThread.getNewWorker; + PThread.getNewWorker = function () { + var r = __original_getNewWorker_1.apply(this, arguments); + emnapiAWMT.addListener(r); + return r; + }; + } + }, + addListener: function (worker) { + if (!worker) + return false; + if (worker._emnapiAWMTListener) + return true; + var handler = function (e) { + var data = ENVIRONMENT_IS_NODE ? e : e.data; + var __emnapi__ = data.__emnapi__; + if (__emnapi__) { + var type = __emnapi__.type; + var payload = __emnapi__.payload; + if (type === 'async-work-complete') { + emnapiAWMT.callComplete(payload.work, 0); + } + } + }; + var dispose = function () { + if (ENVIRONMENT_IS_NODE) { + worker.off('message', handler); + } + else { + worker.removeEventListener('message', handler, false); + } + delete worker._emnapiAWMTListener; + }; + worker._emnapiAWMTListener = { handler: handler, dispose: dispose }; + if (ENVIRONMENT_IS_NODE) { + worker.on('message', handler); + } + else { + worker.addEventListener('message', handler, false); + } + return true; + }, + initGlobal: function () { + if (!emnapiAWMT.globalAddress) { + emnapiAWMT.globalAddress = _malloc(emnapiAWMT.globalOffset.end); + emnapiAWMT.globalAddress >>>= 0; + var size = emnapiAWMT.globalOffset.end; + var addr = emnapiAWMT.globalAddress; + new Uint8Array(emnapiAWMT.ensureBufferFor(addr + size), addr, size).fill(0); + emnapiAWMT.queueInit(emnapiAWMT.globalAddress + emnapiAWMT.globalOffset.q); + emnapiAWMT.queueInit(emnapiAWMT.globalAddress + emnapiAWMT.globalOffset.exit_message); + } + }, + terminateWorkers: function () { + emnapiAWMT.pool.forEach(function (w) { + var _a, _b; + (_a = w._emnapiAWMTListener) === null || _a === void 0 ? void 0 : _a.dispose(); + (_b = w._emnapiTSFNListener) === null || _b === void 0 ? void 0 : _b.dispose(); + w.terminate(); + }); + emnapiAWMT.pool.length = 0; + }, + initWorkers: function (n) { + if (ENVIRONMENT_IS_PTHREAD) { + return emnapiAWMT.workerReady || (emnapiAWMT.workerReady = Promise.resolve()); + } + if (emnapiAWMT.workerReady) + return emnapiAWMT.workerReady; + if (!('emnapi_async_worker_create' in wasmInstance.exports)) { + throw new TypeError('`emnapi_async_worker_create` is not exported, please try to add `--export=emnapi_async_worker_create` to linker flags'); + } + var emnapi_async_worker_create = wasmInstance.exports.emnapi_async_worker_create; + var args = []; + emnapiAWMT.initGlobal(); + for (var i = 0; i < n; ++i) { + args.push(emnapi_async_worker_create(1, emnapiAWMT.globalAddress)); + } + var promises = args.map(function (index) { + if (index === 0) { + return Promise.reject(new Error('Failed to create async worker')); + } + var worker; + if (index < 0) { + worker = emnapiAWMT.pool[-index - 1]; + if (worker) + return worker.whenLoaded; + } + index >>>= 0; + var tidOffset = 20; + var view = new DataView(emnapiAWMT.ensureBufferFor(index + tidOffset + 4)); + var tid = view.getInt32(index + tidOffset, true); + worker = PThread.pthreads[tid]; + return worker.whenLoaded; + }); + emnapiAWMT.workerReady = Promise.all(promises); + return emnapiAWMT.workerReady; + }, + getResource: function (work) { + emnapiAWMT.ensureBufferFor(work + emnapiAWMT.offset.resource + 4); + var HEAP_DATA_VIEW = new DataView(wasmMemory.buffer), GET_HEAP_DATA_VIEW = function () { return HEAP_DATA_VIEW.buffer === wasmMemory.buffer ? HEAP_DATA_VIEW : (HEAP_DATA_VIEW = new DataView(wasmMemory.buffer)); }; + return GET_HEAP_DATA_VIEW().getUint32(work + emnapiAWMT.offset.resource, true); + }, + getExecute: function (work) { + emnapiAWMT.ensureBufferFor(work + emnapiAWMT.offset.execute + 4); + var HEAP_DATA_VIEW = new DataView(wasmMemory.buffer), GET_HEAP_DATA_VIEW = function () { return HEAP_DATA_VIEW.buffer === wasmMemory.buffer ? HEAP_DATA_VIEW : (HEAP_DATA_VIEW = new DataView(wasmMemory.buffer)); }; + return GET_HEAP_DATA_VIEW().getUint32(work + emnapiAWMT.offset.execute, true); + }, + getComplete: function (work) { + emnapiAWMT.ensureBufferFor(work + emnapiAWMT.offset.complete + 4); + var HEAP_DATA_VIEW = new DataView(wasmMemory.buffer), GET_HEAP_DATA_VIEW = function () { return HEAP_DATA_VIEW.buffer === wasmMemory.buffer ? HEAP_DATA_VIEW : (HEAP_DATA_VIEW = new DataView(wasmMemory.buffer)); }; + return GET_HEAP_DATA_VIEW().getUint32(work + emnapiAWMT.offset.complete, true); + }, + getEnv: function (work) { + emnapiAWMT.ensureBufferFor(work + emnapiAWMT.offset.env + 4); + var HEAP_DATA_VIEW = new DataView(wasmMemory.buffer), GET_HEAP_DATA_VIEW = function () { return HEAP_DATA_VIEW.buffer === wasmMemory.buffer ? HEAP_DATA_VIEW : (HEAP_DATA_VIEW = new DataView(wasmMemory.buffer)); }; + return GET_HEAP_DATA_VIEW().getUint32(work + emnapiAWMT.offset.env, true); + }, + getData: function (work) { + emnapiAWMT.ensureBufferFor(work + emnapiAWMT.offset.data + 4); + var HEAP_DATA_VIEW = new DataView(wasmMemory.buffer), GET_HEAP_DATA_VIEW = function () { return HEAP_DATA_VIEW.buffer === wasmMemory.buffer ? HEAP_DATA_VIEW : (HEAP_DATA_VIEW = new DataView(wasmMemory.buffer)); }; + return GET_HEAP_DATA_VIEW().getUint32(work + emnapiAWMT.offset.data, true); + }, + getMutex: function () { + var index = emnapiAWMT.globalAddress + emnapiAWMT.globalOffset.mutex; + var mutex = { + lock: function () { + var isBrowserMain = typeof window !== 'undefined' && typeof document !== 'undefined' && !ENVIRONMENT_IS_NODE; + var i32a = new Int32Array(emnapiAWMT.ensureBufferFor(index + 4), index, 1); + if (isBrowserMain) { + while (true) { + var oldValue = Atomics.compareExchange(i32a, 0, 0, 10); + if (oldValue === 0) { + return; + } + } + } + else { + while (true) { + var oldValue = Atomics.compareExchange(i32a, 0, 0, 10); + if (oldValue === 0) { + return; + } + Atomics.wait(i32a, 0, 10); + } + } + }, + unlock: function () { + var i32a = new Int32Array(emnapiAWMT.ensureBufferFor(index + 4), index, 1); + var oldValue = Atomics.compareExchange(i32a, 0, 10, 0); + if (oldValue !== 10) { + throw new Error('Tried to unlock while not holding the mutex'); + } + Atomics.notify(i32a, 0, 1); + }, + execute: function (fn) { + mutex.lock(); + try { + return fn(); + } + finally { + mutex.unlock(); + } + } + }; + return mutex; + }, + getCond: function () { + var index = emnapiAWMT.globalAddress + emnapiAWMT.globalOffset.cond; + var mutex = emnapiAWMT.getMutex(); + var cond = { + wait: function () { + var i32a = new Int32Array(emnapiAWMT.ensureBufferFor(index + 4), index, 1); + var value = Atomics.load(i32a, 0); + mutex.unlock(); + Atomics.wait(i32a, 0, value); + mutex.lock(); + }, + signal: function () { + var i32a = new Int32Array(emnapiAWMT.ensureBufferFor(index + 4), index, 1); + Atomics.add(i32a, 0, 1); + Atomics.notify(i32a, 0, 1); + } + }; + return cond; + }, + queueInit: function (q) { + emnapiAWMT.ensureBufferFor(q + 4 + 4); + var HEAP_DATA_VIEW = new DataView(wasmMemory.buffer), GET_HEAP_DATA_VIEW = function () { return HEAP_DATA_VIEW.buffer === wasmMemory.buffer ? HEAP_DATA_VIEW : (HEAP_DATA_VIEW = new DataView(wasmMemory.buffer)); }; + GET_HEAP_DATA_VIEW().setUint32(q, q, true); + GET_HEAP_DATA_VIEW().setUint32(q + 4, q, true); + }, + queueInsertTail: function (h, q) { + emnapiAWMT.ensureBufferFor(h + 4 + 4); + emnapiAWMT.ensureBufferFor(q + 4 + 4); + var HEAP_DATA_VIEW = new DataView(wasmMemory.buffer), GET_HEAP_DATA_VIEW = function () { return HEAP_DATA_VIEW.buffer === wasmMemory.buffer ? HEAP_DATA_VIEW : (HEAP_DATA_VIEW = new DataView(wasmMemory.buffer)); }; + GET_HEAP_DATA_VIEW().setUint32(q, h, true); + var tempValue = GET_HEAP_DATA_VIEW().getUint32(h + 4, true); + GET_HEAP_DATA_VIEW().setUint32(q + 4, tempValue, true); + var qprev = GET_HEAP_DATA_VIEW().getUint32(q + 4, true); + GET_HEAP_DATA_VIEW().setUint32(qprev, q, true); + GET_HEAP_DATA_VIEW().setUint32(h + 4, q, true); + }, + queueRemove: function (q) { + emnapiAWMT.ensureBufferFor(q + 4 + 4); + var HEAP_DATA_VIEW = new DataView(wasmMemory.buffer), GET_HEAP_DATA_VIEW = function () { return HEAP_DATA_VIEW.buffer === wasmMemory.buffer ? HEAP_DATA_VIEW : (HEAP_DATA_VIEW = new DataView(wasmMemory.buffer)); }; + var qprev = GET_HEAP_DATA_VIEW().getUint32(q + 4, true); + var qnext = GET_HEAP_DATA_VIEW().getUint32(q, true); + GET_HEAP_DATA_VIEW().setUint32(qprev, qnext, true); + GET_HEAP_DATA_VIEW().setUint32(qnext + 4, qprev, true); + }, + queueEmpty: function (q) { + emnapiAWMT.ensureBufferFor(q + 4); + var HEAP_DATA_VIEW = new DataView(wasmMemory.buffer), GET_HEAP_DATA_VIEW = function () { return HEAP_DATA_VIEW.buffer === wasmMemory.buffer ? HEAP_DATA_VIEW : (HEAP_DATA_VIEW = new DataView(wasmMemory.buffer)); }; + return q == GET_HEAP_DATA_VIEW().getUint32(q, true); + }, + scheduleWork: function (work) { + var _a; + if (!((_a = emnapiAWMT.workerReady) === null || _a === void 0 ? void 0 : _a.ready)) { + emnapiAWMT.initWorkers(_emnapi_async_work_pool_size()).then(function () { + emnapiAWMT.workerReady.ready = true; + }).catch(function (err) { + emnapiAWMT.workerReady = null; + throw err; + }); + } + emnapiCtx.increaseWaitingRequestCounter(); + var statusBuffer = new Int32Array(emnapiAWMT.ensureBufferFor(work + emnapiAWMT.offset.status + 4), work + emnapiAWMT.offset.status, 1); + Atomics.store(statusBuffer, 0, 0); + var mutex = emnapiAWMT.getMutex(); + var cond = emnapiAWMT.getCond(); + mutex.lock(); + try { + emnapiAWMT.queueInsertTail(emnapiAWMT.globalAddress + emnapiAWMT.globalOffset.q, work + emnapiAWMT.offset.queue); + } + catch (err) { + emnapiCtx.decreaseWaitingRequestCounter(); + mutex.unlock(); + throw err; + } + emnapiAWMT.ensureBufferFor(emnapiAWMT.globalAddress + emnapiAWMT.globalOffset.idle_threads + 4); + var HEAP_DATA_VIEW = new DataView(wasmMemory.buffer), GET_HEAP_DATA_VIEW = function () { return HEAP_DATA_VIEW.buffer === wasmMemory.buffer ? HEAP_DATA_VIEW : (HEAP_DATA_VIEW = new DataView(wasmMemory.buffer)); }; + if (GET_HEAP_DATA_VIEW().getUint32(emnapiAWMT.globalAddress + emnapiAWMT.globalOffset.idle_threads, true) > 0) { + cond.signal(); + } + mutex.unlock(); + }, + cancelWork: function (work) { + var cancelled = false; + emnapiAWMT.getMutex().execute(function () { + emnapiAWMT.ensureBufferFor(work + emnapiAWMT.offset.status + 4); + var HEAP_DATA_VIEW = new DataView(wasmMemory.buffer), GET_HEAP_DATA_VIEW = function () { return HEAP_DATA_VIEW.buffer === wasmMemory.buffer ? HEAP_DATA_VIEW : (HEAP_DATA_VIEW = new DataView(wasmMemory.buffer)); }; + cancelled = !emnapiAWMT.queueEmpty(work + emnapiAWMT.offset.queue) && GET_HEAP_DATA_VIEW().getInt32(work + emnapiAWMT.offset.status, true) !== 2; + if (cancelled) { + emnapiAWMT.queueRemove(work + emnapiAWMT.offset.queue); + } + }); + if (!cancelled) { + return 9; + } + if (Atomics.compareExchange(new Int32Array(emnapiAWMT.ensureBufferFor(work + emnapiAWMT.offset.status + 4), work + emnapiAWMT.offset.status, 1), 0, 0, 1) !== 0) { + return 9; + } + emnapiCtx.feature.setImmediate(function () { + emnapiAWMT.callComplete(work, 11); + }); + return 0; + }, + callComplete: function (work, status) { + emnapiCtx.decreaseWaitingRequestCounter(); + var complete = emnapiAWMT.getComplete(work); + var env = emnapiAWMT.getEnv(work); + var data = emnapiAWMT.getData(work); + var envObject = emnapiCtx.envStore.get(env); + var scope = emnapiCtx.openScope(envObject); + var callback = function () { + if (!complete) + return; + envObject.callbackIntoModule(true, function () { + (wasmTable.get(complete))(env, status, data); + }); + }; + try { + if (emnapiNodeBinding) { + var resource = emnapiAWMT.getResource(work); + var resource_value = emnapiCtx.refStore.get(resource).get(); + var resourceObject = emnapiCtx.handleStore.get(resource_value).value; + var view = new DataView(emnapiAWMT.ensureBufferFor(work + emnapiAWMT.offset.trigger_async_id + 8)); + var asyncId = view.getFloat64(work + emnapiAWMT.offset.async_id, true); + var triggerAsyncId = view.getFloat64(work + emnapiAWMT.offset.trigger_async_id, true); + emnapiNodeBinding.node.makeCallback(resourceObject, callback, [], { + asyncId: asyncId, + triggerAsyncId: triggerAsyncId + }); + } + else { + callback(); + } + } + finally { + emnapiCtx.closeScope(envObject, scope); + } + } + }; + emnapiAWMT.init(); + var napi_create_async_work = singleThreadAsyncWork + ? function (env, resource, resource_name, execute, complete, data, result) { + if (!env) + return 1; + var envObject = emnapiCtx.envStore.get(env); + envObject.checkGCAccess(); + if (!execute) + return envObject.setLastError(1); + if (!result) + return envObject.setLastError(1); + var resourceObject; + if (resource) { + resourceObject = Object(emnapiCtx.handleStore.get(resource).value); + } + else { + resourceObject = {}; + } + if (!resource_name) + return envObject.setLastError(1); + var resourceName = String(emnapiCtx.handleStore.get(resource_name).value); + var id = emnapiAWST.create(env, resourceObject, resourceName, execute, complete, data); + result >>>= 0; + var HEAP_DATA_VIEW = new DataView(wasmMemory.buffer), GET_HEAP_DATA_VIEW = function () { return HEAP_DATA_VIEW.buffer === wasmMemory.buffer ? HEAP_DATA_VIEW : (HEAP_DATA_VIEW = new DataView(wasmMemory.buffer)); }; + GET_HEAP_DATA_VIEW().setUint32(result, id, true); + return envObject.clearLastError(); + } + : function (env, resource, resource_name, execute, complete, data, result) { + if (!env) + return 1; + var envObject = emnapiCtx.envStore.get(env); + envObject.checkGCAccess(); + if (!execute) + return envObject.setLastError(1); + if (!result) + return envObject.setLastError(1); + var resourceObject; + if (resource) { + resourceObject = Object(emnapiCtx.handleStore.get(resource).value); + } + else { + resourceObject = {}; + } + if (!resource_name) + return envObject.setLastError(1); + var sizeofAW = emnapiAWMT.offset.end; + var aw = _malloc(sizeofAW); + if (!aw) + return envObject.setLastError(9); + aw >>>= 0; + new Uint8Array(emnapiAWMT.ensureBufferFor(aw + sizeofAW)).subarray(aw, aw + sizeofAW).fill(0); + var s = envObject.ensureHandleId(resourceObject); + var resourceRef = emnapiCtx.createReference(envObject, s, 1, 1); + var resource_ = resourceRef.id; + var HEAP_DATA_VIEW = new DataView(wasmMemory.buffer), GET_HEAP_DATA_VIEW = function () { return HEAP_DATA_VIEW.buffer === wasmMemory.buffer ? HEAP_DATA_VIEW : (HEAP_DATA_VIEW = new DataView(wasmMemory.buffer)); }; + GET_HEAP_DATA_VIEW().setUint32(aw, resource_, true); + _emnapi_node_emit_async_init(s, resource_name, -1, aw + emnapiAWMT.offset.async_id); + GET_HEAP_DATA_VIEW().setUint32(aw + emnapiAWMT.offset.env, env, true); + GET_HEAP_DATA_VIEW().setUint32(aw + emnapiAWMT.offset.execute, execute, true); + GET_HEAP_DATA_VIEW().setUint32(aw + emnapiAWMT.offset.complete, complete, true); + GET_HEAP_DATA_VIEW().setUint32(aw + emnapiAWMT.offset.data, data, true); + emnapiAWMT.queueInit(aw + emnapiAWMT.offset.queue); + result >>>= 0; + GET_HEAP_DATA_VIEW().setUint32(result, aw, true); + return envObject.clearLastError(); + }; + var napi_delete_async_work = singleThreadAsyncWork + ? function (env, work) { + if (!env) + return 1; + var envObject = emnapiCtx.envStore.get(env); + envObject.checkGCAccess(); + if (!work) + return envObject.setLastError(1); + work >>>= 0; + emnapiAWST.remove(work); + return envObject.clearLastError(); + } + : function (env, work) { + if (!env) + return 1; + var envObject = emnapiCtx.envStore.get(env); + envObject.checkGCAccess(); + if (!work) + return envObject.setLastError(1); + work >>>= 0; + var resource = emnapiAWMT.getResource(work); + emnapiCtx.refStore.get(resource).dispose(); + if (emnapiNodeBinding) { + var view = new DataView(emnapiAWMT.ensureBufferFor(work + emnapiAWMT.offset.trigger_async_id + 8)); + var asyncId = view.getFloat64(work + emnapiAWMT.offset.async_id, true); + var triggerAsyncId = view.getFloat64(work + emnapiAWMT.offset.trigger_async_id, true); + _emnapi_node_emit_async_destroy(asyncId, triggerAsyncId); + } + _free(work); + return envObject.clearLastError(); + }; + var napi_queue_async_work = singleThreadAsyncWork + ? function (env, work) { + if (!env) + return 1; + var envObject = emnapiCtx.envStore.get(env); + if (!work) + return envObject.setLastError(1); + work >>>= 0; + emnapiAWST.queue(work); + return envObject.clearLastError(); + } + : function (env, work) { + if (!env) + return 1; + var envObject = emnapiCtx.envStore.get(env); + if (!work) + return envObject.setLastError(1); + work >>>= 0; + emnapiAWMT.scheduleWork(work); + return envObject.clearLastError(); + }; + var napi_cancel_async_work = singleThreadAsyncWork + ? function (env, work) { + if (!env) + return 1; + var envObject = emnapiCtx.envStore.get(env); + if (!work) + return envObject.setLastError(1); + work >>>= 0; + var status = emnapiAWST.cancel(work); + if (status === 0) + return envObject.clearLastError(); + return envObject.setLastError(status); + } + : function (env, work) { + if (!env) + return 1; + var envObject = emnapiCtx.envStore.get(env); + if (!work) + return envObject.setLastError(1); + work >>>= 0; + var status = emnapiAWMT.cancelWork(work); + if (status === 0) + return envObject.clearLastError(); + return envObject.setLastError(status); + }; + function _emnapi_async_worker(globalAddress) { + globalAddress >>>= 0; + emnapiAWMT.globalAddress = globalAddress; + var mutex = emnapiAWMT.getMutex(); + var cond = emnapiAWMT.getCond(); + mutex.lock(); + var exitMessageAddr = globalAddress + emnapiAWMT.globalOffset.exit_message; + var idleThreadsAddr = globalAddress + emnapiAWMT.globalOffset.idle_threads; + var workerQueueAddr = globalAddress + emnapiAWMT.globalOffset.q; + var HEAP_DATA_VIEW = new DataView(wasmMemory.buffer), GET_HEAP_DATA_VIEW = function () { return HEAP_DATA_VIEW.buffer === wasmMemory.buffer ? HEAP_DATA_VIEW : (HEAP_DATA_VIEW = new DataView(wasmMemory.buffer)); }; + for (;;) { + emnapiAWMT.ensureBufferFor(workerQueueAddr + 4); + while (emnapiAWMT.queueEmpty(workerQueueAddr)) { + Atomics.add(new Int32Array(emnapiAWMT.ensureBufferFor(idleThreadsAddr + 4), idleThreadsAddr, 1), 0, 1); + cond.wait(); + Atomics.sub(new Int32Array(emnapiAWMT.ensureBufferFor(idleThreadsAddr + 4), idleThreadsAddr, 1), 0, 1); + } + var q = GET_HEAP_DATA_VIEW().getUint32(workerQueueAddr, true); + if (q === exitMessageAddr) { + cond.signal(); + mutex.unlock(); + break; + } + var work = q - emnapiAWMT.offset.queue; + emnapiAWMT.queueRemove(q); + emnapiAWMT.queueInit(q); + mutex.unlock(); + var statusBuffer = new Int32Array(emnapiAWMT.ensureBufferFor(work + emnapiAWMT.offset.status + 4), work + emnapiAWMT.offset.status, 1); + if (Atomics.load(statusBuffer, 0) === 1) { + abort('unreachable'); + } + var execute = emnapiAWMT.getExecute(work); + var env = emnapiAWMT.getEnv(work); + var data = emnapiAWMT.getData(work); + (wasmTable.get(execute))(env, data); + Atomics.store(statusBuffer, 0, 2); + var postMessage_1 = napiModule.postMessage; + postMessage_1({ + __emnapi__: { + type: 'async-work-complete', + payload: { work: work } + } + }); + mutex.lock(); + } + return 0; + } + function _emnapi_spawn_worker(f, globalAddress) { + if (typeof onCreateWorker !== 'function') { + throw new TypeError('`options.onCreateWorker` is not a function'); + } + var promises = []; + var args = []; + if (!('emnapi_async_worker_create' in wasmInstance.exports)) { + throw new TypeError('`emnapi_async_worker_create` is not exported, please try to add `--export=emnapi_async_worker_create` to linker flags'); + } + args.push(wasmInstance.exports.emnapi_async_worker_create(0, 0)); + var handleError = function (e) { + if ('message' in e && (e.message.indexOf('RuntimeError') !== -1 || e.message.indexOf('unreachable') !== -1)) { + emnapiAWMT.terminateWorkers(); + } + }; + var ret; + try { + var worker_1 = onCreateWorker({ type: 'async-work', name: 'emnapi-async-worker' }); + var p = PThread.loadWasmModuleToWorker(worker_1); + if (ENVIRONMENT_IS_NODE) { + worker_1.on('error', handleError); + } + else { + worker_1.addEventListener('error', handleError, false); + } + emnapiAWMT.addListener(worker_1); + emnapiTSFN.addListener(worker_1); + promises.push(p.then(function () { + if (typeof worker_1.unref === 'function') { + worker_1.unref(); + } + })); + ret = emnapiAWMT.pool.push(worker_1) - 1; + var arg = args[0]; + worker_1.threadBlockBase = arg; + worker_1.postMessage({ + __emnapi__: { + type: 'async-worker-init', + payload: { arg: arg, func: [f, globalAddress] } + } + }); + } + catch (err) { + var arg = args[0]; + _free(arg); + throw err; + } + return ret; + } + function initWorker(startArg, func) { + if (napiModule.childThread) { + if (typeof wasmInstance.exports.emnapi_async_worker_init !== 'function') { + throw new TypeError('`emnapi_async_worker_init` is not exported, please try to add `--export=emnapi_async_worker_init` to linker flags'); + } + wasmInstance.exports.emnapi_async_worker_init(startArg); + (wasmTable.get(func[0]))(func[1]); + } + else { + throw new Error('startThread is only available in child threads'); + } + } + napiModule.initWorker = initWorker; + var asyncWorkMod = Object.freeze({ + __proto__: null, + _emnapi_async_worker: _emnapi_async_worker, + _emnapi_spawn_worker: _emnapi_spawn_worker, + napi_cancel_async_work: napi_cancel_async_work, + napi_create_async_work: napi_create_async_work, + napi_delete_async_work: napi_delete_async_work, + napi_queue_async_work: napi_queue_async_work + }); + var emnapiExternalMemory = { + registry: typeof FinalizationRegistry === 'function' ? new FinalizationRegistry(function (_pointer) { _free(_pointer); }) : undefined, + table: new WeakMap(), + wasmMemoryViewTable: new WeakMap(), + intrinsics: undefined, + init: function () { + var _a; + emnapiExternalMemory.registry = typeof FinalizationRegistry === 'function' ? new FinalizationRegistry(function (_pointer) { _free(_pointer); }) : undefined; + emnapiExternalMemory.table = new WeakMap(); + emnapiExternalMemory.wasmMemoryViewTable = new WeakMap(); + var sharedArrayBufferByteLength = typeof SharedArrayBuffer === 'function' + ? (_a = Object.getOwnPropertyDescriptor(SharedArrayBuffer.prototype, 'byteLength')) === null || _a === void 0 ? void 0 : _a.get + : undefined; + emnapiExternalMemory.intrinsics = { + isView: ArrayBuffer.isView, + typedArray: { + buffer: Object.getOwnPropertyDescriptor(Object.getPrototypeOf(Uint8Array.prototype), 'buffer').get, + byteOffset: Object.getOwnPropertyDescriptor(Object.getPrototypeOf(Uint8Array.prototype), 'byteOffset').get, + length: Object.getOwnPropertyDescriptor(Object.getPrototypeOf(Uint8Array.prototype), 'length').get, + tag: Object.getOwnPropertyDescriptor(Object.getPrototypeOf(Uint8Array.prototype), Symbol.toStringTag).get + }, + dataView: { + buffer: Object.getOwnPropertyDescriptor(DataView.prototype, 'buffer').get, + byteOffset: Object.getOwnPropertyDescriptor(DataView.prototype, 'byteOffset').get, + byteLength: Object.getOwnPropertyDescriptor(DataView.prototype, 'byteLength').get + }, + arrayBuffer: { + byteLength: Object.getOwnPropertyDescriptor(ArrayBuffer.prototype, 'byteLength').get + }, + sharedArrayBuffer: sharedArrayBufferByteLength !== undefined + ? { + byteLength: sharedArrayBufferByteLength + } + : undefined, + ctors: { + Int8Array: Int8Array, + Uint8Array: Uint8Array, + Uint8ClampedArray: Uint8ClampedArray, + Int16Array: Int16Array, + Uint16Array: Uint16Array, + Int32Array: Int32Array, + Uint32Array: Uint32Array, + Float16Array: typeof Float16Array === 'function' ? Float16Array : undefined, + Float32Array: Float32Array, + Float64Array: Float64Array, + BigInt64Array: BigInt64Array, + BigUint64Array: BigUint64Array + }, + bufferFrom: undefined + }; + }, + isSharedArrayBuffer: function (value) { + var sharedArrayBuffer = emnapiExternalMemory.intrinsics.sharedArrayBuffer; + if (sharedArrayBuffer !== undefined) { + if (typeof SharedArrayBuffer === 'function' && value instanceof SharedArrayBuffer) + return true; + try { + sharedArrayBuffer.byteLength.call(value); + return true; + } + catch (_) { + return false; + } + } + try { + emnapiExternalMemory.intrinsics.arrayBuffer.byteLength.call(value); + return false; + } + catch (_) { } + return Object.prototype.toString.call(value) === '[object SharedArrayBuffer]'; + }, + isDetachedArrayBuffer: function (arrayBuffer) { + if (emnapiExternalMemory.bufferByteLength(arrayBuffer) === 0) { + try { + new Uint8Array(arrayBuffer); + } + catch (_) { + return true; + } + } + return false; + }, + bufferByteLength: function (buffer) { + var _a; + var intrinsics = emnapiExternalMemory.intrinsics; + try { + return intrinsics.arrayBuffer.byteLength.call(buffer); + } + catch (err) { + var sharedArrayBuffer = intrinsics.sharedArrayBuffer; + if (sharedArrayBuffer !== undefined) { + return sharedArrayBuffer.byteLength.call(buffer); + } + var proto = Object.getPrototypeOf(buffer); + var get = proto !== null && proto !== undefined + ? (_a = Object.getOwnPropertyDescriptor(proto, 'byteLength')) === null || _a === void 0 ? void 0 : _a.get + : undefined; + if (get === undefined) + throw err; + return get.call(buffer); + } + }, + viewBuffer: function (view) { + var intrinsics = emnapiExternalMemory.intrinsics; + return intrinsics.typedArray.tag.call(view) === undefined + ? intrinsics.dataView.buffer.call(view) + : intrinsics.typedArray.buffer.call(view); + }, + viewByteOffset: function (view) { + var intrinsics = emnapiExternalMemory.intrinsics; + return intrinsics.typedArray.tag.call(view) === undefined + ? intrinsics.dataView.byteOffset.call(view) + : intrinsics.typedArray.byteOffset.call(view); + }, + viewLength: function (view) { + var intrinsics = emnapiExternalMemory.intrinsics; + return intrinsics.typedArray.tag.call(view) === undefined + ? intrinsics.dataView.byteLength.call(view) + : intrinsics.typedArray.length.call(view); + }, + getBufferFrom: function () { + var _a; + return (_a = emnapiExternalMemory.intrinsics.bufferFrom) !== null && _a !== void 0 ? _a : (emnapiExternalMemory.intrinsics.bufferFrom = emnapiCtx.feature.Buffer.from); + }, + getArrayBufferPointer: function (arrayBuffer, shouldCopy) { + var _a; + var info = { + address: 0, + ownership: 0, + runtimeAllocated: 0 + }; + if (arrayBuffer === wasmMemory.buffer) { + return info; + } + var isDetached = emnapiExternalMemory.isDetachedArrayBuffer(arrayBuffer); + if (emnapiExternalMemory.table.has(arrayBuffer)) { + var cachedInfo = emnapiExternalMemory.table.get(arrayBuffer); + if (isDetached) { + cachedInfo.address = 0; + return cachedInfo; + } + if (shouldCopy && cachedInfo.ownership === 0 && cachedInfo.runtimeAllocated === 1) { + new Uint8Array(wasmMemory.buffer).set(new Uint8Array(arrayBuffer), cachedInfo.address); + } + return cachedInfo; + } + var byteLength = emnapiExternalMemory.bufferByteLength(arrayBuffer); + if (isDetached || (byteLength === 0)) { + return info; + } + if (!shouldCopy) { + return info; + } + var pointer = _malloc(byteLength); + if (!pointer) + throw new Error('Out of memory'); + pointer >>>= 0; + new Uint8Array(wasmMemory.buffer).set(new Uint8Array(arrayBuffer), pointer); + info.address = pointer; + info.ownership = emnapiExternalMemory.registry ? 0 : 1; + info.runtimeAllocated = 1; + emnapiExternalMemory.table.set(arrayBuffer, info); + (_a = emnapiExternalMemory.registry) === null || _a === void 0 ? void 0 : _a.register(arrayBuffer, pointer); + return info; + }, + getOrUpdateMemoryView: function (view) { + var intrinsics = emnapiExternalMemory.intrinsics; + var tag = intrinsics.typedArray.tag.call(view); + var isDataView = tag === undefined; + var buffer = isDataView ? intrinsics.dataView.buffer.call(view) : intrinsics.typedArray.buffer.call(view); + if (buffer === wasmMemory.buffer) { + if (!emnapiExternalMemory.wasmMemoryViewTable.has(view)) { + emnapiExternalMemory.wasmMemoryViewTable.set(view, { + Ctor: isDataView ? DataView : intrinsics.ctors[tag], + address: isDataView ? intrinsics.dataView.byteOffset.call(view) : intrinsics.typedArray.byteOffset.call(view), + length: isDataView ? intrinsics.dataView.byteLength.call(view) : intrinsics.typedArray.length.call(view), + ownership: 1, + runtimeAllocated: 0 + }); + } + return view; + } + var maybeOldWasmMemory = emnapiExternalMemory.isDetachedArrayBuffer(buffer) || emnapiExternalMemory.isSharedArrayBuffer(buffer); + if (maybeOldWasmMemory && emnapiExternalMemory.wasmMemoryViewTable.has(view)) { + var info = emnapiExternalMemory.wasmMemoryViewTable.get(view); + var Ctor = info.Ctor; + var newView = void 0; + var Buffer_1 = emnapiCtx.feature.Buffer; + if (typeof Buffer_1 === 'function' && Ctor === Buffer_1) { + newView = emnapiExternalMemory.getBufferFrom()(wasmMemory.buffer, info.address, info.length); + } + else { + newView = new Ctor(wasmMemory.buffer, info.address, info.length); + } + emnapiExternalMemory.wasmMemoryViewTable.set(newView, info); + return newView; + } + return view; + }, + getViewPointer: function (view, shouldCopy) { + view = emnapiExternalMemory.getOrUpdateMemoryView(view); + var buffer = emnapiExternalMemory.viewBuffer(view); + if (buffer === wasmMemory.buffer) { + if (emnapiExternalMemory.wasmMemoryViewTable.has(view)) { + var _a = emnapiExternalMemory.wasmMemoryViewTable.get(view), address_1 = _a.address, ownership_1 = _a.ownership, runtimeAllocated_1 = _a.runtimeAllocated; + return { address: address_1, ownership: ownership_1, runtimeAllocated: runtimeAllocated_1, view: view }; + } + return { address: emnapiExternalMemory.viewByteOffset(view), ownership: 1, runtimeAllocated: 0, view: view }; + } + var _b = emnapiExternalMemory.getArrayBufferPointer(buffer, shouldCopy), address = _b.address, ownership = _b.ownership, runtimeAllocated = _b.runtimeAllocated; + return { address: address === 0 ? 0 : (address + emnapiExternalMemory.viewByteOffset(view)), ownership: ownership, runtimeAllocated: runtimeAllocated, view: view }; + } + }; + var emnapiExternalSAB = { + registry: undefined, + handleTable: new WeakMap(), + init: function () { + emnapiExternalSAB.handleTable = new WeakMap(); + emnapiExternalSAB.registry = typeof FinalizationRegistry === 'function' + ? new FinalizationRegistry(function (metaPtr) { + emnapiExternalSAB.release(metaPtr); + }) + : undefined; + }, + allocMeta: function (external_data, byte_length, finalize_cb, finalize_data, finalize_hint) { + var size = 4 * 6; + var metaPtr = _malloc(size); + if (!metaPtr) + throw new Error('Out of memory'); + metaPtr >>>= 0; + Atomics.store(new Int32Array(wasmMemory.buffer, metaPtr, 1), 0, 1); + var HEAP_DATA_VIEW = new DataView(wasmMemory.buffer), GET_HEAP_DATA_VIEW = function () { return HEAP_DATA_VIEW.buffer === wasmMemory.buffer ? HEAP_DATA_VIEW : (HEAP_DATA_VIEW = new DataView(wasmMemory.buffer)); }; + GET_HEAP_DATA_VIEW().setUint32(metaPtr + 4, external_data, true); + GET_HEAP_DATA_VIEW().setUint32(metaPtr + 8, byte_length, true); + GET_HEAP_DATA_VIEW().setUint32(metaPtr + 12, finalize_cb, true); + GET_HEAP_DATA_VIEW().setUint32(metaPtr + 16, finalize_data, true); + GET_HEAP_DATA_VIEW().setUint32(metaPtr + 20, finalize_hint, true); + return metaPtr; + }, + readMeta: function (metaPtr) { + var HEAP_DATA_VIEW = new DataView(wasmMemory.buffer), GET_HEAP_DATA_VIEW = function () { return HEAP_DATA_VIEW.buffer === wasmMemory.buffer ? HEAP_DATA_VIEW : (HEAP_DATA_VIEW = new DataView(wasmMemory.buffer)); }; + var external_data = GET_HEAP_DATA_VIEW().getUint32(metaPtr + 4, true); + var byte_length = GET_HEAP_DATA_VIEW().getUint32(metaPtr + 8, true); + var finalize_cb = GET_HEAP_DATA_VIEW().getUint32(metaPtr + 12, true); + var finalize_data = GET_HEAP_DATA_VIEW().getUint32(metaPtr + 16, true); + var finalize_hint = GET_HEAP_DATA_VIEW().getUint32(metaPtr + 20, true); + return { external_data: external_data, byte_length: byte_length, finalize_cb: finalize_cb, finalize_data: finalize_data, finalize_hint: finalize_hint }; + }, + release: function (metaPtr) { + var oldRefcount = Atomics.sub(new Int32Array(wasmMemory.buffer, metaPtr, 1), 0, 1); + if (oldRefcount === 1) { + var info = emnapiExternalSAB.readMeta(metaPtr); + var finalize_cb = info.finalize_cb; + if (finalize_cb) { + var finalize_data = info.finalize_data; + var finalize_hint = info.finalize_hint; + (wasmTable.get(finalize_cb))(finalize_data, finalize_hint); + } + _free(metaPtr); + } + } + }; + var emnapiString = { + utf8Decoder: undefined, + utf16Decoder: undefined, + init: function () { + var fallbackDecoder = { + decode: function (bytes) { + var inputIndex = 0; + var pendingSize = Math.min(0x1000, bytes.length + 1); + var pending = new Uint16Array(pendingSize); + var chunks = []; + var pendingIndex = 0; + for (;;) { + var more = inputIndex < bytes.length; + if (!more || (pendingIndex >= pendingSize - 1)) { + var subarray = pending.subarray(0, pendingIndex); + var arraylike = subarray; + chunks.push(String.fromCharCode.apply(null, arraylike)); + if (!more) { + return chunks.join(''); + } + bytes = bytes.subarray(inputIndex); + inputIndex = 0; + pendingIndex = 0; + } + var byte1 = bytes[inputIndex++]; + if ((byte1 & 0x80) === 0) { + pending[pendingIndex++] = byte1; + } + else if ((byte1 & 0xe0) === 0xc0) { + var byte2 = bytes[inputIndex++] & 0x3f; + pending[pendingIndex++] = ((byte1 & 0x1f) << 6) | byte2; + } + else if ((byte1 & 0xf0) === 0xe0) { + var byte2 = bytes[inputIndex++] & 0x3f; + var byte3 = bytes[inputIndex++] & 0x3f; + pending[pendingIndex++] = ((byte1 & 0x1f) << 12) | (byte2 << 6) | byte3; + } + else if ((byte1 & 0xf8) === 0xf0) { + var byte2 = bytes[inputIndex++] & 0x3f; + var byte3 = bytes[inputIndex++] & 0x3f; + var byte4 = bytes[inputIndex++] & 0x3f; + var codepoint = ((byte1 & 0x07) << 0x12) | (byte2 << 0x0c) | (byte3 << 0x06) | byte4; + if (codepoint > 0xffff) { + codepoint -= 0x10000; + pending[pendingIndex++] = (codepoint >>> 10) & 0x3ff | 0xd800; + codepoint = 0xdc00 | codepoint & 0x3ff; + } + pending[pendingIndex++] = codepoint; + } + else ; + } + } + }; + var utf8Decoder; + utf8Decoder = typeof TextDecoder === 'function' ? new TextDecoder() : fallbackDecoder; + emnapiString.utf8Decoder = utf8Decoder; + var fallbackDecoder2 = { + decode: function (input) { + var bytes = new Uint16Array(input.buffer, input.byteOffset, input.byteLength / 2); + if (bytes.length <= 0x1000) { + return String.fromCharCode.apply(null, bytes); + } + var chunks = []; + var i = 0; + var len = 0; + for (; i < bytes.length; i += len) { + len = Math.min(0x1000, bytes.length - i); + chunks.push(String.fromCharCode.apply(null, bytes.subarray(i, i + len))); + } + return chunks.join(''); + } + }; + var utf16Decoder; + utf16Decoder = typeof TextDecoder === 'function' ? new TextDecoder('utf-16le') : fallbackDecoder2; + emnapiString.utf16Decoder = utf16Decoder; + }, + lengthBytesUTF8: function (str) { + var c; + var len = 0; + for (var i = 0; i < str.length; ++i) { + c = str.charCodeAt(i); + if (c <= 0x7F) { + len++; + } + else if (c <= 0x7FF) { + len += 2; + } + else if (c >= 0xD800 && c <= 0xDFFF) { + len += 4; + ++i; + } + else { + len += 3; + } + } + return len; + }, + UTF8ToString: function (ptr, length) { + if (!ptr || !length) + return ''; + ptr >>>= 0; + var HEAPU8 = new Uint8Array(wasmMemory.buffer); + var end = ptr; + if (length === -1 || length === 4294967295) { + for (; HEAPU8[end];) + ++end; + } + else { + end = ptr + (length >>> 0); + } + length = end - ptr; + if (length <= 16) { + var idx = ptr; + var str = ''; + while (idx < end) { + var u0 = HEAPU8[idx++]; + if (!(u0 & 0x80)) { + str += String.fromCharCode(u0); + continue; + } + var u1 = HEAPU8[idx++] & 63; + if ((u0 & 0xE0) === 0xC0) { + str += String.fromCharCode(((u0 & 31) << 6) | u1); + continue; + } + var u2 = HEAPU8[idx++] & 63; + if ((u0 & 0xF0) === 0xE0) { + u0 = ((u0 & 15) << 12) | (u1 << 6) | u2; + } + else { + u0 = ((u0 & 7) << 18) | (u1 << 12) | (u2 << 6) | (HEAPU8[idx++] & 63); + } + if (u0 < 0x10000) { + str += String.fromCharCode(u0); + } + else { + var ch = u0 - 0x10000; + str += String.fromCharCode(0xD800 | (ch >> 10), 0xDC00 | (ch & 0x3FF)); + } + } + return str; + } + return emnapiString.utf8Decoder.decode(((typeof SharedArrayBuffer === "function" && HEAPU8.buffer instanceof SharedArrayBuffer) || (Object.prototype.toString.call(HEAPU8.buffer) === "[object SharedArrayBuffer]")) ? HEAPU8.slice(ptr, end) : HEAPU8.subarray(ptr, end)); + }, + stringToUTF8: function (str, outPtr, maxBytesToWrite) { + var HEAPU8 = new Uint8Array(wasmMemory.buffer); + var outIdx = outPtr; + outIdx >>>= 0; + if (!(maxBytesToWrite > 0)) { + return 0; + } + var startIdx = outIdx; + var endIdx = outIdx + maxBytesToWrite - 1; + for (var i = 0; i < str.length; ++i) { + var u = str.charCodeAt(i); + if (u >= 0xD800 && u <= 0xDFFF) { + var u1 = str.charCodeAt(++i); + u = 0x10000 + ((u & 0x3FF) << 10) | (u1 & 0x3FF); + } + if (u <= 0x7F) { + if (outIdx >= endIdx) + break; + HEAPU8[outIdx++] = u; + } + else if (u <= 0x7FF) { + if (outIdx + 1 >= endIdx) + break; + HEAPU8[outIdx++] = 0xC0 | (u >> 6); + HEAPU8[outIdx++] = 0x80 | (u & 63); + } + else if (u <= 0xFFFF) { + if (outIdx + 2 >= endIdx) + break; + HEAPU8[outIdx++] = 0xE0 | (u >> 12); + HEAPU8[outIdx++] = 0x80 | ((u >> 6) & 63); + HEAPU8[outIdx++] = 0x80 | (u & 63); + } + else { + if (outIdx + 3 >= endIdx) + break; + HEAPU8[outIdx++] = 0xF0 | (u >> 18); + HEAPU8[outIdx++] = 0x80 | ((u >> 12) & 63); + HEAPU8[outIdx++] = 0x80 | ((u >> 6) & 63); + HEAPU8[outIdx++] = 0x80 | (u & 63); + } + } + HEAPU8[outIdx] = 0; + return outIdx - startIdx; + }, + UTF16ToString: function (ptr, length) { + if (!ptr || !length) + return ''; + ptr >>>= 0; + var end = ptr; + if (length === -1 || length === 4294967295) { + var idx = end >>> 1; + var HEAPU16 = new Uint16Array(wasmMemory.buffer); + while (HEAPU16[idx]) + ++idx; + end = (idx << 1) >>> 0; + } + else { + end = ptr + (length >>> 0) * 2; + } + length = end - ptr; + if (length <= 32) { + return String.fromCharCode.apply(null, new Uint16Array(wasmMemory.buffer, ptr, length / 2)); + } + var HEAPU8 = new Uint8Array(wasmMemory.buffer); + return emnapiString.utf16Decoder.decode(((typeof SharedArrayBuffer === "function" && HEAPU8.buffer instanceof SharedArrayBuffer) || (Object.prototype.toString.call(HEAPU8.buffer) === "[object SharedArrayBuffer]")) ? HEAPU8.slice(ptr, end) : HEAPU8.subarray(ptr, end)); + }, + stringToUTF16: function (str, outPtr, maxBytesToWrite) { + if (maxBytesToWrite === undefined) { + maxBytesToWrite = 0x7FFFFFFF; + } + if (maxBytesToWrite < 2) + return 0; + maxBytesToWrite -= 2; + var startPtr = outPtr; + var numCharsToWrite = (maxBytesToWrite < str.length * 2) ? (maxBytesToWrite / 2) : str.length; + var HEAP_DATA_VIEW = new DataView(wasmMemory.buffer), GET_HEAP_DATA_VIEW = function () { return HEAP_DATA_VIEW.buffer === wasmMemory.buffer ? HEAP_DATA_VIEW : (HEAP_DATA_VIEW = new DataView(wasmMemory.buffer)); }; + for (var i = 0; i < numCharsToWrite; ++i) { + var codeUnit = str.charCodeAt(i); + GET_HEAP_DATA_VIEW().setInt16(outPtr, codeUnit, true); + outPtr += 2; + } + GET_HEAP_DATA_VIEW().setInt16(outPtr, 0, true); + return outPtr - startPtr; + }, + newString: function (env, str, length, result, stringMaker) { + length >>>= 0; + if (!env) + return 1; + var envObject = emnapiCtx.envStore.get(env); + envObject.checkGCAccess(); + var autoLength = length === -1 || length === 4294967295; + var sizelength = length >>> 0; + if (length !== 0) { + if (!str) + return envObject.setLastError(1); + } + if (!result) + return envObject.setLastError(1); + if (!(autoLength || (sizelength <= 2147483647))) + return envObject.setLastError(1); + str >>>= 0; + var strValue = stringMaker(str, autoLength, sizelength); + result >>>= 0; + var value = emnapiCtx.addToCurrentScope(strValue).id; + var HEAP_DATA_VIEW = new DataView(wasmMemory.buffer), GET_HEAP_DATA_VIEW = function () { return HEAP_DATA_VIEW.buffer === wasmMemory.buffer ? HEAP_DATA_VIEW : (HEAP_DATA_VIEW = new DataView(wasmMemory.buffer)); }; + GET_HEAP_DATA_VIEW().setUint32(result, value, true); + return envObject.clearLastError(); + }, + newExternalString: function (env, str, length, finalize_callback, finalize_hint, result, copied, createApi, stringMaker) { + length >>>= 0; + if (!env) + return 1; + var envObject = emnapiCtx.envStore.get(env); + envObject.checkGCAccess(); + var autoLength = length === -1 || length === 4294967295; + var sizelength = length >>> 0; + if (length !== 0) { + if (!str) + return envObject.setLastError(1); + } + if (!result) + return envObject.setLastError(1); + if (!(autoLength || (sizelength <= 2147483647))) + return envObject.setLastError(1); + var status = createApi(env, str, length, result); + if (status === 0) { + if (copied) { + var HEAP_DATA_VIEW = new DataView(wasmMemory.buffer), GET_HEAP_DATA_VIEW = function () { return HEAP_DATA_VIEW.buffer === wasmMemory.buffer ? HEAP_DATA_VIEW : (HEAP_DATA_VIEW = new DataView(wasmMemory.buffer)); }; + GET_HEAP_DATA_VIEW().setInt8(copied, 1, true); + } + if (finalize_callback) { + envObject.callFinalizer(finalize_callback, str, finalize_hint); + } + } + return status; + } + }; + function napi_get_array_length(env, value, result) { + if (!env) + return 1; + var envObject = emnapiCtx.envStore.get(env); + envObject.checkGCAccess(); + if (!envObject.tryCatch.isEmpty()) + return envObject.setLastError(10); + if (!envObject.canCallIntoJs()) + return envObject.setLastError(envObject.moduleApiVersion >= 10 ? 23 : 10); + envObject.clearLastError(); + try { + if (!value) + return envObject.setLastError(1); + if (!result) + return envObject.setLastError(1); + var handle = emnapiCtx.handleStore.get(value); + if (!handle.isArray()) { + return envObject.setLastError(8); + } + result >>>= 0; + var v = handle.value.length >>> 0; + var HEAP_DATA_VIEW = new DataView(wasmMemory.buffer), GET_HEAP_DATA_VIEW = function () { return HEAP_DATA_VIEW.buffer === wasmMemory.buffer ? HEAP_DATA_VIEW : (HEAP_DATA_VIEW = new DataView(wasmMemory.buffer)); }; + GET_HEAP_DATA_VIEW().setUint32(result, v, true); + return envObject.getReturnStatus(); + } + catch (err) { + envObject.tryCatch.setError(err); + return envObject.setLastError(10); + } + } + function napi_get_arraybuffer_info(env, arraybuffer, data, byte_length) { + if (!env) + return 1; + var envObject = emnapiCtx.envStore.get(env); + envObject.checkGCAccess(); + if (!arraybuffer) + return envObject.setLastError(1); + var handle = emnapiCtx.handleStore.get(arraybuffer); + if (!handle.isArrayBuffer() && !emnapiExternalMemory.isSharedArrayBuffer(handle.value)) { + return envObject.setLastError(1); + } + var HEAP_DATA_VIEW = new DataView(wasmMemory.buffer), GET_HEAP_DATA_VIEW = function () { return HEAP_DATA_VIEW.buffer === wasmMemory.buffer ? HEAP_DATA_VIEW : (HEAP_DATA_VIEW = new DataView(wasmMemory.buffer)); }; + if (data) { + data >>>= 0; + var p = emnapiExternalMemory.getArrayBufferPointer(handle.value, true).address; + GET_HEAP_DATA_VIEW().setUint32(data, p, true); + } + if (byte_length) { + byte_length >>>= 0; + var len = emnapiExternalMemory.bufferByteLength(handle.value); + GET_HEAP_DATA_VIEW().setUint32(byte_length, len, true); + } + return envObject.clearLastError(); + } + function node_api_set_prototype(env, object, value) { + if (!env) + return 1; + var envObject = emnapiCtx.envStore.get(env); + envObject.checkGCAccess(); + if (!envObject.tryCatch.isEmpty()) + return envObject.setLastError(10); + if (!envObject.canCallIntoJs()) + return envObject.setLastError(envObject.moduleApiVersion >= 10 ? 23 : 10); + envObject.clearLastError(); + try { + if (!value) + return envObject.setLastError(1); + var obj = emnapiCtx.handleStore.get(object).value; + if (obj == null) { + throw new TypeError('Cannot convert undefined or null to object'); + } + var type = typeof obj; + var v = void 0; + try { + v = (type === 'object' && obj !== null) || type === 'function' ? obj : Object(obj); + } + catch (_) { + return envObject.setLastError(2); + } + var val = emnapiCtx.handleStore.get(value).value; + Object.setPrototypeOf(v, val); + return envObject.getReturnStatus(); + } + catch (err) { + envObject.tryCatch.setError(err); + return envObject.setLastError(10); + } + } + function napi_get_prototype(env, value, result) { + if (!env) + return 1; + var envObject = emnapiCtx.envStore.get(env); + envObject.checkGCAccess(); + if (!envObject.tryCatch.isEmpty()) + return envObject.setLastError(10); + if (!envObject.canCallIntoJs()) + return envObject.setLastError(envObject.moduleApiVersion >= 10 ? 23 : 10); + envObject.clearLastError(); + try { + if (!value) + return envObject.setLastError(1); + if (!result) + return envObject.setLastError(1); + var handle = emnapiCtx.handleStore.get(value); + if (handle.value == null) { + throw new TypeError('Cannot convert undefined or null to object'); + } + var v = void 0; + try { + v = handle.isObject() || handle.isFunction() ? handle.value : Object(handle.value); + } + catch (_) { + return envObject.setLastError(2); + } + result >>>= 0; + var p = envObject.ensureHandleId(Object.getPrototypeOf(v)); + var HEAP_DATA_VIEW = new DataView(wasmMemory.buffer), GET_HEAP_DATA_VIEW = function () { return HEAP_DATA_VIEW.buffer === wasmMemory.buffer ? HEAP_DATA_VIEW : (HEAP_DATA_VIEW = new DataView(wasmMemory.buffer)); }; + GET_HEAP_DATA_VIEW().setUint32(result, p, true); + return envObject.getReturnStatus(); + } + catch (err) { + envObject.tryCatch.setError(err); + return envObject.setLastError(10); + } + } + function napi_get_typedarray_info(env, typedarray, type, length, data, arraybuffer, byte_offset) { + if (!env) + return 1; + var envObject = emnapiCtx.envStore.get(env); + envObject.checkGCAccess(); + if (!typedarray) + return envObject.setLastError(1); + var handle = emnapiCtx.handleStore.get(typedarray); + if (!(emnapiExternalMemory.intrinsics.isView(handle.value))) { + return envObject.setLastError(1); + } + var v = handle.value; + var HEAP_DATA_VIEW = new DataView(wasmMemory.buffer), GET_HEAP_DATA_VIEW = function () { return HEAP_DATA_VIEW.buffer === wasmMemory.buffer ? HEAP_DATA_VIEW : (HEAP_DATA_VIEW = new DataView(wasmMemory.buffer)); }; + if (type) { + type >>>= 0; + var t = void 0; + switch (emnapiExternalMemory.intrinsics.typedArray.tag.call(v)) { + case 'Int8Array': + t = 0; + break; + case 'Uint8Array': + t = 1; + break; + case 'Uint8ClampedArray': + t = 2; + break; + case 'Int16Array': + t = 3; + break; + case 'Uint16Array': + t = 4; + break; + case 'Int32Array': + t = 5; + break; + case 'Uint32Array': + t = 6; + break; + case 'Float16Array': + t = 11; + break; + case 'Float32Array': + t = 7; + break; + case 'Float64Array': + t = 8; + break; + case 'BigInt64Array': + t = 9; + break; + case 'BigUint64Array': + t = 10; + break; + default: + return envObject.setLastError(9); + } + GET_HEAP_DATA_VIEW().setInt32(type, t, true); + } + v = emnapiExternalMemory.getOrUpdateMemoryView(v); + if (length) { + length >>>= 0; + var len = emnapiExternalMemory.viewLength(v); + GET_HEAP_DATA_VIEW().setUint32(length, len, true); + } + if (data || arraybuffer) { + if (data) { + data >>>= 0; + var vp = emnapiExternalMemory.getViewPointer(v, true); + v = vp.view; + var p = vp.address; + GET_HEAP_DATA_VIEW().setUint32(data, p, true); + } + if (arraybuffer) { + arraybuffer >>>= 0; + var ab = envObject.ensureHandleId(emnapiExternalMemory.viewBuffer(v)); + GET_HEAP_DATA_VIEW().setUint32(arraybuffer, ab, true); + } + } + if (byte_offset) { + byte_offset >>>= 0; + var offset = emnapiExternalMemory.viewByteOffset(v); + GET_HEAP_DATA_VIEW().setUint32(byte_offset, offset, true); + } + return envObject.clearLastError(); + } + function napi_get_buffer_info(env, buffer, data, length) { + if (!env) + return 1; + var envObject = emnapiCtx.envStore.get(env); + envObject.checkGCAccess(); + if (!buffer) + return envObject.setLastError(1); + var handle = emnapiCtx.handleStore.get(buffer); + var Buffer = emnapiCtx.feature.Buffer; + var bool = (emnapiExternalMemory.intrinsics.isView(handle.value) || (typeof Buffer === 'function' && Buffer.isBuffer(handle.value))); + if (!bool) + return envObject.setLastError(1); + if (emnapiExternalMemory.intrinsics.typedArray.tag.call(handle.value) === undefined) { + return napi_get_dataview_info(env, buffer, length, data, 0, 0); + } + return napi_get_typedarray_info(env, buffer, 0, length, data, 0, 0); + } + function napi_get_dataview_info(env, dataview, byte_length, data, arraybuffer, byte_offset) { + if (!env) + return 1; + var envObject = emnapiCtx.envStore.get(env); + envObject.checkGCAccess(); + if (!dataview) + return envObject.setLastError(1); + var handle = emnapiCtx.handleStore.get(dataview); + if (!(emnapiExternalMemory.intrinsics.isView(handle.value)) || emnapiExternalMemory.intrinsics.typedArray.tag.call(handle.value) !== undefined) { + return envObject.setLastError(1); + } + var v = emnapiExternalMemory.getOrUpdateMemoryView(handle.value); + var HEAP_DATA_VIEW = new DataView(wasmMemory.buffer), GET_HEAP_DATA_VIEW = function () { return HEAP_DATA_VIEW.buffer === wasmMemory.buffer ? HEAP_DATA_VIEW : (HEAP_DATA_VIEW = new DataView(wasmMemory.buffer)); }; + if (byte_length) { + byte_length >>>= 0; + var len = emnapiExternalMemory.viewLength(v); + GET_HEAP_DATA_VIEW().setUint32(byte_length, len, true); + } + if (data || arraybuffer) { + if (data) { + data >>>= 0; + var vp = emnapiExternalMemory.getViewPointer(v, true); + v = vp.view; + var p = vp.address; + GET_HEAP_DATA_VIEW().setUint32(data, p, true); + } + if (arraybuffer) { + arraybuffer >>>= 0; + var ab = envObject.ensureHandleId(emnapiExternalMemory.viewBuffer(v)); + GET_HEAP_DATA_VIEW().setUint32(arraybuffer, ab, true); + } + } + if (byte_offset) { + byte_offset >>>= 0; + var offset = emnapiExternalMemory.viewByteOffset(v); + GET_HEAP_DATA_VIEW().setUint32(byte_offset, offset, true); + } + return envObject.clearLastError(); + } + function napi_get_date_value(env, value, result) { + var v; + if (!env) + return 1; + var envObject = emnapiCtx.envStore.get(env); + envObject.checkGCAccess(); + if (!envObject.tryCatch.isEmpty()) + return envObject.setLastError(10); + if (!envObject.canCallIntoJs()) + return envObject.setLastError(envObject.moduleApiVersion >= 10 ? 23 : 10); + envObject.clearLastError(); + try { + if (!value) + return envObject.setLastError(1); + if (!result) + return envObject.setLastError(1); + var handle = emnapiCtx.handleStore.get(value); + if (!handle.isDate()) { + return envObject.setLastError(1); + } + result >>>= 0; + v = handle.value.valueOf(); + var HEAP_DATA_VIEW = new DataView(wasmMemory.buffer), GET_HEAP_DATA_VIEW = function () { return HEAP_DATA_VIEW.buffer === wasmMemory.buffer ? HEAP_DATA_VIEW : (HEAP_DATA_VIEW = new DataView(wasmMemory.buffer)); }; + GET_HEAP_DATA_VIEW().setFloat64(result, v, true); + return envObject.getReturnStatus(); + } + catch (err) { + envObject.tryCatch.setError(err); + return envObject.setLastError(10); + } + } + function napi_get_value_bool(env, value, result) { + if (!env) + return 1; + var envObject = emnapiCtx.envStore.get(env); + envObject.checkGCAccess(); + if (!value) + return envObject.setLastError(1); + if (!result) + return envObject.setLastError(1); + var handle = emnapiCtx.handleStore.get(value); + if (typeof handle.value !== 'boolean') { + return envObject.setLastError(7); + } + result >>>= 0; + var r = handle.value ? 1 : 0; + var HEAP_DATA_VIEW = new DataView(wasmMemory.buffer), GET_HEAP_DATA_VIEW = function () { return HEAP_DATA_VIEW.buffer === wasmMemory.buffer ? HEAP_DATA_VIEW : (HEAP_DATA_VIEW = new DataView(wasmMemory.buffer)); }; + GET_HEAP_DATA_VIEW().setInt8(result, r, true); + return envObject.clearLastError(); + } + function napi_get_value_double(env, value, result) { + if (!env) + return 1; + var envObject = emnapiCtx.envStore.get(env); + envObject.checkGCAccess(); + if (!value) + return envObject.setLastError(1); + if (!result) + return envObject.setLastError(1); + var handle = emnapiCtx.handleStore.get(value); + if (typeof handle.value !== 'number') { + return envObject.setLastError(6); + } + result >>>= 0; + var r = handle.value; + var HEAP_DATA_VIEW = new DataView(wasmMemory.buffer), GET_HEAP_DATA_VIEW = function () { return HEAP_DATA_VIEW.buffer === wasmMemory.buffer ? HEAP_DATA_VIEW : (HEAP_DATA_VIEW = new DataView(wasmMemory.buffer)); }; + GET_HEAP_DATA_VIEW().setFloat64(result, r, true); + return envObject.clearLastError(); + } + function napi_get_value_bigint_int64(env, value, result, lossless) { + if (!env) + return 1; + var envObject = emnapiCtx.envStore.get(env); + envObject.checkGCAccess(); + if (!emnapiCtx.feature.supportBigInt) { + return envObject.setLastError(9); + } + if (!value) + return envObject.setLastError(1); + if (!result) + return envObject.setLastError(1); + if (!lossless) + return envObject.setLastError(1); + var handle = emnapiCtx.handleStore.get(value); + var numberValue = handle.value; + if (typeof numberValue !== 'bigint') { + return envObject.setLastError(6); + } + lossless >>>= 0; + result >>>= 0; + var HEAP_DATA_VIEW = new DataView(wasmMemory.buffer), GET_HEAP_DATA_VIEW = function () { return HEAP_DATA_VIEW.buffer === wasmMemory.buffer ? HEAP_DATA_VIEW : (HEAP_DATA_VIEW = new DataView(wasmMemory.buffer)); }; + if ((numberValue >= (BigInt(-1) * (BigInt(1) << BigInt(63)))) && (numberValue < (BigInt(1) << BigInt(63)))) { + GET_HEAP_DATA_VIEW().setInt8(lossless, 1, true); + } + else { + GET_HEAP_DATA_VIEW().setInt8(lossless, 0, true); + numberValue = numberValue & ((BigInt(1) << BigInt(64)) - BigInt(1)); + if (numberValue >= (BigInt(1) << BigInt(63))) { + numberValue = numberValue - (BigInt(1) << BigInt(64)); + } + } + var low = Number(numberValue & BigInt(0xffffffff)); + var high = Number(numberValue >> BigInt(32)); + GET_HEAP_DATA_VIEW().setInt32(result, low, true); + GET_HEAP_DATA_VIEW().setInt32(result + 4, high, true); + return envObject.clearLastError(); + } + function napi_get_value_bigint_uint64(env, value, result, lossless) { + if (!env) + return 1; + var envObject = emnapiCtx.envStore.get(env); + envObject.checkGCAccess(); + if (!emnapiCtx.feature.supportBigInt) { + return envObject.setLastError(9); + } + if (!value) + return envObject.setLastError(1); + if (!result) + return envObject.setLastError(1); + if (!lossless) + return envObject.setLastError(1); + var handle = emnapiCtx.handleStore.get(value); + var numberValue = handle.value; + if (typeof numberValue !== 'bigint') { + return envObject.setLastError(6); + } + lossless >>>= 0; + result >>>= 0; + var HEAP_DATA_VIEW = new DataView(wasmMemory.buffer), GET_HEAP_DATA_VIEW = function () { return HEAP_DATA_VIEW.buffer === wasmMemory.buffer ? HEAP_DATA_VIEW : (HEAP_DATA_VIEW = new DataView(wasmMemory.buffer)); }; + if ((numberValue >= BigInt(0)) && (numberValue < (BigInt(1) << BigInt(64)))) { + GET_HEAP_DATA_VIEW().setInt8(lossless, 1, true); + } + else { + GET_HEAP_DATA_VIEW().setInt8(lossless, 0, true); + numberValue = numberValue & ((BigInt(1) << BigInt(64)) - BigInt(1)); + } + var low = Number(numberValue & BigInt(0xffffffff)); + var high = Number(numberValue >> BigInt(32)); + GET_HEAP_DATA_VIEW().setUint32(result, low, true); + GET_HEAP_DATA_VIEW().setUint32(result + 4, high, true); + return envObject.clearLastError(); + } + function napi_get_value_bigint_words(env, value, sign_bit, word_count, words) { + if (!env) + return 1; + var envObject = emnapiCtx.envStore.get(env); + envObject.checkGCAccess(); + if (!emnapiCtx.feature.supportBigInt) { + return envObject.setLastError(9); + } + if (!value) + return envObject.setLastError(1); + if (!word_count) + return envObject.setLastError(1); + var handle = emnapiCtx.handleStore.get(value); + if (!handle.isBigInt()) { + return envObject.setLastError(17); + } + var isMinus = handle.value < BigInt(0); + sign_bit >>>= 0; + words >>>= 0; + word_count >>>= 0; + var HEAP_DATA_VIEW = new DataView(wasmMemory.buffer), GET_HEAP_DATA_VIEW = function () { return HEAP_DATA_VIEW.buffer === wasmMemory.buffer ? HEAP_DATA_VIEW : (HEAP_DATA_VIEW = new DataView(wasmMemory.buffer)); }; + var word_count_int = GET_HEAP_DATA_VIEW().getUint32(word_count, true); + word_count_int >>>= 0; + var wordCount = 0; + var bigintValue = isMinus ? (handle.value * BigInt(-1)) : handle.value; + while (bigintValue !== BigInt(0)) { + wordCount++; + bigintValue = bigintValue >> BigInt(64); + } + bigintValue = isMinus ? (handle.value * BigInt(-1)) : handle.value; + if (!sign_bit && !words) { + word_count_int = wordCount; + GET_HEAP_DATA_VIEW().setUint32(word_count, word_count_int, true); + } + else { + if (!sign_bit) + return envObject.setLastError(1); + if (!words) + return envObject.setLastError(1); + var wordsArr = []; + while (bigintValue !== BigInt(0)) { + var uint64 = bigintValue & ((BigInt(1) << BigInt(64)) - BigInt(1)); + wordsArr.push(uint64); + bigintValue = bigintValue >> BigInt(64); + } + var len = Math.min(word_count_int, wordsArr.length); + for (var i = 0; i < len; i++) { + var low = Number(wordsArr[i] & BigInt(0xffffffff)); + var high = Number(wordsArr[i] >> BigInt(32)); + GET_HEAP_DATA_VIEW().setUint32(words + i * 8, low, true); + GET_HEAP_DATA_VIEW().setUint32(words + (i * 8 + 4), high, true); + } + GET_HEAP_DATA_VIEW().setInt32(sign_bit, isMinus ? 1 : 0, true); + GET_HEAP_DATA_VIEW().setUint32(word_count, len, true); + } + return envObject.clearLastError(); + } + function napi_get_value_external(env, value, result) { + if (!env) + return 1; + var envObject = emnapiCtx.envStore.get(env); + envObject.checkGCAccess(); + if (!value) + return envObject.setLastError(1); + if (!result) + return envObject.setLastError(1); + var handle = emnapiCtx.handleStore.get(value); + if (!handle.isExternal()) { + return envObject.setLastError(1); + } + result >>>= 0; + var p = handle.data(); + var HEAP_DATA_VIEW = new DataView(wasmMemory.buffer), GET_HEAP_DATA_VIEW = function () { return HEAP_DATA_VIEW.buffer === wasmMemory.buffer ? HEAP_DATA_VIEW : (HEAP_DATA_VIEW = new DataView(wasmMemory.buffer)); }; + GET_HEAP_DATA_VIEW().setUint32(result, p, true); + return envObject.clearLastError(); + } + function napi_get_value_int32(env, value, result) { + if (!env) + return 1; + var envObject = emnapiCtx.envStore.get(env); + envObject.checkGCAccess(); + if (!value) + return envObject.setLastError(1); + if (!result) + return envObject.setLastError(1); + var handle = emnapiCtx.handleStore.get(value); + if (typeof handle.value !== 'number') { + return envObject.setLastError(6); + } + result >>>= 0; + var v = new Int32Array([handle.value])[0]; + var HEAP_DATA_VIEW = new DataView(wasmMemory.buffer), GET_HEAP_DATA_VIEW = function () { return HEAP_DATA_VIEW.buffer === wasmMemory.buffer ? HEAP_DATA_VIEW : (HEAP_DATA_VIEW = new DataView(wasmMemory.buffer)); }; + GET_HEAP_DATA_VIEW().setInt32(result, v, true); + return envObject.clearLastError(); + } + function napi_get_value_int64(env, value, result) { + if (!env) + return 1; + var envObject = emnapiCtx.envStore.get(env); + envObject.checkGCAccess(); + if (!value) + return envObject.setLastError(1); + if (!result) + return envObject.setLastError(1); + var handle = emnapiCtx.handleStore.get(value); + if (typeof handle.value !== 'number') { + return envObject.setLastError(6); + } + var numberValue = handle.value; + result >>>= 0; + var HEAP_DATA_VIEW = new DataView(wasmMemory.buffer), GET_HEAP_DATA_VIEW = function () { return HEAP_DATA_VIEW.buffer === wasmMemory.buffer ? HEAP_DATA_VIEW : (HEAP_DATA_VIEW = new DataView(wasmMemory.buffer)); }; + if (numberValue === Number.POSITIVE_INFINITY || numberValue === Number.NEGATIVE_INFINITY || isNaN(numberValue)) { + GET_HEAP_DATA_VIEW().setInt32(result, 0, true); + GET_HEAP_DATA_VIEW().setInt32(result + 4, 0, true); + } + else if (numberValue < -9223372036854776e3) { + GET_HEAP_DATA_VIEW().setInt32(result, 0, true); + GET_HEAP_DATA_VIEW().setInt32(result + 4, 2147483648, true); + } + else if (numberValue >= 9223372036854776000) { + GET_HEAP_DATA_VIEW().setUint32(result, 4294967295, true); + GET_HEAP_DATA_VIEW().setUint32(result + 4, 2147483647, true); + } + else { + $emnapiSetValueI64(result, Math.trunc(numberValue)); + } + return envObject.clearLastError(); + } + function napi_get_value_string_latin1(env, value, buf, buf_size, result) { + if (!env) + return 1; + var envObject = emnapiCtx.envStore.get(env); + envObject.checkGCAccess(); + if (!value) + return envObject.setLastError(1); + result >>>= 0; + buf >>>= 0; + buf_size >>>= 0; + buf_size = buf_size >>> 0; + var handle = emnapiCtx.handleStore.get(value); + if (typeof handle.value !== 'string') { + return envObject.setLastError(3); + } + var HEAP_DATA_VIEW = new DataView(wasmMemory.buffer), GET_HEAP_DATA_VIEW = function () { return HEAP_DATA_VIEW.buffer === wasmMemory.buffer ? HEAP_DATA_VIEW : (HEAP_DATA_VIEW = new DataView(wasmMemory.buffer)); }; + if (!buf) { + if (!result) + return envObject.setLastError(1); + GET_HEAP_DATA_VIEW().setUint32(result, handle.value.length, true); + } + else if (buf_size !== 0) { + var copied = 0; + var v = void 0; + for (var i = 0; i < buf_size - 1; ++i) { + v = handle.value.charCodeAt(i) & 0xff; + GET_HEAP_DATA_VIEW().setUint8(buf + i, v, true); + copied++; + } + GET_HEAP_DATA_VIEW().setUint8(buf + copied, 0, true); + if (result) { + GET_HEAP_DATA_VIEW().setUint32(result, copied, true); + } + } + else if (result) { + GET_HEAP_DATA_VIEW().setUint32(result, 0, true); + } + return envObject.clearLastError(); + } + function napi_get_value_string_utf8(env, value, buf, buf_size, result) { + if (!env) + return 1; + var envObject = emnapiCtx.envStore.get(env); + envObject.checkGCAccess(); + if (!value) + return envObject.setLastError(1); + result >>>= 0; + buf >>>= 0; + buf_size >>>= 0; + buf_size = buf_size >>> 0; + var handle = emnapiCtx.handleStore.get(value); + if (typeof handle.value !== 'string') { + return envObject.setLastError(3); + } + var HEAP_DATA_VIEW = new DataView(wasmMemory.buffer), GET_HEAP_DATA_VIEW = function () { return HEAP_DATA_VIEW.buffer === wasmMemory.buffer ? HEAP_DATA_VIEW : (HEAP_DATA_VIEW = new DataView(wasmMemory.buffer)); }; + if (!buf) { + if (!result) + return envObject.setLastError(1); + var strLength = emnapiString.lengthBytesUTF8(handle.value); + GET_HEAP_DATA_VIEW().setUint32(result, strLength, true); + } + else if (buf_size !== 0) { + var copied = emnapiString.stringToUTF8(handle.value, buf, buf_size); + if (result) { + GET_HEAP_DATA_VIEW().setUint32(result, copied, true); + } + } + else if (result) { + GET_HEAP_DATA_VIEW().setUint32(result, 0, true); + } + return envObject.clearLastError(); + } + function napi_get_value_string_utf16(env, value, buf, buf_size, result) { + if (!env) + return 1; + var envObject = emnapiCtx.envStore.get(env); + envObject.checkGCAccess(); + if (!value) + return envObject.setLastError(1); + result >>>= 0; + buf >>>= 0; + buf_size >>>= 0; + buf_size = buf_size >>> 0; + var handle = emnapiCtx.handleStore.get(value); + if (typeof handle.value !== 'string') { + return envObject.setLastError(3); + } + var HEAP_DATA_VIEW = new DataView(wasmMemory.buffer), GET_HEAP_DATA_VIEW = function () { return HEAP_DATA_VIEW.buffer === wasmMemory.buffer ? HEAP_DATA_VIEW : (HEAP_DATA_VIEW = new DataView(wasmMemory.buffer)); }; + if (!buf) { + if (!result) + return envObject.setLastError(1); + GET_HEAP_DATA_VIEW().setUint32(result, handle.value.length, true); + } + else if (buf_size !== 0) { + var copied = emnapiString.stringToUTF16(handle.value, buf, buf_size * 2); + if (result) { + GET_HEAP_DATA_VIEW().setUint32(result, copied / 2, true); + } + } + else if (result) { + GET_HEAP_DATA_VIEW().setUint32(result, 0, true); + } + return envObject.clearLastError(); + } + function napi_get_value_uint32(env, value, result) { + if (!env) + return 1; + var envObject = emnapiCtx.envStore.get(env); + envObject.checkGCAccess(); + if (!value) + return envObject.setLastError(1); + if (!result) + return envObject.setLastError(1); + var handle = emnapiCtx.handleStore.get(value); + if (typeof handle.value !== 'number') { + return envObject.setLastError(6); + } + result >>>= 0; + var v = new Uint32Array([handle.value])[0]; + var HEAP_DATA_VIEW = new DataView(wasmMemory.buffer), GET_HEAP_DATA_VIEW = function () { return HEAP_DATA_VIEW.buffer === wasmMemory.buffer ? HEAP_DATA_VIEW : (HEAP_DATA_VIEW = new DataView(wasmMemory.buffer)); }; + GET_HEAP_DATA_VIEW().setUint32(result, v, true); + return envObject.clearLastError(); + } + var convert2cMod = Object.freeze({ + __proto__: null, + napi_get_array_length: napi_get_array_length, + napi_get_arraybuffer_info: napi_get_arraybuffer_info, + napi_get_buffer_info: napi_get_buffer_info, + napi_get_dataview_info: napi_get_dataview_info, + napi_get_date_value: napi_get_date_value, + napi_get_prototype: napi_get_prototype, + napi_get_typedarray_info: napi_get_typedarray_info, + napi_get_value_bigint_int64: napi_get_value_bigint_int64, + napi_get_value_bigint_uint64: napi_get_value_bigint_uint64, + napi_get_value_bigint_words: napi_get_value_bigint_words, + napi_get_value_bool: napi_get_value_bool, + napi_get_value_double: napi_get_value_double, + napi_get_value_external: napi_get_value_external, + napi_get_value_int32: napi_get_value_int32, + napi_get_value_int64: napi_get_value_int64, + napi_get_value_string_latin1: napi_get_value_string_latin1, + napi_get_value_string_utf16: napi_get_value_string_utf16, + napi_get_value_string_utf8: napi_get_value_string_utf8, + napi_get_value_uint32: napi_get_value_uint32, + node_api_set_prototype: node_api_set_prototype + }); + function napi_create_int32(env, value, result) { + if (!env) + return 1; + var envObject = emnapiCtx.envStore.get(env); + envObject.checkGCAccess(); + if (!result) + return envObject.setLastError(1); + result >>>= 0; + var v = emnapiCtx.addToCurrentScope(value).id; + var HEAP_DATA_VIEW = new DataView(wasmMemory.buffer), GET_HEAP_DATA_VIEW = function () { return HEAP_DATA_VIEW.buffer === wasmMemory.buffer ? HEAP_DATA_VIEW : (HEAP_DATA_VIEW = new DataView(wasmMemory.buffer)); }; + GET_HEAP_DATA_VIEW().setUint32(result, v, true); + return envObject.clearLastError(); + } + function napi_create_uint32(env, value, result) { + if (!env) + return 1; + var envObject = emnapiCtx.envStore.get(env); + envObject.checkGCAccess(); + if (!result) + return envObject.setLastError(1); + result >>>= 0; + var v = emnapiCtx.addToCurrentScope(value >>> 0).id; + var HEAP_DATA_VIEW = new DataView(wasmMemory.buffer), GET_HEAP_DATA_VIEW = function () { return HEAP_DATA_VIEW.buffer === wasmMemory.buffer ? HEAP_DATA_VIEW : (HEAP_DATA_VIEW = new DataView(wasmMemory.buffer)); }; + GET_HEAP_DATA_VIEW().setUint32(result, v, true); + return envObject.clearLastError(); + } + function napi_create_int64(env, low, high, result) { + if (!env) + return 1; + var envObject = emnapiCtx.envStore.get(env); + envObject.checkGCAccess(); + var value; + if (!high) + return envObject.setLastError(1); + value = Number(low); + var v1 = emnapiCtx.addToCurrentScope(value).id; + high >>>= 0; + var HEAP_DATA_VIEW = new DataView(wasmMemory.buffer), GET_HEAP_DATA_VIEW = function () { return HEAP_DATA_VIEW.buffer === wasmMemory.buffer ? HEAP_DATA_VIEW : (HEAP_DATA_VIEW = new DataView(wasmMemory.buffer)); }; + GET_HEAP_DATA_VIEW().setUint32(high, v1, true); + return envObject.clearLastError(); + } + function napi_create_double(env, value, result) { + if (!env) + return 1; + var envObject = emnapiCtx.envStore.get(env); + envObject.checkGCAccess(); + if (!result) + return envObject.setLastError(1); + result >>>= 0; + var v = emnapiCtx.addToCurrentScope(value).id; + var HEAP_DATA_VIEW = new DataView(wasmMemory.buffer), GET_HEAP_DATA_VIEW = function () { return HEAP_DATA_VIEW.buffer === wasmMemory.buffer ? HEAP_DATA_VIEW : (HEAP_DATA_VIEW = new DataView(wasmMemory.buffer)); }; + GET_HEAP_DATA_VIEW().setUint32(result, v, true); + return envObject.clearLastError(); + } + function napi_create_string_latin1(env, str, length, result) { + return emnapiString.newString(env, str, length, result, function (str, autoLength, sizeLength) { + var latin1String = ''; + var len = 0; + var HEAP_DATA_VIEW = new DataView(wasmMemory.buffer), GET_HEAP_DATA_VIEW = function () { return HEAP_DATA_VIEW.buffer === wasmMemory.buffer ? HEAP_DATA_VIEW : (HEAP_DATA_VIEW = new DataView(wasmMemory.buffer)); }; + if (autoLength) { + while (true) { + var ch = GET_HEAP_DATA_VIEW().getUint8(str, true); + if (!ch) + break; + latin1String += String.fromCharCode(ch); + str++; + } + } + else { + while (len < sizeLength) { + var ch = GET_HEAP_DATA_VIEW().getUint8(str, true); + if (!ch) + break; + latin1String += String.fromCharCode(ch); + len++; + str++; + } + } + return latin1String; + }); + } + function napi_create_string_utf16(env, str, length, result) { + return emnapiString.newString(env, str, length, result, function (str) { + return emnapiString.UTF16ToString(str, length); + }); + } + function napi_create_string_utf8(env, str, length, result) { + return emnapiString.newString(env, str, length, result, function (str) { + return emnapiString.UTF8ToString(str, length); + }); + } + function node_api_create_external_string_latin1(env, str, length, finalize_callback, finalize_hint, result, copied) { + return emnapiString.newExternalString(env, str, length, finalize_callback, finalize_hint, result, copied, napi_create_string_latin1, undefined); + } + function node_api_create_external_string_utf16(env, str, length, finalize_callback, finalize_hint, result, copied) { + return emnapiString.newExternalString(env, str, length, finalize_callback, finalize_hint, result, copied, napi_create_string_utf16, undefined); + } + function node_api_create_property_key_latin1(env, str, length, result) { + return napi_create_string_latin1(env, str, length, result); + } + function node_api_create_property_key_utf8(env, str, length, result) { + return napi_create_string_utf8(env, str, length, result); + } + function node_api_create_property_key_utf16(env, str, length, result) { + return napi_create_string_utf16(env, str, length, result); + } + function napi_create_bigint_int64(env, low, high, result) { + if (!env) + return 1; + var envObject = emnapiCtx.envStore.get(env); + envObject.checkGCAccess(); + if (!emnapiCtx.feature.supportBigInt) { + return envObject.setLastError(9); + } + var value; + if (!high) + return envObject.setLastError(1); + value = low; + var v1 = emnapiCtx.addToCurrentScope(value).id; + high >>>= 0; + var HEAP_DATA_VIEW = new DataView(wasmMemory.buffer), GET_HEAP_DATA_VIEW = function () { return HEAP_DATA_VIEW.buffer === wasmMemory.buffer ? HEAP_DATA_VIEW : (HEAP_DATA_VIEW = new DataView(wasmMemory.buffer)); }; + GET_HEAP_DATA_VIEW().setUint32(high, v1, true); + return envObject.clearLastError(); + } + function napi_create_bigint_uint64(env, low, high, result) { + if (!env) + return 1; + var envObject = emnapiCtx.envStore.get(env); + envObject.checkGCAccess(); + if (!emnapiCtx.feature.supportBigInt) { + return envObject.setLastError(9); + } + var value; + if (!high) + return envObject.setLastError(1); + value = low & ((BigInt(1) << BigInt(64)) - BigInt(1)); + var v1 = emnapiCtx.addToCurrentScope(value).id; + high >>>= 0; + var HEAP_DATA_VIEW = new DataView(wasmMemory.buffer), GET_HEAP_DATA_VIEW = function () { return HEAP_DATA_VIEW.buffer === wasmMemory.buffer ? HEAP_DATA_VIEW : (HEAP_DATA_VIEW = new DataView(wasmMemory.buffer)); }; + GET_HEAP_DATA_VIEW().setUint32(high, v1, true); + return envObject.clearLastError(); + } + function napi_create_bigint_words(env, sign_bit, word_count, words, result) { + var v, i; + if (!env) + return 1; + var envObject = emnapiCtx.envStore.get(env); + envObject.checkGCAccess(); + if (!envObject.tryCatch.isEmpty()) + return envObject.setLastError(10); + if (!envObject.canCallIntoJs()) + return envObject.setLastError(envObject.moduleApiVersion >= 10 ? 23 : 10); + envObject.clearLastError(); + try { + if (!emnapiCtx.feature.supportBigInt) { + return envObject.setLastError(9); + } + if (!result) + return envObject.setLastError(1); + words >>>= 0; + word_count >>>= 0; + word_count = word_count >>> 0; + if (word_count > 2147483647) { + return envObject.setLastError(1); + } + if (word_count > (1024 * 1024 / (4 * 8) / 2)) { + throw new RangeError('Maximum BigInt size exceeded'); + } + var value = BigInt(0); + var HEAP_DATA_VIEW = new DataView(wasmMemory.buffer), GET_HEAP_DATA_VIEW = function () { return HEAP_DATA_VIEW.buffer === wasmMemory.buffer ? HEAP_DATA_VIEW : (HEAP_DATA_VIEW = new DataView(wasmMemory.buffer)); }; + for (i = 0; i < word_count; i++) { + var low = GET_HEAP_DATA_VIEW().getUint32(words + i * 8, true); + var high = GET_HEAP_DATA_VIEW().getUint32(words + (i * 8 + 4), true); + var wordi = BigInt(low) | (BigInt(high) << BigInt(32)); + value += wordi << BigInt(64 * i); + } + value *= ((BigInt(sign_bit) % BigInt(2) === BigInt(0)) ? BigInt(1) : BigInt(-1)); + result >>>= 0; + v = emnapiCtx.addToCurrentScope(value).id; + GET_HEAP_DATA_VIEW().setUint32(result, v, true); + return envObject.getReturnStatus(); + } + catch (err) { + envObject.tryCatch.setError(err); + return envObject.setLastError(10); + } + } + var convert2napiMod = Object.freeze({ + __proto__: null, + napi_create_bigint_int64: napi_create_bigint_int64, + napi_create_bigint_uint64: napi_create_bigint_uint64, + napi_create_bigint_words: napi_create_bigint_words, + napi_create_double: napi_create_double, + napi_create_int32: napi_create_int32, + napi_create_int64: napi_create_int64, + napi_create_string_latin1: napi_create_string_latin1, + napi_create_string_utf16: napi_create_string_utf16, + napi_create_string_utf8: napi_create_string_utf8, + napi_create_uint32: napi_create_uint32, + node_api_create_external_string_latin1: node_api_create_external_string_latin1, + node_api_create_external_string_utf16: node_api_create_external_string_utf16, + node_api_create_property_key_latin1: node_api_create_property_key_latin1, + node_api_create_property_key_utf16: node_api_create_property_key_utf16, + node_api_create_property_key_utf8: node_api_create_property_key_utf8 + }); + function emnapiCreateFunction(envObject, utf8name, length, cb, data) { + utf8name >>>= 0; + var functionName = (!utf8name || !length) ? '' : (emnapiString.UTF8ToString(utf8name, length)); + var f; + var napiCallback = (wasmTable.get(cb)); + var callback = function (envObject) { + return napiCallback(envObject.id, envObject.ctx.scopeStore.currentScope.id); + }; + var makeFunction = function (envObject, callback) { + return function () { + var scope = envObject.ctx.openScope(envObject); + var callbackInfo = scope.callbackInfo; + callbackInfo.data = data; + callbackInfo.args = arguments; + callbackInfo.thiz = this; + callbackInfo.fn = f; + try { + var napiValue = envObject.callIntoModule(callback); + return (!napiValue) ? undefined : envObject.ctx.handleStore.get(napiValue).value; + } + finally { + callbackInfo.data = 0; + callbackInfo.args = undefined; + callbackInfo.thiz = undefined; + callbackInfo.fn = undefined; + envObject.ctx.closeScope(envObject, scope); + } + }; + }; + if (functionName === '') { + f = makeFunction(envObject, callback); + return { status: 0, f: f }; + } + if (!(/^[_$a-zA-Z][_$a-zA-Z0-9]*$/.test(functionName))) { + return { status: 1, f: undefined }; + } + if (emnapiCtx.feature.supportNewFunction) { + var _ = makeFunction(envObject, callback); + try { + f = (new Function('_', 'return function ' + functionName + '(){' + + '"use strict";' + + 'return _.apply(this,arguments);' + + '};'))(_); + } + catch (_err) { + f = makeFunction(envObject, callback); + if (emnapiCtx.feature.canSetFunctionName) + Object.defineProperty(f, 'name', { value: functionName }); + } + } + else { + f = makeFunction(envObject, callback); + if (emnapiCtx.feature.canSetFunctionName) + Object.defineProperty(f, 'name', { value: functionName }); + } + return { status: 0, f: f }; + } + function emnapiDefineProperty(envObject, obj, propertyName, method, getter, setter, value, attributes, data) { + if (getter || setter) { + var localGetter = void 0; + var localSetter = void 0; + if (getter) { + localGetter = emnapiCreateFunction(envObject, 0, 0, getter, data).f; + } + if (setter) { + localSetter = emnapiCreateFunction(envObject, 0, 0, setter, data).f; + } + var desc = { + configurable: (attributes & 4) !== 0, + enumerable: (attributes & 2) !== 0, + get: localGetter, + set: localSetter + }; + Object.defineProperty(obj, propertyName, desc); + } + else if (method) { + var localMethod = emnapiCreateFunction(envObject, 0, 0, method, data).f; + var desc = { + configurable: (attributes & 4) !== 0, + enumerable: (attributes & 2) !== 0, + writable: (attributes & 1) !== 0, + value: localMethod + }; + Object.defineProperty(obj, propertyName, desc); + } + else { + var desc = { + configurable: (attributes & 4) !== 0, + enumerable: (attributes & 2) !== 0, + writable: (attributes & 1) !== 0, + value: emnapiCtx.handleStore.get(value).value + }; + Object.defineProperty(obj, propertyName, desc); + } + } + function emnapiGetHandle(js_object) { + var handle = emnapiCtx.handleStore.get(js_object); + if (!(handle.isObject() || handle.isFunction())) { + return { status: 1 }; + } + if (typeof emnapiExternalMemory !== 'undefined' && ArrayBuffer.isView(handle.value)) { + if (emnapiExternalMemory.wasmMemoryViewTable.has(handle.value)) { + handle = emnapiCtx.addToCurrentScope(emnapiExternalMemory.wasmMemoryViewTable.get(handle.value)); + } + } + return { status: 0, handle: handle }; + } + function emnapiWrap(env, js_object, native_object, finalize_cb, finalize_hint, result) { + var referenceId; + if (!env) + return 1; + var envObject = emnapiCtx.envStore.get(env); + envObject.checkGCAccess(); + if (!envObject.tryCatch.isEmpty()) + return envObject.setLastError(10); + if (!envObject.canCallIntoJs()) + return envObject.setLastError(envObject.moduleApiVersion >= 10 ? 23 : 10); + envObject.clearLastError(); + try { + if (!emnapiCtx.feature.supportFinalizer) { + if (finalize_cb) { + throw emnapiCtx.createNotSupportWeakRefError('napi_wrap', 'Parameter "finalize_cb" must be 0(NULL)'); + } + if (result) { + throw emnapiCtx.createNotSupportWeakRefError('napi_wrap', 'Parameter "result" must be 0(NULL)'); + } + } + if (!js_object) + return envObject.setLastError(1); + var handleResult = emnapiGetHandle(js_object); + if (handleResult.status !== 0) { + return envObject.setLastError(handleResult.status); + } + var handle = handleResult.handle; + if (envObject.getObjectBinding(handle.value).wrapped !== 0) { + return envObject.setLastError(1); + } + var reference = void 0; + if (result) { + if (!finalize_cb) + return envObject.setLastError(1); + reference = emnapiCtx.createReferenceWithFinalizer(envObject, handle.id, 0, 1, finalize_cb, native_object, finalize_hint); + result >>>= 0; + referenceId = reference.id; + var HEAP_DATA_VIEW = new DataView(wasmMemory.buffer), GET_HEAP_DATA_VIEW = function () { return HEAP_DATA_VIEW.buffer === wasmMemory.buffer ? HEAP_DATA_VIEW : (HEAP_DATA_VIEW = new DataView(wasmMemory.buffer)); }; + GET_HEAP_DATA_VIEW().setUint32(result, referenceId, true); + } + else { + if (finalize_cb) { + reference = emnapiCtx.createReferenceWithFinalizer(envObject, handle.id, 0, 0, finalize_cb, native_object, finalize_hint); + } + else { + reference = emnapiCtx.createReferenceWithData(envObject, handle.id, 0, 0, native_object); + } + } + envObject.getObjectBinding(handle.value).wrapped = reference.id; + return envObject.getReturnStatus(); + } + catch (err) { + envObject.tryCatch.setError(err); + return envObject.setLastError(10); + } + } + function emnapiUnwrap(env, js_object, result, action) { + var data; + if (!env) + return 1; + var envObject = emnapiCtx.envStore.get(env); + envObject.checkGCAccess(); + if (!envObject.tryCatch.isEmpty()) + return envObject.setLastError(10); + if (!envObject.canCallIntoJs()) + return envObject.setLastError(envObject.moduleApiVersion >= 10 ? 23 : 10); + envObject.clearLastError(); + try { + if (!js_object) + return envObject.setLastError(1); + if (action === 0) { + if (!result) + return envObject.setLastError(1); + } + var value = emnapiCtx.handleStore.get(js_object); + if (!(value.isObject() || value.isFunction())) { + return envObject.setLastError(1); + } + var binding = envObject.getObjectBinding(value.value); + var referenceId = binding.wrapped; + var ref = emnapiCtx.refStore.get(referenceId); + if (!ref) + return envObject.setLastError(1); + if (result) { + result >>>= 0; + data = ref.data(); + var HEAP_DATA_VIEW = new DataView(wasmMemory.buffer), GET_HEAP_DATA_VIEW = function () { return HEAP_DATA_VIEW.buffer === wasmMemory.buffer ? HEAP_DATA_VIEW : (HEAP_DATA_VIEW = new DataView(wasmMemory.buffer)); }; + GET_HEAP_DATA_VIEW().setUint32(result, data, true); + } + if (action === 1) { + binding.wrapped = 0; + if (ref.ownership() === 1) { + ref.resetFinalizer(); + } + else { + ref.dispose(); + } + } + return envObject.getReturnStatus(); + } + catch (err) { + envObject.tryCatch.setError(err); + return envObject.setLastError(10); + } + } + function napi_define_class(env, utf8name, length, constructor, callback_data, property_count, properties, result) { + var propPtr, valueHandleId, attributes; + if (!env) + return 1; + var envObject = emnapiCtx.envStore.get(env); + envObject.checkGCAccess(); + if (!envObject.tryCatch.isEmpty()) + return envObject.setLastError(10); + if (!envObject.canCallIntoJs()) + return envObject.setLastError(envObject.moduleApiVersion >= 10 ? 23 : 10); + envObject.clearLastError(); + try { + if (!result) + return envObject.setLastError(1); + if (!constructor) + return envObject.setLastError(1); + length >>>= 0; + properties >>>= 0; + property_count >>>= 0; + property_count = property_count >>> 0; + if (property_count > 0) { + if (!properties) + return envObject.setLastError(1); + } + if (!((length >= -1 && length <= 2147483647) || length === 4294967295) || (!utf8name)) { + return envObject.setLastError(1); + } + var fresult = emnapiCreateFunction(envObject, utf8name, length, constructor, callback_data); + if (fresult.status !== 0) + return envObject.setLastError(fresult.status); + var F = fresult.f; + var propertyName = void 0; + var HEAP_DATA_VIEW = new DataView(wasmMemory.buffer), GET_HEAP_DATA_VIEW = function () { return HEAP_DATA_VIEW.buffer === wasmMemory.buffer ? HEAP_DATA_VIEW : (HEAP_DATA_VIEW = new DataView(wasmMemory.buffer)); }; + for (var i = 0; i < property_count; i++) { + propPtr = properties + (i * (4 * 8)); + var utf8Name = GET_HEAP_DATA_VIEW().getUint32(propPtr, true); + var name_1 = GET_HEAP_DATA_VIEW().getUint32(propPtr + 4, true); + var method = GET_HEAP_DATA_VIEW().getUint32(propPtr + 8, true); + var getter = GET_HEAP_DATA_VIEW().getUint32(propPtr + 12, true); + var setter = GET_HEAP_DATA_VIEW().getUint32(propPtr + 16, true); + var value = GET_HEAP_DATA_VIEW().getUint32(propPtr + 20, true); + attributes = GET_HEAP_DATA_VIEW().getInt32(propPtr + 24, true); + attributes >>>= 0; + var data = GET_HEAP_DATA_VIEW().getUint32(propPtr + 28, true); + if (utf8Name) { + propertyName = emnapiString.UTF8ToString(utf8Name, -1); + } + else { + if (!name_1) { + return envObject.setLastError(4); + } + propertyName = emnapiCtx.handleStore.get(name_1).value; + if (typeof propertyName !== 'string' && typeof propertyName !== 'symbol') { + return envObject.setLastError(4); + } + } + if ((attributes & 1024) !== 0) { + emnapiDefineProperty(envObject, F, propertyName, method, getter, setter, value, attributes, data); + continue; + } + emnapiDefineProperty(envObject, F.prototype, propertyName, method, getter, setter, value, attributes, data); + } + var valueHandle = emnapiCtx.addToCurrentScope(F); + valueHandleId = valueHandle.id; + result >>>= 0; + GET_HEAP_DATA_VIEW().setUint32(result, valueHandleId, true); + return envObject.getReturnStatus(); + } + catch (err) { + envObject.tryCatch.setError(err); + return envObject.setLastError(10); + } + } + function napi_wrap(env, js_object, native_object, finalize_cb, finalize_hint, result) { + return emnapiWrap(env, js_object, native_object, finalize_cb, finalize_hint, result); + } + function napi_unwrap(env, js_object, result) { + return emnapiUnwrap(env, js_object, result, 0); + } + function napi_remove_wrap(env, js_object, result) { + return emnapiUnwrap(env, js_object, result, 1); + } + function napi_type_tag_object(env, object, type_tag) { + if (!env) + return 1; + var envObject = emnapiCtx.envStore.get(env); + envObject.checkGCAccess(); + if (!envObject.tryCatch.isEmpty()) + return envObject.setLastError(10); + if (!envObject.canCallIntoJs()) + return envObject.setLastError(envObject.moduleApiVersion >= 10 ? 23 : 10); + envObject.clearLastError(); + try { + if (!object) { + return envObject.setLastError(envObject.tryCatch.hasCaught() ? 10 : 1); + } + var value = emnapiCtx.handleStore.get(object); + if (!(value.isObject() || value.isFunction())) { + return envObject.setLastError(envObject.tryCatch.hasCaught() ? 10 : 2); + } + type_tag >>>= 0; + if (!type_tag) { + return envObject.setLastError(envObject.tryCatch.hasCaught() ? 10 : 1); + } + var binding = envObject.getObjectBinding(value.value); + if (binding.tag !== null) { + return envObject.setLastError(envObject.tryCatch.hasCaught() ? 10 : 1); + } + var tag = new Uint8Array(16); + tag.set(new Uint8Array(wasmMemory.buffer, type_tag, 16)); + binding.tag = new Uint32Array(tag.buffer); + return envObject.getReturnStatus(); + } + catch (err) { + envObject.tryCatch.setError(err); + return envObject.setLastError(10); + } + } + function napi_check_object_type_tag(env, object, type_tag, result) { + var ret = true; + if (!env) + return 1; + var envObject = emnapiCtx.envStore.get(env); + envObject.checkGCAccess(); + if (!envObject.tryCatch.isEmpty()) + return envObject.setLastError(10); + if (!envObject.canCallIntoJs()) + return envObject.setLastError(envObject.moduleApiVersion >= 10 ? 23 : 10); + envObject.clearLastError(); + try { + if (!object) { + return envObject.setLastError(envObject.tryCatch.hasCaught() ? 10 : 1); + } + var value = emnapiCtx.handleStore.get(object); + if (!(value.isObject() || value.isFunction())) { + return envObject.setLastError(envObject.tryCatch.hasCaught() ? 10 : 2); + } + if (!type_tag) { + return envObject.setLastError(envObject.tryCatch.hasCaught() ? 10 : 1); + } + if (!result) { + return envObject.setLastError(envObject.tryCatch.hasCaught() ? 10 : 1); + } + var binding = envObject.getObjectBinding(value.value); + if (binding.tag !== null) { + type_tag >>>= 0; + var tag = binding.tag; + var typeTag = new Uint32Array(wasmMemory.buffer, type_tag, 4); + ret = (tag[0] === typeTag[0] && + tag[1] === typeTag[1] && + tag[2] === typeTag[2] && + tag[3] === typeTag[3]); + } + else { + ret = false; + } + result >>>= 0; + var HEAP_DATA_VIEW = new DataView(wasmMemory.buffer), GET_HEAP_DATA_VIEW = function () { return HEAP_DATA_VIEW.buffer === wasmMemory.buffer ? HEAP_DATA_VIEW : (HEAP_DATA_VIEW = new DataView(wasmMemory.buffer)); }; + GET_HEAP_DATA_VIEW().setInt8(result, ret ? 1 : 0, true); + return envObject.getReturnStatus(); + } + catch (err) { + envObject.tryCatch.setError(err); + return envObject.setLastError(10); + } + } + function napi_add_finalizer(env, js_object, finalize_data, finalize_cb, finalize_hint, result) { + if (!env) + return 1; + var envObject = emnapiCtx.envStore.get(env); + envObject.checkGCAccess(); + if (!emnapiCtx.feature.supportFinalizer) { + return envObject.setLastError(9); + } + if (!js_object) + return envObject.setLastError(1); + if (!finalize_cb) + return envObject.setLastError(1); + var handleResult = emnapiGetHandle(js_object); + if (handleResult.status !== 0) { + return envObject.setLastError(handleResult.status); + } + var handle = handleResult.handle; + var ownership = !result ? 0 : 1; + finalize_data >>>= 0; + finalize_cb >>>= 0; + finalize_hint >>>= 0; + var reference = emnapiCtx.createReferenceWithFinalizer(envObject, handle.id, 0, ownership, finalize_cb, finalize_data, finalize_hint); + if (result) { + result >>>= 0; + var referenceId = reference.id; + var HEAP_DATA_VIEW = new DataView(wasmMemory.buffer), GET_HEAP_DATA_VIEW = function () { return HEAP_DATA_VIEW.buffer === wasmMemory.buffer ? HEAP_DATA_VIEW : (HEAP_DATA_VIEW = new DataView(wasmMemory.buffer)); }; + GET_HEAP_DATA_VIEW().setUint32(result, referenceId, true); + } + return envObject.clearLastError(); + } + function node_api_post_finalizer(env, finalize_cb, finalize_data, finalize_hint) { + if (!env) + return 1; + var envObject = emnapiCtx.envStore.get(env); + envObject.enqueueFinalizer(emnapiCtx.createTrackedFinalizer(envObject, finalize_cb, finalize_data, finalize_hint)); + return envObject.clearLastError(); + } + var wrapMod = Object.freeze({ + __proto__: null, + napi_add_finalizer: napi_add_finalizer, + napi_check_object_type_tag: napi_check_object_type_tag, + napi_define_class: napi_define_class, + napi_remove_wrap: napi_remove_wrap, + napi_type_tag_object: napi_type_tag_object, + napi_unwrap: napi_unwrap, + napi_wrap: napi_wrap, + node_api_post_finalizer: node_api_post_finalizer + }); + function emnapi_create_memory_view(env, typedarray_type, external_data, byte_length, finalize_cb, finalize_hint, result) { + var value; + if (!env) + return 1; + var envObject = emnapiCtx.envStore.get(env); + envObject.checkGCAccess(); + if (!envObject.tryCatch.isEmpty()) + return envObject.setLastError(10); + if (!envObject.canCallIntoJs()) + return envObject.setLastError(envObject.moduleApiVersion >= 10 ? 23 : 10); + envObject.clearLastError(); + try { + if (!result) + return envObject.setLastError(1); + byte_length >>>= 0; + external_data >>>= 0; + result >>>= 0; + byte_length = byte_length >>> 0; + if (!external_data) { + byte_length = 0; + } + if (byte_length > 2147483647) { + throw new RangeError('Cannot create a memory view larger than 2147483647 bytes'); + } + if ((external_data + byte_length) > wasmMemory.buffer.byteLength) { + throw new RangeError('Memory out of range'); + } + if (!emnapiCtx.feature.supportFinalizer && finalize_cb) { + throw emnapiCtx.createNotSupportWeakRefError('emnapi_create_memory_view', 'Parameter "finalize_cb" must be 0(NULL)'); + } + var viewDescriptor = void 0; + switch (typedarray_type) { + case 0: + viewDescriptor = { Ctor: Int8Array, address: external_data, length: byte_length, ownership: 1, runtimeAllocated: 0 }; + break; + case 1: + viewDescriptor = { Ctor: Uint8Array, address: external_data, length: byte_length, ownership: 1, runtimeAllocated: 0 }; + break; + case 2: + viewDescriptor = { Ctor: Uint8ClampedArray, address: external_data, length: byte_length, ownership: 1, runtimeAllocated: 0 }; + break; + case 3: + viewDescriptor = { Ctor: Int16Array, address: external_data, length: byte_length >> 1, ownership: 1, runtimeAllocated: 0 }; + break; + case 4: + viewDescriptor = { Ctor: Uint16Array, address: external_data, length: byte_length >> 1, ownership: 1, runtimeAllocated: 0 }; + break; + case 5: + viewDescriptor = { Ctor: Int32Array, address: external_data, length: byte_length >> 2, ownership: 1, runtimeAllocated: 0 }; + break; + case 6: + viewDescriptor = { Ctor: Uint32Array, address: external_data, length: byte_length >> 2, ownership: 1, runtimeAllocated: 0 }; + break; + case 7: + viewDescriptor = { Ctor: Float32Array, address: external_data, length: byte_length >> 2, ownership: 1, runtimeAllocated: 0 }; + break; + case 8: + viewDescriptor = { Ctor: Float64Array, address: external_data, length: byte_length >> 3, ownership: 1, runtimeAllocated: 0 }; + break; + case 9: + viewDescriptor = { Ctor: BigInt64Array, address: external_data, length: byte_length >> 3, ownership: 1, runtimeAllocated: 0 }; + break; + case 10: + viewDescriptor = { Ctor: BigUint64Array, address: external_data, length: byte_length >> 3, ownership: 1, runtimeAllocated: 0 }; + break; + case -1: + viewDescriptor = { Ctor: DataView, address: external_data, length: byte_length, ownership: 1, runtimeAllocated: 0 }; + break; + case 11: + if (typeof Float16Array !== 'function') { + return envObject.setLastError(1); + } + viewDescriptor = { Ctor: Float16Array, address: external_data, length: byte_length >> 1, ownership: 1, runtimeAllocated: 0 }; + break; + case -2: { + if (!emnapiCtx.feature.Buffer) { + throw emnapiCtx.createNotSupportBufferError('emnapi_create_memory_view', ''); + } + viewDescriptor = { Ctor: emnapiCtx.feature.Buffer, address: external_data, length: byte_length, ownership: 1, runtimeAllocated: 0 }; + break; + } + default: return envObject.setLastError(1); + } + var Ctor = viewDescriptor.Ctor; + var typedArray = typedarray_type === -2 + ? emnapiExternalMemory.getBufferFrom()(wasmMemory.buffer, viewDescriptor.address, viewDescriptor.length) + : new Ctor(wasmMemory.buffer, viewDescriptor.address, viewDescriptor.length); + var handle = emnapiCtx.addToCurrentScope(typedArray); + emnapiExternalMemory.wasmMemoryViewTable.set(typedArray, viewDescriptor); + if (finalize_cb) { + var status_1 = napi_add_finalizer(env, handle.id, external_data, finalize_cb, finalize_hint, 0); + if (status_1 === 10) { + var err = envObject.tryCatch.extractException(); + envObject.clearLastError(); + throw err; + } + else if (status_1 !== 0) { + return envObject.setLastError(status_1); + } + } + value = handle.id; + var HEAP_DATA_VIEW = new DataView(wasmMemory.buffer), GET_HEAP_DATA_VIEW = function () { return HEAP_DATA_VIEW.buffer === wasmMemory.buffer ? HEAP_DATA_VIEW : (HEAP_DATA_VIEW = new DataView(wasmMemory.buffer)); }; + GET_HEAP_DATA_VIEW().setUint32(result, value, true); + return envObject.getReturnStatus(); + } + catch (err) { + envObject.tryCatch.setError(err); + return envObject.setLastError(10); + } + } + function emnapi_is_support_weakref() { + return emnapiCtx.feature.supportFinalizer ? 1 : 0; + } + function emnapi_is_support_bigint() { + return emnapiCtx.feature.supportBigInt ? 1 : 0; + } + function emnapi_is_node_binding_available() { + return emnapiNodeBinding ? 1 : 0; + } + function $emnapiSyncMemory(js_to_wasm, arrayBufferOrView, offset, len) { + offset = offset !== null && offset !== void 0 ? offset : 0; + offset = offset >>> 0; + var view; + if (arrayBufferOrView instanceof ArrayBuffer || emnapiExternalMemory.isSharedArrayBuffer(arrayBufferOrView)) { + var pointer = emnapiExternalMemory.getArrayBufferPointer(arrayBufferOrView, false).address; + if (!pointer) + throw new Error('Unknown ArrayBuffer address'); + if (typeof len !== 'number' || len === -1 || len === 4294967295) { + len = arrayBufferOrView.byteLength - offset; + } + len = len >>> 0; + if (len === 0) + return arrayBufferOrView; + view = new Uint8Array(arrayBufferOrView, offset, len); + var wasmMemoryU8 = new Uint8Array(wasmMemory.buffer); + if (!js_to_wasm) { + view.set(wasmMemoryU8.subarray(pointer, pointer + len)); + } + else { + wasmMemoryU8.set(view, pointer); + } + return arrayBufferOrView; + } + if (ArrayBuffer.isView(arrayBufferOrView)) { + var viewPointerInfo = emnapiExternalMemory.getViewPointer(arrayBufferOrView, false); + var latestView = viewPointerInfo.view; + var pointer = viewPointerInfo.address; + if (!pointer) + throw new Error('Unknown ArrayBuffer address'); + if (typeof len !== 'number' || len === -1 || len === 4294967295) { + len = latestView.byteLength - offset; + } + len = len >>> 0; + if (len === 0) + return latestView; + view = new Uint8Array(latestView.buffer, latestView.byteOffset + offset, len); + var wasmMemoryU8 = new Uint8Array(wasmMemory.buffer); + if (!js_to_wasm) { + view.set(wasmMemoryU8.subarray(pointer, pointer + len)); + } + else { + wasmMemoryU8.set(view, pointer); + } + return latestView; + } + throw new TypeError('emnapiSyncMemory expect ArrayBuffer or ArrayBufferView as first parameter'); + } + function emnapi_sync_memory(env, js_to_wasm, arraybuffer_or_view, offset, len) { + var v; + if (!env) + return 1; + var envObject = emnapiCtx.envStore.get(env); + envObject.checkGCAccess(); + if (!envObject.tryCatch.isEmpty()) + return envObject.setLastError(10); + if (!envObject.canCallIntoJs()) + return envObject.setLastError(envObject.moduleApiVersion >= 10 ? 23 : 10); + envObject.clearLastError(); + try { + if (!arraybuffer_or_view) + return envObject.setLastError(1); + arraybuffer_or_view >>>= 0; + offset >>>= 0; + len >>>= 0; + var HEAP_DATA_VIEW = new DataView(wasmMemory.buffer), GET_HEAP_DATA_VIEW = function () { return HEAP_DATA_VIEW.buffer === wasmMemory.buffer ? HEAP_DATA_VIEW : (HEAP_DATA_VIEW = new DataView(wasmMemory.buffer)); }; + var handleId = GET_HEAP_DATA_VIEW().getUint32(arraybuffer_or_view, true); + var handle = envObject.ctx.handleStore.get(handleId); + if (!handle.isArrayBuffer() && !handle.isTypedArray() && !handle.isDataView() && !emnapiExternalMemory.isSharedArrayBuffer(handle.value)) { + return envObject.setLastError(1); + } + var ret = $emnapiSyncMemory(Boolean(js_to_wasm), handle.value, offset, len); + if (handle.value !== ret) { + arraybuffer_or_view >>>= 0; + v = envObject.ensureHandleId(ret); + GET_HEAP_DATA_VIEW().setUint32(arraybuffer_or_view, v, true); + } + return envObject.getReturnStatus(); + } + catch (err) { + envObject.tryCatch.setError(err); + return envObject.setLastError(10); + } + } + function $emnapiGetMemoryAddress(arrayBufferOrView) { + var isArrayBuffer = arrayBufferOrView instanceof ArrayBuffer; + var isDataView = arrayBufferOrView instanceof DataView; + var isTypedArray = ArrayBuffer.isView(arrayBufferOrView) && !isDataView; + if (!isArrayBuffer && !isTypedArray && !isDataView && !emnapiExternalMemory.isSharedArrayBuffer(arrayBufferOrView)) { + throw new TypeError('emnapiGetMemoryAddress expect ArrayBuffer or ArrayBufferView as first parameter'); + } + var info; + if (isArrayBuffer) { + info = emnapiExternalMemory.getArrayBufferPointer(arrayBufferOrView, false); + } + else { + info = emnapiExternalMemory.getViewPointer(arrayBufferOrView, false); + } + return { + address: info.address, + ownership: info.ownership, + runtimeAllocated: info.runtimeAllocated + }; + } + function emnapi_get_memory_address(env, arraybuffer_or_view, address, ownership, runtime_allocated) { + var p, runtimeAllocated, ownershipOut; + var info; + if (!env) + return 1; + var envObject = emnapiCtx.envStore.get(env); + envObject.checkGCAccess(); + if (!envObject.tryCatch.isEmpty()) + return envObject.setLastError(10); + if (!envObject.canCallIntoJs()) + return envObject.setLastError(envObject.moduleApiVersion >= 10 ? 23 : 10); + envObject.clearLastError(); + try { + if (!arraybuffer_or_view) + return envObject.setLastError(1); + if (!address && !ownership && !runtime_allocated) { + return envObject.setLastError(1); + } + var handle = envObject.ctx.handleStore.get(arraybuffer_or_view); + info = $emnapiGetMemoryAddress(handle.value); + p = info.address; + var HEAP_DATA_VIEW = new DataView(wasmMemory.buffer), GET_HEAP_DATA_VIEW = function () { return HEAP_DATA_VIEW.buffer === wasmMemory.buffer ? HEAP_DATA_VIEW : (HEAP_DATA_VIEW = new DataView(wasmMemory.buffer)); }; + if (address) { + address >>>= 0; + GET_HEAP_DATA_VIEW().setUint32(address, p, true); + } + if (ownership) { + ownership >>>= 0; + ownershipOut = info.ownership; + GET_HEAP_DATA_VIEW().setInt32(ownership, ownershipOut, true); + } + if (runtime_allocated) { + runtime_allocated >>>= 0; + runtimeAllocated = info.runtimeAllocated; + GET_HEAP_DATA_VIEW().setInt8(runtime_allocated, runtimeAllocated, true); + } + return envObject.getReturnStatus(); + } + catch (err) { + envObject.tryCatch.setError(err); + return envObject.setLastError(10); + } + } + function emnapi_get_runtime_version(env, version) { + if (!env) + return 1; + var envObject = emnapiCtx.envStore.get(env); + if (!version) + return envObject.setLastError(1); + var runtimeVersion; + try { + runtimeVersion = emnapiCtx.getRuntimeVersions().version; + } + catch (_) { + return envObject.setLastError(9); + } + var versions = runtimeVersion.split('.') + .map(function (n) { return Number(n); }); + version >>>= 0; + var HEAP_DATA_VIEW = new DataView(wasmMemory.buffer), GET_HEAP_DATA_VIEW = function () { return HEAP_DATA_VIEW.buffer === wasmMemory.buffer ? HEAP_DATA_VIEW : (HEAP_DATA_VIEW = new DataView(wasmMemory.buffer)); }; + GET_HEAP_DATA_VIEW().setUint32(version, versions[0], true); + GET_HEAP_DATA_VIEW().setUint32(version + 4, versions[1], true); + GET_HEAP_DATA_VIEW().setUint32(version + 8, versions[2], true); + return envObject.clearLastError(); + } + function emnapi_get_external_sharedarraybuffer_handle(env, sharedarraybuffer, handle) { + if (!env) + return 1; + var envObject = emnapiCtx.envStore.get(env); + envObject.checkGCAccess(); + if (!envObject.tryCatch.isEmpty()) + return envObject.setLastError(10); + if (!envObject.canCallIntoJs()) + return envObject.setLastError(envObject.moduleApiVersion >= 10 ? 23 : 10); + envObject.clearLastError(); + try { + if (!sharedarraybuffer) + return envObject.setLastError(1); + if (!handle) + return envObject.setLastError(1); + handle >>>= 0; + var jsValue = emnapiCtx.handleStore.get(sharedarraybuffer).value; + if (!emnapiExternalMemory.isSharedArrayBuffer(jsValue)) { + return envObject.setLastError(1); + } + var metaPtr = emnapiExternalSAB.handleTable.get(jsValue); + if (metaPtr === undefined) { + return envObject.setLastError(1); + } + var HEAP_DATA_VIEW = new DataView(wasmMemory.buffer), GET_HEAP_DATA_VIEW = function () { return HEAP_DATA_VIEW.buffer === wasmMemory.buffer ? HEAP_DATA_VIEW : (HEAP_DATA_VIEW = new DataView(wasmMemory.buffer)); }; + GET_HEAP_DATA_VIEW().setUint32(handle, metaPtr, true); + return envObject.getReturnStatus(); + } + catch (err) { + envObject.tryCatch.setError(err); + return envObject.setLastError(10); + } + } + function emnapi_acquire_external_sharedarraybuffer(handle) { + handle >>>= 0; + Atomics.add(new Int32Array(wasmMemory.buffer, handle, 1), 0, 1); + } + function emnapi_release_external_sharedarraybuffer(handle) { + handle >>>= 0; + emnapiExternalSAB.release(handle); + } + function $emnapiAcquireExternalSharedArrayBuffer(handle, sab) { + if (sab != null && !emnapiExternalMemory.isSharedArrayBuffer(sab)) { + throw new TypeError('Expected a SharedArrayBuffer'); + } + if (!emnapiExternalSAB.registry) { + throw new Error('FinalizationRegistry is not supported in this environment'); + } + handle >>>= 0; + var meta = emnapiExternalSAB.readMeta(handle); + var external_data = meta.external_data; + external_data >>>= 0; + if (sab == null) { + sab = new SharedArrayBuffer(meta.byte_length); + new Uint8Array(sab).set(new Uint8Array(wasmMemory.buffer, external_data, meta.byte_length)); + } + else { + if (emnapiExternalSAB.handleTable.has(sab)) { + return sab; + } + } + Atomics.add(new Int32Array(wasmMemory.buffer, handle, 1), 0, 1); + if (!emnapiExternalMemory.table.has(sab)) { + if (external_data) { + emnapiExternalMemory.table.set(sab, { + address: external_data, + ownership: 1, + runtimeAllocated: 0 + }); + } + } + emnapiExternalSAB.handleTable.set(sab, handle); + emnapiExternalSAB.registry.register(sab, handle); + return sab; + } + var emnapiMod = Object.freeze({ + __proto__: null, + $emnapiAcquireExternalSharedArrayBuffer: $emnapiAcquireExternalSharedArrayBuffer, + $emnapiGetMemoryAddress: $emnapiGetMemoryAddress, + $emnapiSyncMemory: $emnapiSyncMemory, + emnapi_acquire_external_sharedarraybuffer: emnapi_acquire_external_sharedarraybuffer, + emnapi_create_memory_view: emnapi_create_memory_view, + emnapi_get_external_sharedarraybuffer_handle: emnapi_get_external_sharedarraybuffer_handle, + emnapi_get_memory_address: emnapi_get_memory_address, + emnapi_get_runtime_version: emnapi_get_runtime_version, + emnapi_is_node_binding_available: emnapi_is_node_binding_available, + emnapi_is_support_bigint: emnapi_is_support_bigint, + emnapi_is_support_weakref: emnapi_is_support_weakref, + emnapi_release_external_sharedarraybuffer: emnapi_release_external_sharedarraybuffer, + emnapi_sync_memory: emnapi_sync_memory + }); + function napi_create_array(env, result) { + if (!env) + return 1; + var envObject = emnapiCtx.envStore.get(env); + envObject.checkGCAccess(); + if (!result) + return envObject.setLastError(1); + result >>>= 0; + var value = emnapiCtx.addToCurrentScope([]).id; + var HEAP_DATA_VIEW = new DataView(wasmMemory.buffer), GET_HEAP_DATA_VIEW = function () { return HEAP_DATA_VIEW.buffer === wasmMemory.buffer ? HEAP_DATA_VIEW : (HEAP_DATA_VIEW = new DataView(wasmMemory.buffer)); }; + GET_HEAP_DATA_VIEW().setUint32(result, value, true); + return envObject.clearLastError(); + } + function napi_create_array_with_length(env, length, result) { + if (!env) + return 1; + var envObject = emnapiCtx.envStore.get(env); + envObject.checkGCAccess(); + if (!result) + return envObject.setLastError(1); + length >>>= 0; + result >>>= 0; + length = length >>> 0; + var value = emnapiCtx.addToCurrentScope(new Array(length)).id; + var HEAP_DATA_VIEW = new DataView(wasmMemory.buffer), GET_HEAP_DATA_VIEW = function () { return HEAP_DATA_VIEW.buffer === wasmMemory.buffer ? HEAP_DATA_VIEW : (HEAP_DATA_VIEW = new DataView(wasmMemory.buffer)); }; + GET_HEAP_DATA_VIEW().setUint32(result, value, true); + return envObject.clearLastError(); + } + function emnapiCreateArrayBuffer(byte_length, data, shared) { + byte_length >>>= 0; + byte_length = byte_length >>> 0; + var arrayBuffer = shared ? new SharedArrayBuffer(byte_length) : new ArrayBuffer(byte_length); + if (data) { + data >>>= 0; + var p = emnapiExternalMemory.getArrayBufferPointer(arrayBuffer, true).address; + var HEAP_DATA_VIEW = new DataView(wasmMemory.buffer), GET_HEAP_DATA_VIEW = function () { return HEAP_DATA_VIEW.buffer === wasmMemory.buffer ? HEAP_DATA_VIEW : (HEAP_DATA_VIEW = new DataView(wasmMemory.buffer)); }; + GET_HEAP_DATA_VIEW().setUint32(data, p, true); + } + return arrayBuffer; + } + function napi_create_arraybuffer(env, byte_length, data, result) { + var value; + if (!env) + return 1; + var envObject = emnapiCtx.envStore.get(env); + envObject.checkGCAccess(); + if (!envObject.tryCatch.isEmpty()) + return envObject.setLastError(10); + if (!envObject.canCallIntoJs()) + return envObject.setLastError(envObject.moduleApiVersion >= 10 ? 23 : 10); + envObject.clearLastError(); + try { + if (!result) + return envObject.setLastError(1); + result >>>= 0; + var arrayBuffer = emnapiCreateArrayBuffer(byte_length, data, false); + value = emnapiCtx.addToCurrentScope(arrayBuffer).id; + var HEAP_DATA_VIEW = new DataView(wasmMemory.buffer), GET_HEAP_DATA_VIEW = function () { return HEAP_DATA_VIEW.buffer === wasmMemory.buffer ? HEAP_DATA_VIEW : (HEAP_DATA_VIEW = new DataView(wasmMemory.buffer)); }; + GET_HEAP_DATA_VIEW().setUint32(result, value, true); + return envObject.getReturnStatus(); + } + catch (err) { + envObject.tryCatch.setError(err); + return envObject.setLastError(10); + } + } + function node_api_create_sharedarraybuffer(env, byte_length, data, result) { + var value; + if (!env) + return 1; + var envObject = emnapiCtx.envStore.get(env); + envObject.checkGCAccess(); + if (!envObject.tryCatch.isEmpty()) + return envObject.setLastError(10); + if (!envObject.canCallIntoJs()) + return envObject.setLastError(envObject.moduleApiVersion >= 10 ? 23 : 10); + envObject.clearLastError(); + try { + if (!result) + return envObject.setLastError(1); + result >>>= 0; + var arrayBuffer = emnapiCreateArrayBuffer(byte_length, data, true); + value = emnapiCtx.addToCurrentScope(arrayBuffer).id; + var HEAP_DATA_VIEW = new DataView(wasmMemory.buffer), GET_HEAP_DATA_VIEW = function () { return HEAP_DATA_VIEW.buffer === wasmMemory.buffer ? HEAP_DATA_VIEW : (HEAP_DATA_VIEW = new DataView(wasmMemory.buffer)); }; + GET_HEAP_DATA_VIEW().setUint32(result, value, true); + return envObject.getReturnStatus(); + } + catch (err) { + envObject.tryCatch.setError(err); + return envObject.setLastError(10); + } + } + function napi_create_date(env, time, result) { + var value; + if (!env) + return 1; + var envObject = emnapiCtx.envStore.get(env); + envObject.checkGCAccess(); + if (!envObject.tryCatch.isEmpty()) + return envObject.setLastError(10); + if (!envObject.canCallIntoJs()) + return envObject.setLastError(envObject.moduleApiVersion >= 10 ? 23 : 10); + envObject.clearLastError(); + try { + if (!result) + return envObject.setLastError(1); + result >>>= 0; + value = emnapiCtx.addToCurrentScope(new Date(time)).id; + var HEAP_DATA_VIEW = new DataView(wasmMemory.buffer), GET_HEAP_DATA_VIEW = function () { return HEAP_DATA_VIEW.buffer === wasmMemory.buffer ? HEAP_DATA_VIEW : (HEAP_DATA_VIEW = new DataView(wasmMemory.buffer)); }; + GET_HEAP_DATA_VIEW().setUint32(result, value, true); + return envObject.getReturnStatus(); + } + catch (err) { + envObject.tryCatch.setError(err); + return envObject.setLastError(10); + } + } + function napi_create_external(env, data, finalize_cb, finalize_hint, result) { + var value; + if (!env) + return 1; + var envObject = emnapiCtx.envStore.get(env); + envObject.checkGCAccess(); + if (!envObject.tryCatch.isEmpty()) + return envObject.setLastError(10); + if (!envObject.canCallIntoJs()) + return envObject.setLastError(envObject.moduleApiVersion >= 10 ? 23 : 10); + envObject.clearLastError(); + try { + if (!result) + return envObject.setLastError(1); + if (!emnapiCtx.feature.supportFinalizer && finalize_cb) { + throw emnapiCtx.createNotSupportWeakRefError('napi_create_external', 'Parameter "finalize_cb" must be 0(NULL)'); + } + var externalHandle = emnapiCtx.getCurrentScope().addExternal(data); + if (finalize_cb) { + emnapiCtx.createReferenceWithFinalizer(envObject, externalHandle.id, 0, 0, finalize_cb, data, finalize_hint); + } + result >>>= 0; + value = externalHandle.id; + var HEAP_DATA_VIEW = new DataView(wasmMemory.buffer), GET_HEAP_DATA_VIEW = function () { return HEAP_DATA_VIEW.buffer === wasmMemory.buffer ? HEAP_DATA_VIEW : (HEAP_DATA_VIEW = new DataView(wasmMemory.buffer)); }; + GET_HEAP_DATA_VIEW().setUint32(result, value, true); + return envObject.clearLastError(); + } + catch (err) { + envObject.tryCatch.setError(err); + return envObject.setLastError(10); + } + } + function napi_create_external_arraybuffer(env, external_data, byte_length, finalize_cb, finalize_hint, result) { + var value; + if (!env) + return 1; + var envObject = emnapiCtx.envStore.get(env); + envObject.checkGCAccess(); + if (!envObject.tryCatch.isEmpty()) + return envObject.setLastError(10); + if (!envObject.canCallIntoJs()) + return envObject.setLastError(envObject.moduleApiVersion >= 10 ? 23 : 10); + envObject.clearLastError(); + try { + if (!result) + return envObject.setLastError(1); + byte_length >>>= 0; + external_data >>>= 0; + result >>>= 0; + byte_length = byte_length >>> 0; + if (!external_data) { + byte_length = 0; + } + if ((external_data + byte_length) > wasmMemory.buffer.byteLength) { + throw new RangeError('Memory out of range'); + } + if (!emnapiCtx.feature.supportFinalizer && finalize_cb) { + throw emnapiCtx.createNotSupportWeakRefError('napi_create_external_arraybuffer', 'Parameter "finalize_cb" must be 0(NULL)'); + } + var arrayBuffer = new ArrayBuffer(byte_length); + if (byte_length === 0) { + try { + var MessageChannel_1 = emnapiCtx.feature.MessageChannel; + var messageChannel = new MessageChannel_1(); + messageChannel.port1.postMessage(arrayBuffer, [arrayBuffer]); + } + catch (_) { } + } + else { + var u8arr = new Uint8Array(arrayBuffer); + u8arr.set(new Uint8Array(wasmMemory.buffer).subarray(external_data, external_data + byte_length)); + emnapiExternalMemory.table.set(arrayBuffer, { + address: external_data, + ownership: 1, + runtimeAllocated: 0 + }); + } + var handle = emnapiCtx.addToCurrentScope(arrayBuffer); + if (finalize_cb) { + var status_1 = napi_add_finalizer(env, handle.id, external_data, finalize_cb, finalize_hint, 0); + if (status_1 === 10) { + var err = envObject.tryCatch.extractException(); + envObject.clearLastError(); + throw err; + } + else if (status_1 !== 0) { + return envObject.setLastError(status_1); + } + } + value = handle.id; + var HEAP_DATA_VIEW = new DataView(wasmMemory.buffer), GET_HEAP_DATA_VIEW = function () { return HEAP_DATA_VIEW.buffer === wasmMemory.buffer ? HEAP_DATA_VIEW : (HEAP_DATA_VIEW = new DataView(wasmMemory.buffer)); }; + GET_HEAP_DATA_VIEW().setUint32(result, value, true); + return envObject.getReturnStatus(); + } + catch (err) { + envObject.tryCatch.setError(err); + return envObject.setLastError(10); + } + } + function node_api_create_external_sharedarraybuffer(env, external_data, byte_length, finalize_cb, finalize_hint, result) { + var value; + if (!env) + return 1; + var envObject = emnapiCtx.envStore.get(env); + envObject.checkGCAccess(); + if (!envObject.tryCatch.isEmpty()) + return envObject.setLastError(10); + if (!envObject.canCallIntoJs()) + return envObject.setLastError(envObject.moduleApiVersion >= 10 ? 23 : 10); + envObject.clearLastError(); + try { + if (!result) + return envObject.setLastError(1); + byte_length >>>= 0; + external_data >>>= 0; + result >>>= 0; + byte_length = byte_length >>> 0; + if (!external_data) { + byte_length = 0; + } + if ((external_data + byte_length) > wasmMemory.buffer.byteLength) { + throw new RangeError('Memory out of range'); + } + if (!emnapiExternalSAB.registry && finalize_cb) { + throw emnapiCtx.createNotSupportWeakRefError('node_api_create_external_sharedarraybuffer', 'Parameter "finalize_cb" must be 0(NULL)'); + } + var sharedArrayBuffer = new SharedArrayBuffer(byte_length); + if (byte_length !== 0) { + var u8arr = new Uint8Array(sharedArrayBuffer); + u8arr.set(new Uint8Array(wasmMemory.buffer).subarray(external_data, external_data + byte_length)); + emnapiExternalMemory.table.set(sharedArrayBuffer, { + address: external_data, + ownership: 1, + runtimeAllocated: 0 + }); + } + value = emnapiCtx.addToCurrentScope(sharedArrayBuffer).id; + if (finalize_cb) { + finalize_cb >>>= 0; + finalize_hint >>>= 0; + var metaPtr = emnapiExternalSAB.allocMeta(external_data, byte_length, finalize_cb, external_data, finalize_hint); + emnapiExternalSAB.handleTable.set(sharedArrayBuffer, metaPtr); + emnapiExternalSAB.registry.register(sharedArrayBuffer, metaPtr); + } + var HEAP_DATA_VIEW = new DataView(wasmMemory.buffer), GET_HEAP_DATA_VIEW = function () { return HEAP_DATA_VIEW.buffer === wasmMemory.buffer ? HEAP_DATA_VIEW : (HEAP_DATA_VIEW = new DataView(wasmMemory.buffer)); }; + GET_HEAP_DATA_VIEW().setUint32(result, value, true); + return envObject.getReturnStatus(); + } + catch (err) { + envObject.tryCatch.setError(err); + return envObject.setLastError(10); + } + } + function napi_create_object(env, result) { + if (!env) + return 1; + var envObject = emnapiCtx.envStore.get(env); + envObject.checkGCAccess(); + if (!result) + return envObject.setLastError(1); + result >>>= 0; + var value = emnapiCtx.addToCurrentScope({}).id; + var HEAP_DATA_VIEW = new DataView(wasmMemory.buffer), GET_HEAP_DATA_VIEW = function () { return HEAP_DATA_VIEW.buffer === wasmMemory.buffer ? HEAP_DATA_VIEW : (HEAP_DATA_VIEW = new DataView(wasmMemory.buffer)); }; + GET_HEAP_DATA_VIEW().setUint32(result, value, true); + return envObject.clearLastError(); + } + function node_api_create_object_with_properties(env, prototype_or_null, property_names, property_values, property_count, result) { + if (!env) + return 1; + var envObject = emnapiCtx.envStore.get(env); + envObject.checkGCAccess(); + if (!result) + return envObject.setLastError(1); + property_count >>>= 0; + property_count = property_count >>> 0; + if (property_count > 0) { + if (!property_names) + return envObject.setLastError(1); + if (!property_values) + return envObject.setLastError(1); + } + var v8_prototype_or_null = prototype_or_null + ? emnapiCtx.handleStore.get(prototype_or_null).value + : null; + var properties = {}; + property_names >>>= 0; + property_values >>>= 0; + var HEAP_DATA_VIEW = new DataView(wasmMemory.buffer), GET_HEAP_DATA_VIEW = function () { return HEAP_DATA_VIEW.buffer === wasmMemory.buffer ? HEAP_DATA_VIEW : (HEAP_DATA_VIEW = new DataView(wasmMemory.buffer)); }; + for (var i = 0; i < property_count; i++) { + var name_value = emnapiCtx.handleStore.get(GET_HEAP_DATA_VIEW().getUint32(property_names + i * 4, true)).value; + if (!(typeof name_value === "string" || typeof name_value === "symbol")) + return envObject.setLastError(4); + properties[name_value] = { + value: emnapiCtx.handleStore.get(GET_HEAP_DATA_VIEW().getUint32(property_values + i * 4, true)).value, + writable: true, + enumerable: true, + configurable: true + }; + } + var obj; + try { + obj = Object.defineProperties(Object.create(v8_prototype_or_null), properties); + } + catch (_) { + return envObject.setLastError(9); + } + var value = emnapiCtx.addToCurrentScope(obj).id; + result >>>= 0; + GET_HEAP_DATA_VIEW().setUint32(result, value, true); + return envObject.clearLastError(); + } + function napi_create_symbol(env, description, result) { + if (!env) + return 1; + var envObject = emnapiCtx.envStore.get(env); + envObject.checkGCAccess(); + if (!result) + return envObject.setLastError(1); + result >>>= 0; + var HEAP_DATA_VIEW = new DataView(wasmMemory.buffer), GET_HEAP_DATA_VIEW = function () { return HEAP_DATA_VIEW.buffer === wasmMemory.buffer ? HEAP_DATA_VIEW : (HEAP_DATA_VIEW = new DataView(wasmMemory.buffer)); }; + if (!description) { + var value = emnapiCtx.addToCurrentScope(Symbol()).id; + GET_HEAP_DATA_VIEW().setUint32(result, value, true); + } + else { + var handle = emnapiCtx.handleStore.get(description); + var desc = handle.value; + if (typeof desc !== 'string') { + return envObject.setLastError(3); + } + var v = emnapiCtx.addToCurrentScope(Symbol(desc)).id; + GET_HEAP_DATA_VIEW().setUint32(result, v, true); + } + return envObject.clearLastError(); + } + function napi_create_typedarray(env, type, length, arraybuffer, byte_offset, result) { + var value; + if (!env) + return 1; + var envObject = emnapiCtx.envStore.get(env); + envObject.checkGCAccess(); + if (!envObject.tryCatch.isEmpty()) + return envObject.setLastError(10); + if (!envObject.canCallIntoJs()) + return envObject.setLastError(envObject.moduleApiVersion >= 10 ? 23 : 10); + envObject.clearLastError(); + try { + if (!arraybuffer) + return envObject.setLastError(1); + if (!result) + return envObject.setLastError(1); + var handle = emnapiCtx.handleStore.get(arraybuffer); + var buffer = handle.value; + byte_offset >>>= 0; + length >>>= 0; + var createTypedArray = function (envObject, Type, size_of_element, buffer, byte_offset, length) { + var _a; + byte_offset = byte_offset >>> 0; + length = length >>> 0; + if (size_of_element > 1) { + if ((byte_offset) % (size_of_element) !== 0) { + var err = new RangeError("start offset of ".concat((_a = Type.name) !== null && _a !== void 0 ? _a : '', " should be a multiple of ").concat(size_of_element)); + err.code = 'ERR_NAPI_INVALID_TYPEDARRAY_ALIGNMENT'; + envObject.tryCatch.setError(err); + return envObject.setLastError(9); + } + } + if (((length * size_of_element) + byte_offset) > buffer.byteLength) { + var err = new RangeError('Invalid typed array length'); + err.code = 'ERR_NAPI_INVALID_TYPEDARRAY_LENGTH'; + envObject.tryCatch.setError(err); + return envObject.setLastError(9); + } + var out = new Type(buffer, byte_offset, length); + if (buffer === wasmMemory.buffer) { + if (!emnapiExternalMemory.wasmMemoryViewTable.has(out)) { + emnapiExternalMemory.wasmMemoryViewTable.set(out, { + Ctor: Type, + address: byte_offset, + length: length, + ownership: 1, + runtimeAllocated: 0 + }); + } + } + result >>>= 0; + value = emnapiCtx.addToCurrentScope(out).id; + var HEAP_DATA_VIEW = new DataView(wasmMemory.buffer), GET_HEAP_DATA_VIEW = function () { return HEAP_DATA_VIEW.buffer === wasmMemory.buffer ? HEAP_DATA_VIEW : (HEAP_DATA_VIEW = new DataView(wasmMemory.buffer)); }; + GET_HEAP_DATA_VIEW().setUint32(result, value, true); + return envObject.getReturnStatus(); + }; + if (buffer instanceof ArrayBuffer || emnapiExternalMemory.isSharedArrayBuffer(buffer)) { + switch (type) { + case 0: + return createTypedArray(envObject, Int8Array, 1, buffer, byte_offset, length); + case 1: + return createTypedArray(envObject, Uint8Array, 1, buffer, byte_offset, length); + case 2: + return createTypedArray(envObject, Uint8ClampedArray, 1, buffer, byte_offset, length); + case 3: + return createTypedArray(envObject, Int16Array, 2, buffer, byte_offset, length); + case 4: + return createTypedArray(envObject, Uint16Array, 2, buffer, byte_offset, length); + case 5: + return createTypedArray(envObject, Int32Array, 4, buffer, byte_offset, length); + case 6: + return createTypedArray(envObject, Uint32Array, 4, buffer, byte_offset, length); + case 7: + return createTypedArray(envObject, Float32Array, 4, buffer, byte_offset, length); + case 8: + return createTypedArray(envObject, Float64Array, 8, buffer, byte_offset, length); + case 9: + return createTypedArray(envObject, BigInt64Array, 8, buffer, byte_offset, length); + case 10: + return createTypedArray(envObject, BigUint64Array, 8, buffer, byte_offset, length); + case 11: + if (typeof Float16Array !== 'function') { + return envObject.setLastError(1); + } + return createTypedArray(envObject, Float16Array, 2, buffer, byte_offset, length); + default: + return envObject.setLastError(1); + } + } + else { + return envObject.setLastError(1); + } + } + catch (err) { + envObject.tryCatch.setError(err); + return envObject.setLastError(10); + } + } + function napi_create_buffer(env, size, data, result) { + var _a; + var value, pointer; + if (!env) + return 1; + var envObject = emnapiCtx.envStore.get(env); + envObject.checkGCAccess(); + if (!envObject.tryCatch.isEmpty()) + return envObject.setLastError(10); + if (!envObject.canCallIntoJs()) + return envObject.setLastError(envObject.moduleApiVersion >= 10 ? 23 : 10); + envObject.clearLastError(); + try { + if (!result) + return envObject.setLastError(1); + var Buffer = emnapiCtx.feature.Buffer; + if (!Buffer) { + throw emnapiCtx.createNotSupportBufferError('napi_create_buffer', ''); + } + result >>>= 0; + var buffer = void 0; + size >>>= 0; + size = size >>> 0; + var HEAP_DATA_VIEW = new DataView(wasmMemory.buffer), GET_HEAP_DATA_VIEW = function () { return HEAP_DATA_VIEW.buffer === wasmMemory.buffer ? HEAP_DATA_VIEW : (HEAP_DATA_VIEW = new DataView(wasmMemory.buffer)); }; + if (!data || (size === 0)) { + buffer = Buffer.alloc(size); + value = emnapiCtx.addToCurrentScope(buffer).id; + GET_HEAP_DATA_VIEW().setUint32(result, value, true); + } + else { + pointer = _malloc(size); + if (!pointer) + throw new Error('Out of memory'); + pointer >>>= 0; + new Uint8Array(wasmMemory.buffer).subarray(pointer, pointer + size).fill(0); + var buffer_1 = emnapiExternalMemory.getBufferFrom()(wasmMemory.buffer, pointer, size); + var viewDescriptor = { + Ctor: Buffer, + address: pointer, + length: size, + ownership: emnapiExternalMemory.registry ? 0 : 1, + runtimeAllocated: 1 + }; + emnapiExternalMemory.wasmMemoryViewTable.set(buffer_1, viewDescriptor); + (_a = emnapiExternalMemory.registry) === null || _a === void 0 ? void 0 : _a.register(viewDescriptor, pointer); + value = emnapiCtx.addToCurrentScope(buffer_1).id; + GET_HEAP_DATA_VIEW().setUint32(result, value, true); + data >>>= 0; + GET_HEAP_DATA_VIEW().setUint32(data, pointer, true); + } + return envObject.getReturnStatus(); + } + catch (err) { + envObject.tryCatch.setError(err); + return envObject.setLastError(10); + } + } + function napi_create_buffer_copy(env, length, data, result_data, result) { + var value; + if (!env) + return 1; + var envObject = emnapiCtx.envStore.get(env); + envObject.checkGCAccess(); + if (!envObject.tryCatch.isEmpty()) + return envObject.setLastError(10); + if (!envObject.canCallIntoJs()) + return envObject.setLastError(envObject.moduleApiVersion >= 10 ? 23 : 10); + envObject.clearLastError(); + try { + if (!result) + return envObject.setLastError(1); + var Buffer = emnapiCtx.feature.Buffer; + if (!Buffer) { + throw emnapiCtx.createNotSupportBufferError('napi_create_buffer_copy', ''); + } + var arrayBuffer = emnapiCreateArrayBuffer(length, result_data, false); + var buffer = Buffer.from(arrayBuffer); + data >>>= 0; + length >>>= 0; + buffer.set(new Uint8Array(wasmMemory.buffer).subarray(data, data + length)); + value = emnapiCtx.addToCurrentScope(buffer).id; + result >>>= 0; + var HEAP_DATA_VIEW = new DataView(wasmMemory.buffer), GET_HEAP_DATA_VIEW = function () { return HEAP_DATA_VIEW.buffer === wasmMemory.buffer ? HEAP_DATA_VIEW : (HEAP_DATA_VIEW = new DataView(wasmMemory.buffer)); }; + GET_HEAP_DATA_VIEW().setUint32(result, value, true); + return envObject.getReturnStatus(); + } + catch (err) { + envObject.tryCatch.setError(err); + return envObject.setLastError(10); + } + } + function napi_create_external_buffer(env, length, data, finalize_cb, finalize_hint, result) { + return emnapi_create_memory_view(env, -2, data, length, finalize_cb, finalize_hint, result); + } + function node_api_create_buffer_from_arraybuffer(env, arraybuffer, byte_offset, byte_length, result) { + var value; + if (!env) + return 1; + var envObject = emnapiCtx.envStore.get(env); + envObject.checkGCAccess(); + if (!envObject.tryCatch.isEmpty()) + return envObject.setLastError(10); + if (!envObject.canCallIntoJs()) + return envObject.setLastError(envObject.moduleApiVersion >= 10 ? 23 : 10); + envObject.clearLastError(); + try { + if (!arraybuffer) + return envObject.setLastError(1); + if (!result) + return envObject.setLastError(1); + byte_offset >>>= 0; + byte_length >>>= 0; + byte_offset = byte_offset >>> 0; + byte_length = byte_length >>> 0; + var handle = emnapiCtx.handleStore.get(arraybuffer); + if (!handle.isArrayBuffer()) { + return envObject.setLastError(1); + } + var buffer = handle.value; + if ((byte_length + byte_offset) > buffer.byteLength) { + var err = new RangeError('The byte offset + length is out of range'); + err.code = 'ERR_OUT_OF_RANGE'; + throw err; + } + var Buffer = emnapiCtx.feature.Buffer; + if (!Buffer) { + throw emnapiCtx.createNotSupportBufferError('node_api_create_buffer_from_arraybuffer', ''); + } + var out = emnapiExternalMemory.getBufferFrom()(buffer, byte_offset, byte_length); + if (buffer === wasmMemory.buffer) { + if (!emnapiExternalMemory.wasmMemoryViewTable.has(out)) { + emnapiExternalMemory.wasmMemoryViewTable.set(out, { + Ctor: Buffer, + address: byte_offset, + length: byte_length, + ownership: 1, + runtimeAllocated: 0 + }); + } + } + result >>>= 0; + value = emnapiCtx.addToCurrentScope(out).id; + var HEAP_DATA_VIEW = new DataView(wasmMemory.buffer), GET_HEAP_DATA_VIEW = function () { return HEAP_DATA_VIEW.buffer === wasmMemory.buffer ? HEAP_DATA_VIEW : (HEAP_DATA_VIEW = new DataView(wasmMemory.buffer)); }; + GET_HEAP_DATA_VIEW().setUint32(result, value, true); + return envObject.getReturnStatus(); + } + catch (err) { + envObject.tryCatch.setError(err); + return envObject.setLastError(10); + } + } + function napi_create_dataview(env, byte_length, arraybuffer, byte_offset, result) { + if (!env) + return 1; + var envObject = emnapiCtx.envStore.get(env); + envObject.checkGCAccess(); + if (!envObject.tryCatch.isEmpty()) + return envObject.setLastError(10); + if (!envObject.canCallIntoJs()) + return envObject.setLastError(envObject.moduleApiVersion >= 10 ? 23 : 10); + envObject.clearLastError(); + try { + if (!arraybuffer) + return envObject.setLastError(1); + if (!result) + return envObject.setLastError(1); + byte_length >>>= 0; + byte_offset >>>= 0; + byte_length = byte_length >>> 0; + byte_offset = byte_offset >>> 0; + var value = emnapiCtx.handleStore.get(arraybuffer).value; + var createDataview = function (buffer) { + if ((byte_length + byte_offset) > buffer.byteLength) { + var err = new RangeError('byte_offset + byte_length should be less than or equal to the size in bytes of the array passed in'); + err.code = 'ERR_NAPI_INVALID_DATAVIEW_ARGS'; + throw err; + } + var dataview = new DataView(buffer, byte_offset, byte_length); + if (buffer === wasmMemory.buffer) { + if (!emnapiExternalMemory.wasmMemoryViewTable.has(dataview)) { + emnapiExternalMemory.wasmMemoryViewTable.set(dataview, { + Ctor: DataView, + address: byte_offset, + length: byte_length, + ownership: 1, + runtimeAllocated: 0 + }); + } + } + result >>>= 0; + var v = emnapiCtx.addToCurrentScope(dataview).id; + var HEAP_DATA_VIEW = new DataView(wasmMemory.buffer), GET_HEAP_DATA_VIEW = function () { return HEAP_DATA_VIEW.buffer === wasmMemory.buffer ? HEAP_DATA_VIEW : (HEAP_DATA_VIEW = new DataView(wasmMemory.buffer)); }; + GET_HEAP_DATA_VIEW().setUint32(result, v, true); + return envObject.getReturnStatus(); + }; + if (value instanceof ArrayBuffer || emnapiExternalMemory.isSharedArrayBuffer(value)) { + return createDataview(value); + } + else { + return envObject.setLastError(1); + } + } + catch (err) { + envObject.tryCatch.setError(err); + return envObject.setLastError(10); + } + } + function node_api_symbol_for(env, utf8description, length, result) { + if (!env) + return 1; + var envObject = emnapiCtx.envStore.get(env); + envObject.checkGCAccess(); + if (!result) + return envObject.setLastError(1); + length >>>= 0; + utf8description >>>= 0; + result >>>= 0; + var autoLength = length === -1 || length === 4294967295; + var sizelength = length >>> 0; + if (length !== 0) { + if (!utf8description) + return envObject.setLastError(1); + } + if (!(autoLength || (sizelength <= 2147483647))) { + return envObject.setLastError(1); + } + var descriptionString = emnapiString.UTF8ToString(utf8description, length); + var value = emnapiCtx.addToCurrentScope(Symbol.for(descriptionString)).id; + var HEAP_DATA_VIEW = new DataView(wasmMemory.buffer), GET_HEAP_DATA_VIEW = function () { return HEAP_DATA_VIEW.buffer === wasmMemory.buffer ? HEAP_DATA_VIEW : (HEAP_DATA_VIEW = new DataView(wasmMemory.buffer)); }; + GET_HEAP_DATA_VIEW().setUint32(result, value, true); + return envObject.clearLastError(); + } + var createMod = Object.freeze({ + __proto__: null, + napi_create_array: napi_create_array, + napi_create_array_with_length: napi_create_array_with_length, + napi_create_arraybuffer: napi_create_arraybuffer, + napi_create_buffer: napi_create_buffer, + napi_create_buffer_copy: napi_create_buffer_copy, + napi_create_dataview: napi_create_dataview, + napi_create_date: napi_create_date, + napi_create_external: napi_create_external, + napi_create_external_arraybuffer: napi_create_external_arraybuffer, + napi_create_external_buffer: napi_create_external_buffer, + napi_create_object: napi_create_object, + napi_create_symbol: napi_create_symbol, + napi_create_typedarray: napi_create_typedarray, + node_api_create_buffer_from_arraybuffer: node_api_create_buffer_from_arraybuffer, + node_api_create_external_sharedarraybuffer: node_api_create_external_sharedarraybuffer, + node_api_create_object_with_properties: node_api_create_object_with_properties, + node_api_create_sharedarraybuffer: node_api_create_sharedarraybuffer, + node_api_symbol_for: node_api_symbol_for + }); + function napi_get_boolean(env, value, result) { + if (!env) + return 1; + var envObject = emnapiCtx.envStore.get(env); + envObject.checkGCAccess(); + if (!result) + return envObject.setLastError(1); + result >>>= 0; + var v = value === 0 ? 3 : 4; + var HEAP_DATA_VIEW = new DataView(wasmMemory.buffer), GET_HEAP_DATA_VIEW = function () { return HEAP_DATA_VIEW.buffer === wasmMemory.buffer ? HEAP_DATA_VIEW : (HEAP_DATA_VIEW = new DataView(wasmMemory.buffer)); }; + GET_HEAP_DATA_VIEW().setUint32(result, v, true); + return envObject.clearLastError(); + } + function napi_get_global(env, result) { + if (!env) + return 1; + var envObject = emnapiCtx.envStore.get(env); + envObject.checkGCAccess(); + if (!result) + return envObject.setLastError(1); + result >>>= 0; + var value = 5; + var HEAP_DATA_VIEW = new DataView(wasmMemory.buffer), GET_HEAP_DATA_VIEW = function () { return HEAP_DATA_VIEW.buffer === wasmMemory.buffer ? HEAP_DATA_VIEW : (HEAP_DATA_VIEW = new DataView(wasmMemory.buffer)); }; + GET_HEAP_DATA_VIEW().setUint32(result, value, true); + return envObject.clearLastError(); + } + function napi_get_null(env, result) { + if (!env) + return 1; + var envObject = emnapiCtx.envStore.get(env); + envObject.checkGCAccess(); + if (!result) + return envObject.setLastError(1); + result >>>= 0; + var value = 2; + var HEAP_DATA_VIEW = new DataView(wasmMemory.buffer), GET_HEAP_DATA_VIEW = function () { return HEAP_DATA_VIEW.buffer === wasmMemory.buffer ? HEAP_DATA_VIEW : (HEAP_DATA_VIEW = new DataView(wasmMemory.buffer)); }; + GET_HEAP_DATA_VIEW().setUint32(result, value, true); + return envObject.clearLastError(); + } + function napi_get_undefined(env, result) { + if (!env) + return 1; + var envObject = emnapiCtx.envStore.get(env); + envObject.checkGCAccess(); + if (!result) + return envObject.setLastError(1); + result >>>= 0; + var value = 1; + var HEAP_DATA_VIEW = new DataView(wasmMemory.buffer), GET_HEAP_DATA_VIEW = function () { return HEAP_DATA_VIEW.buffer === wasmMemory.buffer ? HEAP_DATA_VIEW : (HEAP_DATA_VIEW = new DataView(wasmMemory.buffer)); }; + GET_HEAP_DATA_VIEW().setUint32(result, value, true); + return envObject.clearLastError(); + } + var globalMod = Object.freeze({ + __proto__: null, + napi_get_boolean: napi_get_boolean, + napi_get_global: napi_get_global, + napi_get_null: napi_get_null, + napi_get_undefined: napi_get_undefined + }); + function napi_set_instance_data(env, data, finalize_cb, finalize_hint) { + if (!env) + return 1; + var envObject = emnapiCtx.envStore.get(env); + data >>>= 0; + finalize_cb >>>= 0; + finalize_hint >>>= 0; + envObject.setInstanceData(data, finalize_cb, finalize_hint); + return envObject.clearLastError(); + } + function napi_get_instance_data(env, data) { + if (!env) + return 1; + var envObject = emnapiCtx.envStore.get(env); + if (!data) + return envObject.setLastError(1); + data >>>= 0; + var value = envObject.getInstanceData(); + var HEAP_DATA_VIEW = new DataView(wasmMemory.buffer), GET_HEAP_DATA_VIEW = function () { return HEAP_DATA_VIEW.buffer === wasmMemory.buffer ? HEAP_DATA_VIEW : (HEAP_DATA_VIEW = new DataView(wasmMemory.buffer)); }; + GET_HEAP_DATA_VIEW().setUint32(data, value, true); + return envObject.clearLastError(); + } + var envMod = Object.freeze({ + __proto__: null, + napi_get_instance_data: napi_get_instance_data, + napi_set_instance_data: napi_set_instance_data + }); + function _emnapi_get_last_error_info(env, error_code, engine_error_code, engine_reserved) { + error_code >>>= 0; + engine_error_code >>>= 0; + engine_reserved >>>= 0; + var envObject = emnapiCtx.envStore.get(env); + var lastError = envObject.lastError; + var errorCode = lastError.errorCode; + var engineErrorCode = lastError.engineErrorCode >>> 0; + var engineReserved = lastError.engineReserved; + engineReserved >>>= 0; + var HEAP_DATA_VIEW = new DataView(wasmMemory.buffer), GET_HEAP_DATA_VIEW = function () { return HEAP_DATA_VIEW.buffer === wasmMemory.buffer ? HEAP_DATA_VIEW : (HEAP_DATA_VIEW = new DataView(wasmMemory.buffer)); }; + GET_HEAP_DATA_VIEW().setInt32(error_code, errorCode, true); + GET_HEAP_DATA_VIEW().setUint32(engine_error_code, engineErrorCode, true); + GET_HEAP_DATA_VIEW().setUint32(engine_reserved, engineReserved, true); + } + function napi_throw(env, error) { + if (!env) + return 1; + var envObject = emnapiCtx.envStore.get(env); + envObject.checkGCAccess(); + if (!envObject.tryCatch.isEmpty()) + return envObject.setLastError(10); + if (!envObject.canCallIntoJs()) + return envObject.setLastError(envObject.moduleApiVersion >= 10 ? 23 : 10); + envObject.clearLastError(); + try { + if (!error) + return envObject.setLastError(1); + envObject.tryCatch.setError(emnapiCtx.handleStore.get(error).value); + return envObject.clearLastError(); + } + catch (err) { + envObject.tryCatch.setError(err); + return envObject.setLastError(10); + } + } + function napi_throw_error(env, code, msg) { + if (!env) + return 1; + var envObject = emnapiCtx.envStore.get(env); + envObject.checkGCAccess(); + if (!envObject.tryCatch.isEmpty()) + return envObject.setLastError(10); + if (!envObject.canCallIntoJs()) + return envObject.setLastError(envObject.moduleApiVersion >= 10 ? 23 : 10); + envObject.clearLastError(); + try { + if (!msg) + return envObject.setLastError(1); + code >>>= 0; + msg >>>= 0; + var error = new Error(emnapiString.UTF8ToString(msg, -1)); + if (code) + error.code = emnapiString.UTF8ToString(code, -1); + envObject.tryCatch.setError(error); + return envObject.clearLastError(); + } + catch (err) { + envObject.tryCatch.setError(err); + return envObject.setLastError(10); + } + } + function napi_throw_type_error(env, code, msg) { + if (!env) + return 1; + var envObject = emnapiCtx.envStore.get(env); + envObject.checkGCAccess(); + if (!envObject.tryCatch.isEmpty()) + return envObject.setLastError(10); + if (!envObject.canCallIntoJs()) + return envObject.setLastError(envObject.moduleApiVersion >= 10 ? 23 : 10); + envObject.clearLastError(); + try { + if (!msg) + return envObject.setLastError(1); + code >>>= 0; + msg >>>= 0; + var error = new TypeError(emnapiString.UTF8ToString(msg, -1)); + if (code) + error.code = emnapiString.UTF8ToString(code, -1); + envObject.tryCatch.setError(error); + return envObject.clearLastError(); + } + catch (err) { + envObject.tryCatch.setError(err); + return envObject.setLastError(10); + } + } + function napi_throw_range_error(env, code, msg) { + if (!env) + return 1; + var envObject = emnapiCtx.envStore.get(env); + envObject.checkGCAccess(); + if (!envObject.tryCatch.isEmpty()) + return envObject.setLastError(10); + if (!envObject.canCallIntoJs()) + return envObject.setLastError(envObject.moduleApiVersion >= 10 ? 23 : 10); + envObject.clearLastError(); + try { + if (!msg) + return envObject.setLastError(1); + code >>>= 0; + msg >>>= 0; + var error = new RangeError(emnapiString.UTF8ToString(msg, -1)); + if (code) + error.code = emnapiString.UTF8ToString(code, -1); + envObject.tryCatch.setError(error); + return envObject.clearLastError(); + } + catch (err) { + envObject.tryCatch.setError(err); + return envObject.setLastError(10); + } + } + function node_api_throw_syntax_error(env, code, msg) { + if (!env) + return 1; + var envObject = emnapiCtx.envStore.get(env); + envObject.checkGCAccess(); + if (!envObject.tryCatch.isEmpty()) + return envObject.setLastError(10); + if (!envObject.canCallIntoJs()) + return envObject.setLastError(envObject.moduleApiVersion >= 10 ? 23 : 10); + envObject.clearLastError(); + try { + if (!msg) + return envObject.setLastError(1); + code >>>= 0; + msg >>>= 0; + var error = new SyntaxError(emnapiString.UTF8ToString(msg, -1)); + if (code) + error.code = emnapiString.UTF8ToString(code, -1); + envObject.tryCatch.setError(error); + return envObject.clearLastError(); + } + catch (err) { + envObject.tryCatch.setError(err); + return envObject.setLastError(10); + } + } + function napi_is_exception_pending(env, result) { + if (!env) + return 1; + var envObject = emnapiCtx.envStore.get(env); + envObject.checkGCAccess(); + if (!result) + return envObject.setLastError(1); + var r = envObject.tryCatch.hasCaught(); + result >>>= 0; + var HEAP_DATA_VIEW = new DataView(wasmMemory.buffer), GET_HEAP_DATA_VIEW = function () { return HEAP_DATA_VIEW.buffer === wasmMemory.buffer ? HEAP_DATA_VIEW : (HEAP_DATA_VIEW = new DataView(wasmMemory.buffer)); }; + GET_HEAP_DATA_VIEW().setInt8(result, r ? 1 : 0, true); + return envObject.clearLastError(); + } + function napi_create_error(env, code, msg, result) { + if (!env) + return 1; + var envObject = emnapiCtx.envStore.get(env); + envObject.checkGCAccess(); + if (!msg) + return envObject.setLastError(1); + if (!result) + return envObject.setLastError(1); + var msgValue = emnapiCtx.handleStore.get(msg).value; + if (typeof msgValue !== 'string') { + return envObject.setLastError(3); + } + var error = new Error(msgValue); + if (code) { + var codeValue = emnapiCtx.handleStore.get(code).value; + if (typeof codeValue !== 'string') { + return envObject.setLastError(3); + } + error.code = codeValue; + } + result >>>= 0; + var value = emnapiCtx.addToCurrentScope(error).id; + var HEAP_DATA_VIEW = new DataView(wasmMemory.buffer), GET_HEAP_DATA_VIEW = function () { return HEAP_DATA_VIEW.buffer === wasmMemory.buffer ? HEAP_DATA_VIEW : (HEAP_DATA_VIEW = new DataView(wasmMemory.buffer)); }; + GET_HEAP_DATA_VIEW().setUint32(result, value, true); + return envObject.clearLastError(); + } + function napi_create_type_error(env, code, msg, result) { + if (!env) + return 1; + var envObject = emnapiCtx.envStore.get(env); + envObject.checkGCAccess(); + if (!msg) + return envObject.setLastError(1); + if (!result) + return envObject.setLastError(1); + var msgValue = emnapiCtx.handleStore.get(msg).value; + if (typeof msgValue !== 'string') { + return envObject.setLastError(3); + } + var error = new TypeError(msgValue); + if (code) { + var codeValue = emnapiCtx.handleStore.get(code).value; + if (typeof codeValue !== 'string') { + return envObject.setLastError(3); + } + error.code = codeValue; + } + result >>>= 0; + var value = emnapiCtx.addToCurrentScope(error).id; + var HEAP_DATA_VIEW = new DataView(wasmMemory.buffer), GET_HEAP_DATA_VIEW = function () { return HEAP_DATA_VIEW.buffer === wasmMemory.buffer ? HEAP_DATA_VIEW : (HEAP_DATA_VIEW = new DataView(wasmMemory.buffer)); }; + GET_HEAP_DATA_VIEW().setUint32(result, value, true); + return envObject.clearLastError(); + } + function napi_create_range_error(env, code, msg, result) { + if (!env) + return 1; + var envObject = emnapiCtx.envStore.get(env); + envObject.checkGCAccess(); + if (!msg) + return envObject.setLastError(1); + if (!result) + return envObject.setLastError(1); + var msgValue = emnapiCtx.handleStore.get(msg).value; + if (typeof msgValue !== 'string') { + return envObject.setLastError(3); + } + var error = new RangeError(msgValue); + if (code) { + var codeValue = emnapiCtx.handleStore.get(code).value; + if (typeof codeValue !== 'string') { + return envObject.setLastError(3); + } + error.code = codeValue; + } + result >>>= 0; + var value = emnapiCtx.addToCurrentScope(error).id; + var HEAP_DATA_VIEW = new DataView(wasmMemory.buffer), GET_HEAP_DATA_VIEW = function () { return HEAP_DATA_VIEW.buffer === wasmMemory.buffer ? HEAP_DATA_VIEW : (HEAP_DATA_VIEW = new DataView(wasmMemory.buffer)); }; + GET_HEAP_DATA_VIEW().setUint32(result, value, true); + return envObject.clearLastError(); + } + function node_api_create_syntax_error(env, code, msg, result) { + if (!env) + return 1; + var envObject = emnapiCtx.envStore.get(env); + envObject.checkGCAccess(); + if (!msg) + return envObject.setLastError(1); + if (!result) + return envObject.setLastError(1); + var msgValue = emnapiCtx.handleStore.get(msg).value; + if (typeof msgValue !== 'string') { + return envObject.setLastError(3); + } + var error = new SyntaxError(msgValue); + if (code) { + var codeValue = emnapiCtx.handleStore.get(code).value; + if (typeof codeValue !== 'string') { + return envObject.setLastError(3); + } + error.code = codeValue; + } + result >>>= 0; + var value = emnapiCtx.addToCurrentScope(error).id; + var HEAP_DATA_VIEW = new DataView(wasmMemory.buffer), GET_HEAP_DATA_VIEW = function () { return HEAP_DATA_VIEW.buffer === wasmMemory.buffer ? HEAP_DATA_VIEW : (HEAP_DATA_VIEW = new DataView(wasmMemory.buffer)); }; + GET_HEAP_DATA_VIEW().setUint32(result, value, true); + return envObject.clearLastError(); + } + function napi_get_and_clear_last_exception(env, result) { + if (!env) + return 1; + var envObject = emnapiCtx.envStore.get(env); + envObject.checkGCAccess(); + if (!result) + return envObject.setLastError(1); + result >>>= 0; + var HEAP_DATA_VIEW = new DataView(wasmMemory.buffer), GET_HEAP_DATA_VIEW = function () { return HEAP_DATA_VIEW.buffer === wasmMemory.buffer ? HEAP_DATA_VIEW : (HEAP_DATA_VIEW = new DataView(wasmMemory.buffer)); }; + if (!envObject.tryCatch.hasCaught()) { + GET_HEAP_DATA_VIEW().setUint32(result, 1, true); + return envObject.clearLastError(); + } + else { + var err = envObject.tryCatch.exception(); + var value = envObject.ensureHandleId(err); + GET_HEAP_DATA_VIEW().setUint32(result, value, true); + envObject.tryCatch.reset(); + } + return envObject.clearLastError(); + } + function napi_fatal_error(location, location_len, message, message_len) { + location >>>= 0; + location_len >>>= 0; + message >>>= 0; + message_len >>>= 0; + var locationStr = emnapiString.UTF8ToString(location, location_len); + var messageStr = emnapiString.UTF8ToString(message, message_len); + if (emnapiNodeBinding) { + emnapiNodeBinding.napi.fatalError(locationStr, messageStr); + } + else { + abort('FATAL ERROR: ' + locationStr + ' ' + messageStr); + } + } + function napi_fatal_exception(env, err) { + if (!env) + return 1; + var envObject = emnapiCtx.envStore.get(env); + envObject.checkGCAccess(); + if (!envObject.tryCatch.isEmpty()) + return envObject.setLastError(10); + if (!envObject.canCallIntoJs()) + return envObject.setLastError(envObject.moduleApiVersion >= 10 ? 23 : 10); + envObject.clearLastError(); + try { + if (!err) + return envObject.setLastError(1); + var error = envObject.ctx.handleStore.get(err); + try { + envObject.triggerFatalException(error.value); + } + catch (_) { + return envObject.setLastError(9); + } + return envObject.clearLastError(); + } + catch (err) { + envObject.tryCatch.setError(err); + return envObject.setLastError(10); + } + } + var errorMod = Object.freeze({ + __proto__: null, + _emnapi_get_last_error_info: _emnapi_get_last_error_info, + napi_create_error: napi_create_error, + napi_create_range_error: napi_create_range_error, + napi_create_type_error: napi_create_type_error, + napi_fatal_error: napi_fatal_error, + napi_fatal_exception: napi_fatal_exception, + napi_get_and_clear_last_exception: napi_get_and_clear_last_exception, + napi_is_exception_pending: napi_is_exception_pending, + napi_throw: napi_throw, + napi_throw_error: napi_throw_error, + napi_throw_range_error: napi_throw_range_error, + napi_throw_type_error: napi_throw_type_error, + node_api_create_syntax_error: node_api_create_syntax_error, + node_api_throw_syntax_error: node_api_throw_syntax_error + }); + function _emnapi_create_function(env, utf8name, length, cb, data, result) { + length >>>= 0; + var envObject = emnapiCtx.envStore.get(env); + var fresult = emnapiCreateFunction(envObject, utf8name, length, cb, data); + if (fresult.status !== 0) + return envObject.setLastError(fresult.status); + var f = fresult.f; + var valueHandle = emnapiCtx.addToCurrentScope(f); + result >>>= 0; + var value = valueHandle.id; + var HEAP_DATA_VIEW = new DataView(wasmMemory.buffer), GET_HEAP_DATA_VIEW = function () { return HEAP_DATA_VIEW.buffer === wasmMemory.buffer ? HEAP_DATA_VIEW : (HEAP_DATA_VIEW = new DataView(wasmMemory.buffer)); }; + GET_HEAP_DATA_VIEW().setUint32(result, value, true); + return envObject.getReturnStatus(); + } + function napi_create_function(env, utf8name, length, cb, data, result) { + if (!env) + return 1; + var envObject = emnapiCtx.envStore.get(env); + envObject.checkGCAccess(); + if (!envObject.tryCatch.isEmpty()) + return envObject.setLastError(10); + if (!envObject.canCallIntoJs()) + return envObject.setLastError(envObject.moduleApiVersion >= 10 ? 23 : 10); + envObject.clearLastError(); + try { + if (!result) + return envObject.setLastError(1); + if (!cb) + return envObject.setLastError(1); + return _emnapi_create_function(env, utf8name, length, cb, data, result); + } + catch (err) { + envObject.tryCatch.setError(err); + return envObject.setLastError(10); + } + } + function napi_get_cb_info(env, cbinfo, argc, argv, this_arg, data) { + if (!env) + return 1; + var envObject = emnapiCtx.envStore.get(env); + if (!cbinfo) + return envObject.setLastError(1); + var cbinfoValue = emnapiCtx.scopeStore.get(cbinfo).callbackInfo; + argc >>>= 0; + argv >>>= 0; + var HEAP_DATA_VIEW = new DataView(wasmMemory.buffer), GET_HEAP_DATA_VIEW = function () { return HEAP_DATA_VIEW.buffer === wasmMemory.buffer ? HEAP_DATA_VIEW : (HEAP_DATA_VIEW = new DataView(wasmMemory.buffer)); }; + if (argv) { + if (!argc) + return envObject.setLastError(1); + var argcValue = GET_HEAP_DATA_VIEW().getUint32(argc, true); + argcValue >>>= 0; + var len = cbinfoValue.args.length; + var arrlen = argcValue < len ? argcValue : len; + var i = 0; + for (; i < arrlen; i++) { + var argVal = envObject.ensureHandleId(cbinfoValue.args[i]); + GET_HEAP_DATA_VIEW().setUint32(argv + i * 4, argVal, true); + } + if (i < argcValue) { + for (; i < argcValue; i++) { + GET_HEAP_DATA_VIEW().setUint32(argv + i * 4, 1, true); + } + } + } + if (argc) { + GET_HEAP_DATA_VIEW().setUint32(argc, cbinfoValue.args.length, true); + } + if (this_arg) { + this_arg >>>= 0; + var v = envObject.ensureHandleId(cbinfoValue.thiz); + GET_HEAP_DATA_VIEW().setUint32(this_arg, v, true); + } + if (data) { + data >>>= 0; + GET_HEAP_DATA_VIEW().setUint32(data, cbinfoValue.data, true); + } + return envObject.clearLastError(); + } + function napi_call_function(env, recv, func, argc, argv, result) { + var i = 0; + var v; + if (!env) + return 1; + var envObject = emnapiCtx.envStore.get(env); + envObject.checkGCAccess(); + if (!envObject.tryCatch.isEmpty()) + return envObject.setLastError(10); + if (!envObject.canCallIntoJs()) + return envObject.setLastError(envObject.moduleApiVersion >= 10 ? 23 : 10); + envObject.clearLastError(); + try { + if (!recv) + return envObject.setLastError(1); + argc >>>= 0; + argv >>>= 0; + result >>>= 0; + argc = argc >>> 0; + if (argc > 0) { + if (!argv) + return envObject.setLastError(1); + } + var v8recv = emnapiCtx.handleStore.get(recv).value; + if (!func) + return envObject.setLastError(1); + var v8func = emnapiCtx.handleStore.get(func).value; + if (typeof v8func !== 'function') + return envObject.setLastError(1); + var args = []; + var HEAP_DATA_VIEW = new DataView(wasmMemory.buffer), GET_HEAP_DATA_VIEW = function () { return HEAP_DATA_VIEW.buffer === wasmMemory.buffer ? HEAP_DATA_VIEW : (HEAP_DATA_VIEW = new DataView(wasmMemory.buffer)); }; + for (; i < argc; i++) { + var argVal = GET_HEAP_DATA_VIEW().getUint32(argv + i * 4, true); + args.push(emnapiCtx.handleStore.get(argVal).value); + } + var ret = v8func.apply(v8recv, args); + if (result) { + v = envObject.ensureHandleId(ret); + GET_HEAP_DATA_VIEW().setUint32(result, v, true); + } + return envObject.clearLastError(); + } + catch (err) { + envObject.tryCatch.setError(err); + return envObject.setLastError(10); + } + } + function napi_new_instance(env, constructor, argc, argv, result) { + var i; + var v; + if (!env) + return 1; + var envObject = emnapiCtx.envStore.get(env); + envObject.checkGCAccess(); + if (!envObject.tryCatch.isEmpty()) + return envObject.setLastError(10); + if (!envObject.canCallIntoJs()) + return envObject.setLastError(envObject.moduleApiVersion >= 10 ? 23 : 10); + envObject.clearLastError(); + try { + if (!constructor) + return envObject.setLastError(1); + argc >>>= 0; + argv >>>= 0; + result >>>= 0; + argc = argc >>> 0; + if (argc > 0) { + if (!argv) + return envObject.setLastError(1); + } + if (!result) + return envObject.setLastError(1); + var Ctor = emnapiCtx.handleStore.get(constructor).value; + if (typeof Ctor !== 'function') + return envObject.setLastError(1); + var ret = void 0; + var HEAP_DATA_VIEW = new DataView(wasmMemory.buffer), GET_HEAP_DATA_VIEW = function () { return HEAP_DATA_VIEW.buffer === wasmMemory.buffer ? HEAP_DATA_VIEW : (HEAP_DATA_VIEW = new DataView(wasmMemory.buffer)); }; + if (emnapiCtx.feature.supportReflect) { + var argList = Array(argc); + for (i = 0; i < argc; i++) { + var argVal = GET_HEAP_DATA_VIEW().getUint32(argv + i * 4, true); + argList[i] = emnapiCtx.handleStore.get(argVal).value; + } + ret = Reflect.construct(Ctor, argList, Ctor); + } + else { + var args = Array(argc + 1); + args[0] = undefined; + for (i = 0; i < argc; i++) { + var argVal = GET_HEAP_DATA_VIEW().getUint32(argv + i * 4, true); + args[i + 1] = emnapiCtx.handleStore.get(argVal).value; + } + var BoundCtor = Ctor.bind.apply(Ctor, args); + ret = new BoundCtor(); + } + if (result) { + v = envObject.ensureHandleId(ret); + GET_HEAP_DATA_VIEW().setUint32(result, v, true); + } + return envObject.getReturnStatus(); + } + catch (err) { + envObject.tryCatch.setError(err); + return envObject.setLastError(10); + } + } + function napi_get_new_target(env, cbinfo, result) { + if (!env) + return 1; + var envObject = emnapiCtx.envStore.get(env); + envObject.checkGCAccess(); + if (!cbinfo) + return envObject.setLastError(1); + if (!result) + return envObject.setLastError(1); + result >>>= 0; + var cbinfoValue = emnapiCtx.scopeStore.get(cbinfo).callbackInfo; + var thiz = cbinfoValue.thiz, fn = cbinfoValue.fn; + var value = thiz == null || thiz.constructor == null + ? 0 + : thiz instanceof fn + ? envObject.ensureHandleId(thiz.constructor) + : 0; + var HEAP_DATA_VIEW = new DataView(wasmMemory.buffer), GET_HEAP_DATA_VIEW = function () { return HEAP_DATA_VIEW.buffer === wasmMemory.buffer ? HEAP_DATA_VIEW : (HEAP_DATA_VIEW = new DataView(wasmMemory.buffer)); }; + GET_HEAP_DATA_VIEW().setUint32(result, value, true); + return envObject.clearLastError(); + } + var functionMod = Object.freeze({ + __proto__: null, + _emnapi_create_function: _emnapi_create_function, + napi_call_function: napi_call_function, + napi_create_function: napi_create_function, + napi_get_cb_info: napi_get_cb_info, + napi_get_new_target: napi_get_new_target, + napi_new_instance: napi_new_instance + }); + function napi_open_handle_scope(env, result) { + if (!env) + return 1; + var envObject = emnapiCtx.envStore.get(env); + envObject.checkGCAccess(); + if (!result) + return envObject.setLastError(1); + var scope = emnapiCtx.openScope(envObject); + result >>>= 0; + var HEAP_DATA_VIEW = new DataView(wasmMemory.buffer), GET_HEAP_DATA_VIEW = function () { return HEAP_DATA_VIEW.buffer === wasmMemory.buffer ? HEAP_DATA_VIEW : (HEAP_DATA_VIEW = new DataView(wasmMemory.buffer)); }; + GET_HEAP_DATA_VIEW().setUint32(result, scope.id, true); + return envObject.clearLastError(); + } + function napi_close_handle_scope(env, scope) { + if (!env) + return 1; + var envObject = emnapiCtx.envStore.get(env); + envObject.checkGCAccess(); + if (!scope) + return envObject.setLastError(1); + if ((envObject.openHandleScopes === 0)) { + return 13; + } + emnapiCtx.closeScope(envObject); + return envObject.clearLastError(); + } + function napi_open_escapable_handle_scope(env, result) { + if (!env) + return 1; + var envObject = emnapiCtx.envStore.get(env); + envObject.checkGCAccess(); + if (!result) + return envObject.setLastError(1); + var scope = emnapiCtx.openScope(envObject); + result >>>= 0; + var HEAP_DATA_VIEW = new DataView(wasmMemory.buffer), GET_HEAP_DATA_VIEW = function () { return HEAP_DATA_VIEW.buffer === wasmMemory.buffer ? HEAP_DATA_VIEW : (HEAP_DATA_VIEW = new DataView(wasmMemory.buffer)); }; + GET_HEAP_DATA_VIEW().setUint32(result, scope.id, true); + return envObject.clearLastError(); + } + function napi_close_escapable_handle_scope(env, scope) { + if (!env) + return 1; + var envObject = emnapiCtx.envStore.get(env); + envObject.checkGCAccess(); + if (!scope) + return envObject.setLastError(1); + if ((envObject.openHandleScopes === 0)) { + return 13; + } + emnapiCtx.closeScope(envObject); + return envObject.clearLastError(); + } + function napi_escape_handle(env, scope, escapee, result) { + if (!env) + return 1; + var envObject = emnapiCtx.envStore.get(env); + envObject.checkGCAccess(); + if (!scope) + return envObject.setLastError(1); + if (!escapee) + return envObject.setLastError(1); + if (!result) + return envObject.setLastError(1); + var scopeObject = emnapiCtx.scopeStore.get(scope); + if (!scopeObject.escapeCalled()) { + escapee >>>= 0; + result >>>= 0; + var newHandle = scopeObject.escape(escapee); + var value = newHandle ? newHandle.id : 0; + var HEAP_DATA_VIEW = new DataView(wasmMemory.buffer), GET_HEAP_DATA_VIEW = function () { return HEAP_DATA_VIEW.buffer === wasmMemory.buffer ? HEAP_DATA_VIEW : (HEAP_DATA_VIEW = new DataView(wasmMemory.buffer)); }; + GET_HEAP_DATA_VIEW().setUint32(result, value, true); + return envObject.clearLastError(); + } + return envObject.setLastError(12); + } + function napi_create_reference(env, value, initial_refcount, result) { + if (!env) + return 1; + var envObject = emnapiCtx.envStore.get(env); + envObject.checkGCAccess(); + if (!value) + return envObject.setLastError(1); + if (!result) + return envObject.setLastError(1); + var handle = emnapiCtx.handleStore.get(value); + if (envObject.moduleApiVersion < 10) { + if (!(handle.isObject() || handle.isFunction() || handle.isSymbol())) { + return envObject.setLastError(1); + } + } + var ref = emnapiCtx.createReference(envObject, handle.id, initial_refcount >>> 0, 1); + result >>>= 0; + var HEAP_DATA_VIEW = new DataView(wasmMemory.buffer), GET_HEAP_DATA_VIEW = function () { return HEAP_DATA_VIEW.buffer === wasmMemory.buffer ? HEAP_DATA_VIEW : (HEAP_DATA_VIEW = new DataView(wasmMemory.buffer)); }; + GET_HEAP_DATA_VIEW().setUint32(result, ref.id, true); + return envObject.clearLastError(); + } + function napi_delete_reference(env, ref) { + if (!env) + return 1; + var envObject = emnapiCtx.envStore.get(env); + if (!ref) + return envObject.setLastError(1); + emnapiCtx.refStore.get(ref).dispose(); + return envObject.clearLastError(); + } + function napi_reference_ref(env, ref, result) { + if (!env) + return 1; + var envObject = emnapiCtx.envStore.get(env); + envObject.checkGCAccess(); + if (!ref) + return envObject.setLastError(1); + var count = emnapiCtx.refStore.get(ref).ref(); + if (result) { + result >>>= 0; + var HEAP_DATA_VIEW = new DataView(wasmMemory.buffer), GET_HEAP_DATA_VIEW = function () { return HEAP_DATA_VIEW.buffer === wasmMemory.buffer ? HEAP_DATA_VIEW : (HEAP_DATA_VIEW = new DataView(wasmMemory.buffer)); }; + GET_HEAP_DATA_VIEW().setUint32(result, count, true); + } + return envObject.clearLastError(); + } + function napi_reference_unref(env, ref, result) { + if (!env) + return 1; + var envObject = emnapiCtx.envStore.get(env); + envObject.checkGCAccess(); + if (!ref) + return envObject.setLastError(1); + var reference = emnapiCtx.refStore.get(ref); + var refcount = reference.refcount(); + if (refcount === 0) { + return envObject.setLastError(9); + } + var count = reference.unref(); + if (result) { + result >>>= 0; + var HEAP_DATA_VIEW = new DataView(wasmMemory.buffer), GET_HEAP_DATA_VIEW = function () { return HEAP_DATA_VIEW.buffer === wasmMemory.buffer ? HEAP_DATA_VIEW : (HEAP_DATA_VIEW = new DataView(wasmMemory.buffer)); }; + GET_HEAP_DATA_VIEW().setUint32(result, count, true); + } + return envObject.clearLastError(); + } + function napi_get_reference_value(env, ref, result) { + if (!env) + return 1; + var envObject = emnapiCtx.envStore.get(env); + envObject.checkGCAccess(); + if (!ref) + return envObject.setLastError(1); + if (!result) + return envObject.setLastError(1); + var reference = emnapiCtx.refStore.get(ref); + var handleId = reference.get(envObject); + result >>>= 0; + var HEAP_DATA_VIEW = new DataView(wasmMemory.buffer), GET_HEAP_DATA_VIEW = function () { return HEAP_DATA_VIEW.buffer === wasmMemory.buffer ? HEAP_DATA_VIEW : (HEAP_DATA_VIEW = new DataView(wasmMemory.buffer)); }; + GET_HEAP_DATA_VIEW().setUint32(result, handleId, true); + return envObject.clearLastError(); + } + function napi_add_env_cleanup_hook(env, fun, arg) { + if (!env) + return 1; + var envObject = emnapiCtx.envStore.get(env); + if (!fun) + return envObject.setLastError(1); + fun >>>= 0; + arg >>>= 0; + emnapiCtx.addCleanupHook(envObject, fun, arg); + return 0; + } + function napi_remove_env_cleanup_hook(env, fun, arg) { + if (!env) + return 1; + var envObject = emnapiCtx.envStore.get(env); + if (!fun) + return envObject.setLastError(1); + fun >>>= 0; + arg >>>= 0; + emnapiCtx.removeCleanupHook(envObject, fun, arg); + return 0; + } + function _emnapi_env_ref(env) { + var envObject = emnapiCtx.envStore.get(env); + envObject.ref(); + } + function _emnapi_env_unref(env) { + var envObject = emnapiCtx.envStore.get(env); + envObject.unref(); + } + var lifeMod = Object.freeze({ + __proto__: null, + _emnapi_env_ref: _emnapi_env_ref, + _emnapi_env_unref: _emnapi_env_unref, + napi_add_env_cleanup_hook: napi_add_env_cleanup_hook, + napi_close_escapable_handle_scope: napi_close_escapable_handle_scope, + napi_close_handle_scope: napi_close_handle_scope, + napi_create_reference: napi_create_reference, + napi_delete_reference: napi_delete_reference, + napi_escape_handle: napi_escape_handle, + napi_get_reference_value: napi_get_reference_value, + napi_open_escapable_handle_scope: napi_open_escapable_handle_scope, + napi_open_handle_scope: napi_open_handle_scope, + napi_reference_ref: napi_reference_ref, + napi_reference_unref: napi_reference_unref, + napi_remove_env_cleanup_hook: napi_remove_env_cleanup_hook + }); + function _emnapi_get_filename(env, buf, len) { + var envObject = emnapiCtx.envStore.get(env); + var filename = envObject.filename; + if (!buf) { + return emnapiString.lengthBytesUTF8(filename); + } + return emnapiString.stringToUTF8(filename, buf, len); + } + var miscellaneousMod = Object.freeze({ + __proto__: null, + _emnapi_get_filename: _emnapi_get_filename + }); + function napi_create_promise(env, deferred, promise) { + var deferredObjectId, value; + if (!env) + return 1; + var envObject = emnapiCtx.envStore.get(env); + envObject.checkGCAccess(); + if (!envObject.tryCatch.isEmpty()) + return envObject.setLastError(10); + if (!envObject.canCallIntoJs()) + return envObject.setLastError(envObject.moduleApiVersion >= 10 ? 23 : 10); + envObject.clearLastError(); + try { + if (!deferred) + return envObject.setLastError(1); + if (!promise) + return envObject.setLastError(1); + var HEAP_DATA_VIEW = new DataView(wasmMemory.buffer), GET_HEAP_DATA_VIEW = function () { return HEAP_DATA_VIEW.buffer === wasmMemory.buffer ? HEAP_DATA_VIEW : (HEAP_DATA_VIEW = new DataView(wasmMemory.buffer)); }; + var p = new Promise(function (resolve, reject) { + var deferredObject = emnapiCtx.createDeferred({ resolve: resolve, reject: reject }); + deferredObjectId = deferredObject.id; + deferred >>>= 0; + GET_HEAP_DATA_VIEW().setUint32(deferred, deferredObjectId, true); + }); + promise >>>= 0; + value = emnapiCtx.addToCurrentScope(p).id; + GET_HEAP_DATA_VIEW().setUint32(promise, value, true); + return envObject.getReturnStatus(); + } + catch (err) { + envObject.tryCatch.setError(err); + return envObject.setLastError(10); + } + } + function napi_resolve_deferred(env, deferred, resolution) { + if (!env) + return 1; + var envObject = emnapiCtx.envStore.get(env); + envObject.checkGCAccess(); + if (!envObject.tryCatch.isEmpty()) + return envObject.setLastError(10); + if (!envObject.canCallIntoJs()) + return envObject.setLastError(envObject.moduleApiVersion >= 10 ? 23 : 10); + envObject.clearLastError(); + try { + if (!deferred) + return envObject.setLastError(1); + if (!resolution) + return envObject.setLastError(1); + var deferredObject = emnapiCtx.deferredStore.get(deferred); + deferredObject.resolve(emnapiCtx.handleStore.get(resolution).value); + return envObject.getReturnStatus(); + } + catch (err) { + envObject.tryCatch.setError(err); + return envObject.setLastError(10); + } + } + function napi_reject_deferred(env, deferred, resolution) { + if (!env) + return 1; + var envObject = emnapiCtx.envStore.get(env); + envObject.checkGCAccess(); + if (!envObject.tryCatch.isEmpty()) + return envObject.setLastError(10); + if (!envObject.canCallIntoJs()) + return envObject.setLastError(envObject.moduleApiVersion >= 10 ? 23 : 10); + envObject.clearLastError(); + try { + if (!deferred) + return envObject.setLastError(1); + if (!resolution) + return envObject.setLastError(1); + var deferredObject = emnapiCtx.deferredStore.get(deferred); + deferredObject.reject(emnapiCtx.handleStore.get(resolution).value); + return envObject.getReturnStatus(); + } + catch (err) { + envObject.tryCatch.setError(err); + return envObject.setLastError(10); + } + } + function napi_is_promise(env, value, is_promise) { + if (!env) + return 1; + var envObject = emnapiCtx.envStore.get(env); + envObject.checkGCAccess(); + if (!value) + return envObject.setLastError(1); + if (!is_promise) + return envObject.setLastError(1); + var h = emnapiCtx.handleStore.get(value); + is_promise >>>= 0; + var r = h.isPromise() ? 1 : 0; + var HEAP_DATA_VIEW = new DataView(wasmMemory.buffer), GET_HEAP_DATA_VIEW = function () { return HEAP_DATA_VIEW.buffer === wasmMemory.buffer ? HEAP_DATA_VIEW : (HEAP_DATA_VIEW = new DataView(wasmMemory.buffer)); }; + GET_HEAP_DATA_VIEW().setInt8(is_promise, r, true); + return envObject.clearLastError(); + } + var promiseMod = Object.freeze({ + __proto__: null, + napi_create_promise: napi_create_promise, + napi_is_promise: napi_is_promise, + napi_reject_deferred: napi_reject_deferred, + napi_resolve_deferred: napi_resolve_deferred + }); + function napi_get_all_property_names(env, object, key_mode, key_filter, key_conversion, result) { + var value; + if (!env) + return 1; + var envObject = emnapiCtx.envStore.get(env); + envObject.checkGCAccess(); + if (!envObject.tryCatch.isEmpty()) + return envObject.setLastError(10); + if (!envObject.canCallIntoJs()) + return envObject.setLastError(envObject.moduleApiVersion >= 10 ? 23 : 10); + envObject.clearLastError(); + try { + if (!result) + return envObject.setLastError(1); + if (!object) + return envObject.setLastError(1); + var h = emnapiCtx.handleStore.get(object); + if (h.value == null) { + throw new TypeError('Cannot convert undefined or null to object'); + } + var obj = void 0; + try { + obj = h.isObject() || h.isFunction() ? h.value : Object(h.value); + } + catch (_) { + return envObject.setLastError(2); + } + if (key_mode !== 0 && key_mode !== 1) { + return envObject.setLastError(1); + } + if (key_conversion !== 0 && key_conversion !== 1) { + return envObject.setLastError(1); + } + var props = []; + var names = void 0; + var symbols = void 0; + var i = void 0; + var own = true; + var integerIndiceRegex = /^(0|[1-9][0-9]*)$/; + do { + names = Object.getOwnPropertyNames(obj); + symbols = Object.getOwnPropertySymbols(obj); + for (i = 0; i < names.length; i++) { + props.push({ + name: integerIndiceRegex.test(names[i]) ? Number(names[i]) : names[i], + desc: Object.getOwnPropertyDescriptor(obj, names[i]), + own: own + }); + } + for (i = 0; i < symbols.length; i++) { + props.push({ + name: symbols[i], + desc: Object.getOwnPropertyDescriptor(obj, symbols[i]), + own: own + }); + } + if (key_mode === 1) { + break; + } + obj = Object.getPrototypeOf(obj); + own = false; + } while (obj); + var ret = []; + var addName = function (ret, name, key_filter, conversion_mode) { + if (ret.indexOf(name) !== -1) + return; + if (conversion_mode === 0) { + ret.push(name); + } + else if (conversion_mode === 1) { + var realName = typeof name === 'number' ? String(name) : name; + if (typeof realName === 'string') { + if (!(key_filter & 8)) { + ret.push(realName); + } + } + else { + ret.push(realName); + } + } + }; + for (i = 0; i < props.length; i++) { + var prop = props[i]; + var name_1 = prop.name; + var desc = prop.desc; + if (key_filter === 0) { + addName(ret, name_1, key_filter, key_conversion); + } + else { + if (key_filter & 8 && typeof name_1 === 'string') { + continue; + } + if (key_filter & 16 && typeof name_1 === 'symbol') { + continue; + } + var shouldAdd = true; + switch (key_filter & 7) { + case 1: { + shouldAdd = Boolean(desc.writable); + break; + } + case 2: { + shouldAdd = Boolean(desc.enumerable); + break; + } + case (1 | 2): { + shouldAdd = Boolean(desc.writable && desc.enumerable); + break; + } + case 4: { + shouldAdd = Boolean(desc.configurable); + break; + } + case (4 | 1): { + shouldAdd = Boolean(desc.configurable && desc.writable); + break; + } + case (4 | 2): { + shouldAdd = Boolean(desc.configurable && desc.enumerable); + break; + } + case (4 | 2 | 1): { + shouldAdd = Boolean(desc.configurable && desc.enumerable && desc.writable); + break; + } + } + if (shouldAdd) { + addName(ret, name_1, key_filter, key_conversion); + } + } + } + result >>>= 0; + value = emnapiCtx.addToCurrentScope(ret).id; + var HEAP_DATA_VIEW = new DataView(wasmMemory.buffer), GET_HEAP_DATA_VIEW = function () { return HEAP_DATA_VIEW.buffer === wasmMemory.buffer ? HEAP_DATA_VIEW : (HEAP_DATA_VIEW = new DataView(wasmMemory.buffer)); }; + GET_HEAP_DATA_VIEW().setUint32(result, value, true); + return envObject.getReturnStatus(); + } + catch (err) { + envObject.tryCatch.setError(err); + return envObject.setLastError(10); + } + } + function napi_get_property_names(env, object, result) { + return napi_get_all_property_names(env, object, 0, 2 | 16, 1, result); + } + function napi_set_property(env, object, key, value) { + if (!env) + return 1; + var envObject = emnapiCtx.envStore.get(env); + envObject.checkGCAccess(); + if (!envObject.tryCatch.isEmpty()) + return envObject.setLastError(10); + if (!envObject.canCallIntoJs()) + return envObject.setLastError(envObject.moduleApiVersion >= 10 ? 23 : 10); + envObject.clearLastError(); + try { + if (!key) + return envObject.setLastError(1); + if (!value) + return envObject.setLastError(1); + if (!object) + return envObject.setLastError(1); + var h = emnapiCtx.handleStore.get(object); + if (!(h.isObject() || h.isFunction())) { + return envObject.setLastError(2); + } + h.value[emnapiCtx.handleStore.get(key).value] = emnapiCtx.handleStore.get(value).value; + return envObject.getReturnStatus(); + } + catch (err) { + envObject.tryCatch.setError(err); + return envObject.setLastError(10); + } + } + function napi_has_property(env, object, key, result) { + var r; + if (!env) + return 1; + var envObject = emnapiCtx.envStore.get(env); + envObject.checkGCAccess(); + if (!envObject.tryCatch.isEmpty()) + return envObject.setLastError(10); + if (!envObject.canCallIntoJs()) + return envObject.setLastError(envObject.moduleApiVersion >= 10 ? 23 : 10); + envObject.clearLastError(); + try { + if (!key) + return envObject.setLastError(1); + if (!result) + return envObject.setLastError(1); + if (!object) + return envObject.setLastError(1); + var h = emnapiCtx.handleStore.get(object); + if (h.value == null) { + throw new TypeError('Cannot convert undefined or null to object'); + } + var v = void 0; + try { + v = h.isObject() || h.isFunction() ? h.value : Object(h.value); + } + catch (_) { + return envObject.setLastError(2); + } + result >>>= 0; + r = (emnapiCtx.handleStore.get(key).value in v) ? 1 : 0; + var HEAP_DATA_VIEW = new DataView(wasmMemory.buffer), GET_HEAP_DATA_VIEW = function () { return HEAP_DATA_VIEW.buffer === wasmMemory.buffer ? HEAP_DATA_VIEW : (HEAP_DATA_VIEW = new DataView(wasmMemory.buffer)); }; + GET_HEAP_DATA_VIEW().setInt8(result, r, true); + return envObject.getReturnStatus(); + } + catch (err) { + envObject.tryCatch.setError(err); + return envObject.setLastError(10); + } + } + function napi_get_property(env, object, key, result) { + var value; + if (!env) + return 1; + var envObject = emnapiCtx.envStore.get(env); + envObject.checkGCAccess(); + if (!envObject.tryCatch.isEmpty()) + return envObject.setLastError(10); + if (!envObject.canCallIntoJs()) + return envObject.setLastError(envObject.moduleApiVersion >= 10 ? 23 : 10); + envObject.clearLastError(); + try { + if (!key) + return envObject.setLastError(1); + if (!result) + return envObject.setLastError(1); + if (!object) + return envObject.setLastError(1); + var h = emnapiCtx.handleStore.get(object); + if (h.value == null) { + throw new TypeError('Cannot convert undefined or null to object'); + } + var v = void 0; + try { + v = h.isObject() || h.isFunction() ? h.value : Object(h.value); + } + catch (_) { + return envObject.setLastError(2); + } + result >>>= 0; + value = envObject.ensureHandleId(v[emnapiCtx.handleStore.get(key).value]); + var HEAP_DATA_VIEW = new DataView(wasmMemory.buffer), GET_HEAP_DATA_VIEW = function () { return HEAP_DATA_VIEW.buffer === wasmMemory.buffer ? HEAP_DATA_VIEW : (HEAP_DATA_VIEW = new DataView(wasmMemory.buffer)); }; + GET_HEAP_DATA_VIEW().setUint32(result, value, true); + return envObject.getReturnStatus(); + } + catch (err) { + envObject.tryCatch.setError(err); + return envObject.setLastError(10); + } + } + function napi_delete_property(env, object, key, result) { + var r; + if (!env) + return 1; + var envObject = emnapiCtx.envStore.get(env); + envObject.checkGCAccess(); + if (!envObject.tryCatch.isEmpty()) + return envObject.setLastError(10); + if (!envObject.canCallIntoJs()) + return envObject.setLastError(envObject.moduleApiVersion >= 10 ? 23 : 10); + envObject.clearLastError(); + try { + if (!key) + return envObject.setLastError(1); + if (!object) + return envObject.setLastError(1); + var h = emnapiCtx.handleStore.get(object); + if (!(h.isObject() || h.isFunction())) { + return envObject.setLastError(2); + } + var propertyKey = emnapiCtx.handleStore.get(key).value; + if (emnapiCtx.feature.supportReflect) { + r = Reflect.deleteProperty(h.value, propertyKey); + } + else { + try { + r = delete h.value[propertyKey]; + } + catch (_) { + r = false; + } + } + if (result) { + result >>>= 0; + var HEAP_DATA_VIEW = new DataView(wasmMemory.buffer), GET_HEAP_DATA_VIEW = function () { return HEAP_DATA_VIEW.buffer === wasmMemory.buffer ? HEAP_DATA_VIEW : (HEAP_DATA_VIEW = new DataView(wasmMemory.buffer)); }; + GET_HEAP_DATA_VIEW().setInt8(result, r ? 1 : 0, true); + } + return envObject.getReturnStatus(); + } + catch (err) { + envObject.tryCatch.setError(err); + return envObject.setLastError(10); + } + } + function napi_has_own_property(env, object, key, result) { + var r; + if (!env) + return 1; + var envObject = emnapiCtx.envStore.get(env); + envObject.checkGCAccess(); + if (!envObject.tryCatch.isEmpty()) + return envObject.setLastError(10); + if (!envObject.canCallIntoJs()) + return envObject.setLastError(envObject.moduleApiVersion >= 10 ? 23 : 10); + envObject.clearLastError(); + try { + if (!key) + return envObject.setLastError(1); + if (!result) + return envObject.setLastError(1); + if (!object) + return envObject.setLastError(1); + var h = emnapiCtx.handleStore.get(object); + if (h.value == null) { + throw new TypeError('Cannot convert undefined or null to object'); + } + var v = void 0; + try { + v = h.isObject() || h.isFunction() ? h.value : Object(h.value); + } + catch (_) { + return envObject.setLastError(2); + } + var prop = emnapiCtx.handleStore.get(key).value; + if (typeof prop !== 'string' && typeof prop !== 'symbol') { + return envObject.setLastError(4); + } + r = Object.prototype.hasOwnProperty.call(v, emnapiCtx.handleStore.get(key).value); + result >>>= 0; + var HEAP_DATA_VIEW = new DataView(wasmMemory.buffer), GET_HEAP_DATA_VIEW = function () { return HEAP_DATA_VIEW.buffer === wasmMemory.buffer ? HEAP_DATA_VIEW : (HEAP_DATA_VIEW = new DataView(wasmMemory.buffer)); }; + GET_HEAP_DATA_VIEW().setInt8(result, r ? 1 : 0, true); + return envObject.getReturnStatus(); + } + catch (err) { + envObject.tryCatch.setError(err); + return envObject.setLastError(10); + } + } + function napi_set_named_property(env, object, cname, value) { + if (!env) + return 1; + var envObject = emnapiCtx.envStore.get(env); + envObject.checkGCAccess(); + if (!envObject.tryCatch.isEmpty()) + return envObject.setLastError(10); + if (!envObject.canCallIntoJs()) + return envObject.setLastError(envObject.moduleApiVersion >= 10 ? 23 : 10); + envObject.clearLastError(); + try { + if (!value) + return envObject.setLastError(1); + if (!object) + return envObject.setLastError(1); + var h = emnapiCtx.handleStore.get(object); + if (!(h.isObject() || h.isFunction())) { + return envObject.setLastError(2); + } + if (!cname) { + return envObject.setLastError(1); + } + cname >>>= 0; + emnapiCtx.handleStore.get(object).value[emnapiString.UTF8ToString(cname, -1)] = emnapiCtx.handleStore.get(value).value; + return envObject.getReturnStatus(); + } + catch (err) { + envObject.tryCatch.setError(err); + return envObject.setLastError(10); + } + } + function napi_has_named_property(env, object, utf8name, result) { + var r; + if (!env) + return 1; + var envObject = emnapiCtx.envStore.get(env); + envObject.checkGCAccess(); + if (!envObject.tryCatch.isEmpty()) + return envObject.setLastError(10); + if (!envObject.canCallIntoJs()) + return envObject.setLastError(envObject.moduleApiVersion >= 10 ? 23 : 10); + envObject.clearLastError(); + try { + if (!result) + return envObject.setLastError(1); + if (!object) + return envObject.setLastError(1); + if (!utf8name) { + return envObject.setLastError(1); + } + var h = emnapiCtx.handleStore.get(object); + if (h.value == null) { + throw new TypeError('Cannot convert undefined or null to object'); + } + var v = void 0; + try { + v = h.isObject() || h.isFunction() ? h.value : Object(h.value); + } + catch (_) { + return envObject.setLastError(2); + } + utf8name >>>= 0; + result >>>= 0; + r = emnapiString.UTF8ToString(utf8name, -1) in v; + var HEAP_DATA_VIEW = new DataView(wasmMemory.buffer), GET_HEAP_DATA_VIEW = function () { return HEAP_DATA_VIEW.buffer === wasmMemory.buffer ? HEAP_DATA_VIEW : (HEAP_DATA_VIEW = new DataView(wasmMemory.buffer)); }; + GET_HEAP_DATA_VIEW().setInt8(result, r ? 1 : 0, true); + return envObject.getReturnStatus(); + } + catch (err) { + envObject.tryCatch.setError(err); + return envObject.setLastError(10); + } + } + function napi_get_named_property(env, object, utf8name, result) { + var value; + if (!env) + return 1; + var envObject = emnapiCtx.envStore.get(env); + envObject.checkGCAccess(); + if (!envObject.tryCatch.isEmpty()) + return envObject.setLastError(10); + if (!envObject.canCallIntoJs()) + return envObject.setLastError(envObject.moduleApiVersion >= 10 ? 23 : 10); + envObject.clearLastError(); + try { + if (!result) + return envObject.setLastError(1); + if (!object) + return envObject.setLastError(1); + if (!utf8name) { + return envObject.setLastError(1); + } + var h = emnapiCtx.handleStore.get(object); + if (h.value == null) { + throw new TypeError('Cannot convert undefined or null to object'); + } + var v = void 0; + try { + v = h.isObject() || h.isFunction() ? h.value : Object(h.value); + } + catch (_) { + return envObject.setLastError(2); + } + utf8name >>>= 0; + result >>>= 0; + value = envObject.ensureHandleId(v[emnapiString.UTF8ToString(utf8name, -1)]); + var HEAP_DATA_VIEW = new DataView(wasmMemory.buffer), GET_HEAP_DATA_VIEW = function () { return HEAP_DATA_VIEW.buffer === wasmMemory.buffer ? HEAP_DATA_VIEW : (HEAP_DATA_VIEW = new DataView(wasmMemory.buffer)); }; + GET_HEAP_DATA_VIEW().setUint32(result, value, true); + return envObject.getReturnStatus(); + } + catch (err) { + envObject.tryCatch.setError(err); + return envObject.setLastError(10); + } + } + function napi_set_element(env, object, index, value) { + if (!env) + return 1; + var envObject = emnapiCtx.envStore.get(env); + envObject.checkGCAccess(); + if (!envObject.tryCatch.isEmpty()) + return envObject.setLastError(10); + if (!envObject.canCallIntoJs()) + return envObject.setLastError(envObject.moduleApiVersion >= 10 ? 23 : 10); + envObject.clearLastError(); + try { + if (!value) + return envObject.setLastError(1); + if (!object) + return envObject.setLastError(1); + var h = emnapiCtx.handleStore.get(object); + if (!(h.isObject() || h.isFunction())) { + return envObject.setLastError(2); + } + h.value[index >>> 0] = emnapiCtx.handleStore.get(value).value; + return envObject.getReturnStatus(); + } + catch (err) { + envObject.tryCatch.setError(err); + return envObject.setLastError(10); + } + } + function napi_has_element(env, object, index, result) { + var r; + if (!env) + return 1; + var envObject = emnapiCtx.envStore.get(env); + envObject.checkGCAccess(); + if (!envObject.tryCatch.isEmpty()) + return envObject.setLastError(10); + if (!envObject.canCallIntoJs()) + return envObject.setLastError(envObject.moduleApiVersion >= 10 ? 23 : 10); + envObject.clearLastError(); + try { + if (!result) + return envObject.setLastError(1); + if (!object) + return envObject.setLastError(1); + var h = emnapiCtx.handleStore.get(object); + if (h.value == null) { + throw new TypeError('Cannot convert undefined or null to object'); + } + var v = void 0; + try { + v = h.isObject() || h.isFunction() ? h.value : Object(h.value); + } + catch (_) { + return envObject.setLastError(2); + } + result >>>= 0; + r = ((index >>> 0) in v) ? 1 : 0; + var HEAP_DATA_VIEW = new DataView(wasmMemory.buffer), GET_HEAP_DATA_VIEW = function () { return HEAP_DATA_VIEW.buffer === wasmMemory.buffer ? HEAP_DATA_VIEW : (HEAP_DATA_VIEW = new DataView(wasmMemory.buffer)); }; + GET_HEAP_DATA_VIEW().setInt8(result, r, true); + return envObject.getReturnStatus(); + } + catch (err) { + envObject.tryCatch.setError(err); + return envObject.setLastError(10); + } + } + function napi_get_element(env, object, index, result) { + var value; + if (!env) + return 1; + var envObject = emnapiCtx.envStore.get(env); + envObject.checkGCAccess(); + if (!envObject.tryCatch.isEmpty()) + return envObject.setLastError(10); + if (!envObject.canCallIntoJs()) + return envObject.setLastError(envObject.moduleApiVersion >= 10 ? 23 : 10); + envObject.clearLastError(); + try { + if (!result) + return envObject.setLastError(1); + if (!object) + return envObject.setLastError(1); + var h = emnapiCtx.handleStore.get(object); + if (h.value == null) { + throw new TypeError('Cannot convert undefined or null to object'); + } + var v = void 0; + try { + v = h.isObject() || h.isFunction() ? h.value : Object(h.value); + } + catch (_) { + return envObject.setLastError(2); + } + result >>>= 0; + value = envObject.ensureHandleId(v[index >>> 0]); + var HEAP_DATA_VIEW = new DataView(wasmMemory.buffer), GET_HEAP_DATA_VIEW = function () { return HEAP_DATA_VIEW.buffer === wasmMemory.buffer ? HEAP_DATA_VIEW : (HEAP_DATA_VIEW = new DataView(wasmMemory.buffer)); }; + GET_HEAP_DATA_VIEW().setUint32(result, value, true); + return envObject.getReturnStatus(); + } + catch (err) { + envObject.tryCatch.setError(err); + return envObject.setLastError(10); + } + } + function napi_delete_element(env, object, index, result) { + var r; + if (!env) + return 1; + var envObject = emnapiCtx.envStore.get(env); + envObject.checkGCAccess(); + if (!envObject.tryCatch.isEmpty()) + return envObject.setLastError(10); + if (!envObject.canCallIntoJs()) + return envObject.setLastError(envObject.moduleApiVersion >= 10 ? 23 : 10); + envObject.clearLastError(); + try { + if (!object) + return envObject.setLastError(1); + var h = emnapiCtx.handleStore.get(object); + if (!(h.isObject() || h.isFunction())) { + return envObject.setLastError(2); + } + if (emnapiCtx.feature.supportReflect) { + r = Reflect.deleteProperty(h.value, index >>> 0); + } + else { + try { + r = delete h.value[index >>> 0]; + } + catch (_) { + r = false; + } + } + if (result) { + result >>>= 0; + var HEAP_DATA_VIEW = new DataView(wasmMemory.buffer), GET_HEAP_DATA_VIEW = function () { return HEAP_DATA_VIEW.buffer === wasmMemory.buffer ? HEAP_DATA_VIEW : (HEAP_DATA_VIEW = new DataView(wasmMemory.buffer)); }; + GET_HEAP_DATA_VIEW().setInt8(result, r ? 1 : 0, true); + } + return envObject.getReturnStatus(); + } + catch (err) { + envObject.tryCatch.setError(err); + return envObject.setLastError(10); + } + } + function napi_define_properties(env, object, property_count, properties) { + var propPtr, attributes; + if (!env) + return 1; + var envObject = emnapiCtx.envStore.get(env); + envObject.checkGCAccess(); + if (!envObject.tryCatch.isEmpty()) + return envObject.setLastError(10); + if (!envObject.canCallIntoJs()) + return envObject.setLastError(envObject.moduleApiVersion >= 10 ? 23 : 10); + envObject.clearLastError(); + try { + properties >>>= 0; + property_count >>>= 0; + property_count = property_count >>> 0; + if (property_count > 0) { + if (!properties) + return envObject.setLastError(1); + } + if (!object) + return envObject.setLastError(1); + var h = emnapiCtx.handleStore.get(object); + var maybeObject = h.value; + if (!(h.isObject() || h.isFunction())) { + return envObject.setLastError(2); + } + var propertyName = void 0; + var HEAP_DATA_VIEW = new DataView(wasmMemory.buffer), GET_HEAP_DATA_VIEW = function () { return HEAP_DATA_VIEW.buffer === wasmMemory.buffer ? HEAP_DATA_VIEW : (HEAP_DATA_VIEW = new DataView(wasmMemory.buffer)); }; + for (var i = 0; i < property_count; i++) { + propPtr = properties + (i * (4 * 8)); + var utf8Name = GET_HEAP_DATA_VIEW().getUint32(propPtr, true); + var name_2 = GET_HEAP_DATA_VIEW().getUint32(propPtr + 4, true); + var method = GET_HEAP_DATA_VIEW().getUint32(propPtr + 8, true); + var getter = GET_HEAP_DATA_VIEW().getUint32(propPtr + 12, true); + var setter = GET_HEAP_DATA_VIEW().getUint32(propPtr + 16, true); + var value = GET_HEAP_DATA_VIEW().getUint32(propPtr + 20, true); + attributes = GET_HEAP_DATA_VIEW().getInt32(propPtr + 24, true); + attributes >>>= 0; + var data = GET_HEAP_DATA_VIEW().getUint32(propPtr + 28, true); + if (utf8Name) { + propertyName = emnapiString.UTF8ToString(utf8Name, -1); + } + else { + if (!name_2) { + return envObject.setLastError(4); + } + propertyName = emnapiCtx.handleStore.get(name_2).value; + if (typeof propertyName !== 'string' && typeof propertyName !== 'symbol') { + return envObject.setLastError(4); + } + } + emnapiDefineProperty(envObject, maybeObject, propertyName, method, getter, setter, value, attributes, data); + } + return envObject.getReturnStatus(); + } + catch (err) { + envObject.tryCatch.setError(err); + return envObject.setLastError(10); + } + } + function napi_object_freeze(env, object) { + if (!env) + return 1; + var envObject = emnapiCtx.envStore.get(env); + envObject.checkGCAccess(); + if (!envObject.tryCatch.isEmpty()) + return envObject.setLastError(10); + if (!envObject.canCallIntoJs()) + return envObject.setLastError(envObject.moduleApiVersion >= 10 ? 23 : 10); + envObject.clearLastError(); + try { + if (!object) + return envObject.setLastError(1); + var h = emnapiCtx.handleStore.get(object); + var maybeObject = h.value; + if (!(h.isObject() || h.isFunction())) { + return envObject.setLastError(2); + } + Object.freeze(maybeObject); + return envObject.getReturnStatus(); + } + catch (err) { + envObject.tryCatch.setError(err); + return envObject.setLastError(10); + } + } + function napi_object_seal(env, object) { + if (!env) + return 1; + var envObject = emnapiCtx.envStore.get(env); + envObject.checkGCAccess(); + if (!envObject.tryCatch.isEmpty()) + return envObject.setLastError(10); + if (!envObject.canCallIntoJs()) + return envObject.setLastError(envObject.moduleApiVersion >= 10 ? 23 : 10); + envObject.clearLastError(); + try { + if (!object) + return envObject.setLastError(1); + var h = emnapiCtx.handleStore.get(object); + var maybeObject = h.value; + if (!(h.isObject() || h.isFunction())) { + return envObject.setLastError(2); + } + Object.seal(maybeObject); + return envObject.getReturnStatus(); + } + catch (err) { + envObject.tryCatch.setError(err); + return envObject.setLastError(10); + } + } + var propertyMod = Object.freeze({ + __proto__: null, + napi_define_properties: napi_define_properties, + napi_delete_element: napi_delete_element, + napi_delete_property: napi_delete_property, + napi_get_all_property_names: napi_get_all_property_names, + napi_get_element: napi_get_element, + napi_get_named_property: napi_get_named_property, + napi_get_property: napi_get_property, + napi_get_property_names: napi_get_property_names, + napi_has_element: napi_has_element, + napi_has_named_property: napi_has_named_property, + napi_has_own_property: napi_has_own_property, + napi_has_property: napi_has_property, + napi_object_freeze: napi_object_freeze, + napi_object_seal: napi_object_seal, + napi_set_element: napi_set_element, + napi_set_named_property: napi_set_named_property, + napi_set_property: napi_set_property + }); + function napi_run_script(env, script, result) { + var status; + var value; + if (!env) + return 1; + var envObject = emnapiCtx.envStore.get(env); + envObject.checkGCAccess(); + if (!envObject.tryCatch.isEmpty()) + return envObject.setLastError(10); + if (!envObject.canCallIntoJs()) + return envObject.setLastError(envObject.moduleApiVersion >= 10 ? 23 : 10); + envObject.clearLastError(); + try { + if (!script) + return envObject.setLastError(1); + if (!result) + return envObject.setLastError(1); + var v8Script = emnapiCtx.handleStore.get(script); + if (!v8Script.isString()) { + return envObject.setLastError(3); + } + var g = emnapiCtx.handleStore.get(5).value; + var ret = g.eval(v8Script.value); + result >>>= 0; + value = envObject.ensureHandleId(ret); + var HEAP_DATA_VIEW = new DataView(wasmMemory.buffer), GET_HEAP_DATA_VIEW = function () { return HEAP_DATA_VIEW.buffer === wasmMemory.buffer ? HEAP_DATA_VIEW : (HEAP_DATA_VIEW = new DataView(wasmMemory.buffer)); }; + GET_HEAP_DATA_VIEW().setUint32(result, value, true); + status = envObject.getReturnStatus(); + } + catch (err) { + envObject.tryCatch.setError(err); + return envObject.setLastError(10); + } + return status; + } + var scriptMod = Object.freeze({ + __proto__: null, + napi_run_script: napi_run_script + }); + function napi_typeof(env, value, result) { + if (!env) + return 1; + var envObject = emnapiCtx.envStore.get(env); + envObject.checkGCAccess(); + if (!value) + return envObject.setLastError(1); + if (!result) + return envObject.setLastError(1); + var v = emnapiCtx.handleStore.get(value); + result >>>= 0; + var r; + if (v.isNumber()) { + r = 3; + } + else if (v.isBigInt()) { + r = 9; + } + else if (v.isString()) { + r = 4; + } + else if (v.isFunction()) { + r = 7; + } + else if (v.isExternal()) { + r = 8; + } + else if (v.isObject()) { + r = 6; + } + else if (v.isBoolean()) { + r = 2; + } + else if (v.isUndefined()) { + r = 0; + } + else if (v.isSymbol()) { + r = 5; + } + else if (v.isNull()) { + r = 1; + } + else { + return envObject.setLastError(1); + } + var HEAP_DATA_VIEW = new DataView(wasmMemory.buffer), GET_HEAP_DATA_VIEW = function () { return HEAP_DATA_VIEW.buffer === wasmMemory.buffer ? HEAP_DATA_VIEW : (HEAP_DATA_VIEW = new DataView(wasmMemory.buffer)); }; + GET_HEAP_DATA_VIEW().setInt32(result, r, true); + return envObject.clearLastError(); + } + function napi_coerce_to_bool(env, value, result) { + var v; + if (!env) + return 1; + var envObject = emnapiCtx.envStore.get(env); + envObject.checkGCAccess(); + if (!envObject.tryCatch.isEmpty()) + return envObject.setLastError(10); + if (!envObject.canCallIntoJs()) + return envObject.setLastError(envObject.moduleApiVersion >= 10 ? 23 : 10); + envObject.clearLastError(); + try { + if (!value) + return envObject.setLastError(1); + if (!result) + return envObject.setLastError(1); + var handle = emnapiCtx.handleStore.get(value); + result >>>= 0; + v = handle.value ? 4 : 3; + var HEAP_DATA_VIEW = new DataView(wasmMemory.buffer), GET_HEAP_DATA_VIEW = function () { return HEAP_DATA_VIEW.buffer === wasmMemory.buffer ? HEAP_DATA_VIEW : (HEAP_DATA_VIEW = new DataView(wasmMemory.buffer)); }; + GET_HEAP_DATA_VIEW().setUint32(result, v, true); + return envObject.getReturnStatus(); + } + catch (err) { + envObject.tryCatch.setError(err); + return envObject.setLastError(10); + } + } + function napi_coerce_to_number(env, value, result) { + var v; + if (!env) + return 1; + var envObject = emnapiCtx.envStore.get(env); + envObject.checkGCAccess(); + if (!envObject.tryCatch.isEmpty()) + return envObject.setLastError(10); + if (!envObject.canCallIntoJs()) + return envObject.setLastError(envObject.moduleApiVersion >= 10 ? 23 : 10); + envObject.clearLastError(); + try { + if (!value) + return envObject.setLastError(1); + if (!result) + return envObject.setLastError(1); + var handle = emnapiCtx.handleStore.get(value); + if (handle.isBigInt()) { + throw new TypeError('Cannot convert a BigInt value to a number'); + } + result >>>= 0; + v = emnapiCtx.addToCurrentScope(Number(handle.value)).id; + var HEAP_DATA_VIEW = new DataView(wasmMemory.buffer), GET_HEAP_DATA_VIEW = function () { return HEAP_DATA_VIEW.buffer === wasmMemory.buffer ? HEAP_DATA_VIEW : (HEAP_DATA_VIEW = new DataView(wasmMemory.buffer)); }; + GET_HEAP_DATA_VIEW().setUint32(result, v, true); + return envObject.getReturnStatus(); + } + catch (err) { + envObject.tryCatch.setError(err); + return envObject.setLastError(10); + } + } + function napi_coerce_to_object(env, value, result) { + var v; + if (!env) + return 1; + var envObject = emnapiCtx.envStore.get(env); + envObject.checkGCAccess(); + if (!envObject.tryCatch.isEmpty()) + return envObject.setLastError(10); + if (!envObject.canCallIntoJs()) + return envObject.setLastError(envObject.moduleApiVersion >= 10 ? 23 : 10); + envObject.clearLastError(); + try { + if (!value) + return envObject.setLastError(1); + if (!result) + return envObject.setLastError(1); + var handle = emnapiCtx.handleStore.get(value); + if (handle.value == null) { + throw new TypeError('Cannot convert undefined or null to object'); + } + result >>>= 0; + v = envObject.ensureHandleId(Object(handle.value)); + var HEAP_DATA_VIEW = new DataView(wasmMemory.buffer), GET_HEAP_DATA_VIEW = function () { return HEAP_DATA_VIEW.buffer === wasmMemory.buffer ? HEAP_DATA_VIEW : (HEAP_DATA_VIEW = new DataView(wasmMemory.buffer)); }; + GET_HEAP_DATA_VIEW().setUint32(result, v, true); + return envObject.getReturnStatus(); + } + catch (err) { + envObject.tryCatch.setError(err); + return envObject.setLastError(10); + } + } + function napi_coerce_to_string(env, value, result) { + var v; + if (!env) + return 1; + var envObject = emnapiCtx.envStore.get(env); + envObject.checkGCAccess(); + if (!envObject.tryCatch.isEmpty()) + return envObject.setLastError(10); + if (!envObject.canCallIntoJs()) + return envObject.setLastError(envObject.moduleApiVersion >= 10 ? 23 : 10); + envObject.clearLastError(); + try { + if (!value) + return envObject.setLastError(1); + if (!result) + return envObject.setLastError(1); + var handle = emnapiCtx.handleStore.get(value); + if (handle.isSymbol()) { + throw new TypeError('Cannot convert a Symbol value to a string'); + } + result >>>= 0; + v = emnapiCtx.addToCurrentScope(String(handle.value)).id; + var HEAP_DATA_VIEW = new DataView(wasmMemory.buffer), GET_HEAP_DATA_VIEW = function () { return HEAP_DATA_VIEW.buffer === wasmMemory.buffer ? HEAP_DATA_VIEW : (HEAP_DATA_VIEW = new DataView(wasmMemory.buffer)); }; + GET_HEAP_DATA_VIEW().setUint32(result, v, true); + return envObject.getReturnStatus(); + } + catch (err) { + envObject.tryCatch.setError(err); + return envObject.setLastError(10); + } + } + function napi_instanceof(env, object, constructor, result) { + var r; + if (!env) + return 1; + var envObject = emnapiCtx.envStore.get(env); + envObject.checkGCAccess(); + if (!envObject.tryCatch.isEmpty()) + return envObject.setLastError(10); + if (!envObject.canCallIntoJs()) + return envObject.setLastError(envObject.moduleApiVersion >= 10 ? 23 : 10); + envObject.clearLastError(); + try { + if (!object) + return envObject.setLastError(1); + if (!result) + return envObject.setLastError(1); + if (!constructor) + return envObject.setLastError(1); + result >>>= 0; + var HEAP_DATA_VIEW = new DataView(wasmMemory.buffer), GET_HEAP_DATA_VIEW = function () { return HEAP_DATA_VIEW.buffer === wasmMemory.buffer ? HEAP_DATA_VIEW : (HEAP_DATA_VIEW = new DataView(wasmMemory.buffer)); }; + GET_HEAP_DATA_VIEW().setInt8(result, 0, true); + var ctor = emnapiCtx.handleStore.get(constructor); + if (!ctor.isFunction()) { + return envObject.setLastError(5); + } + var val = emnapiCtx.handleStore.get(object).value; + var ret = val instanceof ctor.value; + r = ret ? 1 : 0; + GET_HEAP_DATA_VIEW().setInt8(result, r, true); + return envObject.getReturnStatus(); + } + catch (err) { + envObject.tryCatch.setError(err); + return envObject.setLastError(10); + } + } + function napi_is_array(env, value, result) { + if (!env) + return 1; + var envObject = emnapiCtx.envStore.get(env); + envObject.checkGCAccess(); + if (!value) + return envObject.setLastError(1); + if (!result) + return envObject.setLastError(1); + var h = emnapiCtx.handleStore.get(value); + result >>>= 0; + var r = h.isArray() ? 1 : 0; + var HEAP_DATA_VIEW = new DataView(wasmMemory.buffer), GET_HEAP_DATA_VIEW = function () { return HEAP_DATA_VIEW.buffer === wasmMemory.buffer ? HEAP_DATA_VIEW : (HEAP_DATA_VIEW = new DataView(wasmMemory.buffer)); }; + GET_HEAP_DATA_VIEW().setInt8(result, r, true); + return envObject.clearLastError(); + } + function napi_is_arraybuffer(env, value, result) { + if (!env) + return 1; + var envObject = emnapiCtx.envStore.get(env); + envObject.checkGCAccess(); + if (!value) + return envObject.setLastError(1); + if (!result) + return envObject.setLastError(1); + var h = emnapiCtx.handleStore.get(value); + result >>>= 0; + var r = h.isArrayBuffer() ? 1 : 0; + var HEAP_DATA_VIEW = new DataView(wasmMemory.buffer), GET_HEAP_DATA_VIEW = function () { return HEAP_DATA_VIEW.buffer === wasmMemory.buffer ? HEAP_DATA_VIEW : (HEAP_DATA_VIEW = new DataView(wasmMemory.buffer)); }; + GET_HEAP_DATA_VIEW().setInt8(result, r, true); + return envObject.clearLastError(); + } + function node_api_is_sharedarraybuffer(env, value, result) { + if (!env) + return 1; + var envObject = emnapiCtx.envStore.get(env); + envObject.checkGCAccess(); + if (!value) + return envObject.setLastError(1); + if (!result) + return envObject.setLastError(1); + var h = emnapiCtx.handleStore.get(value); + result >>>= 0; + var r = ((typeof SharedArrayBuffer === 'function' && h.value instanceof SharedArrayBuffer) || + (Object.prototype.toString.call(h.value) === '[object SharedArrayBuffer]')) + ? 1 + : 0; + var HEAP_DATA_VIEW = new DataView(wasmMemory.buffer), GET_HEAP_DATA_VIEW = function () { return HEAP_DATA_VIEW.buffer === wasmMemory.buffer ? HEAP_DATA_VIEW : (HEAP_DATA_VIEW = new DataView(wasmMemory.buffer)); }; + GET_HEAP_DATA_VIEW().setInt8(result, r, true); + return envObject.clearLastError(); + } + function napi_is_date(env, value, result) { + if (!env) + return 1; + var envObject = emnapiCtx.envStore.get(env); + envObject.checkGCAccess(); + if (!value) + return envObject.setLastError(1); + if (!result) + return envObject.setLastError(1); + var h = emnapiCtx.handleStore.get(value); + result >>>= 0; + var r = h.isDate() ? 1 : 0; + var HEAP_DATA_VIEW = new DataView(wasmMemory.buffer), GET_HEAP_DATA_VIEW = function () { return HEAP_DATA_VIEW.buffer === wasmMemory.buffer ? HEAP_DATA_VIEW : (HEAP_DATA_VIEW = new DataView(wasmMemory.buffer)); }; + GET_HEAP_DATA_VIEW().setInt8(result, r, true); + return envObject.clearLastError(); + } + function napi_is_error(env, value, result) { + if (!env) + return 1; + var envObject = emnapiCtx.envStore.get(env); + envObject.checkGCAccess(); + if (!value) + return envObject.setLastError(1); + if (!result) + return envObject.setLastError(1); + var val = emnapiCtx.handleStore.get(value).value; + result >>>= 0; + var r = (val instanceof Error) ? 1 : 0; + var HEAP_DATA_VIEW = new DataView(wasmMemory.buffer), GET_HEAP_DATA_VIEW = function () { return HEAP_DATA_VIEW.buffer === wasmMemory.buffer ? HEAP_DATA_VIEW : (HEAP_DATA_VIEW = new DataView(wasmMemory.buffer)); }; + GET_HEAP_DATA_VIEW().setInt8(result, r, true); + return envObject.clearLastError(); + } + function napi_is_typedarray(env, value, result) { + if (!env) + return 1; + var envObject = emnapiCtx.envStore.get(env); + envObject.checkGCAccess(); + if (!value) + return envObject.setLastError(1); + if (!result) + return envObject.setLastError(1); + var h = emnapiCtx.handleStore.get(value); + result >>>= 0; + var r = h.isTypedArray() ? 1 : 0; + var HEAP_DATA_VIEW = new DataView(wasmMemory.buffer), GET_HEAP_DATA_VIEW = function () { return HEAP_DATA_VIEW.buffer === wasmMemory.buffer ? HEAP_DATA_VIEW : (HEAP_DATA_VIEW = new DataView(wasmMemory.buffer)); }; + GET_HEAP_DATA_VIEW().setInt8(result, r, true); + return envObject.clearLastError(); + } + function napi_is_buffer(env, value, result) { + if (!env) + return 1; + var envObject = emnapiCtx.envStore.get(env); + envObject.checkGCAccess(); + if (!value) + return envObject.setLastError(1); + if (!result) + return envObject.setLastError(1); + var h = emnapiCtx.handleStore.get(value); + result >>>= 0; + var r = h.isBuffer(emnapiCtx.feature.Buffer) ? 1 : 0; + var HEAP_DATA_VIEW = new DataView(wasmMemory.buffer), GET_HEAP_DATA_VIEW = function () { return HEAP_DATA_VIEW.buffer === wasmMemory.buffer ? HEAP_DATA_VIEW : (HEAP_DATA_VIEW = new DataView(wasmMemory.buffer)); }; + GET_HEAP_DATA_VIEW().setInt8(result, r, true); + return envObject.clearLastError(); + } + function napi_is_dataview(env, value, result) { + if (!env) + return 1; + var envObject = emnapiCtx.envStore.get(env); + envObject.checkGCAccess(); + if (!value) + return envObject.setLastError(1); + if (!result) + return envObject.setLastError(1); + var h = emnapiCtx.handleStore.get(value); + result >>>= 0; + var r = h.isDataView() ? 1 : 0; + var HEAP_DATA_VIEW = new DataView(wasmMemory.buffer), GET_HEAP_DATA_VIEW = function () { return HEAP_DATA_VIEW.buffer === wasmMemory.buffer ? HEAP_DATA_VIEW : (HEAP_DATA_VIEW = new DataView(wasmMemory.buffer)); }; + GET_HEAP_DATA_VIEW().setInt8(result, r, true); + return envObject.clearLastError(); + } + function napi_strict_equals(env, lhs, rhs, result) { + var r; + if (!env) + return 1; + var envObject = emnapiCtx.envStore.get(env); + envObject.checkGCAccess(); + if (!envObject.tryCatch.isEmpty()) + return envObject.setLastError(10); + if (!envObject.canCallIntoJs()) + return envObject.setLastError(envObject.moduleApiVersion >= 10 ? 23 : 10); + envObject.clearLastError(); + try { + if (!lhs) + return envObject.setLastError(1); + if (!rhs) + return envObject.setLastError(1); + if (!result) + return envObject.setLastError(1); + var lv = emnapiCtx.handleStore.get(lhs).value; + var rv = emnapiCtx.handleStore.get(rhs).value; + result >>>= 0; + r = (lv === rv) ? 1 : 0; + var HEAP_DATA_VIEW = new DataView(wasmMemory.buffer), GET_HEAP_DATA_VIEW = function () { return HEAP_DATA_VIEW.buffer === wasmMemory.buffer ? HEAP_DATA_VIEW : (HEAP_DATA_VIEW = new DataView(wasmMemory.buffer)); }; + GET_HEAP_DATA_VIEW().setInt8(result, r, true); + return envObject.getReturnStatus(); + } + catch (err) { + envObject.tryCatch.setError(err); + return envObject.setLastError(10); + } + } + function napi_detach_arraybuffer(env, arraybuffer) { + if (!env) + return 1; + var envObject = emnapiCtx.envStore.get(env); + envObject.checkGCAccess(); + if (!arraybuffer) + return envObject.setLastError(1); + var value = emnapiCtx.handleStore.get(arraybuffer).value; + if (!(value instanceof ArrayBuffer)) { + if (typeof SharedArrayBuffer === 'function' && (value instanceof SharedArrayBuffer)) { + return envObject.setLastError(20); + } + return envObject.setLastError(19); + } + try { + var MessageChannel_1 = emnapiCtx.feature.MessageChannel; + var messageChannel = new MessageChannel_1(); + messageChannel.port1.postMessage(value, [value]); + } + catch (_) { + return envObject.setLastError(9); + } + return envObject.clearLastError(); + } + function napi_is_detached_arraybuffer(env, arraybuffer, result) { + if (!env) + return 1; + var envObject = emnapiCtx.envStore.get(env); + envObject.checkGCAccess(); + if (!envObject.tryCatch.isEmpty()) + return envObject.setLastError(10); + if (!envObject.canCallIntoJs()) + return envObject.setLastError(envObject.moduleApiVersion >= 10 ? 23 : 10); + envObject.clearLastError(); + try { + if (!arraybuffer) + return envObject.setLastError(1); + if (!result) + return envObject.setLastError(1); + var h = emnapiCtx.handleStore.get(arraybuffer); + result >>>= 0; + var HEAP_DATA_VIEW = new DataView(wasmMemory.buffer), GET_HEAP_DATA_VIEW = function () { return HEAP_DATA_VIEW.buffer === wasmMemory.buffer ? HEAP_DATA_VIEW : (HEAP_DATA_VIEW = new DataView(wasmMemory.buffer)); }; + if (h.isArrayBuffer() && h.value.byteLength === 0) { + try { + new Uint8Array(h.value); + } + catch (_) { + GET_HEAP_DATA_VIEW().setInt8(result, 1, true); + return envObject.getReturnStatus(); + } + } + GET_HEAP_DATA_VIEW().setInt8(result, 0, true); + return envObject.getReturnStatus(); + } + catch (err) { + envObject.tryCatch.setError(err); + return envObject.setLastError(10); + } + } + var valueOperationMod = Object.freeze({ + __proto__: null, + napi_coerce_to_bool: napi_coerce_to_bool, + napi_coerce_to_number: napi_coerce_to_number, + napi_coerce_to_object: napi_coerce_to_object, + napi_coerce_to_string: napi_coerce_to_string, + napi_detach_arraybuffer: napi_detach_arraybuffer, + napi_instanceof: napi_instanceof, + napi_is_array: napi_is_array, + napi_is_arraybuffer: napi_is_arraybuffer, + napi_is_buffer: napi_is_buffer, + napi_is_dataview: napi_is_dataview, + napi_is_date: napi_is_date, + napi_is_detached_arraybuffer: napi_is_detached_arraybuffer, + napi_is_error: napi_is_error, + napi_is_typedarray: napi_is_typedarray, + napi_strict_equals: napi_strict_equals, + napi_typeof: napi_typeof, + node_api_is_sharedarraybuffer: node_api_is_sharedarraybuffer + }); + function napi_get_version(env, result) { + if (!env) + return 1; + var envObject = emnapiCtx.envStore.get(env); + if (!result) + return envObject.setLastError(1); + var NODE_API_SUPPORTED_VERSION_MAX = 10; + var HEAP_DATA_VIEW = new DataView(wasmMemory.buffer), GET_HEAP_DATA_VIEW = function () { return HEAP_DATA_VIEW.buffer === wasmMemory.buffer ? HEAP_DATA_VIEW : (HEAP_DATA_VIEW = new DataView(wasmMemory.buffer)); }; + GET_HEAP_DATA_VIEW().setUint32(result, NODE_API_SUPPORTED_VERSION_MAX, true); + return envObject.clearLastError(); + } + var versionMod = Object.freeze({ + __proto__: null, + napi_get_version: napi_get_version + }); + emnapiAWST.init(); + emnapiExternalMemory.init(); + emnapiExternalSAB.init(); + emnapiString.init(); + emnapiTSFN.init(); + PThread.init(); + napiModule.emnapi.syncMemory = $emnapiSyncMemory; + napiModule.emnapi.getMemoryAddress = $emnapiGetMemoryAddress; + napiModule.emnapi.acquireExternalSharedArrayBuffer = $emnapiAcquireExternalSharedArrayBuffer; + function addImports(mod) { + var keys = Object.keys(mod); + for (var i = 0; i < keys.length; ++i) { + var k = keys[i]; + if (k.indexOf('$') === 0) + continue; + if (k.indexOf('emnapi_') === 0) { + napiModule.imports.emnapi[k] = mod[k]; + } + else if (k.indexOf('_emnapi_') === 0 || k === 'napi_set_last_error' || k === 'napi_clear_last_error') { + napiModule.imports.env[k] = mod[k]; + } + else { + napiModule.imports.napi[k] = mod[k]; + } + } + } + addImports(asyncMod); + addImports(memoryMod); + addImports(asyncWorkMod); + addImports(utilMod); + addImports(convert2cMod); + addImports(convert2napiMod); + addImports(createMod); + addImports(globalMod); + addImports(wrapMod); + addImports(envMod); + addImports(emnapiMod); + addImports(errorMod); + addImports(functionMod); + addImports(lifeMod); + addImports(miscellaneousMod); + addImports(nodeMod); + addImports(promiseMod); + addImports(propertyMod); + addImports(scriptMod); + addImports(valueOperationMod); + addImports(versionMod); + napiModule.imports.napi.napi_create_threadsafe_function = napi_create_threadsafe_function; + napiModule.imports.napi.napi_get_threadsafe_function_context = napi_get_threadsafe_function_context; + napiModule.imports.napi.napi_call_threadsafe_function = napi_call_threadsafe_function; + napiModule.imports.napi.napi_acquire_threadsafe_function = napi_acquire_threadsafe_function; + napiModule.imports.napi.napi_release_threadsafe_function = napi_release_threadsafe_function; + napiModule.imports.napi.napi_unref_threadsafe_function = napi_unref_threadsafe_function; + napiModule.imports.napi.napi_ref_threadsafe_function = napi_ref_threadsafe_function; + return napiModule; + })(); + return napiModule; +} + +function loadNapiModuleImpl(loadFn, userNapiModule, wasmInput, options) { + options = options !== null && options !== void 0 ? options : {}; + const getMemory = options.getMemory; + const getTable = options.getTable; + const beforeInit = options.beforeInit; + if (getMemory != null && typeof getMemory !== 'function') { + throw new TypeError('options.getMemory is not a function'); + } + if (getTable != null && typeof getTable !== 'function') { + throw new TypeError('options.getTable is not a function'); + } + if (beforeInit != null && typeof beforeInit !== 'function') { + throw new TypeError('options.beforeInit is not a function'); + } + let napiModule; + const isLoad = typeof userNapiModule === 'object' && userNapiModule !== null; + if (isLoad) { + if (userNapiModule.loaded) { + throw new Error('napiModule has already loaded'); + } + napiModule = userNapiModule; + } + else { + napiModule = createNapiModule(options); + } + const wasi = options.wasi; + let wasiThreads$1; + let importObject = { + env: napiModule.imports.env, + napi: napiModule.imports.napi, + emnapi: napiModule.imports.emnapi + }; + if (wasi) { + wasiThreads$1 = new wasiThreads.WASIThreads(napiModule.childThread + ? { + wasi, + childThread: true, + postMessage: napiModule.postMessage + } + : { + wasi, + threadManager: napiModule.PThread, + waitThreadStart: napiModule.waitThreadStart + }); + Object.assign(importObject, typeof wasi.getImportObject === 'function' + ? wasi.getImportObject() + : { wasi_snapshot_preview1: wasi.wasiImport }); + Object.assign(importObject, wasiThreads$1.getImportObject()); + } + const overwriteImports = options.overwriteImports; + if (typeof overwriteImports === 'function') { + const newImportObject = overwriteImports(importObject); + if (typeof newImportObject === 'object' && newImportObject !== null) { + importObject = newImportObject; + } + } + return loadFn(wasmInput, importObject, (err, source) => { + if (err) { + throw err; + } + const originalInstance = source.instance; + let instance = originalInstance; + const originalExports = originalInstance.exports; + const exportMemory = 'memory' in originalExports; + const importMemory = 'memory' in importObject.env; + const memory = getMemory + ? getMemory(originalExports) + : exportMemory + ? originalExports.memory + : importMemory + ? importObject.env.memory + : undefined; + if (!memory) { + throw new Error('memory is neither exported nor imported'); + } + const table = getTable ? getTable(originalExports) : originalExports.__indirect_function_table; + if (wasi && !exportMemory) { + const exports = Object.create(null); + Object.assign(exports, originalExports, { memory }); + instance = { exports }; + } + const module = source.module; + if (wasi) { + instance = wasiThreads$1.initialize(instance, module, memory); + } + else { + napiModule.PThread.setup(module, memory); + } + const emnapiInit = () => { + if (beforeInit) { + beforeInit({ + instance: originalInstance, + module + }); + } + napiModule.init({ + instance, + module, + memory, + table + }); + const ret = { + instance: originalInstance, + module, + usedInstance: instance + }; + if (!isLoad) { + ret.napiModule = napiModule; + } + return ret; + }; + if (napiModule.PThread.shouldPreloadWorkers()) { + const poolReady = napiModule.PThread.loadWasmModuleToAllWorkers(); + if (loadFn === loadCallback) { + return poolReady.then(emnapiInit); + } + else { + throw new Error('Synchronous loading is not supported with worker pool (reuseWorker.size > 0)'); + } + } + return emnapiInit(); + }); +} +function loadCallback(wasmInput, importObject, callback) { + return load(wasmInput, importObject).then((source) => { + return callback(null, source); + }, err => { + return callback(err); + }); +} +function loadSyncCallback(wasmInput, importObject, callback) { + let source; + try { + source = loadSync(wasmInput, importObject); + } + catch (err) { + return callback(err); + } + return callback(null, source); +} +function loadNapiModule(napiModule, wasmInput, options) { + if (typeof napiModule !== 'object' || napiModule === null) { + throw new TypeError('Invalid napiModule'); + } + return loadNapiModuleImpl(loadCallback, napiModule, wasmInput, options); +} +function loadNapiModuleSync(napiModule, wasmInput, options) { + if (typeof napiModule !== 'object' || napiModule === null) { + throw new TypeError('Invalid napiModule'); + } + return loadNapiModuleImpl(loadSyncCallback, napiModule, wasmInput, options); +} +function instantiateNapiModule(wasmInput, options) { + return loadNapiModuleImpl(loadCallback, undefined, wasmInput, options); +} +function instantiateNapiModuleSync(wasmInput, options) { + return loadNapiModuleImpl(loadSyncCallback, undefined, wasmInput, options); +} + +class MessageHandler extends wasiThreads.ThreadMessageHandler { + constructor(options) { + if (typeof options.onLoad !== 'function') { + throw new TypeError('options.onLoad is not a function'); + } + const userOnError = options.onError; + super({ + ...options, + onError: (err, type) => { + var _a; + const emnapi_thread_crashed = (_a = this.instance) === null || _a === void 0 ? void 0 : _a.exports.emnapi_thread_crashed; + if (typeof emnapi_thread_crashed === 'function') { + emnapi_thread_crashed(); + } + if (typeof userOnError === 'function') { + userOnError(err, type); + } + else { + throw err; + } + } + }); + this.napiModule = undefined; + } + instantiate(data) { + const source = this.onLoad(data); + const then = source.then; + if (typeof then === 'function') { + return source.then((result) => { + this.napiModule = result.napiModule; + return result; + }); + } + this.napiModule = source.napiModule; + return source; + } + handle(e) { + var _a; + super.handle(e); + if ((_a = e === null || e === void 0 ? void 0 : e.data) === null || _a === void 0 ? void 0 : _a.__emnapi__) { + const type = e.data.__emnapi__.type; + const payload = e.data.__emnapi__.payload; + try { + if (type === 'async-worker-init') { + this.handleAfterLoad(e, () => { + this.napiModule.initWorker(payload.arg, payload.func); + }); + } + } + catch (err) { + this.onError(err, type); + } + } + } +} + +const version = "1.11.3"; + +exports.MessageHandler = MessageHandler; +exports.createNapiModule = createNapiModule; +exports.instantiateNapiModule = instantiateNapiModule; +exports.instantiateNapiModuleSync = instantiateNapiModuleSync; +exports.loadNapiModule = loadNapiModule; +exports.loadNapiModuleSync = loadNapiModuleSync; +exports.version = version; +Object.keys(wasiThreads).forEach(function (k) { + if (k !== 'default' && !Object.prototype.hasOwnProperty.call(exports, k)) Object.defineProperty(exports, k, { + enumerable: true, + get: function () { return wasiThreads[k]; } + }); +}); diff --git a/dg-ui/node_modules/@tailwindcss/oxide-wasm32-wasi/node_modules/@emnapi/core/dist/emnapi-core.cjs.min.d.ts b/dg-ui/node_modules/@tailwindcss/oxide-wasm32-wasi/node_modules/@emnapi/core/dist/emnapi-core.cjs.min.d.ts new file mode 100644 index 0000000..fde8e40 --- /dev/null +++ b/dg-ui/node_modules/@tailwindcss/oxide-wasm32-wasi/node_modules/@emnapi/core/dist/emnapi-core.cjs.min.d.ts @@ -0,0 +1,428 @@ +/// + +import type { Context } from '@emnapi/runtime'; +import type { ReferenceOwnership } from '@emnapi/runtime'; +import type { Worker as Worker_2 } from 'worker_threads'; + +/** @public */ +export declare type BaseCreateOptions = { + filename?: string + nodeBinding?: NodeBinding + reuseWorker?: ThreadManagerOptionsMain['reuseWorker'] + asyncWorkPoolSize?: number + waitThreadStart?: MainThreadBaseOptions['waitThreadStart'] + onCreateWorker?: (info: CreateWorkerInfo) => any + print?: (str: string) => void + printErr?: (str: string) => void + postMessage?: (msg: any) => any +} + +/** @public */ +export declare interface BaseOptions { + wasi: WASIInstance; + version?: 'preview1'; + wasm64?: boolean; +} + +/** @public */ +export declare interface ChildThreadOptions extends BaseOptions { + childThread: true; + postMessage?: (data: any) => void; +} + +/** @public */ +export declare interface CleanupThreadPayload { + tid: number; +} + +/** @public */ +export declare interface CommandInfo { + type: T; + payload: CommandPayloadMap[T]; +} + +/** @public */ +export declare interface CommandPayloadMap { + load: LoadPayload; + loaded: LoadedPayload; + start: StartPayload; + 'cleanup-thread': CleanupThreadPayload; + 'terminate-all-threads': TerminateAllThreadsPayload; + 'spawn-thread': SpawnThreadPayload; +} + +/** @public */ +export declare type CommandType = keyof CommandPayloadMap; + +/** @public */ +export declare function createInstanceProxy(instance: WebAssembly.Instance, memory?: WebAssembly.Memory | (() => WebAssembly.Memory)): WebAssembly.Instance; + +/** @public */ +export declare function createNapiModule ( +options: CreateOptions +): NapiModule + +/** @public */ +export declare type CreateOptions = BaseCreateOptions & ({ + context: Context + childThread?: boolean +} | { + context?: Context + childThread: true +}) + +/** @public */ +export declare interface CreateWorkerInfo { + type: 'thread' | 'async-work' + name: string +} + +/** @public */ +export declare interface InitOptions { + instance: WebAssembly.Instance + module: WebAssembly.Module + memory?: WebAssembly.Memory + table?: WebAssembly.Table +} + +export declare type InputType = string | URL | Response | BufferSource | WebAssembly.Module; + +/** @public */ +export declare interface InstantiatedSource extends LoadedSource { + napiModule: NapiModule; +} + +/** @public */ +export declare function instantiateNapiModule( +/** Only support `BufferSource` or `WebAssembly.Module` on Node.js */ +wasmInput: InputType | Promise, options: InstantiateOptions): Promise; + +/** @public */ +export declare function instantiateNapiModuleSync(wasmInput: BufferSource | WebAssembly.Module, options: InstantiateOptions): InstantiatedSource; + +/** @public */ +export declare type InstantiateOptions = CreateOptions & LoadOptions; + +/** @public */ +export declare function isSharedArrayBuffer(value: any): value is SharedArrayBuffer; + +/** @public */ +export declare function isTrapError(e: Error): e is WebAssembly.RuntimeError; + +/** @public */ +export declare interface LoadedPayload { +} + +/** @public */ +export declare interface LoadedSource extends WebAssembly.WebAssemblyInstantiatedSource { + usedInstance: WebAssembly.Instance; +} + +/** @public */ +export declare function loadNapiModule(napiModule: NapiModule, +/** Only support `BufferSource` or `WebAssembly.Module` on Node.js */ +wasmInput: InputType | Promise, options?: LoadOptions): Promise; + +/** @public */ +export declare function loadNapiModuleSync(napiModule: NapiModule, wasmInput: BufferSource | WebAssembly.Module, options?: LoadOptions): LoadedSource; + +/** @public */ +export declare interface LoadOptions { + wasi?: WASIInstance; + overwriteImports?: (importObject: WebAssembly.Imports) => WebAssembly.Imports; + beforeInit?: (source: WebAssembly.WebAssemblyInstantiatedSource) => void; + getMemory?: (exports: WebAssembly.Exports) => WebAssembly.Memory; + getTable?: (exports: WebAssembly.Exports) => WebAssembly.Table; +} + +/** @public */ +export declare interface LoadPayload { + wasmModule: WebAssembly.Module; + wasmMemory: WebAssembly.Memory; + sab?: Int32Array; +} + +/** @public */ +export declare interface MainThreadBaseOptions extends BaseOptions { + waitThreadStart?: boolean | number; +} + +/** @public */ +export declare type MainThreadOptions = MainThreadOptionsWithThreadManager | MainThreadOptionsCreateThreadManager; + +/** @public */ +export declare interface MainThreadOptionsCreateThreadManager extends MainThreadBaseOptions, ThreadManagerOptionsMain { +} + +/** @public */ +export declare interface MainThreadOptionsWithThreadManager extends MainThreadBaseOptions { + threadManager?: ThreadManager | (() => ThreadManager); +} + +/** @public */ +export declare interface MessageEventData { + __emnapi__: CommandInfo; +} + +/** @public */ +export declare class MessageHandler extends ThreadMessageHandler { + napiModule: NapiModule | undefined; + constructor(options: MessageHandlerOptions); + instantiate(data: LoadPayload): InstantiatedSource | PromiseLike; + handle(e: WorkerMessageEvent): void; +} + +/** @public */ +export declare interface MessageHandlerOptions extends ThreadMessageHandlerOptions { + onLoad: (data: LoadPayload) => InstantiatedSource | PromiseLike; +} + +/** @public */ +export declare interface NapiModule { + imports: { + env: any + napi: any + emnapi: any + } + exports: any + loaded: boolean + filename: string + childThread: boolean + emnapi: { + /** + * Synchronize data between the wasm memory and an ArrayBuffer / view. + * + * Note: when a non-shared wasm memory has grown, a view over the + * detached old buffer is re-created over the current buffer through the + * intrinsic base-class constructor, so for view inputs the returned view + * may be a base-class instance (e.g. `Uint8Array` or `DataView`) + * instead of the subclass that was passed in. + */ + syncMemory ( + js_to_wasm: boolean, + arrayBufferOrView: T, + offset?: number, + len?: number + ): T extends ArrayBufferView ? ArrayBufferView : T + getMemoryAddress (arrayBufferOrView: ArrayBuffer | ArrayBufferView): PointerInfo + addSendListener (worker: any): boolean + } + + init (options: InitOptions): any + initWorker (arg: number, func: [number, number]): void + postMessage?: (msg: any) => any + + waitThreadStart: boolean | number + /* Excluded from this release type: PThread */} + +/** @public */ +export declare interface NodeBinding { + node: { + emitAsyncInit: Function + emitAsyncDestroy: Function + makeCallback: Function + } + napi: { + asyncInit: Function + asyncDestroy: Function + makeCallback: Function + } +} + +/** @public */ +export declare interface PointerInfo { + address: number + ownership: ReferenceOwnership + runtimeAllocated: 0 | 1 +} + +/** @public */ +export declare interface ReuseWorkerOptions { + /** + * @see {@link https://emscripten.org/docs/tools_reference/settings_reference.html#pthread-pool-size | PTHREAD_POOL_SIZE} + */ + size: number; + /** + * @see {@link https://emscripten.org/docs/tools_reference/settings_reference.html#pthread-pool-size-strict | PTHREAD_POOL_SIZE_STRICT} + */ + strict?: boolean; +} + +/** @public */ +export declare interface SpawnThreadPayload { + startArg: number; + errorOrTid: number; +} + +/** @public */ +export declare interface StartPayload { + tid: number; + arg: number; + sab?: Int32Array; +} + +/** @public */ +export declare interface StartResult { + exitCode: number; + instance: WebAssembly.Instance; +} + +/** @public */ +export declare interface TerminateAllThreadsPayload { +} + +/** @public */ +export declare class ThreadManager { + unusedWorkers: WorkerLike[]; + pthreads: Record; + get nextWorkerID(): number; + wasmModule: WebAssembly.Module | null; + wasmMemory: WebAssembly.Memory | null; + private readonly messageEvents; + private readonly _childThread; + private readonly _onCreateWorker; + private readonly _reuseWorker; + private readonly _beforeLoad?; + /* Excluded from this release type: printErr */ + threadSpawn?: ((startArg: number, errorOrTid?: number) => number); + constructor(options: ThreadManagerOptions); + init(): void; + initMainThread(): void; + private preparePool; + shouldPreloadWorkers(): boolean; + loadWasmModuleToAllWorkers(): Promise; + preloadWorkers(): Promise; + setup(wasmModule: WebAssembly.Module, wasmMemory: WebAssembly.Memory): void; + markId(worker: WorkerLike): number; + returnWorkerToPool(worker: WorkerLike): void; + loadWasmModuleToWorker(worker: WorkerLike, sab?: Int32Array): Promise; + allocateUnusedWorker(): WorkerLike; + getNewWorker(sab?: Int32Array): WorkerLike | undefined; + cleanThread(worker: WorkerLike, tid: number, force?: boolean): void; + terminateWorker(worker: WorkerLike): void; + terminateAllThreads(): void; + addMessageEventListener(worker: WorkerLike, onMessage: (e: WorkerMessageEvent) => void): () => void; + fireMessageEvent(worker: WorkerLike, e: WorkerMessageEvent): void; +} + +/** @public */ +export declare type ThreadManagerOptions = ThreadManagerOptionsMain | ThreadManagerOptionsChild; + +/** @public */ +export declare interface ThreadManagerOptionsBase { + printErr?: (message: string) => void; + threadSpawn?: (startArg: number, errorOrTid?: number) => number; +} + +/** @public */ +export declare interface ThreadManagerOptionsChild extends ThreadManagerOptionsBase { + childThread: true; +} + +/** @public */ +export declare interface ThreadManagerOptionsMain extends ThreadManagerOptionsBase { + beforeLoad?: (worker: WorkerLike) => any; + reuseWorker?: boolean | number | ReuseWorkerOptions; + onCreateWorker: WorkerFactory; + childThread?: false; +} + +/** @public */ +export declare class ThreadMessageHandler { + protected instance: WebAssembly.Instance | undefined; + private messagesBeforeLoad; + protected postMessage: (message: any) => void; + protected onLoad?: (data: LoadPayload) => WebAssembly.WebAssemblyInstantiatedSource | PromiseLike; + protected onError: (error: Error, type: WorkerMessageType) => void; + constructor(options?: ThreadMessageHandlerOptions); + /** @virtual */ + instantiate(data: LoadPayload): WebAssembly.WebAssemblyInstantiatedSource | PromiseLike; + /** @virtual */ + handle(e: WorkerMessageEvent>): void; + private _load; + private _start; + protected _loaded(err: Error | null, source: WebAssembly.WebAssemblyInstantiatedSource | null, payload: LoadPayload): void; + protected handleAfterLoad(e: E, f: (e: E) => void): void; +} + +/** @public */ +export declare interface ThreadMessageHandlerOptions { + onLoad?: (data: LoadPayload) => WebAssembly.WebAssemblyInstantiatedSource | PromiseLike; + onError?: (error: Error, type: WorkerMessageType) => void; + postMessage?: (message: any) => void; +} + +export declare const version: string; + +/** @public */ +export declare interface WASIInstance { + readonly wasiImport?: Record; + initialize(instance: object): void; + start(instance: object): number; + getImportObject?(): any; +} + +/** @public */ +export declare class WASIThreads { + PThread: ThreadManager | undefined; + private wasmMemory; + private wasmInstance; + private readonly threadSpawn; + readonly childThread: boolean; + private readonly postMessage; + readonly wasi: WASIInstance; + constructor(options: WASIThreadsOptions); + getImportObject(): { + wasi: WASIThreadsImports; + }; + setup(wasmInstance: WebAssembly.Instance, wasmModule: WebAssembly.Module, wasmMemory?: WebAssembly.Memory): void; + preloadWorkers(): Promise; + /** + * It's ok to call this method to a WASI command module. + * + * in child thread, must call this method instead of {@link WASIThreads.start} even if it's a WASI command module + * + * @returns A proxied WebAssembly instance if in child thread, other wise the original instance + */ + initialize(instance: WebAssembly.Instance, module: WebAssembly.Module, memory?: WebAssembly.Memory): WebAssembly.Instance; + /** + * Equivalent to calling {@link WASIThreads.initialize} and then calling {@link WASIInstance.start} + * ```js + * this.initialize(instance, module, memory) + * this.wasi.start(instance) + * ``` + */ + start(instance: WebAssembly.Instance, module: WebAssembly.Module, memory?: WebAssembly.Memory): StartResult; + terminateAllThreads(): void; +} + +/** @public */ +export declare interface WASIThreadsImports { + 'thread-spawn': (startArg: number, errorOrTid?: number) => number; +} + +/** @public */ +export declare type WASIThreadsOptions = MainThreadOptions | ChildThreadOptions; + +/** @public */ +export declare type WorkerFactory = (ctx: { + type: string; + name: string; +}) => WorkerLike; + +/** @public */ +export declare type WorkerLike = (Worker | Worker_2) & { + whenLoaded?: Promise; + loaded?: boolean; + __emnapi_tid?: number; +}; + +/** @public */ +export declare interface WorkerMessageEvent { + data: T; +} + +/** @public */ +export declare type WorkerMessageType = 'load' | 'start'; + +export { } diff --git a/dg-ui/node_modules/@tailwindcss/oxide-wasm32-wasi/node_modules/@emnapi/core/dist/emnapi-core.cjs.min.js b/dg-ui/node_modules/@tailwindcss/oxide-wasm32-wasi/node_modules/@emnapi/core/dist/emnapi-core.cjs.min.js new file mode 100644 index 0000000..d3eb122 --- /dev/null +++ b/dg-ui/node_modules/@tailwindcss/oxide-wasm32-wasi/node_modules/@emnapi/core/dist/emnapi-core.cjs.min.js @@ -0,0 +1 @@ +var e=require("@emnapi/wasi-threads");const r="undefined"!=typeof WebAssembly?WebAssembly:"undefined"!=typeof WXWebAssembly?WXWebAssembly:void 0;function t(e){if(e&&"object"!=typeof e)throw new TypeError("imports must be an object or undefined");return!0}function n(e,a){if(!e)throw new TypeError("Invalid wasm source");t(a),a=null!=a?a:{};try{const r="object"==typeof e&&null!==e&&"then"in e?e.then:void 0;if("function"==typeof r)return r.call(e,e=>n(e,a))}catch(e){}if(e instanceof ArrayBuffer||ArrayBuffer.isView(e))return r.instantiate(e,a);if(e instanceof r.Module)return r.instantiate(e,a).then(r=>({instance:r,module:e}));if("undefined"!=typeof Response&&e instanceof Response)return e.arrayBuffer().then(e=>r.instantiate(e,a));const o="string"==typeof e;if(o||"undefined"!=typeof URL&&e instanceof URL){if(o&&"undefined"!=typeof wx&&"undefined"!=typeof __wxConfig)return r.instantiate(e,a);if("function"!=typeof fetch)throw new TypeError("wasm source can not be a string or URL in this environment");if("function"!=typeof r.instantiateStreaming)return n(fetch(e),a);try{return r.instantiateStreaming(fetch(e),a).catch(()=>n(fetch(e),a))}catch(r){return n(fetch(e),a)}}throw new TypeError("Invalid wasm source")}function a(t){var n=function(){var n,a,o,i,s,f="object"==typeof process&&null!==process&&"object"==typeof process.versions&&null!==process.versions&&"string"==typeof process.versions.node,u=Boolean(t.childThread),c="number"==typeof t.waitThreadStart?t.waitThreadStart:Boolean(t.waitThreadStart);function l(e){if("function"==typeof r.RuntimeError)throw new r.RuntimeError(e);throw Error(e)}var d,v,p,y={imports:{env:{},napi:{},emnapi:{}},exports:{},emnapi:{},loaded:!1,filename:"",childThread:u,initWorker:void 0,waitThreadStart:c,PThread:void 0,init:function(e){if(y.loaded)return y.exports;if(!e)throw new TypeError("Invalid napi init options");var t=e.instance;if(!(null==t?void 0:t.exports))throw new TypeError("Invalid wasm instance");n=t;var f=t.exports,u=e.module,c=e.memory||f.memory,p=e.table||f.__indirect_function_table;if(!(u instanceof r.Module))throw new TypeError("Invalid wasm module");if(!(c instanceof r.Memory))throw new TypeError("Invalid wasm memory");if(!(p instanceof r.Table))throw new TypeError("Invalid wasm table");if(a=c,o=p,"function"!=typeof f.malloc)throw new TypeError("malloc is not exported");if("function"!=typeof f.free)throw new TypeError("free is not exported");if(i=f.malloc,s=f.free,!y.childThread){var g=8,w=t.exports.node_api_module_get_api_version_v1;"function"==typeof w&&(g=w());var b=y.envObject||(y.envObject=d.createEnv(y.filename,g,function(e){return o.get(e)},function(e){return o.get(e)},l,v)),h=d.openScope(b);try{b.callIntoModule(function(e){var r=y.exports,n=h.add(r),a=(0,t.exports.napi_register_wasm_v1)(e.id,n.id);y.exports=a?d.handleStore.get(a).value:r})}catch(e){if("unwind"!==e)throw e}finally{d.closeScope(b,h)}return y.loaded=!0,delete y.envObject,y.exports}}},g=void 0;if(u){d=null==t?void 0:t.context;var w="function"==typeof t.postMessage?t.postMessage:"function"==typeof postMessage?postMessage:void 0;if("function"!=typeof w)throw new TypeError("No postMessage found");y.postMessage=w}else{var b=t.context;if("object"!=typeof b||null===b)throw new TypeError("Invalid `options.context`. Use `import { getDefaultContext } from '@emnapi/runtime'`");d=b}if("string"==typeof t.filename&&(y.filename=t.filename),"function"==typeof t.onCreateWorker&&(g=t.onCreateWorker),"function"==typeof t.print?t.print:console.log.bind(console),p="function"==typeof t.printErr?t.printErr:console.warn.bind(console),"nodeBinding"in t){var h=t.nodeBinding;if("object"!=typeof h||null===h)throw new TypeError("Invalid `options.nodeBinding`. Use @emnapi/node-binding package");v=h}var _=0;if("asyncWorkPoolSize"in t){if("number"!=typeof t.asyncWorkPoolSize)throw new TypeError("options.asyncWorkPoolSize must be a integer");(_=t.asyncWorkPoolSize|0)>1024?_=1024:_<-1024&&(_=-1024)}var E=!u&&_<=0;function L(){return Math.abs(_)}function m(e){if(!e)return!1;if(e._emnapiSendListener)return!0;var r=function(e){var r=(f?e:e.data).__emnapi__;if(r&&"async-send"===r.type)if(u){(0,y.postMessage)({__emnapi__:r})}else{var t=r.payload.callback;o.get(t)(r.payload.data)}};return e._emnapiSendListener={handler:r,dispose:function(){f?e.off("message",r):e.removeEventListener("message",r,!1),delete e._emnapiSendListener}},f?e.on("message",r):e.addEventListener("message",r,!1),!0}y.imports.env._emnapi_async_work_pool_size=L,y.emnapi.addSendListener=m;var S=new e.ThreadManager(u?{printErr:p,childThread:!0}:{printErr:p,beforeLoad:function(e){m(e)},reuseWorker:t.reuseWorker,onCreateWorker:g});function A(e,r){d.feature.setImmediate(function(){o.get(e)(r)})}function C(e,r){Promise.resolve().then(function(){o.get(e)(r)})}function V(e,r){var t,n=[r>>>0,(t=r,+Math.abs(t)>=1?t>0?(0|Math.min(+Math.floor(t/4294967296),4294967295))>>>0:~~+Math.ceil((t-+(~~t>>>0))/4294967296)>>>0:0)],o=new DataView(a.buffer),i=function(){return o.buffer===a.buffer?o:o=new DataView(a.buffer)};i().setInt32(e,n[0],!0),i().setInt32(e+4,n[1],!0)}y.PThread=S;var I,D=Object.freeze({__proto__:null,$emnapiSetValueI64:V,_emnapi_call_finalizer:function(e,r,t,n,a){t>>>=0,d.envStore.get(r).callFinalizerInternal(e,t,n,a)},_emnapi_callback_into_module:function(e,r,t,n,a){var i=d.envStore.get(r),s=d.openScope(i);try{i.callbackIntoModule(Boolean(e),function(){o.get(t)(r,n)})}catch(e){throw d.closeScope(i,s),a&&d.closeScope(i),e}d.closeScope(i,s)},_emnapi_close_handle_scope:function(e){return d.closeScope()},_emnapi_ctx_decrease_waiting_request_counter:function(){d.decreaseWaitingRequestCounter()},_emnapi_ctx_increase_waiting_request_counter:function(){d.increaseWaitingRequestCounter()},_emnapi_get_node_version:function(e,r,t){e>>>=0,r>>>=0,t>>>=0;var n="object"==typeof process&&null!==process&&"object"==typeof process.versions&&null!==process.versions&&"string"==typeof process.versions.node?process.versions.node.split(".").map(function(e){return Number(e)}):[0,0,0],o=new DataView(a.buffer),i=function(){return o.buffer===a.buffer?o:o=new DataView(a.buffer)};i().setUint32(e,n[0],!0),i().setUint32(r,n[1],!0),i().setUint32(t,n[2],!0)},_emnapi_get_now:function(){return performance.timeOrigin+performance.now()},_emnapi_is_main_browser_thread:function(){return"undefined"==typeof window||"undefined"==typeof document||f?0:1},_emnapi_is_main_runtime_thread:function(){return u?0:1},_emnapi_next_tick:C,_emnapi_open_handle_scope:function(){return d.openScope().id},_emnapi_runtime_keepalive_pop:function(){},_emnapi_runtime_keepalive_push:function(){},_emnapi_set_immediate:A,_emnapi_unwind:function(){throw"unwind"},napi_clear_last_error:function(e){return d.envStore.get(e).clearLastError()},napi_set_last_error:function(e,r,t,n){return d.envStore.get(e).setLastError(r,t,n)}});function k(e){var r=new DataView(a.buffer).getInt32(e+20,!0);return S.pthreads[r]}var U=new Promise(function(e){I=function(){U.ready=!0,e()}});U.ready=!1;var B=Object.freeze({__proto__:null,_emnapi_after_uvthreadpool_ready:function(e,r,t){U.ready?o.get(e)(r,t):U.then(function(){o.get(e)(r,t)})},_emnapi_async_send_js:function(e,r,t){if(u)(0,y.postMessage)({__emnapi__:{type:"async-send",payload:{callback:r,data:t}}});else switch(e){case 0:A(r,t);break;case 1:C(r,t)}},_emnapi_emit_async_thread_ready:function(){u&&(0,y.postMessage)({__emnapi__:{type:"async-thread-ready",payload:{}}})},_emnapi_tell_js_uvthreadpool:function(e,r){for(var t=[],n=new DataView(a.buffer),o=function(r){var o=k((n.buffer===a.buffer?n:n=new DataView(a.buffer)).getUint32(e+4*r,!0));t.push(new Promise(function(e){var r=function(t){var n=(f?t:t.data).__emnapi__;n&&"async-thread-ready"===n.type&&(e(),o&&"function"==typeof o.unref&&o.unref(),f?o.off("message",r):o.removeEventListener("message",r))};f?o.on("message",r):o.addEventListener("message",r)}))},i=0;i>>=0);r&&"function"==typeof r.ref&&r.ref()}},_emnapi_worker_unref:function(e){if(!u){var r=k(e>>>=0);r&&"function"==typeof r.unref&&r.unref()}}});var T=Object.freeze({__proto__:null,napi_adjust_external_memory:function(e,r,t){if(!e)return 1;var n=d.envStore.get(e);if(!t)return n.setLastError(1);var o=d.adjustAmountOfExternalAllocatedMemory(r);if(t>>>=0,d.feature.supportBigInt){var i=new DataView(a.buffer);(i.buffer===a.buffer?i:i=new DataView(a.buffer)).setBigInt64(t,BigInt(o),!0)}else V(t,Number(o));return n.clearLastError()}}),F={idGen:{},values:[void 0],queued:new Set,pending:[],init:function(){var e={nextId:1,list:[],generate:function(){var r;return e.list.length?r=e.list.shift():(r=e.nextId,e.nextId++),r},reuse:function(r){e.list.push(r)}};F.idGen=e,F.values=[void 0],F.queued=new Set,F.pending=[]},create:function(e,r,t,n,a,o){var i=0,s=0;if(v){var f=v.node.emitAsyncInit(r,t,-1);i=f.asyncId,s=f.triggerAsyncId}var u=F.idGen.generate();return F.values[u]={env:e,id:u,resource:r,asyncId:i,triggerAsyncId:s,status:0,execute:n,complete:a,data:o},u},callComplete:function(e,r){var t=e.complete,n=e.env,a=e.data,i=function(){if(t){var e=d.envStore.get(n),i=d.openScope(e);try{e.callbackIntoModule(!0,function(){o.get(t)(n,r,a)})}finally{d.closeScope(e,i)}}};v?v.node.makeCallback(e.resource,i,[],{asyncId:e.asyncId,triggerAsyncId:e.triggerAsyncId}):i()},queue:function(e){var r=F.values[e];if(r&&0===r.status){if(r.status=1,F.queued.size>=(Math.abs(_)||4))return void F.pending.push(e);F.queued.add(e);var t=r.env,n=r.data,a=r.execute;r.status=2,d.feature.setImmediate(function(){if(o.get(a)(t,n),F.queued.delete(e),r.status=3,d.feature.setImmediate(function(){F.callComplete(r,0)}),F.pending.length>0){var i=F.pending.shift();F.values[i].status=0,F.queue(i)}})}},cancel:function(e){var r=F.pending.indexOf(e);if(-1!==r){var t=F.values[e];return t&&1===t.status?(t.status=4,F.pending.splice(r,1),d.feature.setImmediate(function(){F.callComplete(t,11)}),0):9}return 9},remove:function(e){var r=F.values[e];r&&(v&&v.node.emitAsyncDestroy({asyncId:r.asyncId,triggerAsyncId:r.triggerAsyncId}),F.values[e]=void 0,F.idGen.reuse(e))}};function O(e,r,t,n){if(v){var o=d.handleStore.get(e).value,i=d.handleStore.get(r).value,s=v.node.emitAsyncInit(o,i,t),f=s.asyncId,u=s.triggerAsyncId;if(n){n>>>=0;var c=new DataView(a.buffer),l=function(){return c.buffer===a.buffer?c:c=new DataView(a.buffer)};l().setFloat64(n,f,!0),l().setFloat64(n+8,u,!0)}}}function x(e,r){v&&v.node.emitAsyncDestroy({asyncId:e,triggerAsyncId:r})}var j=Object.freeze({__proto__:null,_emnapi_async_destroy_js:function(e){if(!v)return 9;e>>>=0;var r=new DataView(a.buffer),t=function(){return r.buffer===a.buffer?r:r=new DataView(a.buffer)},n=t().getInt32(e,!0),o=t().getInt32(e+4,!0),i=BigInt(n>>>0)|BigInt(o)<=BigInt(-1)*(BigInt(1)<=BigInt(1)<>BigInt(32));t>>>=0;var c=new DataView(a.buffer),l=function(){return c.buffer===a.buffer?c:c=new DataView(a.buffer)};return l().setInt32(t,f,!0),l().setInt32(t+4,u,!0),0},_emnapi_env_check_gc_access:function(e){d.envStore.get(e).checkGCAccess()},_emnapi_node_emit_async_destroy:x,_emnapi_node_emit_async_init:O,_emnapi_node_make_callback:function(e,r,t,n,o,i,s,f){var u,c=0;if(v){var l=d.handleStore.get(r).value,p=d.handleStore.get(t).value;n>>>=0,o>>>=0,o>>>=0;for(var y=Array(o),g=new DataView(a.buffer),w=function(){return g.buffer===a.buffer?g:g=new DataView(a.buffer)};c>>=0,u=d.envStore.get(e).ensureHandleId(h),w().setUint32(f,u,!0)}},napi_close_callback_scope:function(e,r){throw new Error("napi_close_callback_scope has not been implemented yet")},napi_make_callback:function(e,r,t,n,o,i,s){var f,u=0;if(!e)return 1;var c=d.envStore.get(e);if(c.checkGCAccess(),!c.tryCatch.isEmpty())return c.setLastError(10);if(!c.canCallIntoJs())return c.setLastError(c.moduleApiVersion>=10?23:10);c.clearLastError();try{if(!v)return c.setLastError(9);if(!t)return c.setLastError(1);if(o>0&&!i)return c.setLastError(1);var l=Object(d.handleStore.get(t).value),p=d.handleStore.get(n).value;if("function"!=typeof p)return c.setLastError(1);r>>>=0;var y=new DataView(a.buffer),g=function(){return y.buffer===a.buffer?y:y=new DataView(a.buffer)},w=g().getInt32(r,!0),b=g().getInt32(r+4,!0),h=BigInt(w>>>0)|BigInt(b)<>>=0,o>>>=0,o>>>=0;for(var _=Array(o);u>>=0,f=c.ensureHandleId(L.value),g().setUint32(s,f,!0)),c.getReturnStatus())}catch(e){return c.tryCatch.setError(e),c.setLastError(10)}},napi_open_callback_scope:function(e,r,t,n){throw new Error("napi_open_callback_scope has not been implemented yet")}}),R={_liveSet:{},offset:{__size__:0,resource:0,async_id:0,trigger_async_id:0,queue_size:0,is_some:0,queue:0,async_pending:0,async_u_fd:0,thread_count:0,state:0,dispatch_state:0,context:0,max_queue_size:0,ref:0,env:0,finalize_data:0,finalize_cb:0,call_js_cb:0,handles_closing:0,async_ref:0,mutex:0,cond:0},init:function(){if(R._liveSet=new Set,R.offset.__size__=184,R.offset.resource=0,R.offset.async_id=8,R.offset.trigger_async_id=16,R.offset.queue_size=60,R.offset.is_some=24,R.offset.queue=64,R.offset.async_pending=132,R.offset.async_u_fd=96,R.offset.thread_count=136,R.offset.state=140,R.offset.dispatch_state=144,R.offset.context=148,R.offset.max_queue_size=152,R.offset.ref=156,R.offset.env=160,R.offset.finalize_data=164,R.offset.finalize_cb=168,R.offset.call_js_cb=172,R.offset.handles_closing=176,R.offset.async_ref=180,R.offset.mutex=32,R.offset.cond=56,R.offset.mutex=R.offset.mutex+4,void 0!==S){S.unusedWorkers.forEach(R.addListener),Object.values(S.pthreads).forEach(R.addListener);var e=S.getNewWorker;S.getNewWorker=function(){var r=e.apply(this,arguments);return R.addListener(r),r}}},addListener:function(e){if(!e)return!1;if(e._emnapiTSFNListener)return!0;var r=function(e){var r=(f?e:e.data).__emnapi__;if(r){var t=r.type,n=r.payload;if("tsfn-send"===t){var a=n.tsfn+R.offset.async_pending;0!==Atomics.load(new Int32Array(R.ensureBufferFor(a+4)),a>>>2)&&R.enqueue(n.tsfn)}}};return e._emnapiTSFNListener={handler:r,dispose:function(){f?e.off("message",r):e.removeEventListener("message",r,!1),delete e._emnapiTSFNListener}},f?e.on("message",r):e.addEventListener("message",r,!1),!0},ensureBufferFor:function(e){var r=a.buffer;return e>r.byteLength&&(a.grow(0),r=a.buffer),r},initQueue:function(e){var r=i(8);return!!r&&(r>>>=0,new Uint8Array(R.ensureBufferFor(r+8),r,8).fill(0),R.storeSizeTypeValue(e+R.offset.queue,r,!1),!0)},destroyQueue:function(e){var r=R.loadSizeTypeValue(e+R.offset.queue,!1);if(r){for(var t=R.loadSizeTypeValue(r,!1);0!==t;){var n=R.loadSizeTypeValue(t+4,!1);s(t),t=n}s(r)}},pushQueue:function(e,r){var t=R.loadSizeTypeValue(e+R.offset.queue,!1),n=R.loadSizeTypeValue(t,!1),a=R.loadSizeTypeValue(t+4,!1),o=i(8);if(!o)throw new Error("OOM");o>>>=0,R.storeSizeTypeValue(o,r,!1),R.storeSizeTypeValue(o+4,0,!1),0===n&&0===a?(R.storeSizeTypeValue(t,o,!1),R.storeSizeTypeValue(t+4,o,!1)):(R.storeSizeTypeValue(a+4,o,!1),R.storeSizeTypeValue(t+4,o,!1)),R.addQueueSize(e)},shiftQueue:function(e){var r=R.loadSizeTypeValue(e+R.offset.queue,!1),t=R.loadSizeTypeValue(r,!1);if(0===t)return 0;var n=t,a=R.loadSizeTypeValue(t+4,!1);R.storeSizeTypeValue(r,a,!1),0===a&&R.storeSizeTypeValue(r+4,0,!1),R.storeSizeTypeValue(n+4,0,!1);var o=R.loadSizeTypeValue(n,!1);return s(n),R.subQueueSize(e),o},push:function(e,r,t){var n=R.getMutex(e),a=R.getCond(e),o=function(){var r=R.getQueueSize(e),t=R.getMaxQueueSize(e);return r>=t&&t>0&&0===R.getState(e)},i="undefined"!=typeof window&&"undefined"!=typeof document&&!f,s=!1,u=n.execute(function(){for(;o();){if(0===t)return 15;if(i)return 21;a.wait()}return 0===R.getState(e)?(R.pushQueue(e,r),R.send(e),0):0===R.getThreadCount(e)?1:(R.subThreadCount(e),2!==R.getState(e)||0!==R.getThreadCount(e)||(s=!0),16)});return s&&R.destroy(e),u},getMutex:function(e){var r=e+R.offset.mutex,t={lock:function(){var e="undefined"!=typeof window&&"undefined"!=typeof document&&!f,t=new Int32Array(R.ensureBufferFor(r+4),r,1);if(e)for(;;){if(0===Atomics.compareExchange(t,0,0,10))return}else for(;;){if(0===Atomics.compareExchange(t,0,0,10))return;Atomics.wait(t,0,10)}},unlock:function(){var e=new Int32Array(R.ensureBufferFor(r+4),r,1);if(10!==Atomics.compareExchange(e,0,10,0))throw new Error("Tried to unlock while not holding the mutex");Atomics.notify(e,0,1)},execute:function(e){t.lock();try{return e()}finally{t.unlock()}}};return t},getCond:function(e){var r=e+R.offset.cond,t=R.getMutex(e);return{wait:function(){var e=new Int32Array(R.ensureBufferFor(r+4),r,1),n=Atomics.load(e,0);t.unlock(),Atomics.wait(e,0,n),t.lock()},signal:function(){var e=new Int32Array(R.ensureBufferFor(r+4),r,1);Atomics.add(e,0,1),Atomics.notify(e,0,1)}}},getQueueSize:function(e){return R.loadSizeTypeValue(e+R.offset.queue_size,!0)},addQueueSize:function(e){var r,t,n=R.offset.queue_size;r=new Uint32Array(R.ensureBufferFor(e+n+4)),t=e+n>>>2,Atomics.add(r,t,1)},subQueueSize:function(e){var r,t,n=R.offset.queue_size;r=new Uint32Array(R.ensureBufferFor(e+n+4)),t=e+n>>>2,Atomics.sub(r,t,1)},getThreadCount:function(e){return R.loadSizeTypeValue(e+R.offset.thread_count,!0)},addThreadCount:function(e){var r,t,n=R.offset.thread_count;r=new Uint32Array(R.ensureBufferFor(e+n+4)),t=e+n>>>2,Atomics.add(r,t,1)},subThreadCount:function(e){var r,t,n=R.offset.thread_count;r=new Uint32Array(R.ensureBufferFor(e+n+4)),t=e+n>>>2,Atomics.sub(r,t,1)},getState:function(e){return Atomics.load(new Int32Array(R.ensureBufferFor(e+R.offset.state+4)),e+R.offset.state>>>2)},setState:function(e,r){Atomics.store(new Int32Array(R.ensureBufferFor(e+R.offset.state+4)),e+R.offset.state>>>2,r)},getHandlesClosing:function(e){return Atomics.load(new Int8Array(R.ensureBufferFor(e+R.offset.handles_closing+1)),e+R.offset.handles_closing)},setHandlesClosing:function(e,r){Atomics.store(new Int8Array(R.ensureBufferFor(e+R.offset.handles_closing+1)),e+R.offset.handles_closing,r)},getDispatchState:function(e){return Atomics.load(new Uint32Array(R.ensureBufferFor(e+R.offset.dispatch_state+4)),e+R.offset.dispatch_state>>>2)},getContext:function(e){return R.loadSizeTypeValue(e+R.offset.context,!1)},getMaxQueueSize:function(e){return R.loadSizeTypeValue(e+R.offset.max_queue_size,!0)},getEnv:function(e){return R.loadSizeTypeValue(e+R.offset.env,!1)},getCallJSCb:function(e){return R.loadSizeTypeValue(e+R.offset.call_js_cb,!1)},getRef:function(e){return R.loadSizeTypeValue(e+R.offset.ref,!1)},getResource:function(e){return R.loadSizeTypeValue(e+R.offset.resource,!1)},getFinalizeCb:function(e){return R.loadSizeTypeValue(e+R.offset.finalize_cb,!1)},getFinalizeData:function(e){return R.loadSizeTypeValue(e+R.offset.finalize_data,!1)},loadSizeTypeValue:function(e,r){var t;return r?(t=new Uint32Array(R.ensureBufferFor(e+4)),Atomics.load(t,e>>>2)):(t=new Int32Array(R.ensureBufferFor(e+4)),Atomics.load(t,e>>>2))},storeSizeTypeValue:function(e,r,t){var n;return t?(n=new Uint32Array(R.ensureBufferFor(e+4)),void Atomics.store(n,e>>>2,r)):(n=new Int32Array(R.ensureBufferFor(e+4)),void Atomics.store(n,e>>>2,r>>>0))},releaseResources:function(e){if(2!==R.getState(e)){R.setState(e,2);var r=R.getEnv(e),t=d.envStore.get(r),n=R.getRef(e);n&&d.refStore.get(n).dispose();var o=R.getResource(e);d.refStore.get(o).dispose(),R.ensureBufferFor(e+R.offset.is_some+1);var i=new DataView(a.buffer);(i.buffer===a.buffer?i:i=new DataView(a.buffer)).setInt8(e+R.offset.is_some,0,!0),d.removeCleanupHook(t,R.cleanup,e),t.unref();var s=e+R.offset.async_ref,f=s>>>2,u=new Uint32Array(R.ensureBufferFor(s+4));if(Atomics.load(u,f)>0&&(Atomics.store(u,f,0),d.decreaseWaitingRequestCounter()),v){var c=new DataView(R.ensureBufferFor(e+R.offset.trigger_async_id+8));x(c.getFloat64(e+R.offset.async_id,!0),c.getFloat64(e+R.offset.trigger_async_id,!0))}}},destroy:function(e){R._liveSet.delete(e),R.destroyQueue(e),R.releaseResources(e),s(e)},emptyQueue:function(e){var r=[];R.getMutex(e).execute(function(){for(;R.getQueueSize(e)>0;)r.push(R.shiftQueue(e))});for(var t,n=R.getCallJSCb(e),a=R.getContext(e),i=0;i0?R.releaseResources(e):r=!0}),r&&R.destroy(e)},finalize:function(e){var r=R.getEnv(e),t=d.envStore.get(r);d.openScope(t);var n=R.getFinalizeCb(e),a=R.getFinalizeData(e),o=R.getContext(e),i=function(){t.callFinalizerInternal(0,n,a,o)};try{if(R.emptyQueue(e),n)if(v){var s=R.getResource(e),f=d.refStore.get(s).get(),u=d.handleStore.get(f).value,c=new DataView(R.ensureBufferFor(e+R.offset.trigger_async_id+8)),l=c.getFloat64(e+R.offset.async_id,!0),p=c.getFloat64(e+R.offset.trigger_async_id,!0);v.node.makeCallback(u,i,[],{asyncId:l,triggerAsyncId:p})}else i();R.maybeDelete(e)}finally{d.closeScope(t)}},cleanup:function(e){R.closeHandlesAndMaybeDelete(e,1)},closeHandlesAndMaybeDelete:function(e,r){var t=R.getEnv(e),n=d.envStore.get(t);d.openScope(n);try{if(r&&R.getMutex(e).execute(function(){R.setState(e,1),R.getMaxQueueSize(e)>0&&R.getCond(e).signal()}),R.getHandlesClosing(e))return;R.setHandlesClosing(e,1),Atomics.store(new Int32Array(R.ensureBufferFor(e+R.offset.async_pending+4)),e+R.offset.async_pending>>>2,1),d.feature.setImmediate(function(){R.finalize(e)})}finally{d.closeScope(n)}},dispatchOne:function(e){var r=0,t=!1,n=!1,a=R.getMutex(e),i=R.getCond(e);if(a.execute(function(){if(0===R.getState(e)){var a=R.getQueueSize(e);if(a>0){r=R.shiftQueue(e),t=!0;var o=R.getMaxQueueSize(e);a===o&&o>0&&i.signal(),a--}0===a?0===R.getThreadCount(e)&&(R.setState(e,1),R.getMaxQueueSize(e)>0&&i.signal(),R.closeHandlesAndMaybeDelete(e,0)):n=!0}else R.closeHandlesAndMaybeDelete(e,0)}),t){var s=R.getEnv(e),f=d.envStore.get(s);d.openScope(f);var u=function(){f.callbackIntoModule(!1,function(){var t=R.getCallJSCb(e),n=R.getRef(e),a=n?d.refStore.get(n).get():0;if(t){var i=R.getContext(e);o.get(t)(s,a,i,r)}else{var f=a?d.handleStore.get(a).value:null;"function"==typeof f&&f()}})};try{if(v){var c=R.getResource(e),l=d.refStore.get(c).get(),p=d.handleStore.get(l).value,y=new DataView(R.ensureBufferFor(e+R.offset.trigger_async_id+8));v.node.makeCallback(p,u,[],{asyncId:y.getFloat64(e+R.offset.async_id,!0),triggerAsyncId:y.getFloat64(e+R.offset.trigger_async_id,!0)})}else u()}finally{d.closeScope(f)}}return n},dispatch:function(e){for(var r=!0,t=1e3,n=e+R.offset.dispatch_state,a=n>>>2;r&&0!==--t;){Atomics.store(new Uint32Array(R.ensureBufferFor(n+4)),a,1);try{r=R.dispatchOne(e)}catch(r){throw R._liveSet.has(e)&&(Atomics.exchange(new Uint32Array(R.ensureBufferFor(n+4)),a,0),R.send(e)),r}1!==Atomics.exchange(new Uint32Array(R.ensureBufferFor(n+4)),a,0)&&(r=!0)}r&&R.send(e)},enqueue:function(e){var r=e+R.offset.async_pending,t=e+R.offset.async_u_fd,n=Math.max(r,t)+4,a=function(){return new Int32Array(R.ensureBufferFor(n))};0===Atomics.exchange(a(),t>>>2,1)&&d.feature.setImmediate(function(){R._liveSet.has(e)&&(0!==Atomics.load(a(),r>>>2)?d.feature.setImmediate(function(){if(R._liveSet.has(e))try{if(0===Atomics.exchange(a(),r>>>2,0))return;R.dispatch(e)}finally{R._liveSet.has(e)&&(Atomics.store(a(),t>>>2,0),0!==Atomics.load(a(),r>>>2)&&R.enqueue(e))}}):Atomics.store(a(),t>>>2,0))})},send:function(e){var r=e+R.offset.dispatch_state;if(1&~Atomics.or(new Uint32Array(R.ensureBufferFor(r+4)),r>>>2,2)){var t=e+R.offset.async_pending;0===Atomics.load(new Int32Array(R.ensureBufferFor(t+4)),t>>>2)&&0===Atomics.exchange(new Int32Array(R.ensureBufferFor(t+4)),t>>>2,1)&&(void 0!==u&&u?postMessage({__emnapi__:{type:"tsfn-send",payload:{tsfn:e}}}):R.enqueue(e))}}};var z={pool:[],workerReady:null,globalAddress:0,globalOffset:{idle_threads:0,q:4,next:4,prev:8,mutex:12,cond:16,exit_message:20,end:28},offset:{resource:0,async_id:8,trigger_async_id:16,env:24,status:28,queue:32,queue_next:32,queue_prev:36,data:40,execute:44,complete:48,end:52},ensureBufferFor:function(e){var r=a.buffer;return e>r.byteLength&&(a.grow(0),r=a.buffer),r},init:function(){if(z.pool=[],z.workerReady=null,void 0!==S){S.unusedWorkers.forEach(z.addListener),Object.values(S.pthreads).forEach(z.addListener);var e=S.getNewWorker;S.getNewWorker=function(){var r=e.apply(this,arguments);return z.addListener(r),r}}},addListener:function(e){if(!e)return!1;if(e._emnapiAWMTListener)return!0;var r=function(e){var r=(f?e:e.data).__emnapi__;if(r){var t=r.type,n=r.payload;"async-work-complete"===t&&z.callComplete(n.work,0)}};return e._emnapiAWMTListener={handler:r,dispose:function(){f?e.off("message",r):e.removeEventListener("message",r,!1),delete e._emnapiAWMTListener}},f?e.on("message",r):e.addEventListener("message",r,!1),!0},initGlobal:function(){if(!z.globalAddress){z.globalAddress=i(z.globalOffset.end),z.globalAddress>>>=0;var e=z.globalOffset.end,r=z.globalAddress;new Uint8Array(z.ensureBufferFor(r+e),r,e).fill(0),z.queueInit(z.globalAddress+z.globalOffset.q),z.queueInit(z.globalAddress+z.globalOffset.exit_message)}},terminateWorkers:function(){z.pool.forEach(function(e){var r,t;null===(r=e._emnapiAWMTListener)||void 0===r||r.dispose(),null===(t=e._emnapiTSFNListener)||void 0===t||t.dispose(),e.terminate()}),z.pool.length=0},initWorkers:function(e){if(u)return z.workerReady||(z.workerReady=Promise.resolve());if(z.workerReady)return z.workerReady;if(!("emnapi_async_worker_create"in n.exports))throw new TypeError("`emnapi_async_worker_create` is not exported, please try to add `--export=emnapi_async_worker_create` to linker flags");var r=n.exports.emnapi_async_worker_create,t=[];z.initGlobal();for(var a=0;a>>=0;var t=new DataView(z.ensureBufferFor(e+20+4)).getInt32(e+20,!0);return(r=S.pthreads[t]).whenLoaded});return z.workerReady=Promise.all(o),z.workerReady},getResource:function(e){z.ensureBufferFor(e+z.offset.resource+4);var r=new DataView(a.buffer);return(r.buffer===a.buffer?r:r=new DataView(a.buffer)).getUint32(e+z.offset.resource,!0)},getExecute:function(e){z.ensureBufferFor(e+z.offset.execute+4);var r=new DataView(a.buffer);return(r.buffer===a.buffer?r:r=new DataView(a.buffer)).getUint32(e+z.offset.execute,!0)},getComplete:function(e){z.ensureBufferFor(e+z.offset.complete+4);var r=new DataView(a.buffer);return(r.buffer===a.buffer?r:r=new DataView(a.buffer)).getUint32(e+z.offset.complete,!0)},getEnv:function(e){z.ensureBufferFor(e+z.offset.env+4);var r=new DataView(a.buffer);return(r.buffer===a.buffer?r:r=new DataView(a.buffer)).getUint32(e+z.offset.env,!0)},getData:function(e){z.ensureBufferFor(e+z.offset.data+4);var r=new DataView(a.buffer);return(r.buffer===a.buffer?r:r=new DataView(a.buffer)).getUint32(e+z.offset.data,!0)},getMutex:function(){var e=z.globalAddress+z.globalOffset.mutex,r={lock:function(){var r="undefined"!=typeof window&&"undefined"!=typeof document&&!f,t=new Int32Array(z.ensureBufferFor(e+4),e,1);if(r)for(;;){if(0===Atomics.compareExchange(t,0,0,10))return}else for(;;){if(0===Atomics.compareExchange(t,0,0,10))return;Atomics.wait(t,0,10)}},unlock:function(){var r=new Int32Array(z.ensureBufferFor(e+4),e,1);if(10!==Atomics.compareExchange(r,0,10,0))throw new Error("Tried to unlock while not holding the mutex");Atomics.notify(r,0,1)},execute:function(e){r.lock();try{return e()}finally{r.unlock()}}};return r},getCond:function(){var e=z.globalAddress+z.globalOffset.cond,r=z.getMutex();return{wait:function(){var t=new Int32Array(z.ensureBufferFor(e+4),e,1),n=Atomics.load(t,0);r.unlock(),Atomics.wait(t,0,n),r.lock()},signal:function(){var r=new Int32Array(z.ensureBufferFor(e+4),e,1);Atomics.add(r,0,1),Atomics.notify(r,0,1)}}},queueInit:function(e){z.ensureBufferFor(e+4+4);var r=new DataView(a.buffer),t=function(){return r.buffer===a.buffer?r:r=new DataView(a.buffer)};t().setUint32(e,e,!0),t().setUint32(e+4,e,!0)},queueInsertTail:function(e,r){z.ensureBufferFor(e+4+4),z.ensureBufferFor(r+4+4);var t=new DataView(a.buffer),n=function(){return t.buffer===a.buffer?t:t=new DataView(a.buffer)};n().setUint32(r,e,!0);var o=n().getUint32(e+4,!0);n().setUint32(r+4,o,!0);var i=n().getUint32(r+4,!0);n().setUint32(i,r,!0),n().setUint32(e+4,r,!0)},queueRemove:function(e){z.ensureBufferFor(e+4+4);var r=new DataView(a.buffer),t=function(){return r.buffer===a.buffer?r:r=new DataView(a.buffer)},n=t().getUint32(e+4,!0),o=t().getUint32(e,!0);t().setUint32(n,o,!0),t().setUint32(o+4,n,!0)},queueEmpty:function(e){z.ensureBufferFor(e+4);var r=new DataView(a.buffer);return e==(r.buffer===a.buffer?r:r=new DataView(a.buffer)).getUint32(e,!0)},scheduleWork:function(e){var r;(null===(r=z.workerReady)||void 0===r?void 0:r.ready)||z.initWorkers(L()).then(function(){z.workerReady.ready=!0}).catch(function(e){throw z.workerReady=null,e}),d.increaseWaitingRequestCounter();var t=new Int32Array(z.ensureBufferFor(e+z.offset.status+4),e+z.offset.status,1);Atomics.store(t,0,0);var n=z.getMutex(),o=z.getCond();n.lock();try{z.queueInsertTail(z.globalAddress+z.globalOffset.q,e+z.offset.queue)}catch(e){throw d.decreaseWaitingRequestCounter(),n.unlock(),e}z.ensureBufferFor(z.globalAddress+z.globalOffset.idle_threads+4);var i=new DataView(a.buffer);(i.buffer===a.buffer?i:i=new DataView(a.buffer)).getUint32(z.globalAddress+z.globalOffset.idle_threads,!0)>0&&o.signal(),n.unlock()},cancelWork:function(e){var r=!1;return z.getMutex().execute(function(){z.ensureBufferFor(e+z.offset.status+4);var t=new DataView(a.buffer);(r=!z.queueEmpty(e+z.offset.queue)&&2!==(t.buffer===a.buffer?t:t=new DataView(a.buffer)).getInt32(e+z.offset.status,!0))&&z.queueRemove(e+z.offset.queue)}),r?0!==Atomics.compareExchange(new Int32Array(z.ensureBufferFor(e+z.offset.status+4),e+z.offset.status,1),0,0,1)?9:(d.feature.setImmediate(function(){z.callComplete(e,11)}),0):9},callComplete:function(e,r){d.decreaseWaitingRequestCounter();var t=z.getComplete(e),n=z.getEnv(e),a=z.getData(e),i=d.envStore.get(n),s=d.openScope(i),f=function(){t&&i.callbackIntoModule(!0,function(){o.get(t)(n,r,a)})};try{if(v){var u=z.getResource(e),c=d.refStore.get(u).get(),l=d.handleStore.get(c).value,p=new DataView(z.ensureBufferFor(e+z.offset.trigger_async_id+8)),y=p.getFloat64(e+z.offset.async_id,!0),g=p.getFloat64(e+z.offset.trigger_async_id,!0);v.node.makeCallback(l,f,[],{asyncId:y,triggerAsyncId:g})}else f()}finally{d.closeScope(i,s)}}};z.init();var G=E?function(e,r,t,n,o,i,s){if(!e)return 1;var f,u=d.envStore.get(e);if(u.checkGCAccess(),!n)return u.setLastError(1);if(!s)return u.setLastError(1);if(f=r?Object(d.handleStore.get(r).value):{},!t)return u.setLastError(1);var c=String(d.handleStore.get(t).value),l=F.create(e,f,c,n,o,i);s>>>=0;var v=new DataView(a.buffer);return(v.buffer===a.buffer?v:v=new DataView(a.buffer)).setUint32(s,l,!0),u.clearLastError()}:function(e,r,t,n,o,s,f){if(!e)return 1;var u,c=d.envStore.get(e);if(c.checkGCAccess(),!n)return c.setLastError(1);if(!f)return c.setLastError(1);if(u=r?Object(d.handleStore.get(r).value):{},!t)return c.setLastError(1);var l=z.offset.end,v=i(l);if(!v)return c.setLastError(9);v>>>=0,new Uint8Array(z.ensureBufferFor(v+l)).subarray(v,v+l).fill(0);var p=c.ensureHandleId(u),y=d.createReference(c,p,1,1).id,g=new DataView(a.buffer),w=function(){return g.buffer===a.buffer?g:g=new DataView(a.buffer)};return w().setUint32(v,y,!0),O(p,t,-1,v+z.offset.async_id),w().setUint32(v+z.offset.env,e,!0),w().setUint32(v+z.offset.execute,n,!0),w().setUint32(v+z.offset.complete,o,!0),w().setUint32(v+z.offset.data,s,!0),z.queueInit(v+z.offset.queue),f>>>=0,w().setUint32(f,v,!0),c.clearLastError()},M=E?function(e,r){if(!e)return 1;var t=d.envStore.get(e);return t.checkGCAccess(),r?(r>>>=0,F.remove(r),t.clearLastError()):t.setLastError(1)}:function(e,r){if(!e)return 1;var t=d.envStore.get(e);if(t.checkGCAccess(),!r)return t.setLastError(1);r>>>=0;var n=z.getResource(r);if(d.refStore.get(n).dispose(),v){var a=new DataView(z.ensureBufferFor(r+z.offset.trigger_async_id+8));x(a.getFloat64(r+z.offset.async_id,!0),a.getFloat64(r+z.offset.trigger_async_id,!0))}return s(r),t.clearLastError()},P=E?function(e,r){if(!e)return 1;var t=d.envStore.get(e);return r?(r>>>=0,F.queue(r),t.clearLastError()):t.setLastError(1)}:function(e,r){if(!e)return 1;var t=d.envStore.get(e);return r?(r>>>=0,z.scheduleWork(r),t.clearLastError()):t.setLastError(1)},q=E?function(e,r){if(!e)return 1;var t=d.envStore.get(e);if(!r)return t.setLastError(1);r>>>=0;var n=F.cancel(r);return 0===n?t.clearLastError():t.setLastError(n)}:function(e,r){if(!e)return 1;var t=d.envStore.get(e);if(!r)return t.setLastError(1);r>>>=0;var n=z.cancelWork(r);return 0===n?t.clearLastError():t.setLastError(n)};y.initWorker=function(e,r){if(!y.childThread)throw new Error("startThread is only available in child threads");if("function"!=typeof n.exports.emnapi_async_worker_init)throw new TypeError("`emnapi_async_worker_init` is not exported, please try to add `--export=emnapi_async_worker_init` to linker flags");n.exports.emnapi_async_worker_init(e),o.get(r[0])(r[1])};var W=Object.freeze({__proto__:null,_emnapi_async_worker:function(e){e>>>=0,z.globalAddress=e;var r=z.getMutex(),t=z.getCond();r.lock();for(var n=e+z.globalOffset.exit_message,i=e+z.globalOffset.idle_threads,s=e+z.globalOffset.q,f=new DataView(a.buffer),u=function(){return f.buffer===a.buffer?f:f=new DataView(a.buffer)};;){for(z.ensureBufferFor(s+4);z.queueEmpty(s);)Atomics.add(new Int32Array(z.ensureBufferFor(i+4),i,1),0,1),t.wait(),Atomics.sub(new Int32Array(z.ensureBufferFor(i+4),i,1),0,1);var c=u().getUint32(s,!0);if(c===n){t.signal(),r.unlock();break}var d=c-z.offset.queue;z.queueRemove(c),z.queueInit(c),r.unlock();var v=new Int32Array(z.ensureBufferFor(d+z.offset.status+4),d+z.offset.status,1);1===Atomics.load(v,0)&&l("unreachable");var p=z.getExecute(d),g=z.getEnv(d),w=z.getData(d);o.get(p)(g,w),Atomics.store(v,0,2),(0,y.postMessage)({__emnapi__:{type:"async-work-complete",payload:{work:d}}}),r.lock()}return 0},_emnapi_spawn_worker:function(e,r){if("function"!=typeof g)throw new TypeError("`options.onCreateWorker` is not a function");var t=[];if(!("emnapi_async_worker_create"in n.exports))throw new TypeError("`emnapi_async_worker_create` is not exported, please try to add `--export=emnapi_async_worker_create` to linker flags");t.push(n.exports.emnapi_async_worker_create(0,0));var a,o=function(e){!("message"in e)||-1===e.message.indexOf("RuntimeError")&&-1===e.message.indexOf("unreachable")||z.terminateWorkers()};try{var i=g({type:"async-work",name:"emnapi-async-worker"}),u=S.loadWasmModuleToWorker(i);f?i.on("error",o):i.addEventListener("error",o,!1),z.addListener(i),R.addListener(i),[].push(u.then(function(){"function"==typeof i.unref&&i.unref()})),a=z.pool.push(i)-1;var c=t[0];i.threadBlockBase=c,i.postMessage({__emnapi__:{type:"async-worker-init",payload:{arg:c,func:[e,r]}}})}catch(e){c=t[0];throw s(c),e}return a},napi_cancel_async_work:q,napi_create_async_work:G,napi_delete_async_work:M,napi_queue_async_work:P}),N={registry:"function"==typeof FinalizationRegistry?new FinalizationRegistry(function(e){s(e)}):void 0,table:new WeakMap,wasmMemoryViewTable:new WeakMap,intrinsics:void 0,init:function(){var e;N.registry="function"==typeof FinalizationRegistry?new FinalizationRegistry(function(e){s(e)}):void 0,N.table=new WeakMap,N.wasmMemoryViewTable=new WeakMap;var r="function"==typeof SharedArrayBuffer?null===(e=Object.getOwnPropertyDescriptor(SharedArrayBuffer.prototype,"byteLength"))||void 0===e?void 0:e.get:void 0;N.intrinsics={isView:ArrayBuffer.isView,typedArray:{buffer:Object.getOwnPropertyDescriptor(Object.getPrototypeOf(Uint8Array.prototype),"buffer").get,byteOffset:Object.getOwnPropertyDescriptor(Object.getPrototypeOf(Uint8Array.prototype),"byteOffset").get,length:Object.getOwnPropertyDescriptor(Object.getPrototypeOf(Uint8Array.prototype),"length").get,tag:Object.getOwnPropertyDescriptor(Object.getPrototypeOf(Uint8Array.prototype),Symbol.toStringTag).get},dataView:{buffer:Object.getOwnPropertyDescriptor(DataView.prototype,"buffer").get,byteOffset:Object.getOwnPropertyDescriptor(DataView.prototype,"byteOffset").get,byteLength:Object.getOwnPropertyDescriptor(DataView.prototype,"byteLength").get},arrayBuffer:{byteLength:Object.getOwnPropertyDescriptor(ArrayBuffer.prototype,"byteLength").get},sharedArrayBuffer:void 0!==r?{byteLength:r}:void 0,ctors:{Int8Array:Int8Array,Uint8Array:Uint8Array,Uint8ClampedArray:Uint8ClampedArray,Int16Array:Int16Array,Uint16Array:Uint16Array,Int32Array:Int32Array,Uint32Array:Uint32Array,Float16Array:"function"==typeof Float16Array?Float16Array:void 0,Float32Array:Float32Array,Float64Array:Float64Array,BigInt64Array:BigInt64Array,BigUint64Array:BigUint64Array},bufferFrom:void 0}},isSharedArrayBuffer:function(e){var r=N.intrinsics.sharedArrayBuffer;if(void 0!==r){if("function"==typeof SharedArrayBuffer&&e instanceof SharedArrayBuffer)return!0;try{return r.byteLength.call(e),!0}catch(e){return!1}}try{return N.intrinsics.arrayBuffer.byteLength.call(e),!1}catch(e){}return"[object SharedArrayBuffer]"===Object.prototype.toString.call(e)},isDetachedArrayBuffer:function(e){if(0===N.bufferByteLength(e))try{new Uint8Array(e)}catch(e){return!0}return!1},bufferByteLength:function(e){var r,t=N.intrinsics;try{return t.arrayBuffer.byteLength.call(e)}catch(i){var n=t.sharedArrayBuffer;if(void 0!==n)return n.byteLength.call(e);var a=Object.getPrototypeOf(e),o=null!=a?null===(r=Object.getOwnPropertyDescriptor(a,"byteLength"))||void 0===r?void 0:r.get:void 0;if(void 0===o)throw i;return o.call(e)}},viewBuffer:function(e){var r=N.intrinsics;return void 0===r.typedArray.tag.call(e)?r.dataView.buffer.call(e):r.typedArray.buffer.call(e)},viewByteOffset:function(e){var r=N.intrinsics;return void 0===r.typedArray.tag.call(e)?r.dataView.byteOffset.call(e):r.typedArray.byteOffset.call(e)},viewLength:function(e){var r=N.intrinsics;return void 0===r.typedArray.tag.call(e)?r.dataView.byteLength.call(e):r.typedArray.length.call(e)},getBufferFrom:function(){var e;return null!==(e=N.intrinsics.bufferFrom)&&void 0!==e?e:N.intrinsics.bufferFrom=d.feature.Buffer.from},getArrayBufferPointer:function(e,r){var t,n={address:0,ownership:0,runtimeAllocated:0};if(e===a.buffer)return n;var o=N.isDetachedArrayBuffer(e);if(N.table.has(e)){var s=N.table.get(e);return o?(s.address=0,s):(r&&0===s.ownership&&1===s.runtimeAllocated&&new Uint8Array(a.buffer).set(new Uint8Array(e),s.address),s)}var f=N.bufferByteLength(e);if(o||0===f)return n;if(!r)return n;var u=i(f);if(!u)throw new Error("Out of memory");return u>>>=0,new Uint8Array(a.buffer).set(new Uint8Array(e),u),n.address=u,n.ownership=N.registry?0:1,n.runtimeAllocated=1,N.table.set(e,n),null===(t=N.registry)||void 0===t||t.register(e,u),n},getOrUpdateMemoryView:function(e){var r=N.intrinsics,t=r.typedArray.tag.call(e),n=void 0===t,o=n?r.dataView.buffer.call(e):r.typedArray.buffer.call(e);if(o===a.buffer)return N.wasmMemoryViewTable.has(e)||N.wasmMemoryViewTable.set(e,{Ctor:n?DataView:r.ctors[t],address:n?r.dataView.byteOffset.call(e):r.typedArray.byteOffset.call(e),length:n?r.dataView.byteLength.call(e):r.typedArray.length.call(e),ownership:1,runtimeAllocated:0}),e;if((N.isDetachedArrayBuffer(o)||N.isSharedArrayBuffer(o))&&N.wasmMemoryViewTable.has(e)){var i=N.wasmMemoryViewTable.get(e),s=i.Ctor,f=void 0,u=d.feature.Buffer;return f="function"==typeof u&&s===u?N.getBufferFrom()(a.buffer,i.address,i.length):new s(a.buffer,i.address,i.length),N.wasmMemoryViewTable.set(f,i),f}return e},getViewPointer:function(e,r){e=N.getOrUpdateMemoryView(e);var t=N.viewBuffer(e);if(t===a.buffer){if(N.wasmMemoryViewTable.has(e)){var n=N.wasmMemoryViewTable.get(e);return{address:n.address,ownership:n.ownership,runtimeAllocated:n.runtimeAllocated,view:e}}return{address:N.viewByteOffset(e),ownership:1,runtimeAllocated:0,view:e}}var o=N.getArrayBufferPointer(t,r),i=o.address,s=o.ownership,f=o.runtimeAllocated;return{address:0===i?0:i+N.viewByteOffset(e),ownership:s,runtimeAllocated:f,view:e}}},J={registry:void 0,handleTable:new WeakMap,init:function(){J.handleTable=new WeakMap,J.registry="function"==typeof FinalizationRegistry?new FinalizationRegistry(function(e){J.release(e)}):void 0},allocMeta:function(e,r,t,n,o){var s=i(24);if(!s)throw new Error("Out of memory");s>>>=0,Atomics.store(new Int32Array(a.buffer,s,1),0,1);var f=new DataView(a.buffer),u=function(){return f.buffer===a.buffer?f:f=new DataView(a.buffer)};return u().setUint32(s+4,e,!0),u().setUint32(s+8,r,!0),u().setUint32(s+12,t,!0),u().setUint32(s+16,n,!0),u().setUint32(s+20,o,!0),s},readMeta:function(e){var r=new DataView(a.buffer),t=function(){return r.buffer===a.buffer?r:r=new DataView(a.buffer)};return{external_data:t().getUint32(e+4,!0),byte_length:t().getUint32(e+8,!0),finalize_cb:t().getUint32(e+12,!0),finalize_data:t().getUint32(e+16,!0),finalize_hint:t().getUint32(e+20,!0)}},release:function(e){if(1===Atomics.sub(new Int32Array(a.buffer,e,1),0,1)){var r=J.readMeta(e),t=r.finalize_cb;if(t){var n=r.finalize_data,i=r.finalize_hint;o.get(t)(n,i)}s(e)}}},H={utf8Decoder:void 0,utf16Decoder:void 0,init:function(){var e,r={decode:function(e){for(var r=0,t=Math.min(4096,e.length+1),n=new Uint16Array(t),a=[],o=0;;){var i=r=t-1){var s=n.subarray(0,o);if(a.push(String.fromCharCode.apply(null,s)),!i)return a.join("");e=e.subarray(r),r=0,o=0}var f=e[r++];if(128&f){if(192==(224&f)){var u=63&e[r++];n[o++]=(31&f)<<6|u}else if(224==(240&f)){u=63&e[r++];var c=63&e[r++];n[o++]=(31&f)<<12|u<<6|c}else if(240==(248&f)){var l=(7&f)<<18|(u=63&e[r++])<<12|(c=63&e[r++])<<6|63&e[r++];l>65535&&(l-=65536,n[o++]=l>>>10&1023|55296,l=56320|1023&l),n[o++]=l}}else n[o++]=f}}};e="function"==typeof TextDecoder?new TextDecoder:r,H.utf8Decoder=e;var t,n={decode:function(e){var r=new Uint16Array(e.buffer,e.byteOffset,e.byteLength/2);if(r.length<=4096)return String.fromCharCode.apply(null,r);for(var t=[],n=0,a=0;n=55296&&r<=57343?(t+=4,++n):t+=3;return t},UTF8ToString:function(e,r){if(!e||!r)return"";e>>>=0;var t=new Uint8Array(a.buffer),n=e;if(-1===r||4294967295===r)for(;t[n];)++n;else n=e+(r>>>0);if((r=n-e)<=16){for(var o=e,i="";o>10,56320|1023&c)}}else i+=String.fromCharCode((31&s)<<6|f)}else i+=String.fromCharCode(s)}return i}return H.utf8Decoder.decode("function"==typeof SharedArrayBuffer&&t.buffer instanceof SharedArrayBuffer||"[object SharedArrayBuffer]"===Object.prototype.toString.call(t.buffer)?t.slice(e,n):t.subarray(e,n))},stringToUTF8:function(e,r,t){var n=new Uint8Array(a.buffer),o=r;if(!(t>0))return 0;for(var i=o>>>=0,s=o+t-1,f=0;f=55296&&u<=57343)u=65536+((1023&u)<<10)|1023&e.charCodeAt(++f);if(u<=127){if(o>=s)break;n[o++]=u}else if(u<=2047){if(o+1>=s)break;n[o++]=192|u>>6,n[o++]=128|63&u}else if(u<=65535){if(o+2>=s)break;n[o++]=224|u>>12,n[o++]=128|u>>6&63,n[o++]=128|63&u}else{if(o+3>=s)break;n[o++]=240|u>>18,n[o++]=128|u>>12&63,n[o++]=128|u>>6&63,n[o++]=128|63&u}}return n[o]=0,o-i},UTF16ToString:function(e,r){if(!e||!r)return"";var t=e>>>=0;if(-1===r||4294967295===r){for(var n=t>>>1,o=new Uint16Array(a.buffer);o[n];)++n;t=n<<1>>>0}else t=e+2*(r>>>0);if((r=t-e)<=32)return String.fromCharCode.apply(null,new Uint16Array(a.buffer,e,r/2));var i=new Uint8Array(a.buffer);return H.utf16Decoder.decode("function"==typeof SharedArrayBuffer&&i.buffer instanceof SharedArrayBuffer||"[object SharedArrayBuffer]"===Object.prototype.toString.call(i.buffer)?i.slice(e,t):i.subarray(e,t))},stringToUTF16:function(e,r,t){if(void 0===t&&(t=2147483647),t<2)return 0;for(var n=r,o=(t-=2)<2*e.length?t/2:e.length,i=new DataView(a.buffer),s=function(){return i.buffer===a.buffer?i:i=new DataView(a.buffer)},f=0;f>>=0,!e)return 1;var i=d.envStore.get(e);i.checkGCAccess();var s=-1===t||4294967295===t,f=t>>>0;if(0!==t&&!r)return i.setLastError(1);if(!n)return i.setLastError(1);if(!(s||f<=2147483647))return i.setLastError(1);var u=o(r>>>=0,s,f);n>>>=0;var c=d.addToCurrentScope(u).id,l=new DataView(a.buffer);return(l.buffer===a.buffer?l:l=new DataView(a.buffer)).setUint32(n,c,!0),i.clearLastError()},newExternalString:function(e,r,t,n,o,i,s,f,u){if(t>>>=0,!e)return 1;var c=d.envStore.get(e);c.checkGCAccess();var l=-1===t||4294967295===t,v=t>>>0;if(0!==t&&!r)return c.setLastError(1);if(!i)return c.setLastError(1);if(!(l||v<=2147483647))return c.setLastError(1);var p=f(e,r,t,i);if(0===p){if(s){var y=new DataView(a.buffer);(y.buffer===a.buffer?y:y=new DataView(a.buffer)).setInt8(s,1,!0)}n&&c.callFinalizer(n,r,o)}return p}};function Q(e,r,t,n,o,i,s){if(!e)return 1;var f=d.envStore.get(e);if(f.checkGCAccess(),!r)return f.setLastError(1);var u=d.handleStore.get(r);if(!N.intrinsics.isView(u.value))return f.setLastError(1);var c=u.value,l=new DataView(a.buffer),v=function(){return l.buffer===a.buffer?l:l=new DataView(a.buffer)};if(t){t>>>=0;var p=void 0;switch(N.intrinsics.typedArray.tag.call(c)){case"Int8Array":p=0;break;case"Uint8Array":p=1;break;case"Uint8ClampedArray":p=2;break;case"Int16Array":p=3;break;case"Uint16Array":p=4;break;case"Int32Array":p=5;break;case"Uint32Array":p=6;break;case"Float16Array":p=11;break;case"Float32Array":p=7;break;case"Float64Array":p=8;break;case"BigInt64Array":p=9;break;case"BigUint64Array":p=10;break;default:return f.setLastError(9)}v().setInt32(t,p,!0)}if(c=N.getOrUpdateMemoryView(c),n){n>>>=0;var y=N.viewLength(c);v().setUint32(n,y,!0)}if(o||i){if(o){o>>>=0;var g=N.getViewPointer(c,!0);c=g.view;var w=g.address;v().setUint32(o,w,!0)}if(i){i>>>=0;var b=f.ensureHandleId(N.viewBuffer(c));v().setUint32(i,b,!0)}}if(s){s>>>=0;var h=N.viewByteOffset(c);v().setUint32(s,h,!0)}return f.clearLastError()}function $(e,r,t,n,o,i){if(!e)return 1;var s=d.envStore.get(e);if(s.checkGCAccess(),!r)return s.setLastError(1);var f=d.handleStore.get(r);if(!N.intrinsics.isView(f.value)||void 0!==N.intrinsics.typedArray.tag.call(f.value))return s.setLastError(1);var u=N.getOrUpdateMemoryView(f.value),c=new DataView(a.buffer),l=function(){return c.buffer===a.buffer?c:c=new DataView(a.buffer)};if(t){t>>>=0;var v=N.viewLength(u);l().setUint32(t,v,!0)}if(n||o){if(n){n>>>=0;var p=N.getViewPointer(u,!0);u=p.view;var y=p.address;l().setUint32(n,y,!0)}if(o){o>>>=0;var g=s.ensureHandleId(N.viewBuffer(u));l().setUint32(o,g,!0)}}if(i){i>>>=0;var w=N.viewByteOffset(u);l().setUint32(i,w,!0)}return s.clearLastError()}var Y=Object.freeze({__proto__:null,napi_get_array_length:function(e,r,t){if(!e)return 1;var n=d.envStore.get(e);if(n.checkGCAccess(),!n.tryCatch.isEmpty())return n.setLastError(10);if(!n.canCallIntoJs())return n.setLastError(n.moduleApiVersion>=10?23:10);n.clearLastError();try{if(!r)return n.setLastError(1);if(!t)return n.setLastError(1);var o=d.handleStore.get(r);if(!o.isArray())return n.setLastError(8);t>>>=0;var i=o.value.length>>>0,s=new DataView(a.buffer);return(s.buffer===a.buffer?s:s=new DataView(a.buffer)).setUint32(t,i,!0),n.getReturnStatus()}catch(e){return n.tryCatch.setError(e),n.setLastError(10)}},napi_get_arraybuffer_info:function(e,r,t,n){if(!e)return 1;var o=d.envStore.get(e);if(o.checkGCAccess(),!r)return o.setLastError(1);var i=d.handleStore.get(r);if(!i.isArrayBuffer()&&!N.isSharedArrayBuffer(i.value))return o.setLastError(1);var s=new DataView(a.buffer),f=function(){return s.buffer===a.buffer?s:s=new DataView(a.buffer)};if(t){t>>>=0;var u=N.getArrayBufferPointer(i.value,!0).address;f().setUint32(t,u,!0)}if(n){n>>>=0;var c=N.bufferByteLength(i.value);f().setUint32(n,c,!0)}return o.clearLastError()},napi_get_buffer_info:function(e,r,t,n){if(!e)return 1;var a=d.envStore.get(e);if(a.checkGCAccess(),!r)return a.setLastError(1);var o=d.handleStore.get(r),i=d.feature.Buffer;return N.intrinsics.isView(o.value)||"function"==typeof i&&i.isBuffer(o.value)?void 0===N.intrinsics.typedArray.tag.call(o.value)?$(e,r,n,t,0,0):Q(e,r,0,n,t,0,0):a.setLastError(1)},napi_get_dataview_info:$,napi_get_date_value:function(e,r,t){var n;if(!e)return 1;var o=d.envStore.get(e);if(o.checkGCAccess(),!o.tryCatch.isEmpty())return o.setLastError(10);if(!o.canCallIntoJs())return o.setLastError(o.moduleApiVersion>=10?23:10);o.clearLastError();try{if(!r)return o.setLastError(1);if(!t)return o.setLastError(1);var i=d.handleStore.get(r);if(!i.isDate())return o.setLastError(1);t>>>=0,n=i.value.valueOf();var s=new DataView(a.buffer);return(s.buffer===a.buffer?s:s=new DataView(a.buffer)).setFloat64(t,n,!0),o.getReturnStatus()}catch(e){return o.tryCatch.setError(e),o.setLastError(10)}},napi_get_prototype:function(e,r,t){if(!e)return 1;var n=d.envStore.get(e);if(n.checkGCAccess(),!n.tryCatch.isEmpty())return n.setLastError(10);if(!n.canCallIntoJs())return n.setLastError(n.moduleApiVersion>=10?23:10);n.clearLastError();try{if(!r)return n.setLastError(1);if(!t)return n.setLastError(1);var o=d.handleStore.get(r);if(null==o.value)throw new TypeError("Cannot convert undefined or null to object");var i=void 0;try{i=o.isObject()||o.isFunction()?o.value:Object(o.value)}catch(e){return n.setLastError(2)}t>>>=0;var s=n.ensureHandleId(Object.getPrototypeOf(i)),f=new DataView(a.buffer);return(f.buffer===a.buffer?f:f=new DataView(a.buffer)).setUint32(t,s,!0),n.getReturnStatus()}catch(e){return n.tryCatch.setError(e),n.setLastError(10)}},napi_get_typedarray_info:Q,napi_get_value_bigint_int64:function(e,r,t,n){if(!e)return 1;var o=d.envStore.get(e);if(o.checkGCAccess(),!d.feature.supportBigInt)return o.setLastError(9);if(!r)return o.setLastError(1);if(!t)return o.setLastError(1);if(!n)return o.setLastError(1);var i=d.handleStore.get(r).value;if("bigint"!=typeof i)return o.setLastError(6);n>>>=0,t>>>=0;var s=new DataView(a.buffer),f=function(){return s.buffer===a.buffer?s:s=new DataView(a.buffer)};i>=BigInt(-1)*(BigInt(1)<=BigInt(1)<>BigInt(32));return f().setInt32(t,u,!0),f().setInt32(t+4,c,!0),o.clearLastError()},napi_get_value_bigint_uint64:function(e,r,t,n){if(!e)return 1;var o=d.envStore.get(e);if(o.checkGCAccess(),!d.feature.supportBigInt)return o.setLastError(9);if(!r)return o.setLastError(1);if(!t)return o.setLastError(1);if(!n)return o.setLastError(1);var i=d.handleStore.get(r).value;if("bigint"!=typeof i)return o.setLastError(6);n>>>=0,t>>>=0;var s=new DataView(a.buffer),f=function(){return s.buffer===a.buffer?s:s=new DataView(a.buffer)};i>=BigInt(0)&&i>BigInt(32));return f().setUint32(t,u,!0),f().setUint32(t+4,c,!0),o.clearLastError()},napi_get_value_bigint_words:function(e,r,t,n,o){if(!e)return 1;var i=d.envStore.get(e);if(i.checkGCAccess(),!d.feature.supportBigInt)return i.setLastError(9);if(!r)return i.setLastError(1);if(!n)return i.setLastError(1);var s=d.handleStore.get(r);if(!s.isBigInt())return i.setLastError(17);var f=s.value>>=0,o>>>=0,n>>>=0;var u=new DataView(a.buffer),c=function(){return u.buffer===a.buffer?u:u=new DataView(a.buffer)},l=c().getUint32(n,!0);l>>>=0;for(var v=0,p=f?s.value*BigInt(-1):s.value;p!==BigInt(0);)v++,p>>=BigInt(64);if(p=f?s.value*BigInt(-1):s.value,t||o){if(!t)return i.setLastError(1);if(!o)return i.setLastError(1);for(var y=[];p!==BigInt(0);){var g=p&(BigInt(1)<>=BigInt(64)}for(var w=Math.min(l,y.length),b=0;b>BigInt(32));c().setUint32(o+8*b,h,!0),c().setUint32(o+(8*b+4),_,!0)}c().setInt32(t,f?1:0,!0),c().setUint32(n,w,!0)}else l=v,c().setUint32(n,l,!0);return i.clearLastError()},napi_get_value_bool:function(e,r,t){if(!e)return 1;var n=d.envStore.get(e);if(n.checkGCAccess(),!r)return n.setLastError(1);if(!t)return n.setLastError(1);var o=d.handleStore.get(r);if("boolean"!=typeof o.value)return n.setLastError(7);t>>>=0;var i=o.value?1:0,s=new DataView(a.buffer);return(s.buffer===a.buffer?s:s=new DataView(a.buffer)).setInt8(t,i,!0),n.clearLastError()},napi_get_value_double:function(e,r,t){if(!e)return 1;var n=d.envStore.get(e);if(n.checkGCAccess(),!r)return n.setLastError(1);if(!t)return n.setLastError(1);var o=d.handleStore.get(r);if("number"!=typeof o.value)return n.setLastError(6);t>>>=0;var i=o.value,s=new DataView(a.buffer);return(s.buffer===a.buffer?s:s=new DataView(a.buffer)).setFloat64(t,i,!0),n.clearLastError()},napi_get_value_external:function(e,r,t){if(!e)return 1;var n=d.envStore.get(e);if(n.checkGCAccess(),!r)return n.setLastError(1);if(!t)return n.setLastError(1);var o=d.handleStore.get(r);if(!o.isExternal())return n.setLastError(1);t>>>=0;var i=o.data(),s=new DataView(a.buffer);return(s.buffer===a.buffer?s:s=new DataView(a.buffer)).setUint32(t,i,!0),n.clearLastError()},napi_get_value_int32:function(e,r,t){if(!e)return 1;var n=d.envStore.get(e);if(n.checkGCAccess(),!r)return n.setLastError(1);if(!t)return n.setLastError(1);var o=d.handleStore.get(r);if("number"!=typeof o.value)return n.setLastError(6);t>>>=0;var i=new Int32Array([o.value])[0],s=new DataView(a.buffer);return(s.buffer===a.buffer?s:s=new DataView(a.buffer)).setInt32(t,i,!0),n.clearLastError()},napi_get_value_int64:function(e,r,t){if(!e)return 1;var n=d.envStore.get(e);if(n.checkGCAccess(),!r)return n.setLastError(1);if(!t)return n.setLastError(1);var o=d.handleStore.get(r);if("number"!=typeof o.value)return n.setLastError(6);var i=o.value;t>>>=0;var s=new DataView(a.buffer),f=function(){return s.buffer===a.buffer?s:s=new DataView(a.buffer)};return i===Number.POSITIVE_INFINITY||i===Number.NEGATIVE_INFINITY||isNaN(i)?(f().setInt32(t,0,!0),f().setInt32(t+4,0,!0)):i<-0x8000000000000000?(f().setInt32(t,0,!0),f().setInt32(t+4,2147483648,!0)):i>=0x8000000000000000?(f().setUint32(t,4294967295,!0),f().setUint32(t+4,2147483647,!0)):V(t,Math.trunc(i)),n.clearLastError()},napi_get_value_string_latin1:function(e,r,t,n,o){if(!e)return 1;var i=d.envStore.get(e);if(i.checkGCAccess(),!r)return i.setLastError(1);o>>>=0,t>>>=0,n>>>=0,n>>>=0;var s=d.handleStore.get(r);if("string"!=typeof s.value)return i.setLastError(3);var f=new DataView(a.buffer),u=function(){return f.buffer===a.buffer?f:f=new DataView(a.buffer)};if(t)if(0!==n){for(var c=0,l=void 0,v=0;v>>=0,t>>>=0,n>>>=0,n>>>=0;var s=d.handleStore.get(r);if("string"!=typeof s.value)return i.setLastError(3);var f=new DataView(a.buffer),u=function(){return f.buffer===a.buffer?f:f=new DataView(a.buffer)};if(t)if(0!==n){var c=H.stringToUTF16(s.value,t,2*n);o&&u().setUint32(o,c/2,!0)}else o&&u().setUint32(o,0,!0);else{if(!o)return i.setLastError(1);u().setUint32(o,s.value.length,!0)}return i.clearLastError()},napi_get_value_string_utf8:function(e,r,t,n,o){if(!e)return 1;var i=d.envStore.get(e);if(i.checkGCAccess(),!r)return i.setLastError(1);o>>>=0,t>>>=0,n>>>=0,n>>>=0;var s=d.handleStore.get(r);if("string"!=typeof s.value)return i.setLastError(3);var f=new DataView(a.buffer),u=function(){return f.buffer===a.buffer?f:f=new DataView(a.buffer)};if(t)if(0!==n){var c=H.stringToUTF8(s.value,t,n);o&&u().setUint32(o,c,!0)}else o&&u().setUint32(o,0,!0);else{if(!o)return i.setLastError(1);var l=H.lengthBytesUTF8(s.value);u().setUint32(o,l,!0)}return i.clearLastError()},napi_get_value_uint32:function(e,r,t){if(!e)return 1;var n=d.envStore.get(e);if(n.checkGCAccess(),!r)return n.setLastError(1);if(!t)return n.setLastError(1);var o=d.handleStore.get(r);if("number"!=typeof o.value)return n.setLastError(6);t>>>=0;var i=new Uint32Array([o.value])[0],s=new DataView(a.buffer);return(s.buffer===a.buffer?s:s=new DataView(a.buffer)).setUint32(t,i,!0),n.clearLastError()},node_api_set_prototype:function(e,r,t){if(!e)return 1;var n=d.envStore.get(e);if(n.checkGCAccess(),!n.tryCatch.isEmpty())return n.setLastError(10);if(!n.canCallIntoJs())return n.setLastError(n.moduleApiVersion>=10?23:10);n.clearLastError();try{if(!t)return n.setLastError(1);var a=d.handleStore.get(r).value;if(null==a)throw new TypeError("Cannot convert undefined or null to object");var o=typeof a,i=void 0;try{i="object"===o&&null!==a||"function"===o?a:Object(a)}catch(e){return n.setLastError(2)}var s=d.handleStore.get(t).value;return Object.setPrototypeOf(i,s),n.getReturnStatus()}catch(e){return n.tryCatch.setError(e),n.setLastError(10)}}});function X(e,r,t,n){return H.newString(e,r,t,n,function(e,r,t){var n="",o=0,i=new DataView(a.buffer),s=function(){return i.buffer===a.buffer?i:i=new DataView(a.buffer)};if(r)for(;;){if(!(f=s().getUint8(e,!0)))break;n+=String.fromCharCode(f),e++}else for(;o>>=0;var f=new DataView(a.buffer);return(f.buffer===a.buffer?f:f=new DataView(a.buffer)).setUint32(t,s,!0),i.clearLastError()},napi_create_bigint_uint64:function(e,r,t,n){if(!e)return 1;var o,i=d.envStore.get(e);if(i.checkGCAccess(),!d.feature.supportBigInt)return i.setLastError(9);if(!t)return i.setLastError(1);o=r&(BigInt(1)<>>=0;var f=new DataView(a.buffer);return(f.buffer===a.buffer?f:f=new DataView(a.buffer)).setUint32(t,s,!0),i.clearLastError()},napi_create_bigint_words:function(e,r,t,n,o){var i,s;if(!e)return 1;var f=d.envStore.get(e);if(f.checkGCAccess(),!f.tryCatch.isEmpty())return f.setLastError(10);if(!f.canCallIntoJs())return f.setLastError(f.moduleApiVersion>=10?23:10);f.clearLastError();try{if(!d.feature.supportBigInt)return f.setLastError(9);if(!o)return f.setLastError(1);if(n>>>=0,t>>>=0,(t>>>=0)>2147483647)return f.setLastError(1);if(t>16384)throw new RangeError("Maximum BigInt size exceeded");var u=BigInt(0),c=new DataView(a.buffer),l=function(){return c.buffer===a.buffer?c:c=new DataView(a.buffer)};for(s=0;s>>=0,i=d.addToCurrentScope(u).id,l().setUint32(o,i,!0),f.getReturnStatus()}catch(e){return f.tryCatch.setError(e),f.setLastError(10)}},napi_create_double:function(e,r,t){if(!e)return 1;var n=d.envStore.get(e);if(n.checkGCAccess(),!t)return n.setLastError(1);t>>>=0;var o=d.addToCurrentScope(r).id,i=new DataView(a.buffer);return(i.buffer===a.buffer?i:i=new DataView(a.buffer)).setUint32(t,o,!0),n.clearLastError()},napi_create_int32:function(e,r,t){if(!e)return 1;var n=d.envStore.get(e);if(n.checkGCAccess(),!t)return n.setLastError(1);t>>>=0;var o=d.addToCurrentScope(r).id,i=new DataView(a.buffer);return(i.buffer===a.buffer?i:i=new DataView(a.buffer)).setUint32(t,o,!0),n.clearLastError()},napi_create_int64:function(e,r,t,n){if(!e)return 1;var o,i=d.envStore.get(e);if(i.checkGCAccess(),!t)return i.setLastError(1);o=Number(r);var s=d.addToCurrentScope(o).id;t>>>=0;var f=new DataView(a.buffer);return(f.buffer===a.buffer?f:f=new DataView(a.buffer)).setUint32(t,s,!0),i.clearLastError()},napi_create_string_latin1:X,napi_create_string_utf16:Z,napi_create_string_utf8:K,napi_create_uint32:function(e,r,t){if(!e)return 1;var n=d.envStore.get(e);if(n.checkGCAccess(),!t)return n.setLastError(1);t>>>=0;var o=d.addToCurrentScope(r>>>0).id,i=new DataView(a.buffer);return(i.buffer===a.buffer?i:i=new DataView(a.buffer)).setUint32(t,o,!0),n.clearLastError()},node_api_create_external_string_latin1:function(e,r,t,n,a,o,i){return H.newExternalString(e,r,t,n,a,o,i,X,void 0)},node_api_create_external_string_utf16:function(e,r,t,n,a,o,i){return H.newExternalString(e,r,t,n,a,o,i,Z,void 0)},node_api_create_property_key_latin1:function(e,r,t,n){return X(e,r,t,n)},node_api_create_property_key_utf16:function(e,r,t,n){return Z(e,r,t,n)},node_api_create_property_key_utf8:function(e,r,t,n){return K(e,r,t,n)}});function re(e,r,t,n,a){var i,s=(r>>>=0)&&t?H.UTF8ToString(r,t):"",f=o.get(n),u=function(e){return f(e.id,e.ctx.scopeStore.currentScope.id)},c=function(e,r){return function(){var t=e.ctx.openScope(e),n=t.callbackInfo;n.data=a,n.args=arguments,n.thiz=this,n.fn=i;try{var o=e.callIntoModule(r);return o?e.ctx.handleStore.get(o).value:void 0}finally{n.data=0,n.args=void 0,n.thiz=void 0,n.fn=void 0,e.ctx.closeScope(e,t)}}};if(""===s)return{status:0,f:i=c(e,u)};if(!/^[_$a-zA-Z][_$a-zA-Z0-9]*$/.test(s))return{status:1,f:void 0};if(d.feature.supportNewFunction){var l=c(e,u);try{i=new Function("_","return function "+s+'(){"use strict";return _.apply(this,arguments);};')(l)}catch(r){i=c(e,u),d.feature.canSetFunctionName&&Object.defineProperty(i,"name",{value:s})}}else i=c(e,u),d.feature.canSetFunctionName&&Object.defineProperty(i,"name",{value:s});return{status:0,f:i}}function te(e,r,t,n,a,o,i,s,f){if(a||o){var u=void 0,c=void 0;a&&(u=re(e,0,0,a,f).f),o&&(c=re(e,0,0,o,f).f);var l={configurable:!!(4&s),enumerable:!!(2&s),get:u,set:c};Object.defineProperty(r,t,l)}else if(n){l={configurable:!!(4&s),enumerable:!!(2&s),writable:!!(1&s),value:re(e,0,0,n,f).f};Object.defineProperty(r,t,l)}else{l={configurable:!!(4&s),enumerable:!!(2&s),writable:!!(1&s),value:d.handleStore.get(i).value};Object.defineProperty(r,t,l)}}function ne(e){var r=d.handleStore.get(e);return r.isObject()||r.isFunction()?(void 0!==N&&ArrayBuffer.isView(r.value)&&N.wasmMemoryViewTable.has(r.value)&&(r=d.addToCurrentScope(N.wasmMemoryViewTable.get(r.value))),{status:0,handle:r}):{status:1}}function ae(e,r,t,n){var o;if(!e)return 1;var i=d.envStore.get(e);if(i.checkGCAccess(),!i.tryCatch.isEmpty())return i.setLastError(10);if(!i.canCallIntoJs())return i.setLastError(i.moduleApiVersion>=10?23:10);i.clearLastError();try{if(!r)return i.setLastError(1);if(0===n&&!t)return i.setLastError(1);var s=d.handleStore.get(r);if(!s.isObject()&&!s.isFunction())return i.setLastError(1);var f=i.getObjectBinding(s.value),u=f.wrapped,c=d.refStore.get(u);if(!c)return i.setLastError(1);if(t){t>>>=0,o=c.data();var l=new DataView(a.buffer);(l.buffer===a.buffer?l:l=new DataView(a.buffer)).setUint32(t,o,!0)}return 1===n&&(f.wrapped=0,1===c.ownership()?c.resetFinalizer():c.dispose()),i.getReturnStatus()}catch(e){return i.tryCatch.setError(e),i.setLastError(10)}}function oe(e,r,t,n,o,i){if(!e)return 1;var s=d.envStore.get(e);if(s.checkGCAccess(),!d.feature.supportFinalizer)return s.setLastError(9);if(!r)return s.setLastError(1);if(!n)return s.setLastError(1);var f=ne(r);if(0!==f.status)return s.setLastError(f.status);var u=f.handle,c=i?1:0;t>>>=0,n>>>=0,o>>>=0;var l=d.createReferenceWithFinalizer(s,u.id,0,c,n,t,o);if(i){i>>>=0;var v=l.id,p=new DataView(a.buffer);(p.buffer===a.buffer?p:p=new DataView(a.buffer)).setUint32(i,v,!0)}return s.clearLastError()}var ie=Object.freeze({__proto__:null,napi_add_finalizer:oe,napi_check_object_type_tag:function(e,r,t,n){var o=!0;if(!e)return 1;var i=d.envStore.get(e);if(i.checkGCAccess(),!i.tryCatch.isEmpty())return i.setLastError(10);if(!i.canCallIntoJs())return i.setLastError(i.moduleApiVersion>=10?23:10);i.clearLastError();try{if(!r)return i.setLastError(i.tryCatch.hasCaught()?10:1);var s=d.handleStore.get(r);if(!s.isObject()&&!s.isFunction())return i.setLastError(i.tryCatch.hasCaught()?10:2);if(!t)return i.setLastError(i.tryCatch.hasCaught()?10:1);if(!n)return i.setLastError(i.tryCatch.hasCaught()?10:1);var f=i.getObjectBinding(s.value);if(null!==f.tag){t>>>=0;var u=f.tag,c=new Uint32Array(a.buffer,t,4);o=u[0]===c[0]&&u[1]===c[1]&&u[2]===c[2]&&u[3]===c[3]}else o=!1;n>>>=0;var l=new DataView(a.buffer);return(l.buffer===a.buffer?l:l=new DataView(a.buffer)).setInt8(n,o?1:0,!0),i.getReturnStatus()}catch(e){return i.tryCatch.setError(e),i.setLastError(10)}},napi_define_class:function(e,r,t,n,o,i,s,f){var u,c,l;if(!e)return 1;var v=d.envStore.get(e);if(v.checkGCAccess(),!v.tryCatch.isEmpty())return v.setLastError(10);if(!v.canCallIntoJs())return v.setLastError(v.moduleApiVersion>=10?23:10);v.clearLastError();try{if(!f)return v.setLastError(1);if(!n)return v.setLastError(1);if(t>>>=0,s>>>=0,i>>>=0,(i>>>=0)>0&&!s)return v.setLastError(1);if(!(t>=-1&&t<=2147483647||4294967295===t)||!r)return v.setLastError(1);var p=re(v,r,t,n,o);if(0!==p.status)return v.setLastError(p.status);for(var y=p.f,g=void 0,w=new DataView(a.buffer),b=function(){return w.buffer===a.buffer?w:w=new DataView(a.buffer)},h=0;h>>=0;var C=b().getUint32(u+28,!0);if(_)g=H.UTF8ToString(_,-1);else{if(!E)return v.setLastError(4);if("string"!=typeof(g=d.handleStore.get(E).value)&&"symbol"!=typeof g)return v.setLastError(4)}1024&l?te(v,y,g,L,m,S,A,l,C):te(v,y.prototype,g,L,m,S,A,l,C)}return c=d.addToCurrentScope(y).id,f>>>=0,b().setUint32(f,c,!0),v.getReturnStatus()}catch(e){return v.tryCatch.setError(e),v.setLastError(10)}},napi_remove_wrap:function(e,r,t){return ae(e,r,t,1)},napi_type_tag_object:function(e,r,t){if(!e)return 1;var n=d.envStore.get(e);if(n.checkGCAccess(),!n.tryCatch.isEmpty())return n.setLastError(10);if(!n.canCallIntoJs())return n.setLastError(n.moduleApiVersion>=10?23:10);n.clearLastError();try{if(!r)return n.setLastError(n.tryCatch.hasCaught()?10:1);var o=d.handleStore.get(r);if(!o.isObject()&&!o.isFunction())return n.setLastError(n.tryCatch.hasCaught()?10:2);if(!(t>>>=0))return n.setLastError(n.tryCatch.hasCaught()?10:1);var i=n.getObjectBinding(o.value);if(null!==i.tag)return n.setLastError(n.tryCatch.hasCaught()?10:1);var s=new Uint8Array(16);return s.set(new Uint8Array(a.buffer,t,16)),i.tag=new Uint32Array(s.buffer),n.getReturnStatus()}catch(e){return n.tryCatch.setError(e),n.setLastError(10)}},napi_unwrap:function(e,r,t){return ae(e,r,t,0)},napi_wrap:function(e,r,t,n,o,i){return function(e,r,t,n,o,i){var s;if(!e)return 1;var f=d.envStore.get(e);if(f.checkGCAccess(),!f.tryCatch.isEmpty())return f.setLastError(10);if(!f.canCallIntoJs())return f.setLastError(f.moduleApiVersion>=10?23:10);f.clearLastError();try{if(!d.feature.supportFinalizer){if(n)throw d.createNotSupportWeakRefError("napi_wrap",'Parameter "finalize_cb" must be 0(NULL)');if(i)throw d.createNotSupportWeakRefError("napi_wrap",'Parameter "result" must be 0(NULL)')}if(!r)return f.setLastError(1);var u=ne(r);if(0!==u.status)return f.setLastError(u.status);var c=u.handle;if(0!==f.getObjectBinding(c.value).wrapped)return f.setLastError(1);var l=void 0;if(i){if(!n)return f.setLastError(1);l=d.createReferenceWithFinalizer(f,c.id,0,1,n,t,o),i>>>=0,s=l.id;var v=new DataView(a.buffer);(v.buffer===a.buffer?v:v=new DataView(a.buffer)).setUint32(i,s,!0)}else l=n?d.createReferenceWithFinalizer(f,c.id,0,0,n,t,o):d.createReferenceWithData(f,c.id,0,0,t);return f.getObjectBinding(c.value).wrapped=l.id,f.getReturnStatus()}catch(e){return f.tryCatch.setError(e),f.setLastError(10)}}(e,r,t,n,o,i)},node_api_post_finalizer:function(e,r,t,n){if(!e)return 1;var a=d.envStore.get(e);return a.enqueueFinalizer(d.createTrackedFinalizer(a,r,t,n)),a.clearLastError()}});function se(e,r,t,n,o,i,s){var f;if(!e)return 1;var u=d.envStore.get(e);if(u.checkGCAccess(),!u.tryCatch.isEmpty())return u.setLastError(10);if(!u.canCallIntoJs())return u.setLastError(u.moduleApiVersion>=10?23:10);u.clearLastError();try{if(!s)return u.setLastError(1);if(n>>>=0,s>>>=0,n>>>=0,(t>>>=0)||(n=0),n>2147483647)throw new RangeError("Cannot create a memory view larger than 2147483647 bytes");if(t+n>a.buffer.byteLength)throw new RangeError("Memory out of range");if(!d.feature.supportFinalizer&&o)throw d.createNotSupportWeakRefError("emnapi_create_memory_view",'Parameter "finalize_cb" must be 0(NULL)');var c=void 0;switch(r){case 0:c={Ctor:Int8Array,address:t,length:n,ownership:1,runtimeAllocated:0};break;case 1:c={Ctor:Uint8Array,address:t,length:n,ownership:1,runtimeAllocated:0};break;case 2:c={Ctor:Uint8ClampedArray,address:t,length:n,ownership:1,runtimeAllocated:0};break;case 3:c={Ctor:Int16Array,address:t,length:n>>1,ownership:1,runtimeAllocated:0};break;case 4:c={Ctor:Uint16Array,address:t,length:n>>1,ownership:1,runtimeAllocated:0};break;case 5:c={Ctor:Int32Array,address:t,length:n>>2,ownership:1,runtimeAllocated:0};break;case 6:c={Ctor:Uint32Array,address:t,length:n>>2,ownership:1,runtimeAllocated:0};break;case 7:c={Ctor:Float32Array,address:t,length:n>>2,ownership:1,runtimeAllocated:0};break;case 8:c={Ctor:Float64Array,address:t,length:n>>3,ownership:1,runtimeAllocated:0};break;case 9:c={Ctor:BigInt64Array,address:t,length:n>>3,ownership:1,runtimeAllocated:0};break;case 10:c={Ctor:BigUint64Array,address:t,length:n>>3,ownership:1,runtimeAllocated:0};break;case-1:c={Ctor:DataView,address:t,length:n,ownership:1,runtimeAllocated:0};break;case 11:if("function"!=typeof Float16Array)return u.setLastError(1);c={Ctor:Float16Array,address:t,length:n>>1,ownership:1,runtimeAllocated:0};break;case-2:if(!d.feature.Buffer)throw d.createNotSupportBufferError("emnapi_create_memory_view","");c={Ctor:d.feature.Buffer,address:t,length:n,ownership:1,runtimeAllocated:0};break;default:return u.setLastError(1)}var l=c.Ctor,v=-2===r?N.getBufferFrom()(a.buffer,c.address,c.length):new l(a.buffer,c.address,c.length),p=d.addToCurrentScope(v);if(N.wasmMemoryViewTable.set(v,c),o){var y=oe(e,p.id,t,o,i,0);if(10===y){var g=u.tryCatch.extractException();throw u.clearLastError(),g}if(0!==y)return u.setLastError(y)}f=p.id;var w=new DataView(a.buffer);return(w.buffer===a.buffer?w:w=new DataView(a.buffer)).setUint32(s,f,!0),u.getReturnStatus()}catch(g){return u.tryCatch.setError(g),u.setLastError(10)}}function fe(e,r,t,n){var o;if(t=null!=t?t:0,t>>>=0,r instanceof ArrayBuffer||N.isSharedArrayBuffer(r)){if(!(s=N.getArrayBufferPointer(r,!1).address))throw new Error("Unknown ArrayBuffer address");if("number"==typeof n&&-1!==n&&4294967295!==n||(n=r.byteLength-t),0===(n>>>=0))return r;o=new Uint8Array(r,t,n);var i=new Uint8Array(a.buffer);return e?i.set(o,s):o.set(i.subarray(s,s+n)),r}if(ArrayBuffer.isView(r)){var s,f=N.getViewPointer(r,!1),u=f.view;if(!(s=f.address))throw new Error("Unknown ArrayBuffer address");if("number"==typeof n&&-1!==n&&4294967295!==n||(n=u.byteLength-t),0===(n>>>=0))return u;o=new Uint8Array(u.buffer,u.byteOffset+t,n);i=new Uint8Array(a.buffer);return e?i.set(o,s):o.set(i.subarray(s,s+n)),u}throw new TypeError("emnapiSyncMemory expect ArrayBuffer or ArrayBufferView as first parameter")}function ue(e){var r,t=e instanceof ArrayBuffer,n=e instanceof DataView,a=ArrayBuffer.isView(e)&&!n;if(!(t||a||n||N.isSharedArrayBuffer(e)))throw new TypeError("emnapiGetMemoryAddress expect ArrayBuffer or ArrayBufferView as first parameter");return{address:(r=t?N.getArrayBufferPointer(e,!1):N.getViewPointer(e,!1)).address,ownership:r.ownership,runtimeAllocated:r.runtimeAllocated}}function ce(e,r){if(null!=r&&!N.isSharedArrayBuffer(r))throw new TypeError("Expected a SharedArrayBuffer");if(!J.registry)throw new Error("FinalizationRegistry is not supported in this environment");e>>>=0;var t=J.readMeta(e),n=t.external_data;if(n>>>=0,null==r)r=new SharedArrayBuffer(t.byte_length),new Uint8Array(r).set(new Uint8Array(a.buffer,n,t.byte_length));else if(J.handleTable.has(r))return r;return Atomics.add(new Int32Array(a.buffer,e,1),0,1),N.table.has(r)||n&&N.table.set(r,{address:n,ownership:1,runtimeAllocated:0}),J.handleTable.set(r,e),J.registry.register(r,e),r}var le=Object.freeze({__proto__:null,$emnapiAcquireExternalSharedArrayBuffer:ce,$emnapiGetMemoryAddress:ue,$emnapiSyncMemory:fe,emnapi_acquire_external_sharedarraybuffer:function(e){e>>>=0,Atomics.add(new Int32Array(a.buffer,e,1),0,1)},emnapi_create_memory_view:se,emnapi_get_external_sharedarraybuffer_handle:function(e,r,t){if(!e)return 1;var n=d.envStore.get(e);if(n.checkGCAccess(),!n.tryCatch.isEmpty())return n.setLastError(10);if(!n.canCallIntoJs())return n.setLastError(n.moduleApiVersion>=10?23:10);n.clearLastError();try{if(!r)return n.setLastError(1);if(!t)return n.setLastError(1);t>>>=0;var o=d.handleStore.get(r).value;if(!N.isSharedArrayBuffer(o))return n.setLastError(1);var i=J.handleTable.get(o);if(void 0===i)return n.setLastError(1);var s=new DataView(a.buffer);return(s.buffer===a.buffer?s:s=new DataView(a.buffer)).setUint32(t,i,!0),n.getReturnStatus()}catch(e){return n.tryCatch.setError(e),n.setLastError(10)}},emnapi_get_memory_address:function(e,r,t,n,o){var i,s,f,u;if(!e)return 1;var c=d.envStore.get(e);if(c.checkGCAccess(),!c.tryCatch.isEmpty())return c.setLastError(10);if(!c.canCallIntoJs())return c.setLastError(c.moduleApiVersion>=10?23:10);c.clearLastError();try{if(!r)return c.setLastError(1);if(!t&&!n&&!o)return c.setLastError(1);i=(u=ue(c.ctx.handleStore.get(r).value)).address;var l=new DataView(a.buffer),v=function(){return l.buffer===a.buffer?l:l=new DataView(a.buffer)};return t&&(t>>>=0,v().setUint32(t,i,!0)),n&&(n>>>=0,f=u.ownership,v().setInt32(n,f,!0)),o&&(o>>>=0,s=u.runtimeAllocated,v().setInt8(o,s,!0)),c.getReturnStatus()}catch(e){return c.tryCatch.setError(e),c.setLastError(10)}},emnapi_get_runtime_version:function(e,r){if(!e)return 1;var t,n=d.envStore.get(e);if(!r)return n.setLastError(1);try{t=d.getRuntimeVersions().version}catch(e){return n.setLastError(9)}var o=t.split(".").map(function(e){return Number(e)});r>>>=0;var i=new DataView(a.buffer),s=function(){return i.buffer===a.buffer?i:i=new DataView(a.buffer)};return s().setUint32(r,o[0],!0),s().setUint32(r+4,o[1],!0),s().setUint32(r+8,o[2],!0),n.clearLastError()},emnapi_is_node_binding_available:function(){return v?1:0},emnapi_is_support_bigint:function(){return d.feature.supportBigInt?1:0},emnapi_is_support_weakref:function(){return d.feature.supportFinalizer?1:0},emnapi_release_external_sharedarraybuffer:function(e){e>>>=0,J.release(e)},emnapi_sync_memory:function(e,r,t,n,o){var i;if(!e)return 1;var s=d.envStore.get(e);if(s.checkGCAccess(),!s.tryCatch.isEmpty())return s.setLastError(10);if(!s.canCallIntoJs())return s.setLastError(s.moduleApiVersion>=10?23:10);s.clearLastError();try{if(!t)return s.setLastError(1);t>>>=0,n>>>=0,o>>>=0;var f=new DataView(a.buffer),u=function(){return f.buffer===a.buffer?f:f=new DataView(a.buffer)},c=u().getUint32(t,!0),l=s.ctx.handleStore.get(c);if(!(l.isArrayBuffer()||l.isTypedArray()||l.isDataView()||N.isSharedArrayBuffer(l.value)))return s.setLastError(1);var v=fe(Boolean(r),l.value,n,o);return l.value!==v&&(t>>>=0,i=s.ensureHandleId(v),u().setUint32(t,i,!0)),s.getReturnStatus()}catch(e){return s.tryCatch.setError(e),s.setLastError(10)}}});function de(e,r,t){e>>>=0,e>>>=0;var n=t?new SharedArrayBuffer(e):new ArrayBuffer(e);if(r){r>>>=0;var o=N.getArrayBufferPointer(n,!0).address,i=new DataView(a.buffer);(i.buffer===a.buffer?i:i=new DataView(a.buffer)).setUint32(r,o,!0)}return n}var ve=Object.freeze({__proto__:null,napi_create_array:function(e,r){if(!e)return 1;var t=d.envStore.get(e);if(t.checkGCAccess(),!r)return t.setLastError(1);r>>>=0;var n=d.addToCurrentScope([]).id,o=new DataView(a.buffer);return(o.buffer===a.buffer?o:o=new DataView(a.buffer)).setUint32(r,n,!0),t.clearLastError()},napi_create_array_with_length:function(e,r,t){if(!e)return 1;var n=d.envStore.get(e);if(n.checkGCAccess(),!t)return n.setLastError(1);r>>>=0,t>>>=0,r>>>=0;var o=d.addToCurrentScope(new Array(r)).id,i=new DataView(a.buffer);return(i.buffer===a.buffer?i:i=new DataView(a.buffer)).setUint32(t,o,!0),n.clearLastError()},napi_create_arraybuffer:function(e,r,t,n){var o;if(!e)return 1;var i=d.envStore.get(e);if(i.checkGCAccess(),!i.tryCatch.isEmpty())return i.setLastError(10);if(!i.canCallIntoJs())return i.setLastError(i.moduleApiVersion>=10?23:10);i.clearLastError();try{if(!n)return i.setLastError(1);n>>>=0;var s=de(r,t,!1);o=d.addToCurrentScope(s).id;var f=new DataView(a.buffer);return(f.buffer===a.buffer?f:f=new DataView(a.buffer)).setUint32(n,o,!0),i.getReturnStatus()}catch(e){return i.tryCatch.setError(e),i.setLastError(10)}},napi_create_buffer:function(e,r,t,n){var o,s,f;if(!e)return 1;var u=d.envStore.get(e);if(u.checkGCAccess(),!u.tryCatch.isEmpty())return u.setLastError(10);if(!u.canCallIntoJs())return u.setLastError(u.moduleApiVersion>=10?23:10);u.clearLastError();try{if(!n)return u.setLastError(1);var c=d.feature.Buffer;if(!c)throw d.createNotSupportBufferError("napi_create_buffer","");n>>>=0;var l=void 0;r>>>=0,r>>>=0;var v=new DataView(a.buffer),p=function(){return v.buffer===a.buffer?v:v=new DataView(a.buffer)};if(t&&0!==r){if(!(f=i(r)))throw new Error("Out of memory");f>>>=0,new Uint8Array(a.buffer).subarray(f,f+r).fill(0);var y=N.getBufferFrom()(a.buffer,f,r),g={Ctor:c,address:f,length:r,ownership:N.registry?0:1,runtimeAllocated:1};N.wasmMemoryViewTable.set(y,g),null===(o=N.registry)||void 0===o||o.register(g,f),s=d.addToCurrentScope(y).id,p().setUint32(n,s,!0),t>>>=0,p().setUint32(t,f,!0)}else l=c.alloc(r),s=d.addToCurrentScope(l).id,p().setUint32(n,s,!0);return u.getReturnStatus()}catch(e){return u.tryCatch.setError(e),u.setLastError(10)}},napi_create_buffer_copy:function(e,r,t,n,o){var i;if(!e)return 1;var s=d.envStore.get(e);if(s.checkGCAccess(),!s.tryCatch.isEmpty())return s.setLastError(10);if(!s.canCallIntoJs())return s.setLastError(s.moduleApiVersion>=10?23:10);s.clearLastError();try{if(!o)return s.setLastError(1);var f=d.feature.Buffer;if(!f)throw d.createNotSupportBufferError("napi_create_buffer_copy","");var u=de(r,n,!1),c=f.from(u);t>>>=0,r>>>=0,c.set(new Uint8Array(a.buffer).subarray(t,t+r)),i=d.addToCurrentScope(c).id,o>>>=0;var l=new DataView(a.buffer);return(l.buffer===a.buffer?l:l=new DataView(a.buffer)).setUint32(o,i,!0),s.getReturnStatus()}catch(e){return s.tryCatch.setError(e),s.setLastError(10)}},napi_create_dataview:function(e,r,t,n,o){if(!e)return 1;var i=d.envStore.get(e);if(i.checkGCAccess(),!i.tryCatch.isEmpty())return i.setLastError(10);if(!i.canCallIntoJs())return i.setLastError(i.moduleApiVersion>=10?23:10);i.clearLastError();try{if(!t)return i.setLastError(1);if(!o)return i.setLastError(1);r>>>=0,n>>>=0,r>>>=0,n>>>=0;var s=d.handleStore.get(t).value;return s instanceof ArrayBuffer||N.isSharedArrayBuffer(s)?function(e){if(r+n>e.byteLength){var t=new RangeError("byte_offset + byte_length should be less than or equal to the size in bytes of the array passed in");throw t.code="ERR_NAPI_INVALID_DATAVIEW_ARGS",t}var s=new DataView(e,n,r);e===a.buffer&&(N.wasmMemoryViewTable.has(s)||N.wasmMemoryViewTable.set(s,{Ctor:DataView,address:n,length:r,ownership:1,runtimeAllocated:0})),o>>>=0;var f=d.addToCurrentScope(s).id,u=new DataView(a.buffer);return(u.buffer===a.buffer?u:u=new DataView(a.buffer)).setUint32(o,f,!0),i.getReturnStatus()}(s):i.setLastError(1)}catch(e){return i.tryCatch.setError(e),i.setLastError(10)}},napi_create_date:function(e,r,t){var n;if(!e)return 1;var o=d.envStore.get(e);if(o.checkGCAccess(),!o.tryCatch.isEmpty())return o.setLastError(10);if(!o.canCallIntoJs())return o.setLastError(o.moduleApiVersion>=10?23:10);o.clearLastError();try{if(!t)return o.setLastError(1);t>>>=0,n=d.addToCurrentScope(new Date(r)).id;var i=new DataView(a.buffer);return(i.buffer===a.buffer?i:i=new DataView(a.buffer)).setUint32(t,n,!0),o.getReturnStatus()}catch(e){return o.tryCatch.setError(e),o.setLastError(10)}},napi_create_external:function(e,r,t,n,o){var i;if(!e)return 1;var s=d.envStore.get(e);if(s.checkGCAccess(),!s.tryCatch.isEmpty())return s.setLastError(10);if(!s.canCallIntoJs())return s.setLastError(s.moduleApiVersion>=10?23:10);s.clearLastError();try{if(!o)return s.setLastError(1);if(!d.feature.supportFinalizer&&t)throw d.createNotSupportWeakRefError("napi_create_external",'Parameter "finalize_cb" must be 0(NULL)');var f=d.getCurrentScope().addExternal(r);t&&d.createReferenceWithFinalizer(s,f.id,0,0,t,r,n),o>>>=0,i=f.id;var u=new DataView(a.buffer);return(u.buffer===a.buffer?u:u=new DataView(a.buffer)).setUint32(o,i,!0),s.clearLastError()}catch(e){return s.tryCatch.setError(e),s.setLastError(10)}},napi_create_external_arraybuffer:function(e,r,t,n,o,i){var s;if(!e)return 1;var f=d.envStore.get(e);if(f.checkGCAccess(),!f.tryCatch.isEmpty())return f.setLastError(10);if(!f.canCallIntoJs())return f.setLastError(f.moduleApiVersion>=10?23:10);f.clearLastError();try{if(!i)return f.setLastError(1);if(t>>>=0,i>>>=0,t>>>=0,(r>>>=0)||(t=0),r+t>a.buffer.byteLength)throw new RangeError("Memory out of range");if(!d.feature.supportFinalizer&&n)throw d.createNotSupportWeakRefError("napi_create_external_arraybuffer",'Parameter "finalize_cb" must be 0(NULL)');var u=new ArrayBuffer(t);if(0===t)try{(new(0,d.feature.MessageChannel)).port1.postMessage(u,[u])}catch(e){}else new Uint8Array(u).set(new Uint8Array(a.buffer).subarray(r,r+t)),N.table.set(u,{address:r,ownership:1,runtimeAllocated:0});var c=d.addToCurrentScope(u);if(n){var l=oe(e,c.id,r,n,o,0);if(10===l){var v=f.tryCatch.extractException();throw f.clearLastError(),v}if(0!==l)return f.setLastError(l)}s=c.id;var p=new DataView(a.buffer);return(p.buffer===a.buffer?p:p=new DataView(a.buffer)).setUint32(i,s,!0),f.getReturnStatus()}catch(v){return f.tryCatch.setError(v),f.setLastError(10)}},napi_create_external_buffer:function(e,r,t,n,a,o){return se(e,-2,t,r,n,a,o)},napi_create_object:function(e,r){if(!e)return 1;var t=d.envStore.get(e);if(t.checkGCAccess(),!r)return t.setLastError(1);r>>>=0;var n=d.addToCurrentScope({}).id,o=new DataView(a.buffer);return(o.buffer===a.buffer?o:o=new DataView(a.buffer)).setUint32(r,n,!0),t.clearLastError()},napi_create_symbol:function(e,r,t){if(!e)return 1;var n=d.envStore.get(e);if(n.checkGCAccess(),!t)return n.setLastError(1);t>>>=0;var o=new DataView(a.buffer),i=function(){return o.buffer===a.buffer?o:o=new DataView(a.buffer)};if(r){var s=d.handleStore.get(r).value;if("string"!=typeof s)return n.setLastError(3);var f=d.addToCurrentScope(Symbol(s)).id;i().setUint32(t,f,!0)}else{var u=d.addToCurrentScope(Symbol()).id;i().setUint32(t,u,!0)}return n.clearLastError()},napi_create_typedarray:function(e,r,t,n,o,i){var s;if(!e)return 1;var f=d.envStore.get(e);if(f.checkGCAccess(),!f.tryCatch.isEmpty())return f.setLastError(10);if(!f.canCallIntoJs())return f.setLastError(f.moduleApiVersion>=10?23:10);f.clearLastError();try{if(!n)return f.setLastError(1);if(!i)return f.setLastError(1);var u=d.handleStore.get(n).value;o>>>=0,t>>>=0;var c=function(e,r,t,n,o,f){var u,c;if((o>>>=0,f>>>=0,t>1)&&o%t!==0)return(c=new RangeError("start offset of ".concat(null!==(u=r.name)&&void 0!==u?u:""," should be a multiple of ").concat(t))).code="ERR_NAPI_INVALID_TYPEDARRAY_ALIGNMENT",e.tryCatch.setError(c),e.setLastError(9);if(f*t+o>n.byteLength)return(c=new RangeError("Invalid typed array length")).code="ERR_NAPI_INVALID_TYPEDARRAY_LENGTH",e.tryCatch.setError(c),e.setLastError(9);var l=new r(n,o,f);n===a.buffer&&(N.wasmMemoryViewTable.has(l)||N.wasmMemoryViewTable.set(l,{Ctor:r,address:o,length:f,ownership:1,runtimeAllocated:0})),i>>>=0,s=d.addToCurrentScope(l).id;var v=new DataView(a.buffer);return(v.buffer===a.buffer?v:v=new DataView(a.buffer)).setUint32(i,s,!0),e.getReturnStatus()};if(!(u instanceof ArrayBuffer||N.isSharedArrayBuffer(u)))return f.setLastError(1);switch(r){case 0:return c(f,Int8Array,1,u,o,t);case 1:return c(f,Uint8Array,1,u,o,t);case 2:return c(f,Uint8ClampedArray,1,u,o,t);case 3:return c(f,Int16Array,2,u,o,t);case 4:return c(f,Uint16Array,2,u,o,t);case 5:return c(f,Int32Array,4,u,o,t);case 6:return c(f,Uint32Array,4,u,o,t);case 7:return c(f,Float32Array,4,u,o,t);case 8:return c(f,Float64Array,8,u,o,t);case 9:return c(f,BigInt64Array,8,u,o,t);case 10:return c(f,BigUint64Array,8,u,o,t);case 11:return"function"!=typeof Float16Array?f.setLastError(1):c(f,Float16Array,2,u,o,t);default:return f.setLastError(1)}}catch(e){return f.tryCatch.setError(e),f.setLastError(10)}},node_api_create_buffer_from_arraybuffer:function(e,r,t,n,o){var i;if(!e)return 1;var s=d.envStore.get(e);if(s.checkGCAccess(),!s.tryCatch.isEmpty())return s.setLastError(10);if(!s.canCallIntoJs())return s.setLastError(s.moduleApiVersion>=10?23:10);s.clearLastError();try{if(!r)return s.setLastError(1);if(!o)return s.setLastError(1);t>>>=0,n>>>=0,t>>>=0,n>>>=0;var f=d.handleStore.get(r);if(!f.isArrayBuffer())return s.setLastError(1);var u=f.value;if(n+t>u.byteLength){var c=new RangeError("The byte offset + length is out of range");throw c.code="ERR_OUT_OF_RANGE",c}var l=d.feature.Buffer;if(!l)throw d.createNotSupportBufferError("node_api_create_buffer_from_arraybuffer","");var v=N.getBufferFrom()(u,t,n);u===a.buffer&&(N.wasmMemoryViewTable.has(v)||N.wasmMemoryViewTable.set(v,{Ctor:l,address:t,length:n,ownership:1,runtimeAllocated:0})),o>>>=0,i=d.addToCurrentScope(v).id;var p=new DataView(a.buffer);return(p.buffer===a.buffer?p:p=new DataView(a.buffer)).setUint32(o,i,!0),s.getReturnStatus()}catch(c){return s.tryCatch.setError(c),s.setLastError(10)}},node_api_create_external_sharedarraybuffer:function(e,r,t,n,o,i){var s;if(!e)return 1;var f=d.envStore.get(e);if(f.checkGCAccess(),!f.tryCatch.isEmpty())return f.setLastError(10);if(!f.canCallIntoJs())return f.setLastError(f.moduleApiVersion>=10?23:10);f.clearLastError();try{if(!i)return f.setLastError(1);if(t>>>=0,i>>>=0,t>>>=0,(r>>>=0)||(t=0),r+t>a.buffer.byteLength)throw new RangeError("Memory out of range");if(!J.registry&&n)throw d.createNotSupportWeakRefError("node_api_create_external_sharedarraybuffer",'Parameter "finalize_cb" must be 0(NULL)');var u=new SharedArrayBuffer(t);if(0!==t)new Uint8Array(u).set(new Uint8Array(a.buffer).subarray(r,r+t)),N.table.set(u,{address:r,ownership:1,runtimeAllocated:0});if(s=d.addToCurrentScope(u).id,n){n>>>=0,o>>>=0;var c=J.allocMeta(r,t,n,r,o);J.handleTable.set(u,c),J.registry.register(u,c)}var l=new DataView(a.buffer);return(l.buffer===a.buffer?l:l=new DataView(a.buffer)).setUint32(i,s,!0),f.getReturnStatus()}catch(e){return f.tryCatch.setError(e),f.setLastError(10)}},node_api_create_object_with_properties:function(e,r,t,n,o,i){if(!e)return 1;var s=d.envStore.get(e);if(s.checkGCAccess(),!i)return s.setLastError(1);if(o>>>=0,(o>>>=0)>0){if(!t)return s.setLastError(1);if(!n)return s.setLastError(1)}var f=r?d.handleStore.get(r).value:null,u={};t>>>=0,n>>>=0;for(var c,l=new DataView(a.buffer),v=function(){return l.buffer===a.buffer?l:l=new DataView(a.buffer)},p=0;p>>=0,v().setUint32(i,g,!0),s.clearLastError()},node_api_create_sharedarraybuffer:function(e,r,t,n){var o;if(!e)return 1;var i=d.envStore.get(e);if(i.checkGCAccess(),!i.tryCatch.isEmpty())return i.setLastError(10);if(!i.canCallIntoJs())return i.setLastError(i.moduleApiVersion>=10?23:10);i.clearLastError();try{if(!n)return i.setLastError(1);n>>>=0;var s=de(r,t,!0);o=d.addToCurrentScope(s).id;var f=new DataView(a.buffer);return(f.buffer===a.buffer?f:f=new DataView(a.buffer)).setUint32(n,o,!0),i.getReturnStatus()}catch(e){return i.tryCatch.setError(e),i.setLastError(10)}},node_api_symbol_for:function(e,r,t,n){if(!e)return 1;var o=d.envStore.get(e);if(o.checkGCAccess(),!n)return o.setLastError(1);r>>>=0,n>>>=0;var i=-1===(t>>>=0)||4294967295===t,s=t>>>0;if(0!==t&&!r)return o.setLastError(1);if(!(i||s<=2147483647))return o.setLastError(1);var f=H.UTF8ToString(r,t),u=d.addToCurrentScope(Symbol.for(f)).id,c=new DataView(a.buffer);return(c.buffer===a.buffer?c:c=new DataView(a.buffer)).setUint32(n,u,!0),o.clearLastError()}});var pe=Object.freeze({__proto__:null,napi_get_boolean:function(e,r,t){if(!e)return 1;var n=d.envStore.get(e);if(n.checkGCAccess(),!t)return n.setLastError(1);t>>>=0;var o=0===r?3:4,i=new DataView(a.buffer);return(i.buffer===a.buffer?i:i=new DataView(a.buffer)).setUint32(t,o,!0),n.clearLastError()},napi_get_global:function(e,r){if(!e)return 1;var t=d.envStore.get(e);if(t.checkGCAccess(),!r)return t.setLastError(1);r>>>=0;var n=new DataView(a.buffer);return(n.buffer===a.buffer?n:n=new DataView(a.buffer)).setUint32(r,5,!0),t.clearLastError()},napi_get_null:function(e,r){if(!e)return 1;var t=d.envStore.get(e);if(t.checkGCAccess(),!r)return t.setLastError(1);r>>>=0;var n=new DataView(a.buffer);return(n.buffer===a.buffer?n:n=new DataView(a.buffer)).setUint32(r,2,!0),t.clearLastError()},napi_get_undefined:function(e,r){if(!e)return 1;var t=d.envStore.get(e);if(t.checkGCAccess(),!r)return t.setLastError(1);r>>>=0;var n=new DataView(a.buffer);return(n.buffer===a.buffer?n:n=new DataView(a.buffer)).setUint32(r,1,!0),t.clearLastError()}});var ye=Object.freeze({__proto__:null,napi_get_instance_data:function(e,r){if(!e)return 1;var t=d.envStore.get(e);if(!r)return t.setLastError(1);r>>>=0;var n=t.getInstanceData(),o=new DataView(a.buffer);return(o.buffer===a.buffer?o:o=new DataView(a.buffer)).setUint32(r,n,!0),t.clearLastError()},napi_set_instance_data:function(e,r,t,n){if(!e)return 1;var a=d.envStore.get(e);return r>>>=0,t>>>=0,n>>>=0,a.setInstanceData(r,t,n),a.clearLastError()}});var ge=Object.freeze({__proto__:null,_emnapi_get_last_error_info:function(e,r,t,n){r>>>=0,t>>>=0,n>>>=0;var o=d.envStore.get(e).lastError,i=o.errorCode,s=o.engineErrorCode>>>0,f=o.engineReserved;f>>>=0;var u=new DataView(a.buffer),c=function(){return u.buffer===a.buffer?u:u=new DataView(a.buffer)};c().setInt32(r,i,!0),c().setUint32(t,s,!0),c().setUint32(n,f,!0)},napi_create_error:function(e,r,t,n){if(!e)return 1;var o=d.envStore.get(e);if(o.checkGCAccess(),!t)return o.setLastError(1);if(!n)return o.setLastError(1);var i=d.handleStore.get(t).value;if("string"!=typeof i)return o.setLastError(3);var s=new Error(i);if(r){var f=d.handleStore.get(r).value;if("string"!=typeof f)return o.setLastError(3);s.code=f}n>>>=0;var u=d.addToCurrentScope(s).id,c=new DataView(a.buffer);return(c.buffer===a.buffer?c:c=new DataView(a.buffer)).setUint32(n,u,!0),o.clearLastError()},napi_create_range_error:function(e,r,t,n){if(!e)return 1;var o=d.envStore.get(e);if(o.checkGCAccess(),!t)return o.setLastError(1);if(!n)return o.setLastError(1);var i=d.handleStore.get(t).value;if("string"!=typeof i)return o.setLastError(3);var s=new RangeError(i);if(r){var f=d.handleStore.get(r).value;if("string"!=typeof f)return o.setLastError(3);s.code=f}n>>>=0;var u=d.addToCurrentScope(s).id,c=new DataView(a.buffer);return(c.buffer===a.buffer?c:c=new DataView(a.buffer)).setUint32(n,u,!0),o.clearLastError()},napi_create_type_error:function(e,r,t,n){if(!e)return 1;var o=d.envStore.get(e);if(o.checkGCAccess(),!t)return o.setLastError(1);if(!n)return o.setLastError(1);var i=d.handleStore.get(t).value;if("string"!=typeof i)return o.setLastError(3);var s=new TypeError(i);if(r){var f=d.handleStore.get(r).value;if("string"!=typeof f)return o.setLastError(3);s.code=f}n>>>=0;var u=d.addToCurrentScope(s).id,c=new DataView(a.buffer);return(c.buffer===a.buffer?c:c=new DataView(a.buffer)).setUint32(n,u,!0),o.clearLastError()},napi_fatal_error:function(e,r,t,n){e>>>=0,r>>>=0,t>>>=0,n>>>=0;var a=H.UTF8ToString(e,r),o=H.UTF8ToString(t,n);v?v.napi.fatalError(a,o):l("FATAL ERROR: "+a+" "+o)},napi_fatal_exception:function(e,r){if(!e)return 1;var t=d.envStore.get(e);if(t.checkGCAccess(),!t.tryCatch.isEmpty())return t.setLastError(10);if(!t.canCallIntoJs())return t.setLastError(t.moduleApiVersion>=10?23:10);t.clearLastError();try{if(!r)return t.setLastError(1);var n=t.ctx.handleStore.get(r);try{t.triggerFatalException(n.value)}catch(e){return t.setLastError(9)}return t.clearLastError()}catch(r){return t.tryCatch.setError(r),t.setLastError(10)}},napi_get_and_clear_last_exception:function(e,r){if(!e)return 1;var t=d.envStore.get(e);if(t.checkGCAccess(),!r)return t.setLastError(1);r>>>=0;var n=new DataView(a.buffer),o=function(){return n.buffer===a.buffer?n:n=new DataView(a.buffer)};if(!t.tryCatch.hasCaught())return o().setUint32(r,1,!0),t.clearLastError();var i=t.tryCatch.exception(),s=t.ensureHandleId(i);return o().setUint32(r,s,!0),t.tryCatch.reset(),t.clearLastError()},napi_is_exception_pending:function(e,r){if(!e)return 1;var t=d.envStore.get(e);if(t.checkGCAccess(),!r)return t.setLastError(1);var n=t.tryCatch.hasCaught();r>>>=0;var o=new DataView(a.buffer);return(o.buffer===a.buffer?o:o=new DataView(a.buffer)).setInt8(r,n?1:0,!0),t.clearLastError()},napi_throw:function(e,r){if(!e)return 1;var t=d.envStore.get(e);if(t.checkGCAccess(),!t.tryCatch.isEmpty())return t.setLastError(10);if(!t.canCallIntoJs())return t.setLastError(t.moduleApiVersion>=10?23:10);t.clearLastError();try{return r?(t.tryCatch.setError(d.handleStore.get(r).value),t.clearLastError()):t.setLastError(1)}catch(e){return t.tryCatch.setError(e),t.setLastError(10)}},napi_throw_error:function(e,r,t){if(!e)return 1;var n=d.envStore.get(e);if(n.checkGCAccess(),!n.tryCatch.isEmpty())return n.setLastError(10);if(!n.canCallIntoJs())return n.setLastError(n.moduleApiVersion>=10?23:10);n.clearLastError();try{if(!t)return n.setLastError(1);r>>>=0,t>>>=0;var a=new Error(H.UTF8ToString(t,-1));return r&&(a.code=H.UTF8ToString(r,-1)),n.tryCatch.setError(a),n.clearLastError()}catch(e){return n.tryCatch.setError(e),n.setLastError(10)}},napi_throw_range_error:function(e,r,t){if(!e)return 1;var n=d.envStore.get(e);if(n.checkGCAccess(),!n.tryCatch.isEmpty())return n.setLastError(10);if(!n.canCallIntoJs())return n.setLastError(n.moduleApiVersion>=10?23:10);n.clearLastError();try{if(!t)return n.setLastError(1);r>>>=0,t>>>=0;var a=new RangeError(H.UTF8ToString(t,-1));return r&&(a.code=H.UTF8ToString(r,-1)),n.tryCatch.setError(a),n.clearLastError()}catch(e){return n.tryCatch.setError(e),n.setLastError(10)}},napi_throw_type_error:function(e,r,t){if(!e)return 1;var n=d.envStore.get(e);if(n.checkGCAccess(),!n.tryCatch.isEmpty())return n.setLastError(10);if(!n.canCallIntoJs())return n.setLastError(n.moduleApiVersion>=10?23:10);n.clearLastError();try{if(!t)return n.setLastError(1);r>>>=0,t>>>=0;var a=new TypeError(H.UTF8ToString(t,-1));return r&&(a.code=H.UTF8ToString(r,-1)),n.tryCatch.setError(a),n.clearLastError()}catch(e){return n.tryCatch.setError(e),n.setLastError(10)}},node_api_create_syntax_error:function(e,r,t,n){if(!e)return 1;var o=d.envStore.get(e);if(o.checkGCAccess(),!t)return o.setLastError(1);if(!n)return o.setLastError(1);var i=d.handleStore.get(t).value;if("string"!=typeof i)return o.setLastError(3);var s=new SyntaxError(i);if(r){var f=d.handleStore.get(r).value;if("string"!=typeof f)return o.setLastError(3);s.code=f}n>>>=0;var u=d.addToCurrentScope(s).id,c=new DataView(a.buffer);return(c.buffer===a.buffer?c:c=new DataView(a.buffer)).setUint32(n,u,!0),o.clearLastError()},node_api_throw_syntax_error:function(e,r,t){if(!e)return 1;var n=d.envStore.get(e);if(n.checkGCAccess(),!n.tryCatch.isEmpty())return n.setLastError(10);if(!n.canCallIntoJs())return n.setLastError(n.moduleApiVersion>=10?23:10);n.clearLastError();try{if(!t)return n.setLastError(1);r>>>=0,t>>>=0;var a=new SyntaxError(H.UTF8ToString(t,-1));return r&&(a.code=H.UTF8ToString(r,-1)),n.tryCatch.setError(a),n.clearLastError()}catch(e){return n.tryCatch.setError(e),n.setLastError(10)}}});function we(e,r,t,n,o,i){t>>>=0;var s=d.envStore.get(e),f=re(s,r,t,n,o);if(0!==f.status)return s.setLastError(f.status);var u=f.f;i>>>=0;var c=d.addToCurrentScope(u).id,l=new DataView(a.buffer);return(l.buffer===a.buffer?l:l=new DataView(a.buffer)).setUint32(i,c,!0),s.getReturnStatus()}var be=Object.freeze({__proto__:null,_emnapi_create_function:we,napi_call_function:function(e,r,t,n,o,i){var s,f=0;if(!e)return 1;var u=d.envStore.get(e);if(u.checkGCAccess(),!u.tryCatch.isEmpty())return u.setLastError(10);if(!u.canCallIntoJs())return u.setLastError(u.moduleApiVersion>=10?23:10);u.clearLastError();try{if(!r)return u.setLastError(1);if(n>>>=0,o>>>=0,i>>>=0,(n>>>=0)>0&&!o)return u.setLastError(1);var c=d.handleStore.get(r).value;if(!t)return u.setLastError(1);var l=d.handleStore.get(t).value;if("function"!=typeof l)return u.setLastError(1);for(var v=[],p=new DataView(a.buffer),y=function(){return p.buffer===a.buffer?p:p=new DataView(a.buffer)};f=10?23:10);i.clearLastError();try{return o&&n?we(e,r,t,n,a,o):i.setLastError(1)}catch(e){return i.tryCatch.setError(e),i.setLastError(10)}},napi_get_cb_info:function(e,r,t,n,o,i){if(!e)return 1;var s=d.envStore.get(e);if(!r)return s.setLastError(1);var f=d.scopeStore.get(r).callbackInfo;t>>>=0,n>>>=0;var u=new DataView(a.buffer),c=function(){return u.buffer===a.buffer?u:u=new DataView(a.buffer)};if(n){if(!t)return s.setLastError(1);var l=c().getUint32(t,!0);l>>>=0;for(var v=f.args.length,p=l>>=0;var w=s.ensureHandleId(f.thiz);c().setUint32(o,w,!0)}return i&&(i>>>=0,c().setUint32(i,f.data,!0)),s.clearLastError()},napi_get_new_target:function(e,r,t){if(!e)return 1;var n=d.envStore.get(e);if(n.checkGCAccess(),!r)return n.setLastError(1);if(!t)return n.setLastError(1);t>>>=0;var o=d.scopeStore.get(r).callbackInfo,i=o.thiz,s=o.fn,f=null==i||null==i.constructor?0:i instanceof s?n.ensureHandleId(i.constructor):0,u=new DataView(a.buffer);return(u.buffer===a.buffer?u:u=new DataView(a.buffer)).setUint32(t,f,!0),n.clearLastError()},napi_new_instance:function(e,r,t,n,o){var i,s;if(!e)return 1;var f=d.envStore.get(e);if(f.checkGCAccess(),!f.tryCatch.isEmpty())return f.setLastError(10);if(!f.canCallIntoJs())return f.setLastError(f.moduleApiVersion>=10?23:10);f.clearLastError();try{if(!r)return f.setLastError(1);if(t>>>=0,n>>>=0,o>>>=0,(t>>>=0)>0&&!n)return f.setLastError(1);if(!o)return f.setLastError(1);var u=d.handleStore.get(r).value;if("function"!=typeof u)return f.setLastError(1);var c=void 0,l=new DataView(a.buffer),v=function(){return l.buffer===a.buffer?l:l=new DataView(a.buffer)};if(d.feature.supportReflect){var p=Array(t);for(i=0;i>>=0,t>>>=0,d.addCleanupHook(n,r,t),0):n.setLastError(1)},napi_close_escapable_handle_scope:function(e,r){if(!e)return 1;var t=d.envStore.get(e);return t.checkGCAccess(),r?0===t.openHandleScopes?13:(d.closeScope(t),t.clearLastError()):t.setLastError(1)},napi_close_handle_scope:function(e,r){if(!e)return 1;var t=d.envStore.get(e);return t.checkGCAccess(),r?0===t.openHandleScopes?13:(d.closeScope(t),t.clearLastError()):t.setLastError(1)},napi_create_reference:function(e,r,t,n){if(!e)return 1;var o=d.envStore.get(e);if(o.checkGCAccess(),!r)return o.setLastError(1);if(!n)return o.setLastError(1);var i=d.handleStore.get(r);if(o.moduleApiVersion<10&&!(i.isObject()||i.isFunction()||i.isSymbol()))return o.setLastError(1);var s=d.createReference(o,i.id,t>>>0,1);n>>>=0;var f=new DataView(a.buffer);return(f.buffer===a.buffer?f:f=new DataView(a.buffer)).setUint32(n,s.id,!0),o.clearLastError()},napi_delete_reference:function(e,r){if(!e)return 1;var t=d.envStore.get(e);return r?(d.refStore.get(r).dispose(),t.clearLastError()):t.setLastError(1)},napi_escape_handle:function(e,r,t,n){if(!e)return 1;var o=d.envStore.get(e);if(o.checkGCAccess(),!r)return o.setLastError(1);if(!t)return o.setLastError(1);if(!n)return o.setLastError(1);var i=d.scopeStore.get(r);if(!i.escapeCalled()){t>>>=0,n>>>=0;var s=i.escape(t),f=s?s.id:0,u=new DataView(a.buffer);return(u.buffer===a.buffer?u:u=new DataView(a.buffer)).setUint32(n,f,!0),o.clearLastError()}return o.setLastError(12)},napi_get_reference_value:function(e,r,t){if(!e)return 1;var n=d.envStore.get(e);if(n.checkGCAccess(),!r)return n.setLastError(1);if(!t)return n.setLastError(1);var o=d.refStore.get(r).get(n);t>>>=0;var i=new DataView(a.buffer);return(i.buffer===a.buffer?i:i=new DataView(a.buffer)).setUint32(t,o,!0),n.clearLastError()},napi_open_escapable_handle_scope:function(e,r){if(!e)return 1;var t=d.envStore.get(e);if(t.checkGCAccess(),!r)return t.setLastError(1);var n=d.openScope(t);r>>>=0;var o=new DataView(a.buffer);return(o.buffer===a.buffer?o:o=new DataView(a.buffer)).setUint32(r,n.id,!0),t.clearLastError()},napi_open_handle_scope:function(e,r){if(!e)return 1;var t=d.envStore.get(e);if(t.checkGCAccess(),!r)return t.setLastError(1);var n=d.openScope(t);r>>>=0;var o=new DataView(a.buffer);return(o.buffer===a.buffer?o:o=new DataView(a.buffer)).setUint32(r,n.id,!0),t.clearLastError()},napi_reference_ref:function(e,r,t){if(!e)return 1;var n=d.envStore.get(e);if(n.checkGCAccess(),!r)return n.setLastError(1);var o=d.refStore.get(r).ref();if(t){t>>>=0;var i=new DataView(a.buffer);(i.buffer===a.buffer?i:i=new DataView(a.buffer)).setUint32(t,o,!0)}return n.clearLastError()},napi_reference_unref:function(e,r,t){if(!e)return 1;var n=d.envStore.get(e);if(n.checkGCAccess(),!r)return n.setLastError(1);var o=d.refStore.get(r);if(0===o.refcount())return n.setLastError(9);var i=o.unref();if(t){t>>>=0;var s=new DataView(a.buffer);(s.buffer===a.buffer?s:s=new DataView(a.buffer)).setUint32(t,i,!0)}return n.clearLastError()},napi_remove_env_cleanup_hook:function(e,r,t){if(!e)return 1;var n=d.envStore.get(e);return r?(r>>>=0,t>>>=0,d.removeCleanupHook(n,r,t),0):n.setLastError(1)}});var _e=Object.freeze({__proto__:null,_emnapi_get_filename:function(e,r,t){var n=d.envStore.get(e).filename;return r?H.stringToUTF8(n,r,t):H.lengthBytesUTF8(n)}});var Ee=Object.freeze({__proto__:null,napi_create_promise:function(e,r,t){var n,o;if(!e)return 1;var i=d.envStore.get(e);if(i.checkGCAccess(),!i.tryCatch.isEmpty())return i.setLastError(10);if(!i.canCallIntoJs())return i.setLastError(i.moduleApiVersion>=10?23:10);i.clearLastError();try{if(!r)return i.setLastError(1);if(!t)return i.setLastError(1);var s=new DataView(a.buffer),f=function(){return s.buffer===a.buffer?s:s=new DataView(a.buffer)},u=new Promise(function(e,t){var a=d.createDeferred({resolve:e,reject:t});n=a.id,r>>>=0,f().setUint32(r,n,!0)});return t>>>=0,o=d.addToCurrentScope(u).id,f().setUint32(t,o,!0),i.getReturnStatus()}catch(e){return i.tryCatch.setError(e),i.setLastError(10)}},napi_is_promise:function(e,r,t){if(!e)return 1;var n=d.envStore.get(e);if(n.checkGCAccess(),!r)return n.setLastError(1);if(!t)return n.setLastError(1);t>>>=0;var o=d.handleStore.get(r).isPromise()?1:0,i=new DataView(a.buffer);return(i.buffer===a.buffer?i:i=new DataView(a.buffer)).setInt8(t,o,!0),n.clearLastError()},napi_reject_deferred:function(e,r,t){if(!e)return 1;var n=d.envStore.get(e);if(n.checkGCAccess(),!n.tryCatch.isEmpty())return n.setLastError(10);if(!n.canCallIntoJs())return n.setLastError(n.moduleApiVersion>=10?23:10);n.clearLastError();try{return r&&t?(d.deferredStore.get(r).reject(d.handleStore.get(t).value),n.getReturnStatus()):n.setLastError(1)}catch(e){return n.tryCatch.setError(e),n.setLastError(10)}},napi_resolve_deferred:function(e,r,t){if(!e)return 1;var n=d.envStore.get(e);if(n.checkGCAccess(),!n.tryCatch.isEmpty())return n.setLastError(10);if(!n.canCallIntoJs())return n.setLastError(n.moduleApiVersion>=10?23:10);n.clearLastError();try{return r&&t?(d.deferredStore.get(r).resolve(d.handleStore.get(t).value),n.getReturnStatus()):n.setLastError(1)}catch(e){return n.tryCatch.setError(e),n.setLastError(10)}}});function Le(e,r,t,n,o,i){var s;if(!e)return 1;var f=d.envStore.get(e);if(f.checkGCAccess(),!f.tryCatch.isEmpty())return f.setLastError(10);if(!f.canCallIntoJs())return f.setLastError(f.moduleApiVersion>=10?23:10);f.clearLastError();try{if(!i)return f.setLastError(1);if(!r)return f.setLastError(1);var u=d.handleStore.get(r);if(null==u.value)throw new TypeError("Cannot convert undefined or null to object");var c=void 0;try{c=u.isObject()||u.isFunction()?u.value:Object(u.value)}catch(e){return f.setLastError(2)}if(0!==t&&1!==t)return f.setLastError(1);if(0!==o&&1!==o)return f.setLastError(1);var l=[],v=void 0,p=void 0,y=void 0,g=!0,w=/^(0|[1-9][0-9]*)$/;do{for(v=Object.getOwnPropertyNames(c),p=Object.getOwnPropertySymbols(c),y=0;y>>=0,s=d.addToCurrentScope(b).id;var S=new DataView(a.buffer);return(S.buffer===a.buffer?S:S=new DataView(a.buffer)).setUint32(i,s,!0),f.getReturnStatus()}catch(e){return f.tryCatch.setError(e),f.setLastError(10)}}var me=Object.freeze({__proto__:null,napi_define_properties:function(e,r,t,n){var o,i;if(!e)return 1;var s=d.envStore.get(e);if(s.checkGCAccess(),!s.tryCatch.isEmpty())return s.setLastError(10);if(!s.canCallIntoJs())return s.setLastError(s.moduleApiVersion>=10?23:10);s.clearLastError();try{if(n>>>=0,t>>>=0,(t>>>=0)>0&&!n)return s.setLastError(1);if(!r)return s.setLastError(1);var f=d.handleStore.get(r),u=f.value;if(!f.isObject()&&!f.isFunction())return s.setLastError(2);for(var c=void 0,l=new DataView(a.buffer),v=function(){return l.buffer===a.buffer?l:l=new DataView(a.buffer)},p=0;p>>=0;var E=v().getUint32(o+28,!0);if(y)c=H.UTF8ToString(y,-1);else{if(!g)return s.setLastError(4);if("string"!=typeof(c=d.handleStore.get(g).value)&&"symbol"!=typeof c)return s.setLastError(4)}te(s,u,c,w,b,h,_,i,E)}return s.getReturnStatus()}catch(e){return s.tryCatch.setError(e),s.setLastError(10)}},napi_delete_element:function(e,r,t,n){var o;if(!e)return 1;var i=d.envStore.get(e);if(i.checkGCAccess(),!i.tryCatch.isEmpty())return i.setLastError(10);if(!i.canCallIntoJs())return i.setLastError(i.moduleApiVersion>=10?23:10);i.clearLastError();try{if(!r)return i.setLastError(1);var s=d.handleStore.get(r);if(!s.isObject()&&!s.isFunction())return i.setLastError(2);if(d.feature.supportReflect)o=Reflect.deleteProperty(s.value,t>>>0);else try{o=delete s.value[t>>>0]}catch(e){o=!1}if(n){n>>>=0;var f=new DataView(a.buffer);(f.buffer===a.buffer?f:f=new DataView(a.buffer)).setInt8(n,o?1:0,!0)}return i.getReturnStatus()}catch(e){return i.tryCatch.setError(e),i.setLastError(10)}},napi_delete_property:function(e,r,t,n){var o;if(!e)return 1;var i=d.envStore.get(e);if(i.checkGCAccess(),!i.tryCatch.isEmpty())return i.setLastError(10);if(!i.canCallIntoJs())return i.setLastError(i.moduleApiVersion>=10?23:10);i.clearLastError();try{if(!t)return i.setLastError(1);if(!r)return i.setLastError(1);var s=d.handleStore.get(r);if(!s.isObject()&&!s.isFunction())return i.setLastError(2);var f=d.handleStore.get(t).value;if(d.feature.supportReflect)o=Reflect.deleteProperty(s.value,f);else try{o=delete s.value[f]}catch(e){o=!1}if(n){n>>>=0;var u=new DataView(a.buffer);(u.buffer===a.buffer?u:u=new DataView(a.buffer)).setInt8(n,o?1:0,!0)}return i.getReturnStatus()}catch(e){return i.tryCatch.setError(e),i.setLastError(10)}},napi_get_all_property_names:Le,napi_get_element:function(e,r,t,n){var o;if(!e)return 1;var i=d.envStore.get(e);if(i.checkGCAccess(),!i.tryCatch.isEmpty())return i.setLastError(10);if(!i.canCallIntoJs())return i.setLastError(i.moduleApiVersion>=10?23:10);i.clearLastError();try{if(!n)return i.setLastError(1);if(!r)return i.setLastError(1);var s=d.handleStore.get(r);if(null==s.value)throw new TypeError("Cannot convert undefined or null to object");var f=void 0;try{f=s.isObject()||s.isFunction()?s.value:Object(s.value)}catch(e){return i.setLastError(2)}n>>>=0,o=i.ensureHandleId(f[t>>>0]);var u=new DataView(a.buffer);return(u.buffer===a.buffer?u:u=new DataView(a.buffer)).setUint32(n,o,!0),i.getReturnStatus()}catch(e){return i.tryCatch.setError(e),i.setLastError(10)}},napi_get_named_property:function(e,r,t,n){var o;if(!e)return 1;var i=d.envStore.get(e);if(i.checkGCAccess(),!i.tryCatch.isEmpty())return i.setLastError(10);if(!i.canCallIntoJs())return i.setLastError(i.moduleApiVersion>=10?23:10);i.clearLastError();try{if(!n)return i.setLastError(1);if(!r)return i.setLastError(1);if(!t)return i.setLastError(1);var s=d.handleStore.get(r);if(null==s.value)throw new TypeError("Cannot convert undefined or null to object");var f=void 0;try{f=s.isObject()||s.isFunction()?s.value:Object(s.value)}catch(e){return i.setLastError(2)}t>>>=0,n>>>=0,o=i.ensureHandleId(f[H.UTF8ToString(t,-1)]);var u=new DataView(a.buffer);return(u.buffer===a.buffer?u:u=new DataView(a.buffer)).setUint32(n,o,!0),i.getReturnStatus()}catch(e){return i.tryCatch.setError(e),i.setLastError(10)}},napi_get_property:function(e,r,t,n){var o;if(!e)return 1;var i=d.envStore.get(e);if(i.checkGCAccess(),!i.tryCatch.isEmpty())return i.setLastError(10);if(!i.canCallIntoJs())return i.setLastError(i.moduleApiVersion>=10?23:10);i.clearLastError();try{if(!t)return i.setLastError(1);if(!n)return i.setLastError(1);if(!r)return i.setLastError(1);var s=d.handleStore.get(r);if(null==s.value)throw new TypeError("Cannot convert undefined or null to object");var f=void 0;try{f=s.isObject()||s.isFunction()?s.value:Object(s.value)}catch(e){return i.setLastError(2)}n>>>=0,o=i.ensureHandleId(f[d.handleStore.get(t).value]);var u=new DataView(a.buffer);return(u.buffer===a.buffer?u:u=new DataView(a.buffer)).setUint32(n,o,!0),i.getReturnStatus()}catch(e){return i.tryCatch.setError(e),i.setLastError(10)}},napi_get_property_names:function(e,r,t){return Le(e,r,0,18,1,t)},napi_has_element:function(e,r,t,n){var o;if(!e)return 1;var i=d.envStore.get(e);if(i.checkGCAccess(),!i.tryCatch.isEmpty())return i.setLastError(10);if(!i.canCallIntoJs())return i.setLastError(i.moduleApiVersion>=10?23:10);i.clearLastError();try{if(!n)return i.setLastError(1);if(!r)return i.setLastError(1);var s=d.handleStore.get(r);if(null==s.value)throw new TypeError("Cannot convert undefined or null to object");var f=void 0;try{f=s.isObject()||s.isFunction()?s.value:Object(s.value)}catch(e){return i.setLastError(2)}n>>>=0,o=t>>>0 in f?1:0;var u=new DataView(a.buffer);return(u.buffer===a.buffer?u:u=new DataView(a.buffer)).setInt8(n,o,!0),i.getReturnStatus()}catch(e){return i.tryCatch.setError(e),i.setLastError(10)}},napi_has_named_property:function(e,r,t,n){var o;if(!e)return 1;var i=d.envStore.get(e);if(i.checkGCAccess(),!i.tryCatch.isEmpty())return i.setLastError(10);if(!i.canCallIntoJs())return i.setLastError(i.moduleApiVersion>=10?23:10);i.clearLastError();try{if(!n)return i.setLastError(1);if(!r)return i.setLastError(1);if(!t)return i.setLastError(1);var s=d.handleStore.get(r);if(null==s.value)throw new TypeError("Cannot convert undefined or null to object");var f=void 0;try{f=s.isObject()||s.isFunction()?s.value:Object(s.value)}catch(e){return i.setLastError(2)}t>>>=0,n>>>=0,o=H.UTF8ToString(t,-1)in f;var u=new DataView(a.buffer);return(u.buffer===a.buffer?u:u=new DataView(a.buffer)).setInt8(n,o?1:0,!0),i.getReturnStatus()}catch(e){return i.tryCatch.setError(e),i.setLastError(10)}},napi_has_own_property:function(e,r,t,n){var o;if(!e)return 1;var i=d.envStore.get(e);if(i.checkGCAccess(),!i.tryCatch.isEmpty())return i.setLastError(10);if(!i.canCallIntoJs())return i.setLastError(i.moduleApiVersion>=10?23:10);i.clearLastError();try{if(!t)return i.setLastError(1);if(!n)return i.setLastError(1);if(!r)return i.setLastError(1);var s=d.handleStore.get(r);if(null==s.value)throw new TypeError("Cannot convert undefined or null to object");var f=void 0;try{f=s.isObject()||s.isFunction()?s.value:Object(s.value)}catch(e){return i.setLastError(2)}var u=d.handleStore.get(t).value;if("string"!=typeof u&&"symbol"!=typeof u)return i.setLastError(4);o=Object.prototype.hasOwnProperty.call(f,d.handleStore.get(t).value),n>>>=0;var c=new DataView(a.buffer);return(c.buffer===a.buffer?c:c=new DataView(a.buffer)).setInt8(n,o?1:0,!0),i.getReturnStatus()}catch(e){return i.tryCatch.setError(e),i.setLastError(10)}},napi_has_property:function(e,r,t,n){var o;if(!e)return 1;var i=d.envStore.get(e);if(i.checkGCAccess(),!i.tryCatch.isEmpty())return i.setLastError(10);if(!i.canCallIntoJs())return i.setLastError(i.moduleApiVersion>=10?23:10);i.clearLastError();try{if(!t)return i.setLastError(1);if(!n)return i.setLastError(1);if(!r)return i.setLastError(1);var s=d.handleStore.get(r);if(null==s.value)throw new TypeError("Cannot convert undefined or null to object");var f=void 0;try{f=s.isObject()||s.isFunction()?s.value:Object(s.value)}catch(e){return i.setLastError(2)}n>>>=0,o=d.handleStore.get(t).value in f?1:0;var u=new DataView(a.buffer);return(u.buffer===a.buffer?u:u=new DataView(a.buffer)).setInt8(n,o,!0),i.getReturnStatus()}catch(e){return i.tryCatch.setError(e),i.setLastError(10)}},napi_object_freeze:function(e,r){if(!e)return 1;var t=d.envStore.get(e);if(t.checkGCAccess(),!t.tryCatch.isEmpty())return t.setLastError(10);if(!t.canCallIntoJs())return t.setLastError(t.moduleApiVersion>=10?23:10);t.clearLastError();try{if(!r)return t.setLastError(1);var n=d.handleStore.get(r),a=n.value;return n.isObject()||n.isFunction()?(Object.freeze(a),t.getReturnStatus()):t.setLastError(2)}catch(e){return t.tryCatch.setError(e),t.setLastError(10)}},napi_object_seal:function(e,r){if(!e)return 1;var t=d.envStore.get(e);if(t.checkGCAccess(),!t.tryCatch.isEmpty())return t.setLastError(10);if(!t.canCallIntoJs())return t.setLastError(t.moduleApiVersion>=10?23:10);t.clearLastError();try{if(!r)return t.setLastError(1);var n=d.handleStore.get(r),a=n.value;return n.isObject()||n.isFunction()?(Object.seal(a),t.getReturnStatus()):t.setLastError(2)}catch(e){return t.tryCatch.setError(e),t.setLastError(10)}},napi_set_element:function(e,r,t,n){if(!e)return 1;var a=d.envStore.get(e);if(a.checkGCAccess(),!a.tryCatch.isEmpty())return a.setLastError(10);if(!a.canCallIntoJs())return a.setLastError(a.moduleApiVersion>=10?23:10);a.clearLastError();try{if(!n)return a.setLastError(1);if(!r)return a.setLastError(1);var o=d.handleStore.get(r);return o.isObject()||o.isFunction()?(o.value[t>>>0]=d.handleStore.get(n).value,a.getReturnStatus()):a.setLastError(2)}catch(e){return a.tryCatch.setError(e),a.setLastError(10)}},napi_set_named_property:function(e,r,t,n){if(!e)return 1;var a=d.envStore.get(e);if(a.checkGCAccess(),!a.tryCatch.isEmpty())return a.setLastError(10);if(!a.canCallIntoJs())return a.setLastError(a.moduleApiVersion>=10?23:10);a.clearLastError();try{if(!n)return a.setLastError(1);if(!r)return a.setLastError(1);var o=d.handleStore.get(r);return o.isObject()||o.isFunction()?t?(t>>>=0,d.handleStore.get(r).value[H.UTF8ToString(t,-1)]=d.handleStore.get(n).value,a.getReturnStatus()):a.setLastError(1):a.setLastError(2)}catch(e){return a.tryCatch.setError(e),a.setLastError(10)}},napi_set_property:function(e,r,t,n){if(!e)return 1;var a=d.envStore.get(e);if(a.checkGCAccess(),!a.tryCatch.isEmpty())return a.setLastError(10);if(!a.canCallIntoJs())return a.setLastError(a.moduleApiVersion>=10?23:10);a.clearLastError();try{if(!t)return a.setLastError(1);if(!n)return a.setLastError(1);if(!r)return a.setLastError(1);var o=d.handleStore.get(r);return o.isObject()||o.isFunction()?(o.value[d.handleStore.get(t).value]=d.handleStore.get(n).value,a.getReturnStatus()):a.setLastError(2)}catch(e){return a.tryCatch.setError(e),a.setLastError(10)}}});var Se=Object.freeze({__proto__:null,napi_run_script:function(e,r,t){var n,o;if(!e)return 1;var i=d.envStore.get(e);if(i.checkGCAccess(),!i.tryCatch.isEmpty())return i.setLastError(10);if(!i.canCallIntoJs())return i.setLastError(i.moduleApiVersion>=10?23:10);i.clearLastError();try{if(!r)return i.setLastError(1);if(!t)return i.setLastError(1);var s=d.handleStore.get(r);if(!s.isString())return i.setLastError(3);var f=d.handleStore.get(5).value.eval(s.value);t>>>=0,o=i.ensureHandleId(f);var u=new DataView(a.buffer);(u.buffer===a.buffer?u:u=new DataView(a.buffer)).setUint32(t,o,!0),n=i.getReturnStatus()}catch(e){return i.tryCatch.setError(e),i.setLastError(10)}return n}});var Ae=Object.freeze({__proto__:null,napi_coerce_to_bool:function(e,r,t){var n;if(!e)return 1;var o=d.envStore.get(e);if(o.checkGCAccess(),!o.tryCatch.isEmpty())return o.setLastError(10);if(!o.canCallIntoJs())return o.setLastError(o.moduleApiVersion>=10?23:10);o.clearLastError();try{if(!r)return o.setLastError(1);if(!t)return o.setLastError(1);var i=d.handleStore.get(r);t>>>=0,n=i.value?4:3;var s=new DataView(a.buffer);return(s.buffer===a.buffer?s:s=new DataView(a.buffer)).setUint32(t,n,!0),o.getReturnStatus()}catch(e){return o.tryCatch.setError(e),o.setLastError(10)}},napi_coerce_to_number:function(e,r,t){var n;if(!e)return 1;var o=d.envStore.get(e);if(o.checkGCAccess(),!o.tryCatch.isEmpty())return o.setLastError(10);if(!o.canCallIntoJs())return o.setLastError(o.moduleApiVersion>=10?23:10);o.clearLastError();try{if(!r)return o.setLastError(1);if(!t)return o.setLastError(1);var i=d.handleStore.get(r);if(i.isBigInt())throw new TypeError("Cannot convert a BigInt value to a number");t>>>=0,n=d.addToCurrentScope(Number(i.value)).id;var s=new DataView(a.buffer);return(s.buffer===a.buffer?s:s=new DataView(a.buffer)).setUint32(t,n,!0),o.getReturnStatus()}catch(e){return o.tryCatch.setError(e),o.setLastError(10)}},napi_coerce_to_object:function(e,r,t){var n;if(!e)return 1;var o=d.envStore.get(e);if(o.checkGCAccess(),!o.tryCatch.isEmpty())return o.setLastError(10);if(!o.canCallIntoJs())return o.setLastError(o.moduleApiVersion>=10?23:10);o.clearLastError();try{if(!r)return o.setLastError(1);if(!t)return o.setLastError(1);var i=d.handleStore.get(r);if(null==i.value)throw new TypeError("Cannot convert undefined or null to object");t>>>=0,n=o.ensureHandleId(Object(i.value));var s=new DataView(a.buffer);return(s.buffer===a.buffer?s:s=new DataView(a.buffer)).setUint32(t,n,!0),o.getReturnStatus()}catch(e){return o.tryCatch.setError(e),o.setLastError(10)}},napi_coerce_to_string:function(e,r,t){var n;if(!e)return 1;var o=d.envStore.get(e);if(o.checkGCAccess(),!o.tryCatch.isEmpty())return o.setLastError(10);if(!o.canCallIntoJs())return o.setLastError(o.moduleApiVersion>=10?23:10);o.clearLastError();try{if(!r)return o.setLastError(1);if(!t)return o.setLastError(1);var i=d.handleStore.get(r);if(i.isSymbol())throw new TypeError("Cannot convert a Symbol value to a string");t>>>=0,n=d.addToCurrentScope(String(i.value)).id;var s=new DataView(a.buffer);return(s.buffer===a.buffer?s:s=new DataView(a.buffer)).setUint32(t,n,!0),o.getReturnStatus()}catch(e){return o.tryCatch.setError(e),o.setLastError(10)}},napi_detach_arraybuffer:function(e,r){if(!e)return 1;var t=d.envStore.get(e);if(t.checkGCAccess(),!r)return t.setLastError(1);var n=d.handleStore.get(r).value;if(!(n instanceof ArrayBuffer))return"function"==typeof SharedArrayBuffer&&n instanceof SharedArrayBuffer?t.setLastError(20):t.setLastError(19);try{(new(0,d.feature.MessageChannel)).port1.postMessage(n,[n])}catch(e){return t.setLastError(9)}return t.clearLastError()},napi_instanceof:function(e,r,t,n){var o;if(!e)return 1;var i=d.envStore.get(e);if(i.checkGCAccess(),!i.tryCatch.isEmpty())return i.setLastError(10);if(!i.canCallIntoJs())return i.setLastError(i.moduleApiVersion>=10?23:10);i.clearLastError();try{if(!r)return i.setLastError(1);if(!n)return i.setLastError(1);if(!t)return i.setLastError(1);n>>>=0;var s=new DataView(a.buffer),f=function(){return s.buffer===a.buffer?s:s=new DataView(a.buffer)};f().setInt8(n,0,!0);var u=d.handleStore.get(t);return u.isFunction()?(o=d.handleStore.get(r).value instanceof u.value?1:0,f().setInt8(n,o,!0),i.getReturnStatus()):i.setLastError(5)}catch(e){return i.tryCatch.setError(e),i.setLastError(10)}},napi_is_array:function(e,r,t){if(!e)return 1;var n=d.envStore.get(e);if(n.checkGCAccess(),!r)return n.setLastError(1);if(!t)return n.setLastError(1);t>>>=0;var o=d.handleStore.get(r).isArray()?1:0,i=new DataView(a.buffer);return(i.buffer===a.buffer?i:i=new DataView(a.buffer)).setInt8(t,o,!0),n.clearLastError()},napi_is_arraybuffer:function(e,r,t){if(!e)return 1;var n=d.envStore.get(e);if(n.checkGCAccess(),!r)return n.setLastError(1);if(!t)return n.setLastError(1);t>>>=0;var o=d.handleStore.get(r).isArrayBuffer()?1:0,i=new DataView(a.buffer);return(i.buffer===a.buffer?i:i=new DataView(a.buffer)).setInt8(t,o,!0),n.clearLastError()},napi_is_buffer:function(e,r,t){if(!e)return 1;var n=d.envStore.get(e);if(n.checkGCAccess(),!r)return n.setLastError(1);if(!t)return n.setLastError(1);t>>>=0;var o=d.handleStore.get(r).isBuffer(d.feature.Buffer)?1:0,i=new DataView(a.buffer);return(i.buffer===a.buffer?i:i=new DataView(a.buffer)).setInt8(t,o,!0),n.clearLastError()},napi_is_dataview:function(e,r,t){if(!e)return 1;var n=d.envStore.get(e);if(n.checkGCAccess(),!r)return n.setLastError(1);if(!t)return n.setLastError(1);t>>>=0;var o=d.handleStore.get(r).isDataView()?1:0,i=new DataView(a.buffer);return(i.buffer===a.buffer?i:i=new DataView(a.buffer)).setInt8(t,o,!0),n.clearLastError()},napi_is_date:function(e,r,t){if(!e)return 1;var n=d.envStore.get(e);if(n.checkGCAccess(),!r)return n.setLastError(1);if(!t)return n.setLastError(1);t>>>=0;var o=d.handleStore.get(r).isDate()?1:0,i=new DataView(a.buffer);return(i.buffer===a.buffer?i:i=new DataView(a.buffer)).setInt8(t,o,!0),n.clearLastError()},napi_is_detached_arraybuffer:function(e,r,t){if(!e)return 1;var n=d.envStore.get(e);if(n.checkGCAccess(),!n.tryCatch.isEmpty())return n.setLastError(10);if(!n.canCallIntoJs())return n.setLastError(n.moduleApiVersion>=10?23:10);n.clearLastError();try{if(!r)return n.setLastError(1);if(!t)return n.setLastError(1);var o=d.handleStore.get(r);t>>>=0;var i=new DataView(a.buffer),s=function(){return i.buffer===a.buffer?i:i=new DataView(a.buffer)};if(o.isArrayBuffer()&&0===o.value.byteLength)try{new Uint8Array(o.value)}catch(e){return s().setInt8(t,1,!0),n.getReturnStatus()}return s().setInt8(t,0,!0),n.getReturnStatus()}catch(e){return n.tryCatch.setError(e),n.setLastError(10)}},napi_is_error:function(e,r,t){if(!e)return 1;var n=d.envStore.get(e);if(n.checkGCAccess(),!r)return n.setLastError(1);if(!t)return n.setLastError(1);t>>>=0;var o=d.handleStore.get(r).value instanceof Error?1:0,i=new DataView(a.buffer);return(i.buffer===a.buffer?i:i=new DataView(a.buffer)).setInt8(t,o,!0),n.clearLastError()},napi_is_typedarray:function(e,r,t){if(!e)return 1;var n=d.envStore.get(e);if(n.checkGCAccess(),!r)return n.setLastError(1);if(!t)return n.setLastError(1);t>>>=0;var o=d.handleStore.get(r).isTypedArray()?1:0,i=new DataView(a.buffer);return(i.buffer===a.buffer?i:i=new DataView(a.buffer)).setInt8(t,o,!0),n.clearLastError()},napi_strict_equals:function(e,r,t,n){var o;if(!e)return 1;var i=d.envStore.get(e);if(i.checkGCAccess(),!i.tryCatch.isEmpty())return i.setLastError(10);if(!i.canCallIntoJs())return i.setLastError(i.moduleApiVersion>=10?23:10);i.clearLastError();try{if(!r)return i.setLastError(1);if(!t)return i.setLastError(1);if(!n)return i.setLastError(1);var s=d.handleStore.get(r).value,f=d.handleStore.get(t).value;n>>>=0,o=s===f?1:0;var u=new DataView(a.buffer);return(u.buffer===a.buffer?u:u=new DataView(a.buffer)).setInt8(n,o,!0),i.getReturnStatus()}catch(e){return i.tryCatch.setError(e),i.setLastError(10)}},napi_typeof:function(e,r,t){if(!e)return 1;var n=d.envStore.get(e);if(n.checkGCAccess(),!r)return n.setLastError(1);if(!t)return n.setLastError(1);var o,i=d.handleStore.get(r);if(t>>>=0,i.isNumber())o=3;else if(i.isBigInt())o=9;else if(i.isString())o=4;else if(i.isFunction())o=7;else if(i.isExternal())o=8;else if(i.isObject())o=6;else if(i.isBoolean())o=2;else if(i.isUndefined())o=0;else if(i.isSymbol())o=5;else{if(!i.isNull())return n.setLastError(1);o=1}var s=new DataView(a.buffer);return(s.buffer===a.buffer?s:s=new DataView(a.buffer)).setInt32(t,o,!0),n.clearLastError()},node_api_is_sharedarraybuffer:function(e,r,t){if(!e)return 1;var n=d.envStore.get(e);if(n.checkGCAccess(),!r)return n.setLastError(1);if(!t)return n.setLastError(1);var o=d.handleStore.get(r);t>>>=0;var i="function"==typeof SharedArrayBuffer&&o.value instanceof SharedArrayBuffer||"[object SharedArrayBuffer]"===Object.prototype.toString.call(o.value)?1:0,s=new DataView(a.buffer);return(s.buffer===a.buffer?s:s=new DataView(a.buffer)).setInt8(t,i,!0),n.clearLastError()}});var Ce=Object.freeze({__proto__:null,napi_get_version:function(e,r){if(!e)return 1;var t=d.envStore.get(e);if(!r)return t.setLastError(1);var n=new DataView(a.buffer);return(n.buffer===a.buffer?n:n=new DataView(a.buffer)).setUint32(r,10,!0),t.clearLastError()}});function Ve(e){for(var r=Object.keys(e),t=0;t>>=0,f>>>=0,e>>>=0,u>>>=0,c>>>=0,l>>>=0,v>>>=0,o>>>=0,0===(f>>>=0))return y.setLastError(1);if(!p)return y.setLastError(1);var g,w=0;if(r>>>=0){if("function"!=typeof d.handleStore.get(r).value)return y.setLastError(1);w=d.createReference(y,r,1,1).id}else if(!v)return y.setLastError(1);if(t){if(null==(g=d.handleStore.get(t).value))return y.setLastError(2);g=Object(g)}else g={};var b=y.ensureHandleId(g),h=d.handleStore.get(n).value;if("symbol"==typeof h)return y.setLastError(3);h=String(h);var _=y.ensureHandleId(h),E=R.offset.__size__,L=i(E);if(!L)return y.setLastError(9);L>>>=0,new Uint8Array(R.ensureBufferFor(L+E)).subarray(L,L+E).fill(0);var m=d.createReference(y,b,1,1),S=m.id,A=new DataView(a.buffer),C=function(){return A.buffer===a.buffer?A:A=new DataView(a.buffer)};return C().setUint32(L+R.offset.resource,S,!0),R.initQueue(L)?(O(b,_,-1,L+R.offset.async_id),C().setInt8(L+R.offset.is_some,1,!0),C().setUint32(L+R.offset.thread_count,f,!0),C().setUint32(L+R.offset.context,l,!0),C().setUint32(L+R.offset.max_queue_size,o,!0),C().setUint32(L+R.offset.ref,w,!0),C().setUint32(L+R.offset.env,e,!0),C().setUint32(L+R.offset.finalize_data,u,!0),C().setUint32(L+R.offset.finalize_cb,c,!0),C().setUint32(L+R.offset.call_js_cb,v,!0),d.addCleanupHook(y,R.cleanup,L),R._liveSet.add(L),y.ref(),d.increaseWaitingRequestCounter(),C().setUint32(L+R.offset.async_ref,1,!0),p>>>=0,C().setUint32(p,L,!0),y.clearLastError()):(s(L),m.dispose(),y.setLastError(9))},y.imports.napi.napi_get_threadsafe_function_context=function(e,r){if(!e||!r)return l(),1;e>>>=0,r>>>=0;var t=R.getContext(e),n=new DataView(a.buffer);return(n.buffer===a.buffer?n:n=new DataView(a.buffer)).setUint32(r,t,!0),0},y.imports.napi.napi_call_threadsafe_function=function(e,r,t){return e?(e>>>=0,r>>>=0,R.push(e,r,t)):(l(),1)},y.imports.napi.napi_acquire_threadsafe_function=function(e){return e?(e>>>=0,R.getMutex(e).execute(function(){return 0===R.getState(e)?(R.addThreadCount(e),0):16})):(l(),1)},y.imports.napi.napi_release_threadsafe_function=function(e,r){if(!e)return l(),1;e>>>=0;var t=R.getMutex(e),n=R.getCond(e),a=!1,o=t.execute(function(){return 0===R.getThreadCount(e)?1:(R.subThreadCount(e),0!==R.getThreadCount(e)&&1!==r||0===R.getState(e)&&(1===r&&R.setState(e,1),1===R.getState(e)&&R.getMaxQueueSize(e)>0&&n.signal(),R.send(e)),2!==R.getState(e)||0!==R.getThreadCount(e)||(a=!0),0)});return a&&R.destroy(e),o},y.imports.napi.napi_unref_threadsafe_function=function(e,r){if(!r)return l(),1;var t=(r>>>=0)+R.offset.async_ref,n=t>>>2,a=new Uint32Array(R.ensureBufferFor(t+4)),o=Atomics.load(a,n);return o>0&&(Atomics.store(a,n,o-1),1===o&&d.decreaseWaitingRequestCounter()),0},y.imports.napi.napi_ref_threadsafe_function=function(e,r){if(!r)return l(),1;var t=(r>>>=0)+R.offset.async_ref,n=t>>>2,a=new Uint32Array(R.ensureBufferFor(t+4)),o=Atomics.load(a,n);return o||d.increaseWaitingRequestCounter(),Atomics.store(a,n,o+1),0},y}();return n}function o(r,t,n,o){const s=(o=null!=o?o:{}).getMemory,f=o.getTable,u=o.beforeInit;if(null!=s&&"function"!=typeof s)throw new TypeError("options.getMemory is not a function");if(null!=f&&"function"!=typeof f)throw new TypeError("options.getTable is not a function");if(null!=u&&"function"!=typeof u)throw new TypeError("options.beforeInit is not a function");let c;const l="object"==typeof t&&null!==t;if(l){if(t.loaded)throw new Error("napiModule has already loaded");c=t}else c=a(o);const d=o.wasi;let v,p={env:c.imports.env,napi:c.imports.napi,emnapi:c.imports.emnapi};d&&(v=new e.WASIThreads(c.childThread?{wasi:d,childThread:!0,postMessage:c.postMessage}:{wasi:d,threadManager:c.PThread,waitThreadStart:c.waitThreadStart}),Object.assign(p,"function"==typeof d.getImportObject?d.getImportObject():{wasi_snapshot_preview1:d.wasiImport}),Object.assign(p,v.getImportObject()));const y=o.overwriteImports;if("function"==typeof y){const e=y(p);"object"==typeof e&&null!==e&&(p=e)}return r(n,p,(e,t)=>{if(e)throw e;const n=t.instance;let a=n;const o=n.exports,y="memory"in o,g="memory"in p.env,w=s?s(o):y?o.memory:g?p.env.memory:void 0;if(!w)throw new Error("memory is neither exported nor imported");const b=f?f(o):o.__indirect_function_table;if(d&&!y){const e=Object.create(null);Object.assign(e,o,{memory:w}),a={exports:e}}const h=t.module;d?a=v.initialize(a,h,w):c.PThread.setup(h,w);const _=()=>{u&&u({instance:n,module:h}),c.init({instance:a,module:h,memory:w,table:b});const e={instance:n,module:h,usedInstance:a};return l||(e.napiModule=c),e};if(c.PThread.shouldPreloadWorkers()){const e=c.PThread.loadWasmModuleToAllWorkers();if(r===i)return e.then(_);throw new Error("Synchronous loading is not supported with worker pool (reuseWorker.size > 0)")}return _()})}function i(e,r,t){return n(e,r).then(e=>t(null,e),e=>t(e))}function s(e,n,a){let o;try{o=function(e,n){if(!e)throw new TypeError("Invalid wasm source");let a;if(t(n),n=null!=n?n:{},e instanceof ArrayBuffer||ArrayBuffer.isView(e))a=new r.Module(e);else{if(!(e instanceof WebAssembly.Module))throw new TypeError("Invalid wasm source");a=e}return{instance:new r.Instance(a,n),module:a}}(e,n)}catch(e){return a(e)}return a(null,o)}class f extends e.ThreadMessageHandler{constructor(e){if("function"!=typeof e.onLoad)throw new TypeError("options.onLoad is not a function");const r=e.onError;super({...e,onError:(e,t)=>{var n;const a=null===(n=this.instance)||void 0===n?void 0:n.exports.emnapi_thread_crashed;if("function"==typeof a&&a(),"function"!=typeof r)throw e;r(e,t)}}),this.napiModule=void 0}instantiate(e){const r=this.onLoad(e);return"function"==typeof r.then?r.then(e=>(this.napiModule=e.napiModule,e)):(this.napiModule=r.napiModule,r)}handle(e){var r;if(super.handle(e),null===(r=null==e?void 0:e.data)||void 0===r?void 0:r.__emnapi__){const r=e.data.__emnapi__.type,t=e.data.__emnapi__.payload;try{"async-worker-init"===r&&this.handleAfterLoad(e,()=>{this.napiModule.initWorker(t.arg,t.func)})}catch(e){this.onError(e,r)}}}}exports.MessageHandler=f,exports.createNapiModule=a,exports.instantiateNapiModule=function(e,r){return o(i,void 0,e,r)},exports.instantiateNapiModuleSync=function(e,r){return o(s,void 0,e,r)},exports.loadNapiModule=function(e,r,t){if("object"!=typeof e||null===e)throw new TypeError("Invalid napiModule");return o(i,e,r,t)},exports.loadNapiModuleSync=function(e,r,t){if("object"!=typeof e||null===e)throw new TypeError("Invalid napiModule");return o(s,e,r,t)},exports.version="1.11.3",Object.keys(e).forEach(function(r){"default"===r||Object.prototype.hasOwnProperty.call(exports,r)||Object.defineProperty(exports,r,{enumerable:!0,get:function(){return e[r]}})}); diff --git a/dg-ui/node_modules/@tailwindcss/oxide-wasm32-wasi/node_modules/@emnapi/core/dist/emnapi-core.d.mts b/dg-ui/node_modules/@tailwindcss/oxide-wasm32-wasi/node_modules/@emnapi/core/dist/emnapi-core.d.mts new file mode 100644 index 0000000..fde8e40 --- /dev/null +++ b/dg-ui/node_modules/@tailwindcss/oxide-wasm32-wasi/node_modules/@emnapi/core/dist/emnapi-core.d.mts @@ -0,0 +1,428 @@ +/// + +import type { Context } from '@emnapi/runtime'; +import type { ReferenceOwnership } from '@emnapi/runtime'; +import type { Worker as Worker_2 } from 'worker_threads'; + +/** @public */ +export declare type BaseCreateOptions = { + filename?: string + nodeBinding?: NodeBinding + reuseWorker?: ThreadManagerOptionsMain['reuseWorker'] + asyncWorkPoolSize?: number + waitThreadStart?: MainThreadBaseOptions['waitThreadStart'] + onCreateWorker?: (info: CreateWorkerInfo) => any + print?: (str: string) => void + printErr?: (str: string) => void + postMessage?: (msg: any) => any +} + +/** @public */ +export declare interface BaseOptions { + wasi: WASIInstance; + version?: 'preview1'; + wasm64?: boolean; +} + +/** @public */ +export declare interface ChildThreadOptions extends BaseOptions { + childThread: true; + postMessage?: (data: any) => void; +} + +/** @public */ +export declare interface CleanupThreadPayload { + tid: number; +} + +/** @public */ +export declare interface CommandInfo { + type: T; + payload: CommandPayloadMap[T]; +} + +/** @public */ +export declare interface CommandPayloadMap { + load: LoadPayload; + loaded: LoadedPayload; + start: StartPayload; + 'cleanup-thread': CleanupThreadPayload; + 'terminate-all-threads': TerminateAllThreadsPayload; + 'spawn-thread': SpawnThreadPayload; +} + +/** @public */ +export declare type CommandType = keyof CommandPayloadMap; + +/** @public */ +export declare function createInstanceProxy(instance: WebAssembly.Instance, memory?: WebAssembly.Memory | (() => WebAssembly.Memory)): WebAssembly.Instance; + +/** @public */ +export declare function createNapiModule ( +options: CreateOptions +): NapiModule + +/** @public */ +export declare type CreateOptions = BaseCreateOptions & ({ + context: Context + childThread?: boolean +} | { + context?: Context + childThread: true +}) + +/** @public */ +export declare interface CreateWorkerInfo { + type: 'thread' | 'async-work' + name: string +} + +/** @public */ +export declare interface InitOptions { + instance: WebAssembly.Instance + module: WebAssembly.Module + memory?: WebAssembly.Memory + table?: WebAssembly.Table +} + +export declare type InputType = string | URL | Response | BufferSource | WebAssembly.Module; + +/** @public */ +export declare interface InstantiatedSource extends LoadedSource { + napiModule: NapiModule; +} + +/** @public */ +export declare function instantiateNapiModule( +/** Only support `BufferSource` or `WebAssembly.Module` on Node.js */ +wasmInput: InputType | Promise, options: InstantiateOptions): Promise; + +/** @public */ +export declare function instantiateNapiModuleSync(wasmInput: BufferSource | WebAssembly.Module, options: InstantiateOptions): InstantiatedSource; + +/** @public */ +export declare type InstantiateOptions = CreateOptions & LoadOptions; + +/** @public */ +export declare function isSharedArrayBuffer(value: any): value is SharedArrayBuffer; + +/** @public */ +export declare function isTrapError(e: Error): e is WebAssembly.RuntimeError; + +/** @public */ +export declare interface LoadedPayload { +} + +/** @public */ +export declare interface LoadedSource extends WebAssembly.WebAssemblyInstantiatedSource { + usedInstance: WebAssembly.Instance; +} + +/** @public */ +export declare function loadNapiModule(napiModule: NapiModule, +/** Only support `BufferSource` or `WebAssembly.Module` on Node.js */ +wasmInput: InputType | Promise, options?: LoadOptions): Promise; + +/** @public */ +export declare function loadNapiModuleSync(napiModule: NapiModule, wasmInput: BufferSource | WebAssembly.Module, options?: LoadOptions): LoadedSource; + +/** @public */ +export declare interface LoadOptions { + wasi?: WASIInstance; + overwriteImports?: (importObject: WebAssembly.Imports) => WebAssembly.Imports; + beforeInit?: (source: WebAssembly.WebAssemblyInstantiatedSource) => void; + getMemory?: (exports: WebAssembly.Exports) => WebAssembly.Memory; + getTable?: (exports: WebAssembly.Exports) => WebAssembly.Table; +} + +/** @public */ +export declare interface LoadPayload { + wasmModule: WebAssembly.Module; + wasmMemory: WebAssembly.Memory; + sab?: Int32Array; +} + +/** @public */ +export declare interface MainThreadBaseOptions extends BaseOptions { + waitThreadStart?: boolean | number; +} + +/** @public */ +export declare type MainThreadOptions = MainThreadOptionsWithThreadManager | MainThreadOptionsCreateThreadManager; + +/** @public */ +export declare interface MainThreadOptionsCreateThreadManager extends MainThreadBaseOptions, ThreadManagerOptionsMain { +} + +/** @public */ +export declare interface MainThreadOptionsWithThreadManager extends MainThreadBaseOptions { + threadManager?: ThreadManager | (() => ThreadManager); +} + +/** @public */ +export declare interface MessageEventData { + __emnapi__: CommandInfo; +} + +/** @public */ +export declare class MessageHandler extends ThreadMessageHandler { + napiModule: NapiModule | undefined; + constructor(options: MessageHandlerOptions); + instantiate(data: LoadPayload): InstantiatedSource | PromiseLike; + handle(e: WorkerMessageEvent): void; +} + +/** @public */ +export declare interface MessageHandlerOptions extends ThreadMessageHandlerOptions { + onLoad: (data: LoadPayload) => InstantiatedSource | PromiseLike; +} + +/** @public */ +export declare interface NapiModule { + imports: { + env: any + napi: any + emnapi: any + } + exports: any + loaded: boolean + filename: string + childThread: boolean + emnapi: { + /** + * Synchronize data between the wasm memory and an ArrayBuffer / view. + * + * Note: when a non-shared wasm memory has grown, a view over the + * detached old buffer is re-created over the current buffer through the + * intrinsic base-class constructor, so for view inputs the returned view + * may be a base-class instance (e.g. `Uint8Array` or `DataView`) + * instead of the subclass that was passed in. + */ + syncMemory ( + js_to_wasm: boolean, + arrayBufferOrView: T, + offset?: number, + len?: number + ): T extends ArrayBufferView ? ArrayBufferView : T + getMemoryAddress (arrayBufferOrView: ArrayBuffer | ArrayBufferView): PointerInfo + addSendListener (worker: any): boolean + } + + init (options: InitOptions): any + initWorker (arg: number, func: [number, number]): void + postMessage?: (msg: any) => any + + waitThreadStart: boolean | number + /* Excluded from this release type: PThread */} + +/** @public */ +export declare interface NodeBinding { + node: { + emitAsyncInit: Function + emitAsyncDestroy: Function + makeCallback: Function + } + napi: { + asyncInit: Function + asyncDestroy: Function + makeCallback: Function + } +} + +/** @public */ +export declare interface PointerInfo { + address: number + ownership: ReferenceOwnership + runtimeAllocated: 0 | 1 +} + +/** @public */ +export declare interface ReuseWorkerOptions { + /** + * @see {@link https://emscripten.org/docs/tools_reference/settings_reference.html#pthread-pool-size | PTHREAD_POOL_SIZE} + */ + size: number; + /** + * @see {@link https://emscripten.org/docs/tools_reference/settings_reference.html#pthread-pool-size-strict | PTHREAD_POOL_SIZE_STRICT} + */ + strict?: boolean; +} + +/** @public */ +export declare interface SpawnThreadPayload { + startArg: number; + errorOrTid: number; +} + +/** @public */ +export declare interface StartPayload { + tid: number; + arg: number; + sab?: Int32Array; +} + +/** @public */ +export declare interface StartResult { + exitCode: number; + instance: WebAssembly.Instance; +} + +/** @public */ +export declare interface TerminateAllThreadsPayload { +} + +/** @public */ +export declare class ThreadManager { + unusedWorkers: WorkerLike[]; + pthreads: Record; + get nextWorkerID(): number; + wasmModule: WebAssembly.Module | null; + wasmMemory: WebAssembly.Memory | null; + private readonly messageEvents; + private readonly _childThread; + private readonly _onCreateWorker; + private readonly _reuseWorker; + private readonly _beforeLoad?; + /* Excluded from this release type: printErr */ + threadSpawn?: ((startArg: number, errorOrTid?: number) => number); + constructor(options: ThreadManagerOptions); + init(): void; + initMainThread(): void; + private preparePool; + shouldPreloadWorkers(): boolean; + loadWasmModuleToAllWorkers(): Promise; + preloadWorkers(): Promise; + setup(wasmModule: WebAssembly.Module, wasmMemory: WebAssembly.Memory): void; + markId(worker: WorkerLike): number; + returnWorkerToPool(worker: WorkerLike): void; + loadWasmModuleToWorker(worker: WorkerLike, sab?: Int32Array): Promise; + allocateUnusedWorker(): WorkerLike; + getNewWorker(sab?: Int32Array): WorkerLike | undefined; + cleanThread(worker: WorkerLike, tid: number, force?: boolean): void; + terminateWorker(worker: WorkerLike): void; + terminateAllThreads(): void; + addMessageEventListener(worker: WorkerLike, onMessage: (e: WorkerMessageEvent) => void): () => void; + fireMessageEvent(worker: WorkerLike, e: WorkerMessageEvent): void; +} + +/** @public */ +export declare type ThreadManagerOptions = ThreadManagerOptionsMain | ThreadManagerOptionsChild; + +/** @public */ +export declare interface ThreadManagerOptionsBase { + printErr?: (message: string) => void; + threadSpawn?: (startArg: number, errorOrTid?: number) => number; +} + +/** @public */ +export declare interface ThreadManagerOptionsChild extends ThreadManagerOptionsBase { + childThread: true; +} + +/** @public */ +export declare interface ThreadManagerOptionsMain extends ThreadManagerOptionsBase { + beforeLoad?: (worker: WorkerLike) => any; + reuseWorker?: boolean | number | ReuseWorkerOptions; + onCreateWorker: WorkerFactory; + childThread?: false; +} + +/** @public */ +export declare class ThreadMessageHandler { + protected instance: WebAssembly.Instance | undefined; + private messagesBeforeLoad; + protected postMessage: (message: any) => void; + protected onLoad?: (data: LoadPayload) => WebAssembly.WebAssemblyInstantiatedSource | PromiseLike; + protected onError: (error: Error, type: WorkerMessageType) => void; + constructor(options?: ThreadMessageHandlerOptions); + /** @virtual */ + instantiate(data: LoadPayload): WebAssembly.WebAssemblyInstantiatedSource | PromiseLike; + /** @virtual */ + handle(e: WorkerMessageEvent>): void; + private _load; + private _start; + protected _loaded(err: Error | null, source: WebAssembly.WebAssemblyInstantiatedSource | null, payload: LoadPayload): void; + protected handleAfterLoad(e: E, f: (e: E) => void): void; +} + +/** @public */ +export declare interface ThreadMessageHandlerOptions { + onLoad?: (data: LoadPayload) => WebAssembly.WebAssemblyInstantiatedSource | PromiseLike; + onError?: (error: Error, type: WorkerMessageType) => void; + postMessage?: (message: any) => void; +} + +export declare const version: string; + +/** @public */ +export declare interface WASIInstance { + readonly wasiImport?: Record; + initialize(instance: object): void; + start(instance: object): number; + getImportObject?(): any; +} + +/** @public */ +export declare class WASIThreads { + PThread: ThreadManager | undefined; + private wasmMemory; + private wasmInstance; + private readonly threadSpawn; + readonly childThread: boolean; + private readonly postMessage; + readonly wasi: WASIInstance; + constructor(options: WASIThreadsOptions); + getImportObject(): { + wasi: WASIThreadsImports; + }; + setup(wasmInstance: WebAssembly.Instance, wasmModule: WebAssembly.Module, wasmMemory?: WebAssembly.Memory): void; + preloadWorkers(): Promise; + /** + * It's ok to call this method to a WASI command module. + * + * in child thread, must call this method instead of {@link WASIThreads.start} even if it's a WASI command module + * + * @returns A proxied WebAssembly instance if in child thread, other wise the original instance + */ + initialize(instance: WebAssembly.Instance, module: WebAssembly.Module, memory?: WebAssembly.Memory): WebAssembly.Instance; + /** + * Equivalent to calling {@link WASIThreads.initialize} and then calling {@link WASIInstance.start} + * ```js + * this.initialize(instance, module, memory) + * this.wasi.start(instance) + * ``` + */ + start(instance: WebAssembly.Instance, module: WebAssembly.Module, memory?: WebAssembly.Memory): StartResult; + terminateAllThreads(): void; +} + +/** @public */ +export declare interface WASIThreadsImports { + 'thread-spawn': (startArg: number, errorOrTid?: number) => number; +} + +/** @public */ +export declare type WASIThreadsOptions = MainThreadOptions | ChildThreadOptions; + +/** @public */ +export declare type WorkerFactory = (ctx: { + type: string; + name: string; +}) => WorkerLike; + +/** @public */ +export declare type WorkerLike = (Worker | Worker_2) & { + whenLoaded?: Promise; + loaded?: boolean; + __emnapi_tid?: number; +}; + +/** @public */ +export declare interface WorkerMessageEvent { + data: T; +} + +/** @public */ +export declare type WorkerMessageType = 'load' | 'start'; + +export { } diff --git a/dg-ui/node_modules/@tailwindcss/oxide-wasm32-wasi/node_modules/@emnapi/core/dist/emnapi-core.d.ts b/dg-ui/node_modules/@tailwindcss/oxide-wasm32-wasi/node_modules/@emnapi/core/dist/emnapi-core.d.ts new file mode 100644 index 0000000..8f00802 --- /dev/null +++ b/dg-ui/node_modules/@tailwindcss/oxide-wasm32-wasi/node_modules/@emnapi/core/dist/emnapi-core.d.ts @@ -0,0 +1,430 @@ +/// + +import type { Context } from '@emnapi/runtime'; +import type { ReferenceOwnership } from '@emnapi/runtime'; +import type { Worker as Worker_2 } from 'worker_threads'; + +/** @public */ +export declare type BaseCreateOptions = { + filename?: string + nodeBinding?: NodeBinding + reuseWorker?: ThreadManagerOptionsMain['reuseWorker'] + asyncWorkPoolSize?: number + waitThreadStart?: MainThreadBaseOptions['waitThreadStart'] + onCreateWorker?: (info: CreateWorkerInfo) => any + print?: (str: string) => void + printErr?: (str: string) => void + postMessage?: (msg: any) => any +} + +/** @public */ +export declare interface BaseOptions { + wasi: WASIInstance; + version?: 'preview1'; + wasm64?: boolean; +} + +/** @public */ +export declare interface ChildThreadOptions extends BaseOptions { + childThread: true; + postMessage?: (data: any) => void; +} + +/** @public */ +export declare interface CleanupThreadPayload { + tid: number; +} + +/** @public */ +export declare interface CommandInfo { + type: T; + payload: CommandPayloadMap[T]; +} + +/** @public */ +export declare interface CommandPayloadMap { + load: LoadPayload; + loaded: LoadedPayload; + start: StartPayload; + 'cleanup-thread': CleanupThreadPayload; + 'terminate-all-threads': TerminateAllThreadsPayload; + 'spawn-thread': SpawnThreadPayload; +} + +/** @public */ +export declare type CommandType = keyof CommandPayloadMap; + +/** @public */ +export declare function createInstanceProxy(instance: WebAssembly.Instance, memory?: WebAssembly.Memory | (() => WebAssembly.Memory)): WebAssembly.Instance; + +/** @public */ +export declare function createNapiModule ( +options: CreateOptions +): NapiModule + +/** @public */ +export declare type CreateOptions = BaseCreateOptions & ({ + context: Context + childThread?: boolean +} | { + context?: Context + childThread: true +}) + +/** @public */ +export declare interface CreateWorkerInfo { + type: 'thread' | 'async-work' + name: string +} + +/** @public */ +export declare interface InitOptions { + instance: WebAssembly.Instance + module: WebAssembly.Module + memory?: WebAssembly.Memory + table?: WebAssembly.Table +} + +export declare type InputType = string | URL | Response | BufferSource | WebAssembly.Module; + +/** @public */ +export declare interface InstantiatedSource extends LoadedSource { + napiModule: NapiModule; +} + +/** @public */ +export declare function instantiateNapiModule( +/** Only support `BufferSource` or `WebAssembly.Module` on Node.js */ +wasmInput: InputType | Promise, options: InstantiateOptions): Promise; + +/** @public */ +export declare function instantiateNapiModuleSync(wasmInput: BufferSource | WebAssembly.Module, options: InstantiateOptions): InstantiatedSource; + +/** @public */ +export declare type InstantiateOptions = CreateOptions & LoadOptions; + +/** @public */ +export declare function isSharedArrayBuffer(value: any): value is SharedArrayBuffer; + +/** @public */ +export declare function isTrapError(e: Error): e is WebAssembly.RuntimeError; + +/** @public */ +export declare interface LoadedPayload { +} + +/** @public */ +export declare interface LoadedSource extends WebAssembly.WebAssemblyInstantiatedSource { + usedInstance: WebAssembly.Instance; +} + +/** @public */ +export declare function loadNapiModule(napiModule: NapiModule, +/** Only support `BufferSource` or `WebAssembly.Module` on Node.js */ +wasmInput: InputType | Promise, options?: LoadOptions): Promise; + +/** @public */ +export declare function loadNapiModuleSync(napiModule: NapiModule, wasmInput: BufferSource | WebAssembly.Module, options?: LoadOptions): LoadedSource; + +/** @public */ +export declare interface LoadOptions { + wasi?: WASIInstance; + overwriteImports?: (importObject: WebAssembly.Imports) => WebAssembly.Imports; + beforeInit?: (source: WebAssembly.WebAssemblyInstantiatedSource) => void; + getMemory?: (exports: WebAssembly.Exports) => WebAssembly.Memory; + getTable?: (exports: WebAssembly.Exports) => WebAssembly.Table; +} + +/** @public */ +export declare interface LoadPayload { + wasmModule: WebAssembly.Module; + wasmMemory: WebAssembly.Memory; + sab?: Int32Array; +} + +/** @public */ +export declare interface MainThreadBaseOptions extends BaseOptions { + waitThreadStart?: boolean | number; +} + +/** @public */ +export declare type MainThreadOptions = MainThreadOptionsWithThreadManager | MainThreadOptionsCreateThreadManager; + +/** @public */ +export declare interface MainThreadOptionsCreateThreadManager extends MainThreadBaseOptions, ThreadManagerOptionsMain { +} + +/** @public */ +export declare interface MainThreadOptionsWithThreadManager extends MainThreadBaseOptions { + threadManager?: ThreadManager | (() => ThreadManager); +} + +/** @public */ +export declare interface MessageEventData { + __emnapi__: CommandInfo; +} + +/** @public */ +export declare class MessageHandler extends ThreadMessageHandler { + napiModule: NapiModule | undefined; + constructor(options: MessageHandlerOptions); + instantiate(data: LoadPayload): InstantiatedSource | PromiseLike; + handle(e: WorkerMessageEvent): void; +} + +/** @public */ +export declare interface MessageHandlerOptions extends ThreadMessageHandlerOptions { + onLoad: (data: LoadPayload) => InstantiatedSource | PromiseLike; +} + +/** @public */ +export declare interface NapiModule { + imports: { + env: any + napi: any + emnapi: any + } + exports: any + loaded: boolean + filename: string + childThread: boolean + emnapi: { + /** + * Synchronize data between the wasm memory and an ArrayBuffer / view. + * + * Note: when a non-shared wasm memory has grown, a view over the + * detached old buffer is re-created over the current buffer through the + * intrinsic base-class constructor, so for view inputs the returned view + * may be a base-class instance (e.g. `Uint8Array` or `DataView`) + * instead of the subclass that was passed in. + */ + syncMemory ( + js_to_wasm: boolean, + arrayBufferOrView: T, + offset?: number, + len?: number + ): T extends ArrayBufferView ? ArrayBufferView : T + getMemoryAddress (arrayBufferOrView: ArrayBuffer | ArrayBufferView): PointerInfo + addSendListener (worker: any): boolean + } + + init (options: InitOptions): any + initWorker (arg: number, func: [number, number]): void + postMessage?: (msg: any) => any + + waitThreadStart: boolean | number + /* Excluded from this release type: PThread */} + +/** @public */ +export declare interface NodeBinding { + node: { + emitAsyncInit: Function + emitAsyncDestroy: Function + makeCallback: Function + } + napi: { + asyncInit: Function + asyncDestroy: Function + makeCallback: Function + } +} + +/** @public */ +export declare interface PointerInfo { + address: number + ownership: ReferenceOwnership + runtimeAllocated: 0 | 1 +} + +/** @public */ +export declare interface ReuseWorkerOptions { + /** + * @see {@link https://emscripten.org/docs/tools_reference/settings_reference.html#pthread-pool-size | PTHREAD_POOL_SIZE} + */ + size: number; + /** + * @see {@link https://emscripten.org/docs/tools_reference/settings_reference.html#pthread-pool-size-strict | PTHREAD_POOL_SIZE_STRICT} + */ + strict?: boolean; +} + +/** @public */ +export declare interface SpawnThreadPayload { + startArg: number; + errorOrTid: number; +} + +/** @public */ +export declare interface StartPayload { + tid: number; + arg: number; + sab?: Int32Array; +} + +/** @public */ +export declare interface StartResult { + exitCode: number; + instance: WebAssembly.Instance; +} + +/** @public */ +export declare interface TerminateAllThreadsPayload { +} + +/** @public */ +export declare class ThreadManager { + unusedWorkers: WorkerLike[]; + pthreads: Record; + get nextWorkerID(): number; + wasmModule: WebAssembly.Module | null; + wasmMemory: WebAssembly.Memory | null; + private readonly messageEvents; + private readonly _childThread; + private readonly _onCreateWorker; + private readonly _reuseWorker; + private readonly _beforeLoad?; + /* Excluded from this release type: printErr */ + threadSpawn?: ((startArg: number, errorOrTid?: number) => number); + constructor(options: ThreadManagerOptions); + init(): void; + initMainThread(): void; + private preparePool; + shouldPreloadWorkers(): boolean; + loadWasmModuleToAllWorkers(): Promise; + preloadWorkers(): Promise; + setup(wasmModule: WebAssembly.Module, wasmMemory: WebAssembly.Memory): void; + markId(worker: WorkerLike): number; + returnWorkerToPool(worker: WorkerLike): void; + loadWasmModuleToWorker(worker: WorkerLike, sab?: Int32Array): Promise; + allocateUnusedWorker(): WorkerLike; + getNewWorker(sab?: Int32Array): WorkerLike | undefined; + cleanThread(worker: WorkerLike, tid: number, force?: boolean): void; + terminateWorker(worker: WorkerLike): void; + terminateAllThreads(): void; + addMessageEventListener(worker: WorkerLike, onMessage: (e: WorkerMessageEvent) => void): () => void; + fireMessageEvent(worker: WorkerLike, e: WorkerMessageEvent): void; +} + +/** @public */ +export declare type ThreadManagerOptions = ThreadManagerOptionsMain | ThreadManagerOptionsChild; + +/** @public */ +export declare interface ThreadManagerOptionsBase { + printErr?: (message: string) => void; + threadSpawn?: (startArg: number, errorOrTid?: number) => number; +} + +/** @public */ +export declare interface ThreadManagerOptionsChild extends ThreadManagerOptionsBase { + childThread: true; +} + +/** @public */ +export declare interface ThreadManagerOptionsMain extends ThreadManagerOptionsBase { + beforeLoad?: (worker: WorkerLike) => any; + reuseWorker?: boolean | number | ReuseWorkerOptions; + onCreateWorker: WorkerFactory; + childThread?: false; +} + +/** @public */ +export declare class ThreadMessageHandler { + protected instance: WebAssembly.Instance | undefined; + private messagesBeforeLoad; + protected postMessage: (message: any) => void; + protected onLoad?: (data: LoadPayload) => WebAssembly.WebAssemblyInstantiatedSource | PromiseLike; + protected onError: (error: Error, type: WorkerMessageType) => void; + constructor(options?: ThreadMessageHandlerOptions); + /** @virtual */ + instantiate(data: LoadPayload): WebAssembly.WebAssemblyInstantiatedSource | PromiseLike; + /** @virtual */ + handle(e: WorkerMessageEvent>): void; + private _load; + private _start; + protected _loaded(err: Error | null, source: WebAssembly.WebAssemblyInstantiatedSource | null, payload: LoadPayload): void; + protected handleAfterLoad(e: E, f: (e: E) => void): void; +} + +/** @public */ +export declare interface ThreadMessageHandlerOptions { + onLoad?: (data: LoadPayload) => WebAssembly.WebAssemblyInstantiatedSource | PromiseLike; + onError?: (error: Error, type: WorkerMessageType) => void; + postMessage?: (message: any) => void; +} + +export declare const version: string; + +/** @public */ +export declare interface WASIInstance { + readonly wasiImport?: Record; + initialize(instance: object): void; + start(instance: object): number; + getImportObject?(): any; +} + +/** @public */ +export declare class WASIThreads { + PThread: ThreadManager | undefined; + private wasmMemory; + private wasmInstance; + private readonly threadSpawn; + readonly childThread: boolean; + private readonly postMessage; + readonly wasi: WASIInstance; + constructor(options: WASIThreadsOptions); + getImportObject(): { + wasi: WASIThreadsImports; + }; + setup(wasmInstance: WebAssembly.Instance, wasmModule: WebAssembly.Module, wasmMemory?: WebAssembly.Memory): void; + preloadWorkers(): Promise; + /** + * It's ok to call this method to a WASI command module. + * + * in child thread, must call this method instead of {@link WASIThreads.start} even if it's a WASI command module + * + * @returns A proxied WebAssembly instance if in child thread, other wise the original instance + */ + initialize(instance: WebAssembly.Instance, module: WebAssembly.Module, memory?: WebAssembly.Memory): WebAssembly.Instance; + /** + * Equivalent to calling {@link WASIThreads.initialize} and then calling {@link WASIInstance.start} + * ```js + * this.initialize(instance, module, memory) + * this.wasi.start(instance) + * ``` + */ + start(instance: WebAssembly.Instance, module: WebAssembly.Module, memory?: WebAssembly.Memory): StartResult; + terminateAllThreads(): void; +} + +/** @public */ +export declare interface WASIThreadsImports { + 'thread-spawn': (startArg: number, errorOrTid?: number) => number; +} + +/** @public */ +export declare type WASIThreadsOptions = MainThreadOptions | ChildThreadOptions; + +/** @public */ +export declare type WorkerFactory = (ctx: { + type: string; + name: string; +}) => WorkerLike; + +/** @public */ +export declare type WorkerLike = (Worker | Worker_2) & { + whenLoaded?: Promise; + loaded?: boolean; + __emnapi_tid?: number; +}; + +/** @public */ +export declare interface WorkerMessageEvent { + data: T; +} + +/** @public */ +export declare type WorkerMessageType = 'load' | 'start'; + +export { } + +export as namespace emnapiCore; diff --git a/dg-ui/node_modules/@tailwindcss/oxide-wasm32-wasi/node_modules/@emnapi/core/dist/emnapi-core.esm-bundler.js b/dg-ui/node_modules/@tailwindcss/oxide-wasm32-wasi/node_modules/@emnapi/core/dist/emnapi-core.esm-bundler.js new file mode 100644 index 0000000..5032888 --- /dev/null +++ b/dg-ui/node_modules/@tailwindcss/oxide-wasm32-wasi/node_modules/@emnapi/core/dist/emnapi-core.esm-bundler.js @@ -0,0 +1,8741 @@ +import { ThreadManager, WASIThreads, ThreadMessageHandler } from '@emnapi/wasi-threads'; +export * from '@emnapi/wasi-threads'; +import { __extends, __assign } from 'tslib'; + +/* eslint-disable no-undef */ +var _WebAssembly = typeof WebAssembly !== 'undefined' + ? WebAssembly + : typeof WXWebAssembly !== 'undefined' + ? WXWebAssembly + : undefined; +function validateImports(imports) { + if (imports && typeof imports !== 'object') { + throw new TypeError('imports must be an object or undefined'); + } + return true; +} +function load(wasmInput, imports) { + if (!wasmInput) + throw new TypeError('Invalid wasm source'); + validateImports(imports); + imports = imports !== null && imports !== void 0 ? imports : {}; + // Promise + try { + var then = typeof wasmInput === 'object' && wasmInput !== null && 'then' in wasmInput ? wasmInput.then : undefined; + if (typeof then === 'function') { + return then.call(wasmInput, function (input) { return load(input, imports); }); + } + } + catch (_) { } + // BufferSource + if (wasmInput instanceof ArrayBuffer || ArrayBuffer.isView(wasmInput)) { + return _WebAssembly.instantiate(wasmInput, imports); + } + // WebAssembly.Module + if (wasmInput instanceof _WebAssembly.Module) { + return _WebAssembly.instantiate(wasmInput, imports).then(function (instance) { + return { instance: instance, module: wasmInput }; + }); + } + // Response + if (typeof Response !== 'undefined' && wasmInput instanceof Response) { + return wasmInput.arrayBuffer().then(function (buffer) { + return _WebAssembly.instantiate(buffer, imports); + }); + } + // string | URL + var inputIsString = typeof wasmInput === 'string'; + if (inputIsString || (typeof URL !== 'undefined' && wasmInput instanceof URL)) { + if (inputIsString && typeof wx !== 'undefined' && typeof __wxConfig !== 'undefined') { + return _WebAssembly.instantiate(wasmInput, imports); + } + if (typeof fetch !== 'function') { + throw new TypeError('wasm source can not be a string or URL in this environment'); + } + if (typeof _WebAssembly.instantiateStreaming === 'function') { + try { + return _WebAssembly.instantiateStreaming(fetch(wasmInput), imports).catch(function () { + return load(fetch(wasmInput), imports); + }); + } + catch (_) { + return load(fetch(wasmInput), imports); + } + } + else { + return load(fetch(wasmInput), imports); + } + } + throw new TypeError('Invalid wasm source'); +} +function loadSync(wasmInput, imports) { + if (!wasmInput) + throw new TypeError('Invalid wasm source'); + validateImports(imports); + imports = imports !== null && imports !== void 0 ? imports : {}; + var module; + if ((wasmInput instanceof ArrayBuffer) || ArrayBuffer.isView(wasmInput)) { + module = new _WebAssembly.Module(wasmInput); + } + else if (wasmInput instanceof WebAssembly.Module) { + module = wasmInput; + } + else { + throw new TypeError('Invalid wasm source'); + } + var instance = new _WebAssembly.Instance(module, imports); + var source = { instance: instance, module: module }; + return source; +} + +function createNapiModule(options) { + var napiModule = (function () { + var ENVIRONMENT_IS_NODE = typeof process === 'object' && process !== null && typeof process.versions === 'object' && process.versions !== null && typeof process.versions.node === 'string'; + var ENVIRONMENT_IS_PTHREAD = Boolean(options.childThread); + var waitThreadStart = typeof options.waitThreadStart === 'number' ? options.waitThreadStart : Boolean(options.waitThreadStart); + var wasmInstance; + var wasmMemory; + var wasmTable; + var _malloc; + var _free; + function abort(msg) { + if (typeof _WebAssembly.RuntimeError === 'function') { + throw new _WebAssembly.RuntimeError(msg); + } + throw Error(msg); + } + var napiModule = { + imports: { + env: {}, + napi: {}, + emnapi: {} + }, + exports: {}, + emnapi: {}, + loaded: false, + filename: '', + childThread: ENVIRONMENT_IS_PTHREAD, + initWorker: undefined, + waitThreadStart: waitThreadStart, + PThread: undefined, + init: function (options) { + if (napiModule.loaded) + return napiModule.exports; + if (!options) + throw new TypeError('Invalid napi init options'); + var instance = options.instance; + if (!(instance === null || instance === void 0 ? void 0 : instance.exports)) + throw new TypeError('Invalid wasm instance'); + wasmInstance = instance; + var exports = instance.exports; + var module = options.module; + var memory = options.memory || exports.memory; + var table = options.table || exports.__indirect_function_table; + if (!(module instanceof _WebAssembly.Module)) + throw new TypeError('Invalid wasm module'); + if (!(memory instanceof _WebAssembly.Memory)) + throw new TypeError('Invalid wasm memory'); + if (!(table instanceof _WebAssembly.Table)) + throw new TypeError('Invalid wasm table'); + wasmMemory = memory; + wasmTable = table; + if (typeof exports.malloc !== 'function') + throw new TypeError('malloc is not exported'); + if (typeof exports.free !== 'function') + throw new TypeError('free is not exported'); + _malloc = exports.malloc; + _free = exports.free; + if (!napiModule.childThread) { + // main thread only + var moduleApiVersion = 8 /* Version.NODE_API_DEFAULT_MODULE_API_VERSION */; + var node_api_module_get_api_version_v1 = instance.exports.node_api_module_get_api_version_v1; + if (typeof node_api_module_get_api_version_v1 === 'function') { + moduleApiVersion = node_api_module_get_api_version_v1(); + } + // eslint-disable-next-line @typescript-eslint/prefer-nullish-coalescing + var envObject = napiModule.envObject || (napiModule.envObject = emnapiCtx.createEnv(napiModule.filename, moduleApiVersion, function (cb) { return (wasmTable.get(cb)); }, function (cb) { return (wasmTable.get(cb)); }, abort, emnapiNodeBinding)); + var scope_1 = emnapiCtx.openScope(envObject); + try { + envObject.callIntoModule(function (_envObject) { + var exports = napiModule.exports; + var exportsHandle = scope_1.add(exports); + var napi_register_wasm_v1 = instance.exports.napi_register_wasm_v1; + var napiValue = napi_register_wasm_v1(_envObject.id, exportsHandle.id); + napiModule.exports = (!napiValue) ? exports : emnapiCtx.handleStore.get(napiValue).value; + }); + } + catch (e) { + if (e !== 'unwind') { + throw e; + } + } + finally { + emnapiCtx.closeScope(envObject, scope_1); + } + napiModule.loaded = true; + delete napiModule.envObject; + return napiModule.exports; + } + } + }; + var emnapiCtx; + var emnapiNodeBinding; + var onCreateWorker = undefined; + var err; + if (!ENVIRONMENT_IS_PTHREAD) { + var context = options.context; + if (typeof context !== 'object' || context === null) { + throw new TypeError("Invalid `options.context`. Use `import { getDefaultContext } from '@emnapi/runtime'`"); + } + emnapiCtx = context; + } + else { + emnapiCtx = options === null || options === void 0 ? void 0 : options.context; + var postMsg = typeof options.postMessage === 'function' + ? options.postMessage + : typeof postMessage === 'function' + ? postMessage + : undefined; + if (typeof postMsg !== 'function') { + throw new TypeError('No postMessage found'); + } + napiModule.postMessage = postMsg; + } + if (typeof options.filename === 'string') { + napiModule.filename = options.filename; + } + if (typeof options.onCreateWorker === 'function') { + onCreateWorker = options.onCreateWorker; + } + if (typeof options.print === 'function') { + options.print; + } + else { + console.log.bind(console); + } + if (typeof options.printErr === 'function') { + err = options.printErr; + } + else { + err = console.warn.bind(console); + } + if ('nodeBinding' in options) { + var nodeBinding = options.nodeBinding; + if (typeof nodeBinding !== 'object' || nodeBinding === null) { + throw new TypeError('Invalid `options.nodeBinding`. Use @emnapi/node-binding package'); + } + emnapiNodeBinding = nodeBinding; + } + var emnapiAsyncWorkPoolSize = 0; + if ('asyncWorkPoolSize' in options) { + if (typeof options.asyncWorkPoolSize !== 'number') { + throw new TypeError('options.asyncWorkPoolSize must be a integer'); + } + emnapiAsyncWorkPoolSize = options.asyncWorkPoolSize >> 0; + if (emnapiAsyncWorkPoolSize > 1024) { + emnapiAsyncWorkPoolSize = 1024; + } + else if (emnapiAsyncWorkPoolSize < -1024) { + emnapiAsyncWorkPoolSize = -1024; + } + } + var singleThreadAsyncWork = ENVIRONMENT_IS_PTHREAD ? false : (emnapiAsyncWorkPoolSize <= 0); + function _emnapi_async_work_pool_size() { + return Math.abs(emnapiAsyncWorkPoolSize); + } + napiModule.imports.env._emnapi_async_work_pool_size = _emnapi_async_work_pool_size; + // ------------------------------ pthread ------------------------------- + function emnapiAddSendListener(worker) { + if (!worker) + return false; + if (worker._emnapiSendListener) + return true; + var handler = function (e) { + var data = ENVIRONMENT_IS_NODE ? e : e.data; + var __emnapi__ = data.__emnapi__; + if (__emnapi__ && __emnapi__.type === 'async-send') { + if (ENVIRONMENT_IS_PTHREAD) { + var postMessage_1 = napiModule.postMessage; + postMessage_1({ __emnapi__: __emnapi__ }); + } + else { + // eslint-disable-next-line @typescript-eslint/no-unused-vars + var callback = __emnapi__.payload.callback; + (wasmTable.get(callback))(__emnapi__.payload.data); + } + } + }; + var dispose = function () { + if (ENVIRONMENT_IS_NODE) { + worker.off('message', handler); + } + else { + worker.removeEventListener('message', handler, false); + } + delete worker._emnapiSendListener; + }; + worker._emnapiSendListener = { handler: handler, dispose: dispose }; + if (ENVIRONMENT_IS_NODE) { + worker.on('message', handler); + } + else { + worker.addEventListener('message', handler, false); + } + return true; + } + napiModule.emnapi.addSendListener = emnapiAddSendListener; + var PThread = new ThreadManager(ENVIRONMENT_IS_PTHREAD + ? { + printErr: err, + childThread: true + } + : { + printErr: err, + beforeLoad: function (worker) { + emnapiAddSendListener(worker); + }, + reuseWorker: options.reuseWorker, + onCreateWorker: onCreateWorker + }); + napiModule.PThread = PThread; + /** + * @__sig ipiip + */ + function napi_set_last_error(env, error_code, engine_error_code, engine_reserved) { + var envObject = emnapiCtx.envStore.get(env); + return envObject.setLastError(error_code, engine_error_code, engine_reserved); + } + /** + * @__sig ip + */ + function napi_clear_last_error(env) { + var envObject = emnapiCtx.envStore.get(env); + return envObject.clearLastError(); + } + /** + * @__sig vppp + */ + function _emnapi_get_node_version(major, minor, patch) { + major >>>= 0; + minor >>>= 0; + patch >>>= 0; + // eslint-disable-next-line @typescript-eslint/no-unused-vars + var versions = (typeof process === 'object' && process !== null && + typeof process.versions === 'object' && process.versions !== null && + typeof process.versions.node === 'string') + ? process.versions.node.split('.').map(function (n) { return Number(n); }) + : [0, 0, 0]; + var HEAP_DATA_VIEW = new DataView(wasmMemory.buffer), GET_HEAP_DATA_VIEW = function () { return HEAP_DATA_VIEW.buffer === wasmMemory.buffer ? HEAP_DATA_VIEW : (HEAP_DATA_VIEW = new DataView(wasmMemory.buffer)); }; + GET_HEAP_DATA_VIEW().setUint32(major, versions[0], true); + GET_HEAP_DATA_VIEW().setUint32(minor, versions[1], true); + GET_HEAP_DATA_VIEW().setUint32(patch, versions[2], true); + } + /** + * @__sig v + * @__deps $runtimeKeepalivePush + */ + function _emnapi_runtime_keepalive_push() { + } + /** + * @__sig v + * @__deps $runtimeKeepalivePop + */ + function _emnapi_runtime_keepalive_pop() { + } + /** + * @__sig vpp + */ + function _emnapi_set_immediate(callback, data) { + emnapiCtx.feature.setImmediate(function () { + (wasmTable.get(callback))(data); + }); + } + /** + * @__sig vpp + */ + function _emnapi_next_tick(callback, data) { + // eslint-disable-next-line @typescript-eslint/no-floating-promises + Promise.resolve().then(function () { + (wasmTable.get(callback))(data); + }); + } + /** + * @__sig vipppi + */ + function _emnapi_callback_into_module(forceUncaught, env, callback, data, close_scope_if_throw) { + var envObject = emnapiCtx.envStore.get(env); + var scope = emnapiCtx.openScope(envObject); + try { + envObject.callbackIntoModule(Boolean(forceUncaught), function () { + (wasmTable.get(callback))(env, data); + }); + } + catch (err) { + emnapiCtx.closeScope(envObject, scope); + if (close_scope_if_throw) { + emnapiCtx.closeScope(envObject); + } + throw err; + } + emnapiCtx.closeScope(envObject, scope); + } + /** + * @__sig vipppp + */ + function _emnapi_call_finalizer(forceUncaught, env, callback, data, hint) { + var envObject = emnapiCtx.envStore.get(env); + callback >>>= 0; + envObject.callFinalizerInternal(forceUncaught, callback, data, hint); + } + /** + * @__sig v + */ + function _emnapi_ctx_increase_waiting_request_counter() { + emnapiCtx.increaseWaitingRequestCounter(); + } + /** + * @__sig v + */ + function _emnapi_ctx_decrease_waiting_request_counter() { + emnapiCtx.decreaseWaitingRequestCounter(); + } + /** + * @__sig i + */ + function _emnapi_is_main_runtime_thread() { + return ENVIRONMENT_IS_PTHREAD ? 0 : 1; + } + /** + * @__sig i + */ + function _emnapi_is_main_browser_thread() { + return (typeof window !== 'undefined' && typeof document !== 'undefined' && !ENVIRONMENT_IS_NODE) ? 1 : 0; + } + /** + * @__sig v + */ + function _emnapi_unwind() { + // eslint-disable-next-line @typescript-eslint/no-throw-literal + throw 'unwind'; + } + /** + * @__sig d + */ + function _emnapi_get_now() { + return performance.timeOrigin + performance.now(); + } + function $emnapiSetValueI64(result, numberValue) { + var tempDouble; + // eslint-disable-next-line @typescript-eslint/no-unused-vars + var tempI64 = [ + numberValue >>> 0, + (tempDouble = numberValue, +Math.abs(tempDouble) >= 1 ? tempDouble > 0 ? (Math.min(+Math.floor(tempDouble / 4294967296), 4294967295) | 0) >>> 0 : ~~+Math.ceil((tempDouble - +(~~tempDouble >>> 0)) / 4294967296) >>> 0 : 0) + ]; + var HEAP_DATA_VIEW = new DataView(wasmMemory.buffer), GET_HEAP_DATA_VIEW = function () { return HEAP_DATA_VIEW.buffer === wasmMemory.buffer ? HEAP_DATA_VIEW : (HEAP_DATA_VIEW = new DataView(wasmMemory.buffer)); }; + GET_HEAP_DATA_VIEW().setInt32(result, tempI64[0], true); + GET_HEAP_DATA_VIEW().setInt32(result + 4, tempI64[1], true); + } + /** + * @__deps $emnapiCtx + * @__sig p + */ + function _emnapi_open_handle_scope() { + return emnapiCtx.openScope().id; + } + /** + * @__deps $emnapiCtx + * @__sig vp + */ + function _emnapi_close_handle_scope(_scope) { + return emnapiCtx.closeScope(); + } + var utilMod = /*#__PURE__*/ Object.freeze({ + __proto__: null, + $emnapiSetValueI64: $emnapiSetValueI64, + _emnapi_call_finalizer: _emnapi_call_finalizer, + _emnapi_callback_into_module: _emnapi_callback_into_module, + _emnapi_close_handle_scope: _emnapi_close_handle_scope, + _emnapi_ctx_decrease_waiting_request_counter: _emnapi_ctx_decrease_waiting_request_counter, + _emnapi_ctx_increase_waiting_request_counter: _emnapi_ctx_increase_waiting_request_counter, + _emnapi_get_node_version: _emnapi_get_node_version, + _emnapi_get_now: _emnapi_get_now, + _emnapi_is_main_browser_thread: _emnapi_is_main_browser_thread, + _emnapi_is_main_runtime_thread: _emnapi_is_main_runtime_thread, + _emnapi_next_tick: _emnapi_next_tick, + _emnapi_open_handle_scope: _emnapi_open_handle_scope, + _emnapi_runtime_keepalive_pop: _emnapi_runtime_keepalive_pop, + _emnapi_runtime_keepalive_push: _emnapi_runtime_keepalive_push, + _emnapi_set_immediate: _emnapi_set_immediate, + _emnapi_unwind: _emnapi_unwind, + napi_clear_last_error: napi_clear_last_error, + napi_set_last_error: napi_set_last_error + }); + function emnapiGetWorkerByPthreadPtr(pthreadPtr) { + var view = new DataView(wasmMemory.buffer); + /** + * wasi-sdk-20.0+threads + * + * struct pthread { + * struct pthread *self; // 0 + * struct pthread *prev, *next; // 4, 8 + * uintptr_t sysinfo; // 12 + * uintptr_t canary; // 16 + * int tid; // 20 + * // ... + * } + */ + var tidOffset = 20; + var tid = view.getInt32(pthreadPtr + tidOffset, true); + var worker = PThread.pthreads[tid]; + return worker; + } + /** @__sig vp */ + function _emnapi_worker_ref(pthreadPtr) { + if (ENVIRONMENT_IS_PTHREAD) + return; + pthreadPtr >>>= 0; + var worker = emnapiGetWorkerByPthreadPtr(pthreadPtr); + if (worker && typeof worker.ref === 'function') { + worker.ref(); + } + } + /** @__sig vp */ + function _emnapi_worker_unref(pthreadPtr) { + if (ENVIRONMENT_IS_PTHREAD) + return; + pthreadPtr >>>= 0; + var worker = emnapiGetWorkerByPthreadPtr(pthreadPtr); + if (worker && typeof worker.unref === 'function') { + worker.unref(); + } + } + /** @__sig vipp */ + function _emnapi_async_send_js(type, callback, data) { + if (ENVIRONMENT_IS_PTHREAD) { + var postMessage_1 = napiModule.postMessage; + postMessage_1({ + __emnapi__: { + type: 'async-send', + payload: { + callback: callback, + data: data + } + } + }); + } + else { + switch (type) { + case 0: + _emnapi_set_immediate(callback, data); + break; + case 1: + _emnapi_next_tick(callback, data); + break; + } + } + } + // function ptrToString (ptr: number): string { + // return '0x' + ('00000000' + ptr.toString(16)).slice(-8) + // } + var uvThreadpoolReadyResolve; + var uvThreadpoolReady = new Promise(function (resolve) { + uvThreadpoolReadyResolve = function () { + uvThreadpoolReady.ready = true; + resolve(); + }; + }); + uvThreadpoolReady.ready = false; + /** @__sig vppi */ + function _emnapi_after_uvthreadpool_ready(callback, q, type) { + if (uvThreadpoolReady.ready) { + (wasmTable.get(callback))(q, type); + } + else { + uvThreadpoolReady.then(function () { + (wasmTable.get(callback))(q, type); + }); + } + } + /** @__sig vpi */ + function _emnapi_tell_js_uvthreadpool(threads, size) { + var p = []; + var HEAP_DATA_VIEW = new DataView(wasmMemory.buffer), GET_HEAP_DATA_VIEW = function () { return HEAP_DATA_VIEW.buffer === wasmMemory.buffer ? HEAP_DATA_VIEW : (HEAP_DATA_VIEW = new DataView(wasmMemory.buffer)); }; + var _loop_1 = function (i) { + var pthreadPtr = GET_HEAP_DATA_VIEW().getUint32(threads + i * 4, true); + var worker = emnapiGetWorkerByPthreadPtr(pthreadPtr); + p.push(new Promise(function (resolve) { + var handler = function (e) { + var data = ENVIRONMENT_IS_NODE ? e : e.data; + var __emnapi__ = data.__emnapi__; + if (__emnapi__ && __emnapi__.type === 'async-thread-ready') { + resolve(); + if (worker && typeof worker.unref === 'function') { + worker.unref(); + } + if (ENVIRONMENT_IS_NODE) { + worker.off('message', handler); + } + else { + worker.removeEventListener('message', handler); + } + } + }; + if (ENVIRONMENT_IS_NODE) { + worker.on('message', handler); + } + else { + worker.addEventListener('message', handler); + } + })); + }; + for (var i = 0; i < size; i++) { + _loop_1(i); + } + Promise.all(p).then(uvThreadpoolReadyResolve); + } + /** @__sig v */ + function _emnapi_emit_async_thread_ready() { + if (!ENVIRONMENT_IS_PTHREAD) + return; + var postMessage = napiModule.postMessage; + postMessage({ + __emnapi__: { + type: 'async-thread-ready', + payload: {} + } + }); + } + var asyncMod = /*#__PURE__*/ Object.freeze({ + __proto__: null, + _emnapi_after_uvthreadpool_ready: _emnapi_after_uvthreadpool_ready, + _emnapi_async_send_js: _emnapi_async_send_js, + _emnapi_emit_async_thread_ready: _emnapi_emit_async_thread_ready, + _emnapi_tell_js_uvthreadpool: _emnapi_tell_js_uvthreadpool, + _emnapi_worker_ref: _emnapi_worker_ref, + _emnapi_worker_unref: _emnapi_worker_unref + }); + /** @__sig ipjp */ + function napi_adjust_external_memory(env, change_in_bytes, adjusted_value) { + if (!env) + return 1 /* napi_status.napi_invalid_arg */; + var envObject = emnapiCtx.envStore.get(env); + if (!adjusted_value) + return envObject.setLastError(1 /* napi_status.napi_invalid_arg */); + // eslint-disable-next-line prefer-const + var adjusted_memory = emnapiCtx.adjustAmountOfExternalAllocatedMemory(change_in_bytes); + adjusted_value >>>= 0; + if (emnapiCtx.feature.supportBigInt) { + var HEAP_DATA_VIEW = new DataView(wasmMemory.buffer), GET_HEAP_DATA_VIEW = function () { return HEAP_DATA_VIEW.buffer === wasmMemory.buffer ? HEAP_DATA_VIEW : (HEAP_DATA_VIEW = new DataView(wasmMemory.buffer)); }; + GET_HEAP_DATA_VIEW().setBigInt64(adjusted_value, BigInt(adjusted_memory), true); + } + else { + $emnapiSetValueI64(adjusted_value, Number(adjusted_memory)); + } + return envObject.clearLastError(); + } + var memoryMod = /*#__PURE__*/ Object.freeze({ + __proto__: null, + napi_adjust_external_memory: napi_adjust_external_memory + }); + /** + * @__postset + * ``` + * emnapiAWST.init(); + * ``` + */ + var emnapiAWST = { + idGen: {}, + values: [undefined], + queued: new Set(), + pending: [], + init: function () { + var idGen = { + nextId: 1, + list: [], + generate: function () { + var id; + if (idGen.list.length) { + id = idGen.list.shift(); + } + else { + id = idGen.nextId; + idGen.nextId++; + } + return id; + }, + reuse: function (id) { + idGen.list.push(id); + } + }; + emnapiAWST.idGen = idGen; + emnapiAWST.values = [undefined]; + emnapiAWST.queued = new Set(); + emnapiAWST.pending = []; + }, + create: function (env, resource, resourceName, execute, complete, data) { + var asyncId = 0; + var triggerAsyncId = 0; + if (emnapiNodeBinding) { + var asyncContext = emnapiNodeBinding.node.emitAsyncInit(resource, resourceName, -1); + asyncId = asyncContext.asyncId; + triggerAsyncId = asyncContext.triggerAsyncId; + } + var id = emnapiAWST.idGen.generate(); + emnapiAWST.values[id] = { + env: env, + id: id, + resource: resource, + asyncId: asyncId, + triggerAsyncId: triggerAsyncId, + status: 0, + execute: execute, + complete: complete, + data: data + }; + return id; + }, + callComplete: function (work, status) { + // eslint-disable-next-line @typescript-eslint/no-unused-vars + var complete = work.complete; + var env = work.env; + var data = work.data; + var callback = function () { + if (!complete) + return; + var envObject = emnapiCtx.envStore.get(env); + var scope = emnapiCtx.openScope(envObject); + try { + envObject.callbackIntoModule(true, function () { + (wasmTable.get(complete))(env, status, data); + }); + } + finally { + emnapiCtx.closeScope(envObject, scope); + } + }; + if (emnapiNodeBinding) { + emnapiNodeBinding.node.makeCallback(work.resource, callback, [], { + asyncId: work.asyncId, + triggerAsyncId: work.triggerAsyncId + }); + } + else { + callback(); + } + }, + queue: function (id) { + var work = emnapiAWST.values[id]; + if (!work) + return; + if (work.status === 0) { + work.status = 1; + if (emnapiAWST.queued.size >= (Math.abs(emnapiAsyncWorkPoolSize) || 4)) { + emnapiAWST.pending.push(id); + return; + } + emnapiAWST.queued.add(id); + var env_1 = work.env; + var data_1 = work.data; + // eslint-disable-next-line @typescript-eslint/no-unused-vars + var execute = work.execute; + work.status = 2; + emnapiCtx.feature.setImmediate(function () { + (wasmTable.get(execute))(env_1, data_1); + emnapiAWST.queued.delete(id); + work.status = 3; + emnapiCtx.feature.setImmediate(function () { + emnapiAWST.callComplete(work, 0 /* napi_status.napi_ok */); + }); + if (emnapiAWST.pending.length > 0) { + var nextWorkId = emnapiAWST.pending.shift(); + emnapiAWST.values[nextWorkId].status = 0; + emnapiAWST.queue(nextWorkId); + } + }); + } + }, + cancel: function (id) { + var index = emnapiAWST.pending.indexOf(id); + if (index !== -1) { + var work_1 = emnapiAWST.values[id]; + if (work_1 && (work_1.status === 1)) { + work_1.status = 4; + emnapiAWST.pending.splice(index, 1); + emnapiCtx.feature.setImmediate(function () { + emnapiAWST.callComplete(work_1, 11 /* napi_status.napi_cancelled */); + }); + return 0 /* napi_status.napi_ok */; + } + else { + return 9 /* napi_status.napi_generic_failure */; + } + } + return 9 /* napi_status.napi_generic_failure */; + }, + remove: function (id) { + var work = emnapiAWST.values[id]; + if (!work) + return; + if (emnapiNodeBinding) { + emnapiNodeBinding.node.emitAsyncDestroy({ + asyncId: work.asyncId, + triggerAsyncId: work.triggerAsyncId + }); + } + emnapiAWST.values[id] = undefined; + emnapiAWST.idGen.reuse(id); + } + }; + /** @__sig vppdp */ + function _emnapi_node_emit_async_init(async_resource, async_resource_name, trigger_async_id, result) { + if (!emnapiNodeBinding) + return; + var resource = emnapiCtx.handleStore.get(async_resource).value; + var resource_name = emnapiCtx.handleStore.get(async_resource_name).value; + var asyncContext = emnapiNodeBinding.node.emitAsyncInit(resource, resource_name, trigger_async_id); + // eslint-disable-next-line @typescript-eslint/no-unused-vars + var asyncId = asyncContext.asyncId; + var triggerAsyncId = asyncContext.triggerAsyncId; + if (result) { + result >>>= 0; + var HEAP_DATA_VIEW = new DataView(wasmMemory.buffer), GET_HEAP_DATA_VIEW = function () { return HEAP_DATA_VIEW.buffer === wasmMemory.buffer ? HEAP_DATA_VIEW : (HEAP_DATA_VIEW = new DataView(wasmMemory.buffer)); }; + GET_HEAP_DATA_VIEW().setFloat64(result, asyncId, true); + GET_HEAP_DATA_VIEW().setFloat64(result + 8, triggerAsyncId, true); + } + } + /** @__sig vdd */ + function _emnapi_node_emit_async_destroy(async_id, trigger_async_id) { + if (!emnapiNodeBinding) + return; + emnapiNodeBinding.node.emitAsyncDestroy({ + asyncId: async_id, + triggerAsyncId: trigger_async_id + }); + } + /* vpddp export function _emnapi_node_open_callback_scope (async_resource: napi_value, async_id: double, trigger_async_id: double, result: Pointer): void { + if (!emnapiNodeBinding || !result) return + const resource = emnapiCtx.handleStore.get(async_resource)!.value + // eslint-disable-next-line @typescript-eslint/no-unused-vars + const nativeCallbackScopePointer = emnapiNodeBinding.node.openCallbackScope(resource, { + asyncId: async_id, + triggerAsyncId: trigger_async_id + }) + + from64('result') + $_TODO_makeSetValue('result', 0, 'nativeCallbackScopePointer', 'i64') + } + + vp + export function _emnapi_node_close_callback_scope (scope: Pointer): void { + if (!emnapiNodeBinding || !scope) return + from64('scope') + const nativeCallbackScopePointer = $_TODO_makeGetValue('scope', 0, 'i64') + emnapiNodeBinding.node.closeCallbackScope(BigInt(nativeCallbackScopePointer)) + } */ + /** @__sig ipppppddp */ + function _emnapi_node_make_callback(env, async_resource, cb, argv, size, async_id, trigger_async_id, result) { + var i = 0; + // eslint-disable-next-line @typescript-eslint/no-unused-vars + var v; + if (!emnapiNodeBinding) + return; + var resource = emnapiCtx.handleStore.get(async_resource).value; + var callback = emnapiCtx.handleStore.get(cb).value; + argv >>>= 0; + size >>>= 0; + size = size >>> 0; + var arr = Array(size); + var HEAP_DATA_VIEW = new DataView(wasmMemory.buffer), GET_HEAP_DATA_VIEW = function () { return HEAP_DATA_VIEW.buffer === wasmMemory.buffer ? HEAP_DATA_VIEW : (HEAP_DATA_VIEW = new DataView(wasmMemory.buffer)); }; + for (; i < size; i++) { + var argVal = GET_HEAP_DATA_VIEW().getUint32(argv + i * 4, true); + arr[i] = emnapiCtx.handleStore.get(argVal).value; + } + var ret = emnapiNodeBinding.node.makeCallback(resource, callback, arr, { + asyncId: async_id, + triggerAsyncId: trigger_async_id + }); + if (result) { + result >>>= 0; + var envObject = emnapiCtx.envStore.get(env); + // eslint-disable-next-line @typescript-eslint/no-unused-vars + v = envObject.ensureHandleId(ret); + GET_HEAP_DATA_VIEW().setUint32(result, v, true); + } + } + /** @__sig ippp */ + function _emnapi_async_init_js(async_resource, async_resource_name, result) { + if (!emnapiNodeBinding) { + return 9 /* napi_status.napi_generic_failure */; + } + var resource; + if (async_resource) { + resource = Object(emnapiCtx.handleStore.get(async_resource).value); + } + var name = emnapiCtx.handleStore.get(async_resource_name).value; + var ret = emnapiNodeBinding.napi.asyncInit(resource, name); + if (ret.status !== 0) + return ret.status; + var numberValue = ret.value; + if (!((numberValue >= (BigInt(-1) * (BigInt(1) << BigInt(63)))) && (numberValue < (BigInt(1) << BigInt(63))))) { + numberValue = numberValue & ((BigInt(1) << BigInt(64)) - BigInt(1)); + if (numberValue >= (BigInt(1) << BigInt(63))) { + numberValue = numberValue - (BigInt(1) << BigInt(64)); + } + } + // eslint-disable-next-line @typescript-eslint/no-unused-vars + var low = Number(numberValue & BigInt(0xffffffff)); + // eslint-disable-next-line @typescript-eslint/no-unused-vars + var high = Number(numberValue >> BigInt(32)); + result >>>= 0; + var HEAP_DATA_VIEW = new DataView(wasmMemory.buffer), GET_HEAP_DATA_VIEW = function () { return HEAP_DATA_VIEW.buffer === wasmMemory.buffer ? HEAP_DATA_VIEW : (HEAP_DATA_VIEW = new DataView(wasmMemory.buffer)); }; + GET_HEAP_DATA_VIEW().setInt32(result, low, true); + GET_HEAP_DATA_VIEW().setInt32(result + 4, high, true); + return 0 /* napi_status.napi_ok */; + } + /** @__sig ip */ + function _emnapi_async_destroy_js(async_context) { + if (!emnapiNodeBinding) { + return 9 /* napi_status.napi_generic_failure */; + } + async_context >>>= 0; + var HEAP_DATA_VIEW = new DataView(wasmMemory.buffer), GET_HEAP_DATA_VIEW = function () { return HEAP_DATA_VIEW.buffer === wasmMemory.buffer ? HEAP_DATA_VIEW : (HEAP_DATA_VIEW = new DataView(wasmMemory.buffer)); }; + var low = GET_HEAP_DATA_VIEW().getInt32(async_context, true); + var high = GET_HEAP_DATA_VIEW().getInt32(async_context + 4, true); + var pointer = BigInt(low >>> 0) | (BigInt(high) << BigInt(32)); + var ret = emnapiNodeBinding.napi.asyncDestroy(pointer); + if (ret.status !== 0) + return ret.status; + return 0 /* napi_status.napi_ok */; + } + // https://github.com/nodejs/node-addon-api/pull/1283 + /** @__sig ipppp */ + function napi_open_callback_scope(env, ignored, async_context_handle, result) { + throw new Error('napi_open_callback_scope has not been implemented yet'); + } + /** @__sig ipp */ + function napi_close_callback_scope(env, scope) { + throw new Error('napi_close_callback_scope has not been implemented yet'); + } + /** @__sig ippppppp */ + function napi_make_callback(env, async_context, recv, func, argc, argv, result) { + var i = 0; + // eslint-disable-next-line @typescript-eslint/no-unused-vars + var v; + if (!env) + return 1 /* napi_status.napi_invalid_arg */; + // @ts-expect-error + var envObject = emnapiCtx.envStore.get(env); + envObject.checkGCAccess(); + if (!envObject.tryCatch.isEmpty()) + return envObject.setLastError(10 /* napi_status.napi_pending_exception */); + if (!envObject.canCallIntoJs()) + return envObject.setLastError(envObject.moduleApiVersion >= 10 ? 23 /* napi_status.napi_cannot_run_js */ : 10 /* napi_status.napi_pending_exception */); + envObject.clearLastError(); + try { + if (!emnapiNodeBinding) { + return envObject.setLastError(9 /* napi_status.napi_generic_failure */); + } + if (!recv) + return envObject.setLastError(1 /* napi_status.napi_invalid_arg */); + if (argc > 0) { + if (!argv) + return envObject.setLastError(1 /* napi_status.napi_invalid_arg */); + } + var v8recv = Object(emnapiCtx.handleStore.get(recv).value); + var v8func = emnapiCtx.handleStore.get(func).value; + if (typeof v8func !== 'function') { + return envObject.setLastError(1 /* napi_status.napi_invalid_arg */); + } + async_context >>>= 0; + var HEAP_DATA_VIEW = new DataView(wasmMemory.buffer), GET_HEAP_DATA_VIEW = function () { return HEAP_DATA_VIEW.buffer === wasmMemory.buffer ? HEAP_DATA_VIEW : (HEAP_DATA_VIEW = new DataView(wasmMemory.buffer)); }; + var low = GET_HEAP_DATA_VIEW().getInt32(async_context, true); + var high = GET_HEAP_DATA_VIEW().getInt32(async_context + 4, true); + var ctx = BigInt(low >>> 0) | (BigInt(high) << BigInt(32)); + argv >>>= 0; + argc >>>= 0; + argc = argc >>> 0; + var arr = Array(argc); + for (; i < argc; i++) { + var argVal = GET_HEAP_DATA_VIEW().getUint32(argv + i * 4, true); + arr[i] = emnapiCtx.handleStore.get(argVal).value; + } + var ret = emnapiNodeBinding.napi.makeCallback(ctx, v8recv, v8func, arr); + if (ret.error) { + throw ret.error; + } + if (ret.status !== 0 /* napi_status.napi_ok */) + return envObject.setLastError(ret.status); + if (result) { + result >>>= 0; + // The makeCallback call into JS above may have grown wasm memory: + // resolve v before the write (the store target is evaluated before the + // RHS, so an RHS running user JS could write through a stale heap view) + // eslint-disable-next-line @typescript-eslint/no-unused-vars + v = envObject.ensureHandleId(ret.value); + GET_HEAP_DATA_VIEW().setUint32(result, v, true); + } + return envObject.getReturnStatus(); + } + catch (err) { + envObject.tryCatch.setError(err); + return envObject.setLastError(10 /* napi_status.napi_pending_exception */); + } + } + /** @__sig vp */ + function _emnapi_env_check_gc_access(env) { + var envObject = emnapiCtx.envStore.get(env); + envObject.checkGCAccess(); + } + var nodeMod = /*#__PURE__*/ Object.freeze({ + __proto__: null, + _emnapi_async_destroy_js: _emnapi_async_destroy_js, + _emnapi_async_init_js: _emnapi_async_init_js, + _emnapi_env_check_gc_access: _emnapi_env_check_gc_access, + _emnapi_node_emit_async_destroy: _emnapi_node_emit_async_destroy, + _emnapi_node_emit_async_init: _emnapi_node_emit_async_init, + _emnapi_node_make_callback: _emnapi_node_make_callback, + napi_close_callback_scope: napi_close_callback_scope, + napi_make_callback: napi_make_callback, + napi_open_callback_scope: napi_open_callback_scope + }); + /** + * @__deps malloc + * @__deps free + * @__postset + * ``` + * emnapiTSFN.init(); + * ``` + */ + var emnapiTSFN = { + _liveSet: {}, + offset: { + __size__: 0, + /* napi_ref */ resource: 0, + /* double */ async_id: 0, + /* double */ trigger_async_id: 0, + /* size_t */ queue_size: 0, + /* bool */ is_some: 0, + /* void* */ queue: 0, + // Reuse uv_async_t storage as JS-side wakeup state: pending event + scheduled drain. + async_pending: 0, + async_u_fd: 0, + /* size_t */ thread_count: 0, + /* int32_t */ state: 0, + /* atomic_uchar */ dispatch_state: 0, + /* void* */ context: 0, + /* size_t */ max_queue_size: 0, + /* napi_ref */ ref: 0, + /* napi_env */ env: 0, + /* void* */ finalize_data: 0, + /* napi_finalize */ finalize_cb: 0, + /* napi_threadsafe_function_call_js */ call_js_cb: 0, + /* bool */ handles_closing: 0, + /* bool */ async_ref: 0, + /* int32_t */ mutex: 0, + /* int32_t */ cond: 0 + }, + init: function () { + emnapiTSFN._liveSet = new Set(); + emnapiTSFN.offset.__size__ = 184 /* NapiTSFNOffset32.__size__ */; + emnapiTSFN.offset.resource = 0 /* NapiTSFNOffset32.async_resource_resource */; + emnapiTSFN.offset.async_id = 8 /* NapiTSFNOffset32.async_resource_async_context_async_id */; + emnapiTSFN.offset.trigger_async_id = 16 /* NapiTSFNOffset32.async_resource_async_context_trigger_async_id */; + emnapiTSFN.offset.queue_size = 60 /* NapiTSFNOffset32.queue_size */; + emnapiTSFN.offset.is_some = 24 /* NapiTSFNOffset32.async_resource_is_some */; + emnapiTSFN.offset.queue = 64 /* NapiTSFNOffset32.queue */; + emnapiTSFN.offset.async_pending = 132 /* NapiTSFNOffset32.async_pending */; + emnapiTSFN.offset.async_u_fd = 96 /* NapiTSFNOffset32.async_u_fd */; + emnapiTSFN.offset.thread_count = 136 /* NapiTSFNOffset32.thread_count */; + emnapiTSFN.offset.state = 140 /* NapiTSFNOffset32.state */; + emnapiTSFN.offset.dispatch_state = 144 /* NapiTSFNOffset32.dispatch_state */; + emnapiTSFN.offset.context = 148 /* NapiTSFNOffset32.context */; + emnapiTSFN.offset.max_queue_size = 152 /* NapiTSFNOffset32.max_queue_size */; + emnapiTSFN.offset.ref = 156 /* NapiTSFNOffset32.ref */; + emnapiTSFN.offset.env = 160 /* NapiTSFNOffset32.env */; + emnapiTSFN.offset.finalize_data = 164 /* NapiTSFNOffset32.finalize_data */; + emnapiTSFN.offset.finalize_cb = 168 /* NapiTSFNOffset32.finalize_cb */; + emnapiTSFN.offset.call_js_cb = 172 /* NapiTSFNOffset32.call_js_cb */; + emnapiTSFN.offset.handles_closing = 176 /* NapiTSFNOffset32.handles_closing */; + emnapiTSFN.offset.async_ref = 180 /* NapiTSFNOffset32.async_ref */; + emnapiTSFN.offset.mutex = 32 /* NapiTSFNOffset32.mutex */; + emnapiTSFN.offset.cond = 56 /* NapiTSFNOffset32.cond */; + emnapiTSFN.offset.mutex = emnapiTSFN.offset.mutex + 4; + if (typeof PThread !== 'undefined') { + PThread.unusedWorkers.forEach(emnapiTSFN.addListener); + Object.values(PThread.pthreads).forEach(emnapiTSFN.addListener); + var __original_getNewWorker_1 = PThread.getNewWorker; + PThread.getNewWorker = function () { + var r = __original_getNewWorker_1.apply(this, arguments); + emnapiTSFN.addListener(r); + return r; + }; + } + }, + addListener: function (worker) { + if (!worker) + return false; + if (worker._emnapiTSFNListener) + return true; + var handler = function (e) { + var data = ENVIRONMENT_IS_NODE ? e : e.data; + var __emnapi__ = data.__emnapi__; + if (__emnapi__) { + var type = __emnapi__.type; + var payload = __emnapi__.payload; + if (type === 'tsfn-send') { + var pendng = payload.tsfn + emnapiTSFN.offset.async_pending; + if (Atomics.load(new Int32Array(emnapiTSFN.ensureBufferFor(pendng + 4)), pendng >>> 2) !== 0) { + emnapiTSFN.enqueue(payload.tsfn); + } + } + } + }; + var dispose = function () { + if (ENVIRONMENT_IS_NODE) { + worker.off('message', handler); + } + else { + worker.removeEventListener('message', handler, false); + } + delete worker._emnapiTSFNListener; + }; + worker._emnapiTSFNListener = { handler: handler, dispose: dispose }; + if (ENVIRONMENT_IS_NODE) { + worker.on('message', handler); + } + else { + worker.addEventListener('message', handler, false); + } + return true; + }, + /** + * When another thread grows the shared WebAssembly.Memory, this agent's + * cached `wasmMemory.buffer` may still have the old shorter length + * (V8 refreshes it lazily). If a pointer derived from shared memory lies + * beyond the cached length, `wasmMemory.grow(0)` forces the agent to + * observe the current memory size and refreshes the buffer. + */ + ensureBufferFor: function (end) { + var buffer = wasmMemory.buffer; + if (end > buffer.byteLength) { + wasmMemory.grow(0); + buffer = wasmMemory.buffer; + } + return buffer; + }, + initQueue: function (func) { + var size = 2 * 4; + var queue = _malloc(size); + if (!queue) + return false; + queue >>>= 0; + new Uint8Array(emnapiTSFN.ensureBufferFor(queue + size), queue, size).fill(0); + emnapiTSFN.storeSizeTypeValue(func + emnapiTSFN.offset.queue, queue, false); + return true; + }, + destroyQueue: function (func) { + var queue = emnapiTSFN.loadSizeTypeValue(func + emnapiTSFN.offset.queue, false); + if (queue) { + var node = emnapiTSFN.loadSizeTypeValue(queue, false); + while (node !== 0) { + var next = emnapiTSFN.loadSizeTypeValue(node + 4, false); + _free(node); + node = next; + } + _free(queue); + } + }, + pushQueue: function (func, data) { + var queue = emnapiTSFN.loadSizeTypeValue(func + emnapiTSFN.offset.queue, false); + var head = emnapiTSFN.loadSizeTypeValue(queue, false); + var tail = emnapiTSFN.loadSizeTypeValue(queue + 4, false); + // eslint-disable-next-line @typescript-eslint/no-unused-vars + var size = 2 * 4; + var node = _malloc(size); + if (!node) + throw new Error('OOM'); + node >>>= 0; + emnapiTSFN.storeSizeTypeValue(node, data, false); + emnapiTSFN.storeSizeTypeValue(node + 4, 0, false); + if (head === 0 && tail === 0) { + emnapiTSFN.storeSizeTypeValue(queue, node, false); + emnapiTSFN.storeSizeTypeValue(queue + 4, node, false); + } + else { + emnapiTSFN.storeSizeTypeValue(tail + 4, node, false); + emnapiTSFN.storeSizeTypeValue(queue + 4, node, false); + } + emnapiTSFN.addQueueSize(func); + }, + shiftQueue: function (func) { + var queue = emnapiTSFN.loadSizeTypeValue(func + emnapiTSFN.offset.queue, false); + var head = emnapiTSFN.loadSizeTypeValue(queue, false); + if (head === 0) + return 0; + var node = head; + var next = emnapiTSFN.loadSizeTypeValue(head + 4, false); + emnapiTSFN.storeSizeTypeValue(queue, next, false); + if (next === 0) { + emnapiTSFN.storeSizeTypeValue(queue + 4, 0, false); + } + emnapiTSFN.storeSizeTypeValue(node + 4, 0, false); + var value = emnapiTSFN.loadSizeTypeValue(node, false); + _free(node); + emnapiTSFN.subQueueSize(func); + return value; + }, + push: function (func, data, mode) { + var mutex = emnapiTSFN.getMutex(func); + var cond = emnapiTSFN.getCond(func); + var waitCondition = function () { + var queueSize = emnapiTSFN.getQueueSize(func); + var maxSize = emnapiTSFN.getMaxQueueSize(func); + return queueSize >= maxSize && maxSize > 0 && emnapiTSFN.getState(func) === 0 /* State.kOpen */; + }; + var isBrowserMain = typeof window !== 'undefined' && typeof document !== 'undefined' && !ENVIRONMENT_IS_NODE; + var shouldDelete = false; + var ret = mutex.execute(function () { + while (waitCondition()) { + if (mode === 0 /* napi_threadsafe_function_call_mode.napi_tsfn_nonblocking */) { + return 15 /* napi_status.napi_queue_full */; + } + /** + * Browser JS main thread can not use `Atomics.wait` + * + * Related: + * https://github.com/nodejs/node/pull/32689 + * https://github.com/nodejs/node/pull/33453 + */ + if (isBrowserMain) { + return 21 /* napi_status.napi_would_deadlock */; + } + cond.wait(); + } + if (emnapiTSFN.getState(func) === 0 /* State.kOpen */) { + emnapiTSFN.pushQueue(func, data); + emnapiTSFN.send(func); + return 0 /* napi_status.napi_ok */; + } + if (emnapiTSFN.getThreadCount(func) === 0) { + return 1 /* napi_status.napi_invalid_arg */; + } + emnapiTSFN.subThreadCount(func); + if (!(emnapiTSFN.getState(func) === 2 /* State.kClosed */ && emnapiTSFN.getThreadCount(func) === 0)) { + return 16 /* napi_status.napi_closing */; + } + shouldDelete = true; + return 16 /* napi_status.napi_closing */; + }); + if (shouldDelete) { + emnapiTSFN.destroy(func); + } + return ret; + }, + getMutex: function (func) { + var index = func + emnapiTSFN.offset.mutex; + var mutex = { + lock: function () { + var isBrowserMain = typeof window !== 'undefined' && typeof document !== 'undefined' && !ENVIRONMENT_IS_NODE; + var i32a = new Int32Array(emnapiTSFN.ensureBufferFor(index + 4), index, 1); + if (isBrowserMain) { + while (true) { + var oldValue = Atomics.compareExchange(i32a, 0, 0, 10); + if (oldValue === 0) { + return; + } + } + } + else { + while (true) { + var oldValue = Atomics.compareExchange(i32a, 0, 0, 10); + if (oldValue === 0) { + return; + } + Atomics.wait(i32a, 0, 10); + } + } + }, + /* lockAsync () { + return new Promise(resolve => { + const again = (): void => { fn() } + const fn = (): void => { + const i32a = new Int32Array(emnapiTSFN.ensureBufferFor(index + 4), index, 1) + const oldValue = Atomics.compareExchange(i32a, 0, 0, 10) + if (oldValue === 0) { + resolve() + return + } + (Atomics as any).waitAsync(i32a, 0, 10).value.then(again) + } + fn() + }) + }, */ + unlock: function () { + var i32a = new Int32Array(emnapiTSFN.ensureBufferFor(index + 4), index, 1); + var oldValue = Atomics.compareExchange(i32a, 0, 10, 0); + if (oldValue !== 10) { + throw new Error('Tried to unlock while not holding the mutex'); + } + Atomics.notify(i32a, 0, 1); + }, + execute: function (fn) { + mutex.lock(); + try { + return fn(); + } + finally { + mutex.unlock(); + } + } /* , + executeAsync (fn: () => Promise): Promise { + return mutex.lockAsync().then(() => { + const r = fn() + mutex.unlock() + return r + }, (err) => { + mutex.unlock() + throw err + }) + } */ + }; + return mutex; + }, + getCond: function (func) { + var index = func + emnapiTSFN.offset.cond; + var mutex = emnapiTSFN.getMutex(func); + var cond = { + wait: function () { + var i32a = new Int32Array(emnapiTSFN.ensureBufferFor(index + 4), index, 1); + var value = Atomics.load(i32a, 0); + mutex.unlock(); + Atomics.wait(i32a, 0, value); + mutex.lock(); + }, + /* waitAsync () { + const i32a = new Int32Array(emnapiTSFN.ensureBufferFor(index + 4), index, 1) + const value = Atomics.load(i32a, 0) + mutex.unlock() + const lock = (): Promise => mutex.lockAsync() + try { + return (Atomics as any).waitAsync(i32a, 0, value).value.then(lock, lock) + } catch (err) { + return lock() + } + }, */ + signal: function () { + var i32a = new Int32Array(emnapiTSFN.ensureBufferFor(index + 4), index, 1); + Atomics.add(i32a, 0, 1); + Atomics.notify(i32a, 0, 1); + } + }; + return cond; + }, + getQueueSize: function (func) { + return emnapiTSFN.loadSizeTypeValue(func + emnapiTSFN.offset.queue_size, true); + }, + addQueueSize: function (func) { + var offset = emnapiTSFN.offset.queue_size; + var arr, index; + arr = new Uint32Array(emnapiTSFN.ensureBufferFor(func + offset + 4)); + index = (func + offset) >>> 2; + Atomics.add(arr, index, 1); + }, + subQueueSize: function (func) { + var offset = emnapiTSFN.offset.queue_size; + var arr, index; + arr = new Uint32Array(emnapiTSFN.ensureBufferFor(func + offset + 4)); + index = (func + offset) >>> 2; + Atomics.sub(arr, index, 1); + }, + getThreadCount: function (func) { + return emnapiTSFN.loadSizeTypeValue(func + emnapiTSFN.offset.thread_count, true); + }, + addThreadCount: function (func) { + var offset = emnapiTSFN.offset.thread_count; + var arr, index; + arr = new Uint32Array(emnapiTSFN.ensureBufferFor(func + offset + 4)); + index = (func + offset) >>> 2; + Atomics.add(arr, index, 1); + }, + subThreadCount: function (func) { + var offset = emnapiTSFN.offset.thread_count; + var arr, index; + arr = new Uint32Array(emnapiTSFN.ensureBufferFor(func + offset + 4)); + index = (func + offset) >>> 2; + Atomics.sub(arr, index, 1); + }, + getState: function (func) { + return Atomics.load(new Int32Array(emnapiTSFN.ensureBufferFor(func + emnapiTSFN.offset.state + 4)), (func + emnapiTSFN.offset.state) >>> 2); + }, + setState: function (func, value) { + Atomics.store(new Int32Array(emnapiTSFN.ensureBufferFor(func + emnapiTSFN.offset.state + 4)), (func + emnapiTSFN.offset.state) >>> 2, value); + }, + getHandlesClosing: function (func) { + return Atomics.load(new Int8Array(emnapiTSFN.ensureBufferFor(func + emnapiTSFN.offset.handles_closing + 1)), (func + emnapiTSFN.offset.handles_closing)); + }, + setHandlesClosing: function (func, value) { + Atomics.store(new Int8Array(emnapiTSFN.ensureBufferFor(func + emnapiTSFN.offset.handles_closing + 1)), (func + emnapiTSFN.offset.handles_closing), value); + }, + getDispatchState: function (func) { + return Atomics.load(new Uint32Array(emnapiTSFN.ensureBufferFor(func + emnapiTSFN.offset.dispatch_state + 4)), (func + emnapiTSFN.offset.dispatch_state) >>> 2); + }, + getContext: function (func) { + return emnapiTSFN.loadSizeTypeValue(func + emnapiTSFN.offset.context, false); + }, + getMaxQueueSize: function (func) { + return emnapiTSFN.loadSizeTypeValue(func + emnapiTSFN.offset.max_queue_size, true); + }, + getEnv: function (func) { + return emnapiTSFN.loadSizeTypeValue(func + emnapiTSFN.offset.env, false); + }, + getCallJSCb: function (func) { + return emnapiTSFN.loadSizeTypeValue(func + emnapiTSFN.offset.call_js_cb, false); + }, + getRef: function (func) { + return emnapiTSFN.loadSizeTypeValue(func + emnapiTSFN.offset.ref, false); + }, + getResource: function (func) { + return emnapiTSFN.loadSizeTypeValue(func + emnapiTSFN.offset.resource, false); + }, + getFinalizeCb: function (func) { + return emnapiTSFN.loadSizeTypeValue(func + emnapiTSFN.offset.finalize_cb, false); + }, + getFinalizeData: function (func) { + return emnapiTSFN.loadSizeTypeValue(func + emnapiTSFN.offset.finalize_data, false); + }, + loadSizeTypeValue: function (offset, unsigned) { + var ret; + var arr; + if (unsigned) { + arr = new Uint32Array(emnapiTSFN.ensureBufferFor(offset + 4)); + ret = Atomics.load(arr, offset >>> 2); + return ret; + } + else { + arr = new Int32Array(emnapiTSFN.ensureBufferFor(offset + 4)); + ret = Atomics.load(arr, offset >>> 2); + return ret; + } + }, + storeSizeTypeValue: function (offset, value, unsigned) { + var arr; + if (unsigned) { + arr = new Uint32Array(emnapiTSFN.ensureBufferFor(offset + 4)); + Atomics.store(arr, offset >>> 2, value); + return undefined; + } + else { + arr = new Int32Array(emnapiTSFN.ensureBufferFor(offset + 4)); + Atomics.store(arr, offset >>> 2, value >>> 0); + return undefined; + } + }, + releaseResources: function (func) { + if (emnapiTSFN.getState(func) !== 2 /* State.kClosed */) { + emnapiTSFN.setState(func, 2 /* State.kClosed */); + var env = emnapiTSFN.getEnv(func); + var envObject = emnapiCtx.envStore.get(env); + var ref = emnapiTSFN.getRef(func); + if (ref) { + emnapiCtx.refStore.get(ref).dispose(); + } + var resource = emnapiTSFN.getResource(func); + emnapiCtx.refStore.get(resource).dispose(); + emnapiTSFN.ensureBufferFor(func + emnapiTSFN.offset.is_some + 1); + var HEAP_DATA_VIEW = new DataView(wasmMemory.buffer), GET_HEAP_DATA_VIEW = function () { return HEAP_DATA_VIEW.buffer === wasmMemory.buffer ? HEAP_DATA_VIEW : (HEAP_DATA_VIEW = new DataView(wasmMemory.buffer)); }; + GET_HEAP_DATA_VIEW().setInt8(func + emnapiTSFN.offset.is_some, 0, true); + emnapiCtx.removeCleanupHook(envObject, emnapiTSFN.cleanup, func); + envObject.unref(); + var asyncRefAddress = func + emnapiTSFN.offset.async_ref; + var asyncRefOffset = asyncRefAddress >>> 2; + var arr = new Uint32Array(emnapiTSFN.ensureBufferFor(asyncRefAddress + 4)); + if (Atomics.load(arr, asyncRefOffset) > 0) { + Atomics.store(arr, asyncRefOffset, 0); + emnapiCtx.decreaseWaitingRequestCounter(); + } + if (emnapiNodeBinding) { + var view = new DataView(emnapiTSFN.ensureBufferFor(func + emnapiTSFN.offset.trigger_async_id + 8)); + var asyncId = view.getFloat64(func + emnapiTSFN.offset.async_id, true); + var triggerAsyncId = view.getFloat64(func + emnapiTSFN.offset.trigger_async_id, true); + _emnapi_node_emit_async_destroy(asyncId, triggerAsyncId); + } + } + }, + destroy: function (func) { + emnapiTSFN._liveSet.delete(func); + emnapiTSFN.destroyQueue(func); + emnapiTSFN.releaseResources(func); + _free(func); + }, + emptyQueue: function (func) { + var drainQueue = []; + emnapiTSFN.getMutex(func).execute(function () { + while (emnapiTSFN.getQueueSize(func) > 0) { + drainQueue.push(emnapiTSFN.shiftQueue(func)); + } + }); + var callJsCb = emnapiTSFN.getCallJSCb(func); + // eslint-disable-next-line @typescript-eslint/no-unused-vars + var context = emnapiTSFN.getContext(func); + var data; + for (var i = 0; i < drainQueue.length; i++) { + // eslint-disable-next-line @typescript-eslint/no-unused-vars + data = drainQueue[i]; + if (callJsCb) { + (wasmTable.get(callJsCb))(0, 0, context, data); + } + } + }, + maybeDelete: function (func) { + var shouldDelete = false; + emnapiTSFN.getMutex(func).execute(function () { + if (emnapiTSFN.getThreadCount(func) > 0) { + emnapiTSFN.releaseResources(func); + } + else { + shouldDelete = true; + } + }); + if (shouldDelete) { + emnapiTSFN.destroy(func); + } + }, + finalize: function (func) { + var env = emnapiTSFN.getEnv(func); + var envObject = emnapiCtx.envStore.get(env); + emnapiCtx.openScope(envObject); + var finalize = emnapiTSFN.getFinalizeCb(func); + // eslint-disable-next-line @typescript-eslint/no-unused-vars + var data = emnapiTSFN.getFinalizeData(func); + // eslint-disable-next-line @typescript-eslint/no-unused-vars + var context = emnapiTSFN.getContext(func); + var f = function () { + envObject.callFinalizerInternal(0, finalize, data, context); + }; + try { + emnapiTSFN.emptyQueue(func); + if (finalize) { + if (emnapiNodeBinding) { + var resource = emnapiTSFN.getResource(func); + var resource_value = emnapiCtx.refStore.get(resource).get(); + var resourceObject = emnapiCtx.handleStore.get(resource_value).value; + var view = new DataView(emnapiTSFN.ensureBufferFor(func + emnapiTSFN.offset.trigger_async_id + 8)); + var asyncId = view.getFloat64(func + emnapiTSFN.offset.async_id, true); + var triggerAsyncId = view.getFloat64(func + emnapiTSFN.offset.trigger_async_id, true); + emnapiNodeBinding.node.makeCallback(resourceObject, f, [], { + asyncId: asyncId, + triggerAsyncId: triggerAsyncId + }); + } + else { + f(); + } + } + emnapiTSFN.maybeDelete(func); + } + finally { + emnapiCtx.closeScope(envObject); + } + }, + cleanup: function (func) { + emnapiTSFN.closeHandlesAndMaybeDelete(func, 1); + }, + closeHandlesAndMaybeDelete: function (func, set_closing) { + var env = emnapiTSFN.getEnv(func); + var envObject = emnapiCtx.envStore.get(env); + emnapiCtx.openScope(envObject); + try { + if (set_closing) { + emnapiTSFN.getMutex(func).execute(function () { + emnapiTSFN.setState(func, 1 /* State.kClosing */); + if (emnapiTSFN.getMaxQueueSize(func) > 0) { + emnapiTSFN.getCond(func).signal(); + } + }); + } + if (emnapiTSFN.getHandlesClosing(func)) { + return; + } + emnapiTSFN.setHandlesClosing(func, 1); + Atomics.store(new Int32Array(emnapiTSFN.ensureBufferFor(func + emnapiTSFN.offset.async_pending + 4)), (func + emnapiTSFN.offset.async_pending) >>> 2, 1); + emnapiCtx.feature.setImmediate(function () { + emnapiTSFN.finalize(func); + }); + } + finally { + emnapiCtx.closeScope(envObject); + } + }, + dispatchOne: function (func) { + // eslint-disable-next-line @typescript-eslint/no-unused-vars + var data = 0; + var popped_value = false; + var has_more = false; + var mutex = emnapiTSFN.getMutex(func); + var cond = emnapiTSFN.getCond(func); + mutex.execute(function () { + if (emnapiTSFN.getState(func) === 0 /* State.kOpen */) { + var size = emnapiTSFN.getQueueSize(func); + if (size > 0) { + data = emnapiTSFN.shiftQueue(func); + popped_value = true; + var maxQueueSize = emnapiTSFN.getMaxQueueSize(func); + if (size === maxQueueSize && maxQueueSize > 0) { + cond.signal(); + } + size--; + } + if (size === 0) { + if (emnapiTSFN.getThreadCount(func) === 0) { + emnapiTSFN.setState(func, 1 /* State.kClosing */); + if (emnapiTSFN.getMaxQueueSize(func) > 0) { + cond.signal(); + } + emnapiTSFN.closeHandlesAndMaybeDelete(func, 0); + } + } + else { + has_more = true; + } + } + else { + emnapiTSFN.closeHandlesAndMaybeDelete(func, 0); + } + }); + if (popped_value) { + var env = emnapiTSFN.getEnv(func); + var envObject_1 = emnapiCtx.envStore.get(env); + emnapiCtx.openScope(envObject_1); + var f = function () { + envObject_1.callbackIntoModule(false, function () { + var callJsCb = emnapiTSFN.getCallJSCb(func); + var ref = emnapiTSFN.getRef(func); + var js_callback = ref ? emnapiCtx.refStore.get(ref).get() : 0; + if (callJsCb) { + // eslint-disable-next-line @typescript-eslint/no-unused-vars + var context = emnapiTSFN.getContext(func); + (wasmTable.get(callJsCb))(env, js_callback, context, data); + } + else { + var jsCallback = js_callback ? emnapiCtx.handleStore.get(js_callback).value : null; + if (typeof jsCallback === 'function') { + jsCallback(); + } + } + }); + }; + try { + if (emnapiNodeBinding) { + var resource = emnapiTSFN.getResource(func); + var resource_value = emnapiCtx.refStore.get(resource).get(); + var resourceObject = emnapiCtx.handleStore.get(resource_value).value; + var view = new DataView(emnapiTSFN.ensureBufferFor(func + emnapiTSFN.offset.trigger_async_id + 8)); + emnapiNodeBinding.node.makeCallback(resourceObject, f, [], { + asyncId: view.getFloat64(func + emnapiTSFN.offset.async_id, true), + triggerAsyncId: view.getFloat64(func + emnapiTSFN.offset.trigger_async_id, true) + }); + } + else { + f(); + } + } + finally { + emnapiCtx.closeScope(envObject_1); + } + } + return has_more; + }, + dispatch: function (func) { + var has_more = true; + var iterations_left = 1000; + var dispatchStateAddress = func + emnapiTSFN.offset.dispatch_state; + var index = dispatchStateAddress >>> 2; + while (has_more && --iterations_left !== 0) { + Atomics.store(new Uint32Array(emnapiTSFN.ensureBufferFor(dispatchStateAddress + 4)), index, 1); + try { + has_more = emnapiTSFN.dispatchOne(func); + } + catch (err) { + // A throwing callback must not leave dispatch_state marked as + // dispatching, or every later send() would be swallowed. Re-arm + // the state and schedule another drain before rethrowing. + if (emnapiTSFN._liveSet.has(func)) { + Atomics.exchange(new Uint32Array(emnapiTSFN.ensureBufferFor(dispatchStateAddress + 4)), index, 0); + emnapiTSFN.send(func); + } + throw err; + } + if (Atomics.exchange(new Uint32Array(emnapiTSFN.ensureBufferFor(dispatchStateAddress + 4)), index, 0) !== 1) { + has_more = true; + } + } + if (has_more) { + emnapiTSFN.send(func); + } + }, + enqueue: function (func) { + // `pending` means a worker thread has requested a wakeup that has not + // been drained on the main thread yet. + var pending = func + emnapiTSFN.offset.async_pending; + // `scheduled` prevents queueing the same main-thread drain chain more than + // once while a previous wakeup is still in flight. + var scheduled = func + emnapiTSFN.offset.async_u_fd; + var end = Math.max(pending, scheduled) + 4; + var state = function () { return new Int32Array(emnapiTSFN.ensureBufferFor(end)); }; + if (Atomics.exchange(state(), scheduled >>> 2, 1) !== 0) { + return; + } + // Match uv_async_send-style coalescing in JS: the first turn represents + // the wakeup reaching the main thread, and the second turn performs the + // actual TSFN drain after nearby Send/Signal calls have had a chance to + // collapse into the shared AsyncProgressWorker state. + emnapiCtx.feature.setImmediate(function () { + if (!emnapiTSFN._liveSet.has(func)) { + return; + } + if (Atomics.load(state(), pending >>> 2) === 0) { + Atomics.store(state(), scheduled >>> 2, 0); + return; + } + emnapiCtx.feature.setImmediate(function () { + // After destroy(), the func address is freed. Skip the atomics + // on that address entirely to avoid use-after-free (JS-side + // lifecycle check must run before touching the state words). + if (!emnapiTSFN._liveSet.has(func)) { + return; + } + try { + // Consume the coalesced wakeup once, then let dispatch() observe any + // queue mutations through dispatch_state like the C implementation. + if (Atomics.exchange(state(), pending >>> 2, 0) === 0) { + return; + } + emnapiTSFN.dispatch(func); + } + finally { + // Allow a later wakeup to schedule a new drain chain. If another + // worker-thread send raced with this drain, enqueue one more turn. + if (emnapiTSFN._liveSet.has(func)) { + Atomics.store(state(), scheduled >>> 2, 0); + if (Atomics.load(state(), pending >>> 2) !== 0) { + emnapiTSFN.enqueue(func); + } + } + } + }); + }); + }, + send: function (func) { + var dispatchStateAddress = func + emnapiTSFN.offset.dispatch_state; + var current_state = Atomics.or(new Uint32Array(emnapiTSFN.ensureBufferFor(dispatchStateAddress + 4)), dispatchStateAddress >>> 2, 1 << 1); + if ((current_state & 1) === 1) { + return; + } + var pendng = func + emnapiTSFN.offset.async_pending; + // A wakeup is already pending, so this send only needs to leave the queued + // work in the TSFN queue and let the existing drain pick it up. + if (Atomics.load(new Int32Array(emnapiTSFN.ensureBufferFor(pendng + 4)), pendng >>> 2) !== 0) { + return; + } + if (Atomics.exchange(new Int32Array(emnapiTSFN.ensureBufferFor(pendng + 4)), pendng >>> 2, 1) === 0) { + if ((typeof ENVIRONMENT_IS_PTHREAD !== 'undefined') && ENVIRONMENT_IS_PTHREAD) { + // Worker threads only post a wakeup token. Main-thread draining is + // serialized by enqueue() once the message is received. + postMessage({ + __emnapi__: { + type: 'tsfn-send', + payload: { + tsfn: func + } + } + }); + } + else { + // On the main thread we can skip the cross-thread hop and schedule the + // coalesced drain chain directly. + emnapiTSFN.enqueue(func); + } + } + } + }; + /** @__sig ippppppppppp */ + function napi_create_threadsafe_function(env, func, async_resource, async_resource_name, max_queue_size, initial_thread_count, thread_finalize_data, thread_finalize_cb, context, call_js_cb, result) { + if (!env) + return 1 /* napi_status.napi_invalid_arg */; + // @ts-expect-error + var envObject = emnapiCtx.envStore.get(env); + envObject.checkGCAccess(); + if (!async_resource_name) + return envObject.setLastError(1 /* napi_status.napi_invalid_arg */); + max_queue_size >>>= 0; + initial_thread_count >>>= 0; + env >>>= 0; + thread_finalize_data >>>= 0; + thread_finalize_cb >>>= 0; + context >>>= 0; + call_js_cb >>>= 0; + max_queue_size = max_queue_size >>> 0; + initial_thread_count = initial_thread_count >>> 0; + if (initial_thread_count === 0) { + return envObject.setLastError(1 /* napi_status.napi_invalid_arg */); + } + if (!result) + return envObject.setLastError(1 /* napi_status.napi_invalid_arg */); + var ref = 0; + func >>>= 0; + if (!func) { + if (!call_js_cb) + return envObject.setLastError(1 /* napi_status.napi_invalid_arg */); + } + else { + var funcValue = emnapiCtx.handleStore.get(func).value; + if (typeof funcValue !== 'function') { + return envObject.setLastError(1 /* napi_status.napi_invalid_arg */); + } + // eslint-disable-next-line @typescript-eslint/no-unused-vars + ref = emnapiCtx.createReference(envObject, func, 1, 1 /* ReferenceOwnership.kUserland */).id; + } + var asyncResourceObject; + if (async_resource) { + asyncResourceObject = emnapiCtx.handleStore.get(async_resource).value; + if (asyncResourceObject == null) { + return envObject.setLastError(2 /* napi_status.napi_object_expected */); + } + asyncResourceObject = Object(asyncResourceObject); + } + else { + asyncResourceObject = {}; + } + var resource = envObject.ensureHandleId(asyncResourceObject); + var asyncResourceName = emnapiCtx.handleStore.get(async_resource_name).value; + if (typeof asyncResourceName === 'symbol') { + return envObject.setLastError(3 /* napi_status.napi_string_expected */); + } + asyncResourceName = String(asyncResourceName); + var resource_name = envObject.ensureHandleId(asyncResourceName); + // tsfn create + var sizeofTSFN = emnapiTSFN.offset.__size__; + // eslint-disable-next-line prefer-const + var tsfn = _malloc(sizeofTSFN); + if (!tsfn) + return envObject.setLastError(9 /* napi_status.napi_generic_failure */); + tsfn >>>= 0; + new Uint8Array(emnapiTSFN.ensureBufferFor(tsfn + sizeofTSFN)).subarray(tsfn, tsfn + sizeofTSFN).fill(0); + var resourceRef = emnapiCtx.createReference(envObject, resource, 1, 1 /* ReferenceOwnership.kUserland */); + // eslint-disable-next-line @typescript-eslint/no-unused-vars + var resource_ = resourceRef.id; + var HEAP_DATA_VIEW = new DataView(wasmMemory.buffer), GET_HEAP_DATA_VIEW = function () { return HEAP_DATA_VIEW.buffer === wasmMemory.buffer ? HEAP_DATA_VIEW : (HEAP_DATA_VIEW = new DataView(wasmMemory.buffer)); }; + GET_HEAP_DATA_VIEW().setUint32(tsfn + emnapiTSFN.offset.resource, resource_, true); + if (!emnapiTSFN.initQueue(tsfn)) { + _free(tsfn); + resourceRef.dispose(); + return envObject.setLastError(9 /* napi_status.napi_generic_failure */); + } + _emnapi_node_emit_async_init(resource, resource_name, -1, tsfn + emnapiTSFN.offset.async_id); + GET_HEAP_DATA_VIEW().setInt8(tsfn + emnapiTSFN.offset.is_some, 1, true); + GET_HEAP_DATA_VIEW().setUint32(tsfn + emnapiTSFN.offset.thread_count, initial_thread_count, true); + GET_HEAP_DATA_VIEW().setUint32(tsfn + emnapiTSFN.offset.context, context, true); + GET_HEAP_DATA_VIEW().setUint32(tsfn + emnapiTSFN.offset.max_queue_size, max_queue_size, true); + GET_HEAP_DATA_VIEW().setUint32(tsfn + emnapiTSFN.offset.ref, ref, true); + GET_HEAP_DATA_VIEW().setUint32(tsfn + emnapiTSFN.offset.env, env, true); + GET_HEAP_DATA_VIEW().setUint32(tsfn + emnapiTSFN.offset.finalize_data, thread_finalize_data, true); + GET_HEAP_DATA_VIEW().setUint32(tsfn + emnapiTSFN.offset.finalize_cb, thread_finalize_cb, true); + GET_HEAP_DATA_VIEW().setUint32(tsfn + emnapiTSFN.offset.call_js_cb, call_js_cb, true); + emnapiCtx.addCleanupHook(envObject, emnapiTSFN.cleanup, tsfn); + emnapiTSFN._liveSet.add(tsfn); + envObject.ref(); + emnapiCtx.increaseWaitingRequestCounter(); + GET_HEAP_DATA_VIEW().setUint32(tsfn + emnapiTSFN.offset.async_ref, 1, true); + result >>>= 0; + GET_HEAP_DATA_VIEW().setUint32(result, tsfn, true); + return envObject.clearLastError(); + } + /** @__sig ipp */ + function napi_get_threadsafe_function_context(func, result) { + if (!func || !result) { + abort(); + return 1 /* napi_status.napi_invalid_arg */; + } + func >>>= 0; + result >>>= 0; + // eslint-disable-next-line @typescript-eslint/no-unused-vars + var context = emnapiTSFN.getContext(func); + var HEAP_DATA_VIEW = new DataView(wasmMemory.buffer), GET_HEAP_DATA_VIEW = function () { return HEAP_DATA_VIEW.buffer === wasmMemory.buffer ? HEAP_DATA_VIEW : (HEAP_DATA_VIEW = new DataView(wasmMemory.buffer)); }; + GET_HEAP_DATA_VIEW().setUint32(result, context, true); + return 0 /* napi_status.napi_ok */; + } + /** @__sig ippi */ + function napi_call_threadsafe_function(func, data, mode) { + if (!func) { + abort(); + return 1 /* napi_status.napi_invalid_arg */; + } + func >>>= 0; + data >>>= 0; + return emnapiTSFN.push(func, data, mode); + } + /** @__sig ip */ + function napi_acquire_threadsafe_function(func) { + if (!func) { + abort(); + return 1 /* napi_status.napi_invalid_arg */; + } + func >>>= 0; + var mutex = emnapiTSFN.getMutex(func); + return mutex.execute(function () { + if (emnapiTSFN.getState(func) === 0 /* State.kOpen */) { + emnapiTSFN.addThreadCount(func); + return 0 /* napi_status.napi_ok */; + } + return 16 /* napi_status.napi_closing */; + }); + } + /** @__sig ipi */ + function napi_release_threadsafe_function(func, mode) { + if (!func) { + abort(); + return 1 /* napi_status.napi_invalid_arg */; + } + func >>>= 0; + var mutex = emnapiTSFN.getMutex(func); + var cond = emnapiTSFN.getCond(func); + var shouldDelete = false; + var ret = mutex.execute(function () { + if (emnapiTSFN.getThreadCount(func) === 0) { + return 1 /* napi_status.napi_invalid_arg */; + } + emnapiTSFN.subThreadCount(func); + if (emnapiTSFN.getThreadCount(func) === 0 || mode === 1 /* napi_threadsafe_function_release_mode.napi_tsfn_abort */) { + if (emnapiTSFN.getState(func) === 0 /* State.kOpen */) { + if (mode === 1 /* napi_threadsafe_function_release_mode.napi_tsfn_abort */) { + emnapiTSFN.setState(func, 1 /* State.kClosing */); + } + if (emnapiTSFN.getState(func) === 1 /* State.kClosing */ && emnapiTSFN.getMaxQueueSize(func) > 0) { + cond.signal(); + } + emnapiTSFN.send(func); + } + } + if (!(emnapiTSFN.getState(func) === 2 /* State.kClosed */ && emnapiTSFN.getThreadCount(func) === 0)) { + return 0 /* napi_status.napi_ok */; + } + shouldDelete = true; + return 0 /* napi_status.napi_ok */; + }); + if (shouldDelete) { + emnapiTSFN.destroy(func); + } + return ret; + } + /** @__sig ipp */ + function napi_unref_threadsafe_function(env, func) { + if (!func) { + abort(); + return 1 /* napi_status.napi_invalid_arg */; + } + func >>>= 0; + var asyncRefAddress = func + emnapiTSFN.offset.async_ref; + var asyncRefOffset = asyncRefAddress >>> 2; + var arr = new Uint32Array(emnapiTSFN.ensureBufferFor(asyncRefAddress + 4)); + var currentValue = Atomics.load(arr, asyncRefOffset); + if (currentValue > 0) { + Atomics.store(arr, asyncRefOffset, currentValue - 1); + if (currentValue === 1) { + emnapiCtx.decreaseWaitingRequestCounter(); + } + } + return 0 /* napi_status.napi_ok */; + } + /** @__sig ipp */ + function napi_ref_threadsafe_function(env, func) { + if (!func) { + abort(); + return 1 /* napi_status.napi_invalid_arg */; + } + func >>>= 0; + var asyncRefAddress = func + emnapiTSFN.offset.async_ref; + var asyncRefOffset = asyncRefAddress >>> 2; + var arr = new Uint32Array(emnapiTSFN.ensureBufferFor(asyncRefAddress + 4)); + var currentValue = Atomics.load(arr, asyncRefOffset); + if (!currentValue) { + emnapiCtx.increaseWaitingRequestCounter(); + } + Atomics.store(arr, asyncRefOffset, currentValue + 1); + return 0 /* napi_status.napi_ok */; + } + var emnapiAWMT = { + pool: [], + workerReady: null, + globalAddress: 0, + globalOffset: { + idle_threads: 0, + q: 1 * 4, + next: 1 * 4, + prev: 2 * 4, + mutex: 3 * 4, + cond: 4 * 4, + exit_message: 5 * 4, + end: 7 * 4 + }, + offset: { + /* napi_ref */ resource: 0, + /* double */ async_id: 8, + /* double */ trigger_async_id: 16, + /* napi_env */ env: 24, + /* int32_t */ status: 1 * 4 + 24, // 0 for pending, 1 for cancelled, 2 for completed + queue: 2 * 4 + 24, + queue_next: 2 * 4 + 24, + queue_prev: 3 * 4 + 24, + /* void* */ data: 4 * 4 + 24, + /* napi_async_execute_callback */ execute: 5 * 4 + 24, + /* napi_async_complete_callback */ complete: 6 * 4 + 24, + end: 7 * 4 + 24 + }, + /** + * When another thread grows the shared WebAssembly.Memory, this agent's + * cached `wasmMemory.buffer` may still have the old shorter length + * (V8 refreshes it lazily). If a pointer derived from shared memory lies + * beyond the cached length, `wasmMemory.grow(0)` forces the agent to + * observe the current memory size and refreshes the buffer. + */ + ensureBufferFor: function (end) { + var buffer = wasmMemory.buffer; + if (end > buffer.byteLength) { + wasmMemory.grow(0); + buffer = wasmMemory.buffer; + } + return buffer; + }, + init: function () { + emnapiAWMT.pool = []; + emnapiAWMT.workerReady = null; + if (typeof PThread !== 'undefined') { + PThread.unusedWorkers.forEach(emnapiAWMT.addListener); + Object.values(PThread.pthreads).forEach(emnapiAWMT.addListener); + var __original_getNewWorker_1 = PThread.getNewWorker; + PThread.getNewWorker = function () { + var r = __original_getNewWorker_1.apply(this, arguments); + emnapiAWMT.addListener(r); + return r; + }; + } + }, + addListener: function (worker) { + if (!worker) + return false; + if (worker._emnapiAWMTListener) + return true; + var handler = function (e) { + var data = ENVIRONMENT_IS_NODE ? e : e.data; + var __emnapi__ = data.__emnapi__; + if (__emnapi__) { + var type = __emnapi__.type; + var payload = __emnapi__.payload; + if (type === 'async-work-complete') { + emnapiAWMT.callComplete(payload.work, 0 /* napi_status.napi_ok */); + } + } + }; + var dispose = function () { + if (ENVIRONMENT_IS_NODE) { + worker.off('message', handler); + } + else { + worker.removeEventListener('message', handler, false); + } + delete worker._emnapiAWMTListener; + }; + worker._emnapiAWMTListener = { handler: handler, dispose: dispose }; + if (ENVIRONMENT_IS_NODE) { + worker.on('message', handler); + } + else { + worker.addEventListener('message', handler, false); + } + return true; + }, + initGlobal: function () { + if (!emnapiAWMT.globalAddress) { + emnapiAWMT.globalAddress = _malloc(emnapiAWMT.globalOffset.end); + emnapiAWMT.globalAddress >>>= 0; + var size = emnapiAWMT.globalOffset.end; + var addr = emnapiAWMT.globalAddress; + new Uint8Array(emnapiAWMT.ensureBufferFor(addr + size), addr, size).fill(0); + emnapiAWMT.queueInit(emnapiAWMT.globalAddress + emnapiAWMT.globalOffset.q); + emnapiAWMT.queueInit(emnapiAWMT.globalAddress + emnapiAWMT.globalOffset.exit_message); + } + }, + terminateWorkers: function () { + emnapiAWMT.pool.forEach(function (w) { + var _a, _b; + (_a = w._emnapiAWMTListener) === null || _a === void 0 ? void 0 : _a.dispose(); + (_b = w._emnapiTSFNListener) === null || _b === void 0 ? void 0 : _b.dispose(); + w.terminate(); + }); + emnapiAWMT.pool.length = 0; + }, + initWorkers: function (n) { + if (ENVIRONMENT_IS_PTHREAD) { + // eslint-disable-next-line @typescript-eslint/prefer-nullish-coalescing + return emnapiAWMT.workerReady || (emnapiAWMT.workerReady = Promise.resolve()); + } + if (emnapiAWMT.workerReady) + return emnapiAWMT.workerReady; + if (!('emnapi_async_worker_create' in wasmInstance.exports)) { + throw new TypeError('`emnapi_async_worker_create` is not exported, please try to add `--export=emnapi_async_worker_create` to linker flags'); + } + var emnapi_async_worker_create = wasmInstance.exports.emnapi_async_worker_create; + var args = []; + emnapiAWMT.initGlobal(); + for (var i = 0; i < n; ++i) { + args.push(emnapi_async_worker_create(1, emnapiAWMT.globalAddress)); + } + var promises = args.map(function (index) { + if (index === 0) { + return Promise.reject(new Error('Failed to create async worker')); + } + var worker; + if (index < 0) { + worker = emnapiAWMT.pool[-index - 1]; + if (worker) + return worker.whenLoaded; + } + index >>>= 0; + var tidOffset = 20; + var view = new DataView(emnapiAWMT.ensureBufferFor(index + tidOffset + 4)); + var tid = view.getInt32(index + tidOffset, true); + worker = PThread.pthreads[tid]; + return worker.whenLoaded; + }); + emnapiAWMT.workerReady = Promise.all(promises); + return emnapiAWMT.workerReady; + }, + getResource: function (work) { + emnapiAWMT.ensureBufferFor(work + emnapiAWMT.offset.resource + 4); + var HEAP_DATA_VIEW = new DataView(wasmMemory.buffer), GET_HEAP_DATA_VIEW = function () { return HEAP_DATA_VIEW.buffer === wasmMemory.buffer ? HEAP_DATA_VIEW : (HEAP_DATA_VIEW = new DataView(wasmMemory.buffer)); }; + return GET_HEAP_DATA_VIEW().getUint32(work + emnapiAWMT.offset.resource, true); + }, + getExecute: function (work) { + emnapiAWMT.ensureBufferFor(work + emnapiAWMT.offset.execute + 4); + var HEAP_DATA_VIEW = new DataView(wasmMemory.buffer), GET_HEAP_DATA_VIEW = function () { return HEAP_DATA_VIEW.buffer === wasmMemory.buffer ? HEAP_DATA_VIEW : (HEAP_DATA_VIEW = new DataView(wasmMemory.buffer)); }; + return GET_HEAP_DATA_VIEW().getUint32(work + emnapiAWMT.offset.execute, true); + }, + getComplete: function (work) { + emnapiAWMT.ensureBufferFor(work + emnapiAWMT.offset.complete + 4); + var HEAP_DATA_VIEW = new DataView(wasmMemory.buffer), GET_HEAP_DATA_VIEW = function () { return HEAP_DATA_VIEW.buffer === wasmMemory.buffer ? HEAP_DATA_VIEW : (HEAP_DATA_VIEW = new DataView(wasmMemory.buffer)); }; + return GET_HEAP_DATA_VIEW().getUint32(work + emnapiAWMT.offset.complete, true); + }, + getEnv: function (work) { + emnapiAWMT.ensureBufferFor(work + emnapiAWMT.offset.env + 4); + var HEAP_DATA_VIEW = new DataView(wasmMemory.buffer), GET_HEAP_DATA_VIEW = function () { return HEAP_DATA_VIEW.buffer === wasmMemory.buffer ? HEAP_DATA_VIEW : (HEAP_DATA_VIEW = new DataView(wasmMemory.buffer)); }; + return GET_HEAP_DATA_VIEW().getUint32(work + emnapiAWMT.offset.env, true); + }, + getData: function (work) { + emnapiAWMT.ensureBufferFor(work + emnapiAWMT.offset.data + 4); + var HEAP_DATA_VIEW = new DataView(wasmMemory.buffer), GET_HEAP_DATA_VIEW = function () { return HEAP_DATA_VIEW.buffer === wasmMemory.buffer ? HEAP_DATA_VIEW : (HEAP_DATA_VIEW = new DataView(wasmMemory.buffer)); }; + return GET_HEAP_DATA_VIEW().getUint32(work + emnapiAWMT.offset.data, true); + }, + getMutex: function () { + var index = emnapiAWMT.globalAddress + emnapiAWMT.globalOffset.mutex; + var mutex = { + lock: function () { + var isBrowserMain = typeof window !== 'undefined' && typeof document !== 'undefined' && !ENVIRONMENT_IS_NODE; + var i32a = new Int32Array(emnapiAWMT.ensureBufferFor(index + 4), index, 1); + if (isBrowserMain) { + while (true) { + var oldValue = Atomics.compareExchange(i32a, 0, 0, 10); + if (oldValue === 0) { + return; + } + } + } + else { + while (true) { + var oldValue = Atomics.compareExchange(i32a, 0, 0, 10); + if (oldValue === 0) { + return; + } + Atomics.wait(i32a, 0, 10); + } + } + }, + unlock: function () { + var i32a = new Int32Array(emnapiAWMT.ensureBufferFor(index + 4), index, 1); + var oldValue = Atomics.compareExchange(i32a, 0, 10, 0); + if (oldValue !== 10) { + throw new Error('Tried to unlock while not holding the mutex'); + } + Atomics.notify(i32a, 0, 1); + }, + execute: function (fn) { + mutex.lock(); + try { + return fn(); + } + finally { + mutex.unlock(); + } + } + }; + return mutex; + }, + getCond: function () { + var index = emnapiAWMT.globalAddress + emnapiAWMT.globalOffset.cond; + var mutex = emnapiAWMT.getMutex(); + var cond = { + wait: function () { + var i32a = new Int32Array(emnapiAWMT.ensureBufferFor(index + 4), index, 1); + var value = Atomics.load(i32a, 0); + mutex.unlock(); + Atomics.wait(i32a, 0, value); + mutex.lock(); + }, + signal: function () { + var i32a = new Int32Array(emnapiAWMT.ensureBufferFor(index + 4), index, 1); + Atomics.add(i32a, 0, 1); + Atomics.notify(i32a, 0, 1); + } + }; + return cond; + }, + queueInit: function (q) { + emnapiAWMT.ensureBufferFor(q + 4 + 4); + var HEAP_DATA_VIEW = new DataView(wasmMemory.buffer), GET_HEAP_DATA_VIEW = function () { return HEAP_DATA_VIEW.buffer === wasmMemory.buffer ? HEAP_DATA_VIEW : (HEAP_DATA_VIEW = new DataView(wasmMemory.buffer)); }; + GET_HEAP_DATA_VIEW().setUint32(q, q, true); + GET_HEAP_DATA_VIEW().setUint32(q + 4, q, true); + }, + queueInsertTail: function (h, q) { + emnapiAWMT.ensureBufferFor(h + 4 + 4); + emnapiAWMT.ensureBufferFor(q + 4 + 4); + var HEAP_DATA_VIEW = new DataView(wasmMemory.buffer), GET_HEAP_DATA_VIEW = function () { return HEAP_DATA_VIEW.buffer === wasmMemory.buffer ? HEAP_DATA_VIEW : (HEAP_DATA_VIEW = new DataView(wasmMemory.buffer)); }; + GET_HEAP_DATA_VIEW().setUint32(q, h, true); + // eslint-disable-next-line @typescript-eslint/no-unused-vars + var tempValue = GET_HEAP_DATA_VIEW().getUint32(h + 4, true); + GET_HEAP_DATA_VIEW().setUint32(q + 4, tempValue, true); + // eslint-disable-next-line @typescript-eslint/no-unused-vars + var qprev = GET_HEAP_DATA_VIEW().getUint32(q + 4, true); + GET_HEAP_DATA_VIEW().setUint32(qprev, q, true); + GET_HEAP_DATA_VIEW().setUint32(h + 4, q, true); + }, + queueRemove: function (q) { + emnapiAWMT.ensureBufferFor(q + 4 + 4); + var HEAP_DATA_VIEW = new DataView(wasmMemory.buffer), GET_HEAP_DATA_VIEW = function () { return HEAP_DATA_VIEW.buffer === wasmMemory.buffer ? HEAP_DATA_VIEW : (HEAP_DATA_VIEW = new DataView(wasmMemory.buffer)); }; + // eslint-disable-next-line @typescript-eslint/no-unused-vars + var qprev = GET_HEAP_DATA_VIEW().getUint32(q + 4, true); + // eslint-disable-next-line @typescript-eslint/no-unused-vars + var qnext = GET_HEAP_DATA_VIEW().getUint32(q, true); + GET_HEAP_DATA_VIEW().setUint32(qprev, qnext, true); + GET_HEAP_DATA_VIEW().setUint32(qnext + 4, qprev, true); + }, + queueEmpty: function (q) { + emnapiAWMT.ensureBufferFor(q + 4); + var HEAP_DATA_VIEW = new DataView(wasmMemory.buffer), GET_HEAP_DATA_VIEW = function () { return HEAP_DATA_VIEW.buffer === wasmMemory.buffer ? HEAP_DATA_VIEW : (HEAP_DATA_VIEW = new DataView(wasmMemory.buffer)); }; + // eslint-disable-next-line eqeqeq + return q == GET_HEAP_DATA_VIEW().getUint32(q, true); + }, + scheduleWork: function (work) { + var _a; + if (!((_a = emnapiAWMT.workerReady) === null || _a === void 0 ? void 0 : _a.ready)) { + emnapiAWMT.initWorkers(_emnapi_async_work_pool_size()).then(function () { + emnapiAWMT.workerReady.ready = true; + }).catch(function (err) { + emnapiAWMT.workerReady = null; + throw err; + }); + } + emnapiCtx.increaseWaitingRequestCounter(); + var statusBuffer = new Int32Array(emnapiAWMT.ensureBufferFor(work + emnapiAWMT.offset.status + 4), work + emnapiAWMT.offset.status, 1); + Atomics.store(statusBuffer, 0, 0 /* AsyncWorkStatus.Pending */); + var mutex = emnapiAWMT.getMutex(); + var cond = emnapiAWMT.getCond(); + mutex.lock(); + try { + emnapiAWMT.queueInsertTail(emnapiAWMT.globalAddress + emnapiAWMT.globalOffset.q, work + emnapiAWMT.offset.queue); + } + catch (err) { + emnapiCtx.decreaseWaitingRequestCounter(); + mutex.unlock(); + throw err; + } + emnapiAWMT.ensureBufferFor(emnapiAWMT.globalAddress + emnapiAWMT.globalOffset.idle_threads + 4); + var HEAP_DATA_VIEW = new DataView(wasmMemory.buffer), GET_HEAP_DATA_VIEW = function () { return HEAP_DATA_VIEW.buffer === wasmMemory.buffer ? HEAP_DATA_VIEW : (HEAP_DATA_VIEW = new DataView(wasmMemory.buffer)); }; + if (GET_HEAP_DATA_VIEW().getUint32(emnapiAWMT.globalAddress + emnapiAWMT.globalOffset.idle_threads, true) > 0) { + cond.signal(); + } + mutex.unlock(); + }, + cancelWork: function (work) { + var cancelled = false; + emnapiAWMT.getMutex().execute(function () { + emnapiAWMT.ensureBufferFor(work + emnapiAWMT.offset.status + 4); + var HEAP_DATA_VIEW = new DataView(wasmMemory.buffer), GET_HEAP_DATA_VIEW = function () { return HEAP_DATA_VIEW.buffer === wasmMemory.buffer ? HEAP_DATA_VIEW : (HEAP_DATA_VIEW = new DataView(wasmMemory.buffer)); }; + cancelled = !emnapiAWMT.queueEmpty(work + emnapiAWMT.offset.queue) && GET_HEAP_DATA_VIEW().getInt32(work + emnapiAWMT.offset.status, true) !== 2 /* AsyncWorkStatus.Completed */; + if (cancelled) { + emnapiAWMT.queueRemove(work + emnapiAWMT.offset.queue); + } + }); + if (!cancelled) { + return 9 /* napi_status.napi_generic_failure */; + } + if (Atomics.compareExchange(new Int32Array(emnapiAWMT.ensureBufferFor(work + emnapiAWMT.offset.status + 4), work + emnapiAWMT.offset.status, 1), 0, 0 /* AsyncWorkStatus.Pending */, 1 /* AsyncWorkStatus.Cancelled */) !== 0 /* AsyncWorkStatus.Pending */) { + return 9 /* napi_status.napi_generic_failure */; + } + emnapiCtx.feature.setImmediate(function () { + emnapiAWMT.callComplete(work, 11 /* napi_status.napi_cancelled */); + }); + return 0 /* napi_status.napi_ok */; + }, + callComplete: function (work, status) { + emnapiCtx.decreaseWaitingRequestCounter(); + var complete = emnapiAWMT.getComplete(work); + var env = emnapiAWMT.getEnv(work); + var data = emnapiAWMT.getData(work); + var envObject = emnapiCtx.envStore.get(env); + var scope = emnapiCtx.openScope(envObject); + var callback = function () { + if (!complete) + return; + envObject.callbackIntoModule(true, function () { + (wasmTable.get(complete))(env, status, data); + }); + }; + try { + if (emnapiNodeBinding) { + var resource = emnapiAWMT.getResource(work); + var resource_value = emnapiCtx.refStore.get(resource).get(); + var resourceObject = emnapiCtx.handleStore.get(resource_value).value; + var view = new DataView(emnapiAWMT.ensureBufferFor(work + emnapiAWMT.offset.trigger_async_id + 8)); + var asyncId = view.getFloat64(work + emnapiAWMT.offset.async_id, true); + var triggerAsyncId = view.getFloat64(work + emnapiAWMT.offset.trigger_async_id, true); + emnapiNodeBinding.node.makeCallback(resourceObject, callback, [], { + asyncId: asyncId, + triggerAsyncId: triggerAsyncId + }); + } + else { + callback(); + } + } + finally { + emnapiCtx.closeScope(envObject, scope); + } + } + }; + emnapiAWMT.init(); + /** @__sig ippppppp */ + var napi_create_async_work = singleThreadAsyncWork + ? function (env, resource, resource_name, execute, complete, data, result) { + if (!env) + return 1 /* napi_status.napi_invalid_arg */; + // @ts-expect-error + var envObject = emnapiCtx.envStore.get(env); + envObject.checkGCAccess(); + if (!execute) + return envObject.setLastError(1 /* napi_status.napi_invalid_arg */); + if (!result) + return envObject.setLastError(1 /* napi_status.napi_invalid_arg */); + var resourceObject; + if (resource) { + resourceObject = Object(emnapiCtx.handleStore.get(resource).value); + } + else { + resourceObject = {}; + } + if (!resource_name) + return envObject.setLastError(1 /* napi_status.napi_invalid_arg */); + var resourceName = String(emnapiCtx.handleStore.get(resource_name).value); + // eslint-disable-next-line @typescript-eslint/no-unused-vars + var id = emnapiAWST.create(env, resourceObject, resourceName, execute, complete, data); + result >>>= 0; + var HEAP_DATA_VIEW = new DataView(wasmMemory.buffer), GET_HEAP_DATA_VIEW = function () { return HEAP_DATA_VIEW.buffer === wasmMemory.buffer ? HEAP_DATA_VIEW : (HEAP_DATA_VIEW = new DataView(wasmMemory.buffer)); }; + GET_HEAP_DATA_VIEW().setUint32(result, id, true); + return envObject.clearLastError(); + } + : function (env, resource, resource_name, execute, complete, data, result) { + if (!env) + return 1 /* napi_status.napi_invalid_arg */; + // @ts-expect-error + var envObject = emnapiCtx.envStore.get(env); + envObject.checkGCAccess(); + if (!execute) + return envObject.setLastError(1 /* napi_status.napi_invalid_arg */); + if (!result) + return envObject.setLastError(1 /* napi_status.napi_invalid_arg */); + var resourceObject; + if (resource) { + resourceObject = Object(emnapiCtx.handleStore.get(resource).value); + } + else { + resourceObject = {}; + } + if (!resource_name) + return envObject.setLastError(1 /* napi_status.napi_invalid_arg */); + var sizeofAW = emnapiAWMT.offset.end; + var aw = _malloc(sizeofAW); + if (!aw) + return envObject.setLastError(9 /* napi_status.napi_generic_failure */); + aw >>>= 0; + new Uint8Array(emnapiAWMT.ensureBufferFor(aw + sizeofAW)).subarray(aw, aw + sizeofAW).fill(0); + var s = envObject.ensureHandleId(resourceObject); + var resourceRef = emnapiCtx.createReference(envObject, s, 1, 1 /* ReferenceOwnership.kUserland */); + // eslint-disable-next-line @typescript-eslint/no-unused-vars + var resource_ = resourceRef.id; + var HEAP_DATA_VIEW = new DataView(wasmMemory.buffer), GET_HEAP_DATA_VIEW = function () { return HEAP_DATA_VIEW.buffer === wasmMemory.buffer ? HEAP_DATA_VIEW : (HEAP_DATA_VIEW = new DataView(wasmMemory.buffer)); }; + GET_HEAP_DATA_VIEW().setUint32(aw, resource_, true); + _emnapi_node_emit_async_init(s, resource_name, -1, aw + emnapiAWMT.offset.async_id); + GET_HEAP_DATA_VIEW().setUint32(aw + emnapiAWMT.offset.env, env, true); + GET_HEAP_DATA_VIEW().setUint32(aw + emnapiAWMT.offset.execute, execute, true); + GET_HEAP_DATA_VIEW().setUint32(aw + emnapiAWMT.offset.complete, complete, true); + GET_HEAP_DATA_VIEW().setUint32(aw + emnapiAWMT.offset.data, data, true); + emnapiAWMT.queueInit(aw + emnapiAWMT.offset.queue); + result >>>= 0; + GET_HEAP_DATA_VIEW().setUint32(result, aw, true); + return envObject.clearLastError(); + }; + /** @__sig ipp */ + var napi_delete_async_work = singleThreadAsyncWork + ? function (env, work) { + if (!env) + return 1 /* napi_status.napi_invalid_arg */; + // @ts-expect-error + var envObject = emnapiCtx.envStore.get(env); + envObject.checkGCAccess(); + if (!work) + return envObject.setLastError(1 /* napi_status.napi_invalid_arg */); + work >>>= 0; + emnapiAWST.remove(work); + return envObject.clearLastError(); + } + : function (env, work) { + if (!env) + return 1 /* napi_status.napi_invalid_arg */; + // @ts-expect-error + var envObject = emnapiCtx.envStore.get(env); + envObject.checkGCAccess(); + if (!work) + return envObject.setLastError(1 /* napi_status.napi_invalid_arg */); + work >>>= 0; + var resource = emnapiAWMT.getResource(work); + emnapiCtx.refStore.get(resource).dispose(); + if (emnapiNodeBinding) { + var view = new DataView(emnapiAWMT.ensureBufferFor(work + emnapiAWMT.offset.trigger_async_id + 8)); + var asyncId = view.getFloat64(work + emnapiAWMT.offset.async_id, true); + var triggerAsyncId = view.getFloat64(work + emnapiAWMT.offset.trigger_async_id, true); + _emnapi_node_emit_async_destroy(asyncId, triggerAsyncId); + } + _free(work); + return envObject.clearLastError(); + }; + /** @__sig ipp */ + var napi_queue_async_work = singleThreadAsyncWork + ? function (env, work) { + if (!env) + return 1 /* napi_status.napi_invalid_arg */; + var envObject = emnapiCtx.envStore.get(env); + if (!work) + return envObject.setLastError(1 /* napi_status.napi_invalid_arg */); + work >>>= 0; + emnapiAWST.queue(work); + return envObject.clearLastError(); + } + : function (env, work) { + if (!env) + return 1 /* napi_status.napi_invalid_arg */; + var envObject = emnapiCtx.envStore.get(env); + if (!work) + return envObject.setLastError(1 /* napi_status.napi_invalid_arg */); + work >>>= 0; + emnapiAWMT.scheduleWork(work); + return envObject.clearLastError(); + }; + /** @__sig ipp */ + var napi_cancel_async_work = singleThreadAsyncWork + ? function (env, work) { + if (!env) + return 1 /* napi_status.napi_invalid_arg */; + var envObject = emnapiCtx.envStore.get(env); + if (!work) + return envObject.setLastError(1 /* napi_status.napi_invalid_arg */); + work >>>= 0; + var status = emnapiAWST.cancel(work); + if (status === 0 /* napi_status.napi_ok */) + return envObject.clearLastError(); + return envObject.setLastError(status); + } + : function (env, work) { + if (!env) + return 1 /* napi_status.napi_invalid_arg */; + var envObject = emnapiCtx.envStore.get(env); + if (!work) + return envObject.setLastError(1 /* napi_status.napi_invalid_arg */); + work >>>= 0; + var status = emnapiAWMT.cancelWork(work); + if (status === 0 /* napi_status.napi_ok */) + return envObject.clearLastError(); + return envObject.setLastError(status); + }; + /** @__sig pp */ + function _emnapi_async_worker(globalAddress) { + globalAddress >>>= 0; + emnapiAWMT.globalAddress = globalAddress; + var mutex = emnapiAWMT.getMutex(); + var cond = emnapiAWMT.getCond(); + mutex.lock(); + var exitMessageAddr = globalAddress + emnapiAWMT.globalOffset.exit_message; + var idleThreadsAddr = globalAddress + emnapiAWMT.globalOffset.idle_threads; + var workerQueueAddr = globalAddress + emnapiAWMT.globalOffset.q; + var HEAP_DATA_VIEW = new DataView(wasmMemory.buffer), GET_HEAP_DATA_VIEW = function () { return HEAP_DATA_VIEW.buffer === wasmMemory.buffer ? HEAP_DATA_VIEW : (HEAP_DATA_VIEW = new DataView(wasmMemory.buffer)); }; + for (;;) { + emnapiAWMT.ensureBufferFor(workerQueueAddr + 4); + while (emnapiAWMT.queueEmpty(workerQueueAddr)) { + Atomics.add(new Int32Array(emnapiAWMT.ensureBufferFor(idleThreadsAddr + 4), idleThreadsAddr, 1), 0, 1); + cond.wait(); + Atomics.sub(new Int32Array(emnapiAWMT.ensureBufferFor(idleThreadsAddr + 4), idleThreadsAddr, 1), 0, 1); + } + var q = GET_HEAP_DATA_VIEW().getUint32(workerQueueAddr, true); + if (q === exitMessageAddr) { + cond.signal(); + mutex.unlock(); + break; + } + var work = q - emnapiAWMT.offset.queue; + emnapiAWMT.queueRemove(q); + emnapiAWMT.queueInit(q); + mutex.unlock(); + var statusBuffer = new Int32Array(emnapiAWMT.ensureBufferFor(work + emnapiAWMT.offset.status + 4), work + emnapiAWMT.offset.status, 1); + if (Atomics.load(statusBuffer, 0) === 1 /* AsyncWorkStatus.Cancelled */) { + abort('unreachable'); + } + // eslint-disable-next-line @typescript-eslint/no-unused-vars + var execute = emnapiAWMT.getExecute(work); + var env = emnapiAWMT.getEnv(work); + var data = emnapiAWMT.getData(work); + (wasmTable.get(execute))(env, data); + Atomics.store(statusBuffer, 0, 2 /* AsyncWorkStatus.Completed */); + var postMessage_1 = napiModule.postMessage; + postMessage_1({ + __emnapi__: { + type: 'async-work-complete', + payload: { work: work } + } + }); + mutex.lock(); + } + return 0; + } + /** @__sig ipp */ + function _emnapi_spawn_worker(f, globalAddress) { + if (typeof onCreateWorker !== 'function') { + throw new TypeError('`options.onCreateWorker` is not a function'); + } + var promises = []; + var args = []; + if (!('emnapi_async_worker_create' in wasmInstance.exports)) { + throw new TypeError('`emnapi_async_worker_create` is not exported, please try to add `--export=emnapi_async_worker_create` to linker flags'); + } + args.push(wasmInstance.exports.emnapi_async_worker_create(0, 0)); + var handleError = function (e) { + if ('message' in e && (e.message.indexOf('RuntimeError') !== -1 || e.message.indexOf('unreachable') !== -1)) { + emnapiAWMT.terminateWorkers(); + } + }; + var ret; + try { + var worker_1 = onCreateWorker({ type: 'async-work', name: 'emnapi-async-worker' }); + var p = PThread.loadWasmModuleToWorker(worker_1); + if (ENVIRONMENT_IS_NODE) { + worker_1.on('error', handleError); + } + else { + worker_1.addEventListener('error', handleError, false); + } + emnapiAWMT.addListener(worker_1); + emnapiTSFN.addListener(worker_1); + promises.push(p.then(function () { + if (typeof worker_1.unref === 'function') { + worker_1.unref(); + } + })); + ret = emnapiAWMT.pool.push(worker_1) - 1; + var arg = args[0]; + worker_1.threadBlockBase = arg; + worker_1.postMessage({ + __emnapi__: { + type: 'async-worker-init', + payload: { arg: arg, func: [f, globalAddress] } + } + }); + } + catch (err) { + // eslint-disable-next-line @typescript-eslint/no-unused-vars + var arg = args[0]; + _free(arg); + throw err; + } + return ret; + } + function initWorker(startArg, func) { + if (napiModule.childThread) { + if (typeof wasmInstance.exports.emnapi_async_worker_init !== 'function') { + throw new TypeError('`emnapi_async_worker_init` is not exported, please try to add `--export=emnapi_async_worker_init` to linker flags'); + } + wasmInstance.exports.emnapi_async_worker_init(startArg); + (wasmTable.get(func[0]))(func[1]); + } + else { + throw new Error('startThread is only available in child threads'); + } + } + napiModule.initWorker = initWorker; + var asyncWorkMod = /*#__PURE__*/ Object.freeze({ + __proto__: null, + _emnapi_async_worker: _emnapi_async_worker, + _emnapi_spawn_worker: _emnapi_spawn_worker, + napi_cancel_async_work: napi_cancel_async_work, + napi_create_async_work: napi_create_async_work, + napi_delete_async_work: napi_delete_async_work, + napi_queue_async_work: napi_queue_async_work + }); + /** + * @__deps malloc + * @__deps free + * @__postset + * ``` + * emnapiExternalMemory.init(); + * ``` + */ + var emnapiExternalMemory = { + registry: typeof FinalizationRegistry === 'function' ? new FinalizationRegistry(function (_pointer) { _free(_pointer); }) : undefined, + table: new WeakMap(), + wasmMemoryViewTable: new WeakMap(), + // populated by init(): live intrinsic function references must not exist at + // library definition time — the emscripten jsifier re-serializes this object + // and native functions do not stringify to parseable source + intrinsics: undefined, + init: function () { + var _a; + emnapiExternalMemory.registry = typeof FinalizationRegistry === 'function' ? new FinalizationRegistry(function (_pointer) { _free(_pointer); }) : undefined; + emnapiExternalMemory.table = new WeakMap(); + emnapiExternalMemory.wasmMemoryViewTable = new WeakMap(); + var sharedArrayBufferByteLength = typeof SharedArrayBuffer === 'function' + ? (_a = Object.getOwnPropertyDescriptor(SharedArrayBuffer.prototype, 'byteLength')) === null || _a === void 0 ? void 0 : _a.get + : undefined; + // cached intrinsic prototype getters and element-type constructors: they + // read the internal slots directly like native Node-API does, so user + // accessors and user subclass constructors can never run inside get-info + // metadata reads, descriptor registration or view reconstruction, and they + // work for instances from any realm + emnapiExternalMemory.intrinsics = { + // ArrayBuffer.isView ignores its `this`, so a bare cached reference is + // safe and cannot be swapped out by user code replacing the global + isView: ArrayBuffer.isView, + typedArray: { + buffer: Object.getOwnPropertyDescriptor(Object.getPrototypeOf(Uint8Array.prototype), 'buffer').get, + byteOffset: Object.getOwnPropertyDescriptor(Object.getPrototypeOf(Uint8Array.prototype), 'byteOffset').get, + length: Object.getOwnPropertyDescriptor(Object.getPrototypeOf(Uint8Array.prototype), 'length').get, + tag: Object.getOwnPropertyDescriptor(Object.getPrototypeOf(Uint8Array.prototype), Symbol.toStringTag).get + }, + dataView: { + buffer: Object.getOwnPropertyDescriptor(DataView.prototype, 'buffer').get, + byteOffset: Object.getOwnPropertyDescriptor(DataView.prototype, 'byteOffset').get, + byteLength: Object.getOwnPropertyDescriptor(DataView.prototype, 'byteLength').get + }, + arrayBuffer: { + byteLength: Object.getOwnPropertyDescriptor(ArrayBuffer.prototype, 'byteLength').get + }, + // a SharedArrayBuffer polyfill may lack the byteLength accessor: degrade + // to the hidden-global classification path instead of throwing here + sharedArrayBuffer: sharedArrayBufferByteLength !== undefined + ? { + byteLength: sharedArrayBufferByteLength + } + : undefined, + ctors: { + Int8Array: Int8Array, + Uint8Array: Uint8Array, + Uint8ClampedArray: Uint8ClampedArray, + Int16Array: Int16Array, + Uint16Array: Uint16Array, + Int32Array: Int32Array, + Uint32Array: Uint32Array, + Float16Array: typeof Float16Array === 'function' ? Float16Array : undefined, + Float32Array: Float32Array, + Float64Array: Float64Array, + BigInt64Array: BigInt64Array, + BigUint64Array: BigUint64Array + }, + bufferFrom: undefined + }; + }, + isSharedArrayBuffer: function (value) { + var sharedArrayBuffer = emnapiExternalMemory.intrinsics.sharedArrayBuffer; + if (sharedArrayBuffer !== undefined) { + if (typeof SharedArrayBuffer === 'function' && value instanceof SharedArrayBuffer) + return true; + // the intrinsic byteLength getter reads the internal slot: it accepts + // SharedArrayBuffer instances from any realm and throws for anything + // else, without consulting user-controllable properties + try { + sharedArrayBuffer.byteLength.call(value); + return true; + } + catch (_) { + return false; + } + } + // hidden-global environment (see #143): the SharedArrayBuffer global was + // absent at init time, but the engine can still hand out genuine SABs + // (e.g. a shared WebAssembly.Memory buffer). A genuine ArrayBuffer + // answers the intrinsic byteLength probe, settling the common case + // without the (spoofable, user-JS-running) toString tag read below. + try { + emnapiExternalMemory.intrinsics.arrayBuffer.byteLength.call(value); + return false; + } + catch (_) { } + return Object.prototype.toString.call(value) === '[object SharedArrayBuffer]'; + }, + isDetachedArrayBuffer: function (arrayBuffer) { + if (emnapiExternalMemory.bufferByteLength(arrayBuffer) === 0) { + try { + // eslint-disable-next-line no-new + new Uint8Array(arrayBuffer); + } + catch (_) { + return true; + } + } + return false; + }, + bufferByteLength: function (buffer) { + var _a; + var intrinsics = emnapiExternalMemory.intrinsics; + try { + return intrinsics.arrayBuffer.byteLength.call(buffer); + } + catch (err) { + var sharedArrayBuffer = intrinsics.sharedArrayBuffer; + if (sharedArrayBuffer !== undefined) { + return sharedArrayBuffer.byteLength.call(buffer); + } + // hidden-global environment (see isSharedArrayBuffer): no SAB getter + // was capturable at init, recover it from the instance's own prototype + // (for a genuine SAB that is the hidden SharedArrayBuffer.prototype) + var proto = Object.getPrototypeOf(buffer); + var get = proto !== null && proto !== undefined + ? (_a = Object.getOwnPropertyDescriptor(proto, 'byteLength')) === null || _a === void 0 ? void 0 : _a.get + : undefined; + if (get === undefined) + throw err; + return get.call(buffer); + } + }, + viewBuffer: function (view) { + var intrinsics = emnapiExternalMemory.intrinsics; + return intrinsics.typedArray.tag.call(view) === undefined + ? intrinsics.dataView.buffer.call(view) + : intrinsics.typedArray.buffer.call(view); + }, + viewByteOffset: function (view) { + var intrinsics = emnapiExternalMemory.intrinsics; + return intrinsics.typedArray.tag.call(view) === undefined + ? intrinsics.dataView.byteOffset.call(view) + : intrinsics.typedArray.byteOffset.call(view); + }, + // element count for typed arrays, byteLength for DataViews (the unit used + // by the napi_get_typedarray_info / napi_get_dataview_info length outputs + // and by the view constructors at reconstruction) + viewLength: function (view) { + var intrinsics = emnapiExternalMemory.intrinsics; + return intrinsics.typedArray.tag.call(view) === undefined + ? intrinsics.dataView.byteLength.call(view) + : intrinsics.typedArray.length.call(view); + }, + // Buffer descriptors are only ever created by emnapi's own buffer creation + // paths; capturing Buffer.from the first time one is created snapshots the + // legitimate function before any later reconstruction, so a user replacing + // Buffer.from afterwards cannot influence a refreshed view + getBufferFrom: function () { + var _a; + return (_a = emnapiExternalMemory.intrinsics.bufferFrom) !== null && _a !== void 0 ? _a : (emnapiExternalMemory.intrinsics.bufferFrom = emnapiCtx.feature.Buffer.from); + }, + getArrayBufferPointer: function (arrayBuffer, shouldCopy) { + var _a; + var info = { + address: 0, + ownership: 0 /* ReferenceOwnership.kRuntime */, + runtimeAllocated: 0 + }; + if (arrayBuffer === wasmMemory.buffer) { + return info; + } + var isDetached = emnapiExternalMemory.isDetachedArrayBuffer(arrayBuffer); + if (emnapiExternalMemory.table.has(arrayBuffer)) { + var cachedInfo = emnapiExternalMemory.table.get(arrayBuffer); + if (isDetached) { + cachedInfo.address = 0; + return cachedInfo; + } + if (shouldCopy && cachedInfo.ownership === 0 /* ReferenceOwnership.kRuntime */ && cachedInfo.runtimeAllocated === 1) { + new Uint8Array(wasmMemory.buffer).set(new Uint8Array(arrayBuffer), cachedInfo.address); + } + return cachedInfo; + } + var byteLength = emnapiExternalMemory.bufferByteLength(arrayBuffer); + if (isDetached || (byteLength === 0)) { + return info; + } + if (!shouldCopy) { + return info; + } + var pointer = _malloc(byteLength); + if (!pointer) + throw new Error('Out of memory'); + pointer >>>= 0; + new Uint8Array(wasmMemory.buffer).set(new Uint8Array(arrayBuffer), pointer); + info.address = pointer; + info.ownership = emnapiExternalMemory.registry ? 0 /* ReferenceOwnership.kRuntime */ : 1 /* ReferenceOwnership.kUserland */; + info.runtimeAllocated = 1; + emnapiExternalMemory.table.set(arrayBuffer, info); + (_a = emnapiExternalMemory.registry) === null || _a === void 0 ? void 0 : _a.register(arrayBuffer, pointer); + return info; + }, + getOrUpdateMemoryView: function (view) { + // classify and read the view state through the cached intrinsic + // prototype getters only: own accessors on the instance could otherwise + // run user JS that grows (and detaches) a non-shared memory in the + // middle of registration, poisoning the stored descriptor; the intrinsic + // reads return primitives from the internal slots and run zero user JS. + // The @@toStringTag slot getter classifies views from any realm: it + // returns the element-type name for typed arrays (seeing through user + // subclasses) and undefined for DataViews + var intrinsics = emnapiExternalMemory.intrinsics; + var tag = intrinsics.typedArray.tag.call(view); + var isDataView = tag === undefined; + var buffer = isDataView ? intrinsics.dataView.buffer.call(view) : intrinsics.typedArray.buffer.call(view); + if (buffer === wasmMemory.buffer) { + if (!emnapiExternalMemory.wasmMemoryViewTable.has(view)) { + emnapiExternalMemory.wasmMemoryViewTable.set(view, { + // store the intrinsic element-type constructor keyed by the + // @@toStringTag slot (never view.constructor and never a + // user-definable Buffer @@hasInstance check): reconstruction after a + // memory growth must not run any user code, because it could grow + // again after the fresh buffer was captured as an argument. Buffers + // are tagged 'Uint8Array' and reconstruct as base Uint8Array views + Ctor: isDataView ? DataView : intrinsics.ctors[tag], + address: isDataView ? intrinsics.dataView.byteOffset.call(view) : intrinsics.typedArray.byteOffset.call(view), + length: isDataView ? intrinsics.dataView.byteLength.call(view) : intrinsics.typedArray.length.call(view), + ownership: 1 /* ReferenceOwnership.kUserland */, + runtimeAllocated: 0 + }); + } + return view; + } + var maybeOldWasmMemory = emnapiExternalMemory.isDetachedArrayBuffer(buffer) || emnapiExternalMemory.isSharedArrayBuffer(buffer); + if (maybeOldWasmMemory && emnapiExternalMemory.wasmMemoryViewTable.has(view)) { + var info = emnapiExternalMemory.wasmMemoryViewTable.get(view); + var Ctor = info.Ctor; + var newView = void 0; + var Buffer_1 = emnapiCtx.feature.Buffer; + if (typeof Buffer_1 === 'function' && Ctor === Buffer_1) { + // reconstruct through the Buffer.from captured at creation time + newView = emnapiExternalMemory.getBufferFrom()(wasmMemory.buffer, info.address, info.length); + } + else { + newView = new Ctor(wasmMemory.buffer, info.address, info.length); + } + emnapiExternalMemory.wasmMemoryViewTable.set(newView, info); + return newView; + } + return view; + }, + getViewPointer: function (view, shouldCopy) { + view = emnapiExternalMemory.getOrUpdateMemoryView(view); + var buffer = emnapiExternalMemory.viewBuffer(view); + if (buffer === wasmMemory.buffer) { + if (emnapiExternalMemory.wasmMemoryViewTable.has(view)) { + var _a = emnapiExternalMemory.wasmMemoryViewTable.get(view), address_1 = _a.address, ownership_1 = _a.ownership, runtimeAllocated_1 = _a.runtimeAllocated; + return { address: address_1, ownership: ownership_1, runtimeAllocated: runtimeAllocated_1, view: view }; + } + return { address: emnapiExternalMemory.viewByteOffset(view), ownership: 1 /* ReferenceOwnership.kUserland */, runtimeAllocated: 0, view: view }; + } + var _b = emnapiExternalMemory.getArrayBufferPointer(buffer, shouldCopy), address = _b.address, ownership = _b.ownership, runtimeAllocated = _b.runtimeAllocated; + return { address: address === 0 ? 0 : (address + emnapiExternalMemory.viewByteOffset(view)), ownership: ownership, runtimeAllocated: runtimeAllocated, view: view }; + } + }; + /** + * Metadata layout in wasm shared memory (allocated with _malloc): + * offset 0: refcount (int32, 4 bytes - for Atomics) + * offset POINTER_SIZE: external_data (pointer) + * offset 2*POINTER_SIZE: byte_length (size_t) + * offset 3*POINTER_SIZE: finalize_cb (pointer) + * offset 4*POINTER_SIZE: finalize_data (pointer) + * offset 5*POINTER_SIZE: finalize_hint (pointer) + * Total: 6 * POINTER_SIZE bytes + */ + /** + * @__postset + * ``` + * emnapiExternalSAB.init(); + * ``` + */ + var emnapiExternalSAB = { + registry: undefined, + handleTable: new WeakMap(), + init: function () { + emnapiExternalSAB.handleTable = new WeakMap(); + emnapiExternalSAB.registry = typeof FinalizationRegistry === 'function' + ? new FinalizationRegistry(function (metaPtr) { + emnapiExternalSAB.release(metaPtr); + }) + : undefined; + }, + allocMeta: function (external_data, byte_length, finalize_cb, finalize_data, finalize_hint) { + // eslint-disable-next-line @typescript-eslint/no-unused-vars + var size = 4 * 6; + // eslint-disable-next-line prefer-const + var metaPtr = _malloc(size); + if (!metaPtr) + throw new Error('Out of memory'); + metaPtr >>>= 0; + // refcount = 1 + Atomics.store(new Int32Array(wasmMemory.buffer, metaPtr, 1), 0, 1); + var HEAP_DATA_VIEW = new DataView(wasmMemory.buffer), GET_HEAP_DATA_VIEW = function () { return HEAP_DATA_VIEW.buffer === wasmMemory.buffer ? HEAP_DATA_VIEW : (HEAP_DATA_VIEW = new DataView(wasmMemory.buffer)); }; + GET_HEAP_DATA_VIEW().setUint32(metaPtr + 4, external_data, true); + GET_HEAP_DATA_VIEW().setUint32(metaPtr + 8, byte_length, true); + GET_HEAP_DATA_VIEW().setUint32(metaPtr + 12, finalize_cb, true); + GET_HEAP_DATA_VIEW().setUint32(metaPtr + 16, finalize_data, true); + GET_HEAP_DATA_VIEW().setUint32(metaPtr + 20, finalize_hint, true); + return metaPtr; + }, + readMeta: function (metaPtr) { + var HEAP_DATA_VIEW = new DataView(wasmMemory.buffer), GET_HEAP_DATA_VIEW = function () { return HEAP_DATA_VIEW.buffer === wasmMemory.buffer ? HEAP_DATA_VIEW : (HEAP_DATA_VIEW = new DataView(wasmMemory.buffer)); }; + var external_data = GET_HEAP_DATA_VIEW().getUint32(metaPtr + 4, true); + var byte_length = GET_HEAP_DATA_VIEW().getUint32(metaPtr + 8, true); + var finalize_cb = GET_HEAP_DATA_VIEW().getUint32(metaPtr + 12, true); + var finalize_data = GET_HEAP_DATA_VIEW().getUint32(metaPtr + 16, true); + var finalize_hint = GET_HEAP_DATA_VIEW().getUint32(metaPtr + 20, true); + return { external_data: external_data, byte_length: byte_length, finalize_cb: finalize_cb, finalize_data: finalize_data, finalize_hint: finalize_hint }; + }, + release: function (metaPtr) { + var oldRefcount = Atomics.sub(new Int32Array(wasmMemory.buffer, metaPtr, 1), 0, 1); + if (oldRefcount === 1) { + // refcount reached 0, we are the last holder + var info = emnapiExternalSAB.readMeta(metaPtr); + var finalize_cb = info.finalize_cb; + if (finalize_cb) { + var finalize_data = info.finalize_data; + var finalize_hint = info.finalize_hint; + (wasmTable.get(finalize_cb))(finalize_data, finalize_hint); + } + _free(metaPtr); + } + } + }; + /* eslint-disable @typescript-eslint/indent */ + /** + * @__postset + * ``` + * emnapiString.init(); + * ``` + */ + var emnapiString = { + utf8Decoder: undefined, + utf16Decoder: undefined, + init: function () { + var fallbackDecoder = { + decode: function (bytes) { + var inputIndex = 0; + var pendingSize = Math.min(0x1000, bytes.length + 1); + var pending = new Uint16Array(pendingSize); + var chunks = []; + var pendingIndex = 0; + for (;;) { + var more = inputIndex < bytes.length; + if (!more || (pendingIndex >= pendingSize - 1)) { + var subarray = pending.subarray(0, pendingIndex); + var arraylike = subarray; + chunks.push(String.fromCharCode.apply(null, arraylike)); + if (!more) { + return chunks.join(''); + } + bytes = bytes.subarray(inputIndex); + inputIndex = 0; + pendingIndex = 0; + } + var byte1 = bytes[inputIndex++]; + if ((byte1 & 0x80) === 0) { + pending[pendingIndex++] = byte1; + } + else if ((byte1 & 0xe0) === 0xc0) { + var byte2 = bytes[inputIndex++] & 0x3f; + pending[pendingIndex++] = ((byte1 & 0x1f) << 6) | byte2; + } + else if ((byte1 & 0xf0) === 0xe0) { + var byte2 = bytes[inputIndex++] & 0x3f; + var byte3 = bytes[inputIndex++] & 0x3f; + pending[pendingIndex++] = ((byte1 & 0x1f) << 12) | (byte2 << 6) | byte3; + } + else if ((byte1 & 0xf8) === 0xf0) { + var byte2 = bytes[inputIndex++] & 0x3f; + var byte3 = bytes[inputIndex++] & 0x3f; + var byte4 = bytes[inputIndex++] & 0x3f; + var codepoint = ((byte1 & 0x07) << 0x12) | (byte2 << 0x0c) | (byte3 << 0x06) | byte4; + if (codepoint > 0xffff) { + codepoint -= 0x10000; + pending[pendingIndex++] = (codepoint >>> 10) & 0x3ff | 0xd800; + codepoint = 0xdc00 | codepoint & 0x3ff; + } + pending[pendingIndex++] = codepoint; + } + else ; + } + } + }; + var utf8Decoder; + utf8Decoder = typeof TextDecoder === 'function' ? new TextDecoder() : fallbackDecoder; + emnapiString.utf8Decoder = utf8Decoder; + var fallbackDecoder2 = { + decode: function (input) { + var bytes = new Uint16Array(input.buffer, input.byteOffset, input.byteLength / 2); + if (bytes.length <= 0x1000) { + return String.fromCharCode.apply(null, bytes); + } + var chunks = []; + var i = 0; + var len = 0; + for (; i < bytes.length; i += len) { + len = Math.min(0x1000, bytes.length - i); + chunks.push(String.fromCharCode.apply(null, bytes.subarray(i, i + len))); + } + return chunks.join(''); + } + }; + var utf16Decoder; + utf16Decoder = typeof TextDecoder === 'function' ? new TextDecoder('utf-16le') : fallbackDecoder2; + emnapiString.utf16Decoder = utf16Decoder; + }, + lengthBytesUTF8: function (str) { + var c; + var len = 0; + for (var i = 0; i < str.length; ++i) { + c = str.charCodeAt(i); + if (c <= 0x7F) { + len++; + } + else if (c <= 0x7FF) { + len += 2; + } + else if (c >= 0xD800 && c <= 0xDFFF) { + len += 4; + ++i; + } + else { + len += 3; + } + } + return len; + }, + UTF8ToString: function (ptr, length) { + if (!ptr || !length) + return ''; + ptr >>>= 0; + var HEAPU8 = new Uint8Array(wasmMemory.buffer); + var end = ptr; + if (length === -1 || length === 4294967295) { + for (; HEAPU8[end];) + ++end; + } + else { + end = ptr + (length >>> 0); + } + length = end - ptr; + if (length <= 16) { + var idx = ptr; + var str = ''; + while (idx < end) { + var u0 = HEAPU8[idx++]; + if (!(u0 & 0x80)) { + str += String.fromCharCode(u0); + continue; + } + var u1 = HEAPU8[idx++] & 63; + if ((u0 & 0xE0) === 0xC0) { + str += String.fromCharCode(((u0 & 31) << 6) | u1); + continue; + } + var u2 = HEAPU8[idx++] & 63; + if ((u0 & 0xF0) === 0xE0) { + u0 = ((u0 & 15) << 12) | (u1 << 6) | u2; + } + else { + u0 = ((u0 & 7) << 18) | (u1 << 12) | (u2 << 6) | (HEAPU8[idx++] & 63); + } + if (u0 < 0x10000) { + str += String.fromCharCode(u0); + } + else { + var ch = u0 - 0x10000; + str += String.fromCharCode(0xD800 | (ch >> 10), 0xDC00 | (ch & 0x3FF)); + } + } + return str; + } + return emnapiString.utf8Decoder.decode(((typeof SharedArrayBuffer === "function" && HEAPU8.buffer instanceof SharedArrayBuffer) || (Object.prototype.toString.call(HEAPU8.buffer) === "[object SharedArrayBuffer]")) ? HEAPU8.slice(ptr, end) : HEAPU8.subarray(ptr, end)); + }, + stringToUTF8: function (str, outPtr, maxBytesToWrite) { + var HEAPU8 = new Uint8Array(wasmMemory.buffer); + var outIdx = outPtr; + outIdx >>>= 0; + if (!(maxBytesToWrite > 0)) { + return 0; + } + var startIdx = outIdx; + var endIdx = outIdx + maxBytesToWrite - 1; + for (var i = 0; i < str.length; ++i) { + var u = str.charCodeAt(i); + if (u >= 0xD800 && u <= 0xDFFF) { + var u1 = str.charCodeAt(++i); + u = 0x10000 + ((u & 0x3FF) << 10) | (u1 & 0x3FF); + } + if (u <= 0x7F) { + if (outIdx >= endIdx) + break; + HEAPU8[outIdx++] = u; + } + else if (u <= 0x7FF) { + if (outIdx + 1 >= endIdx) + break; + HEAPU8[outIdx++] = 0xC0 | (u >> 6); + HEAPU8[outIdx++] = 0x80 | (u & 63); + } + else if (u <= 0xFFFF) { + if (outIdx + 2 >= endIdx) + break; + HEAPU8[outIdx++] = 0xE0 | (u >> 12); + HEAPU8[outIdx++] = 0x80 | ((u >> 6) & 63); + HEAPU8[outIdx++] = 0x80 | (u & 63); + } + else { + if (outIdx + 3 >= endIdx) + break; + HEAPU8[outIdx++] = 0xF0 | (u >> 18); + HEAPU8[outIdx++] = 0x80 | ((u >> 12) & 63); + HEAPU8[outIdx++] = 0x80 | ((u >> 6) & 63); + HEAPU8[outIdx++] = 0x80 | (u & 63); + } + } + HEAPU8[outIdx] = 0; + return outIdx - startIdx; + }, + UTF16ToString: function (ptr, length) { + if (!ptr || !length) + return ''; + ptr >>>= 0; + var end = ptr; + if (length === -1 || length === 4294967295) { + var idx = end >>> 1; + var HEAPU16 = new Uint16Array(wasmMemory.buffer); + while (HEAPU16[idx]) + ++idx; + end = (idx << 1) >>> 0; + } + else { + end = ptr + (length >>> 0) * 2; + } + length = end - ptr; + if (length <= 32) { + return String.fromCharCode.apply(null, new Uint16Array(wasmMemory.buffer, ptr, length / 2)); + } + // eslint-disable-next-line @typescript-eslint/no-unused-vars + var HEAPU8 = new Uint8Array(wasmMemory.buffer); + return emnapiString.utf16Decoder.decode(((typeof SharedArrayBuffer === "function" && HEAPU8.buffer instanceof SharedArrayBuffer) || (Object.prototype.toString.call(HEAPU8.buffer) === "[object SharedArrayBuffer]")) ? HEAPU8.slice(ptr, end) : HEAPU8.subarray(ptr, end)); + }, + stringToUTF16: function (str, outPtr, maxBytesToWrite) { + if (maxBytesToWrite === undefined) { + maxBytesToWrite = 0x7FFFFFFF; + } + if (maxBytesToWrite < 2) + return 0; + maxBytesToWrite -= 2; + var startPtr = outPtr; + var numCharsToWrite = (maxBytesToWrite < str.length * 2) ? (maxBytesToWrite / 2) : str.length; + var HEAP_DATA_VIEW = new DataView(wasmMemory.buffer), GET_HEAP_DATA_VIEW = function () { return HEAP_DATA_VIEW.buffer === wasmMemory.buffer ? HEAP_DATA_VIEW : (HEAP_DATA_VIEW = new DataView(wasmMemory.buffer)); }; + for (var i = 0; i < numCharsToWrite; ++i) { + // eslint-disable-next-line @typescript-eslint/no-unused-vars + var codeUnit = str.charCodeAt(i); + GET_HEAP_DATA_VIEW().setInt16(outPtr, codeUnit, true); + outPtr += 2; + } + GET_HEAP_DATA_VIEW().setInt16(outPtr, 0, true); + return outPtr - startPtr; + }, + newString: function (env, str, length, result, stringMaker) { + length >>>= 0; + if (!env) + return 1 /* napi_status.napi_invalid_arg */; + // @ts-expect-error + var envObject = emnapiCtx.envStore.get(env); + envObject.checkGCAccess(); + var autoLength = length === -1 || length === 4294967295; + var sizelength = length >>> 0; + if (length !== 0) { + if (!str) + return envObject.setLastError(1 /* napi_status.napi_invalid_arg */); + } + if (!result) + return envObject.setLastError(1 /* napi_status.napi_invalid_arg */); + if (!(autoLength || (sizelength <= 2147483647))) + return envObject.setLastError(1 /* napi_status.napi_invalid_arg */); + str >>>= 0; + var strValue = stringMaker(str, autoLength, sizelength); + result >>>= 0; + // eslint-disable-next-line @typescript-eslint/no-unused-vars + var value = emnapiCtx.addToCurrentScope(strValue).id; + var HEAP_DATA_VIEW = new DataView(wasmMemory.buffer), GET_HEAP_DATA_VIEW = function () { return HEAP_DATA_VIEW.buffer === wasmMemory.buffer ? HEAP_DATA_VIEW : (HEAP_DATA_VIEW = new DataView(wasmMemory.buffer)); }; + GET_HEAP_DATA_VIEW().setUint32(result, value, true); + return envObject.clearLastError(); + }, + newExternalString: function (env, str, length, finalize_callback, finalize_hint, result, copied, createApi, stringMaker) { + length >>>= 0; + if (!env) + return 1 /* napi_status.napi_invalid_arg */; + // @ts-expect-error + var envObject = emnapiCtx.envStore.get(env); + envObject.checkGCAccess(); + var autoLength = length === -1 || length === 4294967295; + var sizelength = length >>> 0; + if (length !== 0) { + if (!str) + return envObject.setLastError(1 /* napi_status.napi_invalid_arg */); + } + if (!result) + return envObject.setLastError(1 /* napi_status.napi_invalid_arg */); + if (!(autoLength || (sizelength <= 2147483647))) + return envObject.setLastError(1 /* napi_status.napi_invalid_arg */); + var status = createApi(env, str, length, result); + if (status === 0 /* napi_status.napi_ok */) { + if (copied) { + var HEAP_DATA_VIEW = new DataView(wasmMemory.buffer), GET_HEAP_DATA_VIEW = function () { return HEAP_DATA_VIEW.buffer === wasmMemory.buffer ? HEAP_DATA_VIEW : (HEAP_DATA_VIEW = new DataView(wasmMemory.buffer)); }; + GET_HEAP_DATA_VIEW().setInt8(copied, 1, true); + } + if (finalize_callback) { + envObject.callFinalizer(finalize_callback, str, finalize_hint); + } + } + return status; + } + }; + /** + * @__sig ippp + */ + function napi_get_array_length(env, value, result) { + if (!env) + return 1 /* napi_status.napi_invalid_arg */; + // @ts-expect-error + var envObject = emnapiCtx.envStore.get(env); + envObject.checkGCAccess(); + if (!envObject.tryCatch.isEmpty()) + return envObject.setLastError(10 /* napi_status.napi_pending_exception */); + if (!envObject.canCallIntoJs()) + return envObject.setLastError(envObject.moduleApiVersion >= 10 ? 23 /* napi_status.napi_cannot_run_js */ : 10 /* napi_status.napi_pending_exception */); + envObject.clearLastError(); + try { + if (!value) + return envObject.setLastError(1 /* napi_status.napi_invalid_arg */); + if (!result) + return envObject.setLastError(1 /* napi_status.napi_invalid_arg */); + var handle = emnapiCtx.handleStore.get(value); + if (!handle.isArray()) { + return envObject.setLastError(8 /* napi_status.napi_array_expected */); + } + result >>>= 0; + // eslint-disable-next-line @typescript-eslint/no-unused-vars + var v = handle.value.length >>> 0; + var HEAP_DATA_VIEW = new DataView(wasmMemory.buffer), GET_HEAP_DATA_VIEW = function () { return HEAP_DATA_VIEW.buffer === wasmMemory.buffer ? HEAP_DATA_VIEW : (HEAP_DATA_VIEW = new DataView(wasmMemory.buffer)); }; + GET_HEAP_DATA_VIEW().setUint32(result, v, true); + return envObject.getReturnStatus(); + } + catch (err) { + envObject.tryCatch.setError(err); + return envObject.setLastError(10 /* napi_status.napi_pending_exception */); + } + } + /** + * @__sig ipppp + */ + function napi_get_arraybuffer_info(env, arraybuffer, data, byte_length) { + if (!env) + return 1 /* napi_status.napi_invalid_arg */; + // @ts-expect-error + var envObject = emnapiCtx.envStore.get(env); + envObject.checkGCAccess(); + if (!arraybuffer) + return envObject.setLastError(1 /* napi_status.napi_invalid_arg */); + var handle = emnapiCtx.handleStore.get(arraybuffer); + if (!handle.isArrayBuffer() && !emnapiExternalMemory.isSharedArrayBuffer(handle.value)) { + return envObject.setLastError(1 /* napi_status.napi_invalid_arg */); + } + var HEAP_DATA_VIEW = new DataView(wasmMemory.buffer), GET_HEAP_DATA_VIEW = function () { return HEAP_DATA_VIEW.buffer === wasmMemory.buffer ? HEAP_DATA_VIEW : (HEAP_DATA_VIEW = new DataView(wasmMemory.buffer)); }; + // metadata is read through cached intrinsic getters (internal slots, like + // native Node-API): no user JS can run inside this call. Only emnapi's own + // getArrayBufferPointer() can still grow the memory (malloc for the copy of + // an external buffer), which detaches the previous non-shared buffer, so + // each value is resolved into a local BEFORE its makeSetValue write (the + // store target is evaluated before the RHS). + if (data) { + data >>>= 0; + // eslint-disable-next-line @typescript-eslint/no-unused-vars + var p = emnapiExternalMemory.getArrayBufferPointer(handle.value, true).address; + GET_HEAP_DATA_VIEW().setUint32(data, p, true); + } + if (byte_length) { + byte_length >>>= 0; + // eslint-disable-next-line @typescript-eslint/no-unused-vars + var len = emnapiExternalMemory.bufferByteLength(handle.value); + GET_HEAP_DATA_VIEW().setUint32(byte_length, len, true); + } + return envObject.clearLastError(); + } + /** + * @__sig ippp + */ + function node_api_set_prototype(env, object, value) { + if (!env) + return 1 /* napi_status.napi_invalid_arg */; + // @ts-expect-error + var envObject = emnapiCtx.envStore.get(env); + envObject.checkGCAccess(); + if (!envObject.tryCatch.isEmpty()) + return envObject.setLastError(10 /* napi_status.napi_pending_exception */); + if (!envObject.canCallIntoJs()) + return envObject.setLastError(envObject.moduleApiVersion >= 10 ? 23 /* napi_status.napi_cannot_run_js */ : 10 /* napi_status.napi_pending_exception */); + envObject.clearLastError(); + try { + if (!value) + return envObject.setLastError(1 /* napi_status.napi_invalid_arg */); + var obj = emnapiCtx.handleStore.get(object).value; + if (obj == null) { + throw new TypeError('Cannot convert undefined or null to object'); + } + var type = typeof obj; + var v = void 0; + try { + v = (type === 'object' && obj !== null) || type === 'function' ? obj : Object(obj); + } + catch (_) { + return envObject.setLastError(2 /* napi_status.napi_object_expected */); + } + var val = emnapiCtx.handleStore.get(value).value; + Object.setPrototypeOf(v, val); + return envObject.getReturnStatus(); + } + catch (err) { + envObject.tryCatch.setError(err); + return envObject.setLastError(10 /* napi_status.napi_pending_exception */); + } + } + /** + * @__sig ippp + */ + function napi_get_prototype(env, value, result) { + if (!env) + return 1 /* napi_status.napi_invalid_arg */; + // @ts-expect-error + var envObject = emnapiCtx.envStore.get(env); + envObject.checkGCAccess(); + if (!envObject.tryCatch.isEmpty()) + return envObject.setLastError(10 /* napi_status.napi_pending_exception */); + if (!envObject.canCallIntoJs()) + return envObject.setLastError(envObject.moduleApiVersion >= 10 ? 23 /* napi_status.napi_cannot_run_js */ : 10 /* napi_status.napi_pending_exception */); + envObject.clearLastError(); + try { + if (!value) + return envObject.setLastError(1 /* napi_status.napi_invalid_arg */); + if (!result) + return envObject.setLastError(1 /* napi_status.napi_invalid_arg */); + var handle = emnapiCtx.handleStore.get(value); + if (handle.value == null) { + throw new TypeError('Cannot convert undefined or null to object'); + } + var v = void 0; + try { + v = handle.isObject() || handle.isFunction() ? handle.value : Object(handle.value); + } + catch (_) { + return envObject.setLastError(2 /* napi_status.napi_object_expected */); + } + result >>>= 0; + // eslint-disable-next-line @typescript-eslint/no-unused-vars + var p = envObject.ensureHandleId(Object.getPrototypeOf(v)); + var HEAP_DATA_VIEW = new DataView(wasmMemory.buffer), GET_HEAP_DATA_VIEW = function () { return HEAP_DATA_VIEW.buffer === wasmMemory.buffer ? HEAP_DATA_VIEW : (HEAP_DATA_VIEW = new DataView(wasmMemory.buffer)); }; + GET_HEAP_DATA_VIEW().setUint32(result, p, true); + return envObject.getReturnStatus(); + } + catch (err) { + envObject.tryCatch.setError(err); + return envObject.setLastError(10 /* napi_status.napi_pending_exception */); + } + } + /** + * @__sig ippppppp + */ + function napi_get_typedarray_info(env, typedarray, type, length, data, arraybuffer, byte_offset) { + if (!env) + return 1 /* napi_status.napi_invalid_arg */; + // @ts-expect-error + var envObject = emnapiCtx.envStore.get(env); + envObject.checkGCAccess(); + if (!typedarray) + return envObject.setLastError(1 /* napi_status.napi_invalid_arg */); + var handle = emnapiCtx.handleStore.get(typedarray); + if (!(emnapiExternalMemory.intrinsics.isView(handle.value))) { + return envObject.setLastError(1 /* napi_status.napi_invalid_arg */); + } + var v = handle.value; + var HEAP_DATA_VIEW = new DataView(wasmMemory.buffer), GET_HEAP_DATA_VIEW = function () { return HEAP_DATA_VIEW.buffer === wasmMemory.buffer ? HEAP_DATA_VIEW : (HEAP_DATA_VIEW = new DataView(wasmMemory.buffer)); }; + // all view metadata (kind, buffer, byteOffset, length) is read through + // cached intrinsic prototype getters: like native Node-API they read the + // internal slots, never consult user accessors (no user JS can run inside + // this call) and work for instances from any realm. Only emnapi's own + // getViewPointer() can still grow the memory (malloc for the copy of an + // external buffer), which detaches the previous non-shared buffer, so each + // value is resolved into a local BEFORE its makeSetValue write (the store + // target is evaluated before the RHS). + if (type) { + type >>>= 0; + var t = void 0; + switch (emnapiExternalMemory.intrinsics.typedArray.tag.call(v)) { + case 'Int8Array': + t = 0 /* napi_typedarray_type.napi_int8_array */; + break; + case 'Uint8Array': + t = 1 /* napi_typedarray_type.napi_uint8_array */; + break; + case 'Uint8ClampedArray': + t = 2 /* napi_typedarray_type.napi_uint8_clamped_array */; + break; + case 'Int16Array': + t = 3 /* napi_typedarray_type.napi_int16_array */; + break; + case 'Uint16Array': + t = 4 /* napi_typedarray_type.napi_uint16_array */; + break; + case 'Int32Array': + t = 5 /* napi_typedarray_type.napi_int32_array */; + break; + case 'Uint32Array': + t = 6 /* napi_typedarray_type.napi_uint32_array */; + break; + case 'Float16Array': + t = 11 /* napi_typedarray_type.napi_float16_array */; + break; + case 'Float32Array': + t = 7 /* napi_typedarray_type.napi_float32_array */; + break; + case 'Float64Array': + t = 8 /* napi_typedarray_type.napi_float64_array */; + break; + case 'BigInt64Array': + t = 9 /* napi_typedarray_type.napi_bigint64_array */; + break; + // eslint-disable-next-line @typescript-eslint/no-unused-vars + case 'BigUint64Array': + t = 10 /* napi_typedarray_type.napi_biguint64_array */; + break; + default: + return envObject.setLastError(9 /* napi_status.napi_generic_failure */); + } + GET_HEAP_DATA_VIEW().setInt32(type, t, true); + } + v = emnapiExternalMemory.getOrUpdateMemoryView(v); + if (length) { + length >>>= 0; + // eslint-disable-next-line @typescript-eslint/no-unused-vars + var len = emnapiExternalMemory.viewLength(v); + GET_HEAP_DATA_VIEW().setUint32(length, len, true); + } + if (data || arraybuffer) { + if (data) { + data >>>= 0; + var vp = emnapiExternalMemory.getViewPointer(v, true); + v = vp.view; + // eslint-disable-next-line @typescript-eslint/no-unused-vars + var p = vp.address; + GET_HEAP_DATA_VIEW().setUint32(data, p, true); + } + if (arraybuffer) { + arraybuffer >>>= 0; + // eslint-disable-next-line @typescript-eslint/no-unused-vars + var ab = envObject.ensureHandleId(emnapiExternalMemory.viewBuffer(v)); + GET_HEAP_DATA_VIEW().setUint32(arraybuffer, ab, true); + } + } + if (byte_offset) { + byte_offset >>>= 0; + // eslint-disable-next-line @typescript-eslint/no-unused-vars + var offset = emnapiExternalMemory.viewByteOffset(v); + GET_HEAP_DATA_VIEW().setUint32(byte_offset, offset, true); + } + return envObject.clearLastError(); + } + /** + * @__sig ipppp + */ + function napi_get_buffer_info(env, buffer, data, length) { + if (!env) + return 1 /* napi_status.napi_invalid_arg */; + // @ts-expect-error + var envObject = emnapiCtx.envStore.get(env); + envObject.checkGCAccess(); + if (!buffer) + return envObject.setLastError(1 /* napi_status.napi_invalid_arg */); + var handle = emnapiCtx.handleStore.get(buffer); + var Buffer = emnapiCtx.feature.Buffer; + var bool = (emnapiExternalMemory.intrinsics.isView(handle.value) || (typeof Buffer === 'function' && Buffer.isBuffer(handle.value))); + if (!bool) + return envObject.setLastError(1 /* napi_status.napi_invalid_arg */); + // any-realm slot-based classification: the intrinsic @@toStringTag getter + // returns undefined exactly for DataViews among ArrayBuffer views + if (emnapiExternalMemory.intrinsics.typedArray.tag.call(handle.value) === undefined) { + return napi_get_dataview_info(env, buffer, length, data, 0, 0); + } + return napi_get_typedarray_info(env, buffer, 0, length, data, 0, 0); + } + /** + * @__sig ipppppp + */ + function napi_get_dataview_info(env, dataview, byte_length, data, arraybuffer, byte_offset) { + if (!env) + return 1 /* napi_status.napi_invalid_arg */; + // @ts-expect-error + var envObject = emnapiCtx.envStore.get(env); + envObject.checkGCAccess(); + if (!dataview) + return envObject.setLastError(1 /* napi_status.napi_invalid_arg */); + var handle = emnapiCtx.handleStore.get(dataview); + // any-realm slot-based classification (see napi_get_buffer_info) + if (!(emnapiExternalMemory.intrinsics.isView(handle.value)) || emnapiExternalMemory.intrinsics.typedArray.tag.call(handle.value) !== undefined) { + return envObject.setLastError(1 /* napi_status.napi_invalid_arg */); + } + var v = emnapiExternalMemory.getOrUpdateMemoryView(handle.value); + var HEAP_DATA_VIEW = new DataView(wasmMemory.buffer), GET_HEAP_DATA_VIEW = function () { return HEAP_DATA_VIEW.buffer === wasmMemory.buffer ? HEAP_DATA_VIEW : (HEAP_DATA_VIEW = new DataView(wasmMemory.buffer)); }; + // all view metadata is read through cached intrinsic prototype getters: + // like native Node-API they read the internal slots, never consult user + // accessors (no user JS can run inside this call) and work for instances + // from any realm. Only emnapi's own getViewPointer() can still grow the + // memory (malloc for the copy of an external buffer), which detaches the + // previous non-shared buffer, so each value is resolved into a local + // BEFORE its makeSetValue write (the store target is evaluated before + // the RHS). + if (byte_length) { + byte_length >>>= 0; + // eslint-disable-next-line @typescript-eslint/no-unused-vars + var len = emnapiExternalMemory.viewLength(v); + GET_HEAP_DATA_VIEW().setUint32(byte_length, len, true); + } + if (data || arraybuffer) { + if (data) { + data >>>= 0; + var vp = emnapiExternalMemory.getViewPointer(v, true); + v = vp.view; + // eslint-disable-next-line @typescript-eslint/no-unused-vars + var p = vp.address; + GET_HEAP_DATA_VIEW().setUint32(data, p, true); + } + if (arraybuffer) { + arraybuffer >>>= 0; + // eslint-disable-next-line @typescript-eslint/no-unused-vars + var ab = envObject.ensureHandleId(emnapiExternalMemory.viewBuffer(v)); + GET_HEAP_DATA_VIEW().setUint32(arraybuffer, ab, true); + } + } + if (byte_offset) { + byte_offset >>>= 0; + // eslint-disable-next-line @typescript-eslint/no-unused-vars + var offset = emnapiExternalMemory.viewByteOffset(v); + GET_HEAP_DATA_VIEW().setUint32(byte_offset, offset, true); + } + return envObject.clearLastError(); + } + /** + * @__sig ippp + */ + function napi_get_date_value(env, value, result) { + // eslint-disable-next-line @typescript-eslint/no-unused-vars + var v; + if (!env) + return 1 /* napi_status.napi_invalid_arg */; + // @ts-expect-error + var envObject = emnapiCtx.envStore.get(env); + envObject.checkGCAccess(); + if (!envObject.tryCatch.isEmpty()) + return envObject.setLastError(10 /* napi_status.napi_pending_exception */); + if (!envObject.canCallIntoJs()) + return envObject.setLastError(envObject.moduleApiVersion >= 10 ? 23 /* napi_status.napi_cannot_run_js */ : 10 /* napi_status.napi_pending_exception */); + envObject.clearLastError(); + try { + if (!value) + return envObject.setLastError(1 /* napi_status.napi_invalid_arg */); + if (!result) + return envObject.setLastError(1 /* napi_status.napi_invalid_arg */); + var handle = emnapiCtx.handleStore.get(value); + if (!handle.isDate()) { + return envObject.setLastError(1 /* napi_status.napi_invalid_arg */); + } + result >>>= 0; + v = handle.value.valueOf(); + var HEAP_DATA_VIEW = new DataView(wasmMemory.buffer), GET_HEAP_DATA_VIEW = function () { return HEAP_DATA_VIEW.buffer === wasmMemory.buffer ? HEAP_DATA_VIEW : (HEAP_DATA_VIEW = new DataView(wasmMemory.buffer)); }; + GET_HEAP_DATA_VIEW().setFloat64(result, v, true); + return envObject.getReturnStatus(); + } + catch (err) { + envObject.tryCatch.setError(err); + return envObject.setLastError(10 /* napi_status.napi_pending_exception */); + } + } + /** + * @__sig ippp + */ + function napi_get_value_bool(env, value, result) { + if (!env) + return 1 /* napi_status.napi_invalid_arg */; + // @ts-expect-error + var envObject = emnapiCtx.envStore.get(env); + envObject.checkGCAccess(); + if (!value) + return envObject.setLastError(1 /* napi_status.napi_invalid_arg */); + if (!result) + return envObject.setLastError(1 /* napi_status.napi_invalid_arg */); + var handle = emnapiCtx.handleStore.get(value); + if (typeof handle.value !== 'boolean') { + return envObject.setLastError(7 /* napi_status.napi_boolean_expected */); + } + result >>>= 0; + // eslint-disable-next-line @typescript-eslint/no-unused-vars + var r = handle.value ? 1 : 0; + var HEAP_DATA_VIEW = new DataView(wasmMemory.buffer), GET_HEAP_DATA_VIEW = function () { return HEAP_DATA_VIEW.buffer === wasmMemory.buffer ? HEAP_DATA_VIEW : (HEAP_DATA_VIEW = new DataView(wasmMemory.buffer)); }; + GET_HEAP_DATA_VIEW().setInt8(result, r, true); + return envObject.clearLastError(); + } + /** + * @__sig ippp + */ + function napi_get_value_double(env, value, result) { + if (!env) + return 1 /* napi_status.napi_invalid_arg */; + // @ts-expect-error + var envObject = emnapiCtx.envStore.get(env); + envObject.checkGCAccess(); + if (!value) + return envObject.setLastError(1 /* napi_status.napi_invalid_arg */); + if (!result) + return envObject.setLastError(1 /* napi_status.napi_invalid_arg */); + var handle = emnapiCtx.handleStore.get(value); + if (typeof handle.value !== 'number') { + return envObject.setLastError(6 /* napi_status.napi_number_expected */); + } + result >>>= 0; + // eslint-disable-next-line @typescript-eslint/no-unused-vars + var r = handle.value; + var HEAP_DATA_VIEW = new DataView(wasmMemory.buffer), GET_HEAP_DATA_VIEW = function () { return HEAP_DATA_VIEW.buffer === wasmMemory.buffer ? HEAP_DATA_VIEW : (HEAP_DATA_VIEW = new DataView(wasmMemory.buffer)); }; + GET_HEAP_DATA_VIEW().setFloat64(result, r, true); + return envObject.clearLastError(); + } + /** + * @__sig ipppp + */ + function napi_get_value_bigint_int64(env, value, result, lossless) { + if (!env) + return 1 /* napi_status.napi_invalid_arg */; + // @ts-expect-error + var envObject = emnapiCtx.envStore.get(env); + envObject.checkGCAccess(); + if (!emnapiCtx.feature.supportBigInt) { + return envObject.setLastError(9 /* napi_status.napi_generic_failure */); + } + if (!value) + return envObject.setLastError(1 /* napi_status.napi_invalid_arg */); + if (!result) + return envObject.setLastError(1 /* napi_status.napi_invalid_arg */); + if (!lossless) + return envObject.setLastError(1 /* napi_status.napi_invalid_arg */); + var handle = emnapiCtx.handleStore.get(value); + var numberValue = handle.value; + if (typeof numberValue !== 'bigint') { + return envObject.setLastError(6 /* napi_status.napi_number_expected */); + } + lossless >>>= 0; + result >>>= 0; + var HEAP_DATA_VIEW = new DataView(wasmMemory.buffer), GET_HEAP_DATA_VIEW = function () { return HEAP_DATA_VIEW.buffer === wasmMemory.buffer ? HEAP_DATA_VIEW : (HEAP_DATA_VIEW = new DataView(wasmMemory.buffer)); }; + if ((numberValue >= (BigInt(-1) * (BigInt(1) << BigInt(63)))) && (numberValue < (BigInt(1) << BigInt(63)))) { + GET_HEAP_DATA_VIEW().setInt8(lossless, 1, true); + } + else { + GET_HEAP_DATA_VIEW().setInt8(lossless, 0, true); + numberValue = numberValue & ((BigInt(1) << BigInt(64)) - BigInt(1)); + if (numberValue >= (BigInt(1) << BigInt(63))) { + numberValue = numberValue - (BigInt(1) << BigInt(64)); + } + } + // eslint-disable-next-line @typescript-eslint/no-unused-vars + var low = Number(numberValue & BigInt(0xffffffff)); + // eslint-disable-next-line @typescript-eslint/no-unused-vars + var high = Number(numberValue >> BigInt(32)); + GET_HEAP_DATA_VIEW().setInt32(result, low, true); + GET_HEAP_DATA_VIEW().setInt32(result + 4, high, true); + return envObject.clearLastError(); + } + /** + * @__sig ipppp + */ + function napi_get_value_bigint_uint64(env, value, result, lossless) { + if (!env) + return 1 /* napi_status.napi_invalid_arg */; + // @ts-expect-error + var envObject = emnapiCtx.envStore.get(env); + envObject.checkGCAccess(); + if (!emnapiCtx.feature.supportBigInt) { + return envObject.setLastError(9 /* napi_status.napi_generic_failure */); + } + if (!value) + return envObject.setLastError(1 /* napi_status.napi_invalid_arg */); + if (!result) + return envObject.setLastError(1 /* napi_status.napi_invalid_arg */); + if (!lossless) + return envObject.setLastError(1 /* napi_status.napi_invalid_arg */); + var handle = emnapiCtx.handleStore.get(value); + var numberValue = handle.value; + if (typeof numberValue !== 'bigint') { + return envObject.setLastError(6 /* napi_status.napi_number_expected */); + } + lossless >>>= 0; + result >>>= 0; + var HEAP_DATA_VIEW = new DataView(wasmMemory.buffer), GET_HEAP_DATA_VIEW = function () { return HEAP_DATA_VIEW.buffer === wasmMemory.buffer ? HEAP_DATA_VIEW : (HEAP_DATA_VIEW = new DataView(wasmMemory.buffer)); }; + if ((numberValue >= BigInt(0)) && (numberValue < (BigInt(1) << BigInt(64)))) { + GET_HEAP_DATA_VIEW().setInt8(lossless, 1, true); + } + else { + GET_HEAP_DATA_VIEW().setInt8(lossless, 0, true); + numberValue = numberValue & ((BigInt(1) << BigInt(64)) - BigInt(1)); + } + // eslint-disable-next-line @typescript-eslint/no-unused-vars + var low = Number(numberValue & BigInt(0xffffffff)); + // eslint-disable-next-line @typescript-eslint/no-unused-vars + var high = Number(numberValue >> BigInt(32)); + GET_HEAP_DATA_VIEW().setUint32(result, low, true); + GET_HEAP_DATA_VIEW().setUint32(result + 4, high, true); + return envObject.clearLastError(); + } + /** + * @__sig ippppp + */ + function napi_get_value_bigint_words(env, value, sign_bit, word_count, words) { + if (!env) + return 1 /* napi_status.napi_invalid_arg */; + // @ts-expect-error + var envObject = emnapiCtx.envStore.get(env); + envObject.checkGCAccess(); + if (!emnapiCtx.feature.supportBigInt) { + return envObject.setLastError(9 /* napi_status.napi_generic_failure */); + } + if (!value) + return envObject.setLastError(1 /* napi_status.napi_invalid_arg */); + if (!word_count) + return envObject.setLastError(1 /* napi_status.napi_invalid_arg */); + var handle = emnapiCtx.handleStore.get(value); + if (!handle.isBigInt()) { + return envObject.setLastError(17 /* napi_status.napi_bigint_expected */); + } + var isMinus = handle.value < BigInt(0); + sign_bit >>>= 0; + words >>>= 0; + word_count >>>= 0; + var HEAP_DATA_VIEW = new DataView(wasmMemory.buffer), GET_HEAP_DATA_VIEW = function () { return HEAP_DATA_VIEW.buffer === wasmMemory.buffer ? HEAP_DATA_VIEW : (HEAP_DATA_VIEW = new DataView(wasmMemory.buffer)); }; + var word_count_int = GET_HEAP_DATA_VIEW().getUint32(word_count, true); + word_count_int >>>= 0; + var wordCount = 0; + var bigintValue = isMinus ? (handle.value * BigInt(-1)) : handle.value; + while (bigintValue !== BigInt(0)) { + wordCount++; + bigintValue = bigintValue >> BigInt(64); + } + bigintValue = isMinus ? (handle.value * BigInt(-1)) : handle.value; + if (!sign_bit && !words) { + word_count_int = wordCount; + GET_HEAP_DATA_VIEW().setUint32(word_count, word_count_int, true); + } + else { + if (!sign_bit) + return envObject.setLastError(1 /* napi_status.napi_invalid_arg */); + if (!words) + return envObject.setLastError(1 /* napi_status.napi_invalid_arg */); + var wordsArr = []; + while (bigintValue !== BigInt(0)) { + var uint64 = bigintValue & ((BigInt(1) << BigInt(64)) - BigInt(1)); + wordsArr.push(uint64); + bigintValue = bigintValue >> BigInt(64); + } + var len = Math.min(word_count_int, wordsArr.length); + for (var i = 0; i < len; i++) { + // eslint-disable-next-line @typescript-eslint/no-unused-vars + var low = Number(wordsArr[i] & BigInt(0xffffffff)); + // eslint-disable-next-line @typescript-eslint/no-unused-vars + var high = Number(wordsArr[i] >> BigInt(32)); + GET_HEAP_DATA_VIEW().setUint32(words + i * 8, low, true); + GET_HEAP_DATA_VIEW().setUint32(words + (i * 8 + 4), high, true); + } + GET_HEAP_DATA_VIEW().setInt32(sign_bit, isMinus ? 1 : 0, true); + GET_HEAP_DATA_VIEW().setUint32(word_count, len, true); + } + return envObject.clearLastError(); + } + /** + * @__sig ippp + */ + function napi_get_value_external(env, value, result) { + if (!env) + return 1 /* napi_status.napi_invalid_arg */; + // @ts-expect-error + var envObject = emnapiCtx.envStore.get(env); + envObject.checkGCAccess(); + if (!value) + return envObject.setLastError(1 /* napi_status.napi_invalid_arg */); + if (!result) + return envObject.setLastError(1 /* napi_status.napi_invalid_arg */); + var handle = emnapiCtx.handleStore.get(value); + if (!handle.isExternal()) { + return envObject.setLastError(1 /* napi_status.napi_invalid_arg */); + } + result >>>= 0; + // eslint-disable-next-line @typescript-eslint/no-unused-vars + var p = handle.data(); + var HEAP_DATA_VIEW = new DataView(wasmMemory.buffer), GET_HEAP_DATA_VIEW = function () { return HEAP_DATA_VIEW.buffer === wasmMemory.buffer ? HEAP_DATA_VIEW : (HEAP_DATA_VIEW = new DataView(wasmMemory.buffer)); }; + GET_HEAP_DATA_VIEW().setUint32(result, p, true); + return envObject.clearLastError(); + } + /** + * @__sig ippp + */ + function napi_get_value_int32(env, value, result) { + if (!env) + return 1 /* napi_status.napi_invalid_arg */; + // @ts-expect-error + var envObject = emnapiCtx.envStore.get(env); + envObject.checkGCAccess(); + if (!value) + return envObject.setLastError(1 /* napi_status.napi_invalid_arg */); + if (!result) + return envObject.setLastError(1 /* napi_status.napi_invalid_arg */); + var handle = emnapiCtx.handleStore.get(value); + if (typeof handle.value !== 'number') { + return envObject.setLastError(6 /* napi_status.napi_number_expected */); + } + result >>>= 0; + // eslint-disable-next-line @typescript-eslint/no-unused-vars + var v = new Int32Array([handle.value])[0]; + var HEAP_DATA_VIEW = new DataView(wasmMemory.buffer), GET_HEAP_DATA_VIEW = function () { return HEAP_DATA_VIEW.buffer === wasmMemory.buffer ? HEAP_DATA_VIEW : (HEAP_DATA_VIEW = new DataView(wasmMemory.buffer)); }; + GET_HEAP_DATA_VIEW().setInt32(result, v, true); + return envObject.clearLastError(); + } + /** + * @__sig ippp + */ + function napi_get_value_int64(env, value, result) { + if (!env) + return 1 /* napi_status.napi_invalid_arg */; + // @ts-expect-error + var envObject = emnapiCtx.envStore.get(env); + envObject.checkGCAccess(); + if (!value) + return envObject.setLastError(1 /* napi_status.napi_invalid_arg */); + if (!result) + return envObject.setLastError(1 /* napi_status.napi_invalid_arg */); + var handle = emnapiCtx.handleStore.get(value); + if (typeof handle.value !== 'number') { + return envObject.setLastError(6 /* napi_status.napi_number_expected */); + } + var numberValue = handle.value; + result >>>= 0; + var HEAP_DATA_VIEW = new DataView(wasmMemory.buffer), GET_HEAP_DATA_VIEW = function () { return HEAP_DATA_VIEW.buffer === wasmMemory.buffer ? HEAP_DATA_VIEW : (HEAP_DATA_VIEW = new DataView(wasmMemory.buffer)); }; + if (numberValue === Number.POSITIVE_INFINITY || numberValue === Number.NEGATIVE_INFINITY || isNaN(numberValue)) { + GET_HEAP_DATA_VIEW().setInt32(result, 0, true); + GET_HEAP_DATA_VIEW().setInt32(result + 4, 0, true); + } + else if (numberValue < /* INT64_RANGE_NEGATIVE */ -9223372036854776e3) { + GET_HEAP_DATA_VIEW().setInt32(result, 0, true); + GET_HEAP_DATA_VIEW().setInt32(result + 4, 2147483648, true); + } + else if (numberValue >= /* INT64_RANGE_POSITIVE */ 9223372036854776000) { + GET_HEAP_DATA_VIEW().setUint32(result, 4294967295, true); + GET_HEAP_DATA_VIEW().setUint32(result + 4, 2147483647, true); + } + else { + $emnapiSetValueI64(result, Math.trunc(numberValue)); + } + return envObject.clearLastError(); + } + /** + * @__sig ippppp + */ + function napi_get_value_string_latin1(env, value, buf, buf_size, result) { + if (!env) + return 1 /* napi_status.napi_invalid_arg */; + // @ts-expect-error + var envObject = emnapiCtx.envStore.get(env); + envObject.checkGCAccess(); + if (!value) + return envObject.setLastError(1 /* napi_status.napi_invalid_arg */); + result >>>= 0; + buf >>>= 0; + buf_size >>>= 0; + buf_size = buf_size >>> 0; + var handle = emnapiCtx.handleStore.get(value); + if (typeof handle.value !== 'string') { + return envObject.setLastError(3 /* napi_status.napi_string_expected */); + } + var HEAP_DATA_VIEW = new DataView(wasmMemory.buffer), GET_HEAP_DATA_VIEW = function () { return HEAP_DATA_VIEW.buffer === wasmMemory.buffer ? HEAP_DATA_VIEW : (HEAP_DATA_VIEW = new DataView(wasmMemory.buffer)); }; + if (!buf) { + if (!result) + return envObject.setLastError(1 /* napi_status.napi_invalid_arg */); + GET_HEAP_DATA_VIEW().setUint32(result, handle.value.length, true); + } + else if (buf_size !== 0) { + var copied = 0; + var v = void 0; + for (var i = 0; i < buf_size - 1; ++i) { + // eslint-disable-next-line @typescript-eslint/no-unused-vars + v = handle.value.charCodeAt(i) & 0xff; + GET_HEAP_DATA_VIEW().setUint8(buf + i, v, true); + // eslint-disable-next-line @typescript-eslint/no-unused-vars + copied++; + } + GET_HEAP_DATA_VIEW().setUint8(buf + copied, 0, true); + if (result) { + GET_HEAP_DATA_VIEW().setUint32(result, copied, true); + } + } + else if (result) { + GET_HEAP_DATA_VIEW().setUint32(result, 0, true); + } + return envObject.clearLastError(); + } + /** + * @__sig ippppp + */ + function napi_get_value_string_utf8(env, value, buf, buf_size, result) { + if (!env) + return 1 /* napi_status.napi_invalid_arg */; + // @ts-expect-error + var envObject = emnapiCtx.envStore.get(env); + envObject.checkGCAccess(); + if (!value) + return envObject.setLastError(1 /* napi_status.napi_invalid_arg */); + result >>>= 0; + buf >>>= 0; + buf_size >>>= 0; + buf_size = buf_size >>> 0; + var handle = emnapiCtx.handleStore.get(value); + if (typeof handle.value !== 'string') { + return envObject.setLastError(3 /* napi_status.napi_string_expected */); + } + var HEAP_DATA_VIEW = new DataView(wasmMemory.buffer), GET_HEAP_DATA_VIEW = function () { return HEAP_DATA_VIEW.buffer === wasmMemory.buffer ? HEAP_DATA_VIEW : (HEAP_DATA_VIEW = new DataView(wasmMemory.buffer)); }; + if (!buf) { + if (!result) + return envObject.setLastError(1 /* napi_status.napi_invalid_arg */); + // eslint-disable-next-line @typescript-eslint/no-unused-vars + var strLength = emnapiString.lengthBytesUTF8(handle.value); + GET_HEAP_DATA_VIEW().setUint32(result, strLength, true); + } + else if (buf_size !== 0) { + // eslint-disable-next-line @typescript-eslint/no-unused-vars + var copied = emnapiString.stringToUTF8(handle.value, buf, buf_size); + if (result) { + GET_HEAP_DATA_VIEW().setUint32(result, copied, true); + } + } + else if (result) { + GET_HEAP_DATA_VIEW().setUint32(result, 0, true); + } + return envObject.clearLastError(); + } + /** + * @__sig ippppp + */ + function napi_get_value_string_utf16(env, value, buf, buf_size, result) { + if (!env) + return 1 /* napi_status.napi_invalid_arg */; + // @ts-expect-error + var envObject = emnapiCtx.envStore.get(env); + envObject.checkGCAccess(); + if (!value) + return envObject.setLastError(1 /* napi_status.napi_invalid_arg */); + result >>>= 0; + buf >>>= 0; + buf_size >>>= 0; + buf_size = buf_size >>> 0; + var handle = emnapiCtx.handleStore.get(value); + if (typeof handle.value !== 'string') { + return envObject.setLastError(3 /* napi_status.napi_string_expected */); + } + var HEAP_DATA_VIEW = new DataView(wasmMemory.buffer), GET_HEAP_DATA_VIEW = function () { return HEAP_DATA_VIEW.buffer === wasmMemory.buffer ? HEAP_DATA_VIEW : (HEAP_DATA_VIEW = new DataView(wasmMemory.buffer)); }; + if (!buf) { + if (!result) + return envObject.setLastError(1 /* napi_status.napi_invalid_arg */); + GET_HEAP_DATA_VIEW().setUint32(result, handle.value.length, true); + } + else if (buf_size !== 0) { + // eslint-disable-next-line @typescript-eslint/no-unused-vars + var copied = emnapiString.stringToUTF16(handle.value, buf, buf_size * 2); + if (result) { + GET_HEAP_DATA_VIEW().setUint32(result, copied / 2, true); + } + } + else if (result) { + GET_HEAP_DATA_VIEW().setUint32(result, 0, true); + } + return envObject.clearLastError(); + } + /** + * @__sig ippp + */ + function napi_get_value_uint32(env, value, result) { + if (!env) + return 1 /* napi_status.napi_invalid_arg */; + // @ts-expect-error + var envObject = emnapiCtx.envStore.get(env); + envObject.checkGCAccess(); + if (!value) + return envObject.setLastError(1 /* napi_status.napi_invalid_arg */); + if (!result) + return envObject.setLastError(1 /* napi_status.napi_invalid_arg */); + var handle = emnapiCtx.handleStore.get(value); + if (typeof handle.value !== 'number') { + return envObject.setLastError(6 /* napi_status.napi_number_expected */); + } + result >>>= 0; + // eslint-disable-next-line @typescript-eslint/no-unused-vars + var v = new Uint32Array([handle.value])[0]; + var HEAP_DATA_VIEW = new DataView(wasmMemory.buffer), GET_HEAP_DATA_VIEW = function () { return HEAP_DATA_VIEW.buffer === wasmMemory.buffer ? HEAP_DATA_VIEW : (HEAP_DATA_VIEW = new DataView(wasmMemory.buffer)); }; + GET_HEAP_DATA_VIEW().setUint32(result, v, true); + return envObject.clearLastError(); + } + var convert2cMod = /*#__PURE__*/ Object.freeze({ + __proto__: null, + napi_get_array_length: napi_get_array_length, + napi_get_arraybuffer_info: napi_get_arraybuffer_info, + napi_get_buffer_info: napi_get_buffer_info, + napi_get_dataview_info: napi_get_dataview_info, + napi_get_date_value: napi_get_date_value, + napi_get_prototype: napi_get_prototype, + napi_get_typedarray_info: napi_get_typedarray_info, + napi_get_value_bigint_int64: napi_get_value_bigint_int64, + napi_get_value_bigint_uint64: napi_get_value_bigint_uint64, + napi_get_value_bigint_words: napi_get_value_bigint_words, + napi_get_value_bool: napi_get_value_bool, + napi_get_value_double: napi_get_value_double, + napi_get_value_external: napi_get_value_external, + napi_get_value_int32: napi_get_value_int32, + napi_get_value_int64: napi_get_value_int64, + napi_get_value_string_latin1: napi_get_value_string_latin1, + napi_get_value_string_utf16: napi_get_value_string_utf16, + napi_get_value_string_utf8: napi_get_value_string_utf8, + napi_get_value_uint32: napi_get_value_uint32, + node_api_set_prototype: node_api_set_prototype + }); + /** + * @__sig ipip + */ + function napi_create_int32(env, value, result) { + if (!env) + return 1 /* napi_status.napi_invalid_arg */; + // @ts-expect-error + var envObject = emnapiCtx.envStore.get(env); + envObject.checkGCAccess(); + if (!result) + return envObject.setLastError(1 /* napi_status.napi_invalid_arg */); + result >>>= 0; + // eslint-disable-next-line @typescript-eslint/no-unused-vars + var v = emnapiCtx.addToCurrentScope(value).id; + var HEAP_DATA_VIEW = new DataView(wasmMemory.buffer), GET_HEAP_DATA_VIEW = function () { return HEAP_DATA_VIEW.buffer === wasmMemory.buffer ? HEAP_DATA_VIEW : (HEAP_DATA_VIEW = new DataView(wasmMemory.buffer)); }; + GET_HEAP_DATA_VIEW().setUint32(result, v, true); + return envObject.clearLastError(); + } + /** + * @__sig ipip + */ + function napi_create_uint32(env, value, result) { + if (!env) + return 1 /* napi_status.napi_invalid_arg */; + // @ts-expect-error + var envObject = emnapiCtx.envStore.get(env); + envObject.checkGCAccess(); + if (!result) + return envObject.setLastError(1 /* napi_status.napi_invalid_arg */); + result >>>= 0; + // eslint-disable-next-line @typescript-eslint/no-unused-vars + var v = emnapiCtx.addToCurrentScope(value >>> 0).id; + var HEAP_DATA_VIEW = new DataView(wasmMemory.buffer), GET_HEAP_DATA_VIEW = function () { return HEAP_DATA_VIEW.buffer === wasmMemory.buffer ? HEAP_DATA_VIEW : (HEAP_DATA_VIEW = new DataView(wasmMemory.buffer)); }; + GET_HEAP_DATA_VIEW().setUint32(result, v, true); + return envObject.clearLastError(); + } + /** + * @__sig ipjp + */ + function napi_create_int64(env, low, high, result) { + if (!env) + return 1 /* napi_status.napi_invalid_arg */; + // @ts-expect-error + var envObject = emnapiCtx.envStore.get(env); + envObject.checkGCAccess(); + var value; + if (!high) + return envObject.setLastError(1 /* napi_status.napi_invalid_arg */); + value = Number(low); + // eslint-disable-next-line @typescript-eslint/no-unused-vars + var v1 = emnapiCtx.addToCurrentScope(value).id; + high >>>= 0; + var HEAP_DATA_VIEW = new DataView(wasmMemory.buffer), GET_HEAP_DATA_VIEW = function () { return HEAP_DATA_VIEW.buffer === wasmMemory.buffer ? HEAP_DATA_VIEW : (HEAP_DATA_VIEW = new DataView(wasmMemory.buffer)); }; + GET_HEAP_DATA_VIEW().setUint32(high, v1, true); + return envObject.clearLastError(); + } + /** + * @__sig ipdp + */ + function napi_create_double(env, value, result) { + if (!env) + return 1 /* napi_status.napi_invalid_arg */; + // @ts-expect-error + var envObject = emnapiCtx.envStore.get(env); + envObject.checkGCAccess(); + if (!result) + return envObject.setLastError(1 /* napi_status.napi_invalid_arg */); + result >>>= 0; + // eslint-disable-next-line @typescript-eslint/no-unused-vars + var v = emnapiCtx.addToCurrentScope(value).id; + var HEAP_DATA_VIEW = new DataView(wasmMemory.buffer), GET_HEAP_DATA_VIEW = function () { return HEAP_DATA_VIEW.buffer === wasmMemory.buffer ? HEAP_DATA_VIEW : (HEAP_DATA_VIEW = new DataView(wasmMemory.buffer)); }; + GET_HEAP_DATA_VIEW().setUint32(result, v, true); + return envObject.clearLastError(); + } + /** + * @__sig ipppp + */ + function napi_create_string_latin1(env, str, length, result) { + return emnapiString.newString(env, str, length, result, function (str, autoLength, sizeLength) { + var latin1String = ''; + var len = 0; + var HEAP_DATA_VIEW = new DataView(wasmMemory.buffer), GET_HEAP_DATA_VIEW = function () { return HEAP_DATA_VIEW.buffer === wasmMemory.buffer ? HEAP_DATA_VIEW : (HEAP_DATA_VIEW = new DataView(wasmMemory.buffer)); }; + if (autoLength) { + while (true) { + var ch = GET_HEAP_DATA_VIEW().getUint8(str, true); + if (!ch) + break; + latin1String += String.fromCharCode(ch); + str++; + } + } + else { + while (len < sizeLength) { + var ch = GET_HEAP_DATA_VIEW().getUint8(str, true); + if (!ch) + break; + latin1String += String.fromCharCode(ch); + len++; + str++; + } + } + return latin1String; + }); + } + /** + * @__sig ipppp + */ + function napi_create_string_utf16(env, str, length, result) { + return emnapiString.newString(env, str, length, result, function (str) { + return emnapiString.UTF16ToString(str, length); + }); + } + /** + * @__sig ipppp + */ + function napi_create_string_utf8(env, str, length, result) { + return emnapiString.newString(env, str, length, result, function (str) { + return emnapiString.UTF8ToString(str, length); + }); + } + /** + * @__sig ippppppp + */ + function node_api_create_external_string_latin1(env, str, length, finalize_callback, finalize_hint, result, copied) { + return emnapiString.newExternalString(env, str, length, finalize_callback, finalize_hint, result, copied, napi_create_string_latin1, undefined); + } + /** + * @__sig ippppppp + */ + function node_api_create_external_string_utf16(env, str, length, finalize_callback, finalize_hint, result, copied) { + return emnapiString.newExternalString(env, str, length, finalize_callback, finalize_hint, result, copied, napi_create_string_utf16, undefined); + } + /** + * @__sig ipppp + */ + function node_api_create_property_key_latin1(env, str, length, result) { + return napi_create_string_latin1(env, str, length, result); + } + /** + * @__sig ipppp + */ + function node_api_create_property_key_utf8(env, str, length, result) { + return napi_create_string_utf8(env, str, length, result); + } + /** + * @__sig ipppp + */ + function node_api_create_property_key_utf16(env, str, length, result) { + return napi_create_string_utf16(env, str, length, result); + } + /** + * @__sig ipjp + */ + function napi_create_bigint_int64(env, low, high, result) { + if (!env) + return 1 /* napi_status.napi_invalid_arg */; + // @ts-expect-error + var envObject = emnapiCtx.envStore.get(env); + envObject.checkGCAccess(); + if (!emnapiCtx.feature.supportBigInt) { + return envObject.setLastError(9 /* napi_status.napi_generic_failure */); + } + var value; + if (!high) + return envObject.setLastError(1 /* napi_status.napi_invalid_arg */); + value = low; + // eslint-disable-next-line @typescript-eslint/no-unused-vars + var v1 = emnapiCtx.addToCurrentScope(value).id; + high >>>= 0; + var HEAP_DATA_VIEW = new DataView(wasmMemory.buffer), GET_HEAP_DATA_VIEW = function () { return HEAP_DATA_VIEW.buffer === wasmMemory.buffer ? HEAP_DATA_VIEW : (HEAP_DATA_VIEW = new DataView(wasmMemory.buffer)); }; + GET_HEAP_DATA_VIEW().setUint32(high, v1, true); + return envObject.clearLastError(); + } + /** + * @__sig ipjp + */ + function napi_create_bigint_uint64(env, low, high, result) { + if (!env) + return 1 /* napi_status.napi_invalid_arg */; + // @ts-expect-error + var envObject = emnapiCtx.envStore.get(env); + envObject.checkGCAccess(); + if (!emnapiCtx.feature.supportBigInt) { + return envObject.setLastError(9 /* napi_status.napi_generic_failure */); + } + var value; + if (!high) + return envObject.setLastError(1 /* napi_status.napi_invalid_arg */); + value = low & ((BigInt(1) << BigInt(64)) - BigInt(1)); + // eslint-disable-next-line @typescript-eslint/no-unused-vars + var v1 = emnapiCtx.addToCurrentScope(value).id; + high >>>= 0; + var HEAP_DATA_VIEW = new DataView(wasmMemory.buffer), GET_HEAP_DATA_VIEW = function () { return HEAP_DATA_VIEW.buffer === wasmMemory.buffer ? HEAP_DATA_VIEW : (HEAP_DATA_VIEW = new DataView(wasmMemory.buffer)); }; + GET_HEAP_DATA_VIEW().setUint32(high, v1, true); + return envObject.clearLastError(); + } + /** + * @__sig ipippp + */ + function napi_create_bigint_words(env, sign_bit, word_count, words, result) { + // eslint-disable-next-line @typescript-eslint/no-unused-vars + var v, i; + if (!env) + return 1 /* napi_status.napi_invalid_arg */; + // @ts-expect-error + var envObject = emnapiCtx.envStore.get(env); + envObject.checkGCAccess(); + if (!envObject.tryCatch.isEmpty()) + return envObject.setLastError(10 /* napi_status.napi_pending_exception */); + if (!envObject.canCallIntoJs()) + return envObject.setLastError(envObject.moduleApiVersion >= 10 ? 23 /* napi_status.napi_cannot_run_js */ : 10 /* napi_status.napi_pending_exception */); + envObject.clearLastError(); + try { + if (!emnapiCtx.feature.supportBigInt) { + return envObject.setLastError(9 /* napi_status.napi_generic_failure */); + } + if (!result) + return envObject.setLastError(1 /* napi_status.napi_invalid_arg */); + words >>>= 0; + word_count >>>= 0; + word_count = word_count >>> 0; + if (word_count > 2147483647) { + return envObject.setLastError(1 /* napi_status.napi_invalid_arg */); + } + if (word_count > (1024 * 1024 / (4 * 8) / 2)) { + throw new RangeError('Maximum BigInt size exceeded'); + } + var value = BigInt(0); + var HEAP_DATA_VIEW = new DataView(wasmMemory.buffer), GET_HEAP_DATA_VIEW = function () { return HEAP_DATA_VIEW.buffer === wasmMemory.buffer ? HEAP_DATA_VIEW : (HEAP_DATA_VIEW = new DataView(wasmMemory.buffer)); }; + for (i = 0; i < word_count; i++) { + var low = GET_HEAP_DATA_VIEW().getUint32(words + i * 8, true); + var high = GET_HEAP_DATA_VIEW().getUint32(words + (i * 8 + 4), true); + var wordi = BigInt(low) | (BigInt(high) << BigInt(32)); + value += wordi << BigInt(64 * i); + } + value *= ((BigInt(sign_bit) % BigInt(2) === BigInt(0)) ? BigInt(1) : BigInt(-1)); + result >>>= 0; + v = emnapiCtx.addToCurrentScope(value).id; + GET_HEAP_DATA_VIEW().setUint32(result, v, true); + return envObject.getReturnStatus(); + } + catch (err) { + envObject.tryCatch.setError(err); + return envObject.setLastError(10 /* napi_status.napi_pending_exception */); + } + } + var convert2napiMod = /*#__PURE__*/ Object.freeze({ + __proto__: null, + napi_create_bigint_int64: napi_create_bigint_int64, + napi_create_bigint_uint64: napi_create_bigint_uint64, + napi_create_bigint_words: napi_create_bigint_words, + napi_create_double: napi_create_double, + napi_create_int32: napi_create_int32, + napi_create_int64: napi_create_int64, + napi_create_string_latin1: napi_create_string_latin1, + napi_create_string_utf16: napi_create_string_utf16, + napi_create_string_utf8: napi_create_string_utf8, + napi_create_uint32: napi_create_uint32, + node_api_create_external_string_latin1: node_api_create_external_string_latin1, + node_api_create_external_string_utf16: node_api_create_external_string_utf16, + node_api_create_property_key_latin1: node_api_create_property_key_latin1, + node_api_create_property_key_utf16: node_api_create_property_key_utf16, + node_api_create_property_key_utf8: node_api_create_property_key_utf8 + }); + function emnapiCreateFunction(envObject, utf8name, length, cb, data) { + utf8name >>>= 0; + var functionName = (!utf8name || !length) ? '' : (emnapiString.UTF8ToString(utf8name, length)); + var f; + var napiCallback = (wasmTable.get(cb)); + var callback = function (envObject) { + return napiCallback(envObject.id, envObject.ctx.scopeStore.currentScope.id); + }; + var makeFunction = function (envObject, callback) { + return function () { + var scope = envObject.ctx.openScope(envObject); + var callbackInfo = scope.callbackInfo; + callbackInfo.data = data; + callbackInfo.args = arguments; + callbackInfo.thiz = this; + callbackInfo.fn = f; + try { + var napiValue = envObject.callIntoModule(callback); + return (!napiValue) ? undefined : envObject.ctx.handleStore.get(napiValue).value; + } + finally { + callbackInfo.data = 0; + callbackInfo.args = undefined; + callbackInfo.thiz = undefined; + callbackInfo.fn = undefined; + envObject.ctx.closeScope(envObject, scope); + } + }; + }; + if (functionName === '') { + f = makeFunction(envObject, callback); + return { status: 0 /* napi_status.napi_ok */, f: f }; + } + if (!(/^[_$a-zA-Z][_$a-zA-Z0-9]*$/.test(functionName))) { + return { status: 1 /* napi_status.napi_invalid_arg */, f: undefined }; + } + if (emnapiCtx.feature.supportNewFunction) { + var _ = makeFunction(envObject, callback); + try { + f = (new Function('_', 'return function ' + functionName + '(){' + + '"use strict";' + + 'return _.apply(this,arguments);' + + '};'))(_); + } + catch (_err) { + f = makeFunction(envObject, callback); + if (emnapiCtx.feature.canSetFunctionName) + Object.defineProperty(f, 'name', { value: functionName }); + } + } + else { + f = makeFunction(envObject, callback); + if (emnapiCtx.feature.canSetFunctionName) + Object.defineProperty(f, 'name', { value: functionName }); + } + return { status: 0 /* napi_status.napi_ok */, f: f }; + } + function emnapiDefineProperty(envObject, obj, propertyName, method, getter, setter, value, attributes, data) { + if (getter || setter) { + var localGetter = void 0; + var localSetter = void 0; + if (getter) { + localGetter = emnapiCreateFunction(envObject, 0, 0, getter, data).f; + } + if (setter) { + localSetter = emnapiCreateFunction(envObject, 0, 0, setter, data).f; + } + var desc = { + configurable: (attributes & 4 /* napi_property_attributes.napi_configurable */) !== 0, + enumerable: (attributes & 2 /* napi_property_attributes.napi_enumerable */) !== 0, + get: localGetter, + set: localSetter + }; + Object.defineProperty(obj, propertyName, desc); + } + else if (method) { + var localMethod = emnapiCreateFunction(envObject, 0, 0, method, data).f; + var desc = { + configurable: (attributes & 4 /* napi_property_attributes.napi_configurable */) !== 0, + enumerable: (attributes & 2 /* napi_property_attributes.napi_enumerable */) !== 0, + writable: (attributes & 1 /* napi_property_attributes.napi_writable */) !== 0, + value: localMethod + }; + Object.defineProperty(obj, propertyName, desc); + } + else { + var desc = { + configurable: (attributes & 4 /* napi_property_attributes.napi_configurable */) !== 0, + enumerable: (attributes & 2 /* napi_property_attributes.napi_enumerable */) !== 0, + writable: (attributes & 1 /* napi_property_attributes.napi_writable */) !== 0, + value: emnapiCtx.handleStore.get(value).value + }; + Object.defineProperty(obj, propertyName, desc); + } + } + function emnapiGetHandle(js_object) { + var handle = emnapiCtx.handleStore.get(js_object); + if (!(handle.isObject() || handle.isFunction())) { + return { status: 1 /* napi_status.napi_invalid_arg */ }; + } + if (typeof emnapiExternalMemory !== 'undefined' && ArrayBuffer.isView(handle.value)) { + if (emnapiExternalMemory.wasmMemoryViewTable.has(handle.value)) { + handle = emnapiCtx.addToCurrentScope(emnapiExternalMemory.wasmMemoryViewTable.get(handle.value)); + } + } + return { status: 0 /* napi_status.napi_ok */, handle: handle }; + } + function emnapiWrap(env, js_object, native_object, finalize_cb, finalize_hint, result) { + // eslint-disable-next-line @typescript-eslint/no-unused-vars + var referenceId; + if (!env) + return 1 /* napi_status.napi_invalid_arg */; + // @ts-expect-error + var envObject = emnapiCtx.envStore.get(env); + envObject.checkGCAccess(); + if (!envObject.tryCatch.isEmpty()) + return envObject.setLastError(10 /* napi_status.napi_pending_exception */); + if (!envObject.canCallIntoJs()) + return envObject.setLastError(envObject.moduleApiVersion >= 10 ? 23 /* napi_status.napi_cannot_run_js */ : 10 /* napi_status.napi_pending_exception */); + envObject.clearLastError(); + try { + if (!emnapiCtx.feature.supportFinalizer) { + if (finalize_cb) { + throw emnapiCtx.createNotSupportWeakRefError('napi_wrap', 'Parameter "finalize_cb" must be 0(NULL)'); + } + if (result) { + throw emnapiCtx.createNotSupportWeakRefError('napi_wrap', 'Parameter "result" must be 0(NULL)'); + } + } + if (!js_object) + return envObject.setLastError(1 /* napi_status.napi_invalid_arg */); + var handleResult = emnapiGetHandle(js_object); + if (handleResult.status !== 0 /* napi_status.napi_ok */) { + return envObject.setLastError(handleResult.status); + } + var handle = handleResult.handle; + if (envObject.getObjectBinding(handle.value).wrapped !== 0) { + return envObject.setLastError(1 /* napi_status.napi_invalid_arg */); + } + var reference = void 0; + if (result) { + if (!finalize_cb) + return envObject.setLastError(1 /* napi_status.napi_invalid_arg */); + reference = emnapiCtx.createReferenceWithFinalizer(envObject, handle.id, 0, 1 /* ReferenceOwnership.kUserland */, finalize_cb, native_object, finalize_hint); + result >>>= 0; + referenceId = reference.id; + var HEAP_DATA_VIEW = new DataView(wasmMemory.buffer), GET_HEAP_DATA_VIEW = function () { return HEAP_DATA_VIEW.buffer === wasmMemory.buffer ? HEAP_DATA_VIEW : (HEAP_DATA_VIEW = new DataView(wasmMemory.buffer)); }; + GET_HEAP_DATA_VIEW().setUint32(result, referenceId, true); + } + else { + if (finalize_cb) { + reference = emnapiCtx.createReferenceWithFinalizer(envObject, handle.id, 0, 0 /* ReferenceOwnership.kRuntime */, finalize_cb, native_object, finalize_hint); + } + else { + reference = emnapiCtx.createReferenceWithData(envObject, handle.id, 0, 0 /* ReferenceOwnership.kRuntime */, native_object); + } + } + envObject.getObjectBinding(handle.value).wrapped = reference.id; + return envObject.getReturnStatus(); + } + catch (err) { + envObject.tryCatch.setError(err); + return envObject.setLastError(10 /* napi_status.napi_pending_exception */); + } + } + function emnapiUnwrap(env, js_object, result, action) { + // eslint-disable-next-line @typescript-eslint/no-unused-vars + var data; + if (!env) + return 1 /* napi_status.napi_invalid_arg */; + // @ts-expect-error + var envObject = emnapiCtx.envStore.get(env); + envObject.checkGCAccess(); + if (!envObject.tryCatch.isEmpty()) + return envObject.setLastError(10 /* napi_status.napi_pending_exception */); + if (!envObject.canCallIntoJs()) + return envObject.setLastError(envObject.moduleApiVersion >= 10 ? 23 /* napi_status.napi_cannot_run_js */ : 10 /* napi_status.napi_pending_exception */); + envObject.clearLastError(); + try { + if (!js_object) + return envObject.setLastError(1 /* napi_status.napi_invalid_arg */); + if (action === 0 /* UnwrapAction.KeepWrap */) { + if (!result) + return envObject.setLastError(1 /* napi_status.napi_invalid_arg */); + } + var value = emnapiCtx.handleStore.get(js_object); + if (!(value.isObject() || value.isFunction())) { + return envObject.setLastError(1 /* napi_status.napi_invalid_arg */); + } + var binding = envObject.getObjectBinding(value.value); + var referenceId = binding.wrapped; + var ref = emnapiCtx.refStore.get(referenceId); + if (!ref) + return envObject.setLastError(1 /* napi_status.napi_invalid_arg */); + if (result) { + result >>>= 0; + // eslint-disable-next-line @typescript-eslint/no-unused-vars + data = ref.data(); + var HEAP_DATA_VIEW = new DataView(wasmMemory.buffer), GET_HEAP_DATA_VIEW = function () { return HEAP_DATA_VIEW.buffer === wasmMemory.buffer ? HEAP_DATA_VIEW : (HEAP_DATA_VIEW = new DataView(wasmMemory.buffer)); }; + GET_HEAP_DATA_VIEW().setUint32(result, data, true); + } + if (action === 1 /* UnwrapAction.RemoveWrap */) { + binding.wrapped = 0; + if (ref.ownership() === 1 /* ReferenceOwnership.kUserland */) { + // When the wrap is been removed, the finalizer should be reset. + ref.resetFinalizer(); + } + else { + ref.dispose(); + } + } + return envObject.getReturnStatus(); + } + catch (err) { + envObject.tryCatch.setError(err); + return envObject.setLastError(10 /* napi_status.napi_pending_exception */); + } + } + /** + * @__sig ipppppppp + */ + function napi_define_class(env, utf8name, length, constructor, callback_data, property_count, properties, result) { + // eslint-disable-next-line @typescript-eslint/no-unused-vars + var propPtr, valueHandleId, attributes; + if (!env) + return 1 /* napi_status.napi_invalid_arg */; + // @ts-expect-error + var envObject = emnapiCtx.envStore.get(env); + envObject.checkGCAccess(); + if (!envObject.tryCatch.isEmpty()) + return envObject.setLastError(10 /* napi_status.napi_pending_exception */); + if (!envObject.canCallIntoJs()) + return envObject.setLastError(envObject.moduleApiVersion >= 10 ? 23 /* napi_status.napi_cannot_run_js */ : 10 /* napi_status.napi_pending_exception */); + envObject.clearLastError(); + try { + if (!result) + return envObject.setLastError(1 /* napi_status.napi_invalid_arg */); + if (!constructor) + return envObject.setLastError(1 /* napi_status.napi_invalid_arg */); + length >>>= 0; + properties >>>= 0; + property_count >>>= 0; + property_count = property_count >>> 0; + if (property_count > 0) { + if (!properties) + return envObject.setLastError(1 /* napi_status.napi_invalid_arg */); + } + if (!((length >= -1 && length <= 2147483647) || length === 4294967295) || (!utf8name)) { + return envObject.setLastError(1 /* napi_status.napi_invalid_arg */); + } + var fresult = emnapiCreateFunction(envObject, utf8name, length, constructor, callback_data); + if (fresult.status !== 0 /* napi_status.napi_ok */) + return envObject.setLastError(fresult.status); + var F = fresult.f; + var propertyName = void 0; + var HEAP_DATA_VIEW = new DataView(wasmMemory.buffer), GET_HEAP_DATA_VIEW = function () { return HEAP_DATA_VIEW.buffer === wasmMemory.buffer ? HEAP_DATA_VIEW : (HEAP_DATA_VIEW = new DataView(wasmMemory.buffer)); }; + for (var i = 0; i < property_count; i++) { + // eslint-disable-next-line @typescript-eslint/no-unused-vars + propPtr = properties + (i * (4 * 8)); + var utf8Name = GET_HEAP_DATA_VIEW().getUint32(propPtr, true); + var name_1 = GET_HEAP_DATA_VIEW().getUint32(propPtr + 4, true); + var method = GET_HEAP_DATA_VIEW().getUint32(propPtr + 8, true); + var getter = GET_HEAP_DATA_VIEW().getUint32(propPtr + 12, true); + var setter = GET_HEAP_DATA_VIEW().getUint32(propPtr + 16, true); + var value = GET_HEAP_DATA_VIEW().getUint32(propPtr + 20, true); + attributes = GET_HEAP_DATA_VIEW().getInt32(propPtr + 24, true); + attributes >>>= 0; + var data = GET_HEAP_DATA_VIEW().getUint32(propPtr + 28, true); + if (utf8Name) { + propertyName = emnapiString.UTF8ToString(utf8Name, -1); + } + else { + if (!name_1) { + return envObject.setLastError(4 /* napi_status.napi_name_expected */); + } + propertyName = emnapiCtx.handleStore.get(name_1).value; + if (typeof propertyName !== 'string' && typeof propertyName !== 'symbol') { + return envObject.setLastError(4 /* napi_status.napi_name_expected */); + } + } + if ((attributes & 1024 /* napi_property_attributes.napi_static */) !== 0) { + emnapiDefineProperty(envObject, F, propertyName, method, getter, setter, value, attributes, data); + continue; + } + emnapiDefineProperty(envObject, F.prototype, propertyName, method, getter, setter, value, attributes, data); + } + // eslint-disable-next-line @typescript-eslint/no-unused-vars + var valueHandle = emnapiCtx.addToCurrentScope(F); + valueHandleId = valueHandle.id; + result >>>= 0; + GET_HEAP_DATA_VIEW().setUint32(result, valueHandleId, true); + return envObject.getReturnStatus(); + } + catch (err) { + envObject.tryCatch.setError(err); + return envObject.setLastError(10 /* napi_status.napi_pending_exception */); + } + } + /** + * @__sig ipppppp + */ + function napi_wrap(env, js_object, native_object, finalize_cb, finalize_hint, result) { + return emnapiWrap(env, js_object, native_object, finalize_cb, finalize_hint, result); + } + /** + * @__sig ippp + */ + function napi_unwrap(env, js_object, result) { + return emnapiUnwrap(env, js_object, result, 0 /* UnwrapAction.KeepWrap */); + } + /** + * @__sig ippp + */ + function napi_remove_wrap(env, js_object, result) { + return emnapiUnwrap(env, js_object, result, 1 /* UnwrapAction.RemoveWrap */); + } + /** + * @__sig ippp + */ + function napi_type_tag_object(env, object, type_tag) { + if (!env) + return 1 /* napi_status.napi_invalid_arg */; + // @ts-expect-error + var envObject = emnapiCtx.envStore.get(env); + envObject.checkGCAccess(); + if (!envObject.tryCatch.isEmpty()) + return envObject.setLastError(10 /* napi_status.napi_pending_exception */); + if (!envObject.canCallIntoJs()) + return envObject.setLastError(envObject.moduleApiVersion >= 10 ? 23 /* napi_status.napi_cannot_run_js */ : 10 /* napi_status.napi_pending_exception */); + envObject.clearLastError(); + try { + if (!object) { + return envObject.setLastError(envObject.tryCatch.hasCaught() ? 10 /* napi_status.napi_pending_exception */ : 1 /* napi_status.napi_invalid_arg */); + } + var value = emnapiCtx.handleStore.get(object); + if (!(value.isObject() || value.isFunction())) { + return envObject.setLastError(envObject.tryCatch.hasCaught() ? 10 /* napi_status.napi_pending_exception */ : 2 /* napi_status.napi_object_expected */); + } + type_tag >>>= 0; + if (!type_tag) { + return envObject.setLastError(envObject.tryCatch.hasCaught() ? 10 /* napi_status.napi_pending_exception */ : 1 /* napi_status.napi_invalid_arg */); + } + var binding = envObject.getObjectBinding(value.value); + if (binding.tag !== null) { + return envObject.setLastError(envObject.tryCatch.hasCaught() ? 10 /* napi_status.napi_pending_exception */ : 1 /* napi_status.napi_invalid_arg */); + } + var tag = new Uint8Array(16); + tag.set(new Uint8Array(wasmMemory.buffer, type_tag, 16)); + binding.tag = new Uint32Array(tag.buffer); + return envObject.getReturnStatus(); + } + catch (err) { + envObject.tryCatch.setError(err); + return envObject.setLastError(10 /* napi_status.napi_pending_exception */); + } + } + /** + * @__sig ipppp + */ + function napi_check_object_type_tag(env, object, type_tag, result) { + // eslint-disable-next-line @typescript-eslint/no-unused-vars, one-var + var ret = true; + if (!env) + return 1 /* napi_status.napi_invalid_arg */; + // @ts-expect-error + var envObject = emnapiCtx.envStore.get(env); + envObject.checkGCAccess(); + if (!envObject.tryCatch.isEmpty()) + return envObject.setLastError(10 /* napi_status.napi_pending_exception */); + if (!envObject.canCallIntoJs()) + return envObject.setLastError(envObject.moduleApiVersion >= 10 ? 23 /* napi_status.napi_cannot_run_js */ : 10 /* napi_status.napi_pending_exception */); + envObject.clearLastError(); + try { + if (!object) { + return envObject.setLastError(envObject.tryCatch.hasCaught() ? 10 /* napi_status.napi_pending_exception */ : 1 /* napi_status.napi_invalid_arg */); + } + var value = emnapiCtx.handleStore.get(object); + if (!(value.isObject() || value.isFunction())) { + return envObject.setLastError(envObject.tryCatch.hasCaught() ? 10 /* napi_status.napi_pending_exception */ : 2 /* napi_status.napi_object_expected */); + } + if (!type_tag) { + return envObject.setLastError(envObject.tryCatch.hasCaught() ? 10 /* napi_status.napi_pending_exception */ : 1 /* napi_status.napi_invalid_arg */); + } + if (!result) { + return envObject.setLastError(envObject.tryCatch.hasCaught() ? 10 /* napi_status.napi_pending_exception */ : 1 /* napi_status.napi_invalid_arg */); + } + var binding = envObject.getObjectBinding(value.value); + if (binding.tag !== null) { + type_tag >>>= 0; + var tag = binding.tag; + var typeTag = new Uint32Array(wasmMemory.buffer, type_tag, 4); + ret = (tag[0] === typeTag[0] && + tag[1] === typeTag[1] && + tag[2] === typeTag[2] && + tag[3] === typeTag[3]); + } + else { + ret = false; + } + result >>>= 0; + var HEAP_DATA_VIEW = new DataView(wasmMemory.buffer), GET_HEAP_DATA_VIEW = function () { return HEAP_DATA_VIEW.buffer === wasmMemory.buffer ? HEAP_DATA_VIEW : (HEAP_DATA_VIEW = new DataView(wasmMemory.buffer)); }; + GET_HEAP_DATA_VIEW().setInt8(result, ret ? 1 : 0, true); + return envObject.getReturnStatus(); + } + catch (err) { + envObject.tryCatch.setError(err); + return envObject.setLastError(10 /* napi_status.napi_pending_exception */); + } + } + /** + * @__sig ipppppp + */ + function napi_add_finalizer(env, js_object, finalize_data, finalize_cb, finalize_hint, result) { + if (!env) + return 1 /* napi_status.napi_invalid_arg */; + // @ts-expect-error + var envObject = emnapiCtx.envStore.get(env); + envObject.checkGCAccess(); + if (!emnapiCtx.feature.supportFinalizer) { + return envObject.setLastError(9 /* napi_status.napi_generic_failure */); + } + if (!js_object) + return envObject.setLastError(1 /* napi_status.napi_invalid_arg */); + if (!finalize_cb) + return envObject.setLastError(1 /* napi_status.napi_invalid_arg */); + var handleResult = emnapiGetHandle(js_object); + if (handleResult.status !== 0 /* napi_status.napi_ok */) { + return envObject.setLastError(handleResult.status); + } + var handle = handleResult.handle; + var ownership = !result ? 0 /* ReferenceOwnership.kRuntime */ : 1 /* ReferenceOwnership.kUserland */; + finalize_data >>>= 0; + finalize_cb >>>= 0; + finalize_hint >>>= 0; + var reference = emnapiCtx.createReferenceWithFinalizer(envObject, handle.id, 0, ownership, finalize_cb, finalize_data, finalize_hint); + if (result) { + result >>>= 0; + // eslint-disable-next-line @typescript-eslint/no-unused-vars + var referenceId = reference.id; + var HEAP_DATA_VIEW = new DataView(wasmMemory.buffer), GET_HEAP_DATA_VIEW = function () { return HEAP_DATA_VIEW.buffer === wasmMemory.buffer ? HEAP_DATA_VIEW : (HEAP_DATA_VIEW = new DataView(wasmMemory.buffer)); }; + GET_HEAP_DATA_VIEW().setUint32(result, referenceId, true); + } + return envObject.clearLastError(); + } + /** + * @__sig ipppp + */ + function node_api_post_finalizer(env, finalize_cb, finalize_data, finalize_hint) { + if (!env) + return 1 /* napi_status.napi_invalid_arg */; + var envObject = emnapiCtx.envStore.get(env); + envObject.enqueueFinalizer(emnapiCtx.createTrackedFinalizer(envObject, finalize_cb, finalize_data, finalize_hint)); + return envObject.clearLastError(); + } + var wrapMod = /*#__PURE__*/ Object.freeze({ + __proto__: null, + napi_add_finalizer: napi_add_finalizer, + napi_check_object_type_tag: napi_check_object_type_tag, + napi_define_class: napi_define_class, + napi_remove_wrap: napi_remove_wrap, + napi_type_tag_object: napi_type_tag_object, + napi_unwrap: napi_unwrap, + napi_wrap: napi_wrap, + node_api_post_finalizer: node_api_post_finalizer + }); + /** + * @__sig ipippppp + */ + function emnapi_create_memory_view(env, typedarray_type, external_data, byte_length, finalize_cb, finalize_hint, result) { + // eslint-disable-next-line @typescript-eslint/no-unused-vars + var value; + if (!env) + return 1 /* napi_status.napi_invalid_arg */; + // @ts-expect-error + var envObject = emnapiCtx.envStore.get(env); + envObject.checkGCAccess(); + if (!envObject.tryCatch.isEmpty()) + return envObject.setLastError(10 /* napi_status.napi_pending_exception */); + if (!envObject.canCallIntoJs()) + return envObject.setLastError(envObject.moduleApiVersion >= 10 ? 23 /* napi_status.napi_cannot_run_js */ : 10 /* napi_status.napi_pending_exception */); + envObject.clearLastError(); + try { + if (!result) + return envObject.setLastError(1 /* napi_status.napi_invalid_arg */); + byte_length >>>= 0; + external_data >>>= 0; + result >>>= 0; + byte_length = byte_length >>> 0; + if (!external_data) { + byte_length = 0; + } + if (byte_length > 2147483647) { + throw new RangeError('Cannot create a memory view larger than 2147483647 bytes'); + } + if ((external_data + byte_length) > wasmMemory.buffer.byteLength) { + throw new RangeError('Memory out of range'); + } + if (!emnapiCtx.feature.supportFinalizer && finalize_cb) { + throw emnapiCtx.createNotSupportWeakRefError('emnapi_create_memory_view', 'Parameter "finalize_cb" must be 0(NULL)'); + } + var viewDescriptor = void 0; + switch (typedarray_type) { + case 0 /* emnapi_memory_view_type.emnapi_int8_array */: + viewDescriptor = { Ctor: Int8Array, address: external_data, length: byte_length, ownership: 1 /* ReferenceOwnership.kUserland */, runtimeAllocated: 0 }; + break; + case 1 /* emnapi_memory_view_type.emnapi_uint8_array */: + viewDescriptor = { Ctor: Uint8Array, address: external_data, length: byte_length, ownership: 1 /* ReferenceOwnership.kUserland */, runtimeAllocated: 0 }; + break; + case 2 /* emnapi_memory_view_type.emnapi_uint8_clamped_array */: + viewDescriptor = { Ctor: Uint8ClampedArray, address: external_data, length: byte_length, ownership: 1 /* ReferenceOwnership.kUserland */, runtimeAllocated: 0 }; + break; + case 3 /* emnapi_memory_view_type.emnapi_int16_array */: + viewDescriptor = { Ctor: Int16Array, address: external_data, length: byte_length >> 1, ownership: 1 /* ReferenceOwnership.kUserland */, runtimeAllocated: 0 }; + break; + case 4 /* emnapi_memory_view_type.emnapi_uint16_array */: + viewDescriptor = { Ctor: Uint16Array, address: external_data, length: byte_length >> 1, ownership: 1 /* ReferenceOwnership.kUserland */, runtimeAllocated: 0 }; + break; + case 5 /* emnapi_memory_view_type.emnapi_int32_array */: + viewDescriptor = { Ctor: Int32Array, address: external_data, length: byte_length >> 2, ownership: 1 /* ReferenceOwnership.kUserland */, runtimeAllocated: 0 }; + break; + case 6 /* emnapi_memory_view_type.emnapi_uint32_array */: + viewDescriptor = { Ctor: Uint32Array, address: external_data, length: byte_length >> 2, ownership: 1 /* ReferenceOwnership.kUserland */, runtimeAllocated: 0 }; + break; + case 7 /* emnapi_memory_view_type.emnapi_float32_array */: + viewDescriptor = { Ctor: Float32Array, address: external_data, length: byte_length >> 2, ownership: 1 /* ReferenceOwnership.kUserland */, runtimeAllocated: 0 }; + break; + case 8 /* emnapi_memory_view_type.emnapi_float64_array */: + viewDescriptor = { Ctor: Float64Array, address: external_data, length: byte_length >> 3, ownership: 1 /* ReferenceOwnership.kUserland */, runtimeAllocated: 0 }; + break; + case 9 /* emnapi_memory_view_type.emnapi_bigint64_array */: + viewDescriptor = { Ctor: BigInt64Array, address: external_data, length: byte_length >> 3, ownership: 1 /* ReferenceOwnership.kUserland */, runtimeAllocated: 0 }; + break; + case 10 /* emnapi_memory_view_type.emnapi_biguint64_array */: + viewDescriptor = { Ctor: BigUint64Array, address: external_data, length: byte_length >> 3, ownership: 1 /* ReferenceOwnership.kUserland */, runtimeAllocated: 0 }; + break; + case -1 /* emnapi_memory_view_type.emnapi_data_view */: + viewDescriptor = { Ctor: DataView, address: external_data, length: byte_length, ownership: 1 /* ReferenceOwnership.kUserland */, runtimeAllocated: 0 }; + break; + case 11 /* emnapi_memory_view_type.emnapi_float16_array */: + if (typeof Float16Array !== 'function') { + return envObject.setLastError(1 /* napi_status.napi_invalid_arg */); + } + viewDescriptor = { Ctor: Float16Array, address: external_data, length: byte_length >> 1, ownership: 1 /* ReferenceOwnership.kUserland */, runtimeAllocated: 0 }; + break; + case -2 /* emnapi_memory_view_type.emnapi_buffer */: { + if (!emnapiCtx.feature.Buffer) { + throw emnapiCtx.createNotSupportBufferError('emnapi_create_memory_view', ''); + } + viewDescriptor = { Ctor: emnapiCtx.feature.Buffer, address: external_data, length: byte_length, ownership: 1 /* ReferenceOwnership.kUserland */, runtimeAllocated: 0 }; + break; + } + default: return envObject.setLastError(1 /* napi_status.napi_invalid_arg */); + } + var Ctor = viewDescriptor.Ctor; + var typedArray = typedarray_type === -2 /* emnapi_memory_view_type.emnapi_buffer */ + // capture Buffer.from at creation so a later refreshed view uses it + ? emnapiExternalMemory.getBufferFrom()(wasmMemory.buffer, viewDescriptor.address, viewDescriptor.length) + : new Ctor(wasmMemory.buffer, viewDescriptor.address, viewDescriptor.length); + var handle = emnapiCtx.addToCurrentScope(typedArray); + emnapiExternalMemory.wasmMemoryViewTable.set(typedArray, viewDescriptor); + if (finalize_cb) { + var status_1 = napi_add_finalizer(env, handle.id, external_data, finalize_cb, finalize_hint, /* NULL */ 0); + if (status_1 === 10 /* napi_status.napi_pending_exception */) { + var err = envObject.tryCatch.extractException(); + envObject.clearLastError(); + throw err; + } + else if (status_1 !== 0 /* napi_status.napi_ok */) { + return envObject.setLastError(status_1); + } + } + value = handle.id; + var HEAP_DATA_VIEW = new DataView(wasmMemory.buffer), GET_HEAP_DATA_VIEW = function () { return HEAP_DATA_VIEW.buffer === wasmMemory.buffer ? HEAP_DATA_VIEW : (HEAP_DATA_VIEW = new DataView(wasmMemory.buffer)); }; + GET_HEAP_DATA_VIEW().setUint32(result, value, true); + return envObject.getReturnStatus(); + } + catch (err) { + envObject.tryCatch.setError(err); + return envObject.setLastError(10 /* napi_status.napi_pending_exception */); + } + } + /** + * @__sig i + */ + function emnapi_is_support_weakref() { + return emnapiCtx.feature.supportFinalizer ? 1 : 0; + } + /** + * @__sig i + */ + function emnapi_is_support_bigint() { + return emnapiCtx.feature.supportBigInt ? 1 : 0; + } + /** + * @__sig i + */ + function emnapi_is_node_binding_available() { + return emnapiNodeBinding ? 1 : 0; + } + /** + * Synchronize data between the wasm memory and an ArrayBuffer / view. + * + * Note: when a non-shared wasm memory has grown, a view over the detached + * old buffer is re-created over the current buffer through the intrinsic + * base-class constructor, so for view inputs the returned view may be a + * base-class instance (e.g. `Uint8Array` or `DataView`) instead of the + * subclass that was passed in. + */ + function $emnapiSyncMemory(js_to_wasm, arrayBufferOrView, offset, len) { + offset = offset !== null && offset !== void 0 ? offset : 0; + offset = offset >>> 0; + var view; + if (arrayBufferOrView instanceof ArrayBuffer || emnapiExternalMemory.isSharedArrayBuffer(arrayBufferOrView)) { + var pointer = emnapiExternalMemory.getArrayBufferPointer(arrayBufferOrView, false).address; + if (!pointer) + throw new Error('Unknown ArrayBuffer address'); + if (typeof len !== 'number' || len === -1 || len === 4294967295) { + len = arrayBufferOrView.byteLength - offset; + } + len = len >>> 0; + if (len === 0) + return arrayBufferOrView; + view = new Uint8Array(arrayBufferOrView, offset, len); + var wasmMemoryU8 = new Uint8Array(wasmMemory.buffer); + if (!js_to_wasm) { + view.set(wasmMemoryU8.subarray(pointer, pointer + len)); + } + else { + wasmMemoryU8.set(view, pointer); + } + return arrayBufferOrView; + } + if (ArrayBuffer.isView(arrayBufferOrView)) { + var viewPointerInfo = emnapiExternalMemory.getViewPointer(arrayBufferOrView, false); + var latestView = viewPointerInfo.view; + var pointer = viewPointerInfo.address; + if (!pointer) + throw new Error('Unknown ArrayBuffer address'); + if (typeof len !== 'number' || len === -1 || len === 4294967295) { + len = latestView.byteLength - offset; + } + len = len >>> 0; + if (len === 0) + return latestView; + view = new Uint8Array(latestView.buffer, latestView.byteOffset + offset, len); + var wasmMemoryU8 = new Uint8Array(wasmMemory.buffer); + if (!js_to_wasm) { + view.set(wasmMemoryU8.subarray(pointer, pointer + len)); + } + else { + wasmMemoryU8.set(view, pointer); + } + return latestView; + } + throw new TypeError('emnapiSyncMemory expect ArrayBuffer or ArrayBufferView as first parameter'); + } + /** + * @__sig ipippp + */ + function emnapi_sync_memory(env, js_to_wasm, arraybuffer_or_view, offset, len) { + // eslint-disable-next-line @typescript-eslint/no-unused-vars + var v; + if (!env) + return 1 /* napi_status.napi_invalid_arg */; + // @ts-expect-error + var envObject = emnapiCtx.envStore.get(env); + envObject.checkGCAccess(); + if (!envObject.tryCatch.isEmpty()) + return envObject.setLastError(10 /* napi_status.napi_pending_exception */); + if (!envObject.canCallIntoJs()) + return envObject.setLastError(envObject.moduleApiVersion >= 10 ? 23 /* napi_status.napi_cannot_run_js */ : 10 /* napi_status.napi_pending_exception */); + envObject.clearLastError(); + try { + if (!arraybuffer_or_view) + return envObject.setLastError(1 /* napi_status.napi_invalid_arg */); + arraybuffer_or_view >>>= 0; + offset >>>= 0; + len >>>= 0; + var HEAP_DATA_VIEW = new DataView(wasmMemory.buffer), GET_HEAP_DATA_VIEW = function () { return HEAP_DATA_VIEW.buffer === wasmMemory.buffer ? HEAP_DATA_VIEW : (HEAP_DATA_VIEW = new DataView(wasmMemory.buffer)); }; + var handleId = GET_HEAP_DATA_VIEW().getUint32(arraybuffer_or_view, true); + var handle = envObject.ctx.handleStore.get(handleId); + if (!handle.isArrayBuffer() && !handle.isTypedArray() && !handle.isDataView() && !emnapiExternalMemory.isSharedArrayBuffer(handle.value)) { + return envObject.setLastError(1 /* napi_status.napi_invalid_arg */); + } + var ret = $emnapiSyncMemory(Boolean(js_to_wasm), handle.value, offset, len); + if (handle.value !== ret) { + arraybuffer_or_view >>>= 0; + v = envObject.ensureHandleId(ret); + GET_HEAP_DATA_VIEW().setUint32(arraybuffer_or_view, v, true); + } + return envObject.getReturnStatus(); + } + catch (err) { + envObject.tryCatch.setError(err); + return envObject.setLastError(10 /* napi_status.napi_pending_exception */); + } + } + function $emnapiGetMemoryAddress(arrayBufferOrView) { + var isArrayBuffer = arrayBufferOrView instanceof ArrayBuffer; + var isDataView = arrayBufferOrView instanceof DataView; + var isTypedArray = ArrayBuffer.isView(arrayBufferOrView) && !isDataView; + if (!isArrayBuffer && !isTypedArray && !isDataView && !emnapiExternalMemory.isSharedArrayBuffer(arrayBufferOrView)) { + throw new TypeError('emnapiGetMemoryAddress expect ArrayBuffer or ArrayBufferView as first parameter'); + } + var info; + if (isArrayBuffer) { + info = emnapiExternalMemory.getArrayBufferPointer(arrayBufferOrView, false); + } + else { + info = emnapiExternalMemory.getViewPointer(arrayBufferOrView, false); + } + return { + address: info.address, + ownership: info.ownership, + runtimeAllocated: info.runtimeAllocated + }; + } + /** + * @__sig ipppp + */ + function emnapi_get_memory_address(env, arraybuffer_or_view, address, ownership, runtime_allocated) { + // eslint-disable-next-line @typescript-eslint/no-unused-vars + var p, runtimeAllocated, ownershipOut; + var info; + if (!env) + return 1 /* napi_status.napi_invalid_arg */; + // @ts-expect-error + var envObject = emnapiCtx.envStore.get(env); + envObject.checkGCAccess(); + if (!envObject.tryCatch.isEmpty()) + return envObject.setLastError(10 /* napi_status.napi_pending_exception */); + if (!envObject.canCallIntoJs()) + return envObject.setLastError(envObject.moduleApiVersion >= 10 ? 23 /* napi_status.napi_cannot_run_js */ : 10 /* napi_status.napi_pending_exception */); + envObject.clearLastError(); + try { + if (!arraybuffer_or_view) + return envObject.setLastError(1 /* napi_status.napi_invalid_arg */); + if (!address && !ownership && !runtime_allocated) { + return envObject.setLastError(1 /* napi_status.napi_invalid_arg */); + } + var handle = envObject.ctx.handleStore.get(arraybuffer_or_view); + info = $emnapiGetMemoryAddress(handle.value); + p = info.address; + var HEAP_DATA_VIEW = new DataView(wasmMemory.buffer), GET_HEAP_DATA_VIEW = function () { return HEAP_DATA_VIEW.buffer === wasmMemory.buffer ? HEAP_DATA_VIEW : (HEAP_DATA_VIEW = new DataView(wasmMemory.buffer)); }; + if (address) { + address >>>= 0; + GET_HEAP_DATA_VIEW().setUint32(address, p, true); + } + if (ownership) { + ownership >>>= 0; + ownershipOut = info.ownership; + GET_HEAP_DATA_VIEW().setInt32(ownership, ownershipOut, true); + } + if (runtime_allocated) { + runtime_allocated >>>= 0; + runtimeAllocated = info.runtimeAllocated; + GET_HEAP_DATA_VIEW().setInt8(runtime_allocated, runtimeAllocated, true); + } + return envObject.getReturnStatus(); + } + catch (err) { + envObject.tryCatch.setError(err); + return envObject.setLastError(10 /* napi_status.napi_pending_exception */); + } + } + /** + * @__sig ipp + */ + function emnapi_get_runtime_version(env, version) { + if (!env) + return 1 /* napi_status.napi_invalid_arg */; + var envObject = emnapiCtx.envStore.get(env); + if (!version) + return envObject.setLastError(1 /* napi_status.napi_invalid_arg */); + var runtimeVersion; + try { + runtimeVersion = emnapiCtx.getRuntimeVersions().version; + } + catch (_) { + return envObject.setLastError(9 /* napi_status.napi_generic_failure */); + } + // eslint-disable-next-line @typescript-eslint/no-unused-vars + var versions = runtimeVersion.split('.') + .map(function (n) { return Number(n); }); + version >>>= 0; + var HEAP_DATA_VIEW = new DataView(wasmMemory.buffer), GET_HEAP_DATA_VIEW = function () { return HEAP_DATA_VIEW.buffer === wasmMemory.buffer ? HEAP_DATA_VIEW : (HEAP_DATA_VIEW = new DataView(wasmMemory.buffer)); }; + GET_HEAP_DATA_VIEW().setUint32(version, versions[0], true); + GET_HEAP_DATA_VIEW().setUint32(version + 4, versions[1], true); + GET_HEAP_DATA_VIEW().setUint32(version + 8, versions[2], true); + return envObject.clearLastError(); + } + /** + * Get the handle for an external SharedArrayBuffer. + * Must be called on the emnapi main thread. + * @__sig ippp + */ + function emnapi_get_external_sharedarraybuffer_handle(env, sharedarraybuffer, handle) { + if (!env) + return 1 /* napi_status.napi_invalid_arg */; + // @ts-expect-error + var envObject = emnapiCtx.envStore.get(env); + envObject.checkGCAccess(); + if (!envObject.tryCatch.isEmpty()) + return envObject.setLastError(10 /* napi_status.napi_pending_exception */); + if (!envObject.canCallIntoJs()) + return envObject.setLastError(envObject.moduleApiVersion >= 10 ? 23 /* napi_status.napi_cannot_run_js */ : 10 /* napi_status.napi_pending_exception */); + envObject.clearLastError(); + try { + if (!sharedarraybuffer) + return envObject.setLastError(1 /* napi_status.napi_invalid_arg */); + if (!handle) + return envObject.setLastError(1 /* napi_status.napi_invalid_arg */); + handle >>>= 0; + var jsValue = emnapiCtx.handleStore.get(sharedarraybuffer).value; + if (!emnapiExternalMemory.isSharedArrayBuffer(jsValue)) { + return envObject.setLastError(1 /* napi_status.napi_invalid_arg */); + } + var metaPtr = emnapiExternalSAB.handleTable.get(jsValue); + if (metaPtr === undefined) { + return envObject.setLastError(1 /* napi_status.napi_invalid_arg */); + } + var HEAP_DATA_VIEW = new DataView(wasmMemory.buffer), GET_HEAP_DATA_VIEW = function () { return HEAP_DATA_VIEW.buffer === wasmMemory.buffer ? HEAP_DATA_VIEW : (HEAP_DATA_VIEW = new DataView(wasmMemory.buffer)); }; + GET_HEAP_DATA_VIEW().setUint32(handle, metaPtr, true); + return envObject.getReturnStatus(); + } + catch (err) { + envObject.tryCatch.setError(err); + return envObject.setLastError(10 /* napi_status.napi_pending_exception */); + } + } + /** + * Acquire a reference to an external SharedArrayBuffer. + * Can be called on any thread. + * @__sig vp + */ + function emnapi_acquire_external_sharedarraybuffer(handle) { + handle >>>= 0; + Atomics.add(new Int32Array(wasmMemory.buffer, handle, 1), 0, 1); + } + /** + * Release a reference to an external SharedArrayBuffer. + * Can be called on any thread. + * @__sig vp + */ + function emnapi_release_external_sharedarraybuffer(handle) { + handle >>>= 0; + emnapiExternalSAB.release(handle); + } + /** + * Acquire a reference to an external SharedArrayBuffer on the current thread. + * Can be called on any thread. Increments refcount and registers in + * the current thread's FinalizationRegistry. + * Exposed as Module.emnapiAcquireExternalSharedArrayBuffer (emscripten) or + * napiModule.emnapi.acquireExternalSharedArrayBuffer (core). + */ + function $emnapiAcquireExternalSharedArrayBuffer(handle, sab) { + if (sab != null && !emnapiExternalMemory.isSharedArrayBuffer(sab)) { + throw new TypeError('Expected a SharedArrayBuffer'); + } + if (!emnapiExternalSAB.registry) { + throw new Error('FinalizationRegistry is not supported in this environment'); + } + handle >>>= 0; + var meta = emnapiExternalSAB.readMeta(handle); + // eslint-disable-next-line prefer-const + var external_data = meta.external_data; + external_data >>>= 0; + if (sab == null) { + sab = new SharedArrayBuffer(meta.byte_length); + new Uint8Array(sab).set(new Uint8Array(wasmMemory.buffer, external_data, meta.byte_length)); + } + else { + if (emnapiExternalSAB.handleTable.has(sab)) { + return sab; + } + } + // Increment refcount atomically + Atomics.add(new Int32Array(wasmMemory.buffer, handle, 1), 0, 1); + // Register in emnapiExternalMemory.table for emnapi_sync_memory support + if (!emnapiExternalMemory.table.has(sab)) { + if (external_data) { + emnapiExternalMemory.table.set(sab, { + address: external_data, + ownership: 1 /* ReferenceOwnership.kUserland */, + runtimeAllocated: 0 + }); + } + } + // Register in handleTable and FinalizationRegistry for this thread + emnapiExternalSAB.handleTable.set(sab, handle); + emnapiExternalSAB.registry.register(sab, handle); + return sab; + } + var emnapiMod = /*#__PURE__*/ Object.freeze({ + __proto__: null, + $emnapiAcquireExternalSharedArrayBuffer: $emnapiAcquireExternalSharedArrayBuffer, + $emnapiGetMemoryAddress: $emnapiGetMemoryAddress, + $emnapiSyncMemory: $emnapiSyncMemory, + emnapi_acquire_external_sharedarraybuffer: emnapi_acquire_external_sharedarraybuffer, + emnapi_create_memory_view: emnapi_create_memory_view, + emnapi_get_external_sharedarraybuffer_handle: emnapi_get_external_sharedarraybuffer_handle, + emnapi_get_memory_address: emnapi_get_memory_address, + emnapi_get_runtime_version: emnapi_get_runtime_version, + emnapi_is_node_binding_available: emnapi_is_node_binding_available, + emnapi_is_support_bigint: emnapi_is_support_bigint, + emnapi_is_support_weakref: emnapi_is_support_weakref, + emnapi_release_external_sharedarraybuffer: emnapi_release_external_sharedarraybuffer, + emnapi_sync_memory: emnapi_sync_memory + }); + /** + * @__sig ipp + */ + function napi_create_array(env, result) { + if (!env) + return 1 /* napi_status.napi_invalid_arg */; + // @ts-expect-error + var envObject = emnapiCtx.envStore.get(env); + envObject.checkGCAccess(); + if (!result) + return envObject.setLastError(1 /* napi_status.napi_invalid_arg */); + result >>>= 0; + // eslint-disable-next-line @typescript-eslint/no-unused-vars + var value = emnapiCtx.addToCurrentScope([]).id; + var HEAP_DATA_VIEW = new DataView(wasmMemory.buffer), GET_HEAP_DATA_VIEW = function () { return HEAP_DATA_VIEW.buffer === wasmMemory.buffer ? HEAP_DATA_VIEW : (HEAP_DATA_VIEW = new DataView(wasmMemory.buffer)); }; + GET_HEAP_DATA_VIEW().setUint32(result, value, true); + return envObject.clearLastError(); + } + /** + * @__sig ippp + */ + function napi_create_array_with_length(env, length, result) { + if (!env) + return 1 /* napi_status.napi_invalid_arg */; + // @ts-expect-error + var envObject = emnapiCtx.envStore.get(env); + envObject.checkGCAccess(); + if (!result) + return envObject.setLastError(1 /* napi_status.napi_invalid_arg */); + length >>>= 0; + result >>>= 0; + length = length >>> 0; + // eslint-disable-next-line @typescript-eslint/no-unused-vars + var value = emnapiCtx.addToCurrentScope(new Array(length)).id; + var HEAP_DATA_VIEW = new DataView(wasmMemory.buffer), GET_HEAP_DATA_VIEW = function () { return HEAP_DATA_VIEW.buffer === wasmMemory.buffer ? HEAP_DATA_VIEW : (HEAP_DATA_VIEW = new DataView(wasmMemory.buffer)); }; + GET_HEAP_DATA_VIEW().setUint32(result, value, true); + return envObject.clearLastError(); + } + function emnapiCreateArrayBuffer(byte_length, data, shared) { + byte_length >>>= 0; + byte_length = byte_length >>> 0; + var arrayBuffer = shared ? new SharedArrayBuffer(byte_length) : new ArrayBuffer(byte_length); + if (data) { + data >>>= 0; + // eslint-disable-next-line @typescript-eslint/no-unused-vars + var p = emnapiExternalMemory.getArrayBufferPointer(arrayBuffer, true).address; + var HEAP_DATA_VIEW = new DataView(wasmMemory.buffer), GET_HEAP_DATA_VIEW = function () { return HEAP_DATA_VIEW.buffer === wasmMemory.buffer ? HEAP_DATA_VIEW : (HEAP_DATA_VIEW = new DataView(wasmMemory.buffer)); }; + GET_HEAP_DATA_VIEW().setUint32(data, p, true); + } + return arrayBuffer; + } + /** + * @__sig ipppp + */ + function napi_create_arraybuffer(env, byte_length, data, result) { + // eslint-disable-next-line @typescript-eslint/no-unused-vars + var value; + if (!env) + return 1 /* napi_status.napi_invalid_arg */; + // @ts-expect-error + var envObject = emnapiCtx.envStore.get(env); + envObject.checkGCAccess(); + if (!envObject.tryCatch.isEmpty()) + return envObject.setLastError(10 /* napi_status.napi_pending_exception */); + if (!envObject.canCallIntoJs()) + return envObject.setLastError(envObject.moduleApiVersion >= 10 ? 23 /* napi_status.napi_cannot_run_js */ : 10 /* napi_status.napi_pending_exception */); + envObject.clearLastError(); + try { + if (!result) + return envObject.setLastError(1 /* napi_status.napi_invalid_arg */); + result >>>= 0; + var arrayBuffer = emnapiCreateArrayBuffer(byte_length, data, false); + value = emnapiCtx.addToCurrentScope(arrayBuffer).id; + var HEAP_DATA_VIEW = new DataView(wasmMemory.buffer), GET_HEAP_DATA_VIEW = function () { return HEAP_DATA_VIEW.buffer === wasmMemory.buffer ? HEAP_DATA_VIEW : (HEAP_DATA_VIEW = new DataView(wasmMemory.buffer)); }; + GET_HEAP_DATA_VIEW().setUint32(result, value, true); + return envObject.getReturnStatus(); + } + catch (err) { + envObject.tryCatch.setError(err); + return envObject.setLastError(10 /* napi_status.napi_pending_exception */); + } + } + /** + * @__sig ipppp + */ + function node_api_create_sharedarraybuffer(env, byte_length, data, result) { + // eslint-disable-next-line @typescript-eslint/no-unused-vars + var value; + if (!env) + return 1 /* napi_status.napi_invalid_arg */; + // @ts-expect-error + var envObject = emnapiCtx.envStore.get(env); + envObject.checkGCAccess(); + if (!envObject.tryCatch.isEmpty()) + return envObject.setLastError(10 /* napi_status.napi_pending_exception */); + if (!envObject.canCallIntoJs()) + return envObject.setLastError(envObject.moduleApiVersion >= 10 ? 23 /* napi_status.napi_cannot_run_js */ : 10 /* napi_status.napi_pending_exception */); + envObject.clearLastError(); + try { + if (!result) + return envObject.setLastError(1 /* napi_status.napi_invalid_arg */); + result >>>= 0; + var arrayBuffer = emnapiCreateArrayBuffer(byte_length, data, true); + value = emnapiCtx.addToCurrentScope(arrayBuffer).id; + var HEAP_DATA_VIEW = new DataView(wasmMemory.buffer), GET_HEAP_DATA_VIEW = function () { return HEAP_DATA_VIEW.buffer === wasmMemory.buffer ? HEAP_DATA_VIEW : (HEAP_DATA_VIEW = new DataView(wasmMemory.buffer)); }; + GET_HEAP_DATA_VIEW().setUint32(result, value, true); + return envObject.getReturnStatus(); + } + catch (err) { + envObject.tryCatch.setError(err); + return envObject.setLastError(10 /* napi_status.napi_pending_exception */); + } + } + /** + * @__sig ipdp + */ + function napi_create_date(env, time, result) { + // eslint-disable-next-line @typescript-eslint/no-unused-vars + var value; + if (!env) + return 1 /* napi_status.napi_invalid_arg */; + // @ts-expect-error + var envObject = emnapiCtx.envStore.get(env); + envObject.checkGCAccess(); + if (!envObject.tryCatch.isEmpty()) + return envObject.setLastError(10 /* napi_status.napi_pending_exception */); + if (!envObject.canCallIntoJs()) + return envObject.setLastError(envObject.moduleApiVersion >= 10 ? 23 /* napi_status.napi_cannot_run_js */ : 10 /* napi_status.napi_pending_exception */); + envObject.clearLastError(); + try { + if (!result) + return envObject.setLastError(1 /* napi_status.napi_invalid_arg */); + result >>>= 0; + // eslint-disable-next-line @typescript-eslint/no-unused-vars + value = emnapiCtx.addToCurrentScope(new Date(time)).id; + var HEAP_DATA_VIEW = new DataView(wasmMemory.buffer), GET_HEAP_DATA_VIEW = function () { return HEAP_DATA_VIEW.buffer === wasmMemory.buffer ? HEAP_DATA_VIEW : (HEAP_DATA_VIEW = new DataView(wasmMemory.buffer)); }; + GET_HEAP_DATA_VIEW().setUint32(result, value, true); + return envObject.getReturnStatus(); + } + catch (err) { + envObject.tryCatch.setError(err); + return envObject.setLastError(10 /* napi_status.napi_pending_exception */); + } + } + /** + * @__sig ippppp + */ + function napi_create_external(env, data, finalize_cb, finalize_hint, result) { + // eslint-disable-next-line @typescript-eslint/no-unused-vars + var value; + if (!env) + return 1 /* napi_status.napi_invalid_arg */; + // @ts-expect-error + var envObject = emnapiCtx.envStore.get(env); + envObject.checkGCAccess(); + if (!envObject.tryCatch.isEmpty()) + return envObject.setLastError(10 /* napi_status.napi_pending_exception */); + if (!envObject.canCallIntoJs()) + return envObject.setLastError(envObject.moduleApiVersion >= 10 ? 23 /* napi_status.napi_cannot_run_js */ : 10 /* napi_status.napi_pending_exception */); + envObject.clearLastError(); + try { + if (!result) + return envObject.setLastError(1 /* napi_status.napi_invalid_arg */); + if (!emnapiCtx.feature.supportFinalizer && finalize_cb) { + throw emnapiCtx.createNotSupportWeakRefError('napi_create_external', 'Parameter "finalize_cb" must be 0(NULL)'); + } + var externalHandle = emnapiCtx.getCurrentScope().addExternal(data); + if (finalize_cb) { + emnapiCtx.createReferenceWithFinalizer(envObject, externalHandle.id, 0, 0 /* ReferenceOwnership.kRuntime */, finalize_cb, data, finalize_hint); + } + result >>>= 0; + value = externalHandle.id; + var HEAP_DATA_VIEW = new DataView(wasmMemory.buffer), GET_HEAP_DATA_VIEW = function () { return HEAP_DATA_VIEW.buffer === wasmMemory.buffer ? HEAP_DATA_VIEW : (HEAP_DATA_VIEW = new DataView(wasmMemory.buffer)); }; + GET_HEAP_DATA_VIEW().setUint32(result, value, true); + return envObject.clearLastError(); + } + catch (err) { + envObject.tryCatch.setError(err); + return envObject.setLastError(10 /* napi_status.napi_pending_exception */); + } + } + /** + * @__sig ipppppp + */ + function napi_create_external_arraybuffer(env, external_data, byte_length, finalize_cb, finalize_hint, result) { + // eslint-disable-next-line @typescript-eslint/no-unused-vars + var value; + if (!env) + return 1 /* napi_status.napi_invalid_arg */; + // @ts-expect-error + var envObject = emnapiCtx.envStore.get(env); + envObject.checkGCAccess(); + if (!envObject.tryCatch.isEmpty()) + return envObject.setLastError(10 /* napi_status.napi_pending_exception */); + if (!envObject.canCallIntoJs()) + return envObject.setLastError(envObject.moduleApiVersion >= 10 ? 23 /* napi_status.napi_cannot_run_js */ : 10 /* napi_status.napi_pending_exception */); + envObject.clearLastError(); + try { + if (!result) + return envObject.setLastError(1 /* napi_status.napi_invalid_arg */); + byte_length >>>= 0; + external_data >>>= 0; + result >>>= 0; + byte_length = byte_length >>> 0; + if (!external_data) { + byte_length = 0; + } + if ((external_data + byte_length) > wasmMemory.buffer.byteLength) { + throw new RangeError('Memory out of range'); + } + if (!emnapiCtx.feature.supportFinalizer && finalize_cb) { + throw emnapiCtx.createNotSupportWeakRefError('napi_create_external_arraybuffer', 'Parameter "finalize_cb" must be 0(NULL)'); + } + var arrayBuffer = new ArrayBuffer(byte_length); + if (byte_length === 0) { + try { + var MessageChannel_1 = emnapiCtx.feature.MessageChannel; + var messageChannel = new MessageChannel_1(); + messageChannel.port1.postMessage(arrayBuffer, [arrayBuffer]); + } + catch (_) { } + } + else { + var u8arr = new Uint8Array(arrayBuffer); + u8arr.set(new Uint8Array(wasmMemory.buffer).subarray(external_data, external_data + byte_length)); + emnapiExternalMemory.table.set(arrayBuffer, { + address: external_data, + ownership: 1 /* ReferenceOwnership.kUserland */, + runtimeAllocated: 0 + }); + } + var handle = emnapiCtx.addToCurrentScope(arrayBuffer); + if (finalize_cb) { + var status_1 = napi_add_finalizer(env, handle.id, external_data, finalize_cb, finalize_hint, /* NULL */ 0); + if (status_1 === 10 /* napi_status.napi_pending_exception */) { + var err = envObject.tryCatch.extractException(); + envObject.clearLastError(); + throw err; + } + else if (status_1 !== 0 /* napi_status.napi_ok */) { + return envObject.setLastError(status_1); + } + } + value = handle.id; + var HEAP_DATA_VIEW = new DataView(wasmMemory.buffer), GET_HEAP_DATA_VIEW = function () { return HEAP_DATA_VIEW.buffer === wasmMemory.buffer ? HEAP_DATA_VIEW : (HEAP_DATA_VIEW = new DataView(wasmMemory.buffer)); }; + GET_HEAP_DATA_VIEW().setUint32(result, value, true); + return envObject.getReturnStatus(); + } + catch (err) { + envObject.tryCatch.setError(err); + return envObject.setLastError(10 /* napi_status.napi_pending_exception */); + } + } + /** + * @__sig ipppppp + */ + function node_api_create_external_sharedarraybuffer(env, external_data, byte_length, finalize_cb, finalize_hint, result) { + // eslint-disable-next-line @typescript-eslint/no-unused-vars + var value; + if (!env) + return 1 /* napi_status.napi_invalid_arg */; + // @ts-expect-error + var envObject = emnapiCtx.envStore.get(env); + envObject.checkGCAccess(); + if (!envObject.tryCatch.isEmpty()) + return envObject.setLastError(10 /* napi_status.napi_pending_exception */); + if (!envObject.canCallIntoJs()) + return envObject.setLastError(envObject.moduleApiVersion >= 10 ? 23 /* napi_status.napi_cannot_run_js */ : 10 /* napi_status.napi_pending_exception */); + envObject.clearLastError(); + try { + if (!result) + return envObject.setLastError(1 /* napi_status.napi_invalid_arg */); + byte_length >>>= 0; + external_data >>>= 0; + result >>>= 0; + byte_length = byte_length >>> 0; + if (!external_data) { + byte_length = 0; + } + if ((external_data + byte_length) > wasmMemory.buffer.byteLength) { + throw new RangeError('Memory out of range'); + } + if (!emnapiExternalSAB.registry && finalize_cb) { + throw emnapiCtx.createNotSupportWeakRefError('node_api_create_external_sharedarraybuffer', 'Parameter "finalize_cb" must be 0(NULL)'); + } + var sharedArrayBuffer = new SharedArrayBuffer(byte_length); + if (byte_length !== 0) { + var u8arr = new Uint8Array(sharedArrayBuffer); + u8arr.set(new Uint8Array(wasmMemory.buffer).subarray(external_data, external_data + byte_length)); + emnapiExternalMemory.table.set(sharedArrayBuffer, { + address: external_data, + ownership: 1 /* ReferenceOwnership.kUserland */, + runtimeAllocated: 0 + }); + } + value = emnapiCtx.addToCurrentScope(sharedArrayBuffer).id; + if (finalize_cb) { + finalize_cb >>>= 0; + finalize_hint >>>= 0; + var metaPtr = emnapiExternalSAB.allocMeta(external_data, byte_length, finalize_cb, external_data, finalize_hint); + emnapiExternalSAB.handleTable.set(sharedArrayBuffer, metaPtr); + emnapiExternalSAB.registry.register(sharedArrayBuffer, metaPtr); + } + var HEAP_DATA_VIEW = new DataView(wasmMemory.buffer), GET_HEAP_DATA_VIEW = function () { return HEAP_DATA_VIEW.buffer === wasmMemory.buffer ? HEAP_DATA_VIEW : (HEAP_DATA_VIEW = new DataView(wasmMemory.buffer)); }; + GET_HEAP_DATA_VIEW().setUint32(result, value, true); + return envObject.getReturnStatus(); + } + catch (err) { + envObject.tryCatch.setError(err); + return envObject.setLastError(10 /* napi_status.napi_pending_exception */); + } + } + /** + * @__sig ipp + */ + function napi_create_object(env, result) { + if (!env) + return 1 /* napi_status.napi_invalid_arg */; + // @ts-expect-error + var envObject = emnapiCtx.envStore.get(env); + envObject.checkGCAccess(); + if (!result) + return envObject.setLastError(1 /* napi_status.napi_invalid_arg */); + result >>>= 0; + // eslint-disable-next-line @typescript-eslint/no-unused-vars + var value = emnapiCtx.addToCurrentScope({}).id; + var HEAP_DATA_VIEW = new DataView(wasmMemory.buffer), GET_HEAP_DATA_VIEW = function () { return HEAP_DATA_VIEW.buffer === wasmMemory.buffer ? HEAP_DATA_VIEW : (HEAP_DATA_VIEW = new DataView(wasmMemory.buffer)); }; + GET_HEAP_DATA_VIEW().setUint32(result, value, true); + return envObject.clearLastError(); + } + /** + * @__sig ipppppp + */ + function node_api_create_object_with_properties(env, prototype_or_null, property_names, property_values, property_count, result) { + if (!env) + return 1 /* napi_status.napi_invalid_arg */; + // @ts-expect-error + var envObject = emnapiCtx.envStore.get(env); + envObject.checkGCAccess(); + if (!result) + return envObject.setLastError(1 /* napi_status.napi_invalid_arg */); + property_count >>>= 0; + property_count = property_count >>> 0; + if (property_count > 0) { + if (!property_names) + return envObject.setLastError(1 /* napi_status.napi_invalid_arg */); + if (!property_values) + return envObject.setLastError(1 /* napi_status.napi_invalid_arg */); + } + var v8_prototype_or_null = prototype_or_null + ? emnapiCtx.handleStore.get(prototype_or_null).value + : null; + var properties = {}; + property_names >>>= 0; + property_values >>>= 0; + var HEAP_DATA_VIEW = new DataView(wasmMemory.buffer), GET_HEAP_DATA_VIEW = function () { return HEAP_DATA_VIEW.buffer === wasmMemory.buffer ? HEAP_DATA_VIEW : (HEAP_DATA_VIEW = new DataView(wasmMemory.buffer)); }; + for (var i = 0; i < property_count; i++) { + var name_value = emnapiCtx.handleStore.get(GET_HEAP_DATA_VIEW().getUint32(property_names + i * 4, true)).value; + if (!(typeof name_value === "string" || typeof name_value === "symbol")) + return envObject.setLastError(4 /* napi_status.napi_name_expected */); + properties[name_value] = { + value: emnapiCtx.handleStore.get(GET_HEAP_DATA_VIEW().getUint32(property_values + i * 4, true)).value, + writable: true, + enumerable: true, + configurable: true + }; + } + var obj; + try { + obj = Object.defineProperties(Object.create(v8_prototype_or_null), properties); + } + catch (_) { + return envObject.setLastError(9 /* napi_status.napi_generic_failure */); + } + // eslint-disable-next-line @typescript-eslint/no-unused-vars + var value = emnapiCtx.addToCurrentScope(obj).id; + result >>>= 0; + GET_HEAP_DATA_VIEW().setUint32(result, value, true); + return envObject.clearLastError(); + } + /** + * @__sig ippp + */ + function napi_create_symbol(env, description, result) { + if (!env) + return 1 /* napi_status.napi_invalid_arg */; + // @ts-expect-error + var envObject = emnapiCtx.envStore.get(env); + envObject.checkGCAccess(); + if (!result) + return envObject.setLastError(1 /* napi_status.napi_invalid_arg */); + result >>>= 0; + var HEAP_DATA_VIEW = new DataView(wasmMemory.buffer), GET_HEAP_DATA_VIEW = function () { return HEAP_DATA_VIEW.buffer === wasmMemory.buffer ? HEAP_DATA_VIEW : (HEAP_DATA_VIEW = new DataView(wasmMemory.buffer)); }; + if (!description) { + // eslint-disable-next-line symbol-description, @typescript-eslint/no-unused-vars + var value = emnapiCtx.addToCurrentScope(Symbol()).id; + GET_HEAP_DATA_VIEW().setUint32(result, value, true); + } + else { + var handle = emnapiCtx.handleStore.get(description); + var desc = handle.value; + if (typeof desc !== 'string') { + return envObject.setLastError(3 /* napi_status.napi_string_expected */); + } + // eslint-disable-next-line @typescript-eslint/no-unused-vars + var v = emnapiCtx.addToCurrentScope(Symbol(desc)).id; + GET_HEAP_DATA_VIEW().setUint32(result, v, true); + } + return envObject.clearLastError(); + } + /** + * @__sig ipipppp + */ + function napi_create_typedarray(env, type, length, arraybuffer, byte_offset, result) { + // eslint-disable-next-line @typescript-eslint/no-unused-vars + var value; + if (!env) + return 1 /* napi_status.napi_invalid_arg */; + // @ts-expect-error + var envObject = emnapiCtx.envStore.get(env); + envObject.checkGCAccess(); + if (!envObject.tryCatch.isEmpty()) + return envObject.setLastError(10 /* napi_status.napi_pending_exception */); + if (!envObject.canCallIntoJs()) + return envObject.setLastError(envObject.moduleApiVersion >= 10 ? 23 /* napi_status.napi_cannot_run_js */ : 10 /* napi_status.napi_pending_exception */); + envObject.clearLastError(); + try { + if (!arraybuffer) + return envObject.setLastError(1 /* napi_status.napi_invalid_arg */); + if (!result) + return envObject.setLastError(1 /* napi_status.napi_invalid_arg */); + var handle = emnapiCtx.handleStore.get(arraybuffer); + var buffer = handle.value; + byte_offset >>>= 0; + length >>>= 0; + var createTypedArray = function (envObject, Type, size_of_element, buffer, byte_offset, length) { + var _a; + byte_offset = byte_offset >>> 0; + length = length >>> 0; + if (size_of_element > 1) { + if ((byte_offset) % (size_of_element) !== 0) { + var err = new RangeError("start offset of ".concat((_a = Type.name) !== null && _a !== void 0 ? _a : '', " should be a multiple of ").concat(size_of_element)); + err.code = 'ERR_NAPI_INVALID_TYPEDARRAY_ALIGNMENT'; + envObject.tryCatch.setError(err); + return envObject.setLastError(9 /* napi_status.napi_generic_failure */); + } + } + if (((length * size_of_element) + byte_offset) > buffer.byteLength) { + var err = new RangeError('Invalid typed array length'); + err.code = 'ERR_NAPI_INVALID_TYPEDARRAY_LENGTH'; + envObject.tryCatch.setError(err); + return envObject.setLastError(9 /* napi_status.napi_generic_failure */); + } + var out = new Type(buffer, byte_offset, length); + if (buffer === wasmMemory.buffer) { + if (!emnapiExternalMemory.wasmMemoryViewTable.has(out)) { + emnapiExternalMemory.wasmMemoryViewTable.set(out, { + Ctor: Type, + address: byte_offset, + length: length, + ownership: 1 /* ReferenceOwnership.kUserland */, + runtimeAllocated: 0 + }); + } + } + result >>>= 0; + // eslint-disable-next-line @typescript-eslint/no-unused-vars + value = emnapiCtx.addToCurrentScope(out).id; + var HEAP_DATA_VIEW = new DataView(wasmMemory.buffer), GET_HEAP_DATA_VIEW = function () { return HEAP_DATA_VIEW.buffer === wasmMemory.buffer ? HEAP_DATA_VIEW : (HEAP_DATA_VIEW = new DataView(wasmMemory.buffer)); }; + GET_HEAP_DATA_VIEW().setUint32(result, value, true); + return envObject.getReturnStatus(); + }; + if (buffer instanceof ArrayBuffer || emnapiExternalMemory.isSharedArrayBuffer(buffer)) { + switch (type) { + case 0 /* napi_typedarray_type.napi_int8_array */: + return createTypedArray(envObject, Int8Array, 1, buffer, byte_offset, length); + case 1 /* napi_typedarray_type.napi_uint8_array */: + return createTypedArray(envObject, Uint8Array, 1, buffer, byte_offset, length); + case 2 /* napi_typedarray_type.napi_uint8_clamped_array */: + return createTypedArray(envObject, Uint8ClampedArray, 1, buffer, byte_offset, length); + case 3 /* napi_typedarray_type.napi_int16_array */: + return createTypedArray(envObject, Int16Array, 2, buffer, byte_offset, length); + case 4 /* napi_typedarray_type.napi_uint16_array */: + return createTypedArray(envObject, Uint16Array, 2, buffer, byte_offset, length); + case 5 /* napi_typedarray_type.napi_int32_array */: + return createTypedArray(envObject, Int32Array, 4, buffer, byte_offset, length); + case 6 /* napi_typedarray_type.napi_uint32_array */: + return createTypedArray(envObject, Uint32Array, 4, buffer, byte_offset, length); + case 7 /* napi_typedarray_type.napi_float32_array */: + return createTypedArray(envObject, Float32Array, 4, buffer, byte_offset, length); + case 8 /* napi_typedarray_type.napi_float64_array */: + return createTypedArray(envObject, Float64Array, 8, buffer, byte_offset, length); + case 9 /* napi_typedarray_type.napi_bigint64_array */: + return createTypedArray(envObject, BigInt64Array, 8, buffer, byte_offset, length); + case 10 /* napi_typedarray_type.napi_biguint64_array */: + return createTypedArray(envObject, BigUint64Array, 8, buffer, byte_offset, length); + case 11 /* napi_typedarray_type.napi_float16_array */: + if (typeof Float16Array !== 'function') { + return envObject.setLastError(1 /* napi_status.napi_invalid_arg */); + } + return createTypedArray(envObject, Float16Array, 2, buffer, byte_offset, length); + default: + return envObject.setLastError(1 /* napi_status.napi_invalid_arg */); + } + } + else { + return envObject.setLastError(1 /* napi_status.napi_invalid_arg */); + } + } + catch (err) { + envObject.tryCatch.setError(err); + return envObject.setLastError(10 /* napi_status.napi_pending_exception */); + } + } + /** + * @__deps malloc + * @__sig ippp + */ + function napi_create_buffer(env, size, data, result) { + var _a; + // eslint-disable-next-line @typescript-eslint/no-unused-vars + var value, pointer; + if (!env) + return 1 /* napi_status.napi_invalid_arg */; + // @ts-expect-error + var envObject = emnapiCtx.envStore.get(env); + envObject.checkGCAccess(); + if (!envObject.tryCatch.isEmpty()) + return envObject.setLastError(10 /* napi_status.napi_pending_exception */); + if (!envObject.canCallIntoJs()) + return envObject.setLastError(envObject.moduleApiVersion >= 10 ? 23 /* napi_status.napi_cannot_run_js */ : 10 /* napi_status.napi_pending_exception */); + envObject.clearLastError(); + try { + if (!result) + return envObject.setLastError(1 /* napi_status.napi_invalid_arg */); + var Buffer = emnapiCtx.feature.Buffer; + if (!Buffer) { + throw emnapiCtx.createNotSupportBufferError('napi_create_buffer', ''); + } + result >>>= 0; + var buffer = void 0; + size >>>= 0; + size = size >>> 0; + var HEAP_DATA_VIEW = new DataView(wasmMemory.buffer), GET_HEAP_DATA_VIEW = function () { return HEAP_DATA_VIEW.buffer === wasmMemory.buffer ? HEAP_DATA_VIEW : (HEAP_DATA_VIEW = new DataView(wasmMemory.buffer)); }; + if (!data || (size === 0)) { + buffer = Buffer.alloc(size); + value = emnapiCtx.addToCurrentScope(buffer).id; + GET_HEAP_DATA_VIEW().setUint32(result, value, true); + } + else { + pointer = _malloc(size); + if (!pointer) + throw new Error('Out of memory'); + pointer >>>= 0; + new Uint8Array(wasmMemory.buffer).subarray(pointer, pointer + size).fill(0); + // capture Buffer.from at creation so a later refreshed view uses it + var buffer_1 = emnapiExternalMemory.getBufferFrom()(wasmMemory.buffer, pointer, size); + var viewDescriptor = { + Ctor: Buffer, + address: pointer, + length: size, + ownership: emnapiExternalMemory.registry ? 0 /* ReferenceOwnership.kRuntime */ : 1 /* ReferenceOwnership.kUserland */, + runtimeAllocated: 1 + }; + emnapiExternalMemory.wasmMemoryViewTable.set(buffer_1, viewDescriptor); + (_a = emnapiExternalMemory.registry) === null || _a === void 0 ? void 0 : _a.register(viewDescriptor, pointer); + value = emnapiCtx.addToCurrentScope(buffer_1).id; + GET_HEAP_DATA_VIEW().setUint32(result, value, true); + data >>>= 0; + GET_HEAP_DATA_VIEW().setUint32(data, pointer, true); + } + return envObject.getReturnStatus(); + } + catch (err) { + envObject.tryCatch.setError(err); + return envObject.setLastError(10 /* napi_status.napi_pending_exception */); + } + } + /** + * @__sig ippppp + */ + function napi_create_buffer_copy(env, length, data, result_data, result) { + // eslint-disable-next-line @typescript-eslint/no-unused-vars + var value; + if (!env) + return 1 /* napi_status.napi_invalid_arg */; + // @ts-expect-error + var envObject = emnapiCtx.envStore.get(env); + envObject.checkGCAccess(); + if (!envObject.tryCatch.isEmpty()) + return envObject.setLastError(10 /* napi_status.napi_pending_exception */); + if (!envObject.canCallIntoJs()) + return envObject.setLastError(envObject.moduleApiVersion >= 10 ? 23 /* napi_status.napi_cannot_run_js */ : 10 /* napi_status.napi_pending_exception */); + envObject.clearLastError(); + try { + if (!result) + return envObject.setLastError(1 /* napi_status.napi_invalid_arg */); + var Buffer = emnapiCtx.feature.Buffer; + if (!Buffer) { + throw emnapiCtx.createNotSupportBufferError('napi_create_buffer_copy', ''); + } + var arrayBuffer = emnapiCreateArrayBuffer(length, result_data, false); + var buffer = Buffer.from(arrayBuffer); + data >>>= 0; + length >>>= 0; + buffer.set(new Uint8Array(wasmMemory.buffer).subarray(data, data + length)); + value = emnapiCtx.addToCurrentScope(buffer).id; + result >>>= 0; + var HEAP_DATA_VIEW = new DataView(wasmMemory.buffer), GET_HEAP_DATA_VIEW = function () { return HEAP_DATA_VIEW.buffer === wasmMemory.buffer ? HEAP_DATA_VIEW : (HEAP_DATA_VIEW = new DataView(wasmMemory.buffer)); }; + GET_HEAP_DATA_VIEW().setUint32(result, value, true); + return envObject.getReturnStatus(); + } + catch (err) { + envObject.tryCatch.setError(err); + return envObject.setLastError(10 /* napi_status.napi_pending_exception */); + } + } + /** + * @__sig ipppppp + */ + function napi_create_external_buffer(env, length, data, finalize_cb, finalize_hint, result) { + return emnapi_create_memory_view(env, -2 /* emnapi_memory_view_type.emnapi_buffer */, data, length, finalize_cb, finalize_hint, result); + } + /** + * @__sig ippppp + */ + function node_api_create_buffer_from_arraybuffer(env, arraybuffer, byte_offset, byte_length, result) { + // eslint-disable-next-line @typescript-eslint/no-unused-vars + var value; + if (!env) + return 1 /* napi_status.napi_invalid_arg */; + // @ts-expect-error + var envObject = emnapiCtx.envStore.get(env); + envObject.checkGCAccess(); + if (!envObject.tryCatch.isEmpty()) + return envObject.setLastError(10 /* napi_status.napi_pending_exception */); + if (!envObject.canCallIntoJs()) + return envObject.setLastError(envObject.moduleApiVersion >= 10 ? 23 /* napi_status.napi_cannot_run_js */ : 10 /* napi_status.napi_pending_exception */); + envObject.clearLastError(); + try { + if (!arraybuffer) + return envObject.setLastError(1 /* napi_status.napi_invalid_arg */); + if (!result) + return envObject.setLastError(1 /* napi_status.napi_invalid_arg */); + byte_offset >>>= 0; + byte_length >>>= 0; + byte_offset = byte_offset >>> 0; + byte_length = byte_length >>> 0; + var handle = emnapiCtx.handleStore.get(arraybuffer); + if (!handle.isArrayBuffer()) { + return envObject.setLastError(1 /* napi_status.napi_invalid_arg */); + } + var buffer = handle.value; + if ((byte_length + byte_offset) > buffer.byteLength) { + var err = new RangeError('The byte offset + length is out of range'); + err.code = 'ERR_OUT_OF_RANGE'; + throw err; + } + var Buffer = emnapiCtx.feature.Buffer; + if (!Buffer) { + throw emnapiCtx.createNotSupportBufferError('node_api_create_buffer_from_arraybuffer', ''); + } + // capture Buffer.from at creation so a later refreshed view uses it + var out = emnapiExternalMemory.getBufferFrom()(buffer, byte_offset, byte_length); + if (buffer === wasmMemory.buffer) { + if (!emnapiExternalMemory.wasmMemoryViewTable.has(out)) { + emnapiExternalMemory.wasmMemoryViewTable.set(out, { + Ctor: Buffer, + address: byte_offset, + length: byte_length, + ownership: 1 /* ReferenceOwnership.kUserland */, + runtimeAllocated: 0 + }); + } + } + result >>>= 0; + // eslint-disable-next-line @typescript-eslint/no-unused-vars + value = emnapiCtx.addToCurrentScope(out).id; + var HEAP_DATA_VIEW = new DataView(wasmMemory.buffer), GET_HEAP_DATA_VIEW = function () { return HEAP_DATA_VIEW.buffer === wasmMemory.buffer ? HEAP_DATA_VIEW : (HEAP_DATA_VIEW = new DataView(wasmMemory.buffer)); }; + GET_HEAP_DATA_VIEW().setUint32(result, value, true); + return envObject.getReturnStatus(); + } + catch (err) { + envObject.tryCatch.setError(err); + return envObject.setLastError(10 /* napi_status.napi_pending_exception */); + } + } + /** + * @__sig ippppp + */ + function napi_create_dataview(env, byte_length, arraybuffer, byte_offset, result) { + if (!env) + return 1 /* napi_status.napi_invalid_arg */; + // @ts-expect-error + var envObject = emnapiCtx.envStore.get(env); + envObject.checkGCAccess(); + if (!envObject.tryCatch.isEmpty()) + return envObject.setLastError(10 /* napi_status.napi_pending_exception */); + if (!envObject.canCallIntoJs()) + return envObject.setLastError(envObject.moduleApiVersion >= 10 ? 23 /* napi_status.napi_cannot_run_js */ : 10 /* napi_status.napi_pending_exception */); + envObject.clearLastError(); + try { + if (!arraybuffer) + return envObject.setLastError(1 /* napi_status.napi_invalid_arg */); + if (!result) + return envObject.setLastError(1 /* napi_status.napi_invalid_arg */); + byte_length >>>= 0; + byte_offset >>>= 0; + byte_length = byte_length >>> 0; + byte_offset = byte_offset >>> 0; + var value = emnapiCtx.handleStore.get(arraybuffer).value; + var createDataview = function (buffer) { + if ((byte_length + byte_offset) > buffer.byteLength) { + var err = new RangeError('byte_offset + byte_length should be less than or equal to the size in bytes of the array passed in'); + err.code = 'ERR_NAPI_INVALID_DATAVIEW_ARGS'; + throw err; + } + var dataview = new DataView(buffer, byte_offset, byte_length); + if (buffer === wasmMemory.buffer) { + if (!emnapiExternalMemory.wasmMemoryViewTable.has(dataview)) { + emnapiExternalMemory.wasmMemoryViewTable.set(dataview, { + Ctor: DataView, + address: byte_offset, + length: byte_length, + ownership: 1 /* ReferenceOwnership.kUserland */, + runtimeAllocated: 0 + }); + } + } + result >>>= 0; + // eslint-disable-next-line @typescript-eslint/no-unused-vars + var v = emnapiCtx.addToCurrentScope(dataview).id; + var HEAP_DATA_VIEW = new DataView(wasmMemory.buffer), GET_HEAP_DATA_VIEW = function () { return HEAP_DATA_VIEW.buffer === wasmMemory.buffer ? HEAP_DATA_VIEW : (HEAP_DATA_VIEW = new DataView(wasmMemory.buffer)); }; + GET_HEAP_DATA_VIEW().setUint32(result, v, true); + return envObject.getReturnStatus(); + }; + if (value instanceof ArrayBuffer || emnapiExternalMemory.isSharedArrayBuffer(value)) { + return createDataview(value); + } + else { + return envObject.setLastError(1 /* napi_status.napi_invalid_arg */); + } + } + catch (err) { + envObject.tryCatch.setError(err); + return envObject.setLastError(10 /* napi_status.napi_pending_exception */); + } + } + /** + * @__sig ipppp + */ + function node_api_symbol_for(env, utf8description, length, result) { + if (!env) + return 1 /* napi_status.napi_invalid_arg */; + // @ts-expect-error + var envObject = emnapiCtx.envStore.get(env); + envObject.checkGCAccess(); + if (!result) + return envObject.setLastError(1 /* napi_status.napi_invalid_arg */); + length >>>= 0; + utf8description >>>= 0; + result >>>= 0; + var autoLength = length === -1 || length === 4294967295; + var sizelength = length >>> 0; + if (length !== 0) { + if (!utf8description) + return envObject.setLastError(1 /* napi_status.napi_invalid_arg */); + } + if (!(autoLength || (sizelength <= 2147483647))) { + return envObject.setLastError(1 /* napi_status.napi_invalid_arg */); + } + var descriptionString = emnapiString.UTF8ToString(utf8description, length); + // eslint-disable-next-line @typescript-eslint/no-unused-vars + var value = emnapiCtx.addToCurrentScope(Symbol.for(descriptionString)).id; + var HEAP_DATA_VIEW = new DataView(wasmMemory.buffer), GET_HEAP_DATA_VIEW = function () { return HEAP_DATA_VIEW.buffer === wasmMemory.buffer ? HEAP_DATA_VIEW : (HEAP_DATA_VIEW = new DataView(wasmMemory.buffer)); }; + GET_HEAP_DATA_VIEW().setUint32(result, value, true); + return envObject.clearLastError(); + } + var createMod = /*#__PURE__*/ Object.freeze({ + __proto__: null, + napi_create_array: napi_create_array, + napi_create_array_with_length: napi_create_array_with_length, + napi_create_arraybuffer: napi_create_arraybuffer, + napi_create_buffer: napi_create_buffer, + napi_create_buffer_copy: napi_create_buffer_copy, + napi_create_dataview: napi_create_dataview, + napi_create_date: napi_create_date, + napi_create_external: napi_create_external, + napi_create_external_arraybuffer: napi_create_external_arraybuffer, + napi_create_external_buffer: napi_create_external_buffer, + napi_create_object: napi_create_object, + napi_create_symbol: napi_create_symbol, + napi_create_typedarray: napi_create_typedarray, + node_api_create_buffer_from_arraybuffer: node_api_create_buffer_from_arraybuffer, + node_api_create_external_sharedarraybuffer: node_api_create_external_sharedarraybuffer, + node_api_create_object_with_properties: node_api_create_object_with_properties, + node_api_create_sharedarraybuffer: node_api_create_sharedarraybuffer, + node_api_symbol_for: node_api_symbol_for + }); + /** @__sig ipip */ + function napi_get_boolean(env, value, result) { + if (!env) + return 1 /* napi_status.napi_invalid_arg */; + // @ts-expect-error + var envObject = emnapiCtx.envStore.get(env); + envObject.checkGCAccess(); + if (!result) + return envObject.setLastError(1 /* napi_status.napi_invalid_arg */); + result >>>= 0; + // eslint-disable-next-line @typescript-eslint/no-unused-vars + var v = value === 0 ? 3 /* GlobalHandle.FALSE */ : 4 /* GlobalHandle.TRUE */; + var HEAP_DATA_VIEW = new DataView(wasmMemory.buffer), GET_HEAP_DATA_VIEW = function () { return HEAP_DATA_VIEW.buffer === wasmMemory.buffer ? HEAP_DATA_VIEW : (HEAP_DATA_VIEW = new DataView(wasmMemory.buffer)); }; + GET_HEAP_DATA_VIEW().setUint32(result, v, true); + return envObject.clearLastError(); + } + /** @__sig ipp */ + function napi_get_global(env, result) { + if (!env) + return 1 /* napi_status.napi_invalid_arg */; + // @ts-expect-error + var envObject = emnapiCtx.envStore.get(env); + envObject.checkGCAccess(); + if (!result) + return envObject.setLastError(1 /* napi_status.napi_invalid_arg */); + result >>>= 0; + // eslint-disable-next-line @typescript-eslint/no-unused-vars + var value = 5 /* GlobalHandle.GLOBAL */; + var HEAP_DATA_VIEW = new DataView(wasmMemory.buffer), GET_HEAP_DATA_VIEW = function () { return HEAP_DATA_VIEW.buffer === wasmMemory.buffer ? HEAP_DATA_VIEW : (HEAP_DATA_VIEW = new DataView(wasmMemory.buffer)); }; + GET_HEAP_DATA_VIEW().setUint32(result, value, true); + return envObject.clearLastError(); + } + /** @__sig ipp */ + function napi_get_null(env, result) { + if (!env) + return 1 /* napi_status.napi_invalid_arg */; + // @ts-expect-error + var envObject = emnapiCtx.envStore.get(env); + envObject.checkGCAccess(); + if (!result) + return envObject.setLastError(1 /* napi_status.napi_invalid_arg */); + result >>>= 0; + // eslint-disable-next-line @typescript-eslint/no-unused-vars + var value = 2 /* GlobalHandle.NULL */; + var HEAP_DATA_VIEW = new DataView(wasmMemory.buffer), GET_HEAP_DATA_VIEW = function () { return HEAP_DATA_VIEW.buffer === wasmMemory.buffer ? HEAP_DATA_VIEW : (HEAP_DATA_VIEW = new DataView(wasmMemory.buffer)); }; + GET_HEAP_DATA_VIEW().setUint32(result, value, true); + return envObject.clearLastError(); + } + /** @__sig ipp */ + function napi_get_undefined(env, result) { + if (!env) + return 1 /* napi_status.napi_invalid_arg */; + // @ts-expect-error + var envObject = emnapiCtx.envStore.get(env); + envObject.checkGCAccess(); + if (!result) + return envObject.setLastError(1 /* napi_status.napi_invalid_arg */); + result >>>= 0; + // eslint-disable-next-line @typescript-eslint/no-unused-vars + var value = 1 /* GlobalHandle.UNDEFINED */; + var HEAP_DATA_VIEW = new DataView(wasmMemory.buffer), GET_HEAP_DATA_VIEW = function () { return HEAP_DATA_VIEW.buffer === wasmMemory.buffer ? HEAP_DATA_VIEW : (HEAP_DATA_VIEW = new DataView(wasmMemory.buffer)); }; + GET_HEAP_DATA_VIEW().setUint32(result, value, true); + return envObject.clearLastError(); + } + var globalMod = /*#__PURE__*/ Object.freeze({ + __proto__: null, + napi_get_boolean: napi_get_boolean, + napi_get_global: napi_get_global, + napi_get_null: napi_get_null, + napi_get_undefined: napi_get_undefined + }); + /** @__sig ipppp */ + function napi_set_instance_data(env, data, finalize_cb, finalize_hint) { + if (!env) + return 1 /* napi_status.napi_invalid_arg */; + var envObject = emnapiCtx.envStore.get(env); + data >>>= 0; + finalize_cb >>>= 0; + finalize_hint >>>= 0; + envObject.setInstanceData(data, finalize_cb, finalize_hint); + return envObject.clearLastError(); + } + /** @__sig ipp */ + function napi_get_instance_data(env, data) { + if (!env) + return 1 /* napi_status.napi_invalid_arg */; + var envObject = emnapiCtx.envStore.get(env); + if (!data) + return envObject.setLastError(1 /* napi_status.napi_invalid_arg */); + data >>>= 0; + // eslint-disable-next-line @typescript-eslint/no-unused-vars + var value = envObject.getInstanceData(); + var HEAP_DATA_VIEW = new DataView(wasmMemory.buffer), GET_HEAP_DATA_VIEW = function () { return HEAP_DATA_VIEW.buffer === wasmMemory.buffer ? HEAP_DATA_VIEW : (HEAP_DATA_VIEW = new DataView(wasmMemory.buffer)); }; + GET_HEAP_DATA_VIEW().setUint32(data, value, true); + return envObject.clearLastError(); + } + var envMod = /*#__PURE__*/ Object.freeze({ + __proto__: null, + napi_get_instance_data: napi_get_instance_data, + napi_set_instance_data: napi_set_instance_data + }); + /** @__sig vpppp */ + function _emnapi_get_last_error_info(env, error_code, engine_error_code, engine_reserved) { + error_code >>>= 0; + engine_error_code >>>= 0; + engine_reserved >>>= 0; + var envObject = emnapiCtx.envStore.get(env); + var lastError = envObject.lastError; + // eslint-disable-next-line @typescript-eslint/no-unused-vars + var errorCode = lastError.errorCode; + // eslint-disable-next-line @typescript-eslint/no-unused-vars + var engineErrorCode = lastError.engineErrorCode >>> 0; + // eslint-disable-next-line @typescript-eslint/no-unused-vars + var engineReserved = lastError.engineReserved; + engineReserved >>>= 0; + var HEAP_DATA_VIEW = new DataView(wasmMemory.buffer), GET_HEAP_DATA_VIEW = function () { return HEAP_DATA_VIEW.buffer === wasmMemory.buffer ? HEAP_DATA_VIEW : (HEAP_DATA_VIEW = new DataView(wasmMemory.buffer)); }; + GET_HEAP_DATA_VIEW().setInt32(error_code, errorCode, true); + GET_HEAP_DATA_VIEW().setUint32(engine_error_code, engineErrorCode, true); + GET_HEAP_DATA_VIEW().setUint32(engine_reserved, engineReserved, true); + } + /** @__sig ipp */ + function napi_throw(env, error) { + if (!env) + return 1 /* napi_status.napi_invalid_arg */; + // @ts-expect-error + var envObject = emnapiCtx.envStore.get(env); + envObject.checkGCAccess(); + if (!envObject.tryCatch.isEmpty()) + return envObject.setLastError(10 /* napi_status.napi_pending_exception */); + if (!envObject.canCallIntoJs()) + return envObject.setLastError(envObject.moduleApiVersion >= 10 ? 23 /* napi_status.napi_cannot_run_js */ : 10 /* napi_status.napi_pending_exception */); + envObject.clearLastError(); + try { + if (!error) + return envObject.setLastError(1 /* napi_status.napi_invalid_arg */); + envObject.tryCatch.setError(emnapiCtx.handleStore.get(error).value); + return envObject.clearLastError(); + } + catch (err) { + envObject.tryCatch.setError(err); + return envObject.setLastError(10 /* napi_status.napi_pending_exception */); + } + } + /** @__sig ippp */ + function napi_throw_error(env, code, msg) { + if (!env) + return 1 /* napi_status.napi_invalid_arg */; + // @ts-expect-error + var envObject = emnapiCtx.envStore.get(env); + envObject.checkGCAccess(); + if (!envObject.tryCatch.isEmpty()) + return envObject.setLastError(10 /* napi_status.napi_pending_exception */); + if (!envObject.canCallIntoJs()) + return envObject.setLastError(envObject.moduleApiVersion >= 10 ? 23 /* napi_status.napi_cannot_run_js */ : 10 /* napi_status.napi_pending_exception */); + envObject.clearLastError(); + try { + if (!msg) + return envObject.setLastError(1 /* napi_status.napi_invalid_arg */); + code >>>= 0; + msg >>>= 0; + var error = new Error(emnapiString.UTF8ToString(msg, -1)); + if (code) + error.code = emnapiString.UTF8ToString(code, -1); + envObject.tryCatch.setError(error); + return envObject.clearLastError(); + } + catch (err) { + envObject.tryCatch.setError(err); + return envObject.setLastError(10 /* napi_status.napi_pending_exception */); + } + } + /** @__sig ippp */ + function napi_throw_type_error(env, code, msg) { + if (!env) + return 1 /* napi_status.napi_invalid_arg */; + // @ts-expect-error + var envObject = emnapiCtx.envStore.get(env); + envObject.checkGCAccess(); + if (!envObject.tryCatch.isEmpty()) + return envObject.setLastError(10 /* napi_status.napi_pending_exception */); + if (!envObject.canCallIntoJs()) + return envObject.setLastError(envObject.moduleApiVersion >= 10 ? 23 /* napi_status.napi_cannot_run_js */ : 10 /* napi_status.napi_pending_exception */); + envObject.clearLastError(); + try { + if (!msg) + return envObject.setLastError(1 /* napi_status.napi_invalid_arg */); + code >>>= 0; + msg >>>= 0; + var error = new TypeError(emnapiString.UTF8ToString(msg, -1)); + if (code) + error.code = emnapiString.UTF8ToString(code, -1); + envObject.tryCatch.setError(error); + return envObject.clearLastError(); + } + catch (err) { + envObject.tryCatch.setError(err); + return envObject.setLastError(10 /* napi_status.napi_pending_exception */); + } + } + /** @__sig ippp */ + function napi_throw_range_error(env, code, msg) { + if (!env) + return 1 /* napi_status.napi_invalid_arg */; + // @ts-expect-error + var envObject = emnapiCtx.envStore.get(env); + envObject.checkGCAccess(); + if (!envObject.tryCatch.isEmpty()) + return envObject.setLastError(10 /* napi_status.napi_pending_exception */); + if (!envObject.canCallIntoJs()) + return envObject.setLastError(envObject.moduleApiVersion >= 10 ? 23 /* napi_status.napi_cannot_run_js */ : 10 /* napi_status.napi_pending_exception */); + envObject.clearLastError(); + try { + if (!msg) + return envObject.setLastError(1 /* napi_status.napi_invalid_arg */); + code >>>= 0; + msg >>>= 0; + var error = new RangeError(emnapiString.UTF8ToString(msg, -1)); + if (code) + error.code = emnapiString.UTF8ToString(code, -1); + envObject.tryCatch.setError(error); + return envObject.clearLastError(); + } + catch (err) { + envObject.tryCatch.setError(err); + return envObject.setLastError(10 /* napi_status.napi_pending_exception */); + } + } + /** @__sig ippp */ + function node_api_throw_syntax_error(env, code, msg) { + if (!env) + return 1 /* napi_status.napi_invalid_arg */; + // @ts-expect-error + var envObject = emnapiCtx.envStore.get(env); + envObject.checkGCAccess(); + if (!envObject.tryCatch.isEmpty()) + return envObject.setLastError(10 /* napi_status.napi_pending_exception */); + if (!envObject.canCallIntoJs()) + return envObject.setLastError(envObject.moduleApiVersion >= 10 ? 23 /* napi_status.napi_cannot_run_js */ : 10 /* napi_status.napi_pending_exception */); + envObject.clearLastError(); + try { + if (!msg) + return envObject.setLastError(1 /* napi_status.napi_invalid_arg */); + code >>>= 0; + msg >>>= 0; + var error = new SyntaxError(emnapiString.UTF8ToString(msg, -1)); + if (code) + error.code = emnapiString.UTF8ToString(code, -1); + envObject.tryCatch.setError(error); + return envObject.clearLastError(); + } + catch (err) { + envObject.tryCatch.setError(err); + return envObject.setLastError(10 /* napi_status.napi_pending_exception */); + } + } + /** @__sig ipp */ + function napi_is_exception_pending(env, result) { + if (!env) + return 1 /* napi_status.napi_invalid_arg */; + // @ts-expect-error + var envObject = emnapiCtx.envStore.get(env); + envObject.checkGCAccess(); + if (!result) + return envObject.setLastError(1 /* napi_status.napi_invalid_arg */); + // eslint-disable-next-line @typescript-eslint/no-unused-vars + var r = envObject.tryCatch.hasCaught(); + result >>>= 0; + var HEAP_DATA_VIEW = new DataView(wasmMemory.buffer), GET_HEAP_DATA_VIEW = function () { return HEAP_DATA_VIEW.buffer === wasmMemory.buffer ? HEAP_DATA_VIEW : (HEAP_DATA_VIEW = new DataView(wasmMemory.buffer)); }; + GET_HEAP_DATA_VIEW().setInt8(result, r ? 1 : 0, true); + return envObject.clearLastError(); + } + /** @__sig ipppp */ + function napi_create_error(env, code, msg, result) { + if (!env) + return 1 /* napi_status.napi_invalid_arg */; + // @ts-expect-error + var envObject = emnapiCtx.envStore.get(env); + envObject.checkGCAccess(); + if (!msg) + return envObject.setLastError(1 /* napi_status.napi_invalid_arg */); + if (!result) + return envObject.setLastError(1 /* napi_status.napi_invalid_arg */); + var msgValue = emnapiCtx.handleStore.get(msg).value; + if (typeof msgValue !== 'string') { + return envObject.setLastError(3 /* napi_status.napi_string_expected */); + } + var error = new Error(msgValue); + if (code) { + var codeValue = emnapiCtx.handleStore.get(code).value; + if (typeof codeValue !== 'string') { + return envObject.setLastError(3 /* napi_status.napi_string_expected */); + } + error.code = codeValue; + } + result >>>= 0; + // eslint-disable-next-line @typescript-eslint/no-unused-vars + var value = emnapiCtx.addToCurrentScope(error).id; + var HEAP_DATA_VIEW = new DataView(wasmMemory.buffer), GET_HEAP_DATA_VIEW = function () { return HEAP_DATA_VIEW.buffer === wasmMemory.buffer ? HEAP_DATA_VIEW : (HEAP_DATA_VIEW = new DataView(wasmMemory.buffer)); }; + GET_HEAP_DATA_VIEW().setUint32(result, value, true); + return envObject.clearLastError(); + } + /** @__sig ipppp */ + function napi_create_type_error(env, code, msg, result) { + if (!env) + return 1 /* napi_status.napi_invalid_arg */; + // @ts-expect-error + var envObject = emnapiCtx.envStore.get(env); + envObject.checkGCAccess(); + if (!msg) + return envObject.setLastError(1 /* napi_status.napi_invalid_arg */); + if (!result) + return envObject.setLastError(1 /* napi_status.napi_invalid_arg */); + var msgValue = emnapiCtx.handleStore.get(msg).value; + if (typeof msgValue !== 'string') { + return envObject.setLastError(3 /* napi_status.napi_string_expected */); + } + var error = new TypeError(msgValue); + if (code) { + var codeValue = emnapiCtx.handleStore.get(code).value; + if (typeof codeValue !== 'string') { + return envObject.setLastError(3 /* napi_status.napi_string_expected */); + } + error.code = codeValue; + } + result >>>= 0; + // eslint-disable-next-line @typescript-eslint/no-unused-vars + var value = emnapiCtx.addToCurrentScope(error).id; + var HEAP_DATA_VIEW = new DataView(wasmMemory.buffer), GET_HEAP_DATA_VIEW = function () { return HEAP_DATA_VIEW.buffer === wasmMemory.buffer ? HEAP_DATA_VIEW : (HEAP_DATA_VIEW = new DataView(wasmMemory.buffer)); }; + GET_HEAP_DATA_VIEW().setUint32(result, value, true); + return envObject.clearLastError(); + } + /** @__sig ipppp */ + function napi_create_range_error(env, code, msg, result) { + if (!env) + return 1 /* napi_status.napi_invalid_arg */; + // @ts-expect-error + var envObject = emnapiCtx.envStore.get(env); + envObject.checkGCAccess(); + if (!msg) + return envObject.setLastError(1 /* napi_status.napi_invalid_arg */); + if (!result) + return envObject.setLastError(1 /* napi_status.napi_invalid_arg */); + var msgValue = emnapiCtx.handleStore.get(msg).value; + if (typeof msgValue !== 'string') { + return envObject.setLastError(3 /* napi_status.napi_string_expected */); + } + var error = new RangeError(msgValue); + if (code) { + var codeValue = emnapiCtx.handleStore.get(code).value; + if (typeof codeValue !== 'string') { + return envObject.setLastError(3 /* napi_status.napi_string_expected */); + } + error.code = codeValue; + } + result >>>= 0; + // eslint-disable-next-line @typescript-eslint/no-unused-vars + var value = emnapiCtx.addToCurrentScope(error).id; + var HEAP_DATA_VIEW = new DataView(wasmMemory.buffer), GET_HEAP_DATA_VIEW = function () { return HEAP_DATA_VIEW.buffer === wasmMemory.buffer ? HEAP_DATA_VIEW : (HEAP_DATA_VIEW = new DataView(wasmMemory.buffer)); }; + GET_HEAP_DATA_VIEW().setUint32(result, value, true); + return envObject.clearLastError(); + } + /** @__sig ipppp */ + function node_api_create_syntax_error(env, code, msg, result) { + if (!env) + return 1 /* napi_status.napi_invalid_arg */; + // @ts-expect-error + var envObject = emnapiCtx.envStore.get(env); + envObject.checkGCAccess(); + if (!msg) + return envObject.setLastError(1 /* napi_status.napi_invalid_arg */); + if (!result) + return envObject.setLastError(1 /* napi_status.napi_invalid_arg */); + var msgValue = emnapiCtx.handleStore.get(msg).value; + if (typeof msgValue !== 'string') { + return envObject.setLastError(3 /* napi_status.napi_string_expected */); + } + var error = new SyntaxError(msgValue); + if (code) { + var codeValue = emnapiCtx.handleStore.get(code).value; + if (typeof codeValue !== 'string') { + return envObject.setLastError(3 /* napi_status.napi_string_expected */); + } + error.code = codeValue; + } + result >>>= 0; + // eslint-disable-next-line @typescript-eslint/no-unused-vars + var value = emnapiCtx.addToCurrentScope(error).id; + var HEAP_DATA_VIEW = new DataView(wasmMemory.buffer), GET_HEAP_DATA_VIEW = function () { return HEAP_DATA_VIEW.buffer === wasmMemory.buffer ? HEAP_DATA_VIEW : (HEAP_DATA_VIEW = new DataView(wasmMemory.buffer)); }; + GET_HEAP_DATA_VIEW().setUint32(result, value, true); + return envObject.clearLastError(); + } + /** @__sig ipp */ + function napi_get_and_clear_last_exception(env, result) { + if (!env) + return 1 /* napi_status.napi_invalid_arg */; + // @ts-expect-error + var envObject = emnapiCtx.envStore.get(env); + envObject.checkGCAccess(); + if (!result) + return envObject.setLastError(1 /* napi_status.napi_invalid_arg */); + result >>>= 0; + var HEAP_DATA_VIEW = new DataView(wasmMemory.buffer), GET_HEAP_DATA_VIEW = function () { return HEAP_DATA_VIEW.buffer === wasmMemory.buffer ? HEAP_DATA_VIEW : (HEAP_DATA_VIEW = new DataView(wasmMemory.buffer)); }; + if (!envObject.tryCatch.hasCaught()) { + GET_HEAP_DATA_VIEW().setUint32(result, 1, true); // ID_UNDEFINED + return envObject.clearLastError(); + } + else { + var err = envObject.tryCatch.exception(); + // eslint-disable-next-line @typescript-eslint/no-unused-vars + var value = envObject.ensureHandleId(err); + GET_HEAP_DATA_VIEW().setUint32(result, value, true); + envObject.tryCatch.reset(); + } + return envObject.clearLastError(); + } + /** @__sig vpppp */ + function napi_fatal_error(location, location_len, message, message_len) { + location >>>= 0; + location_len >>>= 0; + message >>>= 0; + message_len >>>= 0; + var locationStr = emnapiString.UTF8ToString(location, location_len); + var messageStr = emnapiString.UTF8ToString(message, message_len); + if (emnapiNodeBinding) { + emnapiNodeBinding.napi.fatalError(locationStr, messageStr); + } + else { + abort('FATAL ERROR: ' + locationStr + ' ' + messageStr); + } + } + /** @__sig ipp */ + function napi_fatal_exception(env, err) { + if (!env) + return 1 /* napi_status.napi_invalid_arg */; + // @ts-expect-error + var envObject = emnapiCtx.envStore.get(env); + envObject.checkGCAccess(); + if (!envObject.tryCatch.isEmpty()) + return envObject.setLastError(10 /* napi_status.napi_pending_exception */); + if (!envObject.canCallIntoJs()) + return envObject.setLastError(envObject.moduleApiVersion >= 10 ? 23 /* napi_status.napi_cannot_run_js */ : 10 /* napi_status.napi_pending_exception */); + envObject.clearLastError(); + try { + if (!err) + return envObject.setLastError(1 /* napi_status.napi_invalid_arg */); + var error = envObject.ctx.handleStore.get(err); + try { + envObject.triggerFatalException(error.value); + } + catch (_) { + return envObject.setLastError(9 /* napi_status.napi_generic_failure */); + } + return envObject.clearLastError(); + } + catch (err) { + envObject.tryCatch.setError(err); + return envObject.setLastError(10 /* napi_status.napi_pending_exception */); + } + } + var errorMod = /*#__PURE__*/ Object.freeze({ + __proto__: null, + _emnapi_get_last_error_info: _emnapi_get_last_error_info, + napi_create_error: napi_create_error, + napi_create_range_error: napi_create_range_error, + napi_create_type_error: napi_create_type_error, + napi_fatal_error: napi_fatal_error, + napi_fatal_exception: napi_fatal_exception, + napi_get_and_clear_last_exception: napi_get_and_clear_last_exception, + napi_is_exception_pending: napi_is_exception_pending, + napi_throw: napi_throw, + napi_throw_error: napi_throw_error, + napi_throw_range_error: napi_throw_range_error, + napi_throw_type_error: napi_throw_type_error, + node_api_create_syntax_error: node_api_create_syntax_error, + node_api_throw_syntax_error: node_api_throw_syntax_error + }); + /** @__sig ipppppp */ + function _emnapi_create_function(env, utf8name, length, cb, data, result) { + length >>>= 0; + var envObject = emnapiCtx.envStore.get(env); + var fresult = emnapiCreateFunction(envObject, utf8name, length, cb, data); + if (fresult.status !== 0 /* napi_status.napi_ok */) + return envObject.setLastError(fresult.status); + var f = fresult.f; + var valueHandle = emnapiCtx.addToCurrentScope(f); + result >>>= 0; + // eslint-disable-next-line @typescript-eslint/no-unused-vars + var value = valueHandle.id; + var HEAP_DATA_VIEW = new DataView(wasmMemory.buffer), GET_HEAP_DATA_VIEW = function () { return HEAP_DATA_VIEW.buffer === wasmMemory.buffer ? HEAP_DATA_VIEW : (HEAP_DATA_VIEW = new DataView(wasmMemory.buffer)); }; + GET_HEAP_DATA_VIEW().setUint32(result, value, true); + return envObject.getReturnStatus(); + } + /** @__sig ipppppp */ + function napi_create_function(env, utf8name, length, cb, data, result) { + if (!env) + return 1 /* napi_status.napi_invalid_arg */; + // @ts-expect-error + var envObject = emnapiCtx.envStore.get(env); + envObject.checkGCAccess(); + if (!envObject.tryCatch.isEmpty()) + return envObject.setLastError(10 /* napi_status.napi_pending_exception */); + if (!envObject.canCallIntoJs()) + return envObject.setLastError(envObject.moduleApiVersion >= 10 ? 23 /* napi_status.napi_cannot_run_js */ : 10 /* napi_status.napi_pending_exception */); + envObject.clearLastError(); + try { + if (!result) + return envObject.setLastError(1 /* napi_status.napi_invalid_arg */); + if (!cb) + return envObject.setLastError(1 /* napi_status.napi_invalid_arg */); + return _emnapi_create_function(env, utf8name, length, cb, data, result); + } + catch (err) { + envObject.tryCatch.setError(err); + return envObject.setLastError(10 /* napi_status.napi_pending_exception */); + } + } + /** @__sig ipppppp */ + function napi_get_cb_info(env, cbinfo, argc, argv, this_arg, data) { + if (!env) + return 1 /* napi_status.napi_invalid_arg */; + var envObject = emnapiCtx.envStore.get(env); + if (!cbinfo) + return envObject.setLastError(1 /* napi_status.napi_invalid_arg */); + var cbinfoValue = emnapiCtx.scopeStore.get(cbinfo).callbackInfo; + argc >>>= 0; + argv >>>= 0; + var HEAP_DATA_VIEW = new DataView(wasmMemory.buffer), GET_HEAP_DATA_VIEW = function () { return HEAP_DATA_VIEW.buffer === wasmMemory.buffer ? HEAP_DATA_VIEW : (HEAP_DATA_VIEW = new DataView(wasmMemory.buffer)); }; + if (argv) { + if (!argc) + return envObject.setLastError(1 /* napi_status.napi_invalid_arg */); + var argcValue = GET_HEAP_DATA_VIEW().getUint32(argc, true); + argcValue >>>= 0; + var len = cbinfoValue.args.length; + var arrlen = argcValue < len ? argcValue : len; + var i = 0; + for (; i < arrlen; i++) { + // eslint-disable-next-line @typescript-eslint/no-unused-vars + var argVal = envObject.ensureHandleId(cbinfoValue.args[i]); + GET_HEAP_DATA_VIEW().setUint32(argv + i * 4, argVal, true); + } + if (i < argcValue) { + for (; i < argcValue; i++) { + GET_HEAP_DATA_VIEW().setUint32(argv + i * 4, 1, true); + } + } + } + if (argc) { + GET_HEAP_DATA_VIEW().setUint32(argc, cbinfoValue.args.length, true); + } + if (this_arg) { + this_arg >>>= 0; + // eslint-disable-next-line @typescript-eslint/no-unused-vars + var v = envObject.ensureHandleId(cbinfoValue.thiz); + GET_HEAP_DATA_VIEW().setUint32(this_arg, v, true); + } + if (data) { + data >>>= 0; + GET_HEAP_DATA_VIEW().setUint32(data, cbinfoValue.data, true); + } + return envObject.clearLastError(); + } + /** @__sig ipppppp */ + function napi_call_function(env, recv, func, argc, argv, result) { + var i = 0; + // eslint-disable-next-line @typescript-eslint/no-unused-vars + var v; + if (!env) + return 1 /* napi_status.napi_invalid_arg */; + // @ts-expect-error + var envObject = emnapiCtx.envStore.get(env); + envObject.checkGCAccess(); + if (!envObject.tryCatch.isEmpty()) + return envObject.setLastError(10 /* napi_status.napi_pending_exception */); + if (!envObject.canCallIntoJs()) + return envObject.setLastError(envObject.moduleApiVersion >= 10 ? 23 /* napi_status.napi_cannot_run_js */ : 10 /* napi_status.napi_pending_exception */); + envObject.clearLastError(); + try { + if (!recv) + return envObject.setLastError(1 /* napi_status.napi_invalid_arg */); + argc >>>= 0; + argv >>>= 0; + result >>>= 0; + argc = argc >>> 0; + if (argc > 0) { + if (!argv) + return envObject.setLastError(1 /* napi_status.napi_invalid_arg */); + } + var v8recv = emnapiCtx.handleStore.get(recv).value; + if (!func) + return envObject.setLastError(1 /* napi_status.napi_invalid_arg */); + var v8func = emnapiCtx.handleStore.get(func).value; + if (typeof v8func !== 'function') + return envObject.setLastError(1 /* napi_status.napi_invalid_arg */); + var args = []; + var HEAP_DATA_VIEW = new DataView(wasmMemory.buffer), GET_HEAP_DATA_VIEW = function () { return HEAP_DATA_VIEW.buffer === wasmMemory.buffer ? HEAP_DATA_VIEW : (HEAP_DATA_VIEW = new DataView(wasmMemory.buffer)); }; + for (; i < argc; i++) { + var argVal = GET_HEAP_DATA_VIEW().getUint32(argv + i * 4, true); + args.push(emnapiCtx.handleStore.get(argVal).value); + } + var ret = v8func.apply(v8recv, args); + if (result) { + // resolving v BEFORE the write matters: the store target is evaluated + // before the RHS, so an RHS running user JS could otherwise write + // through a stale heap view after a growth + v = envObject.ensureHandleId(ret); + GET_HEAP_DATA_VIEW().setUint32(result, v, true); + } + return envObject.clearLastError(); + } + catch (err) { + envObject.tryCatch.setError(err); + return envObject.setLastError(10 /* napi_status.napi_pending_exception */); + } + } + /** @__sig ippppp */ + function napi_new_instance(env, constructor, argc, argv, result) { + var i; + // eslint-disable-next-line @typescript-eslint/no-unused-vars + var v; + if (!env) + return 1 /* napi_status.napi_invalid_arg */; + // @ts-expect-error + var envObject = emnapiCtx.envStore.get(env); + envObject.checkGCAccess(); + if (!envObject.tryCatch.isEmpty()) + return envObject.setLastError(10 /* napi_status.napi_pending_exception */); + if (!envObject.canCallIntoJs()) + return envObject.setLastError(envObject.moduleApiVersion >= 10 ? 23 /* napi_status.napi_cannot_run_js */ : 10 /* napi_status.napi_pending_exception */); + envObject.clearLastError(); + try { + if (!constructor) + return envObject.setLastError(1 /* napi_status.napi_invalid_arg */); + argc >>>= 0; + argv >>>= 0; + result >>>= 0; + argc = argc >>> 0; + if (argc > 0) { + if (!argv) + return envObject.setLastError(1 /* napi_status.napi_invalid_arg */); + } + if (!result) + return envObject.setLastError(1 /* napi_status.napi_invalid_arg */); + var Ctor = emnapiCtx.handleStore.get(constructor).value; + if (typeof Ctor !== 'function') + return envObject.setLastError(1 /* napi_status.napi_invalid_arg */); + var ret = void 0; + var HEAP_DATA_VIEW = new DataView(wasmMemory.buffer), GET_HEAP_DATA_VIEW = function () { return HEAP_DATA_VIEW.buffer === wasmMemory.buffer ? HEAP_DATA_VIEW : (HEAP_DATA_VIEW = new DataView(wasmMemory.buffer)); }; + if (emnapiCtx.feature.supportReflect) { + var argList = Array(argc); + for (i = 0; i < argc; i++) { + var argVal = GET_HEAP_DATA_VIEW().getUint32(argv + i * 4, true); + argList[i] = emnapiCtx.handleStore.get(argVal).value; + } + ret = Reflect.construct(Ctor, argList, Ctor); + } + else { + var args = Array(argc + 1); + args[0] = undefined; + for (i = 0; i < argc; i++) { + var argVal = GET_HEAP_DATA_VIEW().getUint32(argv + i * 4, true); + args[i + 1] = emnapiCtx.handleStore.get(argVal).value; + } + var BoundCtor = Ctor.bind.apply(Ctor, args); + ret = new BoundCtor(); + } + if (result) { + // see napi_call_function: resolve v before the write + v = envObject.ensureHandleId(ret); + GET_HEAP_DATA_VIEW().setUint32(result, v, true); + } + return envObject.getReturnStatus(); + } + catch (err) { + envObject.tryCatch.setError(err); + return envObject.setLastError(10 /* napi_status.napi_pending_exception */); + } + } + /** @__sig ippp */ + function napi_get_new_target(env, cbinfo, result) { + if (!env) + return 1 /* napi_status.napi_invalid_arg */; + // @ts-expect-error + var envObject = emnapiCtx.envStore.get(env); + envObject.checkGCAccess(); + if (!cbinfo) + return envObject.setLastError(1 /* napi_status.napi_invalid_arg */); + if (!result) + return envObject.setLastError(1 /* napi_status.napi_invalid_arg */); + result >>>= 0; + var cbinfoValue = emnapiCtx.scopeStore.get(cbinfo).callbackInfo; + var thiz = cbinfoValue.thiz, fn = cbinfoValue.fn; + // eslint-disable-next-line @typescript-eslint/prefer-optional-chain, @typescript-eslint/no-unused-vars + var value = thiz == null || thiz.constructor == null + ? 0 + : thiz instanceof fn + ? envObject.ensureHandleId(thiz.constructor) + : 0; + var HEAP_DATA_VIEW = new DataView(wasmMemory.buffer), GET_HEAP_DATA_VIEW = function () { return HEAP_DATA_VIEW.buffer === wasmMemory.buffer ? HEAP_DATA_VIEW : (HEAP_DATA_VIEW = new DataView(wasmMemory.buffer)); }; + GET_HEAP_DATA_VIEW().setUint32(result, value, true); + return envObject.clearLastError(); + } + var functionMod = /*#__PURE__*/ Object.freeze({ + __proto__: null, + _emnapi_create_function: _emnapi_create_function, + napi_call_function: napi_call_function, + napi_create_function: napi_create_function, + napi_get_cb_info: napi_get_cb_info, + napi_get_new_target: napi_get_new_target, + napi_new_instance: napi_new_instance + }); + /** @__sig ipp */ + function napi_open_handle_scope(env, result) { + if (!env) + return 1 /* napi_status.napi_invalid_arg */; + // @ts-expect-error + var envObject = emnapiCtx.envStore.get(env); + envObject.checkGCAccess(); + if (!result) + return envObject.setLastError(1 /* napi_status.napi_invalid_arg */); + // eslint-disable-next-line @typescript-eslint/no-unused-vars + var scope = emnapiCtx.openScope(envObject); + result >>>= 0; + var HEAP_DATA_VIEW = new DataView(wasmMemory.buffer), GET_HEAP_DATA_VIEW = function () { return HEAP_DATA_VIEW.buffer === wasmMemory.buffer ? HEAP_DATA_VIEW : (HEAP_DATA_VIEW = new DataView(wasmMemory.buffer)); }; + GET_HEAP_DATA_VIEW().setUint32(result, scope.id, true); + return envObject.clearLastError(); + } + /** @__sig ipp */ + function napi_close_handle_scope(env, scope) { + if (!env) + return 1 /* napi_status.napi_invalid_arg */; + // @ts-expect-error + var envObject = emnapiCtx.envStore.get(env); + envObject.checkGCAccess(); + if (!scope) + return envObject.setLastError(1 /* napi_status.napi_invalid_arg */); + if ((envObject.openHandleScopes === 0)) { + return 13 /* napi_status.napi_handle_scope_mismatch */; + } + emnapiCtx.closeScope(envObject); + return envObject.clearLastError(); + } + /** @__sig ipp */ + function napi_open_escapable_handle_scope(env, result) { + if (!env) + return 1 /* napi_status.napi_invalid_arg */; + // @ts-expect-error + var envObject = emnapiCtx.envStore.get(env); + envObject.checkGCAccess(); + if (!result) + return envObject.setLastError(1 /* napi_status.napi_invalid_arg */); + // eslint-disable-next-line @typescript-eslint/no-unused-vars + var scope = emnapiCtx.openScope(envObject); + result >>>= 0; + var HEAP_DATA_VIEW = new DataView(wasmMemory.buffer), GET_HEAP_DATA_VIEW = function () { return HEAP_DATA_VIEW.buffer === wasmMemory.buffer ? HEAP_DATA_VIEW : (HEAP_DATA_VIEW = new DataView(wasmMemory.buffer)); }; + GET_HEAP_DATA_VIEW().setUint32(result, scope.id, true); + return envObject.clearLastError(); + } + /** @__sig ipp */ + function napi_close_escapable_handle_scope(env, scope) { + if (!env) + return 1 /* napi_status.napi_invalid_arg */; + // @ts-expect-error + var envObject = emnapiCtx.envStore.get(env); + envObject.checkGCAccess(); + if (!scope) + return envObject.setLastError(1 /* napi_status.napi_invalid_arg */); + if ((envObject.openHandleScopes === 0)) { + return 13 /* napi_status.napi_handle_scope_mismatch */; + } + emnapiCtx.closeScope(envObject); + return envObject.clearLastError(); + } + /** @__sig ipppp */ + function napi_escape_handle(env, scope, escapee, result) { + if (!env) + return 1 /* napi_status.napi_invalid_arg */; + // @ts-expect-error + var envObject = emnapiCtx.envStore.get(env); + envObject.checkGCAccess(); + if (!scope) + return envObject.setLastError(1 /* napi_status.napi_invalid_arg */); + if (!escapee) + return envObject.setLastError(1 /* napi_status.napi_invalid_arg */); + if (!result) + return envObject.setLastError(1 /* napi_status.napi_invalid_arg */); + var scopeObject = emnapiCtx.scopeStore.get(scope); + if (!scopeObject.escapeCalled()) { + escapee >>>= 0; + result >>>= 0; + var newHandle = scopeObject.escape(escapee); + // eslint-disable-next-line @typescript-eslint/no-unused-vars + var value = newHandle ? newHandle.id : 0; + var HEAP_DATA_VIEW = new DataView(wasmMemory.buffer), GET_HEAP_DATA_VIEW = function () { return HEAP_DATA_VIEW.buffer === wasmMemory.buffer ? HEAP_DATA_VIEW : (HEAP_DATA_VIEW = new DataView(wasmMemory.buffer)); }; + GET_HEAP_DATA_VIEW().setUint32(result, value, true); + return envObject.clearLastError(); + } + return envObject.setLastError(12 /* napi_status.napi_escape_called_twice */); + } + /** @__sig ippip */ + function napi_create_reference(env, value, initial_refcount, result) { + if (!env) + return 1 /* napi_status.napi_invalid_arg */; + // @ts-expect-error + var envObject = emnapiCtx.envStore.get(env); + envObject.checkGCAccess(); + if (!value) + return envObject.setLastError(1 /* napi_status.napi_invalid_arg */); + if (!result) + return envObject.setLastError(1 /* napi_status.napi_invalid_arg */); + var handle = emnapiCtx.handleStore.get(value); + if (envObject.moduleApiVersion < 10) { + if (!(handle.isObject() || handle.isFunction() || handle.isSymbol())) { + return envObject.setLastError(1 /* napi_status.napi_invalid_arg */); + } + } + // eslint-disable-next-line @typescript-eslint/no-unused-vars + var ref = emnapiCtx.createReference(envObject, handle.id, initial_refcount >>> 0, 1 /* ReferenceOwnership.kUserland */); + result >>>= 0; + var HEAP_DATA_VIEW = new DataView(wasmMemory.buffer), GET_HEAP_DATA_VIEW = function () { return HEAP_DATA_VIEW.buffer === wasmMemory.buffer ? HEAP_DATA_VIEW : (HEAP_DATA_VIEW = new DataView(wasmMemory.buffer)); }; + GET_HEAP_DATA_VIEW().setUint32(result, ref.id, true); + return envObject.clearLastError(); + } + /** @__sig ipp */ + function napi_delete_reference(env, ref) { + if (!env) + return 1 /* napi_status.napi_invalid_arg */; + var envObject = emnapiCtx.envStore.get(env); + if (!ref) + return envObject.setLastError(1 /* napi_status.napi_invalid_arg */); + emnapiCtx.refStore.get(ref).dispose(); + return envObject.clearLastError(); + } + /** @__sig ippp */ + function napi_reference_ref(env, ref, result) { + if (!env) + return 1 /* napi_status.napi_invalid_arg */; + // @ts-expect-error + var envObject = emnapiCtx.envStore.get(env); + envObject.checkGCAccess(); + if (!ref) + return envObject.setLastError(1 /* napi_status.napi_invalid_arg */); + // eslint-disable-next-line @typescript-eslint/no-unused-vars + var count = emnapiCtx.refStore.get(ref).ref(); + if (result) { + result >>>= 0; + var HEAP_DATA_VIEW = new DataView(wasmMemory.buffer), GET_HEAP_DATA_VIEW = function () { return HEAP_DATA_VIEW.buffer === wasmMemory.buffer ? HEAP_DATA_VIEW : (HEAP_DATA_VIEW = new DataView(wasmMemory.buffer)); }; + GET_HEAP_DATA_VIEW().setUint32(result, count, true); + } + return envObject.clearLastError(); + } + /** @__sig ippp */ + function napi_reference_unref(env, ref, result) { + if (!env) + return 1 /* napi_status.napi_invalid_arg */; + // @ts-expect-error + var envObject = emnapiCtx.envStore.get(env); + envObject.checkGCAccess(); + if (!ref) + return envObject.setLastError(1 /* napi_status.napi_invalid_arg */); + var reference = emnapiCtx.refStore.get(ref); + var refcount = reference.refcount(); + if (refcount === 0) { + return envObject.setLastError(9 /* napi_status.napi_generic_failure */); + } + // eslint-disable-next-line @typescript-eslint/no-unused-vars + var count = reference.unref(); + if (result) { + result >>>= 0; + var HEAP_DATA_VIEW = new DataView(wasmMemory.buffer), GET_HEAP_DATA_VIEW = function () { return HEAP_DATA_VIEW.buffer === wasmMemory.buffer ? HEAP_DATA_VIEW : (HEAP_DATA_VIEW = new DataView(wasmMemory.buffer)); }; + GET_HEAP_DATA_VIEW().setUint32(result, count, true); + } + return envObject.clearLastError(); + } + /** @__sig ippp */ + function napi_get_reference_value(env, ref, result) { + if (!env) + return 1 /* napi_status.napi_invalid_arg */; + // @ts-expect-error + var envObject = emnapiCtx.envStore.get(env); + envObject.checkGCAccess(); + if (!ref) + return envObject.setLastError(1 /* napi_status.napi_invalid_arg */); + if (!result) + return envObject.setLastError(1 /* napi_status.napi_invalid_arg */); + var reference = emnapiCtx.refStore.get(ref); + // eslint-disable-next-line @typescript-eslint/no-unused-vars + var handleId = reference.get(envObject); + result >>>= 0; + var HEAP_DATA_VIEW = new DataView(wasmMemory.buffer), GET_HEAP_DATA_VIEW = function () { return HEAP_DATA_VIEW.buffer === wasmMemory.buffer ? HEAP_DATA_VIEW : (HEAP_DATA_VIEW = new DataView(wasmMemory.buffer)); }; + GET_HEAP_DATA_VIEW().setUint32(result, handleId, true); + return envObject.clearLastError(); + } + /** @__sig ippp */ + function napi_add_env_cleanup_hook(env, fun, arg) { + if (!env) + return 1 /* napi_status.napi_invalid_arg */; + var envObject = emnapiCtx.envStore.get(env); + if (!fun) + return envObject.setLastError(1 /* napi_status.napi_invalid_arg */); + fun >>>= 0; + arg >>>= 0; + emnapiCtx.addCleanupHook(envObject, fun, arg); + return 0 /* napi_status.napi_ok */; + } + /** @__sig ippp */ + function napi_remove_env_cleanup_hook(env, fun, arg) { + if (!env) + return 1 /* napi_status.napi_invalid_arg */; + var envObject = emnapiCtx.envStore.get(env); + if (!fun) + return envObject.setLastError(1 /* napi_status.napi_invalid_arg */); + fun >>>= 0; + arg >>>= 0; + emnapiCtx.removeCleanupHook(envObject, fun, arg); + return 0 /* napi_status.napi_ok */; + } + /** @__sig vp */ + function _emnapi_env_ref(env) { + var envObject = emnapiCtx.envStore.get(env); + envObject.ref(); + } + /** @__sig vp */ + function _emnapi_env_unref(env) { + var envObject = emnapiCtx.envStore.get(env); + envObject.unref(); + } + var lifeMod = /*#__PURE__*/ Object.freeze({ + __proto__: null, + _emnapi_env_ref: _emnapi_env_ref, + _emnapi_env_unref: _emnapi_env_unref, + napi_add_env_cleanup_hook: napi_add_env_cleanup_hook, + napi_close_escapable_handle_scope: napi_close_escapable_handle_scope, + napi_close_handle_scope: napi_close_handle_scope, + napi_create_reference: napi_create_reference, + napi_delete_reference: napi_delete_reference, + napi_escape_handle: napi_escape_handle, + napi_get_reference_value: napi_get_reference_value, + napi_open_escapable_handle_scope: napi_open_escapable_handle_scope, + napi_open_handle_scope: napi_open_handle_scope, + napi_reference_ref: napi_reference_ref, + napi_reference_unref: napi_reference_unref, + napi_remove_env_cleanup_hook: napi_remove_env_cleanup_hook + }); + /** @__sig ippi */ + function _emnapi_get_filename(env, buf, len) { + var envObject = emnapiCtx.envStore.get(env); + var filename = envObject.filename; + if (!buf) { + return emnapiString.lengthBytesUTF8(filename); + } + return emnapiString.stringToUTF8(filename, buf, len); + } + var miscellaneousMod = /*#__PURE__*/ Object.freeze({ + __proto__: null, + _emnapi_get_filename: _emnapi_get_filename + }); + /** @__sig ippp */ + function napi_create_promise(env, deferred, promise) { + // eslint-disable-next-line @typescript-eslint/no-unused-vars + var deferredObjectId, value; + if (!env) + return 1 /* napi_status.napi_invalid_arg */; + // @ts-expect-error + var envObject = emnapiCtx.envStore.get(env); + envObject.checkGCAccess(); + if (!envObject.tryCatch.isEmpty()) + return envObject.setLastError(10 /* napi_status.napi_pending_exception */); + if (!envObject.canCallIntoJs()) + return envObject.setLastError(envObject.moduleApiVersion >= 10 ? 23 /* napi_status.napi_cannot_run_js */ : 10 /* napi_status.napi_pending_exception */); + envObject.clearLastError(); + try { + if (!deferred) + return envObject.setLastError(1 /* napi_status.napi_invalid_arg */); + if (!promise) + return envObject.setLastError(1 /* napi_status.napi_invalid_arg */); + var HEAP_DATA_VIEW = new DataView(wasmMemory.buffer), GET_HEAP_DATA_VIEW = function () { return HEAP_DATA_VIEW.buffer === wasmMemory.buffer ? HEAP_DATA_VIEW : (HEAP_DATA_VIEW = new DataView(wasmMemory.buffer)); }; + var p = new Promise(function (resolve, reject) { + var deferredObject = emnapiCtx.createDeferred({ resolve: resolve, reject: reject }); + deferredObjectId = deferredObject.id; + deferred >>>= 0; + GET_HEAP_DATA_VIEW().setUint32(deferred, deferredObjectId, true); + }); + promise >>>= 0; + // eslint-disable-next-line @typescript-eslint/no-unused-vars + value = emnapiCtx.addToCurrentScope(p).id; + GET_HEAP_DATA_VIEW().setUint32(promise, value, true); + return envObject.getReturnStatus(); + } + catch (err) { + envObject.tryCatch.setError(err); + return envObject.setLastError(10 /* napi_status.napi_pending_exception */); + } + } + /** @__sig ippp */ + function napi_resolve_deferred(env, deferred, resolution) { + if (!env) + return 1 /* napi_status.napi_invalid_arg */; + // @ts-expect-error + var envObject = emnapiCtx.envStore.get(env); + envObject.checkGCAccess(); + if (!envObject.tryCatch.isEmpty()) + return envObject.setLastError(10 /* napi_status.napi_pending_exception */); + if (!envObject.canCallIntoJs()) + return envObject.setLastError(envObject.moduleApiVersion >= 10 ? 23 /* napi_status.napi_cannot_run_js */ : 10 /* napi_status.napi_pending_exception */); + envObject.clearLastError(); + try { + if (!deferred) + return envObject.setLastError(1 /* napi_status.napi_invalid_arg */); + if (!resolution) + return envObject.setLastError(1 /* napi_status.napi_invalid_arg */); + var deferredObject = emnapiCtx.deferredStore.get(deferred); + deferredObject.resolve(emnapiCtx.handleStore.get(resolution).value); + return envObject.getReturnStatus(); + } + catch (err) { + envObject.tryCatch.setError(err); + return envObject.setLastError(10 /* napi_status.napi_pending_exception */); + } + } + /** @__sig ippp */ + function napi_reject_deferred(env, deferred, resolution) { + if (!env) + return 1 /* napi_status.napi_invalid_arg */; + // @ts-expect-error + var envObject = emnapiCtx.envStore.get(env); + envObject.checkGCAccess(); + if (!envObject.tryCatch.isEmpty()) + return envObject.setLastError(10 /* napi_status.napi_pending_exception */); + if (!envObject.canCallIntoJs()) + return envObject.setLastError(envObject.moduleApiVersion >= 10 ? 23 /* napi_status.napi_cannot_run_js */ : 10 /* napi_status.napi_pending_exception */); + envObject.clearLastError(); + try { + if (!deferred) + return envObject.setLastError(1 /* napi_status.napi_invalid_arg */); + if (!resolution) + return envObject.setLastError(1 /* napi_status.napi_invalid_arg */); + var deferredObject = emnapiCtx.deferredStore.get(deferred); + deferredObject.reject(emnapiCtx.handleStore.get(resolution).value); + return envObject.getReturnStatus(); + } + catch (err) { + envObject.tryCatch.setError(err); + return envObject.setLastError(10 /* napi_status.napi_pending_exception */); + } + } + /** @__sig ippp */ + function napi_is_promise(env, value, is_promise) { + if (!env) + return 1 /* napi_status.napi_invalid_arg */; + // @ts-expect-error + var envObject = emnapiCtx.envStore.get(env); + envObject.checkGCAccess(); + if (!value) + return envObject.setLastError(1 /* napi_status.napi_invalid_arg */); + if (!is_promise) + return envObject.setLastError(1 /* napi_status.napi_invalid_arg */); + var h = emnapiCtx.handleStore.get(value); + is_promise >>>= 0; + // eslint-disable-next-line @typescript-eslint/no-unused-vars + var r = h.isPromise() ? 1 : 0; + var HEAP_DATA_VIEW = new DataView(wasmMemory.buffer), GET_HEAP_DATA_VIEW = function () { return HEAP_DATA_VIEW.buffer === wasmMemory.buffer ? HEAP_DATA_VIEW : (HEAP_DATA_VIEW = new DataView(wasmMemory.buffer)); }; + GET_HEAP_DATA_VIEW().setInt8(is_promise, r, true); + return envObject.clearLastError(); + } + var promiseMod = /*#__PURE__*/ Object.freeze({ + __proto__: null, + napi_create_promise: napi_create_promise, + napi_is_promise: napi_is_promise, + napi_reject_deferred: napi_reject_deferred, + napi_resolve_deferred: napi_resolve_deferred + }); + /** @__sig ippiiip */ + function napi_get_all_property_names(env, object, key_mode, key_filter, key_conversion, result) { + // eslint-disable-next-line @typescript-eslint/no-unused-vars + var value; + if (!env) + return 1 /* napi_status.napi_invalid_arg */; + // @ts-expect-error + var envObject = emnapiCtx.envStore.get(env); + envObject.checkGCAccess(); + if (!envObject.tryCatch.isEmpty()) + return envObject.setLastError(10 /* napi_status.napi_pending_exception */); + if (!envObject.canCallIntoJs()) + return envObject.setLastError(envObject.moduleApiVersion >= 10 ? 23 /* napi_status.napi_cannot_run_js */ : 10 /* napi_status.napi_pending_exception */); + envObject.clearLastError(); + try { + if (!result) + return envObject.setLastError(1 /* napi_status.napi_invalid_arg */); + if (!object) + return envObject.setLastError(1 /* napi_status.napi_invalid_arg */); + var h = emnapiCtx.handleStore.get(object); + if (h.value == null) { + throw new TypeError('Cannot convert undefined or null to object'); + } + var obj = void 0; + try { + obj = h.isObject() || h.isFunction() ? h.value : Object(h.value); + } + catch (_) { + return envObject.setLastError(2 /* napi_status.napi_object_expected */); + } + if (key_mode !== 0 /* napi_key_collection_mode.napi_key_include_prototypes */ && key_mode !== 1 /* napi_key_collection_mode.napi_key_own_only */) { + return envObject.setLastError(1 /* napi_status.napi_invalid_arg */); + } + if (key_conversion !== 0 /* napi_key_conversion.napi_key_keep_numbers */ && key_conversion !== 1 /* napi_key_conversion.napi_key_numbers_to_strings */) { + return envObject.setLastError(1 /* napi_status.napi_invalid_arg */); + } + var props = []; + var names = void 0; + var symbols = void 0; + var i = void 0; + var own = true; + var integerIndiceRegex = /^(0|[1-9][0-9]*)$/; + do { + names = Object.getOwnPropertyNames(obj); + symbols = Object.getOwnPropertySymbols(obj); + for (i = 0; i < names.length; i++) { + props.push({ + name: integerIndiceRegex.test(names[i]) ? Number(names[i]) : names[i], + desc: Object.getOwnPropertyDescriptor(obj, names[i]), + own: own + }); + } + for (i = 0; i < symbols.length; i++) { + props.push({ + name: symbols[i], + desc: Object.getOwnPropertyDescriptor(obj, symbols[i]), + own: own + }); + } + if (key_mode === 1 /* napi_key_collection_mode.napi_key_own_only */) { + break; + } + obj = Object.getPrototypeOf(obj); + own = false; + } while (obj); + var ret = []; + var addName = function (ret, name, key_filter, conversion_mode) { + if (ret.indexOf(name) !== -1) + return; + if (conversion_mode === 0 /* napi_key_conversion.napi_key_keep_numbers */) { + ret.push(name); + } + else if (conversion_mode === 1 /* napi_key_conversion.napi_key_numbers_to_strings */) { + var realName = typeof name === 'number' ? String(name) : name; + if (typeof realName === 'string') { + if (!(key_filter & 8 /* napi_key_filter.napi_key_skip_strings */)) { + ret.push(realName); + } + } + else { + ret.push(realName); + } + } + }; + for (i = 0; i < props.length; i++) { + var prop = props[i]; + var name_1 = prop.name; + var desc = prop.desc; + if (key_filter === 0 /* napi_key_filter.napi_key_all_properties */) { + addName(ret, name_1, key_filter, key_conversion); + } + else { + if (key_filter & 8 /* napi_key_filter.napi_key_skip_strings */ && typeof name_1 === 'string') { + continue; + } + if (key_filter & 16 /* napi_key_filter.napi_key_skip_symbols */ && typeof name_1 === 'symbol') { + continue; + } + var shouldAdd = true; + switch (key_filter & 7) { + case 1 /* napi_key_filter.napi_key_writable */: { + shouldAdd = Boolean(desc.writable); + break; + } + case 2 /* napi_key_filter.napi_key_enumerable */: { + shouldAdd = Boolean(desc.enumerable); + break; + } + case (1 /* napi_key_filter.napi_key_writable */ | 2 /* napi_key_filter.napi_key_enumerable */): { + shouldAdd = Boolean(desc.writable && desc.enumerable); + break; + } + case 4 /* napi_key_filter.napi_key_configurable */: { + shouldAdd = Boolean(desc.configurable); + break; + } + case (4 /* napi_key_filter.napi_key_configurable */ | 1 /* napi_key_filter.napi_key_writable */): { + shouldAdd = Boolean(desc.configurable && desc.writable); + break; + } + case (4 /* napi_key_filter.napi_key_configurable */ | 2 /* napi_key_filter.napi_key_enumerable */): { + shouldAdd = Boolean(desc.configurable && desc.enumerable); + break; + } + case (4 /* napi_key_filter.napi_key_configurable */ | 2 /* napi_key_filter.napi_key_enumerable */ | 1 /* napi_key_filter.napi_key_writable */): { + shouldAdd = Boolean(desc.configurable && desc.enumerable && desc.writable); + break; + } + } + if (shouldAdd) { + addName(ret, name_1, key_filter, key_conversion); + } + } + } + result >>>= 0; + // eslint-disable-next-line @typescript-eslint/no-unused-vars + value = emnapiCtx.addToCurrentScope(ret).id; + var HEAP_DATA_VIEW = new DataView(wasmMemory.buffer), GET_HEAP_DATA_VIEW = function () { return HEAP_DATA_VIEW.buffer === wasmMemory.buffer ? HEAP_DATA_VIEW : (HEAP_DATA_VIEW = new DataView(wasmMemory.buffer)); }; + GET_HEAP_DATA_VIEW().setUint32(result, value, true); + return envObject.getReturnStatus(); + } + catch (err) { + envObject.tryCatch.setError(err); + return envObject.setLastError(10 /* napi_status.napi_pending_exception */); + } + } + /** @__sig ippp */ + function napi_get_property_names(env, object, result) { + return napi_get_all_property_names(env, object, 0 /* napi_key_collection_mode.napi_key_include_prototypes */, 2 /* napi_key_filter.napi_key_enumerable */ | 16 /* napi_key_filter.napi_key_skip_symbols */, 1 /* napi_key_conversion.napi_key_numbers_to_strings */, result); + } + /** @__sig ipppp */ + function napi_set_property(env, object, key, value) { + if (!env) + return 1 /* napi_status.napi_invalid_arg */; + // @ts-expect-error + var envObject = emnapiCtx.envStore.get(env); + envObject.checkGCAccess(); + if (!envObject.tryCatch.isEmpty()) + return envObject.setLastError(10 /* napi_status.napi_pending_exception */); + if (!envObject.canCallIntoJs()) + return envObject.setLastError(envObject.moduleApiVersion >= 10 ? 23 /* napi_status.napi_cannot_run_js */ : 10 /* napi_status.napi_pending_exception */); + envObject.clearLastError(); + try { + if (!key) + return envObject.setLastError(1 /* napi_status.napi_invalid_arg */); + if (!value) + return envObject.setLastError(1 /* napi_status.napi_invalid_arg */); + if (!object) + return envObject.setLastError(1 /* napi_status.napi_invalid_arg */); + var h = emnapiCtx.handleStore.get(object); + if (!(h.isObject() || h.isFunction())) { + return envObject.setLastError(2 /* napi_status.napi_object_expected */); + } + h.value[emnapiCtx.handleStore.get(key).value] = emnapiCtx.handleStore.get(value).value; + return envObject.getReturnStatus(); + } + catch (err) { + envObject.tryCatch.setError(err); + return envObject.setLastError(10 /* napi_status.napi_pending_exception */); + } + } + /** @__sig ipppp */ + function napi_has_property(env, object, key, result) { + // eslint-disable-next-line @typescript-eslint/no-unused-vars + var r; + if (!env) + return 1 /* napi_status.napi_invalid_arg */; + // @ts-expect-error + var envObject = emnapiCtx.envStore.get(env); + envObject.checkGCAccess(); + if (!envObject.tryCatch.isEmpty()) + return envObject.setLastError(10 /* napi_status.napi_pending_exception */); + if (!envObject.canCallIntoJs()) + return envObject.setLastError(envObject.moduleApiVersion >= 10 ? 23 /* napi_status.napi_cannot_run_js */ : 10 /* napi_status.napi_pending_exception */); + envObject.clearLastError(); + try { + if (!key) + return envObject.setLastError(1 /* napi_status.napi_invalid_arg */); + if (!result) + return envObject.setLastError(1 /* napi_status.napi_invalid_arg */); + if (!object) + return envObject.setLastError(1 /* napi_status.napi_invalid_arg */); + var h = emnapiCtx.handleStore.get(object); + if (h.value == null) { + throw new TypeError('Cannot convert undefined or null to object'); + } + var v = void 0; + try { + v = h.isObject() || h.isFunction() ? h.value : Object(h.value); + } + catch (_) { + return envObject.setLastError(2 /* napi_status.napi_object_expected */); + } + result >>>= 0; + r = (emnapiCtx.handleStore.get(key).value in v) ? 1 : 0; + var HEAP_DATA_VIEW = new DataView(wasmMemory.buffer), GET_HEAP_DATA_VIEW = function () { return HEAP_DATA_VIEW.buffer === wasmMemory.buffer ? HEAP_DATA_VIEW : (HEAP_DATA_VIEW = new DataView(wasmMemory.buffer)); }; + GET_HEAP_DATA_VIEW().setInt8(result, r, true); + return envObject.getReturnStatus(); + } + catch (err) { + envObject.tryCatch.setError(err); + return envObject.setLastError(10 /* napi_status.napi_pending_exception */); + } + } + /** @__sig ipppp */ + function napi_get_property(env, object, key, result) { + // eslint-disable-next-line @typescript-eslint/no-unused-vars + var value; + if (!env) + return 1 /* napi_status.napi_invalid_arg */; + // @ts-expect-error + var envObject = emnapiCtx.envStore.get(env); + envObject.checkGCAccess(); + if (!envObject.tryCatch.isEmpty()) + return envObject.setLastError(10 /* napi_status.napi_pending_exception */); + if (!envObject.canCallIntoJs()) + return envObject.setLastError(envObject.moduleApiVersion >= 10 ? 23 /* napi_status.napi_cannot_run_js */ : 10 /* napi_status.napi_pending_exception */); + envObject.clearLastError(); + try { + if (!key) + return envObject.setLastError(1 /* napi_status.napi_invalid_arg */); + if (!result) + return envObject.setLastError(1 /* napi_status.napi_invalid_arg */); + if (!object) + return envObject.setLastError(1 /* napi_status.napi_invalid_arg */); + var h = emnapiCtx.handleStore.get(object); + if (h.value == null) { + throw new TypeError('Cannot convert undefined or null to object'); + } + var v = void 0; + try { + v = h.isObject() || h.isFunction() ? h.value : Object(h.value); + } + catch (_) { + return envObject.setLastError(2 /* napi_status.napi_object_expected */); + } + result >>>= 0; + // eslint-disable-next-line @typescript-eslint/no-unused-vars + value = envObject.ensureHandleId(v[emnapiCtx.handleStore.get(key).value]); + var HEAP_DATA_VIEW = new DataView(wasmMemory.buffer), GET_HEAP_DATA_VIEW = function () { return HEAP_DATA_VIEW.buffer === wasmMemory.buffer ? HEAP_DATA_VIEW : (HEAP_DATA_VIEW = new DataView(wasmMemory.buffer)); }; + GET_HEAP_DATA_VIEW().setUint32(result, value, true); + return envObject.getReturnStatus(); + } + catch (err) { + envObject.tryCatch.setError(err); + return envObject.setLastError(10 /* napi_status.napi_pending_exception */); + } + } + /** @__sig ipppp */ + function napi_delete_property(env, object, key, result) { + // eslint-disable-next-line @typescript-eslint/no-unused-vars + var r; + if (!env) + return 1 /* napi_status.napi_invalid_arg */; + // @ts-expect-error + var envObject = emnapiCtx.envStore.get(env); + envObject.checkGCAccess(); + if (!envObject.tryCatch.isEmpty()) + return envObject.setLastError(10 /* napi_status.napi_pending_exception */); + if (!envObject.canCallIntoJs()) + return envObject.setLastError(envObject.moduleApiVersion >= 10 ? 23 /* napi_status.napi_cannot_run_js */ : 10 /* napi_status.napi_pending_exception */); + envObject.clearLastError(); + try { + if (!key) + return envObject.setLastError(1 /* napi_status.napi_invalid_arg */); + if (!object) + return envObject.setLastError(1 /* napi_status.napi_invalid_arg */); + var h = emnapiCtx.handleStore.get(object); + if (!(h.isObject() || h.isFunction())) { + return envObject.setLastError(2 /* napi_status.napi_object_expected */); + } + var propertyKey = emnapiCtx.handleStore.get(key).value; + if (emnapiCtx.feature.supportReflect) { + r = Reflect.deleteProperty(h.value, propertyKey); + } + else { + try { + r = delete h.value[propertyKey]; + } + catch (_) { + r = false; + } + } + if (result) { + result >>>= 0; + var HEAP_DATA_VIEW = new DataView(wasmMemory.buffer), GET_HEAP_DATA_VIEW = function () { return HEAP_DATA_VIEW.buffer === wasmMemory.buffer ? HEAP_DATA_VIEW : (HEAP_DATA_VIEW = new DataView(wasmMemory.buffer)); }; + GET_HEAP_DATA_VIEW().setInt8(result, r ? 1 : 0, true); + } + return envObject.getReturnStatus(); + } + catch (err) { + envObject.tryCatch.setError(err); + return envObject.setLastError(10 /* napi_status.napi_pending_exception */); + } + } + /** @__sig ipppp */ + function napi_has_own_property(env, object, key, result) { + // eslint-disable-next-line @typescript-eslint/no-unused-vars + var r; + if (!env) + return 1 /* napi_status.napi_invalid_arg */; + // @ts-expect-error + var envObject = emnapiCtx.envStore.get(env); + envObject.checkGCAccess(); + if (!envObject.tryCatch.isEmpty()) + return envObject.setLastError(10 /* napi_status.napi_pending_exception */); + if (!envObject.canCallIntoJs()) + return envObject.setLastError(envObject.moduleApiVersion >= 10 ? 23 /* napi_status.napi_cannot_run_js */ : 10 /* napi_status.napi_pending_exception */); + envObject.clearLastError(); + try { + if (!key) + return envObject.setLastError(1 /* napi_status.napi_invalid_arg */); + if (!result) + return envObject.setLastError(1 /* napi_status.napi_invalid_arg */); + if (!object) + return envObject.setLastError(1 /* napi_status.napi_invalid_arg */); + var h = emnapiCtx.handleStore.get(object); + if (h.value == null) { + throw new TypeError('Cannot convert undefined or null to object'); + } + var v = void 0; + try { + v = h.isObject() || h.isFunction() ? h.value : Object(h.value); + } + catch (_) { + return envObject.setLastError(2 /* napi_status.napi_object_expected */); + } + var prop = emnapiCtx.handleStore.get(key).value; + if (typeof prop !== 'string' && typeof prop !== 'symbol') { + return envObject.setLastError(4 /* napi_status.napi_name_expected */); + } + r = Object.prototype.hasOwnProperty.call(v, emnapiCtx.handleStore.get(key).value); + result >>>= 0; + var HEAP_DATA_VIEW = new DataView(wasmMemory.buffer), GET_HEAP_DATA_VIEW = function () { return HEAP_DATA_VIEW.buffer === wasmMemory.buffer ? HEAP_DATA_VIEW : (HEAP_DATA_VIEW = new DataView(wasmMemory.buffer)); }; + GET_HEAP_DATA_VIEW().setInt8(result, r ? 1 : 0, true); + return envObject.getReturnStatus(); + } + catch (err) { + envObject.tryCatch.setError(err); + return envObject.setLastError(10 /* napi_status.napi_pending_exception */); + } + } + /** @__sig ipppp */ + function napi_set_named_property(env, object, cname, value) { + if (!env) + return 1 /* napi_status.napi_invalid_arg */; + // @ts-expect-error + var envObject = emnapiCtx.envStore.get(env); + envObject.checkGCAccess(); + if (!envObject.tryCatch.isEmpty()) + return envObject.setLastError(10 /* napi_status.napi_pending_exception */); + if (!envObject.canCallIntoJs()) + return envObject.setLastError(envObject.moduleApiVersion >= 10 ? 23 /* napi_status.napi_cannot_run_js */ : 10 /* napi_status.napi_pending_exception */); + envObject.clearLastError(); + try { + if (!value) + return envObject.setLastError(1 /* napi_status.napi_invalid_arg */); + if (!object) + return envObject.setLastError(1 /* napi_status.napi_invalid_arg */); + var h = emnapiCtx.handleStore.get(object); + if (!(h.isObject() || h.isFunction())) { + return envObject.setLastError(2 /* napi_status.napi_object_expected */); + } + if (!cname) { + return envObject.setLastError(1 /* napi_status.napi_invalid_arg */); + } + cname >>>= 0; + emnapiCtx.handleStore.get(object).value[emnapiString.UTF8ToString(cname, -1)] = emnapiCtx.handleStore.get(value).value; + return envObject.getReturnStatus(); + } + catch (err) { + envObject.tryCatch.setError(err); + return envObject.setLastError(10 /* napi_status.napi_pending_exception */); + } + } + /** @__sig ipppp */ + function napi_has_named_property(env, object, utf8name, result) { + // eslint-disable-next-line @typescript-eslint/no-unused-vars + var r; + if (!env) + return 1 /* napi_status.napi_invalid_arg */; + // @ts-expect-error + var envObject = emnapiCtx.envStore.get(env); + envObject.checkGCAccess(); + if (!envObject.tryCatch.isEmpty()) + return envObject.setLastError(10 /* napi_status.napi_pending_exception */); + if (!envObject.canCallIntoJs()) + return envObject.setLastError(envObject.moduleApiVersion >= 10 ? 23 /* napi_status.napi_cannot_run_js */ : 10 /* napi_status.napi_pending_exception */); + envObject.clearLastError(); + try { + if (!result) + return envObject.setLastError(1 /* napi_status.napi_invalid_arg */); + if (!object) + return envObject.setLastError(1 /* napi_status.napi_invalid_arg */); + if (!utf8name) { + return envObject.setLastError(1 /* napi_status.napi_invalid_arg */); + } + var h = emnapiCtx.handleStore.get(object); + if (h.value == null) { + throw new TypeError('Cannot convert undefined or null to object'); + } + var v = void 0; + try { + v = h.isObject() || h.isFunction() ? h.value : Object(h.value); + } + catch (_) { + return envObject.setLastError(2 /* napi_status.napi_object_expected */); + } + utf8name >>>= 0; + result >>>= 0; + r = emnapiString.UTF8ToString(utf8name, -1) in v; + var HEAP_DATA_VIEW = new DataView(wasmMemory.buffer), GET_HEAP_DATA_VIEW = function () { return HEAP_DATA_VIEW.buffer === wasmMemory.buffer ? HEAP_DATA_VIEW : (HEAP_DATA_VIEW = new DataView(wasmMemory.buffer)); }; + GET_HEAP_DATA_VIEW().setInt8(result, r ? 1 : 0, true); + return envObject.getReturnStatus(); + } + catch (err) { + envObject.tryCatch.setError(err); + return envObject.setLastError(10 /* napi_status.napi_pending_exception */); + } + } + /** @__sig ipppp */ + function napi_get_named_property(env, object, utf8name, result) { + // eslint-disable-next-line @typescript-eslint/no-unused-vars + var value; + if (!env) + return 1 /* napi_status.napi_invalid_arg */; + // @ts-expect-error + var envObject = emnapiCtx.envStore.get(env); + envObject.checkGCAccess(); + if (!envObject.tryCatch.isEmpty()) + return envObject.setLastError(10 /* napi_status.napi_pending_exception */); + if (!envObject.canCallIntoJs()) + return envObject.setLastError(envObject.moduleApiVersion >= 10 ? 23 /* napi_status.napi_cannot_run_js */ : 10 /* napi_status.napi_pending_exception */); + envObject.clearLastError(); + try { + if (!result) + return envObject.setLastError(1 /* napi_status.napi_invalid_arg */); + if (!object) + return envObject.setLastError(1 /* napi_status.napi_invalid_arg */); + if (!utf8name) { + return envObject.setLastError(1 /* napi_status.napi_invalid_arg */); + } + var h = emnapiCtx.handleStore.get(object); + if (h.value == null) { + throw new TypeError('Cannot convert undefined or null to object'); + } + var v = void 0; + try { + v = h.isObject() || h.isFunction() ? h.value : Object(h.value); + } + catch (_) { + return envObject.setLastError(2 /* napi_status.napi_object_expected */); + } + utf8name >>>= 0; + result >>>= 0; + // eslint-disable-next-line @typescript-eslint/no-unused-vars + value = envObject.ensureHandleId(v[emnapiString.UTF8ToString(utf8name, -1)]); + var HEAP_DATA_VIEW = new DataView(wasmMemory.buffer), GET_HEAP_DATA_VIEW = function () { return HEAP_DATA_VIEW.buffer === wasmMemory.buffer ? HEAP_DATA_VIEW : (HEAP_DATA_VIEW = new DataView(wasmMemory.buffer)); }; + GET_HEAP_DATA_VIEW().setUint32(result, value, true); + return envObject.getReturnStatus(); + } + catch (err) { + envObject.tryCatch.setError(err); + return envObject.setLastError(10 /* napi_status.napi_pending_exception */); + } + } + /** @__sig ippip */ + function napi_set_element(env, object, index, value) { + if (!env) + return 1 /* napi_status.napi_invalid_arg */; + // @ts-expect-error + var envObject = emnapiCtx.envStore.get(env); + envObject.checkGCAccess(); + if (!envObject.tryCatch.isEmpty()) + return envObject.setLastError(10 /* napi_status.napi_pending_exception */); + if (!envObject.canCallIntoJs()) + return envObject.setLastError(envObject.moduleApiVersion >= 10 ? 23 /* napi_status.napi_cannot_run_js */ : 10 /* napi_status.napi_pending_exception */); + envObject.clearLastError(); + try { + if (!value) + return envObject.setLastError(1 /* napi_status.napi_invalid_arg */); + if (!object) + return envObject.setLastError(1 /* napi_status.napi_invalid_arg */); + var h = emnapiCtx.handleStore.get(object); + if (!(h.isObject() || h.isFunction())) { + return envObject.setLastError(2 /* napi_status.napi_object_expected */); + } + h.value[index >>> 0] = emnapiCtx.handleStore.get(value).value; + return envObject.getReturnStatus(); + } + catch (err) { + envObject.tryCatch.setError(err); + return envObject.setLastError(10 /* napi_status.napi_pending_exception */); + } + } + /** @__sig ippip */ + function napi_has_element(env, object, index, result) { + // eslint-disable-next-line @typescript-eslint/no-unused-vars + var r; + if (!env) + return 1 /* napi_status.napi_invalid_arg */; + // @ts-expect-error + var envObject = emnapiCtx.envStore.get(env); + envObject.checkGCAccess(); + if (!envObject.tryCatch.isEmpty()) + return envObject.setLastError(10 /* napi_status.napi_pending_exception */); + if (!envObject.canCallIntoJs()) + return envObject.setLastError(envObject.moduleApiVersion >= 10 ? 23 /* napi_status.napi_cannot_run_js */ : 10 /* napi_status.napi_pending_exception */); + envObject.clearLastError(); + try { + if (!result) + return envObject.setLastError(1 /* napi_status.napi_invalid_arg */); + if (!object) + return envObject.setLastError(1 /* napi_status.napi_invalid_arg */); + var h = emnapiCtx.handleStore.get(object); + if (h.value == null) { + throw new TypeError('Cannot convert undefined or null to object'); + } + var v = void 0; + try { + v = h.isObject() || h.isFunction() ? h.value : Object(h.value); + } + catch (_) { + return envObject.setLastError(2 /* napi_status.napi_object_expected */); + } + result >>>= 0; + r = ((index >>> 0) in v) ? 1 : 0; + var HEAP_DATA_VIEW = new DataView(wasmMemory.buffer), GET_HEAP_DATA_VIEW = function () { return HEAP_DATA_VIEW.buffer === wasmMemory.buffer ? HEAP_DATA_VIEW : (HEAP_DATA_VIEW = new DataView(wasmMemory.buffer)); }; + GET_HEAP_DATA_VIEW().setInt8(result, r, true); + return envObject.getReturnStatus(); + } + catch (err) { + envObject.tryCatch.setError(err); + return envObject.setLastError(10 /* napi_status.napi_pending_exception */); + } + } + /** @__sig ippip */ + function napi_get_element(env, object, index, result) { + // eslint-disable-next-line @typescript-eslint/no-unused-vars + var value; + if (!env) + return 1 /* napi_status.napi_invalid_arg */; + // @ts-expect-error + var envObject = emnapiCtx.envStore.get(env); + envObject.checkGCAccess(); + if (!envObject.tryCatch.isEmpty()) + return envObject.setLastError(10 /* napi_status.napi_pending_exception */); + if (!envObject.canCallIntoJs()) + return envObject.setLastError(envObject.moduleApiVersion >= 10 ? 23 /* napi_status.napi_cannot_run_js */ : 10 /* napi_status.napi_pending_exception */); + envObject.clearLastError(); + try { + if (!result) + return envObject.setLastError(1 /* napi_status.napi_invalid_arg */); + if (!object) + return envObject.setLastError(1 /* napi_status.napi_invalid_arg */); + var h = emnapiCtx.handleStore.get(object); + if (h.value == null) { + throw new TypeError('Cannot convert undefined or null to object'); + } + var v = void 0; + try { + v = h.isObject() || h.isFunction() ? h.value : Object(h.value); + } + catch (_) { + return envObject.setLastError(2 /* napi_status.napi_object_expected */); + } + result >>>= 0; + // eslint-disable-next-line @typescript-eslint/no-unused-vars + value = envObject.ensureHandleId(v[index >>> 0]); + var HEAP_DATA_VIEW = new DataView(wasmMemory.buffer), GET_HEAP_DATA_VIEW = function () { return HEAP_DATA_VIEW.buffer === wasmMemory.buffer ? HEAP_DATA_VIEW : (HEAP_DATA_VIEW = new DataView(wasmMemory.buffer)); }; + GET_HEAP_DATA_VIEW().setUint32(result, value, true); + return envObject.getReturnStatus(); + } + catch (err) { + envObject.tryCatch.setError(err); + return envObject.setLastError(10 /* napi_status.napi_pending_exception */); + } + } + /** @__sig ippip */ + function napi_delete_element(env, object, index, result) { + // eslint-disable-next-line @typescript-eslint/no-unused-vars + var r; + if (!env) + return 1 /* napi_status.napi_invalid_arg */; + // @ts-expect-error + var envObject = emnapiCtx.envStore.get(env); + envObject.checkGCAccess(); + if (!envObject.tryCatch.isEmpty()) + return envObject.setLastError(10 /* napi_status.napi_pending_exception */); + if (!envObject.canCallIntoJs()) + return envObject.setLastError(envObject.moduleApiVersion >= 10 ? 23 /* napi_status.napi_cannot_run_js */ : 10 /* napi_status.napi_pending_exception */); + envObject.clearLastError(); + try { + if (!object) + return envObject.setLastError(1 /* napi_status.napi_invalid_arg */); + var h = emnapiCtx.handleStore.get(object); + if (!(h.isObject() || h.isFunction())) { + return envObject.setLastError(2 /* napi_status.napi_object_expected */); + } + if (emnapiCtx.feature.supportReflect) { + r = Reflect.deleteProperty(h.value, index >>> 0); + } + else { + try { + r = delete h.value[index >>> 0]; + } + catch (_) { + r = false; + } + } + if (result) { + result >>>= 0; + var HEAP_DATA_VIEW = new DataView(wasmMemory.buffer), GET_HEAP_DATA_VIEW = function () { return HEAP_DATA_VIEW.buffer === wasmMemory.buffer ? HEAP_DATA_VIEW : (HEAP_DATA_VIEW = new DataView(wasmMemory.buffer)); }; + GET_HEAP_DATA_VIEW().setInt8(result, r ? 1 : 0, true); + } + return envObject.getReturnStatus(); + } + catch (err) { + envObject.tryCatch.setError(err); + return envObject.setLastError(10 /* napi_status.napi_pending_exception */); + } + } + /** @__sig ipppp */ + function napi_define_properties(env, object, property_count, properties) { + // eslint-disable-next-line @typescript-eslint/no-unused-vars + var propPtr, attributes; + if (!env) + return 1 /* napi_status.napi_invalid_arg */; + // @ts-expect-error + var envObject = emnapiCtx.envStore.get(env); + envObject.checkGCAccess(); + if (!envObject.tryCatch.isEmpty()) + return envObject.setLastError(10 /* napi_status.napi_pending_exception */); + if (!envObject.canCallIntoJs()) + return envObject.setLastError(envObject.moduleApiVersion >= 10 ? 23 /* napi_status.napi_cannot_run_js */ : 10 /* napi_status.napi_pending_exception */); + envObject.clearLastError(); + try { + properties >>>= 0; + property_count >>>= 0; + property_count = property_count >>> 0; + if (property_count > 0) { + if (!properties) + return envObject.setLastError(1 /* napi_status.napi_invalid_arg */); + } + if (!object) + return envObject.setLastError(1 /* napi_status.napi_invalid_arg */); + var h = emnapiCtx.handleStore.get(object); + var maybeObject = h.value; + if (!(h.isObject() || h.isFunction())) { + return envObject.setLastError(2 /* napi_status.napi_object_expected */); + } + var propertyName = void 0; + var HEAP_DATA_VIEW = new DataView(wasmMemory.buffer), GET_HEAP_DATA_VIEW = function () { return HEAP_DATA_VIEW.buffer === wasmMemory.buffer ? HEAP_DATA_VIEW : (HEAP_DATA_VIEW = new DataView(wasmMemory.buffer)); }; + for (var i = 0; i < property_count; i++) { + // eslint-disable-next-line @typescript-eslint/no-unused-vars + propPtr = properties + (i * (4 * 8)); + var utf8Name = GET_HEAP_DATA_VIEW().getUint32(propPtr, true); + var name_2 = GET_HEAP_DATA_VIEW().getUint32(propPtr + 4, true); + var method = GET_HEAP_DATA_VIEW().getUint32(propPtr + 8, true); + var getter = GET_HEAP_DATA_VIEW().getUint32(propPtr + 12, true); + var setter = GET_HEAP_DATA_VIEW().getUint32(propPtr + 16, true); + var value = GET_HEAP_DATA_VIEW().getUint32(propPtr + 20, true); + attributes = GET_HEAP_DATA_VIEW().getInt32(propPtr + 24, true); + attributes >>>= 0; + var data = GET_HEAP_DATA_VIEW().getUint32(propPtr + 28, true); + if (utf8Name) { + propertyName = emnapiString.UTF8ToString(utf8Name, -1); + } + else { + if (!name_2) { + return envObject.setLastError(4 /* napi_status.napi_name_expected */); + } + propertyName = emnapiCtx.handleStore.get(name_2).value; + if (typeof propertyName !== 'string' && typeof propertyName !== 'symbol') { + return envObject.setLastError(4 /* napi_status.napi_name_expected */); + } + } + emnapiDefineProperty(envObject, maybeObject, propertyName, method, getter, setter, value, attributes, data); + } + return envObject.getReturnStatus(); + } + catch (err) { + envObject.tryCatch.setError(err); + return envObject.setLastError(10 /* napi_status.napi_pending_exception */); + } + } + /** @__sig ipp */ + function napi_object_freeze(env, object) { + if (!env) + return 1 /* napi_status.napi_invalid_arg */; + // @ts-expect-error + var envObject = emnapiCtx.envStore.get(env); + envObject.checkGCAccess(); + if (!envObject.tryCatch.isEmpty()) + return envObject.setLastError(10 /* napi_status.napi_pending_exception */); + if (!envObject.canCallIntoJs()) + return envObject.setLastError(envObject.moduleApiVersion >= 10 ? 23 /* napi_status.napi_cannot_run_js */ : 10 /* napi_status.napi_pending_exception */); + envObject.clearLastError(); + try { + if (!object) + return envObject.setLastError(1 /* napi_status.napi_invalid_arg */); + var h = emnapiCtx.handleStore.get(object); + var maybeObject = h.value; + if (!(h.isObject() || h.isFunction())) { + return envObject.setLastError(2 /* napi_status.napi_object_expected */); + } + Object.freeze(maybeObject); + return envObject.getReturnStatus(); + } + catch (err) { + envObject.tryCatch.setError(err); + return envObject.setLastError(10 /* napi_status.napi_pending_exception */); + } + } + /** @__sig ipp */ + function napi_object_seal(env, object) { + if (!env) + return 1 /* napi_status.napi_invalid_arg */; + // @ts-expect-error + var envObject = emnapiCtx.envStore.get(env); + envObject.checkGCAccess(); + if (!envObject.tryCatch.isEmpty()) + return envObject.setLastError(10 /* napi_status.napi_pending_exception */); + if (!envObject.canCallIntoJs()) + return envObject.setLastError(envObject.moduleApiVersion >= 10 ? 23 /* napi_status.napi_cannot_run_js */ : 10 /* napi_status.napi_pending_exception */); + envObject.clearLastError(); + try { + if (!object) + return envObject.setLastError(1 /* napi_status.napi_invalid_arg */); + var h = emnapiCtx.handleStore.get(object); + var maybeObject = h.value; + if (!(h.isObject() || h.isFunction())) { + return envObject.setLastError(2 /* napi_status.napi_object_expected */); + } + Object.seal(maybeObject); + return envObject.getReturnStatus(); + } + catch (err) { + envObject.tryCatch.setError(err); + return envObject.setLastError(10 /* napi_status.napi_pending_exception */); + } + } + var propertyMod = /*#__PURE__*/ Object.freeze({ + __proto__: null, + napi_define_properties: napi_define_properties, + napi_delete_element: napi_delete_element, + napi_delete_property: napi_delete_property, + napi_get_all_property_names: napi_get_all_property_names, + napi_get_element: napi_get_element, + napi_get_named_property: napi_get_named_property, + napi_get_property: napi_get_property, + napi_get_property_names: napi_get_property_names, + napi_has_element: napi_has_element, + napi_has_named_property: napi_has_named_property, + napi_has_own_property: napi_has_own_property, + napi_has_property: napi_has_property, + napi_object_freeze: napi_object_freeze, + napi_object_seal: napi_object_seal, + napi_set_element: napi_set_element, + napi_set_named_property: napi_set_named_property, + napi_set_property: napi_set_property + }); + /** @__sig ippp */ + function napi_run_script(env, script, result) { + var status; + // eslint-disable-next-line @typescript-eslint/no-unused-vars + var value; + if (!env) + return 1 /* napi_status.napi_invalid_arg */; + // @ts-expect-error + var envObject = emnapiCtx.envStore.get(env); + envObject.checkGCAccess(); + if (!envObject.tryCatch.isEmpty()) + return envObject.setLastError(10 /* napi_status.napi_pending_exception */); + if (!envObject.canCallIntoJs()) + return envObject.setLastError(envObject.moduleApiVersion >= 10 ? 23 /* napi_status.napi_cannot_run_js */ : 10 /* napi_status.napi_pending_exception */); + envObject.clearLastError(); + try { + if (!script) + return envObject.setLastError(1 /* napi_status.napi_invalid_arg */); + if (!result) + return envObject.setLastError(1 /* napi_status.napi_invalid_arg */); + var v8Script = emnapiCtx.handleStore.get(script); + if (!v8Script.isString()) { + return envObject.setLastError(3 /* napi_status.napi_string_expected */); + } + var g = emnapiCtx.handleStore.get(5 /* GlobalHandle.GLOBAL */).value; + var ret = g.eval(v8Script.value); + result >>>= 0; + // eslint-disable-next-line @typescript-eslint/no-unused-vars + value = envObject.ensureHandleId(ret); + var HEAP_DATA_VIEW = new DataView(wasmMemory.buffer), GET_HEAP_DATA_VIEW = function () { return HEAP_DATA_VIEW.buffer === wasmMemory.buffer ? HEAP_DATA_VIEW : (HEAP_DATA_VIEW = new DataView(wasmMemory.buffer)); }; + GET_HEAP_DATA_VIEW().setUint32(result, value, true); + status = envObject.getReturnStatus(); + } + catch (err) { + envObject.tryCatch.setError(err); + return envObject.setLastError(10 /* napi_status.napi_pending_exception */); + } + return status; + } + var scriptMod = /*#__PURE__*/ Object.freeze({ + __proto__: null, + napi_run_script: napi_run_script + }); + /** @__sig ippp */ + function napi_typeof(env, value, result) { + if (!env) + return 1 /* napi_status.napi_invalid_arg */; + // @ts-expect-error + var envObject = emnapiCtx.envStore.get(env); + envObject.checkGCAccess(); + if (!value) + return envObject.setLastError(1 /* napi_status.napi_invalid_arg */); + if (!result) + return envObject.setLastError(1 /* napi_status.napi_invalid_arg */); + var v = emnapiCtx.handleStore.get(value); + result >>>= 0; + var r; + if (v.isNumber()) { + r = 3 /* napi_valuetype.napi_number */; + } + else if (v.isBigInt()) { + r = 9 /* napi_valuetype.napi_bigint */; + } + else if (v.isString()) { + r = 4 /* napi_valuetype.napi_string */; + } + else if (v.isFunction()) { + // This test has to come before IsObject because IsFunction + // implies IsObject + r = 7 /* napi_valuetype.napi_function */; + } + else if (v.isExternal()) { + // This test has to come before IsObject because IsExternal + // implies IsObject + r = 8 /* napi_valuetype.napi_external */; + } + else if (v.isObject()) { + r = 6 /* napi_valuetype.napi_object */; + } + else if (v.isBoolean()) { + r = 2 /* napi_valuetype.napi_boolean */; + } + else if (v.isUndefined()) { + r = 0 /* napi_valuetype.napi_undefined */; + } + else if (v.isSymbol()) { + r = 5 /* napi_valuetype.napi_symbol */; + } + else if (v.isNull()) { + // eslint-disable-next-line @typescript-eslint/no-unused-vars + r = 1 /* napi_valuetype.napi_null */; + } + else { + // Should not get here unless V8 has added some new kind of value. + return envObject.setLastError(1 /* napi_status.napi_invalid_arg */); + } + var HEAP_DATA_VIEW = new DataView(wasmMemory.buffer), GET_HEAP_DATA_VIEW = function () { return HEAP_DATA_VIEW.buffer === wasmMemory.buffer ? HEAP_DATA_VIEW : (HEAP_DATA_VIEW = new DataView(wasmMemory.buffer)); }; + GET_HEAP_DATA_VIEW().setInt32(result, r, true); + return envObject.clearLastError(); + } + /** @__sig ippp */ + function napi_coerce_to_bool(env, value, result) { + // eslint-disable-next-line @typescript-eslint/no-unused-vars + var v; + if (!env) + return 1 /* napi_status.napi_invalid_arg */; + // @ts-expect-error + var envObject = emnapiCtx.envStore.get(env); + envObject.checkGCAccess(); + if (!envObject.tryCatch.isEmpty()) + return envObject.setLastError(10 /* napi_status.napi_pending_exception */); + if (!envObject.canCallIntoJs()) + return envObject.setLastError(envObject.moduleApiVersion >= 10 ? 23 /* napi_status.napi_cannot_run_js */ : 10 /* napi_status.napi_pending_exception */); + envObject.clearLastError(); + try { + if (!value) + return envObject.setLastError(1 /* napi_status.napi_invalid_arg */); + if (!result) + return envObject.setLastError(1 /* napi_status.napi_invalid_arg */); + var handle = emnapiCtx.handleStore.get(value); + result >>>= 0; + v = handle.value ? 4 /* GlobalHandle.TRUE */ : 3 /* GlobalHandle.FALSE */; + var HEAP_DATA_VIEW = new DataView(wasmMemory.buffer), GET_HEAP_DATA_VIEW = function () { return HEAP_DATA_VIEW.buffer === wasmMemory.buffer ? HEAP_DATA_VIEW : (HEAP_DATA_VIEW = new DataView(wasmMemory.buffer)); }; + GET_HEAP_DATA_VIEW().setUint32(result, v, true); + return envObject.getReturnStatus(); + } + catch (err) { + envObject.tryCatch.setError(err); + return envObject.setLastError(10 /* napi_status.napi_pending_exception */); + } + } + /** @__sig ippp */ + function napi_coerce_to_number(env, value, result) { + // eslint-disable-next-line @typescript-eslint/no-unused-vars + var v; + if (!env) + return 1 /* napi_status.napi_invalid_arg */; + // @ts-expect-error + var envObject = emnapiCtx.envStore.get(env); + envObject.checkGCAccess(); + if (!envObject.tryCatch.isEmpty()) + return envObject.setLastError(10 /* napi_status.napi_pending_exception */); + if (!envObject.canCallIntoJs()) + return envObject.setLastError(envObject.moduleApiVersion >= 10 ? 23 /* napi_status.napi_cannot_run_js */ : 10 /* napi_status.napi_pending_exception */); + envObject.clearLastError(); + try { + if (!value) + return envObject.setLastError(1 /* napi_status.napi_invalid_arg */); + if (!result) + return envObject.setLastError(1 /* napi_status.napi_invalid_arg */); + var handle = emnapiCtx.handleStore.get(value); + if (handle.isBigInt()) { + throw new TypeError('Cannot convert a BigInt value to a number'); + } + result >>>= 0; + // eslint-disable-next-line @typescript-eslint/no-unused-vars + v = emnapiCtx.addToCurrentScope(Number(handle.value)).id; + var HEAP_DATA_VIEW = new DataView(wasmMemory.buffer), GET_HEAP_DATA_VIEW = function () { return HEAP_DATA_VIEW.buffer === wasmMemory.buffer ? HEAP_DATA_VIEW : (HEAP_DATA_VIEW = new DataView(wasmMemory.buffer)); }; + GET_HEAP_DATA_VIEW().setUint32(result, v, true); + return envObject.getReturnStatus(); + } + catch (err) { + envObject.tryCatch.setError(err); + return envObject.setLastError(10 /* napi_status.napi_pending_exception */); + } + } + /** @__sig ippp */ + function napi_coerce_to_object(env, value, result) { + // eslint-disable-next-line @typescript-eslint/no-unused-vars + var v; + if (!env) + return 1 /* napi_status.napi_invalid_arg */; + // @ts-expect-error + var envObject = emnapiCtx.envStore.get(env); + envObject.checkGCAccess(); + if (!envObject.tryCatch.isEmpty()) + return envObject.setLastError(10 /* napi_status.napi_pending_exception */); + if (!envObject.canCallIntoJs()) + return envObject.setLastError(envObject.moduleApiVersion >= 10 ? 23 /* napi_status.napi_cannot_run_js */ : 10 /* napi_status.napi_pending_exception */); + envObject.clearLastError(); + try { + if (!value) + return envObject.setLastError(1 /* napi_status.napi_invalid_arg */); + if (!result) + return envObject.setLastError(1 /* napi_status.napi_invalid_arg */); + var handle = emnapiCtx.handleStore.get(value); + if (handle.value == null) { + throw new TypeError('Cannot convert undefined or null to object'); + } + result >>>= 0; + // eslint-disable-next-line @typescript-eslint/no-unused-vars + v = envObject.ensureHandleId(Object(handle.value)); + var HEAP_DATA_VIEW = new DataView(wasmMemory.buffer), GET_HEAP_DATA_VIEW = function () { return HEAP_DATA_VIEW.buffer === wasmMemory.buffer ? HEAP_DATA_VIEW : (HEAP_DATA_VIEW = new DataView(wasmMemory.buffer)); }; + GET_HEAP_DATA_VIEW().setUint32(result, v, true); + return envObject.getReturnStatus(); + } + catch (err) { + envObject.tryCatch.setError(err); + return envObject.setLastError(10 /* napi_status.napi_pending_exception */); + } + } + /** @__sig ippp */ + function napi_coerce_to_string(env, value, result) { + // eslint-disable-next-line @typescript-eslint/no-unused-vars + var v; + if (!env) + return 1 /* napi_status.napi_invalid_arg */; + // @ts-expect-error + var envObject = emnapiCtx.envStore.get(env); + envObject.checkGCAccess(); + if (!envObject.tryCatch.isEmpty()) + return envObject.setLastError(10 /* napi_status.napi_pending_exception */); + if (!envObject.canCallIntoJs()) + return envObject.setLastError(envObject.moduleApiVersion >= 10 ? 23 /* napi_status.napi_cannot_run_js */ : 10 /* napi_status.napi_pending_exception */); + envObject.clearLastError(); + try { + if (!value) + return envObject.setLastError(1 /* napi_status.napi_invalid_arg */); + if (!result) + return envObject.setLastError(1 /* napi_status.napi_invalid_arg */); + var handle = emnapiCtx.handleStore.get(value); + if (handle.isSymbol()) { + throw new TypeError('Cannot convert a Symbol value to a string'); + } + result >>>= 0; + // eslint-disable-next-line @typescript-eslint/no-unused-vars + v = emnapiCtx.addToCurrentScope(String(handle.value)).id; + var HEAP_DATA_VIEW = new DataView(wasmMemory.buffer), GET_HEAP_DATA_VIEW = function () { return HEAP_DATA_VIEW.buffer === wasmMemory.buffer ? HEAP_DATA_VIEW : (HEAP_DATA_VIEW = new DataView(wasmMemory.buffer)); }; + GET_HEAP_DATA_VIEW().setUint32(result, v, true); + return envObject.getReturnStatus(); + } + catch (err) { + envObject.tryCatch.setError(err); + return envObject.setLastError(10 /* napi_status.napi_pending_exception */); + } + } + /** @__sig ipppp */ + function napi_instanceof(env, object, constructor, result) { + // eslint-disable-next-line @typescript-eslint/no-unused-vars + var r; + if (!env) + return 1 /* napi_status.napi_invalid_arg */; + // @ts-expect-error + var envObject = emnapiCtx.envStore.get(env); + envObject.checkGCAccess(); + if (!envObject.tryCatch.isEmpty()) + return envObject.setLastError(10 /* napi_status.napi_pending_exception */); + if (!envObject.canCallIntoJs()) + return envObject.setLastError(envObject.moduleApiVersion >= 10 ? 23 /* napi_status.napi_cannot_run_js */ : 10 /* napi_status.napi_pending_exception */); + envObject.clearLastError(); + try { + if (!object) + return envObject.setLastError(1 /* napi_status.napi_invalid_arg */); + if (!result) + return envObject.setLastError(1 /* napi_status.napi_invalid_arg */); + if (!constructor) + return envObject.setLastError(1 /* napi_status.napi_invalid_arg */); + result >>>= 0; + var HEAP_DATA_VIEW = new DataView(wasmMemory.buffer), GET_HEAP_DATA_VIEW = function () { return HEAP_DATA_VIEW.buffer === wasmMemory.buffer ? HEAP_DATA_VIEW : (HEAP_DATA_VIEW = new DataView(wasmMemory.buffer)); }; + GET_HEAP_DATA_VIEW().setInt8(result, 0, true); + var ctor = emnapiCtx.handleStore.get(constructor); + if (!ctor.isFunction()) { + return envObject.setLastError(5 /* napi_status.napi_function_expected */); + } + var val = emnapiCtx.handleStore.get(object).value; + var ret = val instanceof ctor.value; + r = ret ? 1 : 0; + GET_HEAP_DATA_VIEW().setInt8(result, r, true); + return envObject.getReturnStatus(); + } + catch (err) { + envObject.tryCatch.setError(err); + return envObject.setLastError(10 /* napi_status.napi_pending_exception */); + } + } + /** @__sig ippp */ + function napi_is_array(env, value, result) { + if (!env) + return 1 /* napi_status.napi_invalid_arg */; + // @ts-expect-error + var envObject = emnapiCtx.envStore.get(env); + envObject.checkGCAccess(); + if (!value) + return envObject.setLastError(1 /* napi_status.napi_invalid_arg */); + if (!result) + return envObject.setLastError(1 /* napi_status.napi_invalid_arg */); + var h = emnapiCtx.handleStore.get(value); + result >>>= 0; + // eslint-disable-next-line @typescript-eslint/no-unused-vars + var r = h.isArray() ? 1 : 0; + var HEAP_DATA_VIEW = new DataView(wasmMemory.buffer), GET_HEAP_DATA_VIEW = function () { return HEAP_DATA_VIEW.buffer === wasmMemory.buffer ? HEAP_DATA_VIEW : (HEAP_DATA_VIEW = new DataView(wasmMemory.buffer)); }; + GET_HEAP_DATA_VIEW().setInt8(result, r, true); + return envObject.clearLastError(); + } + /** @__sig ippp */ + function napi_is_arraybuffer(env, value, result) { + if (!env) + return 1 /* napi_status.napi_invalid_arg */; + // @ts-expect-error + var envObject = emnapiCtx.envStore.get(env); + envObject.checkGCAccess(); + if (!value) + return envObject.setLastError(1 /* napi_status.napi_invalid_arg */); + if (!result) + return envObject.setLastError(1 /* napi_status.napi_invalid_arg */); + var h = emnapiCtx.handleStore.get(value); + result >>>= 0; + // eslint-disable-next-line @typescript-eslint/no-unused-vars + var r = h.isArrayBuffer() ? 1 : 0; + var HEAP_DATA_VIEW = new DataView(wasmMemory.buffer), GET_HEAP_DATA_VIEW = function () { return HEAP_DATA_VIEW.buffer === wasmMemory.buffer ? HEAP_DATA_VIEW : (HEAP_DATA_VIEW = new DataView(wasmMemory.buffer)); }; + GET_HEAP_DATA_VIEW().setInt8(result, r, true); + return envObject.clearLastError(); + } + /** @__sig ippp */ + function node_api_is_sharedarraybuffer(env, value, result) { + if (!env) + return 1 /* napi_status.napi_invalid_arg */; + // @ts-expect-error + var envObject = emnapiCtx.envStore.get(env); + envObject.checkGCAccess(); + if (!value) + return envObject.setLastError(1 /* napi_status.napi_invalid_arg */); + if (!result) + return envObject.setLastError(1 /* napi_status.napi_invalid_arg */); + var h = emnapiCtx.handleStore.get(value); + result >>>= 0; + // eslint-disable-next-line @typescript-eslint/no-unused-vars + var r = ((typeof SharedArrayBuffer === 'function' && h.value instanceof SharedArrayBuffer) || + (Object.prototype.toString.call(h.value) === '[object SharedArrayBuffer]')) + ? 1 + : 0; + var HEAP_DATA_VIEW = new DataView(wasmMemory.buffer), GET_HEAP_DATA_VIEW = function () { return HEAP_DATA_VIEW.buffer === wasmMemory.buffer ? HEAP_DATA_VIEW : (HEAP_DATA_VIEW = new DataView(wasmMemory.buffer)); }; + GET_HEAP_DATA_VIEW().setInt8(result, r, true); + return envObject.clearLastError(); + } + /** @__sig ippp */ + function napi_is_date(env, value, result) { + if (!env) + return 1 /* napi_status.napi_invalid_arg */; + // @ts-expect-error + var envObject = emnapiCtx.envStore.get(env); + envObject.checkGCAccess(); + if (!value) + return envObject.setLastError(1 /* napi_status.napi_invalid_arg */); + if (!result) + return envObject.setLastError(1 /* napi_status.napi_invalid_arg */); + var h = emnapiCtx.handleStore.get(value); + result >>>= 0; + // eslint-disable-next-line @typescript-eslint/no-unused-vars + var r = h.isDate() ? 1 : 0; + var HEAP_DATA_VIEW = new DataView(wasmMemory.buffer), GET_HEAP_DATA_VIEW = function () { return HEAP_DATA_VIEW.buffer === wasmMemory.buffer ? HEAP_DATA_VIEW : (HEAP_DATA_VIEW = new DataView(wasmMemory.buffer)); }; + GET_HEAP_DATA_VIEW().setInt8(result, r, true); + return envObject.clearLastError(); + } + /** @__sig ippp */ + function napi_is_error(env, value, result) { + if (!env) + return 1 /* napi_status.napi_invalid_arg */; + // @ts-expect-error + var envObject = emnapiCtx.envStore.get(env); + envObject.checkGCAccess(); + if (!value) + return envObject.setLastError(1 /* napi_status.napi_invalid_arg */); + if (!result) + return envObject.setLastError(1 /* napi_status.napi_invalid_arg */); + var val = emnapiCtx.handleStore.get(value).value; + result >>>= 0; + // eslint-disable-next-line @typescript-eslint/no-unused-vars + var r = (val instanceof Error) ? 1 : 0; + var HEAP_DATA_VIEW = new DataView(wasmMemory.buffer), GET_HEAP_DATA_VIEW = function () { return HEAP_DATA_VIEW.buffer === wasmMemory.buffer ? HEAP_DATA_VIEW : (HEAP_DATA_VIEW = new DataView(wasmMemory.buffer)); }; + GET_HEAP_DATA_VIEW().setInt8(result, r, true); + return envObject.clearLastError(); + } + /** @__sig ippp */ + function napi_is_typedarray(env, value, result) { + if (!env) + return 1 /* napi_status.napi_invalid_arg */; + // @ts-expect-error + var envObject = emnapiCtx.envStore.get(env); + envObject.checkGCAccess(); + if (!value) + return envObject.setLastError(1 /* napi_status.napi_invalid_arg */); + if (!result) + return envObject.setLastError(1 /* napi_status.napi_invalid_arg */); + var h = emnapiCtx.handleStore.get(value); + result >>>= 0; + // eslint-disable-next-line @typescript-eslint/no-unused-vars + var r = h.isTypedArray() ? 1 : 0; + var HEAP_DATA_VIEW = new DataView(wasmMemory.buffer), GET_HEAP_DATA_VIEW = function () { return HEAP_DATA_VIEW.buffer === wasmMemory.buffer ? HEAP_DATA_VIEW : (HEAP_DATA_VIEW = new DataView(wasmMemory.buffer)); }; + GET_HEAP_DATA_VIEW().setInt8(result, r, true); + return envObject.clearLastError(); + } + /** @__sig ippp */ + function napi_is_buffer(env, value, result) { + if (!env) + return 1 /* napi_status.napi_invalid_arg */; + // @ts-expect-error + var envObject = emnapiCtx.envStore.get(env); + envObject.checkGCAccess(); + if (!value) + return envObject.setLastError(1 /* napi_status.napi_invalid_arg */); + if (!result) + return envObject.setLastError(1 /* napi_status.napi_invalid_arg */); + var h = emnapiCtx.handleStore.get(value); + result >>>= 0; + // eslint-disable-next-line @typescript-eslint/no-unused-vars + var r = h.isBuffer(emnapiCtx.feature.Buffer) ? 1 : 0; + var HEAP_DATA_VIEW = new DataView(wasmMemory.buffer), GET_HEAP_DATA_VIEW = function () { return HEAP_DATA_VIEW.buffer === wasmMemory.buffer ? HEAP_DATA_VIEW : (HEAP_DATA_VIEW = new DataView(wasmMemory.buffer)); }; + GET_HEAP_DATA_VIEW().setInt8(result, r, true); + return envObject.clearLastError(); + } + /** @__sig ippp */ + function napi_is_dataview(env, value, result) { + if (!env) + return 1 /* napi_status.napi_invalid_arg */; + // @ts-expect-error + var envObject = emnapiCtx.envStore.get(env); + envObject.checkGCAccess(); + if (!value) + return envObject.setLastError(1 /* napi_status.napi_invalid_arg */); + if (!result) + return envObject.setLastError(1 /* napi_status.napi_invalid_arg */); + var h = emnapiCtx.handleStore.get(value); + result >>>= 0; + // eslint-disable-next-line @typescript-eslint/no-unused-vars + var r = h.isDataView() ? 1 : 0; + var HEAP_DATA_VIEW = new DataView(wasmMemory.buffer), GET_HEAP_DATA_VIEW = function () { return HEAP_DATA_VIEW.buffer === wasmMemory.buffer ? HEAP_DATA_VIEW : (HEAP_DATA_VIEW = new DataView(wasmMemory.buffer)); }; + GET_HEAP_DATA_VIEW().setInt8(result, r, true); + return envObject.clearLastError(); + } + /** @__sig ipppp */ + function napi_strict_equals(env, lhs, rhs, result) { + // eslint-disable-next-line @typescript-eslint/no-unused-vars + var r; + if (!env) + return 1 /* napi_status.napi_invalid_arg */; + // @ts-expect-error + var envObject = emnapiCtx.envStore.get(env); + envObject.checkGCAccess(); + if (!envObject.tryCatch.isEmpty()) + return envObject.setLastError(10 /* napi_status.napi_pending_exception */); + if (!envObject.canCallIntoJs()) + return envObject.setLastError(envObject.moduleApiVersion >= 10 ? 23 /* napi_status.napi_cannot_run_js */ : 10 /* napi_status.napi_pending_exception */); + envObject.clearLastError(); + try { + if (!lhs) + return envObject.setLastError(1 /* napi_status.napi_invalid_arg */); + if (!rhs) + return envObject.setLastError(1 /* napi_status.napi_invalid_arg */); + if (!result) + return envObject.setLastError(1 /* napi_status.napi_invalid_arg */); + var lv = emnapiCtx.handleStore.get(lhs).value; + var rv = emnapiCtx.handleStore.get(rhs).value; + result >>>= 0; + r = (lv === rv) ? 1 : 0; + var HEAP_DATA_VIEW = new DataView(wasmMemory.buffer), GET_HEAP_DATA_VIEW = function () { return HEAP_DATA_VIEW.buffer === wasmMemory.buffer ? HEAP_DATA_VIEW : (HEAP_DATA_VIEW = new DataView(wasmMemory.buffer)); }; + GET_HEAP_DATA_VIEW().setInt8(result, r, true); + return envObject.getReturnStatus(); + } + catch (err) { + envObject.tryCatch.setError(err); + return envObject.setLastError(10 /* napi_status.napi_pending_exception */); + } + } + /** @__sig ipp */ + function napi_detach_arraybuffer(env, arraybuffer) { + if (!env) + return 1 /* napi_status.napi_invalid_arg */; + // @ts-expect-error + var envObject = emnapiCtx.envStore.get(env); + envObject.checkGCAccess(); + if (!arraybuffer) + return envObject.setLastError(1 /* napi_status.napi_invalid_arg */); + var value = emnapiCtx.handleStore.get(arraybuffer).value; + if (!(value instanceof ArrayBuffer)) { + if (typeof SharedArrayBuffer === 'function' && (value instanceof SharedArrayBuffer)) { + return envObject.setLastError(20 /* napi_status.napi_detachable_arraybuffer_expected */); + } + return envObject.setLastError(19 /* napi_status.napi_arraybuffer_expected */); + } + try { + var MessageChannel_1 = emnapiCtx.feature.MessageChannel; + var messageChannel = new MessageChannel_1(); + messageChannel.port1.postMessage(value, [value]); + } + catch (_) { + return envObject.setLastError(9 /* napi_status.napi_generic_failure */); + } + return envObject.clearLastError(); + } + /** @__sig ippp */ + function napi_is_detached_arraybuffer(env, arraybuffer, result) { + if (!env) + return 1 /* napi_status.napi_invalid_arg */; + // @ts-expect-error + var envObject = emnapiCtx.envStore.get(env); + envObject.checkGCAccess(); + if (!envObject.tryCatch.isEmpty()) + return envObject.setLastError(10 /* napi_status.napi_pending_exception */); + if (!envObject.canCallIntoJs()) + return envObject.setLastError(envObject.moduleApiVersion >= 10 ? 23 /* napi_status.napi_cannot_run_js */ : 10 /* napi_status.napi_pending_exception */); + envObject.clearLastError(); + try { + if (!arraybuffer) + return envObject.setLastError(1 /* napi_status.napi_invalid_arg */); + if (!result) + return envObject.setLastError(1 /* napi_status.napi_invalid_arg */); + var h = emnapiCtx.handleStore.get(arraybuffer); + result >>>= 0; + var HEAP_DATA_VIEW = new DataView(wasmMemory.buffer), GET_HEAP_DATA_VIEW = function () { return HEAP_DATA_VIEW.buffer === wasmMemory.buffer ? HEAP_DATA_VIEW : (HEAP_DATA_VIEW = new DataView(wasmMemory.buffer)); }; + if (h.isArrayBuffer() && h.value.byteLength === 0) { + try { + // eslint-disable-next-line no-new + new Uint8Array(h.value); + } + catch (_) { + GET_HEAP_DATA_VIEW().setInt8(result, 1, true); + return envObject.getReturnStatus(); + } + } + GET_HEAP_DATA_VIEW().setInt8(result, 0, true); + return envObject.getReturnStatus(); + } + catch (err) { + envObject.tryCatch.setError(err); + return envObject.setLastError(10 /* napi_status.napi_pending_exception */); + } + } + var valueOperationMod = /*#__PURE__*/ Object.freeze({ + __proto__: null, + napi_coerce_to_bool: napi_coerce_to_bool, + napi_coerce_to_number: napi_coerce_to_number, + napi_coerce_to_object: napi_coerce_to_object, + napi_coerce_to_string: napi_coerce_to_string, + napi_detach_arraybuffer: napi_detach_arraybuffer, + napi_instanceof: napi_instanceof, + napi_is_array: napi_is_array, + napi_is_arraybuffer: napi_is_arraybuffer, + napi_is_buffer: napi_is_buffer, + napi_is_dataview: napi_is_dataview, + napi_is_date: napi_is_date, + napi_is_detached_arraybuffer: napi_is_detached_arraybuffer, + napi_is_error: napi_is_error, + napi_is_typedarray: napi_is_typedarray, + napi_strict_equals: napi_strict_equals, + napi_typeof: napi_typeof, + node_api_is_sharedarraybuffer: node_api_is_sharedarraybuffer + }); + /** @__sig ipp */ + function napi_get_version(env, result) { + if (!env) + return 1 /* napi_status.napi_invalid_arg */; + var envObject = emnapiCtx.envStore.get(env); + if (!result) + return envObject.setLastError(1 /* napi_status.napi_invalid_arg */); + // eslint-disable-next-line @typescript-eslint/no-unused-vars + var NODE_API_SUPPORTED_VERSION_MAX = 10 /* Version.NODE_API_SUPPORTED_VERSION_MAX */; + var HEAP_DATA_VIEW = new DataView(wasmMemory.buffer), GET_HEAP_DATA_VIEW = function () { return HEAP_DATA_VIEW.buffer === wasmMemory.buffer ? HEAP_DATA_VIEW : (HEAP_DATA_VIEW = new DataView(wasmMemory.buffer)); }; + GET_HEAP_DATA_VIEW().setUint32(result, NODE_API_SUPPORTED_VERSION_MAX, true); + return envObject.clearLastError(); + } + var versionMod = /*#__PURE__*/ Object.freeze({ + __proto__: null, + napi_get_version: napi_get_version + }); + emnapiAWST.init(); + emnapiExternalMemory.init(); + emnapiExternalSAB.init(); + emnapiString.init(); + emnapiTSFN.init(); + PThread.init(); + napiModule.emnapi.syncMemory = $emnapiSyncMemory; + napiModule.emnapi.getMemoryAddress = $emnapiGetMemoryAddress; + napiModule.emnapi.acquireExternalSharedArrayBuffer = $emnapiAcquireExternalSharedArrayBuffer; + function addImports(mod) { + var keys = Object.keys(mod); + for (var i = 0; i < keys.length; ++i) { + var k = keys[i]; + if (k.indexOf('$') === 0) + continue; + if (k.indexOf('emnapi_') === 0) { + napiModule.imports.emnapi[k] = mod[k]; + } + else if (k.indexOf('_emnapi_') === 0 || k === 'napi_set_last_error' || k === 'napi_clear_last_error') { + napiModule.imports.env[k] = mod[k]; + } + else { + napiModule.imports.napi[k] = mod[k]; + } + } + } + addImports(asyncMod); + addImports(memoryMod); + addImports(asyncWorkMod); + addImports(utilMod); + addImports(convert2cMod); + addImports(convert2napiMod); + addImports(createMod); + addImports(globalMod); + addImports(wrapMod); + addImports(envMod); + addImports(emnapiMod); + addImports(errorMod); + addImports(functionMod); + addImports(lifeMod); + addImports(miscellaneousMod); + addImports(nodeMod); + addImports(promiseMod); + addImports(propertyMod); + addImports(scriptMod); + addImports(valueOperationMod); + addImports(versionMod); + napiModule.imports.napi.napi_create_threadsafe_function = napi_create_threadsafe_function; + napiModule.imports.napi.napi_get_threadsafe_function_context = napi_get_threadsafe_function_context; + napiModule.imports.napi.napi_call_threadsafe_function = napi_call_threadsafe_function; + napiModule.imports.napi.napi_acquire_threadsafe_function = napi_acquire_threadsafe_function; + napiModule.imports.napi.napi_release_threadsafe_function = napi_release_threadsafe_function; + napiModule.imports.napi.napi_unref_threadsafe_function = napi_unref_threadsafe_function; + napiModule.imports.napi.napi_ref_threadsafe_function = napi_ref_threadsafe_function; + return napiModule; + })(); + return napiModule; +} + +function loadNapiModuleImpl(loadFn, userNapiModule, wasmInput, options) { + // eslint-disable-next-line @typescript-eslint/consistent-type-assertions + options = options !== null && options !== void 0 ? options : {}; + var getMemory = options.getMemory; + var getTable = options.getTable; + var beforeInit = options.beforeInit; + if (getMemory != null && typeof getMemory !== 'function') { + throw new TypeError('options.getMemory is not a function'); + } + if (getTable != null && typeof getTable !== 'function') { + throw new TypeError('options.getTable is not a function'); + } + if (beforeInit != null && typeof beforeInit !== 'function') { + throw new TypeError('options.beforeInit is not a function'); + } + var napiModule; + var isLoad = typeof userNapiModule === 'object' && userNapiModule !== null; + if (isLoad) { + if (userNapiModule.loaded) { + throw new Error('napiModule has already loaded'); + } + napiModule = userNapiModule; + } + else { + napiModule = createNapiModule(options); + } + var wasi = options.wasi; + var wasiThreads; + var importObject = { + env: napiModule.imports.env, + napi: napiModule.imports.napi, + emnapi: napiModule.imports.emnapi + }; + if (wasi) { + wasiThreads = new WASIThreads(napiModule.childThread + ? { + wasi: wasi, + childThread: true, + postMessage: napiModule.postMessage + } + : { + wasi: wasi, + threadManager: napiModule.PThread, + waitThreadStart: napiModule.waitThreadStart + }); + Object.assign(importObject, typeof wasi.getImportObject === 'function' + ? wasi.getImportObject() + : { wasi_snapshot_preview1: wasi.wasiImport }); + Object.assign(importObject, wasiThreads.getImportObject()); + } + var overwriteImports = options.overwriteImports; + if (typeof overwriteImports === 'function') { + var newImportObject = overwriteImports(importObject); + if (typeof newImportObject === 'object' && newImportObject !== null) { + importObject = newImportObject; + } + } + return loadFn(wasmInput, importObject, function (err, source) { + if (err) { + throw err; + } + var originalInstance = source.instance; + var instance = originalInstance; + var originalExports = originalInstance.exports; + var exportMemory = 'memory' in originalExports; + var importMemory = 'memory' in importObject.env; + var memory = getMemory + ? getMemory(originalExports) + : exportMemory + ? originalExports.memory + : importMemory + ? importObject.env.memory + : undefined; + if (!memory) { + throw new Error('memory is neither exported nor imported'); + } + var table = getTable ? getTable(originalExports) : originalExports.__indirect_function_table; + if (wasi && !exportMemory) { + var exports_1 = Object.create(null); + Object.assign(exports_1, originalExports, { memory: memory }); + instance = { exports: exports_1 }; + } + var module = source.module; + if (wasi) { + instance = wasiThreads.initialize(instance, module, memory); + } + else { + napiModule.PThread.setup(module, memory); + } + var emnapiInit = function () { + if (beforeInit) { + beforeInit({ + instance: originalInstance, + module: module + }); + } + napiModule.init({ + instance: instance, + module: module, + memory: memory, + table: table + }); + var ret = { + instance: originalInstance, + module: module, + usedInstance: instance + }; + if (!isLoad) { + ret.napiModule = napiModule; + } + return ret; + }; + if (napiModule.PThread.shouldPreloadWorkers()) { + var poolReady = napiModule.PThread.loadWasmModuleToAllWorkers(); + if (loadFn === loadCallback) { + return poolReady.then(emnapiInit); + } + else { + throw new Error('Synchronous loading is not supported with worker pool (reuseWorker.size > 0)'); + } + } + return emnapiInit(); + }); +} +function loadCallback(wasmInput, importObject, callback) { + return load(wasmInput, importObject).then(function (source) { + return callback(null, source); + }, function (err) { + return callback(err); + }); +} +function loadSyncCallback(wasmInput, importObject, callback) { + var source; + try { + source = loadSync(wasmInput, importObject); + } + catch (err) { + return callback(err); + } + return callback(null, source); +} +/** @public */ +function loadNapiModule(napiModule, +/** Only support `BufferSource` or `WebAssembly.Module` on Node.js */ +wasmInput, options) { + if (typeof napiModule !== 'object' || napiModule === null) { + throw new TypeError('Invalid napiModule'); + } + return loadNapiModuleImpl(loadCallback, napiModule, wasmInput, options); +} +/** @public */ +function loadNapiModuleSync(napiModule, wasmInput, options) { + if (typeof napiModule !== 'object' || napiModule === null) { + throw new TypeError('Invalid napiModule'); + } + return loadNapiModuleImpl(loadSyncCallback, napiModule, wasmInput, options); +} +/** @public */ +function instantiateNapiModule( +/** Only support `BufferSource` or `WebAssembly.Module` on Node.js */ +wasmInput, options) { + return loadNapiModuleImpl(loadCallback, undefined, wasmInput, options); +} +/** @public */ +function instantiateNapiModuleSync(wasmInput, options) { + return loadNapiModuleImpl(loadSyncCallback, undefined, wasmInput, options); +} + +/** @public */ +var MessageHandler = /*#__PURE__*/ (function (_super) { + __extends(MessageHandler, _super); + function MessageHandler(options) { + var _this = this; + if (typeof options.onLoad !== 'function') { + throw new TypeError('options.onLoad is not a function'); + } + var userOnError = options.onError; + _this = _super.call(this, __assign(__assign({}, options), { onError: function (err, type) { + var _a; + var emnapi_thread_crashed = (_a = _this.instance) === null || _a === void 0 ? void 0 : _a.exports.emnapi_thread_crashed; + if (typeof emnapi_thread_crashed === 'function') { + emnapi_thread_crashed(); + } /* else { + tryWakeUpPthreadJoin(this.instance!) + } */ + if (typeof userOnError === 'function') { + userOnError(err, type); + } + else { + throw err; + } + } })) || this; + _this.napiModule = undefined; + return _this; + } + MessageHandler.prototype.instantiate = function (data) { + var _this = this; + var source = this.onLoad(data); + var then = source.then; + if (typeof then === 'function') { + return source.then(function (result) { + _this.napiModule = result.napiModule; + return result; + }); + } + this.napiModule = source.napiModule; + return source; + }; + MessageHandler.prototype.handle = function (e) { + var _this = this; + var _a; + _super.prototype.handle.call(this, e); + if ((_a = e === null || e === void 0 ? void 0 : e.data) === null || _a === void 0 ? void 0 : _a.__emnapi__) { + var type = e.data.__emnapi__.type; + var payload_1 = e.data.__emnapi__.payload; + try { + if (type === 'async-worker-init') { + this.handleAfterLoad(e, function () { + _this.napiModule.initWorker(payload_1.arg, payload_1.func); + }); + } + } + catch (err) { + this.onError(err, type); + } + } + }; + return MessageHandler; +}(ThreadMessageHandler)); +// function tryWakeUpPthreadJoin (instance: WebAssembly.Instance): void { +// // https://github.com/WebAssembly/wasi-libc/blob/574b88da481569b65a237cb80daf9a2d5aeaf82d/libc-top-half/musl/src/thread/pthread_join.c#L18-L21 +// const pthread_self = instance.exports.pthread_self as () => number +// const memory = instance.exports.memory as WebAssembly.Memory +// if (typeof pthread_self === 'function') { +// const selfThread = pthread_self() +// if (selfThread && memory) { +// // https://github.com/WebAssembly/wasi-libc/blob/574b88da481569b65a237cb80daf9a2d5aeaf82d/libc-top-half/musl/src/internal/pthread_impl.h#L45 +// const detatchState = new Int32Array(memory.buffer, selfThread + 7 * 4 /** detach_state */, 1) +// Atomics.store(detatchState, 0, 0) +// Atomics.notify(detatchState, 0, Infinity) +// } +// } +// } + +var version = "1.11.3"; + +export { MessageHandler, createNapiModule, instantiateNapiModule, instantiateNapiModuleSync, loadNapiModule, loadNapiModuleSync, version }; diff --git a/dg-ui/node_modules/@tailwindcss/oxide-wasm32-wasi/node_modules/@emnapi/core/dist/emnapi-core.js b/dg-ui/node_modules/@tailwindcss/oxide-wasm32-wasi/node_modules/@emnapi/core/dist/emnapi-core.js new file mode 100644 index 0000000..f4c4a0f --- /dev/null +++ b/dg-ui/node_modules/@tailwindcss/oxide-wasm32-wasi/node_modules/@emnapi/core/dist/emnapi-core.js @@ -0,0 +1,9777 @@ +(function (global, factory) { + typeof exports === 'object' && typeof module !== 'undefined' ? factory(exports) : + typeof define === 'function' && define.amd ? define(['exports'], factory) : + (global = typeof globalThis !== 'undefined' ? globalThis : global || self, factory(global.emnapiCore = {})); +})(this, (function (exports) { + /* eslint-disable no-undef */ + var _WebAssembly$1 = typeof WebAssembly !== 'undefined' + ? WebAssembly + : typeof WXWebAssembly !== 'undefined' + ? WXWebAssembly + : undefined; + function validateImports(imports) { + if (imports && typeof imports !== 'object') { + throw new TypeError('imports must be an object or undefined'); + } + return true; + } + function load(wasmInput, imports) { + if (!wasmInput) + throw new TypeError('Invalid wasm source'); + validateImports(imports); + imports = imports !== null && imports !== void 0 ? imports : {}; + // Promise + try { + var then = typeof wasmInput === 'object' && wasmInput !== null && 'then' in wasmInput ? wasmInput.then : undefined; + if (typeof then === 'function') { + return then.call(wasmInput, function (input) { return load(input, imports); }); + } + } + catch (_) { } + // BufferSource + if (wasmInput instanceof ArrayBuffer || ArrayBuffer.isView(wasmInput)) { + return _WebAssembly$1.instantiate(wasmInput, imports); + } + // WebAssembly.Module + if (wasmInput instanceof _WebAssembly$1.Module) { + return _WebAssembly$1.instantiate(wasmInput, imports).then(function (instance) { + return { instance: instance, module: wasmInput }; + }); + } + // Response + if (typeof Response !== 'undefined' && wasmInput instanceof Response) { + return wasmInput.arrayBuffer().then(function (buffer) { + return _WebAssembly$1.instantiate(buffer, imports); + }); + } + // string | URL + var inputIsString = typeof wasmInput === 'string'; + if (inputIsString || (typeof URL !== 'undefined' && wasmInput instanceof URL)) { + if (inputIsString && typeof wx !== 'undefined' && typeof __wxConfig !== 'undefined') { + return _WebAssembly$1.instantiate(wasmInput, imports); + } + if (typeof fetch !== 'function') { + throw new TypeError('wasm source can not be a string or URL in this environment'); + } + if (typeof _WebAssembly$1.instantiateStreaming === 'function') { + try { + return _WebAssembly$1.instantiateStreaming(fetch(wasmInput), imports).catch(function () { + return load(fetch(wasmInput), imports); + }); + } + catch (_) { + return load(fetch(wasmInput), imports); + } + } + else { + return load(fetch(wasmInput), imports); + } + } + throw new TypeError('Invalid wasm source'); + } + function loadSync(wasmInput, imports) { + if (!wasmInput) + throw new TypeError('Invalid wasm source'); + validateImports(imports); + imports = imports !== null && imports !== void 0 ? imports : {}; + var module; + if ((wasmInput instanceof ArrayBuffer) || ArrayBuffer.isView(wasmInput)) { + module = new _WebAssembly$1.Module(wasmInput); + } + else if (wasmInput instanceof WebAssembly.Module) { + module = wasmInput; + } + else { + throw new TypeError('Invalid wasm source'); + } + var instance = new _WebAssembly$1.Instance(module, imports); + var source = { instance: instance, module: module }; + return source; + } + + var _WebAssembly = typeof WebAssembly !== 'undefined' + ? WebAssembly + : typeof WXWebAssembly !== 'undefined' + ? WXWebAssembly + : undefined; + var ENVIRONMENT_IS_NODE = typeof process === 'object' && process !== null && + typeof process.versions === 'object' && process.versions !== null && + typeof process.versions.node === 'string'; + function getPostMessage(options) { + return typeof (options === null || options === void 0 ? void 0 : options.postMessage) === 'function' + ? options.postMessage + : typeof postMessage === 'function' + ? postMessage + : undefined; + } + function serizeErrorToBuffer(sab, code, error) { + var i32array = new Int32Array(sab); + Atomics.store(i32array, 0, code); + if (code > 1 && error) { + var name_1 = error.name; + var message = error.message; + var stack = error.stack; + var nameBuffer = new TextEncoder().encode(name_1); + var messageBuffer = new TextEncoder().encode(message); + var stackBuffer = new TextEncoder().encode(stack); + Atomics.store(i32array, 1, nameBuffer.length); + Atomics.store(i32array, 2, messageBuffer.length); + Atomics.store(i32array, 3, stackBuffer.length); + var buffer = new Uint8Array(sab); + buffer.set(nameBuffer, 16); + buffer.set(messageBuffer, 16 + nameBuffer.length); + buffer.set(stackBuffer, 16 + nameBuffer.length + messageBuffer.length); + } + } + function deserizeErrorFromBuffer(sab) { + var _a, _b; + var i32array = new Int32Array(sab); + var status = Atomics.load(i32array, 0); + if (status <= 1) { + return null; + } + var nameLength = Atomics.load(i32array, 1); + var messageLength = Atomics.load(i32array, 2); + var stackLength = Atomics.load(i32array, 3); + var buffer = new Uint8Array(sab); + var nameBuffer = buffer.slice(16, 16 + nameLength); + var messageBuffer = buffer.slice(16 + nameLength, 16 + nameLength + messageLength); + var stackBuffer = buffer.slice(16 + nameLength + messageLength, 16 + nameLength + messageLength + stackLength); + var name = new TextDecoder().decode(nameBuffer); + var message = new TextDecoder().decode(messageBuffer); + var stack = new TextDecoder().decode(stackBuffer); + var ErrorConstructor = (_a = globalThis[name]) !== null && _a !== void 0 ? _a : (name === 'RuntimeError' ? ((_b = _WebAssembly.RuntimeError) !== null && _b !== void 0 ? _b : Error) : Error); + var error = new ErrorConstructor(message); + Object.defineProperty(error, 'stack', { + value: stack, + writable: true, + enumerable: false, + configurable: true + }); + return error; + } + /** @public */ + function isSharedArrayBuffer(value) { + return ((typeof SharedArrayBuffer === 'function' && value instanceof SharedArrayBuffer) || + (Object.prototype.toString.call(value) === '[object SharedArrayBuffer]')); + } + /** @public */ + function isTrapError(e) { + try { + return e instanceof _WebAssembly.RuntimeError; + } + catch (_) { + return false; + } + } + + function createMessage(type, payload) { + return { + __emnapi__: { + type: type, + payload: payload + } + }; + } + + var WASI_THREADS_MAX_TID = 0x1FFFFFFF; + function checkSharedWasmMemory(wasmMemory) { + if (wasmMemory) { + if (!isSharedArrayBuffer(wasmMemory.buffer)) { + throw new Error('Multithread features require shared wasm memory. ' + + 'Try to compile with `-matomics -mbulk-memory` and use `--import-memory --shared-memory` during linking, ' + + 'then create WebAssembly.Memory with `shared: true` option'); + } + } + else { + if (typeof SharedArrayBuffer === 'undefined') { + throw new Error('Current environment does not support SharedArrayBuffer, threads are not available!'); + } + } + } + function getReuseWorker(value) { + var _a; + if (typeof value === 'boolean') { + return value ? { size: 0, strict: false } : false; + } + if (typeof value === 'number') { + if (!(value >= 0)) { + throw new RangeError('reuseWorker: size must be a non-negative integer'); + } + return { size: value, strict: false }; + } + if (!value) { + return false; + } + var size = (_a = Number(value.size)) !== null && _a !== void 0 ? _a : 0; + var strict = Boolean(value.strict); + if (!(size > 0) && strict) { + throw new RangeError('reuseWorker: size must be set to positive integer if strict is set to true'); + } + return { size: size, strict: strict }; + } + var nextWorkerID = 0; + /** @public */ + var ThreadManager = /*#__PURE__*/ (function () { + function ThreadManager(options) { + var _a; + this.unusedWorkers = []; + this.pthreads = Object.create(null); + this.wasmModule = null; + this.wasmMemory = null; + this.messageEvents = new WeakMap(); + if (!options) { + throw new TypeError('ThreadManager(): options is not provided'); + } + if ('childThread' in options) { + this._childThread = Boolean(options.childThread); + } + else { + this._childThread = false; + } + if (this._childThread) { + this._onCreateWorker = undefined; + this._reuseWorker = false; + this._beforeLoad = undefined; + } + else { + this._onCreateWorker = options.onCreateWorker; + this._reuseWorker = getReuseWorker(options.reuseWorker); + this._beforeLoad = options.beforeLoad; + } + this.printErr = (_a = options.printErr) !== null && _a !== void 0 ? _a : console.error.bind(console); + this.threadSpawn = options.threadSpawn; + } + Object.defineProperty(ThreadManager.prototype, "nextWorkerID", { + get: function () { return nextWorkerID; }, + enumerable: false, + configurable: true + }); + ThreadManager.prototype.init = function () { + if (!this._childThread) { + this.initMainThread(); + } + }; + ThreadManager.prototype.initMainThread = function () { + this.preparePool(); + }; + ThreadManager.prototype.preparePool = function () { + if (this._reuseWorker) { + if (this._reuseWorker.size) { + var pthreadPoolSize = this._reuseWorker.size; + while (pthreadPoolSize--) { + var worker = this.allocateUnusedWorker(); + if (ENVIRONMENT_IS_NODE) { + // https://github.com/nodejs/node/issues/53036 + worker.once('message', function () { }); + worker.unref(); + } + } + } + } + }; + ThreadManager.prototype.shouldPreloadWorkers = function () { + return !this._childThread && this._reuseWorker && this._reuseWorker.size > 0; + }; + ThreadManager.prototype.loadWasmModuleToAllWorkers = function () { + var _this_1 = this; + var promises = Array(this.unusedWorkers.length); + var _loop_1 = function (i) { + var worker = this_1.unusedWorkers[i]; + if (ENVIRONMENT_IS_NODE) + worker.ref(); + promises[i] = this_1.loadWasmModuleToWorker(worker).then(function (w) { + if (ENVIRONMENT_IS_NODE) + worker.unref(); + return w; + }, function (e) { + if (ENVIRONMENT_IS_NODE) + worker.unref(); + throw e; + }); + }; + var this_1 = this; + for (var i = 0; i < this.unusedWorkers.length; ++i) { + _loop_1(i); + } + return Promise.all(promises).catch(function (err) { + _this_1.terminateAllThreads(); + throw err; + }); + }; + ThreadManager.prototype.preloadWorkers = function () { + if (this.shouldPreloadWorkers()) { + return this.loadWasmModuleToAllWorkers(); + } + return Promise.resolve([]); + }; + ThreadManager.prototype.setup = function (wasmModule, wasmMemory) { + this.wasmModule = wasmModule; + this.wasmMemory = wasmMemory; + }; + ThreadManager.prototype.markId = function (worker) { + if (worker.__emnapi_tid) + return worker.__emnapi_tid; + var tid = nextWorkerID + 43; + nextWorkerID = (nextWorkerID + 1) % (WASI_THREADS_MAX_TID - 42); + this.pthreads[tid] = worker; + worker.__emnapi_tid = tid; + return tid; + }; + ThreadManager.prototype.returnWorkerToPool = function (worker) { + var tid = worker.__emnapi_tid; + if (tid !== undefined) { + delete this.pthreads[tid]; + } + this.unusedWorkers.push(worker); + delete worker.__emnapi_tid; + if (ENVIRONMENT_IS_NODE) { + worker.unref(); + } + }; + ThreadManager.prototype.loadWasmModuleToWorker = function (worker, sab) { + var _this_1 = this; + if (worker.whenLoaded) + return worker.whenLoaded; + var err = this.printErr; + var beforeLoad = this._beforeLoad; + // eslint-disable-next-line @typescript-eslint/no-this-alias + var _this = this; + worker.whenLoaded = new Promise(function (resolve, reject) { + var handleError = function (e) { + var message = 'worker sent an error!'; + if (worker.__emnapi_tid !== undefined) { + message = 'worker (tid = ' + worker.__emnapi_tid + ') sent an error!'; + } + if ('message' in e) { + err(message + ' ' + e.message); + if (e.message.indexOf('RuntimeError') !== -1 || e.message.indexOf('unreachable') !== -1) { + try { + _this.terminateAllThreads(); + } + catch (_) { } + } + } + else { + err(message); + } + reject(e); + throw e; + }; + var handleMessage = function (data) { + if (data.__emnapi__) { + var type = data.__emnapi__.type; + var payload = data.__emnapi__.payload; + if (type === 'loaded') { + worker.loaded = true; + if (ENVIRONMENT_IS_NODE && !worker.__emnapi_tid) { + worker.unref(); + } + resolve(worker); + // if (payload.err) { + // err('failed to load in child thread: ' + (payload.err.message || payload.err)) + // } + } + else if (type === 'cleanup-thread') { + if (payload.tid in _this_1.pthreads) { + _this_1.cleanThread(worker, payload.tid); + } + } + else if (type === 'spawn-thread') { + _this_1.threadSpawn(payload.startArg, payload.errorOrTid); + } + else if (type === 'terminate-all-threads') { + _this_1.terminateAllThreads(); + } + } + }; + worker.onmessage = function (e) { + handleMessage(e.data); + _this_1.fireMessageEvent(worker, e); + }; + worker.onerror = handleError; + if (ENVIRONMENT_IS_NODE) { + worker.on('message', function (data) { + var _a, _b; + (_b = (_a = worker).onmessage) === null || _b === void 0 ? void 0 : _b.call(_a, { + data: data + }); + }); + worker.on('error', function (e) { + var _a, _b; + (_b = (_a = worker).onerror) === null || _b === void 0 ? void 0 : _b.call(_a, e); + }); + worker.on('detachedExit', function () { }); + } + if (typeof beforeLoad === 'function') { + beforeLoad(worker); + } + try { + worker.postMessage(createMessage('load', { + wasmModule: _this_1.wasmModule, + wasmMemory: _this_1.wasmMemory, + sab: sab + })); + } + catch (err) { + checkSharedWasmMemory(_this_1.wasmMemory); + throw err; + } + }); + return worker.whenLoaded; + }; + ThreadManager.prototype.allocateUnusedWorker = function () { + var _onCreateWorker = this._onCreateWorker; + if (typeof _onCreateWorker !== 'function') { + throw new TypeError('`options.onCreateWorker` is not provided'); + } + var worker = _onCreateWorker({ type: 'thread', name: 'emnapi-pthread' }); + this.unusedWorkers.push(worker); + return worker; + }; + ThreadManager.prototype.getNewWorker = function (sab) { + if (this._reuseWorker) { + if (this.unusedWorkers.length === 0) { + if (this._reuseWorker.strict) { + if (!ENVIRONMENT_IS_NODE) { + var err = this.printErr; + err('Tried to spawn a new thread, but the thread pool is exhausted.\n' + + 'This might result in a deadlock unless some threads eventually exit or the code explicitly breaks out to the event loop.'); + return; + } + } + var worker_1 = this.allocateUnusedWorker(); + // eslint-disable-next-line @typescript-eslint/no-floating-promises + this.loadWasmModuleToWorker(worker_1, sab); + } + return this.unusedWorkers.pop(); + } + var worker = this.allocateUnusedWorker(); + // eslint-disable-next-line @typescript-eslint/no-floating-promises + this.loadWasmModuleToWorker(worker, sab); + return this.unusedWorkers.pop(); + }; + ThreadManager.prototype.cleanThread = function (worker, tid, force) { + if (!force && this._reuseWorker) { + this.returnWorkerToPool(worker); + } + else { + delete this.pthreads[tid]; + this.terminateWorker(worker); + delete worker.__emnapi_tid; + } + }; + ThreadManager.prototype.terminateWorker = function (worker) { + var _this_1 = this; + var _a; + var tid = worker.__emnapi_tid; + // eslint-disable-next-line @typescript-eslint/no-floating-promises + worker.terminate(); + (_a = this.messageEvents.get(worker)) === null || _a === void 0 ? void 0 : _a.clear(); + this.messageEvents.delete(worker); + worker.onmessage = function (e) { + if (e.data.__emnapi__) { + var err = _this_1.printErr; + err('received "' + e.data.__emnapi__.type + '" command from terminated worker: ' + tid); + } + }; + }; + ThreadManager.prototype.terminateAllThreads = function () { + var runningWorkers = Object.values(this.pthreads); + for (var i = 0; i < runningWorkers.length; ++i) { + this.terminateWorker(runningWorkers[i]); + } + for (var i = 0; i < this.unusedWorkers.length; ++i) { + this.terminateWorker(this.unusedWorkers[i]); + } + this.unusedWorkers = []; + this.pthreads = Object.create(null); + this.preparePool(); + }; + ThreadManager.prototype.addMessageEventListener = function (worker, onMessage) { + var listeners = this.messageEvents.get(worker); + if (!listeners) { + listeners = new Set(); + this.messageEvents.set(worker, listeners); + } + listeners.add(onMessage); + return function () { + listeners === null || listeners === void 0 ? void 0 : listeners.delete(onMessage); + }; + }; + ThreadManager.prototype.fireMessageEvent = function (worker, e) { + var listeners = this.messageEvents.get(worker); + if (!listeners) + return; + var err = this.printErr; + listeners.forEach(function (listener) { + try { + listener(e); + } + catch (e) { + err(e.stack); + } + }); + }; + return ThreadManager; + }()); + + var kIsProxy = Symbol('kIsProxy'); + /** @public */ + function createInstanceProxy(instance, memory) { + if (instance[kIsProxy]) + return instance; + // https://github.com/nodejs/help/issues/4102 + var originalExports = instance.exports; + var createHandler = function (target) { + var handlers = [ + 'apply', + 'construct', + 'defineProperty', + 'deleteProperty', + 'get', + 'getOwnPropertyDescriptor', + 'getPrototypeOf', + 'has', + 'isExtensible', + 'ownKeys', + 'preventExtensions', + 'set', + 'setPrototypeOf' + ]; + var handler = {}; + var _loop_1 = function (i) { + var name_1 = handlers[i]; + handler[name_1] = function () { + var args = Array.prototype.slice.call(arguments, 1); + args.unshift(target); + return Reflect[name_1].apply(Reflect, args); + }; + }; + for (var i = 0; i < handlers.length; i++) { + _loop_1(i); + } + return handler; + }; + var handler = createHandler(originalExports); + var _initialize = function () { }; + var _start = function () { return 0; }; + handler.get = function (_target, p, receiver) { + var _a; + if (p === 'memory') { + return (_a = (typeof memory === 'function' ? memory() : memory)) !== null && _a !== void 0 ? _a : Reflect.get(originalExports, p, receiver); + } + if (p === '_initialize') { + return p in originalExports ? _initialize : undefined; + } + if (p === '_start') { + return p in originalExports ? _start : undefined; + } + return Reflect.get(originalExports, p, receiver); + }; + handler.has = function (_target, p) { + if (p === 'memory') + return true; + return Reflect.has(originalExports, p); + }; + var exportsProxy = new Proxy(Object.create(null), handler); + return new Proxy(instance, { + get: function (target, p, receiver) { + if (p === 'exports') { + return exportsProxy; + } + if (p === kIsProxy) { + return true; + } + return Reflect.get(target, p, receiver); + } + }); + } + + var patchedWasiInstances = new WeakMap(); + var THREAD_SPAWN_RESULT_SIZE = Int32Array.BYTES_PER_ELEMENT * 2; + // Intrinsic SharedArrayBuffer.prototype.byteLength getter: it reads the + // internal slot, so it is a conclusive brand check that a spoofed own + // Symbol.toStringTag (which fools Object.prototype.toString) cannot satisfy. + var sharedArrayBufferByteLength = typeof SharedArrayBuffer === 'function' + ? Object.getOwnPropertyDescriptor(SharedArrayBuffer.prototype, 'byteLength').get + : undefined; + function isConclusivelySharedArrayBuffer(buffer) { + if (sharedArrayBufferByteLength === undefined) + return false; + try { + sharedArrayBufferByteLength.call(buffer); + return true; + } + catch (_) { + return false; + } + } + function getThreadSpawnResultView(memory, address, wasm64) { + // The result pointer arrives across the wasm ABI: an i64 (memory64) address + // is a bigint, and an upper-half i32 address is a negative Number. Normalize + // it the way malloc results are normalized elsewhere in this file. + var offset = typeof address === 'bigint' ? Number(address) : address >>> 0; + var buffer = memory.buffer; + if (offset + THREAD_SPAWN_RESULT_SIZE > buffer.byteLength && + // Only refresh shared memory. A conclusive brand check is required here: + // grow(0) detaches an *unshared* buffer (spec: even at delta 0), so a + // spoofed 'SharedArrayBuffer' tag must never be allowed to reach it. + isConclusivelySharedArrayBuffer(buffer)) { + // Another agent may have grown shared memory while this agent still sees + // the previous shorter buffer. A zero-page grow refreshes the local view + // without changing the memory size. + if (wasm64) { + memory.grow(BigInt(0)); + } + else { + memory.grow(0); + } + buffer = memory.buffer; + } + return new Int32Array(buffer, offset, 2); + } + /** @public */ + var WASIThreads = /*#__PURE__*/ (function () { + function WASIThreads(options) { + var _this_1 = this; + if (!options) { + throw new TypeError('WASIThreads(): options is not provided'); + } + if (!options.wasi) { + throw new TypeError('WASIThreads(): options.wasi is not provided'); + } + patchedWasiInstances.set(this, new WeakSet()); + var wasi = options.wasi; + patchWasiInstance(this, wasi); + this.wasi = wasi; + if ('childThread' in options) { + this.childThread = Boolean(options.childThread); + } + else { + this.childThread = false; + } + this.PThread = undefined; + if ('threadManager' in options) { + if (typeof options.threadManager === 'function') { + this.PThread = options.threadManager(); + } + else { + this.PThread = options.threadManager; + } + } + else { + if (!this.childThread) { + this.PThread = new ThreadManager(options); + this.PThread.init(); + } + } + var waitThreadStart = false; + if ('waitThreadStart' in options) { + waitThreadStart = typeof options.waitThreadStart === 'number' ? options.waitThreadStart : Boolean(options.waitThreadStart); + } + var postMessage = getPostMessage(options); + if (this.childThread && typeof postMessage !== 'function') { + throw new TypeError('options.postMessage is not a function'); + } + this.postMessage = postMessage; + var wasm64 = Boolean(options.wasm64); + var threadSpawn = function (startArg, errorOrTid) { + var _a; + var EAGAIN = 6; + var isNewABI = errorOrTid !== undefined; + try { + checkSharedWasmMemory(_this_1.wasmMemory); + } + catch (err) { + (_a = _this_1.PThread) === null || _a === void 0 ? void 0 : _a.printErr(err.stack); + if (isNewABI) { + var struct_1 = getThreadSpawnResultView(_this_1.wasmMemory, errorOrTid, wasm64); + Atomics.store(struct_1, 0, 1); + Atomics.store(struct_1, 1, EAGAIN); + Atomics.notify(struct_1, 1); + return 1; + } + else { + return -EAGAIN; + } + } + if (!isNewABI) { + var malloc = _this_1.wasmInstance.exports.malloc; + errorOrTid = wasm64 ? Number(malloc(BigInt(8))) : (malloc(8) >>> 0); + if (!errorOrTid) { + return -48; /* ENOMEM */ + } + } + var _free = _this_1.wasmInstance.exports.free; + var free = wasm64 ? function (ptr) { _free(BigInt(ptr)); } : _free; + var struct = getThreadSpawnResultView(_this_1.wasmMemory, errorOrTid, wasm64); + Atomics.store(struct, 0, 0); + Atomics.store(struct, 1, 0); + if (_this_1.childThread) { + postMessage(createMessage('spawn-thread', { + startArg: startArg, + errorOrTid: errorOrTid + })); + Atomics.wait(struct, 1, 0); + var isError = Atomics.load(struct, 0); + var result = Atomics.load(struct, 1); + if (isNewABI) { + return isError; + } + free(errorOrTid); + return isError ? -result : result; + } + var shouldWait = waitThreadStart || (waitThreadStart === 0); + var sab; + if (shouldWait) { + sab = new Int32Array(new SharedArrayBuffer(16 + 8192)); + Atomics.store(sab, 0, 0); + } + var worker; + var tid; + var PThread = _this_1.PThread; + try { + worker = PThread.getNewWorker(sab); + if (!worker) { + throw new Error('failed to get new worker'); + } + tid = PThread.markId(worker); + if (ENVIRONMENT_IS_NODE) { + worker.unref(); + } + worker.postMessage(createMessage('start', { + tid: tid, + arg: startArg, + sab: sab + })); + if (shouldWait) { + if (typeof waitThreadStart === 'number') { + var waitResult = Atomics.wait(sab, 0, 0, waitThreadStart); + if (waitResult === 'timed-out') { + throw new Error('Spawning thread timed out. Please check if the worker is created successfully and if message is handled properly in the worker.'); + } + } + else { + Atomics.wait(sab, 0, 0); + } + var r = Atomics.load(sab, 0); + if (r > 1) { + throw deserizeErrorFromBuffer(sab.buffer); + } + } + } + catch (e) { + if (worker !== undefined && tid !== undefined) { + try { + PThread.cleanThread(worker, tid, true); + } + catch (_) { } + } + Atomics.store(struct, 0, 1); + Atomics.store(struct, 1, EAGAIN); + Atomics.notify(struct, 1); + PThread === null || PThread === void 0 ? void 0 : PThread.printErr(e.stack); + if (isNewABI) { + return 1; + } + free(errorOrTid); + return -EAGAIN; + } + Atomics.store(struct, 0, 0); + Atomics.store(struct, 1, tid); + Atomics.notify(struct, 1); + if (!shouldWait) { + worker.whenLoaded.catch(function (err) { + delete worker.whenLoaded; + PThread.cleanThread(worker, tid, true); + throw err; + }); + } + if (isNewABI) { + return 0; + } + free(errorOrTid); + return tid; + }; + this.threadSpawn = threadSpawn; + if (this.PThread) { + this.PThread.threadSpawn = threadSpawn; + } + } + WASIThreads.prototype.getImportObject = function () { + return { + wasi: { + 'thread-spawn': this.threadSpawn + } + }; + }; + WASIThreads.prototype.setup = function (wasmInstance, wasmModule, wasmMemory) { + wasmMemory !== null && wasmMemory !== void 0 ? wasmMemory : (wasmMemory = wasmInstance.exports.memory); + this.wasmInstance = wasmInstance; + this.wasmMemory = wasmMemory; + if (this.PThread) { + this.PThread.setup(wasmModule, wasmMemory); + } + }; + WASIThreads.prototype.preloadWorkers = function () { + if (this.PThread) { + return this.PThread.preloadWorkers(); + } + return Promise.resolve([]); + }; + /** + * It's ok to call this method to a WASI command module. + * + * in child thread, must call this method instead of {@link WASIThreads.start} even if it's a WASI command module + * + * @returns A proxied WebAssembly instance if in child thread, other wise the original instance + */ + WASIThreads.prototype.initialize = function (instance, module, memory) { + var exports = instance.exports; + memory !== null && memory !== void 0 ? memory : (memory = exports.memory); + if (this.childThread) { + instance = createInstanceProxy(instance, memory); + } + this.setup(instance, module, memory); + var wasi = this.wasi; + if (('_start' in exports) && (typeof exports._start === 'function')) { + if (this.childThread) { + wasi.start(instance); + try { + var kStarted = getWasiSymbol(wasi, 'kStarted'); + wasi[kStarted] = false; + } + catch (_) { } + } + else { + setupInstance(wasi, instance); + } + } + else { + wasi.initialize(instance); + } + return instance; + }; + /** + * Equivalent to calling {@link WASIThreads.initialize} and then calling {@link WASIInstance.start} + * ```js + * this.initialize(instance, module, memory) + * this.wasi.start(instance) + * ``` + */ + WASIThreads.prototype.start = function (instance, module, memory) { + var exports = instance.exports; + memory !== null && memory !== void 0 ? memory : (memory = exports.memory); + if (this.childThread) { + instance = createInstanceProxy(instance, memory); + } + this.setup(instance, module, memory); + var exitCode = this.wasi.start(instance); + return { exitCode: exitCode, instance: instance }; + }; + WASIThreads.prototype.terminateAllThreads = function () { + var _a; + if (!this.childThread) { + (_a = this.PThread) === null || _a === void 0 ? void 0 : _a.terminateAllThreads(); + } + else { + this.postMessage(createMessage('terminate-all-threads', {})); + } + }; + return WASIThreads; + }()); + function patchWasiInstance(wasiThreads, wasi) { + var patched = patchedWasiInstances.get(wasiThreads); + if (patched.has(wasi)) { + return; + } + var _this = wasiThreads; + var wasiImport = wasi.wasiImport; + if (wasiImport) { + var proc_exit_1 = wasiImport.proc_exit; + wasiImport.proc_exit = function (code) { + _this.terminateAllThreads(); + return proc_exit_1.call(this, code); + }; + } + if (!_this.childThread) { + var start_1 = wasi.start; + if (typeof start_1 === 'function') { + wasi.start = function (instance) { + try { + return start_1.call(this, instance); + } + catch (err) { + if (isTrapError(err)) { + _this.terminateAllThreads(); + } + throw err; + } + }; + } + } + patched.add(wasi); + } + function getWasiSymbol(wasi, description) { + var symbols = Object.getOwnPropertySymbols(wasi); + var selectDescription = function (description) { return function (s) { + if (s.description) { + return s.description === description; + } + return s.toString() === "Symbol(".concat(description, ")"); + }; }; + if (Array.isArray(description)) { + return description.map(function (d) { return symbols.filter(selectDescription(d))[0]; }); + } + return symbols.filter(selectDescription(description))[0]; + } + function setupInstance(wasi, instance) { + var _a = getWasiSymbol(wasi, ['kInstance', 'kSetMemory']), kInstance = _a[0], kSetMemory = _a[1]; + wasi[kInstance] = instance; + wasi[kSetMemory](instance.exports.memory); + } + + /** @public */ + var ThreadMessageHandler = /*#__PURE__*/ (function () { + function ThreadMessageHandler(options) { + var postMsg = getPostMessage(options); + if (typeof postMsg !== 'function') { + throw new TypeError('options.postMessage is not a function'); + } + this.postMessage = postMsg; + this.onLoad = options === null || options === void 0 ? void 0 : options.onLoad; + this.onError = typeof (options === null || options === void 0 ? void 0 : options.onError) === 'function' ? options.onError : function (_type, err) { throw err; }; + this.instance = undefined; + // this.module = undefined + this.messagesBeforeLoad = []; + } + /** @virtual */ + ThreadMessageHandler.prototype.instantiate = function (data) { + if (typeof this.onLoad === 'function') { + return this.onLoad(data); + } + throw new Error('ThreadMessageHandler.prototype.instantiate is not implemented'); + }; + /** @virtual */ + ThreadMessageHandler.prototype.handle = function (e) { + var _this = this; + var _a; + if ((_a = e === null || e === void 0 ? void 0 : e.data) === null || _a === void 0 ? void 0 : _a.__emnapi__) { + var type = e.data.__emnapi__.type; + var payload_1 = e.data.__emnapi__.payload; + try { + if (type === 'load') { + this._load(payload_1); + } + else if (type === 'start') { + this.handleAfterLoad(e, function () { + _this._start(payload_1); + }); + } + } + catch (err) { + this.onError(err, type); + } + } + }; + ThreadMessageHandler.prototype._load = function (payload) { + var _this = this; + if (this.instance !== undefined) + return; + var source; + try { + source = this.instantiate(payload); + } + catch (err) { + this._loaded(err, null, payload); + return; + } + var then = source && 'then' in source ? source.then : undefined; + if (typeof then === 'function') { + // eslint-disable-next-line @typescript-eslint/no-floating-promises + then.call(source, function (source) { _this._loaded(null, source, payload); }, function (err) { _this._loaded(err, null, payload); }); + } + else { + this._loaded(null, source, payload); + } + }; + ThreadMessageHandler.prototype._start = function (payload) { + var wasi_thread_start = this.instance.exports.wasi_thread_start; + if (typeof wasi_thread_start !== 'function') { + var err = new TypeError('wasi_thread_start is not exported'); + notifyPthreadCreateResult(payload.sab, 2, err); + throw err; + } + var postMessage = this.postMessage; + var tid = payload.tid; + var startArg = payload.arg; + notifyPthreadCreateResult(payload.sab, 1); + try { + wasi_thread_start(tid, startArg); + } + catch (err) { + if (err !== 'unwind') { + throw err; + } + else { + return; + } + } + postMessage(createMessage('cleanup-thread', { tid: tid })); + }; + ThreadMessageHandler.prototype._loaded = function (err, source, payload) { + if (err) { + notifyPthreadCreateResult(payload.sab, 2, err); + throw err; + } + if (source == null) { + var err_1 = new TypeError('onLoad should return an object'); + notifyPthreadCreateResult(payload.sab, 2, err_1); + throw err_1; + } + var instance = source.instance; + if (!instance) { + var err_2 = new TypeError('onLoad should return an object which includes "instance"'); + notifyPthreadCreateResult(payload.sab, 2, err_2); + throw err_2; + } + this.instance = instance; + var postMessage = this.postMessage; + postMessage(createMessage('loaded', {})); + var messages = this.messagesBeforeLoad; + this.messagesBeforeLoad = []; + for (var i = 0; i < messages.length; i++) { + var data = messages[i]; + this.handle({ data: data }); + } + }; + ThreadMessageHandler.prototype.handleAfterLoad = function (e, f) { + if (this.instance !== undefined) { + f.call(this, e); + } + else { + this.messagesBeforeLoad.push(e.data); + } + }; + return ThreadMessageHandler; + }()); + function notifyPthreadCreateResult(sab, result, error) { + if (sab) { + serizeErrorToBuffer(sab.buffer, result, error); + Atomics.notify(sab, 0); + } + } + + function createNapiModule(options) { + var napiModule = (function () { + var ENVIRONMENT_IS_NODE = typeof process === 'object' && process !== null && typeof process.versions === 'object' && process.versions !== null && typeof process.versions.node === 'string'; + var ENVIRONMENT_IS_PTHREAD = Boolean(options.childThread); + var waitThreadStart = typeof options.waitThreadStart === 'number' ? options.waitThreadStart : Boolean(options.waitThreadStart); + var wasmInstance; + var wasmMemory; + var wasmTable; + var _malloc; + var _free; + function abort(msg) { + if (typeof _WebAssembly$1.RuntimeError === 'function') { + throw new _WebAssembly$1.RuntimeError(msg); + } + throw Error(msg); + } + var napiModule = { + imports: { + env: {}, + napi: {}, + emnapi: {} + }, + exports: {}, + emnapi: {}, + loaded: false, + filename: '', + childThread: ENVIRONMENT_IS_PTHREAD, + initWorker: undefined, + waitThreadStart: waitThreadStart, + PThread: undefined, + init: function (options) { + if (napiModule.loaded) + return napiModule.exports; + if (!options) + throw new TypeError('Invalid napi init options'); + var instance = options.instance; + if (!(instance === null || instance === void 0 ? void 0 : instance.exports)) + throw new TypeError('Invalid wasm instance'); + wasmInstance = instance; + var exports = instance.exports; + var module = options.module; + var memory = options.memory || exports.memory; + var table = options.table || exports.__indirect_function_table; + if (!(module instanceof _WebAssembly$1.Module)) + throw new TypeError('Invalid wasm module'); + if (!(memory instanceof _WebAssembly$1.Memory)) + throw new TypeError('Invalid wasm memory'); + if (!(table instanceof _WebAssembly$1.Table)) + throw new TypeError('Invalid wasm table'); + wasmMemory = memory; + wasmTable = table; + if (typeof exports.malloc !== 'function') + throw new TypeError('malloc is not exported'); + if (typeof exports.free !== 'function') + throw new TypeError('free is not exported'); + _malloc = exports.malloc; + _free = exports.free; + if (!napiModule.childThread) { + // main thread only + var moduleApiVersion = 8 /* Version.NODE_API_DEFAULT_MODULE_API_VERSION */; + var node_api_module_get_api_version_v1 = instance.exports.node_api_module_get_api_version_v1; + if (typeof node_api_module_get_api_version_v1 === 'function') { + moduleApiVersion = node_api_module_get_api_version_v1(); + } + // eslint-disable-next-line @typescript-eslint/prefer-nullish-coalescing + var envObject = napiModule.envObject || (napiModule.envObject = emnapiCtx.createEnv(napiModule.filename, moduleApiVersion, function (cb) { return (wasmTable.get(cb)); }, function (cb) { return (wasmTable.get(cb)); }, abort, emnapiNodeBinding)); + var scope_1 = emnapiCtx.openScope(envObject); + try { + envObject.callIntoModule(function (_envObject) { + var exports = napiModule.exports; + var exportsHandle = scope_1.add(exports); + var napi_register_wasm_v1 = instance.exports.napi_register_wasm_v1; + var napiValue = napi_register_wasm_v1(_envObject.id, exportsHandle.id); + napiModule.exports = (!napiValue) ? exports : emnapiCtx.handleStore.get(napiValue).value; + }); + } + catch (e) { + if (e !== 'unwind') { + throw e; + } + } + finally { + emnapiCtx.closeScope(envObject, scope_1); + } + napiModule.loaded = true; + delete napiModule.envObject; + return napiModule.exports; + } + } + }; + var emnapiCtx; + var emnapiNodeBinding; + var onCreateWorker = undefined; + var err; + if (!ENVIRONMENT_IS_PTHREAD) { + var context = options.context; + if (typeof context !== 'object' || context === null) { + throw new TypeError("Invalid `options.context`. Use `import { getDefaultContext } from '@emnapi/runtime'`"); + } + emnapiCtx = context; + } + else { + emnapiCtx = options === null || options === void 0 ? void 0 : options.context; + var postMsg = typeof options.postMessage === 'function' + ? options.postMessage + : typeof postMessage === 'function' + ? postMessage + : undefined; + if (typeof postMsg !== 'function') { + throw new TypeError('No postMessage found'); + } + napiModule.postMessage = postMsg; + } + if (typeof options.filename === 'string') { + napiModule.filename = options.filename; + } + if (typeof options.onCreateWorker === 'function') { + onCreateWorker = options.onCreateWorker; + } + if (typeof options.print === 'function') { + options.print; + } + else { + console.log.bind(console); + } + if (typeof options.printErr === 'function') { + err = options.printErr; + } + else { + err = console.warn.bind(console); + } + if ('nodeBinding' in options) { + var nodeBinding = options.nodeBinding; + if (typeof nodeBinding !== 'object' || nodeBinding === null) { + throw new TypeError('Invalid `options.nodeBinding`. Use @emnapi/node-binding package'); + } + emnapiNodeBinding = nodeBinding; + } + var emnapiAsyncWorkPoolSize = 0; + if ('asyncWorkPoolSize' in options) { + if (typeof options.asyncWorkPoolSize !== 'number') { + throw new TypeError('options.asyncWorkPoolSize must be a integer'); + } + emnapiAsyncWorkPoolSize = options.asyncWorkPoolSize >> 0; + if (emnapiAsyncWorkPoolSize > 1024) { + emnapiAsyncWorkPoolSize = 1024; + } + else if (emnapiAsyncWorkPoolSize < -1024) { + emnapiAsyncWorkPoolSize = -1024; + } + } + var singleThreadAsyncWork = ENVIRONMENT_IS_PTHREAD ? false : (emnapiAsyncWorkPoolSize <= 0); + function _emnapi_async_work_pool_size() { + return Math.abs(emnapiAsyncWorkPoolSize); + } + napiModule.imports.env._emnapi_async_work_pool_size = _emnapi_async_work_pool_size; + // ------------------------------ pthread ------------------------------- + function emnapiAddSendListener(worker) { + if (!worker) + return false; + if (worker._emnapiSendListener) + return true; + var handler = function (e) { + var data = ENVIRONMENT_IS_NODE ? e : e.data; + var __emnapi__ = data.__emnapi__; + if (__emnapi__ && __emnapi__.type === 'async-send') { + if (ENVIRONMENT_IS_PTHREAD) { + var postMessage_1 = napiModule.postMessage; + postMessage_1({ __emnapi__: __emnapi__ }); + } + else { + // eslint-disable-next-line @typescript-eslint/no-unused-vars + var callback = __emnapi__.payload.callback; + (wasmTable.get(callback))(__emnapi__.payload.data); + } + } + }; + var dispose = function () { + if (ENVIRONMENT_IS_NODE) { + worker.off('message', handler); + } + else { + worker.removeEventListener('message', handler, false); + } + delete worker._emnapiSendListener; + }; + worker._emnapiSendListener = { handler: handler, dispose: dispose }; + if (ENVIRONMENT_IS_NODE) { + worker.on('message', handler); + } + else { + worker.addEventListener('message', handler, false); + } + return true; + } + napiModule.emnapi.addSendListener = emnapiAddSendListener; + var PThread = new ThreadManager(ENVIRONMENT_IS_PTHREAD + ? { + printErr: err, + childThread: true + } + : { + printErr: err, + beforeLoad: function (worker) { + emnapiAddSendListener(worker); + }, + reuseWorker: options.reuseWorker, + onCreateWorker: onCreateWorker + }); + napiModule.PThread = PThread; + /** + * @__sig ipiip + */ + function napi_set_last_error(env, error_code, engine_error_code, engine_reserved) { + var envObject = emnapiCtx.envStore.get(env); + return envObject.setLastError(error_code, engine_error_code, engine_reserved); + } + /** + * @__sig ip + */ + function napi_clear_last_error(env) { + var envObject = emnapiCtx.envStore.get(env); + return envObject.clearLastError(); + } + /** + * @__sig vppp + */ + function _emnapi_get_node_version(major, minor, patch) { + major >>>= 0; + minor >>>= 0; + patch >>>= 0; + // eslint-disable-next-line @typescript-eslint/no-unused-vars + var versions = (typeof process === 'object' && process !== null && + typeof process.versions === 'object' && process.versions !== null && + typeof process.versions.node === 'string') + ? process.versions.node.split('.').map(function (n) { return Number(n); }) + : [0, 0, 0]; + var HEAP_DATA_VIEW = new DataView(wasmMemory.buffer), GET_HEAP_DATA_VIEW = function () { return HEAP_DATA_VIEW.buffer === wasmMemory.buffer ? HEAP_DATA_VIEW : (HEAP_DATA_VIEW = new DataView(wasmMemory.buffer)); }; + GET_HEAP_DATA_VIEW().setUint32(major, versions[0], true); + GET_HEAP_DATA_VIEW().setUint32(minor, versions[1], true); + GET_HEAP_DATA_VIEW().setUint32(patch, versions[2], true); + } + /** + * @__sig v + * @__deps $runtimeKeepalivePush + */ + function _emnapi_runtime_keepalive_push() { + } + /** + * @__sig v + * @__deps $runtimeKeepalivePop + */ + function _emnapi_runtime_keepalive_pop() { + } + /** + * @__sig vpp + */ + function _emnapi_set_immediate(callback, data) { + emnapiCtx.feature.setImmediate(function () { + (wasmTable.get(callback))(data); + }); + } + /** + * @__sig vpp + */ + function _emnapi_next_tick(callback, data) { + // eslint-disable-next-line @typescript-eslint/no-floating-promises + Promise.resolve().then(function () { + (wasmTable.get(callback))(data); + }); + } + /** + * @__sig vipppi + */ + function _emnapi_callback_into_module(forceUncaught, env, callback, data, close_scope_if_throw) { + var envObject = emnapiCtx.envStore.get(env); + var scope = emnapiCtx.openScope(envObject); + try { + envObject.callbackIntoModule(Boolean(forceUncaught), function () { + (wasmTable.get(callback))(env, data); + }); + } + catch (err) { + emnapiCtx.closeScope(envObject, scope); + if (close_scope_if_throw) { + emnapiCtx.closeScope(envObject); + } + throw err; + } + emnapiCtx.closeScope(envObject, scope); + } + /** + * @__sig vipppp + */ + function _emnapi_call_finalizer(forceUncaught, env, callback, data, hint) { + var envObject = emnapiCtx.envStore.get(env); + callback >>>= 0; + envObject.callFinalizerInternal(forceUncaught, callback, data, hint); + } + /** + * @__sig v + */ + function _emnapi_ctx_increase_waiting_request_counter() { + emnapiCtx.increaseWaitingRequestCounter(); + } + /** + * @__sig v + */ + function _emnapi_ctx_decrease_waiting_request_counter() { + emnapiCtx.decreaseWaitingRequestCounter(); + } + /** + * @__sig i + */ + function _emnapi_is_main_runtime_thread() { + return ENVIRONMENT_IS_PTHREAD ? 0 : 1; + } + /** + * @__sig i + */ + function _emnapi_is_main_browser_thread() { + return (typeof window !== 'undefined' && typeof document !== 'undefined' && !ENVIRONMENT_IS_NODE) ? 1 : 0; + } + /** + * @__sig v + */ + function _emnapi_unwind() { + // eslint-disable-next-line @typescript-eslint/no-throw-literal + throw 'unwind'; + } + /** + * @__sig d + */ + function _emnapi_get_now() { + return performance.timeOrigin + performance.now(); + } + function $emnapiSetValueI64(result, numberValue) { + var tempDouble; + // eslint-disable-next-line @typescript-eslint/no-unused-vars + var tempI64 = [ + numberValue >>> 0, + (tempDouble = numberValue, +Math.abs(tempDouble) >= 1 ? tempDouble > 0 ? (Math.min(+Math.floor(tempDouble / 4294967296), 4294967295) | 0) >>> 0 : ~~+Math.ceil((tempDouble - +(~~tempDouble >>> 0)) / 4294967296) >>> 0 : 0) + ]; + var HEAP_DATA_VIEW = new DataView(wasmMemory.buffer), GET_HEAP_DATA_VIEW = function () { return HEAP_DATA_VIEW.buffer === wasmMemory.buffer ? HEAP_DATA_VIEW : (HEAP_DATA_VIEW = new DataView(wasmMemory.buffer)); }; + GET_HEAP_DATA_VIEW().setInt32(result, tempI64[0], true); + GET_HEAP_DATA_VIEW().setInt32(result + 4, tempI64[1], true); + } + /** + * @__deps $emnapiCtx + * @__sig p + */ + function _emnapi_open_handle_scope() { + return emnapiCtx.openScope().id; + } + /** + * @__deps $emnapiCtx + * @__sig vp + */ + function _emnapi_close_handle_scope(_scope) { + return emnapiCtx.closeScope(); + } + var utilMod = /*#__PURE__*/ Object.freeze({ + __proto__: null, + $emnapiSetValueI64: $emnapiSetValueI64, + _emnapi_call_finalizer: _emnapi_call_finalizer, + _emnapi_callback_into_module: _emnapi_callback_into_module, + _emnapi_close_handle_scope: _emnapi_close_handle_scope, + _emnapi_ctx_decrease_waiting_request_counter: _emnapi_ctx_decrease_waiting_request_counter, + _emnapi_ctx_increase_waiting_request_counter: _emnapi_ctx_increase_waiting_request_counter, + _emnapi_get_node_version: _emnapi_get_node_version, + _emnapi_get_now: _emnapi_get_now, + _emnapi_is_main_browser_thread: _emnapi_is_main_browser_thread, + _emnapi_is_main_runtime_thread: _emnapi_is_main_runtime_thread, + _emnapi_next_tick: _emnapi_next_tick, + _emnapi_open_handle_scope: _emnapi_open_handle_scope, + _emnapi_runtime_keepalive_pop: _emnapi_runtime_keepalive_pop, + _emnapi_runtime_keepalive_push: _emnapi_runtime_keepalive_push, + _emnapi_set_immediate: _emnapi_set_immediate, + _emnapi_unwind: _emnapi_unwind, + napi_clear_last_error: napi_clear_last_error, + napi_set_last_error: napi_set_last_error + }); + function emnapiGetWorkerByPthreadPtr(pthreadPtr) { + var view = new DataView(wasmMemory.buffer); + /** + * wasi-sdk-20.0+threads + * + * struct pthread { + * struct pthread *self; // 0 + * struct pthread *prev, *next; // 4, 8 + * uintptr_t sysinfo; // 12 + * uintptr_t canary; // 16 + * int tid; // 20 + * // ... + * } + */ + var tidOffset = 20; + var tid = view.getInt32(pthreadPtr + tidOffset, true); + var worker = PThread.pthreads[tid]; + return worker; + } + /** @__sig vp */ + function _emnapi_worker_ref(pthreadPtr) { + if (ENVIRONMENT_IS_PTHREAD) + return; + pthreadPtr >>>= 0; + var worker = emnapiGetWorkerByPthreadPtr(pthreadPtr); + if (worker && typeof worker.ref === 'function') { + worker.ref(); + } + } + /** @__sig vp */ + function _emnapi_worker_unref(pthreadPtr) { + if (ENVIRONMENT_IS_PTHREAD) + return; + pthreadPtr >>>= 0; + var worker = emnapiGetWorkerByPthreadPtr(pthreadPtr); + if (worker && typeof worker.unref === 'function') { + worker.unref(); + } + } + /** @__sig vipp */ + function _emnapi_async_send_js(type, callback, data) { + if (ENVIRONMENT_IS_PTHREAD) { + var postMessage_1 = napiModule.postMessage; + postMessage_1({ + __emnapi__: { + type: 'async-send', + payload: { + callback: callback, + data: data + } + } + }); + } + else { + switch (type) { + case 0: + _emnapi_set_immediate(callback, data); + break; + case 1: + _emnapi_next_tick(callback, data); + break; + } + } + } + // function ptrToString (ptr: number): string { + // return '0x' + ('00000000' + ptr.toString(16)).slice(-8) + // } + var uvThreadpoolReadyResolve; + var uvThreadpoolReady = new Promise(function (resolve) { + uvThreadpoolReadyResolve = function () { + uvThreadpoolReady.ready = true; + resolve(); + }; + }); + uvThreadpoolReady.ready = false; + /** @__sig vppi */ + function _emnapi_after_uvthreadpool_ready(callback, q, type) { + if (uvThreadpoolReady.ready) { + (wasmTable.get(callback))(q, type); + } + else { + uvThreadpoolReady.then(function () { + (wasmTable.get(callback))(q, type); + }); + } + } + /** @__sig vpi */ + function _emnapi_tell_js_uvthreadpool(threads, size) { + var p = []; + var HEAP_DATA_VIEW = new DataView(wasmMemory.buffer), GET_HEAP_DATA_VIEW = function () { return HEAP_DATA_VIEW.buffer === wasmMemory.buffer ? HEAP_DATA_VIEW : (HEAP_DATA_VIEW = new DataView(wasmMemory.buffer)); }; + var _loop_1 = function (i) { + var pthreadPtr = GET_HEAP_DATA_VIEW().getUint32(threads + i * 4, true); + var worker = emnapiGetWorkerByPthreadPtr(pthreadPtr); + p.push(new Promise(function (resolve) { + var handler = function (e) { + var data = ENVIRONMENT_IS_NODE ? e : e.data; + var __emnapi__ = data.__emnapi__; + if (__emnapi__ && __emnapi__.type === 'async-thread-ready') { + resolve(); + if (worker && typeof worker.unref === 'function') { + worker.unref(); + } + if (ENVIRONMENT_IS_NODE) { + worker.off('message', handler); + } + else { + worker.removeEventListener('message', handler); + } + } + }; + if (ENVIRONMENT_IS_NODE) { + worker.on('message', handler); + } + else { + worker.addEventListener('message', handler); + } + })); + }; + for (var i = 0; i < size; i++) { + _loop_1(i); + } + Promise.all(p).then(uvThreadpoolReadyResolve); + } + /** @__sig v */ + function _emnapi_emit_async_thread_ready() { + if (!ENVIRONMENT_IS_PTHREAD) + return; + var postMessage = napiModule.postMessage; + postMessage({ + __emnapi__: { + type: 'async-thread-ready', + payload: {} + } + }); + } + var asyncMod = /*#__PURE__*/ Object.freeze({ + __proto__: null, + _emnapi_after_uvthreadpool_ready: _emnapi_after_uvthreadpool_ready, + _emnapi_async_send_js: _emnapi_async_send_js, + _emnapi_emit_async_thread_ready: _emnapi_emit_async_thread_ready, + _emnapi_tell_js_uvthreadpool: _emnapi_tell_js_uvthreadpool, + _emnapi_worker_ref: _emnapi_worker_ref, + _emnapi_worker_unref: _emnapi_worker_unref + }); + /** @__sig ipjp */ + function napi_adjust_external_memory(env, change_in_bytes, adjusted_value) { + if (!env) + return 1 /* napi_status.napi_invalid_arg */; + var envObject = emnapiCtx.envStore.get(env); + if (!adjusted_value) + return envObject.setLastError(1 /* napi_status.napi_invalid_arg */); + // eslint-disable-next-line prefer-const + var adjusted_memory = emnapiCtx.adjustAmountOfExternalAllocatedMemory(change_in_bytes); + adjusted_value >>>= 0; + if (emnapiCtx.feature.supportBigInt) { + var HEAP_DATA_VIEW = new DataView(wasmMemory.buffer), GET_HEAP_DATA_VIEW = function () { return HEAP_DATA_VIEW.buffer === wasmMemory.buffer ? HEAP_DATA_VIEW : (HEAP_DATA_VIEW = new DataView(wasmMemory.buffer)); }; + GET_HEAP_DATA_VIEW().setBigInt64(adjusted_value, BigInt(adjusted_memory), true); + } + else { + $emnapiSetValueI64(adjusted_value, Number(adjusted_memory)); + } + return envObject.clearLastError(); + } + var memoryMod = /*#__PURE__*/ Object.freeze({ + __proto__: null, + napi_adjust_external_memory: napi_adjust_external_memory + }); + /** + * @__postset + * ``` + * emnapiAWST.init(); + * ``` + */ + var emnapiAWST = { + idGen: {}, + values: [undefined], + queued: new Set(), + pending: [], + init: function () { + var idGen = { + nextId: 1, + list: [], + generate: function () { + var id; + if (idGen.list.length) { + id = idGen.list.shift(); + } + else { + id = idGen.nextId; + idGen.nextId++; + } + return id; + }, + reuse: function (id) { + idGen.list.push(id); + } + }; + emnapiAWST.idGen = idGen; + emnapiAWST.values = [undefined]; + emnapiAWST.queued = new Set(); + emnapiAWST.pending = []; + }, + create: function (env, resource, resourceName, execute, complete, data) { + var asyncId = 0; + var triggerAsyncId = 0; + if (emnapiNodeBinding) { + var asyncContext = emnapiNodeBinding.node.emitAsyncInit(resource, resourceName, -1); + asyncId = asyncContext.asyncId; + triggerAsyncId = asyncContext.triggerAsyncId; + } + var id = emnapiAWST.idGen.generate(); + emnapiAWST.values[id] = { + env: env, + id: id, + resource: resource, + asyncId: asyncId, + triggerAsyncId: triggerAsyncId, + status: 0, + execute: execute, + complete: complete, + data: data + }; + return id; + }, + callComplete: function (work, status) { + // eslint-disable-next-line @typescript-eslint/no-unused-vars + var complete = work.complete; + var env = work.env; + var data = work.data; + var callback = function () { + if (!complete) + return; + var envObject = emnapiCtx.envStore.get(env); + var scope = emnapiCtx.openScope(envObject); + try { + envObject.callbackIntoModule(true, function () { + (wasmTable.get(complete))(env, status, data); + }); + } + finally { + emnapiCtx.closeScope(envObject, scope); + } + }; + if (emnapiNodeBinding) { + emnapiNodeBinding.node.makeCallback(work.resource, callback, [], { + asyncId: work.asyncId, + triggerAsyncId: work.triggerAsyncId + }); + } + else { + callback(); + } + }, + queue: function (id) { + var work = emnapiAWST.values[id]; + if (!work) + return; + if (work.status === 0) { + work.status = 1; + if (emnapiAWST.queued.size >= (Math.abs(emnapiAsyncWorkPoolSize) || 4)) { + emnapiAWST.pending.push(id); + return; + } + emnapiAWST.queued.add(id); + var env_1 = work.env; + var data_1 = work.data; + // eslint-disable-next-line @typescript-eslint/no-unused-vars + var execute = work.execute; + work.status = 2; + emnapiCtx.feature.setImmediate(function () { + (wasmTable.get(execute))(env_1, data_1); + emnapiAWST.queued.delete(id); + work.status = 3; + emnapiCtx.feature.setImmediate(function () { + emnapiAWST.callComplete(work, 0 /* napi_status.napi_ok */); + }); + if (emnapiAWST.pending.length > 0) { + var nextWorkId = emnapiAWST.pending.shift(); + emnapiAWST.values[nextWorkId].status = 0; + emnapiAWST.queue(nextWorkId); + } + }); + } + }, + cancel: function (id) { + var index = emnapiAWST.pending.indexOf(id); + if (index !== -1) { + var work_1 = emnapiAWST.values[id]; + if (work_1 && (work_1.status === 1)) { + work_1.status = 4; + emnapiAWST.pending.splice(index, 1); + emnapiCtx.feature.setImmediate(function () { + emnapiAWST.callComplete(work_1, 11 /* napi_status.napi_cancelled */); + }); + return 0 /* napi_status.napi_ok */; + } + else { + return 9 /* napi_status.napi_generic_failure */; + } + } + return 9 /* napi_status.napi_generic_failure */; + }, + remove: function (id) { + var work = emnapiAWST.values[id]; + if (!work) + return; + if (emnapiNodeBinding) { + emnapiNodeBinding.node.emitAsyncDestroy({ + asyncId: work.asyncId, + triggerAsyncId: work.triggerAsyncId + }); + } + emnapiAWST.values[id] = undefined; + emnapiAWST.idGen.reuse(id); + } + }; + /** @__sig vppdp */ + function _emnapi_node_emit_async_init(async_resource, async_resource_name, trigger_async_id, result) { + if (!emnapiNodeBinding) + return; + var resource = emnapiCtx.handleStore.get(async_resource).value; + var resource_name = emnapiCtx.handleStore.get(async_resource_name).value; + var asyncContext = emnapiNodeBinding.node.emitAsyncInit(resource, resource_name, trigger_async_id); + // eslint-disable-next-line @typescript-eslint/no-unused-vars + var asyncId = asyncContext.asyncId; + var triggerAsyncId = asyncContext.triggerAsyncId; + if (result) { + result >>>= 0; + var HEAP_DATA_VIEW = new DataView(wasmMemory.buffer), GET_HEAP_DATA_VIEW = function () { return HEAP_DATA_VIEW.buffer === wasmMemory.buffer ? HEAP_DATA_VIEW : (HEAP_DATA_VIEW = new DataView(wasmMemory.buffer)); }; + GET_HEAP_DATA_VIEW().setFloat64(result, asyncId, true); + GET_HEAP_DATA_VIEW().setFloat64(result + 8, triggerAsyncId, true); + } + } + /** @__sig vdd */ + function _emnapi_node_emit_async_destroy(async_id, trigger_async_id) { + if (!emnapiNodeBinding) + return; + emnapiNodeBinding.node.emitAsyncDestroy({ + asyncId: async_id, + triggerAsyncId: trigger_async_id + }); + } + /* vpddp export function _emnapi_node_open_callback_scope (async_resource: napi_value, async_id: double, trigger_async_id: double, result: Pointer): void { + if (!emnapiNodeBinding || !result) return + const resource = emnapiCtx.handleStore.get(async_resource)!.value + // eslint-disable-next-line @typescript-eslint/no-unused-vars + const nativeCallbackScopePointer = emnapiNodeBinding.node.openCallbackScope(resource, { + asyncId: async_id, + triggerAsyncId: trigger_async_id + }) + + from64('result') + $_TODO_makeSetValue('result', 0, 'nativeCallbackScopePointer', 'i64') + } + + vp + export function _emnapi_node_close_callback_scope (scope: Pointer): void { + if (!emnapiNodeBinding || !scope) return + from64('scope') + const nativeCallbackScopePointer = $_TODO_makeGetValue('scope', 0, 'i64') + emnapiNodeBinding.node.closeCallbackScope(BigInt(nativeCallbackScopePointer)) + } */ + /** @__sig ipppppddp */ + function _emnapi_node_make_callback(env, async_resource, cb, argv, size, async_id, trigger_async_id, result) { + var i = 0; + // eslint-disable-next-line @typescript-eslint/no-unused-vars + var v; + if (!emnapiNodeBinding) + return; + var resource = emnapiCtx.handleStore.get(async_resource).value; + var callback = emnapiCtx.handleStore.get(cb).value; + argv >>>= 0; + size >>>= 0; + size = size >>> 0; + var arr = Array(size); + var HEAP_DATA_VIEW = new DataView(wasmMemory.buffer), GET_HEAP_DATA_VIEW = function () { return HEAP_DATA_VIEW.buffer === wasmMemory.buffer ? HEAP_DATA_VIEW : (HEAP_DATA_VIEW = new DataView(wasmMemory.buffer)); }; + for (; i < size; i++) { + var argVal = GET_HEAP_DATA_VIEW().getUint32(argv + i * 4, true); + arr[i] = emnapiCtx.handleStore.get(argVal).value; + } + var ret = emnapiNodeBinding.node.makeCallback(resource, callback, arr, { + asyncId: async_id, + triggerAsyncId: trigger_async_id + }); + if (result) { + result >>>= 0; + var envObject = emnapiCtx.envStore.get(env); + // eslint-disable-next-line @typescript-eslint/no-unused-vars + v = envObject.ensureHandleId(ret); + GET_HEAP_DATA_VIEW().setUint32(result, v, true); + } + } + /** @__sig ippp */ + function _emnapi_async_init_js(async_resource, async_resource_name, result) { + if (!emnapiNodeBinding) { + return 9 /* napi_status.napi_generic_failure */; + } + var resource; + if (async_resource) { + resource = Object(emnapiCtx.handleStore.get(async_resource).value); + } + var name = emnapiCtx.handleStore.get(async_resource_name).value; + var ret = emnapiNodeBinding.napi.asyncInit(resource, name); + if (ret.status !== 0) + return ret.status; + var numberValue = ret.value; + if (!((numberValue >= (BigInt(-1) * (BigInt(1) << BigInt(63)))) && (numberValue < (BigInt(1) << BigInt(63))))) { + numberValue = numberValue & ((BigInt(1) << BigInt(64)) - BigInt(1)); + if (numberValue >= (BigInt(1) << BigInt(63))) { + numberValue = numberValue - (BigInt(1) << BigInt(64)); + } + } + // eslint-disable-next-line @typescript-eslint/no-unused-vars + var low = Number(numberValue & BigInt(0xffffffff)); + // eslint-disable-next-line @typescript-eslint/no-unused-vars + var high = Number(numberValue >> BigInt(32)); + result >>>= 0; + var HEAP_DATA_VIEW = new DataView(wasmMemory.buffer), GET_HEAP_DATA_VIEW = function () { return HEAP_DATA_VIEW.buffer === wasmMemory.buffer ? HEAP_DATA_VIEW : (HEAP_DATA_VIEW = new DataView(wasmMemory.buffer)); }; + GET_HEAP_DATA_VIEW().setInt32(result, low, true); + GET_HEAP_DATA_VIEW().setInt32(result + 4, high, true); + return 0 /* napi_status.napi_ok */; + } + /** @__sig ip */ + function _emnapi_async_destroy_js(async_context) { + if (!emnapiNodeBinding) { + return 9 /* napi_status.napi_generic_failure */; + } + async_context >>>= 0; + var HEAP_DATA_VIEW = new DataView(wasmMemory.buffer), GET_HEAP_DATA_VIEW = function () { return HEAP_DATA_VIEW.buffer === wasmMemory.buffer ? HEAP_DATA_VIEW : (HEAP_DATA_VIEW = new DataView(wasmMemory.buffer)); }; + var low = GET_HEAP_DATA_VIEW().getInt32(async_context, true); + var high = GET_HEAP_DATA_VIEW().getInt32(async_context + 4, true); + var pointer = BigInt(low >>> 0) | (BigInt(high) << BigInt(32)); + var ret = emnapiNodeBinding.napi.asyncDestroy(pointer); + if (ret.status !== 0) + return ret.status; + return 0 /* napi_status.napi_ok */; + } + // https://github.com/nodejs/node-addon-api/pull/1283 + /** @__sig ipppp */ + function napi_open_callback_scope(env, ignored, async_context_handle, result) { + throw new Error('napi_open_callback_scope has not been implemented yet'); + } + /** @__sig ipp */ + function napi_close_callback_scope(env, scope) { + throw new Error('napi_close_callback_scope has not been implemented yet'); + } + /** @__sig ippppppp */ + function napi_make_callback(env, async_context, recv, func, argc, argv, result) { + var i = 0; + // eslint-disable-next-line @typescript-eslint/no-unused-vars + var v; + if (!env) + return 1 /* napi_status.napi_invalid_arg */; + // @ts-expect-error + var envObject = emnapiCtx.envStore.get(env); + envObject.checkGCAccess(); + if (!envObject.tryCatch.isEmpty()) + return envObject.setLastError(10 /* napi_status.napi_pending_exception */); + if (!envObject.canCallIntoJs()) + return envObject.setLastError(envObject.moduleApiVersion >= 10 ? 23 /* napi_status.napi_cannot_run_js */ : 10 /* napi_status.napi_pending_exception */); + envObject.clearLastError(); + try { + if (!emnapiNodeBinding) { + return envObject.setLastError(9 /* napi_status.napi_generic_failure */); + } + if (!recv) + return envObject.setLastError(1 /* napi_status.napi_invalid_arg */); + if (argc > 0) { + if (!argv) + return envObject.setLastError(1 /* napi_status.napi_invalid_arg */); + } + var v8recv = Object(emnapiCtx.handleStore.get(recv).value); + var v8func = emnapiCtx.handleStore.get(func).value; + if (typeof v8func !== 'function') { + return envObject.setLastError(1 /* napi_status.napi_invalid_arg */); + } + async_context >>>= 0; + var HEAP_DATA_VIEW = new DataView(wasmMemory.buffer), GET_HEAP_DATA_VIEW = function () { return HEAP_DATA_VIEW.buffer === wasmMemory.buffer ? HEAP_DATA_VIEW : (HEAP_DATA_VIEW = new DataView(wasmMemory.buffer)); }; + var low = GET_HEAP_DATA_VIEW().getInt32(async_context, true); + var high = GET_HEAP_DATA_VIEW().getInt32(async_context + 4, true); + var ctx = BigInt(low >>> 0) | (BigInt(high) << BigInt(32)); + argv >>>= 0; + argc >>>= 0; + argc = argc >>> 0; + var arr = Array(argc); + for (; i < argc; i++) { + var argVal = GET_HEAP_DATA_VIEW().getUint32(argv + i * 4, true); + arr[i] = emnapiCtx.handleStore.get(argVal).value; + } + var ret = emnapiNodeBinding.napi.makeCallback(ctx, v8recv, v8func, arr); + if (ret.error) { + throw ret.error; + } + if (ret.status !== 0 /* napi_status.napi_ok */) + return envObject.setLastError(ret.status); + if (result) { + result >>>= 0; + // The makeCallback call into JS above may have grown wasm memory: + // resolve v before the write (the store target is evaluated before the + // RHS, so an RHS running user JS could write through a stale heap view) + // eslint-disable-next-line @typescript-eslint/no-unused-vars + v = envObject.ensureHandleId(ret.value); + GET_HEAP_DATA_VIEW().setUint32(result, v, true); + } + return envObject.getReturnStatus(); + } + catch (err) { + envObject.tryCatch.setError(err); + return envObject.setLastError(10 /* napi_status.napi_pending_exception */); + } + } + /** @__sig vp */ + function _emnapi_env_check_gc_access(env) { + var envObject = emnapiCtx.envStore.get(env); + envObject.checkGCAccess(); + } + var nodeMod = /*#__PURE__*/ Object.freeze({ + __proto__: null, + _emnapi_async_destroy_js: _emnapi_async_destroy_js, + _emnapi_async_init_js: _emnapi_async_init_js, + _emnapi_env_check_gc_access: _emnapi_env_check_gc_access, + _emnapi_node_emit_async_destroy: _emnapi_node_emit_async_destroy, + _emnapi_node_emit_async_init: _emnapi_node_emit_async_init, + _emnapi_node_make_callback: _emnapi_node_make_callback, + napi_close_callback_scope: napi_close_callback_scope, + napi_make_callback: napi_make_callback, + napi_open_callback_scope: napi_open_callback_scope + }); + /** + * @__deps malloc + * @__deps free + * @__postset + * ``` + * emnapiTSFN.init(); + * ``` + */ + var emnapiTSFN = { + _liveSet: {}, + offset: { + __size__: 0, + /* napi_ref */ resource: 0, + /* double */ async_id: 0, + /* double */ trigger_async_id: 0, + /* size_t */ queue_size: 0, + /* bool */ is_some: 0, + /* void* */ queue: 0, + // Reuse uv_async_t storage as JS-side wakeup state: pending event + scheduled drain. + async_pending: 0, + async_u_fd: 0, + /* size_t */ thread_count: 0, + /* int32_t */ state: 0, + /* atomic_uchar */ dispatch_state: 0, + /* void* */ context: 0, + /* size_t */ max_queue_size: 0, + /* napi_ref */ ref: 0, + /* napi_env */ env: 0, + /* void* */ finalize_data: 0, + /* napi_finalize */ finalize_cb: 0, + /* napi_threadsafe_function_call_js */ call_js_cb: 0, + /* bool */ handles_closing: 0, + /* bool */ async_ref: 0, + /* int32_t */ mutex: 0, + /* int32_t */ cond: 0 + }, + init: function () { + emnapiTSFN._liveSet = new Set(); + emnapiTSFN.offset.__size__ = 184 /* NapiTSFNOffset32.__size__ */; + emnapiTSFN.offset.resource = 0 /* NapiTSFNOffset32.async_resource_resource */; + emnapiTSFN.offset.async_id = 8 /* NapiTSFNOffset32.async_resource_async_context_async_id */; + emnapiTSFN.offset.trigger_async_id = 16 /* NapiTSFNOffset32.async_resource_async_context_trigger_async_id */; + emnapiTSFN.offset.queue_size = 60 /* NapiTSFNOffset32.queue_size */; + emnapiTSFN.offset.is_some = 24 /* NapiTSFNOffset32.async_resource_is_some */; + emnapiTSFN.offset.queue = 64 /* NapiTSFNOffset32.queue */; + emnapiTSFN.offset.async_pending = 132 /* NapiTSFNOffset32.async_pending */; + emnapiTSFN.offset.async_u_fd = 96 /* NapiTSFNOffset32.async_u_fd */; + emnapiTSFN.offset.thread_count = 136 /* NapiTSFNOffset32.thread_count */; + emnapiTSFN.offset.state = 140 /* NapiTSFNOffset32.state */; + emnapiTSFN.offset.dispatch_state = 144 /* NapiTSFNOffset32.dispatch_state */; + emnapiTSFN.offset.context = 148 /* NapiTSFNOffset32.context */; + emnapiTSFN.offset.max_queue_size = 152 /* NapiTSFNOffset32.max_queue_size */; + emnapiTSFN.offset.ref = 156 /* NapiTSFNOffset32.ref */; + emnapiTSFN.offset.env = 160 /* NapiTSFNOffset32.env */; + emnapiTSFN.offset.finalize_data = 164 /* NapiTSFNOffset32.finalize_data */; + emnapiTSFN.offset.finalize_cb = 168 /* NapiTSFNOffset32.finalize_cb */; + emnapiTSFN.offset.call_js_cb = 172 /* NapiTSFNOffset32.call_js_cb */; + emnapiTSFN.offset.handles_closing = 176 /* NapiTSFNOffset32.handles_closing */; + emnapiTSFN.offset.async_ref = 180 /* NapiTSFNOffset32.async_ref */; + emnapiTSFN.offset.mutex = 32 /* NapiTSFNOffset32.mutex */; + emnapiTSFN.offset.cond = 56 /* NapiTSFNOffset32.cond */; + emnapiTSFN.offset.mutex = emnapiTSFN.offset.mutex + 4; + if (typeof PThread !== 'undefined') { + PThread.unusedWorkers.forEach(emnapiTSFN.addListener); + Object.values(PThread.pthreads).forEach(emnapiTSFN.addListener); + var __original_getNewWorker_1 = PThread.getNewWorker; + PThread.getNewWorker = function () { + var r = __original_getNewWorker_1.apply(this, arguments); + emnapiTSFN.addListener(r); + return r; + }; + } + }, + addListener: function (worker) { + if (!worker) + return false; + if (worker._emnapiTSFNListener) + return true; + var handler = function (e) { + var data = ENVIRONMENT_IS_NODE ? e : e.data; + var __emnapi__ = data.__emnapi__; + if (__emnapi__) { + var type = __emnapi__.type; + var payload = __emnapi__.payload; + if (type === 'tsfn-send') { + var pendng = payload.tsfn + emnapiTSFN.offset.async_pending; + if (Atomics.load(new Int32Array(emnapiTSFN.ensureBufferFor(pendng + 4)), pendng >>> 2) !== 0) { + emnapiTSFN.enqueue(payload.tsfn); + } + } + } + }; + var dispose = function () { + if (ENVIRONMENT_IS_NODE) { + worker.off('message', handler); + } + else { + worker.removeEventListener('message', handler, false); + } + delete worker._emnapiTSFNListener; + }; + worker._emnapiTSFNListener = { handler: handler, dispose: dispose }; + if (ENVIRONMENT_IS_NODE) { + worker.on('message', handler); + } + else { + worker.addEventListener('message', handler, false); + } + return true; + }, + /** + * When another thread grows the shared WebAssembly.Memory, this agent's + * cached `wasmMemory.buffer` may still have the old shorter length + * (V8 refreshes it lazily). If a pointer derived from shared memory lies + * beyond the cached length, `wasmMemory.grow(0)` forces the agent to + * observe the current memory size and refreshes the buffer. + */ + ensureBufferFor: function (end) { + var buffer = wasmMemory.buffer; + if (end > buffer.byteLength) { + wasmMemory.grow(0); + buffer = wasmMemory.buffer; + } + return buffer; + }, + initQueue: function (func) { + var size = 2 * 4; + var queue = _malloc(size); + if (!queue) + return false; + queue >>>= 0; + new Uint8Array(emnapiTSFN.ensureBufferFor(queue + size), queue, size).fill(0); + emnapiTSFN.storeSizeTypeValue(func + emnapiTSFN.offset.queue, queue, false); + return true; + }, + destroyQueue: function (func) { + var queue = emnapiTSFN.loadSizeTypeValue(func + emnapiTSFN.offset.queue, false); + if (queue) { + var node = emnapiTSFN.loadSizeTypeValue(queue, false); + while (node !== 0) { + var next = emnapiTSFN.loadSizeTypeValue(node + 4, false); + _free(node); + node = next; + } + _free(queue); + } + }, + pushQueue: function (func, data) { + var queue = emnapiTSFN.loadSizeTypeValue(func + emnapiTSFN.offset.queue, false); + var head = emnapiTSFN.loadSizeTypeValue(queue, false); + var tail = emnapiTSFN.loadSizeTypeValue(queue + 4, false); + // eslint-disable-next-line @typescript-eslint/no-unused-vars + var size = 2 * 4; + var node = _malloc(size); + if (!node) + throw new Error('OOM'); + node >>>= 0; + emnapiTSFN.storeSizeTypeValue(node, data, false); + emnapiTSFN.storeSizeTypeValue(node + 4, 0, false); + if (head === 0 && tail === 0) { + emnapiTSFN.storeSizeTypeValue(queue, node, false); + emnapiTSFN.storeSizeTypeValue(queue + 4, node, false); + } + else { + emnapiTSFN.storeSizeTypeValue(tail + 4, node, false); + emnapiTSFN.storeSizeTypeValue(queue + 4, node, false); + } + emnapiTSFN.addQueueSize(func); + }, + shiftQueue: function (func) { + var queue = emnapiTSFN.loadSizeTypeValue(func + emnapiTSFN.offset.queue, false); + var head = emnapiTSFN.loadSizeTypeValue(queue, false); + if (head === 0) + return 0; + var node = head; + var next = emnapiTSFN.loadSizeTypeValue(head + 4, false); + emnapiTSFN.storeSizeTypeValue(queue, next, false); + if (next === 0) { + emnapiTSFN.storeSizeTypeValue(queue + 4, 0, false); + } + emnapiTSFN.storeSizeTypeValue(node + 4, 0, false); + var value = emnapiTSFN.loadSizeTypeValue(node, false); + _free(node); + emnapiTSFN.subQueueSize(func); + return value; + }, + push: function (func, data, mode) { + var mutex = emnapiTSFN.getMutex(func); + var cond = emnapiTSFN.getCond(func); + var waitCondition = function () { + var queueSize = emnapiTSFN.getQueueSize(func); + var maxSize = emnapiTSFN.getMaxQueueSize(func); + return queueSize >= maxSize && maxSize > 0 && emnapiTSFN.getState(func) === 0 /* State.kOpen */; + }; + var isBrowserMain = typeof window !== 'undefined' && typeof document !== 'undefined' && !ENVIRONMENT_IS_NODE; + var shouldDelete = false; + var ret = mutex.execute(function () { + while (waitCondition()) { + if (mode === 0 /* napi_threadsafe_function_call_mode.napi_tsfn_nonblocking */) { + return 15 /* napi_status.napi_queue_full */; + } + /** + * Browser JS main thread can not use `Atomics.wait` + * + * Related: + * https://github.com/nodejs/node/pull/32689 + * https://github.com/nodejs/node/pull/33453 + */ + if (isBrowserMain) { + return 21 /* napi_status.napi_would_deadlock */; + } + cond.wait(); + } + if (emnapiTSFN.getState(func) === 0 /* State.kOpen */) { + emnapiTSFN.pushQueue(func, data); + emnapiTSFN.send(func); + return 0 /* napi_status.napi_ok */; + } + if (emnapiTSFN.getThreadCount(func) === 0) { + return 1 /* napi_status.napi_invalid_arg */; + } + emnapiTSFN.subThreadCount(func); + if (!(emnapiTSFN.getState(func) === 2 /* State.kClosed */ && emnapiTSFN.getThreadCount(func) === 0)) { + return 16 /* napi_status.napi_closing */; + } + shouldDelete = true; + return 16 /* napi_status.napi_closing */; + }); + if (shouldDelete) { + emnapiTSFN.destroy(func); + } + return ret; + }, + getMutex: function (func) { + var index = func + emnapiTSFN.offset.mutex; + var mutex = { + lock: function () { + var isBrowserMain = typeof window !== 'undefined' && typeof document !== 'undefined' && !ENVIRONMENT_IS_NODE; + var i32a = new Int32Array(emnapiTSFN.ensureBufferFor(index + 4), index, 1); + if (isBrowserMain) { + while (true) { + var oldValue = Atomics.compareExchange(i32a, 0, 0, 10); + if (oldValue === 0) { + return; + } + } + } + else { + while (true) { + var oldValue = Atomics.compareExchange(i32a, 0, 0, 10); + if (oldValue === 0) { + return; + } + Atomics.wait(i32a, 0, 10); + } + } + }, + /* lockAsync () { + return new Promise(resolve => { + const again = (): void => { fn() } + const fn = (): void => { + const i32a = new Int32Array(emnapiTSFN.ensureBufferFor(index + 4), index, 1) + const oldValue = Atomics.compareExchange(i32a, 0, 0, 10) + if (oldValue === 0) { + resolve() + return + } + (Atomics as any).waitAsync(i32a, 0, 10).value.then(again) + } + fn() + }) + }, */ + unlock: function () { + var i32a = new Int32Array(emnapiTSFN.ensureBufferFor(index + 4), index, 1); + var oldValue = Atomics.compareExchange(i32a, 0, 10, 0); + if (oldValue !== 10) { + throw new Error('Tried to unlock while not holding the mutex'); + } + Atomics.notify(i32a, 0, 1); + }, + execute: function (fn) { + mutex.lock(); + try { + return fn(); + } + finally { + mutex.unlock(); + } + } /* , + executeAsync (fn: () => Promise): Promise { + return mutex.lockAsync().then(() => { + const r = fn() + mutex.unlock() + return r + }, (err) => { + mutex.unlock() + throw err + }) + } */ + }; + return mutex; + }, + getCond: function (func) { + var index = func + emnapiTSFN.offset.cond; + var mutex = emnapiTSFN.getMutex(func); + var cond = { + wait: function () { + var i32a = new Int32Array(emnapiTSFN.ensureBufferFor(index + 4), index, 1); + var value = Atomics.load(i32a, 0); + mutex.unlock(); + Atomics.wait(i32a, 0, value); + mutex.lock(); + }, + /* waitAsync () { + const i32a = new Int32Array(emnapiTSFN.ensureBufferFor(index + 4), index, 1) + const value = Atomics.load(i32a, 0) + mutex.unlock() + const lock = (): Promise => mutex.lockAsync() + try { + return (Atomics as any).waitAsync(i32a, 0, value).value.then(lock, lock) + } catch (err) { + return lock() + } + }, */ + signal: function () { + var i32a = new Int32Array(emnapiTSFN.ensureBufferFor(index + 4), index, 1); + Atomics.add(i32a, 0, 1); + Atomics.notify(i32a, 0, 1); + } + }; + return cond; + }, + getQueueSize: function (func) { + return emnapiTSFN.loadSizeTypeValue(func + emnapiTSFN.offset.queue_size, true); + }, + addQueueSize: function (func) { + var offset = emnapiTSFN.offset.queue_size; + var arr, index; + arr = new Uint32Array(emnapiTSFN.ensureBufferFor(func + offset + 4)); + index = (func + offset) >>> 2; + Atomics.add(arr, index, 1); + }, + subQueueSize: function (func) { + var offset = emnapiTSFN.offset.queue_size; + var arr, index; + arr = new Uint32Array(emnapiTSFN.ensureBufferFor(func + offset + 4)); + index = (func + offset) >>> 2; + Atomics.sub(arr, index, 1); + }, + getThreadCount: function (func) { + return emnapiTSFN.loadSizeTypeValue(func + emnapiTSFN.offset.thread_count, true); + }, + addThreadCount: function (func) { + var offset = emnapiTSFN.offset.thread_count; + var arr, index; + arr = new Uint32Array(emnapiTSFN.ensureBufferFor(func + offset + 4)); + index = (func + offset) >>> 2; + Atomics.add(arr, index, 1); + }, + subThreadCount: function (func) { + var offset = emnapiTSFN.offset.thread_count; + var arr, index; + arr = new Uint32Array(emnapiTSFN.ensureBufferFor(func + offset + 4)); + index = (func + offset) >>> 2; + Atomics.sub(arr, index, 1); + }, + getState: function (func) { + return Atomics.load(new Int32Array(emnapiTSFN.ensureBufferFor(func + emnapiTSFN.offset.state + 4)), (func + emnapiTSFN.offset.state) >>> 2); + }, + setState: function (func, value) { + Atomics.store(new Int32Array(emnapiTSFN.ensureBufferFor(func + emnapiTSFN.offset.state + 4)), (func + emnapiTSFN.offset.state) >>> 2, value); + }, + getHandlesClosing: function (func) { + return Atomics.load(new Int8Array(emnapiTSFN.ensureBufferFor(func + emnapiTSFN.offset.handles_closing + 1)), (func + emnapiTSFN.offset.handles_closing)); + }, + setHandlesClosing: function (func, value) { + Atomics.store(new Int8Array(emnapiTSFN.ensureBufferFor(func + emnapiTSFN.offset.handles_closing + 1)), (func + emnapiTSFN.offset.handles_closing), value); + }, + getDispatchState: function (func) { + return Atomics.load(new Uint32Array(emnapiTSFN.ensureBufferFor(func + emnapiTSFN.offset.dispatch_state + 4)), (func + emnapiTSFN.offset.dispatch_state) >>> 2); + }, + getContext: function (func) { + return emnapiTSFN.loadSizeTypeValue(func + emnapiTSFN.offset.context, false); + }, + getMaxQueueSize: function (func) { + return emnapiTSFN.loadSizeTypeValue(func + emnapiTSFN.offset.max_queue_size, true); + }, + getEnv: function (func) { + return emnapiTSFN.loadSizeTypeValue(func + emnapiTSFN.offset.env, false); + }, + getCallJSCb: function (func) { + return emnapiTSFN.loadSizeTypeValue(func + emnapiTSFN.offset.call_js_cb, false); + }, + getRef: function (func) { + return emnapiTSFN.loadSizeTypeValue(func + emnapiTSFN.offset.ref, false); + }, + getResource: function (func) { + return emnapiTSFN.loadSizeTypeValue(func + emnapiTSFN.offset.resource, false); + }, + getFinalizeCb: function (func) { + return emnapiTSFN.loadSizeTypeValue(func + emnapiTSFN.offset.finalize_cb, false); + }, + getFinalizeData: function (func) { + return emnapiTSFN.loadSizeTypeValue(func + emnapiTSFN.offset.finalize_data, false); + }, + loadSizeTypeValue: function (offset, unsigned) { + var ret; + var arr; + if (unsigned) { + arr = new Uint32Array(emnapiTSFN.ensureBufferFor(offset + 4)); + ret = Atomics.load(arr, offset >>> 2); + return ret; + } + else { + arr = new Int32Array(emnapiTSFN.ensureBufferFor(offset + 4)); + ret = Atomics.load(arr, offset >>> 2); + return ret; + } + }, + storeSizeTypeValue: function (offset, value, unsigned) { + var arr; + if (unsigned) { + arr = new Uint32Array(emnapiTSFN.ensureBufferFor(offset + 4)); + Atomics.store(arr, offset >>> 2, value); + return undefined; + } + else { + arr = new Int32Array(emnapiTSFN.ensureBufferFor(offset + 4)); + Atomics.store(arr, offset >>> 2, value >>> 0); + return undefined; + } + }, + releaseResources: function (func) { + if (emnapiTSFN.getState(func) !== 2 /* State.kClosed */) { + emnapiTSFN.setState(func, 2 /* State.kClosed */); + var env = emnapiTSFN.getEnv(func); + var envObject = emnapiCtx.envStore.get(env); + var ref = emnapiTSFN.getRef(func); + if (ref) { + emnapiCtx.refStore.get(ref).dispose(); + } + var resource = emnapiTSFN.getResource(func); + emnapiCtx.refStore.get(resource).dispose(); + emnapiTSFN.ensureBufferFor(func + emnapiTSFN.offset.is_some + 1); + var HEAP_DATA_VIEW = new DataView(wasmMemory.buffer), GET_HEAP_DATA_VIEW = function () { return HEAP_DATA_VIEW.buffer === wasmMemory.buffer ? HEAP_DATA_VIEW : (HEAP_DATA_VIEW = new DataView(wasmMemory.buffer)); }; + GET_HEAP_DATA_VIEW().setInt8(func + emnapiTSFN.offset.is_some, 0, true); + emnapiCtx.removeCleanupHook(envObject, emnapiTSFN.cleanup, func); + envObject.unref(); + var asyncRefAddress = func + emnapiTSFN.offset.async_ref; + var asyncRefOffset = asyncRefAddress >>> 2; + var arr = new Uint32Array(emnapiTSFN.ensureBufferFor(asyncRefAddress + 4)); + if (Atomics.load(arr, asyncRefOffset) > 0) { + Atomics.store(arr, asyncRefOffset, 0); + emnapiCtx.decreaseWaitingRequestCounter(); + } + if (emnapiNodeBinding) { + var view = new DataView(emnapiTSFN.ensureBufferFor(func + emnapiTSFN.offset.trigger_async_id + 8)); + var asyncId = view.getFloat64(func + emnapiTSFN.offset.async_id, true); + var triggerAsyncId = view.getFloat64(func + emnapiTSFN.offset.trigger_async_id, true); + _emnapi_node_emit_async_destroy(asyncId, triggerAsyncId); + } + } + }, + destroy: function (func) { + emnapiTSFN._liveSet.delete(func); + emnapiTSFN.destroyQueue(func); + emnapiTSFN.releaseResources(func); + _free(func); + }, + emptyQueue: function (func) { + var drainQueue = []; + emnapiTSFN.getMutex(func).execute(function () { + while (emnapiTSFN.getQueueSize(func) > 0) { + drainQueue.push(emnapiTSFN.shiftQueue(func)); + } + }); + var callJsCb = emnapiTSFN.getCallJSCb(func); + // eslint-disable-next-line @typescript-eslint/no-unused-vars + var context = emnapiTSFN.getContext(func); + var data; + for (var i = 0; i < drainQueue.length; i++) { + // eslint-disable-next-line @typescript-eslint/no-unused-vars + data = drainQueue[i]; + if (callJsCb) { + (wasmTable.get(callJsCb))(0, 0, context, data); + } + } + }, + maybeDelete: function (func) { + var shouldDelete = false; + emnapiTSFN.getMutex(func).execute(function () { + if (emnapiTSFN.getThreadCount(func) > 0) { + emnapiTSFN.releaseResources(func); + } + else { + shouldDelete = true; + } + }); + if (shouldDelete) { + emnapiTSFN.destroy(func); + } + }, + finalize: function (func) { + var env = emnapiTSFN.getEnv(func); + var envObject = emnapiCtx.envStore.get(env); + emnapiCtx.openScope(envObject); + var finalize = emnapiTSFN.getFinalizeCb(func); + // eslint-disable-next-line @typescript-eslint/no-unused-vars + var data = emnapiTSFN.getFinalizeData(func); + // eslint-disable-next-line @typescript-eslint/no-unused-vars + var context = emnapiTSFN.getContext(func); + var f = function () { + envObject.callFinalizerInternal(0, finalize, data, context); + }; + try { + emnapiTSFN.emptyQueue(func); + if (finalize) { + if (emnapiNodeBinding) { + var resource = emnapiTSFN.getResource(func); + var resource_value = emnapiCtx.refStore.get(resource).get(); + var resourceObject = emnapiCtx.handleStore.get(resource_value).value; + var view = new DataView(emnapiTSFN.ensureBufferFor(func + emnapiTSFN.offset.trigger_async_id + 8)); + var asyncId = view.getFloat64(func + emnapiTSFN.offset.async_id, true); + var triggerAsyncId = view.getFloat64(func + emnapiTSFN.offset.trigger_async_id, true); + emnapiNodeBinding.node.makeCallback(resourceObject, f, [], { + asyncId: asyncId, + triggerAsyncId: triggerAsyncId + }); + } + else { + f(); + } + } + emnapiTSFN.maybeDelete(func); + } + finally { + emnapiCtx.closeScope(envObject); + } + }, + cleanup: function (func) { + emnapiTSFN.closeHandlesAndMaybeDelete(func, 1); + }, + closeHandlesAndMaybeDelete: function (func, set_closing) { + var env = emnapiTSFN.getEnv(func); + var envObject = emnapiCtx.envStore.get(env); + emnapiCtx.openScope(envObject); + try { + if (set_closing) { + emnapiTSFN.getMutex(func).execute(function () { + emnapiTSFN.setState(func, 1 /* State.kClosing */); + if (emnapiTSFN.getMaxQueueSize(func) > 0) { + emnapiTSFN.getCond(func).signal(); + } + }); + } + if (emnapiTSFN.getHandlesClosing(func)) { + return; + } + emnapiTSFN.setHandlesClosing(func, 1); + Atomics.store(new Int32Array(emnapiTSFN.ensureBufferFor(func + emnapiTSFN.offset.async_pending + 4)), (func + emnapiTSFN.offset.async_pending) >>> 2, 1); + emnapiCtx.feature.setImmediate(function () { + emnapiTSFN.finalize(func); + }); + } + finally { + emnapiCtx.closeScope(envObject); + } + }, + dispatchOne: function (func) { + // eslint-disable-next-line @typescript-eslint/no-unused-vars + var data = 0; + var popped_value = false; + var has_more = false; + var mutex = emnapiTSFN.getMutex(func); + var cond = emnapiTSFN.getCond(func); + mutex.execute(function () { + if (emnapiTSFN.getState(func) === 0 /* State.kOpen */) { + var size = emnapiTSFN.getQueueSize(func); + if (size > 0) { + data = emnapiTSFN.shiftQueue(func); + popped_value = true; + var maxQueueSize = emnapiTSFN.getMaxQueueSize(func); + if (size === maxQueueSize && maxQueueSize > 0) { + cond.signal(); + } + size--; + } + if (size === 0) { + if (emnapiTSFN.getThreadCount(func) === 0) { + emnapiTSFN.setState(func, 1 /* State.kClosing */); + if (emnapiTSFN.getMaxQueueSize(func) > 0) { + cond.signal(); + } + emnapiTSFN.closeHandlesAndMaybeDelete(func, 0); + } + } + else { + has_more = true; + } + } + else { + emnapiTSFN.closeHandlesAndMaybeDelete(func, 0); + } + }); + if (popped_value) { + var env = emnapiTSFN.getEnv(func); + var envObject_1 = emnapiCtx.envStore.get(env); + emnapiCtx.openScope(envObject_1); + var f = function () { + envObject_1.callbackIntoModule(false, function () { + var callJsCb = emnapiTSFN.getCallJSCb(func); + var ref = emnapiTSFN.getRef(func); + var js_callback = ref ? emnapiCtx.refStore.get(ref).get() : 0; + if (callJsCb) { + // eslint-disable-next-line @typescript-eslint/no-unused-vars + var context = emnapiTSFN.getContext(func); + (wasmTable.get(callJsCb))(env, js_callback, context, data); + } + else { + var jsCallback = js_callback ? emnapiCtx.handleStore.get(js_callback).value : null; + if (typeof jsCallback === 'function') { + jsCallback(); + } + } + }); + }; + try { + if (emnapiNodeBinding) { + var resource = emnapiTSFN.getResource(func); + var resource_value = emnapiCtx.refStore.get(resource).get(); + var resourceObject = emnapiCtx.handleStore.get(resource_value).value; + var view = new DataView(emnapiTSFN.ensureBufferFor(func + emnapiTSFN.offset.trigger_async_id + 8)); + emnapiNodeBinding.node.makeCallback(resourceObject, f, [], { + asyncId: view.getFloat64(func + emnapiTSFN.offset.async_id, true), + triggerAsyncId: view.getFloat64(func + emnapiTSFN.offset.trigger_async_id, true) + }); + } + else { + f(); + } + } + finally { + emnapiCtx.closeScope(envObject_1); + } + } + return has_more; + }, + dispatch: function (func) { + var has_more = true; + var iterations_left = 1000; + var dispatchStateAddress = func + emnapiTSFN.offset.dispatch_state; + var index = dispatchStateAddress >>> 2; + while (has_more && --iterations_left !== 0) { + Atomics.store(new Uint32Array(emnapiTSFN.ensureBufferFor(dispatchStateAddress + 4)), index, 1); + try { + has_more = emnapiTSFN.dispatchOne(func); + } + catch (err) { + // A throwing callback must not leave dispatch_state marked as + // dispatching, or every later send() would be swallowed. Re-arm + // the state and schedule another drain before rethrowing. + if (emnapiTSFN._liveSet.has(func)) { + Atomics.exchange(new Uint32Array(emnapiTSFN.ensureBufferFor(dispatchStateAddress + 4)), index, 0); + emnapiTSFN.send(func); + } + throw err; + } + if (Atomics.exchange(new Uint32Array(emnapiTSFN.ensureBufferFor(dispatchStateAddress + 4)), index, 0) !== 1) { + has_more = true; + } + } + if (has_more) { + emnapiTSFN.send(func); + } + }, + enqueue: function (func) { + // `pending` means a worker thread has requested a wakeup that has not + // been drained on the main thread yet. + var pending = func + emnapiTSFN.offset.async_pending; + // `scheduled` prevents queueing the same main-thread drain chain more than + // once while a previous wakeup is still in flight. + var scheduled = func + emnapiTSFN.offset.async_u_fd; + var end = Math.max(pending, scheduled) + 4; + var state = function () { return new Int32Array(emnapiTSFN.ensureBufferFor(end)); }; + if (Atomics.exchange(state(), scheduled >>> 2, 1) !== 0) { + return; + } + // Match uv_async_send-style coalescing in JS: the first turn represents + // the wakeup reaching the main thread, and the second turn performs the + // actual TSFN drain after nearby Send/Signal calls have had a chance to + // collapse into the shared AsyncProgressWorker state. + emnapiCtx.feature.setImmediate(function () { + if (!emnapiTSFN._liveSet.has(func)) { + return; + } + if (Atomics.load(state(), pending >>> 2) === 0) { + Atomics.store(state(), scheduled >>> 2, 0); + return; + } + emnapiCtx.feature.setImmediate(function () { + // After destroy(), the func address is freed. Skip the atomics + // on that address entirely to avoid use-after-free (JS-side + // lifecycle check must run before touching the state words). + if (!emnapiTSFN._liveSet.has(func)) { + return; + } + try { + // Consume the coalesced wakeup once, then let dispatch() observe any + // queue mutations through dispatch_state like the C implementation. + if (Atomics.exchange(state(), pending >>> 2, 0) === 0) { + return; + } + emnapiTSFN.dispatch(func); + } + finally { + // Allow a later wakeup to schedule a new drain chain. If another + // worker-thread send raced with this drain, enqueue one more turn. + if (emnapiTSFN._liveSet.has(func)) { + Atomics.store(state(), scheduled >>> 2, 0); + if (Atomics.load(state(), pending >>> 2) !== 0) { + emnapiTSFN.enqueue(func); + } + } + } + }); + }); + }, + send: function (func) { + var dispatchStateAddress = func + emnapiTSFN.offset.dispatch_state; + var current_state = Atomics.or(new Uint32Array(emnapiTSFN.ensureBufferFor(dispatchStateAddress + 4)), dispatchStateAddress >>> 2, 1 << 1); + if ((current_state & 1) === 1) { + return; + } + var pendng = func + emnapiTSFN.offset.async_pending; + // A wakeup is already pending, so this send only needs to leave the queued + // work in the TSFN queue and let the existing drain pick it up. + if (Atomics.load(new Int32Array(emnapiTSFN.ensureBufferFor(pendng + 4)), pendng >>> 2) !== 0) { + return; + } + if (Atomics.exchange(new Int32Array(emnapiTSFN.ensureBufferFor(pendng + 4)), pendng >>> 2, 1) === 0) { + if ((typeof ENVIRONMENT_IS_PTHREAD !== 'undefined') && ENVIRONMENT_IS_PTHREAD) { + // Worker threads only post a wakeup token. Main-thread draining is + // serialized by enqueue() once the message is received. + postMessage({ + __emnapi__: { + type: 'tsfn-send', + payload: { + tsfn: func + } + } + }); + } + else { + // On the main thread we can skip the cross-thread hop and schedule the + // coalesced drain chain directly. + emnapiTSFN.enqueue(func); + } + } + } + }; + /** @__sig ippppppppppp */ + function napi_create_threadsafe_function(env, func, async_resource, async_resource_name, max_queue_size, initial_thread_count, thread_finalize_data, thread_finalize_cb, context, call_js_cb, result) { + if (!env) + return 1 /* napi_status.napi_invalid_arg */; + // @ts-expect-error + var envObject = emnapiCtx.envStore.get(env); + envObject.checkGCAccess(); + if (!async_resource_name) + return envObject.setLastError(1 /* napi_status.napi_invalid_arg */); + max_queue_size >>>= 0; + initial_thread_count >>>= 0; + env >>>= 0; + thread_finalize_data >>>= 0; + thread_finalize_cb >>>= 0; + context >>>= 0; + call_js_cb >>>= 0; + max_queue_size = max_queue_size >>> 0; + initial_thread_count = initial_thread_count >>> 0; + if (initial_thread_count === 0) { + return envObject.setLastError(1 /* napi_status.napi_invalid_arg */); + } + if (!result) + return envObject.setLastError(1 /* napi_status.napi_invalid_arg */); + var ref = 0; + func >>>= 0; + if (!func) { + if (!call_js_cb) + return envObject.setLastError(1 /* napi_status.napi_invalid_arg */); + } + else { + var funcValue = emnapiCtx.handleStore.get(func).value; + if (typeof funcValue !== 'function') { + return envObject.setLastError(1 /* napi_status.napi_invalid_arg */); + } + // eslint-disable-next-line @typescript-eslint/no-unused-vars + ref = emnapiCtx.createReference(envObject, func, 1, 1 /* ReferenceOwnership.kUserland */).id; + } + var asyncResourceObject; + if (async_resource) { + asyncResourceObject = emnapiCtx.handleStore.get(async_resource).value; + if (asyncResourceObject == null) { + return envObject.setLastError(2 /* napi_status.napi_object_expected */); + } + asyncResourceObject = Object(asyncResourceObject); + } + else { + asyncResourceObject = {}; + } + var resource = envObject.ensureHandleId(asyncResourceObject); + var asyncResourceName = emnapiCtx.handleStore.get(async_resource_name).value; + if (typeof asyncResourceName === 'symbol') { + return envObject.setLastError(3 /* napi_status.napi_string_expected */); + } + asyncResourceName = String(asyncResourceName); + var resource_name = envObject.ensureHandleId(asyncResourceName); + // tsfn create + var sizeofTSFN = emnapiTSFN.offset.__size__; + // eslint-disable-next-line prefer-const + var tsfn = _malloc(sizeofTSFN); + if (!tsfn) + return envObject.setLastError(9 /* napi_status.napi_generic_failure */); + tsfn >>>= 0; + new Uint8Array(emnapiTSFN.ensureBufferFor(tsfn + sizeofTSFN)).subarray(tsfn, tsfn + sizeofTSFN).fill(0); + var resourceRef = emnapiCtx.createReference(envObject, resource, 1, 1 /* ReferenceOwnership.kUserland */); + // eslint-disable-next-line @typescript-eslint/no-unused-vars + var resource_ = resourceRef.id; + var HEAP_DATA_VIEW = new DataView(wasmMemory.buffer), GET_HEAP_DATA_VIEW = function () { return HEAP_DATA_VIEW.buffer === wasmMemory.buffer ? HEAP_DATA_VIEW : (HEAP_DATA_VIEW = new DataView(wasmMemory.buffer)); }; + GET_HEAP_DATA_VIEW().setUint32(tsfn + emnapiTSFN.offset.resource, resource_, true); + if (!emnapiTSFN.initQueue(tsfn)) { + _free(tsfn); + resourceRef.dispose(); + return envObject.setLastError(9 /* napi_status.napi_generic_failure */); + } + _emnapi_node_emit_async_init(resource, resource_name, -1, tsfn + emnapiTSFN.offset.async_id); + GET_HEAP_DATA_VIEW().setInt8(tsfn + emnapiTSFN.offset.is_some, 1, true); + GET_HEAP_DATA_VIEW().setUint32(tsfn + emnapiTSFN.offset.thread_count, initial_thread_count, true); + GET_HEAP_DATA_VIEW().setUint32(tsfn + emnapiTSFN.offset.context, context, true); + GET_HEAP_DATA_VIEW().setUint32(tsfn + emnapiTSFN.offset.max_queue_size, max_queue_size, true); + GET_HEAP_DATA_VIEW().setUint32(tsfn + emnapiTSFN.offset.ref, ref, true); + GET_HEAP_DATA_VIEW().setUint32(tsfn + emnapiTSFN.offset.env, env, true); + GET_HEAP_DATA_VIEW().setUint32(tsfn + emnapiTSFN.offset.finalize_data, thread_finalize_data, true); + GET_HEAP_DATA_VIEW().setUint32(tsfn + emnapiTSFN.offset.finalize_cb, thread_finalize_cb, true); + GET_HEAP_DATA_VIEW().setUint32(tsfn + emnapiTSFN.offset.call_js_cb, call_js_cb, true); + emnapiCtx.addCleanupHook(envObject, emnapiTSFN.cleanup, tsfn); + emnapiTSFN._liveSet.add(tsfn); + envObject.ref(); + emnapiCtx.increaseWaitingRequestCounter(); + GET_HEAP_DATA_VIEW().setUint32(tsfn + emnapiTSFN.offset.async_ref, 1, true); + result >>>= 0; + GET_HEAP_DATA_VIEW().setUint32(result, tsfn, true); + return envObject.clearLastError(); + } + /** @__sig ipp */ + function napi_get_threadsafe_function_context(func, result) { + if (!func || !result) { + abort(); + return 1 /* napi_status.napi_invalid_arg */; + } + func >>>= 0; + result >>>= 0; + // eslint-disable-next-line @typescript-eslint/no-unused-vars + var context = emnapiTSFN.getContext(func); + var HEAP_DATA_VIEW = new DataView(wasmMemory.buffer), GET_HEAP_DATA_VIEW = function () { return HEAP_DATA_VIEW.buffer === wasmMemory.buffer ? HEAP_DATA_VIEW : (HEAP_DATA_VIEW = new DataView(wasmMemory.buffer)); }; + GET_HEAP_DATA_VIEW().setUint32(result, context, true); + return 0 /* napi_status.napi_ok */; + } + /** @__sig ippi */ + function napi_call_threadsafe_function(func, data, mode) { + if (!func) { + abort(); + return 1 /* napi_status.napi_invalid_arg */; + } + func >>>= 0; + data >>>= 0; + return emnapiTSFN.push(func, data, mode); + } + /** @__sig ip */ + function napi_acquire_threadsafe_function(func) { + if (!func) { + abort(); + return 1 /* napi_status.napi_invalid_arg */; + } + func >>>= 0; + var mutex = emnapiTSFN.getMutex(func); + return mutex.execute(function () { + if (emnapiTSFN.getState(func) === 0 /* State.kOpen */) { + emnapiTSFN.addThreadCount(func); + return 0 /* napi_status.napi_ok */; + } + return 16 /* napi_status.napi_closing */; + }); + } + /** @__sig ipi */ + function napi_release_threadsafe_function(func, mode) { + if (!func) { + abort(); + return 1 /* napi_status.napi_invalid_arg */; + } + func >>>= 0; + var mutex = emnapiTSFN.getMutex(func); + var cond = emnapiTSFN.getCond(func); + var shouldDelete = false; + var ret = mutex.execute(function () { + if (emnapiTSFN.getThreadCount(func) === 0) { + return 1 /* napi_status.napi_invalid_arg */; + } + emnapiTSFN.subThreadCount(func); + if (emnapiTSFN.getThreadCount(func) === 0 || mode === 1 /* napi_threadsafe_function_release_mode.napi_tsfn_abort */) { + if (emnapiTSFN.getState(func) === 0 /* State.kOpen */) { + if (mode === 1 /* napi_threadsafe_function_release_mode.napi_tsfn_abort */) { + emnapiTSFN.setState(func, 1 /* State.kClosing */); + } + if (emnapiTSFN.getState(func) === 1 /* State.kClosing */ && emnapiTSFN.getMaxQueueSize(func) > 0) { + cond.signal(); + } + emnapiTSFN.send(func); + } + } + if (!(emnapiTSFN.getState(func) === 2 /* State.kClosed */ && emnapiTSFN.getThreadCount(func) === 0)) { + return 0 /* napi_status.napi_ok */; + } + shouldDelete = true; + return 0 /* napi_status.napi_ok */; + }); + if (shouldDelete) { + emnapiTSFN.destroy(func); + } + return ret; + } + /** @__sig ipp */ + function napi_unref_threadsafe_function(env, func) { + if (!func) { + abort(); + return 1 /* napi_status.napi_invalid_arg */; + } + func >>>= 0; + var asyncRefAddress = func + emnapiTSFN.offset.async_ref; + var asyncRefOffset = asyncRefAddress >>> 2; + var arr = new Uint32Array(emnapiTSFN.ensureBufferFor(asyncRefAddress + 4)); + var currentValue = Atomics.load(arr, asyncRefOffset); + if (currentValue > 0) { + Atomics.store(arr, asyncRefOffset, currentValue - 1); + if (currentValue === 1) { + emnapiCtx.decreaseWaitingRequestCounter(); + } + } + return 0 /* napi_status.napi_ok */; + } + /** @__sig ipp */ + function napi_ref_threadsafe_function(env, func) { + if (!func) { + abort(); + return 1 /* napi_status.napi_invalid_arg */; + } + func >>>= 0; + var asyncRefAddress = func + emnapiTSFN.offset.async_ref; + var asyncRefOffset = asyncRefAddress >>> 2; + var arr = new Uint32Array(emnapiTSFN.ensureBufferFor(asyncRefAddress + 4)); + var currentValue = Atomics.load(arr, asyncRefOffset); + if (!currentValue) { + emnapiCtx.increaseWaitingRequestCounter(); + } + Atomics.store(arr, asyncRefOffset, currentValue + 1); + return 0 /* napi_status.napi_ok */; + } + var emnapiAWMT = { + pool: [], + workerReady: null, + globalAddress: 0, + globalOffset: { + idle_threads: 0, + q: 1 * 4, + next: 1 * 4, + prev: 2 * 4, + mutex: 3 * 4, + cond: 4 * 4, + exit_message: 5 * 4, + end: 7 * 4 + }, + offset: { + /* napi_ref */ resource: 0, + /* double */ async_id: 8, + /* double */ trigger_async_id: 16, + /* napi_env */ env: 24, + /* int32_t */ status: 1 * 4 + 24, // 0 for pending, 1 for cancelled, 2 for completed + queue: 2 * 4 + 24, + queue_next: 2 * 4 + 24, + queue_prev: 3 * 4 + 24, + /* void* */ data: 4 * 4 + 24, + /* napi_async_execute_callback */ execute: 5 * 4 + 24, + /* napi_async_complete_callback */ complete: 6 * 4 + 24, + end: 7 * 4 + 24 + }, + /** + * When another thread grows the shared WebAssembly.Memory, this agent's + * cached `wasmMemory.buffer` may still have the old shorter length + * (V8 refreshes it lazily). If a pointer derived from shared memory lies + * beyond the cached length, `wasmMemory.grow(0)` forces the agent to + * observe the current memory size and refreshes the buffer. + */ + ensureBufferFor: function (end) { + var buffer = wasmMemory.buffer; + if (end > buffer.byteLength) { + wasmMemory.grow(0); + buffer = wasmMemory.buffer; + } + return buffer; + }, + init: function () { + emnapiAWMT.pool = []; + emnapiAWMT.workerReady = null; + if (typeof PThread !== 'undefined') { + PThread.unusedWorkers.forEach(emnapiAWMT.addListener); + Object.values(PThread.pthreads).forEach(emnapiAWMT.addListener); + var __original_getNewWorker_1 = PThread.getNewWorker; + PThread.getNewWorker = function () { + var r = __original_getNewWorker_1.apply(this, arguments); + emnapiAWMT.addListener(r); + return r; + }; + } + }, + addListener: function (worker) { + if (!worker) + return false; + if (worker._emnapiAWMTListener) + return true; + var handler = function (e) { + var data = ENVIRONMENT_IS_NODE ? e : e.data; + var __emnapi__ = data.__emnapi__; + if (__emnapi__) { + var type = __emnapi__.type; + var payload = __emnapi__.payload; + if (type === 'async-work-complete') { + emnapiAWMT.callComplete(payload.work, 0 /* napi_status.napi_ok */); + } + } + }; + var dispose = function () { + if (ENVIRONMENT_IS_NODE) { + worker.off('message', handler); + } + else { + worker.removeEventListener('message', handler, false); + } + delete worker._emnapiAWMTListener; + }; + worker._emnapiAWMTListener = { handler: handler, dispose: dispose }; + if (ENVIRONMENT_IS_NODE) { + worker.on('message', handler); + } + else { + worker.addEventListener('message', handler, false); + } + return true; + }, + initGlobal: function () { + if (!emnapiAWMT.globalAddress) { + emnapiAWMT.globalAddress = _malloc(emnapiAWMT.globalOffset.end); + emnapiAWMT.globalAddress >>>= 0; + var size = emnapiAWMT.globalOffset.end; + var addr = emnapiAWMT.globalAddress; + new Uint8Array(emnapiAWMT.ensureBufferFor(addr + size), addr, size).fill(0); + emnapiAWMT.queueInit(emnapiAWMT.globalAddress + emnapiAWMT.globalOffset.q); + emnapiAWMT.queueInit(emnapiAWMT.globalAddress + emnapiAWMT.globalOffset.exit_message); + } + }, + terminateWorkers: function () { + emnapiAWMT.pool.forEach(function (w) { + var _a, _b; + (_a = w._emnapiAWMTListener) === null || _a === void 0 ? void 0 : _a.dispose(); + (_b = w._emnapiTSFNListener) === null || _b === void 0 ? void 0 : _b.dispose(); + w.terminate(); + }); + emnapiAWMT.pool.length = 0; + }, + initWorkers: function (n) { + if (ENVIRONMENT_IS_PTHREAD) { + // eslint-disable-next-line @typescript-eslint/prefer-nullish-coalescing + return emnapiAWMT.workerReady || (emnapiAWMT.workerReady = Promise.resolve()); + } + if (emnapiAWMT.workerReady) + return emnapiAWMT.workerReady; + if (!('emnapi_async_worker_create' in wasmInstance.exports)) { + throw new TypeError('`emnapi_async_worker_create` is not exported, please try to add `--export=emnapi_async_worker_create` to linker flags'); + } + var emnapi_async_worker_create = wasmInstance.exports.emnapi_async_worker_create; + var args = []; + emnapiAWMT.initGlobal(); + for (var i = 0; i < n; ++i) { + args.push(emnapi_async_worker_create(1, emnapiAWMT.globalAddress)); + } + var promises = args.map(function (index) { + if (index === 0) { + return Promise.reject(new Error('Failed to create async worker')); + } + var worker; + if (index < 0) { + worker = emnapiAWMT.pool[-index - 1]; + if (worker) + return worker.whenLoaded; + } + index >>>= 0; + var tidOffset = 20; + var view = new DataView(emnapiAWMT.ensureBufferFor(index + tidOffset + 4)); + var tid = view.getInt32(index + tidOffset, true); + worker = PThread.pthreads[tid]; + return worker.whenLoaded; + }); + emnapiAWMT.workerReady = Promise.all(promises); + return emnapiAWMT.workerReady; + }, + getResource: function (work) { + emnapiAWMT.ensureBufferFor(work + emnapiAWMT.offset.resource + 4); + var HEAP_DATA_VIEW = new DataView(wasmMemory.buffer), GET_HEAP_DATA_VIEW = function () { return HEAP_DATA_VIEW.buffer === wasmMemory.buffer ? HEAP_DATA_VIEW : (HEAP_DATA_VIEW = new DataView(wasmMemory.buffer)); }; + return GET_HEAP_DATA_VIEW().getUint32(work + emnapiAWMT.offset.resource, true); + }, + getExecute: function (work) { + emnapiAWMT.ensureBufferFor(work + emnapiAWMT.offset.execute + 4); + var HEAP_DATA_VIEW = new DataView(wasmMemory.buffer), GET_HEAP_DATA_VIEW = function () { return HEAP_DATA_VIEW.buffer === wasmMemory.buffer ? HEAP_DATA_VIEW : (HEAP_DATA_VIEW = new DataView(wasmMemory.buffer)); }; + return GET_HEAP_DATA_VIEW().getUint32(work + emnapiAWMT.offset.execute, true); + }, + getComplete: function (work) { + emnapiAWMT.ensureBufferFor(work + emnapiAWMT.offset.complete + 4); + var HEAP_DATA_VIEW = new DataView(wasmMemory.buffer), GET_HEAP_DATA_VIEW = function () { return HEAP_DATA_VIEW.buffer === wasmMemory.buffer ? HEAP_DATA_VIEW : (HEAP_DATA_VIEW = new DataView(wasmMemory.buffer)); }; + return GET_HEAP_DATA_VIEW().getUint32(work + emnapiAWMT.offset.complete, true); + }, + getEnv: function (work) { + emnapiAWMT.ensureBufferFor(work + emnapiAWMT.offset.env + 4); + var HEAP_DATA_VIEW = new DataView(wasmMemory.buffer), GET_HEAP_DATA_VIEW = function () { return HEAP_DATA_VIEW.buffer === wasmMemory.buffer ? HEAP_DATA_VIEW : (HEAP_DATA_VIEW = new DataView(wasmMemory.buffer)); }; + return GET_HEAP_DATA_VIEW().getUint32(work + emnapiAWMT.offset.env, true); + }, + getData: function (work) { + emnapiAWMT.ensureBufferFor(work + emnapiAWMT.offset.data + 4); + var HEAP_DATA_VIEW = new DataView(wasmMemory.buffer), GET_HEAP_DATA_VIEW = function () { return HEAP_DATA_VIEW.buffer === wasmMemory.buffer ? HEAP_DATA_VIEW : (HEAP_DATA_VIEW = new DataView(wasmMemory.buffer)); }; + return GET_HEAP_DATA_VIEW().getUint32(work + emnapiAWMT.offset.data, true); + }, + getMutex: function () { + var index = emnapiAWMT.globalAddress + emnapiAWMT.globalOffset.mutex; + var mutex = { + lock: function () { + var isBrowserMain = typeof window !== 'undefined' && typeof document !== 'undefined' && !ENVIRONMENT_IS_NODE; + var i32a = new Int32Array(emnapiAWMT.ensureBufferFor(index + 4), index, 1); + if (isBrowserMain) { + while (true) { + var oldValue = Atomics.compareExchange(i32a, 0, 0, 10); + if (oldValue === 0) { + return; + } + } + } + else { + while (true) { + var oldValue = Atomics.compareExchange(i32a, 0, 0, 10); + if (oldValue === 0) { + return; + } + Atomics.wait(i32a, 0, 10); + } + } + }, + unlock: function () { + var i32a = new Int32Array(emnapiAWMT.ensureBufferFor(index + 4), index, 1); + var oldValue = Atomics.compareExchange(i32a, 0, 10, 0); + if (oldValue !== 10) { + throw new Error('Tried to unlock while not holding the mutex'); + } + Atomics.notify(i32a, 0, 1); + }, + execute: function (fn) { + mutex.lock(); + try { + return fn(); + } + finally { + mutex.unlock(); + } + } + }; + return mutex; + }, + getCond: function () { + var index = emnapiAWMT.globalAddress + emnapiAWMT.globalOffset.cond; + var mutex = emnapiAWMT.getMutex(); + var cond = { + wait: function () { + var i32a = new Int32Array(emnapiAWMT.ensureBufferFor(index + 4), index, 1); + var value = Atomics.load(i32a, 0); + mutex.unlock(); + Atomics.wait(i32a, 0, value); + mutex.lock(); + }, + signal: function () { + var i32a = new Int32Array(emnapiAWMT.ensureBufferFor(index + 4), index, 1); + Atomics.add(i32a, 0, 1); + Atomics.notify(i32a, 0, 1); + } + }; + return cond; + }, + queueInit: function (q) { + emnapiAWMT.ensureBufferFor(q + 4 + 4); + var HEAP_DATA_VIEW = new DataView(wasmMemory.buffer), GET_HEAP_DATA_VIEW = function () { return HEAP_DATA_VIEW.buffer === wasmMemory.buffer ? HEAP_DATA_VIEW : (HEAP_DATA_VIEW = new DataView(wasmMemory.buffer)); }; + GET_HEAP_DATA_VIEW().setUint32(q, q, true); + GET_HEAP_DATA_VIEW().setUint32(q + 4, q, true); + }, + queueInsertTail: function (h, q) { + emnapiAWMT.ensureBufferFor(h + 4 + 4); + emnapiAWMT.ensureBufferFor(q + 4 + 4); + var HEAP_DATA_VIEW = new DataView(wasmMemory.buffer), GET_HEAP_DATA_VIEW = function () { return HEAP_DATA_VIEW.buffer === wasmMemory.buffer ? HEAP_DATA_VIEW : (HEAP_DATA_VIEW = new DataView(wasmMemory.buffer)); }; + GET_HEAP_DATA_VIEW().setUint32(q, h, true); + // eslint-disable-next-line @typescript-eslint/no-unused-vars + var tempValue = GET_HEAP_DATA_VIEW().getUint32(h + 4, true); + GET_HEAP_DATA_VIEW().setUint32(q + 4, tempValue, true); + // eslint-disable-next-line @typescript-eslint/no-unused-vars + var qprev = GET_HEAP_DATA_VIEW().getUint32(q + 4, true); + GET_HEAP_DATA_VIEW().setUint32(qprev, q, true); + GET_HEAP_DATA_VIEW().setUint32(h + 4, q, true); + }, + queueRemove: function (q) { + emnapiAWMT.ensureBufferFor(q + 4 + 4); + var HEAP_DATA_VIEW = new DataView(wasmMemory.buffer), GET_HEAP_DATA_VIEW = function () { return HEAP_DATA_VIEW.buffer === wasmMemory.buffer ? HEAP_DATA_VIEW : (HEAP_DATA_VIEW = new DataView(wasmMemory.buffer)); }; + // eslint-disable-next-line @typescript-eslint/no-unused-vars + var qprev = GET_HEAP_DATA_VIEW().getUint32(q + 4, true); + // eslint-disable-next-line @typescript-eslint/no-unused-vars + var qnext = GET_HEAP_DATA_VIEW().getUint32(q, true); + GET_HEAP_DATA_VIEW().setUint32(qprev, qnext, true); + GET_HEAP_DATA_VIEW().setUint32(qnext + 4, qprev, true); + }, + queueEmpty: function (q) { + emnapiAWMT.ensureBufferFor(q + 4); + var HEAP_DATA_VIEW = new DataView(wasmMemory.buffer), GET_HEAP_DATA_VIEW = function () { return HEAP_DATA_VIEW.buffer === wasmMemory.buffer ? HEAP_DATA_VIEW : (HEAP_DATA_VIEW = new DataView(wasmMemory.buffer)); }; + // eslint-disable-next-line eqeqeq + return q == GET_HEAP_DATA_VIEW().getUint32(q, true); + }, + scheduleWork: function (work) { + var _a; + if (!((_a = emnapiAWMT.workerReady) === null || _a === void 0 ? void 0 : _a.ready)) { + emnapiAWMT.initWorkers(_emnapi_async_work_pool_size()).then(function () { + emnapiAWMT.workerReady.ready = true; + }).catch(function (err) { + emnapiAWMT.workerReady = null; + throw err; + }); + } + emnapiCtx.increaseWaitingRequestCounter(); + var statusBuffer = new Int32Array(emnapiAWMT.ensureBufferFor(work + emnapiAWMT.offset.status + 4), work + emnapiAWMT.offset.status, 1); + Atomics.store(statusBuffer, 0, 0 /* AsyncWorkStatus.Pending */); + var mutex = emnapiAWMT.getMutex(); + var cond = emnapiAWMT.getCond(); + mutex.lock(); + try { + emnapiAWMT.queueInsertTail(emnapiAWMT.globalAddress + emnapiAWMT.globalOffset.q, work + emnapiAWMT.offset.queue); + } + catch (err) { + emnapiCtx.decreaseWaitingRequestCounter(); + mutex.unlock(); + throw err; + } + emnapiAWMT.ensureBufferFor(emnapiAWMT.globalAddress + emnapiAWMT.globalOffset.idle_threads + 4); + var HEAP_DATA_VIEW = new DataView(wasmMemory.buffer), GET_HEAP_DATA_VIEW = function () { return HEAP_DATA_VIEW.buffer === wasmMemory.buffer ? HEAP_DATA_VIEW : (HEAP_DATA_VIEW = new DataView(wasmMemory.buffer)); }; + if (GET_HEAP_DATA_VIEW().getUint32(emnapiAWMT.globalAddress + emnapiAWMT.globalOffset.idle_threads, true) > 0) { + cond.signal(); + } + mutex.unlock(); + }, + cancelWork: function (work) { + var cancelled = false; + emnapiAWMT.getMutex().execute(function () { + emnapiAWMT.ensureBufferFor(work + emnapiAWMT.offset.status + 4); + var HEAP_DATA_VIEW = new DataView(wasmMemory.buffer), GET_HEAP_DATA_VIEW = function () { return HEAP_DATA_VIEW.buffer === wasmMemory.buffer ? HEAP_DATA_VIEW : (HEAP_DATA_VIEW = new DataView(wasmMemory.buffer)); }; + cancelled = !emnapiAWMT.queueEmpty(work + emnapiAWMT.offset.queue) && GET_HEAP_DATA_VIEW().getInt32(work + emnapiAWMT.offset.status, true) !== 2 /* AsyncWorkStatus.Completed */; + if (cancelled) { + emnapiAWMT.queueRemove(work + emnapiAWMT.offset.queue); + } + }); + if (!cancelled) { + return 9 /* napi_status.napi_generic_failure */; + } + if (Atomics.compareExchange(new Int32Array(emnapiAWMT.ensureBufferFor(work + emnapiAWMT.offset.status + 4), work + emnapiAWMT.offset.status, 1), 0, 0 /* AsyncWorkStatus.Pending */, 1 /* AsyncWorkStatus.Cancelled */) !== 0 /* AsyncWorkStatus.Pending */) { + return 9 /* napi_status.napi_generic_failure */; + } + emnapiCtx.feature.setImmediate(function () { + emnapiAWMT.callComplete(work, 11 /* napi_status.napi_cancelled */); + }); + return 0 /* napi_status.napi_ok */; + }, + callComplete: function (work, status) { + emnapiCtx.decreaseWaitingRequestCounter(); + var complete = emnapiAWMT.getComplete(work); + var env = emnapiAWMT.getEnv(work); + var data = emnapiAWMT.getData(work); + var envObject = emnapiCtx.envStore.get(env); + var scope = emnapiCtx.openScope(envObject); + var callback = function () { + if (!complete) + return; + envObject.callbackIntoModule(true, function () { + (wasmTable.get(complete))(env, status, data); + }); + }; + try { + if (emnapiNodeBinding) { + var resource = emnapiAWMT.getResource(work); + var resource_value = emnapiCtx.refStore.get(resource).get(); + var resourceObject = emnapiCtx.handleStore.get(resource_value).value; + var view = new DataView(emnapiAWMT.ensureBufferFor(work + emnapiAWMT.offset.trigger_async_id + 8)); + var asyncId = view.getFloat64(work + emnapiAWMT.offset.async_id, true); + var triggerAsyncId = view.getFloat64(work + emnapiAWMT.offset.trigger_async_id, true); + emnapiNodeBinding.node.makeCallback(resourceObject, callback, [], { + asyncId: asyncId, + triggerAsyncId: triggerAsyncId + }); + } + else { + callback(); + } + } + finally { + emnapiCtx.closeScope(envObject, scope); + } + } + }; + emnapiAWMT.init(); + /** @__sig ippppppp */ + var napi_create_async_work = singleThreadAsyncWork + ? function (env, resource, resource_name, execute, complete, data, result) { + if (!env) + return 1 /* napi_status.napi_invalid_arg */; + // @ts-expect-error + var envObject = emnapiCtx.envStore.get(env); + envObject.checkGCAccess(); + if (!execute) + return envObject.setLastError(1 /* napi_status.napi_invalid_arg */); + if (!result) + return envObject.setLastError(1 /* napi_status.napi_invalid_arg */); + var resourceObject; + if (resource) { + resourceObject = Object(emnapiCtx.handleStore.get(resource).value); + } + else { + resourceObject = {}; + } + if (!resource_name) + return envObject.setLastError(1 /* napi_status.napi_invalid_arg */); + var resourceName = String(emnapiCtx.handleStore.get(resource_name).value); + // eslint-disable-next-line @typescript-eslint/no-unused-vars + var id = emnapiAWST.create(env, resourceObject, resourceName, execute, complete, data); + result >>>= 0; + var HEAP_DATA_VIEW = new DataView(wasmMemory.buffer), GET_HEAP_DATA_VIEW = function () { return HEAP_DATA_VIEW.buffer === wasmMemory.buffer ? HEAP_DATA_VIEW : (HEAP_DATA_VIEW = new DataView(wasmMemory.buffer)); }; + GET_HEAP_DATA_VIEW().setUint32(result, id, true); + return envObject.clearLastError(); + } + : function (env, resource, resource_name, execute, complete, data, result) { + if (!env) + return 1 /* napi_status.napi_invalid_arg */; + // @ts-expect-error + var envObject = emnapiCtx.envStore.get(env); + envObject.checkGCAccess(); + if (!execute) + return envObject.setLastError(1 /* napi_status.napi_invalid_arg */); + if (!result) + return envObject.setLastError(1 /* napi_status.napi_invalid_arg */); + var resourceObject; + if (resource) { + resourceObject = Object(emnapiCtx.handleStore.get(resource).value); + } + else { + resourceObject = {}; + } + if (!resource_name) + return envObject.setLastError(1 /* napi_status.napi_invalid_arg */); + var sizeofAW = emnapiAWMT.offset.end; + var aw = _malloc(sizeofAW); + if (!aw) + return envObject.setLastError(9 /* napi_status.napi_generic_failure */); + aw >>>= 0; + new Uint8Array(emnapiAWMT.ensureBufferFor(aw + sizeofAW)).subarray(aw, aw + sizeofAW).fill(0); + var s = envObject.ensureHandleId(resourceObject); + var resourceRef = emnapiCtx.createReference(envObject, s, 1, 1 /* ReferenceOwnership.kUserland */); + // eslint-disable-next-line @typescript-eslint/no-unused-vars + var resource_ = resourceRef.id; + var HEAP_DATA_VIEW = new DataView(wasmMemory.buffer), GET_HEAP_DATA_VIEW = function () { return HEAP_DATA_VIEW.buffer === wasmMemory.buffer ? HEAP_DATA_VIEW : (HEAP_DATA_VIEW = new DataView(wasmMemory.buffer)); }; + GET_HEAP_DATA_VIEW().setUint32(aw, resource_, true); + _emnapi_node_emit_async_init(s, resource_name, -1, aw + emnapiAWMT.offset.async_id); + GET_HEAP_DATA_VIEW().setUint32(aw + emnapiAWMT.offset.env, env, true); + GET_HEAP_DATA_VIEW().setUint32(aw + emnapiAWMT.offset.execute, execute, true); + GET_HEAP_DATA_VIEW().setUint32(aw + emnapiAWMT.offset.complete, complete, true); + GET_HEAP_DATA_VIEW().setUint32(aw + emnapiAWMT.offset.data, data, true); + emnapiAWMT.queueInit(aw + emnapiAWMT.offset.queue); + result >>>= 0; + GET_HEAP_DATA_VIEW().setUint32(result, aw, true); + return envObject.clearLastError(); + }; + /** @__sig ipp */ + var napi_delete_async_work = singleThreadAsyncWork + ? function (env, work) { + if (!env) + return 1 /* napi_status.napi_invalid_arg */; + // @ts-expect-error + var envObject = emnapiCtx.envStore.get(env); + envObject.checkGCAccess(); + if (!work) + return envObject.setLastError(1 /* napi_status.napi_invalid_arg */); + work >>>= 0; + emnapiAWST.remove(work); + return envObject.clearLastError(); + } + : function (env, work) { + if (!env) + return 1 /* napi_status.napi_invalid_arg */; + // @ts-expect-error + var envObject = emnapiCtx.envStore.get(env); + envObject.checkGCAccess(); + if (!work) + return envObject.setLastError(1 /* napi_status.napi_invalid_arg */); + work >>>= 0; + var resource = emnapiAWMT.getResource(work); + emnapiCtx.refStore.get(resource).dispose(); + if (emnapiNodeBinding) { + var view = new DataView(emnapiAWMT.ensureBufferFor(work + emnapiAWMT.offset.trigger_async_id + 8)); + var asyncId = view.getFloat64(work + emnapiAWMT.offset.async_id, true); + var triggerAsyncId = view.getFloat64(work + emnapiAWMT.offset.trigger_async_id, true); + _emnapi_node_emit_async_destroy(asyncId, triggerAsyncId); + } + _free(work); + return envObject.clearLastError(); + }; + /** @__sig ipp */ + var napi_queue_async_work = singleThreadAsyncWork + ? function (env, work) { + if (!env) + return 1 /* napi_status.napi_invalid_arg */; + var envObject = emnapiCtx.envStore.get(env); + if (!work) + return envObject.setLastError(1 /* napi_status.napi_invalid_arg */); + work >>>= 0; + emnapiAWST.queue(work); + return envObject.clearLastError(); + } + : function (env, work) { + if (!env) + return 1 /* napi_status.napi_invalid_arg */; + var envObject = emnapiCtx.envStore.get(env); + if (!work) + return envObject.setLastError(1 /* napi_status.napi_invalid_arg */); + work >>>= 0; + emnapiAWMT.scheduleWork(work); + return envObject.clearLastError(); + }; + /** @__sig ipp */ + var napi_cancel_async_work = singleThreadAsyncWork + ? function (env, work) { + if (!env) + return 1 /* napi_status.napi_invalid_arg */; + var envObject = emnapiCtx.envStore.get(env); + if (!work) + return envObject.setLastError(1 /* napi_status.napi_invalid_arg */); + work >>>= 0; + var status = emnapiAWST.cancel(work); + if (status === 0 /* napi_status.napi_ok */) + return envObject.clearLastError(); + return envObject.setLastError(status); + } + : function (env, work) { + if (!env) + return 1 /* napi_status.napi_invalid_arg */; + var envObject = emnapiCtx.envStore.get(env); + if (!work) + return envObject.setLastError(1 /* napi_status.napi_invalid_arg */); + work >>>= 0; + var status = emnapiAWMT.cancelWork(work); + if (status === 0 /* napi_status.napi_ok */) + return envObject.clearLastError(); + return envObject.setLastError(status); + }; + /** @__sig pp */ + function _emnapi_async_worker(globalAddress) { + globalAddress >>>= 0; + emnapiAWMT.globalAddress = globalAddress; + var mutex = emnapiAWMT.getMutex(); + var cond = emnapiAWMT.getCond(); + mutex.lock(); + var exitMessageAddr = globalAddress + emnapiAWMT.globalOffset.exit_message; + var idleThreadsAddr = globalAddress + emnapiAWMT.globalOffset.idle_threads; + var workerQueueAddr = globalAddress + emnapiAWMT.globalOffset.q; + var HEAP_DATA_VIEW = new DataView(wasmMemory.buffer), GET_HEAP_DATA_VIEW = function () { return HEAP_DATA_VIEW.buffer === wasmMemory.buffer ? HEAP_DATA_VIEW : (HEAP_DATA_VIEW = new DataView(wasmMemory.buffer)); }; + for (;;) { + emnapiAWMT.ensureBufferFor(workerQueueAddr + 4); + while (emnapiAWMT.queueEmpty(workerQueueAddr)) { + Atomics.add(new Int32Array(emnapiAWMT.ensureBufferFor(idleThreadsAddr + 4), idleThreadsAddr, 1), 0, 1); + cond.wait(); + Atomics.sub(new Int32Array(emnapiAWMT.ensureBufferFor(idleThreadsAddr + 4), idleThreadsAddr, 1), 0, 1); + } + var q = GET_HEAP_DATA_VIEW().getUint32(workerQueueAddr, true); + if (q === exitMessageAddr) { + cond.signal(); + mutex.unlock(); + break; + } + var work = q - emnapiAWMT.offset.queue; + emnapiAWMT.queueRemove(q); + emnapiAWMT.queueInit(q); + mutex.unlock(); + var statusBuffer = new Int32Array(emnapiAWMT.ensureBufferFor(work + emnapiAWMT.offset.status + 4), work + emnapiAWMT.offset.status, 1); + if (Atomics.load(statusBuffer, 0) === 1 /* AsyncWorkStatus.Cancelled */) { + abort('unreachable'); + } + // eslint-disable-next-line @typescript-eslint/no-unused-vars + var execute = emnapiAWMT.getExecute(work); + var env = emnapiAWMT.getEnv(work); + var data = emnapiAWMT.getData(work); + (wasmTable.get(execute))(env, data); + Atomics.store(statusBuffer, 0, 2 /* AsyncWorkStatus.Completed */); + var postMessage_1 = napiModule.postMessage; + postMessage_1({ + __emnapi__: { + type: 'async-work-complete', + payload: { work: work } + } + }); + mutex.lock(); + } + return 0; + } + /** @__sig ipp */ + function _emnapi_spawn_worker(f, globalAddress) { + if (typeof onCreateWorker !== 'function') { + throw new TypeError('`options.onCreateWorker` is not a function'); + } + var promises = []; + var args = []; + if (!('emnapi_async_worker_create' in wasmInstance.exports)) { + throw new TypeError('`emnapi_async_worker_create` is not exported, please try to add `--export=emnapi_async_worker_create` to linker flags'); + } + args.push(wasmInstance.exports.emnapi_async_worker_create(0, 0)); + var handleError = function (e) { + if ('message' in e && (e.message.indexOf('RuntimeError') !== -1 || e.message.indexOf('unreachable') !== -1)) { + emnapiAWMT.terminateWorkers(); + } + }; + var ret; + try { + var worker_1 = onCreateWorker({ type: 'async-work', name: 'emnapi-async-worker' }); + var p = PThread.loadWasmModuleToWorker(worker_1); + if (ENVIRONMENT_IS_NODE) { + worker_1.on('error', handleError); + } + else { + worker_1.addEventListener('error', handleError, false); + } + emnapiAWMT.addListener(worker_1); + emnapiTSFN.addListener(worker_1); + promises.push(p.then(function () { + if (typeof worker_1.unref === 'function') { + worker_1.unref(); + } + })); + ret = emnapiAWMT.pool.push(worker_1) - 1; + var arg = args[0]; + worker_1.threadBlockBase = arg; + worker_1.postMessage({ + __emnapi__: { + type: 'async-worker-init', + payload: { arg: arg, func: [f, globalAddress] } + } + }); + } + catch (err) { + // eslint-disable-next-line @typescript-eslint/no-unused-vars + var arg = args[0]; + _free(arg); + throw err; + } + return ret; + } + function initWorker(startArg, func) { + if (napiModule.childThread) { + if (typeof wasmInstance.exports.emnapi_async_worker_init !== 'function') { + throw new TypeError('`emnapi_async_worker_init` is not exported, please try to add `--export=emnapi_async_worker_init` to linker flags'); + } + wasmInstance.exports.emnapi_async_worker_init(startArg); + (wasmTable.get(func[0]))(func[1]); + } + else { + throw new Error('startThread is only available in child threads'); + } + } + napiModule.initWorker = initWorker; + var asyncWorkMod = /*#__PURE__*/ Object.freeze({ + __proto__: null, + _emnapi_async_worker: _emnapi_async_worker, + _emnapi_spawn_worker: _emnapi_spawn_worker, + napi_cancel_async_work: napi_cancel_async_work, + napi_create_async_work: napi_create_async_work, + napi_delete_async_work: napi_delete_async_work, + napi_queue_async_work: napi_queue_async_work + }); + /** + * @__deps malloc + * @__deps free + * @__postset + * ``` + * emnapiExternalMemory.init(); + * ``` + */ + var emnapiExternalMemory = { + registry: typeof FinalizationRegistry === 'function' ? new FinalizationRegistry(function (_pointer) { _free(_pointer); }) : undefined, + table: new WeakMap(), + wasmMemoryViewTable: new WeakMap(), + // populated by init(): live intrinsic function references must not exist at + // library definition time — the emscripten jsifier re-serializes this object + // and native functions do not stringify to parseable source + intrinsics: undefined, + init: function () { + var _a; + emnapiExternalMemory.registry = typeof FinalizationRegistry === 'function' ? new FinalizationRegistry(function (_pointer) { _free(_pointer); }) : undefined; + emnapiExternalMemory.table = new WeakMap(); + emnapiExternalMemory.wasmMemoryViewTable = new WeakMap(); + var sharedArrayBufferByteLength = typeof SharedArrayBuffer === 'function' + ? (_a = Object.getOwnPropertyDescriptor(SharedArrayBuffer.prototype, 'byteLength')) === null || _a === void 0 ? void 0 : _a.get + : undefined; + // cached intrinsic prototype getters and element-type constructors: they + // read the internal slots directly like native Node-API does, so user + // accessors and user subclass constructors can never run inside get-info + // metadata reads, descriptor registration or view reconstruction, and they + // work for instances from any realm + emnapiExternalMemory.intrinsics = { + // ArrayBuffer.isView ignores its `this`, so a bare cached reference is + // safe and cannot be swapped out by user code replacing the global + isView: ArrayBuffer.isView, + typedArray: { + buffer: Object.getOwnPropertyDescriptor(Object.getPrototypeOf(Uint8Array.prototype), 'buffer').get, + byteOffset: Object.getOwnPropertyDescriptor(Object.getPrototypeOf(Uint8Array.prototype), 'byteOffset').get, + length: Object.getOwnPropertyDescriptor(Object.getPrototypeOf(Uint8Array.prototype), 'length').get, + tag: Object.getOwnPropertyDescriptor(Object.getPrototypeOf(Uint8Array.prototype), Symbol.toStringTag).get + }, + dataView: { + buffer: Object.getOwnPropertyDescriptor(DataView.prototype, 'buffer').get, + byteOffset: Object.getOwnPropertyDescriptor(DataView.prototype, 'byteOffset').get, + byteLength: Object.getOwnPropertyDescriptor(DataView.prototype, 'byteLength').get + }, + arrayBuffer: { + byteLength: Object.getOwnPropertyDescriptor(ArrayBuffer.prototype, 'byteLength').get + }, + // a SharedArrayBuffer polyfill may lack the byteLength accessor: degrade + // to the hidden-global classification path instead of throwing here + sharedArrayBuffer: sharedArrayBufferByteLength !== undefined + ? { + byteLength: sharedArrayBufferByteLength + } + : undefined, + ctors: { + Int8Array: Int8Array, + Uint8Array: Uint8Array, + Uint8ClampedArray: Uint8ClampedArray, + Int16Array: Int16Array, + Uint16Array: Uint16Array, + Int32Array: Int32Array, + Uint32Array: Uint32Array, + Float16Array: typeof Float16Array === 'function' ? Float16Array : undefined, + Float32Array: Float32Array, + Float64Array: Float64Array, + BigInt64Array: BigInt64Array, + BigUint64Array: BigUint64Array + }, + bufferFrom: undefined + }; + }, + isSharedArrayBuffer: function (value) { + var sharedArrayBuffer = emnapiExternalMemory.intrinsics.sharedArrayBuffer; + if (sharedArrayBuffer !== undefined) { + if (typeof SharedArrayBuffer === 'function' && value instanceof SharedArrayBuffer) + return true; + // the intrinsic byteLength getter reads the internal slot: it accepts + // SharedArrayBuffer instances from any realm and throws for anything + // else, without consulting user-controllable properties + try { + sharedArrayBuffer.byteLength.call(value); + return true; + } + catch (_) { + return false; + } + } + // hidden-global environment (see #143): the SharedArrayBuffer global was + // absent at init time, but the engine can still hand out genuine SABs + // (e.g. a shared WebAssembly.Memory buffer). A genuine ArrayBuffer + // answers the intrinsic byteLength probe, settling the common case + // without the (spoofable, user-JS-running) toString tag read below. + try { + emnapiExternalMemory.intrinsics.arrayBuffer.byteLength.call(value); + return false; + } + catch (_) { } + return Object.prototype.toString.call(value) === '[object SharedArrayBuffer]'; + }, + isDetachedArrayBuffer: function (arrayBuffer) { + if (emnapiExternalMemory.bufferByteLength(arrayBuffer) === 0) { + try { + // eslint-disable-next-line no-new + new Uint8Array(arrayBuffer); + } + catch (_) { + return true; + } + } + return false; + }, + bufferByteLength: function (buffer) { + var _a; + var intrinsics = emnapiExternalMemory.intrinsics; + try { + return intrinsics.arrayBuffer.byteLength.call(buffer); + } + catch (err) { + var sharedArrayBuffer = intrinsics.sharedArrayBuffer; + if (sharedArrayBuffer !== undefined) { + return sharedArrayBuffer.byteLength.call(buffer); + } + // hidden-global environment (see isSharedArrayBuffer): no SAB getter + // was capturable at init, recover it from the instance's own prototype + // (for a genuine SAB that is the hidden SharedArrayBuffer.prototype) + var proto = Object.getPrototypeOf(buffer); + var get = proto !== null && proto !== undefined + ? (_a = Object.getOwnPropertyDescriptor(proto, 'byteLength')) === null || _a === void 0 ? void 0 : _a.get + : undefined; + if (get === undefined) + throw err; + return get.call(buffer); + } + }, + viewBuffer: function (view) { + var intrinsics = emnapiExternalMemory.intrinsics; + return intrinsics.typedArray.tag.call(view) === undefined + ? intrinsics.dataView.buffer.call(view) + : intrinsics.typedArray.buffer.call(view); + }, + viewByteOffset: function (view) { + var intrinsics = emnapiExternalMemory.intrinsics; + return intrinsics.typedArray.tag.call(view) === undefined + ? intrinsics.dataView.byteOffset.call(view) + : intrinsics.typedArray.byteOffset.call(view); + }, + // element count for typed arrays, byteLength for DataViews (the unit used + // by the napi_get_typedarray_info / napi_get_dataview_info length outputs + // and by the view constructors at reconstruction) + viewLength: function (view) { + var intrinsics = emnapiExternalMemory.intrinsics; + return intrinsics.typedArray.tag.call(view) === undefined + ? intrinsics.dataView.byteLength.call(view) + : intrinsics.typedArray.length.call(view); + }, + // Buffer descriptors are only ever created by emnapi's own buffer creation + // paths; capturing Buffer.from the first time one is created snapshots the + // legitimate function before any later reconstruction, so a user replacing + // Buffer.from afterwards cannot influence a refreshed view + getBufferFrom: function () { + var _a; + return (_a = emnapiExternalMemory.intrinsics.bufferFrom) !== null && _a !== void 0 ? _a : (emnapiExternalMemory.intrinsics.bufferFrom = emnapiCtx.feature.Buffer.from); + }, + getArrayBufferPointer: function (arrayBuffer, shouldCopy) { + var _a; + var info = { + address: 0, + ownership: 0 /* ReferenceOwnership.kRuntime */, + runtimeAllocated: 0 + }; + if (arrayBuffer === wasmMemory.buffer) { + return info; + } + var isDetached = emnapiExternalMemory.isDetachedArrayBuffer(arrayBuffer); + if (emnapiExternalMemory.table.has(arrayBuffer)) { + var cachedInfo = emnapiExternalMemory.table.get(arrayBuffer); + if (isDetached) { + cachedInfo.address = 0; + return cachedInfo; + } + if (shouldCopy && cachedInfo.ownership === 0 /* ReferenceOwnership.kRuntime */ && cachedInfo.runtimeAllocated === 1) { + new Uint8Array(wasmMemory.buffer).set(new Uint8Array(arrayBuffer), cachedInfo.address); + } + return cachedInfo; + } + var byteLength = emnapiExternalMemory.bufferByteLength(arrayBuffer); + if (isDetached || (byteLength === 0)) { + return info; + } + if (!shouldCopy) { + return info; + } + var pointer = _malloc(byteLength); + if (!pointer) + throw new Error('Out of memory'); + pointer >>>= 0; + new Uint8Array(wasmMemory.buffer).set(new Uint8Array(arrayBuffer), pointer); + info.address = pointer; + info.ownership = emnapiExternalMemory.registry ? 0 /* ReferenceOwnership.kRuntime */ : 1 /* ReferenceOwnership.kUserland */; + info.runtimeAllocated = 1; + emnapiExternalMemory.table.set(arrayBuffer, info); + (_a = emnapiExternalMemory.registry) === null || _a === void 0 ? void 0 : _a.register(arrayBuffer, pointer); + return info; + }, + getOrUpdateMemoryView: function (view) { + // classify and read the view state through the cached intrinsic + // prototype getters only: own accessors on the instance could otherwise + // run user JS that grows (and detaches) a non-shared memory in the + // middle of registration, poisoning the stored descriptor; the intrinsic + // reads return primitives from the internal slots and run zero user JS. + // The @@toStringTag slot getter classifies views from any realm: it + // returns the element-type name for typed arrays (seeing through user + // subclasses) and undefined for DataViews + var intrinsics = emnapiExternalMemory.intrinsics; + var tag = intrinsics.typedArray.tag.call(view); + var isDataView = tag === undefined; + var buffer = isDataView ? intrinsics.dataView.buffer.call(view) : intrinsics.typedArray.buffer.call(view); + if (buffer === wasmMemory.buffer) { + if (!emnapiExternalMemory.wasmMemoryViewTable.has(view)) { + emnapiExternalMemory.wasmMemoryViewTable.set(view, { + // store the intrinsic element-type constructor keyed by the + // @@toStringTag slot (never view.constructor and never a + // user-definable Buffer @@hasInstance check): reconstruction after a + // memory growth must not run any user code, because it could grow + // again after the fresh buffer was captured as an argument. Buffers + // are tagged 'Uint8Array' and reconstruct as base Uint8Array views + Ctor: isDataView ? DataView : intrinsics.ctors[tag], + address: isDataView ? intrinsics.dataView.byteOffset.call(view) : intrinsics.typedArray.byteOffset.call(view), + length: isDataView ? intrinsics.dataView.byteLength.call(view) : intrinsics.typedArray.length.call(view), + ownership: 1 /* ReferenceOwnership.kUserland */, + runtimeAllocated: 0 + }); + } + return view; + } + var maybeOldWasmMemory = emnapiExternalMemory.isDetachedArrayBuffer(buffer) || emnapiExternalMemory.isSharedArrayBuffer(buffer); + if (maybeOldWasmMemory && emnapiExternalMemory.wasmMemoryViewTable.has(view)) { + var info = emnapiExternalMemory.wasmMemoryViewTable.get(view); + var Ctor = info.Ctor; + var newView = void 0; + var Buffer_1 = emnapiCtx.feature.Buffer; + if (typeof Buffer_1 === 'function' && Ctor === Buffer_1) { + // reconstruct through the Buffer.from captured at creation time + newView = emnapiExternalMemory.getBufferFrom()(wasmMemory.buffer, info.address, info.length); + } + else { + newView = new Ctor(wasmMemory.buffer, info.address, info.length); + } + emnapiExternalMemory.wasmMemoryViewTable.set(newView, info); + return newView; + } + return view; + }, + getViewPointer: function (view, shouldCopy) { + view = emnapiExternalMemory.getOrUpdateMemoryView(view); + var buffer = emnapiExternalMemory.viewBuffer(view); + if (buffer === wasmMemory.buffer) { + if (emnapiExternalMemory.wasmMemoryViewTable.has(view)) { + var _a = emnapiExternalMemory.wasmMemoryViewTable.get(view), address_1 = _a.address, ownership_1 = _a.ownership, runtimeAllocated_1 = _a.runtimeAllocated; + return { address: address_1, ownership: ownership_1, runtimeAllocated: runtimeAllocated_1, view: view }; + } + return { address: emnapiExternalMemory.viewByteOffset(view), ownership: 1 /* ReferenceOwnership.kUserland */, runtimeAllocated: 0, view: view }; + } + var _b = emnapiExternalMemory.getArrayBufferPointer(buffer, shouldCopy), address = _b.address, ownership = _b.ownership, runtimeAllocated = _b.runtimeAllocated; + return { address: address === 0 ? 0 : (address + emnapiExternalMemory.viewByteOffset(view)), ownership: ownership, runtimeAllocated: runtimeAllocated, view: view }; + } + }; + /** + * Metadata layout in wasm shared memory (allocated with _malloc): + * offset 0: refcount (int32, 4 bytes - for Atomics) + * offset POINTER_SIZE: external_data (pointer) + * offset 2*POINTER_SIZE: byte_length (size_t) + * offset 3*POINTER_SIZE: finalize_cb (pointer) + * offset 4*POINTER_SIZE: finalize_data (pointer) + * offset 5*POINTER_SIZE: finalize_hint (pointer) + * Total: 6 * POINTER_SIZE bytes + */ + /** + * @__postset + * ``` + * emnapiExternalSAB.init(); + * ``` + */ + var emnapiExternalSAB = { + registry: undefined, + handleTable: new WeakMap(), + init: function () { + emnapiExternalSAB.handleTable = new WeakMap(); + emnapiExternalSAB.registry = typeof FinalizationRegistry === 'function' + ? new FinalizationRegistry(function (metaPtr) { + emnapiExternalSAB.release(metaPtr); + }) + : undefined; + }, + allocMeta: function (external_data, byte_length, finalize_cb, finalize_data, finalize_hint) { + // eslint-disable-next-line @typescript-eslint/no-unused-vars + var size = 4 * 6; + // eslint-disable-next-line prefer-const + var metaPtr = _malloc(size); + if (!metaPtr) + throw new Error('Out of memory'); + metaPtr >>>= 0; + // refcount = 1 + Atomics.store(new Int32Array(wasmMemory.buffer, metaPtr, 1), 0, 1); + var HEAP_DATA_VIEW = new DataView(wasmMemory.buffer), GET_HEAP_DATA_VIEW = function () { return HEAP_DATA_VIEW.buffer === wasmMemory.buffer ? HEAP_DATA_VIEW : (HEAP_DATA_VIEW = new DataView(wasmMemory.buffer)); }; + GET_HEAP_DATA_VIEW().setUint32(metaPtr + 4, external_data, true); + GET_HEAP_DATA_VIEW().setUint32(metaPtr + 8, byte_length, true); + GET_HEAP_DATA_VIEW().setUint32(metaPtr + 12, finalize_cb, true); + GET_HEAP_DATA_VIEW().setUint32(metaPtr + 16, finalize_data, true); + GET_HEAP_DATA_VIEW().setUint32(metaPtr + 20, finalize_hint, true); + return metaPtr; + }, + readMeta: function (metaPtr) { + var HEAP_DATA_VIEW = new DataView(wasmMemory.buffer), GET_HEAP_DATA_VIEW = function () { return HEAP_DATA_VIEW.buffer === wasmMemory.buffer ? HEAP_DATA_VIEW : (HEAP_DATA_VIEW = new DataView(wasmMemory.buffer)); }; + var external_data = GET_HEAP_DATA_VIEW().getUint32(metaPtr + 4, true); + var byte_length = GET_HEAP_DATA_VIEW().getUint32(metaPtr + 8, true); + var finalize_cb = GET_HEAP_DATA_VIEW().getUint32(metaPtr + 12, true); + var finalize_data = GET_HEAP_DATA_VIEW().getUint32(metaPtr + 16, true); + var finalize_hint = GET_HEAP_DATA_VIEW().getUint32(metaPtr + 20, true); + return { external_data: external_data, byte_length: byte_length, finalize_cb: finalize_cb, finalize_data: finalize_data, finalize_hint: finalize_hint }; + }, + release: function (metaPtr) { + var oldRefcount = Atomics.sub(new Int32Array(wasmMemory.buffer, metaPtr, 1), 0, 1); + if (oldRefcount === 1) { + // refcount reached 0, we are the last holder + var info = emnapiExternalSAB.readMeta(metaPtr); + var finalize_cb = info.finalize_cb; + if (finalize_cb) { + var finalize_data = info.finalize_data; + var finalize_hint = info.finalize_hint; + (wasmTable.get(finalize_cb))(finalize_data, finalize_hint); + } + _free(metaPtr); + } + } + }; + /* eslint-disable @typescript-eslint/indent */ + /** + * @__postset + * ``` + * emnapiString.init(); + * ``` + */ + var emnapiString = { + utf8Decoder: undefined, + utf16Decoder: undefined, + init: function () { + var fallbackDecoder = { + decode: function (bytes) { + var inputIndex = 0; + var pendingSize = Math.min(0x1000, bytes.length + 1); + var pending = new Uint16Array(pendingSize); + var chunks = []; + var pendingIndex = 0; + for (;;) { + var more = inputIndex < bytes.length; + if (!more || (pendingIndex >= pendingSize - 1)) { + var subarray = pending.subarray(0, pendingIndex); + var arraylike = subarray; + chunks.push(String.fromCharCode.apply(null, arraylike)); + if (!more) { + return chunks.join(''); + } + bytes = bytes.subarray(inputIndex); + inputIndex = 0; + pendingIndex = 0; + } + var byte1 = bytes[inputIndex++]; + if ((byte1 & 0x80) === 0) { + pending[pendingIndex++] = byte1; + } + else if ((byte1 & 0xe0) === 0xc0) { + var byte2 = bytes[inputIndex++] & 0x3f; + pending[pendingIndex++] = ((byte1 & 0x1f) << 6) | byte2; + } + else if ((byte1 & 0xf0) === 0xe0) { + var byte2 = bytes[inputIndex++] & 0x3f; + var byte3 = bytes[inputIndex++] & 0x3f; + pending[pendingIndex++] = ((byte1 & 0x1f) << 12) | (byte2 << 6) | byte3; + } + else if ((byte1 & 0xf8) === 0xf0) { + var byte2 = bytes[inputIndex++] & 0x3f; + var byte3 = bytes[inputIndex++] & 0x3f; + var byte4 = bytes[inputIndex++] & 0x3f; + var codepoint = ((byte1 & 0x07) << 0x12) | (byte2 << 0x0c) | (byte3 << 0x06) | byte4; + if (codepoint > 0xffff) { + codepoint -= 0x10000; + pending[pendingIndex++] = (codepoint >>> 10) & 0x3ff | 0xd800; + codepoint = 0xdc00 | codepoint & 0x3ff; + } + pending[pendingIndex++] = codepoint; + } + else ; + } + } + }; + var utf8Decoder; + utf8Decoder = typeof TextDecoder === 'function' ? new TextDecoder() : fallbackDecoder; + emnapiString.utf8Decoder = utf8Decoder; + var fallbackDecoder2 = { + decode: function (input) { + var bytes = new Uint16Array(input.buffer, input.byteOffset, input.byteLength / 2); + if (bytes.length <= 0x1000) { + return String.fromCharCode.apply(null, bytes); + } + var chunks = []; + var i = 0; + var len = 0; + for (; i < bytes.length; i += len) { + len = Math.min(0x1000, bytes.length - i); + chunks.push(String.fromCharCode.apply(null, bytes.subarray(i, i + len))); + } + return chunks.join(''); + } + }; + var utf16Decoder; + utf16Decoder = typeof TextDecoder === 'function' ? new TextDecoder('utf-16le') : fallbackDecoder2; + emnapiString.utf16Decoder = utf16Decoder; + }, + lengthBytesUTF8: function (str) { + var c; + var len = 0; + for (var i = 0; i < str.length; ++i) { + c = str.charCodeAt(i); + if (c <= 0x7F) { + len++; + } + else if (c <= 0x7FF) { + len += 2; + } + else if (c >= 0xD800 && c <= 0xDFFF) { + len += 4; + ++i; + } + else { + len += 3; + } + } + return len; + }, + UTF8ToString: function (ptr, length) { + if (!ptr || !length) + return ''; + ptr >>>= 0; + var HEAPU8 = new Uint8Array(wasmMemory.buffer); + var end = ptr; + if (length === -1 || length === 4294967295) { + for (; HEAPU8[end];) + ++end; + } + else { + end = ptr + (length >>> 0); + } + length = end - ptr; + if (length <= 16) { + var idx = ptr; + var str = ''; + while (idx < end) { + var u0 = HEAPU8[idx++]; + if (!(u0 & 0x80)) { + str += String.fromCharCode(u0); + continue; + } + var u1 = HEAPU8[idx++] & 63; + if ((u0 & 0xE0) === 0xC0) { + str += String.fromCharCode(((u0 & 31) << 6) | u1); + continue; + } + var u2 = HEAPU8[idx++] & 63; + if ((u0 & 0xF0) === 0xE0) { + u0 = ((u0 & 15) << 12) | (u1 << 6) | u2; + } + else { + u0 = ((u0 & 7) << 18) | (u1 << 12) | (u2 << 6) | (HEAPU8[idx++] & 63); + } + if (u0 < 0x10000) { + str += String.fromCharCode(u0); + } + else { + var ch = u0 - 0x10000; + str += String.fromCharCode(0xD800 | (ch >> 10), 0xDC00 | (ch & 0x3FF)); + } + } + return str; + } + return emnapiString.utf8Decoder.decode(((typeof SharedArrayBuffer === "function" && HEAPU8.buffer instanceof SharedArrayBuffer) || (Object.prototype.toString.call(HEAPU8.buffer) === "[object SharedArrayBuffer]")) ? HEAPU8.slice(ptr, end) : HEAPU8.subarray(ptr, end)); + }, + stringToUTF8: function (str, outPtr, maxBytesToWrite) { + var HEAPU8 = new Uint8Array(wasmMemory.buffer); + var outIdx = outPtr; + outIdx >>>= 0; + if (!(maxBytesToWrite > 0)) { + return 0; + } + var startIdx = outIdx; + var endIdx = outIdx + maxBytesToWrite - 1; + for (var i = 0; i < str.length; ++i) { + var u = str.charCodeAt(i); + if (u >= 0xD800 && u <= 0xDFFF) { + var u1 = str.charCodeAt(++i); + u = 0x10000 + ((u & 0x3FF) << 10) | (u1 & 0x3FF); + } + if (u <= 0x7F) { + if (outIdx >= endIdx) + break; + HEAPU8[outIdx++] = u; + } + else if (u <= 0x7FF) { + if (outIdx + 1 >= endIdx) + break; + HEAPU8[outIdx++] = 0xC0 | (u >> 6); + HEAPU8[outIdx++] = 0x80 | (u & 63); + } + else if (u <= 0xFFFF) { + if (outIdx + 2 >= endIdx) + break; + HEAPU8[outIdx++] = 0xE0 | (u >> 12); + HEAPU8[outIdx++] = 0x80 | ((u >> 6) & 63); + HEAPU8[outIdx++] = 0x80 | (u & 63); + } + else { + if (outIdx + 3 >= endIdx) + break; + HEAPU8[outIdx++] = 0xF0 | (u >> 18); + HEAPU8[outIdx++] = 0x80 | ((u >> 12) & 63); + HEAPU8[outIdx++] = 0x80 | ((u >> 6) & 63); + HEAPU8[outIdx++] = 0x80 | (u & 63); + } + } + HEAPU8[outIdx] = 0; + return outIdx - startIdx; + }, + UTF16ToString: function (ptr, length) { + if (!ptr || !length) + return ''; + ptr >>>= 0; + var end = ptr; + if (length === -1 || length === 4294967295) { + var idx = end >>> 1; + var HEAPU16 = new Uint16Array(wasmMemory.buffer); + while (HEAPU16[idx]) + ++idx; + end = (idx << 1) >>> 0; + } + else { + end = ptr + (length >>> 0) * 2; + } + length = end - ptr; + if (length <= 32) { + return String.fromCharCode.apply(null, new Uint16Array(wasmMemory.buffer, ptr, length / 2)); + } + // eslint-disable-next-line @typescript-eslint/no-unused-vars + var HEAPU8 = new Uint8Array(wasmMemory.buffer); + return emnapiString.utf16Decoder.decode(((typeof SharedArrayBuffer === "function" && HEAPU8.buffer instanceof SharedArrayBuffer) || (Object.prototype.toString.call(HEAPU8.buffer) === "[object SharedArrayBuffer]")) ? HEAPU8.slice(ptr, end) : HEAPU8.subarray(ptr, end)); + }, + stringToUTF16: function (str, outPtr, maxBytesToWrite) { + if (maxBytesToWrite === undefined) { + maxBytesToWrite = 0x7FFFFFFF; + } + if (maxBytesToWrite < 2) + return 0; + maxBytesToWrite -= 2; + var startPtr = outPtr; + var numCharsToWrite = (maxBytesToWrite < str.length * 2) ? (maxBytesToWrite / 2) : str.length; + var HEAP_DATA_VIEW = new DataView(wasmMemory.buffer), GET_HEAP_DATA_VIEW = function () { return HEAP_DATA_VIEW.buffer === wasmMemory.buffer ? HEAP_DATA_VIEW : (HEAP_DATA_VIEW = new DataView(wasmMemory.buffer)); }; + for (var i = 0; i < numCharsToWrite; ++i) { + // eslint-disable-next-line @typescript-eslint/no-unused-vars + var codeUnit = str.charCodeAt(i); + GET_HEAP_DATA_VIEW().setInt16(outPtr, codeUnit, true); + outPtr += 2; + } + GET_HEAP_DATA_VIEW().setInt16(outPtr, 0, true); + return outPtr - startPtr; + }, + newString: function (env, str, length, result, stringMaker) { + length >>>= 0; + if (!env) + return 1 /* napi_status.napi_invalid_arg */; + // @ts-expect-error + var envObject = emnapiCtx.envStore.get(env); + envObject.checkGCAccess(); + var autoLength = length === -1 || length === 4294967295; + var sizelength = length >>> 0; + if (length !== 0) { + if (!str) + return envObject.setLastError(1 /* napi_status.napi_invalid_arg */); + } + if (!result) + return envObject.setLastError(1 /* napi_status.napi_invalid_arg */); + if (!(autoLength || (sizelength <= 2147483647))) + return envObject.setLastError(1 /* napi_status.napi_invalid_arg */); + str >>>= 0; + var strValue = stringMaker(str, autoLength, sizelength); + result >>>= 0; + // eslint-disable-next-line @typescript-eslint/no-unused-vars + var value = emnapiCtx.addToCurrentScope(strValue).id; + var HEAP_DATA_VIEW = new DataView(wasmMemory.buffer), GET_HEAP_DATA_VIEW = function () { return HEAP_DATA_VIEW.buffer === wasmMemory.buffer ? HEAP_DATA_VIEW : (HEAP_DATA_VIEW = new DataView(wasmMemory.buffer)); }; + GET_HEAP_DATA_VIEW().setUint32(result, value, true); + return envObject.clearLastError(); + }, + newExternalString: function (env, str, length, finalize_callback, finalize_hint, result, copied, createApi, stringMaker) { + length >>>= 0; + if (!env) + return 1 /* napi_status.napi_invalid_arg */; + // @ts-expect-error + var envObject = emnapiCtx.envStore.get(env); + envObject.checkGCAccess(); + var autoLength = length === -1 || length === 4294967295; + var sizelength = length >>> 0; + if (length !== 0) { + if (!str) + return envObject.setLastError(1 /* napi_status.napi_invalid_arg */); + } + if (!result) + return envObject.setLastError(1 /* napi_status.napi_invalid_arg */); + if (!(autoLength || (sizelength <= 2147483647))) + return envObject.setLastError(1 /* napi_status.napi_invalid_arg */); + var status = createApi(env, str, length, result); + if (status === 0 /* napi_status.napi_ok */) { + if (copied) { + var HEAP_DATA_VIEW = new DataView(wasmMemory.buffer), GET_HEAP_DATA_VIEW = function () { return HEAP_DATA_VIEW.buffer === wasmMemory.buffer ? HEAP_DATA_VIEW : (HEAP_DATA_VIEW = new DataView(wasmMemory.buffer)); }; + GET_HEAP_DATA_VIEW().setInt8(copied, 1, true); + } + if (finalize_callback) { + envObject.callFinalizer(finalize_callback, str, finalize_hint); + } + } + return status; + } + }; + /** + * @__sig ippp + */ + function napi_get_array_length(env, value, result) { + if (!env) + return 1 /* napi_status.napi_invalid_arg */; + // @ts-expect-error + var envObject = emnapiCtx.envStore.get(env); + envObject.checkGCAccess(); + if (!envObject.tryCatch.isEmpty()) + return envObject.setLastError(10 /* napi_status.napi_pending_exception */); + if (!envObject.canCallIntoJs()) + return envObject.setLastError(envObject.moduleApiVersion >= 10 ? 23 /* napi_status.napi_cannot_run_js */ : 10 /* napi_status.napi_pending_exception */); + envObject.clearLastError(); + try { + if (!value) + return envObject.setLastError(1 /* napi_status.napi_invalid_arg */); + if (!result) + return envObject.setLastError(1 /* napi_status.napi_invalid_arg */); + var handle = emnapiCtx.handleStore.get(value); + if (!handle.isArray()) { + return envObject.setLastError(8 /* napi_status.napi_array_expected */); + } + result >>>= 0; + // eslint-disable-next-line @typescript-eslint/no-unused-vars + var v = handle.value.length >>> 0; + var HEAP_DATA_VIEW = new DataView(wasmMemory.buffer), GET_HEAP_DATA_VIEW = function () { return HEAP_DATA_VIEW.buffer === wasmMemory.buffer ? HEAP_DATA_VIEW : (HEAP_DATA_VIEW = new DataView(wasmMemory.buffer)); }; + GET_HEAP_DATA_VIEW().setUint32(result, v, true); + return envObject.getReturnStatus(); + } + catch (err) { + envObject.tryCatch.setError(err); + return envObject.setLastError(10 /* napi_status.napi_pending_exception */); + } + } + /** + * @__sig ipppp + */ + function napi_get_arraybuffer_info(env, arraybuffer, data, byte_length) { + if (!env) + return 1 /* napi_status.napi_invalid_arg */; + // @ts-expect-error + var envObject = emnapiCtx.envStore.get(env); + envObject.checkGCAccess(); + if (!arraybuffer) + return envObject.setLastError(1 /* napi_status.napi_invalid_arg */); + var handle = emnapiCtx.handleStore.get(arraybuffer); + if (!handle.isArrayBuffer() && !emnapiExternalMemory.isSharedArrayBuffer(handle.value)) { + return envObject.setLastError(1 /* napi_status.napi_invalid_arg */); + } + var HEAP_DATA_VIEW = new DataView(wasmMemory.buffer), GET_HEAP_DATA_VIEW = function () { return HEAP_DATA_VIEW.buffer === wasmMemory.buffer ? HEAP_DATA_VIEW : (HEAP_DATA_VIEW = new DataView(wasmMemory.buffer)); }; + // metadata is read through cached intrinsic getters (internal slots, like + // native Node-API): no user JS can run inside this call. Only emnapi's own + // getArrayBufferPointer() can still grow the memory (malloc for the copy of + // an external buffer), which detaches the previous non-shared buffer, so + // each value is resolved into a local BEFORE its makeSetValue write (the + // store target is evaluated before the RHS). + if (data) { + data >>>= 0; + // eslint-disable-next-line @typescript-eslint/no-unused-vars + var p = emnapiExternalMemory.getArrayBufferPointer(handle.value, true).address; + GET_HEAP_DATA_VIEW().setUint32(data, p, true); + } + if (byte_length) { + byte_length >>>= 0; + // eslint-disable-next-line @typescript-eslint/no-unused-vars + var len = emnapiExternalMemory.bufferByteLength(handle.value); + GET_HEAP_DATA_VIEW().setUint32(byte_length, len, true); + } + return envObject.clearLastError(); + } + /** + * @__sig ippp + */ + function node_api_set_prototype(env, object, value) { + if (!env) + return 1 /* napi_status.napi_invalid_arg */; + // @ts-expect-error + var envObject = emnapiCtx.envStore.get(env); + envObject.checkGCAccess(); + if (!envObject.tryCatch.isEmpty()) + return envObject.setLastError(10 /* napi_status.napi_pending_exception */); + if (!envObject.canCallIntoJs()) + return envObject.setLastError(envObject.moduleApiVersion >= 10 ? 23 /* napi_status.napi_cannot_run_js */ : 10 /* napi_status.napi_pending_exception */); + envObject.clearLastError(); + try { + if (!value) + return envObject.setLastError(1 /* napi_status.napi_invalid_arg */); + var obj = emnapiCtx.handleStore.get(object).value; + if (obj == null) { + throw new TypeError('Cannot convert undefined or null to object'); + } + var type = typeof obj; + var v = void 0; + try { + v = (type === 'object' && obj !== null) || type === 'function' ? obj : Object(obj); + } + catch (_) { + return envObject.setLastError(2 /* napi_status.napi_object_expected */); + } + var val = emnapiCtx.handleStore.get(value).value; + Object.setPrototypeOf(v, val); + return envObject.getReturnStatus(); + } + catch (err) { + envObject.tryCatch.setError(err); + return envObject.setLastError(10 /* napi_status.napi_pending_exception */); + } + } + /** + * @__sig ippp + */ + function napi_get_prototype(env, value, result) { + if (!env) + return 1 /* napi_status.napi_invalid_arg */; + // @ts-expect-error + var envObject = emnapiCtx.envStore.get(env); + envObject.checkGCAccess(); + if (!envObject.tryCatch.isEmpty()) + return envObject.setLastError(10 /* napi_status.napi_pending_exception */); + if (!envObject.canCallIntoJs()) + return envObject.setLastError(envObject.moduleApiVersion >= 10 ? 23 /* napi_status.napi_cannot_run_js */ : 10 /* napi_status.napi_pending_exception */); + envObject.clearLastError(); + try { + if (!value) + return envObject.setLastError(1 /* napi_status.napi_invalid_arg */); + if (!result) + return envObject.setLastError(1 /* napi_status.napi_invalid_arg */); + var handle = emnapiCtx.handleStore.get(value); + if (handle.value == null) { + throw new TypeError('Cannot convert undefined or null to object'); + } + var v = void 0; + try { + v = handle.isObject() || handle.isFunction() ? handle.value : Object(handle.value); + } + catch (_) { + return envObject.setLastError(2 /* napi_status.napi_object_expected */); + } + result >>>= 0; + // eslint-disable-next-line @typescript-eslint/no-unused-vars + var p = envObject.ensureHandleId(Object.getPrototypeOf(v)); + var HEAP_DATA_VIEW = new DataView(wasmMemory.buffer), GET_HEAP_DATA_VIEW = function () { return HEAP_DATA_VIEW.buffer === wasmMemory.buffer ? HEAP_DATA_VIEW : (HEAP_DATA_VIEW = new DataView(wasmMemory.buffer)); }; + GET_HEAP_DATA_VIEW().setUint32(result, p, true); + return envObject.getReturnStatus(); + } + catch (err) { + envObject.tryCatch.setError(err); + return envObject.setLastError(10 /* napi_status.napi_pending_exception */); + } + } + /** + * @__sig ippppppp + */ + function napi_get_typedarray_info(env, typedarray, type, length, data, arraybuffer, byte_offset) { + if (!env) + return 1 /* napi_status.napi_invalid_arg */; + // @ts-expect-error + var envObject = emnapiCtx.envStore.get(env); + envObject.checkGCAccess(); + if (!typedarray) + return envObject.setLastError(1 /* napi_status.napi_invalid_arg */); + var handle = emnapiCtx.handleStore.get(typedarray); + if (!(emnapiExternalMemory.intrinsics.isView(handle.value))) { + return envObject.setLastError(1 /* napi_status.napi_invalid_arg */); + } + var v = handle.value; + var HEAP_DATA_VIEW = new DataView(wasmMemory.buffer), GET_HEAP_DATA_VIEW = function () { return HEAP_DATA_VIEW.buffer === wasmMemory.buffer ? HEAP_DATA_VIEW : (HEAP_DATA_VIEW = new DataView(wasmMemory.buffer)); }; + // all view metadata (kind, buffer, byteOffset, length) is read through + // cached intrinsic prototype getters: like native Node-API they read the + // internal slots, never consult user accessors (no user JS can run inside + // this call) and work for instances from any realm. Only emnapi's own + // getViewPointer() can still grow the memory (malloc for the copy of an + // external buffer), which detaches the previous non-shared buffer, so each + // value is resolved into a local BEFORE its makeSetValue write (the store + // target is evaluated before the RHS). + if (type) { + type >>>= 0; + var t = void 0; + switch (emnapiExternalMemory.intrinsics.typedArray.tag.call(v)) { + case 'Int8Array': + t = 0 /* napi_typedarray_type.napi_int8_array */; + break; + case 'Uint8Array': + t = 1 /* napi_typedarray_type.napi_uint8_array */; + break; + case 'Uint8ClampedArray': + t = 2 /* napi_typedarray_type.napi_uint8_clamped_array */; + break; + case 'Int16Array': + t = 3 /* napi_typedarray_type.napi_int16_array */; + break; + case 'Uint16Array': + t = 4 /* napi_typedarray_type.napi_uint16_array */; + break; + case 'Int32Array': + t = 5 /* napi_typedarray_type.napi_int32_array */; + break; + case 'Uint32Array': + t = 6 /* napi_typedarray_type.napi_uint32_array */; + break; + case 'Float16Array': + t = 11 /* napi_typedarray_type.napi_float16_array */; + break; + case 'Float32Array': + t = 7 /* napi_typedarray_type.napi_float32_array */; + break; + case 'Float64Array': + t = 8 /* napi_typedarray_type.napi_float64_array */; + break; + case 'BigInt64Array': + t = 9 /* napi_typedarray_type.napi_bigint64_array */; + break; + // eslint-disable-next-line @typescript-eslint/no-unused-vars + case 'BigUint64Array': + t = 10 /* napi_typedarray_type.napi_biguint64_array */; + break; + default: + return envObject.setLastError(9 /* napi_status.napi_generic_failure */); + } + GET_HEAP_DATA_VIEW().setInt32(type, t, true); + } + v = emnapiExternalMemory.getOrUpdateMemoryView(v); + if (length) { + length >>>= 0; + // eslint-disable-next-line @typescript-eslint/no-unused-vars + var len = emnapiExternalMemory.viewLength(v); + GET_HEAP_DATA_VIEW().setUint32(length, len, true); + } + if (data || arraybuffer) { + if (data) { + data >>>= 0; + var vp = emnapiExternalMemory.getViewPointer(v, true); + v = vp.view; + // eslint-disable-next-line @typescript-eslint/no-unused-vars + var p = vp.address; + GET_HEAP_DATA_VIEW().setUint32(data, p, true); + } + if (arraybuffer) { + arraybuffer >>>= 0; + // eslint-disable-next-line @typescript-eslint/no-unused-vars + var ab = envObject.ensureHandleId(emnapiExternalMemory.viewBuffer(v)); + GET_HEAP_DATA_VIEW().setUint32(arraybuffer, ab, true); + } + } + if (byte_offset) { + byte_offset >>>= 0; + // eslint-disable-next-line @typescript-eslint/no-unused-vars + var offset = emnapiExternalMemory.viewByteOffset(v); + GET_HEAP_DATA_VIEW().setUint32(byte_offset, offset, true); + } + return envObject.clearLastError(); + } + /** + * @__sig ipppp + */ + function napi_get_buffer_info(env, buffer, data, length) { + if (!env) + return 1 /* napi_status.napi_invalid_arg */; + // @ts-expect-error + var envObject = emnapiCtx.envStore.get(env); + envObject.checkGCAccess(); + if (!buffer) + return envObject.setLastError(1 /* napi_status.napi_invalid_arg */); + var handle = emnapiCtx.handleStore.get(buffer); + var Buffer = emnapiCtx.feature.Buffer; + var bool = (emnapiExternalMemory.intrinsics.isView(handle.value) || (typeof Buffer === 'function' && Buffer.isBuffer(handle.value))); + if (!bool) + return envObject.setLastError(1 /* napi_status.napi_invalid_arg */); + // any-realm slot-based classification: the intrinsic @@toStringTag getter + // returns undefined exactly for DataViews among ArrayBuffer views + if (emnapiExternalMemory.intrinsics.typedArray.tag.call(handle.value) === undefined) { + return napi_get_dataview_info(env, buffer, length, data, 0, 0); + } + return napi_get_typedarray_info(env, buffer, 0, length, data, 0, 0); + } + /** + * @__sig ipppppp + */ + function napi_get_dataview_info(env, dataview, byte_length, data, arraybuffer, byte_offset) { + if (!env) + return 1 /* napi_status.napi_invalid_arg */; + // @ts-expect-error + var envObject = emnapiCtx.envStore.get(env); + envObject.checkGCAccess(); + if (!dataview) + return envObject.setLastError(1 /* napi_status.napi_invalid_arg */); + var handle = emnapiCtx.handleStore.get(dataview); + // any-realm slot-based classification (see napi_get_buffer_info) + if (!(emnapiExternalMemory.intrinsics.isView(handle.value)) || emnapiExternalMemory.intrinsics.typedArray.tag.call(handle.value) !== undefined) { + return envObject.setLastError(1 /* napi_status.napi_invalid_arg */); + } + var v = emnapiExternalMemory.getOrUpdateMemoryView(handle.value); + var HEAP_DATA_VIEW = new DataView(wasmMemory.buffer), GET_HEAP_DATA_VIEW = function () { return HEAP_DATA_VIEW.buffer === wasmMemory.buffer ? HEAP_DATA_VIEW : (HEAP_DATA_VIEW = new DataView(wasmMemory.buffer)); }; + // all view metadata is read through cached intrinsic prototype getters: + // like native Node-API they read the internal slots, never consult user + // accessors (no user JS can run inside this call) and work for instances + // from any realm. Only emnapi's own getViewPointer() can still grow the + // memory (malloc for the copy of an external buffer), which detaches the + // previous non-shared buffer, so each value is resolved into a local + // BEFORE its makeSetValue write (the store target is evaluated before + // the RHS). + if (byte_length) { + byte_length >>>= 0; + // eslint-disable-next-line @typescript-eslint/no-unused-vars + var len = emnapiExternalMemory.viewLength(v); + GET_HEAP_DATA_VIEW().setUint32(byte_length, len, true); + } + if (data || arraybuffer) { + if (data) { + data >>>= 0; + var vp = emnapiExternalMemory.getViewPointer(v, true); + v = vp.view; + // eslint-disable-next-line @typescript-eslint/no-unused-vars + var p = vp.address; + GET_HEAP_DATA_VIEW().setUint32(data, p, true); + } + if (arraybuffer) { + arraybuffer >>>= 0; + // eslint-disable-next-line @typescript-eslint/no-unused-vars + var ab = envObject.ensureHandleId(emnapiExternalMemory.viewBuffer(v)); + GET_HEAP_DATA_VIEW().setUint32(arraybuffer, ab, true); + } + } + if (byte_offset) { + byte_offset >>>= 0; + // eslint-disable-next-line @typescript-eslint/no-unused-vars + var offset = emnapiExternalMemory.viewByteOffset(v); + GET_HEAP_DATA_VIEW().setUint32(byte_offset, offset, true); + } + return envObject.clearLastError(); + } + /** + * @__sig ippp + */ + function napi_get_date_value(env, value, result) { + // eslint-disable-next-line @typescript-eslint/no-unused-vars + var v; + if (!env) + return 1 /* napi_status.napi_invalid_arg */; + // @ts-expect-error + var envObject = emnapiCtx.envStore.get(env); + envObject.checkGCAccess(); + if (!envObject.tryCatch.isEmpty()) + return envObject.setLastError(10 /* napi_status.napi_pending_exception */); + if (!envObject.canCallIntoJs()) + return envObject.setLastError(envObject.moduleApiVersion >= 10 ? 23 /* napi_status.napi_cannot_run_js */ : 10 /* napi_status.napi_pending_exception */); + envObject.clearLastError(); + try { + if (!value) + return envObject.setLastError(1 /* napi_status.napi_invalid_arg */); + if (!result) + return envObject.setLastError(1 /* napi_status.napi_invalid_arg */); + var handle = emnapiCtx.handleStore.get(value); + if (!handle.isDate()) { + return envObject.setLastError(1 /* napi_status.napi_invalid_arg */); + } + result >>>= 0; + v = handle.value.valueOf(); + var HEAP_DATA_VIEW = new DataView(wasmMemory.buffer), GET_HEAP_DATA_VIEW = function () { return HEAP_DATA_VIEW.buffer === wasmMemory.buffer ? HEAP_DATA_VIEW : (HEAP_DATA_VIEW = new DataView(wasmMemory.buffer)); }; + GET_HEAP_DATA_VIEW().setFloat64(result, v, true); + return envObject.getReturnStatus(); + } + catch (err) { + envObject.tryCatch.setError(err); + return envObject.setLastError(10 /* napi_status.napi_pending_exception */); + } + } + /** + * @__sig ippp + */ + function napi_get_value_bool(env, value, result) { + if (!env) + return 1 /* napi_status.napi_invalid_arg */; + // @ts-expect-error + var envObject = emnapiCtx.envStore.get(env); + envObject.checkGCAccess(); + if (!value) + return envObject.setLastError(1 /* napi_status.napi_invalid_arg */); + if (!result) + return envObject.setLastError(1 /* napi_status.napi_invalid_arg */); + var handle = emnapiCtx.handleStore.get(value); + if (typeof handle.value !== 'boolean') { + return envObject.setLastError(7 /* napi_status.napi_boolean_expected */); + } + result >>>= 0; + // eslint-disable-next-line @typescript-eslint/no-unused-vars + var r = handle.value ? 1 : 0; + var HEAP_DATA_VIEW = new DataView(wasmMemory.buffer), GET_HEAP_DATA_VIEW = function () { return HEAP_DATA_VIEW.buffer === wasmMemory.buffer ? HEAP_DATA_VIEW : (HEAP_DATA_VIEW = new DataView(wasmMemory.buffer)); }; + GET_HEAP_DATA_VIEW().setInt8(result, r, true); + return envObject.clearLastError(); + } + /** + * @__sig ippp + */ + function napi_get_value_double(env, value, result) { + if (!env) + return 1 /* napi_status.napi_invalid_arg */; + // @ts-expect-error + var envObject = emnapiCtx.envStore.get(env); + envObject.checkGCAccess(); + if (!value) + return envObject.setLastError(1 /* napi_status.napi_invalid_arg */); + if (!result) + return envObject.setLastError(1 /* napi_status.napi_invalid_arg */); + var handle = emnapiCtx.handleStore.get(value); + if (typeof handle.value !== 'number') { + return envObject.setLastError(6 /* napi_status.napi_number_expected */); + } + result >>>= 0; + // eslint-disable-next-line @typescript-eslint/no-unused-vars + var r = handle.value; + var HEAP_DATA_VIEW = new DataView(wasmMemory.buffer), GET_HEAP_DATA_VIEW = function () { return HEAP_DATA_VIEW.buffer === wasmMemory.buffer ? HEAP_DATA_VIEW : (HEAP_DATA_VIEW = new DataView(wasmMemory.buffer)); }; + GET_HEAP_DATA_VIEW().setFloat64(result, r, true); + return envObject.clearLastError(); + } + /** + * @__sig ipppp + */ + function napi_get_value_bigint_int64(env, value, result, lossless) { + if (!env) + return 1 /* napi_status.napi_invalid_arg */; + // @ts-expect-error + var envObject = emnapiCtx.envStore.get(env); + envObject.checkGCAccess(); + if (!emnapiCtx.feature.supportBigInt) { + return envObject.setLastError(9 /* napi_status.napi_generic_failure */); + } + if (!value) + return envObject.setLastError(1 /* napi_status.napi_invalid_arg */); + if (!result) + return envObject.setLastError(1 /* napi_status.napi_invalid_arg */); + if (!lossless) + return envObject.setLastError(1 /* napi_status.napi_invalid_arg */); + var handle = emnapiCtx.handleStore.get(value); + var numberValue = handle.value; + if (typeof numberValue !== 'bigint') { + return envObject.setLastError(6 /* napi_status.napi_number_expected */); + } + lossless >>>= 0; + result >>>= 0; + var HEAP_DATA_VIEW = new DataView(wasmMemory.buffer), GET_HEAP_DATA_VIEW = function () { return HEAP_DATA_VIEW.buffer === wasmMemory.buffer ? HEAP_DATA_VIEW : (HEAP_DATA_VIEW = new DataView(wasmMemory.buffer)); }; + if ((numberValue >= (BigInt(-1) * (BigInt(1) << BigInt(63)))) && (numberValue < (BigInt(1) << BigInt(63)))) { + GET_HEAP_DATA_VIEW().setInt8(lossless, 1, true); + } + else { + GET_HEAP_DATA_VIEW().setInt8(lossless, 0, true); + numberValue = numberValue & ((BigInt(1) << BigInt(64)) - BigInt(1)); + if (numberValue >= (BigInt(1) << BigInt(63))) { + numberValue = numberValue - (BigInt(1) << BigInt(64)); + } + } + // eslint-disable-next-line @typescript-eslint/no-unused-vars + var low = Number(numberValue & BigInt(0xffffffff)); + // eslint-disable-next-line @typescript-eslint/no-unused-vars + var high = Number(numberValue >> BigInt(32)); + GET_HEAP_DATA_VIEW().setInt32(result, low, true); + GET_HEAP_DATA_VIEW().setInt32(result + 4, high, true); + return envObject.clearLastError(); + } + /** + * @__sig ipppp + */ + function napi_get_value_bigint_uint64(env, value, result, lossless) { + if (!env) + return 1 /* napi_status.napi_invalid_arg */; + // @ts-expect-error + var envObject = emnapiCtx.envStore.get(env); + envObject.checkGCAccess(); + if (!emnapiCtx.feature.supportBigInt) { + return envObject.setLastError(9 /* napi_status.napi_generic_failure */); + } + if (!value) + return envObject.setLastError(1 /* napi_status.napi_invalid_arg */); + if (!result) + return envObject.setLastError(1 /* napi_status.napi_invalid_arg */); + if (!lossless) + return envObject.setLastError(1 /* napi_status.napi_invalid_arg */); + var handle = emnapiCtx.handleStore.get(value); + var numberValue = handle.value; + if (typeof numberValue !== 'bigint') { + return envObject.setLastError(6 /* napi_status.napi_number_expected */); + } + lossless >>>= 0; + result >>>= 0; + var HEAP_DATA_VIEW = new DataView(wasmMemory.buffer), GET_HEAP_DATA_VIEW = function () { return HEAP_DATA_VIEW.buffer === wasmMemory.buffer ? HEAP_DATA_VIEW : (HEAP_DATA_VIEW = new DataView(wasmMemory.buffer)); }; + if ((numberValue >= BigInt(0)) && (numberValue < (BigInt(1) << BigInt(64)))) { + GET_HEAP_DATA_VIEW().setInt8(lossless, 1, true); + } + else { + GET_HEAP_DATA_VIEW().setInt8(lossless, 0, true); + numberValue = numberValue & ((BigInt(1) << BigInt(64)) - BigInt(1)); + } + // eslint-disable-next-line @typescript-eslint/no-unused-vars + var low = Number(numberValue & BigInt(0xffffffff)); + // eslint-disable-next-line @typescript-eslint/no-unused-vars + var high = Number(numberValue >> BigInt(32)); + GET_HEAP_DATA_VIEW().setUint32(result, low, true); + GET_HEAP_DATA_VIEW().setUint32(result + 4, high, true); + return envObject.clearLastError(); + } + /** + * @__sig ippppp + */ + function napi_get_value_bigint_words(env, value, sign_bit, word_count, words) { + if (!env) + return 1 /* napi_status.napi_invalid_arg */; + // @ts-expect-error + var envObject = emnapiCtx.envStore.get(env); + envObject.checkGCAccess(); + if (!emnapiCtx.feature.supportBigInt) { + return envObject.setLastError(9 /* napi_status.napi_generic_failure */); + } + if (!value) + return envObject.setLastError(1 /* napi_status.napi_invalid_arg */); + if (!word_count) + return envObject.setLastError(1 /* napi_status.napi_invalid_arg */); + var handle = emnapiCtx.handleStore.get(value); + if (!handle.isBigInt()) { + return envObject.setLastError(17 /* napi_status.napi_bigint_expected */); + } + var isMinus = handle.value < BigInt(0); + sign_bit >>>= 0; + words >>>= 0; + word_count >>>= 0; + var HEAP_DATA_VIEW = new DataView(wasmMemory.buffer), GET_HEAP_DATA_VIEW = function () { return HEAP_DATA_VIEW.buffer === wasmMemory.buffer ? HEAP_DATA_VIEW : (HEAP_DATA_VIEW = new DataView(wasmMemory.buffer)); }; + var word_count_int = GET_HEAP_DATA_VIEW().getUint32(word_count, true); + word_count_int >>>= 0; + var wordCount = 0; + var bigintValue = isMinus ? (handle.value * BigInt(-1)) : handle.value; + while (bigintValue !== BigInt(0)) { + wordCount++; + bigintValue = bigintValue >> BigInt(64); + } + bigintValue = isMinus ? (handle.value * BigInt(-1)) : handle.value; + if (!sign_bit && !words) { + word_count_int = wordCount; + GET_HEAP_DATA_VIEW().setUint32(word_count, word_count_int, true); + } + else { + if (!sign_bit) + return envObject.setLastError(1 /* napi_status.napi_invalid_arg */); + if (!words) + return envObject.setLastError(1 /* napi_status.napi_invalid_arg */); + var wordsArr = []; + while (bigintValue !== BigInt(0)) { + var uint64 = bigintValue & ((BigInt(1) << BigInt(64)) - BigInt(1)); + wordsArr.push(uint64); + bigintValue = bigintValue >> BigInt(64); + } + var len = Math.min(word_count_int, wordsArr.length); + for (var i = 0; i < len; i++) { + // eslint-disable-next-line @typescript-eslint/no-unused-vars + var low = Number(wordsArr[i] & BigInt(0xffffffff)); + // eslint-disable-next-line @typescript-eslint/no-unused-vars + var high = Number(wordsArr[i] >> BigInt(32)); + GET_HEAP_DATA_VIEW().setUint32(words + i * 8, low, true); + GET_HEAP_DATA_VIEW().setUint32(words + (i * 8 + 4), high, true); + } + GET_HEAP_DATA_VIEW().setInt32(sign_bit, isMinus ? 1 : 0, true); + GET_HEAP_DATA_VIEW().setUint32(word_count, len, true); + } + return envObject.clearLastError(); + } + /** + * @__sig ippp + */ + function napi_get_value_external(env, value, result) { + if (!env) + return 1 /* napi_status.napi_invalid_arg */; + // @ts-expect-error + var envObject = emnapiCtx.envStore.get(env); + envObject.checkGCAccess(); + if (!value) + return envObject.setLastError(1 /* napi_status.napi_invalid_arg */); + if (!result) + return envObject.setLastError(1 /* napi_status.napi_invalid_arg */); + var handle = emnapiCtx.handleStore.get(value); + if (!handle.isExternal()) { + return envObject.setLastError(1 /* napi_status.napi_invalid_arg */); + } + result >>>= 0; + // eslint-disable-next-line @typescript-eslint/no-unused-vars + var p = handle.data(); + var HEAP_DATA_VIEW = new DataView(wasmMemory.buffer), GET_HEAP_DATA_VIEW = function () { return HEAP_DATA_VIEW.buffer === wasmMemory.buffer ? HEAP_DATA_VIEW : (HEAP_DATA_VIEW = new DataView(wasmMemory.buffer)); }; + GET_HEAP_DATA_VIEW().setUint32(result, p, true); + return envObject.clearLastError(); + } + /** + * @__sig ippp + */ + function napi_get_value_int32(env, value, result) { + if (!env) + return 1 /* napi_status.napi_invalid_arg */; + // @ts-expect-error + var envObject = emnapiCtx.envStore.get(env); + envObject.checkGCAccess(); + if (!value) + return envObject.setLastError(1 /* napi_status.napi_invalid_arg */); + if (!result) + return envObject.setLastError(1 /* napi_status.napi_invalid_arg */); + var handle = emnapiCtx.handleStore.get(value); + if (typeof handle.value !== 'number') { + return envObject.setLastError(6 /* napi_status.napi_number_expected */); + } + result >>>= 0; + // eslint-disable-next-line @typescript-eslint/no-unused-vars + var v = new Int32Array([handle.value])[0]; + var HEAP_DATA_VIEW = new DataView(wasmMemory.buffer), GET_HEAP_DATA_VIEW = function () { return HEAP_DATA_VIEW.buffer === wasmMemory.buffer ? HEAP_DATA_VIEW : (HEAP_DATA_VIEW = new DataView(wasmMemory.buffer)); }; + GET_HEAP_DATA_VIEW().setInt32(result, v, true); + return envObject.clearLastError(); + } + /** + * @__sig ippp + */ + function napi_get_value_int64(env, value, result) { + if (!env) + return 1 /* napi_status.napi_invalid_arg */; + // @ts-expect-error + var envObject = emnapiCtx.envStore.get(env); + envObject.checkGCAccess(); + if (!value) + return envObject.setLastError(1 /* napi_status.napi_invalid_arg */); + if (!result) + return envObject.setLastError(1 /* napi_status.napi_invalid_arg */); + var handle = emnapiCtx.handleStore.get(value); + if (typeof handle.value !== 'number') { + return envObject.setLastError(6 /* napi_status.napi_number_expected */); + } + var numberValue = handle.value; + result >>>= 0; + var HEAP_DATA_VIEW = new DataView(wasmMemory.buffer), GET_HEAP_DATA_VIEW = function () { return HEAP_DATA_VIEW.buffer === wasmMemory.buffer ? HEAP_DATA_VIEW : (HEAP_DATA_VIEW = new DataView(wasmMemory.buffer)); }; + if (numberValue === Number.POSITIVE_INFINITY || numberValue === Number.NEGATIVE_INFINITY || isNaN(numberValue)) { + GET_HEAP_DATA_VIEW().setInt32(result, 0, true); + GET_HEAP_DATA_VIEW().setInt32(result + 4, 0, true); + } + else if (numberValue < /* INT64_RANGE_NEGATIVE */ -9223372036854776e3) { + GET_HEAP_DATA_VIEW().setInt32(result, 0, true); + GET_HEAP_DATA_VIEW().setInt32(result + 4, 2147483648, true); + } + else if (numberValue >= /* INT64_RANGE_POSITIVE */ 9223372036854776000) { + GET_HEAP_DATA_VIEW().setUint32(result, 4294967295, true); + GET_HEAP_DATA_VIEW().setUint32(result + 4, 2147483647, true); + } + else { + $emnapiSetValueI64(result, Math.trunc(numberValue)); + } + return envObject.clearLastError(); + } + /** + * @__sig ippppp + */ + function napi_get_value_string_latin1(env, value, buf, buf_size, result) { + if (!env) + return 1 /* napi_status.napi_invalid_arg */; + // @ts-expect-error + var envObject = emnapiCtx.envStore.get(env); + envObject.checkGCAccess(); + if (!value) + return envObject.setLastError(1 /* napi_status.napi_invalid_arg */); + result >>>= 0; + buf >>>= 0; + buf_size >>>= 0; + buf_size = buf_size >>> 0; + var handle = emnapiCtx.handleStore.get(value); + if (typeof handle.value !== 'string') { + return envObject.setLastError(3 /* napi_status.napi_string_expected */); + } + var HEAP_DATA_VIEW = new DataView(wasmMemory.buffer), GET_HEAP_DATA_VIEW = function () { return HEAP_DATA_VIEW.buffer === wasmMemory.buffer ? HEAP_DATA_VIEW : (HEAP_DATA_VIEW = new DataView(wasmMemory.buffer)); }; + if (!buf) { + if (!result) + return envObject.setLastError(1 /* napi_status.napi_invalid_arg */); + GET_HEAP_DATA_VIEW().setUint32(result, handle.value.length, true); + } + else if (buf_size !== 0) { + var copied = 0; + var v = void 0; + for (var i = 0; i < buf_size - 1; ++i) { + // eslint-disable-next-line @typescript-eslint/no-unused-vars + v = handle.value.charCodeAt(i) & 0xff; + GET_HEAP_DATA_VIEW().setUint8(buf + i, v, true); + // eslint-disable-next-line @typescript-eslint/no-unused-vars + copied++; + } + GET_HEAP_DATA_VIEW().setUint8(buf + copied, 0, true); + if (result) { + GET_HEAP_DATA_VIEW().setUint32(result, copied, true); + } + } + else if (result) { + GET_HEAP_DATA_VIEW().setUint32(result, 0, true); + } + return envObject.clearLastError(); + } + /** + * @__sig ippppp + */ + function napi_get_value_string_utf8(env, value, buf, buf_size, result) { + if (!env) + return 1 /* napi_status.napi_invalid_arg */; + // @ts-expect-error + var envObject = emnapiCtx.envStore.get(env); + envObject.checkGCAccess(); + if (!value) + return envObject.setLastError(1 /* napi_status.napi_invalid_arg */); + result >>>= 0; + buf >>>= 0; + buf_size >>>= 0; + buf_size = buf_size >>> 0; + var handle = emnapiCtx.handleStore.get(value); + if (typeof handle.value !== 'string') { + return envObject.setLastError(3 /* napi_status.napi_string_expected */); + } + var HEAP_DATA_VIEW = new DataView(wasmMemory.buffer), GET_HEAP_DATA_VIEW = function () { return HEAP_DATA_VIEW.buffer === wasmMemory.buffer ? HEAP_DATA_VIEW : (HEAP_DATA_VIEW = new DataView(wasmMemory.buffer)); }; + if (!buf) { + if (!result) + return envObject.setLastError(1 /* napi_status.napi_invalid_arg */); + // eslint-disable-next-line @typescript-eslint/no-unused-vars + var strLength = emnapiString.lengthBytesUTF8(handle.value); + GET_HEAP_DATA_VIEW().setUint32(result, strLength, true); + } + else if (buf_size !== 0) { + // eslint-disable-next-line @typescript-eslint/no-unused-vars + var copied = emnapiString.stringToUTF8(handle.value, buf, buf_size); + if (result) { + GET_HEAP_DATA_VIEW().setUint32(result, copied, true); + } + } + else if (result) { + GET_HEAP_DATA_VIEW().setUint32(result, 0, true); + } + return envObject.clearLastError(); + } + /** + * @__sig ippppp + */ + function napi_get_value_string_utf16(env, value, buf, buf_size, result) { + if (!env) + return 1 /* napi_status.napi_invalid_arg */; + // @ts-expect-error + var envObject = emnapiCtx.envStore.get(env); + envObject.checkGCAccess(); + if (!value) + return envObject.setLastError(1 /* napi_status.napi_invalid_arg */); + result >>>= 0; + buf >>>= 0; + buf_size >>>= 0; + buf_size = buf_size >>> 0; + var handle = emnapiCtx.handleStore.get(value); + if (typeof handle.value !== 'string') { + return envObject.setLastError(3 /* napi_status.napi_string_expected */); + } + var HEAP_DATA_VIEW = new DataView(wasmMemory.buffer), GET_HEAP_DATA_VIEW = function () { return HEAP_DATA_VIEW.buffer === wasmMemory.buffer ? HEAP_DATA_VIEW : (HEAP_DATA_VIEW = new DataView(wasmMemory.buffer)); }; + if (!buf) { + if (!result) + return envObject.setLastError(1 /* napi_status.napi_invalid_arg */); + GET_HEAP_DATA_VIEW().setUint32(result, handle.value.length, true); + } + else if (buf_size !== 0) { + // eslint-disable-next-line @typescript-eslint/no-unused-vars + var copied = emnapiString.stringToUTF16(handle.value, buf, buf_size * 2); + if (result) { + GET_HEAP_DATA_VIEW().setUint32(result, copied / 2, true); + } + } + else if (result) { + GET_HEAP_DATA_VIEW().setUint32(result, 0, true); + } + return envObject.clearLastError(); + } + /** + * @__sig ippp + */ + function napi_get_value_uint32(env, value, result) { + if (!env) + return 1 /* napi_status.napi_invalid_arg */; + // @ts-expect-error + var envObject = emnapiCtx.envStore.get(env); + envObject.checkGCAccess(); + if (!value) + return envObject.setLastError(1 /* napi_status.napi_invalid_arg */); + if (!result) + return envObject.setLastError(1 /* napi_status.napi_invalid_arg */); + var handle = emnapiCtx.handleStore.get(value); + if (typeof handle.value !== 'number') { + return envObject.setLastError(6 /* napi_status.napi_number_expected */); + } + result >>>= 0; + // eslint-disable-next-line @typescript-eslint/no-unused-vars + var v = new Uint32Array([handle.value])[0]; + var HEAP_DATA_VIEW = new DataView(wasmMemory.buffer), GET_HEAP_DATA_VIEW = function () { return HEAP_DATA_VIEW.buffer === wasmMemory.buffer ? HEAP_DATA_VIEW : (HEAP_DATA_VIEW = new DataView(wasmMemory.buffer)); }; + GET_HEAP_DATA_VIEW().setUint32(result, v, true); + return envObject.clearLastError(); + } + var convert2cMod = /*#__PURE__*/ Object.freeze({ + __proto__: null, + napi_get_array_length: napi_get_array_length, + napi_get_arraybuffer_info: napi_get_arraybuffer_info, + napi_get_buffer_info: napi_get_buffer_info, + napi_get_dataview_info: napi_get_dataview_info, + napi_get_date_value: napi_get_date_value, + napi_get_prototype: napi_get_prototype, + napi_get_typedarray_info: napi_get_typedarray_info, + napi_get_value_bigint_int64: napi_get_value_bigint_int64, + napi_get_value_bigint_uint64: napi_get_value_bigint_uint64, + napi_get_value_bigint_words: napi_get_value_bigint_words, + napi_get_value_bool: napi_get_value_bool, + napi_get_value_double: napi_get_value_double, + napi_get_value_external: napi_get_value_external, + napi_get_value_int32: napi_get_value_int32, + napi_get_value_int64: napi_get_value_int64, + napi_get_value_string_latin1: napi_get_value_string_latin1, + napi_get_value_string_utf16: napi_get_value_string_utf16, + napi_get_value_string_utf8: napi_get_value_string_utf8, + napi_get_value_uint32: napi_get_value_uint32, + node_api_set_prototype: node_api_set_prototype + }); + /** + * @__sig ipip + */ + function napi_create_int32(env, value, result) { + if (!env) + return 1 /* napi_status.napi_invalid_arg */; + // @ts-expect-error + var envObject = emnapiCtx.envStore.get(env); + envObject.checkGCAccess(); + if (!result) + return envObject.setLastError(1 /* napi_status.napi_invalid_arg */); + result >>>= 0; + // eslint-disable-next-line @typescript-eslint/no-unused-vars + var v = emnapiCtx.addToCurrentScope(value).id; + var HEAP_DATA_VIEW = new DataView(wasmMemory.buffer), GET_HEAP_DATA_VIEW = function () { return HEAP_DATA_VIEW.buffer === wasmMemory.buffer ? HEAP_DATA_VIEW : (HEAP_DATA_VIEW = new DataView(wasmMemory.buffer)); }; + GET_HEAP_DATA_VIEW().setUint32(result, v, true); + return envObject.clearLastError(); + } + /** + * @__sig ipip + */ + function napi_create_uint32(env, value, result) { + if (!env) + return 1 /* napi_status.napi_invalid_arg */; + // @ts-expect-error + var envObject = emnapiCtx.envStore.get(env); + envObject.checkGCAccess(); + if (!result) + return envObject.setLastError(1 /* napi_status.napi_invalid_arg */); + result >>>= 0; + // eslint-disable-next-line @typescript-eslint/no-unused-vars + var v = emnapiCtx.addToCurrentScope(value >>> 0).id; + var HEAP_DATA_VIEW = new DataView(wasmMemory.buffer), GET_HEAP_DATA_VIEW = function () { return HEAP_DATA_VIEW.buffer === wasmMemory.buffer ? HEAP_DATA_VIEW : (HEAP_DATA_VIEW = new DataView(wasmMemory.buffer)); }; + GET_HEAP_DATA_VIEW().setUint32(result, v, true); + return envObject.clearLastError(); + } + /** + * @__sig ipjp + */ + function napi_create_int64(env, low, high, result) { + if (!env) + return 1 /* napi_status.napi_invalid_arg */; + // @ts-expect-error + var envObject = emnapiCtx.envStore.get(env); + envObject.checkGCAccess(); + var value; + if (!high) + return envObject.setLastError(1 /* napi_status.napi_invalid_arg */); + value = Number(low); + // eslint-disable-next-line @typescript-eslint/no-unused-vars + var v1 = emnapiCtx.addToCurrentScope(value).id; + high >>>= 0; + var HEAP_DATA_VIEW = new DataView(wasmMemory.buffer), GET_HEAP_DATA_VIEW = function () { return HEAP_DATA_VIEW.buffer === wasmMemory.buffer ? HEAP_DATA_VIEW : (HEAP_DATA_VIEW = new DataView(wasmMemory.buffer)); }; + GET_HEAP_DATA_VIEW().setUint32(high, v1, true); + return envObject.clearLastError(); + } + /** + * @__sig ipdp + */ + function napi_create_double(env, value, result) { + if (!env) + return 1 /* napi_status.napi_invalid_arg */; + // @ts-expect-error + var envObject = emnapiCtx.envStore.get(env); + envObject.checkGCAccess(); + if (!result) + return envObject.setLastError(1 /* napi_status.napi_invalid_arg */); + result >>>= 0; + // eslint-disable-next-line @typescript-eslint/no-unused-vars + var v = emnapiCtx.addToCurrentScope(value).id; + var HEAP_DATA_VIEW = new DataView(wasmMemory.buffer), GET_HEAP_DATA_VIEW = function () { return HEAP_DATA_VIEW.buffer === wasmMemory.buffer ? HEAP_DATA_VIEW : (HEAP_DATA_VIEW = new DataView(wasmMemory.buffer)); }; + GET_HEAP_DATA_VIEW().setUint32(result, v, true); + return envObject.clearLastError(); + } + /** + * @__sig ipppp + */ + function napi_create_string_latin1(env, str, length, result) { + return emnapiString.newString(env, str, length, result, function (str, autoLength, sizeLength) { + var latin1String = ''; + var len = 0; + var HEAP_DATA_VIEW = new DataView(wasmMemory.buffer), GET_HEAP_DATA_VIEW = function () { return HEAP_DATA_VIEW.buffer === wasmMemory.buffer ? HEAP_DATA_VIEW : (HEAP_DATA_VIEW = new DataView(wasmMemory.buffer)); }; + if (autoLength) { + while (true) { + var ch = GET_HEAP_DATA_VIEW().getUint8(str, true); + if (!ch) + break; + latin1String += String.fromCharCode(ch); + str++; + } + } + else { + while (len < sizeLength) { + var ch = GET_HEAP_DATA_VIEW().getUint8(str, true); + if (!ch) + break; + latin1String += String.fromCharCode(ch); + len++; + str++; + } + } + return latin1String; + }); + } + /** + * @__sig ipppp + */ + function napi_create_string_utf16(env, str, length, result) { + return emnapiString.newString(env, str, length, result, function (str) { + return emnapiString.UTF16ToString(str, length); + }); + } + /** + * @__sig ipppp + */ + function napi_create_string_utf8(env, str, length, result) { + return emnapiString.newString(env, str, length, result, function (str) { + return emnapiString.UTF8ToString(str, length); + }); + } + /** + * @__sig ippppppp + */ + function node_api_create_external_string_latin1(env, str, length, finalize_callback, finalize_hint, result, copied) { + return emnapiString.newExternalString(env, str, length, finalize_callback, finalize_hint, result, copied, napi_create_string_latin1, undefined); + } + /** + * @__sig ippppppp + */ + function node_api_create_external_string_utf16(env, str, length, finalize_callback, finalize_hint, result, copied) { + return emnapiString.newExternalString(env, str, length, finalize_callback, finalize_hint, result, copied, napi_create_string_utf16, undefined); + } + /** + * @__sig ipppp + */ + function node_api_create_property_key_latin1(env, str, length, result) { + return napi_create_string_latin1(env, str, length, result); + } + /** + * @__sig ipppp + */ + function node_api_create_property_key_utf8(env, str, length, result) { + return napi_create_string_utf8(env, str, length, result); + } + /** + * @__sig ipppp + */ + function node_api_create_property_key_utf16(env, str, length, result) { + return napi_create_string_utf16(env, str, length, result); + } + /** + * @__sig ipjp + */ + function napi_create_bigint_int64(env, low, high, result) { + if (!env) + return 1 /* napi_status.napi_invalid_arg */; + // @ts-expect-error + var envObject = emnapiCtx.envStore.get(env); + envObject.checkGCAccess(); + if (!emnapiCtx.feature.supportBigInt) { + return envObject.setLastError(9 /* napi_status.napi_generic_failure */); + } + var value; + if (!high) + return envObject.setLastError(1 /* napi_status.napi_invalid_arg */); + value = low; + // eslint-disable-next-line @typescript-eslint/no-unused-vars + var v1 = emnapiCtx.addToCurrentScope(value).id; + high >>>= 0; + var HEAP_DATA_VIEW = new DataView(wasmMemory.buffer), GET_HEAP_DATA_VIEW = function () { return HEAP_DATA_VIEW.buffer === wasmMemory.buffer ? HEAP_DATA_VIEW : (HEAP_DATA_VIEW = new DataView(wasmMemory.buffer)); }; + GET_HEAP_DATA_VIEW().setUint32(high, v1, true); + return envObject.clearLastError(); + } + /** + * @__sig ipjp + */ + function napi_create_bigint_uint64(env, low, high, result) { + if (!env) + return 1 /* napi_status.napi_invalid_arg */; + // @ts-expect-error + var envObject = emnapiCtx.envStore.get(env); + envObject.checkGCAccess(); + if (!emnapiCtx.feature.supportBigInt) { + return envObject.setLastError(9 /* napi_status.napi_generic_failure */); + } + var value; + if (!high) + return envObject.setLastError(1 /* napi_status.napi_invalid_arg */); + value = low & ((BigInt(1) << BigInt(64)) - BigInt(1)); + // eslint-disable-next-line @typescript-eslint/no-unused-vars + var v1 = emnapiCtx.addToCurrentScope(value).id; + high >>>= 0; + var HEAP_DATA_VIEW = new DataView(wasmMemory.buffer), GET_HEAP_DATA_VIEW = function () { return HEAP_DATA_VIEW.buffer === wasmMemory.buffer ? HEAP_DATA_VIEW : (HEAP_DATA_VIEW = new DataView(wasmMemory.buffer)); }; + GET_HEAP_DATA_VIEW().setUint32(high, v1, true); + return envObject.clearLastError(); + } + /** + * @__sig ipippp + */ + function napi_create_bigint_words(env, sign_bit, word_count, words, result) { + // eslint-disable-next-line @typescript-eslint/no-unused-vars + var v, i; + if (!env) + return 1 /* napi_status.napi_invalid_arg */; + // @ts-expect-error + var envObject = emnapiCtx.envStore.get(env); + envObject.checkGCAccess(); + if (!envObject.tryCatch.isEmpty()) + return envObject.setLastError(10 /* napi_status.napi_pending_exception */); + if (!envObject.canCallIntoJs()) + return envObject.setLastError(envObject.moduleApiVersion >= 10 ? 23 /* napi_status.napi_cannot_run_js */ : 10 /* napi_status.napi_pending_exception */); + envObject.clearLastError(); + try { + if (!emnapiCtx.feature.supportBigInt) { + return envObject.setLastError(9 /* napi_status.napi_generic_failure */); + } + if (!result) + return envObject.setLastError(1 /* napi_status.napi_invalid_arg */); + words >>>= 0; + word_count >>>= 0; + word_count = word_count >>> 0; + if (word_count > 2147483647) { + return envObject.setLastError(1 /* napi_status.napi_invalid_arg */); + } + if (word_count > (1024 * 1024 / (4 * 8) / 2)) { + throw new RangeError('Maximum BigInt size exceeded'); + } + var value = BigInt(0); + var HEAP_DATA_VIEW = new DataView(wasmMemory.buffer), GET_HEAP_DATA_VIEW = function () { return HEAP_DATA_VIEW.buffer === wasmMemory.buffer ? HEAP_DATA_VIEW : (HEAP_DATA_VIEW = new DataView(wasmMemory.buffer)); }; + for (i = 0; i < word_count; i++) { + var low = GET_HEAP_DATA_VIEW().getUint32(words + i * 8, true); + var high = GET_HEAP_DATA_VIEW().getUint32(words + (i * 8 + 4), true); + var wordi = BigInt(low) | (BigInt(high) << BigInt(32)); + value += wordi << BigInt(64 * i); + } + value *= ((BigInt(sign_bit) % BigInt(2) === BigInt(0)) ? BigInt(1) : BigInt(-1)); + result >>>= 0; + v = emnapiCtx.addToCurrentScope(value).id; + GET_HEAP_DATA_VIEW().setUint32(result, v, true); + return envObject.getReturnStatus(); + } + catch (err) { + envObject.tryCatch.setError(err); + return envObject.setLastError(10 /* napi_status.napi_pending_exception */); + } + } + var convert2napiMod = /*#__PURE__*/ Object.freeze({ + __proto__: null, + napi_create_bigint_int64: napi_create_bigint_int64, + napi_create_bigint_uint64: napi_create_bigint_uint64, + napi_create_bigint_words: napi_create_bigint_words, + napi_create_double: napi_create_double, + napi_create_int32: napi_create_int32, + napi_create_int64: napi_create_int64, + napi_create_string_latin1: napi_create_string_latin1, + napi_create_string_utf16: napi_create_string_utf16, + napi_create_string_utf8: napi_create_string_utf8, + napi_create_uint32: napi_create_uint32, + node_api_create_external_string_latin1: node_api_create_external_string_latin1, + node_api_create_external_string_utf16: node_api_create_external_string_utf16, + node_api_create_property_key_latin1: node_api_create_property_key_latin1, + node_api_create_property_key_utf16: node_api_create_property_key_utf16, + node_api_create_property_key_utf8: node_api_create_property_key_utf8 + }); + function emnapiCreateFunction(envObject, utf8name, length, cb, data) { + utf8name >>>= 0; + var functionName = (!utf8name || !length) ? '' : (emnapiString.UTF8ToString(utf8name, length)); + var f; + var napiCallback = (wasmTable.get(cb)); + var callback = function (envObject) { + return napiCallback(envObject.id, envObject.ctx.scopeStore.currentScope.id); + }; + var makeFunction = function (envObject, callback) { + return function () { + var scope = envObject.ctx.openScope(envObject); + var callbackInfo = scope.callbackInfo; + callbackInfo.data = data; + callbackInfo.args = arguments; + callbackInfo.thiz = this; + callbackInfo.fn = f; + try { + var napiValue = envObject.callIntoModule(callback); + return (!napiValue) ? undefined : envObject.ctx.handleStore.get(napiValue).value; + } + finally { + callbackInfo.data = 0; + callbackInfo.args = undefined; + callbackInfo.thiz = undefined; + callbackInfo.fn = undefined; + envObject.ctx.closeScope(envObject, scope); + } + }; + }; + if (functionName === '') { + f = makeFunction(envObject, callback); + return { status: 0 /* napi_status.napi_ok */, f: f }; + } + if (!(/^[_$a-zA-Z][_$a-zA-Z0-9]*$/.test(functionName))) { + return { status: 1 /* napi_status.napi_invalid_arg */, f: undefined }; + } + if (emnapiCtx.feature.supportNewFunction) { + var _ = makeFunction(envObject, callback); + try { + f = (new Function('_', 'return function ' + functionName + '(){' + + '"use strict";' + + 'return _.apply(this,arguments);' + + '};'))(_); + } + catch (_err) { + f = makeFunction(envObject, callback); + if (emnapiCtx.feature.canSetFunctionName) + Object.defineProperty(f, 'name', { value: functionName }); + } + } + else { + f = makeFunction(envObject, callback); + if (emnapiCtx.feature.canSetFunctionName) + Object.defineProperty(f, 'name', { value: functionName }); + } + return { status: 0 /* napi_status.napi_ok */, f: f }; + } + function emnapiDefineProperty(envObject, obj, propertyName, method, getter, setter, value, attributes, data) { + if (getter || setter) { + var localGetter = void 0; + var localSetter = void 0; + if (getter) { + localGetter = emnapiCreateFunction(envObject, 0, 0, getter, data).f; + } + if (setter) { + localSetter = emnapiCreateFunction(envObject, 0, 0, setter, data).f; + } + var desc = { + configurable: (attributes & 4 /* napi_property_attributes.napi_configurable */) !== 0, + enumerable: (attributes & 2 /* napi_property_attributes.napi_enumerable */) !== 0, + get: localGetter, + set: localSetter + }; + Object.defineProperty(obj, propertyName, desc); + } + else if (method) { + var localMethod = emnapiCreateFunction(envObject, 0, 0, method, data).f; + var desc = { + configurable: (attributes & 4 /* napi_property_attributes.napi_configurable */) !== 0, + enumerable: (attributes & 2 /* napi_property_attributes.napi_enumerable */) !== 0, + writable: (attributes & 1 /* napi_property_attributes.napi_writable */) !== 0, + value: localMethod + }; + Object.defineProperty(obj, propertyName, desc); + } + else { + var desc = { + configurable: (attributes & 4 /* napi_property_attributes.napi_configurable */) !== 0, + enumerable: (attributes & 2 /* napi_property_attributes.napi_enumerable */) !== 0, + writable: (attributes & 1 /* napi_property_attributes.napi_writable */) !== 0, + value: emnapiCtx.handleStore.get(value).value + }; + Object.defineProperty(obj, propertyName, desc); + } + } + function emnapiGetHandle(js_object) { + var handle = emnapiCtx.handleStore.get(js_object); + if (!(handle.isObject() || handle.isFunction())) { + return { status: 1 /* napi_status.napi_invalid_arg */ }; + } + if (typeof emnapiExternalMemory !== 'undefined' && ArrayBuffer.isView(handle.value)) { + if (emnapiExternalMemory.wasmMemoryViewTable.has(handle.value)) { + handle = emnapiCtx.addToCurrentScope(emnapiExternalMemory.wasmMemoryViewTable.get(handle.value)); + } + } + return { status: 0 /* napi_status.napi_ok */, handle: handle }; + } + function emnapiWrap(env, js_object, native_object, finalize_cb, finalize_hint, result) { + // eslint-disable-next-line @typescript-eslint/no-unused-vars + var referenceId; + if (!env) + return 1 /* napi_status.napi_invalid_arg */; + // @ts-expect-error + var envObject = emnapiCtx.envStore.get(env); + envObject.checkGCAccess(); + if (!envObject.tryCatch.isEmpty()) + return envObject.setLastError(10 /* napi_status.napi_pending_exception */); + if (!envObject.canCallIntoJs()) + return envObject.setLastError(envObject.moduleApiVersion >= 10 ? 23 /* napi_status.napi_cannot_run_js */ : 10 /* napi_status.napi_pending_exception */); + envObject.clearLastError(); + try { + if (!emnapiCtx.feature.supportFinalizer) { + if (finalize_cb) { + throw emnapiCtx.createNotSupportWeakRefError('napi_wrap', 'Parameter "finalize_cb" must be 0(NULL)'); + } + if (result) { + throw emnapiCtx.createNotSupportWeakRefError('napi_wrap', 'Parameter "result" must be 0(NULL)'); + } + } + if (!js_object) + return envObject.setLastError(1 /* napi_status.napi_invalid_arg */); + var handleResult = emnapiGetHandle(js_object); + if (handleResult.status !== 0 /* napi_status.napi_ok */) { + return envObject.setLastError(handleResult.status); + } + var handle = handleResult.handle; + if (envObject.getObjectBinding(handle.value).wrapped !== 0) { + return envObject.setLastError(1 /* napi_status.napi_invalid_arg */); + } + var reference = void 0; + if (result) { + if (!finalize_cb) + return envObject.setLastError(1 /* napi_status.napi_invalid_arg */); + reference = emnapiCtx.createReferenceWithFinalizer(envObject, handle.id, 0, 1 /* ReferenceOwnership.kUserland */, finalize_cb, native_object, finalize_hint); + result >>>= 0; + referenceId = reference.id; + var HEAP_DATA_VIEW = new DataView(wasmMemory.buffer), GET_HEAP_DATA_VIEW = function () { return HEAP_DATA_VIEW.buffer === wasmMemory.buffer ? HEAP_DATA_VIEW : (HEAP_DATA_VIEW = new DataView(wasmMemory.buffer)); }; + GET_HEAP_DATA_VIEW().setUint32(result, referenceId, true); + } + else { + if (finalize_cb) { + reference = emnapiCtx.createReferenceWithFinalizer(envObject, handle.id, 0, 0 /* ReferenceOwnership.kRuntime */, finalize_cb, native_object, finalize_hint); + } + else { + reference = emnapiCtx.createReferenceWithData(envObject, handle.id, 0, 0 /* ReferenceOwnership.kRuntime */, native_object); + } + } + envObject.getObjectBinding(handle.value).wrapped = reference.id; + return envObject.getReturnStatus(); + } + catch (err) { + envObject.tryCatch.setError(err); + return envObject.setLastError(10 /* napi_status.napi_pending_exception */); + } + } + function emnapiUnwrap(env, js_object, result, action) { + // eslint-disable-next-line @typescript-eslint/no-unused-vars + var data; + if (!env) + return 1 /* napi_status.napi_invalid_arg */; + // @ts-expect-error + var envObject = emnapiCtx.envStore.get(env); + envObject.checkGCAccess(); + if (!envObject.tryCatch.isEmpty()) + return envObject.setLastError(10 /* napi_status.napi_pending_exception */); + if (!envObject.canCallIntoJs()) + return envObject.setLastError(envObject.moduleApiVersion >= 10 ? 23 /* napi_status.napi_cannot_run_js */ : 10 /* napi_status.napi_pending_exception */); + envObject.clearLastError(); + try { + if (!js_object) + return envObject.setLastError(1 /* napi_status.napi_invalid_arg */); + if (action === 0 /* UnwrapAction.KeepWrap */) { + if (!result) + return envObject.setLastError(1 /* napi_status.napi_invalid_arg */); + } + var value = emnapiCtx.handleStore.get(js_object); + if (!(value.isObject() || value.isFunction())) { + return envObject.setLastError(1 /* napi_status.napi_invalid_arg */); + } + var binding = envObject.getObjectBinding(value.value); + var referenceId = binding.wrapped; + var ref = emnapiCtx.refStore.get(referenceId); + if (!ref) + return envObject.setLastError(1 /* napi_status.napi_invalid_arg */); + if (result) { + result >>>= 0; + // eslint-disable-next-line @typescript-eslint/no-unused-vars + data = ref.data(); + var HEAP_DATA_VIEW = new DataView(wasmMemory.buffer), GET_HEAP_DATA_VIEW = function () { return HEAP_DATA_VIEW.buffer === wasmMemory.buffer ? HEAP_DATA_VIEW : (HEAP_DATA_VIEW = new DataView(wasmMemory.buffer)); }; + GET_HEAP_DATA_VIEW().setUint32(result, data, true); + } + if (action === 1 /* UnwrapAction.RemoveWrap */) { + binding.wrapped = 0; + if (ref.ownership() === 1 /* ReferenceOwnership.kUserland */) { + // When the wrap is been removed, the finalizer should be reset. + ref.resetFinalizer(); + } + else { + ref.dispose(); + } + } + return envObject.getReturnStatus(); + } + catch (err) { + envObject.tryCatch.setError(err); + return envObject.setLastError(10 /* napi_status.napi_pending_exception */); + } + } + /** + * @__sig ipppppppp + */ + function napi_define_class(env, utf8name, length, constructor, callback_data, property_count, properties, result) { + // eslint-disable-next-line @typescript-eslint/no-unused-vars + var propPtr, valueHandleId, attributes; + if (!env) + return 1 /* napi_status.napi_invalid_arg */; + // @ts-expect-error + var envObject = emnapiCtx.envStore.get(env); + envObject.checkGCAccess(); + if (!envObject.tryCatch.isEmpty()) + return envObject.setLastError(10 /* napi_status.napi_pending_exception */); + if (!envObject.canCallIntoJs()) + return envObject.setLastError(envObject.moduleApiVersion >= 10 ? 23 /* napi_status.napi_cannot_run_js */ : 10 /* napi_status.napi_pending_exception */); + envObject.clearLastError(); + try { + if (!result) + return envObject.setLastError(1 /* napi_status.napi_invalid_arg */); + if (!constructor) + return envObject.setLastError(1 /* napi_status.napi_invalid_arg */); + length >>>= 0; + properties >>>= 0; + property_count >>>= 0; + property_count = property_count >>> 0; + if (property_count > 0) { + if (!properties) + return envObject.setLastError(1 /* napi_status.napi_invalid_arg */); + } + if (!((length >= -1 && length <= 2147483647) || length === 4294967295) || (!utf8name)) { + return envObject.setLastError(1 /* napi_status.napi_invalid_arg */); + } + var fresult = emnapiCreateFunction(envObject, utf8name, length, constructor, callback_data); + if (fresult.status !== 0 /* napi_status.napi_ok */) + return envObject.setLastError(fresult.status); + var F = fresult.f; + var propertyName = void 0; + var HEAP_DATA_VIEW = new DataView(wasmMemory.buffer), GET_HEAP_DATA_VIEW = function () { return HEAP_DATA_VIEW.buffer === wasmMemory.buffer ? HEAP_DATA_VIEW : (HEAP_DATA_VIEW = new DataView(wasmMemory.buffer)); }; + for (var i = 0; i < property_count; i++) { + // eslint-disable-next-line @typescript-eslint/no-unused-vars + propPtr = properties + (i * (4 * 8)); + var utf8Name = GET_HEAP_DATA_VIEW().getUint32(propPtr, true); + var name_1 = GET_HEAP_DATA_VIEW().getUint32(propPtr + 4, true); + var method = GET_HEAP_DATA_VIEW().getUint32(propPtr + 8, true); + var getter = GET_HEAP_DATA_VIEW().getUint32(propPtr + 12, true); + var setter = GET_HEAP_DATA_VIEW().getUint32(propPtr + 16, true); + var value = GET_HEAP_DATA_VIEW().getUint32(propPtr + 20, true); + attributes = GET_HEAP_DATA_VIEW().getInt32(propPtr + 24, true); + attributes >>>= 0; + var data = GET_HEAP_DATA_VIEW().getUint32(propPtr + 28, true); + if (utf8Name) { + propertyName = emnapiString.UTF8ToString(utf8Name, -1); + } + else { + if (!name_1) { + return envObject.setLastError(4 /* napi_status.napi_name_expected */); + } + propertyName = emnapiCtx.handleStore.get(name_1).value; + if (typeof propertyName !== 'string' && typeof propertyName !== 'symbol') { + return envObject.setLastError(4 /* napi_status.napi_name_expected */); + } + } + if ((attributes & 1024 /* napi_property_attributes.napi_static */) !== 0) { + emnapiDefineProperty(envObject, F, propertyName, method, getter, setter, value, attributes, data); + continue; + } + emnapiDefineProperty(envObject, F.prototype, propertyName, method, getter, setter, value, attributes, data); + } + // eslint-disable-next-line @typescript-eslint/no-unused-vars + var valueHandle = emnapiCtx.addToCurrentScope(F); + valueHandleId = valueHandle.id; + result >>>= 0; + GET_HEAP_DATA_VIEW().setUint32(result, valueHandleId, true); + return envObject.getReturnStatus(); + } + catch (err) { + envObject.tryCatch.setError(err); + return envObject.setLastError(10 /* napi_status.napi_pending_exception */); + } + } + /** + * @__sig ipppppp + */ + function napi_wrap(env, js_object, native_object, finalize_cb, finalize_hint, result) { + return emnapiWrap(env, js_object, native_object, finalize_cb, finalize_hint, result); + } + /** + * @__sig ippp + */ + function napi_unwrap(env, js_object, result) { + return emnapiUnwrap(env, js_object, result, 0 /* UnwrapAction.KeepWrap */); + } + /** + * @__sig ippp + */ + function napi_remove_wrap(env, js_object, result) { + return emnapiUnwrap(env, js_object, result, 1 /* UnwrapAction.RemoveWrap */); + } + /** + * @__sig ippp + */ + function napi_type_tag_object(env, object, type_tag) { + if (!env) + return 1 /* napi_status.napi_invalid_arg */; + // @ts-expect-error + var envObject = emnapiCtx.envStore.get(env); + envObject.checkGCAccess(); + if (!envObject.tryCatch.isEmpty()) + return envObject.setLastError(10 /* napi_status.napi_pending_exception */); + if (!envObject.canCallIntoJs()) + return envObject.setLastError(envObject.moduleApiVersion >= 10 ? 23 /* napi_status.napi_cannot_run_js */ : 10 /* napi_status.napi_pending_exception */); + envObject.clearLastError(); + try { + if (!object) { + return envObject.setLastError(envObject.tryCatch.hasCaught() ? 10 /* napi_status.napi_pending_exception */ : 1 /* napi_status.napi_invalid_arg */); + } + var value = emnapiCtx.handleStore.get(object); + if (!(value.isObject() || value.isFunction())) { + return envObject.setLastError(envObject.tryCatch.hasCaught() ? 10 /* napi_status.napi_pending_exception */ : 2 /* napi_status.napi_object_expected */); + } + type_tag >>>= 0; + if (!type_tag) { + return envObject.setLastError(envObject.tryCatch.hasCaught() ? 10 /* napi_status.napi_pending_exception */ : 1 /* napi_status.napi_invalid_arg */); + } + var binding = envObject.getObjectBinding(value.value); + if (binding.tag !== null) { + return envObject.setLastError(envObject.tryCatch.hasCaught() ? 10 /* napi_status.napi_pending_exception */ : 1 /* napi_status.napi_invalid_arg */); + } + var tag = new Uint8Array(16); + tag.set(new Uint8Array(wasmMemory.buffer, type_tag, 16)); + binding.tag = new Uint32Array(tag.buffer); + return envObject.getReturnStatus(); + } + catch (err) { + envObject.tryCatch.setError(err); + return envObject.setLastError(10 /* napi_status.napi_pending_exception */); + } + } + /** + * @__sig ipppp + */ + function napi_check_object_type_tag(env, object, type_tag, result) { + // eslint-disable-next-line @typescript-eslint/no-unused-vars, one-var + var ret = true; + if (!env) + return 1 /* napi_status.napi_invalid_arg */; + // @ts-expect-error + var envObject = emnapiCtx.envStore.get(env); + envObject.checkGCAccess(); + if (!envObject.tryCatch.isEmpty()) + return envObject.setLastError(10 /* napi_status.napi_pending_exception */); + if (!envObject.canCallIntoJs()) + return envObject.setLastError(envObject.moduleApiVersion >= 10 ? 23 /* napi_status.napi_cannot_run_js */ : 10 /* napi_status.napi_pending_exception */); + envObject.clearLastError(); + try { + if (!object) { + return envObject.setLastError(envObject.tryCatch.hasCaught() ? 10 /* napi_status.napi_pending_exception */ : 1 /* napi_status.napi_invalid_arg */); + } + var value = emnapiCtx.handleStore.get(object); + if (!(value.isObject() || value.isFunction())) { + return envObject.setLastError(envObject.tryCatch.hasCaught() ? 10 /* napi_status.napi_pending_exception */ : 2 /* napi_status.napi_object_expected */); + } + if (!type_tag) { + return envObject.setLastError(envObject.tryCatch.hasCaught() ? 10 /* napi_status.napi_pending_exception */ : 1 /* napi_status.napi_invalid_arg */); + } + if (!result) { + return envObject.setLastError(envObject.tryCatch.hasCaught() ? 10 /* napi_status.napi_pending_exception */ : 1 /* napi_status.napi_invalid_arg */); + } + var binding = envObject.getObjectBinding(value.value); + if (binding.tag !== null) { + type_tag >>>= 0; + var tag = binding.tag; + var typeTag = new Uint32Array(wasmMemory.buffer, type_tag, 4); + ret = (tag[0] === typeTag[0] && + tag[1] === typeTag[1] && + tag[2] === typeTag[2] && + tag[3] === typeTag[3]); + } + else { + ret = false; + } + result >>>= 0; + var HEAP_DATA_VIEW = new DataView(wasmMemory.buffer), GET_HEAP_DATA_VIEW = function () { return HEAP_DATA_VIEW.buffer === wasmMemory.buffer ? HEAP_DATA_VIEW : (HEAP_DATA_VIEW = new DataView(wasmMemory.buffer)); }; + GET_HEAP_DATA_VIEW().setInt8(result, ret ? 1 : 0, true); + return envObject.getReturnStatus(); + } + catch (err) { + envObject.tryCatch.setError(err); + return envObject.setLastError(10 /* napi_status.napi_pending_exception */); + } + } + /** + * @__sig ipppppp + */ + function napi_add_finalizer(env, js_object, finalize_data, finalize_cb, finalize_hint, result) { + if (!env) + return 1 /* napi_status.napi_invalid_arg */; + // @ts-expect-error + var envObject = emnapiCtx.envStore.get(env); + envObject.checkGCAccess(); + if (!emnapiCtx.feature.supportFinalizer) { + return envObject.setLastError(9 /* napi_status.napi_generic_failure */); + } + if (!js_object) + return envObject.setLastError(1 /* napi_status.napi_invalid_arg */); + if (!finalize_cb) + return envObject.setLastError(1 /* napi_status.napi_invalid_arg */); + var handleResult = emnapiGetHandle(js_object); + if (handleResult.status !== 0 /* napi_status.napi_ok */) { + return envObject.setLastError(handleResult.status); + } + var handle = handleResult.handle; + var ownership = !result ? 0 /* ReferenceOwnership.kRuntime */ : 1 /* ReferenceOwnership.kUserland */; + finalize_data >>>= 0; + finalize_cb >>>= 0; + finalize_hint >>>= 0; + var reference = emnapiCtx.createReferenceWithFinalizer(envObject, handle.id, 0, ownership, finalize_cb, finalize_data, finalize_hint); + if (result) { + result >>>= 0; + // eslint-disable-next-line @typescript-eslint/no-unused-vars + var referenceId = reference.id; + var HEAP_DATA_VIEW = new DataView(wasmMemory.buffer), GET_HEAP_DATA_VIEW = function () { return HEAP_DATA_VIEW.buffer === wasmMemory.buffer ? HEAP_DATA_VIEW : (HEAP_DATA_VIEW = new DataView(wasmMemory.buffer)); }; + GET_HEAP_DATA_VIEW().setUint32(result, referenceId, true); + } + return envObject.clearLastError(); + } + /** + * @__sig ipppp + */ + function node_api_post_finalizer(env, finalize_cb, finalize_data, finalize_hint) { + if (!env) + return 1 /* napi_status.napi_invalid_arg */; + var envObject = emnapiCtx.envStore.get(env); + envObject.enqueueFinalizer(emnapiCtx.createTrackedFinalizer(envObject, finalize_cb, finalize_data, finalize_hint)); + return envObject.clearLastError(); + } + var wrapMod = /*#__PURE__*/ Object.freeze({ + __proto__: null, + napi_add_finalizer: napi_add_finalizer, + napi_check_object_type_tag: napi_check_object_type_tag, + napi_define_class: napi_define_class, + napi_remove_wrap: napi_remove_wrap, + napi_type_tag_object: napi_type_tag_object, + napi_unwrap: napi_unwrap, + napi_wrap: napi_wrap, + node_api_post_finalizer: node_api_post_finalizer + }); + /** + * @__sig ipippppp + */ + function emnapi_create_memory_view(env, typedarray_type, external_data, byte_length, finalize_cb, finalize_hint, result) { + // eslint-disable-next-line @typescript-eslint/no-unused-vars + var value; + if (!env) + return 1 /* napi_status.napi_invalid_arg */; + // @ts-expect-error + var envObject = emnapiCtx.envStore.get(env); + envObject.checkGCAccess(); + if (!envObject.tryCatch.isEmpty()) + return envObject.setLastError(10 /* napi_status.napi_pending_exception */); + if (!envObject.canCallIntoJs()) + return envObject.setLastError(envObject.moduleApiVersion >= 10 ? 23 /* napi_status.napi_cannot_run_js */ : 10 /* napi_status.napi_pending_exception */); + envObject.clearLastError(); + try { + if (!result) + return envObject.setLastError(1 /* napi_status.napi_invalid_arg */); + byte_length >>>= 0; + external_data >>>= 0; + result >>>= 0; + byte_length = byte_length >>> 0; + if (!external_data) { + byte_length = 0; + } + if (byte_length > 2147483647) { + throw new RangeError('Cannot create a memory view larger than 2147483647 bytes'); + } + if ((external_data + byte_length) > wasmMemory.buffer.byteLength) { + throw new RangeError('Memory out of range'); + } + if (!emnapiCtx.feature.supportFinalizer && finalize_cb) { + throw emnapiCtx.createNotSupportWeakRefError('emnapi_create_memory_view', 'Parameter "finalize_cb" must be 0(NULL)'); + } + var viewDescriptor = void 0; + switch (typedarray_type) { + case 0 /* emnapi_memory_view_type.emnapi_int8_array */: + viewDescriptor = { Ctor: Int8Array, address: external_data, length: byte_length, ownership: 1 /* ReferenceOwnership.kUserland */, runtimeAllocated: 0 }; + break; + case 1 /* emnapi_memory_view_type.emnapi_uint8_array */: + viewDescriptor = { Ctor: Uint8Array, address: external_data, length: byte_length, ownership: 1 /* ReferenceOwnership.kUserland */, runtimeAllocated: 0 }; + break; + case 2 /* emnapi_memory_view_type.emnapi_uint8_clamped_array */: + viewDescriptor = { Ctor: Uint8ClampedArray, address: external_data, length: byte_length, ownership: 1 /* ReferenceOwnership.kUserland */, runtimeAllocated: 0 }; + break; + case 3 /* emnapi_memory_view_type.emnapi_int16_array */: + viewDescriptor = { Ctor: Int16Array, address: external_data, length: byte_length >> 1, ownership: 1 /* ReferenceOwnership.kUserland */, runtimeAllocated: 0 }; + break; + case 4 /* emnapi_memory_view_type.emnapi_uint16_array */: + viewDescriptor = { Ctor: Uint16Array, address: external_data, length: byte_length >> 1, ownership: 1 /* ReferenceOwnership.kUserland */, runtimeAllocated: 0 }; + break; + case 5 /* emnapi_memory_view_type.emnapi_int32_array */: + viewDescriptor = { Ctor: Int32Array, address: external_data, length: byte_length >> 2, ownership: 1 /* ReferenceOwnership.kUserland */, runtimeAllocated: 0 }; + break; + case 6 /* emnapi_memory_view_type.emnapi_uint32_array */: + viewDescriptor = { Ctor: Uint32Array, address: external_data, length: byte_length >> 2, ownership: 1 /* ReferenceOwnership.kUserland */, runtimeAllocated: 0 }; + break; + case 7 /* emnapi_memory_view_type.emnapi_float32_array */: + viewDescriptor = { Ctor: Float32Array, address: external_data, length: byte_length >> 2, ownership: 1 /* ReferenceOwnership.kUserland */, runtimeAllocated: 0 }; + break; + case 8 /* emnapi_memory_view_type.emnapi_float64_array */: + viewDescriptor = { Ctor: Float64Array, address: external_data, length: byte_length >> 3, ownership: 1 /* ReferenceOwnership.kUserland */, runtimeAllocated: 0 }; + break; + case 9 /* emnapi_memory_view_type.emnapi_bigint64_array */: + viewDescriptor = { Ctor: BigInt64Array, address: external_data, length: byte_length >> 3, ownership: 1 /* ReferenceOwnership.kUserland */, runtimeAllocated: 0 }; + break; + case 10 /* emnapi_memory_view_type.emnapi_biguint64_array */: + viewDescriptor = { Ctor: BigUint64Array, address: external_data, length: byte_length >> 3, ownership: 1 /* ReferenceOwnership.kUserland */, runtimeAllocated: 0 }; + break; + case -1 /* emnapi_memory_view_type.emnapi_data_view */: + viewDescriptor = { Ctor: DataView, address: external_data, length: byte_length, ownership: 1 /* ReferenceOwnership.kUserland */, runtimeAllocated: 0 }; + break; + case 11 /* emnapi_memory_view_type.emnapi_float16_array */: + if (typeof Float16Array !== 'function') { + return envObject.setLastError(1 /* napi_status.napi_invalid_arg */); + } + viewDescriptor = { Ctor: Float16Array, address: external_data, length: byte_length >> 1, ownership: 1 /* ReferenceOwnership.kUserland */, runtimeAllocated: 0 }; + break; + case -2 /* emnapi_memory_view_type.emnapi_buffer */: { + if (!emnapiCtx.feature.Buffer) { + throw emnapiCtx.createNotSupportBufferError('emnapi_create_memory_view', ''); + } + viewDescriptor = { Ctor: emnapiCtx.feature.Buffer, address: external_data, length: byte_length, ownership: 1 /* ReferenceOwnership.kUserland */, runtimeAllocated: 0 }; + break; + } + default: return envObject.setLastError(1 /* napi_status.napi_invalid_arg */); + } + var Ctor = viewDescriptor.Ctor; + var typedArray = typedarray_type === -2 /* emnapi_memory_view_type.emnapi_buffer */ + // capture Buffer.from at creation so a later refreshed view uses it + ? emnapiExternalMemory.getBufferFrom()(wasmMemory.buffer, viewDescriptor.address, viewDescriptor.length) + : new Ctor(wasmMemory.buffer, viewDescriptor.address, viewDescriptor.length); + var handle = emnapiCtx.addToCurrentScope(typedArray); + emnapiExternalMemory.wasmMemoryViewTable.set(typedArray, viewDescriptor); + if (finalize_cb) { + var status_1 = napi_add_finalizer(env, handle.id, external_data, finalize_cb, finalize_hint, /* NULL */ 0); + if (status_1 === 10 /* napi_status.napi_pending_exception */) { + var err = envObject.tryCatch.extractException(); + envObject.clearLastError(); + throw err; + } + else if (status_1 !== 0 /* napi_status.napi_ok */) { + return envObject.setLastError(status_1); + } + } + value = handle.id; + var HEAP_DATA_VIEW = new DataView(wasmMemory.buffer), GET_HEAP_DATA_VIEW = function () { return HEAP_DATA_VIEW.buffer === wasmMemory.buffer ? HEAP_DATA_VIEW : (HEAP_DATA_VIEW = new DataView(wasmMemory.buffer)); }; + GET_HEAP_DATA_VIEW().setUint32(result, value, true); + return envObject.getReturnStatus(); + } + catch (err) { + envObject.tryCatch.setError(err); + return envObject.setLastError(10 /* napi_status.napi_pending_exception */); + } + } + /** + * @__sig i + */ + function emnapi_is_support_weakref() { + return emnapiCtx.feature.supportFinalizer ? 1 : 0; + } + /** + * @__sig i + */ + function emnapi_is_support_bigint() { + return emnapiCtx.feature.supportBigInt ? 1 : 0; + } + /** + * @__sig i + */ + function emnapi_is_node_binding_available() { + return emnapiNodeBinding ? 1 : 0; + } + /** + * Synchronize data between the wasm memory and an ArrayBuffer / view. + * + * Note: when a non-shared wasm memory has grown, a view over the detached + * old buffer is re-created over the current buffer through the intrinsic + * base-class constructor, so for view inputs the returned view may be a + * base-class instance (e.g. `Uint8Array` or `DataView`) instead of the + * subclass that was passed in. + */ + function $emnapiSyncMemory(js_to_wasm, arrayBufferOrView, offset, len) { + offset = offset !== null && offset !== void 0 ? offset : 0; + offset = offset >>> 0; + var view; + if (arrayBufferOrView instanceof ArrayBuffer || emnapiExternalMemory.isSharedArrayBuffer(arrayBufferOrView)) { + var pointer = emnapiExternalMemory.getArrayBufferPointer(arrayBufferOrView, false).address; + if (!pointer) + throw new Error('Unknown ArrayBuffer address'); + if (typeof len !== 'number' || len === -1 || len === 4294967295) { + len = arrayBufferOrView.byteLength - offset; + } + len = len >>> 0; + if (len === 0) + return arrayBufferOrView; + view = new Uint8Array(arrayBufferOrView, offset, len); + var wasmMemoryU8 = new Uint8Array(wasmMemory.buffer); + if (!js_to_wasm) { + view.set(wasmMemoryU8.subarray(pointer, pointer + len)); + } + else { + wasmMemoryU8.set(view, pointer); + } + return arrayBufferOrView; + } + if (ArrayBuffer.isView(arrayBufferOrView)) { + var viewPointerInfo = emnapiExternalMemory.getViewPointer(arrayBufferOrView, false); + var latestView = viewPointerInfo.view; + var pointer = viewPointerInfo.address; + if (!pointer) + throw new Error('Unknown ArrayBuffer address'); + if (typeof len !== 'number' || len === -1 || len === 4294967295) { + len = latestView.byteLength - offset; + } + len = len >>> 0; + if (len === 0) + return latestView; + view = new Uint8Array(latestView.buffer, latestView.byteOffset + offset, len); + var wasmMemoryU8 = new Uint8Array(wasmMemory.buffer); + if (!js_to_wasm) { + view.set(wasmMemoryU8.subarray(pointer, pointer + len)); + } + else { + wasmMemoryU8.set(view, pointer); + } + return latestView; + } + throw new TypeError('emnapiSyncMemory expect ArrayBuffer or ArrayBufferView as first parameter'); + } + /** + * @__sig ipippp + */ + function emnapi_sync_memory(env, js_to_wasm, arraybuffer_or_view, offset, len) { + // eslint-disable-next-line @typescript-eslint/no-unused-vars + var v; + if (!env) + return 1 /* napi_status.napi_invalid_arg */; + // @ts-expect-error + var envObject = emnapiCtx.envStore.get(env); + envObject.checkGCAccess(); + if (!envObject.tryCatch.isEmpty()) + return envObject.setLastError(10 /* napi_status.napi_pending_exception */); + if (!envObject.canCallIntoJs()) + return envObject.setLastError(envObject.moduleApiVersion >= 10 ? 23 /* napi_status.napi_cannot_run_js */ : 10 /* napi_status.napi_pending_exception */); + envObject.clearLastError(); + try { + if (!arraybuffer_or_view) + return envObject.setLastError(1 /* napi_status.napi_invalid_arg */); + arraybuffer_or_view >>>= 0; + offset >>>= 0; + len >>>= 0; + var HEAP_DATA_VIEW = new DataView(wasmMemory.buffer), GET_HEAP_DATA_VIEW = function () { return HEAP_DATA_VIEW.buffer === wasmMemory.buffer ? HEAP_DATA_VIEW : (HEAP_DATA_VIEW = new DataView(wasmMemory.buffer)); }; + var handleId = GET_HEAP_DATA_VIEW().getUint32(arraybuffer_or_view, true); + var handle = envObject.ctx.handleStore.get(handleId); + if (!handle.isArrayBuffer() && !handle.isTypedArray() && !handle.isDataView() && !emnapiExternalMemory.isSharedArrayBuffer(handle.value)) { + return envObject.setLastError(1 /* napi_status.napi_invalid_arg */); + } + var ret = $emnapiSyncMemory(Boolean(js_to_wasm), handle.value, offset, len); + if (handle.value !== ret) { + arraybuffer_or_view >>>= 0; + v = envObject.ensureHandleId(ret); + GET_HEAP_DATA_VIEW().setUint32(arraybuffer_or_view, v, true); + } + return envObject.getReturnStatus(); + } + catch (err) { + envObject.tryCatch.setError(err); + return envObject.setLastError(10 /* napi_status.napi_pending_exception */); + } + } + function $emnapiGetMemoryAddress(arrayBufferOrView) { + var isArrayBuffer = arrayBufferOrView instanceof ArrayBuffer; + var isDataView = arrayBufferOrView instanceof DataView; + var isTypedArray = ArrayBuffer.isView(arrayBufferOrView) && !isDataView; + if (!isArrayBuffer && !isTypedArray && !isDataView && !emnapiExternalMemory.isSharedArrayBuffer(arrayBufferOrView)) { + throw new TypeError('emnapiGetMemoryAddress expect ArrayBuffer or ArrayBufferView as first parameter'); + } + var info; + if (isArrayBuffer) { + info = emnapiExternalMemory.getArrayBufferPointer(arrayBufferOrView, false); + } + else { + info = emnapiExternalMemory.getViewPointer(arrayBufferOrView, false); + } + return { + address: info.address, + ownership: info.ownership, + runtimeAllocated: info.runtimeAllocated + }; + } + /** + * @__sig ipppp + */ + function emnapi_get_memory_address(env, arraybuffer_or_view, address, ownership, runtime_allocated) { + // eslint-disable-next-line @typescript-eslint/no-unused-vars + var p, runtimeAllocated, ownershipOut; + var info; + if (!env) + return 1 /* napi_status.napi_invalid_arg */; + // @ts-expect-error + var envObject = emnapiCtx.envStore.get(env); + envObject.checkGCAccess(); + if (!envObject.tryCatch.isEmpty()) + return envObject.setLastError(10 /* napi_status.napi_pending_exception */); + if (!envObject.canCallIntoJs()) + return envObject.setLastError(envObject.moduleApiVersion >= 10 ? 23 /* napi_status.napi_cannot_run_js */ : 10 /* napi_status.napi_pending_exception */); + envObject.clearLastError(); + try { + if (!arraybuffer_or_view) + return envObject.setLastError(1 /* napi_status.napi_invalid_arg */); + if (!address && !ownership && !runtime_allocated) { + return envObject.setLastError(1 /* napi_status.napi_invalid_arg */); + } + var handle = envObject.ctx.handleStore.get(arraybuffer_or_view); + info = $emnapiGetMemoryAddress(handle.value); + p = info.address; + var HEAP_DATA_VIEW = new DataView(wasmMemory.buffer), GET_HEAP_DATA_VIEW = function () { return HEAP_DATA_VIEW.buffer === wasmMemory.buffer ? HEAP_DATA_VIEW : (HEAP_DATA_VIEW = new DataView(wasmMemory.buffer)); }; + if (address) { + address >>>= 0; + GET_HEAP_DATA_VIEW().setUint32(address, p, true); + } + if (ownership) { + ownership >>>= 0; + ownershipOut = info.ownership; + GET_HEAP_DATA_VIEW().setInt32(ownership, ownershipOut, true); + } + if (runtime_allocated) { + runtime_allocated >>>= 0; + runtimeAllocated = info.runtimeAllocated; + GET_HEAP_DATA_VIEW().setInt8(runtime_allocated, runtimeAllocated, true); + } + return envObject.getReturnStatus(); + } + catch (err) { + envObject.tryCatch.setError(err); + return envObject.setLastError(10 /* napi_status.napi_pending_exception */); + } + } + /** + * @__sig ipp + */ + function emnapi_get_runtime_version(env, version) { + if (!env) + return 1 /* napi_status.napi_invalid_arg */; + var envObject = emnapiCtx.envStore.get(env); + if (!version) + return envObject.setLastError(1 /* napi_status.napi_invalid_arg */); + var runtimeVersion; + try { + runtimeVersion = emnapiCtx.getRuntimeVersions().version; + } + catch (_) { + return envObject.setLastError(9 /* napi_status.napi_generic_failure */); + } + // eslint-disable-next-line @typescript-eslint/no-unused-vars + var versions = runtimeVersion.split('.') + .map(function (n) { return Number(n); }); + version >>>= 0; + var HEAP_DATA_VIEW = new DataView(wasmMemory.buffer), GET_HEAP_DATA_VIEW = function () { return HEAP_DATA_VIEW.buffer === wasmMemory.buffer ? HEAP_DATA_VIEW : (HEAP_DATA_VIEW = new DataView(wasmMemory.buffer)); }; + GET_HEAP_DATA_VIEW().setUint32(version, versions[0], true); + GET_HEAP_DATA_VIEW().setUint32(version + 4, versions[1], true); + GET_HEAP_DATA_VIEW().setUint32(version + 8, versions[2], true); + return envObject.clearLastError(); + } + /** + * Get the handle for an external SharedArrayBuffer. + * Must be called on the emnapi main thread. + * @__sig ippp + */ + function emnapi_get_external_sharedarraybuffer_handle(env, sharedarraybuffer, handle) { + if (!env) + return 1 /* napi_status.napi_invalid_arg */; + // @ts-expect-error + var envObject = emnapiCtx.envStore.get(env); + envObject.checkGCAccess(); + if (!envObject.tryCatch.isEmpty()) + return envObject.setLastError(10 /* napi_status.napi_pending_exception */); + if (!envObject.canCallIntoJs()) + return envObject.setLastError(envObject.moduleApiVersion >= 10 ? 23 /* napi_status.napi_cannot_run_js */ : 10 /* napi_status.napi_pending_exception */); + envObject.clearLastError(); + try { + if (!sharedarraybuffer) + return envObject.setLastError(1 /* napi_status.napi_invalid_arg */); + if (!handle) + return envObject.setLastError(1 /* napi_status.napi_invalid_arg */); + handle >>>= 0; + var jsValue = emnapiCtx.handleStore.get(sharedarraybuffer).value; + if (!emnapiExternalMemory.isSharedArrayBuffer(jsValue)) { + return envObject.setLastError(1 /* napi_status.napi_invalid_arg */); + } + var metaPtr = emnapiExternalSAB.handleTable.get(jsValue); + if (metaPtr === undefined) { + return envObject.setLastError(1 /* napi_status.napi_invalid_arg */); + } + var HEAP_DATA_VIEW = new DataView(wasmMemory.buffer), GET_HEAP_DATA_VIEW = function () { return HEAP_DATA_VIEW.buffer === wasmMemory.buffer ? HEAP_DATA_VIEW : (HEAP_DATA_VIEW = new DataView(wasmMemory.buffer)); }; + GET_HEAP_DATA_VIEW().setUint32(handle, metaPtr, true); + return envObject.getReturnStatus(); + } + catch (err) { + envObject.tryCatch.setError(err); + return envObject.setLastError(10 /* napi_status.napi_pending_exception */); + } + } + /** + * Acquire a reference to an external SharedArrayBuffer. + * Can be called on any thread. + * @__sig vp + */ + function emnapi_acquire_external_sharedarraybuffer(handle) { + handle >>>= 0; + Atomics.add(new Int32Array(wasmMemory.buffer, handle, 1), 0, 1); + } + /** + * Release a reference to an external SharedArrayBuffer. + * Can be called on any thread. + * @__sig vp + */ + function emnapi_release_external_sharedarraybuffer(handle) { + handle >>>= 0; + emnapiExternalSAB.release(handle); + } + /** + * Acquire a reference to an external SharedArrayBuffer on the current thread. + * Can be called on any thread. Increments refcount and registers in + * the current thread's FinalizationRegistry. + * Exposed as Module.emnapiAcquireExternalSharedArrayBuffer (emscripten) or + * napiModule.emnapi.acquireExternalSharedArrayBuffer (core). + */ + function $emnapiAcquireExternalSharedArrayBuffer(handle, sab) { + if (sab != null && !emnapiExternalMemory.isSharedArrayBuffer(sab)) { + throw new TypeError('Expected a SharedArrayBuffer'); + } + if (!emnapiExternalSAB.registry) { + throw new Error('FinalizationRegistry is not supported in this environment'); + } + handle >>>= 0; + var meta = emnapiExternalSAB.readMeta(handle); + // eslint-disable-next-line prefer-const + var external_data = meta.external_data; + external_data >>>= 0; + if (sab == null) { + sab = new SharedArrayBuffer(meta.byte_length); + new Uint8Array(sab).set(new Uint8Array(wasmMemory.buffer, external_data, meta.byte_length)); + } + else { + if (emnapiExternalSAB.handleTable.has(sab)) { + return sab; + } + } + // Increment refcount atomically + Atomics.add(new Int32Array(wasmMemory.buffer, handle, 1), 0, 1); + // Register in emnapiExternalMemory.table for emnapi_sync_memory support + if (!emnapiExternalMemory.table.has(sab)) { + if (external_data) { + emnapiExternalMemory.table.set(sab, { + address: external_data, + ownership: 1 /* ReferenceOwnership.kUserland */, + runtimeAllocated: 0 + }); + } + } + // Register in handleTable and FinalizationRegistry for this thread + emnapiExternalSAB.handleTable.set(sab, handle); + emnapiExternalSAB.registry.register(sab, handle); + return sab; + } + var emnapiMod = /*#__PURE__*/ Object.freeze({ + __proto__: null, + $emnapiAcquireExternalSharedArrayBuffer: $emnapiAcquireExternalSharedArrayBuffer, + $emnapiGetMemoryAddress: $emnapiGetMemoryAddress, + $emnapiSyncMemory: $emnapiSyncMemory, + emnapi_acquire_external_sharedarraybuffer: emnapi_acquire_external_sharedarraybuffer, + emnapi_create_memory_view: emnapi_create_memory_view, + emnapi_get_external_sharedarraybuffer_handle: emnapi_get_external_sharedarraybuffer_handle, + emnapi_get_memory_address: emnapi_get_memory_address, + emnapi_get_runtime_version: emnapi_get_runtime_version, + emnapi_is_node_binding_available: emnapi_is_node_binding_available, + emnapi_is_support_bigint: emnapi_is_support_bigint, + emnapi_is_support_weakref: emnapi_is_support_weakref, + emnapi_release_external_sharedarraybuffer: emnapi_release_external_sharedarraybuffer, + emnapi_sync_memory: emnapi_sync_memory + }); + /** + * @__sig ipp + */ + function napi_create_array(env, result) { + if (!env) + return 1 /* napi_status.napi_invalid_arg */; + // @ts-expect-error + var envObject = emnapiCtx.envStore.get(env); + envObject.checkGCAccess(); + if (!result) + return envObject.setLastError(1 /* napi_status.napi_invalid_arg */); + result >>>= 0; + // eslint-disable-next-line @typescript-eslint/no-unused-vars + var value = emnapiCtx.addToCurrentScope([]).id; + var HEAP_DATA_VIEW = new DataView(wasmMemory.buffer), GET_HEAP_DATA_VIEW = function () { return HEAP_DATA_VIEW.buffer === wasmMemory.buffer ? HEAP_DATA_VIEW : (HEAP_DATA_VIEW = new DataView(wasmMemory.buffer)); }; + GET_HEAP_DATA_VIEW().setUint32(result, value, true); + return envObject.clearLastError(); + } + /** + * @__sig ippp + */ + function napi_create_array_with_length(env, length, result) { + if (!env) + return 1 /* napi_status.napi_invalid_arg */; + // @ts-expect-error + var envObject = emnapiCtx.envStore.get(env); + envObject.checkGCAccess(); + if (!result) + return envObject.setLastError(1 /* napi_status.napi_invalid_arg */); + length >>>= 0; + result >>>= 0; + length = length >>> 0; + // eslint-disable-next-line @typescript-eslint/no-unused-vars + var value = emnapiCtx.addToCurrentScope(new Array(length)).id; + var HEAP_DATA_VIEW = new DataView(wasmMemory.buffer), GET_HEAP_DATA_VIEW = function () { return HEAP_DATA_VIEW.buffer === wasmMemory.buffer ? HEAP_DATA_VIEW : (HEAP_DATA_VIEW = new DataView(wasmMemory.buffer)); }; + GET_HEAP_DATA_VIEW().setUint32(result, value, true); + return envObject.clearLastError(); + } + function emnapiCreateArrayBuffer(byte_length, data, shared) { + byte_length >>>= 0; + byte_length = byte_length >>> 0; + var arrayBuffer = shared ? new SharedArrayBuffer(byte_length) : new ArrayBuffer(byte_length); + if (data) { + data >>>= 0; + // eslint-disable-next-line @typescript-eslint/no-unused-vars + var p = emnapiExternalMemory.getArrayBufferPointer(arrayBuffer, true).address; + var HEAP_DATA_VIEW = new DataView(wasmMemory.buffer), GET_HEAP_DATA_VIEW = function () { return HEAP_DATA_VIEW.buffer === wasmMemory.buffer ? HEAP_DATA_VIEW : (HEAP_DATA_VIEW = new DataView(wasmMemory.buffer)); }; + GET_HEAP_DATA_VIEW().setUint32(data, p, true); + } + return arrayBuffer; + } + /** + * @__sig ipppp + */ + function napi_create_arraybuffer(env, byte_length, data, result) { + // eslint-disable-next-line @typescript-eslint/no-unused-vars + var value; + if (!env) + return 1 /* napi_status.napi_invalid_arg */; + // @ts-expect-error + var envObject = emnapiCtx.envStore.get(env); + envObject.checkGCAccess(); + if (!envObject.tryCatch.isEmpty()) + return envObject.setLastError(10 /* napi_status.napi_pending_exception */); + if (!envObject.canCallIntoJs()) + return envObject.setLastError(envObject.moduleApiVersion >= 10 ? 23 /* napi_status.napi_cannot_run_js */ : 10 /* napi_status.napi_pending_exception */); + envObject.clearLastError(); + try { + if (!result) + return envObject.setLastError(1 /* napi_status.napi_invalid_arg */); + result >>>= 0; + var arrayBuffer = emnapiCreateArrayBuffer(byte_length, data, false); + value = emnapiCtx.addToCurrentScope(arrayBuffer).id; + var HEAP_DATA_VIEW = new DataView(wasmMemory.buffer), GET_HEAP_DATA_VIEW = function () { return HEAP_DATA_VIEW.buffer === wasmMemory.buffer ? HEAP_DATA_VIEW : (HEAP_DATA_VIEW = new DataView(wasmMemory.buffer)); }; + GET_HEAP_DATA_VIEW().setUint32(result, value, true); + return envObject.getReturnStatus(); + } + catch (err) { + envObject.tryCatch.setError(err); + return envObject.setLastError(10 /* napi_status.napi_pending_exception */); + } + } + /** + * @__sig ipppp + */ + function node_api_create_sharedarraybuffer(env, byte_length, data, result) { + // eslint-disable-next-line @typescript-eslint/no-unused-vars + var value; + if (!env) + return 1 /* napi_status.napi_invalid_arg */; + // @ts-expect-error + var envObject = emnapiCtx.envStore.get(env); + envObject.checkGCAccess(); + if (!envObject.tryCatch.isEmpty()) + return envObject.setLastError(10 /* napi_status.napi_pending_exception */); + if (!envObject.canCallIntoJs()) + return envObject.setLastError(envObject.moduleApiVersion >= 10 ? 23 /* napi_status.napi_cannot_run_js */ : 10 /* napi_status.napi_pending_exception */); + envObject.clearLastError(); + try { + if (!result) + return envObject.setLastError(1 /* napi_status.napi_invalid_arg */); + result >>>= 0; + var arrayBuffer = emnapiCreateArrayBuffer(byte_length, data, true); + value = emnapiCtx.addToCurrentScope(arrayBuffer).id; + var HEAP_DATA_VIEW = new DataView(wasmMemory.buffer), GET_HEAP_DATA_VIEW = function () { return HEAP_DATA_VIEW.buffer === wasmMemory.buffer ? HEAP_DATA_VIEW : (HEAP_DATA_VIEW = new DataView(wasmMemory.buffer)); }; + GET_HEAP_DATA_VIEW().setUint32(result, value, true); + return envObject.getReturnStatus(); + } + catch (err) { + envObject.tryCatch.setError(err); + return envObject.setLastError(10 /* napi_status.napi_pending_exception */); + } + } + /** + * @__sig ipdp + */ + function napi_create_date(env, time, result) { + // eslint-disable-next-line @typescript-eslint/no-unused-vars + var value; + if (!env) + return 1 /* napi_status.napi_invalid_arg */; + // @ts-expect-error + var envObject = emnapiCtx.envStore.get(env); + envObject.checkGCAccess(); + if (!envObject.tryCatch.isEmpty()) + return envObject.setLastError(10 /* napi_status.napi_pending_exception */); + if (!envObject.canCallIntoJs()) + return envObject.setLastError(envObject.moduleApiVersion >= 10 ? 23 /* napi_status.napi_cannot_run_js */ : 10 /* napi_status.napi_pending_exception */); + envObject.clearLastError(); + try { + if (!result) + return envObject.setLastError(1 /* napi_status.napi_invalid_arg */); + result >>>= 0; + // eslint-disable-next-line @typescript-eslint/no-unused-vars + value = emnapiCtx.addToCurrentScope(new Date(time)).id; + var HEAP_DATA_VIEW = new DataView(wasmMemory.buffer), GET_HEAP_DATA_VIEW = function () { return HEAP_DATA_VIEW.buffer === wasmMemory.buffer ? HEAP_DATA_VIEW : (HEAP_DATA_VIEW = new DataView(wasmMemory.buffer)); }; + GET_HEAP_DATA_VIEW().setUint32(result, value, true); + return envObject.getReturnStatus(); + } + catch (err) { + envObject.tryCatch.setError(err); + return envObject.setLastError(10 /* napi_status.napi_pending_exception */); + } + } + /** + * @__sig ippppp + */ + function napi_create_external(env, data, finalize_cb, finalize_hint, result) { + // eslint-disable-next-line @typescript-eslint/no-unused-vars + var value; + if (!env) + return 1 /* napi_status.napi_invalid_arg */; + // @ts-expect-error + var envObject = emnapiCtx.envStore.get(env); + envObject.checkGCAccess(); + if (!envObject.tryCatch.isEmpty()) + return envObject.setLastError(10 /* napi_status.napi_pending_exception */); + if (!envObject.canCallIntoJs()) + return envObject.setLastError(envObject.moduleApiVersion >= 10 ? 23 /* napi_status.napi_cannot_run_js */ : 10 /* napi_status.napi_pending_exception */); + envObject.clearLastError(); + try { + if (!result) + return envObject.setLastError(1 /* napi_status.napi_invalid_arg */); + if (!emnapiCtx.feature.supportFinalizer && finalize_cb) { + throw emnapiCtx.createNotSupportWeakRefError('napi_create_external', 'Parameter "finalize_cb" must be 0(NULL)'); + } + var externalHandle = emnapiCtx.getCurrentScope().addExternal(data); + if (finalize_cb) { + emnapiCtx.createReferenceWithFinalizer(envObject, externalHandle.id, 0, 0 /* ReferenceOwnership.kRuntime */, finalize_cb, data, finalize_hint); + } + result >>>= 0; + value = externalHandle.id; + var HEAP_DATA_VIEW = new DataView(wasmMemory.buffer), GET_HEAP_DATA_VIEW = function () { return HEAP_DATA_VIEW.buffer === wasmMemory.buffer ? HEAP_DATA_VIEW : (HEAP_DATA_VIEW = new DataView(wasmMemory.buffer)); }; + GET_HEAP_DATA_VIEW().setUint32(result, value, true); + return envObject.clearLastError(); + } + catch (err) { + envObject.tryCatch.setError(err); + return envObject.setLastError(10 /* napi_status.napi_pending_exception */); + } + } + /** + * @__sig ipppppp + */ + function napi_create_external_arraybuffer(env, external_data, byte_length, finalize_cb, finalize_hint, result) { + // eslint-disable-next-line @typescript-eslint/no-unused-vars + var value; + if (!env) + return 1 /* napi_status.napi_invalid_arg */; + // @ts-expect-error + var envObject = emnapiCtx.envStore.get(env); + envObject.checkGCAccess(); + if (!envObject.tryCatch.isEmpty()) + return envObject.setLastError(10 /* napi_status.napi_pending_exception */); + if (!envObject.canCallIntoJs()) + return envObject.setLastError(envObject.moduleApiVersion >= 10 ? 23 /* napi_status.napi_cannot_run_js */ : 10 /* napi_status.napi_pending_exception */); + envObject.clearLastError(); + try { + if (!result) + return envObject.setLastError(1 /* napi_status.napi_invalid_arg */); + byte_length >>>= 0; + external_data >>>= 0; + result >>>= 0; + byte_length = byte_length >>> 0; + if (!external_data) { + byte_length = 0; + } + if ((external_data + byte_length) > wasmMemory.buffer.byteLength) { + throw new RangeError('Memory out of range'); + } + if (!emnapiCtx.feature.supportFinalizer && finalize_cb) { + throw emnapiCtx.createNotSupportWeakRefError('napi_create_external_arraybuffer', 'Parameter "finalize_cb" must be 0(NULL)'); + } + var arrayBuffer = new ArrayBuffer(byte_length); + if (byte_length === 0) { + try { + var MessageChannel_1 = emnapiCtx.feature.MessageChannel; + var messageChannel = new MessageChannel_1(); + messageChannel.port1.postMessage(arrayBuffer, [arrayBuffer]); + } + catch (_) { } + } + else { + var u8arr = new Uint8Array(arrayBuffer); + u8arr.set(new Uint8Array(wasmMemory.buffer).subarray(external_data, external_data + byte_length)); + emnapiExternalMemory.table.set(arrayBuffer, { + address: external_data, + ownership: 1 /* ReferenceOwnership.kUserland */, + runtimeAllocated: 0 + }); + } + var handle = emnapiCtx.addToCurrentScope(arrayBuffer); + if (finalize_cb) { + var status_1 = napi_add_finalizer(env, handle.id, external_data, finalize_cb, finalize_hint, /* NULL */ 0); + if (status_1 === 10 /* napi_status.napi_pending_exception */) { + var err = envObject.tryCatch.extractException(); + envObject.clearLastError(); + throw err; + } + else if (status_1 !== 0 /* napi_status.napi_ok */) { + return envObject.setLastError(status_1); + } + } + value = handle.id; + var HEAP_DATA_VIEW = new DataView(wasmMemory.buffer), GET_HEAP_DATA_VIEW = function () { return HEAP_DATA_VIEW.buffer === wasmMemory.buffer ? HEAP_DATA_VIEW : (HEAP_DATA_VIEW = new DataView(wasmMemory.buffer)); }; + GET_HEAP_DATA_VIEW().setUint32(result, value, true); + return envObject.getReturnStatus(); + } + catch (err) { + envObject.tryCatch.setError(err); + return envObject.setLastError(10 /* napi_status.napi_pending_exception */); + } + } + /** + * @__sig ipppppp + */ + function node_api_create_external_sharedarraybuffer(env, external_data, byte_length, finalize_cb, finalize_hint, result) { + // eslint-disable-next-line @typescript-eslint/no-unused-vars + var value; + if (!env) + return 1 /* napi_status.napi_invalid_arg */; + // @ts-expect-error + var envObject = emnapiCtx.envStore.get(env); + envObject.checkGCAccess(); + if (!envObject.tryCatch.isEmpty()) + return envObject.setLastError(10 /* napi_status.napi_pending_exception */); + if (!envObject.canCallIntoJs()) + return envObject.setLastError(envObject.moduleApiVersion >= 10 ? 23 /* napi_status.napi_cannot_run_js */ : 10 /* napi_status.napi_pending_exception */); + envObject.clearLastError(); + try { + if (!result) + return envObject.setLastError(1 /* napi_status.napi_invalid_arg */); + byte_length >>>= 0; + external_data >>>= 0; + result >>>= 0; + byte_length = byte_length >>> 0; + if (!external_data) { + byte_length = 0; + } + if ((external_data + byte_length) > wasmMemory.buffer.byteLength) { + throw new RangeError('Memory out of range'); + } + if (!emnapiExternalSAB.registry && finalize_cb) { + throw emnapiCtx.createNotSupportWeakRefError('node_api_create_external_sharedarraybuffer', 'Parameter "finalize_cb" must be 0(NULL)'); + } + var sharedArrayBuffer = new SharedArrayBuffer(byte_length); + if (byte_length !== 0) { + var u8arr = new Uint8Array(sharedArrayBuffer); + u8arr.set(new Uint8Array(wasmMemory.buffer).subarray(external_data, external_data + byte_length)); + emnapiExternalMemory.table.set(sharedArrayBuffer, { + address: external_data, + ownership: 1 /* ReferenceOwnership.kUserland */, + runtimeAllocated: 0 + }); + } + value = emnapiCtx.addToCurrentScope(sharedArrayBuffer).id; + if (finalize_cb) { + finalize_cb >>>= 0; + finalize_hint >>>= 0; + var metaPtr = emnapiExternalSAB.allocMeta(external_data, byte_length, finalize_cb, external_data, finalize_hint); + emnapiExternalSAB.handleTable.set(sharedArrayBuffer, metaPtr); + emnapiExternalSAB.registry.register(sharedArrayBuffer, metaPtr); + } + var HEAP_DATA_VIEW = new DataView(wasmMemory.buffer), GET_HEAP_DATA_VIEW = function () { return HEAP_DATA_VIEW.buffer === wasmMemory.buffer ? HEAP_DATA_VIEW : (HEAP_DATA_VIEW = new DataView(wasmMemory.buffer)); }; + GET_HEAP_DATA_VIEW().setUint32(result, value, true); + return envObject.getReturnStatus(); + } + catch (err) { + envObject.tryCatch.setError(err); + return envObject.setLastError(10 /* napi_status.napi_pending_exception */); + } + } + /** + * @__sig ipp + */ + function napi_create_object(env, result) { + if (!env) + return 1 /* napi_status.napi_invalid_arg */; + // @ts-expect-error + var envObject = emnapiCtx.envStore.get(env); + envObject.checkGCAccess(); + if (!result) + return envObject.setLastError(1 /* napi_status.napi_invalid_arg */); + result >>>= 0; + // eslint-disable-next-line @typescript-eslint/no-unused-vars + var value = emnapiCtx.addToCurrentScope({}).id; + var HEAP_DATA_VIEW = new DataView(wasmMemory.buffer), GET_HEAP_DATA_VIEW = function () { return HEAP_DATA_VIEW.buffer === wasmMemory.buffer ? HEAP_DATA_VIEW : (HEAP_DATA_VIEW = new DataView(wasmMemory.buffer)); }; + GET_HEAP_DATA_VIEW().setUint32(result, value, true); + return envObject.clearLastError(); + } + /** + * @__sig ipppppp + */ + function node_api_create_object_with_properties(env, prototype_or_null, property_names, property_values, property_count, result) { + if (!env) + return 1 /* napi_status.napi_invalid_arg */; + // @ts-expect-error + var envObject = emnapiCtx.envStore.get(env); + envObject.checkGCAccess(); + if (!result) + return envObject.setLastError(1 /* napi_status.napi_invalid_arg */); + property_count >>>= 0; + property_count = property_count >>> 0; + if (property_count > 0) { + if (!property_names) + return envObject.setLastError(1 /* napi_status.napi_invalid_arg */); + if (!property_values) + return envObject.setLastError(1 /* napi_status.napi_invalid_arg */); + } + var v8_prototype_or_null = prototype_or_null + ? emnapiCtx.handleStore.get(prototype_or_null).value + : null; + var properties = {}; + property_names >>>= 0; + property_values >>>= 0; + var HEAP_DATA_VIEW = new DataView(wasmMemory.buffer), GET_HEAP_DATA_VIEW = function () { return HEAP_DATA_VIEW.buffer === wasmMemory.buffer ? HEAP_DATA_VIEW : (HEAP_DATA_VIEW = new DataView(wasmMemory.buffer)); }; + for (var i = 0; i < property_count; i++) { + var name_value = emnapiCtx.handleStore.get(GET_HEAP_DATA_VIEW().getUint32(property_names + i * 4, true)).value; + if (!(typeof name_value === "string" || typeof name_value === "symbol")) + return envObject.setLastError(4 /* napi_status.napi_name_expected */); + properties[name_value] = { + value: emnapiCtx.handleStore.get(GET_HEAP_DATA_VIEW().getUint32(property_values + i * 4, true)).value, + writable: true, + enumerable: true, + configurable: true + }; + } + var obj; + try { + obj = Object.defineProperties(Object.create(v8_prototype_or_null), properties); + } + catch (_) { + return envObject.setLastError(9 /* napi_status.napi_generic_failure */); + } + // eslint-disable-next-line @typescript-eslint/no-unused-vars + var value = emnapiCtx.addToCurrentScope(obj).id; + result >>>= 0; + GET_HEAP_DATA_VIEW().setUint32(result, value, true); + return envObject.clearLastError(); + } + /** + * @__sig ippp + */ + function napi_create_symbol(env, description, result) { + if (!env) + return 1 /* napi_status.napi_invalid_arg */; + // @ts-expect-error + var envObject = emnapiCtx.envStore.get(env); + envObject.checkGCAccess(); + if (!result) + return envObject.setLastError(1 /* napi_status.napi_invalid_arg */); + result >>>= 0; + var HEAP_DATA_VIEW = new DataView(wasmMemory.buffer), GET_HEAP_DATA_VIEW = function () { return HEAP_DATA_VIEW.buffer === wasmMemory.buffer ? HEAP_DATA_VIEW : (HEAP_DATA_VIEW = new DataView(wasmMemory.buffer)); }; + if (!description) { + // eslint-disable-next-line symbol-description, @typescript-eslint/no-unused-vars + var value = emnapiCtx.addToCurrentScope(Symbol()).id; + GET_HEAP_DATA_VIEW().setUint32(result, value, true); + } + else { + var handle = emnapiCtx.handleStore.get(description); + var desc = handle.value; + if (typeof desc !== 'string') { + return envObject.setLastError(3 /* napi_status.napi_string_expected */); + } + // eslint-disable-next-line @typescript-eslint/no-unused-vars + var v = emnapiCtx.addToCurrentScope(Symbol(desc)).id; + GET_HEAP_DATA_VIEW().setUint32(result, v, true); + } + return envObject.clearLastError(); + } + /** + * @__sig ipipppp + */ + function napi_create_typedarray(env, type, length, arraybuffer, byte_offset, result) { + // eslint-disable-next-line @typescript-eslint/no-unused-vars + var value; + if (!env) + return 1 /* napi_status.napi_invalid_arg */; + // @ts-expect-error + var envObject = emnapiCtx.envStore.get(env); + envObject.checkGCAccess(); + if (!envObject.tryCatch.isEmpty()) + return envObject.setLastError(10 /* napi_status.napi_pending_exception */); + if (!envObject.canCallIntoJs()) + return envObject.setLastError(envObject.moduleApiVersion >= 10 ? 23 /* napi_status.napi_cannot_run_js */ : 10 /* napi_status.napi_pending_exception */); + envObject.clearLastError(); + try { + if (!arraybuffer) + return envObject.setLastError(1 /* napi_status.napi_invalid_arg */); + if (!result) + return envObject.setLastError(1 /* napi_status.napi_invalid_arg */); + var handle = emnapiCtx.handleStore.get(arraybuffer); + var buffer = handle.value; + byte_offset >>>= 0; + length >>>= 0; + var createTypedArray = function (envObject, Type, size_of_element, buffer, byte_offset, length) { + var _a; + byte_offset = byte_offset >>> 0; + length = length >>> 0; + if (size_of_element > 1) { + if ((byte_offset) % (size_of_element) !== 0) { + var err = new RangeError("start offset of ".concat((_a = Type.name) !== null && _a !== void 0 ? _a : '', " should be a multiple of ").concat(size_of_element)); + err.code = 'ERR_NAPI_INVALID_TYPEDARRAY_ALIGNMENT'; + envObject.tryCatch.setError(err); + return envObject.setLastError(9 /* napi_status.napi_generic_failure */); + } + } + if (((length * size_of_element) + byte_offset) > buffer.byteLength) { + var err = new RangeError('Invalid typed array length'); + err.code = 'ERR_NAPI_INVALID_TYPEDARRAY_LENGTH'; + envObject.tryCatch.setError(err); + return envObject.setLastError(9 /* napi_status.napi_generic_failure */); + } + var out = new Type(buffer, byte_offset, length); + if (buffer === wasmMemory.buffer) { + if (!emnapiExternalMemory.wasmMemoryViewTable.has(out)) { + emnapiExternalMemory.wasmMemoryViewTable.set(out, { + Ctor: Type, + address: byte_offset, + length: length, + ownership: 1 /* ReferenceOwnership.kUserland */, + runtimeAllocated: 0 + }); + } + } + result >>>= 0; + // eslint-disable-next-line @typescript-eslint/no-unused-vars + value = emnapiCtx.addToCurrentScope(out).id; + var HEAP_DATA_VIEW = new DataView(wasmMemory.buffer), GET_HEAP_DATA_VIEW = function () { return HEAP_DATA_VIEW.buffer === wasmMemory.buffer ? HEAP_DATA_VIEW : (HEAP_DATA_VIEW = new DataView(wasmMemory.buffer)); }; + GET_HEAP_DATA_VIEW().setUint32(result, value, true); + return envObject.getReturnStatus(); + }; + if (buffer instanceof ArrayBuffer || emnapiExternalMemory.isSharedArrayBuffer(buffer)) { + switch (type) { + case 0 /* napi_typedarray_type.napi_int8_array */: + return createTypedArray(envObject, Int8Array, 1, buffer, byte_offset, length); + case 1 /* napi_typedarray_type.napi_uint8_array */: + return createTypedArray(envObject, Uint8Array, 1, buffer, byte_offset, length); + case 2 /* napi_typedarray_type.napi_uint8_clamped_array */: + return createTypedArray(envObject, Uint8ClampedArray, 1, buffer, byte_offset, length); + case 3 /* napi_typedarray_type.napi_int16_array */: + return createTypedArray(envObject, Int16Array, 2, buffer, byte_offset, length); + case 4 /* napi_typedarray_type.napi_uint16_array */: + return createTypedArray(envObject, Uint16Array, 2, buffer, byte_offset, length); + case 5 /* napi_typedarray_type.napi_int32_array */: + return createTypedArray(envObject, Int32Array, 4, buffer, byte_offset, length); + case 6 /* napi_typedarray_type.napi_uint32_array */: + return createTypedArray(envObject, Uint32Array, 4, buffer, byte_offset, length); + case 7 /* napi_typedarray_type.napi_float32_array */: + return createTypedArray(envObject, Float32Array, 4, buffer, byte_offset, length); + case 8 /* napi_typedarray_type.napi_float64_array */: + return createTypedArray(envObject, Float64Array, 8, buffer, byte_offset, length); + case 9 /* napi_typedarray_type.napi_bigint64_array */: + return createTypedArray(envObject, BigInt64Array, 8, buffer, byte_offset, length); + case 10 /* napi_typedarray_type.napi_biguint64_array */: + return createTypedArray(envObject, BigUint64Array, 8, buffer, byte_offset, length); + case 11 /* napi_typedarray_type.napi_float16_array */: + if (typeof Float16Array !== 'function') { + return envObject.setLastError(1 /* napi_status.napi_invalid_arg */); + } + return createTypedArray(envObject, Float16Array, 2, buffer, byte_offset, length); + default: + return envObject.setLastError(1 /* napi_status.napi_invalid_arg */); + } + } + else { + return envObject.setLastError(1 /* napi_status.napi_invalid_arg */); + } + } + catch (err) { + envObject.tryCatch.setError(err); + return envObject.setLastError(10 /* napi_status.napi_pending_exception */); + } + } + /** + * @__deps malloc + * @__sig ippp + */ + function napi_create_buffer(env, size, data, result) { + var _a; + // eslint-disable-next-line @typescript-eslint/no-unused-vars + var value, pointer; + if (!env) + return 1 /* napi_status.napi_invalid_arg */; + // @ts-expect-error + var envObject = emnapiCtx.envStore.get(env); + envObject.checkGCAccess(); + if (!envObject.tryCatch.isEmpty()) + return envObject.setLastError(10 /* napi_status.napi_pending_exception */); + if (!envObject.canCallIntoJs()) + return envObject.setLastError(envObject.moduleApiVersion >= 10 ? 23 /* napi_status.napi_cannot_run_js */ : 10 /* napi_status.napi_pending_exception */); + envObject.clearLastError(); + try { + if (!result) + return envObject.setLastError(1 /* napi_status.napi_invalid_arg */); + var Buffer = emnapiCtx.feature.Buffer; + if (!Buffer) { + throw emnapiCtx.createNotSupportBufferError('napi_create_buffer', ''); + } + result >>>= 0; + var buffer = void 0; + size >>>= 0; + size = size >>> 0; + var HEAP_DATA_VIEW = new DataView(wasmMemory.buffer), GET_HEAP_DATA_VIEW = function () { return HEAP_DATA_VIEW.buffer === wasmMemory.buffer ? HEAP_DATA_VIEW : (HEAP_DATA_VIEW = new DataView(wasmMemory.buffer)); }; + if (!data || (size === 0)) { + buffer = Buffer.alloc(size); + value = emnapiCtx.addToCurrentScope(buffer).id; + GET_HEAP_DATA_VIEW().setUint32(result, value, true); + } + else { + pointer = _malloc(size); + if (!pointer) + throw new Error('Out of memory'); + pointer >>>= 0; + new Uint8Array(wasmMemory.buffer).subarray(pointer, pointer + size).fill(0); + // capture Buffer.from at creation so a later refreshed view uses it + var buffer_1 = emnapiExternalMemory.getBufferFrom()(wasmMemory.buffer, pointer, size); + var viewDescriptor = { + Ctor: Buffer, + address: pointer, + length: size, + ownership: emnapiExternalMemory.registry ? 0 /* ReferenceOwnership.kRuntime */ : 1 /* ReferenceOwnership.kUserland */, + runtimeAllocated: 1 + }; + emnapiExternalMemory.wasmMemoryViewTable.set(buffer_1, viewDescriptor); + (_a = emnapiExternalMemory.registry) === null || _a === void 0 ? void 0 : _a.register(viewDescriptor, pointer); + value = emnapiCtx.addToCurrentScope(buffer_1).id; + GET_HEAP_DATA_VIEW().setUint32(result, value, true); + data >>>= 0; + GET_HEAP_DATA_VIEW().setUint32(data, pointer, true); + } + return envObject.getReturnStatus(); + } + catch (err) { + envObject.tryCatch.setError(err); + return envObject.setLastError(10 /* napi_status.napi_pending_exception */); + } + } + /** + * @__sig ippppp + */ + function napi_create_buffer_copy(env, length, data, result_data, result) { + // eslint-disable-next-line @typescript-eslint/no-unused-vars + var value; + if (!env) + return 1 /* napi_status.napi_invalid_arg */; + // @ts-expect-error + var envObject = emnapiCtx.envStore.get(env); + envObject.checkGCAccess(); + if (!envObject.tryCatch.isEmpty()) + return envObject.setLastError(10 /* napi_status.napi_pending_exception */); + if (!envObject.canCallIntoJs()) + return envObject.setLastError(envObject.moduleApiVersion >= 10 ? 23 /* napi_status.napi_cannot_run_js */ : 10 /* napi_status.napi_pending_exception */); + envObject.clearLastError(); + try { + if (!result) + return envObject.setLastError(1 /* napi_status.napi_invalid_arg */); + var Buffer = emnapiCtx.feature.Buffer; + if (!Buffer) { + throw emnapiCtx.createNotSupportBufferError('napi_create_buffer_copy', ''); + } + var arrayBuffer = emnapiCreateArrayBuffer(length, result_data, false); + var buffer = Buffer.from(arrayBuffer); + data >>>= 0; + length >>>= 0; + buffer.set(new Uint8Array(wasmMemory.buffer).subarray(data, data + length)); + value = emnapiCtx.addToCurrentScope(buffer).id; + result >>>= 0; + var HEAP_DATA_VIEW = new DataView(wasmMemory.buffer), GET_HEAP_DATA_VIEW = function () { return HEAP_DATA_VIEW.buffer === wasmMemory.buffer ? HEAP_DATA_VIEW : (HEAP_DATA_VIEW = new DataView(wasmMemory.buffer)); }; + GET_HEAP_DATA_VIEW().setUint32(result, value, true); + return envObject.getReturnStatus(); + } + catch (err) { + envObject.tryCatch.setError(err); + return envObject.setLastError(10 /* napi_status.napi_pending_exception */); + } + } + /** + * @__sig ipppppp + */ + function napi_create_external_buffer(env, length, data, finalize_cb, finalize_hint, result) { + return emnapi_create_memory_view(env, -2 /* emnapi_memory_view_type.emnapi_buffer */, data, length, finalize_cb, finalize_hint, result); + } + /** + * @__sig ippppp + */ + function node_api_create_buffer_from_arraybuffer(env, arraybuffer, byte_offset, byte_length, result) { + // eslint-disable-next-line @typescript-eslint/no-unused-vars + var value; + if (!env) + return 1 /* napi_status.napi_invalid_arg */; + // @ts-expect-error + var envObject = emnapiCtx.envStore.get(env); + envObject.checkGCAccess(); + if (!envObject.tryCatch.isEmpty()) + return envObject.setLastError(10 /* napi_status.napi_pending_exception */); + if (!envObject.canCallIntoJs()) + return envObject.setLastError(envObject.moduleApiVersion >= 10 ? 23 /* napi_status.napi_cannot_run_js */ : 10 /* napi_status.napi_pending_exception */); + envObject.clearLastError(); + try { + if (!arraybuffer) + return envObject.setLastError(1 /* napi_status.napi_invalid_arg */); + if (!result) + return envObject.setLastError(1 /* napi_status.napi_invalid_arg */); + byte_offset >>>= 0; + byte_length >>>= 0; + byte_offset = byte_offset >>> 0; + byte_length = byte_length >>> 0; + var handle = emnapiCtx.handleStore.get(arraybuffer); + if (!handle.isArrayBuffer()) { + return envObject.setLastError(1 /* napi_status.napi_invalid_arg */); + } + var buffer = handle.value; + if ((byte_length + byte_offset) > buffer.byteLength) { + var err = new RangeError('The byte offset + length is out of range'); + err.code = 'ERR_OUT_OF_RANGE'; + throw err; + } + var Buffer = emnapiCtx.feature.Buffer; + if (!Buffer) { + throw emnapiCtx.createNotSupportBufferError('node_api_create_buffer_from_arraybuffer', ''); + } + // capture Buffer.from at creation so a later refreshed view uses it + var out = emnapiExternalMemory.getBufferFrom()(buffer, byte_offset, byte_length); + if (buffer === wasmMemory.buffer) { + if (!emnapiExternalMemory.wasmMemoryViewTable.has(out)) { + emnapiExternalMemory.wasmMemoryViewTable.set(out, { + Ctor: Buffer, + address: byte_offset, + length: byte_length, + ownership: 1 /* ReferenceOwnership.kUserland */, + runtimeAllocated: 0 + }); + } + } + result >>>= 0; + // eslint-disable-next-line @typescript-eslint/no-unused-vars + value = emnapiCtx.addToCurrentScope(out).id; + var HEAP_DATA_VIEW = new DataView(wasmMemory.buffer), GET_HEAP_DATA_VIEW = function () { return HEAP_DATA_VIEW.buffer === wasmMemory.buffer ? HEAP_DATA_VIEW : (HEAP_DATA_VIEW = new DataView(wasmMemory.buffer)); }; + GET_HEAP_DATA_VIEW().setUint32(result, value, true); + return envObject.getReturnStatus(); + } + catch (err) { + envObject.tryCatch.setError(err); + return envObject.setLastError(10 /* napi_status.napi_pending_exception */); + } + } + /** + * @__sig ippppp + */ + function napi_create_dataview(env, byte_length, arraybuffer, byte_offset, result) { + if (!env) + return 1 /* napi_status.napi_invalid_arg */; + // @ts-expect-error + var envObject = emnapiCtx.envStore.get(env); + envObject.checkGCAccess(); + if (!envObject.tryCatch.isEmpty()) + return envObject.setLastError(10 /* napi_status.napi_pending_exception */); + if (!envObject.canCallIntoJs()) + return envObject.setLastError(envObject.moduleApiVersion >= 10 ? 23 /* napi_status.napi_cannot_run_js */ : 10 /* napi_status.napi_pending_exception */); + envObject.clearLastError(); + try { + if (!arraybuffer) + return envObject.setLastError(1 /* napi_status.napi_invalid_arg */); + if (!result) + return envObject.setLastError(1 /* napi_status.napi_invalid_arg */); + byte_length >>>= 0; + byte_offset >>>= 0; + byte_length = byte_length >>> 0; + byte_offset = byte_offset >>> 0; + var value = emnapiCtx.handleStore.get(arraybuffer).value; + var createDataview = function (buffer) { + if ((byte_length + byte_offset) > buffer.byteLength) { + var err = new RangeError('byte_offset + byte_length should be less than or equal to the size in bytes of the array passed in'); + err.code = 'ERR_NAPI_INVALID_DATAVIEW_ARGS'; + throw err; + } + var dataview = new DataView(buffer, byte_offset, byte_length); + if (buffer === wasmMemory.buffer) { + if (!emnapiExternalMemory.wasmMemoryViewTable.has(dataview)) { + emnapiExternalMemory.wasmMemoryViewTable.set(dataview, { + Ctor: DataView, + address: byte_offset, + length: byte_length, + ownership: 1 /* ReferenceOwnership.kUserland */, + runtimeAllocated: 0 + }); + } + } + result >>>= 0; + // eslint-disable-next-line @typescript-eslint/no-unused-vars + var v = emnapiCtx.addToCurrentScope(dataview).id; + var HEAP_DATA_VIEW = new DataView(wasmMemory.buffer), GET_HEAP_DATA_VIEW = function () { return HEAP_DATA_VIEW.buffer === wasmMemory.buffer ? HEAP_DATA_VIEW : (HEAP_DATA_VIEW = new DataView(wasmMemory.buffer)); }; + GET_HEAP_DATA_VIEW().setUint32(result, v, true); + return envObject.getReturnStatus(); + }; + if (value instanceof ArrayBuffer || emnapiExternalMemory.isSharedArrayBuffer(value)) { + return createDataview(value); + } + else { + return envObject.setLastError(1 /* napi_status.napi_invalid_arg */); + } + } + catch (err) { + envObject.tryCatch.setError(err); + return envObject.setLastError(10 /* napi_status.napi_pending_exception */); + } + } + /** + * @__sig ipppp + */ + function node_api_symbol_for(env, utf8description, length, result) { + if (!env) + return 1 /* napi_status.napi_invalid_arg */; + // @ts-expect-error + var envObject = emnapiCtx.envStore.get(env); + envObject.checkGCAccess(); + if (!result) + return envObject.setLastError(1 /* napi_status.napi_invalid_arg */); + length >>>= 0; + utf8description >>>= 0; + result >>>= 0; + var autoLength = length === -1 || length === 4294967295; + var sizelength = length >>> 0; + if (length !== 0) { + if (!utf8description) + return envObject.setLastError(1 /* napi_status.napi_invalid_arg */); + } + if (!(autoLength || (sizelength <= 2147483647))) { + return envObject.setLastError(1 /* napi_status.napi_invalid_arg */); + } + var descriptionString = emnapiString.UTF8ToString(utf8description, length); + // eslint-disable-next-line @typescript-eslint/no-unused-vars + var value = emnapiCtx.addToCurrentScope(Symbol.for(descriptionString)).id; + var HEAP_DATA_VIEW = new DataView(wasmMemory.buffer), GET_HEAP_DATA_VIEW = function () { return HEAP_DATA_VIEW.buffer === wasmMemory.buffer ? HEAP_DATA_VIEW : (HEAP_DATA_VIEW = new DataView(wasmMemory.buffer)); }; + GET_HEAP_DATA_VIEW().setUint32(result, value, true); + return envObject.clearLastError(); + } + var createMod = /*#__PURE__*/ Object.freeze({ + __proto__: null, + napi_create_array: napi_create_array, + napi_create_array_with_length: napi_create_array_with_length, + napi_create_arraybuffer: napi_create_arraybuffer, + napi_create_buffer: napi_create_buffer, + napi_create_buffer_copy: napi_create_buffer_copy, + napi_create_dataview: napi_create_dataview, + napi_create_date: napi_create_date, + napi_create_external: napi_create_external, + napi_create_external_arraybuffer: napi_create_external_arraybuffer, + napi_create_external_buffer: napi_create_external_buffer, + napi_create_object: napi_create_object, + napi_create_symbol: napi_create_symbol, + napi_create_typedarray: napi_create_typedarray, + node_api_create_buffer_from_arraybuffer: node_api_create_buffer_from_arraybuffer, + node_api_create_external_sharedarraybuffer: node_api_create_external_sharedarraybuffer, + node_api_create_object_with_properties: node_api_create_object_with_properties, + node_api_create_sharedarraybuffer: node_api_create_sharedarraybuffer, + node_api_symbol_for: node_api_symbol_for + }); + /** @__sig ipip */ + function napi_get_boolean(env, value, result) { + if (!env) + return 1 /* napi_status.napi_invalid_arg */; + // @ts-expect-error + var envObject = emnapiCtx.envStore.get(env); + envObject.checkGCAccess(); + if (!result) + return envObject.setLastError(1 /* napi_status.napi_invalid_arg */); + result >>>= 0; + // eslint-disable-next-line @typescript-eslint/no-unused-vars + var v = value === 0 ? 3 /* GlobalHandle.FALSE */ : 4 /* GlobalHandle.TRUE */; + var HEAP_DATA_VIEW = new DataView(wasmMemory.buffer), GET_HEAP_DATA_VIEW = function () { return HEAP_DATA_VIEW.buffer === wasmMemory.buffer ? HEAP_DATA_VIEW : (HEAP_DATA_VIEW = new DataView(wasmMemory.buffer)); }; + GET_HEAP_DATA_VIEW().setUint32(result, v, true); + return envObject.clearLastError(); + } + /** @__sig ipp */ + function napi_get_global(env, result) { + if (!env) + return 1 /* napi_status.napi_invalid_arg */; + // @ts-expect-error + var envObject = emnapiCtx.envStore.get(env); + envObject.checkGCAccess(); + if (!result) + return envObject.setLastError(1 /* napi_status.napi_invalid_arg */); + result >>>= 0; + // eslint-disable-next-line @typescript-eslint/no-unused-vars + var value = 5 /* GlobalHandle.GLOBAL */; + var HEAP_DATA_VIEW = new DataView(wasmMemory.buffer), GET_HEAP_DATA_VIEW = function () { return HEAP_DATA_VIEW.buffer === wasmMemory.buffer ? HEAP_DATA_VIEW : (HEAP_DATA_VIEW = new DataView(wasmMemory.buffer)); }; + GET_HEAP_DATA_VIEW().setUint32(result, value, true); + return envObject.clearLastError(); + } + /** @__sig ipp */ + function napi_get_null(env, result) { + if (!env) + return 1 /* napi_status.napi_invalid_arg */; + // @ts-expect-error + var envObject = emnapiCtx.envStore.get(env); + envObject.checkGCAccess(); + if (!result) + return envObject.setLastError(1 /* napi_status.napi_invalid_arg */); + result >>>= 0; + // eslint-disable-next-line @typescript-eslint/no-unused-vars + var value = 2 /* GlobalHandle.NULL */; + var HEAP_DATA_VIEW = new DataView(wasmMemory.buffer), GET_HEAP_DATA_VIEW = function () { return HEAP_DATA_VIEW.buffer === wasmMemory.buffer ? HEAP_DATA_VIEW : (HEAP_DATA_VIEW = new DataView(wasmMemory.buffer)); }; + GET_HEAP_DATA_VIEW().setUint32(result, value, true); + return envObject.clearLastError(); + } + /** @__sig ipp */ + function napi_get_undefined(env, result) { + if (!env) + return 1 /* napi_status.napi_invalid_arg */; + // @ts-expect-error + var envObject = emnapiCtx.envStore.get(env); + envObject.checkGCAccess(); + if (!result) + return envObject.setLastError(1 /* napi_status.napi_invalid_arg */); + result >>>= 0; + // eslint-disable-next-line @typescript-eslint/no-unused-vars + var value = 1 /* GlobalHandle.UNDEFINED */; + var HEAP_DATA_VIEW = new DataView(wasmMemory.buffer), GET_HEAP_DATA_VIEW = function () { return HEAP_DATA_VIEW.buffer === wasmMemory.buffer ? HEAP_DATA_VIEW : (HEAP_DATA_VIEW = new DataView(wasmMemory.buffer)); }; + GET_HEAP_DATA_VIEW().setUint32(result, value, true); + return envObject.clearLastError(); + } + var globalMod = /*#__PURE__*/ Object.freeze({ + __proto__: null, + napi_get_boolean: napi_get_boolean, + napi_get_global: napi_get_global, + napi_get_null: napi_get_null, + napi_get_undefined: napi_get_undefined + }); + /** @__sig ipppp */ + function napi_set_instance_data(env, data, finalize_cb, finalize_hint) { + if (!env) + return 1 /* napi_status.napi_invalid_arg */; + var envObject = emnapiCtx.envStore.get(env); + data >>>= 0; + finalize_cb >>>= 0; + finalize_hint >>>= 0; + envObject.setInstanceData(data, finalize_cb, finalize_hint); + return envObject.clearLastError(); + } + /** @__sig ipp */ + function napi_get_instance_data(env, data) { + if (!env) + return 1 /* napi_status.napi_invalid_arg */; + var envObject = emnapiCtx.envStore.get(env); + if (!data) + return envObject.setLastError(1 /* napi_status.napi_invalid_arg */); + data >>>= 0; + // eslint-disable-next-line @typescript-eslint/no-unused-vars + var value = envObject.getInstanceData(); + var HEAP_DATA_VIEW = new DataView(wasmMemory.buffer), GET_HEAP_DATA_VIEW = function () { return HEAP_DATA_VIEW.buffer === wasmMemory.buffer ? HEAP_DATA_VIEW : (HEAP_DATA_VIEW = new DataView(wasmMemory.buffer)); }; + GET_HEAP_DATA_VIEW().setUint32(data, value, true); + return envObject.clearLastError(); + } + var envMod = /*#__PURE__*/ Object.freeze({ + __proto__: null, + napi_get_instance_data: napi_get_instance_data, + napi_set_instance_data: napi_set_instance_data + }); + /** @__sig vpppp */ + function _emnapi_get_last_error_info(env, error_code, engine_error_code, engine_reserved) { + error_code >>>= 0; + engine_error_code >>>= 0; + engine_reserved >>>= 0; + var envObject = emnapiCtx.envStore.get(env); + var lastError = envObject.lastError; + // eslint-disable-next-line @typescript-eslint/no-unused-vars + var errorCode = lastError.errorCode; + // eslint-disable-next-line @typescript-eslint/no-unused-vars + var engineErrorCode = lastError.engineErrorCode >>> 0; + // eslint-disable-next-line @typescript-eslint/no-unused-vars + var engineReserved = lastError.engineReserved; + engineReserved >>>= 0; + var HEAP_DATA_VIEW = new DataView(wasmMemory.buffer), GET_HEAP_DATA_VIEW = function () { return HEAP_DATA_VIEW.buffer === wasmMemory.buffer ? HEAP_DATA_VIEW : (HEAP_DATA_VIEW = new DataView(wasmMemory.buffer)); }; + GET_HEAP_DATA_VIEW().setInt32(error_code, errorCode, true); + GET_HEAP_DATA_VIEW().setUint32(engine_error_code, engineErrorCode, true); + GET_HEAP_DATA_VIEW().setUint32(engine_reserved, engineReserved, true); + } + /** @__sig ipp */ + function napi_throw(env, error) { + if (!env) + return 1 /* napi_status.napi_invalid_arg */; + // @ts-expect-error + var envObject = emnapiCtx.envStore.get(env); + envObject.checkGCAccess(); + if (!envObject.tryCatch.isEmpty()) + return envObject.setLastError(10 /* napi_status.napi_pending_exception */); + if (!envObject.canCallIntoJs()) + return envObject.setLastError(envObject.moduleApiVersion >= 10 ? 23 /* napi_status.napi_cannot_run_js */ : 10 /* napi_status.napi_pending_exception */); + envObject.clearLastError(); + try { + if (!error) + return envObject.setLastError(1 /* napi_status.napi_invalid_arg */); + envObject.tryCatch.setError(emnapiCtx.handleStore.get(error).value); + return envObject.clearLastError(); + } + catch (err) { + envObject.tryCatch.setError(err); + return envObject.setLastError(10 /* napi_status.napi_pending_exception */); + } + } + /** @__sig ippp */ + function napi_throw_error(env, code, msg) { + if (!env) + return 1 /* napi_status.napi_invalid_arg */; + // @ts-expect-error + var envObject = emnapiCtx.envStore.get(env); + envObject.checkGCAccess(); + if (!envObject.tryCatch.isEmpty()) + return envObject.setLastError(10 /* napi_status.napi_pending_exception */); + if (!envObject.canCallIntoJs()) + return envObject.setLastError(envObject.moduleApiVersion >= 10 ? 23 /* napi_status.napi_cannot_run_js */ : 10 /* napi_status.napi_pending_exception */); + envObject.clearLastError(); + try { + if (!msg) + return envObject.setLastError(1 /* napi_status.napi_invalid_arg */); + code >>>= 0; + msg >>>= 0; + var error = new Error(emnapiString.UTF8ToString(msg, -1)); + if (code) + error.code = emnapiString.UTF8ToString(code, -1); + envObject.tryCatch.setError(error); + return envObject.clearLastError(); + } + catch (err) { + envObject.tryCatch.setError(err); + return envObject.setLastError(10 /* napi_status.napi_pending_exception */); + } + } + /** @__sig ippp */ + function napi_throw_type_error(env, code, msg) { + if (!env) + return 1 /* napi_status.napi_invalid_arg */; + // @ts-expect-error + var envObject = emnapiCtx.envStore.get(env); + envObject.checkGCAccess(); + if (!envObject.tryCatch.isEmpty()) + return envObject.setLastError(10 /* napi_status.napi_pending_exception */); + if (!envObject.canCallIntoJs()) + return envObject.setLastError(envObject.moduleApiVersion >= 10 ? 23 /* napi_status.napi_cannot_run_js */ : 10 /* napi_status.napi_pending_exception */); + envObject.clearLastError(); + try { + if (!msg) + return envObject.setLastError(1 /* napi_status.napi_invalid_arg */); + code >>>= 0; + msg >>>= 0; + var error = new TypeError(emnapiString.UTF8ToString(msg, -1)); + if (code) + error.code = emnapiString.UTF8ToString(code, -1); + envObject.tryCatch.setError(error); + return envObject.clearLastError(); + } + catch (err) { + envObject.tryCatch.setError(err); + return envObject.setLastError(10 /* napi_status.napi_pending_exception */); + } + } + /** @__sig ippp */ + function napi_throw_range_error(env, code, msg) { + if (!env) + return 1 /* napi_status.napi_invalid_arg */; + // @ts-expect-error + var envObject = emnapiCtx.envStore.get(env); + envObject.checkGCAccess(); + if (!envObject.tryCatch.isEmpty()) + return envObject.setLastError(10 /* napi_status.napi_pending_exception */); + if (!envObject.canCallIntoJs()) + return envObject.setLastError(envObject.moduleApiVersion >= 10 ? 23 /* napi_status.napi_cannot_run_js */ : 10 /* napi_status.napi_pending_exception */); + envObject.clearLastError(); + try { + if (!msg) + return envObject.setLastError(1 /* napi_status.napi_invalid_arg */); + code >>>= 0; + msg >>>= 0; + var error = new RangeError(emnapiString.UTF8ToString(msg, -1)); + if (code) + error.code = emnapiString.UTF8ToString(code, -1); + envObject.tryCatch.setError(error); + return envObject.clearLastError(); + } + catch (err) { + envObject.tryCatch.setError(err); + return envObject.setLastError(10 /* napi_status.napi_pending_exception */); + } + } + /** @__sig ippp */ + function node_api_throw_syntax_error(env, code, msg) { + if (!env) + return 1 /* napi_status.napi_invalid_arg */; + // @ts-expect-error + var envObject = emnapiCtx.envStore.get(env); + envObject.checkGCAccess(); + if (!envObject.tryCatch.isEmpty()) + return envObject.setLastError(10 /* napi_status.napi_pending_exception */); + if (!envObject.canCallIntoJs()) + return envObject.setLastError(envObject.moduleApiVersion >= 10 ? 23 /* napi_status.napi_cannot_run_js */ : 10 /* napi_status.napi_pending_exception */); + envObject.clearLastError(); + try { + if (!msg) + return envObject.setLastError(1 /* napi_status.napi_invalid_arg */); + code >>>= 0; + msg >>>= 0; + var error = new SyntaxError(emnapiString.UTF8ToString(msg, -1)); + if (code) + error.code = emnapiString.UTF8ToString(code, -1); + envObject.tryCatch.setError(error); + return envObject.clearLastError(); + } + catch (err) { + envObject.tryCatch.setError(err); + return envObject.setLastError(10 /* napi_status.napi_pending_exception */); + } + } + /** @__sig ipp */ + function napi_is_exception_pending(env, result) { + if (!env) + return 1 /* napi_status.napi_invalid_arg */; + // @ts-expect-error + var envObject = emnapiCtx.envStore.get(env); + envObject.checkGCAccess(); + if (!result) + return envObject.setLastError(1 /* napi_status.napi_invalid_arg */); + // eslint-disable-next-line @typescript-eslint/no-unused-vars + var r = envObject.tryCatch.hasCaught(); + result >>>= 0; + var HEAP_DATA_VIEW = new DataView(wasmMemory.buffer), GET_HEAP_DATA_VIEW = function () { return HEAP_DATA_VIEW.buffer === wasmMemory.buffer ? HEAP_DATA_VIEW : (HEAP_DATA_VIEW = new DataView(wasmMemory.buffer)); }; + GET_HEAP_DATA_VIEW().setInt8(result, r ? 1 : 0, true); + return envObject.clearLastError(); + } + /** @__sig ipppp */ + function napi_create_error(env, code, msg, result) { + if (!env) + return 1 /* napi_status.napi_invalid_arg */; + // @ts-expect-error + var envObject = emnapiCtx.envStore.get(env); + envObject.checkGCAccess(); + if (!msg) + return envObject.setLastError(1 /* napi_status.napi_invalid_arg */); + if (!result) + return envObject.setLastError(1 /* napi_status.napi_invalid_arg */); + var msgValue = emnapiCtx.handleStore.get(msg).value; + if (typeof msgValue !== 'string') { + return envObject.setLastError(3 /* napi_status.napi_string_expected */); + } + var error = new Error(msgValue); + if (code) { + var codeValue = emnapiCtx.handleStore.get(code).value; + if (typeof codeValue !== 'string') { + return envObject.setLastError(3 /* napi_status.napi_string_expected */); + } + error.code = codeValue; + } + result >>>= 0; + // eslint-disable-next-line @typescript-eslint/no-unused-vars + var value = emnapiCtx.addToCurrentScope(error).id; + var HEAP_DATA_VIEW = new DataView(wasmMemory.buffer), GET_HEAP_DATA_VIEW = function () { return HEAP_DATA_VIEW.buffer === wasmMemory.buffer ? HEAP_DATA_VIEW : (HEAP_DATA_VIEW = new DataView(wasmMemory.buffer)); }; + GET_HEAP_DATA_VIEW().setUint32(result, value, true); + return envObject.clearLastError(); + } + /** @__sig ipppp */ + function napi_create_type_error(env, code, msg, result) { + if (!env) + return 1 /* napi_status.napi_invalid_arg */; + // @ts-expect-error + var envObject = emnapiCtx.envStore.get(env); + envObject.checkGCAccess(); + if (!msg) + return envObject.setLastError(1 /* napi_status.napi_invalid_arg */); + if (!result) + return envObject.setLastError(1 /* napi_status.napi_invalid_arg */); + var msgValue = emnapiCtx.handleStore.get(msg).value; + if (typeof msgValue !== 'string') { + return envObject.setLastError(3 /* napi_status.napi_string_expected */); + } + var error = new TypeError(msgValue); + if (code) { + var codeValue = emnapiCtx.handleStore.get(code).value; + if (typeof codeValue !== 'string') { + return envObject.setLastError(3 /* napi_status.napi_string_expected */); + } + error.code = codeValue; + } + result >>>= 0; + // eslint-disable-next-line @typescript-eslint/no-unused-vars + var value = emnapiCtx.addToCurrentScope(error).id; + var HEAP_DATA_VIEW = new DataView(wasmMemory.buffer), GET_HEAP_DATA_VIEW = function () { return HEAP_DATA_VIEW.buffer === wasmMemory.buffer ? HEAP_DATA_VIEW : (HEAP_DATA_VIEW = new DataView(wasmMemory.buffer)); }; + GET_HEAP_DATA_VIEW().setUint32(result, value, true); + return envObject.clearLastError(); + } + /** @__sig ipppp */ + function napi_create_range_error(env, code, msg, result) { + if (!env) + return 1 /* napi_status.napi_invalid_arg */; + // @ts-expect-error + var envObject = emnapiCtx.envStore.get(env); + envObject.checkGCAccess(); + if (!msg) + return envObject.setLastError(1 /* napi_status.napi_invalid_arg */); + if (!result) + return envObject.setLastError(1 /* napi_status.napi_invalid_arg */); + var msgValue = emnapiCtx.handleStore.get(msg).value; + if (typeof msgValue !== 'string') { + return envObject.setLastError(3 /* napi_status.napi_string_expected */); + } + var error = new RangeError(msgValue); + if (code) { + var codeValue = emnapiCtx.handleStore.get(code).value; + if (typeof codeValue !== 'string') { + return envObject.setLastError(3 /* napi_status.napi_string_expected */); + } + error.code = codeValue; + } + result >>>= 0; + // eslint-disable-next-line @typescript-eslint/no-unused-vars + var value = emnapiCtx.addToCurrentScope(error).id; + var HEAP_DATA_VIEW = new DataView(wasmMemory.buffer), GET_HEAP_DATA_VIEW = function () { return HEAP_DATA_VIEW.buffer === wasmMemory.buffer ? HEAP_DATA_VIEW : (HEAP_DATA_VIEW = new DataView(wasmMemory.buffer)); }; + GET_HEAP_DATA_VIEW().setUint32(result, value, true); + return envObject.clearLastError(); + } + /** @__sig ipppp */ + function node_api_create_syntax_error(env, code, msg, result) { + if (!env) + return 1 /* napi_status.napi_invalid_arg */; + // @ts-expect-error + var envObject = emnapiCtx.envStore.get(env); + envObject.checkGCAccess(); + if (!msg) + return envObject.setLastError(1 /* napi_status.napi_invalid_arg */); + if (!result) + return envObject.setLastError(1 /* napi_status.napi_invalid_arg */); + var msgValue = emnapiCtx.handleStore.get(msg).value; + if (typeof msgValue !== 'string') { + return envObject.setLastError(3 /* napi_status.napi_string_expected */); + } + var error = new SyntaxError(msgValue); + if (code) { + var codeValue = emnapiCtx.handleStore.get(code).value; + if (typeof codeValue !== 'string') { + return envObject.setLastError(3 /* napi_status.napi_string_expected */); + } + error.code = codeValue; + } + result >>>= 0; + // eslint-disable-next-line @typescript-eslint/no-unused-vars + var value = emnapiCtx.addToCurrentScope(error).id; + var HEAP_DATA_VIEW = new DataView(wasmMemory.buffer), GET_HEAP_DATA_VIEW = function () { return HEAP_DATA_VIEW.buffer === wasmMemory.buffer ? HEAP_DATA_VIEW : (HEAP_DATA_VIEW = new DataView(wasmMemory.buffer)); }; + GET_HEAP_DATA_VIEW().setUint32(result, value, true); + return envObject.clearLastError(); + } + /** @__sig ipp */ + function napi_get_and_clear_last_exception(env, result) { + if (!env) + return 1 /* napi_status.napi_invalid_arg */; + // @ts-expect-error + var envObject = emnapiCtx.envStore.get(env); + envObject.checkGCAccess(); + if (!result) + return envObject.setLastError(1 /* napi_status.napi_invalid_arg */); + result >>>= 0; + var HEAP_DATA_VIEW = new DataView(wasmMemory.buffer), GET_HEAP_DATA_VIEW = function () { return HEAP_DATA_VIEW.buffer === wasmMemory.buffer ? HEAP_DATA_VIEW : (HEAP_DATA_VIEW = new DataView(wasmMemory.buffer)); }; + if (!envObject.tryCatch.hasCaught()) { + GET_HEAP_DATA_VIEW().setUint32(result, 1, true); // ID_UNDEFINED + return envObject.clearLastError(); + } + else { + var err = envObject.tryCatch.exception(); + // eslint-disable-next-line @typescript-eslint/no-unused-vars + var value = envObject.ensureHandleId(err); + GET_HEAP_DATA_VIEW().setUint32(result, value, true); + envObject.tryCatch.reset(); + } + return envObject.clearLastError(); + } + /** @__sig vpppp */ + function napi_fatal_error(location, location_len, message, message_len) { + location >>>= 0; + location_len >>>= 0; + message >>>= 0; + message_len >>>= 0; + var locationStr = emnapiString.UTF8ToString(location, location_len); + var messageStr = emnapiString.UTF8ToString(message, message_len); + if (emnapiNodeBinding) { + emnapiNodeBinding.napi.fatalError(locationStr, messageStr); + } + else { + abort('FATAL ERROR: ' + locationStr + ' ' + messageStr); + } + } + /** @__sig ipp */ + function napi_fatal_exception(env, err) { + if (!env) + return 1 /* napi_status.napi_invalid_arg */; + // @ts-expect-error + var envObject = emnapiCtx.envStore.get(env); + envObject.checkGCAccess(); + if (!envObject.tryCatch.isEmpty()) + return envObject.setLastError(10 /* napi_status.napi_pending_exception */); + if (!envObject.canCallIntoJs()) + return envObject.setLastError(envObject.moduleApiVersion >= 10 ? 23 /* napi_status.napi_cannot_run_js */ : 10 /* napi_status.napi_pending_exception */); + envObject.clearLastError(); + try { + if (!err) + return envObject.setLastError(1 /* napi_status.napi_invalid_arg */); + var error = envObject.ctx.handleStore.get(err); + try { + envObject.triggerFatalException(error.value); + } + catch (_) { + return envObject.setLastError(9 /* napi_status.napi_generic_failure */); + } + return envObject.clearLastError(); + } + catch (err) { + envObject.tryCatch.setError(err); + return envObject.setLastError(10 /* napi_status.napi_pending_exception */); + } + } + var errorMod = /*#__PURE__*/ Object.freeze({ + __proto__: null, + _emnapi_get_last_error_info: _emnapi_get_last_error_info, + napi_create_error: napi_create_error, + napi_create_range_error: napi_create_range_error, + napi_create_type_error: napi_create_type_error, + napi_fatal_error: napi_fatal_error, + napi_fatal_exception: napi_fatal_exception, + napi_get_and_clear_last_exception: napi_get_and_clear_last_exception, + napi_is_exception_pending: napi_is_exception_pending, + napi_throw: napi_throw, + napi_throw_error: napi_throw_error, + napi_throw_range_error: napi_throw_range_error, + napi_throw_type_error: napi_throw_type_error, + node_api_create_syntax_error: node_api_create_syntax_error, + node_api_throw_syntax_error: node_api_throw_syntax_error + }); + /** @__sig ipppppp */ + function _emnapi_create_function(env, utf8name, length, cb, data, result) { + length >>>= 0; + var envObject = emnapiCtx.envStore.get(env); + var fresult = emnapiCreateFunction(envObject, utf8name, length, cb, data); + if (fresult.status !== 0 /* napi_status.napi_ok */) + return envObject.setLastError(fresult.status); + var f = fresult.f; + var valueHandle = emnapiCtx.addToCurrentScope(f); + result >>>= 0; + // eslint-disable-next-line @typescript-eslint/no-unused-vars + var value = valueHandle.id; + var HEAP_DATA_VIEW = new DataView(wasmMemory.buffer), GET_HEAP_DATA_VIEW = function () { return HEAP_DATA_VIEW.buffer === wasmMemory.buffer ? HEAP_DATA_VIEW : (HEAP_DATA_VIEW = new DataView(wasmMemory.buffer)); }; + GET_HEAP_DATA_VIEW().setUint32(result, value, true); + return envObject.getReturnStatus(); + } + /** @__sig ipppppp */ + function napi_create_function(env, utf8name, length, cb, data, result) { + if (!env) + return 1 /* napi_status.napi_invalid_arg */; + // @ts-expect-error + var envObject = emnapiCtx.envStore.get(env); + envObject.checkGCAccess(); + if (!envObject.tryCatch.isEmpty()) + return envObject.setLastError(10 /* napi_status.napi_pending_exception */); + if (!envObject.canCallIntoJs()) + return envObject.setLastError(envObject.moduleApiVersion >= 10 ? 23 /* napi_status.napi_cannot_run_js */ : 10 /* napi_status.napi_pending_exception */); + envObject.clearLastError(); + try { + if (!result) + return envObject.setLastError(1 /* napi_status.napi_invalid_arg */); + if (!cb) + return envObject.setLastError(1 /* napi_status.napi_invalid_arg */); + return _emnapi_create_function(env, utf8name, length, cb, data, result); + } + catch (err) { + envObject.tryCatch.setError(err); + return envObject.setLastError(10 /* napi_status.napi_pending_exception */); + } + } + /** @__sig ipppppp */ + function napi_get_cb_info(env, cbinfo, argc, argv, this_arg, data) { + if (!env) + return 1 /* napi_status.napi_invalid_arg */; + var envObject = emnapiCtx.envStore.get(env); + if (!cbinfo) + return envObject.setLastError(1 /* napi_status.napi_invalid_arg */); + var cbinfoValue = emnapiCtx.scopeStore.get(cbinfo).callbackInfo; + argc >>>= 0; + argv >>>= 0; + var HEAP_DATA_VIEW = new DataView(wasmMemory.buffer), GET_HEAP_DATA_VIEW = function () { return HEAP_DATA_VIEW.buffer === wasmMemory.buffer ? HEAP_DATA_VIEW : (HEAP_DATA_VIEW = new DataView(wasmMemory.buffer)); }; + if (argv) { + if (!argc) + return envObject.setLastError(1 /* napi_status.napi_invalid_arg */); + var argcValue = GET_HEAP_DATA_VIEW().getUint32(argc, true); + argcValue >>>= 0; + var len = cbinfoValue.args.length; + var arrlen = argcValue < len ? argcValue : len; + var i = 0; + for (; i < arrlen; i++) { + // eslint-disable-next-line @typescript-eslint/no-unused-vars + var argVal = envObject.ensureHandleId(cbinfoValue.args[i]); + GET_HEAP_DATA_VIEW().setUint32(argv + i * 4, argVal, true); + } + if (i < argcValue) { + for (; i < argcValue; i++) { + GET_HEAP_DATA_VIEW().setUint32(argv + i * 4, 1, true); + } + } + } + if (argc) { + GET_HEAP_DATA_VIEW().setUint32(argc, cbinfoValue.args.length, true); + } + if (this_arg) { + this_arg >>>= 0; + // eslint-disable-next-line @typescript-eslint/no-unused-vars + var v = envObject.ensureHandleId(cbinfoValue.thiz); + GET_HEAP_DATA_VIEW().setUint32(this_arg, v, true); + } + if (data) { + data >>>= 0; + GET_HEAP_DATA_VIEW().setUint32(data, cbinfoValue.data, true); + } + return envObject.clearLastError(); + } + /** @__sig ipppppp */ + function napi_call_function(env, recv, func, argc, argv, result) { + var i = 0; + // eslint-disable-next-line @typescript-eslint/no-unused-vars + var v; + if (!env) + return 1 /* napi_status.napi_invalid_arg */; + // @ts-expect-error + var envObject = emnapiCtx.envStore.get(env); + envObject.checkGCAccess(); + if (!envObject.tryCatch.isEmpty()) + return envObject.setLastError(10 /* napi_status.napi_pending_exception */); + if (!envObject.canCallIntoJs()) + return envObject.setLastError(envObject.moduleApiVersion >= 10 ? 23 /* napi_status.napi_cannot_run_js */ : 10 /* napi_status.napi_pending_exception */); + envObject.clearLastError(); + try { + if (!recv) + return envObject.setLastError(1 /* napi_status.napi_invalid_arg */); + argc >>>= 0; + argv >>>= 0; + result >>>= 0; + argc = argc >>> 0; + if (argc > 0) { + if (!argv) + return envObject.setLastError(1 /* napi_status.napi_invalid_arg */); + } + var v8recv = emnapiCtx.handleStore.get(recv).value; + if (!func) + return envObject.setLastError(1 /* napi_status.napi_invalid_arg */); + var v8func = emnapiCtx.handleStore.get(func).value; + if (typeof v8func !== 'function') + return envObject.setLastError(1 /* napi_status.napi_invalid_arg */); + var args = []; + var HEAP_DATA_VIEW = new DataView(wasmMemory.buffer), GET_HEAP_DATA_VIEW = function () { return HEAP_DATA_VIEW.buffer === wasmMemory.buffer ? HEAP_DATA_VIEW : (HEAP_DATA_VIEW = new DataView(wasmMemory.buffer)); }; + for (; i < argc; i++) { + var argVal = GET_HEAP_DATA_VIEW().getUint32(argv + i * 4, true); + args.push(emnapiCtx.handleStore.get(argVal).value); + } + var ret = v8func.apply(v8recv, args); + if (result) { + // resolving v BEFORE the write matters: the store target is evaluated + // before the RHS, so an RHS running user JS could otherwise write + // through a stale heap view after a growth + v = envObject.ensureHandleId(ret); + GET_HEAP_DATA_VIEW().setUint32(result, v, true); + } + return envObject.clearLastError(); + } + catch (err) { + envObject.tryCatch.setError(err); + return envObject.setLastError(10 /* napi_status.napi_pending_exception */); + } + } + /** @__sig ippppp */ + function napi_new_instance(env, constructor, argc, argv, result) { + var i; + // eslint-disable-next-line @typescript-eslint/no-unused-vars + var v; + if (!env) + return 1 /* napi_status.napi_invalid_arg */; + // @ts-expect-error + var envObject = emnapiCtx.envStore.get(env); + envObject.checkGCAccess(); + if (!envObject.tryCatch.isEmpty()) + return envObject.setLastError(10 /* napi_status.napi_pending_exception */); + if (!envObject.canCallIntoJs()) + return envObject.setLastError(envObject.moduleApiVersion >= 10 ? 23 /* napi_status.napi_cannot_run_js */ : 10 /* napi_status.napi_pending_exception */); + envObject.clearLastError(); + try { + if (!constructor) + return envObject.setLastError(1 /* napi_status.napi_invalid_arg */); + argc >>>= 0; + argv >>>= 0; + result >>>= 0; + argc = argc >>> 0; + if (argc > 0) { + if (!argv) + return envObject.setLastError(1 /* napi_status.napi_invalid_arg */); + } + if (!result) + return envObject.setLastError(1 /* napi_status.napi_invalid_arg */); + var Ctor = emnapiCtx.handleStore.get(constructor).value; + if (typeof Ctor !== 'function') + return envObject.setLastError(1 /* napi_status.napi_invalid_arg */); + var ret = void 0; + var HEAP_DATA_VIEW = new DataView(wasmMemory.buffer), GET_HEAP_DATA_VIEW = function () { return HEAP_DATA_VIEW.buffer === wasmMemory.buffer ? HEAP_DATA_VIEW : (HEAP_DATA_VIEW = new DataView(wasmMemory.buffer)); }; + if (emnapiCtx.feature.supportReflect) { + var argList = Array(argc); + for (i = 0; i < argc; i++) { + var argVal = GET_HEAP_DATA_VIEW().getUint32(argv + i * 4, true); + argList[i] = emnapiCtx.handleStore.get(argVal).value; + } + ret = Reflect.construct(Ctor, argList, Ctor); + } + else { + var args = Array(argc + 1); + args[0] = undefined; + for (i = 0; i < argc; i++) { + var argVal = GET_HEAP_DATA_VIEW().getUint32(argv + i * 4, true); + args[i + 1] = emnapiCtx.handleStore.get(argVal).value; + } + var BoundCtor = Ctor.bind.apply(Ctor, args); + ret = new BoundCtor(); + } + if (result) { + // see napi_call_function: resolve v before the write + v = envObject.ensureHandleId(ret); + GET_HEAP_DATA_VIEW().setUint32(result, v, true); + } + return envObject.getReturnStatus(); + } + catch (err) { + envObject.tryCatch.setError(err); + return envObject.setLastError(10 /* napi_status.napi_pending_exception */); + } + } + /** @__sig ippp */ + function napi_get_new_target(env, cbinfo, result) { + if (!env) + return 1 /* napi_status.napi_invalid_arg */; + // @ts-expect-error + var envObject = emnapiCtx.envStore.get(env); + envObject.checkGCAccess(); + if (!cbinfo) + return envObject.setLastError(1 /* napi_status.napi_invalid_arg */); + if (!result) + return envObject.setLastError(1 /* napi_status.napi_invalid_arg */); + result >>>= 0; + var cbinfoValue = emnapiCtx.scopeStore.get(cbinfo).callbackInfo; + var thiz = cbinfoValue.thiz, fn = cbinfoValue.fn; + // eslint-disable-next-line @typescript-eslint/prefer-optional-chain, @typescript-eslint/no-unused-vars + var value = thiz == null || thiz.constructor == null + ? 0 + : thiz instanceof fn + ? envObject.ensureHandleId(thiz.constructor) + : 0; + var HEAP_DATA_VIEW = new DataView(wasmMemory.buffer), GET_HEAP_DATA_VIEW = function () { return HEAP_DATA_VIEW.buffer === wasmMemory.buffer ? HEAP_DATA_VIEW : (HEAP_DATA_VIEW = new DataView(wasmMemory.buffer)); }; + GET_HEAP_DATA_VIEW().setUint32(result, value, true); + return envObject.clearLastError(); + } + var functionMod = /*#__PURE__*/ Object.freeze({ + __proto__: null, + _emnapi_create_function: _emnapi_create_function, + napi_call_function: napi_call_function, + napi_create_function: napi_create_function, + napi_get_cb_info: napi_get_cb_info, + napi_get_new_target: napi_get_new_target, + napi_new_instance: napi_new_instance + }); + /** @__sig ipp */ + function napi_open_handle_scope(env, result) { + if (!env) + return 1 /* napi_status.napi_invalid_arg */; + // @ts-expect-error + var envObject = emnapiCtx.envStore.get(env); + envObject.checkGCAccess(); + if (!result) + return envObject.setLastError(1 /* napi_status.napi_invalid_arg */); + // eslint-disable-next-line @typescript-eslint/no-unused-vars + var scope = emnapiCtx.openScope(envObject); + result >>>= 0; + var HEAP_DATA_VIEW = new DataView(wasmMemory.buffer), GET_HEAP_DATA_VIEW = function () { return HEAP_DATA_VIEW.buffer === wasmMemory.buffer ? HEAP_DATA_VIEW : (HEAP_DATA_VIEW = new DataView(wasmMemory.buffer)); }; + GET_HEAP_DATA_VIEW().setUint32(result, scope.id, true); + return envObject.clearLastError(); + } + /** @__sig ipp */ + function napi_close_handle_scope(env, scope) { + if (!env) + return 1 /* napi_status.napi_invalid_arg */; + // @ts-expect-error + var envObject = emnapiCtx.envStore.get(env); + envObject.checkGCAccess(); + if (!scope) + return envObject.setLastError(1 /* napi_status.napi_invalid_arg */); + if ((envObject.openHandleScopes === 0)) { + return 13 /* napi_status.napi_handle_scope_mismatch */; + } + emnapiCtx.closeScope(envObject); + return envObject.clearLastError(); + } + /** @__sig ipp */ + function napi_open_escapable_handle_scope(env, result) { + if (!env) + return 1 /* napi_status.napi_invalid_arg */; + // @ts-expect-error + var envObject = emnapiCtx.envStore.get(env); + envObject.checkGCAccess(); + if (!result) + return envObject.setLastError(1 /* napi_status.napi_invalid_arg */); + // eslint-disable-next-line @typescript-eslint/no-unused-vars + var scope = emnapiCtx.openScope(envObject); + result >>>= 0; + var HEAP_DATA_VIEW = new DataView(wasmMemory.buffer), GET_HEAP_DATA_VIEW = function () { return HEAP_DATA_VIEW.buffer === wasmMemory.buffer ? HEAP_DATA_VIEW : (HEAP_DATA_VIEW = new DataView(wasmMemory.buffer)); }; + GET_HEAP_DATA_VIEW().setUint32(result, scope.id, true); + return envObject.clearLastError(); + } + /** @__sig ipp */ + function napi_close_escapable_handle_scope(env, scope) { + if (!env) + return 1 /* napi_status.napi_invalid_arg */; + // @ts-expect-error + var envObject = emnapiCtx.envStore.get(env); + envObject.checkGCAccess(); + if (!scope) + return envObject.setLastError(1 /* napi_status.napi_invalid_arg */); + if ((envObject.openHandleScopes === 0)) { + return 13 /* napi_status.napi_handle_scope_mismatch */; + } + emnapiCtx.closeScope(envObject); + return envObject.clearLastError(); + } + /** @__sig ipppp */ + function napi_escape_handle(env, scope, escapee, result) { + if (!env) + return 1 /* napi_status.napi_invalid_arg */; + // @ts-expect-error + var envObject = emnapiCtx.envStore.get(env); + envObject.checkGCAccess(); + if (!scope) + return envObject.setLastError(1 /* napi_status.napi_invalid_arg */); + if (!escapee) + return envObject.setLastError(1 /* napi_status.napi_invalid_arg */); + if (!result) + return envObject.setLastError(1 /* napi_status.napi_invalid_arg */); + var scopeObject = emnapiCtx.scopeStore.get(scope); + if (!scopeObject.escapeCalled()) { + escapee >>>= 0; + result >>>= 0; + var newHandle = scopeObject.escape(escapee); + // eslint-disable-next-line @typescript-eslint/no-unused-vars + var value = newHandle ? newHandle.id : 0; + var HEAP_DATA_VIEW = new DataView(wasmMemory.buffer), GET_HEAP_DATA_VIEW = function () { return HEAP_DATA_VIEW.buffer === wasmMemory.buffer ? HEAP_DATA_VIEW : (HEAP_DATA_VIEW = new DataView(wasmMemory.buffer)); }; + GET_HEAP_DATA_VIEW().setUint32(result, value, true); + return envObject.clearLastError(); + } + return envObject.setLastError(12 /* napi_status.napi_escape_called_twice */); + } + /** @__sig ippip */ + function napi_create_reference(env, value, initial_refcount, result) { + if (!env) + return 1 /* napi_status.napi_invalid_arg */; + // @ts-expect-error + var envObject = emnapiCtx.envStore.get(env); + envObject.checkGCAccess(); + if (!value) + return envObject.setLastError(1 /* napi_status.napi_invalid_arg */); + if (!result) + return envObject.setLastError(1 /* napi_status.napi_invalid_arg */); + var handle = emnapiCtx.handleStore.get(value); + if (envObject.moduleApiVersion < 10) { + if (!(handle.isObject() || handle.isFunction() || handle.isSymbol())) { + return envObject.setLastError(1 /* napi_status.napi_invalid_arg */); + } + } + // eslint-disable-next-line @typescript-eslint/no-unused-vars + var ref = emnapiCtx.createReference(envObject, handle.id, initial_refcount >>> 0, 1 /* ReferenceOwnership.kUserland */); + result >>>= 0; + var HEAP_DATA_VIEW = new DataView(wasmMemory.buffer), GET_HEAP_DATA_VIEW = function () { return HEAP_DATA_VIEW.buffer === wasmMemory.buffer ? HEAP_DATA_VIEW : (HEAP_DATA_VIEW = new DataView(wasmMemory.buffer)); }; + GET_HEAP_DATA_VIEW().setUint32(result, ref.id, true); + return envObject.clearLastError(); + } + /** @__sig ipp */ + function napi_delete_reference(env, ref) { + if (!env) + return 1 /* napi_status.napi_invalid_arg */; + var envObject = emnapiCtx.envStore.get(env); + if (!ref) + return envObject.setLastError(1 /* napi_status.napi_invalid_arg */); + emnapiCtx.refStore.get(ref).dispose(); + return envObject.clearLastError(); + } + /** @__sig ippp */ + function napi_reference_ref(env, ref, result) { + if (!env) + return 1 /* napi_status.napi_invalid_arg */; + // @ts-expect-error + var envObject = emnapiCtx.envStore.get(env); + envObject.checkGCAccess(); + if (!ref) + return envObject.setLastError(1 /* napi_status.napi_invalid_arg */); + // eslint-disable-next-line @typescript-eslint/no-unused-vars + var count = emnapiCtx.refStore.get(ref).ref(); + if (result) { + result >>>= 0; + var HEAP_DATA_VIEW = new DataView(wasmMemory.buffer), GET_HEAP_DATA_VIEW = function () { return HEAP_DATA_VIEW.buffer === wasmMemory.buffer ? HEAP_DATA_VIEW : (HEAP_DATA_VIEW = new DataView(wasmMemory.buffer)); }; + GET_HEAP_DATA_VIEW().setUint32(result, count, true); + } + return envObject.clearLastError(); + } + /** @__sig ippp */ + function napi_reference_unref(env, ref, result) { + if (!env) + return 1 /* napi_status.napi_invalid_arg */; + // @ts-expect-error + var envObject = emnapiCtx.envStore.get(env); + envObject.checkGCAccess(); + if (!ref) + return envObject.setLastError(1 /* napi_status.napi_invalid_arg */); + var reference = emnapiCtx.refStore.get(ref); + var refcount = reference.refcount(); + if (refcount === 0) { + return envObject.setLastError(9 /* napi_status.napi_generic_failure */); + } + // eslint-disable-next-line @typescript-eslint/no-unused-vars + var count = reference.unref(); + if (result) { + result >>>= 0; + var HEAP_DATA_VIEW = new DataView(wasmMemory.buffer), GET_HEAP_DATA_VIEW = function () { return HEAP_DATA_VIEW.buffer === wasmMemory.buffer ? HEAP_DATA_VIEW : (HEAP_DATA_VIEW = new DataView(wasmMemory.buffer)); }; + GET_HEAP_DATA_VIEW().setUint32(result, count, true); + } + return envObject.clearLastError(); + } + /** @__sig ippp */ + function napi_get_reference_value(env, ref, result) { + if (!env) + return 1 /* napi_status.napi_invalid_arg */; + // @ts-expect-error + var envObject = emnapiCtx.envStore.get(env); + envObject.checkGCAccess(); + if (!ref) + return envObject.setLastError(1 /* napi_status.napi_invalid_arg */); + if (!result) + return envObject.setLastError(1 /* napi_status.napi_invalid_arg */); + var reference = emnapiCtx.refStore.get(ref); + // eslint-disable-next-line @typescript-eslint/no-unused-vars + var handleId = reference.get(envObject); + result >>>= 0; + var HEAP_DATA_VIEW = new DataView(wasmMemory.buffer), GET_HEAP_DATA_VIEW = function () { return HEAP_DATA_VIEW.buffer === wasmMemory.buffer ? HEAP_DATA_VIEW : (HEAP_DATA_VIEW = new DataView(wasmMemory.buffer)); }; + GET_HEAP_DATA_VIEW().setUint32(result, handleId, true); + return envObject.clearLastError(); + } + /** @__sig ippp */ + function napi_add_env_cleanup_hook(env, fun, arg) { + if (!env) + return 1 /* napi_status.napi_invalid_arg */; + var envObject = emnapiCtx.envStore.get(env); + if (!fun) + return envObject.setLastError(1 /* napi_status.napi_invalid_arg */); + fun >>>= 0; + arg >>>= 0; + emnapiCtx.addCleanupHook(envObject, fun, arg); + return 0 /* napi_status.napi_ok */; + } + /** @__sig ippp */ + function napi_remove_env_cleanup_hook(env, fun, arg) { + if (!env) + return 1 /* napi_status.napi_invalid_arg */; + var envObject = emnapiCtx.envStore.get(env); + if (!fun) + return envObject.setLastError(1 /* napi_status.napi_invalid_arg */); + fun >>>= 0; + arg >>>= 0; + emnapiCtx.removeCleanupHook(envObject, fun, arg); + return 0 /* napi_status.napi_ok */; + } + /** @__sig vp */ + function _emnapi_env_ref(env) { + var envObject = emnapiCtx.envStore.get(env); + envObject.ref(); + } + /** @__sig vp */ + function _emnapi_env_unref(env) { + var envObject = emnapiCtx.envStore.get(env); + envObject.unref(); + } + var lifeMod = /*#__PURE__*/ Object.freeze({ + __proto__: null, + _emnapi_env_ref: _emnapi_env_ref, + _emnapi_env_unref: _emnapi_env_unref, + napi_add_env_cleanup_hook: napi_add_env_cleanup_hook, + napi_close_escapable_handle_scope: napi_close_escapable_handle_scope, + napi_close_handle_scope: napi_close_handle_scope, + napi_create_reference: napi_create_reference, + napi_delete_reference: napi_delete_reference, + napi_escape_handle: napi_escape_handle, + napi_get_reference_value: napi_get_reference_value, + napi_open_escapable_handle_scope: napi_open_escapable_handle_scope, + napi_open_handle_scope: napi_open_handle_scope, + napi_reference_ref: napi_reference_ref, + napi_reference_unref: napi_reference_unref, + napi_remove_env_cleanup_hook: napi_remove_env_cleanup_hook + }); + /** @__sig ippi */ + function _emnapi_get_filename(env, buf, len) { + var envObject = emnapiCtx.envStore.get(env); + var filename = envObject.filename; + if (!buf) { + return emnapiString.lengthBytesUTF8(filename); + } + return emnapiString.stringToUTF8(filename, buf, len); + } + var miscellaneousMod = /*#__PURE__*/ Object.freeze({ + __proto__: null, + _emnapi_get_filename: _emnapi_get_filename + }); + /** @__sig ippp */ + function napi_create_promise(env, deferred, promise) { + // eslint-disable-next-line @typescript-eslint/no-unused-vars + var deferredObjectId, value; + if (!env) + return 1 /* napi_status.napi_invalid_arg */; + // @ts-expect-error + var envObject = emnapiCtx.envStore.get(env); + envObject.checkGCAccess(); + if (!envObject.tryCatch.isEmpty()) + return envObject.setLastError(10 /* napi_status.napi_pending_exception */); + if (!envObject.canCallIntoJs()) + return envObject.setLastError(envObject.moduleApiVersion >= 10 ? 23 /* napi_status.napi_cannot_run_js */ : 10 /* napi_status.napi_pending_exception */); + envObject.clearLastError(); + try { + if (!deferred) + return envObject.setLastError(1 /* napi_status.napi_invalid_arg */); + if (!promise) + return envObject.setLastError(1 /* napi_status.napi_invalid_arg */); + var HEAP_DATA_VIEW = new DataView(wasmMemory.buffer), GET_HEAP_DATA_VIEW = function () { return HEAP_DATA_VIEW.buffer === wasmMemory.buffer ? HEAP_DATA_VIEW : (HEAP_DATA_VIEW = new DataView(wasmMemory.buffer)); }; + var p = new Promise(function (resolve, reject) { + var deferredObject = emnapiCtx.createDeferred({ resolve: resolve, reject: reject }); + deferredObjectId = deferredObject.id; + deferred >>>= 0; + GET_HEAP_DATA_VIEW().setUint32(deferred, deferredObjectId, true); + }); + promise >>>= 0; + // eslint-disable-next-line @typescript-eslint/no-unused-vars + value = emnapiCtx.addToCurrentScope(p).id; + GET_HEAP_DATA_VIEW().setUint32(promise, value, true); + return envObject.getReturnStatus(); + } + catch (err) { + envObject.tryCatch.setError(err); + return envObject.setLastError(10 /* napi_status.napi_pending_exception */); + } + } + /** @__sig ippp */ + function napi_resolve_deferred(env, deferred, resolution) { + if (!env) + return 1 /* napi_status.napi_invalid_arg */; + // @ts-expect-error + var envObject = emnapiCtx.envStore.get(env); + envObject.checkGCAccess(); + if (!envObject.tryCatch.isEmpty()) + return envObject.setLastError(10 /* napi_status.napi_pending_exception */); + if (!envObject.canCallIntoJs()) + return envObject.setLastError(envObject.moduleApiVersion >= 10 ? 23 /* napi_status.napi_cannot_run_js */ : 10 /* napi_status.napi_pending_exception */); + envObject.clearLastError(); + try { + if (!deferred) + return envObject.setLastError(1 /* napi_status.napi_invalid_arg */); + if (!resolution) + return envObject.setLastError(1 /* napi_status.napi_invalid_arg */); + var deferredObject = emnapiCtx.deferredStore.get(deferred); + deferredObject.resolve(emnapiCtx.handleStore.get(resolution).value); + return envObject.getReturnStatus(); + } + catch (err) { + envObject.tryCatch.setError(err); + return envObject.setLastError(10 /* napi_status.napi_pending_exception */); + } + } + /** @__sig ippp */ + function napi_reject_deferred(env, deferred, resolution) { + if (!env) + return 1 /* napi_status.napi_invalid_arg */; + // @ts-expect-error + var envObject = emnapiCtx.envStore.get(env); + envObject.checkGCAccess(); + if (!envObject.tryCatch.isEmpty()) + return envObject.setLastError(10 /* napi_status.napi_pending_exception */); + if (!envObject.canCallIntoJs()) + return envObject.setLastError(envObject.moduleApiVersion >= 10 ? 23 /* napi_status.napi_cannot_run_js */ : 10 /* napi_status.napi_pending_exception */); + envObject.clearLastError(); + try { + if (!deferred) + return envObject.setLastError(1 /* napi_status.napi_invalid_arg */); + if (!resolution) + return envObject.setLastError(1 /* napi_status.napi_invalid_arg */); + var deferredObject = emnapiCtx.deferredStore.get(deferred); + deferredObject.reject(emnapiCtx.handleStore.get(resolution).value); + return envObject.getReturnStatus(); + } + catch (err) { + envObject.tryCatch.setError(err); + return envObject.setLastError(10 /* napi_status.napi_pending_exception */); + } + } + /** @__sig ippp */ + function napi_is_promise(env, value, is_promise) { + if (!env) + return 1 /* napi_status.napi_invalid_arg */; + // @ts-expect-error + var envObject = emnapiCtx.envStore.get(env); + envObject.checkGCAccess(); + if (!value) + return envObject.setLastError(1 /* napi_status.napi_invalid_arg */); + if (!is_promise) + return envObject.setLastError(1 /* napi_status.napi_invalid_arg */); + var h = emnapiCtx.handleStore.get(value); + is_promise >>>= 0; + // eslint-disable-next-line @typescript-eslint/no-unused-vars + var r = h.isPromise() ? 1 : 0; + var HEAP_DATA_VIEW = new DataView(wasmMemory.buffer), GET_HEAP_DATA_VIEW = function () { return HEAP_DATA_VIEW.buffer === wasmMemory.buffer ? HEAP_DATA_VIEW : (HEAP_DATA_VIEW = new DataView(wasmMemory.buffer)); }; + GET_HEAP_DATA_VIEW().setInt8(is_promise, r, true); + return envObject.clearLastError(); + } + var promiseMod = /*#__PURE__*/ Object.freeze({ + __proto__: null, + napi_create_promise: napi_create_promise, + napi_is_promise: napi_is_promise, + napi_reject_deferred: napi_reject_deferred, + napi_resolve_deferred: napi_resolve_deferred + }); + /** @__sig ippiiip */ + function napi_get_all_property_names(env, object, key_mode, key_filter, key_conversion, result) { + // eslint-disable-next-line @typescript-eslint/no-unused-vars + var value; + if (!env) + return 1 /* napi_status.napi_invalid_arg */; + // @ts-expect-error + var envObject = emnapiCtx.envStore.get(env); + envObject.checkGCAccess(); + if (!envObject.tryCatch.isEmpty()) + return envObject.setLastError(10 /* napi_status.napi_pending_exception */); + if (!envObject.canCallIntoJs()) + return envObject.setLastError(envObject.moduleApiVersion >= 10 ? 23 /* napi_status.napi_cannot_run_js */ : 10 /* napi_status.napi_pending_exception */); + envObject.clearLastError(); + try { + if (!result) + return envObject.setLastError(1 /* napi_status.napi_invalid_arg */); + if (!object) + return envObject.setLastError(1 /* napi_status.napi_invalid_arg */); + var h = emnapiCtx.handleStore.get(object); + if (h.value == null) { + throw new TypeError('Cannot convert undefined or null to object'); + } + var obj = void 0; + try { + obj = h.isObject() || h.isFunction() ? h.value : Object(h.value); + } + catch (_) { + return envObject.setLastError(2 /* napi_status.napi_object_expected */); + } + if (key_mode !== 0 /* napi_key_collection_mode.napi_key_include_prototypes */ && key_mode !== 1 /* napi_key_collection_mode.napi_key_own_only */) { + return envObject.setLastError(1 /* napi_status.napi_invalid_arg */); + } + if (key_conversion !== 0 /* napi_key_conversion.napi_key_keep_numbers */ && key_conversion !== 1 /* napi_key_conversion.napi_key_numbers_to_strings */) { + return envObject.setLastError(1 /* napi_status.napi_invalid_arg */); + } + var props = []; + var names = void 0; + var symbols = void 0; + var i = void 0; + var own = true; + var integerIndiceRegex = /^(0|[1-9][0-9]*)$/; + do { + names = Object.getOwnPropertyNames(obj); + symbols = Object.getOwnPropertySymbols(obj); + for (i = 0; i < names.length; i++) { + props.push({ + name: integerIndiceRegex.test(names[i]) ? Number(names[i]) : names[i], + desc: Object.getOwnPropertyDescriptor(obj, names[i]), + own: own + }); + } + for (i = 0; i < symbols.length; i++) { + props.push({ + name: symbols[i], + desc: Object.getOwnPropertyDescriptor(obj, symbols[i]), + own: own + }); + } + if (key_mode === 1 /* napi_key_collection_mode.napi_key_own_only */) { + break; + } + obj = Object.getPrototypeOf(obj); + own = false; + } while (obj); + var ret = []; + var addName = function (ret, name, key_filter, conversion_mode) { + if (ret.indexOf(name) !== -1) + return; + if (conversion_mode === 0 /* napi_key_conversion.napi_key_keep_numbers */) { + ret.push(name); + } + else if (conversion_mode === 1 /* napi_key_conversion.napi_key_numbers_to_strings */) { + var realName = typeof name === 'number' ? String(name) : name; + if (typeof realName === 'string') { + if (!(key_filter & 8 /* napi_key_filter.napi_key_skip_strings */)) { + ret.push(realName); + } + } + else { + ret.push(realName); + } + } + }; + for (i = 0; i < props.length; i++) { + var prop = props[i]; + var name_1 = prop.name; + var desc = prop.desc; + if (key_filter === 0 /* napi_key_filter.napi_key_all_properties */) { + addName(ret, name_1, key_filter, key_conversion); + } + else { + if (key_filter & 8 /* napi_key_filter.napi_key_skip_strings */ && typeof name_1 === 'string') { + continue; + } + if (key_filter & 16 /* napi_key_filter.napi_key_skip_symbols */ && typeof name_1 === 'symbol') { + continue; + } + var shouldAdd = true; + switch (key_filter & 7) { + case 1 /* napi_key_filter.napi_key_writable */: { + shouldAdd = Boolean(desc.writable); + break; + } + case 2 /* napi_key_filter.napi_key_enumerable */: { + shouldAdd = Boolean(desc.enumerable); + break; + } + case (1 /* napi_key_filter.napi_key_writable */ | 2 /* napi_key_filter.napi_key_enumerable */): { + shouldAdd = Boolean(desc.writable && desc.enumerable); + break; + } + case 4 /* napi_key_filter.napi_key_configurable */: { + shouldAdd = Boolean(desc.configurable); + break; + } + case (4 /* napi_key_filter.napi_key_configurable */ | 1 /* napi_key_filter.napi_key_writable */): { + shouldAdd = Boolean(desc.configurable && desc.writable); + break; + } + case (4 /* napi_key_filter.napi_key_configurable */ | 2 /* napi_key_filter.napi_key_enumerable */): { + shouldAdd = Boolean(desc.configurable && desc.enumerable); + break; + } + case (4 /* napi_key_filter.napi_key_configurable */ | 2 /* napi_key_filter.napi_key_enumerable */ | 1 /* napi_key_filter.napi_key_writable */): { + shouldAdd = Boolean(desc.configurable && desc.enumerable && desc.writable); + break; + } + } + if (shouldAdd) { + addName(ret, name_1, key_filter, key_conversion); + } + } + } + result >>>= 0; + // eslint-disable-next-line @typescript-eslint/no-unused-vars + value = emnapiCtx.addToCurrentScope(ret).id; + var HEAP_DATA_VIEW = new DataView(wasmMemory.buffer), GET_HEAP_DATA_VIEW = function () { return HEAP_DATA_VIEW.buffer === wasmMemory.buffer ? HEAP_DATA_VIEW : (HEAP_DATA_VIEW = new DataView(wasmMemory.buffer)); }; + GET_HEAP_DATA_VIEW().setUint32(result, value, true); + return envObject.getReturnStatus(); + } + catch (err) { + envObject.tryCatch.setError(err); + return envObject.setLastError(10 /* napi_status.napi_pending_exception */); + } + } + /** @__sig ippp */ + function napi_get_property_names(env, object, result) { + return napi_get_all_property_names(env, object, 0 /* napi_key_collection_mode.napi_key_include_prototypes */, 2 /* napi_key_filter.napi_key_enumerable */ | 16 /* napi_key_filter.napi_key_skip_symbols */, 1 /* napi_key_conversion.napi_key_numbers_to_strings */, result); + } + /** @__sig ipppp */ + function napi_set_property(env, object, key, value) { + if (!env) + return 1 /* napi_status.napi_invalid_arg */; + // @ts-expect-error + var envObject = emnapiCtx.envStore.get(env); + envObject.checkGCAccess(); + if (!envObject.tryCatch.isEmpty()) + return envObject.setLastError(10 /* napi_status.napi_pending_exception */); + if (!envObject.canCallIntoJs()) + return envObject.setLastError(envObject.moduleApiVersion >= 10 ? 23 /* napi_status.napi_cannot_run_js */ : 10 /* napi_status.napi_pending_exception */); + envObject.clearLastError(); + try { + if (!key) + return envObject.setLastError(1 /* napi_status.napi_invalid_arg */); + if (!value) + return envObject.setLastError(1 /* napi_status.napi_invalid_arg */); + if (!object) + return envObject.setLastError(1 /* napi_status.napi_invalid_arg */); + var h = emnapiCtx.handleStore.get(object); + if (!(h.isObject() || h.isFunction())) { + return envObject.setLastError(2 /* napi_status.napi_object_expected */); + } + h.value[emnapiCtx.handleStore.get(key).value] = emnapiCtx.handleStore.get(value).value; + return envObject.getReturnStatus(); + } + catch (err) { + envObject.tryCatch.setError(err); + return envObject.setLastError(10 /* napi_status.napi_pending_exception */); + } + } + /** @__sig ipppp */ + function napi_has_property(env, object, key, result) { + // eslint-disable-next-line @typescript-eslint/no-unused-vars + var r; + if (!env) + return 1 /* napi_status.napi_invalid_arg */; + // @ts-expect-error + var envObject = emnapiCtx.envStore.get(env); + envObject.checkGCAccess(); + if (!envObject.tryCatch.isEmpty()) + return envObject.setLastError(10 /* napi_status.napi_pending_exception */); + if (!envObject.canCallIntoJs()) + return envObject.setLastError(envObject.moduleApiVersion >= 10 ? 23 /* napi_status.napi_cannot_run_js */ : 10 /* napi_status.napi_pending_exception */); + envObject.clearLastError(); + try { + if (!key) + return envObject.setLastError(1 /* napi_status.napi_invalid_arg */); + if (!result) + return envObject.setLastError(1 /* napi_status.napi_invalid_arg */); + if (!object) + return envObject.setLastError(1 /* napi_status.napi_invalid_arg */); + var h = emnapiCtx.handleStore.get(object); + if (h.value == null) { + throw new TypeError('Cannot convert undefined or null to object'); + } + var v = void 0; + try { + v = h.isObject() || h.isFunction() ? h.value : Object(h.value); + } + catch (_) { + return envObject.setLastError(2 /* napi_status.napi_object_expected */); + } + result >>>= 0; + r = (emnapiCtx.handleStore.get(key).value in v) ? 1 : 0; + var HEAP_DATA_VIEW = new DataView(wasmMemory.buffer), GET_HEAP_DATA_VIEW = function () { return HEAP_DATA_VIEW.buffer === wasmMemory.buffer ? HEAP_DATA_VIEW : (HEAP_DATA_VIEW = new DataView(wasmMemory.buffer)); }; + GET_HEAP_DATA_VIEW().setInt8(result, r, true); + return envObject.getReturnStatus(); + } + catch (err) { + envObject.tryCatch.setError(err); + return envObject.setLastError(10 /* napi_status.napi_pending_exception */); + } + } + /** @__sig ipppp */ + function napi_get_property(env, object, key, result) { + // eslint-disable-next-line @typescript-eslint/no-unused-vars + var value; + if (!env) + return 1 /* napi_status.napi_invalid_arg */; + // @ts-expect-error + var envObject = emnapiCtx.envStore.get(env); + envObject.checkGCAccess(); + if (!envObject.tryCatch.isEmpty()) + return envObject.setLastError(10 /* napi_status.napi_pending_exception */); + if (!envObject.canCallIntoJs()) + return envObject.setLastError(envObject.moduleApiVersion >= 10 ? 23 /* napi_status.napi_cannot_run_js */ : 10 /* napi_status.napi_pending_exception */); + envObject.clearLastError(); + try { + if (!key) + return envObject.setLastError(1 /* napi_status.napi_invalid_arg */); + if (!result) + return envObject.setLastError(1 /* napi_status.napi_invalid_arg */); + if (!object) + return envObject.setLastError(1 /* napi_status.napi_invalid_arg */); + var h = emnapiCtx.handleStore.get(object); + if (h.value == null) { + throw new TypeError('Cannot convert undefined or null to object'); + } + var v = void 0; + try { + v = h.isObject() || h.isFunction() ? h.value : Object(h.value); + } + catch (_) { + return envObject.setLastError(2 /* napi_status.napi_object_expected */); + } + result >>>= 0; + // eslint-disable-next-line @typescript-eslint/no-unused-vars + value = envObject.ensureHandleId(v[emnapiCtx.handleStore.get(key).value]); + var HEAP_DATA_VIEW = new DataView(wasmMemory.buffer), GET_HEAP_DATA_VIEW = function () { return HEAP_DATA_VIEW.buffer === wasmMemory.buffer ? HEAP_DATA_VIEW : (HEAP_DATA_VIEW = new DataView(wasmMemory.buffer)); }; + GET_HEAP_DATA_VIEW().setUint32(result, value, true); + return envObject.getReturnStatus(); + } + catch (err) { + envObject.tryCatch.setError(err); + return envObject.setLastError(10 /* napi_status.napi_pending_exception */); + } + } + /** @__sig ipppp */ + function napi_delete_property(env, object, key, result) { + // eslint-disable-next-line @typescript-eslint/no-unused-vars + var r; + if (!env) + return 1 /* napi_status.napi_invalid_arg */; + // @ts-expect-error + var envObject = emnapiCtx.envStore.get(env); + envObject.checkGCAccess(); + if (!envObject.tryCatch.isEmpty()) + return envObject.setLastError(10 /* napi_status.napi_pending_exception */); + if (!envObject.canCallIntoJs()) + return envObject.setLastError(envObject.moduleApiVersion >= 10 ? 23 /* napi_status.napi_cannot_run_js */ : 10 /* napi_status.napi_pending_exception */); + envObject.clearLastError(); + try { + if (!key) + return envObject.setLastError(1 /* napi_status.napi_invalid_arg */); + if (!object) + return envObject.setLastError(1 /* napi_status.napi_invalid_arg */); + var h = emnapiCtx.handleStore.get(object); + if (!(h.isObject() || h.isFunction())) { + return envObject.setLastError(2 /* napi_status.napi_object_expected */); + } + var propertyKey = emnapiCtx.handleStore.get(key).value; + if (emnapiCtx.feature.supportReflect) { + r = Reflect.deleteProperty(h.value, propertyKey); + } + else { + try { + r = delete h.value[propertyKey]; + } + catch (_) { + r = false; + } + } + if (result) { + result >>>= 0; + var HEAP_DATA_VIEW = new DataView(wasmMemory.buffer), GET_HEAP_DATA_VIEW = function () { return HEAP_DATA_VIEW.buffer === wasmMemory.buffer ? HEAP_DATA_VIEW : (HEAP_DATA_VIEW = new DataView(wasmMemory.buffer)); }; + GET_HEAP_DATA_VIEW().setInt8(result, r ? 1 : 0, true); + } + return envObject.getReturnStatus(); + } + catch (err) { + envObject.tryCatch.setError(err); + return envObject.setLastError(10 /* napi_status.napi_pending_exception */); + } + } + /** @__sig ipppp */ + function napi_has_own_property(env, object, key, result) { + // eslint-disable-next-line @typescript-eslint/no-unused-vars + var r; + if (!env) + return 1 /* napi_status.napi_invalid_arg */; + // @ts-expect-error + var envObject = emnapiCtx.envStore.get(env); + envObject.checkGCAccess(); + if (!envObject.tryCatch.isEmpty()) + return envObject.setLastError(10 /* napi_status.napi_pending_exception */); + if (!envObject.canCallIntoJs()) + return envObject.setLastError(envObject.moduleApiVersion >= 10 ? 23 /* napi_status.napi_cannot_run_js */ : 10 /* napi_status.napi_pending_exception */); + envObject.clearLastError(); + try { + if (!key) + return envObject.setLastError(1 /* napi_status.napi_invalid_arg */); + if (!result) + return envObject.setLastError(1 /* napi_status.napi_invalid_arg */); + if (!object) + return envObject.setLastError(1 /* napi_status.napi_invalid_arg */); + var h = emnapiCtx.handleStore.get(object); + if (h.value == null) { + throw new TypeError('Cannot convert undefined or null to object'); + } + var v = void 0; + try { + v = h.isObject() || h.isFunction() ? h.value : Object(h.value); + } + catch (_) { + return envObject.setLastError(2 /* napi_status.napi_object_expected */); + } + var prop = emnapiCtx.handleStore.get(key).value; + if (typeof prop !== 'string' && typeof prop !== 'symbol') { + return envObject.setLastError(4 /* napi_status.napi_name_expected */); + } + r = Object.prototype.hasOwnProperty.call(v, emnapiCtx.handleStore.get(key).value); + result >>>= 0; + var HEAP_DATA_VIEW = new DataView(wasmMemory.buffer), GET_HEAP_DATA_VIEW = function () { return HEAP_DATA_VIEW.buffer === wasmMemory.buffer ? HEAP_DATA_VIEW : (HEAP_DATA_VIEW = new DataView(wasmMemory.buffer)); }; + GET_HEAP_DATA_VIEW().setInt8(result, r ? 1 : 0, true); + return envObject.getReturnStatus(); + } + catch (err) { + envObject.tryCatch.setError(err); + return envObject.setLastError(10 /* napi_status.napi_pending_exception */); + } + } + /** @__sig ipppp */ + function napi_set_named_property(env, object, cname, value) { + if (!env) + return 1 /* napi_status.napi_invalid_arg */; + // @ts-expect-error + var envObject = emnapiCtx.envStore.get(env); + envObject.checkGCAccess(); + if (!envObject.tryCatch.isEmpty()) + return envObject.setLastError(10 /* napi_status.napi_pending_exception */); + if (!envObject.canCallIntoJs()) + return envObject.setLastError(envObject.moduleApiVersion >= 10 ? 23 /* napi_status.napi_cannot_run_js */ : 10 /* napi_status.napi_pending_exception */); + envObject.clearLastError(); + try { + if (!value) + return envObject.setLastError(1 /* napi_status.napi_invalid_arg */); + if (!object) + return envObject.setLastError(1 /* napi_status.napi_invalid_arg */); + var h = emnapiCtx.handleStore.get(object); + if (!(h.isObject() || h.isFunction())) { + return envObject.setLastError(2 /* napi_status.napi_object_expected */); + } + if (!cname) { + return envObject.setLastError(1 /* napi_status.napi_invalid_arg */); + } + cname >>>= 0; + emnapiCtx.handleStore.get(object).value[emnapiString.UTF8ToString(cname, -1)] = emnapiCtx.handleStore.get(value).value; + return envObject.getReturnStatus(); + } + catch (err) { + envObject.tryCatch.setError(err); + return envObject.setLastError(10 /* napi_status.napi_pending_exception */); + } + } + /** @__sig ipppp */ + function napi_has_named_property(env, object, utf8name, result) { + // eslint-disable-next-line @typescript-eslint/no-unused-vars + var r; + if (!env) + return 1 /* napi_status.napi_invalid_arg */; + // @ts-expect-error + var envObject = emnapiCtx.envStore.get(env); + envObject.checkGCAccess(); + if (!envObject.tryCatch.isEmpty()) + return envObject.setLastError(10 /* napi_status.napi_pending_exception */); + if (!envObject.canCallIntoJs()) + return envObject.setLastError(envObject.moduleApiVersion >= 10 ? 23 /* napi_status.napi_cannot_run_js */ : 10 /* napi_status.napi_pending_exception */); + envObject.clearLastError(); + try { + if (!result) + return envObject.setLastError(1 /* napi_status.napi_invalid_arg */); + if (!object) + return envObject.setLastError(1 /* napi_status.napi_invalid_arg */); + if (!utf8name) { + return envObject.setLastError(1 /* napi_status.napi_invalid_arg */); + } + var h = emnapiCtx.handleStore.get(object); + if (h.value == null) { + throw new TypeError('Cannot convert undefined or null to object'); + } + var v = void 0; + try { + v = h.isObject() || h.isFunction() ? h.value : Object(h.value); + } + catch (_) { + return envObject.setLastError(2 /* napi_status.napi_object_expected */); + } + utf8name >>>= 0; + result >>>= 0; + r = emnapiString.UTF8ToString(utf8name, -1) in v; + var HEAP_DATA_VIEW = new DataView(wasmMemory.buffer), GET_HEAP_DATA_VIEW = function () { return HEAP_DATA_VIEW.buffer === wasmMemory.buffer ? HEAP_DATA_VIEW : (HEAP_DATA_VIEW = new DataView(wasmMemory.buffer)); }; + GET_HEAP_DATA_VIEW().setInt8(result, r ? 1 : 0, true); + return envObject.getReturnStatus(); + } + catch (err) { + envObject.tryCatch.setError(err); + return envObject.setLastError(10 /* napi_status.napi_pending_exception */); + } + } + /** @__sig ipppp */ + function napi_get_named_property(env, object, utf8name, result) { + // eslint-disable-next-line @typescript-eslint/no-unused-vars + var value; + if (!env) + return 1 /* napi_status.napi_invalid_arg */; + // @ts-expect-error + var envObject = emnapiCtx.envStore.get(env); + envObject.checkGCAccess(); + if (!envObject.tryCatch.isEmpty()) + return envObject.setLastError(10 /* napi_status.napi_pending_exception */); + if (!envObject.canCallIntoJs()) + return envObject.setLastError(envObject.moduleApiVersion >= 10 ? 23 /* napi_status.napi_cannot_run_js */ : 10 /* napi_status.napi_pending_exception */); + envObject.clearLastError(); + try { + if (!result) + return envObject.setLastError(1 /* napi_status.napi_invalid_arg */); + if (!object) + return envObject.setLastError(1 /* napi_status.napi_invalid_arg */); + if (!utf8name) { + return envObject.setLastError(1 /* napi_status.napi_invalid_arg */); + } + var h = emnapiCtx.handleStore.get(object); + if (h.value == null) { + throw new TypeError('Cannot convert undefined or null to object'); + } + var v = void 0; + try { + v = h.isObject() || h.isFunction() ? h.value : Object(h.value); + } + catch (_) { + return envObject.setLastError(2 /* napi_status.napi_object_expected */); + } + utf8name >>>= 0; + result >>>= 0; + // eslint-disable-next-line @typescript-eslint/no-unused-vars + value = envObject.ensureHandleId(v[emnapiString.UTF8ToString(utf8name, -1)]); + var HEAP_DATA_VIEW = new DataView(wasmMemory.buffer), GET_HEAP_DATA_VIEW = function () { return HEAP_DATA_VIEW.buffer === wasmMemory.buffer ? HEAP_DATA_VIEW : (HEAP_DATA_VIEW = new DataView(wasmMemory.buffer)); }; + GET_HEAP_DATA_VIEW().setUint32(result, value, true); + return envObject.getReturnStatus(); + } + catch (err) { + envObject.tryCatch.setError(err); + return envObject.setLastError(10 /* napi_status.napi_pending_exception */); + } + } + /** @__sig ippip */ + function napi_set_element(env, object, index, value) { + if (!env) + return 1 /* napi_status.napi_invalid_arg */; + // @ts-expect-error + var envObject = emnapiCtx.envStore.get(env); + envObject.checkGCAccess(); + if (!envObject.tryCatch.isEmpty()) + return envObject.setLastError(10 /* napi_status.napi_pending_exception */); + if (!envObject.canCallIntoJs()) + return envObject.setLastError(envObject.moduleApiVersion >= 10 ? 23 /* napi_status.napi_cannot_run_js */ : 10 /* napi_status.napi_pending_exception */); + envObject.clearLastError(); + try { + if (!value) + return envObject.setLastError(1 /* napi_status.napi_invalid_arg */); + if (!object) + return envObject.setLastError(1 /* napi_status.napi_invalid_arg */); + var h = emnapiCtx.handleStore.get(object); + if (!(h.isObject() || h.isFunction())) { + return envObject.setLastError(2 /* napi_status.napi_object_expected */); + } + h.value[index >>> 0] = emnapiCtx.handleStore.get(value).value; + return envObject.getReturnStatus(); + } + catch (err) { + envObject.tryCatch.setError(err); + return envObject.setLastError(10 /* napi_status.napi_pending_exception */); + } + } + /** @__sig ippip */ + function napi_has_element(env, object, index, result) { + // eslint-disable-next-line @typescript-eslint/no-unused-vars + var r; + if (!env) + return 1 /* napi_status.napi_invalid_arg */; + // @ts-expect-error + var envObject = emnapiCtx.envStore.get(env); + envObject.checkGCAccess(); + if (!envObject.tryCatch.isEmpty()) + return envObject.setLastError(10 /* napi_status.napi_pending_exception */); + if (!envObject.canCallIntoJs()) + return envObject.setLastError(envObject.moduleApiVersion >= 10 ? 23 /* napi_status.napi_cannot_run_js */ : 10 /* napi_status.napi_pending_exception */); + envObject.clearLastError(); + try { + if (!result) + return envObject.setLastError(1 /* napi_status.napi_invalid_arg */); + if (!object) + return envObject.setLastError(1 /* napi_status.napi_invalid_arg */); + var h = emnapiCtx.handleStore.get(object); + if (h.value == null) { + throw new TypeError('Cannot convert undefined or null to object'); + } + var v = void 0; + try { + v = h.isObject() || h.isFunction() ? h.value : Object(h.value); + } + catch (_) { + return envObject.setLastError(2 /* napi_status.napi_object_expected */); + } + result >>>= 0; + r = ((index >>> 0) in v) ? 1 : 0; + var HEAP_DATA_VIEW = new DataView(wasmMemory.buffer), GET_HEAP_DATA_VIEW = function () { return HEAP_DATA_VIEW.buffer === wasmMemory.buffer ? HEAP_DATA_VIEW : (HEAP_DATA_VIEW = new DataView(wasmMemory.buffer)); }; + GET_HEAP_DATA_VIEW().setInt8(result, r, true); + return envObject.getReturnStatus(); + } + catch (err) { + envObject.tryCatch.setError(err); + return envObject.setLastError(10 /* napi_status.napi_pending_exception */); + } + } + /** @__sig ippip */ + function napi_get_element(env, object, index, result) { + // eslint-disable-next-line @typescript-eslint/no-unused-vars + var value; + if (!env) + return 1 /* napi_status.napi_invalid_arg */; + // @ts-expect-error + var envObject = emnapiCtx.envStore.get(env); + envObject.checkGCAccess(); + if (!envObject.tryCatch.isEmpty()) + return envObject.setLastError(10 /* napi_status.napi_pending_exception */); + if (!envObject.canCallIntoJs()) + return envObject.setLastError(envObject.moduleApiVersion >= 10 ? 23 /* napi_status.napi_cannot_run_js */ : 10 /* napi_status.napi_pending_exception */); + envObject.clearLastError(); + try { + if (!result) + return envObject.setLastError(1 /* napi_status.napi_invalid_arg */); + if (!object) + return envObject.setLastError(1 /* napi_status.napi_invalid_arg */); + var h = emnapiCtx.handleStore.get(object); + if (h.value == null) { + throw new TypeError('Cannot convert undefined or null to object'); + } + var v = void 0; + try { + v = h.isObject() || h.isFunction() ? h.value : Object(h.value); + } + catch (_) { + return envObject.setLastError(2 /* napi_status.napi_object_expected */); + } + result >>>= 0; + // eslint-disable-next-line @typescript-eslint/no-unused-vars + value = envObject.ensureHandleId(v[index >>> 0]); + var HEAP_DATA_VIEW = new DataView(wasmMemory.buffer), GET_HEAP_DATA_VIEW = function () { return HEAP_DATA_VIEW.buffer === wasmMemory.buffer ? HEAP_DATA_VIEW : (HEAP_DATA_VIEW = new DataView(wasmMemory.buffer)); }; + GET_HEAP_DATA_VIEW().setUint32(result, value, true); + return envObject.getReturnStatus(); + } + catch (err) { + envObject.tryCatch.setError(err); + return envObject.setLastError(10 /* napi_status.napi_pending_exception */); + } + } + /** @__sig ippip */ + function napi_delete_element(env, object, index, result) { + // eslint-disable-next-line @typescript-eslint/no-unused-vars + var r; + if (!env) + return 1 /* napi_status.napi_invalid_arg */; + // @ts-expect-error + var envObject = emnapiCtx.envStore.get(env); + envObject.checkGCAccess(); + if (!envObject.tryCatch.isEmpty()) + return envObject.setLastError(10 /* napi_status.napi_pending_exception */); + if (!envObject.canCallIntoJs()) + return envObject.setLastError(envObject.moduleApiVersion >= 10 ? 23 /* napi_status.napi_cannot_run_js */ : 10 /* napi_status.napi_pending_exception */); + envObject.clearLastError(); + try { + if (!object) + return envObject.setLastError(1 /* napi_status.napi_invalid_arg */); + var h = emnapiCtx.handleStore.get(object); + if (!(h.isObject() || h.isFunction())) { + return envObject.setLastError(2 /* napi_status.napi_object_expected */); + } + if (emnapiCtx.feature.supportReflect) { + r = Reflect.deleteProperty(h.value, index >>> 0); + } + else { + try { + r = delete h.value[index >>> 0]; + } + catch (_) { + r = false; + } + } + if (result) { + result >>>= 0; + var HEAP_DATA_VIEW = new DataView(wasmMemory.buffer), GET_HEAP_DATA_VIEW = function () { return HEAP_DATA_VIEW.buffer === wasmMemory.buffer ? HEAP_DATA_VIEW : (HEAP_DATA_VIEW = new DataView(wasmMemory.buffer)); }; + GET_HEAP_DATA_VIEW().setInt8(result, r ? 1 : 0, true); + } + return envObject.getReturnStatus(); + } + catch (err) { + envObject.tryCatch.setError(err); + return envObject.setLastError(10 /* napi_status.napi_pending_exception */); + } + } + /** @__sig ipppp */ + function napi_define_properties(env, object, property_count, properties) { + // eslint-disable-next-line @typescript-eslint/no-unused-vars + var propPtr, attributes; + if (!env) + return 1 /* napi_status.napi_invalid_arg */; + // @ts-expect-error + var envObject = emnapiCtx.envStore.get(env); + envObject.checkGCAccess(); + if (!envObject.tryCatch.isEmpty()) + return envObject.setLastError(10 /* napi_status.napi_pending_exception */); + if (!envObject.canCallIntoJs()) + return envObject.setLastError(envObject.moduleApiVersion >= 10 ? 23 /* napi_status.napi_cannot_run_js */ : 10 /* napi_status.napi_pending_exception */); + envObject.clearLastError(); + try { + properties >>>= 0; + property_count >>>= 0; + property_count = property_count >>> 0; + if (property_count > 0) { + if (!properties) + return envObject.setLastError(1 /* napi_status.napi_invalid_arg */); + } + if (!object) + return envObject.setLastError(1 /* napi_status.napi_invalid_arg */); + var h = emnapiCtx.handleStore.get(object); + var maybeObject = h.value; + if (!(h.isObject() || h.isFunction())) { + return envObject.setLastError(2 /* napi_status.napi_object_expected */); + } + var propertyName = void 0; + var HEAP_DATA_VIEW = new DataView(wasmMemory.buffer), GET_HEAP_DATA_VIEW = function () { return HEAP_DATA_VIEW.buffer === wasmMemory.buffer ? HEAP_DATA_VIEW : (HEAP_DATA_VIEW = new DataView(wasmMemory.buffer)); }; + for (var i = 0; i < property_count; i++) { + // eslint-disable-next-line @typescript-eslint/no-unused-vars + propPtr = properties + (i * (4 * 8)); + var utf8Name = GET_HEAP_DATA_VIEW().getUint32(propPtr, true); + var name_2 = GET_HEAP_DATA_VIEW().getUint32(propPtr + 4, true); + var method = GET_HEAP_DATA_VIEW().getUint32(propPtr + 8, true); + var getter = GET_HEAP_DATA_VIEW().getUint32(propPtr + 12, true); + var setter = GET_HEAP_DATA_VIEW().getUint32(propPtr + 16, true); + var value = GET_HEAP_DATA_VIEW().getUint32(propPtr + 20, true); + attributes = GET_HEAP_DATA_VIEW().getInt32(propPtr + 24, true); + attributes >>>= 0; + var data = GET_HEAP_DATA_VIEW().getUint32(propPtr + 28, true); + if (utf8Name) { + propertyName = emnapiString.UTF8ToString(utf8Name, -1); + } + else { + if (!name_2) { + return envObject.setLastError(4 /* napi_status.napi_name_expected */); + } + propertyName = emnapiCtx.handleStore.get(name_2).value; + if (typeof propertyName !== 'string' && typeof propertyName !== 'symbol') { + return envObject.setLastError(4 /* napi_status.napi_name_expected */); + } + } + emnapiDefineProperty(envObject, maybeObject, propertyName, method, getter, setter, value, attributes, data); + } + return envObject.getReturnStatus(); + } + catch (err) { + envObject.tryCatch.setError(err); + return envObject.setLastError(10 /* napi_status.napi_pending_exception */); + } + } + /** @__sig ipp */ + function napi_object_freeze(env, object) { + if (!env) + return 1 /* napi_status.napi_invalid_arg */; + // @ts-expect-error + var envObject = emnapiCtx.envStore.get(env); + envObject.checkGCAccess(); + if (!envObject.tryCatch.isEmpty()) + return envObject.setLastError(10 /* napi_status.napi_pending_exception */); + if (!envObject.canCallIntoJs()) + return envObject.setLastError(envObject.moduleApiVersion >= 10 ? 23 /* napi_status.napi_cannot_run_js */ : 10 /* napi_status.napi_pending_exception */); + envObject.clearLastError(); + try { + if (!object) + return envObject.setLastError(1 /* napi_status.napi_invalid_arg */); + var h = emnapiCtx.handleStore.get(object); + var maybeObject = h.value; + if (!(h.isObject() || h.isFunction())) { + return envObject.setLastError(2 /* napi_status.napi_object_expected */); + } + Object.freeze(maybeObject); + return envObject.getReturnStatus(); + } + catch (err) { + envObject.tryCatch.setError(err); + return envObject.setLastError(10 /* napi_status.napi_pending_exception */); + } + } + /** @__sig ipp */ + function napi_object_seal(env, object) { + if (!env) + return 1 /* napi_status.napi_invalid_arg */; + // @ts-expect-error + var envObject = emnapiCtx.envStore.get(env); + envObject.checkGCAccess(); + if (!envObject.tryCatch.isEmpty()) + return envObject.setLastError(10 /* napi_status.napi_pending_exception */); + if (!envObject.canCallIntoJs()) + return envObject.setLastError(envObject.moduleApiVersion >= 10 ? 23 /* napi_status.napi_cannot_run_js */ : 10 /* napi_status.napi_pending_exception */); + envObject.clearLastError(); + try { + if (!object) + return envObject.setLastError(1 /* napi_status.napi_invalid_arg */); + var h = emnapiCtx.handleStore.get(object); + var maybeObject = h.value; + if (!(h.isObject() || h.isFunction())) { + return envObject.setLastError(2 /* napi_status.napi_object_expected */); + } + Object.seal(maybeObject); + return envObject.getReturnStatus(); + } + catch (err) { + envObject.tryCatch.setError(err); + return envObject.setLastError(10 /* napi_status.napi_pending_exception */); + } + } + var propertyMod = /*#__PURE__*/ Object.freeze({ + __proto__: null, + napi_define_properties: napi_define_properties, + napi_delete_element: napi_delete_element, + napi_delete_property: napi_delete_property, + napi_get_all_property_names: napi_get_all_property_names, + napi_get_element: napi_get_element, + napi_get_named_property: napi_get_named_property, + napi_get_property: napi_get_property, + napi_get_property_names: napi_get_property_names, + napi_has_element: napi_has_element, + napi_has_named_property: napi_has_named_property, + napi_has_own_property: napi_has_own_property, + napi_has_property: napi_has_property, + napi_object_freeze: napi_object_freeze, + napi_object_seal: napi_object_seal, + napi_set_element: napi_set_element, + napi_set_named_property: napi_set_named_property, + napi_set_property: napi_set_property + }); + /** @__sig ippp */ + function napi_run_script(env, script, result) { + var status; + // eslint-disable-next-line @typescript-eslint/no-unused-vars + var value; + if (!env) + return 1 /* napi_status.napi_invalid_arg */; + // @ts-expect-error + var envObject = emnapiCtx.envStore.get(env); + envObject.checkGCAccess(); + if (!envObject.tryCatch.isEmpty()) + return envObject.setLastError(10 /* napi_status.napi_pending_exception */); + if (!envObject.canCallIntoJs()) + return envObject.setLastError(envObject.moduleApiVersion >= 10 ? 23 /* napi_status.napi_cannot_run_js */ : 10 /* napi_status.napi_pending_exception */); + envObject.clearLastError(); + try { + if (!script) + return envObject.setLastError(1 /* napi_status.napi_invalid_arg */); + if (!result) + return envObject.setLastError(1 /* napi_status.napi_invalid_arg */); + var v8Script = emnapiCtx.handleStore.get(script); + if (!v8Script.isString()) { + return envObject.setLastError(3 /* napi_status.napi_string_expected */); + } + var g = emnapiCtx.handleStore.get(5 /* GlobalHandle.GLOBAL */).value; + var ret = g.eval(v8Script.value); + result >>>= 0; + // eslint-disable-next-line @typescript-eslint/no-unused-vars + value = envObject.ensureHandleId(ret); + var HEAP_DATA_VIEW = new DataView(wasmMemory.buffer), GET_HEAP_DATA_VIEW = function () { return HEAP_DATA_VIEW.buffer === wasmMemory.buffer ? HEAP_DATA_VIEW : (HEAP_DATA_VIEW = new DataView(wasmMemory.buffer)); }; + GET_HEAP_DATA_VIEW().setUint32(result, value, true); + status = envObject.getReturnStatus(); + } + catch (err) { + envObject.tryCatch.setError(err); + return envObject.setLastError(10 /* napi_status.napi_pending_exception */); + } + return status; + } + var scriptMod = /*#__PURE__*/ Object.freeze({ + __proto__: null, + napi_run_script: napi_run_script + }); + /** @__sig ippp */ + function napi_typeof(env, value, result) { + if (!env) + return 1 /* napi_status.napi_invalid_arg */; + // @ts-expect-error + var envObject = emnapiCtx.envStore.get(env); + envObject.checkGCAccess(); + if (!value) + return envObject.setLastError(1 /* napi_status.napi_invalid_arg */); + if (!result) + return envObject.setLastError(1 /* napi_status.napi_invalid_arg */); + var v = emnapiCtx.handleStore.get(value); + result >>>= 0; + var r; + if (v.isNumber()) { + r = 3 /* napi_valuetype.napi_number */; + } + else if (v.isBigInt()) { + r = 9 /* napi_valuetype.napi_bigint */; + } + else if (v.isString()) { + r = 4 /* napi_valuetype.napi_string */; + } + else if (v.isFunction()) { + // This test has to come before IsObject because IsFunction + // implies IsObject + r = 7 /* napi_valuetype.napi_function */; + } + else if (v.isExternal()) { + // This test has to come before IsObject because IsExternal + // implies IsObject + r = 8 /* napi_valuetype.napi_external */; + } + else if (v.isObject()) { + r = 6 /* napi_valuetype.napi_object */; + } + else if (v.isBoolean()) { + r = 2 /* napi_valuetype.napi_boolean */; + } + else if (v.isUndefined()) { + r = 0 /* napi_valuetype.napi_undefined */; + } + else if (v.isSymbol()) { + r = 5 /* napi_valuetype.napi_symbol */; + } + else if (v.isNull()) { + // eslint-disable-next-line @typescript-eslint/no-unused-vars + r = 1 /* napi_valuetype.napi_null */; + } + else { + // Should not get here unless V8 has added some new kind of value. + return envObject.setLastError(1 /* napi_status.napi_invalid_arg */); + } + var HEAP_DATA_VIEW = new DataView(wasmMemory.buffer), GET_HEAP_DATA_VIEW = function () { return HEAP_DATA_VIEW.buffer === wasmMemory.buffer ? HEAP_DATA_VIEW : (HEAP_DATA_VIEW = new DataView(wasmMemory.buffer)); }; + GET_HEAP_DATA_VIEW().setInt32(result, r, true); + return envObject.clearLastError(); + } + /** @__sig ippp */ + function napi_coerce_to_bool(env, value, result) { + // eslint-disable-next-line @typescript-eslint/no-unused-vars + var v; + if (!env) + return 1 /* napi_status.napi_invalid_arg */; + // @ts-expect-error + var envObject = emnapiCtx.envStore.get(env); + envObject.checkGCAccess(); + if (!envObject.tryCatch.isEmpty()) + return envObject.setLastError(10 /* napi_status.napi_pending_exception */); + if (!envObject.canCallIntoJs()) + return envObject.setLastError(envObject.moduleApiVersion >= 10 ? 23 /* napi_status.napi_cannot_run_js */ : 10 /* napi_status.napi_pending_exception */); + envObject.clearLastError(); + try { + if (!value) + return envObject.setLastError(1 /* napi_status.napi_invalid_arg */); + if (!result) + return envObject.setLastError(1 /* napi_status.napi_invalid_arg */); + var handle = emnapiCtx.handleStore.get(value); + result >>>= 0; + v = handle.value ? 4 /* GlobalHandle.TRUE */ : 3 /* GlobalHandle.FALSE */; + var HEAP_DATA_VIEW = new DataView(wasmMemory.buffer), GET_HEAP_DATA_VIEW = function () { return HEAP_DATA_VIEW.buffer === wasmMemory.buffer ? HEAP_DATA_VIEW : (HEAP_DATA_VIEW = new DataView(wasmMemory.buffer)); }; + GET_HEAP_DATA_VIEW().setUint32(result, v, true); + return envObject.getReturnStatus(); + } + catch (err) { + envObject.tryCatch.setError(err); + return envObject.setLastError(10 /* napi_status.napi_pending_exception */); + } + } + /** @__sig ippp */ + function napi_coerce_to_number(env, value, result) { + // eslint-disable-next-line @typescript-eslint/no-unused-vars + var v; + if (!env) + return 1 /* napi_status.napi_invalid_arg */; + // @ts-expect-error + var envObject = emnapiCtx.envStore.get(env); + envObject.checkGCAccess(); + if (!envObject.tryCatch.isEmpty()) + return envObject.setLastError(10 /* napi_status.napi_pending_exception */); + if (!envObject.canCallIntoJs()) + return envObject.setLastError(envObject.moduleApiVersion >= 10 ? 23 /* napi_status.napi_cannot_run_js */ : 10 /* napi_status.napi_pending_exception */); + envObject.clearLastError(); + try { + if (!value) + return envObject.setLastError(1 /* napi_status.napi_invalid_arg */); + if (!result) + return envObject.setLastError(1 /* napi_status.napi_invalid_arg */); + var handle = emnapiCtx.handleStore.get(value); + if (handle.isBigInt()) { + throw new TypeError('Cannot convert a BigInt value to a number'); + } + result >>>= 0; + // eslint-disable-next-line @typescript-eslint/no-unused-vars + v = emnapiCtx.addToCurrentScope(Number(handle.value)).id; + var HEAP_DATA_VIEW = new DataView(wasmMemory.buffer), GET_HEAP_DATA_VIEW = function () { return HEAP_DATA_VIEW.buffer === wasmMemory.buffer ? HEAP_DATA_VIEW : (HEAP_DATA_VIEW = new DataView(wasmMemory.buffer)); }; + GET_HEAP_DATA_VIEW().setUint32(result, v, true); + return envObject.getReturnStatus(); + } + catch (err) { + envObject.tryCatch.setError(err); + return envObject.setLastError(10 /* napi_status.napi_pending_exception */); + } + } + /** @__sig ippp */ + function napi_coerce_to_object(env, value, result) { + // eslint-disable-next-line @typescript-eslint/no-unused-vars + var v; + if (!env) + return 1 /* napi_status.napi_invalid_arg */; + // @ts-expect-error + var envObject = emnapiCtx.envStore.get(env); + envObject.checkGCAccess(); + if (!envObject.tryCatch.isEmpty()) + return envObject.setLastError(10 /* napi_status.napi_pending_exception */); + if (!envObject.canCallIntoJs()) + return envObject.setLastError(envObject.moduleApiVersion >= 10 ? 23 /* napi_status.napi_cannot_run_js */ : 10 /* napi_status.napi_pending_exception */); + envObject.clearLastError(); + try { + if (!value) + return envObject.setLastError(1 /* napi_status.napi_invalid_arg */); + if (!result) + return envObject.setLastError(1 /* napi_status.napi_invalid_arg */); + var handle = emnapiCtx.handleStore.get(value); + if (handle.value == null) { + throw new TypeError('Cannot convert undefined or null to object'); + } + result >>>= 0; + // eslint-disable-next-line @typescript-eslint/no-unused-vars + v = envObject.ensureHandleId(Object(handle.value)); + var HEAP_DATA_VIEW = new DataView(wasmMemory.buffer), GET_HEAP_DATA_VIEW = function () { return HEAP_DATA_VIEW.buffer === wasmMemory.buffer ? HEAP_DATA_VIEW : (HEAP_DATA_VIEW = new DataView(wasmMemory.buffer)); }; + GET_HEAP_DATA_VIEW().setUint32(result, v, true); + return envObject.getReturnStatus(); + } + catch (err) { + envObject.tryCatch.setError(err); + return envObject.setLastError(10 /* napi_status.napi_pending_exception */); + } + } + /** @__sig ippp */ + function napi_coerce_to_string(env, value, result) { + // eslint-disable-next-line @typescript-eslint/no-unused-vars + var v; + if (!env) + return 1 /* napi_status.napi_invalid_arg */; + // @ts-expect-error + var envObject = emnapiCtx.envStore.get(env); + envObject.checkGCAccess(); + if (!envObject.tryCatch.isEmpty()) + return envObject.setLastError(10 /* napi_status.napi_pending_exception */); + if (!envObject.canCallIntoJs()) + return envObject.setLastError(envObject.moduleApiVersion >= 10 ? 23 /* napi_status.napi_cannot_run_js */ : 10 /* napi_status.napi_pending_exception */); + envObject.clearLastError(); + try { + if (!value) + return envObject.setLastError(1 /* napi_status.napi_invalid_arg */); + if (!result) + return envObject.setLastError(1 /* napi_status.napi_invalid_arg */); + var handle = emnapiCtx.handleStore.get(value); + if (handle.isSymbol()) { + throw new TypeError('Cannot convert a Symbol value to a string'); + } + result >>>= 0; + // eslint-disable-next-line @typescript-eslint/no-unused-vars + v = emnapiCtx.addToCurrentScope(String(handle.value)).id; + var HEAP_DATA_VIEW = new DataView(wasmMemory.buffer), GET_HEAP_DATA_VIEW = function () { return HEAP_DATA_VIEW.buffer === wasmMemory.buffer ? HEAP_DATA_VIEW : (HEAP_DATA_VIEW = new DataView(wasmMemory.buffer)); }; + GET_HEAP_DATA_VIEW().setUint32(result, v, true); + return envObject.getReturnStatus(); + } + catch (err) { + envObject.tryCatch.setError(err); + return envObject.setLastError(10 /* napi_status.napi_pending_exception */); + } + } + /** @__sig ipppp */ + function napi_instanceof(env, object, constructor, result) { + // eslint-disable-next-line @typescript-eslint/no-unused-vars + var r; + if (!env) + return 1 /* napi_status.napi_invalid_arg */; + // @ts-expect-error + var envObject = emnapiCtx.envStore.get(env); + envObject.checkGCAccess(); + if (!envObject.tryCatch.isEmpty()) + return envObject.setLastError(10 /* napi_status.napi_pending_exception */); + if (!envObject.canCallIntoJs()) + return envObject.setLastError(envObject.moduleApiVersion >= 10 ? 23 /* napi_status.napi_cannot_run_js */ : 10 /* napi_status.napi_pending_exception */); + envObject.clearLastError(); + try { + if (!object) + return envObject.setLastError(1 /* napi_status.napi_invalid_arg */); + if (!result) + return envObject.setLastError(1 /* napi_status.napi_invalid_arg */); + if (!constructor) + return envObject.setLastError(1 /* napi_status.napi_invalid_arg */); + result >>>= 0; + var HEAP_DATA_VIEW = new DataView(wasmMemory.buffer), GET_HEAP_DATA_VIEW = function () { return HEAP_DATA_VIEW.buffer === wasmMemory.buffer ? HEAP_DATA_VIEW : (HEAP_DATA_VIEW = new DataView(wasmMemory.buffer)); }; + GET_HEAP_DATA_VIEW().setInt8(result, 0, true); + var ctor = emnapiCtx.handleStore.get(constructor); + if (!ctor.isFunction()) { + return envObject.setLastError(5 /* napi_status.napi_function_expected */); + } + var val = emnapiCtx.handleStore.get(object).value; + var ret = val instanceof ctor.value; + r = ret ? 1 : 0; + GET_HEAP_DATA_VIEW().setInt8(result, r, true); + return envObject.getReturnStatus(); + } + catch (err) { + envObject.tryCatch.setError(err); + return envObject.setLastError(10 /* napi_status.napi_pending_exception */); + } + } + /** @__sig ippp */ + function napi_is_array(env, value, result) { + if (!env) + return 1 /* napi_status.napi_invalid_arg */; + // @ts-expect-error + var envObject = emnapiCtx.envStore.get(env); + envObject.checkGCAccess(); + if (!value) + return envObject.setLastError(1 /* napi_status.napi_invalid_arg */); + if (!result) + return envObject.setLastError(1 /* napi_status.napi_invalid_arg */); + var h = emnapiCtx.handleStore.get(value); + result >>>= 0; + // eslint-disable-next-line @typescript-eslint/no-unused-vars + var r = h.isArray() ? 1 : 0; + var HEAP_DATA_VIEW = new DataView(wasmMemory.buffer), GET_HEAP_DATA_VIEW = function () { return HEAP_DATA_VIEW.buffer === wasmMemory.buffer ? HEAP_DATA_VIEW : (HEAP_DATA_VIEW = new DataView(wasmMemory.buffer)); }; + GET_HEAP_DATA_VIEW().setInt8(result, r, true); + return envObject.clearLastError(); + } + /** @__sig ippp */ + function napi_is_arraybuffer(env, value, result) { + if (!env) + return 1 /* napi_status.napi_invalid_arg */; + // @ts-expect-error + var envObject = emnapiCtx.envStore.get(env); + envObject.checkGCAccess(); + if (!value) + return envObject.setLastError(1 /* napi_status.napi_invalid_arg */); + if (!result) + return envObject.setLastError(1 /* napi_status.napi_invalid_arg */); + var h = emnapiCtx.handleStore.get(value); + result >>>= 0; + // eslint-disable-next-line @typescript-eslint/no-unused-vars + var r = h.isArrayBuffer() ? 1 : 0; + var HEAP_DATA_VIEW = new DataView(wasmMemory.buffer), GET_HEAP_DATA_VIEW = function () { return HEAP_DATA_VIEW.buffer === wasmMemory.buffer ? HEAP_DATA_VIEW : (HEAP_DATA_VIEW = new DataView(wasmMemory.buffer)); }; + GET_HEAP_DATA_VIEW().setInt8(result, r, true); + return envObject.clearLastError(); + } + /** @__sig ippp */ + function node_api_is_sharedarraybuffer(env, value, result) { + if (!env) + return 1 /* napi_status.napi_invalid_arg */; + // @ts-expect-error + var envObject = emnapiCtx.envStore.get(env); + envObject.checkGCAccess(); + if (!value) + return envObject.setLastError(1 /* napi_status.napi_invalid_arg */); + if (!result) + return envObject.setLastError(1 /* napi_status.napi_invalid_arg */); + var h = emnapiCtx.handleStore.get(value); + result >>>= 0; + // eslint-disable-next-line @typescript-eslint/no-unused-vars + var r = ((typeof SharedArrayBuffer === 'function' && h.value instanceof SharedArrayBuffer) || + (Object.prototype.toString.call(h.value) === '[object SharedArrayBuffer]')) + ? 1 + : 0; + var HEAP_DATA_VIEW = new DataView(wasmMemory.buffer), GET_HEAP_DATA_VIEW = function () { return HEAP_DATA_VIEW.buffer === wasmMemory.buffer ? HEAP_DATA_VIEW : (HEAP_DATA_VIEW = new DataView(wasmMemory.buffer)); }; + GET_HEAP_DATA_VIEW().setInt8(result, r, true); + return envObject.clearLastError(); + } + /** @__sig ippp */ + function napi_is_date(env, value, result) { + if (!env) + return 1 /* napi_status.napi_invalid_arg */; + // @ts-expect-error + var envObject = emnapiCtx.envStore.get(env); + envObject.checkGCAccess(); + if (!value) + return envObject.setLastError(1 /* napi_status.napi_invalid_arg */); + if (!result) + return envObject.setLastError(1 /* napi_status.napi_invalid_arg */); + var h = emnapiCtx.handleStore.get(value); + result >>>= 0; + // eslint-disable-next-line @typescript-eslint/no-unused-vars + var r = h.isDate() ? 1 : 0; + var HEAP_DATA_VIEW = new DataView(wasmMemory.buffer), GET_HEAP_DATA_VIEW = function () { return HEAP_DATA_VIEW.buffer === wasmMemory.buffer ? HEAP_DATA_VIEW : (HEAP_DATA_VIEW = new DataView(wasmMemory.buffer)); }; + GET_HEAP_DATA_VIEW().setInt8(result, r, true); + return envObject.clearLastError(); + } + /** @__sig ippp */ + function napi_is_error(env, value, result) { + if (!env) + return 1 /* napi_status.napi_invalid_arg */; + // @ts-expect-error + var envObject = emnapiCtx.envStore.get(env); + envObject.checkGCAccess(); + if (!value) + return envObject.setLastError(1 /* napi_status.napi_invalid_arg */); + if (!result) + return envObject.setLastError(1 /* napi_status.napi_invalid_arg */); + var val = emnapiCtx.handleStore.get(value).value; + result >>>= 0; + // eslint-disable-next-line @typescript-eslint/no-unused-vars + var r = (val instanceof Error) ? 1 : 0; + var HEAP_DATA_VIEW = new DataView(wasmMemory.buffer), GET_HEAP_DATA_VIEW = function () { return HEAP_DATA_VIEW.buffer === wasmMemory.buffer ? HEAP_DATA_VIEW : (HEAP_DATA_VIEW = new DataView(wasmMemory.buffer)); }; + GET_HEAP_DATA_VIEW().setInt8(result, r, true); + return envObject.clearLastError(); + } + /** @__sig ippp */ + function napi_is_typedarray(env, value, result) { + if (!env) + return 1 /* napi_status.napi_invalid_arg */; + // @ts-expect-error + var envObject = emnapiCtx.envStore.get(env); + envObject.checkGCAccess(); + if (!value) + return envObject.setLastError(1 /* napi_status.napi_invalid_arg */); + if (!result) + return envObject.setLastError(1 /* napi_status.napi_invalid_arg */); + var h = emnapiCtx.handleStore.get(value); + result >>>= 0; + // eslint-disable-next-line @typescript-eslint/no-unused-vars + var r = h.isTypedArray() ? 1 : 0; + var HEAP_DATA_VIEW = new DataView(wasmMemory.buffer), GET_HEAP_DATA_VIEW = function () { return HEAP_DATA_VIEW.buffer === wasmMemory.buffer ? HEAP_DATA_VIEW : (HEAP_DATA_VIEW = new DataView(wasmMemory.buffer)); }; + GET_HEAP_DATA_VIEW().setInt8(result, r, true); + return envObject.clearLastError(); + } + /** @__sig ippp */ + function napi_is_buffer(env, value, result) { + if (!env) + return 1 /* napi_status.napi_invalid_arg */; + // @ts-expect-error + var envObject = emnapiCtx.envStore.get(env); + envObject.checkGCAccess(); + if (!value) + return envObject.setLastError(1 /* napi_status.napi_invalid_arg */); + if (!result) + return envObject.setLastError(1 /* napi_status.napi_invalid_arg */); + var h = emnapiCtx.handleStore.get(value); + result >>>= 0; + // eslint-disable-next-line @typescript-eslint/no-unused-vars + var r = h.isBuffer(emnapiCtx.feature.Buffer) ? 1 : 0; + var HEAP_DATA_VIEW = new DataView(wasmMemory.buffer), GET_HEAP_DATA_VIEW = function () { return HEAP_DATA_VIEW.buffer === wasmMemory.buffer ? HEAP_DATA_VIEW : (HEAP_DATA_VIEW = new DataView(wasmMemory.buffer)); }; + GET_HEAP_DATA_VIEW().setInt8(result, r, true); + return envObject.clearLastError(); + } + /** @__sig ippp */ + function napi_is_dataview(env, value, result) { + if (!env) + return 1 /* napi_status.napi_invalid_arg */; + // @ts-expect-error + var envObject = emnapiCtx.envStore.get(env); + envObject.checkGCAccess(); + if (!value) + return envObject.setLastError(1 /* napi_status.napi_invalid_arg */); + if (!result) + return envObject.setLastError(1 /* napi_status.napi_invalid_arg */); + var h = emnapiCtx.handleStore.get(value); + result >>>= 0; + // eslint-disable-next-line @typescript-eslint/no-unused-vars + var r = h.isDataView() ? 1 : 0; + var HEAP_DATA_VIEW = new DataView(wasmMemory.buffer), GET_HEAP_DATA_VIEW = function () { return HEAP_DATA_VIEW.buffer === wasmMemory.buffer ? HEAP_DATA_VIEW : (HEAP_DATA_VIEW = new DataView(wasmMemory.buffer)); }; + GET_HEAP_DATA_VIEW().setInt8(result, r, true); + return envObject.clearLastError(); + } + /** @__sig ipppp */ + function napi_strict_equals(env, lhs, rhs, result) { + // eslint-disable-next-line @typescript-eslint/no-unused-vars + var r; + if (!env) + return 1 /* napi_status.napi_invalid_arg */; + // @ts-expect-error + var envObject = emnapiCtx.envStore.get(env); + envObject.checkGCAccess(); + if (!envObject.tryCatch.isEmpty()) + return envObject.setLastError(10 /* napi_status.napi_pending_exception */); + if (!envObject.canCallIntoJs()) + return envObject.setLastError(envObject.moduleApiVersion >= 10 ? 23 /* napi_status.napi_cannot_run_js */ : 10 /* napi_status.napi_pending_exception */); + envObject.clearLastError(); + try { + if (!lhs) + return envObject.setLastError(1 /* napi_status.napi_invalid_arg */); + if (!rhs) + return envObject.setLastError(1 /* napi_status.napi_invalid_arg */); + if (!result) + return envObject.setLastError(1 /* napi_status.napi_invalid_arg */); + var lv = emnapiCtx.handleStore.get(lhs).value; + var rv = emnapiCtx.handleStore.get(rhs).value; + result >>>= 0; + r = (lv === rv) ? 1 : 0; + var HEAP_DATA_VIEW = new DataView(wasmMemory.buffer), GET_HEAP_DATA_VIEW = function () { return HEAP_DATA_VIEW.buffer === wasmMemory.buffer ? HEAP_DATA_VIEW : (HEAP_DATA_VIEW = new DataView(wasmMemory.buffer)); }; + GET_HEAP_DATA_VIEW().setInt8(result, r, true); + return envObject.getReturnStatus(); + } + catch (err) { + envObject.tryCatch.setError(err); + return envObject.setLastError(10 /* napi_status.napi_pending_exception */); + } + } + /** @__sig ipp */ + function napi_detach_arraybuffer(env, arraybuffer) { + if (!env) + return 1 /* napi_status.napi_invalid_arg */; + // @ts-expect-error + var envObject = emnapiCtx.envStore.get(env); + envObject.checkGCAccess(); + if (!arraybuffer) + return envObject.setLastError(1 /* napi_status.napi_invalid_arg */); + var value = emnapiCtx.handleStore.get(arraybuffer).value; + if (!(value instanceof ArrayBuffer)) { + if (typeof SharedArrayBuffer === 'function' && (value instanceof SharedArrayBuffer)) { + return envObject.setLastError(20 /* napi_status.napi_detachable_arraybuffer_expected */); + } + return envObject.setLastError(19 /* napi_status.napi_arraybuffer_expected */); + } + try { + var MessageChannel_1 = emnapiCtx.feature.MessageChannel; + var messageChannel = new MessageChannel_1(); + messageChannel.port1.postMessage(value, [value]); + } + catch (_) { + return envObject.setLastError(9 /* napi_status.napi_generic_failure */); + } + return envObject.clearLastError(); + } + /** @__sig ippp */ + function napi_is_detached_arraybuffer(env, arraybuffer, result) { + if (!env) + return 1 /* napi_status.napi_invalid_arg */; + // @ts-expect-error + var envObject = emnapiCtx.envStore.get(env); + envObject.checkGCAccess(); + if (!envObject.tryCatch.isEmpty()) + return envObject.setLastError(10 /* napi_status.napi_pending_exception */); + if (!envObject.canCallIntoJs()) + return envObject.setLastError(envObject.moduleApiVersion >= 10 ? 23 /* napi_status.napi_cannot_run_js */ : 10 /* napi_status.napi_pending_exception */); + envObject.clearLastError(); + try { + if (!arraybuffer) + return envObject.setLastError(1 /* napi_status.napi_invalid_arg */); + if (!result) + return envObject.setLastError(1 /* napi_status.napi_invalid_arg */); + var h = emnapiCtx.handleStore.get(arraybuffer); + result >>>= 0; + var HEAP_DATA_VIEW = new DataView(wasmMemory.buffer), GET_HEAP_DATA_VIEW = function () { return HEAP_DATA_VIEW.buffer === wasmMemory.buffer ? HEAP_DATA_VIEW : (HEAP_DATA_VIEW = new DataView(wasmMemory.buffer)); }; + if (h.isArrayBuffer() && h.value.byteLength === 0) { + try { + // eslint-disable-next-line no-new + new Uint8Array(h.value); + } + catch (_) { + GET_HEAP_DATA_VIEW().setInt8(result, 1, true); + return envObject.getReturnStatus(); + } + } + GET_HEAP_DATA_VIEW().setInt8(result, 0, true); + return envObject.getReturnStatus(); + } + catch (err) { + envObject.tryCatch.setError(err); + return envObject.setLastError(10 /* napi_status.napi_pending_exception */); + } + } + var valueOperationMod = /*#__PURE__*/ Object.freeze({ + __proto__: null, + napi_coerce_to_bool: napi_coerce_to_bool, + napi_coerce_to_number: napi_coerce_to_number, + napi_coerce_to_object: napi_coerce_to_object, + napi_coerce_to_string: napi_coerce_to_string, + napi_detach_arraybuffer: napi_detach_arraybuffer, + napi_instanceof: napi_instanceof, + napi_is_array: napi_is_array, + napi_is_arraybuffer: napi_is_arraybuffer, + napi_is_buffer: napi_is_buffer, + napi_is_dataview: napi_is_dataview, + napi_is_date: napi_is_date, + napi_is_detached_arraybuffer: napi_is_detached_arraybuffer, + napi_is_error: napi_is_error, + napi_is_typedarray: napi_is_typedarray, + napi_strict_equals: napi_strict_equals, + napi_typeof: napi_typeof, + node_api_is_sharedarraybuffer: node_api_is_sharedarraybuffer + }); + /** @__sig ipp */ + function napi_get_version(env, result) { + if (!env) + return 1 /* napi_status.napi_invalid_arg */; + var envObject = emnapiCtx.envStore.get(env); + if (!result) + return envObject.setLastError(1 /* napi_status.napi_invalid_arg */); + // eslint-disable-next-line @typescript-eslint/no-unused-vars + var NODE_API_SUPPORTED_VERSION_MAX = 10 /* Version.NODE_API_SUPPORTED_VERSION_MAX */; + var HEAP_DATA_VIEW = new DataView(wasmMemory.buffer), GET_HEAP_DATA_VIEW = function () { return HEAP_DATA_VIEW.buffer === wasmMemory.buffer ? HEAP_DATA_VIEW : (HEAP_DATA_VIEW = new DataView(wasmMemory.buffer)); }; + GET_HEAP_DATA_VIEW().setUint32(result, NODE_API_SUPPORTED_VERSION_MAX, true); + return envObject.clearLastError(); + } + var versionMod = /*#__PURE__*/ Object.freeze({ + __proto__: null, + napi_get_version: napi_get_version + }); + emnapiAWST.init(); + emnapiExternalMemory.init(); + emnapiExternalSAB.init(); + emnapiString.init(); + emnapiTSFN.init(); + PThread.init(); + napiModule.emnapi.syncMemory = $emnapiSyncMemory; + napiModule.emnapi.getMemoryAddress = $emnapiGetMemoryAddress; + napiModule.emnapi.acquireExternalSharedArrayBuffer = $emnapiAcquireExternalSharedArrayBuffer; + function addImports(mod) { + var keys = Object.keys(mod); + for (var i = 0; i < keys.length; ++i) { + var k = keys[i]; + if (k.indexOf('$') === 0) + continue; + if (k.indexOf('emnapi_') === 0) { + napiModule.imports.emnapi[k] = mod[k]; + } + else if (k.indexOf('_emnapi_') === 0 || k === 'napi_set_last_error' || k === 'napi_clear_last_error') { + napiModule.imports.env[k] = mod[k]; + } + else { + napiModule.imports.napi[k] = mod[k]; + } + } + } + addImports(asyncMod); + addImports(memoryMod); + addImports(asyncWorkMod); + addImports(utilMod); + addImports(convert2cMod); + addImports(convert2napiMod); + addImports(createMod); + addImports(globalMod); + addImports(wrapMod); + addImports(envMod); + addImports(emnapiMod); + addImports(errorMod); + addImports(functionMod); + addImports(lifeMod); + addImports(miscellaneousMod); + addImports(nodeMod); + addImports(promiseMod); + addImports(propertyMod); + addImports(scriptMod); + addImports(valueOperationMod); + addImports(versionMod); + napiModule.imports.napi.napi_create_threadsafe_function = napi_create_threadsafe_function; + napiModule.imports.napi.napi_get_threadsafe_function_context = napi_get_threadsafe_function_context; + napiModule.imports.napi.napi_call_threadsafe_function = napi_call_threadsafe_function; + napiModule.imports.napi.napi_acquire_threadsafe_function = napi_acquire_threadsafe_function; + napiModule.imports.napi.napi_release_threadsafe_function = napi_release_threadsafe_function; + napiModule.imports.napi.napi_unref_threadsafe_function = napi_unref_threadsafe_function; + napiModule.imports.napi.napi_ref_threadsafe_function = napi_ref_threadsafe_function; + return napiModule; + })(); + return napiModule; + } + + function loadNapiModuleImpl(loadFn, userNapiModule, wasmInput, options) { + // eslint-disable-next-line @typescript-eslint/consistent-type-assertions + options = options !== null && options !== void 0 ? options : {}; + var getMemory = options.getMemory; + var getTable = options.getTable; + var beforeInit = options.beforeInit; + if (getMemory != null && typeof getMemory !== 'function') { + throw new TypeError('options.getMemory is not a function'); + } + if (getTable != null && typeof getTable !== 'function') { + throw new TypeError('options.getTable is not a function'); + } + if (beforeInit != null && typeof beforeInit !== 'function') { + throw new TypeError('options.beforeInit is not a function'); + } + var napiModule; + var isLoad = typeof userNapiModule === 'object' && userNapiModule !== null; + if (isLoad) { + if (userNapiModule.loaded) { + throw new Error('napiModule has already loaded'); + } + napiModule = userNapiModule; + } + else { + napiModule = createNapiModule(options); + } + var wasi = options.wasi; + var wasiThreads; + var importObject = { + env: napiModule.imports.env, + napi: napiModule.imports.napi, + emnapi: napiModule.imports.emnapi + }; + if (wasi) { + wasiThreads = new WASIThreads(napiModule.childThread + ? { + wasi: wasi, + childThread: true, + postMessage: napiModule.postMessage + } + : { + wasi: wasi, + threadManager: napiModule.PThread, + waitThreadStart: napiModule.waitThreadStart + }); + Object.assign(importObject, typeof wasi.getImportObject === 'function' + ? wasi.getImportObject() + : { wasi_snapshot_preview1: wasi.wasiImport }); + Object.assign(importObject, wasiThreads.getImportObject()); + } + var overwriteImports = options.overwriteImports; + if (typeof overwriteImports === 'function') { + var newImportObject = overwriteImports(importObject); + if (typeof newImportObject === 'object' && newImportObject !== null) { + importObject = newImportObject; + } + } + return loadFn(wasmInput, importObject, function (err, source) { + if (err) { + throw err; + } + var originalInstance = source.instance; + var instance = originalInstance; + var originalExports = originalInstance.exports; + var exportMemory = 'memory' in originalExports; + var importMemory = 'memory' in importObject.env; + var memory = getMemory + ? getMemory(originalExports) + : exportMemory + ? originalExports.memory + : importMemory + ? importObject.env.memory + : undefined; + if (!memory) { + throw new Error('memory is neither exported nor imported'); + } + var table = getTable ? getTable(originalExports) : originalExports.__indirect_function_table; + if (wasi && !exportMemory) { + var exports_1 = Object.create(null); + Object.assign(exports_1, originalExports, { memory: memory }); + instance = { exports: exports_1 }; + } + var module = source.module; + if (wasi) { + instance = wasiThreads.initialize(instance, module, memory); + } + else { + napiModule.PThread.setup(module, memory); + } + var emnapiInit = function () { + if (beforeInit) { + beforeInit({ + instance: originalInstance, + module: module + }); + } + napiModule.init({ + instance: instance, + module: module, + memory: memory, + table: table + }); + var ret = { + instance: originalInstance, + module: module, + usedInstance: instance + }; + if (!isLoad) { + ret.napiModule = napiModule; + } + return ret; + }; + if (napiModule.PThread.shouldPreloadWorkers()) { + var poolReady = napiModule.PThread.loadWasmModuleToAllWorkers(); + if (loadFn === loadCallback) { + return poolReady.then(emnapiInit); + } + else { + throw new Error('Synchronous loading is not supported with worker pool (reuseWorker.size > 0)'); + } + } + return emnapiInit(); + }); + } + function loadCallback(wasmInput, importObject, callback) { + return load(wasmInput, importObject).then(function (source) { + return callback(null, source); + }, function (err) { + return callback(err); + }); + } + function loadSyncCallback(wasmInput, importObject, callback) { + var source; + try { + source = loadSync(wasmInput, importObject); + } + catch (err) { + return callback(err); + } + return callback(null, source); + } + /** @public */ + function loadNapiModule(napiModule, + /** Only support `BufferSource` or `WebAssembly.Module` on Node.js */ + wasmInput, options) { + if (typeof napiModule !== 'object' || napiModule === null) { + throw new TypeError('Invalid napiModule'); + } + return loadNapiModuleImpl(loadCallback, napiModule, wasmInput, options); + } + /** @public */ + function loadNapiModuleSync(napiModule, wasmInput, options) { + if (typeof napiModule !== 'object' || napiModule === null) { + throw new TypeError('Invalid napiModule'); + } + return loadNapiModuleImpl(loadSyncCallback, napiModule, wasmInput, options); + } + /** @public */ + function instantiateNapiModule( + /** Only support `BufferSource` or `WebAssembly.Module` on Node.js */ + wasmInput, options) { + return loadNapiModuleImpl(loadCallback, undefined, wasmInput, options); + } + /** @public */ + function instantiateNapiModuleSync(wasmInput, options) { + return loadNapiModuleImpl(loadSyncCallback, undefined, wasmInput, options); + } + + /****************************************************************************** + Copyright (c) Microsoft Corporation. + + Permission to use, copy, modify, and/or distribute this software for any + purpose with or without fee is hereby granted. + + THE SOFTWARE IS PROVIDED "AS IS" AND THE AUTHOR DISCLAIMS ALL WARRANTIES WITH + REGARD TO THIS SOFTWARE INCLUDING ALL IMPLIED WARRANTIES OF MERCHANTABILITY + AND FITNESS. IN NO EVENT SHALL THE AUTHOR BE LIABLE FOR ANY SPECIAL, DIRECT, + INDIRECT, OR CONSEQUENTIAL DAMAGES OR ANY DAMAGES WHATSOEVER RESULTING FROM + LOSS OF USE, DATA OR PROFITS, WHETHER IN AN ACTION OF CONTRACT, NEGLIGENCE OR + OTHER TORTIOUS ACTION, ARISING OUT OF OR IN CONNECTION WITH THE USE OR + PERFORMANCE OF THIS SOFTWARE. + ***************************************************************************** */ + /* global Reflect, Promise, SuppressedError, Symbol, Iterator */ + + var extendStatics = function(d, b) { + extendStatics = Object.setPrototypeOf || + ({ __proto__: [] } instanceof Array && function (d, b) { d.__proto__ = b; }) || + function (d, b) { for (var p in b) if (Object.prototype.hasOwnProperty.call(b, p)) d[p] = b[p]; }; + return extendStatics(d, b); + }; + + function __extends(d, b) { + if (typeof b !== "function" && b !== null) + throw new TypeError("Class extends value " + String(b) + " is not a constructor or null"); + extendStatics(d, b); + function __() { this.constructor = d; } + d.prototype = b === null ? Object.create(b) : (__.prototype = b.prototype, new __()); + } + + var __assign = function() { + __assign = Object.assign || function __assign(t) { + for (var s, i = 1, n = arguments.length; i < n; i++) { + s = arguments[i]; + for (var p in s) if (Object.prototype.hasOwnProperty.call(s, p)) t[p] = s[p]; + } + return t; + }; + return __assign.apply(this, arguments); + }; + + typeof SuppressedError === "function" ? SuppressedError : function (error, suppressed, message) { + var e = new Error(message); + return e.name = "SuppressedError", e.error = error, e.suppressed = suppressed, e; + }; + + /** @public */ + var MessageHandler = /*#__PURE__*/ (function (_super) { + __extends(MessageHandler, _super); + function MessageHandler(options) { + var _this = this; + if (typeof options.onLoad !== 'function') { + throw new TypeError('options.onLoad is not a function'); + } + var userOnError = options.onError; + _this = _super.call(this, __assign(__assign({}, options), { onError: function (err, type) { + var _a; + var emnapi_thread_crashed = (_a = _this.instance) === null || _a === void 0 ? void 0 : _a.exports.emnapi_thread_crashed; + if (typeof emnapi_thread_crashed === 'function') { + emnapi_thread_crashed(); + } /* else { + tryWakeUpPthreadJoin(this.instance!) + } */ + if (typeof userOnError === 'function') { + userOnError(err, type); + } + else { + throw err; + } + } })) || this; + _this.napiModule = undefined; + return _this; + } + MessageHandler.prototype.instantiate = function (data) { + var _this = this; + var source = this.onLoad(data); + var then = source.then; + if (typeof then === 'function') { + return source.then(function (result) { + _this.napiModule = result.napiModule; + return result; + }); + } + this.napiModule = source.napiModule; + return source; + }; + MessageHandler.prototype.handle = function (e) { + var _this = this; + var _a; + _super.prototype.handle.call(this, e); + if ((_a = e === null || e === void 0 ? void 0 : e.data) === null || _a === void 0 ? void 0 : _a.__emnapi__) { + var type = e.data.__emnapi__.type; + var payload_1 = e.data.__emnapi__.payload; + try { + if (type === 'async-worker-init') { + this.handleAfterLoad(e, function () { + _this.napiModule.initWorker(payload_1.arg, payload_1.func); + }); + } + } + catch (err) { + this.onError(err, type); + } + } + }; + return MessageHandler; + }(ThreadMessageHandler)); + // function tryWakeUpPthreadJoin (instance: WebAssembly.Instance): void { + // // https://github.com/WebAssembly/wasi-libc/blob/574b88da481569b65a237cb80daf9a2d5aeaf82d/libc-top-half/musl/src/thread/pthread_join.c#L18-L21 + // const pthread_self = instance.exports.pthread_self as () => number + // const memory = instance.exports.memory as WebAssembly.Memory + // if (typeof pthread_self === 'function') { + // const selfThread = pthread_self() + // if (selfThread && memory) { + // // https://github.com/WebAssembly/wasi-libc/blob/574b88da481569b65a237cb80daf9a2d5aeaf82d/libc-top-half/musl/src/internal/pthread_impl.h#L45 + // const detatchState = new Int32Array(memory.buffer, selfThread + 7 * 4 /** detach_state */, 1) + // Atomics.store(detatchState, 0, 0) + // Atomics.notify(detatchState, 0, Infinity) + // } + // } + // } + + var version = "1.11.3"; + + exports.MessageHandler = MessageHandler; + exports.ThreadManager = ThreadManager; + exports.ThreadMessageHandler = ThreadMessageHandler; + exports.WASIThreads = WASIThreads; + exports.createInstanceProxy = createInstanceProxy; + exports.createNapiModule = createNapiModule; + exports.instantiateNapiModule = instantiateNapiModule; + exports.instantiateNapiModuleSync = instantiateNapiModuleSync; + exports.isSharedArrayBuffer = isSharedArrayBuffer; + exports.isTrapError = isTrapError; + exports.loadNapiModule = loadNapiModule; + exports.loadNapiModuleSync = loadNapiModuleSync; + exports.version = version; + +})); diff --git a/dg-ui/node_modules/@tailwindcss/oxide-wasm32-wasi/node_modules/@emnapi/core/dist/emnapi-core.min.d.mts b/dg-ui/node_modules/@tailwindcss/oxide-wasm32-wasi/node_modules/@emnapi/core/dist/emnapi-core.min.d.mts new file mode 100644 index 0000000..fde8e40 --- /dev/null +++ b/dg-ui/node_modules/@tailwindcss/oxide-wasm32-wasi/node_modules/@emnapi/core/dist/emnapi-core.min.d.mts @@ -0,0 +1,428 @@ +/// + +import type { Context } from '@emnapi/runtime'; +import type { ReferenceOwnership } from '@emnapi/runtime'; +import type { Worker as Worker_2 } from 'worker_threads'; + +/** @public */ +export declare type BaseCreateOptions = { + filename?: string + nodeBinding?: NodeBinding + reuseWorker?: ThreadManagerOptionsMain['reuseWorker'] + asyncWorkPoolSize?: number + waitThreadStart?: MainThreadBaseOptions['waitThreadStart'] + onCreateWorker?: (info: CreateWorkerInfo) => any + print?: (str: string) => void + printErr?: (str: string) => void + postMessage?: (msg: any) => any +} + +/** @public */ +export declare interface BaseOptions { + wasi: WASIInstance; + version?: 'preview1'; + wasm64?: boolean; +} + +/** @public */ +export declare interface ChildThreadOptions extends BaseOptions { + childThread: true; + postMessage?: (data: any) => void; +} + +/** @public */ +export declare interface CleanupThreadPayload { + tid: number; +} + +/** @public */ +export declare interface CommandInfo { + type: T; + payload: CommandPayloadMap[T]; +} + +/** @public */ +export declare interface CommandPayloadMap { + load: LoadPayload; + loaded: LoadedPayload; + start: StartPayload; + 'cleanup-thread': CleanupThreadPayload; + 'terminate-all-threads': TerminateAllThreadsPayload; + 'spawn-thread': SpawnThreadPayload; +} + +/** @public */ +export declare type CommandType = keyof CommandPayloadMap; + +/** @public */ +export declare function createInstanceProxy(instance: WebAssembly.Instance, memory?: WebAssembly.Memory | (() => WebAssembly.Memory)): WebAssembly.Instance; + +/** @public */ +export declare function createNapiModule ( +options: CreateOptions +): NapiModule + +/** @public */ +export declare type CreateOptions = BaseCreateOptions & ({ + context: Context + childThread?: boolean +} | { + context?: Context + childThread: true +}) + +/** @public */ +export declare interface CreateWorkerInfo { + type: 'thread' | 'async-work' + name: string +} + +/** @public */ +export declare interface InitOptions { + instance: WebAssembly.Instance + module: WebAssembly.Module + memory?: WebAssembly.Memory + table?: WebAssembly.Table +} + +export declare type InputType = string | URL | Response | BufferSource | WebAssembly.Module; + +/** @public */ +export declare interface InstantiatedSource extends LoadedSource { + napiModule: NapiModule; +} + +/** @public */ +export declare function instantiateNapiModule( +/** Only support `BufferSource` or `WebAssembly.Module` on Node.js */ +wasmInput: InputType | Promise, options: InstantiateOptions): Promise; + +/** @public */ +export declare function instantiateNapiModuleSync(wasmInput: BufferSource | WebAssembly.Module, options: InstantiateOptions): InstantiatedSource; + +/** @public */ +export declare type InstantiateOptions = CreateOptions & LoadOptions; + +/** @public */ +export declare function isSharedArrayBuffer(value: any): value is SharedArrayBuffer; + +/** @public */ +export declare function isTrapError(e: Error): e is WebAssembly.RuntimeError; + +/** @public */ +export declare interface LoadedPayload { +} + +/** @public */ +export declare interface LoadedSource extends WebAssembly.WebAssemblyInstantiatedSource { + usedInstance: WebAssembly.Instance; +} + +/** @public */ +export declare function loadNapiModule(napiModule: NapiModule, +/** Only support `BufferSource` or `WebAssembly.Module` on Node.js */ +wasmInput: InputType | Promise, options?: LoadOptions): Promise; + +/** @public */ +export declare function loadNapiModuleSync(napiModule: NapiModule, wasmInput: BufferSource | WebAssembly.Module, options?: LoadOptions): LoadedSource; + +/** @public */ +export declare interface LoadOptions { + wasi?: WASIInstance; + overwriteImports?: (importObject: WebAssembly.Imports) => WebAssembly.Imports; + beforeInit?: (source: WebAssembly.WebAssemblyInstantiatedSource) => void; + getMemory?: (exports: WebAssembly.Exports) => WebAssembly.Memory; + getTable?: (exports: WebAssembly.Exports) => WebAssembly.Table; +} + +/** @public */ +export declare interface LoadPayload { + wasmModule: WebAssembly.Module; + wasmMemory: WebAssembly.Memory; + sab?: Int32Array; +} + +/** @public */ +export declare interface MainThreadBaseOptions extends BaseOptions { + waitThreadStart?: boolean | number; +} + +/** @public */ +export declare type MainThreadOptions = MainThreadOptionsWithThreadManager | MainThreadOptionsCreateThreadManager; + +/** @public */ +export declare interface MainThreadOptionsCreateThreadManager extends MainThreadBaseOptions, ThreadManagerOptionsMain { +} + +/** @public */ +export declare interface MainThreadOptionsWithThreadManager extends MainThreadBaseOptions { + threadManager?: ThreadManager | (() => ThreadManager); +} + +/** @public */ +export declare interface MessageEventData { + __emnapi__: CommandInfo; +} + +/** @public */ +export declare class MessageHandler extends ThreadMessageHandler { + napiModule: NapiModule | undefined; + constructor(options: MessageHandlerOptions); + instantiate(data: LoadPayload): InstantiatedSource | PromiseLike; + handle(e: WorkerMessageEvent): void; +} + +/** @public */ +export declare interface MessageHandlerOptions extends ThreadMessageHandlerOptions { + onLoad: (data: LoadPayload) => InstantiatedSource | PromiseLike; +} + +/** @public */ +export declare interface NapiModule { + imports: { + env: any + napi: any + emnapi: any + } + exports: any + loaded: boolean + filename: string + childThread: boolean + emnapi: { + /** + * Synchronize data between the wasm memory and an ArrayBuffer / view. + * + * Note: when a non-shared wasm memory has grown, a view over the + * detached old buffer is re-created over the current buffer through the + * intrinsic base-class constructor, so for view inputs the returned view + * may be a base-class instance (e.g. `Uint8Array` or `DataView`) + * instead of the subclass that was passed in. + */ + syncMemory ( + js_to_wasm: boolean, + arrayBufferOrView: T, + offset?: number, + len?: number + ): T extends ArrayBufferView ? ArrayBufferView : T + getMemoryAddress (arrayBufferOrView: ArrayBuffer | ArrayBufferView): PointerInfo + addSendListener (worker: any): boolean + } + + init (options: InitOptions): any + initWorker (arg: number, func: [number, number]): void + postMessage?: (msg: any) => any + + waitThreadStart: boolean | number + /* Excluded from this release type: PThread */} + +/** @public */ +export declare interface NodeBinding { + node: { + emitAsyncInit: Function + emitAsyncDestroy: Function + makeCallback: Function + } + napi: { + asyncInit: Function + asyncDestroy: Function + makeCallback: Function + } +} + +/** @public */ +export declare interface PointerInfo { + address: number + ownership: ReferenceOwnership + runtimeAllocated: 0 | 1 +} + +/** @public */ +export declare interface ReuseWorkerOptions { + /** + * @see {@link https://emscripten.org/docs/tools_reference/settings_reference.html#pthread-pool-size | PTHREAD_POOL_SIZE} + */ + size: number; + /** + * @see {@link https://emscripten.org/docs/tools_reference/settings_reference.html#pthread-pool-size-strict | PTHREAD_POOL_SIZE_STRICT} + */ + strict?: boolean; +} + +/** @public */ +export declare interface SpawnThreadPayload { + startArg: number; + errorOrTid: number; +} + +/** @public */ +export declare interface StartPayload { + tid: number; + arg: number; + sab?: Int32Array; +} + +/** @public */ +export declare interface StartResult { + exitCode: number; + instance: WebAssembly.Instance; +} + +/** @public */ +export declare interface TerminateAllThreadsPayload { +} + +/** @public */ +export declare class ThreadManager { + unusedWorkers: WorkerLike[]; + pthreads: Record; + get nextWorkerID(): number; + wasmModule: WebAssembly.Module | null; + wasmMemory: WebAssembly.Memory | null; + private readonly messageEvents; + private readonly _childThread; + private readonly _onCreateWorker; + private readonly _reuseWorker; + private readonly _beforeLoad?; + /* Excluded from this release type: printErr */ + threadSpawn?: ((startArg: number, errorOrTid?: number) => number); + constructor(options: ThreadManagerOptions); + init(): void; + initMainThread(): void; + private preparePool; + shouldPreloadWorkers(): boolean; + loadWasmModuleToAllWorkers(): Promise; + preloadWorkers(): Promise; + setup(wasmModule: WebAssembly.Module, wasmMemory: WebAssembly.Memory): void; + markId(worker: WorkerLike): number; + returnWorkerToPool(worker: WorkerLike): void; + loadWasmModuleToWorker(worker: WorkerLike, sab?: Int32Array): Promise; + allocateUnusedWorker(): WorkerLike; + getNewWorker(sab?: Int32Array): WorkerLike | undefined; + cleanThread(worker: WorkerLike, tid: number, force?: boolean): void; + terminateWorker(worker: WorkerLike): void; + terminateAllThreads(): void; + addMessageEventListener(worker: WorkerLike, onMessage: (e: WorkerMessageEvent) => void): () => void; + fireMessageEvent(worker: WorkerLike, e: WorkerMessageEvent): void; +} + +/** @public */ +export declare type ThreadManagerOptions = ThreadManagerOptionsMain | ThreadManagerOptionsChild; + +/** @public */ +export declare interface ThreadManagerOptionsBase { + printErr?: (message: string) => void; + threadSpawn?: (startArg: number, errorOrTid?: number) => number; +} + +/** @public */ +export declare interface ThreadManagerOptionsChild extends ThreadManagerOptionsBase { + childThread: true; +} + +/** @public */ +export declare interface ThreadManagerOptionsMain extends ThreadManagerOptionsBase { + beforeLoad?: (worker: WorkerLike) => any; + reuseWorker?: boolean | number | ReuseWorkerOptions; + onCreateWorker: WorkerFactory; + childThread?: false; +} + +/** @public */ +export declare class ThreadMessageHandler { + protected instance: WebAssembly.Instance | undefined; + private messagesBeforeLoad; + protected postMessage: (message: any) => void; + protected onLoad?: (data: LoadPayload) => WebAssembly.WebAssemblyInstantiatedSource | PromiseLike; + protected onError: (error: Error, type: WorkerMessageType) => void; + constructor(options?: ThreadMessageHandlerOptions); + /** @virtual */ + instantiate(data: LoadPayload): WebAssembly.WebAssemblyInstantiatedSource | PromiseLike; + /** @virtual */ + handle(e: WorkerMessageEvent>): void; + private _load; + private _start; + protected _loaded(err: Error | null, source: WebAssembly.WebAssemblyInstantiatedSource | null, payload: LoadPayload): void; + protected handleAfterLoad(e: E, f: (e: E) => void): void; +} + +/** @public */ +export declare interface ThreadMessageHandlerOptions { + onLoad?: (data: LoadPayload) => WebAssembly.WebAssemblyInstantiatedSource | PromiseLike; + onError?: (error: Error, type: WorkerMessageType) => void; + postMessage?: (message: any) => void; +} + +export declare const version: string; + +/** @public */ +export declare interface WASIInstance { + readonly wasiImport?: Record; + initialize(instance: object): void; + start(instance: object): number; + getImportObject?(): any; +} + +/** @public */ +export declare class WASIThreads { + PThread: ThreadManager | undefined; + private wasmMemory; + private wasmInstance; + private readonly threadSpawn; + readonly childThread: boolean; + private readonly postMessage; + readonly wasi: WASIInstance; + constructor(options: WASIThreadsOptions); + getImportObject(): { + wasi: WASIThreadsImports; + }; + setup(wasmInstance: WebAssembly.Instance, wasmModule: WebAssembly.Module, wasmMemory?: WebAssembly.Memory): void; + preloadWorkers(): Promise; + /** + * It's ok to call this method to a WASI command module. + * + * in child thread, must call this method instead of {@link WASIThreads.start} even if it's a WASI command module + * + * @returns A proxied WebAssembly instance if in child thread, other wise the original instance + */ + initialize(instance: WebAssembly.Instance, module: WebAssembly.Module, memory?: WebAssembly.Memory): WebAssembly.Instance; + /** + * Equivalent to calling {@link WASIThreads.initialize} and then calling {@link WASIInstance.start} + * ```js + * this.initialize(instance, module, memory) + * this.wasi.start(instance) + * ``` + */ + start(instance: WebAssembly.Instance, module: WebAssembly.Module, memory?: WebAssembly.Memory): StartResult; + terminateAllThreads(): void; +} + +/** @public */ +export declare interface WASIThreadsImports { + 'thread-spawn': (startArg: number, errorOrTid?: number) => number; +} + +/** @public */ +export declare type WASIThreadsOptions = MainThreadOptions | ChildThreadOptions; + +/** @public */ +export declare type WorkerFactory = (ctx: { + type: string; + name: string; +}) => WorkerLike; + +/** @public */ +export declare type WorkerLike = (Worker | Worker_2) & { + whenLoaded?: Promise; + loaded?: boolean; + __emnapi_tid?: number; +}; + +/** @public */ +export declare interface WorkerMessageEvent { + data: T; +} + +/** @public */ +export declare type WorkerMessageType = 'load' | 'start'; + +export { } diff --git a/dg-ui/node_modules/@tailwindcss/oxide-wasm32-wasi/node_modules/@emnapi/core/dist/emnapi-core.min.js b/dg-ui/node_modules/@tailwindcss/oxide-wasm32-wasi/node_modules/@emnapi/core/dist/emnapi-core.min.js new file mode 100644 index 0000000..425fcc1 --- /dev/null +++ b/dg-ui/node_modules/@tailwindcss/oxide-wasm32-wasi/node_modules/@emnapi/core/dist/emnapi-core.min.js @@ -0,0 +1 @@ +!function(e,r){"object"==typeof exports&&"undefined"!=typeof module?r(exports):"function"==typeof define&&define.amd?define(["exports"],r):r((e="undefined"!=typeof globalThis?globalThis:e||self).emnapiCore={})}(this,function(e){var r="undefined"!=typeof WebAssembly?WebAssembly:"undefined"!=typeof WXWebAssembly?WXWebAssembly:void 0;function t(e){if(e&&"object"!=typeof e)throw new TypeError("imports must be an object or undefined");return!0}function n(e,a){if(!e)throw new TypeError("Invalid wasm source");t(a),a=null!=a?a:{};try{var o="object"==typeof e&&null!==e&&"then"in e?e.then:void 0;if("function"==typeof o)return o.call(e,function(e){return n(e,a)})}catch(e){}if(e instanceof ArrayBuffer||ArrayBuffer.isView(e))return r.instantiate(e,a);if(e instanceof r.Module)return r.instantiate(e,a).then(function(r){return{instance:r,module:e}});if("undefined"!=typeof Response&&e instanceof Response)return e.arrayBuffer().then(function(e){return r.instantiate(e,a)});var i="string"==typeof e;if(i||"undefined"!=typeof URL&&e instanceof URL){if(i&&"undefined"!=typeof wx&&"undefined"!=typeof __wxConfig)return r.instantiate(e,a);if("function"!=typeof fetch)throw new TypeError("wasm source can not be a string or URL in this environment");if("function"!=typeof r.instantiateStreaming)return n(fetch(e),a);try{return r.instantiateStreaming(fetch(e),a).catch(function(){return n(fetch(e),a)})}catch(r){return n(fetch(e),a)}}throw new TypeError("Invalid wasm source")}var a="undefined"!=typeof WebAssembly?WebAssembly:"undefined"!=typeof WXWebAssembly?WXWebAssembly:void 0,o="object"==typeof process&&null!==process&&"object"==typeof process.versions&&null!==process.versions&&"string"==typeof process.versions.node;function i(e){return"function"==typeof(null==e?void 0:e.postMessage)?e.postMessage:"function"==typeof postMessage?postMessage:void 0}function s(e){return"function"==typeof SharedArrayBuffer&&e instanceof SharedArrayBuffer||"[object SharedArrayBuffer]"===Object.prototype.toString.call(e)}function f(e){try{return e instanceof a.RuntimeError}catch(e){return!1}}function u(e,r){return{__emnapi__:{type:e,payload:r}}}function c(e){if(e){if(!s(e.buffer))throw new Error("Multithread features require shared wasm memory. Try to compile with `-matomics -mbulk-memory` and use `--import-memory --shared-memory` during linking, then create WebAssembly.Memory with `shared: true` option")}else if("undefined"==typeof SharedArrayBuffer)throw new Error("Current environment does not support SharedArrayBuffer, threads are not available!")}var l=0,d=function(){function e(e){var r;if(this.unusedWorkers=[],this.pthreads=Object.create(null),this.wasmModule=null,this.wasmMemory=null,this.messageEvents=new WeakMap,!e)throw new TypeError("ThreadManager(): options is not provided");this._childThread="childThread"in e&&Boolean(e.childThread),this._childThread?(this._onCreateWorker=void 0,this._reuseWorker=!1,this._beforeLoad=void 0):(this._onCreateWorker=e.onCreateWorker,this._reuseWorker=function(e){var r;if("boolean"==typeof e)return!!e&&{size:0,strict:!1};if("number"==typeof e){if(!(e>=0))throw new RangeError("reuseWorker: size must be a non-negative integer");return{size:e,strict:!1}}if(!e)return!1;var t=null!==(r=Number(e.size))&&void 0!==r?r:0,n=Boolean(e.strict);if(!(t>0)&&n)throw new RangeError("reuseWorker: size must be set to positive integer if strict is set to true");return{size:t,strict:n}}(e.reuseWorker),this._beforeLoad=e.beforeLoad),this.printErr=null!==(r=e.printErr)&&void 0!==r?r:console.error.bind(console),this.threadSpawn=e.threadSpawn}return Object.defineProperty(e.prototype,"nextWorkerID",{get:function(){return l},enumerable:!1,configurable:!0}),e.prototype.init=function(){this._childThread||this.initMainThread()},e.prototype.initMainThread=function(){this.preparePool()},e.prototype.preparePool=function(){if(this._reuseWorker&&this._reuseWorker.size)for(var e=this._reuseWorker.size;e--;){var r=this.allocateUnusedWorker();o&&(r.once("message",function(){}),r.unref())}},e.prototype.shouldPreloadWorkers=function(){return!this._childThread&&this._reuseWorker&&this._reuseWorker.size>0},e.prototype.loadWasmModuleToAllWorkers=function(){for(var e=this,r=Array(this.unusedWorkers.length),t=function(e){var t=n.unusedWorkers[e];o&&t.ref(),r[e]=n.loadWasmModuleToWorker(t).then(function(e){return o&&t.unref(),e},function(e){throw o&&t.unref(),e})},n=this,a=0;a>>0,a=e.buffer;return n+y>a.byteLength&&function(e){if(void 0===g)return!1;try{return g.call(e),!0}catch(e){return!1}}(a)&&(t?e.grow(BigInt(0)):e.grow(0),a=e.buffer),new Int32Array(a,n,2)}var b=function(){function e(e){var r=this;if(!e)throw new TypeError("WASIThreads(): options is not provided");if(!e.wasi)throw new TypeError("WASIThreads(): options.wasi is not provided");h.set(this,new WeakSet);var t=e.wasi;!function(e,r){var t=h.get(e);if(t.has(r))return;var n=e,a=r.wasiImport;if(a){var o=a.proc_exit;a.proc_exit=function(e){return n.terminateAllThreads(),o.call(this,e)}}if(!n.childThread){var i=r.start;"function"==typeof i&&(r.start=function(e){try{return i.call(this,e)}catch(e){throw f(e)&&n.terminateAllThreads(),e}})}t.add(r)}(this,t),this.wasi=t,this.childThread="childThread"in e&&Boolean(e.childThread),this.PThread=void 0,"threadManager"in e?"function"==typeof e.threadManager?this.PThread=e.threadManager():this.PThread=e.threadManager:this.childThread||(this.PThread=new d(e),this.PThread.init());var n=!1;"waitThreadStart"in e&&(n="number"==typeof e.waitThreadStart?e.waitThreadStart:Boolean(e.waitThreadStart));var s=i(e);if(this.childThread&&"function"!=typeof s)throw new TypeError("options.postMessage is not a function");this.postMessage=s;var l=Boolean(e.wasm64),p=function(e,t){var i,f=void 0!==t;try{c(r.wasmMemory)}catch(e){if(null===(i=r.PThread)||void 0===i||i.printErr(e.stack),f){var d=w(r.wasmMemory,t,l);return Atomics.store(d,0,1),Atomics.store(d,1,6),Atomics.notify(d,1),1}return-6}if(!f){var p=r.wasmInstance.exports.malloc;if(!(t=l?Number(p(BigInt(8))):p(8)>>>0))return-48}var v=r.wasmInstance.exports.free,h=l?function(e){v(BigInt(e))}:v,y=w(r.wasmMemory,t,l);if(Atomics.store(y,0,0),Atomics.store(y,1,0),r.childThread){s(u("spawn-thread",{startArg:e,errorOrTid:t})),Atomics.wait(y,1,0);var g=Atomics.load(y,0),b=Atomics.load(y,1);return f?g:(h(t),g?-b:b)}var _,E,m,L=n||0===n;L&&(_=new Int32Array(new SharedArrayBuffer(8208)),Atomics.store(_,0,0));var A=r.PThread;try{if(!(E=A.getNewWorker(_)))throw new Error("failed to get new worker");if(m=A.markId(E),o&&E.unref(),E.postMessage(u("start",{tid:m,arg:e,sab:_})),L){if("number"==typeof n){if("timed-out"===Atomics.wait(_,0,0,n))throw new Error("Spawning thread timed out. Please check if the worker is created successfully and if message is handled properly in the worker.")}else Atomics.wait(_,0,0);if(Atomics.load(_,0)>1)throw function(e){var r,t,n=new Int32Array(e);if(Atomics.load(n,0)<=1)return null;var o=Atomics.load(n,1),i=Atomics.load(n,2),s=Atomics.load(n,3),f=new Uint8Array(e),u=f.slice(16,16+o),c=f.slice(16+o,16+o+i),l=f.slice(16+o+i,16+o+i+s),d=(new TextDecoder).decode(u),p=(new TextDecoder).decode(c),v=(new TextDecoder).decode(l),h=new(null!==(r=globalThis[d])&&void 0!==r?r:"RuntimeError"===d&&null!==(t=a.RuntimeError)&&void 0!==t?t:Error)(p);return Object.defineProperty(h,"stack",{value:v,writable:!0,enumerable:!1,configurable:!0}),h}(_.buffer)}}catch(e){if(void 0!==E&&void 0!==m)try{A.cleanThread(E,m,!0)}catch(e){}return Atomics.store(y,0,1),Atomics.store(y,1,6),Atomics.notify(y,1),null==A||A.printErr(e.stack),f?1:(h(t),-6)}return Atomics.store(y,0,0),Atomics.store(y,1,m),Atomics.notify(y,1),L||E.whenLoaded.catch(function(e){throw delete E.whenLoaded,A.cleanThread(E,m,!0),e}),f?0:(h(t),m)};this.threadSpawn=p,this.PThread&&(this.PThread.threadSpawn=p)}return e.prototype.getImportObject=function(){return{wasi:{"thread-spawn":this.threadSpawn}}},e.prototype.setup=function(e,r,t){null!=t||(t=e.exports.memory),this.wasmInstance=e,this.wasmMemory=t,this.PThread&&this.PThread.setup(r,t)},e.prototype.preloadWorkers=function(){return this.PThread?this.PThread.preloadWorkers():Promise.resolve([])},e.prototype.initialize=function(e,r,t){var n=e.exports;null!=t||(t=n.memory),this.childThread&&(e=v(e,t)),this.setup(e,r,t);var a=this.wasi;if("_start"in n&&"function"==typeof n._start)if(this.childThread){a.start(e);try{a[_(a,"kStarted")]=!1}catch(e){}}else!function(e,r){var t=_(e,["kInstance","kSetMemory"]),n=t[0],a=t[1];e[n]=r,e[a](r.exports.memory)}(a,e);else a.initialize(e);return e},e.prototype.start=function(e,r,t){var n=e.exports;return null!=t||(t=n.memory),this.childThread&&(e=v(e,t)),this.setup(e,r,t),{exitCode:this.wasi.start(e),instance:e}},e.prototype.terminateAllThreads=function(){var e;this.childThread?this.postMessage(u("terminate-all-threads",{})):null===(e=this.PThread)||void 0===e||e.terminateAllThreads()},e}();function _(e,r){var t=Object.getOwnPropertySymbols(e),n=function(e){return function(r){return r.description?r.description===e:r.toString()==="Symbol(".concat(e,")")}};return Array.isArray(r)?r.map(function(e){return t.filter(n(e))[0]}):t.filter(n(r))[0]}var E=function(){function e(e){var r=i(e);if("function"!=typeof r)throw new TypeError("options.postMessage is not a function");this.postMessage=r,this.onLoad=null==e?void 0:e.onLoad,this.onError="function"==typeof(null==e?void 0:e.onError)?e.onError:function(e,r){throw r},this.instance=void 0,this.messagesBeforeLoad=[]}return e.prototype.instantiate=function(e){if("function"==typeof this.onLoad)return this.onLoad(e);throw new Error("ThreadMessageHandler.prototype.instantiate is not implemented")},e.prototype.handle=function(e){var r,t=this;if(null===(r=null==e?void 0:e.data)||void 0===r?void 0:r.__emnapi__){var n=e.data.__emnapi__.type,a=e.data.__emnapi__.payload;try{"load"===n?this._load(a):"start"===n&&this.handleAfterLoad(e,function(){t._start(a)})}catch(e){this.onError(e,n)}}},e.prototype._load=function(e){var r=this;if(void 0===this.instance){var t;try{t=this.instantiate(e)}catch(r){return void this._loaded(r,null,e)}var n=t&&"then"in t?t.then:void 0;"function"==typeof n?n.call(t,function(t){r._loaded(null,t,e)},function(t){r._loaded(t,null,e)}):this._loaded(null,t,e)}},e.prototype._start=function(e){var r=this.instance.exports.wasi_thread_start;if("function"!=typeof r){var t=new TypeError("wasi_thread_start is not exported");throw m(e.sab,2,t),t}var n=this.postMessage,a=e.tid,o=e.arg;m(e.sab,1);try{r(a,o)}catch(t){if("unwind"!==t)throw t;return}n(u("cleanup-thread",{tid:a}))},e.prototype._loaded=function(e,r,t){if(e)throw m(t.sab,2,e),e;if(null==r){var n=new TypeError("onLoad should return an object");throw m(t.sab,2,n),n}var a=r.instance;if(!a){var o=new TypeError('onLoad should return an object which includes "instance"');throw m(t.sab,2,o),o}this.instance=a,(0,this.postMessage)(u("loaded",{}));var i=this.messagesBeforeLoad;this.messagesBeforeLoad=[];for(var s=0;s1&&t){var a=t.name,o=t.message,i=t.stack,s=(new TextEncoder).encode(a),f=(new TextEncoder).encode(o),u=(new TextEncoder).encode(i);Atomics.store(n,1,s.length),Atomics.store(n,2,f.length),Atomics.store(n,3,u.length);var c=new Uint8Array(e);c.set(s,16),c.set(f,16+s.length),c.set(u,16+s.length+f.length)}}(e.buffer,r,t),Atomics.notify(e,0))}function L(e){var t=function(){var t,n,a,o,i,s="object"==typeof process&&null!==process&&"object"==typeof process.versions&&null!==process.versions&&"string"==typeof process.versions.node,f=Boolean(e.childThread),u="number"==typeof e.waitThreadStart?e.waitThreadStart:Boolean(e.waitThreadStart);function c(e){if("function"==typeof r.RuntimeError)throw new r.RuntimeError(e);throw Error(e)}var l,p,v,h={imports:{env:{},napi:{},emnapi:{}},exports:{},emnapi:{},loaded:!1,filename:"",childThread:f,initWorker:void 0,waitThreadStart:u,PThread:void 0,init:function(e){if(h.loaded)return h.exports;if(!e)throw new TypeError("Invalid napi init options");var s=e.instance;if(!(null==s?void 0:s.exports))throw new TypeError("Invalid wasm instance");t=s;var f=s.exports,u=e.module,d=e.memory||f.memory,v=e.table||f.__indirect_function_table;if(!(u instanceof r.Module))throw new TypeError("Invalid wasm module");if(!(d instanceof r.Memory))throw new TypeError("Invalid wasm memory");if(!(v instanceof r.Table))throw new TypeError("Invalid wasm table");if(n=d,a=v,"function"!=typeof f.malloc)throw new TypeError("malloc is not exported");if("function"!=typeof f.free)throw new TypeError("free is not exported");if(o=f.malloc,i=f.free,!h.childThread){var y=8,g=s.exports.node_api_module_get_api_version_v1;"function"==typeof g&&(y=g());var w=h.envObject||(h.envObject=l.createEnv(h.filename,y,function(e){return a.get(e)},function(e){return a.get(e)},c,p)),b=l.openScope(w);try{w.callIntoModule(function(e){var r=h.exports,t=b.add(r),n=(0,s.exports.napi_register_wasm_v1)(e.id,t.id);h.exports=n?l.handleStore.get(n).value:r})}catch(e){if("unwind"!==e)throw e}finally{l.closeScope(w,b)}return h.loaded=!0,delete h.envObject,h.exports}}},y=void 0;if(f){l=null==e?void 0:e.context;var g="function"==typeof e.postMessage?e.postMessage:"function"==typeof postMessage?postMessage:void 0;if("function"!=typeof g)throw new TypeError("No postMessage found");h.postMessage=g}else{var w=e.context;if("object"!=typeof w||null===w)throw new TypeError("Invalid `options.context`. Use `import { getDefaultContext } from '@emnapi/runtime'`");l=w}if("string"==typeof e.filename&&(h.filename=e.filename),"function"==typeof e.onCreateWorker&&(y=e.onCreateWorker),"function"==typeof e.print?e.print:console.log.bind(console),v="function"==typeof e.printErr?e.printErr:console.warn.bind(console),"nodeBinding"in e){var b=e.nodeBinding;if("object"!=typeof b||null===b)throw new TypeError("Invalid `options.nodeBinding`. Use @emnapi/node-binding package");p=b}var _=0;if("asyncWorkPoolSize"in e){if("number"!=typeof e.asyncWorkPoolSize)throw new TypeError("options.asyncWorkPoolSize must be a integer");(_=e.asyncWorkPoolSize|0)>1024?_=1024:_<-1024&&(_=-1024)}var E=!f&&_<=0;function m(){return Math.abs(_)}function L(e){if(!e)return!1;if(e._emnapiSendListener)return!0;var r=function(e){var r=(s?e:e.data).__emnapi__;if(r&&"async-send"===r.type)if(f){(0,h.postMessage)({__emnapi__:r})}else{var t=r.payload.callback;a.get(t)(r.payload.data)}};return e._emnapiSendListener={handler:r,dispose:function(){s?e.off("message",r):e.removeEventListener("message",r,!1),delete e._emnapiSendListener}},s?e.on("message",r):e.addEventListener("message",r,!1),!0}h.imports.env._emnapi_async_work_pool_size=m,h.emnapi.addSendListener=L;var A=new d(f?{printErr:v,childThread:!0}:{printErr:v,beforeLoad:function(e){L(e)},reuseWorker:e.reuseWorker,onCreateWorker:y});function S(e,r){l.feature.setImmediate(function(){a.get(e)(r)})}function C(e,r){Promise.resolve().then(function(){a.get(e)(r)})}function V(e,r){var t,a=[r>>>0,(t=r,+Math.abs(t)>=1?t>0?(0|Math.min(+Math.floor(t/4294967296),4294967295))>>>0:~~+Math.ceil((t-+(~~t>>>0))/4294967296)>>>0:0)],o=new DataView(n.buffer),i=function(){return o.buffer===n.buffer?o:o=new DataView(n.buffer)};i().setInt32(e,a[0],!0),i().setInt32(e+4,a[1],!0)}h.PThread=A;var k,I=Object.freeze({__proto__:null,$emnapiSetValueI64:V,_emnapi_call_finalizer:function(e,r,t,n,a){t>>>=0,l.envStore.get(r).callFinalizerInternal(e,t,n,a)},_emnapi_callback_into_module:function(e,r,t,n,o){var i=l.envStore.get(r),s=l.openScope(i);try{i.callbackIntoModule(Boolean(e),function(){a.get(t)(r,n)})}catch(e){throw l.closeScope(i,s),o&&l.closeScope(i),e}l.closeScope(i,s)},_emnapi_close_handle_scope:function(e){return l.closeScope()},_emnapi_ctx_decrease_waiting_request_counter:function(){l.decreaseWaitingRequestCounter()},_emnapi_ctx_increase_waiting_request_counter:function(){l.increaseWaitingRequestCounter()},_emnapi_get_node_version:function(e,r,t){e>>>=0,r>>>=0,t>>>=0;var a="object"==typeof process&&null!==process&&"object"==typeof process.versions&&null!==process.versions&&"string"==typeof process.versions.node?process.versions.node.split(".").map(function(e){return Number(e)}):[0,0,0],o=new DataView(n.buffer),i=function(){return o.buffer===n.buffer?o:o=new DataView(n.buffer)};i().setUint32(e,a[0],!0),i().setUint32(r,a[1],!0),i().setUint32(t,a[2],!0)},_emnapi_get_now:function(){return performance.timeOrigin+performance.now()},_emnapi_is_main_browser_thread:function(){return"undefined"==typeof window||"undefined"==typeof document||s?0:1},_emnapi_is_main_runtime_thread:function(){return f?0:1},_emnapi_next_tick:C,_emnapi_open_handle_scope:function(){return l.openScope().id},_emnapi_runtime_keepalive_pop:function(){},_emnapi_runtime_keepalive_push:function(){},_emnapi_set_immediate:S,_emnapi_unwind:function(){throw"unwind"},napi_clear_last_error:function(e){return l.envStore.get(e).clearLastError()},napi_set_last_error:function(e,r,t,n){return l.envStore.get(e).setLastError(r,t,n)}});function D(e){var r=new DataView(n.buffer).getInt32(e+20,!0);return A.pthreads[r]}var T=new Promise(function(e){k=function(){T.ready=!0,e()}});T.ready=!1;var U=Object.freeze({__proto__:null,_emnapi_after_uvthreadpool_ready:function(e,r,t){T.ready?a.get(e)(r,t):T.then(function(){a.get(e)(r,t)})},_emnapi_async_send_js:function(e,r,t){if(f)(0,h.postMessage)({__emnapi__:{type:"async-send",payload:{callback:r,data:t}}});else switch(e){case 0:S(r,t);break;case 1:C(r,t)}},_emnapi_emit_async_thread_ready:function(){f&&(0,h.postMessage)({__emnapi__:{type:"async-thread-ready",payload:{}}})},_emnapi_tell_js_uvthreadpool:function(e,r){for(var t=[],a=new DataView(n.buffer),o=function(r){var o=D((a.buffer===n.buffer?a:a=new DataView(n.buffer)).getUint32(e+4*r,!0));t.push(new Promise(function(e){var r=function(t){var n=(s?t:t.data).__emnapi__;n&&"async-thread-ready"===n.type&&(e(),o&&"function"==typeof o.unref&&o.unref(),s?o.off("message",r):o.removeEventListener("message",r))};s?o.on("message",r):o.addEventListener("message",r)}))},i=0;i>>=0);r&&"function"==typeof r.ref&&r.ref()}},_emnapi_worker_unref:function(e){if(!f){var r=D(e>>>=0);r&&"function"==typeof r.unref&&r.unref()}}});var B=Object.freeze({__proto__:null,napi_adjust_external_memory:function(e,r,t){if(!e)return 1;var a=l.envStore.get(e);if(!t)return a.setLastError(1);var o=l.adjustAmountOfExternalAllocatedMemory(r);if(t>>>=0,l.feature.supportBigInt){var i=new DataView(n.buffer);(i.buffer===n.buffer?i:i=new DataView(n.buffer)).setBigInt64(t,BigInt(o),!0)}else V(t,Number(o));return a.clearLastError()}}),x={idGen:{},values:[void 0],queued:new Set,pending:[],init:function(){var e={nextId:1,list:[],generate:function(){var r;return e.list.length?r=e.list.shift():(r=e.nextId,e.nextId++),r},reuse:function(r){e.list.push(r)}};x.idGen=e,x.values=[void 0],x.queued=new Set,x.pending=[]},create:function(e,r,t,n,a,o){var i=0,s=0;if(p){var f=p.node.emitAsyncInit(r,t,-1);i=f.asyncId,s=f.triggerAsyncId}var u=x.idGen.generate();return x.values[u]={env:e,id:u,resource:r,asyncId:i,triggerAsyncId:s,status:0,execute:n,complete:a,data:o},u},callComplete:function(e,r){var t=e.complete,n=e.env,o=e.data,i=function(){if(t){var e=l.envStore.get(n),i=l.openScope(e);try{e.callbackIntoModule(!0,function(){a.get(t)(n,r,o)})}finally{l.closeScope(e,i)}}};p?p.node.makeCallback(e.resource,i,[],{asyncId:e.asyncId,triggerAsyncId:e.triggerAsyncId}):i()},queue:function(e){var r=x.values[e];if(r&&0===r.status){if(r.status=1,x.queued.size>=(Math.abs(_)||4))return void x.pending.push(e);x.queued.add(e);var t=r.env,n=r.data,o=r.execute;r.status=2,l.feature.setImmediate(function(){if(a.get(o)(t,n),x.queued.delete(e),r.status=3,l.feature.setImmediate(function(){x.callComplete(r,0)}),x.pending.length>0){var i=x.pending.shift();x.values[i].status=0,x.queue(i)}})}},cancel:function(e){var r=x.pending.indexOf(e);if(-1!==r){var t=x.values[e];return t&&1===t.status?(t.status=4,x.pending.splice(r,1),l.feature.setImmediate(function(){x.callComplete(t,11)}),0):9}return 9},remove:function(e){var r=x.values[e];r&&(p&&p.node.emitAsyncDestroy({asyncId:r.asyncId,triggerAsyncId:r.triggerAsyncId}),x.values[e]=void 0,x.idGen.reuse(e))}};function O(e,r,t,a){if(p){var o=l.handleStore.get(e).value,i=l.handleStore.get(r).value,s=p.node.emitAsyncInit(o,i,t),f=s.asyncId,u=s.triggerAsyncId;if(a){a>>>=0;var c=new DataView(n.buffer),d=function(){return c.buffer===n.buffer?c:c=new DataView(n.buffer)};d().setFloat64(a,f,!0),d().setFloat64(a+8,u,!0)}}}function F(e,r){p&&p.node.emitAsyncDestroy({asyncId:e,triggerAsyncId:r})}var j=Object.freeze({__proto__:null,_emnapi_async_destroy_js:function(e){if(!p)return 9;e>>>=0;var r=new DataView(n.buffer),t=function(){return r.buffer===n.buffer?r:r=new DataView(n.buffer)},a=t().getInt32(e,!0),o=t().getInt32(e+4,!0),i=BigInt(a>>>0)|BigInt(o)<=BigInt(-1)*(BigInt(1)<=BigInt(1)<>BigInt(32));t>>>=0;var c=new DataView(n.buffer),d=function(){return c.buffer===n.buffer?c:c=new DataView(n.buffer)};return d().setInt32(t,f,!0),d().setInt32(t+4,u,!0),0},_emnapi_env_check_gc_access:function(e){l.envStore.get(e).checkGCAccess()},_emnapi_node_emit_async_destroy:F,_emnapi_node_emit_async_init:O,_emnapi_node_make_callback:function(e,r,t,a,o,i,s,f){var u,c=0;if(p){var d=l.handleStore.get(r).value,v=l.handleStore.get(t).value;a>>>=0,o>>>=0,o>>>=0;for(var h=Array(o),y=new DataView(n.buffer),g=function(){return y.buffer===n.buffer?y:y=new DataView(n.buffer)};c>>=0,u=l.envStore.get(e).ensureHandleId(b),g().setUint32(f,u,!0)}},napi_close_callback_scope:function(e,r){throw new Error("napi_close_callback_scope has not been implemented yet")},napi_make_callback:function(e,r,t,a,o,i,s){var f,u=0;if(!e)return 1;var c=l.envStore.get(e);if(c.checkGCAccess(),!c.tryCatch.isEmpty())return c.setLastError(10);if(!c.canCallIntoJs())return c.setLastError(c.moduleApiVersion>=10?23:10);c.clearLastError();try{if(!p)return c.setLastError(9);if(!t)return c.setLastError(1);if(o>0&&!i)return c.setLastError(1);var d=Object(l.handleStore.get(t).value),v=l.handleStore.get(a).value;if("function"!=typeof v)return c.setLastError(1);r>>>=0;var h=new DataView(n.buffer),y=function(){return h.buffer===n.buffer?h:h=new DataView(n.buffer)},g=y().getInt32(r,!0),w=y().getInt32(r+4,!0),b=BigInt(g>>>0)|BigInt(w)<>>=0,o>>>=0,o>>>=0;for(var _=Array(o);u>>=0,f=c.ensureHandleId(m.value),y().setUint32(s,f,!0)),c.getReturnStatus())}catch(e){return c.tryCatch.setError(e),c.setLastError(10)}},napi_open_callback_scope:function(e,r,t,n){throw new Error("napi_open_callback_scope has not been implemented yet")}}),M={_liveSet:{},offset:{__size__:0,resource:0,async_id:0,trigger_async_id:0,queue_size:0,is_some:0,queue:0,async_pending:0,async_u_fd:0,thread_count:0,state:0,dispatch_state:0,context:0,max_queue_size:0,ref:0,env:0,finalize_data:0,finalize_cb:0,call_js_cb:0,handles_closing:0,async_ref:0,mutex:0,cond:0},init:function(){if(M._liveSet=new Set,M.offset.__size__=184,M.offset.resource=0,M.offset.async_id=8,M.offset.trigger_async_id=16,M.offset.queue_size=60,M.offset.is_some=24,M.offset.queue=64,M.offset.async_pending=132,M.offset.async_u_fd=96,M.offset.thread_count=136,M.offset.state=140,M.offset.dispatch_state=144,M.offset.context=148,M.offset.max_queue_size=152,M.offset.ref=156,M.offset.env=160,M.offset.finalize_data=164,M.offset.finalize_cb=168,M.offset.call_js_cb=172,M.offset.handles_closing=176,M.offset.async_ref=180,M.offset.mutex=32,M.offset.cond=56,M.offset.mutex=M.offset.mutex+4,void 0!==A){A.unusedWorkers.forEach(M.addListener),Object.values(A.pthreads).forEach(M.addListener);var e=A.getNewWorker;A.getNewWorker=function(){var r=e.apply(this,arguments);return M.addListener(r),r}}},addListener:function(e){if(!e)return!1;if(e._emnapiTSFNListener)return!0;var r=function(e){var r=(s?e:e.data).__emnapi__;if(r){var t=r.type,n=r.payload;if("tsfn-send"===t){var a=n.tsfn+M.offset.async_pending;0!==Atomics.load(new Int32Array(M.ensureBufferFor(a+4)),a>>>2)&&M.enqueue(n.tsfn)}}};return e._emnapiTSFNListener={handler:r,dispose:function(){s?e.off("message",r):e.removeEventListener("message",r,!1),delete e._emnapiTSFNListener}},s?e.on("message",r):e.addEventListener("message",r,!1),!0},ensureBufferFor:function(e){var r=n.buffer;return e>r.byteLength&&(n.grow(0),r=n.buffer),r},initQueue:function(e){var r=o(8);return!!r&&(r>>>=0,new Uint8Array(M.ensureBufferFor(r+8),r,8).fill(0),M.storeSizeTypeValue(e+M.offset.queue,r,!1),!0)},destroyQueue:function(e){var r=M.loadSizeTypeValue(e+M.offset.queue,!1);if(r){for(var t=M.loadSizeTypeValue(r,!1);0!==t;){var n=M.loadSizeTypeValue(t+4,!1);i(t),t=n}i(r)}},pushQueue:function(e,r){var t=M.loadSizeTypeValue(e+M.offset.queue,!1),n=M.loadSizeTypeValue(t,!1),a=M.loadSizeTypeValue(t+4,!1),i=o(8);if(!i)throw new Error("OOM");i>>>=0,M.storeSizeTypeValue(i,r,!1),M.storeSizeTypeValue(i+4,0,!1),0===n&&0===a?(M.storeSizeTypeValue(t,i,!1),M.storeSizeTypeValue(t+4,i,!1)):(M.storeSizeTypeValue(a+4,i,!1),M.storeSizeTypeValue(t+4,i,!1)),M.addQueueSize(e)},shiftQueue:function(e){var r=M.loadSizeTypeValue(e+M.offset.queue,!1),t=M.loadSizeTypeValue(r,!1);if(0===t)return 0;var n=t,a=M.loadSizeTypeValue(t+4,!1);M.storeSizeTypeValue(r,a,!1),0===a&&M.storeSizeTypeValue(r+4,0,!1),M.storeSizeTypeValue(n+4,0,!1);var o=M.loadSizeTypeValue(n,!1);return i(n),M.subQueueSize(e),o},push:function(e,r,t){var n=M.getMutex(e),a=M.getCond(e),o=function(){var r=M.getQueueSize(e),t=M.getMaxQueueSize(e);return r>=t&&t>0&&0===M.getState(e)},i="undefined"!=typeof window&&"undefined"!=typeof document&&!s,f=!1,u=n.execute(function(){for(;o();){if(0===t)return 15;if(i)return 21;a.wait()}return 0===M.getState(e)?(M.pushQueue(e,r),M.send(e),0):0===M.getThreadCount(e)?1:(M.subThreadCount(e),2!==M.getState(e)||0!==M.getThreadCount(e)||(f=!0),16)});return f&&M.destroy(e),u},getMutex:function(e){var r=e+M.offset.mutex,t={lock:function(){var e="undefined"!=typeof window&&"undefined"!=typeof document&&!s,t=new Int32Array(M.ensureBufferFor(r+4),r,1);if(e)for(;;){if(0===Atomics.compareExchange(t,0,0,10))return}else for(;;){if(0===Atomics.compareExchange(t,0,0,10))return;Atomics.wait(t,0,10)}},unlock:function(){var e=new Int32Array(M.ensureBufferFor(r+4),r,1);if(10!==Atomics.compareExchange(e,0,10,0))throw new Error("Tried to unlock while not holding the mutex");Atomics.notify(e,0,1)},execute:function(e){t.lock();try{return e()}finally{t.unlock()}}};return t},getCond:function(e){var r=e+M.offset.cond,t=M.getMutex(e);return{wait:function(){var e=new Int32Array(M.ensureBufferFor(r+4),r,1),n=Atomics.load(e,0);t.unlock(),Atomics.wait(e,0,n),t.lock()},signal:function(){var e=new Int32Array(M.ensureBufferFor(r+4),r,1);Atomics.add(e,0,1),Atomics.notify(e,0,1)}}},getQueueSize:function(e){return M.loadSizeTypeValue(e+M.offset.queue_size,!0)},addQueueSize:function(e){var r,t,n=M.offset.queue_size;r=new Uint32Array(M.ensureBufferFor(e+n+4)),t=e+n>>>2,Atomics.add(r,t,1)},subQueueSize:function(e){var r,t,n=M.offset.queue_size;r=new Uint32Array(M.ensureBufferFor(e+n+4)),t=e+n>>>2,Atomics.sub(r,t,1)},getThreadCount:function(e){return M.loadSizeTypeValue(e+M.offset.thread_count,!0)},addThreadCount:function(e){var r,t,n=M.offset.thread_count;r=new Uint32Array(M.ensureBufferFor(e+n+4)),t=e+n>>>2,Atomics.add(r,t,1)},subThreadCount:function(e){var r,t,n=M.offset.thread_count;r=new Uint32Array(M.ensureBufferFor(e+n+4)),t=e+n>>>2,Atomics.sub(r,t,1)},getState:function(e){return Atomics.load(new Int32Array(M.ensureBufferFor(e+M.offset.state+4)),e+M.offset.state>>>2)},setState:function(e,r){Atomics.store(new Int32Array(M.ensureBufferFor(e+M.offset.state+4)),e+M.offset.state>>>2,r)},getHandlesClosing:function(e){return Atomics.load(new Int8Array(M.ensureBufferFor(e+M.offset.handles_closing+1)),e+M.offset.handles_closing)},setHandlesClosing:function(e,r){Atomics.store(new Int8Array(M.ensureBufferFor(e+M.offset.handles_closing+1)),e+M.offset.handles_closing,r)},getDispatchState:function(e){return Atomics.load(new Uint32Array(M.ensureBufferFor(e+M.offset.dispatch_state+4)),e+M.offset.dispatch_state>>>2)},getContext:function(e){return M.loadSizeTypeValue(e+M.offset.context,!1)},getMaxQueueSize:function(e){return M.loadSizeTypeValue(e+M.offset.max_queue_size,!0)},getEnv:function(e){return M.loadSizeTypeValue(e+M.offset.env,!1)},getCallJSCb:function(e){return M.loadSizeTypeValue(e+M.offset.call_js_cb,!1)},getRef:function(e){return M.loadSizeTypeValue(e+M.offset.ref,!1)},getResource:function(e){return M.loadSizeTypeValue(e+M.offset.resource,!1)},getFinalizeCb:function(e){return M.loadSizeTypeValue(e+M.offset.finalize_cb,!1)},getFinalizeData:function(e){return M.loadSizeTypeValue(e+M.offset.finalize_data,!1)},loadSizeTypeValue:function(e,r){var t;return r?(t=new Uint32Array(M.ensureBufferFor(e+4)),Atomics.load(t,e>>>2)):(t=new Int32Array(M.ensureBufferFor(e+4)),Atomics.load(t,e>>>2))},storeSizeTypeValue:function(e,r,t){var n;return t?(n=new Uint32Array(M.ensureBufferFor(e+4)),void Atomics.store(n,e>>>2,r)):(n=new Int32Array(M.ensureBufferFor(e+4)),void Atomics.store(n,e>>>2,r>>>0))},releaseResources:function(e){if(2!==M.getState(e)){M.setState(e,2);var r=M.getEnv(e),t=l.envStore.get(r),a=M.getRef(e);a&&l.refStore.get(a).dispose();var o=M.getResource(e);l.refStore.get(o).dispose(),M.ensureBufferFor(e+M.offset.is_some+1);var i=new DataView(n.buffer);(i.buffer===n.buffer?i:i=new DataView(n.buffer)).setInt8(e+M.offset.is_some,0,!0),l.removeCleanupHook(t,M.cleanup,e),t.unref();var s=e+M.offset.async_ref,f=s>>>2,u=new Uint32Array(M.ensureBufferFor(s+4));if(Atomics.load(u,f)>0&&(Atomics.store(u,f,0),l.decreaseWaitingRequestCounter()),p){var c=new DataView(M.ensureBufferFor(e+M.offset.trigger_async_id+8));F(c.getFloat64(e+M.offset.async_id,!0),c.getFloat64(e+M.offset.trigger_async_id,!0))}}},destroy:function(e){M._liveSet.delete(e),M.destroyQueue(e),M.releaseResources(e),i(e)},emptyQueue:function(e){var r=[];M.getMutex(e).execute(function(){for(;M.getQueueSize(e)>0;)r.push(M.shiftQueue(e))});for(var t,n=M.getCallJSCb(e),o=M.getContext(e),i=0;i0?M.releaseResources(e):r=!0}),r&&M.destroy(e)},finalize:function(e){var r=M.getEnv(e),t=l.envStore.get(r);l.openScope(t);var n=M.getFinalizeCb(e),a=M.getFinalizeData(e),o=M.getContext(e),i=function(){t.callFinalizerInternal(0,n,a,o)};try{if(M.emptyQueue(e),n)if(p){var s=M.getResource(e),f=l.refStore.get(s).get(),u=l.handleStore.get(f).value,c=new DataView(M.ensureBufferFor(e+M.offset.trigger_async_id+8)),d=c.getFloat64(e+M.offset.async_id,!0),v=c.getFloat64(e+M.offset.trigger_async_id,!0);p.node.makeCallback(u,i,[],{asyncId:d,triggerAsyncId:v})}else i();M.maybeDelete(e)}finally{l.closeScope(t)}},cleanup:function(e){M.closeHandlesAndMaybeDelete(e,1)},closeHandlesAndMaybeDelete:function(e,r){var t=M.getEnv(e),n=l.envStore.get(t);l.openScope(n);try{if(r&&M.getMutex(e).execute(function(){M.setState(e,1),M.getMaxQueueSize(e)>0&&M.getCond(e).signal()}),M.getHandlesClosing(e))return;M.setHandlesClosing(e,1),Atomics.store(new Int32Array(M.ensureBufferFor(e+M.offset.async_pending+4)),e+M.offset.async_pending>>>2,1),l.feature.setImmediate(function(){M.finalize(e)})}finally{l.closeScope(n)}},dispatchOne:function(e){var r=0,t=!1,n=!1,o=M.getMutex(e),i=M.getCond(e);if(o.execute(function(){if(0===M.getState(e)){var a=M.getQueueSize(e);if(a>0){r=M.shiftQueue(e),t=!0;var o=M.getMaxQueueSize(e);a===o&&o>0&&i.signal(),a--}0===a?0===M.getThreadCount(e)&&(M.setState(e,1),M.getMaxQueueSize(e)>0&&i.signal(),M.closeHandlesAndMaybeDelete(e,0)):n=!0}else M.closeHandlesAndMaybeDelete(e,0)}),t){var s=M.getEnv(e),f=l.envStore.get(s);l.openScope(f);var u=function(){f.callbackIntoModule(!1,function(){var t=M.getCallJSCb(e),n=M.getRef(e),o=n?l.refStore.get(n).get():0;if(t){var i=M.getContext(e);a.get(t)(s,o,i,r)}else{var f=o?l.handleStore.get(o).value:null;"function"==typeof f&&f()}})};try{if(p){var c=M.getResource(e),d=l.refStore.get(c).get(),v=l.handleStore.get(d).value,h=new DataView(M.ensureBufferFor(e+M.offset.trigger_async_id+8));p.node.makeCallback(v,u,[],{asyncId:h.getFloat64(e+M.offset.async_id,!0),triggerAsyncId:h.getFloat64(e+M.offset.trigger_async_id,!0)})}else u()}finally{l.closeScope(f)}}return n},dispatch:function(e){for(var r=!0,t=1e3,n=e+M.offset.dispatch_state,a=n>>>2;r&&0!==--t;){Atomics.store(new Uint32Array(M.ensureBufferFor(n+4)),a,1);try{r=M.dispatchOne(e)}catch(r){throw M._liveSet.has(e)&&(Atomics.exchange(new Uint32Array(M.ensureBufferFor(n+4)),a,0),M.send(e)),r}1!==Atomics.exchange(new Uint32Array(M.ensureBufferFor(n+4)),a,0)&&(r=!0)}r&&M.send(e)},enqueue:function(e){var r=e+M.offset.async_pending,t=e+M.offset.async_u_fd,n=Math.max(r,t)+4,a=function(){return new Int32Array(M.ensureBufferFor(n))};0===Atomics.exchange(a(),t>>>2,1)&&l.feature.setImmediate(function(){M._liveSet.has(e)&&(0!==Atomics.load(a(),r>>>2)?l.feature.setImmediate(function(){if(M._liveSet.has(e))try{if(0===Atomics.exchange(a(),r>>>2,0))return;M.dispatch(e)}finally{M._liveSet.has(e)&&(Atomics.store(a(),t>>>2,0),0!==Atomics.load(a(),r>>>2)&&M.enqueue(e))}}):Atomics.store(a(),t>>>2,0))})},send:function(e){var r=e+M.offset.dispatch_state;if(1&~Atomics.or(new Uint32Array(M.ensureBufferFor(r+4)),r>>>2,2)){var t=e+M.offset.async_pending;0===Atomics.load(new Int32Array(M.ensureBufferFor(t+4)),t>>>2)&&0===Atomics.exchange(new Int32Array(M.ensureBufferFor(t+4)),t>>>2,1)&&(void 0!==f&&f?postMessage({__emnapi__:{type:"tsfn-send",payload:{tsfn:e}}}):M.enqueue(e))}}};var R={pool:[],workerReady:null,globalAddress:0,globalOffset:{idle_threads:0,q:4,next:4,prev:8,mutex:12,cond:16,exit_message:20,end:28},offset:{resource:0,async_id:8,trigger_async_id:16,env:24,status:28,queue:32,queue_next:32,queue_prev:36,data:40,execute:44,complete:48,end:52},ensureBufferFor:function(e){var r=n.buffer;return e>r.byteLength&&(n.grow(0),r=n.buffer),r},init:function(){if(R.pool=[],R.workerReady=null,void 0!==A){A.unusedWorkers.forEach(R.addListener),Object.values(A.pthreads).forEach(R.addListener);var e=A.getNewWorker;A.getNewWorker=function(){var r=e.apply(this,arguments);return R.addListener(r),r}}},addListener:function(e){if(!e)return!1;if(e._emnapiAWMTListener)return!0;var r=function(e){var r=(s?e:e.data).__emnapi__;if(r){var t=r.type,n=r.payload;"async-work-complete"===t&&R.callComplete(n.work,0)}};return e._emnapiAWMTListener={handler:r,dispose:function(){s?e.off("message",r):e.removeEventListener("message",r,!1),delete e._emnapiAWMTListener}},s?e.on("message",r):e.addEventListener("message",r,!1),!0},initGlobal:function(){if(!R.globalAddress){R.globalAddress=o(R.globalOffset.end),R.globalAddress>>>=0;var e=R.globalOffset.end,r=R.globalAddress;new Uint8Array(R.ensureBufferFor(r+e),r,e).fill(0),R.queueInit(R.globalAddress+R.globalOffset.q),R.queueInit(R.globalAddress+R.globalOffset.exit_message)}},terminateWorkers:function(){R.pool.forEach(function(e){var r,t;null===(r=e._emnapiAWMTListener)||void 0===r||r.dispose(),null===(t=e._emnapiTSFNListener)||void 0===t||t.dispose(),e.terminate()}),R.pool.length=0},initWorkers:function(e){if(f)return R.workerReady||(R.workerReady=Promise.resolve());if(R.workerReady)return R.workerReady;if(!("emnapi_async_worker_create"in t.exports))throw new TypeError("`emnapi_async_worker_create` is not exported, please try to add `--export=emnapi_async_worker_create` to linker flags");var r=t.exports.emnapi_async_worker_create,n=[];R.initGlobal();for(var a=0;a>>=0;var t=new DataView(R.ensureBufferFor(e+20+4)).getInt32(e+20,!0);return(r=A.pthreads[t]).whenLoaded});return R.workerReady=Promise.all(o),R.workerReady},getResource:function(e){R.ensureBufferFor(e+R.offset.resource+4);var r=new DataView(n.buffer);return(r.buffer===n.buffer?r:r=new DataView(n.buffer)).getUint32(e+R.offset.resource,!0)},getExecute:function(e){R.ensureBufferFor(e+R.offset.execute+4);var r=new DataView(n.buffer);return(r.buffer===n.buffer?r:r=new DataView(n.buffer)).getUint32(e+R.offset.execute,!0)},getComplete:function(e){R.ensureBufferFor(e+R.offset.complete+4);var r=new DataView(n.buffer);return(r.buffer===n.buffer?r:r=new DataView(n.buffer)).getUint32(e+R.offset.complete,!0)},getEnv:function(e){R.ensureBufferFor(e+R.offset.env+4);var r=new DataView(n.buffer);return(r.buffer===n.buffer?r:r=new DataView(n.buffer)).getUint32(e+R.offset.env,!0)},getData:function(e){R.ensureBufferFor(e+R.offset.data+4);var r=new DataView(n.buffer);return(r.buffer===n.buffer?r:r=new DataView(n.buffer)).getUint32(e+R.offset.data,!0)},getMutex:function(){var e=R.globalAddress+R.globalOffset.mutex,r={lock:function(){var r="undefined"!=typeof window&&"undefined"!=typeof document&&!s,t=new Int32Array(R.ensureBufferFor(e+4),e,1);if(r)for(;;){if(0===Atomics.compareExchange(t,0,0,10))return}else for(;;){if(0===Atomics.compareExchange(t,0,0,10))return;Atomics.wait(t,0,10)}},unlock:function(){var r=new Int32Array(R.ensureBufferFor(e+4),e,1);if(10!==Atomics.compareExchange(r,0,10,0))throw new Error("Tried to unlock while not holding the mutex");Atomics.notify(r,0,1)},execute:function(e){r.lock();try{return e()}finally{r.unlock()}}};return r},getCond:function(){var e=R.globalAddress+R.globalOffset.cond,r=R.getMutex();return{wait:function(){var t=new Int32Array(R.ensureBufferFor(e+4),e,1),n=Atomics.load(t,0);r.unlock(),Atomics.wait(t,0,n),r.lock()},signal:function(){var r=new Int32Array(R.ensureBufferFor(e+4),e,1);Atomics.add(r,0,1),Atomics.notify(r,0,1)}}},queueInit:function(e){R.ensureBufferFor(e+4+4);var r=new DataView(n.buffer),t=function(){return r.buffer===n.buffer?r:r=new DataView(n.buffer)};t().setUint32(e,e,!0),t().setUint32(e+4,e,!0)},queueInsertTail:function(e,r){R.ensureBufferFor(e+4+4),R.ensureBufferFor(r+4+4);var t=new DataView(n.buffer),a=function(){return t.buffer===n.buffer?t:t=new DataView(n.buffer)};a().setUint32(r,e,!0);var o=a().getUint32(e+4,!0);a().setUint32(r+4,o,!0);var i=a().getUint32(r+4,!0);a().setUint32(i,r,!0),a().setUint32(e+4,r,!0)},queueRemove:function(e){R.ensureBufferFor(e+4+4);var r=new DataView(n.buffer),t=function(){return r.buffer===n.buffer?r:r=new DataView(n.buffer)},a=t().getUint32(e+4,!0),o=t().getUint32(e,!0);t().setUint32(a,o,!0),t().setUint32(o+4,a,!0)},queueEmpty:function(e){R.ensureBufferFor(e+4);var r=new DataView(n.buffer);return e==(r.buffer===n.buffer?r:r=new DataView(n.buffer)).getUint32(e,!0)},scheduleWork:function(e){var r;(null===(r=R.workerReady)||void 0===r?void 0:r.ready)||R.initWorkers(m()).then(function(){R.workerReady.ready=!0}).catch(function(e){throw R.workerReady=null,e}),l.increaseWaitingRequestCounter();var t=new Int32Array(R.ensureBufferFor(e+R.offset.status+4),e+R.offset.status,1);Atomics.store(t,0,0);var a=R.getMutex(),o=R.getCond();a.lock();try{R.queueInsertTail(R.globalAddress+R.globalOffset.q,e+R.offset.queue)}catch(e){throw l.decreaseWaitingRequestCounter(),a.unlock(),e}R.ensureBufferFor(R.globalAddress+R.globalOffset.idle_threads+4);var i=new DataView(n.buffer);(i.buffer===n.buffer?i:i=new DataView(n.buffer)).getUint32(R.globalAddress+R.globalOffset.idle_threads,!0)>0&&o.signal(),a.unlock()},cancelWork:function(e){var r=!1;return R.getMutex().execute(function(){R.ensureBufferFor(e+R.offset.status+4);var t=new DataView(n.buffer);(r=!R.queueEmpty(e+R.offset.queue)&&2!==(t.buffer===n.buffer?t:t=new DataView(n.buffer)).getInt32(e+R.offset.status,!0))&&R.queueRemove(e+R.offset.queue)}),r?0!==Atomics.compareExchange(new Int32Array(R.ensureBufferFor(e+R.offset.status+4),e+R.offset.status,1),0,0,1)?9:(l.feature.setImmediate(function(){R.callComplete(e,11)}),0):9},callComplete:function(e,r){l.decreaseWaitingRequestCounter();var t=R.getComplete(e),n=R.getEnv(e),o=R.getData(e),i=l.envStore.get(n),s=l.openScope(i),f=function(){t&&i.callbackIntoModule(!0,function(){a.get(t)(n,r,o)})};try{if(p){var u=R.getResource(e),c=l.refStore.get(u).get(),d=l.handleStore.get(c).value,v=new DataView(R.ensureBufferFor(e+R.offset.trigger_async_id+8)),h=v.getFloat64(e+R.offset.async_id,!0),y=v.getFloat64(e+R.offset.trigger_async_id,!0);p.node.makeCallback(d,f,[],{asyncId:h,triggerAsyncId:y})}else f()}finally{l.closeScope(i,s)}}};R.init();var z=E?function(e,r,t,a,o,i,s){if(!e)return 1;var f,u=l.envStore.get(e);if(u.checkGCAccess(),!a)return u.setLastError(1);if(!s)return u.setLastError(1);if(f=r?Object(l.handleStore.get(r).value):{},!t)return u.setLastError(1);var c=String(l.handleStore.get(t).value),d=x.create(e,f,c,a,o,i);s>>>=0;var p=new DataView(n.buffer);return(p.buffer===n.buffer?p:p=new DataView(n.buffer)).setUint32(s,d,!0),u.clearLastError()}:function(e,r,t,a,i,s,f){if(!e)return 1;var u,c=l.envStore.get(e);if(c.checkGCAccess(),!a)return c.setLastError(1);if(!f)return c.setLastError(1);if(u=r?Object(l.handleStore.get(r).value):{},!t)return c.setLastError(1);var d=R.offset.end,p=o(d);if(!p)return c.setLastError(9);p>>>=0,new Uint8Array(R.ensureBufferFor(p+d)).subarray(p,p+d).fill(0);var v=c.ensureHandleId(u),h=l.createReference(c,v,1,1).id,y=new DataView(n.buffer),g=function(){return y.buffer===n.buffer?y:y=new DataView(n.buffer)};return g().setUint32(p,h,!0),O(v,t,-1,p+R.offset.async_id),g().setUint32(p+R.offset.env,e,!0),g().setUint32(p+R.offset.execute,a,!0),g().setUint32(p+R.offset.complete,i,!0),g().setUint32(p+R.offset.data,s,!0),R.queueInit(p+R.offset.queue),f>>>=0,g().setUint32(f,p,!0),c.clearLastError()},W=E?function(e,r){if(!e)return 1;var t=l.envStore.get(e);return t.checkGCAccess(),r?(r>>>=0,x.remove(r),t.clearLastError()):t.setLastError(1)}:function(e,r){if(!e)return 1;var t=l.envStore.get(e);if(t.checkGCAccess(),!r)return t.setLastError(1);r>>>=0;var n=R.getResource(r);if(l.refStore.get(n).dispose(),p){var a=new DataView(R.ensureBufferFor(r+R.offset.trigger_async_id+8));F(a.getFloat64(r+R.offset.async_id,!0),a.getFloat64(r+R.offset.trigger_async_id,!0))}return i(r),t.clearLastError()},G=E?function(e,r){if(!e)return 1;var t=l.envStore.get(e);return r?(r>>>=0,x.queue(r),t.clearLastError()):t.setLastError(1)}:function(e,r){if(!e)return 1;var t=l.envStore.get(e);return r?(r>>>=0,R.scheduleWork(r),t.clearLastError()):t.setLastError(1)},P=E?function(e,r){if(!e)return 1;var t=l.envStore.get(e);if(!r)return t.setLastError(1);r>>>=0;var n=x.cancel(r);return 0===n?t.clearLastError():t.setLastError(n)}:function(e,r){if(!e)return 1;var t=l.envStore.get(e);if(!r)return t.setLastError(1);r>>>=0;var n=R.cancelWork(r);return 0===n?t.clearLastError():t.setLastError(n)};h.initWorker=function(e,r){if(!h.childThread)throw new Error("startThread is only available in child threads");if("function"!=typeof t.exports.emnapi_async_worker_init)throw new TypeError("`emnapi_async_worker_init` is not exported, please try to add `--export=emnapi_async_worker_init` to linker flags");t.exports.emnapi_async_worker_init(e),a.get(r[0])(r[1])};var N=Object.freeze({__proto__:null,_emnapi_async_worker:function(e){e>>>=0,R.globalAddress=e;var r=R.getMutex(),t=R.getCond();r.lock();for(var o=e+R.globalOffset.exit_message,i=e+R.globalOffset.idle_threads,s=e+R.globalOffset.q,f=new DataView(n.buffer),u=function(){return f.buffer===n.buffer?f:f=new DataView(n.buffer)};;){for(R.ensureBufferFor(s+4);R.queueEmpty(s);)Atomics.add(new Int32Array(R.ensureBufferFor(i+4),i,1),0,1),t.wait(),Atomics.sub(new Int32Array(R.ensureBufferFor(i+4),i,1),0,1);var l=u().getUint32(s,!0);if(l===o){t.signal(),r.unlock();break}var d=l-R.offset.queue;R.queueRemove(l),R.queueInit(l),r.unlock();var p=new Int32Array(R.ensureBufferFor(d+R.offset.status+4),d+R.offset.status,1);1===Atomics.load(p,0)&&c("unreachable");var v=R.getExecute(d),y=R.getEnv(d),g=R.getData(d);a.get(v)(y,g),Atomics.store(p,0,2),(0,h.postMessage)({__emnapi__:{type:"async-work-complete",payload:{work:d}}}),r.lock()}return 0},_emnapi_spawn_worker:function(e,r){if("function"!=typeof y)throw new TypeError("`options.onCreateWorker` is not a function");var n=[];if(!("emnapi_async_worker_create"in t.exports))throw new TypeError("`emnapi_async_worker_create` is not exported, please try to add `--export=emnapi_async_worker_create` to linker flags");n.push(t.exports.emnapi_async_worker_create(0,0));var a,o=function(e){!("message"in e)||-1===e.message.indexOf("RuntimeError")&&-1===e.message.indexOf("unreachable")||R.terminateWorkers()};try{var f=y({type:"async-work",name:"emnapi-async-worker"}),u=A.loadWasmModuleToWorker(f);s?f.on("error",o):f.addEventListener("error",o,!1),R.addListener(f),M.addListener(f),[].push(u.then(function(){"function"==typeof f.unref&&f.unref()})),a=R.pool.push(f)-1;var c=n[0];f.threadBlockBase=c,f.postMessage({__emnapi__:{type:"async-worker-init",payload:{arg:c,func:[e,r]}}})}catch(e){c=n[0];throw i(c),e}return a},napi_cancel_async_work:P,napi_create_async_work:z,napi_delete_async_work:W,napi_queue_async_work:G}),q={registry:"function"==typeof FinalizationRegistry?new FinalizationRegistry(function(e){i(e)}):void 0,table:new WeakMap,wasmMemoryViewTable:new WeakMap,intrinsics:void 0,init:function(){var e;q.registry="function"==typeof FinalizationRegistry?new FinalizationRegistry(function(e){i(e)}):void 0,q.table=new WeakMap,q.wasmMemoryViewTable=new WeakMap;var r="function"==typeof SharedArrayBuffer?null===(e=Object.getOwnPropertyDescriptor(SharedArrayBuffer.prototype,"byteLength"))||void 0===e?void 0:e.get:void 0;q.intrinsics={isView:ArrayBuffer.isView,typedArray:{buffer:Object.getOwnPropertyDescriptor(Object.getPrototypeOf(Uint8Array.prototype),"buffer").get,byteOffset:Object.getOwnPropertyDescriptor(Object.getPrototypeOf(Uint8Array.prototype),"byteOffset").get,length:Object.getOwnPropertyDescriptor(Object.getPrototypeOf(Uint8Array.prototype),"length").get,tag:Object.getOwnPropertyDescriptor(Object.getPrototypeOf(Uint8Array.prototype),Symbol.toStringTag).get},dataView:{buffer:Object.getOwnPropertyDescriptor(DataView.prototype,"buffer").get,byteOffset:Object.getOwnPropertyDescriptor(DataView.prototype,"byteOffset").get,byteLength:Object.getOwnPropertyDescriptor(DataView.prototype,"byteLength").get},arrayBuffer:{byteLength:Object.getOwnPropertyDescriptor(ArrayBuffer.prototype,"byteLength").get},sharedArrayBuffer:void 0!==r?{byteLength:r}:void 0,ctors:{Int8Array:Int8Array,Uint8Array:Uint8Array,Uint8ClampedArray:Uint8ClampedArray,Int16Array:Int16Array,Uint16Array:Uint16Array,Int32Array:Int32Array,Uint32Array:Uint32Array,Float16Array:"function"==typeof Float16Array?Float16Array:void 0,Float32Array:Float32Array,Float64Array:Float64Array,BigInt64Array:BigInt64Array,BigUint64Array:BigUint64Array},bufferFrom:void 0}},isSharedArrayBuffer:function(e){var r=q.intrinsics.sharedArrayBuffer;if(void 0!==r){if("function"==typeof SharedArrayBuffer&&e instanceof SharedArrayBuffer)return!0;try{return r.byteLength.call(e),!0}catch(e){return!1}}try{return q.intrinsics.arrayBuffer.byteLength.call(e),!1}catch(e){}return"[object SharedArrayBuffer]"===Object.prototype.toString.call(e)},isDetachedArrayBuffer:function(e){if(0===q.bufferByteLength(e))try{new Uint8Array(e)}catch(e){return!0}return!1},bufferByteLength:function(e){var r,t=q.intrinsics;try{return t.arrayBuffer.byteLength.call(e)}catch(i){var n=t.sharedArrayBuffer;if(void 0!==n)return n.byteLength.call(e);var a=Object.getPrototypeOf(e),o=null!=a?null===(r=Object.getOwnPropertyDescriptor(a,"byteLength"))||void 0===r?void 0:r.get:void 0;if(void 0===o)throw i;return o.call(e)}},viewBuffer:function(e){var r=q.intrinsics;return void 0===r.typedArray.tag.call(e)?r.dataView.buffer.call(e):r.typedArray.buffer.call(e)},viewByteOffset:function(e){var r=q.intrinsics;return void 0===r.typedArray.tag.call(e)?r.dataView.byteOffset.call(e):r.typedArray.byteOffset.call(e)},viewLength:function(e){var r=q.intrinsics;return void 0===r.typedArray.tag.call(e)?r.dataView.byteLength.call(e):r.typedArray.length.call(e)},getBufferFrom:function(){var e;return null!==(e=q.intrinsics.bufferFrom)&&void 0!==e?e:q.intrinsics.bufferFrom=l.feature.Buffer.from},getArrayBufferPointer:function(e,r){var t,a={address:0,ownership:0,runtimeAllocated:0};if(e===n.buffer)return a;var i=q.isDetachedArrayBuffer(e);if(q.table.has(e)){var s=q.table.get(e);return i?(s.address=0,s):(r&&0===s.ownership&&1===s.runtimeAllocated&&new Uint8Array(n.buffer).set(new Uint8Array(e),s.address),s)}var f=q.bufferByteLength(e);if(i||0===f)return a;if(!r)return a;var u=o(f);if(!u)throw new Error("Out of memory");return u>>>=0,new Uint8Array(n.buffer).set(new Uint8Array(e),u),a.address=u,a.ownership=q.registry?0:1,a.runtimeAllocated=1,q.table.set(e,a),null===(t=q.registry)||void 0===t||t.register(e,u),a},getOrUpdateMemoryView:function(e){var r=q.intrinsics,t=r.typedArray.tag.call(e),a=void 0===t,o=a?r.dataView.buffer.call(e):r.typedArray.buffer.call(e);if(o===n.buffer)return q.wasmMemoryViewTable.has(e)||q.wasmMemoryViewTable.set(e,{Ctor:a?DataView:r.ctors[t],address:a?r.dataView.byteOffset.call(e):r.typedArray.byteOffset.call(e),length:a?r.dataView.byteLength.call(e):r.typedArray.length.call(e),ownership:1,runtimeAllocated:0}),e;if((q.isDetachedArrayBuffer(o)||q.isSharedArrayBuffer(o))&&q.wasmMemoryViewTable.has(e)){var i=q.wasmMemoryViewTable.get(e),s=i.Ctor,f=void 0,u=l.feature.Buffer;return f="function"==typeof u&&s===u?q.getBufferFrom()(n.buffer,i.address,i.length):new s(n.buffer,i.address,i.length),q.wasmMemoryViewTable.set(f,i),f}return e},getViewPointer:function(e,r){e=q.getOrUpdateMemoryView(e);var t=q.viewBuffer(e);if(t===n.buffer){if(q.wasmMemoryViewTable.has(e)){var a=q.wasmMemoryViewTable.get(e);return{address:a.address,ownership:a.ownership,runtimeAllocated:a.runtimeAllocated,view:e}}return{address:q.viewByteOffset(e),ownership:1,runtimeAllocated:0,view:e}}var o=q.getArrayBufferPointer(t,r),i=o.address,s=o.ownership,f=o.runtimeAllocated;return{address:0===i?0:i+q.viewByteOffset(e),ownership:s,runtimeAllocated:f,view:e}}},J={registry:void 0,handleTable:new WeakMap,init:function(){J.handleTable=new WeakMap,J.registry="function"==typeof FinalizationRegistry?new FinalizationRegistry(function(e){J.release(e)}):void 0},allocMeta:function(e,r,t,a,i){var s=o(24);if(!s)throw new Error("Out of memory");s>>>=0,Atomics.store(new Int32Array(n.buffer,s,1),0,1);var f=new DataView(n.buffer),u=function(){return f.buffer===n.buffer?f:f=new DataView(n.buffer)};return u().setUint32(s+4,e,!0),u().setUint32(s+8,r,!0),u().setUint32(s+12,t,!0),u().setUint32(s+16,a,!0),u().setUint32(s+20,i,!0),s},readMeta:function(e){var r=new DataView(n.buffer),t=function(){return r.buffer===n.buffer?r:r=new DataView(n.buffer)};return{external_data:t().getUint32(e+4,!0),byte_length:t().getUint32(e+8,!0),finalize_cb:t().getUint32(e+12,!0),finalize_data:t().getUint32(e+16,!0),finalize_hint:t().getUint32(e+20,!0)}},release:function(e){if(1===Atomics.sub(new Int32Array(n.buffer,e,1),0,1)){var r=J.readMeta(e),t=r.finalize_cb;if(t){var o=r.finalize_data,s=r.finalize_hint;a.get(t)(o,s)}i(e)}}},H={utf8Decoder:void 0,utf16Decoder:void 0,init:function(){var e,r={decode:function(e){for(var r=0,t=Math.min(4096,e.length+1),n=new Uint16Array(t),a=[],o=0;;){var i=r=t-1){var s=n.subarray(0,o);if(a.push(String.fromCharCode.apply(null,s)),!i)return a.join("");e=e.subarray(r),r=0,o=0}var f=e[r++];if(128&f){if(192==(224&f)){var u=63&e[r++];n[o++]=(31&f)<<6|u}else if(224==(240&f)){u=63&e[r++];var c=63&e[r++];n[o++]=(31&f)<<12|u<<6|c}else if(240==(248&f)){var l=(7&f)<<18|(u=63&e[r++])<<12|(c=63&e[r++])<<6|63&e[r++];l>65535&&(l-=65536,n[o++]=l>>>10&1023|55296,l=56320|1023&l),n[o++]=l}}else n[o++]=f}}};e="function"==typeof TextDecoder?new TextDecoder:r,H.utf8Decoder=e;var t,n={decode:function(e){var r=new Uint16Array(e.buffer,e.byteOffset,e.byteLength/2);if(r.length<=4096)return String.fromCharCode.apply(null,r);for(var t=[],n=0,a=0;n=55296&&r<=57343?(t+=4,++n):t+=3;return t},UTF8ToString:function(e,r){if(!e||!r)return"";e>>>=0;var t=new Uint8Array(n.buffer),a=e;if(-1===r||4294967295===r)for(;t[a];)++a;else a=e+(r>>>0);if((r=a-e)<=16){for(var o=e,i="";o>10,56320|1023&c)}}else i+=String.fromCharCode((31&s)<<6|f)}else i+=String.fromCharCode(s)}return i}return H.utf8Decoder.decode("function"==typeof SharedArrayBuffer&&t.buffer instanceof SharedArrayBuffer||"[object SharedArrayBuffer]"===Object.prototype.toString.call(t.buffer)?t.slice(e,a):t.subarray(e,a))},stringToUTF8:function(e,r,t){var a=new Uint8Array(n.buffer),o=r;if(!(t>0))return 0;for(var i=o>>>=0,s=o+t-1,f=0;f=55296&&u<=57343)u=65536+((1023&u)<<10)|1023&e.charCodeAt(++f);if(u<=127){if(o>=s)break;a[o++]=u}else if(u<=2047){if(o+1>=s)break;a[o++]=192|u>>6,a[o++]=128|63&u}else if(u<=65535){if(o+2>=s)break;a[o++]=224|u>>12,a[o++]=128|u>>6&63,a[o++]=128|63&u}else{if(o+3>=s)break;a[o++]=240|u>>18,a[o++]=128|u>>12&63,a[o++]=128|u>>6&63,a[o++]=128|63&u}}return a[o]=0,o-i},UTF16ToString:function(e,r){if(!e||!r)return"";var t=e>>>=0;if(-1===r||4294967295===r){for(var a=t>>>1,o=new Uint16Array(n.buffer);o[a];)++a;t=a<<1>>>0}else t=e+2*(r>>>0);if((r=t-e)<=32)return String.fromCharCode.apply(null,new Uint16Array(n.buffer,e,r/2));var i=new Uint8Array(n.buffer);return H.utf16Decoder.decode("function"==typeof SharedArrayBuffer&&i.buffer instanceof SharedArrayBuffer||"[object SharedArrayBuffer]"===Object.prototype.toString.call(i.buffer)?i.slice(e,t):i.subarray(e,t))},stringToUTF16:function(e,r,t){if(void 0===t&&(t=2147483647),t<2)return 0;for(var a=r,o=(t-=2)<2*e.length?t/2:e.length,i=new DataView(n.buffer),s=function(){return i.buffer===n.buffer?i:i=new DataView(n.buffer)},f=0;f>>=0,!e)return 1;var i=l.envStore.get(e);i.checkGCAccess();var s=-1===t||4294967295===t,f=t>>>0;if(0!==t&&!r)return i.setLastError(1);if(!a)return i.setLastError(1);if(!(s||f<=2147483647))return i.setLastError(1);var u=o(r>>>=0,s,f);a>>>=0;var c=l.addToCurrentScope(u).id,d=new DataView(n.buffer);return(d.buffer===n.buffer?d:d=new DataView(n.buffer)).setUint32(a,c,!0),i.clearLastError()},newExternalString:function(e,r,t,a,o,i,s,f,u){if(t>>>=0,!e)return 1;var c=l.envStore.get(e);c.checkGCAccess();var d=-1===t||4294967295===t,p=t>>>0;if(0!==t&&!r)return c.setLastError(1);if(!i)return c.setLastError(1);if(!(d||p<=2147483647))return c.setLastError(1);var v=f(e,r,t,i);if(0===v){if(s){var h=new DataView(n.buffer);(h.buffer===n.buffer?h:h=new DataView(n.buffer)).setInt8(s,1,!0)}a&&c.callFinalizer(a,r,o)}return v}};function Q(e,r,t,a,o,i,s){if(!e)return 1;var f=l.envStore.get(e);if(f.checkGCAccess(),!r)return f.setLastError(1);var u=l.handleStore.get(r);if(!q.intrinsics.isView(u.value))return f.setLastError(1);var c=u.value,d=new DataView(n.buffer),p=function(){return d.buffer===n.buffer?d:d=new DataView(n.buffer)};if(t){t>>>=0;var v=void 0;switch(q.intrinsics.typedArray.tag.call(c)){case"Int8Array":v=0;break;case"Uint8Array":v=1;break;case"Uint8ClampedArray":v=2;break;case"Int16Array":v=3;break;case"Uint16Array":v=4;break;case"Int32Array":v=5;break;case"Uint32Array":v=6;break;case"Float16Array":v=11;break;case"Float32Array":v=7;break;case"Float64Array":v=8;break;case"BigInt64Array":v=9;break;case"BigUint64Array":v=10;break;default:return f.setLastError(9)}p().setInt32(t,v,!0)}if(c=q.getOrUpdateMemoryView(c),a){a>>>=0;var h=q.viewLength(c);p().setUint32(a,h,!0)}if(o||i){if(o){o>>>=0;var y=q.getViewPointer(c,!0);c=y.view;var g=y.address;p().setUint32(o,g,!0)}if(i){i>>>=0;var w=f.ensureHandleId(q.viewBuffer(c));p().setUint32(i,w,!0)}}if(s){s>>>=0;var b=q.viewByteOffset(c);p().setUint32(s,b,!0)}return f.clearLastError()}function $(e,r,t,a,o,i){if(!e)return 1;var s=l.envStore.get(e);if(s.checkGCAccess(),!r)return s.setLastError(1);var f=l.handleStore.get(r);if(!q.intrinsics.isView(f.value)||void 0!==q.intrinsics.typedArray.tag.call(f.value))return s.setLastError(1);var u=q.getOrUpdateMemoryView(f.value),c=new DataView(n.buffer),d=function(){return c.buffer===n.buffer?c:c=new DataView(n.buffer)};if(t){t>>>=0;var p=q.viewLength(u);d().setUint32(t,p,!0)}if(a||o){if(a){a>>>=0;var v=q.getViewPointer(u,!0);u=v.view;var h=v.address;d().setUint32(a,h,!0)}if(o){o>>>=0;var y=s.ensureHandleId(q.viewBuffer(u));d().setUint32(o,y,!0)}}if(i){i>>>=0;var g=q.viewByteOffset(u);d().setUint32(i,g,!0)}return s.clearLastError()}var Y=Object.freeze({__proto__:null,napi_get_array_length:function(e,r,t){if(!e)return 1;var a=l.envStore.get(e);if(a.checkGCAccess(),!a.tryCatch.isEmpty())return a.setLastError(10);if(!a.canCallIntoJs())return a.setLastError(a.moduleApiVersion>=10?23:10);a.clearLastError();try{if(!r)return a.setLastError(1);if(!t)return a.setLastError(1);var o=l.handleStore.get(r);if(!o.isArray())return a.setLastError(8);t>>>=0;var i=o.value.length>>>0,s=new DataView(n.buffer);return(s.buffer===n.buffer?s:s=new DataView(n.buffer)).setUint32(t,i,!0),a.getReturnStatus()}catch(e){return a.tryCatch.setError(e),a.setLastError(10)}},napi_get_arraybuffer_info:function(e,r,t,a){if(!e)return 1;var o=l.envStore.get(e);if(o.checkGCAccess(),!r)return o.setLastError(1);var i=l.handleStore.get(r);if(!i.isArrayBuffer()&&!q.isSharedArrayBuffer(i.value))return o.setLastError(1);var s=new DataView(n.buffer),f=function(){return s.buffer===n.buffer?s:s=new DataView(n.buffer)};if(t){t>>>=0;var u=q.getArrayBufferPointer(i.value,!0).address;f().setUint32(t,u,!0)}if(a){a>>>=0;var c=q.bufferByteLength(i.value);f().setUint32(a,c,!0)}return o.clearLastError()},napi_get_buffer_info:function(e,r,t,n){if(!e)return 1;var a=l.envStore.get(e);if(a.checkGCAccess(),!r)return a.setLastError(1);var o=l.handleStore.get(r),i=l.feature.Buffer;return q.intrinsics.isView(o.value)||"function"==typeof i&&i.isBuffer(o.value)?void 0===q.intrinsics.typedArray.tag.call(o.value)?$(e,r,n,t,0,0):Q(e,r,0,n,t,0,0):a.setLastError(1)},napi_get_dataview_info:$,napi_get_date_value:function(e,r,t){var a;if(!e)return 1;var o=l.envStore.get(e);if(o.checkGCAccess(),!o.tryCatch.isEmpty())return o.setLastError(10);if(!o.canCallIntoJs())return o.setLastError(o.moduleApiVersion>=10?23:10);o.clearLastError();try{if(!r)return o.setLastError(1);if(!t)return o.setLastError(1);var i=l.handleStore.get(r);if(!i.isDate())return o.setLastError(1);t>>>=0,a=i.value.valueOf();var s=new DataView(n.buffer);return(s.buffer===n.buffer?s:s=new DataView(n.buffer)).setFloat64(t,a,!0),o.getReturnStatus()}catch(e){return o.tryCatch.setError(e),o.setLastError(10)}},napi_get_prototype:function(e,r,t){if(!e)return 1;var a=l.envStore.get(e);if(a.checkGCAccess(),!a.tryCatch.isEmpty())return a.setLastError(10);if(!a.canCallIntoJs())return a.setLastError(a.moduleApiVersion>=10?23:10);a.clearLastError();try{if(!r)return a.setLastError(1);if(!t)return a.setLastError(1);var o=l.handleStore.get(r);if(null==o.value)throw new TypeError("Cannot convert undefined or null to object");var i=void 0;try{i=o.isObject()||o.isFunction()?o.value:Object(o.value)}catch(e){return a.setLastError(2)}t>>>=0;var s=a.ensureHandleId(Object.getPrototypeOf(i)),f=new DataView(n.buffer);return(f.buffer===n.buffer?f:f=new DataView(n.buffer)).setUint32(t,s,!0),a.getReturnStatus()}catch(e){return a.tryCatch.setError(e),a.setLastError(10)}},napi_get_typedarray_info:Q,napi_get_value_bigint_int64:function(e,r,t,a){if(!e)return 1;var o=l.envStore.get(e);if(o.checkGCAccess(),!l.feature.supportBigInt)return o.setLastError(9);if(!r)return o.setLastError(1);if(!t)return o.setLastError(1);if(!a)return o.setLastError(1);var i=l.handleStore.get(r).value;if("bigint"!=typeof i)return o.setLastError(6);a>>>=0,t>>>=0;var s=new DataView(n.buffer),f=function(){return s.buffer===n.buffer?s:s=new DataView(n.buffer)};i>=BigInt(-1)*(BigInt(1)<=BigInt(1)<>BigInt(32));return f().setInt32(t,u,!0),f().setInt32(t+4,c,!0),o.clearLastError()},napi_get_value_bigint_uint64:function(e,r,t,a){if(!e)return 1;var o=l.envStore.get(e);if(o.checkGCAccess(),!l.feature.supportBigInt)return o.setLastError(9);if(!r)return o.setLastError(1);if(!t)return o.setLastError(1);if(!a)return o.setLastError(1);var i=l.handleStore.get(r).value;if("bigint"!=typeof i)return o.setLastError(6);a>>>=0,t>>>=0;var s=new DataView(n.buffer),f=function(){return s.buffer===n.buffer?s:s=new DataView(n.buffer)};i>=BigInt(0)&&i>BigInt(32));return f().setUint32(t,u,!0),f().setUint32(t+4,c,!0),o.clearLastError()},napi_get_value_bigint_words:function(e,r,t,a,o){if(!e)return 1;var i=l.envStore.get(e);if(i.checkGCAccess(),!l.feature.supportBigInt)return i.setLastError(9);if(!r)return i.setLastError(1);if(!a)return i.setLastError(1);var s=l.handleStore.get(r);if(!s.isBigInt())return i.setLastError(17);var f=s.value>>=0,o>>>=0,a>>>=0;var u=new DataView(n.buffer),c=function(){return u.buffer===n.buffer?u:u=new DataView(n.buffer)},d=c().getUint32(a,!0);d>>>=0;for(var p=0,v=f?s.value*BigInt(-1):s.value;v!==BigInt(0);)p++,v>>=BigInt(64);if(v=f?s.value*BigInt(-1):s.value,t||o){if(!t)return i.setLastError(1);if(!o)return i.setLastError(1);for(var h=[];v!==BigInt(0);){var y=v&(BigInt(1)<>=BigInt(64)}for(var g=Math.min(d,h.length),w=0;w>BigInt(32));c().setUint32(o+8*w,b,!0),c().setUint32(o+(8*w+4),_,!0)}c().setInt32(t,f?1:0,!0),c().setUint32(a,g,!0)}else d=p,c().setUint32(a,d,!0);return i.clearLastError()},napi_get_value_bool:function(e,r,t){if(!e)return 1;var a=l.envStore.get(e);if(a.checkGCAccess(),!r)return a.setLastError(1);if(!t)return a.setLastError(1);var o=l.handleStore.get(r);if("boolean"!=typeof o.value)return a.setLastError(7);t>>>=0;var i=o.value?1:0,s=new DataView(n.buffer);return(s.buffer===n.buffer?s:s=new DataView(n.buffer)).setInt8(t,i,!0),a.clearLastError()},napi_get_value_double:function(e,r,t){if(!e)return 1;var a=l.envStore.get(e);if(a.checkGCAccess(),!r)return a.setLastError(1);if(!t)return a.setLastError(1);var o=l.handleStore.get(r);if("number"!=typeof o.value)return a.setLastError(6);t>>>=0;var i=o.value,s=new DataView(n.buffer);return(s.buffer===n.buffer?s:s=new DataView(n.buffer)).setFloat64(t,i,!0),a.clearLastError()},napi_get_value_external:function(e,r,t){if(!e)return 1;var a=l.envStore.get(e);if(a.checkGCAccess(),!r)return a.setLastError(1);if(!t)return a.setLastError(1);var o=l.handleStore.get(r);if(!o.isExternal())return a.setLastError(1);t>>>=0;var i=o.data(),s=new DataView(n.buffer);return(s.buffer===n.buffer?s:s=new DataView(n.buffer)).setUint32(t,i,!0),a.clearLastError()},napi_get_value_int32:function(e,r,t){if(!e)return 1;var a=l.envStore.get(e);if(a.checkGCAccess(),!r)return a.setLastError(1);if(!t)return a.setLastError(1);var o=l.handleStore.get(r);if("number"!=typeof o.value)return a.setLastError(6);t>>>=0;var i=new Int32Array([o.value])[0],s=new DataView(n.buffer);return(s.buffer===n.buffer?s:s=new DataView(n.buffer)).setInt32(t,i,!0),a.clearLastError()},napi_get_value_int64:function(e,r,t){if(!e)return 1;var a=l.envStore.get(e);if(a.checkGCAccess(),!r)return a.setLastError(1);if(!t)return a.setLastError(1);var o=l.handleStore.get(r);if("number"!=typeof o.value)return a.setLastError(6);var i=o.value;t>>>=0;var s=new DataView(n.buffer),f=function(){return s.buffer===n.buffer?s:s=new DataView(n.buffer)};return i===Number.POSITIVE_INFINITY||i===Number.NEGATIVE_INFINITY||isNaN(i)?(f().setInt32(t,0,!0),f().setInt32(t+4,0,!0)):i<-0x8000000000000000?(f().setInt32(t,0,!0),f().setInt32(t+4,2147483648,!0)):i>=0x8000000000000000?(f().setUint32(t,4294967295,!0),f().setUint32(t+4,2147483647,!0)):V(t,Math.trunc(i)),a.clearLastError()},napi_get_value_string_latin1:function(e,r,t,a,o){if(!e)return 1;var i=l.envStore.get(e);if(i.checkGCAccess(),!r)return i.setLastError(1);o>>>=0,t>>>=0,a>>>=0,a>>>=0;var s=l.handleStore.get(r);if("string"!=typeof s.value)return i.setLastError(3);var f=new DataView(n.buffer),u=function(){return f.buffer===n.buffer?f:f=new DataView(n.buffer)};if(t)if(0!==a){for(var c=0,d=void 0,p=0;p>>=0,t>>>=0,a>>>=0,a>>>=0;var s=l.handleStore.get(r);if("string"!=typeof s.value)return i.setLastError(3);var f=new DataView(n.buffer),u=function(){return f.buffer===n.buffer?f:f=new DataView(n.buffer)};if(t)if(0!==a){var c=H.stringToUTF16(s.value,t,2*a);o&&u().setUint32(o,c/2,!0)}else o&&u().setUint32(o,0,!0);else{if(!o)return i.setLastError(1);u().setUint32(o,s.value.length,!0)}return i.clearLastError()},napi_get_value_string_utf8:function(e,r,t,a,o){if(!e)return 1;var i=l.envStore.get(e);if(i.checkGCAccess(),!r)return i.setLastError(1);o>>>=0,t>>>=0,a>>>=0,a>>>=0;var s=l.handleStore.get(r);if("string"!=typeof s.value)return i.setLastError(3);var f=new DataView(n.buffer),u=function(){return f.buffer===n.buffer?f:f=new DataView(n.buffer)};if(t)if(0!==a){var c=H.stringToUTF8(s.value,t,a);o&&u().setUint32(o,c,!0)}else o&&u().setUint32(o,0,!0);else{if(!o)return i.setLastError(1);var d=H.lengthBytesUTF8(s.value);u().setUint32(o,d,!0)}return i.clearLastError()},napi_get_value_uint32:function(e,r,t){if(!e)return 1;var a=l.envStore.get(e);if(a.checkGCAccess(),!r)return a.setLastError(1);if(!t)return a.setLastError(1);var o=l.handleStore.get(r);if("number"!=typeof o.value)return a.setLastError(6);t>>>=0;var i=new Uint32Array([o.value])[0],s=new DataView(n.buffer);return(s.buffer===n.buffer?s:s=new DataView(n.buffer)).setUint32(t,i,!0),a.clearLastError()},node_api_set_prototype:function(e,r,t){if(!e)return 1;var n=l.envStore.get(e);if(n.checkGCAccess(),!n.tryCatch.isEmpty())return n.setLastError(10);if(!n.canCallIntoJs())return n.setLastError(n.moduleApiVersion>=10?23:10);n.clearLastError();try{if(!t)return n.setLastError(1);var a=l.handleStore.get(r).value;if(null==a)throw new TypeError("Cannot convert undefined or null to object");var o=typeof a,i=void 0;try{i="object"===o&&null!==a||"function"===o?a:Object(a)}catch(e){return n.setLastError(2)}var s=l.handleStore.get(t).value;return Object.setPrototypeOf(i,s),n.getReturnStatus()}catch(e){return n.tryCatch.setError(e),n.setLastError(10)}}});function X(e,r,t,a){return H.newString(e,r,t,a,function(e,r,t){var a="",o=0,i=new DataView(n.buffer),s=function(){return i.buffer===n.buffer?i:i=new DataView(n.buffer)};if(r)for(;;){if(!(f=s().getUint8(e,!0)))break;a+=String.fromCharCode(f),e++}else for(;o>>=0;var f=new DataView(n.buffer);return(f.buffer===n.buffer?f:f=new DataView(n.buffer)).setUint32(t,s,!0),i.clearLastError()},napi_create_bigint_uint64:function(e,r,t,a){if(!e)return 1;var o,i=l.envStore.get(e);if(i.checkGCAccess(),!l.feature.supportBigInt)return i.setLastError(9);if(!t)return i.setLastError(1);o=r&(BigInt(1)<>>=0;var f=new DataView(n.buffer);return(f.buffer===n.buffer?f:f=new DataView(n.buffer)).setUint32(t,s,!0),i.clearLastError()},napi_create_bigint_words:function(e,r,t,a,o){var i,s;if(!e)return 1;var f=l.envStore.get(e);if(f.checkGCAccess(),!f.tryCatch.isEmpty())return f.setLastError(10);if(!f.canCallIntoJs())return f.setLastError(f.moduleApiVersion>=10?23:10);f.clearLastError();try{if(!l.feature.supportBigInt)return f.setLastError(9);if(!o)return f.setLastError(1);if(a>>>=0,t>>>=0,(t>>>=0)>2147483647)return f.setLastError(1);if(t>16384)throw new RangeError("Maximum BigInt size exceeded");var u=BigInt(0),c=new DataView(n.buffer),d=function(){return c.buffer===n.buffer?c:c=new DataView(n.buffer)};for(s=0;s>>=0,i=l.addToCurrentScope(u).id,d().setUint32(o,i,!0),f.getReturnStatus()}catch(e){return f.tryCatch.setError(e),f.setLastError(10)}},napi_create_double:function(e,r,t){if(!e)return 1;var a=l.envStore.get(e);if(a.checkGCAccess(),!t)return a.setLastError(1);t>>>=0;var o=l.addToCurrentScope(r).id,i=new DataView(n.buffer);return(i.buffer===n.buffer?i:i=new DataView(n.buffer)).setUint32(t,o,!0),a.clearLastError()},napi_create_int32:function(e,r,t){if(!e)return 1;var a=l.envStore.get(e);if(a.checkGCAccess(),!t)return a.setLastError(1);t>>>=0;var o=l.addToCurrentScope(r).id,i=new DataView(n.buffer);return(i.buffer===n.buffer?i:i=new DataView(n.buffer)).setUint32(t,o,!0),a.clearLastError()},napi_create_int64:function(e,r,t,a){if(!e)return 1;var o,i=l.envStore.get(e);if(i.checkGCAccess(),!t)return i.setLastError(1);o=Number(r);var s=l.addToCurrentScope(o).id;t>>>=0;var f=new DataView(n.buffer);return(f.buffer===n.buffer?f:f=new DataView(n.buffer)).setUint32(t,s,!0),i.clearLastError()},napi_create_string_latin1:X,napi_create_string_utf16:Z,napi_create_string_utf8:K,napi_create_uint32:function(e,r,t){if(!e)return 1;var a=l.envStore.get(e);if(a.checkGCAccess(),!t)return a.setLastError(1);t>>>=0;var o=l.addToCurrentScope(r>>>0).id,i=new DataView(n.buffer);return(i.buffer===n.buffer?i:i=new DataView(n.buffer)).setUint32(t,o,!0),a.clearLastError()},node_api_create_external_string_latin1:function(e,r,t,n,a,o,i){return H.newExternalString(e,r,t,n,a,o,i,X,void 0)},node_api_create_external_string_utf16:function(e,r,t,n,a,o,i){return H.newExternalString(e,r,t,n,a,o,i,Z,void 0)},node_api_create_property_key_latin1:function(e,r,t,n){return X(e,r,t,n)},node_api_create_property_key_utf16:function(e,r,t,n){return Z(e,r,t,n)},node_api_create_property_key_utf8:function(e,r,t,n){return K(e,r,t,n)}});function re(e,r,t,n,o){var i,s=(r>>>=0)&&t?H.UTF8ToString(r,t):"",f=a.get(n),u=function(e){return f(e.id,e.ctx.scopeStore.currentScope.id)},c=function(e,r){return function(){var t=e.ctx.openScope(e),n=t.callbackInfo;n.data=o,n.args=arguments,n.thiz=this,n.fn=i;try{var a=e.callIntoModule(r);return a?e.ctx.handleStore.get(a).value:void 0}finally{n.data=0,n.args=void 0,n.thiz=void 0,n.fn=void 0,e.ctx.closeScope(e,t)}}};if(""===s)return{status:0,f:i=c(e,u)};if(!/^[_$a-zA-Z][_$a-zA-Z0-9]*$/.test(s))return{status:1,f:void 0};if(l.feature.supportNewFunction){var d=c(e,u);try{i=new Function("_","return function "+s+'(){"use strict";return _.apply(this,arguments);};')(d)}catch(r){i=c(e,u),l.feature.canSetFunctionName&&Object.defineProperty(i,"name",{value:s})}}else i=c(e,u),l.feature.canSetFunctionName&&Object.defineProperty(i,"name",{value:s});return{status:0,f:i}}function te(e,r,t,n,a,o,i,s,f){if(a||o){var u=void 0,c=void 0;a&&(u=re(e,0,0,a,f).f),o&&(c=re(e,0,0,o,f).f);var d={configurable:!!(4&s),enumerable:!!(2&s),get:u,set:c};Object.defineProperty(r,t,d)}else if(n){d={configurable:!!(4&s),enumerable:!!(2&s),writable:!!(1&s),value:re(e,0,0,n,f).f};Object.defineProperty(r,t,d)}else{d={configurable:!!(4&s),enumerable:!!(2&s),writable:!!(1&s),value:l.handleStore.get(i).value};Object.defineProperty(r,t,d)}}function ne(e){var r=l.handleStore.get(e);return r.isObject()||r.isFunction()?(void 0!==q&&ArrayBuffer.isView(r.value)&&q.wasmMemoryViewTable.has(r.value)&&(r=l.addToCurrentScope(q.wasmMemoryViewTable.get(r.value))),{status:0,handle:r}):{status:1}}function ae(e,r,t,a){var o;if(!e)return 1;var i=l.envStore.get(e);if(i.checkGCAccess(),!i.tryCatch.isEmpty())return i.setLastError(10);if(!i.canCallIntoJs())return i.setLastError(i.moduleApiVersion>=10?23:10);i.clearLastError();try{if(!r)return i.setLastError(1);if(0===a&&!t)return i.setLastError(1);var s=l.handleStore.get(r);if(!s.isObject()&&!s.isFunction())return i.setLastError(1);var f=i.getObjectBinding(s.value),u=f.wrapped,c=l.refStore.get(u);if(!c)return i.setLastError(1);if(t){t>>>=0,o=c.data();var d=new DataView(n.buffer);(d.buffer===n.buffer?d:d=new DataView(n.buffer)).setUint32(t,o,!0)}return 1===a&&(f.wrapped=0,1===c.ownership()?c.resetFinalizer():c.dispose()),i.getReturnStatus()}catch(e){return i.tryCatch.setError(e),i.setLastError(10)}}function oe(e,r,t,a,o,i){if(!e)return 1;var s=l.envStore.get(e);if(s.checkGCAccess(),!l.feature.supportFinalizer)return s.setLastError(9);if(!r)return s.setLastError(1);if(!a)return s.setLastError(1);var f=ne(r);if(0!==f.status)return s.setLastError(f.status);var u=f.handle,c=i?1:0;t>>>=0,a>>>=0,o>>>=0;var d=l.createReferenceWithFinalizer(s,u.id,0,c,a,t,o);if(i){i>>>=0;var p=d.id,v=new DataView(n.buffer);(v.buffer===n.buffer?v:v=new DataView(n.buffer)).setUint32(i,p,!0)}return s.clearLastError()}var ie=Object.freeze({__proto__:null,napi_add_finalizer:oe,napi_check_object_type_tag:function(e,r,t,a){var o=!0;if(!e)return 1;var i=l.envStore.get(e);if(i.checkGCAccess(),!i.tryCatch.isEmpty())return i.setLastError(10);if(!i.canCallIntoJs())return i.setLastError(i.moduleApiVersion>=10?23:10);i.clearLastError();try{if(!r)return i.setLastError(i.tryCatch.hasCaught()?10:1);var s=l.handleStore.get(r);if(!s.isObject()&&!s.isFunction())return i.setLastError(i.tryCatch.hasCaught()?10:2);if(!t)return i.setLastError(i.tryCatch.hasCaught()?10:1);if(!a)return i.setLastError(i.tryCatch.hasCaught()?10:1);var f=i.getObjectBinding(s.value);if(null!==f.tag){t>>>=0;var u=f.tag,c=new Uint32Array(n.buffer,t,4);o=u[0]===c[0]&&u[1]===c[1]&&u[2]===c[2]&&u[3]===c[3]}else o=!1;a>>>=0;var d=new DataView(n.buffer);return(d.buffer===n.buffer?d:d=new DataView(n.buffer)).setInt8(a,o?1:0,!0),i.getReturnStatus()}catch(e){return i.tryCatch.setError(e),i.setLastError(10)}},napi_define_class:function(e,r,t,a,o,i,s,f){var u,c,d;if(!e)return 1;var p=l.envStore.get(e);if(p.checkGCAccess(),!p.tryCatch.isEmpty())return p.setLastError(10);if(!p.canCallIntoJs())return p.setLastError(p.moduleApiVersion>=10?23:10);p.clearLastError();try{if(!f)return p.setLastError(1);if(!a)return p.setLastError(1);if(t>>>=0,s>>>=0,i>>>=0,(i>>>=0)>0&&!s)return p.setLastError(1);if(!(t>=-1&&t<=2147483647||4294967295===t)||!r)return p.setLastError(1);var v=re(p,r,t,a,o);if(0!==v.status)return p.setLastError(v.status);for(var h=v.f,y=void 0,g=new DataView(n.buffer),w=function(){return g.buffer===n.buffer?g:g=new DataView(n.buffer)},b=0;b>>=0;var C=w().getUint32(u+28,!0);if(_)y=H.UTF8ToString(_,-1);else{if(!E)return p.setLastError(4);if("string"!=typeof(y=l.handleStore.get(E).value)&&"symbol"!=typeof y)return p.setLastError(4)}1024&d?te(p,h,y,m,L,A,S,d,C):te(p,h.prototype,y,m,L,A,S,d,C)}return c=l.addToCurrentScope(h).id,f>>>=0,w().setUint32(f,c,!0),p.getReturnStatus()}catch(e){return p.tryCatch.setError(e),p.setLastError(10)}},napi_remove_wrap:function(e,r,t){return ae(e,r,t,1)},napi_type_tag_object:function(e,r,t){if(!e)return 1;var a=l.envStore.get(e);if(a.checkGCAccess(),!a.tryCatch.isEmpty())return a.setLastError(10);if(!a.canCallIntoJs())return a.setLastError(a.moduleApiVersion>=10?23:10);a.clearLastError();try{if(!r)return a.setLastError(a.tryCatch.hasCaught()?10:1);var o=l.handleStore.get(r);if(!o.isObject()&&!o.isFunction())return a.setLastError(a.tryCatch.hasCaught()?10:2);if(!(t>>>=0))return a.setLastError(a.tryCatch.hasCaught()?10:1);var i=a.getObjectBinding(o.value);if(null!==i.tag)return a.setLastError(a.tryCatch.hasCaught()?10:1);var s=new Uint8Array(16);return s.set(new Uint8Array(n.buffer,t,16)),i.tag=new Uint32Array(s.buffer),a.getReturnStatus()}catch(e){return a.tryCatch.setError(e),a.setLastError(10)}},napi_unwrap:function(e,r,t){return ae(e,r,t,0)},napi_wrap:function(e,r,t,a,o,i){return function(e,r,t,a,o,i){var s;if(!e)return 1;var f=l.envStore.get(e);if(f.checkGCAccess(),!f.tryCatch.isEmpty())return f.setLastError(10);if(!f.canCallIntoJs())return f.setLastError(f.moduleApiVersion>=10?23:10);f.clearLastError();try{if(!l.feature.supportFinalizer){if(a)throw l.createNotSupportWeakRefError("napi_wrap",'Parameter "finalize_cb" must be 0(NULL)');if(i)throw l.createNotSupportWeakRefError("napi_wrap",'Parameter "result" must be 0(NULL)')}if(!r)return f.setLastError(1);var u=ne(r);if(0!==u.status)return f.setLastError(u.status);var c=u.handle;if(0!==f.getObjectBinding(c.value).wrapped)return f.setLastError(1);var d=void 0;if(i){if(!a)return f.setLastError(1);d=l.createReferenceWithFinalizer(f,c.id,0,1,a,t,o),i>>>=0,s=d.id;var p=new DataView(n.buffer);(p.buffer===n.buffer?p:p=new DataView(n.buffer)).setUint32(i,s,!0)}else d=a?l.createReferenceWithFinalizer(f,c.id,0,0,a,t,o):l.createReferenceWithData(f,c.id,0,0,t);return f.getObjectBinding(c.value).wrapped=d.id,f.getReturnStatus()}catch(e){return f.tryCatch.setError(e),f.setLastError(10)}}(e,r,t,a,o,i)},node_api_post_finalizer:function(e,r,t,n){if(!e)return 1;var a=l.envStore.get(e);return a.enqueueFinalizer(l.createTrackedFinalizer(a,r,t,n)),a.clearLastError()}});function se(e,r,t,a,o,i,s){var f;if(!e)return 1;var u=l.envStore.get(e);if(u.checkGCAccess(),!u.tryCatch.isEmpty())return u.setLastError(10);if(!u.canCallIntoJs())return u.setLastError(u.moduleApiVersion>=10?23:10);u.clearLastError();try{if(!s)return u.setLastError(1);if(a>>>=0,s>>>=0,a>>>=0,(t>>>=0)||(a=0),a>2147483647)throw new RangeError("Cannot create a memory view larger than 2147483647 bytes");if(t+a>n.buffer.byteLength)throw new RangeError("Memory out of range");if(!l.feature.supportFinalizer&&o)throw l.createNotSupportWeakRefError("emnapi_create_memory_view",'Parameter "finalize_cb" must be 0(NULL)');var c=void 0;switch(r){case 0:c={Ctor:Int8Array,address:t,length:a,ownership:1,runtimeAllocated:0};break;case 1:c={Ctor:Uint8Array,address:t,length:a,ownership:1,runtimeAllocated:0};break;case 2:c={Ctor:Uint8ClampedArray,address:t,length:a,ownership:1,runtimeAllocated:0};break;case 3:c={Ctor:Int16Array,address:t,length:a>>1,ownership:1,runtimeAllocated:0};break;case 4:c={Ctor:Uint16Array,address:t,length:a>>1,ownership:1,runtimeAllocated:0};break;case 5:c={Ctor:Int32Array,address:t,length:a>>2,ownership:1,runtimeAllocated:0};break;case 6:c={Ctor:Uint32Array,address:t,length:a>>2,ownership:1,runtimeAllocated:0};break;case 7:c={Ctor:Float32Array,address:t,length:a>>2,ownership:1,runtimeAllocated:0};break;case 8:c={Ctor:Float64Array,address:t,length:a>>3,ownership:1,runtimeAllocated:0};break;case 9:c={Ctor:BigInt64Array,address:t,length:a>>3,ownership:1,runtimeAllocated:0};break;case 10:c={Ctor:BigUint64Array,address:t,length:a>>3,ownership:1,runtimeAllocated:0};break;case-1:c={Ctor:DataView,address:t,length:a,ownership:1,runtimeAllocated:0};break;case 11:if("function"!=typeof Float16Array)return u.setLastError(1);c={Ctor:Float16Array,address:t,length:a>>1,ownership:1,runtimeAllocated:0};break;case-2:if(!l.feature.Buffer)throw l.createNotSupportBufferError("emnapi_create_memory_view","");c={Ctor:l.feature.Buffer,address:t,length:a,ownership:1,runtimeAllocated:0};break;default:return u.setLastError(1)}var d=c.Ctor,p=-2===r?q.getBufferFrom()(n.buffer,c.address,c.length):new d(n.buffer,c.address,c.length),v=l.addToCurrentScope(p);if(q.wasmMemoryViewTable.set(p,c),o){var h=oe(e,v.id,t,o,i,0);if(10===h){var y=u.tryCatch.extractException();throw u.clearLastError(),y}if(0!==h)return u.setLastError(h)}f=v.id;var g=new DataView(n.buffer);return(g.buffer===n.buffer?g:g=new DataView(n.buffer)).setUint32(s,f,!0),u.getReturnStatus()}catch(y){return u.tryCatch.setError(y),u.setLastError(10)}}function fe(e,r,t,a){var o;if(t=null!=t?t:0,t>>>=0,r instanceof ArrayBuffer||q.isSharedArrayBuffer(r)){if(!(s=q.getArrayBufferPointer(r,!1).address))throw new Error("Unknown ArrayBuffer address");if("number"==typeof a&&-1!==a&&4294967295!==a||(a=r.byteLength-t),0===(a>>>=0))return r;o=new Uint8Array(r,t,a);var i=new Uint8Array(n.buffer);return e?i.set(o,s):o.set(i.subarray(s,s+a)),r}if(ArrayBuffer.isView(r)){var s,f=q.getViewPointer(r,!1),u=f.view;if(!(s=f.address))throw new Error("Unknown ArrayBuffer address");if("number"==typeof a&&-1!==a&&4294967295!==a||(a=u.byteLength-t),0===(a>>>=0))return u;o=new Uint8Array(u.buffer,u.byteOffset+t,a);i=new Uint8Array(n.buffer);return e?i.set(o,s):o.set(i.subarray(s,s+a)),u}throw new TypeError("emnapiSyncMemory expect ArrayBuffer or ArrayBufferView as first parameter")}function ue(e){var r,t=e instanceof ArrayBuffer,n=e instanceof DataView,a=ArrayBuffer.isView(e)&&!n;if(!(t||a||n||q.isSharedArrayBuffer(e)))throw new TypeError("emnapiGetMemoryAddress expect ArrayBuffer or ArrayBufferView as first parameter");return{address:(r=t?q.getArrayBufferPointer(e,!1):q.getViewPointer(e,!1)).address,ownership:r.ownership,runtimeAllocated:r.runtimeAllocated}}function ce(e,r){if(null!=r&&!q.isSharedArrayBuffer(r))throw new TypeError("Expected a SharedArrayBuffer");if(!J.registry)throw new Error("FinalizationRegistry is not supported in this environment");e>>>=0;var t=J.readMeta(e),a=t.external_data;if(a>>>=0,null==r)r=new SharedArrayBuffer(t.byte_length),new Uint8Array(r).set(new Uint8Array(n.buffer,a,t.byte_length));else if(J.handleTable.has(r))return r;return Atomics.add(new Int32Array(n.buffer,e,1),0,1),q.table.has(r)||a&&q.table.set(r,{address:a,ownership:1,runtimeAllocated:0}),J.handleTable.set(r,e),J.registry.register(r,e),r}var le=Object.freeze({__proto__:null,$emnapiAcquireExternalSharedArrayBuffer:ce,$emnapiGetMemoryAddress:ue,$emnapiSyncMemory:fe,emnapi_acquire_external_sharedarraybuffer:function(e){e>>>=0,Atomics.add(new Int32Array(n.buffer,e,1),0,1)},emnapi_create_memory_view:se,emnapi_get_external_sharedarraybuffer_handle:function(e,r,t){if(!e)return 1;var a=l.envStore.get(e);if(a.checkGCAccess(),!a.tryCatch.isEmpty())return a.setLastError(10);if(!a.canCallIntoJs())return a.setLastError(a.moduleApiVersion>=10?23:10);a.clearLastError();try{if(!r)return a.setLastError(1);if(!t)return a.setLastError(1);t>>>=0;var o=l.handleStore.get(r).value;if(!q.isSharedArrayBuffer(o))return a.setLastError(1);var i=J.handleTable.get(o);if(void 0===i)return a.setLastError(1);var s=new DataView(n.buffer);return(s.buffer===n.buffer?s:s=new DataView(n.buffer)).setUint32(t,i,!0),a.getReturnStatus()}catch(e){return a.tryCatch.setError(e),a.setLastError(10)}},emnapi_get_memory_address:function(e,r,t,a,o){var i,s,f,u;if(!e)return 1;var c=l.envStore.get(e);if(c.checkGCAccess(),!c.tryCatch.isEmpty())return c.setLastError(10);if(!c.canCallIntoJs())return c.setLastError(c.moduleApiVersion>=10?23:10);c.clearLastError();try{if(!r)return c.setLastError(1);if(!t&&!a&&!o)return c.setLastError(1);i=(u=ue(c.ctx.handleStore.get(r).value)).address;var d=new DataView(n.buffer),p=function(){return d.buffer===n.buffer?d:d=new DataView(n.buffer)};return t&&(t>>>=0,p().setUint32(t,i,!0)),a&&(a>>>=0,f=u.ownership,p().setInt32(a,f,!0)),o&&(o>>>=0,s=u.runtimeAllocated,p().setInt8(o,s,!0)),c.getReturnStatus()}catch(e){return c.tryCatch.setError(e),c.setLastError(10)}},emnapi_get_runtime_version:function(e,r){if(!e)return 1;var t,a=l.envStore.get(e);if(!r)return a.setLastError(1);try{t=l.getRuntimeVersions().version}catch(e){return a.setLastError(9)}var o=t.split(".").map(function(e){return Number(e)});r>>>=0;var i=new DataView(n.buffer),s=function(){return i.buffer===n.buffer?i:i=new DataView(n.buffer)};return s().setUint32(r,o[0],!0),s().setUint32(r+4,o[1],!0),s().setUint32(r+8,o[2],!0),a.clearLastError()},emnapi_is_node_binding_available:function(){return p?1:0},emnapi_is_support_bigint:function(){return l.feature.supportBigInt?1:0},emnapi_is_support_weakref:function(){return l.feature.supportFinalizer?1:0},emnapi_release_external_sharedarraybuffer:function(e){e>>>=0,J.release(e)},emnapi_sync_memory:function(e,r,t,a,o){var i;if(!e)return 1;var s=l.envStore.get(e);if(s.checkGCAccess(),!s.tryCatch.isEmpty())return s.setLastError(10);if(!s.canCallIntoJs())return s.setLastError(s.moduleApiVersion>=10?23:10);s.clearLastError();try{if(!t)return s.setLastError(1);t>>>=0,a>>>=0,o>>>=0;var f=new DataView(n.buffer),u=function(){return f.buffer===n.buffer?f:f=new DataView(n.buffer)},c=u().getUint32(t,!0),d=s.ctx.handleStore.get(c);if(!(d.isArrayBuffer()||d.isTypedArray()||d.isDataView()||q.isSharedArrayBuffer(d.value)))return s.setLastError(1);var p=fe(Boolean(r),d.value,a,o);return d.value!==p&&(t>>>=0,i=s.ensureHandleId(p),u().setUint32(t,i,!0)),s.getReturnStatus()}catch(e){return s.tryCatch.setError(e),s.setLastError(10)}}});function de(e,r,t){e>>>=0,e>>>=0;var a=t?new SharedArrayBuffer(e):new ArrayBuffer(e);if(r){r>>>=0;var o=q.getArrayBufferPointer(a,!0).address,i=new DataView(n.buffer);(i.buffer===n.buffer?i:i=new DataView(n.buffer)).setUint32(r,o,!0)}return a}var pe=Object.freeze({__proto__:null,napi_create_array:function(e,r){if(!e)return 1;var t=l.envStore.get(e);if(t.checkGCAccess(),!r)return t.setLastError(1);r>>>=0;var a=l.addToCurrentScope([]).id,o=new DataView(n.buffer);return(o.buffer===n.buffer?o:o=new DataView(n.buffer)).setUint32(r,a,!0),t.clearLastError()},napi_create_array_with_length:function(e,r,t){if(!e)return 1;var a=l.envStore.get(e);if(a.checkGCAccess(),!t)return a.setLastError(1);r>>>=0,t>>>=0,r>>>=0;var o=l.addToCurrentScope(new Array(r)).id,i=new DataView(n.buffer);return(i.buffer===n.buffer?i:i=new DataView(n.buffer)).setUint32(t,o,!0),a.clearLastError()},napi_create_arraybuffer:function(e,r,t,a){var o;if(!e)return 1;var i=l.envStore.get(e);if(i.checkGCAccess(),!i.tryCatch.isEmpty())return i.setLastError(10);if(!i.canCallIntoJs())return i.setLastError(i.moduleApiVersion>=10?23:10);i.clearLastError();try{if(!a)return i.setLastError(1);a>>>=0;var s=de(r,t,!1);o=l.addToCurrentScope(s).id;var f=new DataView(n.buffer);return(f.buffer===n.buffer?f:f=new DataView(n.buffer)).setUint32(a,o,!0),i.getReturnStatus()}catch(e){return i.tryCatch.setError(e),i.setLastError(10)}},napi_create_buffer:function(e,r,t,a){var i,s,f;if(!e)return 1;var u=l.envStore.get(e);if(u.checkGCAccess(),!u.tryCatch.isEmpty())return u.setLastError(10);if(!u.canCallIntoJs())return u.setLastError(u.moduleApiVersion>=10?23:10);u.clearLastError();try{if(!a)return u.setLastError(1);var c=l.feature.Buffer;if(!c)throw l.createNotSupportBufferError("napi_create_buffer","");a>>>=0;var d=void 0;r>>>=0,r>>>=0;var p=new DataView(n.buffer),v=function(){return p.buffer===n.buffer?p:p=new DataView(n.buffer)};if(t&&0!==r){if(!(f=o(r)))throw new Error("Out of memory");f>>>=0,new Uint8Array(n.buffer).subarray(f,f+r).fill(0);var h=q.getBufferFrom()(n.buffer,f,r),y={Ctor:c,address:f,length:r,ownership:q.registry?0:1,runtimeAllocated:1};q.wasmMemoryViewTable.set(h,y),null===(i=q.registry)||void 0===i||i.register(y,f),s=l.addToCurrentScope(h).id,v().setUint32(a,s,!0),t>>>=0,v().setUint32(t,f,!0)}else d=c.alloc(r),s=l.addToCurrentScope(d).id,v().setUint32(a,s,!0);return u.getReturnStatus()}catch(e){return u.tryCatch.setError(e),u.setLastError(10)}},napi_create_buffer_copy:function(e,r,t,a,o){var i;if(!e)return 1;var s=l.envStore.get(e);if(s.checkGCAccess(),!s.tryCatch.isEmpty())return s.setLastError(10);if(!s.canCallIntoJs())return s.setLastError(s.moduleApiVersion>=10?23:10);s.clearLastError();try{if(!o)return s.setLastError(1);var f=l.feature.Buffer;if(!f)throw l.createNotSupportBufferError("napi_create_buffer_copy","");var u=de(r,a,!1),c=f.from(u);t>>>=0,r>>>=0,c.set(new Uint8Array(n.buffer).subarray(t,t+r)),i=l.addToCurrentScope(c).id,o>>>=0;var d=new DataView(n.buffer);return(d.buffer===n.buffer?d:d=new DataView(n.buffer)).setUint32(o,i,!0),s.getReturnStatus()}catch(e){return s.tryCatch.setError(e),s.setLastError(10)}},napi_create_dataview:function(e,r,t,a,o){if(!e)return 1;var i=l.envStore.get(e);if(i.checkGCAccess(),!i.tryCatch.isEmpty())return i.setLastError(10);if(!i.canCallIntoJs())return i.setLastError(i.moduleApiVersion>=10?23:10);i.clearLastError();try{if(!t)return i.setLastError(1);if(!o)return i.setLastError(1);r>>>=0,a>>>=0,r>>>=0,a>>>=0;var s=l.handleStore.get(t).value;return s instanceof ArrayBuffer||q.isSharedArrayBuffer(s)?function(e){if(r+a>e.byteLength){var t=new RangeError("byte_offset + byte_length should be less than or equal to the size in bytes of the array passed in");throw t.code="ERR_NAPI_INVALID_DATAVIEW_ARGS",t}var s=new DataView(e,a,r);e===n.buffer&&(q.wasmMemoryViewTable.has(s)||q.wasmMemoryViewTable.set(s,{Ctor:DataView,address:a,length:r,ownership:1,runtimeAllocated:0})),o>>>=0;var f=l.addToCurrentScope(s).id,u=new DataView(n.buffer);return(u.buffer===n.buffer?u:u=new DataView(n.buffer)).setUint32(o,f,!0),i.getReturnStatus()}(s):i.setLastError(1)}catch(e){return i.tryCatch.setError(e),i.setLastError(10)}},napi_create_date:function(e,r,t){var a;if(!e)return 1;var o=l.envStore.get(e);if(o.checkGCAccess(),!o.tryCatch.isEmpty())return o.setLastError(10);if(!o.canCallIntoJs())return o.setLastError(o.moduleApiVersion>=10?23:10);o.clearLastError();try{if(!t)return o.setLastError(1);t>>>=0,a=l.addToCurrentScope(new Date(r)).id;var i=new DataView(n.buffer);return(i.buffer===n.buffer?i:i=new DataView(n.buffer)).setUint32(t,a,!0),o.getReturnStatus()}catch(e){return o.tryCatch.setError(e),o.setLastError(10)}},napi_create_external:function(e,r,t,a,o){var i;if(!e)return 1;var s=l.envStore.get(e);if(s.checkGCAccess(),!s.tryCatch.isEmpty())return s.setLastError(10);if(!s.canCallIntoJs())return s.setLastError(s.moduleApiVersion>=10?23:10);s.clearLastError();try{if(!o)return s.setLastError(1);if(!l.feature.supportFinalizer&&t)throw l.createNotSupportWeakRefError("napi_create_external",'Parameter "finalize_cb" must be 0(NULL)');var f=l.getCurrentScope().addExternal(r);t&&l.createReferenceWithFinalizer(s,f.id,0,0,t,r,a),o>>>=0,i=f.id;var u=new DataView(n.buffer);return(u.buffer===n.buffer?u:u=new DataView(n.buffer)).setUint32(o,i,!0),s.clearLastError()}catch(e){return s.tryCatch.setError(e),s.setLastError(10)}},napi_create_external_arraybuffer:function(e,r,t,a,o,i){var s;if(!e)return 1;var f=l.envStore.get(e);if(f.checkGCAccess(),!f.tryCatch.isEmpty())return f.setLastError(10);if(!f.canCallIntoJs())return f.setLastError(f.moduleApiVersion>=10?23:10);f.clearLastError();try{if(!i)return f.setLastError(1);if(t>>>=0,i>>>=0,t>>>=0,(r>>>=0)||(t=0),r+t>n.buffer.byteLength)throw new RangeError("Memory out of range");if(!l.feature.supportFinalizer&&a)throw l.createNotSupportWeakRefError("napi_create_external_arraybuffer",'Parameter "finalize_cb" must be 0(NULL)');var u=new ArrayBuffer(t);if(0===t)try{(new(0,l.feature.MessageChannel)).port1.postMessage(u,[u])}catch(e){}else new Uint8Array(u).set(new Uint8Array(n.buffer).subarray(r,r+t)),q.table.set(u,{address:r,ownership:1,runtimeAllocated:0});var c=l.addToCurrentScope(u);if(a){var d=oe(e,c.id,r,a,o,0);if(10===d){var p=f.tryCatch.extractException();throw f.clearLastError(),p}if(0!==d)return f.setLastError(d)}s=c.id;var v=new DataView(n.buffer);return(v.buffer===n.buffer?v:v=new DataView(n.buffer)).setUint32(i,s,!0),f.getReturnStatus()}catch(p){return f.tryCatch.setError(p),f.setLastError(10)}},napi_create_external_buffer:function(e,r,t,n,a,o){return se(e,-2,t,r,n,a,o)},napi_create_object:function(e,r){if(!e)return 1;var t=l.envStore.get(e);if(t.checkGCAccess(),!r)return t.setLastError(1);r>>>=0;var a=l.addToCurrentScope({}).id,o=new DataView(n.buffer);return(o.buffer===n.buffer?o:o=new DataView(n.buffer)).setUint32(r,a,!0),t.clearLastError()},napi_create_symbol:function(e,r,t){if(!e)return 1;var a=l.envStore.get(e);if(a.checkGCAccess(),!t)return a.setLastError(1);t>>>=0;var o=new DataView(n.buffer),i=function(){return o.buffer===n.buffer?o:o=new DataView(n.buffer)};if(r){var s=l.handleStore.get(r).value;if("string"!=typeof s)return a.setLastError(3);var f=l.addToCurrentScope(Symbol(s)).id;i().setUint32(t,f,!0)}else{var u=l.addToCurrentScope(Symbol()).id;i().setUint32(t,u,!0)}return a.clearLastError()},napi_create_typedarray:function(e,r,t,a,o,i){var s;if(!e)return 1;var f=l.envStore.get(e);if(f.checkGCAccess(),!f.tryCatch.isEmpty())return f.setLastError(10);if(!f.canCallIntoJs())return f.setLastError(f.moduleApiVersion>=10?23:10);f.clearLastError();try{if(!a)return f.setLastError(1);if(!i)return f.setLastError(1);var u=l.handleStore.get(a).value;o>>>=0,t>>>=0;var c=function(e,r,t,a,o,f){var u,c;if((o>>>=0,f>>>=0,t>1)&&o%t!==0)return(c=new RangeError("start offset of ".concat(null!==(u=r.name)&&void 0!==u?u:""," should be a multiple of ").concat(t))).code="ERR_NAPI_INVALID_TYPEDARRAY_ALIGNMENT",e.tryCatch.setError(c),e.setLastError(9);if(f*t+o>a.byteLength)return(c=new RangeError("Invalid typed array length")).code="ERR_NAPI_INVALID_TYPEDARRAY_LENGTH",e.tryCatch.setError(c),e.setLastError(9);var d=new r(a,o,f);a===n.buffer&&(q.wasmMemoryViewTable.has(d)||q.wasmMemoryViewTable.set(d,{Ctor:r,address:o,length:f,ownership:1,runtimeAllocated:0})),i>>>=0,s=l.addToCurrentScope(d).id;var p=new DataView(n.buffer);return(p.buffer===n.buffer?p:p=new DataView(n.buffer)).setUint32(i,s,!0),e.getReturnStatus()};if(!(u instanceof ArrayBuffer||q.isSharedArrayBuffer(u)))return f.setLastError(1);switch(r){case 0:return c(f,Int8Array,1,u,o,t);case 1:return c(f,Uint8Array,1,u,o,t);case 2:return c(f,Uint8ClampedArray,1,u,o,t);case 3:return c(f,Int16Array,2,u,o,t);case 4:return c(f,Uint16Array,2,u,o,t);case 5:return c(f,Int32Array,4,u,o,t);case 6:return c(f,Uint32Array,4,u,o,t);case 7:return c(f,Float32Array,4,u,o,t);case 8:return c(f,Float64Array,8,u,o,t);case 9:return c(f,BigInt64Array,8,u,o,t);case 10:return c(f,BigUint64Array,8,u,o,t);case 11:return"function"!=typeof Float16Array?f.setLastError(1):c(f,Float16Array,2,u,o,t);default:return f.setLastError(1)}}catch(e){return f.tryCatch.setError(e),f.setLastError(10)}},node_api_create_buffer_from_arraybuffer:function(e,r,t,a,o){var i;if(!e)return 1;var s=l.envStore.get(e);if(s.checkGCAccess(),!s.tryCatch.isEmpty())return s.setLastError(10);if(!s.canCallIntoJs())return s.setLastError(s.moduleApiVersion>=10?23:10);s.clearLastError();try{if(!r)return s.setLastError(1);if(!o)return s.setLastError(1);t>>>=0,a>>>=0,t>>>=0,a>>>=0;var f=l.handleStore.get(r);if(!f.isArrayBuffer())return s.setLastError(1);var u=f.value;if(a+t>u.byteLength){var c=new RangeError("The byte offset + length is out of range");throw c.code="ERR_OUT_OF_RANGE",c}var d=l.feature.Buffer;if(!d)throw l.createNotSupportBufferError("node_api_create_buffer_from_arraybuffer","");var p=q.getBufferFrom()(u,t,a);u===n.buffer&&(q.wasmMemoryViewTable.has(p)||q.wasmMemoryViewTable.set(p,{Ctor:d,address:t,length:a,ownership:1,runtimeAllocated:0})),o>>>=0,i=l.addToCurrentScope(p).id;var v=new DataView(n.buffer);return(v.buffer===n.buffer?v:v=new DataView(n.buffer)).setUint32(o,i,!0),s.getReturnStatus()}catch(c){return s.tryCatch.setError(c),s.setLastError(10)}},node_api_create_external_sharedarraybuffer:function(e,r,t,a,o,i){var s;if(!e)return 1;var f=l.envStore.get(e);if(f.checkGCAccess(),!f.tryCatch.isEmpty())return f.setLastError(10);if(!f.canCallIntoJs())return f.setLastError(f.moduleApiVersion>=10?23:10);f.clearLastError();try{if(!i)return f.setLastError(1);if(t>>>=0,i>>>=0,t>>>=0,(r>>>=0)||(t=0),r+t>n.buffer.byteLength)throw new RangeError("Memory out of range");if(!J.registry&&a)throw l.createNotSupportWeakRefError("node_api_create_external_sharedarraybuffer",'Parameter "finalize_cb" must be 0(NULL)');var u=new SharedArrayBuffer(t);if(0!==t)new Uint8Array(u).set(new Uint8Array(n.buffer).subarray(r,r+t)),q.table.set(u,{address:r,ownership:1,runtimeAllocated:0});if(s=l.addToCurrentScope(u).id,a){a>>>=0,o>>>=0;var c=J.allocMeta(r,t,a,r,o);J.handleTable.set(u,c),J.registry.register(u,c)}var d=new DataView(n.buffer);return(d.buffer===n.buffer?d:d=new DataView(n.buffer)).setUint32(i,s,!0),f.getReturnStatus()}catch(e){return f.tryCatch.setError(e),f.setLastError(10)}},node_api_create_object_with_properties:function(e,r,t,a,o,i){if(!e)return 1;var s=l.envStore.get(e);if(s.checkGCAccess(),!i)return s.setLastError(1);if(o>>>=0,(o>>>=0)>0){if(!t)return s.setLastError(1);if(!a)return s.setLastError(1)}var f=r?l.handleStore.get(r).value:null,u={};t>>>=0,a>>>=0;for(var c,d=new DataView(n.buffer),p=function(){return d.buffer===n.buffer?d:d=new DataView(n.buffer)},v=0;v>>=0,p().setUint32(i,y,!0),s.clearLastError()},node_api_create_sharedarraybuffer:function(e,r,t,a){var o;if(!e)return 1;var i=l.envStore.get(e);if(i.checkGCAccess(),!i.tryCatch.isEmpty())return i.setLastError(10);if(!i.canCallIntoJs())return i.setLastError(i.moduleApiVersion>=10?23:10);i.clearLastError();try{if(!a)return i.setLastError(1);a>>>=0;var s=de(r,t,!0);o=l.addToCurrentScope(s).id;var f=new DataView(n.buffer);return(f.buffer===n.buffer?f:f=new DataView(n.buffer)).setUint32(a,o,!0),i.getReturnStatus()}catch(e){return i.tryCatch.setError(e),i.setLastError(10)}},node_api_symbol_for:function(e,r,t,a){if(!e)return 1;var o=l.envStore.get(e);if(o.checkGCAccess(),!a)return o.setLastError(1);r>>>=0,a>>>=0;var i=-1===(t>>>=0)||4294967295===t,s=t>>>0;if(0!==t&&!r)return o.setLastError(1);if(!(i||s<=2147483647))return o.setLastError(1);var f=H.UTF8ToString(r,t),u=l.addToCurrentScope(Symbol.for(f)).id,c=new DataView(n.buffer);return(c.buffer===n.buffer?c:c=new DataView(n.buffer)).setUint32(a,u,!0),o.clearLastError()}});var ve=Object.freeze({__proto__:null,napi_get_boolean:function(e,r,t){if(!e)return 1;var a=l.envStore.get(e);if(a.checkGCAccess(),!t)return a.setLastError(1);t>>>=0;var o=0===r?3:4,i=new DataView(n.buffer);return(i.buffer===n.buffer?i:i=new DataView(n.buffer)).setUint32(t,o,!0),a.clearLastError()},napi_get_global:function(e,r){if(!e)return 1;var t=l.envStore.get(e);if(t.checkGCAccess(),!r)return t.setLastError(1);r>>>=0;var a=new DataView(n.buffer);return(a.buffer===n.buffer?a:a=new DataView(n.buffer)).setUint32(r,5,!0),t.clearLastError()},napi_get_null:function(e,r){if(!e)return 1;var t=l.envStore.get(e);if(t.checkGCAccess(),!r)return t.setLastError(1);r>>>=0;var a=new DataView(n.buffer);return(a.buffer===n.buffer?a:a=new DataView(n.buffer)).setUint32(r,2,!0),t.clearLastError()},napi_get_undefined:function(e,r){if(!e)return 1;var t=l.envStore.get(e);if(t.checkGCAccess(),!r)return t.setLastError(1);r>>>=0;var a=new DataView(n.buffer);return(a.buffer===n.buffer?a:a=new DataView(n.buffer)).setUint32(r,1,!0),t.clearLastError()}});var he=Object.freeze({__proto__:null,napi_get_instance_data:function(e,r){if(!e)return 1;var t=l.envStore.get(e);if(!r)return t.setLastError(1);r>>>=0;var a=t.getInstanceData(),o=new DataView(n.buffer);return(o.buffer===n.buffer?o:o=new DataView(n.buffer)).setUint32(r,a,!0),t.clearLastError()},napi_set_instance_data:function(e,r,t,n){if(!e)return 1;var a=l.envStore.get(e);return r>>>=0,t>>>=0,n>>>=0,a.setInstanceData(r,t,n),a.clearLastError()}});var ye=Object.freeze({__proto__:null,_emnapi_get_last_error_info:function(e,r,t,a){r>>>=0,t>>>=0,a>>>=0;var o=l.envStore.get(e).lastError,i=o.errorCode,s=o.engineErrorCode>>>0,f=o.engineReserved;f>>>=0;var u=new DataView(n.buffer),c=function(){return u.buffer===n.buffer?u:u=new DataView(n.buffer)};c().setInt32(r,i,!0),c().setUint32(t,s,!0),c().setUint32(a,f,!0)},napi_create_error:function(e,r,t,a){if(!e)return 1;var o=l.envStore.get(e);if(o.checkGCAccess(),!t)return o.setLastError(1);if(!a)return o.setLastError(1);var i=l.handleStore.get(t).value;if("string"!=typeof i)return o.setLastError(3);var s=new Error(i);if(r){var f=l.handleStore.get(r).value;if("string"!=typeof f)return o.setLastError(3);s.code=f}a>>>=0;var u=l.addToCurrentScope(s).id,c=new DataView(n.buffer);return(c.buffer===n.buffer?c:c=new DataView(n.buffer)).setUint32(a,u,!0),o.clearLastError()},napi_create_range_error:function(e,r,t,a){if(!e)return 1;var o=l.envStore.get(e);if(o.checkGCAccess(),!t)return o.setLastError(1);if(!a)return o.setLastError(1);var i=l.handleStore.get(t).value;if("string"!=typeof i)return o.setLastError(3);var s=new RangeError(i);if(r){var f=l.handleStore.get(r).value;if("string"!=typeof f)return o.setLastError(3);s.code=f}a>>>=0;var u=l.addToCurrentScope(s).id,c=new DataView(n.buffer);return(c.buffer===n.buffer?c:c=new DataView(n.buffer)).setUint32(a,u,!0),o.clearLastError()},napi_create_type_error:function(e,r,t,a){if(!e)return 1;var o=l.envStore.get(e);if(o.checkGCAccess(),!t)return o.setLastError(1);if(!a)return o.setLastError(1);var i=l.handleStore.get(t).value;if("string"!=typeof i)return o.setLastError(3);var s=new TypeError(i);if(r){var f=l.handleStore.get(r).value;if("string"!=typeof f)return o.setLastError(3);s.code=f}a>>>=0;var u=l.addToCurrentScope(s).id,c=new DataView(n.buffer);return(c.buffer===n.buffer?c:c=new DataView(n.buffer)).setUint32(a,u,!0),o.clearLastError()},napi_fatal_error:function(e,r,t,n){e>>>=0,r>>>=0,t>>>=0,n>>>=0;var a=H.UTF8ToString(e,r),o=H.UTF8ToString(t,n);p?p.napi.fatalError(a,o):c("FATAL ERROR: "+a+" "+o)},napi_fatal_exception:function(e,r){if(!e)return 1;var t=l.envStore.get(e);if(t.checkGCAccess(),!t.tryCatch.isEmpty())return t.setLastError(10);if(!t.canCallIntoJs())return t.setLastError(t.moduleApiVersion>=10?23:10);t.clearLastError();try{if(!r)return t.setLastError(1);var n=t.ctx.handleStore.get(r);try{t.triggerFatalException(n.value)}catch(e){return t.setLastError(9)}return t.clearLastError()}catch(r){return t.tryCatch.setError(r),t.setLastError(10)}},napi_get_and_clear_last_exception:function(e,r){if(!e)return 1;var t=l.envStore.get(e);if(t.checkGCAccess(),!r)return t.setLastError(1);r>>>=0;var a=new DataView(n.buffer),o=function(){return a.buffer===n.buffer?a:a=new DataView(n.buffer)};if(!t.tryCatch.hasCaught())return o().setUint32(r,1,!0),t.clearLastError();var i=t.tryCatch.exception(),s=t.ensureHandleId(i);return o().setUint32(r,s,!0),t.tryCatch.reset(),t.clearLastError()},napi_is_exception_pending:function(e,r){if(!e)return 1;var t=l.envStore.get(e);if(t.checkGCAccess(),!r)return t.setLastError(1);var a=t.tryCatch.hasCaught();r>>>=0;var o=new DataView(n.buffer);return(o.buffer===n.buffer?o:o=new DataView(n.buffer)).setInt8(r,a?1:0,!0),t.clearLastError()},napi_throw:function(e,r){if(!e)return 1;var t=l.envStore.get(e);if(t.checkGCAccess(),!t.tryCatch.isEmpty())return t.setLastError(10);if(!t.canCallIntoJs())return t.setLastError(t.moduleApiVersion>=10?23:10);t.clearLastError();try{return r?(t.tryCatch.setError(l.handleStore.get(r).value),t.clearLastError()):t.setLastError(1)}catch(e){return t.tryCatch.setError(e),t.setLastError(10)}},napi_throw_error:function(e,r,t){if(!e)return 1;var n=l.envStore.get(e);if(n.checkGCAccess(),!n.tryCatch.isEmpty())return n.setLastError(10);if(!n.canCallIntoJs())return n.setLastError(n.moduleApiVersion>=10?23:10);n.clearLastError();try{if(!t)return n.setLastError(1);r>>>=0,t>>>=0;var a=new Error(H.UTF8ToString(t,-1));return r&&(a.code=H.UTF8ToString(r,-1)),n.tryCatch.setError(a),n.clearLastError()}catch(e){return n.tryCatch.setError(e),n.setLastError(10)}},napi_throw_range_error:function(e,r,t){if(!e)return 1;var n=l.envStore.get(e);if(n.checkGCAccess(),!n.tryCatch.isEmpty())return n.setLastError(10);if(!n.canCallIntoJs())return n.setLastError(n.moduleApiVersion>=10?23:10);n.clearLastError();try{if(!t)return n.setLastError(1);r>>>=0,t>>>=0;var a=new RangeError(H.UTF8ToString(t,-1));return r&&(a.code=H.UTF8ToString(r,-1)),n.tryCatch.setError(a),n.clearLastError()}catch(e){return n.tryCatch.setError(e),n.setLastError(10)}},napi_throw_type_error:function(e,r,t){if(!e)return 1;var n=l.envStore.get(e);if(n.checkGCAccess(),!n.tryCatch.isEmpty())return n.setLastError(10);if(!n.canCallIntoJs())return n.setLastError(n.moduleApiVersion>=10?23:10);n.clearLastError();try{if(!t)return n.setLastError(1);r>>>=0,t>>>=0;var a=new TypeError(H.UTF8ToString(t,-1));return r&&(a.code=H.UTF8ToString(r,-1)),n.tryCatch.setError(a),n.clearLastError()}catch(e){return n.tryCatch.setError(e),n.setLastError(10)}},node_api_create_syntax_error:function(e,r,t,a){if(!e)return 1;var o=l.envStore.get(e);if(o.checkGCAccess(),!t)return o.setLastError(1);if(!a)return o.setLastError(1);var i=l.handleStore.get(t).value;if("string"!=typeof i)return o.setLastError(3);var s=new SyntaxError(i);if(r){var f=l.handleStore.get(r).value;if("string"!=typeof f)return o.setLastError(3);s.code=f}a>>>=0;var u=l.addToCurrentScope(s).id,c=new DataView(n.buffer);return(c.buffer===n.buffer?c:c=new DataView(n.buffer)).setUint32(a,u,!0),o.clearLastError()},node_api_throw_syntax_error:function(e,r,t){if(!e)return 1;var n=l.envStore.get(e);if(n.checkGCAccess(),!n.tryCatch.isEmpty())return n.setLastError(10);if(!n.canCallIntoJs())return n.setLastError(n.moduleApiVersion>=10?23:10);n.clearLastError();try{if(!t)return n.setLastError(1);r>>>=0,t>>>=0;var a=new SyntaxError(H.UTF8ToString(t,-1));return r&&(a.code=H.UTF8ToString(r,-1)),n.tryCatch.setError(a),n.clearLastError()}catch(e){return n.tryCatch.setError(e),n.setLastError(10)}}});function ge(e,r,t,a,o,i){t>>>=0;var s=l.envStore.get(e),f=re(s,r,t,a,o);if(0!==f.status)return s.setLastError(f.status);var u=f.f;i>>>=0;var c=l.addToCurrentScope(u).id,d=new DataView(n.buffer);return(d.buffer===n.buffer?d:d=new DataView(n.buffer)).setUint32(i,c,!0),s.getReturnStatus()}var we=Object.freeze({__proto__:null,_emnapi_create_function:ge,napi_call_function:function(e,r,t,a,o,i){var s,f=0;if(!e)return 1;var u=l.envStore.get(e);if(u.checkGCAccess(),!u.tryCatch.isEmpty())return u.setLastError(10);if(!u.canCallIntoJs())return u.setLastError(u.moduleApiVersion>=10?23:10);u.clearLastError();try{if(!r)return u.setLastError(1);if(a>>>=0,o>>>=0,i>>>=0,(a>>>=0)>0&&!o)return u.setLastError(1);var c=l.handleStore.get(r).value;if(!t)return u.setLastError(1);var d=l.handleStore.get(t).value;if("function"!=typeof d)return u.setLastError(1);for(var p=[],v=new DataView(n.buffer),h=function(){return v.buffer===n.buffer?v:v=new DataView(n.buffer)};f=10?23:10);i.clearLastError();try{return o&&n?ge(e,r,t,n,a,o):i.setLastError(1)}catch(e){return i.tryCatch.setError(e),i.setLastError(10)}},napi_get_cb_info:function(e,r,t,a,o,i){if(!e)return 1;var s=l.envStore.get(e);if(!r)return s.setLastError(1);var f=l.scopeStore.get(r).callbackInfo;t>>>=0,a>>>=0;var u=new DataView(n.buffer),c=function(){return u.buffer===n.buffer?u:u=new DataView(n.buffer)};if(a){if(!t)return s.setLastError(1);var d=c().getUint32(t,!0);d>>>=0;for(var p=f.args.length,v=d>>=0;var g=s.ensureHandleId(f.thiz);c().setUint32(o,g,!0)}return i&&(i>>>=0,c().setUint32(i,f.data,!0)),s.clearLastError()},napi_get_new_target:function(e,r,t){if(!e)return 1;var a=l.envStore.get(e);if(a.checkGCAccess(),!r)return a.setLastError(1);if(!t)return a.setLastError(1);t>>>=0;var o=l.scopeStore.get(r).callbackInfo,i=o.thiz,s=o.fn,f=null==i||null==i.constructor?0:i instanceof s?a.ensureHandleId(i.constructor):0,u=new DataView(n.buffer);return(u.buffer===n.buffer?u:u=new DataView(n.buffer)).setUint32(t,f,!0),a.clearLastError()},napi_new_instance:function(e,r,t,a,o){var i,s;if(!e)return 1;var f=l.envStore.get(e);if(f.checkGCAccess(),!f.tryCatch.isEmpty())return f.setLastError(10);if(!f.canCallIntoJs())return f.setLastError(f.moduleApiVersion>=10?23:10);f.clearLastError();try{if(!r)return f.setLastError(1);if(t>>>=0,a>>>=0,o>>>=0,(t>>>=0)>0&&!a)return f.setLastError(1);if(!o)return f.setLastError(1);var u=l.handleStore.get(r).value;if("function"!=typeof u)return f.setLastError(1);var c=void 0,d=new DataView(n.buffer),p=function(){return d.buffer===n.buffer?d:d=new DataView(n.buffer)};if(l.feature.supportReflect){var v=Array(t);for(i=0;i>>=0,t>>>=0,l.addCleanupHook(n,r,t),0):n.setLastError(1)},napi_close_escapable_handle_scope:function(e,r){if(!e)return 1;var t=l.envStore.get(e);return t.checkGCAccess(),r?0===t.openHandleScopes?13:(l.closeScope(t),t.clearLastError()):t.setLastError(1)},napi_close_handle_scope:function(e,r){if(!e)return 1;var t=l.envStore.get(e);return t.checkGCAccess(),r?0===t.openHandleScopes?13:(l.closeScope(t),t.clearLastError()):t.setLastError(1)},napi_create_reference:function(e,r,t,a){if(!e)return 1;var o=l.envStore.get(e);if(o.checkGCAccess(),!r)return o.setLastError(1);if(!a)return o.setLastError(1);var i=l.handleStore.get(r);if(o.moduleApiVersion<10&&!(i.isObject()||i.isFunction()||i.isSymbol()))return o.setLastError(1);var s=l.createReference(o,i.id,t>>>0,1);a>>>=0;var f=new DataView(n.buffer);return(f.buffer===n.buffer?f:f=new DataView(n.buffer)).setUint32(a,s.id,!0),o.clearLastError()},napi_delete_reference:function(e,r){if(!e)return 1;var t=l.envStore.get(e);return r?(l.refStore.get(r).dispose(),t.clearLastError()):t.setLastError(1)},napi_escape_handle:function(e,r,t,a){if(!e)return 1;var o=l.envStore.get(e);if(o.checkGCAccess(),!r)return o.setLastError(1);if(!t)return o.setLastError(1);if(!a)return o.setLastError(1);var i=l.scopeStore.get(r);if(!i.escapeCalled()){t>>>=0,a>>>=0;var s=i.escape(t),f=s?s.id:0,u=new DataView(n.buffer);return(u.buffer===n.buffer?u:u=new DataView(n.buffer)).setUint32(a,f,!0),o.clearLastError()}return o.setLastError(12)},napi_get_reference_value:function(e,r,t){if(!e)return 1;var a=l.envStore.get(e);if(a.checkGCAccess(),!r)return a.setLastError(1);if(!t)return a.setLastError(1);var o=l.refStore.get(r).get(a);t>>>=0;var i=new DataView(n.buffer);return(i.buffer===n.buffer?i:i=new DataView(n.buffer)).setUint32(t,o,!0),a.clearLastError()},napi_open_escapable_handle_scope:function(e,r){if(!e)return 1;var t=l.envStore.get(e);if(t.checkGCAccess(),!r)return t.setLastError(1);var a=l.openScope(t);r>>>=0;var o=new DataView(n.buffer);return(o.buffer===n.buffer?o:o=new DataView(n.buffer)).setUint32(r,a.id,!0),t.clearLastError()},napi_open_handle_scope:function(e,r){if(!e)return 1;var t=l.envStore.get(e);if(t.checkGCAccess(),!r)return t.setLastError(1);var a=l.openScope(t);r>>>=0;var o=new DataView(n.buffer);return(o.buffer===n.buffer?o:o=new DataView(n.buffer)).setUint32(r,a.id,!0),t.clearLastError()},napi_reference_ref:function(e,r,t){if(!e)return 1;var a=l.envStore.get(e);if(a.checkGCAccess(),!r)return a.setLastError(1);var o=l.refStore.get(r).ref();if(t){t>>>=0;var i=new DataView(n.buffer);(i.buffer===n.buffer?i:i=new DataView(n.buffer)).setUint32(t,o,!0)}return a.clearLastError()},napi_reference_unref:function(e,r,t){if(!e)return 1;var a=l.envStore.get(e);if(a.checkGCAccess(),!r)return a.setLastError(1);var o=l.refStore.get(r);if(0===o.refcount())return a.setLastError(9);var i=o.unref();if(t){t>>>=0;var s=new DataView(n.buffer);(s.buffer===n.buffer?s:s=new DataView(n.buffer)).setUint32(t,i,!0)}return a.clearLastError()},napi_remove_env_cleanup_hook:function(e,r,t){if(!e)return 1;var n=l.envStore.get(e);return r?(r>>>=0,t>>>=0,l.removeCleanupHook(n,r,t),0):n.setLastError(1)}});var _e=Object.freeze({__proto__:null,_emnapi_get_filename:function(e,r,t){var n=l.envStore.get(e).filename;return r?H.stringToUTF8(n,r,t):H.lengthBytesUTF8(n)}});var Ee=Object.freeze({__proto__:null,napi_create_promise:function(e,r,t){var a,o;if(!e)return 1;var i=l.envStore.get(e);if(i.checkGCAccess(),!i.tryCatch.isEmpty())return i.setLastError(10);if(!i.canCallIntoJs())return i.setLastError(i.moduleApiVersion>=10?23:10);i.clearLastError();try{if(!r)return i.setLastError(1);if(!t)return i.setLastError(1);var s=new DataView(n.buffer),f=function(){return s.buffer===n.buffer?s:s=new DataView(n.buffer)},u=new Promise(function(e,t){var n=l.createDeferred({resolve:e,reject:t});a=n.id,r>>>=0,f().setUint32(r,a,!0)});return t>>>=0,o=l.addToCurrentScope(u).id,f().setUint32(t,o,!0),i.getReturnStatus()}catch(e){return i.tryCatch.setError(e),i.setLastError(10)}},napi_is_promise:function(e,r,t){if(!e)return 1;var a=l.envStore.get(e);if(a.checkGCAccess(),!r)return a.setLastError(1);if(!t)return a.setLastError(1);t>>>=0;var o=l.handleStore.get(r).isPromise()?1:0,i=new DataView(n.buffer);return(i.buffer===n.buffer?i:i=new DataView(n.buffer)).setInt8(t,o,!0),a.clearLastError()},napi_reject_deferred:function(e,r,t){if(!e)return 1;var n=l.envStore.get(e);if(n.checkGCAccess(),!n.tryCatch.isEmpty())return n.setLastError(10);if(!n.canCallIntoJs())return n.setLastError(n.moduleApiVersion>=10?23:10);n.clearLastError();try{return r&&t?(l.deferredStore.get(r).reject(l.handleStore.get(t).value),n.getReturnStatus()):n.setLastError(1)}catch(e){return n.tryCatch.setError(e),n.setLastError(10)}},napi_resolve_deferred:function(e,r,t){if(!e)return 1;var n=l.envStore.get(e);if(n.checkGCAccess(),!n.tryCatch.isEmpty())return n.setLastError(10);if(!n.canCallIntoJs())return n.setLastError(n.moduleApiVersion>=10?23:10);n.clearLastError();try{return r&&t?(l.deferredStore.get(r).resolve(l.handleStore.get(t).value),n.getReturnStatus()):n.setLastError(1)}catch(e){return n.tryCatch.setError(e),n.setLastError(10)}}});function me(e,r,t,a,o,i){var s;if(!e)return 1;var f=l.envStore.get(e);if(f.checkGCAccess(),!f.tryCatch.isEmpty())return f.setLastError(10);if(!f.canCallIntoJs())return f.setLastError(f.moduleApiVersion>=10?23:10);f.clearLastError();try{if(!i)return f.setLastError(1);if(!r)return f.setLastError(1);var u=l.handleStore.get(r);if(null==u.value)throw new TypeError("Cannot convert undefined or null to object");var c=void 0;try{c=u.isObject()||u.isFunction()?u.value:Object(u.value)}catch(e){return f.setLastError(2)}if(0!==t&&1!==t)return f.setLastError(1);if(0!==o&&1!==o)return f.setLastError(1);var d=[],p=void 0,v=void 0,h=void 0,y=!0,g=/^(0|[1-9][0-9]*)$/;do{for(p=Object.getOwnPropertyNames(c),v=Object.getOwnPropertySymbols(c),h=0;h>>=0,s=l.addToCurrentScope(w).id;var A=new DataView(n.buffer);return(A.buffer===n.buffer?A:A=new DataView(n.buffer)).setUint32(i,s,!0),f.getReturnStatus()}catch(e){return f.tryCatch.setError(e),f.setLastError(10)}}var Le=Object.freeze({__proto__:null,napi_define_properties:function(e,r,t,a){var o,i;if(!e)return 1;var s=l.envStore.get(e);if(s.checkGCAccess(),!s.tryCatch.isEmpty())return s.setLastError(10);if(!s.canCallIntoJs())return s.setLastError(s.moduleApiVersion>=10?23:10);s.clearLastError();try{if(a>>>=0,t>>>=0,(t>>>=0)>0&&!a)return s.setLastError(1);if(!r)return s.setLastError(1);var f=l.handleStore.get(r),u=f.value;if(!f.isObject()&&!f.isFunction())return s.setLastError(2);for(var c=void 0,d=new DataView(n.buffer),p=function(){return d.buffer===n.buffer?d:d=new DataView(n.buffer)},v=0;v>>=0;var E=p().getUint32(o+28,!0);if(h)c=H.UTF8ToString(h,-1);else{if(!y)return s.setLastError(4);if("string"!=typeof(c=l.handleStore.get(y).value)&&"symbol"!=typeof c)return s.setLastError(4)}te(s,u,c,g,w,b,_,i,E)}return s.getReturnStatus()}catch(e){return s.tryCatch.setError(e),s.setLastError(10)}},napi_delete_element:function(e,r,t,a){var o;if(!e)return 1;var i=l.envStore.get(e);if(i.checkGCAccess(),!i.tryCatch.isEmpty())return i.setLastError(10);if(!i.canCallIntoJs())return i.setLastError(i.moduleApiVersion>=10?23:10);i.clearLastError();try{if(!r)return i.setLastError(1);var s=l.handleStore.get(r);if(!s.isObject()&&!s.isFunction())return i.setLastError(2);if(l.feature.supportReflect)o=Reflect.deleteProperty(s.value,t>>>0);else try{o=delete s.value[t>>>0]}catch(e){o=!1}if(a){a>>>=0;var f=new DataView(n.buffer);(f.buffer===n.buffer?f:f=new DataView(n.buffer)).setInt8(a,o?1:0,!0)}return i.getReturnStatus()}catch(e){return i.tryCatch.setError(e),i.setLastError(10)}},napi_delete_property:function(e,r,t,a){var o;if(!e)return 1;var i=l.envStore.get(e);if(i.checkGCAccess(),!i.tryCatch.isEmpty())return i.setLastError(10);if(!i.canCallIntoJs())return i.setLastError(i.moduleApiVersion>=10?23:10);i.clearLastError();try{if(!t)return i.setLastError(1);if(!r)return i.setLastError(1);var s=l.handleStore.get(r);if(!s.isObject()&&!s.isFunction())return i.setLastError(2);var f=l.handleStore.get(t).value;if(l.feature.supportReflect)o=Reflect.deleteProperty(s.value,f);else try{o=delete s.value[f]}catch(e){o=!1}if(a){a>>>=0;var u=new DataView(n.buffer);(u.buffer===n.buffer?u:u=new DataView(n.buffer)).setInt8(a,o?1:0,!0)}return i.getReturnStatus()}catch(e){return i.tryCatch.setError(e),i.setLastError(10)}},napi_get_all_property_names:me,napi_get_element:function(e,r,t,a){var o;if(!e)return 1;var i=l.envStore.get(e);if(i.checkGCAccess(),!i.tryCatch.isEmpty())return i.setLastError(10);if(!i.canCallIntoJs())return i.setLastError(i.moduleApiVersion>=10?23:10);i.clearLastError();try{if(!a)return i.setLastError(1);if(!r)return i.setLastError(1);var s=l.handleStore.get(r);if(null==s.value)throw new TypeError("Cannot convert undefined or null to object");var f=void 0;try{f=s.isObject()||s.isFunction()?s.value:Object(s.value)}catch(e){return i.setLastError(2)}a>>>=0,o=i.ensureHandleId(f[t>>>0]);var u=new DataView(n.buffer);return(u.buffer===n.buffer?u:u=new DataView(n.buffer)).setUint32(a,o,!0),i.getReturnStatus()}catch(e){return i.tryCatch.setError(e),i.setLastError(10)}},napi_get_named_property:function(e,r,t,a){var o;if(!e)return 1;var i=l.envStore.get(e);if(i.checkGCAccess(),!i.tryCatch.isEmpty())return i.setLastError(10);if(!i.canCallIntoJs())return i.setLastError(i.moduleApiVersion>=10?23:10);i.clearLastError();try{if(!a)return i.setLastError(1);if(!r)return i.setLastError(1);if(!t)return i.setLastError(1);var s=l.handleStore.get(r);if(null==s.value)throw new TypeError("Cannot convert undefined or null to object");var f=void 0;try{f=s.isObject()||s.isFunction()?s.value:Object(s.value)}catch(e){return i.setLastError(2)}t>>>=0,a>>>=0,o=i.ensureHandleId(f[H.UTF8ToString(t,-1)]);var u=new DataView(n.buffer);return(u.buffer===n.buffer?u:u=new DataView(n.buffer)).setUint32(a,o,!0),i.getReturnStatus()}catch(e){return i.tryCatch.setError(e),i.setLastError(10)}},napi_get_property:function(e,r,t,a){var o;if(!e)return 1;var i=l.envStore.get(e);if(i.checkGCAccess(),!i.tryCatch.isEmpty())return i.setLastError(10);if(!i.canCallIntoJs())return i.setLastError(i.moduleApiVersion>=10?23:10);i.clearLastError();try{if(!t)return i.setLastError(1);if(!a)return i.setLastError(1);if(!r)return i.setLastError(1);var s=l.handleStore.get(r);if(null==s.value)throw new TypeError("Cannot convert undefined or null to object");var f=void 0;try{f=s.isObject()||s.isFunction()?s.value:Object(s.value)}catch(e){return i.setLastError(2)}a>>>=0,o=i.ensureHandleId(f[l.handleStore.get(t).value]);var u=new DataView(n.buffer);return(u.buffer===n.buffer?u:u=new DataView(n.buffer)).setUint32(a,o,!0),i.getReturnStatus()}catch(e){return i.tryCatch.setError(e),i.setLastError(10)}},napi_get_property_names:function(e,r,t){return me(e,r,0,18,1,t)},napi_has_element:function(e,r,t,a){var o;if(!e)return 1;var i=l.envStore.get(e);if(i.checkGCAccess(),!i.tryCatch.isEmpty())return i.setLastError(10);if(!i.canCallIntoJs())return i.setLastError(i.moduleApiVersion>=10?23:10);i.clearLastError();try{if(!a)return i.setLastError(1);if(!r)return i.setLastError(1);var s=l.handleStore.get(r);if(null==s.value)throw new TypeError("Cannot convert undefined or null to object");var f=void 0;try{f=s.isObject()||s.isFunction()?s.value:Object(s.value)}catch(e){return i.setLastError(2)}a>>>=0,o=t>>>0 in f?1:0;var u=new DataView(n.buffer);return(u.buffer===n.buffer?u:u=new DataView(n.buffer)).setInt8(a,o,!0),i.getReturnStatus()}catch(e){return i.tryCatch.setError(e),i.setLastError(10)}},napi_has_named_property:function(e,r,t,a){var o;if(!e)return 1;var i=l.envStore.get(e);if(i.checkGCAccess(),!i.tryCatch.isEmpty())return i.setLastError(10);if(!i.canCallIntoJs())return i.setLastError(i.moduleApiVersion>=10?23:10);i.clearLastError();try{if(!a)return i.setLastError(1);if(!r)return i.setLastError(1);if(!t)return i.setLastError(1);var s=l.handleStore.get(r);if(null==s.value)throw new TypeError("Cannot convert undefined or null to object");var f=void 0;try{f=s.isObject()||s.isFunction()?s.value:Object(s.value)}catch(e){return i.setLastError(2)}t>>>=0,a>>>=0,o=H.UTF8ToString(t,-1)in f;var u=new DataView(n.buffer);return(u.buffer===n.buffer?u:u=new DataView(n.buffer)).setInt8(a,o?1:0,!0),i.getReturnStatus()}catch(e){return i.tryCatch.setError(e),i.setLastError(10)}},napi_has_own_property:function(e,r,t,a){var o;if(!e)return 1;var i=l.envStore.get(e);if(i.checkGCAccess(),!i.tryCatch.isEmpty())return i.setLastError(10);if(!i.canCallIntoJs())return i.setLastError(i.moduleApiVersion>=10?23:10);i.clearLastError();try{if(!t)return i.setLastError(1);if(!a)return i.setLastError(1);if(!r)return i.setLastError(1);var s=l.handleStore.get(r);if(null==s.value)throw new TypeError("Cannot convert undefined or null to object");var f=void 0;try{f=s.isObject()||s.isFunction()?s.value:Object(s.value)}catch(e){return i.setLastError(2)}var u=l.handleStore.get(t).value;if("string"!=typeof u&&"symbol"!=typeof u)return i.setLastError(4);o=Object.prototype.hasOwnProperty.call(f,l.handleStore.get(t).value),a>>>=0;var c=new DataView(n.buffer);return(c.buffer===n.buffer?c:c=new DataView(n.buffer)).setInt8(a,o?1:0,!0),i.getReturnStatus()}catch(e){return i.tryCatch.setError(e),i.setLastError(10)}},napi_has_property:function(e,r,t,a){var o;if(!e)return 1;var i=l.envStore.get(e);if(i.checkGCAccess(),!i.tryCatch.isEmpty())return i.setLastError(10);if(!i.canCallIntoJs())return i.setLastError(i.moduleApiVersion>=10?23:10);i.clearLastError();try{if(!t)return i.setLastError(1);if(!a)return i.setLastError(1);if(!r)return i.setLastError(1);var s=l.handleStore.get(r);if(null==s.value)throw new TypeError("Cannot convert undefined or null to object");var f=void 0;try{f=s.isObject()||s.isFunction()?s.value:Object(s.value)}catch(e){return i.setLastError(2)}a>>>=0,o=l.handleStore.get(t).value in f?1:0;var u=new DataView(n.buffer);return(u.buffer===n.buffer?u:u=new DataView(n.buffer)).setInt8(a,o,!0),i.getReturnStatus()}catch(e){return i.tryCatch.setError(e),i.setLastError(10)}},napi_object_freeze:function(e,r){if(!e)return 1;var t=l.envStore.get(e);if(t.checkGCAccess(),!t.tryCatch.isEmpty())return t.setLastError(10);if(!t.canCallIntoJs())return t.setLastError(t.moduleApiVersion>=10?23:10);t.clearLastError();try{if(!r)return t.setLastError(1);var n=l.handleStore.get(r),a=n.value;return n.isObject()||n.isFunction()?(Object.freeze(a),t.getReturnStatus()):t.setLastError(2)}catch(e){return t.tryCatch.setError(e),t.setLastError(10)}},napi_object_seal:function(e,r){if(!e)return 1;var t=l.envStore.get(e);if(t.checkGCAccess(),!t.tryCatch.isEmpty())return t.setLastError(10);if(!t.canCallIntoJs())return t.setLastError(t.moduleApiVersion>=10?23:10);t.clearLastError();try{if(!r)return t.setLastError(1);var n=l.handleStore.get(r),a=n.value;return n.isObject()||n.isFunction()?(Object.seal(a),t.getReturnStatus()):t.setLastError(2)}catch(e){return t.tryCatch.setError(e),t.setLastError(10)}},napi_set_element:function(e,r,t,n){if(!e)return 1;var a=l.envStore.get(e);if(a.checkGCAccess(),!a.tryCatch.isEmpty())return a.setLastError(10);if(!a.canCallIntoJs())return a.setLastError(a.moduleApiVersion>=10?23:10);a.clearLastError();try{if(!n)return a.setLastError(1);if(!r)return a.setLastError(1);var o=l.handleStore.get(r);return o.isObject()||o.isFunction()?(o.value[t>>>0]=l.handleStore.get(n).value,a.getReturnStatus()):a.setLastError(2)}catch(e){return a.tryCatch.setError(e),a.setLastError(10)}},napi_set_named_property:function(e,r,t,n){if(!e)return 1;var a=l.envStore.get(e);if(a.checkGCAccess(),!a.tryCatch.isEmpty())return a.setLastError(10);if(!a.canCallIntoJs())return a.setLastError(a.moduleApiVersion>=10?23:10);a.clearLastError();try{if(!n)return a.setLastError(1);if(!r)return a.setLastError(1);var o=l.handleStore.get(r);return o.isObject()||o.isFunction()?t?(t>>>=0,l.handleStore.get(r).value[H.UTF8ToString(t,-1)]=l.handleStore.get(n).value,a.getReturnStatus()):a.setLastError(1):a.setLastError(2)}catch(e){return a.tryCatch.setError(e),a.setLastError(10)}},napi_set_property:function(e,r,t,n){if(!e)return 1;var a=l.envStore.get(e);if(a.checkGCAccess(),!a.tryCatch.isEmpty())return a.setLastError(10);if(!a.canCallIntoJs())return a.setLastError(a.moduleApiVersion>=10?23:10);a.clearLastError();try{if(!t)return a.setLastError(1);if(!n)return a.setLastError(1);if(!r)return a.setLastError(1);var o=l.handleStore.get(r);return o.isObject()||o.isFunction()?(o.value[l.handleStore.get(t).value]=l.handleStore.get(n).value,a.getReturnStatus()):a.setLastError(2)}catch(e){return a.tryCatch.setError(e),a.setLastError(10)}}});var Ae=Object.freeze({__proto__:null,napi_run_script:function(e,r,t){var a,o;if(!e)return 1;var i=l.envStore.get(e);if(i.checkGCAccess(),!i.tryCatch.isEmpty())return i.setLastError(10);if(!i.canCallIntoJs())return i.setLastError(i.moduleApiVersion>=10?23:10);i.clearLastError();try{if(!r)return i.setLastError(1);if(!t)return i.setLastError(1);var s=l.handleStore.get(r);if(!s.isString())return i.setLastError(3);var f=l.handleStore.get(5).value.eval(s.value);t>>>=0,o=i.ensureHandleId(f);var u=new DataView(n.buffer);(u.buffer===n.buffer?u:u=new DataView(n.buffer)).setUint32(t,o,!0),a=i.getReturnStatus()}catch(e){return i.tryCatch.setError(e),i.setLastError(10)}return a}});var Se=Object.freeze({__proto__:null,napi_coerce_to_bool:function(e,r,t){var a;if(!e)return 1;var o=l.envStore.get(e);if(o.checkGCAccess(),!o.tryCatch.isEmpty())return o.setLastError(10);if(!o.canCallIntoJs())return o.setLastError(o.moduleApiVersion>=10?23:10);o.clearLastError();try{if(!r)return o.setLastError(1);if(!t)return o.setLastError(1);var i=l.handleStore.get(r);t>>>=0,a=i.value?4:3;var s=new DataView(n.buffer);return(s.buffer===n.buffer?s:s=new DataView(n.buffer)).setUint32(t,a,!0),o.getReturnStatus()}catch(e){return o.tryCatch.setError(e),o.setLastError(10)}},napi_coerce_to_number:function(e,r,t){var a;if(!e)return 1;var o=l.envStore.get(e);if(o.checkGCAccess(),!o.tryCatch.isEmpty())return o.setLastError(10);if(!o.canCallIntoJs())return o.setLastError(o.moduleApiVersion>=10?23:10);o.clearLastError();try{if(!r)return o.setLastError(1);if(!t)return o.setLastError(1);var i=l.handleStore.get(r);if(i.isBigInt())throw new TypeError("Cannot convert a BigInt value to a number");t>>>=0,a=l.addToCurrentScope(Number(i.value)).id;var s=new DataView(n.buffer);return(s.buffer===n.buffer?s:s=new DataView(n.buffer)).setUint32(t,a,!0),o.getReturnStatus()}catch(e){return o.tryCatch.setError(e),o.setLastError(10)}},napi_coerce_to_object:function(e,r,t){var a;if(!e)return 1;var o=l.envStore.get(e);if(o.checkGCAccess(),!o.tryCatch.isEmpty())return o.setLastError(10);if(!o.canCallIntoJs())return o.setLastError(o.moduleApiVersion>=10?23:10);o.clearLastError();try{if(!r)return o.setLastError(1);if(!t)return o.setLastError(1);var i=l.handleStore.get(r);if(null==i.value)throw new TypeError("Cannot convert undefined or null to object");t>>>=0,a=o.ensureHandleId(Object(i.value));var s=new DataView(n.buffer);return(s.buffer===n.buffer?s:s=new DataView(n.buffer)).setUint32(t,a,!0),o.getReturnStatus()}catch(e){return o.tryCatch.setError(e),o.setLastError(10)}},napi_coerce_to_string:function(e,r,t){var a;if(!e)return 1;var o=l.envStore.get(e);if(o.checkGCAccess(),!o.tryCatch.isEmpty())return o.setLastError(10);if(!o.canCallIntoJs())return o.setLastError(o.moduleApiVersion>=10?23:10);o.clearLastError();try{if(!r)return o.setLastError(1);if(!t)return o.setLastError(1);var i=l.handleStore.get(r);if(i.isSymbol())throw new TypeError("Cannot convert a Symbol value to a string");t>>>=0,a=l.addToCurrentScope(String(i.value)).id;var s=new DataView(n.buffer);return(s.buffer===n.buffer?s:s=new DataView(n.buffer)).setUint32(t,a,!0),o.getReturnStatus()}catch(e){return o.tryCatch.setError(e),o.setLastError(10)}},napi_detach_arraybuffer:function(e,r){if(!e)return 1;var t=l.envStore.get(e);if(t.checkGCAccess(),!r)return t.setLastError(1);var n=l.handleStore.get(r).value;if(!(n instanceof ArrayBuffer))return"function"==typeof SharedArrayBuffer&&n instanceof SharedArrayBuffer?t.setLastError(20):t.setLastError(19);try{(new(0,l.feature.MessageChannel)).port1.postMessage(n,[n])}catch(e){return t.setLastError(9)}return t.clearLastError()},napi_instanceof:function(e,r,t,a){var o;if(!e)return 1;var i=l.envStore.get(e);if(i.checkGCAccess(),!i.tryCatch.isEmpty())return i.setLastError(10);if(!i.canCallIntoJs())return i.setLastError(i.moduleApiVersion>=10?23:10);i.clearLastError();try{if(!r)return i.setLastError(1);if(!a)return i.setLastError(1);if(!t)return i.setLastError(1);a>>>=0;var s=new DataView(n.buffer),f=function(){return s.buffer===n.buffer?s:s=new DataView(n.buffer)};f().setInt8(a,0,!0);var u=l.handleStore.get(t);return u.isFunction()?(o=l.handleStore.get(r).value instanceof u.value?1:0,f().setInt8(a,o,!0),i.getReturnStatus()):i.setLastError(5)}catch(e){return i.tryCatch.setError(e),i.setLastError(10)}},napi_is_array:function(e,r,t){if(!e)return 1;var a=l.envStore.get(e);if(a.checkGCAccess(),!r)return a.setLastError(1);if(!t)return a.setLastError(1);t>>>=0;var o=l.handleStore.get(r).isArray()?1:0,i=new DataView(n.buffer);return(i.buffer===n.buffer?i:i=new DataView(n.buffer)).setInt8(t,o,!0),a.clearLastError()},napi_is_arraybuffer:function(e,r,t){if(!e)return 1;var a=l.envStore.get(e);if(a.checkGCAccess(),!r)return a.setLastError(1);if(!t)return a.setLastError(1);t>>>=0;var o=l.handleStore.get(r).isArrayBuffer()?1:0,i=new DataView(n.buffer);return(i.buffer===n.buffer?i:i=new DataView(n.buffer)).setInt8(t,o,!0),a.clearLastError()},napi_is_buffer:function(e,r,t){if(!e)return 1;var a=l.envStore.get(e);if(a.checkGCAccess(),!r)return a.setLastError(1);if(!t)return a.setLastError(1);t>>>=0;var o=l.handleStore.get(r).isBuffer(l.feature.Buffer)?1:0,i=new DataView(n.buffer);return(i.buffer===n.buffer?i:i=new DataView(n.buffer)).setInt8(t,o,!0),a.clearLastError()},napi_is_dataview:function(e,r,t){if(!e)return 1;var a=l.envStore.get(e);if(a.checkGCAccess(),!r)return a.setLastError(1);if(!t)return a.setLastError(1);t>>>=0;var o=l.handleStore.get(r).isDataView()?1:0,i=new DataView(n.buffer);return(i.buffer===n.buffer?i:i=new DataView(n.buffer)).setInt8(t,o,!0),a.clearLastError()},napi_is_date:function(e,r,t){if(!e)return 1;var a=l.envStore.get(e);if(a.checkGCAccess(),!r)return a.setLastError(1);if(!t)return a.setLastError(1);t>>>=0;var o=l.handleStore.get(r).isDate()?1:0,i=new DataView(n.buffer);return(i.buffer===n.buffer?i:i=new DataView(n.buffer)).setInt8(t,o,!0),a.clearLastError()},napi_is_detached_arraybuffer:function(e,r,t){if(!e)return 1;var a=l.envStore.get(e);if(a.checkGCAccess(),!a.tryCatch.isEmpty())return a.setLastError(10);if(!a.canCallIntoJs())return a.setLastError(a.moduleApiVersion>=10?23:10);a.clearLastError();try{if(!r)return a.setLastError(1);if(!t)return a.setLastError(1);var o=l.handleStore.get(r);t>>>=0;var i=new DataView(n.buffer),s=function(){return i.buffer===n.buffer?i:i=new DataView(n.buffer)};if(o.isArrayBuffer()&&0===o.value.byteLength)try{new Uint8Array(o.value)}catch(e){return s().setInt8(t,1,!0),a.getReturnStatus()}return s().setInt8(t,0,!0),a.getReturnStatus()}catch(e){return a.tryCatch.setError(e),a.setLastError(10)}},napi_is_error:function(e,r,t){if(!e)return 1;var a=l.envStore.get(e);if(a.checkGCAccess(),!r)return a.setLastError(1);if(!t)return a.setLastError(1);t>>>=0;var o=l.handleStore.get(r).value instanceof Error?1:0,i=new DataView(n.buffer);return(i.buffer===n.buffer?i:i=new DataView(n.buffer)).setInt8(t,o,!0),a.clearLastError()},napi_is_typedarray:function(e,r,t){if(!e)return 1;var a=l.envStore.get(e);if(a.checkGCAccess(),!r)return a.setLastError(1);if(!t)return a.setLastError(1);t>>>=0;var o=l.handleStore.get(r).isTypedArray()?1:0,i=new DataView(n.buffer);return(i.buffer===n.buffer?i:i=new DataView(n.buffer)).setInt8(t,o,!0),a.clearLastError()},napi_strict_equals:function(e,r,t,a){var o;if(!e)return 1;var i=l.envStore.get(e);if(i.checkGCAccess(),!i.tryCatch.isEmpty())return i.setLastError(10);if(!i.canCallIntoJs())return i.setLastError(i.moduleApiVersion>=10?23:10);i.clearLastError();try{if(!r)return i.setLastError(1);if(!t)return i.setLastError(1);if(!a)return i.setLastError(1);var s=l.handleStore.get(r).value,f=l.handleStore.get(t).value;a>>>=0,o=s===f?1:0;var u=new DataView(n.buffer);return(u.buffer===n.buffer?u:u=new DataView(n.buffer)).setInt8(a,o,!0),i.getReturnStatus()}catch(e){return i.tryCatch.setError(e),i.setLastError(10)}},napi_typeof:function(e,r,t){if(!e)return 1;var a=l.envStore.get(e);if(a.checkGCAccess(),!r)return a.setLastError(1);if(!t)return a.setLastError(1);var o,i=l.handleStore.get(r);if(t>>>=0,i.isNumber())o=3;else if(i.isBigInt())o=9;else if(i.isString())o=4;else if(i.isFunction())o=7;else if(i.isExternal())o=8;else if(i.isObject())o=6;else if(i.isBoolean())o=2;else if(i.isUndefined())o=0;else if(i.isSymbol())o=5;else{if(!i.isNull())return a.setLastError(1);o=1}var s=new DataView(n.buffer);return(s.buffer===n.buffer?s:s=new DataView(n.buffer)).setInt32(t,o,!0),a.clearLastError()},node_api_is_sharedarraybuffer:function(e,r,t){if(!e)return 1;var a=l.envStore.get(e);if(a.checkGCAccess(),!r)return a.setLastError(1);if(!t)return a.setLastError(1);var o=l.handleStore.get(r);t>>>=0;var i="function"==typeof SharedArrayBuffer&&o.value instanceof SharedArrayBuffer||"[object SharedArrayBuffer]"===Object.prototype.toString.call(o.value)?1:0,s=new DataView(n.buffer);return(s.buffer===n.buffer?s:s=new DataView(n.buffer)).setInt8(t,i,!0),a.clearLastError()}});var Ce=Object.freeze({__proto__:null,napi_get_version:function(e,r){if(!e)return 1;var t=l.envStore.get(e);if(!r)return t.setLastError(1);var a=new DataView(n.buffer);return(a.buffer===n.buffer?a:a=new DataView(n.buffer)).setUint32(r,10,!0),t.clearLastError()}});function Ve(e){for(var r=Object.keys(e),t=0;t>>=0,f>>>=0,e>>>=0,u>>>=0,c>>>=0,d>>>=0,p>>>=0,s>>>=0,0===(f>>>=0))return h.setLastError(1);if(!v)return h.setLastError(1);var y,g=0;if(r>>>=0){if("function"!=typeof l.handleStore.get(r).value)return h.setLastError(1);g=l.createReference(h,r,1,1).id}else if(!p)return h.setLastError(1);if(t){if(null==(y=l.handleStore.get(t).value))return h.setLastError(2);y=Object(y)}else y={};var w=h.ensureHandleId(y),b=l.handleStore.get(a).value;if("symbol"==typeof b)return h.setLastError(3);b=String(b);var _=h.ensureHandleId(b),E=M.offset.__size__,m=o(E);if(!m)return h.setLastError(9);m>>>=0,new Uint8Array(M.ensureBufferFor(m+E)).subarray(m,m+E).fill(0);var L=l.createReference(h,w,1,1),A=L.id,S=new DataView(n.buffer),C=function(){return S.buffer===n.buffer?S:S=new DataView(n.buffer)};return C().setUint32(m+M.offset.resource,A,!0),M.initQueue(m)?(O(w,_,-1,m+M.offset.async_id),C().setInt8(m+M.offset.is_some,1,!0),C().setUint32(m+M.offset.thread_count,f,!0),C().setUint32(m+M.offset.context,d,!0),C().setUint32(m+M.offset.max_queue_size,s,!0),C().setUint32(m+M.offset.ref,g,!0),C().setUint32(m+M.offset.env,e,!0),C().setUint32(m+M.offset.finalize_data,u,!0),C().setUint32(m+M.offset.finalize_cb,c,!0),C().setUint32(m+M.offset.call_js_cb,p,!0),l.addCleanupHook(h,M.cleanup,m),M._liveSet.add(m),h.ref(),l.increaseWaitingRequestCounter(),C().setUint32(m+M.offset.async_ref,1,!0),v>>>=0,C().setUint32(v,m,!0),h.clearLastError()):(i(m),L.dispose(),h.setLastError(9))},h.imports.napi.napi_get_threadsafe_function_context=function(e,r){if(!e||!r)return c(),1;e>>>=0,r>>>=0;var t=M.getContext(e),a=new DataView(n.buffer);return(a.buffer===n.buffer?a:a=new DataView(n.buffer)).setUint32(r,t,!0),0},h.imports.napi.napi_call_threadsafe_function=function(e,r,t){return e?(e>>>=0,r>>>=0,M.push(e,r,t)):(c(),1)},h.imports.napi.napi_acquire_threadsafe_function=function(e){return e?(e>>>=0,M.getMutex(e).execute(function(){return 0===M.getState(e)?(M.addThreadCount(e),0):16})):(c(),1)},h.imports.napi.napi_release_threadsafe_function=function(e,r){if(!e)return c(),1;e>>>=0;var t=M.getMutex(e),n=M.getCond(e),a=!1,o=t.execute(function(){return 0===M.getThreadCount(e)?1:(M.subThreadCount(e),0!==M.getThreadCount(e)&&1!==r||0===M.getState(e)&&(1===r&&M.setState(e,1),1===M.getState(e)&&M.getMaxQueueSize(e)>0&&n.signal(),M.send(e)),2!==M.getState(e)||0!==M.getThreadCount(e)||(a=!0),0)});return a&&M.destroy(e),o},h.imports.napi.napi_unref_threadsafe_function=function(e,r){if(!r)return c(),1;var t=(r>>>=0)+M.offset.async_ref,n=t>>>2,a=new Uint32Array(M.ensureBufferFor(t+4)),o=Atomics.load(a,n);return o>0&&(Atomics.store(a,n,o-1),1===o&&l.decreaseWaitingRequestCounter()),0},h.imports.napi.napi_ref_threadsafe_function=function(e,r){if(!r)return c(),1;var t=(r>>>=0)+M.offset.async_ref,n=t>>>2,a=new Uint32Array(M.ensureBufferFor(t+4)),o=Atomics.load(a,n);return o||l.increaseWaitingRequestCounter(),Atomics.store(a,n,o+1),0},h}();return t}function A(e,r,t,n){var a,o=(n=null!=n?n:{}).getMemory,i=n.getTable,s=n.beforeInit;if(null!=o&&"function"!=typeof o)throw new TypeError("options.getMemory is not a function");if(null!=i&&"function"!=typeof i)throw new TypeError("options.getTable is not a function");if(null!=s&&"function"!=typeof s)throw new TypeError("options.beforeInit is not a function");var f="object"==typeof r&&null!==r;if(f){if(r.loaded)throw new Error("napiModule has already loaded");a=r}else a=L(n);var u,c=n.wasi,l={env:a.imports.env,napi:a.imports.napi,emnapi:a.imports.emnapi};c&&(u=new b(a.childThread?{wasi:c,childThread:!0,postMessage:a.postMessage}:{wasi:c,threadManager:a.PThread,waitThreadStart:a.waitThreadStart}),Object.assign(l,"function"==typeof c.getImportObject?c.getImportObject():{wasi_snapshot_preview1:c.wasiImport}),Object.assign(l,u.getImportObject()));var d=n.overwriteImports;if("function"==typeof d){var p=d(l);"object"==typeof p&&null!==p&&(l=p)}return e(t,l,function(r,t){if(r)throw r;var n=t.instance,d=n,p=n.exports,v="memory"in p,h="memory"in l.env,y=o?o(p):v?p.memory:h?l.env.memory:void 0;if(!y)throw new Error("memory is neither exported nor imported");var g=i?i(p):p.__indirect_function_table;if(c&&!v){var w=Object.create(null);Object.assign(w,p,{memory:y}),d={exports:w}}var b=t.module;c?d=u.initialize(d,b,y):a.PThread.setup(b,y);var _=function(){s&&s({instance:n,module:b}),a.init({instance:d,module:b,memory:y,table:g});var e={instance:n,module:b,usedInstance:d};return f||(e.napiModule=a),e};if(a.PThread.shouldPreloadWorkers()){var E=a.PThread.loadWasmModuleToAllWorkers();if(e===S)return E.then(_);throw new Error("Synchronous loading is not supported with worker pool (reuseWorker.size > 0)")}return _()})}function S(e,r,t){return n(e,r).then(function(e){return t(null,e)},function(e){return t(e)})}function C(e,n,a){var o;try{o=function(e,n){if(!e)throw new TypeError("Invalid wasm source");var a;if(t(n),n=null!=n?n:{},e instanceof ArrayBuffer||ArrayBuffer.isView(e))a=new r.Module(e);else{if(!(e instanceof WebAssembly.Module))throw new TypeError("Invalid wasm source");a=e}return{instance:new r.Instance(a,n),module:a}}(e,n)}catch(e){return a(e)}return a(null,o)}var V=function(e,r){return V=Object.setPrototypeOf||{__proto__:[]}instanceof Array&&function(e,r){e.__proto__=r}||function(e,r){for(var t in r)Object.prototype.hasOwnProperty.call(r,t)&&(e[t]=r[t])},V(e,r)};var k=function(){return k=Object.assign||function(e){for(var r,t=1,n=arguments.length;ti(e,r))}catch(e){}if(e instanceof ArrayBuffer||ArrayBuffer.isView(e))return n.instantiate(e,r);if(e instanceof n.Module)return n.instantiate(e,r).then(r=>({instance:r,module:e}));if("undefined"!=typeof Response&&e instanceof Response)return e.arrayBuffer().then(e=>n.instantiate(e,r));const t="string"==typeof e;if(t||"undefined"!=typeof URL&&e instanceof URL){if(t&&"undefined"!=typeof wx&&"undefined"!=typeof __wxConfig)return n.instantiate(e,r);if("function"!=typeof fetch)throw new TypeError("wasm source can not be a string or URL in this environment");if("function"!=typeof n.instantiateStreaming)return i(fetch(e),r);try{return n.instantiateStreaming(fetch(e),r).catch(()=>i(fetch(e),r))}catch(t){return i(fetch(e),r)}}throw new TypeError("Invalid wasm source")}function o(r){var t=function(){var t,a,i,o,s,f="object"==typeof process&&null!==process&&"object"==typeof process.versions&&null!==process.versions&&"string"==typeof process.versions.node,u=Boolean(r.childThread),c="number"==typeof r.waitThreadStart?r.waitThreadStart:Boolean(r.waitThreadStart);function l(e){if("function"==typeof n.RuntimeError)throw new n.RuntimeError(e);throw Error(e)}var d,v,p,y={imports:{env:{},napi:{},emnapi:{}},exports:{},emnapi:{},loaded:!1,filename:"",childThread:u,initWorker:void 0,waitThreadStart:c,PThread:void 0,init:function(e){if(y.loaded)return y.exports;if(!e)throw new TypeError("Invalid napi init options");var r=e.instance;if(!(null==r?void 0:r.exports))throw new TypeError("Invalid wasm instance");t=r;var f=r.exports,u=e.module,c=e.memory||f.memory,p=e.table||f.__indirect_function_table;if(!(u instanceof n.Module))throw new TypeError("Invalid wasm module");if(!(c instanceof n.Memory))throw new TypeError("Invalid wasm memory");if(!(p instanceof n.Table))throw new TypeError("Invalid wasm table");if(a=c,i=p,"function"!=typeof f.malloc)throw new TypeError("malloc is not exported");if("function"!=typeof f.free)throw new TypeError("free is not exported");if(o=f.malloc,s=f.free,!y.childThread){var g=8,w=r.exports.node_api_module_get_api_version_v1;"function"==typeof w&&(g=w());var b=y.envObject||(y.envObject=d.createEnv(y.filename,g,function(e){return i.get(e)},function(e){return i.get(e)},l,v)),h=d.openScope(b);try{b.callIntoModule(function(e){var t=y.exports,n=h.add(t),a=(0,r.exports.napi_register_wasm_v1)(e.id,n.id);y.exports=a?d.handleStore.get(a).value:t})}catch(e){if("unwind"!==e)throw e}finally{d.closeScope(b,h)}return y.loaded=!0,delete y.envObject,y.exports}}},g=void 0;if(u){d=null==r?void 0:r.context;var w="function"==typeof r.postMessage?r.postMessage:"function"==typeof postMessage?postMessage:void 0;if("function"!=typeof w)throw new TypeError("No postMessage found");y.postMessage=w}else{var b=r.context;if("object"!=typeof b||null===b)throw new TypeError("Invalid `options.context`. Use `import { getDefaultContext } from '@emnapi/runtime'`");d=b}if("string"==typeof r.filename&&(y.filename=r.filename),"function"==typeof r.onCreateWorker&&(g=r.onCreateWorker),"function"==typeof r.print?r.print:console.log.bind(console),p="function"==typeof r.printErr?r.printErr:console.warn.bind(console),"nodeBinding"in r){var h=r.nodeBinding;if("object"!=typeof h||null===h)throw new TypeError("Invalid `options.nodeBinding`. Use @emnapi/node-binding package");v=h}var _=0;if("asyncWorkPoolSize"in r){if("number"!=typeof r.asyncWorkPoolSize)throw new TypeError("options.asyncWorkPoolSize must be a integer");(_=r.asyncWorkPoolSize|0)>1024?_=1024:_<-1024&&(_=-1024)}var E=!u&&_<=0;function L(){return Math.abs(_)}function m(e){if(!e)return!1;if(e._emnapiSendListener)return!0;var r=function(e){var r=(f?e:e.data).__emnapi__;if(r&&"async-send"===r.type)if(u){(0,y.postMessage)({__emnapi__:r})}else{var t=r.payload.callback;i.get(t)(r.payload.data)}};return e._emnapiSendListener={handler:r,dispose:function(){f?e.off("message",r):e.removeEventListener("message",r,!1),delete e._emnapiSendListener}},f?e.on("message",r):e.addEventListener("message",r,!1),!0}y.imports.env._emnapi_async_work_pool_size=L,y.emnapi.addSendListener=m;var S=new e(u?{printErr:p,childThread:!0}:{printErr:p,beforeLoad:function(e){m(e)},reuseWorker:r.reuseWorker,onCreateWorker:g});function A(e,r){d.feature.setImmediate(function(){i.get(e)(r)})}function C(e,r){Promise.resolve().then(function(){i.get(e)(r)})}function V(e,r){var t,n=[r>>>0,(t=r,+Math.abs(t)>=1?t>0?(0|Math.min(+Math.floor(t/4294967296),4294967295))>>>0:~~+Math.ceil((t-+(~~t>>>0))/4294967296)>>>0:0)],i=new DataView(a.buffer),o=function(){return i.buffer===a.buffer?i:i=new DataView(a.buffer)};o().setInt32(e,n[0],!0),o().setInt32(e+4,n[1],!0)}y.PThread=S;var I,D=Object.freeze({__proto__:null,$emnapiSetValueI64:V,_emnapi_call_finalizer:function(e,r,t,n,a){t>>>=0,d.envStore.get(r).callFinalizerInternal(e,t,n,a)},_emnapi_callback_into_module:function(e,r,t,n,a){var o=d.envStore.get(r),s=d.openScope(o);try{o.callbackIntoModule(Boolean(e),function(){i.get(t)(r,n)})}catch(e){throw d.closeScope(o,s),a&&d.closeScope(o),e}d.closeScope(o,s)},_emnapi_close_handle_scope:function(e){return d.closeScope()},_emnapi_ctx_decrease_waiting_request_counter:function(){d.decreaseWaitingRequestCounter()},_emnapi_ctx_increase_waiting_request_counter:function(){d.increaseWaitingRequestCounter()},_emnapi_get_node_version:function(e,r,t){e>>>=0,r>>>=0,t>>>=0;var n="object"==typeof process&&null!==process&&"object"==typeof process.versions&&null!==process.versions&&"string"==typeof process.versions.node?process.versions.node.split(".").map(function(e){return Number(e)}):[0,0,0],i=new DataView(a.buffer),o=function(){return i.buffer===a.buffer?i:i=new DataView(a.buffer)};o().setUint32(e,n[0],!0),o().setUint32(r,n[1],!0),o().setUint32(t,n[2],!0)},_emnapi_get_now:function(){return performance.timeOrigin+performance.now()},_emnapi_is_main_browser_thread:function(){return"undefined"==typeof window||"undefined"==typeof document||f?0:1},_emnapi_is_main_runtime_thread:function(){return u?0:1},_emnapi_next_tick:C,_emnapi_open_handle_scope:function(){return d.openScope().id},_emnapi_runtime_keepalive_pop:function(){},_emnapi_runtime_keepalive_push:function(){},_emnapi_set_immediate:A,_emnapi_unwind:function(){throw"unwind"},napi_clear_last_error:function(e){return d.envStore.get(e).clearLastError()},napi_set_last_error:function(e,r,t,n){return d.envStore.get(e).setLastError(r,t,n)}});function k(e){var r=new DataView(a.buffer).getInt32(e+20,!0);return S.pthreads[r]}var U=new Promise(function(e){I=function(){U.ready=!0,e()}});U.ready=!1;var B=Object.freeze({__proto__:null,_emnapi_after_uvthreadpool_ready:function(e,r,t){U.ready?i.get(e)(r,t):U.then(function(){i.get(e)(r,t)})},_emnapi_async_send_js:function(e,r,t){if(u)(0,y.postMessage)({__emnapi__:{type:"async-send",payload:{callback:r,data:t}}});else switch(e){case 0:A(r,t);break;case 1:C(r,t)}},_emnapi_emit_async_thread_ready:function(){u&&(0,y.postMessage)({__emnapi__:{type:"async-thread-ready",payload:{}}})},_emnapi_tell_js_uvthreadpool:function(e,r){for(var t=[],n=new DataView(a.buffer),i=function(r){var i=k((n.buffer===a.buffer?n:n=new DataView(a.buffer)).getUint32(e+4*r,!0));t.push(new Promise(function(e){var r=function(t){var n=(f?t:t.data).__emnapi__;n&&"async-thread-ready"===n.type&&(e(),i&&"function"==typeof i.unref&&i.unref(),f?i.off("message",r):i.removeEventListener("message",r))};f?i.on("message",r):i.addEventListener("message",r)}))},o=0;o>>=0);r&&"function"==typeof r.ref&&r.ref()}},_emnapi_worker_unref:function(e){if(!u){var r=k(e>>>=0);r&&"function"==typeof r.unref&&r.unref()}}});var T=Object.freeze({__proto__:null,napi_adjust_external_memory:function(e,r,t){if(!e)return 1;var n=d.envStore.get(e);if(!t)return n.setLastError(1);var i=d.adjustAmountOfExternalAllocatedMemory(r);if(t>>>=0,d.feature.supportBigInt){var o=new DataView(a.buffer);(o.buffer===a.buffer?o:o=new DataView(a.buffer)).setBigInt64(t,BigInt(i),!0)}else V(t,Number(i));return n.clearLastError()}}),F={idGen:{},values:[void 0],queued:new Set,pending:[],init:function(){var e={nextId:1,list:[],generate:function(){var r;return e.list.length?r=e.list.shift():(r=e.nextId,e.nextId++),r},reuse:function(r){e.list.push(r)}};F.idGen=e,F.values=[void 0],F.queued=new Set,F.pending=[]},create:function(e,r,t,n,a,i){var o=0,s=0;if(v){var f=v.node.emitAsyncInit(r,t,-1);o=f.asyncId,s=f.triggerAsyncId}var u=F.idGen.generate();return F.values[u]={env:e,id:u,resource:r,asyncId:o,triggerAsyncId:s,status:0,execute:n,complete:a,data:i},u},callComplete:function(e,r){var t=e.complete,n=e.env,a=e.data,o=function(){if(t){var e=d.envStore.get(n),o=d.openScope(e);try{e.callbackIntoModule(!0,function(){i.get(t)(n,r,a)})}finally{d.closeScope(e,o)}}};v?v.node.makeCallback(e.resource,o,[],{asyncId:e.asyncId,triggerAsyncId:e.triggerAsyncId}):o()},queue:function(e){var r=F.values[e];if(r&&0===r.status){if(r.status=1,F.queued.size>=(Math.abs(_)||4))return void F.pending.push(e);F.queued.add(e);var t=r.env,n=r.data,a=r.execute;r.status=2,d.feature.setImmediate(function(){if(i.get(a)(t,n),F.queued.delete(e),r.status=3,d.feature.setImmediate(function(){F.callComplete(r,0)}),F.pending.length>0){var o=F.pending.shift();F.values[o].status=0,F.queue(o)}})}},cancel:function(e){var r=F.pending.indexOf(e);if(-1!==r){var t=F.values[e];return t&&1===t.status?(t.status=4,F.pending.splice(r,1),d.feature.setImmediate(function(){F.callComplete(t,11)}),0):9}return 9},remove:function(e){var r=F.values[e];r&&(v&&v.node.emitAsyncDestroy({asyncId:r.asyncId,triggerAsyncId:r.triggerAsyncId}),F.values[e]=void 0,F.idGen.reuse(e))}};function O(e,r,t,n){if(v){var i=d.handleStore.get(e).value,o=d.handleStore.get(r).value,s=v.node.emitAsyncInit(i,o,t),f=s.asyncId,u=s.triggerAsyncId;if(n){n>>>=0;var c=new DataView(a.buffer),l=function(){return c.buffer===a.buffer?c:c=new DataView(a.buffer)};l().setFloat64(n,f,!0),l().setFloat64(n+8,u,!0)}}}function x(e,r){v&&v.node.emitAsyncDestroy({asyncId:e,triggerAsyncId:r})}var j=Object.freeze({__proto__:null,_emnapi_async_destroy_js:function(e){if(!v)return 9;e>>>=0;var r=new DataView(a.buffer),t=function(){return r.buffer===a.buffer?r:r=new DataView(a.buffer)},n=t().getInt32(e,!0),i=t().getInt32(e+4,!0),o=BigInt(n>>>0)|BigInt(i)<=BigInt(-1)*(BigInt(1)<=BigInt(1)<>BigInt(32));t>>>=0;var c=new DataView(a.buffer),l=function(){return c.buffer===a.buffer?c:c=new DataView(a.buffer)};return l().setInt32(t,f,!0),l().setInt32(t+4,u,!0),0},_emnapi_env_check_gc_access:function(e){d.envStore.get(e).checkGCAccess()},_emnapi_node_emit_async_destroy:x,_emnapi_node_emit_async_init:O,_emnapi_node_make_callback:function(e,r,t,n,i,o,s,f){var u,c=0;if(v){var l=d.handleStore.get(r).value,p=d.handleStore.get(t).value;n>>>=0,i>>>=0,i>>>=0;for(var y=Array(i),g=new DataView(a.buffer),w=function(){return g.buffer===a.buffer?g:g=new DataView(a.buffer)};c>>=0,u=d.envStore.get(e).ensureHandleId(h),w().setUint32(f,u,!0)}},napi_close_callback_scope:function(e,r){throw new Error("napi_close_callback_scope has not been implemented yet")},napi_make_callback:function(e,r,t,n,i,o,s){var f,u=0;if(!e)return 1;var c=d.envStore.get(e);if(c.checkGCAccess(),!c.tryCatch.isEmpty())return c.setLastError(10);if(!c.canCallIntoJs())return c.setLastError(c.moduleApiVersion>=10?23:10);c.clearLastError();try{if(!v)return c.setLastError(9);if(!t)return c.setLastError(1);if(i>0&&!o)return c.setLastError(1);var l=Object(d.handleStore.get(t).value),p=d.handleStore.get(n).value;if("function"!=typeof p)return c.setLastError(1);r>>>=0;var y=new DataView(a.buffer),g=function(){return y.buffer===a.buffer?y:y=new DataView(a.buffer)},w=g().getInt32(r,!0),b=g().getInt32(r+4,!0),h=BigInt(w>>>0)|BigInt(b)<>>=0,i>>>=0,i>>>=0;for(var _=Array(i);u>>=0,f=c.ensureHandleId(L.value),g().setUint32(s,f,!0)),c.getReturnStatus())}catch(e){return c.tryCatch.setError(e),c.setLastError(10)}},napi_open_callback_scope:function(e,r,t,n){throw new Error("napi_open_callback_scope has not been implemented yet")}}),R={_liveSet:{},offset:{__size__:0,resource:0,async_id:0,trigger_async_id:0,queue_size:0,is_some:0,queue:0,async_pending:0,async_u_fd:0,thread_count:0,state:0,dispatch_state:0,context:0,max_queue_size:0,ref:0,env:0,finalize_data:0,finalize_cb:0,call_js_cb:0,handles_closing:0,async_ref:0,mutex:0,cond:0},init:function(){if(R._liveSet=new Set,R.offset.__size__=184,R.offset.resource=0,R.offset.async_id=8,R.offset.trigger_async_id=16,R.offset.queue_size=60,R.offset.is_some=24,R.offset.queue=64,R.offset.async_pending=132,R.offset.async_u_fd=96,R.offset.thread_count=136,R.offset.state=140,R.offset.dispatch_state=144,R.offset.context=148,R.offset.max_queue_size=152,R.offset.ref=156,R.offset.env=160,R.offset.finalize_data=164,R.offset.finalize_cb=168,R.offset.call_js_cb=172,R.offset.handles_closing=176,R.offset.async_ref=180,R.offset.mutex=32,R.offset.cond=56,R.offset.mutex=R.offset.mutex+4,void 0!==S){S.unusedWorkers.forEach(R.addListener),Object.values(S.pthreads).forEach(R.addListener);var e=S.getNewWorker;S.getNewWorker=function(){var r=e.apply(this,arguments);return R.addListener(r),r}}},addListener:function(e){if(!e)return!1;if(e._emnapiTSFNListener)return!0;var r=function(e){var r=(f?e:e.data).__emnapi__;if(r){var t=r.type,n=r.payload;if("tsfn-send"===t){var a=n.tsfn+R.offset.async_pending;0!==Atomics.load(new Int32Array(R.ensureBufferFor(a+4)),a>>>2)&&R.enqueue(n.tsfn)}}};return e._emnapiTSFNListener={handler:r,dispose:function(){f?e.off("message",r):e.removeEventListener("message",r,!1),delete e._emnapiTSFNListener}},f?e.on("message",r):e.addEventListener("message",r,!1),!0},ensureBufferFor:function(e){var r=a.buffer;return e>r.byteLength&&(a.grow(0),r=a.buffer),r},initQueue:function(e){var r=o(8);return!!r&&(r>>>=0,new Uint8Array(R.ensureBufferFor(r+8),r,8).fill(0),R.storeSizeTypeValue(e+R.offset.queue,r,!1),!0)},destroyQueue:function(e){var r=R.loadSizeTypeValue(e+R.offset.queue,!1);if(r){for(var t=R.loadSizeTypeValue(r,!1);0!==t;){var n=R.loadSizeTypeValue(t+4,!1);s(t),t=n}s(r)}},pushQueue:function(e,r){var t=R.loadSizeTypeValue(e+R.offset.queue,!1),n=R.loadSizeTypeValue(t,!1),a=R.loadSizeTypeValue(t+4,!1),i=o(8);if(!i)throw new Error("OOM");i>>>=0,R.storeSizeTypeValue(i,r,!1),R.storeSizeTypeValue(i+4,0,!1),0===n&&0===a?(R.storeSizeTypeValue(t,i,!1),R.storeSizeTypeValue(t+4,i,!1)):(R.storeSizeTypeValue(a+4,i,!1),R.storeSizeTypeValue(t+4,i,!1)),R.addQueueSize(e)},shiftQueue:function(e){var r=R.loadSizeTypeValue(e+R.offset.queue,!1),t=R.loadSizeTypeValue(r,!1);if(0===t)return 0;var n=t,a=R.loadSizeTypeValue(t+4,!1);R.storeSizeTypeValue(r,a,!1),0===a&&R.storeSizeTypeValue(r+4,0,!1),R.storeSizeTypeValue(n+4,0,!1);var i=R.loadSizeTypeValue(n,!1);return s(n),R.subQueueSize(e),i},push:function(e,r,t){var n=R.getMutex(e),a=R.getCond(e),i=function(){var r=R.getQueueSize(e),t=R.getMaxQueueSize(e);return r>=t&&t>0&&0===R.getState(e)},o="undefined"!=typeof window&&"undefined"!=typeof document&&!f,s=!1,u=n.execute(function(){for(;i();){if(0===t)return 15;if(o)return 21;a.wait()}return 0===R.getState(e)?(R.pushQueue(e,r),R.send(e),0):0===R.getThreadCount(e)?1:(R.subThreadCount(e),2!==R.getState(e)||0!==R.getThreadCount(e)||(s=!0),16)});return s&&R.destroy(e),u},getMutex:function(e){var r=e+R.offset.mutex,t={lock:function(){var e="undefined"!=typeof window&&"undefined"!=typeof document&&!f,t=new Int32Array(R.ensureBufferFor(r+4),r,1);if(e)for(;;){if(0===Atomics.compareExchange(t,0,0,10))return}else for(;;){if(0===Atomics.compareExchange(t,0,0,10))return;Atomics.wait(t,0,10)}},unlock:function(){var e=new Int32Array(R.ensureBufferFor(r+4),r,1);if(10!==Atomics.compareExchange(e,0,10,0))throw new Error("Tried to unlock while not holding the mutex");Atomics.notify(e,0,1)},execute:function(e){t.lock();try{return e()}finally{t.unlock()}}};return t},getCond:function(e){var r=e+R.offset.cond,t=R.getMutex(e);return{wait:function(){var e=new Int32Array(R.ensureBufferFor(r+4),r,1),n=Atomics.load(e,0);t.unlock(),Atomics.wait(e,0,n),t.lock()},signal:function(){var e=new Int32Array(R.ensureBufferFor(r+4),r,1);Atomics.add(e,0,1),Atomics.notify(e,0,1)}}},getQueueSize:function(e){return R.loadSizeTypeValue(e+R.offset.queue_size,!0)},addQueueSize:function(e){var r,t,n=R.offset.queue_size;r=new Uint32Array(R.ensureBufferFor(e+n+4)),t=e+n>>>2,Atomics.add(r,t,1)},subQueueSize:function(e){var r,t,n=R.offset.queue_size;r=new Uint32Array(R.ensureBufferFor(e+n+4)),t=e+n>>>2,Atomics.sub(r,t,1)},getThreadCount:function(e){return R.loadSizeTypeValue(e+R.offset.thread_count,!0)},addThreadCount:function(e){var r,t,n=R.offset.thread_count;r=new Uint32Array(R.ensureBufferFor(e+n+4)),t=e+n>>>2,Atomics.add(r,t,1)},subThreadCount:function(e){var r,t,n=R.offset.thread_count;r=new Uint32Array(R.ensureBufferFor(e+n+4)),t=e+n>>>2,Atomics.sub(r,t,1)},getState:function(e){return Atomics.load(new Int32Array(R.ensureBufferFor(e+R.offset.state+4)),e+R.offset.state>>>2)},setState:function(e,r){Atomics.store(new Int32Array(R.ensureBufferFor(e+R.offset.state+4)),e+R.offset.state>>>2,r)},getHandlesClosing:function(e){return Atomics.load(new Int8Array(R.ensureBufferFor(e+R.offset.handles_closing+1)),e+R.offset.handles_closing)},setHandlesClosing:function(e,r){Atomics.store(new Int8Array(R.ensureBufferFor(e+R.offset.handles_closing+1)),e+R.offset.handles_closing,r)},getDispatchState:function(e){return Atomics.load(new Uint32Array(R.ensureBufferFor(e+R.offset.dispatch_state+4)),e+R.offset.dispatch_state>>>2)},getContext:function(e){return R.loadSizeTypeValue(e+R.offset.context,!1)},getMaxQueueSize:function(e){return R.loadSizeTypeValue(e+R.offset.max_queue_size,!0)},getEnv:function(e){return R.loadSizeTypeValue(e+R.offset.env,!1)},getCallJSCb:function(e){return R.loadSizeTypeValue(e+R.offset.call_js_cb,!1)},getRef:function(e){return R.loadSizeTypeValue(e+R.offset.ref,!1)},getResource:function(e){return R.loadSizeTypeValue(e+R.offset.resource,!1)},getFinalizeCb:function(e){return R.loadSizeTypeValue(e+R.offset.finalize_cb,!1)},getFinalizeData:function(e){return R.loadSizeTypeValue(e+R.offset.finalize_data,!1)},loadSizeTypeValue:function(e,r){var t;return r?(t=new Uint32Array(R.ensureBufferFor(e+4)),Atomics.load(t,e>>>2)):(t=new Int32Array(R.ensureBufferFor(e+4)),Atomics.load(t,e>>>2))},storeSizeTypeValue:function(e,r,t){var n;return t?(n=new Uint32Array(R.ensureBufferFor(e+4)),void Atomics.store(n,e>>>2,r)):(n=new Int32Array(R.ensureBufferFor(e+4)),void Atomics.store(n,e>>>2,r>>>0))},releaseResources:function(e){if(2!==R.getState(e)){R.setState(e,2);var r=R.getEnv(e),t=d.envStore.get(r),n=R.getRef(e);n&&d.refStore.get(n).dispose();var i=R.getResource(e);d.refStore.get(i).dispose(),R.ensureBufferFor(e+R.offset.is_some+1);var o=new DataView(a.buffer);(o.buffer===a.buffer?o:o=new DataView(a.buffer)).setInt8(e+R.offset.is_some,0,!0),d.removeCleanupHook(t,R.cleanup,e),t.unref();var s=e+R.offset.async_ref,f=s>>>2,u=new Uint32Array(R.ensureBufferFor(s+4));if(Atomics.load(u,f)>0&&(Atomics.store(u,f,0),d.decreaseWaitingRequestCounter()),v){var c=new DataView(R.ensureBufferFor(e+R.offset.trigger_async_id+8));x(c.getFloat64(e+R.offset.async_id,!0),c.getFloat64(e+R.offset.trigger_async_id,!0))}}},destroy:function(e){R._liveSet.delete(e),R.destroyQueue(e),R.releaseResources(e),s(e)},emptyQueue:function(e){var r=[];R.getMutex(e).execute(function(){for(;R.getQueueSize(e)>0;)r.push(R.shiftQueue(e))});for(var t,n=R.getCallJSCb(e),a=R.getContext(e),o=0;o0?R.releaseResources(e):r=!0}),r&&R.destroy(e)},finalize:function(e){var r=R.getEnv(e),t=d.envStore.get(r);d.openScope(t);var n=R.getFinalizeCb(e),a=R.getFinalizeData(e),i=R.getContext(e),o=function(){t.callFinalizerInternal(0,n,a,i)};try{if(R.emptyQueue(e),n)if(v){var s=R.getResource(e),f=d.refStore.get(s).get(),u=d.handleStore.get(f).value,c=new DataView(R.ensureBufferFor(e+R.offset.trigger_async_id+8)),l=c.getFloat64(e+R.offset.async_id,!0),p=c.getFloat64(e+R.offset.trigger_async_id,!0);v.node.makeCallback(u,o,[],{asyncId:l,triggerAsyncId:p})}else o();R.maybeDelete(e)}finally{d.closeScope(t)}},cleanup:function(e){R.closeHandlesAndMaybeDelete(e,1)},closeHandlesAndMaybeDelete:function(e,r){var t=R.getEnv(e),n=d.envStore.get(t);d.openScope(n);try{if(r&&R.getMutex(e).execute(function(){R.setState(e,1),R.getMaxQueueSize(e)>0&&R.getCond(e).signal()}),R.getHandlesClosing(e))return;R.setHandlesClosing(e,1),Atomics.store(new Int32Array(R.ensureBufferFor(e+R.offset.async_pending+4)),e+R.offset.async_pending>>>2,1),d.feature.setImmediate(function(){R.finalize(e)})}finally{d.closeScope(n)}},dispatchOne:function(e){var r=0,t=!1,n=!1,a=R.getMutex(e),o=R.getCond(e);if(a.execute(function(){if(0===R.getState(e)){var a=R.getQueueSize(e);if(a>0){r=R.shiftQueue(e),t=!0;var i=R.getMaxQueueSize(e);a===i&&i>0&&o.signal(),a--}0===a?0===R.getThreadCount(e)&&(R.setState(e,1),R.getMaxQueueSize(e)>0&&o.signal(),R.closeHandlesAndMaybeDelete(e,0)):n=!0}else R.closeHandlesAndMaybeDelete(e,0)}),t){var s=R.getEnv(e),f=d.envStore.get(s);d.openScope(f);var u=function(){f.callbackIntoModule(!1,function(){var t=R.getCallJSCb(e),n=R.getRef(e),a=n?d.refStore.get(n).get():0;if(t){var o=R.getContext(e);i.get(t)(s,a,o,r)}else{var f=a?d.handleStore.get(a).value:null;"function"==typeof f&&f()}})};try{if(v){var c=R.getResource(e),l=d.refStore.get(c).get(),p=d.handleStore.get(l).value,y=new DataView(R.ensureBufferFor(e+R.offset.trigger_async_id+8));v.node.makeCallback(p,u,[],{asyncId:y.getFloat64(e+R.offset.async_id,!0),triggerAsyncId:y.getFloat64(e+R.offset.trigger_async_id,!0)})}else u()}finally{d.closeScope(f)}}return n},dispatch:function(e){for(var r=!0,t=1e3,n=e+R.offset.dispatch_state,a=n>>>2;r&&0!==--t;){Atomics.store(new Uint32Array(R.ensureBufferFor(n+4)),a,1);try{r=R.dispatchOne(e)}catch(r){throw R._liveSet.has(e)&&(Atomics.exchange(new Uint32Array(R.ensureBufferFor(n+4)),a,0),R.send(e)),r}1!==Atomics.exchange(new Uint32Array(R.ensureBufferFor(n+4)),a,0)&&(r=!0)}r&&R.send(e)},enqueue:function(e){var r=e+R.offset.async_pending,t=e+R.offset.async_u_fd,n=Math.max(r,t)+4,a=function(){return new Int32Array(R.ensureBufferFor(n))};0===Atomics.exchange(a(),t>>>2,1)&&d.feature.setImmediate(function(){R._liveSet.has(e)&&(0!==Atomics.load(a(),r>>>2)?d.feature.setImmediate(function(){if(R._liveSet.has(e))try{if(0===Atomics.exchange(a(),r>>>2,0))return;R.dispatch(e)}finally{R._liveSet.has(e)&&(Atomics.store(a(),t>>>2,0),0!==Atomics.load(a(),r>>>2)&&R.enqueue(e))}}):Atomics.store(a(),t>>>2,0))})},send:function(e){var r=e+R.offset.dispatch_state;if(1&~Atomics.or(new Uint32Array(R.ensureBufferFor(r+4)),r>>>2,2)){var t=e+R.offset.async_pending;0===Atomics.load(new Int32Array(R.ensureBufferFor(t+4)),t>>>2)&&0===Atomics.exchange(new Int32Array(R.ensureBufferFor(t+4)),t>>>2,1)&&(void 0!==u&&u?postMessage({__emnapi__:{type:"tsfn-send",payload:{tsfn:e}}}):R.enqueue(e))}}};var z={pool:[],workerReady:null,globalAddress:0,globalOffset:{idle_threads:0,q:4,next:4,prev:8,mutex:12,cond:16,exit_message:20,end:28},offset:{resource:0,async_id:8,trigger_async_id:16,env:24,status:28,queue:32,queue_next:32,queue_prev:36,data:40,execute:44,complete:48,end:52},ensureBufferFor:function(e){var r=a.buffer;return e>r.byteLength&&(a.grow(0),r=a.buffer),r},init:function(){if(z.pool=[],z.workerReady=null,void 0!==S){S.unusedWorkers.forEach(z.addListener),Object.values(S.pthreads).forEach(z.addListener);var e=S.getNewWorker;S.getNewWorker=function(){var r=e.apply(this,arguments);return z.addListener(r),r}}},addListener:function(e){if(!e)return!1;if(e._emnapiAWMTListener)return!0;var r=function(e){var r=(f?e:e.data).__emnapi__;if(r){var t=r.type,n=r.payload;"async-work-complete"===t&&z.callComplete(n.work,0)}};return e._emnapiAWMTListener={handler:r,dispose:function(){f?e.off("message",r):e.removeEventListener("message",r,!1),delete e._emnapiAWMTListener}},f?e.on("message",r):e.addEventListener("message",r,!1),!0},initGlobal:function(){if(!z.globalAddress){z.globalAddress=o(z.globalOffset.end),z.globalAddress>>>=0;var e=z.globalOffset.end,r=z.globalAddress;new Uint8Array(z.ensureBufferFor(r+e),r,e).fill(0),z.queueInit(z.globalAddress+z.globalOffset.q),z.queueInit(z.globalAddress+z.globalOffset.exit_message)}},terminateWorkers:function(){z.pool.forEach(function(e){var r,t;null===(r=e._emnapiAWMTListener)||void 0===r||r.dispose(),null===(t=e._emnapiTSFNListener)||void 0===t||t.dispose(),e.terminate()}),z.pool.length=0},initWorkers:function(e){if(u)return z.workerReady||(z.workerReady=Promise.resolve());if(z.workerReady)return z.workerReady;if(!("emnapi_async_worker_create"in t.exports))throw new TypeError("`emnapi_async_worker_create` is not exported, please try to add `--export=emnapi_async_worker_create` to linker flags");var r=t.exports.emnapi_async_worker_create,n=[];z.initGlobal();for(var a=0;a>>=0;var t=new DataView(z.ensureBufferFor(e+20+4)).getInt32(e+20,!0);return(r=S.pthreads[t]).whenLoaded});return z.workerReady=Promise.all(i),z.workerReady},getResource:function(e){z.ensureBufferFor(e+z.offset.resource+4);var r=new DataView(a.buffer);return(r.buffer===a.buffer?r:r=new DataView(a.buffer)).getUint32(e+z.offset.resource,!0)},getExecute:function(e){z.ensureBufferFor(e+z.offset.execute+4);var r=new DataView(a.buffer);return(r.buffer===a.buffer?r:r=new DataView(a.buffer)).getUint32(e+z.offset.execute,!0)},getComplete:function(e){z.ensureBufferFor(e+z.offset.complete+4);var r=new DataView(a.buffer);return(r.buffer===a.buffer?r:r=new DataView(a.buffer)).getUint32(e+z.offset.complete,!0)},getEnv:function(e){z.ensureBufferFor(e+z.offset.env+4);var r=new DataView(a.buffer);return(r.buffer===a.buffer?r:r=new DataView(a.buffer)).getUint32(e+z.offset.env,!0)},getData:function(e){z.ensureBufferFor(e+z.offset.data+4);var r=new DataView(a.buffer);return(r.buffer===a.buffer?r:r=new DataView(a.buffer)).getUint32(e+z.offset.data,!0)},getMutex:function(){var e=z.globalAddress+z.globalOffset.mutex,r={lock:function(){var r="undefined"!=typeof window&&"undefined"!=typeof document&&!f,t=new Int32Array(z.ensureBufferFor(e+4),e,1);if(r)for(;;){if(0===Atomics.compareExchange(t,0,0,10))return}else for(;;){if(0===Atomics.compareExchange(t,0,0,10))return;Atomics.wait(t,0,10)}},unlock:function(){var r=new Int32Array(z.ensureBufferFor(e+4),e,1);if(10!==Atomics.compareExchange(r,0,10,0))throw new Error("Tried to unlock while not holding the mutex");Atomics.notify(r,0,1)},execute:function(e){r.lock();try{return e()}finally{r.unlock()}}};return r},getCond:function(){var e=z.globalAddress+z.globalOffset.cond,r=z.getMutex();return{wait:function(){var t=new Int32Array(z.ensureBufferFor(e+4),e,1),n=Atomics.load(t,0);r.unlock(),Atomics.wait(t,0,n),r.lock()},signal:function(){var r=new Int32Array(z.ensureBufferFor(e+4),e,1);Atomics.add(r,0,1),Atomics.notify(r,0,1)}}},queueInit:function(e){z.ensureBufferFor(e+4+4);var r=new DataView(a.buffer),t=function(){return r.buffer===a.buffer?r:r=new DataView(a.buffer)};t().setUint32(e,e,!0),t().setUint32(e+4,e,!0)},queueInsertTail:function(e,r){z.ensureBufferFor(e+4+4),z.ensureBufferFor(r+4+4);var t=new DataView(a.buffer),n=function(){return t.buffer===a.buffer?t:t=new DataView(a.buffer)};n().setUint32(r,e,!0);var i=n().getUint32(e+4,!0);n().setUint32(r+4,i,!0);var o=n().getUint32(r+4,!0);n().setUint32(o,r,!0),n().setUint32(e+4,r,!0)},queueRemove:function(e){z.ensureBufferFor(e+4+4);var r=new DataView(a.buffer),t=function(){return r.buffer===a.buffer?r:r=new DataView(a.buffer)},n=t().getUint32(e+4,!0),i=t().getUint32(e,!0);t().setUint32(n,i,!0),t().setUint32(i+4,n,!0)},queueEmpty:function(e){z.ensureBufferFor(e+4);var r=new DataView(a.buffer);return e==(r.buffer===a.buffer?r:r=new DataView(a.buffer)).getUint32(e,!0)},scheduleWork:function(e){var r;(null===(r=z.workerReady)||void 0===r?void 0:r.ready)||z.initWorkers(L()).then(function(){z.workerReady.ready=!0}).catch(function(e){throw z.workerReady=null,e}),d.increaseWaitingRequestCounter();var t=new Int32Array(z.ensureBufferFor(e+z.offset.status+4),e+z.offset.status,1);Atomics.store(t,0,0);var n=z.getMutex(),i=z.getCond();n.lock();try{z.queueInsertTail(z.globalAddress+z.globalOffset.q,e+z.offset.queue)}catch(e){throw d.decreaseWaitingRequestCounter(),n.unlock(),e}z.ensureBufferFor(z.globalAddress+z.globalOffset.idle_threads+4);var o=new DataView(a.buffer);(o.buffer===a.buffer?o:o=new DataView(a.buffer)).getUint32(z.globalAddress+z.globalOffset.idle_threads,!0)>0&&i.signal(),n.unlock()},cancelWork:function(e){var r=!1;return z.getMutex().execute(function(){z.ensureBufferFor(e+z.offset.status+4);var t=new DataView(a.buffer);(r=!z.queueEmpty(e+z.offset.queue)&&2!==(t.buffer===a.buffer?t:t=new DataView(a.buffer)).getInt32(e+z.offset.status,!0))&&z.queueRemove(e+z.offset.queue)}),r?0!==Atomics.compareExchange(new Int32Array(z.ensureBufferFor(e+z.offset.status+4),e+z.offset.status,1),0,0,1)?9:(d.feature.setImmediate(function(){z.callComplete(e,11)}),0):9},callComplete:function(e,r){d.decreaseWaitingRequestCounter();var t=z.getComplete(e),n=z.getEnv(e),a=z.getData(e),o=d.envStore.get(n),s=d.openScope(o),f=function(){t&&o.callbackIntoModule(!0,function(){i.get(t)(n,r,a)})};try{if(v){var u=z.getResource(e),c=d.refStore.get(u).get(),l=d.handleStore.get(c).value,p=new DataView(z.ensureBufferFor(e+z.offset.trigger_async_id+8)),y=p.getFloat64(e+z.offset.async_id,!0),g=p.getFloat64(e+z.offset.trigger_async_id,!0);v.node.makeCallback(l,f,[],{asyncId:y,triggerAsyncId:g})}else f()}finally{d.closeScope(o,s)}}};z.init();var G=E?function(e,r,t,n,i,o,s){if(!e)return 1;var f,u=d.envStore.get(e);if(u.checkGCAccess(),!n)return u.setLastError(1);if(!s)return u.setLastError(1);if(f=r?Object(d.handleStore.get(r).value):{},!t)return u.setLastError(1);var c=String(d.handleStore.get(t).value),l=F.create(e,f,c,n,i,o);s>>>=0;var v=new DataView(a.buffer);return(v.buffer===a.buffer?v:v=new DataView(a.buffer)).setUint32(s,l,!0),u.clearLastError()}:function(e,r,t,n,i,s,f){if(!e)return 1;var u,c=d.envStore.get(e);if(c.checkGCAccess(),!n)return c.setLastError(1);if(!f)return c.setLastError(1);if(u=r?Object(d.handleStore.get(r).value):{},!t)return c.setLastError(1);var l=z.offset.end,v=o(l);if(!v)return c.setLastError(9);v>>>=0,new Uint8Array(z.ensureBufferFor(v+l)).subarray(v,v+l).fill(0);var p=c.ensureHandleId(u),y=d.createReference(c,p,1,1).id,g=new DataView(a.buffer),w=function(){return g.buffer===a.buffer?g:g=new DataView(a.buffer)};return w().setUint32(v,y,!0),O(p,t,-1,v+z.offset.async_id),w().setUint32(v+z.offset.env,e,!0),w().setUint32(v+z.offset.execute,n,!0),w().setUint32(v+z.offset.complete,i,!0),w().setUint32(v+z.offset.data,s,!0),z.queueInit(v+z.offset.queue),f>>>=0,w().setUint32(f,v,!0),c.clearLastError()},M=E?function(e,r){if(!e)return 1;var t=d.envStore.get(e);return t.checkGCAccess(),r?(r>>>=0,F.remove(r),t.clearLastError()):t.setLastError(1)}:function(e,r){if(!e)return 1;var t=d.envStore.get(e);if(t.checkGCAccess(),!r)return t.setLastError(1);r>>>=0;var n=z.getResource(r);if(d.refStore.get(n).dispose(),v){var a=new DataView(z.ensureBufferFor(r+z.offset.trigger_async_id+8));x(a.getFloat64(r+z.offset.async_id,!0),a.getFloat64(r+z.offset.trigger_async_id,!0))}return s(r),t.clearLastError()},P=E?function(e,r){if(!e)return 1;var t=d.envStore.get(e);return r?(r>>>=0,F.queue(r),t.clearLastError()):t.setLastError(1)}:function(e,r){if(!e)return 1;var t=d.envStore.get(e);return r?(r>>>=0,z.scheduleWork(r),t.clearLastError()):t.setLastError(1)},q=E?function(e,r){if(!e)return 1;var t=d.envStore.get(e);if(!r)return t.setLastError(1);r>>>=0;var n=F.cancel(r);return 0===n?t.clearLastError():t.setLastError(n)}:function(e,r){if(!e)return 1;var t=d.envStore.get(e);if(!r)return t.setLastError(1);r>>>=0;var n=z.cancelWork(r);return 0===n?t.clearLastError():t.setLastError(n)};y.initWorker=function(e,r){if(!y.childThread)throw new Error("startThread is only available in child threads");if("function"!=typeof t.exports.emnapi_async_worker_init)throw new TypeError("`emnapi_async_worker_init` is not exported, please try to add `--export=emnapi_async_worker_init` to linker flags");t.exports.emnapi_async_worker_init(e),i.get(r[0])(r[1])};var W=Object.freeze({__proto__:null,_emnapi_async_worker:function(e){e>>>=0,z.globalAddress=e;var r=z.getMutex(),t=z.getCond();r.lock();for(var n=e+z.globalOffset.exit_message,o=e+z.globalOffset.idle_threads,s=e+z.globalOffset.q,f=new DataView(a.buffer),u=function(){return f.buffer===a.buffer?f:f=new DataView(a.buffer)};;){for(z.ensureBufferFor(s+4);z.queueEmpty(s);)Atomics.add(new Int32Array(z.ensureBufferFor(o+4),o,1),0,1),t.wait(),Atomics.sub(new Int32Array(z.ensureBufferFor(o+4),o,1),0,1);var c=u().getUint32(s,!0);if(c===n){t.signal(),r.unlock();break}var d=c-z.offset.queue;z.queueRemove(c),z.queueInit(c),r.unlock();var v=new Int32Array(z.ensureBufferFor(d+z.offset.status+4),d+z.offset.status,1);1===Atomics.load(v,0)&&l("unreachable");var p=z.getExecute(d),g=z.getEnv(d),w=z.getData(d);i.get(p)(g,w),Atomics.store(v,0,2),(0,y.postMessage)({__emnapi__:{type:"async-work-complete",payload:{work:d}}}),r.lock()}return 0},_emnapi_spawn_worker:function(e,r){if("function"!=typeof g)throw new TypeError("`options.onCreateWorker` is not a function");var n=[];if(!("emnapi_async_worker_create"in t.exports))throw new TypeError("`emnapi_async_worker_create` is not exported, please try to add `--export=emnapi_async_worker_create` to linker flags");n.push(t.exports.emnapi_async_worker_create(0,0));var a,i=function(e){!("message"in e)||-1===e.message.indexOf("RuntimeError")&&-1===e.message.indexOf("unreachable")||z.terminateWorkers()};try{var o=g({type:"async-work",name:"emnapi-async-worker"}),u=S.loadWasmModuleToWorker(o);f?o.on("error",i):o.addEventListener("error",i,!1),z.addListener(o),R.addListener(o),[].push(u.then(function(){"function"==typeof o.unref&&o.unref()})),a=z.pool.push(o)-1;var c=n[0];o.threadBlockBase=c,o.postMessage({__emnapi__:{type:"async-worker-init",payload:{arg:c,func:[e,r]}}})}catch(e){c=n[0];throw s(c),e}return a},napi_cancel_async_work:q,napi_create_async_work:G,napi_delete_async_work:M,napi_queue_async_work:P}),J={registry:"function"==typeof FinalizationRegistry?new FinalizationRegistry(function(e){s(e)}):void 0,table:new WeakMap,wasmMemoryViewTable:new WeakMap,intrinsics:void 0,init:function(){var e;J.registry="function"==typeof FinalizationRegistry?new FinalizationRegistry(function(e){s(e)}):void 0,J.table=new WeakMap,J.wasmMemoryViewTable=new WeakMap;var r="function"==typeof SharedArrayBuffer?null===(e=Object.getOwnPropertyDescriptor(SharedArrayBuffer.prototype,"byteLength"))||void 0===e?void 0:e.get:void 0;J.intrinsics={isView:ArrayBuffer.isView,typedArray:{buffer:Object.getOwnPropertyDescriptor(Object.getPrototypeOf(Uint8Array.prototype),"buffer").get,byteOffset:Object.getOwnPropertyDescriptor(Object.getPrototypeOf(Uint8Array.prototype),"byteOffset").get,length:Object.getOwnPropertyDescriptor(Object.getPrototypeOf(Uint8Array.prototype),"length").get,tag:Object.getOwnPropertyDescriptor(Object.getPrototypeOf(Uint8Array.prototype),Symbol.toStringTag).get},dataView:{buffer:Object.getOwnPropertyDescriptor(DataView.prototype,"buffer").get,byteOffset:Object.getOwnPropertyDescriptor(DataView.prototype,"byteOffset").get,byteLength:Object.getOwnPropertyDescriptor(DataView.prototype,"byteLength").get},arrayBuffer:{byteLength:Object.getOwnPropertyDescriptor(ArrayBuffer.prototype,"byteLength").get},sharedArrayBuffer:void 0!==r?{byteLength:r}:void 0,ctors:{Int8Array:Int8Array,Uint8Array:Uint8Array,Uint8ClampedArray:Uint8ClampedArray,Int16Array:Int16Array,Uint16Array:Uint16Array,Int32Array:Int32Array,Uint32Array:Uint32Array,Float16Array:"function"==typeof Float16Array?Float16Array:void 0,Float32Array:Float32Array,Float64Array:Float64Array,BigInt64Array:BigInt64Array,BigUint64Array:BigUint64Array},bufferFrom:void 0}},isSharedArrayBuffer:function(e){var r=J.intrinsics.sharedArrayBuffer;if(void 0!==r){if("function"==typeof SharedArrayBuffer&&e instanceof SharedArrayBuffer)return!0;try{return r.byteLength.call(e),!0}catch(e){return!1}}try{return J.intrinsics.arrayBuffer.byteLength.call(e),!1}catch(e){}return"[object SharedArrayBuffer]"===Object.prototype.toString.call(e)},isDetachedArrayBuffer:function(e){if(0===J.bufferByteLength(e))try{new Uint8Array(e)}catch(e){return!0}return!1},bufferByteLength:function(e){var r,t=J.intrinsics;try{return t.arrayBuffer.byteLength.call(e)}catch(o){var n=t.sharedArrayBuffer;if(void 0!==n)return n.byteLength.call(e);var a=Object.getPrototypeOf(e),i=null!=a?null===(r=Object.getOwnPropertyDescriptor(a,"byteLength"))||void 0===r?void 0:r.get:void 0;if(void 0===i)throw o;return i.call(e)}},viewBuffer:function(e){var r=J.intrinsics;return void 0===r.typedArray.tag.call(e)?r.dataView.buffer.call(e):r.typedArray.buffer.call(e)},viewByteOffset:function(e){var r=J.intrinsics;return void 0===r.typedArray.tag.call(e)?r.dataView.byteOffset.call(e):r.typedArray.byteOffset.call(e)},viewLength:function(e){var r=J.intrinsics;return void 0===r.typedArray.tag.call(e)?r.dataView.byteLength.call(e):r.typedArray.length.call(e)},getBufferFrom:function(){var e;return null!==(e=J.intrinsics.bufferFrom)&&void 0!==e?e:J.intrinsics.bufferFrom=d.feature.Buffer.from},getArrayBufferPointer:function(e,r){var t,n={address:0,ownership:0,runtimeAllocated:0};if(e===a.buffer)return n;var i=J.isDetachedArrayBuffer(e);if(J.table.has(e)){var s=J.table.get(e);return i?(s.address=0,s):(r&&0===s.ownership&&1===s.runtimeAllocated&&new Uint8Array(a.buffer).set(new Uint8Array(e),s.address),s)}var f=J.bufferByteLength(e);if(i||0===f)return n;if(!r)return n;var u=o(f);if(!u)throw new Error("Out of memory");return u>>>=0,new Uint8Array(a.buffer).set(new Uint8Array(e),u),n.address=u,n.ownership=J.registry?0:1,n.runtimeAllocated=1,J.table.set(e,n),null===(t=J.registry)||void 0===t||t.register(e,u),n},getOrUpdateMemoryView:function(e){var r=J.intrinsics,t=r.typedArray.tag.call(e),n=void 0===t,i=n?r.dataView.buffer.call(e):r.typedArray.buffer.call(e);if(i===a.buffer)return J.wasmMemoryViewTable.has(e)||J.wasmMemoryViewTable.set(e,{Ctor:n?DataView:r.ctors[t],address:n?r.dataView.byteOffset.call(e):r.typedArray.byteOffset.call(e),length:n?r.dataView.byteLength.call(e):r.typedArray.length.call(e),ownership:1,runtimeAllocated:0}),e;if((J.isDetachedArrayBuffer(i)||J.isSharedArrayBuffer(i))&&J.wasmMemoryViewTable.has(e)){var o=J.wasmMemoryViewTable.get(e),s=o.Ctor,f=void 0,u=d.feature.Buffer;return f="function"==typeof u&&s===u?J.getBufferFrom()(a.buffer,o.address,o.length):new s(a.buffer,o.address,o.length),J.wasmMemoryViewTable.set(f,o),f}return e},getViewPointer:function(e,r){e=J.getOrUpdateMemoryView(e);var t=J.viewBuffer(e);if(t===a.buffer){if(J.wasmMemoryViewTable.has(e)){var n=J.wasmMemoryViewTable.get(e);return{address:n.address,ownership:n.ownership,runtimeAllocated:n.runtimeAllocated,view:e}}return{address:J.viewByteOffset(e),ownership:1,runtimeAllocated:0,view:e}}var i=J.getArrayBufferPointer(t,r),o=i.address,s=i.ownership,f=i.runtimeAllocated;return{address:0===o?0:o+J.viewByteOffset(e),ownership:s,runtimeAllocated:f,view:e}}},N={registry:void 0,handleTable:new WeakMap,init:function(){N.handleTable=new WeakMap,N.registry="function"==typeof FinalizationRegistry?new FinalizationRegistry(function(e){N.release(e)}):void 0},allocMeta:function(e,r,t,n,i){var s=o(24);if(!s)throw new Error("Out of memory");s>>>=0,Atomics.store(new Int32Array(a.buffer,s,1),0,1);var f=new DataView(a.buffer),u=function(){return f.buffer===a.buffer?f:f=new DataView(a.buffer)};return u().setUint32(s+4,e,!0),u().setUint32(s+8,r,!0),u().setUint32(s+12,t,!0),u().setUint32(s+16,n,!0),u().setUint32(s+20,i,!0),s},readMeta:function(e){var r=new DataView(a.buffer),t=function(){return r.buffer===a.buffer?r:r=new DataView(a.buffer)};return{external_data:t().getUint32(e+4,!0),byte_length:t().getUint32(e+8,!0),finalize_cb:t().getUint32(e+12,!0),finalize_data:t().getUint32(e+16,!0),finalize_hint:t().getUint32(e+20,!0)}},release:function(e){if(1===Atomics.sub(new Int32Array(a.buffer,e,1),0,1)){var r=N.readMeta(e),t=r.finalize_cb;if(t){var n=r.finalize_data,o=r.finalize_hint;i.get(t)(n,o)}s(e)}}},H={utf8Decoder:void 0,utf16Decoder:void 0,init:function(){var e,r={decode:function(e){for(var r=0,t=Math.min(4096,e.length+1),n=new Uint16Array(t),a=[],i=0;;){var o=r=t-1){var s=n.subarray(0,i);if(a.push(String.fromCharCode.apply(null,s)),!o)return a.join("");e=e.subarray(r),r=0,i=0}var f=e[r++];if(128&f){if(192==(224&f)){var u=63&e[r++];n[i++]=(31&f)<<6|u}else if(224==(240&f)){u=63&e[r++];var c=63&e[r++];n[i++]=(31&f)<<12|u<<6|c}else if(240==(248&f)){var l=(7&f)<<18|(u=63&e[r++])<<12|(c=63&e[r++])<<6|63&e[r++];l>65535&&(l-=65536,n[i++]=l>>>10&1023|55296,l=56320|1023&l),n[i++]=l}}else n[i++]=f}}};e="function"==typeof TextDecoder?new TextDecoder:r,H.utf8Decoder=e;var t,n={decode:function(e){var r=new Uint16Array(e.buffer,e.byteOffset,e.byteLength/2);if(r.length<=4096)return String.fromCharCode.apply(null,r);for(var t=[],n=0,a=0;n=55296&&r<=57343?(t+=4,++n):t+=3;return t},UTF8ToString:function(e,r){if(!e||!r)return"";e>>>=0;var t=new Uint8Array(a.buffer),n=e;if(-1===r||4294967295===r)for(;t[n];)++n;else n=e+(r>>>0);if((r=n-e)<=16){for(var i=e,o="";i>10,56320|1023&c)}}else o+=String.fromCharCode((31&s)<<6|f)}else o+=String.fromCharCode(s)}return o}return H.utf8Decoder.decode("function"==typeof SharedArrayBuffer&&t.buffer instanceof SharedArrayBuffer||"[object SharedArrayBuffer]"===Object.prototype.toString.call(t.buffer)?t.slice(e,n):t.subarray(e,n))},stringToUTF8:function(e,r,t){var n=new Uint8Array(a.buffer),i=r;if(!(t>0))return 0;for(var o=i>>>=0,s=i+t-1,f=0;f=55296&&u<=57343)u=65536+((1023&u)<<10)|1023&e.charCodeAt(++f);if(u<=127){if(i>=s)break;n[i++]=u}else if(u<=2047){if(i+1>=s)break;n[i++]=192|u>>6,n[i++]=128|63&u}else if(u<=65535){if(i+2>=s)break;n[i++]=224|u>>12,n[i++]=128|u>>6&63,n[i++]=128|63&u}else{if(i+3>=s)break;n[i++]=240|u>>18,n[i++]=128|u>>12&63,n[i++]=128|u>>6&63,n[i++]=128|63&u}}return n[i]=0,i-o},UTF16ToString:function(e,r){if(!e||!r)return"";var t=e>>>=0;if(-1===r||4294967295===r){for(var n=t>>>1,i=new Uint16Array(a.buffer);i[n];)++n;t=n<<1>>>0}else t=e+2*(r>>>0);if((r=t-e)<=32)return String.fromCharCode.apply(null,new Uint16Array(a.buffer,e,r/2));var o=new Uint8Array(a.buffer);return H.utf16Decoder.decode("function"==typeof SharedArrayBuffer&&o.buffer instanceof SharedArrayBuffer||"[object SharedArrayBuffer]"===Object.prototype.toString.call(o.buffer)?o.slice(e,t):o.subarray(e,t))},stringToUTF16:function(e,r,t){if(void 0===t&&(t=2147483647),t<2)return 0;for(var n=r,i=(t-=2)<2*e.length?t/2:e.length,o=new DataView(a.buffer),s=function(){return o.buffer===a.buffer?o:o=new DataView(a.buffer)},f=0;f>>=0,!e)return 1;var o=d.envStore.get(e);o.checkGCAccess();var s=-1===t||4294967295===t,f=t>>>0;if(0!==t&&!r)return o.setLastError(1);if(!n)return o.setLastError(1);if(!(s||f<=2147483647))return o.setLastError(1);var u=i(r>>>=0,s,f);n>>>=0;var c=d.addToCurrentScope(u).id,l=new DataView(a.buffer);return(l.buffer===a.buffer?l:l=new DataView(a.buffer)).setUint32(n,c,!0),o.clearLastError()},newExternalString:function(e,r,t,n,i,o,s,f,u){if(t>>>=0,!e)return 1;var c=d.envStore.get(e);c.checkGCAccess();var l=-1===t||4294967295===t,v=t>>>0;if(0!==t&&!r)return c.setLastError(1);if(!o)return c.setLastError(1);if(!(l||v<=2147483647))return c.setLastError(1);var p=f(e,r,t,o);if(0===p){if(s){var y=new DataView(a.buffer);(y.buffer===a.buffer?y:y=new DataView(a.buffer)).setInt8(s,1,!0)}n&&c.callFinalizer(n,r,i)}return p}};function Q(e,r,t,n,i,o,s){if(!e)return 1;var f=d.envStore.get(e);if(f.checkGCAccess(),!r)return f.setLastError(1);var u=d.handleStore.get(r);if(!J.intrinsics.isView(u.value))return f.setLastError(1);var c=u.value,l=new DataView(a.buffer),v=function(){return l.buffer===a.buffer?l:l=new DataView(a.buffer)};if(t){t>>>=0;var p=void 0;switch(J.intrinsics.typedArray.tag.call(c)){case"Int8Array":p=0;break;case"Uint8Array":p=1;break;case"Uint8ClampedArray":p=2;break;case"Int16Array":p=3;break;case"Uint16Array":p=4;break;case"Int32Array":p=5;break;case"Uint32Array":p=6;break;case"Float16Array":p=11;break;case"Float32Array":p=7;break;case"Float64Array":p=8;break;case"BigInt64Array":p=9;break;case"BigUint64Array":p=10;break;default:return f.setLastError(9)}v().setInt32(t,p,!0)}if(c=J.getOrUpdateMemoryView(c),n){n>>>=0;var y=J.viewLength(c);v().setUint32(n,y,!0)}if(i||o){if(i){i>>>=0;var g=J.getViewPointer(c,!0);c=g.view;var w=g.address;v().setUint32(i,w,!0)}if(o){o>>>=0;var b=f.ensureHandleId(J.viewBuffer(c));v().setUint32(o,b,!0)}}if(s){s>>>=0;var h=J.viewByteOffset(c);v().setUint32(s,h,!0)}return f.clearLastError()}function $(e,r,t,n,i,o){if(!e)return 1;var s=d.envStore.get(e);if(s.checkGCAccess(),!r)return s.setLastError(1);var f=d.handleStore.get(r);if(!J.intrinsics.isView(f.value)||void 0!==J.intrinsics.typedArray.tag.call(f.value))return s.setLastError(1);var u=J.getOrUpdateMemoryView(f.value),c=new DataView(a.buffer),l=function(){return c.buffer===a.buffer?c:c=new DataView(a.buffer)};if(t){t>>>=0;var v=J.viewLength(u);l().setUint32(t,v,!0)}if(n||i){if(n){n>>>=0;var p=J.getViewPointer(u,!0);u=p.view;var y=p.address;l().setUint32(n,y,!0)}if(i){i>>>=0;var g=s.ensureHandleId(J.viewBuffer(u));l().setUint32(i,g,!0)}}if(o){o>>>=0;var w=J.viewByteOffset(u);l().setUint32(o,w,!0)}return s.clearLastError()}var Y=Object.freeze({__proto__:null,napi_get_array_length:function(e,r,t){if(!e)return 1;var n=d.envStore.get(e);if(n.checkGCAccess(),!n.tryCatch.isEmpty())return n.setLastError(10);if(!n.canCallIntoJs())return n.setLastError(n.moduleApiVersion>=10?23:10);n.clearLastError();try{if(!r)return n.setLastError(1);if(!t)return n.setLastError(1);var i=d.handleStore.get(r);if(!i.isArray())return n.setLastError(8);t>>>=0;var o=i.value.length>>>0,s=new DataView(a.buffer);return(s.buffer===a.buffer?s:s=new DataView(a.buffer)).setUint32(t,o,!0),n.getReturnStatus()}catch(e){return n.tryCatch.setError(e),n.setLastError(10)}},napi_get_arraybuffer_info:function(e,r,t,n){if(!e)return 1;var i=d.envStore.get(e);if(i.checkGCAccess(),!r)return i.setLastError(1);var o=d.handleStore.get(r);if(!o.isArrayBuffer()&&!J.isSharedArrayBuffer(o.value))return i.setLastError(1);var s=new DataView(a.buffer),f=function(){return s.buffer===a.buffer?s:s=new DataView(a.buffer)};if(t){t>>>=0;var u=J.getArrayBufferPointer(o.value,!0).address;f().setUint32(t,u,!0)}if(n){n>>>=0;var c=J.bufferByteLength(o.value);f().setUint32(n,c,!0)}return i.clearLastError()},napi_get_buffer_info:function(e,r,t,n){if(!e)return 1;var a=d.envStore.get(e);if(a.checkGCAccess(),!r)return a.setLastError(1);var i=d.handleStore.get(r),o=d.feature.Buffer;return J.intrinsics.isView(i.value)||"function"==typeof o&&o.isBuffer(i.value)?void 0===J.intrinsics.typedArray.tag.call(i.value)?$(e,r,n,t,0,0):Q(e,r,0,n,t,0,0):a.setLastError(1)},napi_get_dataview_info:$,napi_get_date_value:function(e,r,t){var n;if(!e)return 1;var i=d.envStore.get(e);if(i.checkGCAccess(),!i.tryCatch.isEmpty())return i.setLastError(10);if(!i.canCallIntoJs())return i.setLastError(i.moduleApiVersion>=10?23:10);i.clearLastError();try{if(!r)return i.setLastError(1);if(!t)return i.setLastError(1);var o=d.handleStore.get(r);if(!o.isDate())return i.setLastError(1);t>>>=0,n=o.value.valueOf();var s=new DataView(a.buffer);return(s.buffer===a.buffer?s:s=new DataView(a.buffer)).setFloat64(t,n,!0),i.getReturnStatus()}catch(e){return i.tryCatch.setError(e),i.setLastError(10)}},napi_get_prototype:function(e,r,t){if(!e)return 1;var n=d.envStore.get(e);if(n.checkGCAccess(),!n.tryCatch.isEmpty())return n.setLastError(10);if(!n.canCallIntoJs())return n.setLastError(n.moduleApiVersion>=10?23:10);n.clearLastError();try{if(!r)return n.setLastError(1);if(!t)return n.setLastError(1);var i=d.handleStore.get(r);if(null==i.value)throw new TypeError("Cannot convert undefined or null to object");var o=void 0;try{o=i.isObject()||i.isFunction()?i.value:Object(i.value)}catch(e){return n.setLastError(2)}t>>>=0;var s=n.ensureHandleId(Object.getPrototypeOf(o)),f=new DataView(a.buffer);return(f.buffer===a.buffer?f:f=new DataView(a.buffer)).setUint32(t,s,!0),n.getReturnStatus()}catch(e){return n.tryCatch.setError(e),n.setLastError(10)}},napi_get_typedarray_info:Q,napi_get_value_bigint_int64:function(e,r,t,n){if(!e)return 1;var i=d.envStore.get(e);if(i.checkGCAccess(),!d.feature.supportBigInt)return i.setLastError(9);if(!r)return i.setLastError(1);if(!t)return i.setLastError(1);if(!n)return i.setLastError(1);var o=d.handleStore.get(r).value;if("bigint"!=typeof o)return i.setLastError(6);n>>>=0,t>>>=0;var s=new DataView(a.buffer),f=function(){return s.buffer===a.buffer?s:s=new DataView(a.buffer)};o>=BigInt(-1)*(BigInt(1)<=BigInt(1)<>BigInt(32));return f().setInt32(t,u,!0),f().setInt32(t+4,c,!0),i.clearLastError()},napi_get_value_bigint_uint64:function(e,r,t,n){if(!e)return 1;var i=d.envStore.get(e);if(i.checkGCAccess(),!d.feature.supportBigInt)return i.setLastError(9);if(!r)return i.setLastError(1);if(!t)return i.setLastError(1);if(!n)return i.setLastError(1);var o=d.handleStore.get(r).value;if("bigint"!=typeof o)return i.setLastError(6);n>>>=0,t>>>=0;var s=new DataView(a.buffer),f=function(){return s.buffer===a.buffer?s:s=new DataView(a.buffer)};o>=BigInt(0)&&o>BigInt(32));return f().setUint32(t,u,!0),f().setUint32(t+4,c,!0),i.clearLastError()},napi_get_value_bigint_words:function(e,r,t,n,i){if(!e)return 1;var o=d.envStore.get(e);if(o.checkGCAccess(),!d.feature.supportBigInt)return o.setLastError(9);if(!r)return o.setLastError(1);if(!n)return o.setLastError(1);var s=d.handleStore.get(r);if(!s.isBigInt())return o.setLastError(17);var f=s.value>>=0,i>>>=0,n>>>=0;var u=new DataView(a.buffer),c=function(){return u.buffer===a.buffer?u:u=new DataView(a.buffer)},l=c().getUint32(n,!0);l>>>=0;for(var v=0,p=f?s.value*BigInt(-1):s.value;p!==BigInt(0);)v++,p>>=BigInt(64);if(p=f?s.value*BigInt(-1):s.value,t||i){if(!t)return o.setLastError(1);if(!i)return o.setLastError(1);for(var y=[];p!==BigInt(0);){var g=p&(BigInt(1)<>=BigInt(64)}for(var w=Math.min(l,y.length),b=0;b>BigInt(32));c().setUint32(i+8*b,h,!0),c().setUint32(i+(8*b+4),_,!0)}c().setInt32(t,f?1:0,!0),c().setUint32(n,w,!0)}else l=v,c().setUint32(n,l,!0);return o.clearLastError()},napi_get_value_bool:function(e,r,t){if(!e)return 1;var n=d.envStore.get(e);if(n.checkGCAccess(),!r)return n.setLastError(1);if(!t)return n.setLastError(1);var i=d.handleStore.get(r);if("boolean"!=typeof i.value)return n.setLastError(7);t>>>=0;var o=i.value?1:0,s=new DataView(a.buffer);return(s.buffer===a.buffer?s:s=new DataView(a.buffer)).setInt8(t,o,!0),n.clearLastError()},napi_get_value_double:function(e,r,t){if(!e)return 1;var n=d.envStore.get(e);if(n.checkGCAccess(),!r)return n.setLastError(1);if(!t)return n.setLastError(1);var i=d.handleStore.get(r);if("number"!=typeof i.value)return n.setLastError(6);t>>>=0;var o=i.value,s=new DataView(a.buffer);return(s.buffer===a.buffer?s:s=new DataView(a.buffer)).setFloat64(t,o,!0),n.clearLastError()},napi_get_value_external:function(e,r,t){if(!e)return 1;var n=d.envStore.get(e);if(n.checkGCAccess(),!r)return n.setLastError(1);if(!t)return n.setLastError(1);var i=d.handleStore.get(r);if(!i.isExternal())return n.setLastError(1);t>>>=0;var o=i.data(),s=new DataView(a.buffer);return(s.buffer===a.buffer?s:s=new DataView(a.buffer)).setUint32(t,o,!0),n.clearLastError()},napi_get_value_int32:function(e,r,t){if(!e)return 1;var n=d.envStore.get(e);if(n.checkGCAccess(),!r)return n.setLastError(1);if(!t)return n.setLastError(1);var i=d.handleStore.get(r);if("number"!=typeof i.value)return n.setLastError(6);t>>>=0;var o=new Int32Array([i.value])[0],s=new DataView(a.buffer);return(s.buffer===a.buffer?s:s=new DataView(a.buffer)).setInt32(t,o,!0),n.clearLastError()},napi_get_value_int64:function(e,r,t){if(!e)return 1;var n=d.envStore.get(e);if(n.checkGCAccess(),!r)return n.setLastError(1);if(!t)return n.setLastError(1);var i=d.handleStore.get(r);if("number"!=typeof i.value)return n.setLastError(6);var o=i.value;t>>>=0;var s=new DataView(a.buffer),f=function(){return s.buffer===a.buffer?s:s=new DataView(a.buffer)};return o===Number.POSITIVE_INFINITY||o===Number.NEGATIVE_INFINITY||isNaN(o)?(f().setInt32(t,0,!0),f().setInt32(t+4,0,!0)):o<-0x8000000000000000?(f().setInt32(t,0,!0),f().setInt32(t+4,2147483648,!0)):o>=0x8000000000000000?(f().setUint32(t,4294967295,!0),f().setUint32(t+4,2147483647,!0)):V(t,Math.trunc(o)),n.clearLastError()},napi_get_value_string_latin1:function(e,r,t,n,i){if(!e)return 1;var o=d.envStore.get(e);if(o.checkGCAccess(),!r)return o.setLastError(1);i>>>=0,t>>>=0,n>>>=0,n>>>=0;var s=d.handleStore.get(r);if("string"!=typeof s.value)return o.setLastError(3);var f=new DataView(a.buffer),u=function(){return f.buffer===a.buffer?f:f=new DataView(a.buffer)};if(t)if(0!==n){for(var c=0,l=void 0,v=0;v>>=0,t>>>=0,n>>>=0,n>>>=0;var s=d.handleStore.get(r);if("string"!=typeof s.value)return o.setLastError(3);var f=new DataView(a.buffer),u=function(){return f.buffer===a.buffer?f:f=new DataView(a.buffer)};if(t)if(0!==n){var c=H.stringToUTF16(s.value,t,2*n);i&&u().setUint32(i,c/2,!0)}else i&&u().setUint32(i,0,!0);else{if(!i)return o.setLastError(1);u().setUint32(i,s.value.length,!0)}return o.clearLastError()},napi_get_value_string_utf8:function(e,r,t,n,i){if(!e)return 1;var o=d.envStore.get(e);if(o.checkGCAccess(),!r)return o.setLastError(1);i>>>=0,t>>>=0,n>>>=0,n>>>=0;var s=d.handleStore.get(r);if("string"!=typeof s.value)return o.setLastError(3);var f=new DataView(a.buffer),u=function(){return f.buffer===a.buffer?f:f=new DataView(a.buffer)};if(t)if(0!==n){var c=H.stringToUTF8(s.value,t,n);i&&u().setUint32(i,c,!0)}else i&&u().setUint32(i,0,!0);else{if(!i)return o.setLastError(1);var l=H.lengthBytesUTF8(s.value);u().setUint32(i,l,!0)}return o.clearLastError()},napi_get_value_uint32:function(e,r,t){if(!e)return 1;var n=d.envStore.get(e);if(n.checkGCAccess(),!r)return n.setLastError(1);if(!t)return n.setLastError(1);var i=d.handleStore.get(r);if("number"!=typeof i.value)return n.setLastError(6);t>>>=0;var o=new Uint32Array([i.value])[0],s=new DataView(a.buffer);return(s.buffer===a.buffer?s:s=new DataView(a.buffer)).setUint32(t,o,!0),n.clearLastError()},node_api_set_prototype:function(e,r,t){if(!e)return 1;var n=d.envStore.get(e);if(n.checkGCAccess(),!n.tryCatch.isEmpty())return n.setLastError(10);if(!n.canCallIntoJs())return n.setLastError(n.moduleApiVersion>=10?23:10);n.clearLastError();try{if(!t)return n.setLastError(1);var a=d.handleStore.get(r).value;if(null==a)throw new TypeError("Cannot convert undefined or null to object");var i=typeof a,o=void 0;try{o="object"===i&&null!==a||"function"===i?a:Object(a)}catch(e){return n.setLastError(2)}var s=d.handleStore.get(t).value;return Object.setPrototypeOf(o,s),n.getReturnStatus()}catch(e){return n.tryCatch.setError(e),n.setLastError(10)}}});function X(e,r,t,n){return H.newString(e,r,t,n,function(e,r,t){var n="",i=0,o=new DataView(a.buffer),s=function(){return o.buffer===a.buffer?o:o=new DataView(a.buffer)};if(r)for(;;){if(!(f=s().getUint8(e,!0)))break;n+=String.fromCharCode(f),e++}else for(;i>>=0;var f=new DataView(a.buffer);return(f.buffer===a.buffer?f:f=new DataView(a.buffer)).setUint32(t,s,!0),o.clearLastError()},napi_create_bigint_uint64:function(e,r,t,n){if(!e)return 1;var i,o=d.envStore.get(e);if(o.checkGCAccess(),!d.feature.supportBigInt)return o.setLastError(9);if(!t)return o.setLastError(1);i=r&(BigInt(1)<>>=0;var f=new DataView(a.buffer);return(f.buffer===a.buffer?f:f=new DataView(a.buffer)).setUint32(t,s,!0),o.clearLastError()},napi_create_bigint_words:function(e,r,t,n,i){var o,s;if(!e)return 1;var f=d.envStore.get(e);if(f.checkGCAccess(),!f.tryCatch.isEmpty())return f.setLastError(10);if(!f.canCallIntoJs())return f.setLastError(f.moduleApiVersion>=10?23:10);f.clearLastError();try{if(!d.feature.supportBigInt)return f.setLastError(9);if(!i)return f.setLastError(1);if(n>>>=0,t>>>=0,(t>>>=0)>2147483647)return f.setLastError(1);if(t>16384)throw new RangeError("Maximum BigInt size exceeded");var u=BigInt(0),c=new DataView(a.buffer),l=function(){return c.buffer===a.buffer?c:c=new DataView(a.buffer)};for(s=0;s>>=0,o=d.addToCurrentScope(u).id,l().setUint32(i,o,!0),f.getReturnStatus()}catch(e){return f.tryCatch.setError(e),f.setLastError(10)}},napi_create_double:function(e,r,t){if(!e)return 1;var n=d.envStore.get(e);if(n.checkGCAccess(),!t)return n.setLastError(1);t>>>=0;var i=d.addToCurrentScope(r).id,o=new DataView(a.buffer);return(o.buffer===a.buffer?o:o=new DataView(a.buffer)).setUint32(t,i,!0),n.clearLastError()},napi_create_int32:function(e,r,t){if(!e)return 1;var n=d.envStore.get(e);if(n.checkGCAccess(),!t)return n.setLastError(1);t>>>=0;var i=d.addToCurrentScope(r).id,o=new DataView(a.buffer);return(o.buffer===a.buffer?o:o=new DataView(a.buffer)).setUint32(t,i,!0),n.clearLastError()},napi_create_int64:function(e,r,t,n){if(!e)return 1;var i,o=d.envStore.get(e);if(o.checkGCAccess(),!t)return o.setLastError(1);i=Number(r);var s=d.addToCurrentScope(i).id;t>>>=0;var f=new DataView(a.buffer);return(f.buffer===a.buffer?f:f=new DataView(a.buffer)).setUint32(t,s,!0),o.clearLastError()},napi_create_string_latin1:X,napi_create_string_utf16:Z,napi_create_string_utf8:K,napi_create_uint32:function(e,r,t){if(!e)return 1;var n=d.envStore.get(e);if(n.checkGCAccess(),!t)return n.setLastError(1);t>>>=0;var i=d.addToCurrentScope(r>>>0).id,o=new DataView(a.buffer);return(o.buffer===a.buffer?o:o=new DataView(a.buffer)).setUint32(t,i,!0),n.clearLastError()},node_api_create_external_string_latin1:function(e,r,t,n,a,i,o){return H.newExternalString(e,r,t,n,a,i,o,X,void 0)},node_api_create_external_string_utf16:function(e,r,t,n,a,i,o){return H.newExternalString(e,r,t,n,a,i,o,Z,void 0)},node_api_create_property_key_latin1:function(e,r,t,n){return X(e,r,t,n)},node_api_create_property_key_utf16:function(e,r,t,n){return Z(e,r,t,n)},node_api_create_property_key_utf8:function(e,r,t,n){return K(e,r,t,n)}});function re(e,r,t,n,a){var o,s=(r>>>=0)&&t?H.UTF8ToString(r,t):"",f=i.get(n),u=function(e){return f(e.id,e.ctx.scopeStore.currentScope.id)},c=function(e,r){return function(){var t=e.ctx.openScope(e),n=t.callbackInfo;n.data=a,n.args=arguments,n.thiz=this,n.fn=o;try{var i=e.callIntoModule(r);return i?e.ctx.handleStore.get(i).value:void 0}finally{n.data=0,n.args=void 0,n.thiz=void 0,n.fn=void 0,e.ctx.closeScope(e,t)}}};if(""===s)return{status:0,f:o=c(e,u)};if(!/^[_$a-zA-Z][_$a-zA-Z0-9]*$/.test(s))return{status:1,f:void 0};if(d.feature.supportNewFunction){var l=c(e,u);try{o=new Function("_","return function "+s+'(){"use strict";return _.apply(this,arguments);};')(l)}catch(r){o=c(e,u),d.feature.canSetFunctionName&&Object.defineProperty(o,"name",{value:s})}}else o=c(e,u),d.feature.canSetFunctionName&&Object.defineProperty(o,"name",{value:s});return{status:0,f:o}}function te(e,r,t,n,a,i,o,s,f){if(a||i){var u=void 0,c=void 0;a&&(u=re(e,0,0,a,f).f),i&&(c=re(e,0,0,i,f).f);var l={configurable:!!(4&s),enumerable:!!(2&s),get:u,set:c};Object.defineProperty(r,t,l)}else if(n){l={configurable:!!(4&s),enumerable:!!(2&s),writable:!!(1&s),value:re(e,0,0,n,f).f};Object.defineProperty(r,t,l)}else{l={configurable:!!(4&s),enumerable:!!(2&s),writable:!!(1&s),value:d.handleStore.get(o).value};Object.defineProperty(r,t,l)}}function ne(e){var r=d.handleStore.get(e);return r.isObject()||r.isFunction()?(void 0!==J&&ArrayBuffer.isView(r.value)&&J.wasmMemoryViewTable.has(r.value)&&(r=d.addToCurrentScope(J.wasmMemoryViewTable.get(r.value))),{status:0,handle:r}):{status:1}}function ae(e,r,t,n){var i;if(!e)return 1;var o=d.envStore.get(e);if(o.checkGCAccess(),!o.tryCatch.isEmpty())return o.setLastError(10);if(!o.canCallIntoJs())return o.setLastError(o.moduleApiVersion>=10?23:10);o.clearLastError();try{if(!r)return o.setLastError(1);if(0===n&&!t)return o.setLastError(1);var s=d.handleStore.get(r);if(!s.isObject()&&!s.isFunction())return o.setLastError(1);var f=o.getObjectBinding(s.value),u=f.wrapped,c=d.refStore.get(u);if(!c)return o.setLastError(1);if(t){t>>>=0,i=c.data();var l=new DataView(a.buffer);(l.buffer===a.buffer?l:l=new DataView(a.buffer)).setUint32(t,i,!0)}return 1===n&&(f.wrapped=0,1===c.ownership()?c.resetFinalizer():c.dispose()),o.getReturnStatus()}catch(e){return o.tryCatch.setError(e),o.setLastError(10)}}function ie(e,r,t,n,i,o){if(!e)return 1;var s=d.envStore.get(e);if(s.checkGCAccess(),!d.feature.supportFinalizer)return s.setLastError(9);if(!r)return s.setLastError(1);if(!n)return s.setLastError(1);var f=ne(r);if(0!==f.status)return s.setLastError(f.status);var u=f.handle,c=o?1:0;t>>>=0,n>>>=0,i>>>=0;var l=d.createReferenceWithFinalizer(s,u.id,0,c,n,t,i);if(o){o>>>=0;var v=l.id,p=new DataView(a.buffer);(p.buffer===a.buffer?p:p=new DataView(a.buffer)).setUint32(o,v,!0)}return s.clearLastError()}var oe=Object.freeze({__proto__:null,napi_add_finalizer:ie,napi_check_object_type_tag:function(e,r,t,n){var i=!0;if(!e)return 1;var o=d.envStore.get(e);if(o.checkGCAccess(),!o.tryCatch.isEmpty())return o.setLastError(10);if(!o.canCallIntoJs())return o.setLastError(o.moduleApiVersion>=10?23:10);o.clearLastError();try{if(!r)return o.setLastError(o.tryCatch.hasCaught()?10:1);var s=d.handleStore.get(r);if(!s.isObject()&&!s.isFunction())return o.setLastError(o.tryCatch.hasCaught()?10:2);if(!t)return o.setLastError(o.tryCatch.hasCaught()?10:1);if(!n)return o.setLastError(o.tryCatch.hasCaught()?10:1);var f=o.getObjectBinding(s.value);if(null!==f.tag){t>>>=0;var u=f.tag,c=new Uint32Array(a.buffer,t,4);i=u[0]===c[0]&&u[1]===c[1]&&u[2]===c[2]&&u[3]===c[3]}else i=!1;n>>>=0;var l=new DataView(a.buffer);return(l.buffer===a.buffer?l:l=new DataView(a.buffer)).setInt8(n,i?1:0,!0),o.getReturnStatus()}catch(e){return o.tryCatch.setError(e),o.setLastError(10)}},napi_define_class:function(e,r,t,n,i,o,s,f){var u,c,l;if(!e)return 1;var v=d.envStore.get(e);if(v.checkGCAccess(),!v.tryCatch.isEmpty())return v.setLastError(10);if(!v.canCallIntoJs())return v.setLastError(v.moduleApiVersion>=10?23:10);v.clearLastError();try{if(!f)return v.setLastError(1);if(!n)return v.setLastError(1);if(t>>>=0,s>>>=0,o>>>=0,(o>>>=0)>0&&!s)return v.setLastError(1);if(!(t>=-1&&t<=2147483647||4294967295===t)||!r)return v.setLastError(1);var p=re(v,r,t,n,i);if(0!==p.status)return v.setLastError(p.status);for(var y=p.f,g=void 0,w=new DataView(a.buffer),b=function(){return w.buffer===a.buffer?w:w=new DataView(a.buffer)},h=0;h>>=0;var C=b().getUint32(u+28,!0);if(_)g=H.UTF8ToString(_,-1);else{if(!E)return v.setLastError(4);if("string"!=typeof(g=d.handleStore.get(E).value)&&"symbol"!=typeof g)return v.setLastError(4)}1024&l?te(v,y,g,L,m,S,A,l,C):te(v,y.prototype,g,L,m,S,A,l,C)}return c=d.addToCurrentScope(y).id,f>>>=0,b().setUint32(f,c,!0),v.getReturnStatus()}catch(e){return v.tryCatch.setError(e),v.setLastError(10)}},napi_remove_wrap:function(e,r,t){return ae(e,r,t,1)},napi_type_tag_object:function(e,r,t){if(!e)return 1;var n=d.envStore.get(e);if(n.checkGCAccess(),!n.tryCatch.isEmpty())return n.setLastError(10);if(!n.canCallIntoJs())return n.setLastError(n.moduleApiVersion>=10?23:10);n.clearLastError();try{if(!r)return n.setLastError(n.tryCatch.hasCaught()?10:1);var i=d.handleStore.get(r);if(!i.isObject()&&!i.isFunction())return n.setLastError(n.tryCatch.hasCaught()?10:2);if(!(t>>>=0))return n.setLastError(n.tryCatch.hasCaught()?10:1);var o=n.getObjectBinding(i.value);if(null!==o.tag)return n.setLastError(n.tryCatch.hasCaught()?10:1);var s=new Uint8Array(16);return s.set(new Uint8Array(a.buffer,t,16)),o.tag=new Uint32Array(s.buffer),n.getReturnStatus()}catch(e){return n.tryCatch.setError(e),n.setLastError(10)}},napi_unwrap:function(e,r,t){return ae(e,r,t,0)},napi_wrap:function(e,r,t,n,i,o){return function(e,r,t,n,i,o){var s;if(!e)return 1;var f=d.envStore.get(e);if(f.checkGCAccess(),!f.tryCatch.isEmpty())return f.setLastError(10);if(!f.canCallIntoJs())return f.setLastError(f.moduleApiVersion>=10?23:10);f.clearLastError();try{if(!d.feature.supportFinalizer){if(n)throw d.createNotSupportWeakRefError("napi_wrap",'Parameter "finalize_cb" must be 0(NULL)');if(o)throw d.createNotSupportWeakRefError("napi_wrap",'Parameter "result" must be 0(NULL)')}if(!r)return f.setLastError(1);var u=ne(r);if(0!==u.status)return f.setLastError(u.status);var c=u.handle;if(0!==f.getObjectBinding(c.value).wrapped)return f.setLastError(1);var l=void 0;if(o){if(!n)return f.setLastError(1);l=d.createReferenceWithFinalizer(f,c.id,0,1,n,t,i),o>>>=0,s=l.id;var v=new DataView(a.buffer);(v.buffer===a.buffer?v:v=new DataView(a.buffer)).setUint32(o,s,!0)}else l=n?d.createReferenceWithFinalizer(f,c.id,0,0,n,t,i):d.createReferenceWithData(f,c.id,0,0,t);return f.getObjectBinding(c.value).wrapped=l.id,f.getReturnStatus()}catch(e){return f.tryCatch.setError(e),f.setLastError(10)}}(e,r,t,n,i,o)},node_api_post_finalizer:function(e,r,t,n){if(!e)return 1;var a=d.envStore.get(e);return a.enqueueFinalizer(d.createTrackedFinalizer(a,r,t,n)),a.clearLastError()}});function se(e,r,t,n,i,o,s){var f;if(!e)return 1;var u=d.envStore.get(e);if(u.checkGCAccess(),!u.tryCatch.isEmpty())return u.setLastError(10);if(!u.canCallIntoJs())return u.setLastError(u.moduleApiVersion>=10?23:10);u.clearLastError();try{if(!s)return u.setLastError(1);if(n>>>=0,s>>>=0,n>>>=0,(t>>>=0)||(n=0),n>2147483647)throw new RangeError("Cannot create a memory view larger than 2147483647 bytes");if(t+n>a.buffer.byteLength)throw new RangeError("Memory out of range");if(!d.feature.supportFinalizer&&i)throw d.createNotSupportWeakRefError("emnapi_create_memory_view",'Parameter "finalize_cb" must be 0(NULL)');var c=void 0;switch(r){case 0:c={Ctor:Int8Array,address:t,length:n,ownership:1,runtimeAllocated:0};break;case 1:c={Ctor:Uint8Array,address:t,length:n,ownership:1,runtimeAllocated:0};break;case 2:c={Ctor:Uint8ClampedArray,address:t,length:n,ownership:1,runtimeAllocated:0};break;case 3:c={Ctor:Int16Array,address:t,length:n>>1,ownership:1,runtimeAllocated:0};break;case 4:c={Ctor:Uint16Array,address:t,length:n>>1,ownership:1,runtimeAllocated:0};break;case 5:c={Ctor:Int32Array,address:t,length:n>>2,ownership:1,runtimeAllocated:0};break;case 6:c={Ctor:Uint32Array,address:t,length:n>>2,ownership:1,runtimeAllocated:0};break;case 7:c={Ctor:Float32Array,address:t,length:n>>2,ownership:1,runtimeAllocated:0};break;case 8:c={Ctor:Float64Array,address:t,length:n>>3,ownership:1,runtimeAllocated:0};break;case 9:c={Ctor:BigInt64Array,address:t,length:n>>3,ownership:1,runtimeAllocated:0};break;case 10:c={Ctor:BigUint64Array,address:t,length:n>>3,ownership:1,runtimeAllocated:0};break;case-1:c={Ctor:DataView,address:t,length:n,ownership:1,runtimeAllocated:0};break;case 11:if("function"!=typeof Float16Array)return u.setLastError(1);c={Ctor:Float16Array,address:t,length:n>>1,ownership:1,runtimeAllocated:0};break;case-2:if(!d.feature.Buffer)throw d.createNotSupportBufferError("emnapi_create_memory_view","");c={Ctor:d.feature.Buffer,address:t,length:n,ownership:1,runtimeAllocated:0};break;default:return u.setLastError(1)}var l=c.Ctor,v=-2===r?J.getBufferFrom()(a.buffer,c.address,c.length):new l(a.buffer,c.address,c.length),p=d.addToCurrentScope(v);if(J.wasmMemoryViewTable.set(v,c),i){var y=ie(e,p.id,t,i,o,0);if(10===y){var g=u.tryCatch.extractException();throw u.clearLastError(),g}if(0!==y)return u.setLastError(y)}f=p.id;var w=new DataView(a.buffer);return(w.buffer===a.buffer?w:w=new DataView(a.buffer)).setUint32(s,f,!0),u.getReturnStatus()}catch(g){return u.tryCatch.setError(g),u.setLastError(10)}}function fe(e,r,t,n){var i;if(t=null!=t?t:0,t>>>=0,r instanceof ArrayBuffer||J.isSharedArrayBuffer(r)){if(!(s=J.getArrayBufferPointer(r,!1).address))throw new Error("Unknown ArrayBuffer address");if("number"==typeof n&&-1!==n&&4294967295!==n||(n=r.byteLength-t),0===(n>>>=0))return r;i=new Uint8Array(r,t,n);var o=new Uint8Array(a.buffer);return e?o.set(i,s):i.set(o.subarray(s,s+n)),r}if(ArrayBuffer.isView(r)){var s,f=J.getViewPointer(r,!1),u=f.view;if(!(s=f.address))throw new Error("Unknown ArrayBuffer address");if("number"==typeof n&&-1!==n&&4294967295!==n||(n=u.byteLength-t),0===(n>>>=0))return u;i=new Uint8Array(u.buffer,u.byteOffset+t,n);o=new Uint8Array(a.buffer);return e?o.set(i,s):i.set(o.subarray(s,s+n)),u}throw new TypeError("emnapiSyncMemory expect ArrayBuffer or ArrayBufferView as first parameter")}function ue(e){var r,t=e instanceof ArrayBuffer,n=e instanceof DataView,a=ArrayBuffer.isView(e)&&!n;if(!(t||a||n||J.isSharedArrayBuffer(e)))throw new TypeError("emnapiGetMemoryAddress expect ArrayBuffer or ArrayBufferView as first parameter");return{address:(r=t?J.getArrayBufferPointer(e,!1):J.getViewPointer(e,!1)).address,ownership:r.ownership,runtimeAllocated:r.runtimeAllocated}}function ce(e,r){if(null!=r&&!J.isSharedArrayBuffer(r))throw new TypeError("Expected a SharedArrayBuffer");if(!N.registry)throw new Error("FinalizationRegistry is not supported in this environment");e>>>=0;var t=N.readMeta(e),n=t.external_data;if(n>>>=0,null==r)r=new SharedArrayBuffer(t.byte_length),new Uint8Array(r).set(new Uint8Array(a.buffer,n,t.byte_length));else if(N.handleTable.has(r))return r;return Atomics.add(new Int32Array(a.buffer,e,1),0,1),J.table.has(r)||n&&J.table.set(r,{address:n,ownership:1,runtimeAllocated:0}),N.handleTable.set(r,e),N.registry.register(r,e),r}var le=Object.freeze({__proto__:null,$emnapiAcquireExternalSharedArrayBuffer:ce,$emnapiGetMemoryAddress:ue,$emnapiSyncMemory:fe,emnapi_acquire_external_sharedarraybuffer:function(e){e>>>=0,Atomics.add(new Int32Array(a.buffer,e,1),0,1)},emnapi_create_memory_view:se,emnapi_get_external_sharedarraybuffer_handle:function(e,r,t){if(!e)return 1;var n=d.envStore.get(e);if(n.checkGCAccess(),!n.tryCatch.isEmpty())return n.setLastError(10);if(!n.canCallIntoJs())return n.setLastError(n.moduleApiVersion>=10?23:10);n.clearLastError();try{if(!r)return n.setLastError(1);if(!t)return n.setLastError(1);t>>>=0;var i=d.handleStore.get(r).value;if(!J.isSharedArrayBuffer(i))return n.setLastError(1);var o=N.handleTable.get(i);if(void 0===o)return n.setLastError(1);var s=new DataView(a.buffer);return(s.buffer===a.buffer?s:s=new DataView(a.buffer)).setUint32(t,o,!0),n.getReturnStatus()}catch(e){return n.tryCatch.setError(e),n.setLastError(10)}},emnapi_get_memory_address:function(e,r,t,n,i){var o,s,f,u;if(!e)return 1;var c=d.envStore.get(e);if(c.checkGCAccess(),!c.tryCatch.isEmpty())return c.setLastError(10);if(!c.canCallIntoJs())return c.setLastError(c.moduleApiVersion>=10?23:10);c.clearLastError();try{if(!r)return c.setLastError(1);if(!t&&!n&&!i)return c.setLastError(1);o=(u=ue(c.ctx.handleStore.get(r).value)).address;var l=new DataView(a.buffer),v=function(){return l.buffer===a.buffer?l:l=new DataView(a.buffer)};return t&&(t>>>=0,v().setUint32(t,o,!0)),n&&(n>>>=0,f=u.ownership,v().setInt32(n,f,!0)),i&&(i>>>=0,s=u.runtimeAllocated,v().setInt8(i,s,!0)),c.getReturnStatus()}catch(e){return c.tryCatch.setError(e),c.setLastError(10)}},emnapi_get_runtime_version:function(e,r){if(!e)return 1;var t,n=d.envStore.get(e);if(!r)return n.setLastError(1);try{t=d.getRuntimeVersions().version}catch(e){return n.setLastError(9)}var i=t.split(".").map(function(e){return Number(e)});r>>>=0;var o=new DataView(a.buffer),s=function(){return o.buffer===a.buffer?o:o=new DataView(a.buffer)};return s().setUint32(r,i[0],!0),s().setUint32(r+4,i[1],!0),s().setUint32(r+8,i[2],!0),n.clearLastError()},emnapi_is_node_binding_available:function(){return v?1:0},emnapi_is_support_bigint:function(){return d.feature.supportBigInt?1:0},emnapi_is_support_weakref:function(){return d.feature.supportFinalizer?1:0},emnapi_release_external_sharedarraybuffer:function(e){e>>>=0,N.release(e)},emnapi_sync_memory:function(e,r,t,n,i){var o;if(!e)return 1;var s=d.envStore.get(e);if(s.checkGCAccess(),!s.tryCatch.isEmpty())return s.setLastError(10);if(!s.canCallIntoJs())return s.setLastError(s.moduleApiVersion>=10?23:10);s.clearLastError();try{if(!t)return s.setLastError(1);t>>>=0,n>>>=0,i>>>=0;var f=new DataView(a.buffer),u=function(){return f.buffer===a.buffer?f:f=new DataView(a.buffer)},c=u().getUint32(t,!0),l=s.ctx.handleStore.get(c);if(!(l.isArrayBuffer()||l.isTypedArray()||l.isDataView()||J.isSharedArrayBuffer(l.value)))return s.setLastError(1);var v=fe(Boolean(r),l.value,n,i);return l.value!==v&&(t>>>=0,o=s.ensureHandleId(v),u().setUint32(t,o,!0)),s.getReturnStatus()}catch(e){return s.tryCatch.setError(e),s.setLastError(10)}}});function de(e,r,t){e>>>=0,e>>>=0;var n=t?new SharedArrayBuffer(e):new ArrayBuffer(e);if(r){r>>>=0;var i=J.getArrayBufferPointer(n,!0).address,o=new DataView(a.buffer);(o.buffer===a.buffer?o:o=new DataView(a.buffer)).setUint32(r,i,!0)}return n}var ve=Object.freeze({__proto__:null,napi_create_array:function(e,r){if(!e)return 1;var t=d.envStore.get(e);if(t.checkGCAccess(),!r)return t.setLastError(1);r>>>=0;var n=d.addToCurrentScope([]).id,i=new DataView(a.buffer);return(i.buffer===a.buffer?i:i=new DataView(a.buffer)).setUint32(r,n,!0),t.clearLastError()},napi_create_array_with_length:function(e,r,t){if(!e)return 1;var n=d.envStore.get(e);if(n.checkGCAccess(),!t)return n.setLastError(1);r>>>=0,t>>>=0,r>>>=0;var i=d.addToCurrentScope(new Array(r)).id,o=new DataView(a.buffer);return(o.buffer===a.buffer?o:o=new DataView(a.buffer)).setUint32(t,i,!0),n.clearLastError()},napi_create_arraybuffer:function(e,r,t,n){var i;if(!e)return 1;var o=d.envStore.get(e);if(o.checkGCAccess(),!o.tryCatch.isEmpty())return o.setLastError(10);if(!o.canCallIntoJs())return o.setLastError(o.moduleApiVersion>=10?23:10);o.clearLastError();try{if(!n)return o.setLastError(1);n>>>=0;var s=de(r,t,!1);i=d.addToCurrentScope(s).id;var f=new DataView(a.buffer);return(f.buffer===a.buffer?f:f=new DataView(a.buffer)).setUint32(n,i,!0),o.getReturnStatus()}catch(e){return o.tryCatch.setError(e),o.setLastError(10)}},napi_create_buffer:function(e,r,t,n){var i,s,f;if(!e)return 1;var u=d.envStore.get(e);if(u.checkGCAccess(),!u.tryCatch.isEmpty())return u.setLastError(10);if(!u.canCallIntoJs())return u.setLastError(u.moduleApiVersion>=10?23:10);u.clearLastError();try{if(!n)return u.setLastError(1);var c=d.feature.Buffer;if(!c)throw d.createNotSupportBufferError("napi_create_buffer","");n>>>=0;var l=void 0;r>>>=0,r>>>=0;var v=new DataView(a.buffer),p=function(){return v.buffer===a.buffer?v:v=new DataView(a.buffer)};if(t&&0!==r){if(!(f=o(r)))throw new Error("Out of memory");f>>>=0,new Uint8Array(a.buffer).subarray(f,f+r).fill(0);var y=J.getBufferFrom()(a.buffer,f,r),g={Ctor:c,address:f,length:r,ownership:J.registry?0:1,runtimeAllocated:1};J.wasmMemoryViewTable.set(y,g),null===(i=J.registry)||void 0===i||i.register(g,f),s=d.addToCurrentScope(y).id,p().setUint32(n,s,!0),t>>>=0,p().setUint32(t,f,!0)}else l=c.alloc(r),s=d.addToCurrentScope(l).id,p().setUint32(n,s,!0);return u.getReturnStatus()}catch(e){return u.tryCatch.setError(e),u.setLastError(10)}},napi_create_buffer_copy:function(e,r,t,n,i){var o;if(!e)return 1;var s=d.envStore.get(e);if(s.checkGCAccess(),!s.tryCatch.isEmpty())return s.setLastError(10);if(!s.canCallIntoJs())return s.setLastError(s.moduleApiVersion>=10?23:10);s.clearLastError();try{if(!i)return s.setLastError(1);var f=d.feature.Buffer;if(!f)throw d.createNotSupportBufferError("napi_create_buffer_copy","");var u=de(r,n,!1),c=f.from(u);t>>>=0,r>>>=0,c.set(new Uint8Array(a.buffer).subarray(t,t+r)),o=d.addToCurrentScope(c).id,i>>>=0;var l=new DataView(a.buffer);return(l.buffer===a.buffer?l:l=new DataView(a.buffer)).setUint32(i,o,!0),s.getReturnStatus()}catch(e){return s.tryCatch.setError(e),s.setLastError(10)}},napi_create_dataview:function(e,r,t,n,i){if(!e)return 1;var o=d.envStore.get(e);if(o.checkGCAccess(),!o.tryCatch.isEmpty())return o.setLastError(10);if(!o.canCallIntoJs())return o.setLastError(o.moduleApiVersion>=10?23:10);o.clearLastError();try{if(!t)return o.setLastError(1);if(!i)return o.setLastError(1);r>>>=0,n>>>=0,r>>>=0,n>>>=0;var s=d.handleStore.get(t).value;return s instanceof ArrayBuffer||J.isSharedArrayBuffer(s)?function(e){if(r+n>e.byteLength){var t=new RangeError("byte_offset + byte_length should be less than or equal to the size in bytes of the array passed in");throw t.code="ERR_NAPI_INVALID_DATAVIEW_ARGS",t}var s=new DataView(e,n,r);e===a.buffer&&(J.wasmMemoryViewTable.has(s)||J.wasmMemoryViewTable.set(s,{Ctor:DataView,address:n,length:r,ownership:1,runtimeAllocated:0})),i>>>=0;var f=d.addToCurrentScope(s).id,u=new DataView(a.buffer);return(u.buffer===a.buffer?u:u=new DataView(a.buffer)).setUint32(i,f,!0),o.getReturnStatus()}(s):o.setLastError(1)}catch(e){return o.tryCatch.setError(e),o.setLastError(10)}},napi_create_date:function(e,r,t){var n;if(!e)return 1;var i=d.envStore.get(e);if(i.checkGCAccess(),!i.tryCatch.isEmpty())return i.setLastError(10);if(!i.canCallIntoJs())return i.setLastError(i.moduleApiVersion>=10?23:10);i.clearLastError();try{if(!t)return i.setLastError(1);t>>>=0,n=d.addToCurrentScope(new Date(r)).id;var o=new DataView(a.buffer);return(o.buffer===a.buffer?o:o=new DataView(a.buffer)).setUint32(t,n,!0),i.getReturnStatus()}catch(e){return i.tryCatch.setError(e),i.setLastError(10)}},napi_create_external:function(e,r,t,n,i){var o;if(!e)return 1;var s=d.envStore.get(e);if(s.checkGCAccess(),!s.tryCatch.isEmpty())return s.setLastError(10);if(!s.canCallIntoJs())return s.setLastError(s.moduleApiVersion>=10?23:10);s.clearLastError();try{if(!i)return s.setLastError(1);if(!d.feature.supportFinalizer&&t)throw d.createNotSupportWeakRefError("napi_create_external",'Parameter "finalize_cb" must be 0(NULL)');var f=d.getCurrentScope().addExternal(r);t&&d.createReferenceWithFinalizer(s,f.id,0,0,t,r,n),i>>>=0,o=f.id;var u=new DataView(a.buffer);return(u.buffer===a.buffer?u:u=new DataView(a.buffer)).setUint32(i,o,!0),s.clearLastError()}catch(e){return s.tryCatch.setError(e),s.setLastError(10)}},napi_create_external_arraybuffer:function(e,r,t,n,i,o){var s;if(!e)return 1;var f=d.envStore.get(e);if(f.checkGCAccess(),!f.tryCatch.isEmpty())return f.setLastError(10);if(!f.canCallIntoJs())return f.setLastError(f.moduleApiVersion>=10?23:10);f.clearLastError();try{if(!o)return f.setLastError(1);if(t>>>=0,o>>>=0,t>>>=0,(r>>>=0)||(t=0),r+t>a.buffer.byteLength)throw new RangeError("Memory out of range");if(!d.feature.supportFinalizer&&n)throw d.createNotSupportWeakRefError("napi_create_external_arraybuffer",'Parameter "finalize_cb" must be 0(NULL)');var u=new ArrayBuffer(t);if(0===t)try{(new(0,d.feature.MessageChannel)).port1.postMessage(u,[u])}catch(e){}else new Uint8Array(u).set(new Uint8Array(a.buffer).subarray(r,r+t)),J.table.set(u,{address:r,ownership:1,runtimeAllocated:0});var c=d.addToCurrentScope(u);if(n){var l=ie(e,c.id,r,n,i,0);if(10===l){var v=f.tryCatch.extractException();throw f.clearLastError(),v}if(0!==l)return f.setLastError(l)}s=c.id;var p=new DataView(a.buffer);return(p.buffer===a.buffer?p:p=new DataView(a.buffer)).setUint32(o,s,!0),f.getReturnStatus()}catch(v){return f.tryCatch.setError(v),f.setLastError(10)}},napi_create_external_buffer:function(e,r,t,n,a,i){return se(e,-2,t,r,n,a,i)},napi_create_object:function(e,r){if(!e)return 1;var t=d.envStore.get(e);if(t.checkGCAccess(),!r)return t.setLastError(1);r>>>=0;var n=d.addToCurrentScope({}).id,i=new DataView(a.buffer);return(i.buffer===a.buffer?i:i=new DataView(a.buffer)).setUint32(r,n,!0),t.clearLastError()},napi_create_symbol:function(e,r,t){if(!e)return 1;var n=d.envStore.get(e);if(n.checkGCAccess(),!t)return n.setLastError(1);t>>>=0;var i=new DataView(a.buffer),o=function(){return i.buffer===a.buffer?i:i=new DataView(a.buffer)};if(r){var s=d.handleStore.get(r).value;if("string"!=typeof s)return n.setLastError(3);var f=d.addToCurrentScope(Symbol(s)).id;o().setUint32(t,f,!0)}else{var u=d.addToCurrentScope(Symbol()).id;o().setUint32(t,u,!0)}return n.clearLastError()},napi_create_typedarray:function(e,r,t,n,i,o){var s;if(!e)return 1;var f=d.envStore.get(e);if(f.checkGCAccess(),!f.tryCatch.isEmpty())return f.setLastError(10);if(!f.canCallIntoJs())return f.setLastError(f.moduleApiVersion>=10?23:10);f.clearLastError();try{if(!n)return f.setLastError(1);if(!o)return f.setLastError(1);var u=d.handleStore.get(n).value;i>>>=0,t>>>=0;var c=function(e,r,t,n,i,f){var u,c;if((i>>>=0,f>>>=0,t>1)&&i%t!==0)return(c=new RangeError("start offset of ".concat(null!==(u=r.name)&&void 0!==u?u:""," should be a multiple of ").concat(t))).code="ERR_NAPI_INVALID_TYPEDARRAY_ALIGNMENT",e.tryCatch.setError(c),e.setLastError(9);if(f*t+i>n.byteLength)return(c=new RangeError("Invalid typed array length")).code="ERR_NAPI_INVALID_TYPEDARRAY_LENGTH",e.tryCatch.setError(c),e.setLastError(9);var l=new r(n,i,f);n===a.buffer&&(J.wasmMemoryViewTable.has(l)||J.wasmMemoryViewTable.set(l,{Ctor:r,address:i,length:f,ownership:1,runtimeAllocated:0})),o>>>=0,s=d.addToCurrentScope(l).id;var v=new DataView(a.buffer);return(v.buffer===a.buffer?v:v=new DataView(a.buffer)).setUint32(o,s,!0),e.getReturnStatus()};if(!(u instanceof ArrayBuffer||J.isSharedArrayBuffer(u)))return f.setLastError(1);switch(r){case 0:return c(f,Int8Array,1,u,i,t);case 1:return c(f,Uint8Array,1,u,i,t);case 2:return c(f,Uint8ClampedArray,1,u,i,t);case 3:return c(f,Int16Array,2,u,i,t);case 4:return c(f,Uint16Array,2,u,i,t);case 5:return c(f,Int32Array,4,u,i,t);case 6:return c(f,Uint32Array,4,u,i,t);case 7:return c(f,Float32Array,4,u,i,t);case 8:return c(f,Float64Array,8,u,i,t);case 9:return c(f,BigInt64Array,8,u,i,t);case 10:return c(f,BigUint64Array,8,u,i,t);case 11:return"function"!=typeof Float16Array?f.setLastError(1):c(f,Float16Array,2,u,i,t);default:return f.setLastError(1)}}catch(e){return f.tryCatch.setError(e),f.setLastError(10)}},node_api_create_buffer_from_arraybuffer:function(e,r,t,n,i){var o;if(!e)return 1;var s=d.envStore.get(e);if(s.checkGCAccess(),!s.tryCatch.isEmpty())return s.setLastError(10);if(!s.canCallIntoJs())return s.setLastError(s.moduleApiVersion>=10?23:10);s.clearLastError();try{if(!r)return s.setLastError(1);if(!i)return s.setLastError(1);t>>>=0,n>>>=0,t>>>=0,n>>>=0;var f=d.handleStore.get(r);if(!f.isArrayBuffer())return s.setLastError(1);var u=f.value;if(n+t>u.byteLength){var c=new RangeError("The byte offset + length is out of range");throw c.code="ERR_OUT_OF_RANGE",c}var l=d.feature.Buffer;if(!l)throw d.createNotSupportBufferError("node_api_create_buffer_from_arraybuffer","");var v=J.getBufferFrom()(u,t,n);u===a.buffer&&(J.wasmMemoryViewTable.has(v)||J.wasmMemoryViewTable.set(v,{Ctor:l,address:t,length:n,ownership:1,runtimeAllocated:0})),i>>>=0,o=d.addToCurrentScope(v).id;var p=new DataView(a.buffer);return(p.buffer===a.buffer?p:p=new DataView(a.buffer)).setUint32(i,o,!0),s.getReturnStatus()}catch(c){return s.tryCatch.setError(c),s.setLastError(10)}},node_api_create_external_sharedarraybuffer:function(e,r,t,n,i,o){var s;if(!e)return 1;var f=d.envStore.get(e);if(f.checkGCAccess(),!f.tryCatch.isEmpty())return f.setLastError(10);if(!f.canCallIntoJs())return f.setLastError(f.moduleApiVersion>=10?23:10);f.clearLastError();try{if(!o)return f.setLastError(1);if(t>>>=0,o>>>=0,t>>>=0,(r>>>=0)||(t=0),r+t>a.buffer.byteLength)throw new RangeError("Memory out of range");if(!N.registry&&n)throw d.createNotSupportWeakRefError("node_api_create_external_sharedarraybuffer",'Parameter "finalize_cb" must be 0(NULL)');var u=new SharedArrayBuffer(t);if(0!==t)new Uint8Array(u).set(new Uint8Array(a.buffer).subarray(r,r+t)),J.table.set(u,{address:r,ownership:1,runtimeAllocated:0});if(s=d.addToCurrentScope(u).id,n){n>>>=0,i>>>=0;var c=N.allocMeta(r,t,n,r,i);N.handleTable.set(u,c),N.registry.register(u,c)}var l=new DataView(a.buffer);return(l.buffer===a.buffer?l:l=new DataView(a.buffer)).setUint32(o,s,!0),f.getReturnStatus()}catch(e){return f.tryCatch.setError(e),f.setLastError(10)}},node_api_create_object_with_properties:function(e,r,t,n,i,o){if(!e)return 1;var s=d.envStore.get(e);if(s.checkGCAccess(),!o)return s.setLastError(1);if(i>>>=0,(i>>>=0)>0){if(!t)return s.setLastError(1);if(!n)return s.setLastError(1)}var f=r?d.handleStore.get(r).value:null,u={};t>>>=0,n>>>=0;for(var c,l=new DataView(a.buffer),v=function(){return l.buffer===a.buffer?l:l=new DataView(a.buffer)},p=0;p>>=0,v().setUint32(o,g,!0),s.clearLastError()},node_api_create_sharedarraybuffer:function(e,r,t,n){var i;if(!e)return 1;var o=d.envStore.get(e);if(o.checkGCAccess(),!o.tryCatch.isEmpty())return o.setLastError(10);if(!o.canCallIntoJs())return o.setLastError(o.moduleApiVersion>=10?23:10);o.clearLastError();try{if(!n)return o.setLastError(1);n>>>=0;var s=de(r,t,!0);i=d.addToCurrentScope(s).id;var f=new DataView(a.buffer);return(f.buffer===a.buffer?f:f=new DataView(a.buffer)).setUint32(n,i,!0),o.getReturnStatus()}catch(e){return o.tryCatch.setError(e),o.setLastError(10)}},node_api_symbol_for:function(e,r,t,n){if(!e)return 1;var i=d.envStore.get(e);if(i.checkGCAccess(),!n)return i.setLastError(1);r>>>=0,n>>>=0;var o=-1===(t>>>=0)||4294967295===t,s=t>>>0;if(0!==t&&!r)return i.setLastError(1);if(!(o||s<=2147483647))return i.setLastError(1);var f=H.UTF8ToString(r,t),u=d.addToCurrentScope(Symbol.for(f)).id,c=new DataView(a.buffer);return(c.buffer===a.buffer?c:c=new DataView(a.buffer)).setUint32(n,u,!0),i.clearLastError()}});var pe=Object.freeze({__proto__:null,napi_get_boolean:function(e,r,t){if(!e)return 1;var n=d.envStore.get(e);if(n.checkGCAccess(),!t)return n.setLastError(1);t>>>=0;var i=0===r?3:4,o=new DataView(a.buffer);return(o.buffer===a.buffer?o:o=new DataView(a.buffer)).setUint32(t,i,!0),n.clearLastError()},napi_get_global:function(e,r){if(!e)return 1;var t=d.envStore.get(e);if(t.checkGCAccess(),!r)return t.setLastError(1);r>>>=0;var n=new DataView(a.buffer);return(n.buffer===a.buffer?n:n=new DataView(a.buffer)).setUint32(r,5,!0),t.clearLastError()},napi_get_null:function(e,r){if(!e)return 1;var t=d.envStore.get(e);if(t.checkGCAccess(),!r)return t.setLastError(1);r>>>=0;var n=new DataView(a.buffer);return(n.buffer===a.buffer?n:n=new DataView(a.buffer)).setUint32(r,2,!0),t.clearLastError()},napi_get_undefined:function(e,r){if(!e)return 1;var t=d.envStore.get(e);if(t.checkGCAccess(),!r)return t.setLastError(1);r>>>=0;var n=new DataView(a.buffer);return(n.buffer===a.buffer?n:n=new DataView(a.buffer)).setUint32(r,1,!0),t.clearLastError()}});var ye=Object.freeze({__proto__:null,napi_get_instance_data:function(e,r){if(!e)return 1;var t=d.envStore.get(e);if(!r)return t.setLastError(1);r>>>=0;var n=t.getInstanceData(),i=new DataView(a.buffer);return(i.buffer===a.buffer?i:i=new DataView(a.buffer)).setUint32(r,n,!0),t.clearLastError()},napi_set_instance_data:function(e,r,t,n){if(!e)return 1;var a=d.envStore.get(e);return r>>>=0,t>>>=0,n>>>=0,a.setInstanceData(r,t,n),a.clearLastError()}});var ge=Object.freeze({__proto__:null,_emnapi_get_last_error_info:function(e,r,t,n){r>>>=0,t>>>=0,n>>>=0;var i=d.envStore.get(e).lastError,o=i.errorCode,s=i.engineErrorCode>>>0,f=i.engineReserved;f>>>=0;var u=new DataView(a.buffer),c=function(){return u.buffer===a.buffer?u:u=new DataView(a.buffer)};c().setInt32(r,o,!0),c().setUint32(t,s,!0),c().setUint32(n,f,!0)},napi_create_error:function(e,r,t,n){if(!e)return 1;var i=d.envStore.get(e);if(i.checkGCAccess(),!t)return i.setLastError(1);if(!n)return i.setLastError(1);var o=d.handleStore.get(t).value;if("string"!=typeof o)return i.setLastError(3);var s=new Error(o);if(r){var f=d.handleStore.get(r).value;if("string"!=typeof f)return i.setLastError(3);s.code=f}n>>>=0;var u=d.addToCurrentScope(s).id,c=new DataView(a.buffer);return(c.buffer===a.buffer?c:c=new DataView(a.buffer)).setUint32(n,u,!0),i.clearLastError()},napi_create_range_error:function(e,r,t,n){if(!e)return 1;var i=d.envStore.get(e);if(i.checkGCAccess(),!t)return i.setLastError(1);if(!n)return i.setLastError(1);var o=d.handleStore.get(t).value;if("string"!=typeof o)return i.setLastError(3);var s=new RangeError(o);if(r){var f=d.handleStore.get(r).value;if("string"!=typeof f)return i.setLastError(3);s.code=f}n>>>=0;var u=d.addToCurrentScope(s).id,c=new DataView(a.buffer);return(c.buffer===a.buffer?c:c=new DataView(a.buffer)).setUint32(n,u,!0),i.clearLastError()},napi_create_type_error:function(e,r,t,n){if(!e)return 1;var i=d.envStore.get(e);if(i.checkGCAccess(),!t)return i.setLastError(1);if(!n)return i.setLastError(1);var o=d.handleStore.get(t).value;if("string"!=typeof o)return i.setLastError(3);var s=new TypeError(o);if(r){var f=d.handleStore.get(r).value;if("string"!=typeof f)return i.setLastError(3);s.code=f}n>>>=0;var u=d.addToCurrentScope(s).id,c=new DataView(a.buffer);return(c.buffer===a.buffer?c:c=new DataView(a.buffer)).setUint32(n,u,!0),i.clearLastError()},napi_fatal_error:function(e,r,t,n){e>>>=0,r>>>=0,t>>>=0,n>>>=0;var a=H.UTF8ToString(e,r),i=H.UTF8ToString(t,n);v?v.napi.fatalError(a,i):l("FATAL ERROR: "+a+" "+i)},napi_fatal_exception:function(e,r){if(!e)return 1;var t=d.envStore.get(e);if(t.checkGCAccess(),!t.tryCatch.isEmpty())return t.setLastError(10);if(!t.canCallIntoJs())return t.setLastError(t.moduleApiVersion>=10?23:10);t.clearLastError();try{if(!r)return t.setLastError(1);var n=t.ctx.handleStore.get(r);try{t.triggerFatalException(n.value)}catch(e){return t.setLastError(9)}return t.clearLastError()}catch(r){return t.tryCatch.setError(r),t.setLastError(10)}},napi_get_and_clear_last_exception:function(e,r){if(!e)return 1;var t=d.envStore.get(e);if(t.checkGCAccess(),!r)return t.setLastError(1);r>>>=0;var n=new DataView(a.buffer),i=function(){return n.buffer===a.buffer?n:n=new DataView(a.buffer)};if(!t.tryCatch.hasCaught())return i().setUint32(r,1,!0),t.clearLastError();var o=t.tryCatch.exception(),s=t.ensureHandleId(o);return i().setUint32(r,s,!0),t.tryCatch.reset(),t.clearLastError()},napi_is_exception_pending:function(e,r){if(!e)return 1;var t=d.envStore.get(e);if(t.checkGCAccess(),!r)return t.setLastError(1);var n=t.tryCatch.hasCaught();r>>>=0;var i=new DataView(a.buffer);return(i.buffer===a.buffer?i:i=new DataView(a.buffer)).setInt8(r,n?1:0,!0),t.clearLastError()},napi_throw:function(e,r){if(!e)return 1;var t=d.envStore.get(e);if(t.checkGCAccess(),!t.tryCatch.isEmpty())return t.setLastError(10);if(!t.canCallIntoJs())return t.setLastError(t.moduleApiVersion>=10?23:10);t.clearLastError();try{return r?(t.tryCatch.setError(d.handleStore.get(r).value),t.clearLastError()):t.setLastError(1)}catch(e){return t.tryCatch.setError(e),t.setLastError(10)}},napi_throw_error:function(e,r,t){if(!e)return 1;var n=d.envStore.get(e);if(n.checkGCAccess(),!n.tryCatch.isEmpty())return n.setLastError(10);if(!n.canCallIntoJs())return n.setLastError(n.moduleApiVersion>=10?23:10);n.clearLastError();try{if(!t)return n.setLastError(1);r>>>=0,t>>>=0;var a=new Error(H.UTF8ToString(t,-1));return r&&(a.code=H.UTF8ToString(r,-1)),n.tryCatch.setError(a),n.clearLastError()}catch(e){return n.tryCatch.setError(e),n.setLastError(10)}},napi_throw_range_error:function(e,r,t){if(!e)return 1;var n=d.envStore.get(e);if(n.checkGCAccess(),!n.tryCatch.isEmpty())return n.setLastError(10);if(!n.canCallIntoJs())return n.setLastError(n.moduleApiVersion>=10?23:10);n.clearLastError();try{if(!t)return n.setLastError(1);r>>>=0,t>>>=0;var a=new RangeError(H.UTF8ToString(t,-1));return r&&(a.code=H.UTF8ToString(r,-1)),n.tryCatch.setError(a),n.clearLastError()}catch(e){return n.tryCatch.setError(e),n.setLastError(10)}},napi_throw_type_error:function(e,r,t){if(!e)return 1;var n=d.envStore.get(e);if(n.checkGCAccess(),!n.tryCatch.isEmpty())return n.setLastError(10);if(!n.canCallIntoJs())return n.setLastError(n.moduleApiVersion>=10?23:10);n.clearLastError();try{if(!t)return n.setLastError(1);r>>>=0,t>>>=0;var a=new TypeError(H.UTF8ToString(t,-1));return r&&(a.code=H.UTF8ToString(r,-1)),n.tryCatch.setError(a),n.clearLastError()}catch(e){return n.tryCatch.setError(e),n.setLastError(10)}},node_api_create_syntax_error:function(e,r,t,n){if(!e)return 1;var i=d.envStore.get(e);if(i.checkGCAccess(),!t)return i.setLastError(1);if(!n)return i.setLastError(1);var o=d.handleStore.get(t).value;if("string"!=typeof o)return i.setLastError(3);var s=new SyntaxError(o);if(r){var f=d.handleStore.get(r).value;if("string"!=typeof f)return i.setLastError(3);s.code=f}n>>>=0;var u=d.addToCurrentScope(s).id,c=new DataView(a.buffer);return(c.buffer===a.buffer?c:c=new DataView(a.buffer)).setUint32(n,u,!0),i.clearLastError()},node_api_throw_syntax_error:function(e,r,t){if(!e)return 1;var n=d.envStore.get(e);if(n.checkGCAccess(),!n.tryCatch.isEmpty())return n.setLastError(10);if(!n.canCallIntoJs())return n.setLastError(n.moduleApiVersion>=10?23:10);n.clearLastError();try{if(!t)return n.setLastError(1);r>>>=0,t>>>=0;var a=new SyntaxError(H.UTF8ToString(t,-1));return r&&(a.code=H.UTF8ToString(r,-1)),n.tryCatch.setError(a),n.clearLastError()}catch(e){return n.tryCatch.setError(e),n.setLastError(10)}}});function we(e,r,t,n,i,o){t>>>=0;var s=d.envStore.get(e),f=re(s,r,t,n,i);if(0!==f.status)return s.setLastError(f.status);var u=f.f;o>>>=0;var c=d.addToCurrentScope(u).id,l=new DataView(a.buffer);return(l.buffer===a.buffer?l:l=new DataView(a.buffer)).setUint32(o,c,!0),s.getReturnStatus()}var be=Object.freeze({__proto__:null,_emnapi_create_function:we,napi_call_function:function(e,r,t,n,i,o){var s,f=0;if(!e)return 1;var u=d.envStore.get(e);if(u.checkGCAccess(),!u.tryCatch.isEmpty())return u.setLastError(10);if(!u.canCallIntoJs())return u.setLastError(u.moduleApiVersion>=10?23:10);u.clearLastError();try{if(!r)return u.setLastError(1);if(n>>>=0,i>>>=0,o>>>=0,(n>>>=0)>0&&!i)return u.setLastError(1);var c=d.handleStore.get(r).value;if(!t)return u.setLastError(1);var l=d.handleStore.get(t).value;if("function"!=typeof l)return u.setLastError(1);for(var v=[],p=new DataView(a.buffer),y=function(){return p.buffer===a.buffer?p:p=new DataView(a.buffer)};f=10?23:10);o.clearLastError();try{return i&&n?we(e,r,t,n,a,i):o.setLastError(1)}catch(e){return o.tryCatch.setError(e),o.setLastError(10)}},napi_get_cb_info:function(e,r,t,n,i,o){if(!e)return 1;var s=d.envStore.get(e);if(!r)return s.setLastError(1);var f=d.scopeStore.get(r).callbackInfo;t>>>=0,n>>>=0;var u=new DataView(a.buffer),c=function(){return u.buffer===a.buffer?u:u=new DataView(a.buffer)};if(n){if(!t)return s.setLastError(1);var l=c().getUint32(t,!0);l>>>=0;for(var v=f.args.length,p=l>>=0;var w=s.ensureHandleId(f.thiz);c().setUint32(i,w,!0)}return o&&(o>>>=0,c().setUint32(o,f.data,!0)),s.clearLastError()},napi_get_new_target:function(e,r,t){if(!e)return 1;var n=d.envStore.get(e);if(n.checkGCAccess(),!r)return n.setLastError(1);if(!t)return n.setLastError(1);t>>>=0;var i=d.scopeStore.get(r).callbackInfo,o=i.thiz,s=i.fn,f=null==o||null==o.constructor?0:o instanceof s?n.ensureHandleId(o.constructor):0,u=new DataView(a.buffer);return(u.buffer===a.buffer?u:u=new DataView(a.buffer)).setUint32(t,f,!0),n.clearLastError()},napi_new_instance:function(e,r,t,n,i){var o,s;if(!e)return 1;var f=d.envStore.get(e);if(f.checkGCAccess(),!f.tryCatch.isEmpty())return f.setLastError(10);if(!f.canCallIntoJs())return f.setLastError(f.moduleApiVersion>=10?23:10);f.clearLastError();try{if(!r)return f.setLastError(1);if(t>>>=0,n>>>=0,i>>>=0,(t>>>=0)>0&&!n)return f.setLastError(1);if(!i)return f.setLastError(1);var u=d.handleStore.get(r).value;if("function"!=typeof u)return f.setLastError(1);var c=void 0,l=new DataView(a.buffer),v=function(){return l.buffer===a.buffer?l:l=new DataView(a.buffer)};if(d.feature.supportReflect){var p=Array(t);for(o=0;o>>=0,t>>>=0,d.addCleanupHook(n,r,t),0):n.setLastError(1)},napi_close_escapable_handle_scope:function(e,r){if(!e)return 1;var t=d.envStore.get(e);return t.checkGCAccess(),r?0===t.openHandleScopes?13:(d.closeScope(t),t.clearLastError()):t.setLastError(1)},napi_close_handle_scope:function(e,r){if(!e)return 1;var t=d.envStore.get(e);return t.checkGCAccess(),r?0===t.openHandleScopes?13:(d.closeScope(t),t.clearLastError()):t.setLastError(1)},napi_create_reference:function(e,r,t,n){if(!e)return 1;var i=d.envStore.get(e);if(i.checkGCAccess(),!r)return i.setLastError(1);if(!n)return i.setLastError(1);var o=d.handleStore.get(r);if(i.moduleApiVersion<10&&!(o.isObject()||o.isFunction()||o.isSymbol()))return i.setLastError(1);var s=d.createReference(i,o.id,t>>>0,1);n>>>=0;var f=new DataView(a.buffer);return(f.buffer===a.buffer?f:f=new DataView(a.buffer)).setUint32(n,s.id,!0),i.clearLastError()},napi_delete_reference:function(e,r){if(!e)return 1;var t=d.envStore.get(e);return r?(d.refStore.get(r).dispose(),t.clearLastError()):t.setLastError(1)},napi_escape_handle:function(e,r,t,n){if(!e)return 1;var i=d.envStore.get(e);if(i.checkGCAccess(),!r)return i.setLastError(1);if(!t)return i.setLastError(1);if(!n)return i.setLastError(1);var o=d.scopeStore.get(r);if(!o.escapeCalled()){t>>>=0,n>>>=0;var s=o.escape(t),f=s?s.id:0,u=new DataView(a.buffer);return(u.buffer===a.buffer?u:u=new DataView(a.buffer)).setUint32(n,f,!0),i.clearLastError()}return i.setLastError(12)},napi_get_reference_value:function(e,r,t){if(!e)return 1;var n=d.envStore.get(e);if(n.checkGCAccess(),!r)return n.setLastError(1);if(!t)return n.setLastError(1);var i=d.refStore.get(r).get(n);t>>>=0;var o=new DataView(a.buffer);return(o.buffer===a.buffer?o:o=new DataView(a.buffer)).setUint32(t,i,!0),n.clearLastError()},napi_open_escapable_handle_scope:function(e,r){if(!e)return 1;var t=d.envStore.get(e);if(t.checkGCAccess(),!r)return t.setLastError(1);var n=d.openScope(t);r>>>=0;var i=new DataView(a.buffer);return(i.buffer===a.buffer?i:i=new DataView(a.buffer)).setUint32(r,n.id,!0),t.clearLastError()},napi_open_handle_scope:function(e,r){if(!e)return 1;var t=d.envStore.get(e);if(t.checkGCAccess(),!r)return t.setLastError(1);var n=d.openScope(t);r>>>=0;var i=new DataView(a.buffer);return(i.buffer===a.buffer?i:i=new DataView(a.buffer)).setUint32(r,n.id,!0),t.clearLastError()},napi_reference_ref:function(e,r,t){if(!e)return 1;var n=d.envStore.get(e);if(n.checkGCAccess(),!r)return n.setLastError(1);var i=d.refStore.get(r).ref();if(t){t>>>=0;var o=new DataView(a.buffer);(o.buffer===a.buffer?o:o=new DataView(a.buffer)).setUint32(t,i,!0)}return n.clearLastError()},napi_reference_unref:function(e,r,t){if(!e)return 1;var n=d.envStore.get(e);if(n.checkGCAccess(),!r)return n.setLastError(1);var i=d.refStore.get(r);if(0===i.refcount())return n.setLastError(9);var o=i.unref();if(t){t>>>=0;var s=new DataView(a.buffer);(s.buffer===a.buffer?s:s=new DataView(a.buffer)).setUint32(t,o,!0)}return n.clearLastError()},napi_remove_env_cleanup_hook:function(e,r,t){if(!e)return 1;var n=d.envStore.get(e);return r?(r>>>=0,t>>>=0,d.removeCleanupHook(n,r,t),0):n.setLastError(1)}});var _e=Object.freeze({__proto__:null,_emnapi_get_filename:function(e,r,t){var n=d.envStore.get(e).filename;return r?H.stringToUTF8(n,r,t):H.lengthBytesUTF8(n)}});var Ee=Object.freeze({__proto__:null,napi_create_promise:function(e,r,t){var n,i;if(!e)return 1;var o=d.envStore.get(e);if(o.checkGCAccess(),!o.tryCatch.isEmpty())return o.setLastError(10);if(!o.canCallIntoJs())return o.setLastError(o.moduleApiVersion>=10?23:10);o.clearLastError();try{if(!r)return o.setLastError(1);if(!t)return o.setLastError(1);var s=new DataView(a.buffer),f=function(){return s.buffer===a.buffer?s:s=new DataView(a.buffer)},u=new Promise(function(e,t){var a=d.createDeferred({resolve:e,reject:t});n=a.id,r>>>=0,f().setUint32(r,n,!0)});return t>>>=0,i=d.addToCurrentScope(u).id,f().setUint32(t,i,!0),o.getReturnStatus()}catch(e){return o.tryCatch.setError(e),o.setLastError(10)}},napi_is_promise:function(e,r,t){if(!e)return 1;var n=d.envStore.get(e);if(n.checkGCAccess(),!r)return n.setLastError(1);if(!t)return n.setLastError(1);t>>>=0;var i=d.handleStore.get(r).isPromise()?1:0,o=new DataView(a.buffer);return(o.buffer===a.buffer?o:o=new DataView(a.buffer)).setInt8(t,i,!0),n.clearLastError()},napi_reject_deferred:function(e,r,t){if(!e)return 1;var n=d.envStore.get(e);if(n.checkGCAccess(),!n.tryCatch.isEmpty())return n.setLastError(10);if(!n.canCallIntoJs())return n.setLastError(n.moduleApiVersion>=10?23:10);n.clearLastError();try{return r&&t?(d.deferredStore.get(r).reject(d.handleStore.get(t).value),n.getReturnStatus()):n.setLastError(1)}catch(e){return n.tryCatch.setError(e),n.setLastError(10)}},napi_resolve_deferred:function(e,r,t){if(!e)return 1;var n=d.envStore.get(e);if(n.checkGCAccess(),!n.tryCatch.isEmpty())return n.setLastError(10);if(!n.canCallIntoJs())return n.setLastError(n.moduleApiVersion>=10?23:10);n.clearLastError();try{return r&&t?(d.deferredStore.get(r).resolve(d.handleStore.get(t).value),n.getReturnStatus()):n.setLastError(1)}catch(e){return n.tryCatch.setError(e),n.setLastError(10)}}});function Le(e,r,t,n,i,o){var s;if(!e)return 1;var f=d.envStore.get(e);if(f.checkGCAccess(),!f.tryCatch.isEmpty())return f.setLastError(10);if(!f.canCallIntoJs())return f.setLastError(f.moduleApiVersion>=10?23:10);f.clearLastError();try{if(!o)return f.setLastError(1);if(!r)return f.setLastError(1);var u=d.handleStore.get(r);if(null==u.value)throw new TypeError("Cannot convert undefined or null to object");var c=void 0;try{c=u.isObject()||u.isFunction()?u.value:Object(u.value)}catch(e){return f.setLastError(2)}if(0!==t&&1!==t)return f.setLastError(1);if(0!==i&&1!==i)return f.setLastError(1);var l=[],v=void 0,p=void 0,y=void 0,g=!0,w=/^(0|[1-9][0-9]*)$/;do{for(v=Object.getOwnPropertyNames(c),p=Object.getOwnPropertySymbols(c),y=0;y>>=0,s=d.addToCurrentScope(b).id;var S=new DataView(a.buffer);return(S.buffer===a.buffer?S:S=new DataView(a.buffer)).setUint32(o,s,!0),f.getReturnStatus()}catch(e){return f.tryCatch.setError(e),f.setLastError(10)}}var me=Object.freeze({__proto__:null,napi_define_properties:function(e,r,t,n){var i,o;if(!e)return 1;var s=d.envStore.get(e);if(s.checkGCAccess(),!s.tryCatch.isEmpty())return s.setLastError(10);if(!s.canCallIntoJs())return s.setLastError(s.moduleApiVersion>=10?23:10);s.clearLastError();try{if(n>>>=0,t>>>=0,(t>>>=0)>0&&!n)return s.setLastError(1);if(!r)return s.setLastError(1);var f=d.handleStore.get(r),u=f.value;if(!f.isObject()&&!f.isFunction())return s.setLastError(2);for(var c=void 0,l=new DataView(a.buffer),v=function(){return l.buffer===a.buffer?l:l=new DataView(a.buffer)},p=0;p>>=0;var E=v().getUint32(i+28,!0);if(y)c=H.UTF8ToString(y,-1);else{if(!g)return s.setLastError(4);if("string"!=typeof(c=d.handleStore.get(g).value)&&"symbol"!=typeof c)return s.setLastError(4)}te(s,u,c,w,b,h,_,o,E)}return s.getReturnStatus()}catch(e){return s.tryCatch.setError(e),s.setLastError(10)}},napi_delete_element:function(e,r,t,n){var i;if(!e)return 1;var o=d.envStore.get(e);if(o.checkGCAccess(),!o.tryCatch.isEmpty())return o.setLastError(10);if(!o.canCallIntoJs())return o.setLastError(o.moduleApiVersion>=10?23:10);o.clearLastError();try{if(!r)return o.setLastError(1);var s=d.handleStore.get(r);if(!s.isObject()&&!s.isFunction())return o.setLastError(2);if(d.feature.supportReflect)i=Reflect.deleteProperty(s.value,t>>>0);else try{i=delete s.value[t>>>0]}catch(e){i=!1}if(n){n>>>=0;var f=new DataView(a.buffer);(f.buffer===a.buffer?f:f=new DataView(a.buffer)).setInt8(n,i?1:0,!0)}return o.getReturnStatus()}catch(e){return o.tryCatch.setError(e),o.setLastError(10)}},napi_delete_property:function(e,r,t,n){var i;if(!e)return 1;var o=d.envStore.get(e);if(o.checkGCAccess(),!o.tryCatch.isEmpty())return o.setLastError(10);if(!o.canCallIntoJs())return o.setLastError(o.moduleApiVersion>=10?23:10);o.clearLastError();try{if(!t)return o.setLastError(1);if(!r)return o.setLastError(1);var s=d.handleStore.get(r);if(!s.isObject()&&!s.isFunction())return o.setLastError(2);var f=d.handleStore.get(t).value;if(d.feature.supportReflect)i=Reflect.deleteProperty(s.value,f);else try{i=delete s.value[f]}catch(e){i=!1}if(n){n>>>=0;var u=new DataView(a.buffer);(u.buffer===a.buffer?u:u=new DataView(a.buffer)).setInt8(n,i?1:0,!0)}return o.getReturnStatus()}catch(e){return o.tryCatch.setError(e),o.setLastError(10)}},napi_get_all_property_names:Le,napi_get_element:function(e,r,t,n){var i;if(!e)return 1;var o=d.envStore.get(e);if(o.checkGCAccess(),!o.tryCatch.isEmpty())return o.setLastError(10);if(!o.canCallIntoJs())return o.setLastError(o.moduleApiVersion>=10?23:10);o.clearLastError();try{if(!n)return o.setLastError(1);if(!r)return o.setLastError(1);var s=d.handleStore.get(r);if(null==s.value)throw new TypeError("Cannot convert undefined or null to object");var f=void 0;try{f=s.isObject()||s.isFunction()?s.value:Object(s.value)}catch(e){return o.setLastError(2)}n>>>=0,i=o.ensureHandleId(f[t>>>0]);var u=new DataView(a.buffer);return(u.buffer===a.buffer?u:u=new DataView(a.buffer)).setUint32(n,i,!0),o.getReturnStatus()}catch(e){return o.tryCatch.setError(e),o.setLastError(10)}},napi_get_named_property:function(e,r,t,n){var i;if(!e)return 1;var o=d.envStore.get(e);if(o.checkGCAccess(),!o.tryCatch.isEmpty())return o.setLastError(10);if(!o.canCallIntoJs())return o.setLastError(o.moduleApiVersion>=10?23:10);o.clearLastError();try{if(!n)return o.setLastError(1);if(!r)return o.setLastError(1);if(!t)return o.setLastError(1);var s=d.handleStore.get(r);if(null==s.value)throw new TypeError("Cannot convert undefined or null to object");var f=void 0;try{f=s.isObject()||s.isFunction()?s.value:Object(s.value)}catch(e){return o.setLastError(2)}t>>>=0,n>>>=0,i=o.ensureHandleId(f[H.UTF8ToString(t,-1)]);var u=new DataView(a.buffer);return(u.buffer===a.buffer?u:u=new DataView(a.buffer)).setUint32(n,i,!0),o.getReturnStatus()}catch(e){return o.tryCatch.setError(e),o.setLastError(10)}},napi_get_property:function(e,r,t,n){var i;if(!e)return 1;var o=d.envStore.get(e);if(o.checkGCAccess(),!o.tryCatch.isEmpty())return o.setLastError(10);if(!o.canCallIntoJs())return o.setLastError(o.moduleApiVersion>=10?23:10);o.clearLastError();try{if(!t)return o.setLastError(1);if(!n)return o.setLastError(1);if(!r)return o.setLastError(1);var s=d.handleStore.get(r);if(null==s.value)throw new TypeError("Cannot convert undefined or null to object");var f=void 0;try{f=s.isObject()||s.isFunction()?s.value:Object(s.value)}catch(e){return o.setLastError(2)}n>>>=0,i=o.ensureHandleId(f[d.handleStore.get(t).value]);var u=new DataView(a.buffer);return(u.buffer===a.buffer?u:u=new DataView(a.buffer)).setUint32(n,i,!0),o.getReturnStatus()}catch(e){return o.tryCatch.setError(e),o.setLastError(10)}},napi_get_property_names:function(e,r,t){return Le(e,r,0,18,1,t)},napi_has_element:function(e,r,t,n){var i;if(!e)return 1;var o=d.envStore.get(e);if(o.checkGCAccess(),!o.tryCatch.isEmpty())return o.setLastError(10);if(!o.canCallIntoJs())return o.setLastError(o.moduleApiVersion>=10?23:10);o.clearLastError();try{if(!n)return o.setLastError(1);if(!r)return o.setLastError(1);var s=d.handleStore.get(r);if(null==s.value)throw new TypeError("Cannot convert undefined or null to object");var f=void 0;try{f=s.isObject()||s.isFunction()?s.value:Object(s.value)}catch(e){return o.setLastError(2)}n>>>=0,i=t>>>0 in f?1:0;var u=new DataView(a.buffer);return(u.buffer===a.buffer?u:u=new DataView(a.buffer)).setInt8(n,i,!0),o.getReturnStatus()}catch(e){return o.tryCatch.setError(e),o.setLastError(10)}},napi_has_named_property:function(e,r,t,n){var i;if(!e)return 1;var o=d.envStore.get(e);if(o.checkGCAccess(),!o.tryCatch.isEmpty())return o.setLastError(10);if(!o.canCallIntoJs())return o.setLastError(o.moduleApiVersion>=10?23:10);o.clearLastError();try{if(!n)return o.setLastError(1);if(!r)return o.setLastError(1);if(!t)return o.setLastError(1);var s=d.handleStore.get(r);if(null==s.value)throw new TypeError("Cannot convert undefined or null to object");var f=void 0;try{f=s.isObject()||s.isFunction()?s.value:Object(s.value)}catch(e){return o.setLastError(2)}t>>>=0,n>>>=0,i=H.UTF8ToString(t,-1)in f;var u=new DataView(a.buffer);return(u.buffer===a.buffer?u:u=new DataView(a.buffer)).setInt8(n,i?1:0,!0),o.getReturnStatus()}catch(e){return o.tryCatch.setError(e),o.setLastError(10)}},napi_has_own_property:function(e,r,t,n){var i;if(!e)return 1;var o=d.envStore.get(e);if(o.checkGCAccess(),!o.tryCatch.isEmpty())return o.setLastError(10);if(!o.canCallIntoJs())return o.setLastError(o.moduleApiVersion>=10?23:10);o.clearLastError();try{if(!t)return o.setLastError(1);if(!n)return o.setLastError(1);if(!r)return o.setLastError(1);var s=d.handleStore.get(r);if(null==s.value)throw new TypeError("Cannot convert undefined or null to object");var f=void 0;try{f=s.isObject()||s.isFunction()?s.value:Object(s.value)}catch(e){return o.setLastError(2)}var u=d.handleStore.get(t).value;if("string"!=typeof u&&"symbol"!=typeof u)return o.setLastError(4);i=Object.prototype.hasOwnProperty.call(f,d.handleStore.get(t).value),n>>>=0;var c=new DataView(a.buffer);return(c.buffer===a.buffer?c:c=new DataView(a.buffer)).setInt8(n,i?1:0,!0),o.getReturnStatus()}catch(e){return o.tryCatch.setError(e),o.setLastError(10)}},napi_has_property:function(e,r,t,n){var i;if(!e)return 1;var o=d.envStore.get(e);if(o.checkGCAccess(),!o.tryCatch.isEmpty())return o.setLastError(10);if(!o.canCallIntoJs())return o.setLastError(o.moduleApiVersion>=10?23:10);o.clearLastError();try{if(!t)return o.setLastError(1);if(!n)return o.setLastError(1);if(!r)return o.setLastError(1);var s=d.handleStore.get(r);if(null==s.value)throw new TypeError("Cannot convert undefined or null to object");var f=void 0;try{f=s.isObject()||s.isFunction()?s.value:Object(s.value)}catch(e){return o.setLastError(2)}n>>>=0,i=d.handleStore.get(t).value in f?1:0;var u=new DataView(a.buffer);return(u.buffer===a.buffer?u:u=new DataView(a.buffer)).setInt8(n,i,!0),o.getReturnStatus()}catch(e){return o.tryCatch.setError(e),o.setLastError(10)}},napi_object_freeze:function(e,r){if(!e)return 1;var t=d.envStore.get(e);if(t.checkGCAccess(),!t.tryCatch.isEmpty())return t.setLastError(10);if(!t.canCallIntoJs())return t.setLastError(t.moduleApiVersion>=10?23:10);t.clearLastError();try{if(!r)return t.setLastError(1);var n=d.handleStore.get(r),a=n.value;return n.isObject()||n.isFunction()?(Object.freeze(a),t.getReturnStatus()):t.setLastError(2)}catch(e){return t.tryCatch.setError(e),t.setLastError(10)}},napi_object_seal:function(e,r){if(!e)return 1;var t=d.envStore.get(e);if(t.checkGCAccess(),!t.tryCatch.isEmpty())return t.setLastError(10);if(!t.canCallIntoJs())return t.setLastError(t.moduleApiVersion>=10?23:10);t.clearLastError();try{if(!r)return t.setLastError(1);var n=d.handleStore.get(r),a=n.value;return n.isObject()||n.isFunction()?(Object.seal(a),t.getReturnStatus()):t.setLastError(2)}catch(e){return t.tryCatch.setError(e),t.setLastError(10)}},napi_set_element:function(e,r,t,n){if(!e)return 1;var a=d.envStore.get(e);if(a.checkGCAccess(),!a.tryCatch.isEmpty())return a.setLastError(10);if(!a.canCallIntoJs())return a.setLastError(a.moduleApiVersion>=10?23:10);a.clearLastError();try{if(!n)return a.setLastError(1);if(!r)return a.setLastError(1);var i=d.handleStore.get(r);return i.isObject()||i.isFunction()?(i.value[t>>>0]=d.handleStore.get(n).value,a.getReturnStatus()):a.setLastError(2)}catch(e){return a.tryCatch.setError(e),a.setLastError(10)}},napi_set_named_property:function(e,r,t,n){if(!e)return 1;var a=d.envStore.get(e);if(a.checkGCAccess(),!a.tryCatch.isEmpty())return a.setLastError(10);if(!a.canCallIntoJs())return a.setLastError(a.moduleApiVersion>=10?23:10);a.clearLastError();try{if(!n)return a.setLastError(1);if(!r)return a.setLastError(1);var i=d.handleStore.get(r);return i.isObject()||i.isFunction()?t?(t>>>=0,d.handleStore.get(r).value[H.UTF8ToString(t,-1)]=d.handleStore.get(n).value,a.getReturnStatus()):a.setLastError(1):a.setLastError(2)}catch(e){return a.tryCatch.setError(e),a.setLastError(10)}},napi_set_property:function(e,r,t,n){if(!e)return 1;var a=d.envStore.get(e);if(a.checkGCAccess(),!a.tryCatch.isEmpty())return a.setLastError(10);if(!a.canCallIntoJs())return a.setLastError(a.moduleApiVersion>=10?23:10);a.clearLastError();try{if(!t)return a.setLastError(1);if(!n)return a.setLastError(1);if(!r)return a.setLastError(1);var i=d.handleStore.get(r);return i.isObject()||i.isFunction()?(i.value[d.handleStore.get(t).value]=d.handleStore.get(n).value,a.getReturnStatus()):a.setLastError(2)}catch(e){return a.tryCatch.setError(e),a.setLastError(10)}}});var Se=Object.freeze({__proto__:null,napi_run_script:function(e,r,t){var n,i;if(!e)return 1;var o=d.envStore.get(e);if(o.checkGCAccess(),!o.tryCatch.isEmpty())return o.setLastError(10);if(!o.canCallIntoJs())return o.setLastError(o.moduleApiVersion>=10?23:10);o.clearLastError();try{if(!r)return o.setLastError(1);if(!t)return o.setLastError(1);var s=d.handleStore.get(r);if(!s.isString())return o.setLastError(3);var f=d.handleStore.get(5).value.eval(s.value);t>>>=0,i=o.ensureHandleId(f);var u=new DataView(a.buffer);(u.buffer===a.buffer?u:u=new DataView(a.buffer)).setUint32(t,i,!0),n=o.getReturnStatus()}catch(e){return o.tryCatch.setError(e),o.setLastError(10)}return n}});var Ae=Object.freeze({__proto__:null,napi_coerce_to_bool:function(e,r,t){var n;if(!e)return 1;var i=d.envStore.get(e);if(i.checkGCAccess(),!i.tryCatch.isEmpty())return i.setLastError(10);if(!i.canCallIntoJs())return i.setLastError(i.moduleApiVersion>=10?23:10);i.clearLastError();try{if(!r)return i.setLastError(1);if(!t)return i.setLastError(1);var o=d.handleStore.get(r);t>>>=0,n=o.value?4:3;var s=new DataView(a.buffer);return(s.buffer===a.buffer?s:s=new DataView(a.buffer)).setUint32(t,n,!0),i.getReturnStatus()}catch(e){return i.tryCatch.setError(e),i.setLastError(10)}},napi_coerce_to_number:function(e,r,t){var n;if(!e)return 1;var i=d.envStore.get(e);if(i.checkGCAccess(),!i.tryCatch.isEmpty())return i.setLastError(10);if(!i.canCallIntoJs())return i.setLastError(i.moduleApiVersion>=10?23:10);i.clearLastError();try{if(!r)return i.setLastError(1);if(!t)return i.setLastError(1);var o=d.handleStore.get(r);if(o.isBigInt())throw new TypeError("Cannot convert a BigInt value to a number");t>>>=0,n=d.addToCurrentScope(Number(o.value)).id;var s=new DataView(a.buffer);return(s.buffer===a.buffer?s:s=new DataView(a.buffer)).setUint32(t,n,!0),i.getReturnStatus()}catch(e){return i.tryCatch.setError(e),i.setLastError(10)}},napi_coerce_to_object:function(e,r,t){var n;if(!e)return 1;var i=d.envStore.get(e);if(i.checkGCAccess(),!i.tryCatch.isEmpty())return i.setLastError(10);if(!i.canCallIntoJs())return i.setLastError(i.moduleApiVersion>=10?23:10);i.clearLastError();try{if(!r)return i.setLastError(1);if(!t)return i.setLastError(1);var o=d.handleStore.get(r);if(null==o.value)throw new TypeError("Cannot convert undefined or null to object");t>>>=0,n=i.ensureHandleId(Object(o.value));var s=new DataView(a.buffer);return(s.buffer===a.buffer?s:s=new DataView(a.buffer)).setUint32(t,n,!0),i.getReturnStatus()}catch(e){return i.tryCatch.setError(e),i.setLastError(10)}},napi_coerce_to_string:function(e,r,t){var n;if(!e)return 1;var i=d.envStore.get(e);if(i.checkGCAccess(),!i.tryCatch.isEmpty())return i.setLastError(10);if(!i.canCallIntoJs())return i.setLastError(i.moduleApiVersion>=10?23:10);i.clearLastError();try{if(!r)return i.setLastError(1);if(!t)return i.setLastError(1);var o=d.handleStore.get(r);if(o.isSymbol())throw new TypeError("Cannot convert a Symbol value to a string");t>>>=0,n=d.addToCurrentScope(String(o.value)).id;var s=new DataView(a.buffer);return(s.buffer===a.buffer?s:s=new DataView(a.buffer)).setUint32(t,n,!0),i.getReturnStatus()}catch(e){return i.tryCatch.setError(e),i.setLastError(10)}},napi_detach_arraybuffer:function(e,r){if(!e)return 1;var t=d.envStore.get(e);if(t.checkGCAccess(),!r)return t.setLastError(1);var n=d.handleStore.get(r).value;if(!(n instanceof ArrayBuffer))return"function"==typeof SharedArrayBuffer&&n instanceof SharedArrayBuffer?t.setLastError(20):t.setLastError(19);try{(new(0,d.feature.MessageChannel)).port1.postMessage(n,[n])}catch(e){return t.setLastError(9)}return t.clearLastError()},napi_instanceof:function(e,r,t,n){var i;if(!e)return 1;var o=d.envStore.get(e);if(o.checkGCAccess(),!o.tryCatch.isEmpty())return o.setLastError(10);if(!o.canCallIntoJs())return o.setLastError(o.moduleApiVersion>=10?23:10);o.clearLastError();try{if(!r)return o.setLastError(1);if(!n)return o.setLastError(1);if(!t)return o.setLastError(1);n>>>=0;var s=new DataView(a.buffer),f=function(){return s.buffer===a.buffer?s:s=new DataView(a.buffer)};f().setInt8(n,0,!0);var u=d.handleStore.get(t);return u.isFunction()?(i=d.handleStore.get(r).value instanceof u.value?1:0,f().setInt8(n,i,!0),o.getReturnStatus()):o.setLastError(5)}catch(e){return o.tryCatch.setError(e),o.setLastError(10)}},napi_is_array:function(e,r,t){if(!e)return 1;var n=d.envStore.get(e);if(n.checkGCAccess(),!r)return n.setLastError(1);if(!t)return n.setLastError(1);t>>>=0;var i=d.handleStore.get(r).isArray()?1:0,o=new DataView(a.buffer);return(o.buffer===a.buffer?o:o=new DataView(a.buffer)).setInt8(t,i,!0),n.clearLastError()},napi_is_arraybuffer:function(e,r,t){if(!e)return 1;var n=d.envStore.get(e);if(n.checkGCAccess(),!r)return n.setLastError(1);if(!t)return n.setLastError(1);t>>>=0;var i=d.handleStore.get(r).isArrayBuffer()?1:0,o=new DataView(a.buffer);return(o.buffer===a.buffer?o:o=new DataView(a.buffer)).setInt8(t,i,!0),n.clearLastError()},napi_is_buffer:function(e,r,t){if(!e)return 1;var n=d.envStore.get(e);if(n.checkGCAccess(),!r)return n.setLastError(1);if(!t)return n.setLastError(1);t>>>=0;var i=d.handleStore.get(r).isBuffer(d.feature.Buffer)?1:0,o=new DataView(a.buffer);return(o.buffer===a.buffer?o:o=new DataView(a.buffer)).setInt8(t,i,!0),n.clearLastError()},napi_is_dataview:function(e,r,t){if(!e)return 1;var n=d.envStore.get(e);if(n.checkGCAccess(),!r)return n.setLastError(1);if(!t)return n.setLastError(1);t>>>=0;var i=d.handleStore.get(r).isDataView()?1:0,o=new DataView(a.buffer);return(o.buffer===a.buffer?o:o=new DataView(a.buffer)).setInt8(t,i,!0),n.clearLastError()},napi_is_date:function(e,r,t){if(!e)return 1;var n=d.envStore.get(e);if(n.checkGCAccess(),!r)return n.setLastError(1);if(!t)return n.setLastError(1);t>>>=0;var i=d.handleStore.get(r).isDate()?1:0,o=new DataView(a.buffer);return(o.buffer===a.buffer?o:o=new DataView(a.buffer)).setInt8(t,i,!0),n.clearLastError()},napi_is_detached_arraybuffer:function(e,r,t){if(!e)return 1;var n=d.envStore.get(e);if(n.checkGCAccess(),!n.tryCatch.isEmpty())return n.setLastError(10);if(!n.canCallIntoJs())return n.setLastError(n.moduleApiVersion>=10?23:10);n.clearLastError();try{if(!r)return n.setLastError(1);if(!t)return n.setLastError(1);var i=d.handleStore.get(r);t>>>=0;var o=new DataView(a.buffer),s=function(){return o.buffer===a.buffer?o:o=new DataView(a.buffer)};if(i.isArrayBuffer()&&0===i.value.byteLength)try{new Uint8Array(i.value)}catch(e){return s().setInt8(t,1,!0),n.getReturnStatus()}return s().setInt8(t,0,!0),n.getReturnStatus()}catch(e){return n.tryCatch.setError(e),n.setLastError(10)}},napi_is_error:function(e,r,t){if(!e)return 1;var n=d.envStore.get(e);if(n.checkGCAccess(),!r)return n.setLastError(1);if(!t)return n.setLastError(1);t>>>=0;var i=d.handleStore.get(r).value instanceof Error?1:0,o=new DataView(a.buffer);return(o.buffer===a.buffer?o:o=new DataView(a.buffer)).setInt8(t,i,!0),n.clearLastError()},napi_is_typedarray:function(e,r,t){if(!e)return 1;var n=d.envStore.get(e);if(n.checkGCAccess(),!r)return n.setLastError(1);if(!t)return n.setLastError(1);t>>>=0;var i=d.handleStore.get(r).isTypedArray()?1:0,o=new DataView(a.buffer);return(o.buffer===a.buffer?o:o=new DataView(a.buffer)).setInt8(t,i,!0),n.clearLastError()},napi_strict_equals:function(e,r,t,n){var i;if(!e)return 1;var o=d.envStore.get(e);if(o.checkGCAccess(),!o.tryCatch.isEmpty())return o.setLastError(10);if(!o.canCallIntoJs())return o.setLastError(o.moduleApiVersion>=10?23:10);o.clearLastError();try{if(!r)return o.setLastError(1);if(!t)return o.setLastError(1);if(!n)return o.setLastError(1);var s=d.handleStore.get(r).value,f=d.handleStore.get(t).value;n>>>=0,i=s===f?1:0;var u=new DataView(a.buffer);return(u.buffer===a.buffer?u:u=new DataView(a.buffer)).setInt8(n,i,!0),o.getReturnStatus()}catch(e){return o.tryCatch.setError(e),o.setLastError(10)}},napi_typeof:function(e,r,t){if(!e)return 1;var n=d.envStore.get(e);if(n.checkGCAccess(),!r)return n.setLastError(1);if(!t)return n.setLastError(1);var i,o=d.handleStore.get(r);if(t>>>=0,o.isNumber())i=3;else if(o.isBigInt())i=9;else if(o.isString())i=4;else if(o.isFunction())i=7;else if(o.isExternal())i=8;else if(o.isObject())i=6;else if(o.isBoolean())i=2;else if(o.isUndefined())i=0;else if(o.isSymbol())i=5;else{if(!o.isNull())return n.setLastError(1);i=1}var s=new DataView(a.buffer);return(s.buffer===a.buffer?s:s=new DataView(a.buffer)).setInt32(t,i,!0),n.clearLastError()},node_api_is_sharedarraybuffer:function(e,r,t){if(!e)return 1;var n=d.envStore.get(e);if(n.checkGCAccess(),!r)return n.setLastError(1);if(!t)return n.setLastError(1);var i=d.handleStore.get(r);t>>>=0;var o="function"==typeof SharedArrayBuffer&&i.value instanceof SharedArrayBuffer||"[object SharedArrayBuffer]"===Object.prototype.toString.call(i.value)?1:0,s=new DataView(a.buffer);return(s.buffer===a.buffer?s:s=new DataView(a.buffer)).setInt8(t,o,!0),n.clearLastError()}});var Ce=Object.freeze({__proto__:null,napi_get_version:function(e,r){if(!e)return 1;var t=d.envStore.get(e);if(!r)return t.setLastError(1);var n=new DataView(a.buffer);return(n.buffer===a.buffer?n:n=new DataView(a.buffer)).setUint32(r,10,!0),t.clearLastError()}});function Ve(e){for(var r=Object.keys(e),t=0;t>>=0,f>>>=0,e>>>=0,u>>>=0,c>>>=0,l>>>=0,v>>>=0,i>>>=0,0===(f>>>=0))return y.setLastError(1);if(!p)return y.setLastError(1);var g,w=0;if(r>>>=0){if("function"!=typeof d.handleStore.get(r).value)return y.setLastError(1);w=d.createReference(y,r,1,1).id}else if(!v)return y.setLastError(1);if(t){if(null==(g=d.handleStore.get(t).value))return y.setLastError(2);g=Object(g)}else g={};var b=y.ensureHandleId(g),h=d.handleStore.get(n).value;if("symbol"==typeof h)return y.setLastError(3);h=String(h);var _=y.ensureHandleId(h),E=R.offset.__size__,L=o(E);if(!L)return y.setLastError(9);L>>>=0,new Uint8Array(R.ensureBufferFor(L+E)).subarray(L,L+E).fill(0);var m=d.createReference(y,b,1,1),S=m.id,A=new DataView(a.buffer),C=function(){return A.buffer===a.buffer?A:A=new DataView(a.buffer)};return C().setUint32(L+R.offset.resource,S,!0),R.initQueue(L)?(O(b,_,-1,L+R.offset.async_id),C().setInt8(L+R.offset.is_some,1,!0),C().setUint32(L+R.offset.thread_count,f,!0),C().setUint32(L+R.offset.context,l,!0),C().setUint32(L+R.offset.max_queue_size,i,!0),C().setUint32(L+R.offset.ref,w,!0),C().setUint32(L+R.offset.env,e,!0),C().setUint32(L+R.offset.finalize_data,u,!0),C().setUint32(L+R.offset.finalize_cb,c,!0),C().setUint32(L+R.offset.call_js_cb,v,!0),d.addCleanupHook(y,R.cleanup,L),R._liveSet.add(L),y.ref(),d.increaseWaitingRequestCounter(),C().setUint32(L+R.offset.async_ref,1,!0),p>>>=0,C().setUint32(p,L,!0),y.clearLastError()):(s(L),m.dispose(),y.setLastError(9))},y.imports.napi.napi_get_threadsafe_function_context=function(e,r){if(!e||!r)return l(),1;e>>>=0,r>>>=0;var t=R.getContext(e),n=new DataView(a.buffer);return(n.buffer===a.buffer?n:n=new DataView(a.buffer)).setUint32(r,t,!0),0},y.imports.napi.napi_call_threadsafe_function=function(e,r,t){return e?(e>>>=0,r>>>=0,R.push(e,r,t)):(l(),1)},y.imports.napi.napi_acquire_threadsafe_function=function(e){return e?(e>>>=0,R.getMutex(e).execute(function(){return 0===R.getState(e)?(R.addThreadCount(e),0):16})):(l(),1)},y.imports.napi.napi_release_threadsafe_function=function(e,r){if(!e)return l(),1;e>>>=0;var t=R.getMutex(e),n=R.getCond(e),a=!1,i=t.execute(function(){return 0===R.getThreadCount(e)?1:(R.subThreadCount(e),0!==R.getThreadCount(e)&&1!==r||0===R.getState(e)&&(1===r&&R.setState(e,1),1===R.getState(e)&&R.getMaxQueueSize(e)>0&&n.signal(),R.send(e)),2!==R.getState(e)||0!==R.getThreadCount(e)||(a=!0),0)});return a&&R.destroy(e),i},y.imports.napi.napi_unref_threadsafe_function=function(e,r){if(!r)return l(),1;var t=(r>>>=0)+R.offset.async_ref,n=t>>>2,a=new Uint32Array(R.ensureBufferFor(t+4)),i=Atomics.load(a,n);return i>0&&(Atomics.store(a,n,i-1),1===i&&d.decreaseWaitingRequestCounter()),0},y.imports.napi.napi_ref_threadsafe_function=function(e,r){if(!r)return l(),1;var t=(r>>>=0)+R.offset.async_ref,n=t>>>2,a=new Uint32Array(R.ensureBufferFor(t+4)),i=Atomics.load(a,n);return i||d.increaseWaitingRequestCounter(),Atomics.store(a,n,i+1),0},y}();return t}function s(e,t,n,a){const i=(a=null!=a?a:{}).getMemory,s=a.getTable,u=a.beforeInit;if(null!=i&&"function"!=typeof i)throw new TypeError("options.getMemory is not a function");if(null!=s&&"function"!=typeof s)throw new TypeError("options.getTable is not a function");if(null!=u&&"function"!=typeof u)throw new TypeError("options.beforeInit is not a function");let c;const l="object"==typeof t&&null!==t;if(l){if(t.loaded)throw new Error("napiModule has already loaded");c=t}else c=o(a);const d=a.wasi;let v,p={env:c.imports.env,napi:c.imports.napi,emnapi:c.imports.emnapi};d&&(v=new r(c.childThread?{wasi:d,childThread:!0,postMessage:c.postMessage}:{wasi:d,threadManager:c.PThread,waitThreadStart:c.waitThreadStart}),Object.assign(p,"function"==typeof d.getImportObject?d.getImportObject():{wasi_snapshot_preview1:d.wasiImport}),Object.assign(p,v.getImportObject()));const y=a.overwriteImports;if("function"==typeof y){const e=y(p);"object"==typeof e&&null!==e&&(p=e)}return e(n,p,(r,t)=>{if(r)throw r;const n=t.instance;let a=n;const o=n.exports,y="memory"in o,g="memory"in p.env,w=i?i(o):y?o.memory:g?p.env.memory:void 0;if(!w)throw new Error("memory is neither exported nor imported");const b=s?s(o):o.__indirect_function_table;if(d&&!y){const e=Object.create(null);Object.assign(e,o,{memory:w}),a={exports:e}}const h=t.module;d?a=v.initialize(a,h,w):c.PThread.setup(h,w);const _=()=>{u&&u({instance:n,module:h}),c.init({instance:a,module:h,memory:w,table:b});const e={instance:n,module:h,usedInstance:a};return l||(e.napiModule=c),e};if(c.PThread.shouldPreloadWorkers()){const r=c.PThread.loadWasmModuleToAllWorkers();if(e===f)return r.then(_);throw new Error("Synchronous loading is not supported with worker pool (reuseWorker.size > 0)")}return _()})}function f(e,r,t){return i(e,r).then(e=>t(null,e),e=>t(e))}function u(e,r,t){let i;try{i=function(e,r){if(!e)throw new TypeError("Invalid wasm source");let t;if(a(r),r=null!=r?r:{},e instanceof ArrayBuffer||ArrayBuffer.isView(e))t=new n.Module(e);else{if(!(e instanceof WebAssembly.Module))throw new TypeError("Invalid wasm source");t=e}return{instance:new n.Instance(t,r),module:t}}(e,r)}catch(e){return t(e)}return t(null,i)}function c(e,r,t){if("object"!=typeof e||null===e)throw new TypeError("Invalid napiModule");return s(f,e,r,t)}function l(e,r,t){if("object"!=typeof e||null===e)throw new TypeError("Invalid napiModule");return s(u,e,r,t)}function d(e,r){return s(f,void 0,e,r)}function v(e,r){return s(u,void 0,e,r)}class p extends t{constructor(e){if("function"!=typeof e.onLoad)throw new TypeError("options.onLoad is not a function");const r=e.onError;super({...e,onError:(e,t)=>{var n;const a=null===(n=this.instance)||void 0===n?void 0:n.exports.emnapi_thread_crashed;if("function"==typeof a&&a(),"function"!=typeof r)throw e;r(e,t)}}),this.napiModule=void 0}instantiate(e){const r=this.onLoad(e);return"function"==typeof r.then?r.then(e=>(this.napiModule=e.napiModule,e)):(this.napiModule=r.napiModule,r)}handle(e){var r;if(super.handle(e),null===(r=null==e?void 0:e.data)||void 0===r?void 0:r.__emnapi__){const r=e.data.__emnapi__.type,t=e.data.__emnapi__.payload;try{"async-worker-init"===r&&this.handleAfterLoad(e,()=>{this.napiModule.initWorker(t.arg,t.func)})}catch(e){this.onError(e,r)}}}}const y="1.11.3";export{p as MessageHandler,o as createNapiModule,d as instantiateNapiModule,v as instantiateNapiModuleSync,c as loadNapiModule,l as loadNapiModuleSync,y as version}; diff --git a/dg-ui/node_modules/@tailwindcss/oxide-wasm32-wasi/node_modules/@emnapi/core/dist/emnapi-core.mjs b/dg-ui/node_modules/@tailwindcss/oxide-wasm32-wasi/node_modules/@emnapi/core/dist/emnapi-core.mjs new file mode 100644 index 0000000..e948976 --- /dev/null +++ b/dg-ui/node_modules/@tailwindcss/oxide-wasm32-wasi/node_modules/@emnapi/core/dist/emnapi-core.mjs @@ -0,0 +1,7735 @@ +import { ThreadManager, WASIThreads, ThreadMessageHandler } from '@emnapi/wasi-threads'; +export * from '@emnapi/wasi-threads'; + +const _WebAssembly = typeof WebAssembly !== 'undefined' + ? WebAssembly + : typeof WXWebAssembly !== 'undefined' + ? WXWebAssembly + : undefined; +function validateImports(imports) { + if (imports && typeof imports !== 'object') { + throw new TypeError('imports must be an object or undefined'); + } + return true; +} +function load(wasmInput, imports) { + if (!wasmInput) + throw new TypeError('Invalid wasm source'); + validateImports(imports); + imports = imports !== null && imports !== void 0 ? imports : {}; + try { + const then = typeof wasmInput === 'object' && wasmInput !== null && 'then' in wasmInput ? wasmInput.then : undefined; + if (typeof then === 'function') { + return then.call(wasmInput, (input) => load(input, imports)); + } + } + catch (_) { } + if (wasmInput instanceof ArrayBuffer || ArrayBuffer.isView(wasmInput)) { + return _WebAssembly.instantiate(wasmInput, imports); + } + if (wasmInput instanceof _WebAssembly.Module) { + return _WebAssembly.instantiate(wasmInput, imports).then((instance) => { + return { instance, module: wasmInput }; + }); + } + if (typeof Response !== 'undefined' && wasmInput instanceof Response) { + return wasmInput.arrayBuffer().then(buffer => { + return _WebAssembly.instantiate(buffer, imports); + }); + } + const inputIsString = typeof wasmInput === 'string'; + if (inputIsString || (typeof URL !== 'undefined' && wasmInput instanceof URL)) { + if (inputIsString && typeof wx !== 'undefined' && typeof __wxConfig !== 'undefined') { + return _WebAssembly.instantiate(wasmInput, imports); + } + if (typeof fetch !== 'function') { + throw new TypeError('wasm source can not be a string or URL in this environment'); + } + if (typeof _WebAssembly.instantiateStreaming === 'function') { + try { + return _WebAssembly.instantiateStreaming(fetch(wasmInput), imports).catch(() => { + return load(fetch(wasmInput), imports); + }); + } + catch (_) { + return load(fetch(wasmInput), imports); + } + } + else { + return load(fetch(wasmInput), imports); + } + } + throw new TypeError('Invalid wasm source'); +} +function loadSync(wasmInput, imports) { + if (!wasmInput) + throw new TypeError('Invalid wasm source'); + validateImports(imports); + imports = imports !== null && imports !== void 0 ? imports : {}; + let module; + if ((wasmInput instanceof ArrayBuffer) || ArrayBuffer.isView(wasmInput)) { + module = new _WebAssembly.Module(wasmInput); + } + else if (wasmInput instanceof WebAssembly.Module) { + module = wasmInput; + } + else { + throw new TypeError('Invalid wasm source'); + } + const instance = new _WebAssembly.Instance(module, imports); + const source = { instance, module }; + return source; +} + +function createNapiModule(options) { + var napiModule = (function () { + var ENVIRONMENT_IS_NODE = typeof process === 'object' && process !== null && typeof process.versions === 'object' && process.versions !== null && typeof process.versions.node === 'string'; + var ENVIRONMENT_IS_PTHREAD = Boolean(options.childThread); + var waitThreadStart = typeof options.waitThreadStart === 'number' ? options.waitThreadStart : Boolean(options.waitThreadStart); + var wasmInstance; + var wasmMemory; + var wasmTable; + var _malloc; + var _free; + function abort(msg) { + if (typeof _WebAssembly.RuntimeError === 'function') { + throw new _WebAssembly.RuntimeError(msg); + } + throw Error(msg); + } + var napiModule = { + imports: { + env: {}, + napi: {}, + emnapi: {} + }, + exports: {}, + emnapi: {}, + loaded: false, + filename: '', + childThread: ENVIRONMENT_IS_PTHREAD, + initWorker: undefined, + waitThreadStart: waitThreadStart, + PThread: undefined, + init: function (options) { + if (napiModule.loaded) + return napiModule.exports; + if (!options) + throw new TypeError('Invalid napi init options'); + var instance = options.instance; + if (!(instance === null || instance === void 0 ? void 0 : instance.exports)) + throw new TypeError('Invalid wasm instance'); + wasmInstance = instance; + var exports = instance.exports; + var module = options.module; + var memory = options.memory || exports.memory; + var table = options.table || exports.__indirect_function_table; + if (!(module instanceof _WebAssembly.Module)) + throw new TypeError('Invalid wasm module'); + if (!(memory instanceof _WebAssembly.Memory)) + throw new TypeError('Invalid wasm memory'); + if (!(table instanceof _WebAssembly.Table)) + throw new TypeError('Invalid wasm table'); + wasmMemory = memory; + wasmTable = table; + if (typeof exports.malloc !== 'function') + throw new TypeError('malloc is not exported'); + if (typeof exports.free !== 'function') + throw new TypeError('free is not exported'); + _malloc = exports.malloc; + _free = exports.free; + if (!napiModule.childThread) { + var moduleApiVersion = 8; + var node_api_module_get_api_version_v1 = instance.exports.node_api_module_get_api_version_v1; + if (typeof node_api_module_get_api_version_v1 === 'function') { + moduleApiVersion = node_api_module_get_api_version_v1(); + } + var envObject = napiModule.envObject || (napiModule.envObject = emnapiCtx.createEnv(napiModule.filename, moduleApiVersion, function (cb) { return (wasmTable.get(cb)); }, function (cb) { return (wasmTable.get(cb)); }, abort, emnapiNodeBinding)); + var scope_1 = emnapiCtx.openScope(envObject); + try { + envObject.callIntoModule(function (_envObject) { + var exports = napiModule.exports; + var exportsHandle = scope_1.add(exports); + var napi_register_wasm_v1 = instance.exports.napi_register_wasm_v1; + var napiValue = napi_register_wasm_v1(_envObject.id, exportsHandle.id); + napiModule.exports = (!napiValue) ? exports : emnapiCtx.handleStore.get(napiValue).value; + }); + } + catch (e) { + if (e !== 'unwind') { + throw e; + } + } + finally { + emnapiCtx.closeScope(envObject, scope_1); + } + napiModule.loaded = true; + delete napiModule.envObject; + return napiModule.exports; + } + } + }; + var emnapiCtx; + var emnapiNodeBinding; + var onCreateWorker = undefined; + var err; + if (!ENVIRONMENT_IS_PTHREAD) { + var context = options.context; + if (typeof context !== 'object' || context === null) { + throw new TypeError("Invalid `options.context`. Use `import { getDefaultContext } from '@emnapi/runtime'`"); + } + emnapiCtx = context; + } + else { + emnapiCtx = options === null || options === void 0 ? void 0 : options.context; + var postMsg = typeof options.postMessage === 'function' + ? options.postMessage + : typeof postMessage === 'function' + ? postMessage + : undefined; + if (typeof postMsg !== 'function') { + throw new TypeError('No postMessage found'); + } + napiModule.postMessage = postMsg; + } + if (typeof options.filename === 'string') { + napiModule.filename = options.filename; + } + if (typeof options.onCreateWorker === 'function') { + onCreateWorker = options.onCreateWorker; + } + if (typeof options.print === 'function') { + options.print; + } + else { + console.log.bind(console); + } + if (typeof options.printErr === 'function') { + err = options.printErr; + } + else { + err = console.warn.bind(console); + } + if ('nodeBinding' in options) { + var nodeBinding = options.nodeBinding; + if (typeof nodeBinding !== 'object' || nodeBinding === null) { + throw new TypeError('Invalid `options.nodeBinding`. Use @emnapi/node-binding package'); + } + emnapiNodeBinding = nodeBinding; + } + var emnapiAsyncWorkPoolSize = 0; + if ('asyncWorkPoolSize' in options) { + if (typeof options.asyncWorkPoolSize !== 'number') { + throw new TypeError('options.asyncWorkPoolSize must be a integer'); + } + emnapiAsyncWorkPoolSize = options.asyncWorkPoolSize >> 0; + if (emnapiAsyncWorkPoolSize > 1024) { + emnapiAsyncWorkPoolSize = 1024; + } + else if (emnapiAsyncWorkPoolSize < -1024) { + emnapiAsyncWorkPoolSize = -1024; + } + } + var singleThreadAsyncWork = ENVIRONMENT_IS_PTHREAD ? false : (emnapiAsyncWorkPoolSize <= 0); + function _emnapi_async_work_pool_size() { + return Math.abs(emnapiAsyncWorkPoolSize); + } + napiModule.imports.env._emnapi_async_work_pool_size = _emnapi_async_work_pool_size; + function emnapiAddSendListener(worker) { + if (!worker) + return false; + if (worker._emnapiSendListener) + return true; + var handler = function (e) { + var data = ENVIRONMENT_IS_NODE ? e : e.data; + var __emnapi__ = data.__emnapi__; + if (__emnapi__ && __emnapi__.type === 'async-send') { + if (ENVIRONMENT_IS_PTHREAD) { + var postMessage_1 = napiModule.postMessage; + postMessage_1({ __emnapi__: __emnapi__ }); + } + else { + var callback = __emnapi__.payload.callback; + (wasmTable.get(callback))(__emnapi__.payload.data); + } + } + }; + var dispose = function () { + if (ENVIRONMENT_IS_NODE) { + worker.off('message', handler); + } + else { + worker.removeEventListener('message', handler, false); + } + delete worker._emnapiSendListener; + }; + worker._emnapiSendListener = { handler: handler, dispose: dispose }; + if (ENVIRONMENT_IS_NODE) { + worker.on('message', handler); + } + else { + worker.addEventListener('message', handler, false); + } + return true; + } + napiModule.emnapi.addSendListener = emnapiAddSendListener; + var PThread = new ThreadManager(ENVIRONMENT_IS_PTHREAD + ? { + printErr: err, + childThread: true + } + : { + printErr: err, + beforeLoad: function (worker) { + emnapiAddSendListener(worker); + }, + reuseWorker: options.reuseWorker, + onCreateWorker: onCreateWorker + }); + napiModule.PThread = PThread; + function napi_set_last_error(env, error_code, engine_error_code, engine_reserved) { + var envObject = emnapiCtx.envStore.get(env); + return envObject.setLastError(error_code, engine_error_code, engine_reserved); + } + function napi_clear_last_error(env) { + var envObject = emnapiCtx.envStore.get(env); + return envObject.clearLastError(); + } + function _emnapi_get_node_version(major, minor, patch) { + major >>>= 0; + minor >>>= 0; + patch >>>= 0; + var versions = (typeof process === 'object' && process !== null && + typeof process.versions === 'object' && process.versions !== null && + typeof process.versions.node === 'string') + ? process.versions.node.split('.').map(function (n) { return Number(n); }) + : [0, 0, 0]; + var HEAP_DATA_VIEW = new DataView(wasmMemory.buffer), GET_HEAP_DATA_VIEW = function () { return HEAP_DATA_VIEW.buffer === wasmMemory.buffer ? HEAP_DATA_VIEW : (HEAP_DATA_VIEW = new DataView(wasmMemory.buffer)); }; + GET_HEAP_DATA_VIEW().setUint32(major, versions[0], true); + GET_HEAP_DATA_VIEW().setUint32(minor, versions[1], true); + GET_HEAP_DATA_VIEW().setUint32(patch, versions[2], true); + } + function _emnapi_runtime_keepalive_push() { + } + function _emnapi_runtime_keepalive_pop() { + } + function _emnapi_set_immediate(callback, data) { + emnapiCtx.feature.setImmediate(function () { + (wasmTable.get(callback))(data); + }); + } + function _emnapi_next_tick(callback, data) { + Promise.resolve().then(function () { + (wasmTable.get(callback))(data); + }); + } + function _emnapi_callback_into_module(forceUncaught, env, callback, data, close_scope_if_throw) { + var envObject = emnapiCtx.envStore.get(env); + var scope = emnapiCtx.openScope(envObject); + try { + envObject.callbackIntoModule(Boolean(forceUncaught), function () { + (wasmTable.get(callback))(env, data); + }); + } + catch (err) { + emnapiCtx.closeScope(envObject, scope); + if (close_scope_if_throw) { + emnapiCtx.closeScope(envObject); + } + throw err; + } + emnapiCtx.closeScope(envObject, scope); + } + function _emnapi_call_finalizer(forceUncaught, env, callback, data, hint) { + var envObject = emnapiCtx.envStore.get(env); + callback >>>= 0; + envObject.callFinalizerInternal(forceUncaught, callback, data, hint); + } + function _emnapi_ctx_increase_waiting_request_counter() { + emnapiCtx.increaseWaitingRequestCounter(); + } + function _emnapi_ctx_decrease_waiting_request_counter() { + emnapiCtx.decreaseWaitingRequestCounter(); + } + function _emnapi_is_main_runtime_thread() { + return ENVIRONMENT_IS_PTHREAD ? 0 : 1; + } + function _emnapi_is_main_browser_thread() { + return (typeof window !== 'undefined' && typeof document !== 'undefined' && !ENVIRONMENT_IS_NODE) ? 1 : 0; + } + function _emnapi_unwind() { + throw 'unwind'; + } + function _emnapi_get_now() { + return performance.timeOrigin + performance.now(); + } + function $emnapiSetValueI64(result, numberValue) { + var tempDouble; + var tempI64 = [ + numberValue >>> 0, + (tempDouble = numberValue, +Math.abs(tempDouble) >= 1 ? tempDouble > 0 ? (Math.min(+Math.floor(tempDouble / 4294967296), 4294967295) | 0) >>> 0 : ~~+Math.ceil((tempDouble - +(~~tempDouble >>> 0)) / 4294967296) >>> 0 : 0) + ]; + var HEAP_DATA_VIEW = new DataView(wasmMemory.buffer), GET_HEAP_DATA_VIEW = function () { return HEAP_DATA_VIEW.buffer === wasmMemory.buffer ? HEAP_DATA_VIEW : (HEAP_DATA_VIEW = new DataView(wasmMemory.buffer)); }; + GET_HEAP_DATA_VIEW().setInt32(result, tempI64[0], true); + GET_HEAP_DATA_VIEW().setInt32(result + 4, tempI64[1], true); + } + function _emnapi_open_handle_scope() { + return emnapiCtx.openScope().id; + } + function _emnapi_close_handle_scope(_scope) { + return emnapiCtx.closeScope(); + } + var utilMod = Object.freeze({ + __proto__: null, + $emnapiSetValueI64: $emnapiSetValueI64, + _emnapi_call_finalizer: _emnapi_call_finalizer, + _emnapi_callback_into_module: _emnapi_callback_into_module, + _emnapi_close_handle_scope: _emnapi_close_handle_scope, + _emnapi_ctx_decrease_waiting_request_counter: _emnapi_ctx_decrease_waiting_request_counter, + _emnapi_ctx_increase_waiting_request_counter: _emnapi_ctx_increase_waiting_request_counter, + _emnapi_get_node_version: _emnapi_get_node_version, + _emnapi_get_now: _emnapi_get_now, + _emnapi_is_main_browser_thread: _emnapi_is_main_browser_thread, + _emnapi_is_main_runtime_thread: _emnapi_is_main_runtime_thread, + _emnapi_next_tick: _emnapi_next_tick, + _emnapi_open_handle_scope: _emnapi_open_handle_scope, + _emnapi_runtime_keepalive_pop: _emnapi_runtime_keepalive_pop, + _emnapi_runtime_keepalive_push: _emnapi_runtime_keepalive_push, + _emnapi_set_immediate: _emnapi_set_immediate, + _emnapi_unwind: _emnapi_unwind, + napi_clear_last_error: napi_clear_last_error, + napi_set_last_error: napi_set_last_error + }); + function emnapiGetWorkerByPthreadPtr(pthreadPtr) { + var view = new DataView(wasmMemory.buffer); + var tidOffset = 20; + var tid = view.getInt32(pthreadPtr + tidOffset, true); + var worker = PThread.pthreads[tid]; + return worker; + } + function _emnapi_worker_ref(pthreadPtr) { + if (ENVIRONMENT_IS_PTHREAD) + return; + pthreadPtr >>>= 0; + var worker = emnapiGetWorkerByPthreadPtr(pthreadPtr); + if (worker && typeof worker.ref === 'function') { + worker.ref(); + } + } + function _emnapi_worker_unref(pthreadPtr) { + if (ENVIRONMENT_IS_PTHREAD) + return; + pthreadPtr >>>= 0; + var worker = emnapiGetWorkerByPthreadPtr(pthreadPtr); + if (worker && typeof worker.unref === 'function') { + worker.unref(); + } + } + function _emnapi_async_send_js(type, callback, data) { + if (ENVIRONMENT_IS_PTHREAD) { + var postMessage_1 = napiModule.postMessage; + postMessage_1({ + __emnapi__: { + type: 'async-send', + payload: { + callback: callback, + data: data + } + } + }); + } + else { + switch (type) { + case 0: + _emnapi_set_immediate(callback, data); + break; + case 1: + _emnapi_next_tick(callback, data); + break; + } + } + } + var uvThreadpoolReadyResolve; + var uvThreadpoolReady = new Promise(function (resolve) { + uvThreadpoolReadyResolve = function () { + uvThreadpoolReady.ready = true; + resolve(); + }; + }); + uvThreadpoolReady.ready = false; + function _emnapi_after_uvthreadpool_ready(callback, q, type) { + if (uvThreadpoolReady.ready) { + (wasmTable.get(callback))(q, type); + } + else { + uvThreadpoolReady.then(function () { + (wasmTable.get(callback))(q, type); + }); + } + } + function _emnapi_tell_js_uvthreadpool(threads, size) { + var p = []; + var HEAP_DATA_VIEW = new DataView(wasmMemory.buffer), GET_HEAP_DATA_VIEW = function () { return HEAP_DATA_VIEW.buffer === wasmMemory.buffer ? HEAP_DATA_VIEW : (HEAP_DATA_VIEW = new DataView(wasmMemory.buffer)); }; + var _loop_1 = function (i) { + var pthreadPtr = GET_HEAP_DATA_VIEW().getUint32(threads + i * 4, true); + var worker = emnapiGetWorkerByPthreadPtr(pthreadPtr); + p.push(new Promise(function (resolve) { + var handler = function (e) { + var data = ENVIRONMENT_IS_NODE ? e : e.data; + var __emnapi__ = data.__emnapi__; + if (__emnapi__ && __emnapi__.type === 'async-thread-ready') { + resolve(); + if (worker && typeof worker.unref === 'function') { + worker.unref(); + } + if (ENVIRONMENT_IS_NODE) { + worker.off('message', handler); + } + else { + worker.removeEventListener('message', handler); + } + } + }; + if (ENVIRONMENT_IS_NODE) { + worker.on('message', handler); + } + else { + worker.addEventListener('message', handler); + } + })); + }; + for (var i = 0; i < size; i++) { + _loop_1(i); + } + Promise.all(p).then(uvThreadpoolReadyResolve); + } + function _emnapi_emit_async_thread_ready() { + if (!ENVIRONMENT_IS_PTHREAD) + return; + var postMessage = napiModule.postMessage; + postMessage({ + __emnapi__: { + type: 'async-thread-ready', + payload: {} + } + }); + } + var asyncMod = Object.freeze({ + __proto__: null, + _emnapi_after_uvthreadpool_ready: _emnapi_after_uvthreadpool_ready, + _emnapi_async_send_js: _emnapi_async_send_js, + _emnapi_emit_async_thread_ready: _emnapi_emit_async_thread_ready, + _emnapi_tell_js_uvthreadpool: _emnapi_tell_js_uvthreadpool, + _emnapi_worker_ref: _emnapi_worker_ref, + _emnapi_worker_unref: _emnapi_worker_unref + }); + function napi_adjust_external_memory(env, change_in_bytes, adjusted_value) { + if (!env) + return 1; + var envObject = emnapiCtx.envStore.get(env); + if (!adjusted_value) + return envObject.setLastError(1); + var adjusted_memory = emnapiCtx.adjustAmountOfExternalAllocatedMemory(change_in_bytes); + adjusted_value >>>= 0; + if (emnapiCtx.feature.supportBigInt) { + var HEAP_DATA_VIEW = new DataView(wasmMemory.buffer), GET_HEAP_DATA_VIEW = function () { return HEAP_DATA_VIEW.buffer === wasmMemory.buffer ? HEAP_DATA_VIEW : (HEAP_DATA_VIEW = new DataView(wasmMemory.buffer)); }; + GET_HEAP_DATA_VIEW().setBigInt64(adjusted_value, BigInt(adjusted_memory), true); + } + else { + $emnapiSetValueI64(adjusted_value, Number(adjusted_memory)); + } + return envObject.clearLastError(); + } + var memoryMod = Object.freeze({ + __proto__: null, + napi_adjust_external_memory: napi_adjust_external_memory + }); + var emnapiAWST = { + idGen: {}, + values: [undefined], + queued: new Set(), + pending: [], + init: function () { + var idGen = { + nextId: 1, + list: [], + generate: function () { + var id; + if (idGen.list.length) { + id = idGen.list.shift(); + } + else { + id = idGen.nextId; + idGen.nextId++; + } + return id; + }, + reuse: function (id) { + idGen.list.push(id); + } + }; + emnapiAWST.idGen = idGen; + emnapiAWST.values = [undefined]; + emnapiAWST.queued = new Set(); + emnapiAWST.pending = []; + }, + create: function (env, resource, resourceName, execute, complete, data) { + var asyncId = 0; + var triggerAsyncId = 0; + if (emnapiNodeBinding) { + var asyncContext = emnapiNodeBinding.node.emitAsyncInit(resource, resourceName, -1); + asyncId = asyncContext.asyncId; + triggerAsyncId = asyncContext.triggerAsyncId; + } + var id = emnapiAWST.idGen.generate(); + emnapiAWST.values[id] = { + env: env, + id: id, + resource: resource, + asyncId: asyncId, + triggerAsyncId: triggerAsyncId, + status: 0, + execute: execute, + complete: complete, + data: data + }; + return id; + }, + callComplete: function (work, status) { + var complete = work.complete; + var env = work.env; + var data = work.data; + var callback = function () { + if (!complete) + return; + var envObject = emnapiCtx.envStore.get(env); + var scope = emnapiCtx.openScope(envObject); + try { + envObject.callbackIntoModule(true, function () { + (wasmTable.get(complete))(env, status, data); + }); + } + finally { + emnapiCtx.closeScope(envObject, scope); + } + }; + if (emnapiNodeBinding) { + emnapiNodeBinding.node.makeCallback(work.resource, callback, [], { + asyncId: work.asyncId, + triggerAsyncId: work.triggerAsyncId + }); + } + else { + callback(); + } + }, + queue: function (id) { + var work = emnapiAWST.values[id]; + if (!work) + return; + if (work.status === 0) { + work.status = 1; + if (emnapiAWST.queued.size >= (Math.abs(emnapiAsyncWorkPoolSize) || 4)) { + emnapiAWST.pending.push(id); + return; + } + emnapiAWST.queued.add(id); + var env_1 = work.env; + var data_1 = work.data; + var execute = work.execute; + work.status = 2; + emnapiCtx.feature.setImmediate(function () { + (wasmTable.get(execute))(env_1, data_1); + emnapiAWST.queued.delete(id); + work.status = 3; + emnapiCtx.feature.setImmediate(function () { + emnapiAWST.callComplete(work, 0); + }); + if (emnapiAWST.pending.length > 0) { + var nextWorkId = emnapiAWST.pending.shift(); + emnapiAWST.values[nextWorkId].status = 0; + emnapiAWST.queue(nextWorkId); + } + }); + } + }, + cancel: function (id) { + var index = emnapiAWST.pending.indexOf(id); + if (index !== -1) { + var work_1 = emnapiAWST.values[id]; + if (work_1 && (work_1.status === 1)) { + work_1.status = 4; + emnapiAWST.pending.splice(index, 1); + emnapiCtx.feature.setImmediate(function () { + emnapiAWST.callComplete(work_1, 11); + }); + return 0; + } + else { + return 9; + } + } + return 9; + }, + remove: function (id) { + var work = emnapiAWST.values[id]; + if (!work) + return; + if (emnapiNodeBinding) { + emnapiNodeBinding.node.emitAsyncDestroy({ + asyncId: work.asyncId, + triggerAsyncId: work.triggerAsyncId + }); + } + emnapiAWST.values[id] = undefined; + emnapiAWST.idGen.reuse(id); + } + }; + function _emnapi_node_emit_async_init(async_resource, async_resource_name, trigger_async_id, result) { + if (!emnapiNodeBinding) + return; + var resource = emnapiCtx.handleStore.get(async_resource).value; + var resource_name = emnapiCtx.handleStore.get(async_resource_name).value; + var asyncContext = emnapiNodeBinding.node.emitAsyncInit(resource, resource_name, trigger_async_id); + var asyncId = asyncContext.asyncId; + var triggerAsyncId = asyncContext.triggerAsyncId; + if (result) { + result >>>= 0; + var HEAP_DATA_VIEW = new DataView(wasmMemory.buffer), GET_HEAP_DATA_VIEW = function () { return HEAP_DATA_VIEW.buffer === wasmMemory.buffer ? HEAP_DATA_VIEW : (HEAP_DATA_VIEW = new DataView(wasmMemory.buffer)); }; + GET_HEAP_DATA_VIEW().setFloat64(result, asyncId, true); + GET_HEAP_DATA_VIEW().setFloat64(result + 8, triggerAsyncId, true); + } + } + function _emnapi_node_emit_async_destroy(async_id, trigger_async_id) { + if (!emnapiNodeBinding) + return; + emnapiNodeBinding.node.emitAsyncDestroy({ + asyncId: async_id, + triggerAsyncId: trigger_async_id + }); + } + function _emnapi_node_make_callback(env, async_resource, cb, argv, size, async_id, trigger_async_id, result) { + var i = 0; + var v; + if (!emnapiNodeBinding) + return; + var resource = emnapiCtx.handleStore.get(async_resource).value; + var callback = emnapiCtx.handleStore.get(cb).value; + argv >>>= 0; + size >>>= 0; + size = size >>> 0; + var arr = Array(size); + var HEAP_DATA_VIEW = new DataView(wasmMemory.buffer), GET_HEAP_DATA_VIEW = function () { return HEAP_DATA_VIEW.buffer === wasmMemory.buffer ? HEAP_DATA_VIEW : (HEAP_DATA_VIEW = new DataView(wasmMemory.buffer)); }; + for (; i < size; i++) { + var argVal = GET_HEAP_DATA_VIEW().getUint32(argv + i * 4, true); + arr[i] = emnapiCtx.handleStore.get(argVal).value; + } + var ret = emnapiNodeBinding.node.makeCallback(resource, callback, arr, { + asyncId: async_id, + triggerAsyncId: trigger_async_id + }); + if (result) { + result >>>= 0; + var envObject = emnapiCtx.envStore.get(env); + v = envObject.ensureHandleId(ret); + GET_HEAP_DATA_VIEW().setUint32(result, v, true); + } + } + function _emnapi_async_init_js(async_resource, async_resource_name, result) { + if (!emnapiNodeBinding) { + return 9; + } + var resource; + if (async_resource) { + resource = Object(emnapiCtx.handleStore.get(async_resource).value); + } + var name = emnapiCtx.handleStore.get(async_resource_name).value; + var ret = emnapiNodeBinding.napi.asyncInit(resource, name); + if (ret.status !== 0) + return ret.status; + var numberValue = ret.value; + if (!((numberValue >= (BigInt(-1) * (BigInt(1) << BigInt(63)))) && (numberValue < (BigInt(1) << BigInt(63))))) { + numberValue = numberValue & ((BigInt(1) << BigInt(64)) - BigInt(1)); + if (numberValue >= (BigInt(1) << BigInt(63))) { + numberValue = numberValue - (BigInt(1) << BigInt(64)); + } + } + var low = Number(numberValue & BigInt(0xffffffff)); + var high = Number(numberValue >> BigInt(32)); + result >>>= 0; + var HEAP_DATA_VIEW = new DataView(wasmMemory.buffer), GET_HEAP_DATA_VIEW = function () { return HEAP_DATA_VIEW.buffer === wasmMemory.buffer ? HEAP_DATA_VIEW : (HEAP_DATA_VIEW = new DataView(wasmMemory.buffer)); }; + GET_HEAP_DATA_VIEW().setInt32(result, low, true); + GET_HEAP_DATA_VIEW().setInt32(result + 4, high, true); + return 0; + } + function _emnapi_async_destroy_js(async_context) { + if (!emnapiNodeBinding) { + return 9; + } + async_context >>>= 0; + var HEAP_DATA_VIEW = new DataView(wasmMemory.buffer), GET_HEAP_DATA_VIEW = function () { return HEAP_DATA_VIEW.buffer === wasmMemory.buffer ? HEAP_DATA_VIEW : (HEAP_DATA_VIEW = new DataView(wasmMemory.buffer)); }; + var low = GET_HEAP_DATA_VIEW().getInt32(async_context, true); + var high = GET_HEAP_DATA_VIEW().getInt32(async_context + 4, true); + var pointer = BigInt(low >>> 0) | (BigInt(high) << BigInt(32)); + var ret = emnapiNodeBinding.napi.asyncDestroy(pointer); + if (ret.status !== 0) + return ret.status; + return 0; + } + function napi_open_callback_scope(env, ignored, async_context_handle, result) { + throw new Error('napi_open_callback_scope has not been implemented yet'); + } + function napi_close_callback_scope(env, scope) { + throw new Error('napi_close_callback_scope has not been implemented yet'); + } + function napi_make_callback(env, async_context, recv, func, argc, argv, result) { + var i = 0; + var v; + if (!env) + return 1; + var envObject = emnapiCtx.envStore.get(env); + envObject.checkGCAccess(); + if (!envObject.tryCatch.isEmpty()) + return envObject.setLastError(10); + if (!envObject.canCallIntoJs()) + return envObject.setLastError(envObject.moduleApiVersion >= 10 ? 23 : 10); + envObject.clearLastError(); + try { + if (!emnapiNodeBinding) { + return envObject.setLastError(9); + } + if (!recv) + return envObject.setLastError(1); + if (argc > 0) { + if (!argv) + return envObject.setLastError(1); + } + var v8recv = Object(emnapiCtx.handleStore.get(recv).value); + var v8func = emnapiCtx.handleStore.get(func).value; + if (typeof v8func !== 'function') { + return envObject.setLastError(1); + } + async_context >>>= 0; + var HEAP_DATA_VIEW = new DataView(wasmMemory.buffer), GET_HEAP_DATA_VIEW = function () { return HEAP_DATA_VIEW.buffer === wasmMemory.buffer ? HEAP_DATA_VIEW : (HEAP_DATA_VIEW = new DataView(wasmMemory.buffer)); }; + var low = GET_HEAP_DATA_VIEW().getInt32(async_context, true); + var high = GET_HEAP_DATA_VIEW().getInt32(async_context + 4, true); + var ctx = BigInt(low >>> 0) | (BigInt(high) << BigInt(32)); + argv >>>= 0; + argc >>>= 0; + argc = argc >>> 0; + var arr = Array(argc); + for (; i < argc; i++) { + var argVal = GET_HEAP_DATA_VIEW().getUint32(argv + i * 4, true); + arr[i] = emnapiCtx.handleStore.get(argVal).value; + } + var ret = emnapiNodeBinding.napi.makeCallback(ctx, v8recv, v8func, arr); + if (ret.error) { + throw ret.error; + } + if (ret.status !== 0) + return envObject.setLastError(ret.status); + if (result) { + result >>>= 0; + v = envObject.ensureHandleId(ret.value); + GET_HEAP_DATA_VIEW().setUint32(result, v, true); + } + return envObject.getReturnStatus(); + } + catch (err) { + envObject.tryCatch.setError(err); + return envObject.setLastError(10); + } + } + function _emnapi_env_check_gc_access(env) { + var envObject = emnapiCtx.envStore.get(env); + envObject.checkGCAccess(); + } + var nodeMod = Object.freeze({ + __proto__: null, + _emnapi_async_destroy_js: _emnapi_async_destroy_js, + _emnapi_async_init_js: _emnapi_async_init_js, + _emnapi_env_check_gc_access: _emnapi_env_check_gc_access, + _emnapi_node_emit_async_destroy: _emnapi_node_emit_async_destroy, + _emnapi_node_emit_async_init: _emnapi_node_emit_async_init, + _emnapi_node_make_callback: _emnapi_node_make_callback, + napi_close_callback_scope: napi_close_callback_scope, + napi_make_callback: napi_make_callback, + napi_open_callback_scope: napi_open_callback_scope + }); + var emnapiTSFN = { + _liveSet: {}, + offset: { + __size__: 0, + resource: 0, + async_id: 0, + trigger_async_id: 0, + queue_size: 0, + is_some: 0, + queue: 0, + async_pending: 0, + async_u_fd: 0, + thread_count: 0, + state: 0, + dispatch_state: 0, + context: 0, + max_queue_size: 0, + ref: 0, + env: 0, + finalize_data: 0, + finalize_cb: 0, + call_js_cb: 0, + handles_closing: 0, + async_ref: 0, + mutex: 0, + cond: 0 + }, + init: function () { + emnapiTSFN._liveSet = new Set(); + emnapiTSFN.offset.__size__ = 184; + emnapiTSFN.offset.resource = 0; + emnapiTSFN.offset.async_id = 8; + emnapiTSFN.offset.trigger_async_id = 16; + emnapiTSFN.offset.queue_size = 60; + emnapiTSFN.offset.is_some = 24; + emnapiTSFN.offset.queue = 64; + emnapiTSFN.offset.async_pending = 132; + emnapiTSFN.offset.async_u_fd = 96; + emnapiTSFN.offset.thread_count = 136; + emnapiTSFN.offset.state = 140; + emnapiTSFN.offset.dispatch_state = 144; + emnapiTSFN.offset.context = 148; + emnapiTSFN.offset.max_queue_size = 152; + emnapiTSFN.offset.ref = 156; + emnapiTSFN.offset.env = 160; + emnapiTSFN.offset.finalize_data = 164; + emnapiTSFN.offset.finalize_cb = 168; + emnapiTSFN.offset.call_js_cb = 172; + emnapiTSFN.offset.handles_closing = 176; + emnapiTSFN.offset.async_ref = 180; + emnapiTSFN.offset.mutex = 32; + emnapiTSFN.offset.cond = 56; + emnapiTSFN.offset.mutex = emnapiTSFN.offset.mutex + 4; + if (typeof PThread !== 'undefined') { + PThread.unusedWorkers.forEach(emnapiTSFN.addListener); + Object.values(PThread.pthreads).forEach(emnapiTSFN.addListener); + var __original_getNewWorker_1 = PThread.getNewWorker; + PThread.getNewWorker = function () { + var r = __original_getNewWorker_1.apply(this, arguments); + emnapiTSFN.addListener(r); + return r; + }; + } + }, + addListener: function (worker) { + if (!worker) + return false; + if (worker._emnapiTSFNListener) + return true; + var handler = function (e) { + var data = ENVIRONMENT_IS_NODE ? e : e.data; + var __emnapi__ = data.__emnapi__; + if (__emnapi__) { + var type = __emnapi__.type; + var payload = __emnapi__.payload; + if (type === 'tsfn-send') { + var pendng = payload.tsfn + emnapiTSFN.offset.async_pending; + if (Atomics.load(new Int32Array(emnapiTSFN.ensureBufferFor(pendng + 4)), pendng >>> 2) !== 0) { + emnapiTSFN.enqueue(payload.tsfn); + } + } + } + }; + var dispose = function () { + if (ENVIRONMENT_IS_NODE) { + worker.off('message', handler); + } + else { + worker.removeEventListener('message', handler, false); + } + delete worker._emnapiTSFNListener; + }; + worker._emnapiTSFNListener = { handler: handler, dispose: dispose }; + if (ENVIRONMENT_IS_NODE) { + worker.on('message', handler); + } + else { + worker.addEventListener('message', handler, false); + } + return true; + }, + ensureBufferFor: function (end) { + var buffer = wasmMemory.buffer; + if (end > buffer.byteLength) { + wasmMemory.grow(0); + buffer = wasmMemory.buffer; + } + return buffer; + }, + initQueue: function (func) { + var size = 2 * 4; + var queue = _malloc(size); + if (!queue) + return false; + queue >>>= 0; + new Uint8Array(emnapiTSFN.ensureBufferFor(queue + size), queue, size).fill(0); + emnapiTSFN.storeSizeTypeValue(func + emnapiTSFN.offset.queue, queue, false); + return true; + }, + destroyQueue: function (func) { + var queue = emnapiTSFN.loadSizeTypeValue(func + emnapiTSFN.offset.queue, false); + if (queue) { + var node = emnapiTSFN.loadSizeTypeValue(queue, false); + while (node !== 0) { + var next = emnapiTSFN.loadSizeTypeValue(node + 4, false); + _free(node); + node = next; + } + _free(queue); + } + }, + pushQueue: function (func, data) { + var queue = emnapiTSFN.loadSizeTypeValue(func + emnapiTSFN.offset.queue, false); + var head = emnapiTSFN.loadSizeTypeValue(queue, false); + var tail = emnapiTSFN.loadSizeTypeValue(queue + 4, false); + var size = 2 * 4; + var node = _malloc(size); + if (!node) + throw new Error('OOM'); + node >>>= 0; + emnapiTSFN.storeSizeTypeValue(node, data, false); + emnapiTSFN.storeSizeTypeValue(node + 4, 0, false); + if (head === 0 && tail === 0) { + emnapiTSFN.storeSizeTypeValue(queue, node, false); + emnapiTSFN.storeSizeTypeValue(queue + 4, node, false); + } + else { + emnapiTSFN.storeSizeTypeValue(tail + 4, node, false); + emnapiTSFN.storeSizeTypeValue(queue + 4, node, false); + } + emnapiTSFN.addQueueSize(func); + }, + shiftQueue: function (func) { + var queue = emnapiTSFN.loadSizeTypeValue(func + emnapiTSFN.offset.queue, false); + var head = emnapiTSFN.loadSizeTypeValue(queue, false); + if (head === 0) + return 0; + var node = head; + var next = emnapiTSFN.loadSizeTypeValue(head + 4, false); + emnapiTSFN.storeSizeTypeValue(queue, next, false); + if (next === 0) { + emnapiTSFN.storeSizeTypeValue(queue + 4, 0, false); + } + emnapiTSFN.storeSizeTypeValue(node + 4, 0, false); + var value = emnapiTSFN.loadSizeTypeValue(node, false); + _free(node); + emnapiTSFN.subQueueSize(func); + return value; + }, + push: function (func, data, mode) { + var mutex = emnapiTSFN.getMutex(func); + var cond = emnapiTSFN.getCond(func); + var waitCondition = function () { + var queueSize = emnapiTSFN.getQueueSize(func); + var maxSize = emnapiTSFN.getMaxQueueSize(func); + return queueSize >= maxSize && maxSize > 0 && emnapiTSFN.getState(func) === 0; + }; + var isBrowserMain = typeof window !== 'undefined' && typeof document !== 'undefined' && !ENVIRONMENT_IS_NODE; + var shouldDelete = false; + var ret = mutex.execute(function () { + while (waitCondition()) { + if (mode === 0) { + return 15; + } + if (isBrowserMain) { + return 21; + } + cond.wait(); + } + if (emnapiTSFN.getState(func) === 0) { + emnapiTSFN.pushQueue(func, data); + emnapiTSFN.send(func); + return 0; + } + if (emnapiTSFN.getThreadCount(func) === 0) { + return 1; + } + emnapiTSFN.subThreadCount(func); + if (!(emnapiTSFN.getState(func) === 2 && emnapiTSFN.getThreadCount(func) === 0)) { + return 16; + } + shouldDelete = true; + return 16; + }); + if (shouldDelete) { + emnapiTSFN.destroy(func); + } + return ret; + }, + getMutex: function (func) { + var index = func + emnapiTSFN.offset.mutex; + var mutex = { + lock: function () { + var isBrowserMain = typeof window !== 'undefined' && typeof document !== 'undefined' && !ENVIRONMENT_IS_NODE; + var i32a = new Int32Array(emnapiTSFN.ensureBufferFor(index + 4), index, 1); + if (isBrowserMain) { + while (true) { + var oldValue = Atomics.compareExchange(i32a, 0, 0, 10); + if (oldValue === 0) { + return; + } + } + } + else { + while (true) { + var oldValue = Atomics.compareExchange(i32a, 0, 0, 10); + if (oldValue === 0) { + return; + } + Atomics.wait(i32a, 0, 10); + } + } + }, + unlock: function () { + var i32a = new Int32Array(emnapiTSFN.ensureBufferFor(index + 4), index, 1); + var oldValue = Atomics.compareExchange(i32a, 0, 10, 0); + if (oldValue !== 10) { + throw new Error('Tried to unlock while not holding the mutex'); + } + Atomics.notify(i32a, 0, 1); + }, + execute: function (fn) { + mutex.lock(); + try { + return fn(); + } + finally { + mutex.unlock(); + } + } + }; + return mutex; + }, + getCond: function (func) { + var index = func + emnapiTSFN.offset.cond; + var mutex = emnapiTSFN.getMutex(func); + var cond = { + wait: function () { + var i32a = new Int32Array(emnapiTSFN.ensureBufferFor(index + 4), index, 1); + var value = Atomics.load(i32a, 0); + mutex.unlock(); + Atomics.wait(i32a, 0, value); + mutex.lock(); + }, + signal: function () { + var i32a = new Int32Array(emnapiTSFN.ensureBufferFor(index + 4), index, 1); + Atomics.add(i32a, 0, 1); + Atomics.notify(i32a, 0, 1); + } + }; + return cond; + }, + getQueueSize: function (func) { + return emnapiTSFN.loadSizeTypeValue(func + emnapiTSFN.offset.queue_size, true); + }, + addQueueSize: function (func) { + var offset = emnapiTSFN.offset.queue_size; + var arr, index; + arr = new Uint32Array(emnapiTSFN.ensureBufferFor(func + offset + 4)); + index = (func + offset) >>> 2; + Atomics.add(arr, index, 1); + }, + subQueueSize: function (func) { + var offset = emnapiTSFN.offset.queue_size; + var arr, index; + arr = new Uint32Array(emnapiTSFN.ensureBufferFor(func + offset + 4)); + index = (func + offset) >>> 2; + Atomics.sub(arr, index, 1); + }, + getThreadCount: function (func) { + return emnapiTSFN.loadSizeTypeValue(func + emnapiTSFN.offset.thread_count, true); + }, + addThreadCount: function (func) { + var offset = emnapiTSFN.offset.thread_count; + var arr, index; + arr = new Uint32Array(emnapiTSFN.ensureBufferFor(func + offset + 4)); + index = (func + offset) >>> 2; + Atomics.add(arr, index, 1); + }, + subThreadCount: function (func) { + var offset = emnapiTSFN.offset.thread_count; + var arr, index; + arr = new Uint32Array(emnapiTSFN.ensureBufferFor(func + offset + 4)); + index = (func + offset) >>> 2; + Atomics.sub(arr, index, 1); + }, + getState: function (func) { + return Atomics.load(new Int32Array(emnapiTSFN.ensureBufferFor(func + emnapiTSFN.offset.state + 4)), (func + emnapiTSFN.offset.state) >>> 2); + }, + setState: function (func, value) { + Atomics.store(new Int32Array(emnapiTSFN.ensureBufferFor(func + emnapiTSFN.offset.state + 4)), (func + emnapiTSFN.offset.state) >>> 2, value); + }, + getHandlesClosing: function (func) { + return Atomics.load(new Int8Array(emnapiTSFN.ensureBufferFor(func + emnapiTSFN.offset.handles_closing + 1)), (func + emnapiTSFN.offset.handles_closing)); + }, + setHandlesClosing: function (func, value) { + Atomics.store(new Int8Array(emnapiTSFN.ensureBufferFor(func + emnapiTSFN.offset.handles_closing + 1)), (func + emnapiTSFN.offset.handles_closing), value); + }, + getDispatchState: function (func) { + return Atomics.load(new Uint32Array(emnapiTSFN.ensureBufferFor(func + emnapiTSFN.offset.dispatch_state + 4)), (func + emnapiTSFN.offset.dispatch_state) >>> 2); + }, + getContext: function (func) { + return emnapiTSFN.loadSizeTypeValue(func + emnapiTSFN.offset.context, false); + }, + getMaxQueueSize: function (func) { + return emnapiTSFN.loadSizeTypeValue(func + emnapiTSFN.offset.max_queue_size, true); + }, + getEnv: function (func) { + return emnapiTSFN.loadSizeTypeValue(func + emnapiTSFN.offset.env, false); + }, + getCallJSCb: function (func) { + return emnapiTSFN.loadSizeTypeValue(func + emnapiTSFN.offset.call_js_cb, false); + }, + getRef: function (func) { + return emnapiTSFN.loadSizeTypeValue(func + emnapiTSFN.offset.ref, false); + }, + getResource: function (func) { + return emnapiTSFN.loadSizeTypeValue(func + emnapiTSFN.offset.resource, false); + }, + getFinalizeCb: function (func) { + return emnapiTSFN.loadSizeTypeValue(func + emnapiTSFN.offset.finalize_cb, false); + }, + getFinalizeData: function (func) { + return emnapiTSFN.loadSizeTypeValue(func + emnapiTSFN.offset.finalize_data, false); + }, + loadSizeTypeValue: function (offset, unsigned) { + var ret; + var arr; + if (unsigned) { + arr = new Uint32Array(emnapiTSFN.ensureBufferFor(offset + 4)); + ret = Atomics.load(arr, offset >>> 2); + return ret; + } + else { + arr = new Int32Array(emnapiTSFN.ensureBufferFor(offset + 4)); + ret = Atomics.load(arr, offset >>> 2); + return ret; + } + }, + storeSizeTypeValue: function (offset, value, unsigned) { + var arr; + if (unsigned) { + arr = new Uint32Array(emnapiTSFN.ensureBufferFor(offset + 4)); + Atomics.store(arr, offset >>> 2, value); + return undefined; + } + else { + arr = new Int32Array(emnapiTSFN.ensureBufferFor(offset + 4)); + Atomics.store(arr, offset >>> 2, value >>> 0); + return undefined; + } + }, + releaseResources: function (func) { + if (emnapiTSFN.getState(func) !== 2) { + emnapiTSFN.setState(func, 2); + var env = emnapiTSFN.getEnv(func); + var envObject = emnapiCtx.envStore.get(env); + var ref = emnapiTSFN.getRef(func); + if (ref) { + emnapiCtx.refStore.get(ref).dispose(); + } + var resource = emnapiTSFN.getResource(func); + emnapiCtx.refStore.get(resource).dispose(); + emnapiTSFN.ensureBufferFor(func + emnapiTSFN.offset.is_some + 1); + var HEAP_DATA_VIEW = new DataView(wasmMemory.buffer), GET_HEAP_DATA_VIEW = function () { return HEAP_DATA_VIEW.buffer === wasmMemory.buffer ? HEAP_DATA_VIEW : (HEAP_DATA_VIEW = new DataView(wasmMemory.buffer)); }; + GET_HEAP_DATA_VIEW().setInt8(func + emnapiTSFN.offset.is_some, 0, true); + emnapiCtx.removeCleanupHook(envObject, emnapiTSFN.cleanup, func); + envObject.unref(); + var asyncRefAddress = func + emnapiTSFN.offset.async_ref; + var asyncRefOffset = asyncRefAddress >>> 2; + var arr = new Uint32Array(emnapiTSFN.ensureBufferFor(asyncRefAddress + 4)); + if (Atomics.load(arr, asyncRefOffset) > 0) { + Atomics.store(arr, asyncRefOffset, 0); + emnapiCtx.decreaseWaitingRequestCounter(); + } + if (emnapiNodeBinding) { + var view = new DataView(emnapiTSFN.ensureBufferFor(func + emnapiTSFN.offset.trigger_async_id + 8)); + var asyncId = view.getFloat64(func + emnapiTSFN.offset.async_id, true); + var triggerAsyncId = view.getFloat64(func + emnapiTSFN.offset.trigger_async_id, true); + _emnapi_node_emit_async_destroy(asyncId, triggerAsyncId); + } + } + }, + destroy: function (func) { + emnapiTSFN._liveSet.delete(func); + emnapiTSFN.destroyQueue(func); + emnapiTSFN.releaseResources(func); + _free(func); + }, + emptyQueue: function (func) { + var drainQueue = []; + emnapiTSFN.getMutex(func).execute(function () { + while (emnapiTSFN.getQueueSize(func) > 0) { + drainQueue.push(emnapiTSFN.shiftQueue(func)); + } + }); + var callJsCb = emnapiTSFN.getCallJSCb(func); + var context = emnapiTSFN.getContext(func); + var data; + for (var i = 0; i < drainQueue.length; i++) { + data = drainQueue[i]; + if (callJsCb) { + (wasmTable.get(callJsCb))(0, 0, context, data); + } + } + }, + maybeDelete: function (func) { + var shouldDelete = false; + emnapiTSFN.getMutex(func).execute(function () { + if (emnapiTSFN.getThreadCount(func) > 0) { + emnapiTSFN.releaseResources(func); + } + else { + shouldDelete = true; + } + }); + if (shouldDelete) { + emnapiTSFN.destroy(func); + } + }, + finalize: function (func) { + var env = emnapiTSFN.getEnv(func); + var envObject = emnapiCtx.envStore.get(env); + emnapiCtx.openScope(envObject); + var finalize = emnapiTSFN.getFinalizeCb(func); + var data = emnapiTSFN.getFinalizeData(func); + var context = emnapiTSFN.getContext(func); + var f = function () { + envObject.callFinalizerInternal(0, finalize, data, context); + }; + try { + emnapiTSFN.emptyQueue(func); + if (finalize) { + if (emnapiNodeBinding) { + var resource = emnapiTSFN.getResource(func); + var resource_value = emnapiCtx.refStore.get(resource).get(); + var resourceObject = emnapiCtx.handleStore.get(resource_value).value; + var view = new DataView(emnapiTSFN.ensureBufferFor(func + emnapiTSFN.offset.trigger_async_id + 8)); + var asyncId = view.getFloat64(func + emnapiTSFN.offset.async_id, true); + var triggerAsyncId = view.getFloat64(func + emnapiTSFN.offset.trigger_async_id, true); + emnapiNodeBinding.node.makeCallback(resourceObject, f, [], { + asyncId: asyncId, + triggerAsyncId: triggerAsyncId + }); + } + else { + f(); + } + } + emnapiTSFN.maybeDelete(func); + } + finally { + emnapiCtx.closeScope(envObject); + } + }, + cleanup: function (func) { + emnapiTSFN.closeHandlesAndMaybeDelete(func, 1); + }, + closeHandlesAndMaybeDelete: function (func, set_closing) { + var env = emnapiTSFN.getEnv(func); + var envObject = emnapiCtx.envStore.get(env); + emnapiCtx.openScope(envObject); + try { + if (set_closing) { + emnapiTSFN.getMutex(func).execute(function () { + emnapiTSFN.setState(func, 1); + if (emnapiTSFN.getMaxQueueSize(func) > 0) { + emnapiTSFN.getCond(func).signal(); + } + }); + } + if (emnapiTSFN.getHandlesClosing(func)) { + return; + } + emnapiTSFN.setHandlesClosing(func, 1); + Atomics.store(new Int32Array(emnapiTSFN.ensureBufferFor(func + emnapiTSFN.offset.async_pending + 4)), (func + emnapiTSFN.offset.async_pending) >>> 2, 1); + emnapiCtx.feature.setImmediate(function () { + emnapiTSFN.finalize(func); + }); + } + finally { + emnapiCtx.closeScope(envObject); + } + }, + dispatchOne: function (func) { + var data = 0; + var popped_value = false; + var has_more = false; + var mutex = emnapiTSFN.getMutex(func); + var cond = emnapiTSFN.getCond(func); + mutex.execute(function () { + if (emnapiTSFN.getState(func) === 0) { + var size = emnapiTSFN.getQueueSize(func); + if (size > 0) { + data = emnapiTSFN.shiftQueue(func); + popped_value = true; + var maxQueueSize = emnapiTSFN.getMaxQueueSize(func); + if (size === maxQueueSize && maxQueueSize > 0) { + cond.signal(); + } + size--; + } + if (size === 0) { + if (emnapiTSFN.getThreadCount(func) === 0) { + emnapiTSFN.setState(func, 1); + if (emnapiTSFN.getMaxQueueSize(func) > 0) { + cond.signal(); + } + emnapiTSFN.closeHandlesAndMaybeDelete(func, 0); + } + } + else { + has_more = true; + } + } + else { + emnapiTSFN.closeHandlesAndMaybeDelete(func, 0); + } + }); + if (popped_value) { + var env = emnapiTSFN.getEnv(func); + var envObject_1 = emnapiCtx.envStore.get(env); + emnapiCtx.openScope(envObject_1); + var f = function () { + envObject_1.callbackIntoModule(false, function () { + var callJsCb = emnapiTSFN.getCallJSCb(func); + var ref = emnapiTSFN.getRef(func); + var js_callback = ref ? emnapiCtx.refStore.get(ref).get() : 0; + if (callJsCb) { + var context = emnapiTSFN.getContext(func); + (wasmTable.get(callJsCb))(env, js_callback, context, data); + } + else { + var jsCallback = js_callback ? emnapiCtx.handleStore.get(js_callback).value : null; + if (typeof jsCallback === 'function') { + jsCallback(); + } + } + }); + }; + try { + if (emnapiNodeBinding) { + var resource = emnapiTSFN.getResource(func); + var resource_value = emnapiCtx.refStore.get(resource).get(); + var resourceObject = emnapiCtx.handleStore.get(resource_value).value; + var view = new DataView(emnapiTSFN.ensureBufferFor(func + emnapiTSFN.offset.trigger_async_id + 8)); + emnapiNodeBinding.node.makeCallback(resourceObject, f, [], { + asyncId: view.getFloat64(func + emnapiTSFN.offset.async_id, true), + triggerAsyncId: view.getFloat64(func + emnapiTSFN.offset.trigger_async_id, true) + }); + } + else { + f(); + } + } + finally { + emnapiCtx.closeScope(envObject_1); + } + } + return has_more; + }, + dispatch: function (func) { + var has_more = true; + var iterations_left = 1000; + var dispatchStateAddress = func + emnapiTSFN.offset.dispatch_state; + var index = dispatchStateAddress >>> 2; + while (has_more && --iterations_left !== 0) { + Atomics.store(new Uint32Array(emnapiTSFN.ensureBufferFor(dispatchStateAddress + 4)), index, 1); + try { + has_more = emnapiTSFN.dispatchOne(func); + } + catch (err) { + if (emnapiTSFN._liveSet.has(func)) { + Atomics.exchange(new Uint32Array(emnapiTSFN.ensureBufferFor(dispatchStateAddress + 4)), index, 0); + emnapiTSFN.send(func); + } + throw err; + } + if (Atomics.exchange(new Uint32Array(emnapiTSFN.ensureBufferFor(dispatchStateAddress + 4)), index, 0) !== 1) { + has_more = true; + } + } + if (has_more) { + emnapiTSFN.send(func); + } + }, + enqueue: function (func) { + var pending = func + emnapiTSFN.offset.async_pending; + var scheduled = func + emnapiTSFN.offset.async_u_fd; + var end = Math.max(pending, scheduled) + 4; + var state = function () { return new Int32Array(emnapiTSFN.ensureBufferFor(end)); }; + if (Atomics.exchange(state(), scheduled >>> 2, 1) !== 0) { + return; + } + emnapiCtx.feature.setImmediate(function () { + if (!emnapiTSFN._liveSet.has(func)) { + return; + } + if (Atomics.load(state(), pending >>> 2) === 0) { + Atomics.store(state(), scheduled >>> 2, 0); + return; + } + emnapiCtx.feature.setImmediate(function () { + if (!emnapiTSFN._liveSet.has(func)) { + return; + } + try { + if (Atomics.exchange(state(), pending >>> 2, 0) === 0) { + return; + } + emnapiTSFN.dispatch(func); + } + finally { + if (emnapiTSFN._liveSet.has(func)) { + Atomics.store(state(), scheduled >>> 2, 0); + if (Atomics.load(state(), pending >>> 2) !== 0) { + emnapiTSFN.enqueue(func); + } + } + } + }); + }); + }, + send: function (func) { + var dispatchStateAddress = func + emnapiTSFN.offset.dispatch_state; + var current_state = Atomics.or(new Uint32Array(emnapiTSFN.ensureBufferFor(dispatchStateAddress + 4)), dispatchStateAddress >>> 2, 1 << 1); + if ((current_state & 1) === 1) { + return; + } + var pendng = func + emnapiTSFN.offset.async_pending; + if (Atomics.load(new Int32Array(emnapiTSFN.ensureBufferFor(pendng + 4)), pendng >>> 2) !== 0) { + return; + } + if (Atomics.exchange(new Int32Array(emnapiTSFN.ensureBufferFor(pendng + 4)), pendng >>> 2, 1) === 0) { + if ((typeof ENVIRONMENT_IS_PTHREAD !== 'undefined') && ENVIRONMENT_IS_PTHREAD) { + postMessage({ + __emnapi__: { + type: 'tsfn-send', + payload: { + tsfn: func + } + } + }); + } + else { + emnapiTSFN.enqueue(func); + } + } + } + }; + function napi_create_threadsafe_function(env, func, async_resource, async_resource_name, max_queue_size, initial_thread_count, thread_finalize_data, thread_finalize_cb, context, call_js_cb, result) { + if (!env) + return 1; + var envObject = emnapiCtx.envStore.get(env); + envObject.checkGCAccess(); + if (!async_resource_name) + return envObject.setLastError(1); + max_queue_size >>>= 0; + initial_thread_count >>>= 0; + env >>>= 0; + thread_finalize_data >>>= 0; + thread_finalize_cb >>>= 0; + context >>>= 0; + call_js_cb >>>= 0; + max_queue_size = max_queue_size >>> 0; + initial_thread_count = initial_thread_count >>> 0; + if (initial_thread_count === 0) { + return envObject.setLastError(1); + } + if (!result) + return envObject.setLastError(1); + var ref = 0; + func >>>= 0; + if (!func) { + if (!call_js_cb) + return envObject.setLastError(1); + } + else { + var funcValue = emnapiCtx.handleStore.get(func).value; + if (typeof funcValue !== 'function') { + return envObject.setLastError(1); + } + ref = emnapiCtx.createReference(envObject, func, 1, 1).id; + } + var asyncResourceObject; + if (async_resource) { + asyncResourceObject = emnapiCtx.handleStore.get(async_resource).value; + if (asyncResourceObject == null) { + return envObject.setLastError(2); + } + asyncResourceObject = Object(asyncResourceObject); + } + else { + asyncResourceObject = {}; + } + var resource = envObject.ensureHandleId(asyncResourceObject); + var asyncResourceName = emnapiCtx.handleStore.get(async_resource_name).value; + if (typeof asyncResourceName === 'symbol') { + return envObject.setLastError(3); + } + asyncResourceName = String(asyncResourceName); + var resource_name = envObject.ensureHandleId(asyncResourceName); + var sizeofTSFN = emnapiTSFN.offset.__size__; + var tsfn = _malloc(sizeofTSFN); + if (!tsfn) + return envObject.setLastError(9); + tsfn >>>= 0; + new Uint8Array(emnapiTSFN.ensureBufferFor(tsfn + sizeofTSFN)).subarray(tsfn, tsfn + sizeofTSFN).fill(0); + var resourceRef = emnapiCtx.createReference(envObject, resource, 1, 1); + var resource_ = resourceRef.id; + var HEAP_DATA_VIEW = new DataView(wasmMemory.buffer), GET_HEAP_DATA_VIEW = function () { return HEAP_DATA_VIEW.buffer === wasmMemory.buffer ? HEAP_DATA_VIEW : (HEAP_DATA_VIEW = new DataView(wasmMemory.buffer)); }; + GET_HEAP_DATA_VIEW().setUint32(tsfn + emnapiTSFN.offset.resource, resource_, true); + if (!emnapiTSFN.initQueue(tsfn)) { + _free(tsfn); + resourceRef.dispose(); + return envObject.setLastError(9); + } + _emnapi_node_emit_async_init(resource, resource_name, -1, tsfn + emnapiTSFN.offset.async_id); + GET_HEAP_DATA_VIEW().setInt8(tsfn + emnapiTSFN.offset.is_some, 1, true); + GET_HEAP_DATA_VIEW().setUint32(tsfn + emnapiTSFN.offset.thread_count, initial_thread_count, true); + GET_HEAP_DATA_VIEW().setUint32(tsfn + emnapiTSFN.offset.context, context, true); + GET_HEAP_DATA_VIEW().setUint32(tsfn + emnapiTSFN.offset.max_queue_size, max_queue_size, true); + GET_HEAP_DATA_VIEW().setUint32(tsfn + emnapiTSFN.offset.ref, ref, true); + GET_HEAP_DATA_VIEW().setUint32(tsfn + emnapiTSFN.offset.env, env, true); + GET_HEAP_DATA_VIEW().setUint32(tsfn + emnapiTSFN.offset.finalize_data, thread_finalize_data, true); + GET_HEAP_DATA_VIEW().setUint32(tsfn + emnapiTSFN.offset.finalize_cb, thread_finalize_cb, true); + GET_HEAP_DATA_VIEW().setUint32(tsfn + emnapiTSFN.offset.call_js_cb, call_js_cb, true); + emnapiCtx.addCleanupHook(envObject, emnapiTSFN.cleanup, tsfn); + emnapiTSFN._liveSet.add(tsfn); + envObject.ref(); + emnapiCtx.increaseWaitingRequestCounter(); + GET_HEAP_DATA_VIEW().setUint32(tsfn + emnapiTSFN.offset.async_ref, 1, true); + result >>>= 0; + GET_HEAP_DATA_VIEW().setUint32(result, tsfn, true); + return envObject.clearLastError(); + } + function napi_get_threadsafe_function_context(func, result) { + if (!func || !result) { + abort(); + return 1; + } + func >>>= 0; + result >>>= 0; + var context = emnapiTSFN.getContext(func); + var HEAP_DATA_VIEW = new DataView(wasmMemory.buffer), GET_HEAP_DATA_VIEW = function () { return HEAP_DATA_VIEW.buffer === wasmMemory.buffer ? HEAP_DATA_VIEW : (HEAP_DATA_VIEW = new DataView(wasmMemory.buffer)); }; + GET_HEAP_DATA_VIEW().setUint32(result, context, true); + return 0; + } + function napi_call_threadsafe_function(func, data, mode) { + if (!func) { + abort(); + return 1; + } + func >>>= 0; + data >>>= 0; + return emnapiTSFN.push(func, data, mode); + } + function napi_acquire_threadsafe_function(func) { + if (!func) { + abort(); + return 1; + } + func >>>= 0; + var mutex = emnapiTSFN.getMutex(func); + return mutex.execute(function () { + if (emnapiTSFN.getState(func) === 0) { + emnapiTSFN.addThreadCount(func); + return 0; + } + return 16; + }); + } + function napi_release_threadsafe_function(func, mode) { + if (!func) { + abort(); + return 1; + } + func >>>= 0; + var mutex = emnapiTSFN.getMutex(func); + var cond = emnapiTSFN.getCond(func); + var shouldDelete = false; + var ret = mutex.execute(function () { + if (emnapiTSFN.getThreadCount(func) === 0) { + return 1; + } + emnapiTSFN.subThreadCount(func); + if (emnapiTSFN.getThreadCount(func) === 0 || mode === 1) { + if (emnapiTSFN.getState(func) === 0) { + if (mode === 1) { + emnapiTSFN.setState(func, 1); + } + if (emnapiTSFN.getState(func) === 1 && emnapiTSFN.getMaxQueueSize(func) > 0) { + cond.signal(); + } + emnapiTSFN.send(func); + } + } + if (!(emnapiTSFN.getState(func) === 2 && emnapiTSFN.getThreadCount(func) === 0)) { + return 0; + } + shouldDelete = true; + return 0; + }); + if (shouldDelete) { + emnapiTSFN.destroy(func); + } + return ret; + } + function napi_unref_threadsafe_function(env, func) { + if (!func) { + abort(); + return 1; + } + func >>>= 0; + var asyncRefAddress = func + emnapiTSFN.offset.async_ref; + var asyncRefOffset = asyncRefAddress >>> 2; + var arr = new Uint32Array(emnapiTSFN.ensureBufferFor(asyncRefAddress + 4)); + var currentValue = Atomics.load(arr, asyncRefOffset); + if (currentValue > 0) { + Atomics.store(arr, asyncRefOffset, currentValue - 1); + if (currentValue === 1) { + emnapiCtx.decreaseWaitingRequestCounter(); + } + } + return 0; + } + function napi_ref_threadsafe_function(env, func) { + if (!func) { + abort(); + return 1; + } + func >>>= 0; + var asyncRefAddress = func + emnapiTSFN.offset.async_ref; + var asyncRefOffset = asyncRefAddress >>> 2; + var arr = new Uint32Array(emnapiTSFN.ensureBufferFor(asyncRefAddress + 4)); + var currentValue = Atomics.load(arr, asyncRefOffset); + if (!currentValue) { + emnapiCtx.increaseWaitingRequestCounter(); + } + Atomics.store(arr, asyncRefOffset, currentValue + 1); + return 0; + } + var emnapiAWMT = { + pool: [], + workerReady: null, + globalAddress: 0, + globalOffset: { + idle_threads: 0, + q: 1 * 4, + next: 1 * 4, + prev: 2 * 4, + mutex: 3 * 4, + cond: 4 * 4, + exit_message: 5 * 4, + end: 7 * 4 + }, + offset: { + resource: 0, + async_id: 8, + trigger_async_id: 16, + env: 24, + status: 1 * 4 + 24, + queue: 2 * 4 + 24, + queue_next: 2 * 4 + 24, + queue_prev: 3 * 4 + 24, + data: 4 * 4 + 24, + execute: 5 * 4 + 24, + complete: 6 * 4 + 24, + end: 7 * 4 + 24 + }, + ensureBufferFor: function (end) { + var buffer = wasmMemory.buffer; + if (end > buffer.byteLength) { + wasmMemory.grow(0); + buffer = wasmMemory.buffer; + } + return buffer; + }, + init: function () { + emnapiAWMT.pool = []; + emnapiAWMT.workerReady = null; + if (typeof PThread !== 'undefined') { + PThread.unusedWorkers.forEach(emnapiAWMT.addListener); + Object.values(PThread.pthreads).forEach(emnapiAWMT.addListener); + var __original_getNewWorker_1 = PThread.getNewWorker; + PThread.getNewWorker = function () { + var r = __original_getNewWorker_1.apply(this, arguments); + emnapiAWMT.addListener(r); + return r; + }; + } + }, + addListener: function (worker) { + if (!worker) + return false; + if (worker._emnapiAWMTListener) + return true; + var handler = function (e) { + var data = ENVIRONMENT_IS_NODE ? e : e.data; + var __emnapi__ = data.__emnapi__; + if (__emnapi__) { + var type = __emnapi__.type; + var payload = __emnapi__.payload; + if (type === 'async-work-complete') { + emnapiAWMT.callComplete(payload.work, 0); + } + } + }; + var dispose = function () { + if (ENVIRONMENT_IS_NODE) { + worker.off('message', handler); + } + else { + worker.removeEventListener('message', handler, false); + } + delete worker._emnapiAWMTListener; + }; + worker._emnapiAWMTListener = { handler: handler, dispose: dispose }; + if (ENVIRONMENT_IS_NODE) { + worker.on('message', handler); + } + else { + worker.addEventListener('message', handler, false); + } + return true; + }, + initGlobal: function () { + if (!emnapiAWMT.globalAddress) { + emnapiAWMT.globalAddress = _malloc(emnapiAWMT.globalOffset.end); + emnapiAWMT.globalAddress >>>= 0; + var size = emnapiAWMT.globalOffset.end; + var addr = emnapiAWMT.globalAddress; + new Uint8Array(emnapiAWMT.ensureBufferFor(addr + size), addr, size).fill(0); + emnapiAWMT.queueInit(emnapiAWMT.globalAddress + emnapiAWMT.globalOffset.q); + emnapiAWMT.queueInit(emnapiAWMT.globalAddress + emnapiAWMT.globalOffset.exit_message); + } + }, + terminateWorkers: function () { + emnapiAWMT.pool.forEach(function (w) { + var _a, _b; + (_a = w._emnapiAWMTListener) === null || _a === void 0 ? void 0 : _a.dispose(); + (_b = w._emnapiTSFNListener) === null || _b === void 0 ? void 0 : _b.dispose(); + w.terminate(); + }); + emnapiAWMT.pool.length = 0; + }, + initWorkers: function (n) { + if (ENVIRONMENT_IS_PTHREAD) { + return emnapiAWMT.workerReady || (emnapiAWMT.workerReady = Promise.resolve()); + } + if (emnapiAWMT.workerReady) + return emnapiAWMT.workerReady; + if (!('emnapi_async_worker_create' in wasmInstance.exports)) { + throw new TypeError('`emnapi_async_worker_create` is not exported, please try to add `--export=emnapi_async_worker_create` to linker flags'); + } + var emnapi_async_worker_create = wasmInstance.exports.emnapi_async_worker_create; + var args = []; + emnapiAWMT.initGlobal(); + for (var i = 0; i < n; ++i) { + args.push(emnapi_async_worker_create(1, emnapiAWMT.globalAddress)); + } + var promises = args.map(function (index) { + if (index === 0) { + return Promise.reject(new Error('Failed to create async worker')); + } + var worker; + if (index < 0) { + worker = emnapiAWMT.pool[-index - 1]; + if (worker) + return worker.whenLoaded; + } + index >>>= 0; + var tidOffset = 20; + var view = new DataView(emnapiAWMT.ensureBufferFor(index + tidOffset + 4)); + var tid = view.getInt32(index + tidOffset, true); + worker = PThread.pthreads[tid]; + return worker.whenLoaded; + }); + emnapiAWMT.workerReady = Promise.all(promises); + return emnapiAWMT.workerReady; + }, + getResource: function (work) { + emnapiAWMT.ensureBufferFor(work + emnapiAWMT.offset.resource + 4); + var HEAP_DATA_VIEW = new DataView(wasmMemory.buffer), GET_HEAP_DATA_VIEW = function () { return HEAP_DATA_VIEW.buffer === wasmMemory.buffer ? HEAP_DATA_VIEW : (HEAP_DATA_VIEW = new DataView(wasmMemory.buffer)); }; + return GET_HEAP_DATA_VIEW().getUint32(work + emnapiAWMT.offset.resource, true); + }, + getExecute: function (work) { + emnapiAWMT.ensureBufferFor(work + emnapiAWMT.offset.execute + 4); + var HEAP_DATA_VIEW = new DataView(wasmMemory.buffer), GET_HEAP_DATA_VIEW = function () { return HEAP_DATA_VIEW.buffer === wasmMemory.buffer ? HEAP_DATA_VIEW : (HEAP_DATA_VIEW = new DataView(wasmMemory.buffer)); }; + return GET_HEAP_DATA_VIEW().getUint32(work + emnapiAWMT.offset.execute, true); + }, + getComplete: function (work) { + emnapiAWMT.ensureBufferFor(work + emnapiAWMT.offset.complete + 4); + var HEAP_DATA_VIEW = new DataView(wasmMemory.buffer), GET_HEAP_DATA_VIEW = function () { return HEAP_DATA_VIEW.buffer === wasmMemory.buffer ? HEAP_DATA_VIEW : (HEAP_DATA_VIEW = new DataView(wasmMemory.buffer)); }; + return GET_HEAP_DATA_VIEW().getUint32(work + emnapiAWMT.offset.complete, true); + }, + getEnv: function (work) { + emnapiAWMT.ensureBufferFor(work + emnapiAWMT.offset.env + 4); + var HEAP_DATA_VIEW = new DataView(wasmMemory.buffer), GET_HEAP_DATA_VIEW = function () { return HEAP_DATA_VIEW.buffer === wasmMemory.buffer ? HEAP_DATA_VIEW : (HEAP_DATA_VIEW = new DataView(wasmMemory.buffer)); }; + return GET_HEAP_DATA_VIEW().getUint32(work + emnapiAWMT.offset.env, true); + }, + getData: function (work) { + emnapiAWMT.ensureBufferFor(work + emnapiAWMT.offset.data + 4); + var HEAP_DATA_VIEW = new DataView(wasmMemory.buffer), GET_HEAP_DATA_VIEW = function () { return HEAP_DATA_VIEW.buffer === wasmMemory.buffer ? HEAP_DATA_VIEW : (HEAP_DATA_VIEW = new DataView(wasmMemory.buffer)); }; + return GET_HEAP_DATA_VIEW().getUint32(work + emnapiAWMT.offset.data, true); + }, + getMutex: function () { + var index = emnapiAWMT.globalAddress + emnapiAWMT.globalOffset.mutex; + var mutex = { + lock: function () { + var isBrowserMain = typeof window !== 'undefined' && typeof document !== 'undefined' && !ENVIRONMENT_IS_NODE; + var i32a = new Int32Array(emnapiAWMT.ensureBufferFor(index + 4), index, 1); + if (isBrowserMain) { + while (true) { + var oldValue = Atomics.compareExchange(i32a, 0, 0, 10); + if (oldValue === 0) { + return; + } + } + } + else { + while (true) { + var oldValue = Atomics.compareExchange(i32a, 0, 0, 10); + if (oldValue === 0) { + return; + } + Atomics.wait(i32a, 0, 10); + } + } + }, + unlock: function () { + var i32a = new Int32Array(emnapiAWMT.ensureBufferFor(index + 4), index, 1); + var oldValue = Atomics.compareExchange(i32a, 0, 10, 0); + if (oldValue !== 10) { + throw new Error('Tried to unlock while not holding the mutex'); + } + Atomics.notify(i32a, 0, 1); + }, + execute: function (fn) { + mutex.lock(); + try { + return fn(); + } + finally { + mutex.unlock(); + } + } + }; + return mutex; + }, + getCond: function () { + var index = emnapiAWMT.globalAddress + emnapiAWMT.globalOffset.cond; + var mutex = emnapiAWMT.getMutex(); + var cond = { + wait: function () { + var i32a = new Int32Array(emnapiAWMT.ensureBufferFor(index + 4), index, 1); + var value = Atomics.load(i32a, 0); + mutex.unlock(); + Atomics.wait(i32a, 0, value); + mutex.lock(); + }, + signal: function () { + var i32a = new Int32Array(emnapiAWMT.ensureBufferFor(index + 4), index, 1); + Atomics.add(i32a, 0, 1); + Atomics.notify(i32a, 0, 1); + } + }; + return cond; + }, + queueInit: function (q) { + emnapiAWMT.ensureBufferFor(q + 4 + 4); + var HEAP_DATA_VIEW = new DataView(wasmMemory.buffer), GET_HEAP_DATA_VIEW = function () { return HEAP_DATA_VIEW.buffer === wasmMemory.buffer ? HEAP_DATA_VIEW : (HEAP_DATA_VIEW = new DataView(wasmMemory.buffer)); }; + GET_HEAP_DATA_VIEW().setUint32(q, q, true); + GET_HEAP_DATA_VIEW().setUint32(q + 4, q, true); + }, + queueInsertTail: function (h, q) { + emnapiAWMT.ensureBufferFor(h + 4 + 4); + emnapiAWMT.ensureBufferFor(q + 4 + 4); + var HEAP_DATA_VIEW = new DataView(wasmMemory.buffer), GET_HEAP_DATA_VIEW = function () { return HEAP_DATA_VIEW.buffer === wasmMemory.buffer ? HEAP_DATA_VIEW : (HEAP_DATA_VIEW = new DataView(wasmMemory.buffer)); }; + GET_HEAP_DATA_VIEW().setUint32(q, h, true); + var tempValue = GET_HEAP_DATA_VIEW().getUint32(h + 4, true); + GET_HEAP_DATA_VIEW().setUint32(q + 4, tempValue, true); + var qprev = GET_HEAP_DATA_VIEW().getUint32(q + 4, true); + GET_HEAP_DATA_VIEW().setUint32(qprev, q, true); + GET_HEAP_DATA_VIEW().setUint32(h + 4, q, true); + }, + queueRemove: function (q) { + emnapiAWMT.ensureBufferFor(q + 4 + 4); + var HEAP_DATA_VIEW = new DataView(wasmMemory.buffer), GET_HEAP_DATA_VIEW = function () { return HEAP_DATA_VIEW.buffer === wasmMemory.buffer ? HEAP_DATA_VIEW : (HEAP_DATA_VIEW = new DataView(wasmMemory.buffer)); }; + var qprev = GET_HEAP_DATA_VIEW().getUint32(q + 4, true); + var qnext = GET_HEAP_DATA_VIEW().getUint32(q, true); + GET_HEAP_DATA_VIEW().setUint32(qprev, qnext, true); + GET_HEAP_DATA_VIEW().setUint32(qnext + 4, qprev, true); + }, + queueEmpty: function (q) { + emnapiAWMT.ensureBufferFor(q + 4); + var HEAP_DATA_VIEW = new DataView(wasmMemory.buffer), GET_HEAP_DATA_VIEW = function () { return HEAP_DATA_VIEW.buffer === wasmMemory.buffer ? HEAP_DATA_VIEW : (HEAP_DATA_VIEW = new DataView(wasmMemory.buffer)); }; + return q == GET_HEAP_DATA_VIEW().getUint32(q, true); + }, + scheduleWork: function (work) { + var _a; + if (!((_a = emnapiAWMT.workerReady) === null || _a === void 0 ? void 0 : _a.ready)) { + emnapiAWMT.initWorkers(_emnapi_async_work_pool_size()).then(function () { + emnapiAWMT.workerReady.ready = true; + }).catch(function (err) { + emnapiAWMT.workerReady = null; + throw err; + }); + } + emnapiCtx.increaseWaitingRequestCounter(); + var statusBuffer = new Int32Array(emnapiAWMT.ensureBufferFor(work + emnapiAWMT.offset.status + 4), work + emnapiAWMT.offset.status, 1); + Atomics.store(statusBuffer, 0, 0); + var mutex = emnapiAWMT.getMutex(); + var cond = emnapiAWMT.getCond(); + mutex.lock(); + try { + emnapiAWMT.queueInsertTail(emnapiAWMT.globalAddress + emnapiAWMT.globalOffset.q, work + emnapiAWMT.offset.queue); + } + catch (err) { + emnapiCtx.decreaseWaitingRequestCounter(); + mutex.unlock(); + throw err; + } + emnapiAWMT.ensureBufferFor(emnapiAWMT.globalAddress + emnapiAWMT.globalOffset.idle_threads + 4); + var HEAP_DATA_VIEW = new DataView(wasmMemory.buffer), GET_HEAP_DATA_VIEW = function () { return HEAP_DATA_VIEW.buffer === wasmMemory.buffer ? HEAP_DATA_VIEW : (HEAP_DATA_VIEW = new DataView(wasmMemory.buffer)); }; + if (GET_HEAP_DATA_VIEW().getUint32(emnapiAWMT.globalAddress + emnapiAWMT.globalOffset.idle_threads, true) > 0) { + cond.signal(); + } + mutex.unlock(); + }, + cancelWork: function (work) { + var cancelled = false; + emnapiAWMT.getMutex().execute(function () { + emnapiAWMT.ensureBufferFor(work + emnapiAWMT.offset.status + 4); + var HEAP_DATA_VIEW = new DataView(wasmMemory.buffer), GET_HEAP_DATA_VIEW = function () { return HEAP_DATA_VIEW.buffer === wasmMemory.buffer ? HEAP_DATA_VIEW : (HEAP_DATA_VIEW = new DataView(wasmMemory.buffer)); }; + cancelled = !emnapiAWMT.queueEmpty(work + emnapiAWMT.offset.queue) && GET_HEAP_DATA_VIEW().getInt32(work + emnapiAWMT.offset.status, true) !== 2; + if (cancelled) { + emnapiAWMT.queueRemove(work + emnapiAWMT.offset.queue); + } + }); + if (!cancelled) { + return 9; + } + if (Atomics.compareExchange(new Int32Array(emnapiAWMT.ensureBufferFor(work + emnapiAWMT.offset.status + 4), work + emnapiAWMT.offset.status, 1), 0, 0, 1) !== 0) { + return 9; + } + emnapiCtx.feature.setImmediate(function () { + emnapiAWMT.callComplete(work, 11); + }); + return 0; + }, + callComplete: function (work, status) { + emnapiCtx.decreaseWaitingRequestCounter(); + var complete = emnapiAWMT.getComplete(work); + var env = emnapiAWMT.getEnv(work); + var data = emnapiAWMT.getData(work); + var envObject = emnapiCtx.envStore.get(env); + var scope = emnapiCtx.openScope(envObject); + var callback = function () { + if (!complete) + return; + envObject.callbackIntoModule(true, function () { + (wasmTable.get(complete))(env, status, data); + }); + }; + try { + if (emnapiNodeBinding) { + var resource = emnapiAWMT.getResource(work); + var resource_value = emnapiCtx.refStore.get(resource).get(); + var resourceObject = emnapiCtx.handleStore.get(resource_value).value; + var view = new DataView(emnapiAWMT.ensureBufferFor(work + emnapiAWMT.offset.trigger_async_id + 8)); + var asyncId = view.getFloat64(work + emnapiAWMT.offset.async_id, true); + var triggerAsyncId = view.getFloat64(work + emnapiAWMT.offset.trigger_async_id, true); + emnapiNodeBinding.node.makeCallback(resourceObject, callback, [], { + asyncId: asyncId, + triggerAsyncId: triggerAsyncId + }); + } + else { + callback(); + } + } + finally { + emnapiCtx.closeScope(envObject, scope); + } + } + }; + emnapiAWMT.init(); + var napi_create_async_work = singleThreadAsyncWork + ? function (env, resource, resource_name, execute, complete, data, result) { + if (!env) + return 1; + var envObject = emnapiCtx.envStore.get(env); + envObject.checkGCAccess(); + if (!execute) + return envObject.setLastError(1); + if (!result) + return envObject.setLastError(1); + var resourceObject; + if (resource) { + resourceObject = Object(emnapiCtx.handleStore.get(resource).value); + } + else { + resourceObject = {}; + } + if (!resource_name) + return envObject.setLastError(1); + var resourceName = String(emnapiCtx.handleStore.get(resource_name).value); + var id = emnapiAWST.create(env, resourceObject, resourceName, execute, complete, data); + result >>>= 0; + var HEAP_DATA_VIEW = new DataView(wasmMemory.buffer), GET_HEAP_DATA_VIEW = function () { return HEAP_DATA_VIEW.buffer === wasmMemory.buffer ? HEAP_DATA_VIEW : (HEAP_DATA_VIEW = new DataView(wasmMemory.buffer)); }; + GET_HEAP_DATA_VIEW().setUint32(result, id, true); + return envObject.clearLastError(); + } + : function (env, resource, resource_name, execute, complete, data, result) { + if (!env) + return 1; + var envObject = emnapiCtx.envStore.get(env); + envObject.checkGCAccess(); + if (!execute) + return envObject.setLastError(1); + if (!result) + return envObject.setLastError(1); + var resourceObject; + if (resource) { + resourceObject = Object(emnapiCtx.handleStore.get(resource).value); + } + else { + resourceObject = {}; + } + if (!resource_name) + return envObject.setLastError(1); + var sizeofAW = emnapiAWMT.offset.end; + var aw = _malloc(sizeofAW); + if (!aw) + return envObject.setLastError(9); + aw >>>= 0; + new Uint8Array(emnapiAWMT.ensureBufferFor(aw + sizeofAW)).subarray(aw, aw + sizeofAW).fill(0); + var s = envObject.ensureHandleId(resourceObject); + var resourceRef = emnapiCtx.createReference(envObject, s, 1, 1); + var resource_ = resourceRef.id; + var HEAP_DATA_VIEW = new DataView(wasmMemory.buffer), GET_HEAP_DATA_VIEW = function () { return HEAP_DATA_VIEW.buffer === wasmMemory.buffer ? HEAP_DATA_VIEW : (HEAP_DATA_VIEW = new DataView(wasmMemory.buffer)); }; + GET_HEAP_DATA_VIEW().setUint32(aw, resource_, true); + _emnapi_node_emit_async_init(s, resource_name, -1, aw + emnapiAWMT.offset.async_id); + GET_HEAP_DATA_VIEW().setUint32(aw + emnapiAWMT.offset.env, env, true); + GET_HEAP_DATA_VIEW().setUint32(aw + emnapiAWMT.offset.execute, execute, true); + GET_HEAP_DATA_VIEW().setUint32(aw + emnapiAWMT.offset.complete, complete, true); + GET_HEAP_DATA_VIEW().setUint32(aw + emnapiAWMT.offset.data, data, true); + emnapiAWMT.queueInit(aw + emnapiAWMT.offset.queue); + result >>>= 0; + GET_HEAP_DATA_VIEW().setUint32(result, aw, true); + return envObject.clearLastError(); + }; + var napi_delete_async_work = singleThreadAsyncWork + ? function (env, work) { + if (!env) + return 1; + var envObject = emnapiCtx.envStore.get(env); + envObject.checkGCAccess(); + if (!work) + return envObject.setLastError(1); + work >>>= 0; + emnapiAWST.remove(work); + return envObject.clearLastError(); + } + : function (env, work) { + if (!env) + return 1; + var envObject = emnapiCtx.envStore.get(env); + envObject.checkGCAccess(); + if (!work) + return envObject.setLastError(1); + work >>>= 0; + var resource = emnapiAWMT.getResource(work); + emnapiCtx.refStore.get(resource).dispose(); + if (emnapiNodeBinding) { + var view = new DataView(emnapiAWMT.ensureBufferFor(work + emnapiAWMT.offset.trigger_async_id + 8)); + var asyncId = view.getFloat64(work + emnapiAWMT.offset.async_id, true); + var triggerAsyncId = view.getFloat64(work + emnapiAWMT.offset.trigger_async_id, true); + _emnapi_node_emit_async_destroy(asyncId, triggerAsyncId); + } + _free(work); + return envObject.clearLastError(); + }; + var napi_queue_async_work = singleThreadAsyncWork + ? function (env, work) { + if (!env) + return 1; + var envObject = emnapiCtx.envStore.get(env); + if (!work) + return envObject.setLastError(1); + work >>>= 0; + emnapiAWST.queue(work); + return envObject.clearLastError(); + } + : function (env, work) { + if (!env) + return 1; + var envObject = emnapiCtx.envStore.get(env); + if (!work) + return envObject.setLastError(1); + work >>>= 0; + emnapiAWMT.scheduleWork(work); + return envObject.clearLastError(); + }; + var napi_cancel_async_work = singleThreadAsyncWork + ? function (env, work) { + if (!env) + return 1; + var envObject = emnapiCtx.envStore.get(env); + if (!work) + return envObject.setLastError(1); + work >>>= 0; + var status = emnapiAWST.cancel(work); + if (status === 0) + return envObject.clearLastError(); + return envObject.setLastError(status); + } + : function (env, work) { + if (!env) + return 1; + var envObject = emnapiCtx.envStore.get(env); + if (!work) + return envObject.setLastError(1); + work >>>= 0; + var status = emnapiAWMT.cancelWork(work); + if (status === 0) + return envObject.clearLastError(); + return envObject.setLastError(status); + }; + function _emnapi_async_worker(globalAddress) { + globalAddress >>>= 0; + emnapiAWMT.globalAddress = globalAddress; + var mutex = emnapiAWMT.getMutex(); + var cond = emnapiAWMT.getCond(); + mutex.lock(); + var exitMessageAddr = globalAddress + emnapiAWMT.globalOffset.exit_message; + var idleThreadsAddr = globalAddress + emnapiAWMT.globalOffset.idle_threads; + var workerQueueAddr = globalAddress + emnapiAWMT.globalOffset.q; + var HEAP_DATA_VIEW = new DataView(wasmMemory.buffer), GET_HEAP_DATA_VIEW = function () { return HEAP_DATA_VIEW.buffer === wasmMemory.buffer ? HEAP_DATA_VIEW : (HEAP_DATA_VIEW = new DataView(wasmMemory.buffer)); }; + for (;;) { + emnapiAWMT.ensureBufferFor(workerQueueAddr + 4); + while (emnapiAWMT.queueEmpty(workerQueueAddr)) { + Atomics.add(new Int32Array(emnapiAWMT.ensureBufferFor(idleThreadsAddr + 4), idleThreadsAddr, 1), 0, 1); + cond.wait(); + Atomics.sub(new Int32Array(emnapiAWMT.ensureBufferFor(idleThreadsAddr + 4), idleThreadsAddr, 1), 0, 1); + } + var q = GET_HEAP_DATA_VIEW().getUint32(workerQueueAddr, true); + if (q === exitMessageAddr) { + cond.signal(); + mutex.unlock(); + break; + } + var work = q - emnapiAWMT.offset.queue; + emnapiAWMT.queueRemove(q); + emnapiAWMT.queueInit(q); + mutex.unlock(); + var statusBuffer = new Int32Array(emnapiAWMT.ensureBufferFor(work + emnapiAWMT.offset.status + 4), work + emnapiAWMT.offset.status, 1); + if (Atomics.load(statusBuffer, 0) === 1) { + abort('unreachable'); + } + var execute = emnapiAWMT.getExecute(work); + var env = emnapiAWMT.getEnv(work); + var data = emnapiAWMT.getData(work); + (wasmTable.get(execute))(env, data); + Atomics.store(statusBuffer, 0, 2); + var postMessage_1 = napiModule.postMessage; + postMessage_1({ + __emnapi__: { + type: 'async-work-complete', + payload: { work: work } + } + }); + mutex.lock(); + } + return 0; + } + function _emnapi_spawn_worker(f, globalAddress) { + if (typeof onCreateWorker !== 'function') { + throw new TypeError('`options.onCreateWorker` is not a function'); + } + var promises = []; + var args = []; + if (!('emnapi_async_worker_create' in wasmInstance.exports)) { + throw new TypeError('`emnapi_async_worker_create` is not exported, please try to add `--export=emnapi_async_worker_create` to linker flags'); + } + args.push(wasmInstance.exports.emnapi_async_worker_create(0, 0)); + var handleError = function (e) { + if ('message' in e && (e.message.indexOf('RuntimeError') !== -1 || e.message.indexOf('unreachable') !== -1)) { + emnapiAWMT.terminateWorkers(); + } + }; + var ret; + try { + var worker_1 = onCreateWorker({ type: 'async-work', name: 'emnapi-async-worker' }); + var p = PThread.loadWasmModuleToWorker(worker_1); + if (ENVIRONMENT_IS_NODE) { + worker_1.on('error', handleError); + } + else { + worker_1.addEventListener('error', handleError, false); + } + emnapiAWMT.addListener(worker_1); + emnapiTSFN.addListener(worker_1); + promises.push(p.then(function () { + if (typeof worker_1.unref === 'function') { + worker_1.unref(); + } + })); + ret = emnapiAWMT.pool.push(worker_1) - 1; + var arg = args[0]; + worker_1.threadBlockBase = arg; + worker_1.postMessage({ + __emnapi__: { + type: 'async-worker-init', + payload: { arg: arg, func: [f, globalAddress] } + } + }); + } + catch (err) { + var arg = args[0]; + _free(arg); + throw err; + } + return ret; + } + function initWorker(startArg, func) { + if (napiModule.childThread) { + if (typeof wasmInstance.exports.emnapi_async_worker_init !== 'function') { + throw new TypeError('`emnapi_async_worker_init` is not exported, please try to add `--export=emnapi_async_worker_init` to linker flags'); + } + wasmInstance.exports.emnapi_async_worker_init(startArg); + (wasmTable.get(func[0]))(func[1]); + } + else { + throw new Error('startThread is only available in child threads'); + } + } + napiModule.initWorker = initWorker; + var asyncWorkMod = Object.freeze({ + __proto__: null, + _emnapi_async_worker: _emnapi_async_worker, + _emnapi_spawn_worker: _emnapi_spawn_worker, + napi_cancel_async_work: napi_cancel_async_work, + napi_create_async_work: napi_create_async_work, + napi_delete_async_work: napi_delete_async_work, + napi_queue_async_work: napi_queue_async_work + }); + var emnapiExternalMemory = { + registry: typeof FinalizationRegistry === 'function' ? new FinalizationRegistry(function (_pointer) { _free(_pointer); }) : undefined, + table: new WeakMap(), + wasmMemoryViewTable: new WeakMap(), + intrinsics: undefined, + init: function () { + var _a; + emnapiExternalMemory.registry = typeof FinalizationRegistry === 'function' ? new FinalizationRegistry(function (_pointer) { _free(_pointer); }) : undefined; + emnapiExternalMemory.table = new WeakMap(); + emnapiExternalMemory.wasmMemoryViewTable = new WeakMap(); + var sharedArrayBufferByteLength = typeof SharedArrayBuffer === 'function' + ? (_a = Object.getOwnPropertyDescriptor(SharedArrayBuffer.prototype, 'byteLength')) === null || _a === void 0 ? void 0 : _a.get + : undefined; + emnapiExternalMemory.intrinsics = { + isView: ArrayBuffer.isView, + typedArray: { + buffer: Object.getOwnPropertyDescriptor(Object.getPrototypeOf(Uint8Array.prototype), 'buffer').get, + byteOffset: Object.getOwnPropertyDescriptor(Object.getPrototypeOf(Uint8Array.prototype), 'byteOffset').get, + length: Object.getOwnPropertyDescriptor(Object.getPrototypeOf(Uint8Array.prototype), 'length').get, + tag: Object.getOwnPropertyDescriptor(Object.getPrototypeOf(Uint8Array.prototype), Symbol.toStringTag).get + }, + dataView: { + buffer: Object.getOwnPropertyDescriptor(DataView.prototype, 'buffer').get, + byteOffset: Object.getOwnPropertyDescriptor(DataView.prototype, 'byteOffset').get, + byteLength: Object.getOwnPropertyDescriptor(DataView.prototype, 'byteLength').get + }, + arrayBuffer: { + byteLength: Object.getOwnPropertyDescriptor(ArrayBuffer.prototype, 'byteLength').get + }, + sharedArrayBuffer: sharedArrayBufferByteLength !== undefined + ? { + byteLength: sharedArrayBufferByteLength + } + : undefined, + ctors: { + Int8Array: Int8Array, + Uint8Array: Uint8Array, + Uint8ClampedArray: Uint8ClampedArray, + Int16Array: Int16Array, + Uint16Array: Uint16Array, + Int32Array: Int32Array, + Uint32Array: Uint32Array, + Float16Array: typeof Float16Array === 'function' ? Float16Array : undefined, + Float32Array: Float32Array, + Float64Array: Float64Array, + BigInt64Array: BigInt64Array, + BigUint64Array: BigUint64Array + }, + bufferFrom: undefined + }; + }, + isSharedArrayBuffer: function (value) { + var sharedArrayBuffer = emnapiExternalMemory.intrinsics.sharedArrayBuffer; + if (sharedArrayBuffer !== undefined) { + if (typeof SharedArrayBuffer === 'function' && value instanceof SharedArrayBuffer) + return true; + try { + sharedArrayBuffer.byteLength.call(value); + return true; + } + catch (_) { + return false; + } + } + try { + emnapiExternalMemory.intrinsics.arrayBuffer.byteLength.call(value); + return false; + } + catch (_) { } + return Object.prototype.toString.call(value) === '[object SharedArrayBuffer]'; + }, + isDetachedArrayBuffer: function (arrayBuffer) { + if (emnapiExternalMemory.bufferByteLength(arrayBuffer) === 0) { + try { + new Uint8Array(arrayBuffer); + } + catch (_) { + return true; + } + } + return false; + }, + bufferByteLength: function (buffer) { + var _a; + var intrinsics = emnapiExternalMemory.intrinsics; + try { + return intrinsics.arrayBuffer.byteLength.call(buffer); + } + catch (err) { + var sharedArrayBuffer = intrinsics.sharedArrayBuffer; + if (sharedArrayBuffer !== undefined) { + return sharedArrayBuffer.byteLength.call(buffer); + } + var proto = Object.getPrototypeOf(buffer); + var get = proto !== null && proto !== undefined + ? (_a = Object.getOwnPropertyDescriptor(proto, 'byteLength')) === null || _a === void 0 ? void 0 : _a.get + : undefined; + if (get === undefined) + throw err; + return get.call(buffer); + } + }, + viewBuffer: function (view) { + var intrinsics = emnapiExternalMemory.intrinsics; + return intrinsics.typedArray.tag.call(view) === undefined + ? intrinsics.dataView.buffer.call(view) + : intrinsics.typedArray.buffer.call(view); + }, + viewByteOffset: function (view) { + var intrinsics = emnapiExternalMemory.intrinsics; + return intrinsics.typedArray.tag.call(view) === undefined + ? intrinsics.dataView.byteOffset.call(view) + : intrinsics.typedArray.byteOffset.call(view); + }, + viewLength: function (view) { + var intrinsics = emnapiExternalMemory.intrinsics; + return intrinsics.typedArray.tag.call(view) === undefined + ? intrinsics.dataView.byteLength.call(view) + : intrinsics.typedArray.length.call(view); + }, + getBufferFrom: function () { + var _a; + return (_a = emnapiExternalMemory.intrinsics.bufferFrom) !== null && _a !== void 0 ? _a : (emnapiExternalMemory.intrinsics.bufferFrom = emnapiCtx.feature.Buffer.from); + }, + getArrayBufferPointer: function (arrayBuffer, shouldCopy) { + var _a; + var info = { + address: 0, + ownership: 0, + runtimeAllocated: 0 + }; + if (arrayBuffer === wasmMemory.buffer) { + return info; + } + var isDetached = emnapiExternalMemory.isDetachedArrayBuffer(arrayBuffer); + if (emnapiExternalMemory.table.has(arrayBuffer)) { + var cachedInfo = emnapiExternalMemory.table.get(arrayBuffer); + if (isDetached) { + cachedInfo.address = 0; + return cachedInfo; + } + if (shouldCopy && cachedInfo.ownership === 0 && cachedInfo.runtimeAllocated === 1) { + new Uint8Array(wasmMemory.buffer).set(new Uint8Array(arrayBuffer), cachedInfo.address); + } + return cachedInfo; + } + var byteLength = emnapiExternalMemory.bufferByteLength(arrayBuffer); + if (isDetached || (byteLength === 0)) { + return info; + } + if (!shouldCopy) { + return info; + } + var pointer = _malloc(byteLength); + if (!pointer) + throw new Error('Out of memory'); + pointer >>>= 0; + new Uint8Array(wasmMemory.buffer).set(new Uint8Array(arrayBuffer), pointer); + info.address = pointer; + info.ownership = emnapiExternalMemory.registry ? 0 : 1; + info.runtimeAllocated = 1; + emnapiExternalMemory.table.set(arrayBuffer, info); + (_a = emnapiExternalMemory.registry) === null || _a === void 0 ? void 0 : _a.register(arrayBuffer, pointer); + return info; + }, + getOrUpdateMemoryView: function (view) { + var intrinsics = emnapiExternalMemory.intrinsics; + var tag = intrinsics.typedArray.tag.call(view); + var isDataView = tag === undefined; + var buffer = isDataView ? intrinsics.dataView.buffer.call(view) : intrinsics.typedArray.buffer.call(view); + if (buffer === wasmMemory.buffer) { + if (!emnapiExternalMemory.wasmMemoryViewTable.has(view)) { + emnapiExternalMemory.wasmMemoryViewTable.set(view, { + Ctor: isDataView ? DataView : intrinsics.ctors[tag], + address: isDataView ? intrinsics.dataView.byteOffset.call(view) : intrinsics.typedArray.byteOffset.call(view), + length: isDataView ? intrinsics.dataView.byteLength.call(view) : intrinsics.typedArray.length.call(view), + ownership: 1, + runtimeAllocated: 0 + }); + } + return view; + } + var maybeOldWasmMemory = emnapiExternalMemory.isDetachedArrayBuffer(buffer) || emnapiExternalMemory.isSharedArrayBuffer(buffer); + if (maybeOldWasmMemory && emnapiExternalMemory.wasmMemoryViewTable.has(view)) { + var info = emnapiExternalMemory.wasmMemoryViewTable.get(view); + var Ctor = info.Ctor; + var newView = void 0; + var Buffer_1 = emnapiCtx.feature.Buffer; + if (typeof Buffer_1 === 'function' && Ctor === Buffer_1) { + newView = emnapiExternalMemory.getBufferFrom()(wasmMemory.buffer, info.address, info.length); + } + else { + newView = new Ctor(wasmMemory.buffer, info.address, info.length); + } + emnapiExternalMemory.wasmMemoryViewTable.set(newView, info); + return newView; + } + return view; + }, + getViewPointer: function (view, shouldCopy) { + view = emnapiExternalMemory.getOrUpdateMemoryView(view); + var buffer = emnapiExternalMemory.viewBuffer(view); + if (buffer === wasmMemory.buffer) { + if (emnapiExternalMemory.wasmMemoryViewTable.has(view)) { + var _a = emnapiExternalMemory.wasmMemoryViewTable.get(view), address_1 = _a.address, ownership_1 = _a.ownership, runtimeAllocated_1 = _a.runtimeAllocated; + return { address: address_1, ownership: ownership_1, runtimeAllocated: runtimeAllocated_1, view: view }; + } + return { address: emnapiExternalMemory.viewByteOffset(view), ownership: 1, runtimeAllocated: 0, view: view }; + } + var _b = emnapiExternalMemory.getArrayBufferPointer(buffer, shouldCopy), address = _b.address, ownership = _b.ownership, runtimeAllocated = _b.runtimeAllocated; + return { address: address === 0 ? 0 : (address + emnapiExternalMemory.viewByteOffset(view)), ownership: ownership, runtimeAllocated: runtimeAllocated, view: view }; + } + }; + var emnapiExternalSAB = { + registry: undefined, + handleTable: new WeakMap(), + init: function () { + emnapiExternalSAB.handleTable = new WeakMap(); + emnapiExternalSAB.registry = typeof FinalizationRegistry === 'function' + ? new FinalizationRegistry(function (metaPtr) { + emnapiExternalSAB.release(metaPtr); + }) + : undefined; + }, + allocMeta: function (external_data, byte_length, finalize_cb, finalize_data, finalize_hint) { + var size = 4 * 6; + var metaPtr = _malloc(size); + if (!metaPtr) + throw new Error('Out of memory'); + metaPtr >>>= 0; + Atomics.store(new Int32Array(wasmMemory.buffer, metaPtr, 1), 0, 1); + var HEAP_DATA_VIEW = new DataView(wasmMemory.buffer), GET_HEAP_DATA_VIEW = function () { return HEAP_DATA_VIEW.buffer === wasmMemory.buffer ? HEAP_DATA_VIEW : (HEAP_DATA_VIEW = new DataView(wasmMemory.buffer)); }; + GET_HEAP_DATA_VIEW().setUint32(metaPtr + 4, external_data, true); + GET_HEAP_DATA_VIEW().setUint32(metaPtr + 8, byte_length, true); + GET_HEAP_DATA_VIEW().setUint32(metaPtr + 12, finalize_cb, true); + GET_HEAP_DATA_VIEW().setUint32(metaPtr + 16, finalize_data, true); + GET_HEAP_DATA_VIEW().setUint32(metaPtr + 20, finalize_hint, true); + return metaPtr; + }, + readMeta: function (metaPtr) { + var HEAP_DATA_VIEW = new DataView(wasmMemory.buffer), GET_HEAP_DATA_VIEW = function () { return HEAP_DATA_VIEW.buffer === wasmMemory.buffer ? HEAP_DATA_VIEW : (HEAP_DATA_VIEW = new DataView(wasmMemory.buffer)); }; + var external_data = GET_HEAP_DATA_VIEW().getUint32(metaPtr + 4, true); + var byte_length = GET_HEAP_DATA_VIEW().getUint32(metaPtr + 8, true); + var finalize_cb = GET_HEAP_DATA_VIEW().getUint32(metaPtr + 12, true); + var finalize_data = GET_HEAP_DATA_VIEW().getUint32(metaPtr + 16, true); + var finalize_hint = GET_HEAP_DATA_VIEW().getUint32(metaPtr + 20, true); + return { external_data: external_data, byte_length: byte_length, finalize_cb: finalize_cb, finalize_data: finalize_data, finalize_hint: finalize_hint }; + }, + release: function (metaPtr) { + var oldRefcount = Atomics.sub(new Int32Array(wasmMemory.buffer, metaPtr, 1), 0, 1); + if (oldRefcount === 1) { + var info = emnapiExternalSAB.readMeta(metaPtr); + var finalize_cb = info.finalize_cb; + if (finalize_cb) { + var finalize_data = info.finalize_data; + var finalize_hint = info.finalize_hint; + (wasmTable.get(finalize_cb))(finalize_data, finalize_hint); + } + _free(metaPtr); + } + } + }; + var emnapiString = { + utf8Decoder: undefined, + utf16Decoder: undefined, + init: function () { + var fallbackDecoder = { + decode: function (bytes) { + var inputIndex = 0; + var pendingSize = Math.min(0x1000, bytes.length + 1); + var pending = new Uint16Array(pendingSize); + var chunks = []; + var pendingIndex = 0; + for (;;) { + var more = inputIndex < bytes.length; + if (!more || (pendingIndex >= pendingSize - 1)) { + var subarray = pending.subarray(0, pendingIndex); + var arraylike = subarray; + chunks.push(String.fromCharCode.apply(null, arraylike)); + if (!more) { + return chunks.join(''); + } + bytes = bytes.subarray(inputIndex); + inputIndex = 0; + pendingIndex = 0; + } + var byte1 = bytes[inputIndex++]; + if ((byte1 & 0x80) === 0) { + pending[pendingIndex++] = byte1; + } + else if ((byte1 & 0xe0) === 0xc0) { + var byte2 = bytes[inputIndex++] & 0x3f; + pending[pendingIndex++] = ((byte1 & 0x1f) << 6) | byte2; + } + else if ((byte1 & 0xf0) === 0xe0) { + var byte2 = bytes[inputIndex++] & 0x3f; + var byte3 = bytes[inputIndex++] & 0x3f; + pending[pendingIndex++] = ((byte1 & 0x1f) << 12) | (byte2 << 6) | byte3; + } + else if ((byte1 & 0xf8) === 0xf0) { + var byte2 = bytes[inputIndex++] & 0x3f; + var byte3 = bytes[inputIndex++] & 0x3f; + var byte4 = bytes[inputIndex++] & 0x3f; + var codepoint = ((byte1 & 0x07) << 0x12) | (byte2 << 0x0c) | (byte3 << 0x06) | byte4; + if (codepoint > 0xffff) { + codepoint -= 0x10000; + pending[pendingIndex++] = (codepoint >>> 10) & 0x3ff | 0xd800; + codepoint = 0xdc00 | codepoint & 0x3ff; + } + pending[pendingIndex++] = codepoint; + } + else ; + } + } + }; + var utf8Decoder; + utf8Decoder = typeof TextDecoder === 'function' ? new TextDecoder() : fallbackDecoder; + emnapiString.utf8Decoder = utf8Decoder; + var fallbackDecoder2 = { + decode: function (input) { + var bytes = new Uint16Array(input.buffer, input.byteOffset, input.byteLength / 2); + if (bytes.length <= 0x1000) { + return String.fromCharCode.apply(null, bytes); + } + var chunks = []; + var i = 0; + var len = 0; + for (; i < bytes.length; i += len) { + len = Math.min(0x1000, bytes.length - i); + chunks.push(String.fromCharCode.apply(null, bytes.subarray(i, i + len))); + } + return chunks.join(''); + } + }; + var utf16Decoder; + utf16Decoder = typeof TextDecoder === 'function' ? new TextDecoder('utf-16le') : fallbackDecoder2; + emnapiString.utf16Decoder = utf16Decoder; + }, + lengthBytesUTF8: function (str) { + var c; + var len = 0; + for (var i = 0; i < str.length; ++i) { + c = str.charCodeAt(i); + if (c <= 0x7F) { + len++; + } + else if (c <= 0x7FF) { + len += 2; + } + else if (c >= 0xD800 && c <= 0xDFFF) { + len += 4; + ++i; + } + else { + len += 3; + } + } + return len; + }, + UTF8ToString: function (ptr, length) { + if (!ptr || !length) + return ''; + ptr >>>= 0; + var HEAPU8 = new Uint8Array(wasmMemory.buffer); + var end = ptr; + if (length === -1 || length === 4294967295) { + for (; HEAPU8[end];) + ++end; + } + else { + end = ptr + (length >>> 0); + } + length = end - ptr; + if (length <= 16) { + var idx = ptr; + var str = ''; + while (idx < end) { + var u0 = HEAPU8[idx++]; + if (!(u0 & 0x80)) { + str += String.fromCharCode(u0); + continue; + } + var u1 = HEAPU8[idx++] & 63; + if ((u0 & 0xE0) === 0xC0) { + str += String.fromCharCode(((u0 & 31) << 6) | u1); + continue; + } + var u2 = HEAPU8[idx++] & 63; + if ((u0 & 0xF0) === 0xE0) { + u0 = ((u0 & 15) << 12) | (u1 << 6) | u2; + } + else { + u0 = ((u0 & 7) << 18) | (u1 << 12) | (u2 << 6) | (HEAPU8[idx++] & 63); + } + if (u0 < 0x10000) { + str += String.fromCharCode(u0); + } + else { + var ch = u0 - 0x10000; + str += String.fromCharCode(0xD800 | (ch >> 10), 0xDC00 | (ch & 0x3FF)); + } + } + return str; + } + return emnapiString.utf8Decoder.decode(((typeof SharedArrayBuffer === "function" && HEAPU8.buffer instanceof SharedArrayBuffer) || (Object.prototype.toString.call(HEAPU8.buffer) === "[object SharedArrayBuffer]")) ? HEAPU8.slice(ptr, end) : HEAPU8.subarray(ptr, end)); + }, + stringToUTF8: function (str, outPtr, maxBytesToWrite) { + var HEAPU8 = new Uint8Array(wasmMemory.buffer); + var outIdx = outPtr; + outIdx >>>= 0; + if (!(maxBytesToWrite > 0)) { + return 0; + } + var startIdx = outIdx; + var endIdx = outIdx + maxBytesToWrite - 1; + for (var i = 0; i < str.length; ++i) { + var u = str.charCodeAt(i); + if (u >= 0xD800 && u <= 0xDFFF) { + var u1 = str.charCodeAt(++i); + u = 0x10000 + ((u & 0x3FF) << 10) | (u1 & 0x3FF); + } + if (u <= 0x7F) { + if (outIdx >= endIdx) + break; + HEAPU8[outIdx++] = u; + } + else if (u <= 0x7FF) { + if (outIdx + 1 >= endIdx) + break; + HEAPU8[outIdx++] = 0xC0 | (u >> 6); + HEAPU8[outIdx++] = 0x80 | (u & 63); + } + else if (u <= 0xFFFF) { + if (outIdx + 2 >= endIdx) + break; + HEAPU8[outIdx++] = 0xE0 | (u >> 12); + HEAPU8[outIdx++] = 0x80 | ((u >> 6) & 63); + HEAPU8[outIdx++] = 0x80 | (u & 63); + } + else { + if (outIdx + 3 >= endIdx) + break; + HEAPU8[outIdx++] = 0xF0 | (u >> 18); + HEAPU8[outIdx++] = 0x80 | ((u >> 12) & 63); + HEAPU8[outIdx++] = 0x80 | ((u >> 6) & 63); + HEAPU8[outIdx++] = 0x80 | (u & 63); + } + } + HEAPU8[outIdx] = 0; + return outIdx - startIdx; + }, + UTF16ToString: function (ptr, length) { + if (!ptr || !length) + return ''; + ptr >>>= 0; + var end = ptr; + if (length === -1 || length === 4294967295) { + var idx = end >>> 1; + var HEAPU16 = new Uint16Array(wasmMemory.buffer); + while (HEAPU16[idx]) + ++idx; + end = (idx << 1) >>> 0; + } + else { + end = ptr + (length >>> 0) * 2; + } + length = end - ptr; + if (length <= 32) { + return String.fromCharCode.apply(null, new Uint16Array(wasmMemory.buffer, ptr, length / 2)); + } + var HEAPU8 = new Uint8Array(wasmMemory.buffer); + return emnapiString.utf16Decoder.decode(((typeof SharedArrayBuffer === "function" && HEAPU8.buffer instanceof SharedArrayBuffer) || (Object.prototype.toString.call(HEAPU8.buffer) === "[object SharedArrayBuffer]")) ? HEAPU8.slice(ptr, end) : HEAPU8.subarray(ptr, end)); + }, + stringToUTF16: function (str, outPtr, maxBytesToWrite) { + if (maxBytesToWrite === undefined) { + maxBytesToWrite = 0x7FFFFFFF; + } + if (maxBytesToWrite < 2) + return 0; + maxBytesToWrite -= 2; + var startPtr = outPtr; + var numCharsToWrite = (maxBytesToWrite < str.length * 2) ? (maxBytesToWrite / 2) : str.length; + var HEAP_DATA_VIEW = new DataView(wasmMemory.buffer), GET_HEAP_DATA_VIEW = function () { return HEAP_DATA_VIEW.buffer === wasmMemory.buffer ? HEAP_DATA_VIEW : (HEAP_DATA_VIEW = new DataView(wasmMemory.buffer)); }; + for (var i = 0; i < numCharsToWrite; ++i) { + var codeUnit = str.charCodeAt(i); + GET_HEAP_DATA_VIEW().setInt16(outPtr, codeUnit, true); + outPtr += 2; + } + GET_HEAP_DATA_VIEW().setInt16(outPtr, 0, true); + return outPtr - startPtr; + }, + newString: function (env, str, length, result, stringMaker) { + length >>>= 0; + if (!env) + return 1; + var envObject = emnapiCtx.envStore.get(env); + envObject.checkGCAccess(); + var autoLength = length === -1 || length === 4294967295; + var sizelength = length >>> 0; + if (length !== 0) { + if (!str) + return envObject.setLastError(1); + } + if (!result) + return envObject.setLastError(1); + if (!(autoLength || (sizelength <= 2147483647))) + return envObject.setLastError(1); + str >>>= 0; + var strValue = stringMaker(str, autoLength, sizelength); + result >>>= 0; + var value = emnapiCtx.addToCurrentScope(strValue).id; + var HEAP_DATA_VIEW = new DataView(wasmMemory.buffer), GET_HEAP_DATA_VIEW = function () { return HEAP_DATA_VIEW.buffer === wasmMemory.buffer ? HEAP_DATA_VIEW : (HEAP_DATA_VIEW = new DataView(wasmMemory.buffer)); }; + GET_HEAP_DATA_VIEW().setUint32(result, value, true); + return envObject.clearLastError(); + }, + newExternalString: function (env, str, length, finalize_callback, finalize_hint, result, copied, createApi, stringMaker) { + length >>>= 0; + if (!env) + return 1; + var envObject = emnapiCtx.envStore.get(env); + envObject.checkGCAccess(); + var autoLength = length === -1 || length === 4294967295; + var sizelength = length >>> 0; + if (length !== 0) { + if (!str) + return envObject.setLastError(1); + } + if (!result) + return envObject.setLastError(1); + if (!(autoLength || (sizelength <= 2147483647))) + return envObject.setLastError(1); + var status = createApi(env, str, length, result); + if (status === 0) { + if (copied) { + var HEAP_DATA_VIEW = new DataView(wasmMemory.buffer), GET_HEAP_DATA_VIEW = function () { return HEAP_DATA_VIEW.buffer === wasmMemory.buffer ? HEAP_DATA_VIEW : (HEAP_DATA_VIEW = new DataView(wasmMemory.buffer)); }; + GET_HEAP_DATA_VIEW().setInt8(copied, 1, true); + } + if (finalize_callback) { + envObject.callFinalizer(finalize_callback, str, finalize_hint); + } + } + return status; + } + }; + function napi_get_array_length(env, value, result) { + if (!env) + return 1; + var envObject = emnapiCtx.envStore.get(env); + envObject.checkGCAccess(); + if (!envObject.tryCatch.isEmpty()) + return envObject.setLastError(10); + if (!envObject.canCallIntoJs()) + return envObject.setLastError(envObject.moduleApiVersion >= 10 ? 23 : 10); + envObject.clearLastError(); + try { + if (!value) + return envObject.setLastError(1); + if (!result) + return envObject.setLastError(1); + var handle = emnapiCtx.handleStore.get(value); + if (!handle.isArray()) { + return envObject.setLastError(8); + } + result >>>= 0; + var v = handle.value.length >>> 0; + var HEAP_DATA_VIEW = new DataView(wasmMemory.buffer), GET_HEAP_DATA_VIEW = function () { return HEAP_DATA_VIEW.buffer === wasmMemory.buffer ? HEAP_DATA_VIEW : (HEAP_DATA_VIEW = new DataView(wasmMemory.buffer)); }; + GET_HEAP_DATA_VIEW().setUint32(result, v, true); + return envObject.getReturnStatus(); + } + catch (err) { + envObject.tryCatch.setError(err); + return envObject.setLastError(10); + } + } + function napi_get_arraybuffer_info(env, arraybuffer, data, byte_length) { + if (!env) + return 1; + var envObject = emnapiCtx.envStore.get(env); + envObject.checkGCAccess(); + if (!arraybuffer) + return envObject.setLastError(1); + var handle = emnapiCtx.handleStore.get(arraybuffer); + if (!handle.isArrayBuffer() && !emnapiExternalMemory.isSharedArrayBuffer(handle.value)) { + return envObject.setLastError(1); + } + var HEAP_DATA_VIEW = new DataView(wasmMemory.buffer), GET_HEAP_DATA_VIEW = function () { return HEAP_DATA_VIEW.buffer === wasmMemory.buffer ? HEAP_DATA_VIEW : (HEAP_DATA_VIEW = new DataView(wasmMemory.buffer)); }; + if (data) { + data >>>= 0; + var p = emnapiExternalMemory.getArrayBufferPointer(handle.value, true).address; + GET_HEAP_DATA_VIEW().setUint32(data, p, true); + } + if (byte_length) { + byte_length >>>= 0; + var len = emnapiExternalMemory.bufferByteLength(handle.value); + GET_HEAP_DATA_VIEW().setUint32(byte_length, len, true); + } + return envObject.clearLastError(); + } + function node_api_set_prototype(env, object, value) { + if (!env) + return 1; + var envObject = emnapiCtx.envStore.get(env); + envObject.checkGCAccess(); + if (!envObject.tryCatch.isEmpty()) + return envObject.setLastError(10); + if (!envObject.canCallIntoJs()) + return envObject.setLastError(envObject.moduleApiVersion >= 10 ? 23 : 10); + envObject.clearLastError(); + try { + if (!value) + return envObject.setLastError(1); + var obj = emnapiCtx.handleStore.get(object).value; + if (obj == null) { + throw new TypeError('Cannot convert undefined or null to object'); + } + var type = typeof obj; + var v = void 0; + try { + v = (type === 'object' && obj !== null) || type === 'function' ? obj : Object(obj); + } + catch (_) { + return envObject.setLastError(2); + } + var val = emnapiCtx.handleStore.get(value).value; + Object.setPrototypeOf(v, val); + return envObject.getReturnStatus(); + } + catch (err) { + envObject.tryCatch.setError(err); + return envObject.setLastError(10); + } + } + function napi_get_prototype(env, value, result) { + if (!env) + return 1; + var envObject = emnapiCtx.envStore.get(env); + envObject.checkGCAccess(); + if (!envObject.tryCatch.isEmpty()) + return envObject.setLastError(10); + if (!envObject.canCallIntoJs()) + return envObject.setLastError(envObject.moduleApiVersion >= 10 ? 23 : 10); + envObject.clearLastError(); + try { + if (!value) + return envObject.setLastError(1); + if (!result) + return envObject.setLastError(1); + var handle = emnapiCtx.handleStore.get(value); + if (handle.value == null) { + throw new TypeError('Cannot convert undefined or null to object'); + } + var v = void 0; + try { + v = handle.isObject() || handle.isFunction() ? handle.value : Object(handle.value); + } + catch (_) { + return envObject.setLastError(2); + } + result >>>= 0; + var p = envObject.ensureHandleId(Object.getPrototypeOf(v)); + var HEAP_DATA_VIEW = new DataView(wasmMemory.buffer), GET_HEAP_DATA_VIEW = function () { return HEAP_DATA_VIEW.buffer === wasmMemory.buffer ? HEAP_DATA_VIEW : (HEAP_DATA_VIEW = new DataView(wasmMemory.buffer)); }; + GET_HEAP_DATA_VIEW().setUint32(result, p, true); + return envObject.getReturnStatus(); + } + catch (err) { + envObject.tryCatch.setError(err); + return envObject.setLastError(10); + } + } + function napi_get_typedarray_info(env, typedarray, type, length, data, arraybuffer, byte_offset) { + if (!env) + return 1; + var envObject = emnapiCtx.envStore.get(env); + envObject.checkGCAccess(); + if (!typedarray) + return envObject.setLastError(1); + var handle = emnapiCtx.handleStore.get(typedarray); + if (!(emnapiExternalMemory.intrinsics.isView(handle.value))) { + return envObject.setLastError(1); + } + var v = handle.value; + var HEAP_DATA_VIEW = new DataView(wasmMemory.buffer), GET_HEAP_DATA_VIEW = function () { return HEAP_DATA_VIEW.buffer === wasmMemory.buffer ? HEAP_DATA_VIEW : (HEAP_DATA_VIEW = new DataView(wasmMemory.buffer)); }; + if (type) { + type >>>= 0; + var t = void 0; + switch (emnapiExternalMemory.intrinsics.typedArray.tag.call(v)) { + case 'Int8Array': + t = 0; + break; + case 'Uint8Array': + t = 1; + break; + case 'Uint8ClampedArray': + t = 2; + break; + case 'Int16Array': + t = 3; + break; + case 'Uint16Array': + t = 4; + break; + case 'Int32Array': + t = 5; + break; + case 'Uint32Array': + t = 6; + break; + case 'Float16Array': + t = 11; + break; + case 'Float32Array': + t = 7; + break; + case 'Float64Array': + t = 8; + break; + case 'BigInt64Array': + t = 9; + break; + case 'BigUint64Array': + t = 10; + break; + default: + return envObject.setLastError(9); + } + GET_HEAP_DATA_VIEW().setInt32(type, t, true); + } + v = emnapiExternalMemory.getOrUpdateMemoryView(v); + if (length) { + length >>>= 0; + var len = emnapiExternalMemory.viewLength(v); + GET_HEAP_DATA_VIEW().setUint32(length, len, true); + } + if (data || arraybuffer) { + if (data) { + data >>>= 0; + var vp = emnapiExternalMemory.getViewPointer(v, true); + v = vp.view; + var p = vp.address; + GET_HEAP_DATA_VIEW().setUint32(data, p, true); + } + if (arraybuffer) { + arraybuffer >>>= 0; + var ab = envObject.ensureHandleId(emnapiExternalMemory.viewBuffer(v)); + GET_HEAP_DATA_VIEW().setUint32(arraybuffer, ab, true); + } + } + if (byte_offset) { + byte_offset >>>= 0; + var offset = emnapiExternalMemory.viewByteOffset(v); + GET_HEAP_DATA_VIEW().setUint32(byte_offset, offset, true); + } + return envObject.clearLastError(); + } + function napi_get_buffer_info(env, buffer, data, length) { + if (!env) + return 1; + var envObject = emnapiCtx.envStore.get(env); + envObject.checkGCAccess(); + if (!buffer) + return envObject.setLastError(1); + var handle = emnapiCtx.handleStore.get(buffer); + var Buffer = emnapiCtx.feature.Buffer; + var bool = (emnapiExternalMemory.intrinsics.isView(handle.value) || (typeof Buffer === 'function' && Buffer.isBuffer(handle.value))); + if (!bool) + return envObject.setLastError(1); + if (emnapiExternalMemory.intrinsics.typedArray.tag.call(handle.value) === undefined) { + return napi_get_dataview_info(env, buffer, length, data, 0, 0); + } + return napi_get_typedarray_info(env, buffer, 0, length, data, 0, 0); + } + function napi_get_dataview_info(env, dataview, byte_length, data, arraybuffer, byte_offset) { + if (!env) + return 1; + var envObject = emnapiCtx.envStore.get(env); + envObject.checkGCAccess(); + if (!dataview) + return envObject.setLastError(1); + var handle = emnapiCtx.handleStore.get(dataview); + if (!(emnapiExternalMemory.intrinsics.isView(handle.value)) || emnapiExternalMemory.intrinsics.typedArray.tag.call(handle.value) !== undefined) { + return envObject.setLastError(1); + } + var v = emnapiExternalMemory.getOrUpdateMemoryView(handle.value); + var HEAP_DATA_VIEW = new DataView(wasmMemory.buffer), GET_HEAP_DATA_VIEW = function () { return HEAP_DATA_VIEW.buffer === wasmMemory.buffer ? HEAP_DATA_VIEW : (HEAP_DATA_VIEW = new DataView(wasmMemory.buffer)); }; + if (byte_length) { + byte_length >>>= 0; + var len = emnapiExternalMemory.viewLength(v); + GET_HEAP_DATA_VIEW().setUint32(byte_length, len, true); + } + if (data || arraybuffer) { + if (data) { + data >>>= 0; + var vp = emnapiExternalMemory.getViewPointer(v, true); + v = vp.view; + var p = vp.address; + GET_HEAP_DATA_VIEW().setUint32(data, p, true); + } + if (arraybuffer) { + arraybuffer >>>= 0; + var ab = envObject.ensureHandleId(emnapiExternalMemory.viewBuffer(v)); + GET_HEAP_DATA_VIEW().setUint32(arraybuffer, ab, true); + } + } + if (byte_offset) { + byte_offset >>>= 0; + var offset = emnapiExternalMemory.viewByteOffset(v); + GET_HEAP_DATA_VIEW().setUint32(byte_offset, offset, true); + } + return envObject.clearLastError(); + } + function napi_get_date_value(env, value, result) { + var v; + if (!env) + return 1; + var envObject = emnapiCtx.envStore.get(env); + envObject.checkGCAccess(); + if (!envObject.tryCatch.isEmpty()) + return envObject.setLastError(10); + if (!envObject.canCallIntoJs()) + return envObject.setLastError(envObject.moduleApiVersion >= 10 ? 23 : 10); + envObject.clearLastError(); + try { + if (!value) + return envObject.setLastError(1); + if (!result) + return envObject.setLastError(1); + var handle = emnapiCtx.handleStore.get(value); + if (!handle.isDate()) { + return envObject.setLastError(1); + } + result >>>= 0; + v = handle.value.valueOf(); + var HEAP_DATA_VIEW = new DataView(wasmMemory.buffer), GET_HEAP_DATA_VIEW = function () { return HEAP_DATA_VIEW.buffer === wasmMemory.buffer ? HEAP_DATA_VIEW : (HEAP_DATA_VIEW = new DataView(wasmMemory.buffer)); }; + GET_HEAP_DATA_VIEW().setFloat64(result, v, true); + return envObject.getReturnStatus(); + } + catch (err) { + envObject.tryCatch.setError(err); + return envObject.setLastError(10); + } + } + function napi_get_value_bool(env, value, result) { + if (!env) + return 1; + var envObject = emnapiCtx.envStore.get(env); + envObject.checkGCAccess(); + if (!value) + return envObject.setLastError(1); + if (!result) + return envObject.setLastError(1); + var handle = emnapiCtx.handleStore.get(value); + if (typeof handle.value !== 'boolean') { + return envObject.setLastError(7); + } + result >>>= 0; + var r = handle.value ? 1 : 0; + var HEAP_DATA_VIEW = new DataView(wasmMemory.buffer), GET_HEAP_DATA_VIEW = function () { return HEAP_DATA_VIEW.buffer === wasmMemory.buffer ? HEAP_DATA_VIEW : (HEAP_DATA_VIEW = new DataView(wasmMemory.buffer)); }; + GET_HEAP_DATA_VIEW().setInt8(result, r, true); + return envObject.clearLastError(); + } + function napi_get_value_double(env, value, result) { + if (!env) + return 1; + var envObject = emnapiCtx.envStore.get(env); + envObject.checkGCAccess(); + if (!value) + return envObject.setLastError(1); + if (!result) + return envObject.setLastError(1); + var handle = emnapiCtx.handleStore.get(value); + if (typeof handle.value !== 'number') { + return envObject.setLastError(6); + } + result >>>= 0; + var r = handle.value; + var HEAP_DATA_VIEW = new DataView(wasmMemory.buffer), GET_HEAP_DATA_VIEW = function () { return HEAP_DATA_VIEW.buffer === wasmMemory.buffer ? HEAP_DATA_VIEW : (HEAP_DATA_VIEW = new DataView(wasmMemory.buffer)); }; + GET_HEAP_DATA_VIEW().setFloat64(result, r, true); + return envObject.clearLastError(); + } + function napi_get_value_bigint_int64(env, value, result, lossless) { + if (!env) + return 1; + var envObject = emnapiCtx.envStore.get(env); + envObject.checkGCAccess(); + if (!emnapiCtx.feature.supportBigInt) { + return envObject.setLastError(9); + } + if (!value) + return envObject.setLastError(1); + if (!result) + return envObject.setLastError(1); + if (!lossless) + return envObject.setLastError(1); + var handle = emnapiCtx.handleStore.get(value); + var numberValue = handle.value; + if (typeof numberValue !== 'bigint') { + return envObject.setLastError(6); + } + lossless >>>= 0; + result >>>= 0; + var HEAP_DATA_VIEW = new DataView(wasmMemory.buffer), GET_HEAP_DATA_VIEW = function () { return HEAP_DATA_VIEW.buffer === wasmMemory.buffer ? HEAP_DATA_VIEW : (HEAP_DATA_VIEW = new DataView(wasmMemory.buffer)); }; + if ((numberValue >= (BigInt(-1) * (BigInt(1) << BigInt(63)))) && (numberValue < (BigInt(1) << BigInt(63)))) { + GET_HEAP_DATA_VIEW().setInt8(lossless, 1, true); + } + else { + GET_HEAP_DATA_VIEW().setInt8(lossless, 0, true); + numberValue = numberValue & ((BigInt(1) << BigInt(64)) - BigInt(1)); + if (numberValue >= (BigInt(1) << BigInt(63))) { + numberValue = numberValue - (BigInt(1) << BigInt(64)); + } + } + var low = Number(numberValue & BigInt(0xffffffff)); + var high = Number(numberValue >> BigInt(32)); + GET_HEAP_DATA_VIEW().setInt32(result, low, true); + GET_HEAP_DATA_VIEW().setInt32(result + 4, high, true); + return envObject.clearLastError(); + } + function napi_get_value_bigint_uint64(env, value, result, lossless) { + if (!env) + return 1; + var envObject = emnapiCtx.envStore.get(env); + envObject.checkGCAccess(); + if (!emnapiCtx.feature.supportBigInt) { + return envObject.setLastError(9); + } + if (!value) + return envObject.setLastError(1); + if (!result) + return envObject.setLastError(1); + if (!lossless) + return envObject.setLastError(1); + var handle = emnapiCtx.handleStore.get(value); + var numberValue = handle.value; + if (typeof numberValue !== 'bigint') { + return envObject.setLastError(6); + } + lossless >>>= 0; + result >>>= 0; + var HEAP_DATA_VIEW = new DataView(wasmMemory.buffer), GET_HEAP_DATA_VIEW = function () { return HEAP_DATA_VIEW.buffer === wasmMemory.buffer ? HEAP_DATA_VIEW : (HEAP_DATA_VIEW = new DataView(wasmMemory.buffer)); }; + if ((numberValue >= BigInt(0)) && (numberValue < (BigInt(1) << BigInt(64)))) { + GET_HEAP_DATA_VIEW().setInt8(lossless, 1, true); + } + else { + GET_HEAP_DATA_VIEW().setInt8(lossless, 0, true); + numberValue = numberValue & ((BigInt(1) << BigInt(64)) - BigInt(1)); + } + var low = Number(numberValue & BigInt(0xffffffff)); + var high = Number(numberValue >> BigInt(32)); + GET_HEAP_DATA_VIEW().setUint32(result, low, true); + GET_HEAP_DATA_VIEW().setUint32(result + 4, high, true); + return envObject.clearLastError(); + } + function napi_get_value_bigint_words(env, value, sign_bit, word_count, words) { + if (!env) + return 1; + var envObject = emnapiCtx.envStore.get(env); + envObject.checkGCAccess(); + if (!emnapiCtx.feature.supportBigInt) { + return envObject.setLastError(9); + } + if (!value) + return envObject.setLastError(1); + if (!word_count) + return envObject.setLastError(1); + var handle = emnapiCtx.handleStore.get(value); + if (!handle.isBigInt()) { + return envObject.setLastError(17); + } + var isMinus = handle.value < BigInt(0); + sign_bit >>>= 0; + words >>>= 0; + word_count >>>= 0; + var HEAP_DATA_VIEW = new DataView(wasmMemory.buffer), GET_HEAP_DATA_VIEW = function () { return HEAP_DATA_VIEW.buffer === wasmMemory.buffer ? HEAP_DATA_VIEW : (HEAP_DATA_VIEW = new DataView(wasmMemory.buffer)); }; + var word_count_int = GET_HEAP_DATA_VIEW().getUint32(word_count, true); + word_count_int >>>= 0; + var wordCount = 0; + var bigintValue = isMinus ? (handle.value * BigInt(-1)) : handle.value; + while (bigintValue !== BigInt(0)) { + wordCount++; + bigintValue = bigintValue >> BigInt(64); + } + bigintValue = isMinus ? (handle.value * BigInt(-1)) : handle.value; + if (!sign_bit && !words) { + word_count_int = wordCount; + GET_HEAP_DATA_VIEW().setUint32(word_count, word_count_int, true); + } + else { + if (!sign_bit) + return envObject.setLastError(1); + if (!words) + return envObject.setLastError(1); + var wordsArr = []; + while (bigintValue !== BigInt(0)) { + var uint64 = bigintValue & ((BigInt(1) << BigInt(64)) - BigInt(1)); + wordsArr.push(uint64); + bigintValue = bigintValue >> BigInt(64); + } + var len = Math.min(word_count_int, wordsArr.length); + for (var i = 0; i < len; i++) { + var low = Number(wordsArr[i] & BigInt(0xffffffff)); + var high = Number(wordsArr[i] >> BigInt(32)); + GET_HEAP_DATA_VIEW().setUint32(words + i * 8, low, true); + GET_HEAP_DATA_VIEW().setUint32(words + (i * 8 + 4), high, true); + } + GET_HEAP_DATA_VIEW().setInt32(sign_bit, isMinus ? 1 : 0, true); + GET_HEAP_DATA_VIEW().setUint32(word_count, len, true); + } + return envObject.clearLastError(); + } + function napi_get_value_external(env, value, result) { + if (!env) + return 1; + var envObject = emnapiCtx.envStore.get(env); + envObject.checkGCAccess(); + if (!value) + return envObject.setLastError(1); + if (!result) + return envObject.setLastError(1); + var handle = emnapiCtx.handleStore.get(value); + if (!handle.isExternal()) { + return envObject.setLastError(1); + } + result >>>= 0; + var p = handle.data(); + var HEAP_DATA_VIEW = new DataView(wasmMemory.buffer), GET_HEAP_DATA_VIEW = function () { return HEAP_DATA_VIEW.buffer === wasmMemory.buffer ? HEAP_DATA_VIEW : (HEAP_DATA_VIEW = new DataView(wasmMemory.buffer)); }; + GET_HEAP_DATA_VIEW().setUint32(result, p, true); + return envObject.clearLastError(); + } + function napi_get_value_int32(env, value, result) { + if (!env) + return 1; + var envObject = emnapiCtx.envStore.get(env); + envObject.checkGCAccess(); + if (!value) + return envObject.setLastError(1); + if (!result) + return envObject.setLastError(1); + var handle = emnapiCtx.handleStore.get(value); + if (typeof handle.value !== 'number') { + return envObject.setLastError(6); + } + result >>>= 0; + var v = new Int32Array([handle.value])[0]; + var HEAP_DATA_VIEW = new DataView(wasmMemory.buffer), GET_HEAP_DATA_VIEW = function () { return HEAP_DATA_VIEW.buffer === wasmMemory.buffer ? HEAP_DATA_VIEW : (HEAP_DATA_VIEW = new DataView(wasmMemory.buffer)); }; + GET_HEAP_DATA_VIEW().setInt32(result, v, true); + return envObject.clearLastError(); + } + function napi_get_value_int64(env, value, result) { + if (!env) + return 1; + var envObject = emnapiCtx.envStore.get(env); + envObject.checkGCAccess(); + if (!value) + return envObject.setLastError(1); + if (!result) + return envObject.setLastError(1); + var handle = emnapiCtx.handleStore.get(value); + if (typeof handle.value !== 'number') { + return envObject.setLastError(6); + } + var numberValue = handle.value; + result >>>= 0; + var HEAP_DATA_VIEW = new DataView(wasmMemory.buffer), GET_HEAP_DATA_VIEW = function () { return HEAP_DATA_VIEW.buffer === wasmMemory.buffer ? HEAP_DATA_VIEW : (HEAP_DATA_VIEW = new DataView(wasmMemory.buffer)); }; + if (numberValue === Number.POSITIVE_INFINITY || numberValue === Number.NEGATIVE_INFINITY || isNaN(numberValue)) { + GET_HEAP_DATA_VIEW().setInt32(result, 0, true); + GET_HEAP_DATA_VIEW().setInt32(result + 4, 0, true); + } + else if (numberValue < -9223372036854776e3) { + GET_HEAP_DATA_VIEW().setInt32(result, 0, true); + GET_HEAP_DATA_VIEW().setInt32(result + 4, 2147483648, true); + } + else if (numberValue >= 9223372036854776000) { + GET_HEAP_DATA_VIEW().setUint32(result, 4294967295, true); + GET_HEAP_DATA_VIEW().setUint32(result + 4, 2147483647, true); + } + else { + $emnapiSetValueI64(result, Math.trunc(numberValue)); + } + return envObject.clearLastError(); + } + function napi_get_value_string_latin1(env, value, buf, buf_size, result) { + if (!env) + return 1; + var envObject = emnapiCtx.envStore.get(env); + envObject.checkGCAccess(); + if (!value) + return envObject.setLastError(1); + result >>>= 0; + buf >>>= 0; + buf_size >>>= 0; + buf_size = buf_size >>> 0; + var handle = emnapiCtx.handleStore.get(value); + if (typeof handle.value !== 'string') { + return envObject.setLastError(3); + } + var HEAP_DATA_VIEW = new DataView(wasmMemory.buffer), GET_HEAP_DATA_VIEW = function () { return HEAP_DATA_VIEW.buffer === wasmMemory.buffer ? HEAP_DATA_VIEW : (HEAP_DATA_VIEW = new DataView(wasmMemory.buffer)); }; + if (!buf) { + if (!result) + return envObject.setLastError(1); + GET_HEAP_DATA_VIEW().setUint32(result, handle.value.length, true); + } + else if (buf_size !== 0) { + var copied = 0; + var v = void 0; + for (var i = 0; i < buf_size - 1; ++i) { + v = handle.value.charCodeAt(i) & 0xff; + GET_HEAP_DATA_VIEW().setUint8(buf + i, v, true); + copied++; + } + GET_HEAP_DATA_VIEW().setUint8(buf + copied, 0, true); + if (result) { + GET_HEAP_DATA_VIEW().setUint32(result, copied, true); + } + } + else if (result) { + GET_HEAP_DATA_VIEW().setUint32(result, 0, true); + } + return envObject.clearLastError(); + } + function napi_get_value_string_utf8(env, value, buf, buf_size, result) { + if (!env) + return 1; + var envObject = emnapiCtx.envStore.get(env); + envObject.checkGCAccess(); + if (!value) + return envObject.setLastError(1); + result >>>= 0; + buf >>>= 0; + buf_size >>>= 0; + buf_size = buf_size >>> 0; + var handle = emnapiCtx.handleStore.get(value); + if (typeof handle.value !== 'string') { + return envObject.setLastError(3); + } + var HEAP_DATA_VIEW = new DataView(wasmMemory.buffer), GET_HEAP_DATA_VIEW = function () { return HEAP_DATA_VIEW.buffer === wasmMemory.buffer ? HEAP_DATA_VIEW : (HEAP_DATA_VIEW = new DataView(wasmMemory.buffer)); }; + if (!buf) { + if (!result) + return envObject.setLastError(1); + var strLength = emnapiString.lengthBytesUTF8(handle.value); + GET_HEAP_DATA_VIEW().setUint32(result, strLength, true); + } + else if (buf_size !== 0) { + var copied = emnapiString.stringToUTF8(handle.value, buf, buf_size); + if (result) { + GET_HEAP_DATA_VIEW().setUint32(result, copied, true); + } + } + else if (result) { + GET_HEAP_DATA_VIEW().setUint32(result, 0, true); + } + return envObject.clearLastError(); + } + function napi_get_value_string_utf16(env, value, buf, buf_size, result) { + if (!env) + return 1; + var envObject = emnapiCtx.envStore.get(env); + envObject.checkGCAccess(); + if (!value) + return envObject.setLastError(1); + result >>>= 0; + buf >>>= 0; + buf_size >>>= 0; + buf_size = buf_size >>> 0; + var handle = emnapiCtx.handleStore.get(value); + if (typeof handle.value !== 'string') { + return envObject.setLastError(3); + } + var HEAP_DATA_VIEW = new DataView(wasmMemory.buffer), GET_HEAP_DATA_VIEW = function () { return HEAP_DATA_VIEW.buffer === wasmMemory.buffer ? HEAP_DATA_VIEW : (HEAP_DATA_VIEW = new DataView(wasmMemory.buffer)); }; + if (!buf) { + if (!result) + return envObject.setLastError(1); + GET_HEAP_DATA_VIEW().setUint32(result, handle.value.length, true); + } + else if (buf_size !== 0) { + var copied = emnapiString.stringToUTF16(handle.value, buf, buf_size * 2); + if (result) { + GET_HEAP_DATA_VIEW().setUint32(result, copied / 2, true); + } + } + else if (result) { + GET_HEAP_DATA_VIEW().setUint32(result, 0, true); + } + return envObject.clearLastError(); + } + function napi_get_value_uint32(env, value, result) { + if (!env) + return 1; + var envObject = emnapiCtx.envStore.get(env); + envObject.checkGCAccess(); + if (!value) + return envObject.setLastError(1); + if (!result) + return envObject.setLastError(1); + var handle = emnapiCtx.handleStore.get(value); + if (typeof handle.value !== 'number') { + return envObject.setLastError(6); + } + result >>>= 0; + var v = new Uint32Array([handle.value])[0]; + var HEAP_DATA_VIEW = new DataView(wasmMemory.buffer), GET_HEAP_DATA_VIEW = function () { return HEAP_DATA_VIEW.buffer === wasmMemory.buffer ? HEAP_DATA_VIEW : (HEAP_DATA_VIEW = new DataView(wasmMemory.buffer)); }; + GET_HEAP_DATA_VIEW().setUint32(result, v, true); + return envObject.clearLastError(); + } + var convert2cMod = Object.freeze({ + __proto__: null, + napi_get_array_length: napi_get_array_length, + napi_get_arraybuffer_info: napi_get_arraybuffer_info, + napi_get_buffer_info: napi_get_buffer_info, + napi_get_dataview_info: napi_get_dataview_info, + napi_get_date_value: napi_get_date_value, + napi_get_prototype: napi_get_prototype, + napi_get_typedarray_info: napi_get_typedarray_info, + napi_get_value_bigint_int64: napi_get_value_bigint_int64, + napi_get_value_bigint_uint64: napi_get_value_bigint_uint64, + napi_get_value_bigint_words: napi_get_value_bigint_words, + napi_get_value_bool: napi_get_value_bool, + napi_get_value_double: napi_get_value_double, + napi_get_value_external: napi_get_value_external, + napi_get_value_int32: napi_get_value_int32, + napi_get_value_int64: napi_get_value_int64, + napi_get_value_string_latin1: napi_get_value_string_latin1, + napi_get_value_string_utf16: napi_get_value_string_utf16, + napi_get_value_string_utf8: napi_get_value_string_utf8, + napi_get_value_uint32: napi_get_value_uint32, + node_api_set_prototype: node_api_set_prototype + }); + function napi_create_int32(env, value, result) { + if (!env) + return 1; + var envObject = emnapiCtx.envStore.get(env); + envObject.checkGCAccess(); + if (!result) + return envObject.setLastError(1); + result >>>= 0; + var v = emnapiCtx.addToCurrentScope(value).id; + var HEAP_DATA_VIEW = new DataView(wasmMemory.buffer), GET_HEAP_DATA_VIEW = function () { return HEAP_DATA_VIEW.buffer === wasmMemory.buffer ? HEAP_DATA_VIEW : (HEAP_DATA_VIEW = new DataView(wasmMemory.buffer)); }; + GET_HEAP_DATA_VIEW().setUint32(result, v, true); + return envObject.clearLastError(); + } + function napi_create_uint32(env, value, result) { + if (!env) + return 1; + var envObject = emnapiCtx.envStore.get(env); + envObject.checkGCAccess(); + if (!result) + return envObject.setLastError(1); + result >>>= 0; + var v = emnapiCtx.addToCurrentScope(value >>> 0).id; + var HEAP_DATA_VIEW = new DataView(wasmMemory.buffer), GET_HEAP_DATA_VIEW = function () { return HEAP_DATA_VIEW.buffer === wasmMemory.buffer ? HEAP_DATA_VIEW : (HEAP_DATA_VIEW = new DataView(wasmMemory.buffer)); }; + GET_HEAP_DATA_VIEW().setUint32(result, v, true); + return envObject.clearLastError(); + } + function napi_create_int64(env, low, high, result) { + if (!env) + return 1; + var envObject = emnapiCtx.envStore.get(env); + envObject.checkGCAccess(); + var value; + if (!high) + return envObject.setLastError(1); + value = Number(low); + var v1 = emnapiCtx.addToCurrentScope(value).id; + high >>>= 0; + var HEAP_DATA_VIEW = new DataView(wasmMemory.buffer), GET_HEAP_DATA_VIEW = function () { return HEAP_DATA_VIEW.buffer === wasmMemory.buffer ? HEAP_DATA_VIEW : (HEAP_DATA_VIEW = new DataView(wasmMemory.buffer)); }; + GET_HEAP_DATA_VIEW().setUint32(high, v1, true); + return envObject.clearLastError(); + } + function napi_create_double(env, value, result) { + if (!env) + return 1; + var envObject = emnapiCtx.envStore.get(env); + envObject.checkGCAccess(); + if (!result) + return envObject.setLastError(1); + result >>>= 0; + var v = emnapiCtx.addToCurrentScope(value).id; + var HEAP_DATA_VIEW = new DataView(wasmMemory.buffer), GET_HEAP_DATA_VIEW = function () { return HEAP_DATA_VIEW.buffer === wasmMemory.buffer ? HEAP_DATA_VIEW : (HEAP_DATA_VIEW = new DataView(wasmMemory.buffer)); }; + GET_HEAP_DATA_VIEW().setUint32(result, v, true); + return envObject.clearLastError(); + } + function napi_create_string_latin1(env, str, length, result) { + return emnapiString.newString(env, str, length, result, function (str, autoLength, sizeLength) { + var latin1String = ''; + var len = 0; + var HEAP_DATA_VIEW = new DataView(wasmMemory.buffer), GET_HEAP_DATA_VIEW = function () { return HEAP_DATA_VIEW.buffer === wasmMemory.buffer ? HEAP_DATA_VIEW : (HEAP_DATA_VIEW = new DataView(wasmMemory.buffer)); }; + if (autoLength) { + while (true) { + var ch = GET_HEAP_DATA_VIEW().getUint8(str, true); + if (!ch) + break; + latin1String += String.fromCharCode(ch); + str++; + } + } + else { + while (len < sizeLength) { + var ch = GET_HEAP_DATA_VIEW().getUint8(str, true); + if (!ch) + break; + latin1String += String.fromCharCode(ch); + len++; + str++; + } + } + return latin1String; + }); + } + function napi_create_string_utf16(env, str, length, result) { + return emnapiString.newString(env, str, length, result, function (str) { + return emnapiString.UTF16ToString(str, length); + }); + } + function napi_create_string_utf8(env, str, length, result) { + return emnapiString.newString(env, str, length, result, function (str) { + return emnapiString.UTF8ToString(str, length); + }); + } + function node_api_create_external_string_latin1(env, str, length, finalize_callback, finalize_hint, result, copied) { + return emnapiString.newExternalString(env, str, length, finalize_callback, finalize_hint, result, copied, napi_create_string_latin1, undefined); + } + function node_api_create_external_string_utf16(env, str, length, finalize_callback, finalize_hint, result, copied) { + return emnapiString.newExternalString(env, str, length, finalize_callback, finalize_hint, result, copied, napi_create_string_utf16, undefined); + } + function node_api_create_property_key_latin1(env, str, length, result) { + return napi_create_string_latin1(env, str, length, result); + } + function node_api_create_property_key_utf8(env, str, length, result) { + return napi_create_string_utf8(env, str, length, result); + } + function node_api_create_property_key_utf16(env, str, length, result) { + return napi_create_string_utf16(env, str, length, result); + } + function napi_create_bigint_int64(env, low, high, result) { + if (!env) + return 1; + var envObject = emnapiCtx.envStore.get(env); + envObject.checkGCAccess(); + if (!emnapiCtx.feature.supportBigInt) { + return envObject.setLastError(9); + } + var value; + if (!high) + return envObject.setLastError(1); + value = low; + var v1 = emnapiCtx.addToCurrentScope(value).id; + high >>>= 0; + var HEAP_DATA_VIEW = new DataView(wasmMemory.buffer), GET_HEAP_DATA_VIEW = function () { return HEAP_DATA_VIEW.buffer === wasmMemory.buffer ? HEAP_DATA_VIEW : (HEAP_DATA_VIEW = new DataView(wasmMemory.buffer)); }; + GET_HEAP_DATA_VIEW().setUint32(high, v1, true); + return envObject.clearLastError(); + } + function napi_create_bigint_uint64(env, low, high, result) { + if (!env) + return 1; + var envObject = emnapiCtx.envStore.get(env); + envObject.checkGCAccess(); + if (!emnapiCtx.feature.supportBigInt) { + return envObject.setLastError(9); + } + var value; + if (!high) + return envObject.setLastError(1); + value = low & ((BigInt(1) << BigInt(64)) - BigInt(1)); + var v1 = emnapiCtx.addToCurrentScope(value).id; + high >>>= 0; + var HEAP_DATA_VIEW = new DataView(wasmMemory.buffer), GET_HEAP_DATA_VIEW = function () { return HEAP_DATA_VIEW.buffer === wasmMemory.buffer ? HEAP_DATA_VIEW : (HEAP_DATA_VIEW = new DataView(wasmMemory.buffer)); }; + GET_HEAP_DATA_VIEW().setUint32(high, v1, true); + return envObject.clearLastError(); + } + function napi_create_bigint_words(env, sign_bit, word_count, words, result) { + var v, i; + if (!env) + return 1; + var envObject = emnapiCtx.envStore.get(env); + envObject.checkGCAccess(); + if (!envObject.tryCatch.isEmpty()) + return envObject.setLastError(10); + if (!envObject.canCallIntoJs()) + return envObject.setLastError(envObject.moduleApiVersion >= 10 ? 23 : 10); + envObject.clearLastError(); + try { + if (!emnapiCtx.feature.supportBigInt) { + return envObject.setLastError(9); + } + if (!result) + return envObject.setLastError(1); + words >>>= 0; + word_count >>>= 0; + word_count = word_count >>> 0; + if (word_count > 2147483647) { + return envObject.setLastError(1); + } + if (word_count > (1024 * 1024 / (4 * 8) / 2)) { + throw new RangeError('Maximum BigInt size exceeded'); + } + var value = BigInt(0); + var HEAP_DATA_VIEW = new DataView(wasmMemory.buffer), GET_HEAP_DATA_VIEW = function () { return HEAP_DATA_VIEW.buffer === wasmMemory.buffer ? HEAP_DATA_VIEW : (HEAP_DATA_VIEW = new DataView(wasmMemory.buffer)); }; + for (i = 0; i < word_count; i++) { + var low = GET_HEAP_DATA_VIEW().getUint32(words + i * 8, true); + var high = GET_HEAP_DATA_VIEW().getUint32(words + (i * 8 + 4), true); + var wordi = BigInt(low) | (BigInt(high) << BigInt(32)); + value += wordi << BigInt(64 * i); + } + value *= ((BigInt(sign_bit) % BigInt(2) === BigInt(0)) ? BigInt(1) : BigInt(-1)); + result >>>= 0; + v = emnapiCtx.addToCurrentScope(value).id; + GET_HEAP_DATA_VIEW().setUint32(result, v, true); + return envObject.getReturnStatus(); + } + catch (err) { + envObject.tryCatch.setError(err); + return envObject.setLastError(10); + } + } + var convert2napiMod = Object.freeze({ + __proto__: null, + napi_create_bigint_int64: napi_create_bigint_int64, + napi_create_bigint_uint64: napi_create_bigint_uint64, + napi_create_bigint_words: napi_create_bigint_words, + napi_create_double: napi_create_double, + napi_create_int32: napi_create_int32, + napi_create_int64: napi_create_int64, + napi_create_string_latin1: napi_create_string_latin1, + napi_create_string_utf16: napi_create_string_utf16, + napi_create_string_utf8: napi_create_string_utf8, + napi_create_uint32: napi_create_uint32, + node_api_create_external_string_latin1: node_api_create_external_string_latin1, + node_api_create_external_string_utf16: node_api_create_external_string_utf16, + node_api_create_property_key_latin1: node_api_create_property_key_latin1, + node_api_create_property_key_utf16: node_api_create_property_key_utf16, + node_api_create_property_key_utf8: node_api_create_property_key_utf8 + }); + function emnapiCreateFunction(envObject, utf8name, length, cb, data) { + utf8name >>>= 0; + var functionName = (!utf8name || !length) ? '' : (emnapiString.UTF8ToString(utf8name, length)); + var f; + var napiCallback = (wasmTable.get(cb)); + var callback = function (envObject) { + return napiCallback(envObject.id, envObject.ctx.scopeStore.currentScope.id); + }; + var makeFunction = function (envObject, callback) { + return function () { + var scope = envObject.ctx.openScope(envObject); + var callbackInfo = scope.callbackInfo; + callbackInfo.data = data; + callbackInfo.args = arguments; + callbackInfo.thiz = this; + callbackInfo.fn = f; + try { + var napiValue = envObject.callIntoModule(callback); + return (!napiValue) ? undefined : envObject.ctx.handleStore.get(napiValue).value; + } + finally { + callbackInfo.data = 0; + callbackInfo.args = undefined; + callbackInfo.thiz = undefined; + callbackInfo.fn = undefined; + envObject.ctx.closeScope(envObject, scope); + } + }; + }; + if (functionName === '') { + f = makeFunction(envObject, callback); + return { status: 0, f: f }; + } + if (!(/^[_$a-zA-Z][_$a-zA-Z0-9]*$/.test(functionName))) { + return { status: 1, f: undefined }; + } + if (emnapiCtx.feature.supportNewFunction) { + var _ = makeFunction(envObject, callback); + try { + f = (new Function('_', 'return function ' + functionName + '(){' + + '"use strict";' + + 'return _.apply(this,arguments);' + + '};'))(_); + } + catch (_err) { + f = makeFunction(envObject, callback); + if (emnapiCtx.feature.canSetFunctionName) + Object.defineProperty(f, 'name', { value: functionName }); + } + } + else { + f = makeFunction(envObject, callback); + if (emnapiCtx.feature.canSetFunctionName) + Object.defineProperty(f, 'name', { value: functionName }); + } + return { status: 0, f: f }; + } + function emnapiDefineProperty(envObject, obj, propertyName, method, getter, setter, value, attributes, data) { + if (getter || setter) { + var localGetter = void 0; + var localSetter = void 0; + if (getter) { + localGetter = emnapiCreateFunction(envObject, 0, 0, getter, data).f; + } + if (setter) { + localSetter = emnapiCreateFunction(envObject, 0, 0, setter, data).f; + } + var desc = { + configurable: (attributes & 4) !== 0, + enumerable: (attributes & 2) !== 0, + get: localGetter, + set: localSetter + }; + Object.defineProperty(obj, propertyName, desc); + } + else if (method) { + var localMethod = emnapiCreateFunction(envObject, 0, 0, method, data).f; + var desc = { + configurable: (attributes & 4) !== 0, + enumerable: (attributes & 2) !== 0, + writable: (attributes & 1) !== 0, + value: localMethod + }; + Object.defineProperty(obj, propertyName, desc); + } + else { + var desc = { + configurable: (attributes & 4) !== 0, + enumerable: (attributes & 2) !== 0, + writable: (attributes & 1) !== 0, + value: emnapiCtx.handleStore.get(value).value + }; + Object.defineProperty(obj, propertyName, desc); + } + } + function emnapiGetHandle(js_object) { + var handle = emnapiCtx.handleStore.get(js_object); + if (!(handle.isObject() || handle.isFunction())) { + return { status: 1 }; + } + if (typeof emnapiExternalMemory !== 'undefined' && ArrayBuffer.isView(handle.value)) { + if (emnapiExternalMemory.wasmMemoryViewTable.has(handle.value)) { + handle = emnapiCtx.addToCurrentScope(emnapiExternalMemory.wasmMemoryViewTable.get(handle.value)); + } + } + return { status: 0, handle: handle }; + } + function emnapiWrap(env, js_object, native_object, finalize_cb, finalize_hint, result) { + var referenceId; + if (!env) + return 1; + var envObject = emnapiCtx.envStore.get(env); + envObject.checkGCAccess(); + if (!envObject.tryCatch.isEmpty()) + return envObject.setLastError(10); + if (!envObject.canCallIntoJs()) + return envObject.setLastError(envObject.moduleApiVersion >= 10 ? 23 : 10); + envObject.clearLastError(); + try { + if (!emnapiCtx.feature.supportFinalizer) { + if (finalize_cb) { + throw emnapiCtx.createNotSupportWeakRefError('napi_wrap', 'Parameter "finalize_cb" must be 0(NULL)'); + } + if (result) { + throw emnapiCtx.createNotSupportWeakRefError('napi_wrap', 'Parameter "result" must be 0(NULL)'); + } + } + if (!js_object) + return envObject.setLastError(1); + var handleResult = emnapiGetHandle(js_object); + if (handleResult.status !== 0) { + return envObject.setLastError(handleResult.status); + } + var handle = handleResult.handle; + if (envObject.getObjectBinding(handle.value).wrapped !== 0) { + return envObject.setLastError(1); + } + var reference = void 0; + if (result) { + if (!finalize_cb) + return envObject.setLastError(1); + reference = emnapiCtx.createReferenceWithFinalizer(envObject, handle.id, 0, 1, finalize_cb, native_object, finalize_hint); + result >>>= 0; + referenceId = reference.id; + var HEAP_DATA_VIEW = new DataView(wasmMemory.buffer), GET_HEAP_DATA_VIEW = function () { return HEAP_DATA_VIEW.buffer === wasmMemory.buffer ? HEAP_DATA_VIEW : (HEAP_DATA_VIEW = new DataView(wasmMemory.buffer)); }; + GET_HEAP_DATA_VIEW().setUint32(result, referenceId, true); + } + else { + if (finalize_cb) { + reference = emnapiCtx.createReferenceWithFinalizer(envObject, handle.id, 0, 0, finalize_cb, native_object, finalize_hint); + } + else { + reference = emnapiCtx.createReferenceWithData(envObject, handle.id, 0, 0, native_object); + } + } + envObject.getObjectBinding(handle.value).wrapped = reference.id; + return envObject.getReturnStatus(); + } + catch (err) { + envObject.tryCatch.setError(err); + return envObject.setLastError(10); + } + } + function emnapiUnwrap(env, js_object, result, action) { + var data; + if (!env) + return 1; + var envObject = emnapiCtx.envStore.get(env); + envObject.checkGCAccess(); + if (!envObject.tryCatch.isEmpty()) + return envObject.setLastError(10); + if (!envObject.canCallIntoJs()) + return envObject.setLastError(envObject.moduleApiVersion >= 10 ? 23 : 10); + envObject.clearLastError(); + try { + if (!js_object) + return envObject.setLastError(1); + if (action === 0) { + if (!result) + return envObject.setLastError(1); + } + var value = emnapiCtx.handleStore.get(js_object); + if (!(value.isObject() || value.isFunction())) { + return envObject.setLastError(1); + } + var binding = envObject.getObjectBinding(value.value); + var referenceId = binding.wrapped; + var ref = emnapiCtx.refStore.get(referenceId); + if (!ref) + return envObject.setLastError(1); + if (result) { + result >>>= 0; + data = ref.data(); + var HEAP_DATA_VIEW = new DataView(wasmMemory.buffer), GET_HEAP_DATA_VIEW = function () { return HEAP_DATA_VIEW.buffer === wasmMemory.buffer ? HEAP_DATA_VIEW : (HEAP_DATA_VIEW = new DataView(wasmMemory.buffer)); }; + GET_HEAP_DATA_VIEW().setUint32(result, data, true); + } + if (action === 1) { + binding.wrapped = 0; + if (ref.ownership() === 1) { + ref.resetFinalizer(); + } + else { + ref.dispose(); + } + } + return envObject.getReturnStatus(); + } + catch (err) { + envObject.tryCatch.setError(err); + return envObject.setLastError(10); + } + } + function napi_define_class(env, utf8name, length, constructor, callback_data, property_count, properties, result) { + var propPtr, valueHandleId, attributes; + if (!env) + return 1; + var envObject = emnapiCtx.envStore.get(env); + envObject.checkGCAccess(); + if (!envObject.tryCatch.isEmpty()) + return envObject.setLastError(10); + if (!envObject.canCallIntoJs()) + return envObject.setLastError(envObject.moduleApiVersion >= 10 ? 23 : 10); + envObject.clearLastError(); + try { + if (!result) + return envObject.setLastError(1); + if (!constructor) + return envObject.setLastError(1); + length >>>= 0; + properties >>>= 0; + property_count >>>= 0; + property_count = property_count >>> 0; + if (property_count > 0) { + if (!properties) + return envObject.setLastError(1); + } + if (!((length >= -1 && length <= 2147483647) || length === 4294967295) || (!utf8name)) { + return envObject.setLastError(1); + } + var fresult = emnapiCreateFunction(envObject, utf8name, length, constructor, callback_data); + if (fresult.status !== 0) + return envObject.setLastError(fresult.status); + var F = fresult.f; + var propertyName = void 0; + var HEAP_DATA_VIEW = new DataView(wasmMemory.buffer), GET_HEAP_DATA_VIEW = function () { return HEAP_DATA_VIEW.buffer === wasmMemory.buffer ? HEAP_DATA_VIEW : (HEAP_DATA_VIEW = new DataView(wasmMemory.buffer)); }; + for (var i = 0; i < property_count; i++) { + propPtr = properties + (i * (4 * 8)); + var utf8Name = GET_HEAP_DATA_VIEW().getUint32(propPtr, true); + var name_1 = GET_HEAP_DATA_VIEW().getUint32(propPtr + 4, true); + var method = GET_HEAP_DATA_VIEW().getUint32(propPtr + 8, true); + var getter = GET_HEAP_DATA_VIEW().getUint32(propPtr + 12, true); + var setter = GET_HEAP_DATA_VIEW().getUint32(propPtr + 16, true); + var value = GET_HEAP_DATA_VIEW().getUint32(propPtr + 20, true); + attributes = GET_HEAP_DATA_VIEW().getInt32(propPtr + 24, true); + attributes >>>= 0; + var data = GET_HEAP_DATA_VIEW().getUint32(propPtr + 28, true); + if (utf8Name) { + propertyName = emnapiString.UTF8ToString(utf8Name, -1); + } + else { + if (!name_1) { + return envObject.setLastError(4); + } + propertyName = emnapiCtx.handleStore.get(name_1).value; + if (typeof propertyName !== 'string' && typeof propertyName !== 'symbol') { + return envObject.setLastError(4); + } + } + if ((attributes & 1024) !== 0) { + emnapiDefineProperty(envObject, F, propertyName, method, getter, setter, value, attributes, data); + continue; + } + emnapiDefineProperty(envObject, F.prototype, propertyName, method, getter, setter, value, attributes, data); + } + var valueHandle = emnapiCtx.addToCurrentScope(F); + valueHandleId = valueHandle.id; + result >>>= 0; + GET_HEAP_DATA_VIEW().setUint32(result, valueHandleId, true); + return envObject.getReturnStatus(); + } + catch (err) { + envObject.tryCatch.setError(err); + return envObject.setLastError(10); + } + } + function napi_wrap(env, js_object, native_object, finalize_cb, finalize_hint, result) { + return emnapiWrap(env, js_object, native_object, finalize_cb, finalize_hint, result); + } + function napi_unwrap(env, js_object, result) { + return emnapiUnwrap(env, js_object, result, 0); + } + function napi_remove_wrap(env, js_object, result) { + return emnapiUnwrap(env, js_object, result, 1); + } + function napi_type_tag_object(env, object, type_tag) { + if (!env) + return 1; + var envObject = emnapiCtx.envStore.get(env); + envObject.checkGCAccess(); + if (!envObject.tryCatch.isEmpty()) + return envObject.setLastError(10); + if (!envObject.canCallIntoJs()) + return envObject.setLastError(envObject.moduleApiVersion >= 10 ? 23 : 10); + envObject.clearLastError(); + try { + if (!object) { + return envObject.setLastError(envObject.tryCatch.hasCaught() ? 10 : 1); + } + var value = emnapiCtx.handleStore.get(object); + if (!(value.isObject() || value.isFunction())) { + return envObject.setLastError(envObject.tryCatch.hasCaught() ? 10 : 2); + } + type_tag >>>= 0; + if (!type_tag) { + return envObject.setLastError(envObject.tryCatch.hasCaught() ? 10 : 1); + } + var binding = envObject.getObjectBinding(value.value); + if (binding.tag !== null) { + return envObject.setLastError(envObject.tryCatch.hasCaught() ? 10 : 1); + } + var tag = new Uint8Array(16); + tag.set(new Uint8Array(wasmMemory.buffer, type_tag, 16)); + binding.tag = new Uint32Array(tag.buffer); + return envObject.getReturnStatus(); + } + catch (err) { + envObject.tryCatch.setError(err); + return envObject.setLastError(10); + } + } + function napi_check_object_type_tag(env, object, type_tag, result) { + var ret = true; + if (!env) + return 1; + var envObject = emnapiCtx.envStore.get(env); + envObject.checkGCAccess(); + if (!envObject.tryCatch.isEmpty()) + return envObject.setLastError(10); + if (!envObject.canCallIntoJs()) + return envObject.setLastError(envObject.moduleApiVersion >= 10 ? 23 : 10); + envObject.clearLastError(); + try { + if (!object) { + return envObject.setLastError(envObject.tryCatch.hasCaught() ? 10 : 1); + } + var value = emnapiCtx.handleStore.get(object); + if (!(value.isObject() || value.isFunction())) { + return envObject.setLastError(envObject.tryCatch.hasCaught() ? 10 : 2); + } + if (!type_tag) { + return envObject.setLastError(envObject.tryCatch.hasCaught() ? 10 : 1); + } + if (!result) { + return envObject.setLastError(envObject.tryCatch.hasCaught() ? 10 : 1); + } + var binding = envObject.getObjectBinding(value.value); + if (binding.tag !== null) { + type_tag >>>= 0; + var tag = binding.tag; + var typeTag = new Uint32Array(wasmMemory.buffer, type_tag, 4); + ret = (tag[0] === typeTag[0] && + tag[1] === typeTag[1] && + tag[2] === typeTag[2] && + tag[3] === typeTag[3]); + } + else { + ret = false; + } + result >>>= 0; + var HEAP_DATA_VIEW = new DataView(wasmMemory.buffer), GET_HEAP_DATA_VIEW = function () { return HEAP_DATA_VIEW.buffer === wasmMemory.buffer ? HEAP_DATA_VIEW : (HEAP_DATA_VIEW = new DataView(wasmMemory.buffer)); }; + GET_HEAP_DATA_VIEW().setInt8(result, ret ? 1 : 0, true); + return envObject.getReturnStatus(); + } + catch (err) { + envObject.tryCatch.setError(err); + return envObject.setLastError(10); + } + } + function napi_add_finalizer(env, js_object, finalize_data, finalize_cb, finalize_hint, result) { + if (!env) + return 1; + var envObject = emnapiCtx.envStore.get(env); + envObject.checkGCAccess(); + if (!emnapiCtx.feature.supportFinalizer) { + return envObject.setLastError(9); + } + if (!js_object) + return envObject.setLastError(1); + if (!finalize_cb) + return envObject.setLastError(1); + var handleResult = emnapiGetHandle(js_object); + if (handleResult.status !== 0) { + return envObject.setLastError(handleResult.status); + } + var handle = handleResult.handle; + var ownership = !result ? 0 : 1; + finalize_data >>>= 0; + finalize_cb >>>= 0; + finalize_hint >>>= 0; + var reference = emnapiCtx.createReferenceWithFinalizer(envObject, handle.id, 0, ownership, finalize_cb, finalize_data, finalize_hint); + if (result) { + result >>>= 0; + var referenceId = reference.id; + var HEAP_DATA_VIEW = new DataView(wasmMemory.buffer), GET_HEAP_DATA_VIEW = function () { return HEAP_DATA_VIEW.buffer === wasmMemory.buffer ? HEAP_DATA_VIEW : (HEAP_DATA_VIEW = new DataView(wasmMemory.buffer)); }; + GET_HEAP_DATA_VIEW().setUint32(result, referenceId, true); + } + return envObject.clearLastError(); + } + function node_api_post_finalizer(env, finalize_cb, finalize_data, finalize_hint) { + if (!env) + return 1; + var envObject = emnapiCtx.envStore.get(env); + envObject.enqueueFinalizer(emnapiCtx.createTrackedFinalizer(envObject, finalize_cb, finalize_data, finalize_hint)); + return envObject.clearLastError(); + } + var wrapMod = Object.freeze({ + __proto__: null, + napi_add_finalizer: napi_add_finalizer, + napi_check_object_type_tag: napi_check_object_type_tag, + napi_define_class: napi_define_class, + napi_remove_wrap: napi_remove_wrap, + napi_type_tag_object: napi_type_tag_object, + napi_unwrap: napi_unwrap, + napi_wrap: napi_wrap, + node_api_post_finalizer: node_api_post_finalizer + }); + function emnapi_create_memory_view(env, typedarray_type, external_data, byte_length, finalize_cb, finalize_hint, result) { + var value; + if (!env) + return 1; + var envObject = emnapiCtx.envStore.get(env); + envObject.checkGCAccess(); + if (!envObject.tryCatch.isEmpty()) + return envObject.setLastError(10); + if (!envObject.canCallIntoJs()) + return envObject.setLastError(envObject.moduleApiVersion >= 10 ? 23 : 10); + envObject.clearLastError(); + try { + if (!result) + return envObject.setLastError(1); + byte_length >>>= 0; + external_data >>>= 0; + result >>>= 0; + byte_length = byte_length >>> 0; + if (!external_data) { + byte_length = 0; + } + if (byte_length > 2147483647) { + throw new RangeError('Cannot create a memory view larger than 2147483647 bytes'); + } + if ((external_data + byte_length) > wasmMemory.buffer.byteLength) { + throw new RangeError('Memory out of range'); + } + if (!emnapiCtx.feature.supportFinalizer && finalize_cb) { + throw emnapiCtx.createNotSupportWeakRefError('emnapi_create_memory_view', 'Parameter "finalize_cb" must be 0(NULL)'); + } + var viewDescriptor = void 0; + switch (typedarray_type) { + case 0: + viewDescriptor = { Ctor: Int8Array, address: external_data, length: byte_length, ownership: 1, runtimeAllocated: 0 }; + break; + case 1: + viewDescriptor = { Ctor: Uint8Array, address: external_data, length: byte_length, ownership: 1, runtimeAllocated: 0 }; + break; + case 2: + viewDescriptor = { Ctor: Uint8ClampedArray, address: external_data, length: byte_length, ownership: 1, runtimeAllocated: 0 }; + break; + case 3: + viewDescriptor = { Ctor: Int16Array, address: external_data, length: byte_length >> 1, ownership: 1, runtimeAllocated: 0 }; + break; + case 4: + viewDescriptor = { Ctor: Uint16Array, address: external_data, length: byte_length >> 1, ownership: 1, runtimeAllocated: 0 }; + break; + case 5: + viewDescriptor = { Ctor: Int32Array, address: external_data, length: byte_length >> 2, ownership: 1, runtimeAllocated: 0 }; + break; + case 6: + viewDescriptor = { Ctor: Uint32Array, address: external_data, length: byte_length >> 2, ownership: 1, runtimeAllocated: 0 }; + break; + case 7: + viewDescriptor = { Ctor: Float32Array, address: external_data, length: byte_length >> 2, ownership: 1, runtimeAllocated: 0 }; + break; + case 8: + viewDescriptor = { Ctor: Float64Array, address: external_data, length: byte_length >> 3, ownership: 1, runtimeAllocated: 0 }; + break; + case 9: + viewDescriptor = { Ctor: BigInt64Array, address: external_data, length: byte_length >> 3, ownership: 1, runtimeAllocated: 0 }; + break; + case 10: + viewDescriptor = { Ctor: BigUint64Array, address: external_data, length: byte_length >> 3, ownership: 1, runtimeAllocated: 0 }; + break; + case -1: + viewDescriptor = { Ctor: DataView, address: external_data, length: byte_length, ownership: 1, runtimeAllocated: 0 }; + break; + case 11: + if (typeof Float16Array !== 'function') { + return envObject.setLastError(1); + } + viewDescriptor = { Ctor: Float16Array, address: external_data, length: byte_length >> 1, ownership: 1, runtimeAllocated: 0 }; + break; + case -2: { + if (!emnapiCtx.feature.Buffer) { + throw emnapiCtx.createNotSupportBufferError('emnapi_create_memory_view', ''); + } + viewDescriptor = { Ctor: emnapiCtx.feature.Buffer, address: external_data, length: byte_length, ownership: 1, runtimeAllocated: 0 }; + break; + } + default: return envObject.setLastError(1); + } + var Ctor = viewDescriptor.Ctor; + var typedArray = typedarray_type === -2 + ? emnapiExternalMemory.getBufferFrom()(wasmMemory.buffer, viewDescriptor.address, viewDescriptor.length) + : new Ctor(wasmMemory.buffer, viewDescriptor.address, viewDescriptor.length); + var handle = emnapiCtx.addToCurrentScope(typedArray); + emnapiExternalMemory.wasmMemoryViewTable.set(typedArray, viewDescriptor); + if (finalize_cb) { + var status_1 = napi_add_finalizer(env, handle.id, external_data, finalize_cb, finalize_hint, 0); + if (status_1 === 10) { + var err = envObject.tryCatch.extractException(); + envObject.clearLastError(); + throw err; + } + else if (status_1 !== 0) { + return envObject.setLastError(status_1); + } + } + value = handle.id; + var HEAP_DATA_VIEW = new DataView(wasmMemory.buffer), GET_HEAP_DATA_VIEW = function () { return HEAP_DATA_VIEW.buffer === wasmMemory.buffer ? HEAP_DATA_VIEW : (HEAP_DATA_VIEW = new DataView(wasmMemory.buffer)); }; + GET_HEAP_DATA_VIEW().setUint32(result, value, true); + return envObject.getReturnStatus(); + } + catch (err) { + envObject.tryCatch.setError(err); + return envObject.setLastError(10); + } + } + function emnapi_is_support_weakref() { + return emnapiCtx.feature.supportFinalizer ? 1 : 0; + } + function emnapi_is_support_bigint() { + return emnapiCtx.feature.supportBigInt ? 1 : 0; + } + function emnapi_is_node_binding_available() { + return emnapiNodeBinding ? 1 : 0; + } + function $emnapiSyncMemory(js_to_wasm, arrayBufferOrView, offset, len) { + offset = offset !== null && offset !== void 0 ? offset : 0; + offset = offset >>> 0; + var view; + if (arrayBufferOrView instanceof ArrayBuffer || emnapiExternalMemory.isSharedArrayBuffer(arrayBufferOrView)) { + var pointer = emnapiExternalMemory.getArrayBufferPointer(arrayBufferOrView, false).address; + if (!pointer) + throw new Error('Unknown ArrayBuffer address'); + if (typeof len !== 'number' || len === -1 || len === 4294967295) { + len = arrayBufferOrView.byteLength - offset; + } + len = len >>> 0; + if (len === 0) + return arrayBufferOrView; + view = new Uint8Array(arrayBufferOrView, offset, len); + var wasmMemoryU8 = new Uint8Array(wasmMemory.buffer); + if (!js_to_wasm) { + view.set(wasmMemoryU8.subarray(pointer, pointer + len)); + } + else { + wasmMemoryU8.set(view, pointer); + } + return arrayBufferOrView; + } + if (ArrayBuffer.isView(arrayBufferOrView)) { + var viewPointerInfo = emnapiExternalMemory.getViewPointer(arrayBufferOrView, false); + var latestView = viewPointerInfo.view; + var pointer = viewPointerInfo.address; + if (!pointer) + throw new Error('Unknown ArrayBuffer address'); + if (typeof len !== 'number' || len === -1 || len === 4294967295) { + len = latestView.byteLength - offset; + } + len = len >>> 0; + if (len === 0) + return latestView; + view = new Uint8Array(latestView.buffer, latestView.byteOffset + offset, len); + var wasmMemoryU8 = new Uint8Array(wasmMemory.buffer); + if (!js_to_wasm) { + view.set(wasmMemoryU8.subarray(pointer, pointer + len)); + } + else { + wasmMemoryU8.set(view, pointer); + } + return latestView; + } + throw new TypeError('emnapiSyncMemory expect ArrayBuffer or ArrayBufferView as first parameter'); + } + function emnapi_sync_memory(env, js_to_wasm, arraybuffer_or_view, offset, len) { + var v; + if (!env) + return 1; + var envObject = emnapiCtx.envStore.get(env); + envObject.checkGCAccess(); + if (!envObject.tryCatch.isEmpty()) + return envObject.setLastError(10); + if (!envObject.canCallIntoJs()) + return envObject.setLastError(envObject.moduleApiVersion >= 10 ? 23 : 10); + envObject.clearLastError(); + try { + if (!arraybuffer_or_view) + return envObject.setLastError(1); + arraybuffer_or_view >>>= 0; + offset >>>= 0; + len >>>= 0; + var HEAP_DATA_VIEW = new DataView(wasmMemory.buffer), GET_HEAP_DATA_VIEW = function () { return HEAP_DATA_VIEW.buffer === wasmMemory.buffer ? HEAP_DATA_VIEW : (HEAP_DATA_VIEW = new DataView(wasmMemory.buffer)); }; + var handleId = GET_HEAP_DATA_VIEW().getUint32(arraybuffer_or_view, true); + var handle = envObject.ctx.handleStore.get(handleId); + if (!handle.isArrayBuffer() && !handle.isTypedArray() && !handle.isDataView() && !emnapiExternalMemory.isSharedArrayBuffer(handle.value)) { + return envObject.setLastError(1); + } + var ret = $emnapiSyncMemory(Boolean(js_to_wasm), handle.value, offset, len); + if (handle.value !== ret) { + arraybuffer_or_view >>>= 0; + v = envObject.ensureHandleId(ret); + GET_HEAP_DATA_VIEW().setUint32(arraybuffer_or_view, v, true); + } + return envObject.getReturnStatus(); + } + catch (err) { + envObject.tryCatch.setError(err); + return envObject.setLastError(10); + } + } + function $emnapiGetMemoryAddress(arrayBufferOrView) { + var isArrayBuffer = arrayBufferOrView instanceof ArrayBuffer; + var isDataView = arrayBufferOrView instanceof DataView; + var isTypedArray = ArrayBuffer.isView(arrayBufferOrView) && !isDataView; + if (!isArrayBuffer && !isTypedArray && !isDataView && !emnapiExternalMemory.isSharedArrayBuffer(arrayBufferOrView)) { + throw new TypeError('emnapiGetMemoryAddress expect ArrayBuffer or ArrayBufferView as first parameter'); + } + var info; + if (isArrayBuffer) { + info = emnapiExternalMemory.getArrayBufferPointer(arrayBufferOrView, false); + } + else { + info = emnapiExternalMemory.getViewPointer(arrayBufferOrView, false); + } + return { + address: info.address, + ownership: info.ownership, + runtimeAllocated: info.runtimeAllocated + }; + } + function emnapi_get_memory_address(env, arraybuffer_or_view, address, ownership, runtime_allocated) { + var p, runtimeAllocated, ownershipOut; + var info; + if (!env) + return 1; + var envObject = emnapiCtx.envStore.get(env); + envObject.checkGCAccess(); + if (!envObject.tryCatch.isEmpty()) + return envObject.setLastError(10); + if (!envObject.canCallIntoJs()) + return envObject.setLastError(envObject.moduleApiVersion >= 10 ? 23 : 10); + envObject.clearLastError(); + try { + if (!arraybuffer_or_view) + return envObject.setLastError(1); + if (!address && !ownership && !runtime_allocated) { + return envObject.setLastError(1); + } + var handle = envObject.ctx.handleStore.get(arraybuffer_or_view); + info = $emnapiGetMemoryAddress(handle.value); + p = info.address; + var HEAP_DATA_VIEW = new DataView(wasmMemory.buffer), GET_HEAP_DATA_VIEW = function () { return HEAP_DATA_VIEW.buffer === wasmMemory.buffer ? HEAP_DATA_VIEW : (HEAP_DATA_VIEW = new DataView(wasmMemory.buffer)); }; + if (address) { + address >>>= 0; + GET_HEAP_DATA_VIEW().setUint32(address, p, true); + } + if (ownership) { + ownership >>>= 0; + ownershipOut = info.ownership; + GET_HEAP_DATA_VIEW().setInt32(ownership, ownershipOut, true); + } + if (runtime_allocated) { + runtime_allocated >>>= 0; + runtimeAllocated = info.runtimeAllocated; + GET_HEAP_DATA_VIEW().setInt8(runtime_allocated, runtimeAllocated, true); + } + return envObject.getReturnStatus(); + } + catch (err) { + envObject.tryCatch.setError(err); + return envObject.setLastError(10); + } + } + function emnapi_get_runtime_version(env, version) { + if (!env) + return 1; + var envObject = emnapiCtx.envStore.get(env); + if (!version) + return envObject.setLastError(1); + var runtimeVersion; + try { + runtimeVersion = emnapiCtx.getRuntimeVersions().version; + } + catch (_) { + return envObject.setLastError(9); + } + var versions = runtimeVersion.split('.') + .map(function (n) { return Number(n); }); + version >>>= 0; + var HEAP_DATA_VIEW = new DataView(wasmMemory.buffer), GET_HEAP_DATA_VIEW = function () { return HEAP_DATA_VIEW.buffer === wasmMemory.buffer ? HEAP_DATA_VIEW : (HEAP_DATA_VIEW = new DataView(wasmMemory.buffer)); }; + GET_HEAP_DATA_VIEW().setUint32(version, versions[0], true); + GET_HEAP_DATA_VIEW().setUint32(version + 4, versions[1], true); + GET_HEAP_DATA_VIEW().setUint32(version + 8, versions[2], true); + return envObject.clearLastError(); + } + function emnapi_get_external_sharedarraybuffer_handle(env, sharedarraybuffer, handle) { + if (!env) + return 1; + var envObject = emnapiCtx.envStore.get(env); + envObject.checkGCAccess(); + if (!envObject.tryCatch.isEmpty()) + return envObject.setLastError(10); + if (!envObject.canCallIntoJs()) + return envObject.setLastError(envObject.moduleApiVersion >= 10 ? 23 : 10); + envObject.clearLastError(); + try { + if (!sharedarraybuffer) + return envObject.setLastError(1); + if (!handle) + return envObject.setLastError(1); + handle >>>= 0; + var jsValue = emnapiCtx.handleStore.get(sharedarraybuffer).value; + if (!emnapiExternalMemory.isSharedArrayBuffer(jsValue)) { + return envObject.setLastError(1); + } + var metaPtr = emnapiExternalSAB.handleTable.get(jsValue); + if (metaPtr === undefined) { + return envObject.setLastError(1); + } + var HEAP_DATA_VIEW = new DataView(wasmMemory.buffer), GET_HEAP_DATA_VIEW = function () { return HEAP_DATA_VIEW.buffer === wasmMemory.buffer ? HEAP_DATA_VIEW : (HEAP_DATA_VIEW = new DataView(wasmMemory.buffer)); }; + GET_HEAP_DATA_VIEW().setUint32(handle, metaPtr, true); + return envObject.getReturnStatus(); + } + catch (err) { + envObject.tryCatch.setError(err); + return envObject.setLastError(10); + } + } + function emnapi_acquire_external_sharedarraybuffer(handle) { + handle >>>= 0; + Atomics.add(new Int32Array(wasmMemory.buffer, handle, 1), 0, 1); + } + function emnapi_release_external_sharedarraybuffer(handle) { + handle >>>= 0; + emnapiExternalSAB.release(handle); + } + function $emnapiAcquireExternalSharedArrayBuffer(handle, sab) { + if (sab != null && !emnapiExternalMemory.isSharedArrayBuffer(sab)) { + throw new TypeError('Expected a SharedArrayBuffer'); + } + if (!emnapiExternalSAB.registry) { + throw new Error('FinalizationRegistry is not supported in this environment'); + } + handle >>>= 0; + var meta = emnapiExternalSAB.readMeta(handle); + var external_data = meta.external_data; + external_data >>>= 0; + if (sab == null) { + sab = new SharedArrayBuffer(meta.byte_length); + new Uint8Array(sab).set(new Uint8Array(wasmMemory.buffer, external_data, meta.byte_length)); + } + else { + if (emnapiExternalSAB.handleTable.has(sab)) { + return sab; + } + } + Atomics.add(new Int32Array(wasmMemory.buffer, handle, 1), 0, 1); + if (!emnapiExternalMemory.table.has(sab)) { + if (external_data) { + emnapiExternalMemory.table.set(sab, { + address: external_data, + ownership: 1, + runtimeAllocated: 0 + }); + } + } + emnapiExternalSAB.handleTable.set(sab, handle); + emnapiExternalSAB.registry.register(sab, handle); + return sab; + } + var emnapiMod = Object.freeze({ + __proto__: null, + $emnapiAcquireExternalSharedArrayBuffer: $emnapiAcquireExternalSharedArrayBuffer, + $emnapiGetMemoryAddress: $emnapiGetMemoryAddress, + $emnapiSyncMemory: $emnapiSyncMemory, + emnapi_acquire_external_sharedarraybuffer: emnapi_acquire_external_sharedarraybuffer, + emnapi_create_memory_view: emnapi_create_memory_view, + emnapi_get_external_sharedarraybuffer_handle: emnapi_get_external_sharedarraybuffer_handle, + emnapi_get_memory_address: emnapi_get_memory_address, + emnapi_get_runtime_version: emnapi_get_runtime_version, + emnapi_is_node_binding_available: emnapi_is_node_binding_available, + emnapi_is_support_bigint: emnapi_is_support_bigint, + emnapi_is_support_weakref: emnapi_is_support_weakref, + emnapi_release_external_sharedarraybuffer: emnapi_release_external_sharedarraybuffer, + emnapi_sync_memory: emnapi_sync_memory + }); + function napi_create_array(env, result) { + if (!env) + return 1; + var envObject = emnapiCtx.envStore.get(env); + envObject.checkGCAccess(); + if (!result) + return envObject.setLastError(1); + result >>>= 0; + var value = emnapiCtx.addToCurrentScope([]).id; + var HEAP_DATA_VIEW = new DataView(wasmMemory.buffer), GET_HEAP_DATA_VIEW = function () { return HEAP_DATA_VIEW.buffer === wasmMemory.buffer ? HEAP_DATA_VIEW : (HEAP_DATA_VIEW = new DataView(wasmMemory.buffer)); }; + GET_HEAP_DATA_VIEW().setUint32(result, value, true); + return envObject.clearLastError(); + } + function napi_create_array_with_length(env, length, result) { + if (!env) + return 1; + var envObject = emnapiCtx.envStore.get(env); + envObject.checkGCAccess(); + if (!result) + return envObject.setLastError(1); + length >>>= 0; + result >>>= 0; + length = length >>> 0; + var value = emnapiCtx.addToCurrentScope(new Array(length)).id; + var HEAP_DATA_VIEW = new DataView(wasmMemory.buffer), GET_HEAP_DATA_VIEW = function () { return HEAP_DATA_VIEW.buffer === wasmMemory.buffer ? HEAP_DATA_VIEW : (HEAP_DATA_VIEW = new DataView(wasmMemory.buffer)); }; + GET_HEAP_DATA_VIEW().setUint32(result, value, true); + return envObject.clearLastError(); + } + function emnapiCreateArrayBuffer(byte_length, data, shared) { + byte_length >>>= 0; + byte_length = byte_length >>> 0; + var arrayBuffer = shared ? new SharedArrayBuffer(byte_length) : new ArrayBuffer(byte_length); + if (data) { + data >>>= 0; + var p = emnapiExternalMemory.getArrayBufferPointer(arrayBuffer, true).address; + var HEAP_DATA_VIEW = new DataView(wasmMemory.buffer), GET_HEAP_DATA_VIEW = function () { return HEAP_DATA_VIEW.buffer === wasmMemory.buffer ? HEAP_DATA_VIEW : (HEAP_DATA_VIEW = new DataView(wasmMemory.buffer)); }; + GET_HEAP_DATA_VIEW().setUint32(data, p, true); + } + return arrayBuffer; + } + function napi_create_arraybuffer(env, byte_length, data, result) { + var value; + if (!env) + return 1; + var envObject = emnapiCtx.envStore.get(env); + envObject.checkGCAccess(); + if (!envObject.tryCatch.isEmpty()) + return envObject.setLastError(10); + if (!envObject.canCallIntoJs()) + return envObject.setLastError(envObject.moduleApiVersion >= 10 ? 23 : 10); + envObject.clearLastError(); + try { + if (!result) + return envObject.setLastError(1); + result >>>= 0; + var arrayBuffer = emnapiCreateArrayBuffer(byte_length, data, false); + value = emnapiCtx.addToCurrentScope(arrayBuffer).id; + var HEAP_DATA_VIEW = new DataView(wasmMemory.buffer), GET_HEAP_DATA_VIEW = function () { return HEAP_DATA_VIEW.buffer === wasmMemory.buffer ? HEAP_DATA_VIEW : (HEAP_DATA_VIEW = new DataView(wasmMemory.buffer)); }; + GET_HEAP_DATA_VIEW().setUint32(result, value, true); + return envObject.getReturnStatus(); + } + catch (err) { + envObject.tryCatch.setError(err); + return envObject.setLastError(10); + } + } + function node_api_create_sharedarraybuffer(env, byte_length, data, result) { + var value; + if (!env) + return 1; + var envObject = emnapiCtx.envStore.get(env); + envObject.checkGCAccess(); + if (!envObject.tryCatch.isEmpty()) + return envObject.setLastError(10); + if (!envObject.canCallIntoJs()) + return envObject.setLastError(envObject.moduleApiVersion >= 10 ? 23 : 10); + envObject.clearLastError(); + try { + if (!result) + return envObject.setLastError(1); + result >>>= 0; + var arrayBuffer = emnapiCreateArrayBuffer(byte_length, data, true); + value = emnapiCtx.addToCurrentScope(arrayBuffer).id; + var HEAP_DATA_VIEW = new DataView(wasmMemory.buffer), GET_HEAP_DATA_VIEW = function () { return HEAP_DATA_VIEW.buffer === wasmMemory.buffer ? HEAP_DATA_VIEW : (HEAP_DATA_VIEW = new DataView(wasmMemory.buffer)); }; + GET_HEAP_DATA_VIEW().setUint32(result, value, true); + return envObject.getReturnStatus(); + } + catch (err) { + envObject.tryCatch.setError(err); + return envObject.setLastError(10); + } + } + function napi_create_date(env, time, result) { + var value; + if (!env) + return 1; + var envObject = emnapiCtx.envStore.get(env); + envObject.checkGCAccess(); + if (!envObject.tryCatch.isEmpty()) + return envObject.setLastError(10); + if (!envObject.canCallIntoJs()) + return envObject.setLastError(envObject.moduleApiVersion >= 10 ? 23 : 10); + envObject.clearLastError(); + try { + if (!result) + return envObject.setLastError(1); + result >>>= 0; + value = emnapiCtx.addToCurrentScope(new Date(time)).id; + var HEAP_DATA_VIEW = new DataView(wasmMemory.buffer), GET_HEAP_DATA_VIEW = function () { return HEAP_DATA_VIEW.buffer === wasmMemory.buffer ? HEAP_DATA_VIEW : (HEAP_DATA_VIEW = new DataView(wasmMemory.buffer)); }; + GET_HEAP_DATA_VIEW().setUint32(result, value, true); + return envObject.getReturnStatus(); + } + catch (err) { + envObject.tryCatch.setError(err); + return envObject.setLastError(10); + } + } + function napi_create_external(env, data, finalize_cb, finalize_hint, result) { + var value; + if (!env) + return 1; + var envObject = emnapiCtx.envStore.get(env); + envObject.checkGCAccess(); + if (!envObject.tryCatch.isEmpty()) + return envObject.setLastError(10); + if (!envObject.canCallIntoJs()) + return envObject.setLastError(envObject.moduleApiVersion >= 10 ? 23 : 10); + envObject.clearLastError(); + try { + if (!result) + return envObject.setLastError(1); + if (!emnapiCtx.feature.supportFinalizer && finalize_cb) { + throw emnapiCtx.createNotSupportWeakRefError('napi_create_external', 'Parameter "finalize_cb" must be 0(NULL)'); + } + var externalHandle = emnapiCtx.getCurrentScope().addExternal(data); + if (finalize_cb) { + emnapiCtx.createReferenceWithFinalizer(envObject, externalHandle.id, 0, 0, finalize_cb, data, finalize_hint); + } + result >>>= 0; + value = externalHandle.id; + var HEAP_DATA_VIEW = new DataView(wasmMemory.buffer), GET_HEAP_DATA_VIEW = function () { return HEAP_DATA_VIEW.buffer === wasmMemory.buffer ? HEAP_DATA_VIEW : (HEAP_DATA_VIEW = new DataView(wasmMemory.buffer)); }; + GET_HEAP_DATA_VIEW().setUint32(result, value, true); + return envObject.clearLastError(); + } + catch (err) { + envObject.tryCatch.setError(err); + return envObject.setLastError(10); + } + } + function napi_create_external_arraybuffer(env, external_data, byte_length, finalize_cb, finalize_hint, result) { + var value; + if (!env) + return 1; + var envObject = emnapiCtx.envStore.get(env); + envObject.checkGCAccess(); + if (!envObject.tryCatch.isEmpty()) + return envObject.setLastError(10); + if (!envObject.canCallIntoJs()) + return envObject.setLastError(envObject.moduleApiVersion >= 10 ? 23 : 10); + envObject.clearLastError(); + try { + if (!result) + return envObject.setLastError(1); + byte_length >>>= 0; + external_data >>>= 0; + result >>>= 0; + byte_length = byte_length >>> 0; + if (!external_data) { + byte_length = 0; + } + if ((external_data + byte_length) > wasmMemory.buffer.byteLength) { + throw new RangeError('Memory out of range'); + } + if (!emnapiCtx.feature.supportFinalizer && finalize_cb) { + throw emnapiCtx.createNotSupportWeakRefError('napi_create_external_arraybuffer', 'Parameter "finalize_cb" must be 0(NULL)'); + } + var arrayBuffer = new ArrayBuffer(byte_length); + if (byte_length === 0) { + try { + var MessageChannel_1 = emnapiCtx.feature.MessageChannel; + var messageChannel = new MessageChannel_1(); + messageChannel.port1.postMessage(arrayBuffer, [arrayBuffer]); + } + catch (_) { } + } + else { + var u8arr = new Uint8Array(arrayBuffer); + u8arr.set(new Uint8Array(wasmMemory.buffer).subarray(external_data, external_data + byte_length)); + emnapiExternalMemory.table.set(arrayBuffer, { + address: external_data, + ownership: 1, + runtimeAllocated: 0 + }); + } + var handle = emnapiCtx.addToCurrentScope(arrayBuffer); + if (finalize_cb) { + var status_1 = napi_add_finalizer(env, handle.id, external_data, finalize_cb, finalize_hint, 0); + if (status_1 === 10) { + var err = envObject.tryCatch.extractException(); + envObject.clearLastError(); + throw err; + } + else if (status_1 !== 0) { + return envObject.setLastError(status_1); + } + } + value = handle.id; + var HEAP_DATA_VIEW = new DataView(wasmMemory.buffer), GET_HEAP_DATA_VIEW = function () { return HEAP_DATA_VIEW.buffer === wasmMemory.buffer ? HEAP_DATA_VIEW : (HEAP_DATA_VIEW = new DataView(wasmMemory.buffer)); }; + GET_HEAP_DATA_VIEW().setUint32(result, value, true); + return envObject.getReturnStatus(); + } + catch (err) { + envObject.tryCatch.setError(err); + return envObject.setLastError(10); + } + } + function node_api_create_external_sharedarraybuffer(env, external_data, byte_length, finalize_cb, finalize_hint, result) { + var value; + if (!env) + return 1; + var envObject = emnapiCtx.envStore.get(env); + envObject.checkGCAccess(); + if (!envObject.tryCatch.isEmpty()) + return envObject.setLastError(10); + if (!envObject.canCallIntoJs()) + return envObject.setLastError(envObject.moduleApiVersion >= 10 ? 23 : 10); + envObject.clearLastError(); + try { + if (!result) + return envObject.setLastError(1); + byte_length >>>= 0; + external_data >>>= 0; + result >>>= 0; + byte_length = byte_length >>> 0; + if (!external_data) { + byte_length = 0; + } + if ((external_data + byte_length) > wasmMemory.buffer.byteLength) { + throw new RangeError('Memory out of range'); + } + if (!emnapiExternalSAB.registry && finalize_cb) { + throw emnapiCtx.createNotSupportWeakRefError('node_api_create_external_sharedarraybuffer', 'Parameter "finalize_cb" must be 0(NULL)'); + } + var sharedArrayBuffer = new SharedArrayBuffer(byte_length); + if (byte_length !== 0) { + var u8arr = new Uint8Array(sharedArrayBuffer); + u8arr.set(new Uint8Array(wasmMemory.buffer).subarray(external_data, external_data + byte_length)); + emnapiExternalMemory.table.set(sharedArrayBuffer, { + address: external_data, + ownership: 1, + runtimeAllocated: 0 + }); + } + value = emnapiCtx.addToCurrentScope(sharedArrayBuffer).id; + if (finalize_cb) { + finalize_cb >>>= 0; + finalize_hint >>>= 0; + var metaPtr = emnapiExternalSAB.allocMeta(external_data, byte_length, finalize_cb, external_data, finalize_hint); + emnapiExternalSAB.handleTable.set(sharedArrayBuffer, metaPtr); + emnapiExternalSAB.registry.register(sharedArrayBuffer, metaPtr); + } + var HEAP_DATA_VIEW = new DataView(wasmMemory.buffer), GET_HEAP_DATA_VIEW = function () { return HEAP_DATA_VIEW.buffer === wasmMemory.buffer ? HEAP_DATA_VIEW : (HEAP_DATA_VIEW = new DataView(wasmMemory.buffer)); }; + GET_HEAP_DATA_VIEW().setUint32(result, value, true); + return envObject.getReturnStatus(); + } + catch (err) { + envObject.tryCatch.setError(err); + return envObject.setLastError(10); + } + } + function napi_create_object(env, result) { + if (!env) + return 1; + var envObject = emnapiCtx.envStore.get(env); + envObject.checkGCAccess(); + if (!result) + return envObject.setLastError(1); + result >>>= 0; + var value = emnapiCtx.addToCurrentScope({}).id; + var HEAP_DATA_VIEW = new DataView(wasmMemory.buffer), GET_HEAP_DATA_VIEW = function () { return HEAP_DATA_VIEW.buffer === wasmMemory.buffer ? HEAP_DATA_VIEW : (HEAP_DATA_VIEW = new DataView(wasmMemory.buffer)); }; + GET_HEAP_DATA_VIEW().setUint32(result, value, true); + return envObject.clearLastError(); + } + function node_api_create_object_with_properties(env, prototype_or_null, property_names, property_values, property_count, result) { + if (!env) + return 1; + var envObject = emnapiCtx.envStore.get(env); + envObject.checkGCAccess(); + if (!result) + return envObject.setLastError(1); + property_count >>>= 0; + property_count = property_count >>> 0; + if (property_count > 0) { + if (!property_names) + return envObject.setLastError(1); + if (!property_values) + return envObject.setLastError(1); + } + var v8_prototype_or_null = prototype_or_null + ? emnapiCtx.handleStore.get(prototype_or_null).value + : null; + var properties = {}; + property_names >>>= 0; + property_values >>>= 0; + var HEAP_DATA_VIEW = new DataView(wasmMemory.buffer), GET_HEAP_DATA_VIEW = function () { return HEAP_DATA_VIEW.buffer === wasmMemory.buffer ? HEAP_DATA_VIEW : (HEAP_DATA_VIEW = new DataView(wasmMemory.buffer)); }; + for (var i = 0; i < property_count; i++) { + var name_value = emnapiCtx.handleStore.get(GET_HEAP_DATA_VIEW().getUint32(property_names + i * 4, true)).value; + if (!(typeof name_value === "string" || typeof name_value === "symbol")) + return envObject.setLastError(4); + properties[name_value] = { + value: emnapiCtx.handleStore.get(GET_HEAP_DATA_VIEW().getUint32(property_values + i * 4, true)).value, + writable: true, + enumerable: true, + configurable: true + }; + } + var obj; + try { + obj = Object.defineProperties(Object.create(v8_prototype_or_null), properties); + } + catch (_) { + return envObject.setLastError(9); + } + var value = emnapiCtx.addToCurrentScope(obj).id; + result >>>= 0; + GET_HEAP_DATA_VIEW().setUint32(result, value, true); + return envObject.clearLastError(); + } + function napi_create_symbol(env, description, result) { + if (!env) + return 1; + var envObject = emnapiCtx.envStore.get(env); + envObject.checkGCAccess(); + if (!result) + return envObject.setLastError(1); + result >>>= 0; + var HEAP_DATA_VIEW = new DataView(wasmMemory.buffer), GET_HEAP_DATA_VIEW = function () { return HEAP_DATA_VIEW.buffer === wasmMemory.buffer ? HEAP_DATA_VIEW : (HEAP_DATA_VIEW = new DataView(wasmMemory.buffer)); }; + if (!description) { + var value = emnapiCtx.addToCurrentScope(Symbol()).id; + GET_HEAP_DATA_VIEW().setUint32(result, value, true); + } + else { + var handle = emnapiCtx.handleStore.get(description); + var desc = handle.value; + if (typeof desc !== 'string') { + return envObject.setLastError(3); + } + var v = emnapiCtx.addToCurrentScope(Symbol(desc)).id; + GET_HEAP_DATA_VIEW().setUint32(result, v, true); + } + return envObject.clearLastError(); + } + function napi_create_typedarray(env, type, length, arraybuffer, byte_offset, result) { + var value; + if (!env) + return 1; + var envObject = emnapiCtx.envStore.get(env); + envObject.checkGCAccess(); + if (!envObject.tryCatch.isEmpty()) + return envObject.setLastError(10); + if (!envObject.canCallIntoJs()) + return envObject.setLastError(envObject.moduleApiVersion >= 10 ? 23 : 10); + envObject.clearLastError(); + try { + if (!arraybuffer) + return envObject.setLastError(1); + if (!result) + return envObject.setLastError(1); + var handle = emnapiCtx.handleStore.get(arraybuffer); + var buffer = handle.value; + byte_offset >>>= 0; + length >>>= 0; + var createTypedArray = function (envObject, Type, size_of_element, buffer, byte_offset, length) { + var _a; + byte_offset = byte_offset >>> 0; + length = length >>> 0; + if (size_of_element > 1) { + if ((byte_offset) % (size_of_element) !== 0) { + var err = new RangeError("start offset of ".concat((_a = Type.name) !== null && _a !== void 0 ? _a : '', " should be a multiple of ").concat(size_of_element)); + err.code = 'ERR_NAPI_INVALID_TYPEDARRAY_ALIGNMENT'; + envObject.tryCatch.setError(err); + return envObject.setLastError(9); + } + } + if (((length * size_of_element) + byte_offset) > buffer.byteLength) { + var err = new RangeError('Invalid typed array length'); + err.code = 'ERR_NAPI_INVALID_TYPEDARRAY_LENGTH'; + envObject.tryCatch.setError(err); + return envObject.setLastError(9); + } + var out = new Type(buffer, byte_offset, length); + if (buffer === wasmMemory.buffer) { + if (!emnapiExternalMemory.wasmMemoryViewTable.has(out)) { + emnapiExternalMemory.wasmMemoryViewTable.set(out, { + Ctor: Type, + address: byte_offset, + length: length, + ownership: 1, + runtimeAllocated: 0 + }); + } + } + result >>>= 0; + value = emnapiCtx.addToCurrentScope(out).id; + var HEAP_DATA_VIEW = new DataView(wasmMemory.buffer), GET_HEAP_DATA_VIEW = function () { return HEAP_DATA_VIEW.buffer === wasmMemory.buffer ? HEAP_DATA_VIEW : (HEAP_DATA_VIEW = new DataView(wasmMemory.buffer)); }; + GET_HEAP_DATA_VIEW().setUint32(result, value, true); + return envObject.getReturnStatus(); + }; + if (buffer instanceof ArrayBuffer || emnapiExternalMemory.isSharedArrayBuffer(buffer)) { + switch (type) { + case 0: + return createTypedArray(envObject, Int8Array, 1, buffer, byte_offset, length); + case 1: + return createTypedArray(envObject, Uint8Array, 1, buffer, byte_offset, length); + case 2: + return createTypedArray(envObject, Uint8ClampedArray, 1, buffer, byte_offset, length); + case 3: + return createTypedArray(envObject, Int16Array, 2, buffer, byte_offset, length); + case 4: + return createTypedArray(envObject, Uint16Array, 2, buffer, byte_offset, length); + case 5: + return createTypedArray(envObject, Int32Array, 4, buffer, byte_offset, length); + case 6: + return createTypedArray(envObject, Uint32Array, 4, buffer, byte_offset, length); + case 7: + return createTypedArray(envObject, Float32Array, 4, buffer, byte_offset, length); + case 8: + return createTypedArray(envObject, Float64Array, 8, buffer, byte_offset, length); + case 9: + return createTypedArray(envObject, BigInt64Array, 8, buffer, byte_offset, length); + case 10: + return createTypedArray(envObject, BigUint64Array, 8, buffer, byte_offset, length); + case 11: + if (typeof Float16Array !== 'function') { + return envObject.setLastError(1); + } + return createTypedArray(envObject, Float16Array, 2, buffer, byte_offset, length); + default: + return envObject.setLastError(1); + } + } + else { + return envObject.setLastError(1); + } + } + catch (err) { + envObject.tryCatch.setError(err); + return envObject.setLastError(10); + } + } + function napi_create_buffer(env, size, data, result) { + var _a; + var value, pointer; + if (!env) + return 1; + var envObject = emnapiCtx.envStore.get(env); + envObject.checkGCAccess(); + if (!envObject.tryCatch.isEmpty()) + return envObject.setLastError(10); + if (!envObject.canCallIntoJs()) + return envObject.setLastError(envObject.moduleApiVersion >= 10 ? 23 : 10); + envObject.clearLastError(); + try { + if (!result) + return envObject.setLastError(1); + var Buffer = emnapiCtx.feature.Buffer; + if (!Buffer) { + throw emnapiCtx.createNotSupportBufferError('napi_create_buffer', ''); + } + result >>>= 0; + var buffer = void 0; + size >>>= 0; + size = size >>> 0; + var HEAP_DATA_VIEW = new DataView(wasmMemory.buffer), GET_HEAP_DATA_VIEW = function () { return HEAP_DATA_VIEW.buffer === wasmMemory.buffer ? HEAP_DATA_VIEW : (HEAP_DATA_VIEW = new DataView(wasmMemory.buffer)); }; + if (!data || (size === 0)) { + buffer = Buffer.alloc(size); + value = emnapiCtx.addToCurrentScope(buffer).id; + GET_HEAP_DATA_VIEW().setUint32(result, value, true); + } + else { + pointer = _malloc(size); + if (!pointer) + throw new Error('Out of memory'); + pointer >>>= 0; + new Uint8Array(wasmMemory.buffer).subarray(pointer, pointer + size).fill(0); + var buffer_1 = emnapiExternalMemory.getBufferFrom()(wasmMemory.buffer, pointer, size); + var viewDescriptor = { + Ctor: Buffer, + address: pointer, + length: size, + ownership: emnapiExternalMemory.registry ? 0 : 1, + runtimeAllocated: 1 + }; + emnapiExternalMemory.wasmMemoryViewTable.set(buffer_1, viewDescriptor); + (_a = emnapiExternalMemory.registry) === null || _a === void 0 ? void 0 : _a.register(viewDescriptor, pointer); + value = emnapiCtx.addToCurrentScope(buffer_1).id; + GET_HEAP_DATA_VIEW().setUint32(result, value, true); + data >>>= 0; + GET_HEAP_DATA_VIEW().setUint32(data, pointer, true); + } + return envObject.getReturnStatus(); + } + catch (err) { + envObject.tryCatch.setError(err); + return envObject.setLastError(10); + } + } + function napi_create_buffer_copy(env, length, data, result_data, result) { + var value; + if (!env) + return 1; + var envObject = emnapiCtx.envStore.get(env); + envObject.checkGCAccess(); + if (!envObject.tryCatch.isEmpty()) + return envObject.setLastError(10); + if (!envObject.canCallIntoJs()) + return envObject.setLastError(envObject.moduleApiVersion >= 10 ? 23 : 10); + envObject.clearLastError(); + try { + if (!result) + return envObject.setLastError(1); + var Buffer = emnapiCtx.feature.Buffer; + if (!Buffer) { + throw emnapiCtx.createNotSupportBufferError('napi_create_buffer_copy', ''); + } + var arrayBuffer = emnapiCreateArrayBuffer(length, result_data, false); + var buffer = Buffer.from(arrayBuffer); + data >>>= 0; + length >>>= 0; + buffer.set(new Uint8Array(wasmMemory.buffer).subarray(data, data + length)); + value = emnapiCtx.addToCurrentScope(buffer).id; + result >>>= 0; + var HEAP_DATA_VIEW = new DataView(wasmMemory.buffer), GET_HEAP_DATA_VIEW = function () { return HEAP_DATA_VIEW.buffer === wasmMemory.buffer ? HEAP_DATA_VIEW : (HEAP_DATA_VIEW = new DataView(wasmMemory.buffer)); }; + GET_HEAP_DATA_VIEW().setUint32(result, value, true); + return envObject.getReturnStatus(); + } + catch (err) { + envObject.tryCatch.setError(err); + return envObject.setLastError(10); + } + } + function napi_create_external_buffer(env, length, data, finalize_cb, finalize_hint, result) { + return emnapi_create_memory_view(env, -2, data, length, finalize_cb, finalize_hint, result); + } + function node_api_create_buffer_from_arraybuffer(env, arraybuffer, byte_offset, byte_length, result) { + var value; + if (!env) + return 1; + var envObject = emnapiCtx.envStore.get(env); + envObject.checkGCAccess(); + if (!envObject.tryCatch.isEmpty()) + return envObject.setLastError(10); + if (!envObject.canCallIntoJs()) + return envObject.setLastError(envObject.moduleApiVersion >= 10 ? 23 : 10); + envObject.clearLastError(); + try { + if (!arraybuffer) + return envObject.setLastError(1); + if (!result) + return envObject.setLastError(1); + byte_offset >>>= 0; + byte_length >>>= 0; + byte_offset = byte_offset >>> 0; + byte_length = byte_length >>> 0; + var handle = emnapiCtx.handleStore.get(arraybuffer); + if (!handle.isArrayBuffer()) { + return envObject.setLastError(1); + } + var buffer = handle.value; + if ((byte_length + byte_offset) > buffer.byteLength) { + var err = new RangeError('The byte offset + length is out of range'); + err.code = 'ERR_OUT_OF_RANGE'; + throw err; + } + var Buffer = emnapiCtx.feature.Buffer; + if (!Buffer) { + throw emnapiCtx.createNotSupportBufferError('node_api_create_buffer_from_arraybuffer', ''); + } + var out = emnapiExternalMemory.getBufferFrom()(buffer, byte_offset, byte_length); + if (buffer === wasmMemory.buffer) { + if (!emnapiExternalMemory.wasmMemoryViewTable.has(out)) { + emnapiExternalMemory.wasmMemoryViewTable.set(out, { + Ctor: Buffer, + address: byte_offset, + length: byte_length, + ownership: 1, + runtimeAllocated: 0 + }); + } + } + result >>>= 0; + value = emnapiCtx.addToCurrentScope(out).id; + var HEAP_DATA_VIEW = new DataView(wasmMemory.buffer), GET_HEAP_DATA_VIEW = function () { return HEAP_DATA_VIEW.buffer === wasmMemory.buffer ? HEAP_DATA_VIEW : (HEAP_DATA_VIEW = new DataView(wasmMemory.buffer)); }; + GET_HEAP_DATA_VIEW().setUint32(result, value, true); + return envObject.getReturnStatus(); + } + catch (err) { + envObject.tryCatch.setError(err); + return envObject.setLastError(10); + } + } + function napi_create_dataview(env, byte_length, arraybuffer, byte_offset, result) { + if (!env) + return 1; + var envObject = emnapiCtx.envStore.get(env); + envObject.checkGCAccess(); + if (!envObject.tryCatch.isEmpty()) + return envObject.setLastError(10); + if (!envObject.canCallIntoJs()) + return envObject.setLastError(envObject.moduleApiVersion >= 10 ? 23 : 10); + envObject.clearLastError(); + try { + if (!arraybuffer) + return envObject.setLastError(1); + if (!result) + return envObject.setLastError(1); + byte_length >>>= 0; + byte_offset >>>= 0; + byte_length = byte_length >>> 0; + byte_offset = byte_offset >>> 0; + var value = emnapiCtx.handleStore.get(arraybuffer).value; + var createDataview = function (buffer) { + if ((byte_length + byte_offset) > buffer.byteLength) { + var err = new RangeError('byte_offset + byte_length should be less than or equal to the size in bytes of the array passed in'); + err.code = 'ERR_NAPI_INVALID_DATAVIEW_ARGS'; + throw err; + } + var dataview = new DataView(buffer, byte_offset, byte_length); + if (buffer === wasmMemory.buffer) { + if (!emnapiExternalMemory.wasmMemoryViewTable.has(dataview)) { + emnapiExternalMemory.wasmMemoryViewTable.set(dataview, { + Ctor: DataView, + address: byte_offset, + length: byte_length, + ownership: 1, + runtimeAllocated: 0 + }); + } + } + result >>>= 0; + var v = emnapiCtx.addToCurrentScope(dataview).id; + var HEAP_DATA_VIEW = new DataView(wasmMemory.buffer), GET_HEAP_DATA_VIEW = function () { return HEAP_DATA_VIEW.buffer === wasmMemory.buffer ? HEAP_DATA_VIEW : (HEAP_DATA_VIEW = new DataView(wasmMemory.buffer)); }; + GET_HEAP_DATA_VIEW().setUint32(result, v, true); + return envObject.getReturnStatus(); + }; + if (value instanceof ArrayBuffer || emnapiExternalMemory.isSharedArrayBuffer(value)) { + return createDataview(value); + } + else { + return envObject.setLastError(1); + } + } + catch (err) { + envObject.tryCatch.setError(err); + return envObject.setLastError(10); + } + } + function node_api_symbol_for(env, utf8description, length, result) { + if (!env) + return 1; + var envObject = emnapiCtx.envStore.get(env); + envObject.checkGCAccess(); + if (!result) + return envObject.setLastError(1); + length >>>= 0; + utf8description >>>= 0; + result >>>= 0; + var autoLength = length === -1 || length === 4294967295; + var sizelength = length >>> 0; + if (length !== 0) { + if (!utf8description) + return envObject.setLastError(1); + } + if (!(autoLength || (sizelength <= 2147483647))) { + return envObject.setLastError(1); + } + var descriptionString = emnapiString.UTF8ToString(utf8description, length); + var value = emnapiCtx.addToCurrentScope(Symbol.for(descriptionString)).id; + var HEAP_DATA_VIEW = new DataView(wasmMemory.buffer), GET_HEAP_DATA_VIEW = function () { return HEAP_DATA_VIEW.buffer === wasmMemory.buffer ? HEAP_DATA_VIEW : (HEAP_DATA_VIEW = new DataView(wasmMemory.buffer)); }; + GET_HEAP_DATA_VIEW().setUint32(result, value, true); + return envObject.clearLastError(); + } + var createMod = Object.freeze({ + __proto__: null, + napi_create_array: napi_create_array, + napi_create_array_with_length: napi_create_array_with_length, + napi_create_arraybuffer: napi_create_arraybuffer, + napi_create_buffer: napi_create_buffer, + napi_create_buffer_copy: napi_create_buffer_copy, + napi_create_dataview: napi_create_dataview, + napi_create_date: napi_create_date, + napi_create_external: napi_create_external, + napi_create_external_arraybuffer: napi_create_external_arraybuffer, + napi_create_external_buffer: napi_create_external_buffer, + napi_create_object: napi_create_object, + napi_create_symbol: napi_create_symbol, + napi_create_typedarray: napi_create_typedarray, + node_api_create_buffer_from_arraybuffer: node_api_create_buffer_from_arraybuffer, + node_api_create_external_sharedarraybuffer: node_api_create_external_sharedarraybuffer, + node_api_create_object_with_properties: node_api_create_object_with_properties, + node_api_create_sharedarraybuffer: node_api_create_sharedarraybuffer, + node_api_symbol_for: node_api_symbol_for + }); + function napi_get_boolean(env, value, result) { + if (!env) + return 1; + var envObject = emnapiCtx.envStore.get(env); + envObject.checkGCAccess(); + if (!result) + return envObject.setLastError(1); + result >>>= 0; + var v = value === 0 ? 3 : 4; + var HEAP_DATA_VIEW = new DataView(wasmMemory.buffer), GET_HEAP_DATA_VIEW = function () { return HEAP_DATA_VIEW.buffer === wasmMemory.buffer ? HEAP_DATA_VIEW : (HEAP_DATA_VIEW = new DataView(wasmMemory.buffer)); }; + GET_HEAP_DATA_VIEW().setUint32(result, v, true); + return envObject.clearLastError(); + } + function napi_get_global(env, result) { + if (!env) + return 1; + var envObject = emnapiCtx.envStore.get(env); + envObject.checkGCAccess(); + if (!result) + return envObject.setLastError(1); + result >>>= 0; + var value = 5; + var HEAP_DATA_VIEW = new DataView(wasmMemory.buffer), GET_HEAP_DATA_VIEW = function () { return HEAP_DATA_VIEW.buffer === wasmMemory.buffer ? HEAP_DATA_VIEW : (HEAP_DATA_VIEW = new DataView(wasmMemory.buffer)); }; + GET_HEAP_DATA_VIEW().setUint32(result, value, true); + return envObject.clearLastError(); + } + function napi_get_null(env, result) { + if (!env) + return 1; + var envObject = emnapiCtx.envStore.get(env); + envObject.checkGCAccess(); + if (!result) + return envObject.setLastError(1); + result >>>= 0; + var value = 2; + var HEAP_DATA_VIEW = new DataView(wasmMemory.buffer), GET_HEAP_DATA_VIEW = function () { return HEAP_DATA_VIEW.buffer === wasmMemory.buffer ? HEAP_DATA_VIEW : (HEAP_DATA_VIEW = new DataView(wasmMemory.buffer)); }; + GET_HEAP_DATA_VIEW().setUint32(result, value, true); + return envObject.clearLastError(); + } + function napi_get_undefined(env, result) { + if (!env) + return 1; + var envObject = emnapiCtx.envStore.get(env); + envObject.checkGCAccess(); + if (!result) + return envObject.setLastError(1); + result >>>= 0; + var value = 1; + var HEAP_DATA_VIEW = new DataView(wasmMemory.buffer), GET_HEAP_DATA_VIEW = function () { return HEAP_DATA_VIEW.buffer === wasmMemory.buffer ? HEAP_DATA_VIEW : (HEAP_DATA_VIEW = new DataView(wasmMemory.buffer)); }; + GET_HEAP_DATA_VIEW().setUint32(result, value, true); + return envObject.clearLastError(); + } + var globalMod = Object.freeze({ + __proto__: null, + napi_get_boolean: napi_get_boolean, + napi_get_global: napi_get_global, + napi_get_null: napi_get_null, + napi_get_undefined: napi_get_undefined + }); + function napi_set_instance_data(env, data, finalize_cb, finalize_hint) { + if (!env) + return 1; + var envObject = emnapiCtx.envStore.get(env); + data >>>= 0; + finalize_cb >>>= 0; + finalize_hint >>>= 0; + envObject.setInstanceData(data, finalize_cb, finalize_hint); + return envObject.clearLastError(); + } + function napi_get_instance_data(env, data) { + if (!env) + return 1; + var envObject = emnapiCtx.envStore.get(env); + if (!data) + return envObject.setLastError(1); + data >>>= 0; + var value = envObject.getInstanceData(); + var HEAP_DATA_VIEW = new DataView(wasmMemory.buffer), GET_HEAP_DATA_VIEW = function () { return HEAP_DATA_VIEW.buffer === wasmMemory.buffer ? HEAP_DATA_VIEW : (HEAP_DATA_VIEW = new DataView(wasmMemory.buffer)); }; + GET_HEAP_DATA_VIEW().setUint32(data, value, true); + return envObject.clearLastError(); + } + var envMod = Object.freeze({ + __proto__: null, + napi_get_instance_data: napi_get_instance_data, + napi_set_instance_data: napi_set_instance_data + }); + function _emnapi_get_last_error_info(env, error_code, engine_error_code, engine_reserved) { + error_code >>>= 0; + engine_error_code >>>= 0; + engine_reserved >>>= 0; + var envObject = emnapiCtx.envStore.get(env); + var lastError = envObject.lastError; + var errorCode = lastError.errorCode; + var engineErrorCode = lastError.engineErrorCode >>> 0; + var engineReserved = lastError.engineReserved; + engineReserved >>>= 0; + var HEAP_DATA_VIEW = new DataView(wasmMemory.buffer), GET_HEAP_DATA_VIEW = function () { return HEAP_DATA_VIEW.buffer === wasmMemory.buffer ? HEAP_DATA_VIEW : (HEAP_DATA_VIEW = new DataView(wasmMemory.buffer)); }; + GET_HEAP_DATA_VIEW().setInt32(error_code, errorCode, true); + GET_HEAP_DATA_VIEW().setUint32(engine_error_code, engineErrorCode, true); + GET_HEAP_DATA_VIEW().setUint32(engine_reserved, engineReserved, true); + } + function napi_throw(env, error) { + if (!env) + return 1; + var envObject = emnapiCtx.envStore.get(env); + envObject.checkGCAccess(); + if (!envObject.tryCatch.isEmpty()) + return envObject.setLastError(10); + if (!envObject.canCallIntoJs()) + return envObject.setLastError(envObject.moduleApiVersion >= 10 ? 23 : 10); + envObject.clearLastError(); + try { + if (!error) + return envObject.setLastError(1); + envObject.tryCatch.setError(emnapiCtx.handleStore.get(error).value); + return envObject.clearLastError(); + } + catch (err) { + envObject.tryCatch.setError(err); + return envObject.setLastError(10); + } + } + function napi_throw_error(env, code, msg) { + if (!env) + return 1; + var envObject = emnapiCtx.envStore.get(env); + envObject.checkGCAccess(); + if (!envObject.tryCatch.isEmpty()) + return envObject.setLastError(10); + if (!envObject.canCallIntoJs()) + return envObject.setLastError(envObject.moduleApiVersion >= 10 ? 23 : 10); + envObject.clearLastError(); + try { + if (!msg) + return envObject.setLastError(1); + code >>>= 0; + msg >>>= 0; + var error = new Error(emnapiString.UTF8ToString(msg, -1)); + if (code) + error.code = emnapiString.UTF8ToString(code, -1); + envObject.tryCatch.setError(error); + return envObject.clearLastError(); + } + catch (err) { + envObject.tryCatch.setError(err); + return envObject.setLastError(10); + } + } + function napi_throw_type_error(env, code, msg) { + if (!env) + return 1; + var envObject = emnapiCtx.envStore.get(env); + envObject.checkGCAccess(); + if (!envObject.tryCatch.isEmpty()) + return envObject.setLastError(10); + if (!envObject.canCallIntoJs()) + return envObject.setLastError(envObject.moduleApiVersion >= 10 ? 23 : 10); + envObject.clearLastError(); + try { + if (!msg) + return envObject.setLastError(1); + code >>>= 0; + msg >>>= 0; + var error = new TypeError(emnapiString.UTF8ToString(msg, -1)); + if (code) + error.code = emnapiString.UTF8ToString(code, -1); + envObject.tryCatch.setError(error); + return envObject.clearLastError(); + } + catch (err) { + envObject.tryCatch.setError(err); + return envObject.setLastError(10); + } + } + function napi_throw_range_error(env, code, msg) { + if (!env) + return 1; + var envObject = emnapiCtx.envStore.get(env); + envObject.checkGCAccess(); + if (!envObject.tryCatch.isEmpty()) + return envObject.setLastError(10); + if (!envObject.canCallIntoJs()) + return envObject.setLastError(envObject.moduleApiVersion >= 10 ? 23 : 10); + envObject.clearLastError(); + try { + if (!msg) + return envObject.setLastError(1); + code >>>= 0; + msg >>>= 0; + var error = new RangeError(emnapiString.UTF8ToString(msg, -1)); + if (code) + error.code = emnapiString.UTF8ToString(code, -1); + envObject.tryCatch.setError(error); + return envObject.clearLastError(); + } + catch (err) { + envObject.tryCatch.setError(err); + return envObject.setLastError(10); + } + } + function node_api_throw_syntax_error(env, code, msg) { + if (!env) + return 1; + var envObject = emnapiCtx.envStore.get(env); + envObject.checkGCAccess(); + if (!envObject.tryCatch.isEmpty()) + return envObject.setLastError(10); + if (!envObject.canCallIntoJs()) + return envObject.setLastError(envObject.moduleApiVersion >= 10 ? 23 : 10); + envObject.clearLastError(); + try { + if (!msg) + return envObject.setLastError(1); + code >>>= 0; + msg >>>= 0; + var error = new SyntaxError(emnapiString.UTF8ToString(msg, -1)); + if (code) + error.code = emnapiString.UTF8ToString(code, -1); + envObject.tryCatch.setError(error); + return envObject.clearLastError(); + } + catch (err) { + envObject.tryCatch.setError(err); + return envObject.setLastError(10); + } + } + function napi_is_exception_pending(env, result) { + if (!env) + return 1; + var envObject = emnapiCtx.envStore.get(env); + envObject.checkGCAccess(); + if (!result) + return envObject.setLastError(1); + var r = envObject.tryCatch.hasCaught(); + result >>>= 0; + var HEAP_DATA_VIEW = new DataView(wasmMemory.buffer), GET_HEAP_DATA_VIEW = function () { return HEAP_DATA_VIEW.buffer === wasmMemory.buffer ? HEAP_DATA_VIEW : (HEAP_DATA_VIEW = new DataView(wasmMemory.buffer)); }; + GET_HEAP_DATA_VIEW().setInt8(result, r ? 1 : 0, true); + return envObject.clearLastError(); + } + function napi_create_error(env, code, msg, result) { + if (!env) + return 1; + var envObject = emnapiCtx.envStore.get(env); + envObject.checkGCAccess(); + if (!msg) + return envObject.setLastError(1); + if (!result) + return envObject.setLastError(1); + var msgValue = emnapiCtx.handleStore.get(msg).value; + if (typeof msgValue !== 'string') { + return envObject.setLastError(3); + } + var error = new Error(msgValue); + if (code) { + var codeValue = emnapiCtx.handleStore.get(code).value; + if (typeof codeValue !== 'string') { + return envObject.setLastError(3); + } + error.code = codeValue; + } + result >>>= 0; + var value = emnapiCtx.addToCurrentScope(error).id; + var HEAP_DATA_VIEW = new DataView(wasmMemory.buffer), GET_HEAP_DATA_VIEW = function () { return HEAP_DATA_VIEW.buffer === wasmMemory.buffer ? HEAP_DATA_VIEW : (HEAP_DATA_VIEW = new DataView(wasmMemory.buffer)); }; + GET_HEAP_DATA_VIEW().setUint32(result, value, true); + return envObject.clearLastError(); + } + function napi_create_type_error(env, code, msg, result) { + if (!env) + return 1; + var envObject = emnapiCtx.envStore.get(env); + envObject.checkGCAccess(); + if (!msg) + return envObject.setLastError(1); + if (!result) + return envObject.setLastError(1); + var msgValue = emnapiCtx.handleStore.get(msg).value; + if (typeof msgValue !== 'string') { + return envObject.setLastError(3); + } + var error = new TypeError(msgValue); + if (code) { + var codeValue = emnapiCtx.handleStore.get(code).value; + if (typeof codeValue !== 'string') { + return envObject.setLastError(3); + } + error.code = codeValue; + } + result >>>= 0; + var value = emnapiCtx.addToCurrentScope(error).id; + var HEAP_DATA_VIEW = new DataView(wasmMemory.buffer), GET_HEAP_DATA_VIEW = function () { return HEAP_DATA_VIEW.buffer === wasmMemory.buffer ? HEAP_DATA_VIEW : (HEAP_DATA_VIEW = new DataView(wasmMemory.buffer)); }; + GET_HEAP_DATA_VIEW().setUint32(result, value, true); + return envObject.clearLastError(); + } + function napi_create_range_error(env, code, msg, result) { + if (!env) + return 1; + var envObject = emnapiCtx.envStore.get(env); + envObject.checkGCAccess(); + if (!msg) + return envObject.setLastError(1); + if (!result) + return envObject.setLastError(1); + var msgValue = emnapiCtx.handleStore.get(msg).value; + if (typeof msgValue !== 'string') { + return envObject.setLastError(3); + } + var error = new RangeError(msgValue); + if (code) { + var codeValue = emnapiCtx.handleStore.get(code).value; + if (typeof codeValue !== 'string') { + return envObject.setLastError(3); + } + error.code = codeValue; + } + result >>>= 0; + var value = emnapiCtx.addToCurrentScope(error).id; + var HEAP_DATA_VIEW = new DataView(wasmMemory.buffer), GET_HEAP_DATA_VIEW = function () { return HEAP_DATA_VIEW.buffer === wasmMemory.buffer ? HEAP_DATA_VIEW : (HEAP_DATA_VIEW = new DataView(wasmMemory.buffer)); }; + GET_HEAP_DATA_VIEW().setUint32(result, value, true); + return envObject.clearLastError(); + } + function node_api_create_syntax_error(env, code, msg, result) { + if (!env) + return 1; + var envObject = emnapiCtx.envStore.get(env); + envObject.checkGCAccess(); + if (!msg) + return envObject.setLastError(1); + if (!result) + return envObject.setLastError(1); + var msgValue = emnapiCtx.handleStore.get(msg).value; + if (typeof msgValue !== 'string') { + return envObject.setLastError(3); + } + var error = new SyntaxError(msgValue); + if (code) { + var codeValue = emnapiCtx.handleStore.get(code).value; + if (typeof codeValue !== 'string') { + return envObject.setLastError(3); + } + error.code = codeValue; + } + result >>>= 0; + var value = emnapiCtx.addToCurrentScope(error).id; + var HEAP_DATA_VIEW = new DataView(wasmMemory.buffer), GET_HEAP_DATA_VIEW = function () { return HEAP_DATA_VIEW.buffer === wasmMemory.buffer ? HEAP_DATA_VIEW : (HEAP_DATA_VIEW = new DataView(wasmMemory.buffer)); }; + GET_HEAP_DATA_VIEW().setUint32(result, value, true); + return envObject.clearLastError(); + } + function napi_get_and_clear_last_exception(env, result) { + if (!env) + return 1; + var envObject = emnapiCtx.envStore.get(env); + envObject.checkGCAccess(); + if (!result) + return envObject.setLastError(1); + result >>>= 0; + var HEAP_DATA_VIEW = new DataView(wasmMemory.buffer), GET_HEAP_DATA_VIEW = function () { return HEAP_DATA_VIEW.buffer === wasmMemory.buffer ? HEAP_DATA_VIEW : (HEAP_DATA_VIEW = new DataView(wasmMemory.buffer)); }; + if (!envObject.tryCatch.hasCaught()) { + GET_HEAP_DATA_VIEW().setUint32(result, 1, true); + return envObject.clearLastError(); + } + else { + var err = envObject.tryCatch.exception(); + var value = envObject.ensureHandleId(err); + GET_HEAP_DATA_VIEW().setUint32(result, value, true); + envObject.tryCatch.reset(); + } + return envObject.clearLastError(); + } + function napi_fatal_error(location, location_len, message, message_len) { + location >>>= 0; + location_len >>>= 0; + message >>>= 0; + message_len >>>= 0; + var locationStr = emnapiString.UTF8ToString(location, location_len); + var messageStr = emnapiString.UTF8ToString(message, message_len); + if (emnapiNodeBinding) { + emnapiNodeBinding.napi.fatalError(locationStr, messageStr); + } + else { + abort('FATAL ERROR: ' + locationStr + ' ' + messageStr); + } + } + function napi_fatal_exception(env, err) { + if (!env) + return 1; + var envObject = emnapiCtx.envStore.get(env); + envObject.checkGCAccess(); + if (!envObject.tryCatch.isEmpty()) + return envObject.setLastError(10); + if (!envObject.canCallIntoJs()) + return envObject.setLastError(envObject.moduleApiVersion >= 10 ? 23 : 10); + envObject.clearLastError(); + try { + if (!err) + return envObject.setLastError(1); + var error = envObject.ctx.handleStore.get(err); + try { + envObject.triggerFatalException(error.value); + } + catch (_) { + return envObject.setLastError(9); + } + return envObject.clearLastError(); + } + catch (err) { + envObject.tryCatch.setError(err); + return envObject.setLastError(10); + } + } + var errorMod = Object.freeze({ + __proto__: null, + _emnapi_get_last_error_info: _emnapi_get_last_error_info, + napi_create_error: napi_create_error, + napi_create_range_error: napi_create_range_error, + napi_create_type_error: napi_create_type_error, + napi_fatal_error: napi_fatal_error, + napi_fatal_exception: napi_fatal_exception, + napi_get_and_clear_last_exception: napi_get_and_clear_last_exception, + napi_is_exception_pending: napi_is_exception_pending, + napi_throw: napi_throw, + napi_throw_error: napi_throw_error, + napi_throw_range_error: napi_throw_range_error, + napi_throw_type_error: napi_throw_type_error, + node_api_create_syntax_error: node_api_create_syntax_error, + node_api_throw_syntax_error: node_api_throw_syntax_error + }); + function _emnapi_create_function(env, utf8name, length, cb, data, result) { + length >>>= 0; + var envObject = emnapiCtx.envStore.get(env); + var fresult = emnapiCreateFunction(envObject, utf8name, length, cb, data); + if (fresult.status !== 0) + return envObject.setLastError(fresult.status); + var f = fresult.f; + var valueHandle = emnapiCtx.addToCurrentScope(f); + result >>>= 0; + var value = valueHandle.id; + var HEAP_DATA_VIEW = new DataView(wasmMemory.buffer), GET_HEAP_DATA_VIEW = function () { return HEAP_DATA_VIEW.buffer === wasmMemory.buffer ? HEAP_DATA_VIEW : (HEAP_DATA_VIEW = new DataView(wasmMemory.buffer)); }; + GET_HEAP_DATA_VIEW().setUint32(result, value, true); + return envObject.getReturnStatus(); + } + function napi_create_function(env, utf8name, length, cb, data, result) { + if (!env) + return 1; + var envObject = emnapiCtx.envStore.get(env); + envObject.checkGCAccess(); + if (!envObject.tryCatch.isEmpty()) + return envObject.setLastError(10); + if (!envObject.canCallIntoJs()) + return envObject.setLastError(envObject.moduleApiVersion >= 10 ? 23 : 10); + envObject.clearLastError(); + try { + if (!result) + return envObject.setLastError(1); + if (!cb) + return envObject.setLastError(1); + return _emnapi_create_function(env, utf8name, length, cb, data, result); + } + catch (err) { + envObject.tryCatch.setError(err); + return envObject.setLastError(10); + } + } + function napi_get_cb_info(env, cbinfo, argc, argv, this_arg, data) { + if (!env) + return 1; + var envObject = emnapiCtx.envStore.get(env); + if (!cbinfo) + return envObject.setLastError(1); + var cbinfoValue = emnapiCtx.scopeStore.get(cbinfo).callbackInfo; + argc >>>= 0; + argv >>>= 0; + var HEAP_DATA_VIEW = new DataView(wasmMemory.buffer), GET_HEAP_DATA_VIEW = function () { return HEAP_DATA_VIEW.buffer === wasmMemory.buffer ? HEAP_DATA_VIEW : (HEAP_DATA_VIEW = new DataView(wasmMemory.buffer)); }; + if (argv) { + if (!argc) + return envObject.setLastError(1); + var argcValue = GET_HEAP_DATA_VIEW().getUint32(argc, true); + argcValue >>>= 0; + var len = cbinfoValue.args.length; + var arrlen = argcValue < len ? argcValue : len; + var i = 0; + for (; i < arrlen; i++) { + var argVal = envObject.ensureHandleId(cbinfoValue.args[i]); + GET_HEAP_DATA_VIEW().setUint32(argv + i * 4, argVal, true); + } + if (i < argcValue) { + for (; i < argcValue; i++) { + GET_HEAP_DATA_VIEW().setUint32(argv + i * 4, 1, true); + } + } + } + if (argc) { + GET_HEAP_DATA_VIEW().setUint32(argc, cbinfoValue.args.length, true); + } + if (this_arg) { + this_arg >>>= 0; + var v = envObject.ensureHandleId(cbinfoValue.thiz); + GET_HEAP_DATA_VIEW().setUint32(this_arg, v, true); + } + if (data) { + data >>>= 0; + GET_HEAP_DATA_VIEW().setUint32(data, cbinfoValue.data, true); + } + return envObject.clearLastError(); + } + function napi_call_function(env, recv, func, argc, argv, result) { + var i = 0; + var v; + if (!env) + return 1; + var envObject = emnapiCtx.envStore.get(env); + envObject.checkGCAccess(); + if (!envObject.tryCatch.isEmpty()) + return envObject.setLastError(10); + if (!envObject.canCallIntoJs()) + return envObject.setLastError(envObject.moduleApiVersion >= 10 ? 23 : 10); + envObject.clearLastError(); + try { + if (!recv) + return envObject.setLastError(1); + argc >>>= 0; + argv >>>= 0; + result >>>= 0; + argc = argc >>> 0; + if (argc > 0) { + if (!argv) + return envObject.setLastError(1); + } + var v8recv = emnapiCtx.handleStore.get(recv).value; + if (!func) + return envObject.setLastError(1); + var v8func = emnapiCtx.handleStore.get(func).value; + if (typeof v8func !== 'function') + return envObject.setLastError(1); + var args = []; + var HEAP_DATA_VIEW = new DataView(wasmMemory.buffer), GET_HEAP_DATA_VIEW = function () { return HEAP_DATA_VIEW.buffer === wasmMemory.buffer ? HEAP_DATA_VIEW : (HEAP_DATA_VIEW = new DataView(wasmMemory.buffer)); }; + for (; i < argc; i++) { + var argVal = GET_HEAP_DATA_VIEW().getUint32(argv + i * 4, true); + args.push(emnapiCtx.handleStore.get(argVal).value); + } + var ret = v8func.apply(v8recv, args); + if (result) { + v = envObject.ensureHandleId(ret); + GET_HEAP_DATA_VIEW().setUint32(result, v, true); + } + return envObject.clearLastError(); + } + catch (err) { + envObject.tryCatch.setError(err); + return envObject.setLastError(10); + } + } + function napi_new_instance(env, constructor, argc, argv, result) { + var i; + var v; + if (!env) + return 1; + var envObject = emnapiCtx.envStore.get(env); + envObject.checkGCAccess(); + if (!envObject.tryCatch.isEmpty()) + return envObject.setLastError(10); + if (!envObject.canCallIntoJs()) + return envObject.setLastError(envObject.moduleApiVersion >= 10 ? 23 : 10); + envObject.clearLastError(); + try { + if (!constructor) + return envObject.setLastError(1); + argc >>>= 0; + argv >>>= 0; + result >>>= 0; + argc = argc >>> 0; + if (argc > 0) { + if (!argv) + return envObject.setLastError(1); + } + if (!result) + return envObject.setLastError(1); + var Ctor = emnapiCtx.handleStore.get(constructor).value; + if (typeof Ctor !== 'function') + return envObject.setLastError(1); + var ret = void 0; + var HEAP_DATA_VIEW = new DataView(wasmMemory.buffer), GET_HEAP_DATA_VIEW = function () { return HEAP_DATA_VIEW.buffer === wasmMemory.buffer ? HEAP_DATA_VIEW : (HEAP_DATA_VIEW = new DataView(wasmMemory.buffer)); }; + if (emnapiCtx.feature.supportReflect) { + var argList = Array(argc); + for (i = 0; i < argc; i++) { + var argVal = GET_HEAP_DATA_VIEW().getUint32(argv + i * 4, true); + argList[i] = emnapiCtx.handleStore.get(argVal).value; + } + ret = Reflect.construct(Ctor, argList, Ctor); + } + else { + var args = Array(argc + 1); + args[0] = undefined; + for (i = 0; i < argc; i++) { + var argVal = GET_HEAP_DATA_VIEW().getUint32(argv + i * 4, true); + args[i + 1] = emnapiCtx.handleStore.get(argVal).value; + } + var BoundCtor = Ctor.bind.apply(Ctor, args); + ret = new BoundCtor(); + } + if (result) { + v = envObject.ensureHandleId(ret); + GET_HEAP_DATA_VIEW().setUint32(result, v, true); + } + return envObject.getReturnStatus(); + } + catch (err) { + envObject.tryCatch.setError(err); + return envObject.setLastError(10); + } + } + function napi_get_new_target(env, cbinfo, result) { + if (!env) + return 1; + var envObject = emnapiCtx.envStore.get(env); + envObject.checkGCAccess(); + if (!cbinfo) + return envObject.setLastError(1); + if (!result) + return envObject.setLastError(1); + result >>>= 0; + var cbinfoValue = emnapiCtx.scopeStore.get(cbinfo).callbackInfo; + var thiz = cbinfoValue.thiz, fn = cbinfoValue.fn; + var value = thiz == null || thiz.constructor == null + ? 0 + : thiz instanceof fn + ? envObject.ensureHandleId(thiz.constructor) + : 0; + var HEAP_DATA_VIEW = new DataView(wasmMemory.buffer), GET_HEAP_DATA_VIEW = function () { return HEAP_DATA_VIEW.buffer === wasmMemory.buffer ? HEAP_DATA_VIEW : (HEAP_DATA_VIEW = new DataView(wasmMemory.buffer)); }; + GET_HEAP_DATA_VIEW().setUint32(result, value, true); + return envObject.clearLastError(); + } + var functionMod = Object.freeze({ + __proto__: null, + _emnapi_create_function: _emnapi_create_function, + napi_call_function: napi_call_function, + napi_create_function: napi_create_function, + napi_get_cb_info: napi_get_cb_info, + napi_get_new_target: napi_get_new_target, + napi_new_instance: napi_new_instance + }); + function napi_open_handle_scope(env, result) { + if (!env) + return 1; + var envObject = emnapiCtx.envStore.get(env); + envObject.checkGCAccess(); + if (!result) + return envObject.setLastError(1); + var scope = emnapiCtx.openScope(envObject); + result >>>= 0; + var HEAP_DATA_VIEW = new DataView(wasmMemory.buffer), GET_HEAP_DATA_VIEW = function () { return HEAP_DATA_VIEW.buffer === wasmMemory.buffer ? HEAP_DATA_VIEW : (HEAP_DATA_VIEW = new DataView(wasmMemory.buffer)); }; + GET_HEAP_DATA_VIEW().setUint32(result, scope.id, true); + return envObject.clearLastError(); + } + function napi_close_handle_scope(env, scope) { + if (!env) + return 1; + var envObject = emnapiCtx.envStore.get(env); + envObject.checkGCAccess(); + if (!scope) + return envObject.setLastError(1); + if ((envObject.openHandleScopes === 0)) { + return 13; + } + emnapiCtx.closeScope(envObject); + return envObject.clearLastError(); + } + function napi_open_escapable_handle_scope(env, result) { + if (!env) + return 1; + var envObject = emnapiCtx.envStore.get(env); + envObject.checkGCAccess(); + if (!result) + return envObject.setLastError(1); + var scope = emnapiCtx.openScope(envObject); + result >>>= 0; + var HEAP_DATA_VIEW = new DataView(wasmMemory.buffer), GET_HEAP_DATA_VIEW = function () { return HEAP_DATA_VIEW.buffer === wasmMemory.buffer ? HEAP_DATA_VIEW : (HEAP_DATA_VIEW = new DataView(wasmMemory.buffer)); }; + GET_HEAP_DATA_VIEW().setUint32(result, scope.id, true); + return envObject.clearLastError(); + } + function napi_close_escapable_handle_scope(env, scope) { + if (!env) + return 1; + var envObject = emnapiCtx.envStore.get(env); + envObject.checkGCAccess(); + if (!scope) + return envObject.setLastError(1); + if ((envObject.openHandleScopes === 0)) { + return 13; + } + emnapiCtx.closeScope(envObject); + return envObject.clearLastError(); + } + function napi_escape_handle(env, scope, escapee, result) { + if (!env) + return 1; + var envObject = emnapiCtx.envStore.get(env); + envObject.checkGCAccess(); + if (!scope) + return envObject.setLastError(1); + if (!escapee) + return envObject.setLastError(1); + if (!result) + return envObject.setLastError(1); + var scopeObject = emnapiCtx.scopeStore.get(scope); + if (!scopeObject.escapeCalled()) { + escapee >>>= 0; + result >>>= 0; + var newHandle = scopeObject.escape(escapee); + var value = newHandle ? newHandle.id : 0; + var HEAP_DATA_VIEW = new DataView(wasmMemory.buffer), GET_HEAP_DATA_VIEW = function () { return HEAP_DATA_VIEW.buffer === wasmMemory.buffer ? HEAP_DATA_VIEW : (HEAP_DATA_VIEW = new DataView(wasmMemory.buffer)); }; + GET_HEAP_DATA_VIEW().setUint32(result, value, true); + return envObject.clearLastError(); + } + return envObject.setLastError(12); + } + function napi_create_reference(env, value, initial_refcount, result) { + if (!env) + return 1; + var envObject = emnapiCtx.envStore.get(env); + envObject.checkGCAccess(); + if (!value) + return envObject.setLastError(1); + if (!result) + return envObject.setLastError(1); + var handle = emnapiCtx.handleStore.get(value); + if (envObject.moduleApiVersion < 10) { + if (!(handle.isObject() || handle.isFunction() || handle.isSymbol())) { + return envObject.setLastError(1); + } + } + var ref = emnapiCtx.createReference(envObject, handle.id, initial_refcount >>> 0, 1); + result >>>= 0; + var HEAP_DATA_VIEW = new DataView(wasmMemory.buffer), GET_HEAP_DATA_VIEW = function () { return HEAP_DATA_VIEW.buffer === wasmMemory.buffer ? HEAP_DATA_VIEW : (HEAP_DATA_VIEW = new DataView(wasmMemory.buffer)); }; + GET_HEAP_DATA_VIEW().setUint32(result, ref.id, true); + return envObject.clearLastError(); + } + function napi_delete_reference(env, ref) { + if (!env) + return 1; + var envObject = emnapiCtx.envStore.get(env); + if (!ref) + return envObject.setLastError(1); + emnapiCtx.refStore.get(ref).dispose(); + return envObject.clearLastError(); + } + function napi_reference_ref(env, ref, result) { + if (!env) + return 1; + var envObject = emnapiCtx.envStore.get(env); + envObject.checkGCAccess(); + if (!ref) + return envObject.setLastError(1); + var count = emnapiCtx.refStore.get(ref).ref(); + if (result) { + result >>>= 0; + var HEAP_DATA_VIEW = new DataView(wasmMemory.buffer), GET_HEAP_DATA_VIEW = function () { return HEAP_DATA_VIEW.buffer === wasmMemory.buffer ? HEAP_DATA_VIEW : (HEAP_DATA_VIEW = new DataView(wasmMemory.buffer)); }; + GET_HEAP_DATA_VIEW().setUint32(result, count, true); + } + return envObject.clearLastError(); + } + function napi_reference_unref(env, ref, result) { + if (!env) + return 1; + var envObject = emnapiCtx.envStore.get(env); + envObject.checkGCAccess(); + if (!ref) + return envObject.setLastError(1); + var reference = emnapiCtx.refStore.get(ref); + var refcount = reference.refcount(); + if (refcount === 0) { + return envObject.setLastError(9); + } + var count = reference.unref(); + if (result) { + result >>>= 0; + var HEAP_DATA_VIEW = new DataView(wasmMemory.buffer), GET_HEAP_DATA_VIEW = function () { return HEAP_DATA_VIEW.buffer === wasmMemory.buffer ? HEAP_DATA_VIEW : (HEAP_DATA_VIEW = new DataView(wasmMemory.buffer)); }; + GET_HEAP_DATA_VIEW().setUint32(result, count, true); + } + return envObject.clearLastError(); + } + function napi_get_reference_value(env, ref, result) { + if (!env) + return 1; + var envObject = emnapiCtx.envStore.get(env); + envObject.checkGCAccess(); + if (!ref) + return envObject.setLastError(1); + if (!result) + return envObject.setLastError(1); + var reference = emnapiCtx.refStore.get(ref); + var handleId = reference.get(envObject); + result >>>= 0; + var HEAP_DATA_VIEW = new DataView(wasmMemory.buffer), GET_HEAP_DATA_VIEW = function () { return HEAP_DATA_VIEW.buffer === wasmMemory.buffer ? HEAP_DATA_VIEW : (HEAP_DATA_VIEW = new DataView(wasmMemory.buffer)); }; + GET_HEAP_DATA_VIEW().setUint32(result, handleId, true); + return envObject.clearLastError(); + } + function napi_add_env_cleanup_hook(env, fun, arg) { + if (!env) + return 1; + var envObject = emnapiCtx.envStore.get(env); + if (!fun) + return envObject.setLastError(1); + fun >>>= 0; + arg >>>= 0; + emnapiCtx.addCleanupHook(envObject, fun, arg); + return 0; + } + function napi_remove_env_cleanup_hook(env, fun, arg) { + if (!env) + return 1; + var envObject = emnapiCtx.envStore.get(env); + if (!fun) + return envObject.setLastError(1); + fun >>>= 0; + arg >>>= 0; + emnapiCtx.removeCleanupHook(envObject, fun, arg); + return 0; + } + function _emnapi_env_ref(env) { + var envObject = emnapiCtx.envStore.get(env); + envObject.ref(); + } + function _emnapi_env_unref(env) { + var envObject = emnapiCtx.envStore.get(env); + envObject.unref(); + } + var lifeMod = Object.freeze({ + __proto__: null, + _emnapi_env_ref: _emnapi_env_ref, + _emnapi_env_unref: _emnapi_env_unref, + napi_add_env_cleanup_hook: napi_add_env_cleanup_hook, + napi_close_escapable_handle_scope: napi_close_escapable_handle_scope, + napi_close_handle_scope: napi_close_handle_scope, + napi_create_reference: napi_create_reference, + napi_delete_reference: napi_delete_reference, + napi_escape_handle: napi_escape_handle, + napi_get_reference_value: napi_get_reference_value, + napi_open_escapable_handle_scope: napi_open_escapable_handle_scope, + napi_open_handle_scope: napi_open_handle_scope, + napi_reference_ref: napi_reference_ref, + napi_reference_unref: napi_reference_unref, + napi_remove_env_cleanup_hook: napi_remove_env_cleanup_hook + }); + function _emnapi_get_filename(env, buf, len) { + var envObject = emnapiCtx.envStore.get(env); + var filename = envObject.filename; + if (!buf) { + return emnapiString.lengthBytesUTF8(filename); + } + return emnapiString.stringToUTF8(filename, buf, len); + } + var miscellaneousMod = Object.freeze({ + __proto__: null, + _emnapi_get_filename: _emnapi_get_filename + }); + function napi_create_promise(env, deferred, promise) { + var deferredObjectId, value; + if (!env) + return 1; + var envObject = emnapiCtx.envStore.get(env); + envObject.checkGCAccess(); + if (!envObject.tryCatch.isEmpty()) + return envObject.setLastError(10); + if (!envObject.canCallIntoJs()) + return envObject.setLastError(envObject.moduleApiVersion >= 10 ? 23 : 10); + envObject.clearLastError(); + try { + if (!deferred) + return envObject.setLastError(1); + if (!promise) + return envObject.setLastError(1); + var HEAP_DATA_VIEW = new DataView(wasmMemory.buffer), GET_HEAP_DATA_VIEW = function () { return HEAP_DATA_VIEW.buffer === wasmMemory.buffer ? HEAP_DATA_VIEW : (HEAP_DATA_VIEW = new DataView(wasmMemory.buffer)); }; + var p = new Promise(function (resolve, reject) { + var deferredObject = emnapiCtx.createDeferred({ resolve: resolve, reject: reject }); + deferredObjectId = deferredObject.id; + deferred >>>= 0; + GET_HEAP_DATA_VIEW().setUint32(deferred, deferredObjectId, true); + }); + promise >>>= 0; + value = emnapiCtx.addToCurrentScope(p).id; + GET_HEAP_DATA_VIEW().setUint32(promise, value, true); + return envObject.getReturnStatus(); + } + catch (err) { + envObject.tryCatch.setError(err); + return envObject.setLastError(10); + } + } + function napi_resolve_deferred(env, deferred, resolution) { + if (!env) + return 1; + var envObject = emnapiCtx.envStore.get(env); + envObject.checkGCAccess(); + if (!envObject.tryCatch.isEmpty()) + return envObject.setLastError(10); + if (!envObject.canCallIntoJs()) + return envObject.setLastError(envObject.moduleApiVersion >= 10 ? 23 : 10); + envObject.clearLastError(); + try { + if (!deferred) + return envObject.setLastError(1); + if (!resolution) + return envObject.setLastError(1); + var deferredObject = emnapiCtx.deferredStore.get(deferred); + deferredObject.resolve(emnapiCtx.handleStore.get(resolution).value); + return envObject.getReturnStatus(); + } + catch (err) { + envObject.tryCatch.setError(err); + return envObject.setLastError(10); + } + } + function napi_reject_deferred(env, deferred, resolution) { + if (!env) + return 1; + var envObject = emnapiCtx.envStore.get(env); + envObject.checkGCAccess(); + if (!envObject.tryCatch.isEmpty()) + return envObject.setLastError(10); + if (!envObject.canCallIntoJs()) + return envObject.setLastError(envObject.moduleApiVersion >= 10 ? 23 : 10); + envObject.clearLastError(); + try { + if (!deferred) + return envObject.setLastError(1); + if (!resolution) + return envObject.setLastError(1); + var deferredObject = emnapiCtx.deferredStore.get(deferred); + deferredObject.reject(emnapiCtx.handleStore.get(resolution).value); + return envObject.getReturnStatus(); + } + catch (err) { + envObject.tryCatch.setError(err); + return envObject.setLastError(10); + } + } + function napi_is_promise(env, value, is_promise) { + if (!env) + return 1; + var envObject = emnapiCtx.envStore.get(env); + envObject.checkGCAccess(); + if (!value) + return envObject.setLastError(1); + if (!is_promise) + return envObject.setLastError(1); + var h = emnapiCtx.handleStore.get(value); + is_promise >>>= 0; + var r = h.isPromise() ? 1 : 0; + var HEAP_DATA_VIEW = new DataView(wasmMemory.buffer), GET_HEAP_DATA_VIEW = function () { return HEAP_DATA_VIEW.buffer === wasmMemory.buffer ? HEAP_DATA_VIEW : (HEAP_DATA_VIEW = new DataView(wasmMemory.buffer)); }; + GET_HEAP_DATA_VIEW().setInt8(is_promise, r, true); + return envObject.clearLastError(); + } + var promiseMod = Object.freeze({ + __proto__: null, + napi_create_promise: napi_create_promise, + napi_is_promise: napi_is_promise, + napi_reject_deferred: napi_reject_deferred, + napi_resolve_deferred: napi_resolve_deferred + }); + function napi_get_all_property_names(env, object, key_mode, key_filter, key_conversion, result) { + var value; + if (!env) + return 1; + var envObject = emnapiCtx.envStore.get(env); + envObject.checkGCAccess(); + if (!envObject.tryCatch.isEmpty()) + return envObject.setLastError(10); + if (!envObject.canCallIntoJs()) + return envObject.setLastError(envObject.moduleApiVersion >= 10 ? 23 : 10); + envObject.clearLastError(); + try { + if (!result) + return envObject.setLastError(1); + if (!object) + return envObject.setLastError(1); + var h = emnapiCtx.handleStore.get(object); + if (h.value == null) { + throw new TypeError('Cannot convert undefined or null to object'); + } + var obj = void 0; + try { + obj = h.isObject() || h.isFunction() ? h.value : Object(h.value); + } + catch (_) { + return envObject.setLastError(2); + } + if (key_mode !== 0 && key_mode !== 1) { + return envObject.setLastError(1); + } + if (key_conversion !== 0 && key_conversion !== 1) { + return envObject.setLastError(1); + } + var props = []; + var names = void 0; + var symbols = void 0; + var i = void 0; + var own = true; + var integerIndiceRegex = /^(0|[1-9][0-9]*)$/; + do { + names = Object.getOwnPropertyNames(obj); + symbols = Object.getOwnPropertySymbols(obj); + for (i = 0; i < names.length; i++) { + props.push({ + name: integerIndiceRegex.test(names[i]) ? Number(names[i]) : names[i], + desc: Object.getOwnPropertyDescriptor(obj, names[i]), + own: own + }); + } + for (i = 0; i < symbols.length; i++) { + props.push({ + name: symbols[i], + desc: Object.getOwnPropertyDescriptor(obj, symbols[i]), + own: own + }); + } + if (key_mode === 1) { + break; + } + obj = Object.getPrototypeOf(obj); + own = false; + } while (obj); + var ret = []; + var addName = function (ret, name, key_filter, conversion_mode) { + if (ret.indexOf(name) !== -1) + return; + if (conversion_mode === 0) { + ret.push(name); + } + else if (conversion_mode === 1) { + var realName = typeof name === 'number' ? String(name) : name; + if (typeof realName === 'string') { + if (!(key_filter & 8)) { + ret.push(realName); + } + } + else { + ret.push(realName); + } + } + }; + for (i = 0; i < props.length; i++) { + var prop = props[i]; + var name_1 = prop.name; + var desc = prop.desc; + if (key_filter === 0) { + addName(ret, name_1, key_filter, key_conversion); + } + else { + if (key_filter & 8 && typeof name_1 === 'string') { + continue; + } + if (key_filter & 16 && typeof name_1 === 'symbol') { + continue; + } + var shouldAdd = true; + switch (key_filter & 7) { + case 1: { + shouldAdd = Boolean(desc.writable); + break; + } + case 2: { + shouldAdd = Boolean(desc.enumerable); + break; + } + case (1 | 2): { + shouldAdd = Boolean(desc.writable && desc.enumerable); + break; + } + case 4: { + shouldAdd = Boolean(desc.configurable); + break; + } + case (4 | 1): { + shouldAdd = Boolean(desc.configurable && desc.writable); + break; + } + case (4 | 2): { + shouldAdd = Boolean(desc.configurable && desc.enumerable); + break; + } + case (4 | 2 | 1): { + shouldAdd = Boolean(desc.configurable && desc.enumerable && desc.writable); + break; + } + } + if (shouldAdd) { + addName(ret, name_1, key_filter, key_conversion); + } + } + } + result >>>= 0; + value = emnapiCtx.addToCurrentScope(ret).id; + var HEAP_DATA_VIEW = new DataView(wasmMemory.buffer), GET_HEAP_DATA_VIEW = function () { return HEAP_DATA_VIEW.buffer === wasmMemory.buffer ? HEAP_DATA_VIEW : (HEAP_DATA_VIEW = new DataView(wasmMemory.buffer)); }; + GET_HEAP_DATA_VIEW().setUint32(result, value, true); + return envObject.getReturnStatus(); + } + catch (err) { + envObject.tryCatch.setError(err); + return envObject.setLastError(10); + } + } + function napi_get_property_names(env, object, result) { + return napi_get_all_property_names(env, object, 0, 2 | 16, 1, result); + } + function napi_set_property(env, object, key, value) { + if (!env) + return 1; + var envObject = emnapiCtx.envStore.get(env); + envObject.checkGCAccess(); + if (!envObject.tryCatch.isEmpty()) + return envObject.setLastError(10); + if (!envObject.canCallIntoJs()) + return envObject.setLastError(envObject.moduleApiVersion >= 10 ? 23 : 10); + envObject.clearLastError(); + try { + if (!key) + return envObject.setLastError(1); + if (!value) + return envObject.setLastError(1); + if (!object) + return envObject.setLastError(1); + var h = emnapiCtx.handleStore.get(object); + if (!(h.isObject() || h.isFunction())) { + return envObject.setLastError(2); + } + h.value[emnapiCtx.handleStore.get(key).value] = emnapiCtx.handleStore.get(value).value; + return envObject.getReturnStatus(); + } + catch (err) { + envObject.tryCatch.setError(err); + return envObject.setLastError(10); + } + } + function napi_has_property(env, object, key, result) { + var r; + if (!env) + return 1; + var envObject = emnapiCtx.envStore.get(env); + envObject.checkGCAccess(); + if (!envObject.tryCatch.isEmpty()) + return envObject.setLastError(10); + if (!envObject.canCallIntoJs()) + return envObject.setLastError(envObject.moduleApiVersion >= 10 ? 23 : 10); + envObject.clearLastError(); + try { + if (!key) + return envObject.setLastError(1); + if (!result) + return envObject.setLastError(1); + if (!object) + return envObject.setLastError(1); + var h = emnapiCtx.handleStore.get(object); + if (h.value == null) { + throw new TypeError('Cannot convert undefined or null to object'); + } + var v = void 0; + try { + v = h.isObject() || h.isFunction() ? h.value : Object(h.value); + } + catch (_) { + return envObject.setLastError(2); + } + result >>>= 0; + r = (emnapiCtx.handleStore.get(key).value in v) ? 1 : 0; + var HEAP_DATA_VIEW = new DataView(wasmMemory.buffer), GET_HEAP_DATA_VIEW = function () { return HEAP_DATA_VIEW.buffer === wasmMemory.buffer ? HEAP_DATA_VIEW : (HEAP_DATA_VIEW = new DataView(wasmMemory.buffer)); }; + GET_HEAP_DATA_VIEW().setInt8(result, r, true); + return envObject.getReturnStatus(); + } + catch (err) { + envObject.tryCatch.setError(err); + return envObject.setLastError(10); + } + } + function napi_get_property(env, object, key, result) { + var value; + if (!env) + return 1; + var envObject = emnapiCtx.envStore.get(env); + envObject.checkGCAccess(); + if (!envObject.tryCatch.isEmpty()) + return envObject.setLastError(10); + if (!envObject.canCallIntoJs()) + return envObject.setLastError(envObject.moduleApiVersion >= 10 ? 23 : 10); + envObject.clearLastError(); + try { + if (!key) + return envObject.setLastError(1); + if (!result) + return envObject.setLastError(1); + if (!object) + return envObject.setLastError(1); + var h = emnapiCtx.handleStore.get(object); + if (h.value == null) { + throw new TypeError('Cannot convert undefined or null to object'); + } + var v = void 0; + try { + v = h.isObject() || h.isFunction() ? h.value : Object(h.value); + } + catch (_) { + return envObject.setLastError(2); + } + result >>>= 0; + value = envObject.ensureHandleId(v[emnapiCtx.handleStore.get(key).value]); + var HEAP_DATA_VIEW = new DataView(wasmMemory.buffer), GET_HEAP_DATA_VIEW = function () { return HEAP_DATA_VIEW.buffer === wasmMemory.buffer ? HEAP_DATA_VIEW : (HEAP_DATA_VIEW = new DataView(wasmMemory.buffer)); }; + GET_HEAP_DATA_VIEW().setUint32(result, value, true); + return envObject.getReturnStatus(); + } + catch (err) { + envObject.tryCatch.setError(err); + return envObject.setLastError(10); + } + } + function napi_delete_property(env, object, key, result) { + var r; + if (!env) + return 1; + var envObject = emnapiCtx.envStore.get(env); + envObject.checkGCAccess(); + if (!envObject.tryCatch.isEmpty()) + return envObject.setLastError(10); + if (!envObject.canCallIntoJs()) + return envObject.setLastError(envObject.moduleApiVersion >= 10 ? 23 : 10); + envObject.clearLastError(); + try { + if (!key) + return envObject.setLastError(1); + if (!object) + return envObject.setLastError(1); + var h = emnapiCtx.handleStore.get(object); + if (!(h.isObject() || h.isFunction())) { + return envObject.setLastError(2); + } + var propertyKey = emnapiCtx.handleStore.get(key).value; + if (emnapiCtx.feature.supportReflect) { + r = Reflect.deleteProperty(h.value, propertyKey); + } + else { + try { + r = delete h.value[propertyKey]; + } + catch (_) { + r = false; + } + } + if (result) { + result >>>= 0; + var HEAP_DATA_VIEW = new DataView(wasmMemory.buffer), GET_HEAP_DATA_VIEW = function () { return HEAP_DATA_VIEW.buffer === wasmMemory.buffer ? HEAP_DATA_VIEW : (HEAP_DATA_VIEW = new DataView(wasmMemory.buffer)); }; + GET_HEAP_DATA_VIEW().setInt8(result, r ? 1 : 0, true); + } + return envObject.getReturnStatus(); + } + catch (err) { + envObject.tryCatch.setError(err); + return envObject.setLastError(10); + } + } + function napi_has_own_property(env, object, key, result) { + var r; + if (!env) + return 1; + var envObject = emnapiCtx.envStore.get(env); + envObject.checkGCAccess(); + if (!envObject.tryCatch.isEmpty()) + return envObject.setLastError(10); + if (!envObject.canCallIntoJs()) + return envObject.setLastError(envObject.moduleApiVersion >= 10 ? 23 : 10); + envObject.clearLastError(); + try { + if (!key) + return envObject.setLastError(1); + if (!result) + return envObject.setLastError(1); + if (!object) + return envObject.setLastError(1); + var h = emnapiCtx.handleStore.get(object); + if (h.value == null) { + throw new TypeError('Cannot convert undefined or null to object'); + } + var v = void 0; + try { + v = h.isObject() || h.isFunction() ? h.value : Object(h.value); + } + catch (_) { + return envObject.setLastError(2); + } + var prop = emnapiCtx.handleStore.get(key).value; + if (typeof prop !== 'string' && typeof prop !== 'symbol') { + return envObject.setLastError(4); + } + r = Object.prototype.hasOwnProperty.call(v, emnapiCtx.handleStore.get(key).value); + result >>>= 0; + var HEAP_DATA_VIEW = new DataView(wasmMemory.buffer), GET_HEAP_DATA_VIEW = function () { return HEAP_DATA_VIEW.buffer === wasmMemory.buffer ? HEAP_DATA_VIEW : (HEAP_DATA_VIEW = new DataView(wasmMemory.buffer)); }; + GET_HEAP_DATA_VIEW().setInt8(result, r ? 1 : 0, true); + return envObject.getReturnStatus(); + } + catch (err) { + envObject.tryCatch.setError(err); + return envObject.setLastError(10); + } + } + function napi_set_named_property(env, object, cname, value) { + if (!env) + return 1; + var envObject = emnapiCtx.envStore.get(env); + envObject.checkGCAccess(); + if (!envObject.tryCatch.isEmpty()) + return envObject.setLastError(10); + if (!envObject.canCallIntoJs()) + return envObject.setLastError(envObject.moduleApiVersion >= 10 ? 23 : 10); + envObject.clearLastError(); + try { + if (!value) + return envObject.setLastError(1); + if (!object) + return envObject.setLastError(1); + var h = emnapiCtx.handleStore.get(object); + if (!(h.isObject() || h.isFunction())) { + return envObject.setLastError(2); + } + if (!cname) { + return envObject.setLastError(1); + } + cname >>>= 0; + emnapiCtx.handleStore.get(object).value[emnapiString.UTF8ToString(cname, -1)] = emnapiCtx.handleStore.get(value).value; + return envObject.getReturnStatus(); + } + catch (err) { + envObject.tryCatch.setError(err); + return envObject.setLastError(10); + } + } + function napi_has_named_property(env, object, utf8name, result) { + var r; + if (!env) + return 1; + var envObject = emnapiCtx.envStore.get(env); + envObject.checkGCAccess(); + if (!envObject.tryCatch.isEmpty()) + return envObject.setLastError(10); + if (!envObject.canCallIntoJs()) + return envObject.setLastError(envObject.moduleApiVersion >= 10 ? 23 : 10); + envObject.clearLastError(); + try { + if (!result) + return envObject.setLastError(1); + if (!object) + return envObject.setLastError(1); + if (!utf8name) { + return envObject.setLastError(1); + } + var h = emnapiCtx.handleStore.get(object); + if (h.value == null) { + throw new TypeError('Cannot convert undefined or null to object'); + } + var v = void 0; + try { + v = h.isObject() || h.isFunction() ? h.value : Object(h.value); + } + catch (_) { + return envObject.setLastError(2); + } + utf8name >>>= 0; + result >>>= 0; + r = emnapiString.UTF8ToString(utf8name, -1) in v; + var HEAP_DATA_VIEW = new DataView(wasmMemory.buffer), GET_HEAP_DATA_VIEW = function () { return HEAP_DATA_VIEW.buffer === wasmMemory.buffer ? HEAP_DATA_VIEW : (HEAP_DATA_VIEW = new DataView(wasmMemory.buffer)); }; + GET_HEAP_DATA_VIEW().setInt8(result, r ? 1 : 0, true); + return envObject.getReturnStatus(); + } + catch (err) { + envObject.tryCatch.setError(err); + return envObject.setLastError(10); + } + } + function napi_get_named_property(env, object, utf8name, result) { + var value; + if (!env) + return 1; + var envObject = emnapiCtx.envStore.get(env); + envObject.checkGCAccess(); + if (!envObject.tryCatch.isEmpty()) + return envObject.setLastError(10); + if (!envObject.canCallIntoJs()) + return envObject.setLastError(envObject.moduleApiVersion >= 10 ? 23 : 10); + envObject.clearLastError(); + try { + if (!result) + return envObject.setLastError(1); + if (!object) + return envObject.setLastError(1); + if (!utf8name) { + return envObject.setLastError(1); + } + var h = emnapiCtx.handleStore.get(object); + if (h.value == null) { + throw new TypeError('Cannot convert undefined or null to object'); + } + var v = void 0; + try { + v = h.isObject() || h.isFunction() ? h.value : Object(h.value); + } + catch (_) { + return envObject.setLastError(2); + } + utf8name >>>= 0; + result >>>= 0; + value = envObject.ensureHandleId(v[emnapiString.UTF8ToString(utf8name, -1)]); + var HEAP_DATA_VIEW = new DataView(wasmMemory.buffer), GET_HEAP_DATA_VIEW = function () { return HEAP_DATA_VIEW.buffer === wasmMemory.buffer ? HEAP_DATA_VIEW : (HEAP_DATA_VIEW = new DataView(wasmMemory.buffer)); }; + GET_HEAP_DATA_VIEW().setUint32(result, value, true); + return envObject.getReturnStatus(); + } + catch (err) { + envObject.tryCatch.setError(err); + return envObject.setLastError(10); + } + } + function napi_set_element(env, object, index, value) { + if (!env) + return 1; + var envObject = emnapiCtx.envStore.get(env); + envObject.checkGCAccess(); + if (!envObject.tryCatch.isEmpty()) + return envObject.setLastError(10); + if (!envObject.canCallIntoJs()) + return envObject.setLastError(envObject.moduleApiVersion >= 10 ? 23 : 10); + envObject.clearLastError(); + try { + if (!value) + return envObject.setLastError(1); + if (!object) + return envObject.setLastError(1); + var h = emnapiCtx.handleStore.get(object); + if (!(h.isObject() || h.isFunction())) { + return envObject.setLastError(2); + } + h.value[index >>> 0] = emnapiCtx.handleStore.get(value).value; + return envObject.getReturnStatus(); + } + catch (err) { + envObject.tryCatch.setError(err); + return envObject.setLastError(10); + } + } + function napi_has_element(env, object, index, result) { + var r; + if (!env) + return 1; + var envObject = emnapiCtx.envStore.get(env); + envObject.checkGCAccess(); + if (!envObject.tryCatch.isEmpty()) + return envObject.setLastError(10); + if (!envObject.canCallIntoJs()) + return envObject.setLastError(envObject.moduleApiVersion >= 10 ? 23 : 10); + envObject.clearLastError(); + try { + if (!result) + return envObject.setLastError(1); + if (!object) + return envObject.setLastError(1); + var h = emnapiCtx.handleStore.get(object); + if (h.value == null) { + throw new TypeError('Cannot convert undefined or null to object'); + } + var v = void 0; + try { + v = h.isObject() || h.isFunction() ? h.value : Object(h.value); + } + catch (_) { + return envObject.setLastError(2); + } + result >>>= 0; + r = ((index >>> 0) in v) ? 1 : 0; + var HEAP_DATA_VIEW = new DataView(wasmMemory.buffer), GET_HEAP_DATA_VIEW = function () { return HEAP_DATA_VIEW.buffer === wasmMemory.buffer ? HEAP_DATA_VIEW : (HEAP_DATA_VIEW = new DataView(wasmMemory.buffer)); }; + GET_HEAP_DATA_VIEW().setInt8(result, r, true); + return envObject.getReturnStatus(); + } + catch (err) { + envObject.tryCatch.setError(err); + return envObject.setLastError(10); + } + } + function napi_get_element(env, object, index, result) { + var value; + if (!env) + return 1; + var envObject = emnapiCtx.envStore.get(env); + envObject.checkGCAccess(); + if (!envObject.tryCatch.isEmpty()) + return envObject.setLastError(10); + if (!envObject.canCallIntoJs()) + return envObject.setLastError(envObject.moduleApiVersion >= 10 ? 23 : 10); + envObject.clearLastError(); + try { + if (!result) + return envObject.setLastError(1); + if (!object) + return envObject.setLastError(1); + var h = emnapiCtx.handleStore.get(object); + if (h.value == null) { + throw new TypeError('Cannot convert undefined or null to object'); + } + var v = void 0; + try { + v = h.isObject() || h.isFunction() ? h.value : Object(h.value); + } + catch (_) { + return envObject.setLastError(2); + } + result >>>= 0; + value = envObject.ensureHandleId(v[index >>> 0]); + var HEAP_DATA_VIEW = new DataView(wasmMemory.buffer), GET_HEAP_DATA_VIEW = function () { return HEAP_DATA_VIEW.buffer === wasmMemory.buffer ? HEAP_DATA_VIEW : (HEAP_DATA_VIEW = new DataView(wasmMemory.buffer)); }; + GET_HEAP_DATA_VIEW().setUint32(result, value, true); + return envObject.getReturnStatus(); + } + catch (err) { + envObject.tryCatch.setError(err); + return envObject.setLastError(10); + } + } + function napi_delete_element(env, object, index, result) { + var r; + if (!env) + return 1; + var envObject = emnapiCtx.envStore.get(env); + envObject.checkGCAccess(); + if (!envObject.tryCatch.isEmpty()) + return envObject.setLastError(10); + if (!envObject.canCallIntoJs()) + return envObject.setLastError(envObject.moduleApiVersion >= 10 ? 23 : 10); + envObject.clearLastError(); + try { + if (!object) + return envObject.setLastError(1); + var h = emnapiCtx.handleStore.get(object); + if (!(h.isObject() || h.isFunction())) { + return envObject.setLastError(2); + } + if (emnapiCtx.feature.supportReflect) { + r = Reflect.deleteProperty(h.value, index >>> 0); + } + else { + try { + r = delete h.value[index >>> 0]; + } + catch (_) { + r = false; + } + } + if (result) { + result >>>= 0; + var HEAP_DATA_VIEW = new DataView(wasmMemory.buffer), GET_HEAP_DATA_VIEW = function () { return HEAP_DATA_VIEW.buffer === wasmMemory.buffer ? HEAP_DATA_VIEW : (HEAP_DATA_VIEW = new DataView(wasmMemory.buffer)); }; + GET_HEAP_DATA_VIEW().setInt8(result, r ? 1 : 0, true); + } + return envObject.getReturnStatus(); + } + catch (err) { + envObject.tryCatch.setError(err); + return envObject.setLastError(10); + } + } + function napi_define_properties(env, object, property_count, properties) { + var propPtr, attributes; + if (!env) + return 1; + var envObject = emnapiCtx.envStore.get(env); + envObject.checkGCAccess(); + if (!envObject.tryCatch.isEmpty()) + return envObject.setLastError(10); + if (!envObject.canCallIntoJs()) + return envObject.setLastError(envObject.moduleApiVersion >= 10 ? 23 : 10); + envObject.clearLastError(); + try { + properties >>>= 0; + property_count >>>= 0; + property_count = property_count >>> 0; + if (property_count > 0) { + if (!properties) + return envObject.setLastError(1); + } + if (!object) + return envObject.setLastError(1); + var h = emnapiCtx.handleStore.get(object); + var maybeObject = h.value; + if (!(h.isObject() || h.isFunction())) { + return envObject.setLastError(2); + } + var propertyName = void 0; + var HEAP_DATA_VIEW = new DataView(wasmMemory.buffer), GET_HEAP_DATA_VIEW = function () { return HEAP_DATA_VIEW.buffer === wasmMemory.buffer ? HEAP_DATA_VIEW : (HEAP_DATA_VIEW = new DataView(wasmMemory.buffer)); }; + for (var i = 0; i < property_count; i++) { + propPtr = properties + (i * (4 * 8)); + var utf8Name = GET_HEAP_DATA_VIEW().getUint32(propPtr, true); + var name_2 = GET_HEAP_DATA_VIEW().getUint32(propPtr + 4, true); + var method = GET_HEAP_DATA_VIEW().getUint32(propPtr + 8, true); + var getter = GET_HEAP_DATA_VIEW().getUint32(propPtr + 12, true); + var setter = GET_HEAP_DATA_VIEW().getUint32(propPtr + 16, true); + var value = GET_HEAP_DATA_VIEW().getUint32(propPtr + 20, true); + attributes = GET_HEAP_DATA_VIEW().getInt32(propPtr + 24, true); + attributes >>>= 0; + var data = GET_HEAP_DATA_VIEW().getUint32(propPtr + 28, true); + if (utf8Name) { + propertyName = emnapiString.UTF8ToString(utf8Name, -1); + } + else { + if (!name_2) { + return envObject.setLastError(4); + } + propertyName = emnapiCtx.handleStore.get(name_2).value; + if (typeof propertyName !== 'string' && typeof propertyName !== 'symbol') { + return envObject.setLastError(4); + } + } + emnapiDefineProperty(envObject, maybeObject, propertyName, method, getter, setter, value, attributes, data); + } + return envObject.getReturnStatus(); + } + catch (err) { + envObject.tryCatch.setError(err); + return envObject.setLastError(10); + } + } + function napi_object_freeze(env, object) { + if (!env) + return 1; + var envObject = emnapiCtx.envStore.get(env); + envObject.checkGCAccess(); + if (!envObject.tryCatch.isEmpty()) + return envObject.setLastError(10); + if (!envObject.canCallIntoJs()) + return envObject.setLastError(envObject.moduleApiVersion >= 10 ? 23 : 10); + envObject.clearLastError(); + try { + if (!object) + return envObject.setLastError(1); + var h = emnapiCtx.handleStore.get(object); + var maybeObject = h.value; + if (!(h.isObject() || h.isFunction())) { + return envObject.setLastError(2); + } + Object.freeze(maybeObject); + return envObject.getReturnStatus(); + } + catch (err) { + envObject.tryCatch.setError(err); + return envObject.setLastError(10); + } + } + function napi_object_seal(env, object) { + if (!env) + return 1; + var envObject = emnapiCtx.envStore.get(env); + envObject.checkGCAccess(); + if (!envObject.tryCatch.isEmpty()) + return envObject.setLastError(10); + if (!envObject.canCallIntoJs()) + return envObject.setLastError(envObject.moduleApiVersion >= 10 ? 23 : 10); + envObject.clearLastError(); + try { + if (!object) + return envObject.setLastError(1); + var h = emnapiCtx.handleStore.get(object); + var maybeObject = h.value; + if (!(h.isObject() || h.isFunction())) { + return envObject.setLastError(2); + } + Object.seal(maybeObject); + return envObject.getReturnStatus(); + } + catch (err) { + envObject.tryCatch.setError(err); + return envObject.setLastError(10); + } + } + var propertyMod = Object.freeze({ + __proto__: null, + napi_define_properties: napi_define_properties, + napi_delete_element: napi_delete_element, + napi_delete_property: napi_delete_property, + napi_get_all_property_names: napi_get_all_property_names, + napi_get_element: napi_get_element, + napi_get_named_property: napi_get_named_property, + napi_get_property: napi_get_property, + napi_get_property_names: napi_get_property_names, + napi_has_element: napi_has_element, + napi_has_named_property: napi_has_named_property, + napi_has_own_property: napi_has_own_property, + napi_has_property: napi_has_property, + napi_object_freeze: napi_object_freeze, + napi_object_seal: napi_object_seal, + napi_set_element: napi_set_element, + napi_set_named_property: napi_set_named_property, + napi_set_property: napi_set_property + }); + function napi_run_script(env, script, result) { + var status; + var value; + if (!env) + return 1; + var envObject = emnapiCtx.envStore.get(env); + envObject.checkGCAccess(); + if (!envObject.tryCatch.isEmpty()) + return envObject.setLastError(10); + if (!envObject.canCallIntoJs()) + return envObject.setLastError(envObject.moduleApiVersion >= 10 ? 23 : 10); + envObject.clearLastError(); + try { + if (!script) + return envObject.setLastError(1); + if (!result) + return envObject.setLastError(1); + var v8Script = emnapiCtx.handleStore.get(script); + if (!v8Script.isString()) { + return envObject.setLastError(3); + } + var g = emnapiCtx.handleStore.get(5).value; + var ret = g.eval(v8Script.value); + result >>>= 0; + value = envObject.ensureHandleId(ret); + var HEAP_DATA_VIEW = new DataView(wasmMemory.buffer), GET_HEAP_DATA_VIEW = function () { return HEAP_DATA_VIEW.buffer === wasmMemory.buffer ? HEAP_DATA_VIEW : (HEAP_DATA_VIEW = new DataView(wasmMemory.buffer)); }; + GET_HEAP_DATA_VIEW().setUint32(result, value, true); + status = envObject.getReturnStatus(); + } + catch (err) { + envObject.tryCatch.setError(err); + return envObject.setLastError(10); + } + return status; + } + var scriptMod = Object.freeze({ + __proto__: null, + napi_run_script: napi_run_script + }); + function napi_typeof(env, value, result) { + if (!env) + return 1; + var envObject = emnapiCtx.envStore.get(env); + envObject.checkGCAccess(); + if (!value) + return envObject.setLastError(1); + if (!result) + return envObject.setLastError(1); + var v = emnapiCtx.handleStore.get(value); + result >>>= 0; + var r; + if (v.isNumber()) { + r = 3; + } + else if (v.isBigInt()) { + r = 9; + } + else if (v.isString()) { + r = 4; + } + else if (v.isFunction()) { + r = 7; + } + else if (v.isExternal()) { + r = 8; + } + else if (v.isObject()) { + r = 6; + } + else if (v.isBoolean()) { + r = 2; + } + else if (v.isUndefined()) { + r = 0; + } + else if (v.isSymbol()) { + r = 5; + } + else if (v.isNull()) { + r = 1; + } + else { + return envObject.setLastError(1); + } + var HEAP_DATA_VIEW = new DataView(wasmMemory.buffer), GET_HEAP_DATA_VIEW = function () { return HEAP_DATA_VIEW.buffer === wasmMemory.buffer ? HEAP_DATA_VIEW : (HEAP_DATA_VIEW = new DataView(wasmMemory.buffer)); }; + GET_HEAP_DATA_VIEW().setInt32(result, r, true); + return envObject.clearLastError(); + } + function napi_coerce_to_bool(env, value, result) { + var v; + if (!env) + return 1; + var envObject = emnapiCtx.envStore.get(env); + envObject.checkGCAccess(); + if (!envObject.tryCatch.isEmpty()) + return envObject.setLastError(10); + if (!envObject.canCallIntoJs()) + return envObject.setLastError(envObject.moduleApiVersion >= 10 ? 23 : 10); + envObject.clearLastError(); + try { + if (!value) + return envObject.setLastError(1); + if (!result) + return envObject.setLastError(1); + var handle = emnapiCtx.handleStore.get(value); + result >>>= 0; + v = handle.value ? 4 : 3; + var HEAP_DATA_VIEW = new DataView(wasmMemory.buffer), GET_HEAP_DATA_VIEW = function () { return HEAP_DATA_VIEW.buffer === wasmMemory.buffer ? HEAP_DATA_VIEW : (HEAP_DATA_VIEW = new DataView(wasmMemory.buffer)); }; + GET_HEAP_DATA_VIEW().setUint32(result, v, true); + return envObject.getReturnStatus(); + } + catch (err) { + envObject.tryCatch.setError(err); + return envObject.setLastError(10); + } + } + function napi_coerce_to_number(env, value, result) { + var v; + if (!env) + return 1; + var envObject = emnapiCtx.envStore.get(env); + envObject.checkGCAccess(); + if (!envObject.tryCatch.isEmpty()) + return envObject.setLastError(10); + if (!envObject.canCallIntoJs()) + return envObject.setLastError(envObject.moduleApiVersion >= 10 ? 23 : 10); + envObject.clearLastError(); + try { + if (!value) + return envObject.setLastError(1); + if (!result) + return envObject.setLastError(1); + var handle = emnapiCtx.handleStore.get(value); + if (handle.isBigInt()) { + throw new TypeError('Cannot convert a BigInt value to a number'); + } + result >>>= 0; + v = emnapiCtx.addToCurrentScope(Number(handle.value)).id; + var HEAP_DATA_VIEW = new DataView(wasmMemory.buffer), GET_HEAP_DATA_VIEW = function () { return HEAP_DATA_VIEW.buffer === wasmMemory.buffer ? HEAP_DATA_VIEW : (HEAP_DATA_VIEW = new DataView(wasmMemory.buffer)); }; + GET_HEAP_DATA_VIEW().setUint32(result, v, true); + return envObject.getReturnStatus(); + } + catch (err) { + envObject.tryCatch.setError(err); + return envObject.setLastError(10); + } + } + function napi_coerce_to_object(env, value, result) { + var v; + if (!env) + return 1; + var envObject = emnapiCtx.envStore.get(env); + envObject.checkGCAccess(); + if (!envObject.tryCatch.isEmpty()) + return envObject.setLastError(10); + if (!envObject.canCallIntoJs()) + return envObject.setLastError(envObject.moduleApiVersion >= 10 ? 23 : 10); + envObject.clearLastError(); + try { + if (!value) + return envObject.setLastError(1); + if (!result) + return envObject.setLastError(1); + var handle = emnapiCtx.handleStore.get(value); + if (handle.value == null) { + throw new TypeError('Cannot convert undefined or null to object'); + } + result >>>= 0; + v = envObject.ensureHandleId(Object(handle.value)); + var HEAP_DATA_VIEW = new DataView(wasmMemory.buffer), GET_HEAP_DATA_VIEW = function () { return HEAP_DATA_VIEW.buffer === wasmMemory.buffer ? HEAP_DATA_VIEW : (HEAP_DATA_VIEW = new DataView(wasmMemory.buffer)); }; + GET_HEAP_DATA_VIEW().setUint32(result, v, true); + return envObject.getReturnStatus(); + } + catch (err) { + envObject.tryCatch.setError(err); + return envObject.setLastError(10); + } + } + function napi_coerce_to_string(env, value, result) { + var v; + if (!env) + return 1; + var envObject = emnapiCtx.envStore.get(env); + envObject.checkGCAccess(); + if (!envObject.tryCatch.isEmpty()) + return envObject.setLastError(10); + if (!envObject.canCallIntoJs()) + return envObject.setLastError(envObject.moduleApiVersion >= 10 ? 23 : 10); + envObject.clearLastError(); + try { + if (!value) + return envObject.setLastError(1); + if (!result) + return envObject.setLastError(1); + var handle = emnapiCtx.handleStore.get(value); + if (handle.isSymbol()) { + throw new TypeError('Cannot convert a Symbol value to a string'); + } + result >>>= 0; + v = emnapiCtx.addToCurrentScope(String(handle.value)).id; + var HEAP_DATA_VIEW = new DataView(wasmMemory.buffer), GET_HEAP_DATA_VIEW = function () { return HEAP_DATA_VIEW.buffer === wasmMemory.buffer ? HEAP_DATA_VIEW : (HEAP_DATA_VIEW = new DataView(wasmMemory.buffer)); }; + GET_HEAP_DATA_VIEW().setUint32(result, v, true); + return envObject.getReturnStatus(); + } + catch (err) { + envObject.tryCatch.setError(err); + return envObject.setLastError(10); + } + } + function napi_instanceof(env, object, constructor, result) { + var r; + if (!env) + return 1; + var envObject = emnapiCtx.envStore.get(env); + envObject.checkGCAccess(); + if (!envObject.tryCatch.isEmpty()) + return envObject.setLastError(10); + if (!envObject.canCallIntoJs()) + return envObject.setLastError(envObject.moduleApiVersion >= 10 ? 23 : 10); + envObject.clearLastError(); + try { + if (!object) + return envObject.setLastError(1); + if (!result) + return envObject.setLastError(1); + if (!constructor) + return envObject.setLastError(1); + result >>>= 0; + var HEAP_DATA_VIEW = new DataView(wasmMemory.buffer), GET_HEAP_DATA_VIEW = function () { return HEAP_DATA_VIEW.buffer === wasmMemory.buffer ? HEAP_DATA_VIEW : (HEAP_DATA_VIEW = new DataView(wasmMemory.buffer)); }; + GET_HEAP_DATA_VIEW().setInt8(result, 0, true); + var ctor = emnapiCtx.handleStore.get(constructor); + if (!ctor.isFunction()) { + return envObject.setLastError(5); + } + var val = emnapiCtx.handleStore.get(object).value; + var ret = val instanceof ctor.value; + r = ret ? 1 : 0; + GET_HEAP_DATA_VIEW().setInt8(result, r, true); + return envObject.getReturnStatus(); + } + catch (err) { + envObject.tryCatch.setError(err); + return envObject.setLastError(10); + } + } + function napi_is_array(env, value, result) { + if (!env) + return 1; + var envObject = emnapiCtx.envStore.get(env); + envObject.checkGCAccess(); + if (!value) + return envObject.setLastError(1); + if (!result) + return envObject.setLastError(1); + var h = emnapiCtx.handleStore.get(value); + result >>>= 0; + var r = h.isArray() ? 1 : 0; + var HEAP_DATA_VIEW = new DataView(wasmMemory.buffer), GET_HEAP_DATA_VIEW = function () { return HEAP_DATA_VIEW.buffer === wasmMemory.buffer ? HEAP_DATA_VIEW : (HEAP_DATA_VIEW = new DataView(wasmMemory.buffer)); }; + GET_HEAP_DATA_VIEW().setInt8(result, r, true); + return envObject.clearLastError(); + } + function napi_is_arraybuffer(env, value, result) { + if (!env) + return 1; + var envObject = emnapiCtx.envStore.get(env); + envObject.checkGCAccess(); + if (!value) + return envObject.setLastError(1); + if (!result) + return envObject.setLastError(1); + var h = emnapiCtx.handleStore.get(value); + result >>>= 0; + var r = h.isArrayBuffer() ? 1 : 0; + var HEAP_DATA_VIEW = new DataView(wasmMemory.buffer), GET_HEAP_DATA_VIEW = function () { return HEAP_DATA_VIEW.buffer === wasmMemory.buffer ? HEAP_DATA_VIEW : (HEAP_DATA_VIEW = new DataView(wasmMemory.buffer)); }; + GET_HEAP_DATA_VIEW().setInt8(result, r, true); + return envObject.clearLastError(); + } + function node_api_is_sharedarraybuffer(env, value, result) { + if (!env) + return 1; + var envObject = emnapiCtx.envStore.get(env); + envObject.checkGCAccess(); + if (!value) + return envObject.setLastError(1); + if (!result) + return envObject.setLastError(1); + var h = emnapiCtx.handleStore.get(value); + result >>>= 0; + var r = ((typeof SharedArrayBuffer === 'function' && h.value instanceof SharedArrayBuffer) || + (Object.prototype.toString.call(h.value) === '[object SharedArrayBuffer]')) + ? 1 + : 0; + var HEAP_DATA_VIEW = new DataView(wasmMemory.buffer), GET_HEAP_DATA_VIEW = function () { return HEAP_DATA_VIEW.buffer === wasmMemory.buffer ? HEAP_DATA_VIEW : (HEAP_DATA_VIEW = new DataView(wasmMemory.buffer)); }; + GET_HEAP_DATA_VIEW().setInt8(result, r, true); + return envObject.clearLastError(); + } + function napi_is_date(env, value, result) { + if (!env) + return 1; + var envObject = emnapiCtx.envStore.get(env); + envObject.checkGCAccess(); + if (!value) + return envObject.setLastError(1); + if (!result) + return envObject.setLastError(1); + var h = emnapiCtx.handleStore.get(value); + result >>>= 0; + var r = h.isDate() ? 1 : 0; + var HEAP_DATA_VIEW = new DataView(wasmMemory.buffer), GET_HEAP_DATA_VIEW = function () { return HEAP_DATA_VIEW.buffer === wasmMemory.buffer ? HEAP_DATA_VIEW : (HEAP_DATA_VIEW = new DataView(wasmMemory.buffer)); }; + GET_HEAP_DATA_VIEW().setInt8(result, r, true); + return envObject.clearLastError(); + } + function napi_is_error(env, value, result) { + if (!env) + return 1; + var envObject = emnapiCtx.envStore.get(env); + envObject.checkGCAccess(); + if (!value) + return envObject.setLastError(1); + if (!result) + return envObject.setLastError(1); + var val = emnapiCtx.handleStore.get(value).value; + result >>>= 0; + var r = (val instanceof Error) ? 1 : 0; + var HEAP_DATA_VIEW = new DataView(wasmMemory.buffer), GET_HEAP_DATA_VIEW = function () { return HEAP_DATA_VIEW.buffer === wasmMemory.buffer ? HEAP_DATA_VIEW : (HEAP_DATA_VIEW = new DataView(wasmMemory.buffer)); }; + GET_HEAP_DATA_VIEW().setInt8(result, r, true); + return envObject.clearLastError(); + } + function napi_is_typedarray(env, value, result) { + if (!env) + return 1; + var envObject = emnapiCtx.envStore.get(env); + envObject.checkGCAccess(); + if (!value) + return envObject.setLastError(1); + if (!result) + return envObject.setLastError(1); + var h = emnapiCtx.handleStore.get(value); + result >>>= 0; + var r = h.isTypedArray() ? 1 : 0; + var HEAP_DATA_VIEW = new DataView(wasmMemory.buffer), GET_HEAP_DATA_VIEW = function () { return HEAP_DATA_VIEW.buffer === wasmMemory.buffer ? HEAP_DATA_VIEW : (HEAP_DATA_VIEW = new DataView(wasmMemory.buffer)); }; + GET_HEAP_DATA_VIEW().setInt8(result, r, true); + return envObject.clearLastError(); + } + function napi_is_buffer(env, value, result) { + if (!env) + return 1; + var envObject = emnapiCtx.envStore.get(env); + envObject.checkGCAccess(); + if (!value) + return envObject.setLastError(1); + if (!result) + return envObject.setLastError(1); + var h = emnapiCtx.handleStore.get(value); + result >>>= 0; + var r = h.isBuffer(emnapiCtx.feature.Buffer) ? 1 : 0; + var HEAP_DATA_VIEW = new DataView(wasmMemory.buffer), GET_HEAP_DATA_VIEW = function () { return HEAP_DATA_VIEW.buffer === wasmMemory.buffer ? HEAP_DATA_VIEW : (HEAP_DATA_VIEW = new DataView(wasmMemory.buffer)); }; + GET_HEAP_DATA_VIEW().setInt8(result, r, true); + return envObject.clearLastError(); + } + function napi_is_dataview(env, value, result) { + if (!env) + return 1; + var envObject = emnapiCtx.envStore.get(env); + envObject.checkGCAccess(); + if (!value) + return envObject.setLastError(1); + if (!result) + return envObject.setLastError(1); + var h = emnapiCtx.handleStore.get(value); + result >>>= 0; + var r = h.isDataView() ? 1 : 0; + var HEAP_DATA_VIEW = new DataView(wasmMemory.buffer), GET_HEAP_DATA_VIEW = function () { return HEAP_DATA_VIEW.buffer === wasmMemory.buffer ? HEAP_DATA_VIEW : (HEAP_DATA_VIEW = new DataView(wasmMemory.buffer)); }; + GET_HEAP_DATA_VIEW().setInt8(result, r, true); + return envObject.clearLastError(); + } + function napi_strict_equals(env, lhs, rhs, result) { + var r; + if (!env) + return 1; + var envObject = emnapiCtx.envStore.get(env); + envObject.checkGCAccess(); + if (!envObject.tryCatch.isEmpty()) + return envObject.setLastError(10); + if (!envObject.canCallIntoJs()) + return envObject.setLastError(envObject.moduleApiVersion >= 10 ? 23 : 10); + envObject.clearLastError(); + try { + if (!lhs) + return envObject.setLastError(1); + if (!rhs) + return envObject.setLastError(1); + if (!result) + return envObject.setLastError(1); + var lv = emnapiCtx.handleStore.get(lhs).value; + var rv = emnapiCtx.handleStore.get(rhs).value; + result >>>= 0; + r = (lv === rv) ? 1 : 0; + var HEAP_DATA_VIEW = new DataView(wasmMemory.buffer), GET_HEAP_DATA_VIEW = function () { return HEAP_DATA_VIEW.buffer === wasmMemory.buffer ? HEAP_DATA_VIEW : (HEAP_DATA_VIEW = new DataView(wasmMemory.buffer)); }; + GET_HEAP_DATA_VIEW().setInt8(result, r, true); + return envObject.getReturnStatus(); + } + catch (err) { + envObject.tryCatch.setError(err); + return envObject.setLastError(10); + } + } + function napi_detach_arraybuffer(env, arraybuffer) { + if (!env) + return 1; + var envObject = emnapiCtx.envStore.get(env); + envObject.checkGCAccess(); + if (!arraybuffer) + return envObject.setLastError(1); + var value = emnapiCtx.handleStore.get(arraybuffer).value; + if (!(value instanceof ArrayBuffer)) { + if (typeof SharedArrayBuffer === 'function' && (value instanceof SharedArrayBuffer)) { + return envObject.setLastError(20); + } + return envObject.setLastError(19); + } + try { + var MessageChannel_1 = emnapiCtx.feature.MessageChannel; + var messageChannel = new MessageChannel_1(); + messageChannel.port1.postMessage(value, [value]); + } + catch (_) { + return envObject.setLastError(9); + } + return envObject.clearLastError(); + } + function napi_is_detached_arraybuffer(env, arraybuffer, result) { + if (!env) + return 1; + var envObject = emnapiCtx.envStore.get(env); + envObject.checkGCAccess(); + if (!envObject.tryCatch.isEmpty()) + return envObject.setLastError(10); + if (!envObject.canCallIntoJs()) + return envObject.setLastError(envObject.moduleApiVersion >= 10 ? 23 : 10); + envObject.clearLastError(); + try { + if (!arraybuffer) + return envObject.setLastError(1); + if (!result) + return envObject.setLastError(1); + var h = emnapiCtx.handleStore.get(arraybuffer); + result >>>= 0; + var HEAP_DATA_VIEW = new DataView(wasmMemory.buffer), GET_HEAP_DATA_VIEW = function () { return HEAP_DATA_VIEW.buffer === wasmMemory.buffer ? HEAP_DATA_VIEW : (HEAP_DATA_VIEW = new DataView(wasmMemory.buffer)); }; + if (h.isArrayBuffer() && h.value.byteLength === 0) { + try { + new Uint8Array(h.value); + } + catch (_) { + GET_HEAP_DATA_VIEW().setInt8(result, 1, true); + return envObject.getReturnStatus(); + } + } + GET_HEAP_DATA_VIEW().setInt8(result, 0, true); + return envObject.getReturnStatus(); + } + catch (err) { + envObject.tryCatch.setError(err); + return envObject.setLastError(10); + } + } + var valueOperationMod = Object.freeze({ + __proto__: null, + napi_coerce_to_bool: napi_coerce_to_bool, + napi_coerce_to_number: napi_coerce_to_number, + napi_coerce_to_object: napi_coerce_to_object, + napi_coerce_to_string: napi_coerce_to_string, + napi_detach_arraybuffer: napi_detach_arraybuffer, + napi_instanceof: napi_instanceof, + napi_is_array: napi_is_array, + napi_is_arraybuffer: napi_is_arraybuffer, + napi_is_buffer: napi_is_buffer, + napi_is_dataview: napi_is_dataview, + napi_is_date: napi_is_date, + napi_is_detached_arraybuffer: napi_is_detached_arraybuffer, + napi_is_error: napi_is_error, + napi_is_typedarray: napi_is_typedarray, + napi_strict_equals: napi_strict_equals, + napi_typeof: napi_typeof, + node_api_is_sharedarraybuffer: node_api_is_sharedarraybuffer + }); + function napi_get_version(env, result) { + if (!env) + return 1; + var envObject = emnapiCtx.envStore.get(env); + if (!result) + return envObject.setLastError(1); + var NODE_API_SUPPORTED_VERSION_MAX = 10; + var HEAP_DATA_VIEW = new DataView(wasmMemory.buffer), GET_HEAP_DATA_VIEW = function () { return HEAP_DATA_VIEW.buffer === wasmMemory.buffer ? HEAP_DATA_VIEW : (HEAP_DATA_VIEW = new DataView(wasmMemory.buffer)); }; + GET_HEAP_DATA_VIEW().setUint32(result, NODE_API_SUPPORTED_VERSION_MAX, true); + return envObject.clearLastError(); + } + var versionMod = Object.freeze({ + __proto__: null, + napi_get_version: napi_get_version + }); + emnapiAWST.init(); + emnapiExternalMemory.init(); + emnapiExternalSAB.init(); + emnapiString.init(); + emnapiTSFN.init(); + PThread.init(); + napiModule.emnapi.syncMemory = $emnapiSyncMemory; + napiModule.emnapi.getMemoryAddress = $emnapiGetMemoryAddress; + napiModule.emnapi.acquireExternalSharedArrayBuffer = $emnapiAcquireExternalSharedArrayBuffer; + function addImports(mod) { + var keys = Object.keys(mod); + for (var i = 0; i < keys.length; ++i) { + var k = keys[i]; + if (k.indexOf('$') === 0) + continue; + if (k.indexOf('emnapi_') === 0) { + napiModule.imports.emnapi[k] = mod[k]; + } + else if (k.indexOf('_emnapi_') === 0 || k === 'napi_set_last_error' || k === 'napi_clear_last_error') { + napiModule.imports.env[k] = mod[k]; + } + else { + napiModule.imports.napi[k] = mod[k]; + } + } + } + addImports(asyncMod); + addImports(memoryMod); + addImports(asyncWorkMod); + addImports(utilMod); + addImports(convert2cMod); + addImports(convert2napiMod); + addImports(createMod); + addImports(globalMod); + addImports(wrapMod); + addImports(envMod); + addImports(emnapiMod); + addImports(errorMod); + addImports(functionMod); + addImports(lifeMod); + addImports(miscellaneousMod); + addImports(nodeMod); + addImports(promiseMod); + addImports(propertyMod); + addImports(scriptMod); + addImports(valueOperationMod); + addImports(versionMod); + napiModule.imports.napi.napi_create_threadsafe_function = napi_create_threadsafe_function; + napiModule.imports.napi.napi_get_threadsafe_function_context = napi_get_threadsafe_function_context; + napiModule.imports.napi.napi_call_threadsafe_function = napi_call_threadsafe_function; + napiModule.imports.napi.napi_acquire_threadsafe_function = napi_acquire_threadsafe_function; + napiModule.imports.napi.napi_release_threadsafe_function = napi_release_threadsafe_function; + napiModule.imports.napi.napi_unref_threadsafe_function = napi_unref_threadsafe_function; + napiModule.imports.napi.napi_ref_threadsafe_function = napi_ref_threadsafe_function; + return napiModule; + })(); + return napiModule; +} + +function loadNapiModuleImpl(loadFn, userNapiModule, wasmInput, options) { + options = options !== null && options !== void 0 ? options : {}; + const getMemory = options.getMemory; + const getTable = options.getTable; + const beforeInit = options.beforeInit; + if (getMemory != null && typeof getMemory !== 'function') { + throw new TypeError('options.getMemory is not a function'); + } + if (getTable != null && typeof getTable !== 'function') { + throw new TypeError('options.getTable is not a function'); + } + if (beforeInit != null && typeof beforeInit !== 'function') { + throw new TypeError('options.beforeInit is not a function'); + } + let napiModule; + const isLoad = typeof userNapiModule === 'object' && userNapiModule !== null; + if (isLoad) { + if (userNapiModule.loaded) { + throw new Error('napiModule has already loaded'); + } + napiModule = userNapiModule; + } + else { + napiModule = createNapiModule(options); + } + const wasi = options.wasi; + let wasiThreads; + let importObject = { + env: napiModule.imports.env, + napi: napiModule.imports.napi, + emnapi: napiModule.imports.emnapi + }; + if (wasi) { + wasiThreads = new WASIThreads(napiModule.childThread + ? { + wasi, + childThread: true, + postMessage: napiModule.postMessage + } + : { + wasi, + threadManager: napiModule.PThread, + waitThreadStart: napiModule.waitThreadStart + }); + Object.assign(importObject, typeof wasi.getImportObject === 'function' + ? wasi.getImportObject() + : { wasi_snapshot_preview1: wasi.wasiImport }); + Object.assign(importObject, wasiThreads.getImportObject()); + } + const overwriteImports = options.overwriteImports; + if (typeof overwriteImports === 'function') { + const newImportObject = overwriteImports(importObject); + if (typeof newImportObject === 'object' && newImportObject !== null) { + importObject = newImportObject; + } + } + return loadFn(wasmInput, importObject, (err, source) => { + if (err) { + throw err; + } + const originalInstance = source.instance; + let instance = originalInstance; + const originalExports = originalInstance.exports; + const exportMemory = 'memory' in originalExports; + const importMemory = 'memory' in importObject.env; + const memory = getMemory + ? getMemory(originalExports) + : exportMemory + ? originalExports.memory + : importMemory + ? importObject.env.memory + : undefined; + if (!memory) { + throw new Error('memory is neither exported nor imported'); + } + const table = getTable ? getTable(originalExports) : originalExports.__indirect_function_table; + if (wasi && !exportMemory) { + const exports = Object.create(null); + Object.assign(exports, originalExports, { memory }); + instance = { exports }; + } + const module = source.module; + if (wasi) { + instance = wasiThreads.initialize(instance, module, memory); + } + else { + napiModule.PThread.setup(module, memory); + } + const emnapiInit = () => { + if (beforeInit) { + beforeInit({ + instance: originalInstance, + module + }); + } + napiModule.init({ + instance, + module, + memory, + table + }); + const ret = { + instance: originalInstance, + module, + usedInstance: instance + }; + if (!isLoad) { + ret.napiModule = napiModule; + } + return ret; + }; + if (napiModule.PThread.shouldPreloadWorkers()) { + const poolReady = napiModule.PThread.loadWasmModuleToAllWorkers(); + if (loadFn === loadCallback) { + return poolReady.then(emnapiInit); + } + else { + throw new Error('Synchronous loading is not supported with worker pool (reuseWorker.size > 0)'); + } + } + return emnapiInit(); + }); +} +function loadCallback(wasmInput, importObject, callback) { + return load(wasmInput, importObject).then((source) => { + return callback(null, source); + }, err => { + return callback(err); + }); +} +function loadSyncCallback(wasmInput, importObject, callback) { + let source; + try { + source = loadSync(wasmInput, importObject); + } + catch (err) { + return callback(err); + } + return callback(null, source); +} +function loadNapiModule(napiModule, wasmInput, options) { + if (typeof napiModule !== 'object' || napiModule === null) { + throw new TypeError('Invalid napiModule'); + } + return loadNapiModuleImpl(loadCallback, napiModule, wasmInput, options); +} +function loadNapiModuleSync(napiModule, wasmInput, options) { + if (typeof napiModule !== 'object' || napiModule === null) { + throw new TypeError('Invalid napiModule'); + } + return loadNapiModuleImpl(loadSyncCallback, napiModule, wasmInput, options); +} +function instantiateNapiModule(wasmInput, options) { + return loadNapiModuleImpl(loadCallback, undefined, wasmInput, options); +} +function instantiateNapiModuleSync(wasmInput, options) { + return loadNapiModuleImpl(loadSyncCallback, undefined, wasmInput, options); +} + +class MessageHandler extends ThreadMessageHandler { + constructor(options) { + if (typeof options.onLoad !== 'function') { + throw new TypeError('options.onLoad is not a function'); + } + const userOnError = options.onError; + super({ + ...options, + onError: (err, type) => { + var _a; + const emnapi_thread_crashed = (_a = this.instance) === null || _a === void 0 ? void 0 : _a.exports.emnapi_thread_crashed; + if (typeof emnapi_thread_crashed === 'function') { + emnapi_thread_crashed(); + } + if (typeof userOnError === 'function') { + userOnError(err, type); + } + else { + throw err; + } + } + }); + this.napiModule = undefined; + } + instantiate(data) { + const source = this.onLoad(data); + const then = source.then; + if (typeof then === 'function') { + return source.then((result) => { + this.napiModule = result.napiModule; + return result; + }); + } + this.napiModule = source.napiModule; + return source; + } + handle(e) { + var _a; + super.handle(e); + if ((_a = e === null || e === void 0 ? void 0 : e.data) === null || _a === void 0 ? void 0 : _a.__emnapi__) { + const type = e.data.__emnapi__.type; + const payload = e.data.__emnapi__.payload; + try { + if (type === 'async-worker-init') { + this.handleAfterLoad(e, () => { + this.napiModule.initWorker(payload.arg, payload.func); + }); + } + } + catch (err) { + this.onError(err, type); + } + } + } +} + +const version = "1.11.3"; + +export { MessageHandler, createNapiModule, instantiateNapiModule, instantiateNapiModuleSync, loadNapiModule, loadNapiModuleSync, version }; diff --git a/dg-ui/node_modules/@tailwindcss/oxide-wasm32-wasi/node_modules/@emnapi/core/index.js b/dg-ui/node_modules/@tailwindcss/oxide-wasm32-wasi/node_modules/@emnapi/core/index.js new file mode 100644 index 0000000..11764ed --- /dev/null +++ b/dg-ui/node_modules/@tailwindcss/oxide-wasm32-wasi/node_modules/@emnapi/core/index.js @@ -0,0 +1,5 @@ +if (typeof process !== 'undefined' && process.env.NODE_ENV === 'production') { + module.exports = require('./dist/emnapi-core.cjs.min.js') +} else { + module.exports = require('./dist/emnapi-core.cjs.js') +} diff --git a/dg-ui/node_modules/@tailwindcss/oxide-wasm32-wasi/node_modules/@emnapi/core/package.json b/dg-ui/node_modules/@tailwindcss/oxide-wasm32-wasi/node_modules/@emnapi/core/package.json new file mode 100644 index 0000000..96e8595 --- /dev/null +++ b/dg-ui/node_modules/@tailwindcss/oxide-wasm32-wasi/node_modules/@emnapi/core/package.json @@ -0,0 +1,49 @@ +{ + "name": "@emnapi/core", + "version": "1.11.3", + "description": "emnapi core", + "main": "index.js", + "module": "./dist/emnapi-core.esm-bundler.js", + "types": "./dist/emnapi-core.d.ts", + "sideEffects": false, + "exports": { + ".": { + "types": { + "module": "./dist/emnapi-core.d.ts", + "import": "./dist/emnapi-core.d.mts", + "default": "./dist/emnapi-core.d.ts" + }, + "module": "./dist/emnapi-core.esm-bundler.js", + "import": "./dist/emnapi-core.mjs", + "default": "./index.js" + }, + "./dist/emnapi-core.cjs.min": { + "types": "./dist/emnapi-core.d.ts", + "default": "./dist/emnapi-core.cjs.min.js" + }, + "./dist/emnapi-core.min.mjs": { + "types": "./dist/emnapi-core.d.mts", + "default": "./dist/emnapi-core.min.mjs" + } + }, + "dependencies": { + "@emnapi/wasi-threads": "1.2.3", + "tslib": "^2.4.0" + }, + "scripts": { + "build": "node ./script/build.js" + }, + "repository": { + "type": "git", + "url": "git+https://github.com/toyobayashi/emnapi.git" + }, + "author": "toyobayashi", + "license": "MIT", + "bugs": { + "url": "https://github.com/toyobayashi/emnapi/issues" + }, + "homepage": "https://github.com/toyobayashi/emnapi#readme", + "publishConfig": { + "access": "public" + } +} diff --git a/dg-ui/node_modules/@tailwindcss/oxide-wasm32-wasi/node_modules/@emnapi/runtime/LICENSE b/dg-ui/node_modules/@tailwindcss/oxide-wasm32-wasi/node_modules/@emnapi/runtime/LICENSE new file mode 100644 index 0000000..05a5944 --- /dev/null +++ b/dg-ui/node_modules/@tailwindcss/oxide-wasm32-wasi/node_modules/@emnapi/runtime/LICENSE @@ -0,0 +1,21 @@ +MIT License + +Copyright (c) 2021-present Toyobayashi + +Permission is hereby granted, free of charge, to any person obtaining a copy +of this software and associated documentation files (the "Software"), to deal +in the Software without restriction, including without limitation the rights +to use, copy, modify, merge, publish, distribute, sublicense, and/or sell +copies of the Software, and to permit persons to whom the Software is +furnished to do so, subject to the following conditions: + +The above copyright notice and this permission notice shall be included in all +copies or substantial portions of the Software. + +THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR +IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, +FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE +AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER +LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, +OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE +SOFTWARE. diff --git a/dg-ui/node_modules/@tailwindcss/oxide-wasm32-wasi/node_modules/@emnapi/runtime/README.md b/dg-ui/node_modules/@tailwindcss/oxide-wasm32-wasi/node_modules/@emnapi/runtime/README.md new file mode 100644 index 0000000..c98dddc --- /dev/null +++ b/dg-ui/node_modules/@tailwindcss/oxide-wasm32-wasi/node_modules/@emnapi/runtime/README.md @@ -0,0 +1 @@ +See [https://github.com/toyobayashi/emnapi](https://github.com/toyobayashi/emnapi) diff --git a/dg-ui/node_modules/@tailwindcss/oxide-wasm32-wasi/node_modules/@emnapi/runtime/dist/emnapi.cjs.js b/dg-ui/node_modules/@tailwindcss/oxide-wasm32-wasi/node_modules/@emnapi/runtime/dist/emnapi.cjs.js new file mode 100644 index 0000000..5bba2ba --- /dev/null +++ b/dg-ui/node_modules/@tailwindcss/oxide-wasm32-wasi/node_modules/@emnapi/runtime/dist/emnapi.cjs.js @@ -0,0 +1,1398 @@ +const externalValue = new WeakMap(); +function isExternal(object) { + return externalValue.has(object); +} +const External = (() => { + function External(value) { + Object.setPrototypeOf(this, null); + externalValue.set(this, value); + } + External.prototype = null; + return External; +})(); +function getExternalValue(external) { + if (!isExternal(external)) { + throw new TypeError('not external'); + } + return externalValue.get(external); +} + +const supportNewFunction = (function () { + let f; + try { + f = new Function(); + } + catch (_) { + return false; + } + return typeof f === 'function'; +})(); +const _global = (function () { + if (typeof globalThis !== 'undefined') + return globalThis; + let g = (function () { return this; })(); + if (!g && supportNewFunction) { + try { + g = new Function('return this')(); + } + catch (_) { } + } + if (!g) { + if (typeof __webpack_public_path__ === 'undefined') { + if (typeof global !== 'undefined') + return global; + } + if (typeof window !== 'undefined') + return window; + if (typeof self !== 'undefined') + return self; + } + return g; +})(); +class TryCatch { + constructor() { + this._exception = undefined; + this._caught = false; + } + isEmpty() { + return !this._caught; + } + hasCaught() { + return this._caught; + } + exception() { + return this._exception; + } + setError(err) { + this._caught = true; + this._exception = err; + } + reset() { + this._caught = false; + this._exception = undefined; + } + extractException() { + const e = this._exception; + this.reset(); + return e; + } +} +const canSetFunctionName = (function () { + var _a; + try { + return Boolean((_a = Object.getOwnPropertyDescriptor(Function.prototype, 'name')) === null || _a === void 0 ? void 0 : _a.configurable); + } + catch (_) { + return false; + } +})(); +const supportReflect = typeof Reflect === 'object'; +const supportFinalizer = (typeof FinalizationRegistry !== 'undefined') && (typeof WeakRef !== 'undefined'); +const supportWeakSymbol = (function () { + try { + const sym = Symbol(); + new WeakRef(sym); + new WeakMap().set(sym, undefined); + } + catch (_) { + return false; + } + return true; +})(); +const supportBigInt = typeof BigInt !== 'undefined'; +function isReferenceType(v) { + return (typeof v === 'object' && v !== null) || typeof v === 'function'; +} +const _require = (function () { + let nativeRequire; + if (typeof __webpack_public_path__ !== 'undefined') { + nativeRequire = (function () { + return typeof __non_webpack_require__ !== 'undefined' ? __non_webpack_require__ : undefined; + })(); + } + else { + nativeRequire = (function () { + return typeof __webpack_public_path__ !== 'undefined' ? (typeof __non_webpack_require__ !== 'undefined' ? __non_webpack_require__ : undefined) : (typeof require !== 'undefined' ? require : undefined); + })(); + } + return nativeRequire; +})(); +const _MessageChannel = typeof MessageChannel === 'function' + ? MessageChannel + : (function () { + try { + return _require('worker_threads').MessageChannel; + } + catch (_) { } + return undefined; + })(); +const _setImmediate = typeof setImmediate === 'function' + ? setImmediate.bind(_global) + : function (callback) { + if (typeof callback !== 'function') { + throw new TypeError('The "callback" argument must be of type function'); + } + if (_MessageChannel) { + let channel = new _MessageChannel(); + channel.port1.onmessage = function () { + channel.port1.onmessage = null; + channel = undefined; + callback(); + }; + channel.port2.postMessage(null); + } + else { + setTimeout(callback, 0); + } + }; +const _Buffer = typeof Buffer === 'function' + ? Buffer + : (function () { + try { + return _require('buffer').Buffer; + } + catch (_) { } + return undefined; + })(); +const version = "1.11.3"; +const NODE_API_SUPPORTED_VERSION_MIN = 1; +const NODE_API_SUPPORTED_VERSION_MAX = 10; +const NAPI_VERSION_EXPERIMENTAL = 2147483647; +const NODE_API_DEFAULT_MODULE_API_VERSION = 8; + +class Handle { + constructor(id, value) { + this.id = id; + this.value = value; + } + data() { + return getExternalValue(this.value); + } + isNumber() { + return typeof this.value === 'number'; + } + isBigInt() { + return typeof this.value === 'bigint'; + } + isString() { + return typeof this.value === 'string'; + } + isFunction() { + return typeof this.value === 'function'; + } + isExternal() { + return isExternal(this.value); + } + isObject() { + return typeof this.value === 'object' && this.value !== null; + } + isArray() { + return Array.isArray(this.value); + } + isArrayBuffer() { + return (this.value instanceof ArrayBuffer); + } + isTypedArray() { + return (ArrayBuffer.isView(this.value)) && !(this.value instanceof DataView); + } + isBuffer(BufferConstructor) { + if (ArrayBuffer.isView(this.value)) + return true; + BufferConstructor !== null && BufferConstructor !== void 0 ? BufferConstructor : (BufferConstructor = _Buffer); + return typeof BufferConstructor === 'function' && BufferConstructor.isBuffer(this.value); + } + isDataView() { + return (this.value instanceof DataView); + } + isDate() { + return (this.value instanceof Date); + } + isPromise() { + return (this.value instanceof Promise); + } + isBoolean() { + return typeof this.value === 'boolean'; + } + isUndefined() { + return this.value === undefined; + } + isSymbol() { + return typeof this.value === 'symbol'; + } + isNull() { + return this.value === null; + } + dispose() { + this.value = undefined; + } +} +class ConstHandle extends Handle { + constructor(id, value) { + super(id, value); + } + dispose() { } +} +class HandleStore { + constructor() { + this._values = [ + undefined, + HandleStore.UNDEFINED, + HandleStore.NULL, + HandleStore.FALSE, + HandleStore.TRUE, + HandleStore.GLOBAL + ]; + this._next = HandleStore.MIN_ID; + } + push(value) { + let h; + const next = this._next; + const values = this._values; + if (next < values.length) { + h = values[next]; + h.value = value; + } + else { + h = new Handle(next, value); + values[next] = h; + } + this._next++; + return h; + } + erase(start, end) { + this._next = start; + const values = this._values; + for (let i = start; i < end; ++i) { + values[i].dispose(); + } + } + get(id) { + return this._values[id]; + } + swap(a, b) { + const values = this._values; + const h = values[a]; + values[a] = values[b]; + values[a].id = Number(a); + values[b] = h; + h.id = Number(b); + } + dispose() { + this._values.length = HandleStore.MIN_ID; + this._next = HandleStore.MIN_ID; + } +} +HandleStore.UNDEFINED = new ConstHandle(1, undefined); +HandleStore.NULL = new ConstHandle(2, null); +HandleStore.FALSE = new ConstHandle(3, false); +HandleStore.TRUE = new ConstHandle(4, true); +HandleStore.GLOBAL = new ConstHandle(5, _global); +HandleStore.MIN_ID = 6; + +class HandleScope { + constructor(handleStore, id, parentScope, start, end = start) { + this.handleStore = handleStore; + this.id = id; + this.parent = parentScope; + this.child = null; + if (parentScope !== null) + parentScope.child = this; + this.start = start; + this.end = end; + this._escapeCalled = false; + this.callbackInfo = { + thiz: undefined, + data: 0, + args: undefined, + fn: undefined + }; + } + add(value) { + const h = this.handleStore.push(value); + this.end++; + return h; + } + addExternal(data) { + return this.add(new External(data)); + } + dispose() { + if (this._escapeCalled) + this._escapeCalled = false; + if (this.start === this.end) + return; + this.handleStore.erase(this.start, this.end); + } + escape(handle) { + if (this._escapeCalled) + return null; + this._escapeCalled = true; + if (handle < this.start || handle >= this.end) { + return null; + } + this.handleStore.swap(handle, this.start); + const h = this.handleStore.get(this.start); + this.start++; + this.parent.end++; + return h; + } + escapeCalled() { + return this._escapeCalled; + } +} + +class ScopeStore { + constructor() { + this._rootScope = new HandleScope(null, 0, null, 1, HandleStore.MIN_ID); + this.currentScope = this._rootScope; + this._values = [undefined]; + } + get(id) { + return this._values[id]; + } + openScope(handleStore) { + const currentScope = this.currentScope; + let scope = currentScope.child; + if (scope !== null) { + scope.start = scope.end = currentScope.end; + } + else { + const id = currentScope.id + 1; + scope = new HandleScope(handleStore, id, currentScope, currentScope.end); + this._values[id] = scope; + } + this.currentScope = scope; + return scope; + } + closeScope() { + const scope = this.currentScope; + this.currentScope = scope.parent; + scope.dispose(); + } + dispose() { + this.currentScope = this._rootScope; + this._values.length = 1; + } +} + +class RefTracker { + constructor() { + this._next = null; + this._prev = null; + } + dispose() { } + finalize() { } + link(list) { + this._prev = list; + this._next = list._next; + if (this._next !== null) { + this._next._prev = this; + } + list._next = this; + } + unlink() { + if (this._prev !== null) { + this._prev._next = this._next; + } + if (this._next !== null) { + this._next._prev = this._prev; + } + this._prev = null; + this._next = null; + } + static finalizeAll(list) { + while (list._next !== null) { + list._next.finalize(); + } + } +} + +class Finalizer { + constructor(envObject, _finalizeCallback = 0, _finalizeData = 0, _finalizeHint = 0) { + this.envObject = envObject; + this._finalizeCallback = _finalizeCallback; + this._finalizeData = _finalizeData; + this._finalizeHint = _finalizeHint; + this._makeDynCall_vppp = envObject.makeDynCall_vppp; + } + callback() { return this._finalizeCallback; } + data() { return this._finalizeData; } + hint() { return this._finalizeHint; } + resetEnv() { + this.envObject = undefined; + } + resetFinalizer() { + this._finalizeCallback = 0; + this._finalizeData = 0; + this._finalizeHint = 0; + } + callFinalizer() { + const finalize_callback = this._finalizeCallback; + const finalize_data = this._finalizeData; + const finalize_hint = this._finalizeHint; + this.resetFinalizer(); + if (!finalize_callback) + return; + const fini = Number(finalize_callback); + if (!this.envObject) { + this._makeDynCall_vppp(fini)(0, finalize_data, finalize_hint); + } + else { + this.envObject.callFinalizer(fini, finalize_data, finalize_hint); + } + } + dispose() { + this.envObject = undefined; + this._makeDynCall_vppp = undefined; + } +} + +class TrackedFinalizer extends RefTracker { + static create(envObject, finalize_callback, finalize_data, finalize_hint) { + const finalizer = new TrackedFinalizer(envObject, finalize_callback, finalize_data, finalize_hint); + finalizer.link(envObject.finalizing_reflist); + return finalizer; + } + constructor(envObject, finalize_callback, finalize_data, finalize_hint) { + super(); + this._finalizer = new Finalizer(envObject, finalize_callback, finalize_data, finalize_hint); + } + data() { + return this._finalizer.data(); + } + dispose() { + if (!this._finalizer) + return; + this.unlink(); + this._finalizer.envObject.dequeueFinalizer(this); + this._finalizer.dispose(); + this._finalizer = undefined; + super.dispose(); + } + finalize() { + this.unlink(); + let error; + let caught = false; + try { + this._finalizer.callFinalizer(); + } + catch (err) { + caught = true; + error = err; + } + this.dispose(); + if (caught) { + throw error; + } + } +} + +function throwNodeApiVersionError(moduleName, moduleApiVersion) { + const errorMessage = `${moduleName} requires Node-API version ${moduleApiVersion}, but this version of Node.js only supports version ${NODE_API_SUPPORTED_VERSION_MAX} add-ons.`; + throw new Error(errorMessage); +} +function handleThrow(envObject, value) { + if (envObject.terminatedOrTerminating()) { + return; + } + throw value; +} +class Env { + constructor(ctx, moduleApiVersion, makeDynCall_vppp, makeDynCall_vp, abort) { + this.ctx = ctx; + this.moduleApiVersion = moduleApiVersion; + this.makeDynCall_vppp = makeDynCall_vppp; + this.makeDynCall_vp = makeDynCall_vp; + this.abort = abort; + this.openHandleScopes = 0; + this.instanceData = null; + this.tryCatch = new TryCatch(); + this.refs = 1; + this.reflist = new RefTracker(); + this.finalizing_reflist = new RefTracker(); + this.pendingFinalizers = []; + this.lastError = { + errorCode: 0, + engineErrorCode: 0, + engineReserved: 0 + }; + this.inGcFinalizer = false; + this._bindingMap = new WeakMap(); + this.id = 0; + } + canCallIntoJs() { + return true; + } + terminatedOrTerminating() { + return !this.canCallIntoJs(); + } + ref() { + this.refs++; + } + unref() { + this.refs--; + if (this.refs === 0) { + this.dispose(); + } + } + ensureHandle(value) { + return this.ctx.ensureHandle(value); + } + ensureHandleId(value) { + return this.ensureHandle(value).id; + } + clearLastError() { + const lastError = this.lastError; + if (lastError.errorCode !== 0) + lastError.errorCode = 0; + if (lastError.engineErrorCode !== 0) + lastError.engineErrorCode = 0; + if (lastError.engineReserved !== 0) + lastError.engineReserved = 0; + return 0; + } + setLastError(error_code, engine_error_code = 0, engine_reserved = 0) { + const lastError = this.lastError; + if (lastError.errorCode !== error_code) + lastError.errorCode = error_code; + if (lastError.engineErrorCode !== engine_error_code) + lastError.engineErrorCode = engine_error_code; + if (lastError.engineReserved !== engine_reserved) + lastError.engineReserved = engine_reserved; + return error_code; + } + getReturnStatus() { + return !this.tryCatch.hasCaught() ? 0 : this.setLastError(10); + } + callIntoModule(fn, handleException = handleThrow) { + const openHandleScopesBefore = this.openHandleScopes; + this.clearLastError(); + const r = fn(this); + if (openHandleScopesBefore !== this.openHandleScopes) { + this.abort('open_handle_scopes != open_handle_scopes_before'); + } + if (this.tryCatch.hasCaught()) { + const err = this.tryCatch.extractException(); + handleException(this, err); + } + return r; + } + invokeFinalizerFromGC(finalizer) { + if (this.moduleApiVersion !== NAPI_VERSION_EXPERIMENTAL) { + this.enqueueFinalizer(finalizer); + } + else { + const saved = this.inGcFinalizer; + this.inGcFinalizer = true; + try { + finalizer.finalize(); + } + finally { + this.inGcFinalizer = saved; + } + } + } + checkGCAccess() { + if (this.moduleApiVersion === NAPI_VERSION_EXPERIMENTAL && this.inGcFinalizer) { + this.abort('Finalizer is calling a function that may affect GC state.\n' + + 'The finalizers are run directly from GC and must not affect GC ' + + 'state.\n' + + 'Use `node_api_post_finalizer` from inside of the finalizer to work ' + + 'around this issue.\n' + + 'It schedules the call as a new task in the event loop.'); + } + } + enqueueFinalizer(finalizer) { + if (this.pendingFinalizers.indexOf(finalizer) === -1) { + this.pendingFinalizers.push(finalizer); + } + } + dequeueFinalizer(finalizer) { + const index = this.pendingFinalizers.indexOf(finalizer); + if (index !== -1) { + this.pendingFinalizers.splice(index, 1); + } + } + deleteMe() { + RefTracker.finalizeAll(this.finalizing_reflist); + RefTracker.finalizeAll(this.reflist); + this.tryCatch.extractException(); + this.ctx.envStore.remove(this.id); + } + dispose() { + if (this.id === 0) + return; + this.deleteMe(); + this.finalizing_reflist.dispose(); + this.reflist.dispose(); + this.id = 0; + } + initObjectBinding(value) { + const binding = { + wrapped: 0, + tag: null + }; + this._bindingMap.set(value, binding); + return binding; + } + getObjectBinding(value) { + if (this._bindingMap.has(value)) { + return this._bindingMap.get(value); + } + return this.initObjectBinding(value); + } + setInstanceData(data, finalize_cb, finalize_hint) { + if (this.instanceData) { + this.instanceData.dispose(); + } + this.instanceData = TrackedFinalizer.create(this, finalize_cb, data, finalize_hint); + } + getInstanceData() { + return this.instanceData ? this.instanceData.data() : 0; + } +} +class NodeEnv extends Env { + constructor(ctx, filename, moduleApiVersion, makeDynCall_vppp, makeDynCall_vp, abort, nodeBinding) { + super(ctx, moduleApiVersion, makeDynCall_vppp, makeDynCall_vp, abort); + this.filename = filename; + this.nodeBinding = nodeBinding; + this.destructing = false; + this.finalizationScheduled = false; + } + deleteMe() { + this.destructing = true; + this.drainFinalizerQueue(); + super.deleteMe(); + } + canCallIntoJs() { + return super.canCallIntoJs() && this.ctx.canCallIntoJs(); + } + triggerFatalException(err) { + if (this.nodeBinding) { + this.nodeBinding.napi.fatalException(err); + } + else { + if (typeof process === 'object' && process !== null && typeof process._fatalException === 'function') { + const handled = process._fatalException(err); + if (!handled) { + console.error(err); + process.exit(1); + } + } + else { + throw err; + } + } + } + callbackIntoModule(enforceUncaughtExceptionPolicy, fn) { + return this.callIntoModule(fn, (envObject, err) => { + if (envObject.terminatedOrTerminating()) { + return; + } + const hasProcess = typeof process === 'object' && process !== null; + const hasForceFlag = hasProcess ? Boolean(process.execArgv && (process.execArgv.indexOf('--force-node-api-uncaught-exceptions-policy') !== -1)) : false; + if (envObject.moduleApiVersion < 10 && !hasForceFlag && !enforceUncaughtExceptionPolicy) { + const warn = hasProcess && typeof process.emitWarning === 'function' + ? process.emitWarning + : function (warning, type, code) { + if (warning instanceof Error) { + console.warn(warning.toString()); + } + else { + const prefix = code ? `[${code}] ` : ''; + console.warn(`${prefix}${type || 'Warning'}: ${warning}`); + } + }; + warn('Uncaught Node-API callback exception detected, please run node with option --force-node-api-uncaught-exceptions-policy=true to handle those exceptions properly.', 'DeprecationWarning', 'DEP0168'); + return; + } + envObject.triggerFatalException(err); + }); + } + callFinalizer(cb, data, hint) { + this.callFinalizerInternal(1, cb, data, hint); + } + callFinalizerInternal(forceUncaught, cb, data, hint) { + const f = this.makeDynCall_vppp(cb); + const env = this.id; + const scope = this.ctx.openScope(this); + try { + this.callbackIntoModule(Boolean(forceUncaught), () => { f(env, data, hint); }); + } + finally { + this.ctx.closeScope(this, scope); + } + } + enqueueFinalizer(finalizer) { + super.enqueueFinalizer(finalizer); + if (!this.finalizationScheduled && !this.destructing) { + this.finalizationScheduled = true; + this.ref(); + _setImmediate(() => { + this.finalizationScheduled = false; + this.unref(); + this.drainFinalizerQueue(); + }); + } + } + drainFinalizerQueue() { + while (this.pendingFinalizers.length > 0) { + const refTracker = this.pendingFinalizers.shift(); + refTracker.finalize(); + } + } +} +function newEnv(ctx, filename, moduleApiVersion, makeDynCall_vppp, makeDynCall_vp, abort, nodeBinding) { + moduleApiVersion = typeof moduleApiVersion !== 'number' ? NODE_API_DEFAULT_MODULE_API_VERSION : moduleApiVersion; + if (moduleApiVersion < NODE_API_DEFAULT_MODULE_API_VERSION) { + moduleApiVersion = NODE_API_DEFAULT_MODULE_API_VERSION; + } + else if (moduleApiVersion > NODE_API_SUPPORTED_VERSION_MAX && moduleApiVersion !== NAPI_VERSION_EXPERIMENTAL) { + throwNodeApiVersionError(filename, moduleApiVersion); + } + const env = new NodeEnv(ctx, filename, moduleApiVersion, makeDynCall_vppp, makeDynCall_vp, abort, nodeBinding); + ctx.envStore.add(env); + ctx.addCleanupHook(env, () => { env.unref(); }, 0); + return env; +} + +class EmnapiError extends Error { + constructor(message) { + super(message); + const ErrorConstructor = new.target; + const proto = ErrorConstructor.prototype; + if (!(this instanceof EmnapiError)) { + const setPrototypeOf = Object.setPrototypeOf; + if (typeof setPrototypeOf === 'function') { + setPrototypeOf.call(Object, this, proto); + } + else { + this.__proto__ = proto; + } + if (typeof Error.captureStackTrace === 'function') { + Error.captureStackTrace(this, ErrorConstructor); + } + } + } +} +Object.defineProperty(EmnapiError.prototype, 'name', { + configurable: true, + writable: true, + value: 'EmnapiError' +}); +class NotSupportWeakRefError extends EmnapiError { + constructor(api, message) { + super(`${api}: The current runtime does not support "FinalizationRegistry" and "WeakRef".${message ? ` ${message}` : ''}`); + } +} +Object.defineProperty(NotSupportWeakRefError.prototype, 'name', { + configurable: true, + writable: true, + value: 'NotSupportWeakRefError' +}); +class NotSupportBufferError extends EmnapiError { + constructor(api, message) { + super(`${api}: The current runtime does not support "Buffer". Consider using buffer polyfill to make sure \`globalThis.Buffer\` is defined.${message ? ` ${message}` : ''}`); + } +} +Object.defineProperty(NotSupportBufferError.prototype, 'name', { + configurable: true, + writable: true, + value: 'NotSupportBufferError' +}); + +class StrongRef { + constructor(value) { + this._value = value; + } + deref() { + return this._value; + } + dispose() { + this._value = undefined; + } +} +class Persistent { + constructor(value) { + this._ref = new StrongRef(value); + } + setWeak(param, callback) { + if (!supportFinalizer || this._ref === undefined || this._ref instanceof WeakRef) + return; + const value = this._ref.deref(); + try { + Persistent._registry.register(value, this, this); + const weakRef = new WeakRef(value); + this._ref.dispose(); + this._ref = weakRef; + this._param = param; + this._callback = callback; + } + catch (err) { + if (typeof value === 'symbol') ; + else { + throw err; + } + } + } + clearWeak() { + if (!supportFinalizer || this._ref === undefined) + return; + if (this._ref instanceof WeakRef) { + try { + Persistent._registry.unregister(this); + } + catch (_) { } + this._param = undefined; + this._callback = undefined; + const value = this._ref.deref(); + if (value === undefined) { + this._ref = value; + } + else { + this._ref = new StrongRef(value); + } + } + } + reset() { + if (supportFinalizer) { + try { + Persistent._registry.unregister(this); + } + catch (_) { } + } + this._param = undefined; + this._callback = undefined; + if (this._ref instanceof StrongRef) { + this._ref.dispose(); + } + this._ref = undefined; + } + isEmpty() { + return this._ref === undefined; + } + deref() { + if (this._ref === undefined) + return undefined; + return this._ref.deref(); + } +} +Persistent._registry = supportFinalizer + ? new FinalizationRegistry((value) => { + value._ref = undefined; + const callback = value._callback; + const param = value._param; + value._callback = undefined; + value._param = undefined; + if (typeof callback === 'function') { + callback(param); + } + }) + : undefined; + +exports.ReferenceOwnership = void 0; +(function (ReferenceOwnership) { + ReferenceOwnership[ReferenceOwnership["kRuntime"] = 0] = "kRuntime"; + ReferenceOwnership[ReferenceOwnership["kUserland"] = 1] = "kUserland"; +})(exports.ReferenceOwnership || (exports.ReferenceOwnership = {})); +function canBeHeldWeakly(value) { + return value.isObject() || value.isFunction() || value.isSymbol(); +} +class Reference extends RefTracker { + static weakCallback(ref) { + ref.persistent.reset(); + ref.invokeFinalizerFromGC(); + } + static create(envObject, handle_id, initialRefcount, ownership, _unused1, _unused2, _unused3) { + const ref = new Reference(envObject, handle_id, initialRefcount, ownership); + envObject.ctx.refStore.add(ref); + ref.link(envObject.reflist); + return ref; + } + constructor(envObject, handle_id, initialRefcount, ownership) { + super(); + this.envObject = envObject; + this._refcount = initialRefcount; + this._ownership = ownership; + const handle = envObject.ctx.handleStore.get(handle_id); + this.canBeWeak = canBeHeldWeakly(handle); + this.persistent = new Persistent(handle.value); + this.id = 0; + if (initialRefcount === 0) { + this._setWeak(); + } + } + ref() { + if (this.persistent.isEmpty()) { + return 0; + } + if (++this._refcount === 1 && this.canBeWeak) { + this.persistent.clearWeak(); + } + return this._refcount; + } + unref() { + if (this.persistent.isEmpty() || this._refcount === 0) { + return 0; + } + if (--this._refcount === 0) { + this._setWeak(); + } + return this._refcount; + } + get(envObject = this.envObject) { + if (this.persistent.isEmpty()) { + return 0; + } + const obj = this.persistent.deref(); + const handle = envObject.ensureHandle(obj); + return handle.id; + } + resetFinalizer() { } + data() { return 0; } + refcount() { return this._refcount; } + ownership() { return this._ownership; } + callUserFinalizer() { } + invokeFinalizerFromGC() { + this.finalize(); + } + _setWeak() { + if (this.canBeWeak) { + this.persistent.setWeak(this, Reference.weakCallback); + } + else { + this.persistent.reset(); + } + } + finalize() { + this.persistent.reset(); + const deleteMe = this._ownership === exports.ReferenceOwnership.kRuntime; + this.unlink(); + this.callUserFinalizer(); + if (deleteMe) { + this.dispose(); + } + } + dispose() { + if (this.id === 0) + return; + this.unlink(); + this.persistent.reset(); + this.envObject.ctx.refStore.remove(this.id); + super.dispose(); + this.envObject = undefined; + this.id = 0; + } +} +class ReferenceWithData extends Reference { + static create(envObject, value, initialRefcount, ownership, data) { + const reference = new ReferenceWithData(envObject, value, initialRefcount, ownership, data); + envObject.ctx.refStore.add(reference); + reference.link(envObject.reflist); + return reference; + } + constructor(envObject, value, initialRefcount, ownership, _data) { + super(envObject, value, initialRefcount, ownership); + this._data = _data; + } + data() { + return this._data; + } +} +class ReferenceWithFinalizer extends Reference { + static create(envObject, value, initialRefcount, ownership, finalize_callback, finalize_data, finalize_hint) { + const reference = new ReferenceWithFinalizer(envObject, value, initialRefcount, ownership, finalize_callback, finalize_data, finalize_hint); + envObject.ctx.refStore.add(reference); + reference.link(envObject.finalizing_reflist); + return reference; + } + constructor(envObject, value, initialRefcount, ownership, finalize_callback, finalize_data, finalize_hint) { + super(envObject, value, initialRefcount, ownership); + this._finalizer = new Finalizer(envObject, finalize_callback, finalize_data, finalize_hint); + } + resetFinalizer() { + this._finalizer.resetFinalizer(); + } + data() { + return this._finalizer.data(); + } + callUserFinalizer() { + this._finalizer.callFinalizer(); + } + invokeFinalizerFromGC() { + this._finalizer.envObject.invokeFinalizerFromGC(this); + } + dispose() { + if (!this._finalizer) + return; + this._finalizer.envObject.dequeueFinalizer(this); + this._finalizer.dispose(); + super.dispose(); + this._finalizer = undefined; + } +} + +class Deferred { + static create(ctx, value) { + const deferred = new Deferred(ctx, value); + ctx.deferredStore.add(deferred); + return deferred; + } + constructor(ctx, value) { + Object.defineProperties(this, { + id: { + configurable: true, + enumerable: true, + value: 0, + writable: true + }, + ctx: { + configurable: true, + enumerable: true, + value: ctx, + writable: true + }, + value: { + configurable: true, + enumerable: true, + value, + writable: true + } + }); + } + resolve(value) { + this.value.resolve(value); + this.dispose(); + } + reject(reason) { + this.value.reject(reason); + this.dispose(); + } + dispose() { + this.ctx.deferredStore.remove(this.id); + this.id = 0; + this.value = null; + this.ctx = null; + } +} + +class Store { + constructor() { + this._values = [undefined]; + this._values.length = 4; + this._size = 1; + this._freeList = []; + } + add(value) { + let id; + if (this._freeList.length) { + id = this._freeList.shift(); + } + else { + id = this._size; + this._size++; + const capacity = this._values.length; + if (id >= capacity) { + this._values.length = capacity + (capacity >> 1) + 16; + } + } + value.id = id; + this._values[id] = value; + } + get(id) { + return this._values[id]; + } + has(id) { + return this._values[id] !== undefined; + } + remove(id) { + const value = this._values[id]; + if (value) { + value.id = 0; + this._values[id] = undefined; + this._freeList.push(Number(id)); + } + } + dispose() { + for (let i = 1; i < this._size; ++i) { + const value = this._values[i]; + value === null || value === void 0 ? void 0 : value.dispose(); + } + this._values = [undefined]; + this._size = 1; + this._freeList = []; + } +} + +const kMaxReasonableBytes = BigInt(1) << BigInt(60); +const kMinReasonableBytes = -kMaxReasonableBytes; +class ExternalMemory { + constructor(onChange) { + this.total = BigInt(0); + this.onChange = onChange !== null && onChange !== void 0 ? onChange : null; + } + adjust(changeInBytes) { + changeInBytes = BigInt(changeInBytes); + if (!(kMinReasonableBytes <= changeInBytes && changeInBytes < kMaxReasonableBytes)) { + throw new RangeError(`changeInBytes ${changeInBytes} is out of reasonable range`); + } + const old = this.total; + this.total += changeInBytes; + const amount = this.total; + const onChange = this.onChange; + if (changeInBytes) { + onChange === null || onChange === void 0 ? void 0 : onChange(amount, old, changeInBytes); + } + return amount; + } +} + +class CleanupHookCallback { + constructor(envObject, fn, arg, order) { + this.envObject = envObject; + this.fn = fn; + this.arg = arg; + this.order = order; + } +} +class CleanupQueue { + constructor() { + this._cleanupHooks = []; + this._cleanupHookCounter = 0; + } + empty() { + return this._cleanupHooks.length === 0; + } + add(envObject, fn, arg) { + if (this._cleanupHooks.filter((hook) => (hook.envObject === envObject && hook.fn === fn && hook.arg === arg)).length > 0) { + throw new Error('Can not add same fn and arg twice'); + } + this._cleanupHooks.push(new CleanupHookCallback(envObject, fn, arg, this._cleanupHookCounter++)); + } + remove(envObject, fn, arg) { + for (let i = 0; i < this._cleanupHooks.length; ++i) { + const hook = this._cleanupHooks[i]; + if (hook.envObject === envObject && hook.fn === fn && hook.arg === arg) { + this._cleanupHooks.splice(i, 1); + return; + } + } + } + drain() { + const hooks = this._cleanupHooks.slice(); + hooks.sort((a, b) => (b.order - a.order)); + for (let i = 0; i < hooks.length; ++i) { + const cb = hooks[i]; + if (typeof cb.fn === 'number') { + cb.envObject.makeDynCall_vp(cb.fn)(cb.arg); + } + else { + cb.fn(cb.arg); + } + this._cleanupHooks.splice(this._cleanupHooks.indexOf(cb), 1); + } + } + dispose() { + this._cleanupHooks.length = 0; + this._cleanupHookCounter = 0; + } +} +class NodejsWaitingRequestCounter { + constructor() { + this.refHandle = new _MessageChannel().port1; + this.count = 0; + } + increase() { + if (this.count === 0) { + if (this.refHandle.ref) { + this.refHandle.ref(); + } + } + this.count++; + } + decrease() { + if (this.count === 0) + return; + if (this.count === 1) { + if (this.refHandle.unref) { + this.refHandle.unref(); + } + } + this.count--; + } +} +class Context { + constructor(options) { + this._isStopping = false; + this._canCallIntoJs = true; + this._suppressDestroy = false; + this.envStore = new Store(); + this.scopeStore = new ScopeStore(); + this.refStore = new Store(); + this.deferredStore = new Store(); + this.handleStore = new HandleStore(); + this.feature = { + supportReflect, + supportFinalizer, + supportWeakSymbol, + supportBigInt, + supportNewFunction, + canSetFunctionName, + setImmediate: _setImmediate, + Buffer: _Buffer, + MessageChannel: _MessageChannel + }; + this.cleanupQueue = new CleanupQueue(); + this._externalMemory = new ExternalMemory(options === null || options === void 0 ? void 0 : options.onExternalMemoryChange); + if (typeof process === 'object' && process !== null && typeof process.once === 'function') { + this.refCounter = new NodejsWaitingRequestCounter(); + process.once('beforeExit', () => { + if (!this._suppressDestroy) { + this.destroy(); + } + }); + } + } + suppressDestroy() { + this._suppressDestroy = true; + } + getRuntimeVersions() { + return { + version, + NODE_API_SUPPORTED_VERSION_MAX, + NAPI_VERSION_EXPERIMENTAL, + NODE_API_DEFAULT_MODULE_API_VERSION + }; + } + createNotSupportWeakRefError(api, message) { + return new NotSupportWeakRefError(api, message); + } + createNotSupportBufferError(api, message) { + return new NotSupportBufferError(api, message); + } + createReference(envObject, handle_id, initialRefcount, ownership) { + return Reference.create(envObject, handle_id, initialRefcount, ownership); + } + createReferenceWithData(envObject, handle_id, initialRefcount, ownership, data) { + return ReferenceWithData.create(envObject, handle_id, initialRefcount, ownership, data); + } + createReferenceWithFinalizer(envObject, handle_id, initialRefcount, ownership, finalize_callback = 0, finalize_data = 0, finalize_hint = 0) { + return ReferenceWithFinalizer.create(envObject, handle_id, initialRefcount, ownership, finalize_callback, finalize_data, finalize_hint); + } + createDeferred(value) { + return Deferred.create(this, value); + } + adjustAmountOfExternalAllocatedMemory(changeInBytes) { + return this._externalMemory.adjust(changeInBytes); + } + createEnv(filename, moduleApiVersion, makeDynCall_vppp, makeDynCall_vp, abort, nodeBinding) { + return newEnv(this, filename, moduleApiVersion, makeDynCall_vppp, makeDynCall_vp, abort, nodeBinding); + } + createTrackedFinalizer(envObject, finalize_callback, finalize_data, finalize_hint) { + return TrackedFinalizer.create(envObject, finalize_callback, finalize_data, finalize_hint); + } + getCurrentScope() { + return this.scopeStore.currentScope; + } + addToCurrentScope(value) { + return this.scopeStore.currentScope.add(value); + } + openScope(envObject) { + const scope = this.scopeStore.openScope(this.handleStore); + if (envObject) + envObject.openHandleScopes++; + return scope; + } + closeScope(envObject, _scope) { + if (envObject && envObject.openHandleScopes === 0) + return; + this.scopeStore.closeScope(); + if (envObject) + envObject.openHandleScopes--; + } + ensureHandle(value) { + switch (value) { + case undefined: return HandleStore.UNDEFINED; + case null: return HandleStore.NULL; + case true: return HandleStore.TRUE; + case false: return HandleStore.FALSE; + case _global: return HandleStore.GLOBAL; + } + return this.addToCurrentScope(value); + } + addCleanupHook(envObject, fn, arg) { + this.cleanupQueue.add(envObject, fn, arg); + } + removeCleanupHook(envObject, fn, arg) { + this.cleanupQueue.remove(envObject, fn, arg); + } + runCleanup() { + while (!this.cleanupQueue.empty()) { + this.cleanupQueue.drain(); + } + } + increaseWaitingRequestCounter() { + var _a; + (_a = this.refCounter) === null || _a === void 0 ? void 0 : _a.increase(); + } + decreaseWaitingRequestCounter() { + var _a; + (_a = this.refCounter) === null || _a === void 0 ? void 0 : _a.decrease(); + } + setCanCallIntoJs(value) { + this._canCallIntoJs = value; + } + setStopping(value) { + this._isStopping = value; + } + canCallIntoJs() { + return this._canCallIntoJs && !this._isStopping; + } + destroy() { + this.setStopping(true); + this.setCanCallIntoJs(false); + this.runCleanup(); + } +} +let defaultContext; +function createContext(options) { + return new Context(options); +} +function getDefaultContext() { + if (!defaultContext) { + defaultContext = createContext(); + } + return defaultContext; +} + +exports.ConstHandle = ConstHandle; +exports.Context = Context; +exports.Deferred = Deferred; +exports.EmnapiError = EmnapiError; +exports.Env = Env; +exports.External = External; +exports.Finalizer = Finalizer; +exports.Handle = Handle; +exports.HandleScope = HandleScope; +exports.HandleStore = HandleStore; +exports.NAPI_VERSION_EXPERIMENTAL = NAPI_VERSION_EXPERIMENTAL; +exports.NODE_API_DEFAULT_MODULE_API_VERSION = NODE_API_DEFAULT_MODULE_API_VERSION; +exports.NODE_API_SUPPORTED_VERSION_MAX = NODE_API_SUPPORTED_VERSION_MAX; +exports.NODE_API_SUPPORTED_VERSION_MIN = NODE_API_SUPPORTED_VERSION_MIN; +exports.NodeEnv = NodeEnv; +exports.NotSupportBufferError = NotSupportBufferError; +exports.NotSupportWeakRefError = NotSupportWeakRefError; +exports.Persistent = Persistent; +exports.RefTracker = RefTracker; +exports.Reference = Reference; +exports.ReferenceWithData = ReferenceWithData; +exports.ReferenceWithFinalizer = ReferenceWithFinalizer; +exports.ScopeStore = ScopeStore; +exports.Store = Store; +exports.TrackedFinalizer = TrackedFinalizer; +exports.TryCatch = TryCatch; +exports.createContext = createContext; +exports.getDefaultContext = getDefaultContext; +exports.getExternalValue = getExternalValue; +exports.isExternal = isExternal; +exports.isReferenceType = isReferenceType; +exports.version = version; diff --git a/dg-ui/node_modules/@tailwindcss/oxide-wasm32-wasi/node_modules/@emnapi/runtime/dist/emnapi.cjs.min.d.ts b/dg-ui/node_modules/@tailwindcss/oxide-wasm32-wasi/node_modules/@emnapi/runtime/dist/emnapi.cjs.min.d.ts new file mode 100644 index 0000000..482aec2 --- /dev/null +++ b/dg-ui/node_modules/@tailwindcss/oxide-wasm32-wasi/node_modules/@emnapi/runtime/dist/emnapi.cjs.min.d.ts @@ -0,0 +1,671 @@ +export declare type Ptr = number | bigint + +export declare interface IBuffer extends Uint8Array {} +export declare interface BufferCtor { + readonly prototype: IBuffer + /** @deprecated */ + new (...args: any[]): IBuffer + from: { + (buffer: ArrayBufferLike): IBuffer + (buffer: ArrayBufferLike, byteOffset: number, length: number): IBuffer + } + alloc: (size: number) => IBuffer + isBuffer: (obj: unknown) => obj is IBuffer +} + +export declare const enum GlobalHandle { + UNDEFINED = 1, + NULL, + FALSE, + TRUE, + GLOBAL +} + +export declare const enum Version { + NODE_API_SUPPORTED_VERSION_MIN = 1, + NODE_API_DEFAULT_MODULE_API_VERSION = 8, + NODE_API_SUPPORTED_VERSION_MAX = 10, + NAPI_VERSION_EXPERIMENTAL = 2147483647 // INT_MAX +} +// eslint-disable-next-line @typescript-eslint/no-unused-vars +export declare type Pointer = number +// eslint-disable-next-line @typescript-eslint/no-unused-vars +export declare type PointerPointer = number +export declare type FunctionPointer any> = Pointer +export declare type Const = T + +export declare type void_p = Pointer +export declare type void_pp = Pointer +export declare type bool = number +export declare type char = number +export declare type char_p = Pointer +export declare type unsigned_char = number +export declare type const_char = Const +export declare type const_char_p = Pointer +export declare type char16_t_p = number +export declare type const_char16_t_p = number + +export declare type short = number +export declare type unsigned_short = number +export declare type int = number +export declare type unsigned_int = number +export declare type long = number +export declare type unsigned_long = number +export declare type long_long = bigint +export declare type unsigned_long_long = bigint +export declare type float = number +export declare type double = number +export declare type long_double = number +export declare type size_t = number + +export declare type int8_t = number +export declare type uint8_t = number +export declare type int16_t = number +export declare type uint16_t = number +export declare type int32_t = number +export declare type uint32_t = number +export declare type int64_t = bigint +export declare type uint64_t = bigint +export declare type napi_env = Pointer + +export declare type napi_value = Pointer +export declare type napi_ref = Pointer +export declare type napi_deferred = Pointer +export declare type napi_handle_scope = Pointer +export declare type napi_escapable_handle_scope = Pointer + +export declare type napi_addon_register_func = FunctionPointer<(env: napi_env, exports: napi_value) => napi_value> + +export declare type napi_callback_info = Pointer +export declare type napi_callback = FunctionPointer<(env: napi_env, info: napi_callback_info) => napi_value> + +export declare interface napi_extended_error_info { + error_message: const_char_p + engine_reserved: void_p + engine_error_code: uint32_t + error_code: napi_status +} + +export declare interface napi_property_descriptor { + // One of utf8name or name should be NULL. + utf8name: const_char_p + name: napi_value + + method: napi_callback + getter: napi_callback + setter: napi_callback + value: napi_value + /* napi_property_attributes */ + attributes: number + data: void_p +} + +export declare type napi_finalize = FunctionPointer<( + env: napi_env, + finalize_data: void_p, + finalize_hint: void_p +) => void> + +export declare interface node_module { + nm_version: int32_t + nm_flags: uint32_t + nm_filename: Pointer + nm_register_func: napi_addon_register_func + nm_modname: Pointer + nm_priv: Pointer + reserved: PointerPointer +} + +export declare interface napi_node_version { + major: uint32_t + minor: uint32_t + patch: uint32_t + release: const_char_p +} + +export declare interface emnapi_emscripten_version { + major: uint32_t + minor: uint32_t + patch: uint32_t +} + +export declare const enum napi_status { + napi_ok, + napi_invalid_arg, + napi_object_expected, + napi_string_expected, + napi_name_expected, + napi_function_expected, + napi_number_expected, + napi_boolean_expected, + napi_array_expected, + napi_generic_failure, + napi_pending_exception, + napi_cancelled, + napi_escape_called_twice, + napi_handle_scope_mismatch, + napi_callback_scope_mismatch, + napi_queue_full, + napi_closing, + napi_bigint_expected, + napi_date_expected, + napi_arraybuffer_expected, + napi_detachable_arraybuffer_expected, + napi_would_deadlock, // unused + napi_no_external_buffers_allowed, + napi_cannot_run_js +} + +export declare const enum napi_property_attributes { + napi_default = 0, + napi_writable = 1 << 0, + napi_enumerable = 1 << 1, + napi_configurable = 1 << 2, + + // Used with napi_define_class to distinguish static properties + // from instance properties. Ignored by napi_define_properties. + napi_static = 1 << 10, + + /// #ifdef NAPI_EXPERIMENTAL + // Default for class methods. + napi_default_method = napi_writable | napi_configurable, + + // Default for object properties, like in JS obj[prop]. + napi_default_jsproperty = napi_writable | napi_enumerable | napi_configurable + /// #endif // NAPI_EXPERIMENTAL +} + +export declare const enum napi_valuetype { + napi_undefined, + napi_null, + napi_boolean, + napi_number, + napi_string, + napi_symbol, + napi_object, + napi_function, + napi_external, + napi_bigint +} + +export declare const enum napi_typedarray_type { + napi_int8_array, + napi_uint8_array, + napi_uint8_clamped_array, + napi_int16_array, + napi_uint16_array, + napi_int32_array, + napi_uint32_array, + napi_float32_array, + napi_float64_array, + napi_bigint64_array, + napi_biguint64_array, + napi_float16_array, +} + +export declare const enum napi_key_collection_mode { + napi_key_include_prototypes, + napi_key_own_only +} + +export declare const enum napi_key_filter { + napi_key_all_properties = 0, + napi_key_writable = 1, + napi_key_enumerable = 1 << 1, + napi_key_configurable = 1 << 2, + napi_key_skip_strings = 1 << 3, + napi_key_skip_symbols = 1 << 4 +} + +export declare const enum napi_key_conversion { + napi_key_keep_numbers, + napi_key_numbers_to_strings +} + +export declare const enum emnapi_memory_view_type { + emnapi_int8_array, + emnapi_uint8_array, + emnapi_uint8_clamped_array, + emnapi_int16_array, + emnapi_uint16_array, + emnapi_int32_array, + emnapi_uint32_array, + emnapi_float32_array, + emnapi_float64_array, + emnapi_bigint64_array, + emnapi_biguint64_array, + emnapi_float16_array, + emnapi_data_view = -1, + emnapi_buffer = -2 +} + +export declare const enum napi_threadsafe_function_call_mode { + napi_tsfn_nonblocking, + napi_tsfn_blocking +} + +export declare const enum napi_threadsafe_function_release_mode { + napi_tsfn_release, + napi_tsfn_abort +} +export declare type CleanupHookCallbackFunction = number | ((arg: number) => void); + +export declare class ConstHandle extends Handle { + constructor(id: number, value: S); + dispose(): void; +} + +export declare class Context { + private _isStopping; + private _canCallIntoJs; + private _suppressDestroy; + envStore: Store; + scopeStore: ScopeStore; + refStore: Store; + deferredStore: Store>; + handleStore: HandleStore; + private readonly refCounter?; + private readonly cleanupQueue; + private readonly _externalMemory; + feature: { + supportReflect: boolean; + supportFinalizer: boolean; + supportWeakSymbol: boolean; + supportBigInt: boolean; + supportNewFunction: boolean; + canSetFunctionName: boolean; + setImmediate: (callback: () => void) => void; + Buffer: BufferCtor | undefined; + MessageChannel: { + new (): MessageChannel; + prototype: MessageChannel; + } | undefined; + }; + constructor(options?: ContextOptions); + /** + * Suppress the destroy on `beforeExit` event in Node.js. + * Call this method if you want to keep the context and + * all associated {@link Env | Env} alive, + * this also means that cleanup hooks will not be called. + * After call this method, you should call + * {@link Context.destroy | `Context.prototype.destroy`} method manually. + */ + suppressDestroy(): void; + getRuntimeVersions(): { + version: string; + NODE_API_SUPPORTED_VERSION_MAX: Version; + NAPI_VERSION_EXPERIMENTAL: Version; + NODE_API_DEFAULT_MODULE_API_VERSION: Version; + }; + createNotSupportWeakRefError(api: string, message: string): NotSupportWeakRefError; + createNotSupportBufferError(api: string, message: string): NotSupportBufferError; + createReference(envObject: Env, handle_id: napi_value, initialRefcount: uint32_t, ownership: ReferenceOwnership): Reference; + createReferenceWithData(envObject: Env, handle_id: napi_value, initialRefcount: uint32_t, ownership: ReferenceOwnership, data: void_p): Reference; + createReferenceWithFinalizer(envObject: Env, handle_id: napi_value, initialRefcount: uint32_t, ownership: ReferenceOwnership, finalize_callback?: napi_finalize, finalize_data?: void_p, finalize_hint?: void_p): Reference; + createDeferred(value: IDeferrdValue): Deferred; + adjustAmountOfExternalAllocatedMemory(changeInBytes: number | bigint): bigint; + createEnv(filename: string, moduleApiVersion: number, makeDynCall_vppp: (cb: Ptr) => (a: Ptr, b: Ptr, c: Ptr) => void, makeDynCall_vp: (cb: Ptr) => (a: Ptr) => void, abort: (msg?: string) => never, nodeBinding?: any): Env; + createTrackedFinalizer(envObject: Env, finalize_callback: napi_finalize, finalize_data: void_p, finalize_hint: void_p): TrackedFinalizer; + getCurrentScope(): HandleScope | null; + addToCurrentScope(value: V): Handle; + openScope(envObject?: Env): HandleScope; + closeScope(envObject?: Env, _scope?: HandleScope): void; + ensureHandle(value: S): Handle; + addCleanupHook(envObject: Env, fn: CleanupHookCallbackFunction, arg: number): void; + removeCleanupHook(envObject: Env, fn: CleanupHookCallbackFunction, arg: number): void; + runCleanup(): void; + increaseWaitingRequestCounter(): void; + decreaseWaitingRequestCounter(): void; + setCanCallIntoJs(value: boolean): void; + setStopping(value: boolean): void; + canCallIntoJs(): boolean; + /** + * Destroy the context and call cleanup hooks. + * Associated {@link Env | Env} will be destroyed. + */ + destroy(): void; +} + +export declare interface ContextOptions { + onExternalMemoryChange?: (current: bigint, old: bigint, delta: bigint) => any; +} + +export declare function createContext(options?: ContextOptions): Context; + +export declare class Deferred implements IStoreValue { + static create(ctx: Context, value: IDeferrdValue): Deferred; + id: number; + ctx: Context; + value: IDeferrdValue; + constructor(ctx: Context, value: IDeferrdValue); + resolve(value: T): void; + reject(reason?: any): void; + dispose(): void; +} + +export declare class EmnapiError extends Error { + constructor(message?: string); +} + +export declare abstract class Env implements IStoreValue { + readonly ctx: Context; + moduleApiVersion: number; + makeDynCall_vppp: (cb: Ptr) => (a: Ptr, b: Ptr, c: Ptr) => void; + makeDynCall_vp: (cb: Ptr) => (a: Ptr) => void; + abort: (msg?: string) => never; + id: number; + openHandleScopes: number; + instanceData: TrackedFinalizer | null; + tryCatch: TryCatch; + refs: number; + reflist: RefTracker; + finalizing_reflist: RefTracker; + pendingFinalizers: RefTracker[]; + lastError: { + errorCode: napi_status; + engineErrorCode: number; + engineReserved: Ptr; + }; + inGcFinalizer: boolean; + constructor(ctx: Context, moduleApiVersion: number, makeDynCall_vppp: (cb: Ptr) => (a: Ptr, b: Ptr, c: Ptr) => void, makeDynCall_vp: (cb: Ptr) => (a: Ptr) => void, abort: (msg?: string) => never); + /** @virtual */ + canCallIntoJs(): boolean; + terminatedOrTerminating(): boolean; + ref(): void; + unref(): void; + ensureHandle(value: S): Handle; + ensureHandleId(value: any): napi_value; + clearLastError(): napi_status; + setLastError(error_code: napi_status, engine_error_code?: uint32_t, engine_reserved?: void_p): napi_status; + getReturnStatus(): napi_status; + callIntoModule(fn: (env: Env) => T, handleException?: (envObject: Env, value: any) => void): T; + /** @virtual */ + abstract callFinalizer(cb: napi_finalize, data: void_p, hint: void_p): void; + invokeFinalizerFromGC(finalizer: RefTracker): void; + checkGCAccess(): void; + /** @virtual */ + enqueueFinalizer(finalizer: RefTracker): void; + /** @virtual */ + dequeueFinalizer(finalizer: RefTracker): void; + /** @virtual */ + deleteMe(): void; + dispose(): void; + private readonly _bindingMap; + initObjectBinding(value: S): IReferenceBinding; + getObjectBinding(value: S): IReferenceBinding; + setInstanceData(data: number, finalize_cb: number, finalize_hint: number): void; + getInstanceData(): number; +} + +/** @public */ +declare interface External_2 extends Record { +} + +/** @public */ +declare const External_2: { + new (value: number | bigint): External_2; + prototype: null; +}; +export { External_2 as External } + +export declare class Finalizer { + envObject: Env; + private _finalizeCallback; + private _finalizeData; + private _finalizeHint; + private _makeDynCall_vppp; + constructor(envObject: Env, _finalizeCallback?: napi_finalize, _finalizeData?: void_p, _finalizeHint?: void_p); + callback(): napi_finalize; + data(): void_p; + hint(): void_p; + resetEnv(): void; + resetFinalizer(): void; + callFinalizer(): void; + dispose(): void; +} + +export declare function getDefaultContext(): Context; + +/** @public */ +export declare function getExternalValue(external: External_2): number | bigint; + +export declare class Handle { + id: number; + value: S; + constructor(id: number, value: S); + data(): void_p; + isNumber(): boolean; + isBigInt(): boolean; + isString(): boolean; + isFunction(): boolean; + isExternal(): boolean; + isObject(): boolean; + isArray(): boolean; + isArrayBuffer(): boolean; + isTypedArray(): boolean; + isBuffer(BufferConstructor?: BufferCtor): boolean; + isDataView(): boolean; + isDate(): boolean; + isPromise(): boolean; + isBoolean(): boolean; + isUndefined(): boolean; + isSymbol(): boolean; + isNull(): boolean; + dispose(): void; +} + +export declare class HandleScope { + handleStore: HandleStore; + id: number; + parent: HandleScope | null; + child: HandleScope | null; + start: number; + end: number; + private _escapeCalled; + callbackInfo: ICallbackInfo; + constructor(handleStore: HandleStore, id: number, parentScope: HandleScope | null, start: number, end?: number); + add(value: V): Handle; + addExternal(data: void_p): Handle; + dispose(): void; + escape(handle: number): Handle | null; + escapeCalled(): boolean; +} + +export declare class HandleStore { + static UNDEFINED: ConstHandle; + static NULL: ConstHandle; + static FALSE: ConstHandle; + static TRUE: ConstHandle; + static GLOBAL: ConstHandle; + static MIN_ID: 6; + private readonly _values; + private _next; + push(value: S): Handle; + erase(start: number, end: number): void; + get(id: Ptr): Handle | undefined; + swap(a: number, b: number): void; + dispose(): void; +} + +export declare interface ICallbackInfo { + thiz: any; + data: void_p; + args: ArrayLike; + fn: Function; +} + +export declare interface IDeferrdValue { + resolve: (value: T) => void; + reject: (reason?: any) => void; +} + +export declare interface IReferenceBinding { + wrapped: number; + tag: Uint32Array | null; +} + +/** @public */ +export declare function isExternal(object: unknown): object is External_2; + +export declare function isReferenceType(v: any): v is object; + +export declare interface IStoreValue { + id: number; + dispose(): void; + [x: string]: any; +} + +export declare const NAPI_VERSION_EXPERIMENTAL = Version.NAPI_VERSION_EXPERIMENTAL; + +export declare const NODE_API_DEFAULT_MODULE_API_VERSION = Version.NODE_API_DEFAULT_MODULE_API_VERSION; + +export declare const NODE_API_SUPPORTED_VERSION_MAX = Version.NODE_API_SUPPORTED_VERSION_MAX; + +export declare const NODE_API_SUPPORTED_VERSION_MIN = Version.NODE_API_SUPPORTED_VERSION_MIN; + +export declare class NodeEnv extends Env { + filename: string; + private readonly nodeBinding?; + destructing: boolean; + finalizationScheduled: boolean; + constructor(ctx: Context, filename: string, moduleApiVersion: number, makeDynCall_vppp: (cb: Ptr) => (a: Ptr, b: Ptr, c: Ptr) => void, makeDynCall_vp: (cb: Ptr) => (a: Ptr) => void, abort: (msg?: string) => never, nodeBinding?: any); + deleteMe(): void; + canCallIntoJs(): boolean; + triggerFatalException(err: any): void; + callbackIntoModule(enforceUncaughtExceptionPolicy: boolean, fn: (env: Env) => T): T; + callFinalizer(cb: napi_finalize, data: void_p, hint: void_p): void; + callFinalizerInternal(forceUncaught: int, cb: napi_finalize, data: void_p, hint: void_p): void; + enqueueFinalizer(finalizer: RefTracker): void; + drainFinalizerQueue(): void; +} + +export declare class NotSupportBufferError extends EmnapiError { + constructor(api: string, message: string); +} + +export declare class NotSupportWeakRefError extends EmnapiError { + constructor(api: string, message: string); +} + +export declare class Persistent { + private _ref; + private _param; + private _callback; + private static readonly _registry; + constructor(value: T); + setWeak

(param: P, callback: (param: P) => void): void; + clearWeak(): void; + reset(): void; + isEmpty(): boolean; + deref(): T | undefined; +} + +export declare class Reference extends RefTracker implements IStoreValue { + private static weakCallback; + id: number; + envObject: Env; + private readonly canBeWeak; + private _refcount; + private readonly _ownership; + persistent: Persistent; + static create(envObject: Env, handle_id: napi_value, initialRefcount: uint32_t, ownership: ReferenceOwnership, _unused1?: void_p, _unused2?: void_p, _unused3?: void_p): Reference; + protected constructor(envObject: Env, handle_id: napi_value, initialRefcount: uint32_t, ownership: ReferenceOwnership); + ref(): number; + unref(): number; + get(envObject?: Env): napi_value; + /** @virtual */ + resetFinalizer(): void; + /** @virtual */ + data(): void_p; + refcount(): number; + ownership(): ReferenceOwnership; + /** @virtual */ + protected callUserFinalizer(): void; + /** @virtual */ + protected invokeFinalizerFromGC(): void; + private _setWeak; + finalize(): void; + dispose(): void; +} + +export declare enum ReferenceOwnership { + kRuntime = 0, + kUserland = 1 +} + +export declare class ReferenceWithData extends Reference { + private readonly _data; + static create(envObject: Env, value: napi_value, initialRefcount: uint32_t, ownership: ReferenceOwnership, data: void_p): ReferenceWithData; + private constructor(); + data(): void_p; +} + +export declare class ReferenceWithFinalizer extends Reference { + private _finalizer; + static create(envObject: Env, value: napi_value, initialRefcount: uint32_t, ownership: ReferenceOwnership, finalize_callback: napi_finalize, finalize_data: void_p, finalize_hint: void_p): ReferenceWithFinalizer; + private constructor(); + resetFinalizer(): void; + data(): void_p; + protected callUserFinalizer(): void; + protected invokeFinalizerFromGC(): void; + dispose(): void; +} + +export declare class RefTracker { + /** @virtual */ + dispose(): void; + /** @virtual */ + finalize(): void; + private _next; + private _prev; + link(list: RefTracker): void; + unlink(): void; + static finalizeAll(list: RefTracker): void; +} + +export declare class ScopeStore { + private readonly _rootScope; + currentScope: HandleScope; + private readonly _values; + constructor(); + get(id: number): HandleScope | undefined; + openScope(handleStore: HandleStore): HandleScope; + closeScope(): void; + dispose(): void; +} + +export declare class Store { + protected _values: Array; + private _freeList; + private _size; + constructor(); + add(value: V): void; + get(id: Ptr): V | undefined; + has(id: Ptr): boolean; + remove(id: Ptr): void; + dispose(): void; +} + +export declare class TrackedFinalizer extends RefTracker { + private _finalizer; + static create(envObject: Env, finalize_callback: napi_finalize, finalize_data: void_p, finalize_hint: void_p): TrackedFinalizer; + private constructor(); + data(): void_p; + dispose(): void; + finalize(): void; +} + +export declare class TryCatch { + private _exception; + private _caught; + isEmpty(): boolean; + hasCaught(): boolean; + exception(): any; + setError(err: any): void; + reset(): void; + extractException(): any; +} + +export declare const version: string; + +export { } diff --git a/dg-ui/node_modules/@tailwindcss/oxide-wasm32-wasi/node_modules/@emnapi/runtime/dist/emnapi.cjs.min.js b/dg-ui/node_modules/@tailwindcss/oxide-wasm32-wasi/node_modules/@emnapi/runtime/dist/emnapi.cjs.min.js new file mode 100644 index 0000000..32aaf71 --- /dev/null +++ b/dg-ui/node_modules/@tailwindcss/oxide-wasm32-wasi/node_modules/@emnapi/runtime/dist/emnapi.cjs.min.js @@ -0,0 +1 @@ +const e=new WeakMap;function t(t){return e.has(t)}const i=(()=>{function t(t){Object.setPrototypeOf(this,null),e.set(this,t)}return t.prototype=null,t})();function s(i){if(!t(i))throw new TypeError("not external");return e.get(i)}const n=function(){let e;try{e=new Function}catch(e){return!1}return"function"==typeof e}(),r=function(){if("undefined"!=typeof globalThis)return globalThis;let e=function(){return this}();if(!e&&n)try{e=new Function("return this")()}catch(e){}if(!e){if("undefined"==typeof __webpack_public_path__&&"undefined"!=typeof global)return global;if("undefined"!=typeof window)return window;if("undefined"!=typeof self)return self}return e}();class o{constructor(){this._exception=void 0,this._caught=!1}isEmpty(){return!this._caught}hasCaught(){return this._caught}exception(){return this._exception}setError(e){this._caught=!0,this._exception=e}reset(){this._caught=!1,this._exception=void 0}extractException(){const e=this._exception;return this.reset(),e}}const a=function(){var e;try{return Boolean(null===(e=Object.getOwnPropertyDescriptor(Function.prototype,"name"))||void 0===e?void 0:e.configurable)}catch(e){return!1}}(),l="object"==typeof Reflect,c="undefined"!=typeof FinalizationRegistry&&"undefined"!=typeof WeakRef,u=function(){try{const e=Symbol();new WeakRef(e),(new WeakMap).set(e,void 0)}catch(e){return!1}return!0}(),h="undefined"!=typeof BigInt;const p=function(){let e;return e="undefined"!=typeof __webpack_public_path__||"undefined"!=typeof __webpack_public_path__?"undefined"!=typeof __non_webpack_require__?__non_webpack_require__:void 0:"undefined"!=typeof require?require:void 0,e}(),f="function"==typeof MessageChannel?MessageChannel:function(){try{return p("worker_threads").MessageChannel}catch(e){}}(),d="function"==typeof setImmediate?setImmediate.bind(r):function(e){if("function"!=typeof e)throw new TypeError('The "callback" argument must be of type function');if(f){let t=new f;t.port1.onmessage=function(){t.port1.onmessage=null,t=void 0,e()},t.port2.postMessage(null)}else setTimeout(e,0)},_="function"==typeof Buffer?Buffer:function(){try{return p("buffer").Buffer}catch(e){}}(),v="1.11.3",g=2147483647;class y{constructor(e,t){this.id=e,this.value=t}data(){return s(this.value)}isNumber(){return"number"==typeof this.value}isBigInt(){return"bigint"==typeof this.value}isString(){return"string"==typeof this.value}isFunction(){return"function"==typeof this.value}isExternal(){return t(this.value)}isObject(){return"object"==typeof this.value&&null!==this.value}isArray(){return Array.isArray(this.value)}isArrayBuffer(){return this.value instanceof ArrayBuffer}isTypedArray(){return ArrayBuffer.isView(this.value)&&!(this.value instanceof DataView)}isBuffer(e){return!!ArrayBuffer.isView(this.value)||(null!=e||(e=_),"function"==typeof e&&e.isBuffer(this.value))}isDataView(){return this.value instanceof DataView}isDate(){return this.value instanceof Date}isPromise(){return this.value instanceof Promise}isBoolean(){return"boolean"==typeof this.value}isUndefined(){return void 0===this.value}isSymbol(){return"symbol"==typeof this.value}isNull(){return null===this.value}dispose(){this.value=void 0}}class x extends y{constructor(e,t){super(e,t)}dispose(){}}class b{constructor(){this._values=[void 0,b.UNDEFINED,b.NULL,b.FALSE,b.TRUE,b.GLOBAL],this._next=b.MIN_ID}push(e){let t;const i=this._next,s=this._values;return i=this.end)return null;this.handleStore.swap(e,this.start);const t=this.handleStore.get(this.start);return this.start++,this.parent.end++,t}escapeCalled(){return this._escapeCalled}}class w{constructor(){this._rootScope=new z(null,0,null,1,b.MIN_ID),this.currentScope=this._rootScope,this._values=[void 0]}get(e){return this._values[e]}openScope(e){const t=this.currentScope;let i=t.child;if(null!==i)i.start=i.end=t.end;else{const s=t.id+1;i=new z(e,s,t,t.end),this._values[s]=i}return this.currentScope=i,i}closeScope(){const e=this.currentScope;this.currentScope=e.parent,e.dispose()}dispose(){this.currentScope=this._rootScope,this._values.length=1}}class k{constructor(){this._next=null,this._prev=null}dispose(){}finalize(){}link(e){this._prev=e,this._next=e._next,null!==this._next&&(this._next._prev=this),e._next=this}unlink(){null!==this._prev&&(this._prev._next=this._next),null!==this._next&&(this._next._prev=this._prev),this._prev=null,this._next=null}static finalizeAll(e){for(;null!==e._next;)e._next.finalize()}}class m{constructor(e,t=0,i=0,s=0){this.envObject=e,this._finalizeCallback=t,this._finalizeData=i,this._finalizeHint=s,this._makeDynCall_vppp=e.makeDynCall_vppp}callback(){return this._finalizeCallback}data(){return this._finalizeData}hint(){return this._finalizeHint}resetEnv(){this.envObject=void 0}resetFinalizer(){this._finalizeCallback=0,this._finalizeData=0,this._finalizeHint=0}callFinalizer(){const e=this._finalizeCallback,t=this._finalizeData,i=this._finalizeHint;if(this.resetFinalizer(),!e)return;const s=Number(e);this.envObject?this.envObject.callFinalizer(s,t,i):this._makeDynCall_vppp(s)(0,t,i)}dispose(){this.envObject=void 0,this._makeDynCall_vppp=void 0}}class E extends k{static create(e,t,i,s){const n=new E(e,t,i,s);return n.link(e.finalizing_reflist),n}constructor(e,t,i,s){super(),this._finalizer=new m(e,t,i,s)}data(){return this._finalizer.data()}dispose(){this._finalizer&&(this.unlink(),this._finalizer.envObject.dequeueFinalizer(this),this._finalizer.dispose(),this._finalizer=void 0,super.dispose())}finalize(){let e;this.unlink();let t=!1;try{this._finalizer.callFinalizer()}catch(i){t=!0,e=i}if(this.dispose(),t)throw e}}function S(e,t){if(!e.terminatedOrTerminating())throw t}class C{constructor(e,t,i,s,n){this.ctx=e,this.moduleApiVersion=t,this.makeDynCall_vppp=i,this.makeDynCall_vp=s,this.abort=n,this.openHandleScopes=0,this.instanceData=null,this.tryCatch=new o,this.refs=1,this.reflist=new k,this.finalizing_reflist=new k,this.pendingFinalizers=[],this.lastError={errorCode:0,engineErrorCode:0,engineReserved:0},this.inGcFinalizer=!1,this._bindingMap=new WeakMap,this.id=0}canCallIntoJs(){return!0}terminatedOrTerminating(){return!this.canCallIntoJs()}ref(){this.refs++}unref(){this.refs--,0===this.refs&&this.dispose()}ensureHandle(e){return this.ctx.ensureHandle(e)}ensureHandleId(e){return this.ensureHandle(e).id}clearLastError(){const e=this.lastError;return 0!==e.errorCode&&(e.errorCode=0),0!==e.engineErrorCode&&(e.engineErrorCode=0),0!==e.engineReserved&&(e.engineReserved=0),0}setLastError(e,t=0,i=0){const s=this.lastError;return s.errorCode!==e&&(s.errorCode=e),s.engineErrorCode!==t&&(s.engineErrorCode=t),s.engineReserved!==i&&(s.engineReserved=i),e}getReturnStatus(){return this.tryCatch.hasCaught()?this.setLastError(10):0}callIntoModule(e,t=S){const i=this.openHandleScopes;this.clearLastError();const s=e(this);if(i!==this.openHandleScopes&&this.abort("open_handle_scopes != open_handle_scopes_before"),this.tryCatch.hasCaught()){t(this,this.tryCatch.extractException())}return s}invokeFinalizerFromGC(e){if(this.moduleApiVersion!==g)this.enqueueFinalizer(e);else{const t=this.inGcFinalizer;this.inGcFinalizer=!0;try{e.finalize()}finally{this.inGcFinalizer=t}}}checkGCAccess(){this.moduleApiVersion===g&&this.inGcFinalizer&&this.abort("Finalizer is calling a function that may affect GC state.\nThe finalizers are run directly from GC and must not affect GC state.\nUse `node_api_post_finalizer` from inside of the finalizer to work around this issue.\nIt schedules the call as a new task in the event loop.")}enqueueFinalizer(e){-1===this.pendingFinalizers.indexOf(e)&&this.pendingFinalizers.push(e)}dequeueFinalizer(e){const t=this.pendingFinalizers.indexOf(e);-1!==t&&this.pendingFinalizers.splice(t,1)}deleteMe(){k.finalizeAll(this.finalizing_reflist),k.finalizeAll(this.reflist),this.tryCatch.extractException(),this.ctx.envStore.remove(this.id)}dispose(){0!==this.id&&(this.deleteMe(),this.finalizing_reflist.dispose(),this.reflist.dispose(),this.id=0)}initObjectBinding(e){const t={wrapped:0,tag:null};return this._bindingMap.set(e,t),t}getObjectBinding(e){return this._bindingMap.has(e)?this._bindingMap.get(e):this.initObjectBinding(e)}setInstanceData(e,t,i){this.instanceData&&this.instanceData.dispose(),this.instanceData=E.create(this,t,e,i)}getInstanceData(){return this.instanceData?this.instanceData.data():0}}class F extends C{constructor(e,t,i,s,n,r,o){super(e,i,s,n,r),this.filename=t,this.nodeBinding=o,this.destructing=!1,this.finalizationScheduled=!1}deleteMe(){this.destructing=!0,this.drainFinalizerQueue(),super.deleteMe()}canCallIntoJs(){return super.canCallIntoJs()&&this.ctx.canCallIntoJs()}triggerFatalException(e){if(this.nodeBinding)this.nodeBinding.napi.fatalException(e);else{if("object"!=typeof process||null===process||"function"!=typeof process._fatalException)throw e;process._fatalException(e)||(console.error(e),process.exit(1))}}callbackIntoModule(e,t){return this.callIntoModule(t,(t,i)=>{if(t.terminatedOrTerminating())return;const s="object"==typeof process&&null!==process,n=!!s&&Boolean(process.execArgv&&-1!==process.execArgv.indexOf("--force-node-api-uncaught-exceptions-policy"));if(t.moduleApiVersion<10&&!n&&!e){return void(s&&"function"==typeof process.emitWarning?process.emitWarning:function(e,t,i){if(e instanceof Error)console.warn(e.toString());else{const s=i?`[${i}] `:"";console.warn(`${s}${t||"Warning"}: ${e}`)}})("Uncaught Node-API callback exception detected, please run node with option --force-node-api-uncaught-exceptions-policy=true to handle those exceptions properly.","DeprecationWarning","DEP0168")}t.triggerFatalException(i)})}callFinalizer(e,t,i){this.callFinalizerInternal(1,e,t,i)}callFinalizerInternal(e,t,i,s){const n=this.makeDynCall_vppp(t),r=this.id,o=this.ctx.openScope(this);try{this.callbackIntoModule(Boolean(e),()=>{n(r,i,s)})}finally{this.ctx.closeScope(this,o)}}enqueueFinalizer(e){super.enqueueFinalizer(e),this.finalizationScheduled||this.destructing||(this.finalizationScheduled=!0,this.ref(),d(()=>{this.finalizationScheduled=!1,this.unref(),this.drainFinalizerQueue()}))}drainFinalizerQueue(){for(;this.pendingFinalizers.length>0;){this.pendingFinalizers.shift().finalize()}}}function I(e,t,i,s,n,r,o){(i="number"!=typeof i?8:i)<8?i=8:i>10&&i!==g&&function(e,t){throw new Error(`${e} requires Node-API version ${t}, but this version of Node.js only supports version 10 add-ons.`)}(t,i);const a=new F(e,t,i,s,n,r,o);return e.envStore.add(a),e.addCleanupHook(a,()=>{a.unref()},0),a}class O extends Error{constructor(e){super(e);const t=new.target,i=t.prototype;if(!(this instanceof O)){const e=Object.setPrototypeOf;"function"==typeof e?e.call(Object,this,i):this.__proto__=i,"function"==typeof Error.captureStackTrace&&Error.captureStackTrace(this,t)}}}Object.defineProperty(O.prototype,"name",{configurable:!0,writable:!0,value:"EmnapiError"});class D extends O{constructor(e,t){super(`${e}: The current runtime does not support "FinalizationRegistry" and "WeakRef".${t?` ${t}`:""}`)}}Object.defineProperty(D.prototype,"name",{configurable:!0,writable:!0,value:"NotSupportWeakRefError"});class R extends O{constructor(e,t){super(`${e}: The current runtime does not support "Buffer". Consider using buffer polyfill to make sure \`globalThis.Buffer\` is defined.${t?` ${t}`:""}`)}}Object.defineProperty(R.prototype,"name",{configurable:!0,writable:!0,value:"NotSupportBufferError"});class N{constructor(e){this._value=e}deref(){return this._value}dispose(){this._value=void 0}}class A{constructor(e){this._ref=new N(e)}setWeak(e,t){if(!c||void 0===this._ref||this._ref instanceof WeakRef)return;const i=this._ref.deref();try{A._registry.register(i,this,this);const s=new WeakRef(i);this._ref.dispose(),this._ref=s,this._param=e,this._callback=t}catch(e){if("symbol"!=typeof i)throw e}}clearWeak(){if(c&&void 0!==this._ref&&this._ref instanceof WeakRef){try{A._registry.unregister(this)}catch(e){}this._param=void 0,this._callback=void 0;const e=this._ref.deref();this._ref=void 0===e?e:new N(e)}}reset(){if(c)try{A._registry.unregister(this)}catch(e){}this._param=void 0,this._callback=void 0,this._ref instanceof N&&this._ref.dispose(),this._ref=void 0}isEmpty(){return void 0===this._ref}deref(){if(void 0!==this._ref)return this._ref.deref()}}var H;A._registry=c?new FinalizationRegistry(e=>{e._ref=void 0;const t=e._callback,i=e._param;e._callback=void 0,e._param=void 0,"function"==typeof t&&t(i)}):void 0,exports.ReferenceOwnership=void 0,(H=exports.ReferenceOwnership||(exports.ReferenceOwnership={}))[H.kRuntime=0]="kRuntime",H[H.kUserland=1]="kUserland";class j extends k{static weakCallback(e){e.persistent.reset(),e.invokeFinalizerFromGC()}static create(e,t,i,s,n,r,o){const a=new j(e,t,i,s);return e.ctx.refStore.add(a),a.link(e.reflist),a}constructor(e,t,i,s){super(),this.envObject=e,this._refcount=i,this._ownership=s;const n=e.ctx.handleStore.get(t);var r;this.canBeWeak=(r=n).isObject()||r.isFunction()||r.isSymbol(),this.persistent=new A(n.value),this.id=0,0===i&&this._setWeak()}ref(){return this.persistent.isEmpty()?0:(1===++this._refcount&&this.canBeWeak&&this.persistent.clearWeak(),this._refcount)}unref(){return this.persistent.isEmpty()||0===this._refcount?0:(0===--this._refcount&&this._setWeak(),this._refcount)}get(e=this.envObject){if(this.persistent.isEmpty())return 0;const t=this.persistent.deref();return e.ensureHandle(t).id}resetFinalizer(){}data(){return 0}refcount(){return this._refcount}ownership(){return this._ownership}callUserFinalizer(){}invokeFinalizerFromGC(){this.finalize()}_setWeak(){this.canBeWeak?this.persistent.setWeak(this,j.weakCallback):this.persistent.reset()}finalize(){this.persistent.reset();const e=this._ownership===exports.ReferenceOwnership.kRuntime;this.unlink(),this.callUserFinalizer(),e&&this.dispose()}dispose(){0!==this.id&&(this.unlink(),this.persistent.reset(),this.envObject.ctx.refStore.remove(this.id),super.dispose(),this.envObject=void 0,this.id=0)}}class B extends j{static create(e,t,i,s,n){const r=new B(e,t,i,s,n);return e.ctx.refStore.add(r),r.link(e.reflist),r}constructor(e,t,i,s,n){super(e,t,i,s),this._data=n}data(){return this._data}}class M extends j{static create(e,t,i,s,n,r,o){const a=new M(e,t,i,s,n,r,o);return e.ctx.refStore.add(a),a.link(e.finalizing_reflist),a}constructor(e,t,i,s,n,r,o){super(e,t,i,s),this._finalizer=new m(e,n,r,o)}resetFinalizer(){this._finalizer.resetFinalizer()}data(){return this._finalizer.data()}callUserFinalizer(){this._finalizer.callFinalizer()}invokeFinalizerFromGC(){this._finalizer.envObject.invokeFinalizerFromGC(this)}dispose(){this._finalizer&&(this._finalizer.envObject.dequeueFinalizer(this),this._finalizer.dispose(),super.dispose(),this._finalizer=void 0)}}class T{static create(e,t){const i=new T(e,t);return e.deferredStore.add(i),i}constructor(e,t){Object.defineProperties(this,{id:{configurable:!0,enumerable:!0,value:0,writable:!0},ctx:{configurable:!0,enumerable:!0,value:e,writable:!0},value:{configurable:!0,enumerable:!0,value:t,writable:!0}})}resolve(e){this.value.resolve(e),this.dispose()}reject(e){this.value.reject(e),this.dispose()}dispose(){this.ctx.deferredStore.remove(this.id),this.id=0,this.value=null,this.ctx=null}}class W{constructor(){this._values=[void 0],this._values.length=4,this._size=1,this._freeList=[]}add(e){let t;if(this._freeList.length)t=this._freeList.shift();else{t=this._size,this._size++;const e=this._values.length;t>=e&&(this._values.length=e+(e>>1)+16)}e.id=t,this._values[t]=e}get(e){return this._values[e]}has(e){return void 0!==this._values[e]}remove(e){const t=this._values[e];t&&(t.id=0,this._values[e]=void 0,this._freeList.push(Number(e)))}dispose(){for(let e=1;es.envObject===e&&s.fn===t&&s.arg===i).length>0)throw new Error("Can not add same fn and arg twice");this._cleanupHooks.push(new V(e,t,i,this._cleanupHookCounter++))}remove(e,t,i){for(let s=0;st.order-e.order);for(let t=0;t{this._suppressDestroy||this.destroy()}))}suppressDestroy(){this._suppressDestroy=!0}getRuntimeVersions(){return{version:v,NODE_API_SUPPORTED_VERSION_MAX:10,NAPI_VERSION_EXPERIMENTAL:g,NODE_API_DEFAULT_MODULE_API_VERSION:8}}createNotSupportWeakRefError(e,t){return new D(e,t)}createNotSupportBufferError(e,t){return new R(e,t)}createReference(e,t,i,s){return j.create(e,t,i,s)}createReferenceWithData(e,t,i,s,n){return B.create(e,t,i,s,n)}createReferenceWithFinalizer(e,t,i,s,n=0,r=0,o=0){return M.create(e,t,i,s,n,r,o)}createDeferred(e){return T.create(this,e)}adjustAmountOfExternalAllocatedMemory(e){return this._externalMemory.adjust(e)}createEnv(e,t,i,s,n,r){return I(this,e,t,i,s,n,r)}createTrackedFinalizer(e,t,i,s){return E.create(e,t,i,s)}getCurrentScope(){return this.scopeStore.currentScope}addToCurrentScope(e){return this.scopeStore.currentScope.add(e)}openScope(e){const t=this.scopeStore.openScope(this.handleStore);return e&&e.openHandleScopes++,t}closeScope(e,t){e&&0===e.openHandleScopes||(this.scopeStore.closeScope(),e&&e.openHandleScopes--)}ensureHandle(e){switch(e){case void 0:return b.UNDEFINED;case null:return b.NULL;case!0:return b.TRUE;case!1:return b.FALSE;case r:return b.GLOBAL}return this.addToCurrentScope(e)}addCleanupHook(e,t,i){this.cleanupQueue.add(e,t,i)}removeCleanupHook(e,t,i){this.cleanupQueue.remove(e,t,i)}runCleanup(){for(;!this.cleanupQueue.empty();)this.cleanupQueue.drain()}increaseWaitingRequestCounter(){var e;null===(e=this.refCounter)||void 0===e||e.increase()}decreaseWaitingRequestCounter(){var e;null===(e=this.refCounter)||void 0===e||e.decrease()}setCanCallIntoJs(e){this._canCallIntoJs=e}setStopping(e){this._isStopping=e}canCallIntoJs(){return this._canCallIntoJs&&!this._isStopping}destroy(){this.setStopping(!0),this.setCanCallIntoJs(!1),this.runCleanup()}}let J;function Q(e){return new $(e)}exports.ConstHandle=x,exports.Context=$,exports.Deferred=T,exports.EmnapiError=O,exports.Env=C,exports.External=i,exports.Finalizer=m,exports.Handle=y,exports.HandleScope=z,exports.HandleStore=b,exports.NAPI_VERSION_EXPERIMENTAL=g,exports.NODE_API_DEFAULT_MODULE_API_VERSION=8,exports.NODE_API_SUPPORTED_VERSION_MAX=10,exports.NODE_API_SUPPORTED_VERSION_MIN=1,exports.NodeEnv=F,exports.NotSupportBufferError=R,exports.NotSupportWeakRefError=D,exports.Persistent=A,exports.RefTracker=k,exports.Reference=j,exports.ReferenceWithData=B,exports.ReferenceWithFinalizer=M,exports.ScopeStore=w,exports.Store=W,exports.TrackedFinalizer=E,exports.TryCatch=o,exports.createContext=Q,exports.getDefaultContext=function(){return J||(J=Q()),J},exports.getExternalValue=s,exports.isExternal=t,exports.isReferenceType=function(e){return"object"==typeof e&&null!==e||"function"==typeof e},exports.version=v; diff --git a/dg-ui/node_modules/@tailwindcss/oxide-wasm32-wasi/node_modules/@emnapi/runtime/dist/emnapi.d.mts b/dg-ui/node_modules/@tailwindcss/oxide-wasm32-wasi/node_modules/@emnapi/runtime/dist/emnapi.d.mts new file mode 100644 index 0000000..482aec2 --- /dev/null +++ b/dg-ui/node_modules/@tailwindcss/oxide-wasm32-wasi/node_modules/@emnapi/runtime/dist/emnapi.d.mts @@ -0,0 +1,671 @@ +export declare type Ptr = number | bigint + +export declare interface IBuffer extends Uint8Array {} +export declare interface BufferCtor { + readonly prototype: IBuffer + /** @deprecated */ + new (...args: any[]): IBuffer + from: { + (buffer: ArrayBufferLike): IBuffer + (buffer: ArrayBufferLike, byteOffset: number, length: number): IBuffer + } + alloc: (size: number) => IBuffer + isBuffer: (obj: unknown) => obj is IBuffer +} + +export declare const enum GlobalHandle { + UNDEFINED = 1, + NULL, + FALSE, + TRUE, + GLOBAL +} + +export declare const enum Version { + NODE_API_SUPPORTED_VERSION_MIN = 1, + NODE_API_DEFAULT_MODULE_API_VERSION = 8, + NODE_API_SUPPORTED_VERSION_MAX = 10, + NAPI_VERSION_EXPERIMENTAL = 2147483647 // INT_MAX +} +// eslint-disable-next-line @typescript-eslint/no-unused-vars +export declare type Pointer = number +// eslint-disable-next-line @typescript-eslint/no-unused-vars +export declare type PointerPointer = number +export declare type FunctionPointer any> = Pointer +export declare type Const = T + +export declare type void_p = Pointer +export declare type void_pp = Pointer +export declare type bool = number +export declare type char = number +export declare type char_p = Pointer +export declare type unsigned_char = number +export declare type const_char = Const +export declare type const_char_p = Pointer +export declare type char16_t_p = number +export declare type const_char16_t_p = number + +export declare type short = number +export declare type unsigned_short = number +export declare type int = number +export declare type unsigned_int = number +export declare type long = number +export declare type unsigned_long = number +export declare type long_long = bigint +export declare type unsigned_long_long = bigint +export declare type float = number +export declare type double = number +export declare type long_double = number +export declare type size_t = number + +export declare type int8_t = number +export declare type uint8_t = number +export declare type int16_t = number +export declare type uint16_t = number +export declare type int32_t = number +export declare type uint32_t = number +export declare type int64_t = bigint +export declare type uint64_t = bigint +export declare type napi_env = Pointer + +export declare type napi_value = Pointer +export declare type napi_ref = Pointer +export declare type napi_deferred = Pointer +export declare type napi_handle_scope = Pointer +export declare type napi_escapable_handle_scope = Pointer + +export declare type napi_addon_register_func = FunctionPointer<(env: napi_env, exports: napi_value) => napi_value> + +export declare type napi_callback_info = Pointer +export declare type napi_callback = FunctionPointer<(env: napi_env, info: napi_callback_info) => napi_value> + +export declare interface napi_extended_error_info { + error_message: const_char_p + engine_reserved: void_p + engine_error_code: uint32_t + error_code: napi_status +} + +export declare interface napi_property_descriptor { + // One of utf8name or name should be NULL. + utf8name: const_char_p + name: napi_value + + method: napi_callback + getter: napi_callback + setter: napi_callback + value: napi_value + /* napi_property_attributes */ + attributes: number + data: void_p +} + +export declare type napi_finalize = FunctionPointer<( + env: napi_env, + finalize_data: void_p, + finalize_hint: void_p +) => void> + +export declare interface node_module { + nm_version: int32_t + nm_flags: uint32_t + nm_filename: Pointer + nm_register_func: napi_addon_register_func + nm_modname: Pointer + nm_priv: Pointer + reserved: PointerPointer +} + +export declare interface napi_node_version { + major: uint32_t + minor: uint32_t + patch: uint32_t + release: const_char_p +} + +export declare interface emnapi_emscripten_version { + major: uint32_t + minor: uint32_t + patch: uint32_t +} + +export declare const enum napi_status { + napi_ok, + napi_invalid_arg, + napi_object_expected, + napi_string_expected, + napi_name_expected, + napi_function_expected, + napi_number_expected, + napi_boolean_expected, + napi_array_expected, + napi_generic_failure, + napi_pending_exception, + napi_cancelled, + napi_escape_called_twice, + napi_handle_scope_mismatch, + napi_callback_scope_mismatch, + napi_queue_full, + napi_closing, + napi_bigint_expected, + napi_date_expected, + napi_arraybuffer_expected, + napi_detachable_arraybuffer_expected, + napi_would_deadlock, // unused + napi_no_external_buffers_allowed, + napi_cannot_run_js +} + +export declare const enum napi_property_attributes { + napi_default = 0, + napi_writable = 1 << 0, + napi_enumerable = 1 << 1, + napi_configurable = 1 << 2, + + // Used with napi_define_class to distinguish static properties + // from instance properties. Ignored by napi_define_properties. + napi_static = 1 << 10, + + /// #ifdef NAPI_EXPERIMENTAL + // Default for class methods. + napi_default_method = napi_writable | napi_configurable, + + // Default for object properties, like in JS obj[prop]. + napi_default_jsproperty = napi_writable | napi_enumerable | napi_configurable + /// #endif // NAPI_EXPERIMENTAL +} + +export declare const enum napi_valuetype { + napi_undefined, + napi_null, + napi_boolean, + napi_number, + napi_string, + napi_symbol, + napi_object, + napi_function, + napi_external, + napi_bigint +} + +export declare const enum napi_typedarray_type { + napi_int8_array, + napi_uint8_array, + napi_uint8_clamped_array, + napi_int16_array, + napi_uint16_array, + napi_int32_array, + napi_uint32_array, + napi_float32_array, + napi_float64_array, + napi_bigint64_array, + napi_biguint64_array, + napi_float16_array, +} + +export declare const enum napi_key_collection_mode { + napi_key_include_prototypes, + napi_key_own_only +} + +export declare const enum napi_key_filter { + napi_key_all_properties = 0, + napi_key_writable = 1, + napi_key_enumerable = 1 << 1, + napi_key_configurable = 1 << 2, + napi_key_skip_strings = 1 << 3, + napi_key_skip_symbols = 1 << 4 +} + +export declare const enum napi_key_conversion { + napi_key_keep_numbers, + napi_key_numbers_to_strings +} + +export declare const enum emnapi_memory_view_type { + emnapi_int8_array, + emnapi_uint8_array, + emnapi_uint8_clamped_array, + emnapi_int16_array, + emnapi_uint16_array, + emnapi_int32_array, + emnapi_uint32_array, + emnapi_float32_array, + emnapi_float64_array, + emnapi_bigint64_array, + emnapi_biguint64_array, + emnapi_float16_array, + emnapi_data_view = -1, + emnapi_buffer = -2 +} + +export declare const enum napi_threadsafe_function_call_mode { + napi_tsfn_nonblocking, + napi_tsfn_blocking +} + +export declare const enum napi_threadsafe_function_release_mode { + napi_tsfn_release, + napi_tsfn_abort +} +export declare type CleanupHookCallbackFunction = number | ((arg: number) => void); + +export declare class ConstHandle extends Handle { + constructor(id: number, value: S); + dispose(): void; +} + +export declare class Context { + private _isStopping; + private _canCallIntoJs; + private _suppressDestroy; + envStore: Store; + scopeStore: ScopeStore; + refStore: Store; + deferredStore: Store>; + handleStore: HandleStore; + private readonly refCounter?; + private readonly cleanupQueue; + private readonly _externalMemory; + feature: { + supportReflect: boolean; + supportFinalizer: boolean; + supportWeakSymbol: boolean; + supportBigInt: boolean; + supportNewFunction: boolean; + canSetFunctionName: boolean; + setImmediate: (callback: () => void) => void; + Buffer: BufferCtor | undefined; + MessageChannel: { + new (): MessageChannel; + prototype: MessageChannel; + } | undefined; + }; + constructor(options?: ContextOptions); + /** + * Suppress the destroy on `beforeExit` event in Node.js. + * Call this method if you want to keep the context and + * all associated {@link Env | Env} alive, + * this also means that cleanup hooks will not be called. + * After call this method, you should call + * {@link Context.destroy | `Context.prototype.destroy`} method manually. + */ + suppressDestroy(): void; + getRuntimeVersions(): { + version: string; + NODE_API_SUPPORTED_VERSION_MAX: Version; + NAPI_VERSION_EXPERIMENTAL: Version; + NODE_API_DEFAULT_MODULE_API_VERSION: Version; + }; + createNotSupportWeakRefError(api: string, message: string): NotSupportWeakRefError; + createNotSupportBufferError(api: string, message: string): NotSupportBufferError; + createReference(envObject: Env, handle_id: napi_value, initialRefcount: uint32_t, ownership: ReferenceOwnership): Reference; + createReferenceWithData(envObject: Env, handle_id: napi_value, initialRefcount: uint32_t, ownership: ReferenceOwnership, data: void_p): Reference; + createReferenceWithFinalizer(envObject: Env, handle_id: napi_value, initialRefcount: uint32_t, ownership: ReferenceOwnership, finalize_callback?: napi_finalize, finalize_data?: void_p, finalize_hint?: void_p): Reference; + createDeferred(value: IDeferrdValue): Deferred; + adjustAmountOfExternalAllocatedMemory(changeInBytes: number | bigint): bigint; + createEnv(filename: string, moduleApiVersion: number, makeDynCall_vppp: (cb: Ptr) => (a: Ptr, b: Ptr, c: Ptr) => void, makeDynCall_vp: (cb: Ptr) => (a: Ptr) => void, abort: (msg?: string) => never, nodeBinding?: any): Env; + createTrackedFinalizer(envObject: Env, finalize_callback: napi_finalize, finalize_data: void_p, finalize_hint: void_p): TrackedFinalizer; + getCurrentScope(): HandleScope | null; + addToCurrentScope(value: V): Handle; + openScope(envObject?: Env): HandleScope; + closeScope(envObject?: Env, _scope?: HandleScope): void; + ensureHandle(value: S): Handle; + addCleanupHook(envObject: Env, fn: CleanupHookCallbackFunction, arg: number): void; + removeCleanupHook(envObject: Env, fn: CleanupHookCallbackFunction, arg: number): void; + runCleanup(): void; + increaseWaitingRequestCounter(): void; + decreaseWaitingRequestCounter(): void; + setCanCallIntoJs(value: boolean): void; + setStopping(value: boolean): void; + canCallIntoJs(): boolean; + /** + * Destroy the context and call cleanup hooks. + * Associated {@link Env | Env} will be destroyed. + */ + destroy(): void; +} + +export declare interface ContextOptions { + onExternalMemoryChange?: (current: bigint, old: bigint, delta: bigint) => any; +} + +export declare function createContext(options?: ContextOptions): Context; + +export declare class Deferred implements IStoreValue { + static create(ctx: Context, value: IDeferrdValue): Deferred; + id: number; + ctx: Context; + value: IDeferrdValue; + constructor(ctx: Context, value: IDeferrdValue); + resolve(value: T): void; + reject(reason?: any): void; + dispose(): void; +} + +export declare class EmnapiError extends Error { + constructor(message?: string); +} + +export declare abstract class Env implements IStoreValue { + readonly ctx: Context; + moduleApiVersion: number; + makeDynCall_vppp: (cb: Ptr) => (a: Ptr, b: Ptr, c: Ptr) => void; + makeDynCall_vp: (cb: Ptr) => (a: Ptr) => void; + abort: (msg?: string) => never; + id: number; + openHandleScopes: number; + instanceData: TrackedFinalizer | null; + tryCatch: TryCatch; + refs: number; + reflist: RefTracker; + finalizing_reflist: RefTracker; + pendingFinalizers: RefTracker[]; + lastError: { + errorCode: napi_status; + engineErrorCode: number; + engineReserved: Ptr; + }; + inGcFinalizer: boolean; + constructor(ctx: Context, moduleApiVersion: number, makeDynCall_vppp: (cb: Ptr) => (a: Ptr, b: Ptr, c: Ptr) => void, makeDynCall_vp: (cb: Ptr) => (a: Ptr) => void, abort: (msg?: string) => never); + /** @virtual */ + canCallIntoJs(): boolean; + terminatedOrTerminating(): boolean; + ref(): void; + unref(): void; + ensureHandle(value: S): Handle; + ensureHandleId(value: any): napi_value; + clearLastError(): napi_status; + setLastError(error_code: napi_status, engine_error_code?: uint32_t, engine_reserved?: void_p): napi_status; + getReturnStatus(): napi_status; + callIntoModule(fn: (env: Env) => T, handleException?: (envObject: Env, value: any) => void): T; + /** @virtual */ + abstract callFinalizer(cb: napi_finalize, data: void_p, hint: void_p): void; + invokeFinalizerFromGC(finalizer: RefTracker): void; + checkGCAccess(): void; + /** @virtual */ + enqueueFinalizer(finalizer: RefTracker): void; + /** @virtual */ + dequeueFinalizer(finalizer: RefTracker): void; + /** @virtual */ + deleteMe(): void; + dispose(): void; + private readonly _bindingMap; + initObjectBinding(value: S): IReferenceBinding; + getObjectBinding(value: S): IReferenceBinding; + setInstanceData(data: number, finalize_cb: number, finalize_hint: number): void; + getInstanceData(): number; +} + +/** @public */ +declare interface External_2 extends Record { +} + +/** @public */ +declare const External_2: { + new (value: number | bigint): External_2; + prototype: null; +}; +export { External_2 as External } + +export declare class Finalizer { + envObject: Env; + private _finalizeCallback; + private _finalizeData; + private _finalizeHint; + private _makeDynCall_vppp; + constructor(envObject: Env, _finalizeCallback?: napi_finalize, _finalizeData?: void_p, _finalizeHint?: void_p); + callback(): napi_finalize; + data(): void_p; + hint(): void_p; + resetEnv(): void; + resetFinalizer(): void; + callFinalizer(): void; + dispose(): void; +} + +export declare function getDefaultContext(): Context; + +/** @public */ +export declare function getExternalValue(external: External_2): number | bigint; + +export declare class Handle { + id: number; + value: S; + constructor(id: number, value: S); + data(): void_p; + isNumber(): boolean; + isBigInt(): boolean; + isString(): boolean; + isFunction(): boolean; + isExternal(): boolean; + isObject(): boolean; + isArray(): boolean; + isArrayBuffer(): boolean; + isTypedArray(): boolean; + isBuffer(BufferConstructor?: BufferCtor): boolean; + isDataView(): boolean; + isDate(): boolean; + isPromise(): boolean; + isBoolean(): boolean; + isUndefined(): boolean; + isSymbol(): boolean; + isNull(): boolean; + dispose(): void; +} + +export declare class HandleScope { + handleStore: HandleStore; + id: number; + parent: HandleScope | null; + child: HandleScope | null; + start: number; + end: number; + private _escapeCalled; + callbackInfo: ICallbackInfo; + constructor(handleStore: HandleStore, id: number, parentScope: HandleScope | null, start: number, end?: number); + add(value: V): Handle; + addExternal(data: void_p): Handle; + dispose(): void; + escape(handle: number): Handle | null; + escapeCalled(): boolean; +} + +export declare class HandleStore { + static UNDEFINED: ConstHandle; + static NULL: ConstHandle; + static FALSE: ConstHandle; + static TRUE: ConstHandle; + static GLOBAL: ConstHandle; + static MIN_ID: 6; + private readonly _values; + private _next; + push(value: S): Handle; + erase(start: number, end: number): void; + get(id: Ptr): Handle | undefined; + swap(a: number, b: number): void; + dispose(): void; +} + +export declare interface ICallbackInfo { + thiz: any; + data: void_p; + args: ArrayLike; + fn: Function; +} + +export declare interface IDeferrdValue { + resolve: (value: T) => void; + reject: (reason?: any) => void; +} + +export declare interface IReferenceBinding { + wrapped: number; + tag: Uint32Array | null; +} + +/** @public */ +export declare function isExternal(object: unknown): object is External_2; + +export declare function isReferenceType(v: any): v is object; + +export declare interface IStoreValue { + id: number; + dispose(): void; + [x: string]: any; +} + +export declare const NAPI_VERSION_EXPERIMENTAL = Version.NAPI_VERSION_EXPERIMENTAL; + +export declare const NODE_API_DEFAULT_MODULE_API_VERSION = Version.NODE_API_DEFAULT_MODULE_API_VERSION; + +export declare const NODE_API_SUPPORTED_VERSION_MAX = Version.NODE_API_SUPPORTED_VERSION_MAX; + +export declare const NODE_API_SUPPORTED_VERSION_MIN = Version.NODE_API_SUPPORTED_VERSION_MIN; + +export declare class NodeEnv extends Env { + filename: string; + private readonly nodeBinding?; + destructing: boolean; + finalizationScheduled: boolean; + constructor(ctx: Context, filename: string, moduleApiVersion: number, makeDynCall_vppp: (cb: Ptr) => (a: Ptr, b: Ptr, c: Ptr) => void, makeDynCall_vp: (cb: Ptr) => (a: Ptr) => void, abort: (msg?: string) => never, nodeBinding?: any); + deleteMe(): void; + canCallIntoJs(): boolean; + triggerFatalException(err: any): void; + callbackIntoModule(enforceUncaughtExceptionPolicy: boolean, fn: (env: Env) => T): T; + callFinalizer(cb: napi_finalize, data: void_p, hint: void_p): void; + callFinalizerInternal(forceUncaught: int, cb: napi_finalize, data: void_p, hint: void_p): void; + enqueueFinalizer(finalizer: RefTracker): void; + drainFinalizerQueue(): void; +} + +export declare class NotSupportBufferError extends EmnapiError { + constructor(api: string, message: string); +} + +export declare class NotSupportWeakRefError extends EmnapiError { + constructor(api: string, message: string); +} + +export declare class Persistent { + private _ref; + private _param; + private _callback; + private static readonly _registry; + constructor(value: T); + setWeak

(param: P, callback: (param: P) => void): void; + clearWeak(): void; + reset(): void; + isEmpty(): boolean; + deref(): T | undefined; +} + +export declare class Reference extends RefTracker implements IStoreValue { + private static weakCallback; + id: number; + envObject: Env; + private readonly canBeWeak; + private _refcount; + private readonly _ownership; + persistent: Persistent; + static create(envObject: Env, handle_id: napi_value, initialRefcount: uint32_t, ownership: ReferenceOwnership, _unused1?: void_p, _unused2?: void_p, _unused3?: void_p): Reference; + protected constructor(envObject: Env, handle_id: napi_value, initialRefcount: uint32_t, ownership: ReferenceOwnership); + ref(): number; + unref(): number; + get(envObject?: Env): napi_value; + /** @virtual */ + resetFinalizer(): void; + /** @virtual */ + data(): void_p; + refcount(): number; + ownership(): ReferenceOwnership; + /** @virtual */ + protected callUserFinalizer(): void; + /** @virtual */ + protected invokeFinalizerFromGC(): void; + private _setWeak; + finalize(): void; + dispose(): void; +} + +export declare enum ReferenceOwnership { + kRuntime = 0, + kUserland = 1 +} + +export declare class ReferenceWithData extends Reference { + private readonly _data; + static create(envObject: Env, value: napi_value, initialRefcount: uint32_t, ownership: ReferenceOwnership, data: void_p): ReferenceWithData; + private constructor(); + data(): void_p; +} + +export declare class ReferenceWithFinalizer extends Reference { + private _finalizer; + static create(envObject: Env, value: napi_value, initialRefcount: uint32_t, ownership: ReferenceOwnership, finalize_callback: napi_finalize, finalize_data: void_p, finalize_hint: void_p): ReferenceWithFinalizer; + private constructor(); + resetFinalizer(): void; + data(): void_p; + protected callUserFinalizer(): void; + protected invokeFinalizerFromGC(): void; + dispose(): void; +} + +export declare class RefTracker { + /** @virtual */ + dispose(): void; + /** @virtual */ + finalize(): void; + private _next; + private _prev; + link(list: RefTracker): void; + unlink(): void; + static finalizeAll(list: RefTracker): void; +} + +export declare class ScopeStore { + private readonly _rootScope; + currentScope: HandleScope; + private readonly _values; + constructor(); + get(id: number): HandleScope | undefined; + openScope(handleStore: HandleStore): HandleScope; + closeScope(): void; + dispose(): void; +} + +export declare class Store { + protected _values: Array; + private _freeList; + private _size; + constructor(); + add(value: V): void; + get(id: Ptr): V | undefined; + has(id: Ptr): boolean; + remove(id: Ptr): void; + dispose(): void; +} + +export declare class TrackedFinalizer extends RefTracker { + private _finalizer; + static create(envObject: Env, finalize_callback: napi_finalize, finalize_data: void_p, finalize_hint: void_p): TrackedFinalizer; + private constructor(); + data(): void_p; + dispose(): void; + finalize(): void; +} + +export declare class TryCatch { + private _exception; + private _caught; + isEmpty(): boolean; + hasCaught(): boolean; + exception(): any; + setError(err: any): void; + reset(): void; + extractException(): any; +} + +export declare const version: string; + +export { } diff --git a/dg-ui/node_modules/@tailwindcss/oxide-wasm32-wasi/node_modules/@emnapi/runtime/dist/emnapi.d.ts b/dg-ui/node_modules/@tailwindcss/oxide-wasm32-wasi/node_modules/@emnapi/runtime/dist/emnapi.d.ts new file mode 100644 index 0000000..01aa859 --- /dev/null +++ b/dg-ui/node_modules/@tailwindcss/oxide-wasm32-wasi/node_modules/@emnapi/runtime/dist/emnapi.d.ts @@ -0,0 +1,673 @@ +export declare type Ptr = number | bigint + +export declare interface IBuffer extends Uint8Array {} +export declare interface BufferCtor { + readonly prototype: IBuffer + /** @deprecated */ + new (...args: any[]): IBuffer + from: { + (buffer: ArrayBufferLike): IBuffer + (buffer: ArrayBufferLike, byteOffset: number, length: number): IBuffer + } + alloc: (size: number) => IBuffer + isBuffer: (obj: unknown) => obj is IBuffer +} + +export declare const enum GlobalHandle { + UNDEFINED = 1, + NULL, + FALSE, + TRUE, + GLOBAL +} + +export declare const enum Version { + NODE_API_SUPPORTED_VERSION_MIN = 1, + NODE_API_DEFAULT_MODULE_API_VERSION = 8, + NODE_API_SUPPORTED_VERSION_MAX = 10, + NAPI_VERSION_EXPERIMENTAL = 2147483647 // INT_MAX +} +// eslint-disable-next-line @typescript-eslint/no-unused-vars +export declare type Pointer = number +// eslint-disable-next-line @typescript-eslint/no-unused-vars +export declare type PointerPointer = number +export declare type FunctionPointer any> = Pointer +export declare type Const = T + +export declare type void_p = Pointer +export declare type void_pp = Pointer +export declare type bool = number +export declare type char = number +export declare type char_p = Pointer +export declare type unsigned_char = number +export declare type const_char = Const +export declare type const_char_p = Pointer +export declare type char16_t_p = number +export declare type const_char16_t_p = number + +export declare type short = number +export declare type unsigned_short = number +export declare type int = number +export declare type unsigned_int = number +export declare type long = number +export declare type unsigned_long = number +export declare type long_long = bigint +export declare type unsigned_long_long = bigint +export declare type float = number +export declare type double = number +export declare type long_double = number +export declare type size_t = number + +export declare type int8_t = number +export declare type uint8_t = number +export declare type int16_t = number +export declare type uint16_t = number +export declare type int32_t = number +export declare type uint32_t = number +export declare type int64_t = bigint +export declare type uint64_t = bigint +export declare type napi_env = Pointer + +export declare type napi_value = Pointer +export declare type napi_ref = Pointer +export declare type napi_deferred = Pointer +export declare type napi_handle_scope = Pointer +export declare type napi_escapable_handle_scope = Pointer + +export declare type napi_addon_register_func = FunctionPointer<(env: napi_env, exports: napi_value) => napi_value> + +export declare type napi_callback_info = Pointer +export declare type napi_callback = FunctionPointer<(env: napi_env, info: napi_callback_info) => napi_value> + +export declare interface napi_extended_error_info { + error_message: const_char_p + engine_reserved: void_p + engine_error_code: uint32_t + error_code: napi_status +} + +export declare interface napi_property_descriptor { + // One of utf8name or name should be NULL. + utf8name: const_char_p + name: napi_value + + method: napi_callback + getter: napi_callback + setter: napi_callback + value: napi_value + /* napi_property_attributes */ + attributes: number + data: void_p +} + +export declare type napi_finalize = FunctionPointer<( + env: napi_env, + finalize_data: void_p, + finalize_hint: void_p +) => void> + +export declare interface node_module { + nm_version: int32_t + nm_flags: uint32_t + nm_filename: Pointer + nm_register_func: napi_addon_register_func + nm_modname: Pointer + nm_priv: Pointer + reserved: PointerPointer +} + +export declare interface napi_node_version { + major: uint32_t + minor: uint32_t + patch: uint32_t + release: const_char_p +} + +export declare interface emnapi_emscripten_version { + major: uint32_t + minor: uint32_t + patch: uint32_t +} + +export declare const enum napi_status { + napi_ok, + napi_invalid_arg, + napi_object_expected, + napi_string_expected, + napi_name_expected, + napi_function_expected, + napi_number_expected, + napi_boolean_expected, + napi_array_expected, + napi_generic_failure, + napi_pending_exception, + napi_cancelled, + napi_escape_called_twice, + napi_handle_scope_mismatch, + napi_callback_scope_mismatch, + napi_queue_full, + napi_closing, + napi_bigint_expected, + napi_date_expected, + napi_arraybuffer_expected, + napi_detachable_arraybuffer_expected, + napi_would_deadlock, // unused + napi_no_external_buffers_allowed, + napi_cannot_run_js +} + +export declare const enum napi_property_attributes { + napi_default = 0, + napi_writable = 1 << 0, + napi_enumerable = 1 << 1, + napi_configurable = 1 << 2, + + // Used with napi_define_class to distinguish static properties + // from instance properties. Ignored by napi_define_properties. + napi_static = 1 << 10, + + /// #ifdef NAPI_EXPERIMENTAL + // Default for class methods. + napi_default_method = napi_writable | napi_configurable, + + // Default for object properties, like in JS obj[prop]. + napi_default_jsproperty = napi_writable | napi_enumerable | napi_configurable + /// #endif // NAPI_EXPERIMENTAL +} + +export declare const enum napi_valuetype { + napi_undefined, + napi_null, + napi_boolean, + napi_number, + napi_string, + napi_symbol, + napi_object, + napi_function, + napi_external, + napi_bigint +} + +export declare const enum napi_typedarray_type { + napi_int8_array, + napi_uint8_array, + napi_uint8_clamped_array, + napi_int16_array, + napi_uint16_array, + napi_int32_array, + napi_uint32_array, + napi_float32_array, + napi_float64_array, + napi_bigint64_array, + napi_biguint64_array, + napi_float16_array, +} + +export declare const enum napi_key_collection_mode { + napi_key_include_prototypes, + napi_key_own_only +} + +export declare const enum napi_key_filter { + napi_key_all_properties = 0, + napi_key_writable = 1, + napi_key_enumerable = 1 << 1, + napi_key_configurable = 1 << 2, + napi_key_skip_strings = 1 << 3, + napi_key_skip_symbols = 1 << 4 +} + +export declare const enum napi_key_conversion { + napi_key_keep_numbers, + napi_key_numbers_to_strings +} + +export declare const enum emnapi_memory_view_type { + emnapi_int8_array, + emnapi_uint8_array, + emnapi_uint8_clamped_array, + emnapi_int16_array, + emnapi_uint16_array, + emnapi_int32_array, + emnapi_uint32_array, + emnapi_float32_array, + emnapi_float64_array, + emnapi_bigint64_array, + emnapi_biguint64_array, + emnapi_float16_array, + emnapi_data_view = -1, + emnapi_buffer = -2 +} + +export declare const enum napi_threadsafe_function_call_mode { + napi_tsfn_nonblocking, + napi_tsfn_blocking +} + +export declare const enum napi_threadsafe_function_release_mode { + napi_tsfn_release, + napi_tsfn_abort +} +export declare type CleanupHookCallbackFunction = number | ((arg: number) => void); + +export declare class ConstHandle extends Handle { + constructor(id: number, value: S); + dispose(): void; +} + +export declare class Context { + private _isStopping; + private _canCallIntoJs; + private _suppressDestroy; + envStore: Store; + scopeStore: ScopeStore; + refStore: Store; + deferredStore: Store>; + handleStore: HandleStore; + private readonly refCounter?; + private readonly cleanupQueue; + private readonly _externalMemory; + feature: { + supportReflect: boolean; + supportFinalizer: boolean; + supportWeakSymbol: boolean; + supportBigInt: boolean; + supportNewFunction: boolean; + canSetFunctionName: boolean; + setImmediate: (callback: () => void) => void; + Buffer: BufferCtor | undefined; + MessageChannel: { + new (): MessageChannel; + prototype: MessageChannel; + } | undefined; + }; + constructor(options?: ContextOptions); + /** + * Suppress the destroy on `beforeExit` event in Node.js. + * Call this method if you want to keep the context and + * all associated {@link Env | Env} alive, + * this also means that cleanup hooks will not be called. + * After call this method, you should call + * {@link Context.destroy | `Context.prototype.destroy`} method manually. + */ + suppressDestroy(): void; + getRuntimeVersions(): { + version: string; + NODE_API_SUPPORTED_VERSION_MAX: Version; + NAPI_VERSION_EXPERIMENTAL: Version; + NODE_API_DEFAULT_MODULE_API_VERSION: Version; + }; + createNotSupportWeakRefError(api: string, message: string): NotSupportWeakRefError; + createNotSupportBufferError(api: string, message: string): NotSupportBufferError; + createReference(envObject: Env, handle_id: napi_value, initialRefcount: uint32_t, ownership: ReferenceOwnership): Reference; + createReferenceWithData(envObject: Env, handle_id: napi_value, initialRefcount: uint32_t, ownership: ReferenceOwnership, data: void_p): Reference; + createReferenceWithFinalizer(envObject: Env, handle_id: napi_value, initialRefcount: uint32_t, ownership: ReferenceOwnership, finalize_callback?: napi_finalize, finalize_data?: void_p, finalize_hint?: void_p): Reference; + createDeferred(value: IDeferrdValue): Deferred; + adjustAmountOfExternalAllocatedMemory(changeInBytes: number | bigint): bigint; + createEnv(filename: string, moduleApiVersion: number, makeDynCall_vppp: (cb: Ptr) => (a: Ptr, b: Ptr, c: Ptr) => void, makeDynCall_vp: (cb: Ptr) => (a: Ptr) => void, abort: (msg?: string) => never, nodeBinding?: any): Env; + createTrackedFinalizer(envObject: Env, finalize_callback: napi_finalize, finalize_data: void_p, finalize_hint: void_p): TrackedFinalizer; + getCurrentScope(): HandleScope | null; + addToCurrentScope(value: V): Handle; + openScope(envObject?: Env): HandleScope; + closeScope(envObject?: Env, _scope?: HandleScope): void; + ensureHandle(value: S): Handle; + addCleanupHook(envObject: Env, fn: CleanupHookCallbackFunction, arg: number): void; + removeCleanupHook(envObject: Env, fn: CleanupHookCallbackFunction, arg: number): void; + runCleanup(): void; + increaseWaitingRequestCounter(): void; + decreaseWaitingRequestCounter(): void; + setCanCallIntoJs(value: boolean): void; + setStopping(value: boolean): void; + canCallIntoJs(): boolean; + /** + * Destroy the context and call cleanup hooks. + * Associated {@link Env | Env} will be destroyed. + */ + destroy(): void; +} + +export declare interface ContextOptions { + onExternalMemoryChange?: (current: bigint, old: bigint, delta: bigint) => any; +} + +export declare function createContext(options?: ContextOptions): Context; + +export declare class Deferred implements IStoreValue { + static create(ctx: Context, value: IDeferrdValue): Deferred; + id: number; + ctx: Context; + value: IDeferrdValue; + constructor(ctx: Context, value: IDeferrdValue); + resolve(value: T): void; + reject(reason?: any): void; + dispose(): void; +} + +export declare class EmnapiError extends Error { + constructor(message?: string); +} + +export declare abstract class Env implements IStoreValue { + readonly ctx: Context; + moduleApiVersion: number; + makeDynCall_vppp: (cb: Ptr) => (a: Ptr, b: Ptr, c: Ptr) => void; + makeDynCall_vp: (cb: Ptr) => (a: Ptr) => void; + abort: (msg?: string) => never; + id: number; + openHandleScopes: number; + instanceData: TrackedFinalizer | null; + tryCatch: TryCatch; + refs: number; + reflist: RefTracker; + finalizing_reflist: RefTracker; + pendingFinalizers: RefTracker[]; + lastError: { + errorCode: napi_status; + engineErrorCode: number; + engineReserved: Ptr; + }; + inGcFinalizer: boolean; + constructor(ctx: Context, moduleApiVersion: number, makeDynCall_vppp: (cb: Ptr) => (a: Ptr, b: Ptr, c: Ptr) => void, makeDynCall_vp: (cb: Ptr) => (a: Ptr) => void, abort: (msg?: string) => never); + /** @virtual */ + canCallIntoJs(): boolean; + terminatedOrTerminating(): boolean; + ref(): void; + unref(): void; + ensureHandle(value: S): Handle; + ensureHandleId(value: any): napi_value; + clearLastError(): napi_status; + setLastError(error_code: napi_status, engine_error_code?: uint32_t, engine_reserved?: void_p): napi_status; + getReturnStatus(): napi_status; + callIntoModule(fn: (env: Env) => T, handleException?: (envObject: Env, value: any) => void): T; + /** @virtual */ + abstract callFinalizer(cb: napi_finalize, data: void_p, hint: void_p): void; + invokeFinalizerFromGC(finalizer: RefTracker): void; + checkGCAccess(): void; + /** @virtual */ + enqueueFinalizer(finalizer: RefTracker): void; + /** @virtual */ + dequeueFinalizer(finalizer: RefTracker): void; + /** @virtual */ + deleteMe(): void; + dispose(): void; + private readonly _bindingMap; + initObjectBinding(value: S): IReferenceBinding; + getObjectBinding(value: S): IReferenceBinding; + setInstanceData(data: number, finalize_cb: number, finalize_hint: number): void; + getInstanceData(): number; +} + +/** @public */ +declare interface External_2 extends Record { +} + +/** @public */ +declare const External_2: { + new (value: number | bigint): External_2; + prototype: null; +}; +export { External_2 as External } + +export declare class Finalizer { + envObject: Env; + private _finalizeCallback; + private _finalizeData; + private _finalizeHint; + private _makeDynCall_vppp; + constructor(envObject: Env, _finalizeCallback?: napi_finalize, _finalizeData?: void_p, _finalizeHint?: void_p); + callback(): napi_finalize; + data(): void_p; + hint(): void_p; + resetEnv(): void; + resetFinalizer(): void; + callFinalizer(): void; + dispose(): void; +} + +export declare function getDefaultContext(): Context; + +/** @public */ +export declare function getExternalValue(external: External_2): number | bigint; + +export declare class Handle { + id: number; + value: S; + constructor(id: number, value: S); + data(): void_p; + isNumber(): boolean; + isBigInt(): boolean; + isString(): boolean; + isFunction(): boolean; + isExternal(): boolean; + isObject(): boolean; + isArray(): boolean; + isArrayBuffer(): boolean; + isTypedArray(): boolean; + isBuffer(BufferConstructor?: BufferCtor): boolean; + isDataView(): boolean; + isDate(): boolean; + isPromise(): boolean; + isBoolean(): boolean; + isUndefined(): boolean; + isSymbol(): boolean; + isNull(): boolean; + dispose(): void; +} + +export declare class HandleScope { + handleStore: HandleStore; + id: number; + parent: HandleScope | null; + child: HandleScope | null; + start: number; + end: number; + private _escapeCalled; + callbackInfo: ICallbackInfo; + constructor(handleStore: HandleStore, id: number, parentScope: HandleScope | null, start: number, end?: number); + add(value: V): Handle; + addExternal(data: void_p): Handle; + dispose(): void; + escape(handle: number): Handle | null; + escapeCalled(): boolean; +} + +export declare class HandleStore { + static UNDEFINED: ConstHandle; + static NULL: ConstHandle; + static FALSE: ConstHandle; + static TRUE: ConstHandle; + static GLOBAL: ConstHandle; + static MIN_ID: 6; + private readonly _values; + private _next; + push(value: S): Handle; + erase(start: number, end: number): void; + get(id: Ptr): Handle | undefined; + swap(a: number, b: number): void; + dispose(): void; +} + +export declare interface ICallbackInfo { + thiz: any; + data: void_p; + args: ArrayLike; + fn: Function; +} + +export declare interface IDeferrdValue { + resolve: (value: T) => void; + reject: (reason?: any) => void; +} + +export declare interface IReferenceBinding { + wrapped: number; + tag: Uint32Array | null; +} + +/** @public */ +export declare function isExternal(object: unknown): object is External_2; + +export declare function isReferenceType(v: any): v is object; + +export declare interface IStoreValue { + id: number; + dispose(): void; + [x: string]: any; +} + +export declare const NAPI_VERSION_EXPERIMENTAL = Version.NAPI_VERSION_EXPERIMENTAL; + +export declare const NODE_API_DEFAULT_MODULE_API_VERSION = Version.NODE_API_DEFAULT_MODULE_API_VERSION; + +export declare const NODE_API_SUPPORTED_VERSION_MAX = Version.NODE_API_SUPPORTED_VERSION_MAX; + +export declare const NODE_API_SUPPORTED_VERSION_MIN = Version.NODE_API_SUPPORTED_VERSION_MIN; + +export declare class NodeEnv extends Env { + filename: string; + private readonly nodeBinding?; + destructing: boolean; + finalizationScheduled: boolean; + constructor(ctx: Context, filename: string, moduleApiVersion: number, makeDynCall_vppp: (cb: Ptr) => (a: Ptr, b: Ptr, c: Ptr) => void, makeDynCall_vp: (cb: Ptr) => (a: Ptr) => void, abort: (msg?: string) => never, nodeBinding?: any); + deleteMe(): void; + canCallIntoJs(): boolean; + triggerFatalException(err: any): void; + callbackIntoModule(enforceUncaughtExceptionPolicy: boolean, fn: (env: Env) => T): T; + callFinalizer(cb: napi_finalize, data: void_p, hint: void_p): void; + callFinalizerInternal(forceUncaught: int, cb: napi_finalize, data: void_p, hint: void_p): void; + enqueueFinalizer(finalizer: RefTracker): void; + drainFinalizerQueue(): void; +} + +export declare class NotSupportBufferError extends EmnapiError { + constructor(api: string, message: string); +} + +export declare class NotSupportWeakRefError extends EmnapiError { + constructor(api: string, message: string); +} + +export declare class Persistent { + private _ref; + private _param; + private _callback; + private static readonly _registry; + constructor(value: T); + setWeak

(param: P, callback: (param: P) => void): void; + clearWeak(): void; + reset(): void; + isEmpty(): boolean; + deref(): T | undefined; +} + +export declare class Reference extends RefTracker implements IStoreValue { + private static weakCallback; + id: number; + envObject: Env; + private readonly canBeWeak; + private _refcount; + private readonly _ownership; + persistent: Persistent; + static create(envObject: Env, handle_id: napi_value, initialRefcount: uint32_t, ownership: ReferenceOwnership, _unused1?: void_p, _unused2?: void_p, _unused3?: void_p): Reference; + protected constructor(envObject: Env, handle_id: napi_value, initialRefcount: uint32_t, ownership: ReferenceOwnership); + ref(): number; + unref(): number; + get(envObject?: Env): napi_value; + /** @virtual */ + resetFinalizer(): void; + /** @virtual */ + data(): void_p; + refcount(): number; + ownership(): ReferenceOwnership; + /** @virtual */ + protected callUserFinalizer(): void; + /** @virtual */ + protected invokeFinalizerFromGC(): void; + private _setWeak; + finalize(): void; + dispose(): void; +} + +export declare enum ReferenceOwnership { + kRuntime = 0, + kUserland = 1 +} + +export declare class ReferenceWithData extends Reference { + private readonly _data; + static create(envObject: Env, value: napi_value, initialRefcount: uint32_t, ownership: ReferenceOwnership, data: void_p): ReferenceWithData; + private constructor(); + data(): void_p; +} + +export declare class ReferenceWithFinalizer extends Reference { + private _finalizer; + static create(envObject: Env, value: napi_value, initialRefcount: uint32_t, ownership: ReferenceOwnership, finalize_callback: napi_finalize, finalize_data: void_p, finalize_hint: void_p): ReferenceWithFinalizer; + private constructor(); + resetFinalizer(): void; + data(): void_p; + protected callUserFinalizer(): void; + protected invokeFinalizerFromGC(): void; + dispose(): void; +} + +export declare class RefTracker { + /** @virtual */ + dispose(): void; + /** @virtual */ + finalize(): void; + private _next; + private _prev; + link(list: RefTracker): void; + unlink(): void; + static finalizeAll(list: RefTracker): void; +} + +export declare class ScopeStore { + private readonly _rootScope; + currentScope: HandleScope; + private readonly _values; + constructor(); + get(id: number): HandleScope | undefined; + openScope(handleStore: HandleStore): HandleScope; + closeScope(): void; + dispose(): void; +} + +export declare class Store { + protected _values: Array; + private _freeList; + private _size; + constructor(); + add(value: V): void; + get(id: Ptr): V | undefined; + has(id: Ptr): boolean; + remove(id: Ptr): void; + dispose(): void; +} + +export declare class TrackedFinalizer extends RefTracker { + private _finalizer; + static create(envObject: Env, finalize_callback: napi_finalize, finalize_data: void_p, finalize_hint: void_p): TrackedFinalizer; + private constructor(); + data(): void_p; + dispose(): void; + finalize(): void; +} + +export declare class TryCatch { + private _exception; + private _caught; + isEmpty(): boolean; + hasCaught(): boolean; + exception(): any; + setError(err: any): void; + reset(): void; + extractException(): any; +} + +export declare const version: string; + +export { } + +export as namespace emnapi; diff --git a/dg-ui/node_modules/@tailwindcss/oxide-wasm32-wasi/node_modules/@emnapi/runtime/dist/emnapi.esm-bundler.js b/dg-ui/node_modules/@tailwindcss/oxide-wasm32-wasi/node_modules/@emnapi/runtime/dist/emnapi.esm-bundler.js new file mode 100644 index 0000000..bed71f4 --- /dev/null +++ b/dg-ui/node_modules/@tailwindcss/oxide-wasm32-wasi/node_modules/@emnapi/runtime/dist/emnapi.esm-bundler.js @@ -0,0 +1,1457 @@ +import { __extends } from 'tslib'; + +var externalValue = new WeakMap(); +/** @public */ +function isExternal(object) { + return externalValue.has(object); +} +/** @public */ // eslint-disable-next-line @typescript-eslint/no-redeclare +var External = (function () { + function External(value) { + Object.setPrototypeOf(this, null); + externalValue.set(this, value); + } + External.prototype = null; + return External; +})(); +/** @public */ +function getExternalValue(external) { + if (!isExternal(external)) { + throw new TypeError('not external'); + } + return externalValue.get(external); +} + +var supportNewFunction = /*#__PURE__*/ (function () { + var f; + try { + f = new Function(); + } + catch (_) { + return false; + } + return typeof f === 'function'; +})(); +var _global = /*#__PURE__*/ (function () { + if (typeof globalThis !== 'undefined') + return globalThis; + var g = (function () { return this; })(); + if (!g && supportNewFunction) { + try { + g = new Function('return this')(); + } + catch (_) { } + } + if (!g) { + if (typeof __webpack_public_path__ === 'undefined') { + if (typeof global !== 'undefined') + return global; + } + if (typeof window !== 'undefined') + return window; + if (typeof self !== 'undefined') + return self; + } + return g; +})(); +var TryCatch = /*#__PURE__*/ (function () { + function TryCatch() { + this._exception = undefined; + this._caught = false; + } + TryCatch.prototype.isEmpty = function () { + return !this._caught; + }; + TryCatch.prototype.hasCaught = function () { + return this._caught; + }; + TryCatch.prototype.exception = function () { + return this._exception; + }; + TryCatch.prototype.setError = function (err) { + this._caught = true; + this._exception = err; + }; + TryCatch.prototype.reset = function () { + this._caught = false; + this._exception = undefined; + }; + TryCatch.prototype.extractException = function () { + var e = this._exception; + this.reset(); + return e; + }; + return TryCatch; +}()); +var canSetFunctionName = /*#__PURE__*/ (function () { + var _a; + try { + return Boolean((_a = Object.getOwnPropertyDescriptor(Function.prototype, 'name')) === null || _a === void 0 ? void 0 : _a.configurable); + } + catch (_) { + return false; + } +})(); +var supportReflect = typeof Reflect === 'object'; +var supportFinalizer = (typeof FinalizationRegistry !== 'undefined') && (typeof WeakRef !== 'undefined'); +var supportWeakSymbol = /*#__PURE__*/ (function () { + try { + // eslint-disable-next-line symbol-description + var sym = Symbol(); + // eslint-disable-next-line no-new + new WeakRef(sym); + new WeakMap().set(sym, undefined); + } + catch (_) { + return false; + } + return true; +})(); +var supportBigInt = typeof BigInt !== 'undefined'; +function isReferenceType(v) { + return (typeof v === 'object' && v !== null) || typeof v === 'function'; +} +var _require = /*#__PURE__*/ (function () { + var nativeRequire; + if (typeof __webpack_public_path__ !== 'undefined') { + nativeRequire = (function () { + return typeof __non_webpack_require__ !== 'undefined' ? __non_webpack_require__ : undefined; + })(); + } + else { + nativeRequire = (function () { + return typeof __webpack_public_path__ !== 'undefined' ? (typeof __non_webpack_require__ !== 'undefined' ? __non_webpack_require__ : undefined) : (typeof require !== 'undefined' ? require : undefined); + })(); + } + return nativeRequire; +})(); +var _MessageChannel = typeof MessageChannel === 'function' + ? MessageChannel + : /*#__PURE__*/ (function () { + try { + return _require('worker_threads').MessageChannel; + } + catch (_) { } + return undefined; + })(); +var _setImmediate = typeof setImmediate === 'function' + ? setImmediate.bind(_global) + : function (callback) { + if (typeof callback !== 'function') { + throw new TypeError('The "callback" argument must be of type function'); + } + if (_MessageChannel) { + var channel_1 = new _MessageChannel(); + channel_1.port1.onmessage = function () { + channel_1.port1.onmessage = null; + channel_1 = undefined; + callback(); + }; + channel_1.port2.postMessage(null); + } + else { + setTimeout(callback, 0); + } + }; +var _Buffer = typeof Buffer === 'function' + ? Buffer + : /*#__PURE__*/ (function () { + try { + return _require('buffer').Buffer; + } + catch (_) { } + return undefined; + })(); +var version = "1.11.3"; +var NODE_API_SUPPORTED_VERSION_MIN = 1 /* Version.NODE_API_SUPPORTED_VERSION_MIN */; +var NODE_API_SUPPORTED_VERSION_MAX = 10 /* Version.NODE_API_SUPPORTED_VERSION_MAX */; +var NAPI_VERSION_EXPERIMENTAL = 2147483647 /* Version.NAPI_VERSION_EXPERIMENTAL */; +var NODE_API_DEFAULT_MODULE_API_VERSION = 8 /* Version.NODE_API_DEFAULT_MODULE_API_VERSION */; + +var Handle = /*#__PURE__*/ (function () { + function Handle(id, value) { + this.id = id; + this.value = value; + } + Handle.prototype.data = function () { + return getExternalValue(this.value); + }; + Handle.prototype.isNumber = function () { + return typeof this.value === 'number'; + }; + Handle.prototype.isBigInt = function () { + return typeof this.value === 'bigint'; + }; + Handle.prototype.isString = function () { + return typeof this.value === 'string'; + }; + Handle.prototype.isFunction = function () { + return typeof this.value === 'function'; + }; + Handle.prototype.isExternal = function () { + return isExternal(this.value); + }; + Handle.prototype.isObject = function () { + return typeof this.value === 'object' && this.value !== null; + }; + Handle.prototype.isArray = function () { + return Array.isArray(this.value); + }; + Handle.prototype.isArrayBuffer = function () { + return (this.value instanceof ArrayBuffer); + }; + Handle.prototype.isTypedArray = function () { + return (ArrayBuffer.isView(this.value)) && !(this.value instanceof DataView); + }; + Handle.prototype.isBuffer = function (BufferConstructor) { + if (ArrayBuffer.isView(this.value)) + return true; + BufferConstructor !== null && BufferConstructor !== void 0 ? BufferConstructor : (BufferConstructor = _Buffer); + return typeof BufferConstructor === 'function' && BufferConstructor.isBuffer(this.value); + }; + Handle.prototype.isDataView = function () { + return (this.value instanceof DataView); + }; + Handle.prototype.isDate = function () { + return (this.value instanceof Date); + }; + Handle.prototype.isPromise = function () { + return (this.value instanceof Promise); + }; + Handle.prototype.isBoolean = function () { + return typeof this.value === 'boolean'; + }; + Handle.prototype.isUndefined = function () { + return this.value === undefined; + }; + Handle.prototype.isSymbol = function () { + return typeof this.value === 'symbol'; + }; + Handle.prototype.isNull = function () { + return this.value === null; + }; + Handle.prototype.dispose = function () { + this.value = undefined; + }; + return Handle; +}()); +var ConstHandle = /*#__PURE__*/ (function (_super) { + __extends(ConstHandle, _super); + function ConstHandle(id, value) { + return _super.call(this, id, value) || this; + } + ConstHandle.prototype.dispose = function () { }; + return ConstHandle; +}(Handle)); +var HandleStore = /*#__PURE__*/ (function () { + function HandleStore() { + this._values = [ + undefined, + HandleStore.UNDEFINED, + HandleStore.NULL, + HandleStore.FALSE, + HandleStore.TRUE, + HandleStore.GLOBAL + ]; + this._next = HandleStore.MIN_ID; + } + HandleStore.prototype.push = function (value) { + var h; + var next = this._next; + var values = this._values; + if (next < values.length) { + h = values[next]; + h.value = value; + } + else { + h = new Handle(next, value); + values[next] = h; + } + this._next++; + return h; + }; + HandleStore.prototype.erase = function (start, end) { + this._next = start; + var values = this._values; + for (var i = start; i < end; ++i) { + values[i].dispose(); + } + }; + HandleStore.prototype.get = function (id) { + return this._values[id]; + }; + HandleStore.prototype.swap = function (a, b) { + var values = this._values; + var h = values[a]; + values[a] = values[b]; + values[a].id = Number(a); + values[b] = h; + h.id = Number(b); + }; + HandleStore.prototype.dispose = function () { + this._values.length = HandleStore.MIN_ID; + this._next = HandleStore.MIN_ID; + }; + HandleStore.UNDEFINED = new ConstHandle(1 /* GlobalHandle.UNDEFINED */, undefined); + HandleStore.NULL = new ConstHandle(2 /* GlobalHandle.NULL */, null); + HandleStore.FALSE = new ConstHandle(3 /* GlobalHandle.FALSE */, false); + HandleStore.TRUE = new ConstHandle(4 /* GlobalHandle.TRUE */, true); + HandleStore.GLOBAL = new ConstHandle(5 /* GlobalHandle.GLOBAL */, _global); + HandleStore.MIN_ID = 6; + return HandleStore; +}()); + +var HandleScope = /*#__PURE__*/ (function () { + function HandleScope(handleStore, id, parentScope, start, end) { + if (end === void 0) { end = start; } + this.handleStore = handleStore; + this.id = id; + this.parent = parentScope; + this.child = null; + if (parentScope !== null) + parentScope.child = this; + this.start = start; + this.end = end; + this._escapeCalled = false; + this.callbackInfo = { + thiz: undefined, + data: 0, + args: undefined, + fn: undefined + }; + } + HandleScope.prototype.add = function (value) { + var h = this.handleStore.push(value); + this.end++; + return h; + }; + HandleScope.prototype.addExternal = function (data) { + return this.add(new External(data)); + }; + HandleScope.prototype.dispose = function () { + if (this._escapeCalled) + this._escapeCalled = false; + if (this.start === this.end) + return; + this.handleStore.erase(this.start, this.end); + }; + HandleScope.prototype.escape = function (handle) { + if (this._escapeCalled) + return null; + this._escapeCalled = true; + if (handle < this.start || handle >= this.end) { + return null; + } + this.handleStore.swap(handle, this.start); + var h = this.handleStore.get(this.start); + this.start++; + this.parent.end++; + return h; + }; + HandleScope.prototype.escapeCalled = function () { + return this._escapeCalled; + }; + return HandleScope; +}()); + +var ScopeStore = /*#__PURE__*/ (function () { + function ScopeStore() { + this._rootScope = new HandleScope(null, 0, null, 1, HandleStore.MIN_ID); + this.currentScope = this._rootScope; + this._values = [undefined]; + } + ScopeStore.prototype.get = function (id) { + return this._values[id]; + }; + ScopeStore.prototype.openScope = function (handleStore) { + var currentScope = this.currentScope; + var scope = currentScope.child; + if (scope !== null) { + scope.start = scope.end = currentScope.end; + } + else { + var id = currentScope.id + 1; + scope = new HandleScope(handleStore, id, currentScope, currentScope.end); + this._values[id] = scope; + } + this.currentScope = scope; + return scope; + }; + ScopeStore.prototype.closeScope = function () { + var scope = this.currentScope; + this.currentScope = scope.parent; + scope.dispose(); + }; + ScopeStore.prototype.dispose = function () { + this.currentScope = this._rootScope; + this._values.length = 1; + }; + return ScopeStore; +}()); + +var RefTracker = /*#__PURE__*/ (function () { + function RefTracker() { + this._next = null; + this._prev = null; + } + /** @virtual */ + RefTracker.prototype.dispose = function () { }; + /** @virtual */ + RefTracker.prototype.finalize = function () { }; + RefTracker.prototype.link = function (list) { + this._prev = list; + this._next = list._next; + if (this._next !== null) { + this._next._prev = this; + } + list._next = this; + }; + RefTracker.prototype.unlink = function () { + if (this._prev !== null) { + this._prev._next = this._next; + } + if (this._next !== null) { + this._next._prev = this._prev; + } + this._prev = null; + this._next = null; + }; + RefTracker.finalizeAll = function (list) { + while (list._next !== null) { + list._next.finalize(); + } + }; + return RefTracker; +}()); + +var Finalizer = /*#__PURE__*/ (function () { + function Finalizer(envObject, _finalizeCallback, _finalizeData, _finalizeHint) { + if (_finalizeCallback === void 0) { _finalizeCallback = 0; } + if (_finalizeData === void 0) { _finalizeData = 0; } + if (_finalizeHint === void 0) { _finalizeHint = 0; } + this.envObject = envObject; + this._finalizeCallback = _finalizeCallback; + this._finalizeData = _finalizeData; + this._finalizeHint = _finalizeHint; + this._makeDynCall_vppp = envObject.makeDynCall_vppp; + } + Finalizer.prototype.callback = function () { return this._finalizeCallback; }; + Finalizer.prototype.data = function () { return this._finalizeData; }; + Finalizer.prototype.hint = function () { return this._finalizeHint; }; + Finalizer.prototype.resetEnv = function () { + this.envObject = undefined; + }; + Finalizer.prototype.resetFinalizer = function () { + this._finalizeCallback = 0; + this._finalizeData = 0; + this._finalizeHint = 0; + }; + Finalizer.prototype.callFinalizer = function () { + var finalize_callback = this._finalizeCallback; + var finalize_data = this._finalizeData; + var finalize_hint = this._finalizeHint; + this.resetFinalizer(); + if (!finalize_callback) + return; + var fini = Number(finalize_callback); + if (!this.envObject) { + this._makeDynCall_vppp(fini)(0, finalize_data, finalize_hint); + } + else { + this.envObject.callFinalizer(fini, finalize_data, finalize_hint); + } + }; + Finalizer.prototype.dispose = function () { + this.envObject = undefined; + this._makeDynCall_vppp = undefined; + }; + return Finalizer; +}()); + +var TrackedFinalizer = /*#__PURE__*/ (function (_super) { + __extends(TrackedFinalizer, _super); + function TrackedFinalizer(envObject, finalize_callback, finalize_data, finalize_hint) { + var _this = _super.call(this) || this; + _this._finalizer = new Finalizer(envObject, finalize_callback, finalize_data, finalize_hint); + return _this; + } + TrackedFinalizer.create = function (envObject, finalize_callback, finalize_data, finalize_hint) { + var finalizer = new TrackedFinalizer(envObject, finalize_callback, finalize_data, finalize_hint); + finalizer.link(envObject.finalizing_reflist); + return finalizer; + }; + TrackedFinalizer.prototype.data = function () { + return this._finalizer.data(); + }; + TrackedFinalizer.prototype.dispose = function () { + if (!this._finalizer) + return; + this.unlink(); + this._finalizer.envObject.dequeueFinalizer(this); + this._finalizer.dispose(); + this._finalizer = undefined; + _super.prototype.dispose.call(this); + }; + TrackedFinalizer.prototype.finalize = function () { + this.unlink(); + var error; + var caught = false; + try { + this._finalizer.callFinalizer(); + } + catch (err) { + caught = true; + error = err; + } + this.dispose(); + if (caught) { + throw error; + } + }; + return TrackedFinalizer; +}(RefTracker)); + +function throwNodeApiVersionError(moduleName, moduleApiVersion) { + var errorMessage = "".concat(moduleName, " requires Node-API version ").concat(moduleApiVersion, ", but this version of Node.js only supports version ").concat(NODE_API_SUPPORTED_VERSION_MAX, " add-ons."); + throw new Error(errorMessage); +} +function handleThrow(envObject, value) { + if (envObject.terminatedOrTerminating()) { + return; + } + throw value; +} +var Env = /*#__PURE__*/ (function () { + function Env(ctx, moduleApiVersion, makeDynCall_vppp, makeDynCall_vp, abort) { + this.ctx = ctx; + this.moduleApiVersion = moduleApiVersion; + this.makeDynCall_vppp = makeDynCall_vppp; + this.makeDynCall_vp = makeDynCall_vp; + this.abort = abort; + this.openHandleScopes = 0; + this.instanceData = null; + this.tryCatch = new TryCatch(); + this.refs = 1; + this.reflist = new RefTracker(); + this.finalizing_reflist = new RefTracker(); + this.pendingFinalizers = []; + this.lastError = { + errorCode: 0 /* napi_status.napi_ok */, + engineErrorCode: 0, + engineReserved: 0 + }; + this.inGcFinalizer = false; + this._bindingMap = new WeakMap(); + this.id = 0; + } + /** @virtual */ + Env.prototype.canCallIntoJs = function () { + return true; + }; + Env.prototype.terminatedOrTerminating = function () { + return !this.canCallIntoJs(); + }; + Env.prototype.ref = function () { + this.refs++; + }; + Env.prototype.unref = function () { + this.refs--; + if (this.refs === 0) { + this.dispose(); + } + }; + Env.prototype.ensureHandle = function (value) { + return this.ctx.ensureHandle(value); + }; + Env.prototype.ensureHandleId = function (value) { + return this.ensureHandle(value).id; + }; + Env.prototype.clearLastError = function () { + var lastError = this.lastError; + if (lastError.errorCode !== 0 /* napi_status.napi_ok */) + lastError.errorCode = 0 /* napi_status.napi_ok */; + if (lastError.engineErrorCode !== 0) + lastError.engineErrorCode = 0; + if (lastError.engineReserved !== 0) + lastError.engineReserved = 0; + return 0 /* napi_status.napi_ok */; + }; + Env.prototype.setLastError = function (error_code, engine_error_code, engine_reserved) { + if (engine_error_code === void 0) { engine_error_code = 0; } + if (engine_reserved === void 0) { engine_reserved = 0; } + var lastError = this.lastError; + if (lastError.errorCode !== error_code) + lastError.errorCode = error_code; + if (lastError.engineErrorCode !== engine_error_code) + lastError.engineErrorCode = engine_error_code; + if (lastError.engineReserved !== engine_reserved) + lastError.engineReserved = engine_reserved; + return error_code; + }; + Env.prototype.getReturnStatus = function () { + return !this.tryCatch.hasCaught() ? 0 /* napi_status.napi_ok */ : this.setLastError(10 /* napi_status.napi_pending_exception */); + }; + Env.prototype.callIntoModule = function (fn, handleException) { + if (handleException === void 0) { handleException = handleThrow; } + var openHandleScopesBefore = this.openHandleScopes; + this.clearLastError(); + var r = fn(this); + if (openHandleScopesBefore !== this.openHandleScopes) { + this.abort('open_handle_scopes != open_handle_scopes_before'); + } + if (this.tryCatch.hasCaught()) { + var err = this.tryCatch.extractException(); + handleException(this, err); + } + return r; + }; + Env.prototype.invokeFinalizerFromGC = function (finalizer) { + if (this.moduleApiVersion !== NAPI_VERSION_EXPERIMENTAL) { + this.enqueueFinalizer(finalizer); + } + else { + var saved = this.inGcFinalizer; + this.inGcFinalizer = true; + try { + finalizer.finalize(); + } + finally { + this.inGcFinalizer = saved; + } + } + }; + Env.prototype.checkGCAccess = function () { + if (this.moduleApiVersion === NAPI_VERSION_EXPERIMENTAL && this.inGcFinalizer) { + this.abort('Finalizer is calling a function that may affect GC state.\n' + + 'The finalizers are run directly from GC and must not affect GC ' + + 'state.\n' + + 'Use `node_api_post_finalizer` from inside of the finalizer to work ' + + 'around this issue.\n' + + 'It schedules the call as a new task in the event loop.'); + } + }; + /** @virtual */ + Env.prototype.enqueueFinalizer = function (finalizer) { + if (this.pendingFinalizers.indexOf(finalizer) === -1) { + this.pendingFinalizers.push(finalizer); + } + }; + /** @virtual */ + Env.prototype.dequeueFinalizer = function (finalizer) { + var index = this.pendingFinalizers.indexOf(finalizer); + if (index !== -1) { + this.pendingFinalizers.splice(index, 1); + } + }; + /** @virtual */ + Env.prototype.deleteMe = function () { + RefTracker.finalizeAll(this.finalizing_reflist); + RefTracker.finalizeAll(this.reflist); + this.tryCatch.extractException(); + this.ctx.envStore.remove(this.id); + }; + Env.prototype.dispose = function () { + if (this.id === 0) + return; + this.deleteMe(); + this.finalizing_reflist.dispose(); + this.reflist.dispose(); + this.id = 0; + }; + Env.prototype.initObjectBinding = function (value) { + var binding = { + wrapped: 0, + tag: null + }; + this._bindingMap.set(value, binding); + return binding; + }; + Env.prototype.getObjectBinding = function (value) { + if (this._bindingMap.has(value)) { + return this._bindingMap.get(value); + } + return this.initObjectBinding(value); + }; + Env.prototype.setInstanceData = function (data, finalize_cb, finalize_hint) { + if (this.instanceData) { + this.instanceData.dispose(); + } + this.instanceData = TrackedFinalizer.create(this, finalize_cb, data, finalize_hint); + }; + Env.prototype.getInstanceData = function () { + return this.instanceData ? this.instanceData.data() : 0; + }; + return Env; +}()); +var NodeEnv = /*#__PURE__*/ (function (_super) { + __extends(NodeEnv, _super); + function NodeEnv(ctx, filename, moduleApiVersion, makeDynCall_vppp, makeDynCall_vp, abort, nodeBinding) { + var _this = _super.call(this, ctx, moduleApiVersion, makeDynCall_vppp, makeDynCall_vp, abort) || this; + _this.filename = filename; + _this.nodeBinding = nodeBinding; + _this.destructing = false; + _this.finalizationScheduled = false; + return _this; + } + NodeEnv.prototype.deleteMe = function () { + this.destructing = true; + this.drainFinalizerQueue(); + _super.prototype.deleteMe.call(this); + }; + NodeEnv.prototype.canCallIntoJs = function () { + return _super.prototype.canCallIntoJs.call(this) && this.ctx.canCallIntoJs(); + }; + NodeEnv.prototype.triggerFatalException = function (err) { + if (this.nodeBinding) { + this.nodeBinding.napi.fatalException(err); + } + else { + if (typeof process === 'object' && process !== null && typeof process._fatalException === 'function') { + var handled = process._fatalException(err); + if (!handled) { + console.error(err); + process.exit(1); + } + } + else { + throw err; + } + } + }; + NodeEnv.prototype.callbackIntoModule = function (enforceUncaughtExceptionPolicy, fn) { + return this.callIntoModule(fn, function (envObject, err) { + if (envObject.terminatedOrTerminating()) { + return; + } + var hasProcess = typeof process === 'object' && process !== null; + var hasForceFlag = hasProcess ? Boolean(process.execArgv && (process.execArgv.indexOf('--force-node-api-uncaught-exceptions-policy') !== -1)) : false; + if (envObject.moduleApiVersion < 10 && !hasForceFlag && !enforceUncaughtExceptionPolicy) { + var warn = hasProcess && typeof process.emitWarning === 'function' + ? process.emitWarning + : function (warning, type, code) { + if (warning instanceof Error) { + console.warn(warning.toString()); + } + else { + var prefix = code ? "[".concat(code, "] ") : ''; + // eslint-disable-next-line @typescript-eslint/prefer-nullish-coalescing + console.warn("".concat(prefix).concat(type || 'Warning', ": ").concat(warning)); + } + }; + warn('Uncaught Node-API callback exception detected, please run node with option --force-node-api-uncaught-exceptions-policy=true to handle those exceptions properly.', 'DeprecationWarning', 'DEP0168'); + return; + } + envObject.triggerFatalException(err); + }); + }; + NodeEnv.prototype.callFinalizer = function (cb, data, hint) { + this.callFinalizerInternal(1, cb, data, hint); + }; + NodeEnv.prototype.callFinalizerInternal = function (forceUncaught, cb, data, hint) { + var f = this.makeDynCall_vppp(cb); + var env = this.id; + var scope = this.ctx.openScope(this); + try { + this.callbackIntoModule(Boolean(forceUncaught), function () { f(env, data, hint); }); + } + finally { + this.ctx.closeScope(this, scope); + } + }; + NodeEnv.prototype.enqueueFinalizer = function (finalizer) { + var _this = this; + _super.prototype.enqueueFinalizer.call(this, finalizer); + if (!this.finalizationScheduled && !this.destructing) { + this.finalizationScheduled = true; + this.ref(); + _setImmediate(function () { + _this.finalizationScheduled = false; + _this.unref(); + _this.drainFinalizerQueue(); + }); + } + }; + NodeEnv.prototype.drainFinalizerQueue = function () { + while (this.pendingFinalizers.length > 0) { + var refTracker = this.pendingFinalizers.shift(); + refTracker.finalize(); + } + }; + return NodeEnv; +}(Env)); +function newEnv(ctx, filename, moduleApiVersion, makeDynCall_vppp, makeDynCall_vp, abort, nodeBinding) { + moduleApiVersion = typeof moduleApiVersion !== 'number' ? NODE_API_DEFAULT_MODULE_API_VERSION : moduleApiVersion; + // Validate module_api_version. + if (moduleApiVersion < NODE_API_DEFAULT_MODULE_API_VERSION) { + moduleApiVersion = NODE_API_DEFAULT_MODULE_API_VERSION; + } + else if (moduleApiVersion > NODE_API_SUPPORTED_VERSION_MAX && moduleApiVersion !== NAPI_VERSION_EXPERIMENTAL) { + throwNodeApiVersionError(filename, moduleApiVersion); + } + var env = new NodeEnv(ctx, filename, moduleApiVersion, makeDynCall_vppp, makeDynCall_vp, abort, nodeBinding); + ctx.envStore.add(env); + ctx.addCleanupHook(env, function () { env.unref(); }, 0); + return env; +} + +var EmnapiError = /*#__PURE__*/ (function (_super) { + __extends(EmnapiError, _super); + function EmnapiError(message) { + var _newTarget = this.constructor; + var _this = _super.call(this, message) || this; + var ErrorConstructor = _newTarget; + var proto = ErrorConstructor.prototype; + if (!(_this instanceof EmnapiError)) { + var setPrototypeOf = Object.setPrototypeOf; + if (typeof setPrototypeOf === 'function') { + setPrototypeOf.call(Object, _this, proto); + } + else { + // eslint-disable-next-line no-proto + _this.__proto__ = proto; + } + if (typeof Error.captureStackTrace === 'function') { + Error.captureStackTrace(_this, ErrorConstructor); + } + } + return _this; + } + return EmnapiError; +}(Error)); +Object.defineProperty(EmnapiError.prototype, 'name', { + configurable: true, + writable: true, + value: 'EmnapiError' +}); +var NotSupportWeakRefError = /*#__PURE__*/ (function (_super) { + __extends(NotSupportWeakRefError, _super); + function NotSupportWeakRefError(api, message) { + return _super.call(this, "".concat(api, ": The current runtime does not support \"FinalizationRegistry\" and \"WeakRef\".").concat(message ? " ".concat(message) : '')) || this; + } + return NotSupportWeakRefError; +}(EmnapiError)); +Object.defineProperty(NotSupportWeakRefError.prototype, 'name', { + configurable: true, + writable: true, + value: 'NotSupportWeakRefError' +}); +var NotSupportBufferError = /*#__PURE__*/ (function (_super) { + __extends(NotSupportBufferError, _super); + function NotSupportBufferError(api, message) { + return _super.call(this, "".concat(api, ": The current runtime does not support \"Buffer\". Consider using buffer polyfill to make sure `globalThis.Buffer` is defined.").concat(message ? " ".concat(message) : '')) || this; + } + return NotSupportBufferError; +}(EmnapiError)); +Object.defineProperty(NotSupportBufferError.prototype, 'name', { + configurable: true, + writable: true, + value: 'NotSupportBufferError' +}); + +var StrongRef = /*#__PURE__*/ (function () { + function StrongRef(value) { + this._value = value; + } + StrongRef.prototype.deref = function () { + return this._value; + }; + StrongRef.prototype.dispose = function () { + this._value = undefined; + }; + return StrongRef; +}()); +var Persistent = /*#__PURE__*/ (function () { + function Persistent(value) { + this._ref = new StrongRef(value); + } + Persistent.prototype.setWeak = function (param, callback) { + if (!supportFinalizer || this._ref === undefined || this._ref instanceof WeakRef) + return; + var value = this._ref.deref(); + try { + Persistent._registry.register(value, this, this); + var weakRef = new WeakRef(value); + this._ref.dispose(); + this._ref = weakRef; + this._param = param; + this._callback = callback; + } + catch (err) { + if (typeof value === 'symbol') ; + else { + throw err; + } + } + }; + Persistent.prototype.clearWeak = function () { + if (!supportFinalizer || this._ref === undefined) + return; + if (this._ref instanceof WeakRef) { + try { + Persistent._registry.unregister(this); + } + catch (_) { } + this._param = undefined; + this._callback = undefined; + var value = this._ref.deref(); + if (value === undefined) { + this._ref = value; + } + else { + this._ref = new StrongRef(value); + } + } + }; + Persistent.prototype.reset = function () { + if (supportFinalizer) { + try { + Persistent._registry.unregister(this); + } + catch (_) { } + } + this._param = undefined; + this._callback = undefined; + if (this._ref instanceof StrongRef) { + this._ref.dispose(); + } + this._ref = undefined; + }; + Persistent.prototype.isEmpty = function () { + return this._ref === undefined; + }; + Persistent.prototype.deref = function () { + if (this._ref === undefined) + return undefined; + return this._ref.deref(); + }; + Persistent._registry = supportFinalizer + ? new FinalizationRegistry(function (value) { + value._ref = undefined; + var callback = value._callback; + var param = value._param; + value._callback = undefined; + value._param = undefined; + if (typeof callback === 'function') { + callback(param); + } + }) + : undefined; + return Persistent; +}()); + +var ReferenceOwnership; +(function (ReferenceOwnership) { + ReferenceOwnership[ReferenceOwnership["kRuntime"] = 0] = "kRuntime"; + ReferenceOwnership[ReferenceOwnership["kUserland"] = 1] = "kUserland"; +})(ReferenceOwnership || (ReferenceOwnership = {})); +function canBeHeldWeakly(value) { + return value.isObject() || value.isFunction() || value.isSymbol(); +} +var Reference = /*#__PURE__*/ (function (_super) { + __extends(Reference, _super); + function Reference(envObject, handle_id, initialRefcount, ownership) { + var _this = _super.call(this) || this; + _this.envObject = envObject; + _this._refcount = initialRefcount; + _this._ownership = ownership; + var handle = envObject.ctx.handleStore.get(handle_id); + _this.canBeWeak = canBeHeldWeakly(handle); + _this.persistent = new Persistent(handle.value); + _this.id = 0; + if (initialRefcount === 0) { + _this._setWeak(); + } + return _this; + } + Reference.weakCallback = function (ref) { + ref.persistent.reset(); + ref.invokeFinalizerFromGC(); + }; + Reference.create = function (envObject, handle_id, initialRefcount, ownership, _unused1, _unused2, _unused3) { + var ref = new Reference(envObject, handle_id, initialRefcount, ownership); + envObject.ctx.refStore.add(ref); + ref.link(envObject.reflist); + return ref; + }; + Reference.prototype.ref = function () { + if (this.persistent.isEmpty()) { + return 0; + } + if (++this._refcount === 1 && this.canBeWeak) { + this.persistent.clearWeak(); + } + return this._refcount; + }; + Reference.prototype.unref = function () { + if (this.persistent.isEmpty() || this._refcount === 0) { + return 0; + } + if (--this._refcount === 0) { + this._setWeak(); + } + return this._refcount; + }; + Reference.prototype.get = function (envObject) { + if (envObject === void 0) { envObject = this.envObject; } + if (this.persistent.isEmpty()) { + return 0; + } + var obj = this.persistent.deref(); + var handle = envObject.ensureHandle(obj); + return handle.id; + }; + /** @virtual */ + Reference.prototype.resetFinalizer = function () { }; + /** @virtual */ + Reference.prototype.data = function () { return 0; }; + Reference.prototype.refcount = function () { return this._refcount; }; + Reference.prototype.ownership = function () { return this._ownership; }; + /** @virtual */ + Reference.prototype.callUserFinalizer = function () { }; + /** @virtual */ + Reference.prototype.invokeFinalizerFromGC = function () { + this.finalize(); + }; + Reference.prototype._setWeak = function () { + if (this.canBeWeak) { + this.persistent.setWeak(this, Reference.weakCallback); + } + else { + this.persistent.reset(); + } + }; + Reference.prototype.finalize = function () { + this.persistent.reset(); + var deleteMe = this._ownership === ReferenceOwnership.kRuntime; + this.unlink(); + this.callUserFinalizer(); + if (deleteMe) { + this.dispose(); + } + }; + Reference.prototype.dispose = function () { + if (this.id === 0) + return; + this.unlink(); + this.persistent.reset(); + this.envObject.ctx.refStore.remove(this.id); + _super.prototype.dispose.call(this); + this.envObject = undefined; + this.id = 0; + }; + return Reference; +}(RefTracker)); +var ReferenceWithData = /*#__PURE__*/ (function (_super) { + __extends(ReferenceWithData, _super); + function ReferenceWithData(envObject, value, initialRefcount, ownership, _data) { + var _this = _super.call(this, envObject, value, initialRefcount, ownership) || this; + _this._data = _data; + return _this; + } + ReferenceWithData.create = function (envObject, value, initialRefcount, ownership, data) { + var reference = new ReferenceWithData(envObject, value, initialRefcount, ownership, data); + envObject.ctx.refStore.add(reference); + reference.link(envObject.reflist); + return reference; + }; + ReferenceWithData.prototype.data = function () { + return this._data; + }; + return ReferenceWithData; +}(Reference)); +var ReferenceWithFinalizer = /*#__PURE__*/ (function (_super) { + __extends(ReferenceWithFinalizer, _super); + function ReferenceWithFinalizer(envObject, value, initialRefcount, ownership, finalize_callback, finalize_data, finalize_hint) { + var _this = _super.call(this, envObject, value, initialRefcount, ownership) || this; + _this._finalizer = new Finalizer(envObject, finalize_callback, finalize_data, finalize_hint); + return _this; + } + ReferenceWithFinalizer.create = function (envObject, value, initialRefcount, ownership, finalize_callback, finalize_data, finalize_hint) { + var reference = new ReferenceWithFinalizer(envObject, value, initialRefcount, ownership, finalize_callback, finalize_data, finalize_hint); + envObject.ctx.refStore.add(reference); + reference.link(envObject.finalizing_reflist); + return reference; + }; + ReferenceWithFinalizer.prototype.resetFinalizer = function () { + this._finalizer.resetFinalizer(); + }; + ReferenceWithFinalizer.prototype.data = function () { + return this._finalizer.data(); + }; + ReferenceWithFinalizer.prototype.callUserFinalizer = function () { + this._finalizer.callFinalizer(); + }; + ReferenceWithFinalizer.prototype.invokeFinalizerFromGC = function () { + this._finalizer.envObject.invokeFinalizerFromGC(this); + }; + ReferenceWithFinalizer.prototype.dispose = function () { + if (!this._finalizer) + return; + this._finalizer.envObject.dequeueFinalizer(this); + this._finalizer.dispose(); + _super.prototype.dispose.call(this); + this._finalizer = undefined; + }; + return ReferenceWithFinalizer; +}(Reference)); + +var Deferred = /*#__PURE__*/ (function () { + function Deferred(ctx, value) { + // Plain assignment would invoke inherited setters before these fields + // become own properties. + Object.defineProperties(this, { + id: { + configurable: true, + enumerable: true, + value: 0, + writable: true + }, + ctx: { + configurable: true, + enumerable: true, + value: ctx, + writable: true + }, + value: { + configurable: true, + enumerable: true, + value: value, + writable: true + } + }); + } + Deferred.create = function (ctx, value) { + var deferred = new Deferred(ctx, value); + ctx.deferredStore.add(deferred); + return deferred; + }; + Deferred.prototype.resolve = function (value) { + this.value.resolve(value); + this.dispose(); + }; + Deferred.prototype.reject = function (reason) { + this.value.reject(reason); + this.dispose(); + }; + Deferred.prototype.dispose = function () { + this.ctx.deferredStore.remove(this.id); + this.id = 0; + this.value = null; + this.ctx = null; + }; + return Deferred; +}()); + +var Store = /*#__PURE__*/ (function () { + function Store() { + this._values = [undefined]; + this._values.length = 4; + this._size = 1; + this._freeList = []; + } + Store.prototype.add = function (value) { + var id; + if (this._freeList.length) { + id = this._freeList.shift(); + } + else { + id = this._size; + this._size++; + var capacity = this._values.length; + if (id >= capacity) { + this._values.length = capacity + (capacity >> 1) + 16; + } + } + value.id = id; + this._values[id] = value; + }; + Store.prototype.get = function (id) { + return this._values[id]; + }; + Store.prototype.has = function (id) { + return this._values[id] !== undefined; + }; + Store.prototype.remove = function (id) { + var value = this._values[id]; + if (value) { + value.id = 0; + this._values[id] = undefined; + this._freeList.push(Number(id)); + } + }; + Store.prototype.dispose = function () { + for (var i = 1; i < this._size; ++i) { + var value = this._values[i]; + value === null || value === void 0 ? void 0 : value.dispose(); + } + this._values = [undefined]; + this._size = 1; + this._freeList = []; + }; + return Store; +}()); + +var kMaxReasonableBytes = BigInt(1) << BigInt(60); +var kMinReasonableBytes = -kMaxReasonableBytes; +var ExternalMemory = /*#__PURE__*/ (function () { + function ExternalMemory(onChange) { + this.total = BigInt(0); + this.onChange = onChange !== null && onChange !== void 0 ? onChange : null; + } + ExternalMemory.prototype.adjust = function (changeInBytes) { + changeInBytes = BigInt(changeInBytes); + if (!(kMinReasonableBytes <= changeInBytes && changeInBytes < kMaxReasonableBytes)) { + throw new RangeError("changeInBytes ".concat(changeInBytes, " is out of reasonable range")); + } + var old = this.total; + this.total += changeInBytes; + var amount = this.total; + var onChange = this.onChange; + if (changeInBytes) { + onChange === null || onChange === void 0 ? void 0 : onChange(amount, old, changeInBytes); + } + return amount; + }; + return ExternalMemory; +}()); + +var CleanupHookCallback = /*#__PURE__*/ (function () { + function CleanupHookCallback(envObject, fn, arg, order) { + this.envObject = envObject; + this.fn = fn; + this.arg = arg; + this.order = order; + } + return CleanupHookCallback; +}()); +var CleanupQueue = /*#__PURE__*/ (function () { + function CleanupQueue() { + this._cleanupHooks = []; + this._cleanupHookCounter = 0; + } + CleanupQueue.prototype.empty = function () { + return this._cleanupHooks.length === 0; + }; + CleanupQueue.prototype.add = function (envObject, fn, arg) { + if (this._cleanupHooks.filter(function (hook) { return (hook.envObject === envObject && hook.fn === fn && hook.arg === arg); }).length > 0) { + throw new Error('Can not add same fn and arg twice'); + } + this._cleanupHooks.push(new CleanupHookCallback(envObject, fn, arg, this._cleanupHookCounter++)); + }; + CleanupQueue.prototype.remove = function (envObject, fn, arg) { + for (var i = 0; i < this._cleanupHooks.length; ++i) { + var hook = this._cleanupHooks[i]; + if (hook.envObject === envObject && hook.fn === fn && hook.arg === arg) { + this._cleanupHooks.splice(i, 1); + return; + } + } + }; + CleanupQueue.prototype.drain = function () { + var hooks = this._cleanupHooks.slice(); + hooks.sort(function (a, b) { return (b.order - a.order); }); + for (var i = 0; i < hooks.length; ++i) { + var cb = hooks[i]; + if (typeof cb.fn === 'number') { + cb.envObject.makeDynCall_vp(cb.fn)(cb.arg); + } + else { + cb.fn(cb.arg); + } + this._cleanupHooks.splice(this._cleanupHooks.indexOf(cb), 1); + } + }; + CleanupQueue.prototype.dispose = function () { + this._cleanupHooks.length = 0; + this._cleanupHookCounter = 0; + }; + return CleanupQueue; +}()); +var NodejsWaitingRequestCounter = /*#__PURE__*/ (function () { + function NodejsWaitingRequestCounter() { + this.refHandle = new _MessageChannel().port1; + this.count = 0; + } + NodejsWaitingRequestCounter.prototype.increase = function () { + if (this.count === 0) { + if (this.refHandle.ref) { + this.refHandle.ref(); + } + } + this.count++; + }; + NodejsWaitingRequestCounter.prototype.decrease = function () { + if (this.count === 0) + return; + if (this.count === 1) { + if (this.refHandle.unref) { + this.refHandle.unref(); + } + } + this.count--; + }; + return NodejsWaitingRequestCounter; +}()); +var Context = /*#__PURE__*/ (function () { + function Context(options) { + var _this = this; + this._isStopping = false; + this._canCallIntoJs = true; + this._suppressDestroy = false; + this.envStore = new Store(); + this.scopeStore = new ScopeStore(); + this.refStore = new Store(); + this.deferredStore = new Store(); + this.handleStore = new HandleStore(); + this.feature = { + supportReflect: supportReflect, + supportFinalizer: supportFinalizer, + supportWeakSymbol: supportWeakSymbol, + supportBigInt: supportBigInt, + supportNewFunction: supportNewFunction, + canSetFunctionName: canSetFunctionName, + setImmediate: _setImmediate, + Buffer: _Buffer, + MessageChannel: _MessageChannel + }; + this.cleanupQueue = new CleanupQueue(); + this._externalMemory = new ExternalMemory(options === null || options === void 0 ? void 0 : options.onExternalMemoryChange); + if (typeof process === 'object' && process !== null && typeof process.once === 'function') { + this.refCounter = new NodejsWaitingRequestCounter(); + process.once('beforeExit', function () { + if (!_this._suppressDestroy) { + _this.destroy(); + } + }); + } + } + /** + * Suppress the destroy on `beforeExit` event in Node.js. + * Call this method if you want to keep the context and + * all associated {@link Env | Env} alive, + * this also means that cleanup hooks will not be called. + * After call this method, you should call + * {@link Context.destroy | `Context.prototype.destroy`} method manually. + */ + Context.prototype.suppressDestroy = function () { + this._suppressDestroy = true; + }; + // eslint-disable-next-line @typescript-eslint/explicit-function-return-type + Context.prototype.getRuntimeVersions = function () { + return { + version: version, + NODE_API_SUPPORTED_VERSION_MAX: NODE_API_SUPPORTED_VERSION_MAX, + NAPI_VERSION_EXPERIMENTAL: NAPI_VERSION_EXPERIMENTAL, + NODE_API_DEFAULT_MODULE_API_VERSION: NODE_API_DEFAULT_MODULE_API_VERSION + }; + }; + Context.prototype.createNotSupportWeakRefError = function (api, message) { + return new NotSupportWeakRefError(api, message); + }; + Context.prototype.createNotSupportBufferError = function (api, message) { + return new NotSupportBufferError(api, message); + }; + Context.prototype.createReference = function (envObject, handle_id, initialRefcount, ownership) { + return Reference.create(envObject, handle_id, initialRefcount, ownership); + }; + Context.prototype.createReferenceWithData = function (envObject, handle_id, initialRefcount, ownership, data) { + return ReferenceWithData.create(envObject, handle_id, initialRefcount, ownership, data); + }; + Context.prototype.createReferenceWithFinalizer = function (envObject, handle_id, initialRefcount, ownership, finalize_callback, finalize_data, finalize_hint) { + if (finalize_callback === void 0) { finalize_callback = 0; } + if (finalize_data === void 0) { finalize_data = 0; } + if (finalize_hint === void 0) { finalize_hint = 0; } + return ReferenceWithFinalizer.create(envObject, handle_id, initialRefcount, ownership, finalize_callback, finalize_data, finalize_hint); + }; + Context.prototype.createDeferred = function (value) { + return Deferred.create(this, value); + }; + Context.prototype.adjustAmountOfExternalAllocatedMemory = function (changeInBytes) { + return this._externalMemory.adjust(changeInBytes); + }; + Context.prototype.createEnv = function (filename, moduleApiVersion, makeDynCall_vppp, makeDynCall_vp, abort, nodeBinding) { + return newEnv(this, filename, moduleApiVersion, makeDynCall_vppp, makeDynCall_vp, abort, nodeBinding); + }; + Context.prototype.createTrackedFinalizer = function (envObject, finalize_callback, finalize_data, finalize_hint) { + return TrackedFinalizer.create(envObject, finalize_callback, finalize_data, finalize_hint); + }; + Context.prototype.getCurrentScope = function () { + return this.scopeStore.currentScope; + }; + Context.prototype.addToCurrentScope = function (value) { + return this.scopeStore.currentScope.add(value); + }; + Context.prototype.openScope = function (envObject) { + var scope = this.scopeStore.openScope(this.handleStore); + if (envObject) + envObject.openHandleScopes++; + return scope; + }; + Context.prototype.closeScope = function (envObject, _scope) { + if (envObject && envObject.openHandleScopes === 0) + return; + this.scopeStore.closeScope(); + if (envObject) + envObject.openHandleScopes--; + }; + Context.prototype.ensureHandle = function (value) { + switch (value) { + case undefined: return HandleStore.UNDEFINED; + case null: return HandleStore.NULL; + case true: return HandleStore.TRUE; + case false: return HandleStore.FALSE; + case _global: return HandleStore.GLOBAL; + } + return this.addToCurrentScope(value); + }; + Context.prototype.addCleanupHook = function (envObject, fn, arg) { + this.cleanupQueue.add(envObject, fn, arg); + }; + Context.prototype.removeCleanupHook = function (envObject, fn, arg) { + this.cleanupQueue.remove(envObject, fn, arg); + }; + Context.prototype.runCleanup = function () { + while (!this.cleanupQueue.empty()) { + this.cleanupQueue.drain(); + } + }; + Context.prototype.increaseWaitingRequestCounter = function () { + var _a; + (_a = this.refCounter) === null || _a === void 0 ? void 0 : _a.increase(); + }; + Context.prototype.decreaseWaitingRequestCounter = function () { + var _a; + (_a = this.refCounter) === null || _a === void 0 ? void 0 : _a.decrease(); + }; + Context.prototype.setCanCallIntoJs = function (value) { + this._canCallIntoJs = value; + }; + Context.prototype.setStopping = function (value) { + this._isStopping = value; + }; + Context.prototype.canCallIntoJs = function () { + return this._canCallIntoJs && !this._isStopping; + }; + /** + * Destroy the context and call cleanup hooks. + * Associated {@link Env | Env} will be destroyed. + */ + Context.prototype.destroy = function () { + this.setStopping(true); + this.setCanCallIntoJs(false); + this.runCleanup(); + }; + return Context; +}()); +var defaultContext; +function createContext(options) { + return new Context(options); +} +function getDefaultContext() { + if (!defaultContext) { + defaultContext = createContext(); + } + return defaultContext; +} + +export { ConstHandle, Context, Deferred, EmnapiError, Env, External, Finalizer, Handle, HandleScope, HandleStore, NAPI_VERSION_EXPERIMENTAL, NODE_API_DEFAULT_MODULE_API_VERSION, NODE_API_SUPPORTED_VERSION_MAX, NODE_API_SUPPORTED_VERSION_MIN, NodeEnv, NotSupportBufferError, NotSupportWeakRefError, Persistent, RefTracker, Reference, ReferenceOwnership, ReferenceWithData, ReferenceWithFinalizer, ScopeStore, Store, TrackedFinalizer, TryCatch, createContext, getDefaultContext, getExternalValue, isExternal, isReferenceType, version }; diff --git a/dg-ui/node_modules/@tailwindcss/oxide-wasm32-wasi/node_modules/@emnapi/runtime/dist/emnapi.iife.d.ts b/dg-ui/node_modules/@tailwindcss/oxide-wasm32-wasi/node_modules/@emnapi/runtime/dist/emnapi.iife.d.ts new file mode 100644 index 0000000..9387ce7 --- /dev/null +++ b/dg-ui/node_modules/@tailwindcss/oxide-wasm32-wasi/node_modules/@emnapi/runtime/dist/emnapi.iife.d.ts @@ -0,0 +1,426 @@ +declare namespace emnapi { + +export type CleanupHookCallbackFunction = number | ((arg: number) => void); + +export class ConstHandle extends Handle { + constructor(id: number, value: S); + dispose(): void; +} + +export class Context { + private _isStopping; + private _canCallIntoJs; + private _suppressDestroy; + envStore: Store; + scopeStore: ScopeStore; + refStore: Store; + deferredStore: Store>; + handleStore: HandleStore; + private readonly refCounter?; + private readonly cleanupQueue; + private readonly _externalMemory; + feature: { + supportReflect: boolean; + supportFinalizer: boolean; + supportWeakSymbol: boolean; + supportBigInt: boolean; + supportNewFunction: boolean; + canSetFunctionName: boolean; + setImmediate: (callback: () => void) => void; + Buffer: BufferCtor | undefined; + MessageChannel: { + new (): MessageChannel; + prototype: MessageChannel; + } | undefined; + }; + constructor(options?: ContextOptions); + /** + * Suppress the destroy on `beforeExit` event in Node.js. + * Call this method if you want to keep the context and + * all associated {@link Env | Env} alive, + * this also means that cleanup hooks will not be called. + * After call this method, you should call + * {@link Context.destroy | `Context.prototype.destroy`} method manually. + */ + suppressDestroy(): void; + getRuntimeVersions(): { + version: string; + NODE_API_SUPPORTED_VERSION_MAX: Version; + NAPI_VERSION_EXPERIMENTAL: Version; + NODE_API_DEFAULT_MODULE_API_VERSION: Version; + }; + createNotSupportWeakRefError(api: string, message: string): NotSupportWeakRefError; + createNotSupportBufferError(api: string, message: string): NotSupportBufferError; + createReference(envObject: Env, handle_id: napi_value, initialRefcount: uint32_t, ownership: ReferenceOwnership): Reference; + createReferenceWithData(envObject: Env, handle_id: napi_value, initialRefcount: uint32_t, ownership: ReferenceOwnership, data: void_p): Reference; + createReferenceWithFinalizer(envObject: Env, handle_id: napi_value, initialRefcount: uint32_t, ownership: ReferenceOwnership, finalize_callback?: napi_finalize, finalize_data?: void_p, finalize_hint?: void_p): Reference; + createDeferred(value: IDeferrdValue): Deferred; + adjustAmountOfExternalAllocatedMemory(changeInBytes: number | bigint): bigint; + createEnv(filename: string, moduleApiVersion: number, makeDynCall_vppp: (cb: Ptr) => (a: Ptr, b: Ptr, c: Ptr) => void, makeDynCall_vp: (cb: Ptr) => (a: Ptr) => void, abort: (msg?: string) => never, nodeBinding?: any): Env; + createTrackedFinalizer(envObject: Env, finalize_callback: napi_finalize, finalize_data: void_p, finalize_hint: void_p): TrackedFinalizer; + getCurrentScope(): HandleScope | null; + addToCurrentScope(value: V): Handle; + openScope(envObject?: Env): HandleScope; + closeScope(envObject?: Env, _scope?: HandleScope): void; + ensureHandle(value: S): Handle; + addCleanupHook(envObject: Env, fn: CleanupHookCallbackFunction, arg: number): void; + removeCleanupHook(envObject: Env, fn: CleanupHookCallbackFunction, arg: number): void; + runCleanup(): void; + increaseWaitingRequestCounter(): void; + decreaseWaitingRequestCounter(): void; + setCanCallIntoJs(value: boolean): void; + setStopping(value: boolean): void; + canCallIntoJs(): boolean; + /** + * Destroy the context and call cleanup hooks. + * Associated {@link Env | Env} will be destroyed. + */ + destroy(): void; +} + +export interface ContextOptions { + onExternalMemoryChange?: (current: bigint, old: bigint, delta: bigint) => any; +} + +export function createContext(options?: ContextOptions): Context; + +export class Deferred implements IStoreValue { + static create(ctx: Context, value: IDeferrdValue): Deferred; + id: number; + ctx: Context; + value: IDeferrdValue; + constructor(ctx: Context, value: IDeferrdValue); + resolve(value: T): void; + reject(reason?: any): void; + dispose(): void; +} + +export class EmnapiError extends Error { + constructor(message?: string); +} + +export abstract class Env implements IStoreValue { + readonly ctx: Context; + moduleApiVersion: number; + makeDynCall_vppp: (cb: Ptr) => (a: Ptr, b: Ptr, c: Ptr) => void; + makeDynCall_vp: (cb: Ptr) => (a: Ptr) => void; + abort: (msg?: string) => never; + id: number; + openHandleScopes: number; + instanceData: TrackedFinalizer | null; + tryCatch: TryCatch; + refs: number; + reflist: RefTracker; + finalizing_reflist: RefTracker; + pendingFinalizers: RefTracker[]; + lastError: { + errorCode: napi_status; + engineErrorCode: number; + engineReserved: Ptr; + }; + inGcFinalizer: boolean; + constructor(ctx: Context, moduleApiVersion: number, makeDynCall_vppp: (cb: Ptr) => (a: Ptr, b: Ptr, c: Ptr) => void, makeDynCall_vp: (cb: Ptr) => (a: Ptr) => void, abort: (msg?: string) => never); + /** @virtual */ + canCallIntoJs(): boolean; + terminatedOrTerminating(): boolean; + ref(): void; + unref(): void; + ensureHandle(value: S): Handle; + ensureHandleId(value: any): napi_value; + clearLastError(): napi_status; + setLastError(error_code: napi_status, engine_error_code?: uint32_t, engine_reserved?: void_p): napi_status; + getReturnStatus(): napi_status; + callIntoModule(fn: (env: Env) => T, handleException?: (envObject: Env, value: any) => void): T; + /** @virtual */ + abstract callFinalizer(cb: napi_finalize, data: void_p, hint: void_p): void; + invokeFinalizerFromGC(finalizer: RefTracker): void; + checkGCAccess(): void; + /** @virtual */ + enqueueFinalizer(finalizer: RefTracker): void; + /** @virtual */ + dequeueFinalizer(finalizer: RefTracker): void; + /** @virtual */ + deleteMe(): void; + dispose(): void; + private readonly _bindingMap; + initObjectBinding(value: S): IReferenceBinding; + getObjectBinding(value: S): IReferenceBinding; + setInstanceData(data: number, finalize_cb: number, finalize_hint: number): void; + getInstanceData(): number; +} + +/** @public */ +interface External_2 extends Record { +} + +/** @public */ +const External_2: { + new (value: number | bigint): External_2; + prototype: null; +}; +export { External_2 as External } + +export class Finalizer { + envObject: Env; + private _finalizeCallback; + private _finalizeData; + private _finalizeHint; + private _makeDynCall_vppp; + constructor(envObject: Env, _finalizeCallback?: napi_finalize, _finalizeData?: void_p, _finalizeHint?: void_p); + callback(): napi_finalize; + data(): void_p; + hint(): void_p; + resetEnv(): void; + resetFinalizer(): void; + callFinalizer(): void; + dispose(): void; +} + +export function getDefaultContext(): Context; + +/** @public */ +export function getExternalValue(external: External_2): number | bigint; + +export class Handle { + id: number; + value: S; + constructor(id: number, value: S); + data(): void_p; + isNumber(): boolean; + isBigInt(): boolean; + isString(): boolean; + isFunction(): boolean; + isExternal(): boolean; + isObject(): boolean; + isArray(): boolean; + isArrayBuffer(): boolean; + isTypedArray(): boolean; + isBuffer(BufferConstructor?: BufferCtor): boolean; + isDataView(): boolean; + isDate(): boolean; + isPromise(): boolean; + isBoolean(): boolean; + isUndefined(): boolean; + isSymbol(): boolean; + isNull(): boolean; + dispose(): void; +} + +export class HandleScope { + handleStore: HandleStore; + id: number; + parent: HandleScope | null; + child: HandleScope | null; + start: number; + end: number; + private _escapeCalled; + callbackInfo: ICallbackInfo; + constructor(handleStore: HandleStore, id: number, parentScope: HandleScope | null, start: number, end?: number); + add(value: V): Handle; + addExternal(data: void_p): Handle; + dispose(): void; + escape(handle: number): Handle | null; + escapeCalled(): boolean; +} + +export class HandleStore { + static UNDEFINED: ConstHandle; + static NULL: ConstHandle; + static FALSE: ConstHandle; + static TRUE: ConstHandle; + static GLOBAL: ConstHandle; + static MIN_ID: 6; + private readonly _values; + private _next; + push(value: S): Handle; + erase(start: number, end: number): void; + get(id: Ptr): Handle | undefined; + swap(a: number, b: number): void; + dispose(): void; +} + +export interface ICallbackInfo { + thiz: any; + data: void_p; + args: ArrayLike; + fn: Function; +} + +export interface IDeferrdValue { + resolve: (value: T) => void; + reject: (reason?: any) => void; +} + +export interface IReferenceBinding { + wrapped: number; + tag: Uint32Array | null; +} + +/** @public */ +export function isExternal(object: unknown): object is External_2; + +export function isReferenceType(v: any): v is object; + +export interface IStoreValue { + id: number; + dispose(): void; + [x: string]: any; +} + +export const NAPI_VERSION_EXPERIMENTAL = Version.NAPI_VERSION_EXPERIMENTAL; + +export const NODE_API_DEFAULT_MODULE_API_VERSION = Version.NODE_API_DEFAULT_MODULE_API_VERSION; + +export const NODE_API_SUPPORTED_VERSION_MAX = Version.NODE_API_SUPPORTED_VERSION_MAX; + +export const NODE_API_SUPPORTED_VERSION_MIN = Version.NODE_API_SUPPORTED_VERSION_MIN; + +export class NodeEnv extends Env { + filename: string; + private readonly nodeBinding?; + destructing: boolean; + finalizationScheduled: boolean; + constructor(ctx: Context, filename: string, moduleApiVersion: number, makeDynCall_vppp: (cb: Ptr) => (a: Ptr, b: Ptr, c: Ptr) => void, makeDynCall_vp: (cb: Ptr) => (a: Ptr) => void, abort: (msg?: string) => never, nodeBinding?: any); + deleteMe(): void; + canCallIntoJs(): boolean; + triggerFatalException(err: any): void; + callbackIntoModule(enforceUncaughtExceptionPolicy: boolean, fn: (env: Env) => T): T; + callFinalizer(cb: napi_finalize, data: void_p, hint: void_p): void; + callFinalizerInternal(forceUncaught: int, cb: napi_finalize, data: void_p, hint: void_p): void; + enqueueFinalizer(finalizer: RefTracker): void; + drainFinalizerQueue(): void; +} + +export class NotSupportBufferError extends EmnapiError { + constructor(api: string, message: string); +} + +export class NotSupportWeakRefError extends EmnapiError { + constructor(api: string, message: string); +} + +export class Persistent { + private _ref; + private _param; + private _callback; + private static readonly _registry; + constructor(value: T); + setWeak

(param: P, callback: (param: P) => void): void; + clearWeak(): void; + reset(): void; + isEmpty(): boolean; + deref(): T | undefined; +} + +export class Reference extends RefTracker implements IStoreValue { + private static weakCallback; + id: number; + envObject: Env; + private readonly canBeWeak; + private _refcount; + private readonly _ownership; + persistent: Persistent; + static create(envObject: Env, handle_id: napi_value, initialRefcount: uint32_t, ownership: ReferenceOwnership, _unused1?: void_p, _unused2?: void_p, _unused3?: void_p): Reference; + protected constructor(envObject: Env, handle_id: napi_value, initialRefcount: uint32_t, ownership: ReferenceOwnership); + ref(): number; + unref(): number; + get(envObject?: Env): napi_value; + /** @virtual */ + resetFinalizer(): void; + /** @virtual */ + data(): void_p; + refcount(): number; + ownership(): ReferenceOwnership; + /** @virtual */ + protected callUserFinalizer(): void; + /** @virtual */ + protected invokeFinalizerFromGC(): void; + private _setWeak; + finalize(): void; + dispose(): void; +} + +export enum ReferenceOwnership { + kRuntime = 0, + kUserland = 1 +} + +export class ReferenceWithData extends Reference { + private readonly _data; + static create(envObject: Env, value: napi_value, initialRefcount: uint32_t, ownership: ReferenceOwnership, data: void_p): ReferenceWithData; + private constructor(); + data(): void_p; +} + +export class ReferenceWithFinalizer extends Reference { + private _finalizer; + static create(envObject: Env, value: napi_value, initialRefcount: uint32_t, ownership: ReferenceOwnership, finalize_callback: napi_finalize, finalize_data: void_p, finalize_hint: void_p): ReferenceWithFinalizer; + private constructor(); + resetFinalizer(): void; + data(): void_p; + protected callUserFinalizer(): void; + protected invokeFinalizerFromGC(): void; + dispose(): void; +} + +export class RefTracker { + /** @virtual */ + dispose(): void; + /** @virtual */ + finalize(): void; + private _next; + private _prev; + link(list: RefTracker): void; + unlink(): void; + static finalizeAll(list: RefTracker): void; +} + +export class ScopeStore { + private readonly _rootScope; + currentScope: HandleScope; + private readonly _values; + constructor(); + get(id: number): HandleScope | undefined; + openScope(handleStore: HandleStore): HandleScope; + closeScope(): void; + dispose(): void; +} + +export class Store { + protected _values: Array; + private _freeList; + private _size; + constructor(); + add(value: V): void; + get(id: Ptr): V | undefined; + has(id: Ptr): boolean; + remove(id: Ptr): void; + dispose(): void; +} + +export class TrackedFinalizer extends RefTracker { + private _finalizer; + static create(envObject: Env, finalize_callback: napi_finalize, finalize_data: void_p, finalize_hint: void_p): TrackedFinalizer; + private constructor(); + data(): void_p; + dispose(): void; + finalize(): void; +} + +export class TryCatch { + private _exception; + private _caught; + isEmpty(): boolean; + hasCaught(): boolean; + exception(): any; + setError(err: any): void; + reset(): void; + extractException(): any; +} + +export const version: string; + + + + +} \ No newline at end of file diff --git a/dg-ui/node_modules/@tailwindcss/oxide-wasm32-wasi/node_modules/@emnapi/runtime/dist/emnapi.iife.js b/dg-ui/node_modules/@tailwindcss/oxide-wasm32-wasi/node_modules/@emnapi/runtime/dist/emnapi.iife.js new file mode 100644 index 0000000..ea057ab --- /dev/null +++ b/dg-ui/node_modules/@tailwindcss/oxide-wasm32-wasi/node_modules/@emnapi/runtime/dist/emnapi.iife.js @@ -0,0 +1,1528 @@ +var emnapi = (function (exports) { + + /****************************************************************************** + Copyright (c) Microsoft Corporation. + + Permission to use, copy, modify, and/or distribute this software for any + purpose with or without fee is hereby granted. + + THE SOFTWARE IS PROVIDED "AS IS" AND THE AUTHOR DISCLAIMS ALL WARRANTIES WITH + REGARD TO THIS SOFTWARE INCLUDING ALL IMPLIED WARRANTIES OF MERCHANTABILITY + AND FITNESS. IN NO EVENT SHALL THE AUTHOR BE LIABLE FOR ANY SPECIAL, DIRECT, + INDIRECT, OR CONSEQUENTIAL DAMAGES OR ANY DAMAGES WHATSOEVER RESULTING FROM + LOSS OF USE, DATA OR PROFITS, WHETHER IN AN ACTION OF CONTRACT, NEGLIGENCE OR + OTHER TORTIOUS ACTION, ARISING OUT OF OR IN CONNECTION WITH THE USE OR + PERFORMANCE OF THIS SOFTWARE. + ***************************************************************************** */ + /* global Reflect, Promise, SuppressedError, Symbol, Iterator */ + + var extendStatics = function(d, b) { + extendStatics = Object.setPrototypeOf || + ({ __proto__: [] } instanceof Array && function (d, b) { d.__proto__ = b; }) || + function (d, b) { for (var p in b) if (Object.prototype.hasOwnProperty.call(b, p)) d[p] = b[p]; }; + return extendStatics(d, b); + }; + + function __extends(d, b) { + if (typeof b !== "function" && b !== null) + throw new TypeError("Class extends value " + String(b) + " is not a constructor or null"); + extendStatics(d, b); + function __() { this.constructor = d; } + d.prototype = b === null ? Object.create(b) : (__.prototype = b.prototype, new __()); + } + + typeof SuppressedError === "function" ? SuppressedError : function (error, suppressed, message) { + var e = new Error(message); + return e.name = "SuppressedError", e.error = error, e.suppressed = suppressed, e; + }; + + var externalValue = new WeakMap(); + /** @public */ + function isExternal(object) { + return externalValue.has(object); + } + /** @public */ // eslint-disable-next-line @typescript-eslint/no-redeclare + var External = (function () { + function External(value) { + Object.setPrototypeOf(this, null); + externalValue.set(this, value); + } + External.prototype = null; + return External; + })(); + /** @public */ + function getExternalValue(external) { + if (!isExternal(external)) { + throw new TypeError('not external'); + } + return externalValue.get(external); + } + + var supportNewFunction = /*#__PURE__*/ (function () { + var f; + try { + f = new Function(); + } + catch (_) { + return false; + } + return typeof f === 'function'; + })(); + var _global = /*#__PURE__*/ (function () { + if (typeof globalThis !== 'undefined') + return globalThis; + var g = (function () { return this; })(); + if (!g && supportNewFunction) { + try { + g = new Function('return this')(); + } + catch (_) { } + } + if (!g) { + if (typeof __webpack_public_path__ === 'undefined') { + if (typeof global !== 'undefined') + return global; + } + if (typeof window !== 'undefined') + return window; + if (typeof self !== 'undefined') + return self; + } + return g; + })(); + var TryCatch = /*#__PURE__*/ (function () { + function TryCatch() { + this._exception = undefined; + this._caught = false; + } + TryCatch.prototype.isEmpty = function () { + return !this._caught; + }; + TryCatch.prototype.hasCaught = function () { + return this._caught; + }; + TryCatch.prototype.exception = function () { + return this._exception; + }; + TryCatch.prototype.setError = function (err) { + this._caught = true; + this._exception = err; + }; + TryCatch.prototype.reset = function () { + this._caught = false; + this._exception = undefined; + }; + TryCatch.prototype.extractException = function () { + var e = this._exception; + this.reset(); + return e; + }; + return TryCatch; + }()); + var canSetFunctionName = /*#__PURE__*/ (function () { + var _a; + try { + return Boolean((_a = Object.getOwnPropertyDescriptor(Function.prototype, 'name')) === null || _a === void 0 ? void 0 : _a.configurable); + } + catch (_) { + return false; + } + })(); + var supportReflect = typeof Reflect === 'object'; + var supportFinalizer = (typeof FinalizationRegistry !== 'undefined') && (typeof WeakRef !== 'undefined'); + var supportWeakSymbol = /*#__PURE__*/ (function () { + try { + // eslint-disable-next-line symbol-description + var sym = Symbol(); + // eslint-disable-next-line no-new + new WeakRef(sym); + new WeakMap().set(sym, undefined); + } + catch (_) { + return false; + } + return true; + })(); + var supportBigInt = typeof BigInt !== 'undefined'; + function isReferenceType(v) { + return (typeof v === 'object' && v !== null) || typeof v === 'function'; + } + var _require = /*#__PURE__*/ (function () { + var nativeRequire; + if (typeof __webpack_public_path__ !== 'undefined') { + nativeRequire = (function () { + return typeof __non_webpack_require__ !== 'undefined' ? __non_webpack_require__ : undefined; + })(); + } + else { + nativeRequire = (function () { + return typeof __webpack_public_path__ !== 'undefined' ? (typeof __non_webpack_require__ !== 'undefined' ? __non_webpack_require__ : undefined) : (typeof require !== 'undefined' ? require : undefined); + })(); + } + return nativeRequire; + })(); + var _MessageChannel = typeof MessageChannel === 'function' + ? MessageChannel + : /*#__PURE__*/ (function () { + try { + return _require('worker_threads').MessageChannel; + } + catch (_) { } + return undefined; + })(); + var _setImmediate = typeof setImmediate === 'function' + ? setImmediate.bind(_global) + : function (callback) { + if (typeof callback !== 'function') { + throw new TypeError('The "callback" argument must be of type function'); + } + if (_MessageChannel) { + var channel_1 = new _MessageChannel(); + channel_1.port1.onmessage = function () { + channel_1.port1.onmessage = null; + channel_1 = undefined; + callback(); + }; + channel_1.port2.postMessage(null); + } + else { + setTimeout(callback, 0); + } + }; + var _Buffer = typeof Buffer === 'function' + ? Buffer + : /*#__PURE__*/ (function () { + try { + return _require('buffer').Buffer; + } + catch (_) { } + return undefined; + })(); + var version = "1.11.3"; + var NODE_API_SUPPORTED_VERSION_MIN = 1 /* Version.NODE_API_SUPPORTED_VERSION_MIN */; + var NODE_API_SUPPORTED_VERSION_MAX = 10 /* Version.NODE_API_SUPPORTED_VERSION_MAX */; + var NAPI_VERSION_EXPERIMENTAL = 2147483647 /* Version.NAPI_VERSION_EXPERIMENTAL */; + var NODE_API_DEFAULT_MODULE_API_VERSION = 8 /* Version.NODE_API_DEFAULT_MODULE_API_VERSION */; + + var Handle = /*#__PURE__*/ (function () { + function Handle(id, value) { + this.id = id; + this.value = value; + } + Handle.prototype.data = function () { + return getExternalValue(this.value); + }; + Handle.prototype.isNumber = function () { + return typeof this.value === 'number'; + }; + Handle.prototype.isBigInt = function () { + return typeof this.value === 'bigint'; + }; + Handle.prototype.isString = function () { + return typeof this.value === 'string'; + }; + Handle.prototype.isFunction = function () { + return typeof this.value === 'function'; + }; + Handle.prototype.isExternal = function () { + return isExternal(this.value); + }; + Handle.prototype.isObject = function () { + return typeof this.value === 'object' && this.value !== null; + }; + Handle.prototype.isArray = function () { + return Array.isArray(this.value); + }; + Handle.prototype.isArrayBuffer = function () { + return (this.value instanceof ArrayBuffer); + }; + Handle.prototype.isTypedArray = function () { + return (ArrayBuffer.isView(this.value)) && !(this.value instanceof DataView); + }; + Handle.prototype.isBuffer = function (BufferConstructor) { + if (ArrayBuffer.isView(this.value)) + return true; + BufferConstructor !== null && BufferConstructor !== void 0 ? BufferConstructor : (BufferConstructor = _Buffer); + return typeof BufferConstructor === 'function' && BufferConstructor.isBuffer(this.value); + }; + Handle.prototype.isDataView = function () { + return (this.value instanceof DataView); + }; + Handle.prototype.isDate = function () { + return (this.value instanceof Date); + }; + Handle.prototype.isPromise = function () { + return (this.value instanceof Promise); + }; + Handle.prototype.isBoolean = function () { + return typeof this.value === 'boolean'; + }; + Handle.prototype.isUndefined = function () { + return this.value === undefined; + }; + Handle.prototype.isSymbol = function () { + return typeof this.value === 'symbol'; + }; + Handle.prototype.isNull = function () { + return this.value === null; + }; + Handle.prototype.dispose = function () { + this.value = undefined; + }; + return Handle; + }()); + var ConstHandle = /*#__PURE__*/ (function (_super) { + __extends(ConstHandle, _super); + function ConstHandle(id, value) { + return _super.call(this, id, value) || this; + } + ConstHandle.prototype.dispose = function () { }; + return ConstHandle; + }(Handle)); + var HandleStore = /*#__PURE__*/ (function () { + function HandleStore() { + this._values = [ + undefined, + HandleStore.UNDEFINED, + HandleStore.NULL, + HandleStore.FALSE, + HandleStore.TRUE, + HandleStore.GLOBAL + ]; + this._next = HandleStore.MIN_ID; + } + HandleStore.prototype.push = function (value) { + var h; + var next = this._next; + var values = this._values; + if (next < values.length) { + h = values[next]; + h.value = value; + } + else { + h = new Handle(next, value); + values[next] = h; + } + this._next++; + return h; + }; + HandleStore.prototype.erase = function (start, end) { + this._next = start; + var values = this._values; + for (var i = start; i < end; ++i) { + values[i].dispose(); + } + }; + HandleStore.prototype.get = function (id) { + return this._values[id]; + }; + HandleStore.prototype.swap = function (a, b) { + var values = this._values; + var h = values[a]; + values[a] = values[b]; + values[a].id = Number(a); + values[b] = h; + h.id = Number(b); + }; + HandleStore.prototype.dispose = function () { + this._values.length = HandleStore.MIN_ID; + this._next = HandleStore.MIN_ID; + }; + HandleStore.UNDEFINED = new ConstHandle(1 /* GlobalHandle.UNDEFINED */, undefined); + HandleStore.NULL = new ConstHandle(2 /* GlobalHandle.NULL */, null); + HandleStore.FALSE = new ConstHandle(3 /* GlobalHandle.FALSE */, false); + HandleStore.TRUE = new ConstHandle(4 /* GlobalHandle.TRUE */, true); + HandleStore.GLOBAL = new ConstHandle(5 /* GlobalHandle.GLOBAL */, _global); + HandleStore.MIN_ID = 6; + return HandleStore; + }()); + + var HandleScope = /*#__PURE__*/ (function () { + function HandleScope(handleStore, id, parentScope, start, end) { + if (end === void 0) { end = start; } + this.handleStore = handleStore; + this.id = id; + this.parent = parentScope; + this.child = null; + if (parentScope !== null) + parentScope.child = this; + this.start = start; + this.end = end; + this._escapeCalled = false; + this.callbackInfo = { + thiz: undefined, + data: 0, + args: undefined, + fn: undefined + }; + } + HandleScope.prototype.add = function (value) { + var h = this.handleStore.push(value); + this.end++; + return h; + }; + HandleScope.prototype.addExternal = function (data) { + return this.add(new External(data)); + }; + HandleScope.prototype.dispose = function () { + if (this._escapeCalled) + this._escapeCalled = false; + if (this.start === this.end) + return; + this.handleStore.erase(this.start, this.end); + }; + HandleScope.prototype.escape = function (handle) { + if (this._escapeCalled) + return null; + this._escapeCalled = true; + if (handle < this.start || handle >= this.end) { + return null; + } + this.handleStore.swap(handle, this.start); + var h = this.handleStore.get(this.start); + this.start++; + this.parent.end++; + return h; + }; + HandleScope.prototype.escapeCalled = function () { + return this._escapeCalled; + }; + return HandleScope; + }()); + + var ScopeStore = /*#__PURE__*/ (function () { + function ScopeStore() { + this._rootScope = new HandleScope(null, 0, null, 1, HandleStore.MIN_ID); + this.currentScope = this._rootScope; + this._values = [undefined]; + } + ScopeStore.prototype.get = function (id) { + return this._values[id]; + }; + ScopeStore.prototype.openScope = function (handleStore) { + var currentScope = this.currentScope; + var scope = currentScope.child; + if (scope !== null) { + scope.start = scope.end = currentScope.end; + } + else { + var id = currentScope.id + 1; + scope = new HandleScope(handleStore, id, currentScope, currentScope.end); + this._values[id] = scope; + } + this.currentScope = scope; + return scope; + }; + ScopeStore.prototype.closeScope = function () { + var scope = this.currentScope; + this.currentScope = scope.parent; + scope.dispose(); + }; + ScopeStore.prototype.dispose = function () { + this.currentScope = this._rootScope; + this._values.length = 1; + }; + return ScopeStore; + }()); + + var RefTracker = /*#__PURE__*/ (function () { + function RefTracker() { + this._next = null; + this._prev = null; + } + /** @virtual */ + RefTracker.prototype.dispose = function () { }; + /** @virtual */ + RefTracker.prototype.finalize = function () { }; + RefTracker.prototype.link = function (list) { + this._prev = list; + this._next = list._next; + if (this._next !== null) { + this._next._prev = this; + } + list._next = this; + }; + RefTracker.prototype.unlink = function () { + if (this._prev !== null) { + this._prev._next = this._next; + } + if (this._next !== null) { + this._next._prev = this._prev; + } + this._prev = null; + this._next = null; + }; + RefTracker.finalizeAll = function (list) { + while (list._next !== null) { + list._next.finalize(); + } + }; + return RefTracker; + }()); + + var Finalizer = /*#__PURE__*/ (function () { + function Finalizer(envObject, _finalizeCallback, _finalizeData, _finalizeHint) { + if (_finalizeCallback === void 0) { _finalizeCallback = 0; } + if (_finalizeData === void 0) { _finalizeData = 0; } + if (_finalizeHint === void 0) { _finalizeHint = 0; } + this.envObject = envObject; + this._finalizeCallback = _finalizeCallback; + this._finalizeData = _finalizeData; + this._finalizeHint = _finalizeHint; + this._makeDynCall_vppp = envObject.makeDynCall_vppp; + } + Finalizer.prototype.callback = function () { return this._finalizeCallback; }; + Finalizer.prototype.data = function () { return this._finalizeData; }; + Finalizer.prototype.hint = function () { return this._finalizeHint; }; + Finalizer.prototype.resetEnv = function () { + this.envObject = undefined; + }; + Finalizer.prototype.resetFinalizer = function () { + this._finalizeCallback = 0; + this._finalizeData = 0; + this._finalizeHint = 0; + }; + Finalizer.prototype.callFinalizer = function () { + var finalize_callback = this._finalizeCallback; + var finalize_data = this._finalizeData; + var finalize_hint = this._finalizeHint; + this.resetFinalizer(); + if (!finalize_callback) + return; + var fini = Number(finalize_callback); + if (!this.envObject) { + this._makeDynCall_vppp(fini)(0, finalize_data, finalize_hint); + } + else { + this.envObject.callFinalizer(fini, finalize_data, finalize_hint); + } + }; + Finalizer.prototype.dispose = function () { + this.envObject = undefined; + this._makeDynCall_vppp = undefined; + }; + return Finalizer; + }()); + + var TrackedFinalizer = /*#__PURE__*/ (function (_super) { + __extends(TrackedFinalizer, _super); + function TrackedFinalizer(envObject, finalize_callback, finalize_data, finalize_hint) { + var _this = _super.call(this) || this; + _this._finalizer = new Finalizer(envObject, finalize_callback, finalize_data, finalize_hint); + return _this; + } + TrackedFinalizer.create = function (envObject, finalize_callback, finalize_data, finalize_hint) { + var finalizer = new TrackedFinalizer(envObject, finalize_callback, finalize_data, finalize_hint); + finalizer.link(envObject.finalizing_reflist); + return finalizer; + }; + TrackedFinalizer.prototype.data = function () { + return this._finalizer.data(); + }; + TrackedFinalizer.prototype.dispose = function () { + if (!this._finalizer) + return; + this.unlink(); + this._finalizer.envObject.dequeueFinalizer(this); + this._finalizer.dispose(); + this._finalizer = undefined; + _super.prototype.dispose.call(this); + }; + TrackedFinalizer.prototype.finalize = function () { + this.unlink(); + var error; + var caught = false; + try { + this._finalizer.callFinalizer(); + } + catch (err) { + caught = true; + error = err; + } + this.dispose(); + if (caught) { + throw error; + } + }; + return TrackedFinalizer; + }(RefTracker)); + + function throwNodeApiVersionError(moduleName, moduleApiVersion) { + var errorMessage = "".concat(moduleName, " requires Node-API version ").concat(moduleApiVersion, ", but this version of Node.js only supports version ").concat(NODE_API_SUPPORTED_VERSION_MAX, " add-ons."); + throw new Error(errorMessage); + } + function handleThrow(envObject, value) { + if (envObject.terminatedOrTerminating()) { + return; + } + throw value; + } + var Env = /*#__PURE__*/ (function () { + function Env(ctx, moduleApiVersion, makeDynCall_vppp, makeDynCall_vp, abort) { + this.ctx = ctx; + this.moduleApiVersion = moduleApiVersion; + this.makeDynCall_vppp = makeDynCall_vppp; + this.makeDynCall_vp = makeDynCall_vp; + this.abort = abort; + this.openHandleScopes = 0; + this.instanceData = null; + this.tryCatch = new TryCatch(); + this.refs = 1; + this.reflist = new RefTracker(); + this.finalizing_reflist = new RefTracker(); + this.pendingFinalizers = []; + this.lastError = { + errorCode: 0 /* napi_status.napi_ok */, + engineErrorCode: 0, + engineReserved: 0 + }; + this.inGcFinalizer = false; + this._bindingMap = new WeakMap(); + this.id = 0; + } + /** @virtual */ + Env.prototype.canCallIntoJs = function () { + return true; + }; + Env.prototype.terminatedOrTerminating = function () { + return !this.canCallIntoJs(); + }; + Env.prototype.ref = function () { + this.refs++; + }; + Env.prototype.unref = function () { + this.refs--; + if (this.refs === 0) { + this.dispose(); + } + }; + Env.prototype.ensureHandle = function (value) { + return this.ctx.ensureHandle(value); + }; + Env.prototype.ensureHandleId = function (value) { + return this.ensureHandle(value).id; + }; + Env.prototype.clearLastError = function () { + var lastError = this.lastError; + if (lastError.errorCode !== 0 /* napi_status.napi_ok */) + lastError.errorCode = 0 /* napi_status.napi_ok */; + if (lastError.engineErrorCode !== 0) + lastError.engineErrorCode = 0; + if (lastError.engineReserved !== 0) + lastError.engineReserved = 0; + return 0 /* napi_status.napi_ok */; + }; + Env.prototype.setLastError = function (error_code, engine_error_code, engine_reserved) { + if (engine_error_code === void 0) { engine_error_code = 0; } + if (engine_reserved === void 0) { engine_reserved = 0; } + var lastError = this.lastError; + if (lastError.errorCode !== error_code) + lastError.errorCode = error_code; + if (lastError.engineErrorCode !== engine_error_code) + lastError.engineErrorCode = engine_error_code; + if (lastError.engineReserved !== engine_reserved) + lastError.engineReserved = engine_reserved; + return error_code; + }; + Env.prototype.getReturnStatus = function () { + return !this.tryCatch.hasCaught() ? 0 /* napi_status.napi_ok */ : this.setLastError(10 /* napi_status.napi_pending_exception */); + }; + Env.prototype.callIntoModule = function (fn, handleException) { + if (handleException === void 0) { handleException = handleThrow; } + var openHandleScopesBefore = this.openHandleScopes; + this.clearLastError(); + var r = fn(this); + if (openHandleScopesBefore !== this.openHandleScopes) { + this.abort('open_handle_scopes != open_handle_scopes_before'); + } + if (this.tryCatch.hasCaught()) { + var err = this.tryCatch.extractException(); + handleException(this, err); + } + return r; + }; + Env.prototype.invokeFinalizerFromGC = function (finalizer) { + if (this.moduleApiVersion !== NAPI_VERSION_EXPERIMENTAL) { + this.enqueueFinalizer(finalizer); + } + else { + var saved = this.inGcFinalizer; + this.inGcFinalizer = true; + try { + finalizer.finalize(); + } + finally { + this.inGcFinalizer = saved; + } + } + }; + Env.prototype.checkGCAccess = function () { + if (this.moduleApiVersion === NAPI_VERSION_EXPERIMENTAL && this.inGcFinalizer) { + this.abort('Finalizer is calling a function that may affect GC state.\n' + + 'The finalizers are run directly from GC and must not affect GC ' + + 'state.\n' + + 'Use `node_api_post_finalizer` from inside of the finalizer to work ' + + 'around this issue.\n' + + 'It schedules the call as a new task in the event loop.'); + } + }; + /** @virtual */ + Env.prototype.enqueueFinalizer = function (finalizer) { + if (this.pendingFinalizers.indexOf(finalizer) === -1) { + this.pendingFinalizers.push(finalizer); + } + }; + /** @virtual */ + Env.prototype.dequeueFinalizer = function (finalizer) { + var index = this.pendingFinalizers.indexOf(finalizer); + if (index !== -1) { + this.pendingFinalizers.splice(index, 1); + } + }; + /** @virtual */ + Env.prototype.deleteMe = function () { + RefTracker.finalizeAll(this.finalizing_reflist); + RefTracker.finalizeAll(this.reflist); + this.tryCatch.extractException(); + this.ctx.envStore.remove(this.id); + }; + Env.prototype.dispose = function () { + if (this.id === 0) + return; + this.deleteMe(); + this.finalizing_reflist.dispose(); + this.reflist.dispose(); + this.id = 0; + }; + Env.prototype.initObjectBinding = function (value) { + var binding = { + wrapped: 0, + tag: null + }; + this._bindingMap.set(value, binding); + return binding; + }; + Env.prototype.getObjectBinding = function (value) { + if (this._bindingMap.has(value)) { + return this._bindingMap.get(value); + } + return this.initObjectBinding(value); + }; + Env.prototype.setInstanceData = function (data, finalize_cb, finalize_hint) { + if (this.instanceData) { + this.instanceData.dispose(); + } + this.instanceData = TrackedFinalizer.create(this, finalize_cb, data, finalize_hint); + }; + Env.prototype.getInstanceData = function () { + return this.instanceData ? this.instanceData.data() : 0; + }; + return Env; + }()); + var NodeEnv = /*#__PURE__*/ (function (_super) { + __extends(NodeEnv, _super); + function NodeEnv(ctx, filename, moduleApiVersion, makeDynCall_vppp, makeDynCall_vp, abort, nodeBinding) { + var _this = _super.call(this, ctx, moduleApiVersion, makeDynCall_vppp, makeDynCall_vp, abort) || this; + _this.filename = filename; + _this.nodeBinding = nodeBinding; + _this.destructing = false; + _this.finalizationScheduled = false; + return _this; + } + NodeEnv.prototype.deleteMe = function () { + this.destructing = true; + this.drainFinalizerQueue(); + _super.prototype.deleteMe.call(this); + }; + NodeEnv.prototype.canCallIntoJs = function () { + return _super.prototype.canCallIntoJs.call(this) && this.ctx.canCallIntoJs(); + }; + NodeEnv.prototype.triggerFatalException = function (err) { + if (this.nodeBinding) { + this.nodeBinding.napi.fatalException(err); + } + else { + if (typeof process === 'object' && process !== null && typeof process._fatalException === 'function') { + var handled = process._fatalException(err); + if (!handled) { + console.error(err); + process.exit(1); + } + } + else { + throw err; + } + } + }; + NodeEnv.prototype.callbackIntoModule = function (enforceUncaughtExceptionPolicy, fn) { + return this.callIntoModule(fn, function (envObject, err) { + if (envObject.terminatedOrTerminating()) { + return; + } + var hasProcess = typeof process === 'object' && process !== null; + var hasForceFlag = hasProcess ? Boolean(process.execArgv && (process.execArgv.indexOf('--force-node-api-uncaught-exceptions-policy') !== -1)) : false; + if (envObject.moduleApiVersion < 10 && !hasForceFlag && !enforceUncaughtExceptionPolicy) { + var warn = hasProcess && typeof process.emitWarning === 'function' + ? process.emitWarning + : function (warning, type, code) { + if (warning instanceof Error) { + console.warn(warning.toString()); + } + else { + var prefix = code ? "[".concat(code, "] ") : ''; + // eslint-disable-next-line @typescript-eslint/prefer-nullish-coalescing + console.warn("".concat(prefix).concat(type || 'Warning', ": ").concat(warning)); + } + }; + warn('Uncaught Node-API callback exception detected, please run node with option --force-node-api-uncaught-exceptions-policy=true to handle those exceptions properly.', 'DeprecationWarning', 'DEP0168'); + return; + } + envObject.triggerFatalException(err); + }); + }; + NodeEnv.prototype.callFinalizer = function (cb, data, hint) { + this.callFinalizerInternal(1, cb, data, hint); + }; + NodeEnv.prototype.callFinalizerInternal = function (forceUncaught, cb, data, hint) { + var f = this.makeDynCall_vppp(cb); + var env = this.id; + var scope = this.ctx.openScope(this); + try { + this.callbackIntoModule(Boolean(forceUncaught), function () { f(env, data, hint); }); + } + finally { + this.ctx.closeScope(this, scope); + } + }; + NodeEnv.prototype.enqueueFinalizer = function (finalizer) { + var _this = this; + _super.prototype.enqueueFinalizer.call(this, finalizer); + if (!this.finalizationScheduled && !this.destructing) { + this.finalizationScheduled = true; + this.ref(); + _setImmediate(function () { + _this.finalizationScheduled = false; + _this.unref(); + _this.drainFinalizerQueue(); + }); + } + }; + NodeEnv.prototype.drainFinalizerQueue = function () { + while (this.pendingFinalizers.length > 0) { + var refTracker = this.pendingFinalizers.shift(); + refTracker.finalize(); + } + }; + return NodeEnv; + }(Env)); + function newEnv(ctx, filename, moduleApiVersion, makeDynCall_vppp, makeDynCall_vp, abort, nodeBinding) { + moduleApiVersion = typeof moduleApiVersion !== 'number' ? NODE_API_DEFAULT_MODULE_API_VERSION : moduleApiVersion; + // Validate module_api_version. + if (moduleApiVersion < NODE_API_DEFAULT_MODULE_API_VERSION) { + moduleApiVersion = NODE_API_DEFAULT_MODULE_API_VERSION; + } + else if (moduleApiVersion > NODE_API_SUPPORTED_VERSION_MAX && moduleApiVersion !== NAPI_VERSION_EXPERIMENTAL) { + throwNodeApiVersionError(filename, moduleApiVersion); + } + var env = new NodeEnv(ctx, filename, moduleApiVersion, makeDynCall_vppp, makeDynCall_vp, abort, nodeBinding); + ctx.envStore.add(env); + ctx.addCleanupHook(env, function () { env.unref(); }, 0); + return env; + } + + var EmnapiError = /*#__PURE__*/ (function (_super) { + __extends(EmnapiError, _super); + function EmnapiError(message) { + var _newTarget = this.constructor; + var _this = _super.call(this, message) || this; + var ErrorConstructor = _newTarget; + var proto = ErrorConstructor.prototype; + if (!(_this instanceof EmnapiError)) { + var setPrototypeOf = Object.setPrototypeOf; + if (typeof setPrototypeOf === 'function') { + setPrototypeOf.call(Object, _this, proto); + } + else { + // eslint-disable-next-line no-proto + _this.__proto__ = proto; + } + if (typeof Error.captureStackTrace === 'function') { + Error.captureStackTrace(_this, ErrorConstructor); + } + } + return _this; + } + return EmnapiError; + }(Error)); + Object.defineProperty(EmnapiError.prototype, 'name', { + configurable: true, + writable: true, + value: 'EmnapiError' + }); + var NotSupportWeakRefError = /*#__PURE__*/ (function (_super) { + __extends(NotSupportWeakRefError, _super); + function NotSupportWeakRefError(api, message) { + return _super.call(this, "".concat(api, ": The current runtime does not support \"FinalizationRegistry\" and \"WeakRef\".").concat(message ? " ".concat(message) : '')) || this; + } + return NotSupportWeakRefError; + }(EmnapiError)); + Object.defineProperty(NotSupportWeakRefError.prototype, 'name', { + configurable: true, + writable: true, + value: 'NotSupportWeakRefError' + }); + var NotSupportBufferError = /*#__PURE__*/ (function (_super) { + __extends(NotSupportBufferError, _super); + function NotSupportBufferError(api, message) { + return _super.call(this, "".concat(api, ": The current runtime does not support \"Buffer\". Consider using buffer polyfill to make sure `globalThis.Buffer` is defined.").concat(message ? " ".concat(message) : '')) || this; + } + return NotSupportBufferError; + }(EmnapiError)); + Object.defineProperty(NotSupportBufferError.prototype, 'name', { + configurable: true, + writable: true, + value: 'NotSupportBufferError' + }); + + var StrongRef = /*#__PURE__*/ (function () { + function StrongRef(value) { + this._value = value; + } + StrongRef.prototype.deref = function () { + return this._value; + }; + StrongRef.prototype.dispose = function () { + this._value = undefined; + }; + return StrongRef; + }()); + var Persistent = /*#__PURE__*/ (function () { + function Persistent(value) { + this._ref = new StrongRef(value); + } + Persistent.prototype.setWeak = function (param, callback) { + if (!supportFinalizer || this._ref === undefined || this._ref instanceof WeakRef) + return; + var value = this._ref.deref(); + try { + Persistent._registry.register(value, this, this); + var weakRef = new WeakRef(value); + this._ref.dispose(); + this._ref = weakRef; + this._param = param; + this._callback = callback; + } + catch (err) { + if (typeof value === 'symbol') ; + else { + throw err; + } + } + }; + Persistent.prototype.clearWeak = function () { + if (!supportFinalizer || this._ref === undefined) + return; + if (this._ref instanceof WeakRef) { + try { + Persistent._registry.unregister(this); + } + catch (_) { } + this._param = undefined; + this._callback = undefined; + var value = this._ref.deref(); + if (value === undefined) { + this._ref = value; + } + else { + this._ref = new StrongRef(value); + } + } + }; + Persistent.prototype.reset = function () { + if (supportFinalizer) { + try { + Persistent._registry.unregister(this); + } + catch (_) { } + } + this._param = undefined; + this._callback = undefined; + if (this._ref instanceof StrongRef) { + this._ref.dispose(); + } + this._ref = undefined; + }; + Persistent.prototype.isEmpty = function () { + return this._ref === undefined; + }; + Persistent.prototype.deref = function () { + if (this._ref === undefined) + return undefined; + return this._ref.deref(); + }; + Persistent._registry = supportFinalizer + ? new FinalizationRegistry(function (value) { + value._ref = undefined; + var callback = value._callback; + var param = value._param; + value._callback = undefined; + value._param = undefined; + if (typeof callback === 'function') { + callback(param); + } + }) + : undefined; + return Persistent; + }()); + + exports.ReferenceOwnership = void 0; + (function (ReferenceOwnership) { + ReferenceOwnership[ReferenceOwnership["kRuntime"] = 0] = "kRuntime"; + ReferenceOwnership[ReferenceOwnership["kUserland"] = 1] = "kUserland"; + })(exports.ReferenceOwnership || (exports.ReferenceOwnership = {})); + function canBeHeldWeakly(value) { + return value.isObject() || value.isFunction() || value.isSymbol(); + } + var Reference = /*#__PURE__*/ (function (_super) { + __extends(Reference, _super); + function Reference(envObject, handle_id, initialRefcount, ownership) { + var _this = _super.call(this) || this; + _this.envObject = envObject; + _this._refcount = initialRefcount; + _this._ownership = ownership; + var handle = envObject.ctx.handleStore.get(handle_id); + _this.canBeWeak = canBeHeldWeakly(handle); + _this.persistent = new Persistent(handle.value); + _this.id = 0; + if (initialRefcount === 0) { + _this._setWeak(); + } + return _this; + } + Reference.weakCallback = function (ref) { + ref.persistent.reset(); + ref.invokeFinalizerFromGC(); + }; + Reference.create = function (envObject, handle_id, initialRefcount, ownership, _unused1, _unused2, _unused3) { + var ref = new Reference(envObject, handle_id, initialRefcount, ownership); + envObject.ctx.refStore.add(ref); + ref.link(envObject.reflist); + return ref; + }; + Reference.prototype.ref = function () { + if (this.persistent.isEmpty()) { + return 0; + } + if (++this._refcount === 1 && this.canBeWeak) { + this.persistent.clearWeak(); + } + return this._refcount; + }; + Reference.prototype.unref = function () { + if (this.persistent.isEmpty() || this._refcount === 0) { + return 0; + } + if (--this._refcount === 0) { + this._setWeak(); + } + return this._refcount; + }; + Reference.prototype.get = function (envObject) { + if (envObject === void 0) { envObject = this.envObject; } + if (this.persistent.isEmpty()) { + return 0; + } + var obj = this.persistent.deref(); + var handle = envObject.ensureHandle(obj); + return handle.id; + }; + /** @virtual */ + Reference.prototype.resetFinalizer = function () { }; + /** @virtual */ + Reference.prototype.data = function () { return 0; }; + Reference.prototype.refcount = function () { return this._refcount; }; + Reference.prototype.ownership = function () { return this._ownership; }; + /** @virtual */ + Reference.prototype.callUserFinalizer = function () { }; + /** @virtual */ + Reference.prototype.invokeFinalizerFromGC = function () { + this.finalize(); + }; + Reference.prototype._setWeak = function () { + if (this.canBeWeak) { + this.persistent.setWeak(this, Reference.weakCallback); + } + else { + this.persistent.reset(); + } + }; + Reference.prototype.finalize = function () { + this.persistent.reset(); + var deleteMe = this._ownership === exports.ReferenceOwnership.kRuntime; + this.unlink(); + this.callUserFinalizer(); + if (deleteMe) { + this.dispose(); + } + }; + Reference.prototype.dispose = function () { + if (this.id === 0) + return; + this.unlink(); + this.persistent.reset(); + this.envObject.ctx.refStore.remove(this.id); + _super.prototype.dispose.call(this); + this.envObject = undefined; + this.id = 0; + }; + return Reference; + }(RefTracker)); + var ReferenceWithData = /*#__PURE__*/ (function (_super) { + __extends(ReferenceWithData, _super); + function ReferenceWithData(envObject, value, initialRefcount, ownership, _data) { + var _this = _super.call(this, envObject, value, initialRefcount, ownership) || this; + _this._data = _data; + return _this; + } + ReferenceWithData.create = function (envObject, value, initialRefcount, ownership, data) { + var reference = new ReferenceWithData(envObject, value, initialRefcount, ownership, data); + envObject.ctx.refStore.add(reference); + reference.link(envObject.reflist); + return reference; + }; + ReferenceWithData.prototype.data = function () { + return this._data; + }; + return ReferenceWithData; + }(Reference)); + var ReferenceWithFinalizer = /*#__PURE__*/ (function (_super) { + __extends(ReferenceWithFinalizer, _super); + function ReferenceWithFinalizer(envObject, value, initialRefcount, ownership, finalize_callback, finalize_data, finalize_hint) { + var _this = _super.call(this, envObject, value, initialRefcount, ownership) || this; + _this._finalizer = new Finalizer(envObject, finalize_callback, finalize_data, finalize_hint); + return _this; + } + ReferenceWithFinalizer.create = function (envObject, value, initialRefcount, ownership, finalize_callback, finalize_data, finalize_hint) { + var reference = new ReferenceWithFinalizer(envObject, value, initialRefcount, ownership, finalize_callback, finalize_data, finalize_hint); + envObject.ctx.refStore.add(reference); + reference.link(envObject.finalizing_reflist); + return reference; + }; + ReferenceWithFinalizer.prototype.resetFinalizer = function () { + this._finalizer.resetFinalizer(); + }; + ReferenceWithFinalizer.prototype.data = function () { + return this._finalizer.data(); + }; + ReferenceWithFinalizer.prototype.callUserFinalizer = function () { + this._finalizer.callFinalizer(); + }; + ReferenceWithFinalizer.prototype.invokeFinalizerFromGC = function () { + this._finalizer.envObject.invokeFinalizerFromGC(this); + }; + ReferenceWithFinalizer.prototype.dispose = function () { + if (!this._finalizer) + return; + this._finalizer.envObject.dequeueFinalizer(this); + this._finalizer.dispose(); + _super.prototype.dispose.call(this); + this._finalizer = undefined; + }; + return ReferenceWithFinalizer; + }(Reference)); + + var Deferred = /*#__PURE__*/ (function () { + function Deferred(ctx, value) { + // Plain assignment would invoke inherited setters before these fields + // become own properties. + Object.defineProperties(this, { + id: { + configurable: true, + enumerable: true, + value: 0, + writable: true + }, + ctx: { + configurable: true, + enumerable: true, + value: ctx, + writable: true + }, + value: { + configurable: true, + enumerable: true, + value: value, + writable: true + } + }); + } + Deferred.create = function (ctx, value) { + var deferred = new Deferred(ctx, value); + ctx.deferredStore.add(deferred); + return deferred; + }; + Deferred.prototype.resolve = function (value) { + this.value.resolve(value); + this.dispose(); + }; + Deferred.prototype.reject = function (reason) { + this.value.reject(reason); + this.dispose(); + }; + Deferred.prototype.dispose = function () { + this.ctx.deferredStore.remove(this.id); + this.id = 0; + this.value = null; + this.ctx = null; + }; + return Deferred; + }()); + + var Store = /*#__PURE__*/ (function () { + function Store() { + this._values = [undefined]; + this._values.length = 4; + this._size = 1; + this._freeList = []; + } + Store.prototype.add = function (value) { + var id; + if (this._freeList.length) { + id = this._freeList.shift(); + } + else { + id = this._size; + this._size++; + var capacity = this._values.length; + if (id >= capacity) { + this._values.length = capacity + (capacity >> 1) + 16; + } + } + value.id = id; + this._values[id] = value; + }; + Store.prototype.get = function (id) { + return this._values[id]; + }; + Store.prototype.has = function (id) { + return this._values[id] !== undefined; + }; + Store.prototype.remove = function (id) { + var value = this._values[id]; + if (value) { + value.id = 0; + this._values[id] = undefined; + this._freeList.push(Number(id)); + } + }; + Store.prototype.dispose = function () { + for (var i = 1; i < this._size; ++i) { + var value = this._values[i]; + value === null || value === void 0 ? void 0 : value.dispose(); + } + this._values = [undefined]; + this._size = 1; + this._freeList = []; + }; + return Store; + }()); + + var kMaxReasonableBytes = BigInt(1) << BigInt(60); + var kMinReasonableBytes = -kMaxReasonableBytes; + var ExternalMemory = /*#__PURE__*/ (function () { + function ExternalMemory(onChange) { + this.total = BigInt(0); + this.onChange = onChange !== null && onChange !== void 0 ? onChange : null; + } + ExternalMemory.prototype.adjust = function (changeInBytes) { + changeInBytes = BigInt(changeInBytes); + if (!(kMinReasonableBytes <= changeInBytes && changeInBytes < kMaxReasonableBytes)) { + throw new RangeError("changeInBytes ".concat(changeInBytes, " is out of reasonable range")); + } + var old = this.total; + this.total += changeInBytes; + var amount = this.total; + var onChange = this.onChange; + if (changeInBytes) { + onChange === null || onChange === void 0 ? void 0 : onChange(amount, old, changeInBytes); + } + return amount; + }; + return ExternalMemory; + }()); + + var CleanupHookCallback = /*#__PURE__*/ (function () { + function CleanupHookCallback(envObject, fn, arg, order) { + this.envObject = envObject; + this.fn = fn; + this.arg = arg; + this.order = order; + } + return CleanupHookCallback; + }()); + var CleanupQueue = /*#__PURE__*/ (function () { + function CleanupQueue() { + this._cleanupHooks = []; + this._cleanupHookCounter = 0; + } + CleanupQueue.prototype.empty = function () { + return this._cleanupHooks.length === 0; + }; + CleanupQueue.prototype.add = function (envObject, fn, arg) { + if (this._cleanupHooks.filter(function (hook) { return (hook.envObject === envObject && hook.fn === fn && hook.arg === arg); }).length > 0) { + throw new Error('Can not add same fn and arg twice'); + } + this._cleanupHooks.push(new CleanupHookCallback(envObject, fn, arg, this._cleanupHookCounter++)); + }; + CleanupQueue.prototype.remove = function (envObject, fn, arg) { + for (var i = 0; i < this._cleanupHooks.length; ++i) { + var hook = this._cleanupHooks[i]; + if (hook.envObject === envObject && hook.fn === fn && hook.arg === arg) { + this._cleanupHooks.splice(i, 1); + return; + } + } + }; + CleanupQueue.prototype.drain = function () { + var hooks = this._cleanupHooks.slice(); + hooks.sort(function (a, b) { return (b.order - a.order); }); + for (var i = 0; i < hooks.length; ++i) { + var cb = hooks[i]; + if (typeof cb.fn === 'number') { + cb.envObject.makeDynCall_vp(cb.fn)(cb.arg); + } + else { + cb.fn(cb.arg); + } + this._cleanupHooks.splice(this._cleanupHooks.indexOf(cb), 1); + } + }; + CleanupQueue.prototype.dispose = function () { + this._cleanupHooks.length = 0; + this._cleanupHookCounter = 0; + }; + return CleanupQueue; + }()); + var NodejsWaitingRequestCounter = /*#__PURE__*/ (function () { + function NodejsWaitingRequestCounter() { + this.refHandle = new _MessageChannel().port1; + this.count = 0; + } + NodejsWaitingRequestCounter.prototype.increase = function () { + if (this.count === 0) { + if (this.refHandle.ref) { + this.refHandle.ref(); + } + } + this.count++; + }; + NodejsWaitingRequestCounter.prototype.decrease = function () { + if (this.count === 0) + return; + if (this.count === 1) { + if (this.refHandle.unref) { + this.refHandle.unref(); + } + } + this.count--; + }; + return NodejsWaitingRequestCounter; + }()); + var Context = /*#__PURE__*/ (function () { + function Context(options) { + var _this = this; + this._isStopping = false; + this._canCallIntoJs = true; + this._suppressDestroy = false; + this.envStore = new Store(); + this.scopeStore = new ScopeStore(); + this.refStore = new Store(); + this.deferredStore = new Store(); + this.handleStore = new HandleStore(); + this.feature = { + supportReflect: supportReflect, + supportFinalizer: supportFinalizer, + supportWeakSymbol: supportWeakSymbol, + supportBigInt: supportBigInt, + supportNewFunction: supportNewFunction, + canSetFunctionName: canSetFunctionName, + setImmediate: _setImmediate, + Buffer: _Buffer, + MessageChannel: _MessageChannel + }; + this.cleanupQueue = new CleanupQueue(); + this._externalMemory = new ExternalMemory(options === null || options === void 0 ? void 0 : options.onExternalMemoryChange); + if (typeof process === 'object' && process !== null && typeof process.once === 'function') { + this.refCounter = new NodejsWaitingRequestCounter(); + process.once('beforeExit', function () { + if (!_this._suppressDestroy) { + _this.destroy(); + } + }); + } + } + /** + * Suppress the destroy on `beforeExit` event in Node.js. + * Call this method if you want to keep the context and + * all associated {@link Env | Env} alive, + * this also means that cleanup hooks will not be called. + * After call this method, you should call + * {@link Context.destroy | `Context.prototype.destroy`} method manually. + */ + Context.prototype.suppressDestroy = function () { + this._suppressDestroy = true; + }; + // eslint-disable-next-line @typescript-eslint/explicit-function-return-type + Context.prototype.getRuntimeVersions = function () { + return { + version: version, + NODE_API_SUPPORTED_VERSION_MAX: NODE_API_SUPPORTED_VERSION_MAX, + NAPI_VERSION_EXPERIMENTAL: NAPI_VERSION_EXPERIMENTAL, + NODE_API_DEFAULT_MODULE_API_VERSION: NODE_API_DEFAULT_MODULE_API_VERSION + }; + }; + Context.prototype.createNotSupportWeakRefError = function (api, message) { + return new NotSupportWeakRefError(api, message); + }; + Context.prototype.createNotSupportBufferError = function (api, message) { + return new NotSupportBufferError(api, message); + }; + Context.prototype.createReference = function (envObject, handle_id, initialRefcount, ownership) { + return Reference.create(envObject, handle_id, initialRefcount, ownership); + }; + Context.prototype.createReferenceWithData = function (envObject, handle_id, initialRefcount, ownership, data) { + return ReferenceWithData.create(envObject, handle_id, initialRefcount, ownership, data); + }; + Context.prototype.createReferenceWithFinalizer = function (envObject, handle_id, initialRefcount, ownership, finalize_callback, finalize_data, finalize_hint) { + if (finalize_callback === void 0) { finalize_callback = 0; } + if (finalize_data === void 0) { finalize_data = 0; } + if (finalize_hint === void 0) { finalize_hint = 0; } + return ReferenceWithFinalizer.create(envObject, handle_id, initialRefcount, ownership, finalize_callback, finalize_data, finalize_hint); + }; + Context.prototype.createDeferred = function (value) { + return Deferred.create(this, value); + }; + Context.prototype.adjustAmountOfExternalAllocatedMemory = function (changeInBytes) { + return this._externalMemory.adjust(changeInBytes); + }; + Context.prototype.createEnv = function (filename, moduleApiVersion, makeDynCall_vppp, makeDynCall_vp, abort, nodeBinding) { + return newEnv(this, filename, moduleApiVersion, makeDynCall_vppp, makeDynCall_vp, abort, nodeBinding); + }; + Context.prototype.createTrackedFinalizer = function (envObject, finalize_callback, finalize_data, finalize_hint) { + return TrackedFinalizer.create(envObject, finalize_callback, finalize_data, finalize_hint); + }; + Context.prototype.getCurrentScope = function () { + return this.scopeStore.currentScope; + }; + Context.prototype.addToCurrentScope = function (value) { + return this.scopeStore.currentScope.add(value); + }; + Context.prototype.openScope = function (envObject) { + var scope = this.scopeStore.openScope(this.handleStore); + if (envObject) + envObject.openHandleScopes++; + return scope; + }; + Context.prototype.closeScope = function (envObject, _scope) { + if (envObject && envObject.openHandleScopes === 0) + return; + this.scopeStore.closeScope(); + if (envObject) + envObject.openHandleScopes--; + }; + Context.prototype.ensureHandle = function (value) { + switch (value) { + case undefined: return HandleStore.UNDEFINED; + case null: return HandleStore.NULL; + case true: return HandleStore.TRUE; + case false: return HandleStore.FALSE; + case _global: return HandleStore.GLOBAL; + } + return this.addToCurrentScope(value); + }; + Context.prototype.addCleanupHook = function (envObject, fn, arg) { + this.cleanupQueue.add(envObject, fn, arg); + }; + Context.prototype.removeCleanupHook = function (envObject, fn, arg) { + this.cleanupQueue.remove(envObject, fn, arg); + }; + Context.prototype.runCleanup = function () { + while (!this.cleanupQueue.empty()) { + this.cleanupQueue.drain(); + } + }; + Context.prototype.increaseWaitingRequestCounter = function () { + var _a; + (_a = this.refCounter) === null || _a === void 0 ? void 0 : _a.increase(); + }; + Context.prototype.decreaseWaitingRequestCounter = function () { + var _a; + (_a = this.refCounter) === null || _a === void 0 ? void 0 : _a.decrease(); + }; + Context.prototype.setCanCallIntoJs = function (value) { + this._canCallIntoJs = value; + }; + Context.prototype.setStopping = function (value) { + this._isStopping = value; + }; + Context.prototype.canCallIntoJs = function () { + return this._canCallIntoJs && !this._isStopping; + }; + /** + * Destroy the context and call cleanup hooks. + * Associated {@link Env | Env} will be destroyed. + */ + Context.prototype.destroy = function () { + this.setStopping(true); + this.setCanCallIntoJs(false); + this.runCleanup(); + }; + return Context; + }()); + var defaultContext; + function createContext(options) { + return new Context(options); + } + function getDefaultContext() { + if (!defaultContext) { + defaultContext = createContext(); + } + return defaultContext; + } + + exports.ConstHandle = ConstHandle; + exports.Context = Context; + exports.Deferred = Deferred; + exports.EmnapiError = EmnapiError; + exports.Env = Env; + exports.External = External; + exports.Finalizer = Finalizer; + exports.Handle = Handle; + exports.HandleScope = HandleScope; + exports.HandleStore = HandleStore; + exports.NAPI_VERSION_EXPERIMENTAL = NAPI_VERSION_EXPERIMENTAL; + exports.NODE_API_DEFAULT_MODULE_API_VERSION = NODE_API_DEFAULT_MODULE_API_VERSION; + exports.NODE_API_SUPPORTED_VERSION_MAX = NODE_API_SUPPORTED_VERSION_MAX; + exports.NODE_API_SUPPORTED_VERSION_MIN = NODE_API_SUPPORTED_VERSION_MIN; + exports.NodeEnv = NodeEnv; + exports.NotSupportBufferError = NotSupportBufferError; + exports.NotSupportWeakRefError = NotSupportWeakRefError; + exports.Persistent = Persistent; + exports.RefTracker = RefTracker; + exports.Reference = Reference; + exports.ReferenceWithData = ReferenceWithData; + exports.ReferenceWithFinalizer = ReferenceWithFinalizer; + exports.ScopeStore = ScopeStore; + exports.Store = Store; + exports.TrackedFinalizer = TrackedFinalizer; + exports.TryCatch = TryCatch; + exports.createContext = createContext; + exports.getDefaultContext = getDefaultContext; + exports.getExternalValue = getExternalValue; + exports.isExternal = isExternal; + exports.isReferenceType = isReferenceType; + exports.version = version; + + return exports; + +})({}); diff --git a/dg-ui/node_modules/@tailwindcss/oxide-wasm32-wasi/node_modules/@emnapi/runtime/dist/emnapi.js b/dg-ui/node_modules/@tailwindcss/oxide-wasm32-wasi/node_modules/@emnapi/runtime/dist/emnapi.js new file mode 100644 index 0000000..9ff7462 --- /dev/null +++ b/dg-ui/node_modules/@tailwindcss/oxide-wasm32-wasi/node_modules/@emnapi/runtime/dist/emnapi.js @@ -0,0 +1,1529 @@ +(function (global, factory) { + typeof exports === 'object' && typeof module !== 'undefined' ? factory(exports) : + typeof define === 'function' && define.amd ? define(['exports'], factory) : + (global = typeof globalThis !== 'undefined' ? globalThis : global || self, factory(global.emnapi = {})); +})(this, (function (exports) { + /****************************************************************************** + Copyright (c) Microsoft Corporation. + + Permission to use, copy, modify, and/or distribute this software for any + purpose with or without fee is hereby granted. + + THE SOFTWARE IS PROVIDED "AS IS" AND THE AUTHOR DISCLAIMS ALL WARRANTIES WITH + REGARD TO THIS SOFTWARE INCLUDING ALL IMPLIED WARRANTIES OF MERCHANTABILITY + AND FITNESS. IN NO EVENT SHALL THE AUTHOR BE LIABLE FOR ANY SPECIAL, DIRECT, + INDIRECT, OR CONSEQUENTIAL DAMAGES OR ANY DAMAGES WHATSOEVER RESULTING FROM + LOSS OF USE, DATA OR PROFITS, WHETHER IN AN ACTION OF CONTRACT, NEGLIGENCE OR + OTHER TORTIOUS ACTION, ARISING OUT OF OR IN CONNECTION WITH THE USE OR + PERFORMANCE OF THIS SOFTWARE. + ***************************************************************************** */ + /* global Reflect, Promise, SuppressedError, Symbol, Iterator */ + + var extendStatics = function(d, b) { + extendStatics = Object.setPrototypeOf || + ({ __proto__: [] } instanceof Array && function (d, b) { d.__proto__ = b; }) || + function (d, b) { for (var p in b) if (Object.prototype.hasOwnProperty.call(b, p)) d[p] = b[p]; }; + return extendStatics(d, b); + }; + + function __extends(d, b) { + if (typeof b !== "function" && b !== null) + throw new TypeError("Class extends value " + String(b) + " is not a constructor or null"); + extendStatics(d, b); + function __() { this.constructor = d; } + d.prototype = b === null ? Object.create(b) : (__.prototype = b.prototype, new __()); + } + + typeof SuppressedError === "function" ? SuppressedError : function (error, suppressed, message) { + var e = new Error(message); + return e.name = "SuppressedError", e.error = error, e.suppressed = suppressed, e; + }; + + var externalValue = new WeakMap(); + /** @public */ + function isExternal(object) { + return externalValue.has(object); + } + /** @public */ // eslint-disable-next-line @typescript-eslint/no-redeclare + var External = (function () { + function External(value) { + Object.setPrototypeOf(this, null); + externalValue.set(this, value); + } + External.prototype = null; + return External; + })(); + /** @public */ + function getExternalValue(external) { + if (!isExternal(external)) { + throw new TypeError('not external'); + } + return externalValue.get(external); + } + + var supportNewFunction = /*#__PURE__*/ (function () { + var f; + try { + f = new Function(); + } + catch (_) { + return false; + } + return typeof f === 'function'; + })(); + var _global = /*#__PURE__*/ (function () { + if (typeof globalThis !== 'undefined') + return globalThis; + var g = (function () { return this; })(); + if (!g && supportNewFunction) { + try { + g = new Function('return this')(); + } + catch (_) { } + } + if (!g) { + if (typeof __webpack_public_path__ === 'undefined') { + if (typeof global !== 'undefined') + return global; + } + if (typeof window !== 'undefined') + return window; + if (typeof self !== 'undefined') + return self; + } + return g; + })(); + var TryCatch = /*#__PURE__*/ (function () { + function TryCatch() { + this._exception = undefined; + this._caught = false; + } + TryCatch.prototype.isEmpty = function () { + return !this._caught; + }; + TryCatch.prototype.hasCaught = function () { + return this._caught; + }; + TryCatch.prototype.exception = function () { + return this._exception; + }; + TryCatch.prototype.setError = function (err) { + this._caught = true; + this._exception = err; + }; + TryCatch.prototype.reset = function () { + this._caught = false; + this._exception = undefined; + }; + TryCatch.prototype.extractException = function () { + var e = this._exception; + this.reset(); + return e; + }; + return TryCatch; + }()); + var canSetFunctionName = /*#__PURE__*/ (function () { + var _a; + try { + return Boolean((_a = Object.getOwnPropertyDescriptor(Function.prototype, 'name')) === null || _a === void 0 ? void 0 : _a.configurable); + } + catch (_) { + return false; + } + })(); + var supportReflect = typeof Reflect === 'object'; + var supportFinalizer = (typeof FinalizationRegistry !== 'undefined') && (typeof WeakRef !== 'undefined'); + var supportWeakSymbol = /*#__PURE__*/ (function () { + try { + // eslint-disable-next-line symbol-description + var sym = Symbol(); + // eslint-disable-next-line no-new + new WeakRef(sym); + new WeakMap().set(sym, undefined); + } + catch (_) { + return false; + } + return true; + })(); + var supportBigInt = typeof BigInt !== 'undefined'; + function isReferenceType(v) { + return (typeof v === 'object' && v !== null) || typeof v === 'function'; + } + var _require = /*#__PURE__*/ (function () { + var nativeRequire; + if (typeof __webpack_public_path__ !== 'undefined') { + nativeRequire = (function () { + return typeof __non_webpack_require__ !== 'undefined' ? __non_webpack_require__ : undefined; + })(); + } + else { + nativeRequire = (function () { + return typeof __webpack_public_path__ !== 'undefined' ? (typeof __non_webpack_require__ !== 'undefined' ? __non_webpack_require__ : undefined) : (typeof require !== 'undefined' ? require : undefined); + })(); + } + return nativeRequire; + })(); + var _MessageChannel = typeof MessageChannel === 'function' + ? MessageChannel + : /*#__PURE__*/ (function () { + try { + return _require('worker_threads').MessageChannel; + } + catch (_) { } + return undefined; + })(); + var _setImmediate = typeof setImmediate === 'function' + ? setImmediate.bind(_global) + : function (callback) { + if (typeof callback !== 'function') { + throw new TypeError('The "callback" argument must be of type function'); + } + if (_MessageChannel) { + var channel_1 = new _MessageChannel(); + channel_1.port1.onmessage = function () { + channel_1.port1.onmessage = null; + channel_1 = undefined; + callback(); + }; + channel_1.port2.postMessage(null); + } + else { + setTimeout(callback, 0); + } + }; + var _Buffer = typeof Buffer === 'function' + ? Buffer + : /*#__PURE__*/ (function () { + try { + return _require('buffer').Buffer; + } + catch (_) { } + return undefined; + })(); + var version = "1.11.3"; + var NODE_API_SUPPORTED_VERSION_MIN = 1 /* Version.NODE_API_SUPPORTED_VERSION_MIN */; + var NODE_API_SUPPORTED_VERSION_MAX = 10 /* Version.NODE_API_SUPPORTED_VERSION_MAX */; + var NAPI_VERSION_EXPERIMENTAL = 2147483647 /* Version.NAPI_VERSION_EXPERIMENTAL */; + var NODE_API_DEFAULT_MODULE_API_VERSION = 8 /* Version.NODE_API_DEFAULT_MODULE_API_VERSION */; + + var Handle = /*#__PURE__*/ (function () { + function Handle(id, value) { + this.id = id; + this.value = value; + } + Handle.prototype.data = function () { + return getExternalValue(this.value); + }; + Handle.prototype.isNumber = function () { + return typeof this.value === 'number'; + }; + Handle.prototype.isBigInt = function () { + return typeof this.value === 'bigint'; + }; + Handle.prototype.isString = function () { + return typeof this.value === 'string'; + }; + Handle.prototype.isFunction = function () { + return typeof this.value === 'function'; + }; + Handle.prototype.isExternal = function () { + return isExternal(this.value); + }; + Handle.prototype.isObject = function () { + return typeof this.value === 'object' && this.value !== null; + }; + Handle.prototype.isArray = function () { + return Array.isArray(this.value); + }; + Handle.prototype.isArrayBuffer = function () { + return (this.value instanceof ArrayBuffer); + }; + Handle.prototype.isTypedArray = function () { + return (ArrayBuffer.isView(this.value)) && !(this.value instanceof DataView); + }; + Handle.prototype.isBuffer = function (BufferConstructor) { + if (ArrayBuffer.isView(this.value)) + return true; + BufferConstructor !== null && BufferConstructor !== void 0 ? BufferConstructor : (BufferConstructor = _Buffer); + return typeof BufferConstructor === 'function' && BufferConstructor.isBuffer(this.value); + }; + Handle.prototype.isDataView = function () { + return (this.value instanceof DataView); + }; + Handle.prototype.isDate = function () { + return (this.value instanceof Date); + }; + Handle.prototype.isPromise = function () { + return (this.value instanceof Promise); + }; + Handle.prototype.isBoolean = function () { + return typeof this.value === 'boolean'; + }; + Handle.prototype.isUndefined = function () { + return this.value === undefined; + }; + Handle.prototype.isSymbol = function () { + return typeof this.value === 'symbol'; + }; + Handle.prototype.isNull = function () { + return this.value === null; + }; + Handle.prototype.dispose = function () { + this.value = undefined; + }; + return Handle; + }()); + var ConstHandle = /*#__PURE__*/ (function (_super) { + __extends(ConstHandle, _super); + function ConstHandle(id, value) { + return _super.call(this, id, value) || this; + } + ConstHandle.prototype.dispose = function () { }; + return ConstHandle; + }(Handle)); + var HandleStore = /*#__PURE__*/ (function () { + function HandleStore() { + this._values = [ + undefined, + HandleStore.UNDEFINED, + HandleStore.NULL, + HandleStore.FALSE, + HandleStore.TRUE, + HandleStore.GLOBAL + ]; + this._next = HandleStore.MIN_ID; + } + HandleStore.prototype.push = function (value) { + var h; + var next = this._next; + var values = this._values; + if (next < values.length) { + h = values[next]; + h.value = value; + } + else { + h = new Handle(next, value); + values[next] = h; + } + this._next++; + return h; + }; + HandleStore.prototype.erase = function (start, end) { + this._next = start; + var values = this._values; + for (var i = start; i < end; ++i) { + values[i].dispose(); + } + }; + HandleStore.prototype.get = function (id) { + return this._values[id]; + }; + HandleStore.prototype.swap = function (a, b) { + var values = this._values; + var h = values[a]; + values[a] = values[b]; + values[a].id = Number(a); + values[b] = h; + h.id = Number(b); + }; + HandleStore.prototype.dispose = function () { + this._values.length = HandleStore.MIN_ID; + this._next = HandleStore.MIN_ID; + }; + HandleStore.UNDEFINED = new ConstHandle(1 /* GlobalHandle.UNDEFINED */, undefined); + HandleStore.NULL = new ConstHandle(2 /* GlobalHandle.NULL */, null); + HandleStore.FALSE = new ConstHandle(3 /* GlobalHandle.FALSE */, false); + HandleStore.TRUE = new ConstHandle(4 /* GlobalHandle.TRUE */, true); + HandleStore.GLOBAL = new ConstHandle(5 /* GlobalHandle.GLOBAL */, _global); + HandleStore.MIN_ID = 6; + return HandleStore; + }()); + + var HandleScope = /*#__PURE__*/ (function () { + function HandleScope(handleStore, id, parentScope, start, end) { + if (end === void 0) { end = start; } + this.handleStore = handleStore; + this.id = id; + this.parent = parentScope; + this.child = null; + if (parentScope !== null) + parentScope.child = this; + this.start = start; + this.end = end; + this._escapeCalled = false; + this.callbackInfo = { + thiz: undefined, + data: 0, + args: undefined, + fn: undefined + }; + } + HandleScope.prototype.add = function (value) { + var h = this.handleStore.push(value); + this.end++; + return h; + }; + HandleScope.prototype.addExternal = function (data) { + return this.add(new External(data)); + }; + HandleScope.prototype.dispose = function () { + if (this._escapeCalled) + this._escapeCalled = false; + if (this.start === this.end) + return; + this.handleStore.erase(this.start, this.end); + }; + HandleScope.prototype.escape = function (handle) { + if (this._escapeCalled) + return null; + this._escapeCalled = true; + if (handle < this.start || handle >= this.end) { + return null; + } + this.handleStore.swap(handle, this.start); + var h = this.handleStore.get(this.start); + this.start++; + this.parent.end++; + return h; + }; + HandleScope.prototype.escapeCalled = function () { + return this._escapeCalled; + }; + return HandleScope; + }()); + + var ScopeStore = /*#__PURE__*/ (function () { + function ScopeStore() { + this._rootScope = new HandleScope(null, 0, null, 1, HandleStore.MIN_ID); + this.currentScope = this._rootScope; + this._values = [undefined]; + } + ScopeStore.prototype.get = function (id) { + return this._values[id]; + }; + ScopeStore.prototype.openScope = function (handleStore) { + var currentScope = this.currentScope; + var scope = currentScope.child; + if (scope !== null) { + scope.start = scope.end = currentScope.end; + } + else { + var id = currentScope.id + 1; + scope = new HandleScope(handleStore, id, currentScope, currentScope.end); + this._values[id] = scope; + } + this.currentScope = scope; + return scope; + }; + ScopeStore.prototype.closeScope = function () { + var scope = this.currentScope; + this.currentScope = scope.parent; + scope.dispose(); + }; + ScopeStore.prototype.dispose = function () { + this.currentScope = this._rootScope; + this._values.length = 1; + }; + return ScopeStore; + }()); + + var RefTracker = /*#__PURE__*/ (function () { + function RefTracker() { + this._next = null; + this._prev = null; + } + /** @virtual */ + RefTracker.prototype.dispose = function () { }; + /** @virtual */ + RefTracker.prototype.finalize = function () { }; + RefTracker.prototype.link = function (list) { + this._prev = list; + this._next = list._next; + if (this._next !== null) { + this._next._prev = this; + } + list._next = this; + }; + RefTracker.prototype.unlink = function () { + if (this._prev !== null) { + this._prev._next = this._next; + } + if (this._next !== null) { + this._next._prev = this._prev; + } + this._prev = null; + this._next = null; + }; + RefTracker.finalizeAll = function (list) { + while (list._next !== null) { + list._next.finalize(); + } + }; + return RefTracker; + }()); + + var Finalizer = /*#__PURE__*/ (function () { + function Finalizer(envObject, _finalizeCallback, _finalizeData, _finalizeHint) { + if (_finalizeCallback === void 0) { _finalizeCallback = 0; } + if (_finalizeData === void 0) { _finalizeData = 0; } + if (_finalizeHint === void 0) { _finalizeHint = 0; } + this.envObject = envObject; + this._finalizeCallback = _finalizeCallback; + this._finalizeData = _finalizeData; + this._finalizeHint = _finalizeHint; + this._makeDynCall_vppp = envObject.makeDynCall_vppp; + } + Finalizer.prototype.callback = function () { return this._finalizeCallback; }; + Finalizer.prototype.data = function () { return this._finalizeData; }; + Finalizer.prototype.hint = function () { return this._finalizeHint; }; + Finalizer.prototype.resetEnv = function () { + this.envObject = undefined; + }; + Finalizer.prototype.resetFinalizer = function () { + this._finalizeCallback = 0; + this._finalizeData = 0; + this._finalizeHint = 0; + }; + Finalizer.prototype.callFinalizer = function () { + var finalize_callback = this._finalizeCallback; + var finalize_data = this._finalizeData; + var finalize_hint = this._finalizeHint; + this.resetFinalizer(); + if (!finalize_callback) + return; + var fini = Number(finalize_callback); + if (!this.envObject) { + this._makeDynCall_vppp(fini)(0, finalize_data, finalize_hint); + } + else { + this.envObject.callFinalizer(fini, finalize_data, finalize_hint); + } + }; + Finalizer.prototype.dispose = function () { + this.envObject = undefined; + this._makeDynCall_vppp = undefined; + }; + return Finalizer; + }()); + + var TrackedFinalizer = /*#__PURE__*/ (function (_super) { + __extends(TrackedFinalizer, _super); + function TrackedFinalizer(envObject, finalize_callback, finalize_data, finalize_hint) { + var _this = _super.call(this) || this; + _this._finalizer = new Finalizer(envObject, finalize_callback, finalize_data, finalize_hint); + return _this; + } + TrackedFinalizer.create = function (envObject, finalize_callback, finalize_data, finalize_hint) { + var finalizer = new TrackedFinalizer(envObject, finalize_callback, finalize_data, finalize_hint); + finalizer.link(envObject.finalizing_reflist); + return finalizer; + }; + TrackedFinalizer.prototype.data = function () { + return this._finalizer.data(); + }; + TrackedFinalizer.prototype.dispose = function () { + if (!this._finalizer) + return; + this.unlink(); + this._finalizer.envObject.dequeueFinalizer(this); + this._finalizer.dispose(); + this._finalizer = undefined; + _super.prototype.dispose.call(this); + }; + TrackedFinalizer.prototype.finalize = function () { + this.unlink(); + var error; + var caught = false; + try { + this._finalizer.callFinalizer(); + } + catch (err) { + caught = true; + error = err; + } + this.dispose(); + if (caught) { + throw error; + } + }; + return TrackedFinalizer; + }(RefTracker)); + + function throwNodeApiVersionError(moduleName, moduleApiVersion) { + var errorMessage = "".concat(moduleName, " requires Node-API version ").concat(moduleApiVersion, ", but this version of Node.js only supports version ").concat(NODE_API_SUPPORTED_VERSION_MAX, " add-ons."); + throw new Error(errorMessage); + } + function handleThrow(envObject, value) { + if (envObject.terminatedOrTerminating()) { + return; + } + throw value; + } + var Env = /*#__PURE__*/ (function () { + function Env(ctx, moduleApiVersion, makeDynCall_vppp, makeDynCall_vp, abort) { + this.ctx = ctx; + this.moduleApiVersion = moduleApiVersion; + this.makeDynCall_vppp = makeDynCall_vppp; + this.makeDynCall_vp = makeDynCall_vp; + this.abort = abort; + this.openHandleScopes = 0; + this.instanceData = null; + this.tryCatch = new TryCatch(); + this.refs = 1; + this.reflist = new RefTracker(); + this.finalizing_reflist = new RefTracker(); + this.pendingFinalizers = []; + this.lastError = { + errorCode: 0 /* napi_status.napi_ok */, + engineErrorCode: 0, + engineReserved: 0 + }; + this.inGcFinalizer = false; + this._bindingMap = new WeakMap(); + this.id = 0; + } + /** @virtual */ + Env.prototype.canCallIntoJs = function () { + return true; + }; + Env.prototype.terminatedOrTerminating = function () { + return !this.canCallIntoJs(); + }; + Env.prototype.ref = function () { + this.refs++; + }; + Env.prototype.unref = function () { + this.refs--; + if (this.refs === 0) { + this.dispose(); + } + }; + Env.prototype.ensureHandle = function (value) { + return this.ctx.ensureHandle(value); + }; + Env.prototype.ensureHandleId = function (value) { + return this.ensureHandle(value).id; + }; + Env.prototype.clearLastError = function () { + var lastError = this.lastError; + if (lastError.errorCode !== 0 /* napi_status.napi_ok */) + lastError.errorCode = 0 /* napi_status.napi_ok */; + if (lastError.engineErrorCode !== 0) + lastError.engineErrorCode = 0; + if (lastError.engineReserved !== 0) + lastError.engineReserved = 0; + return 0 /* napi_status.napi_ok */; + }; + Env.prototype.setLastError = function (error_code, engine_error_code, engine_reserved) { + if (engine_error_code === void 0) { engine_error_code = 0; } + if (engine_reserved === void 0) { engine_reserved = 0; } + var lastError = this.lastError; + if (lastError.errorCode !== error_code) + lastError.errorCode = error_code; + if (lastError.engineErrorCode !== engine_error_code) + lastError.engineErrorCode = engine_error_code; + if (lastError.engineReserved !== engine_reserved) + lastError.engineReserved = engine_reserved; + return error_code; + }; + Env.prototype.getReturnStatus = function () { + return !this.tryCatch.hasCaught() ? 0 /* napi_status.napi_ok */ : this.setLastError(10 /* napi_status.napi_pending_exception */); + }; + Env.prototype.callIntoModule = function (fn, handleException) { + if (handleException === void 0) { handleException = handleThrow; } + var openHandleScopesBefore = this.openHandleScopes; + this.clearLastError(); + var r = fn(this); + if (openHandleScopesBefore !== this.openHandleScopes) { + this.abort('open_handle_scopes != open_handle_scopes_before'); + } + if (this.tryCatch.hasCaught()) { + var err = this.tryCatch.extractException(); + handleException(this, err); + } + return r; + }; + Env.prototype.invokeFinalizerFromGC = function (finalizer) { + if (this.moduleApiVersion !== NAPI_VERSION_EXPERIMENTAL) { + this.enqueueFinalizer(finalizer); + } + else { + var saved = this.inGcFinalizer; + this.inGcFinalizer = true; + try { + finalizer.finalize(); + } + finally { + this.inGcFinalizer = saved; + } + } + }; + Env.prototype.checkGCAccess = function () { + if (this.moduleApiVersion === NAPI_VERSION_EXPERIMENTAL && this.inGcFinalizer) { + this.abort('Finalizer is calling a function that may affect GC state.\n' + + 'The finalizers are run directly from GC and must not affect GC ' + + 'state.\n' + + 'Use `node_api_post_finalizer` from inside of the finalizer to work ' + + 'around this issue.\n' + + 'It schedules the call as a new task in the event loop.'); + } + }; + /** @virtual */ + Env.prototype.enqueueFinalizer = function (finalizer) { + if (this.pendingFinalizers.indexOf(finalizer) === -1) { + this.pendingFinalizers.push(finalizer); + } + }; + /** @virtual */ + Env.prototype.dequeueFinalizer = function (finalizer) { + var index = this.pendingFinalizers.indexOf(finalizer); + if (index !== -1) { + this.pendingFinalizers.splice(index, 1); + } + }; + /** @virtual */ + Env.prototype.deleteMe = function () { + RefTracker.finalizeAll(this.finalizing_reflist); + RefTracker.finalizeAll(this.reflist); + this.tryCatch.extractException(); + this.ctx.envStore.remove(this.id); + }; + Env.prototype.dispose = function () { + if (this.id === 0) + return; + this.deleteMe(); + this.finalizing_reflist.dispose(); + this.reflist.dispose(); + this.id = 0; + }; + Env.prototype.initObjectBinding = function (value) { + var binding = { + wrapped: 0, + tag: null + }; + this._bindingMap.set(value, binding); + return binding; + }; + Env.prototype.getObjectBinding = function (value) { + if (this._bindingMap.has(value)) { + return this._bindingMap.get(value); + } + return this.initObjectBinding(value); + }; + Env.prototype.setInstanceData = function (data, finalize_cb, finalize_hint) { + if (this.instanceData) { + this.instanceData.dispose(); + } + this.instanceData = TrackedFinalizer.create(this, finalize_cb, data, finalize_hint); + }; + Env.prototype.getInstanceData = function () { + return this.instanceData ? this.instanceData.data() : 0; + }; + return Env; + }()); + var NodeEnv = /*#__PURE__*/ (function (_super) { + __extends(NodeEnv, _super); + function NodeEnv(ctx, filename, moduleApiVersion, makeDynCall_vppp, makeDynCall_vp, abort, nodeBinding) { + var _this = _super.call(this, ctx, moduleApiVersion, makeDynCall_vppp, makeDynCall_vp, abort) || this; + _this.filename = filename; + _this.nodeBinding = nodeBinding; + _this.destructing = false; + _this.finalizationScheduled = false; + return _this; + } + NodeEnv.prototype.deleteMe = function () { + this.destructing = true; + this.drainFinalizerQueue(); + _super.prototype.deleteMe.call(this); + }; + NodeEnv.prototype.canCallIntoJs = function () { + return _super.prototype.canCallIntoJs.call(this) && this.ctx.canCallIntoJs(); + }; + NodeEnv.prototype.triggerFatalException = function (err) { + if (this.nodeBinding) { + this.nodeBinding.napi.fatalException(err); + } + else { + if (typeof process === 'object' && process !== null && typeof process._fatalException === 'function') { + var handled = process._fatalException(err); + if (!handled) { + console.error(err); + process.exit(1); + } + } + else { + throw err; + } + } + }; + NodeEnv.prototype.callbackIntoModule = function (enforceUncaughtExceptionPolicy, fn) { + return this.callIntoModule(fn, function (envObject, err) { + if (envObject.terminatedOrTerminating()) { + return; + } + var hasProcess = typeof process === 'object' && process !== null; + var hasForceFlag = hasProcess ? Boolean(process.execArgv && (process.execArgv.indexOf('--force-node-api-uncaught-exceptions-policy') !== -1)) : false; + if (envObject.moduleApiVersion < 10 && !hasForceFlag && !enforceUncaughtExceptionPolicy) { + var warn = hasProcess && typeof process.emitWarning === 'function' + ? process.emitWarning + : function (warning, type, code) { + if (warning instanceof Error) { + console.warn(warning.toString()); + } + else { + var prefix = code ? "[".concat(code, "] ") : ''; + // eslint-disable-next-line @typescript-eslint/prefer-nullish-coalescing + console.warn("".concat(prefix).concat(type || 'Warning', ": ").concat(warning)); + } + }; + warn('Uncaught Node-API callback exception detected, please run node with option --force-node-api-uncaught-exceptions-policy=true to handle those exceptions properly.', 'DeprecationWarning', 'DEP0168'); + return; + } + envObject.triggerFatalException(err); + }); + }; + NodeEnv.prototype.callFinalizer = function (cb, data, hint) { + this.callFinalizerInternal(1, cb, data, hint); + }; + NodeEnv.prototype.callFinalizerInternal = function (forceUncaught, cb, data, hint) { + var f = this.makeDynCall_vppp(cb); + var env = this.id; + var scope = this.ctx.openScope(this); + try { + this.callbackIntoModule(Boolean(forceUncaught), function () { f(env, data, hint); }); + } + finally { + this.ctx.closeScope(this, scope); + } + }; + NodeEnv.prototype.enqueueFinalizer = function (finalizer) { + var _this = this; + _super.prototype.enqueueFinalizer.call(this, finalizer); + if (!this.finalizationScheduled && !this.destructing) { + this.finalizationScheduled = true; + this.ref(); + _setImmediate(function () { + _this.finalizationScheduled = false; + _this.unref(); + _this.drainFinalizerQueue(); + }); + } + }; + NodeEnv.prototype.drainFinalizerQueue = function () { + while (this.pendingFinalizers.length > 0) { + var refTracker = this.pendingFinalizers.shift(); + refTracker.finalize(); + } + }; + return NodeEnv; + }(Env)); + function newEnv(ctx, filename, moduleApiVersion, makeDynCall_vppp, makeDynCall_vp, abort, nodeBinding) { + moduleApiVersion = typeof moduleApiVersion !== 'number' ? NODE_API_DEFAULT_MODULE_API_VERSION : moduleApiVersion; + // Validate module_api_version. + if (moduleApiVersion < NODE_API_DEFAULT_MODULE_API_VERSION) { + moduleApiVersion = NODE_API_DEFAULT_MODULE_API_VERSION; + } + else if (moduleApiVersion > NODE_API_SUPPORTED_VERSION_MAX && moduleApiVersion !== NAPI_VERSION_EXPERIMENTAL) { + throwNodeApiVersionError(filename, moduleApiVersion); + } + var env = new NodeEnv(ctx, filename, moduleApiVersion, makeDynCall_vppp, makeDynCall_vp, abort, nodeBinding); + ctx.envStore.add(env); + ctx.addCleanupHook(env, function () { env.unref(); }, 0); + return env; + } + + var EmnapiError = /*#__PURE__*/ (function (_super) { + __extends(EmnapiError, _super); + function EmnapiError(message) { + var _newTarget = this.constructor; + var _this = _super.call(this, message) || this; + var ErrorConstructor = _newTarget; + var proto = ErrorConstructor.prototype; + if (!(_this instanceof EmnapiError)) { + var setPrototypeOf = Object.setPrototypeOf; + if (typeof setPrototypeOf === 'function') { + setPrototypeOf.call(Object, _this, proto); + } + else { + // eslint-disable-next-line no-proto + _this.__proto__ = proto; + } + if (typeof Error.captureStackTrace === 'function') { + Error.captureStackTrace(_this, ErrorConstructor); + } + } + return _this; + } + return EmnapiError; + }(Error)); + Object.defineProperty(EmnapiError.prototype, 'name', { + configurable: true, + writable: true, + value: 'EmnapiError' + }); + var NotSupportWeakRefError = /*#__PURE__*/ (function (_super) { + __extends(NotSupportWeakRefError, _super); + function NotSupportWeakRefError(api, message) { + return _super.call(this, "".concat(api, ": The current runtime does not support \"FinalizationRegistry\" and \"WeakRef\".").concat(message ? " ".concat(message) : '')) || this; + } + return NotSupportWeakRefError; + }(EmnapiError)); + Object.defineProperty(NotSupportWeakRefError.prototype, 'name', { + configurable: true, + writable: true, + value: 'NotSupportWeakRefError' + }); + var NotSupportBufferError = /*#__PURE__*/ (function (_super) { + __extends(NotSupportBufferError, _super); + function NotSupportBufferError(api, message) { + return _super.call(this, "".concat(api, ": The current runtime does not support \"Buffer\". Consider using buffer polyfill to make sure `globalThis.Buffer` is defined.").concat(message ? " ".concat(message) : '')) || this; + } + return NotSupportBufferError; + }(EmnapiError)); + Object.defineProperty(NotSupportBufferError.prototype, 'name', { + configurable: true, + writable: true, + value: 'NotSupportBufferError' + }); + + var StrongRef = /*#__PURE__*/ (function () { + function StrongRef(value) { + this._value = value; + } + StrongRef.prototype.deref = function () { + return this._value; + }; + StrongRef.prototype.dispose = function () { + this._value = undefined; + }; + return StrongRef; + }()); + var Persistent = /*#__PURE__*/ (function () { + function Persistent(value) { + this._ref = new StrongRef(value); + } + Persistent.prototype.setWeak = function (param, callback) { + if (!supportFinalizer || this._ref === undefined || this._ref instanceof WeakRef) + return; + var value = this._ref.deref(); + try { + Persistent._registry.register(value, this, this); + var weakRef = new WeakRef(value); + this._ref.dispose(); + this._ref = weakRef; + this._param = param; + this._callback = callback; + } + catch (err) { + if (typeof value === 'symbol') ; + else { + throw err; + } + } + }; + Persistent.prototype.clearWeak = function () { + if (!supportFinalizer || this._ref === undefined) + return; + if (this._ref instanceof WeakRef) { + try { + Persistent._registry.unregister(this); + } + catch (_) { } + this._param = undefined; + this._callback = undefined; + var value = this._ref.deref(); + if (value === undefined) { + this._ref = value; + } + else { + this._ref = new StrongRef(value); + } + } + }; + Persistent.prototype.reset = function () { + if (supportFinalizer) { + try { + Persistent._registry.unregister(this); + } + catch (_) { } + } + this._param = undefined; + this._callback = undefined; + if (this._ref instanceof StrongRef) { + this._ref.dispose(); + } + this._ref = undefined; + }; + Persistent.prototype.isEmpty = function () { + return this._ref === undefined; + }; + Persistent.prototype.deref = function () { + if (this._ref === undefined) + return undefined; + return this._ref.deref(); + }; + Persistent._registry = supportFinalizer + ? new FinalizationRegistry(function (value) { + value._ref = undefined; + var callback = value._callback; + var param = value._param; + value._callback = undefined; + value._param = undefined; + if (typeof callback === 'function') { + callback(param); + } + }) + : undefined; + return Persistent; + }()); + + exports.ReferenceOwnership = void 0; + (function (ReferenceOwnership) { + ReferenceOwnership[ReferenceOwnership["kRuntime"] = 0] = "kRuntime"; + ReferenceOwnership[ReferenceOwnership["kUserland"] = 1] = "kUserland"; + })(exports.ReferenceOwnership || (exports.ReferenceOwnership = {})); + function canBeHeldWeakly(value) { + return value.isObject() || value.isFunction() || value.isSymbol(); + } + var Reference = /*#__PURE__*/ (function (_super) { + __extends(Reference, _super); + function Reference(envObject, handle_id, initialRefcount, ownership) { + var _this = _super.call(this) || this; + _this.envObject = envObject; + _this._refcount = initialRefcount; + _this._ownership = ownership; + var handle = envObject.ctx.handleStore.get(handle_id); + _this.canBeWeak = canBeHeldWeakly(handle); + _this.persistent = new Persistent(handle.value); + _this.id = 0; + if (initialRefcount === 0) { + _this._setWeak(); + } + return _this; + } + Reference.weakCallback = function (ref) { + ref.persistent.reset(); + ref.invokeFinalizerFromGC(); + }; + Reference.create = function (envObject, handle_id, initialRefcount, ownership, _unused1, _unused2, _unused3) { + var ref = new Reference(envObject, handle_id, initialRefcount, ownership); + envObject.ctx.refStore.add(ref); + ref.link(envObject.reflist); + return ref; + }; + Reference.prototype.ref = function () { + if (this.persistent.isEmpty()) { + return 0; + } + if (++this._refcount === 1 && this.canBeWeak) { + this.persistent.clearWeak(); + } + return this._refcount; + }; + Reference.prototype.unref = function () { + if (this.persistent.isEmpty() || this._refcount === 0) { + return 0; + } + if (--this._refcount === 0) { + this._setWeak(); + } + return this._refcount; + }; + Reference.prototype.get = function (envObject) { + if (envObject === void 0) { envObject = this.envObject; } + if (this.persistent.isEmpty()) { + return 0; + } + var obj = this.persistent.deref(); + var handle = envObject.ensureHandle(obj); + return handle.id; + }; + /** @virtual */ + Reference.prototype.resetFinalizer = function () { }; + /** @virtual */ + Reference.prototype.data = function () { return 0; }; + Reference.prototype.refcount = function () { return this._refcount; }; + Reference.prototype.ownership = function () { return this._ownership; }; + /** @virtual */ + Reference.prototype.callUserFinalizer = function () { }; + /** @virtual */ + Reference.prototype.invokeFinalizerFromGC = function () { + this.finalize(); + }; + Reference.prototype._setWeak = function () { + if (this.canBeWeak) { + this.persistent.setWeak(this, Reference.weakCallback); + } + else { + this.persistent.reset(); + } + }; + Reference.prototype.finalize = function () { + this.persistent.reset(); + var deleteMe = this._ownership === exports.ReferenceOwnership.kRuntime; + this.unlink(); + this.callUserFinalizer(); + if (deleteMe) { + this.dispose(); + } + }; + Reference.prototype.dispose = function () { + if (this.id === 0) + return; + this.unlink(); + this.persistent.reset(); + this.envObject.ctx.refStore.remove(this.id); + _super.prototype.dispose.call(this); + this.envObject = undefined; + this.id = 0; + }; + return Reference; + }(RefTracker)); + var ReferenceWithData = /*#__PURE__*/ (function (_super) { + __extends(ReferenceWithData, _super); + function ReferenceWithData(envObject, value, initialRefcount, ownership, _data) { + var _this = _super.call(this, envObject, value, initialRefcount, ownership) || this; + _this._data = _data; + return _this; + } + ReferenceWithData.create = function (envObject, value, initialRefcount, ownership, data) { + var reference = new ReferenceWithData(envObject, value, initialRefcount, ownership, data); + envObject.ctx.refStore.add(reference); + reference.link(envObject.reflist); + return reference; + }; + ReferenceWithData.prototype.data = function () { + return this._data; + }; + return ReferenceWithData; + }(Reference)); + var ReferenceWithFinalizer = /*#__PURE__*/ (function (_super) { + __extends(ReferenceWithFinalizer, _super); + function ReferenceWithFinalizer(envObject, value, initialRefcount, ownership, finalize_callback, finalize_data, finalize_hint) { + var _this = _super.call(this, envObject, value, initialRefcount, ownership) || this; + _this._finalizer = new Finalizer(envObject, finalize_callback, finalize_data, finalize_hint); + return _this; + } + ReferenceWithFinalizer.create = function (envObject, value, initialRefcount, ownership, finalize_callback, finalize_data, finalize_hint) { + var reference = new ReferenceWithFinalizer(envObject, value, initialRefcount, ownership, finalize_callback, finalize_data, finalize_hint); + envObject.ctx.refStore.add(reference); + reference.link(envObject.finalizing_reflist); + return reference; + }; + ReferenceWithFinalizer.prototype.resetFinalizer = function () { + this._finalizer.resetFinalizer(); + }; + ReferenceWithFinalizer.prototype.data = function () { + return this._finalizer.data(); + }; + ReferenceWithFinalizer.prototype.callUserFinalizer = function () { + this._finalizer.callFinalizer(); + }; + ReferenceWithFinalizer.prototype.invokeFinalizerFromGC = function () { + this._finalizer.envObject.invokeFinalizerFromGC(this); + }; + ReferenceWithFinalizer.prototype.dispose = function () { + if (!this._finalizer) + return; + this._finalizer.envObject.dequeueFinalizer(this); + this._finalizer.dispose(); + _super.prototype.dispose.call(this); + this._finalizer = undefined; + }; + return ReferenceWithFinalizer; + }(Reference)); + + var Deferred = /*#__PURE__*/ (function () { + function Deferred(ctx, value) { + // Plain assignment would invoke inherited setters before these fields + // become own properties. + Object.defineProperties(this, { + id: { + configurable: true, + enumerable: true, + value: 0, + writable: true + }, + ctx: { + configurable: true, + enumerable: true, + value: ctx, + writable: true + }, + value: { + configurable: true, + enumerable: true, + value: value, + writable: true + } + }); + } + Deferred.create = function (ctx, value) { + var deferred = new Deferred(ctx, value); + ctx.deferredStore.add(deferred); + return deferred; + }; + Deferred.prototype.resolve = function (value) { + this.value.resolve(value); + this.dispose(); + }; + Deferred.prototype.reject = function (reason) { + this.value.reject(reason); + this.dispose(); + }; + Deferred.prototype.dispose = function () { + this.ctx.deferredStore.remove(this.id); + this.id = 0; + this.value = null; + this.ctx = null; + }; + return Deferred; + }()); + + var Store = /*#__PURE__*/ (function () { + function Store() { + this._values = [undefined]; + this._values.length = 4; + this._size = 1; + this._freeList = []; + } + Store.prototype.add = function (value) { + var id; + if (this._freeList.length) { + id = this._freeList.shift(); + } + else { + id = this._size; + this._size++; + var capacity = this._values.length; + if (id >= capacity) { + this._values.length = capacity + (capacity >> 1) + 16; + } + } + value.id = id; + this._values[id] = value; + }; + Store.prototype.get = function (id) { + return this._values[id]; + }; + Store.prototype.has = function (id) { + return this._values[id] !== undefined; + }; + Store.prototype.remove = function (id) { + var value = this._values[id]; + if (value) { + value.id = 0; + this._values[id] = undefined; + this._freeList.push(Number(id)); + } + }; + Store.prototype.dispose = function () { + for (var i = 1; i < this._size; ++i) { + var value = this._values[i]; + value === null || value === void 0 ? void 0 : value.dispose(); + } + this._values = [undefined]; + this._size = 1; + this._freeList = []; + }; + return Store; + }()); + + var kMaxReasonableBytes = BigInt(1) << BigInt(60); + var kMinReasonableBytes = -kMaxReasonableBytes; + var ExternalMemory = /*#__PURE__*/ (function () { + function ExternalMemory(onChange) { + this.total = BigInt(0); + this.onChange = onChange !== null && onChange !== void 0 ? onChange : null; + } + ExternalMemory.prototype.adjust = function (changeInBytes) { + changeInBytes = BigInt(changeInBytes); + if (!(kMinReasonableBytes <= changeInBytes && changeInBytes < kMaxReasonableBytes)) { + throw new RangeError("changeInBytes ".concat(changeInBytes, " is out of reasonable range")); + } + var old = this.total; + this.total += changeInBytes; + var amount = this.total; + var onChange = this.onChange; + if (changeInBytes) { + onChange === null || onChange === void 0 ? void 0 : onChange(amount, old, changeInBytes); + } + return amount; + }; + return ExternalMemory; + }()); + + var CleanupHookCallback = /*#__PURE__*/ (function () { + function CleanupHookCallback(envObject, fn, arg, order) { + this.envObject = envObject; + this.fn = fn; + this.arg = arg; + this.order = order; + } + return CleanupHookCallback; + }()); + var CleanupQueue = /*#__PURE__*/ (function () { + function CleanupQueue() { + this._cleanupHooks = []; + this._cleanupHookCounter = 0; + } + CleanupQueue.prototype.empty = function () { + return this._cleanupHooks.length === 0; + }; + CleanupQueue.prototype.add = function (envObject, fn, arg) { + if (this._cleanupHooks.filter(function (hook) { return (hook.envObject === envObject && hook.fn === fn && hook.arg === arg); }).length > 0) { + throw new Error('Can not add same fn and arg twice'); + } + this._cleanupHooks.push(new CleanupHookCallback(envObject, fn, arg, this._cleanupHookCounter++)); + }; + CleanupQueue.prototype.remove = function (envObject, fn, arg) { + for (var i = 0; i < this._cleanupHooks.length; ++i) { + var hook = this._cleanupHooks[i]; + if (hook.envObject === envObject && hook.fn === fn && hook.arg === arg) { + this._cleanupHooks.splice(i, 1); + return; + } + } + }; + CleanupQueue.prototype.drain = function () { + var hooks = this._cleanupHooks.slice(); + hooks.sort(function (a, b) { return (b.order - a.order); }); + for (var i = 0; i < hooks.length; ++i) { + var cb = hooks[i]; + if (typeof cb.fn === 'number') { + cb.envObject.makeDynCall_vp(cb.fn)(cb.arg); + } + else { + cb.fn(cb.arg); + } + this._cleanupHooks.splice(this._cleanupHooks.indexOf(cb), 1); + } + }; + CleanupQueue.prototype.dispose = function () { + this._cleanupHooks.length = 0; + this._cleanupHookCounter = 0; + }; + return CleanupQueue; + }()); + var NodejsWaitingRequestCounter = /*#__PURE__*/ (function () { + function NodejsWaitingRequestCounter() { + this.refHandle = new _MessageChannel().port1; + this.count = 0; + } + NodejsWaitingRequestCounter.prototype.increase = function () { + if (this.count === 0) { + if (this.refHandle.ref) { + this.refHandle.ref(); + } + } + this.count++; + }; + NodejsWaitingRequestCounter.prototype.decrease = function () { + if (this.count === 0) + return; + if (this.count === 1) { + if (this.refHandle.unref) { + this.refHandle.unref(); + } + } + this.count--; + }; + return NodejsWaitingRequestCounter; + }()); + var Context = /*#__PURE__*/ (function () { + function Context(options) { + var _this = this; + this._isStopping = false; + this._canCallIntoJs = true; + this._suppressDestroy = false; + this.envStore = new Store(); + this.scopeStore = new ScopeStore(); + this.refStore = new Store(); + this.deferredStore = new Store(); + this.handleStore = new HandleStore(); + this.feature = { + supportReflect: supportReflect, + supportFinalizer: supportFinalizer, + supportWeakSymbol: supportWeakSymbol, + supportBigInt: supportBigInt, + supportNewFunction: supportNewFunction, + canSetFunctionName: canSetFunctionName, + setImmediate: _setImmediate, + Buffer: _Buffer, + MessageChannel: _MessageChannel + }; + this.cleanupQueue = new CleanupQueue(); + this._externalMemory = new ExternalMemory(options === null || options === void 0 ? void 0 : options.onExternalMemoryChange); + if (typeof process === 'object' && process !== null && typeof process.once === 'function') { + this.refCounter = new NodejsWaitingRequestCounter(); + process.once('beforeExit', function () { + if (!_this._suppressDestroy) { + _this.destroy(); + } + }); + } + } + /** + * Suppress the destroy on `beforeExit` event in Node.js. + * Call this method if you want to keep the context and + * all associated {@link Env | Env} alive, + * this also means that cleanup hooks will not be called. + * After call this method, you should call + * {@link Context.destroy | `Context.prototype.destroy`} method manually. + */ + Context.prototype.suppressDestroy = function () { + this._suppressDestroy = true; + }; + // eslint-disable-next-line @typescript-eslint/explicit-function-return-type + Context.prototype.getRuntimeVersions = function () { + return { + version: version, + NODE_API_SUPPORTED_VERSION_MAX: NODE_API_SUPPORTED_VERSION_MAX, + NAPI_VERSION_EXPERIMENTAL: NAPI_VERSION_EXPERIMENTAL, + NODE_API_DEFAULT_MODULE_API_VERSION: NODE_API_DEFAULT_MODULE_API_VERSION + }; + }; + Context.prototype.createNotSupportWeakRefError = function (api, message) { + return new NotSupportWeakRefError(api, message); + }; + Context.prototype.createNotSupportBufferError = function (api, message) { + return new NotSupportBufferError(api, message); + }; + Context.prototype.createReference = function (envObject, handle_id, initialRefcount, ownership) { + return Reference.create(envObject, handle_id, initialRefcount, ownership); + }; + Context.prototype.createReferenceWithData = function (envObject, handle_id, initialRefcount, ownership, data) { + return ReferenceWithData.create(envObject, handle_id, initialRefcount, ownership, data); + }; + Context.prototype.createReferenceWithFinalizer = function (envObject, handle_id, initialRefcount, ownership, finalize_callback, finalize_data, finalize_hint) { + if (finalize_callback === void 0) { finalize_callback = 0; } + if (finalize_data === void 0) { finalize_data = 0; } + if (finalize_hint === void 0) { finalize_hint = 0; } + return ReferenceWithFinalizer.create(envObject, handle_id, initialRefcount, ownership, finalize_callback, finalize_data, finalize_hint); + }; + Context.prototype.createDeferred = function (value) { + return Deferred.create(this, value); + }; + Context.prototype.adjustAmountOfExternalAllocatedMemory = function (changeInBytes) { + return this._externalMemory.adjust(changeInBytes); + }; + Context.prototype.createEnv = function (filename, moduleApiVersion, makeDynCall_vppp, makeDynCall_vp, abort, nodeBinding) { + return newEnv(this, filename, moduleApiVersion, makeDynCall_vppp, makeDynCall_vp, abort, nodeBinding); + }; + Context.prototype.createTrackedFinalizer = function (envObject, finalize_callback, finalize_data, finalize_hint) { + return TrackedFinalizer.create(envObject, finalize_callback, finalize_data, finalize_hint); + }; + Context.prototype.getCurrentScope = function () { + return this.scopeStore.currentScope; + }; + Context.prototype.addToCurrentScope = function (value) { + return this.scopeStore.currentScope.add(value); + }; + Context.prototype.openScope = function (envObject) { + var scope = this.scopeStore.openScope(this.handleStore); + if (envObject) + envObject.openHandleScopes++; + return scope; + }; + Context.prototype.closeScope = function (envObject, _scope) { + if (envObject && envObject.openHandleScopes === 0) + return; + this.scopeStore.closeScope(); + if (envObject) + envObject.openHandleScopes--; + }; + Context.prototype.ensureHandle = function (value) { + switch (value) { + case undefined: return HandleStore.UNDEFINED; + case null: return HandleStore.NULL; + case true: return HandleStore.TRUE; + case false: return HandleStore.FALSE; + case _global: return HandleStore.GLOBAL; + } + return this.addToCurrentScope(value); + }; + Context.prototype.addCleanupHook = function (envObject, fn, arg) { + this.cleanupQueue.add(envObject, fn, arg); + }; + Context.prototype.removeCleanupHook = function (envObject, fn, arg) { + this.cleanupQueue.remove(envObject, fn, arg); + }; + Context.prototype.runCleanup = function () { + while (!this.cleanupQueue.empty()) { + this.cleanupQueue.drain(); + } + }; + Context.prototype.increaseWaitingRequestCounter = function () { + var _a; + (_a = this.refCounter) === null || _a === void 0 ? void 0 : _a.increase(); + }; + Context.prototype.decreaseWaitingRequestCounter = function () { + var _a; + (_a = this.refCounter) === null || _a === void 0 ? void 0 : _a.decrease(); + }; + Context.prototype.setCanCallIntoJs = function (value) { + this._canCallIntoJs = value; + }; + Context.prototype.setStopping = function (value) { + this._isStopping = value; + }; + Context.prototype.canCallIntoJs = function () { + return this._canCallIntoJs && !this._isStopping; + }; + /** + * Destroy the context and call cleanup hooks. + * Associated {@link Env | Env} will be destroyed. + */ + Context.prototype.destroy = function () { + this.setStopping(true); + this.setCanCallIntoJs(false); + this.runCleanup(); + }; + return Context; + }()); + var defaultContext; + function createContext(options) { + return new Context(options); + } + function getDefaultContext() { + if (!defaultContext) { + defaultContext = createContext(); + } + return defaultContext; + } + + exports.ConstHandle = ConstHandle; + exports.Context = Context; + exports.Deferred = Deferred; + exports.EmnapiError = EmnapiError; + exports.Env = Env; + exports.External = External; + exports.Finalizer = Finalizer; + exports.Handle = Handle; + exports.HandleScope = HandleScope; + exports.HandleStore = HandleStore; + exports.NAPI_VERSION_EXPERIMENTAL = NAPI_VERSION_EXPERIMENTAL; + exports.NODE_API_DEFAULT_MODULE_API_VERSION = NODE_API_DEFAULT_MODULE_API_VERSION; + exports.NODE_API_SUPPORTED_VERSION_MAX = NODE_API_SUPPORTED_VERSION_MAX; + exports.NODE_API_SUPPORTED_VERSION_MIN = NODE_API_SUPPORTED_VERSION_MIN; + exports.NodeEnv = NodeEnv; + exports.NotSupportBufferError = NotSupportBufferError; + exports.NotSupportWeakRefError = NotSupportWeakRefError; + exports.Persistent = Persistent; + exports.RefTracker = RefTracker; + exports.Reference = Reference; + exports.ReferenceWithData = ReferenceWithData; + exports.ReferenceWithFinalizer = ReferenceWithFinalizer; + exports.ScopeStore = ScopeStore; + exports.Store = Store; + exports.TrackedFinalizer = TrackedFinalizer; + exports.TryCatch = TryCatch; + exports.createContext = createContext; + exports.getDefaultContext = getDefaultContext; + exports.getExternalValue = getExternalValue; + exports.isExternal = isExternal; + exports.isReferenceType = isReferenceType; + exports.version = version; + +})); diff --git a/dg-ui/node_modules/@tailwindcss/oxide-wasm32-wasi/node_modules/@emnapi/runtime/dist/emnapi.min.d.mts b/dg-ui/node_modules/@tailwindcss/oxide-wasm32-wasi/node_modules/@emnapi/runtime/dist/emnapi.min.d.mts new file mode 100644 index 0000000..482aec2 --- /dev/null +++ b/dg-ui/node_modules/@tailwindcss/oxide-wasm32-wasi/node_modules/@emnapi/runtime/dist/emnapi.min.d.mts @@ -0,0 +1,671 @@ +export declare type Ptr = number | bigint + +export declare interface IBuffer extends Uint8Array {} +export declare interface BufferCtor { + readonly prototype: IBuffer + /** @deprecated */ + new (...args: any[]): IBuffer + from: { + (buffer: ArrayBufferLike): IBuffer + (buffer: ArrayBufferLike, byteOffset: number, length: number): IBuffer + } + alloc: (size: number) => IBuffer + isBuffer: (obj: unknown) => obj is IBuffer +} + +export declare const enum GlobalHandle { + UNDEFINED = 1, + NULL, + FALSE, + TRUE, + GLOBAL +} + +export declare const enum Version { + NODE_API_SUPPORTED_VERSION_MIN = 1, + NODE_API_DEFAULT_MODULE_API_VERSION = 8, + NODE_API_SUPPORTED_VERSION_MAX = 10, + NAPI_VERSION_EXPERIMENTAL = 2147483647 // INT_MAX +} +// eslint-disable-next-line @typescript-eslint/no-unused-vars +export declare type Pointer = number +// eslint-disable-next-line @typescript-eslint/no-unused-vars +export declare type PointerPointer = number +export declare type FunctionPointer any> = Pointer +export declare type Const = T + +export declare type void_p = Pointer +export declare type void_pp = Pointer +export declare type bool = number +export declare type char = number +export declare type char_p = Pointer +export declare type unsigned_char = number +export declare type const_char = Const +export declare type const_char_p = Pointer +export declare type char16_t_p = number +export declare type const_char16_t_p = number + +export declare type short = number +export declare type unsigned_short = number +export declare type int = number +export declare type unsigned_int = number +export declare type long = number +export declare type unsigned_long = number +export declare type long_long = bigint +export declare type unsigned_long_long = bigint +export declare type float = number +export declare type double = number +export declare type long_double = number +export declare type size_t = number + +export declare type int8_t = number +export declare type uint8_t = number +export declare type int16_t = number +export declare type uint16_t = number +export declare type int32_t = number +export declare type uint32_t = number +export declare type int64_t = bigint +export declare type uint64_t = bigint +export declare type napi_env = Pointer + +export declare type napi_value = Pointer +export declare type napi_ref = Pointer +export declare type napi_deferred = Pointer +export declare type napi_handle_scope = Pointer +export declare type napi_escapable_handle_scope = Pointer + +export declare type napi_addon_register_func = FunctionPointer<(env: napi_env, exports: napi_value) => napi_value> + +export declare type napi_callback_info = Pointer +export declare type napi_callback = FunctionPointer<(env: napi_env, info: napi_callback_info) => napi_value> + +export declare interface napi_extended_error_info { + error_message: const_char_p + engine_reserved: void_p + engine_error_code: uint32_t + error_code: napi_status +} + +export declare interface napi_property_descriptor { + // One of utf8name or name should be NULL. + utf8name: const_char_p + name: napi_value + + method: napi_callback + getter: napi_callback + setter: napi_callback + value: napi_value + /* napi_property_attributes */ + attributes: number + data: void_p +} + +export declare type napi_finalize = FunctionPointer<( + env: napi_env, + finalize_data: void_p, + finalize_hint: void_p +) => void> + +export declare interface node_module { + nm_version: int32_t + nm_flags: uint32_t + nm_filename: Pointer + nm_register_func: napi_addon_register_func + nm_modname: Pointer + nm_priv: Pointer + reserved: PointerPointer +} + +export declare interface napi_node_version { + major: uint32_t + minor: uint32_t + patch: uint32_t + release: const_char_p +} + +export declare interface emnapi_emscripten_version { + major: uint32_t + minor: uint32_t + patch: uint32_t +} + +export declare const enum napi_status { + napi_ok, + napi_invalid_arg, + napi_object_expected, + napi_string_expected, + napi_name_expected, + napi_function_expected, + napi_number_expected, + napi_boolean_expected, + napi_array_expected, + napi_generic_failure, + napi_pending_exception, + napi_cancelled, + napi_escape_called_twice, + napi_handle_scope_mismatch, + napi_callback_scope_mismatch, + napi_queue_full, + napi_closing, + napi_bigint_expected, + napi_date_expected, + napi_arraybuffer_expected, + napi_detachable_arraybuffer_expected, + napi_would_deadlock, // unused + napi_no_external_buffers_allowed, + napi_cannot_run_js +} + +export declare const enum napi_property_attributes { + napi_default = 0, + napi_writable = 1 << 0, + napi_enumerable = 1 << 1, + napi_configurable = 1 << 2, + + // Used with napi_define_class to distinguish static properties + // from instance properties. Ignored by napi_define_properties. + napi_static = 1 << 10, + + /// #ifdef NAPI_EXPERIMENTAL + // Default for class methods. + napi_default_method = napi_writable | napi_configurable, + + // Default for object properties, like in JS obj[prop]. + napi_default_jsproperty = napi_writable | napi_enumerable | napi_configurable + /// #endif // NAPI_EXPERIMENTAL +} + +export declare const enum napi_valuetype { + napi_undefined, + napi_null, + napi_boolean, + napi_number, + napi_string, + napi_symbol, + napi_object, + napi_function, + napi_external, + napi_bigint +} + +export declare const enum napi_typedarray_type { + napi_int8_array, + napi_uint8_array, + napi_uint8_clamped_array, + napi_int16_array, + napi_uint16_array, + napi_int32_array, + napi_uint32_array, + napi_float32_array, + napi_float64_array, + napi_bigint64_array, + napi_biguint64_array, + napi_float16_array, +} + +export declare const enum napi_key_collection_mode { + napi_key_include_prototypes, + napi_key_own_only +} + +export declare const enum napi_key_filter { + napi_key_all_properties = 0, + napi_key_writable = 1, + napi_key_enumerable = 1 << 1, + napi_key_configurable = 1 << 2, + napi_key_skip_strings = 1 << 3, + napi_key_skip_symbols = 1 << 4 +} + +export declare const enum napi_key_conversion { + napi_key_keep_numbers, + napi_key_numbers_to_strings +} + +export declare const enum emnapi_memory_view_type { + emnapi_int8_array, + emnapi_uint8_array, + emnapi_uint8_clamped_array, + emnapi_int16_array, + emnapi_uint16_array, + emnapi_int32_array, + emnapi_uint32_array, + emnapi_float32_array, + emnapi_float64_array, + emnapi_bigint64_array, + emnapi_biguint64_array, + emnapi_float16_array, + emnapi_data_view = -1, + emnapi_buffer = -2 +} + +export declare const enum napi_threadsafe_function_call_mode { + napi_tsfn_nonblocking, + napi_tsfn_blocking +} + +export declare const enum napi_threadsafe_function_release_mode { + napi_tsfn_release, + napi_tsfn_abort +} +export declare type CleanupHookCallbackFunction = number | ((arg: number) => void); + +export declare class ConstHandle extends Handle { + constructor(id: number, value: S); + dispose(): void; +} + +export declare class Context { + private _isStopping; + private _canCallIntoJs; + private _suppressDestroy; + envStore: Store; + scopeStore: ScopeStore; + refStore: Store; + deferredStore: Store>; + handleStore: HandleStore; + private readonly refCounter?; + private readonly cleanupQueue; + private readonly _externalMemory; + feature: { + supportReflect: boolean; + supportFinalizer: boolean; + supportWeakSymbol: boolean; + supportBigInt: boolean; + supportNewFunction: boolean; + canSetFunctionName: boolean; + setImmediate: (callback: () => void) => void; + Buffer: BufferCtor | undefined; + MessageChannel: { + new (): MessageChannel; + prototype: MessageChannel; + } | undefined; + }; + constructor(options?: ContextOptions); + /** + * Suppress the destroy on `beforeExit` event in Node.js. + * Call this method if you want to keep the context and + * all associated {@link Env | Env} alive, + * this also means that cleanup hooks will not be called. + * After call this method, you should call + * {@link Context.destroy | `Context.prototype.destroy`} method manually. + */ + suppressDestroy(): void; + getRuntimeVersions(): { + version: string; + NODE_API_SUPPORTED_VERSION_MAX: Version; + NAPI_VERSION_EXPERIMENTAL: Version; + NODE_API_DEFAULT_MODULE_API_VERSION: Version; + }; + createNotSupportWeakRefError(api: string, message: string): NotSupportWeakRefError; + createNotSupportBufferError(api: string, message: string): NotSupportBufferError; + createReference(envObject: Env, handle_id: napi_value, initialRefcount: uint32_t, ownership: ReferenceOwnership): Reference; + createReferenceWithData(envObject: Env, handle_id: napi_value, initialRefcount: uint32_t, ownership: ReferenceOwnership, data: void_p): Reference; + createReferenceWithFinalizer(envObject: Env, handle_id: napi_value, initialRefcount: uint32_t, ownership: ReferenceOwnership, finalize_callback?: napi_finalize, finalize_data?: void_p, finalize_hint?: void_p): Reference; + createDeferred(value: IDeferrdValue): Deferred; + adjustAmountOfExternalAllocatedMemory(changeInBytes: number | bigint): bigint; + createEnv(filename: string, moduleApiVersion: number, makeDynCall_vppp: (cb: Ptr) => (a: Ptr, b: Ptr, c: Ptr) => void, makeDynCall_vp: (cb: Ptr) => (a: Ptr) => void, abort: (msg?: string) => never, nodeBinding?: any): Env; + createTrackedFinalizer(envObject: Env, finalize_callback: napi_finalize, finalize_data: void_p, finalize_hint: void_p): TrackedFinalizer; + getCurrentScope(): HandleScope | null; + addToCurrentScope(value: V): Handle; + openScope(envObject?: Env): HandleScope; + closeScope(envObject?: Env, _scope?: HandleScope): void; + ensureHandle(value: S): Handle; + addCleanupHook(envObject: Env, fn: CleanupHookCallbackFunction, arg: number): void; + removeCleanupHook(envObject: Env, fn: CleanupHookCallbackFunction, arg: number): void; + runCleanup(): void; + increaseWaitingRequestCounter(): void; + decreaseWaitingRequestCounter(): void; + setCanCallIntoJs(value: boolean): void; + setStopping(value: boolean): void; + canCallIntoJs(): boolean; + /** + * Destroy the context and call cleanup hooks. + * Associated {@link Env | Env} will be destroyed. + */ + destroy(): void; +} + +export declare interface ContextOptions { + onExternalMemoryChange?: (current: bigint, old: bigint, delta: bigint) => any; +} + +export declare function createContext(options?: ContextOptions): Context; + +export declare class Deferred implements IStoreValue { + static create(ctx: Context, value: IDeferrdValue): Deferred; + id: number; + ctx: Context; + value: IDeferrdValue; + constructor(ctx: Context, value: IDeferrdValue); + resolve(value: T): void; + reject(reason?: any): void; + dispose(): void; +} + +export declare class EmnapiError extends Error { + constructor(message?: string); +} + +export declare abstract class Env implements IStoreValue { + readonly ctx: Context; + moduleApiVersion: number; + makeDynCall_vppp: (cb: Ptr) => (a: Ptr, b: Ptr, c: Ptr) => void; + makeDynCall_vp: (cb: Ptr) => (a: Ptr) => void; + abort: (msg?: string) => never; + id: number; + openHandleScopes: number; + instanceData: TrackedFinalizer | null; + tryCatch: TryCatch; + refs: number; + reflist: RefTracker; + finalizing_reflist: RefTracker; + pendingFinalizers: RefTracker[]; + lastError: { + errorCode: napi_status; + engineErrorCode: number; + engineReserved: Ptr; + }; + inGcFinalizer: boolean; + constructor(ctx: Context, moduleApiVersion: number, makeDynCall_vppp: (cb: Ptr) => (a: Ptr, b: Ptr, c: Ptr) => void, makeDynCall_vp: (cb: Ptr) => (a: Ptr) => void, abort: (msg?: string) => never); + /** @virtual */ + canCallIntoJs(): boolean; + terminatedOrTerminating(): boolean; + ref(): void; + unref(): void; + ensureHandle(value: S): Handle; + ensureHandleId(value: any): napi_value; + clearLastError(): napi_status; + setLastError(error_code: napi_status, engine_error_code?: uint32_t, engine_reserved?: void_p): napi_status; + getReturnStatus(): napi_status; + callIntoModule(fn: (env: Env) => T, handleException?: (envObject: Env, value: any) => void): T; + /** @virtual */ + abstract callFinalizer(cb: napi_finalize, data: void_p, hint: void_p): void; + invokeFinalizerFromGC(finalizer: RefTracker): void; + checkGCAccess(): void; + /** @virtual */ + enqueueFinalizer(finalizer: RefTracker): void; + /** @virtual */ + dequeueFinalizer(finalizer: RefTracker): void; + /** @virtual */ + deleteMe(): void; + dispose(): void; + private readonly _bindingMap; + initObjectBinding(value: S): IReferenceBinding; + getObjectBinding(value: S): IReferenceBinding; + setInstanceData(data: number, finalize_cb: number, finalize_hint: number): void; + getInstanceData(): number; +} + +/** @public */ +declare interface External_2 extends Record { +} + +/** @public */ +declare const External_2: { + new (value: number | bigint): External_2; + prototype: null; +}; +export { External_2 as External } + +export declare class Finalizer { + envObject: Env; + private _finalizeCallback; + private _finalizeData; + private _finalizeHint; + private _makeDynCall_vppp; + constructor(envObject: Env, _finalizeCallback?: napi_finalize, _finalizeData?: void_p, _finalizeHint?: void_p); + callback(): napi_finalize; + data(): void_p; + hint(): void_p; + resetEnv(): void; + resetFinalizer(): void; + callFinalizer(): void; + dispose(): void; +} + +export declare function getDefaultContext(): Context; + +/** @public */ +export declare function getExternalValue(external: External_2): number | bigint; + +export declare class Handle { + id: number; + value: S; + constructor(id: number, value: S); + data(): void_p; + isNumber(): boolean; + isBigInt(): boolean; + isString(): boolean; + isFunction(): boolean; + isExternal(): boolean; + isObject(): boolean; + isArray(): boolean; + isArrayBuffer(): boolean; + isTypedArray(): boolean; + isBuffer(BufferConstructor?: BufferCtor): boolean; + isDataView(): boolean; + isDate(): boolean; + isPromise(): boolean; + isBoolean(): boolean; + isUndefined(): boolean; + isSymbol(): boolean; + isNull(): boolean; + dispose(): void; +} + +export declare class HandleScope { + handleStore: HandleStore; + id: number; + parent: HandleScope | null; + child: HandleScope | null; + start: number; + end: number; + private _escapeCalled; + callbackInfo: ICallbackInfo; + constructor(handleStore: HandleStore, id: number, parentScope: HandleScope | null, start: number, end?: number); + add(value: V): Handle; + addExternal(data: void_p): Handle; + dispose(): void; + escape(handle: number): Handle | null; + escapeCalled(): boolean; +} + +export declare class HandleStore { + static UNDEFINED: ConstHandle; + static NULL: ConstHandle; + static FALSE: ConstHandle; + static TRUE: ConstHandle; + static GLOBAL: ConstHandle; + static MIN_ID: 6; + private readonly _values; + private _next; + push(value: S): Handle; + erase(start: number, end: number): void; + get(id: Ptr): Handle | undefined; + swap(a: number, b: number): void; + dispose(): void; +} + +export declare interface ICallbackInfo { + thiz: any; + data: void_p; + args: ArrayLike; + fn: Function; +} + +export declare interface IDeferrdValue { + resolve: (value: T) => void; + reject: (reason?: any) => void; +} + +export declare interface IReferenceBinding { + wrapped: number; + tag: Uint32Array | null; +} + +/** @public */ +export declare function isExternal(object: unknown): object is External_2; + +export declare function isReferenceType(v: any): v is object; + +export declare interface IStoreValue { + id: number; + dispose(): void; + [x: string]: any; +} + +export declare const NAPI_VERSION_EXPERIMENTAL = Version.NAPI_VERSION_EXPERIMENTAL; + +export declare const NODE_API_DEFAULT_MODULE_API_VERSION = Version.NODE_API_DEFAULT_MODULE_API_VERSION; + +export declare const NODE_API_SUPPORTED_VERSION_MAX = Version.NODE_API_SUPPORTED_VERSION_MAX; + +export declare const NODE_API_SUPPORTED_VERSION_MIN = Version.NODE_API_SUPPORTED_VERSION_MIN; + +export declare class NodeEnv extends Env { + filename: string; + private readonly nodeBinding?; + destructing: boolean; + finalizationScheduled: boolean; + constructor(ctx: Context, filename: string, moduleApiVersion: number, makeDynCall_vppp: (cb: Ptr) => (a: Ptr, b: Ptr, c: Ptr) => void, makeDynCall_vp: (cb: Ptr) => (a: Ptr) => void, abort: (msg?: string) => never, nodeBinding?: any); + deleteMe(): void; + canCallIntoJs(): boolean; + triggerFatalException(err: any): void; + callbackIntoModule(enforceUncaughtExceptionPolicy: boolean, fn: (env: Env) => T): T; + callFinalizer(cb: napi_finalize, data: void_p, hint: void_p): void; + callFinalizerInternal(forceUncaught: int, cb: napi_finalize, data: void_p, hint: void_p): void; + enqueueFinalizer(finalizer: RefTracker): void; + drainFinalizerQueue(): void; +} + +export declare class NotSupportBufferError extends EmnapiError { + constructor(api: string, message: string); +} + +export declare class NotSupportWeakRefError extends EmnapiError { + constructor(api: string, message: string); +} + +export declare class Persistent { + private _ref; + private _param; + private _callback; + private static readonly _registry; + constructor(value: T); + setWeak

(param: P, callback: (param: P) => void): void; + clearWeak(): void; + reset(): void; + isEmpty(): boolean; + deref(): T | undefined; +} + +export declare class Reference extends RefTracker implements IStoreValue { + private static weakCallback; + id: number; + envObject: Env; + private readonly canBeWeak; + private _refcount; + private readonly _ownership; + persistent: Persistent; + static create(envObject: Env, handle_id: napi_value, initialRefcount: uint32_t, ownership: ReferenceOwnership, _unused1?: void_p, _unused2?: void_p, _unused3?: void_p): Reference; + protected constructor(envObject: Env, handle_id: napi_value, initialRefcount: uint32_t, ownership: ReferenceOwnership); + ref(): number; + unref(): number; + get(envObject?: Env): napi_value; + /** @virtual */ + resetFinalizer(): void; + /** @virtual */ + data(): void_p; + refcount(): number; + ownership(): ReferenceOwnership; + /** @virtual */ + protected callUserFinalizer(): void; + /** @virtual */ + protected invokeFinalizerFromGC(): void; + private _setWeak; + finalize(): void; + dispose(): void; +} + +export declare enum ReferenceOwnership { + kRuntime = 0, + kUserland = 1 +} + +export declare class ReferenceWithData extends Reference { + private readonly _data; + static create(envObject: Env, value: napi_value, initialRefcount: uint32_t, ownership: ReferenceOwnership, data: void_p): ReferenceWithData; + private constructor(); + data(): void_p; +} + +export declare class ReferenceWithFinalizer extends Reference { + private _finalizer; + static create(envObject: Env, value: napi_value, initialRefcount: uint32_t, ownership: ReferenceOwnership, finalize_callback: napi_finalize, finalize_data: void_p, finalize_hint: void_p): ReferenceWithFinalizer; + private constructor(); + resetFinalizer(): void; + data(): void_p; + protected callUserFinalizer(): void; + protected invokeFinalizerFromGC(): void; + dispose(): void; +} + +export declare class RefTracker { + /** @virtual */ + dispose(): void; + /** @virtual */ + finalize(): void; + private _next; + private _prev; + link(list: RefTracker): void; + unlink(): void; + static finalizeAll(list: RefTracker): void; +} + +export declare class ScopeStore { + private readonly _rootScope; + currentScope: HandleScope; + private readonly _values; + constructor(); + get(id: number): HandleScope | undefined; + openScope(handleStore: HandleStore): HandleScope; + closeScope(): void; + dispose(): void; +} + +export declare class Store { + protected _values: Array; + private _freeList; + private _size; + constructor(); + add(value: V): void; + get(id: Ptr): V | undefined; + has(id: Ptr): boolean; + remove(id: Ptr): void; + dispose(): void; +} + +export declare class TrackedFinalizer extends RefTracker { + private _finalizer; + static create(envObject: Env, finalize_callback: napi_finalize, finalize_data: void_p, finalize_hint: void_p): TrackedFinalizer; + private constructor(); + data(): void_p; + dispose(): void; + finalize(): void; +} + +export declare class TryCatch { + private _exception; + private _caught; + isEmpty(): boolean; + hasCaught(): boolean; + exception(): any; + setError(err: any): void; + reset(): void; + extractException(): any; +} + +export declare const version: string; + +export { } diff --git a/dg-ui/node_modules/@tailwindcss/oxide-wasm32-wasi/node_modules/@emnapi/runtime/dist/emnapi.min.js b/dg-ui/node_modules/@tailwindcss/oxide-wasm32-wasi/node_modules/@emnapi/runtime/dist/emnapi.min.js new file mode 100644 index 0000000..afdaf6b --- /dev/null +++ b/dg-ui/node_modules/@tailwindcss/oxide-wasm32-wasi/node_modules/@emnapi/runtime/dist/emnapi.min.js @@ -0,0 +1 @@ +!function(t,e){"object"==typeof exports&&"undefined"!=typeof module?e(exports):"function"==typeof define&&define.amd?define(["exports"],e):e((t="undefined"!=typeof globalThis?globalThis:t||self).emnapi={})}(this,function(t){var e=function(t,n){return e=Object.setPrototypeOf||{__proto__:[]}instanceof Array&&function(t,e){t.__proto__=e}||function(t,e){for(var n in e)Object.prototype.hasOwnProperty.call(e,n)&&(t[n]=e[n])},e(t,n)};function n(t,n){if("function"!=typeof n&&null!==n)throw new TypeError("Class extends value "+String(n)+" is not a constructor or null");function i(){this.constructor=t}e(t,n),t.prototype=null===n?Object.create(n):(i.prototype=n.prototype,new i)}"function"==typeof SuppressedError&&SuppressedError;var i=new WeakMap;function r(t){return i.has(t)}var o=function(){function t(t){Object.setPrototypeOf(this,null),i.set(this,t)}return t.prototype=null,t}();function s(t){if(!r(t))throw new TypeError("not external");return i.get(t)}var a=function(){var t;try{t=new Function}catch(t){return!1}return"function"==typeof t}(),u=function(){if("undefined"!=typeof globalThis)return globalThis;var t=function(){return this}();if(!t&&a)try{t=new Function("return this")()}catch(t){}if(!t){if("undefined"==typeof __webpack_public_path__&&"undefined"!=typeof global)return global;if("undefined"!=typeof window)return window;if("undefined"!=typeof self)return self}return t}(),c=function(){function t(){this._exception=void 0,this._caught=!1}return t.prototype.isEmpty=function(){return!this._caught},t.prototype.hasCaught=function(){return this._caught},t.prototype.exception=function(){return this._exception},t.prototype.setError=function(t){this._caught=!0,this._exception=t},t.prototype.reset=function(){this._caught=!1,this._exception=void 0},t.prototype.extractException=function(){var t=this._exception;return this.reset(),t},t}(),p=function(){var t;try{return Boolean(null===(t=Object.getOwnPropertyDescriptor(Function.prototype,"name"))||void 0===t?void 0:t.configurable)}catch(t){return!1}}(),l="object"==typeof Reflect,f="undefined"!=typeof FinalizationRegistry&&"undefined"!=typeof WeakRef,h=function(){try{var t=Symbol();new WeakRef(t),(new WeakMap).set(t,void 0)}catch(t){return!1}return!0}(),d="undefined"!=typeof BigInt;var y=function(){return"undefined"!=typeof __webpack_public_path__||"undefined"!=typeof __webpack_public_path__?"undefined"!=typeof __non_webpack_require__?__non_webpack_require__:void 0:"undefined"!=typeof require?require:void 0}(),_="function"==typeof MessageChannel?MessageChannel:function(){try{return y("worker_threads").MessageChannel}catch(t){}}(),v="function"==typeof setImmediate?setImmediate.bind(u):function(t){if("function"!=typeof t)throw new TypeError('The "callback" argument must be of type function');if(_){var e=new _;e.port1.onmessage=function(){e.port1.onmessage=null,e=void 0,t()},e.port2.postMessage(null)}else setTimeout(t,0)},g="function"==typeof Buffer?Buffer:function(){try{return y("buffer").Buffer}catch(t){}}(),b="1.11.3",z=2147483647,w=function(){function t(t,e){this.id=t,this.value=e}return t.prototype.data=function(){return s(this.value)},t.prototype.isNumber=function(){return"number"==typeof this.value},t.prototype.isBigInt=function(){return"bigint"==typeof this.value},t.prototype.isString=function(){return"string"==typeof this.value},t.prototype.isFunction=function(){return"function"==typeof this.value},t.prototype.isExternal=function(){return r(this.value)},t.prototype.isObject=function(){return"object"==typeof this.value&&null!==this.value},t.prototype.isArray=function(){return Array.isArray(this.value)},t.prototype.isArrayBuffer=function(){return this.value instanceof ArrayBuffer},t.prototype.isTypedArray=function(){return ArrayBuffer.isView(this.value)&&!(this.value instanceof DataView)},t.prototype.isBuffer=function(t){return!!ArrayBuffer.isView(this.value)||(null!=t||(t=g),"function"==typeof t&&t.isBuffer(this.value))},t.prototype.isDataView=function(){return this.value instanceof DataView},t.prototype.isDate=function(){return this.value instanceof Date},t.prototype.isPromise=function(){return this.value instanceof Promise},t.prototype.isBoolean=function(){return"boolean"==typeof this.value},t.prototype.isUndefined=function(){return void 0===this.value},t.prototype.isSymbol=function(){return"symbol"==typeof this.value},t.prototype.isNull=function(){return null===this.value},t.prototype.dispose=function(){this.value=void 0},t}(),k=function(t){function e(e,n){return t.call(this,e,n)||this}return n(e,t),e.prototype.dispose=function(){},e}(w),m=function(){function t(){this._values=[void 0,t.UNDEFINED,t.NULL,t.FALSE,t.TRUE,t.GLOBAL],this._next=t.MIN_ID}return t.prototype.push=function(t){var e,n=this._next,i=this._values;return n=this.end)return null;this.handleStore.swap(t,this.start);var e=this.handleStore.get(this.start);return this.start++,this.parent.end++,e},t.prototype.escapeCalled=function(){return this._escapeCalled},t}(),S=function(){function t(){this._rootScope=new E(null,0,null,1,m.MIN_ID),this.currentScope=this._rootScope,this._values=[void 0]}return t.prototype.get=function(t){return this._values[t]},t.prototype.openScope=function(t){var e=this.currentScope,n=e.child;if(null!==n)n.start=n.end=e.end;else{var i=e.id+1;n=new E(t,i,e,e.end),this._values[i]=n}return this.currentScope=n,n},t.prototype.closeScope=function(){var t=this.currentScope;this.currentScope=t.parent,t.dispose()},t.prototype.dispose=function(){this.currentScope=this._rootScope,this._values.length=1},t}(),C=function(){function t(){this._next=null,this._prev=null}return t.prototype.dispose=function(){},t.prototype.finalize=function(){},t.prototype.link=function(t){this._prev=t,this._next=t._next,null!==this._next&&(this._next._prev=this),t._next=this},t.prototype.unlink=function(){null!==this._prev&&(this._prev._next=this._next),null!==this._next&&(this._next._prev=this._prev),this._prev=null,this._next=null},t.finalizeAll=function(t){for(;null!==t._next;)t._next.finalize()},t}(),x=function(){function t(t,e,n,i){void 0===e&&(e=0),void 0===n&&(n=0),void 0===i&&(i=0),this.envObject=t,this._finalizeCallback=e,this._finalizeData=n,this._finalizeHint=i,this._makeDynCall_vppp=t.makeDynCall_vppp}return t.prototype.callback=function(){return this._finalizeCallback},t.prototype.data=function(){return this._finalizeData},t.prototype.hint=function(){return this._finalizeHint},t.prototype.resetEnv=function(){this.envObject=void 0},t.prototype.resetFinalizer=function(){this._finalizeCallback=0,this._finalizeData=0,this._finalizeHint=0},t.prototype.callFinalizer=function(){var t=this._finalizeCallback,e=this._finalizeData,n=this._finalizeHint;if(this.resetFinalizer(),t){var i=Number(t);this.envObject?this.envObject.callFinalizer(i,e,n):this._makeDynCall_vppp(i)(0,e,n)}},t.prototype.dispose=function(){this.envObject=void 0,this._makeDynCall_vppp=void 0},t}(),F=function(t){function e(e,n,i,r){var o=t.call(this)||this;return o._finalizer=new x(e,n,i,r),o}return n(e,t),e.create=function(t,n,i,r){var o=new e(t,n,i,r);return o.link(t.finalizing_reflist),o},e.prototype.data=function(){return this._finalizer.data()},e.prototype.dispose=function(){this._finalizer&&(this.unlink(),this._finalizer.envObject.dequeueFinalizer(this),this._finalizer.dispose(),this._finalizer=void 0,t.prototype.dispose.call(this))},e.prototype.finalize=function(){var t;this.unlink();var e=!1;try{this._finalizer.callFinalizer()}catch(n){e=!0,t=n}if(this.dispose(),e)throw t},e}(C);function O(t,e){if(!t.terminatedOrTerminating())throw e}var I=function(){function t(t,e,n,i,r){this.ctx=t,this.moduleApiVersion=e,this.makeDynCall_vppp=n,this.makeDynCall_vp=i,this.abort=r,this.openHandleScopes=0,this.instanceData=null,this.tryCatch=new c,this.refs=1,this.reflist=new C,this.finalizing_reflist=new C,this.pendingFinalizers=[],this.lastError={errorCode:0,engineErrorCode:0,engineReserved:0},this.inGcFinalizer=!1,this._bindingMap=new WeakMap,this.id=0}return t.prototype.canCallIntoJs=function(){return!0},t.prototype.terminatedOrTerminating=function(){return!this.canCallIntoJs()},t.prototype.ref=function(){this.refs++},t.prototype.unref=function(){this.refs--,0===this.refs&&this.dispose()},t.prototype.ensureHandle=function(t){return this.ctx.ensureHandle(t)},t.prototype.ensureHandleId=function(t){return this.ensureHandle(t).id},t.prototype.clearLastError=function(){var t=this.lastError;return 0!==t.errorCode&&(t.errorCode=0),0!==t.engineErrorCode&&(t.engineErrorCode=0),0!==t.engineReserved&&(t.engineReserved=0),0},t.prototype.setLastError=function(t,e,n){void 0===e&&(e=0),void 0===n&&(n=0);var i=this.lastError;return i.errorCode!==t&&(i.errorCode=t),i.engineErrorCode!==e&&(i.engineErrorCode=e),i.engineReserved!==n&&(i.engineReserved=n),t},t.prototype.getReturnStatus=function(){return this.tryCatch.hasCaught()?this.setLastError(10):0},t.prototype.callIntoModule=function(t,e){void 0===e&&(e=O);var n=this.openHandleScopes;this.clearLastError();var i=t(this);(n!==this.openHandleScopes&&this.abort("open_handle_scopes != open_handle_scopes_before"),this.tryCatch.hasCaught())&&e(this,this.tryCatch.extractException());return i},t.prototype.invokeFinalizerFromGC=function(t){if(this.moduleApiVersion!==z)this.enqueueFinalizer(t);else{var e=this.inGcFinalizer;this.inGcFinalizer=!0;try{t.finalize()}finally{this.inGcFinalizer=e}}},t.prototype.checkGCAccess=function(){this.moduleApiVersion===z&&this.inGcFinalizer&&this.abort("Finalizer is calling a function that may affect GC state.\nThe finalizers are run directly from GC and must not affect GC state.\nUse `node_api_post_finalizer` from inside of the finalizer to work around this issue.\nIt schedules the call as a new task in the event loop.")},t.prototype.enqueueFinalizer=function(t){-1===this.pendingFinalizers.indexOf(t)&&this.pendingFinalizers.push(t)},t.prototype.dequeueFinalizer=function(t){var e=this.pendingFinalizers.indexOf(t);-1!==e&&this.pendingFinalizers.splice(e,1)},t.prototype.deleteMe=function(){C.finalizeAll(this.finalizing_reflist),C.finalizeAll(this.reflist),this.tryCatch.extractException(),this.ctx.envStore.remove(this.id)},t.prototype.dispose=function(){0!==this.id&&(this.deleteMe(),this.finalizing_reflist.dispose(),this.reflist.dispose(),this.id=0)},t.prototype.initObjectBinding=function(t){var e={wrapped:0,tag:null};return this._bindingMap.set(t,e),e},t.prototype.getObjectBinding=function(t){return this._bindingMap.has(t)?this._bindingMap.get(t):this.initObjectBinding(t)},t.prototype.setInstanceData=function(t,e,n){this.instanceData&&this.instanceData.dispose(),this.instanceData=F.create(this,e,t,n)},t.prototype.getInstanceData=function(){return this.instanceData?this.instanceData.data():0},t}(),D=function(t){function e(e,n,i,r,o,s,a){var u=t.call(this,e,i,r,o,s)||this;return u.filename=n,u.nodeBinding=a,u.destructing=!1,u.finalizationScheduled=!1,u}return n(e,t),e.prototype.deleteMe=function(){this.destructing=!0,this.drainFinalizerQueue(),t.prototype.deleteMe.call(this)},e.prototype.canCallIntoJs=function(){return t.prototype.canCallIntoJs.call(this)&&this.ctx.canCallIntoJs()},e.prototype.triggerFatalException=function(t){if(this.nodeBinding)this.nodeBinding.napi.fatalException(t);else{if("object"!=typeof process||null===process||"function"!=typeof process._fatalException)throw t;process._fatalException(t)||(console.error(t),process.exit(1))}},e.prototype.callbackIntoModule=function(t,e){return this.callIntoModule(e,function(e,n){if(!e.terminatedOrTerminating()){var i="object"==typeof process&&null!==process,r=!!i&&Boolean(process.execArgv&&-1!==process.execArgv.indexOf("--force-node-api-uncaught-exceptions-policy"));if(e.moduleApiVersion<10&&!r&&!t)(i&&"function"==typeof process.emitWarning?process.emitWarning:function(t,e,n){if(t instanceof Error)console.warn(t.toString());else{var i=n?"[".concat(n,"] "):"";console.warn("".concat(i).concat(e||"Warning",": ").concat(t))}})("Uncaught Node-API callback exception detected, please run node with option --force-node-api-uncaught-exceptions-policy=true to handle those exceptions properly.","DeprecationWarning","DEP0168");else e.triggerFatalException(n)}})},e.prototype.callFinalizer=function(t,e,n){this.callFinalizerInternal(1,t,e,n)},e.prototype.callFinalizerInternal=function(t,e,n,i){var r=this.makeDynCall_vppp(e),o=this.id,s=this.ctx.openScope(this);try{this.callbackIntoModule(Boolean(t),function(){r(o,n,i)})}finally{this.ctx.closeScope(this,s)}},e.prototype.enqueueFinalizer=function(e){var n=this;t.prototype.enqueueFinalizer.call(this,e),this.finalizationScheduled||this.destructing||(this.finalizationScheduled=!0,this.ref(),v(function(){n.finalizationScheduled=!1,n.unref(),n.drainFinalizerQueue()}))},e.prototype.drainFinalizerQueue=function(){for(;this.pendingFinalizers.length>0;){this.pendingFinalizers.shift().finalize()}},e}(I);function R(t,e,n,i,r,o,s){(n="number"!=typeof n?8:n)<8?n=8:n>10&&n!==z&&function(t,e){var n="".concat(t," requires Node-API version ").concat(e,", but this version of Node.js only supports version ").concat(10," add-ons.");throw new Error(n)}(e,n);var a=new D(t,e,n,i,r,o,s);return t.envStore.add(a),t.addCleanupHook(a,function(){a.unref()},0),a}var N=function(t){function e(n){var i=this.constructor,r=t.call(this,n)||this,o=i,s=o.prototype;if(!(r instanceof e)){var a=Object.setPrototypeOf;"function"==typeof a?a.call(Object,r,s):r.__proto__=s,"function"==typeof Error.captureStackTrace&&Error.captureStackTrace(r,o)}return r}return n(e,t),e}(Error);Object.defineProperty(N.prototype,"name",{configurable:!0,writable:!0,value:"EmnapiError"});var j=function(t){function e(e,n){return t.call(this,"".concat(e,': The current runtime does not support "FinalizationRegistry" and "WeakRef".').concat(n?" ".concat(n):""))||this}return n(e,t),e}(N);Object.defineProperty(j.prototype,"name",{configurable:!0,writable:!0,value:"NotSupportWeakRefError"});var A=function(t){function e(e,n){return t.call(this,"".concat(e,': The current runtime does not support "Buffer". Consider using buffer polyfill to make sure `globalThis.Buffer` is defined.').concat(n?" ".concat(n):""))||this}return n(e,t),e}(N);Object.defineProperty(A.prototype,"name",{configurable:!0,writable:!0,value:"NotSupportBufferError"});var H,B=function(){function t(t){this._value=t}return t.prototype.deref=function(){return this._value},t.prototype.dispose=function(){this._value=void 0},t}(),M=function(){function t(t){this._ref=new B(t)}return t.prototype.setWeak=function(e,n){if(f&&void 0!==this._ref&&!(this._ref instanceof WeakRef)){var i=this._ref.deref();try{t._registry.register(i,this,this);var r=new WeakRef(i);this._ref.dispose(),this._ref=r,this._param=e,this._callback=n}catch(t){if("symbol"!=typeof i)throw t}}},t.prototype.clearWeak=function(){if(f&&void 0!==this._ref&&this._ref instanceof WeakRef){try{t._registry.unregister(this)}catch(t){}this._param=void 0,this._callback=void 0;var e=this._ref.deref();this._ref=void 0===e?e:new B(e)}},t.prototype.reset=function(){if(f)try{t._registry.unregister(this)}catch(t){}this._param=void 0,this._callback=void 0,this._ref instanceof B&&this._ref.dispose(),this._ref=void 0},t.prototype.isEmpty=function(){return void 0===this._ref},t.prototype.deref=function(){if(void 0!==this._ref)return this._ref.deref()},t._registry=f?new FinalizationRegistry(function(t){t._ref=void 0;var e=t._callback,n=t._param;t._callback=void 0,t._param=void 0,"function"==typeof e&&e(n)}):void 0,t}();t.ReferenceOwnership=void 0,(H=t.ReferenceOwnership||(t.ReferenceOwnership={}))[H.kRuntime=0]="kRuntime",H[H.kUserland=1]="kUserland";var T,W=function(e){function i(t,n,i,r){var o=e.call(this)||this;o.envObject=t,o._refcount=i,o._ownership=r;var s,a=t.ctx.handleStore.get(n);return o.canBeWeak=(s=a).isObject()||s.isFunction()||s.isSymbol(),o.persistent=new M(a.value),o.id=0,0===i&&o._setWeak(),o}return n(i,e),i.weakCallback=function(t){t.persistent.reset(),t.invokeFinalizerFromGC()},i.create=function(t,e,n,r,o,s,a){var u=new i(t,e,n,r);return t.ctx.refStore.add(u),u.link(t.reflist),u},i.prototype.ref=function(){return this.persistent.isEmpty()?0:(1===++this._refcount&&this.canBeWeak&&this.persistent.clearWeak(),this._refcount)},i.prototype.unref=function(){return this.persistent.isEmpty()||0===this._refcount?0:(0===--this._refcount&&this._setWeak(),this._refcount)},i.prototype.get=function(t){if(void 0===t&&(t=this.envObject),this.persistent.isEmpty())return 0;var e=this.persistent.deref();return t.ensureHandle(e).id},i.prototype.resetFinalizer=function(){},i.prototype.data=function(){return 0},i.prototype.refcount=function(){return this._refcount},i.prototype.ownership=function(){return this._ownership},i.prototype.callUserFinalizer=function(){},i.prototype.invokeFinalizerFromGC=function(){this.finalize()},i.prototype._setWeak=function(){this.canBeWeak?this.persistent.setWeak(this,i.weakCallback):this.persistent.reset()},i.prototype.finalize=function(){this.persistent.reset();var e=this._ownership===t.ReferenceOwnership.kRuntime;this.unlink(),this.callUserFinalizer(),e&&this.dispose()},i.prototype.dispose=function(){0!==this.id&&(this.unlink(),this.persistent.reset(),this.envObject.ctx.refStore.remove(this.id),e.prototype.dispose.call(this),this.envObject=void 0,this.id=0)},i}(C),P=function(t){function e(e,n,i,r,o){var s=t.call(this,e,n,i,r)||this;return s._data=o,s}return n(e,t),e.create=function(t,n,i,r,o){var s=new e(t,n,i,r,o);return t.ctx.refStore.add(s),s.link(t.reflist),s},e.prototype.data=function(){return this._data},e}(W),L=function(t){function e(e,n,i,r,o,s,a){var u=t.call(this,e,n,i,r)||this;return u._finalizer=new x(e,o,s,a),u}return n(e,t),e.create=function(t,n,i,r,o,s,a){var u=new e(t,n,i,r,o,s,a);return t.ctx.refStore.add(u),u.link(t.finalizing_reflist),u},e.prototype.resetFinalizer=function(){this._finalizer.resetFinalizer()},e.prototype.data=function(){return this._finalizer.data()},e.prototype.callUserFinalizer=function(){this._finalizer.callFinalizer()},e.prototype.invokeFinalizerFromGC=function(){this._finalizer.envObject.invokeFinalizerFromGC(this)},e.prototype.dispose=function(){this._finalizer&&(this._finalizer.envObject.dequeueFinalizer(this),this._finalizer.dispose(),t.prototype.dispose.call(this),this._finalizer=void 0)},e}(W),U=function(){function t(t,e){Object.defineProperties(this,{id:{configurable:!0,enumerable:!0,value:0,writable:!0},ctx:{configurable:!0,enumerable:!0,value:t,writable:!0},value:{configurable:!0,enumerable:!0,value:e,writable:!0}})}return t.create=function(e,n){var i=new t(e,n);return e.deferredStore.add(i),i},t.prototype.resolve=function(t){this.value.resolve(t),this.dispose()},t.prototype.reject=function(t){this.value.reject(t),this.dispose()},t.prototype.dispose=function(){this.ctx.deferredStore.remove(this.id),this.id=0,this.value=null,this.ctx=null},t}(),V=function(){function t(){this._values=[void 0],this._values.length=4,this._size=1,this._freeList=[]}return t.prototype.add=function(t){var e;if(this._freeList.length)e=this._freeList.shift();else{e=this._size,this._size++;var n=this._values.length;e>=n&&(this._values.length=n+(n>>1)+16)}t.id=e,this._values[e]=t},t.prototype.get=function(t){return this._values[t]},t.prototype.has=function(t){return void 0!==this._values[t]},t.prototype.remove=function(t){var e=this._values[t];e&&(e.id=0,this._values[t]=void 0,this._freeList.push(Number(t)))},t.prototype.dispose=function(){for(var t=1;t0)throw new Error("Can not add same fn and arg twice");this._cleanupHooks.push(new Q(t,e,n,this._cleanupHookCounter++))},t.prototype.remove=function(t,e,n){for(var i=0;i{function t(t){Object.setPrototypeOf(this,null),e.set(this,t)}return t.prototype=null,t})();function n(i){if(!t(i))throw new TypeError("not external");return e.get(i)}const s=function(){let e;try{e=new Function}catch(e){return!1}return"function"==typeof e}(),r=function(){if("undefined"!=typeof globalThis)return globalThis;let e=function(){return this}();if(!e&&s)try{e=new Function("return this")()}catch(e){}if(!e){if("undefined"==typeof __webpack_public_path__&&"undefined"!=typeof global)return global;if("undefined"!=typeof window)return window;if("undefined"!=typeof self)return self}return e}();class a{constructor(){this._exception=void 0,this._caught=!1}isEmpty(){return!this._caught}hasCaught(){return this._caught}exception(){return this._exception}setError(e){this._caught=!0,this._exception=e}reset(){this._caught=!1,this._exception=void 0}extractException(){const e=this._exception;return this.reset(),e}}const o=function(){var e;try{return Boolean(null===(e=Object.getOwnPropertyDescriptor(Function.prototype,"name"))||void 0===e?void 0:e.configurable)}catch(e){return!1}}(),l="object"==typeof Reflect,c="undefined"!=typeof FinalizationRegistry&&"undefined"!=typeof WeakRef,u=function(){try{const e=Symbol();new WeakRef(e),(new WeakMap).set(e,void 0)}catch(e){return!1}return!0}(),h="undefined"!=typeof BigInt;function p(e){return"object"==typeof e&&null!==e||"function"==typeof e}const f=function(){let e;return e="undefined"!=typeof __webpack_public_path__||"undefined"!=typeof __webpack_public_path__?"undefined"!=typeof __non_webpack_require__?__non_webpack_require__:void 0:"undefined"!=typeof require?require:void 0,e}(),d="function"==typeof MessageChannel?MessageChannel:function(){try{return f("worker_threads").MessageChannel}catch(e){}}(),_="function"==typeof setImmediate?setImmediate.bind(r):function(e){if("function"!=typeof e)throw new TypeError('The "callback" argument must be of type function');if(d){let t=new d;t.port1.onmessage=function(){t.port1.onmessage=null,t=void 0,e()},t.port2.postMessage(null)}else setTimeout(e,0)},v="function"==typeof Buffer?Buffer:function(){try{return f("buffer").Buffer}catch(e){}}(),g="1.11.3",y=1,b=10,z=2147483647,k=8;class w{constructor(e,t){this.id=e,this.value=t}data(){return n(this.value)}isNumber(){return"number"==typeof this.value}isBigInt(){return"bigint"==typeof this.value}isString(){return"string"==typeof this.value}isFunction(){return"function"==typeof this.value}isExternal(){return t(this.value)}isObject(){return"object"==typeof this.value&&null!==this.value}isArray(){return Array.isArray(this.value)}isArrayBuffer(){return this.value instanceof ArrayBuffer}isTypedArray(){return ArrayBuffer.isView(this.value)&&!(this.value instanceof DataView)}isBuffer(e){return!!ArrayBuffer.isView(this.value)||(null!=e||(e=v),"function"==typeof e&&e.isBuffer(this.value))}isDataView(){return this.value instanceof DataView}isDate(){return this.value instanceof Date}isPromise(){return this.value instanceof Promise}isBoolean(){return"boolean"==typeof this.value}isUndefined(){return void 0===this.value}isSymbol(){return"symbol"==typeof this.value}isNull(){return null===this.value}dispose(){this.value=void 0}}class m extends w{constructor(e,t){super(e,t)}dispose(){}}class C{constructor(){this._values=[void 0,C.UNDEFINED,C.NULL,C.FALSE,C.TRUE,C.GLOBAL],this._next=C.MIN_ID}push(e){let t;const i=this._next,n=this._values;return i=this.end)return null;this.handleStore.swap(e,this.start);const t=this.handleStore.get(this.start);return this.start++,this.parent.end++,t}escapeCalled(){return this._escapeCalled}}class x{constructor(){this._rootScope=new S(null,0,null,1,C.MIN_ID),this.currentScope=this._rootScope,this._values=[void 0]}get(e){return this._values[e]}openScope(e){const t=this.currentScope;let i=t.child;if(null!==i)i.start=i.end=t.end;else{const n=t.id+1;i=new S(e,n,t,t.end),this._values[n]=i}return this.currentScope=i,i}closeScope(){const e=this.currentScope;this.currentScope=e.parent,e.dispose()}dispose(){this.currentScope=this._rootScope,this._values.length=1}}class E{constructor(){this._next=null,this._prev=null}dispose(){}finalize(){}link(e){this._prev=e,this._next=e._next,null!==this._next&&(this._next._prev=this),e._next=this}unlink(){null!==this._prev&&(this._prev._next=this._next),null!==this._next&&(this._next._prev=this._prev),this._prev=null,this._next=null}static finalizeAll(e){for(;null!==e._next;)e._next.finalize()}}class F{constructor(e,t=0,i=0,n=0){this.envObject=e,this._finalizeCallback=t,this._finalizeData=i,this._finalizeHint=n,this._makeDynCall_vppp=e.makeDynCall_vppp}callback(){return this._finalizeCallback}data(){return this._finalizeData}hint(){return this._finalizeHint}resetEnv(){this.envObject=void 0}resetFinalizer(){this._finalizeCallback=0,this._finalizeData=0,this._finalizeHint=0}callFinalizer(){const e=this._finalizeCallback,t=this._finalizeData,i=this._finalizeHint;if(this.resetFinalizer(),!e)return;const n=Number(e);this.envObject?this.envObject.callFinalizer(n,t,i):this._makeDynCall_vppp(n)(0,t,i)}dispose(){this.envObject=void 0,this._makeDynCall_vppp=void 0}}class I extends E{static create(e,t,i,n){const s=new I(e,t,i,n);return s.link(e.finalizing_reflist),s}constructor(e,t,i,n){super(),this._finalizer=new F(e,t,i,n)}data(){return this._finalizer.data()}dispose(){this._finalizer&&(this.unlink(),this._finalizer.envObject.dequeueFinalizer(this),this._finalizer.dispose(),this._finalizer=void 0,super.dispose())}finalize(){let e;this.unlink();let t=!1;try{this._finalizer.callFinalizer()}catch(i){t=!0,e=i}if(this.dispose(),t)throw e}}function D(e,t){if(!e.terminatedOrTerminating())throw t}class O{constructor(e,t,i,n,s){this.ctx=e,this.moduleApiVersion=t,this.makeDynCall_vppp=i,this.makeDynCall_vp=n,this.abort=s,this.openHandleScopes=0,this.instanceData=null,this.tryCatch=new a,this.refs=1,this.reflist=new E,this.finalizing_reflist=new E,this.pendingFinalizers=[],this.lastError={errorCode:0,engineErrorCode:0,engineReserved:0},this.inGcFinalizer=!1,this._bindingMap=new WeakMap,this.id=0}canCallIntoJs(){return!0}terminatedOrTerminating(){return!this.canCallIntoJs()}ref(){this.refs++}unref(){this.refs--,0===this.refs&&this.dispose()}ensureHandle(e){return this.ctx.ensureHandle(e)}ensureHandleId(e){return this.ensureHandle(e).id}clearLastError(){const e=this.lastError;return 0!==e.errorCode&&(e.errorCode=0),0!==e.engineErrorCode&&(e.engineErrorCode=0),0!==e.engineReserved&&(e.engineReserved=0),0}setLastError(e,t=0,i=0){const n=this.lastError;return n.errorCode!==e&&(n.errorCode=e),n.engineErrorCode!==t&&(n.engineErrorCode=t),n.engineReserved!==i&&(n.engineReserved=i),e}getReturnStatus(){return this.tryCatch.hasCaught()?this.setLastError(10):0}callIntoModule(e,t=D){const i=this.openHandleScopes;this.clearLastError();const n=e(this);if(i!==this.openHandleScopes&&this.abort("open_handle_scopes != open_handle_scopes_before"),this.tryCatch.hasCaught()){t(this,this.tryCatch.extractException())}return n}invokeFinalizerFromGC(e){if(this.moduleApiVersion!==z)this.enqueueFinalizer(e);else{const t=this.inGcFinalizer;this.inGcFinalizer=!0;try{e.finalize()}finally{this.inGcFinalizer=t}}}checkGCAccess(){this.moduleApiVersion===z&&this.inGcFinalizer&&this.abort("Finalizer is calling a function that may affect GC state.\nThe finalizers are run directly from GC and must not affect GC state.\nUse `node_api_post_finalizer` from inside of the finalizer to work around this issue.\nIt schedules the call as a new task in the event loop.")}enqueueFinalizer(e){-1===this.pendingFinalizers.indexOf(e)&&this.pendingFinalizers.push(e)}dequeueFinalizer(e){const t=this.pendingFinalizers.indexOf(e);-1!==t&&this.pendingFinalizers.splice(t,1)}deleteMe(){E.finalizeAll(this.finalizing_reflist),E.finalizeAll(this.reflist),this.tryCatch.extractException(),this.ctx.envStore.remove(this.id)}dispose(){0!==this.id&&(this.deleteMe(),this.finalizing_reflist.dispose(),this.reflist.dispose(),this.id=0)}initObjectBinding(e){const t={wrapped:0,tag:null};return this._bindingMap.set(e,t),t}getObjectBinding(e){return this._bindingMap.has(e)?this._bindingMap.get(e):this.initObjectBinding(e)}setInstanceData(e,t,i){this.instanceData&&this.instanceData.dispose(),this.instanceData=I.create(this,t,e,i)}getInstanceData(){return this.instanceData?this.instanceData.data():0}}class j extends O{constructor(e,t,i,n,s,r,a){super(e,i,n,s,r),this.filename=t,this.nodeBinding=a,this.destructing=!1,this.finalizationScheduled=!1}deleteMe(){this.destructing=!0,this.drainFinalizerQueue(),super.deleteMe()}canCallIntoJs(){return super.canCallIntoJs()&&this.ctx.canCallIntoJs()}triggerFatalException(e){if(this.nodeBinding)this.nodeBinding.napi.fatalException(e);else{if("object"!=typeof process||null===process||"function"!=typeof process._fatalException)throw e;process._fatalException(e)||(console.error(e),process.exit(1))}}callbackIntoModule(e,t){return this.callIntoModule(t,(t,i)=>{if(t.terminatedOrTerminating())return;const n="object"==typeof process&&null!==process,s=!!n&&Boolean(process.execArgv&&-1!==process.execArgv.indexOf("--force-node-api-uncaught-exceptions-policy"));if(t.moduleApiVersion<10&&!s&&!e){return void(n&&"function"==typeof process.emitWarning?process.emitWarning:function(e,t,i){if(e instanceof Error)console.warn(e.toString());else{const n=i?`[${i}] `:"";console.warn(`${n}${t||"Warning"}: ${e}`)}})("Uncaught Node-API callback exception detected, please run node with option --force-node-api-uncaught-exceptions-policy=true to handle those exceptions properly.","DeprecationWarning","DEP0168")}t.triggerFatalException(i)})}callFinalizer(e,t,i){this.callFinalizerInternal(1,e,t,i)}callFinalizerInternal(e,t,i,n){const s=this.makeDynCall_vppp(t),r=this.id,a=this.ctx.openScope(this);try{this.callbackIntoModule(Boolean(e),()=>{s(r,i,n)})}finally{this.ctx.closeScope(this,a)}}enqueueFinalizer(e){super.enqueueFinalizer(e),this.finalizationScheduled||this.destructing||(this.finalizationScheduled=!0,this.ref(),_(()=>{this.finalizationScheduled=!1,this.unref(),this.drainFinalizerQueue()}))}drainFinalizerQueue(){for(;this.pendingFinalizers.length>0;){this.pendingFinalizers.shift().finalize()}}}function B(e,t,i,n,s,r,a){(i="number"!=typeof i?8:i)<8?i=8:i>10&&i!==z&&function(e,t){throw new Error(`${e} requires Node-API version ${t}, but this version of Node.js only supports version 10 add-ons.`)}(t,i);const o=new j(e,t,i,n,s,r,a);return e.envStore.add(o),e.addCleanupHook(o,()=>{o.unref()},0),o}class H extends Error{constructor(e){super(e);const t=new.target,i=t.prototype;if(!(this instanceof H)){const e=Object.setPrototypeOf;"function"==typeof e?e.call(Object,this,i):this.__proto__=i,"function"==typeof Error.captureStackTrace&&Error.captureStackTrace(this,t)}}}Object.defineProperty(H.prototype,"name",{configurable:!0,writable:!0,value:"EmnapiError"});class R extends H{constructor(e,t){super(`${e}: The current runtime does not support "FinalizationRegistry" and "WeakRef".${t?` ${t}`:""}`)}}Object.defineProperty(R.prototype,"name",{configurable:!0,writable:!0,value:"NotSupportWeakRefError"});class N extends H{constructor(e,t){super(`${e}: The current runtime does not support "Buffer". Consider using buffer polyfill to make sure \`globalThis.Buffer\` is defined.${t?` ${t}`:""}`)}}Object.defineProperty(N.prototype,"name",{configurable:!0,writable:!0,value:"NotSupportBufferError"});class A{constructor(e){this._value=e}deref(){return this._value}dispose(){this._value=void 0}}class M{constructor(e){this._ref=new A(e)}setWeak(e,t){if(!c||void 0===this._ref||this._ref instanceof WeakRef)return;const i=this._ref.deref();try{M._registry.register(i,this,this);const n=new WeakRef(i);this._ref.dispose(),this._ref=n,this._param=e,this._callback=t}catch(e){if("symbol"!=typeof i)throw e}}clearWeak(){if(c&&void 0!==this._ref&&this._ref instanceof WeakRef){try{M._registry.unregister(this)}catch(e){}this._param=void 0,this._callback=void 0;const e=this._ref.deref();this._ref=void 0===e?e:new A(e)}}reset(){if(c)try{M._registry.unregister(this)}catch(e){}this._param=void 0,this._callback=void 0,this._ref instanceof A&&this._ref.dispose(),this._ref=void 0}isEmpty(){return void 0===this._ref}deref(){if(void 0!==this._ref)return this._ref.deref()}}var W;M._registry=c?new FinalizationRegistry(e=>{e._ref=void 0;const t=e._callback,i=e._param;e._callback=void 0,e._param=void 0,"function"==typeof t&&t(i)}):void 0,function(e){e[e.kRuntime=0]="kRuntime",e[e.kUserland=1]="kUserland"}(W||(W={}));class L extends E{static weakCallback(e){e.persistent.reset(),e.invokeFinalizerFromGC()}static create(e,t,i,n,s,r,a){const o=new L(e,t,i,n);return e.ctx.refStore.add(o),o.link(e.reflist),o}constructor(e,t,i,n){super(),this.envObject=e,this._refcount=i,this._ownership=n;const s=e.ctx.handleStore.get(t);var r;this.canBeWeak=(r=s).isObject()||r.isFunction()||r.isSymbol(),this.persistent=new M(s.value),this.id=0,0===i&&this._setWeak()}ref(){return this.persistent.isEmpty()?0:(1===++this._refcount&&this.canBeWeak&&this.persistent.clearWeak(),this._refcount)}unref(){return this.persistent.isEmpty()||0===this._refcount?0:(0===--this._refcount&&this._setWeak(),this._refcount)}get(e=this.envObject){if(this.persistent.isEmpty())return 0;const t=this.persistent.deref();return e.ensureHandle(t).id}resetFinalizer(){}data(){return 0}refcount(){return this._refcount}ownership(){return this._ownership}callUserFinalizer(){}invokeFinalizerFromGC(){this.finalize()}_setWeak(){this.canBeWeak?this.persistent.setWeak(this,L.weakCallback):this.persistent.reset()}finalize(){this.persistent.reset();const e=this._ownership===W.kRuntime;this.unlink(),this.callUserFinalizer(),e&&this.dispose()}dispose(){0!==this.id&&(this.unlink(),this.persistent.reset(),this.envObject.ctx.refStore.remove(this.id),super.dispose(),this.envObject=void 0,this.id=0)}}class T extends L{static create(e,t,i,n,s){const r=new T(e,t,i,n,s);return e.ctx.refStore.add(r),r.link(e.reflist),r}constructor(e,t,i,n,s){super(e,t,i,n),this._data=s}data(){return this._data}}class U extends L{static create(e,t,i,n,s,r,a){const o=new U(e,t,i,n,s,r,a);return e.ctx.refStore.add(o),o.link(e.finalizing_reflist),o}constructor(e,t,i,n,s,r,a){super(e,t,i,n),this._finalizer=new F(e,s,r,a)}resetFinalizer(){this._finalizer.resetFinalizer()}data(){return this._finalizer.data()}callUserFinalizer(){this._finalizer.callFinalizer()}invokeFinalizerFromGC(){this._finalizer.envObject.invokeFinalizerFromGC(this)}dispose(){this._finalizer&&(this._finalizer.envObject.dequeueFinalizer(this),this._finalizer.dispose(),super.dispose(),this._finalizer=void 0)}}class P{static create(e,t){const i=new P(e,t);return e.deferredStore.add(i),i}constructor(e,t){Object.defineProperties(this,{id:{configurable:!0,enumerable:!0,value:0,writable:!0},ctx:{configurable:!0,enumerable:!0,value:e,writable:!0},value:{configurable:!0,enumerable:!0,value:t,writable:!0}})}resolve(e){this.value.resolve(e),this.dispose()}reject(e){this.value.reject(e),this.dispose()}dispose(){this.ctx.deferredStore.remove(this.id),this.id=0,this.value=null,this.ctx=null}}class G{constructor(){this._values=[void 0],this._values.length=4,this._size=1,this._freeList=[]}add(e){let t;if(this._freeList.length)t=this._freeList.shift();else{t=this._size,this._size++;const e=this._values.length;t>=e&&(this._values.length=e+(e>>1)+16)}e.id=t,this._values[t]=e}get(e){return this._values[e]}has(e){return void 0!==this._values[e]}remove(e){const t=this._values[e];t&&(t.id=0,this._values[e]=void 0,this._freeList.push(Number(e)))}dispose(){for(let e=1;en.envObject===e&&n.fn===t&&n.arg===i).length>0)throw new Error("Can not add same fn and arg twice");this._cleanupHooks.push(new J(e,t,i,this._cleanupHookCounter++))}remove(e,t,i){for(let n=0;nt.order-e.order);for(let t=0;t{this._suppressDestroy||this.destroy()}))}suppressDestroy(){this._suppressDestroy=!0}getRuntimeVersions(){return{version:g,NODE_API_SUPPORTED_VERSION_MAX:10,NAPI_VERSION_EXPERIMENTAL:z,NODE_API_DEFAULT_MODULE_API_VERSION:8}}createNotSupportWeakRefError(e,t){return new R(e,t)}createNotSupportBufferError(e,t){return new N(e,t)}createReference(e,t,i,n){return L.create(e,t,i,n)}createReferenceWithData(e,t,i,n,s){return T.create(e,t,i,n,s)}createReferenceWithFinalizer(e,t,i,n,s=0,r=0,a=0){return U.create(e,t,i,n,s,r,a)}createDeferred(e){return P.create(this,e)}adjustAmountOfExternalAllocatedMemory(e){return this._externalMemory.adjust(e)}createEnv(e,t,i,n,s,r){return B(this,e,t,i,n,s,r)}createTrackedFinalizer(e,t,i,n){return I.create(e,t,i,n)}getCurrentScope(){return this.scopeStore.currentScope}addToCurrentScope(e){return this.scopeStore.currentScope.add(e)}openScope(e){const t=this.scopeStore.openScope(this.handleStore);return e&&e.openHandleScopes++,t}closeScope(e,t){e&&0===e.openHandleScopes||(this.scopeStore.closeScope(),e&&e.openHandleScopes--)}ensureHandle(e){switch(e){case void 0:return C.UNDEFINED;case null:return C.NULL;case!0:return C.TRUE;case!1:return C.FALSE;case r:return C.GLOBAL}return this.addToCurrentScope(e)}addCleanupHook(e,t,i){this.cleanupQueue.add(e,t,i)}removeCleanupHook(e,t,i){this.cleanupQueue.remove(e,t,i)}runCleanup(){for(;!this.cleanupQueue.empty();)this.cleanupQueue.drain()}increaseWaitingRequestCounter(){var e;null===(e=this.refCounter)||void 0===e||e.increase()}decreaseWaitingRequestCounter(){var e;null===(e=this.refCounter)||void 0===e||e.decrease()}setCanCallIntoJs(e){this._canCallIntoJs=e}setStopping(e){this._isStopping=e}canCallIntoJs(){return this._canCallIntoJs&&!this._isStopping}destroy(){this.setStopping(!0),this.setCanCallIntoJs(!1),this.runCleanup()}}let Y;function Z(e){return new K(e)}function ee(){return Y||(Y=Z()),Y}export{m as ConstHandle,K as Context,P as Deferred,H as EmnapiError,O as Env,i as External,F as Finalizer,w as Handle,S as HandleScope,C as HandleStore,z as NAPI_VERSION_EXPERIMENTAL,k as NODE_API_DEFAULT_MODULE_API_VERSION,b as NODE_API_SUPPORTED_VERSION_MAX,y as NODE_API_SUPPORTED_VERSION_MIN,j as NodeEnv,N as NotSupportBufferError,R as NotSupportWeakRefError,M as Persistent,E as RefTracker,L as Reference,W as ReferenceOwnership,T as ReferenceWithData,U as ReferenceWithFinalizer,x as ScopeStore,G as Store,I as TrackedFinalizer,a as TryCatch,Z as createContext,ee as getDefaultContext,n as getExternalValue,t as isExternal,p as isReferenceType,g as version}; diff --git a/dg-ui/node_modules/@tailwindcss/oxide-wasm32-wasi/node_modules/@emnapi/runtime/dist/emnapi.mjs b/dg-ui/node_modules/@tailwindcss/oxide-wasm32-wasi/node_modules/@emnapi/runtime/dist/emnapi.mjs new file mode 100644 index 0000000..18e8115 --- /dev/null +++ b/dg-ui/node_modules/@tailwindcss/oxide-wasm32-wasi/node_modules/@emnapi/runtime/dist/emnapi.mjs @@ -0,0 +1,1367 @@ +const externalValue = new WeakMap(); +function isExternal(object) { + return externalValue.has(object); +} +const External = (() => { + function External(value) { + Object.setPrototypeOf(this, null); + externalValue.set(this, value); + } + External.prototype = null; + return External; +})(); +function getExternalValue(external) { + if (!isExternal(external)) { + throw new TypeError('not external'); + } + return externalValue.get(external); +} + +const supportNewFunction = (function () { + let f; + try { + f = new Function(); + } + catch (_) { + return false; + } + return typeof f === 'function'; +})(); +const _global = (function () { + if (typeof globalThis !== 'undefined') + return globalThis; + let g = (function () { return this; })(); + if (!g && supportNewFunction) { + try { + g = new Function('return this')(); + } + catch (_) { } + } + if (!g) { + if (typeof __webpack_public_path__ === 'undefined') { + if (typeof global !== 'undefined') + return global; + } + if (typeof window !== 'undefined') + return window; + if (typeof self !== 'undefined') + return self; + } + return g; +})(); +class TryCatch { + constructor() { + this._exception = undefined; + this._caught = false; + } + isEmpty() { + return !this._caught; + } + hasCaught() { + return this._caught; + } + exception() { + return this._exception; + } + setError(err) { + this._caught = true; + this._exception = err; + } + reset() { + this._caught = false; + this._exception = undefined; + } + extractException() { + const e = this._exception; + this.reset(); + return e; + } +} +const canSetFunctionName = (function () { + var _a; + try { + return Boolean((_a = Object.getOwnPropertyDescriptor(Function.prototype, 'name')) === null || _a === void 0 ? void 0 : _a.configurable); + } + catch (_) { + return false; + } +})(); +const supportReflect = typeof Reflect === 'object'; +const supportFinalizer = (typeof FinalizationRegistry !== 'undefined') && (typeof WeakRef !== 'undefined'); +const supportWeakSymbol = (function () { + try { + const sym = Symbol(); + new WeakRef(sym); + new WeakMap().set(sym, undefined); + } + catch (_) { + return false; + } + return true; +})(); +const supportBigInt = typeof BigInt !== 'undefined'; +function isReferenceType(v) { + return (typeof v === 'object' && v !== null) || typeof v === 'function'; +} +const _require = (function () { + let nativeRequire; + if (typeof __webpack_public_path__ !== 'undefined') { + nativeRequire = (function () { + return typeof __non_webpack_require__ !== 'undefined' ? __non_webpack_require__ : undefined; + })(); + } + else { + nativeRequire = (function () { + return typeof __webpack_public_path__ !== 'undefined' ? (typeof __non_webpack_require__ !== 'undefined' ? __non_webpack_require__ : undefined) : (typeof require !== 'undefined' ? require : undefined); + })(); + } + return nativeRequire; +})(); +const _MessageChannel = typeof MessageChannel === 'function' + ? MessageChannel + : (function () { + try { + return _require('worker_threads').MessageChannel; + } + catch (_) { } + return undefined; + })(); +const _setImmediate = typeof setImmediate === 'function' + ? setImmediate.bind(_global) + : function (callback) { + if (typeof callback !== 'function') { + throw new TypeError('The "callback" argument must be of type function'); + } + if (_MessageChannel) { + let channel = new _MessageChannel(); + channel.port1.onmessage = function () { + channel.port1.onmessage = null; + channel = undefined; + callback(); + }; + channel.port2.postMessage(null); + } + else { + setTimeout(callback, 0); + } + }; +const _Buffer = typeof Buffer === 'function' + ? Buffer + : (function () { + try { + return _require('buffer').Buffer; + } + catch (_) { } + return undefined; + })(); +const version = "1.11.3"; +const NODE_API_SUPPORTED_VERSION_MIN = 1; +const NODE_API_SUPPORTED_VERSION_MAX = 10; +const NAPI_VERSION_EXPERIMENTAL = 2147483647; +const NODE_API_DEFAULT_MODULE_API_VERSION = 8; + +class Handle { + constructor(id, value) { + this.id = id; + this.value = value; + } + data() { + return getExternalValue(this.value); + } + isNumber() { + return typeof this.value === 'number'; + } + isBigInt() { + return typeof this.value === 'bigint'; + } + isString() { + return typeof this.value === 'string'; + } + isFunction() { + return typeof this.value === 'function'; + } + isExternal() { + return isExternal(this.value); + } + isObject() { + return typeof this.value === 'object' && this.value !== null; + } + isArray() { + return Array.isArray(this.value); + } + isArrayBuffer() { + return (this.value instanceof ArrayBuffer); + } + isTypedArray() { + return (ArrayBuffer.isView(this.value)) && !(this.value instanceof DataView); + } + isBuffer(BufferConstructor) { + if (ArrayBuffer.isView(this.value)) + return true; + BufferConstructor !== null && BufferConstructor !== void 0 ? BufferConstructor : (BufferConstructor = _Buffer); + return typeof BufferConstructor === 'function' && BufferConstructor.isBuffer(this.value); + } + isDataView() { + return (this.value instanceof DataView); + } + isDate() { + return (this.value instanceof Date); + } + isPromise() { + return (this.value instanceof Promise); + } + isBoolean() { + return typeof this.value === 'boolean'; + } + isUndefined() { + return this.value === undefined; + } + isSymbol() { + return typeof this.value === 'symbol'; + } + isNull() { + return this.value === null; + } + dispose() { + this.value = undefined; + } +} +class ConstHandle extends Handle { + constructor(id, value) { + super(id, value); + } + dispose() { } +} +class HandleStore { + constructor() { + this._values = [ + undefined, + HandleStore.UNDEFINED, + HandleStore.NULL, + HandleStore.FALSE, + HandleStore.TRUE, + HandleStore.GLOBAL + ]; + this._next = HandleStore.MIN_ID; + } + push(value) { + let h; + const next = this._next; + const values = this._values; + if (next < values.length) { + h = values[next]; + h.value = value; + } + else { + h = new Handle(next, value); + values[next] = h; + } + this._next++; + return h; + } + erase(start, end) { + this._next = start; + const values = this._values; + for (let i = start; i < end; ++i) { + values[i].dispose(); + } + } + get(id) { + return this._values[id]; + } + swap(a, b) { + const values = this._values; + const h = values[a]; + values[a] = values[b]; + values[a].id = Number(a); + values[b] = h; + h.id = Number(b); + } + dispose() { + this._values.length = HandleStore.MIN_ID; + this._next = HandleStore.MIN_ID; + } +} +HandleStore.UNDEFINED = new ConstHandle(1, undefined); +HandleStore.NULL = new ConstHandle(2, null); +HandleStore.FALSE = new ConstHandle(3, false); +HandleStore.TRUE = new ConstHandle(4, true); +HandleStore.GLOBAL = new ConstHandle(5, _global); +HandleStore.MIN_ID = 6; + +class HandleScope { + constructor(handleStore, id, parentScope, start, end = start) { + this.handleStore = handleStore; + this.id = id; + this.parent = parentScope; + this.child = null; + if (parentScope !== null) + parentScope.child = this; + this.start = start; + this.end = end; + this._escapeCalled = false; + this.callbackInfo = { + thiz: undefined, + data: 0, + args: undefined, + fn: undefined + }; + } + add(value) { + const h = this.handleStore.push(value); + this.end++; + return h; + } + addExternal(data) { + return this.add(new External(data)); + } + dispose() { + if (this._escapeCalled) + this._escapeCalled = false; + if (this.start === this.end) + return; + this.handleStore.erase(this.start, this.end); + } + escape(handle) { + if (this._escapeCalled) + return null; + this._escapeCalled = true; + if (handle < this.start || handle >= this.end) { + return null; + } + this.handleStore.swap(handle, this.start); + const h = this.handleStore.get(this.start); + this.start++; + this.parent.end++; + return h; + } + escapeCalled() { + return this._escapeCalled; + } +} + +class ScopeStore { + constructor() { + this._rootScope = new HandleScope(null, 0, null, 1, HandleStore.MIN_ID); + this.currentScope = this._rootScope; + this._values = [undefined]; + } + get(id) { + return this._values[id]; + } + openScope(handleStore) { + const currentScope = this.currentScope; + let scope = currentScope.child; + if (scope !== null) { + scope.start = scope.end = currentScope.end; + } + else { + const id = currentScope.id + 1; + scope = new HandleScope(handleStore, id, currentScope, currentScope.end); + this._values[id] = scope; + } + this.currentScope = scope; + return scope; + } + closeScope() { + const scope = this.currentScope; + this.currentScope = scope.parent; + scope.dispose(); + } + dispose() { + this.currentScope = this._rootScope; + this._values.length = 1; + } +} + +class RefTracker { + constructor() { + this._next = null; + this._prev = null; + } + dispose() { } + finalize() { } + link(list) { + this._prev = list; + this._next = list._next; + if (this._next !== null) { + this._next._prev = this; + } + list._next = this; + } + unlink() { + if (this._prev !== null) { + this._prev._next = this._next; + } + if (this._next !== null) { + this._next._prev = this._prev; + } + this._prev = null; + this._next = null; + } + static finalizeAll(list) { + while (list._next !== null) { + list._next.finalize(); + } + } +} + +class Finalizer { + constructor(envObject, _finalizeCallback = 0, _finalizeData = 0, _finalizeHint = 0) { + this.envObject = envObject; + this._finalizeCallback = _finalizeCallback; + this._finalizeData = _finalizeData; + this._finalizeHint = _finalizeHint; + this._makeDynCall_vppp = envObject.makeDynCall_vppp; + } + callback() { return this._finalizeCallback; } + data() { return this._finalizeData; } + hint() { return this._finalizeHint; } + resetEnv() { + this.envObject = undefined; + } + resetFinalizer() { + this._finalizeCallback = 0; + this._finalizeData = 0; + this._finalizeHint = 0; + } + callFinalizer() { + const finalize_callback = this._finalizeCallback; + const finalize_data = this._finalizeData; + const finalize_hint = this._finalizeHint; + this.resetFinalizer(); + if (!finalize_callback) + return; + const fini = Number(finalize_callback); + if (!this.envObject) { + this._makeDynCall_vppp(fini)(0, finalize_data, finalize_hint); + } + else { + this.envObject.callFinalizer(fini, finalize_data, finalize_hint); + } + } + dispose() { + this.envObject = undefined; + this._makeDynCall_vppp = undefined; + } +} + +class TrackedFinalizer extends RefTracker { + static create(envObject, finalize_callback, finalize_data, finalize_hint) { + const finalizer = new TrackedFinalizer(envObject, finalize_callback, finalize_data, finalize_hint); + finalizer.link(envObject.finalizing_reflist); + return finalizer; + } + constructor(envObject, finalize_callback, finalize_data, finalize_hint) { + super(); + this._finalizer = new Finalizer(envObject, finalize_callback, finalize_data, finalize_hint); + } + data() { + return this._finalizer.data(); + } + dispose() { + if (!this._finalizer) + return; + this.unlink(); + this._finalizer.envObject.dequeueFinalizer(this); + this._finalizer.dispose(); + this._finalizer = undefined; + super.dispose(); + } + finalize() { + this.unlink(); + let error; + let caught = false; + try { + this._finalizer.callFinalizer(); + } + catch (err) { + caught = true; + error = err; + } + this.dispose(); + if (caught) { + throw error; + } + } +} + +function throwNodeApiVersionError(moduleName, moduleApiVersion) { + const errorMessage = `${moduleName} requires Node-API version ${moduleApiVersion}, but this version of Node.js only supports version ${NODE_API_SUPPORTED_VERSION_MAX} add-ons.`; + throw new Error(errorMessage); +} +function handleThrow(envObject, value) { + if (envObject.terminatedOrTerminating()) { + return; + } + throw value; +} +class Env { + constructor(ctx, moduleApiVersion, makeDynCall_vppp, makeDynCall_vp, abort) { + this.ctx = ctx; + this.moduleApiVersion = moduleApiVersion; + this.makeDynCall_vppp = makeDynCall_vppp; + this.makeDynCall_vp = makeDynCall_vp; + this.abort = abort; + this.openHandleScopes = 0; + this.instanceData = null; + this.tryCatch = new TryCatch(); + this.refs = 1; + this.reflist = new RefTracker(); + this.finalizing_reflist = new RefTracker(); + this.pendingFinalizers = []; + this.lastError = { + errorCode: 0, + engineErrorCode: 0, + engineReserved: 0 + }; + this.inGcFinalizer = false; + this._bindingMap = new WeakMap(); + this.id = 0; + } + canCallIntoJs() { + return true; + } + terminatedOrTerminating() { + return !this.canCallIntoJs(); + } + ref() { + this.refs++; + } + unref() { + this.refs--; + if (this.refs === 0) { + this.dispose(); + } + } + ensureHandle(value) { + return this.ctx.ensureHandle(value); + } + ensureHandleId(value) { + return this.ensureHandle(value).id; + } + clearLastError() { + const lastError = this.lastError; + if (lastError.errorCode !== 0) + lastError.errorCode = 0; + if (lastError.engineErrorCode !== 0) + lastError.engineErrorCode = 0; + if (lastError.engineReserved !== 0) + lastError.engineReserved = 0; + return 0; + } + setLastError(error_code, engine_error_code = 0, engine_reserved = 0) { + const lastError = this.lastError; + if (lastError.errorCode !== error_code) + lastError.errorCode = error_code; + if (lastError.engineErrorCode !== engine_error_code) + lastError.engineErrorCode = engine_error_code; + if (lastError.engineReserved !== engine_reserved) + lastError.engineReserved = engine_reserved; + return error_code; + } + getReturnStatus() { + return !this.tryCatch.hasCaught() ? 0 : this.setLastError(10); + } + callIntoModule(fn, handleException = handleThrow) { + const openHandleScopesBefore = this.openHandleScopes; + this.clearLastError(); + const r = fn(this); + if (openHandleScopesBefore !== this.openHandleScopes) { + this.abort('open_handle_scopes != open_handle_scopes_before'); + } + if (this.tryCatch.hasCaught()) { + const err = this.tryCatch.extractException(); + handleException(this, err); + } + return r; + } + invokeFinalizerFromGC(finalizer) { + if (this.moduleApiVersion !== NAPI_VERSION_EXPERIMENTAL) { + this.enqueueFinalizer(finalizer); + } + else { + const saved = this.inGcFinalizer; + this.inGcFinalizer = true; + try { + finalizer.finalize(); + } + finally { + this.inGcFinalizer = saved; + } + } + } + checkGCAccess() { + if (this.moduleApiVersion === NAPI_VERSION_EXPERIMENTAL && this.inGcFinalizer) { + this.abort('Finalizer is calling a function that may affect GC state.\n' + + 'The finalizers are run directly from GC and must not affect GC ' + + 'state.\n' + + 'Use `node_api_post_finalizer` from inside of the finalizer to work ' + + 'around this issue.\n' + + 'It schedules the call as a new task in the event loop.'); + } + } + enqueueFinalizer(finalizer) { + if (this.pendingFinalizers.indexOf(finalizer) === -1) { + this.pendingFinalizers.push(finalizer); + } + } + dequeueFinalizer(finalizer) { + const index = this.pendingFinalizers.indexOf(finalizer); + if (index !== -1) { + this.pendingFinalizers.splice(index, 1); + } + } + deleteMe() { + RefTracker.finalizeAll(this.finalizing_reflist); + RefTracker.finalizeAll(this.reflist); + this.tryCatch.extractException(); + this.ctx.envStore.remove(this.id); + } + dispose() { + if (this.id === 0) + return; + this.deleteMe(); + this.finalizing_reflist.dispose(); + this.reflist.dispose(); + this.id = 0; + } + initObjectBinding(value) { + const binding = { + wrapped: 0, + tag: null + }; + this._bindingMap.set(value, binding); + return binding; + } + getObjectBinding(value) { + if (this._bindingMap.has(value)) { + return this._bindingMap.get(value); + } + return this.initObjectBinding(value); + } + setInstanceData(data, finalize_cb, finalize_hint) { + if (this.instanceData) { + this.instanceData.dispose(); + } + this.instanceData = TrackedFinalizer.create(this, finalize_cb, data, finalize_hint); + } + getInstanceData() { + return this.instanceData ? this.instanceData.data() : 0; + } +} +class NodeEnv extends Env { + constructor(ctx, filename, moduleApiVersion, makeDynCall_vppp, makeDynCall_vp, abort, nodeBinding) { + super(ctx, moduleApiVersion, makeDynCall_vppp, makeDynCall_vp, abort); + this.filename = filename; + this.nodeBinding = nodeBinding; + this.destructing = false; + this.finalizationScheduled = false; + } + deleteMe() { + this.destructing = true; + this.drainFinalizerQueue(); + super.deleteMe(); + } + canCallIntoJs() { + return super.canCallIntoJs() && this.ctx.canCallIntoJs(); + } + triggerFatalException(err) { + if (this.nodeBinding) { + this.nodeBinding.napi.fatalException(err); + } + else { + if (typeof process === 'object' && process !== null && typeof process._fatalException === 'function') { + const handled = process._fatalException(err); + if (!handled) { + console.error(err); + process.exit(1); + } + } + else { + throw err; + } + } + } + callbackIntoModule(enforceUncaughtExceptionPolicy, fn) { + return this.callIntoModule(fn, (envObject, err) => { + if (envObject.terminatedOrTerminating()) { + return; + } + const hasProcess = typeof process === 'object' && process !== null; + const hasForceFlag = hasProcess ? Boolean(process.execArgv && (process.execArgv.indexOf('--force-node-api-uncaught-exceptions-policy') !== -1)) : false; + if (envObject.moduleApiVersion < 10 && !hasForceFlag && !enforceUncaughtExceptionPolicy) { + const warn = hasProcess && typeof process.emitWarning === 'function' + ? process.emitWarning + : function (warning, type, code) { + if (warning instanceof Error) { + console.warn(warning.toString()); + } + else { + const prefix = code ? `[${code}] ` : ''; + console.warn(`${prefix}${type || 'Warning'}: ${warning}`); + } + }; + warn('Uncaught Node-API callback exception detected, please run node with option --force-node-api-uncaught-exceptions-policy=true to handle those exceptions properly.', 'DeprecationWarning', 'DEP0168'); + return; + } + envObject.triggerFatalException(err); + }); + } + callFinalizer(cb, data, hint) { + this.callFinalizerInternal(1, cb, data, hint); + } + callFinalizerInternal(forceUncaught, cb, data, hint) { + const f = this.makeDynCall_vppp(cb); + const env = this.id; + const scope = this.ctx.openScope(this); + try { + this.callbackIntoModule(Boolean(forceUncaught), () => { f(env, data, hint); }); + } + finally { + this.ctx.closeScope(this, scope); + } + } + enqueueFinalizer(finalizer) { + super.enqueueFinalizer(finalizer); + if (!this.finalizationScheduled && !this.destructing) { + this.finalizationScheduled = true; + this.ref(); + _setImmediate(() => { + this.finalizationScheduled = false; + this.unref(); + this.drainFinalizerQueue(); + }); + } + } + drainFinalizerQueue() { + while (this.pendingFinalizers.length > 0) { + const refTracker = this.pendingFinalizers.shift(); + refTracker.finalize(); + } + } +} +function newEnv(ctx, filename, moduleApiVersion, makeDynCall_vppp, makeDynCall_vp, abort, nodeBinding) { + moduleApiVersion = typeof moduleApiVersion !== 'number' ? NODE_API_DEFAULT_MODULE_API_VERSION : moduleApiVersion; + if (moduleApiVersion < NODE_API_DEFAULT_MODULE_API_VERSION) { + moduleApiVersion = NODE_API_DEFAULT_MODULE_API_VERSION; + } + else if (moduleApiVersion > NODE_API_SUPPORTED_VERSION_MAX && moduleApiVersion !== NAPI_VERSION_EXPERIMENTAL) { + throwNodeApiVersionError(filename, moduleApiVersion); + } + const env = new NodeEnv(ctx, filename, moduleApiVersion, makeDynCall_vppp, makeDynCall_vp, abort, nodeBinding); + ctx.envStore.add(env); + ctx.addCleanupHook(env, () => { env.unref(); }, 0); + return env; +} + +class EmnapiError extends Error { + constructor(message) { + super(message); + const ErrorConstructor = new.target; + const proto = ErrorConstructor.prototype; + if (!(this instanceof EmnapiError)) { + const setPrototypeOf = Object.setPrototypeOf; + if (typeof setPrototypeOf === 'function') { + setPrototypeOf.call(Object, this, proto); + } + else { + this.__proto__ = proto; + } + if (typeof Error.captureStackTrace === 'function') { + Error.captureStackTrace(this, ErrorConstructor); + } + } + } +} +Object.defineProperty(EmnapiError.prototype, 'name', { + configurable: true, + writable: true, + value: 'EmnapiError' +}); +class NotSupportWeakRefError extends EmnapiError { + constructor(api, message) { + super(`${api}: The current runtime does not support "FinalizationRegistry" and "WeakRef".${message ? ` ${message}` : ''}`); + } +} +Object.defineProperty(NotSupportWeakRefError.prototype, 'name', { + configurable: true, + writable: true, + value: 'NotSupportWeakRefError' +}); +class NotSupportBufferError extends EmnapiError { + constructor(api, message) { + super(`${api}: The current runtime does not support "Buffer". Consider using buffer polyfill to make sure \`globalThis.Buffer\` is defined.${message ? ` ${message}` : ''}`); + } +} +Object.defineProperty(NotSupportBufferError.prototype, 'name', { + configurable: true, + writable: true, + value: 'NotSupportBufferError' +}); + +class StrongRef { + constructor(value) { + this._value = value; + } + deref() { + return this._value; + } + dispose() { + this._value = undefined; + } +} +class Persistent { + constructor(value) { + this._ref = new StrongRef(value); + } + setWeak(param, callback) { + if (!supportFinalizer || this._ref === undefined || this._ref instanceof WeakRef) + return; + const value = this._ref.deref(); + try { + Persistent._registry.register(value, this, this); + const weakRef = new WeakRef(value); + this._ref.dispose(); + this._ref = weakRef; + this._param = param; + this._callback = callback; + } + catch (err) { + if (typeof value === 'symbol') ; + else { + throw err; + } + } + } + clearWeak() { + if (!supportFinalizer || this._ref === undefined) + return; + if (this._ref instanceof WeakRef) { + try { + Persistent._registry.unregister(this); + } + catch (_) { } + this._param = undefined; + this._callback = undefined; + const value = this._ref.deref(); + if (value === undefined) { + this._ref = value; + } + else { + this._ref = new StrongRef(value); + } + } + } + reset() { + if (supportFinalizer) { + try { + Persistent._registry.unregister(this); + } + catch (_) { } + } + this._param = undefined; + this._callback = undefined; + if (this._ref instanceof StrongRef) { + this._ref.dispose(); + } + this._ref = undefined; + } + isEmpty() { + return this._ref === undefined; + } + deref() { + if (this._ref === undefined) + return undefined; + return this._ref.deref(); + } +} +Persistent._registry = supportFinalizer + ? new FinalizationRegistry((value) => { + value._ref = undefined; + const callback = value._callback; + const param = value._param; + value._callback = undefined; + value._param = undefined; + if (typeof callback === 'function') { + callback(param); + } + }) + : undefined; + +var ReferenceOwnership; +(function (ReferenceOwnership) { + ReferenceOwnership[ReferenceOwnership["kRuntime"] = 0] = "kRuntime"; + ReferenceOwnership[ReferenceOwnership["kUserland"] = 1] = "kUserland"; +})(ReferenceOwnership || (ReferenceOwnership = {})); +function canBeHeldWeakly(value) { + return value.isObject() || value.isFunction() || value.isSymbol(); +} +class Reference extends RefTracker { + static weakCallback(ref) { + ref.persistent.reset(); + ref.invokeFinalizerFromGC(); + } + static create(envObject, handle_id, initialRefcount, ownership, _unused1, _unused2, _unused3) { + const ref = new Reference(envObject, handle_id, initialRefcount, ownership); + envObject.ctx.refStore.add(ref); + ref.link(envObject.reflist); + return ref; + } + constructor(envObject, handle_id, initialRefcount, ownership) { + super(); + this.envObject = envObject; + this._refcount = initialRefcount; + this._ownership = ownership; + const handle = envObject.ctx.handleStore.get(handle_id); + this.canBeWeak = canBeHeldWeakly(handle); + this.persistent = new Persistent(handle.value); + this.id = 0; + if (initialRefcount === 0) { + this._setWeak(); + } + } + ref() { + if (this.persistent.isEmpty()) { + return 0; + } + if (++this._refcount === 1 && this.canBeWeak) { + this.persistent.clearWeak(); + } + return this._refcount; + } + unref() { + if (this.persistent.isEmpty() || this._refcount === 0) { + return 0; + } + if (--this._refcount === 0) { + this._setWeak(); + } + return this._refcount; + } + get(envObject = this.envObject) { + if (this.persistent.isEmpty()) { + return 0; + } + const obj = this.persistent.deref(); + const handle = envObject.ensureHandle(obj); + return handle.id; + } + resetFinalizer() { } + data() { return 0; } + refcount() { return this._refcount; } + ownership() { return this._ownership; } + callUserFinalizer() { } + invokeFinalizerFromGC() { + this.finalize(); + } + _setWeak() { + if (this.canBeWeak) { + this.persistent.setWeak(this, Reference.weakCallback); + } + else { + this.persistent.reset(); + } + } + finalize() { + this.persistent.reset(); + const deleteMe = this._ownership === ReferenceOwnership.kRuntime; + this.unlink(); + this.callUserFinalizer(); + if (deleteMe) { + this.dispose(); + } + } + dispose() { + if (this.id === 0) + return; + this.unlink(); + this.persistent.reset(); + this.envObject.ctx.refStore.remove(this.id); + super.dispose(); + this.envObject = undefined; + this.id = 0; + } +} +class ReferenceWithData extends Reference { + static create(envObject, value, initialRefcount, ownership, data) { + const reference = new ReferenceWithData(envObject, value, initialRefcount, ownership, data); + envObject.ctx.refStore.add(reference); + reference.link(envObject.reflist); + return reference; + } + constructor(envObject, value, initialRefcount, ownership, _data) { + super(envObject, value, initialRefcount, ownership); + this._data = _data; + } + data() { + return this._data; + } +} +class ReferenceWithFinalizer extends Reference { + static create(envObject, value, initialRefcount, ownership, finalize_callback, finalize_data, finalize_hint) { + const reference = new ReferenceWithFinalizer(envObject, value, initialRefcount, ownership, finalize_callback, finalize_data, finalize_hint); + envObject.ctx.refStore.add(reference); + reference.link(envObject.finalizing_reflist); + return reference; + } + constructor(envObject, value, initialRefcount, ownership, finalize_callback, finalize_data, finalize_hint) { + super(envObject, value, initialRefcount, ownership); + this._finalizer = new Finalizer(envObject, finalize_callback, finalize_data, finalize_hint); + } + resetFinalizer() { + this._finalizer.resetFinalizer(); + } + data() { + return this._finalizer.data(); + } + callUserFinalizer() { + this._finalizer.callFinalizer(); + } + invokeFinalizerFromGC() { + this._finalizer.envObject.invokeFinalizerFromGC(this); + } + dispose() { + if (!this._finalizer) + return; + this._finalizer.envObject.dequeueFinalizer(this); + this._finalizer.dispose(); + super.dispose(); + this._finalizer = undefined; + } +} + +class Deferred { + static create(ctx, value) { + const deferred = new Deferred(ctx, value); + ctx.deferredStore.add(deferred); + return deferred; + } + constructor(ctx, value) { + Object.defineProperties(this, { + id: { + configurable: true, + enumerable: true, + value: 0, + writable: true + }, + ctx: { + configurable: true, + enumerable: true, + value: ctx, + writable: true + }, + value: { + configurable: true, + enumerable: true, + value, + writable: true + } + }); + } + resolve(value) { + this.value.resolve(value); + this.dispose(); + } + reject(reason) { + this.value.reject(reason); + this.dispose(); + } + dispose() { + this.ctx.deferredStore.remove(this.id); + this.id = 0; + this.value = null; + this.ctx = null; + } +} + +class Store { + constructor() { + this._values = [undefined]; + this._values.length = 4; + this._size = 1; + this._freeList = []; + } + add(value) { + let id; + if (this._freeList.length) { + id = this._freeList.shift(); + } + else { + id = this._size; + this._size++; + const capacity = this._values.length; + if (id >= capacity) { + this._values.length = capacity + (capacity >> 1) + 16; + } + } + value.id = id; + this._values[id] = value; + } + get(id) { + return this._values[id]; + } + has(id) { + return this._values[id] !== undefined; + } + remove(id) { + const value = this._values[id]; + if (value) { + value.id = 0; + this._values[id] = undefined; + this._freeList.push(Number(id)); + } + } + dispose() { + for (let i = 1; i < this._size; ++i) { + const value = this._values[i]; + value === null || value === void 0 ? void 0 : value.dispose(); + } + this._values = [undefined]; + this._size = 1; + this._freeList = []; + } +} + +const kMaxReasonableBytes = BigInt(1) << BigInt(60); +const kMinReasonableBytes = -kMaxReasonableBytes; +class ExternalMemory { + constructor(onChange) { + this.total = BigInt(0); + this.onChange = onChange !== null && onChange !== void 0 ? onChange : null; + } + adjust(changeInBytes) { + changeInBytes = BigInt(changeInBytes); + if (!(kMinReasonableBytes <= changeInBytes && changeInBytes < kMaxReasonableBytes)) { + throw new RangeError(`changeInBytes ${changeInBytes} is out of reasonable range`); + } + const old = this.total; + this.total += changeInBytes; + const amount = this.total; + const onChange = this.onChange; + if (changeInBytes) { + onChange === null || onChange === void 0 ? void 0 : onChange(amount, old, changeInBytes); + } + return amount; + } +} + +class CleanupHookCallback { + constructor(envObject, fn, arg, order) { + this.envObject = envObject; + this.fn = fn; + this.arg = arg; + this.order = order; + } +} +class CleanupQueue { + constructor() { + this._cleanupHooks = []; + this._cleanupHookCounter = 0; + } + empty() { + return this._cleanupHooks.length === 0; + } + add(envObject, fn, arg) { + if (this._cleanupHooks.filter((hook) => (hook.envObject === envObject && hook.fn === fn && hook.arg === arg)).length > 0) { + throw new Error('Can not add same fn and arg twice'); + } + this._cleanupHooks.push(new CleanupHookCallback(envObject, fn, arg, this._cleanupHookCounter++)); + } + remove(envObject, fn, arg) { + for (let i = 0; i < this._cleanupHooks.length; ++i) { + const hook = this._cleanupHooks[i]; + if (hook.envObject === envObject && hook.fn === fn && hook.arg === arg) { + this._cleanupHooks.splice(i, 1); + return; + } + } + } + drain() { + const hooks = this._cleanupHooks.slice(); + hooks.sort((a, b) => (b.order - a.order)); + for (let i = 0; i < hooks.length; ++i) { + const cb = hooks[i]; + if (typeof cb.fn === 'number') { + cb.envObject.makeDynCall_vp(cb.fn)(cb.arg); + } + else { + cb.fn(cb.arg); + } + this._cleanupHooks.splice(this._cleanupHooks.indexOf(cb), 1); + } + } + dispose() { + this._cleanupHooks.length = 0; + this._cleanupHookCounter = 0; + } +} +class NodejsWaitingRequestCounter { + constructor() { + this.refHandle = new _MessageChannel().port1; + this.count = 0; + } + increase() { + if (this.count === 0) { + if (this.refHandle.ref) { + this.refHandle.ref(); + } + } + this.count++; + } + decrease() { + if (this.count === 0) + return; + if (this.count === 1) { + if (this.refHandle.unref) { + this.refHandle.unref(); + } + } + this.count--; + } +} +class Context { + constructor(options) { + this._isStopping = false; + this._canCallIntoJs = true; + this._suppressDestroy = false; + this.envStore = new Store(); + this.scopeStore = new ScopeStore(); + this.refStore = new Store(); + this.deferredStore = new Store(); + this.handleStore = new HandleStore(); + this.feature = { + supportReflect, + supportFinalizer, + supportWeakSymbol, + supportBigInt, + supportNewFunction, + canSetFunctionName, + setImmediate: _setImmediate, + Buffer: _Buffer, + MessageChannel: _MessageChannel + }; + this.cleanupQueue = new CleanupQueue(); + this._externalMemory = new ExternalMemory(options === null || options === void 0 ? void 0 : options.onExternalMemoryChange); + if (typeof process === 'object' && process !== null && typeof process.once === 'function') { + this.refCounter = new NodejsWaitingRequestCounter(); + process.once('beforeExit', () => { + if (!this._suppressDestroy) { + this.destroy(); + } + }); + } + } + suppressDestroy() { + this._suppressDestroy = true; + } + getRuntimeVersions() { + return { + version, + NODE_API_SUPPORTED_VERSION_MAX, + NAPI_VERSION_EXPERIMENTAL, + NODE_API_DEFAULT_MODULE_API_VERSION + }; + } + createNotSupportWeakRefError(api, message) { + return new NotSupportWeakRefError(api, message); + } + createNotSupportBufferError(api, message) { + return new NotSupportBufferError(api, message); + } + createReference(envObject, handle_id, initialRefcount, ownership) { + return Reference.create(envObject, handle_id, initialRefcount, ownership); + } + createReferenceWithData(envObject, handle_id, initialRefcount, ownership, data) { + return ReferenceWithData.create(envObject, handle_id, initialRefcount, ownership, data); + } + createReferenceWithFinalizer(envObject, handle_id, initialRefcount, ownership, finalize_callback = 0, finalize_data = 0, finalize_hint = 0) { + return ReferenceWithFinalizer.create(envObject, handle_id, initialRefcount, ownership, finalize_callback, finalize_data, finalize_hint); + } + createDeferred(value) { + return Deferred.create(this, value); + } + adjustAmountOfExternalAllocatedMemory(changeInBytes) { + return this._externalMemory.adjust(changeInBytes); + } + createEnv(filename, moduleApiVersion, makeDynCall_vppp, makeDynCall_vp, abort, nodeBinding) { + return newEnv(this, filename, moduleApiVersion, makeDynCall_vppp, makeDynCall_vp, abort, nodeBinding); + } + createTrackedFinalizer(envObject, finalize_callback, finalize_data, finalize_hint) { + return TrackedFinalizer.create(envObject, finalize_callback, finalize_data, finalize_hint); + } + getCurrentScope() { + return this.scopeStore.currentScope; + } + addToCurrentScope(value) { + return this.scopeStore.currentScope.add(value); + } + openScope(envObject) { + const scope = this.scopeStore.openScope(this.handleStore); + if (envObject) + envObject.openHandleScopes++; + return scope; + } + closeScope(envObject, _scope) { + if (envObject && envObject.openHandleScopes === 0) + return; + this.scopeStore.closeScope(); + if (envObject) + envObject.openHandleScopes--; + } + ensureHandle(value) { + switch (value) { + case undefined: return HandleStore.UNDEFINED; + case null: return HandleStore.NULL; + case true: return HandleStore.TRUE; + case false: return HandleStore.FALSE; + case _global: return HandleStore.GLOBAL; + } + return this.addToCurrentScope(value); + } + addCleanupHook(envObject, fn, arg) { + this.cleanupQueue.add(envObject, fn, arg); + } + removeCleanupHook(envObject, fn, arg) { + this.cleanupQueue.remove(envObject, fn, arg); + } + runCleanup() { + while (!this.cleanupQueue.empty()) { + this.cleanupQueue.drain(); + } + } + increaseWaitingRequestCounter() { + var _a; + (_a = this.refCounter) === null || _a === void 0 ? void 0 : _a.increase(); + } + decreaseWaitingRequestCounter() { + var _a; + (_a = this.refCounter) === null || _a === void 0 ? void 0 : _a.decrease(); + } + setCanCallIntoJs(value) { + this._canCallIntoJs = value; + } + setStopping(value) { + this._isStopping = value; + } + canCallIntoJs() { + return this._canCallIntoJs && !this._isStopping; + } + destroy() { + this.setStopping(true); + this.setCanCallIntoJs(false); + this.runCleanup(); + } +} +let defaultContext; +function createContext(options) { + return new Context(options); +} +function getDefaultContext() { + if (!defaultContext) { + defaultContext = createContext(); + } + return defaultContext; +} + +export { ConstHandle, Context, Deferred, EmnapiError, Env, External, Finalizer, Handle, HandleScope, HandleStore, NAPI_VERSION_EXPERIMENTAL, NODE_API_DEFAULT_MODULE_API_VERSION, NODE_API_SUPPORTED_VERSION_MAX, NODE_API_SUPPORTED_VERSION_MIN, NodeEnv, NotSupportBufferError, NotSupportWeakRefError, Persistent, RefTracker, Reference, ReferenceOwnership, ReferenceWithData, ReferenceWithFinalizer, ScopeStore, Store, TrackedFinalizer, TryCatch, createContext, getDefaultContext, getExternalValue, isExternal, isReferenceType, version }; diff --git a/dg-ui/node_modules/@tailwindcss/oxide-wasm32-wasi/node_modules/@emnapi/runtime/index.js b/dg-ui/node_modules/@tailwindcss/oxide-wasm32-wasi/node_modules/@emnapi/runtime/index.js new file mode 100644 index 0000000..efd0f2f --- /dev/null +++ b/dg-ui/node_modules/@tailwindcss/oxide-wasm32-wasi/node_modules/@emnapi/runtime/index.js @@ -0,0 +1,5 @@ +if (typeof process !== 'undefined' && process.env.NODE_ENV === 'production') { + module.exports = require('./dist/emnapi.cjs.min.js') +} else { + module.exports = require('./dist/emnapi.cjs.js') +} diff --git a/dg-ui/node_modules/@tailwindcss/oxide-wasm32-wasi/node_modules/@emnapi/runtime/package.json b/dg-ui/node_modules/@tailwindcss/oxide-wasm32-wasi/node_modules/@emnapi/runtime/package.json new file mode 100644 index 0000000..f0cbd77 --- /dev/null +++ b/dg-ui/node_modules/@tailwindcss/oxide-wasm32-wasi/node_modules/@emnapi/runtime/package.json @@ -0,0 +1,48 @@ +{ + "name": "@emnapi/runtime", + "version": "1.11.3", + "description": "emnapi runtime", + "main": "index.js", + "module": "./dist/emnapi.esm-bundler.js", + "types": "./dist/emnapi.d.ts", + "sideEffects": false, + "exports": { + ".": { + "types": { + "module": "./dist/emnapi.d.ts", + "import": "./dist/emnapi.d.mts", + "default": "./dist/emnapi.d.ts" + }, + "module": "./dist/emnapi.esm-bundler.js", + "import": "./dist/emnapi.mjs", + "default": "./index.js" + }, + "./dist/emnapi.cjs.min": { + "types": "./dist/emnapi.d.ts", + "default": "./dist/emnapi.cjs.min.js" + }, + "./dist/emnapi.min.mjs": { + "types": "./dist/emnapi.d.mts", + "default": "./dist/emnapi.min.mjs" + } + }, + "dependencies": { + "tslib": "^2.4.0" + }, + "scripts": { + "build": "node ./script/build.js" + }, + "repository": { + "type": "git", + "url": "git+https://github.com/toyobayashi/emnapi.git" + }, + "author": "toyobayashi", + "license": "MIT", + "bugs": { + "url": "https://github.com/toyobayashi/emnapi/issues" + }, + "homepage": "https://github.com/toyobayashi/emnapi#readme", + "publishConfig": { + "access": "public" + } +} diff --git a/dg-ui/node_modules/@tailwindcss/oxide-wasm32-wasi/node_modules/@emnapi/wasi-threads/LICENSE b/dg-ui/node_modules/@tailwindcss/oxide-wasm32-wasi/node_modules/@emnapi/wasi-threads/LICENSE new file mode 100644 index 0000000..05a5944 --- /dev/null +++ b/dg-ui/node_modules/@tailwindcss/oxide-wasm32-wasi/node_modules/@emnapi/wasi-threads/LICENSE @@ -0,0 +1,21 @@ +MIT License + +Copyright (c) 2021-present Toyobayashi + +Permission is hereby granted, free of charge, to any person obtaining a copy +of this software and associated documentation files (the "Software"), to deal +in the Software without restriction, including without limitation the rights +to use, copy, modify, merge, publish, distribute, sublicense, and/or sell +copies of the Software, and to permit persons to whom the Software is +furnished to do so, subject to the following conditions: + +The above copyright notice and this permission notice shall be included in all +copies or substantial portions of the Software. + +THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR +IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, +FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE +AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER +LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, +OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE +SOFTWARE. diff --git a/dg-ui/node_modules/@tailwindcss/oxide-wasm32-wasi/node_modules/@emnapi/wasi-threads/README.md b/dg-ui/node_modules/@tailwindcss/oxide-wasm32-wasi/node_modules/@emnapi/wasi-threads/README.md new file mode 100644 index 0000000..d7ab935 --- /dev/null +++ b/dg-ui/node_modules/@tailwindcss/oxide-wasm32-wasi/node_modules/@emnapi/wasi-threads/README.md @@ -0,0 +1,203 @@ +# @emnapi/wasi-threads + +This package makes [wasi-threads proposal](https://github.com/WebAssembly/wasi-threads) based WASI modules work in Node.js and browser. + +## Quick Start + +`index.html` + +```html + + + +``` + +If your application will block browser main thread (for example `pthread_join`), please run it in worker instead. + +```html + +``` + +`index.js` + +```js +const ENVIRONMENT_IS_NODE = + typeof process === 'object' && process !== null && + typeof process.versions === 'object' && process.versions !== null && + typeof process.versions.node === 'string'; + +(function (main) { + if (ENVIRONMENT_IS_NODE) { + main(require) + } else { + if (typeof importScripts === 'function') { + importScripts('./node_modules/@tybys/wasm-util/dist/wasm-util.js') + importScripts('./node_modules/@emnapi/wasi-threads/dist/wasi-threads.js') + } + const nodeWasi = { WASI: globalThis.wasmUtil.WASI } + const nodeWorkerThreads = { + Worker: globalThis.Worker + } + const _require = function (request) { + if (request === 'node:wasi' || request === 'wasi') return nodeWasi + if (request === 'node:worker_threads' || request === 'worker_threads') return nodeWorkerThreads + if (request === '@emnapi/wasi-threads') return globalThis.wasiThreads + throw new Error('Can not find module: ' + request) + } + main(_require) + } +})(async function (require) { + const { WASI } = require('wasi') + const { Worker } = require('worker_threads') + const { WASIThreads } = require('@emnapi/wasi-threads') + + const wasi = new WASI({ + version: 'preview1' + }) + const wasiThreads = new WASIThreads({ + wasi, + + /** + * avoid Atomics.wait() deadlock during thread creation in browser + * see https://emscripten.org/docs/tools_reference/settings_reference.html#pthread-pool-size + */ + reuseWorker: ENVIRONMENT_IS_NODE + ? false + : { + size: 4 /** greater than actual needs (2) */, + strict: true + }, + + /** + * Synchronous thread creation + * pthread_create will not return until thread worker actually starts + */ + waitThreadStart: typeof window === 'undefined' ? 1000 : false, + + onCreateWorker: () => { + return new Worker('./worker.js', { + execArgv: ['--experimental-wasi-unstable-preview1'] + }) + } + }) + const memory = new WebAssembly.Memory({ + initial: 16777216 / 65536, + maximum: 2147483648 / 65536, + shared: true + }) + let input + const file = 'path/to/your/wasi-module.wasm' + try { + input = require('fs').readFileSync(require('path').join(__dirname, file)) + } catch (err) { + const response = await fetch(file) + input = await response.arrayBuffer() + } + let { module, instance } = await WebAssembly.instantiate(input, { + env: { memory }, + wasi_snapshot_preview1: wasi.wasiImport, + ...wasiThreads.getImportObject() + }) + + wasiThreads.setup(instance, module, memory) + await wasiThreads.preloadWorkers() + + if (typeof instance.exports._start === 'function') { + return wasi.start(instance) + } else { + wasi.initialize(instance) + // instance.exports.exported_wasm_function() + } +}) +``` + +`worker.js` + +```js +(function (main) { + const ENVIRONMENT_IS_NODE = + typeof process === 'object' && process !== null && + typeof process.versions === 'object' && process.versions !== null && + typeof process.versions.node === 'string' + + if (ENVIRONMENT_IS_NODE) { + const _require = function (request) { + return require(request) + } + + const _init = function () { + const nodeWorkerThreads = require('worker_threads') + const parentPort = nodeWorkerThreads.parentPort + + parentPort.on('message', (data) => { + globalThis.onmessage({ data }) + }) + + Object.assign(globalThis, { + self: globalThis, + require, + Worker: nodeWorkerThreads.Worker, + importScripts: function (f) { + (0, eval)(require('fs').readFileSync(f, 'utf8') + '//# sourceURL=' + f) + }, + postMessage: function (msg) { + parentPort.postMessage(msg) + } + }) + } + + main(_require, _init) + } else { + importScripts('./node_modules/@tybys/wasm-util/dist/wasm-util.js') + importScripts('./node_modules/@emnapi/wasi-threads/dist/wasi-threads.js') + + const nodeWasi = { WASI: globalThis.wasmUtil.WASI } + const _require = function (request) { + if (request === '@emnapi/wasi-threads') return globalThis.wasiThreads + if (request === 'node:wasi' || request === 'wasi') return nodeWasi + throw new Error('Can not find module: ' + request) + } + const _init = function () {} + main(_require, _init) + } +})(function main (require, init) { + init() + + const { WASI } = require('wasi') + const { ThreadMessageHandler, WASIThreads } = require('@emnapi/wasi-threads') + + const handler = new ThreadMessageHandler({ + async onLoad ({ wasmModule, wasmMemory }) { + const wasi = new WASI({ + version: 'preview1' + }) + + const wasiThreads = new WASIThreads({ + wasi, + childThread: true + }) + + const originalInstance = await WebAssembly.instantiate(wasmModule, { + env: { + memory: wasmMemory, + }, + wasi_snapshot_preview1: wasi.wasiImport, + ...wasiThreads.getImportObject() + }) + + // must call `initialize` instead of `start` in child thread + const instance = wasiThreads.initialize(originalInstance, wasmModule, wasmMemory) + + return { module: wasmModule, instance } + } + }) + + globalThis.onmessage = function (e) { + handler.handle(e) + // handle other messages + } +}) +``` diff --git a/dg-ui/node_modules/@tailwindcss/oxide-wasm32-wasi/node_modules/@emnapi/wasi-threads/dist/wasi-threads.cjs.js b/dg-ui/node_modules/@tailwindcss/oxide-wasm32-wasi/node_modules/@emnapi/wasi-threads/dist/wasi-threads.cjs.js new file mode 100644 index 0000000..fe1ed09 --- /dev/null +++ b/dg-ui/node_modules/@tailwindcss/oxide-wasm32-wasi/node_modules/@emnapi/wasi-threads/dist/wasi-threads.cjs.js @@ -0,0 +1,915 @@ +const _WebAssembly = typeof WebAssembly !== 'undefined' + ? WebAssembly + : typeof WXWebAssembly !== 'undefined' + ? WXWebAssembly + : undefined; +const ENVIRONMENT_IS_NODE = typeof process === 'object' && process !== null && + typeof process.versions === 'object' && process.versions !== null && + typeof process.versions.node === 'string'; +function getPostMessage(options) { + return typeof (options === null || options === void 0 ? void 0 : options.postMessage) === 'function' + ? options.postMessage + : typeof postMessage === 'function' + ? postMessage + : undefined; +} +function serizeErrorToBuffer(sab, code, error) { + const i32array = new Int32Array(sab); + Atomics.store(i32array, 0, code); + if (code > 1 && error) { + const name = error.name; + const message = error.message; + const stack = error.stack; + const nameBuffer = new TextEncoder().encode(name); + const messageBuffer = new TextEncoder().encode(message); + const stackBuffer = new TextEncoder().encode(stack); + Atomics.store(i32array, 1, nameBuffer.length); + Atomics.store(i32array, 2, messageBuffer.length); + Atomics.store(i32array, 3, stackBuffer.length); + const buffer = new Uint8Array(sab); + buffer.set(nameBuffer, 16); + buffer.set(messageBuffer, 16 + nameBuffer.length); + buffer.set(stackBuffer, 16 + nameBuffer.length + messageBuffer.length); + } +} +function deserizeErrorFromBuffer(sab) { + var _a, _b; + const i32array = new Int32Array(sab); + const status = Atomics.load(i32array, 0); + if (status <= 1) { + return null; + } + const nameLength = Atomics.load(i32array, 1); + const messageLength = Atomics.load(i32array, 2); + const stackLength = Atomics.load(i32array, 3); + const buffer = new Uint8Array(sab); + const nameBuffer = buffer.slice(16, 16 + nameLength); + const messageBuffer = buffer.slice(16 + nameLength, 16 + nameLength + messageLength); + const stackBuffer = buffer.slice(16 + nameLength + messageLength, 16 + nameLength + messageLength + stackLength); + const name = new TextDecoder().decode(nameBuffer); + const message = new TextDecoder().decode(messageBuffer); + const stack = new TextDecoder().decode(stackBuffer); + const ErrorConstructor = (_a = globalThis[name]) !== null && _a !== void 0 ? _a : (name === 'RuntimeError' ? ((_b = _WebAssembly.RuntimeError) !== null && _b !== void 0 ? _b : Error) : Error); + const error = new ErrorConstructor(message); + Object.defineProperty(error, 'stack', { + value: stack, + writable: true, + enumerable: false, + configurable: true + }); + return error; +} +function isSharedArrayBuffer(value) { + return ((typeof SharedArrayBuffer === 'function' && value instanceof SharedArrayBuffer) || + (Object.prototype.toString.call(value) === '[object SharedArrayBuffer]')); +} +function isTrapError(e) { + try { + return e instanceof _WebAssembly.RuntimeError; + } + catch (_) { + return false; + } +} + +function createMessage(type, payload) { + return { + __emnapi__: { + type, + payload + } + }; +} + +const WASI_THREADS_MAX_TID = 0x1FFFFFFF; +function checkSharedWasmMemory(wasmMemory) { + if (wasmMemory) { + if (!isSharedArrayBuffer(wasmMemory.buffer)) { + throw new Error('Multithread features require shared wasm memory. ' + + 'Try to compile with `-matomics -mbulk-memory` and use `--import-memory --shared-memory` during linking, ' + + 'then create WebAssembly.Memory with `shared: true` option'); + } + } + else { + if (typeof SharedArrayBuffer === 'undefined') { + throw new Error('Current environment does not support SharedArrayBuffer, threads are not available!'); + } + } +} +function getReuseWorker(value) { + var _a; + if (typeof value === 'boolean') { + return value ? { size: 0, strict: false } : false; + } + if (typeof value === 'number') { + if (!(value >= 0)) { + throw new RangeError('reuseWorker: size must be a non-negative integer'); + } + return { size: value, strict: false }; + } + if (!value) { + return false; + } + const size = (_a = Number(value.size)) !== null && _a !== void 0 ? _a : 0; + const strict = Boolean(value.strict); + if (!(size > 0) && strict) { + throw new RangeError('reuseWorker: size must be set to positive integer if strict is set to true'); + } + return { size, strict }; +} +let nextWorkerID = 0; +class ThreadManager { + get nextWorkerID() { return nextWorkerID; } + constructor(options) { + var _a; + this.unusedWorkers = []; + this.pthreads = Object.create(null); + this.wasmModule = null; + this.wasmMemory = null; + this.messageEvents = new WeakMap(); + if (!options) { + throw new TypeError('ThreadManager(): options is not provided'); + } + if ('childThread' in options) { + this._childThread = Boolean(options.childThread); + } + else { + this._childThread = false; + } + if (this._childThread) { + this._onCreateWorker = undefined; + this._reuseWorker = false; + this._beforeLoad = undefined; + } + else { + this._onCreateWorker = options.onCreateWorker; + this._reuseWorker = getReuseWorker(options.reuseWorker); + this._beforeLoad = options.beforeLoad; + } + this.printErr = (_a = options.printErr) !== null && _a !== void 0 ? _a : console.error.bind(console); + this.threadSpawn = options.threadSpawn; + } + init() { + if (!this._childThread) { + this.initMainThread(); + } + } + initMainThread() { + this.preparePool(); + } + preparePool() { + if (this._reuseWorker) { + if (this._reuseWorker.size) { + let pthreadPoolSize = this._reuseWorker.size; + while (pthreadPoolSize--) { + const worker = this.allocateUnusedWorker(); + if (ENVIRONMENT_IS_NODE) { + worker.once('message', () => { }); + worker.unref(); + } + } + } + } + } + shouldPreloadWorkers() { + return !this._childThread && this._reuseWorker && this._reuseWorker.size > 0; + } + loadWasmModuleToAllWorkers() { + const promises = Array(this.unusedWorkers.length); + for (let i = 0; i < this.unusedWorkers.length; ++i) { + const worker = this.unusedWorkers[i]; + if (ENVIRONMENT_IS_NODE) + worker.ref(); + promises[i] = this.loadWasmModuleToWorker(worker).then((w) => { + if (ENVIRONMENT_IS_NODE) + worker.unref(); + return w; + }, (e) => { + if (ENVIRONMENT_IS_NODE) + worker.unref(); + throw e; + }); + } + return Promise.all(promises).catch((err) => { + this.terminateAllThreads(); + throw err; + }); + } + preloadWorkers() { + if (this.shouldPreloadWorkers()) { + return this.loadWasmModuleToAllWorkers(); + } + return Promise.resolve([]); + } + setup(wasmModule, wasmMemory) { + this.wasmModule = wasmModule; + this.wasmMemory = wasmMemory; + } + markId(worker) { + if (worker.__emnapi_tid) + return worker.__emnapi_tid; + const tid = nextWorkerID + 43; + nextWorkerID = (nextWorkerID + 1) % (WASI_THREADS_MAX_TID - 42); + this.pthreads[tid] = worker; + worker.__emnapi_tid = tid; + return tid; + } + returnWorkerToPool(worker) { + var tid = worker.__emnapi_tid; + if (tid !== undefined) { + delete this.pthreads[tid]; + } + this.unusedWorkers.push(worker); + delete worker.__emnapi_tid; + if (ENVIRONMENT_IS_NODE) { + worker.unref(); + } + } + loadWasmModuleToWorker(worker, sab) { + if (worker.whenLoaded) + return worker.whenLoaded; + const err = this.printErr; + const beforeLoad = this._beforeLoad; + const _this = this; + worker.whenLoaded = new Promise((resolve, reject) => { + const handleError = function (e) { + let message = 'worker sent an error!'; + if (worker.__emnapi_tid !== undefined) { + message = 'worker (tid = ' + worker.__emnapi_tid + ') sent an error!'; + } + if ('message' in e) { + err(message + ' ' + e.message); + if (e.message.indexOf('RuntimeError') !== -1 || e.message.indexOf('unreachable') !== -1) { + try { + _this.terminateAllThreads(); + } + catch (_) { } + } + } + else { + err(message); + } + reject(e); + throw e; + }; + const handleMessage = (data) => { + if (data.__emnapi__) { + const type = data.__emnapi__.type; + const payload = data.__emnapi__.payload; + if (type === 'loaded') { + worker.loaded = true; + if (ENVIRONMENT_IS_NODE && !worker.__emnapi_tid) { + worker.unref(); + } + resolve(worker); + } + else if (type === 'cleanup-thread') { + if (payload.tid in this.pthreads) { + this.cleanThread(worker, payload.tid); + } + } + else if (type === 'spawn-thread') { + this.threadSpawn(payload.startArg, payload.errorOrTid); + } + else if (type === 'terminate-all-threads') { + this.terminateAllThreads(); + } + } + }; + worker.onmessage = (e) => { + handleMessage(e.data); + this.fireMessageEvent(worker, e); + }; + worker.onerror = handleError; + if (ENVIRONMENT_IS_NODE) { + worker.on('message', function (data) { + var _a, _b; + (_b = (_a = worker).onmessage) === null || _b === void 0 ? void 0 : _b.call(_a, { + data + }); + }); + worker.on('error', function (e) { + var _a, _b; + (_b = (_a = worker).onerror) === null || _b === void 0 ? void 0 : _b.call(_a, e); + }); + worker.on('detachedExit', function () { }); + } + if (typeof beforeLoad === 'function') { + beforeLoad(worker); + } + try { + worker.postMessage(createMessage('load', { + wasmModule: this.wasmModule, + wasmMemory: this.wasmMemory, + sab + })); + } + catch (err) { + checkSharedWasmMemory(this.wasmMemory); + throw err; + } + }); + return worker.whenLoaded; + } + allocateUnusedWorker() { + const _onCreateWorker = this._onCreateWorker; + if (typeof _onCreateWorker !== 'function') { + throw new TypeError('`options.onCreateWorker` is not provided'); + } + const worker = _onCreateWorker({ type: 'thread', name: 'emnapi-pthread' }); + this.unusedWorkers.push(worker); + return worker; + } + getNewWorker(sab) { + if (this._reuseWorker) { + if (this.unusedWorkers.length === 0) { + if (this._reuseWorker.strict) { + if (!ENVIRONMENT_IS_NODE) { + const err = this.printErr; + err('Tried to spawn a new thread, but the thread pool is exhausted.\n' + + 'This might result in a deadlock unless some threads eventually exit or the code explicitly breaks out to the event loop.'); + return; + } + } + const worker = this.allocateUnusedWorker(); + this.loadWasmModuleToWorker(worker, sab); + } + return this.unusedWorkers.pop(); + } + const worker = this.allocateUnusedWorker(); + this.loadWasmModuleToWorker(worker, sab); + return this.unusedWorkers.pop(); + } + cleanThread(worker, tid, force) { + if (!force && this._reuseWorker) { + this.returnWorkerToPool(worker); + } + else { + delete this.pthreads[tid]; + this.terminateWorker(worker); + delete worker.__emnapi_tid; + } + } + terminateWorker(worker) { + var _a; + const tid = worker.__emnapi_tid; + worker.terminate(); + (_a = this.messageEvents.get(worker)) === null || _a === void 0 ? void 0 : _a.clear(); + this.messageEvents.delete(worker); + worker.onmessage = (e) => { + if (e.data.__emnapi__) { + const err = this.printErr; + err('received "' + e.data.__emnapi__.type + '" command from terminated worker: ' + tid); + } + }; + } + terminateAllThreads() { + const runningWorkers = Object.values(this.pthreads); + for (let i = 0; i < runningWorkers.length; ++i) { + this.terminateWorker(runningWorkers[i]); + } + for (let i = 0; i < this.unusedWorkers.length; ++i) { + this.terminateWorker(this.unusedWorkers[i]); + } + this.unusedWorkers = []; + this.pthreads = Object.create(null); + this.preparePool(); + } + addMessageEventListener(worker, onMessage) { + let listeners = this.messageEvents.get(worker); + if (!listeners) { + listeners = new Set(); + this.messageEvents.set(worker, listeners); + } + listeners.add(onMessage); + return () => { + listeners === null || listeners === void 0 ? void 0 : listeners.delete(onMessage); + }; + } + fireMessageEvent(worker, e) { + const listeners = this.messageEvents.get(worker); + if (!listeners) + return; + const err = this.printErr; + listeners.forEach((listener) => { + try { + listener(e); + } + catch (e) { + err(e.stack); + } + }); + } +} + +const kIsProxy = Symbol('kIsProxy'); +function createInstanceProxy(instance, memory) { + if (instance[kIsProxy]) + return instance; + const originalExports = instance.exports; + const createHandler = function (target) { + const handlers = [ + 'apply', + 'construct', + 'defineProperty', + 'deleteProperty', + 'get', + 'getOwnPropertyDescriptor', + 'getPrototypeOf', + 'has', + 'isExtensible', + 'ownKeys', + 'preventExtensions', + 'set', + 'setPrototypeOf' + ]; + const handler = {}; + for (let i = 0; i < handlers.length; i++) { + const name = handlers[i]; + handler[name] = function () { + const args = Array.prototype.slice.call(arguments, 1); + args.unshift(target); + return Reflect[name].apply(Reflect, args); + }; + } + return handler; + }; + const handler = createHandler(originalExports); + const _initialize = () => { }; + const _start = () => 0; + handler.get = function (_target, p, receiver) { + var _a; + if (p === 'memory') { + return (_a = (typeof memory === 'function' ? memory() : memory)) !== null && _a !== void 0 ? _a : Reflect.get(originalExports, p, receiver); + } + if (p === '_initialize') { + return p in originalExports ? _initialize : undefined; + } + if (p === '_start') { + return p in originalExports ? _start : undefined; + } + return Reflect.get(originalExports, p, receiver); + }; + handler.has = function (_target, p) { + if (p === 'memory') + return true; + return Reflect.has(originalExports, p); + }; + const exportsProxy = new Proxy(Object.create(null), handler); + return new Proxy(instance, { + get(target, p, receiver) { + if (p === 'exports') { + return exportsProxy; + } + if (p === kIsProxy) { + return true; + } + return Reflect.get(target, p, receiver); + } + }); +} + +const patchedWasiInstances = new WeakMap(); +const THREAD_SPAWN_RESULT_SIZE = Int32Array.BYTES_PER_ELEMENT * 2; +const sharedArrayBufferByteLength = typeof SharedArrayBuffer === 'function' + ? Object.getOwnPropertyDescriptor(SharedArrayBuffer.prototype, 'byteLength').get + : undefined; +function isConclusivelySharedArrayBuffer(buffer) { + if (sharedArrayBufferByteLength === undefined) + return false; + try { + sharedArrayBufferByteLength.call(buffer); + return true; + } + catch (_) { + return false; + } +} +function getThreadSpawnResultView(memory, address, wasm64) { + const offset = typeof address === 'bigint' ? Number(address) : address >>> 0; + let buffer = memory.buffer; + if (offset + THREAD_SPAWN_RESULT_SIZE > buffer.byteLength && + isConclusivelySharedArrayBuffer(buffer)) { + if (wasm64) { + memory.grow(BigInt(0)); + } + else { + memory.grow(0); + } + buffer = memory.buffer; + } + return new Int32Array(buffer, offset, 2); +} +class WASIThreads { + constructor(options) { + if (!options) { + throw new TypeError('WASIThreads(): options is not provided'); + } + if (!options.wasi) { + throw new TypeError('WASIThreads(): options.wasi is not provided'); + } + patchedWasiInstances.set(this, new WeakSet()); + const wasi = options.wasi; + patchWasiInstance(this, wasi); + this.wasi = wasi; + if ('childThread' in options) { + this.childThread = Boolean(options.childThread); + } + else { + this.childThread = false; + } + this.PThread = undefined; + if ('threadManager' in options) { + if (typeof options.threadManager === 'function') { + this.PThread = options.threadManager(); + } + else { + this.PThread = options.threadManager; + } + } + else { + if (!this.childThread) { + this.PThread = new ThreadManager(options); + this.PThread.init(); + } + } + let waitThreadStart = false; + if ('waitThreadStart' in options) { + waitThreadStart = typeof options.waitThreadStart === 'number' ? options.waitThreadStart : Boolean(options.waitThreadStart); + } + const postMessage = getPostMessage(options); + if (this.childThread && typeof postMessage !== 'function') { + throw new TypeError('options.postMessage is not a function'); + } + this.postMessage = postMessage; + const wasm64 = Boolean(options.wasm64); + const threadSpawn = (startArg, errorOrTid) => { + var _a; + const EAGAIN = 6; + const isNewABI = errorOrTid !== undefined; + try { + checkSharedWasmMemory(this.wasmMemory); + } + catch (err) { + (_a = this.PThread) === null || _a === void 0 ? void 0 : _a.printErr(err.stack); + if (isNewABI) { + const struct = getThreadSpawnResultView(this.wasmMemory, errorOrTid, wasm64); + Atomics.store(struct, 0, 1); + Atomics.store(struct, 1, EAGAIN); + Atomics.notify(struct, 1); + return 1; + } + else { + return -EAGAIN; + } + } + if (!isNewABI) { + const malloc = this.wasmInstance.exports.malloc; + errorOrTid = wasm64 ? Number(malloc(BigInt(8))) : (malloc(8) >>> 0); + if (!errorOrTid) { + return -48; + } + } + const _free = this.wasmInstance.exports.free; + const free = wasm64 ? (ptr) => { _free(BigInt(ptr)); } : _free; + const struct = getThreadSpawnResultView(this.wasmMemory, errorOrTid, wasm64); + Atomics.store(struct, 0, 0); + Atomics.store(struct, 1, 0); + if (this.childThread) { + postMessage(createMessage('spawn-thread', { + startArg, + errorOrTid: errorOrTid + })); + Atomics.wait(struct, 1, 0); + const isError = Atomics.load(struct, 0); + const result = Atomics.load(struct, 1); + if (isNewABI) { + return isError; + } + free(errorOrTid); + return isError ? -result : result; + } + const shouldWait = waitThreadStart || (waitThreadStart === 0); + let sab; + if (shouldWait) { + sab = new Int32Array(new SharedArrayBuffer(16 + 8192)); + Atomics.store(sab, 0, 0); + } + let worker; + let tid; + const PThread = this.PThread; + try { + worker = PThread.getNewWorker(sab); + if (!worker) { + throw new Error('failed to get new worker'); + } + tid = PThread.markId(worker); + if (ENVIRONMENT_IS_NODE) { + worker.unref(); + } + worker.postMessage(createMessage('start', { + tid, + arg: startArg, + sab + })); + if (shouldWait) { + if (typeof waitThreadStart === 'number') { + const waitResult = Atomics.wait(sab, 0, 0, waitThreadStart); + if (waitResult === 'timed-out') { + throw new Error('Spawning thread timed out. Please check if the worker is created successfully and if message is handled properly in the worker.'); + } + } + else { + Atomics.wait(sab, 0, 0); + } + const r = Atomics.load(sab, 0); + if (r > 1) { + throw deserizeErrorFromBuffer(sab.buffer); + } + } + } + catch (e) { + if (worker !== undefined && tid !== undefined) { + try { + PThread.cleanThread(worker, tid, true); + } + catch (_) { } + } + Atomics.store(struct, 0, 1); + Atomics.store(struct, 1, EAGAIN); + Atomics.notify(struct, 1); + PThread === null || PThread === void 0 ? void 0 : PThread.printErr(e.stack); + if (isNewABI) { + return 1; + } + free(errorOrTid); + return -EAGAIN; + } + Atomics.store(struct, 0, 0); + Atomics.store(struct, 1, tid); + Atomics.notify(struct, 1); + if (!shouldWait) { + worker.whenLoaded.catch((err) => { + delete worker.whenLoaded; + PThread.cleanThread(worker, tid, true); + throw err; + }); + } + if (isNewABI) { + return 0; + } + free(errorOrTid); + return tid; + }; + this.threadSpawn = threadSpawn; + if (this.PThread) { + this.PThread.threadSpawn = threadSpawn; + } + } + getImportObject() { + return { + wasi: { + 'thread-spawn': this.threadSpawn + } + }; + } + setup(wasmInstance, wasmModule, wasmMemory) { + wasmMemory !== null && wasmMemory !== void 0 ? wasmMemory : (wasmMemory = wasmInstance.exports.memory); + this.wasmInstance = wasmInstance; + this.wasmMemory = wasmMemory; + if (this.PThread) { + this.PThread.setup(wasmModule, wasmMemory); + } + } + preloadWorkers() { + if (this.PThread) { + return this.PThread.preloadWorkers(); + } + return Promise.resolve([]); + } + initialize(instance, module, memory) { + const exports = instance.exports; + memory !== null && memory !== void 0 ? memory : (memory = exports.memory); + if (this.childThread) { + instance = createInstanceProxy(instance, memory); + } + this.setup(instance, module, memory); + const wasi = this.wasi; + if (('_start' in exports) && (typeof exports._start === 'function')) { + if (this.childThread) { + wasi.start(instance); + try { + const kStarted = getWasiSymbol(wasi, 'kStarted'); + wasi[kStarted] = false; + } + catch (_) { } + } + else { + setupInstance(wasi, instance); + } + } + else { + wasi.initialize(instance); + } + return instance; + } + start(instance, module, memory) { + const exports = instance.exports; + memory !== null && memory !== void 0 ? memory : (memory = exports.memory); + if (this.childThread) { + instance = createInstanceProxy(instance, memory); + } + this.setup(instance, module, memory); + const exitCode = this.wasi.start(instance); + return { exitCode, instance }; + } + terminateAllThreads() { + var _a; + if (!this.childThread) { + (_a = this.PThread) === null || _a === void 0 ? void 0 : _a.terminateAllThreads(); + } + else { + this.postMessage(createMessage('terminate-all-threads', {})); + } + } +} +function patchWasiInstance(wasiThreads, wasi) { + const patched = patchedWasiInstances.get(wasiThreads); + if (patched.has(wasi)) { + return; + } + const _this = wasiThreads; + const wasiImport = wasi.wasiImport; + if (wasiImport) { + const proc_exit = wasiImport.proc_exit; + wasiImport.proc_exit = function (code) { + _this.terminateAllThreads(); + return proc_exit.call(this, code); + }; + } + if (!_this.childThread) { + const start = wasi.start; + if (typeof start === 'function') { + wasi.start = function (instance) { + try { + return start.call(this, instance); + } + catch (err) { + if (isTrapError(err)) { + _this.terminateAllThreads(); + } + throw err; + } + }; + } + } + patched.add(wasi); +} +function getWasiSymbol(wasi, description) { + const symbols = Object.getOwnPropertySymbols(wasi); + const selectDescription = (description) => (s) => { + if (s.description) { + return s.description === description; + } + return s.toString() === `Symbol(${description})`; + }; + if (Array.isArray(description)) { + return description.map(d => symbols.filter(selectDescription(d))[0]); + } + return symbols.filter(selectDescription(description))[0]; +} +function setupInstance(wasi, instance) { + const [kInstance, kSetMemory] = getWasiSymbol(wasi, ['kInstance', 'kSetMemory']); + wasi[kInstance] = instance; + wasi[kSetMemory](instance.exports.memory); +} + +class ThreadMessageHandler { + constructor(options) { + const postMsg = getPostMessage(options); + if (typeof postMsg !== 'function') { + throw new TypeError('options.postMessage is not a function'); + } + this.postMessage = postMsg; + this.onLoad = options === null || options === void 0 ? void 0 : options.onLoad; + this.onError = typeof (options === null || options === void 0 ? void 0 : options.onError) === 'function' ? options.onError : (_type, err) => { throw err; }; + this.instance = undefined; + this.messagesBeforeLoad = []; + } + instantiate(data) { + if (typeof this.onLoad === 'function') { + return this.onLoad(data); + } + throw new Error('ThreadMessageHandler.prototype.instantiate is not implemented'); + } + handle(e) { + var _a; + if ((_a = e === null || e === void 0 ? void 0 : e.data) === null || _a === void 0 ? void 0 : _a.__emnapi__) { + const type = e.data.__emnapi__.type; + const payload = e.data.__emnapi__.payload; + try { + if (type === 'load') { + this._load(payload); + } + else if (type === 'start') { + this.handleAfterLoad(e, () => { + this._start(payload); + }); + } + } + catch (err) { + this.onError(err, type); + } + } + } + _load(payload) { + if (this.instance !== undefined) + return; + let source; + try { + source = this.instantiate(payload); + } + catch (err) { + this._loaded(err, null, payload); + return; + } + const then = source && 'then' in source ? source.then : undefined; + if (typeof then === 'function') { + then.call(source, (source) => { this._loaded(null, source, payload); }, (err) => { this._loaded(err, null, payload); }); + } + else { + this._loaded(null, source, payload); + } + } + _start(payload) { + const wasi_thread_start = this.instance.exports.wasi_thread_start; + if (typeof wasi_thread_start !== 'function') { + const err = new TypeError('wasi_thread_start is not exported'); + notifyPthreadCreateResult(payload.sab, 2, err); + throw err; + } + const postMessage = this.postMessage; + const tid = payload.tid; + const startArg = payload.arg; + notifyPthreadCreateResult(payload.sab, 1); + try { + wasi_thread_start(tid, startArg); + } + catch (err) { + if (err !== 'unwind') { + throw err; + } + else { + return; + } + } + postMessage(createMessage('cleanup-thread', { tid })); + } + _loaded(err, source, payload) { + if (err) { + notifyPthreadCreateResult(payload.sab, 2, err); + throw err; + } + if (source == null) { + const err = new TypeError('onLoad should return an object'); + notifyPthreadCreateResult(payload.sab, 2, err); + throw err; + } + const instance = source.instance; + if (!instance) { + const err = new TypeError('onLoad should return an object which includes "instance"'); + notifyPthreadCreateResult(payload.sab, 2, err); + throw err; + } + this.instance = instance; + const postMessage = this.postMessage; + postMessage(createMessage('loaded', {})); + const messages = this.messagesBeforeLoad; + this.messagesBeforeLoad = []; + for (let i = 0; i < messages.length; i++) { + const data = messages[i]; + this.handle({ data }); + } + } + handleAfterLoad(e, f) { + if (this.instance !== undefined) { + f.call(this, e); + } + else { + this.messagesBeforeLoad.push(e.data); + } + } +} +function notifyPthreadCreateResult(sab, result, error) { + if (sab) { + serizeErrorToBuffer(sab.buffer, result, error); + Atomics.notify(sab, 0); + } +} + +exports.ThreadManager = ThreadManager; +exports.ThreadMessageHandler = ThreadMessageHandler; +exports.WASIThreads = WASIThreads; +exports.createInstanceProxy = createInstanceProxy; +exports.isSharedArrayBuffer = isSharedArrayBuffer; +exports.isTrapError = isTrapError; diff --git a/dg-ui/node_modules/@tailwindcss/oxide-wasm32-wasi/node_modules/@emnapi/wasi-threads/dist/wasi-threads.cjs.min.d.ts b/dg-ui/node_modules/@tailwindcss/oxide-wasm32-wasi/node_modules/@emnapi/wasi-threads/dist/wasi-threads.cjs.min.d.ts new file mode 100644 index 0000000..1d3951c --- /dev/null +++ b/dg-ui/node_modules/@tailwindcss/oxide-wasm32-wasi/node_modules/@emnapi/wasi-threads/dist/wasi-threads.cjs.min.d.ts @@ -0,0 +1,271 @@ +/// + +import type { Worker as Worker_2 } from 'worker_threads'; + +/** @public */ +export declare interface BaseOptions { + wasi: WASIInstance; + version?: 'preview1'; + wasm64?: boolean; +} + +/** @public */ +export declare interface ChildThreadOptions extends BaseOptions { + childThread: true; + postMessage?: (data: any) => void; +} + +/** @public */ +export declare interface CleanupThreadPayload { + tid: number; +} + +/** @public */ +export declare interface CommandInfo { + type: T; + payload: CommandPayloadMap[T]; +} + +/** @public */ +export declare interface CommandPayloadMap { + load: LoadPayload; + loaded: LoadedPayload; + start: StartPayload; + 'cleanup-thread': CleanupThreadPayload; + 'terminate-all-threads': TerminateAllThreadsPayload; + 'spawn-thread': SpawnThreadPayload; +} + +/** @public */ +export declare type CommandType = keyof CommandPayloadMap; + +/** @public */ +export declare function createInstanceProxy(instance: WebAssembly.Instance, memory?: WebAssembly.Memory | (() => WebAssembly.Memory)): WebAssembly.Instance; + +/** @public */ +export declare function isSharedArrayBuffer(value: any): value is SharedArrayBuffer; + +/** @public */ +export declare function isTrapError(e: Error): e is WebAssembly.RuntimeError; + +/** @public */ +export declare interface LoadedPayload { +} + +/** @public */ +export declare interface LoadPayload { + wasmModule: WebAssembly.Module; + wasmMemory: WebAssembly.Memory; + sab?: Int32Array; +} + +/** @public */ +export declare interface MainThreadBaseOptions extends BaseOptions { + waitThreadStart?: boolean | number; +} + +/** @public */ +export declare type MainThreadOptions = MainThreadOptionsWithThreadManager | MainThreadOptionsCreateThreadManager; + +/** @public */ +export declare interface MainThreadOptionsCreateThreadManager extends MainThreadBaseOptions, ThreadManagerOptionsMain { +} + +/** @public */ +export declare interface MainThreadOptionsWithThreadManager extends MainThreadBaseOptions { + threadManager?: ThreadManager | (() => ThreadManager); +} + +/** @public */ +export declare interface MessageEventData { + __emnapi__: CommandInfo; +} + +/** @public */ +export declare interface ReuseWorkerOptions { + /** + * @see {@link https://emscripten.org/docs/tools_reference/settings_reference.html#pthread-pool-size | PTHREAD_POOL_SIZE} + */ + size: number; + /** + * @see {@link https://emscripten.org/docs/tools_reference/settings_reference.html#pthread-pool-size-strict | PTHREAD_POOL_SIZE_STRICT} + */ + strict?: boolean; +} + +/** @public */ +export declare interface SpawnThreadPayload { + startArg: number; + errorOrTid: number; +} + +/** @public */ +export declare interface StartPayload { + tid: number; + arg: number; + sab?: Int32Array; +} + +/** @public */ +export declare interface StartResult { + exitCode: number; + instance: WebAssembly.Instance; +} + +/** @public */ +export declare interface TerminateAllThreadsPayload { +} + +/** @public */ +export declare class ThreadManager { + unusedWorkers: WorkerLike[]; + pthreads: Record; + get nextWorkerID(): number; + wasmModule: WebAssembly.Module | null; + wasmMemory: WebAssembly.Memory | null; + private readonly messageEvents; + private readonly _childThread; + private readonly _onCreateWorker; + private readonly _reuseWorker; + private readonly _beforeLoad?; + /* Excluded from this release type: printErr */ + threadSpawn?: ((startArg: number, errorOrTid?: number) => number); + constructor(options: ThreadManagerOptions); + init(): void; + initMainThread(): void; + private preparePool; + shouldPreloadWorkers(): boolean; + loadWasmModuleToAllWorkers(): Promise; + preloadWorkers(): Promise; + setup(wasmModule: WebAssembly.Module, wasmMemory: WebAssembly.Memory): void; + markId(worker: WorkerLike): number; + returnWorkerToPool(worker: WorkerLike): void; + loadWasmModuleToWorker(worker: WorkerLike, sab?: Int32Array): Promise; + allocateUnusedWorker(): WorkerLike; + getNewWorker(sab?: Int32Array): WorkerLike | undefined; + cleanThread(worker: WorkerLike, tid: number, force?: boolean): void; + terminateWorker(worker: WorkerLike): void; + terminateAllThreads(): void; + addMessageEventListener(worker: WorkerLike, onMessage: (e: WorkerMessageEvent) => void): () => void; + fireMessageEvent(worker: WorkerLike, e: WorkerMessageEvent): void; +} + +/** @public */ +export declare type ThreadManagerOptions = ThreadManagerOptionsMain | ThreadManagerOptionsChild; + +/** @public */ +export declare interface ThreadManagerOptionsBase { + printErr?: (message: string) => void; + threadSpawn?: (startArg: number, errorOrTid?: number) => number; +} + +/** @public */ +export declare interface ThreadManagerOptionsChild extends ThreadManagerOptionsBase { + childThread: true; +} + +/** @public */ +export declare interface ThreadManagerOptionsMain extends ThreadManagerOptionsBase { + beforeLoad?: (worker: WorkerLike) => any; + reuseWorker?: boolean | number | ReuseWorkerOptions; + onCreateWorker: WorkerFactory; + childThread?: false; +} + +/** @public */ +export declare class ThreadMessageHandler { + protected instance: WebAssembly.Instance | undefined; + private messagesBeforeLoad; + protected postMessage: (message: any) => void; + protected onLoad?: (data: LoadPayload) => WebAssembly.WebAssemblyInstantiatedSource | PromiseLike; + protected onError: (error: Error, type: WorkerMessageType) => void; + constructor(options?: ThreadMessageHandlerOptions); + /** @virtual */ + instantiate(data: LoadPayload): WebAssembly.WebAssemblyInstantiatedSource | PromiseLike; + /** @virtual */ + handle(e: WorkerMessageEvent>): void; + private _load; + private _start; + protected _loaded(err: Error | null, source: WebAssembly.WebAssemblyInstantiatedSource | null, payload: LoadPayload): void; + protected handleAfterLoad(e: E, f: (e: E) => void): void; +} + +/** @public */ +export declare interface ThreadMessageHandlerOptions { + onLoad?: (data: LoadPayload) => WebAssembly.WebAssemblyInstantiatedSource | PromiseLike; + onError?: (error: Error, type: WorkerMessageType) => void; + postMessage?: (message: any) => void; +} + +/** @public */ +export declare interface WASIInstance { + readonly wasiImport?: Record; + initialize(instance: object): void; + start(instance: object): number; + getImportObject?(): any; +} + +/** @public */ +export declare class WASIThreads { + PThread: ThreadManager | undefined; + private wasmMemory; + private wasmInstance; + private readonly threadSpawn; + readonly childThread: boolean; + private readonly postMessage; + readonly wasi: WASIInstance; + constructor(options: WASIThreadsOptions); + getImportObject(): { + wasi: WASIThreadsImports; + }; + setup(wasmInstance: WebAssembly.Instance, wasmModule: WebAssembly.Module, wasmMemory?: WebAssembly.Memory): void; + preloadWorkers(): Promise; + /** + * It's ok to call this method to a WASI command module. + * + * in child thread, must call this method instead of {@link WASIThreads.start} even if it's a WASI command module + * + * @returns A proxied WebAssembly instance if in child thread, other wise the original instance + */ + initialize(instance: WebAssembly.Instance, module: WebAssembly.Module, memory?: WebAssembly.Memory): WebAssembly.Instance; + /** + * Equivalent to calling {@link WASIThreads.initialize} and then calling {@link WASIInstance.start} + * ```js + * this.initialize(instance, module, memory) + * this.wasi.start(instance) + * ``` + */ + start(instance: WebAssembly.Instance, module: WebAssembly.Module, memory?: WebAssembly.Memory): StartResult; + terminateAllThreads(): void; +} + +/** @public */ +export declare interface WASIThreadsImports { + 'thread-spawn': (startArg: number, errorOrTid?: number) => number; +} + +/** @public */ +export declare type WASIThreadsOptions = MainThreadOptions | ChildThreadOptions; + +/** @public */ +export declare type WorkerFactory = (ctx: { + type: string; + name: string; +}) => WorkerLike; + +/** @public */ +export declare type WorkerLike = (Worker | Worker_2) & { + whenLoaded?: Promise; + loaded?: boolean; + __emnapi_tid?: number; +}; + +/** @public */ +export declare interface WorkerMessageEvent { + data: T; +} + +/** @public */ +export declare type WorkerMessageType = 'load' | 'start'; + +export { } diff --git a/dg-ui/node_modules/@tailwindcss/oxide-wasm32-wasi/node_modules/@emnapi/wasi-threads/dist/wasi-threads.cjs.min.js b/dg-ui/node_modules/@tailwindcss/oxide-wasm32-wasi/node_modules/@emnapi/wasi-threads/dist/wasi-threads.cjs.min.js new file mode 100644 index 0000000..a249936 --- /dev/null +++ b/dg-ui/node_modules/@tailwindcss/oxide-wasm32-wasi/node_modules/@emnapi/wasi-threads/dist/wasi-threads.cjs.min.js @@ -0,0 +1 @@ +const e="undefined"!=typeof WebAssembly?WebAssembly:"undefined"!=typeof WXWebAssembly?WXWebAssembly:void 0,t="object"==typeof process&&null!==process&&"object"==typeof process.versions&&null!==process.versions&&"string"==typeof process.versions.node;function r(e){return"function"==typeof(null==e?void 0:e.postMessage)?e.postMessage:"function"==typeof postMessage?postMessage:void 0}function s(e){return"function"==typeof SharedArrayBuffer&&e instanceof SharedArrayBuffer||"[object SharedArrayBuffer]"===Object.prototype.toString.call(e)}function o(t){try{return t instanceof e.RuntimeError}catch(e){return!1}}function n(e,t){return{__emnapi__:{type:e,payload:t}}}function i(e){if(e){if(!s(e.buffer))throw new Error("Multithread features require shared wasm memory. Try to compile with `-matomics -mbulk-memory` and use `--import-memory --shared-memory` during linking, then create WebAssembly.Memory with `shared: true` option")}else if("undefined"==typeof SharedArrayBuffer)throw new Error("Current environment does not support SharedArrayBuffer, threads are not available!")}let a=0;class h{get nextWorkerID(){return a}constructor(e){var t;if(this.unusedWorkers=[],this.pthreads=Object.create(null),this.wasmModule=null,this.wasmMemory=null,this.messageEvents=new WeakMap,!e)throw new TypeError("ThreadManager(): options is not provided");this._childThread="childThread"in e&&Boolean(e.childThread),this._childThread?(this._onCreateWorker=void 0,this._reuseWorker=!1,this._beforeLoad=void 0):(this._onCreateWorker=e.onCreateWorker,this._reuseWorker=function(e){var t;if("boolean"==typeof e)return!!e&&{size:0,strict:!1};if("number"==typeof e){if(!(e>=0))throw new RangeError("reuseWorker: size must be a non-negative integer");return{size:e,strict:!1}}if(!e)return!1;const r=null!==(t=Number(e.size))&&void 0!==t?t:0,s=Boolean(e.strict);if(!(r>0)&&s)throw new RangeError("reuseWorker: size must be set to positive integer if strict is set to true");return{size:r,strict:s}}(e.reuseWorker),this._beforeLoad=e.beforeLoad),this.printErr=null!==(t=e.printErr)&&void 0!==t?t:console.error.bind(console),this.threadSpawn=e.threadSpawn}init(){this._childThread||this.initMainThread()}initMainThread(){this.preparePool()}preparePool(){if(this._reuseWorker&&this._reuseWorker.size){let e=this._reuseWorker.size;for(;e--;){const e=this.allocateUnusedWorker();t&&(e.once("message",()=>{}),e.unref())}}}shouldPreloadWorkers(){return!this._childThread&&this._reuseWorker&&this._reuseWorker.size>0}loadWasmModuleToAllWorkers(){const e=Array(this.unusedWorkers.length);for(let r=0;r(t&&s.unref(),e),e=>{throw t&&s.unref(),e})}return Promise.all(e).catch(e=>{throw this.terminateAllThreads(),e})}preloadWorkers(){return this.shouldPreloadWorkers()?this.loadWasmModuleToAllWorkers():Promise.resolve([])}setup(e,t){this.wasmModule=e,this.wasmMemory=t}markId(e){if(e.__emnapi_tid)return e.__emnapi_tid;const t=a+43;return a=(a+1)%536870869,this.pthreads[t]=e,e.__emnapi_tid=t,t}returnWorkerToPool(e){var r=e.__emnapi_tid;void 0!==r&&delete this.pthreads[r],this.unusedWorkers.push(e),delete e.__emnapi_tid,t&&e.unref()}loadWasmModuleToWorker(e,r){if(e.whenLoaded)return e.whenLoaded;const s=this.printErr,o=this._beforeLoad,a=this;return e.whenLoaded=new Promise((h,d)=>{const l=r=>{if(r.__emnapi__){const s=r.__emnapi__.type,o=r.__emnapi__.payload;"loaded"===s?(e.loaded=!0,t&&!e.__emnapi_tid&&e.unref(),h(e)):"cleanup-thread"===s?o.tid in this.pthreads&&this.cleanThread(e,o.tid):"spawn-thread"===s?this.threadSpawn(o.startArg,o.errorOrTid):"terminate-all-threads"===s&&this.terminateAllThreads()}};e.onmessage=t=>{l(t.data),this.fireMessageEvent(e,t)},e.onerror=function(t){let r="worker sent an error!";if(void 0!==e.__emnapi_tid&&(r="worker (tid = "+e.__emnapi_tid+") sent an error!"),"message"in t){if(s(r+" "+t.message),-1!==t.message.indexOf("RuntimeError")||-1!==t.message.indexOf("unreachable"))try{a.terminateAllThreads()}catch(e){}}else s(r);throw d(t),t},t&&(e.on("message",function(t){var r,s;null===(s=(r=e).onmessage)||void 0===s||s.call(r,{data:t})}),e.on("error",function(t){var r,s;null===(s=(r=e).onerror)||void 0===s||s.call(r,t)}),e.on("detachedExit",function(){})),"function"==typeof o&&o(e);try{e.postMessage(n("load",{wasmModule:this.wasmModule,wasmMemory:this.wasmMemory,sab:r}))}catch(e){throw i(this.wasmMemory),e}}),e.whenLoaded}allocateUnusedWorker(){const e=this._onCreateWorker;if("function"!=typeof e)throw new TypeError("`options.onCreateWorker` is not provided");const t=e({type:"thread",name:"emnapi-pthread"});return this.unusedWorkers.push(t),t}getNewWorker(e){if(this._reuseWorker){if(0===this.unusedWorkers.length){if(this._reuseWorker.strict&&!t){return void(0,this.printErr)("Tried to spawn a new thread, but the thread pool is exhausted.\nThis might result in a deadlock unless some threads eventually exit or the code explicitly breaks out to the event loop.")}const r=this.allocateUnusedWorker();this.loadWasmModuleToWorker(r,e)}return this.unusedWorkers.pop()}const r=this.allocateUnusedWorker();return this.loadWasmModuleToWorker(r,e),this.unusedWorkers.pop()}cleanThread(e,t,r){!r&&this._reuseWorker?this.returnWorkerToPool(e):(delete this.pthreads[t],this.terminateWorker(e),delete e.__emnapi_tid)}terminateWorker(e){var t;const r=e.__emnapi_tid;e.terminate(),null===(t=this.messageEvents.get(e))||void 0===t||t.clear(),this.messageEvents.delete(e),e.onmessage=e=>{if(e.data.__emnapi__){(0,this.printErr)('received "'+e.data.__emnapi__.type+'" command from terminated worker: '+r)}}}terminateAllThreads(){const e=Object.values(this.pthreads);for(let t=0;t{null==r||r.delete(t)}}fireMessageEvent(e,t){const r=this.messageEvents.get(e);if(!r)return;const s=this.printErr;r.forEach(e=>{try{e(t)}catch(e){s(e.stack)}})}}const d=Symbol("kIsProxy");function l(e,t){if(e[d])return e;const r=e.exports,s=function(e){const t=["apply","construct","defineProperty","deleteProperty","get","getOwnPropertyDescriptor","getPrototypeOf","has","isExtensible","ownKeys","preventExtensions","set","setPrototypeOf"],r={};for(let s=0;s{},n=()=>0;s.get=function(e,s,i){var a;return"memory"===s?null!==(a="function"==typeof t?t():t)&&void 0!==a?a:Reflect.get(r,s,i):"_initialize"===s?s in r?o:void 0:"_start"===s?s in r?n:void 0:Reflect.get(r,s,i)},s.has=function(e,t){return"memory"===t||Reflect.has(r,t)};const i=new Proxy(Object.create(null),s);return new Proxy(e,{get:(e,t,r)=>"exports"===t?i:t===d||Reflect.get(e,t,r)})}const c=new WeakMap,u=2*Int32Array.BYTES_PER_ELEMENT,f="function"==typeof SharedArrayBuffer?Object.getOwnPropertyDescriptor(SharedArrayBuffer.prototype,"byteLength").get:void 0;function p(e,t,r){const s="bigint"==typeof t?Number(t):t>>>0;let o=e.buffer;return s+u>o.byteLength&&function(e){if(void 0===f)return!1;try{return f.call(e),!0}catch(e){return!1}}(o)&&(r?e.grow(BigInt(0)):e.grow(0),o=e.buffer),new Int32Array(o,s,2)}function m(e,t){const r=Object.getOwnPropertySymbols(e),s=e=>t=>t.description?t.description===e:t.toString()===`Symbol(${e})`;return Array.isArray(t)?t.map(e=>r.filter(s(e))[0]):r.filter(s(t))[0]}function w(e,t,r){e&&(!function(e,t,r){const s=new Int32Array(e);if(Atomics.store(s,0,t),t>1&&r){const t=r.name,o=r.message,n=r.stack,i=(new TextEncoder).encode(t),a=(new TextEncoder).encode(o),h=(new TextEncoder).encode(n);Atomics.store(s,1,i.length),Atomics.store(s,2,a.length),Atomics.store(s,3,h.length);const d=new Uint8Array(e);d.set(i,16),d.set(a,16+i.length),d.set(h,16+i.length+a.length)}}(e.buffer,t,r),Atomics.notify(e,0))}exports.ThreadManager=h,exports.ThreadMessageHandler=class{constructor(e){const t=r(e);if("function"!=typeof t)throw new TypeError("options.postMessage is not a function");this.postMessage=t,this.onLoad=null==e?void 0:e.onLoad,this.onError="function"==typeof(null==e?void 0:e.onError)?e.onError:(e,t)=>{throw t},this.instance=void 0,this.messagesBeforeLoad=[]}instantiate(e){if("function"==typeof this.onLoad)return this.onLoad(e);throw new Error("ThreadMessageHandler.prototype.instantiate is not implemented")}handle(e){var t;if(null===(t=null==e?void 0:e.data)||void 0===t?void 0:t.__emnapi__){const t=e.data.__emnapi__.type,r=e.data.__emnapi__.payload;try{"load"===t?this._load(r):"start"===t&&this.handleAfterLoad(e,()=>{this._start(r)})}catch(e){this.onError(e,t)}}}_load(e){if(void 0!==this.instance)return;let t;try{t=this.instantiate(e)}catch(t){return void this._loaded(t,null,e)}const r=t&&"then"in t?t.then:void 0;"function"==typeof r?r.call(t,t=>{this._loaded(null,t,e)},t=>{this._loaded(t,null,e)}):this._loaded(null,t,e)}_start(e){const t=this.instance.exports.wasi_thread_start;if("function"!=typeof t){const t=new TypeError("wasi_thread_start is not exported");throw w(e.sab,2,t),t}const r=this.postMessage,s=e.tid,o=e.arg;w(e.sab,1);try{t(s,o)}catch(e){if("unwind"!==e)throw e;return}r(n("cleanup-thread",{tid:s}))}_loaded(e,t,r){if(e)throw w(r.sab,2,e),e;if(null==t){const e=new TypeError("onLoad should return an object");throw w(r.sab,2,e),e}const s=t.instance;if(!s){const e=new TypeError('onLoad should return an object which includes "instance"');throw w(r.sab,2,e),e}this.instance=s;(0,this.postMessage)(n("loaded",{}));const o=this.messagesBeforeLoad;this.messagesBeforeLoad=[];for(let e=0;e{var o;const a=void 0!==s;try{i(this.wasmMemory)}catch(e){if(null===(o=this.PThread)||void 0===o||o.printErr(e.stack),a){const e=p(this.wasmMemory,s,u);return Atomics.store(e,0,1),Atomics.store(e,1,6),Atomics.notify(e,1),1}return-6}if(!a){const e=this.wasmInstance.exports.malloc;if(!(s=u?Number(e(BigInt(8))):e(8)>>>0))return-48}const h=this.wasmInstance.exports.free,c=u?e=>{h(BigInt(e))}:h,f=p(this.wasmMemory,s,u);if(Atomics.store(f,0,0),Atomics.store(f,1,0),this.childThread){l(n("spawn-thread",{startArg:r,errorOrTid:s})),Atomics.wait(f,1,0);const e=Atomics.load(f,0),t=Atomics.load(f,1);return a?e:(c(s),e?-t:t)}const m=d||0===d;let w,y,_;m&&(w=new Int32Array(new SharedArrayBuffer(8208)),Atomics.store(w,0,0));const g=this.PThread;try{if(y=g.getNewWorker(w),!y)throw new Error("failed to get new worker");if(_=g.markId(y),t&&y.unref(),y.postMessage(n("start",{tid:_,arg:r,sab:w})),m){if("number"==typeof d){if("timed-out"===Atomics.wait(w,0,0,d))throw new Error("Spawning thread timed out. Please check if the worker is created successfully and if message is handled properly in the worker.")}else Atomics.wait(w,0,0);if(Atomics.load(w,0)>1)throw function(t){var r,s;const o=new Int32Array(t);if(Atomics.load(o,0)<=1)return null;const n=Atomics.load(o,1),i=Atomics.load(o,2),a=Atomics.load(o,3),h=new Uint8Array(t),d=h.slice(16,16+n),l=h.slice(16+n,16+n+i),c=h.slice(16+n+i,16+n+i+a),u=(new TextDecoder).decode(d),f=(new TextDecoder).decode(l),p=(new TextDecoder).decode(c),m=new(null!==(r=globalThis[u])&&void 0!==r?r:"RuntimeError"===u&&null!==(s=e.RuntimeError)&&void 0!==s?s:Error)(f);return Object.defineProperty(m,"stack",{value:p,writable:!0,enumerable:!1,configurable:!0}),m}(w.buffer)}}catch(e){if(void 0!==y&&void 0!==_)try{g.cleanThread(y,_,!0)}catch(e){}return Atomics.store(f,0,1),Atomics.store(f,1,6),Atomics.notify(f,1),null==g||g.printErr(e.stack),a?1:(c(s),-6)}return Atomics.store(f,0,0),Atomics.store(f,1,_),Atomics.notify(f,1),m||y.whenLoaded.catch(e=>{throw delete y.whenLoaded,g.cleanThread(y,_,!0),e}),a?0:(c(s),_)};this.threadSpawn=f,this.PThread&&(this.PThread.threadSpawn=f)}getImportObject(){return{wasi:{"thread-spawn":this.threadSpawn}}}setup(e,t,r){null!=r||(r=e.exports.memory),this.wasmInstance=e,this.wasmMemory=r,this.PThread&&this.PThread.setup(t,r)}preloadWorkers(){return this.PThread?this.PThread.preloadWorkers():Promise.resolve([])}initialize(e,t,r){const s=e.exports;null!=r||(r=s.memory),this.childThread&&(e=l(e,r)),this.setup(e,t,r);const o=this.wasi;if("_start"in s&&"function"==typeof s._start)if(this.childThread){o.start(e);try{o[m(o,"kStarted")]=!1}catch(e){}}else!function(e,t){const[r,s]=m(e,["kInstance","kSetMemory"]);e[r]=t,e[s](t.exports.memory)}(o,e);else o.initialize(e);return e}start(e,t,r){const s=e.exports;null!=r||(r=s.memory),this.childThread&&(e=l(e,r)),this.setup(e,t,r);return{exitCode:this.wasi.start(e),instance:e}}terminateAllThreads(){var e;this.childThread?this.postMessage(n("terminate-all-threads",{})):null===(e=this.PThread)||void 0===e||e.terminateAllThreads()}},exports.createInstanceProxy=l,exports.isSharedArrayBuffer=s,exports.isTrapError=o; diff --git a/dg-ui/node_modules/@tailwindcss/oxide-wasm32-wasi/node_modules/@emnapi/wasi-threads/dist/wasi-threads.d.mts b/dg-ui/node_modules/@tailwindcss/oxide-wasm32-wasi/node_modules/@emnapi/wasi-threads/dist/wasi-threads.d.mts new file mode 100644 index 0000000..1d3951c --- /dev/null +++ b/dg-ui/node_modules/@tailwindcss/oxide-wasm32-wasi/node_modules/@emnapi/wasi-threads/dist/wasi-threads.d.mts @@ -0,0 +1,271 @@ +/// + +import type { Worker as Worker_2 } from 'worker_threads'; + +/** @public */ +export declare interface BaseOptions { + wasi: WASIInstance; + version?: 'preview1'; + wasm64?: boolean; +} + +/** @public */ +export declare interface ChildThreadOptions extends BaseOptions { + childThread: true; + postMessage?: (data: any) => void; +} + +/** @public */ +export declare interface CleanupThreadPayload { + tid: number; +} + +/** @public */ +export declare interface CommandInfo { + type: T; + payload: CommandPayloadMap[T]; +} + +/** @public */ +export declare interface CommandPayloadMap { + load: LoadPayload; + loaded: LoadedPayload; + start: StartPayload; + 'cleanup-thread': CleanupThreadPayload; + 'terminate-all-threads': TerminateAllThreadsPayload; + 'spawn-thread': SpawnThreadPayload; +} + +/** @public */ +export declare type CommandType = keyof CommandPayloadMap; + +/** @public */ +export declare function createInstanceProxy(instance: WebAssembly.Instance, memory?: WebAssembly.Memory | (() => WebAssembly.Memory)): WebAssembly.Instance; + +/** @public */ +export declare function isSharedArrayBuffer(value: any): value is SharedArrayBuffer; + +/** @public */ +export declare function isTrapError(e: Error): e is WebAssembly.RuntimeError; + +/** @public */ +export declare interface LoadedPayload { +} + +/** @public */ +export declare interface LoadPayload { + wasmModule: WebAssembly.Module; + wasmMemory: WebAssembly.Memory; + sab?: Int32Array; +} + +/** @public */ +export declare interface MainThreadBaseOptions extends BaseOptions { + waitThreadStart?: boolean | number; +} + +/** @public */ +export declare type MainThreadOptions = MainThreadOptionsWithThreadManager | MainThreadOptionsCreateThreadManager; + +/** @public */ +export declare interface MainThreadOptionsCreateThreadManager extends MainThreadBaseOptions, ThreadManagerOptionsMain { +} + +/** @public */ +export declare interface MainThreadOptionsWithThreadManager extends MainThreadBaseOptions { + threadManager?: ThreadManager | (() => ThreadManager); +} + +/** @public */ +export declare interface MessageEventData { + __emnapi__: CommandInfo; +} + +/** @public */ +export declare interface ReuseWorkerOptions { + /** + * @see {@link https://emscripten.org/docs/tools_reference/settings_reference.html#pthread-pool-size | PTHREAD_POOL_SIZE} + */ + size: number; + /** + * @see {@link https://emscripten.org/docs/tools_reference/settings_reference.html#pthread-pool-size-strict | PTHREAD_POOL_SIZE_STRICT} + */ + strict?: boolean; +} + +/** @public */ +export declare interface SpawnThreadPayload { + startArg: number; + errorOrTid: number; +} + +/** @public */ +export declare interface StartPayload { + tid: number; + arg: number; + sab?: Int32Array; +} + +/** @public */ +export declare interface StartResult { + exitCode: number; + instance: WebAssembly.Instance; +} + +/** @public */ +export declare interface TerminateAllThreadsPayload { +} + +/** @public */ +export declare class ThreadManager { + unusedWorkers: WorkerLike[]; + pthreads: Record; + get nextWorkerID(): number; + wasmModule: WebAssembly.Module | null; + wasmMemory: WebAssembly.Memory | null; + private readonly messageEvents; + private readonly _childThread; + private readonly _onCreateWorker; + private readonly _reuseWorker; + private readonly _beforeLoad?; + /* Excluded from this release type: printErr */ + threadSpawn?: ((startArg: number, errorOrTid?: number) => number); + constructor(options: ThreadManagerOptions); + init(): void; + initMainThread(): void; + private preparePool; + shouldPreloadWorkers(): boolean; + loadWasmModuleToAllWorkers(): Promise; + preloadWorkers(): Promise; + setup(wasmModule: WebAssembly.Module, wasmMemory: WebAssembly.Memory): void; + markId(worker: WorkerLike): number; + returnWorkerToPool(worker: WorkerLike): void; + loadWasmModuleToWorker(worker: WorkerLike, sab?: Int32Array): Promise; + allocateUnusedWorker(): WorkerLike; + getNewWorker(sab?: Int32Array): WorkerLike | undefined; + cleanThread(worker: WorkerLike, tid: number, force?: boolean): void; + terminateWorker(worker: WorkerLike): void; + terminateAllThreads(): void; + addMessageEventListener(worker: WorkerLike, onMessage: (e: WorkerMessageEvent) => void): () => void; + fireMessageEvent(worker: WorkerLike, e: WorkerMessageEvent): void; +} + +/** @public */ +export declare type ThreadManagerOptions = ThreadManagerOptionsMain | ThreadManagerOptionsChild; + +/** @public */ +export declare interface ThreadManagerOptionsBase { + printErr?: (message: string) => void; + threadSpawn?: (startArg: number, errorOrTid?: number) => number; +} + +/** @public */ +export declare interface ThreadManagerOptionsChild extends ThreadManagerOptionsBase { + childThread: true; +} + +/** @public */ +export declare interface ThreadManagerOptionsMain extends ThreadManagerOptionsBase { + beforeLoad?: (worker: WorkerLike) => any; + reuseWorker?: boolean | number | ReuseWorkerOptions; + onCreateWorker: WorkerFactory; + childThread?: false; +} + +/** @public */ +export declare class ThreadMessageHandler { + protected instance: WebAssembly.Instance | undefined; + private messagesBeforeLoad; + protected postMessage: (message: any) => void; + protected onLoad?: (data: LoadPayload) => WebAssembly.WebAssemblyInstantiatedSource | PromiseLike; + protected onError: (error: Error, type: WorkerMessageType) => void; + constructor(options?: ThreadMessageHandlerOptions); + /** @virtual */ + instantiate(data: LoadPayload): WebAssembly.WebAssemblyInstantiatedSource | PromiseLike; + /** @virtual */ + handle(e: WorkerMessageEvent>): void; + private _load; + private _start; + protected _loaded(err: Error | null, source: WebAssembly.WebAssemblyInstantiatedSource | null, payload: LoadPayload): void; + protected handleAfterLoad(e: E, f: (e: E) => void): void; +} + +/** @public */ +export declare interface ThreadMessageHandlerOptions { + onLoad?: (data: LoadPayload) => WebAssembly.WebAssemblyInstantiatedSource | PromiseLike; + onError?: (error: Error, type: WorkerMessageType) => void; + postMessage?: (message: any) => void; +} + +/** @public */ +export declare interface WASIInstance { + readonly wasiImport?: Record; + initialize(instance: object): void; + start(instance: object): number; + getImportObject?(): any; +} + +/** @public */ +export declare class WASIThreads { + PThread: ThreadManager | undefined; + private wasmMemory; + private wasmInstance; + private readonly threadSpawn; + readonly childThread: boolean; + private readonly postMessage; + readonly wasi: WASIInstance; + constructor(options: WASIThreadsOptions); + getImportObject(): { + wasi: WASIThreadsImports; + }; + setup(wasmInstance: WebAssembly.Instance, wasmModule: WebAssembly.Module, wasmMemory?: WebAssembly.Memory): void; + preloadWorkers(): Promise; + /** + * It's ok to call this method to a WASI command module. + * + * in child thread, must call this method instead of {@link WASIThreads.start} even if it's a WASI command module + * + * @returns A proxied WebAssembly instance if in child thread, other wise the original instance + */ + initialize(instance: WebAssembly.Instance, module: WebAssembly.Module, memory?: WebAssembly.Memory): WebAssembly.Instance; + /** + * Equivalent to calling {@link WASIThreads.initialize} and then calling {@link WASIInstance.start} + * ```js + * this.initialize(instance, module, memory) + * this.wasi.start(instance) + * ``` + */ + start(instance: WebAssembly.Instance, module: WebAssembly.Module, memory?: WebAssembly.Memory): StartResult; + terminateAllThreads(): void; +} + +/** @public */ +export declare interface WASIThreadsImports { + 'thread-spawn': (startArg: number, errorOrTid?: number) => number; +} + +/** @public */ +export declare type WASIThreadsOptions = MainThreadOptions | ChildThreadOptions; + +/** @public */ +export declare type WorkerFactory = (ctx: { + type: string; + name: string; +}) => WorkerLike; + +/** @public */ +export declare type WorkerLike = (Worker | Worker_2) & { + whenLoaded?: Promise; + loaded?: boolean; + __emnapi_tid?: number; +}; + +/** @public */ +export declare interface WorkerMessageEvent { + data: T; +} + +/** @public */ +export declare type WorkerMessageType = 'load' | 'start'; + +export { } diff --git a/dg-ui/node_modules/@tailwindcss/oxide-wasm32-wasi/node_modules/@emnapi/wasi-threads/dist/wasi-threads.d.ts b/dg-ui/node_modules/@tailwindcss/oxide-wasm32-wasi/node_modules/@emnapi/wasi-threads/dist/wasi-threads.d.ts new file mode 100644 index 0000000..23b1fe3 --- /dev/null +++ b/dg-ui/node_modules/@tailwindcss/oxide-wasm32-wasi/node_modules/@emnapi/wasi-threads/dist/wasi-threads.d.ts @@ -0,0 +1,273 @@ +/// + +import type { Worker as Worker_2 } from 'worker_threads'; + +/** @public */ +export declare interface BaseOptions { + wasi: WASIInstance; + version?: 'preview1'; + wasm64?: boolean; +} + +/** @public */ +export declare interface ChildThreadOptions extends BaseOptions { + childThread: true; + postMessage?: (data: any) => void; +} + +/** @public */ +export declare interface CleanupThreadPayload { + tid: number; +} + +/** @public */ +export declare interface CommandInfo { + type: T; + payload: CommandPayloadMap[T]; +} + +/** @public */ +export declare interface CommandPayloadMap { + load: LoadPayload; + loaded: LoadedPayload; + start: StartPayload; + 'cleanup-thread': CleanupThreadPayload; + 'terminate-all-threads': TerminateAllThreadsPayload; + 'spawn-thread': SpawnThreadPayload; +} + +/** @public */ +export declare type CommandType = keyof CommandPayloadMap; + +/** @public */ +export declare function createInstanceProxy(instance: WebAssembly.Instance, memory?: WebAssembly.Memory | (() => WebAssembly.Memory)): WebAssembly.Instance; + +/** @public */ +export declare function isSharedArrayBuffer(value: any): value is SharedArrayBuffer; + +/** @public */ +export declare function isTrapError(e: Error): e is WebAssembly.RuntimeError; + +/** @public */ +export declare interface LoadedPayload { +} + +/** @public */ +export declare interface LoadPayload { + wasmModule: WebAssembly.Module; + wasmMemory: WebAssembly.Memory; + sab?: Int32Array; +} + +/** @public */ +export declare interface MainThreadBaseOptions extends BaseOptions { + waitThreadStart?: boolean | number; +} + +/** @public */ +export declare type MainThreadOptions = MainThreadOptionsWithThreadManager | MainThreadOptionsCreateThreadManager; + +/** @public */ +export declare interface MainThreadOptionsCreateThreadManager extends MainThreadBaseOptions, ThreadManagerOptionsMain { +} + +/** @public */ +export declare interface MainThreadOptionsWithThreadManager extends MainThreadBaseOptions { + threadManager?: ThreadManager | (() => ThreadManager); +} + +/** @public */ +export declare interface MessageEventData { + __emnapi__: CommandInfo; +} + +/** @public */ +export declare interface ReuseWorkerOptions { + /** + * @see {@link https://emscripten.org/docs/tools_reference/settings_reference.html#pthread-pool-size | PTHREAD_POOL_SIZE} + */ + size: number; + /** + * @see {@link https://emscripten.org/docs/tools_reference/settings_reference.html#pthread-pool-size-strict | PTHREAD_POOL_SIZE_STRICT} + */ + strict?: boolean; +} + +/** @public */ +export declare interface SpawnThreadPayload { + startArg: number; + errorOrTid: number; +} + +/** @public */ +export declare interface StartPayload { + tid: number; + arg: number; + sab?: Int32Array; +} + +/** @public */ +export declare interface StartResult { + exitCode: number; + instance: WebAssembly.Instance; +} + +/** @public */ +export declare interface TerminateAllThreadsPayload { +} + +/** @public */ +export declare class ThreadManager { + unusedWorkers: WorkerLike[]; + pthreads: Record; + get nextWorkerID(): number; + wasmModule: WebAssembly.Module | null; + wasmMemory: WebAssembly.Memory | null; + private readonly messageEvents; + private readonly _childThread; + private readonly _onCreateWorker; + private readonly _reuseWorker; + private readonly _beforeLoad?; + /* Excluded from this release type: printErr */ + threadSpawn?: ((startArg: number, errorOrTid?: number) => number); + constructor(options: ThreadManagerOptions); + init(): void; + initMainThread(): void; + private preparePool; + shouldPreloadWorkers(): boolean; + loadWasmModuleToAllWorkers(): Promise; + preloadWorkers(): Promise; + setup(wasmModule: WebAssembly.Module, wasmMemory: WebAssembly.Memory): void; + markId(worker: WorkerLike): number; + returnWorkerToPool(worker: WorkerLike): void; + loadWasmModuleToWorker(worker: WorkerLike, sab?: Int32Array): Promise; + allocateUnusedWorker(): WorkerLike; + getNewWorker(sab?: Int32Array): WorkerLike | undefined; + cleanThread(worker: WorkerLike, tid: number, force?: boolean): void; + terminateWorker(worker: WorkerLike): void; + terminateAllThreads(): void; + addMessageEventListener(worker: WorkerLike, onMessage: (e: WorkerMessageEvent) => void): () => void; + fireMessageEvent(worker: WorkerLike, e: WorkerMessageEvent): void; +} + +/** @public */ +export declare type ThreadManagerOptions = ThreadManagerOptionsMain | ThreadManagerOptionsChild; + +/** @public */ +export declare interface ThreadManagerOptionsBase { + printErr?: (message: string) => void; + threadSpawn?: (startArg: number, errorOrTid?: number) => number; +} + +/** @public */ +export declare interface ThreadManagerOptionsChild extends ThreadManagerOptionsBase { + childThread: true; +} + +/** @public */ +export declare interface ThreadManagerOptionsMain extends ThreadManagerOptionsBase { + beforeLoad?: (worker: WorkerLike) => any; + reuseWorker?: boolean | number | ReuseWorkerOptions; + onCreateWorker: WorkerFactory; + childThread?: false; +} + +/** @public */ +export declare class ThreadMessageHandler { + protected instance: WebAssembly.Instance | undefined; + private messagesBeforeLoad; + protected postMessage: (message: any) => void; + protected onLoad?: (data: LoadPayload) => WebAssembly.WebAssemblyInstantiatedSource | PromiseLike; + protected onError: (error: Error, type: WorkerMessageType) => void; + constructor(options?: ThreadMessageHandlerOptions); + /** @virtual */ + instantiate(data: LoadPayload): WebAssembly.WebAssemblyInstantiatedSource | PromiseLike; + /** @virtual */ + handle(e: WorkerMessageEvent>): void; + private _load; + private _start; + protected _loaded(err: Error | null, source: WebAssembly.WebAssemblyInstantiatedSource | null, payload: LoadPayload): void; + protected handleAfterLoad(e: E, f: (e: E) => void): void; +} + +/** @public */ +export declare interface ThreadMessageHandlerOptions { + onLoad?: (data: LoadPayload) => WebAssembly.WebAssemblyInstantiatedSource | PromiseLike; + onError?: (error: Error, type: WorkerMessageType) => void; + postMessage?: (message: any) => void; +} + +/** @public */ +export declare interface WASIInstance { + readonly wasiImport?: Record; + initialize(instance: object): void; + start(instance: object): number; + getImportObject?(): any; +} + +/** @public */ +export declare class WASIThreads { + PThread: ThreadManager | undefined; + private wasmMemory; + private wasmInstance; + private readonly threadSpawn; + readonly childThread: boolean; + private readonly postMessage; + readonly wasi: WASIInstance; + constructor(options: WASIThreadsOptions); + getImportObject(): { + wasi: WASIThreadsImports; + }; + setup(wasmInstance: WebAssembly.Instance, wasmModule: WebAssembly.Module, wasmMemory?: WebAssembly.Memory): void; + preloadWorkers(): Promise; + /** + * It's ok to call this method to a WASI command module. + * + * in child thread, must call this method instead of {@link WASIThreads.start} even if it's a WASI command module + * + * @returns A proxied WebAssembly instance if in child thread, other wise the original instance + */ + initialize(instance: WebAssembly.Instance, module: WebAssembly.Module, memory?: WebAssembly.Memory): WebAssembly.Instance; + /** + * Equivalent to calling {@link WASIThreads.initialize} and then calling {@link WASIInstance.start} + * ```js + * this.initialize(instance, module, memory) + * this.wasi.start(instance) + * ``` + */ + start(instance: WebAssembly.Instance, module: WebAssembly.Module, memory?: WebAssembly.Memory): StartResult; + terminateAllThreads(): void; +} + +/** @public */ +export declare interface WASIThreadsImports { + 'thread-spawn': (startArg: number, errorOrTid?: number) => number; +} + +/** @public */ +export declare type WASIThreadsOptions = MainThreadOptions | ChildThreadOptions; + +/** @public */ +export declare type WorkerFactory = (ctx: { + type: string; + name: string; +}) => WorkerLike; + +/** @public */ +export declare type WorkerLike = (Worker | Worker_2) & { + whenLoaded?: Promise; + loaded?: boolean; + __emnapi_tid?: number; +}; + +/** @public */ +export declare interface WorkerMessageEvent { + data: T; +} + +/** @public */ +export declare type WorkerMessageType = 'load' | 'start'; + +export { } + +export as namespace wasiThreads; diff --git a/dg-ui/node_modules/@tailwindcss/oxide-wasm32-wasi/node_modules/@emnapi/wasi-threads/dist/wasi-threads.esm-bundler.js b/dg-ui/node_modules/@tailwindcss/oxide-wasm32-wasi/node_modules/@emnapi/wasi-threads/dist/wasi-threads.esm-bundler.js new file mode 100644 index 0000000..0e48f56 --- /dev/null +++ b/dg-ui/node_modules/@tailwindcss/oxide-wasm32-wasi/node_modules/@emnapi/wasi-threads/dist/wasi-threads.esm-bundler.js @@ -0,0 +1,975 @@ +var _WebAssembly = typeof WebAssembly !== 'undefined' + ? WebAssembly + : typeof WXWebAssembly !== 'undefined' + ? WXWebAssembly + : undefined; +var ENVIRONMENT_IS_NODE = typeof process === 'object' && process !== null && + typeof process.versions === 'object' && process.versions !== null && + typeof process.versions.node === 'string'; +function getPostMessage(options) { + return typeof (options === null || options === void 0 ? void 0 : options.postMessage) === 'function' + ? options.postMessage + : typeof postMessage === 'function' + ? postMessage + : undefined; +} +function serizeErrorToBuffer(sab, code, error) { + var i32array = new Int32Array(sab); + Atomics.store(i32array, 0, code); + if (code > 1 && error) { + var name_1 = error.name; + var message = error.message; + var stack = error.stack; + var nameBuffer = new TextEncoder().encode(name_1); + var messageBuffer = new TextEncoder().encode(message); + var stackBuffer = new TextEncoder().encode(stack); + Atomics.store(i32array, 1, nameBuffer.length); + Atomics.store(i32array, 2, messageBuffer.length); + Atomics.store(i32array, 3, stackBuffer.length); + var buffer = new Uint8Array(sab); + buffer.set(nameBuffer, 16); + buffer.set(messageBuffer, 16 + nameBuffer.length); + buffer.set(stackBuffer, 16 + nameBuffer.length + messageBuffer.length); + } +} +function deserizeErrorFromBuffer(sab) { + var _a, _b; + var i32array = new Int32Array(sab); + var status = Atomics.load(i32array, 0); + if (status <= 1) { + return null; + } + var nameLength = Atomics.load(i32array, 1); + var messageLength = Atomics.load(i32array, 2); + var stackLength = Atomics.load(i32array, 3); + var buffer = new Uint8Array(sab); + var nameBuffer = buffer.slice(16, 16 + nameLength); + var messageBuffer = buffer.slice(16 + nameLength, 16 + nameLength + messageLength); + var stackBuffer = buffer.slice(16 + nameLength + messageLength, 16 + nameLength + messageLength + stackLength); + var name = new TextDecoder().decode(nameBuffer); + var message = new TextDecoder().decode(messageBuffer); + var stack = new TextDecoder().decode(stackBuffer); + var ErrorConstructor = (_a = globalThis[name]) !== null && _a !== void 0 ? _a : (name === 'RuntimeError' ? ((_b = _WebAssembly.RuntimeError) !== null && _b !== void 0 ? _b : Error) : Error); + var error = new ErrorConstructor(message); + Object.defineProperty(error, 'stack', { + value: stack, + writable: true, + enumerable: false, + configurable: true + }); + return error; +} +/** @public */ +function isSharedArrayBuffer(value) { + return ((typeof SharedArrayBuffer === 'function' && value instanceof SharedArrayBuffer) || + (Object.prototype.toString.call(value) === '[object SharedArrayBuffer]')); +} +/** @public */ +function isTrapError(e) { + try { + return e instanceof _WebAssembly.RuntimeError; + } + catch (_) { + return false; + } +} + +function createMessage(type, payload) { + return { + __emnapi__: { + type: type, + payload: payload + } + }; +} + +var WASI_THREADS_MAX_TID = 0x1FFFFFFF; +function checkSharedWasmMemory(wasmMemory) { + if (wasmMemory) { + if (!isSharedArrayBuffer(wasmMemory.buffer)) { + throw new Error('Multithread features require shared wasm memory. ' + + 'Try to compile with `-matomics -mbulk-memory` and use `--import-memory --shared-memory` during linking, ' + + 'then create WebAssembly.Memory with `shared: true` option'); + } + } + else { + if (typeof SharedArrayBuffer === 'undefined') { + throw new Error('Current environment does not support SharedArrayBuffer, threads are not available!'); + } + } +} +function getReuseWorker(value) { + var _a; + if (typeof value === 'boolean') { + return value ? { size: 0, strict: false } : false; + } + if (typeof value === 'number') { + if (!(value >= 0)) { + throw new RangeError('reuseWorker: size must be a non-negative integer'); + } + return { size: value, strict: false }; + } + if (!value) { + return false; + } + var size = (_a = Number(value.size)) !== null && _a !== void 0 ? _a : 0; + var strict = Boolean(value.strict); + if (!(size > 0) && strict) { + throw new RangeError('reuseWorker: size must be set to positive integer if strict is set to true'); + } + return { size: size, strict: strict }; +} +var nextWorkerID = 0; +/** @public */ +var ThreadManager = /*#__PURE__*/ (function () { + function ThreadManager(options) { + var _a; + this.unusedWorkers = []; + this.pthreads = Object.create(null); + this.wasmModule = null; + this.wasmMemory = null; + this.messageEvents = new WeakMap(); + if (!options) { + throw new TypeError('ThreadManager(): options is not provided'); + } + if ('childThread' in options) { + this._childThread = Boolean(options.childThread); + } + else { + this._childThread = false; + } + if (this._childThread) { + this._onCreateWorker = undefined; + this._reuseWorker = false; + this._beforeLoad = undefined; + } + else { + this._onCreateWorker = options.onCreateWorker; + this._reuseWorker = getReuseWorker(options.reuseWorker); + this._beforeLoad = options.beforeLoad; + } + this.printErr = (_a = options.printErr) !== null && _a !== void 0 ? _a : console.error.bind(console); + this.threadSpawn = options.threadSpawn; + } + Object.defineProperty(ThreadManager.prototype, "nextWorkerID", { + get: function () { return nextWorkerID; }, + enumerable: false, + configurable: true + }); + ThreadManager.prototype.init = function () { + if (!this._childThread) { + this.initMainThread(); + } + }; + ThreadManager.prototype.initMainThread = function () { + this.preparePool(); + }; + ThreadManager.prototype.preparePool = function () { + if (this._reuseWorker) { + if (this._reuseWorker.size) { + var pthreadPoolSize = this._reuseWorker.size; + while (pthreadPoolSize--) { + var worker = this.allocateUnusedWorker(); + if (ENVIRONMENT_IS_NODE) { + // https://github.com/nodejs/node/issues/53036 + worker.once('message', function () { }); + worker.unref(); + } + } + } + } + }; + ThreadManager.prototype.shouldPreloadWorkers = function () { + return !this._childThread && this._reuseWorker && this._reuseWorker.size > 0; + }; + ThreadManager.prototype.loadWasmModuleToAllWorkers = function () { + var _this_1 = this; + var promises = Array(this.unusedWorkers.length); + var _loop_1 = function (i) { + var worker = this_1.unusedWorkers[i]; + if (ENVIRONMENT_IS_NODE) + worker.ref(); + promises[i] = this_1.loadWasmModuleToWorker(worker).then(function (w) { + if (ENVIRONMENT_IS_NODE) + worker.unref(); + return w; + }, function (e) { + if (ENVIRONMENT_IS_NODE) + worker.unref(); + throw e; + }); + }; + var this_1 = this; + for (var i = 0; i < this.unusedWorkers.length; ++i) { + _loop_1(i); + } + return Promise.all(promises).catch(function (err) { + _this_1.terminateAllThreads(); + throw err; + }); + }; + ThreadManager.prototype.preloadWorkers = function () { + if (this.shouldPreloadWorkers()) { + return this.loadWasmModuleToAllWorkers(); + } + return Promise.resolve([]); + }; + ThreadManager.prototype.setup = function (wasmModule, wasmMemory) { + this.wasmModule = wasmModule; + this.wasmMemory = wasmMemory; + }; + ThreadManager.prototype.markId = function (worker) { + if (worker.__emnapi_tid) + return worker.__emnapi_tid; + var tid = nextWorkerID + 43; + nextWorkerID = (nextWorkerID + 1) % (WASI_THREADS_MAX_TID - 42); + this.pthreads[tid] = worker; + worker.__emnapi_tid = tid; + return tid; + }; + ThreadManager.prototype.returnWorkerToPool = function (worker) { + var tid = worker.__emnapi_tid; + if (tid !== undefined) { + delete this.pthreads[tid]; + } + this.unusedWorkers.push(worker); + delete worker.__emnapi_tid; + if (ENVIRONMENT_IS_NODE) { + worker.unref(); + } + }; + ThreadManager.prototype.loadWasmModuleToWorker = function (worker, sab) { + var _this_1 = this; + if (worker.whenLoaded) + return worker.whenLoaded; + var err = this.printErr; + var beforeLoad = this._beforeLoad; + // eslint-disable-next-line @typescript-eslint/no-this-alias + var _this = this; + worker.whenLoaded = new Promise(function (resolve, reject) { + var handleError = function (e) { + var message = 'worker sent an error!'; + if (worker.__emnapi_tid !== undefined) { + message = 'worker (tid = ' + worker.__emnapi_tid + ') sent an error!'; + } + if ('message' in e) { + err(message + ' ' + e.message); + if (e.message.indexOf('RuntimeError') !== -1 || e.message.indexOf('unreachable') !== -1) { + try { + _this.terminateAllThreads(); + } + catch (_) { } + } + } + else { + err(message); + } + reject(e); + throw e; + }; + var handleMessage = function (data) { + if (data.__emnapi__) { + var type = data.__emnapi__.type; + var payload = data.__emnapi__.payload; + if (type === 'loaded') { + worker.loaded = true; + if (ENVIRONMENT_IS_NODE && !worker.__emnapi_tid) { + worker.unref(); + } + resolve(worker); + // if (payload.err) { + // err('failed to load in child thread: ' + (payload.err.message || payload.err)) + // } + } + else if (type === 'cleanup-thread') { + if (payload.tid in _this_1.pthreads) { + _this_1.cleanThread(worker, payload.tid); + } + } + else if (type === 'spawn-thread') { + _this_1.threadSpawn(payload.startArg, payload.errorOrTid); + } + else if (type === 'terminate-all-threads') { + _this_1.terminateAllThreads(); + } + } + }; + worker.onmessage = function (e) { + handleMessage(e.data); + _this_1.fireMessageEvent(worker, e); + }; + worker.onerror = handleError; + if (ENVIRONMENT_IS_NODE) { + worker.on('message', function (data) { + var _a, _b; + (_b = (_a = worker).onmessage) === null || _b === void 0 ? void 0 : _b.call(_a, { + data: data + }); + }); + worker.on('error', function (e) { + var _a, _b; + (_b = (_a = worker).onerror) === null || _b === void 0 ? void 0 : _b.call(_a, e); + }); + worker.on('detachedExit', function () { }); + } + if (typeof beforeLoad === 'function') { + beforeLoad(worker); + } + try { + worker.postMessage(createMessage('load', { + wasmModule: _this_1.wasmModule, + wasmMemory: _this_1.wasmMemory, + sab: sab + })); + } + catch (err) { + checkSharedWasmMemory(_this_1.wasmMemory); + throw err; + } + }); + return worker.whenLoaded; + }; + ThreadManager.prototype.allocateUnusedWorker = function () { + var _onCreateWorker = this._onCreateWorker; + if (typeof _onCreateWorker !== 'function') { + throw new TypeError('`options.onCreateWorker` is not provided'); + } + var worker = _onCreateWorker({ type: 'thread', name: 'emnapi-pthread' }); + this.unusedWorkers.push(worker); + return worker; + }; + ThreadManager.prototype.getNewWorker = function (sab) { + if (this._reuseWorker) { + if (this.unusedWorkers.length === 0) { + if (this._reuseWorker.strict) { + if (!ENVIRONMENT_IS_NODE) { + var err = this.printErr; + err('Tried to spawn a new thread, but the thread pool is exhausted.\n' + + 'This might result in a deadlock unless some threads eventually exit or the code explicitly breaks out to the event loop.'); + return; + } + } + var worker_1 = this.allocateUnusedWorker(); + // eslint-disable-next-line @typescript-eslint/no-floating-promises + this.loadWasmModuleToWorker(worker_1, sab); + } + return this.unusedWorkers.pop(); + } + var worker = this.allocateUnusedWorker(); + // eslint-disable-next-line @typescript-eslint/no-floating-promises + this.loadWasmModuleToWorker(worker, sab); + return this.unusedWorkers.pop(); + }; + ThreadManager.prototype.cleanThread = function (worker, tid, force) { + if (!force && this._reuseWorker) { + this.returnWorkerToPool(worker); + } + else { + delete this.pthreads[tid]; + this.terminateWorker(worker); + delete worker.__emnapi_tid; + } + }; + ThreadManager.prototype.terminateWorker = function (worker) { + var _this_1 = this; + var _a; + var tid = worker.__emnapi_tid; + // eslint-disable-next-line @typescript-eslint/no-floating-promises + worker.terminate(); + (_a = this.messageEvents.get(worker)) === null || _a === void 0 ? void 0 : _a.clear(); + this.messageEvents.delete(worker); + worker.onmessage = function (e) { + if (e.data.__emnapi__) { + var err = _this_1.printErr; + err('received "' + e.data.__emnapi__.type + '" command from terminated worker: ' + tid); + } + }; + }; + ThreadManager.prototype.terminateAllThreads = function () { + var runningWorkers = Object.values(this.pthreads); + for (var i = 0; i < runningWorkers.length; ++i) { + this.terminateWorker(runningWorkers[i]); + } + for (var i = 0; i < this.unusedWorkers.length; ++i) { + this.terminateWorker(this.unusedWorkers[i]); + } + this.unusedWorkers = []; + this.pthreads = Object.create(null); + this.preparePool(); + }; + ThreadManager.prototype.addMessageEventListener = function (worker, onMessage) { + var listeners = this.messageEvents.get(worker); + if (!listeners) { + listeners = new Set(); + this.messageEvents.set(worker, listeners); + } + listeners.add(onMessage); + return function () { + listeners === null || listeners === void 0 ? void 0 : listeners.delete(onMessage); + }; + }; + ThreadManager.prototype.fireMessageEvent = function (worker, e) { + var listeners = this.messageEvents.get(worker); + if (!listeners) + return; + var err = this.printErr; + listeners.forEach(function (listener) { + try { + listener(e); + } + catch (e) { + err(e.stack); + } + }); + }; + return ThreadManager; +}()); + +var kIsProxy = Symbol('kIsProxy'); +/** @public */ +function createInstanceProxy(instance, memory) { + if (instance[kIsProxy]) + return instance; + // https://github.com/nodejs/help/issues/4102 + var originalExports = instance.exports; + var createHandler = function (target) { + var handlers = [ + 'apply', + 'construct', + 'defineProperty', + 'deleteProperty', + 'get', + 'getOwnPropertyDescriptor', + 'getPrototypeOf', + 'has', + 'isExtensible', + 'ownKeys', + 'preventExtensions', + 'set', + 'setPrototypeOf' + ]; + var handler = {}; + var _loop_1 = function (i) { + var name_1 = handlers[i]; + handler[name_1] = function () { + var args = Array.prototype.slice.call(arguments, 1); + args.unshift(target); + return Reflect[name_1].apply(Reflect, args); + }; + }; + for (var i = 0; i < handlers.length; i++) { + _loop_1(i); + } + return handler; + }; + var handler = createHandler(originalExports); + var _initialize = function () { }; + var _start = function () { return 0; }; + handler.get = function (_target, p, receiver) { + var _a; + if (p === 'memory') { + return (_a = (typeof memory === 'function' ? memory() : memory)) !== null && _a !== void 0 ? _a : Reflect.get(originalExports, p, receiver); + } + if (p === '_initialize') { + return p in originalExports ? _initialize : undefined; + } + if (p === '_start') { + return p in originalExports ? _start : undefined; + } + return Reflect.get(originalExports, p, receiver); + }; + handler.has = function (_target, p) { + if (p === 'memory') + return true; + return Reflect.has(originalExports, p); + }; + var exportsProxy = new Proxy(Object.create(null), handler); + return new Proxy(instance, { + get: function (target, p, receiver) { + if (p === 'exports') { + return exportsProxy; + } + if (p === kIsProxy) { + return true; + } + return Reflect.get(target, p, receiver); + } + }); +} + +var patchedWasiInstances = new WeakMap(); +var THREAD_SPAWN_RESULT_SIZE = Int32Array.BYTES_PER_ELEMENT * 2; +// Intrinsic SharedArrayBuffer.prototype.byteLength getter: it reads the +// internal slot, so it is a conclusive brand check that a spoofed own +// Symbol.toStringTag (which fools Object.prototype.toString) cannot satisfy. +var sharedArrayBufferByteLength = typeof SharedArrayBuffer === 'function' + ? Object.getOwnPropertyDescriptor(SharedArrayBuffer.prototype, 'byteLength').get + : undefined; +function isConclusivelySharedArrayBuffer(buffer) { + if (sharedArrayBufferByteLength === undefined) + return false; + try { + sharedArrayBufferByteLength.call(buffer); + return true; + } + catch (_) { + return false; + } +} +function getThreadSpawnResultView(memory, address, wasm64) { + // The result pointer arrives across the wasm ABI: an i64 (memory64) address + // is a bigint, and an upper-half i32 address is a negative Number. Normalize + // it the way malloc results are normalized elsewhere in this file. + var offset = typeof address === 'bigint' ? Number(address) : address >>> 0; + var buffer = memory.buffer; + if (offset + THREAD_SPAWN_RESULT_SIZE > buffer.byteLength && + // Only refresh shared memory. A conclusive brand check is required here: + // grow(0) detaches an *unshared* buffer (spec: even at delta 0), so a + // spoofed 'SharedArrayBuffer' tag must never be allowed to reach it. + isConclusivelySharedArrayBuffer(buffer)) { + // Another agent may have grown shared memory while this agent still sees + // the previous shorter buffer. A zero-page grow refreshes the local view + // without changing the memory size. + if (wasm64) { + memory.grow(BigInt(0)); + } + else { + memory.grow(0); + } + buffer = memory.buffer; + } + return new Int32Array(buffer, offset, 2); +} +/** @public */ +var WASIThreads = /*#__PURE__*/ (function () { + function WASIThreads(options) { + var _this_1 = this; + if (!options) { + throw new TypeError('WASIThreads(): options is not provided'); + } + if (!options.wasi) { + throw new TypeError('WASIThreads(): options.wasi is not provided'); + } + patchedWasiInstances.set(this, new WeakSet()); + var wasi = options.wasi; + patchWasiInstance(this, wasi); + this.wasi = wasi; + if ('childThread' in options) { + this.childThread = Boolean(options.childThread); + } + else { + this.childThread = false; + } + this.PThread = undefined; + if ('threadManager' in options) { + if (typeof options.threadManager === 'function') { + this.PThread = options.threadManager(); + } + else { + this.PThread = options.threadManager; + } + } + else { + if (!this.childThread) { + this.PThread = new ThreadManager(options); + this.PThread.init(); + } + } + var waitThreadStart = false; + if ('waitThreadStart' in options) { + waitThreadStart = typeof options.waitThreadStart === 'number' ? options.waitThreadStart : Boolean(options.waitThreadStart); + } + var postMessage = getPostMessage(options); + if (this.childThread && typeof postMessage !== 'function') { + throw new TypeError('options.postMessage is not a function'); + } + this.postMessage = postMessage; + var wasm64 = Boolean(options.wasm64); + var threadSpawn = function (startArg, errorOrTid) { + var _a; + var EAGAIN = 6; + var isNewABI = errorOrTid !== undefined; + try { + checkSharedWasmMemory(_this_1.wasmMemory); + } + catch (err) { + (_a = _this_1.PThread) === null || _a === void 0 ? void 0 : _a.printErr(err.stack); + if (isNewABI) { + var struct_1 = getThreadSpawnResultView(_this_1.wasmMemory, errorOrTid, wasm64); + Atomics.store(struct_1, 0, 1); + Atomics.store(struct_1, 1, EAGAIN); + Atomics.notify(struct_1, 1); + return 1; + } + else { + return -EAGAIN; + } + } + if (!isNewABI) { + var malloc = _this_1.wasmInstance.exports.malloc; + errorOrTid = wasm64 ? Number(malloc(BigInt(8))) : (malloc(8) >>> 0); + if (!errorOrTid) { + return -48; /* ENOMEM */ + } + } + var _free = _this_1.wasmInstance.exports.free; + var free = wasm64 ? function (ptr) { _free(BigInt(ptr)); } : _free; + var struct = getThreadSpawnResultView(_this_1.wasmMemory, errorOrTid, wasm64); + Atomics.store(struct, 0, 0); + Atomics.store(struct, 1, 0); + if (_this_1.childThread) { + postMessage(createMessage('spawn-thread', { + startArg: startArg, + errorOrTid: errorOrTid + })); + Atomics.wait(struct, 1, 0); + var isError = Atomics.load(struct, 0); + var result = Atomics.load(struct, 1); + if (isNewABI) { + return isError; + } + free(errorOrTid); + return isError ? -result : result; + } + var shouldWait = waitThreadStart || (waitThreadStart === 0); + var sab; + if (shouldWait) { + sab = new Int32Array(new SharedArrayBuffer(16 + 8192)); + Atomics.store(sab, 0, 0); + } + var worker; + var tid; + var PThread = _this_1.PThread; + try { + worker = PThread.getNewWorker(sab); + if (!worker) { + throw new Error('failed to get new worker'); + } + tid = PThread.markId(worker); + if (ENVIRONMENT_IS_NODE) { + worker.unref(); + } + worker.postMessage(createMessage('start', { + tid: tid, + arg: startArg, + sab: sab + })); + if (shouldWait) { + if (typeof waitThreadStart === 'number') { + var waitResult = Atomics.wait(sab, 0, 0, waitThreadStart); + if (waitResult === 'timed-out') { + throw new Error('Spawning thread timed out. Please check if the worker is created successfully and if message is handled properly in the worker.'); + } + } + else { + Atomics.wait(sab, 0, 0); + } + var r = Atomics.load(sab, 0); + if (r > 1) { + throw deserizeErrorFromBuffer(sab.buffer); + } + } + } + catch (e) { + if (worker !== undefined && tid !== undefined) { + try { + PThread.cleanThread(worker, tid, true); + } + catch (_) { } + } + Atomics.store(struct, 0, 1); + Atomics.store(struct, 1, EAGAIN); + Atomics.notify(struct, 1); + PThread === null || PThread === void 0 ? void 0 : PThread.printErr(e.stack); + if (isNewABI) { + return 1; + } + free(errorOrTid); + return -EAGAIN; + } + Atomics.store(struct, 0, 0); + Atomics.store(struct, 1, tid); + Atomics.notify(struct, 1); + if (!shouldWait) { + worker.whenLoaded.catch(function (err) { + delete worker.whenLoaded; + PThread.cleanThread(worker, tid, true); + throw err; + }); + } + if (isNewABI) { + return 0; + } + free(errorOrTid); + return tid; + }; + this.threadSpawn = threadSpawn; + if (this.PThread) { + this.PThread.threadSpawn = threadSpawn; + } + } + WASIThreads.prototype.getImportObject = function () { + return { + wasi: { + 'thread-spawn': this.threadSpawn + } + }; + }; + WASIThreads.prototype.setup = function (wasmInstance, wasmModule, wasmMemory) { + wasmMemory !== null && wasmMemory !== void 0 ? wasmMemory : (wasmMemory = wasmInstance.exports.memory); + this.wasmInstance = wasmInstance; + this.wasmMemory = wasmMemory; + if (this.PThread) { + this.PThread.setup(wasmModule, wasmMemory); + } + }; + WASIThreads.prototype.preloadWorkers = function () { + if (this.PThread) { + return this.PThread.preloadWorkers(); + } + return Promise.resolve([]); + }; + /** + * It's ok to call this method to a WASI command module. + * + * in child thread, must call this method instead of {@link WASIThreads.start} even if it's a WASI command module + * + * @returns A proxied WebAssembly instance if in child thread, other wise the original instance + */ + WASIThreads.prototype.initialize = function (instance, module, memory) { + var exports = instance.exports; + memory !== null && memory !== void 0 ? memory : (memory = exports.memory); + if (this.childThread) { + instance = createInstanceProxy(instance, memory); + } + this.setup(instance, module, memory); + var wasi = this.wasi; + if (('_start' in exports) && (typeof exports._start === 'function')) { + if (this.childThread) { + wasi.start(instance); + try { + var kStarted = getWasiSymbol(wasi, 'kStarted'); + wasi[kStarted] = false; + } + catch (_) { } + } + else { + setupInstance(wasi, instance); + } + } + else { + wasi.initialize(instance); + } + return instance; + }; + /** + * Equivalent to calling {@link WASIThreads.initialize} and then calling {@link WASIInstance.start} + * ```js + * this.initialize(instance, module, memory) + * this.wasi.start(instance) + * ``` + */ + WASIThreads.prototype.start = function (instance, module, memory) { + var exports = instance.exports; + memory !== null && memory !== void 0 ? memory : (memory = exports.memory); + if (this.childThread) { + instance = createInstanceProxy(instance, memory); + } + this.setup(instance, module, memory); + var exitCode = this.wasi.start(instance); + return { exitCode: exitCode, instance: instance }; + }; + WASIThreads.prototype.terminateAllThreads = function () { + var _a; + if (!this.childThread) { + (_a = this.PThread) === null || _a === void 0 ? void 0 : _a.terminateAllThreads(); + } + else { + this.postMessage(createMessage('terminate-all-threads', {})); + } + }; + return WASIThreads; +}()); +function patchWasiInstance(wasiThreads, wasi) { + var patched = patchedWasiInstances.get(wasiThreads); + if (patched.has(wasi)) { + return; + } + var _this = wasiThreads; + var wasiImport = wasi.wasiImport; + if (wasiImport) { + var proc_exit_1 = wasiImport.proc_exit; + wasiImport.proc_exit = function (code) { + _this.terminateAllThreads(); + return proc_exit_1.call(this, code); + }; + } + if (!_this.childThread) { + var start_1 = wasi.start; + if (typeof start_1 === 'function') { + wasi.start = function (instance) { + try { + return start_1.call(this, instance); + } + catch (err) { + if (isTrapError(err)) { + _this.terminateAllThreads(); + } + throw err; + } + }; + } + } + patched.add(wasi); +} +function getWasiSymbol(wasi, description) { + var symbols = Object.getOwnPropertySymbols(wasi); + var selectDescription = function (description) { return function (s) { + if (s.description) { + return s.description === description; + } + return s.toString() === "Symbol(".concat(description, ")"); + }; }; + if (Array.isArray(description)) { + return description.map(function (d) { return symbols.filter(selectDescription(d))[0]; }); + } + return symbols.filter(selectDescription(description))[0]; +} +function setupInstance(wasi, instance) { + var _a = getWasiSymbol(wasi, ['kInstance', 'kSetMemory']), kInstance = _a[0], kSetMemory = _a[1]; + wasi[kInstance] = instance; + wasi[kSetMemory](instance.exports.memory); +} + +/** @public */ +var ThreadMessageHandler = /*#__PURE__*/ (function () { + function ThreadMessageHandler(options) { + var postMsg = getPostMessage(options); + if (typeof postMsg !== 'function') { + throw new TypeError('options.postMessage is not a function'); + } + this.postMessage = postMsg; + this.onLoad = options === null || options === void 0 ? void 0 : options.onLoad; + this.onError = typeof (options === null || options === void 0 ? void 0 : options.onError) === 'function' ? options.onError : function (_type, err) { throw err; }; + this.instance = undefined; + // this.module = undefined + this.messagesBeforeLoad = []; + } + /** @virtual */ + ThreadMessageHandler.prototype.instantiate = function (data) { + if (typeof this.onLoad === 'function') { + return this.onLoad(data); + } + throw new Error('ThreadMessageHandler.prototype.instantiate is not implemented'); + }; + /** @virtual */ + ThreadMessageHandler.prototype.handle = function (e) { + var _this = this; + var _a; + if ((_a = e === null || e === void 0 ? void 0 : e.data) === null || _a === void 0 ? void 0 : _a.__emnapi__) { + var type = e.data.__emnapi__.type; + var payload_1 = e.data.__emnapi__.payload; + try { + if (type === 'load') { + this._load(payload_1); + } + else if (type === 'start') { + this.handleAfterLoad(e, function () { + _this._start(payload_1); + }); + } + } + catch (err) { + this.onError(err, type); + } + } + }; + ThreadMessageHandler.prototype._load = function (payload) { + var _this = this; + if (this.instance !== undefined) + return; + var source; + try { + source = this.instantiate(payload); + } + catch (err) { + this._loaded(err, null, payload); + return; + } + var then = source && 'then' in source ? source.then : undefined; + if (typeof then === 'function') { + // eslint-disable-next-line @typescript-eslint/no-floating-promises + then.call(source, function (source) { _this._loaded(null, source, payload); }, function (err) { _this._loaded(err, null, payload); }); + } + else { + this._loaded(null, source, payload); + } + }; + ThreadMessageHandler.prototype._start = function (payload) { + var wasi_thread_start = this.instance.exports.wasi_thread_start; + if (typeof wasi_thread_start !== 'function') { + var err = new TypeError('wasi_thread_start is not exported'); + notifyPthreadCreateResult(payload.sab, 2, err); + throw err; + } + var postMessage = this.postMessage; + var tid = payload.tid; + var startArg = payload.arg; + notifyPthreadCreateResult(payload.sab, 1); + try { + wasi_thread_start(tid, startArg); + } + catch (err) { + if (err !== 'unwind') { + throw err; + } + else { + return; + } + } + postMessage(createMessage('cleanup-thread', { tid: tid })); + }; + ThreadMessageHandler.prototype._loaded = function (err, source, payload) { + if (err) { + notifyPthreadCreateResult(payload.sab, 2, err); + throw err; + } + if (source == null) { + var err_1 = new TypeError('onLoad should return an object'); + notifyPthreadCreateResult(payload.sab, 2, err_1); + throw err_1; + } + var instance = source.instance; + if (!instance) { + var err_2 = new TypeError('onLoad should return an object which includes "instance"'); + notifyPthreadCreateResult(payload.sab, 2, err_2); + throw err_2; + } + this.instance = instance; + var postMessage = this.postMessage; + postMessage(createMessage('loaded', {})); + var messages = this.messagesBeforeLoad; + this.messagesBeforeLoad = []; + for (var i = 0; i < messages.length; i++) { + var data = messages[i]; + this.handle({ data: data }); + } + }; + ThreadMessageHandler.prototype.handleAfterLoad = function (e, f) { + if (this.instance !== undefined) { + f.call(this, e); + } + else { + this.messagesBeforeLoad.push(e.data); + } + }; + return ThreadMessageHandler; +}()); +function notifyPthreadCreateResult(sab, result, error) { + if (sab) { + serizeErrorToBuffer(sab.buffer, result, error); + Atomics.notify(sab, 0); + } +} + +export { ThreadManager, ThreadMessageHandler, WASIThreads, createInstanceProxy, isSharedArrayBuffer, isTrapError }; diff --git a/dg-ui/node_modules/@tailwindcss/oxide-wasm32-wasi/node_modules/@emnapi/wasi-threads/dist/wasi-threads.js b/dg-ui/node_modules/@tailwindcss/oxide-wasm32-wasi/node_modules/@emnapi/wasi-threads/dist/wasi-threads.js new file mode 100644 index 0000000..23e9e7a --- /dev/null +++ b/dg-ui/node_modules/@tailwindcss/oxide-wasm32-wasi/node_modules/@emnapi/wasi-threads/dist/wasi-threads.js @@ -0,0 +1,987 @@ +(function (global, factory) { + typeof exports === 'object' && typeof module !== 'undefined' ? factory(exports) : + typeof define === 'function' && define.amd ? define(['exports'], factory) : + (global = typeof globalThis !== 'undefined' ? globalThis : global || self, factory(global.wasiThreads = {})); +})(this, (function (exports) { + var _WebAssembly = typeof WebAssembly !== 'undefined' + ? WebAssembly + : typeof WXWebAssembly !== 'undefined' + ? WXWebAssembly + : undefined; + var ENVIRONMENT_IS_NODE = typeof process === 'object' && process !== null && + typeof process.versions === 'object' && process.versions !== null && + typeof process.versions.node === 'string'; + function getPostMessage(options) { + return typeof (options === null || options === void 0 ? void 0 : options.postMessage) === 'function' + ? options.postMessage + : typeof postMessage === 'function' + ? postMessage + : undefined; + } + function serizeErrorToBuffer(sab, code, error) { + var i32array = new Int32Array(sab); + Atomics.store(i32array, 0, code); + if (code > 1 && error) { + var name_1 = error.name; + var message = error.message; + var stack = error.stack; + var nameBuffer = new TextEncoder().encode(name_1); + var messageBuffer = new TextEncoder().encode(message); + var stackBuffer = new TextEncoder().encode(stack); + Atomics.store(i32array, 1, nameBuffer.length); + Atomics.store(i32array, 2, messageBuffer.length); + Atomics.store(i32array, 3, stackBuffer.length); + var buffer = new Uint8Array(sab); + buffer.set(nameBuffer, 16); + buffer.set(messageBuffer, 16 + nameBuffer.length); + buffer.set(stackBuffer, 16 + nameBuffer.length + messageBuffer.length); + } + } + function deserizeErrorFromBuffer(sab) { + var _a, _b; + var i32array = new Int32Array(sab); + var status = Atomics.load(i32array, 0); + if (status <= 1) { + return null; + } + var nameLength = Atomics.load(i32array, 1); + var messageLength = Atomics.load(i32array, 2); + var stackLength = Atomics.load(i32array, 3); + var buffer = new Uint8Array(sab); + var nameBuffer = buffer.slice(16, 16 + nameLength); + var messageBuffer = buffer.slice(16 + nameLength, 16 + nameLength + messageLength); + var stackBuffer = buffer.slice(16 + nameLength + messageLength, 16 + nameLength + messageLength + stackLength); + var name = new TextDecoder().decode(nameBuffer); + var message = new TextDecoder().decode(messageBuffer); + var stack = new TextDecoder().decode(stackBuffer); + var ErrorConstructor = (_a = globalThis[name]) !== null && _a !== void 0 ? _a : (name === 'RuntimeError' ? ((_b = _WebAssembly.RuntimeError) !== null && _b !== void 0 ? _b : Error) : Error); + var error = new ErrorConstructor(message); + Object.defineProperty(error, 'stack', { + value: stack, + writable: true, + enumerable: false, + configurable: true + }); + return error; + } + /** @public */ + function isSharedArrayBuffer(value) { + return ((typeof SharedArrayBuffer === 'function' && value instanceof SharedArrayBuffer) || + (Object.prototype.toString.call(value) === '[object SharedArrayBuffer]')); + } + /** @public */ + function isTrapError(e) { + try { + return e instanceof _WebAssembly.RuntimeError; + } + catch (_) { + return false; + } + } + + function createMessage(type, payload) { + return { + __emnapi__: { + type: type, + payload: payload + } + }; + } + + var WASI_THREADS_MAX_TID = 0x1FFFFFFF; + function checkSharedWasmMemory(wasmMemory) { + if (wasmMemory) { + if (!isSharedArrayBuffer(wasmMemory.buffer)) { + throw new Error('Multithread features require shared wasm memory. ' + + 'Try to compile with `-matomics -mbulk-memory` and use `--import-memory --shared-memory` during linking, ' + + 'then create WebAssembly.Memory with `shared: true` option'); + } + } + else { + if (typeof SharedArrayBuffer === 'undefined') { + throw new Error('Current environment does not support SharedArrayBuffer, threads are not available!'); + } + } + } + function getReuseWorker(value) { + var _a; + if (typeof value === 'boolean') { + return value ? { size: 0, strict: false } : false; + } + if (typeof value === 'number') { + if (!(value >= 0)) { + throw new RangeError('reuseWorker: size must be a non-negative integer'); + } + return { size: value, strict: false }; + } + if (!value) { + return false; + } + var size = (_a = Number(value.size)) !== null && _a !== void 0 ? _a : 0; + var strict = Boolean(value.strict); + if (!(size > 0) && strict) { + throw new RangeError('reuseWorker: size must be set to positive integer if strict is set to true'); + } + return { size: size, strict: strict }; + } + var nextWorkerID = 0; + /** @public */ + var ThreadManager = /*#__PURE__*/ (function () { + function ThreadManager(options) { + var _a; + this.unusedWorkers = []; + this.pthreads = Object.create(null); + this.wasmModule = null; + this.wasmMemory = null; + this.messageEvents = new WeakMap(); + if (!options) { + throw new TypeError('ThreadManager(): options is not provided'); + } + if ('childThread' in options) { + this._childThread = Boolean(options.childThread); + } + else { + this._childThread = false; + } + if (this._childThread) { + this._onCreateWorker = undefined; + this._reuseWorker = false; + this._beforeLoad = undefined; + } + else { + this._onCreateWorker = options.onCreateWorker; + this._reuseWorker = getReuseWorker(options.reuseWorker); + this._beforeLoad = options.beforeLoad; + } + this.printErr = (_a = options.printErr) !== null && _a !== void 0 ? _a : console.error.bind(console); + this.threadSpawn = options.threadSpawn; + } + Object.defineProperty(ThreadManager.prototype, "nextWorkerID", { + get: function () { return nextWorkerID; }, + enumerable: false, + configurable: true + }); + ThreadManager.prototype.init = function () { + if (!this._childThread) { + this.initMainThread(); + } + }; + ThreadManager.prototype.initMainThread = function () { + this.preparePool(); + }; + ThreadManager.prototype.preparePool = function () { + if (this._reuseWorker) { + if (this._reuseWorker.size) { + var pthreadPoolSize = this._reuseWorker.size; + while (pthreadPoolSize--) { + var worker = this.allocateUnusedWorker(); + if (ENVIRONMENT_IS_NODE) { + // https://github.com/nodejs/node/issues/53036 + worker.once('message', function () { }); + worker.unref(); + } + } + } + } + }; + ThreadManager.prototype.shouldPreloadWorkers = function () { + return !this._childThread && this._reuseWorker && this._reuseWorker.size > 0; + }; + ThreadManager.prototype.loadWasmModuleToAllWorkers = function () { + var _this_1 = this; + var promises = Array(this.unusedWorkers.length); + var _loop_1 = function (i) { + var worker = this_1.unusedWorkers[i]; + if (ENVIRONMENT_IS_NODE) + worker.ref(); + promises[i] = this_1.loadWasmModuleToWorker(worker).then(function (w) { + if (ENVIRONMENT_IS_NODE) + worker.unref(); + return w; + }, function (e) { + if (ENVIRONMENT_IS_NODE) + worker.unref(); + throw e; + }); + }; + var this_1 = this; + for (var i = 0; i < this.unusedWorkers.length; ++i) { + _loop_1(i); + } + return Promise.all(promises).catch(function (err) { + _this_1.terminateAllThreads(); + throw err; + }); + }; + ThreadManager.prototype.preloadWorkers = function () { + if (this.shouldPreloadWorkers()) { + return this.loadWasmModuleToAllWorkers(); + } + return Promise.resolve([]); + }; + ThreadManager.prototype.setup = function (wasmModule, wasmMemory) { + this.wasmModule = wasmModule; + this.wasmMemory = wasmMemory; + }; + ThreadManager.prototype.markId = function (worker) { + if (worker.__emnapi_tid) + return worker.__emnapi_tid; + var tid = nextWorkerID + 43; + nextWorkerID = (nextWorkerID + 1) % (WASI_THREADS_MAX_TID - 42); + this.pthreads[tid] = worker; + worker.__emnapi_tid = tid; + return tid; + }; + ThreadManager.prototype.returnWorkerToPool = function (worker) { + var tid = worker.__emnapi_tid; + if (tid !== undefined) { + delete this.pthreads[tid]; + } + this.unusedWorkers.push(worker); + delete worker.__emnapi_tid; + if (ENVIRONMENT_IS_NODE) { + worker.unref(); + } + }; + ThreadManager.prototype.loadWasmModuleToWorker = function (worker, sab) { + var _this_1 = this; + if (worker.whenLoaded) + return worker.whenLoaded; + var err = this.printErr; + var beforeLoad = this._beforeLoad; + // eslint-disable-next-line @typescript-eslint/no-this-alias + var _this = this; + worker.whenLoaded = new Promise(function (resolve, reject) { + var handleError = function (e) { + var message = 'worker sent an error!'; + if (worker.__emnapi_tid !== undefined) { + message = 'worker (tid = ' + worker.__emnapi_tid + ') sent an error!'; + } + if ('message' in e) { + err(message + ' ' + e.message); + if (e.message.indexOf('RuntimeError') !== -1 || e.message.indexOf('unreachable') !== -1) { + try { + _this.terminateAllThreads(); + } + catch (_) { } + } + } + else { + err(message); + } + reject(e); + throw e; + }; + var handleMessage = function (data) { + if (data.__emnapi__) { + var type = data.__emnapi__.type; + var payload = data.__emnapi__.payload; + if (type === 'loaded') { + worker.loaded = true; + if (ENVIRONMENT_IS_NODE && !worker.__emnapi_tid) { + worker.unref(); + } + resolve(worker); + // if (payload.err) { + // err('failed to load in child thread: ' + (payload.err.message || payload.err)) + // } + } + else if (type === 'cleanup-thread') { + if (payload.tid in _this_1.pthreads) { + _this_1.cleanThread(worker, payload.tid); + } + } + else if (type === 'spawn-thread') { + _this_1.threadSpawn(payload.startArg, payload.errorOrTid); + } + else if (type === 'terminate-all-threads') { + _this_1.terminateAllThreads(); + } + } + }; + worker.onmessage = function (e) { + handleMessage(e.data); + _this_1.fireMessageEvent(worker, e); + }; + worker.onerror = handleError; + if (ENVIRONMENT_IS_NODE) { + worker.on('message', function (data) { + var _a, _b; + (_b = (_a = worker).onmessage) === null || _b === void 0 ? void 0 : _b.call(_a, { + data: data + }); + }); + worker.on('error', function (e) { + var _a, _b; + (_b = (_a = worker).onerror) === null || _b === void 0 ? void 0 : _b.call(_a, e); + }); + worker.on('detachedExit', function () { }); + } + if (typeof beforeLoad === 'function') { + beforeLoad(worker); + } + try { + worker.postMessage(createMessage('load', { + wasmModule: _this_1.wasmModule, + wasmMemory: _this_1.wasmMemory, + sab: sab + })); + } + catch (err) { + checkSharedWasmMemory(_this_1.wasmMemory); + throw err; + } + }); + return worker.whenLoaded; + }; + ThreadManager.prototype.allocateUnusedWorker = function () { + var _onCreateWorker = this._onCreateWorker; + if (typeof _onCreateWorker !== 'function') { + throw new TypeError('`options.onCreateWorker` is not provided'); + } + var worker = _onCreateWorker({ type: 'thread', name: 'emnapi-pthread' }); + this.unusedWorkers.push(worker); + return worker; + }; + ThreadManager.prototype.getNewWorker = function (sab) { + if (this._reuseWorker) { + if (this.unusedWorkers.length === 0) { + if (this._reuseWorker.strict) { + if (!ENVIRONMENT_IS_NODE) { + var err = this.printErr; + err('Tried to spawn a new thread, but the thread pool is exhausted.\n' + + 'This might result in a deadlock unless some threads eventually exit or the code explicitly breaks out to the event loop.'); + return; + } + } + var worker_1 = this.allocateUnusedWorker(); + // eslint-disable-next-line @typescript-eslint/no-floating-promises + this.loadWasmModuleToWorker(worker_1, sab); + } + return this.unusedWorkers.pop(); + } + var worker = this.allocateUnusedWorker(); + // eslint-disable-next-line @typescript-eslint/no-floating-promises + this.loadWasmModuleToWorker(worker, sab); + return this.unusedWorkers.pop(); + }; + ThreadManager.prototype.cleanThread = function (worker, tid, force) { + if (!force && this._reuseWorker) { + this.returnWorkerToPool(worker); + } + else { + delete this.pthreads[tid]; + this.terminateWorker(worker); + delete worker.__emnapi_tid; + } + }; + ThreadManager.prototype.terminateWorker = function (worker) { + var _this_1 = this; + var _a; + var tid = worker.__emnapi_tid; + // eslint-disable-next-line @typescript-eslint/no-floating-promises + worker.terminate(); + (_a = this.messageEvents.get(worker)) === null || _a === void 0 ? void 0 : _a.clear(); + this.messageEvents.delete(worker); + worker.onmessage = function (e) { + if (e.data.__emnapi__) { + var err = _this_1.printErr; + err('received "' + e.data.__emnapi__.type + '" command from terminated worker: ' + tid); + } + }; + }; + ThreadManager.prototype.terminateAllThreads = function () { + var runningWorkers = Object.values(this.pthreads); + for (var i = 0; i < runningWorkers.length; ++i) { + this.terminateWorker(runningWorkers[i]); + } + for (var i = 0; i < this.unusedWorkers.length; ++i) { + this.terminateWorker(this.unusedWorkers[i]); + } + this.unusedWorkers = []; + this.pthreads = Object.create(null); + this.preparePool(); + }; + ThreadManager.prototype.addMessageEventListener = function (worker, onMessage) { + var listeners = this.messageEvents.get(worker); + if (!listeners) { + listeners = new Set(); + this.messageEvents.set(worker, listeners); + } + listeners.add(onMessage); + return function () { + listeners === null || listeners === void 0 ? void 0 : listeners.delete(onMessage); + }; + }; + ThreadManager.prototype.fireMessageEvent = function (worker, e) { + var listeners = this.messageEvents.get(worker); + if (!listeners) + return; + var err = this.printErr; + listeners.forEach(function (listener) { + try { + listener(e); + } + catch (e) { + err(e.stack); + } + }); + }; + return ThreadManager; + }()); + + var kIsProxy = Symbol('kIsProxy'); + /** @public */ + function createInstanceProxy(instance, memory) { + if (instance[kIsProxy]) + return instance; + // https://github.com/nodejs/help/issues/4102 + var originalExports = instance.exports; + var createHandler = function (target) { + var handlers = [ + 'apply', + 'construct', + 'defineProperty', + 'deleteProperty', + 'get', + 'getOwnPropertyDescriptor', + 'getPrototypeOf', + 'has', + 'isExtensible', + 'ownKeys', + 'preventExtensions', + 'set', + 'setPrototypeOf' + ]; + var handler = {}; + var _loop_1 = function (i) { + var name_1 = handlers[i]; + handler[name_1] = function () { + var args = Array.prototype.slice.call(arguments, 1); + args.unshift(target); + return Reflect[name_1].apply(Reflect, args); + }; + }; + for (var i = 0; i < handlers.length; i++) { + _loop_1(i); + } + return handler; + }; + var handler = createHandler(originalExports); + var _initialize = function () { }; + var _start = function () { return 0; }; + handler.get = function (_target, p, receiver) { + var _a; + if (p === 'memory') { + return (_a = (typeof memory === 'function' ? memory() : memory)) !== null && _a !== void 0 ? _a : Reflect.get(originalExports, p, receiver); + } + if (p === '_initialize') { + return p in originalExports ? _initialize : undefined; + } + if (p === '_start') { + return p in originalExports ? _start : undefined; + } + return Reflect.get(originalExports, p, receiver); + }; + handler.has = function (_target, p) { + if (p === 'memory') + return true; + return Reflect.has(originalExports, p); + }; + var exportsProxy = new Proxy(Object.create(null), handler); + return new Proxy(instance, { + get: function (target, p, receiver) { + if (p === 'exports') { + return exportsProxy; + } + if (p === kIsProxy) { + return true; + } + return Reflect.get(target, p, receiver); + } + }); + } + + var patchedWasiInstances = new WeakMap(); + var THREAD_SPAWN_RESULT_SIZE = Int32Array.BYTES_PER_ELEMENT * 2; + // Intrinsic SharedArrayBuffer.prototype.byteLength getter: it reads the + // internal slot, so it is a conclusive brand check that a spoofed own + // Symbol.toStringTag (which fools Object.prototype.toString) cannot satisfy. + var sharedArrayBufferByteLength = typeof SharedArrayBuffer === 'function' + ? Object.getOwnPropertyDescriptor(SharedArrayBuffer.prototype, 'byteLength').get + : undefined; + function isConclusivelySharedArrayBuffer(buffer) { + if (sharedArrayBufferByteLength === undefined) + return false; + try { + sharedArrayBufferByteLength.call(buffer); + return true; + } + catch (_) { + return false; + } + } + function getThreadSpawnResultView(memory, address, wasm64) { + // The result pointer arrives across the wasm ABI: an i64 (memory64) address + // is a bigint, and an upper-half i32 address is a negative Number. Normalize + // it the way malloc results are normalized elsewhere in this file. + var offset = typeof address === 'bigint' ? Number(address) : address >>> 0; + var buffer = memory.buffer; + if (offset + THREAD_SPAWN_RESULT_SIZE > buffer.byteLength && + // Only refresh shared memory. A conclusive brand check is required here: + // grow(0) detaches an *unshared* buffer (spec: even at delta 0), so a + // spoofed 'SharedArrayBuffer' tag must never be allowed to reach it. + isConclusivelySharedArrayBuffer(buffer)) { + // Another agent may have grown shared memory while this agent still sees + // the previous shorter buffer. A zero-page grow refreshes the local view + // without changing the memory size. + if (wasm64) { + memory.grow(BigInt(0)); + } + else { + memory.grow(0); + } + buffer = memory.buffer; + } + return new Int32Array(buffer, offset, 2); + } + /** @public */ + var WASIThreads = /*#__PURE__*/ (function () { + function WASIThreads(options) { + var _this_1 = this; + if (!options) { + throw new TypeError('WASIThreads(): options is not provided'); + } + if (!options.wasi) { + throw new TypeError('WASIThreads(): options.wasi is not provided'); + } + patchedWasiInstances.set(this, new WeakSet()); + var wasi = options.wasi; + patchWasiInstance(this, wasi); + this.wasi = wasi; + if ('childThread' in options) { + this.childThread = Boolean(options.childThread); + } + else { + this.childThread = false; + } + this.PThread = undefined; + if ('threadManager' in options) { + if (typeof options.threadManager === 'function') { + this.PThread = options.threadManager(); + } + else { + this.PThread = options.threadManager; + } + } + else { + if (!this.childThread) { + this.PThread = new ThreadManager(options); + this.PThread.init(); + } + } + var waitThreadStart = false; + if ('waitThreadStart' in options) { + waitThreadStart = typeof options.waitThreadStart === 'number' ? options.waitThreadStart : Boolean(options.waitThreadStart); + } + var postMessage = getPostMessage(options); + if (this.childThread && typeof postMessage !== 'function') { + throw new TypeError('options.postMessage is not a function'); + } + this.postMessage = postMessage; + var wasm64 = Boolean(options.wasm64); + var threadSpawn = function (startArg, errorOrTid) { + var _a; + var EAGAIN = 6; + var isNewABI = errorOrTid !== undefined; + try { + checkSharedWasmMemory(_this_1.wasmMemory); + } + catch (err) { + (_a = _this_1.PThread) === null || _a === void 0 ? void 0 : _a.printErr(err.stack); + if (isNewABI) { + var struct_1 = getThreadSpawnResultView(_this_1.wasmMemory, errorOrTid, wasm64); + Atomics.store(struct_1, 0, 1); + Atomics.store(struct_1, 1, EAGAIN); + Atomics.notify(struct_1, 1); + return 1; + } + else { + return -EAGAIN; + } + } + if (!isNewABI) { + var malloc = _this_1.wasmInstance.exports.malloc; + errorOrTid = wasm64 ? Number(malloc(BigInt(8))) : (malloc(8) >>> 0); + if (!errorOrTid) { + return -48; /* ENOMEM */ + } + } + var _free = _this_1.wasmInstance.exports.free; + var free = wasm64 ? function (ptr) { _free(BigInt(ptr)); } : _free; + var struct = getThreadSpawnResultView(_this_1.wasmMemory, errorOrTid, wasm64); + Atomics.store(struct, 0, 0); + Atomics.store(struct, 1, 0); + if (_this_1.childThread) { + postMessage(createMessage('spawn-thread', { + startArg: startArg, + errorOrTid: errorOrTid + })); + Atomics.wait(struct, 1, 0); + var isError = Atomics.load(struct, 0); + var result = Atomics.load(struct, 1); + if (isNewABI) { + return isError; + } + free(errorOrTid); + return isError ? -result : result; + } + var shouldWait = waitThreadStart || (waitThreadStart === 0); + var sab; + if (shouldWait) { + sab = new Int32Array(new SharedArrayBuffer(16 + 8192)); + Atomics.store(sab, 0, 0); + } + var worker; + var tid; + var PThread = _this_1.PThread; + try { + worker = PThread.getNewWorker(sab); + if (!worker) { + throw new Error('failed to get new worker'); + } + tid = PThread.markId(worker); + if (ENVIRONMENT_IS_NODE) { + worker.unref(); + } + worker.postMessage(createMessage('start', { + tid: tid, + arg: startArg, + sab: sab + })); + if (shouldWait) { + if (typeof waitThreadStart === 'number') { + var waitResult = Atomics.wait(sab, 0, 0, waitThreadStart); + if (waitResult === 'timed-out') { + throw new Error('Spawning thread timed out. Please check if the worker is created successfully and if message is handled properly in the worker.'); + } + } + else { + Atomics.wait(sab, 0, 0); + } + var r = Atomics.load(sab, 0); + if (r > 1) { + throw deserizeErrorFromBuffer(sab.buffer); + } + } + } + catch (e) { + if (worker !== undefined && tid !== undefined) { + try { + PThread.cleanThread(worker, tid, true); + } + catch (_) { } + } + Atomics.store(struct, 0, 1); + Atomics.store(struct, 1, EAGAIN); + Atomics.notify(struct, 1); + PThread === null || PThread === void 0 ? void 0 : PThread.printErr(e.stack); + if (isNewABI) { + return 1; + } + free(errorOrTid); + return -EAGAIN; + } + Atomics.store(struct, 0, 0); + Atomics.store(struct, 1, tid); + Atomics.notify(struct, 1); + if (!shouldWait) { + worker.whenLoaded.catch(function (err) { + delete worker.whenLoaded; + PThread.cleanThread(worker, tid, true); + throw err; + }); + } + if (isNewABI) { + return 0; + } + free(errorOrTid); + return tid; + }; + this.threadSpawn = threadSpawn; + if (this.PThread) { + this.PThread.threadSpawn = threadSpawn; + } + } + WASIThreads.prototype.getImportObject = function () { + return { + wasi: { + 'thread-spawn': this.threadSpawn + } + }; + }; + WASIThreads.prototype.setup = function (wasmInstance, wasmModule, wasmMemory) { + wasmMemory !== null && wasmMemory !== void 0 ? wasmMemory : (wasmMemory = wasmInstance.exports.memory); + this.wasmInstance = wasmInstance; + this.wasmMemory = wasmMemory; + if (this.PThread) { + this.PThread.setup(wasmModule, wasmMemory); + } + }; + WASIThreads.prototype.preloadWorkers = function () { + if (this.PThread) { + return this.PThread.preloadWorkers(); + } + return Promise.resolve([]); + }; + /** + * It's ok to call this method to a WASI command module. + * + * in child thread, must call this method instead of {@link WASIThreads.start} even if it's a WASI command module + * + * @returns A proxied WebAssembly instance if in child thread, other wise the original instance + */ + WASIThreads.prototype.initialize = function (instance, module, memory) { + var exports = instance.exports; + memory !== null && memory !== void 0 ? memory : (memory = exports.memory); + if (this.childThread) { + instance = createInstanceProxy(instance, memory); + } + this.setup(instance, module, memory); + var wasi = this.wasi; + if (('_start' in exports) && (typeof exports._start === 'function')) { + if (this.childThread) { + wasi.start(instance); + try { + var kStarted = getWasiSymbol(wasi, 'kStarted'); + wasi[kStarted] = false; + } + catch (_) { } + } + else { + setupInstance(wasi, instance); + } + } + else { + wasi.initialize(instance); + } + return instance; + }; + /** + * Equivalent to calling {@link WASIThreads.initialize} and then calling {@link WASIInstance.start} + * ```js + * this.initialize(instance, module, memory) + * this.wasi.start(instance) + * ``` + */ + WASIThreads.prototype.start = function (instance, module, memory) { + var exports = instance.exports; + memory !== null && memory !== void 0 ? memory : (memory = exports.memory); + if (this.childThread) { + instance = createInstanceProxy(instance, memory); + } + this.setup(instance, module, memory); + var exitCode = this.wasi.start(instance); + return { exitCode: exitCode, instance: instance }; + }; + WASIThreads.prototype.terminateAllThreads = function () { + var _a; + if (!this.childThread) { + (_a = this.PThread) === null || _a === void 0 ? void 0 : _a.terminateAllThreads(); + } + else { + this.postMessage(createMessage('terminate-all-threads', {})); + } + }; + return WASIThreads; + }()); + function patchWasiInstance(wasiThreads, wasi) { + var patched = patchedWasiInstances.get(wasiThreads); + if (patched.has(wasi)) { + return; + } + var _this = wasiThreads; + var wasiImport = wasi.wasiImport; + if (wasiImport) { + var proc_exit_1 = wasiImport.proc_exit; + wasiImport.proc_exit = function (code) { + _this.terminateAllThreads(); + return proc_exit_1.call(this, code); + }; + } + if (!_this.childThread) { + var start_1 = wasi.start; + if (typeof start_1 === 'function') { + wasi.start = function (instance) { + try { + return start_1.call(this, instance); + } + catch (err) { + if (isTrapError(err)) { + _this.terminateAllThreads(); + } + throw err; + } + }; + } + } + patched.add(wasi); + } + function getWasiSymbol(wasi, description) { + var symbols = Object.getOwnPropertySymbols(wasi); + var selectDescription = function (description) { return function (s) { + if (s.description) { + return s.description === description; + } + return s.toString() === "Symbol(".concat(description, ")"); + }; }; + if (Array.isArray(description)) { + return description.map(function (d) { return symbols.filter(selectDescription(d))[0]; }); + } + return symbols.filter(selectDescription(description))[0]; + } + function setupInstance(wasi, instance) { + var _a = getWasiSymbol(wasi, ['kInstance', 'kSetMemory']), kInstance = _a[0], kSetMemory = _a[1]; + wasi[kInstance] = instance; + wasi[kSetMemory](instance.exports.memory); + } + + /** @public */ + var ThreadMessageHandler = /*#__PURE__*/ (function () { + function ThreadMessageHandler(options) { + var postMsg = getPostMessage(options); + if (typeof postMsg !== 'function') { + throw new TypeError('options.postMessage is not a function'); + } + this.postMessage = postMsg; + this.onLoad = options === null || options === void 0 ? void 0 : options.onLoad; + this.onError = typeof (options === null || options === void 0 ? void 0 : options.onError) === 'function' ? options.onError : function (_type, err) { throw err; }; + this.instance = undefined; + // this.module = undefined + this.messagesBeforeLoad = []; + } + /** @virtual */ + ThreadMessageHandler.prototype.instantiate = function (data) { + if (typeof this.onLoad === 'function') { + return this.onLoad(data); + } + throw new Error('ThreadMessageHandler.prototype.instantiate is not implemented'); + }; + /** @virtual */ + ThreadMessageHandler.prototype.handle = function (e) { + var _this = this; + var _a; + if ((_a = e === null || e === void 0 ? void 0 : e.data) === null || _a === void 0 ? void 0 : _a.__emnapi__) { + var type = e.data.__emnapi__.type; + var payload_1 = e.data.__emnapi__.payload; + try { + if (type === 'load') { + this._load(payload_1); + } + else if (type === 'start') { + this.handleAfterLoad(e, function () { + _this._start(payload_1); + }); + } + } + catch (err) { + this.onError(err, type); + } + } + }; + ThreadMessageHandler.prototype._load = function (payload) { + var _this = this; + if (this.instance !== undefined) + return; + var source; + try { + source = this.instantiate(payload); + } + catch (err) { + this._loaded(err, null, payload); + return; + } + var then = source && 'then' in source ? source.then : undefined; + if (typeof then === 'function') { + // eslint-disable-next-line @typescript-eslint/no-floating-promises + then.call(source, function (source) { _this._loaded(null, source, payload); }, function (err) { _this._loaded(err, null, payload); }); + } + else { + this._loaded(null, source, payload); + } + }; + ThreadMessageHandler.prototype._start = function (payload) { + var wasi_thread_start = this.instance.exports.wasi_thread_start; + if (typeof wasi_thread_start !== 'function') { + var err = new TypeError('wasi_thread_start is not exported'); + notifyPthreadCreateResult(payload.sab, 2, err); + throw err; + } + var postMessage = this.postMessage; + var tid = payload.tid; + var startArg = payload.arg; + notifyPthreadCreateResult(payload.sab, 1); + try { + wasi_thread_start(tid, startArg); + } + catch (err) { + if (err !== 'unwind') { + throw err; + } + else { + return; + } + } + postMessage(createMessage('cleanup-thread', { tid: tid })); + }; + ThreadMessageHandler.prototype._loaded = function (err, source, payload) { + if (err) { + notifyPthreadCreateResult(payload.sab, 2, err); + throw err; + } + if (source == null) { + var err_1 = new TypeError('onLoad should return an object'); + notifyPthreadCreateResult(payload.sab, 2, err_1); + throw err_1; + } + var instance = source.instance; + if (!instance) { + var err_2 = new TypeError('onLoad should return an object which includes "instance"'); + notifyPthreadCreateResult(payload.sab, 2, err_2); + throw err_2; + } + this.instance = instance; + var postMessage = this.postMessage; + postMessage(createMessage('loaded', {})); + var messages = this.messagesBeforeLoad; + this.messagesBeforeLoad = []; + for (var i = 0; i < messages.length; i++) { + var data = messages[i]; + this.handle({ data: data }); + } + }; + ThreadMessageHandler.prototype.handleAfterLoad = function (e, f) { + if (this.instance !== undefined) { + f.call(this, e); + } + else { + this.messagesBeforeLoad.push(e.data); + } + }; + return ThreadMessageHandler; + }()); + function notifyPthreadCreateResult(sab, result, error) { + if (sab) { + serizeErrorToBuffer(sab.buffer, result, error); + Atomics.notify(sab, 0); + } + } + + exports.ThreadManager = ThreadManager; + exports.ThreadMessageHandler = ThreadMessageHandler; + exports.WASIThreads = WASIThreads; + exports.createInstanceProxy = createInstanceProxy; + exports.isSharedArrayBuffer = isSharedArrayBuffer; + exports.isTrapError = isTrapError; + +})); diff --git a/dg-ui/node_modules/@tailwindcss/oxide-wasm32-wasi/node_modules/@emnapi/wasi-threads/dist/wasi-threads.min.d.mts b/dg-ui/node_modules/@tailwindcss/oxide-wasm32-wasi/node_modules/@emnapi/wasi-threads/dist/wasi-threads.min.d.mts new file mode 100644 index 0000000..1d3951c --- /dev/null +++ b/dg-ui/node_modules/@tailwindcss/oxide-wasm32-wasi/node_modules/@emnapi/wasi-threads/dist/wasi-threads.min.d.mts @@ -0,0 +1,271 @@ +/// + +import type { Worker as Worker_2 } from 'worker_threads'; + +/** @public */ +export declare interface BaseOptions { + wasi: WASIInstance; + version?: 'preview1'; + wasm64?: boolean; +} + +/** @public */ +export declare interface ChildThreadOptions extends BaseOptions { + childThread: true; + postMessage?: (data: any) => void; +} + +/** @public */ +export declare interface CleanupThreadPayload { + tid: number; +} + +/** @public */ +export declare interface CommandInfo { + type: T; + payload: CommandPayloadMap[T]; +} + +/** @public */ +export declare interface CommandPayloadMap { + load: LoadPayload; + loaded: LoadedPayload; + start: StartPayload; + 'cleanup-thread': CleanupThreadPayload; + 'terminate-all-threads': TerminateAllThreadsPayload; + 'spawn-thread': SpawnThreadPayload; +} + +/** @public */ +export declare type CommandType = keyof CommandPayloadMap; + +/** @public */ +export declare function createInstanceProxy(instance: WebAssembly.Instance, memory?: WebAssembly.Memory | (() => WebAssembly.Memory)): WebAssembly.Instance; + +/** @public */ +export declare function isSharedArrayBuffer(value: any): value is SharedArrayBuffer; + +/** @public */ +export declare function isTrapError(e: Error): e is WebAssembly.RuntimeError; + +/** @public */ +export declare interface LoadedPayload { +} + +/** @public */ +export declare interface LoadPayload { + wasmModule: WebAssembly.Module; + wasmMemory: WebAssembly.Memory; + sab?: Int32Array; +} + +/** @public */ +export declare interface MainThreadBaseOptions extends BaseOptions { + waitThreadStart?: boolean | number; +} + +/** @public */ +export declare type MainThreadOptions = MainThreadOptionsWithThreadManager | MainThreadOptionsCreateThreadManager; + +/** @public */ +export declare interface MainThreadOptionsCreateThreadManager extends MainThreadBaseOptions, ThreadManagerOptionsMain { +} + +/** @public */ +export declare interface MainThreadOptionsWithThreadManager extends MainThreadBaseOptions { + threadManager?: ThreadManager | (() => ThreadManager); +} + +/** @public */ +export declare interface MessageEventData { + __emnapi__: CommandInfo; +} + +/** @public */ +export declare interface ReuseWorkerOptions { + /** + * @see {@link https://emscripten.org/docs/tools_reference/settings_reference.html#pthread-pool-size | PTHREAD_POOL_SIZE} + */ + size: number; + /** + * @see {@link https://emscripten.org/docs/tools_reference/settings_reference.html#pthread-pool-size-strict | PTHREAD_POOL_SIZE_STRICT} + */ + strict?: boolean; +} + +/** @public */ +export declare interface SpawnThreadPayload { + startArg: number; + errorOrTid: number; +} + +/** @public */ +export declare interface StartPayload { + tid: number; + arg: number; + sab?: Int32Array; +} + +/** @public */ +export declare interface StartResult { + exitCode: number; + instance: WebAssembly.Instance; +} + +/** @public */ +export declare interface TerminateAllThreadsPayload { +} + +/** @public */ +export declare class ThreadManager { + unusedWorkers: WorkerLike[]; + pthreads: Record; + get nextWorkerID(): number; + wasmModule: WebAssembly.Module | null; + wasmMemory: WebAssembly.Memory | null; + private readonly messageEvents; + private readonly _childThread; + private readonly _onCreateWorker; + private readonly _reuseWorker; + private readonly _beforeLoad?; + /* Excluded from this release type: printErr */ + threadSpawn?: ((startArg: number, errorOrTid?: number) => number); + constructor(options: ThreadManagerOptions); + init(): void; + initMainThread(): void; + private preparePool; + shouldPreloadWorkers(): boolean; + loadWasmModuleToAllWorkers(): Promise; + preloadWorkers(): Promise; + setup(wasmModule: WebAssembly.Module, wasmMemory: WebAssembly.Memory): void; + markId(worker: WorkerLike): number; + returnWorkerToPool(worker: WorkerLike): void; + loadWasmModuleToWorker(worker: WorkerLike, sab?: Int32Array): Promise; + allocateUnusedWorker(): WorkerLike; + getNewWorker(sab?: Int32Array): WorkerLike | undefined; + cleanThread(worker: WorkerLike, tid: number, force?: boolean): void; + terminateWorker(worker: WorkerLike): void; + terminateAllThreads(): void; + addMessageEventListener(worker: WorkerLike, onMessage: (e: WorkerMessageEvent) => void): () => void; + fireMessageEvent(worker: WorkerLike, e: WorkerMessageEvent): void; +} + +/** @public */ +export declare type ThreadManagerOptions = ThreadManagerOptionsMain | ThreadManagerOptionsChild; + +/** @public */ +export declare interface ThreadManagerOptionsBase { + printErr?: (message: string) => void; + threadSpawn?: (startArg: number, errorOrTid?: number) => number; +} + +/** @public */ +export declare interface ThreadManagerOptionsChild extends ThreadManagerOptionsBase { + childThread: true; +} + +/** @public */ +export declare interface ThreadManagerOptionsMain extends ThreadManagerOptionsBase { + beforeLoad?: (worker: WorkerLike) => any; + reuseWorker?: boolean | number | ReuseWorkerOptions; + onCreateWorker: WorkerFactory; + childThread?: false; +} + +/** @public */ +export declare class ThreadMessageHandler { + protected instance: WebAssembly.Instance | undefined; + private messagesBeforeLoad; + protected postMessage: (message: any) => void; + protected onLoad?: (data: LoadPayload) => WebAssembly.WebAssemblyInstantiatedSource | PromiseLike; + protected onError: (error: Error, type: WorkerMessageType) => void; + constructor(options?: ThreadMessageHandlerOptions); + /** @virtual */ + instantiate(data: LoadPayload): WebAssembly.WebAssemblyInstantiatedSource | PromiseLike; + /** @virtual */ + handle(e: WorkerMessageEvent>): void; + private _load; + private _start; + protected _loaded(err: Error | null, source: WebAssembly.WebAssemblyInstantiatedSource | null, payload: LoadPayload): void; + protected handleAfterLoad(e: E, f: (e: E) => void): void; +} + +/** @public */ +export declare interface ThreadMessageHandlerOptions { + onLoad?: (data: LoadPayload) => WebAssembly.WebAssemblyInstantiatedSource | PromiseLike; + onError?: (error: Error, type: WorkerMessageType) => void; + postMessage?: (message: any) => void; +} + +/** @public */ +export declare interface WASIInstance { + readonly wasiImport?: Record; + initialize(instance: object): void; + start(instance: object): number; + getImportObject?(): any; +} + +/** @public */ +export declare class WASIThreads { + PThread: ThreadManager | undefined; + private wasmMemory; + private wasmInstance; + private readonly threadSpawn; + readonly childThread: boolean; + private readonly postMessage; + readonly wasi: WASIInstance; + constructor(options: WASIThreadsOptions); + getImportObject(): { + wasi: WASIThreadsImports; + }; + setup(wasmInstance: WebAssembly.Instance, wasmModule: WebAssembly.Module, wasmMemory?: WebAssembly.Memory): void; + preloadWorkers(): Promise; + /** + * It's ok to call this method to a WASI command module. + * + * in child thread, must call this method instead of {@link WASIThreads.start} even if it's a WASI command module + * + * @returns A proxied WebAssembly instance if in child thread, other wise the original instance + */ + initialize(instance: WebAssembly.Instance, module: WebAssembly.Module, memory?: WebAssembly.Memory): WebAssembly.Instance; + /** + * Equivalent to calling {@link WASIThreads.initialize} and then calling {@link WASIInstance.start} + * ```js + * this.initialize(instance, module, memory) + * this.wasi.start(instance) + * ``` + */ + start(instance: WebAssembly.Instance, module: WebAssembly.Module, memory?: WebAssembly.Memory): StartResult; + terminateAllThreads(): void; +} + +/** @public */ +export declare interface WASIThreadsImports { + 'thread-spawn': (startArg: number, errorOrTid?: number) => number; +} + +/** @public */ +export declare type WASIThreadsOptions = MainThreadOptions | ChildThreadOptions; + +/** @public */ +export declare type WorkerFactory = (ctx: { + type: string; + name: string; +}) => WorkerLike; + +/** @public */ +export declare type WorkerLike = (Worker | Worker_2) & { + whenLoaded?: Promise; + loaded?: boolean; + __emnapi_tid?: number; +}; + +/** @public */ +export declare interface WorkerMessageEvent { + data: T; +} + +/** @public */ +export declare type WorkerMessageType = 'load' | 'start'; + +export { } diff --git a/dg-ui/node_modules/@tailwindcss/oxide-wasm32-wasi/node_modules/@emnapi/wasi-threads/dist/wasi-threads.min.js b/dg-ui/node_modules/@tailwindcss/oxide-wasm32-wasi/node_modules/@emnapi/wasi-threads/dist/wasi-threads.min.js new file mode 100644 index 0000000..9d82e84 --- /dev/null +++ b/dg-ui/node_modules/@tailwindcss/oxide-wasm32-wasi/node_modules/@emnapi/wasi-threads/dist/wasi-threads.min.js @@ -0,0 +1 @@ +!function(e,t){"object"==typeof exports&&"undefined"!=typeof module?t(exports):"function"==typeof define&&define.amd?define(["exports"],t):t((e="undefined"!=typeof globalThis?globalThis:e||self).wasiThreads={})}(this,function(e){var t="undefined"!=typeof WebAssembly?WebAssembly:"undefined"!=typeof WXWebAssembly?WXWebAssembly:void 0,r="object"==typeof process&&null!==process&&"object"==typeof process.versions&&null!==process.versions&&"string"==typeof process.versions.node;function o(e){return"function"==typeof(null==e?void 0:e.postMessage)?e.postMessage:"function"==typeof postMessage?postMessage:void 0}function n(e){return"function"==typeof SharedArrayBuffer&&e instanceof SharedArrayBuffer||"[object SharedArrayBuffer]"===Object.prototype.toString.call(e)}function i(e){try{return e instanceof t.RuntimeError}catch(e){return!1}}function a(e,t){return{__emnapi__:{type:e,payload:t}}}function s(e){if(e){if(!n(e.buffer))throw new Error("Multithread features require shared wasm memory. Try to compile with `-matomics -mbulk-memory` and use `--import-memory --shared-memory` during linking, then create WebAssembly.Memory with `shared: true` option")}else if("undefined"==typeof SharedArrayBuffer)throw new Error("Current environment does not support SharedArrayBuffer, threads are not available!")}var d=0,h=function(){function e(e){var t;if(this.unusedWorkers=[],this.pthreads=Object.create(null),this.wasmModule=null,this.wasmMemory=null,this.messageEvents=new WeakMap,!e)throw new TypeError("ThreadManager(): options is not provided");this._childThread="childThread"in e&&Boolean(e.childThread),this._childThread?(this._onCreateWorker=void 0,this._reuseWorker=!1,this._beforeLoad=void 0):(this._onCreateWorker=e.onCreateWorker,this._reuseWorker=function(e){var t;if("boolean"==typeof e)return!!e&&{size:0,strict:!1};if("number"==typeof e){if(!(e>=0))throw new RangeError("reuseWorker: size must be a non-negative integer");return{size:e,strict:!1}}if(!e)return!1;var r=null!==(t=Number(e.size))&&void 0!==t?t:0,o=Boolean(e.strict);if(!(r>0)&&o)throw new RangeError("reuseWorker: size must be set to positive integer if strict is set to true");return{size:r,strict:o}}(e.reuseWorker),this._beforeLoad=e.beforeLoad),this.printErr=null!==(t=e.printErr)&&void 0!==t?t:console.error.bind(console),this.threadSpawn=e.threadSpawn}return Object.defineProperty(e.prototype,"nextWorkerID",{get:function(){return d},enumerable:!1,configurable:!0}),e.prototype.init=function(){this._childThread||this.initMainThread()},e.prototype.initMainThread=function(){this.preparePool()},e.prototype.preparePool=function(){if(this._reuseWorker&&this._reuseWorker.size)for(var e=this._reuseWorker.size;e--;){var t=this.allocateUnusedWorker();r&&(t.once("message",function(){}),t.unref())}},e.prototype.shouldPreloadWorkers=function(){return!this._childThread&&this._reuseWorker&&this._reuseWorker.size>0},e.prototype.loadWasmModuleToAllWorkers=function(){for(var e=this,t=Array(this.unusedWorkers.length),o=function(e){var o=n.unusedWorkers[e];r&&o.ref(),t[e]=n.loadWasmModuleToWorker(o).then(function(e){return r&&o.unref(),e},function(e){throw r&&o.unref(),e})},n=this,i=0;i>>0,n=e.buffer;return o+f>n.byteLength&&function(e){if(void 0===p)return!1;try{return p.call(e),!0}catch(e){return!1}}(n)&&(r?e.grow(BigInt(0)):e.grow(0),n=e.buffer),new Int32Array(n,o,2)}var y=function(){function e(e){var n=this;if(!e)throw new TypeError("WASIThreads(): options is not provided");if(!e.wasi)throw new TypeError("WASIThreads(): options.wasi is not provided");l.set(this,new WeakSet);var d=e.wasi;!function(e,t){var r=l.get(e);if(r.has(t))return;var o=e,n=t.wasiImport;if(n){var a=n.proc_exit;n.proc_exit=function(e){return o.terminateAllThreads(),a.call(this,e)}}if(!o.childThread){var s=t.start;"function"==typeof s&&(t.start=function(e){try{return s.call(this,e)}catch(e){throw i(e)&&o.terminateAllThreads(),e}})}r.add(t)}(this,d),this.wasi=d,this.childThread="childThread"in e&&Boolean(e.childThread),this.PThread=void 0,"threadManager"in e?"function"==typeof e.threadManager?this.PThread=e.threadManager():this.PThread=e.threadManager:this.childThread||(this.PThread=new h(e),this.PThread.init());var u=!1;"waitThreadStart"in e&&(u="number"==typeof e.waitThreadStart?e.waitThreadStart:Boolean(e.waitThreadStart));var c=o(e);if(this.childThread&&"function"!=typeof c)throw new TypeError("options.postMessage is not a function");this.postMessage=c;var f=Boolean(e.wasm64),p=function(e,o){var i,d=void 0!==o;try{s(n.wasmMemory)}catch(e){if(null===(i=n.PThread)||void 0===i||i.printErr(e.stack),d){var h=m(n.wasmMemory,o,f);return Atomics.store(h,0,1),Atomics.store(h,1,6),Atomics.notify(h,1),1}return-6}if(!d){var l=n.wasmInstance.exports.malloc;if(!(o=f?Number(l(BigInt(8))):l(8)>>>0))return-48}var p=n.wasmInstance.exports.free,y=f?function(e){p(BigInt(e))}:p,v=m(n.wasmMemory,o,f);if(Atomics.store(v,0,0),Atomics.store(v,1,0),n.childThread){c(a("spawn-thread",{startArg:e,errorOrTid:o})),Atomics.wait(v,1,0);var w=Atomics.load(v,0),g=Atomics.load(v,1);return d?w:(y(o),w?-g:g)}var _,T,k,W=u||0===u;W&&(_=new Int32Array(new SharedArrayBuffer(8208)),Atomics.store(_,0,0));var b=n.PThread;try{if(!(T=b.getNewWorker(_)))throw new Error("failed to get new worker");if(k=b.markId(T),r&&T.unref(),T.postMessage(a("start",{tid:k,arg:e,sab:_})),W){if("number"==typeof u){if("timed-out"===Atomics.wait(_,0,0,u))throw new Error("Spawning thread timed out. Please check if the worker is created successfully and if message is handled properly in the worker.")}else Atomics.wait(_,0,0);if(Atomics.load(_,0)>1)throw function(e){var r,o,n=new Int32Array(e);if(Atomics.load(n,0)<=1)return null;var i=Atomics.load(n,1),a=Atomics.load(n,2),s=Atomics.load(n,3),d=new Uint8Array(e),h=d.slice(16,16+i),u=d.slice(16+i,16+i+a),c=d.slice(16+i+a,16+i+a+s),l=(new TextDecoder).decode(h),f=(new TextDecoder).decode(u),p=(new TextDecoder).decode(c),m=new(null!==(r=globalThis[l])&&void 0!==r?r:"RuntimeError"===l&&null!==(o=t.RuntimeError)&&void 0!==o?o:Error)(f);return Object.defineProperty(m,"stack",{value:p,writable:!0,enumerable:!1,configurable:!0}),m}(_.buffer)}}catch(e){if(void 0!==T&&void 0!==k)try{b.cleanThread(T,k,!0)}catch(e){}return Atomics.store(v,0,1),Atomics.store(v,1,6),Atomics.notify(v,1),null==b||b.printErr(e.stack),d?1:(y(o),-6)}return Atomics.store(v,0,0),Atomics.store(v,1,k),Atomics.notify(v,1),W||T.whenLoaded.catch(function(e){throw delete T.whenLoaded,b.cleanThread(T,k,!0),e}),d?0:(y(o),k)};this.threadSpawn=p,this.PThread&&(this.PThread.threadSpawn=p)}return e.prototype.getImportObject=function(){return{wasi:{"thread-spawn":this.threadSpawn}}},e.prototype.setup=function(e,t,r){null!=r||(r=e.exports.memory),this.wasmInstance=e,this.wasmMemory=r,this.PThread&&this.PThread.setup(t,r)},e.prototype.preloadWorkers=function(){return this.PThread?this.PThread.preloadWorkers():Promise.resolve([])},e.prototype.initialize=function(e,t,r){var o=e.exports;null!=r||(r=o.memory),this.childThread&&(e=c(e,r)),this.setup(e,t,r);var n=this.wasi;if("_start"in o&&"function"==typeof o._start)if(this.childThread){n.start(e);try{n[v(n,"kStarted")]=!1}catch(e){}}else!function(e,t){var r=v(e,["kInstance","kSetMemory"]),o=r[0],n=r[1];e[o]=t,e[n](t.exports.memory)}(n,e);else n.initialize(e);return e},e.prototype.start=function(e,t,r){var o=e.exports;return null!=r||(r=o.memory),this.childThread&&(e=c(e,r)),this.setup(e,t,r),{exitCode:this.wasi.start(e),instance:e}},e.prototype.terminateAllThreads=function(){var e;this.childThread?this.postMessage(a("terminate-all-threads",{})):null===(e=this.PThread)||void 0===e||e.terminateAllThreads()},e}();function v(e,t){var r=Object.getOwnPropertySymbols(e),o=function(e){return function(t){return t.description?t.description===e:t.toString()==="Symbol(".concat(e,")")}};return Array.isArray(t)?t.map(function(e){return r.filter(o(e))[0]}):r.filter(o(t))[0]}var w=function(){function e(e){var t=o(e);if("function"!=typeof t)throw new TypeError("options.postMessage is not a function");this.postMessage=t,this.onLoad=null==e?void 0:e.onLoad,this.onError="function"==typeof(null==e?void 0:e.onError)?e.onError:function(e,t){throw t},this.instance=void 0,this.messagesBeforeLoad=[]}return e.prototype.instantiate=function(e){if("function"==typeof this.onLoad)return this.onLoad(e);throw new Error("ThreadMessageHandler.prototype.instantiate is not implemented")},e.prototype.handle=function(e){var t,r=this;if(null===(t=null==e?void 0:e.data)||void 0===t?void 0:t.__emnapi__){var o=e.data.__emnapi__.type,n=e.data.__emnapi__.payload;try{"load"===o?this._load(n):"start"===o&&this.handleAfterLoad(e,function(){r._start(n)})}catch(e){this.onError(e,o)}}},e.prototype._load=function(e){var t=this;if(void 0===this.instance){var r;try{r=this.instantiate(e)}catch(t){return void this._loaded(t,null,e)}var o=r&&"then"in r?r.then:void 0;"function"==typeof o?o.call(r,function(r){t._loaded(null,r,e)},function(r){t._loaded(r,null,e)}):this._loaded(null,r,e)}},e.prototype._start=function(e){var t=this.instance.exports.wasi_thread_start;if("function"!=typeof t){var r=new TypeError("wasi_thread_start is not exported");throw g(e.sab,2,r),r}var o=this.postMessage,n=e.tid,i=e.arg;g(e.sab,1);try{t(n,i)}catch(r){if("unwind"!==r)throw r;return}o(a("cleanup-thread",{tid:n}))},e.prototype._loaded=function(e,t,r){if(e)throw g(r.sab,2,e),e;if(null==t){var o=new TypeError("onLoad should return an object");throw g(r.sab,2,o),o}var n=t.instance;if(!n){var i=new TypeError('onLoad should return an object which includes "instance"');throw g(r.sab,2,i),i}this.instance=n,(0,this.postMessage)(a("loaded",{}));var s=this.messagesBeforeLoad;this.messagesBeforeLoad=[];for(var d=0;d1&&r){var n=r.name,i=r.message,a=r.stack,s=(new TextEncoder).encode(n),d=(new TextEncoder).encode(i),h=(new TextEncoder).encode(a);Atomics.store(o,1,s.length),Atomics.store(o,2,d.length),Atomics.store(o,3,h.length);var u=new Uint8Array(e);u.set(s,16),u.set(d,16+s.length),u.set(h,16+s.length+d.length)}}(e.buffer,t,r),Atomics.notify(e,0))}e.ThreadManager=h,e.ThreadMessageHandler=w,e.WASIThreads=y,e.createInstanceProxy=c,e.isSharedArrayBuffer=n,e.isTrapError=i}); diff --git a/dg-ui/node_modules/@tailwindcss/oxide-wasm32-wasi/node_modules/@emnapi/wasi-threads/dist/wasi-threads.min.mjs b/dg-ui/node_modules/@tailwindcss/oxide-wasm32-wasi/node_modules/@emnapi/wasi-threads/dist/wasi-threads.min.mjs new file mode 100644 index 0000000..eb4ec41 --- /dev/null +++ b/dg-ui/node_modules/@tailwindcss/oxide-wasm32-wasi/node_modules/@emnapi/wasi-threads/dist/wasi-threads.min.mjs @@ -0,0 +1 @@ +const e="undefined"!=typeof WebAssembly?WebAssembly:"undefined"!=typeof WXWebAssembly?WXWebAssembly:void 0,t="object"==typeof process&&null!==process&&"object"==typeof process.versions&&null!==process.versions&&"string"==typeof process.versions.node;function r(e){return"function"==typeof(null==e?void 0:e.postMessage)?e.postMessage:"function"==typeof postMessage?postMessage:void 0}function o(e){return"function"==typeof SharedArrayBuffer&&e instanceof SharedArrayBuffer||"[object SharedArrayBuffer]"===Object.prototype.toString.call(e)}function s(t){try{return t instanceof e.RuntimeError}catch(e){return!1}}function n(e,t){return{__emnapi__:{type:e,payload:t}}}function i(e){if(e){if(!o(e.buffer))throw new Error("Multithread features require shared wasm memory. Try to compile with `-matomics -mbulk-memory` and use `--import-memory --shared-memory` during linking, then create WebAssembly.Memory with `shared: true` option")}else if("undefined"==typeof SharedArrayBuffer)throw new Error("Current environment does not support SharedArrayBuffer, threads are not available!")}let a=0;class h{get nextWorkerID(){return a}constructor(e){var t;if(this.unusedWorkers=[],this.pthreads=Object.create(null),this.wasmModule=null,this.wasmMemory=null,this.messageEvents=new WeakMap,!e)throw new TypeError("ThreadManager(): options is not provided");this._childThread="childThread"in e&&Boolean(e.childThread),this._childThread?(this._onCreateWorker=void 0,this._reuseWorker=!1,this._beforeLoad=void 0):(this._onCreateWorker=e.onCreateWorker,this._reuseWorker=function(e){var t;if("boolean"==typeof e)return!!e&&{size:0,strict:!1};if("number"==typeof e){if(!(e>=0))throw new RangeError("reuseWorker: size must be a non-negative integer");return{size:e,strict:!1}}if(!e)return!1;const r=null!==(t=Number(e.size))&&void 0!==t?t:0,o=Boolean(e.strict);if(!(r>0)&&o)throw new RangeError("reuseWorker: size must be set to positive integer if strict is set to true");return{size:r,strict:o}}(e.reuseWorker),this._beforeLoad=e.beforeLoad),this.printErr=null!==(t=e.printErr)&&void 0!==t?t:console.error.bind(console),this.threadSpawn=e.threadSpawn}init(){this._childThread||this.initMainThread()}initMainThread(){this.preparePool()}preparePool(){if(this._reuseWorker&&this._reuseWorker.size){let e=this._reuseWorker.size;for(;e--;){const e=this.allocateUnusedWorker();t&&(e.once("message",()=>{}),e.unref())}}}shouldPreloadWorkers(){return!this._childThread&&this._reuseWorker&&this._reuseWorker.size>0}loadWasmModuleToAllWorkers(){const e=Array(this.unusedWorkers.length);for(let r=0;r(t&&o.unref(),e),e=>{throw t&&o.unref(),e})}return Promise.all(e).catch(e=>{throw this.terminateAllThreads(),e})}preloadWorkers(){return this.shouldPreloadWorkers()?this.loadWasmModuleToAllWorkers():Promise.resolve([])}setup(e,t){this.wasmModule=e,this.wasmMemory=t}markId(e){if(e.__emnapi_tid)return e.__emnapi_tid;const t=a+43;return a=(a+1)%536870869,this.pthreads[t]=e,e.__emnapi_tid=t,t}returnWorkerToPool(e){var r=e.__emnapi_tid;void 0!==r&&delete this.pthreads[r],this.unusedWorkers.push(e),delete e.__emnapi_tid,t&&e.unref()}loadWasmModuleToWorker(e,r){if(e.whenLoaded)return e.whenLoaded;const o=this.printErr,s=this._beforeLoad,a=this;return e.whenLoaded=new Promise((h,d)=>{const l=r=>{if(r.__emnapi__){const o=r.__emnapi__.type,s=r.__emnapi__.payload;"loaded"===o?(e.loaded=!0,t&&!e.__emnapi_tid&&e.unref(),h(e)):"cleanup-thread"===o?s.tid in this.pthreads&&this.cleanThread(e,s.tid):"spawn-thread"===o?this.threadSpawn(s.startArg,s.errorOrTid):"terminate-all-threads"===o&&this.terminateAllThreads()}};e.onmessage=t=>{l(t.data),this.fireMessageEvent(e,t)},e.onerror=function(t){let r="worker sent an error!";if(void 0!==e.__emnapi_tid&&(r="worker (tid = "+e.__emnapi_tid+") sent an error!"),"message"in t){if(o(r+" "+t.message),-1!==t.message.indexOf("RuntimeError")||-1!==t.message.indexOf("unreachable"))try{a.terminateAllThreads()}catch(e){}}else o(r);throw d(t),t},t&&(e.on("message",function(t){var r,o;null===(o=(r=e).onmessage)||void 0===o||o.call(r,{data:t})}),e.on("error",function(t){var r,o;null===(o=(r=e).onerror)||void 0===o||o.call(r,t)}),e.on("detachedExit",function(){})),"function"==typeof s&&s(e);try{e.postMessage(n("load",{wasmModule:this.wasmModule,wasmMemory:this.wasmMemory,sab:r}))}catch(e){throw i(this.wasmMemory),e}}),e.whenLoaded}allocateUnusedWorker(){const e=this._onCreateWorker;if("function"!=typeof e)throw new TypeError("`options.onCreateWorker` is not provided");const t=e({type:"thread",name:"emnapi-pthread"});return this.unusedWorkers.push(t),t}getNewWorker(e){if(this._reuseWorker){if(0===this.unusedWorkers.length){if(this._reuseWorker.strict&&!t){return void(0,this.printErr)("Tried to spawn a new thread, but the thread pool is exhausted.\nThis might result in a deadlock unless some threads eventually exit or the code explicitly breaks out to the event loop.")}const r=this.allocateUnusedWorker();this.loadWasmModuleToWorker(r,e)}return this.unusedWorkers.pop()}const r=this.allocateUnusedWorker();return this.loadWasmModuleToWorker(r,e),this.unusedWorkers.pop()}cleanThread(e,t,r){!r&&this._reuseWorker?this.returnWorkerToPool(e):(delete this.pthreads[t],this.terminateWorker(e),delete e.__emnapi_tid)}terminateWorker(e){var t;const r=e.__emnapi_tid;e.terminate(),null===(t=this.messageEvents.get(e))||void 0===t||t.clear(),this.messageEvents.delete(e),e.onmessage=e=>{if(e.data.__emnapi__){(0,this.printErr)('received "'+e.data.__emnapi__.type+'" command from terminated worker: '+r)}}}terminateAllThreads(){const e=Object.values(this.pthreads);for(let t=0;t{null==r||r.delete(t)}}fireMessageEvent(e,t){const r=this.messageEvents.get(e);if(!r)return;const o=this.printErr;r.forEach(e=>{try{e(t)}catch(e){o(e.stack)}})}}const d=Symbol("kIsProxy");function l(e,t){if(e[d])return e;const r=e.exports,o=function(e){const t=["apply","construct","defineProperty","deleteProperty","get","getOwnPropertyDescriptor","getPrototypeOf","has","isExtensible","ownKeys","preventExtensions","set","setPrototypeOf"],r={};for(let o=0;o{},n=()=>0;o.get=function(e,o,i){var a;return"memory"===o?null!==(a="function"==typeof t?t():t)&&void 0!==a?a:Reflect.get(r,o,i):"_initialize"===o?o in r?s:void 0:"_start"===o?o in r?n:void 0:Reflect.get(r,o,i)},o.has=function(e,t){return"memory"===t||Reflect.has(r,t)};const i=new Proxy(Object.create(null),o);return new Proxy(e,{get:(e,t,r)=>"exports"===t?i:t===d||Reflect.get(e,t,r)})}const c=new WeakMap,u=2*Int32Array.BYTES_PER_ELEMENT,f="function"==typeof SharedArrayBuffer?Object.getOwnPropertyDescriptor(SharedArrayBuffer.prototype,"byteLength").get:void 0;function p(e,t,r){const o="bigint"==typeof t?Number(t):t>>>0;let s=e.buffer;return o+u>s.byteLength&&function(e){if(void 0===f)return!1;try{return f.call(e),!0}catch(e){return!1}}(s)&&(r?e.grow(BigInt(0)):e.grow(0),s=e.buffer),new Int32Array(s,o,2)}class m{constructor(o){if(!o)throw new TypeError("WASIThreads(): options is not provided");if(!o.wasi)throw new TypeError("WASIThreads(): options.wasi is not provided");c.set(this,new WeakSet);const a=o.wasi;!function(e,t){const r=c.get(e);if(r.has(t))return;const o=e,n=t.wasiImport;if(n){const e=n.proc_exit;n.proc_exit=function(t){return o.terminateAllThreads(),e.call(this,t)}}if(!o.childThread){const e=t.start;"function"==typeof e&&(t.start=function(t){try{return e.call(this,t)}catch(e){throw s(e)&&o.terminateAllThreads(),e}})}r.add(t)}(this,a),this.wasi=a,this.childThread="childThread"in o&&Boolean(o.childThread),this.PThread=void 0,"threadManager"in o?"function"==typeof o.threadManager?this.PThread=o.threadManager():this.PThread=o.threadManager:this.childThread||(this.PThread=new h(o),this.PThread.init());let d=!1;"waitThreadStart"in o&&(d="number"==typeof o.waitThreadStart?o.waitThreadStart:Boolean(o.waitThreadStart));const l=r(o);if(this.childThread&&"function"!=typeof l)throw new TypeError("options.postMessage is not a function");this.postMessage=l;const u=Boolean(o.wasm64),f=(r,o)=>{var s;const a=void 0!==o;try{i(this.wasmMemory)}catch(e){if(null===(s=this.PThread)||void 0===s||s.printErr(e.stack),a){const e=p(this.wasmMemory,o,u);return Atomics.store(e,0,1),Atomics.store(e,1,6),Atomics.notify(e,1),1}return-6}if(!a){const e=this.wasmInstance.exports.malloc;if(!(o=u?Number(e(BigInt(8))):e(8)>>>0))return-48}const h=this.wasmInstance.exports.free,c=u?e=>{h(BigInt(e))}:h,f=p(this.wasmMemory,o,u);if(Atomics.store(f,0,0),Atomics.store(f,1,0),this.childThread){l(n("spawn-thread",{startArg:r,errorOrTid:o})),Atomics.wait(f,1,0);const e=Atomics.load(f,0),t=Atomics.load(f,1);return a?e:(c(o),e?-t:t)}const m=d||0===d;let w,y,_;m&&(w=new Int32Array(new SharedArrayBuffer(8208)),Atomics.store(w,0,0));const g=this.PThread;try{if(y=g.getNewWorker(w),!y)throw new Error("failed to get new worker");if(_=g.markId(y),t&&y.unref(),y.postMessage(n("start",{tid:_,arg:r,sab:w})),m){if("number"==typeof d){if("timed-out"===Atomics.wait(w,0,0,d))throw new Error("Spawning thread timed out. Please check if the worker is created successfully and if message is handled properly in the worker.")}else Atomics.wait(w,0,0);if(Atomics.load(w,0)>1)throw function(t){var r,o;const s=new Int32Array(t);if(Atomics.load(s,0)<=1)return null;const n=Atomics.load(s,1),i=Atomics.load(s,2),a=Atomics.load(s,3),h=new Uint8Array(t),d=h.slice(16,16+n),l=h.slice(16+n,16+n+i),c=h.slice(16+n+i,16+n+i+a),u=(new TextDecoder).decode(d),f=(new TextDecoder).decode(l),p=(new TextDecoder).decode(c),m=new(null!==(r=globalThis[u])&&void 0!==r?r:"RuntimeError"===u&&null!==(o=e.RuntimeError)&&void 0!==o?o:Error)(f);return Object.defineProperty(m,"stack",{value:p,writable:!0,enumerable:!1,configurable:!0}),m}(w.buffer)}}catch(e){if(void 0!==y&&void 0!==_)try{g.cleanThread(y,_,!0)}catch(e){}return Atomics.store(f,0,1),Atomics.store(f,1,6),Atomics.notify(f,1),null==g||g.printErr(e.stack),a?1:(c(o),-6)}return Atomics.store(f,0,0),Atomics.store(f,1,_),Atomics.notify(f,1),m||y.whenLoaded.catch(e=>{throw delete y.whenLoaded,g.cleanThread(y,_,!0),e}),a?0:(c(o),_)};this.threadSpawn=f,this.PThread&&(this.PThread.threadSpawn=f)}getImportObject(){return{wasi:{"thread-spawn":this.threadSpawn}}}setup(e,t,r){null!=r||(r=e.exports.memory),this.wasmInstance=e,this.wasmMemory=r,this.PThread&&this.PThread.setup(t,r)}preloadWorkers(){return this.PThread?this.PThread.preloadWorkers():Promise.resolve([])}initialize(e,t,r){const o=e.exports;null!=r||(r=o.memory),this.childThread&&(e=l(e,r)),this.setup(e,t,r);const s=this.wasi;if("_start"in o&&"function"==typeof o._start)if(this.childThread){s.start(e);try{s[w(s,"kStarted")]=!1}catch(e){}}else!function(e,t){const[r,o]=w(e,["kInstance","kSetMemory"]);e[r]=t,e[o](t.exports.memory)}(s,e);else s.initialize(e);return e}start(e,t,r){const o=e.exports;null!=r||(r=o.memory),this.childThread&&(e=l(e,r)),this.setup(e,t,r);return{exitCode:this.wasi.start(e),instance:e}}terminateAllThreads(){var e;this.childThread?this.postMessage(n("terminate-all-threads",{})):null===(e=this.PThread)||void 0===e||e.terminateAllThreads()}}function w(e,t){const r=Object.getOwnPropertySymbols(e),o=e=>t=>t.description?t.description===e:t.toString()===`Symbol(${e})`;return Array.isArray(t)?t.map(e=>r.filter(o(e))[0]):r.filter(o(t))[0]}class y{constructor(e){const t=r(e);if("function"!=typeof t)throw new TypeError("options.postMessage is not a function");this.postMessage=t,this.onLoad=null==e?void 0:e.onLoad,this.onError="function"==typeof(null==e?void 0:e.onError)?e.onError:(e,t)=>{throw t},this.instance=void 0,this.messagesBeforeLoad=[]}instantiate(e){if("function"==typeof this.onLoad)return this.onLoad(e);throw new Error("ThreadMessageHandler.prototype.instantiate is not implemented")}handle(e){var t;if(null===(t=null==e?void 0:e.data)||void 0===t?void 0:t.__emnapi__){const t=e.data.__emnapi__.type,r=e.data.__emnapi__.payload;try{"load"===t?this._load(r):"start"===t&&this.handleAfterLoad(e,()=>{this._start(r)})}catch(e){this.onError(e,t)}}}_load(e){if(void 0!==this.instance)return;let t;try{t=this.instantiate(e)}catch(t){return void this._loaded(t,null,e)}const r=t&&"then"in t?t.then:void 0;"function"==typeof r?r.call(t,t=>{this._loaded(null,t,e)},t=>{this._loaded(t,null,e)}):this._loaded(null,t,e)}_start(e){const t=this.instance.exports.wasi_thread_start;if("function"!=typeof t){const t=new TypeError("wasi_thread_start is not exported");throw _(e.sab,2,t),t}const r=this.postMessage,o=e.tid,s=e.arg;_(e.sab,1);try{t(o,s)}catch(e){if("unwind"!==e)throw e;return}r(n("cleanup-thread",{tid:o}))}_loaded(e,t,r){if(e)throw _(r.sab,2,e),e;if(null==t){const e=new TypeError("onLoad should return an object");throw _(r.sab,2,e),e}const o=t.instance;if(!o){const e=new TypeError('onLoad should return an object which includes "instance"');throw _(r.sab,2,e),e}this.instance=o;(0,this.postMessage)(n("loaded",{}));const s=this.messagesBeforeLoad;this.messagesBeforeLoad=[];for(let e=0;e1&&r){const t=r.name,s=r.message,n=r.stack,i=(new TextEncoder).encode(t),a=(new TextEncoder).encode(s),h=(new TextEncoder).encode(n);Atomics.store(o,1,i.length),Atomics.store(o,2,a.length),Atomics.store(o,3,h.length);const d=new Uint8Array(e);d.set(i,16),d.set(a,16+i.length),d.set(h,16+i.length+a.length)}}(e.buffer,t,r),Atomics.notify(e,0))}export{h as ThreadManager,y as ThreadMessageHandler,m as WASIThreads,l as createInstanceProxy,o as isSharedArrayBuffer,s as isTrapError}; diff --git a/dg-ui/node_modules/@tailwindcss/oxide-wasm32-wasi/node_modules/@emnapi/wasi-threads/dist/wasi-threads.mjs b/dg-ui/node_modules/@tailwindcss/oxide-wasm32-wasi/node_modules/@emnapi/wasi-threads/dist/wasi-threads.mjs new file mode 100644 index 0000000..a962a55 --- /dev/null +++ b/dg-ui/node_modules/@tailwindcss/oxide-wasm32-wasi/node_modules/@emnapi/wasi-threads/dist/wasi-threads.mjs @@ -0,0 +1,910 @@ +const _WebAssembly = typeof WebAssembly !== 'undefined' + ? WebAssembly + : typeof WXWebAssembly !== 'undefined' + ? WXWebAssembly + : undefined; +const ENVIRONMENT_IS_NODE = typeof process === 'object' && process !== null && + typeof process.versions === 'object' && process.versions !== null && + typeof process.versions.node === 'string'; +function getPostMessage(options) { + return typeof (options === null || options === void 0 ? void 0 : options.postMessage) === 'function' + ? options.postMessage + : typeof postMessage === 'function' + ? postMessage + : undefined; +} +function serizeErrorToBuffer(sab, code, error) { + const i32array = new Int32Array(sab); + Atomics.store(i32array, 0, code); + if (code > 1 && error) { + const name = error.name; + const message = error.message; + const stack = error.stack; + const nameBuffer = new TextEncoder().encode(name); + const messageBuffer = new TextEncoder().encode(message); + const stackBuffer = new TextEncoder().encode(stack); + Atomics.store(i32array, 1, nameBuffer.length); + Atomics.store(i32array, 2, messageBuffer.length); + Atomics.store(i32array, 3, stackBuffer.length); + const buffer = new Uint8Array(sab); + buffer.set(nameBuffer, 16); + buffer.set(messageBuffer, 16 + nameBuffer.length); + buffer.set(stackBuffer, 16 + nameBuffer.length + messageBuffer.length); + } +} +function deserizeErrorFromBuffer(sab) { + var _a, _b; + const i32array = new Int32Array(sab); + const status = Atomics.load(i32array, 0); + if (status <= 1) { + return null; + } + const nameLength = Atomics.load(i32array, 1); + const messageLength = Atomics.load(i32array, 2); + const stackLength = Atomics.load(i32array, 3); + const buffer = new Uint8Array(sab); + const nameBuffer = buffer.slice(16, 16 + nameLength); + const messageBuffer = buffer.slice(16 + nameLength, 16 + nameLength + messageLength); + const stackBuffer = buffer.slice(16 + nameLength + messageLength, 16 + nameLength + messageLength + stackLength); + const name = new TextDecoder().decode(nameBuffer); + const message = new TextDecoder().decode(messageBuffer); + const stack = new TextDecoder().decode(stackBuffer); + const ErrorConstructor = (_a = globalThis[name]) !== null && _a !== void 0 ? _a : (name === 'RuntimeError' ? ((_b = _WebAssembly.RuntimeError) !== null && _b !== void 0 ? _b : Error) : Error); + const error = new ErrorConstructor(message); + Object.defineProperty(error, 'stack', { + value: stack, + writable: true, + enumerable: false, + configurable: true + }); + return error; +} +function isSharedArrayBuffer(value) { + return ((typeof SharedArrayBuffer === 'function' && value instanceof SharedArrayBuffer) || + (Object.prototype.toString.call(value) === '[object SharedArrayBuffer]')); +} +function isTrapError(e) { + try { + return e instanceof _WebAssembly.RuntimeError; + } + catch (_) { + return false; + } +} + +function createMessage(type, payload) { + return { + __emnapi__: { + type, + payload + } + }; +} + +const WASI_THREADS_MAX_TID = 0x1FFFFFFF; +function checkSharedWasmMemory(wasmMemory) { + if (wasmMemory) { + if (!isSharedArrayBuffer(wasmMemory.buffer)) { + throw new Error('Multithread features require shared wasm memory. ' + + 'Try to compile with `-matomics -mbulk-memory` and use `--import-memory --shared-memory` during linking, ' + + 'then create WebAssembly.Memory with `shared: true` option'); + } + } + else { + if (typeof SharedArrayBuffer === 'undefined') { + throw new Error('Current environment does not support SharedArrayBuffer, threads are not available!'); + } + } +} +function getReuseWorker(value) { + var _a; + if (typeof value === 'boolean') { + return value ? { size: 0, strict: false } : false; + } + if (typeof value === 'number') { + if (!(value >= 0)) { + throw new RangeError('reuseWorker: size must be a non-negative integer'); + } + return { size: value, strict: false }; + } + if (!value) { + return false; + } + const size = (_a = Number(value.size)) !== null && _a !== void 0 ? _a : 0; + const strict = Boolean(value.strict); + if (!(size > 0) && strict) { + throw new RangeError('reuseWorker: size must be set to positive integer if strict is set to true'); + } + return { size, strict }; +} +let nextWorkerID = 0; +class ThreadManager { + get nextWorkerID() { return nextWorkerID; } + constructor(options) { + var _a; + this.unusedWorkers = []; + this.pthreads = Object.create(null); + this.wasmModule = null; + this.wasmMemory = null; + this.messageEvents = new WeakMap(); + if (!options) { + throw new TypeError('ThreadManager(): options is not provided'); + } + if ('childThread' in options) { + this._childThread = Boolean(options.childThread); + } + else { + this._childThread = false; + } + if (this._childThread) { + this._onCreateWorker = undefined; + this._reuseWorker = false; + this._beforeLoad = undefined; + } + else { + this._onCreateWorker = options.onCreateWorker; + this._reuseWorker = getReuseWorker(options.reuseWorker); + this._beforeLoad = options.beforeLoad; + } + this.printErr = (_a = options.printErr) !== null && _a !== void 0 ? _a : console.error.bind(console); + this.threadSpawn = options.threadSpawn; + } + init() { + if (!this._childThread) { + this.initMainThread(); + } + } + initMainThread() { + this.preparePool(); + } + preparePool() { + if (this._reuseWorker) { + if (this._reuseWorker.size) { + let pthreadPoolSize = this._reuseWorker.size; + while (pthreadPoolSize--) { + const worker = this.allocateUnusedWorker(); + if (ENVIRONMENT_IS_NODE) { + worker.once('message', () => { }); + worker.unref(); + } + } + } + } + } + shouldPreloadWorkers() { + return !this._childThread && this._reuseWorker && this._reuseWorker.size > 0; + } + loadWasmModuleToAllWorkers() { + const promises = Array(this.unusedWorkers.length); + for (let i = 0; i < this.unusedWorkers.length; ++i) { + const worker = this.unusedWorkers[i]; + if (ENVIRONMENT_IS_NODE) + worker.ref(); + promises[i] = this.loadWasmModuleToWorker(worker).then((w) => { + if (ENVIRONMENT_IS_NODE) + worker.unref(); + return w; + }, (e) => { + if (ENVIRONMENT_IS_NODE) + worker.unref(); + throw e; + }); + } + return Promise.all(promises).catch((err) => { + this.terminateAllThreads(); + throw err; + }); + } + preloadWorkers() { + if (this.shouldPreloadWorkers()) { + return this.loadWasmModuleToAllWorkers(); + } + return Promise.resolve([]); + } + setup(wasmModule, wasmMemory) { + this.wasmModule = wasmModule; + this.wasmMemory = wasmMemory; + } + markId(worker) { + if (worker.__emnapi_tid) + return worker.__emnapi_tid; + const tid = nextWorkerID + 43; + nextWorkerID = (nextWorkerID + 1) % (WASI_THREADS_MAX_TID - 42); + this.pthreads[tid] = worker; + worker.__emnapi_tid = tid; + return tid; + } + returnWorkerToPool(worker) { + var tid = worker.__emnapi_tid; + if (tid !== undefined) { + delete this.pthreads[tid]; + } + this.unusedWorkers.push(worker); + delete worker.__emnapi_tid; + if (ENVIRONMENT_IS_NODE) { + worker.unref(); + } + } + loadWasmModuleToWorker(worker, sab) { + if (worker.whenLoaded) + return worker.whenLoaded; + const err = this.printErr; + const beforeLoad = this._beforeLoad; + const _this = this; + worker.whenLoaded = new Promise((resolve, reject) => { + const handleError = function (e) { + let message = 'worker sent an error!'; + if (worker.__emnapi_tid !== undefined) { + message = 'worker (tid = ' + worker.__emnapi_tid + ') sent an error!'; + } + if ('message' in e) { + err(message + ' ' + e.message); + if (e.message.indexOf('RuntimeError') !== -1 || e.message.indexOf('unreachable') !== -1) { + try { + _this.terminateAllThreads(); + } + catch (_) { } + } + } + else { + err(message); + } + reject(e); + throw e; + }; + const handleMessage = (data) => { + if (data.__emnapi__) { + const type = data.__emnapi__.type; + const payload = data.__emnapi__.payload; + if (type === 'loaded') { + worker.loaded = true; + if (ENVIRONMENT_IS_NODE && !worker.__emnapi_tid) { + worker.unref(); + } + resolve(worker); + } + else if (type === 'cleanup-thread') { + if (payload.tid in this.pthreads) { + this.cleanThread(worker, payload.tid); + } + } + else if (type === 'spawn-thread') { + this.threadSpawn(payload.startArg, payload.errorOrTid); + } + else if (type === 'terminate-all-threads') { + this.terminateAllThreads(); + } + } + }; + worker.onmessage = (e) => { + handleMessage(e.data); + this.fireMessageEvent(worker, e); + }; + worker.onerror = handleError; + if (ENVIRONMENT_IS_NODE) { + worker.on('message', function (data) { + var _a, _b; + (_b = (_a = worker).onmessage) === null || _b === void 0 ? void 0 : _b.call(_a, { + data + }); + }); + worker.on('error', function (e) { + var _a, _b; + (_b = (_a = worker).onerror) === null || _b === void 0 ? void 0 : _b.call(_a, e); + }); + worker.on('detachedExit', function () { }); + } + if (typeof beforeLoad === 'function') { + beforeLoad(worker); + } + try { + worker.postMessage(createMessage('load', { + wasmModule: this.wasmModule, + wasmMemory: this.wasmMemory, + sab + })); + } + catch (err) { + checkSharedWasmMemory(this.wasmMemory); + throw err; + } + }); + return worker.whenLoaded; + } + allocateUnusedWorker() { + const _onCreateWorker = this._onCreateWorker; + if (typeof _onCreateWorker !== 'function') { + throw new TypeError('`options.onCreateWorker` is not provided'); + } + const worker = _onCreateWorker({ type: 'thread', name: 'emnapi-pthread' }); + this.unusedWorkers.push(worker); + return worker; + } + getNewWorker(sab) { + if (this._reuseWorker) { + if (this.unusedWorkers.length === 0) { + if (this._reuseWorker.strict) { + if (!ENVIRONMENT_IS_NODE) { + const err = this.printErr; + err('Tried to spawn a new thread, but the thread pool is exhausted.\n' + + 'This might result in a deadlock unless some threads eventually exit or the code explicitly breaks out to the event loop.'); + return; + } + } + const worker = this.allocateUnusedWorker(); + this.loadWasmModuleToWorker(worker, sab); + } + return this.unusedWorkers.pop(); + } + const worker = this.allocateUnusedWorker(); + this.loadWasmModuleToWorker(worker, sab); + return this.unusedWorkers.pop(); + } + cleanThread(worker, tid, force) { + if (!force && this._reuseWorker) { + this.returnWorkerToPool(worker); + } + else { + delete this.pthreads[tid]; + this.terminateWorker(worker); + delete worker.__emnapi_tid; + } + } + terminateWorker(worker) { + var _a; + const tid = worker.__emnapi_tid; + worker.terminate(); + (_a = this.messageEvents.get(worker)) === null || _a === void 0 ? void 0 : _a.clear(); + this.messageEvents.delete(worker); + worker.onmessage = (e) => { + if (e.data.__emnapi__) { + const err = this.printErr; + err('received "' + e.data.__emnapi__.type + '" command from terminated worker: ' + tid); + } + }; + } + terminateAllThreads() { + const runningWorkers = Object.values(this.pthreads); + for (let i = 0; i < runningWorkers.length; ++i) { + this.terminateWorker(runningWorkers[i]); + } + for (let i = 0; i < this.unusedWorkers.length; ++i) { + this.terminateWorker(this.unusedWorkers[i]); + } + this.unusedWorkers = []; + this.pthreads = Object.create(null); + this.preparePool(); + } + addMessageEventListener(worker, onMessage) { + let listeners = this.messageEvents.get(worker); + if (!listeners) { + listeners = new Set(); + this.messageEvents.set(worker, listeners); + } + listeners.add(onMessage); + return () => { + listeners === null || listeners === void 0 ? void 0 : listeners.delete(onMessage); + }; + } + fireMessageEvent(worker, e) { + const listeners = this.messageEvents.get(worker); + if (!listeners) + return; + const err = this.printErr; + listeners.forEach((listener) => { + try { + listener(e); + } + catch (e) { + err(e.stack); + } + }); + } +} + +const kIsProxy = Symbol('kIsProxy'); +function createInstanceProxy(instance, memory) { + if (instance[kIsProxy]) + return instance; + const originalExports = instance.exports; + const createHandler = function (target) { + const handlers = [ + 'apply', + 'construct', + 'defineProperty', + 'deleteProperty', + 'get', + 'getOwnPropertyDescriptor', + 'getPrototypeOf', + 'has', + 'isExtensible', + 'ownKeys', + 'preventExtensions', + 'set', + 'setPrototypeOf' + ]; + const handler = {}; + for (let i = 0; i < handlers.length; i++) { + const name = handlers[i]; + handler[name] = function () { + const args = Array.prototype.slice.call(arguments, 1); + args.unshift(target); + return Reflect[name].apply(Reflect, args); + }; + } + return handler; + }; + const handler = createHandler(originalExports); + const _initialize = () => { }; + const _start = () => 0; + handler.get = function (_target, p, receiver) { + var _a; + if (p === 'memory') { + return (_a = (typeof memory === 'function' ? memory() : memory)) !== null && _a !== void 0 ? _a : Reflect.get(originalExports, p, receiver); + } + if (p === '_initialize') { + return p in originalExports ? _initialize : undefined; + } + if (p === '_start') { + return p in originalExports ? _start : undefined; + } + return Reflect.get(originalExports, p, receiver); + }; + handler.has = function (_target, p) { + if (p === 'memory') + return true; + return Reflect.has(originalExports, p); + }; + const exportsProxy = new Proxy(Object.create(null), handler); + return new Proxy(instance, { + get(target, p, receiver) { + if (p === 'exports') { + return exportsProxy; + } + if (p === kIsProxy) { + return true; + } + return Reflect.get(target, p, receiver); + } + }); +} + +const patchedWasiInstances = new WeakMap(); +const THREAD_SPAWN_RESULT_SIZE = Int32Array.BYTES_PER_ELEMENT * 2; +const sharedArrayBufferByteLength = typeof SharedArrayBuffer === 'function' + ? Object.getOwnPropertyDescriptor(SharedArrayBuffer.prototype, 'byteLength').get + : undefined; +function isConclusivelySharedArrayBuffer(buffer) { + if (sharedArrayBufferByteLength === undefined) + return false; + try { + sharedArrayBufferByteLength.call(buffer); + return true; + } + catch (_) { + return false; + } +} +function getThreadSpawnResultView(memory, address, wasm64) { + const offset = typeof address === 'bigint' ? Number(address) : address >>> 0; + let buffer = memory.buffer; + if (offset + THREAD_SPAWN_RESULT_SIZE > buffer.byteLength && + isConclusivelySharedArrayBuffer(buffer)) { + if (wasm64) { + memory.grow(BigInt(0)); + } + else { + memory.grow(0); + } + buffer = memory.buffer; + } + return new Int32Array(buffer, offset, 2); +} +class WASIThreads { + constructor(options) { + if (!options) { + throw new TypeError('WASIThreads(): options is not provided'); + } + if (!options.wasi) { + throw new TypeError('WASIThreads(): options.wasi is not provided'); + } + patchedWasiInstances.set(this, new WeakSet()); + const wasi = options.wasi; + patchWasiInstance(this, wasi); + this.wasi = wasi; + if ('childThread' in options) { + this.childThread = Boolean(options.childThread); + } + else { + this.childThread = false; + } + this.PThread = undefined; + if ('threadManager' in options) { + if (typeof options.threadManager === 'function') { + this.PThread = options.threadManager(); + } + else { + this.PThread = options.threadManager; + } + } + else { + if (!this.childThread) { + this.PThread = new ThreadManager(options); + this.PThread.init(); + } + } + let waitThreadStart = false; + if ('waitThreadStart' in options) { + waitThreadStart = typeof options.waitThreadStart === 'number' ? options.waitThreadStart : Boolean(options.waitThreadStart); + } + const postMessage = getPostMessage(options); + if (this.childThread && typeof postMessage !== 'function') { + throw new TypeError('options.postMessage is not a function'); + } + this.postMessage = postMessage; + const wasm64 = Boolean(options.wasm64); + const threadSpawn = (startArg, errorOrTid) => { + var _a; + const EAGAIN = 6; + const isNewABI = errorOrTid !== undefined; + try { + checkSharedWasmMemory(this.wasmMemory); + } + catch (err) { + (_a = this.PThread) === null || _a === void 0 ? void 0 : _a.printErr(err.stack); + if (isNewABI) { + const struct = getThreadSpawnResultView(this.wasmMemory, errorOrTid, wasm64); + Atomics.store(struct, 0, 1); + Atomics.store(struct, 1, EAGAIN); + Atomics.notify(struct, 1); + return 1; + } + else { + return -EAGAIN; + } + } + if (!isNewABI) { + const malloc = this.wasmInstance.exports.malloc; + errorOrTid = wasm64 ? Number(malloc(BigInt(8))) : (malloc(8) >>> 0); + if (!errorOrTid) { + return -48; + } + } + const _free = this.wasmInstance.exports.free; + const free = wasm64 ? (ptr) => { _free(BigInt(ptr)); } : _free; + const struct = getThreadSpawnResultView(this.wasmMemory, errorOrTid, wasm64); + Atomics.store(struct, 0, 0); + Atomics.store(struct, 1, 0); + if (this.childThread) { + postMessage(createMessage('spawn-thread', { + startArg, + errorOrTid: errorOrTid + })); + Atomics.wait(struct, 1, 0); + const isError = Atomics.load(struct, 0); + const result = Atomics.load(struct, 1); + if (isNewABI) { + return isError; + } + free(errorOrTid); + return isError ? -result : result; + } + const shouldWait = waitThreadStart || (waitThreadStart === 0); + let sab; + if (shouldWait) { + sab = new Int32Array(new SharedArrayBuffer(16 + 8192)); + Atomics.store(sab, 0, 0); + } + let worker; + let tid; + const PThread = this.PThread; + try { + worker = PThread.getNewWorker(sab); + if (!worker) { + throw new Error('failed to get new worker'); + } + tid = PThread.markId(worker); + if (ENVIRONMENT_IS_NODE) { + worker.unref(); + } + worker.postMessage(createMessage('start', { + tid, + arg: startArg, + sab + })); + if (shouldWait) { + if (typeof waitThreadStart === 'number') { + const waitResult = Atomics.wait(sab, 0, 0, waitThreadStart); + if (waitResult === 'timed-out') { + throw new Error('Spawning thread timed out. Please check if the worker is created successfully and if message is handled properly in the worker.'); + } + } + else { + Atomics.wait(sab, 0, 0); + } + const r = Atomics.load(sab, 0); + if (r > 1) { + throw deserizeErrorFromBuffer(sab.buffer); + } + } + } + catch (e) { + if (worker !== undefined && tid !== undefined) { + try { + PThread.cleanThread(worker, tid, true); + } + catch (_) { } + } + Atomics.store(struct, 0, 1); + Atomics.store(struct, 1, EAGAIN); + Atomics.notify(struct, 1); + PThread === null || PThread === void 0 ? void 0 : PThread.printErr(e.stack); + if (isNewABI) { + return 1; + } + free(errorOrTid); + return -EAGAIN; + } + Atomics.store(struct, 0, 0); + Atomics.store(struct, 1, tid); + Atomics.notify(struct, 1); + if (!shouldWait) { + worker.whenLoaded.catch((err) => { + delete worker.whenLoaded; + PThread.cleanThread(worker, tid, true); + throw err; + }); + } + if (isNewABI) { + return 0; + } + free(errorOrTid); + return tid; + }; + this.threadSpawn = threadSpawn; + if (this.PThread) { + this.PThread.threadSpawn = threadSpawn; + } + } + getImportObject() { + return { + wasi: { + 'thread-spawn': this.threadSpawn + } + }; + } + setup(wasmInstance, wasmModule, wasmMemory) { + wasmMemory !== null && wasmMemory !== void 0 ? wasmMemory : (wasmMemory = wasmInstance.exports.memory); + this.wasmInstance = wasmInstance; + this.wasmMemory = wasmMemory; + if (this.PThread) { + this.PThread.setup(wasmModule, wasmMemory); + } + } + preloadWorkers() { + if (this.PThread) { + return this.PThread.preloadWorkers(); + } + return Promise.resolve([]); + } + initialize(instance, module, memory) { + const exports = instance.exports; + memory !== null && memory !== void 0 ? memory : (memory = exports.memory); + if (this.childThread) { + instance = createInstanceProxy(instance, memory); + } + this.setup(instance, module, memory); + const wasi = this.wasi; + if (('_start' in exports) && (typeof exports._start === 'function')) { + if (this.childThread) { + wasi.start(instance); + try { + const kStarted = getWasiSymbol(wasi, 'kStarted'); + wasi[kStarted] = false; + } + catch (_) { } + } + else { + setupInstance(wasi, instance); + } + } + else { + wasi.initialize(instance); + } + return instance; + } + start(instance, module, memory) { + const exports = instance.exports; + memory !== null && memory !== void 0 ? memory : (memory = exports.memory); + if (this.childThread) { + instance = createInstanceProxy(instance, memory); + } + this.setup(instance, module, memory); + const exitCode = this.wasi.start(instance); + return { exitCode, instance }; + } + terminateAllThreads() { + var _a; + if (!this.childThread) { + (_a = this.PThread) === null || _a === void 0 ? void 0 : _a.terminateAllThreads(); + } + else { + this.postMessage(createMessage('terminate-all-threads', {})); + } + } +} +function patchWasiInstance(wasiThreads, wasi) { + const patched = patchedWasiInstances.get(wasiThreads); + if (patched.has(wasi)) { + return; + } + const _this = wasiThreads; + const wasiImport = wasi.wasiImport; + if (wasiImport) { + const proc_exit = wasiImport.proc_exit; + wasiImport.proc_exit = function (code) { + _this.terminateAllThreads(); + return proc_exit.call(this, code); + }; + } + if (!_this.childThread) { + const start = wasi.start; + if (typeof start === 'function') { + wasi.start = function (instance) { + try { + return start.call(this, instance); + } + catch (err) { + if (isTrapError(err)) { + _this.terminateAllThreads(); + } + throw err; + } + }; + } + } + patched.add(wasi); +} +function getWasiSymbol(wasi, description) { + const symbols = Object.getOwnPropertySymbols(wasi); + const selectDescription = (description) => (s) => { + if (s.description) { + return s.description === description; + } + return s.toString() === `Symbol(${description})`; + }; + if (Array.isArray(description)) { + return description.map(d => symbols.filter(selectDescription(d))[0]); + } + return symbols.filter(selectDescription(description))[0]; +} +function setupInstance(wasi, instance) { + const [kInstance, kSetMemory] = getWasiSymbol(wasi, ['kInstance', 'kSetMemory']); + wasi[kInstance] = instance; + wasi[kSetMemory](instance.exports.memory); +} + +class ThreadMessageHandler { + constructor(options) { + const postMsg = getPostMessage(options); + if (typeof postMsg !== 'function') { + throw new TypeError('options.postMessage is not a function'); + } + this.postMessage = postMsg; + this.onLoad = options === null || options === void 0 ? void 0 : options.onLoad; + this.onError = typeof (options === null || options === void 0 ? void 0 : options.onError) === 'function' ? options.onError : (_type, err) => { throw err; }; + this.instance = undefined; + this.messagesBeforeLoad = []; + } + instantiate(data) { + if (typeof this.onLoad === 'function') { + return this.onLoad(data); + } + throw new Error('ThreadMessageHandler.prototype.instantiate is not implemented'); + } + handle(e) { + var _a; + if ((_a = e === null || e === void 0 ? void 0 : e.data) === null || _a === void 0 ? void 0 : _a.__emnapi__) { + const type = e.data.__emnapi__.type; + const payload = e.data.__emnapi__.payload; + try { + if (type === 'load') { + this._load(payload); + } + else if (type === 'start') { + this.handleAfterLoad(e, () => { + this._start(payload); + }); + } + } + catch (err) { + this.onError(err, type); + } + } + } + _load(payload) { + if (this.instance !== undefined) + return; + let source; + try { + source = this.instantiate(payload); + } + catch (err) { + this._loaded(err, null, payload); + return; + } + const then = source && 'then' in source ? source.then : undefined; + if (typeof then === 'function') { + then.call(source, (source) => { this._loaded(null, source, payload); }, (err) => { this._loaded(err, null, payload); }); + } + else { + this._loaded(null, source, payload); + } + } + _start(payload) { + const wasi_thread_start = this.instance.exports.wasi_thread_start; + if (typeof wasi_thread_start !== 'function') { + const err = new TypeError('wasi_thread_start is not exported'); + notifyPthreadCreateResult(payload.sab, 2, err); + throw err; + } + const postMessage = this.postMessage; + const tid = payload.tid; + const startArg = payload.arg; + notifyPthreadCreateResult(payload.sab, 1); + try { + wasi_thread_start(tid, startArg); + } + catch (err) { + if (err !== 'unwind') { + throw err; + } + else { + return; + } + } + postMessage(createMessage('cleanup-thread', { tid })); + } + _loaded(err, source, payload) { + if (err) { + notifyPthreadCreateResult(payload.sab, 2, err); + throw err; + } + if (source == null) { + const err = new TypeError('onLoad should return an object'); + notifyPthreadCreateResult(payload.sab, 2, err); + throw err; + } + const instance = source.instance; + if (!instance) { + const err = new TypeError('onLoad should return an object which includes "instance"'); + notifyPthreadCreateResult(payload.sab, 2, err); + throw err; + } + this.instance = instance; + const postMessage = this.postMessage; + postMessage(createMessage('loaded', {})); + const messages = this.messagesBeforeLoad; + this.messagesBeforeLoad = []; + for (let i = 0; i < messages.length; i++) { + const data = messages[i]; + this.handle({ data }); + } + } + handleAfterLoad(e, f) { + if (this.instance !== undefined) { + f.call(this, e); + } + else { + this.messagesBeforeLoad.push(e.data); + } + } +} +function notifyPthreadCreateResult(sab, result, error) { + if (sab) { + serizeErrorToBuffer(sab.buffer, result, error); + Atomics.notify(sab, 0); + } +} + +export { ThreadManager, ThreadMessageHandler, WASIThreads, createInstanceProxy, isSharedArrayBuffer, isTrapError }; diff --git a/dg-ui/node_modules/@tailwindcss/oxide-wasm32-wasi/node_modules/@emnapi/wasi-threads/index.js b/dg-ui/node_modules/@tailwindcss/oxide-wasm32-wasi/node_modules/@emnapi/wasi-threads/index.js new file mode 100644 index 0000000..7e6eabd --- /dev/null +++ b/dg-ui/node_modules/@tailwindcss/oxide-wasm32-wasi/node_modules/@emnapi/wasi-threads/index.js @@ -0,0 +1,5 @@ +if (typeof process !== 'undefined' && process.env.NODE_ENV === 'production') { + module.exports = require('./dist/wasi-threads.cjs.min.js') +} else { + module.exports = require('./dist/wasi-threads.cjs.js') +} diff --git a/dg-ui/node_modules/@tailwindcss/oxide-wasm32-wasi/node_modules/@emnapi/wasi-threads/package.json b/dg-ui/node_modules/@tailwindcss/oxide-wasm32-wasi/node_modules/@emnapi/wasi-threads/package.json new file mode 100644 index 0000000..1a3f08f --- /dev/null +++ b/dg-ui/node_modules/@tailwindcss/oxide-wasm32-wasi/node_modules/@emnapi/wasi-threads/package.json @@ -0,0 +1,50 @@ +{ + "name": "@emnapi/wasi-threads", + "version": "1.2.3", + "description": "WASI threads proposal implementation in JavaScript", + "main": "index.js", + "module": "./dist/wasi-threads.esm-bundler.js", + "types": "./dist/wasi-threads.d.ts", + "sideEffects": false, + "exports": { + ".": { + "types": { + "module": "./dist/wasi-threads.d.ts", + "import": "./dist/wasi-threads.d.mts", + "default": "./dist/wasi-threads.d.ts" + }, + "module": "./dist/wasi-threads.esm-bundler.js", + "import": "./dist/wasi-threads.mjs", + "default": "./index.js" + }, + "./dist/wasi-threads.cjs.min": { + "types": "./dist/wasi-threads.d.ts", + "default": "./dist/wasi-threads.cjs.min.js" + }, + "./dist/wasi-threads.min.mjs": { + "types": "./dist/wasi-threads.d.mts", + "default": "./dist/wasi-threads.min.mjs" + } + }, + "dependencies": { + "tslib": "^2.4.0" + }, + "scripts": { + "build": "node ./script/build.js", + "build:test": "node ./test/build.js", + "test": "node ./test/index.js" + }, + "repository": { + "type": "git", + "url": "git+https://github.com/toyobayashi/emnapi.git" + }, + "author": "toyobayashi", + "license": "MIT", + "bugs": { + "url": "https://github.com/toyobayashi/emnapi/issues" + }, + "homepage": "https://github.com/toyobayashi/emnapi#readme", + "publishConfig": { + "access": "public" + } +} diff --git a/dg-ui/node_modules/@tailwindcss/oxide-wasm32-wasi/node_modules/@napi-rs/wasm-runtime/dist/emnapi-plugins.cjs b/dg-ui/node_modules/@tailwindcss/oxide-wasm32-wasi/node_modules/@napi-rs/wasm-runtime/dist/emnapi-plugins.cjs new file mode 100644 index 0000000..0b19a52 --- /dev/null +++ b/dg-ui/node_modules/@tailwindcss/oxide-wasm32-wasi/node_modules/@napi-rs/wasm-runtime/dist/emnapi-plugins.cjs @@ -0,0 +1,1826 @@ +'use strict'; + +//#region src/emnapi/async-work.js +function asyncWork (emnapiPluginCtx) { + const { emnapiCtx, emnapiNodeBinding, emnapiAsyncWorkPoolSize } = emnapiPluginCtx; + var mod = (function (exports, emnapi_shared, emscripten_runtime) { + + //#region src/async-work.ts + /** + * @__deps $emnapiCtx + * @__deps $emnapiEnv + * @__deps $emnapiNodeBinding + * @__deps $emnapiAsyncWorkPoolSize + * @__postset + * ``` + * emnapiAWST.init(); + * ``` + */ + var emnapiAWST = { + idGen: {}, + values: [undefined], + queued: new Set(), + pending: [], + init: function () { + const idGen = { + nextId: 1, + list: [], + generate: function () { + let id; + if (idGen.list.length) { + id = idGen.list.shift(); + } + else { + id = idGen.nextId; + idGen.nextId++; + } + return id; + }, + reuse: function (id) { + idGen.list.push(id); + } + }; + emnapiAWST.idGen = idGen; + emnapiAWST.values = [undefined]; + emnapiAWST.queued = new Set(); + emnapiAWST.pending = []; + }, + create: function (env, resource, resourceName, execute, complete, data) { + let asyncId = 0; + let triggerAsyncId = 0; + if (emnapiNodeBinding) { + const asyncContext = emnapiNodeBinding.node.emitAsyncInit(resource, resourceName, -1); + asyncId = asyncContext.asyncId; + triggerAsyncId = asyncContext.triggerAsyncId; + } + const id = emnapiAWST.idGen.generate(); + emnapiAWST.values[id] = { + env, + id, + resource, + asyncId, + triggerAsyncId, + status: 0, + execute, + complete, + data + }; + return id; + }, + callComplete: function (work, status) { + const complete = work.complete; + const env = work.env; + const data = work.data; + const callback = () => { + if (!complete) + return; + const envObject = emnapi_shared.emnapiEnv; + const scope = emnapiCtx.openScope(envObject); + try { + envObject.callbackIntoModule(true, () => { + (emnapiPluginCtx.wasmTable.get(complete))(env, status, data); + }); + } + finally { + emnapiCtx.closeScope(envObject, scope); + } + }; + if (emnapiNodeBinding) { + emnapiNodeBinding.node.makeCallback(work.resource, callback, [], { + asyncId: work.asyncId, + triggerAsyncId: work.triggerAsyncId + }); + } + else { + callback(); + } + }, + queue: function (id) { + const work = emnapiAWST.values[id]; + if (!work) + return; + if (work.status === 0) { + work.status = 1; + if (emnapiAWST.queued.size >= (Math.abs(emnapiAsyncWorkPoolSize) || 4)) { + emnapiAWST.pending.push(id); + return; + } + emnapiAWST.queued.add(id); + const env = work.env; + const data = work.data; + const execute = work.execute; + work.status = 2; + emnapiCtx.features.setImmediate(() => { + (emnapiPluginCtx.wasmTable.get(execute))(env, data); + emnapiAWST.queued.delete(id); + work.status = 3; + emnapiCtx.features.setImmediate(() => { + emnapiAWST.callComplete(work, 0 /* napi_status.napi_ok */); + }); + if (emnapiAWST.pending.length > 0) { + const nextWorkId = emnapiAWST.pending.shift(); + emnapiAWST.values[nextWorkId].status = 0; + emnapiAWST.queue(nextWorkId); + } + }); + } + }, + cancel: function (id) { + const index = emnapiAWST.pending.indexOf(id); + if (index !== -1) { + const work = emnapiAWST.values[id]; + if (work && (work.status === 1)) { + work.status = 4; + emnapiAWST.pending.splice(index, 1); + emnapiCtx.features.setImmediate(() => { + emnapiAWST.callComplete(work, 11 /* napi_status.napi_cancelled */); + }); + return 0 /* napi_status.napi_ok */; + } + else { + return 9 /* napi_status.napi_generic_failure */; + } + } + return 9 /* napi_status.napi_generic_failure */; + }, + remove: function (id) { + const work = emnapiAWST.values[id]; + if (!work) + return; + if (emnapiNodeBinding) { + emnapiNodeBinding.node.emitAsyncDestroy({ + asyncId: work.asyncId, + triggerAsyncId: work.triggerAsyncId + }); + } + emnapiAWST.values[id] = undefined; + emnapiAWST.idGen.reuse(id); + } + }; + + //#endregion src/async-work.ts + + //#region src/macro.ts + + //#endregion src/macro.ts + + //#region src/core/async-work.ts + const { + // onCreateWorker, napiModule, singleThreadAsyncWork, _emnapi_async_work_pool_size, + // PThread, ENVIRONMENT_IS_NODE, ENVIRONMENT_IS_PTHREAD, wasmInstance, _free, wasmMemory, _malloc, + _emnapi_node_emit_async_init, _emnapi_node_emit_async_destroy, _emnapi_runtime_keepalive_pop, _emnapi_runtime_keepalive_push } = emnapiPluginCtx; + var emnapiAWMT = { + pool: [], + workerReady: null, + globalAddress: 0, + globalOffset: { + idle_threads: 0, + q: 1 * 4, + next: 1 * 4, + prev: 2 * 4, + mutex: 3 * 4, + cond: 4 * 4, + exit_message: 5 * 4, + end: 7 * 4 + }, + offset: { + /* napi_ref */ resource: 0, + /* double */ async_id: 8, + /* double */ trigger_async_id: 16, + /* napi_env */ env: 24, + /* int32_t */ status: 1 * 4 + 24, // 0 for pending, 1 for cancelled, 2 for completed + queue: 2 * 4 + 24, + queue_next: 2 * 4 + 24, + queue_prev: 3 * 4 + 24, + /* void* */ data: 4 * 4 + 24, + /* napi_async_execute_callback */ execute: 5 * 4 + 24, + /* napi_async_complete_callback */ complete: 6 * 4 + 24, + end: 7 * 4 + 24 + }, + /** + * When another thread grows the shared WebAssembly.Memory, this agent's + * cached `wasmMemory.buffer` may still have the old shorter length + * (V8 refreshes it lazily). If a pointer derived from shared memory lies + * beyond the cached length, `wasmMemory.grow(0)` forces the agent to + * observe the current memory size and refreshes the buffer. + */ + ensureBufferFor(end) { + let buffer = emscripten_runtime.wasmMemory.buffer; + if (end > buffer.byteLength) { + emscripten_runtime.wasmMemory.grow(0); + buffer = emscripten_runtime.wasmMemory.buffer; + } + return buffer; + }, + init() { + emnapiAWMT.pool = []; + emnapiAWMT.workerReady = null; + if (typeof emscripten_runtime.PThread !== 'undefined') { + emscripten_runtime.PThread.unusedWorkers.forEach(emnapiAWMT.addListener); + Object.values(emscripten_runtime.PThread.pthreads).forEach(emnapiAWMT.addListener); + const __original_getNewWorker = emscripten_runtime.PThread.getNewWorker; + emscripten_runtime.PThread.getNewWorker = function () { + const r = __original_getNewWorker.apply(this, arguments); + emnapiAWMT.addListener(r); + return r; + }; + } + }, + addListener(worker) { + if (!worker) + return false; + if (worker._emnapiAWMTListener) + return true; + const handler = function (e) { + const data = emscripten_runtime.ENVIRONMENT_IS_NODE ? e : e.data; + const __emnapi__ = data.__emnapi__; + if (__emnapi__) { + const type = __emnapi__.type; + const payload = __emnapi__.payload; + if (type === 'async-work-complete') { + emnapiAWMT.callComplete(payload.work, 0 /* napi_status.napi_ok */); + } + } + }; + const dispose = function () { + if (emscripten_runtime.ENVIRONMENT_IS_NODE) { + worker.off('message', handler); + } + else { + worker.removeEventListener('message', handler, false); + } + delete worker._emnapiAWMTListener; + }; + worker._emnapiAWMTListener = { handler, dispose }; + if (emscripten_runtime.ENVIRONMENT_IS_NODE) { + worker.on('message', handler); + } + else { + worker.addEventListener('message', handler, false); + } + return true; + }, + initGlobal() { + if (!emnapiAWMT.globalAddress) { + emnapiAWMT.globalAddress = emscripten_runtime._malloc(emnapiAWMT.globalOffset.end); + emnapiAWMT.globalAddress >>>= 0; + const size = emnapiAWMT.globalOffset.end; + const addr = emnapiAWMT.globalAddress; + new Uint8Array(emnapiAWMT.ensureBufferFor(addr + size), addr, size).fill(0); + emnapiAWMT.queueInit(emnapiAWMT.globalAddress + emnapiAWMT.globalOffset.q); + emnapiAWMT.queueInit(emnapiAWMT.globalAddress + emnapiAWMT.globalOffset.exit_message); + } + }, + terminateWorkers() { + emnapiAWMT.pool.forEach(w => { + w._emnapiAWMTListener?.dispose(); + w._emnapiTSFNListener?.dispose(); + w.terminate(); + }); + emnapiAWMT.pool.length = 0; + }, + initWorkers(n) { + if (emscripten_runtime.ENVIRONMENT_IS_PTHREAD) { + return emnapiAWMT.workerReady || (emnapiAWMT.workerReady = Promise.resolve()); + } + if (emnapiAWMT.workerReady) + return emnapiAWMT.workerReady; + if (!('emnapi_async_worker_create' in emscripten_runtime.wasmInstance.exports)) { + throw new TypeError('`emnapi_async_worker_create` is not exported, please try to add `--export=emnapi_async_worker_create` to linker flags'); + } + const emnapi_async_worker_create = emscripten_runtime.wasmInstance.exports.emnapi_async_worker_create; + const args = []; + emnapiAWMT.initGlobal(); + for (let i = 0; i < n; ++i) { + args.push(emnapi_async_worker_create(1, emnapiAWMT.globalAddress)); + } + const promises = args.map(index => { + if (index === 0) { + return Promise.reject(new Error('Failed to create async worker')); + } + let worker; + if (index < 0) { + worker = emnapiAWMT.pool[-index - 1]; + if (worker) + return worker.whenLoaded; + } + index >>>= 0; + const tidOffset = 20; + const view = new DataView(emnapiAWMT.ensureBufferFor(index + tidOffset + 4)); + const tid = view.getInt32(index + tidOffset, true); + worker = emscripten_runtime.PThread.pthreads[tid]; + return worker.whenLoaded; + }); + emnapiAWMT.workerReady = Promise.all(promises); + return emnapiAWMT.workerReady; + }, + getResource(work) { + emnapiAWMT.ensureBufferFor(work + emnapiAWMT.offset.resource + 4); + var HEAP_DATA_VIEW = new DataView(emnapiPluginCtx.wasmMemory.buffer), GET_HEAP_DATA_VIEW = () => HEAP_DATA_VIEW.buffer === emnapiPluginCtx.wasmMemory.buffer ? HEAP_DATA_VIEW : (HEAP_DATA_VIEW = new DataView(emnapiPluginCtx.wasmMemory.buffer)); + return GET_HEAP_DATA_VIEW().getUint32(work + emnapiAWMT.offset.resource, true); + }, + getExecute(work) { + emnapiAWMT.ensureBufferFor(work + emnapiAWMT.offset.execute + 4); + var HEAP_DATA_VIEW = new DataView(emnapiPluginCtx.wasmMemory.buffer), GET_HEAP_DATA_VIEW = () => HEAP_DATA_VIEW.buffer === emnapiPluginCtx.wasmMemory.buffer ? HEAP_DATA_VIEW : (HEAP_DATA_VIEW = new DataView(emnapiPluginCtx.wasmMemory.buffer)); + return GET_HEAP_DATA_VIEW().getUint32(work + emnapiAWMT.offset.execute, true); + }, + getComplete(work) { + emnapiAWMT.ensureBufferFor(work + emnapiAWMT.offset.complete + 4); + var HEAP_DATA_VIEW = new DataView(emnapiPluginCtx.wasmMemory.buffer), GET_HEAP_DATA_VIEW = () => HEAP_DATA_VIEW.buffer === emnapiPluginCtx.wasmMemory.buffer ? HEAP_DATA_VIEW : (HEAP_DATA_VIEW = new DataView(emnapiPluginCtx.wasmMemory.buffer)); + return GET_HEAP_DATA_VIEW().getUint32(work + emnapiAWMT.offset.complete, true); + }, + getEnv(work) { + emnapiAWMT.ensureBufferFor(work + emnapiAWMT.offset.env + 4); + var HEAP_DATA_VIEW = new DataView(emnapiPluginCtx.wasmMemory.buffer), GET_HEAP_DATA_VIEW = () => HEAP_DATA_VIEW.buffer === emnapiPluginCtx.wasmMemory.buffer ? HEAP_DATA_VIEW : (HEAP_DATA_VIEW = new DataView(emnapiPluginCtx.wasmMemory.buffer)); + return GET_HEAP_DATA_VIEW().getUint32(work + emnapiAWMT.offset.env, true); + }, + getData(work) { + emnapiAWMT.ensureBufferFor(work + emnapiAWMT.offset.data + 4); + var HEAP_DATA_VIEW = new DataView(emnapiPluginCtx.wasmMemory.buffer), GET_HEAP_DATA_VIEW = () => HEAP_DATA_VIEW.buffer === emnapiPluginCtx.wasmMemory.buffer ? HEAP_DATA_VIEW : (HEAP_DATA_VIEW = new DataView(emnapiPluginCtx.wasmMemory.buffer)); + return GET_HEAP_DATA_VIEW().getUint32(work + emnapiAWMT.offset.data, true); + }, + getMutex() { + const index = emnapiAWMT.globalAddress + emnapiAWMT.globalOffset.mutex; + const mutex = { + lock() { + const isBrowserMain = typeof window !== 'undefined' && typeof document !== 'undefined' && !emscripten_runtime.ENVIRONMENT_IS_NODE; + const i32a = new Int32Array(emnapiAWMT.ensureBufferFor(index + 4), index, 1); + if (isBrowserMain) { + while (true) { + const oldValue = Atomics.compareExchange(i32a, 0, 0, 10); + if (oldValue === 0) { + return; + } + } + } + else { + while (true) { + const oldValue = Atomics.compareExchange(i32a, 0, 0, 10); + if (oldValue === 0) { + return; + } + Atomics.wait(i32a, 0, 10); + } + } + }, + unlock() { + const i32a = new Int32Array(emnapiAWMT.ensureBufferFor(index + 4), index, 1); + const oldValue = Atomics.compareExchange(i32a, 0, 10, 0); + if (oldValue !== 10) { + throw new Error('Tried to unlock while not holding the mutex'); + } + Atomics.notify(i32a, 0, 1); + }, + execute(fn) { + mutex.lock(); + try { + return fn(); + } + finally { + mutex.unlock(); + } + } + }; + return mutex; + }, + getCond() { + const index = emnapiAWMT.globalAddress + emnapiAWMT.globalOffset.cond; + const mutex = emnapiAWMT.getMutex(); + const cond = { + wait() { + const i32a = new Int32Array(emnapiAWMT.ensureBufferFor(index + 4), index, 1); + const value = Atomics.load(i32a, 0); + mutex.unlock(); + Atomics.wait(i32a, 0, value); + mutex.lock(); + }, + signal() { + const i32a = new Int32Array(emnapiAWMT.ensureBufferFor(index + 4), index, 1); + Atomics.add(i32a, 0, 1); + Atomics.notify(i32a, 0, 1); + } + }; + return cond; + }, + queueInit(q) { + emnapiAWMT.ensureBufferFor(q + 4 + 4); + var HEAP_DATA_VIEW = new DataView(emnapiPluginCtx.wasmMemory.buffer), GET_HEAP_DATA_VIEW = () => HEAP_DATA_VIEW.buffer === emnapiPluginCtx.wasmMemory.buffer ? HEAP_DATA_VIEW : (HEAP_DATA_VIEW = new DataView(emnapiPluginCtx.wasmMemory.buffer)); + GET_HEAP_DATA_VIEW().setUint32(q, q, true); + GET_HEAP_DATA_VIEW().setUint32(q + 4, q, true); + }, + queueInsertTail(h, q) { + emnapiAWMT.ensureBufferFor(h + 4 + 4); + emnapiAWMT.ensureBufferFor(q + 4 + 4); + var HEAP_DATA_VIEW = new DataView(emnapiPluginCtx.wasmMemory.buffer), GET_HEAP_DATA_VIEW = () => HEAP_DATA_VIEW.buffer === emnapiPluginCtx.wasmMemory.buffer ? HEAP_DATA_VIEW : (HEAP_DATA_VIEW = new DataView(emnapiPluginCtx.wasmMemory.buffer)); + GET_HEAP_DATA_VIEW().setUint32(q, h, true); + const tempValue = GET_HEAP_DATA_VIEW().getUint32(h + 4, true); + GET_HEAP_DATA_VIEW().setUint32(q + 4, tempValue, true); + const qprev = GET_HEAP_DATA_VIEW().getUint32(q + 4, true); + GET_HEAP_DATA_VIEW().setUint32(qprev, q, true); + GET_HEAP_DATA_VIEW().setUint32(h + 4, q, true); + }, + queueRemove(q) { + emnapiAWMT.ensureBufferFor(q + 4 + 4); + var HEAP_DATA_VIEW = new DataView(emnapiPluginCtx.wasmMemory.buffer), GET_HEAP_DATA_VIEW = () => HEAP_DATA_VIEW.buffer === emnapiPluginCtx.wasmMemory.buffer ? HEAP_DATA_VIEW : (HEAP_DATA_VIEW = new DataView(emnapiPluginCtx.wasmMemory.buffer)); + const qprev = GET_HEAP_DATA_VIEW().getUint32(q + 4, true); + const qnext = GET_HEAP_DATA_VIEW().getUint32(q, true); + GET_HEAP_DATA_VIEW().setUint32(qprev, qnext, true); + GET_HEAP_DATA_VIEW().setUint32(qnext + 4, qprev, true); + }, + queueEmpty(q) { + emnapiAWMT.ensureBufferFor(q + 4); + var HEAP_DATA_VIEW = new DataView(emnapiPluginCtx.wasmMemory.buffer), GET_HEAP_DATA_VIEW = () => HEAP_DATA_VIEW.buffer === emnapiPluginCtx.wasmMemory.buffer ? HEAP_DATA_VIEW : (HEAP_DATA_VIEW = new DataView(emnapiPluginCtx.wasmMemory.buffer)); + // eslint-disable-next-line eqeqeq + return q == GET_HEAP_DATA_VIEW().getUint32(q, true); + }, + scheduleWork: function (work) { + if (!emnapiAWMT.workerReady?.ready) { + emnapiAWMT.initWorkers(emnapi_shared._emnapi_async_work_pool_size()).then(() => { + emnapiAWMT.workerReady.ready = true; + }).catch((err) => { + emnapiAWMT.workerReady = null; + throw err; + }); + } + _emnapi_runtime_keepalive_push(); + emnapiCtx.increaseWaitingRequestCounter(); + const statusBuffer = new Int32Array(emnapiAWMT.ensureBufferFor(work + emnapiAWMT.offset.status + 4), work + emnapiAWMT.offset.status, 1); + Atomics.store(statusBuffer, 0, 0 /* AsyncWorkStatus.Pending */); + const mutex = emnapiAWMT.getMutex(); + const cond = emnapiAWMT.getCond(); + mutex.lock(); + try { + emnapiAWMT.queueInsertTail(emnapiAWMT.globalAddress + emnapiAWMT.globalOffset.q, work + emnapiAWMT.offset.queue); + } + catch (err) { + _emnapi_runtime_keepalive_pop(); + emnapiCtx.decreaseWaitingRequestCounter(); + mutex.unlock(); + throw err; + } + emnapiAWMT.ensureBufferFor(emnapiAWMT.globalAddress + emnapiAWMT.globalOffset.idle_threads + 4); + var HEAP_DATA_VIEW = new DataView(emnapiPluginCtx.wasmMemory.buffer), GET_HEAP_DATA_VIEW = () => HEAP_DATA_VIEW.buffer === emnapiPluginCtx.wasmMemory.buffer ? HEAP_DATA_VIEW : (HEAP_DATA_VIEW = new DataView(emnapiPluginCtx.wasmMemory.buffer)); + if (GET_HEAP_DATA_VIEW().getUint32(emnapiAWMT.globalAddress + emnapiAWMT.globalOffset.idle_threads, true) > 0) { + cond.signal(); + } + mutex.unlock(); + }, + cancelWork(work) { + let cancelled = false; + emnapiAWMT.getMutex().execute(() => { + emnapiAWMT.ensureBufferFor(work + emnapiAWMT.offset.status + 4); + var HEAP_DATA_VIEW = new DataView(emnapiPluginCtx.wasmMemory.buffer), GET_HEAP_DATA_VIEW = () => HEAP_DATA_VIEW.buffer === emnapiPluginCtx.wasmMemory.buffer ? HEAP_DATA_VIEW : (HEAP_DATA_VIEW = new DataView(emnapiPluginCtx.wasmMemory.buffer)); + cancelled = !emnapiAWMT.queueEmpty(work + emnapiAWMT.offset.queue) && GET_HEAP_DATA_VIEW().getInt32(work + emnapiAWMT.offset.status, true) !== 2 /* AsyncWorkStatus.Completed */; + if (cancelled) { + emnapiAWMT.queueRemove(work + emnapiAWMT.offset.queue); + } + }); + if (!cancelled) { + return 9 /* napi_status.napi_generic_failure */; + } + if (Atomics.compareExchange(new Int32Array(emnapiAWMT.ensureBufferFor(work + emnapiAWMT.offset.status + 4), work + emnapiAWMT.offset.status, 1), 0, 0 /* AsyncWorkStatus.Pending */, 1 /* AsyncWorkStatus.Cancelled */) !== 0 /* AsyncWorkStatus.Pending */) { + return 9 /* napi_status.napi_generic_failure */; + } + emnapiCtx.features.setImmediate(() => { + emnapiAWMT.callComplete(work, 11 /* napi_status.napi_cancelled */); + }); + return 0 /* napi_status.napi_ok */; + }, + callComplete: function (work, status) { + _emnapi_runtime_keepalive_pop(); + emnapiCtx.decreaseWaitingRequestCounter(); + const complete = emnapiAWMT.getComplete(work); + const env = emnapiAWMT.getEnv(work); + const data = emnapiAWMT.getData(work); + const envObject = emnapi_shared.emnapiEnv; + const scope = emnapiCtx.openScope(envObject); + const callback = () => { + if (!complete) + return; + envObject.callbackIntoModule(true, () => { + (emnapiPluginCtx.wasmTable.get(complete))(env, status, data); + }); + }; + try { + if (emnapiNodeBinding) { + const resource = emnapiAWMT.getResource(work); + const resource_value = emnapiCtx.getRef(resource).get(); + const resourceObject = emnapiCtx.jsValueFromNapiValue(resource_value); + const view = new DataView(emnapiAWMT.ensureBufferFor(work + emnapiAWMT.offset.trigger_async_id + 8)); + const asyncId = view.getFloat64(work + emnapiAWMT.offset.async_id, true); + const triggerAsyncId = view.getFloat64(work + emnapiAWMT.offset.trigger_async_id, true); + emnapiNodeBinding.node.makeCallback(resourceObject, callback, [], { + asyncId, + triggerAsyncId + }); + } + else { + callback(); + } + } + finally { + emnapiCtx.closeScope(envObject, scope); + } + } + }; + emnapiAWST.init(); + emnapiAWMT.init(); + /** @__sig ippppppp */ + var napi_create_async_work = emnapi_shared.singleThreadAsyncWork + ? function (env, resource, resource_name, execute, complete, data, result) { + if (!env) + return 1 /* napi_status.napi_invalid_arg */; + // @ts-expect-error + const envObject = emnapi_shared.emnapiEnv; + envObject.checkGCAccess(); + if (!execute) + return envObject.setLastError(1 /* napi_status.napi_invalid_arg */); + if (!result) + return envObject.setLastError(1 /* napi_status.napi_invalid_arg */); + let resourceObject; + if (resource) { + resourceObject = Object(emnapiCtx.jsValueFromNapiValue(resource)); + } + else { + resourceObject = {}; + } + if (!resource_name) + return envObject.setLastError(1 /* napi_status.napi_invalid_arg */); + const resourceName = String(emnapiCtx.jsValueFromNapiValue(resource_name)); + const id = emnapiAWST.create(env, resourceObject, resourceName, execute, complete, data); + result >>>= 0; + var HEAP_DATA_VIEW = new DataView(emnapiPluginCtx.wasmMemory.buffer), GET_HEAP_DATA_VIEW = () => HEAP_DATA_VIEW.buffer === emnapiPluginCtx.wasmMemory.buffer ? HEAP_DATA_VIEW : (HEAP_DATA_VIEW = new DataView(emnapiPluginCtx.wasmMemory.buffer)); + GET_HEAP_DATA_VIEW().setUint32(result, id, true); + return envObject.clearLastError(); + } + : function (env, resource, resource_name, execute, complete, data, result) { + if (!env) + return 1 /* napi_status.napi_invalid_arg */; + // @ts-expect-error + const envObject = emnapi_shared.emnapiEnv; + envObject.checkGCAccess(); + if (!execute) + return envObject.setLastError(1 /* napi_status.napi_invalid_arg */); + if (!result) + return envObject.setLastError(1 /* napi_status.napi_invalid_arg */); + let resourceObject; + if (resource) { + resourceObject = Object(emnapiCtx.jsValueFromNapiValue(resource)); + } + else { + resourceObject = {}; + } + if (!resource_name) + return envObject.setLastError(1 /* napi_status.napi_invalid_arg */); + const sizeofAW = emnapiAWMT.offset.end; + let aw = emscripten_runtime._malloc(sizeofAW); + if (!aw) + return envObject.setLastError(9 /* napi_status.napi_generic_failure */); + aw >>>= 0; + new Uint8Array(emnapiAWMT.ensureBufferFor(aw + sizeofAW)).subarray(aw, aw + sizeofAW).fill(0); + const s = emnapiCtx.napiValueFromJsValue(resourceObject); + const resourceRef = emnapiCtx.createReference(envObject, s, 1, 1 /* ReferenceOwnership.kUserland */); + const resource_ = resourceRef.id; + var HEAP_DATA_VIEW = new DataView(emnapiPluginCtx.wasmMemory.buffer), GET_HEAP_DATA_VIEW = () => HEAP_DATA_VIEW.buffer === emnapiPluginCtx.wasmMemory.buffer ? HEAP_DATA_VIEW : (HEAP_DATA_VIEW = new DataView(emnapiPluginCtx.wasmMemory.buffer)); + GET_HEAP_DATA_VIEW().setUint32(aw, resource_, true); + _emnapi_node_emit_async_init(s, resource_name, -1, aw + emnapiAWMT.offset.async_id); + GET_HEAP_DATA_VIEW().setUint32(aw + emnapiAWMT.offset.env, env, true); + GET_HEAP_DATA_VIEW().setUint32(aw + emnapiAWMT.offset.execute, execute, true); + GET_HEAP_DATA_VIEW().setUint32(aw + emnapiAWMT.offset.complete, complete, true); + GET_HEAP_DATA_VIEW().setUint32(aw + emnapiAWMT.offset.data, data, true); + emnapiAWMT.queueInit(aw + emnapiAWMT.offset.queue); + result >>>= 0; + GET_HEAP_DATA_VIEW().setUint32(result, aw, true); + return envObject.clearLastError(); + }; + /** @__sig ipp */ + var napi_delete_async_work = emnapi_shared.singleThreadAsyncWork + ? function (env, work) { + if (!env) + return 1 /* napi_status.napi_invalid_arg */; + // @ts-expect-error + const envObject = emnapi_shared.emnapiEnv; + envObject.checkGCAccess(); + if (!work) + return envObject.setLastError(1 /* napi_status.napi_invalid_arg */); + work >>>= 0; + emnapiAWST.remove(work); + return envObject.clearLastError(); + } + : function (env, work) { + if (!env) + return 1 /* napi_status.napi_invalid_arg */; + // @ts-expect-error + const envObject = emnapi_shared.emnapiEnv; + envObject.checkGCAccess(); + if (!work) + return envObject.setLastError(1 /* napi_status.napi_invalid_arg */); + work >>>= 0; + const resource = emnapiAWMT.getResource(work); + emnapiCtx.getRef(resource).dispose(); + if (emnapiNodeBinding) { + const view = new DataView(emnapiAWMT.ensureBufferFor(work + emnapiAWMT.offset.trigger_async_id + 8)); + const asyncId = view.getFloat64(work + emnapiAWMT.offset.async_id, true); + const triggerAsyncId = view.getFloat64(work + emnapiAWMT.offset.trigger_async_id, true); + _emnapi_node_emit_async_destroy(asyncId, triggerAsyncId); + } + emscripten_runtime._free(work); + return envObject.clearLastError(); + }; + /** @__sig ipp */ + var napi_queue_async_work = emnapi_shared.singleThreadAsyncWork + ? function (env, work) { + if (!env) + return 1 /* napi_status.napi_invalid_arg */; + const envObject = emnapi_shared.emnapiEnv; + if (!work) + return envObject.setLastError(1 /* napi_status.napi_invalid_arg */); + work >>>= 0; + emnapiAWST.queue(work); + return envObject.clearLastError(); + } + : function (env, work) { + if (!env) + return 1 /* napi_status.napi_invalid_arg */; + const envObject = emnapi_shared.emnapiEnv; + if (!work) + return envObject.setLastError(1 /* napi_status.napi_invalid_arg */); + work >>>= 0; + emnapiAWMT.scheduleWork(work); + return envObject.clearLastError(); + }; + /** @__sig ipp */ + var napi_cancel_async_work = emnapi_shared.singleThreadAsyncWork + ? function (env, work) { + if (!env) + return 1 /* napi_status.napi_invalid_arg */; + const envObject = emnapi_shared.emnapiEnv; + if (!work) + return envObject.setLastError(1 /* napi_status.napi_invalid_arg */); + work >>>= 0; + const status = emnapiAWST.cancel(work); + if (status === 0 /* napi_status.napi_ok */) + return envObject.clearLastError(); + return envObject.setLastError(status); + } + : function (env, work) { + if (!env) + return 1 /* napi_status.napi_invalid_arg */; + const envObject = emnapi_shared.emnapiEnv; + if (!work) + return envObject.setLastError(1 /* napi_status.napi_invalid_arg */); + work >>>= 0; + const status = emnapiAWMT.cancelWork(work); + if (status === 0 /* napi_status.napi_ok */) + return envObject.clearLastError(); + return envObject.setLastError(status); + }; + /** @__sig pp */ + function _emnapi_async_worker(globalAddress) { + globalAddress >>>= 0; + emnapiAWMT.globalAddress = globalAddress; + const mutex = emnapiAWMT.getMutex(); + const cond = emnapiAWMT.getCond(); + mutex.lock(); + const exitMessageAddr = globalAddress + emnapiAWMT.globalOffset.exit_message; + const idleThreadsAddr = globalAddress + emnapiAWMT.globalOffset.idle_threads; + const workerQueueAddr = globalAddress + emnapiAWMT.globalOffset.q; + var HEAP_DATA_VIEW = new DataView(emnapiPluginCtx.wasmMemory.buffer), GET_HEAP_DATA_VIEW = () => HEAP_DATA_VIEW.buffer === emnapiPluginCtx.wasmMemory.buffer ? HEAP_DATA_VIEW : (HEAP_DATA_VIEW = new DataView(emnapiPluginCtx.wasmMemory.buffer)); + for (;;) { + emnapiAWMT.ensureBufferFor(workerQueueAddr + 4); + while (emnapiAWMT.queueEmpty(workerQueueAddr)) { + Atomics.add(new Int32Array(emnapiAWMT.ensureBufferFor(idleThreadsAddr + 4), idleThreadsAddr, 1), 0, 1); + cond.wait(); + Atomics.sub(new Int32Array(emnapiAWMT.ensureBufferFor(idleThreadsAddr + 4), idleThreadsAddr, 1), 0, 1); + } + const q = GET_HEAP_DATA_VIEW().getUint32(workerQueueAddr, true); + if (q === exitMessageAddr) { + cond.signal(); + mutex.unlock(); + break; + } + const work = q - emnapiAWMT.offset.queue; + emnapiAWMT.queueRemove(q); + emnapiAWMT.queueInit(q); + mutex.unlock(); + const statusBuffer = new Int32Array(emnapiAWMT.ensureBufferFor(work + emnapiAWMT.offset.status + 4), work + emnapiAWMT.offset.status, 1); + if (Atomics.load(statusBuffer, 0) === 1 /* AsyncWorkStatus.Cancelled */) { + emscripten_runtime.abort('unreachable'); + } + const execute = emnapiAWMT.getExecute(work); + const env = emnapiAWMT.getEnv(work); + const data = emnapiAWMT.getData(work); + (emnapiPluginCtx.wasmTable.get(execute))(env, data); + Atomics.store(statusBuffer, 0, 2 /* AsyncWorkStatus.Completed */); + const postMessage = emnapi_shared.napiModule.postMessage; + postMessage({ + __emnapi__: { + type: 'async-work-complete', + payload: { work } + } + }); + mutex.lock(); + } + return 0; + } + /** @__sig ipp */ + function _emnapi_spawn_worker(f, globalAddress) { + if (typeof emnapi_shared.onCreateWorker !== 'function') { + throw new TypeError('`options.onCreateWorker` is not a function'); + } + const promises = []; + const args = []; + if (!('emnapi_async_worker_create' in emscripten_runtime.wasmInstance.exports)) { + throw new TypeError('`emnapi_async_worker_create` is not exported, please try to add `--export=emnapi_async_worker_create` to linker flags'); + } + args.push(emscripten_runtime.wasmInstance.exports.emnapi_async_worker_create(0, 0)); + const handleError = (e) => { + if ('message' in e && (e.message.indexOf('RuntimeError') !== -1 || e.message.indexOf('unreachable') !== -1)) { + emnapiAWMT.terminateWorkers(); + } + }; + let ret; + try { + const worker = emnapi_shared.onCreateWorker({ type: 'async-work', name: 'emnapi-async-worker' }); + const p = emscripten_runtime.PThread.loadWasmModuleToWorker(worker); + if (emscripten_runtime.ENVIRONMENT_IS_NODE) { + worker.on('error', handleError); + } + else { + worker.addEventListener('error', handleError, false); + } + emnapiAWMT.addListener(worker); + if (typeof emnapiPluginCtx.emnapiTSFN !== 'undefined') { + emnapiPluginCtx.emnapiTSFN.addListener(worker); + } + promises.push(p.then(() => { + if (typeof worker.unref === 'function') { + worker.unref(); + } + })); + ret = emnapiAWMT.pool.push(worker) - 1; + const arg = args[0]; + worker.threadBlockBase = arg; + worker.postMessage({ + __emnapi__: { + type: 'async-worker-init', + payload: { arg, func: [f, globalAddress] } + } + }); + } + catch (err) { + const arg = args[0]; + emscripten_runtime._free(arg); + throw err; + } + return ret; + } + function initWorker(startArg, func) { + if (emnapi_shared.napiModule.childThread) { + if (typeof emscripten_runtime.wasmInstance.exports.emnapi_async_worker_init !== 'function') { + throw new TypeError('`emnapi_async_worker_init` is not exported, please try to add `--export=emnapi_async_worker_init` to linker flags'); + } + emscripten_runtime.wasmInstance.exports.emnapi_async_worker_init(startArg); + (emnapiPluginCtx.wasmTable.get(func[0]))(func[1]); + } + else { + throw new Error('startThread is only available in child threads'); + } + } + emnapi_shared.napiModule.initWorker = initWorker; + + //#endregion src/core/async-work.ts + + exports._emnapi_async_worker = _emnapi_async_worker; + exports._emnapi_spawn_worker = _emnapi_spawn_worker; + exports.napi_cancel_async_work = napi_cancel_async_work; + exports.napi_create_async_work = napi_create_async_work; + exports.napi_delete_async_work = napi_delete_async_work; + exports.napi_queue_async_work = napi_queue_async_work; + + return exports; + +})({}, emnapiPluginCtx, emnapiPluginCtx); + return { + importObject: (original) => { + + Object.keys(mod).forEach(key => { + if (key.startsWith('napi_') || key.startsWith('node_api_')) { + original.napi[key] = mod[key]; + } else { + original.env[key] = mod[key]; + } + }); + } + }; +} + +//#region src/emnapi/threadsafe-function.js +function threadsafeFunction (emnapiPluginCtx) { + const { emnapiCtx, emnapiNodeBinding, _emnapi_node_emit_async_destroy: __emnapi_node_emit_async_destroy, _emnapi_node_emit_async_init: __emnapi_node_emit_async_init, _emnapi_runtime_keepalive_pop: __emnapi_runtime_keepalive_pop, _emnapi_runtime_keepalive_push: __emnapi_runtime_keepalive_push } = emnapiPluginCtx; + var mod = (function (exports, emnapi_shared, emscripten_runtime) { + + //#region src/macro.ts + + //#endregion src/macro.ts + + //#region src/threadsafe-function.ts + /* eslint-disable @stylistic/indent */ + /** + * @__deps malloc + * @__deps free + * @__deps $emnapiCtx + * @__deps $emnapiEnv + * @__deps $emnapiNodeBinding + * @__deps _emnapi_node_emit_async_destroy + * @__deps _emnapi_runtime_keepalive_pop + * @__postset + * ``` + * emnapiTSFN.init(); + * ``` + */ + const emnapiTSFN = { + _liveSet: {}, + offset: { + __size__: 0, + /* napi_ref */ resource: 0, + /* double */ async_id: 0, + /* double */ trigger_async_id: 0, + /* size_t */ queue_size: 0, + /* bool */ is_some: 0, + /* void* */ queue: 0, + // Reuse uv_async_t storage as JS-side wakeup state: pending event + scheduled drain. + async_pending: 0, + async_u_fd: 0, + /* size_t */ thread_count: 0, + /* int32_t */ state: 0, + /* atomic_uchar */ dispatch_state: 0, + /* void* */ context: 0, + /* size_t */ max_queue_size: 0, + /* napi_ref */ ref: 0, + /* napi_env */ env: 0, + /* void* */ finalize_data: 0, + /* napi_finalize */ finalize_cb: 0, + /* napi_threadsafe_function_call_js */ call_js_cb: 0, + /* bool */ handles_closing: 0, + /* bool */ async_ref: 0, + /* int32_t */ mutex: 0, + /* int32_t */ cond: 0, + }, + init() { + emnapiTSFN._liveSet = new Set(); + emnapiTSFN.offset.__size__ = 184 /* NapiTSFNOffset32.__size__ */; + emnapiTSFN.offset.resource = 0 /* NapiTSFNOffset32.async_resource_resource */; + emnapiTSFN.offset.async_id = 8 /* NapiTSFNOffset32.async_resource_async_context_async_id */; + emnapiTSFN.offset.trigger_async_id = 16 /* NapiTSFNOffset32.async_resource_async_context_trigger_async_id */; + emnapiTSFN.offset.queue_size = 60 /* NapiTSFNOffset32.queue_size */; + emnapiTSFN.offset.is_some = 24 /* NapiTSFNOffset32.async_resource_is_some */; + emnapiTSFN.offset.queue = 64 /* NapiTSFNOffset32.queue */; + emnapiTSFN.offset.async_pending = 132 /* NapiTSFNOffset32.async_pending */; + emnapiTSFN.offset.async_u_fd = 96 /* NapiTSFNOffset32.async_u_fd */; + emnapiTSFN.offset.thread_count = 136 /* NapiTSFNOffset32.thread_count */; + emnapiTSFN.offset.state = 140 /* NapiTSFNOffset32.state */; + emnapiTSFN.offset.dispatch_state = 144 /* NapiTSFNOffset32.dispatch_state */; + emnapiTSFN.offset.context = 148 /* NapiTSFNOffset32.context */; + emnapiTSFN.offset.max_queue_size = 152 /* NapiTSFNOffset32.max_queue_size */; + emnapiTSFN.offset.ref = 156 /* NapiTSFNOffset32.ref */; + emnapiTSFN.offset.env = 160 /* NapiTSFNOffset32.env */; + emnapiTSFN.offset.finalize_data = 164 /* NapiTSFNOffset32.finalize_data */; + emnapiTSFN.offset.finalize_cb = 168 /* NapiTSFNOffset32.finalize_cb */; + emnapiTSFN.offset.call_js_cb = 172 /* NapiTSFNOffset32.call_js_cb */; + emnapiTSFN.offset.handles_closing = 176 /* NapiTSFNOffset32.handles_closing */; + emnapiTSFN.offset.async_ref = 180 /* NapiTSFNOffset32.async_ref */; + emnapiTSFN.offset.mutex = 32 /* NapiTSFNOffset32.mutex */; + emnapiTSFN.offset.cond = 56 /* NapiTSFNOffset32.cond */; + emnapiTSFN.offset.mutex = emnapiTSFN.offset.mutex + 4; + if (typeof emscripten_runtime.PThread !== 'undefined') { + emscripten_runtime.PThread.unusedWorkers.forEach(emnapiTSFN.addListener); + Object.values(emscripten_runtime.PThread.pthreads).forEach(emnapiTSFN.addListener); + const __original_getNewWorker = emscripten_runtime.PThread.getNewWorker; + emscripten_runtime.PThread.getNewWorker = function () { + const r = __original_getNewWorker.apply(this, arguments); + emnapiTSFN.addListener(r); + return r; + }; + } + }, + addListener(worker) { + if (!worker) + return false; + if (worker._emnapiTSFNListener) + return true; + const handler = function (e) { + const data = emscripten_runtime.ENVIRONMENT_IS_NODE ? e : e.data; + const __emnapi__ = data.__emnapi__; + if (__emnapi__) { + const type = __emnapi__.type; + const payload = __emnapi__.payload; + if (type === 'tsfn-send') { + const pendng = payload.tsfn + emnapiTSFN.offset.async_pending; + if (Atomics.load(new Int32Array(emnapiTSFN.ensureBufferFor(pendng + 4)), pendng >>> 2) !== 0) { + emnapiTSFN.enqueue(payload.tsfn); + } + } + } + }; + const dispose = function () { + if (emscripten_runtime.ENVIRONMENT_IS_NODE) { + worker.off('message', handler); + } + else { + worker.removeEventListener('message', handler, false); + } + delete worker._emnapiTSFNListener; + }; + worker._emnapiTSFNListener = { handler, dispose }; + if (emscripten_runtime.ENVIRONMENT_IS_NODE) { + worker.on('message', handler); + } + else { + worker.addEventListener('message', handler, false); + } + return true; + }, + /** + * When another thread grows the shared WebAssembly.Memory, this agent's + * cached `wasmMemory.buffer` may still have the old shorter length + * (V8 refreshes it lazily). If a pointer derived from shared memory lies + * beyond the cached length, `wasmMemory.grow(0)` forces the agent to + * observe the current memory size and refreshes the buffer. + */ + ensureBufferFor(end) { + let buffer = emscripten_runtime.wasmMemory.buffer; + if (end > buffer.byteLength) { + emscripten_runtime.wasmMemory.grow(0); + buffer = emscripten_runtime.wasmMemory.buffer; + } + return buffer; + }, + initQueue(func) { + const size = 2 * 4; + let queue = emscripten_runtime._malloc(size); + if (!queue) + return false; + queue >>>= 0; + new Uint8Array(emnapiTSFN.ensureBufferFor(queue + size), queue, size).fill(0); + emnapiTSFN.storeSizeTypeValue(func + emnapiTSFN.offset.queue, queue, false); + return true; + }, + destroyQueue(func) { + const queue = emnapiTSFN.loadSizeTypeValue(func + emnapiTSFN.offset.queue, false); + if (queue) { + let node = emnapiTSFN.loadSizeTypeValue(queue, false); + while (node !== 0) { + const next = emnapiTSFN.loadSizeTypeValue(node + 4, false); + emscripten_runtime._free(node); + node = next; + } + emscripten_runtime._free(queue); + } + }, + pushQueue(func, data) { + const queue = emnapiTSFN.loadSizeTypeValue(func + emnapiTSFN.offset.queue, false); + const head = emnapiTSFN.loadSizeTypeValue(queue, false); + const tail = emnapiTSFN.loadSizeTypeValue(queue + 4, false); + const size = 2 * 4; + let node = emscripten_runtime._malloc(size); + if (!node) + throw new Error('OOM'); + node >>>= 0; + emnapiTSFN.storeSizeTypeValue(node, data, false); + emnapiTSFN.storeSizeTypeValue(node + 4, 0, false); + if (head === 0 && tail === 0) { + emnapiTSFN.storeSizeTypeValue(queue, node, false); + emnapiTSFN.storeSizeTypeValue(queue + 4, node, false); + } + else { + emnapiTSFN.storeSizeTypeValue(tail + 4, node, false); + emnapiTSFN.storeSizeTypeValue(queue + 4, node, false); + } + emnapiTSFN.addQueueSize(func); + }, + shiftQueue(func) { + const queue = emnapiTSFN.loadSizeTypeValue(func + emnapiTSFN.offset.queue, false); + const head = emnapiTSFN.loadSizeTypeValue(queue, false); + if (head === 0) + return 0; + const node = head; + const next = emnapiTSFN.loadSizeTypeValue(head + 4, false); + emnapiTSFN.storeSizeTypeValue(queue, next, false); + if (next === 0) { + emnapiTSFN.storeSizeTypeValue(queue + 4, 0, false); + } + emnapiTSFN.storeSizeTypeValue(node + 4, 0, false); + const value = emnapiTSFN.loadSizeTypeValue(node, false); + emscripten_runtime._free(node); + emnapiTSFN.subQueueSize(func); + return value; + }, + push(func, data, mode) { + const mutex = emnapiTSFN.getMutex(func); + const cond = emnapiTSFN.getCond(func); + const waitCondition = () => { + const queueSize = emnapiTSFN.getQueueSize(func); + const maxSize = emnapiTSFN.getMaxQueueSize(func); + return queueSize >= maxSize && maxSize > 0 && emnapiTSFN.getState(func) === 0 /* State.kOpen */; + }; + const isBrowserMain = typeof window !== 'undefined' && typeof document !== 'undefined' && !emscripten_runtime.ENVIRONMENT_IS_NODE; + let shouldDelete = false; + const ret = mutex.execute(() => { + while (waitCondition()) { + if (mode === 0 /* napi_threadsafe_function_call_mode.napi_tsfn_nonblocking */) { + return 15 /* napi_status.napi_queue_full */; + } + /** + * Browser JS main thread can not use `Atomics.wait` + * + * Related: + * https://github.com/nodejs/node/pull/32689 + * https://github.com/nodejs/node/pull/33453 + */ + if (isBrowserMain) { + return 21 /* napi_status.napi_would_deadlock */; + } + cond.wait(); + } + if (emnapiTSFN.getState(func) === 0 /* State.kOpen */) { + emnapiTSFN.pushQueue(func, data); + emnapiTSFN.send(func); + return 0 /* napi_status.napi_ok */; + } + if (emnapiTSFN.getThreadCount(func) === 0) { + return 1 /* napi_status.napi_invalid_arg */; + } + emnapiTSFN.subThreadCount(func); + if (!(emnapiTSFN.getState(func) === 2 /* State.kClosed */ && emnapiTSFN.getThreadCount(func) === 0)) { + return 16 /* napi_status.napi_closing */; + } + shouldDelete = true; + return 16 /* napi_status.napi_closing */; + }); + if (shouldDelete) { + emnapiTSFN.destroy(func); + } + return ret; + }, + getMutex(func) { + const index = func + emnapiTSFN.offset.mutex; + const mutex = { + lock() { + const isBrowserMain = typeof window !== 'undefined' && typeof document !== 'undefined' && !emscripten_runtime.ENVIRONMENT_IS_NODE; + const i32a = new Int32Array(emnapiTSFN.ensureBufferFor(index + 4), index, 1); + if (isBrowserMain) { + while (true) { + const oldValue = Atomics.compareExchange(i32a, 0, 0, 10); + if (oldValue === 0) { + return; + } + } + } + else { + while (true) { + const oldValue = Atomics.compareExchange(i32a, 0, 0, 10); + if (oldValue === 0) { + return; + } + Atomics.wait(i32a, 0, 10); + } + } + }, + /* lockAsync () { + return new Promise(resolve => { + const again = (): void => { fn() } + const fn = (): void => { + const i32a = new Int32Array(emnapiTSFN.ensureBufferFor(index + 4), index, 1) + const oldValue = Atomics.compareExchange(i32a, 0, 0, 10) + if (oldValue === 0) { + resolve() + return + } + (Atomics as any).waitAsync(i32a, 0, 10).value.then(again) + } + fn() + }) + }, */ + unlock() { + const i32a = new Int32Array(emnapiTSFN.ensureBufferFor(index + 4), index, 1); + const oldValue = Atomics.compareExchange(i32a, 0, 10, 0); + if (oldValue !== 10) { + throw new Error('Tried to unlock while not holding the mutex'); + } + Atomics.notify(i32a, 0, 1); + }, + execute(fn) { + mutex.lock(); + try { + return fn(); + } + finally { + mutex.unlock(); + } + } /* , + executeAsync (fn: () => Promise): Promise { + return mutex.lockAsync().then(() => { + const r = fn() + mutex.unlock() + return r + }, (err) => { + mutex.unlock() + throw err + }) + } */ + }; + return mutex; + }, + getCond(func) { + const index = func + emnapiTSFN.offset.cond; + const mutex = emnapiTSFN.getMutex(func); + const cond = { + wait() { + const i32a = new Int32Array(emnapiTSFN.ensureBufferFor(index + 4), index, 1); + const value = Atomics.load(i32a, 0); + mutex.unlock(); + Atomics.wait(i32a, 0, value); + mutex.lock(); + }, + /* waitAsync () { + const i32a = new Int32Array(emnapiTSFN.ensureBufferFor(index + 4), index, 1) + const value = Atomics.load(i32a, 0) + mutex.unlock() + const lock = (): Promise => mutex.lockAsync() + try { + return (Atomics as any).waitAsync(i32a, 0, value).value.then(lock, lock) + } catch (err) { + return lock() + } + }, */ + signal() { + const i32a = new Int32Array(emnapiTSFN.ensureBufferFor(index + 4), index, 1); + Atomics.add(i32a, 0, 1); + Atomics.notify(i32a, 0, 1); + } + }; + return cond; + }, + getQueueSize(func) { + return emnapiTSFN.loadSizeTypeValue(func + emnapiTSFN.offset.queue_size, true); + }, + addQueueSize(func) { + const offset = emnapiTSFN.offset.queue_size; + let arr, index; + arr = new Uint32Array(emnapiTSFN.ensureBufferFor(func + offset + 4)); + index = (func + offset) >>> 2; + Atomics.add(arr, index, 1); + }, + subQueueSize(func) { + const offset = emnapiTSFN.offset.queue_size; + let arr, index; + arr = new Uint32Array(emnapiTSFN.ensureBufferFor(func + offset + 4)); + index = (func + offset) >>> 2; + Atomics.sub(arr, index, 1); + }, + getThreadCount(func) { + return emnapiTSFN.loadSizeTypeValue(func + emnapiTSFN.offset.thread_count, true); + }, + addThreadCount(func) { + const offset = emnapiTSFN.offset.thread_count; + let arr, index; + arr = new Uint32Array(emnapiTSFN.ensureBufferFor(func + offset + 4)); + index = (func + offset) >>> 2; + Atomics.add(arr, index, 1); + }, + subThreadCount(func) { + const offset = emnapiTSFN.offset.thread_count; + let arr, index; + arr = new Uint32Array(emnapiTSFN.ensureBufferFor(func + offset + 4)); + index = (func + offset) >>> 2; + Atomics.sub(arr, index, 1); + }, + getState(func) { + return Atomics.load(new Int32Array(emnapiTSFN.ensureBufferFor(func + emnapiTSFN.offset.state + 4)), (func + emnapiTSFN.offset.state) >>> 2); + }, + setState(func, value) { + Atomics.store(new Int32Array(emnapiTSFN.ensureBufferFor(func + emnapiTSFN.offset.state + 4)), (func + emnapiTSFN.offset.state) >>> 2, value); + }, + getHandlesClosing(func) { + return Atomics.load(new Int8Array(emnapiTSFN.ensureBufferFor(func + emnapiTSFN.offset.handles_closing + 1)), (func + emnapiTSFN.offset.handles_closing)); + }, + setHandlesClosing(func, value) { + Atomics.store(new Int8Array(emnapiTSFN.ensureBufferFor(func + emnapiTSFN.offset.handles_closing + 1)), (func + emnapiTSFN.offset.handles_closing), value); + }, + getDispatchState(func) { + return Atomics.load(new Uint32Array(emnapiTSFN.ensureBufferFor(func + emnapiTSFN.offset.dispatch_state + 4)), (func + emnapiTSFN.offset.dispatch_state) >>> 2); + }, + getContext(func) { + return emnapiTSFN.loadSizeTypeValue(func + emnapiTSFN.offset.context, false); + }, + getMaxQueueSize(func) { + return emnapiTSFN.loadSizeTypeValue(func + emnapiTSFN.offset.max_queue_size, true); + }, + getEnv(func) { + return emnapiTSFN.loadSizeTypeValue(func + emnapiTSFN.offset.env, false); + }, + getCallJSCb(func) { + return emnapiTSFN.loadSizeTypeValue(func + emnapiTSFN.offset.call_js_cb, false); + }, + getRef(func) { + return emnapiTSFN.loadSizeTypeValue(func + emnapiTSFN.offset.ref, false); + }, + getResource(func) { + return emnapiTSFN.loadSizeTypeValue(func + emnapiTSFN.offset.resource, false); + }, + getFinalizeCb(func) { + return emnapiTSFN.loadSizeTypeValue(func + emnapiTSFN.offset.finalize_cb, false); + }, + getFinalizeData(func) { + return emnapiTSFN.loadSizeTypeValue(func + emnapiTSFN.offset.finalize_data, false); + }, + loadSizeTypeValue(offset, unsigned) { + let ret; + let arr; + if (unsigned) { + arr = new Uint32Array(emnapiTSFN.ensureBufferFor(offset + 4)); + ret = Atomics.load(arr, offset >>> 2); + return ret; + } + else { + arr = new Int32Array(emnapiTSFN.ensureBufferFor(offset + 4)); + ret = Atomics.load(arr, offset >>> 2); + return ret; + } + }, + storeSizeTypeValue(offset, value, unsigned) { + let arr; + if (unsigned) { + arr = new Uint32Array(emnapiTSFN.ensureBufferFor(offset + 4)); + Atomics.store(arr, offset >>> 2, value); + return undefined; + } + else { + arr = new Int32Array(emnapiTSFN.ensureBufferFor(offset + 4)); + Atomics.store(arr, offset >>> 2, value >>> 0); + return undefined; + } + }, + releaseResources(func) { + if (emnapiTSFN.getState(func) !== 2 /* State.kClosed */) { + emnapiTSFN.setState(func, 2 /* State.kClosed */); + emnapiTSFN.getEnv(func); + const envObject = emnapi_shared.emnapiEnv; + const ref = emnapiTSFN.getRef(func); + if (ref) { + emnapiCtx.getRef(ref).dispose(); + } + const resource = emnapiTSFN.getResource(func); + emnapiCtx.getRef(resource).dispose(); + emnapiTSFN.ensureBufferFor(func + emnapiTSFN.offset.is_some + 1); + var HEAP_DATA_VIEW = new DataView(emnapiPluginCtx.wasmMemory.buffer), GET_HEAP_DATA_VIEW = () => HEAP_DATA_VIEW.buffer === emnapiPluginCtx.wasmMemory.buffer ? HEAP_DATA_VIEW : (HEAP_DATA_VIEW = new DataView(emnapiPluginCtx.wasmMemory.buffer)); + GET_HEAP_DATA_VIEW().setInt8(func + emnapiTSFN.offset.is_some, 0, true); + emnapiCtx.removeCleanupHook(envObject, emnapiTSFN.cleanup, func); + envObject.unref(); + const asyncRefAddress = func + emnapiTSFN.offset.async_ref; + const asyncRefOffset = asyncRefAddress >>> 2; + const arr = new Uint32Array(emnapiTSFN.ensureBufferFor(asyncRefAddress + 4)); + if (Atomics.load(arr, asyncRefOffset) > 0) { + Atomics.store(arr, asyncRefOffset, 0); + __emnapi_runtime_keepalive_pop(); + emnapiCtx.decreaseWaitingRequestCounter(); + } + if (emnapiNodeBinding) { + const view = new DataView(emnapiTSFN.ensureBufferFor(func + emnapiTSFN.offset.trigger_async_id + 8)); + const asyncId = view.getFloat64(func + emnapiTSFN.offset.async_id, true); + const triggerAsyncId = view.getFloat64(func + emnapiTSFN.offset.trigger_async_id, true); + __emnapi_node_emit_async_destroy(asyncId, triggerAsyncId); + } + } + }, + destroy(func) { + emnapiTSFN._liveSet.delete(func); + emnapiTSFN.destroyQueue(func); + emnapiTSFN.releaseResources(func); + emscripten_runtime._free(func); + }, + emptyQueue(func) { + const drainQueue = []; + emnapiTSFN.getMutex(func).execute(() => { + while (emnapiTSFN.getQueueSize(func) > 0) { + drainQueue.push(emnapiTSFN.shiftQueue(func)); + } + }); + const callJsCb = emnapiTSFN.getCallJSCb(func); + const context = emnapiTSFN.getContext(func); + let data; + for (let i = 0; i < drainQueue.length; i++) { + data = drainQueue[i]; + if (callJsCb) { + (emnapiPluginCtx.wasmTable.get(callJsCb))(0, 0, context, data); + } + } + }, + maybeDelete(func) { + let shouldDelete = false; + emnapiTSFN.getMutex(func).execute(() => { + if (emnapiTSFN.getThreadCount(func) > 0) { + emnapiTSFN.releaseResources(func); + } + else { + shouldDelete = true; + } + }); + if (shouldDelete) { + emnapiTSFN.destroy(func); + } + }, + finalize(func) { + emnapiTSFN.getEnv(func); + const envObject = emnapi_shared.emnapiEnv; + emnapiCtx.openScope(envObject); + const finalize = emnapiTSFN.getFinalizeCb(func); + const data = emnapiTSFN.getFinalizeData(func); + const context = emnapiTSFN.getContext(func); + const f = () => { + envObject.callFinalizerInternal(0, finalize, data, context); + }; + try { + emnapiTSFN.emptyQueue(func); + if (finalize) { + if (emnapiNodeBinding) { + const resource = emnapiTSFN.getResource(func); + const resource_value = emnapiCtx.getRef(resource).get(); + const resourceObject = emnapiCtx.jsValueFromNapiValue(resource_value); + const view = new DataView(emnapiTSFN.ensureBufferFor(func + emnapiTSFN.offset.trigger_async_id + 8)); + const asyncId = view.getFloat64(func + emnapiTSFN.offset.async_id, true); + const triggerAsyncId = view.getFloat64(func + emnapiTSFN.offset.trigger_async_id, true); + emnapiNodeBinding.node.makeCallback(resourceObject, f, [], { + asyncId, + triggerAsyncId + }); + } + else { + f(); + } + } + emnapiTSFN.maybeDelete(func); + } + finally { + emnapiCtx.closeScope(envObject); + } + }, + cleanup(func) { + emnapiTSFN.closeHandlesAndMaybeDelete(func, 1); + }, + closeHandlesAndMaybeDelete(func, set_closing) { + emnapiTSFN.getEnv(func); + const envObject = emnapi_shared.emnapiEnv; + emnapiCtx.openScope(envObject); + try { + if (set_closing) { + emnapiTSFN.getMutex(func).execute(() => { + emnapiTSFN.setState(func, 1 /* State.kClosing */); + if (emnapiTSFN.getMaxQueueSize(func) > 0) { + emnapiTSFN.getCond(func).signal(); + } + }); + } + if (emnapiTSFN.getHandlesClosing(func)) { + return; + } + emnapiTSFN.setHandlesClosing(func, 1); + Atomics.store(new Int32Array(emnapiTSFN.ensureBufferFor(func + emnapiTSFN.offset.async_pending + 4)), (func + emnapiTSFN.offset.async_pending) >>> 2, 1); + emnapiCtx.features.setImmediate(() => { + emnapiTSFN.finalize(func); + }); + } + finally { + emnapiCtx.closeScope(envObject); + } + }, + dispatchOne(func) { + let data = 0; + let popped_value = false; + let has_more = false; + const mutex = emnapiTSFN.getMutex(func); + const cond = emnapiTSFN.getCond(func); + mutex.execute(() => { + if (emnapiTSFN.getState(func) === 0 /* State.kOpen */) { + let size = emnapiTSFN.getQueueSize(func); + if (size > 0) { + data = emnapiTSFN.shiftQueue(func); + popped_value = true; + const maxQueueSize = emnapiTSFN.getMaxQueueSize(func); + if (size === maxQueueSize && maxQueueSize > 0) { + cond.signal(); + } + size--; + } + if (size === 0) { + if (emnapiTSFN.getThreadCount(func) === 0) { + emnapiTSFN.setState(func, 1 /* State.kClosing */); + if (emnapiTSFN.getMaxQueueSize(func) > 0) { + cond.signal(); + } + emnapiTSFN.closeHandlesAndMaybeDelete(func, 0); + } + } + else { + has_more = true; + } + } + else { + emnapiTSFN.closeHandlesAndMaybeDelete(func, 0); + } + }); + if (popped_value) { + const env = emnapiTSFN.getEnv(func); + const envObject = emnapi_shared.emnapiEnv; + emnapiCtx.openScope(envObject); + const f = () => { + envObject.callbackIntoModule(false, () => { + const callJsCb = emnapiTSFN.getCallJSCb(func); + const ref = emnapiTSFN.getRef(func); + const js_callback = ref ? emnapiCtx.getRef(ref).get() : 0; + if (callJsCb) { + const context = emnapiTSFN.getContext(func); + (emnapiPluginCtx.wasmTable.get(callJsCb))(env, js_callback, context, data); + } + else { + const jsCallback = js_callback ? emnapiCtx.jsValueFromNapiValue(js_callback) : null; + if (typeof jsCallback === 'function') { + jsCallback(); + } + } + }); + }; + try { + if (emnapiNodeBinding) { + const resource = emnapiTSFN.getResource(func); + const resource_value = emnapiCtx.getRef(resource).get(); + const resourceObject = emnapiCtx.jsValueFromNapiValue(resource_value); + const view = new DataView(emnapiTSFN.ensureBufferFor(func + emnapiTSFN.offset.trigger_async_id + 8)); + emnapiNodeBinding.node.makeCallback(resourceObject, f, [], { + asyncId: view.getFloat64(func + emnapiTSFN.offset.async_id, true), + triggerAsyncId: view.getFloat64(func + emnapiTSFN.offset.trigger_async_id, true) + }); + } + else { + f(); + } + } + finally { + emnapiCtx.closeScope(envObject); + } + } + return has_more; + }, + dispatch(func) { + let has_more = true; + let iterations_left = 1000; + const dispatchStateAddress = func + emnapiTSFN.offset.dispatch_state; + const index = dispatchStateAddress >>> 2; + while (has_more && --iterations_left !== 0) { + Atomics.store(new Uint32Array(emnapiTSFN.ensureBufferFor(dispatchStateAddress + 4)), index, 1); + try { + has_more = emnapiTSFN.dispatchOne(func); + } + catch (err) { + // A throwing callback must not leave dispatch_state marked as + // dispatching, or every later send() would be swallowed. Re-arm + // the state and schedule another drain before rethrowing. + if (emnapiTSFN._liveSet.has(func)) { + Atomics.exchange(new Uint32Array(emnapiTSFN.ensureBufferFor(dispatchStateAddress + 4)), index, 0); + emnapiTSFN.send(func); + } + throw err; + } + if (Atomics.exchange(new Uint32Array(emnapiTSFN.ensureBufferFor(dispatchStateAddress + 4)), index, 0) !== 1) { + has_more = true; + } + } + if (has_more) { + emnapiTSFN.send(func); + } + }, + enqueue(func) { + // `pending` means a worker thread has requested a wakeup that has not + // been drained on the main thread yet. + const pending = func + emnapiTSFN.offset.async_pending; + // `scheduled` prevents queueing the same main-thread drain chain more than + // once while a previous wakeup is still in flight. + const scheduled = func + emnapiTSFN.offset.async_u_fd; + const end = Math.max(pending, scheduled) + 4; + const state = () => new Int32Array(emnapiTSFN.ensureBufferFor(end)); + if (Atomics.exchange(state(), scheduled >>> 2, 1) !== 0) { + return; + } + // Match uv_async_send-style coalescing in JS: the first turn represents + // the wakeup reaching the main thread, and the second turn performs the + // actual TSFN drain after nearby Send/Signal calls have had a chance to + // collapse into the shared AsyncProgressWorker state. + emnapiCtx.features.setImmediate(() => { + if (!emnapiTSFN._liveSet.has(func)) { + return; + } + if (Atomics.load(state(), pending >>> 2) === 0) { + Atomics.store(state(), scheduled >>> 2, 0); + return; + } + emnapiCtx.features.setImmediate(() => { + // After destroy(), the func address is freed. Skip the atomics + // on that address entirely to avoid use-after-free (JS-side + // lifecycle check must run before touching the state words). + if (!emnapiTSFN._liveSet.has(func)) { + return; + } + try { + // Consume the coalesced wakeup once, then let dispatch() observe any + // queue mutations through dispatch_state like the C implementation. + if (Atomics.exchange(state(), pending >>> 2, 0) === 0) { + return; + } + emnapiTSFN.dispatch(func); + } + finally { + // Allow a later wakeup to schedule a new drain chain. If another + // worker-thread send raced with this drain, enqueue one more turn. + if (emnapiTSFN._liveSet.has(func)) { + Atomics.store(state(), scheduled >>> 2, 0); + if (Atomics.load(state(), pending >>> 2) !== 0) { + emnapiTSFN.enqueue(func); + } + } + } + }); + }); + }, + send(func) { + const dispatchStateAddress = func + emnapiTSFN.offset.dispatch_state; + const current_state = Atomics.or(new Uint32Array(emnapiTSFN.ensureBufferFor(dispatchStateAddress + 4)), dispatchStateAddress >>> 2, 1 << 1); + if ((current_state & 1) === 1) { + return; + } + const pendng = func + emnapiTSFN.offset.async_pending; + // A wakeup is already pending, so this send only needs to leave the queued + // work in the TSFN queue and let the existing drain pick it up. + if (Atomics.load(new Int32Array(emnapiTSFN.ensureBufferFor(pendng + 4)), pendng >>> 2) !== 0) { + return; + } + if (Atomics.exchange(new Int32Array(emnapiTSFN.ensureBufferFor(pendng + 4)), pendng >>> 2, 1) === 0) { + if ((typeof emscripten_runtime.ENVIRONMENT_IS_PTHREAD !== 'undefined') && emscripten_runtime.ENVIRONMENT_IS_PTHREAD) { + // Worker threads only post a wakeup token. Main-thread draining is + // serialized by enqueue() once the message is received. + postMessage({ + __emnapi__: { + type: 'tsfn-send', + payload: { + tsfn: func + } + } + }); + } + else { + // On the main thread we can skip the cross-thread hop and schedule the + // coalesced drain chain directly. + emnapiTSFN.enqueue(func); + } + } + } + }; + emnapiTSFN.init(); + emnapiPluginCtx.emnapiTSFN = emnapiTSFN; + /** + * @__deps _emnapi_node_emit_async_init + * @__deps _emnapi_runtime_keepalive_push + * @__sig ippppppppppp + */ + function napi_create_threadsafe_function(env, func, async_resource, async_resource_name, max_queue_size, initial_thread_count, thread_finalize_data, thread_finalize_cb, context, call_js_cb, result) { + if (!env) + return 1 /* napi_status.napi_invalid_arg */; + // @ts-expect-error + const envObject = emnapi_shared.emnapiEnv; + envObject.checkGCAccess(); + if (!async_resource_name) + return envObject.setLastError(1 /* napi_status.napi_invalid_arg */); + max_queue_size >>>= 0; + initial_thread_count >>>= 0; + env >>>= 0; + thread_finalize_data >>>= 0; + thread_finalize_cb >>>= 0; + context >>>= 0; + call_js_cb >>>= 0; + max_queue_size = max_queue_size >>> 0; + initial_thread_count = initial_thread_count >>> 0; + if (initial_thread_count === 0) { + return envObject.setLastError(1 /* napi_status.napi_invalid_arg */); + } + if (!result) + return envObject.setLastError(1 /* napi_status.napi_invalid_arg */); + let ref = 0; + func >>>= 0; + if (!func) { + if (!call_js_cb) + return envObject.setLastError(1 /* napi_status.napi_invalid_arg */); + } + else { + const funcValue = emnapiCtx.jsValueFromNapiValue(func); + if (typeof funcValue !== 'function') { + return envObject.setLastError(1 /* napi_status.napi_invalid_arg */); + } + ref = emnapiCtx.createReference(envObject, func, 1, 1 /* ReferenceOwnership.kUserland */).id; + } + let asyncResourceObject; + if (async_resource) { + asyncResourceObject = emnapiCtx.jsValueFromNapiValue(async_resource); + if (asyncResourceObject == null) { + return envObject.setLastError(2 /* napi_status.napi_object_expected */); + } + asyncResourceObject = Object(asyncResourceObject); + } + else { + asyncResourceObject = {}; + } + const resource = emnapiCtx.napiValueFromJsValue(asyncResourceObject); + let asyncResourceName = emnapiCtx.jsValueFromNapiValue(async_resource_name); + if (typeof asyncResourceName === 'symbol') { + return envObject.setLastError(3 /* napi_status.napi_string_expected */); + } + asyncResourceName = String(asyncResourceName); + const resource_name = emnapiCtx.napiValueFromJsValue(asyncResourceName); + // tsfn create + const sizeofTSFN = emnapiTSFN.offset.__size__; + let tsfn = emscripten_runtime._malloc(sizeofTSFN); + if (!tsfn) + return envObject.setLastError(9 /* napi_status.napi_generic_failure */); + tsfn >>>= 0; + new Uint8Array(emnapiTSFN.ensureBufferFor(tsfn + sizeofTSFN)).subarray(tsfn, tsfn + sizeofTSFN).fill(0); + const resourceRef = emnapiCtx.createReference(envObject, resource, 1, 1 /* ReferenceOwnership.kUserland */); + const resource_ = resourceRef.id; + var HEAP_DATA_VIEW = new DataView(emnapiPluginCtx.wasmMemory.buffer), GET_HEAP_DATA_VIEW = () => HEAP_DATA_VIEW.buffer === emnapiPluginCtx.wasmMemory.buffer ? HEAP_DATA_VIEW : (HEAP_DATA_VIEW = new DataView(emnapiPluginCtx.wasmMemory.buffer)); + GET_HEAP_DATA_VIEW().setUint32(tsfn + emnapiTSFN.offset.resource, resource_, true); + if (!emnapiTSFN.initQueue(tsfn)) { + emscripten_runtime._free(tsfn); + resourceRef.dispose(); + return envObject.setLastError(9 /* napi_status.napi_generic_failure */); + } + __emnapi_node_emit_async_init(resource, resource_name, -1, tsfn + emnapiTSFN.offset.async_id); + GET_HEAP_DATA_VIEW().setInt8(tsfn + emnapiTSFN.offset.is_some, 1, true); + GET_HEAP_DATA_VIEW().setUint32(tsfn + emnapiTSFN.offset.thread_count, initial_thread_count, true); + GET_HEAP_DATA_VIEW().setUint32(tsfn + emnapiTSFN.offset.context, context, true); + GET_HEAP_DATA_VIEW().setUint32(tsfn + emnapiTSFN.offset.max_queue_size, max_queue_size, true); + GET_HEAP_DATA_VIEW().setUint32(tsfn + emnapiTSFN.offset.ref, ref, true); + GET_HEAP_DATA_VIEW().setUint32(tsfn + emnapiTSFN.offset.env, env, true); + GET_HEAP_DATA_VIEW().setUint32(tsfn + emnapiTSFN.offset.finalize_data, thread_finalize_data, true); + GET_HEAP_DATA_VIEW().setUint32(tsfn + emnapiTSFN.offset.finalize_cb, thread_finalize_cb, true); + GET_HEAP_DATA_VIEW().setUint32(tsfn + emnapiTSFN.offset.call_js_cb, call_js_cb, true); + emnapiCtx.addCleanupHook(envObject, emnapiTSFN.cleanup, tsfn); + emnapiTSFN._liveSet.add(tsfn); + envObject.ref(); + __emnapi_runtime_keepalive_push(); + emnapiCtx.increaseWaitingRequestCounter(); + GET_HEAP_DATA_VIEW().setUint32(tsfn + emnapiTSFN.offset.async_ref, 1, true); + result >>>= 0; + GET_HEAP_DATA_VIEW().setUint32(result, tsfn, true); + return envObject.clearLastError(); + } + /** @__sig ipp */ + function napi_get_threadsafe_function_context(func, result) { + if (!func || !result) { + emscripten_runtime.abort(); + return 1 /* napi_status.napi_invalid_arg */; + } + func >>>= 0; + result >>>= 0; + const context = emnapiTSFN.getContext(func); + var HEAP_DATA_VIEW = new DataView(emnapiPluginCtx.wasmMemory.buffer), GET_HEAP_DATA_VIEW = () => HEAP_DATA_VIEW.buffer === emnapiPluginCtx.wasmMemory.buffer ? HEAP_DATA_VIEW : (HEAP_DATA_VIEW = new DataView(emnapiPluginCtx.wasmMemory.buffer)); + GET_HEAP_DATA_VIEW().setUint32(result, context, true); + return 0 /* napi_status.napi_ok */; + } + /** @__sig ippi */ + function napi_call_threadsafe_function(func, data, mode) { + if (!func) { + emscripten_runtime.abort(); + return 1 /* napi_status.napi_invalid_arg */; + } + func >>>= 0; + data >>>= 0; + return emnapiTSFN.push(func, data, mode); + } + /** @__sig ip */ + function napi_acquire_threadsafe_function(func) { + if (!func) { + emscripten_runtime.abort(); + return 1 /* napi_status.napi_invalid_arg */; + } + func >>>= 0; + const mutex = emnapiTSFN.getMutex(func); + return mutex.execute(() => { + if (emnapiTSFN.getState(func) === 0 /* State.kOpen */) { + emnapiTSFN.addThreadCount(func); + return 0 /* napi_status.napi_ok */; + } + return 16 /* napi_status.napi_closing */; + }); + } + /** @__sig ipi */ + function napi_release_threadsafe_function(func, mode) { + if (!func) { + emscripten_runtime.abort(); + return 1 /* napi_status.napi_invalid_arg */; + } + func >>>= 0; + const mutex = emnapiTSFN.getMutex(func); + const cond = emnapiTSFN.getCond(func); + let shouldDelete = false; + const ret = mutex.execute(() => { + if (emnapiTSFN.getThreadCount(func) === 0) { + return 1 /* napi_status.napi_invalid_arg */; + } + emnapiTSFN.subThreadCount(func); + if (emnapiTSFN.getThreadCount(func) === 0 || mode === 1 /* napi_threadsafe_function_release_mode.napi_tsfn_abort */) { + if (emnapiTSFN.getState(func) === 0 /* State.kOpen */) { + if (mode === 1 /* napi_threadsafe_function_release_mode.napi_tsfn_abort */) { + emnapiTSFN.setState(func, 1 /* State.kClosing */); + } + if (emnapiTSFN.getState(func) === 1 /* State.kClosing */ && emnapiTSFN.getMaxQueueSize(func) > 0) { + cond.signal(); + } + emnapiTSFN.send(func); + } + } + if (!(emnapiTSFN.getState(func) === 2 /* State.kClosed */ && emnapiTSFN.getThreadCount(func) === 0)) { + return 0 /* napi_status.napi_ok */; + } + shouldDelete = true; + return 0 /* napi_status.napi_ok */; + }); + if (shouldDelete) { + emnapiTSFN.destroy(func); + } + return ret; + } + /** + * @__deps _emnapi_runtime_keepalive_pop + * @__sig ipp + */ + function napi_unref_threadsafe_function(env, func) { + if (!func) { + emscripten_runtime.abort(); + return 1 /* napi_status.napi_invalid_arg */; + } + func >>>= 0; + const asyncRefAddress = func + emnapiTSFN.offset.async_ref; + const asyncRefOffset = asyncRefAddress >>> 2; + const arr = new Uint32Array(emnapiTSFN.ensureBufferFor(asyncRefAddress + 4)); + const currentValue = Atomics.load(arr, asyncRefOffset); + if (currentValue > 0) { + Atomics.store(arr, asyncRefOffset, currentValue - 1); + if (currentValue === 1) { + __emnapi_runtime_keepalive_pop(); + emnapiCtx.decreaseWaitingRequestCounter(); + } + } + return 0 /* napi_status.napi_ok */; + } + /** + * @__deps _emnapi_runtime_keepalive_push + * @__sig ipp + */ + function napi_ref_threadsafe_function(env, func) { + if (!func) { + emscripten_runtime.abort(); + return 1 /* napi_status.napi_invalid_arg */; + } + func >>>= 0; + const asyncRefAddress = func + emnapiTSFN.offset.async_ref; + const asyncRefOffset = asyncRefAddress >>> 2; + const arr = new Uint32Array(emnapiTSFN.ensureBufferFor(asyncRefAddress + 4)); + const currentValue = Atomics.load(arr, asyncRefOffset); + if (!currentValue) { + __emnapi_runtime_keepalive_push(); + emnapiCtx.increaseWaitingRequestCounter(); + } + Atomics.store(arr, asyncRefOffset, currentValue + 1); + return 0 /* napi_status.napi_ok */; + } + + //#endregion src/threadsafe-function.ts + + exports.napi_acquire_threadsafe_function = napi_acquire_threadsafe_function; + exports.napi_call_threadsafe_function = napi_call_threadsafe_function; + exports.napi_create_threadsafe_function = napi_create_threadsafe_function; + exports.napi_get_threadsafe_function_context = napi_get_threadsafe_function_context; + exports.napi_ref_threadsafe_function = napi_ref_threadsafe_function; + exports.napi_release_threadsafe_function = napi_release_threadsafe_function; + exports.napi_unref_threadsafe_function = napi_unref_threadsafe_function; + + return exports; + +})({}, emnapiPluginCtx, emnapiPluginCtx); + return { + importObject: (original) => { + Object.assign(original.napi, mod); + } + }; +} + +exports.emnapiAsyncWorkPlugin = asyncWork; +exports.emnapiTSFNPlugin = threadsafeFunction; diff --git a/dg-ui/node_modules/@tailwindcss/oxide-wasm32-wasi/node_modules/@napi-rs/wasm-runtime/dist/emnapi-plugins.js b/dg-ui/node_modules/@tailwindcss/oxide-wasm32-wasi/node_modules/@napi-rs/wasm-runtime/dist/emnapi-plugins.js new file mode 100644 index 0000000..44f883f --- /dev/null +++ b/dg-ui/node_modules/@tailwindcss/oxide-wasm32-wasi/node_modules/@napi-rs/wasm-runtime/dist/emnapi-plugins.js @@ -0,0 +1,1823 @@ +//#region src/emnapi/async-work.js +function asyncWork (emnapiPluginCtx) { + const { emnapiCtx, emnapiNodeBinding, emnapiAsyncWorkPoolSize } = emnapiPluginCtx; + var mod = (function (exports, emnapi_shared, emscripten_runtime) { + + //#region src/async-work.ts + /** + * @__deps $emnapiCtx + * @__deps $emnapiEnv + * @__deps $emnapiNodeBinding + * @__deps $emnapiAsyncWorkPoolSize + * @__postset + * ``` + * emnapiAWST.init(); + * ``` + */ + var emnapiAWST = { + idGen: {}, + values: [undefined], + queued: new Set(), + pending: [], + init: function () { + const idGen = { + nextId: 1, + list: [], + generate: function () { + let id; + if (idGen.list.length) { + id = idGen.list.shift(); + } + else { + id = idGen.nextId; + idGen.nextId++; + } + return id; + }, + reuse: function (id) { + idGen.list.push(id); + } + }; + emnapiAWST.idGen = idGen; + emnapiAWST.values = [undefined]; + emnapiAWST.queued = new Set(); + emnapiAWST.pending = []; + }, + create: function (env, resource, resourceName, execute, complete, data) { + let asyncId = 0; + let triggerAsyncId = 0; + if (emnapiNodeBinding) { + const asyncContext = emnapiNodeBinding.node.emitAsyncInit(resource, resourceName, -1); + asyncId = asyncContext.asyncId; + triggerAsyncId = asyncContext.triggerAsyncId; + } + const id = emnapiAWST.idGen.generate(); + emnapiAWST.values[id] = { + env, + id, + resource, + asyncId, + triggerAsyncId, + status: 0, + execute, + complete, + data + }; + return id; + }, + callComplete: function (work, status) { + const complete = work.complete; + const env = work.env; + const data = work.data; + const callback = () => { + if (!complete) + return; + const envObject = emnapi_shared.emnapiEnv; + const scope = emnapiCtx.openScope(envObject); + try { + envObject.callbackIntoModule(true, () => { + (emnapiPluginCtx.wasmTable.get(complete))(env, status, data); + }); + } + finally { + emnapiCtx.closeScope(envObject, scope); + } + }; + if (emnapiNodeBinding) { + emnapiNodeBinding.node.makeCallback(work.resource, callback, [], { + asyncId: work.asyncId, + triggerAsyncId: work.triggerAsyncId + }); + } + else { + callback(); + } + }, + queue: function (id) { + const work = emnapiAWST.values[id]; + if (!work) + return; + if (work.status === 0) { + work.status = 1; + if (emnapiAWST.queued.size >= (Math.abs(emnapiAsyncWorkPoolSize) || 4)) { + emnapiAWST.pending.push(id); + return; + } + emnapiAWST.queued.add(id); + const env = work.env; + const data = work.data; + const execute = work.execute; + work.status = 2; + emnapiCtx.features.setImmediate(() => { + (emnapiPluginCtx.wasmTable.get(execute))(env, data); + emnapiAWST.queued.delete(id); + work.status = 3; + emnapiCtx.features.setImmediate(() => { + emnapiAWST.callComplete(work, 0 /* napi_status.napi_ok */); + }); + if (emnapiAWST.pending.length > 0) { + const nextWorkId = emnapiAWST.pending.shift(); + emnapiAWST.values[nextWorkId].status = 0; + emnapiAWST.queue(nextWorkId); + } + }); + } + }, + cancel: function (id) { + const index = emnapiAWST.pending.indexOf(id); + if (index !== -1) { + const work = emnapiAWST.values[id]; + if (work && (work.status === 1)) { + work.status = 4; + emnapiAWST.pending.splice(index, 1); + emnapiCtx.features.setImmediate(() => { + emnapiAWST.callComplete(work, 11 /* napi_status.napi_cancelled */); + }); + return 0 /* napi_status.napi_ok */; + } + else { + return 9 /* napi_status.napi_generic_failure */; + } + } + return 9 /* napi_status.napi_generic_failure */; + }, + remove: function (id) { + const work = emnapiAWST.values[id]; + if (!work) + return; + if (emnapiNodeBinding) { + emnapiNodeBinding.node.emitAsyncDestroy({ + asyncId: work.asyncId, + triggerAsyncId: work.triggerAsyncId + }); + } + emnapiAWST.values[id] = undefined; + emnapiAWST.idGen.reuse(id); + } + }; + + //#endregion src/async-work.ts + + //#region src/macro.ts + + //#endregion src/macro.ts + + //#region src/core/async-work.ts + const { + // onCreateWorker, napiModule, singleThreadAsyncWork, _emnapi_async_work_pool_size, + // PThread, ENVIRONMENT_IS_NODE, ENVIRONMENT_IS_PTHREAD, wasmInstance, _free, wasmMemory, _malloc, + _emnapi_node_emit_async_init, _emnapi_node_emit_async_destroy, _emnapi_runtime_keepalive_pop, _emnapi_runtime_keepalive_push } = emnapiPluginCtx; + var emnapiAWMT = { + pool: [], + workerReady: null, + globalAddress: 0, + globalOffset: { + idle_threads: 0, + q: 1 * 4, + next: 1 * 4, + prev: 2 * 4, + mutex: 3 * 4, + cond: 4 * 4, + exit_message: 5 * 4, + end: 7 * 4 + }, + offset: { + /* napi_ref */ resource: 0, + /* double */ async_id: 8, + /* double */ trigger_async_id: 16, + /* napi_env */ env: 24, + /* int32_t */ status: 1 * 4 + 24, // 0 for pending, 1 for cancelled, 2 for completed + queue: 2 * 4 + 24, + queue_next: 2 * 4 + 24, + queue_prev: 3 * 4 + 24, + /* void* */ data: 4 * 4 + 24, + /* napi_async_execute_callback */ execute: 5 * 4 + 24, + /* napi_async_complete_callback */ complete: 6 * 4 + 24, + end: 7 * 4 + 24 + }, + /** + * When another thread grows the shared WebAssembly.Memory, this agent's + * cached `wasmMemory.buffer` may still have the old shorter length + * (V8 refreshes it lazily). If a pointer derived from shared memory lies + * beyond the cached length, `wasmMemory.grow(0)` forces the agent to + * observe the current memory size and refreshes the buffer. + */ + ensureBufferFor(end) { + let buffer = emscripten_runtime.wasmMemory.buffer; + if (end > buffer.byteLength) { + emscripten_runtime.wasmMemory.grow(0); + buffer = emscripten_runtime.wasmMemory.buffer; + } + return buffer; + }, + init() { + emnapiAWMT.pool = []; + emnapiAWMT.workerReady = null; + if (typeof emscripten_runtime.PThread !== 'undefined') { + emscripten_runtime.PThread.unusedWorkers.forEach(emnapiAWMT.addListener); + Object.values(emscripten_runtime.PThread.pthreads).forEach(emnapiAWMT.addListener); + const __original_getNewWorker = emscripten_runtime.PThread.getNewWorker; + emscripten_runtime.PThread.getNewWorker = function () { + const r = __original_getNewWorker.apply(this, arguments); + emnapiAWMT.addListener(r); + return r; + }; + } + }, + addListener(worker) { + if (!worker) + return false; + if (worker._emnapiAWMTListener) + return true; + const handler = function (e) { + const data = emscripten_runtime.ENVIRONMENT_IS_NODE ? e : e.data; + const __emnapi__ = data.__emnapi__; + if (__emnapi__) { + const type = __emnapi__.type; + const payload = __emnapi__.payload; + if (type === 'async-work-complete') { + emnapiAWMT.callComplete(payload.work, 0 /* napi_status.napi_ok */); + } + } + }; + const dispose = function () { + if (emscripten_runtime.ENVIRONMENT_IS_NODE) { + worker.off('message', handler); + } + else { + worker.removeEventListener('message', handler, false); + } + delete worker._emnapiAWMTListener; + }; + worker._emnapiAWMTListener = { handler, dispose }; + if (emscripten_runtime.ENVIRONMENT_IS_NODE) { + worker.on('message', handler); + } + else { + worker.addEventListener('message', handler, false); + } + return true; + }, + initGlobal() { + if (!emnapiAWMT.globalAddress) { + emnapiAWMT.globalAddress = emscripten_runtime._malloc(emnapiAWMT.globalOffset.end); + emnapiAWMT.globalAddress >>>= 0; + const size = emnapiAWMT.globalOffset.end; + const addr = emnapiAWMT.globalAddress; + new Uint8Array(emnapiAWMT.ensureBufferFor(addr + size), addr, size).fill(0); + emnapiAWMT.queueInit(emnapiAWMT.globalAddress + emnapiAWMT.globalOffset.q); + emnapiAWMT.queueInit(emnapiAWMT.globalAddress + emnapiAWMT.globalOffset.exit_message); + } + }, + terminateWorkers() { + emnapiAWMT.pool.forEach(w => { + w._emnapiAWMTListener?.dispose(); + w._emnapiTSFNListener?.dispose(); + w.terminate(); + }); + emnapiAWMT.pool.length = 0; + }, + initWorkers(n) { + if (emscripten_runtime.ENVIRONMENT_IS_PTHREAD) { + return emnapiAWMT.workerReady || (emnapiAWMT.workerReady = Promise.resolve()); + } + if (emnapiAWMT.workerReady) + return emnapiAWMT.workerReady; + if (!('emnapi_async_worker_create' in emscripten_runtime.wasmInstance.exports)) { + throw new TypeError('`emnapi_async_worker_create` is not exported, please try to add `--export=emnapi_async_worker_create` to linker flags'); + } + const emnapi_async_worker_create = emscripten_runtime.wasmInstance.exports.emnapi_async_worker_create; + const args = []; + emnapiAWMT.initGlobal(); + for (let i = 0; i < n; ++i) { + args.push(emnapi_async_worker_create(1, emnapiAWMT.globalAddress)); + } + const promises = args.map(index => { + if (index === 0) { + return Promise.reject(new Error('Failed to create async worker')); + } + let worker; + if (index < 0) { + worker = emnapiAWMT.pool[-index - 1]; + if (worker) + return worker.whenLoaded; + } + index >>>= 0; + const tidOffset = 20; + const view = new DataView(emnapiAWMT.ensureBufferFor(index + tidOffset + 4)); + const tid = view.getInt32(index + tidOffset, true); + worker = emscripten_runtime.PThread.pthreads[tid]; + return worker.whenLoaded; + }); + emnapiAWMT.workerReady = Promise.all(promises); + return emnapiAWMT.workerReady; + }, + getResource(work) { + emnapiAWMT.ensureBufferFor(work + emnapiAWMT.offset.resource + 4); + var HEAP_DATA_VIEW = new DataView(emnapiPluginCtx.wasmMemory.buffer), GET_HEAP_DATA_VIEW = () => HEAP_DATA_VIEW.buffer === emnapiPluginCtx.wasmMemory.buffer ? HEAP_DATA_VIEW : (HEAP_DATA_VIEW = new DataView(emnapiPluginCtx.wasmMemory.buffer)); + return GET_HEAP_DATA_VIEW().getUint32(work + emnapiAWMT.offset.resource, true); + }, + getExecute(work) { + emnapiAWMT.ensureBufferFor(work + emnapiAWMT.offset.execute + 4); + var HEAP_DATA_VIEW = new DataView(emnapiPluginCtx.wasmMemory.buffer), GET_HEAP_DATA_VIEW = () => HEAP_DATA_VIEW.buffer === emnapiPluginCtx.wasmMemory.buffer ? HEAP_DATA_VIEW : (HEAP_DATA_VIEW = new DataView(emnapiPluginCtx.wasmMemory.buffer)); + return GET_HEAP_DATA_VIEW().getUint32(work + emnapiAWMT.offset.execute, true); + }, + getComplete(work) { + emnapiAWMT.ensureBufferFor(work + emnapiAWMT.offset.complete + 4); + var HEAP_DATA_VIEW = new DataView(emnapiPluginCtx.wasmMemory.buffer), GET_HEAP_DATA_VIEW = () => HEAP_DATA_VIEW.buffer === emnapiPluginCtx.wasmMemory.buffer ? HEAP_DATA_VIEW : (HEAP_DATA_VIEW = new DataView(emnapiPluginCtx.wasmMemory.buffer)); + return GET_HEAP_DATA_VIEW().getUint32(work + emnapiAWMT.offset.complete, true); + }, + getEnv(work) { + emnapiAWMT.ensureBufferFor(work + emnapiAWMT.offset.env + 4); + var HEAP_DATA_VIEW = new DataView(emnapiPluginCtx.wasmMemory.buffer), GET_HEAP_DATA_VIEW = () => HEAP_DATA_VIEW.buffer === emnapiPluginCtx.wasmMemory.buffer ? HEAP_DATA_VIEW : (HEAP_DATA_VIEW = new DataView(emnapiPluginCtx.wasmMemory.buffer)); + return GET_HEAP_DATA_VIEW().getUint32(work + emnapiAWMT.offset.env, true); + }, + getData(work) { + emnapiAWMT.ensureBufferFor(work + emnapiAWMT.offset.data + 4); + var HEAP_DATA_VIEW = new DataView(emnapiPluginCtx.wasmMemory.buffer), GET_HEAP_DATA_VIEW = () => HEAP_DATA_VIEW.buffer === emnapiPluginCtx.wasmMemory.buffer ? HEAP_DATA_VIEW : (HEAP_DATA_VIEW = new DataView(emnapiPluginCtx.wasmMemory.buffer)); + return GET_HEAP_DATA_VIEW().getUint32(work + emnapiAWMT.offset.data, true); + }, + getMutex() { + const index = emnapiAWMT.globalAddress + emnapiAWMT.globalOffset.mutex; + const mutex = { + lock() { + const isBrowserMain = typeof window !== 'undefined' && typeof document !== 'undefined' && !emscripten_runtime.ENVIRONMENT_IS_NODE; + const i32a = new Int32Array(emnapiAWMT.ensureBufferFor(index + 4), index, 1); + if (isBrowserMain) { + while (true) { + const oldValue = Atomics.compareExchange(i32a, 0, 0, 10); + if (oldValue === 0) { + return; + } + } + } + else { + while (true) { + const oldValue = Atomics.compareExchange(i32a, 0, 0, 10); + if (oldValue === 0) { + return; + } + Atomics.wait(i32a, 0, 10); + } + } + }, + unlock() { + const i32a = new Int32Array(emnapiAWMT.ensureBufferFor(index + 4), index, 1); + const oldValue = Atomics.compareExchange(i32a, 0, 10, 0); + if (oldValue !== 10) { + throw new Error('Tried to unlock while not holding the mutex'); + } + Atomics.notify(i32a, 0, 1); + }, + execute(fn) { + mutex.lock(); + try { + return fn(); + } + finally { + mutex.unlock(); + } + } + }; + return mutex; + }, + getCond() { + const index = emnapiAWMT.globalAddress + emnapiAWMT.globalOffset.cond; + const mutex = emnapiAWMT.getMutex(); + const cond = { + wait() { + const i32a = new Int32Array(emnapiAWMT.ensureBufferFor(index + 4), index, 1); + const value = Atomics.load(i32a, 0); + mutex.unlock(); + Atomics.wait(i32a, 0, value); + mutex.lock(); + }, + signal() { + const i32a = new Int32Array(emnapiAWMT.ensureBufferFor(index + 4), index, 1); + Atomics.add(i32a, 0, 1); + Atomics.notify(i32a, 0, 1); + } + }; + return cond; + }, + queueInit(q) { + emnapiAWMT.ensureBufferFor(q + 4 + 4); + var HEAP_DATA_VIEW = new DataView(emnapiPluginCtx.wasmMemory.buffer), GET_HEAP_DATA_VIEW = () => HEAP_DATA_VIEW.buffer === emnapiPluginCtx.wasmMemory.buffer ? HEAP_DATA_VIEW : (HEAP_DATA_VIEW = new DataView(emnapiPluginCtx.wasmMemory.buffer)); + GET_HEAP_DATA_VIEW().setUint32(q, q, true); + GET_HEAP_DATA_VIEW().setUint32(q + 4, q, true); + }, + queueInsertTail(h, q) { + emnapiAWMT.ensureBufferFor(h + 4 + 4); + emnapiAWMT.ensureBufferFor(q + 4 + 4); + var HEAP_DATA_VIEW = new DataView(emnapiPluginCtx.wasmMemory.buffer), GET_HEAP_DATA_VIEW = () => HEAP_DATA_VIEW.buffer === emnapiPluginCtx.wasmMemory.buffer ? HEAP_DATA_VIEW : (HEAP_DATA_VIEW = new DataView(emnapiPluginCtx.wasmMemory.buffer)); + GET_HEAP_DATA_VIEW().setUint32(q, h, true); + const tempValue = GET_HEAP_DATA_VIEW().getUint32(h + 4, true); + GET_HEAP_DATA_VIEW().setUint32(q + 4, tempValue, true); + const qprev = GET_HEAP_DATA_VIEW().getUint32(q + 4, true); + GET_HEAP_DATA_VIEW().setUint32(qprev, q, true); + GET_HEAP_DATA_VIEW().setUint32(h + 4, q, true); + }, + queueRemove(q) { + emnapiAWMT.ensureBufferFor(q + 4 + 4); + var HEAP_DATA_VIEW = new DataView(emnapiPluginCtx.wasmMemory.buffer), GET_HEAP_DATA_VIEW = () => HEAP_DATA_VIEW.buffer === emnapiPluginCtx.wasmMemory.buffer ? HEAP_DATA_VIEW : (HEAP_DATA_VIEW = new DataView(emnapiPluginCtx.wasmMemory.buffer)); + const qprev = GET_HEAP_DATA_VIEW().getUint32(q + 4, true); + const qnext = GET_HEAP_DATA_VIEW().getUint32(q, true); + GET_HEAP_DATA_VIEW().setUint32(qprev, qnext, true); + GET_HEAP_DATA_VIEW().setUint32(qnext + 4, qprev, true); + }, + queueEmpty(q) { + emnapiAWMT.ensureBufferFor(q + 4); + var HEAP_DATA_VIEW = new DataView(emnapiPluginCtx.wasmMemory.buffer), GET_HEAP_DATA_VIEW = () => HEAP_DATA_VIEW.buffer === emnapiPluginCtx.wasmMemory.buffer ? HEAP_DATA_VIEW : (HEAP_DATA_VIEW = new DataView(emnapiPluginCtx.wasmMemory.buffer)); + // eslint-disable-next-line eqeqeq + return q == GET_HEAP_DATA_VIEW().getUint32(q, true); + }, + scheduleWork: function (work) { + if (!emnapiAWMT.workerReady?.ready) { + emnapiAWMT.initWorkers(emnapi_shared._emnapi_async_work_pool_size()).then(() => { + emnapiAWMT.workerReady.ready = true; + }).catch((err) => { + emnapiAWMT.workerReady = null; + throw err; + }); + } + _emnapi_runtime_keepalive_push(); + emnapiCtx.increaseWaitingRequestCounter(); + const statusBuffer = new Int32Array(emnapiAWMT.ensureBufferFor(work + emnapiAWMT.offset.status + 4), work + emnapiAWMT.offset.status, 1); + Atomics.store(statusBuffer, 0, 0 /* AsyncWorkStatus.Pending */); + const mutex = emnapiAWMT.getMutex(); + const cond = emnapiAWMT.getCond(); + mutex.lock(); + try { + emnapiAWMT.queueInsertTail(emnapiAWMT.globalAddress + emnapiAWMT.globalOffset.q, work + emnapiAWMT.offset.queue); + } + catch (err) { + _emnapi_runtime_keepalive_pop(); + emnapiCtx.decreaseWaitingRequestCounter(); + mutex.unlock(); + throw err; + } + emnapiAWMT.ensureBufferFor(emnapiAWMT.globalAddress + emnapiAWMT.globalOffset.idle_threads + 4); + var HEAP_DATA_VIEW = new DataView(emnapiPluginCtx.wasmMemory.buffer), GET_HEAP_DATA_VIEW = () => HEAP_DATA_VIEW.buffer === emnapiPluginCtx.wasmMemory.buffer ? HEAP_DATA_VIEW : (HEAP_DATA_VIEW = new DataView(emnapiPluginCtx.wasmMemory.buffer)); + if (GET_HEAP_DATA_VIEW().getUint32(emnapiAWMT.globalAddress + emnapiAWMT.globalOffset.idle_threads, true) > 0) { + cond.signal(); + } + mutex.unlock(); + }, + cancelWork(work) { + let cancelled = false; + emnapiAWMT.getMutex().execute(() => { + emnapiAWMT.ensureBufferFor(work + emnapiAWMT.offset.status + 4); + var HEAP_DATA_VIEW = new DataView(emnapiPluginCtx.wasmMemory.buffer), GET_HEAP_DATA_VIEW = () => HEAP_DATA_VIEW.buffer === emnapiPluginCtx.wasmMemory.buffer ? HEAP_DATA_VIEW : (HEAP_DATA_VIEW = new DataView(emnapiPluginCtx.wasmMemory.buffer)); + cancelled = !emnapiAWMT.queueEmpty(work + emnapiAWMT.offset.queue) && GET_HEAP_DATA_VIEW().getInt32(work + emnapiAWMT.offset.status, true) !== 2 /* AsyncWorkStatus.Completed */; + if (cancelled) { + emnapiAWMT.queueRemove(work + emnapiAWMT.offset.queue); + } + }); + if (!cancelled) { + return 9 /* napi_status.napi_generic_failure */; + } + if (Atomics.compareExchange(new Int32Array(emnapiAWMT.ensureBufferFor(work + emnapiAWMT.offset.status + 4), work + emnapiAWMT.offset.status, 1), 0, 0 /* AsyncWorkStatus.Pending */, 1 /* AsyncWorkStatus.Cancelled */) !== 0 /* AsyncWorkStatus.Pending */) { + return 9 /* napi_status.napi_generic_failure */; + } + emnapiCtx.features.setImmediate(() => { + emnapiAWMT.callComplete(work, 11 /* napi_status.napi_cancelled */); + }); + return 0 /* napi_status.napi_ok */; + }, + callComplete: function (work, status) { + _emnapi_runtime_keepalive_pop(); + emnapiCtx.decreaseWaitingRequestCounter(); + const complete = emnapiAWMT.getComplete(work); + const env = emnapiAWMT.getEnv(work); + const data = emnapiAWMT.getData(work); + const envObject = emnapi_shared.emnapiEnv; + const scope = emnapiCtx.openScope(envObject); + const callback = () => { + if (!complete) + return; + envObject.callbackIntoModule(true, () => { + (emnapiPluginCtx.wasmTable.get(complete))(env, status, data); + }); + }; + try { + if (emnapiNodeBinding) { + const resource = emnapiAWMT.getResource(work); + const resource_value = emnapiCtx.getRef(resource).get(); + const resourceObject = emnapiCtx.jsValueFromNapiValue(resource_value); + const view = new DataView(emnapiAWMT.ensureBufferFor(work + emnapiAWMT.offset.trigger_async_id + 8)); + const asyncId = view.getFloat64(work + emnapiAWMT.offset.async_id, true); + const triggerAsyncId = view.getFloat64(work + emnapiAWMT.offset.trigger_async_id, true); + emnapiNodeBinding.node.makeCallback(resourceObject, callback, [], { + asyncId, + triggerAsyncId + }); + } + else { + callback(); + } + } + finally { + emnapiCtx.closeScope(envObject, scope); + } + } + }; + emnapiAWST.init(); + emnapiAWMT.init(); + /** @__sig ippppppp */ + var napi_create_async_work = emnapi_shared.singleThreadAsyncWork + ? function (env, resource, resource_name, execute, complete, data, result) { + if (!env) + return 1 /* napi_status.napi_invalid_arg */; + // @ts-expect-error + const envObject = emnapi_shared.emnapiEnv; + envObject.checkGCAccess(); + if (!execute) + return envObject.setLastError(1 /* napi_status.napi_invalid_arg */); + if (!result) + return envObject.setLastError(1 /* napi_status.napi_invalid_arg */); + let resourceObject; + if (resource) { + resourceObject = Object(emnapiCtx.jsValueFromNapiValue(resource)); + } + else { + resourceObject = {}; + } + if (!resource_name) + return envObject.setLastError(1 /* napi_status.napi_invalid_arg */); + const resourceName = String(emnapiCtx.jsValueFromNapiValue(resource_name)); + const id = emnapiAWST.create(env, resourceObject, resourceName, execute, complete, data); + result >>>= 0; + var HEAP_DATA_VIEW = new DataView(emnapiPluginCtx.wasmMemory.buffer), GET_HEAP_DATA_VIEW = () => HEAP_DATA_VIEW.buffer === emnapiPluginCtx.wasmMemory.buffer ? HEAP_DATA_VIEW : (HEAP_DATA_VIEW = new DataView(emnapiPluginCtx.wasmMemory.buffer)); + GET_HEAP_DATA_VIEW().setUint32(result, id, true); + return envObject.clearLastError(); + } + : function (env, resource, resource_name, execute, complete, data, result) { + if (!env) + return 1 /* napi_status.napi_invalid_arg */; + // @ts-expect-error + const envObject = emnapi_shared.emnapiEnv; + envObject.checkGCAccess(); + if (!execute) + return envObject.setLastError(1 /* napi_status.napi_invalid_arg */); + if (!result) + return envObject.setLastError(1 /* napi_status.napi_invalid_arg */); + let resourceObject; + if (resource) { + resourceObject = Object(emnapiCtx.jsValueFromNapiValue(resource)); + } + else { + resourceObject = {}; + } + if (!resource_name) + return envObject.setLastError(1 /* napi_status.napi_invalid_arg */); + const sizeofAW = emnapiAWMT.offset.end; + let aw = emscripten_runtime._malloc(sizeofAW); + if (!aw) + return envObject.setLastError(9 /* napi_status.napi_generic_failure */); + aw >>>= 0; + new Uint8Array(emnapiAWMT.ensureBufferFor(aw + sizeofAW)).subarray(aw, aw + sizeofAW).fill(0); + const s = emnapiCtx.napiValueFromJsValue(resourceObject); + const resourceRef = emnapiCtx.createReference(envObject, s, 1, 1 /* ReferenceOwnership.kUserland */); + const resource_ = resourceRef.id; + var HEAP_DATA_VIEW = new DataView(emnapiPluginCtx.wasmMemory.buffer), GET_HEAP_DATA_VIEW = () => HEAP_DATA_VIEW.buffer === emnapiPluginCtx.wasmMemory.buffer ? HEAP_DATA_VIEW : (HEAP_DATA_VIEW = new DataView(emnapiPluginCtx.wasmMemory.buffer)); + GET_HEAP_DATA_VIEW().setUint32(aw, resource_, true); + _emnapi_node_emit_async_init(s, resource_name, -1, aw + emnapiAWMT.offset.async_id); + GET_HEAP_DATA_VIEW().setUint32(aw + emnapiAWMT.offset.env, env, true); + GET_HEAP_DATA_VIEW().setUint32(aw + emnapiAWMT.offset.execute, execute, true); + GET_HEAP_DATA_VIEW().setUint32(aw + emnapiAWMT.offset.complete, complete, true); + GET_HEAP_DATA_VIEW().setUint32(aw + emnapiAWMT.offset.data, data, true); + emnapiAWMT.queueInit(aw + emnapiAWMT.offset.queue); + result >>>= 0; + GET_HEAP_DATA_VIEW().setUint32(result, aw, true); + return envObject.clearLastError(); + }; + /** @__sig ipp */ + var napi_delete_async_work = emnapi_shared.singleThreadAsyncWork + ? function (env, work) { + if (!env) + return 1 /* napi_status.napi_invalid_arg */; + // @ts-expect-error + const envObject = emnapi_shared.emnapiEnv; + envObject.checkGCAccess(); + if (!work) + return envObject.setLastError(1 /* napi_status.napi_invalid_arg */); + work >>>= 0; + emnapiAWST.remove(work); + return envObject.clearLastError(); + } + : function (env, work) { + if (!env) + return 1 /* napi_status.napi_invalid_arg */; + // @ts-expect-error + const envObject = emnapi_shared.emnapiEnv; + envObject.checkGCAccess(); + if (!work) + return envObject.setLastError(1 /* napi_status.napi_invalid_arg */); + work >>>= 0; + const resource = emnapiAWMT.getResource(work); + emnapiCtx.getRef(resource).dispose(); + if (emnapiNodeBinding) { + const view = new DataView(emnapiAWMT.ensureBufferFor(work + emnapiAWMT.offset.trigger_async_id + 8)); + const asyncId = view.getFloat64(work + emnapiAWMT.offset.async_id, true); + const triggerAsyncId = view.getFloat64(work + emnapiAWMT.offset.trigger_async_id, true); + _emnapi_node_emit_async_destroy(asyncId, triggerAsyncId); + } + emscripten_runtime._free(work); + return envObject.clearLastError(); + }; + /** @__sig ipp */ + var napi_queue_async_work = emnapi_shared.singleThreadAsyncWork + ? function (env, work) { + if (!env) + return 1 /* napi_status.napi_invalid_arg */; + const envObject = emnapi_shared.emnapiEnv; + if (!work) + return envObject.setLastError(1 /* napi_status.napi_invalid_arg */); + work >>>= 0; + emnapiAWST.queue(work); + return envObject.clearLastError(); + } + : function (env, work) { + if (!env) + return 1 /* napi_status.napi_invalid_arg */; + const envObject = emnapi_shared.emnapiEnv; + if (!work) + return envObject.setLastError(1 /* napi_status.napi_invalid_arg */); + work >>>= 0; + emnapiAWMT.scheduleWork(work); + return envObject.clearLastError(); + }; + /** @__sig ipp */ + var napi_cancel_async_work = emnapi_shared.singleThreadAsyncWork + ? function (env, work) { + if (!env) + return 1 /* napi_status.napi_invalid_arg */; + const envObject = emnapi_shared.emnapiEnv; + if (!work) + return envObject.setLastError(1 /* napi_status.napi_invalid_arg */); + work >>>= 0; + const status = emnapiAWST.cancel(work); + if (status === 0 /* napi_status.napi_ok */) + return envObject.clearLastError(); + return envObject.setLastError(status); + } + : function (env, work) { + if (!env) + return 1 /* napi_status.napi_invalid_arg */; + const envObject = emnapi_shared.emnapiEnv; + if (!work) + return envObject.setLastError(1 /* napi_status.napi_invalid_arg */); + work >>>= 0; + const status = emnapiAWMT.cancelWork(work); + if (status === 0 /* napi_status.napi_ok */) + return envObject.clearLastError(); + return envObject.setLastError(status); + }; + /** @__sig pp */ + function _emnapi_async_worker(globalAddress) { + globalAddress >>>= 0; + emnapiAWMT.globalAddress = globalAddress; + const mutex = emnapiAWMT.getMutex(); + const cond = emnapiAWMT.getCond(); + mutex.lock(); + const exitMessageAddr = globalAddress + emnapiAWMT.globalOffset.exit_message; + const idleThreadsAddr = globalAddress + emnapiAWMT.globalOffset.idle_threads; + const workerQueueAddr = globalAddress + emnapiAWMT.globalOffset.q; + var HEAP_DATA_VIEW = new DataView(emnapiPluginCtx.wasmMemory.buffer), GET_HEAP_DATA_VIEW = () => HEAP_DATA_VIEW.buffer === emnapiPluginCtx.wasmMemory.buffer ? HEAP_DATA_VIEW : (HEAP_DATA_VIEW = new DataView(emnapiPluginCtx.wasmMemory.buffer)); + for (;;) { + emnapiAWMT.ensureBufferFor(workerQueueAddr + 4); + while (emnapiAWMT.queueEmpty(workerQueueAddr)) { + Atomics.add(new Int32Array(emnapiAWMT.ensureBufferFor(idleThreadsAddr + 4), idleThreadsAddr, 1), 0, 1); + cond.wait(); + Atomics.sub(new Int32Array(emnapiAWMT.ensureBufferFor(idleThreadsAddr + 4), idleThreadsAddr, 1), 0, 1); + } + const q = GET_HEAP_DATA_VIEW().getUint32(workerQueueAddr, true); + if (q === exitMessageAddr) { + cond.signal(); + mutex.unlock(); + break; + } + const work = q - emnapiAWMT.offset.queue; + emnapiAWMT.queueRemove(q); + emnapiAWMT.queueInit(q); + mutex.unlock(); + const statusBuffer = new Int32Array(emnapiAWMT.ensureBufferFor(work + emnapiAWMT.offset.status + 4), work + emnapiAWMT.offset.status, 1); + if (Atomics.load(statusBuffer, 0) === 1 /* AsyncWorkStatus.Cancelled */) { + emscripten_runtime.abort('unreachable'); + } + const execute = emnapiAWMT.getExecute(work); + const env = emnapiAWMT.getEnv(work); + const data = emnapiAWMT.getData(work); + (emnapiPluginCtx.wasmTable.get(execute))(env, data); + Atomics.store(statusBuffer, 0, 2 /* AsyncWorkStatus.Completed */); + const postMessage = emnapi_shared.napiModule.postMessage; + postMessage({ + __emnapi__: { + type: 'async-work-complete', + payload: { work } + } + }); + mutex.lock(); + } + return 0; + } + /** @__sig ipp */ + function _emnapi_spawn_worker(f, globalAddress) { + if (typeof emnapi_shared.onCreateWorker !== 'function') { + throw new TypeError('`options.onCreateWorker` is not a function'); + } + const promises = []; + const args = []; + if (!('emnapi_async_worker_create' in emscripten_runtime.wasmInstance.exports)) { + throw new TypeError('`emnapi_async_worker_create` is not exported, please try to add `--export=emnapi_async_worker_create` to linker flags'); + } + args.push(emscripten_runtime.wasmInstance.exports.emnapi_async_worker_create(0, 0)); + const handleError = (e) => { + if ('message' in e && (e.message.indexOf('RuntimeError') !== -1 || e.message.indexOf('unreachable') !== -1)) { + emnapiAWMT.terminateWorkers(); + } + }; + let ret; + try { + const worker = emnapi_shared.onCreateWorker({ type: 'async-work', name: 'emnapi-async-worker' }); + const p = emscripten_runtime.PThread.loadWasmModuleToWorker(worker); + if (emscripten_runtime.ENVIRONMENT_IS_NODE) { + worker.on('error', handleError); + } + else { + worker.addEventListener('error', handleError, false); + } + emnapiAWMT.addListener(worker); + if (typeof emnapiPluginCtx.emnapiTSFN !== 'undefined') { + emnapiPluginCtx.emnapiTSFN.addListener(worker); + } + promises.push(p.then(() => { + if (typeof worker.unref === 'function') { + worker.unref(); + } + })); + ret = emnapiAWMT.pool.push(worker) - 1; + const arg = args[0]; + worker.threadBlockBase = arg; + worker.postMessage({ + __emnapi__: { + type: 'async-worker-init', + payload: { arg, func: [f, globalAddress] } + } + }); + } + catch (err) { + const arg = args[0]; + emscripten_runtime._free(arg); + throw err; + } + return ret; + } + function initWorker(startArg, func) { + if (emnapi_shared.napiModule.childThread) { + if (typeof emscripten_runtime.wasmInstance.exports.emnapi_async_worker_init !== 'function') { + throw new TypeError('`emnapi_async_worker_init` is not exported, please try to add `--export=emnapi_async_worker_init` to linker flags'); + } + emscripten_runtime.wasmInstance.exports.emnapi_async_worker_init(startArg); + (emnapiPluginCtx.wasmTable.get(func[0]))(func[1]); + } + else { + throw new Error('startThread is only available in child threads'); + } + } + emnapi_shared.napiModule.initWorker = initWorker; + + //#endregion src/core/async-work.ts + + exports._emnapi_async_worker = _emnapi_async_worker; + exports._emnapi_spawn_worker = _emnapi_spawn_worker; + exports.napi_cancel_async_work = napi_cancel_async_work; + exports.napi_create_async_work = napi_create_async_work; + exports.napi_delete_async_work = napi_delete_async_work; + exports.napi_queue_async_work = napi_queue_async_work; + + return exports; + +})({}, emnapiPluginCtx, emnapiPluginCtx); + return { + importObject: (original) => { + + Object.keys(mod).forEach(key => { + if (key.startsWith('napi_') || key.startsWith('node_api_')) { + original.napi[key] = mod[key]; + } else { + original.env[key] = mod[key]; + } + }); + } + }; +} + +//#region src/emnapi/threadsafe-function.js +function threadsafeFunction (emnapiPluginCtx) { + const { emnapiCtx, emnapiNodeBinding, _emnapi_node_emit_async_destroy: __emnapi_node_emit_async_destroy, _emnapi_node_emit_async_init: __emnapi_node_emit_async_init, _emnapi_runtime_keepalive_pop: __emnapi_runtime_keepalive_pop, _emnapi_runtime_keepalive_push: __emnapi_runtime_keepalive_push } = emnapiPluginCtx; + var mod = (function (exports, emnapi_shared, emscripten_runtime) { + + //#region src/macro.ts + + //#endregion src/macro.ts + + //#region src/threadsafe-function.ts + /* eslint-disable @stylistic/indent */ + /** + * @__deps malloc + * @__deps free + * @__deps $emnapiCtx + * @__deps $emnapiEnv + * @__deps $emnapiNodeBinding + * @__deps _emnapi_node_emit_async_destroy + * @__deps _emnapi_runtime_keepalive_pop + * @__postset + * ``` + * emnapiTSFN.init(); + * ``` + */ + const emnapiTSFN = { + _liveSet: {}, + offset: { + __size__: 0, + /* napi_ref */ resource: 0, + /* double */ async_id: 0, + /* double */ trigger_async_id: 0, + /* size_t */ queue_size: 0, + /* bool */ is_some: 0, + /* void* */ queue: 0, + // Reuse uv_async_t storage as JS-side wakeup state: pending event + scheduled drain. + async_pending: 0, + async_u_fd: 0, + /* size_t */ thread_count: 0, + /* int32_t */ state: 0, + /* atomic_uchar */ dispatch_state: 0, + /* void* */ context: 0, + /* size_t */ max_queue_size: 0, + /* napi_ref */ ref: 0, + /* napi_env */ env: 0, + /* void* */ finalize_data: 0, + /* napi_finalize */ finalize_cb: 0, + /* napi_threadsafe_function_call_js */ call_js_cb: 0, + /* bool */ handles_closing: 0, + /* bool */ async_ref: 0, + /* int32_t */ mutex: 0, + /* int32_t */ cond: 0, + }, + init() { + emnapiTSFN._liveSet = new Set(); + emnapiTSFN.offset.__size__ = 184 /* NapiTSFNOffset32.__size__ */; + emnapiTSFN.offset.resource = 0 /* NapiTSFNOffset32.async_resource_resource */; + emnapiTSFN.offset.async_id = 8 /* NapiTSFNOffset32.async_resource_async_context_async_id */; + emnapiTSFN.offset.trigger_async_id = 16 /* NapiTSFNOffset32.async_resource_async_context_trigger_async_id */; + emnapiTSFN.offset.queue_size = 60 /* NapiTSFNOffset32.queue_size */; + emnapiTSFN.offset.is_some = 24 /* NapiTSFNOffset32.async_resource_is_some */; + emnapiTSFN.offset.queue = 64 /* NapiTSFNOffset32.queue */; + emnapiTSFN.offset.async_pending = 132 /* NapiTSFNOffset32.async_pending */; + emnapiTSFN.offset.async_u_fd = 96 /* NapiTSFNOffset32.async_u_fd */; + emnapiTSFN.offset.thread_count = 136 /* NapiTSFNOffset32.thread_count */; + emnapiTSFN.offset.state = 140 /* NapiTSFNOffset32.state */; + emnapiTSFN.offset.dispatch_state = 144 /* NapiTSFNOffset32.dispatch_state */; + emnapiTSFN.offset.context = 148 /* NapiTSFNOffset32.context */; + emnapiTSFN.offset.max_queue_size = 152 /* NapiTSFNOffset32.max_queue_size */; + emnapiTSFN.offset.ref = 156 /* NapiTSFNOffset32.ref */; + emnapiTSFN.offset.env = 160 /* NapiTSFNOffset32.env */; + emnapiTSFN.offset.finalize_data = 164 /* NapiTSFNOffset32.finalize_data */; + emnapiTSFN.offset.finalize_cb = 168 /* NapiTSFNOffset32.finalize_cb */; + emnapiTSFN.offset.call_js_cb = 172 /* NapiTSFNOffset32.call_js_cb */; + emnapiTSFN.offset.handles_closing = 176 /* NapiTSFNOffset32.handles_closing */; + emnapiTSFN.offset.async_ref = 180 /* NapiTSFNOffset32.async_ref */; + emnapiTSFN.offset.mutex = 32 /* NapiTSFNOffset32.mutex */; + emnapiTSFN.offset.cond = 56 /* NapiTSFNOffset32.cond */; + emnapiTSFN.offset.mutex = emnapiTSFN.offset.mutex + 4; + if (typeof emscripten_runtime.PThread !== 'undefined') { + emscripten_runtime.PThread.unusedWorkers.forEach(emnapiTSFN.addListener); + Object.values(emscripten_runtime.PThread.pthreads).forEach(emnapiTSFN.addListener); + const __original_getNewWorker = emscripten_runtime.PThread.getNewWorker; + emscripten_runtime.PThread.getNewWorker = function () { + const r = __original_getNewWorker.apply(this, arguments); + emnapiTSFN.addListener(r); + return r; + }; + } + }, + addListener(worker) { + if (!worker) + return false; + if (worker._emnapiTSFNListener) + return true; + const handler = function (e) { + const data = emscripten_runtime.ENVIRONMENT_IS_NODE ? e : e.data; + const __emnapi__ = data.__emnapi__; + if (__emnapi__) { + const type = __emnapi__.type; + const payload = __emnapi__.payload; + if (type === 'tsfn-send') { + const pendng = payload.tsfn + emnapiTSFN.offset.async_pending; + if (Atomics.load(new Int32Array(emnapiTSFN.ensureBufferFor(pendng + 4)), pendng >>> 2) !== 0) { + emnapiTSFN.enqueue(payload.tsfn); + } + } + } + }; + const dispose = function () { + if (emscripten_runtime.ENVIRONMENT_IS_NODE) { + worker.off('message', handler); + } + else { + worker.removeEventListener('message', handler, false); + } + delete worker._emnapiTSFNListener; + }; + worker._emnapiTSFNListener = { handler, dispose }; + if (emscripten_runtime.ENVIRONMENT_IS_NODE) { + worker.on('message', handler); + } + else { + worker.addEventListener('message', handler, false); + } + return true; + }, + /** + * When another thread grows the shared WebAssembly.Memory, this agent's + * cached `wasmMemory.buffer` may still have the old shorter length + * (V8 refreshes it lazily). If a pointer derived from shared memory lies + * beyond the cached length, `wasmMemory.grow(0)` forces the agent to + * observe the current memory size and refreshes the buffer. + */ + ensureBufferFor(end) { + let buffer = emscripten_runtime.wasmMemory.buffer; + if (end > buffer.byteLength) { + emscripten_runtime.wasmMemory.grow(0); + buffer = emscripten_runtime.wasmMemory.buffer; + } + return buffer; + }, + initQueue(func) { + const size = 2 * 4; + let queue = emscripten_runtime._malloc(size); + if (!queue) + return false; + queue >>>= 0; + new Uint8Array(emnapiTSFN.ensureBufferFor(queue + size), queue, size).fill(0); + emnapiTSFN.storeSizeTypeValue(func + emnapiTSFN.offset.queue, queue, false); + return true; + }, + destroyQueue(func) { + const queue = emnapiTSFN.loadSizeTypeValue(func + emnapiTSFN.offset.queue, false); + if (queue) { + let node = emnapiTSFN.loadSizeTypeValue(queue, false); + while (node !== 0) { + const next = emnapiTSFN.loadSizeTypeValue(node + 4, false); + emscripten_runtime._free(node); + node = next; + } + emscripten_runtime._free(queue); + } + }, + pushQueue(func, data) { + const queue = emnapiTSFN.loadSizeTypeValue(func + emnapiTSFN.offset.queue, false); + const head = emnapiTSFN.loadSizeTypeValue(queue, false); + const tail = emnapiTSFN.loadSizeTypeValue(queue + 4, false); + const size = 2 * 4; + let node = emscripten_runtime._malloc(size); + if (!node) + throw new Error('OOM'); + node >>>= 0; + emnapiTSFN.storeSizeTypeValue(node, data, false); + emnapiTSFN.storeSizeTypeValue(node + 4, 0, false); + if (head === 0 && tail === 0) { + emnapiTSFN.storeSizeTypeValue(queue, node, false); + emnapiTSFN.storeSizeTypeValue(queue + 4, node, false); + } + else { + emnapiTSFN.storeSizeTypeValue(tail + 4, node, false); + emnapiTSFN.storeSizeTypeValue(queue + 4, node, false); + } + emnapiTSFN.addQueueSize(func); + }, + shiftQueue(func) { + const queue = emnapiTSFN.loadSizeTypeValue(func + emnapiTSFN.offset.queue, false); + const head = emnapiTSFN.loadSizeTypeValue(queue, false); + if (head === 0) + return 0; + const node = head; + const next = emnapiTSFN.loadSizeTypeValue(head + 4, false); + emnapiTSFN.storeSizeTypeValue(queue, next, false); + if (next === 0) { + emnapiTSFN.storeSizeTypeValue(queue + 4, 0, false); + } + emnapiTSFN.storeSizeTypeValue(node + 4, 0, false); + const value = emnapiTSFN.loadSizeTypeValue(node, false); + emscripten_runtime._free(node); + emnapiTSFN.subQueueSize(func); + return value; + }, + push(func, data, mode) { + const mutex = emnapiTSFN.getMutex(func); + const cond = emnapiTSFN.getCond(func); + const waitCondition = () => { + const queueSize = emnapiTSFN.getQueueSize(func); + const maxSize = emnapiTSFN.getMaxQueueSize(func); + return queueSize >= maxSize && maxSize > 0 && emnapiTSFN.getState(func) === 0 /* State.kOpen */; + }; + const isBrowserMain = typeof window !== 'undefined' && typeof document !== 'undefined' && !emscripten_runtime.ENVIRONMENT_IS_NODE; + let shouldDelete = false; + const ret = mutex.execute(() => { + while (waitCondition()) { + if (mode === 0 /* napi_threadsafe_function_call_mode.napi_tsfn_nonblocking */) { + return 15 /* napi_status.napi_queue_full */; + } + /** + * Browser JS main thread can not use `Atomics.wait` + * + * Related: + * https://github.com/nodejs/node/pull/32689 + * https://github.com/nodejs/node/pull/33453 + */ + if (isBrowserMain) { + return 21 /* napi_status.napi_would_deadlock */; + } + cond.wait(); + } + if (emnapiTSFN.getState(func) === 0 /* State.kOpen */) { + emnapiTSFN.pushQueue(func, data); + emnapiTSFN.send(func); + return 0 /* napi_status.napi_ok */; + } + if (emnapiTSFN.getThreadCount(func) === 0) { + return 1 /* napi_status.napi_invalid_arg */; + } + emnapiTSFN.subThreadCount(func); + if (!(emnapiTSFN.getState(func) === 2 /* State.kClosed */ && emnapiTSFN.getThreadCount(func) === 0)) { + return 16 /* napi_status.napi_closing */; + } + shouldDelete = true; + return 16 /* napi_status.napi_closing */; + }); + if (shouldDelete) { + emnapiTSFN.destroy(func); + } + return ret; + }, + getMutex(func) { + const index = func + emnapiTSFN.offset.mutex; + const mutex = { + lock() { + const isBrowserMain = typeof window !== 'undefined' && typeof document !== 'undefined' && !emscripten_runtime.ENVIRONMENT_IS_NODE; + const i32a = new Int32Array(emnapiTSFN.ensureBufferFor(index + 4), index, 1); + if (isBrowserMain) { + while (true) { + const oldValue = Atomics.compareExchange(i32a, 0, 0, 10); + if (oldValue === 0) { + return; + } + } + } + else { + while (true) { + const oldValue = Atomics.compareExchange(i32a, 0, 0, 10); + if (oldValue === 0) { + return; + } + Atomics.wait(i32a, 0, 10); + } + } + }, + /* lockAsync () { + return new Promise(resolve => { + const again = (): void => { fn() } + const fn = (): void => { + const i32a = new Int32Array(emnapiTSFN.ensureBufferFor(index + 4), index, 1) + const oldValue = Atomics.compareExchange(i32a, 0, 0, 10) + if (oldValue === 0) { + resolve() + return + } + (Atomics as any).waitAsync(i32a, 0, 10).value.then(again) + } + fn() + }) + }, */ + unlock() { + const i32a = new Int32Array(emnapiTSFN.ensureBufferFor(index + 4), index, 1); + const oldValue = Atomics.compareExchange(i32a, 0, 10, 0); + if (oldValue !== 10) { + throw new Error('Tried to unlock while not holding the mutex'); + } + Atomics.notify(i32a, 0, 1); + }, + execute(fn) { + mutex.lock(); + try { + return fn(); + } + finally { + mutex.unlock(); + } + } /* , + executeAsync (fn: () => Promise): Promise { + return mutex.lockAsync().then(() => { + const r = fn() + mutex.unlock() + return r + }, (err) => { + mutex.unlock() + throw err + }) + } */ + }; + return mutex; + }, + getCond(func) { + const index = func + emnapiTSFN.offset.cond; + const mutex = emnapiTSFN.getMutex(func); + const cond = { + wait() { + const i32a = new Int32Array(emnapiTSFN.ensureBufferFor(index + 4), index, 1); + const value = Atomics.load(i32a, 0); + mutex.unlock(); + Atomics.wait(i32a, 0, value); + mutex.lock(); + }, + /* waitAsync () { + const i32a = new Int32Array(emnapiTSFN.ensureBufferFor(index + 4), index, 1) + const value = Atomics.load(i32a, 0) + mutex.unlock() + const lock = (): Promise => mutex.lockAsync() + try { + return (Atomics as any).waitAsync(i32a, 0, value).value.then(lock, lock) + } catch (err) { + return lock() + } + }, */ + signal() { + const i32a = new Int32Array(emnapiTSFN.ensureBufferFor(index + 4), index, 1); + Atomics.add(i32a, 0, 1); + Atomics.notify(i32a, 0, 1); + } + }; + return cond; + }, + getQueueSize(func) { + return emnapiTSFN.loadSizeTypeValue(func + emnapiTSFN.offset.queue_size, true); + }, + addQueueSize(func) { + const offset = emnapiTSFN.offset.queue_size; + let arr, index; + arr = new Uint32Array(emnapiTSFN.ensureBufferFor(func + offset + 4)); + index = (func + offset) >>> 2; + Atomics.add(arr, index, 1); + }, + subQueueSize(func) { + const offset = emnapiTSFN.offset.queue_size; + let arr, index; + arr = new Uint32Array(emnapiTSFN.ensureBufferFor(func + offset + 4)); + index = (func + offset) >>> 2; + Atomics.sub(arr, index, 1); + }, + getThreadCount(func) { + return emnapiTSFN.loadSizeTypeValue(func + emnapiTSFN.offset.thread_count, true); + }, + addThreadCount(func) { + const offset = emnapiTSFN.offset.thread_count; + let arr, index; + arr = new Uint32Array(emnapiTSFN.ensureBufferFor(func + offset + 4)); + index = (func + offset) >>> 2; + Atomics.add(arr, index, 1); + }, + subThreadCount(func) { + const offset = emnapiTSFN.offset.thread_count; + let arr, index; + arr = new Uint32Array(emnapiTSFN.ensureBufferFor(func + offset + 4)); + index = (func + offset) >>> 2; + Atomics.sub(arr, index, 1); + }, + getState(func) { + return Atomics.load(new Int32Array(emnapiTSFN.ensureBufferFor(func + emnapiTSFN.offset.state + 4)), (func + emnapiTSFN.offset.state) >>> 2); + }, + setState(func, value) { + Atomics.store(new Int32Array(emnapiTSFN.ensureBufferFor(func + emnapiTSFN.offset.state + 4)), (func + emnapiTSFN.offset.state) >>> 2, value); + }, + getHandlesClosing(func) { + return Atomics.load(new Int8Array(emnapiTSFN.ensureBufferFor(func + emnapiTSFN.offset.handles_closing + 1)), (func + emnapiTSFN.offset.handles_closing)); + }, + setHandlesClosing(func, value) { + Atomics.store(new Int8Array(emnapiTSFN.ensureBufferFor(func + emnapiTSFN.offset.handles_closing + 1)), (func + emnapiTSFN.offset.handles_closing), value); + }, + getDispatchState(func) { + return Atomics.load(new Uint32Array(emnapiTSFN.ensureBufferFor(func + emnapiTSFN.offset.dispatch_state + 4)), (func + emnapiTSFN.offset.dispatch_state) >>> 2); + }, + getContext(func) { + return emnapiTSFN.loadSizeTypeValue(func + emnapiTSFN.offset.context, false); + }, + getMaxQueueSize(func) { + return emnapiTSFN.loadSizeTypeValue(func + emnapiTSFN.offset.max_queue_size, true); + }, + getEnv(func) { + return emnapiTSFN.loadSizeTypeValue(func + emnapiTSFN.offset.env, false); + }, + getCallJSCb(func) { + return emnapiTSFN.loadSizeTypeValue(func + emnapiTSFN.offset.call_js_cb, false); + }, + getRef(func) { + return emnapiTSFN.loadSizeTypeValue(func + emnapiTSFN.offset.ref, false); + }, + getResource(func) { + return emnapiTSFN.loadSizeTypeValue(func + emnapiTSFN.offset.resource, false); + }, + getFinalizeCb(func) { + return emnapiTSFN.loadSizeTypeValue(func + emnapiTSFN.offset.finalize_cb, false); + }, + getFinalizeData(func) { + return emnapiTSFN.loadSizeTypeValue(func + emnapiTSFN.offset.finalize_data, false); + }, + loadSizeTypeValue(offset, unsigned) { + let ret; + let arr; + if (unsigned) { + arr = new Uint32Array(emnapiTSFN.ensureBufferFor(offset + 4)); + ret = Atomics.load(arr, offset >>> 2); + return ret; + } + else { + arr = new Int32Array(emnapiTSFN.ensureBufferFor(offset + 4)); + ret = Atomics.load(arr, offset >>> 2); + return ret; + } + }, + storeSizeTypeValue(offset, value, unsigned) { + let arr; + if (unsigned) { + arr = new Uint32Array(emnapiTSFN.ensureBufferFor(offset + 4)); + Atomics.store(arr, offset >>> 2, value); + return undefined; + } + else { + arr = new Int32Array(emnapiTSFN.ensureBufferFor(offset + 4)); + Atomics.store(arr, offset >>> 2, value >>> 0); + return undefined; + } + }, + releaseResources(func) { + if (emnapiTSFN.getState(func) !== 2 /* State.kClosed */) { + emnapiTSFN.setState(func, 2 /* State.kClosed */); + emnapiTSFN.getEnv(func); + const envObject = emnapi_shared.emnapiEnv; + const ref = emnapiTSFN.getRef(func); + if (ref) { + emnapiCtx.getRef(ref).dispose(); + } + const resource = emnapiTSFN.getResource(func); + emnapiCtx.getRef(resource).dispose(); + emnapiTSFN.ensureBufferFor(func + emnapiTSFN.offset.is_some + 1); + var HEAP_DATA_VIEW = new DataView(emnapiPluginCtx.wasmMemory.buffer), GET_HEAP_DATA_VIEW = () => HEAP_DATA_VIEW.buffer === emnapiPluginCtx.wasmMemory.buffer ? HEAP_DATA_VIEW : (HEAP_DATA_VIEW = new DataView(emnapiPluginCtx.wasmMemory.buffer)); + GET_HEAP_DATA_VIEW().setInt8(func + emnapiTSFN.offset.is_some, 0, true); + emnapiCtx.removeCleanupHook(envObject, emnapiTSFN.cleanup, func); + envObject.unref(); + const asyncRefAddress = func + emnapiTSFN.offset.async_ref; + const asyncRefOffset = asyncRefAddress >>> 2; + const arr = new Uint32Array(emnapiTSFN.ensureBufferFor(asyncRefAddress + 4)); + if (Atomics.load(arr, asyncRefOffset) > 0) { + Atomics.store(arr, asyncRefOffset, 0); + __emnapi_runtime_keepalive_pop(); + emnapiCtx.decreaseWaitingRequestCounter(); + } + if (emnapiNodeBinding) { + const view = new DataView(emnapiTSFN.ensureBufferFor(func + emnapiTSFN.offset.trigger_async_id + 8)); + const asyncId = view.getFloat64(func + emnapiTSFN.offset.async_id, true); + const triggerAsyncId = view.getFloat64(func + emnapiTSFN.offset.trigger_async_id, true); + __emnapi_node_emit_async_destroy(asyncId, triggerAsyncId); + } + } + }, + destroy(func) { + emnapiTSFN._liveSet.delete(func); + emnapiTSFN.destroyQueue(func); + emnapiTSFN.releaseResources(func); + emscripten_runtime._free(func); + }, + emptyQueue(func) { + const drainQueue = []; + emnapiTSFN.getMutex(func).execute(() => { + while (emnapiTSFN.getQueueSize(func) > 0) { + drainQueue.push(emnapiTSFN.shiftQueue(func)); + } + }); + const callJsCb = emnapiTSFN.getCallJSCb(func); + const context = emnapiTSFN.getContext(func); + let data; + for (let i = 0; i < drainQueue.length; i++) { + data = drainQueue[i]; + if (callJsCb) { + (emnapiPluginCtx.wasmTable.get(callJsCb))(0, 0, context, data); + } + } + }, + maybeDelete(func) { + let shouldDelete = false; + emnapiTSFN.getMutex(func).execute(() => { + if (emnapiTSFN.getThreadCount(func) > 0) { + emnapiTSFN.releaseResources(func); + } + else { + shouldDelete = true; + } + }); + if (shouldDelete) { + emnapiTSFN.destroy(func); + } + }, + finalize(func) { + emnapiTSFN.getEnv(func); + const envObject = emnapi_shared.emnapiEnv; + emnapiCtx.openScope(envObject); + const finalize = emnapiTSFN.getFinalizeCb(func); + const data = emnapiTSFN.getFinalizeData(func); + const context = emnapiTSFN.getContext(func); + const f = () => { + envObject.callFinalizerInternal(0, finalize, data, context); + }; + try { + emnapiTSFN.emptyQueue(func); + if (finalize) { + if (emnapiNodeBinding) { + const resource = emnapiTSFN.getResource(func); + const resource_value = emnapiCtx.getRef(resource).get(); + const resourceObject = emnapiCtx.jsValueFromNapiValue(resource_value); + const view = new DataView(emnapiTSFN.ensureBufferFor(func + emnapiTSFN.offset.trigger_async_id + 8)); + const asyncId = view.getFloat64(func + emnapiTSFN.offset.async_id, true); + const triggerAsyncId = view.getFloat64(func + emnapiTSFN.offset.trigger_async_id, true); + emnapiNodeBinding.node.makeCallback(resourceObject, f, [], { + asyncId, + triggerAsyncId + }); + } + else { + f(); + } + } + emnapiTSFN.maybeDelete(func); + } + finally { + emnapiCtx.closeScope(envObject); + } + }, + cleanup(func) { + emnapiTSFN.closeHandlesAndMaybeDelete(func, 1); + }, + closeHandlesAndMaybeDelete(func, set_closing) { + emnapiTSFN.getEnv(func); + const envObject = emnapi_shared.emnapiEnv; + emnapiCtx.openScope(envObject); + try { + if (set_closing) { + emnapiTSFN.getMutex(func).execute(() => { + emnapiTSFN.setState(func, 1 /* State.kClosing */); + if (emnapiTSFN.getMaxQueueSize(func) > 0) { + emnapiTSFN.getCond(func).signal(); + } + }); + } + if (emnapiTSFN.getHandlesClosing(func)) { + return; + } + emnapiTSFN.setHandlesClosing(func, 1); + Atomics.store(new Int32Array(emnapiTSFN.ensureBufferFor(func + emnapiTSFN.offset.async_pending + 4)), (func + emnapiTSFN.offset.async_pending) >>> 2, 1); + emnapiCtx.features.setImmediate(() => { + emnapiTSFN.finalize(func); + }); + } + finally { + emnapiCtx.closeScope(envObject); + } + }, + dispatchOne(func) { + let data = 0; + let popped_value = false; + let has_more = false; + const mutex = emnapiTSFN.getMutex(func); + const cond = emnapiTSFN.getCond(func); + mutex.execute(() => { + if (emnapiTSFN.getState(func) === 0 /* State.kOpen */) { + let size = emnapiTSFN.getQueueSize(func); + if (size > 0) { + data = emnapiTSFN.shiftQueue(func); + popped_value = true; + const maxQueueSize = emnapiTSFN.getMaxQueueSize(func); + if (size === maxQueueSize && maxQueueSize > 0) { + cond.signal(); + } + size--; + } + if (size === 0) { + if (emnapiTSFN.getThreadCount(func) === 0) { + emnapiTSFN.setState(func, 1 /* State.kClosing */); + if (emnapiTSFN.getMaxQueueSize(func) > 0) { + cond.signal(); + } + emnapiTSFN.closeHandlesAndMaybeDelete(func, 0); + } + } + else { + has_more = true; + } + } + else { + emnapiTSFN.closeHandlesAndMaybeDelete(func, 0); + } + }); + if (popped_value) { + const env = emnapiTSFN.getEnv(func); + const envObject = emnapi_shared.emnapiEnv; + emnapiCtx.openScope(envObject); + const f = () => { + envObject.callbackIntoModule(false, () => { + const callJsCb = emnapiTSFN.getCallJSCb(func); + const ref = emnapiTSFN.getRef(func); + const js_callback = ref ? emnapiCtx.getRef(ref).get() : 0; + if (callJsCb) { + const context = emnapiTSFN.getContext(func); + (emnapiPluginCtx.wasmTable.get(callJsCb))(env, js_callback, context, data); + } + else { + const jsCallback = js_callback ? emnapiCtx.jsValueFromNapiValue(js_callback) : null; + if (typeof jsCallback === 'function') { + jsCallback(); + } + } + }); + }; + try { + if (emnapiNodeBinding) { + const resource = emnapiTSFN.getResource(func); + const resource_value = emnapiCtx.getRef(resource).get(); + const resourceObject = emnapiCtx.jsValueFromNapiValue(resource_value); + const view = new DataView(emnapiTSFN.ensureBufferFor(func + emnapiTSFN.offset.trigger_async_id + 8)); + emnapiNodeBinding.node.makeCallback(resourceObject, f, [], { + asyncId: view.getFloat64(func + emnapiTSFN.offset.async_id, true), + triggerAsyncId: view.getFloat64(func + emnapiTSFN.offset.trigger_async_id, true) + }); + } + else { + f(); + } + } + finally { + emnapiCtx.closeScope(envObject); + } + } + return has_more; + }, + dispatch(func) { + let has_more = true; + let iterations_left = 1000; + const dispatchStateAddress = func + emnapiTSFN.offset.dispatch_state; + const index = dispatchStateAddress >>> 2; + while (has_more && --iterations_left !== 0) { + Atomics.store(new Uint32Array(emnapiTSFN.ensureBufferFor(dispatchStateAddress + 4)), index, 1); + try { + has_more = emnapiTSFN.dispatchOne(func); + } + catch (err) { + // A throwing callback must not leave dispatch_state marked as + // dispatching, or every later send() would be swallowed. Re-arm + // the state and schedule another drain before rethrowing. + if (emnapiTSFN._liveSet.has(func)) { + Atomics.exchange(new Uint32Array(emnapiTSFN.ensureBufferFor(dispatchStateAddress + 4)), index, 0); + emnapiTSFN.send(func); + } + throw err; + } + if (Atomics.exchange(new Uint32Array(emnapiTSFN.ensureBufferFor(dispatchStateAddress + 4)), index, 0) !== 1) { + has_more = true; + } + } + if (has_more) { + emnapiTSFN.send(func); + } + }, + enqueue(func) { + // `pending` means a worker thread has requested a wakeup that has not + // been drained on the main thread yet. + const pending = func + emnapiTSFN.offset.async_pending; + // `scheduled` prevents queueing the same main-thread drain chain more than + // once while a previous wakeup is still in flight. + const scheduled = func + emnapiTSFN.offset.async_u_fd; + const end = Math.max(pending, scheduled) + 4; + const state = () => new Int32Array(emnapiTSFN.ensureBufferFor(end)); + if (Atomics.exchange(state(), scheduled >>> 2, 1) !== 0) { + return; + } + // Match uv_async_send-style coalescing in JS: the first turn represents + // the wakeup reaching the main thread, and the second turn performs the + // actual TSFN drain after nearby Send/Signal calls have had a chance to + // collapse into the shared AsyncProgressWorker state. + emnapiCtx.features.setImmediate(() => { + if (!emnapiTSFN._liveSet.has(func)) { + return; + } + if (Atomics.load(state(), pending >>> 2) === 0) { + Atomics.store(state(), scheduled >>> 2, 0); + return; + } + emnapiCtx.features.setImmediate(() => { + // After destroy(), the func address is freed. Skip the atomics + // on that address entirely to avoid use-after-free (JS-side + // lifecycle check must run before touching the state words). + if (!emnapiTSFN._liveSet.has(func)) { + return; + } + try { + // Consume the coalesced wakeup once, then let dispatch() observe any + // queue mutations through dispatch_state like the C implementation. + if (Atomics.exchange(state(), pending >>> 2, 0) === 0) { + return; + } + emnapiTSFN.dispatch(func); + } + finally { + // Allow a later wakeup to schedule a new drain chain. If another + // worker-thread send raced with this drain, enqueue one more turn. + if (emnapiTSFN._liveSet.has(func)) { + Atomics.store(state(), scheduled >>> 2, 0); + if (Atomics.load(state(), pending >>> 2) !== 0) { + emnapiTSFN.enqueue(func); + } + } + } + }); + }); + }, + send(func) { + const dispatchStateAddress = func + emnapiTSFN.offset.dispatch_state; + const current_state = Atomics.or(new Uint32Array(emnapiTSFN.ensureBufferFor(dispatchStateAddress + 4)), dispatchStateAddress >>> 2, 1 << 1); + if ((current_state & 1) === 1) { + return; + } + const pendng = func + emnapiTSFN.offset.async_pending; + // A wakeup is already pending, so this send only needs to leave the queued + // work in the TSFN queue and let the existing drain pick it up. + if (Atomics.load(new Int32Array(emnapiTSFN.ensureBufferFor(pendng + 4)), pendng >>> 2) !== 0) { + return; + } + if (Atomics.exchange(new Int32Array(emnapiTSFN.ensureBufferFor(pendng + 4)), pendng >>> 2, 1) === 0) { + if ((typeof emscripten_runtime.ENVIRONMENT_IS_PTHREAD !== 'undefined') && emscripten_runtime.ENVIRONMENT_IS_PTHREAD) { + // Worker threads only post a wakeup token. Main-thread draining is + // serialized by enqueue() once the message is received. + postMessage({ + __emnapi__: { + type: 'tsfn-send', + payload: { + tsfn: func + } + } + }); + } + else { + // On the main thread we can skip the cross-thread hop and schedule the + // coalesced drain chain directly. + emnapiTSFN.enqueue(func); + } + } + } + }; + emnapiTSFN.init(); + emnapiPluginCtx.emnapiTSFN = emnapiTSFN; + /** + * @__deps _emnapi_node_emit_async_init + * @__deps _emnapi_runtime_keepalive_push + * @__sig ippppppppppp + */ + function napi_create_threadsafe_function(env, func, async_resource, async_resource_name, max_queue_size, initial_thread_count, thread_finalize_data, thread_finalize_cb, context, call_js_cb, result) { + if (!env) + return 1 /* napi_status.napi_invalid_arg */; + // @ts-expect-error + const envObject = emnapi_shared.emnapiEnv; + envObject.checkGCAccess(); + if (!async_resource_name) + return envObject.setLastError(1 /* napi_status.napi_invalid_arg */); + max_queue_size >>>= 0; + initial_thread_count >>>= 0; + env >>>= 0; + thread_finalize_data >>>= 0; + thread_finalize_cb >>>= 0; + context >>>= 0; + call_js_cb >>>= 0; + max_queue_size = max_queue_size >>> 0; + initial_thread_count = initial_thread_count >>> 0; + if (initial_thread_count === 0) { + return envObject.setLastError(1 /* napi_status.napi_invalid_arg */); + } + if (!result) + return envObject.setLastError(1 /* napi_status.napi_invalid_arg */); + let ref = 0; + func >>>= 0; + if (!func) { + if (!call_js_cb) + return envObject.setLastError(1 /* napi_status.napi_invalid_arg */); + } + else { + const funcValue = emnapiCtx.jsValueFromNapiValue(func); + if (typeof funcValue !== 'function') { + return envObject.setLastError(1 /* napi_status.napi_invalid_arg */); + } + ref = emnapiCtx.createReference(envObject, func, 1, 1 /* ReferenceOwnership.kUserland */).id; + } + let asyncResourceObject; + if (async_resource) { + asyncResourceObject = emnapiCtx.jsValueFromNapiValue(async_resource); + if (asyncResourceObject == null) { + return envObject.setLastError(2 /* napi_status.napi_object_expected */); + } + asyncResourceObject = Object(asyncResourceObject); + } + else { + asyncResourceObject = {}; + } + const resource = emnapiCtx.napiValueFromJsValue(asyncResourceObject); + let asyncResourceName = emnapiCtx.jsValueFromNapiValue(async_resource_name); + if (typeof asyncResourceName === 'symbol') { + return envObject.setLastError(3 /* napi_status.napi_string_expected */); + } + asyncResourceName = String(asyncResourceName); + const resource_name = emnapiCtx.napiValueFromJsValue(asyncResourceName); + // tsfn create + const sizeofTSFN = emnapiTSFN.offset.__size__; + let tsfn = emscripten_runtime._malloc(sizeofTSFN); + if (!tsfn) + return envObject.setLastError(9 /* napi_status.napi_generic_failure */); + tsfn >>>= 0; + new Uint8Array(emnapiTSFN.ensureBufferFor(tsfn + sizeofTSFN)).subarray(tsfn, tsfn + sizeofTSFN).fill(0); + const resourceRef = emnapiCtx.createReference(envObject, resource, 1, 1 /* ReferenceOwnership.kUserland */); + const resource_ = resourceRef.id; + var HEAP_DATA_VIEW = new DataView(emnapiPluginCtx.wasmMemory.buffer), GET_HEAP_DATA_VIEW = () => HEAP_DATA_VIEW.buffer === emnapiPluginCtx.wasmMemory.buffer ? HEAP_DATA_VIEW : (HEAP_DATA_VIEW = new DataView(emnapiPluginCtx.wasmMemory.buffer)); + GET_HEAP_DATA_VIEW().setUint32(tsfn + emnapiTSFN.offset.resource, resource_, true); + if (!emnapiTSFN.initQueue(tsfn)) { + emscripten_runtime._free(tsfn); + resourceRef.dispose(); + return envObject.setLastError(9 /* napi_status.napi_generic_failure */); + } + __emnapi_node_emit_async_init(resource, resource_name, -1, tsfn + emnapiTSFN.offset.async_id); + GET_HEAP_DATA_VIEW().setInt8(tsfn + emnapiTSFN.offset.is_some, 1, true); + GET_HEAP_DATA_VIEW().setUint32(tsfn + emnapiTSFN.offset.thread_count, initial_thread_count, true); + GET_HEAP_DATA_VIEW().setUint32(tsfn + emnapiTSFN.offset.context, context, true); + GET_HEAP_DATA_VIEW().setUint32(tsfn + emnapiTSFN.offset.max_queue_size, max_queue_size, true); + GET_HEAP_DATA_VIEW().setUint32(tsfn + emnapiTSFN.offset.ref, ref, true); + GET_HEAP_DATA_VIEW().setUint32(tsfn + emnapiTSFN.offset.env, env, true); + GET_HEAP_DATA_VIEW().setUint32(tsfn + emnapiTSFN.offset.finalize_data, thread_finalize_data, true); + GET_HEAP_DATA_VIEW().setUint32(tsfn + emnapiTSFN.offset.finalize_cb, thread_finalize_cb, true); + GET_HEAP_DATA_VIEW().setUint32(tsfn + emnapiTSFN.offset.call_js_cb, call_js_cb, true); + emnapiCtx.addCleanupHook(envObject, emnapiTSFN.cleanup, tsfn); + emnapiTSFN._liveSet.add(tsfn); + envObject.ref(); + __emnapi_runtime_keepalive_push(); + emnapiCtx.increaseWaitingRequestCounter(); + GET_HEAP_DATA_VIEW().setUint32(tsfn + emnapiTSFN.offset.async_ref, 1, true); + result >>>= 0; + GET_HEAP_DATA_VIEW().setUint32(result, tsfn, true); + return envObject.clearLastError(); + } + /** @__sig ipp */ + function napi_get_threadsafe_function_context(func, result) { + if (!func || !result) { + emscripten_runtime.abort(); + return 1 /* napi_status.napi_invalid_arg */; + } + func >>>= 0; + result >>>= 0; + const context = emnapiTSFN.getContext(func); + var HEAP_DATA_VIEW = new DataView(emnapiPluginCtx.wasmMemory.buffer), GET_HEAP_DATA_VIEW = () => HEAP_DATA_VIEW.buffer === emnapiPluginCtx.wasmMemory.buffer ? HEAP_DATA_VIEW : (HEAP_DATA_VIEW = new DataView(emnapiPluginCtx.wasmMemory.buffer)); + GET_HEAP_DATA_VIEW().setUint32(result, context, true); + return 0 /* napi_status.napi_ok */; + } + /** @__sig ippi */ + function napi_call_threadsafe_function(func, data, mode) { + if (!func) { + emscripten_runtime.abort(); + return 1 /* napi_status.napi_invalid_arg */; + } + func >>>= 0; + data >>>= 0; + return emnapiTSFN.push(func, data, mode); + } + /** @__sig ip */ + function napi_acquire_threadsafe_function(func) { + if (!func) { + emscripten_runtime.abort(); + return 1 /* napi_status.napi_invalid_arg */; + } + func >>>= 0; + const mutex = emnapiTSFN.getMutex(func); + return mutex.execute(() => { + if (emnapiTSFN.getState(func) === 0 /* State.kOpen */) { + emnapiTSFN.addThreadCount(func); + return 0 /* napi_status.napi_ok */; + } + return 16 /* napi_status.napi_closing */; + }); + } + /** @__sig ipi */ + function napi_release_threadsafe_function(func, mode) { + if (!func) { + emscripten_runtime.abort(); + return 1 /* napi_status.napi_invalid_arg */; + } + func >>>= 0; + const mutex = emnapiTSFN.getMutex(func); + const cond = emnapiTSFN.getCond(func); + let shouldDelete = false; + const ret = mutex.execute(() => { + if (emnapiTSFN.getThreadCount(func) === 0) { + return 1 /* napi_status.napi_invalid_arg */; + } + emnapiTSFN.subThreadCount(func); + if (emnapiTSFN.getThreadCount(func) === 0 || mode === 1 /* napi_threadsafe_function_release_mode.napi_tsfn_abort */) { + if (emnapiTSFN.getState(func) === 0 /* State.kOpen */) { + if (mode === 1 /* napi_threadsafe_function_release_mode.napi_tsfn_abort */) { + emnapiTSFN.setState(func, 1 /* State.kClosing */); + } + if (emnapiTSFN.getState(func) === 1 /* State.kClosing */ && emnapiTSFN.getMaxQueueSize(func) > 0) { + cond.signal(); + } + emnapiTSFN.send(func); + } + } + if (!(emnapiTSFN.getState(func) === 2 /* State.kClosed */ && emnapiTSFN.getThreadCount(func) === 0)) { + return 0 /* napi_status.napi_ok */; + } + shouldDelete = true; + return 0 /* napi_status.napi_ok */; + }); + if (shouldDelete) { + emnapiTSFN.destroy(func); + } + return ret; + } + /** + * @__deps _emnapi_runtime_keepalive_pop + * @__sig ipp + */ + function napi_unref_threadsafe_function(env, func) { + if (!func) { + emscripten_runtime.abort(); + return 1 /* napi_status.napi_invalid_arg */; + } + func >>>= 0; + const asyncRefAddress = func + emnapiTSFN.offset.async_ref; + const asyncRefOffset = asyncRefAddress >>> 2; + const arr = new Uint32Array(emnapiTSFN.ensureBufferFor(asyncRefAddress + 4)); + const currentValue = Atomics.load(arr, asyncRefOffset); + if (currentValue > 0) { + Atomics.store(arr, asyncRefOffset, currentValue - 1); + if (currentValue === 1) { + __emnapi_runtime_keepalive_pop(); + emnapiCtx.decreaseWaitingRequestCounter(); + } + } + return 0 /* napi_status.napi_ok */; + } + /** + * @__deps _emnapi_runtime_keepalive_push + * @__sig ipp + */ + function napi_ref_threadsafe_function(env, func) { + if (!func) { + emscripten_runtime.abort(); + return 1 /* napi_status.napi_invalid_arg */; + } + func >>>= 0; + const asyncRefAddress = func + emnapiTSFN.offset.async_ref; + const asyncRefOffset = asyncRefAddress >>> 2; + const arr = new Uint32Array(emnapiTSFN.ensureBufferFor(asyncRefAddress + 4)); + const currentValue = Atomics.load(arr, asyncRefOffset); + if (!currentValue) { + __emnapi_runtime_keepalive_push(); + emnapiCtx.increaseWaitingRequestCounter(); + } + Atomics.store(arr, asyncRefOffset, currentValue + 1); + return 0 /* napi_status.napi_ok */; + } + + //#endregion src/threadsafe-function.ts + + exports.napi_acquire_threadsafe_function = napi_acquire_threadsafe_function; + exports.napi_call_threadsafe_function = napi_call_threadsafe_function; + exports.napi_create_threadsafe_function = napi_create_threadsafe_function; + exports.napi_get_threadsafe_function_context = napi_get_threadsafe_function_context; + exports.napi_ref_threadsafe_function = napi_ref_threadsafe_function; + exports.napi_release_threadsafe_function = napi_release_threadsafe_function; + exports.napi_unref_threadsafe_function = napi_unref_threadsafe_function; + + return exports; + +})({}, emnapiPluginCtx, emnapiPluginCtx); + return { + importObject: (original) => { + Object.assign(original.napi, mod); + } + }; +} + +export { asyncWork as emnapiAsyncWorkPlugin, threadsafeFunction as emnapiTSFNPlugin }; diff --git a/dg-ui/node_modules/@tailwindcss/oxide-wasm32-wasi/node_modules/@napi-rs/wasm-runtime/dist/fs-proxy.cjs b/dg-ui/node_modules/@tailwindcss/oxide-wasm32-wasi/node_modules/@napi-rs/wasm-runtime/dist/fs-proxy.cjs new file mode 100644 index 0000000..f6e1afe --- /dev/null +++ b/dg-ui/node_modules/@tailwindcss/oxide-wasm32-wasi/node_modules/@napi-rs/wasm-runtime/dist/fs-proxy.cjs @@ -0,0 +1,321 @@ +'use strict'; + +// @ts-check + +/** + * @param {unknown} value + */ +const getType = (value) => { + if (value === undefined) return 0 + if (value === null) return 1 + if (isBuffer(value)) return 10 + const t = typeof value; + if (t === 'boolean') return 2 + if (t === 'number') return 3 + if (t === 'string') return 4 + if (t === 'object') return 6 + if (t === 'bigint') return 9 + return -1 +}; + +/** + * @param {unknown} value + * @returns {value is Uint8Array} + */ +const isBuffer = (value) => { + const BufferCtor = globalThis.Buffer; + if (typeof BufferCtor?.isBuffer === 'function') { + return BufferCtor.isBuffer(value) + } + return value instanceof Uint8Array && value.constructor?.name === 'Buffer' +}; + +const RESPONSE_HEADER_SIZE = 16; +const RESPONSE_PAYLOAD_SIZE = 10240; +const RESPONSE_BUFFER_SIZE = RESPONSE_HEADER_SIZE + RESPONSE_PAYLOAD_SIZE; + +/** + * @param {Int32Array} sab + * @param {Uint8Array} payload + */ +const writeResponsePayload = (sab, payload) => { + if (payload.length > RESPONSE_PAYLOAD_SIZE) { + throw new RangeError('payload overflow') + } + new Uint8Array(sab.buffer).set(payload, RESPONSE_HEADER_SIZE); +}; + +/** + * @param {import('memfs').IFs} memfs + * @param {any} value + * @param {ReturnType} type + * @returns {Uint8Array} + */ +const encodeValue = (memfs, value, type) => { + switch (type) { + case 0: + case 1: + return new Uint8Array(0) + case 2: { + const view = new Int32Array(1); + view[0] = value ? 1 : 0; + return new Uint8Array(view.buffer) + } + case 3: { + const view = new Float64Array(1); + view[0] = value; + return new Uint8Array(view.buffer) + } + case 4: { + const view = new TextEncoder().encode(value); + return view + } + case 10: + return new Uint8Array(value) + case 6: { + function storeConstructor(obj, memfs, processed = new WeakSet()) { + if (!obj || typeof obj !== 'object') { + return + } + + if (processed.has(obj)) { + return + } + + processed.add(obj); + + const [entry] = + Object.entries(memfs).filter(([_, v]) => v === obj.constructor)[0] ?? + []; + if (entry) { + Object.defineProperty(obj, '__constructor__', { + configurable: true, + writable: true, + enumerable: true, + value: entry, + }); + } + + for (const value of Object.values(obj)) { + storeConstructor(value, memfs, processed); + } + } + + storeConstructor(value, memfs); + + const json = JSON.stringify(value, (_, value) => { + if (typeof value === 'bigint') { + return `BigInt(${String(value)})` + } + if (value instanceof Error) { + return { + ...value, + message: value.message, + stack: value.stack, + __error__: value.constructor.name, + } + } + return value + }); + const view = new TextEncoder().encode(json); + return view + } + case 9: { + return new TextEncoder().encode(String(value)) + } + case -1: + default: + throw new Error('unsupported data') + } +}; + +/** + * @param {typeof import('memfs')} memfs + * @param {Uint8Array} payload + * @param {number} type + * @returns {any} + */ +const decodeValue = (memfs, payload, type) => { + if (type === 0) return undefined + if (type === 1) return null + if (type === 2) + return Boolean(new Int32Array(payload.buffer, payload.byteOffset, 1)[0]) + if (type === 3) + return new Float64Array(payload.buffer, payload.byteOffset, 1)[0] + if (type === 4) return new TextDecoder().decode(payload.slice()) + if (type === 10) { + const BufferCtor = globalThis.Buffer; + if (typeof BufferCtor?.from === 'function') { + return BufferCtor.from(payload) + } + return payload.slice() + } + if (type === 6) { + const obj = JSON.parse( + new TextDecoder().decode(payload.slice()), + (_key, value) => { + if (typeof value === 'string') { + const matched = value.match(/^BigInt\((-?\d+)\)$/); + if (matched && matched[1]) { + return BigInt(matched[1]) + } + } + return value + }, + ); + + function loadConstructor(obj, memfs, processed = new WeakSet()) { + if (!obj || typeof obj !== 'object') { + return + } + + if (processed.has(obj)) { + return + } + + processed.add(obj); + + if (obj.__constructor__) { + const ctor = obj.__constructor__; + delete obj.__constructor__; + Object.setPrototypeOf(obj, memfs[ctor].prototype); + } + + for (const value of Object.values(obj)) { + loadConstructor(value, memfs, processed); + } + } + + loadConstructor(obj, memfs); + + if (obj.__error__) { + const name = obj.__error__; + const ErrorConstructor = globalThis[name] || Error; + delete obj.__error__; + const err = new ErrorConstructor(obj.message); + Object.defineProperty(err, 'stack', { + configurable: true, + enumerable: false, + writable: true, + value: err.stack, + }); + Object.defineProperty(err, Symbol.toStringTag, { + configurable: true, + enumerable: false, + writable: true, + value: name, + }); + for (const [k, v] of Object.entries(obj)) { + if (k === 'message' || k === 'stack') continue + err[k] = v; + } + return err + } + return obj + } + if (type === 9) { + return BigInt(new TextDecoder().decode(payload.slice())) + } + throw new Error('unsupported data') +}; + +/** + * @param {import('memfs').IFs} fs + * @returns {(e: { data: { __fs__: { sab: Int32Array, type: keyof import('memfs').IFs, payload: any[] } } }) => void} + */ +// oxlint-disable-next-line no-unused-vars -- fixed in an upcoming release +const createOnMessage = (fs) => + function onMessage(e) { + if (e.data.__fs__) { + /** + * 0..4 status(int32_t): 21(waiting) 0(success) 1(error) + * 5..8 type(napi_valuetype): 0(undefined) 1(null) 2(boolean) 3(number) 4(string) 6(jsonstring) 9(bigint) 10(buffer) -1(unsupported) + * 9..16 payload_size(uint32_t) <= 10240 + * 16..16 + payload_size payload_content + */ + const { sab, type, payload } = e.data.__fs__; + const fn = fs[type]; + try { + const ret = fn.apply(fs, payload); + const t = getType(ret); + Atomics.store(sab, 1, t); + const v = encodeValue(fs, ret, t); + Atomics.store(sab, 2, v.length); + writeResponsePayload(sab, v); + Atomics.store(sab, 0, 0); // success + } catch (/** @type {any} */ err) { + let t = getType(err); + let v; + try { + if (t === -1) { + throw new Error('unsupported data') + } + v = encodeValue(fs, err, t); + } catch { + const fallback = (() => { + try { + return String(err) + } catch { + return 'Unserializable thrown value' + } + })(); + t = getType(fallback); + v = encodeValue(fs, fallback, t); + } + if (v.length > RESPONSE_PAYLOAD_SIZE) { + const overflowErr = new RangeError('payload overflow'); + t = getType(overflowErr); + v = encodeValue(fs, overflowErr, t); + } + Atomics.store(sab, 1, t); + Atomics.store(sab, 2, v.length); + writeResponsePayload(sab, v); + Atomics.store(sab, 0, 1); // error + } finally { + Atomics.notify(sab, 0); + } + } + }; + +/** + * @param {typeof import('memfs')} memfs + */ +const createFsProxy = (memfs) => + new Proxy( + {}, + { + get(_target, p, _receiver) { + /** + * @param {any[]} args + */ + return function (...args) { + const sab = new SharedArrayBuffer(RESPONSE_BUFFER_SIZE); + const i32arr = new Int32Array(sab); + Atomics.store(i32arr, 0, 21); + + postMessage({ + __fs__: { + sab: i32arr, + type: p, + payload: args, + }, + }); + + Atomics.wait(i32arr, 0, 21); + + const status = Atomics.load(i32arr, 0); + const type = Atomics.load(i32arr, 1); + const size = Atomics.load(i32arr, 2); + const content = new Uint8Array(sab, RESPONSE_HEADER_SIZE, size); + const value = decodeValue(memfs, content, type); + if (status === 1) { + throw value + } + return value + } + }, + }, + ); + +exports.createFsProxy = createFsProxy; +exports.createOnMessage = createOnMessage; diff --git a/dg-ui/node_modules/@tailwindcss/oxide-wasm32-wasi/node_modules/@napi-rs/wasm-runtime/dist/fs.js b/dg-ui/node_modules/@tailwindcss/oxide-wasm32-wasi/node_modules/@napi-rs/wasm-runtime/dist/fs.js new file mode 100644 index 0000000..1b7333c --- /dev/null +++ b/dg-ui/node_modules/@tailwindcss/oxide-wasm32-wasi/node_modules/@napi-rs/wasm-runtime/dist/fs.js @@ -0,0 +1,25524 @@ +function _mergeNamespaces(n, m) { + m.forEach(function (e) { + e && typeof e !== 'string' && !Array.isArray(e) && Object.keys(e).forEach(function (k) { + if (k !== 'default' && !(k in n)) { + var d = Object.getOwnPropertyDescriptor(e, k); + Object.defineProperty(n, k, d.get ? d : { + enumerable: true, + get: function () { return e[k]; } + }); + } + }); + }); + return Object.freeze(n); +} + +var commonjsGlobal = typeof globalThis !== 'undefined' ? globalThis : typeof window !== 'undefined' ? window : typeof undefined !== 'undefined' ? undefined : typeof self !== 'undefined' ? self : {}; + +function getDefaultExportFromCjs (x) { + return x && x.__esModule && Object.prototype.hasOwnProperty.call(x, 'default') ? x['default'] : x; +} + +function getAugmentedNamespace(n) { + if (Object.prototype.hasOwnProperty.call(n, '__esModule')) return n; + var f = n.default; + if (typeof f == "function") { + var a = function a () { + var isInstance = false; + try { + isInstance = this instanceof a; + } catch (e) {} + if (isInstance) { + return Reflect.construct(f, arguments, this.constructor); + } + return f.apply(this, arguments); + }; + a.prototype = f.prototype; + } else a = {}; + Object.defineProperty(a, '__esModule', {value: true}); + Object.keys(n).forEach(function (k) { + var d = Object.getOwnPropertyDescriptor(n, k); + Object.defineProperty(a, k, d.get ? d : { + enumerable: true, + get: function () { + return n[k]; + } + }); + }); + return a; +} + +var lib$8 = {exports: {}}; + +var lib$7 = {}; + +/****************************************************************************** +Copyright (c) Microsoft Corporation. + +Permission to use, copy, modify, and/or distribute this software for any +purpose with or without fee is hereby granted. + +THE SOFTWARE IS PROVIDED "AS IS" AND THE AUTHOR DISCLAIMS ALL WARRANTIES WITH +REGARD TO THIS SOFTWARE INCLUDING ALL IMPLIED WARRANTIES OF MERCHANTABILITY +AND FITNESS. IN NO EVENT SHALL THE AUTHOR BE LIABLE FOR ANY SPECIAL, DIRECT, +INDIRECT, OR CONSEQUENTIAL DAMAGES OR ANY DAMAGES WHATSOEVER RESULTING FROM +LOSS OF USE, DATA OR PROFITS, WHETHER IN AN ACTION OF CONTRACT, NEGLIGENCE OR +OTHER TORTIOUS ACTION, ARISING OUT OF OR IN CONNECTION WITH THE USE OR +PERFORMANCE OF THIS SOFTWARE. +***************************************************************************** */ +/* undefined Reflect, Promise, SuppressedError, Symbol, Iterator */ + +var extendStatics = function(d, b) { + extendStatics = Object.setPrototypeOf || + ({ __proto__: [] } instanceof Array && function (d, b) { d.__proto__ = b; }) || + function (d, b) { for (var p in b) if (Object.prototype.hasOwnProperty.call(b, p)) d[p] = b[p]; }; + return extendStatics(d, b); +}; + +function __extends(d, b) { + if (typeof b !== "function" && b !== null) + throw new TypeError("Class extends value " + String(b) + " is not a constructor or null"); + extendStatics(d, b); + function __() { this.constructor = d; } + d.prototype = b === null ? Object.create(b) : (__.prototype = b.prototype, new __()); +} + +var __assign = function() { + __assign = Object.assign || function __assign(t) { + for (var s, i = 1, n = arguments.length; i < n; i++) { + s = arguments[i]; + for (var p in s) if (Object.prototype.hasOwnProperty.call(s, p)) t[p] = s[p]; + } + return t; + }; + return __assign.apply(this, arguments); +}; + +function __rest(s, e) { + var t = {}; + for (var p in s) if (Object.prototype.hasOwnProperty.call(s, p) && e.indexOf(p) < 0) + t[p] = s[p]; + if (s != null && typeof Object.getOwnPropertySymbols === "function") + for (var i = 0, p = Object.getOwnPropertySymbols(s); i < p.length; i++) { + if (e.indexOf(p[i]) < 0 && Object.prototype.propertyIsEnumerable.call(s, p[i])) + t[p[i]] = s[p[i]]; + } + return t; +} + +function __decorate(decorators, target, key, desc) { + var c = arguments.length, r = c < 3 ? target : desc === null ? desc = Object.getOwnPropertyDescriptor(target, key) : desc, d; + if (typeof Reflect === "object" && typeof Reflect.decorate === "function") r = Reflect.decorate(decorators, target, key, desc); + else for (var i = decorators.length - 1; i >= 0; i--) if (d = decorators[i]) r = (c < 3 ? d(r) : c > 3 ? d(target, key, r) : d(target, key)) || r; + return c > 3 && r && Object.defineProperty(target, key, r), r; +} + +function __param(paramIndex, decorator) { + return function (target, key) { decorator(target, key, paramIndex); } +} + +function __esDecorate(ctor, descriptorIn, decorators, contextIn, initializers, extraInitializers) { + function accept(f) { if (f !== void 0 && typeof f !== "function") throw new TypeError("Function expected"); return f; } + var kind = contextIn.kind, key = kind === "getter" ? "get" : kind === "setter" ? "set" : "value"; + var target = !descriptorIn && ctor ? contextIn["static"] ? ctor : ctor.prototype : null; + var descriptor = descriptorIn || (target ? Object.getOwnPropertyDescriptor(target, contextIn.name) : {}); + var _, done = false; + for (var i = decorators.length - 1; i >= 0; i--) { + var context = {}; + for (var p in contextIn) context[p] = p === "access" ? {} : contextIn[p]; + for (var p in contextIn.access) context.access[p] = contextIn.access[p]; + context.addInitializer = function (f) { if (done) throw new TypeError("Cannot add initializers after decoration has completed"); extraInitializers.push(accept(f || null)); }; + var result = (0, decorators[i])(kind === "accessor" ? { get: descriptor.get, set: descriptor.set } : descriptor[key], context); + if (kind === "accessor") { + if (result === void 0) continue; + if (result === null || typeof result !== "object") throw new TypeError("Object expected"); + if (_ = accept(result.get)) descriptor.get = _; + if (_ = accept(result.set)) descriptor.set = _; + if (_ = accept(result.init)) initializers.unshift(_); + } + else if (_ = accept(result)) { + if (kind === "field") initializers.unshift(_); + else descriptor[key] = _; + } + } + if (target) Object.defineProperty(target, contextIn.name, descriptor); + done = true; +} +function __runInitializers(thisArg, initializers, value) { + var useValue = arguments.length > 2; + for (var i = 0; i < initializers.length; i++) { + value = useValue ? initializers[i].call(thisArg, value) : initializers[i].call(thisArg); + } + return useValue ? value : void 0; +} +function __propKey(x) { + return typeof x === "symbol" ? x : "".concat(x); +} +function __setFunctionName(f, name, prefix) { + if (typeof name === "symbol") name = name.description ? "[".concat(name.description, "]") : ""; + return Object.defineProperty(f, "name", { configurable: true, value: prefix ? "".concat(prefix, " ", name) : name }); +} +function __metadata(metadataKey, metadataValue) { + if (typeof Reflect === "object" && typeof Reflect.metadata === "function") return Reflect.metadata(metadataKey, metadataValue); +} + +function __awaiter(thisArg, _arguments, P, generator) { + function adopt(value) { return value instanceof P ? value : new P(function (resolve) { resolve(value); }); } + return new (P || (P = Promise))(function (resolve, reject) { + function fulfilled(value) { try { step(generator.next(value)); } catch (e) { reject(e); } } + function rejected(value) { try { step(generator["throw"](value)); } catch (e) { reject(e); } } + function step(result) { result.done ? resolve(result.value) : adopt(result.value).then(fulfilled, rejected); } + step((generator = generator.apply(thisArg, _arguments || [])).next()); + }); +} + +function __generator(thisArg, body) { + var _ = { label: 0, sent: function() { if (t[0] & 1) throw t[1]; return t[1]; }, trys: [], ops: [] }, f, y, t, g = Object.create((typeof Iterator === "function" ? Iterator : Object).prototype); + return g.next = verb(0), g["throw"] = verb(1), g["return"] = verb(2), typeof Symbol === "function" && (g[Symbol.iterator] = function() { return this; }), g; + function verb(n) { return function (v) { return step([n, v]); }; } + function step(op) { + if (f) throw new TypeError("Generator is already executing."); + while (g && (g = 0, op[0] && (_ = 0)), _) try { + if (f = 1, y && (t = op[0] & 2 ? y["return"] : op[0] ? y["throw"] || ((t = y["return"]) && t.call(y), 0) : y.next) && !(t = t.call(y, op[1])).done) return t; + if (y = 0, t) op = [op[0] & 2, t.value]; + switch (op[0]) { + case 0: case 1: t = op; break; + case 4: _.label++; return { value: op[1], done: false }; + case 5: _.label++; y = op[1]; op = [0]; continue; + case 7: op = _.ops.pop(); _.trys.pop(); continue; + default: + if (!(t = _.trys, t = t.length > 0 && t[t.length - 1]) && (op[0] === 6 || op[0] === 2)) { _ = 0; continue; } + if (op[0] === 3 && (!t || (op[1] > t[0] && op[1] < t[3]))) { _.label = op[1]; break; } + if (op[0] === 6 && _.label < t[1]) { _.label = t[1]; t = op; break; } + if (t && _.label < t[2]) { _.label = t[2]; _.ops.push(op); break; } + if (t[2]) _.ops.pop(); + _.trys.pop(); continue; + } + op = body.call(thisArg, _); + } catch (e) { op = [6, e]; y = 0; } finally { f = t = 0; } + if (op[0] & 5) throw op[1]; return { value: op[0] ? op[1] : void 0, done: true }; + } +} + +var __createBinding = Object.create ? (function(o, m, k, k2) { + if (k2 === undefined) k2 = k; + var desc = Object.getOwnPropertyDescriptor(m, k); + if (!desc || ("get" in desc ? !m.__esModule : desc.writable || desc.configurable)) { + desc = { enumerable: true, get: function() { return m[k]; } }; + } + Object.defineProperty(o, k2, desc); +}) : (function(o, m, k, k2) { + if (k2 === undefined) k2 = k; + o[k2] = m[k]; +}); + +function __exportStar(m, o) { + for (var p in m) if (p !== "default" && !Object.prototype.hasOwnProperty.call(o, p)) __createBinding(o, m, p); +} + +function __values(o) { + var s = typeof Symbol === "function" && Symbol.iterator, m = s && o[s], i = 0; + if (m) return m.call(o); + if (o && typeof o.length === "number") return { + next: function () { + if (o && i >= o.length) o = void 0; + return { value: o && o[i++], done: !o }; + } + }; + throw new TypeError(s ? "Object is not iterable." : "Symbol.iterator is not defined."); +} + +function __read(o, n) { + var m = typeof Symbol === "function" && o[Symbol.iterator]; + if (!m) return o; + var i = m.call(o), r, ar = [], e; + try { + while ((n === void 0 || n-- > 0) && !(r = i.next()).done) ar.push(r.value); + } + catch (error) { e = { error: error }; } + finally { + try { + if (r && !r.done && (m = i["return"])) m.call(i); + } + finally { if (e) throw e.error; } + } + return ar; +} + +/** @deprecated */ +function __spread() { + for (var ar = [], i = 0; i < arguments.length; i++) + ar = ar.concat(__read(arguments[i])); + return ar; +} + +/** @deprecated */ +function __spreadArrays() { + for (var s = 0, i = 0, il = arguments.length; i < il; i++) s += arguments[i].length; + for (var r = Array(s), k = 0, i = 0; i < il; i++) + for (var a = arguments[i], j = 0, jl = a.length; j < jl; j++, k++) + r[k] = a[j]; + return r; +} + +function __spreadArray(to, from, pack) { + if (pack || arguments.length === 2) for (var i = 0, l = from.length, ar; i < l; i++) { + if (ar || !(i in from)) { + if (!ar) ar = Array.prototype.slice.call(from, 0, i); + ar[i] = from[i]; + } + } + return to.concat(ar || Array.prototype.slice.call(from)); +} + +function __await(v) { + return this instanceof __await ? (this.v = v, this) : new __await(v); +} + +function __asyncGenerator(thisArg, _arguments, generator) { + if (!Symbol.asyncIterator) throw new TypeError("Symbol.asyncIterator is not defined."); + var g = generator.apply(thisArg, _arguments || []), i, q = []; + return i = Object.create((typeof AsyncIterator === "function" ? AsyncIterator : Object).prototype), verb("next"), verb("throw"), verb("return", awaitReturn), i[Symbol.asyncIterator] = function () { return this; }, i; + function awaitReturn(f) { return function (v) { return Promise.resolve(v).then(f, reject); }; } + function verb(n, f) { if (g[n]) { i[n] = function (v) { return new Promise(function (a, b) { q.push([n, v, a, b]) > 1 || resume(n, v); }); }; if (f) i[n] = f(i[n]); } } + function resume(n, v) { try { step(g[n](v)); } catch (e) { settle(q[0][3], e); } } + function step(r) { r.value instanceof __await ? Promise.resolve(r.value.v).then(fulfill, reject) : settle(q[0][2], r); } + function fulfill(value) { resume("next", value); } + function reject(value) { resume("throw", value); } + function settle(f, v) { if (f(v), q.shift(), q.length) resume(q[0][0], q[0][1]); } +} + +function __asyncDelegator(o) { + var i, p; + return i = {}, verb("next"), verb("throw", function (e) { throw e; }), verb("return"), i[Symbol.iterator] = function () { return this; }, i; + function verb(n, f) { i[n] = o[n] ? function (v) { return (p = !p) ? { value: __await(o[n](v)), done: false } : f ? f(v) : v; } : f; } +} + +function __asyncValues(o) { + if (!Symbol.asyncIterator) throw new TypeError("Symbol.asyncIterator is not defined."); + var m = o[Symbol.asyncIterator], i; + return m ? m.call(o) : (o = typeof __values === "function" ? __values(o) : o[Symbol.iterator](), i = {}, verb("next"), verb("throw"), verb("return"), i[Symbol.asyncIterator] = function () { return this; }, i); + function verb(n) { i[n] = o[n] && function (v) { return new Promise(function (resolve, reject) { v = o[n](v), settle(resolve, reject, v.done, v.value); }); }; } + function settle(resolve, reject, d, v) { Promise.resolve(v).then(function(v) { resolve({ value: v, done: d }); }, reject); } +} + +function __makeTemplateObject(cooked, raw) { + if (Object.defineProperty) { Object.defineProperty(cooked, "raw", { value: raw }); } else { cooked.raw = raw; } + return cooked; +} +var __setModuleDefault = Object.create ? (function(o, v) { + Object.defineProperty(o, "default", { enumerable: true, value: v }); +}) : function(o, v) { + o["default"] = v; +}; + +var ownKeys = function(o) { + ownKeys = Object.getOwnPropertyNames || function (o) { + var ar = []; + for (var k in o) if (Object.prototype.hasOwnProperty.call(o, k)) ar[ar.length] = k; + return ar; + }; + return ownKeys(o); +}; + +function __importStar(mod) { + if (mod && mod.__esModule) return mod; + var result = {}; + if (mod != null) for (var k = ownKeys(mod), i = 0; i < k.length; i++) if (k[i] !== "default") __createBinding(result, mod, k[i]); + __setModuleDefault(result, mod); + return result; +} + +function __importDefault(mod) { + return (mod && mod.__esModule) ? mod : { default: mod }; +} + +function __classPrivateFieldGet(receiver, state, kind, f) { + if (kind === "a" && !f) throw new TypeError("Private accessor was defined without a getter"); + if (typeof state === "function" ? receiver !== state || !f : !state.has(receiver)) throw new TypeError("Cannot read private member from an object whose class did not declare it"); + return kind === "m" ? f : kind === "a" ? f.call(receiver) : f ? f.value : state.get(receiver); +} + +function __classPrivateFieldSet(receiver, state, value, kind, f) { + if (kind === "m") throw new TypeError("Private method is not writable"); + if (kind === "a" && !f) throw new TypeError("Private accessor was defined without a setter"); + if (typeof state === "function" ? receiver !== state || !f : !state.has(receiver)) throw new TypeError("Cannot write private member to an object whose class did not declare it"); + return (kind === "a" ? f.call(receiver, value) : f ? f.value = value : state.set(receiver, value)), value; +} + +function __classPrivateFieldIn(state, receiver) { + if (receiver === null || (typeof receiver !== "object" && typeof receiver !== "function")) throw new TypeError("Cannot use 'in' operator on non-object"); + return typeof state === "function" ? receiver === state : state.has(receiver); +} + +function __addDisposableResource(env, value, async) { + if (value !== null && value !== void 0) { + if (typeof value !== "object" && typeof value !== "function") throw new TypeError("Object expected."); + var dispose, inner; + if (async) { + if (!Symbol.asyncDispose) throw new TypeError("Symbol.asyncDispose is not defined."); + dispose = value[Symbol.asyncDispose]; + } + if (dispose === void 0) { + if (!Symbol.dispose) throw new TypeError("Symbol.dispose is not defined."); + dispose = value[Symbol.dispose]; + if (async) inner = dispose; + } + if (typeof dispose !== "function") throw new TypeError("Object not disposable."); + if (inner) dispose = function() { try { inner.call(this); } catch (e) { return Promise.reject(e); } }; + env.stack.push({ value: value, dispose: dispose, async: async }); + } + else if (async) { + env.stack.push({ async: true }); + } + return value; +} + +var _SuppressedError = typeof SuppressedError === "function" ? SuppressedError : function (error, suppressed, message) { + var e = new Error(message); + return e.name = "SuppressedError", e.error = error, e.suppressed = suppressed, e; +}; + +function __disposeResources(env) { + function fail(e) { + env.error = env.hasError ? new _SuppressedError(e, env.error, "An error was suppressed during disposal.") : e; + env.hasError = true; + } + var r, s = 0; + function next() { + while (r = env.stack.pop()) { + try { + if (!r.async && s === 1) return s = 0, env.stack.push(r), Promise.resolve().then(next); + if (r.dispose) { + var result = r.dispose.call(r.value); + if (r.async) return s |= 2, Promise.resolve(result).then(next, function(e) { fail(e); return next(); }); + } + else s |= 1; + } + catch (e) { + fail(e); + } + } + if (s === 1) return env.hasError ? Promise.reject(env.error) : Promise.resolve(); + if (env.hasError) throw env.error; + } + return next(); +} + +function __rewriteRelativeImportExtension(path, preserveJsx) { + if (typeof path === "string" && /^\.\.?\//.test(path)) { + return path.replace(/\.(tsx)$|((?:\.d)?)((?:\.[^./]+?)?)\.([cm]?)ts$/i, function (m, tsx, d, ext, cm) { + return tsx ? preserveJsx ? ".jsx" : ".js" : d && (!ext || !cm) ? m : (d + ext + "." + cm.toLowerCase() + "js"); + }); + } + return path; +} + +var tslib_es6 = { + __extends, + __assign, + __rest, + __decorate, + __param, + __esDecorate, + __runInitializers, + __propKey, + __setFunctionName, + __metadata, + __awaiter, + __generator, + __createBinding, + __exportStar, + __values, + __read, + __spread, + __spreadArrays, + __spreadArray, + __await, + __asyncGenerator, + __asyncDelegator, + __asyncValues, + __makeTemplateObject, + __importStar, + __importDefault, + __classPrivateFieldGet, + __classPrivateFieldSet, + __classPrivateFieldIn, + __addDisposableResource, + __disposeResources, + __rewriteRelativeImportExtension, +}; + +var tslib_es6$1 = /*#__PURE__*/Object.freeze({ + __proto__: null, + __addDisposableResource: __addDisposableResource, + get __assign () { return __assign; }, + __asyncDelegator: __asyncDelegator, + __asyncGenerator: __asyncGenerator, + __asyncValues: __asyncValues, + __await: __await, + __awaiter: __awaiter, + __classPrivateFieldGet: __classPrivateFieldGet, + __classPrivateFieldIn: __classPrivateFieldIn, + __classPrivateFieldSet: __classPrivateFieldSet, + __createBinding: __createBinding, + __decorate: __decorate, + __disposeResources: __disposeResources, + __esDecorate: __esDecorate, + __exportStar: __exportStar, + __extends: __extends, + __generator: __generator, + __importDefault: __importDefault, + __importStar: __importStar, + __makeTemplateObject: __makeTemplateObject, + __metadata: __metadata, + __param: __param, + __propKey: __propKey, + __read: __read, + __rest: __rest, + __rewriteRelativeImportExtension: __rewriteRelativeImportExtension, + __runInitializers: __runInitializers, + __setFunctionName: __setFunctionName, + __spread: __spread, + __spreadArray: __spreadArray, + __spreadArrays: __spreadArrays, + __values: __values, + default: tslib_es6 +}); + +var require$$0$2 = /*@__PURE__*/getAugmentedNamespace(tslib_es6$1); + +var volume = {}; + +var path$1 = {}; + +var browser$2 = {exports: {}}; + +var hasRequiredBrowser$2; + +function requireBrowser$2 () { + if (hasRequiredBrowser$2) return browser$2.exports; + hasRequiredBrowser$2 = 1; + // shim for using process in browser + var process = browser$2.exports = {}; + + // cached from whatever undefined is present so that test runners that stub it + // don't break things. But we need to wrap it in a try catch in case it is + // wrapped in strict mode code which doesn't define any globals. It's inside a + // function because try/catches deoptimize in certain engines. + + var cachedSetTimeout; + var cachedClearTimeout; + + function defaultSetTimout() { + throw new Error('setTimeout has not been defined'); + } + function defaultClearTimeout () { + throw new Error('clearTimeout has not been defined'); + } + (function () { + try { + if (typeof setTimeout === 'function') { + cachedSetTimeout = setTimeout; + } else { + cachedSetTimeout = defaultSetTimout; + } + } catch (e) { + cachedSetTimeout = defaultSetTimout; + } + try { + if (typeof clearTimeout === 'function') { + cachedClearTimeout = clearTimeout; + } else { + cachedClearTimeout = defaultClearTimeout; + } + } catch (e) { + cachedClearTimeout = defaultClearTimeout; + } + } ()); + function runTimeout(fun) { + if (cachedSetTimeout === setTimeout) { + //normal enviroments in sane situations + return setTimeout(fun, 0); + } + // if setTimeout wasn't available but was latter defined + if ((cachedSetTimeout === defaultSetTimout || !cachedSetTimeout) && setTimeout) { + cachedSetTimeout = setTimeout; + return setTimeout(fun, 0); + } + try { + // when when somebody has screwed with setTimeout but no I.E. maddness + return cachedSetTimeout(fun, 0); + } catch(e){ + try { + // When we are in I.E. but the script has been evaled so I.E. doesn't trust the undefined object when called normally + return cachedSetTimeout.call(null, fun, 0); + } catch(e){ + // same as above but when it's a version of I.E. that must have the undefined object for 'this', hopfully our context correct otherwise it will throw a undefined error + return cachedSetTimeout.call(this, fun, 0); + } + } + + + } + function runClearTimeout(marker) { + if (cachedClearTimeout === clearTimeout) { + //normal enviroments in sane situations + return clearTimeout(marker); + } + // if clearTimeout wasn't available but was latter defined + if ((cachedClearTimeout === defaultClearTimeout || !cachedClearTimeout) && clearTimeout) { + cachedClearTimeout = clearTimeout; + return clearTimeout(marker); + } + try { + // when when somebody has screwed with setTimeout but no I.E. maddness + return cachedClearTimeout(marker); + } catch (e){ + try { + // When we are in I.E. but the script has been evaled so I.E. doesn't trust the undefined object when called normally + return cachedClearTimeout.call(null, marker); + } catch (e){ + // same as above but when it's a version of I.E. that must have the undefined object for 'this', hopfully our context correct otherwise it will throw a undefined error. + // Some versions of I.E. have different rules for clearTimeout vs setTimeout + return cachedClearTimeout.call(this, marker); + } + } + + + + } + var queue = []; + var draining = false; + var currentQueue; + var queueIndex = -1; + + function cleanUpNextTick() { + if (!draining || !currentQueue) { + return; + } + draining = false; + if (currentQueue.length) { + queue = currentQueue.concat(queue); + } else { + queueIndex = -1; + } + if (queue.length) { + drainQueue(); + } + } + + function drainQueue() { + if (draining) { + return; + } + var timeout = runTimeout(cleanUpNextTick); + draining = true; + + var len = queue.length; + while(len) { + currentQueue = queue; + queue = []; + while (++queueIndex < len) { + if (currentQueue) { + currentQueue[queueIndex].run(); + } + } + queueIndex = -1; + len = queue.length; + } + currentQueue = null; + draining = false; + runClearTimeout(timeout); + } + + process.nextTick = function (fun) { + var args = new Array(arguments.length - 1); + if (arguments.length > 1) { + for (var i = 1; i < arguments.length; i++) { + args[i - 1] = arguments[i]; + } + } + queue.push(new Item(fun, args)); + if (queue.length === 1 && !draining) { + runTimeout(drainQueue); + } + }; + + // v8 likes predictible objects + function Item(fun, array) { + this.fun = fun; + this.array = array; + } + Item.prototype.run = function () { + this.fun.apply(null, this.array); + }; + process.title = 'browser'; + process.browser = true; + process.env = {}; + process.argv = []; + process.version = ''; // empty string to avoid regexp issues + process.versions = {}; + + function noop() {} + + process.on = noop; + process.addListener = noop; + process.once = noop; + process.off = noop; + process.removeListener = noop; + process.removeAllListeners = noop; + process.emit = noop; + process.prependListener = noop; + process.prependOnceListener = noop; + + process.listeners = function (name) { return [] }; + + process.binding = function (name) { + throw new Error('process.binding is not supported'); + }; + + process.cwd = function () { return '/' }; + process.chdir = function (dir) { + throw new Error('process.chdir is not supported'); + }; + process.umask = function() { return 0; }; + return browser$2.exports; +} + +var browserExports = requireBrowser$2(); +var process$1 = /*@__PURE__*/getDefaultExportFromCjs(browserExports); + +var pathBrowserify; +var hasRequiredPathBrowserify; + +function requirePathBrowserify () { + if (hasRequiredPathBrowserify) return pathBrowserify; + hasRequiredPathBrowserify = 1; + + function assertPath(path) { + if (typeof path !== 'string') { + throw new TypeError('Path must be a string. Received ' + JSON.stringify(path)); + } + } + + // Resolves . and .. elements in a path with directory names + function normalizeStringPosix(path, allowAboveRoot) { + var res = ''; + var lastSegmentLength = 0; + var lastSlash = -1; + var dots = 0; + var code; + for (var i = 0; i <= path.length; ++i) { + if (i < path.length) + code = path.charCodeAt(i); + else if (code === 47 /*/*/) + break; + else + code = 47 /*/*/; + if (code === 47 /*/*/) { + if (lastSlash === i - 1 || dots === 1) ; else if (lastSlash !== i - 1 && dots === 2) { + if (res.length < 2 || lastSegmentLength !== 2 || res.charCodeAt(res.length - 1) !== 46 /*.*/ || res.charCodeAt(res.length - 2) !== 46 /*.*/) { + if (res.length > 2) { + var lastSlashIndex = res.lastIndexOf('/'); + if (lastSlashIndex !== res.length - 1) { + if (lastSlashIndex === -1) { + res = ''; + lastSegmentLength = 0; + } else { + res = res.slice(0, lastSlashIndex); + lastSegmentLength = res.length - 1 - res.lastIndexOf('/'); + } + lastSlash = i; + dots = 0; + continue; + } + } else if (res.length === 2 || res.length === 1) { + res = ''; + lastSegmentLength = 0; + lastSlash = i; + dots = 0; + continue; + } + } + if (allowAboveRoot) { + if (res.length > 0) + res += '/..'; + else + res = '..'; + lastSegmentLength = 2; + } + } else { + if (res.length > 0) + res += '/' + path.slice(lastSlash + 1, i); + else + res = path.slice(lastSlash + 1, i); + lastSegmentLength = i - lastSlash - 1; + } + lastSlash = i; + dots = 0; + } else if (code === 46 /*.*/ && dots !== -1) { + ++dots; + } else { + dots = -1; + } + } + return res; + } + + function _format(sep, pathObject) { + var dir = pathObject.dir || pathObject.root; + var base = pathObject.base || (pathObject.name || '') + (pathObject.ext || ''); + if (!dir) { + return base; + } + if (dir === pathObject.root) { + return dir + base; + } + return dir + sep + base; + } + + var posix = { + // path.resolve([from ...], to) + resolve: function resolve() { + var resolvedPath = ''; + var resolvedAbsolute = false; + var cwd; + + for (var i = arguments.length - 1; i >= -1 && !resolvedAbsolute; i--) { + var path; + if (i >= 0) + path = arguments[i]; + else { + if (cwd === undefined) + cwd = process$1.cwd(); + path = cwd; + } + + assertPath(path); + + // Skip empty entries + if (path.length === 0) { + continue; + } + + resolvedPath = path + '/' + resolvedPath; + resolvedAbsolute = path.charCodeAt(0) === 47 /*/*/; + } + + // At this point the path should be resolved to a full absolute path, but + // handle relative paths to be safe (might happen when process.cwd() fails) + + // Normalize the path + resolvedPath = normalizeStringPosix(resolvedPath, !resolvedAbsolute); + + if (resolvedAbsolute) { + if (resolvedPath.length > 0) + return '/' + resolvedPath; + else + return '/'; + } else if (resolvedPath.length > 0) { + return resolvedPath; + } else { + return '.'; + } + }, + + normalize: function normalize(path) { + assertPath(path); + + if (path.length === 0) return '.'; + + var isAbsolute = path.charCodeAt(0) === 47 /*/*/; + var trailingSeparator = path.charCodeAt(path.length - 1) === 47 /*/*/; + + // Normalize the path + path = normalizeStringPosix(path, !isAbsolute); + + if (path.length === 0 && !isAbsolute) path = '.'; + if (path.length > 0 && trailingSeparator) path += '/'; + + if (isAbsolute) return '/' + path; + return path; + }, + + isAbsolute: function isAbsolute(path) { + assertPath(path); + return path.length > 0 && path.charCodeAt(0) === 47 /*/*/; + }, + + join: function join() { + if (arguments.length === 0) + return '.'; + var joined; + for (var i = 0; i < arguments.length; ++i) { + var arg = arguments[i]; + assertPath(arg); + if (arg.length > 0) { + if (joined === undefined) + joined = arg; + else + joined += '/' + arg; + } + } + if (joined === undefined) + return '.'; + return posix.normalize(joined); + }, + + relative: function relative(from, to) { + assertPath(from); + assertPath(to); + + if (from === to) return ''; + + from = posix.resolve(from); + to = posix.resolve(to); + + if (from === to) return ''; + + // Trim any leading backslashes + var fromStart = 1; + for (; fromStart < from.length; ++fromStart) { + if (from.charCodeAt(fromStart) !== 47 /*/*/) + break; + } + var fromEnd = from.length; + var fromLen = fromEnd - fromStart; + + // Trim any leading backslashes + var toStart = 1; + for (; toStart < to.length; ++toStart) { + if (to.charCodeAt(toStart) !== 47 /*/*/) + break; + } + var toEnd = to.length; + var toLen = toEnd - toStart; + + // Compare paths to find the longest common path from root + var length = fromLen < toLen ? fromLen : toLen; + var lastCommonSep = -1; + var i = 0; + for (; i <= length; ++i) { + if (i === length) { + if (toLen > length) { + if (to.charCodeAt(toStart + i) === 47 /*/*/) { + // We get here if `from` is the exact base path for `to`. + // For example: from='/foo/bar'; to='/foo/bar/baz' + return to.slice(toStart + i + 1); + } else if (i === 0) { + // We get here if `from` is the root + // For example: from='/'; to='/foo' + return to.slice(toStart + i); + } + } else if (fromLen > length) { + if (from.charCodeAt(fromStart + i) === 47 /*/*/) { + // We get here if `to` is the exact base path for `from`. + // For example: from='/foo/bar/baz'; to='/foo/bar' + lastCommonSep = i; + } else if (i === 0) { + // We get here if `to` is the root. + // For example: from='/foo'; to='/' + lastCommonSep = 0; + } + } + break; + } + var fromCode = from.charCodeAt(fromStart + i); + var toCode = to.charCodeAt(toStart + i); + if (fromCode !== toCode) + break; + else if (fromCode === 47 /*/*/) + lastCommonSep = i; + } + + var out = ''; + // Generate the relative path based on the path difference between `to` + // and `from` + for (i = fromStart + lastCommonSep + 1; i <= fromEnd; ++i) { + if (i === fromEnd || from.charCodeAt(i) === 47 /*/*/) { + if (out.length === 0) + out += '..'; + else + out += '/..'; + } + } + + // Lastly, append the rest of the destination (`to`) path that comes after + // the common path parts + if (out.length > 0) + return out + to.slice(toStart + lastCommonSep); + else { + toStart += lastCommonSep; + if (to.charCodeAt(toStart) === 47 /*/*/) + ++toStart; + return to.slice(toStart); + } + }, + + _makeLong: function _makeLong(path) { + return path; + }, + + dirname: function dirname(path) { + assertPath(path); + if (path.length === 0) return '.'; + var code = path.charCodeAt(0); + var hasRoot = code === 47 /*/*/; + var end = -1; + var matchedSlash = true; + for (var i = path.length - 1; i >= 1; --i) { + code = path.charCodeAt(i); + if (code === 47 /*/*/) { + if (!matchedSlash) { + end = i; + break; + } + } else { + // We saw the first non-path separator + matchedSlash = false; + } + } + + if (end === -1) return hasRoot ? '/' : '.'; + if (hasRoot && end === 1) return '//'; + return path.slice(0, end); + }, + + basename: function basename(path, ext) { + if (ext !== undefined && typeof ext !== 'string') throw new TypeError('"ext" argument must be a string'); + assertPath(path); + + var start = 0; + var end = -1; + var matchedSlash = true; + var i; + + if (ext !== undefined && ext.length > 0 && ext.length <= path.length) { + if (ext.length === path.length && ext === path) return ''; + var extIdx = ext.length - 1; + var firstNonSlashEnd = -1; + for (i = path.length - 1; i >= 0; --i) { + var code = path.charCodeAt(i); + if (code === 47 /*/*/) { + // If we reached a path separator that was not part of a set of path + // separators at the end of the string, stop now + if (!matchedSlash) { + start = i + 1; + break; + } + } else { + if (firstNonSlashEnd === -1) { + // We saw the first non-path separator, remember this index in case + // we need it if the extension ends up not matching + matchedSlash = false; + firstNonSlashEnd = i + 1; + } + if (extIdx >= 0) { + // Try to match the explicit extension + if (code === ext.charCodeAt(extIdx)) { + if (--extIdx === -1) { + // We matched the extension, so mark this as the end of our path + // component + end = i; + } + } else { + // Extension does not match, so our result is the entire path + // component + extIdx = -1; + end = firstNonSlashEnd; + } + } + } + } + + if (start === end) end = firstNonSlashEnd;else if (end === -1) end = path.length; + return path.slice(start, end); + } else { + for (i = path.length - 1; i >= 0; --i) { + if (path.charCodeAt(i) === 47 /*/*/) { + // If we reached a path separator that was not part of a set of path + // separators at the end of the string, stop now + if (!matchedSlash) { + start = i + 1; + break; + } + } else if (end === -1) { + // We saw the first non-path separator, mark this as the end of our + // path component + matchedSlash = false; + end = i + 1; + } + } + + if (end === -1) return ''; + return path.slice(start, end); + } + }, + + extname: function extname(path) { + assertPath(path); + var startDot = -1; + var startPart = 0; + var end = -1; + var matchedSlash = true; + // Track the state of characters (if any) we see before our first dot and + // after any path separator we find + var preDotState = 0; + for (var i = path.length - 1; i >= 0; --i) { + var code = path.charCodeAt(i); + if (code === 47 /*/*/) { + // If we reached a path separator that was not part of a set of path + // separators at the end of the string, stop now + if (!matchedSlash) { + startPart = i + 1; + break; + } + continue; + } + if (end === -1) { + // We saw the first non-path separator, mark this as the end of our + // extension + matchedSlash = false; + end = i + 1; + } + if (code === 46 /*.*/) { + // If this is our first dot, mark it as the start of our extension + if (startDot === -1) + startDot = i; + else if (preDotState !== 1) + preDotState = 1; + } else if (startDot !== -1) { + // We saw a non-dot and non-path separator before our dot, so we should + // have a good chance at having a non-empty extension + preDotState = -1; + } + } + + if (startDot === -1 || end === -1 || + // We saw a non-dot character immediately before the dot + preDotState === 0 || + // The (right-most) trimmed path component is exactly '..' + preDotState === 1 && startDot === end - 1 && startDot === startPart + 1) { + return ''; + } + return path.slice(startDot, end); + }, + + format: function format(pathObject) { + if (pathObject === null || typeof pathObject !== 'object') { + throw new TypeError('The "pathObject" argument must be of type Object. Received type ' + typeof pathObject); + } + return _format('/', pathObject); + }, + + parse: function parse(path) { + assertPath(path); + + var ret = { root: '', dir: '', base: '', ext: '', name: '' }; + if (path.length === 0) return ret; + var code = path.charCodeAt(0); + var isAbsolute = code === 47 /*/*/; + var start; + if (isAbsolute) { + ret.root = '/'; + start = 1; + } else { + start = 0; + } + var startDot = -1; + var startPart = 0; + var end = -1; + var matchedSlash = true; + var i = path.length - 1; + + // Track the state of characters (if any) we see before our first dot and + // after any path separator we find + var preDotState = 0; + + // Get non-dir info + for (; i >= start; --i) { + code = path.charCodeAt(i); + if (code === 47 /*/*/) { + // If we reached a path separator that was not part of a set of path + // separators at the end of the string, stop now + if (!matchedSlash) { + startPart = i + 1; + break; + } + continue; + } + if (end === -1) { + // We saw the first non-path separator, mark this as the end of our + // extension + matchedSlash = false; + end = i + 1; + } + if (code === 46 /*.*/) { + // If this is our first dot, mark it as the start of our extension + if (startDot === -1) startDot = i;else if (preDotState !== 1) preDotState = 1; + } else if (startDot !== -1) { + // We saw a non-dot and non-path separator before our dot, so we should + // have a good chance at having a non-empty extension + preDotState = -1; + } + } + + if (startDot === -1 || end === -1 || + // We saw a non-dot character immediately before the dot + preDotState === 0 || + // The (right-most) trimmed path component is exactly '..' + preDotState === 1 && startDot === end - 1 && startDot === startPart + 1) { + if (end !== -1) { + if (startPart === 0 && isAbsolute) ret.base = ret.name = path.slice(1, end);else ret.base = ret.name = path.slice(startPart, end); + } + } else { + if (startPart === 0 && isAbsolute) { + ret.name = path.slice(1, startDot); + ret.base = path.slice(1, end); + } else { + ret.name = path.slice(startPart, startDot); + ret.base = path.slice(startPart, end); + } + ret.ext = path.slice(startDot, end); + } + + if (startPart > 0) ret.dir = path.slice(0, startPart - 1);else if (isAbsolute) ret.dir = '/'; + + return ret; + }, + + sep: '/', + delimiter: ':', + win32: null, + posix: null + }; + + posix.posix = posix; + + pathBrowserify = posix; + return pathBrowserify; +} + +var hasRequiredPath$1; + +function requirePath$1 () { + if (hasRequiredPath$1) return path$1; + hasRequiredPath$1 = 1; + (function (exports) { + Object.defineProperty(exports, "__esModule", { value: true }); + exports.basename = exports.isAbsolute = exports.normalize = exports.dirname = exports.relative = exports.join = exports.posix = exports.sep = exports.resolve = void 0; + var node_path_1 = requirePathBrowserify(); + Object.defineProperty(exports, "resolve", { enumerable: true, get: function () { return node_path_1.resolve; } }); + Object.defineProperty(exports, "sep", { enumerable: true, get: function () { return node_path_1.sep; } }); + Object.defineProperty(exports, "posix", { enumerable: true, get: function () { return node_path_1.posix; } }); + Object.defineProperty(exports, "join", { enumerable: true, get: function () { return node_path_1.join; } }); + Object.defineProperty(exports, "relative", { enumerable: true, get: function () { return node_path_1.relative; } }); + Object.defineProperty(exports, "dirname", { enumerable: true, get: function () { return node_path_1.dirname; } }); + Object.defineProperty(exports, "normalize", { enumerable: true, get: function () { return node_path_1.normalize; } }); + Object.defineProperty(exports, "isAbsolute", { enumerable: true, get: function () { return node_path_1.isAbsolute; } }); + Object.defineProperty(exports, "basename", { enumerable: true, get: function () { return node_path_1.basename; } }); + + } (path$1)); + return path$1; +} + +var lib$6 = {}; + +var types$1 = {}; + +var hasRequiredTypes$1; + +function requireTypes$1 () { + if (hasRequiredTypes$1) return types$1; + hasRequiredTypes$1 = 1; + Object.defineProperty(types$1, "__esModule", { value: true }); + + return types$1; +} + +var json$1 = {}; + +var buffer$2 = {}; + +var buffer$1 = {}; + +var base64Js = {}; + +var hasRequiredBase64Js; + +function requireBase64Js () { + if (hasRequiredBase64Js) return base64Js; + hasRequiredBase64Js = 1; + + base64Js.byteLength = byteLength; + base64Js.toByteArray = toByteArray; + base64Js.fromByteArray = fromByteArray; + + var lookup = []; + var revLookup = []; + var Arr = typeof Uint8Array !== 'undefined' ? Uint8Array : Array; + + var code = 'ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789+/'; + for (var i = 0, len = code.length; i < len; ++i) { + lookup[i] = code[i]; + revLookup[code.charCodeAt(i)] = i; + } + + // Support decoding URL-safe base64 strings, as Node.js does. + // See: https://en.wikipedia.org/wiki/Base64#URL_applications + revLookup['-'.charCodeAt(0)] = 62; + revLookup['_'.charCodeAt(0)] = 63; + + function getLens (b64) { + var len = b64.length; + + if (len % 4 > 0) { + throw new Error('Invalid string. Length must be a multiple of 4') + } + + // Trim off extra bytes after placeholder bytes are found + // See: https://github.com/beatgammit/base64-js/issues/42 + var validLen = b64.indexOf('='); + if (validLen === -1) validLen = len; + + var placeHoldersLen = validLen === len + ? 0 + : 4 - (validLen % 4); + + return [validLen, placeHoldersLen] + } + + // base64 is 4/3 + up to two characters of the original data + function byteLength (b64) { + var lens = getLens(b64); + var validLen = lens[0]; + var placeHoldersLen = lens[1]; + return ((validLen + placeHoldersLen) * 3 / 4) - placeHoldersLen + } + + function _byteLength (b64, validLen, placeHoldersLen) { + return ((validLen + placeHoldersLen) * 3 / 4) - placeHoldersLen + } + + function toByteArray (b64) { + var tmp; + var lens = getLens(b64); + var validLen = lens[0]; + var placeHoldersLen = lens[1]; + + var arr = new Arr(_byteLength(b64, validLen, placeHoldersLen)); + + var curByte = 0; + + // if there are placeholders, only get up to the last complete 4 chars + var len = placeHoldersLen > 0 + ? validLen - 4 + : validLen; + + var i; + for (i = 0; i < len; i += 4) { + tmp = + (revLookup[b64.charCodeAt(i)] << 18) | + (revLookup[b64.charCodeAt(i + 1)] << 12) | + (revLookup[b64.charCodeAt(i + 2)] << 6) | + revLookup[b64.charCodeAt(i + 3)]; + arr[curByte++] = (tmp >> 16) & 0xFF; + arr[curByte++] = (tmp >> 8) & 0xFF; + arr[curByte++] = tmp & 0xFF; + } + + if (placeHoldersLen === 2) { + tmp = + (revLookup[b64.charCodeAt(i)] << 2) | + (revLookup[b64.charCodeAt(i + 1)] >> 4); + arr[curByte++] = tmp & 0xFF; + } + + if (placeHoldersLen === 1) { + tmp = + (revLookup[b64.charCodeAt(i)] << 10) | + (revLookup[b64.charCodeAt(i + 1)] << 4) | + (revLookup[b64.charCodeAt(i + 2)] >> 2); + arr[curByte++] = (tmp >> 8) & 0xFF; + arr[curByte++] = tmp & 0xFF; + } + + return arr + } + + function tripletToBase64 (num) { + return lookup[num >> 18 & 0x3F] + + lookup[num >> 12 & 0x3F] + + lookup[num >> 6 & 0x3F] + + lookup[num & 0x3F] + } + + function encodeChunk (uint8, start, end) { + var tmp; + var output = []; + for (var i = start; i < end; i += 3) { + tmp = + ((uint8[i] << 16) & 0xFF0000) + + ((uint8[i + 1] << 8) & 0xFF00) + + (uint8[i + 2] & 0xFF); + output.push(tripletToBase64(tmp)); + } + return output.join('') + } + + function fromByteArray (uint8) { + var tmp; + var len = uint8.length; + var extraBytes = len % 3; // if we have 1 byte left, pad 2 bytes + var parts = []; + var maxChunkLength = 16383; // must be multiple of 3 + + // go through the array every three bytes, we'll deal with trailing stuff later + for (var i = 0, len2 = len - extraBytes; i < len2; i += maxChunkLength) { + parts.push(encodeChunk(uint8, i, (i + maxChunkLength) > len2 ? len2 : (i + maxChunkLength))); + } + + // pad the end with zeros, but make sure to not forget the extra bytes + if (extraBytes === 1) { + tmp = uint8[len - 1]; + parts.push( + lookup[tmp >> 2] + + lookup[(tmp << 4) & 0x3F] + + '==' + ); + } else if (extraBytes === 2) { + tmp = (uint8[len - 2] << 8) + uint8[len - 1]; + parts.push( + lookup[tmp >> 10] + + lookup[(tmp >> 4) & 0x3F] + + lookup[(tmp << 2) & 0x3F] + + '=' + ); + } + + return parts.join('') + } + return base64Js; +} + +var base64JsExports = requireBase64Js(); + +var ieee754 = {}; + +/*! ieee754. BSD-3-Clause License. Feross Aboukhadijeh */ + +var hasRequiredIeee754; + +function requireIeee754 () { + if (hasRequiredIeee754) return ieee754; + hasRequiredIeee754 = 1; + ieee754.read = function (buffer, offset, isLE, mLen, nBytes) { + var e, m; + var eLen = (nBytes * 8) - mLen - 1; + var eMax = (1 << eLen) - 1; + var eBias = eMax >> 1; + var nBits = -7; + var i = isLE ? (nBytes - 1) : 0; + var d = isLE ? -1 : 1; + var s = buffer[offset + i]; + + i += d; + + e = s & ((1 << (-nBits)) - 1); + s >>= (-nBits); + nBits += eLen; + for (; nBits > 0; e = (e * 256) + buffer[offset + i], i += d, nBits -= 8) {} + + m = e & ((1 << (-nBits)) - 1); + e >>= (-nBits); + nBits += mLen; + for (; nBits > 0; m = (m * 256) + buffer[offset + i], i += d, nBits -= 8) {} + + if (e === 0) { + e = 1 - eBias; + } else if (e === eMax) { + return m ? NaN : ((s ? -1 : 1) * Infinity) + } else { + m = m + Math.pow(2, mLen); + e = e - eBias; + } + return (s ? -1 : 1) * m * Math.pow(2, e - mLen) + }; + + ieee754.write = function (buffer, value, offset, isLE, mLen, nBytes) { + var e, m, c; + var eLen = (nBytes * 8) - mLen - 1; + var eMax = (1 << eLen) - 1; + var eBias = eMax >> 1; + var rt = (mLen === 23 ? Math.pow(2, -24) - Math.pow(2, -77) : 0); + var i = isLE ? 0 : (nBytes - 1); + var d = isLE ? 1 : -1; + var s = value < 0 || (value === 0 && 1 / value < 0) ? 1 : 0; + + value = Math.abs(value); + + if (isNaN(value) || value === Infinity) { + m = isNaN(value) ? 1 : 0; + e = eMax; + } else { + e = Math.floor(Math.log(value) / Math.LN2); + if (value * (c = Math.pow(2, -e)) < 1) { + e--; + c *= 2; + } + if (e + eBias >= 1) { + value += rt / c; + } else { + value += rt * Math.pow(2, 1 - eBias); + } + if (value * c >= 2) { + e++; + c /= 2; + } + + if (e + eBias >= eMax) { + m = 0; + e = eMax; + } else if (e + eBias >= 1) { + m = ((value * c) - 1) * Math.pow(2, mLen); + e = e + eBias; + } else { + m = value * Math.pow(2, eBias - 1) * Math.pow(2, mLen); + e = 0; + } + } + + for (; mLen >= 8; buffer[offset + i] = m & 0xff, i += d, m /= 256, mLen -= 8) {} + + e = (e << mLen) | m; + eLen += mLen; + for (; eLen > 0; buffer[offset + i] = e & 0xff, i += d, e /= 256, eLen -= 8) {} + + buffer[offset + i - d] |= s * 128; + }; + return ieee754; +} + +var ieee754Exports = requireIeee754(); + +/*! + * The buffer module from node.js, for the browser. + * + * @author Feross Aboukhadijeh + * @license MIT + */ +/* eslint-disable no-proto */ + +const customInspectSymbol = + (typeof Symbol === 'function' && typeof Symbol['for'] === 'function') // eslint-disable-line dot-notation + ? Symbol['for']('nodejs.util.inspect.custom') // eslint-disable-line dot-notation + : null; + +const INSPECT_MAX_BYTES = 50; + +const K_MAX_LENGTH = 0x7fffffff; +const kMaxLength = K_MAX_LENGTH; + +/** + * If `Buffer.TYPED_ARRAY_SUPPORT`: + * === true Use Uint8Array implementation (fastest) + * === false Print warning and recommend using `buffer` v4.x which has an Object + * implementation (most compatible, even IE6) + * + * Browsers that support typed arrays are IE 10+, Firefox 4+, Chrome 7+, Safari 5.1+, + * Opera 11.6+, iOS 4.2+. + * + * We report that the browser does not support typed arrays if the are not subclassable + * using __proto__. Firefox 4-29 lacks support for adding new properties to `Uint8Array` + * (See: https://bugzilla.mozilla.org/show_bug.cgi?id=695438). IE 10 lacks support + * for __proto__ and has a buggy typed array implementation. + */ +Buffer.TYPED_ARRAY_SUPPORT = typedArraySupport(); + +if (!Buffer.TYPED_ARRAY_SUPPORT && typeof console !== 'undefined' && + typeof console.error === 'function') { + console.error( + 'This browser lacks typed array (Uint8Array) support which is required by ' + + '`buffer` v5.x. Use `buffer` v4.x if you require old browser support.' + ); +} + +function typedArraySupport () { + // Can typed array instances can be augmented? + try { + const arr = new Uint8Array(1); + const proto = { foo: function () { return 42 } }; + Object.setPrototypeOf(proto, Uint8Array.prototype); + Object.setPrototypeOf(arr, proto); + return arr.foo() === 42 + } catch (e) { + return false + } +} + +Object.defineProperty(Buffer.prototype, 'parent', { + enumerable: true, + get: function () { + if (!Buffer.isBuffer(this)) return undefined + return this.buffer + } +}); + +Object.defineProperty(Buffer.prototype, 'offset', { + enumerable: true, + get: function () { + if (!Buffer.isBuffer(this)) return undefined + return this.byteOffset + } +}); + +function createBuffer (length) { + if (length > K_MAX_LENGTH) { + throw new RangeError('The value "' + length + '" is invalid for option "size"') + } + // Return an augmented `Uint8Array` instance + const buf = new Uint8Array(length); + Object.setPrototypeOf(buf, Buffer.prototype); + return buf +} + +/** + * The Buffer constructor returns instances of `Uint8Array` that have their + * prototype changed to `Buffer.prototype`. Furthermore, `Buffer` is a subclass of + * `Uint8Array`, so the returned instances will have all the node `Buffer` methods + * and the `Uint8Array` methods. Square bracket notation works as expected -- it + * returns a single octet. + * + * The `Uint8Array` prototype remains unmodified. + */ + +function Buffer (arg, encodingOrOffset, length) { + // Common case. + if (typeof arg === 'number') { + if (typeof encodingOrOffset === 'string') { + throw new TypeError( + 'The "string" argument must be of type string. Received type number' + ) + } + return allocUnsafe(arg) + } + return from(arg, encodingOrOffset, length) +} + +Buffer.poolSize = 8192; // not used by this implementation + +function from (value, encodingOrOffset, length) { + if (typeof value === 'string') { + return fromString(value, encodingOrOffset) + } + + if (ArrayBuffer.isView(value)) { + return fromArrayView(value) + } + + if (value == null) { + throw new TypeError( + 'The first argument must be one of type string, Buffer, ArrayBuffer, Array, ' + + 'or Array-like Object. Received type ' + (typeof value) + ) + } + + if (isInstance(value, ArrayBuffer) || + (value && isInstance(value.buffer, ArrayBuffer))) { + return fromArrayBuffer(value, encodingOrOffset, length) + } + + if (typeof SharedArrayBuffer !== 'undefined' && + (isInstance(value, SharedArrayBuffer) || + (value && isInstance(value.buffer, SharedArrayBuffer)))) { + return fromArrayBuffer(value, encodingOrOffset, length) + } + + if (typeof value === 'number') { + throw new TypeError( + 'The "value" argument must not be of type number. Received type number' + ) + } + + const valueOf = value.valueOf && value.valueOf(); + if (valueOf != null && valueOf !== value) { + return Buffer.from(valueOf, encodingOrOffset, length) + } + + const b = fromObject(value); + if (b) return b + + if (typeof Symbol !== 'undefined' && Symbol.toPrimitive != null && + typeof value[Symbol.toPrimitive] === 'function') { + return Buffer.from(value[Symbol.toPrimitive]('string'), encodingOrOffset, length) + } + + throw new TypeError( + 'The first argument must be one of type string, Buffer, ArrayBuffer, Array, ' + + 'or Array-like Object. Received type ' + (typeof value) + ) +} + +/** + * Functionally equivalent to Buffer(arg, encoding) but throws a TypeError + * if value is a number. + * Buffer.from(str[, encoding]) + * Buffer.from(array) + * Buffer.from(buffer) + * Buffer.from(arrayBuffer[, byteOffset[, length]]) + **/ +Buffer.from = function (value, encodingOrOffset, length) { + return from(value, encodingOrOffset, length) +}; + +// Note: Change prototype *after* Buffer.from is defined to workaround Chrome bug: +// https://github.com/feross/buffer/pull/148 +Object.setPrototypeOf(Buffer.prototype, Uint8Array.prototype); +Object.setPrototypeOf(Buffer, Uint8Array); + +function assertSize (size) { + if (typeof size !== 'number') { + throw new TypeError('"size" argument must be of type number') + } else if (size < 0) { + throw new RangeError('The value "' + size + '" is invalid for option "size"') + } +} + +function alloc (size, fill, encoding) { + assertSize(size); + if (size <= 0) { + return createBuffer(size) + } + if (fill !== undefined) { + // Only pay attention to encoding if it's a string. This + // prevents accidentally sending in a number that would + // be interpreted as a start offset. + return typeof encoding === 'string' + ? createBuffer(size).fill(fill, encoding) + : createBuffer(size).fill(fill) + } + return createBuffer(size) +} + +/** + * Creates a new filled Buffer instance. + * alloc(size[, fill[, encoding]]) + **/ +Buffer.alloc = function (size, fill, encoding) { + return alloc(size, fill, encoding) +}; + +function allocUnsafe (size) { + assertSize(size); + return createBuffer(size < 0 ? 0 : checked(size) | 0) +} + +/** + * Equivalent to Buffer(num), by default creates a non-zero-filled Buffer instance. + * */ +Buffer.allocUnsafe = function (size) { + return allocUnsafe(size) +}; +/** + * Equivalent to SlowBuffer(num), by default creates a non-zero-filled Buffer instance. + */ +Buffer.allocUnsafeSlow = function (size) { + return allocUnsafe(size) +}; + +function fromString (string, encoding) { + if (typeof encoding !== 'string' || encoding === '') { + encoding = 'utf8'; + } + + if (!Buffer.isEncoding(encoding)) { + throw new TypeError('Unknown encoding: ' + encoding) + } + + const length = byteLength(string, encoding) | 0; + let buf = createBuffer(length); + + const actual = buf.write(string, encoding); + + if (actual !== length) { + // Writing a hex string, for example, that contains invalid characters will + // cause everything after the first invalid character to be ignored. (e.g. + // 'abxxcd' will be treated as 'ab') + buf = buf.slice(0, actual); + } + + return buf +} + +function fromArrayLike (array) { + const length = array.length < 0 ? 0 : checked(array.length) | 0; + const buf = createBuffer(length); + for (let i = 0; i < length; i += 1) { + buf[i] = array[i] & 255; + } + return buf +} + +function fromArrayView (arrayView) { + if (isInstance(arrayView, Uint8Array)) { + const copy = new Uint8Array(arrayView); + return fromArrayBuffer(copy.buffer, copy.byteOffset, copy.byteLength) + } + return fromArrayLike(arrayView) +} + +function fromArrayBuffer (array, byteOffset, length) { + if (byteOffset < 0 || array.byteLength < byteOffset) { + throw new RangeError('"offset" is outside of buffer bounds') + } + + if (array.byteLength < byteOffset + (length || 0)) { + throw new RangeError('"length" is outside of buffer bounds') + } + + let buf; + if (byteOffset === undefined && length === undefined) { + buf = new Uint8Array(array); + } else if (length === undefined) { + buf = new Uint8Array(array, byteOffset); + } else { + buf = new Uint8Array(array, byteOffset, length); + } + + // Return an augmented `Uint8Array` instance + Object.setPrototypeOf(buf, Buffer.prototype); + + return buf +} + +function fromObject (obj) { + if (Buffer.isBuffer(obj)) { + const len = checked(obj.length) | 0; + const buf = createBuffer(len); + + if (buf.length === 0) { + return buf + } + + obj.copy(buf, 0, 0, len); + return buf + } + + if (obj.length !== undefined) { + if (typeof obj.length !== 'number' || numberIsNaN(obj.length)) { + return createBuffer(0) + } + return fromArrayLike(obj) + } + + if (obj.type === 'Buffer' && Array.isArray(obj.data)) { + return fromArrayLike(obj.data) + } +} + +function checked (length) { + // Note: cannot use `length < K_MAX_LENGTH` here because that fails when + // length is NaN (which is otherwise coerced to zero.) + if (length >= K_MAX_LENGTH) { + throw new RangeError('Attempt to allocate Buffer larger than maximum ' + + 'size: 0x' + K_MAX_LENGTH.toString(16) + ' bytes') + } + return length | 0 +} + +function SlowBuffer (length) { + if (+length != length) { // eslint-disable-line eqeqeq + length = 0; + } + return Buffer.alloc(+length) +} + +Buffer.isBuffer = function isBuffer (b) { + return b != null && b._isBuffer === true && + b !== Buffer.prototype // so Buffer.isBuffer(Buffer.prototype) will be false +}; + +Buffer.compare = function compare (a, b) { + if (isInstance(a, Uint8Array)) a = Buffer.from(a, a.offset, a.byteLength); + if (isInstance(b, Uint8Array)) b = Buffer.from(b, b.offset, b.byteLength); + if (!Buffer.isBuffer(a) || !Buffer.isBuffer(b)) { + throw new TypeError( + 'The "buf1", "buf2" arguments must be one of type Buffer or Uint8Array' + ) + } + + if (a === b) return 0 + + let x = a.length; + let y = b.length; + + for (let i = 0, len = Math.min(x, y); i < len; ++i) { + if (a[i] !== b[i]) { + x = a[i]; + y = b[i]; + break + } + } + + if (x < y) return -1 + if (y < x) return 1 + return 0 +}; + +Buffer.isEncoding = function isEncoding (encoding) { + switch (String(encoding).toLowerCase()) { + case 'hex': + case 'utf8': + case 'utf-8': + case 'ascii': + case 'latin1': + case 'binary': + case 'base64': + case 'ucs2': + case 'ucs-2': + case 'utf16le': + case 'utf-16le': + return true + default: + return false + } +}; + +Buffer.concat = function concat (list, length) { + if (!Array.isArray(list)) { + throw new TypeError('"list" argument must be an Array of Buffers') + } + + if (list.length === 0) { + return Buffer.alloc(0) + } + + let i; + if (length === undefined) { + length = 0; + for (i = 0; i < list.length; ++i) { + length += list[i].length; + } + } + + const buffer = Buffer.allocUnsafe(length); + let pos = 0; + for (i = 0; i < list.length; ++i) { + let buf = list[i]; + if (isInstance(buf, Uint8Array)) { + if (pos + buf.length > buffer.length) { + if (!Buffer.isBuffer(buf)) buf = Buffer.from(buf); + buf.copy(buffer, pos); + } else { + Uint8Array.prototype.set.call( + buffer, + buf, + pos + ); + } + } else if (!Buffer.isBuffer(buf)) { + throw new TypeError('"list" argument must be an Array of Buffers') + } else { + buf.copy(buffer, pos); + } + pos += buf.length; + } + return buffer +}; + +function byteLength (string, encoding) { + if (Buffer.isBuffer(string)) { + return string.length + } + if (ArrayBuffer.isView(string) || isInstance(string, ArrayBuffer)) { + return string.byteLength + } + if (typeof string !== 'string') { + throw new TypeError( + 'The "string" argument must be one of type string, Buffer, or ArrayBuffer. ' + + 'Received type ' + typeof string + ) + } + + const len = string.length; + const mustMatch = (arguments.length > 2 && arguments[2] === true); + if (!mustMatch && len === 0) return 0 + + // Use a for loop to avoid recursion + let loweredCase = false; + for (;;) { + switch (encoding) { + case 'ascii': + case 'latin1': + case 'binary': + return len + case 'utf8': + case 'utf-8': + return utf8ToBytes(string).length + case 'ucs2': + case 'ucs-2': + case 'utf16le': + case 'utf-16le': + return len * 2 + case 'hex': + return len >>> 1 + case 'base64': + return base64ToBytes(string).length + default: + if (loweredCase) { + return mustMatch ? -1 : utf8ToBytes(string).length // assume utf8 + } + encoding = ('' + encoding).toLowerCase(); + loweredCase = true; + } + } +} +Buffer.byteLength = byteLength; + +function slowToString (encoding, start, end) { + let loweredCase = false; + + // No need to verify that "this.length <= MAX_UINT32" since it's a read-only + // property of a typed array. + + // This behaves neither like String nor Uint8Array in that we set start/end + // to their upper/lower bounds if the value passed is out of range. + // undefined is handled specially as per ECMA-262 6th Edition, + // Section 13.3.3.7 Runtime Semantics: KeyedBindingInitialization. + if (start === undefined || start < 0) { + start = 0; + } + // Return early if start > this.length. Done here to prevent potential uint32 + // coercion fail below. + if (start > this.length) { + return '' + } + + if (end === undefined || end > this.length) { + end = this.length; + } + + if (end <= 0) { + return '' + } + + // Force coercion to uint32. This will also coerce falsey/NaN values to 0. + end >>>= 0; + start >>>= 0; + + if (end <= start) { + return '' + } + + if (!encoding) encoding = 'utf8'; + + while (true) { + switch (encoding) { + case 'hex': + return hexSlice(this, start, end) + + case 'utf8': + case 'utf-8': + return utf8Slice(this, start, end) + + case 'ascii': + return asciiSlice(this, start, end) + + case 'latin1': + case 'binary': + return latin1Slice(this, start, end) + + case 'base64': + return base64Slice(this, start, end) + + case 'ucs2': + case 'ucs-2': + case 'utf16le': + case 'utf-16le': + return utf16leSlice(this, start, end) + + default: + if (loweredCase) throw new TypeError('Unknown encoding: ' + encoding) + encoding = (encoding + '').toLowerCase(); + loweredCase = true; + } + } +} + +// This property is used by `Buffer.isBuffer` (and the `is-buffer` npm package) +// to detect a Buffer instance. It's not possible to use `instanceof Buffer` +// reliably in a browserify context because there could be multiple different +// copies of the 'buffer' package in use. This method works even for Buffer +// instances that were created from another copy of the `buffer` package. +// See: https://github.com/feross/buffer/issues/154 +Buffer.prototype._isBuffer = true; + +function swap (b, n, m) { + const i = b[n]; + b[n] = b[m]; + b[m] = i; +} + +Buffer.prototype.swap16 = function swap16 () { + const len = this.length; + if (len % 2 !== 0) { + throw new RangeError('Buffer size must be a multiple of 16-bits') + } + for (let i = 0; i < len; i += 2) { + swap(this, i, i + 1); + } + return this +}; + +Buffer.prototype.swap32 = function swap32 () { + const len = this.length; + if (len % 4 !== 0) { + throw new RangeError('Buffer size must be a multiple of 32-bits') + } + for (let i = 0; i < len; i += 4) { + swap(this, i, i + 3); + swap(this, i + 1, i + 2); + } + return this +}; + +Buffer.prototype.swap64 = function swap64 () { + const len = this.length; + if (len % 8 !== 0) { + throw new RangeError('Buffer size must be a multiple of 64-bits') + } + for (let i = 0; i < len; i += 8) { + swap(this, i, i + 7); + swap(this, i + 1, i + 6); + swap(this, i + 2, i + 5); + swap(this, i + 3, i + 4); + } + return this +}; + +Buffer.prototype.toString = function toString () { + const length = this.length; + if (length === 0) return '' + if (arguments.length === 0) return utf8Slice(this, 0, length) + return slowToString.apply(this, arguments) +}; + +Buffer.prototype.toLocaleString = Buffer.prototype.toString; + +Buffer.prototype.equals = function equals (b) { + if (!Buffer.isBuffer(b)) throw new TypeError('Argument must be a Buffer') + if (this === b) return true + return Buffer.compare(this, b) === 0 +}; + +Buffer.prototype.inspect = function inspect () { + let str = ''; + const max = INSPECT_MAX_BYTES; + str = this.toString('hex', 0, max).replace(/(.{2})/g, '$1 ').trim(); + if (this.length > max) str += ' ... '; + return '' +}; +if (customInspectSymbol) { + Buffer.prototype[customInspectSymbol] = Buffer.prototype.inspect; +} + +Buffer.prototype.compare = function compare (target, start, end, thisStart, thisEnd) { + if (isInstance(target, Uint8Array)) { + target = Buffer.from(target, target.offset, target.byteLength); + } + if (!Buffer.isBuffer(target)) { + throw new TypeError( + 'The "target" argument must be one of type Buffer or Uint8Array. ' + + 'Received type ' + (typeof target) + ) + } + + if (start === undefined) { + start = 0; + } + if (end === undefined) { + end = target ? target.length : 0; + } + if (thisStart === undefined) { + thisStart = 0; + } + if (thisEnd === undefined) { + thisEnd = this.length; + } + + if (start < 0 || end > target.length || thisStart < 0 || thisEnd > this.length) { + throw new RangeError('out of range index') + } + + if (thisStart >= thisEnd && start >= end) { + return 0 + } + if (thisStart >= thisEnd) { + return -1 + } + if (start >= end) { + return 1 + } + + start >>>= 0; + end >>>= 0; + thisStart >>>= 0; + thisEnd >>>= 0; + + if (this === target) return 0 + + let x = thisEnd - thisStart; + let y = end - start; + const len = Math.min(x, y); + + const thisCopy = this.slice(thisStart, thisEnd); + const targetCopy = target.slice(start, end); + + for (let i = 0; i < len; ++i) { + if (thisCopy[i] !== targetCopy[i]) { + x = thisCopy[i]; + y = targetCopy[i]; + break + } + } + + if (x < y) return -1 + if (y < x) return 1 + return 0 +}; + +// Finds either the first index of `val` in `buffer` at offset >= `byteOffset`, +// OR the last index of `val` in `buffer` at offset <= `byteOffset`. +// +// Arguments: +// - buffer - a Buffer to search +// - val - a string, Buffer, or number +// - byteOffset - an index into `buffer`; will be clamped to an int32 +// - encoding - an optional encoding, relevant is val is a string +// - dir - true for indexOf, false for lastIndexOf +function bidirectionalIndexOf (buffer, val, byteOffset, encoding, dir) { + // Empty buffer means no match + if (buffer.length === 0) return -1 + + // Normalize byteOffset + if (typeof byteOffset === 'string') { + encoding = byteOffset; + byteOffset = 0; + } else if (byteOffset > 0x7fffffff) { + byteOffset = 0x7fffffff; + } else if (byteOffset < -2147483648) { + byteOffset = -2147483648; + } + byteOffset = +byteOffset; // Coerce to Number. + if (numberIsNaN(byteOffset)) { + // byteOffset: it it's undefined, null, NaN, "foo", etc, search whole buffer + byteOffset = dir ? 0 : (buffer.length - 1); + } + + // Normalize byteOffset: negative offsets start from the end of the buffer + if (byteOffset < 0) byteOffset = buffer.length + byteOffset; + if (byteOffset >= buffer.length) { + if (dir) return -1 + else byteOffset = buffer.length - 1; + } else if (byteOffset < 0) { + if (dir) byteOffset = 0; + else return -1 + } + + // Normalize val + if (typeof val === 'string') { + val = Buffer.from(val, encoding); + } + + // Finally, search either indexOf (if dir is true) or lastIndexOf + if (Buffer.isBuffer(val)) { + // Special case: looking for empty string/buffer always fails + if (val.length === 0) { + return -1 + } + return arrayIndexOf(buffer, val, byteOffset, encoding, dir) + } else if (typeof val === 'number') { + val = val & 0xFF; // Search for a byte value [0-255] + if (typeof Uint8Array.prototype.indexOf === 'function') { + if (dir) { + return Uint8Array.prototype.indexOf.call(buffer, val, byteOffset) + } else { + return Uint8Array.prototype.lastIndexOf.call(buffer, val, byteOffset) + } + } + return arrayIndexOf(buffer, [val], byteOffset, encoding, dir) + } + + throw new TypeError('val must be string, number or Buffer') +} + +function arrayIndexOf (arr, val, byteOffset, encoding, dir) { + let indexSize = 1; + let arrLength = arr.length; + let valLength = val.length; + + if (encoding !== undefined) { + encoding = String(encoding).toLowerCase(); + if (encoding === 'ucs2' || encoding === 'ucs-2' || + encoding === 'utf16le' || encoding === 'utf-16le') { + if (arr.length < 2 || val.length < 2) { + return -1 + } + indexSize = 2; + arrLength /= 2; + valLength /= 2; + byteOffset /= 2; + } + } + + function read (buf, i) { + if (indexSize === 1) { + return buf[i] + } else { + return buf.readUInt16BE(i * indexSize) + } + } + + let i; + if (dir) { + let foundIndex = -1; + for (i = byteOffset; i < arrLength; i++) { + if (read(arr, i) === read(val, foundIndex === -1 ? 0 : i - foundIndex)) { + if (foundIndex === -1) foundIndex = i; + if (i - foundIndex + 1 === valLength) return foundIndex * indexSize + } else { + if (foundIndex !== -1) i -= i - foundIndex; + foundIndex = -1; + } + } + } else { + if (byteOffset + valLength > arrLength) byteOffset = arrLength - valLength; + for (i = byteOffset; i >= 0; i--) { + let found = true; + for (let j = 0; j < valLength; j++) { + if (read(arr, i + j) !== read(val, j)) { + found = false; + break + } + } + if (found) return i + } + } + + return -1 +} + +Buffer.prototype.includes = function includes (val, byteOffset, encoding) { + return this.indexOf(val, byteOffset, encoding) !== -1 +}; + +Buffer.prototype.indexOf = function indexOf (val, byteOffset, encoding) { + return bidirectionalIndexOf(this, val, byteOffset, encoding, true) +}; + +Buffer.prototype.lastIndexOf = function lastIndexOf (val, byteOffset, encoding) { + return bidirectionalIndexOf(this, val, byteOffset, encoding, false) +}; + +function hexWrite (buf, string, offset, length) { + offset = Number(offset) || 0; + const remaining = buf.length - offset; + if (!length) { + length = remaining; + } else { + length = Number(length); + if (length > remaining) { + length = remaining; + } + } + + const strLen = string.length; + + if (length > strLen / 2) { + length = strLen / 2; + } + let i; + for (i = 0; i < length; ++i) { + const parsed = parseInt(string.substr(i * 2, 2), 16); + if (numberIsNaN(parsed)) return i + buf[offset + i] = parsed; + } + return i +} + +function utf8Write (buf, string, offset, length) { + return blitBuffer(utf8ToBytes(string, buf.length - offset), buf, offset, length) +} + +function asciiWrite (buf, string, offset, length) { + return blitBuffer(asciiToBytes(string), buf, offset, length) +} + +function base64Write (buf, string, offset, length) { + return blitBuffer(base64ToBytes(string), buf, offset, length) +} + +function ucs2Write (buf, string, offset, length) { + return blitBuffer(utf16leToBytes(string, buf.length - offset), buf, offset, length) +} + +Buffer.prototype.write = function write (string, offset, length, encoding) { + // Buffer#write(string) + if (offset === undefined) { + encoding = 'utf8'; + length = this.length; + offset = 0; + // Buffer#write(string, encoding) + } else if (length === undefined && typeof offset === 'string') { + encoding = offset; + length = this.length; + offset = 0; + // Buffer#write(string, offset[, length][, encoding]) + } else if (isFinite(offset)) { + offset = offset >>> 0; + if (isFinite(length)) { + length = length >>> 0; + if (encoding === undefined) encoding = 'utf8'; + } else { + encoding = length; + length = undefined; + } + } else { + throw new Error( + 'Buffer.write(string, encoding, offset[, length]) is no longer supported' + ) + } + + const remaining = this.length - offset; + if (length === undefined || length > remaining) length = remaining; + + if ((string.length > 0 && (length < 0 || offset < 0)) || offset > this.length) { + throw new RangeError('Attempt to write outside buffer bounds') + } + + if (!encoding) encoding = 'utf8'; + + let loweredCase = false; + for (;;) { + switch (encoding) { + case 'hex': + return hexWrite(this, string, offset, length) + + case 'utf8': + case 'utf-8': + return utf8Write(this, string, offset, length) + + case 'ascii': + case 'latin1': + case 'binary': + return asciiWrite(this, string, offset, length) + + case 'base64': + // Warning: maxLength not taken into account in base64Write + return base64Write(this, string, offset, length) + + case 'ucs2': + case 'ucs-2': + case 'utf16le': + case 'utf-16le': + return ucs2Write(this, string, offset, length) + + default: + if (loweredCase) throw new TypeError('Unknown encoding: ' + encoding) + encoding = ('' + encoding).toLowerCase(); + loweredCase = true; + } + } +}; + +Buffer.prototype.toJSON = function toJSON () { + return { + type: 'Buffer', + data: Array.prototype.slice.call(this._arr || this, 0) + } +}; + +function base64Slice (buf, start, end) { + if (start === 0 && end === buf.length) { + return base64JsExports.fromByteArray(buf) + } else { + return base64JsExports.fromByteArray(buf.slice(start, end)) + } +} + +function utf8Slice (buf, start, end) { + end = Math.min(buf.length, end); + const res = []; + + let i = start; + while (i < end) { + const firstByte = buf[i]; + let codePoint = null; + let bytesPerSequence = (firstByte > 0xEF) + ? 4 + : (firstByte > 0xDF) + ? 3 + : (firstByte > 0xBF) + ? 2 + : 1; + + if (i + bytesPerSequence <= end) { + let secondByte, thirdByte, fourthByte, tempCodePoint; + + switch (bytesPerSequence) { + case 1: + if (firstByte < 0x80) { + codePoint = firstByte; + } + break + case 2: + secondByte = buf[i + 1]; + if ((secondByte & 0xC0) === 0x80) { + tempCodePoint = (firstByte & 0x1F) << 0x6 | (secondByte & 0x3F); + if (tempCodePoint > 0x7F) { + codePoint = tempCodePoint; + } + } + break + case 3: + secondByte = buf[i + 1]; + thirdByte = buf[i + 2]; + if ((secondByte & 0xC0) === 0x80 && (thirdByte & 0xC0) === 0x80) { + tempCodePoint = (firstByte & 0xF) << 0xC | (secondByte & 0x3F) << 0x6 | (thirdByte & 0x3F); + if (tempCodePoint > 0x7FF && (tempCodePoint < 0xD800 || tempCodePoint > 0xDFFF)) { + codePoint = tempCodePoint; + } + } + break + case 4: + secondByte = buf[i + 1]; + thirdByte = buf[i + 2]; + fourthByte = buf[i + 3]; + if ((secondByte & 0xC0) === 0x80 && (thirdByte & 0xC0) === 0x80 && (fourthByte & 0xC0) === 0x80) { + tempCodePoint = (firstByte & 0xF) << 0x12 | (secondByte & 0x3F) << 0xC | (thirdByte & 0x3F) << 0x6 | (fourthByte & 0x3F); + if (tempCodePoint > 0xFFFF && tempCodePoint < 0x110000) { + codePoint = tempCodePoint; + } + } + } + } + + if (codePoint === null) { + // we did not generate a valid codePoint so insert a + // replacement char (U+FFFD) and advance only 1 byte + codePoint = 0xFFFD; + bytesPerSequence = 1; + } else if (codePoint > 0xFFFF) { + // encode to utf16 (surrogate pair dance) + codePoint -= 0x10000; + res.push(codePoint >>> 10 & 0x3FF | 0xD800); + codePoint = 0xDC00 | codePoint & 0x3FF; + } + + res.push(codePoint); + i += bytesPerSequence; + } + + return decodeCodePointsArray(res) +} + +// Based on http://stackoverflow.com/a/22747272/680742, the browser with +// the lowest limit is Chrome, with 0x10000 args. +// We go 1 magnitude less, for safety +const MAX_ARGUMENTS_LENGTH = 0x1000; + +function decodeCodePointsArray (codePoints) { + const len = codePoints.length; + if (len <= MAX_ARGUMENTS_LENGTH) { + return String.fromCharCode.apply(String, codePoints) // avoid extra slice() + } + + // Decode in chunks to avoid "call stack size exceeded". + let res = ''; + let i = 0; + while (i < len) { + res += String.fromCharCode.apply( + String, + codePoints.slice(i, i += MAX_ARGUMENTS_LENGTH) + ); + } + return res +} + +function asciiSlice (buf, start, end) { + let ret = ''; + end = Math.min(buf.length, end); + + for (let i = start; i < end; ++i) { + ret += String.fromCharCode(buf[i] & 0x7F); + } + return ret +} + +function latin1Slice (buf, start, end) { + let ret = ''; + end = Math.min(buf.length, end); + + for (let i = start; i < end; ++i) { + ret += String.fromCharCode(buf[i]); + } + return ret +} + +function hexSlice (buf, start, end) { + const len = buf.length; + + if (!start || start < 0) start = 0; + if (!end || end < 0 || end > len) end = len; + + let out = ''; + for (let i = start; i < end; ++i) { + out += hexSliceLookupTable[buf[i]]; + } + return out +} + +function utf16leSlice (buf, start, end) { + const bytes = buf.slice(start, end); + let res = ''; + // If bytes.length is odd, the last 8 bits must be ignored (same as node.js) + for (let i = 0; i < bytes.length - 1; i += 2) { + res += String.fromCharCode(bytes[i] + (bytes[i + 1] * 256)); + } + return res +} + +Buffer.prototype.slice = function slice (start, end) { + const len = this.length; + start = ~~start; + end = end === undefined ? len : ~~end; + + if (start < 0) { + start += len; + if (start < 0) start = 0; + } else if (start > len) { + start = len; + } + + if (end < 0) { + end += len; + if (end < 0) end = 0; + } else if (end > len) { + end = len; + } + + if (end < start) end = start; + + const newBuf = this.subarray(start, end); + // Return an augmented `Uint8Array` instance + Object.setPrototypeOf(newBuf, Buffer.prototype); + + return newBuf +}; + +/* + * Need to make sure that buffer isn't trying to write out of bounds. + */ +function checkOffset (offset, ext, length) { + if ((offset % 1) !== 0 || offset < 0) throw new RangeError('offset is not uint') + if (offset + ext > length) throw new RangeError('Trying to access beyond buffer length') +} + +Buffer.prototype.readUintLE = +Buffer.prototype.readUIntLE = function readUIntLE (offset, byteLength, noAssert) { + offset = offset >>> 0; + byteLength = byteLength >>> 0; + if (!noAssert) checkOffset(offset, byteLength, this.length); + + let val = this[offset]; + let mul = 1; + let i = 0; + while (++i < byteLength && (mul *= 0x100)) { + val += this[offset + i] * mul; + } + + return val +}; + +Buffer.prototype.readUintBE = +Buffer.prototype.readUIntBE = function readUIntBE (offset, byteLength, noAssert) { + offset = offset >>> 0; + byteLength = byteLength >>> 0; + if (!noAssert) { + checkOffset(offset, byteLength, this.length); + } + + let val = this[offset + --byteLength]; + let mul = 1; + while (byteLength > 0 && (mul *= 0x100)) { + val += this[offset + --byteLength] * mul; + } + + return val +}; + +Buffer.prototype.readUint8 = +Buffer.prototype.readUInt8 = function readUInt8 (offset, noAssert) { + offset = offset >>> 0; + if (!noAssert) checkOffset(offset, 1, this.length); + return this[offset] +}; + +Buffer.prototype.readUint16LE = +Buffer.prototype.readUInt16LE = function readUInt16LE (offset, noAssert) { + offset = offset >>> 0; + if (!noAssert) checkOffset(offset, 2, this.length); + return this[offset] | (this[offset + 1] << 8) +}; + +Buffer.prototype.readUint16BE = +Buffer.prototype.readUInt16BE = function readUInt16BE (offset, noAssert) { + offset = offset >>> 0; + if (!noAssert) checkOffset(offset, 2, this.length); + return (this[offset] << 8) | this[offset + 1] +}; + +Buffer.prototype.readUint32LE = +Buffer.prototype.readUInt32LE = function readUInt32LE (offset, noAssert) { + offset = offset >>> 0; + if (!noAssert) checkOffset(offset, 4, this.length); + + return ((this[offset]) | + (this[offset + 1] << 8) | + (this[offset + 2] << 16)) + + (this[offset + 3] * 0x1000000) +}; + +Buffer.prototype.readUint32BE = +Buffer.prototype.readUInt32BE = function readUInt32BE (offset, noAssert) { + offset = offset >>> 0; + if (!noAssert) checkOffset(offset, 4, this.length); + + return (this[offset] * 0x1000000) + + ((this[offset + 1] << 16) | + (this[offset + 2] << 8) | + this[offset + 3]) +}; + +Buffer.prototype.readBigUInt64LE = defineBigIntMethod(function readBigUInt64LE (offset) { + offset = offset >>> 0; + validateNumber(offset, 'offset'); + const first = this[offset]; + const last = this[offset + 7]; + if (first === undefined || last === undefined) { + boundsError(offset, this.length - 8); + } + + const lo = first + + this[++offset] * 2 ** 8 + + this[++offset] * 2 ** 16 + + this[++offset] * 2 ** 24; + + const hi = this[++offset] + + this[++offset] * 2 ** 8 + + this[++offset] * 2 ** 16 + + last * 2 ** 24; + + return BigInt(lo) + (BigInt(hi) << BigInt(32)) +}); + +Buffer.prototype.readBigUInt64BE = defineBigIntMethod(function readBigUInt64BE (offset) { + offset = offset >>> 0; + validateNumber(offset, 'offset'); + const first = this[offset]; + const last = this[offset + 7]; + if (first === undefined || last === undefined) { + boundsError(offset, this.length - 8); + } + + const hi = first * 2 ** 24 + + this[++offset] * 2 ** 16 + + this[++offset] * 2 ** 8 + + this[++offset]; + + const lo = this[++offset] * 2 ** 24 + + this[++offset] * 2 ** 16 + + this[++offset] * 2 ** 8 + + last; + + return (BigInt(hi) << BigInt(32)) + BigInt(lo) +}); + +Buffer.prototype.readIntLE = function readIntLE (offset, byteLength, noAssert) { + offset = offset >>> 0; + byteLength = byteLength >>> 0; + if (!noAssert) checkOffset(offset, byteLength, this.length); + + let val = this[offset]; + let mul = 1; + let i = 0; + while (++i < byteLength && (mul *= 0x100)) { + val += this[offset + i] * mul; + } + mul *= 0x80; + + if (val >= mul) val -= Math.pow(2, 8 * byteLength); + + return val +}; + +Buffer.prototype.readIntBE = function readIntBE (offset, byteLength, noAssert) { + offset = offset >>> 0; + byteLength = byteLength >>> 0; + if (!noAssert) checkOffset(offset, byteLength, this.length); + + let i = byteLength; + let mul = 1; + let val = this[offset + --i]; + while (i > 0 && (mul *= 0x100)) { + val += this[offset + --i] * mul; + } + mul *= 0x80; + + if (val >= mul) val -= Math.pow(2, 8 * byteLength); + + return val +}; + +Buffer.prototype.readInt8 = function readInt8 (offset, noAssert) { + offset = offset >>> 0; + if (!noAssert) checkOffset(offset, 1, this.length); + if (!(this[offset] & 0x80)) return (this[offset]) + return ((0xff - this[offset] + 1) * -1) +}; + +Buffer.prototype.readInt16LE = function readInt16LE (offset, noAssert) { + offset = offset >>> 0; + if (!noAssert) checkOffset(offset, 2, this.length); + const val = this[offset] | (this[offset + 1] << 8); + return (val & 0x8000) ? val | 0xFFFF0000 : val +}; + +Buffer.prototype.readInt16BE = function readInt16BE (offset, noAssert) { + offset = offset >>> 0; + if (!noAssert) checkOffset(offset, 2, this.length); + const val = this[offset + 1] | (this[offset] << 8); + return (val & 0x8000) ? val | 0xFFFF0000 : val +}; + +Buffer.prototype.readInt32LE = function readInt32LE (offset, noAssert) { + offset = offset >>> 0; + if (!noAssert) checkOffset(offset, 4, this.length); + + return (this[offset]) | + (this[offset + 1] << 8) | + (this[offset + 2] << 16) | + (this[offset + 3] << 24) +}; + +Buffer.prototype.readInt32BE = function readInt32BE (offset, noAssert) { + offset = offset >>> 0; + if (!noAssert) checkOffset(offset, 4, this.length); + + return (this[offset] << 24) | + (this[offset + 1] << 16) | + (this[offset + 2] << 8) | + (this[offset + 3]) +}; + +Buffer.prototype.readBigInt64LE = defineBigIntMethod(function readBigInt64LE (offset) { + offset = offset >>> 0; + validateNumber(offset, 'offset'); + const first = this[offset]; + const last = this[offset + 7]; + if (first === undefined || last === undefined) { + boundsError(offset, this.length - 8); + } + + const val = this[offset + 4] + + this[offset + 5] * 2 ** 8 + + this[offset + 6] * 2 ** 16 + + (last << 24); // Overflow + + return (BigInt(val) << BigInt(32)) + + BigInt(first + + this[++offset] * 2 ** 8 + + this[++offset] * 2 ** 16 + + this[++offset] * 2 ** 24) +}); + +Buffer.prototype.readBigInt64BE = defineBigIntMethod(function readBigInt64BE (offset) { + offset = offset >>> 0; + validateNumber(offset, 'offset'); + const first = this[offset]; + const last = this[offset + 7]; + if (first === undefined || last === undefined) { + boundsError(offset, this.length - 8); + } + + const val = (first << 24) + // Overflow + this[++offset] * 2 ** 16 + + this[++offset] * 2 ** 8 + + this[++offset]; + + return (BigInt(val) << BigInt(32)) + + BigInt(this[++offset] * 2 ** 24 + + this[++offset] * 2 ** 16 + + this[++offset] * 2 ** 8 + + last) +}); + +Buffer.prototype.readFloatLE = function readFloatLE (offset, noAssert) { + offset = offset >>> 0; + if (!noAssert) checkOffset(offset, 4, this.length); + return ieee754Exports.read(this, offset, true, 23, 4) +}; + +Buffer.prototype.readFloatBE = function readFloatBE (offset, noAssert) { + offset = offset >>> 0; + if (!noAssert) checkOffset(offset, 4, this.length); + return ieee754Exports.read(this, offset, false, 23, 4) +}; + +Buffer.prototype.readDoubleLE = function readDoubleLE (offset, noAssert) { + offset = offset >>> 0; + if (!noAssert) checkOffset(offset, 8, this.length); + return ieee754Exports.read(this, offset, true, 52, 8) +}; + +Buffer.prototype.readDoubleBE = function readDoubleBE (offset, noAssert) { + offset = offset >>> 0; + if (!noAssert) checkOffset(offset, 8, this.length); + return ieee754Exports.read(this, offset, false, 52, 8) +}; + +function checkInt (buf, value, offset, ext, max, min) { + if (!Buffer.isBuffer(buf)) throw new TypeError('"buffer" argument must be a Buffer instance') + if (value > max || value < min) throw new RangeError('"value" argument is out of bounds') + if (offset + ext > buf.length) throw new RangeError('Index out of range') +} + +Buffer.prototype.writeUintLE = +Buffer.prototype.writeUIntLE = function writeUIntLE (value, offset, byteLength, noAssert) { + value = +value; + offset = offset >>> 0; + byteLength = byteLength >>> 0; + if (!noAssert) { + const maxBytes = Math.pow(2, 8 * byteLength) - 1; + checkInt(this, value, offset, byteLength, maxBytes, 0); + } + + let mul = 1; + let i = 0; + this[offset] = value & 0xFF; + while (++i < byteLength && (mul *= 0x100)) { + this[offset + i] = (value / mul) & 0xFF; + } + + return offset + byteLength +}; + +Buffer.prototype.writeUintBE = +Buffer.prototype.writeUIntBE = function writeUIntBE (value, offset, byteLength, noAssert) { + value = +value; + offset = offset >>> 0; + byteLength = byteLength >>> 0; + if (!noAssert) { + const maxBytes = Math.pow(2, 8 * byteLength) - 1; + checkInt(this, value, offset, byteLength, maxBytes, 0); + } + + let i = byteLength - 1; + let mul = 1; + this[offset + i] = value & 0xFF; + while (--i >= 0 && (mul *= 0x100)) { + this[offset + i] = (value / mul) & 0xFF; + } + + return offset + byteLength +}; + +Buffer.prototype.writeUint8 = +Buffer.prototype.writeUInt8 = function writeUInt8 (value, offset, noAssert) { + value = +value; + offset = offset >>> 0; + if (!noAssert) checkInt(this, value, offset, 1, 0xff, 0); + this[offset] = (value & 0xff); + return offset + 1 +}; + +Buffer.prototype.writeUint16LE = +Buffer.prototype.writeUInt16LE = function writeUInt16LE (value, offset, noAssert) { + value = +value; + offset = offset >>> 0; + if (!noAssert) checkInt(this, value, offset, 2, 0xffff, 0); + this[offset] = (value & 0xff); + this[offset + 1] = (value >>> 8); + return offset + 2 +}; + +Buffer.prototype.writeUint16BE = +Buffer.prototype.writeUInt16BE = function writeUInt16BE (value, offset, noAssert) { + value = +value; + offset = offset >>> 0; + if (!noAssert) checkInt(this, value, offset, 2, 0xffff, 0); + this[offset] = (value >>> 8); + this[offset + 1] = (value & 0xff); + return offset + 2 +}; + +Buffer.prototype.writeUint32LE = +Buffer.prototype.writeUInt32LE = function writeUInt32LE (value, offset, noAssert) { + value = +value; + offset = offset >>> 0; + if (!noAssert) checkInt(this, value, offset, 4, 0xffffffff, 0); + this[offset + 3] = (value >>> 24); + this[offset + 2] = (value >>> 16); + this[offset + 1] = (value >>> 8); + this[offset] = (value & 0xff); + return offset + 4 +}; + +Buffer.prototype.writeUint32BE = +Buffer.prototype.writeUInt32BE = function writeUInt32BE (value, offset, noAssert) { + value = +value; + offset = offset >>> 0; + if (!noAssert) checkInt(this, value, offset, 4, 0xffffffff, 0); + this[offset] = (value >>> 24); + this[offset + 1] = (value >>> 16); + this[offset + 2] = (value >>> 8); + this[offset + 3] = (value & 0xff); + return offset + 4 +}; + +function wrtBigUInt64LE (buf, value, offset, min, max) { + checkIntBI(value, min, max, buf, offset, 7); + + let lo = Number(value & BigInt(0xffffffff)); + buf[offset++] = lo; + lo = lo >> 8; + buf[offset++] = lo; + lo = lo >> 8; + buf[offset++] = lo; + lo = lo >> 8; + buf[offset++] = lo; + let hi = Number(value >> BigInt(32) & BigInt(0xffffffff)); + buf[offset++] = hi; + hi = hi >> 8; + buf[offset++] = hi; + hi = hi >> 8; + buf[offset++] = hi; + hi = hi >> 8; + buf[offset++] = hi; + return offset +} + +function wrtBigUInt64BE (buf, value, offset, min, max) { + checkIntBI(value, min, max, buf, offset, 7); + + let lo = Number(value & BigInt(0xffffffff)); + buf[offset + 7] = lo; + lo = lo >> 8; + buf[offset + 6] = lo; + lo = lo >> 8; + buf[offset + 5] = lo; + lo = lo >> 8; + buf[offset + 4] = lo; + let hi = Number(value >> BigInt(32) & BigInt(0xffffffff)); + buf[offset + 3] = hi; + hi = hi >> 8; + buf[offset + 2] = hi; + hi = hi >> 8; + buf[offset + 1] = hi; + hi = hi >> 8; + buf[offset] = hi; + return offset + 8 +} + +Buffer.prototype.writeBigUInt64LE = defineBigIntMethod(function writeBigUInt64LE (value, offset = 0) { + return wrtBigUInt64LE(this, value, offset, BigInt(0), BigInt('0xffffffffffffffff')) +}); + +Buffer.prototype.writeBigUInt64BE = defineBigIntMethod(function writeBigUInt64BE (value, offset = 0) { + return wrtBigUInt64BE(this, value, offset, BigInt(0), BigInt('0xffffffffffffffff')) +}); + +Buffer.prototype.writeIntLE = function writeIntLE (value, offset, byteLength, noAssert) { + value = +value; + offset = offset >>> 0; + if (!noAssert) { + const limit = Math.pow(2, (8 * byteLength) - 1); + + checkInt(this, value, offset, byteLength, limit - 1, -limit); + } + + let i = 0; + let mul = 1; + let sub = 0; + this[offset] = value & 0xFF; + while (++i < byteLength && (mul *= 0x100)) { + if (value < 0 && sub === 0 && this[offset + i - 1] !== 0) { + sub = 1; + } + this[offset + i] = ((value / mul) >> 0) - sub & 0xFF; + } + + return offset + byteLength +}; + +Buffer.prototype.writeIntBE = function writeIntBE (value, offset, byteLength, noAssert) { + value = +value; + offset = offset >>> 0; + if (!noAssert) { + const limit = Math.pow(2, (8 * byteLength) - 1); + + checkInt(this, value, offset, byteLength, limit - 1, -limit); + } + + let i = byteLength - 1; + let mul = 1; + let sub = 0; + this[offset + i] = value & 0xFF; + while (--i >= 0 && (mul *= 0x100)) { + if (value < 0 && sub === 0 && this[offset + i + 1] !== 0) { + sub = 1; + } + this[offset + i] = ((value / mul) >> 0) - sub & 0xFF; + } + + return offset + byteLength +}; + +Buffer.prototype.writeInt8 = function writeInt8 (value, offset, noAssert) { + value = +value; + offset = offset >>> 0; + if (!noAssert) checkInt(this, value, offset, 1, 0x7f, -128); + if (value < 0) value = 0xff + value + 1; + this[offset] = (value & 0xff); + return offset + 1 +}; + +Buffer.prototype.writeInt16LE = function writeInt16LE (value, offset, noAssert) { + value = +value; + offset = offset >>> 0; + if (!noAssert) checkInt(this, value, offset, 2, 0x7fff, -32768); + this[offset] = (value & 0xff); + this[offset + 1] = (value >>> 8); + return offset + 2 +}; + +Buffer.prototype.writeInt16BE = function writeInt16BE (value, offset, noAssert) { + value = +value; + offset = offset >>> 0; + if (!noAssert) checkInt(this, value, offset, 2, 0x7fff, -32768); + this[offset] = (value >>> 8); + this[offset + 1] = (value & 0xff); + return offset + 2 +}; + +Buffer.prototype.writeInt32LE = function writeInt32LE (value, offset, noAssert) { + value = +value; + offset = offset >>> 0; + if (!noAssert) checkInt(this, value, offset, 4, 0x7fffffff, -2147483648); + this[offset] = (value & 0xff); + this[offset + 1] = (value >>> 8); + this[offset + 2] = (value >>> 16); + this[offset + 3] = (value >>> 24); + return offset + 4 +}; + +Buffer.prototype.writeInt32BE = function writeInt32BE (value, offset, noAssert) { + value = +value; + offset = offset >>> 0; + if (!noAssert) checkInt(this, value, offset, 4, 0x7fffffff, -2147483648); + if (value < 0) value = 0xffffffff + value + 1; + this[offset] = (value >>> 24); + this[offset + 1] = (value >>> 16); + this[offset + 2] = (value >>> 8); + this[offset + 3] = (value & 0xff); + return offset + 4 +}; + +Buffer.prototype.writeBigInt64LE = defineBigIntMethod(function writeBigInt64LE (value, offset = 0) { + return wrtBigUInt64LE(this, value, offset, -BigInt('0x8000000000000000'), BigInt('0x7fffffffffffffff')) +}); + +Buffer.prototype.writeBigInt64BE = defineBigIntMethod(function writeBigInt64BE (value, offset = 0) { + return wrtBigUInt64BE(this, value, offset, -BigInt('0x8000000000000000'), BigInt('0x7fffffffffffffff')) +}); + +function checkIEEE754 (buf, value, offset, ext, max, min) { + if (offset + ext > buf.length) throw new RangeError('Index out of range') + if (offset < 0) throw new RangeError('Index out of range') +} + +function writeFloat (buf, value, offset, littleEndian, noAssert) { + value = +value; + offset = offset >>> 0; + if (!noAssert) { + checkIEEE754(buf, value, offset, 4); + } + ieee754Exports.write(buf, value, offset, littleEndian, 23, 4); + return offset + 4 +} + +Buffer.prototype.writeFloatLE = function writeFloatLE (value, offset, noAssert) { + return writeFloat(this, value, offset, true, noAssert) +}; + +Buffer.prototype.writeFloatBE = function writeFloatBE (value, offset, noAssert) { + return writeFloat(this, value, offset, false, noAssert) +}; + +function writeDouble (buf, value, offset, littleEndian, noAssert) { + value = +value; + offset = offset >>> 0; + if (!noAssert) { + checkIEEE754(buf, value, offset, 8); + } + ieee754Exports.write(buf, value, offset, littleEndian, 52, 8); + return offset + 8 +} + +Buffer.prototype.writeDoubleLE = function writeDoubleLE (value, offset, noAssert) { + return writeDouble(this, value, offset, true, noAssert) +}; + +Buffer.prototype.writeDoubleBE = function writeDoubleBE (value, offset, noAssert) { + return writeDouble(this, value, offset, false, noAssert) +}; + +// copy(targetBuffer, targetStart=0, sourceStart=0, sourceEnd=buffer.length) +Buffer.prototype.copy = function copy (target, targetStart, start, end) { + if (!Buffer.isBuffer(target)) throw new TypeError('argument should be a Buffer') + if (!start) start = 0; + if (!end && end !== 0) end = this.length; + if (targetStart >= target.length) targetStart = target.length; + if (!targetStart) targetStart = 0; + if (end > 0 && end < start) end = start; + + // Copy 0 bytes; we're done + if (end === start) return 0 + if (target.length === 0 || this.length === 0) return 0 + + // Fatal error conditions + if (targetStart < 0) { + throw new RangeError('targetStart out of bounds') + } + if (start < 0 || start >= this.length) throw new RangeError('Index out of range') + if (end < 0) throw new RangeError('sourceEnd out of bounds') + + // Are we oob? + if (end > this.length) end = this.length; + if (target.length - targetStart < end - start) { + end = target.length - targetStart + start; + } + + const len = end - start; + + if (this === target && typeof Uint8Array.prototype.copyWithin === 'function') { + // Use built-in when available, missing from IE11 + this.copyWithin(targetStart, start, end); + } else { + Uint8Array.prototype.set.call( + target, + this.subarray(start, end), + targetStart + ); + } + + return len +}; + +// Usage: +// buffer.fill(number[, offset[, end]]) +// buffer.fill(buffer[, offset[, end]]) +// buffer.fill(string[, offset[, end]][, encoding]) +Buffer.prototype.fill = function fill (val, start, end, encoding) { + // Handle string cases: + if (typeof val === 'string') { + if (typeof start === 'string') { + encoding = start; + start = 0; + end = this.length; + } else if (typeof end === 'string') { + encoding = end; + end = this.length; + } + if (encoding !== undefined && typeof encoding !== 'string') { + throw new TypeError('encoding must be a string') + } + if (typeof encoding === 'string' && !Buffer.isEncoding(encoding)) { + throw new TypeError('Unknown encoding: ' + encoding) + } + if (val.length === 1) { + const code = val.charCodeAt(0); + if ((encoding === 'utf8' && code < 128) || + encoding === 'latin1') { + // Fast path: If `val` fits into a single byte, use that numeric value. + val = code; + } + } + } else if (typeof val === 'number') { + val = val & 255; + } else if (typeof val === 'boolean') { + val = Number(val); + } + + // Invalid ranges are not set to a default, so can range check early. + if (start < 0 || this.length < start || this.length < end) { + throw new RangeError('Out of range index') + } + + if (end <= start) { + return this + } + + start = start >>> 0; + end = end === undefined ? this.length : end >>> 0; + + if (!val) val = 0; + + let i; + if (typeof val === 'number') { + for (i = start; i < end; ++i) { + this[i] = val; + } + } else { + const bytes = Buffer.isBuffer(val) + ? val + : Buffer.from(val, encoding); + const len = bytes.length; + if (len === 0) { + throw new TypeError('The value "' + val + + '" is invalid for argument "value"') + } + for (i = 0; i < end - start; ++i) { + this[i + start] = bytes[i % len]; + } + } + + return this +}; + +// CUSTOM ERRORS +// ============= + +// Simplified versions from Node, changed for Buffer-only usage +const errors$2 = {}; +function E (sym, getMessage, Base) { + errors$2[sym] = class NodeError extends Base { + constructor () { + super(); + + Object.defineProperty(this, 'message', { + value: getMessage.apply(this, arguments), + writable: true, + configurable: true + }); + + // Add the error code to the name to include it in the stack trace. + this.name = `${this.name} [${sym}]`; + // Access the stack to generate the error message including the error code + // from the name. + this.stack; // eslint-disable-line no-unused-expressions + // Reset the name to the actual name. + delete this.name; + } + + get code () { + return sym + } + + set code (value) { + Object.defineProperty(this, 'code', { + configurable: true, + enumerable: true, + value, + writable: true + }); + } + + toString () { + return `${this.name} [${sym}]: ${this.message}` + } + }; +} + +E('ERR_BUFFER_OUT_OF_BOUNDS', + function (name) { + if (name) { + return `${name} is outside of buffer bounds` + } + + return 'Attempt to access memory outside buffer bounds' + }, RangeError); +E('ERR_INVALID_ARG_TYPE', + function (name, actual) { + return `The "${name}" argument must be of type number. Received type ${typeof actual}` + }, TypeError); +E('ERR_OUT_OF_RANGE', + function (str, range, input) { + let msg = `The value of "${str}" is out of range.`; + let received = input; + if (Number.isInteger(input) && Math.abs(input) > 2 ** 32) { + received = addNumericalSeparator(String(input)); + } else if (typeof input === 'bigint') { + received = String(input); + if (input > BigInt(2) ** BigInt(32) || input < -(BigInt(2) ** BigInt(32))) { + received = addNumericalSeparator(received); + } + received += 'n'; + } + msg += ` It must be ${range}. Received ${received}`; + return msg + }, RangeError); + +function addNumericalSeparator (val) { + let res = ''; + let i = val.length; + const start = val[0] === '-' ? 1 : 0; + for (; i >= start + 4; i -= 3) { + res = `_${val.slice(i - 3, i)}${res}`; + } + return `${val.slice(0, i)}${res}` +} + +// CHECK FUNCTIONS +// =============== + +function checkBounds (buf, offset, byteLength) { + validateNumber(offset, 'offset'); + if (buf[offset] === undefined || buf[offset + byteLength] === undefined) { + boundsError(offset, buf.length - (byteLength + 1)); + } +} + +function checkIntBI (value, min, max, buf, offset, byteLength) { + if (value > max || value < min) { + const n = typeof min === 'bigint' ? 'n' : ''; + let range; + { + if (min === 0 || min === BigInt(0)) { + range = `>= 0${n} and < 2${n} ** ${(byteLength + 1) * 8}${n}`; + } else { + range = `>= -(2${n} ** ${(byteLength + 1) * 8 - 1}${n}) and < 2 ** ` + + `${(byteLength + 1) * 8 - 1}${n}`; + } + } + throw new errors$2.ERR_OUT_OF_RANGE('value', range, value) + } + checkBounds(buf, offset, byteLength); +} + +function validateNumber (value, name) { + if (typeof value !== 'number') { + throw new errors$2.ERR_INVALID_ARG_TYPE(name, 'number', value) + } +} + +function boundsError (value, length, type) { + if (Math.floor(value) !== value) { + validateNumber(value, type); + throw new errors$2.ERR_OUT_OF_RANGE('offset', 'an integer', value) + } + + if (length < 0) { + throw new errors$2.ERR_BUFFER_OUT_OF_BOUNDS() + } + + throw new errors$2.ERR_OUT_OF_RANGE('offset', + `>= ${0} and <= ${length}`, + value) +} + +// HELPER FUNCTIONS +// ================ + +const INVALID_BASE64_RE = /[^+/0-9A-Za-z-_]/g; + +function base64clean (str) { + // Node takes equal signs as end of the Base64 encoding + str = str.split('=')[0]; + // Node strips out invalid characters like \n and \t from the string, base64-js does not + str = str.trim().replace(INVALID_BASE64_RE, ''); + // Node converts strings with length < 2 to '' + if (str.length < 2) return '' + // Node allows for non-padded base64 strings (missing trailing ===), base64-js does not + while (str.length % 4 !== 0) { + str = str + '='; + } + return str +} + +function utf8ToBytes (string, units) { + units = units || Infinity; + let codePoint; + const length = string.length; + let leadSurrogate = null; + const bytes = []; + + for (let i = 0; i < length; ++i) { + codePoint = string.charCodeAt(i); + + // is surrogate component + if (codePoint > 0xD7FF && codePoint < 0xE000) { + // last char was a lead + if (!leadSurrogate) { + // no lead yet + if (codePoint > 0xDBFF) { + // unexpected trail + if ((units -= 3) > -1) bytes.push(0xEF, 0xBF, 0xBD); + continue + } else if (i + 1 === length) { + // unpaired lead + if ((units -= 3) > -1) bytes.push(0xEF, 0xBF, 0xBD); + continue + } + + // valid lead + leadSurrogate = codePoint; + + continue + } + + // 2 leads in a row + if (codePoint < 0xDC00) { + if ((units -= 3) > -1) bytes.push(0xEF, 0xBF, 0xBD); + leadSurrogate = codePoint; + continue + } + + // valid surrogate pair + codePoint = (leadSurrogate - 0xD800 << 10 | codePoint - 0xDC00) + 0x10000; + } else if (leadSurrogate) { + // valid bmp char, but last char was a lead + if ((units -= 3) > -1) bytes.push(0xEF, 0xBF, 0xBD); + } + + leadSurrogate = null; + + // encode utf8 + if (codePoint < 0x80) { + if ((units -= 1) < 0) break + bytes.push(codePoint); + } else if (codePoint < 0x800) { + if ((units -= 2) < 0) break + bytes.push( + codePoint >> 0x6 | 0xC0, + codePoint & 0x3F | 0x80 + ); + } else if (codePoint < 0x10000) { + if ((units -= 3) < 0) break + bytes.push( + codePoint >> 0xC | 0xE0, + codePoint >> 0x6 & 0x3F | 0x80, + codePoint & 0x3F | 0x80 + ); + } else if (codePoint < 0x110000) { + if ((units -= 4) < 0) break + bytes.push( + codePoint >> 0x12 | 0xF0, + codePoint >> 0xC & 0x3F | 0x80, + codePoint >> 0x6 & 0x3F | 0x80, + codePoint & 0x3F | 0x80 + ); + } else { + throw new Error('Invalid code point') + } + } + + return bytes +} + +function asciiToBytes (str) { + const byteArray = []; + for (let i = 0; i < str.length; ++i) { + // Node's code seems to be doing this and not & 0x7F.. + byteArray.push(str.charCodeAt(i) & 0xFF); + } + return byteArray +} + +function utf16leToBytes (str, units) { + let c, hi, lo; + const byteArray = []; + for (let i = 0; i < str.length; ++i) { + if ((units -= 2) < 0) break + + c = str.charCodeAt(i); + hi = c >> 8; + lo = c % 256; + byteArray.push(lo); + byteArray.push(hi); + } + + return byteArray +} + +function base64ToBytes (str) { + return base64JsExports.toByteArray(base64clean(str)) +} + +function blitBuffer (src, dst, offset, length) { + let i; + for (i = 0; i < length; ++i) { + if ((i + offset >= dst.length) || (i >= src.length)) break + dst[i + offset] = src[i]; + } + return i +} + +// ArrayBuffer or Uint8Array objects from other contexts (i.e. iframes) do not pass +// the `instanceof` check but they should be treated as of that type. +// See: https://github.com/feross/buffer/issues/166 +function isInstance (obj, type) { + return obj instanceof type || + (obj != null && obj.constructor != null && obj.constructor.name != null && + obj.constructor.name === type.name) +} +function numberIsNaN (obj) { + // For IE11 support + return obj !== obj // eslint-disable-line no-self-compare +} + +// Create lookup table for `toString('hex')` +// See: https://github.com/feross/buffer/issues/219 +const hexSliceLookupTable = (function () { + const alphabet = '0123456789abcdef'; + const table = new Array(256); + for (let i = 0; i < 16; ++i) { + const i16 = i * 16; + for (let j = 0; j < 16; ++j) { + table[i16 + j] = alphabet[i] + alphabet[j]; + } + } + return table +})(); + +// Return not function with Error if BigInt not supported +function defineBigIntMethod (fn) { + return typeof BigInt === 'undefined' ? BufferBigIntNotDefined : fn +} + +function BufferBigIntNotDefined () { + throw new Error('BigInt not supported') +} + +var buffer = /*#__PURE__*/Object.freeze({ + __proto__: null, + Buffer: Buffer, + INSPECT_MAX_BYTES: INSPECT_MAX_BYTES, + SlowBuffer: SlowBuffer, + kMaxLength: kMaxLength +}); + +var require$$0$1 = /*@__PURE__*/getAugmentedNamespace(buffer); + +var hasRequiredBuffer$1; + +function requireBuffer$1 () { + if (hasRequiredBuffer$1) return buffer$1; + hasRequiredBuffer$1 = 1; + (function (exports) { + Object.defineProperty(exports, "__esModule", { value: true }); + exports.Buffer = void 0; + var node_buffer_1 = require$$0$1; + Object.defineProperty(exports, "Buffer", { enumerable: true, get: function () { return node_buffer_1.Buffer; } }); + + } (buffer$1)); + return buffer$1; +} + +var hasRequiredBuffer; + +function requireBuffer () { + if (hasRequiredBuffer) return buffer$2; + hasRequiredBuffer = 1; + (function (exports) { + Object.defineProperty(exports, "__esModule", { value: true }); + exports.bufferFrom = exports.bufferAllocUnsafe = exports.Buffer = void 0; + const buffer_1 = requireBuffer$1(); + Object.defineProperty(exports, "Buffer", { enumerable: true, get: function () { return buffer_1.Buffer; } }); + function bufferV0P12Ponyfill(arg0, ...args) { + return new buffer_1.Buffer(arg0, ...args); + } + const bufferAllocUnsafe = buffer_1.Buffer.allocUnsafe || bufferV0P12Ponyfill; + exports.bufferAllocUnsafe = bufferAllocUnsafe; + const bufferFrom = buffer_1.Buffer.from || bufferV0P12Ponyfill; + exports.bufferFrom = bufferFrom; + + } (buffer$2)); + return buffer$2; +} + +var hasRequiredJson$1; + +function requireJson$1 () { + if (hasRequiredJson$1) return json$1; + hasRequiredJson$1 = 1; + Object.defineProperty(json$1, "__esModule", { value: true }); + json$1.flattenJSON = void 0; + const buffer_1 = requireBuffer(); + const path_1 = requirePath$1(); + const pathJoin = path_1.posix ? path_1.posix.join : path_1.join; + const flattenJSON = (nestedJSON) => { + const flatJSON = {}; + function flatten(pathPrefix, node) { + for (const path in node) { + const contentOrNode = node[path]; + // TODO: Can we avoid using `join` here? Just concatenate? + const joinedPath = pathJoin(pathPrefix, path); + if (typeof contentOrNode === 'string' || contentOrNode instanceof buffer_1.Buffer) { + flatJSON[joinedPath] = contentOrNode; + } + else if (typeof contentOrNode === 'object' && + contentOrNode !== null && + !(contentOrNode instanceof buffer_1.Buffer) && + Object.keys(contentOrNode).length > 0) { + // empty directories need an explicit entry and therefore get handled in `else`, non-empty ones are implicitly considered + flatten(joinedPath, contentOrNode); + } + else { + // without this branch null, empty-object or non-object entries would not be handled in the same way + // by both fromJSON() and fromNestedJSON() + flatJSON[joinedPath] = null; + } + } + } + flatten('', nestedJSON); + return flatJSON; + }; + json$1.flattenJSON = flattenJSON; + + return json$1; +} + +var constants$3 = {}; + +var hasRequiredConstants$3; + +function requireConstants$3 () { + if (hasRequiredConstants$3) return constants$3; + hasRequiredConstants$3 = 1; + Object.defineProperty(constants$3, "__esModule", { value: true }); + + return constants$3; +} + +var result = {}; + +var hasRequiredResult; + +function requireResult () { + if (hasRequiredResult) return result; + hasRequiredResult = 1; + Object.defineProperty(result, "__esModule", { value: true }); + result.Ok = Ok; + result.Err = Err; + function Ok(value) { + return { ok: true, value }; + } + function Err(err) { + return { ok: false, err }; + } + + return result; +} + +var Node = {}; + +var fanout = {}; + +var hasRequiredFanout; + +function requireFanout () { + if (hasRequiredFanout) return fanout; + hasRequiredFanout = 1; + Object.defineProperty(fanout, "__esModule", { value: true }); + fanout.FanOut = void 0; + class FanOut { + constructor() { + this.listeners = new Set(); + } + emit(data) { + this.listeners.forEach((listener) => listener(data)); + } + listen(listener) { + const listeners = this.listeners; + listeners.add(listener); + return () => listeners.delete(listener); + } + } + fanout.FanOut = FanOut; + return fanout; +} + +var process = {}; + +var hasRequiredProcess; + +function requireProcess () { + if (hasRequiredProcess) return process; + hasRequiredProcess = 1; + // Here we mock the undefined `process` variable in case we are not in Node's environment. + Object.defineProperty(process, "__esModule", { value: true }); + process.createProcess = createProcess; + /** + * Looks to return a `process` object, if one is available. + * + * The undefined `process` is returned if defined; + * otherwise `require('process')` is attempted. + * + * If that fails, `undefined` is returned. + * + * @return {IProcess | undefined} + */ + const maybeReturnProcess = () => { + if (typeof process$1 !== 'undefined') { + return process$1; + } + try { + return requireBrowser$2(); + } + catch { + return undefined; + } + }; + function createProcess() { + const p = maybeReturnProcess() || {}; + if (!p.cwd) + p.cwd = () => '/'; + if (!p.emitWarning) + p.emitWarning = (message, type) => { + // tslint:disable-next-line:no-console + console.warn(`${type}${type ? ': ' : ''}${message}`); + }; + if (!p.env) + p.env = {}; + return p; + } + process.default = createProcess(); + + return process; +} + +var lib$5 = {}; + +var types = {}; + +var hasRequiredTypes; + +function requireTypes () { + if (hasRequiredTypes) return types; + hasRequiredTypes = 1; + Object.defineProperty(types, "__esModule", { value: true }); + + return types; +} + +var constants$2 = {}; + +var hasRequiredConstants$2; + +function requireConstants$2 () { + if (hasRequiredConstants$2) return constants$2; + hasRequiredConstants$2 = 1; + (function (exports) { + Object.defineProperty(exports, "__esModule", { value: true }); + exports.FLAGS = exports.ERRSTR = exports.constants = exports.SEP = void 0; + exports.SEP = '/'; + exports.constants = { + O_RDONLY: 0, + O_WRONLY: 1, + O_RDWR: 2, + S_IFMT: 61440, + S_IFREG: 32768, + S_IFDIR: 16384, + S_IFCHR: 8192, + S_IFBLK: 24576, + S_IFIFO: 4096, + S_IFLNK: 40960, + S_IFSOCK: 49152, + O_CREAT: 64, + O_EXCL: 128, + O_NOCTTY: 256, + O_TRUNC: 512, + O_APPEND: 1024, + O_DIRECTORY: 65536, + O_NOATIME: 262144, + O_NOFOLLOW: 131072, + O_SYNC: 1052672, + O_SYMLINK: 2097152, + O_DIRECT: 16384, + O_NONBLOCK: 2048, + S_IRWXU: 448, + S_IRUSR: 256, + S_IWUSR: 128, + S_IXUSR: 64, + S_IRWXG: 56, + S_IRGRP: 32, + S_IWGRP: 16, + S_IXGRP: 8, + S_IRWXO: 7, + S_IROTH: 4, + S_IWOTH: 2, + S_IXOTH: 1, + F_OK: 0, + R_OK: 4, + W_OK: 2, + X_OK: 1, + UV_FS_SYMLINK_DIR: 1, + UV_FS_SYMLINK_JUNCTION: 2, + UV_FS_COPYFILE_EXCL: 1, + UV_FS_COPYFILE_FICLONE: 2, + UV_FS_COPYFILE_FICLONE_FORCE: 4, + COPYFILE_EXCL: 1, + COPYFILE_FICLONE: 2, + COPYFILE_FICLONE_FORCE: 4, + }; + exports.ERRSTR = { + PATH_STR: 'path must be a string, Buffer, or Uint8Array', + // FD: 'file descriptor must be a unsigned 32-bit integer', + FD: 'fd must be a file descriptor', + MODE_INT: 'mode must be an int', + CB: 'callback must be a function', + UID: 'uid must be an unsigned int', + GID: 'gid must be an unsigned int', + LEN: 'len must be an integer', + ATIME: 'atime must be an integer', + MTIME: 'mtime must be an integer', + PREFIX: 'filename prefix is required', + BUFFER: 'buffer must be an instance of Buffer or StaticBuffer', + OFFSET: 'offset must be an integer', + LENGTH: 'length must be an integer', + POSITION: 'position must be an integer', + }; + const { O_RDONLY, O_WRONLY, O_RDWR, O_CREAT, O_EXCL, O_TRUNC, O_APPEND, O_SYNC } = exports.constants; + // List of file `flags` as defined by Node. + var FLAGS; + (function (FLAGS) { + // Open file for reading. An exception occurs if the file does not exist. + FLAGS[FLAGS["r"] = O_RDONLY] = "r"; + // Open file for reading and writing. An exception occurs if the file does not exist. + FLAGS[FLAGS["r+"] = O_RDWR] = "r+"; + // Open file for reading in synchronous mode. Instructs the operating system to bypass the local file system cache. + FLAGS[FLAGS["rs"] = O_RDONLY | O_SYNC] = "rs"; + FLAGS[FLAGS["sr"] = FLAGS.rs] = "sr"; + // Open file for reading and writing, telling the OS to open it synchronously. See notes for 'rs' about using this with caution. + FLAGS[FLAGS["rs+"] = O_RDWR | O_SYNC] = "rs+"; + FLAGS[FLAGS["sr+"] = FLAGS['rs+']] = "sr+"; + // Open file for writing. The file is created (if it does not exist) or truncated (if it exists). + FLAGS[FLAGS["w"] = O_WRONLY | O_CREAT | O_TRUNC] = "w"; + // Like 'w' but fails if path exists. + FLAGS[FLAGS["wx"] = O_WRONLY | O_CREAT | O_TRUNC | O_EXCL] = "wx"; + FLAGS[FLAGS["xw"] = FLAGS.wx] = "xw"; + // Open file for reading and writing. The file is created (if it does not exist) or truncated (if it exists). + FLAGS[FLAGS["w+"] = O_RDWR | O_CREAT | O_TRUNC] = "w+"; + // Like 'w+' but fails if path exists. + FLAGS[FLAGS["wx+"] = O_RDWR | O_CREAT | O_TRUNC | O_EXCL] = "wx+"; + FLAGS[FLAGS["xw+"] = FLAGS['wx+']] = "xw+"; + // Open file for appending. The file is created if it does not exist. + FLAGS[FLAGS["a"] = O_WRONLY | O_APPEND | O_CREAT] = "a"; + // Like 'a' but fails if path exists. + FLAGS[FLAGS["ax"] = O_WRONLY | O_APPEND | O_CREAT | O_EXCL] = "ax"; + FLAGS[FLAGS["xa"] = FLAGS.ax] = "xa"; + // Open file for reading and appending. The file is created if it does not exist. + FLAGS[FLAGS["a+"] = O_RDWR | O_APPEND | O_CREAT] = "a+"; + // Like 'a+' but fails if path exists. + FLAGS[FLAGS["ax+"] = O_RDWR | O_APPEND | O_CREAT | O_EXCL] = "ax+"; + FLAGS[FLAGS["xa+"] = FLAGS['ax+']] = "xa+"; + })(FLAGS || (exports.FLAGS = FLAGS = {})); + + } (constants$2)); + return constants$2; +} + +var AMODE = {}; + +var hasRequiredAMODE; + +function requireAMODE () { + if (hasRequiredAMODE) return AMODE; + hasRequiredAMODE = 1; + Object.defineProperty(AMODE, "__esModule", { value: true }); + + return AMODE; +} + +var FLAG = {}; + +var hasRequiredFLAG; + +function requireFLAG () { + if (hasRequiredFLAG) return FLAG; + hasRequiredFLAG = 1; + Object.defineProperty(FLAG, "__esModule", { value: true }); + FLAG.FLAG = void 0; + /** + * Constants used in `open` system calls, see [open(2)](http://man7.org/linux/man-pages/man2/open.2.html). + * + * These constants are compatible with Node.js fs constants and can be used with both + * memfs and native Node.js fs.promises.open(). + * + * @see http://man7.org/linux/man-pages/man2/open.2.html + * @see https://www.gnu.org/software/libc/manual/html_node/Open_002dtime-Flags.html + */ + var FLAG$1; + (function (FLAG) { + FLAG[FLAG["O_RDONLY"] = 0] = "O_RDONLY"; + FLAG[FLAG["O_WRONLY"] = 1] = "O_WRONLY"; + FLAG[FLAG["O_RDWR"] = 2] = "O_RDWR"; + FLAG[FLAG["O_ACCMODE"] = 3] = "O_ACCMODE"; + FLAG[FLAG["O_CREAT"] = 64] = "O_CREAT"; + FLAG[FLAG["O_EXCL"] = 128] = "O_EXCL"; + FLAG[FLAG["O_NOCTTY"] = 256] = "O_NOCTTY"; + FLAG[FLAG["O_TRUNC"] = 512] = "O_TRUNC"; + FLAG[FLAG["O_APPEND"] = 1024] = "O_APPEND"; + FLAG[FLAG["O_NONBLOCK"] = 2048] = "O_NONBLOCK"; + FLAG[FLAG["O_DSYNC"] = 4096] = "O_DSYNC"; + FLAG[FLAG["FASYNC"] = 8192] = "FASYNC"; + FLAG[FLAG["O_DIRECT"] = 16384] = "O_DIRECT"; + FLAG[FLAG["O_LARGEFILE"] = 0] = "O_LARGEFILE"; + FLAG[FLAG["O_DIRECTORY"] = 65536] = "O_DIRECTORY"; + FLAG[FLAG["O_NOFOLLOW"] = 131072] = "O_NOFOLLOW"; + FLAG[FLAG["O_NOATIME"] = 262144] = "O_NOATIME"; + FLAG[FLAG["O_CLOEXEC"] = 524288] = "O_CLOEXEC"; + FLAG[FLAG["O_SYNC"] = 1052672] = "O_SYNC"; + FLAG[FLAG["O_NDELAY"] = 2048] = "O_NDELAY"; + })(FLAG$1 || (FLAG.FLAG = FLAG$1 = {})); + + return FLAG; +} + +var path = {}; + +var hasRequiredPath; + +function requirePath () { + if (hasRequiredPath) return path; + hasRequiredPath = 1; + Object.defineProperty(path, "__esModule", { value: true }); + path.basename = void 0; + const basename = (path, separator) => { + if (path[path.length - 1] === separator) + path = path.slice(0, -1); + const lastSlashIndex = path.lastIndexOf(separator); + return lastSlashIndex === -1 ? path : path.slice(lastSlashIndex + 1); + }; + path.basename = basename; + + return path; +} + +var encoding$1 = {}; + +var errors$1 = {}; + +var util$4 = {}; + +var hasRequiredUtil$4; + +function requireUtil$4 () { + if (hasRequiredUtil$4) return util$4; + hasRequiredUtil$4 = 1; + Object.defineProperty(util$4, "__esModule", { value: true }); + util$4.inherits = inherits; + util$4.promisify = promisify; + util$4.inspect = inspect; + util$4.format = format; + /** + * Minimal implementation of Node.js util.inherits function. + * Sets up prototype inheritance between constructor functions. + */ + function inherits(ctor, superCtor) { + if (ctor === undefined || ctor === null) { + throw new TypeError('The constructor to inherit from is not defined'); + } + if (superCtor === undefined || superCtor === null) { + throw new TypeError('The super constructor to inherit from is not defined'); + } + ctor.super_ = superCtor; + ctor.prototype = Object.create(superCtor.prototype, { + constructor: { + value: ctor, + enumerable: false, + writable: true, + configurable: true, + }, + }); + } + /** + * Minimal implementation of Node.js util.promisify function. + * Converts callback-based functions to Promise-based functions. + */ + function promisify(fn) { + if (typeof fn !== 'function') { + throw new TypeError('The "original" argument must be of type function'); + } + return function (...args) { + return new Promise((resolve, reject) => { + fn.call(this, ...args, (err, result) => { + if (err) { + reject(err); + } + else { + resolve(result); + } + }); + }); + }; + } + /** + * Minimal implementation of Node.js util.inspect function. + * Converts a value to a string representation for debugging. + */ + function inspect(value) { + if (value === null) + return 'null'; + if (value === undefined) + return 'undefined'; + if (typeof value === 'string') + return `'${value}'`; + if (typeof value === 'number' || typeof value === 'boolean') + return String(value); + if (Array.isArray(value)) { + const items = value.map(item => inspect(item)).join(', '); + return `[ ${items} ]`; + } + if (typeof value === 'object') { + const entries = Object.entries(value) + .map(([key, val]) => `${key}: ${inspect(val)}`) + .join(', '); + return `{ ${entries} }`; + } + return String(value); + } + /** + * Minimal implementation of Node.js util.format function. + * Provides printf-style string formatting with basic placeholder support. + */ + function format(template, ...args) { + if (args.length === 0) + return template; + let result = template; + let argIndex = 0; + // Replace %s (string), %d (number), %j (JSON) placeholders + result = result.replace(/%[sdj%]/g, match => { + if (argIndex >= args.length) + return match; + const arg = args[argIndex++]; + switch (match) { + case '%s': + return String(arg); + case '%d': + return Number(arg).toString(); + case '%j': + try { + return JSON.stringify(arg); + } + catch { + return '[Circular]'; + } + case '%%': + return '%'; + default: + return match; + } + }); + // Append remaining arguments + while (argIndex < args.length) { + result += ' ' + String(args[argIndex++]); + } + return result; + } + + return util$4; +} + +var hasRequiredErrors$1; + +function requireErrors$1 () { + if (hasRequiredErrors$1) return errors$1; + hasRequiredErrors$1 = 1; + (function (exports) { + // Adapted from Node.js ../internal/errors.js, used for throwing similar errors to Node.js. + Object.defineProperty(exports, "__esModule", { value: true }); + exports.AssertionError = exports.RangeError = exports.TypeError = exports.Error = void 0; + exports.message = message; + exports.E = E; + const util_1 = requireUtil$4(); + const kCode = typeof Symbol === 'undefined' ? '_kCode' : Symbol('code'); + const messages = {}; + function makeNodeError(Base) { + return class NodeError extends Base { + constructor(key, ...args) { + super(message(key, args)); + this.code = key; + this[kCode] = key; + this.name = `${super.name} [${this[kCode]}]`; + } + }; + } + const g = typeof globalThis !== 'undefined' ? globalThis : commonjsGlobal; + class AssertionError extends g.Error { + constructor(options) { + if (typeof options !== 'object' || options === null) { + throw new exports.TypeError('ERR_INVALID_ARG_TYPE', 'options', 'object'); + } + if (options.message) { + super(options.message); + } + else { + super(`${(0, util_1.inspect)(options.actual).slice(0, 128)} ` + `${options.operator} ${(0, util_1.inspect)(options.expected).slice(0, 128)}`); + } + this.generatedMessage = !options.message; + this.name = 'AssertionError [ERR_ASSERTION]'; + this.code = 'ERR_ASSERTION'; + this.actual = options.actual; + this.expected = options.expected; + this.operator = options.operator; + exports.Error.captureStackTrace(this, options.stackStartFunction); + } + } + exports.AssertionError = AssertionError; + function message(key, args) { + if (typeof key !== 'string') + throw new exports.Error('Error message key must be a string'); + const msg = messages[key]; + if (!msg) + throw new exports.Error(`An invalid error message key was used: ${key}.`); + let fmt; + if (typeof msg === 'function') { + fmt = msg; + } + else { + fmt = util_1.format; + if (args === undefined || args.length === 0) + return msg; + args.unshift(msg); + } + return String(fmt.apply(null, args)); + } + // Utility function for registering the error codes. Only used here. Exported + // *only* to allow for testing. + function E(sym, val) { + messages[sym] = typeof val === 'function' ? val : String(val); + } + exports.Error = makeNodeError(g.Error); + exports.TypeError = makeNodeError(g.TypeError); + exports.RangeError = makeNodeError(g.RangeError); + E('ERR_DIR_CLOSED', 'Directory handle was closed'); + E('ERR_DIR_CONCURRENT_OPERATION', 'Cannot do synchronous work on directory handle with concurrent asynchronous operations'); + E('ERR_INVALID_FILE_URL_HOST', 'File URL host must be "localhost" or empty on %s'); + E('ERR_INVALID_FILE_URL_PATH', 'File URL path %s'); + E('ERR_INVALID_OPT_VALUE', (name, value) => { + return `The value "${String(value)}" is invalid for option "${name}"`; + }); + E('ERR_INVALID_OPT_VALUE_ENCODING', value => `The value "${String(value)}" is invalid for option "encoding"`); + E('ERR_INVALID_ARG_VALUE', 'Unable to open file as blob'); + + } (errors$1)); + return errors$1; +} + +var hasRequiredEncoding$1; + +function requireEncoding$1 () { + if (hasRequiredEncoding$1) return encoding$1; + hasRequiredEncoding$1 = 1; + (function (exports) { + Object.defineProperty(exports, "__esModule", { value: true }); + exports.ENCODING_UTF8 = void 0; + exports.assertEncoding = assertEncoding; + exports.strToEncoding = strToEncoding; + const buffer_1 = requireBuffer(); + const errors = requireErrors$1(); + exports.ENCODING_UTF8 = 'utf8'; + function assertEncoding(encoding) { + if (encoding && !buffer_1.Buffer.isEncoding(encoding)) + throw new errors.TypeError('ERR_INVALID_OPT_VALUE_ENCODING', encoding); + } + function strToEncoding(str, encoding) { + if (!encoding || encoding === exports.ENCODING_UTF8) + return str; // UTF-8 + if (encoding === 'buffer') + return new buffer_1.Buffer(str); // `buffer` encoding + return new buffer_1.Buffer(str).toString(encoding); // Custom encoding + } + + } (encoding$1)); + return encoding$1; +} + +var watchIgnore = {}; + +var lib$4 = {}; + +var hasRequiredLib$8; + +function requireLib$8 () { + if (hasRequiredLib$8) return lib$4; + hasRequiredLib$8 = 1; + (function (exports) { + Object.defineProperty(exports, "__esModule", { value: true }); + exports.toMatcher = exports.toRegex = void 0; + const escapeRe = (ch) => (/[.^$+{}()|\\]/.test(ch) ? `\\${ch}` : ch); + /** + * Parse an extended glob pattern like ?(a|b|c) + * Returns the regex string equivalent and the new index position + */ + const parseExtGlob = (pattern, startIdx, prefix, options) => { + let i = startIdx; // startIdx should be pointing at the character after '(' + const parts = []; + let cur = ''; + let depth = 1; // Track parenthesis depth for nested patterns + while (i < pattern.length && depth > 0) { + const ch = pattern[i]; + if (ch === '(') { + depth++; + cur += ch; + i++; + } + else if (ch === ')') { + depth--; + if (depth === 0) { + // Found the closing parenthesis + parts.push(cur); + i++; // consume ')' + break; + } + else { + cur += ch; + i++; + } + } + else if (ch === '|' && depth === 1) { + // Pipe separator at top level of this extglob + parts.push(cur); + cur = ''; + i++; + } + else { + cur += ch; + i++; + } + } + if (depth !== 0) + return; // Unclosed parenthesis + let alternatives = ''; + const length = parts.length; + for (let j = 0; j < length; j++) + alternatives += (alternatives ? '|' : '') + (0, exports.toRegex)(parts[j], options).source.replace(/^\^/, '').replace(/\$$/, ''); + switch (prefix) { + case '?': // zero or one + return [`(?:${alternatives})?`, i]; + case '*': // zero or more + return [`(?:${alternatives})*`, i]; + case '+': // one or more + return [`(?:${alternatives})+`, i]; + case '@': // exactly one + return [`(?:${alternatives})`, i]; + case '!': // none of (negative match) + // For negation, we need to match anything that doesn't match the pattern + // Use negative lookahead without consuming characters after + return [`(?!${alternatives})[^/]*`, i]; + } + return; + }; + /** + * Convert a glob pattern to a regular expression + * + * Supports: + * - `/` to separate path segments + * - `*` to match zero or more characters in a path segment + * - `?` to match one character in a path segment + * - `**` to match any number of path segments, including none + * - `{}` to group conditions (e.g. `{html,txt}`) + * - `[abc]`, `[a-z]`, `[!a-z]`, `[!abc]` character classes + * - Extended globbing (when `extglob: true` option is set): + * - `?(pattern-list)` zero or one occurrence + * - `*(pattern-list)` zero or more occurrences + * - `+(pattern-list)` one or more occurrences + * - `@(pattern-list)` exactly one of the patterns + * - `!(pattern-list)` anything except the patterns + */ + const toRegex = (pattern, options) => { + let regexStr = ''; + let i = 0; + // Helper to parse a brace group like {a,b,c}. No nesting support. + const parseBraceGroup = () => { + // Assume current char is '{' + i++; // skip '{' + const parts = []; + let cur = ''; + let closed = false; + while (i < pattern.length) { + const ch = pattern[i]; + if (ch === '}') { + parts.push(cur); + i++; // consume '}' + closed = true; + break; + } + if (ch === ',') { + parts.push(cur); + cur = ''; + i++; + continue; + } + cur += ch; + i++; + } + if (!closed) { + // treat as literal '{...' + return '\\{' + escapeRe(cur); + } + // Convert each part recursively to support globs inside braces + const alt = parts.map((p) => (0, exports.toRegex)(p, options).source.replace(/^\^/, '').replace(/\$$/, '')).join('|'); + return `(?:${alt})`; + }; + const extglob = !!options?.extglob; + while (i < pattern.length) { + const char = pattern[i]; + // Check for extended glob patterns when extglob is enabled + if (extglob && pattern[i + 1] === '(') { + if (char === '?' || char === '*' || char === '+' || char === '@' || char === '!') { + const result = parseExtGlob(pattern, i + 2, char, options); + if (result) { + regexStr += result[0]; + i = result[1]; + continue; + } + // If parse failed, fall through to normal handling + } + } + switch (char) { + case '*': { + // Check for double star ** + if (pattern[i + 1] === '*') { + // Collapse consecutive * beyond two (e.g., *** -> **) + let j = i + 2; + while (pattern[j] === '*') + j++; + // If followed by a slash, make it optional to allow zero segments + if (pattern[j] === '/') { + regexStr += '(?:.*/)?'; + i = j + 1; // consume **/ + } + else { + regexStr += '.*'; + i = j; // consume ** + } + } + else { + regexStr += '[^/]*'; + i++; + } + break; + } + case '?': + regexStr += '[^/]'; + i++; + break; + case '[': { + // Copy character class as-is with support for leading '!' + let cls = '['; + i++; + if (i < pattern.length && pattern[i] === '!') { + cls += '^'; + i++; + } + // if first after [ or [^ is ']' include it literally + if (i < pattern.length && pattern[i] === ']') { + cls += ']'; + i++; + } + while (i < pattern.length && pattern[i] !== ']') { + const ch = pattern[i]; + // Escape backslash inside class + cls += ch === '\\' ? '\\\\' : ch; + i++; + } + if (i < pattern.length && pattern[i] === ']') { + cls += ']'; + i++; + } + else { + // Unclosed class -> treat '[' literally + regexStr += '\\['; + continue; + } + regexStr += cls; + break; + } + case '{': { + regexStr += parseBraceGroup(); + break; + } + case '/': + regexStr += '/'; + i++; + break; + case '.': + case '^': + case '$': + case '+': + case '(': + case ')': + case '|': + case '\\': + regexStr += `\\${char}`; + i++; + break; + default: + regexStr += char; + i++; + break; + } + } + const flags = options?.nocase ? 'i' : ''; + return new RegExp('^' + regexStr + '$', flags); + }; + exports.toRegex = toRegex; + const isRegExp = /^\/(.{1,4096})\/([gimsuy]{0,6})$/; + const toMatcher = (pattern, options) => { + const regexes = []; + const patterns = Array.isArray(pattern) ? pattern : [pattern]; + for (const pat of patterns) { + if (typeof pat === 'string') { + const match = isRegExp.exec(pat); + if (match) { + const [, expr, flags] = match; + regexes.push(new RegExp(expr, flags)); + } + else { + regexes.push((0, exports.toRegex)(pat, options)); + } + } + else { + regexes.push(pat); + } + } + return regexes.length + ? new Function('p', 'return ' + regexes.map((r) => r + '.test(p)').join('||')) + : () => false; + }; + exports.toMatcher = toMatcher; + } (lib$4)); + return lib$4; +} + +var hasRequiredWatchIgnore; + +function requireWatchIgnore () { + if (hasRequiredWatchIgnore) return watchIgnore; + hasRequiredWatchIgnore = 1; + (function (exports) { + Object.defineProperty(exports, "__esModule", { value: true }); + exports.watchIgnoreToMatcher = exports.watchIgnorePatternToMatcher = void 0; + const glob_to_regex_js_1 = requireLib$8(); + /** Converts a single `watch()` `ignore` pattern into a filename predicate. */ + const watchIgnorePatternToMatcher = (pattern) => { + if (typeof pattern === 'function') + return pattern; + if (pattern instanceof RegExp) + return filename => pattern.test(filename); + if (typeof pattern === 'string') { + const regex = (0, glob_to_regex_js_1.toRegex)(pattern); + return filename => regex.test(filename); + } + throw new TypeError('The "options.ignore" property must be of type string, RegExp, function, or an array thereof. ' + + `Received ${typeof pattern}`); + }; + exports.watchIgnorePatternToMatcher = watchIgnorePatternToMatcher; + /** Converts the `watch()` `ignore` option (pattern or array of patterns) into a filename predicate. */ + const watchIgnoreToMatcher = (ignore) => { + if (Array.isArray(ignore)) { + const matchers = ignore.map(exports.watchIgnorePatternToMatcher); + return filename => matchers.some(matcher => matcher(filename)); + } + return (0, exports.watchIgnorePatternToMatcher)(ignore); + }; + exports.watchIgnoreToMatcher = watchIgnoreToMatcher; + + } (watchIgnore)); + return watchIgnore; +} + +var hasRequiredLib$7; + +function requireLib$7 () { + if (hasRequiredLib$7) return lib$5; + hasRequiredLib$7 = 1; + (function (exports) { + Object.defineProperty(exports, "__esModule", { value: true }); + const tslib_1 = require$$0$2; + tslib_1.__exportStar(requireTypes(), exports); + tslib_1.__exportStar(requireConstants$2(), exports); + tslib_1.__exportStar(requireAMODE(), exports); + tslib_1.__exportStar(requireFLAG(), exports); + tslib_1.__exportStar(requirePath(), exports); + tslib_1.__exportStar(requireEncoding$1(), exports); + tslib_1.__exportStar(requireWatchIgnore(), exports); + + } (lib$5)); + return lib$5; +} + +var hasRequiredNode; + +function requireNode () { + if (hasRequiredNode) return Node; + hasRequiredNode = 1; + Object.defineProperty(Node, "__esModule", { value: true }); + Node.Node = void 0; + const fanout_1 = requireFanout(); + const process_1 = requireProcess(); + const buffer_1 = requireBuffer(); + const fs_node_utils_1 = requireLib$7(); + const { S_IFMT, S_IFDIR, S_IFREG, S_IFLNK, S_IFCHR } = fs_node_utils_1.constants; + const getuid = () => process_1.default.getuid?.() ?? 0; + const getgid = () => process_1.default.getgid?.() ?? 0; + const EMPTY_BUFFER = (0, buffer_1.bufferAllocUnsafe)(0); + /** + * Node in a file system (like i-node, v-node). + */ + let Node$1 = class Node { + constructor(ino, mode = 0o666, uid = getuid(), gid = getgid()) { + /** + * @deprecated Subscribe to the volume-level `Superblock.changes` bus or use + * `CoreWatcher` instead. + */ + this.changes = new fanout_1.FanOut(); + // User ID and group ID. + this._uid = getuid(); + this._gid = getgid(); + this._atime = new Date(); + this._mtime = new Date(); + this._ctime = new Date(); + this.buf = EMPTY_BUFFER; + /** Total allocated memory capacity for this node. */ + this.capacity = 0; + /** Actually used bytes to store content. */ + this.size = 0; + this.rdev = 0; + // Number of hard links pointing at this Node. + this._nlink = 1; + this.mode = mode; + this.ino = ino; + this._uid = uid; + this._gid = gid; + } + set ctime(ctime) { + this._ctime = ctime; + } + get ctime() { + return this._ctime; + } + set uid(uid) { + this._uid = uid; + this.ctime = new Date(); + } + get uid() { + return this._uid; + } + set gid(gid) { + this._gid = gid; + this.ctime = new Date(); + } + get gid() { + return this._gid; + } + set atime(atime) { + this._atime = atime; + } + get atime() { + return this._atime; + } + set mtime(mtime) { + this._mtime = mtime; + this.ctime = new Date(); + } + get mtime() { + return this._mtime; + } + get perm() { + return this.mode & ~S_IFMT; + } + set perm(perm) { + this.mode = (this.mode & S_IFMT) | (perm & ~S_IFMT); + this.ctime = new Date(); + } + set nlink(nlink) { + this._nlink = nlink; + this.ctime = new Date(); + } + get nlink() { + return this._nlink; + } + getString(encoding = 'utf8') { + this.atime = new Date(); + return this.getBuffer().toString(encoding); + } + setString(str) { + this._setBuf((0, buffer_1.bufferFrom)(str, 'utf8')); + } + getBuffer() { + this.atime = new Date(); + if (!this.buf) + this.buf = (0, buffer_1.bufferAllocUnsafe)(0); + return (0, buffer_1.bufferFrom)(this.buf.subarray(0, this.size)); // Return a copy of used portion. + } + setBuffer(buf) { + const copy = (0, buffer_1.bufferFrom)(buf); // Creates a copy of data. + this._setBuf(copy); + } + _setBuf(buf) { + const size = buf.length; + this.buf = buf; + this.capacity = size; + this.size = size; + this.touch(); + } + getSize() { + return this.size; + } + setModeProperty(property) { + this.mode = property; + } + isFile() { + return (this.mode & S_IFMT) === S_IFREG; + } + isDirectory() { + return (this.mode & S_IFMT) === S_IFDIR; + } + isSymlink() { + // return !!this.symlink; + return (this.mode & S_IFMT) === S_IFLNK; + } + isCharacterDevice() { + return (this.mode & S_IFMT) === S_IFCHR; + } + makeSymlink(symlink) { + this.mode = S_IFLNK | 0o666; + this.symlink = symlink; + } + write(buf, off = 0, len = buf.length, pos = 0) { + const bufLength = buf.length; + if (off + len > bufLength) + len = bufLength - off; + if (len <= 0) + return 0; + const requiredSize = pos + len; + if (requiredSize > this.capacity) { + let newCapacity = Math.max(this.capacity * 2, 64); + while (newCapacity < requiredSize) + newCapacity *= 2; + const newBuf = (0, buffer_1.bufferAllocUnsafe)(newCapacity); + if (this.size > 0) + this.buf.copy(newBuf, 0, 0, this.size); + this.buf = newBuf; + this.capacity = newCapacity; + } + if (pos > this.size) + this.buf.fill(0, this.size, pos); + buf.copy(this.buf, pos, off, off + len); + if (requiredSize > this.size) + this.size = requiredSize; + this.touch(); + return len; + } + /** + * Read data from the file. + * + * @param buf Buffer to read data into. + * @param off Offset int the `buf` where to start writing data. + * @param len How many bytes to read. Equals to `buf.byteLength` by default. + * @param pos Position offset in file where to start reading. Defaults to `0`. + * @returns Returns the number of bytes read. + */ + read(buf, off = 0, len = buf.byteLength, pos = 0) { + this.atime = new Date(); + if (pos >= this.size) + return 0; + let actualLen = len; + if (actualLen > buf.byteLength) + actualLen = buf.byteLength; + if (actualLen + pos > this.size) + actualLen = this.size - pos; + if (actualLen <= 0) + return 0; + const buf2 = buf instanceof buffer_1.Buffer ? buf : buffer_1.Buffer.from(buf.buffer, buf.byteOffset, buf.byteLength); + this.buf.copy(buf2, off, pos, pos + actualLen); + return actualLen; + } + truncate(len = 0) { + // A negative length is clamped to zero, matching Node.js `fs.truncate`, + // which truncates to an empty file rather than producing a negative size. + // Without this, `this.size` becomes negative and `getBuffer()`'s + // `subarray(0, this.size)` reads past the used region, exposing + // uninitialized heap memory from the unsafe-allocated backing buffer. + if (len <= 0) { + this.buf = EMPTY_BUFFER; + this.capacity = 0; + this.size = 0; + this.touch(); + return; + } + if (len <= this.size) + this.size = len; + else { + if (len > this.capacity) { + let newCapacity = Math.max(this.capacity * 2, 64); + while (newCapacity < len) + newCapacity *= 2; + const buf = (0, buffer_1.bufferAllocUnsafe)(newCapacity); + if (this.size > 0) + this.buf.copy(buf, 0, 0, this.size); + buf.fill(0, this.size, len); + this.buf = buf; + this.capacity = newCapacity; + } + else + this.buf.fill(0, this.size, len); + this.size = len; + } + this.touch(); + } + chmod(perm) { + this.mode = (this.mode & S_IFMT) | (perm & ~S_IFMT); + this.touch(); + } + chown(uid, gid) { + this.uid = uid; + this.gid = gid; + this.touch(); + } + touch() { + this.mtime = new Date(); + this.changes.emit(['modify']); + } + canRead(uid = getuid(), gid = getgid()) { + if (this.perm & 4 /* S.IROTH */) { + return true; + } + if (gid === this.gid) { + if (this.perm & 32 /* S.IRGRP */) { + return true; + } + } + if (uid === this.uid) { + if (this.perm & 256 /* S.IRUSR */) { + return true; + } + } + return false; + } + canWrite(uid = getuid(), gid = getgid()) { + if (this.perm & 2 /* S.IWOTH */) { + return true; + } + if (gid === this.gid) { + if (this.perm & 16 /* S.IWGRP */) { + return true; + } + } + if (uid === this.uid) { + if (this.perm & 128 /* S.IWUSR */) { + return true; + } + } + return false; + } + canExecute(uid = getuid(), gid = getgid()) { + if (this.perm & 1 /* S.IXOTH */) { + return true; + } + if (gid === this.gid) { + if (this.perm & 8 /* S.IXGRP */) { + return true; + } + } + if (uid === this.uid) { + if (this.perm & 64 /* S.IXUSR */) { + return true; + } + } + return false; + } + del() { + this.changes.emit(['delete']); + } + toJSON() { + return { + ino: this.ino, + uid: this.uid, + gid: this.gid, + atime: this.atime.getTime(), + mtime: this.mtime.getTime(), + ctime: this.ctime.getTime(), + perm: this.perm, + mode: this.mode, + nlink: this.nlink, + symlink: this.symlink, + data: this.getString(), + }; + } + }; + Node.Node = Node$1; + + return Node; +} + +var Link = {}; + +var hasRequiredLink; + +function requireLink () { + if (hasRequiredLink) return Link; + hasRequiredLink = 1; + Object.defineProperty(Link, "__esModule", { value: true }); + Link.Link = void 0; + const fs_node_utils_1 = requireLib$7(); + const fanout_1 = requireFanout(); + const { S_IFREG } = fs_node_utils_1.constants; + /** + * Represents a hard link that points to an i-node `node`. + */ + let Link$1 = class Link { + get steps() { + return this._steps; + } + // Recursively sync children steps, e.g. in case of dir rename + set steps(val) { + this._steps = val; + for (const [child, link] of this.children.entries()) { + if (child === '.' || child === '..') { + continue; + } + link?.syncSteps(); + } + } + constructor(vol, parent, name) { + /** + * @deprecated Subscribe to the volume-level `Superblock.changes` bus or use + * `CoreWatcher` instead. + */ + this.changes = new fanout_1.FanOut(); + this.children = new Map(); + // Path to this node as Array: ['usr', 'bin', 'node']. + this._steps = []; + // "i-node" number of the node. + this.ino = 0; + // Number of children. + this.length = 0; + this.vol = vol; + this.parent = parent; + this.name = name; + this.syncSteps(); + } + setNode(node) { + this.node = node; + this.ino = node.ino; + } + getNode() { + return this.node; + } + createChild(name, node = this.vol.createNode(S_IFREG | 0o666)) { + const link = new Link(this.vol, this, name); + link.setNode(node); + if (node.isDirectory()) { + link.children.set('.', link); + link.getNode().nlink++; + } + this.setChild(name, link); + return link; + } + setChild(name, link = new Link(this.vol, this, name)) { + this.children.set(name, link); + link.parent = this; + this.length++; + const node = link.getNode(); + if (node.isDirectory()) { + link.children.set('..', this); + this.getNode().nlink++; + } + this.getNode().mtime = new Date(); + this.changes.emit(['child:add', link, this]); + return link; + } + deleteChild(link) { + const node = link.getNode(); + if (node.isDirectory()) { + link.children.delete('..'); + this.getNode().nlink--; + } + this.children.delete(link.getName()); + this.length--; + this.getNode().mtime = new Date(); + this.changes.emit(['child:del', link, this]); + } + getChild(name) { + this.getNode().atime = new Date(); + return this.children.get(name); + } + getPath() { + return this.steps.join("/" /* PATH.SEP */); + } + getParentPath() { + const parent = this.steps.slice(0, -1).join("/" /* PATH.SEP */); + return parent ? parent : "/" /* PATH.SEP */; + } + getName() { + return this.steps[this.steps.length - 1]; + } + toJSON() { + return { + steps: this.steps, + ino: this.ino, + children: Array.from(this.children.keys()), + }; + } + syncSteps() { + this.steps = this.parent ? this.parent.steps.concat([this.name]) : [this.name]; + } + }; + Link.Link = Link$1; + + return Link; +} + +var File = {}; + +var hasRequiredFile; + +function requireFile () { + if (hasRequiredFile) return File; + hasRequiredFile = 1; + Object.defineProperty(File, "__esModule", { value: true }); + File.File = void 0; + const fs_node_utils_1 = requireLib$7(); + const { O_APPEND } = fs_node_utils_1.constants; + /** + * Represents an open file (file descriptor) that points to a `Link` (Hard-link) and a `Node`. + * + * @todo Rename to `OpenFile`. + */ + let File$1 = class File { + /** + * Open a Link-Node pair. `node` is provided separately as that might be a different node + * rather the one `link` points to, because it might be a symlink. + * @param link + * @param node + * @param flags + * @param fd + */ + constructor(link, node, flags, fd) { + this.link = link; + this.node = node; + this.flags = flags; + this.fd = fd; + this.position = 0; + if (this.flags & O_APPEND) + this.position = this.getSize(); + } + getString(encoding = 'utf8') { + return this.node.getString(); + } + setString(str) { + this.node.setString(str); + } + getBuffer() { + return this.node.getBuffer(); + } + setBuffer(buf) { + this.node.setBuffer(buf); + } + getSize() { + return this.node.getSize(); + } + truncate(len) { + this.node.truncate(len); + } + seekTo(position) { + this.position = position; + } + write(buf, offset = 0, length = buf.length, position) { + if (typeof position !== 'number') + position = this.position; + const bytes = this.node.write(buf, offset, length, position); + this.position = position + bytes; + return bytes; + } + read(buf, offset = 0, length = buf.byteLength, position) { + if (typeof position !== 'number') + position = this.position; + const bytes = this.node.read(buf, offset, length, position); + this.position = position + bytes; + return bytes; + } + chmod(perm) { + this.node.chmod(perm); + } + chown(uid, gid) { + this.node.chown(uid, gid); + } + }; + File.File = File$1; + + return File; +} + +var Superblock = {}; + +var util$3 = {}; + +var encoding = {}; + +var hasRequiredEncoding; + +function requireEncoding () { + if (hasRequiredEncoding) return encoding; + hasRequiredEncoding = 1; + (function (exports) { + Object.defineProperty(exports, "__esModule", { value: true }); + exports.ENCODING_UTF8 = void 0; + exports.assertEncoding = assertEncoding; + exports.strToEncoding = strToEncoding; + const buffer_1 = requireBuffer(); + const errors = requireErrors$1(); + exports.ENCODING_UTF8 = 'utf8'; + function assertEncoding(encoding) { + if (encoding && !buffer_1.Buffer.isEncoding(encoding)) + throw new errors.TypeError('ERR_INVALID_OPT_VALUE_ENCODING', encoding); + } + function strToEncoding(str, encoding) { + if (!encoding || encoding === exports.ENCODING_UTF8) + return str; // UTF-8 + if (encoding === 'buffer') + return new buffer_1.Buffer(str); // `buffer` encoding + return new buffer_1.Buffer(str).toString(encoding); // Custom encoding + } + + } (encoding)); + return encoding; +} + +var url = {}; + +var punycode$1 = {exports: {}}; + +/*! https://mths.be/punycode v1.4.1 by @mathias */ +var punycode = punycode$1.exports; + +var hasRequiredPunycode; + +function requirePunycode () { + if (hasRequiredPunycode) return punycode$1.exports; + hasRequiredPunycode = 1; + (function (module, exports) { +(function(root) { + + /** Detect free variables */ + var freeExports = exports && + !exports.nodeType && exports; + var freeModule = module && + !module.nodeType && module; + var freeGlobal = typeof commonjsGlobal == 'object' && commonjsGlobal; + if ( + freeGlobal.undefined === freeGlobal || + freeGlobal.window === freeGlobal || + freeGlobal.self === freeGlobal + ) { + root = freeGlobal; + } + + /** + * The `punycode` object. + * @name punycode + * @type Object + */ + var punycode, + + /** Highest positive signed 32-bit float value */ + maxInt = 2147483647, // aka. 0x7FFFFFFF or 2^31-1 + + /** Bootstring parameters */ + base = 36, + tMin = 1, + tMax = 26, + skew = 38, + damp = 700, + initialBias = 72, + initialN = 128, // 0x80 + delimiter = '-', // '\x2D' + + /** Regular expressions */ + regexPunycode = /^xn--/, + regexNonASCII = /[^\x20-\x7E]/, // unprintable ASCII chars + non-ASCII chars + regexSeparators = /[\x2E\u3002\uFF0E\uFF61]/g, // RFC 3490 separators + + /** Error messages */ + errors = { + 'overflow': 'Overflow: input needs wider integers to process', + 'not-basic': 'Illegal input >= 0x80 (not a basic code point)', + 'invalid-input': 'Invalid input' + }, + + /** Convenience shortcuts */ + baseMinusTMin = base - tMin, + floor = Math.floor, + stringFromCharCode = String.fromCharCode, + + /** Temporary variable */ + key; + + /*--------------------------------------------------------------------------*/ + + /** + * A generic error utility function. + * @private + * @param {String} type The error type. + * @returns {Error} Throws a `RangeError` with the applicable error message. + */ + function error(type) { + throw new RangeError(errors[type]); + } + + /** + * A generic `Array#map` utility function. + * @private + * @param {Array} array The array to iterate over. + * @param {Function} callback The function that gets called for every array + * item. + * @returns {Array} A new array of values returned by the callback function. + */ + function map(array, fn) { + var length = array.length; + var result = []; + while (length--) { + result[length] = fn(array[length]); + } + return result; + } + + /** + * A simple `Array#map`-like wrapper to work with domain name strings or email + * addresses. + * @private + * @param {String} domain The domain name or email address. + * @param {Function} callback The function that gets called for every + * character. + * @returns {Array} A new string of characters returned by the callback + * function. + */ + function mapDomain(string, fn) { + var parts = string.split('@'); + var result = ''; + if (parts.length > 1) { + // In email addresses, only the domain name should be punycoded. Leave + // the local part (i.e. everything up to `@`) intact. + result = parts[0] + '@'; + string = parts[1]; + } + // Avoid `split(regex)` for IE8 compatibility. See #17. + string = string.replace(regexSeparators, '\x2E'); + var labels = string.split('.'); + var encoded = map(labels, fn).join('.'); + return result + encoded; + } + + /** + * Creates an array containing the numeric code points of each Unicode + * character in the string. While JavaScript uses UCS-2 internally, + * this function will convert a pair of surrogate halves (each of which + * UCS-2 exposes as separate characters) into a single code point, + * matching UTF-16. + * @see `punycode.ucs2.encode` + * @see + * @memberOf punycode.ucs2 + * @name decode + * @param {String} string The Unicode input string (UCS-2). + * @returns {Array} The new array of code points. + */ + function ucs2decode(string) { + var output = [], + counter = 0, + length = string.length, + value, + extra; + while (counter < length) { + value = string.charCodeAt(counter++); + if (value >= 0xD800 && value <= 0xDBFF && counter < length) { + // high surrogate, and there is a next character + extra = string.charCodeAt(counter++); + if ((extra & 0xFC00) == 0xDC00) { // low surrogate + output.push(((value & 0x3FF) << 10) + (extra & 0x3FF) + 0x10000); + } else { + // unmatched surrogate; only append this code unit, in case the next + // code unit is the high surrogate of a surrogate pair + output.push(value); + counter--; + } + } else { + output.push(value); + } + } + return output; + } + + /** + * Creates a string based on an array of numeric code points. + * @see `punycode.ucs2.decode` + * @memberOf punycode.ucs2 + * @name encode + * @param {Array} codePoints The array of numeric code points. + * @returns {String} The new Unicode string (UCS-2). + */ + function ucs2encode(array) { + return map(array, function(value) { + var output = ''; + if (value > 0xFFFF) { + value -= 0x10000; + output += stringFromCharCode(value >>> 10 & 0x3FF | 0xD800); + value = 0xDC00 | value & 0x3FF; + } + output += stringFromCharCode(value); + return output; + }).join(''); + } + + /** + * Converts a basic code point into a digit/integer. + * @see `digitToBasic()` + * @private + * @param {Number} codePoint The basic numeric code point value. + * @returns {Number} The numeric value of a basic code point (for use in + * representing integers) in the range `0` to `base - 1`, or `base` if + * the code point does not represent a value. + */ + function basicToDigit(codePoint) { + if (codePoint - 48 < 10) { + return codePoint - 22; + } + if (codePoint - 65 < 26) { + return codePoint - 65; + } + if (codePoint - 97 < 26) { + return codePoint - 97; + } + return base; + } + + /** + * Converts a digit/integer into a basic code point. + * @see `basicToDigit()` + * @private + * @param {Number} digit The numeric value of a basic code point. + * @returns {Number} The basic code point whose value (when used for + * representing integers) is `digit`, which needs to be in the range + * `0` to `base - 1`. If `flag` is non-zero, the uppercase form is + * used; else, the lowercase form is used. The behavior is undefined + * if `flag` is non-zero and `digit` has no uppercase form. + */ + function digitToBasic(digit, flag) { + // 0..25 map to ASCII a..z or A..Z + // 26..35 map to ASCII 0..9 + return digit + 22 + 75 * (digit < 26) - ((flag != 0) << 5); + } + + /** + * Bias adaptation function as per section 3.4 of RFC 3492. + * https://tools.ietf.org/html/rfc3492#section-3.4 + * @private + */ + function adapt(delta, numPoints, firstTime) { + var k = 0; + delta = firstTime ? floor(delta / damp) : delta >> 1; + delta += floor(delta / numPoints); + for (/* no initialization */; delta > baseMinusTMin * tMax >> 1; k += base) { + delta = floor(delta / baseMinusTMin); + } + return floor(k + (baseMinusTMin + 1) * delta / (delta + skew)); + } + + /** + * Converts a Punycode string of ASCII-only symbols to a string of Unicode + * symbols. + * @memberOf punycode + * @param {String} input The Punycode string of ASCII-only symbols. + * @returns {String} The resulting string of Unicode symbols. + */ + function decode(input) { + // Don't use UCS-2 + var output = [], + inputLength = input.length, + out, + i = 0, + n = initialN, + bias = initialBias, + basic, + j, + index, + oldi, + w, + k, + digit, + t, + /** Cached calculation results */ + baseMinusT; + + // Handle the basic code points: let `basic` be the number of input code + // points before the last delimiter, or `0` if there is none, then copy + // the first basic code points to the output. + + basic = input.lastIndexOf(delimiter); + if (basic < 0) { + basic = 0; + } + + for (j = 0; j < basic; ++j) { + // if it's not a basic code point + if (input.charCodeAt(j) >= 0x80) { + error('not-basic'); + } + output.push(input.charCodeAt(j)); + } + + // Main decoding loop: start just after the last delimiter if any basic code + // points were copied; start at the beginning otherwise. + + for (index = basic > 0 ? basic + 1 : 0; index < inputLength; /* no final expression */) { + + // `index` is the index of the next character to be consumed. + // Decode a generalized variable-length integer into `delta`, + // which gets added to `i`. The overflow checking is easier + // if we increase `i` as we go, then subtract off its starting + // value at the end to obtain `delta`. + for (oldi = i, w = 1, k = base; /* no condition */; k += base) { + + if (index >= inputLength) { + error('invalid-input'); + } + + digit = basicToDigit(input.charCodeAt(index++)); + + if (digit >= base || digit > floor((maxInt - i) / w)) { + error('overflow'); + } + + i += digit * w; + t = k <= bias ? tMin : (k >= bias + tMax ? tMax : k - bias); + + if (digit < t) { + break; + } + + baseMinusT = base - t; + if (w > floor(maxInt / baseMinusT)) { + error('overflow'); + } + + w *= baseMinusT; + + } + + out = output.length + 1; + bias = adapt(i - oldi, out, oldi == 0); + + // `i` was supposed to wrap around from `out` to `0`, + // incrementing `n` each time, so we'll fix that now: + if (floor(i / out) > maxInt - n) { + error('overflow'); + } + + n += floor(i / out); + i %= out; + + // Insert `n` at position `i` of the output + output.splice(i++, 0, n); + + } + + return ucs2encode(output); + } + + /** + * Converts a string of Unicode symbols (e.g. a domain name label) to a + * Punycode string of ASCII-only symbols. + * @memberOf punycode + * @param {String} input The string of Unicode symbols. + * @returns {String} The resulting Punycode string of ASCII-only symbols. + */ + function encode(input) { + var n, + delta, + handledCPCount, + basicLength, + bias, + j, + m, + q, + k, + t, + currentValue, + output = [], + /** `inputLength` will hold the number of code points in `input`. */ + inputLength, + /** Cached calculation results */ + handledCPCountPlusOne, + baseMinusT, + qMinusT; + + // Convert the input in UCS-2 to Unicode + input = ucs2decode(input); + + // Cache the length + inputLength = input.length; + + // Initialize the state + n = initialN; + delta = 0; + bias = initialBias; + + // Handle the basic code points + for (j = 0; j < inputLength; ++j) { + currentValue = input[j]; + if (currentValue < 0x80) { + output.push(stringFromCharCode(currentValue)); + } + } + + handledCPCount = basicLength = output.length; + + // `handledCPCount` is the number of code points that have been handled; + // `basicLength` is the number of basic code points. + + // Finish the basic string - if it is not empty - with a delimiter + if (basicLength) { + output.push(delimiter); + } + + // Main encoding loop: + while (handledCPCount < inputLength) { + + // All non-basic code points < n have been handled already. Find the next + // larger one: + for (m = maxInt, j = 0; j < inputLength; ++j) { + currentValue = input[j]; + if (currentValue >= n && currentValue < m) { + m = currentValue; + } + } + + // Increase `delta` enough to advance the decoder's state to , + // but guard against overflow + handledCPCountPlusOne = handledCPCount + 1; + if (m - n > floor((maxInt - delta) / handledCPCountPlusOne)) { + error('overflow'); + } + + delta += (m - n) * handledCPCountPlusOne; + n = m; + + for (j = 0; j < inputLength; ++j) { + currentValue = input[j]; + + if (currentValue < n && ++delta > maxInt) { + error('overflow'); + } + + if (currentValue == n) { + // Represent delta as a generalized variable-length integer + for (q = delta, k = base; /* no condition */; k += base) { + t = k <= bias ? tMin : (k >= bias + tMax ? tMax : k - bias); + if (q < t) { + break; + } + qMinusT = q - t; + baseMinusT = base - t; + output.push( + stringFromCharCode(digitToBasic(t + qMinusT % baseMinusT, 0)) + ); + q = floor(qMinusT / baseMinusT); + } + + output.push(stringFromCharCode(digitToBasic(q, 0))); + bias = adapt(delta, handledCPCountPlusOne, handledCPCount == basicLength); + delta = 0; + ++handledCPCount; + } + } + + ++delta; + ++n; + + } + return output.join(''); + } + + /** + * Converts a Punycode string representing a domain name or an email address + * to Unicode. Only the Punycoded parts of the input will be converted, i.e. + * it doesn't matter if you call it on a string that has already been + * converted to Unicode. + * @memberOf punycode + * @param {String} input The Punycoded domain name or email address to + * convert to Unicode. + * @returns {String} The Unicode representation of the given Punycode + * string. + */ + function toUnicode(input) { + return mapDomain(input, function(string) { + return regexPunycode.test(string) + ? decode(string.slice(4).toLowerCase()) + : string; + }); + } + + /** + * Converts a Unicode string representing a domain name or an email address to + * Punycode. Only the non-ASCII parts of the domain name will be converted, + * i.e. it doesn't matter if you call it with a domain that's already in + * ASCII. + * @memberOf punycode + * @param {String} input The domain name or email address to convert, as a + * Unicode string. + * @returns {String} The Punycode representation of the given domain name or + * email address. + */ + function toASCII(input) { + return mapDomain(input, function(string) { + return regexNonASCII.test(string) + ? 'xn--' + encode(string) + : string; + }); + } + + /*--------------------------------------------------------------------------*/ + + /** Define the public API */ + punycode = { + /** + * A string representing the current Punycode.js version number. + * @memberOf punycode + * @type String + */ + 'version': '1.4.1', + /** + * An object of methods to convert from JavaScript's internal character + * representation (UCS-2) to Unicode code points, and back. + * @see + * @memberOf punycode + * @type Object + */ + 'ucs2': { + 'decode': ucs2decode, + 'encode': ucs2encode + }, + 'decode': decode, + 'encode': encode, + 'toASCII': toASCII, + 'toUnicode': toUnicode + }; + + /** Expose `punycode` */ + // Some AMD build optimizers, like r.js, check for specific condition patterns + // like the following: + if (freeExports && freeModule) { + if (module.exports == freeExports) { + // in Node.js, io.js, or RingoJS v0.8.0+ + freeModule.exports = punycode; + } else { + // in Narwhal or RingoJS v0.7.0- + for (key in punycode) { + punycode.hasOwnProperty(key) && (freeExports[key] = punycode[key]); + } + } + } else { + // in Rhino or a web browser + root.punycode = punycode; + } + + }(punycode)); + } (punycode$1, punycode$1.exports)); + return punycode$1.exports; +} + +var type; +var hasRequiredType; + +function requireType () { + if (hasRequiredType) return type; + hasRequiredType = 1; + + /** @type {import('./type')} */ + type = TypeError; + return type; +} + +var _nodeResolve_empty = {}; + +var _nodeResolve_empty$1 = /*#__PURE__*/Object.freeze({ + __proto__: null, + default: _nodeResolve_empty +}); + +var require$$0 = /*@__PURE__*/getAugmentedNamespace(_nodeResolve_empty$1); + +var objectInspect; +var hasRequiredObjectInspect; + +function requireObjectInspect () { + if (hasRequiredObjectInspect) return objectInspect; + hasRequiredObjectInspect = 1; + var hasMap = typeof Map === 'function' && Map.prototype; + var mapSizeDescriptor = Object.getOwnPropertyDescriptor && hasMap ? Object.getOwnPropertyDescriptor(Map.prototype, 'size') : null; + var mapSize = hasMap && mapSizeDescriptor && typeof mapSizeDescriptor.get === 'function' ? mapSizeDescriptor.get : null; + var mapForEach = hasMap && Map.prototype.forEach; + var hasSet = typeof Set === 'function' && Set.prototype; + var setSizeDescriptor = Object.getOwnPropertyDescriptor && hasSet ? Object.getOwnPropertyDescriptor(Set.prototype, 'size') : null; + var setSize = hasSet && setSizeDescriptor && typeof setSizeDescriptor.get === 'function' ? setSizeDescriptor.get : null; + var setForEach = hasSet && Set.prototype.forEach; + var hasWeakMap = typeof WeakMap === 'function' && WeakMap.prototype; + var weakMapHas = hasWeakMap ? WeakMap.prototype.has : null; + var hasWeakSet = typeof WeakSet === 'function' && WeakSet.prototype; + var weakSetHas = hasWeakSet ? WeakSet.prototype.has : null; + var hasWeakRef = typeof WeakRef === 'function' && WeakRef.prototype; + var weakRefDeref = hasWeakRef ? WeakRef.prototype.deref : null; + var booleanValueOf = Boolean.prototype.valueOf; + var objectToString = Object.prototype.toString; + var functionToString = Function.prototype.toString; + var $match = String.prototype.match; + var $slice = String.prototype.slice; + var $replace = String.prototype.replace; + var $toUpperCase = String.prototype.toUpperCase; + var $toLowerCase = String.prototype.toLowerCase; + var $test = RegExp.prototype.test; + var $concat = Array.prototype.concat; + var $join = Array.prototype.join; + var $arrSlice = Array.prototype.slice; + var $floor = Math.floor; + var bigIntValueOf = typeof BigInt === 'function' ? BigInt.prototype.valueOf : null; + var gOPS = Object.getOwnPropertySymbols; + var symToString = typeof Symbol === 'function' && typeof Symbol.iterator === 'symbol' ? Symbol.prototype.toString : null; + var hasShammedSymbols = typeof Symbol === 'function' && typeof Symbol.iterator === 'object'; + // ie, `has-tostringtag/shams + var toStringTag = typeof Symbol === 'function' && Symbol.toStringTag && (typeof Symbol.toStringTag === hasShammedSymbols ? 'object' : 'symbol') + ? Symbol.toStringTag + : null; + var isEnumerable = Object.prototype.propertyIsEnumerable; + + var gPO = (typeof Reflect === 'function' ? Reflect.getPrototypeOf : Object.getPrototypeOf) || ( + [].__proto__ === Array.prototype // eslint-disable-line no-proto + ? function (O) { + return O.__proto__; // eslint-disable-line no-proto + } + : null + ); + + function addNumericSeparator(num, str) { + if ( + num === Infinity + || num === -Infinity + || num !== num + || (num && num > -1e3 && num < 1000) + || $test.call(/e/, str) + ) { + return str; + } + var sepRegex = /[0-9](?=(?:[0-9]{3})+(?![0-9]))/g; + if (typeof num === 'number') { + var int = num < 0 ? -$floor(-num) : $floor(num); // trunc(num) + if (int !== num) { + var intStr = String(int); + var dec = $slice.call(str, intStr.length + 1); + return $replace.call(intStr, sepRegex, '$&_') + '.' + $replace.call($replace.call(dec, /([0-9]{3})/g, '$&_'), /_$/, ''); + } + } + return $replace.call(str, sepRegex, '$&_'); + } + + var utilInspect = require$$0; + var inspectCustom = utilInspect.custom; + var inspectSymbol = isSymbol(inspectCustom) ? inspectCustom : null; + + var quotes = { + __proto__: null, + 'double': '"', + single: "'" + }; + var quoteREs = { + __proto__: null, + 'double': /(["\\])/g, + single: /(['\\])/g + }; + + objectInspect = function inspect_(obj, options, depth, seen) { + var opts = options || {}; + + if (has(opts, 'quoteStyle') && !has(quotes, opts.quoteStyle)) { + throw new TypeError('option "quoteStyle" must be "single" or "double"'); + } + if ( + has(opts, 'maxStringLength') && (typeof opts.maxStringLength === 'number' + ? opts.maxStringLength < 0 && opts.maxStringLength !== Infinity + : opts.maxStringLength !== null + ) + ) { + throw new TypeError('option "maxStringLength", if provided, must be a positive integer, Infinity, or `null`'); + } + var customInspect = has(opts, 'customInspect') ? opts.customInspect : true; + if (typeof customInspect !== 'boolean' && customInspect !== 'symbol') { + throw new TypeError('option "customInspect", if provided, must be `true`, `false`, or `\'symbol\'`'); + } + + if ( + has(opts, 'indent') + && opts.indent !== null + && opts.indent !== '\t' + && !(parseInt(opts.indent, 10) === opts.indent && opts.indent > 0) + ) { + throw new TypeError('option "indent" must be "\\t", an integer > 0, or `null`'); + } + if (has(opts, 'numericSeparator') && typeof opts.numericSeparator !== 'boolean') { + throw new TypeError('option "numericSeparator", if provided, must be `true` or `false`'); + } + var numericSeparator = opts.numericSeparator; + + if (typeof obj === 'undefined') { + return 'undefined'; + } + if (obj === null) { + return 'null'; + } + if (typeof obj === 'boolean') { + return obj ? 'true' : 'false'; + } + + if (typeof obj === 'string') { + return inspectString(obj, opts); + } + if (typeof obj === 'number') { + if (obj === 0) { + return Infinity / obj > 0 ? '0' : '-0'; + } + var str = String(obj); + return numericSeparator ? addNumericSeparator(obj, str) : str; + } + if (typeof obj === 'bigint') { + var bigIntStr = String(obj) + 'n'; + return numericSeparator ? addNumericSeparator(obj, bigIntStr) : bigIntStr; + } + + var maxDepth = typeof opts.depth === 'undefined' ? 5 : opts.depth; + if (typeof depth === 'undefined') { depth = 0; } + if (depth >= maxDepth && maxDepth > 0 && typeof obj === 'object') { + return isArray(obj) ? '[Array]' : '[Object]'; + } + + var indent = getIndent(opts, depth); + + if (typeof seen === 'undefined') { + seen = []; + } else if (indexOf(seen, obj) >= 0) { + return '[Circular]'; + } + + function inspect(value, from, noIndent) { + if (from) { + seen = $arrSlice.call(seen); + seen.push(from); + } + if (noIndent) { + var newOpts = { + depth: opts.depth + }; + if (has(opts, 'quoteStyle')) { + newOpts.quoteStyle = opts.quoteStyle; + } + return inspect_(value, newOpts, depth + 1, seen); + } + return inspect_(value, opts, depth + 1, seen); + } + + if (typeof obj === 'function' && !isRegExp(obj)) { // in older engines, regexes are callable + var name = nameOf(obj); + var keys = arrObjKeys(obj, inspect); + return '[Function' + (name ? ': ' + name : ' (anonymous)') + ']' + (keys.length > 0 ? ' { ' + $join.call(keys, ', ') + ' }' : ''); + } + if (isSymbol(obj)) { + var symString = hasShammedSymbols ? $replace.call(String(obj), /^(Symbol\(.*\))_[^)]*$/, '$1') : symToString.call(obj); + return typeof obj === 'object' && !hasShammedSymbols ? markBoxed(symString) : symString; + } + if (isElement(obj)) { + var s = '<' + $toLowerCase.call(String(obj.nodeName)); + var attrs = obj.attributes || []; + for (var i = 0; i < attrs.length; i++) { + s += ' ' + attrs[i].name + '=' + wrapQuotes(quote(attrs[i].value), 'double', opts); + } + s += '>'; + if (obj.childNodes && obj.childNodes.length) { s += '...'; } + s += ''; + return s; + } + if (isArray(obj)) { + if (obj.length === 0) { return '[]'; } + var xs = arrObjKeys(obj, inspect); + if (indent && !singleLineValues(xs)) { + return '[' + indentedJoin(xs, indent) + ']'; + } + return '[ ' + $join.call(xs, ', ') + ' ]'; + } + if (isError(obj)) { + var parts = arrObjKeys(obj, inspect); + if (!('cause' in Error.prototype) && 'cause' in obj && !isEnumerable.call(obj, 'cause')) { + return '{ [' + String(obj) + '] ' + $join.call($concat.call('[cause]: ' + inspect(obj.cause), parts), ', ') + ' }'; + } + if (parts.length === 0) { return '[' + String(obj) + ']'; } + return '{ [' + String(obj) + '] ' + $join.call(parts, ', ') + ' }'; + } + if (typeof obj === 'object' && customInspect) { + if (inspectSymbol && typeof obj[inspectSymbol] === 'function' && utilInspect) { + return utilInspect(obj, { depth: maxDepth - depth }); + } else if (customInspect !== 'symbol' && typeof obj.inspect === 'function') { + return obj.inspect(); + } + } + if (isMap(obj)) { + var mapParts = []; + if (mapForEach) { + mapForEach.call(obj, function (value, key) { + mapParts.push(inspect(key, obj, true) + ' => ' + inspect(value, obj)); + }); + } + return collectionOf('Map', mapSize.call(obj), mapParts, indent); + } + if (isSet(obj)) { + var setParts = []; + if (setForEach) { + setForEach.call(obj, function (value) { + setParts.push(inspect(value, obj)); + }); + } + return collectionOf('Set', setSize.call(obj), setParts, indent); + } + if (isWeakMap(obj)) { + return weakCollectionOf('WeakMap'); + } + if (isWeakSet(obj)) { + return weakCollectionOf('WeakSet'); + } + if (isWeakRef(obj)) { + return weakCollectionOf('WeakRef'); + } + if (isNumber(obj)) { + return markBoxed(inspect(Number(obj))); + } + if (isBigInt(obj)) { + return markBoxed(inspect(bigIntValueOf.call(obj))); + } + if (isBoolean(obj)) { + return markBoxed(booleanValueOf.call(obj)); + } + if (isString(obj)) { + return markBoxed(inspect(String(obj))); + } + // note: in IE 8, sometimes `undefined !== window` but both are the prototypes of each other + /* eslint-env browser */ + if (typeof window !== 'undefined' && obj === window) { + return '{ [object Window] }'; + } + if ( + (typeof globalThis !== 'undefined' && obj === globalThis) + || (typeof commonjsGlobal !== 'undefined' && obj === commonjsGlobal) + ) { + return '{ [object globalThis] }'; + } + if (!isDate(obj) && !isRegExp(obj)) { + var ys = arrObjKeys(obj, inspect); + var isPlainObject = gPO ? gPO(obj) === Object.prototype : obj instanceof Object || obj.constructor === Object; + var protoTag = obj instanceof Object ? '' : 'null prototype'; + var stringTag = !isPlainObject && toStringTag && Object(obj) === obj && toStringTag in obj ? $slice.call(toStr(obj), 8, -1) : protoTag ? 'Object' : ''; + var constructorTag = isPlainObject || typeof obj.constructor !== 'function' ? '' : obj.constructor.name ? obj.constructor.name + ' ' : ''; + var tag = constructorTag + (stringTag || protoTag ? '[' + $join.call($concat.call([], stringTag || [], protoTag || []), ': ') + '] ' : ''); + if (ys.length === 0) { return tag + '{}'; } + if (indent) { + return tag + '{' + indentedJoin(ys, indent) + '}'; + } + return tag + '{ ' + $join.call(ys, ', ') + ' }'; + } + return String(obj); + }; + + function wrapQuotes(s, defaultStyle, opts) { + var style = opts.quoteStyle || defaultStyle; + var quoteChar = quotes[style]; + return quoteChar + s + quoteChar; + } + + function quote(s) { + return $replace.call(String(s), /"/g, '"'); + } + + function canTrustToString(obj) { + return !toStringTag || !(typeof obj === 'object' && (toStringTag in obj || typeof obj[toStringTag] !== 'undefined')); + } + function isArray(obj) { return toStr(obj) === '[object Array]' && canTrustToString(obj); } + function isDate(obj) { return toStr(obj) === '[object Date]' && canTrustToString(obj); } + function isRegExp(obj) { return toStr(obj) === '[object RegExp]' && canTrustToString(obj); } + function isError(obj) { return toStr(obj) === '[object Error]' && canTrustToString(obj); } + function isString(obj) { return toStr(obj) === '[object String]' && canTrustToString(obj); } + function isNumber(obj) { return toStr(obj) === '[object Number]' && canTrustToString(obj); } + function isBoolean(obj) { return toStr(obj) === '[object Boolean]' && canTrustToString(obj); } + + // Symbol and BigInt do have Symbol.toStringTag by spec, so that can't be used to eliminate false positives + function isSymbol(obj) { + if (hasShammedSymbols) { + return obj && typeof obj === 'object' && obj instanceof Symbol; + } + if (typeof obj === 'symbol') { + return true; + } + if (!obj || typeof obj !== 'object' || !symToString) { + return false; + } + try { + symToString.call(obj); + return true; + } catch (e) {} + return false; + } + + function isBigInt(obj) { + if (!obj || typeof obj !== 'object' || !bigIntValueOf) { + return false; + } + try { + bigIntValueOf.call(obj); + return true; + } catch (e) {} + return false; + } + + var hasOwn = Object.prototype.hasOwnProperty || function (key) { return key in this; }; + function has(obj, key) { + return hasOwn.call(obj, key); + } + + function toStr(obj) { + return objectToString.call(obj); + } + + function nameOf(f) { + if (f.name) { return f.name; } + var m = $match.call(functionToString.call(f), /^function\s*([\w$]+)/); + if (m) { return m[1]; } + return null; + } + + function indexOf(xs, x) { + if (xs.indexOf) { return xs.indexOf(x); } + for (var i = 0, l = xs.length; i < l; i++) { + if (xs[i] === x) { return i; } + } + return -1; + } + + function isMap(x) { + if (!mapSize || !x || typeof x !== 'object') { + return false; + } + try { + mapSize.call(x); + try { + setSize.call(x); + } catch (s) { + return true; + } + return x instanceof Map; // core-js workaround, pre-v2.5.0 + } catch (e) {} + return false; + } + + function isWeakMap(x) { + if (!weakMapHas || !x || typeof x !== 'object') { + return false; + } + try { + weakMapHas.call(x, weakMapHas); + try { + weakSetHas.call(x, weakSetHas); + } catch (s) { + return true; + } + return x instanceof WeakMap; // core-js workaround, pre-v2.5.0 + } catch (e) {} + return false; + } + + function isWeakRef(x) { + if (!weakRefDeref || !x || typeof x !== 'object') { + return false; + } + try { + weakRefDeref.call(x); + return true; + } catch (e) {} + return false; + } + + function isSet(x) { + if (!setSize || !x || typeof x !== 'object') { + return false; + } + try { + setSize.call(x); + try { + mapSize.call(x); + } catch (m) { + return true; + } + return x instanceof Set; // core-js workaround, pre-v2.5.0 + } catch (e) {} + return false; + } + + function isWeakSet(x) { + if (!weakSetHas || !x || typeof x !== 'object') { + return false; + } + try { + weakSetHas.call(x, weakSetHas); + try { + weakMapHas.call(x, weakMapHas); + } catch (s) { + return true; + } + return x instanceof WeakSet; // core-js workaround, pre-v2.5.0 + } catch (e) {} + return false; + } + + function isElement(x) { + if (!x || typeof x !== 'object') { return false; } + if (typeof HTMLElement !== 'undefined' && x instanceof HTMLElement) { + return true; + } + return typeof x.nodeName === 'string' && typeof x.getAttribute === 'function'; + } + + function inspectString(str, opts) { + if (str.length > opts.maxStringLength) { + var remaining = str.length - opts.maxStringLength; + var trailer = '... ' + remaining + ' more character' + (remaining > 1 ? 's' : ''); + return inspectString($slice.call(str, 0, opts.maxStringLength), opts) + trailer; + } + var quoteRE = quoteREs[opts.quoteStyle || 'single']; + quoteRE.lastIndex = 0; + // eslint-disable-next-line no-control-regex + var s = $replace.call($replace.call(str, quoteRE, '\\$1'), /[\x00-\x1f]/g, lowbyte); + return wrapQuotes(s, 'single', opts); + } + + function lowbyte(c) { + var n = c.charCodeAt(0); + var x = { + 8: 'b', + 9: 't', + 10: 'n', + 12: 'f', + 13: 'r' + }[n]; + if (x) { return '\\' + x; } + return '\\x' + (n < 0x10 ? '0' : '') + $toUpperCase.call(n.toString(16)); + } + + function markBoxed(str) { + return 'Object(' + str + ')'; + } + + function weakCollectionOf(type) { + return type + ' { ? }'; + } + + function collectionOf(type, size, entries, indent) { + var joinedEntries = indent ? indentedJoin(entries, indent) : $join.call(entries, ', '); + return type + ' (' + size + ') {' + joinedEntries + '}'; + } + + function singleLineValues(xs) { + for (var i = 0; i < xs.length; i++) { + if (indexOf(xs[i], '\n') >= 0) { + return false; + } + } + return true; + } + + function getIndent(opts, depth) { + var baseIndent; + if (opts.indent === '\t') { + baseIndent = '\t'; + } else if (typeof opts.indent === 'number' && opts.indent > 0) { + baseIndent = $join.call(Array(opts.indent + 1), ' '); + } else { + return null; + } + return { + base: baseIndent, + prev: $join.call(Array(depth + 1), baseIndent) + }; + } + + function indentedJoin(xs, indent) { + if (xs.length === 0) { return ''; } + var lineJoiner = '\n' + indent.prev + indent.base; + return lineJoiner + $join.call(xs, ',' + lineJoiner) + '\n' + indent.prev; + } + + function arrObjKeys(obj, inspect) { + var isArr = isArray(obj); + var xs = []; + if (isArr) { + xs.length = obj.length; + for (var i = 0; i < obj.length; i++) { + xs[i] = has(obj, i) ? inspect(obj[i], obj) : ''; + } + } + var syms = typeof gOPS === 'function' ? gOPS(obj) : []; + var symMap; + if (hasShammedSymbols) { + symMap = {}; + for (var k = 0; k < syms.length; k++) { + symMap['$' + syms[k]] = syms[k]; + } + } + + for (var key in obj) { // eslint-disable-line no-restricted-syntax + if (!has(obj, key)) { continue; } // eslint-disable-line no-restricted-syntax, no-continue + if (isArr && String(Number(key)) === key && key < obj.length) { continue; } // eslint-disable-line no-restricted-syntax, no-continue + if (hasShammedSymbols && symMap['$' + key] instanceof Symbol) { + // this is to prevent shammed Symbols, which are stored as strings, from being included in the string key section + continue; // eslint-disable-line no-restricted-syntax, no-continue + } else if ($test.call(/[^\w$]/, key)) { + xs.push(inspect(key, obj) + ': ' + inspect(obj[key], obj)); + } else { + xs.push(key + ': ' + inspect(obj[key], obj)); + } + } + if (typeof gOPS === 'function') { + for (var j = 0; j < syms.length; j++) { + if (isEnumerable.call(obj, syms[j])) { + xs.push('[' + inspect(syms[j]) + ']: ' + inspect(obj[syms[j]], obj)); + } + } + } + return xs; + } + return objectInspect; +} + +var sideChannelList; +var hasRequiredSideChannelList; + +function requireSideChannelList () { + if (hasRequiredSideChannelList) return sideChannelList; + hasRequiredSideChannelList = 1; + + var inspect = /*@__PURE__*/ requireObjectInspect(); + + var $TypeError = /*@__PURE__*/ requireType(); + + /* + * This function traverses the list returning the node corresponding to the given key. + * + * That node is also moved to the head of the list, so that if it's accessed again we don't need to traverse the whole list. + * By doing so, all the recently used nodes can be accessed relatively quickly. + */ + /** @type {import('./list.d.ts').listGetNode} */ + // eslint-disable-next-line consistent-return + var listGetNode = function (list, key, isDelete) { + /** @type {typeof list | NonNullable<(typeof list)['next']>} */ + var prev = list; + /** @type {(typeof list)['next']} */ + var curr; + // eslint-disable-next-line eqeqeq + for (; (curr = prev.next) != null; prev = curr) { + if (curr.key === key) { + prev.next = curr.next; + if (!isDelete) { + // eslint-disable-next-line no-extra-parens + curr.next = /** @type {NonNullable} */ (list.next); + list.next = curr; // eslint-disable-line no-param-reassign + } + return curr; + } + } + }; + + /** @type {import('./list.d.ts').listGet} */ + var listGet = function (objects, key) { + if (!objects) { + return void undefined; + } + var node = listGetNode(objects, key); + return node && node.value; + }; + /** @type {import('./list.d.ts').listSet} */ + var listSet = function (objects, key, value) { + var node = listGetNode(objects, key); + if (node) { + node.value = value; + } else { + // Prepend the new node to the beginning of the list + objects.next = /** @type {import('./list.d.ts').ListNode} */ ({ // eslint-disable-line no-param-reassign, no-extra-parens + key: key, + next: objects.next, + value: value + }); + } + }; + /** @type {import('./list.d.ts').listHas} */ + var listHas = function (objects, key) { + if (!objects) { + return false; + } + return !!listGetNode(objects, key); + }; + /** @type {import('./list.d.ts').listDelete} */ + // eslint-disable-next-line consistent-return + var listDelete = function (objects, key) { + if (objects) { + return listGetNode(objects, key, true); + } + }; + + /** @type {import('.')} */ + sideChannelList = function getSideChannelList() { + /** @typedef {ReturnType} Channel */ + /** @typedef {Parameters[0]} K */ + /** @typedef {Parameters[1]} V */ + + /** @type {import('./list.d.ts').RootNode | undefined} */ var $o; + + /** @type {Channel} */ + var channel = { + assert: function (key) { + if (!channel.has(key)) { + throw new $TypeError('Side channel does not contain ' + inspect(key)); + } + }, + 'delete': function (key) { + var deletedNode = listDelete($o, key); + if (deletedNode && $o && !$o.next) { + $o = void undefined; + } + return !!deletedNode; + }, + get: function (key) { + return listGet($o, key); + }, + has: function (key) { + return listHas($o, key); + }, + set: function (key, value) { + if (!$o) { + // Initialize the linked list as an empty node, so that we don't have to special-case handling of the first node: we can always refer to it as (previous node).next, instead of something like (list).head + $o = { + next: void undefined + }; + } + // eslint-disable-next-line no-extra-parens + listSet(/** @type {NonNullable} */ ($o), key, value); + } + }; + return channel; + }; + return sideChannelList; +} + +var esObjectAtoms; +var hasRequiredEsObjectAtoms; + +function requireEsObjectAtoms () { + if (hasRequiredEsObjectAtoms) return esObjectAtoms; + hasRequiredEsObjectAtoms = 1; + + /** @type {import('.')} */ + esObjectAtoms = Object; + return esObjectAtoms; +} + +var esErrors; +var hasRequiredEsErrors; + +function requireEsErrors () { + if (hasRequiredEsErrors) return esErrors; + hasRequiredEsErrors = 1; + + /** @type {import('.')} */ + esErrors = Error; + return esErrors; +} + +var _eval; +var hasRequired_eval; + +function require_eval () { + if (hasRequired_eval) return _eval; + hasRequired_eval = 1; + + /** @type {import('./eval')} */ + _eval = EvalError; + return _eval; +} + +var range; +var hasRequiredRange; + +function requireRange () { + if (hasRequiredRange) return range; + hasRequiredRange = 1; + + /** @type {import('./range')} */ + range = RangeError; + return range; +} + +var ref; +var hasRequiredRef; + +function requireRef () { + if (hasRequiredRef) return ref; + hasRequiredRef = 1; + + /** @type {import('./ref')} */ + ref = ReferenceError; + return ref; +} + +var syntax; +var hasRequiredSyntax; + +function requireSyntax () { + if (hasRequiredSyntax) return syntax; + hasRequiredSyntax = 1; + + /** @type {import('./syntax')} */ + syntax = SyntaxError; + return syntax; +} + +var uri; +var hasRequiredUri; + +function requireUri () { + if (hasRequiredUri) return uri; + hasRequiredUri = 1; + + /** @type {import('./uri')} */ + uri = URIError; + return uri; +} + +var abs; +var hasRequiredAbs; + +function requireAbs () { + if (hasRequiredAbs) return abs; + hasRequiredAbs = 1; + + /** @type {import('./abs')} */ + abs = Math.abs; + return abs; +} + +var floor; +var hasRequiredFloor; + +function requireFloor () { + if (hasRequiredFloor) return floor; + hasRequiredFloor = 1; + + /** @type {import('./floor')} */ + floor = Math.floor; + return floor; +} + +var max; +var hasRequiredMax; + +function requireMax () { + if (hasRequiredMax) return max; + hasRequiredMax = 1; + + /** @type {import('./max')} */ + max = Math.max; + return max; +} + +var min; +var hasRequiredMin; + +function requireMin () { + if (hasRequiredMin) return min; + hasRequiredMin = 1; + + /** @type {import('./min')} */ + min = Math.min; + return min; +} + +var pow; +var hasRequiredPow; + +function requirePow () { + if (hasRequiredPow) return pow; + hasRequiredPow = 1; + + /** @type {import('./pow')} */ + pow = Math.pow; + return pow; +} + +var round; +var hasRequiredRound; + +function requireRound () { + if (hasRequiredRound) return round; + hasRequiredRound = 1; + + /** @type {import('./round')} */ + round = Math.round; + return round; +} + +var _isNaN; +var hasRequired_isNaN; + +function require_isNaN () { + if (hasRequired_isNaN) return _isNaN; + hasRequired_isNaN = 1; + + /** @type {import('./isNaN')} */ + _isNaN = Number.isNaN || function isNaN(a) { + return a !== a; + }; + return _isNaN; +} + +var sign; +var hasRequiredSign; + +function requireSign () { + if (hasRequiredSign) return sign; + hasRequiredSign = 1; + + var $isNaN = /*@__PURE__*/ require_isNaN(); + + /** @type {import('./sign')} */ + sign = function sign(number) { + if ($isNaN(number) || number === 0) { + return number; + } + return number < 0 ? -1 : 1; + }; + return sign; +} + +var gOPD; +var hasRequiredGOPD; + +function requireGOPD () { + if (hasRequiredGOPD) return gOPD; + hasRequiredGOPD = 1; + + /** @type {import('./gOPD')} */ + gOPD = Object.getOwnPropertyDescriptor; + return gOPD; +} + +var gopd; +var hasRequiredGopd; + +function requireGopd () { + if (hasRequiredGopd) return gopd; + hasRequiredGopd = 1; + + /** @type {import('.')} */ + var $gOPD = /*@__PURE__*/ requireGOPD(); + + if ($gOPD) { + try { + $gOPD([], 'length'); + } catch (e) { + // IE 8 has a broken gOPD + $gOPD = null; + } + } + + gopd = $gOPD; + return gopd; +} + +var esDefineProperty; +var hasRequiredEsDefineProperty; + +function requireEsDefineProperty () { + if (hasRequiredEsDefineProperty) return esDefineProperty; + hasRequiredEsDefineProperty = 1; + + /** @type {import('.')} */ + var $defineProperty = Object.defineProperty || false; + if ($defineProperty) { + try { + $defineProperty({}, 'a', { value: 1 }); + } catch (e) { + // IE 8 has a broken defineProperty + $defineProperty = false; + } + } + + esDefineProperty = $defineProperty; + return esDefineProperty; +} + +var shams; +var hasRequiredShams; + +function requireShams () { + if (hasRequiredShams) return shams; + hasRequiredShams = 1; + + /** @type {import('./shams')} */ + /* eslint complexity: [2, 18], max-statements: [2, 33] */ + shams = function hasSymbols() { + if (typeof Symbol !== 'function' || typeof Object.getOwnPropertySymbols !== 'function') { return false; } + if (typeof Symbol.iterator === 'symbol') { return true; } + + /** @type {{ [k in symbol]?: unknown }} */ + var obj = {}; + var sym = Symbol('test'); + var symObj = Object(sym); + if (typeof sym === 'string') { return false; } + + if (Object.prototype.toString.call(sym) !== '[object Symbol]') { return false; } + if (Object.prototype.toString.call(symObj) !== '[object Symbol]') { return false; } + + // temp disabled per https://github.com/ljharb/object.assign/issues/17 + // if (sym instanceof Symbol) { return false; } + // temp disabled per https://github.com/WebReflection/get-own-property-symbols/issues/4 + // if (!(symObj instanceof Symbol)) { return false; } + + // if (typeof Symbol.prototype.toString !== 'function') { return false; } + // if (String(sym) !== Symbol.prototype.toString.call(sym)) { return false; } + + var symVal = 42; + obj[sym] = symVal; + for (var _ in obj) { return false; } // eslint-disable-line no-restricted-syntax, no-unreachable-loop + if (typeof Object.keys === 'function' && Object.keys(obj).length !== 0) { return false; } + + if (typeof Object.getOwnPropertyNames === 'function' && Object.getOwnPropertyNames(obj).length !== 0) { return false; } + + var syms = Object.getOwnPropertySymbols(obj); + if (syms.length !== 1 || syms[0] !== sym) { return false; } + + if (!Object.prototype.propertyIsEnumerable.call(obj, sym)) { return false; } + + if (typeof Object.getOwnPropertyDescriptor === 'function') { + // eslint-disable-next-line no-extra-parens + var descriptor = /** @type {PropertyDescriptor} */ (Object.getOwnPropertyDescriptor(obj, sym)); + if (descriptor.value !== symVal || descriptor.enumerable !== true) { return false; } + } + + return true; + }; + return shams; +} + +var hasSymbols; +var hasRequiredHasSymbols; + +function requireHasSymbols () { + if (hasRequiredHasSymbols) return hasSymbols; + hasRequiredHasSymbols = 1; + + var origSymbol = typeof Symbol !== 'undefined' && Symbol; + var hasSymbolSham = requireShams(); + + /** @type {import('.')} */ + hasSymbols = function hasNativeSymbols() { + if (typeof origSymbol !== 'function') { return false; } + if (typeof Symbol !== 'function') { return false; } + if (typeof origSymbol('foo') !== 'symbol') { return false; } + if (typeof Symbol('bar') !== 'symbol') { return false; } + + return hasSymbolSham(); + }; + return hasSymbols; +} + +var Reflect_getPrototypeOf; +var hasRequiredReflect_getPrototypeOf; + +function requireReflect_getPrototypeOf () { + if (hasRequiredReflect_getPrototypeOf) return Reflect_getPrototypeOf; + hasRequiredReflect_getPrototypeOf = 1; + + /** @type {import('./Reflect.getPrototypeOf')} */ + Reflect_getPrototypeOf = (typeof Reflect !== 'undefined' && Reflect.getPrototypeOf) || null; + return Reflect_getPrototypeOf; +} + +var Object_getPrototypeOf; +var hasRequiredObject_getPrototypeOf; + +function requireObject_getPrototypeOf () { + if (hasRequiredObject_getPrototypeOf) return Object_getPrototypeOf; + hasRequiredObject_getPrototypeOf = 1; + + var $Object = /*@__PURE__*/ requireEsObjectAtoms(); + + /** @type {import('./Object.getPrototypeOf')} */ + Object_getPrototypeOf = $Object.getPrototypeOf || null; + return Object_getPrototypeOf; +} + +var implementation; +var hasRequiredImplementation; + +function requireImplementation () { + if (hasRequiredImplementation) return implementation; + hasRequiredImplementation = 1; + + /* eslint no-invalid-this: 1 */ + + var ERROR_MESSAGE = 'Function.prototype.bind called on incompatible '; + var toStr = Object.prototype.toString; + var max = Math.max; + var funcType = '[object Function]'; + + var concatty = function concatty(a, b) { + var arr = []; + + for (var i = 0; i < a.length; i += 1) { + arr[i] = a[i]; + } + for (var j = 0; j < b.length; j += 1) { + arr[j + a.length] = b[j]; + } + + return arr; + }; + + var slicy = function slicy(arrLike, offset) { + var arr = []; + for (var i = offset, j = 0; i < arrLike.length; i += 1, j += 1) { + arr[j] = arrLike[i]; + } + return arr; + }; + + var joiny = function (arr, joiner) { + var str = ''; + for (var i = 0; i < arr.length; i += 1) { + str += arr[i]; + if (i + 1 < arr.length) { + str += joiner; + } + } + return str; + }; + + implementation = function bind(that) { + var target = this; + if (typeof target !== 'function' || toStr.apply(target) !== funcType) { + throw new TypeError(ERROR_MESSAGE + target); + } + var args = slicy(arguments, 1); + + var bound; + var binder = function () { + if (this instanceof bound) { + var result = target.apply( + this, + concatty(args, arguments) + ); + if (Object(result) === result) { + return result; + } + return this; + } + return target.apply( + that, + concatty(args, arguments) + ); + + }; + + var boundLength = max(0, target.length - args.length); + var boundArgs = []; + for (var i = 0; i < boundLength; i++) { + boundArgs[i] = '$' + i; + } + + bound = Function('binder', 'return function (' + joiny(boundArgs, ',') + '){ return binder.apply(this,arguments); }')(binder); + + if (target.prototype) { + var Empty = function Empty() {}; + Empty.prototype = target.prototype; + bound.prototype = new Empty(); + Empty.prototype = null; + } + + return bound; + }; + return implementation; +} + +var functionBind; +var hasRequiredFunctionBind; + +function requireFunctionBind () { + if (hasRequiredFunctionBind) return functionBind; + hasRequiredFunctionBind = 1; + + var implementation = requireImplementation(); + + functionBind = Function.prototype.bind || implementation; + return functionBind; +} + +var functionCall; +var hasRequiredFunctionCall; + +function requireFunctionCall () { + if (hasRequiredFunctionCall) return functionCall; + hasRequiredFunctionCall = 1; + + /** @type {import('./functionCall')} */ + functionCall = Function.prototype.call; + return functionCall; +} + +var functionApply; +var hasRequiredFunctionApply; + +function requireFunctionApply () { + if (hasRequiredFunctionApply) return functionApply; + hasRequiredFunctionApply = 1; + + /** @type {import('./functionApply')} */ + functionApply = Function.prototype.apply; + return functionApply; +} + +var reflectApply; +var hasRequiredReflectApply; + +function requireReflectApply () { + if (hasRequiredReflectApply) return reflectApply; + hasRequiredReflectApply = 1; + + /** @type {import('./reflectApply')} */ + reflectApply = typeof Reflect !== 'undefined' && Reflect && Reflect.apply; + return reflectApply; +} + +var actualApply; +var hasRequiredActualApply; + +function requireActualApply () { + if (hasRequiredActualApply) return actualApply; + hasRequiredActualApply = 1; + + var bind = requireFunctionBind(); + + var $apply = requireFunctionApply(); + var $call = requireFunctionCall(); + var $reflectApply = requireReflectApply(); + + /** @type {import('./actualApply')} */ + actualApply = $reflectApply || bind.call($call, $apply); + return actualApply; +} + +var callBindApplyHelpers; +var hasRequiredCallBindApplyHelpers; + +function requireCallBindApplyHelpers () { + if (hasRequiredCallBindApplyHelpers) return callBindApplyHelpers; + hasRequiredCallBindApplyHelpers = 1; + + var bind = requireFunctionBind(); + var $TypeError = /*@__PURE__*/ requireType(); + + var $call = requireFunctionCall(); + var $actualApply = requireActualApply(); + + /** @type {(args: [Function, thisArg?: unknown, ...args: unknown[]]) => Function} TODO FIXME, find a way to use import('.') */ + callBindApplyHelpers = function callBindBasic(args) { + if (args.length < 1 || typeof args[0] !== 'function') { + throw new $TypeError('a function is required'); + } + return $actualApply(bind, $call, args); + }; + return callBindApplyHelpers; +} + +var get; +var hasRequiredGet; + +function requireGet () { + if (hasRequiredGet) return get; + hasRequiredGet = 1; + + var callBind = requireCallBindApplyHelpers(); + var gOPD = /*@__PURE__*/ requireGopd(); + + var hasProtoAccessor; + try { + // eslint-disable-next-line no-extra-parens, no-proto + hasProtoAccessor = /** @type {{ __proto__?: typeof Array.prototype }} */ ([]).__proto__ === Array.prototype; + } catch (e) { + if (!e || typeof e !== 'object' || !('code' in e) || e.code !== 'ERR_PROTO_ACCESS') { + throw e; + } + } + + // eslint-disable-next-line no-extra-parens + var desc = !!hasProtoAccessor && gOPD && gOPD(Object.prototype, /** @type {keyof typeof Object.prototype} */ ('__proto__')); + + var $Object = Object; + var $getPrototypeOf = $Object.getPrototypeOf; + + /** @type {import('./get')} */ + get = desc && typeof desc.get === 'function' + ? callBind([desc.get]) + : typeof $getPrototypeOf === 'function' + ? /** @type {import('./get')} */ function getDunder(value) { + // eslint-disable-next-line eqeqeq + return $getPrototypeOf(value == null ? value : $Object(value)); + } + : false; + return get; +} + +var getProto; +var hasRequiredGetProto; + +function requireGetProto () { + if (hasRequiredGetProto) return getProto; + hasRequiredGetProto = 1; + + var reflectGetProto = requireReflect_getPrototypeOf(); + var originalGetProto = requireObject_getPrototypeOf(); + + var getDunderProto = /*@__PURE__*/ requireGet(); + + /** @type {import('.')} */ + getProto = reflectGetProto + ? function getProto(O) { + // @ts-expect-error TS can't narrow inside a closure, for some reason + return reflectGetProto(O); + } + : originalGetProto + ? function getProto(O) { + if (!O || (typeof O !== 'object' && typeof O !== 'function')) { + throw new TypeError('getProto: not an object'); + } + // @ts-expect-error TS can't narrow inside a closure, for some reason + return originalGetProto(O); + } + : getDunderProto + ? function getProto(O) { + // @ts-expect-error TS can't narrow inside a closure, for some reason + return getDunderProto(O); + } + : null; + return getProto; +} + +var asyncFunction; +var hasRequiredAsyncFunction; + +function requireAsyncFunction () { + if (hasRequiredAsyncFunction) return asyncFunction; + hasRequiredAsyncFunction = 1; + + // eslint-disable-next-line no-extra-parens, no-empty-function + const cached = /** @type {import('.').AsyncFunctionConstructor} */ (async function () {}.constructor); + + /** @type {import('.')} */ + asyncFunction = () => cached; + return asyncFunction; +} + +var generatorFunction; +var hasRequiredGeneratorFunction; + +function requireGeneratorFunction () { + if (hasRequiredGeneratorFunction) return generatorFunction; + hasRequiredGeneratorFunction = 1; + + // eslint-disable-next-line no-extra-parens, no-empty-function + const cached = /** @type {GeneratorFunctionConstructor} */ (function* () {}.constructor); + + /** @type {import('.')} */ + generatorFunction = () => cached; + return generatorFunction; +} + +var asyncGeneratorFunction; +var hasRequiredAsyncGeneratorFunction; + +function requireAsyncGeneratorFunction () { + if (hasRequiredAsyncGeneratorFunction) return asyncGeneratorFunction; + hasRequiredAsyncGeneratorFunction = 1; + + // eslint-disable-next-line no-extra-parens, no-empty-function + const cached = /** @type {import('.').AsyncGeneratorFunctionConstructor} */ (async function* () {}.constructor); + + /** @type {import('.')} */ + asyncGeneratorFunction = () => cached; + return asyncGeneratorFunction; +} + +var hasown; +var hasRequiredHasown; + +function requireHasown () { + if (hasRequiredHasown) return hasown; + hasRequiredHasown = 1; + + var call = Function.prototype.call; + var $hasOwn = Object.prototype.hasOwnProperty; + var bind = requireFunctionBind(); + + /** @type {import('.')} */ + hasown = bind.call(call, $hasOwn); + return hasown; +} + +var getIntrinsic; +var hasRequiredGetIntrinsic; + +function requireGetIntrinsic () { + if (hasRequiredGetIntrinsic) return getIntrinsic; + hasRequiredGetIntrinsic = 1; + + var undefined$1; + + var $Object = /*@__PURE__*/ requireEsObjectAtoms(); + + var $Error = /*@__PURE__*/ requireEsErrors(); + var $EvalError = /*@__PURE__*/ require_eval(); + var $RangeError = /*@__PURE__*/ requireRange(); + var $ReferenceError = /*@__PURE__*/ requireRef(); + var $SyntaxError = /*@__PURE__*/ requireSyntax(); + var $TypeError = /*@__PURE__*/ requireType(); + var $URIError = /*@__PURE__*/ requireUri(); + + var abs = /*@__PURE__*/ requireAbs(); + var floor = /*@__PURE__*/ requireFloor(); + var max = /*@__PURE__*/ requireMax(); + var min = /*@__PURE__*/ requireMin(); + var pow = /*@__PURE__*/ requirePow(); + var round = /*@__PURE__*/ requireRound(); + var sign = /*@__PURE__*/ requireSign(); + + var $gOPD = /*@__PURE__*/ requireGopd(); + var $defineProperty = /*@__PURE__*/ requireEsDefineProperty(); + + var throwTypeError = function () { + throw new $TypeError(); + }; + var ThrowTypeError = $gOPD + ? (function () { + try { + // eslint-disable-next-line no-unused-expressions, no-caller, no-restricted-properties + arguments.callee; // IE 8 does not throw here + return throwTypeError; + } catch (calleeThrows) { + try { + // IE 8 throws on Object.getOwnPropertyDescriptor(arguments, '') + return $gOPD(arguments, 'callee').get; + } catch (gOPDthrows) { + return throwTypeError; + } + } + }()) + : throwTypeError; + + var hasSymbols = requireHasSymbols()(); + + var getProto = requireGetProto(); + var $ObjectGPO = requireObject_getPrototypeOf(); + var $ReflectGPO = requireReflect_getPrototypeOf(); + + var $apply = requireFunctionApply(); + var $call = requireFunctionCall(); + + var needsEval = {}; + + var TypedArray = typeof Uint8Array === 'undefined' || !getProto ? undefined$1 : getProto(Uint8Array); + + var INTRINSICS = { + __proto__: null, + '%AggregateError%': typeof AggregateError === 'undefined' ? undefined$1 : AggregateError, + '%Array%': Array, + '%ArrayBuffer%': typeof ArrayBuffer === 'undefined' ? undefined$1 : ArrayBuffer, + '%ArrayIteratorPrototype%': hasSymbols && getProto ? getProto([][Symbol.iterator]()) : undefined$1, + '%AsyncFromSyncIteratorPrototype%': undefined$1, + '%AsyncFunction%': needsEval, + '%AsyncGenerator%': needsEval, + '%AsyncGeneratorFunction%': needsEval, + '%AsyncIteratorPrototype%': needsEval, + '%Atomics%': typeof Atomics === 'undefined' ? undefined$1 : Atomics, + '%BigInt%': typeof BigInt === 'undefined' ? undefined$1 : BigInt, + '%BigInt64Array%': typeof BigInt64Array === 'undefined' ? undefined$1 : BigInt64Array, + '%BigUint64Array%': typeof BigUint64Array === 'undefined' ? undefined$1 : BigUint64Array, + '%Boolean%': Boolean, + '%DataView%': typeof DataView === 'undefined' ? undefined$1 : DataView, + '%Date%': Date, + '%decodeURI%': decodeURI, + '%decodeURIComponent%': decodeURIComponent, + '%encodeURI%': encodeURI, + '%encodeURIComponent%': encodeURIComponent, + '%Error%': $Error, + '%eval%': eval, // eslint-disable-line no-eval + '%EvalError%': $EvalError, + '%Float16Array%': typeof Float16Array === 'undefined' ? undefined$1 : Float16Array, + '%Float32Array%': typeof Float32Array === 'undefined' ? undefined$1 : Float32Array, + '%Float64Array%': typeof Float64Array === 'undefined' ? undefined$1 : Float64Array, + '%FinalizationRegistry%': typeof FinalizationRegistry === 'undefined' ? undefined$1 : FinalizationRegistry, + '%Function%': Function, + '%GeneratorFunction%': needsEval, + '%Int8Array%': typeof Int8Array === 'undefined' ? undefined$1 : Int8Array, + '%Int16Array%': typeof Int16Array === 'undefined' ? undefined$1 : Int16Array, + '%Int32Array%': typeof Int32Array === 'undefined' ? undefined$1 : Int32Array, + '%isFinite%': isFinite, + '%isNaN%': isNaN, + '%IteratorPrototype%': hasSymbols && getProto ? getProto(getProto([][Symbol.iterator]())) : undefined$1, + '%JSON%': typeof JSON === 'object' ? JSON : undefined$1, + '%Map%': typeof Map === 'undefined' ? undefined$1 : Map, + '%MapIteratorPrototype%': typeof Map === 'undefined' || !hasSymbols || !getProto ? undefined$1 : getProto(new Map()[Symbol.iterator]()), + '%Math%': Math, + '%Number%': Number, + '%Object%': $Object, + '%Object.getOwnPropertyDescriptor%': $gOPD, + '%parseFloat%': parseFloat, + '%parseInt%': parseInt, + '%Promise%': typeof Promise === 'undefined' ? undefined$1 : Promise, + '%Proxy%': typeof Proxy === 'undefined' ? undefined$1 : Proxy, + '%RangeError%': $RangeError, + '%ReferenceError%': $ReferenceError, + '%Reflect%': typeof Reflect === 'undefined' ? undefined$1 : Reflect, + '%RegExp%': RegExp, + '%Set%': typeof Set === 'undefined' ? undefined$1 : Set, + '%SetIteratorPrototype%': typeof Set === 'undefined' || !hasSymbols || !getProto ? undefined$1 : getProto(new Set()[Symbol.iterator]()), + '%SharedArrayBuffer%': typeof SharedArrayBuffer === 'undefined' ? undefined$1 : SharedArrayBuffer, + '%String%': String, + '%StringIteratorPrototype%': hasSymbols && getProto ? getProto(''[Symbol.iterator]()) : undefined$1, + '%Symbol%': hasSymbols ? Symbol : undefined$1, + '%SyntaxError%': $SyntaxError, + '%ThrowTypeError%': ThrowTypeError, + '%TypedArray%': TypedArray, + '%TypeError%': $TypeError, + '%Uint8Array%': typeof Uint8Array === 'undefined' ? undefined$1 : Uint8Array, + '%Uint8ClampedArray%': typeof Uint8ClampedArray === 'undefined' ? undefined$1 : Uint8ClampedArray, + '%Uint16Array%': typeof Uint16Array === 'undefined' ? undefined$1 : Uint16Array, + '%Uint32Array%': typeof Uint32Array === 'undefined' ? undefined$1 : Uint32Array, + '%URIError%': $URIError, + '%WeakMap%': typeof WeakMap === 'undefined' ? undefined$1 : WeakMap, + '%WeakRef%': typeof WeakRef === 'undefined' ? undefined$1 : WeakRef, + '%WeakSet%': typeof WeakSet === 'undefined' ? undefined$1 : WeakSet, + + '%Function.prototype.call%': $call, + '%Function.prototype.apply%': $apply, + '%Object.defineProperty%': $defineProperty, + '%Object.getPrototypeOf%': $ObjectGPO, + '%Math.abs%': abs, + '%Math.floor%': floor, + '%Math.max%': max, + '%Math.min%': min, + '%Math.pow%': pow, + '%Math.round%': round, + '%Math.sign%': sign, + '%Reflect.getPrototypeOf%': $ReflectGPO + }; + + if (getProto) { + try { + null.error; // eslint-disable-line no-unused-expressions + } catch (e) { + // https://github.com/tc39/proposal-shadowrealm/pull/384#issuecomment-1364264229 + var errorProto = getProto(getProto(e)); + INTRINSICS['%Error.prototype%'] = errorProto; + } + } + + var getAsyncFunction = requireAsyncFunction(); + var getGeneratorFunction = /*@__PURE__*/ requireGeneratorFunction(); + var getAsyncGeneratorFunction = requireAsyncGeneratorFunction(); + + var doEval = function doEval(name) { + var value; + if (name === '%AsyncFunction%') { + value = getAsyncFunction() || void undefined$1; + } else if (name === '%GeneratorFunction%') { + value = getGeneratorFunction() || void undefined$1; + } else if (name === '%AsyncGeneratorFunction%') { + value = getAsyncGeneratorFunction() || void undefined$1; + } else if (name === '%AsyncGenerator%') { + var fn = doEval('%AsyncGeneratorFunction%'); + if (fn) { + value = fn.prototype; + } + } else if (name === '%AsyncIteratorPrototype%') { + var gen = doEval('%AsyncGenerator%'); + if (gen && getProto) { + value = getProto(gen.prototype); + } + } + + INTRINSICS[name] = value; + + return value; + }; + + var LEGACY_ALIASES = { + __proto__: null, + '%ArrayBufferPrototype%': ['ArrayBuffer', 'prototype'], + '%ArrayPrototype%': ['Array', 'prototype'], + '%ArrayProto_entries%': ['Array', 'prototype', 'entries'], + '%ArrayProto_forEach%': ['Array', 'prototype', 'forEach'], + '%ArrayProto_keys%': ['Array', 'prototype', 'keys'], + '%ArrayProto_values%': ['Array', 'prototype', 'values'], + '%AsyncFunctionPrototype%': ['AsyncFunction', 'prototype'], + '%AsyncGenerator%': ['AsyncGeneratorFunction', 'prototype'], + '%AsyncGeneratorPrototype%': ['AsyncGeneratorFunction', 'prototype', 'prototype'], + '%BooleanPrototype%': ['Boolean', 'prototype'], + '%DataViewPrototype%': ['DataView', 'prototype'], + '%DatePrototype%': ['Date', 'prototype'], + '%ErrorPrototype%': ['Error', 'prototype'], + '%EvalErrorPrototype%': ['EvalError', 'prototype'], + '%Float32ArrayPrototype%': ['Float32Array', 'prototype'], + '%Float64ArrayPrototype%': ['Float64Array', 'prototype'], + '%FunctionPrototype%': ['Function', 'prototype'], + '%Generator%': ['GeneratorFunction', 'prototype'], + '%GeneratorPrototype%': ['GeneratorFunction', 'prototype', 'prototype'], + '%Int8ArrayPrototype%': ['Int8Array', 'prototype'], + '%Int16ArrayPrototype%': ['Int16Array', 'prototype'], + '%Int32ArrayPrototype%': ['Int32Array', 'prototype'], + '%JSONParse%': ['JSON', 'parse'], + '%JSONStringify%': ['JSON', 'stringify'], + '%MapPrototype%': ['Map', 'prototype'], + '%NumberPrototype%': ['Number', 'prototype'], + '%ObjectPrototype%': ['Object', 'prototype'], + '%ObjProto_toString%': ['Object', 'prototype', 'toString'], + '%ObjProto_valueOf%': ['Object', 'prototype', 'valueOf'], + '%PromisePrototype%': ['Promise', 'prototype'], + '%PromiseProto_then%': ['Promise', 'prototype', 'then'], + '%Promise_all%': ['Promise', 'all'], + '%Promise_reject%': ['Promise', 'reject'], + '%Promise_resolve%': ['Promise', 'resolve'], + '%RangeErrorPrototype%': ['RangeError', 'prototype'], + '%ReferenceErrorPrototype%': ['ReferenceError', 'prototype'], + '%RegExpPrototype%': ['RegExp', 'prototype'], + '%SetPrototype%': ['Set', 'prototype'], + '%SharedArrayBufferPrototype%': ['SharedArrayBuffer', 'prototype'], + '%StringPrototype%': ['String', 'prototype'], + '%SymbolPrototype%': ['Symbol', 'prototype'], + '%SyntaxErrorPrototype%': ['SyntaxError', 'prototype'], + '%TypedArrayPrototype%': ['TypedArray', 'prototype'], + '%TypeErrorPrototype%': ['TypeError', 'prototype'], + '%Uint8ArrayPrototype%': ['Uint8Array', 'prototype'], + '%Uint8ClampedArrayPrototype%': ['Uint8ClampedArray', 'prototype'], + '%Uint16ArrayPrototype%': ['Uint16Array', 'prototype'], + '%Uint32ArrayPrototype%': ['Uint32Array', 'prototype'], + '%URIErrorPrototype%': ['URIError', 'prototype'], + '%WeakMapPrototype%': ['WeakMap', 'prototype'], + '%WeakSetPrototype%': ['WeakSet', 'prototype'] + }; + + var bind = requireFunctionBind(); + var hasOwn = /*@__PURE__*/ requireHasown(); + var $concat = bind.call($call, Array.prototype.concat); + var $spliceApply = bind.call($apply, Array.prototype.splice); + var $replace = bind.call($call, String.prototype.replace); + var $strSlice = bind.call($call, String.prototype.slice); + var $exec = bind.call($call, RegExp.prototype.exec); + + /* adapted from https://github.com/lodash/lodash/blob/4.17.15/dist/lodash.js#L6735-L6744 */ + var rePropName = /[^%.[\]]+|\[(?:(-?\d+(?:\.\d+)?)|(["'])((?:(?!\2)[^\\]|\\.)*?)\2)\]|(?=(?:\.|\[\])(?:\.|\[\]|%$))/g; + var reEscapeChar = /\\(\\)?/g; /** Used to match backslashes in property paths. */ + var stringToPath = function stringToPath(string) { + var first = $strSlice(string, 0, 1); + var last = $strSlice(string, -1); + if (first === '%' && last !== '%') { + throw new $SyntaxError('invalid intrinsic syntax, expected closing `%`'); + } else if (last === '%' && first !== '%') { + throw new $SyntaxError('invalid intrinsic syntax, expected opening `%`'); + } + var result = []; + $replace(string, rePropName, function (match, number, quote, subString) { + result[result.length] = quote ? $replace(subString, reEscapeChar, '$1') : number || match; + }); + return result; + }; + /* end adaptation */ + + var getBaseIntrinsic = function getBaseIntrinsic(name, allowMissing) { + var intrinsicName = name; + var alias; + if (hasOwn(LEGACY_ALIASES, intrinsicName)) { + alias = LEGACY_ALIASES[intrinsicName]; + intrinsicName = '%' + alias[0] + '%'; + } + + if (hasOwn(INTRINSICS, intrinsicName)) { + var value = INTRINSICS[intrinsicName]; + if (value === needsEval) { + value = doEval(intrinsicName); + } + if (typeof value === 'undefined' && !allowMissing) { + throw new $TypeError('intrinsic ' + name + ' exists, but is not available. Please file an issue!'); + } + + return { + alias: alias, + name: intrinsicName, + value: value + }; + } + + throw new $SyntaxError('intrinsic ' + name + ' does not exist!'); + }; + + getIntrinsic = function GetIntrinsic(name, allowMissing) { + if (typeof name !== 'string' || name.length === 0) { + throw new $TypeError('intrinsic name must be a non-empty string'); + } + if (arguments.length > 1 && typeof allowMissing !== 'boolean') { + throw new $TypeError('"allowMissing" argument must be a boolean'); + } + + if ($exec(/^%?[^%]*%?$/, name) === null) { + throw new $SyntaxError('`%` may not be present anywhere but at the beginning and end of the intrinsic name'); + } + var parts = stringToPath(name); + var intrinsicBaseName = parts.length > 0 ? parts[0] : ''; + + var intrinsic = getBaseIntrinsic('%' + intrinsicBaseName + '%', allowMissing); + var intrinsicRealName = intrinsic.name; + var value = intrinsic.value; + var skipFurtherCaching = false; + + var alias = intrinsic.alias; + if (alias) { + intrinsicBaseName = alias[0]; + $spliceApply(parts, $concat([0, 1], alias)); + } + + for (var i = 1, isOwn = true; i < parts.length; i += 1) { + var part = parts[i]; + var first = $strSlice(part, 0, 1); + var last = $strSlice(part, -1); + if ( + ( + (first === '"' || first === "'" || first === '`') + || (last === '"' || last === "'" || last === '`') + ) + && first !== last + ) { + throw new $SyntaxError('property names with quotes must have matching quotes'); + } + if (part === 'constructor' || !isOwn) { + skipFurtherCaching = true; + } + + intrinsicBaseName += '.' + part; + intrinsicRealName = '%' + intrinsicBaseName + '%'; + + if (hasOwn(INTRINSICS, intrinsicRealName)) { + value = INTRINSICS[intrinsicRealName]; + } else if (value != null) { + if (!(part in value)) { + if (!allowMissing) { + throw new $TypeError('base intrinsic for ' + name + ' exists, but the property is not available.'); + } + return void undefined$1; + } + if ($gOPD && (i + 1) >= parts.length) { + var desc = $gOPD(value, part); + isOwn = !!desc; + + // By convention, when a data property is converted to an accessor + // property to emulate a data property that does not suffer from + // the override mistake, that accessor's getter is marked with + // an `originalValue` property. Here, when we detect this, we + // uphold the illusion by pretending to see that original data + // property, i.e., returning the value rather than the getter + // itself. + if (isOwn && 'get' in desc && !('originalValue' in desc.get)) { + value = desc.get; + } else { + value = value[part]; + } + } else { + isOwn = hasOwn(value, part); + value = value[part]; + } + + if (isOwn && !skipFurtherCaching) { + INTRINSICS[intrinsicRealName] = value; + } + } + } + return value; + }; + return getIntrinsic; +} + +var callBound; +var hasRequiredCallBound; + +function requireCallBound () { + if (hasRequiredCallBound) return callBound; + hasRequiredCallBound = 1; + + var GetIntrinsic = /*@__PURE__*/ requireGetIntrinsic(); + + var callBindBasic = requireCallBindApplyHelpers(); + + /** @type {(thisArg: string, searchString: string, position?: number) => number} */ + var $indexOf = callBindBasic([GetIntrinsic('%String.prototype.indexOf%')]); + + /** @type {import('.')} */ + callBound = function callBoundIntrinsic(name, allowMissing) { + /* eslint no-extra-parens: 0 */ + + var intrinsic = /** @type {(this: unknown, ...args: unknown[]) => unknown} */ (GetIntrinsic(name, !!allowMissing)); + if (typeof intrinsic === 'function' && $indexOf(name, '.prototype.') > -1) { + return callBindBasic(/** @type {const} */ ([intrinsic])); + } + return intrinsic; + }; + return callBound; +} + +var sideChannelMap; +var hasRequiredSideChannelMap; + +function requireSideChannelMap () { + if (hasRequiredSideChannelMap) return sideChannelMap; + hasRequiredSideChannelMap = 1; + + var GetIntrinsic = /*@__PURE__*/ requireGetIntrinsic(); + var callBound = /*@__PURE__*/ requireCallBound(); + var inspect = /*@__PURE__*/ requireObjectInspect(); + + var $TypeError = /*@__PURE__*/ requireType(); + var $Map = GetIntrinsic('%Map%', true); + + /** @type {(thisArg: Map, key: K) => V} */ + var $mapGet = callBound('Map.prototype.get', true); + /** @type {(thisArg: Map, key: K, value: V) => void} */ + var $mapSet = callBound('Map.prototype.set', true); + /** @type {(thisArg: Map, key: K) => boolean} */ + var $mapHas = callBound('Map.prototype.has', true); + /** @type {(thisArg: Map, key: K) => boolean} */ + var $mapDelete = callBound('Map.prototype.delete', true); + /** @type {(thisArg: Map) => number} */ + var $mapSize = callBound('Map.prototype.size', true); + + /** @type {import('.')} */ + sideChannelMap = !!$Map && /** @type {Exclude} */ function getSideChannelMap() { + /** @typedef {ReturnType} Channel */ + /** @typedef {Parameters[0]} K */ + /** @typedef {Parameters[1]} V */ + + /** @type {Map | undefined} */ var $m; + + /** @type {Channel} */ + var channel = { + assert: function (key) { + if (!channel.has(key)) { + throw new $TypeError('Side channel does not contain ' + inspect(key)); + } + }, + 'delete': function (key) { + if ($m) { + var result = $mapDelete($m, key); + if ($mapSize($m) === 0) { + $m = void undefined; + } + return result; + } + return false; + }, + get: function (key) { // eslint-disable-line consistent-return + if ($m) { + return $mapGet($m, key); + } + }, + has: function (key) { + if ($m) { + return $mapHas($m, key); + } + return false; + }, + set: function (key, value) { + if (!$m) { + // @ts-expect-error TS can't handle narrowing a variable inside a closure + $m = new $Map(); + } + $mapSet($m, key, value); + } + }; + + // @ts-expect-error TODO: figure out why TS is erroring here + return channel; + }; + return sideChannelMap; +} + +var sideChannelWeakmap; +var hasRequiredSideChannelWeakmap; + +function requireSideChannelWeakmap () { + if (hasRequiredSideChannelWeakmap) return sideChannelWeakmap; + hasRequiredSideChannelWeakmap = 1; + + var GetIntrinsic = /*@__PURE__*/ requireGetIntrinsic(); + var callBound = /*@__PURE__*/ requireCallBound(); + var inspect = /*@__PURE__*/ requireObjectInspect(); + var getSideChannelMap = requireSideChannelMap(); + + var $TypeError = /*@__PURE__*/ requireType(); + var $WeakMap = GetIntrinsic('%WeakMap%', true); + + /** @type {(thisArg: WeakMap, key: K) => V} */ + var $weakMapGet = callBound('WeakMap.prototype.get', true); + /** @type {(thisArg: WeakMap, key: K, value: V) => void} */ + var $weakMapSet = callBound('WeakMap.prototype.set', true); + /** @type {(thisArg: WeakMap, key: K) => boolean} */ + var $weakMapHas = callBound('WeakMap.prototype.has', true); + /** @type {(thisArg: WeakMap, key: K) => boolean} */ + var $weakMapDelete = callBound('WeakMap.prototype.delete', true); + + /** @type {import('.')} */ + sideChannelWeakmap = $WeakMap + ? /** @type {Exclude} */ function getSideChannelWeakMap() { + /** @typedef {ReturnType} Channel */ + /** @typedef {Parameters[0]} K */ + /** @typedef {Parameters[1]} V */ + + /** @type {WeakMap | undefined} */ var $wm; + /** @type {Channel | undefined} */ var $m; + + /** @type {Channel} */ + var channel = { + assert: function (key) { + if (!channel.has(key)) { + throw new $TypeError('Side channel does not contain ' + inspect(key)); + } + }, + 'delete': function (key) { + if ($WeakMap && key && (typeof key === 'object' || typeof key === 'function')) { + if ($wm) { + return $weakMapDelete($wm, key); + } + } else if (getSideChannelMap) { + if ($m) { + return $m['delete'](key); + } + } + return false; + }, + get: function (key) { + if ($WeakMap && key && (typeof key === 'object' || typeof key === 'function')) { + if ($wm) { + return $weakMapGet($wm, key); + } + } + return $m && $m.get(key); + }, + has: function (key) { + if ($WeakMap && key && (typeof key === 'object' || typeof key === 'function')) { + if ($wm) { + return $weakMapHas($wm, key); + } + } + return !!$m && $m.has(key); + }, + set: function (key, value) { + if ($WeakMap && key && (typeof key === 'object' || typeof key === 'function')) { + if (!$wm) { + $wm = new $WeakMap(); + } + $weakMapSet($wm, key, value); + } else if (getSideChannelMap) { + if (!$m) { + $m = getSideChannelMap(); + } + // eslint-disable-next-line no-extra-parens + /** @type {NonNullable} */ ($m).set(key, value); + } + } + }; + + // @ts-expect-error TODO: figure out why this is erroring + return channel; + } + : getSideChannelMap; + return sideChannelWeakmap; +} + +var sideChannel; +var hasRequiredSideChannel; + +function requireSideChannel () { + if (hasRequiredSideChannel) return sideChannel; + hasRequiredSideChannel = 1; + + var $TypeError = /*@__PURE__*/ requireType(); + var inspect = /*@__PURE__*/ requireObjectInspect(); + var getSideChannelList = requireSideChannelList(); + var getSideChannelMap = requireSideChannelMap(); + var getSideChannelWeakMap = requireSideChannelWeakmap(); + + var makeChannel = getSideChannelWeakMap || getSideChannelMap || getSideChannelList; + + /** @type {import('.')} */ + sideChannel = function getSideChannel() { + /** @typedef {ReturnType} Channel */ + + /** @type {Channel | undefined} */ var $channelData; + + /** @type {Channel} */ + var channel = { + assert: function (key) { + if (!channel.has(key)) { + var keyDesc = key && Object(key) === key + ? 'the given object key' + : inspect(key); + throw new $TypeError('Side channel does not contain ' + keyDesc); + } + }, + 'delete': function (key) { + return !!$channelData && $channelData['delete'](key); + }, + get: function (key) { + return $channelData && $channelData.get(key); + }, + has: function (key) { + return !!$channelData && $channelData.has(key); + }, + set: function (key, value) { + if (!$channelData) { + $channelData = makeChannel(); + } + + $channelData.set(key, value); + } + }; + + return channel; + }; + return sideChannel; +} + +var formats; +var hasRequiredFormats; + +function requireFormats () { + if (hasRequiredFormats) return formats; + hasRequiredFormats = 1; + + var replace = String.prototype.replace; + var percentTwenties = /%20/g; + + var Format = { + RFC1738: 'RFC1738', + RFC3986: 'RFC3986' + }; + + formats = { + 'default': Format.RFC3986, + formatters: { + RFC1738: function (value) { + return replace.call(value, percentTwenties, '+'); + }, + RFC3986: function (value) { + return String(value); + } + }, + RFC1738: Format.RFC1738, + RFC3986: Format.RFC3986 + }; + return formats; +} + +var utils$1; +var hasRequiredUtils$1; + +function requireUtils$1 () { + if (hasRequiredUtils$1) return utils$1; + hasRequiredUtils$1 = 1; + + var formats = /*@__PURE__*/ requireFormats(); + var getSideChannel = requireSideChannel(); + var defineProperty = /*@__PURE__*/ requireEsDefineProperty(); + + var has = Object.prototype.hasOwnProperty; + var isArray = Array.isArray; + + // Track objects created from arrayLimit overflow using side-channel + // Stores the current max numeric index for O(1) lookup + var overflowChannel = getSideChannel(); + + var markOverflow = function markOverflow(obj, maxIndex) { + overflowChannel.set(obj, maxIndex); + return obj; + }; + + var isOverflow = function isOverflow(obj) { + return overflowChannel.has(obj); + }; + + var getMaxIndex = function getMaxIndex(obj) { + return overflowChannel.get(obj); + }; + + var setMaxIndex = function setMaxIndex(obj, maxIndex) { + overflowChannel.set(obj, maxIndex); + }; + + var hexTable = (function () { + var array = []; + for (var i = 0; i < 256; ++i) { + array[array.length] = '%' + ((i < 16 ? '0' : '') + i.toString(16)).toUpperCase(); + } + + return array; + }()); + + var compactQueue = function compactQueue(queue) { + while (queue.length > 1) { + var item = queue.pop(); + var obj = item.obj[item.prop]; + + if (isArray(obj)) { + var compacted = []; + + for (var j = 0; j < obj.length; ++j) { + if (typeof obj[j] !== 'undefined') { + compacted[compacted.length] = obj[j]; + } + } + + item.obj[item.prop] = compacted; + } + } + }; + + var arrayToObject = function arrayToObject(source, options) { + var obj = options && options.plainObjects ? { __proto__: null } : {}; + for (var i = 0; i < source.length; ++i) { + if (typeof source[i] !== 'undefined') { + obj[i] = source[i]; + } + } + + return obj; + }; + + var setProperty = function setProperty(obj, key, value) { + if (key === '__proto__' && defineProperty) { + defineProperty(obj, key, { + configurable: true, + enumerable: true, + value: value, + writable: true + }); + } else { + obj[key] = value; + } + }; + + var merge = function merge(target, source, options) { + /* eslint no-param-reassign: 0 */ + if (!source) { + return target; + } + + if (typeof source !== 'object' && typeof source !== 'function') { + if (isArray(target)) { + var nextIndex = target.length; + if (options && typeof options.arrayLimit === 'number' && nextIndex >= options.arrayLimit) { + if (options.throwOnLimitExceeded) { + throw new RangeError('Array limit exceeded. Only ' + options.arrayLimit + ' element' + (options.arrayLimit === 1 ? '' : 's') + ' allowed in an array.'); + } + return markOverflow(arrayToObject(target.concat(source), options), nextIndex); + } + target[nextIndex] = source; + } else if (target && typeof target === 'object') { + if (isOverflow(target)) { + // Add at next numeric index for overflow objects + var newIndex = getMaxIndex(target) + 1; + target[newIndex] = source; + setMaxIndex(target, newIndex); + } else if (options && options.strictMerge) { + return [target, source]; + } else if ( + (options && (options.plainObjects || options.allowPrototypes)) + || !has.call(Object.prototype, source) + ) { + target[source] = true; + } + } else { + return [target, source]; + } + + return target; + } + + if (!target || typeof target !== 'object') { + if (isOverflow(source)) { + // Create new object with target at 0, source values shifted by 1 + var sourceKeys = Object.keys(source); + var result = options && options.plainObjects + ? { __proto__: null, 0: target } + : { 0: target }; + for (var m = 0; m < sourceKeys.length; m++) { + var oldKey = parseInt(sourceKeys[m], 10); + result[oldKey + 1] = source[sourceKeys[m]]; + } + return markOverflow(result, getMaxIndex(source) + 1); + } + var combined = [target].concat(source); + if (options && typeof options.arrayLimit === 'number' && combined.length > options.arrayLimit) { + if (options.throwOnLimitExceeded) { + throw new RangeError('Array limit exceeded. Only ' + options.arrayLimit + ' element' + (options.arrayLimit === 1 ? '' : 's') + ' allowed in an array.'); + } + return markOverflow(arrayToObject(combined, options), combined.length - 1); + } + return combined; + } + + var mergeTarget = target; + if (isArray(target) && !isArray(source)) { + mergeTarget = arrayToObject(target, options); + } + + if (isArray(target) && isArray(source)) { + source.forEach(function (item, i) { + if (has.call(target, i)) { + var targetItem = target[i]; + if (targetItem && typeof targetItem === 'object' && item && typeof item === 'object') { + target[i] = merge(targetItem, item, options); + } else { + target[target.length] = item; + } + } else { + target[i] = item; + } + }); + if (options && typeof options.arrayLimit === 'number' && target.length > options.arrayLimit) { + if (options.throwOnLimitExceeded) { + throw new RangeError('Array limit exceeded. Only ' + options.arrayLimit + ' element' + (options.arrayLimit === 1 ? '' : 's') + ' allowed in an array.'); + } + return markOverflow(arrayToObject(target, options), target.length - 1); + } + return target; + } + + return Object.keys(source).reduce(function (acc, key) { + var value = source[key]; + + if (has.call(acc, key)) { + setProperty(acc, key, merge(acc[key], value, options)); + } else { + setProperty(acc, key, value); + } + + if (isOverflow(source) && !isOverflow(acc)) { + markOverflow(acc, getMaxIndex(source)); + } + if (isOverflow(acc)) { + var keyNum = parseInt(key, 10); + if (String(keyNum) === key && keyNum >= 0 && keyNum > getMaxIndex(acc)) { + setMaxIndex(acc, keyNum); + } + } + + return acc; + }, mergeTarget); + }; + + var assign = function assignSingleSource(target, source) { + return Object.keys(source).reduce(function (acc, key) { + setProperty(acc, key, source[key]); + return acc; + }, target); + }; + + var decode = function (str, defaultDecoder, charset) { + var strWithoutPlus = str.replace(/\+/g, ' '); + if (charset === 'iso-8859-1') { + // unescape never throws, no try...catch needed: + return strWithoutPlus.replace(/%[0-9a-f]{2}/gi, unescape); + } + // utf-8 + try { + return decodeURIComponent(strWithoutPlus); + } catch (e) { + return strWithoutPlus; + } + }; + + var limit = 1024; + + /* eslint operator-linebreak: [2, "before"] */ + + var encode = function encode(str, defaultEncoder, charset, kind, format) { + // This code was originally written by Brian White (mscdex) for the io.js core querystring library. + // It has been adapted here for stricter adherence to RFC 3986 + if (str.length === 0) { + return str; + } + + var string = str; + if (typeof str === 'symbol') { + string = Symbol.prototype.toString.call(str); + } else if (typeof str !== 'string') { + string = String(str); + } + + if (charset === 'iso-8859-1') { + return escape(string).replace(/%u[0-9a-f]{4}/gi, function ($0) { + return '%26%23' + parseInt($0.slice(2), 16) + '%3B'; + }); + } + + var out = ''; + for (var j = 0; j < string.length; j += limit) { + var segment = string.length >= limit ? string.slice(j, j + limit) : string; + if (j + limit < string.length) { + var last = segment.charCodeAt(segment.length - 1); + if (last >= 0xD800 && last <= 0xDBFF) { + segment = segment.slice(0, -1); + j -= 1; + } + } + var arr = []; + + for (var i = 0; i < segment.length; ++i) { + var c = segment.charCodeAt(i); + if ( + c === 0x2D // - + || c === 0x2E // . + || c === 0x5F // _ + || c === 0x7E // ~ + || (c >= 0x30 && c <= 0x39) // 0-9 + || (c >= 0x41 && c <= 0x5A) // a-z + || (c >= 0x61 && c <= 0x7A) // A-Z + || (format === formats.RFC1738 && (c === 0x28 || c === 0x29)) // ( ) + ) { + arr[arr.length] = segment.charAt(i); + continue; + } + + if (c < 0x80) { + arr[arr.length] = hexTable[c]; + continue; + } + + if (c < 0x800) { + arr[arr.length] = hexTable[0xC0 | (c >> 6)] + + hexTable[0x80 | (c & 0x3F)]; + continue; + } + + if (c < 0xD800 || c >= 0xE000) { + arr[arr.length] = hexTable[0xE0 | (c >> 12)] + + hexTable[0x80 | ((c >> 6) & 0x3F)] + + hexTable[0x80 | (c & 0x3F)]; + continue; + } + + i += 1; + c = 0x10000 + (((c & 0x3FF) << 10) | (segment.charCodeAt(i) & 0x3FF)); + + arr[arr.length] = hexTable[0xF0 | (c >> 18)] + + hexTable[0x80 | ((c >> 12) & 0x3F)] + + hexTable[0x80 | ((c >> 6) & 0x3F)] + + hexTable[0x80 | (c & 0x3F)]; + } + + out += arr.join(''); + } + + return out; + }; + + var compact = function compact(value) { + var queue = [{ obj: { o: value }, prop: 'o' }]; + var refs = getSideChannel(); + + for (var i = 0; i < queue.length; ++i) { + var item = queue[i]; + var obj = item.obj[item.prop]; + + var keys = Object.keys(obj); + for (var j = 0; j < keys.length; ++j) { + var key = keys[j]; + var val = obj[key]; + if (typeof val === 'object' && val !== null && !refs.has(val)) { + queue[queue.length] = { obj: obj, prop: key }; + refs.set(val, true); + } + } + } + + compactQueue(queue); + + return value; + }; + + var isRegExp = function isRegExp(obj) { + return Object.prototype.toString.call(obj) === '[object RegExp]'; + }; + + var isBuffer = function isBuffer(obj) { + if (!obj || typeof obj !== 'object') { + return false; + } + + return !!(obj.constructor && obj.constructor.isBuffer && obj.constructor.isBuffer(obj)); + }; + + var combine = function combine(a, b, arrayLimit, plainObjects, throwOnLimitExceeded) { + // If 'a' is already an overflow object, add to it + if (isOverflow(a)) { + if (throwOnLimitExceeded) { + throw new RangeError('Array limit exceeded. Only ' + arrayLimit + ' element' + (arrayLimit === 1 ? '' : 's') + ' allowed in an array.'); + } + var newIndex = getMaxIndex(a) + 1; + a[newIndex] = b; + setMaxIndex(a, newIndex); + return a; + } + + var result = [].concat(a, b); + if (result.length > arrayLimit) { + if (throwOnLimitExceeded) { + throw new RangeError('Array limit exceeded. Only ' + arrayLimit + ' element' + (arrayLimit === 1 ? '' : 's') + ' allowed in an array.'); + } + return markOverflow(arrayToObject(result, { plainObjects: plainObjects }), result.length - 1); + } + return result; + }; + + var maybeMap = function maybeMap(val, fn) { + if (isArray(val)) { + var mapped = []; + for (var i = 0; i < val.length; i += 1) { + mapped[mapped.length] = fn(val[i]); + } + return mapped; + } + return fn(val); + }; + + utils$1 = { + arrayToObject: arrayToObject, + assign: assign, + combine: combine, + compact: compact, + decode: decode, + encode: encode, + isBuffer: isBuffer, + isOverflow: isOverflow, + isRegExp: isRegExp, + markOverflow: markOverflow, + maybeMap: maybeMap, + merge: merge + }; + return utils$1; +} + +var stringify_1; +var hasRequiredStringify; + +function requireStringify () { + if (hasRequiredStringify) return stringify_1; + hasRequiredStringify = 1; + + var getSideChannel = requireSideChannel(); + var utils = /*@__PURE__*/ requireUtils$1(); + var formats = /*@__PURE__*/ requireFormats(); + var has = Object.prototype.hasOwnProperty; + + var arrayPrefixGenerators = { + brackets: function brackets(prefix) { + return prefix + '[]'; + }, + comma: 'comma', + indices: function indices(prefix, key) { + return prefix + '[' + key + ']'; + }, + repeat: function repeat(prefix) { + return prefix; + } + }; + + var isArray = Array.isArray; + var push = Array.prototype.push; + var pushToArray = function (arr, valueOrArray) { + push.apply(arr, isArray(valueOrArray) ? valueOrArray : [valueOrArray]); + }; + + var toISO = Date.prototype.toISOString; + + var defaultFormat = formats['default']; + var defaults = { + addQueryPrefix: false, + allowDots: false, + allowEmptyArrays: false, + arrayFormat: 'indices', + charset: 'utf-8', + charsetSentinel: false, + commaRoundTrip: false, + delimiter: '&', + encode: true, + encodeDotInKeys: false, + encoder: utils.encode, + encodeValuesOnly: false, + filter: void undefined, + format: defaultFormat, + formatter: formats.formatters[defaultFormat], + // deprecated + indices: false, + serializeDate: function serializeDate(date) { + return toISO.call(date); + }, + skipNulls: false, + strictNullHandling: false + }; + + var isNonNullishPrimitive = function isNonNullishPrimitive(v) { + return typeof v === 'string' + || typeof v === 'number' + || typeof v === 'boolean' + || typeof v === 'symbol' + || typeof v === 'bigint'; + }; + + var sentinel = {}; + + var stringify = function stringify( + object, + prefix, + generateArrayPrefix, + commaRoundTrip, + allowEmptyArrays, + strictNullHandling, + skipNulls, + encodeDotInKeys, + encoder, + filter, + sort, + allowDots, + serializeDate, + format, + formatter, + encodeValuesOnly, + charset, + sideChannel + ) { + var obj = object; + + var tmpSc = sideChannel; + var step = 0; + var findFlag = false; + while ((tmpSc = tmpSc.get(sentinel)) !== void undefined && !findFlag) { + // Where object last appeared in the ref tree + var pos = tmpSc.get(object); + step += 1; + if (typeof pos !== 'undefined') { + if (pos === step) { + throw new RangeError('Cyclic object value'); + } else { + findFlag = true; // Break while + } + } + if (typeof tmpSc.get(sentinel) === 'undefined') { + step = 0; + } + } + + if (typeof filter === 'function') { + obj = filter(prefix, obj); + } else if (obj instanceof Date) { + obj = serializeDate(obj); + } else if (generateArrayPrefix === 'comma' && isArray(obj)) { + obj = utils.maybeMap(obj, function (value) { + if (value instanceof Date) { + return serializeDate(value); + } + return value; + }); + } + + if (obj === null) { + if (strictNullHandling) { + return formatter(encoder && !encodeValuesOnly ? encoder(prefix, defaults.encoder, charset, 'key', format) : prefix); + } + + obj = ''; + } + + if (isNonNullishPrimitive(obj) || utils.isBuffer(obj)) { + if (encoder) { + var keyValue = encodeValuesOnly ? prefix : encoder(prefix, defaults.encoder, charset, 'key', format); + return [formatter(keyValue) + '=' + formatter(encoder(obj, defaults.encoder, charset, 'value', format))]; + } + return [formatter(prefix) + '=' + formatter(String(obj))]; + } + + var values = []; + + if (typeof obj === 'undefined') { + return values; + } + + var objKeys; + if (generateArrayPrefix === 'comma' && isArray(obj)) { + // we need to join elements in + if (encodeValuesOnly && encoder) { + obj = utils.maybeMap(obj, function (v) { + return v == null ? v : encoder(v); + }); + } + objKeys = [{ value: obj.length > 0 ? obj.join(',') || null : void undefined }]; + } else if (isArray(filter)) { + objKeys = filter; + } else { + var keys = Object.keys(obj); + objKeys = sort ? keys.sort(sort) : keys; + } + + var encodedPrefix = encodeDotInKeys ? String(prefix).replace(/\./g, '%2E') : String(prefix); + + var adjustedPrefix = commaRoundTrip && isArray(obj) && obj.length === 1 ? encodedPrefix + '[]' : encodedPrefix; + + if (allowEmptyArrays && isArray(obj) && obj.length === 0) { + return adjustedPrefix + '[]'; + } + + for (var j = 0; j < objKeys.length; ++j) { + var key = objKeys[j]; + var value = typeof key === 'object' && key && typeof key.value !== 'undefined' + ? key.value + : obj[key]; + + if (skipNulls && value === null) { + continue; + } + + var encodedKey = allowDots && encodeDotInKeys ? String(key).replace(/\./g, '%2E') : String(key); + var keyPrefix = isArray(obj) + ? typeof generateArrayPrefix === 'function' ? generateArrayPrefix(adjustedPrefix, encodedKey) : adjustedPrefix + : adjustedPrefix + (allowDots ? '.' + encodedKey : '[' + encodedKey + ']'); + + sideChannel.set(object, step); + var valueSideChannel = getSideChannel(); + valueSideChannel.set(sentinel, sideChannel); + pushToArray(values, stringify( + value, + keyPrefix, + generateArrayPrefix, + commaRoundTrip, + allowEmptyArrays, + strictNullHandling, + skipNulls, + encodeDotInKeys, + generateArrayPrefix === 'comma' && encodeValuesOnly && isArray(obj) ? null : encoder, + filter, + sort, + allowDots, + serializeDate, + format, + formatter, + encodeValuesOnly, + charset, + valueSideChannel + )); + } + + return values; + }; + + var normalizeStringifyOptions = function normalizeStringifyOptions(opts) { + if (!opts) { + return defaults; + } + + if (typeof opts.allowEmptyArrays !== 'undefined' && typeof opts.allowEmptyArrays !== 'boolean') { + throw new TypeError('`allowEmptyArrays` option can only be `true` or `false`, when provided'); + } + + if (typeof opts.encodeDotInKeys !== 'undefined' && typeof opts.encodeDotInKeys !== 'boolean') { + throw new TypeError('`encodeDotInKeys` option can only be `true` or `false`, when provided'); + } + + if (opts.encoder !== null && typeof opts.encoder !== 'undefined' && typeof opts.encoder !== 'function') { + throw new TypeError('Encoder has to be a function.'); + } + + var charset = opts.charset || defaults.charset; + if (typeof opts.charset !== 'undefined' && opts.charset !== 'utf-8' && opts.charset !== 'iso-8859-1') { + throw new TypeError('The charset option must be either utf-8, iso-8859-1, or undefined'); + } + + var format = formats['default']; + if (typeof opts.format !== 'undefined') { + if (!has.call(formats.formatters, opts.format)) { + throw new TypeError('Unknown format option provided.'); + } + format = opts.format; + } + var formatter = formats.formatters[format]; + + var filter = defaults.filter; + if (typeof opts.filter === 'function' || isArray(opts.filter)) { + filter = opts.filter; + } + + var arrayFormat; + if (opts.arrayFormat in arrayPrefixGenerators) { + arrayFormat = opts.arrayFormat; + } else if ('indices' in opts) { + arrayFormat = opts.indices ? 'indices' : 'repeat'; + } else { + arrayFormat = defaults.arrayFormat; + } + + if ('commaRoundTrip' in opts && typeof opts.commaRoundTrip !== 'boolean') { + throw new TypeError('`commaRoundTrip` must be a boolean, or absent'); + } + + var allowDots = typeof opts.allowDots === 'undefined' ? opts.encodeDotInKeys === true ? true : defaults.allowDots : !!opts.allowDots; + + return { + addQueryPrefix: typeof opts.addQueryPrefix === 'boolean' ? opts.addQueryPrefix : defaults.addQueryPrefix, + allowDots: allowDots, + allowEmptyArrays: typeof opts.allowEmptyArrays === 'boolean' ? !!opts.allowEmptyArrays : defaults.allowEmptyArrays, + arrayFormat: arrayFormat, + charset: charset, + charsetSentinel: typeof opts.charsetSentinel === 'boolean' ? opts.charsetSentinel : defaults.charsetSentinel, + commaRoundTrip: !!opts.commaRoundTrip, + delimiter: typeof opts.delimiter === 'undefined' ? defaults.delimiter : opts.delimiter, + encode: typeof opts.encode === 'boolean' ? opts.encode : defaults.encode, + encodeDotInKeys: typeof opts.encodeDotInKeys === 'boolean' ? opts.encodeDotInKeys : defaults.encodeDotInKeys, + encoder: typeof opts.encoder === 'function' ? opts.encoder : defaults.encoder, + encodeValuesOnly: typeof opts.encodeValuesOnly === 'boolean' ? opts.encodeValuesOnly : defaults.encodeValuesOnly, + filter: filter, + format: format, + formatter: formatter, + serializeDate: typeof opts.serializeDate === 'function' ? opts.serializeDate : defaults.serializeDate, + skipNulls: typeof opts.skipNulls === 'boolean' ? opts.skipNulls : defaults.skipNulls, + sort: typeof opts.sort === 'function' ? opts.sort : null, + strictNullHandling: typeof opts.strictNullHandling === 'boolean' ? opts.strictNullHandling : defaults.strictNullHandling + }; + }; + + stringify_1 = function (object, opts) { + var obj = object; + var options = normalizeStringifyOptions(opts); + + var objKeys; + var filter; + + if (typeof options.filter === 'function') { + filter = options.filter; + obj = filter('', obj); + } else if (isArray(options.filter)) { + filter = options.filter; + objKeys = filter; + } + + var keys = []; + + if (typeof obj !== 'object' || obj === null) { + return ''; + } + + var generateArrayPrefix = arrayPrefixGenerators[options.arrayFormat]; + var commaRoundTrip = generateArrayPrefix === 'comma' && options.commaRoundTrip; + + if (!objKeys) { + objKeys = Object.keys(obj); + } + + if (options.sort) { + objKeys.sort(options.sort); + } + + var sideChannel = getSideChannel(); + for (var i = 0; i < objKeys.length; ++i) { + var key = objKeys[i]; + + if (typeof key === 'undefined' || key === null) { + continue; + } + + var value = obj[key]; + + if (options.skipNulls && value === null) { + continue; + } + pushToArray(keys, stringify( + value, + key, + generateArrayPrefix, + commaRoundTrip, + options.allowEmptyArrays, + options.strictNullHandling, + options.skipNulls, + options.encodeDotInKeys, + options.encode ? options.encoder : null, + options.filter, + options.sort, + options.allowDots, + options.serializeDate, + options.format, + options.formatter, + options.encodeValuesOnly, + options.charset, + sideChannel + )); + } + + var joined = keys.join(options.delimiter); + var prefix = options.addQueryPrefix === true ? '?' : ''; + + if (options.charsetSentinel) { + if (options.charset === 'iso-8859-1') { + // encodeURIComponent('✓'), the "numeric entity" representation of a checkmark + prefix += 'utf8=%26%2310003%3B' + options.delimiter; + } else { + // encodeURIComponent('✓') + prefix += 'utf8=%E2%9C%93' + options.delimiter; + } + } + + return joined.length > 0 ? prefix + joined : ''; + }; + return stringify_1; +} + +var parse; +var hasRequiredParse; + +function requireParse () { + if (hasRequiredParse) return parse; + hasRequiredParse = 1; + + var utils = /*@__PURE__*/ requireUtils$1(); + + var has = Object.prototype.hasOwnProperty; + var isArray = Array.isArray; + + var defaults = { + allowDots: false, + allowEmptyArrays: false, + allowPrototypes: false, + allowSparse: false, + arrayLimit: 20, + charset: 'utf-8', + charsetSentinel: false, + comma: false, + decodeDotInKeys: false, + decoder: utils.decode, + delimiter: '&', + depth: 5, + duplicates: 'combine', + ignoreQueryPrefix: false, + interpretNumericEntities: false, + parameterLimit: 1000, + parseArrays: true, + plainObjects: false, + strictDepth: false, + strictMerge: true, + strictNullHandling: false, + throwOnLimitExceeded: false + }; + + var interpretNumericEntities = function (str) { + return str.replace(/&#(\d+);/g, function ($0, numberStr) { + return String.fromCharCode(parseInt(numberStr, 10)); + }); + }; + + var parseArrayValue = function (val, options, currentArrayLength, isFlatArrayValue) { + if (val && typeof val === 'string' && options.comma && val.indexOf(',') > -1) { + if (isFlatArrayValue && options.throwOnLimitExceeded) { + var commaCount = 0; + var commaIndex = val.indexOf(','); + while (commaIndex > -1) { + commaCount += 1; + if (commaCount >= options.arrayLimit) { + throw new RangeError('Array limit exceeded. Only ' + options.arrayLimit + ' element' + (options.arrayLimit === 1 ? '' : 's') + ' allowed in an array.'); + } + commaIndex = val.indexOf(',', commaIndex + 1); + } + } + return val.split(','); + } + + if (options.throwOnLimitExceeded && currentArrayLength >= options.arrayLimit) { + throw new RangeError('Array limit exceeded. Only ' + options.arrayLimit + ' element' + (options.arrayLimit === 1 ? '' : 's') + ' allowed in an array.'); + } + + return val; + }; + + // This is what browsers will submit when the ✓ character occurs in an + // application/x-www-form-urlencoded body and the encoding of the page containing + // the form is iso-8859-1, or when the submitted form has an accept-charset + // attribute of iso-8859-1. Presumably also with other charsets that do not contain + // the ✓ character, such as us-ascii. + var isoSentinel = 'utf8=%26%2310003%3B'; // encodeURIComponent('✓') + + // These are the percent-encoded utf-8 octets representing a checkmark, indicating that the request actually is utf-8 encoded. + var charsetSentinel = 'utf8=%E2%9C%93'; // encodeURIComponent('✓') + + var parseValues = function parseQueryStringValues(str, options) { + var obj = { __proto__: null }; + + var cleanStr = options.ignoreQueryPrefix ? str.replace(/^\?/, '') : str; + cleanStr = cleanStr.replace(/%5B/gi, '[').replace(/%5D/gi, ']'); + + var limit = options.parameterLimit === Infinity ? void undefined : options.parameterLimit; + var parts = cleanStr.split( + options.delimiter, + options.throwOnLimitExceeded && typeof limit !== 'undefined' ? limit + 1 : limit + ); + + if (options.throwOnLimitExceeded && typeof limit !== 'undefined' && parts.length > limit) { + throw new RangeError('Parameter limit exceeded. Only ' + limit + ' parameter' + (limit === 1 ? '' : 's') + ' allowed.'); + } + + var skipIndex = -1; // Keep track of where the utf8 sentinel was found + var i; + + var charset = options.charset; + if (options.charsetSentinel) { + for (i = 0; i < parts.length; ++i) { + if (parts[i].indexOf('utf8=') === 0) { + if (parts[i] === charsetSentinel) { + charset = 'utf-8'; + } else if (parts[i] === isoSentinel) { + charset = 'iso-8859-1'; + } + skipIndex = i; + i = parts.length; // The eslint settings do not allow break; + } + } + } + + for (i = 0; i < parts.length; ++i) { + if (i === skipIndex) { + continue; + } + var part = parts[i]; + + var bracketEqualsPos = part.indexOf(']='); + var pos = bracketEqualsPos === -1 ? part.indexOf('=') : bracketEqualsPos + 1; + + var key; + var val; + if (pos === -1) { + key = options.decoder(part, defaults.decoder, charset, 'key'); + val = options.strictNullHandling ? null : ''; + } else { + key = options.decoder(part.slice(0, pos), defaults.decoder, charset, 'key'); + + if (key !== null) { + val = utils.maybeMap( + parseArrayValue( + part.slice(pos + 1), + options, + isArray(obj[key]) ? obj[key].length : 0, + part.indexOf('[]=') === -1 + ), + function (encodedVal) { + return options.decoder(encodedVal, defaults.decoder, charset, 'value'); + } + ); + } + } + + if (val && options.interpretNumericEntities && charset === 'iso-8859-1') { + val = interpretNumericEntities(String(val)); + } + + if (part.indexOf('[]=') > -1) { + val = isArray(val) ? [val] : val; + } + + if (options.comma && isArray(val) && val.length > options.arrayLimit) { + val = utils.combine([], val, options.arrayLimit, options.plainObjects, options.throwOnLimitExceeded); + } + + if (key !== null) { + var existing = has.call(obj, key); + if (existing && (options.duplicates === 'combine' || part.indexOf('[]=') > -1)) { + obj[key] = utils.combine( + obj[key], + val, + options.arrayLimit, + options.plainObjects, + options.throwOnLimitExceeded + ); + } else if (!existing || options.duplicates === 'last') { + obj[key] = val; + } + } + } + + return obj; + }; + + var parseObject = function (chain, val, options, valuesParsed) { + var currentArrayLength = 0; + if (chain.length > 0 && chain[chain.length - 1] === '[]') { + var parentKey = chain.slice(0, -1).join(''); + currentArrayLength = Array.isArray(val) && val[parentKey] ? val[parentKey].length : 0; + } + + var leaf = valuesParsed ? val : parseArrayValue(val, options, currentArrayLength); + + for (var i = chain.length - 1; i >= 0; --i) { + var obj; + var root = chain[i]; + + if (root === '[]' && options.parseArrays) { + if (utils.isOverflow(leaf)) { + // leaf is already an overflow object, preserve it + obj = leaf; + } else { + obj = options.allowEmptyArrays && (leaf === '' || (options.strictNullHandling && leaf === null)) + ? [] + : utils.combine( + [], + leaf, + options.arrayLimit, + options.plainObjects, + options.throwOnLimitExceeded + ); + } + } else { + obj = options.plainObjects ? { __proto__: null } : {}; + var cleanRoot = root.charAt(0) === '[' && root.charAt(root.length - 1) === ']' ? root.slice(1, -1) : root; + var decodedRoot = options.decodeDotInKeys ? cleanRoot.replace(/%2E/g, '.') : cleanRoot; + var index = parseInt(decodedRoot, 10); + var isValidArrayIndex = !isNaN(index) + && root !== decodedRoot + && String(index) === decodedRoot + && index >= 0 + && options.parseArrays; + if (!options.parseArrays && decodedRoot === '') { + obj = { 0: leaf }; + } else if (isValidArrayIndex && index < options.arrayLimit) { + obj = []; + obj[index] = leaf; + } else if (isValidArrayIndex && options.throwOnLimitExceeded) { + throw new RangeError('Array limit exceeded. Only ' + options.arrayLimit + ' element' + (options.arrayLimit === 1 ? '' : 's') + ' allowed in an array.'); + } else if (isValidArrayIndex) { + obj[index] = leaf; + utils.markOverflow(obj, index); + } else if (decodedRoot !== '__proto__') { + obj[decodedRoot] = leaf; + } + } + + leaf = obj; + } + + return leaf; + }; + + // Split a key like "a[b][c[]]" into ['a', '[b]', '[c[]]'] while preserving + // qs parse semantics for depth/prototype guards. + var splitKeyIntoSegments = function splitKeyIntoSegments(originalKey, options) { + var key = options.allowDots ? originalKey.replace(/\.([^.[]+)/g, '[$1]') : originalKey; + + // depth <= 0 keeps the whole key as one segment + if (options.depth <= 0) { + if (!options.plainObjects && has.call(Object.prototype, key)) { + if (!options.allowPrototypes) { + return; + } + } + + return [key]; + } + + var segments = []; + + // parent before the first '[' (may be empty if key starts with '[') + var first = key.indexOf('['); + var parent = first >= 0 ? key.slice(0, first) : key; + if (parent) { + if (!options.plainObjects && has.call(Object.prototype, parent)) { + if (!options.allowPrototypes) { + return; + } + } + + segments[segments.length] = parent; + } + + var n = key.length; + var open = first; + var collected = 0; + + while (open >= 0 && collected < options.depth) { + var level = 1; + var i = open + 1; + var close = -1; + + // balance nested '[' and ']' inside this bracket group using a nesting level counter + while (i < n && close < 0) { + var cu = key.charCodeAt(i); + if (cu === 0x5B) { // '[' + level += 1; + } else if (cu === 0x5D) { // ']' + level -= 1; + if (level === 0) { + close = i; // found matching close; loop will exit by condition + } + } + i += 1; + } + + if (close < 0) { + // Unterminated group: wrap the raw remainder in one bracket pair so it stays + // a single literal segment (e.g. "[[]b" -> "[[]b]"); we do not infer missing ']'. + segments[segments.length] = '[' + key.slice(open) + ']'; + return segments; + } + + var seg = key.slice(open, close + 1); + // prototype guard for the content of this group + var content = seg.slice(1, -1); + if (!options.plainObjects && has.call(Object.prototype, content) && !options.allowPrototypes) { + return; + } + + segments[segments.length] = seg; + collected += 1; + + // find the next '[' after this balanced group + open = key.indexOf('[', close + 1); + } + + if (open >= 0) { + if (options.strictDepth === true) { + throw new RangeError('Input depth exceeded depth option of ' + options.depth + ' and strictDepth is true'); + } + + segments[segments.length] = '[' + key.slice(open) + ']'; + } + + return segments; + }; + + var parseKeys = function parseQueryStringKeys(givenKey, val, options, valuesParsed) { + if (!givenKey) { + return; + } + + var keys = splitKeyIntoSegments(givenKey, options); + + if (!keys) { + return; + } + + return parseObject(keys, val, options, valuesParsed); + }; + + var normalizeParseOptions = function normalizeParseOptions(opts) { + if (!opts) { + return defaults; + } + + if (typeof opts.allowEmptyArrays !== 'undefined' && typeof opts.allowEmptyArrays !== 'boolean') { + throw new TypeError('`allowEmptyArrays` option can only be `true` or `false`, when provided'); + } + + if (typeof opts.decodeDotInKeys !== 'undefined' && typeof opts.decodeDotInKeys !== 'boolean') { + throw new TypeError('`decodeDotInKeys` option can only be `true` or `false`, when provided'); + } + + if (opts.decoder !== null && typeof opts.decoder !== 'undefined' && typeof opts.decoder !== 'function') { + throw new TypeError('Decoder has to be a function.'); + } + + if (typeof opts.charset !== 'undefined' && opts.charset !== 'utf-8' && opts.charset !== 'iso-8859-1') { + throw new TypeError('The charset option must be either utf-8, iso-8859-1, or undefined'); + } + + if (typeof opts.throwOnLimitExceeded !== 'undefined' && typeof opts.throwOnLimitExceeded !== 'boolean') { + throw new TypeError('`throwOnLimitExceeded` option must be a boolean'); + } + + var charset = typeof opts.charset === 'undefined' ? defaults.charset : opts.charset; + + var duplicates = typeof opts.duplicates === 'undefined' ? defaults.duplicates : opts.duplicates; + + if (duplicates !== 'combine' && duplicates !== 'first' && duplicates !== 'last') { + throw new TypeError('The duplicates option must be either combine, first, or last'); + } + + var allowDots = typeof opts.allowDots === 'undefined' ? opts.decodeDotInKeys === true ? true : defaults.allowDots : !!opts.allowDots; + + return { + allowDots: allowDots, + allowEmptyArrays: typeof opts.allowEmptyArrays === 'boolean' ? !!opts.allowEmptyArrays : defaults.allowEmptyArrays, + allowPrototypes: typeof opts.allowPrototypes === 'boolean' ? opts.allowPrototypes : defaults.allowPrototypes, + allowSparse: typeof opts.allowSparse === 'boolean' ? opts.allowSparse : defaults.allowSparse, + arrayLimit: typeof opts.arrayLimit === 'number' ? opts.arrayLimit : defaults.arrayLimit, + charset: charset, + charsetSentinel: typeof opts.charsetSentinel === 'boolean' ? opts.charsetSentinel : defaults.charsetSentinel, + comma: typeof opts.comma === 'boolean' ? opts.comma : defaults.comma, + decodeDotInKeys: typeof opts.decodeDotInKeys === 'boolean' ? opts.decodeDotInKeys : defaults.decodeDotInKeys, + decoder: typeof opts.decoder === 'function' ? opts.decoder : defaults.decoder, + delimiter: typeof opts.delimiter === 'string' || utils.isRegExp(opts.delimiter) ? opts.delimiter : defaults.delimiter, + // eslint-disable-next-line no-implicit-coercion, no-extra-parens + depth: (typeof opts.depth === 'number' || opts.depth === false) ? +opts.depth : defaults.depth, + duplicates: duplicates, + ignoreQueryPrefix: opts.ignoreQueryPrefix === true, + interpretNumericEntities: typeof opts.interpretNumericEntities === 'boolean' ? opts.interpretNumericEntities : defaults.interpretNumericEntities, + parameterLimit: typeof opts.parameterLimit === 'number' ? opts.parameterLimit : defaults.parameterLimit, + parseArrays: opts.parseArrays !== false, + plainObjects: typeof opts.plainObjects === 'boolean' ? opts.plainObjects : defaults.plainObjects, + strictDepth: typeof opts.strictDepth === 'boolean' ? !!opts.strictDepth : defaults.strictDepth, + strictMerge: typeof opts.strictMerge === 'boolean' ? !!opts.strictMerge : defaults.strictMerge, + strictNullHandling: typeof opts.strictNullHandling === 'boolean' ? opts.strictNullHandling : defaults.strictNullHandling, + throwOnLimitExceeded: typeof opts.throwOnLimitExceeded === 'boolean' ? opts.throwOnLimitExceeded : false + }; + }; + + parse = function (str, opts) { + var options = normalizeParseOptions(opts); + + if (str === '' || str === null || typeof str === 'undefined') { + return options.plainObjects ? { __proto__: null } : {}; + } + + var tempObj = typeof str === 'string' ? parseValues(str, options) : str; + var obj = options.plainObjects ? { __proto__: null } : {}; + + // Iterate over the keys and setup the new object + + var keys = Object.keys(tempObj); + for (var i = 0; i < keys.length; ++i) { + var key = keys[i]; + var newObj = parseKeys(key, tempObj[key], options, typeof str === 'string'); + obj = utils.merge(obj, newObj, options); + } + + if (options.allowSparse === true) { + return obj; + } + + return utils.compact(obj); + }; + return parse; +} + +var lib$3; +var hasRequiredLib$6; + +function requireLib$6 () { + if (hasRequiredLib$6) return lib$3; + hasRequiredLib$6 = 1; + + var stringify = /*@__PURE__*/ requireStringify(); + var parse = /*@__PURE__*/ requireParse(); + var formats = /*@__PURE__*/ requireFormats(); + + lib$3 = { + formats: formats, + parse: parse, + stringify: stringify + }; + return lib$3; +} + +/* + * Copyright Joyent, Inc. and other Node contributors. + * + * Permission is hereby granted, free of charge, to any person obtaining a + * copy of this software and associated documentation files (the + * "Software"), to deal in the Software without restriction, including + * without limitation the rights to use, copy, modify, merge, publish, + * distribute, sublicense, and/or sell copies of the Software, and to permit + * persons to whom the Software is furnished to do so, subject to the + * following conditions: + * + * The above copyright notice and this permission notice shall be included + * in all copies or substantial portions of the Software. + * + * THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS + * OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF + * MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN + * NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, + * DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR + * OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE + * USE OR OTHER DEALINGS IN THE SOFTWARE. + */ + +var hasRequiredUrl; + +function requireUrl () { + if (hasRequiredUrl) return url; + hasRequiredUrl = 1; + + var punycode = requirePunycode(); + + function Url() { + this.protocol = null; + this.slashes = null; + this.auth = null; + this.host = null; + this.port = null; + this.hostname = null; + this.hash = null; + this.search = null; + this.query = null; + this.pathname = null; + this.path = null; + this.href = null; + } + + // Reference: RFC 3986, RFC 1808, RFC 2396 + + /* + * define these here so at least they only have to be + * compiled once on the first module load. + */ + var protocolPattern = /^([a-z0-9.+-]+:)/i, + portPattern = /:[0-9]*$/, + + // Special case for a simple path URL + simplePathPattern = /^(\/\/?(?!\/)[^?\s]*)(\?[^\s]*)?$/, + + /* + * RFC 2396: characters reserved for delimiting URLs. + * We actually just auto-escape these. + */ + delims = [ + '<', '>', '"', '`', ' ', '\r', '\n', '\t' + ], + + // RFC 2396: characters not allowed for various reasons. + unwise = [ + '{', '}', '|', '\\', '^', '`' + ].concat(delims), + + // Allowed by RFCs, but cause of XSS attacks. Always escape these. + autoEscape = ['\''].concat(unwise), + /* + * Characters that are never ever allowed in a hostname. + * Note that any invalid chars are also handled, but these + * are the ones that are *expected* to be seen, so we fast-path + * them. + */ + nonHostChars = [ + '%', '/', '?', ';', '#' + ].concat(autoEscape), + hostEndingChars = [ + '/', '?', '#' + ], + hostnameMaxLen = 255, + hostnamePartPattern = /^[+a-z0-9A-Z_-]{0,63}$/, + hostnamePartStart = /^([+a-z0-9A-Z_-]{0,63})(.*)$/, + // protocols that can allow "unsafe" and "unwise" chars. + unsafeProtocol = { + javascript: true, + 'javascript:': true + }, + // protocols that never have a hostname. + hostlessProtocol = { + javascript: true, + 'javascript:': true + }, + // protocols that always contain a // bit. + slashedProtocol = { + http: true, + https: true, + ftp: true, + gopher: true, + file: true, + 'http:': true, + 'https:': true, + 'ftp:': true, + 'gopher:': true, + 'file:': true + }, + querystring = /*@__PURE__*/ requireLib$6(); + + function urlParse(url, parseQueryString, slashesDenoteHost) { + if (url && typeof url === 'object' && url instanceof Url) { return url; } + + var u = new Url(); + u.parse(url, parseQueryString, slashesDenoteHost); + return u; + } + + Url.prototype.parse = function (url, parseQueryString, slashesDenoteHost) { + if (typeof url !== 'string') { + throw new TypeError("Parameter 'url' must be a string, not " + typeof url); + } + + /* + * Copy chrome, IE, opera backslash-handling behavior. + * Back slashes before the query string get converted to forward slashes + * See: https://code.google.com/p/chromium/issues/detail?id=25916 + */ + var queryIndex = url.indexOf('?'), + splitter = queryIndex !== -1 && queryIndex < url.indexOf('#') ? '?' : '#', + uSplit = url.split(splitter), + slashRegex = /\\/g; + uSplit[0] = uSplit[0].replace(slashRegex, '/'); + url = uSplit.join(splitter); + + var rest = url; + + /* + * trim before proceeding. + * This is to support parse stuff like " http://foo.com \n" + */ + rest = rest.trim(); + + if (!slashesDenoteHost && url.split('#').length === 1) { + // Try fast path regexp + var simplePath = simplePathPattern.exec(rest); + if (simplePath) { + this.path = rest; + this.href = rest; + this.pathname = simplePath[1]; + if (simplePath[2]) { + this.search = simplePath[2]; + if (parseQueryString) { + this.query = querystring.parse(this.search.substr(1)); + } else { + this.query = this.search.substr(1); + } + } else if (parseQueryString) { + this.search = ''; + this.query = {}; + } + return this; + } + } + + var proto = protocolPattern.exec(rest); + if (proto) { + proto = proto[0]; + var lowerProto = proto.toLowerCase(); + this.protocol = lowerProto; + rest = rest.substr(proto.length); + } + + /* + * figure out if it's got a host + * user@server is *always* interpreted as a hostname, and url + * resolution will treat //foo/bar as host=foo,path=bar because that's + * how the browser resolves relative URLs. + */ + if (slashesDenoteHost || proto || rest.match(/^\/\/[^@/]+@[^@/]+/)) { + var slashes = rest.substr(0, 2) === '//'; + if (slashes && !(proto && hostlessProtocol[proto])) { + rest = rest.substr(2); + this.slashes = true; + } + } + + if (!hostlessProtocol[proto] && (slashes || (proto && !slashedProtocol[proto]))) { + + /* + * there's a hostname. + * the first instance of /, ?, ;, or # ends the host. + * + * If there is an @ in the hostname, then non-host chars *are* allowed + * to the left of the last @ sign, unless some host-ending character + * comes *before* the @-sign. + * URLs are obnoxious. + * + * ex: + * http://a@b@c/ => user:a@b host:c + * http://a@b?@c => user:a host:c path:/?@c + */ + + /* + * v0.12 TODO(isaacs): This is not quite how Chrome does things. + * Review our test case against browsers more comprehensively. + */ + + // find the first instance of any hostEndingChars + var hostEnd = -1; + for (var i = 0; i < hostEndingChars.length; i++) { + var hec = rest.indexOf(hostEndingChars[i]); + if (hec !== -1 && (hostEnd === -1 || hec < hostEnd)) { hostEnd = hec; } + } + + /* + * at this point, either we have an explicit point where the + * auth portion cannot go past, or the last @ char is the decider. + */ + var auth, atSign; + if (hostEnd === -1) { + // atSign can be anywhere. + atSign = rest.lastIndexOf('@'); + } else { + /* + * atSign must be in auth portion. + * http://a@b/c@d => host:b auth:a path:/c@d + */ + atSign = rest.lastIndexOf('@', hostEnd); + } + + /* + * Now we have a portion which is definitely the auth. + * Pull that off. + */ + if (atSign !== -1) { + auth = rest.slice(0, atSign); + rest = rest.slice(atSign + 1); + this.auth = decodeURIComponent(auth); + } + + // the host is the remaining to the left of the first non-host char + hostEnd = -1; + for (var i = 0; i < nonHostChars.length; i++) { + var hec = rest.indexOf(nonHostChars[i]); + if (hec !== -1 && (hostEnd === -1 || hec < hostEnd)) { hostEnd = hec; } + } + // if we still have not hit it, then the entire thing is a host. + if (hostEnd === -1) { hostEnd = rest.length; } + + this.host = rest.slice(0, hostEnd); + rest = rest.slice(hostEnd); + + // pull out port. + this.parseHost(); + + /* + * we've indicated that there is a hostname, + * so even if it's empty, it has to be present. + */ + this.hostname = this.hostname || ''; + + /* + * if hostname begins with [ and ends with ] + * assume that it's an IPv6 address. + */ + var ipv6Hostname = this.hostname[0] === '[' && this.hostname[this.hostname.length - 1] === ']'; + + // validate a little. + if (!ipv6Hostname) { + var hostparts = this.hostname.split(/\./); + for (var i = 0, l = hostparts.length; i < l; i++) { + var part = hostparts[i]; + if (!part) { continue; } + if (!part.match(hostnamePartPattern)) { + var newpart = ''; + for (var j = 0, k = part.length; j < k; j++) { + if (part.charCodeAt(j) > 127) { + /* + * we replace non-ASCII char with a temporary placeholder + * we need this to make sure size of hostname is not + * broken by replacing non-ASCII by nothing + */ + newpart += 'x'; + } else { + newpart += part[j]; + } + } + // we test again with ASCII char only + if (!newpart.match(hostnamePartPattern)) { + var validParts = hostparts.slice(0, i); + var notHost = hostparts.slice(i + 1); + var bit = part.match(hostnamePartStart); + if (bit) { + validParts.push(bit[1]); + notHost.unshift(bit[2]); + } + if (notHost.length) { + rest = '/' + notHost.join('.') + rest; + } + this.hostname = validParts.join('.'); + break; + } + } + } + } + + if (this.hostname.length > hostnameMaxLen) { + this.hostname = ''; + } else { + // hostnames are always lower case. + this.hostname = this.hostname.toLowerCase(); + } + + if (!ipv6Hostname) { + /* + * IDNA Support: Returns a punycoded representation of "domain". + * It only converts parts of the domain name that + * have non-ASCII characters, i.e. it doesn't matter if + * you call it with a domain that already is ASCII-only. + */ + this.hostname = punycode.toASCII(this.hostname); + } + + var p = this.port ? ':' + this.port : ''; + var h = this.hostname || ''; + this.host = h + p; + this.href += this.host; + + /* + * strip [ and ] from the hostname + * the host field still retains them, though + */ + if (ipv6Hostname) { + this.hostname = this.hostname.substr(1, this.hostname.length - 2); + if (rest[0] !== '/') { + rest = '/' + rest; + } + } + } + + /* + * now rest is set to the post-host stuff. + * chop off any delim chars. + */ + if (!unsafeProtocol[lowerProto]) { + + /* + * First, make 100% sure that any "autoEscape" chars get + * escaped, even if encodeURIComponent doesn't think they + * need to be. + */ + for (var i = 0, l = autoEscape.length; i < l; i++) { + var ae = autoEscape[i]; + if (rest.indexOf(ae) === -1) { continue; } + var esc = encodeURIComponent(ae); + if (esc === ae) { + esc = escape(ae); + } + rest = rest.split(ae).join(esc); + } + } + + // chop off from the tail first. + var hash = rest.indexOf('#'); + if (hash !== -1) { + // got a fragment string. + this.hash = rest.substr(hash); + rest = rest.slice(0, hash); + } + var qm = rest.indexOf('?'); + if (qm !== -1) { + this.search = rest.substr(qm); + this.query = rest.substr(qm + 1); + if (parseQueryString) { + this.query = querystring.parse(this.query); + } + rest = rest.slice(0, qm); + } else if (parseQueryString) { + // no query string, but parseQueryString still requested + this.search = ''; + this.query = {}; + } + if (rest) { this.pathname = rest; } + if (slashedProtocol[lowerProto] && this.hostname && !this.pathname) { + this.pathname = '/'; + } + + // to support http.request + if (this.pathname || this.search) { + var p = this.pathname || ''; + var s = this.search || ''; + this.path = p + s; + } + + // finally, reconstruct the href based on what has been validated. + this.href = this.format(); + return this; + }; + + // format a parsed object into a url string + function urlFormat(obj) { + /* + * ensure it's an object, and not a string url. + * If it's an obj, this is a no-op. + * this way, you can call url_format() on strings + * to clean up potentially wonky urls. + */ + if (typeof obj === 'string') { obj = urlParse(obj); } + if (!(obj instanceof Url)) { return Url.prototype.format.call(obj); } + return obj.format(); + } + + Url.prototype.format = function () { + var auth = this.auth || ''; + if (auth) { + auth = encodeURIComponent(auth); + auth = auth.replace(/%3A/i, ':'); + auth += '@'; + } + + var protocol = this.protocol || '', + pathname = this.pathname || '', + hash = this.hash || '', + host = false, + query = ''; + + if (this.host) { + host = auth + this.host; + } else if (this.hostname) { + host = auth + (this.hostname.indexOf(':') === -1 ? this.hostname : '[' + this.hostname + ']'); + if (this.port) { + host += ':' + this.port; + } + } + + if (this.query && typeof this.query === 'object' && Object.keys(this.query).length) { + query = querystring.stringify(this.query, { + arrayFormat: 'repeat', + addQueryPrefix: false + }); + } + + var search = this.search || (query && ('?' + query)) || ''; + + if (protocol && protocol.substr(-1) !== ':') { protocol += ':'; } + + /* + * only the slashedProtocols get the //. Not mailto:, xmpp:, etc. + * unless they had them to begin with. + */ + if (this.slashes || (!protocol || slashedProtocol[protocol]) && host !== false) { + host = '//' + (host || ''); + if (pathname && pathname.charAt(0) !== '/') { pathname = '/' + pathname; } + } else if (!host) { + host = ''; + } + + if (hash && hash.charAt(0) !== '#') { hash = '#' + hash; } + if (search && search.charAt(0) !== '?') { search = '?' + search; } + + pathname = pathname.replace(/[?#]/g, function (match) { + return encodeURIComponent(match); + }); + search = search.replace('#', '%23'); + + return protocol + host + pathname + search + hash; + }; + + function urlResolve(source, relative) { + return urlParse(source, false, true).resolve(relative); + } + + Url.prototype.resolve = function (relative) { + return this.resolveObject(urlParse(relative, false, true)).format(); + }; + + function urlResolveObject(source, relative) { + if (!source) { return relative; } + return urlParse(source, false, true).resolveObject(relative); + } + + Url.prototype.resolveObject = function (relative) { + if (typeof relative === 'string') { + var rel = new Url(); + rel.parse(relative, false, true); + relative = rel; + } + + var result = new Url(); + var tkeys = Object.keys(this); + for (var tk = 0; tk < tkeys.length; tk++) { + var tkey = tkeys[tk]; + result[tkey] = this[tkey]; + } + + /* + * hash is always overridden, no matter what. + * even href="" will remove it. + */ + result.hash = relative.hash; + + // if the relative url is empty, then there's nothing left to do here. + if (relative.href === '') { + result.href = result.format(); + return result; + } + + // hrefs like //foo/bar always cut to the protocol. + if (relative.slashes && !relative.protocol) { + // take everything except the protocol from relative + var rkeys = Object.keys(relative); + for (var rk = 0; rk < rkeys.length; rk++) { + var rkey = rkeys[rk]; + if (rkey !== 'protocol') { result[rkey] = relative[rkey]; } + } + + // urlParse appends trailing / to urls like http://www.example.com + if (slashedProtocol[result.protocol] && result.hostname && !result.pathname) { + result.pathname = '/'; + result.path = result.pathname; + } + + result.href = result.format(); + return result; + } + + if (relative.protocol && relative.protocol !== result.protocol) { + /* + * if it's a known url protocol, then changing + * the protocol does weird things + * first, if it's not file:, then we MUST have a host, + * and if there was a path + * to begin with, then we MUST have a path. + * if it is file:, then the host is dropped, + * because that's known to be hostless. + * anything else is assumed to be absolute. + */ + if (!slashedProtocol[relative.protocol]) { + var keys = Object.keys(relative); + for (var v = 0; v < keys.length; v++) { + var k = keys[v]; + result[k] = relative[k]; + } + result.href = result.format(); + return result; + } + + result.protocol = relative.protocol; + if (!relative.host && !hostlessProtocol[relative.protocol]) { + var relPath = (relative.pathname || '').split('/'); + while (relPath.length && !(relative.host = relPath.shift())) { } + if (!relative.host) { relative.host = ''; } + if (!relative.hostname) { relative.hostname = ''; } + if (relPath[0] !== '') { relPath.unshift(''); } + if (relPath.length < 2) { relPath.unshift(''); } + result.pathname = relPath.join('/'); + } else { + result.pathname = relative.pathname; + } + result.search = relative.search; + result.query = relative.query; + result.host = relative.host || ''; + result.auth = relative.auth; + result.hostname = relative.hostname || relative.host; + result.port = relative.port; + // to support http.request + if (result.pathname || result.search) { + var p = result.pathname || ''; + var s = result.search || ''; + result.path = p + s; + } + result.slashes = result.slashes || relative.slashes; + result.href = result.format(); + return result; + } + + var isSourceAbs = result.pathname && result.pathname.charAt(0) === '/', + isRelAbs = relative.host || relative.pathname && relative.pathname.charAt(0) === '/', + mustEndAbs = isRelAbs || isSourceAbs || (result.host && relative.pathname), + removeAllDots = mustEndAbs, + srcPath = result.pathname && result.pathname.split('/') || [], + relPath = relative.pathname && relative.pathname.split('/') || [], + psychotic = result.protocol && !slashedProtocol[result.protocol]; + + /* + * if the url is a non-slashed url, then relative + * links like ../.. should be able + * to crawl up to the hostname, as well. This is strange. + * result.protocol has already been set by now. + * Later on, put the first path part into the host field. + */ + if (psychotic) { + result.hostname = ''; + result.port = null; + if (result.host) { + if (srcPath[0] === '') { srcPath[0] = result.host; } else { srcPath.unshift(result.host); } + } + result.host = ''; + if (relative.protocol) { + relative.hostname = null; + relative.port = null; + if (relative.host) { + if (relPath[0] === '') { relPath[0] = relative.host; } else { relPath.unshift(relative.host); } + } + relative.host = null; + } + mustEndAbs = mustEndAbs && (relPath[0] === '' || srcPath[0] === ''); + } + + if (isRelAbs) { + // it's absolute. + result.host = relative.host || relative.host === '' ? relative.host : result.host; + result.hostname = relative.hostname || relative.hostname === '' ? relative.hostname : result.hostname; + result.search = relative.search; + result.query = relative.query; + srcPath = relPath; + // fall through to the dot-handling below. + } else if (relPath.length) { + /* + * it's relative + * throw away the existing file, and take the new path instead. + */ + if (!srcPath) { srcPath = []; } + srcPath.pop(); + srcPath = srcPath.concat(relPath); + result.search = relative.search; + result.query = relative.query; + } else if (relative.search != null) { + /* + * just pull out the search. + * like href='?foo'. + * Put this after the other two cases because it simplifies the booleans + */ + if (psychotic) { + result.host = srcPath.shift(); + result.hostname = result.host; + /* + * occationaly the auth can get stuck only in host + * this especially happens in cases like + * url.resolveObject('mailto:local1@domain1', 'local2@domain2') + */ + var authInHost = result.host && result.host.indexOf('@') > 0 ? result.host.split('@') : false; + if (authInHost) { + result.auth = authInHost.shift(); + result.hostname = authInHost.shift(); + result.host = result.hostname; + } + } + result.search = relative.search; + result.query = relative.query; + // to support http.request + if (result.pathname !== null || result.search !== null) { + result.path = (result.pathname ? result.pathname : '') + (result.search ? result.search : ''); + } + result.href = result.format(); + return result; + } + + if (!srcPath.length) { + /* + * no path at all. easy. + * we've already handled the other stuff above. + */ + result.pathname = null; + // to support http.request + if (result.search) { + result.path = '/' + result.search; + } else { + result.path = null; + } + result.href = result.format(); + return result; + } + + /* + * if a url ENDs in . or .., then it must get a trailing slash. + * however, if it ends in anything else non-slashy, + * then it must NOT get a trailing slash. + */ + var last = srcPath.slice(-1)[0]; + var hasTrailingSlash = (result.host || relative.host || srcPath.length > 1) && (last === '.' || last === '..') || last === ''; + + /* + * strip single dots, resolve double dots to parent dir + * if the path tries to go above the root, `up` ends up > 0 + */ + var up = 0; + for (var i = srcPath.length; i >= 0; i--) { + last = srcPath[i]; + if (last === '.') { + srcPath.splice(i, 1); + } else if (last === '..') { + srcPath.splice(i, 1); + up++; + } else if (up) { + srcPath.splice(i, 1); + up--; + } + } + + // if the path is allowed to go above the root, restore leading ..s + if (!mustEndAbs && !removeAllDots) { + for (; up--; up) { + srcPath.unshift('..'); + } + } + + if (mustEndAbs && srcPath[0] !== '' && (!srcPath[0] || srcPath[0].charAt(0) !== '/')) { + srcPath.unshift(''); + } + + if (hasTrailingSlash && (srcPath.join('/').substr(-1) !== '/')) { + srcPath.push(''); + } + + var isAbsolute = srcPath[0] === '' || (srcPath[0] && srcPath[0].charAt(0) === '/'); + + // put the host back + if (psychotic) { + result.hostname = isAbsolute ? '' : srcPath.length ? srcPath.shift() : ''; + result.host = result.hostname; + /* + * occationaly the auth can get stuck only in host + * this especially happens in cases like + * url.resolveObject('mailto:local1@domain1', 'local2@domain2') + */ + var authInHost = result.host && result.host.indexOf('@') > 0 ? result.host.split('@') : false; + if (authInHost) { + result.auth = authInHost.shift(); + result.hostname = authInHost.shift(); + result.host = result.hostname; + } + } + + mustEndAbs = mustEndAbs || (result.host && srcPath.length); + + if (mustEndAbs && !isAbsolute) { + srcPath.unshift(''); + } + + if (srcPath.length > 0) { + result.pathname = srcPath.join('/'); + } else { + result.pathname = null; + result.path = null; + } + + // to support request.http + if (result.pathname !== null || result.search !== null) { + result.path = (result.pathname ? result.pathname : '') + (result.search ? result.search : ''); + } + result.auth = relative.auth || result.auth; + result.slashes = result.slashes || relative.slashes; + result.href = result.format(); + return result; + }; + + Url.prototype.parseHost = function () { + var host = this.host; + var port = portPattern.exec(host); + if (port) { + port = port[0]; + if (port !== ':') { + this.port = port.substr(1); + } + host = host.substr(0, host.length - port.length); + } + if (host) { this.hostname = host; } + }; + + url.parse = urlParse; + url.resolve = urlResolve; + url.resolveObject = urlResolveObject; + url.format = urlFormat; + + url.Url = Url; + return url; +} + +var hasRequiredUtil$3; + +function requireUtil$3 () { + if (hasRequiredUtil$3) return util$3; + hasRequiredUtil$3 = 1; + (function (exports) { + Object.defineProperty(exports, "__esModule", { value: true }); + exports.filenameToSteps = exports.resolve = exports.unixify = exports.isWin = void 0; + exports.isFd = isFd; + exports.validateFd = validateFd; + exports.dataToBuffer = dataToBuffer; + exports.nullCheck = nullCheck; + exports.pathToFilename = pathToFilename; + exports.createError = createError; + exports.createStatError = createStatError; + const path_1 = requirePath$1(); + const buffer_1 = requireBuffer(); + const errors = requireErrors$1(); + const process_1 = requireProcess(); + const encoding_1 = requireEncoding(); + const fs_node_utils_1 = requireLib$7(); + exports.isWin = process_1.default.platform === 'win32'; + const resolveCrossPlatform = path_1.resolve; + const pathSep = path_1.posix ? path_1.posix.sep : path_1.sep; + const isSeparator = (str, i) => { + let char = str[i]; + return i > 0 && (char === '/' || (exports.isWin && char === '\\')); + }; + const removeTrailingSeparator = (str) => { + let i = str.length - 1; + if (i < 2) + return str; + while (isSeparator(str, i)) + i--; + return str.substr(0, i + 1); + }; + const normalizePath = (str, stripTrailing) => { + if (typeof str !== 'string') + throw new TypeError('expected a string'); + str = str.replace(/[\\\/]+/g, '/'); + if (stripTrailing !== false) + str = removeTrailingSeparator(str); + return str; + }; + const unixify = (filepath, stripTrailing = true) => { + if (exports.isWin) { + filepath = normalizePath(filepath, stripTrailing); + return filepath.replace(/^([a-zA-Z]+:|\.\/)/, ''); + } + return filepath; + }; + exports.unixify = unixify; + let resolve = (filename, base = process_1.default.cwd()) => resolveCrossPlatform(base, filename); + exports.resolve = resolve; + if (exports.isWin) { + const _resolve = resolve; + exports.resolve = resolve = (filename, base) => (0, exports.unixify)(_resolve(filename, base)); + } + const filenameToSteps = (filename, base) => { + const fullPath = resolve(filename, base); + const fullPathSansSlash = fullPath.substring(1); + if (!fullPathSansSlash) + return []; + return fullPathSansSlash.split(pathSep); + }; + exports.filenameToSteps = filenameToSteps; + function isFd(path) { + return path >>> 0 === path; + } + function validateFd(fd) { + if (!isFd(fd)) + throw TypeError(fs_node_utils_1.ERRSTR.FD); + } + function dataToBuffer(data, encoding = encoding_1.ENCODING_UTF8) { + if (buffer_1.Buffer.isBuffer(data)) + return data; + else if (data instanceof Uint8Array) + return (0, buffer_1.bufferFrom)(data); + else if (encoding === 'buffer') + return (0, buffer_1.bufferFrom)(String(data), 'utf8'); + else + return (0, buffer_1.bufferFrom)(String(data), encoding); + } + function nullCheck(path, callback) { + if (('' + path).indexOf('\u0000') !== -1) { + const er = new Error('Path must be a string without null bytes'); + er.code = 'ENOENT'; + if (typeof callback !== 'function') + throw er; + Promise.resolve().then(() => callback(er)); + return false; + } + return true; + } + function getPathFromURLPosix(url) { + if (url.hostname !== '') { + throw new errors.TypeError('ERR_INVALID_FILE_URL_HOST', process_1.default.platform); + } + const pathname = url.pathname; + for (let n = 0; n < pathname.length; n++) { + if (pathname[n] === '%') { + const third = pathname.codePointAt(n + 2) | 0x20; + if (pathname[n + 1] === '2' && third === 102) { + throw new errors.TypeError('ERR_INVALID_FILE_URL_PATH', 'must not include encoded / characters'); + } + } + } + return decodeURIComponent(pathname); + } + function pathToFilename(path) { + if (path instanceof Uint8Array) { + path = (0, buffer_1.bufferFrom)(path); + } + if (typeof path !== 'string' && !buffer_1.Buffer.isBuffer(path)) { + try { + if (!(path instanceof requireUrl().URL)) + throw new TypeError(fs_node_utils_1.ERRSTR.PATH_STR); + } + catch (err) { + throw new TypeError(fs_node_utils_1.ERRSTR.PATH_STR); + } + path = getPathFromURLPosix(path); + } + const pathString = String(path); + nullCheck(pathString); + return pathString; + } + const ENOENT = 'ENOENT'; + const EBADF = 'EBADF'; + const EINVAL = 'EINVAL'; + const EPERM = 'EPERM'; + const EPROTO = 'EPROTO'; + const EEXIST = 'EEXIST'; + const ENOTDIR = 'ENOTDIR'; + const EMFILE = 'EMFILE'; + const EACCES = 'EACCES'; + const EISDIR = 'EISDIR'; + const ENOTEMPTY = 'ENOTEMPTY'; + const ENOSYS = 'ENOSYS'; + const ERR_FS_EISDIR = 'ERR_FS_EISDIR'; + const ERR_OUT_OF_RANGE = 'ERR_OUT_OF_RANGE'; + function formatError(errorCode, func = '', path = '', path2 = '') { + let pathFormatted = ''; + if (path) + pathFormatted = ` '${path}'`; + if (path2) + pathFormatted += ` -> '${path2}'`; + switch (errorCode) { + case ENOENT: + return `ENOENT: no such file or directory, ${func}${pathFormatted}`; + case EBADF: + return `EBADF: bad file descriptor, ${func}${pathFormatted}`; + case EINVAL: + return `EINVAL: invalid argument, ${func}${pathFormatted}`; + case EPERM: + return `EPERM: operation not permitted, ${func}${pathFormatted}`; + case EPROTO: + return `EPROTO: protocol error, ${func}${pathFormatted}`; + case EEXIST: + return `EEXIST: file already exists, ${func}${pathFormatted}`; + case ENOTDIR: + return `ENOTDIR: not a directory, ${func}${pathFormatted}`; + case EISDIR: + return `EISDIR: illegal operation on a directory, ${func}${pathFormatted}`; + case EACCES: + return `EACCES: permission denied, ${func}${pathFormatted}`; + case ENOTEMPTY: + return `ENOTEMPTY: directory not empty, ${func}${pathFormatted}`; + case EMFILE: + return `EMFILE: too many open files, ${func}${pathFormatted}`; + case ENOSYS: + return `ENOSYS: function not implemented, ${func}${pathFormatted}`; + case ERR_FS_EISDIR: + return `[ERR_FS_EISDIR]: Path is a directory: ${func} returned EISDIR (is a directory) ${path}`; + case ERR_OUT_OF_RANGE: + return `[ERR_OUT_OF_RANGE]: value out of range, ${func}${pathFormatted}`; + default: + return `${errorCode}: error occurred, ${func}${pathFormatted}`; + } + } + function createError(errorCode, func = '', path = '', path2 = '', Constructor = Error) { + const error = new Constructor(formatError(errorCode, func, path, path2)); + error.code = errorCode; + if (path) { + error.path = path; + } + return error; + } + function createStatError(errorCode, func = '', path = '', path2 = '') { + return { + code: errorCode, + message: formatError(errorCode, func, path, path2), + path, + toError() { + const error = new Error(this.message); + error.code = this.code; + if (this.path) { + error.path = this.path; + } + return error; + }, + }; + } + + } (util$3)); + return util$3; +} + +var FsEvent = {}; + +var hasRequiredFsEvent; + +function requireFsEvent () { + if (hasRequiredFsEvent) return FsEvent; + hasRequiredFsEvent = 1; + Object.defineProperty(FsEvent, "__esModule", { value: true }); + FsEvent.FsEvent = void 0; + let FsEvent$1 = class FsEvent { + constructor(type, steps, node, link, oldSteps = void 0) { + this.type = type; + this.steps = steps; + this.node = node; + this.link = link; + this.oldSteps = oldSteps; + } + }; + FsEvent.FsEvent = FsEvent$1; + + return FsEvent; +} + +var hasRequiredSuperblock; + +function requireSuperblock () { + if (hasRequiredSuperblock) return Superblock; + hasRequiredSuperblock = 1; + Object.defineProperty(Superblock, "__esModule", { value: true }); + Superblock.Superblock = void 0; + const path_1 = requirePath$1(); + const Node_1 = requireNode(); + const Link_1 = requireLink(); + const File_1 = requireFile(); + const buffer_1 = requireBuffer(); + const process_1 = requireProcess(); + const fs_node_utils_1 = requireLib$7(); + const fs_node_utils_2 = requireLib$7(); + const util_1 = requireUtil$3(); + const json_1 = requireJson$1(); + const result_1 = requireResult(); + const fanout_1 = requireFanout(); + const FsEvent_1 = requireFsEvent(); + const pathSep = path_1.posix ? path_1.posix.sep : path_1.sep; + const pathRelative = path_1.posix ? path_1.posix.relative : path_1.relative; + const pathJoin = path_1.posix ? path_1.posix.join : path_1.join; + const { O_RDONLY, O_WRONLY, O_RDWR, O_CREAT, O_EXCL, O_TRUNC, O_APPEND, O_DIRECTORY } = fs_node_utils_1.constants; + /** + * Represents a filesystem superblock, which is the root of a virtual + * filesystem in Linux. + * @see https://lxr.linux.no/linux+v3.11.2/include/linux/fs.h#L1242 + */ + let Superblock$1 = class Superblock { + static fromJSON(json, cwd, opts) { + const vol = new Superblock(opts); + vol.fromJSON(json, cwd); + return vol; + } + static fromNestedJSON(json, cwd, opts) { + const vol = new Superblock(opts); + vol.fromNestedJSON(json, cwd); + return vol; + } + constructor(opts = {}) { + // I-node number counter. + this.ino = 0; + // A mapping for i-node numbers to i-nodes (`Node`); + this.inodes = {}; + // List of released i-node numbers, for reuse. + this.releasedInos = []; + // A mapping for file descriptors to `File`s. + this.fds = {}; + // A list of reusable (opened and closed) file descriptors, that should be + // used first before creating a new file descriptor. + this.releasedFds = []; + // Max number of open files. + this.maxFiles = 10000; + // Current number of open files. + this.openFiles = 0; + /** Fan-out of file system change events. Multiple consumers may subscribe. */ + this.changes = new fanout_1.FanOut(); + this.open = (filename, flagsNum, modeNum, resolveSymlinks = true) => { + const file = this.openFile(filename, flagsNum, modeNum, resolveSymlinks); + if (!file) + throw (0, util_1.createError)("ENOENT" /* ERROR_CODE.ENOENT */, 'open', filename); + return file.fd; + }; + this.writeFile = (id, buf, flagsNum, modeNum) => { + const isUserFd = typeof id === 'number'; + let fd; + if (isUserFd) + fd = id; + else + fd = this.open((0, util_1.pathToFilename)(id), flagsNum, modeNum); + let offset = 0; + let length = buf.length; + let position = flagsNum & O_APPEND ? undefined : 0; + try { + while (length > 0) { + const written = this.write(fd, buf, offset, length, position); + offset += written; + length -= written; + if (position !== undefined) + position += written; + } + } + finally { + if (!isUserFd) + this.close(fd); + } + }; + this.read = (fd, buffer, offset, length, position) => { + if (buffer.byteLength < length) { + throw (0, util_1.createError)("ERR_OUT_OF_RANGE" /* ERROR_CODE.ERR_OUT_OF_RANGE */, 'read', undefined, undefined, RangeError); + } + const file = this.getFileByFdOrThrow(fd); + if (file.node.isSymlink()) { + throw (0, util_1.createError)("EPERM" /* ERROR_CODE.EPERM */, 'read', file.link.getPath()); + } + return file.read(buffer, Number(offset), Number(length), position === -1 || typeof position !== 'number' ? undefined : position); + }; + this.readv = (fd, buffers, position) => { + const file = this.getFileByFdOrThrow(fd); + let p = position ?? undefined; + if (p === -1) + p = undefined; + let bytesRead = 0; + for (const buffer of buffers) { + const bytes = file.read(buffer, 0, buffer.byteLength, p); + p = undefined; + bytesRead += bytes; + if (bytes < buffer.byteLength) + break; + } + return bytesRead; + }; + this.link = (filename1, filename2) => { + let link1; + try { + link1 = this.getLinkOrThrow(filename1, 'link'); + } + catch (err) { + if (err.code) + err = (0, util_1.createError)(err.code, 'link', filename1, filename2); + throw err; + } + const dirname2 = (0, path_1.dirname)(filename2); + let dir2; + try { + dir2 = this.getLinkOrThrow(dirname2, 'link'); + } + catch (err) { + // Augment error with filename1 + if (err.code) + err = (0, util_1.createError)(err.code, 'link', filename1, filename2); + throw err; + } + const name = (0, path_1.basename)(filename2); + if (dir2.getChild(name)) + throw (0, util_1.createError)("EEXIST" /* ERROR_CODE.EEXIST */, 'link', filename1, filename2); + const node = link1.getNode(); + node.nlink++; + const newLink = dir2.createChild(name, node); + this.emit(new FsEvent_1.FsEvent(0 /* FsEventType.CREATE */, newLink.steps, node, newLink)); + }; + this.unlink = (filename) => { + const link = this.getLinkOrThrow(filename, 'unlink'); + // TODO: Check if it is file, dir, other... + if (link.length) + throw Error('Dir not empty...'); + this._emitDeleteRecursive(link); + this.deleteLink(link); + const node = link.getNode(); + node.nlink--; + // When all hard links to i-node are deleted, remove the i-node, too. + if (node.nlink <= 0) { + this.deleteNode(node); + } + }; + this.symlink = (targetFilename, pathFilename) => { + const pathSteps = (0, util_1.filenameToSteps)(pathFilename); + // Check if directory exists, where we about to create a symlink. + let dirLink; + try { + dirLink = this.getLinkParentAsDirOrThrow(pathSteps); + } + catch (err) { + // Catch error to populate with the correct fields - getLinkParentAsDirOrThrow won't be aware of the second path + if (err.code) + err = (0, util_1.createError)(err.code, 'symlink', targetFilename, pathFilename); + throw err; + } + const name = pathSteps[pathSteps.length - 1]; + // Check if new file already exists. + if (dirLink.getChild(name)) + throw (0, util_1.createError)("EEXIST" /* ERROR_CODE.EEXIST */, 'symlink', targetFilename, pathFilename); + // Check permissions on the path where we are creating the symlink. + // Note we're not checking permissions on the target path: It is not an error to create a symlink to a + // non-existent or inaccessible target + const node = dirLink.getNode(); + if (!node.canExecute() || !node.canWrite()) + throw (0, util_1.createError)("EACCES" /* ERROR_CODE.EACCES */, 'symlink', targetFilename, pathFilename); + // Create symlink. + const symlink = dirLink.createChild(name); + symlink.getNode().makeSymlink(targetFilename); + this.emit(new FsEvent_1.FsEvent(0 /* FsEventType.CREATE */, symlink.steps, symlink.getNode(), symlink)); + return symlink; + }; + this.rename = (oldPathFilename, newPathFilename) => { + let link; + try { + link = this.getResolvedLinkOrThrow(oldPathFilename); + } + catch (err) { + // Augment err with newPathFilename + if (err.code) + err = (0, util_1.createError)(err.code, 'rename', oldPathFilename, newPathFilename); + throw err; + } + // TODO: Check if it is directory, if non-empty, we cannot move it, right? + // Check directory exists for the new location. + let newPathDirLink; + try { + newPathDirLink = this.getLinkParentAsDirOrThrow(newPathFilename); + } + catch (err) { + // Augment error with oldPathFilename + if (err.code) + err = (0, util_1.createError)(err.code, 'rename', oldPathFilename, newPathFilename); + throw err; + } + // TODO: Also treat cases with directories and symbolic links. + // TODO: See: http://man7.org/linux/man-pages/man2/rename.2.html + // Remove hard link from old folder. + const oldLinkParent = link.parent; + if (!oldLinkParent) + throw (0, util_1.createError)("EINVAL" /* ERROR_CODE.EINVAL */, 'rename', oldPathFilename, newPathFilename); + // Check we have access and write permissions in both places + const oldParentNode = oldLinkParent.getNode(); + const newPathDirNode = newPathDirLink.getNode(); + if (!oldParentNode.canExecute() || + !oldParentNode.canWrite() || + !newPathDirNode.canExecute() || + !newPathDirNode.canWrite()) { + throw (0, util_1.createError)("EACCES" /* ERROR_CODE.EACCES */, 'rename', oldPathFilename, newPathFilename); + } + oldLinkParent.deleteChild(link); + // Rename should overwrite the new path, if that exists. + const name = (0, path_1.basename)(newPathFilename); + const oldSteps = link.steps; + link.name = name; + link.steps = [...newPathDirLink.steps, name]; + newPathDirLink.setChild(link.getName(), link); + this.emit(new FsEvent_1.FsEvent(4 /* FsEventType.MOVE */, link.steps, link.getNode(), link, oldSteps)); + }; + this.mkdir = (filename, modeNum) => { + const steps = (0, util_1.filenameToSteps)(filename); + // This will throw if user tries to create root dir `fs.mkdirSync('/')`. + if (!steps.length) + throw (0, util_1.createError)("EEXIST" /* ERROR_CODE.EEXIST */, 'mkdir', filename); + const dir = this.getLinkParentAsDirOrThrow(filename, 'mkdir'); + // Check path already exists. + const name = steps[steps.length - 1]; + if (dir.getChild(name)) + throw (0, util_1.createError)("EEXIST" /* ERROR_CODE.EEXIST */, 'mkdir', filename); + const node = dir.getNode(); + if (!node.canWrite() || !node.canExecute()) + throw (0, util_1.createError)("EACCES" /* ERROR_CODE.EACCES */, 'mkdir', filename); + const child = dir.createChild(name, this.createNode(fs_node_utils_1.constants.S_IFDIR | modeNum)); + this.emit(new FsEvent_1.FsEvent(0 /* FsEventType.CREATE */, child.steps, child.getNode(), child)); + }; + /** + * Creates directory tree recursively. + */ + this.mkdirp = (filename, modeNum) => { + let created = false; + const steps = (0, util_1.filenameToSteps)(filename); + let curr = null; + let i = steps.length; + // Find the longest subpath of filename that still exists: + for (i = steps.length; i >= 0; i--) { + curr = this.getResolvedLink(steps.slice(0, i)); + if (curr) + break; + } + if (!curr) { + curr = this.root; + i = 0; + } + // curr is now the last directory that still exists. + // (If none of them existed, curr is the root.) + // Check access the lazy way: + curr = this.getResolvedLinkOrThrow(path_1.sep + steps.slice(0, i).join(path_1.sep), 'mkdir'); + // Start creating directories: + for (i; i < steps.length; i++) { + const node = curr.getNode(); + if (node.isDirectory()) { + // Check we have permissions + if (!node.canExecute() || !node.canWrite()) + throw (0, util_1.createError)("EACCES" /* ERROR_CODE.EACCES */, 'mkdir', filename); + } + else { + throw (0, util_1.createError)("ENOTDIR" /* ERROR_CODE.ENOTDIR */, 'mkdir', filename); + } + created = true; + curr = curr.createChild(steps[i], this.createNode(fs_node_utils_1.constants.S_IFDIR | modeNum)); + this.emit(new FsEvent_1.FsEvent(0 /* FsEventType.CREATE */, curr.steps, curr.getNode(), curr)); + } + return created ? filename : undefined; + }; + this.rmdir = (filename, recursive = false) => { + const link = this.getLinkAsDirOrThrow(filename, 'rmdir'); + if (link.length && !recursive) + throw (0, util_1.createError)("ENOTEMPTY" /* ERROR_CODE.ENOTEMPTY */, 'rmdir', filename); + this._emitDeleteRecursive(link); + this.deleteLink(link); + }; + this.rm = (filename, force = false, recursive = false) => { + // "stat" is used to match Node's native error message. + let link; + try { + link = this.getResolvedLinkOrThrow(filename, 'stat'); + } + catch (err) { + // Silently ignore missing paths if force option is true + if (err.code === "ENOENT" /* ERROR_CODE.ENOENT */ && force) + return; + else + throw err; + } + if (link.getNode().isDirectory() && !recursive) + throw (0, util_1.createError)("ERR_FS_EISDIR" /* ERROR_CODE.ERR_FS_EISDIR */, 'rm', filename); + if (!link.parent?.getNode().canWrite()) + throw (0, util_1.createError)("EACCES" /* ERROR_CODE.EACCES */, 'rm', filename); + this._emitDeleteRecursive(link); + this.deleteLink(link); + }; + this.close = (fd) => { + (0, util_1.validateFd)(fd); + const file = this.getFileByFdOrThrow(fd, 'close'); + this.closeFile(file); + }; + this.ftruncate = (fd, len) => { + const file = this.getFileByFdOrThrow(fd, 'ftruncate'); + file.truncate(len); + this.emit(new FsEvent_1.FsEvent(2 /* FsEventType.MODIFY */, file.link.steps, file.node, file.link)); + }; + this.fchmod = (fd, modeNum) => { + const file = this.getFileByFdOrThrow(fd, 'fchmod'); + file.chmod(modeNum); + this.emit(new FsEvent_1.FsEvent(3 /* FsEventType.ATTRIB */, file.link.steps, file.node, file.link)); + }; + this.chmod = (filename, modeNum) => { + const link = this.getResolvedLinkOrThrow(filename, 'chmod'); + link.getNode().chmod(modeNum); + this.emit(new FsEvent_1.FsEvent(3 /* FsEventType.ATTRIB */, link.steps, link.getNode(), link)); + }; + this.lchmod = (filename, modeNum) => { + const link = this.getLinkOrThrow(filename, 'lchmod'); + link.getNode().chmod(modeNum); + this.emit(new FsEvent_1.FsEvent(3 /* FsEventType.ATTRIB */, link.steps, link.getNode(), link)); + }; + this.fchown = (fd, uid, gid) => { + const file = this.getFileByFdOrThrow(fd, 'fchown'); + file.chown(uid, gid); + this.emit(new FsEvent_1.FsEvent(3 /* FsEventType.ATTRIB */, file.link.steps, file.node, file.link)); + }; + this.chown = (filename, uid, gid) => { + const link = this.getResolvedLinkOrThrow(filename, 'chown'); + link.getNode().chown(uid, gid); + this.emit(new FsEvent_1.FsEvent(3 /* FsEventType.ATTRIB */, link.steps, link.getNode(), link)); + }; + this.lchown = (filename, uid, gid) => { + const link = this.getLinkOrThrow(filename, 'lchown'); + link.getNode().chown(uid, gid); + this.emit(new FsEvent_1.FsEvent(3 /* FsEventType.ATTRIB */, link.steps, link.getNode(), link)); + }; + this.futimes = (fd, atime, mtime) => { + const file = this.getFileByFdOrThrow(fd, 'futimes'); + const node = file.node; + node.atime = new Date(atime * 1000); + node.mtime = new Date(mtime * 1000); + this.emit(new FsEvent_1.FsEvent(3 /* FsEventType.ATTRIB */, file.link.steps, file.node, file.link)); + }; + this.utimes = (filename, atime, mtime, followSymlinks = true) => { + const link = followSymlinks + ? this.getResolvedLinkOrThrow(filename, 'utimes') + : this.getLinkOrThrow(filename, 'lutimes'); + const node = link.getNode(); + node.atime = new Date(atime * 1000); + node.mtime = new Date(mtime * 1000); + this.emit(new FsEvent_1.FsEvent(3 /* FsEventType.ATTRIB */, link.steps, node, link)); + }; + this.process = opts.process ?? process_1.default; + const root = this.createLink(); + root.setNode(this.createNode(fs_node_utils_1.constants.S_IFDIR | 0o777)); + root.setChild('.', root); + root.getNode().nlink++; + root.setChild('..', root); + root.getNode().nlink++; + this.root = root; + } + emit(change) { + this.changes.emit(change); + } + createLink(parent, name, isDirectory = false, mode) { + if (!parent) { + return new Link_1.Link(this, void 0, ''); + } + if (!name) { + throw new Error('createLink: name cannot be empty'); + } + // If no explicit permission is provided, use defaults based on type + const finalPerm = mode ?? (isDirectory ? 0o777 : 0o666); + // To prevent making a breaking change, `mode` can also just be a permission number + // and the file type is set based on `isDirectory` + const hasFileType = mode && mode & fs_node_utils_1.constants.S_IFMT; + const modeType = hasFileType ? mode & fs_node_utils_1.constants.S_IFMT : isDirectory ? fs_node_utils_1.constants.S_IFDIR : fs_node_utils_1.constants.S_IFREG; + const finalMode = (finalPerm & ~fs_node_utils_1.constants.S_IFMT) | modeType; + return parent.createChild(name, this.createNode(finalMode)); + } + deleteLink(link) { + const parent = link.parent; + if (parent) { + parent.deleteChild(link); + return true; + } + return false; + } + _emitDeleteRecursive(link) { + if (link.getNode().isDirectory()) { + for (const [name, child] of link.children.entries()) { + if (child && name !== '.' && name !== '..') { + this._emitDeleteRecursive(child); + } + } + } + this.emit(new FsEvent_1.FsEvent(1 /* FsEventType.DELETE */, link.steps, link.getNode(), link)); + } + newInoNumber() { + const releasedFd = this.releasedInos.pop(); + if (releasedFd) + return releasedFd; + else { + this.ino = (this.ino + 1) % 0xffffffff; + return this.ino; + } + } + newFdNumber() { + const releasedFd = this.releasedFds.pop(); + return typeof releasedFd === 'number' ? releasedFd : Superblock.fd--; + } + createNode(mode) { + const uid = this.process.getuid?.() ?? 0; + const gid = this.process.getgid?.() ?? 0; + const node = new Node_1.Node(this.newInoNumber(), mode, uid, gid); + this.inodes[node.ino] = node; + return node; + } + deleteNode(node) { + node.del(); + delete this.inodes[node.ino]; + this.releasedInos.push(node.ino); + } + walk(stepsOrFilenameOrLink, resolveSymlinks = false, checkExistence = false, checkAccess = false, funcName) { + let steps; + let filename; + if (stepsOrFilenameOrLink instanceof Link_1.Link) { + steps = stepsOrFilenameOrLink.steps; + filename = pathSep + steps.join(pathSep); + } + else if (typeof stepsOrFilenameOrLink === 'string') { + steps = (0, util_1.filenameToSteps)(stepsOrFilenameOrLink); + filename = stepsOrFilenameOrLink; + } + else { + steps = stepsOrFilenameOrLink; + filename = pathSep + steps.join(pathSep); + } + let curr = this.root; + let i = 0; + const uid = this.process.getuid?.() ?? 0; + const gid = this.process.getgid?.() ?? 0; + while (i < steps.length) { + let node = curr.getNode(); + // Check access permissions if current link is a directory + if (node.isDirectory()) { + if (checkAccess && !node.canExecute(uid, gid)) { + return (0, result_1.Err)((0, util_1.createStatError)("EACCES" /* ERROR_CODE.EACCES */, funcName, filename)); + } + } + else { + if (i < steps.length - 1) { + return (0, result_1.Err)((0, util_1.createStatError)("ENOTDIR" /* ERROR_CODE.ENOTDIR */, funcName, filename)); + } + } + curr = curr.getChild(steps[i]) ?? null; + // Check existence of current link + if (!curr) + if (checkExistence) { + return (0, result_1.Err)((0, util_1.createStatError)("ENOENT" /* ERROR_CODE.ENOENT */, funcName, filename)); + } + else { + return (0, result_1.Ok)(null); + } + node = curr?.getNode(); + // Resolve symlink if we're resolving all symlinks OR if this is an intermediate path component + // This allows lstat to traverse through symlinks in intermediate directories while not resolving the final component + if (node.isSymlink() && (resolveSymlinks || i < steps.length - 1)) { + const resolvedPath = (0, path_1.isAbsolute)(node.symlink) ? node.symlink : pathJoin((0, path_1.dirname)(curr.getPath()), node.symlink); // Relative to symlink's parent + steps = (0, util_1.filenameToSteps)(resolvedPath).concat(steps.slice(i + 1)); + curr = this.root; + i = 0; + continue; + } + // After resolving symlinks, check if it's not a directory and we still have more steps + // This handles the case where we try to traverse through a file + // Only do this check when we're doing filesystem operations (checkExistence = true) + if (checkExistence && !node.isDirectory() && i < steps.length - 1) { + // On Windows, use ENOENT for consistency with Node.js behavior + // On other platforms, use ENOTDIR which is more semantically correct + const errorCode = this.process.platform === 'win32' ? "ENOENT" /* ERROR_CODE.ENOENT */ : "ENOTDIR" /* ERROR_CODE.ENOTDIR */; + return (0, result_1.Err)((0, util_1.createStatError)(errorCode, funcName, filename)); + } + i++; + } + return (0, result_1.Ok)(curr); + } + // Returns a `Link` (hard link) referenced by path "split" into steps. + getLink(steps) { + const result = this.walk(steps, false, false, false); + if (result.ok) { + return result.value; + } + throw result.err.toError(); + } + // Just link `getLink`, but throws a correct user error, if link to found. + getLinkOrThrow(filename, funcName) { + const result = this.walk(filename, false, true, true, funcName); + if (result.ok) { + return result.value; + } + throw result.err.toError(); + } + // Just like `getLink`, but also dereference/resolves symbolic links. + getResolvedLink(filenameOrSteps) { + const result = this.walk(filenameOrSteps, true, false, false); + if (result.ok) { + return result.value; + } + throw result.err.toError(); + } + /** + * Just like `getLinkOrThrow`, but also dereference/resolves symbolic links. + */ + getResolvedLinkOrThrow(filename, funcName) { + const result = this.walk(filename, true, true, true, funcName); + if (result.ok) { + return result.value; + } + throw result.err.toError(); + } + getResolvedLinkResult(filename, funcName) { + const result = this.walk(filename, true, true, true, funcName); + if (result.ok) { + return (0, result_1.Ok)(result.value); + } + return result; + } + resolveSymlinks(link) { + return this.getResolvedLink(link.steps.slice(1)); + } + /** + * Just like `getLinkOrThrow`, but also verifies that the link is a directory. + */ + getLinkAsDirOrThrow(filename, funcName) { + const link = this.getLinkOrThrow(filename, funcName); + if (!link.getNode().isDirectory()) + throw (0, util_1.createError)("ENOTDIR" /* ERROR_CODE.ENOTDIR */, funcName, filename); + return link; + } + // Get the immediate parent directory of the link. + getLinkParent(steps) { + return this.getLink(steps.slice(0, -1)); + } + getLinkParentAsDirOrThrow(filenameOrSteps, funcName) { + const steps = (filenameOrSteps instanceof Array ? filenameOrSteps : (0, util_1.filenameToSteps)(filenameOrSteps)).slice(0, -1); + const filename = pathSep + steps.join(pathSep); + const link = this.getLinkOrThrow(filename, funcName); + if (!link.getNode().isDirectory()) + throw (0, util_1.createError)("ENOTDIR" /* ERROR_CODE.ENOTDIR */, funcName, filename); + return link; + } + getFileByFd(fd) { + return this.fds[String(fd)]; + } + getFileByFdOrThrow(fd, funcName) { + if (!(0, util_1.isFd)(fd)) + throw TypeError(fs_node_utils_2.ERRSTR.FD); + const file = this.getFileByFd(fd); + if (!file) + throw (0, util_1.createError)("EBADF" /* ERROR_CODE.EBADF */, funcName); + return file; + } + _toJSON(link = this.root, json = {}, path, asBuffer) { + let isEmpty = true; + let children = link.children; + if (link.getNode().isFile()) { + children = new Map([[link.getName(), link.parent.getChild(link.getName())]]); + link = link.parent; + } + for (const name of children.keys()) { + if (name === '.' || name === '..') { + continue; + } + isEmpty = false; + const child = link.getChild(name); + if (!child) { + throw new Error('_toJSON: unexpected undefined'); + } + const node = child.getNode(); + if (node.isFile()) { + let filename = child.getPath(); + if (path) + filename = pathRelative(path, filename); + json[filename] = asBuffer ? node.getBuffer() : node.getString(); + } + else if (node.isDirectory()) { + this._toJSON(child, json, path, asBuffer); + } + } + let dirPath = link.getPath(); + if (path) + dirPath = pathRelative(path, dirPath); + if (dirPath && isEmpty) { + json[dirPath] = null; + } + return json; + } + toJSON(paths, json = {}, isRelative = false, asBuffer = false) { + const links = []; + if (paths) { + if (!Array.isArray(paths)) + paths = [paths]; + for (const path of paths) { + const filename = (0, util_1.pathToFilename)(path); + const link = this.getResolvedLink(filename); + if (!link) + continue; + links.push(link); + } + } + else { + links.push(this.root); + } + if (!links.length) + return json; + for (const link of links) + this._toJSON(link, json, isRelative ? link.getPath() : '', asBuffer); + return json; + } + fromJSON(json, cwd = this.process.cwd()) { + for (let filename in json) { + const data = json[filename]; + filename = (0, util_1.resolve)(filename, cwd); + if (typeof data === 'string' || data instanceof buffer_1.Buffer) { + const dir = (0, path_1.dirname)(filename); + this.mkdirp(dir, 511 /* MODE.DIR */); + const buffer = (0, util_1.dataToBuffer)(data); + this.writeFile(filename, buffer, fs_node_utils_2.FLAGS.w, 438 /* MODE.DEFAULT */); + } + else { + this.mkdirp(filename, 511 /* MODE.DIR */); + } + } + } + fromNestedJSON(json, cwd) { + this.fromJSON((0, json_1.flattenJSON)(json), cwd); + } + reset() { + this.ino = 0; + this.inodes = {}; + this.releasedInos = []; + this.fds = {}; + this.releasedFds = []; + this.openFiles = 0; + this.root = this.createLink(); + this.root.setNode(this.createNode(fs_node_utils_1.constants.S_IFDIR | 0o777)); + } + // Legacy interface + mountSync(mountpoint, json) { + this.fromJSON(json, mountpoint); + } + openLink(link, flagsNum, resolveSymlinks = true) { + if (this.openFiles >= this.maxFiles) { + // Too many open files. + throw (0, util_1.createError)("EMFILE" /* ERROR_CODE.EMFILE */, 'open', link.getPath()); + } + // Resolve symlinks. + // + // @TODO: This should be superfluous. This method is only ever called by openFile(), which does its own symlink resolution + // prior to calling. + let realLink = link; + if (resolveSymlinks) + realLink = this.getResolvedLinkOrThrow(link.getPath(), 'open'); + const node = realLink.getNode(); + // Check whether node is a directory + if (node.isDirectory()) { + if ((flagsNum & (O_RDONLY | O_RDWR | O_WRONLY)) !== O_RDONLY) + throw (0, util_1.createError)("EISDIR" /* ERROR_CODE.EISDIR */, 'open', link.getPath()); + } + else { + if (flagsNum & O_DIRECTORY) + throw (0, util_1.createError)("ENOTDIR" /* ERROR_CODE.ENOTDIR */, 'open', link.getPath()); + } + // Check node permissions + // For read access: check if flags are O_RDONLY or O_RDWR (i.e., not only O_WRONLY) + if ((flagsNum & (O_RDONLY | O_RDWR | O_WRONLY)) !== O_WRONLY) { + if (!node.canRead()) { + throw (0, util_1.createError)("EACCES" /* ERROR_CODE.EACCES */, 'open', link.getPath()); + } + } + // For write access: check if flags are O_WRONLY or O_RDWR + if (flagsNum & (O_WRONLY | O_RDWR)) { + if (!node.canWrite()) { + throw (0, util_1.createError)("EACCES" /* ERROR_CODE.EACCES */, 'open', link.getPath()); + } + } + const file = new File_1.File(link, node, flagsNum, this.newFdNumber()); + this.fds[file.fd] = file; + this.openFiles++; + if (flagsNum & O_TRUNC) { + const hadContent = file.node.getSize() > 0; + file.truncate(); + if (hadContent) + this.emit(new FsEvent_1.FsEvent(2 /* FsEventType.MODIFY */, file.link.steps, file.node, file.link)); + } + return file; + } + openFile(filename, flagsNum, modeNum, resolveSymlinks = true) { + const steps = (0, util_1.filenameToSteps)(filename); + let link; + try { + link = resolveSymlinks ? this.getResolvedLinkOrThrow(filename, 'open') : this.getLinkOrThrow(filename, 'open'); + // Check if file already existed when trying to create it exclusively (O_CREAT and O_EXCL flags are set). + // This is an error, see https://pubs.opengroup.org/onlinepubs/009695399/functions/open.html: + // "If O_CREAT and O_EXCL are set, open() shall fail if the file exists." + if (link && flagsNum & O_CREAT && flagsNum & O_EXCL) + throw (0, util_1.createError)("EEXIST" /* ERROR_CODE.EEXIST */, 'open', filename); + } + catch (err) { + // Try creating a new file, if it does not exist and O_CREAT flag is set. + // Note that this will still throw if the ENOENT came from one of the + // intermediate directories instead of the file itself. + if (err.code === "ENOENT" /* ERROR_CODE.ENOENT */ && flagsNum & O_CREAT) { + const dirName = (0, path_1.dirname)(filename); + const dirLink = this.getResolvedLinkOrThrow(dirName); + const dirNode = dirLink.getNode(); + // Check that the place we create the new file is actually a directory and that we are allowed to do so: + if (!dirNode.isDirectory()) + throw (0, util_1.createError)("ENOTDIR" /* ERROR_CODE.ENOTDIR */, 'open', filename); + if (!dirNode.canExecute() || !dirNode.canWrite()) + throw (0, util_1.createError)("EACCES" /* ERROR_CODE.EACCES */, 'open', filename); + // This is a difference to the original implementation, which would simply not create a file unless modeNum was specified. + // However, current Node versions will default to 0o666. + modeNum ?? (modeNum = 0o666); + link = this.createLink(dirLink, steps[steps.length - 1], false, modeNum); + this.emit(new FsEvent_1.FsEvent(0 /* FsEventType.CREATE */, link.steps, link.getNode(), link)); + } + else + throw err; + } + if (link) + return this.openLink(link, flagsNum, resolveSymlinks); + throw (0, util_1.createError)("ENOENT" /* ERROR_CODE.ENOENT */, 'open', filename); + } + closeFile(file) { + if (!this.fds[file.fd]) + return; + this.openFiles--; + delete this.fds[file.fd]; + this.releasedFds.push(file.fd); + } + write(fd, buf, offset, length, position) { + const file = this.getFileByFdOrThrow(fd, 'write'); + if (file.node.isSymlink()) { + throw (0, util_1.createError)("EBADF" /* ERROR_CODE.EBADF */, 'write', file.link.getPath()); + } + const bytes = file.write(buf, offset, length, position === -1 || typeof position !== 'number' ? undefined : position); + if (bytes > 0) + this.emit(new FsEvent_1.FsEvent(2 /* FsEventType.MODIFY */, file.link.steps, file.node, file.link)); + return bytes; + } + }; + Superblock.Superblock = Superblock$1; + /** + * Global file descriptor counter. UNIX file descriptors start from 0 and go sequentially + * up, so here, in order not to conflict with them, we choose some big number and descrease + * the file descriptor of every new opened file. + * @type {number} + * @todo This should not be static, right? + */ + Superblock$1.fd = 0x7fffffff; + + return Superblock; +} + +var CoreWatcher = {}; + +var hasRequiredCoreWatcher; + +function requireCoreWatcher () { + if (hasRequiredCoreWatcher) return CoreWatcher; + hasRequiredCoreWatcher = 1; + Object.defineProperty(CoreWatcher, "__esModule", { value: true }); + CoreWatcher.CoreWatcher = CoreWatcher.CoreWatchEvent = void 0; + const fanout_1 = requireFanout(); + /** + * A change event scoped to a {@link CoreWatcher} watch root. Unlike the + * volume-undefined {@link FsEvent}, `steps` (and `oldSteps`) are relative to the + * watch root; an empty `steps` array means the watch target itself changed. + */ + class CoreWatchEvent { + constructor(type, + /** Path relative to the watch root, empty for the watch target itself. */ + steps, node, link, + /** Former path relative to the watch root, set only for in-scope moves. */ + oldSteps = void 0) { + this.type = type; + this.steps = steps; + this.node = node; + this.link = link; + this.oldSteps = oldSteps; + } + } + CoreWatcher.CoreWatchEvent = CoreWatchEvent; + /** + * Subscribes to a {@link Superblock} change stream and re-emits only the + * events that fall within the scope of one watched file or directory, with + * paths rewritten to be relative to the watch root. + * + * Scope-boundary crossing moves are translated: a move into scope is emitted + * as `CREATE`, a move out of scope as `DELETE`, and a move within scope stays + * a `MOVE` carrying relative `oldSteps`. A `MOVE` with empty `steps` means the + * watch target itself was renamed; watching continues at the new location + * (the current absolute path is always `watcher.link.steps`). A `DELETE` with + * empty `steps` is terminal: the watch target is gone and the watcher closes + * itself after delivering it. + */ + let CoreWatcher$1 = class CoreWatcher { + /** @throws ENOENT-style error when the watch target does not exist. */ + constructor(core, path, opts = {}) { + /** Fan-out of scoped change events. Multiple consumers may subscribe. */ + this.changes = new fanout_1.FanOut(); + this.link = (opts.follow ?? true) ? core.getResolvedLinkOrThrow(path, 'watch') : core.getLinkOrThrow(path, 'watch'); + this.node = this.link.getNode(); + this.recursive = !!opts.recursive; + this.unsub = core.changes.listen(event => this.onEvent(event)); + } + get closed() { + return !this.unsub; + } + onEvent(event) { + const rootLength = this.link.steps.length; + const isSelf = event.link === this.link || + (event.node === this.node && (event.type === 2 /* FsEventType.MODIFY */ || event.type === 3 /* FsEventType.ATTRIB */)); + if (isSelf) { + this.changes.emit(new CoreWatchEvent(event.type, [], event.node, this.link)); + if (event.type === 1 /* FsEventType.DELETE */) + this.close(); + return; + } + if (event.type === 4 /* FsEventType.MOVE */) { + const from = event.oldSteps && this.inScope(event.oldSteps) ? event.oldSteps.slice(rootLength) : undefined; + const to = this.inScope(event.steps) ? event.steps.slice(rootLength) : undefined; + if (from && to) + this.changes.emit(new CoreWatchEvent(4 /* FsEventType.MOVE */, to, event.node, event.link, from)); + else if (from) + this.changes.emit(new CoreWatchEvent(1 /* FsEventType.DELETE */, from, event.node, event.link)); + else if (to) + this.changes.emit(new CoreWatchEvent(0 /* FsEventType.CREATE */, to, event.node, event.link)); + return; + } + if (this.inScope(event.steps)) + this.changes.emit(new CoreWatchEvent(event.type, event.steps.slice(rootLength), event.node, event.link)); + } + inScope(steps) { + const root = this.link.steps; + if (steps.length <= root.length) + return false; + if (!this.recursive && steps.length !== root.length + 1) + return false; + for (let i = 0; i < root.length; i++) + if (steps[i] !== root[i]) + return false; + return true; + } + /** Stop watching and unsubscribe from the volume change stream. */ + close() { + this.unsub?.(); + this.unsub = undefined; + } + }; + CoreWatcher.CoreWatcher = CoreWatcher$1; + + return CoreWatcher; +} + +var hasRequiredLib$5; + +function requireLib$5 () { + if (hasRequiredLib$5) return lib$6; + hasRequiredLib$5 = 1; + (function (exports) { + Object.defineProperty(exports, "__esModule", { value: true }); + exports.resolve = exports.pathToFilename = exports.createStatError = exports.createError = exports.validateFd = exports.isFd = exports.filenameToSteps = exports.dataToBuffer = exports.Superblock = exports.File = exports.Link = exports.Node = void 0; + const tslib_1 = require$$0$2; + tslib_1.__exportStar(requireTypes$1(), exports); + tslib_1.__exportStar(requireJson$1(), exports); + tslib_1.__exportStar(requireConstants$3(), exports); + tslib_1.__exportStar(requireResult(), exports); + var Node_1 = requireNode(); + Object.defineProperty(exports, "Node", { enumerable: true, get: function () { return Node_1.Node; } }); + var Link_1 = requireLink(); + Object.defineProperty(exports, "Link", { enumerable: true, get: function () { return Link_1.Link; } }); + var File_1 = requireFile(); + Object.defineProperty(exports, "File", { enumerable: true, get: function () { return File_1.File; } }); + var Superblock_1 = requireSuperblock(); + Object.defineProperty(exports, "Superblock", { enumerable: true, get: function () { return Superblock_1.Superblock; } }); + tslib_1.__exportStar(requireFsEvent(), exports); + tslib_1.__exportStar(requireCoreWatcher(), exports); + var util_1 = requireUtil$3(); + Object.defineProperty(exports, "dataToBuffer", { enumerable: true, get: function () { return util_1.dataToBuffer; } }); + Object.defineProperty(exports, "filenameToSteps", { enumerable: true, get: function () { return util_1.filenameToSteps; } }); + Object.defineProperty(exports, "isFd", { enumerable: true, get: function () { return util_1.isFd; } }); + Object.defineProperty(exports, "validateFd", { enumerable: true, get: function () { return util_1.validateFd; } }); + Object.defineProperty(exports, "createError", { enumerable: true, get: function () { return util_1.createError; } }); + Object.defineProperty(exports, "createStatError", { enumerable: true, get: function () { return util_1.createStatError; } }); + Object.defineProperty(exports, "pathToFilename", { enumerable: true, get: function () { return util_1.pathToFilename; } }); + Object.defineProperty(exports, "resolve", { enumerable: true, get: function () { return util_1.resolve; } }); + + } (lib$6)); + return lib$6; +} + +var Stats = {}; + +var hasRequiredStats; + +function requireStats () { + if (hasRequiredStats) return Stats; + hasRequiredStats = 1; + Object.defineProperty(Stats, "__esModule", { value: true }); + Stats.Stats = void 0; + const fs_node_utils_1 = requireLib$7(); + const { S_IFMT, S_IFDIR, S_IFREG, S_IFBLK, S_IFCHR, S_IFLNK, S_IFIFO, S_IFSOCK } = fs_node_utils_1.constants; + /** + * Statistics about a file/directory, like `fs.Stats`. + */ + let Stats$1 = class Stats { + static build(node, bigint = false) { + const stats = new Stats(); + const { uid, gid, atime, mtime, ctime } = node; + const getStatNumber = !bigint ? number => number : number => BigInt(number); + // Copy all values on Stats from Node, so that if Node values + // change, values on Stats would still be the old ones, + // just like in Node fs. + stats.uid = getStatNumber(uid); + stats.gid = getStatNumber(gid); + stats.rdev = getStatNumber(node.rdev); + stats.blksize = getStatNumber(4096); + stats.ino = getStatNumber(node.ino); + stats.size = getStatNumber(node.getSize()); + stats.blocks = getStatNumber(1); + stats.atime = atime; + stats.mtime = mtime; + stats.ctime = ctime; + stats.birthtime = ctime; + stats.atimeMs = getStatNumber(atime.getTime()); + stats.mtimeMs = getStatNumber(mtime.getTime()); + const ctimeMs = getStatNumber(ctime.getTime()); + stats.ctimeMs = ctimeMs; + stats.birthtimeMs = ctimeMs; + if (bigint) { + stats.atimeNs = BigInt(atime.getTime()) * BigInt(1000000); + stats.mtimeNs = BigInt(mtime.getTime()) * BigInt(1000000); + const ctimeNs = BigInt(ctime.getTime()) * BigInt(1000000); + stats.ctimeNs = ctimeNs; + stats.birthtimeNs = ctimeNs; + } + stats.dev = getStatNumber(0); + stats.mode = getStatNumber(node.mode); + stats.nlink = getStatNumber(node.nlink); + return stats; + } + _checkModeProperty(property) { + return (Number(this.mode) & S_IFMT) === property; + } + isDirectory() { + return this._checkModeProperty(S_IFDIR); + } + isFile() { + return this._checkModeProperty(S_IFREG); + } + isBlockDevice() { + return this._checkModeProperty(S_IFBLK); + } + isCharacterDevice() { + return this._checkModeProperty(S_IFCHR); + } + isSymbolicLink() { + return this._checkModeProperty(S_IFLNK); + } + isFIFO() { + return this._checkModeProperty(S_IFIFO); + } + isSocket() { + return this._checkModeProperty(S_IFSOCK); + } + }; + Stats.Stats = Stats$1; + Stats.default = Stats$1; + + return Stats; +} + +var Dirent = {}; + +var hasRequiredDirent; + +function requireDirent () { + if (hasRequiredDirent) return Dirent; + hasRequiredDirent = 1; + Object.defineProperty(Dirent, "__esModule", { value: true }); + Dirent.Dirent = void 0; + const fs_node_utils_1 = requireLib$7(); + const { S_IFMT, S_IFDIR, S_IFREG, S_IFBLK, S_IFCHR, S_IFLNK, S_IFIFO, S_IFSOCK } = fs_node_utils_1.constants; + /** + * A directory entry, like `fs.Dirent`. + */ + let Dirent$1 = class Dirent { + constructor() { + this.name = ''; + this.parentPath = ''; + this.mode = 0; + /** + * @deprecated Will be removed at any time. + * @see https://nodejs.org/api/deprecations.html#DEP0178 + */ + this.path = ''; + } + static build(link, encoding) { + const dirent = new Dirent(); + const { mode } = link.getNode(); + dirent.name = (0, fs_node_utils_1.strToEncoding)(link.getName(), encoding); + dirent.mode = mode; + dirent.parentPath = link.getParentPath(); + dirent.path = dirent.parentPath; + return dirent; + } + _checkModeProperty(property) { + return (this.mode & S_IFMT) === property; + } + isDirectory() { + return this._checkModeProperty(S_IFDIR); + } + isFile() { + return this._checkModeProperty(S_IFREG); + } + isBlockDevice() { + return this._checkModeProperty(S_IFBLK); + } + isCharacterDevice() { + return this._checkModeProperty(S_IFCHR); + } + isSymbolicLink() { + return this._checkModeProperty(S_IFLNK); + } + isFIFO() { + return this._checkModeProperty(S_IFIFO); + } + isSocket() { + return this._checkModeProperty(S_IFSOCK); + } + }; + Dirent.Dirent = Dirent$1; + Dirent.default = Dirent$1; + + return Dirent; +} + +var StatFs = {}; + +var hasRequiredStatFs; + +function requireStatFs () { + if (hasRequiredStatFs) return StatFs; + hasRequiredStatFs = 1; + Object.defineProperty(StatFs, "__esModule", { value: true }); + StatFs.StatFs = void 0; + /** + * Statistics about a file system, like `fs.StatFs`. + */ + let StatFs$1 = class StatFs { + static build(superblock, bigint = false) { + const statfs = new StatFs(); + const getStatNumber = !bigint ? number => number : number => BigInt(number); + // For in-memory filesystem, provide mock but reasonable values + // Magic number for in-memory filesystem type (similar to ramfs) + statfs.type = getStatNumber(0x858458f6); + // Optimal transfer block size - commonly 4096 bytes + statfs.bsize = getStatNumber(4096); + // Calculate filesystem stats based on current state + const totalInodes = Object.keys(superblock.inodes).length; + // Mock large filesystem capacity (appears as a large filesystem to applications) + const totalBlocks = 1000000; + const usedBlocks = Math.min(totalInodes * 2, totalBlocks); // Rough estimation + const freeBlocks = totalBlocks - usedBlocks; + statfs.blocks = getStatNumber(totalBlocks); // Total data blocks + statfs.bfree = getStatNumber(freeBlocks); // Free blocks in file system + statfs.bavail = getStatNumber(freeBlocks); // Free blocks available to unprivileged users + // File node statistics + const maxFiles = 1000000; // Mock large number of available inodes + statfs.files = getStatNumber(maxFiles); // Total file nodes in file system + statfs.ffree = getStatNumber(maxFiles - totalInodes); // Free file nodes + return statfs; + } + }; + StatFs.StatFs = StatFs$1; + StatFs.default = StatFs$1; + + return StatFs; +} + +var setTimeoutUnref = {}; + +var hasRequiredSetTimeoutUnref; + +function requireSetTimeoutUnref () { + if (hasRequiredSetTimeoutUnref) return setTimeoutUnref; + hasRequiredSetTimeoutUnref = 1; + Object.defineProperty(setTimeoutUnref, "__esModule", { value: true }); + /** + * `setTimeoutUnref` is just like `setTimeout`, + * only in Node's environment it will "unref" its macro task. + */ + function setTimeoutUnref$1(callback, time, args) { + const ref = setTimeout.apply(typeof globalThis !== 'undefined' ? globalThis : commonjsGlobal, arguments); + if (ref && typeof ref === 'object' && typeof ref.unref === 'function') + ref.unref(); + return ref; + } + setTimeoutUnref.default = setTimeoutUnref$1; + + return setTimeoutUnref; +} + +var stream$1 = {}; + +var browser$1 = {exports: {}}; + +var stream = {exports: {}}; + +var primordials; +var hasRequiredPrimordials; + +function requirePrimordials () { + if (hasRequiredPrimordials) return primordials; + hasRequiredPrimordials = 1; + + /* + This file is a reduced and adapted version of the main lib/internal/per_context/primordials.js file defined at + + https://github.com/nodejs/node/blob/main/lib/internal/per_context/primordials.js + + Don't try to replace with the original file and keep it up to date with the upstream file. + */ + + // This is a simplified version of AggregateError + class AggregateError extends Error { + constructor(errors) { + if (!Array.isArray(errors)) { + throw new TypeError(`Expected input to be an Array, got ${typeof errors}`) + } + let message = ''; + for (let i = 0; i < errors.length; i++) { + message += ` ${errors[i].stack}\n`; + } + super(message); + this.name = 'AggregateError'; + this.errors = errors; + } + } + primordials = { + AggregateError, + ArrayIsArray(self) { + return Array.isArray(self) + }, + ArrayPrototypeIncludes(self, el) { + return self.includes(el) + }, + ArrayPrototypeIndexOf(self, el) { + return self.indexOf(el) + }, + ArrayPrototypeJoin(self, sep) { + return self.join(sep) + }, + ArrayPrototypeMap(self, fn) { + return self.map(fn) + }, + ArrayPrototypePop(self, el) { + return self.pop(el) + }, + ArrayPrototypePush(self, el) { + return self.push(el) + }, + ArrayPrototypeSlice(self, start, end) { + return self.slice(start, end) + }, + Error, + FunctionPrototypeCall(fn, thisArgs, ...args) { + return fn.call(thisArgs, ...args) + }, + FunctionPrototypeSymbolHasInstance(self, instance) { + return Function.prototype[Symbol.hasInstance].call(self, instance) + }, + MathFloor: Math.floor, + Number, + NumberIsInteger: Number.isInteger, + NumberIsNaN: Number.isNaN, + NumberMAX_SAFE_INTEGER: Number.MAX_SAFE_INTEGER, + NumberMIN_SAFE_INTEGER: Number.MIN_SAFE_INTEGER, + NumberParseInt: Number.parseInt, + ObjectDefineProperties(self, props) { + return Object.defineProperties(self, props) + }, + ObjectDefineProperty(self, name, prop) { + return Object.defineProperty(self, name, prop) + }, + ObjectGetOwnPropertyDescriptor(self, name) { + return Object.getOwnPropertyDescriptor(self, name) + }, + ObjectKeys(obj) { + return Object.keys(obj) + }, + ObjectSetPrototypeOf(target, proto) { + return Object.setPrototypeOf(target, proto) + }, + Promise, + PromisePrototypeCatch(self, fn) { + return self.catch(fn) + }, + PromisePrototypeThen(self, thenFn, catchFn) { + return self.then(thenFn, catchFn) + }, + PromiseReject(err) { + return Promise.reject(err) + }, + PromiseResolve(val) { + return Promise.resolve(val) + }, + ReflectApply: Reflect.apply, + RegExpPrototypeTest(self, value) { + return self.test(value) + }, + SafeSet: Set, + String, + StringPrototypeSlice(self, start, end) { + return self.slice(start, end) + }, + StringPrototypeToLowerCase(self) { + return self.toLowerCase() + }, + StringPrototypeToUpperCase(self) { + return self.toUpperCase() + }, + StringPrototypeTrim(self) { + return self.trim() + }, + Symbol, + SymbolFor: Symbol.for, + SymbolAsyncIterator: Symbol.asyncIterator, + SymbolHasInstance: Symbol.hasInstance, + SymbolIterator: Symbol.iterator, + SymbolDispose: Symbol.dispose || Symbol('Symbol.dispose'), + SymbolAsyncDispose: Symbol.asyncDispose || Symbol('Symbol.asyncDispose'), + TypedArrayPrototypeSet(self, buf, len) { + return self.set(buf, len) + }, + Boolean, + Uint8Array + }; + return primordials; +} + +var util$2 = {exports: {}}; + +var inspect; +var hasRequiredInspect; + +function requireInspect () { + if (hasRequiredInspect) return inspect; + hasRequiredInspect = 1; + + /* + This file is a reduced and adapted version of the main lib/internal/util/inspect.js file defined at + + https://github.com/nodejs/node/blob/main/lib/internal/util/inspect.js + + Don't try to replace with the original file and keep it up to date with the upstream file. + */ + inspect = { + format(format, ...args) { + // Simplified version of https://nodejs.org/api/util.html#utilformatformat-args + return format.replace(/%([sdifj])/g, function (...[_unused, type]) { + const replacement = args.shift(); + if (type === 'f') { + return replacement.toFixed(6) + } else if (type === 'j') { + return JSON.stringify(replacement) + } else if (type === 's' && typeof replacement === 'object') { + const ctor = replacement.constructor !== Object ? replacement.constructor.name : ''; + return `${ctor} {}`.trim() + } else { + return replacement.toString() + } + }) + }, + inspect(value) { + // Vastly simplified version of https://nodejs.org/api/util.html#utilinspectobject-options + switch (typeof value) { + case 'string': + if (value.includes("'")) { + if (!value.includes('"')) { + return `"${value}"` + } else if (!value.includes('`') && !value.includes('${')) { + return `\`${value}\`` + } + } + return `'${value}'` + case 'number': + if (isNaN(value)) { + return 'NaN' + } else if (Object.is(value, -0)) { + return String(value) + } + return value + case 'bigint': + return `${String(value)}n` + case 'boolean': + case 'undefined': + return String(value) + case 'object': + return '{}' + } + } + }; + return inspect; +} + +var errors; +var hasRequiredErrors; + +function requireErrors () { + if (hasRequiredErrors) return errors; + hasRequiredErrors = 1; + + const { format, inspect } = requireInspect(); + const { AggregateError: CustomAggregateError } = requirePrimordials(); + + /* + This file is a reduced and adapted version of the main lib/internal/errors.js file defined at + + https://github.com/nodejs/node/blob/main/lib/internal/errors.js + + Don't try to replace with the original file and keep it up to date (starting from E(...) definitions) + with the upstream file. + */ + + const AggregateError = globalThis.AggregateError || CustomAggregateError; + const kIsNodeError = Symbol('kIsNodeError'); + const kTypes = [ + 'string', + 'function', + 'number', + 'object', + // Accept 'Function' and 'Object' as alternative to the lower cased version. + 'Function', + 'Object', + 'boolean', + 'bigint', + 'symbol' + ]; + const classRegExp = /^([A-Z][a-z0-9]*)+$/; + const nodeInternalPrefix = '__node_internal_'; + const codes = {}; + function assert(value, message) { + if (!value) { + throw new codes.ERR_INTERNAL_ASSERTION(message) + } + } + + // Only use this for integers! Decimal numbers do not work with this function. + function addNumericalSeparator(val) { + let res = ''; + let i = val.length; + const start = val[0] === '-' ? 1 : 0; + for (; i >= start + 4; i -= 3) { + res = `_${val.slice(i - 3, i)}${res}`; + } + return `${val.slice(0, i)}${res}` + } + function getMessage(key, msg, args) { + if (typeof msg === 'function') { + assert( + msg.length <= args.length, + // Default options do not count. + `Code: ${key}; The provided arguments length (${args.length}) does not match the required ones (${msg.length}).` + ); + return msg(...args) + } + const expectedLength = (msg.match(/%[dfijoOs]/g) || []).length; + assert( + expectedLength === args.length, + `Code: ${key}; The provided arguments length (${args.length}) does not match the required ones (${expectedLength}).` + ); + if (args.length === 0) { + return msg + } + return format(msg, ...args) + } + function E(code, message, Base) { + if (!Base) { + Base = Error; + } + class NodeError extends Base { + constructor(...args) { + super(getMessage(code, message, args)); + } + toString() { + return `${this.name} [${code}]: ${this.message}` + } + } + Object.defineProperties(NodeError.prototype, { + name: { + value: Base.name, + writable: true, + enumerable: false, + configurable: true + }, + toString: { + value() { + return `${this.name} [${code}]: ${this.message}` + }, + writable: true, + enumerable: false, + configurable: true + } + }); + NodeError.prototype.code = code; + NodeError.prototype[kIsNodeError] = true; + codes[code] = NodeError; + } + function hideStackFrames(fn) { + // We rename the functions that will be hidden to cut off the stacktrace + // at the outermost one + const hidden = nodeInternalPrefix + fn.name; + Object.defineProperty(fn, 'name', { + value: hidden + }); + return fn + } + function aggregateTwoErrors(innerError, outerError) { + if (innerError && outerError && innerError !== outerError) { + if (Array.isArray(outerError.errors)) { + // If `outerError` is already an `AggregateError`. + outerError.errors.push(innerError); + return outerError + } + const err = new AggregateError([outerError, innerError], outerError.message); + err.code = outerError.code; + return err + } + return innerError || outerError + } + class AbortError extends Error { + constructor(message = 'The operation was aborted', options = undefined) { + if (options !== undefined && typeof options !== 'object') { + throw new codes.ERR_INVALID_ARG_TYPE('options', 'Object', options) + } + super(message, options); + this.code = 'ABORT_ERR'; + this.name = 'AbortError'; + } + } + E('ERR_ASSERTION', '%s', Error); + E( + 'ERR_INVALID_ARG_TYPE', + (name, expected, actual) => { + assert(typeof name === 'string', "'name' must be a string"); + if (!Array.isArray(expected)) { + expected = [expected]; + } + let msg = 'The '; + if (name.endsWith(' argument')) { + // For cases like 'first argument' + msg += `${name} `; + } else { + msg += `"${name}" ${name.includes('.') ? 'property' : 'argument'} `; + } + msg += 'must be '; + const types = []; + const instances = []; + const other = []; + for (const value of expected) { + assert(typeof value === 'string', 'All expected entries have to be of type string'); + if (kTypes.includes(value)) { + types.push(value.toLowerCase()); + } else if (classRegExp.test(value)) { + instances.push(value); + } else { + assert(value !== 'object', 'The value "object" should be written as "Object"'); + other.push(value); + } + } + + // Special handle `object` in case other instances are allowed to outline + // the differences between each other. + if (instances.length > 0) { + const pos = types.indexOf('object'); + if (pos !== -1) { + types.splice(types, pos, 1); + instances.push('Object'); + } + } + if (types.length > 0) { + switch (types.length) { + case 1: + msg += `of type ${types[0]}`; + break + case 2: + msg += `one of type ${types[0]} or ${types[1]}`; + break + default: { + const last = types.pop(); + msg += `one of type ${types.join(', ')}, or ${last}`; + } + } + if (instances.length > 0 || other.length > 0) { + msg += ' or '; + } + } + if (instances.length > 0) { + switch (instances.length) { + case 1: + msg += `an instance of ${instances[0]}`; + break + case 2: + msg += `an instance of ${instances[0]} or ${instances[1]}`; + break + default: { + const last = instances.pop(); + msg += `an instance of ${instances.join(', ')}, or ${last}`; + } + } + if (other.length > 0) { + msg += ' or '; + } + } + switch (other.length) { + case 0: + break + case 1: + if (other[0].toLowerCase() !== other[0]) { + msg += 'an '; + } + msg += `${other[0]}`; + break + case 2: + msg += `one of ${other[0]} or ${other[1]}`; + break + default: { + const last = other.pop(); + msg += `one of ${other.join(', ')}, or ${last}`; + } + } + if (actual == null) { + msg += `. Received ${actual}`; + } else if (typeof actual === 'function' && actual.name) { + msg += `. Received function ${actual.name}`; + } else if (typeof actual === 'object') { + var _actual$constructor; + if ( + (_actual$constructor = actual.constructor) !== null && + _actual$constructor !== undefined && + _actual$constructor.name + ) { + msg += `. Received an instance of ${actual.constructor.name}`; + } else { + const inspected = inspect(actual, { + depth: -1 + }); + msg += `. Received ${inspected}`; + } + } else { + let inspected = inspect(actual, { + colors: false + }); + if (inspected.length > 25) { + inspected = `${inspected.slice(0, 25)}...`; + } + msg += `. Received type ${typeof actual} (${inspected})`; + } + return msg + }, + TypeError + ); + E( + 'ERR_INVALID_ARG_VALUE', + (name, value, reason = 'is invalid') => { + let inspected = inspect(value); + if (inspected.length > 128) { + inspected = inspected.slice(0, 128) + '...'; + } + const type = name.includes('.') ? 'property' : 'argument'; + return `The ${type} '${name}' ${reason}. Received ${inspected}` + }, + TypeError + ); + E( + 'ERR_INVALID_RETURN_VALUE', + (input, name, value) => { + var _value$constructor; + const type = + value !== null && + value !== undefined && + (_value$constructor = value.constructor) !== null && + _value$constructor !== undefined && + _value$constructor.name + ? `instance of ${value.constructor.name}` + : `type ${typeof value}`; + return `Expected ${input} to be returned from the "${name}"` + ` function but got ${type}.` + }, + TypeError + ); + E( + 'ERR_MISSING_ARGS', + (...args) => { + assert(args.length > 0, 'At least one arg needs to be specified'); + let msg; + const len = args.length; + args = (Array.isArray(args) ? args : [args]).map((a) => `"${a}"`).join(' or '); + switch (len) { + case 1: + msg += `The ${args[0]} argument`; + break + case 2: + msg += `The ${args[0]} and ${args[1]} arguments`; + break + default: + { + const last = args.pop(); + msg += `The ${args.join(', ')}, and ${last} arguments`; + } + break + } + return `${msg} must be specified` + }, + TypeError + ); + E( + 'ERR_OUT_OF_RANGE', + (str, range, input) => { + assert(range, 'Missing "range" argument'); + let received; + if (Number.isInteger(input) && Math.abs(input) > 2 ** 32) { + received = addNumericalSeparator(String(input)); + } else if (typeof input === 'bigint') { + received = String(input); + const limit = BigInt(2) ** BigInt(32); + if (input > limit || input < -limit) { + received = addNumericalSeparator(received); + } + received += 'n'; + } else { + received = inspect(input); + } + return `The value of "${str}" is out of range. It must be ${range}. Received ${received}` + }, + RangeError + ); + E('ERR_MULTIPLE_CALLBACK', 'Callback called multiple times', Error); + E('ERR_METHOD_NOT_IMPLEMENTED', 'The %s method is not implemented', Error); + E('ERR_STREAM_ALREADY_FINISHED', 'Cannot call %s after a stream was finished', Error); + E('ERR_STREAM_CANNOT_PIPE', 'Cannot pipe, not readable', Error); + E('ERR_STREAM_DESTROYED', 'Cannot call %s after a stream was destroyed', Error); + E('ERR_STREAM_NULL_VALUES', 'May not write null values to stream', TypeError); + E('ERR_STREAM_PREMATURE_CLOSE', 'Premature close', Error); + E('ERR_STREAM_PUSH_AFTER_EOF', 'stream.push() after EOF', Error); + E('ERR_STREAM_UNSHIFT_AFTER_END_EVENT', 'stream.unshift() after end event', Error); + E('ERR_STREAM_WRITE_AFTER_END', 'write after end', Error); + E('ERR_UNKNOWN_ENCODING', 'Unknown encoding: %s', TypeError); + errors = { + AbortError, + aggregateTwoErrors: hideStackFrames(aggregateTwoErrors), + hideStackFrames, + codes + }; + return errors; +} + +var browser = {exports: {}}; + +/*globals self, window */ + +var hasRequiredBrowser$1; + +function requireBrowser$1 () { + if (hasRequiredBrowser$1) return browser.exports; + hasRequiredBrowser$1 = 1; + + /*eslint-disable @mysticatea/prettier */ + const { AbortController, AbortSignal } = + typeof self !== "undefined" ? self : + typeof window !== "undefined" ? window : + /* otherwise */ undefined; + /*eslint-enable @mysticatea/prettier */ + + browser.exports = AbortController; + browser.exports.AbortSignal = AbortSignal; + browser.exports.default = AbortController; + return browser.exports; +} + +var events$1 = {exports: {}}; + +var hasRequiredEvents$1; + +function requireEvents$1 () { + if (hasRequiredEvents$1) return events$1.exports; + hasRequiredEvents$1 = 1; + + var R = typeof Reflect === 'object' ? Reflect : null; + var ReflectApply = R && typeof R.apply === 'function' + ? R.apply + : function ReflectApply(target, receiver, args) { + return Function.prototype.apply.call(target, receiver, args); + }; + + var ReflectOwnKeys; + if (R && typeof R.ownKeys === 'function') { + ReflectOwnKeys = R.ownKeys; + } else if (Object.getOwnPropertySymbols) { + ReflectOwnKeys = function ReflectOwnKeys(target) { + return Object.getOwnPropertyNames(target) + .concat(Object.getOwnPropertySymbols(target)); + }; + } else { + ReflectOwnKeys = function ReflectOwnKeys(target) { + return Object.getOwnPropertyNames(target); + }; + } + + function ProcessEmitWarning(warning) { + if (console && console.warn) console.warn(warning); + } + + var NumberIsNaN = Number.isNaN || function NumberIsNaN(value) { + return value !== value; + }; + + function EventEmitter() { + EventEmitter.init.call(this); + } + events$1.exports = EventEmitter; + events$1.exports.once = once; + + // Backwards-compat with node 0.10.x + EventEmitter.EventEmitter = EventEmitter; + + EventEmitter.prototype._events = undefined; + EventEmitter.prototype._eventsCount = 0; + EventEmitter.prototype._maxListeners = undefined; + + // By default EventEmitters will print a warning if more than 10 listeners are + // added to it. This is a useful default which helps finding memory leaks. + var defaultMaxListeners = 10; + + function checkListener(listener) { + if (typeof listener !== 'function') { + throw new TypeError('The "listener" argument must be of type Function. Received type ' + typeof listener); + } + } + + Object.defineProperty(EventEmitter, 'defaultMaxListeners', { + enumerable: true, + get: function() { + return defaultMaxListeners; + }, + set: function(arg) { + if (typeof arg !== 'number' || arg < 0 || NumberIsNaN(arg)) { + throw new RangeError('The value of "defaultMaxListeners" is out of range. It must be a non-negative number. Received ' + arg + '.'); + } + defaultMaxListeners = arg; + } + }); + + EventEmitter.init = function() { + + if (this._events === undefined || + this._events === Object.getPrototypeOf(this)._events) { + this._events = Object.create(null); + this._eventsCount = 0; + } + + this._maxListeners = this._maxListeners || undefined; + }; + + // Obviously not all Emitters should be limited to 10. This function allows + // that to be increased. Set to zero for unlimited. + EventEmitter.prototype.setMaxListeners = function setMaxListeners(n) { + if (typeof n !== 'number' || n < 0 || NumberIsNaN(n)) { + throw new RangeError('The value of "n" is out of range. It must be a non-negative number. Received ' + n + '.'); + } + this._maxListeners = n; + return this; + }; + + function _getMaxListeners(that) { + if (that._maxListeners === undefined) + return EventEmitter.defaultMaxListeners; + return that._maxListeners; + } + + EventEmitter.prototype.getMaxListeners = function getMaxListeners() { + return _getMaxListeners(this); + }; + + EventEmitter.prototype.emit = function emit(type) { + var args = []; + for (var i = 1; i < arguments.length; i++) args.push(arguments[i]); + var doError = (type === 'error'); + + var events = this._events; + if (events !== undefined) + doError = (doError && events.error === undefined); + else if (!doError) + return false; + + // If there is no 'error' event listener then throw. + if (doError) { + var er; + if (args.length > 0) + er = args[0]; + if (er instanceof Error) { + // Note: The comments on the `throw` lines are intentional, they show + // up in Node's output if this results in an unhandled exception. + throw er; // Unhandled 'error' event + } + // At least give some kind of context to the user + var err = new Error('Unhandled error.' + (er ? ' (' + er.message + ')' : '')); + err.context = er; + throw err; // Unhandled 'error' event + } + + var handler = events[type]; + + if (handler === undefined) + return false; + + if (typeof handler === 'function') { + ReflectApply(handler, this, args); + } else { + var len = handler.length; + var listeners = arrayClone(handler, len); + for (var i = 0; i < len; ++i) + ReflectApply(listeners[i], this, args); + } + + return true; + }; + + function _addListener(target, type, listener, prepend) { + var m; + var events; + var existing; + + checkListener(listener); + + events = target._events; + if (events === undefined) { + events = target._events = Object.create(null); + target._eventsCount = 0; + } else { + // To avoid recursion in the case that type === "newListener"! Before + // adding it to the listeners, first emit "newListener". + if (events.newListener !== undefined) { + target.emit('newListener', type, + listener.listener ? listener.listener : listener); + + // Re-assign `events` because a newListener handler could have caused the + // this._events to be assigned to a new object + events = target._events; + } + existing = events[type]; + } + + if (existing === undefined) { + // Optimize the case of one listener. Don't need the extra array object. + existing = events[type] = listener; + ++target._eventsCount; + } else { + if (typeof existing === 'function') { + // Adding the second element, need to change to array. + existing = events[type] = + prepend ? [listener, existing] : [existing, listener]; + // If we've already got an array, just append. + } else if (prepend) { + existing.unshift(listener); + } else { + existing.push(listener); + } + + // Check for listener leak + m = _getMaxListeners(target); + if (m > 0 && existing.length > m && !existing.warned) { + existing.warned = true; + // No error code for this since it is a Warning + // eslint-disable-next-line no-restricted-syntax + var w = new Error('Possible EventEmitter memory leak detected. ' + + existing.length + ' ' + String(type) + ' listeners ' + + 'added. Use emitter.setMaxListeners() to ' + + 'increase limit'); + w.name = 'MaxListenersExceededWarning'; + w.emitter = target; + w.type = type; + w.count = existing.length; + ProcessEmitWarning(w); + } + } + + return target; + } + + EventEmitter.prototype.addListener = function addListener(type, listener) { + return _addListener(this, type, listener, false); + }; + + EventEmitter.prototype.on = EventEmitter.prototype.addListener; + + EventEmitter.prototype.prependListener = + function prependListener(type, listener) { + return _addListener(this, type, listener, true); + }; + + function onceWrapper() { + if (!this.fired) { + this.target.removeListener(this.type, this.wrapFn); + this.fired = true; + if (arguments.length === 0) + return this.listener.call(this.target); + return this.listener.apply(this.target, arguments); + } + } + + function _onceWrap(target, type, listener) { + var state = { fired: false, wrapFn: undefined, target: target, type: type, listener: listener }; + var wrapped = onceWrapper.bind(state); + wrapped.listener = listener; + state.wrapFn = wrapped; + return wrapped; + } + + EventEmitter.prototype.once = function once(type, listener) { + checkListener(listener); + this.on(type, _onceWrap(this, type, listener)); + return this; + }; + + EventEmitter.prototype.prependOnceListener = + function prependOnceListener(type, listener) { + checkListener(listener); + this.prependListener(type, _onceWrap(this, type, listener)); + return this; + }; + + // Emits a 'removeListener' event if and only if the listener was removed. + EventEmitter.prototype.removeListener = + function removeListener(type, listener) { + var list, events, position, i, originalListener; + + checkListener(listener); + + events = this._events; + if (events === undefined) + return this; + + list = events[type]; + if (list === undefined) + return this; + + if (list === listener || list.listener === listener) { + if (--this._eventsCount === 0) + this._events = Object.create(null); + else { + delete events[type]; + if (events.removeListener) + this.emit('removeListener', type, list.listener || listener); + } + } else if (typeof list !== 'function') { + position = -1; + + for (i = list.length - 1; i >= 0; i--) { + if (list[i] === listener || list[i].listener === listener) { + originalListener = list[i].listener; + position = i; + break; + } + } + + if (position < 0) + return this; + + if (position === 0) + list.shift(); + else { + spliceOne(list, position); + } + + if (list.length === 1) + events[type] = list[0]; + + if (events.removeListener !== undefined) + this.emit('removeListener', type, originalListener || listener); + } + + return this; + }; + + EventEmitter.prototype.off = EventEmitter.prototype.removeListener; + + EventEmitter.prototype.removeAllListeners = + function removeAllListeners(type) { + var listeners, events, i; + + events = this._events; + if (events === undefined) + return this; + + // not listening for removeListener, no need to emit + if (events.removeListener === undefined) { + if (arguments.length === 0) { + this._events = Object.create(null); + this._eventsCount = 0; + } else if (events[type] !== undefined) { + if (--this._eventsCount === 0) + this._events = Object.create(null); + else + delete events[type]; + } + return this; + } + + // emit removeListener for all listeners on all events + if (arguments.length === 0) { + var keys = Object.keys(events); + var key; + for (i = 0; i < keys.length; ++i) { + key = keys[i]; + if (key === 'removeListener') continue; + this.removeAllListeners(key); + } + this.removeAllListeners('removeListener'); + this._events = Object.create(null); + this._eventsCount = 0; + return this; + } + + listeners = events[type]; + + if (typeof listeners === 'function') { + this.removeListener(type, listeners); + } else if (listeners !== undefined) { + // LIFO order + for (i = listeners.length - 1; i >= 0; i--) { + this.removeListener(type, listeners[i]); + } + } + + return this; + }; + + function _listeners(target, type, unwrap) { + var events = target._events; + + if (events === undefined) + return []; + + var evlistener = events[type]; + if (evlistener === undefined) + return []; + + if (typeof evlistener === 'function') + return unwrap ? [evlistener.listener || evlistener] : [evlistener]; + + return unwrap ? + unwrapListeners(evlistener) : arrayClone(evlistener, evlistener.length); + } + + EventEmitter.prototype.listeners = function listeners(type) { + return _listeners(this, type, true); + }; + + EventEmitter.prototype.rawListeners = function rawListeners(type) { + return _listeners(this, type, false); + }; + + EventEmitter.listenerCount = function(emitter, type) { + if (typeof emitter.listenerCount === 'function') { + return emitter.listenerCount(type); + } else { + return listenerCount.call(emitter, type); + } + }; + + EventEmitter.prototype.listenerCount = listenerCount; + function listenerCount(type) { + var events = this._events; + + if (events !== undefined) { + var evlistener = events[type]; + + if (typeof evlistener === 'function') { + return 1; + } else if (evlistener !== undefined) { + return evlistener.length; + } + } + + return 0; + } + + EventEmitter.prototype.eventNames = function eventNames() { + return this._eventsCount > 0 ? ReflectOwnKeys(this._events) : []; + }; + + function arrayClone(arr, n) { + var copy = new Array(n); + for (var i = 0; i < n; ++i) + copy[i] = arr[i]; + return copy; + } + + function spliceOne(list, index) { + for (; index + 1 < list.length; index++) + list[index] = list[index + 1]; + list.pop(); + } + + function unwrapListeners(arr) { + var ret = new Array(arr.length); + for (var i = 0; i < ret.length; ++i) { + ret[i] = arr[i].listener || arr[i]; + } + return ret; + } + + function once(emitter, name) { + return new Promise(function (resolve, reject) { + function errorListener(err) { + emitter.removeListener(name, resolver); + reject(err); + } + + function resolver() { + if (typeof emitter.removeListener === 'function') { + emitter.removeListener('error', errorListener); + } + resolve([].slice.call(arguments)); + } + eventTargetAgnosticAddListener(emitter, name, resolver, { once: true }); + if (name !== 'error') { + addErrorHandlerIfEventEmitter(emitter, errorListener, { once: true }); + } + }); + } + + function addErrorHandlerIfEventEmitter(emitter, handler, flags) { + if (typeof emitter.on === 'function') { + eventTargetAgnosticAddListener(emitter, 'error', handler, flags); + } + } + + function eventTargetAgnosticAddListener(emitter, name, listener, flags) { + if (typeof emitter.on === 'function') { + if (flags.once) { + emitter.once(name, listener); + } else { + emitter.on(name, listener); + } + } else if (typeof emitter.addEventListener === 'function') { + // EventTarget does not have `error` event semantics like Node + // EventEmitters, we do not listen for `error` events here. + emitter.addEventListener(name, function wrapListener(arg) { + // IE does not have builtin `{ once: true }` support so we + // have to do it manually. + if (flags.once) { + emitter.removeEventListener(name, wrapListener); + } + listener(arg); + }); + } else { + throw new TypeError('The "emitter" argument must be of type EventEmitter. Received type ' + typeof emitter); + } + } + return events$1.exports; +} + +var hasRequiredUtil$2; + +function requireUtil$2 () { + if (hasRequiredUtil$2) return util$2.exports; + hasRequiredUtil$2 = 1; + (function (module) { + + const bufferModule = require$$0$1; + const { format, inspect } = requireInspect(); + const { + codes: { ERR_INVALID_ARG_TYPE } + } = requireErrors(); + const { kResistStopPropagation, AggregateError, SymbolDispose } = requirePrimordials(); + const AbortSignal = globalThis.AbortSignal || requireBrowser$1().AbortSignal; + const AbortController = globalThis.AbortController || requireBrowser$1().AbortController; + const AsyncFunction = Object.getPrototypeOf(async function () {}).constructor; + const Blob = globalThis.Blob || bufferModule.Blob; + /* eslint-disable indent */ + const isBlob = + typeof Blob !== 'undefined' + ? function isBlob(b) { + // eslint-disable-next-line indent + return b instanceof Blob + } + : function isBlob(b) { + return false + }; + /* eslint-enable indent */ + + const validateAbortSignal = (signal, name) => { + if (signal !== undefined && (signal === null || typeof signal !== 'object' || !('aborted' in signal))) { + throw new ERR_INVALID_ARG_TYPE(name, 'AbortSignal', signal) + } + }; + const validateFunction = (value, name) => { + if (typeof value !== 'function') { + throw new ERR_INVALID_ARG_TYPE(name, 'Function', value) + } + }; + module.exports = { + AggregateError, + kEmptyObject: Object.freeze({}), + once(callback) { + let called = false; + return function (...args) { + if (called) { + return + } + called = true; + callback.apply(this, args); + } + }, + createDeferredPromise: function () { + let resolve; + let reject; + + // eslint-disable-next-line promise/param-names + const promise = new Promise((res, rej) => { + resolve = res; + reject = rej; + }); + return { + promise, + resolve, + reject + } + }, + promisify(fn) { + return new Promise((resolve, reject) => { + fn((err, ...args) => { + if (err) { + return reject(err) + } + return resolve(...args) + }); + }) + }, + debuglog() { + return function () {} + }, + format, + inspect, + types: { + isAsyncFunction(fn) { + return fn instanceof AsyncFunction + }, + isArrayBufferView(arr) { + return ArrayBuffer.isView(arr) + } + }, + isBlob, + deprecate(fn, message) { + return fn + }, + addAbortListener: + requireEvents$1().addAbortListener || + function addAbortListener(signal, listener) { + if (signal === undefined) { + throw new ERR_INVALID_ARG_TYPE('signal', 'AbortSignal', signal) + } + validateAbortSignal(signal, 'signal'); + validateFunction(listener, 'listener'); + let removeEventListener; + if (signal.aborted) { + queueMicrotask(() => listener()); + } else { + signal.addEventListener('abort', listener, { + __proto__: null, + once: true, + [kResistStopPropagation]: true + }); + removeEventListener = () => { + signal.removeEventListener('abort', listener); + }; + } + return { + __proto__: null, + [SymbolDispose]() { + var _removeEventListener + ;(_removeEventListener = removeEventListener) === null || _removeEventListener === undefined + ? undefined + : _removeEventListener(); + } + } + }, + AbortSignalAny: + AbortSignal.any || + function AbortSignalAny(signals) { + // Fast path if there is only one signal. + if (signals.length === 1) { + return signals[0] + } + const ac = new AbortController(); + const abort = () => ac.abort(); + signals.forEach((signal) => { + validateAbortSignal(signal, 'signals'); + signal.addEventListener('abort', abort, { + once: true + }); + }); + ac.signal.addEventListener( + 'abort', + () => { + signals.forEach((signal) => signal.removeEventListener('abort', abort)); + }, + { + once: true + } + ); + return ac.signal + } + }; + module.exports.promisify.custom = Symbol.for('nodejs.util.promisify.custom'); + } (util$2)); + return util$2.exports; +} + +var operators = {}; + +/* eslint jsdoc/require-jsdoc: "error" */ + +var validators; +var hasRequiredValidators; + +function requireValidators () { + if (hasRequiredValidators) return validators; + hasRequiredValidators = 1; + + const { + ArrayIsArray, + ArrayPrototypeIncludes, + ArrayPrototypeJoin, + ArrayPrototypeMap, + NumberIsInteger, + NumberIsNaN, + NumberMAX_SAFE_INTEGER, + NumberMIN_SAFE_INTEGER, + NumberParseInt, + ObjectPrototypeHasOwnProperty, + RegExpPrototypeExec, + String, + StringPrototypeToUpperCase, + StringPrototypeTrim + } = requirePrimordials(); + const { + hideStackFrames, + codes: { ERR_SOCKET_BAD_PORT, ERR_INVALID_ARG_TYPE, ERR_INVALID_ARG_VALUE, ERR_OUT_OF_RANGE, ERR_UNKNOWN_SIGNAL } + } = requireErrors(); + const { normalizeEncoding } = requireUtil$2(); + const { isAsyncFunction, isArrayBufferView } = requireUtil$2().types; + const signals = {}; + + /** + * @param {*} value + * @returns {boolean} + */ + function isInt32(value) { + return value === (value | 0) + } + + /** + * @param {*} value + * @returns {boolean} + */ + function isUint32(value) { + return value === value >>> 0 + } + const octalReg = /^[0-7]+$/; + const modeDesc = 'must be a 32-bit unsigned integer or an octal string'; + + /** + * Parse and validate values that will be converted into mode_t (the S_* + * constants). Only valid numbers and octal strings are allowed. They could be + * converted to 32-bit unsigned integers or non-negative signed integers in the + * C++ land, but any value higher than 0o777 will result in platform-specific + * behaviors. + * @param {*} value Values to be validated + * @param {string} name Name of the argument + * @param {number} [def] If specified, will be returned for invalid values + * @returns {number} + */ + function parseFileMode(value, name, def) { + if (typeof value === 'undefined') { + value = def; + } + if (typeof value === 'string') { + if (RegExpPrototypeExec(octalReg, value) === null) { + throw new ERR_INVALID_ARG_VALUE(name, value, modeDesc) + } + value = NumberParseInt(value, 8); + } + validateUint32(value, name); + return value + } + + /** + * @callback validateInteger + * @param {*} value + * @param {string} name + * @param {number} [min] + * @param {number} [max] + * @returns {asserts value is number} + */ + + /** @type {validateInteger} */ + const validateInteger = hideStackFrames((value, name, min = NumberMIN_SAFE_INTEGER, max = NumberMAX_SAFE_INTEGER) => { + if (typeof value !== 'number') throw new ERR_INVALID_ARG_TYPE(name, 'number', value) + if (!NumberIsInteger(value)) throw new ERR_OUT_OF_RANGE(name, 'an integer', value) + if (value < min || value > max) throw new ERR_OUT_OF_RANGE(name, `>= ${min} && <= ${max}`, value) + }); + + /** + * @callback validateInt32 + * @param {*} value + * @param {string} name + * @param {number} [min] + * @param {number} [max] + * @returns {asserts value is number} + */ + + /** @type {validateInt32} */ + const validateInt32 = hideStackFrames((value, name, min = -2147483648, max = 2147483647) => { + // The defaults for min and max correspond to the limits of 32-bit integers. + if (typeof value !== 'number') { + throw new ERR_INVALID_ARG_TYPE(name, 'number', value) + } + if (!NumberIsInteger(value)) { + throw new ERR_OUT_OF_RANGE(name, 'an integer', value) + } + if (value < min || value > max) { + throw new ERR_OUT_OF_RANGE(name, `>= ${min} && <= ${max}`, value) + } + }); + + /** + * @callback validateUint32 + * @param {*} value + * @param {string} name + * @param {number|boolean} [positive=false] + * @returns {asserts value is number} + */ + + /** @type {validateUint32} */ + const validateUint32 = hideStackFrames((value, name, positive = false) => { + if (typeof value !== 'number') { + throw new ERR_INVALID_ARG_TYPE(name, 'number', value) + } + if (!NumberIsInteger(value)) { + throw new ERR_OUT_OF_RANGE(name, 'an integer', value) + } + const min = positive ? 1 : 0; + // 2 ** 32 === 4294967296 + const max = 4294967295; + if (value < min || value > max) { + throw new ERR_OUT_OF_RANGE(name, `>= ${min} && <= ${max}`, value) + } + }); + + /** + * @callback validateString + * @param {*} value + * @param {string} name + * @returns {asserts value is string} + */ + + /** @type {validateString} */ + function validateString(value, name) { + if (typeof value !== 'string') throw new ERR_INVALID_ARG_TYPE(name, 'string', value) + } + + /** + * @callback validateNumber + * @param {*} value + * @param {string} name + * @param {number} [min] + * @param {number} [max] + * @returns {asserts value is number} + */ + + /** @type {validateNumber} */ + function validateNumber(value, name, min = undefined, max) { + if (typeof value !== 'number') throw new ERR_INVALID_ARG_TYPE(name, 'number', value) + if ( + (min != null && value < min) || + (max != null && value > max) || + ((min != null || max != null) && NumberIsNaN(value)) + ) { + throw new ERR_OUT_OF_RANGE( + name, + `${min != null ? `>= ${min}` : ''}${min != null && max != null ? ' && ' : ''}${max != null ? `<= ${max}` : ''}`, + value + ) + } + } + + /** + * @callback validateOneOf + * @template T + * @param {T} value + * @param {string} name + * @param {T[]} oneOf + */ + + /** @type {validateOneOf} */ + const validateOneOf = hideStackFrames((value, name, oneOf) => { + if (!ArrayPrototypeIncludes(oneOf, value)) { + const allowed = ArrayPrototypeJoin( + ArrayPrototypeMap(oneOf, (v) => (typeof v === 'string' ? `'${v}'` : String(v))), + ', ' + ); + const reason = 'must be one of: ' + allowed; + throw new ERR_INVALID_ARG_VALUE(name, value, reason) + } + }); + + /** + * @callback validateBoolean + * @param {*} value + * @param {string} name + * @returns {asserts value is boolean} + */ + + /** @type {validateBoolean} */ + function validateBoolean(value, name) { + if (typeof value !== 'boolean') throw new ERR_INVALID_ARG_TYPE(name, 'boolean', value) + } + + /** + * @param {any} options + * @param {string} key + * @param {boolean} defaultValue + * @returns {boolean} + */ + function getOwnPropertyValueOrDefault(options, key, defaultValue) { + return options == null || !ObjectPrototypeHasOwnProperty(options, key) ? defaultValue : options[key] + } + + /** + * @callback validateObject + * @param {*} value + * @param {string} name + * @param {{ + * allowArray?: boolean, + * allowFunction?: boolean, + * nullable?: boolean + * }} [options] + */ + + /** @type {validateObject} */ + const validateObject = hideStackFrames((value, name, options = null) => { + const allowArray = getOwnPropertyValueOrDefault(options, 'allowArray', false); + const allowFunction = getOwnPropertyValueOrDefault(options, 'allowFunction', false); + const nullable = getOwnPropertyValueOrDefault(options, 'nullable', false); + if ( + (!nullable && value === null) || + (!allowArray && ArrayIsArray(value)) || + (typeof value !== 'object' && (!allowFunction || typeof value !== 'function')) + ) { + throw new ERR_INVALID_ARG_TYPE(name, 'Object', value) + } + }); + + /** + * @callback validateDictionary - We are using the Web IDL Standard definition + * of "dictionary" here, which means any value + * whose Type is either Undefined, Null, or + * Object (which includes functions). + * @param {*} value + * @param {string} name + * @see https://webidl.spec.whatwg.org/#es-dictionary + * @see https://tc39.es/ecma262/#table-typeof-operator-results + */ + + /** @type {validateDictionary} */ + const validateDictionary = hideStackFrames((value, name) => { + if (value != null && typeof value !== 'object' && typeof value !== 'function') { + throw new ERR_INVALID_ARG_TYPE(name, 'a dictionary', value) + } + }); + + /** + * @callback validateArray + * @param {*} value + * @param {string} name + * @param {number} [minLength] + * @returns {asserts value is any[]} + */ + + /** @type {validateArray} */ + const validateArray = hideStackFrames((value, name, minLength = 0) => { + if (!ArrayIsArray(value)) { + throw new ERR_INVALID_ARG_TYPE(name, 'Array', value) + } + if (value.length < minLength) { + const reason = `must be longer than ${minLength}`; + throw new ERR_INVALID_ARG_VALUE(name, value, reason) + } + }); + + /** + * @callback validateStringArray + * @param {*} value + * @param {string} name + * @returns {asserts value is string[]} + */ + + /** @type {validateStringArray} */ + function validateStringArray(value, name) { + validateArray(value, name); + for (let i = 0; i < value.length; i++) { + validateString(value[i], `${name}[${i}]`); + } + } + + /** + * @callback validateBooleanArray + * @param {*} value + * @param {string} name + * @returns {asserts value is boolean[]} + */ + + /** @type {validateBooleanArray} */ + function validateBooleanArray(value, name) { + validateArray(value, name); + for (let i = 0; i < value.length; i++) { + validateBoolean(value[i], `${name}[${i}]`); + } + } + + /** + * @callback validateAbortSignalArray + * @param {*} value + * @param {string} name + * @returns {asserts value is AbortSignal[]} + */ + + /** @type {validateAbortSignalArray} */ + function validateAbortSignalArray(value, name) { + validateArray(value, name); + for (let i = 0; i < value.length; i++) { + const signal = value[i]; + const indexedName = `${name}[${i}]`; + if (signal == null) { + throw new ERR_INVALID_ARG_TYPE(indexedName, 'AbortSignal', signal) + } + validateAbortSignal(signal, indexedName); + } + } + + /** + * @param {*} signal + * @param {string} [name='signal'] + * @returns {asserts signal is keyof signals} + */ + function validateSignalName(signal, name = 'signal') { + validateString(signal, name); + if (signals[signal] === undefined) { + if (signals[StringPrototypeToUpperCase(signal)] !== undefined) { + throw new ERR_UNKNOWN_SIGNAL(signal + ' (signals must use all capital letters)') + } + throw new ERR_UNKNOWN_SIGNAL(signal) + } + } + + /** + * @callback validateBuffer + * @param {*} buffer + * @param {string} [name='buffer'] + * @returns {asserts buffer is ArrayBufferView} + */ + + /** @type {validateBuffer} */ + const validateBuffer = hideStackFrames((buffer, name = 'buffer') => { + if (!isArrayBufferView(buffer)) { + throw new ERR_INVALID_ARG_TYPE(name, ['Buffer', 'TypedArray', 'DataView'], buffer) + } + }); + + /** + * @param {string} data + * @param {string} encoding + */ + function validateEncoding(data, encoding) { + const normalizedEncoding = normalizeEncoding(encoding); + const length = data.length; + if (normalizedEncoding === 'hex' && length % 2 !== 0) { + throw new ERR_INVALID_ARG_VALUE('encoding', encoding, `is invalid for data of length ${length}`) + } + } + + /** + * Check that the port number is not NaN when coerced to a number, + * is an integer and that it falls within the legal range of port numbers. + * @param {*} port + * @param {string} [name='Port'] + * @param {boolean} [allowZero=true] + * @returns {number} + */ + function validatePort(port, name = 'Port', allowZero = true) { + if ( + (typeof port !== 'number' && typeof port !== 'string') || + (typeof port === 'string' && StringPrototypeTrim(port).length === 0) || + +port !== +port >>> 0 || + port > 0xffff || + (port === 0 && !allowZero) + ) { + throw new ERR_SOCKET_BAD_PORT(name, port, allowZero) + } + return port | 0 + } + + /** + * @callback validateAbortSignal + * @param {*} signal + * @param {string} name + */ + + /** @type {validateAbortSignal} */ + const validateAbortSignal = hideStackFrames((signal, name) => { + if (signal !== undefined && (signal === null || typeof signal !== 'object' || !('aborted' in signal))) { + throw new ERR_INVALID_ARG_TYPE(name, 'AbortSignal', signal) + } + }); + + /** + * @callback validateFunction + * @param {*} value + * @param {string} name + * @returns {asserts value is Function} + */ + + /** @type {validateFunction} */ + const validateFunction = hideStackFrames((value, name) => { + if (typeof value !== 'function') throw new ERR_INVALID_ARG_TYPE(name, 'Function', value) + }); + + /** + * @callback validatePlainFunction + * @param {*} value + * @param {string} name + * @returns {asserts value is Function} + */ + + /** @type {validatePlainFunction} */ + const validatePlainFunction = hideStackFrames((value, name) => { + if (typeof value !== 'function' || isAsyncFunction(value)) throw new ERR_INVALID_ARG_TYPE(name, 'Function', value) + }); + + /** + * @callback validateUndefined + * @param {*} value + * @param {string} name + * @returns {asserts value is undefined} + */ + + /** @type {validateUndefined} */ + const validateUndefined = hideStackFrames((value, name) => { + if (value !== undefined) throw new ERR_INVALID_ARG_TYPE(name, 'undefined', value) + }); + + /** + * @template T + * @param {T} value + * @param {string} name + * @param {T[]} union + */ + function validateUnion(value, name, union) { + if (!ArrayPrototypeIncludes(union, value)) { + throw new ERR_INVALID_ARG_TYPE(name, `('${ArrayPrototypeJoin(union, '|')}')`, value) + } + } + + /* + The rules for the Link header field are described here: + https://www.rfc-editor.org/rfc/rfc8288.html#section-3 + + This regex validates any string surrounded by angle brackets + (not necessarily a valid URI reference) followed by zero or more + link-params separated by semicolons. + */ + const linkValueRegExp = /^(?:<[^>]*>)(?:\s*;\s*[^;"\s]+(?:=(")?[^;"\s]*\1)?)*$/; + + /** + * @param {any} value + * @param {string} name + */ + function validateLinkHeaderFormat(value, name) { + if (typeof value === 'undefined' || !RegExpPrototypeExec(linkValueRegExp, value)) { + throw new ERR_INVALID_ARG_VALUE( + name, + value, + 'must be an array or string of format "; rel=preload; as=style"' + ) + } + } + + /** + * @param {any} hints + * @return {string} + */ + function validateLinkHeaderValue(hints) { + if (typeof hints === 'string') { + validateLinkHeaderFormat(hints, 'hints'); + return hints + } else if (ArrayIsArray(hints)) { + const hintsLength = hints.length; + let result = ''; + if (hintsLength === 0) { + return result + } + for (let i = 0; i < hintsLength; i++) { + const link = hints[i]; + validateLinkHeaderFormat(link, 'hints'); + result += link; + if (i !== hintsLength - 1) { + result += ', '; + } + } + return result + } + throw new ERR_INVALID_ARG_VALUE( + 'hints', + hints, + 'must be an array or string of format "; rel=preload; as=style"' + ) + } + validators = { + isInt32, + isUint32, + parseFileMode, + validateArray, + validateStringArray, + validateBooleanArray, + validateAbortSignalArray, + validateBoolean, + validateBuffer, + validateDictionary, + validateEncoding, + validateFunction, + validateInt32, + validateInteger, + validateNumber, + validateObject, + validateOneOf, + validatePlainFunction, + validatePort, + validateSignalName, + validateString, + validateUint32, + validateUndefined, + validateUnion, + validateAbortSignal, + validateLinkHeaderValue + }; + return validators; +} + +var endOfStream = {exports: {}}; + +var utils; +var hasRequiredUtils; + +function requireUtils () { + if (hasRequiredUtils) return utils; + hasRequiredUtils = 1; + + const { SymbolAsyncIterator, SymbolIterator, SymbolFor } = requirePrimordials(); + + // We need to use SymbolFor to make these globally available + // for interopt with readable-stream, i.e. readable-stream + // and node core needs to be able to read/write private state + // from each other for proper interoperability. + const kIsDestroyed = SymbolFor('nodejs.stream.destroyed'); + const kIsErrored = SymbolFor('nodejs.stream.errored'); + const kIsReadable = SymbolFor('nodejs.stream.readable'); + const kIsWritable = SymbolFor('nodejs.stream.writable'); + const kIsDisturbed = SymbolFor('nodejs.stream.disturbed'); + const kIsClosedPromise = SymbolFor('nodejs.webstream.isClosedPromise'); + const kControllerErrorFunction = SymbolFor('nodejs.webstream.controllerErrorFunction'); + function isReadableNodeStream(obj, strict = false) { + var _obj$_readableState; + return !!( + ( + obj && + typeof obj.pipe === 'function' && + typeof obj.on === 'function' && + (!strict || (typeof obj.pause === 'function' && typeof obj.resume === 'function')) && + (!obj._writableState || + ((_obj$_readableState = obj._readableState) === null || _obj$_readableState === undefined + ? undefined + : _obj$_readableState.readable) !== false) && + // Duplex + (!obj._writableState || obj._readableState) + ) // Writable has .pipe. + ) + } + function isWritableNodeStream(obj) { + var _obj$_writableState; + return !!( + ( + obj && + typeof obj.write === 'function' && + typeof obj.on === 'function' && + (!obj._readableState || + ((_obj$_writableState = obj._writableState) === null || _obj$_writableState === undefined + ? undefined + : _obj$_writableState.writable) !== false) + ) // Duplex + ) + } + function isDuplexNodeStream(obj) { + return !!( + obj && + typeof obj.pipe === 'function' && + obj._readableState && + typeof obj.on === 'function' && + typeof obj.write === 'function' + ) + } + function isNodeStream(obj) { + return ( + obj && + (obj._readableState || + obj._writableState || + (typeof obj.write === 'function' && typeof obj.on === 'function') || + (typeof obj.pipe === 'function' && typeof obj.on === 'function')) + ) + } + function isReadableStream(obj) { + return !!( + obj && + !isNodeStream(obj) && + typeof obj.pipeThrough === 'function' && + typeof obj.getReader === 'function' && + typeof obj.cancel === 'function' + ) + } + function isWritableStream(obj) { + return !!(obj && !isNodeStream(obj) && typeof obj.getWriter === 'function' && typeof obj.abort === 'function') + } + function isTransformStream(obj) { + return !!(obj && !isNodeStream(obj) && typeof obj.readable === 'object' && typeof obj.writable === 'object') + } + function isWebStream(obj) { + return isReadableStream(obj) || isWritableStream(obj) || isTransformStream(obj) + } + function isIterable(obj, isAsync) { + if (obj == null) return false + if (isAsync === true) return typeof obj[SymbolAsyncIterator] === 'function' + if (isAsync === false) return typeof obj[SymbolIterator] === 'function' + return typeof obj[SymbolAsyncIterator] === 'function' || typeof obj[SymbolIterator] === 'function' + } + function isDestroyed(stream) { + if (!isNodeStream(stream)) return null + const wState = stream._writableState; + const rState = stream._readableState; + const state = wState || rState; + return !!(stream.destroyed || stream[kIsDestroyed] || (state !== null && state !== undefined && state.destroyed)) + } + + // Have been end():d. + function isWritableEnded(stream) { + if (!isWritableNodeStream(stream)) return null + if (stream.writableEnded === true) return true + const wState = stream._writableState; + if (wState !== null && wState !== undefined && wState.errored) return false + if (typeof (wState === null || wState === undefined ? undefined : wState.ended) !== 'boolean') return null + return wState.ended + } + + // Have emitted 'finish'. + function isWritableFinished(stream, strict) { + if (!isWritableNodeStream(stream)) return null + if (stream.writableFinished === true) return true + const wState = stream._writableState; + if (wState !== null && wState !== undefined && wState.errored) return false + if (typeof (wState === null || wState === undefined ? undefined : wState.finished) !== 'boolean') return null + return !!(wState.finished || (strict === false && wState.ended === true && wState.length === 0)) + } + + // Have been push(null):d. + function isReadableEnded(stream) { + if (!isReadableNodeStream(stream)) return null + if (stream.readableEnded === true) return true + const rState = stream._readableState; + if (!rState || rState.errored) return false + if (typeof (rState === null || rState === undefined ? undefined : rState.ended) !== 'boolean') return null + return rState.ended + } + + // Have emitted 'end'. + function isReadableFinished(stream, strict) { + if (!isReadableNodeStream(stream)) return null + const rState = stream._readableState; + if (rState !== null && rState !== undefined && rState.errored) return false + if (typeof (rState === null || rState === undefined ? undefined : rState.endEmitted) !== 'boolean') return null + return !!(rState.endEmitted || (strict === false && rState.ended === true && rState.length === 0)) + } + function isReadable(stream) { + if (stream && stream[kIsReadable] != null) return stream[kIsReadable] + if (typeof (stream === null || stream === undefined ? undefined : stream.readable) !== 'boolean') return null + if (isDestroyed(stream)) return false + return isReadableNodeStream(stream) && stream.readable && !isReadableFinished(stream) + } + function isWritable(stream) { + if (stream && stream[kIsWritable] != null) return stream[kIsWritable] + if (typeof (stream === null || stream === undefined ? undefined : stream.writable) !== 'boolean') return null + if (isDestroyed(stream)) return false + return isWritableNodeStream(stream) && stream.writable && !isWritableEnded(stream) + } + function isFinished(stream, opts) { + if (!isNodeStream(stream)) { + return null + } + if (isDestroyed(stream)) { + return true + } + if ((opts === null || opts === undefined ? undefined : opts.readable) !== false && isReadable(stream)) { + return false + } + if ((opts === null || opts === undefined ? undefined : opts.writable) !== false && isWritable(stream)) { + return false + } + return true + } + function isWritableErrored(stream) { + var _stream$_writableStat, _stream$_writableStat2; + if (!isNodeStream(stream)) { + return null + } + if (stream.writableErrored) { + return stream.writableErrored + } + return (_stream$_writableStat = + (_stream$_writableStat2 = stream._writableState) === null || _stream$_writableStat2 === undefined + ? undefined + : _stream$_writableStat2.errored) !== null && _stream$_writableStat !== undefined + ? _stream$_writableStat + : null + } + function isReadableErrored(stream) { + var _stream$_readableStat, _stream$_readableStat2; + if (!isNodeStream(stream)) { + return null + } + if (stream.readableErrored) { + return stream.readableErrored + } + return (_stream$_readableStat = + (_stream$_readableStat2 = stream._readableState) === null || _stream$_readableStat2 === undefined + ? undefined + : _stream$_readableStat2.errored) !== null && _stream$_readableStat !== undefined + ? _stream$_readableStat + : null + } + function isClosed(stream) { + if (!isNodeStream(stream)) { + return null + } + if (typeof stream.closed === 'boolean') { + return stream.closed + } + const wState = stream._writableState; + const rState = stream._readableState; + if ( + typeof (wState === null || wState === undefined ? undefined : wState.closed) === 'boolean' || + typeof (rState === null || rState === undefined ? undefined : rState.closed) === 'boolean' + ) { + return ( + (wState === null || wState === undefined ? undefined : wState.closed) || + (rState === null || rState === undefined ? undefined : rState.closed) + ) + } + if (typeof stream._closed === 'boolean' && isOutgoingMessage(stream)) { + return stream._closed + } + return null + } + function isOutgoingMessage(stream) { + return ( + typeof stream._closed === 'boolean' && + typeof stream._defaultKeepAlive === 'boolean' && + typeof stream._removedConnection === 'boolean' && + typeof stream._removedContLen === 'boolean' + ) + } + function isServerResponse(stream) { + return typeof stream._sent100 === 'boolean' && isOutgoingMessage(stream) + } + function isServerRequest(stream) { + var _stream$req; + return ( + typeof stream._consuming === 'boolean' && + typeof stream._dumped === 'boolean' && + ((_stream$req = stream.req) === null || _stream$req === undefined ? undefined : _stream$req.upgradeOrConnect) === + undefined + ) + } + function willEmitClose(stream) { + if (!isNodeStream(stream)) return null + const wState = stream._writableState; + const rState = stream._readableState; + const state = wState || rState; + return ( + (!state && isServerResponse(stream)) || !!(state && state.autoDestroy && state.emitClose && state.closed === false) + ) + } + function isDisturbed(stream) { + var _stream$kIsDisturbed; + return !!( + stream && + ((_stream$kIsDisturbed = stream[kIsDisturbed]) !== null && _stream$kIsDisturbed !== undefined + ? _stream$kIsDisturbed + : stream.readableDidRead || stream.readableAborted) + ) + } + function isErrored(stream) { + var _ref, + _ref2, + _ref3, + _ref4, + _ref5, + _stream$kIsErrored, + _stream$_readableStat3, + _stream$_writableStat3, + _stream$_readableStat4, + _stream$_writableStat4; + return !!( + stream && + ((_ref = + (_ref2 = + (_ref3 = + (_ref4 = + (_ref5 = + (_stream$kIsErrored = stream[kIsErrored]) !== null && _stream$kIsErrored !== undefined + ? _stream$kIsErrored + : stream.readableErrored) !== null && _ref5 !== undefined + ? _ref5 + : stream.writableErrored) !== null && _ref4 !== undefined + ? _ref4 + : (_stream$_readableStat3 = stream._readableState) === null || _stream$_readableStat3 === undefined + ? undefined + : _stream$_readableStat3.errorEmitted) !== null && _ref3 !== undefined + ? _ref3 + : (_stream$_writableStat3 = stream._writableState) === null || _stream$_writableStat3 === undefined + ? undefined + : _stream$_writableStat3.errorEmitted) !== null && _ref2 !== undefined + ? _ref2 + : (_stream$_readableStat4 = stream._readableState) === null || _stream$_readableStat4 === undefined + ? undefined + : _stream$_readableStat4.errored) !== null && _ref !== undefined + ? _ref + : (_stream$_writableStat4 = stream._writableState) === null || _stream$_writableStat4 === undefined + ? undefined + : _stream$_writableStat4.errored) + ) + } + utils = { + isDestroyed, + kIsDestroyed, + isDisturbed, + kIsDisturbed, + isErrored, + kIsErrored, + isReadable, + kIsReadable, + kIsClosedPromise, + kControllerErrorFunction, + kIsWritable, + isClosed, + isDuplexNodeStream, + isFinished, + isIterable, + isReadableNodeStream, + isReadableStream, + isReadableEnded, + isReadableFinished, + isReadableErrored, + isNodeStream, + isWebStream, + isWritable, + isWritableNodeStream, + isWritableStream, + isWritableEnded, + isWritableFinished, + isWritableErrored, + isServerRequest, + isServerResponse, + willEmitClose, + isTransformStream + }; + return utils; +} + +var hasRequiredEndOfStream; + +function requireEndOfStream () { + if (hasRequiredEndOfStream) return endOfStream.exports; + hasRequiredEndOfStream = 1; + + /* replacement start */ + + const process = requireBrowser$2(); + + /* replacement end */ + + const { AbortError, codes } = requireErrors(); + const { ERR_INVALID_ARG_TYPE, ERR_STREAM_PREMATURE_CLOSE } = codes; + const { kEmptyObject, once } = requireUtil$2(); + const { validateAbortSignal, validateFunction, validateObject, validateBoolean } = requireValidators(); + const { Promise, PromisePrototypeThen, SymbolDispose } = requirePrimordials(); + const { + isClosed, + isReadable, + isReadableNodeStream, + isReadableStream, + isReadableFinished, + isReadableErrored, + isWritable, + isWritableNodeStream, + isWritableStream, + isWritableFinished, + isWritableErrored, + isNodeStream, + willEmitClose: _willEmitClose, + kIsClosedPromise + } = requireUtils(); + let addAbortListener; + function isRequest(stream) { + return stream.setHeader && typeof stream.abort === 'function' + } + const nop = () => {}; + function eos(stream, options, callback) { + var _options$readable, _options$writable; + if (arguments.length === 2) { + callback = options; + options = kEmptyObject; + } else if (options == null) { + options = kEmptyObject; + } else { + validateObject(options, 'options'); + } + validateFunction(callback, 'callback'); + validateAbortSignal(options.signal, 'options.signal'); + callback = once(callback); + if (isReadableStream(stream) || isWritableStream(stream)) { + return eosWeb(stream, options, callback) + } + if (!isNodeStream(stream)) { + throw new ERR_INVALID_ARG_TYPE('stream', ['ReadableStream', 'WritableStream', 'Stream'], stream) + } + const readable = + (_options$readable = options.readable) !== null && _options$readable !== undefined + ? _options$readable + : isReadableNodeStream(stream); + const writable = + (_options$writable = options.writable) !== null && _options$writable !== undefined + ? _options$writable + : isWritableNodeStream(stream); + const wState = stream._writableState; + const rState = stream._readableState; + const onlegacyfinish = () => { + if (!stream.writable) { + onfinish(); + } + }; + + // TODO (ronag): Improve soft detection to include core modules and + // common ecosystem modules that do properly emit 'close' but fail + // this generic check. + let willEmitClose = + _willEmitClose(stream) && isReadableNodeStream(stream) === readable && isWritableNodeStream(stream) === writable; + let writableFinished = isWritableFinished(stream, false); + const onfinish = () => { + writableFinished = true; + // Stream should not be destroyed here. If it is that + // means that user space is doing something differently and + // we cannot trust willEmitClose. + if (stream.destroyed) { + willEmitClose = false; + } + if (willEmitClose && (!stream.readable || readable)) { + return + } + if (!readable || readableFinished) { + callback.call(stream); + } + }; + let readableFinished = isReadableFinished(stream, false); + const onend = () => { + readableFinished = true; + // Stream should not be destroyed here. If it is that + // means that user space is doing something differently and + // we cannot trust willEmitClose. + if (stream.destroyed) { + willEmitClose = false; + } + if (willEmitClose && (!stream.writable || writable)) { + return + } + if (!writable || writableFinished) { + callback.call(stream); + } + }; + const onerror = (err) => { + callback.call(stream, err); + }; + let closed = isClosed(stream); + const onclose = () => { + closed = true; + const errored = isWritableErrored(stream) || isReadableErrored(stream); + if (errored && typeof errored !== 'boolean') { + return callback.call(stream, errored) + } + if (readable && !readableFinished && isReadableNodeStream(stream, true)) { + if (!isReadableFinished(stream, false)) return callback.call(stream, new ERR_STREAM_PREMATURE_CLOSE()) + } + if (writable && !writableFinished) { + if (!isWritableFinished(stream, false)) return callback.call(stream, new ERR_STREAM_PREMATURE_CLOSE()) + } + callback.call(stream); + }; + const onclosed = () => { + closed = true; + const errored = isWritableErrored(stream) || isReadableErrored(stream); + if (errored && typeof errored !== 'boolean') { + return callback.call(stream, errored) + } + callback.call(stream); + }; + const onrequest = () => { + stream.req.on('finish', onfinish); + }; + if (isRequest(stream)) { + stream.on('complete', onfinish); + if (!willEmitClose) { + stream.on('abort', onclose); + } + if (stream.req) { + onrequest(); + } else { + stream.on('request', onrequest); + } + } else if (writable && !wState) { + // legacy streams + stream.on('end', onlegacyfinish); + stream.on('close', onlegacyfinish); + } + + // Not all streams will emit 'close' after 'aborted'. + if (!willEmitClose && typeof stream.aborted === 'boolean') { + stream.on('aborted', onclose); + } + stream.on('end', onend); + stream.on('finish', onfinish); + if (options.error !== false) { + stream.on('error', onerror); + } + stream.on('close', onclose); + if (closed) { + process.nextTick(onclose); + } else if ( + (wState !== null && wState !== undefined && wState.errorEmitted) || + (rState !== null && rState !== undefined && rState.errorEmitted) + ) { + if (!willEmitClose) { + process.nextTick(onclosed); + } + } else if ( + !readable && + (!willEmitClose || isReadable(stream)) && + (writableFinished || isWritable(stream) === false) + ) { + process.nextTick(onclosed); + } else if ( + !writable && + (!willEmitClose || isWritable(stream)) && + (readableFinished || isReadable(stream) === false) + ) { + process.nextTick(onclosed); + } else if (rState && stream.req && stream.aborted) { + process.nextTick(onclosed); + } + const cleanup = () => { + callback = nop; + stream.removeListener('aborted', onclose); + stream.removeListener('complete', onfinish); + stream.removeListener('abort', onclose); + stream.removeListener('request', onrequest); + if (stream.req) stream.req.removeListener('finish', onfinish); + stream.removeListener('end', onlegacyfinish); + stream.removeListener('close', onlegacyfinish); + stream.removeListener('finish', onfinish); + stream.removeListener('end', onend); + stream.removeListener('error', onerror); + stream.removeListener('close', onclose); + }; + if (options.signal && !closed) { + const abort = () => { + // Keep it because cleanup removes it. + const endCallback = callback; + cleanup(); + endCallback.call( + stream, + new AbortError(undefined, { + cause: options.signal.reason + }) + ); + }; + if (options.signal.aborted) { + process.nextTick(abort); + } else { + addAbortListener = addAbortListener || requireUtil$2().addAbortListener; + const disposable = addAbortListener(options.signal, abort); + const originalCallback = callback; + callback = once((...args) => { + disposable[SymbolDispose](); + originalCallback.apply(stream, args); + }); + } + } + return cleanup + } + function eosWeb(stream, options, callback) { + let isAborted = false; + let abort = nop; + if (options.signal) { + abort = () => { + isAborted = true; + callback.call( + stream, + new AbortError(undefined, { + cause: options.signal.reason + }) + ); + }; + if (options.signal.aborted) { + process.nextTick(abort); + } else { + addAbortListener = addAbortListener || requireUtil$2().addAbortListener; + const disposable = addAbortListener(options.signal, abort); + const originalCallback = callback; + callback = once((...args) => { + disposable[SymbolDispose](); + originalCallback.apply(stream, args); + }); + } + } + const resolverFn = (...args) => { + if (!isAborted) { + process.nextTick(() => callback.apply(stream, args)); + } + }; + PromisePrototypeThen(stream[kIsClosedPromise].promise, resolverFn, resolverFn); + return nop + } + function finished(stream, opts) { + var _opts; + let autoCleanup = false; + if (opts === null) { + opts = kEmptyObject; + } + if ((_opts = opts) !== null && _opts !== undefined && _opts.cleanup) { + validateBoolean(opts.cleanup, 'cleanup'); + autoCleanup = opts.cleanup; + } + return new Promise((resolve, reject) => { + const cleanup = eos(stream, opts, (err) => { + if (autoCleanup) { + cleanup(); + } + if (err) { + reject(err); + } else { + resolve(); + } + }); + }) + } + endOfStream.exports = eos; + endOfStream.exports.finished = finished; + return endOfStream.exports; +} + +var destroy_1; +var hasRequiredDestroy; + +function requireDestroy () { + if (hasRequiredDestroy) return destroy_1; + hasRequiredDestroy = 1; + + /* replacement start */ + + const process = requireBrowser$2(); + + /* replacement end */ + + const { + aggregateTwoErrors, + codes: { ERR_MULTIPLE_CALLBACK }, + AbortError + } = requireErrors(); + const { Symbol } = requirePrimordials(); + const { kIsDestroyed, isDestroyed, isFinished, isServerRequest } = requireUtils(); + const kDestroy = Symbol('kDestroy'); + const kConstruct = Symbol('kConstruct'); + function checkError(err, w, r) { + if (err) { + // Avoid V8 leak, https://github.com/nodejs/node/pull/34103#issuecomment-652002364 + err.stack; // eslint-disable-line no-unused-expressions + + if (w && !w.errored) { + w.errored = err; + } + if (r && !r.errored) { + r.errored = err; + } + } + } + + // Backwards compat. cb() is undocumented and unused in core but + // unfortunately might be used by modules. + function destroy(err, cb) { + const r = this._readableState; + const w = this._writableState; + // With duplex streams we use the writable side for state. + const s = w || r; + if ((w !== null && w !== undefined && w.destroyed) || (r !== null && r !== undefined && r.destroyed)) { + if (typeof cb === 'function') { + cb(); + } + return this + } + + // We set destroyed to true before firing error callbacks in order + // to make it re-entrance safe in case destroy() is called within callbacks + checkError(err, w, r); + if (w) { + w.destroyed = true; + } + if (r) { + r.destroyed = true; + } + + // If still constructing then defer calling _destroy. + if (!s.constructed) { + this.once(kDestroy, function (er) { + _destroy(this, aggregateTwoErrors(er, err), cb); + }); + } else { + _destroy(this, err, cb); + } + return this + } + function _destroy(self, err, cb) { + let called = false; + function onDestroy(err) { + if (called) { + return + } + called = true; + const r = self._readableState; + const w = self._writableState; + checkError(err, w, r); + if (w) { + w.closed = true; + } + if (r) { + r.closed = true; + } + if (typeof cb === 'function') { + cb(err); + } + if (err) { + process.nextTick(emitErrorCloseNT, self, err); + } else { + process.nextTick(emitCloseNT, self); + } + } + try { + self._destroy(err || null, onDestroy); + } catch (err) { + onDestroy(err); + } + } + function emitErrorCloseNT(self, err) { + emitErrorNT(self, err); + emitCloseNT(self); + } + function emitCloseNT(self) { + const r = self._readableState; + const w = self._writableState; + if (w) { + w.closeEmitted = true; + } + if (r) { + r.closeEmitted = true; + } + if ((w !== null && w !== undefined && w.emitClose) || (r !== null && r !== undefined && r.emitClose)) { + self.emit('close'); + } + } + function emitErrorNT(self, err) { + const r = self._readableState; + const w = self._writableState; + if ((w !== null && w !== undefined && w.errorEmitted) || (r !== null && r !== undefined && r.errorEmitted)) { + return + } + if (w) { + w.errorEmitted = true; + } + if (r) { + r.errorEmitted = true; + } + self.emit('error', err); + } + function undestroy() { + const r = this._readableState; + const w = this._writableState; + if (r) { + r.constructed = true; + r.closed = false; + r.closeEmitted = false; + r.destroyed = false; + r.errored = null; + r.errorEmitted = false; + r.reading = false; + r.ended = r.readable === false; + r.endEmitted = r.readable === false; + } + if (w) { + w.constructed = true; + w.destroyed = false; + w.closed = false; + w.closeEmitted = false; + w.errored = null; + w.errorEmitted = false; + w.finalCalled = false; + w.prefinished = false; + w.ended = w.writable === false; + w.ending = w.writable === false; + w.finished = w.writable === false; + } + } + function errorOrDestroy(stream, err, sync) { + // We have tests that rely on errors being emitted + // in the same tick, so changing this is semver major. + // For now when you opt-in to autoDestroy we allow + // the error to be emitted nextTick. In a future + // semver major update we should change the default to this. + + const r = stream._readableState; + const w = stream._writableState; + if ((w !== null && w !== undefined && w.destroyed) || (r !== null && r !== undefined && r.destroyed)) { + return this + } + if ((r !== null && r !== undefined && r.autoDestroy) || (w !== null && w !== undefined && w.autoDestroy)) + stream.destroy(err); + else if (err) { + // Avoid V8 leak, https://github.com/nodejs/node/pull/34103#issuecomment-652002364 + err.stack; // eslint-disable-line no-unused-expressions + + if (w && !w.errored) { + w.errored = err; + } + if (r && !r.errored) { + r.errored = err; + } + if (sync) { + process.nextTick(emitErrorNT, stream, err); + } else { + emitErrorNT(stream, err); + } + } + } + function construct(stream, cb) { + if (typeof stream._construct !== 'function') { + return + } + const r = stream._readableState; + const w = stream._writableState; + if (r) { + r.constructed = false; + } + if (w) { + w.constructed = false; + } + stream.once(kConstruct, cb); + if (stream.listenerCount(kConstruct) > 1) { + // Duplex + return + } + process.nextTick(constructNT, stream); + } + function constructNT(stream) { + let called = false; + function onConstruct(err) { + if (called) { + errorOrDestroy(stream, err !== null && err !== undefined ? err : new ERR_MULTIPLE_CALLBACK()); + return + } + called = true; + const r = stream._readableState; + const w = stream._writableState; + const s = w || r; + if (r) { + r.constructed = true; + } + if (w) { + w.constructed = true; + } + if (s.destroyed) { + stream.emit(kDestroy, err); + } else if (err) { + errorOrDestroy(stream, err, true); + } else { + process.nextTick(emitConstructNT, stream); + } + } + try { + stream._construct((err) => { + process.nextTick(onConstruct, err); + }); + } catch (err) { + process.nextTick(onConstruct, err); + } + } + function emitConstructNT(stream) { + stream.emit(kConstruct); + } + function isRequest(stream) { + return (stream === null || stream === undefined ? undefined : stream.setHeader) && typeof stream.abort === 'function' + } + function emitCloseLegacy(stream) { + stream.emit('close'); + } + function emitErrorCloseLegacy(stream, err) { + stream.emit('error', err); + process.nextTick(emitCloseLegacy, stream); + } + + // Normalize destroy for legacy. + function destroyer(stream, err) { + if (!stream || isDestroyed(stream)) { + return + } + if (!err && !isFinished(stream)) { + err = new AbortError(); + } + + // TODO: Remove isRequest branches. + if (isServerRequest(stream)) { + stream.socket = null; + stream.destroy(err); + } else if (isRequest(stream)) { + stream.abort(); + } else if (isRequest(stream.req)) { + stream.req.abort(); + } else if (typeof stream.destroy === 'function') { + stream.destroy(err); + } else if (typeof stream.close === 'function') { + // TODO: Don't lose err? + stream.close(); + } else if (err) { + process.nextTick(emitErrorCloseLegacy, stream, err); + } else { + process.nextTick(emitCloseLegacy, stream); + } + if (!stream.destroyed) { + stream[kIsDestroyed] = true; + } + } + destroy_1 = { + construct, + destroyer, + destroy, + undestroy, + errorOrDestroy + }; + return destroy_1; +} + +var legacy; +var hasRequiredLegacy; + +function requireLegacy () { + if (hasRequiredLegacy) return legacy; + hasRequiredLegacy = 1; + + const { ArrayIsArray, ObjectSetPrototypeOf } = requirePrimordials(); + const { EventEmitter: EE } = requireEvents$1(); + function Stream(opts) { + EE.call(this, opts); + } + ObjectSetPrototypeOf(Stream.prototype, EE.prototype); + ObjectSetPrototypeOf(Stream, EE); + Stream.prototype.pipe = function (dest, options) { + const source = this; + function ondata(chunk) { + if (dest.writable && dest.write(chunk) === false && source.pause) { + source.pause(); + } + } + source.on('data', ondata); + function ondrain() { + if (source.readable && source.resume) { + source.resume(); + } + } + dest.on('drain', ondrain); + + // If the 'end' option is not supplied, dest.end() will be called when + // source gets the 'end' or 'close' events. Only dest.end() once. + if (!dest._isStdio && (!options || options.end !== false)) { + source.on('end', onend); + source.on('close', onclose); + } + let didOnEnd = false; + function onend() { + if (didOnEnd) return + didOnEnd = true; + dest.end(); + } + function onclose() { + if (didOnEnd) return + didOnEnd = true; + if (typeof dest.destroy === 'function') dest.destroy(); + } + + // Don't leave dangling pipes when there are errors. + function onerror(er) { + cleanup(); + if (EE.listenerCount(this, 'error') === 0) { + this.emit('error', er); + } + } + prependListener(source, 'error', onerror); + prependListener(dest, 'error', onerror); + + // Remove all the event listeners that were added. + function cleanup() { + source.removeListener('data', ondata); + dest.removeListener('drain', ondrain); + source.removeListener('end', onend); + source.removeListener('close', onclose); + source.removeListener('error', onerror); + dest.removeListener('error', onerror); + source.removeListener('end', cleanup); + source.removeListener('close', cleanup); + dest.removeListener('close', cleanup); + } + source.on('end', cleanup); + source.on('close', cleanup); + dest.on('close', cleanup); + dest.emit('pipe', source); + + // Allow for unix-like usage: A.pipe(B).pipe(C) + return dest + }; + function prependListener(emitter, event, fn) { + // Sadly this is not cacheable as some libraries bundle their own + // event emitter implementation with them. + if (typeof emitter.prependListener === 'function') return emitter.prependListener(event, fn) + + // This is a hack to make sure that our error handler is attached before any + // userland ones. NEVER DO THIS. This is here only because this code needs + // to continue to work with older versions of Node.js that do not include + // the prependListener() method. The goal is to eventually remove this hack. + if (!emitter._events || !emitter._events[event]) emitter.on(event, fn); + else if (ArrayIsArray(emitter._events[event])) emitter._events[event].unshift(fn); + else emitter._events[event] = [fn, emitter._events[event]]; + } + legacy = { + Stream, + prependListener + }; + return legacy; +} + +var addAbortSignal = {exports: {}}; + +var hasRequiredAddAbortSignal; + +function requireAddAbortSignal () { + if (hasRequiredAddAbortSignal) return addAbortSignal.exports; + hasRequiredAddAbortSignal = 1; + (function (module) { + + const { SymbolDispose } = requirePrimordials(); + const { AbortError, codes } = requireErrors(); + const { isNodeStream, isWebStream, kControllerErrorFunction } = requireUtils(); + const eos = requireEndOfStream(); + const { ERR_INVALID_ARG_TYPE } = codes; + let addAbortListener; + + // This method is inlined here for readable-stream + // It also does not allow for signal to not exist on the stream + // https://github.com/nodejs/node/pull/36061#discussion_r533718029 + const validateAbortSignal = (signal, name) => { + if (typeof signal !== 'object' || !('aborted' in signal)) { + throw new ERR_INVALID_ARG_TYPE(name, 'AbortSignal', signal) + } + }; + module.exports.addAbortSignal = function addAbortSignal(signal, stream) { + validateAbortSignal(signal, 'signal'); + if (!isNodeStream(stream) && !isWebStream(stream)) { + throw new ERR_INVALID_ARG_TYPE('stream', ['ReadableStream', 'WritableStream', 'Stream'], stream) + } + return module.exports.addAbortSignalNoValidate(signal, stream) + }; + module.exports.addAbortSignalNoValidate = function (signal, stream) { + if (typeof signal !== 'object' || !('aborted' in signal)) { + return stream + } + const onAbort = isNodeStream(stream) + ? () => { + stream.destroy( + new AbortError(undefined, { + cause: signal.reason + }) + ); + } + : () => { + stream[kControllerErrorFunction]( + new AbortError(undefined, { + cause: signal.reason + }) + ); + }; + if (signal.aborted) { + onAbort(); + } else { + addAbortListener = addAbortListener || requireUtil$2().addAbortListener; + const disposable = addAbortListener(signal, onAbort); + eos(stream, disposable[SymbolDispose]); + } + return stream + }; + } (addAbortSignal)); + return addAbortSignal.exports; +} + +var buffer_list; +var hasRequiredBuffer_list; + +function requireBuffer_list () { + if (hasRequiredBuffer_list) return buffer_list; + hasRequiredBuffer_list = 1; + + const { StringPrototypeSlice, SymbolIterator, TypedArrayPrototypeSet, Uint8Array } = requirePrimordials(); + const { Buffer } = require$$0$1; + const { inspect } = requireUtil$2(); + buffer_list = class BufferList { + constructor() { + this.head = null; + this.tail = null; + this.length = 0; + } + push(v) { + const entry = { + data: v, + next: null + }; + if (this.length > 0) this.tail.next = entry; + else this.head = entry; + this.tail = entry; + ++this.length; + } + unshift(v) { + const entry = { + data: v, + next: this.head + }; + if (this.length === 0) this.tail = entry; + this.head = entry; + ++this.length; + } + shift() { + if (this.length === 0) return + const ret = this.head.data; + if (this.length === 1) this.head = this.tail = null; + else this.head = this.head.next; + --this.length; + return ret + } + clear() { + this.head = this.tail = null; + this.length = 0; + } + join(s) { + if (this.length === 0) return '' + let p = this.head; + let ret = '' + p.data; + while ((p = p.next) !== null) ret += s + p.data; + return ret + } + concat(n) { + if (this.length === 0) return Buffer.alloc(0) + const ret = Buffer.allocUnsafe(n >>> 0); + let p = this.head; + let i = 0; + while (p) { + TypedArrayPrototypeSet(ret, p.data, i); + i += p.data.length; + p = p.next; + } + return ret + } + + // Consumes a specified amount of bytes or characters from the buffered data. + consume(n, hasStrings) { + const data = this.head.data; + if (n < data.length) { + // `slice` is the same for buffers and strings. + const slice = data.slice(0, n); + this.head.data = data.slice(n); + return slice + } + if (n === data.length) { + // First chunk is a perfect match. + return this.shift() + } + // Result spans more than one buffer. + return hasStrings ? this._getString(n) : this._getBuffer(n) + } + first() { + return this.head.data + } + *[SymbolIterator]() { + for (let p = this.head; p; p = p.next) { + yield p.data; + } + } + + // Consumes a specified amount of characters from the buffered data. + _getString(n) { + let ret = ''; + let p = this.head; + let c = 0; + do { + const str = p.data; + if (n > str.length) { + ret += str; + n -= str.length; + } else { + if (n === str.length) { + ret += str; + ++c; + if (p.next) this.head = p.next; + else this.head = this.tail = null; + } else { + ret += StringPrototypeSlice(str, 0, n); + this.head = p; + p.data = StringPrototypeSlice(str, n); + } + break + } + ++c; + } while ((p = p.next) !== null) + this.length -= c; + return ret + } + + // Consumes a specified amount of bytes from the buffered data. + _getBuffer(n) { + const ret = Buffer.allocUnsafe(n); + const retLen = n; + let p = this.head; + let c = 0; + do { + const buf = p.data; + if (n > buf.length) { + TypedArrayPrototypeSet(ret, buf, retLen - n); + n -= buf.length; + } else { + if (n === buf.length) { + TypedArrayPrototypeSet(ret, buf, retLen - n); + ++c; + if (p.next) this.head = p.next; + else this.head = this.tail = null; + } else { + TypedArrayPrototypeSet(ret, new Uint8Array(buf.buffer, buf.byteOffset, n), retLen - n); + this.head = p; + p.data = buf.slice(n); + } + break + } + ++c; + } while ((p = p.next) !== null) + this.length -= c; + return ret + } + + // Make sure the linked list only shows the minimal necessary information. + [Symbol.for('nodejs.util.inspect.custom')](_, options) { + return inspect(this, { + ...options, + // Only inspect one level. + depth: 0, + // It should not recurse. + customInspect: false + }) + } + }; + return buffer_list; +} + +var state; +var hasRequiredState; + +function requireState () { + if (hasRequiredState) return state; + hasRequiredState = 1; + + const { MathFloor, NumberIsInteger } = requirePrimordials(); + const { validateInteger } = requireValidators(); + const { ERR_INVALID_ARG_VALUE } = requireErrors().codes; + let defaultHighWaterMarkBytes = 16 * 1024; + let defaultHighWaterMarkObjectMode = 16; + function highWaterMarkFrom(options, isDuplex, duplexKey) { + return options.highWaterMark != null ? options.highWaterMark : isDuplex ? options[duplexKey] : null + } + function getDefaultHighWaterMark(objectMode) { + return objectMode ? defaultHighWaterMarkObjectMode : defaultHighWaterMarkBytes + } + function setDefaultHighWaterMark(objectMode, value) { + validateInteger(value, 'value', 0); + if (objectMode) { + defaultHighWaterMarkObjectMode = value; + } else { + defaultHighWaterMarkBytes = value; + } + } + function getHighWaterMark(state, options, duplexKey, isDuplex) { + const hwm = highWaterMarkFrom(options, isDuplex, duplexKey); + if (hwm != null) { + if (!NumberIsInteger(hwm) || hwm < 0) { + const name = isDuplex ? `options.${duplexKey}` : 'options.highWaterMark'; + throw new ERR_INVALID_ARG_VALUE(name, hwm) + } + return MathFloor(hwm) + } + + // Default value + return getDefaultHighWaterMark(state.objectMode) + } + state = { + getHighWaterMark, + getDefaultHighWaterMark, + setDefaultHighWaterMark + }; + return state; +} + +var string_decoder = {}; + +var safeBuffer = {exports: {}}; + +/*! safe-buffer. MIT License. Feross Aboukhadijeh */ + +var hasRequiredSafeBuffer; + +function requireSafeBuffer () { + if (hasRequiredSafeBuffer) return safeBuffer.exports; + hasRequiredSafeBuffer = 1; + (function (module, exports) { + /* eslint-disable node/no-deprecated-api */ + var buffer = require$$0$1; + var Buffer = buffer.Buffer; + + // alternative to using Object.keys for old browsers + function copyProps (src, dst) { + for (var key in src) { + dst[key] = src[key]; + } + } + if (Buffer.from && Buffer.alloc && Buffer.allocUnsafe && Buffer.allocUnsafeSlow) { + module.exports = buffer; + } else { + // Copy properties from require('buffer') + copyProps(buffer, exports); + exports.Buffer = SafeBuffer; + } + + function SafeBuffer (arg, encodingOrOffset, length) { + return Buffer(arg, encodingOrOffset, length) + } + + SafeBuffer.prototype = Object.create(Buffer.prototype); + + // Copy static methods from Buffer + copyProps(Buffer, SafeBuffer); + + SafeBuffer.from = function (arg, encodingOrOffset, length) { + if (typeof arg === 'number') { + throw new TypeError('Argument must not be a number') + } + return Buffer(arg, encodingOrOffset, length) + }; + + SafeBuffer.alloc = function (size, fill, encoding) { + if (typeof size !== 'number') { + throw new TypeError('Argument must be a number') + } + var buf = Buffer(size); + if (fill !== undefined) { + if (typeof encoding === 'string') { + buf.fill(fill, encoding); + } else { + buf.fill(fill); + } + } else { + buf.fill(0); + } + return buf + }; + + SafeBuffer.allocUnsafe = function (size) { + if (typeof size !== 'number') { + throw new TypeError('Argument must be a number') + } + return Buffer(size) + }; + + SafeBuffer.allocUnsafeSlow = function (size) { + if (typeof size !== 'number') { + throw new TypeError('Argument must be a number') + } + return buffer.SlowBuffer(size) + }; + } (safeBuffer, safeBuffer.exports)); + return safeBuffer.exports; +} + +var hasRequiredString_decoder; + +function requireString_decoder () { + if (hasRequiredString_decoder) return string_decoder; + hasRequiredString_decoder = 1; + + /**/ + + var Buffer = requireSafeBuffer().Buffer; + /**/ + + var isEncoding = Buffer.isEncoding || function (encoding) { + encoding = '' + encoding; + switch (encoding && encoding.toLowerCase()) { + case 'hex':case 'utf8':case 'utf-8':case 'ascii':case 'binary':case 'base64':case 'ucs2':case 'ucs-2':case 'utf16le':case 'utf-16le':case 'raw': + return true; + default: + return false; + } + }; + + function _normalizeEncoding(enc) { + if (!enc) return 'utf8'; + var retried; + while (true) { + switch (enc) { + case 'utf8': + case 'utf-8': + return 'utf8'; + case 'ucs2': + case 'ucs-2': + case 'utf16le': + case 'utf-16le': + return 'utf16le'; + case 'latin1': + case 'binary': + return 'latin1'; + case 'base64': + case 'ascii': + case 'hex': + return enc; + default: + if (retried) return; // undefined + enc = ('' + enc).toLowerCase(); + retried = true; + } + } + } + // Do not cache `Buffer.isEncoding` when checking encoding names as some + // modules monkey-patch it to support additional encodings + function normalizeEncoding(enc) { + var nenc = _normalizeEncoding(enc); + if (typeof nenc !== 'string' && (Buffer.isEncoding === isEncoding || !isEncoding(enc))) throw new Error('Unknown encoding: ' + enc); + return nenc || enc; + } + + // StringDecoder provides an interface for efficiently splitting a series of + // buffers into a series of JS strings without breaking apart multi-byte + // characters. + string_decoder.StringDecoder = StringDecoder; + function StringDecoder(encoding) { + this.encoding = normalizeEncoding(encoding); + var nb; + switch (this.encoding) { + case 'utf16le': + this.text = utf16Text; + this.end = utf16End; + nb = 4; + break; + case 'utf8': + this.fillLast = utf8FillLast; + nb = 4; + break; + case 'base64': + this.text = base64Text; + this.end = base64End; + nb = 3; + break; + default: + this.write = simpleWrite; + this.end = simpleEnd; + return; + } + this.lastNeed = 0; + this.lastTotal = 0; + this.lastChar = Buffer.allocUnsafe(nb); + } + + StringDecoder.prototype.write = function (buf) { + if (buf.length === 0) return ''; + var r; + var i; + if (this.lastNeed) { + r = this.fillLast(buf); + if (r === undefined) return ''; + i = this.lastNeed; + this.lastNeed = 0; + } else { + i = 0; + } + if (i < buf.length) return r ? r + this.text(buf, i) : this.text(buf, i); + return r || ''; + }; + + StringDecoder.prototype.end = utf8End; + + // Returns only complete characters in a Buffer + StringDecoder.prototype.text = utf8Text; + + // Attempts to complete a partial non-UTF-8 character using bytes from a Buffer + StringDecoder.prototype.fillLast = function (buf) { + if (this.lastNeed <= buf.length) { + buf.copy(this.lastChar, this.lastTotal - this.lastNeed, 0, this.lastNeed); + return this.lastChar.toString(this.encoding, 0, this.lastTotal); + } + buf.copy(this.lastChar, this.lastTotal - this.lastNeed, 0, buf.length); + this.lastNeed -= buf.length; + }; + + // Checks the type of a UTF-8 byte, whether it's ASCII, a leading byte, or a + // continuation byte. If an invalid byte is detected, -2 is returned. + function utf8CheckByte(byte) { + if (byte <= 0x7F) return 0;else if (byte >> 5 === 0x06) return 2;else if (byte >> 4 === 0x0E) return 3;else if (byte >> 3 === 0x1E) return 4; + return byte >> 6 === 0x02 ? -1 : -2; + } + + // Checks at most 3 bytes at the end of a Buffer in order to detect an + // incomplete multi-byte UTF-8 character. The total number of bytes (2, 3, or 4) + // needed to complete the UTF-8 character (if applicable) are returned. + function utf8CheckIncomplete(self, buf, i) { + var j = buf.length - 1; + if (j < i) return 0; + var nb = utf8CheckByte(buf[j]); + if (nb >= 0) { + if (nb > 0) self.lastNeed = nb - 1; + return nb; + } + if (--j < i || nb === -2) return 0; + nb = utf8CheckByte(buf[j]); + if (nb >= 0) { + if (nb > 0) self.lastNeed = nb - 2; + return nb; + } + if (--j < i || nb === -2) return 0; + nb = utf8CheckByte(buf[j]); + if (nb >= 0) { + if (nb > 0) { + if (nb === 2) nb = 0;else self.lastNeed = nb - 3; + } + return nb; + } + return 0; + } + + // Validates as many continuation bytes for a multi-byte UTF-8 character as + // needed or are available. If we see a non-continuation byte where we expect + // one, we "replace" the validated continuation bytes we've seen so far with + // a single UTF-8 replacement character ('\ufffd'), to match v8's UTF-8 decoding + // behavior. The continuation byte check is included three times in the case + // where all of the continuation bytes for a character exist in the same buffer. + // It is also done this way as a slight performance increase instead of using a + // loop. + function utf8CheckExtraBytes(self, buf, p) { + if ((buf[0] & 0xC0) !== 0x80) { + self.lastNeed = 0; + return '\ufffd'; + } + if (self.lastNeed > 1 && buf.length > 1) { + if ((buf[1] & 0xC0) !== 0x80) { + self.lastNeed = 1; + return '\ufffd'; + } + if (self.lastNeed > 2 && buf.length > 2) { + if ((buf[2] & 0xC0) !== 0x80) { + self.lastNeed = 2; + return '\ufffd'; + } + } + } + } + + // Attempts to complete a multi-byte UTF-8 character using bytes from a Buffer. + function utf8FillLast(buf) { + var p = this.lastTotal - this.lastNeed; + var r = utf8CheckExtraBytes(this, buf); + if (r !== undefined) return r; + if (this.lastNeed <= buf.length) { + buf.copy(this.lastChar, p, 0, this.lastNeed); + return this.lastChar.toString(this.encoding, 0, this.lastTotal); + } + buf.copy(this.lastChar, p, 0, buf.length); + this.lastNeed -= buf.length; + } + + // Returns all complete UTF-8 characters in a Buffer. If the Buffer ended on a + // partial character, the character's bytes are buffered until the required + // number of bytes are available. + function utf8Text(buf, i) { + var total = utf8CheckIncomplete(this, buf, i); + if (!this.lastNeed) return buf.toString('utf8', i); + this.lastTotal = total; + var end = buf.length - (total - this.lastNeed); + buf.copy(this.lastChar, 0, end); + return buf.toString('utf8', i, end); + } + + // For UTF-8, a replacement character is added when ending on a partial + // character. + function utf8End(buf) { + var r = buf && buf.length ? this.write(buf) : ''; + if (this.lastNeed) return r + '\ufffd'; + return r; + } + + // UTF-16LE typically needs two bytes per character, but even if we have an even + // number of bytes available, we need to check if we end on a leading/high + // surrogate. In that case, we need to wait for the next two bytes in order to + // decode the last character properly. + function utf16Text(buf, i) { + if ((buf.length - i) % 2 === 0) { + var r = buf.toString('utf16le', i); + if (r) { + var c = r.charCodeAt(r.length - 1); + if (c >= 0xD800 && c <= 0xDBFF) { + this.lastNeed = 2; + this.lastTotal = 4; + this.lastChar[0] = buf[buf.length - 2]; + this.lastChar[1] = buf[buf.length - 1]; + return r.slice(0, -1); + } + } + return r; + } + this.lastNeed = 1; + this.lastTotal = 2; + this.lastChar[0] = buf[buf.length - 1]; + return buf.toString('utf16le', i, buf.length - 1); + } + + // For UTF-16LE we do not explicitly append special replacement characters if we + // end on a partial character, we simply let v8 handle that. + function utf16End(buf) { + var r = buf && buf.length ? this.write(buf) : ''; + if (this.lastNeed) { + var end = this.lastTotal - this.lastNeed; + return r + this.lastChar.toString('utf16le', 0, end); + } + return r; + } + + function base64Text(buf, i) { + var n = (buf.length - i) % 3; + if (n === 0) return buf.toString('base64', i); + this.lastNeed = 3 - n; + this.lastTotal = 3; + if (n === 1) { + this.lastChar[0] = buf[buf.length - 1]; + } else { + this.lastChar[0] = buf[buf.length - 2]; + this.lastChar[1] = buf[buf.length - 1]; + } + return buf.toString('base64', i, buf.length - n); + } + + function base64End(buf) { + var r = buf && buf.length ? this.write(buf) : ''; + if (this.lastNeed) return r + this.lastChar.toString('base64', 0, 3 - this.lastNeed); + return r; + } + + // Pass bytes on through for single-byte encodings (e.g. ascii, latin1, hex) + function simpleWrite(buf) { + return buf.toString(this.encoding); + } + + function simpleEnd(buf) { + return buf && buf.length ? this.write(buf) : ''; + } + return string_decoder; +} + +var from_1; +var hasRequiredFrom; + +function requireFrom () { + if (hasRequiredFrom) return from_1; + hasRequiredFrom = 1; + + /* replacement start */ + + const process = requireBrowser$2(); + + /* replacement end */ + + const { PromisePrototypeThen, SymbolAsyncIterator, SymbolIterator } = requirePrimordials(); + const { Buffer } = require$$0$1; + const { ERR_INVALID_ARG_TYPE, ERR_STREAM_NULL_VALUES } = requireErrors().codes; + function from(Readable, iterable, opts) { + let iterator; + if (typeof iterable === 'string' || iterable instanceof Buffer) { + return new Readable({ + objectMode: true, + ...opts, + read() { + this.push(iterable); + this.push(null); + } + }) + } + let isAsync; + if (iterable && iterable[SymbolAsyncIterator]) { + isAsync = true; + iterator = iterable[SymbolAsyncIterator](); + } else if (iterable && iterable[SymbolIterator]) { + isAsync = false; + iterator = iterable[SymbolIterator](); + } else { + throw new ERR_INVALID_ARG_TYPE('iterable', ['Iterable'], iterable) + } + const readable = new Readable({ + objectMode: true, + highWaterMark: 1, + // TODO(ronag): What options should be allowed? + ...opts + }); + + // Flag to protect against _read + // being called before last iteration completion. + let reading = false; + readable._read = function () { + if (!reading) { + reading = true; + next(); + } + }; + readable._destroy = function (error, cb) { + PromisePrototypeThen( + close(error), + () => process.nextTick(cb, error), + // nextTick is here in case cb throws + (e) => process.nextTick(cb, e || error) + ); + }; + async function close(error) { + const hadError = error !== undefined && error !== null; + const hasThrow = typeof iterator.throw === 'function'; + if (hadError && hasThrow) { + const { value, done } = await iterator.throw(error); + await value; + if (done) { + return + } + } + if (typeof iterator.return === 'function') { + const { value } = await iterator.return(); + await value; + } + } + async function next() { + for (;;) { + try { + const { value, done } = isAsync ? await iterator.next() : iterator.next(); + if (done) { + readable.push(null); + } else { + const res = value && typeof value.then === 'function' ? await value : value; + if (res === null) { + reading = false; + throw new ERR_STREAM_NULL_VALUES() + } else if (readable.push(res)) { + continue + } else { + reading = false; + } + } + } catch (err) { + readable.destroy(err); + } + break + } + } + return readable + } + from_1 = from; + return from_1; +} + +var readable; +var hasRequiredReadable; + +function requireReadable () { + if (hasRequiredReadable) return readable; + hasRequiredReadable = 1; + + /* replacement start */ + + const process = requireBrowser$2(); + + /* replacement end */ + + const { + ArrayPrototypeIndexOf, + NumberIsInteger, + NumberIsNaN, + NumberParseInt, + ObjectDefineProperties, + ObjectKeys, + ObjectSetPrototypeOf, + Promise, + SafeSet, + SymbolAsyncDispose, + SymbolAsyncIterator, + Symbol + } = requirePrimordials(); + readable = Readable; + Readable.ReadableState = ReadableState; + const { EventEmitter: EE } = requireEvents$1(); + const { Stream, prependListener } = requireLegacy(); + const { Buffer } = require$$0$1; + const { addAbortSignal } = requireAddAbortSignal(); + const eos = requireEndOfStream(); + let debug = requireUtil$2().debuglog('stream', (fn) => { + debug = fn; + }); + const BufferList = requireBuffer_list(); + const destroyImpl = requireDestroy(); + const { getHighWaterMark, getDefaultHighWaterMark } = requireState(); + const { + aggregateTwoErrors, + codes: { + ERR_INVALID_ARG_TYPE, + ERR_METHOD_NOT_IMPLEMENTED, + ERR_OUT_OF_RANGE, + ERR_STREAM_PUSH_AFTER_EOF, + ERR_STREAM_UNSHIFT_AFTER_END_EVENT + }, + AbortError + } = requireErrors(); + const { validateObject } = requireValidators(); + const kPaused = Symbol('kPaused'); + const { StringDecoder } = requireString_decoder(); + const from = requireFrom(); + ObjectSetPrototypeOf(Readable.prototype, Stream.prototype); + ObjectSetPrototypeOf(Readable, Stream); + const nop = () => {}; + const { errorOrDestroy } = destroyImpl; + const kObjectMode = 1 << 0; + const kEnded = 1 << 1; + const kEndEmitted = 1 << 2; + const kReading = 1 << 3; + const kConstructed = 1 << 4; + const kSync = 1 << 5; + const kNeedReadable = 1 << 6; + const kEmittedReadable = 1 << 7; + const kReadableListening = 1 << 8; + const kResumeScheduled = 1 << 9; + const kErrorEmitted = 1 << 10; + const kEmitClose = 1 << 11; + const kAutoDestroy = 1 << 12; + const kDestroyed = 1 << 13; + const kClosed = 1 << 14; + const kCloseEmitted = 1 << 15; + const kMultiAwaitDrain = 1 << 16; + const kReadingMore = 1 << 17; + const kDataEmitted = 1 << 18; + + // TODO(benjamingr) it is likely slower to do it this way than with free functions + function makeBitMapDescriptor(bit) { + return { + enumerable: false, + get() { + return (this.state & bit) !== 0 + }, + set(value) { + if (value) this.state |= bit; + else this.state &= ~bit; + } + } + } + ObjectDefineProperties(ReadableState.prototype, { + objectMode: makeBitMapDescriptor(kObjectMode), + ended: makeBitMapDescriptor(kEnded), + endEmitted: makeBitMapDescriptor(kEndEmitted), + reading: makeBitMapDescriptor(kReading), + // Stream is still being constructed and cannot be + // destroyed until construction finished or failed. + // Async construction is opt in, therefore we start as + // constructed. + constructed: makeBitMapDescriptor(kConstructed), + // A flag to be able to tell if the event 'readable'/'data' is emitted + // immediately, or on a later tick. We set this to true at first, because + // any actions that shouldn't happen until "later" should generally also + // not happen before the first read call. + sync: makeBitMapDescriptor(kSync), + // Whenever we return null, then we set a flag to say + // that we're awaiting a 'readable' event emission. + needReadable: makeBitMapDescriptor(kNeedReadable), + emittedReadable: makeBitMapDescriptor(kEmittedReadable), + readableListening: makeBitMapDescriptor(kReadableListening), + resumeScheduled: makeBitMapDescriptor(kResumeScheduled), + // True if the error was already emitted and should not be thrown again. + errorEmitted: makeBitMapDescriptor(kErrorEmitted), + emitClose: makeBitMapDescriptor(kEmitClose), + autoDestroy: makeBitMapDescriptor(kAutoDestroy), + // Has it been destroyed. + destroyed: makeBitMapDescriptor(kDestroyed), + // Indicates whether the stream has finished destroying. + closed: makeBitMapDescriptor(kClosed), + // True if close has been emitted or would have been emitted + // depending on emitClose. + closeEmitted: makeBitMapDescriptor(kCloseEmitted), + multiAwaitDrain: makeBitMapDescriptor(kMultiAwaitDrain), + // If true, a maybeReadMore has been scheduled. + readingMore: makeBitMapDescriptor(kReadingMore), + dataEmitted: makeBitMapDescriptor(kDataEmitted) + }); + function ReadableState(options, stream, isDuplex) { + // Duplex streams are both readable and writable, but share + // the same options object. + // However, some cases require setting options to different + // values for the readable and the writable sides of the duplex stream. + // These options can be provided separately as readableXXX and writableXXX. + if (typeof isDuplex !== 'boolean') isDuplex = stream instanceof requireDuplex(); + + // Bit map field to store ReadableState more effciently with 1 bit per field + // instead of a V8 slot per field. + this.state = kEmitClose | kAutoDestroy | kConstructed | kSync; + // Object stream flag. Used to make read(n) ignore n and to + // make all the buffer merging and length checks go away. + if (options && options.objectMode) this.state |= kObjectMode; + if (isDuplex && options && options.readableObjectMode) this.state |= kObjectMode; + + // The point at which it stops calling _read() to fill the buffer + // Note: 0 is a valid value, means "don't call _read preemptively ever" + this.highWaterMark = options + ? getHighWaterMark(this, options, 'readableHighWaterMark', isDuplex) + : getDefaultHighWaterMark(false); + + // A linked list is used to store data chunks instead of an array because the + // linked list can remove elements from the beginning faster than + // array.shift(). + this.buffer = new BufferList(); + this.length = 0; + this.pipes = []; + this.flowing = null; + this[kPaused] = null; + + // Should close be emitted on destroy. Defaults to true. + if (options && options.emitClose === false) this.state &= ~kEmitClose; + + // Should .destroy() be called after 'end' (and potentially 'finish'). + if (options && options.autoDestroy === false) this.state &= ~kAutoDestroy; + + // Indicates whether the stream has errored. When true no further + // _read calls, 'data' or 'readable' events should occur. This is needed + // since when autoDestroy is disabled we need a way to tell whether the + // stream has failed. + this.errored = null; + + // Crypto is kind of old and crusty. Historically, its default string + // encoding is 'binary' so we have to make this configurable. + // Everything else in the universe uses 'utf8', though. + this.defaultEncoding = (options && options.defaultEncoding) || 'utf8'; + + // Ref the piped dest which we need a drain event on it + // type: null | Writable | Set. + this.awaitDrainWriters = null; + this.decoder = null; + this.encoding = null; + if (options && options.encoding) { + this.decoder = new StringDecoder(options.encoding); + this.encoding = options.encoding; + } + } + function Readable(options) { + if (!(this instanceof Readable)) return new Readable(options) + + // Checking for a Stream.Duplex instance is faster here instead of inside + // the ReadableState constructor, at least with V8 6.5. + const isDuplex = this instanceof requireDuplex(); + this._readableState = new ReadableState(options, this, isDuplex); + if (options) { + if (typeof options.read === 'function') this._read = options.read; + if (typeof options.destroy === 'function') this._destroy = options.destroy; + if (typeof options.construct === 'function') this._construct = options.construct; + if (options.signal && !isDuplex) addAbortSignal(options.signal, this); + } + Stream.call(this, options); + destroyImpl.construct(this, () => { + if (this._readableState.needReadable) { + maybeReadMore(this, this._readableState); + } + }); + } + Readable.prototype.destroy = destroyImpl.destroy; + Readable.prototype._undestroy = destroyImpl.undestroy; + Readable.prototype._destroy = function (err, cb) { + cb(err); + }; + Readable.prototype[EE.captureRejectionSymbol] = function (err) { + this.destroy(err); + }; + Readable.prototype[SymbolAsyncDispose] = function () { + let error; + if (!this.destroyed) { + error = this.readableEnded ? null : new AbortError(); + this.destroy(error); + } + return new Promise((resolve, reject) => eos(this, (err) => (err && err !== error ? reject(err) : resolve(null)))) + }; + + // Manually shove something into the read() buffer. + // This returns true if the highWaterMark has not been hit yet, + // similar to how Writable.write() returns true if you should + // write() some more. + Readable.prototype.push = function (chunk, encoding) { + return readableAddChunk(this, chunk, encoding, false) + }; + + // Unshift should *always* be something directly out of read(). + Readable.prototype.unshift = function (chunk, encoding) { + return readableAddChunk(this, chunk, encoding, true) + }; + function readableAddChunk(stream, chunk, encoding, addToFront) { + debug('readableAddChunk', chunk); + const state = stream._readableState; + let err; + if ((state.state & kObjectMode) === 0) { + if (typeof chunk === 'string') { + encoding = encoding || state.defaultEncoding; + if (state.encoding !== encoding) { + if (addToFront && state.encoding) { + // When unshifting, if state.encoding is set, we have to save + // the string in the BufferList with the state encoding. + chunk = Buffer.from(chunk, encoding).toString(state.encoding); + } else { + chunk = Buffer.from(chunk, encoding); + encoding = ''; + } + } + } else if (chunk instanceof Buffer) { + encoding = ''; + } else if (Stream._isUint8Array(chunk)) { + chunk = Stream._uint8ArrayToBuffer(chunk); + encoding = ''; + } else if (chunk != null) { + err = new ERR_INVALID_ARG_TYPE('chunk', ['string', 'Buffer', 'Uint8Array'], chunk); + } + } + if (err) { + errorOrDestroy(stream, err); + } else if (chunk === null) { + state.state &= ~kReading; + onEofChunk(stream, state); + } else if ((state.state & kObjectMode) !== 0 || (chunk && chunk.length > 0)) { + if (addToFront) { + if ((state.state & kEndEmitted) !== 0) errorOrDestroy(stream, new ERR_STREAM_UNSHIFT_AFTER_END_EVENT()); + else if (state.destroyed || state.errored) return false + else addChunk(stream, state, chunk, true); + } else if (state.ended) { + errorOrDestroy(stream, new ERR_STREAM_PUSH_AFTER_EOF()); + } else if (state.destroyed || state.errored) { + return false + } else { + state.state &= ~kReading; + if (state.decoder && !encoding) { + chunk = state.decoder.write(chunk); + if (state.objectMode || chunk.length !== 0) addChunk(stream, state, chunk, false); + else maybeReadMore(stream, state); + } else { + addChunk(stream, state, chunk, false); + } + } + } else if (!addToFront) { + state.state &= ~kReading; + maybeReadMore(stream, state); + } + + // We can push more data if we are below the highWaterMark. + // Also, if we have no data yet, we can stand some more bytes. + // This is to work around cases where hwm=0, such as the repl. + return !state.ended && (state.length < state.highWaterMark || state.length === 0) + } + function addChunk(stream, state, chunk, addToFront) { + if (state.flowing && state.length === 0 && !state.sync && stream.listenerCount('data') > 0) { + // Use the guard to avoid creating `Set()` repeatedly + // when we have multiple pipes. + if ((state.state & kMultiAwaitDrain) !== 0) { + state.awaitDrainWriters.clear(); + } else { + state.awaitDrainWriters = null; + } + state.dataEmitted = true; + stream.emit('data', chunk); + } else { + // Update the buffer info. + state.length += state.objectMode ? 1 : chunk.length; + if (addToFront) state.buffer.unshift(chunk); + else state.buffer.push(chunk); + if ((state.state & kNeedReadable) !== 0) emitReadable(stream); + } + maybeReadMore(stream, state); + } + Readable.prototype.isPaused = function () { + const state = this._readableState; + return state[kPaused] === true || state.flowing === false + }; + + // Backwards compatibility. + Readable.prototype.setEncoding = function (enc) { + const decoder = new StringDecoder(enc); + this._readableState.decoder = decoder; + // If setEncoding(null), decoder.encoding equals utf8. + this._readableState.encoding = this._readableState.decoder.encoding; + const buffer = this._readableState.buffer; + // Iterate over current buffer to convert already stored Buffers: + let content = ''; + for (const data of buffer) { + content += decoder.write(data); + } + buffer.clear(); + if (content !== '') buffer.push(content); + this._readableState.length = content.length; + return this + }; + + // Don't raise the hwm > 1GB. + const MAX_HWM = 0x40000000; + function computeNewHighWaterMark(n) { + if (n > MAX_HWM) { + throw new ERR_OUT_OF_RANGE('size', '<= 1GiB', n) + } else { + // Get the next highest power of 2 to prevent increasing hwm excessively in + // tiny amounts. + n--; + n |= n >>> 1; + n |= n >>> 2; + n |= n >>> 4; + n |= n >>> 8; + n |= n >>> 16; + n++; + } + return n + } + + // This function is designed to be inlinable, so please take care when making + // changes to the function body. + function howMuchToRead(n, state) { + if (n <= 0 || (state.length === 0 && state.ended)) return 0 + if ((state.state & kObjectMode) !== 0) return 1 + if (NumberIsNaN(n)) { + // Only flow one buffer at a time. + if (state.flowing && state.length) return state.buffer.first().length + return state.length + } + if (n <= state.length) return n + return state.ended ? state.length : 0 + } + + // You can override either this method, or the async _read(n) below. + Readable.prototype.read = function (n) { + debug('read', n); + // Same as parseInt(undefined, 10), however V8 7.3 performance regressed + // in this scenario, so we are doing it manually. + if (n === undefined) { + n = NaN; + } else if (!NumberIsInteger(n)) { + n = NumberParseInt(n, 10); + } + const state = this._readableState; + const nOrig = n; + + // If we're asking for more than the current hwm, then raise the hwm. + if (n > state.highWaterMark) state.highWaterMark = computeNewHighWaterMark(n); + if (n !== 0) state.state &= ~kEmittedReadable; + + // If we're doing read(0) to trigger a readable event, but we + // already have a bunch of data in the buffer, then just trigger + // the 'readable' event and move on. + if ( + n === 0 && + state.needReadable && + ((state.highWaterMark !== 0 ? state.length >= state.highWaterMark : state.length > 0) || state.ended) + ) { + debug('read: emitReadable', state.length, state.ended); + if (state.length === 0 && state.ended) endReadable(this); + else emitReadable(this); + return null + } + n = howMuchToRead(n, state); + + // If we've ended, and we're now clear, then finish it up. + if (n === 0 && state.ended) { + if (state.length === 0) endReadable(this); + return null + } + + // All the actual chunk generation logic needs to be + // *below* the call to _read. The reason is that in certain + // synthetic stream cases, such as passthrough streams, _read + // may be a completely synchronous operation which may change + // the state of the read buffer, providing enough data when + // before there was *not* enough. + // + // So, the steps are: + // 1. Figure out what the state of things will be after we do + // a read from the buffer. + // + // 2. If that resulting state will trigger a _read, then call _read. + // Note that this may be asynchronous, or synchronous. Yes, it is + // deeply ugly to write APIs this way, but that still doesn't mean + // that the Readable class should behave improperly, as streams are + // designed to be sync/async agnostic. + // Take note if the _read call is sync or async (ie, if the read call + // has returned yet), so that we know whether or not it's safe to emit + // 'readable' etc. + // + // 3. Actually pull the requested chunks out of the buffer and return. + + // if we need a readable event, then we need to do some reading. + let doRead = (state.state & kNeedReadable) !== 0; + debug('need readable', doRead); + + // If we currently have less than the highWaterMark, then also read some. + if (state.length === 0 || state.length - n < state.highWaterMark) { + doRead = true; + debug('length less than watermark', doRead); + } + + // However, if we've ended, then there's no point, if we're already + // reading, then it's unnecessary, if we're constructing we have to wait, + // and if we're destroyed or errored, then it's not allowed, + if (state.ended || state.reading || state.destroyed || state.errored || !state.constructed) { + doRead = false; + debug('reading, ended or constructing', doRead); + } else if (doRead) { + debug('do read'); + state.state |= kReading | kSync; + // If the length is currently zero, then we *need* a readable event. + if (state.length === 0) state.state |= kNeedReadable; + + // Call internal read method + try { + this._read(state.highWaterMark); + } catch (err) { + errorOrDestroy(this, err); + } + state.state &= ~kSync; + + // If _read pushed data synchronously, then `reading` will be false, + // and we need to re-evaluate how much data we can return to the user. + if (!state.reading) n = howMuchToRead(nOrig, state); + } + let ret; + if (n > 0) ret = fromList(n, state); + else ret = null; + if (ret === null) { + state.needReadable = state.length <= state.highWaterMark; + n = 0; + } else { + state.length -= n; + if (state.multiAwaitDrain) { + state.awaitDrainWriters.clear(); + } else { + state.awaitDrainWriters = null; + } + } + if (state.length === 0) { + // If we have nothing in the buffer, then we want to know + // as soon as we *do* get something into the buffer. + if (!state.ended) state.needReadable = true; + + // If we tried to read() past the EOF, then emit end on the next tick. + if (nOrig !== n && state.ended) endReadable(this); + } + if (ret !== null && !state.errorEmitted && !state.closeEmitted) { + state.dataEmitted = true; + this.emit('data', ret); + } + return ret + }; + function onEofChunk(stream, state) { + debug('onEofChunk'); + if (state.ended) return + if (state.decoder) { + const chunk = state.decoder.end(); + if (chunk && chunk.length) { + state.buffer.push(chunk); + state.length += state.objectMode ? 1 : chunk.length; + } + } + state.ended = true; + if (state.sync) { + // If we are sync, wait until next tick to emit the data. + // Otherwise we risk emitting data in the flow() + // the readable code triggers during a read() call. + emitReadable(stream); + } else { + // Emit 'readable' now to make sure it gets picked up. + state.needReadable = false; + state.emittedReadable = true; + // We have to emit readable now that we are EOF. Modules + // in the ecosystem (e.g. dicer) rely on this event being sync. + emitReadable_(stream); + } + } + + // Don't emit readable right away in sync mode, because this can trigger + // another read() call => stack overflow. This way, it might trigger + // a nextTick recursion warning, but that's not so bad. + function emitReadable(stream) { + const state = stream._readableState; + debug('emitReadable', state.needReadable, state.emittedReadable); + state.needReadable = false; + if (!state.emittedReadable) { + debug('emitReadable', state.flowing); + state.emittedReadable = true; + process.nextTick(emitReadable_, stream); + } + } + function emitReadable_(stream) { + const state = stream._readableState; + debug('emitReadable_', state.destroyed, state.length, state.ended); + if (!state.destroyed && !state.errored && (state.length || state.ended)) { + stream.emit('readable'); + state.emittedReadable = false; + } + + // The stream needs another readable event if: + // 1. It is not flowing, as the flow mechanism will take + // care of it. + // 2. It is not ended. + // 3. It is below the highWaterMark, so we can schedule + // another readable later. + state.needReadable = !state.flowing && !state.ended && state.length <= state.highWaterMark; + flow(stream); + } + + // At this point, the user has presumably seen the 'readable' event, + // and called read() to consume some data. that may have triggered + // in turn another _read(n) call, in which case reading = true if + // it's in progress. + // However, if we're not ended, or reading, and the length < hwm, + // then go ahead and try to read some more preemptively. + function maybeReadMore(stream, state) { + if (!state.readingMore && state.constructed) { + state.readingMore = true; + process.nextTick(maybeReadMore_, stream, state); + } + } + function maybeReadMore_(stream, state) { + // Attempt to read more data if we should. + // + // The conditions for reading more data are (one of): + // - Not enough data buffered (state.length < state.highWaterMark). The loop + // is responsible for filling the buffer with enough data if such data + // is available. If highWaterMark is 0 and we are not in the flowing mode + // we should _not_ attempt to buffer any extra data. We'll get more data + // when the stream consumer calls read() instead. + // - No data in the buffer, and the stream is in flowing mode. In this mode + // the loop below is responsible for ensuring read() is called. Failing to + // call read here would abort the flow and there's no other mechanism for + // continuing the flow if the stream consumer has just subscribed to the + // 'data' event. + // + // In addition to the above conditions to keep reading data, the following + // conditions prevent the data from being read: + // - The stream has ended (state.ended). + // - There is already a pending 'read' operation (state.reading). This is a + // case where the stream has called the implementation defined _read() + // method, but they are processing the call asynchronously and have _not_ + // called push() with new data. In this case we skip performing more + // read()s. The execution ends in this method again after the _read() ends + // up calling push() with more data. + while ( + !state.reading && + !state.ended && + (state.length < state.highWaterMark || (state.flowing && state.length === 0)) + ) { + const len = state.length; + debug('maybeReadMore read 0'); + stream.read(0); + if (len === state.length) + // Didn't get any data, stop spinning. + break + } + state.readingMore = false; + } + + // Abstract method. to be overridden in specific implementation classes. + // call cb(er, data) where data is <= n in length. + // for virtual (non-string, non-buffer) streams, "length" is somewhat + // arbitrary, and perhaps not very meaningful. + Readable.prototype._read = function (n) { + throw new ERR_METHOD_NOT_IMPLEMENTED('_read()') + }; + Readable.prototype.pipe = function (dest, pipeOpts) { + const src = this; + const state = this._readableState; + if (state.pipes.length === 1) { + if (!state.multiAwaitDrain) { + state.multiAwaitDrain = true; + state.awaitDrainWriters = new SafeSet(state.awaitDrainWriters ? [state.awaitDrainWriters] : []); + } + } + state.pipes.push(dest); + debug('pipe count=%d opts=%j', state.pipes.length, pipeOpts); + const doEnd = (!pipeOpts || pipeOpts.end !== false) && dest !== process.stdout && dest !== process.stderr; + const endFn = doEnd ? onend : unpipe; + if (state.endEmitted) process.nextTick(endFn); + else src.once('end', endFn); + dest.on('unpipe', onunpipe); + function onunpipe(readable, unpipeInfo) { + debug('onunpipe'); + if (readable === src) { + if (unpipeInfo && unpipeInfo.hasUnpiped === false) { + unpipeInfo.hasUnpiped = true; + cleanup(); + } + } + } + function onend() { + debug('onend'); + dest.end(); + } + let ondrain; + let cleanedUp = false; + function cleanup() { + debug('cleanup'); + // Cleanup event handlers once the pipe is broken. + dest.removeListener('close', onclose); + dest.removeListener('finish', onfinish); + if (ondrain) { + dest.removeListener('drain', ondrain); + } + dest.removeListener('error', onerror); + dest.removeListener('unpipe', onunpipe); + src.removeListener('end', onend); + src.removeListener('end', unpipe); + src.removeListener('data', ondata); + cleanedUp = true; + + // If the reader is waiting for a drain event from this + // specific writer, then it would cause it to never start + // flowing again. + // So, if this is awaiting a drain, then we just call it now. + // If we don't know, then assume that we are waiting for one. + if (ondrain && state.awaitDrainWriters && (!dest._writableState || dest._writableState.needDrain)) ondrain(); + } + function pause() { + // If the user unpiped during `dest.write()`, it is possible + // to get stuck in a permanently paused state if that write + // also returned false. + // => Check whether `dest` is still a piping destination. + if (!cleanedUp) { + if (state.pipes.length === 1 && state.pipes[0] === dest) { + debug('false write response, pause', 0); + state.awaitDrainWriters = dest; + state.multiAwaitDrain = false; + } else if (state.pipes.length > 1 && state.pipes.includes(dest)) { + debug('false write response, pause', state.awaitDrainWriters.size); + state.awaitDrainWriters.add(dest); + } + src.pause(); + } + if (!ondrain) { + // When the dest drains, it reduces the awaitDrain counter + // on the source. This would be more elegant with a .once() + // handler in flow(), but adding and removing repeatedly is + // too slow. + ondrain = pipeOnDrain(src, dest); + dest.on('drain', ondrain); + } + } + src.on('data', ondata); + function ondata(chunk) { + debug('ondata'); + const ret = dest.write(chunk); + debug('dest.write', ret); + if (ret === false) { + pause(); + } + } + + // If the dest has an error, then stop piping into it. + // However, don't suppress the throwing behavior for this. + function onerror(er) { + debug('onerror', er); + unpipe(); + dest.removeListener('error', onerror); + if (dest.listenerCount('error') === 0) { + const s = dest._writableState || dest._readableState; + if (s && !s.errorEmitted) { + // User incorrectly emitted 'error' directly on the stream. + errorOrDestroy(dest, er); + } else { + dest.emit('error', er); + } + } + } + + // Make sure our error handler is attached before userland ones. + prependListener(dest, 'error', onerror); + + // Both close and finish should trigger unpipe, but only once. + function onclose() { + dest.removeListener('finish', onfinish); + unpipe(); + } + dest.once('close', onclose); + function onfinish() { + debug('onfinish'); + dest.removeListener('close', onclose); + unpipe(); + } + dest.once('finish', onfinish); + function unpipe() { + debug('unpipe'); + src.unpipe(dest); + } + + // Tell the dest that it's being piped to. + dest.emit('pipe', src); + + // Start the flow if it hasn't been started already. + + if (dest.writableNeedDrain === true) { + pause(); + } else if (!state.flowing) { + debug('pipe resume'); + src.resume(); + } + return dest + }; + function pipeOnDrain(src, dest) { + return function pipeOnDrainFunctionResult() { + const state = src._readableState; + + // `ondrain` will call directly, + // `this` maybe not a reference to dest, + // so we use the real dest here. + if (state.awaitDrainWriters === dest) { + debug('pipeOnDrain', 1); + state.awaitDrainWriters = null; + } else if (state.multiAwaitDrain) { + debug('pipeOnDrain', state.awaitDrainWriters.size); + state.awaitDrainWriters.delete(dest); + } + if ((!state.awaitDrainWriters || state.awaitDrainWriters.size === 0) && src.listenerCount('data')) { + src.resume(); + } + } + } + Readable.prototype.unpipe = function (dest) { + const state = this._readableState; + const unpipeInfo = { + hasUnpiped: false + }; + + // If we're not piping anywhere, then do nothing. + if (state.pipes.length === 0) return this + if (!dest) { + // remove all. + const dests = state.pipes; + state.pipes = []; + this.pause(); + for (let i = 0; i < dests.length; i++) + dests[i].emit('unpipe', this, { + hasUnpiped: false + }); + return this + } + + // Try to find the right one. + const index = ArrayPrototypeIndexOf(state.pipes, dest); + if (index === -1) return this + state.pipes.splice(index, 1); + if (state.pipes.length === 0) this.pause(); + dest.emit('unpipe', this, unpipeInfo); + return this + }; + + // Set up data events if they are asked for + // Ensure readable listeners eventually get something. + Readable.prototype.on = function (ev, fn) { + const res = Stream.prototype.on.call(this, ev, fn); + const state = this._readableState; + if (ev === 'data') { + // Update readableListening so that resume() may be a no-op + // a few lines down. This is needed to support once('readable'). + state.readableListening = this.listenerCount('readable') > 0; + + // Try start flowing on next tick if stream isn't explicitly paused. + if (state.flowing !== false) this.resume(); + } else if (ev === 'readable') { + if (!state.endEmitted && !state.readableListening) { + state.readableListening = state.needReadable = true; + state.flowing = false; + state.emittedReadable = false; + debug('on readable', state.length, state.reading); + if (state.length) { + emitReadable(this); + } else if (!state.reading) { + process.nextTick(nReadingNextTick, this); + } + } + } + return res + }; + Readable.prototype.addListener = Readable.prototype.on; + Readable.prototype.removeListener = function (ev, fn) { + const res = Stream.prototype.removeListener.call(this, ev, fn); + if (ev === 'readable') { + // We need to check if there is someone still listening to + // readable and reset the state. However this needs to happen + // after readable has been emitted but before I/O (nextTick) to + // support once('readable', fn) cycles. This means that calling + // resume within the same tick will have no + // effect. + process.nextTick(updateReadableListening, this); + } + return res + }; + Readable.prototype.off = Readable.prototype.removeListener; + Readable.prototype.removeAllListeners = function (ev) { + const res = Stream.prototype.removeAllListeners.apply(this, arguments); + if (ev === 'readable' || ev === undefined) { + // We need to check if there is someone still listening to + // readable and reset the state. However this needs to happen + // after readable has been emitted but before I/O (nextTick) to + // support once('readable', fn) cycles. This means that calling + // resume within the same tick will have no + // effect. + process.nextTick(updateReadableListening, this); + } + return res + }; + function updateReadableListening(self) { + const state = self._readableState; + state.readableListening = self.listenerCount('readable') > 0; + if (state.resumeScheduled && state[kPaused] === false) { + // Flowing needs to be set to true now, otherwise + // the upcoming resume will not flow. + state.flowing = true; + + // Crude way to check if we should resume. + } else if (self.listenerCount('data') > 0) { + self.resume(); + } else if (!state.readableListening) { + state.flowing = null; + } + } + function nReadingNextTick(self) { + debug('readable nexttick read 0'); + self.read(0); + } + + // pause() and resume() are remnants of the legacy readable stream API + // If the user uses them, then switch into old mode. + Readable.prototype.resume = function () { + const state = this._readableState; + if (!state.flowing) { + debug('resume'); + // We flow only if there is no one listening + // for readable, but we still have to call + // resume(). + state.flowing = !state.readableListening; + resume(this, state); + } + state[kPaused] = false; + return this + }; + function resume(stream, state) { + if (!state.resumeScheduled) { + state.resumeScheduled = true; + process.nextTick(resume_, stream, state); + } + } + function resume_(stream, state) { + debug('resume', state.reading); + if (!state.reading) { + stream.read(0); + } + state.resumeScheduled = false; + stream.emit('resume'); + flow(stream); + if (state.flowing && !state.reading) stream.read(0); + } + Readable.prototype.pause = function () { + debug('call pause flowing=%j', this._readableState.flowing); + if (this._readableState.flowing !== false) { + debug('pause'); + this._readableState.flowing = false; + this.emit('pause'); + } + this._readableState[kPaused] = true; + return this + }; + function flow(stream) { + const state = stream._readableState; + debug('flow', state.flowing); + while (state.flowing && stream.read() !== null); + } + + // Wrap an old-style stream as the async data source. + // This is *not* part of the readable stream interface. + // It is an ugly unfortunate mess of history. + Readable.prototype.wrap = function (stream) { + let paused = false; + + // TODO (ronag): Should this.destroy(err) emit + // 'error' on the wrapped stream? Would require + // a static factory method, e.g. Readable.wrap(stream). + + stream.on('data', (chunk) => { + if (!this.push(chunk) && stream.pause) { + paused = true; + stream.pause(); + } + }); + stream.on('end', () => { + this.push(null); + }); + stream.on('error', (err) => { + errorOrDestroy(this, err); + }); + stream.on('close', () => { + this.destroy(); + }); + stream.on('destroy', () => { + this.destroy(); + }); + this._read = () => { + if (paused && stream.resume) { + paused = false; + stream.resume(); + } + }; + + // Proxy all the other methods. Important when wrapping filters and duplexes. + const streamKeys = ObjectKeys(stream); + for (let j = 1; j < streamKeys.length; j++) { + const i = streamKeys[j]; + if (this[i] === undefined && typeof stream[i] === 'function') { + this[i] = stream[i].bind(stream); + } + } + return this + }; + Readable.prototype[SymbolAsyncIterator] = function () { + return streamToAsyncIterator(this) + }; + Readable.prototype.iterator = function (options) { + if (options !== undefined) { + validateObject(options, 'options'); + } + return streamToAsyncIterator(this, options) + }; + function streamToAsyncIterator(stream, options) { + if (typeof stream.read !== 'function') { + stream = Readable.wrap(stream, { + objectMode: true + }); + } + const iter = createAsyncIterator(stream, options); + iter.stream = stream; + return iter + } + async function* createAsyncIterator(stream, options) { + let callback = nop; + function next(resolve) { + if (this === stream) { + callback(); + callback = nop; + } else { + callback = resolve; + } + } + stream.on('readable', next); + let error; + const cleanup = eos( + stream, + { + writable: false + }, + (err) => { + error = err ? aggregateTwoErrors(error, err) : null; + callback(); + callback = nop; + } + ); + try { + while (true) { + const chunk = stream.destroyed ? null : stream.read(); + if (chunk !== null) { + yield chunk; + } else if (error) { + throw error + } else if (error === null) { + return + } else { + await new Promise(next); + } + } + } catch (err) { + error = aggregateTwoErrors(error, err); + throw error + } finally { + if ( + (error || (options === null || options === undefined ? undefined : options.destroyOnReturn) !== false) && + (error === undefined || stream._readableState.autoDestroy) + ) { + destroyImpl.destroyer(stream, null); + } else { + stream.off('readable', next); + cleanup(); + } + } + } + + // Making it explicit these properties are not enumerable + // because otherwise some prototype manipulation in + // userland will fail. + ObjectDefineProperties(Readable.prototype, { + readable: { + __proto__: null, + get() { + const r = this._readableState; + // r.readable === false means that this is part of a Duplex stream + // where the readable side was disabled upon construction. + // Compat. The user might manually disable readable side through + // deprecated setter. + return !!r && r.readable !== false && !r.destroyed && !r.errorEmitted && !r.endEmitted + }, + set(val) { + // Backwards compat. + if (this._readableState) { + this._readableState.readable = !!val; + } + } + }, + readableDidRead: { + __proto__: null, + enumerable: false, + get: function () { + return this._readableState.dataEmitted + } + }, + readableAborted: { + __proto__: null, + enumerable: false, + get: function () { + return !!( + this._readableState.readable !== false && + (this._readableState.destroyed || this._readableState.errored) && + !this._readableState.endEmitted + ) + } + }, + readableHighWaterMark: { + __proto__: null, + enumerable: false, + get: function () { + return this._readableState.highWaterMark + } + }, + readableBuffer: { + __proto__: null, + enumerable: false, + get: function () { + return this._readableState && this._readableState.buffer + } + }, + readableFlowing: { + __proto__: null, + enumerable: false, + get: function () { + return this._readableState.flowing + }, + set: function (state) { + if (this._readableState) { + this._readableState.flowing = state; + } + } + }, + readableLength: { + __proto__: null, + enumerable: false, + get() { + return this._readableState.length + } + }, + readableObjectMode: { + __proto__: null, + enumerable: false, + get() { + return this._readableState ? this._readableState.objectMode : false + } + }, + readableEncoding: { + __proto__: null, + enumerable: false, + get() { + return this._readableState ? this._readableState.encoding : null + } + }, + errored: { + __proto__: null, + enumerable: false, + get() { + return this._readableState ? this._readableState.errored : null + } + }, + closed: { + __proto__: null, + get() { + return this._readableState ? this._readableState.closed : false + } + }, + destroyed: { + __proto__: null, + enumerable: false, + get() { + return this._readableState ? this._readableState.destroyed : false + }, + set(value) { + // We ignore the value if the stream + // has not been initialized yet. + if (!this._readableState) { + return + } + + // Backward compatibility, the user is explicitly + // managing destroyed. + this._readableState.destroyed = value; + } + }, + readableEnded: { + __proto__: null, + enumerable: false, + get() { + return this._readableState ? this._readableState.endEmitted : false + } + } + }); + ObjectDefineProperties(ReadableState.prototype, { + // Legacy getter for `pipesCount`. + pipesCount: { + __proto__: null, + get() { + return this.pipes.length + } + }, + // Legacy property for `paused`. + paused: { + __proto__: null, + get() { + return this[kPaused] !== false + }, + set(value) { + this[kPaused] = !!value; + } + } + }); + + // Exposed for testing purposes only. + Readable._fromList = fromList; + + // Pluck off n bytes from an array of buffers. + // Length is the combined lengths of all the buffers in the list. + // This function is designed to be inlinable, so please take care when making + // changes to the function body. + function fromList(n, state) { + // nothing buffered. + if (state.length === 0) return null + let ret; + if (state.objectMode) ret = state.buffer.shift(); + else if (!n || n >= state.length) { + // Read it all, truncate the list. + if (state.decoder) ret = state.buffer.join(''); + else if (state.buffer.length === 1) ret = state.buffer.first(); + else ret = state.buffer.concat(state.length); + state.buffer.clear(); + } else { + // read part of list. + ret = state.buffer.consume(n, state.decoder); + } + return ret + } + function endReadable(stream) { + const state = stream._readableState; + debug('endReadable', state.endEmitted); + if (!state.endEmitted) { + state.ended = true; + process.nextTick(endReadableNT, state, stream); + } + } + function endReadableNT(state, stream) { + debug('endReadableNT', state.endEmitted, state.length); + + // Check that we didn't get one last unshift. + if (!state.errored && !state.closeEmitted && !state.endEmitted && state.length === 0) { + state.endEmitted = true; + stream.emit('end'); + if (stream.writable && stream.allowHalfOpen === false) { + process.nextTick(endWritableNT, stream); + } else if (state.autoDestroy) { + // In case of duplex streams we need a way to detect + // if the writable side is ready for autoDestroy as well. + const wState = stream._writableState; + const autoDestroy = + !wState || + (wState.autoDestroy && + // We don't expect the writable to ever 'finish' + // if writable is explicitly set to false. + (wState.finished || wState.writable === false)); + if (autoDestroy) { + stream.destroy(); + } + } + } + } + function endWritableNT(stream) { + const writable = stream.writable && !stream.writableEnded && !stream.destroyed; + if (writable) { + stream.end(); + } + } + Readable.from = function (iterable, opts) { + return from(Readable, iterable, opts) + }; + let webStreamsAdapters; + + // Lazy to avoid circular references + function lazyWebStreams() { + if (webStreamsAdapters === undefined) webStreamsAdapters = {}; + return webStreamsAdapters + } + Readable.fromWeb = function (readableStream, options) { + return lazyWebStreams().newStreamReadableFromReadableStream(readableStream, options) + }; + Readable.toWeb = function (streamReadable, options) { + return lazyWebStreams().newReadableStreamFromStreamReadable(streamReadable, options) + }; + Readable.wrap = function (src, options) { + var _ref, _src$readableObjectMo; + return new Readable({ + objectMode: + (_ref = + (_src$readableObjectMo = src.readableObjectMode) !== null && _src$readableObjectMo !== undefined + ? _src$readableObjectMo + : src.objectMode) !== null && _ref !== undefined + ? _ref + : true, + ...options, + destroy(err, callback) { + destroyImpl.destroyer(src, err); + callback(err); + } + }).wrap(src) + }; + return readable; +} + +var writable; +var hasRequiredWritable; + +function requireWritable () { + if (hasRequiredWritable) return writable; + hasRequiredWritable = 1; + + /* replacement start */ + + const process = requireBrowser$2(); + + /* replacement end */ + + const { + ArrayPrototypeSlice, + Error, + FunctionPrototypeSymbolHasInstance, + ObjectDefineProperty, + ObjectDefineProperties, + ObjectSetPrototypeOf, + StringPrototypeToLowerCase, + Symbol, + SymbolHasInstance + } = requirePrimordials(); + writable = Writable; + Writable.WritableState = WritableState; + const { EventEmitter: EE } = requireEvents$1(); + const Stream = requireLegacy().Stream; + const { Buffer } = require$$0$1; + const destroyImpl = requireDestroy(); + const { addAbortSignal } = requireAddAbortSignal(); + const { getHighWaterMark, getDefaultHighWaterMark } = requireState(); + const { + ERR_INVALID_ARG_TYPE, + ERR_METHOD_NOT_IMPLEMENTED, + ERR_MULTIPLE_CALLBACK, + ERR_STREAM_CANNOT_PIPE, + ERR_STREAM_DESTROYED, + ERR_STREAM_ALREADY_FINISHED, + ERR_STREAM_NULL_VALUES, + ERR_STREAM_WRITE_AFTER_END, + ERR_UNKNOWN_ENCODING + } = requireErrors().codes; + const { errorOrDestroy } = destroyImpl; + ObjectSetPrototypeOf(Writable.prototype, Stream.prototype); + ObjectSetPrototypeOf(Writable, Stream); + function nop() {} + const kOnFinished = Symbol('kOnFinished'); + function WritableState(options, stream, isDuplex) { + // Duplex streams are both readable and writable, but share + // the same options object. + // However, some cases require setting options to different + // values for the readable and the writable sides of the duplex stream, + // e.g. options.readableObjectMode vs. options.writableObjectMode, etc. + if (typeof isDuplex !== 'boolean') isDuplex = stream instanceof requireDuplex(); + + // Object stream flag to indicate whether or not this stream + // contains buffers or objects. + this.objectMode = !!(options && options.objectMode); + if (isDuplex) this.objectMode = this.objectMode || !!(options && options.writableObjectMode); + + // The point at which write() starts returning false + // Note: 0 is a valid value, means that we always return false if + // the entire buffer is not flushed immediately on write(). + this.highWaterMark = options + ? getHighWaterMark(this, options, 'writableHighWaterMark', isDuplex) + : getDefaultHighWaterMark(false); + + // if _final has been called. + this.finalCalled = false; + + // drain event flag. + this.needDrain = false; + // At the start of calling end() + this.ending = false; + // When end() has been called, and returned. + this.ended = false; + // When 'finish' is emitted. + this.finished = false; + + // Has it been destroyed + this.destroyed = false; + + // Should we decode strings into buffers before passing to _write? + // this is here so that some node-core streams can optimize string + // handling at a lower level. + const noDecode = !!(options && options.decodeStrings === false); + this.decodeStrings = !noDecode; + + // Crypto is kind of old and crusty. Historically, its default string + // encoding is 'binary' so we have to make this configurable. + // Everything else in the universe uses 'utf8', though. + this.defaultEncoding = (options && options.defaultEncoding) || 'utf8'; + + // Not an actual buffer we keep track of, but a measurement + // of how much we're waiting to get pushed to some underlying + // socket or file. + this.length = 0; + + // A flag to see when we're in the middle of a write. + this.writing = false; + + // When true all writes will be buffered until .uncork() call. + this.corked = 0; + + // A flag to be able to tell if the onwrite cb is called immediately, + // or on a later tick. We set this to true at first, because any + // actions that shouldn't happen until "later" should generally also + // not happen before the first write call. + this.sync = true; + + // A flag to know if we're processing previously buffered items, which + // may call the _write() callback in the same tick, so that we don't + // end up in an overlapped onwrite situation. + this.bufferProcessing = false; + + // The callback that's passed to _write(chunk, cb). + this.onwrite = onwrite.bind(undefined, stream); + + // The callback that the user supplies to write(chunk, encoding, cb). + this.writecb = null; + + // The amount that is being written when _write is called. + this.writelen = 0; + + // Storage for data passed to the afterWrite() callback in case of + // synchronous _write() completion. + this.afterWriteTickInfo = null; + resetBuffer(this); + + // Number of pending user-supplied write callbacks + // this must be 0 before 'finish' can be emitted. + this.pendingcb = 0; + + // Stream is still being constructed and cannot be + // destroyed until construction finished or failed. + // Async construction is opt in, therefore we start as + // constructed. + this.constructed = true; + + // Emit prefinish if the only thing we're waiting for is _write cbs + // This is relevant for synchronous Transform streams. + this.prefinished = false; + + // True if the error was already emitted and should not be thrown again. + this.errorEmitted = false; + + // Should close be emitted on destroy. Defaults to true. + this.emitClose = !options || options.emitClose !== false; + + // Should .destroy() be called after 'finish' (and potentially 'end'). + this.autoDestroy = !options || options.autoDestroy !== false; + + // Indicates whether the stream has errored. When true all write() calls + // should return false. This is needed since when autoDestroy + // is disabled we need a way to tell whether the stream has failed. + this.errored = null; + + // Indicates whether the stream has finished destroying. + this.closed = false; + + // True if close has been emitted or would have been emitted + // depending on emitClose. + this.closeEmitted = false; + this[kOnFinished] = []; + } + function resetBuffer(state) { + state.buffered = []; + state.bufferedIndex = 0; + state.allBuffers = true; + state.allNoop = true; + } + WritableState.prototype.getBuffer = function getBuffer() { + return ArrayPrototypeSlice(this.buffered, this.bufferedIndex) + }; + ObjectDefineProperty(WritableState.prototype, 'bufferedRequestCount', { + __proto__: null, + get() { + return this.buffered.length - this.bufferedIndex + } + }); + function Writable(options) { + // Writable ctor is applied to Duplexes, too. + // `realHasInstance` is necessary because using plain `instanceof` + // would return false, as no `_writableState` property is attached. + + // Trying to use the custom `instanceof` for Writable here will also break the + // Node.js LazyTransform implementation, which has a non-trivial getter for + // `_writableState` that would lead to infinite recursion. + + // Checking for a Stream.Duplex instance is faster here instead of inside + // the WritableState constructor, at least with V8 6.5. + const isDuplex = this instanceof requireDuplex(); + if (!isDuplex && !FunctionPrototypeSymbolHasInstance(Writable, this)) return new Writable(options) + this._writableState = new WritableState(options, this, isDuplex); + if (options) { + if (typeof options.write === 'function') this._write = options.write; + if (typeof options.writev === 'function') this._writev = options.writev; + if (typeof options.destroy === 'function') this._destroy = options.destroy; + if (typeof options.final === 'function') this._final = options.final; + if (typeof options.construct === 'function') this._construct = options.construct; + if (options.signal) addAbortSignal(options.signal, this); + } + Stream.call(this, options); + destroyImpl.construct(this, () => { + const state = this._writableState; + if (!state.writing) { + clearBuffer(this, state); + } + finishMaybe(this, state); + }); + } + ObjectDefineProperty(Writable, SymbolHasInstance, { + __proto__: null, + value: function (object) { + if (FunctionPrototypeSymbolHasInstance(this, object)) return true + if (this !== Writable) return false + return object && object._writableState instanceof WritableState + } + }); + + // Otherwise people can pipe Writable streams, which is just wrong. + Writable.prototype.pipe = function () { + errorOrDestroy(this, new ERR_STREAM_CANNOT_PIPE()); + }; + function _write(stream, chunk, encoding, cb) { + const state = stream._writableState; + if (typeof encoding === 'function') { + cb = encoding; + encoding = state.defaultEncoding; + } else { + if (!encoding) encoding = state.defaultEncoding; + else if (encoding !== 'buffer' && !Buffer.isEncoding(encoding)) throw new ERR_UNKNOWN_ENCODING(encoding) + if (typeof cb !== 'function') cb = nop; + } + if (chunk === null) { + throw new ERR_STREAM_NULL_VALUES() + } else if (!state.objectMode) { + if (typeof chunk === 'string') { + if (state.decodeStrings !== false) { + chunk = Buffer.from(chunk, encoding); + encoding = 'buffer'; + } + } else if (chunk instanceof Buffer) { + encoding = 'buffer'; + } else if (Stream._isUint8Array(chunk)) { + chunk = Stream._uint8ArrayToBuffer(chunk); + encoding = 'buffer'; + } else { + throw new ERR_INVALID_ARG_TYPE('chunk', ['string', 'Buffer', 'Uint8Array'], chunk) + } + } + let err; + if (state.ending) { + err = new ERR_STREAM_WRITE_AFTER_END(); + } else if (state.destroyed) { + err = new ERR_STREAM_DESTROYED('write'); + } + if (err) { + process.nextTick(cb, err); + errorOrDestroy(stream, err, true); + return err + } + state.pendingcb++; + return writeOrBuffer(stream, state, chunk, encoding, cb) + } + Writable.prototype.write = function (chunk, encoding, cb) { + return _write(this, chunk, encoding, cb) === true + }; + Writable.prototype.cork = function () { + this._writableState.corked++; + }; + Writable.prototype.uncork = function () { + const state = this._writableState; + if (state.corked) { + state.corked--; + if (!state.writing) clearBuffer(this, state); + } + }; + Writable.prototype.setDefaultEncoding = function setDefaultEncoding(encoding) { + // node::ParseEncoding() requires lower case. + if (typeof encoding === 'string') encoding = StringPrototypeToLowerCase(encoding); + if (!Buffer.isEncoding(encoding)) throw new ERR_UNKNOWN_ENCODING(encoding) + this._writableState.defaultEncoding = encoding; + return this + }; + + // If we're already writing something, then just put this + // in the queue, and wait our turn. Otherwise, call _write + // If we return false, then we need a drain event, so set that flag. + function writeOrBuffer(stream, state, chunk, encoding, callback) { + const len = state.objectMode ? 1 : chunk.length; + state.length += len; + + // stream._write resets state.length + const ret = state.length < state.highWaterMark; + // We must ensure that previous needDrain will not be reset to false. + if (!ret) state.needDrain = true; + if (state.writing || state.corked || state.errored || !state.constructed) { + state.buffered.push({ + chunk, + encoding, + callback + }); + if (state.allBuffers && encoding !== 'buffer') { + state.allBuffers = false; + } + if (state.allNoop && callback !== nop) { + state.allNoop = false; + } + } else { + state.writelen = len; + state.writecb = callback; + state.writing = true; + state.sync = true; + stream._write(chunk, encoding, state.onwrite); + state.sync = false; + } + + // Return false if errored or destroyed in order to break + // any synchronous while(stream.write(data)) loops. + return ret && !state.errored && !state.destroyed + } + function doWrite(stream, state, writev, len, chunk, encoding, cb) { + state.writelen = len; + state.writecb = cb; + state.writing = true; + state.sync = true; + if (state.destroyed) state.onwrite(new ERR_STREAM_DESTROYED('write')); + else if (writev) stream._writev(chunk, state.onwrite); + else stream._write(chunk, encoding, state.onwrite); + state.sync = false; + } + function onwriteError(stream, state, er, cb) { + --state.pendingcb; + cb(er); + // Ensure callbacks are invoked even when autoDestroy is + // not enabled. Passing `er` here doesn't make sense since + // it's related to one specific write, not to the buffered + // writes. + errorBuffer(state); + // This can emit error, but error must always follow cb. + errorOrDestroy(stream, er); + } + function onwrite(stream, er) { + const state = stream._writableState; + const sync = state.sync; + const cb = state.writecb; + if (typeof cb !== 'function') { + errorOrDestroy(stream, new ERR_MULTIPLE_CALLBACK()); + return + } + state.writing = false; + state.writecb = null; + state.length -= state.writelen; + state.writelen = 0; + if (er) { + // Avoid V8 leak, https://github.com/nodejs/node/pull/34103#issuecomment-652002364 + er.stack; // eslint-disable-line no-unused-expressions + + if (!state.errored) { + state.errored = er; + } + + // In case of duplex streams we need to notify the readable side of the + // error. + if (stream._readableState && !stream._readableState.errored) { + stream._readableState.errored = er; + } + if (sync) { + process.nextTick(onwriteError, stream, state, er, cb); + } else { + onwriteError(stream, state, er, cb); + } + } else { + if (state.buffered.length > state.bufferedIndex) { + clearBuffer(stream, state); + } + if (sync) { + // It is a common case that the callback passed to .write() is always + // the same. In that case, we do not schedule a new nextTick(), but + // rather just increase a counter, to improve performance and avoid + // memory allocations. + if (state.afterWriteTickInfo !== null && state.afterWriteTickInfo.cb === cb) { + state.afterWriteTickInfo.count++; + } else { + state.afterWriteTickInfo = { + count: 1, + cb, + stream, + state + }; + process.nextTick(afterWriteTick, state.afterWriteTickInfo); + } + } else { + afterWrite(stream, state, 1, cb); + } + } + } + function afterWriteTick({ stream, state, count, cb }) { + state.afterWriteTickInfo = null; + return afterWrite(stream, state, count, cb) + } + function afterWrite(stream, state, count, cb) { + const needDrain = !state.ending && !stream.destroyed && state.length === 0 && state.needDrain; + if (needDrain) { + state.needDrain = false; + stream.emit('drain'); + } + while (count-- > 0) { + state.pendingcb--; + cb(); + } + if (state.destroyed) { + errorBuffer(state); + } + finishMaybe(stream, state); + } + + // If there's something in the buffer waiting, then invoke callbacks. + function errorBuffer(state) { + if (state.writing) { + return + } + for (let n = state.bufferedIndex; n < state.buffered.length; ++n) { + var _state$errored; + const { chunk, callback } = state.buffered[n]; + const len = state.objectMode ? 1 : chunk.length; + state.length -= len; + callback( + (_state$errored = state.errored) !== null && _state$errored !== undefined + ? _state$errored + : new ERR_STREAM_DESTROYED('write') + ); + } + const onfinishCallbacks = state[kOnFinished].splice(0); + for (let i = 0; i < onfinishCallbacks.length; i++) { + var _state$errored2; + onfinishCallbacks[i]( + (_state$errored2 = state.errored) !== null && _state$errored2 !== undefined + ? _state$errored2 + : new ERR_STREAM_DESTROYED('end') + ); + } + resetBuffer(state); + } + + // If there's something in the buffer waiting, then process it. + function clearBuffer(stream, state) { + if (state.corked || state.bufferProcessing || state.destroyed || !state.constructed) { + return + } + const { buffered, bufferedIndex, objectMode } = state; + const bufferedLength = buffered.length - bufferedIndex; + if (!bufferedLength) { + return + } + let i = bufferedIndex; + state.bufferProcessing = true; + if (bufferedLength > 1 && stream._writev) { + state.pendingcb -= bufferedLength - 1; + const callback = state.allNoop + ? nop + : (err) => { + for (let n = i; n < buffered.length; ++n) { + buffered[n].callback(err); + } + }; + // Make a copy of `buffered` if it's going to be used by `callback` above, + // since `doWrite` will mutate the array. + const chunks = state.allNoop && i === 0 ? buffered : ArrayPrototypeSlice(buffered, i); + chunks.allBuffers = state.allBuffers; + doWrite(stream, state, true, state.length, chunks, '', callback); + resetBuffer(state); + } else { + do { + const { chunk, encoding, callback } = buffered[i]; + buffered[i++] = null; + const len = objectMode ? 1 : chunk.length; + doWrite(stream, state, false, len, chunk, encoding, callback); + } while (i < buffered.length && !state.writing) + if (i === buffered.length) { + resetBuffer(state); + } else if (i > 256) { + buffered.splice(0, i); + state.bufferedIndex = 0; + } else { + state.bufferedIndex = i; + } + } + state.bufferProcessing = false; + } + Writable.prototype._write = function (chunk, encoding, cb) { + if (this._writev) { + this._writev( + [ + { + chunk, + encoding + } + ], + cb + ); + } else { + throw new ERR_METHOD_NOT_IMPLEMENTED('_write()') + } + }; + Writable.prototype._writev = null; + Writable.prototype.end = function (chunk, encoding, cb) { + const state = this._writableState; + if (typeof chunk === 'function') { + cb = chunk; + chunk = null; + encoding = null; + } else if (typeof encoding === 'function') { + cb = encoding; + encoding = null; + } + let err; + if (chunk !== null && chunk !== undefined) { + const ret = _write(this, chunk, encoding); + if (ret instanceof Error) { + err = ret; + } + } + + // .end() fully uncorks. + if (state.corked) { + state.corked = 1; + this.uncork(); + } + if (err) ; else if (!state.errored && !state.ending) { + // This is forgiving in terms of unnecessary calls to end() and can hide + // logic errors. However, usually such errors are harmless and causing a + // hard error can be disproportionately destructive. It is not always + // trivial for the user to determine whether end() needs to be called + // or not. + + state.ending = true; + finishMaybe(this, state, true); + state.ended = true; + } else if (state.finished) { + err = new ERR_STREAM_ALREADY_FINISHED('end'); + } else if (state.destroyed) { + err = new ERR_STREAM_DESTROYED('end'); + } + if (typeof cb === 'function') { + if (err || state.finished) { + process.nextTick(cb, err); + } else { + state[kOnFinished].push(cb); + } + } + return this + }; + function needFinish(state) { + return ( + state.ending && + !state.destroyed && + state.constructed && + state.length === 0 && + !state.errored && + state.buffered.length === 0 && + !state.finished && + !state.writing && + !state.errorEmitted && + !state.closeEmitted + ) + } + function callFinal(stream, state) { + let called = false; + function onFinish(err) { + if (called) { + errorOrDestroy(stream, err !== null && err !== undefined ? err : ERR_MULTIPLE_CALLBACK()); + return + } + called = true; + state.pendingcb--; + if (err) { + const onfinishCallbacks = state[kOnFinished].splice(0); + for (let i = 0; i < onfinishCallbacks.length; i++) { + onfinishCallbacks[i](err); + } + errorOrDestroy(stream, err, state.sync); + } else if (needFinish(state)) { + state.prefinished = true; + stream.emit('prefinish'); + // Backwards compat. Don't check state.sync here. + // Some streams assume 'finish' will be emitted + // asynchronously relative to _final callback. + state.pendingcb++; + process.nextTick(finish, stream, state); + } + } + state.sync = true; + state.pendingcb++; + try { + stream._final(onFinish); + } catch (err) { + onFinish(err); + } + state.sync = false; + } + function prefinish(stream, state) { + if (!state.prefinished && !state.finalCalled) { + if (typeof stream._final === 'function' && !state.destroyed) { + state.finalCalled = true; + callFinal(stream, state); + } else { + state.prefinished = true; + stream.emit('prefinish'); + } + } + } + function finishMaybe(stream, state, sync) { + if (needFinish(state)) { + prefinish(stream, state); + if (state.pendingcb === 0) { + if (sync) { + state.pendingcb++; + process.nextTick( + (stream, state) => { + if (needFinish(state)) { + finish(stream, state); + } else { + state.pendingcb--; + } + }, + stream, + state + ); + } else if (needFinish(state)) { + state.pendingcb++; + finish(stream, state); + } + } + } + } + function finish(stream, state) { + state.pendingcb--; + state.finished = true; + const onfinishCallbacks = state[kOnFinished].splice(0); + for (let i = 0; i < onfinishCallbacks.length; i++) { + onfinishCallbacks[i](); + } + stream.emit('finish'); + if (state.autoDestroy) { + // In case of duplex streams we need a way to detect + // if the readable side is ready for autoDestroy as well. + const rState = stream._readableState; + const autoDestroy = + !rState || + (rState.autoDestroy && + // We don't expect the readable to ever 'end' + // if readable is explicitly set to false. + (rState.endEmitted || rState.readable === false)); + if (autoDestroy) { + stream.destroy(); + } + } + } + ObjectDefineProperties(Writable.prototype, { + closed: { + __proto__: null, + get() { + return this._writableState ? this._writableState.closed : false + } + }, + destroyed: { + __proto__: null, + get() { + return this._writableState ? this._writableState.destroyed : false + }, + set(value) { + // Backward compatibility, the user is explicitly managing destroyed. + if (this._writableState) { + this._writableState.destroyed = value; + } + } + }, + writable: { + __proto__: null, + get() { + const w = this._writableState; + // w.writable === false means that this is part of a Duplex stream + // where the writable side was disabled upon construction. + // Compat. The user might manually disable writable side through + // deprecated setter. + return !!w && w.writable !== false && !w.destroyed && !w.errored && !w.ending && !w.ended + }, + set(val) { + // Backwards compatible. + if (this._writableState) { + this._writableState.writable = !!val; + } + } + }, + writableFinished: { + __proto__: null, + get() { + return this._writableState ? this._writableState.finished : false + } + }, + writableObjectMode: { + __proto__: null, + get() { + return this._writableState ? this._writableState.objectMode : false + } + }, + writableBuffer: { + __proto__: null, + get() { + return this._writableState && this._writableState.getBuffer() + } + }, + writableEnded: { + __proto__: null, + get() { + return this._writableState ? this._writableState.ending : false + } + }, + writableNeedDrain: { + __proto__: null, + get() { + const wState = this._writableState; + if (!wState) return false + return !wState.destroyed && !wState.ending && wState.needDrain + } + }, + writableHighWaterMark: { + __proto__: null, + get() { + return this._writableState && this._writableState.highWaterMark + } + }, + writableCorked: { + __proto__: null, + get() { + return this._writableState ? this._writableState.corked : 0 + } + }, + writableLength: { + __proto__: null, + get() { + return this._writableState && this._writableState.length + } + }, + errored: { + __proto__: null, + enumerable: false, + get() { + return this._writableState ? this._writableState.errored : null + } + }, + writableAborted: { + __proto__: null, + enumerable: false, + get: function () { + return !!( + this._writableState.writable !== false && + (this._writableState.destroyed || this._writableState.errored) && + !this._writableState.finished + ) + } + } + }); + const destroy = destroyImpl.destroy; + Writable.prototype.destroy = function (err, cb) { + const state = this._writableState; + + // Invoke pending callbacks. + if (!state.destroyed && (state.bufferedIndex < state.buffered.length || state[kOnFinished].length)) { + process.nextTick(errorBuffer, state); + } + destroy.call(this, err, cb); + return this + }; + Writable.prototype._undestroy = destroyImpl.undestroy; + Writable.prototype._destroy = function (err, cb) { + cb(err); + }; + Writable.prototype[EE.captureRejectionSymbol] = function (err) { + this.destroy(err); + }; + let webStreamsAdapters; + + // Lazy to avoid circular references + function lazyWebStreams() { + if (webStreamsAdapters === undefined) webStreamsAdapters = {}; + return webStreamsAdapters + } + Writable.fromWeb = function (writableStream, options) { + return lazyWebStreams().newStreamWritableFromWritableStream(writableStream, options) + }; + Writable.toWeb = function (streamWritable) { + return lazyWebStreams().newWritableStreamFromStreamWritable(streamWritable) + }; + return writable; +} + +/* replacement start */ + +var duplexify; +var hasRequiredDuplexify; + +function requireDuplexify () { + if (hasRequiredDuplexify) return duplexify; + hasRequiredDuplexify = 1; + const process = requireBrowser$2() + + /* replacement end */ + + ; const bufferModule = require$$0$1; + const { + isReadable, + isWritable, + isIterable, + isNodeStream, + isReadableNodeStream, + isWritableNodeStream, + isDuplexNodeStream, + isReadableStream, + isWritableStream + } = requireUtils(); + const eos = requireEndOfStream(); + const { + AbortError, + codes: { ERR_INVALID_ARG_TYPE, ERR_INVALID_RETURN_VALUE } + } = requireErrors(); + const { destroyer } = requireDestroy(); + const Duplex = requireDuplex(); + const Readable = requireReadable(); + const Writable = requireWritable(); + const { createDeferredPromise } = requireUtil$2(); + const from = requireFrom(); + const Blob = globalThis.Blob || bufferModule.Blob; + const isBlob = + typeof Blob !== 'undefined' + ? function isBlob(b) { + return b instanceof Blob + } + : function isBlob(b) { + return false + }; + const AbortController = globalThis.AbortController || requireBrowser$1().AbortController; + const { FunctionPrototypeCall } = requirePrimordials(); + + // This is needed for pre node 17. + class Duplexify extends Duplex { + constructor(options) { + super(options); + + // https://github.com/nodejs/node/pull/34385 + + if ((options === null || options === undefined ? undefined : options.readable) === false) { + this._readableState.readable = false; + this._readableState.ended = true; + this._readableState.endEmitted = true; + } + if ((options === null || options === undefined ? undefined : options.writable) === false) { + this._writableState.writable = false; + this._writableState.ending = true; + this._writableState.ended = true; + this._writableState.finished = true; + } + } + } + duplexify = function duplexify(body, name) { + if (isDuplexNodeStream(body)) { + return body + } + if (isReadableNodeStream(body)) { + return _duplexify({ + readable: body + }) + } + if (isWritableNodeStream(body)) { + return _duplexify({ + writable: body + }) + } + if (isNodeStream(body)) { + return _duplexify({ + writable: false, + readable: false + }) + } + if (isReadableStream(body)) { + return _duplexify({ + readable: Readable.fromWeb(body) + }) + } + if (isWritableStream(body)) { + return _duplexify({ + writable: Writable.fromWeb(body) + }) + } + if (typeof body === 'function') { + const { value, write, final, destroy } = fromAsyncGen(body); + if (isIterable(value)) { + return from(Duplexify, value, { + // TODO (ronag): highWaterMark? + objectMode: true, + write, + final, + destroy + }) + } + const then = value === null || value === undefined ? undefined : value.then; + if (typeof then === 'function') { + let d; + const promise = FunctionPrototypeCall( + then, + value, + (val) => { + if (val != null) { + throw new ERR_INVALID_RETURN_VALUE('nully', 'body', val) + } + }, + (err) => { + destroyer(d, err); + } + ); + return (d = new Duplexify({ + // TODO (ronag): highWaterMark? + objectMode: true, + readable: false, + write, + final(cb) { + final(async () => { + try { + await promise; + process.nextTick(cb, null); + } catch (err) { + process.nextTick(cb, err); + } + }); + }, + destroy + })) + } + throw new ERR_INVALID_RETURN_VALUE('Iterable, AsyncIterable or AsyncFunction', name, value) + } + if (isBlob(body)) { + return duplexify(body.arrayBuffer()) + } + if (isIterable(body)) { + return from(Duplexify, body, { + // TODO (ronag): highWaterMark? + objectMode: true, + writable: false + }) + } + if ( + isReadableStream(body === null || body === undefined ? undefined : body.readable) && + isWritableStream(body === null || body === undefined ? undefined : body.writable) + ) { + return Duplexify.fromWeb(body) + } + if ( + typeof (body === null || body === undefined ? undefined : body.writable) === 'object' || + typeof (body === null || body === undefined ? undefined : body.readable) === 'object' + ) { + const readable = + body !== null && body !== undefined && body.readable + ? isReadableNodeStream(body === null || body === undefined ? undefined : body.readable) + ? body === null || body === undefined + ? undefined + : body.readable + : duplexify(body.readable) + : undefined; + const writable = + body !== null && body !== undefined && body.writable + ? isWritableNodeStream(body === null || body === undefined ? undefined : body.writable) + ? body === null || body === undefined + ? undefined + : body.writable + : duplexify(body.writable) + : undefined; + return _duplexify({ + readable, + writable + }) + } + const then = body === null || body === undefined ? undefined : body.then; + if (typeof then === 'function') { + let d; + FunctionPrototypeCall( + then, + body, + (val) => { + if (val != null) { + d.push(val); + } + d.push(null); + }, + (err) => { + destroyer(d, err); + } + ); + return (d = new Duplexify({ + objectMode: true, + writable: false, + read() {} + })) + } + throw new ERR_INVALID_ARG_TYPE( + name, + [ + 'Blob', + 'ReadableStream', + 'WritableStream', + 'Stream', + 'Iterable', + 'AsyncIterable', + 'Function', + '{ readable, writable } pair', + 'Promise' + ], + body + ) + }; + function fromAsyncGen(fn) { + let { promise, resolve } = createDeferredPromise(); + const ac = new AbortController(); + const signal = ac.signal; + const value = fn( + (async function* () { + while (true) { + const _promise = promise; + promise = null; + const { chunk, done, cb } = await _promise; + process.nextTick(cb); + if (done) return + if (signal.aborted) + throw new AbortError(undefined, { + cause: signal.reason + }) + ;({ promise, resolve } = createDeferredPromise()); + yield chunk; + } + })(), + { + signal + } + ); + return { + value, + write(chunk, encoding, cb) { + const _resolve = resolve; + resolve = null; + _resolve({ + chunk, + done: false, + cb + }); + }, + final(cb) { + const _resolve = resolve; + resolve = null; + _resolve({ + done: true, + cb + }); + }, + destroy(err, cb) { + ac.abort(); + cb(err); + } + } + } + function _duplexify(pair) { + const r = pair.readable && typeof pair.readable.read !== 'function' ? Readable.wrap(pair.readable) : pair.readable; + const w = pair.writable; + let readable = !!isReadable(r); + let writable = !!isWritable(w); + let ondrain; + let onfinish; + let onreadable; + let onclose; + let d; + function onfinished(err) { + const cb = onclose; + onclose = null; + if (cb) { + cb(err); + } else if (err) { + d.destroy(err); + } + } + + // TODO(ronag): Avoid double buffering. + // Implement Writable/Readable/Duplex traits. + // See, https://github.com/nodejs/node/pull/33515. + d = new Duplexify({ + // TODO (ronag): highWaterMark? + readableObjectMode: !!(r !== null && r !== undefined && r.readableObjectMode), + writableObjectMode: !!(w !== null && w !== undefined && w.writableObjectMode), + readable, + writable + }); + if (writable) { + eos(w, (err) => { + writable = false; + if (err) { + destroyer(r, err); + } + onfinished(err); + }); + d._write = function (chunk, encoding, callback) { + if (w.write(chunk, encoding)) { + callback(); + } else { + ondrain = callback; + } + }; + d._final = function (callback) { + w.end(); + onfinish = callback; + }; + w.on('drain', function () { + if (ondrain) { + const cb = ondrain; + ondrain = null; + cb(); + } + }); + w.on('finish', function () { + if (onfinish) { + const cb = onfinish; + onfinish = null; + cb(); + } + }); + } + if (readable) { + eos(r, (err) => { + readable = false; + if (err) { + destroyer(r, err); + } + onfinished(err); + }); + r.on('readable', function () { + if (onreadable) { + const cb = onreadable; + onreadable = null; + cb(); + } + }); + r.on('end', function () { + d.push(null); + }); + d._read = function () { + while (true) { + const buf = r.read(); + if (buf === null) { + onreadable = d._read; + return + } + if (!d.push(buf)) { + return + } + } + }; + } + d._destroy = function (err, callback) { + if (!err && onclose !== null) { + err = new AbortError(); + } + onreadable = null; + ondrain = null; + onfinish = null; + if (onclose === null) { + callback(err); + } else { + onclose = callback; + destroyer(w, err); + destroyer(r, err); + } + }; + return d + } + return duplexify; +} + +var duplex; +var hasRequiredDuplex; + +function requireDuplex () { + if (hasRequiredDuplex) return duplex; + hasRequiredDuplex = 1; + + const { + ObjectDefineProperties, + ObjectGetOwnPropertyDescriptor, + ObjectKeys, + ObjectSetPrototypeOf + } = requirePrimordials(); + duplex = Duplex; + const Readable = requireReadable(); + const Writable = requireWritable(); + ObjectSetPrototypeOf(Duplex.prototype, Readable.prototype); + ObjectSetPrototypeOf(Duplex, Readable); + { + const keys = ObjectKeys(Writable.prototype); + // Allow the keys array to be GC'ed. + for (let i = 0; i < keys.length; i++) { + const method = keys[i]; + if (!Duplex.prototype[method]) Duplex.prototype[method] = Writable.prototype[method]; + } + } + function Duplex(options) { + if (!(this instanceof Duplex)) return new Duplex(options) + Readable.call(this, options); + Writable.call(this, options); + if (options) { + this.allowHalfOpen = options.allowHalfOpen !== false; + if (options.readable === false) { + this._readableState.readable = false; + this._readableState.ended = true; + this._readableState.endEmitted = true; + } + if (options.writable === false) { + this._writableState.writable = false; + this._writableState.ending = true; + this._writableState.ended = true; + this._writableState.finished = true; + } + } else { + this.allowHalfOpen = true; + } + } + ObjectDefineProperties(Duplex.prototype, { + writable: { + __proto__: null, + ...ObjectGetOwnPropertyDescriptor(Writable.prototype, 'writable') + }, + writableHighWaterMark: { + __proto__: null, + ...ObjectGetOwnPropertyDescriptor(Writable.prototype, 'writableHighWaterMark') + }, + writableObjectMode: { + __proto__: null, + ...ObjectGetOwnPropertyDescriptor(Writable.prototype, 'writableObjectMode') + }, + writableBuffer: { + __proto__: null, + ...ObjectGetOwnPropertyDescriptor(Writable.prototype, 'writableBuffer') + }, + writableLength: { + __proto__: null, + ...ObjectGetOwnPropertyDescriptor(Writable.prototype, 'writableLength') + }, + writableFinished: { + __proto__: null, + ...ObjectGetOwnPropertyDescriptor(Writable.prototype, 'writableFinished') + }, + writableCorked: { + __proto__: null, + ...ObjectGetOwnPropertyDescriptor(Writable.prototype, 'writableCorked') + }, + writableEnded: { + __proto__: null, + ...ObjectGetOwnPropertyDescriptor(Writable.prototype, 'writableEnded') + }, + writableNeedDrain: { + __proto__: null, + ...ObjectGetOwnPropertyDescriptor(Writable.prototype, 'writableNeedDrain') + }, + destroyed: { + __proto__: null, + get() { + if (this._readableState === undefined || this._writableState === undefined) { + return false + } + return this._readableState.destroyed && this._writableState.destroyed + }, + set(value) { + // Backward compatibility, the user is explicitly + // managing destroyed. + if (this._readableState && this._writableState) { + this._readableState.destroyed = value; + this._writableState.destroyed = value; + } + } + } + }); + let webStreamsAdapters; + + // Lazy to avoid circular references + function lazyWebStreams() { + if (webStreamsAdapters === undefined) webStreamsAdapters = {}; + return webStreamsAdapters + } + Duplex.fromWeb = function (pair, options) { + return lazyWebStreams().newStreamDuplexFromReadableWritablePair(pair, options) + }; + Duplex.toWeb = function (duplex) { + return lazyWebStreams().newReadableWritablePairFromDuplex(duplex) + }; + let duplexify; + Duplex.from = function (body) { + if (!duplexify) { + duplexify = requireDuplexify(); + } + return duplexify(body, 'body') + }; + return duplex; +} + +var transform; +var hasRequiredTransform; + +function requireTransform () { + if (hasRequiredTransform) return transform; + hasRequiredTransform = 1; + + const { ObjectSetPrototypeOf, Symbol } = requirePrimordials(); + transform = Transform; + const { ERR_METHOD_NOT_IMPLEMENTED } = requireErrors().codes; + const Duplex = requireDuplex(); + const { getHighWaterMark } = requireState(); + ObjectSetPrototypeOf(Transform.prototype, Duplex.prototype); + ObjectSetPrototypeOf(Transform, Duplex); + const kCallback = Symbol('kCallback'); + function Transform(options) { + if (!(this instanceof Transform)) return new Transform(options) + + // TODO (ronag): This should preferably always be + // applied but would be semver-major. Or even better; + // make Transform a Readable with the Writable interface. + const readableHighWaterMark = options ? getHighWaterMark(this, options, 'readableHighWaterMark', true) : null; + if (readableHighWaterMark === 0) { + // A Duplex will buffer both on the writable and readable side while + // a Transform just wants to buffer hwm number of elements. To avoid + // buffering twice we disable buffering on the writable side. + options = { + ...options, + highWaterMark: null, + readableHighWaterMark, + // TODO (ronag): 0 is not optimal since we have + // a "bug" where we check needDrain before calling _write and not after. + // Refs: https://github.com/nodejs/node/pull/32887 + // Refs: https://github.com/nodejs/node/pull/35941 + writableHighWaterMark: options.writableHighWaterMark || 0 + }; + } + Duplex.call(this, options); + + // We have implemented the _read method, and done the other things + // that Readable wants before the first _read call, so unset the + // sync guard flag. + this._readableState.sync = false; + this[kCallback] = null; + if (options) { + if (typeof options.transform === 'function') this._transform = options.transform; + if (typeof options.flush === 'function') this._flush = options.flush; + } + + // When the writable side finishes, then flush out anything remaining. + // Backwards compat. Some Transform streams incorrectly implement _final + // instead of or in addition to _flush. By using 'prefinish' instead of + // implementing _final we continue supporting this unfortunate use case. + this.on('prefinish', prefinish); + } + function final(cb) { + if (typeof this._flush === 'function' && !this.destroyed) { + this._flush((er, data) => { + if (er) { + if (cb) { + cb(er); + } else { + this.destroy(er); + } + return + } + if (data != null) { + this.push(data); + } + this.push(null); + if (cb) { + cb(); + } + }); + } else { + this.push(null); + if (cb) { + cb(); + } + } + } + function prefinish() { + if (this._final !== final) { + final.call(this); + } + } + Transform.prototype._final = final; + Transform.prototype._transform = function (chunk, encoding, callback) { + throw new ERR_METHOD_NOT_IMPLEMENTED('_transform()') + }; + Transform.prototype._write = function (chunk, encoding, callback) { + const rState = this._readableState; + const wState = this._writableState; + const length = rState.length; + this._transform(chunk, encoding, (err, val) => { + if (err) { + callback(err); + return + } + if (val != null) { + this.push(val); + } + if ( + wState.ended || + // Backwards compat. + length === rState.length || + // Backwards compat. + rState.length < rState.highWaterMark + ) { + callback(); + } else { + this[kCallback] = callback; + } + }); + }; + Transform.prototype._read = function () { + if (this[kCallback]) { + const callback = this[kCallback]; + this[kCallback] = null; + callback(); + } + }; + return transform; +} + +var passthrough; +var hasRequiredPassthrough; + +function requirePassthrough () { + if (hasRequiredPassthrough) return passthrough; + hasRequiredPassthrough = 1; + + const { ObjectSetPrototypeOf } = requirePrimordials(); + passthrough = PassThrough; + const Transform = requireTransform(); + ObjectSetPrototypeOf(PassThrough.prototype, Transform.prototype); + ObjectSetPrototypeOf(PassThrough, Transform); + function PassThrough(options) { + if (!(this instanceof PassThrough)) return new PassThrough(options) + Transform.call(this, options); + } + PassThrough.prototype._transform = function (chunk, encoding, cb) { + cb(null, chunk); + }; + return passthrough; +} + +/* replacement start */ + +var pipeline_1; +var hasRequiredPipeline; + +function requirePipeline () { + if (hasRequiredPipeline) return pipeline_1; + hasRequiredPipeline = 1; + const process = requireBrowser$2() + + /* replacement end */ + // Ported from https://github.com/mafintosh/pump with + // permission from the author, Mathias Buus (@mafintosh). + + ; const { ArrayIsArray, Promise, SymbolAsyncIterator, SymbolDispose } = requirePrimordials(); + const eos = requireEndOfStream(); + const { once } = requireUtil$2(); + const destroyImpl = requireDestroy(); + const Duplex = requireDuplex(); + const { + aggregateTwoErrors, + codes: { + ERR_INVALID_ARG_TYPE, + ERR_INVALID_RETURN_VALUE, + ERR_MISSING_ARGS, + ERR_STREAM_DESTROYED, + ERR_STREAM_PREMATURE_CLOSE + }, + AbortError + } = requireErrors(); + const { validateFunction, validateAbortSignal } = requireValidators(); + const { + isIterable, + isReadable, + isReadableNodeStream, + isNodeStream, + isTransformStream, + isWebStream, + isReadableStream, + isReadableFinished + } = requireUtils(); + const AbortController = globalThis.AbortController || requireBrowser$1().AbortController; + let PassThrough; + let Readable; + let addAbortListener; + function destroyer(stream, reading, writing) { + let finished = false; + stream.on('close', () => { + finished = true; + }); + const cleanup = eos( + stream, + { + readable: reading, + writable: writing + }, + (err) => { + finished = !err; + } + ); + return { + destroy: (err) => { + if (finished) return + finished = true; + destroyImpl.destroyer(stream, err || new ERR_STREAM_DESTROYED('pipe')); + }, + cleanup + } + } + function popCallback(streams) { + // Streams should never be an empty array. It should always contain at least + // a single stream. Therefore optimize for the average case instead of + // checking for length === 0 as well. + validateFunction(streams[streams.length - 1], 'streams[stream.length - 1]'); + return streams.pop() + } + function makeAsyncIterable(val) { + if (isIterable(val)) { + return val + } else if (isReadableNodeStream(val)) { + // Legacy streams are not Iterable. + return fromReadable(val) + } + throw new ERR_INVALID_ARG_TYPE('val', ['Readable', 'Iterable', 'AsyncIterable'], val) + } + async function* fromReadable(val) { + if (!Readable) { + Readable = requireReadable(); + } + yield* Readable.prototype[SymbolAsyncIterator].call(val); + } + async function pumpToNode(iterable, writable, finish, { end }) { + let error; + let onresolve = null; + const resume = (err) => { + if (err) { + error = err; + } + if (onresolve) { + const callback = onresolve; + onresolve = null; + callback(); + } + }; + const wait = () => + new Promise((resolve, reject) => { + if (error) { + reject(error); + } else { + onresolve = () => { + if (error) { + reject(error); + } else { + resolve(); + } + }; + } + }); + writable.on('drain', resume); + const cleanup = eos( + writable, + { + readable: false + }, + resume + ); + try { + if (writable.writableNeedDrain) { + await wait(); + } + for await (const chunk of iterable) { + if (!writable.write(chunk)) { + await wait(); + } + } + if (end) { + writable.end(); + await wait(); + } + finish(); + } catch (err) { + finish(error !== err ? aggregateTwoErrors(error, err) : err); + } finally { + cleanup(); + writable.off('drain', resume); + } + } + async function pumpToWeb(readable, writable, finish, { end }) { + if (isTransformStream(writable)) { + writable = writable.writable; + } + // https://streams.spec.whatwg.org/#example-manual-write-with-backpressure + const writer = writable.getWriter(); + try { + for await (const chunk of readable) { + await writer.ready; + writer.write(chunk).catch(() => {}); + } + await writer.ready; + if (end) { + await writer.close(); + } + finish(); + } catch (err) { + try { + await writer.abort(err); + finish(err); + } catch (err) { + finish(err); + } + } + } + function pipeline(...streams) { + return pipelineImpl(streams, once(popCallback(streams))) + } + function pipelineImpl(streams, callback, opts) { + if (streams.length === 1 && ArrayIsArray(streams[0])) { + streams = streams[0]; + } + if (streams.length < 2) { + throw new ERR_MISSING_ARGS('streams') + } + const ac = new AbortController(); + const signal = ac.signal; + const outerSignal = opts === null || opts === undefined ? undefined : opts.signal; + + // Need to cleanup event listeners if last stream is readable + // https://github.com/nodejs/node/issues/35452 + const lastStreamCleanup = []; + validateAbortSignal(outerSignal, 'options.signal'); + function abort() { + finishImpl(new AbortError()); + } + addAbortListener = addAbortListener || requireUtil$2().addAbortListener; + let disposable; + if (outerSignal) { + disposable = addAbortListener(outerSignal, abort); + } + let error; + let value; + const destroys = []; + let finishCount = 0; + function finish(err) { + finishImpl(err, --finishCount === 0); + } + function finishImpl(err, final) { + var _disposable; + if (err && (!error || error.code === 'ERR_STREAM_PREMATURE_CLOSE')) { + error = err; + } + if (!error && !final) { + return + } + while (destroys.length) { + destroys.shift()(error); + } +(_disposable = disposable) === null || _disposable === undefined ? undefined : _disposable[SymbolDispose](); + ac.abort(); + if (final) { + if (!error) { + lastStreamCleanup.forEach((fn) => fn()); + } + process.nextTick(callback, error, value); + } + } + let ret; + for (let i = 0; i < streams.length; i++) { + const stream = streams[i]; + const reading = i < streams.length - 1; + const writing = i > 0; + const end = reading || (opts === null || opts === undefined ? undefined : opts.end) !== false; + const isLastStream = i === streams.length - 1; + if (isNodeStream(stream)) { + if (end) { + const { destroy, cleanup } = destroyer(stream, reading, writing); + destroys.push(destroy); + if (isReadable(stream) && isLastStream) { + lastStreamCleanup.push(cleanup); + } + } + + // Catch stream errors that occur after pipe/pump has completed. + function onError(err) { + if (err && err.name !== 'AbortError' && err.code !== 'ERR_STREAM_PREMATURE_CLOSE') { + finish(err); + } + } + stream.on('error', onError); + if (isReadable(stream) && isLastStream) { + lastStreamCleanup.push(() => { + stream.removeListener('error', onError); + }); + } + } + if (i === 0) { + if (typeof stream === 'function') { + ret = stream({ + signal + }); + if (!isIterable(ret)) { + throw new ERR_INVALID_RETURN_VALUE('Iterable, AsyncIterable or Stream', 'source', ret) + } + } else if (isIterable(stream) || isReadableNodeStream(stream) || isTransformStream(stream)) { + ret = stream; + } else { + ret = Duplex.from(stream); + } + } else if (typeof stream === 'function') { + if (isTransformStream(ret)) { + var _ret; + ret = makeAsyncIterable((_ret = ret) === null || _ret === undefined ? undefined : _ret.readable); + } else { + ret = makeAsyncIterable(ret); + } + ret = stream(ret, { + signal + }); + if (reading) { + if (!isIterable(ret, true)) { + throw new ERR_INVALID_RETURN_VALUE('AsyncIterable', `transform[${i - 1}]`, ret) + } + } else { + var _ret2; + if (!PassThrough) { + PassThrough = requirePassthrough(); + } + + // If the last argument to pipeline is not a stream + // we must create a proxy stream so that pipeline(...) + // always returns a stream which can be further + // composed through `.pipe(stream)`. + + const pt = new PassThrough({ + objectMode: true + }); + + // Handle Promises/A+ spec, `then` could be a getter that throws on + // second use. + const then = (_ret2 = ret) === null || _ret2 === undefined ? undefined : _ret2.then; + if (typeof then === 'function') { + finishCount++; + then.call( + ret, + (val) => { + value = val; + if (val != null) { + pt.write(val); + } + if (end) { + pt.end(); + } + process.nextTick(finish); + }, + (err) => { + pt.destroy(err); + process.nextTick(finish, err); + } + ); + } else if (isIterable(ret, true)) { + finishCount++; + pumpToNode(ret, pt, finish, { + end + }); + } else if (isReadableStream(ret) || isTransformStream(ret)) { + const toRead = ret.readable || ret; + finishCount++; + pumpToNode(toRead, pt, finish, { + end + }); + } else { + throw new ERR_INVALID_RETURN_VALUE('AsyncIterable or Promise', 'destination', ret) + } + ret = pt; + const { destroy, cleanup } = destroyer(ret, false, true); + destroys.push(destroy); + if (isLastStream) { + lastStreamCleanup.push(cleanup); + } + } + } else if (isNodeStream(stream)) { + if (isReadableNodeStream(ret)) { + finishCount += 2; + const cleanup = pipe(ret, stream, finish, { + end + }); + if (isReadable(stream) && isLastStream) { + lastStreamCleanup.push(cleanup); + } + } else if (isTransformStream(ret) || isReadableStream(ret)) { + const toRead = ret.readable || ret; + finishCount++; + pumpToNode(toRead, stream, finish, { + end + }); + } else if (isIterable(ret)) { + finishCount++; + pumpToNode(ret, stream, finish, { + end + }); + } else { + throw new ERR_INVALID_ARG_TYPE( + 'val', + ['Readable', 'Iterable', 'AsyncIterable', 'ReadableStream', 'TransformStream'], + ret + ) + } + ret = stream; + } else if (isWebStream(stream)) { + if (isReadableNodeStream(ret)) { + finishCount++; + pumpToWeb(makeAsyncIterable(ret), stream, finish, { + end + }); + } else if (isReadableStream(ret) || isIterable(ret)) { + finishCount++; + pumpToWeb(ret, stream, finish, { + end + }); + } else if (isTransformStream(ret)) { + finishCount++; + pumpToWeb(ret.readable, stream, finish, { + end + }); + } else { + throw new ERR_INVALID_ARG_TYPE( + 'val', + ['Readable', 'Iterable', 'AsyncIterable', 'ReadableStream', 'TransformStream'], + ret + ) + } + ret = stream; + } else { + ret = Duplex.from(stream); + } + } + if ( + (signal !== null && signal !== undefined && signal.aborted) || + (outerSignal !== null && outerSignal !== undefined && outerSignal.aborted) + ) { + process.nextTick(abort); + } + return ret + } + function pipe(src, dst, finish, { end }) { + let ended = false; + dst.on('close', () => { + if (!ended) { + // Finish if the destination closes before the source has completed. + finish(new ERR_STREAM_PREMATURE_CLOSE()); + } + }); + src.pipe(dst, { + end: false + }); // If end is true we already will have a listener to end dst. + + if (end) { + // Compat. Before node v10.12.0 stdio used to throw an error so + // pipe() did/does not end() stdio destinations. + // Now they allow it but "secretly" don't close the underlying fd. + + function endFn() { + ended = true; + dst.end(); + } + if (isReadableFinished(src)) { + // End the destination if the source has already ended. + process.nextTick(endFn); + } else { + src.once('end', endFn); + } + } else { + finish(); + } + eos( + src, + { + readable: true, + writable: false + }, + (err) => { + const rState = src._readableState; + if ( + err && + err.code === 'ERR_STREAM_PREMATURE_CLOSE' && + rState && + rState.ended && + !rState.errored && + !rState.errorEmitted + ) { + // Some readable streams will emit 'close' before 'end'. However, since + // this is on the readable side 'end' should still be emitted if the + // stream has been ended and no error emitted. This should be allowed in + // favor of backwards compatibility. Since the stream is piped to a + // destination this should not result in any observable difference. + // We don't need to check if this is a writable premature close since + // eos will only fail with premature close on the reading side for + // duplex streams. + src.once('end', finish).once('error', finish); + } else { + finish(err); + } + } + ); + return eos( + dst, + { + readable: false, + writable: true + }, + finish + ) + } + pipeline_1 = { + pipelineImpl, + pipeline + }; + return pipeline_1; +} + +var compose; +var hasRequiredCompose; + +function requireCompose () { + if (hasRequiredCompose) return compose; + hasRequiredCompose = 1; + + const { pipeline } = requirePipeline(); + const Duplex = requireDuplex(); + const { destroyer } = requireDestroy(); + const { + isNodeStream, + isReadable, + isWritable, + isWebStream, + isTransformStream, + isWritableStream, + isReadableStream + } = requireUtils(); + const { + AbortError, + codes: { ERR_INVALID_ARG_VALUE, ERR_MISSING_ARGS } + } = requireErrors(); + const eos = requireEndOfStream(); + compose = function compose(...streams) { + if (streams.length === 0) { + throw new ERR_MISSING_ARGS('streams') + } + if (streams.length === 1) { + return Duplex.from(streams[0]) + } + const orgStreams = [...streams]; + if (typeof streams[0] === 'function') { + streams[0] = Duplex.from(streams[0]); + } + if (typeof streams[streams.length - 1] === 'function') { + const idx = streams.length - 1; + streams[idx] = Duplex.from(streams[idx]); + } + for (let n = 0; n < streams.length; ++n) { + if (!isNodeStream(streams[n]) && !isWebStream(streams[n])) { + // TODO(ronag): Add checks for non streams. + continue + } + if ( + n < streams.length - 1 && + !(isReadable(streams[n]) || isReadableStream(streams[n]) || isTransformStream(streams[n])) + ) { + throw new ERR_INVALID_ARG_VALUE(`streams[${n}]`, orgStreams[n], 'must be readable') + } + if (n > 0 && !(isWritable(streams[n]) || isWritableStream(streams[n]) || isTransformStream(streams[n]))) { + throw new ERR_INVALID_ARG_VALUE(`streams[${n}]`, orgStreams[n], 'must be writable') + } + } + let ondrain; + let onfinish; + let onreadable; + let onclose; + let d; + function onfinished(err) { + const cb = onclose; + onclose = null; + if (cb) { + cb(err); + } else if (err) { + d.destroy(err); + } else if (!readable && !writable) { + d.destroy(); + } + } + const head = streams[0]; + const tail = pipeline(streams, onfinished); + const writable = !!(isWritable(head) || isWritableStream(head) || isTransformStream(head)); + const readable = !!(isReadable(tail) || isReadableStream(tail) || isTransformStream(tail)); + + // TODO(ronag): Avoid double buffering. + // Implement Writable/Readable/Duplex traits. + // See, https://github.com/nodejs/node/pull/33515. + d = new Duplex({ + // TODO (ronag): highWaterMark? + writableObjectMode: !!(head !== null && head !== undefined && head.writableObjectMode), + readableObjectMode: !!(tail !== null && tail !== undefined && tail.readableObjectMode), + writable, + readable + }); + if (writable) { + if (isNodeStream(head)) { + d._write = function (chunk, encoding, callback) { + if (head.write(chunk, encoding)) { + callback(); + } else { + ondrain = callback; + } + }; + d._final = function (callback) { + head.end(); + onfinish = callback; + }; + head.on('drain', function () { + if (ondrain) { + const cb = ondrain; + ondrain = null; + cb(); + } + }); + } else if (isWebStream(head)) { + const writable = isTransformStream(head) ? head.writable : head; + const writer = writable.getWriter(); + d._write = async function (chunk, encoding, callback) { + try { + await writer.ready; + writer.write(chunk).catch(() => {}); + callback(); + } catch (err) { + callback(err); + } + }; + d._final = async function (callback) { + try { + await writer.ready; + writer.close().catch(() => {}); + onfinish = callback; + } catch (err) { + callback(err); + } + }; + } + const toRead = isTransformStream(tail) ? tail.readable : tail; + eos(toRead, () => { + if (onfinish) { + const cb = onfinish; + onfinish = null; + cb(); + } + }); + } + if (readable) { + if (isNodeStream(tail)) { + tail.on('readable', function () { + if (onreadable) { + const cb = onreadable; + onreadable = null; + cb(); + } + }); + tail.on('end', function () { + d.push(null); + }); + d._read = function () { + while (true) { + const buf = tail.read(); + if (buf === null) { + onreadable = d._read; + return + } + if (!d.push(buf)) { + return + } + } + }; + } else if (isWebStream(tail)) { + const readable = isTransformStream(tail) ? tail.readable : tail; + const reader = readable.getReader(); + d._read = async function () { + while (true) { + try { + const { value, done } = await reader.read(); + if (!d.push(value)) { + return + } + if (done) { + d.push(null); + return + } + } catch { + return + } + } + }; + } + } + d._destroy = function (err, callback) { + if (!err && onclose !== null) { + err = new AbortError(); + } + onreadable = null; + ondrain = null; + onfinish = null; + if (onclose === null) { + callback(err); + } else { + onclose = callback; + if (isNodeStream(tail)) { + destroyer(tail, err); + } + } + }; + return d + }; + return compose; +} + +var hasRequiredOperators; + +function requireOperators () { + if (hasRequiredOperators) return operators; + hasRequiredOperators = 1; + + const AbortController = globalThis.AbortController || requireBrowser$1().AbortController; + const { + codes: { ERR_INVALID_ARG_VALUE, ERR_INVALID_ARG_TYPE, ERR_MISSING_ARGS, ERR_OUT_OF_RANGE }, + AbortError + } = requireErrors(); + const { validateAbortSignal, validateInteger, validateObject } = requireValidators(); + const kWeakHandler = requirePrimordials().Symbol('kWeak'); + const kResistStopPropagation = requirePrimordials().Symbol('kResistStopPropagation'); + const { finished } = requireEndOfStream(); + const staticCompose = requireCompose(); + const { addAbortSignalNoValidate } = requireAddAbortSignal(); + const { isWritable, isNodeStream } = requireUtils(); + const { deprecate } = requireUtil$2(); + const { + ArrayPrototypePush, + Boolean, + MathFloor, + Number, + NumberIsNaN, + Promise, + PromiseReject, + PromiseResolve, + PromisePrototypeThen, + Symbol + } = requirePrimordials(); + const kEmpty = Symbol('kEmpty'); + const kEof = Symbol('kEof'); + function compose(stream, options) { + if (options != null) { + validateObject(options, 'options'); + } + if ((options === null || options === undefined ? undefined : options.signal) != null) { + validateAbortSignal(options.signal, 'options.signal'); + } + if (isNodeStream(stream) && !isWritable(stream)) { + throw new ERR_INVALID_ARG_VALUE('stream', stream, 'must be writable') + } + const composedStream = staticCompose(this, stream); + if (options !== null && options !== undefined && options.signal) { + // Not validating as we already validated before + addAbortSignalNoValidate(options.signal, composedStream); + } + return composedStream + } + function map(fn, options) { + if (typeof fn !== 'function') { + throw new ERR_INVALID_ARG_TYPE('fn', ['Function', 'AsyncFunction'], fn) + } + if (options != null) { + validateObject(options, 'options'); + } + if ((options === null || options === undefined ? undefined : options.signal) != null) { + validateAbortSignal(options.signal, 'options.signal'); + } + let concurrency = 1; + if ((options === null || options === undefined ? undefined : options.concurrency) != null) { + concurrency = MathFloor(options.concurrency); + } + let highWaterMark = concurrency - 1; + if ((options === null || options === undefined ? undefined : options.highWaterMark) != null) { + highWaterMark = MathFloor(options.highWaterMark); + } + validateInteger(concurrency, 'options.concurrency', 1); + validateInteger(highWaterMark, 'options.highWaterMark', 0); + highWaterMark += concurrency; + return async function* map() { + const signal = requireUtil$2().AbortSignalAny( + [options === null || options === undefined ? undefined : options.signal].filter(Boolean) + ); + const stream = this; + const queue = []; + const signalOpt = { + signal + }; + let next; + let resume; + let done = false; + let cnt = 0; + function onCatch() { + done = true; + afterItemProcessed(); + } + function afterItemProcessed() { + cnt -= 1; + maybeResume(); + } + function maybeResume() { + if (resume && !done && cnt < concurrency && queue.length < highWaterMark) { + resume(); + resume = null; + } + } + async function pump() { + try { + for await (let val of stream) { + if (done) { + return + } + if (signal.aborted) { + throw new AbortError() + } + try { + val = fn(val, signalOpt); + if (val === kEmpty) { + continue + } + val = PromiseResolve(val); + } catch (err) { + val = PromiseReject(err); + } + cnt += 1; + PromisePrototypeThen(val, afterItemProcessed, onCatch); + queue.push(val); + if (next) { + next(); + next = null; + } + if (!done && (queue.length >= highWaterMark || cnt >= concurrency)) { + await new Promise((resolve) => { + resume = resolve; + }); + } + } + queue.push(kEof); + } catch (err) { + const val = PromiseReject(err); + PromisePrototypeThen(val, afterItemProcessed, onCatch); + queue.push(val); + } finally { + done = true; + if (next) { + next(); + next = null; + } + } + } + pump(); + try { + while (true) { + while (queue.length > 0) { + const val = await queue[0]; + if (val === kEof) { + return + } + if (signal.aborted) { + throw new AbortError() + } + if (val !== kEmpty) { + yield val; + } + queue.shift(); + maybeResume(); + } + await new Promise((resolve) => { + next = resolve; + }); + } + } finally { + done = true; + if (resume) { + resume(); + resume = null; + } + } + }.call(this) + } + function asIndexedPairs(options = undefined) { + if (options != null) { + validateObject(options, 'options'); + } + if ((options === null || options === undefined ? undefined : options.signal) != null) { + validateAbortSignal(options.signal, 'options.signal'); + } + return async function* asIndexedPairs() { + let index = 0; + for await (const val of this) { + var _options$signal; + if ( + options !== null && + options !== undefined && + (_options$signal = options.signal) !== null && + _options$signal !== undefined && + _options$signal.aborted + ) { + throw new AbortError({ + cause: options.signal.reason + }) + } + yield [index++, val]; + } + }.call(this) + } + async function some(fn, options = undefined) { + for await (const unused of filter.call(this, fn, options)) { + return true + } + return false + } + async function every(fn, options = undefined) { + if (typeof fn !== 'function') { + throw new ERR_INVALID_ARG_TYPE('fn', ['Function', 'AsyncFunction'], fn) + } + // https://en.wikipedia.org/wiki/De_Morgan%27s_laws + return !(await some.call( + this, + async (...args) => { + return !(await fn(...args)) + }, + options + )) + } + async function find(fn, options) { + for await (const result of filter.call(this, fn, options)) { + return result + } + return undefined + } + async function forEach(fn, options) { + if (typeof fn !== 'function') { + throw new ERR_INVALID_ARG_TYPE('fn', ['Function', 'AsyncFunction'], fn) + } + async function forEachFn(value, options) { + await fn(value, options); + return kEmpty + } + // eslint-disable-next-line no-unused-vars + for await (const unused of map.call(this, forEachFn, options)); + } + function filter(fn, options) { + if (typeof fn !== 'function') { + throw new ERR_INVALID_ARG_TYPE('fn', ['Function', 'AsyncFunction'], fn) + } + async function filterFn(value, options) { + if (await fn(value, options)) { + return value + } + return kEmpty + } + return map.call(this, filterFn, options) + } + + // Specific to provide better error to reduce since the argument is only + // missing if the stream has no items in it - but the code is still appropriate + class ReduceAwareErrMissingArgs extends ERR_MISSING_ARGS { + constructor() { + super('reduce'); + this.message = 'Reduce of an empty stream requires an initial value'; + } + } + async function reduce(reducer, initialValue, options) { + var _options$signal2; + if (typeof reducer !== 'function') { + throw new ERR_INVALID_ARG_TYPE('reducer', ['Function', 'AsyncFunction'], reducer) + } + if (options != null) { + validateObject(options, 'options'); + } + if ((options === null || options === undefined ? undefined : options.signal) != null) { + validateAbortSignal(options.signal, 'options.signal'); + } + let hasInitialValue = arguments.length > 1; + if ( + options !== null && + options !== undefined && + (_options$signal2 = options.signal) !== null && + _options$signal2 !== undefined && + _options$signal2.aborted + ) { + const err = new AbortError(undefined, { + cause: options.signal.reason + }); + this.once('error', () => {}); // The error is already propagated + await finished(this.destroy(err)); + throw err + } + const ac = new AbortController(); + const signal = ac.signal; + if (options !== null && options !== undefined && options.signal) { + const opts = { + once: true, + [kWeakHandler]: this, + [kResistStopPropagation]: true + }; + options.signal.addEventListener('abort', () => ac.abort(), opts); + } + let gotAnyItemFromStream = false; + try { + for await (const value of this) { + var _options$signal3; + gotAnyItemFromStream = true; + if ( + options !== null && + options !== undefined && + (_options$signal3 = options.signal) !== null && + _options$signal3 !== undefined && + _options$signal3.aborted + ) { + throw new AbortError() + } + if (!hasInitialValue) { + initialValue = value; + hasInitialValue = true; + } else { + initialValue = await reducer(initialValue, value, { + signal + }); + } + } + if (!gotAnyItemFromStream && !hasInitialValue) { + throw new ReduceAwareErrMissingArgs() + } + } finally { + ac.abort(); + } + return initialValue + } + async function toArray(options) { + if (options != null) { + validateObject(options, 'options'); + } + if ((options === null || options === undefined ? undefined : options.signal) != null) { + validateAbortSignal(options.signal, 'options.signal'); + } + const result = []; + for await (const val of this) { + var _options$signal4; + if ( + options !== null && + options !== undefined && + (_options$signal4 = options.signal) !== null && + _options$signal4 !== undefined && + _options$signal4.aborted + ) { + throw new AbortError(undefined, { + cause: options.signal.reason + }) + } + ArrayPrototypePush(result, val); + } + return result + } + function flatMap(fn, options) { + const values = map.call(this, fn, options); + return async function* flatMap() { + for await (const val of values) { + yield* val; + } + }.call(this) + } + function toIntegerOrInfinity(number) { + // We coerce here to align with the spec + // https://github.com/tc39/proposal-iterator-helpers/issues/169 + number = Number(number); + if (NumberIsNaN(number)) { + return 0 + } + if (number < 0) { + throw new ERR_OUT_OF_RANGE('number', '>= 0', number) + } + return number + } + function drop(number, options = undefined) { + if (options != null) { + validateObject(options, 'options'); + } + if ((options === null || options === undefined ? undefined : options.signal) != null) { + validateAbortSignal(options.signal, 'options.signal'); + } + number = toIntegerOrInfinity(number); + return async function* drop() { + var _options$signal5; + if ( + options !== null && + options !== undefined && + (_options$signal5 = options.signal) !== null && + _options$signal5 !== undefined && + _options$signal5.aborted + ) { + throw new AbortError() + } + for await (const val of this) { + var _options$signal6; + if ( + options !== null && + options !== undefined && + (_options$signal6 = options.signal) !== null && + _options$signal6 !== undefined && + _options$signal6.aborted + ) { + throw new AbortError() + } + if (number-- <= 0) { + yield val; + } + } + }.call(this) + } + function take(number, options = undefined) { + if (options != null) { + validateObject(options, 'options'); + } + if ((options === null || options === undefined ? undefined : options.signal) != null) { + validateAbortSignal(options.signal, 'options.signal'); + } + number = toIntegerOrInfinity(number); + return async function* take() { + var _options$signal7; + if ( + options !== null && + options !== undefined && + (_options$signal7 = options.signal) !== null && + _options$signal7 !== undefined && + _options$signal7.aborted + ) { + throw new AbortError() + } + for await (const val of this) { + var _options$signal8; + if ( + options !== null && + options !== undefined && + (_options$signal8 = options.signal) !== null && + _options$signal8 !== undefined && + _options$signal8.aborted + ) { + throw new AbortError() + } + if (number-- > 0) { + yield val; + } + + // Don't get another item from iterator in case we reached the end + if (number <= 0) { + return + } + } + }.call(this) + } + operators.streamReturningOperators = { + asIndexedPairs: deprecate(asIndexedPairs, 'readable.asIndexedPairs will be removed in a future version.'), + drop, + filter, + flatMap, + map, + take, + compose + }; + operators.promiseReturningOperators = { + every, + forEach, + reduce, + toArray, + some, + find + }; + return operators; +} + +var promises; +var hasRequiredPromises; + +function requirePromises () { + if (hasRequiredPromises) return promises; + hasRequiredPromises = 1; + + const { ArrayPrototypePop, Promise } = requirePrimordials(); + const { isIterable, isNodeStream, isWebStream } = requireUtils(); + const { pipelineImpl: pl } = requirePipeline(); + const { finished } = requireEndOfStream(); + requireStream$1(); + function pipeline(...streams) { + return new Promise((resolve, reject) => { + let signal; + let end; + const lastArg = streams[streams.length - 1]; + if ( + lastArg && + typeof lastArg === 'object' && + !isNodeStream(lastArg) && + !isIterable(lastArg) && + !isWebStream(lastArg) + ) { + const options = ArrayPrototypePop(streams); + signal = options.signal; + end = options.end; + } + pl( + streams, + (err, value) => { + if (err) { + reject(err); + } else { + resolve(value); + } + }, + { + signal, + end + } + ); + }) + } + promises = { + finished, + pipeline + }; + return promises; +} + +var hasRequiredStream$1; + +function requireStream$1 () { + if (hasRequiredStream$1) return stream.exports; + hasRequiredStream$1 = 1; + + /* replacement start */ + + const { Buffer } = require$$0$1; + + /* replacement end */ + + const { ObjectDefineProperty, ObjectKeys, ReflectApply } = requirePrimordials(); + const { + promisify: { custom: customPromisify } + } = requireUtil$2(); + const { streamReturningOperators, promiseReturningOperators } = requireOperators(); + const { + codes: { ERR_ILLEGAL_CONSTRUCTOR } + } = requireErrors(); + const compose = requireCompose(); + const { setDefaultHighWaterMark, getDefaultHighWaterMark } = requireState(); + const { pipeline } = requirePipeline(); + const { destroyer } = requireDestroy(); + const eos = requireEndOfStream(); + const promises = requirePromises(); + const utils = requireUtils(); + const Stream = (stream.exports = requireLegacy().Stream); + Stream.isDestroyed = utils.isDestroyed; + Stream.isDisturbed = utils.isDisturbed; + Stream.isErrored = utils.isErrored; + Stream.isReadable = utils.isReadable; + Stream.isWritable = utils.isWritable; + Stream.Readable = requireReadable(); + for (const key of ObjectKeys(streamReturningOperators)) { + const op = streamReturningOperators[key]; + function fn(...args) { + if (new.target) { + throw ERR_ILLEGAL_CONSTRUCTOR() + } + return Stream.Readable.from(ReflectApply(op, this, args)) + } + ObjectDefineProperty(fn, 'name', { + __proto__: null, + value: op.name + }); + ObjectDefineProperty(fn, 'length', { + __proto__: null, + value: op.length + }); + ObjectDefineProperty(Stream.Readable.prototype, key, { + __proto__: null, + value: fn, + enumerable: false, + configurable: true, + writable: true + }); + } + for (const key of ObjectKeys(promiseReturningOperators)) { + const op = promiseReturningOperators[key]; + function fn(...args) { + if (new.target) { + throw ERR_ILLEGAL_CONSTRUCTOR() + } + return ReflectApply(op, this, args) + } + ObjectDefineProperty(fn, 'name', { + __proto__: null, + value: op.name + }); + ObjectDefineProperty(fn, 'length', { + __proto__: null, + value: op.length + }); + ObjectDefineProperty(Stream.Readable.prototype, key, { + __proto__: null, + value: fn, + enumerable: false, + configurable: true, + writable: true + }); + } + Stream.Writable = requireWritable(); + Stream.Duplex = requireDuplex(); + Stream.Transform = requireTransform(); + Stream.PassThrough = requirePassthrough(); + Stream.pipeline = pipeline; + const { addAbortSignal } = requireAddAbortSignal(); + Stream.addAbortSignal = addAbortSignal; + Stream.finished = eos; + Stream.destroy = destroyer; + Stream.compose = compose; + Stream.setDefaultHighWaterMark = setDefaultHighWaterMark; + Stream.getDefaultHighWaterMark = getDefaultHighWaterMark; + ObjectDefineProperty(Stream, 'promises', { + __proto__: null, + configurable: true, + enumerable: true, + get() { + return promises + } + }); + ObjectDefineProperty(pipeline, customPromisify, { + __proto__: null, + enumerable: true, + get() { + return promises.pipeline + } + }); + ObjectDefineProperty(eos, customPromisify, { + __proto__: null, + enumerable: true, + get() { + return promises.finished + } + }); + + // Backwards-compat with node 0.4.x + Stream.Stream = Stream; + Stream._isUint8Array = function isUint8Array(value) { + return value instanceof Uint8Array + }; + Stream._uint8ArrayToBuffer = function _uint8ArrayToBuffer(chunk) { + return Buffer.from(chunk.buffer, chunk.byteOffset, chunk.byteLength) + }; + return stream.exports; +} + +var hasRequiredBrowser; + +function requireBrowser () { + if (hasRequiredBrowser) return browser$1.exports; + hasRequiredBrowser = 1; + (function (module) { + + const CustomStream = requireStream$1(); + const promises = requirePromises(); + const originalDestroy = CustomStream.Readable.destroy; + module.exports = CustomStream.Readable; + + // Explicit export naming is needed for ESM + module.exports._uint8ArrayToBuffer = CustomStream._uint8ArrayToBuffer; + module.exports._isUint8Array = CustomStream._isUint8Array; + module.exports.isDisturbed = CustomStream.isDisturbed; + module.exports.isErrored = CustomStream.isErrored; + module.exports.isReadable = CustomStream.isReadable; + module.exports.Readable = CustomStream.Readable; + module.exports.Writable = CustomStream.Writable; + module.exports.Duplex = CustomStream.Duplex; + module.exports.Transform = CustomStream.Transform; + module.exports.PassThrough = CustomStream.PassThrough; + module.exports.addAbortSignal = CustomStream.addAbortSignal; + module.exports.finished = CustomStream.finished; + module.exports.destroy = CustomStream.destroy; + module.exports.destroy = originalDestroy; + module.exports.pipeline = CustomStream.pipeline; + module.exports.compose = CustomStream.compose; + Object.defineProperty(CustomStream, 'promises', { + configurable: true, + enumerable: true, + get() { + return promises + } + }); + module.exports.Stream = CustomStream.Stream; + + // Allow default importing + module.exports.default = module.exports; + } (browser$1)); + return browser$1.exports; +} + +var hasRequiredStream; + +function requireStream () { + if (hasRequiredStream) return stream$1; + hasRequiredStream = 1; + (function (exports) { + Object.defineProperty(exports, "__esModule", { value: true }); + exports.Writable = exports.Readable = void 0; + var node_stream_1 = requireBrowser(); + Object.defineProperty(exports, "Readable", { enumerable: true, get: function () { return node_stream_1.Readable; } }); + Object.defineProperty(exports, "Writable", { enumerable: true, get: function () { return node_stream_1.Writable; } }); + + } (stream$1)); + return stream$1; +} + +var events = {}; + +var hasRequiredEvents; + +function requireEvents () { + if (hasRequiredEvents) return events; + hasRequiredEvents = 1; + (function (exports) { + Object.defineProperty(exports, "__esModule", { value: true }); + exports.EventEmitter = void 0; + var node_events_1 = requireEvents$1(); + Object.defineProperty(exports, "EventEmitter", { enumerable: true, get: function () { return node_events_1.EventEmitter; } }); + + } (events)); + return events; +} + +var FileHandle = {}; + +var util$1 = {}; + +var hasRequiredUtil$1; + +function requireUtil$1 () { + if (hasRequiredUtil$1) return util$1; + hasRequiredUtil$1 = 1; + Object.defineProperty(util$1, "__esModule", { value: true }); + util$1.getWriteSyncArgs = util$1.getWriteArgs = util$1.bufToUint8 = void 0; + util$1.promisify = promisify; + util$1.validateCallback = validateCallback; + util$1.modeToNumber = modeToNumber; + util$1.nullCheck = nullCheck; + util$1.pathToFilename = pathToFilename; + util$1.createError = createError; + util$1.createStatError = createStatError; + util$1.genRndStr6 = genRndStr6; + util$1.flagsToNumber = flagsToNumber; + util$1.streamToBuffer = streamToBuffer; + util$1.bufferToEncoding = bufferToEncoding; + util$1.isReadableStream = isReadableStream; + const fs_node_utils_1 = requireLib$7(); + const errors = requireErrors$1(); + const buffer_1 = requireBuffer(); + const fs_core_1 = requireLib$5(); + function promisify(fs, fn, getResult = input => input) { + return (...args) => new Promise((resolve, reject) => { + fs[fn].bind(fs)(...args, (error, result) => { + if (error) + return reject(error); + return resolve(getResult(result)); + }); + }); + } + function validateCallback(callback) { + if (typeof callback !== 'function') + throw TypeError(fs_node_utils_1.ERRSTR.CB); + return callback; + } + function _modeToNumber(mode, def) { + if (typeof mode === 'number') + return mode; + if (typeof mode === 'string') + return parseInt(mode, 8); + if (def) + return modeToNumber(def); + return undefined; + } + function modeToNumber(mode, def) { + const result = _modeToNumber(mode, def); + if (typeof result !== 'number' || isNaN(result)) + throw new TypeError(fs_node_utils_1.ERRSTR.MODE_INT); + return result; + } + function nullCheck(path, callback) { + if (('' + path).indexOf('\u0000') !== -1) { + const er = new Error('Path must be a string without null bytes'); + er.code = 'ENOENT'; + if (typeof callback !== 'function') + throw er; + queueMicrotask(() => { + callback(er); + }); + return false; + } + return true; + } + function getPathFromURLPosix(url) { + if (url.hostname !== '') { + throw new errors.TypeError('ERR_INVALID_FILE_URL_HOST', process$1.platform); + } + const pathname = url.pathname; + for (let n = 0; n < pathname.length; n++) { + if (pathname[n] === '%') { + const third = pathname.codePointAt(n + 2) | 0x20; + if (pathname[n + 1] === '2' && third === 102) { + throw new errors.TypeError('ERR_INVALID_FILE_URL_PATH', 'must not include encoded / characters'); + } + } + } + return decodeURIComponent(pathname); + } + function pathToFilename(path) { + if (path instanceof Uint8Array) { + path = (0, buffer_1.bufferFrom)(path); + } + if (typeof path !== 'string' && !buffer_1.Buffer.isBuffer(path)) { + try { + if (!(path instanceof requireUrl().URL)) + throw new TypeError(fs_node_utils_1.ERRSTR.PATH_STR); + } + catch (err) { + throw new TypeError(fs_node_utils_1.ERRSTR.PATH_STR); + } + path = getPathFromURLPosix(path); + } + const pathString = String(path); + nullCheck(pathString); + // return slash(pathString); + return pathString; + } + const ENOENT = 'ENOENT'; + const EBADF = 'EBADF'; + const EINVAL = 'EINVAL'; + const EPERM = 'EPERM'; + const EPROTO = 'EPROTO'; + const EEXIST = 'EEXIST'; + const ENOTDIR = 'ENOTDIR'; + const EMFILE = 'EMFILE'; + const EACCES = 'EACCES'; + const EISDIR = 'EISDIR'; + const ENOTEMPTY = 'ENOTEMPTY'; + const ENOSYS = 'ENOSYS'; + const ERR_FS_EISDIR = 'ERR_FS_EISDIR'; + const ERR_OUT_OF_RANGE = 'ERR_OUT_OF_RANGE'; + function formatError(errorCode, func = '', path = '', path2 = '') { + let pathFormatted = ''; + if (path) + pathFormatted = ` '${path}'`; + if (path2) + pathFormatted += ` -> '${path2}'`; + switch (errorCode) { + case ENOENT: + return `ENOENT: no such file or directory, ${func}${pathFormatted}`; + case EBADF: + return `EBADF: bad file descriptor, ${func}${pathFormatted}`; + case EINVAL: + return `EINVAL: invalid argument, ${func}${pathFormatted}`; + case EPERM: + return `EPERM: operation not permitted, ${func}${pathFormatted}`; + case EPROTO: + return `EPROTO: protocol error, ${func}${pathFormatted}`; + case EEXIST: + return `EEXIST: file already exists, ${func}${pathFormatted}`; + case ENOTDIR: + return `ENOTDIR: not a directory, ${func}${pathFormatted}`; + case EISDIR: + return `EISDIR: illegal operation on a directory, ${func}${pathFormatted}`; + case EACCES: + return `EACCES: permission denied, ${func}${pathFormatted}`; + case ENOTEMPTY: + return `ENOTEMPTY: directory not empty, ${func}${pathFormatted}`; + case EMFILE: + return `EMFILE: too many open files, ${func}${pathFormatted}`; + case ENOSYS: + return `ENOSYS: function not implemented, ${func}${pathFormatted}`; + case ERR_FS_EISDIR: + return `[ERR_FS_EISDIR]: Path is a directory: ${func} returned EISDIR (is a directory) ${path}`; + case ERR_OUT_OF_RANGE: + return `[ERR_OUT_OF_RANGE]: value out of range, ${func}${pathFormatted}`; + default: + return `${errorCode}: error occurred, ${func}${pathFormatted}`; + } + } + function createError(errorCode, func = '', path = '', path2 = '', Constructor = Error) { + const error = new Constructor(formatError(errorCode, func, path, path2)); + error.code = errorCode; + if (path) { + error.path = path; + } + return error; + } + function createStatError(errorCode, func = '', path = '', path2 = '') { + return { + code: errorCode, + message: formatError(errorCode, func, path, path2), + path, + toError() { + const error = new Error(this.message); + error.code = this.code; + if (this.path) { + error.path = this.path; + } + return error; + }, + }; + } + function genRndStr6() { + return Math.random().toString(36).slice(2, 8).padEnd(6, '0'); + } + function flagsToNumber(flags) { + if (typeof flags === 'number') + return flags; + if (typeof flags === 'string') { + const flagsNum = fs_node_utils_1.FLAGS[flags]; + if (typeof flagsNum !== 'undefined') + return flagsNum; + } + // throw new TypeError(formatError(ERRSTR_FLAG(flags))); + throw new errors.TypeError('ERR_INVALID_OPT_VALUE', 'flags', flags); + } + function streamToBuffer(stream) { + const chunks = []; + return new Promise((resolve, reject) => { + stream.on('data', chunk => chunks.push(chunk)); + stream.on('end', () => resolve(buffer_1.Buffer.concat(chunks))); + stream.on('error', reject); + }); + } + const bufToUint8 = (buf) => new Uint8Array(buf.buffer, buf.byteOffset, buf.byteLength); + util$1.bufToUint8 = bufToUint8; + const getWriteArgs = (fd, a, b, c, d, e) => { + (0, fs_core_1.validateFd)(fd); + let offset = 0; + let length; + let position = null; + let encoding; + let callback; + const tipa = typeof a; + const tipb = typeof b; + const tipc = typeof c; + const tipd = typeof d; + if (tipa !== 'string') { + if (tipb === 'function') { + callback = b; + } + else if (tipc === 'function') { + offset = b | 0; + callback = c; + } + else if (tipd === 'function') { + offset = b | 0; + length = c; + callback = d; + } + else { + offset = b | 0; + length = c; + position = d; + callback = e; + } + } + else { + if (tipb === 'function') { + callback = b; + } + else if (tipc === 'function') { + position = b; + callback = c; + } + else if (tipd === 'function') { + position = b; + encoding = c; + callback = d; + } + } + const buf = (0, fs_core_1.dataToBuffer)(a, encoding); + if (tipa !== 'string') { + if (typeof length === 'undefined') + length = buf.length; + } + else { + offset = 0; + length = buf.length; + } + const cb = validateCallback(callback); + return [fd, tipa === 'string', buf, offset, length, position, cb]; + }; + util$1.getWriteArgs = getWriteArgs; + const getWriteSyncArgs = (fd, a, b, c, d) => { + (0, fs_core_1.validateFd)(fd); + let encoding; + let offset; + let length; + let position; + const isBuffer = typeof a !== 'string'; + if (isBuffer) { + offset = (b || 0) | 0; + length = c; + position = d; + } + else { + position = b; + encoding = c; + } + const buf = (0, fs_core_1.dataToBuffer)(a, encoding); + if (isBuffer) { + if (typeof length === 'undefined') { + length = buf.length; + } + } + else { + offset = 0; + length = buf.length; + } + return [fd, buf, offset || 0, length, position]; + }; + util$1.getWriteSyncArgs = getWriteSyncArgs; + function bufferToEncoding(buffer, encoding) { + if (!encoding || encoding === 'buffer') + return buffer; + else + return buffer.toString(encoding); + } + function isReadableStream(stream) { + return (stream !== null && + typeof stream === 'object' && + typeof stream.pipe === 'function' && + typeof stream.on === 'function' && + stream.readable === true); + } + + return util$1; +} + +var hasRequiredFileHandle; + +function requireFileHandle () { + if (hasRequiredFileHandle) return FileHandle; + hasRequiredFileHandle = 1; + Object.defineProperty(FileHandle, "__esModule", { value: true }); + FileHandle.FileHandle = void 0; + const util_1 = requireUtil$1(); + const events_1 = requireEvents(); + let FileHandle$1 = class FileHandle extends events_1.EventEmitter { + constructor(fs, fd) { + super(); + this.refs = 1; + this.closePromise = null; + this.position = 0; + this.readableWebStreamLocked = false; + this.fs = fs; + this.fd = fd; + } + getAsyncId() { + // Return a unique async ID for this file handle + // In a real implementation, this would be provided by the underlying system + return this.fd; + } + appendFile(data, options) { + return (0, util_1.promisify)(this.fs, 'appendFile')(this.fd, data, options); + } + chmod(mode) { + return (0, util_1.promisify)(this.fs, 'fchmod')(this.fd, mode); + } + chown(uid, gid) { + return (0, util_1.promisify)(this.fs, 'fchown')(this.fd, uid, gid); + } + close() { + if (this.fd === -1) { + return Promise.resolve(); + } + if (this.closePromise) { + return this.closePromise; + } + this.refs--; + if (this.refs === 0) { + const currentFd = this.fd; + this.fd = -1; + this.closePromise = (0, util_1.promisify)(this.fs, 'close')(currentFd).finally(() => { + this.closePromise = null; + }); + } + else { + this.closePromise = new Promise((resolve, reject) => { + this.closeResolve = resolve; + this.closeReject = reject; + }).finally(() => { + this.closePromise = null; + this.closeReject = undefined; + this.closeResolve = undefined; + }); + } + this.emit('close'); + return this.closePromise; + } + datasync() { + return (0, util_1.promisify)(this.fs, 'fdatasync')(this.fd); + } + createReadStream(options) { + return this.fs.createReadStream('', { ...options, fd: this }); + } + createWriteStream(options) { + return this.fs.createWriteStream('', { ...options, fd: this }); + } + readableWebStream(options = {}) { + const { type = 'bytes', autoClose = false } = options; + let position = 0; + if (this.fd === -1) { + throw new Error('The FileHandle is closed'); + } + if (this.closePromise) { + throw new Error('The FileHandle is closing'); + } + if (this.readableWebStreamLocked) { + throw new Error('An error will be thrown if this method is called more than once or is called after the FileHandle is closed or closing.'); + } + this.readableWebStreamLocked = true; + this.ref(); + const unlockAndCleanup = () => { + this.readableWebStreamLocked = false; + this.unref(); + if (autoClose) { + this.close().catch(() => { + // Ignore close errors in cleanup + }); + } + }; + return new ReadableStream({ + type: type === 'bytes' ? 'bytes' : undefined, + autoAllocateChunkSize: 16384, + pull: async (controller) => { + try { + const view = controller.byobRequest?.view; + if (!view) { + // Fallback for when BYOB is not available + const buffer = new Uint8Array(16384); + const result = await this.read(buffer, 0, buffer.length, position); + if (result.bytesRead === 0) { + controller.close(); + unlockAndCleanup(); + return; + } + position += result.bytesRead; + controller.enqueue(buffer.slice(0, result.bytesRead)); + return; + } + const result = await this.read(view, view.byteOffset, view.byteLength, position); + if (result.bytesRead === 0) { + controller.close(); + unlockAndCleanup(); + return; + } + position += result.bytesRead; + controller.byobRequest.respond(result.bytesRead); + } + catch (error) { + controller.error(error); + unlockAndCleanup(); + } + }, + cancel: async () => { + unlockAndCleanup(); + }, + }); + } + async read(buffer, offset, length, position) { + const readPosition = position !== null && position !== undefined ? position : this.position; + const result = await (0, util_1.promisify)(this.fs, 'read', bytesRead => ({ bytesRead, buffer }))(this.fd, buffer, offset, length, readPosition); + // Update internal position only if position was null/undefined + if (position === null || position === undefined) { + this.position += result.bytesRead; + } + return result; + } + readv(buffers, position) { + return (0, util_1.promisify)(this.fs, 'readv', bytesRead => ({ bytesRead, buffers }))(this.fd, buffers, position); + } + readFile(options) { + return (0, util_1.promisify)(this.fs, 'readFile')(this.fd, options); + } + stat(options) { + return (0, util_1.promisify)(this.fs, 'fstat')(this.fd, options); + } + sync() { + return (0, util_1.promisify)(this.fs, 'fsync')(this.fd); + } + truncate(len) { + return (0, util_1.promisify)(this.fs, 'ftruncate')(this.fd, len); + } + utimes(atime, mtime) { + return (0, util_1.promisify)(this.fs, 'futimes')(this.fd, atime, mtime); + } + async write(buffer, offset, length, position) { + const useInternalPosition = typeof position !== 'number'; + const writePosition = useInternalPosition ? this.position : position; + const result = await (0, util_1.promisify)(this.fs, 'write', bytesWritten => ({ bytesWritten, buffer }))(this.fd, buffer, offset, length, writePosition); + // Update internal position only if position was null/undefined + if (useInternalPosition) { + this.position += result.bytesWritten; + } + return result; + } + writev(buffers, position) { + return (0, util_1.promisify)(this.fs, 'writev', bytesWritten => ({ bytesWritten, buffers }))(this.fd, buffers, position); + } + writeFile(data, options) { + return (0, util_1.promisify)(this.fs, 'writeFile')(this.fd, data, options); + } + // Implement Symbol.asyncDispose if available (ES2023+) + async [Symbol.asyncDispose]() { + await this.close(); + } + ref() { + this.refs++; + } + unref() { + this.refs--; + if (this.refs === 0) { + this.fd = -1; + if (this.closeResolve) { + (0, util_1.promisify)(this.fs, 'close')(this.fd).then(this.closeResolve, this.closeReject); + } + } + } + }; + FileHandle.FileHandle = FileHandle$1; + + return FileHandle; +} + +var FsPromises = {}; + +var hasRequiredFsPromises; + +function requireFsPromises () { + if (hasRequiredFsPromises) return FsPromises; + hasRequiredFsPromises = 1; + Object.defineProperty(FsPromises, "__esModule", { value: true }); + FsPromises.FsPromises = void 0; + const util_1 = requireUtil$1(); + const fs_node_utils_1 = requireLib$7(); + const newAbortError = (signal) => { + const error = new Error('The operation was aborted'); + error.name = 'AbortError'; + error.code = 'ABORT_ERR'; + error.cause = signal.reason; + return error; + }; + // AsyncIterator implementation for promises.watch + class FSWatchAsyncIterator { + constructor(fs, path, options = {}) { + this.fs = fs; + this.path = path; + this.options = options; + this.eventQueue = []; + this.resolveQueue = []; + this.finished = false; + this.maxQueue = options.maxQueue || 2048; + const overflow = options.overflow || 'ignore'; + if (overflow !== 'ignore' && overflow !== 'error' && overflow !== 'throw') + throw new TypeError(`The argument 'options.overflow' must be one of: 'ignore', 'error'. Received '${overflow}'`); + // Node's docs name the value 'throw' while its implementation validates + // 'error', both are accepted here with the same semantics. + this.overflow = overflow === 'throw' ? 'error' : overflow; + const signal = options.signal; + if (signal) { + if (signal.aborted) { + this.finish(newAbortError(signal)); + return; + } + this.onAbort = () => this.finish(newAbortError(signal)); + signal.addEventListener('abort', this.onAbort); + } + this.startWatching(); + } + startWatching() { + const { signal, ...watchOptions } = this.options; + try { + this.watcher = this.fs.watch(this.path, watchOptions, (eventType, filename) => { + this.enqueueEvent({ eventType, filename }); + }); + } + catch (error) { + // If we can't start watching, finish immediately + this.finish(); + throw error; + } + } + enqueueEvent(event) { + if (this.finished) + return; + // Handle queue overflow: the incoming event is dropped, the queue keeps + // the oldest `maxQueue` events, matching Node.js. + if (this.eventQueue.length >= this.maxQueue) { + if (this.overflow === 'error') { + const error = new Error(`Watch queue overflow: more than ${this.maxQueue} events queued`); + error.code = 'ERR_FS_WATCH_QUEUE_OVERFLOW'; + this.finish(error); + } + else if (typeof process$1 !== 'undefined' && typeof process$1.emitWarning === 'function') { + process$1.emitWarning('fs.watch maxQueue exceeded'); + } + return; + } + this.eventQueue.push(event); + // If there's a waiting promise, resolve it + if (this.resolveQueue.length > 0) { + const { resolve } = this.resolveQueue.shift(); + const nextEvent = this.eventQueue.shift(); + resolve({ value: nextEvent, done: false }); + } + } + finish(error) { + if (this.finished) + return; + this.finished = true; + this.error = error; + if (error) + this.eventQueue.length = 0; + if (this.onAbort) { + this.options.signal.removeEventListener('abort', this.onAbort); + this.onAbort = undefined; + } + if (this.watcher) { + this.watcher.close(); + this.watcher = null; + } + // Resolve or reject all pending promises - a rejected error is considered + // delivered and is not thrown again from a later next() call. + const delivered = error && this.resolveQueue.length > 0; + while (this.resolveQueue.length > 0) { + const { resolve, reject } = this.resolveQueue.shift(); + if (error) { + reject(error); + } + else { + resolve({ value: undefined, done: true }); + } + } + if (delivered) + this.error = undefined; + } + async next() { + if (this.error) { + const error = this.error; + this.error = undefined; + throw error; + } + if (this.finished) { + return { value: undefined, done: true }; + } + // If we have queued events, return one + if (this.eventQueue.length > 0) { + const event = this.eventQueue.shift(); + return { value: event, done: false }; + } + // Otherwise, wait for the next event + return new Promise((resolve, reject) => { + this.resolveQueue.push({ resolve, reject }); + }); + } + async return() { + this.finish(); + return { value: undefined, done: true }; + } + async throw(error) { + this.finish(error); + throw error; + } + [Symbol.asyncIterator]() { + return this; + } + } + let FsPromises$1 = class FsPromises { + constructor(fs, FileHandle) { + this.fs = fs; + this.FileHandle = FileHandle; + this.constants = fs_node_utils_1.constants; + this.cp = (0, util_1.promisify)(this.fs, 'cp'); + this.opendir = (0, util_1.promisify)(this.fs, 'opendir'); + this.statfs = (0, util_1.promisify)(this.fs, 'statfs'); + this.lutimes = (0, util_1.promisify)(this.fs, 'lutimes'); + this.glob = (0, util_1.promisify)(this.fs, 'glob'); + this.access = (0, util_1.promisify)(this.fs, 'access'); + this.chmod = (0, util_1.promisify)(this.fs, 'chmod'); + this.chown = (0, util_1.promisify)(this.fs, 'chown'); + this.copyFile = (0, util_1.promisify)(this.fs, 'copyFile'); + this.lchmod = (0, util_1.promisify)(this.fs, 'lchmod'); + this.lchown = (0, util_1.promisify)(this.fs, 'lchown'); + this.link = (0, util_1.promisify)(this.fs, 'link'); + this.lstat = (0, util_1.promisify)(this.fs, 'lstat'); + this.mkdir = (0, util_1.promisify)(this.fs, 'mkdir'); + this.mkdtemp = (0, util_1.promisify)(this.fs, 'mkdtemp'); + this.readdir = (0, util_1.promisify)(this.fs, 'readdir'); + this.readlink = (0, util_1.promisify)(this.fs, 'readlink'); + this.realpath = (0, util_1.promisify)(this.fs, 'realpath'); + this.rename = (0, util_1.promisify)(this.fs, 'rename'); + this.rmdir = (0, util_1.promisify)(this.fs, 'rmdir'); + this.rm = (0, util_1.promisify)(this.fs, 'rm'); + this.stat = (0, util_1.promisify)(this.fs, 'stat'); + this.symlink = (0, util_1.promisify)(this.fs, 'symlink'); + this.truncate = (0, util_1.promisify)(this.fs, 'truncate'); + this.unlink = (0, util_1.promisify)(this.fs, 'unlink'); + this.utimes = (0, util_1.promisify)(this.fs, 'utimes'); + this.readFile = (id, options) => { + return (0, util_1.promisify)(this.fs, 'readFile')(id instanceof this.FileHandle ? id.fd : id, options); + }; + this.appendFile = (path, data, options) => { + return (0, util_1.promisify)(this.fs, 'appendFile')(path instanceof this.FileHandle ? path.fd : path, data, options); + }; + this.open = (path, flags = 'r', mode) => { + return (0, util_1.promisify)(this.fs, 'open', fd => new this.FileHandle(this.fs, fd))(path, flags, mode); + }; + this.writeFile = (id, data, options) => { + const dataPromise = (0, util_1.isReadableStream)(data) ? (0, util_1.streamToBuffer)(data) : Promise.resolve(data); + return dataPromise.then(data => (0, util_1.promisify)(this.fs, 'writeFile')(id instanceof this.FileHandle ? id.fd : id, data, options)); + }; + this.watch = (filename, options) => { + const watchOptions = typeof options === 'string' ? { encoding: options } : options || {}; + return new FSWatchAsyncIterator(this.fs, filename, watchOptions); + }; + } + }; + FsPromises.FsPromises = FsPromises$1; + + return FsPromises; +} + +var lib$2 = {}; + +var lib$1 = {}; + +var printTree = {}; + +var hasRequiredPrintTree; + +function requirePrintTree () { + if (hasRequiredPrintTree) return printTree; + hasRequiredPrintTree = 1; + Object.defineProperty(printTree, "__esModule", { value: true }); + printTree.printTree = void 0; + const printTree$1 = (tab = '', children) => { + let str = ''; + let last = children.length - 1; + for (; last >= 0; last--) + if (children[last]) + break; + for (let i = 0; i <= last; i++) { + const fn = children[i]; + if (!fn) + continue; + const isLast = i === last; + const child = fn(tab + (isLast ? ' ' : '│') + ' '); + const branch = child ? (isLast ? '└─' : '├─') : '│'; + str += '\n' + tab + branch + (child ? ' ' + child : ''); + } + return str; + }; + printTree.printTree = printTree$1; + return printTree; +} + +var printBinary = {}; + +var hasRequiredPrintBinary; + +function requirePrintBinary () { + if (hasRequiredPrintBinary) return printBinary; + hasRequiredPrintBinary = 1; + Object.defineProperty(printBinary, "__esModule", { value: true }); + printBinary.printBinary = void 0; + const printBinary$1 = (tab = '', children) => { + const left = children[0], right = children[1]; + let str = ''; + if (left) + str += '\n' + tab + '← ' + left(tab + ' '); + if (right) + str += '\n' + tab + '→ ' + right(tab + ' '); + return str; + }; + printBinary.printBinary = printBinary$1; + return printBinary; +} + +var printJson = {}; + +var hasRequiredPrintJson; + +function requirePrintJson () { + if (hasRequiredPrintJson) return printJson; + hasRequiredPrintJson = 1; + Object.defineProperty(printJson, "__esModule", { value: true }); + printJson.printJson = void 0; + const printJson$1 = (tab = '', json, space = 2) => (JSON.stringify(json, null, space) || 'nil').split('\n').join('\n' + tab); + printJson.printJson = printJson$1; + return printJson; +} + +var hasRequiredLib$4; + +function requireLib$4 () { + if (hasRequiredLib$4) return lib$1; + hasRequiredLib$4 = 1; + (function (exports) { + Object.defineProperty(exports, "__esModule", { value: true }); + const tslib_1 = require$$0$2; + tslib_1.__exportStar(requirePrintTree(), exports); + tslib_1.__exportStar(requirePrintBinary(), exports); + tslib_1.__exportStar(requirePrintJson(), exports); + } (lib$1)); + return lib$1; +} + +var hasRequiredLib$3; + +function requireLib$3 () { + if (hasRequiredLib$3) return lib$2; + hasRequiredLib$3 = 1; + (function (exports) { + Object.defineProperty(exports, "__esModule", { value: true }); + exports.toTreeSync = void 0; + const tree_dump_1 = requireLib$4(); + const fs_node_utils_1 = requireLib$7(); + const toTreeSync = (fs, opts = {}) => { + const separator = opts.separator || '/'; + let dir = opts.dir || separator; + if (dir[dir.length - 1] !== separator) + dir += separator; + const tab = opts.tab || ''; + const depth = opts.depth ?? 10; + const sort = opts.sort ?? true; + let subtree = ' (...)'; + if (depth > 0) { + const list = fs.readdirSync(dir, { withFileTypes: true }); + if (sort) { + list.sort((a, b) => { + if (a.isDirectory() && b.isDirectory()) { + return a.name.toString().localeCompare(b.name.toString()); + } + else if (a.isDirectory()) { + return -1; + } + else if (b.isDirectory()) { + return 1; + } + else { + return a.name.toString().localeCompare(b.name.toString()); + } + }); + } + subtree = (0, tree_dump_1.printTree)(tab, list.map(entry => tab => { + if (entry.isDirectory()) { + return (0, exports.toTreeSync)(fs, { dir: dir + entry.name, depth: depth - 1, tab }); + } + else if (entry.isSymbolicLink()) { + return '' + entry.name + ' → ' + fs.readlinkSync(dir + entry.name); + } + else { + return '' + entry.name; + } + })); + } + const base = (0, fs_node_utils_1.basename)(dir, separator) + separator; + return base + subtree; + }; + exports.toTreeSync = toTreeSync; + + } (lib$2)); + return lib$2; +} + +var lib = {}; + +var constants$1 = {}; + +var hasRequiredConstants$1; + +function requireConstants$1 () { + if (hasRequiredConstants$1) return constants$1; + hasRequiredConstants$1 = 1; + Object.defineProperty(constants$1, "__esModule", { value: true }); + + return constants$1; +} + +var sync = {}; + +var shared = {}; + +var Writer = {}; + +var Slice = {}; + +var hasRequiredSlice; + +function requireSlice () { + if (hasRequiredSlice) return Slice; + hasRequiredSlice = 1; + Object.defineProperty(Slice, "__esModule", { value: true }); + Slice.Slice = void 0; + /** + * @deprecated Use {@link Reader} instead. + */ + let Slice$1 = class Slice { + constructor(uint8, view, start, end) { + this.uint8 = uint8; + this.view = view; + this.start = start; + this.end = end; + } + subarray() { + return this.uint8.subarray(this.start, this.end); + } + }; + Slice.Slice = Slice$1; + + return Slice; +} + +var hasRequiredWriter; + +function requireWriter () { + if (hasRequiredWriter) return Writer; + hasRequiredWriter = 1; + Object.defineProperty(Writer, "__esModule", { value: true }); + Writer.Writer = void 0; + const Slice_1 = requireSlice(); + const EMPTY_UINT8 = new Uint8Array([]); + const EMPTY_VIEW = new DataView(EMPTY_UINT8.buffer); + const hasBuffer = typeof Buffer === 'function'; + const utf8Write = hasBuffer + ? Buffer.prototype.utf8Write + : null; + const from = hasBuffer ? Buffer.from : null; + const textEncoder = typeof TextEncoder !== 'undefined' ? new TextEncoder() : null; + /** + * Writer class provides an efficient way to encode binary data. It grows the + * internal memory buffer automatically as more space is required. It is useful + * in cases when it is not known in advance the size of memory needed. + */ + let Writer$1 = class Writer { + /** + * @param allocSize Number of bytes to allocate at a time when buffer ends. + */ + constructor(allocSize = 64 * 1024) { + this.allocSize = allocSize; + /** @ignore */ + this.view = EMPTY_VIEW; + /** @ignore */ + this.x0 = 0; + /** @ignore */ + this.x = 0; + this.uint8 = new Uint8Array(allocSize); + this.size = allocSize; + this.view = new DataView(this.uint8.buffer); + } + /** @ignore */ + grow(size) { + const x0 = this.x0; + const x = this.x; + const oldUint8 = this.uint8; + const newUint8 = new Uint8Array(size); + const view = new DataView(newUint8.buffer); + const activeSlice = oldUint8.subarray(x0, x); + newUint8.set(activeSlice, 0); + this.x = x - x0; + this.x0 = 0; + this.uint8 = newUint8; + this.size = size; + this.view = view; + } + /** + * Make sure the internal buffer has enough space to write the specified number + * of bytes, otherwise resize the internal buffer to accommodate for more size. + * + * @param capacity Number of bytes. + */ + ensureCapacity(capacity) { + const byteLength = this.size; + const remaining = byteLength - this.x; + if (remaining < capacity) { + const total = byteLength - this.x0; + const required = capacity - remaining; + const totalRequired = total + required; + this.grow(totalRequired <= this.allocSize ? this.allocSize : totalRequired * 2); + } + } + /** @todo Consider renaming to "skip"? */ + move(capacity) { + this.ensureCapacity(capacity); + this.x += capacity; + } + reset() { + this.x0 = this.x; + } + /** + * Allocates a new {@link ArrayBuffer}, useful when the underlying + * {@link ArrayBuffer} cannot be shared between threads. + * + * @param size Size of memory to allocate. + */ + newBuffer(size) { + const uint8 = (this.uint8 = new Uint8Array(size)); + this.size = size; + this.view = new DataView(uint8.buffer); + this.x = this.x0 = 0; + } + /** + * @returns Encoded memory buffer contents. + */ + flush() { + const result = this.uint8.subarray(this.x0, this.x); + this.x0 = this.x; + return result; + } + flushSlice() { + const slice = new Slice_1.Slice(this.uint8, this.view, this.x0, this.x); + this.x0 = this.x; + return slice; + } + u8(char) { + this.ensureCapacity(1); + this.uint8[this.x++] = char; + } + u16(word) { + this.ensureCapacity(2); + this.view.setUint16(this.x, word); + this.x += 2; + } + u32(dword) { + this.ensureCapacity(4); + this.view.setUint32(this.x, dword); + this.x += 4; + } + i32(dword) { + this.ensureCapacity(4); + this.view.setInt32(this.x, dword); + this.x += 4; + } + u64(qword) { + this.ensureCapacity(8); + this.view.setBigUint64(this.x, BigInt(qword)); + this.x += 8; + } + f64(float) { + this.ensureCapacity(8); + this.view.setFloat64(this.x, float); + this.x += 8; + } + u8u16(u8, u16) { + this.ensureCapacity(3); + let x = this.x; + this.uint8[x++] = u8; + this.uint8[x++] = u16 >>> 8; + this.uint8[x++] = u16 & 0xff; + this.x = x; + } + u8u32(u8, u32) { + this.ensureCapacity(5); + let x = this.x; + this.uint8[x++] = u8; + this.view.setUint32(x, u32); + this.x = x + 4; + } + u8u64(u8, u64) { + this.ensureCapacity(9); + let x = this.x; + this.uint8[x++] = u8; + this.view.setBigUint64(x, BigInt(u64)); + this.x = x + 8; + } + u8f32(u8, f32) { + this.ensureCapacity(5); + let x = this.x; + this.uint8[x++] = u8; + this.view.setFloat32(x, f32); + this.x = x + 4; + } + u8f64(u8, f64) { + this.ensureCapacity(9); + let x = this.x; + this.uint8[x++] = u8; + this.view.setFloat64(x, f64); + this.x = x + 8; + } + buf(buf, length) { + this.ensureCapacity(length); + const x = this.x; + this.uint8.set(buf, x); + this.x = x + length; + } + /** + * Encodes string as UTF-8. You need to call .ensureCapacity(str.length * 4) + * before calling + * + * @param str String to encode as UTF-8. + * @returns The number of bytes written + */ + utf8(str) { + const theoreticalMaxLength = str.length * 4; + if (theoreticalMaxLength < 168) + return this.utf8Native(str); + this.ensureCapacity(theoreticalMaxLength); + const maxLength = this.size - this.x; + if (utf8Write) { + const writeLength = utf8Write.call(this.uint8, str, this.x, maxLength); + this.x += writeLength; + return writeLength; + } + else if (from) { + const uint8 = this.uint8; + const offset = uint8.byteOffset + this.x; + const buf = from(uint8.buffer).subarray(offset, offset + maxLength); + const writeLength = buf.write(str, 0, maxLength, 'utf8'); + this.x += writeLength; + return writeLength; + } + else if (theoreticalMaxLength > 1024 && textEncoder) { + const writeLength = textEncoder.encodeInto(str, this.uint8.subarray(this.x, this.x + maxLength)).written; + this.x += writeLength; + return writeLength; + } + return this.utf8Native(str); + } + utf8Native(str) { + const length = str.length; + const uint8 = this.uint8; + let offset = this.x; + let pos = 0; + while (pos < length) { + let value = str.charCodeAt(pos++); + if ((value & 0xffffff80) === 0) { + uint8[offset++] = value; + continue; + } + else if ((value & 0xfffff800) === 0) { + uint8[offset++] = ((value >> 6) & 0x1f) | 0xc0; + } + else { + if (value >= 0xd800 && value <= 0xdbff) { + if (pos < length) { + const extra = str.charCodeAt(pos); + if ((extra & 0xfc00) === 0xdc00) { + pos++; + value = ((value & 0x3ff) << 10) + (extra & 0x3ff) + 0x10000; + } + } + } + if ((value & 0xffff0000) === 0) { + uint8[offset++] = ((value >> 12) & 0x0f) | 0xe0; + uint8[offset++] = ((value >> 6) & 0x3f) | 0x80; + } + else { + uint8[offset++] = ((value >> 18) & 0x07) | 0xf0; + uint8[offset++] = ((value >> 12) & 0x3f) | 0x80; + uint8[offset++] = ((value >> 6) & 0x3f) | 0x80; + } + } + uint8[offset++] = (value & 0x3f) | 0x80; + } + const writeLength = offset - this.x; + this.x = offset; + return writeLength; + } + ascii(str) { + const length = str.length; + this.ensureCapacity(length); + const uint8 = this.uint8; + let x = this.x; + let pos = 0; + while (pos < length) + uint8[x++] = str.charCodeAt(pos++); + this.x = x; + } + }; + Writer.Writer = Writer$1; + + return Writer; +} + +var hasRequiredShared; + +function requireShared () { + if (hasRequiredShared) return shared; + hasRequiredShared = 1; + Object.defineProperty(shared, "__esModule", { value: true }); + shared.validateEntryName = shared.writer = void 0; + const Writer_1 = requireWriter(); + shared.writer = new Writer_1.Writer(1024 * 32); + const validateEntryName = (name) => { + if (!name || name === '.' || name === '..' || name.indexOf('/') !== -1 || name.indexOf('\\') !== -1) + throw new Error(`Invalid snapshot entry name: ${JSON.stringify(name)}`); + }; + shared.validateEntryName = validateEntryName; + + return shared; +} + +var hasRequiredSync; + +function requireSync () { + if (hasRequiredSync) return sync; + hasRequiredSync = 1; + (function (exports) { + Object.defineProperty(exports, "__esModule", { value: true }); + exports.fromSnapshotSync = exports.toSnapshotSync = void 0; + const shared_1 = requireShared(); + const toSnapshotSync = ({ fs, path = '/', separator = '/' }) => { + const stats = fs.lstatSync(path); + if (stats.isDirectory()) { + const list = fs.readdirSync(path); + const entries = {}; + const dir = path.endsWith(separator) ? path : path + separator; + for (const child of list) { + const childSnapshot = (0, exports.toSnapshotSync)({ fs, path: `${dir}${child}`, separator }); + if (childSnapshot) + entries['' + child] = childSnapshot; + } + return [0 /* SnapshotNodeType.Folder */, {}, entries]; + } + else if (stats.isFile()) { + const buf = fs.readFileSync(path); + const uint8 = new Uint8Array(buf.buffer, buf.byteOffset, buf.byteLength); + return [1 /* SnapshotNodeType.File */, {}, uint8]; + } + else if (stats.isSymbolicLink()) { + return [ + 2 /* SnapshotNodeType.Symlink */, + { + target: fs.readlinkSync(path).toString(), + }, + ]; + } + return null; + }; + exports.toSnapshotSync = toSnapshotSync; + const fromSnapshotSync = (snapshot, { fs, path = '/', separator = '/' }) => { + if (!snapshot) + return; + switch (snapshot[0]) { + case 0 /* SnapshotNodeType.Folder */: { + if (!path.endsWith(separator)) + path = path + separator; + const [, , entries] = snapshot; + fs.mkdirSync(path, { recursive: true }); + for (const [name, child] of Object.entries(entries)) { + (0, shared_1.validateEntryName)(name); + (0, exports.fromSnapshotSync)(child, { fs, path: `${path}${name}`, separator }); + } + break; + } + case 1 /* SnapshotNodeType.File */: { + const [, , data] = snapshot; + fs.writeFileSync(path, data); + break; + } + case 2 /* SnapshotNodeType.Symlink */: { + const [, { target }] = snapshot; + fs.symlinkSync(target, path); + break; + } + } + }; + exports.fromSnapshotSync = fromSnapshotSync; + + } (sync)); + return sync; +} + +var binary = {}; + +var CborEncoder = {}; + +var isFloat32 = {}; + +var hasRequiredIsFloat32; + +function requireIsFloat32 () { + if (hasRequiredIsFloat32) return isFloat32; + hasRequiredIsFloat32 = 1; + Object.defineProperty(isFloat32, "__esModule", { value: true }); + isFloat32.isFloat32 = void 0; + const view = new DataView(new ArrayBuffer(4)); + const isFloat32$1 = (n) => { + view.setFloat32(0, n); + return n === view.getFloat32(0); + }; + isFloat32.isFloat32 = isFloat32$1; + + return isFloat32; +} + +var JsonPackExtension = {}; + +var hasRequiredJsonPackExtension; + +function requireJsonPackExtension () { + if (hasRequiredJsonPackExtension) return JsonPackExtension; + hasRequiredJsonPackExtension = 1; + Object.defineProperty(JsonPackExtension, "__esModule", { value: true }); + JsonPackExtension.JsonPackExtension = void 0; + /** + * A wrapping for MessagePack extension or CBOR tag value. When encoder + * encounters {@link JsonPackExtension} it will encode it as a MessagePack + * extension or CBOR tag. Likewise, the decoder will + * decode extensions into {@link JsonPackExtension}. + * + * @category Value + */ + let JsonPackExtension$1 = class JsonPackExtension { + constructor(tag, val) { + this.tag = tag; + this.val = val; + } + }; + JsonPackExtension.JsonPackExtension = JsonPackExtension$1; + + return JsonPackExtension; +} + +var CborEncoderFast = {}; + +var hasRequiredCborEncoderFast; + +function requireCborEncoderFast () { + if (hasRequiredCborEncoderFast) return CborEncoderFast; + hasRequiredCborEncoderFast = 1; + Object.defineProperty(CborEncoderFast, "__esModule", { value: true }); + CborEncoderFast.CborEncoderFast = void 0; + const Writer_1 = requireWriter(); + const isSafeInteger = Number.isSafeInteger; + /** + * Fast CBOR encoder supports only JSON values. Use regular `CborEncoder` if + * you need ability to encode all CBOR value types. + */ + let CborEncoderFast$1 = class CborEncoderFast { + constructor(writer = new Writer_1.Writer()) { + this.writer = writer; + } + encode(value) { + this.writeAny(value); + return this.writer.flush(); + } + writeAny(value) { + switch (typeof value) { + case 'number': + return this.writeNumber(value); + case 'string': + return this.writeStr(value); + case 'boolean': + return this.writer.u8(0xf4 + +value); + case 'object': { + if (!value) + return this.writer.u8(0xf6); + const constr = value.constructor; + switch (constr) { + case Array: + return this.writeArr(value); + default: + return this.writeObj(value); + } + } + } + } + writeCbor() { + this.writer.u8u16(0xd9, 0xd9f7); + } + writeEnd() { + this.writer.u8(255 /* CONST.END */); + } + writeNull() { + this.writer.u8(0xf6); + } + writeBoolean(bool) { + if (bool) + this.writer.u8(0xf5); + else + this.writer.u8(0xf4); + } + writeNumber(num) { + if (isSafeInteger(num)) + this.writeInteger(num); + else if (typeof num === 'bigint') + this.writeBigInt(num); + else + this.writeFloat(num); + } + writeBigInt(int) { + if (int >= 0) + this.writeBigUint(int); + else + this.writeBigSint(int); + } + writeBigUint(uint) { + if (uint <= Number.MAX_SAFE_INTEGER) + return this.writeUInteger(Number(uint)); + this.writer.u8u64(0x1b, uint); + } + writeBigSint(int) { + if (int >= Number.MIN_SAFE_INTEGER) + return this.encodeNint(Number(int)); + const uint = -BigInt(1) - int; + this.writer.u8u64(0x3b, uint); + } + writeInteger(int) { + if (int >= 0) + this.writeUInteger(int); + else + this.encodeNint(int); + } + writeUInteger(uint) { + const writer = this.writer; + writer.ensureCapacity(9); + const uint8 = writer.uint8; + let x = writer.x; + if (uint <= 23) { + uint8[x++] = 0 /* MAJOR_OVERLAY.UIN */ + uint; + } + else if (uint <= 0xff) { + uint8[x++] = 0x18; + uint8[x++] = uint; + } + else if (uint <= 0xffff) { + uint8[x++] = 0x19; + writer.view.setUint16(x, uint); + x += 2; + } + else if (uint <= 0xffffffff) { + uint8[x++] = 0x1a; + writer.view.setUint32(x, uint); + x += 4; + } + else { + uint8[x++] = 0x1b; + writer.view.setBigUint64(x, BigInt(uint)); + x += 8; + } + writer.x = x; + } + /** @deprecated Remove and use `writeNumber` instead. */ + encodeNumber(num) { + this.writeNumber(num); + } + /** @deprecated Remove and use `writeInteger` instead. */ + encodeInteger(int) { + this.writeInteger(int); + } + /** @deprecated */ + encodeUint(uint) { + this.writeUInteger(uint); + } + encodeNint(int) { + const uint = -1 - int; + const writer = this.writer; + writer.ensureCapacity(9); + const uint8 = writer.uint8; + let x = writer.x; + if (uint < 24) { + uint8[x++] = 32 /* MAJOR_OVERLAY.NIN */ + uint; + } + else if (uint <= 0xff) { + uint8[x++] = 0x38; + uint8[x++] = uint; + } + else if (uint <= 0xffff) { + uint8[x++] = 0x39; + writer.view.setUint16(x, uint); + x += 2; + } + else if (uint <= 0xffffffff) { + uint8[x++] = 0x3a; + writer.view.setUint32(x, uint); + x += 4; + } + else { + uint8[x++] = 0x3b; + writer.view.setBigUint64(x, BigInt(uint)); + x += 8; + } + writer.x = x; + } + writeFloat(float) { + this.writer.u8f64(0xfb, float); + } + writeBin(buf) { + const length = buf.length; + this.writeBinHdr(length); + this.writer.buf(buf, length); + } + writeBinHdr(length) { + const writer = this.writer; + if (length <= 23) + writer.u8(64 /* MAJOR_OVERLAY.BIN */ + length); + else if (length <= 0xff) + writer.u16((0x58 << 8) + length); + else if (length <= 0xffff) + writer.u8u16(0x59, length); + else if (length <= 0xffffffff) + writer.u8u32(0x5a, length); + else + writer.u8u64(0x5b, length); + } + writeStr(str) { + const writer = this.writer; + const length = str.length; + const maxSize = length * 4; + writer.ensureCapacity(5 + maxSize); + const uint8 = writer.uint8; + let lengthOffset = writer.x; + if (maxSize <= 23) + writer.x++; + else if (maxSize <= 0xff) { + uint8[writer.x++] = 0x78; + lengthOffset = writer.x; + writer.x++; + } + else if (maxSize <= 0xffff) { + uint8[writer.x++] = 0x79; + lengthOffset = writer.x; + writer.x += 2; + } + else { + uint8[writer.x++] = 0x7a; + lengthOffset = writer.x; + writer.x += 4; + } + const bytesWritten = writer.utf8(str); + if (maxSize <= 23) + uint8[lengthOffset] = 96 /* MAJOR_OVERLAY.STR */ + bytesWritten; + else if (maxSize <= 0xff) + uint8[lengthOffset] = bytesWritten; + else if (maxSize <= 0xffff) + writer.view.setUint16(lengthOffset, bytesWritten); + else + writer.view.setUint32(lengthOffset, bytesWritten); + } + writeStrHdr(length) { + const writer = this.writer; + if (length <= 23) + writer.u8(96 /* MAJOR_OVERLAY.STR */ + length); + else if (length <= 0xff) + writer.u16((0x78 << 8) + length); + else if (length <= 0xffff) + writer.u8u16(0x79, length); + else + writer.u8u32(0x7a, length); + } + writeAsciiStr(str) { + this.writeStrHdr(str.length); + this.writer.ascii(str); + } + writeArr(arr) { + const length = arr.length; + this.writeArrHdr(length); + for (let i = 0; i < length; i++) + this.writeAny(arr[i]); + } + writeArrHdr(length) { + const writer = this.writer; + if (length <= 23) + writer.u8(128 /* MAJOR_OVERLAY.ARR */ + length); + else if (length <= 0xff) + writer.u16((0x98 << 8) + length); + else if (length <= 0xffff) + writer.u8u16(0x99, length); + else if (length <= 0xffffffff) + writer.u8u32(0x9a, length); + else + writer.u8u64(0x9b, length); + } + writeObj(obj) { + const keys = Object.keys(obj); + const length = keys.length; + this.writeObjHdr(length); + for (let i = 0; i < length; i++) { + const key = keys[i]; + this.writeStr(key); + this.writeAny(obj[key]); + } + } + writeObjHdr(length) { + const writer = this.writer; + if (length <= 23) + writer.u8(160 /* MAJOR_OVERLAY.MAP */ + length); + else if (length <= 0xff) + writer.u16((0xb8 << 8) + length); + else if (length <= 0xffff) + writer.u8u16(0xb9, length); + else if (length <= 0xffffffff) + writer.u8u32(0xba, length); + else + writer.u8u64(0xbb, length); + } + writeMapHdr(length) { + this.writeObjHdr(length); + } + writeStartMap() { + this.writer.u8(0xbf); + } + writeTag(tag, value) { + this.writeTagHdr(tag); + this.writeAny(value); + } + writeTagHdr(tag) { + const writer = this.writer; + if (tag <= 23) + writer.u8(192 /* MAJOR_OVERLAY.TAG */ + tag); + else if (tag <= 0xff) + writer.u16((0xd8 << 8) + tag); + else if (tag <= 0xffff) + writer.u8u16(0xd9, tag); + else if (tag <= 0xffffffff) + writer.u8u32(0xda, tag); + else + writer.u8u64(0xdb, tag); + } + writeTkn(value) { + const writer = this.writer; + if (value <= 23) + writer.u8(224 /* MAJOR_OVERLAY.TKN */ + value); + else if (value <= 0xff) + writer.u16((0xf8 << 8) + value); + } + // ------------------------------------------------------- Streaming encoding + writeStartStr() { + this.writer.u8(0x7f); + } + writeStrChunk(str) { + throw new Error('Not implemented'); + } + writeEndStr() { + throw new Error('Not implemented'); + } + writeStartBin() { + this.writer.u8(0x5f); + } + writeBinChunk(buf) { + throw new Error('Not implemented'); + } + writeEndBin() { + throw new Error('Not implemented'); + } + writeStartArr() { + this.writer.u8(0x9f); + } + writeArrChunk(item) { + throw new Error('Not implemented'); + } + writeEndArr() { + this.writer.u8(255 /* CONST.END */); + } + writeStartObj() { + this.writer.u8(0xbf); + } + writeObjChunk(key, value) { + throw new Error('Not implemented'); + } + writeEndObj() { + this.writer.u8(255 /* CONST.END */); + } + }; + CborEncoderFast.CborEncoderFast = CborEncoderFast$1; + + return CborEncoderFast; +} + +var JsonPackValue = {}; + +var hasRequiredJsonPackValue; + +function requireJsonPackValue () { + if (hasRequiredJsonPackValue) return JsonPackValue; + hasRequiredJsonPackValue = 1; + Object.defineProperty(JsonPackValue, "__esModule", { value: true }); + JsonPackValue.JsonPackValue = void 0; + /** + * Use this wrapper is you have a pre-encoded MessagePack or CBOR value and you would + * like to dump it into a the document as-is. The contents of `buf` will + * be written as is to the document. + * + * It also serves as CBOR simple value container. In which case the type of value + * `val` field is "number". + * + * @category Value + */ + let JsonPackValue$1 = class JsonPackValue { + constructor(val) { + this.val = val; + } + }; + JsonPackValue.JsonPackValue = JsonPackValue$1; + + return JsonPackValue; +} + +var hasRequiredCborEncoder; + +function requireCborEncoder () { + if (hasRequiredCborEncoder) return CborEncoder; + hasRequiredCborEncoder = 1; + Object.defineProperty(CborEncoder, "__esModule", { value: true }); + CborEncoder.CborEncoder = void 0; + const isFloat32_1 = requireIsFloat32(); + const JsonPackExtension_1 = requireJsonPackExtension(); + const CborEncoderFast_1 = requireCborEncoderFast(); + const JsonPackValue_1 = requireJsonPackValue(); + let CborEncoder$1 = class CborEncoder extends CborEncoderFast_1.CborEncoderFast { + /** + * Called when the encoder encounters a value that it does not know how to encode. + * + * @param value Some JavaScript value. + */ + writeUnknown(value) { + this.writeNull(); + } + writeAny(value) { + switch (typeof value) { + case 'number': + return this.writeNumber(value); + case 'string': + return this.writeStr(value); + case 'boolean': + return this.writer.u8(0xf4 + +value); + case 'object': { + if (!value) + return this.writer.u8(0xf6); + const constr = value.constructor; + switch (constr) { + case Object: + return this.writeObj(value); + case Array: + return this.writeArr(value); + case Uint8Array: + return this.writeBin(value); + case Map: + return this.writeMap(value); + case JsonPackExtension_1.JsonPackExtension: + return this.writeTag(value.tag, value.val); + case JsonPackValue_1.JsonPackValue: { + const buf = value.val; + return this.writer.buf(buf, buf.length); + } + default: + if (value instanceof Uint8Array) + return this.writeBin(value); + if (Array.isArray(value)) + return this.writeArr(value); + if (value instanceof Map) + return this.writeMap(value); + return this.writeUnknown(value); + } + } + case 'undefined': + return this.writeUndef(); + case 'bigint': + return this.writeBigInt(value); + default: + return this.writeUnknown(value); + } + } + writeFloat(float) { + if ((0, isFloat32_1.isFloat32)(float)) + this.writer.u8f32(0xfa, float); + else + this.writer.u8f64(0xfb, float); + } + writeMap(map) { + this.writeMapHdr(map.size); + map.forEach((value, key) => { + this.writeAny(key); + this.writeAny(value); + }); + } + writeUndef() { + this.writer.u8(0xf7); + } + }; + CborEncoder.CborEncoder = CborEncoder$1; + + return CborEncoder; +} + +var CborDecoder = {}; + +var CborDecoderBase = {}; + +var f16 = {}; + +var hasRequiredF16; + +function requireF16 () { + if (hasRequiredF16) return f16; + hasRequiredF16 = 1; + Object.defineProperty(f16, "__esModule", { value: true }); + f16.decodeF16 = void 0; + const pow = Math.pow; + const decodeF16 = (binary) => { + const exponent = (binary & 0x7c00) >> 10; + const fraction = binary & 0x03ff; + return ((binary >> 15 ? -1 : 1) * + (exponent + ? exponent === 0x1f + ? fraction + ? NaN + : Infinity + : pow(2, exponent - 15) * (1 + fraction / 0x400) + : 6.103515625e-5 * (fraction / 0x400))); + }; + f16.decodeF16 = decodeF16; + + return f16; +} + +var Reader = {}; + +var decodeUtf8 = {}; + +var v16 = {}; + +var decodeAscii = {}; + +var hasRequiredDecodeAscii; + +function requireDecodeAscii () { + if (hasRequiredDecodeAscii) return decodeAscii; + hasRequiredDecodeAscii = 1; + Object.defineProperty(decodeAscii, "__esModule", { value: true }); + decodeAscii.decodeAsciiMax15 = decodeAscii.decodeAscii = void 0; + const fromCharCode = String.fromCharCode; + /** This code was borrowed form cbor-x under the MIT license. */ + // MIT License + // Copyright (c) 2020 Kris Zyp + // Permission is hereby granted, free of charge, to any person obtaining a copy + // of this software and associated documentation files (the "Software"), to deal + // in the Software without restriction, including without limitation the rights + // to use, copy, modify, merge, publish, distribute, sublicense, and/or sell + // copies of the Software, and to permit persons to whom the Software is + // furnished to do so, subject to the following conditions: + // The above copyright notice and this permission notice shall be included in all + // copies or substantial portions of the Software. + // THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR + // IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, + // FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE + // AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER + // LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, + // OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE + // SOFTWARE. + const decodeAscii$1 = (src, position, length) => { + const bytes = []; + for (let i = 0; i < length; i++) { + const byte = src[position++]; + if (byte & 0x80) + return; + bytes.push(byte); + } + return fromCharCode.apply(String, bytes); + }; + decodeAscii.decodeAscii = decodeAscii$1; + const decodeAsciiMax15 = (src, position, length) => { + if (length < 4) { + if (length < 2) { + if (length === 0) + return ''; + else { + const a = src[position++]; + if ((a & 0x80) > 1) { + position -= 1; + return; + } + return fromCharCode(a); + } + } + else { + const a = src[position++]; + const b = src[position++]; + if ((a & 0x80) > 0 || (b & 0x80) > 0) { + position -= 2; + return; + } + if (length < 3) + return fromCharCode(a, b); + const c = src[position++]; + if ((c & 0x80) > 0) { + position -= 3; + return; + } + return fromCharCode(a, b, c); + } + } + else { + const a = src[position++]; + const b = src[position++]; + const c = src[position++]; + const d = src[position++]; + if ((a & 0x80) > 0 || (b & 0x80) > 0 || (c & 0x80) > 0 || (d & 0x80) > 0) { + position -= 4; + return; + } + if (length < 6) { + if (length === 4) + return fromCharCode(a, b, c, d); + else { + const e = src[position++]; + if ((e & 0x80) > 0) { + position -= 5; + return; + } + return fromCharCode(a, b, c, d, e); + } + } + else if (length < 8) { + const e = src[position++]; + const f = src[position++]; + if ((e & 0x80) > 0 || (f & 0x80) > 0) { + position -= 6; + return; + } + if (length < 7) + return fromCharCode(a, b, c, d, e, f); + const g = src[position++]; + if ((g & 0x80) > 0) { + position -= 7; + return; + } + return fromCharCode(a, b, c, d, e, f, g); + } + else { + const e = src[position++]; + const f = src[position++]; + const g = src[position++]; + const h = src[position++]; + if ((e & 0x80) > 0 || (f & 0x80) > 0 || (g & 0x80) > 0 || (h & 0x80) > 0) { + position -= 8; + return; + } + if (length < 10) { + if (length === 8) + return fromCharCode(a, b, c, d, e, f, g, h); + else { + const i = src[position++]; + if ((i & 0x80) > 0) { + position -= 9; + return; + } + return fromCharCode(a, b, c, d, e, f, g, h, i); + } + } + else if (length < 12) { + const i = src[position++]; + const j = src[position++]; + if ((i & 0x80) > 0 || (j & 0x80) > 0) { + position -= 10; + return; + } + if (length < 11) + return fromCharCode(a, b, c, d, e, f, g, h, i, j); + const k = src[position++]; + if ((k & 0x80) > 0) { + position -= 11; + return; + } + return fromCharCode(a, b, c, d, e, f, g, h, i, j, k); + } + else { + const i = src[position++]; + const j = src[position++]; + const k = src[position++]; + const l = src[position++]; + if ((i & 0x80) > 0 || (j & 0x80) > 0 || (k & 0x80) > 0 || (l & 0x80) > 0) { + position -= 12; + return; + } + if (length < 14) { + if (length === 12) + return fromCharCode(a, b, c, d, e, f, g, h, i, j, k, l); + else { + const m = src[position++]; + if ((m & 0x80) > 0) { + position -= 13; + return; + } + return fromCharCode(a, b, c, d, e, f, g, h, i, j, k, l, m); + } + } + else { + const m = src[position++]; + const n = src[position++]; + if ((m & 0x80) > 0 || (n & 0x80) > 0) { + position -= 14; + return; + } + if (length < 15) + return fromCharCode(a, b, c, d, e, f, g, h, i, j, k, l, m, n); + const o = src[position++]; + if ((o & 0x80) > 0) { + position -= 15; + return; + } + return fromCharCode(a, b, c, d, e, f, g, h, i, j, k, l, m, n, o); + } + } + } + } + }; + decodeAscii.decodeAsciiMax15 = decodeAsciiMax15; + + return decodeAscii; +} + +var v18 = {}; + +var hasRequiredV18; + +function requireV18 () { + if (hasRequiredV18) return v18; + hasRequiredV18 = 1; + Object.defineProperty(v18, "__esModule", { value: true }); + const fromCharCode = String.fromCharCode; + v18.default = (buf, start, length) => { + let offset = start; + const end = offset + length; + const points = []; + while (offset < end) { + let code = buf[offset++]; + if ((code & 0x80) !== 0) { + const octet2 = buf[offset++] & 0x3f; + if ((code & 0xe0) === 0xc0) { + code = ((code & 0x1f) << 6) | octet2; + } + else { + const octet3 = buf[offset++] & 0x3f; + if ((code & 0xf0) === 0xe0) { + code = ((code & 0x1f) << 12) | (octet2 << 6) | octet3; + } + else { + if ((code & 0xf8) === 0xf0) { + const octet4 = buf[offset++] & 0x3f; + let unit = ((code & 0x07) << 0x12) | (octet2 << 0x0c) | (octet3 << 0x06) | octet4; + if (unit > 0xffff) { + unit -= 0x10000; + const unit0 = ((unit >>> 10) & 0x3ff) | 0xd800; + code = 0xdc00 | (unit & 0x3ff); + points.push(unit0); + } + else { + code = unit; + } + } + } + } + } + points.push(code); + } + return fromCharCode.apply(String, points); + }; + + return v18; +} + +var hasRequiredV16; + +function requireV16 () { + if (hasRequiredV16) return v16; + hasRequiredV16 = 1; + Object.defineProperty(v16, "__esModule", { value: true }); + const tslib_1 = require$$0$2; + const decodeAscii_1 = requireDecodeAscii(); + const v18_1 = tslib_1.__importDefault(requireV18()); + const hasBuffer = typeof Buffer !== 'undefined'; + const utf8Slice = hasBuffer ? Buffer.prototype.utf8Slice : null; + const from = hasBuffer ? Buffer.from : null; + const shortDecoder = (buf, start, length) => (0, decodeAscii_1.decodeAsciiMax15)(buf, start, length) ?? (0, v18_1.default)(buf, start, length); + const midDecoder = (buf, start, length) => (0, decodeAscii_1.decodeAscii)(buf, start, length) ?? (0, v18_1.default)(buf, start, length); + const longDecoder = utf8Slice + ? (buf, start, length) => utf8Slice.call(buf, start, start + length) + : from + ? (buf, start, length) => from(buf) + .subarray(start, start + length) + .toString('utf8') + : v18_1.default; + const decoder = (buf, start, length) => { + if (length < 16) + return shortDecoder(buf, start, length); + if (length < 32) + return midDecoder(buf, start, length); + return longDecoder(buf, start, length); + }; + v16.default = decoder; + + return v16; +} + +var hasRequiredDecodeUtf8; + +function requireDecodeUtf8 () { + if (hasRequiredDecodeUtf8) return decodeUtf8; + hasRequiredDecodeUtf8 = 1; + Object.defineProperty(decodeUtf8, "__esModule", { value: true }); + decodeUtf8.decodeUtf8 = void 0; + const tslib_1 = require$$0$2; + const v16_1 = tslib_1.__importDefault(requireV16()); + decodeUtf8.decodeUtf8 = v16_1.default; + + return decodeUtf8; +} + +var hasRequiredReader; + +function requireReader () { + if (hasRequiredReader) return Reader; + hasRequiredReader = 1; + Object.defineProperty(Reader, "__esModule", { value: true }); + Reader.Reader = void 0; + const decodeUtf8_1 = requireDecodeUtf8(); + let Reader$1 = class Reader { + constructor(uint8 = new Uint8Array([]), view = new DataView(uint8.buffer, uint8.byteOffset, uint8.length), x = 0, end = uint8.length) { + this.uint8 = uint8; + this.view = view; + this.x = x; + this.end = end; + } + reset(uint8) { + this.x = 0; + this.uint8 = uint8; + this.view = new DataView(uint8.buffer, uint8.byteOffset, uint8.length); + } + size() { + return this.end - this.x; + } + /** + * Get current byte value without advancing the cursor. + */ + peek() { + return this.view.getUint8(this.x); + } + /** + * @deprecated Use peek() instead. + */ + peak() { + return this.peek(); + } + skip(length) { + this.x += length; + } + buf(size = this.size()) { + const x = this.x; + const end = x + size; + const bin = this.uint8.subarray(x, end); + this.x = end; + return bin; + } + subarray(start = 0, end) { + const x = this.x; + const actualStart = x + start; + const actualEnd = typeof end === 'number' ? x + end : this.end; + return this.uint8.subarray(actualStart, actualEnd); + } + /** + * Creates a new {@link Reader} that references the same underlying memory + * buffer. But with independent cursor and end. + * + * Preferred over {@link buf} since it also provides a DataView and is much + * faster to allocate a new {@link Slice} than a new {@link Uint8Array}. + * + * @param start Start offset relative to the current cursor position. + * @param end End offset relative to the current cursor position. + * @returns A new {@link Reader} instance. + */ + slice(start = 0, end) { + const x = this.x; + const actualStart = x + start; + const actualEnd = typeof end === 'number' ? x + end : this.end; + return new Reader(this.uint8, this.view, actualStart, actualEnd); + } + /** + * Similar to {@link slice} but also advances the cursor. Returns a new + * {@link Reader} that references the same underlying memory buffer, starting + * from the current cursor position. + * + * @param size Number of bytes to cut from the current position. + * @returns A new {@link Reader} instance. + */ + cut(size = this.size()) { + const slice = this.slice(0, size); + this.skip(size); + return slice; + } + u8() { + return this.uint8[this.x++]; + // return this.view.getUint8(this.x++); + } + i8() { + return this.view.getInt8(this.x++); + } + u16() { + // const num = this.view.getUint16(this.x); + // this.x += 2; + // return num; + let x = this.x; + const num = (this.uint8[x++] << 8) + this.uint8[x++]; + this.x = x; + return num; + } + i16() { + const num = this.view.getInt16(this.x); + this.x += 2; + return num; + } + u32() { + const num = this.view.getUint32(this.x); + this.x += 4; + return num; + } + i32() { + const num = this.view.getInt32(this.x); + this.x += 4; + return num; + } + u64() { + const num = this.view.getBigUint64(this.x); + this.x += 8; + return num; + } + i64() { + const num = this.view.getBigInt64(this.x); + this.x += 8; + return num; + } + f32() { + const pos = this.x; + this.x += 4; + return this.view.getFloat32(pos); + } + f64() { + const pos = this.x; + this.x += 8; + return this.view.getFloat64(pos); + } + utf8(size) { + const start = this.x; + this.x += size; + return (0, decodeUtf8_1.decodeUtf8)(this.uint8, start, size); + } + ascii(length) { + const uint8 = this.uint8; + let str = ''; + const end = this.x + length; + for (let i = this.x; i < end; i++) + str += String.fromCharCode(uint8[i]); + this.x = end; + return str; + } + }; + Reader.Reader = Reader$1; + + return Reader; +} + +var sharedCachedUtf8Decoder = {}; + +var CachedUtf8Decoder = {}; + +var v10 = {}; + +var hasRequiredV10; + +function requireV10 () { + if (hasRequiredV10) return v10; + hasRequiredV10 = 1; + Object.defineProperty(v10, "__esModule", { value: true }); + const fromCharCode = String.fromCharCode; + v10.default = (buf, start, length) => { + let offset = start; + const end = offset + length; + let str = ''; + while (offset < end) { + const octet1 = buf[offset++]; + if ((octet1 & 0x80) === 0) { + str += fromCharCode(octet1); + continue; + } + const octet2 = buf[offset++] & 0x3f; + if ((octet1 & 0xe0) === 0xc0) { + str += fromCharCode(((octet1 & 0x1f) << 6) | octet2); + continue; + } + const octet3 = buf[offset++] & 0x3f; + if ((octet1 & 0xf0) === 0xe0) { + str += fromCharCode(((octet1 & 0x1f) << 12) | (octet2 << 6) | octet3); + continue; + } + if ((octet1 & 0xf8) === 0xf0) { + const octet4 = buf[offset++] & 0x3f; + let unit = ((octet1 & 0x07) << 0x12) | (octet2 << 0x0c) | (octet3 << 0x06) | octet4; + if (unit > 0xffff) { + unit -= 0x10000; + const unit0 = ((unit >>> 10) & 0x3ff) | 0xd800; + unit = 0xdc00 | (unit & 0x3ff); + str += fromCharCode(unit0, unit); + } + else { + str += fromCharCode(unit); + } + } + else { + str += fromCharCode(octet1); + } + } + return str; + }; + + return v10; +} + +var hasRequiredCachedUtf8Decoder; + +function requireCachedUtf8Decoder () { + if (hasRequiredCachedUtf8Decoder) return CachedUtf8Decoder; + hasRequiredCachedUtf8Decoder = 1; + Object.defineProperty(CachedUtf8Decoder, "__esModule", { value: true }); + CachedUtf8Decoder.CachedUtf8Decoder = void 0; + const tslib_1 = require$$0$2; + const v10_1 = tslib_1.__importDefault(requireV10()); + let x = 1 + Math.round(Math.random() * ((-1 >>> 0) - 1)); + /** Generate a random 32-bit unsigned integer in the specified [min, max] range. */ + function randomU32(min, max) { + x ^= x << 13; + x ^= x >>> 17; + x ^= x << 5; + return ((x >>> 0) % (max - min + 1)) + min; + } + class CacheItem { + constructor(bytes, value) { + this.bytes = bytes; + this.value = value; + } + } + let CachedUtf8Decoder$1 = class CachedUtf8Decoder { + constructor() { + this.caches = []; + for (let i = 0; i < 31 /* CONST.MAX_CACHED_STR_LEN */; i++) + this.caches.push([]); + } + get(bytes, offset, size) { + const records = this.caches[size - 1]; + const len = records.length; + FIND_CHUNK: for (let i = 0; i < len; i++) { + const record = records[i]; + const recordBytes = record.bytes; + for (let j = 0; j < size; j++) + if (recordBytes[j] !== bytes[offset + j]) + continue FIND_CHUNK; + return record.value; + } + return null; + } + store(bytes, value) { + const records = this.caches[bytes.length - 1]; + const record = new CacheItem(bytes, value); + const length = records.length; + if (length >= 16 /* CONST.MAX_RECORDS_PER_SIZE */) + records[randomU32(0, 16 /* CONST.MAX_RECORDS_PER_SIZE */ - 1)] = record; + else + records.push(record); + } + decode(bytes, offset, size) { + if (!size) + return ''; + const cachedValue = this.get(bytes, offset, size); + if (cachedValue !== null) + return cachedValue; + const value = (0, v10_1.default)(bytes, offset, size); + // Ensure to copy a slice of bytes because the byte may be NodeJS Buffer and Buffer#slice() returns a reference to its internal ArrayBuffer. + const copy = Uint8Array.prototype.slice.call(bytes, offset, offset + size); + this.store(copy, value); + return value; + } + }; + CachedUtf8Decoder.CachedUtf8Decoder = CachedUtf8Decoder$1; + + return CachedUtf8Decoder; +} + +var hasRequiredSharedCachedUtf8Decoder; + +function requireSharedCachedUtf8Decoder () { + if (hasRequiredSharedCachedUtf8Decoder) return sharedCachedUtf8Decoder; + hasRequiredSharedCachedUtf8Decoder = 1; + Object.defineProperty(sharedCachedUtf8Decoder, "__esModule", { value: true }); + const CachedUtf8Decoder_1 = requireCachedUtf8Decoder(); + sharedCachedUtf8Decoder.default = new CachedUtf8Decoder_1.CachedUtf8Decoder(); + + return sharedCachedUtf8Decoder; +} + +var hasRequiredCborDecoderBase; + +function requireCborDecoderBase () { + if (hasRequiredCborDecoderBase) return CborDecoderBase; + hasRequiredCborDecoderBase = 1; + Object.defineProperty(CborDecoderBase, "__esModule", { value: true }); + CborDecoderBase.CborDecoderBase = void 0; + const tslib_1 = require$$0$2; + const f16_1 = requireF16(); + const JsonPackExtension_1 = requireJsonPackExtension(); + const JsonPackValue_1 = requireJsonPackValue(); + const Reader_1 = requireReader(); + const sharedCachedUtf8Decoder_1 = tslib_1.__importDefault(requireSharedCachedUtf8Decoder()); + let CborDecoderBase$1 = class CborDecoderBase { + constructor(reader = new Reader_1.Reader(), keyDecoder = sharedCachedUtf8Decoder_1.default) { + this.reader = reader; + this.keyDecoder = keyDecoder; + } + read(uint8) { + this.reader.reset(uint8); + return this.readAny(); + } + decode(uint8) { + this.reader.reset(uint8); + return this.readAny(); + } + // -------------------------------------------------------- Any value reading + val() { + return this.readAny(); + } + readAny() { + const reader = this.reader; + const octet = reader.u8(); + const major = octet >> 5; + const minor = octet & 31 /* CONST.MINOR_MASK */; + if (major < 4 /* MAJOR.ARR */) { + if (major < 2 /* MAJOR.BIN */) + return major === 0 /* MAJOR.UIN */ ? this.readUint(minor) : this.readNint(minor); + else + return major === 2 /* MAJOR.BIN */ ? this.readBin(minor) : this.readStr(minor); + } + else { + if (major < 6 /* MAJOR.TAG */) + return major === 4 /* MAJOR.ARR */ ? this.readArr(minor) : this.readObj(minor); + else + return major === 6 /* MAJOR.TAG */ ? this.readTag(minor) : this.readTkn(minor); + } + } + readAnyRaw(octet) { + const major = octet >> 5; + const minor = octet & 31 /* CONST.MINOR_MASK */; + if (major < 4 /* MAJOR.ARR */) { + if (major < 2 /* MAJOR.BIN */) + return major === 0 /* MAJOR.UIN */ ? this.readUint(minor) : this.readNint(minor); + else + return major === 2 /* MAJOR.BIN */ ? this.readBin(minor) : this.readStr(minor); + } + else { + if (major < 6 /* MAJOR.TAG */) + return major === 4 /* MAJOR.ARR */ ? this.readArr(minor) : this.readObj(minor); + else + return major === 6 /* MAJOR.TAG */ ? this.readTag(minor) : this.readTkn(minor); + } + } + readMinorLen(minor) { + if (minor < 24) + return minor; + switch (minor) { + case 24: + return this.reader.u8(); + case 25: + return this.reader.u16(); + case 26: + return this.reader.u32(); + case 27: + return Number(this.reader.u64()); + case 31: + return -1; + default: + throw 1 /* ERROR.UNEXPECTED_MINOR */; + } + } + // ----------------------------------------------------- Unsigned int reading + readUint(minor) { + if (minor < 25) { + return minor === 24 ? this.reader.u8() : minor; + } + else { + if (minor < 27) { + return minor === 25 ? this.reader.u16() : this.reader.u32(); + } + else { + const num = this.reader.u64(); + return num > 9007199254740991 /* CONST.MAX_UINT */ ? num : Number(num); + } + } + } + // ----------------------------------------------------- Negative int reading + readNint(minor) { + if (minor < 25) { + return minor === 24 ? -this.reader.u8() - 1 : -minor - 1; + } + else { + if (minor < 27) { + return minor === 25 ? -this.reader.u16() - 1 : -this.reader.u32() - 1; + } + else { + const num = this.reader.u64(); + return num > 9007199254740991 /* CONST.MAX_UINT */ - 1 ? -num - BigInt(1) : -Number(num) - 1; + } + } + } + // ----------------------------------------------------------- Binary reading + readBin(minor) { + const reader = this.reader; + if (minor <= 23) + return reader.buf(minor); + switch (minor) { + case 24: + return reader.buf(reader.u8()); + case 25: + return reader.buf(reader.u16()); + case 26: + return reader.buf(reader.u32()); + case 27: + return reader.buf(Number(reader.u64())); + case 31: { + let size = 0; + const list = []; + while (this.reader.peak() !== 255 /* CONST.END */) { + const uint8 = this.readBinChunk(); + size += uint8.length; + list.push(uint8); + } + this.reader.x++; + const res = new Uint8Array(size); + let offset = 0; + const length = list.length; + for (let i = 0; i < length; i++) { + const arr = list[i]; + res.set(arr, offset); + offset += arr.length; + } + return res; + } + default: + throw 1 /* ERROR.UNEXPECTED_MINOR */; + } + } + readBinChunk() { + const octet = this.reader.u8(); + const major = octet >> 5; + const minor = octet & 31 /* CONST.MINOR_MASK */; + if (major !== 2 /* MAJOR.BIN */) + throw 2 /* ERROR.UNEXPECTED_BIN_CHUNK_MAJOR */; + if (minor > 27) + throw 3 /* ERROR.UNEXPECTED_BIN_CHUNK_MINOR */; + return this.readBin(minor); + } + // ----------------------------------------------------------- String reading + readAsStr() { + const reader = this.reader; + const octet = reader.u8(); + const major = octet >> 5; + const minor = octet & 31 /* CONST.MINOR_MASK */; + if (major !== 3 /* MAJOR.STR */) + throw 11 /* ERROR.UNEXPECTED_STR_MAJOR */; + return this.readStr(minor); + } + readStr(minor) { + const reader = this.reader; + if (minor <= 23) + return reader.utf8(minor); + switch (minor) { + case 24: + return reader.utf8(reader.u8()); + case 25: + return reader.utf8(reader.u16()); + case 26: + return reader.utf8(reader.u32()); + case 27: + return reader.utf8(Number(reader.u64())); + case 31: { + let str = ''; + while (reader.peak() !== 255 /* CONST.END */) + str += this.readStrChunk(); + this.reader.x++; + return str; + } + default: + throw 1 /* ERROR.UNEXPECTED_MINOR */; + } + } + readStrLen(minor) { + if (minor <= 23) + return minor; + switch (minor) { + case 24: + return this.reader.u8(); + case 25: + return this.reader.u16(); + case 26: + return this.reader.u32(); + case 27: + return Number(this.reader.u64()); + default: + throw 1 /* ERROR.UNEXPECTED_MINOR */; + } + } + readStrChunk() { + const octet = this.reader.u8(); + const major = octet >> 5; + const minor = octet & 31 /* CONST.MINOR_MASK */; + if (major !== 3 /* MAJOR.STR */) + throw 4 /* ERROR.UNEXPECTED_STR_CHUNK_MAJOR */; + if (minor > 27) + throw 5 /* ERROR.UNEXPECTED_STR_CHUNK_MINOR */; + return this.readStr(minor); + } + // ------------------------------------------------------------ Array reading + readArr(minor) { + const length = this.readMinorLen(minor); + if (length >= 0) + return this.readArrRaw(length); + return this.readArrIndef(); + } + readArrRaw(length) { + const arr = []; + for (let i = 0; i < length; i++) + arr.push(this.readAny()); + return arr; + } + readArrIndef() { + const arr = []; + while (this.reader.peak() !== 255 /* CONST.END */) + arr.push(this.readAny()); + this.reader.x++; + return arr; + } + // ----------------------------------------------------------- Object reading + readObj(minor) { + if (minor < 28) { + let length = minor; + switch (minor) { + case 24: + length = this.reader.u8(); + break; + case 25: + length = this.reader.u16(); + break; + case 26: + length = this.reader.u32(); + break; + case 27: + length = Number(this.reader.u64()); + break; + } + const obj = {}; + for (let i = 0; i < length; i++) { + const key = this.key(); + if (key === '__proto__') + throw 6 /* ERROR.UNEXPECTED_OBJ_KEY */; + const value = this.readAny(); + obj[key] = value; + } + return obj; + } + else if (minor === 31) + return this.readObjIndef(); + else + throw 1 /* ERROR.UNEXPECTED_MINOR */; + } + /** Remove this? */ + readObjRaw(length) { + const obj = {}; + for (let i = 0; i < length; i++) { + const key = this.key(); + const value = this.readAny(); + obj[key] = value; + } + return obj; + } + readObjIndef() { + const obj = {}; + while (this.reader.peak() !== 255 /* CONST.END */) { + const key = this.key(); + if (this.reader.peak() === 255 /* CONST.END */) + throw 7 /* ERROR.UNEXPECTED_OBJ_BREAK */; + const value = this.readAny(); + obj[key] = value; + } + this.reader.x++; + return obj; + } + key() { + const octet = this.reader.u8(); + const major = octet >> 5; + const minor = octet & 31 /* CONST.MINOR_MASK */; + if (major !== 3 /* MAJOR.STR */) + return String(this.readAnyRaw(octet)); + const length = this.readStrLen(minor); + if (length > 31) + return this.reader.utf8(length); + const key = this.keyDecoder.decode(this.reader.uint8, this.reader.x, length); + this.reader.skip(length); + return key; + } + // -------------------------------------------------------------- Tag reading + readTag(minor) { + if (minor <= 23) + return this.readTagRaw(minor); + switch (minor) { + case 24: + return this.readTagRaw(this.reader.u8()); + case 25: + return this.readTagRaw(this.reader.u16()); + case 26: + return this.readTagRaw(this.reader.u32()); + case 27: + return this.readTagRaw(Number(this.reader.u64())); + default: + throw 1 /* ERROR.UNEXPECTED_MINOR */; + } + } + readTagRaw(tag) { + return new JsonPackExtension_1.JsonPackExtension(tag, this.readAny()); + } + // ------------------------------------------------------------ Token reading + readTkn(minor) { + switch (minor) { + case 0xf4 & 31 /* CONST.MINOR_MASK */: + return false; + case 0xf5 & 31 /* CONST.MINOR_MASK */: + return true; + case 0xf6 & 31 /* CONST.MINOR_MASK */: + return null; + case 0xf7 & 31 /* CONST.MINOR_MASK */: + return undefined; + case 0xf8 & 31 /* CONST.MINOR_MASK */: + return new JsonPackValue_1.JsonPackValue(this.reader.u8()); + case 0xf9 & 31 /* CONST.MINOR_MASK */: + return this.f16(); + case 0xfa & 31 /* CONST.MINOR_MASK */: + return this.reader.f32(); + case 0xfb & 31 /* CONST.MINOR_MASK */: + return this.reader.f64(); + } + if (minor <= 23) + return new JsonPackValue_1.JsonPackValue(minor); + throw 1 /* ERROR.UNEXPECTED_MINOR */; + } + f16() { + return (0, f16_1.decodeF16)(this.reader.u16()); + } + }; + CborDecoderBase.CborDecoderBase = CborDecoderBase$1; + + return CborDecoderBase; +} + +var hasRequiredCborDecoder; + +function requireCborDecoder () { + if (hasRequiredCborDecoder) return CborDecoder; + hasRequiredCborDecoder = 1; + Object.defineProperty(CborDecoder, "__esModule", { value: true }); + CborDecoder.CborDecoder = void 0; + const CborDecoderBase_1 = requireCborDecoderBase(); + const JsonPackValue_1 = requireJsonPackValue(); + let CborDecoder$1 = class CborDecoder extends CborDecoderBase_1.CborDecoderBase { + // -------------------------------------------------------------- Map reading + readAsMap() { + const octet = this.reader.u8(); + const major = octet >> 5; + const minor = octet & 31 /* CONST.MINOR_MASK */; + switch (major) { + case 5 /* MAJOR.MAP */: + return this.readMap(minor); + default: + throw 0 /* ERROR.UNEXPECTED_MAJOR */; + } + } + readMap(minor) { + const length = this.readMinorLen(minor); + if (length >= 0) + return this.readMapRaw(length); + else + return this.readMapIndef(); + } + readMapRaw(length) { + const map = new Map(); + for (let i = 0; i < length; i++) { + const key = this.readAny(); + const value = this.readAny(); + map.set(key, value); + } + return map; + } + readMapIndef() { + const map = new Map(); + while (this.reader.peak() !== 255 /* CONST.END */) { + const key = this.readAny(); + if (this.reader.peak() === 255 /* CONST.END */) + throw 7 /* ERROR.UNEXPECTED_OBJ_BREAK */; + const value = this.readAny(); + map.set(key, value); + } + this.reader.x++; + return map; + } + // ----------------------------------------------------------- Value skipping + skipN(n) { + for (let i = 0; i < n; i++) + this.skipAny(); + } + skipAny() { + this.skipAnyRaw(this.reader.u8()); + } + skipAnyRaw(octet) { + const major = octet >> 5; + const minor = octet & 31 /* CONST.MINOR_MASK */; + switch (major) { + case 0 /* MAJOR.UIN */: + case 1 /* MAJOR.NIN */: + this.skipUNint(minor); + break; + case 2 /* MAJOR.BIN */: + this.skipBin(minor); + break; + case 3 /* MAJOR.STR */: + this.skipStr(minor); + break; + case 4 /* MAJOR.ARR */: + this.skipArr(minor); + break; + case 5 /* MAJOR.MAP */: + this.skipObj(minor); + break; + case 7 /* MAJOR.TKN */: + this.skipTkn(minor); + break; + case 6 /* MAJOR.TAG */: + this.skipTag(minor); + break; + } + } + skipMinorLen(minor) { + if (minor <= 23) + return minor; + switch (minor) { + case 24: + return this.reader.u8(); + case 25: + return this.reader.u16(); + case 26: + return this.reader.u32(); + case 27: + return Number(this.reader.u64()); + case 31: + return -1; + default: + throw 1 /* ERROR.UNEXPECTED_MINOR */; + } + } + // --------------------------------------------------------- Integer skipping + skipUNint(minor) { + if (minor <= 23) + return; + switch (minor) { + case 24: + return this.reader.skip(1); + case 25: + return this.reader.skip(2); + case 26: + return this.reader.skip(4); + case 27: + return this.reader.skip(8); + default: + throw 1 /* ERROR.UNEXPECTED_MINOR */; + } + } + // ---------------------------------------------------------- Binary skipping + skipBin(minor) { + const length = this.skipMinorLen(minor); + if (length >= 0) + this.reader.skip(length); + else { + while (this.reader.peak() !== 255 /* CONST.END */) + this.skipBinChunk(); + this.reader.x++; + } + } + skipBinChunk() { + const octet = this.reader.u8(); + const major = octet >> 5; + const minor = octet & 31 /* CONST.MINOR_MASK */; + if (major !== 2 /* MAJOR.BIN */) + throw 2 /* ERROR.UNEXPECTED_BIN_CHUNK_MAJOR */; + if (minor > 27) + throw 3 /* ERROR.UNEXPECTED_BIN_CHUNK_MINOR */; + this.skipBin(minor); + } + // ---------------------------------------------------------- String skipping + skipStr(minor) { + const length = this.skipMinorLen(minor); + if (length >= 0) + this.reader.skip(length); + else { + while (this.reader.peak() !== 255 /* CONST.END */) + this.skipStrChunk(); + this.reader.x++; + } + } + skipStrChunk() { + const octet = this.reader.u8(); + const major = octet >> 5; + const minor = octet & 31 /* CONST.MINOR_MASK */; + if (major !== 3 /* MAJOR.STR */) + throw 4 /* ERROR.UNEXPECTED_STR_CHUNK_MAJOR */; + if (minor > 27) + throw 5 /* ERROR.UNEXPECTED_STR_CHUNK_MINOR */; + this.skipStr(minor); + } + // ----------------------------------------------------------- Array skipping + skipArr(minor) { + const length = this.skipMinorLen(minor); + if (length >= 0) + this.skipN(length); + else { + while (this.reader.peak() !== 255 /* CONST.END */) + this.skipAny(); + this.reader.x++; + } + } + // ---------------------------------------------------------- Object skipping + skipObj(minor) { + const length = this.readMinorLen(minor); + if (length >= 0) + return this.skipN(length * 2); + else { + while (this.reader.peak() !== 255 /* CONST.END */) { + this.skipAny(); + if (this.reader.peak() === 255 /* CONST.END */) + throw 7 /* ERROR.UNEXPECTED_OBJ_BREAK */; + this.skipAny(); + } + this.reader.x++; + } + } + // ------------------------------------------------------------- Tag skipping + skipTag(minor) { + const length = this.skipMinorLen(minor); + if (length < 0) + throw 1 /* ERROR.UNEXPECTED_MINOR */; + this.skipAny(); + } + // ----------------------------------------------------------- Token skipping + skipTkn(minor) { + switch (minor) { + case 0xf8 & 31 /* CONST.MINOR_MASK */: + this.reader.skip(1); + return; + case 0xf9 & 31 /* CONST.MINOR_MASK */: + this.reader.skip(2); + return; + case 0xfa & 31 /* CONST.MINOR_MASK */: + this.reader.skip(4); + return; + case 0xfb & 31 /* CONST.MINOR_MASK */: + this.reader.skip(8); + return; + } + if (minor <= 23) + return; + throw 1 /* ERROR.UNEXPECTED_MINOR */; + } + // --------------------------------------------------------------- Validation + /** + * Throws if at given offset in a buffer there is an invalid CBOR value, or + * if the value does not span the exact length specified in `size`. I.e. + * throws if: + * + * - The value is not a valid CBOR value. + * - The value is shorter than `size`. + * - The value is longer than `size`. + * + * @param value Buffer in which to validate CBOR value. + * @param offset Offset at which the value starts. + * @param size Expected size of the value. + */ + validate(value, offset = 0, size = value.length) { + this.reader.reset(value); + this.reader.x = offset; + const start = offset; + this.skipAny(); + const end = this.reader.x; + if (end - start !== size) + throw 8 /* ERROR.INVALID_SIZE */; + } + // -------------------------------------------- One level reading - any value + decodeLevel(value) { + this.reader.reset(value); + return this.readLevel(); + } + /** + * Decodes only one level of objects and arrays. Other values are decoded + * completely. + * + * @returns One level of decoded CBOR value. + */ + readLevel() { + const octet = this.reader.u8(); + const major = octet >> 5; + const minor = octet & 31 /* CONST.MINOR_MASK */; + switch (major) { + case 4 /* MAJOR.ARR */: + return this.readArrLevel(minor); + case 5 /* MAJOR.MAP */: + return this.readObjLevel(minor); + default: + return super.readAnyRaw(octet); + } + } + /** + * Decodes primitive values, returns container values as `JsonPackValue`. + * + * @returns A primitive value, or CBOR container value as a blob. + */ + readPrimitiveOrVal() { + const octet = this.reader.peak(); + const major = octet >> 5; + switch (major) { + case 4 /* MAJOR.ARR */: + case 5 /* MAJOR.MAP */: + return this.readAsValue(); + default: + return this.readAny(); + } + } + readAsValue() { + const reader = this.reader; + const start = reader.x; + this.skipAny(); + const end = reader.x; + return new JsonPackValue_1.JsonPackValue(reader.uint8.subarray(start, end)); + } + // ----------------------------------------------- One level reading - object + readObjLevel(minor) { + const length = this.readMinorLen(minor); + if (length >= 0) + return this.readObjRawLevel(length); + else + return this.readObjIndefLevel(); + } + readObjRawLevel(length) { + const obj = {}; + for (let i = 0; i < length; i++) { + const key = this.key(); + const value = this.readPrimitiveOrVal(); + obj[key] = value; + } + return obj; + } + readObjIndefLevel() { + const obj = {}; + while (this.reader.peak() !== 255 /* CONST.END */) { + const key = this.key(); + if (this.reader.peak() === 255 /* CONST.END */) + throw 7 /* ERROR.UNEXPECTED_OBJ_BREAK */; + const value = this.readPrimitiveOrVal(); + obj[key] = value; + } + this.reader.x++; + return obj; + } + // ------------------------------------------------ One level reading - array + readArrLevel(minor) { + const length = this.readMinorLen(minor); + if (length >= 0) + return this.readArrRawLevel(length); + return this.readArrIndefLevel(); + } + readArrRawLevel(length) { + const arr = []; + for (let i = 0; i < length; i++) + arr.push(this.readPrimitiveOrVal()); + return arr; + } + readArrIndefLevel() { + const arr = []; + while (this.reader.peak() !== 255 /* CONST.END */) + arr.push(this.readPrimitiveOrVal()); + this.reader.x++; + return arr; + } + // ---------------------------------------------------------- Shallow reading + readHdr(expectedMajor) { + const octet = this.reader.u8(); + const major = octet >> 5; + if (major !== expectedMajor) + throw 0 /* ERROR.UNEXPECTED_MAJOR */; + const minor = octet & 31 /* CONST.MINOR_MASK */; + if (minor < 24) + return minor; + switch (minor) { + case 24: + return this.reader.u8(); + case 25: + return this.reader.u16(); + case 26: + return this.reader.u32(); + case 27: + return Number(this.reader.u64()); + case 31: + return -1; + } + throw 1 /* ERROR.UNEXPECTED_MINOR */; + } + readStrHdr() { + return this.readHdr(3 /* MAJOR.STR */); + } + readObjHdr() { + return this.readHdr(5 /* MAJOR.MAP */); + } + readArrHdr() { + return this.readHdr(4 /* MAJOR.ARR */); + } + findKey(key) { + const size = this.readObjHdr(); + for (let i = 0; i < size; i++) { + const k = this.key(); + if (k === key) + return this; + this.skipAny(); + } + throw 9 /* ERROR.KEY_NOT_FOUND */; + } + findIndex(index) { + const size = this.readArrHdr(); + if (index >= size) + throw 10 /* ERROR.INDEX_OUT_OF_BOUNDS */; + for (let i = 0; i < index; i++) + this.skipAny(); + return this; + } + find(path) { + for (let i = 0; i < path.length; i++) { + const segment = path[i]; + if (typeof segment === 'string') + this.findKey(segment); + else + this.findIndex(segment); + } + return this; + } + }; + CborDecoder.CborDecoder = CborDecoder$1; + + return CborDecoder; +} + +var async = {}; + +var hasRequiredAsync; + +function requireAsync () { + if (hasRequiredAsync) return async; + hasRequiredAsync = 1; + (function (exports) { + Object.defineProperty(exports, "__esModule", { value: true }); + exports.fromSnapshot = exports.toSnapshot = void 0; + const shared_1 = requireShared(); + const toSnapshot = async ({ fs, path = '/', separator = '/' }) => { + const stats = await fs.lstat(path); + if (stats.isDirectory()) { + const list = await fs.readdir(path); + const entries = {}; + const dir = path.endsWith(separator) ? path : path + separator; + const snapshots = await Promise.all(list.map(child => (0, exports.toSnapshot)({ fs, path: `${dir}${child}`, separator }))); + for (let i = 0; i < list.length; i++) { + if (snapshots[i]) + entries['' + list[i]] = snapshots[i]; + } + return [0 /* SnapshotNodeType.Folder */, {}, entries]; + } + else if (stats.isFile()) { + const buf = (await fs.readFile(path)); + const uint8 = new Uint8Array(buf.buffer, buf.byteOffset, buf.byteLength); + return [1 /* SnapshotNodeType.File */, {}, uint8]; + } + else if (stats.isSymbolicLink()) { + return [ + 2 /* SnapshotNodeType.Symlink */, + { + target: (await fs.readlink(path, { encoding: 'utf8' })), + }, + ]; + } + return null; + }; + exports.toSnapshot = toSnapshot; + const fromSnapshot = async (snapshot, { fs, path = '/', separator = '/' }) => { + if (!snapshot) + return; + switch (snapshot[0]) { + case 0 /* SnapshotNodeType.Folder */: { + if (!path.endsWith(separator)) + path = path + separator; + const [, , entries] = snapshot; + await fs.mkdir(path, { recursive: true }); + for (const [name, child] of Object.entries(entries)) { + (0, shared_1.validateEntryName)(name); + await (0, exports.fromSnapshot)(child, { fs, path: `${path}${name}`, separator }); + } + break; + } + case 1 /* SnapshotNodeType.File */: { + const [, , data] = snapshot; + await fs.writeFile(path, data); + break; + } + case 2 /* SnapshotNodeType.Symlink */: { + const [, { target }] = snapshot; + await fs.symlink(target, path); + break; + } + } + }; + exports.fromSnapshot = fromSnapshot; + + } (async)); + return async; +} + +var hasRequiredBinary; + +function requireBinary () { + if (hasRequiredBinary) return binary; + hasRequiredBinary = 1; + Object.defineProperty(binary, "__esModule", { value: true }); + binary.fromBinarySnapshot = binary.toBinarySnapshot = binary.fromBinarySnapshotSync = binary.toBinarySnapshotSync = void 0; + const CborEncoder_1 = requireCborEncoder(); + const CborDecoder_1 = requireCborDecoder(); + const sync_1 = requireSync(); + const async_1 = requireAsync(); + const shared_1 = requireShared(); + const encoder = new CborEncoder_1.CborEncoder(shared_1.writer); + const decoder = new CborDecoder_1.CborDecoder(); + const toBinarySnapshotSync = (options) => { + const snapshot = (0, sync_1.toSnapshotSync)(options); + return encoder.encode(snapshot); + }; + binary.toBinarySnapshotSync = toBinarySnapshotSync; + const fromBinarySnapshotSync = (uint8, options) => { + const snapshot = decoder.decode(uint8); + (0, sync_1.fromSnapshotSync)(snapshot, options); + }; + binary.fromBinarySnapshotSync = fromBinarySnapshotSync; + const toBinarySnapshot = async (options) => { + const snapshot = await (0, async_1.toSnapshot)(options); + return encoder.encode(snapshot); + }; + binary.toBinarySnapshot = toBinarySnapshot; + const fromBinarySnapshot = async (uint8, options) => { + const snapshot = decoder.decode(uint8); + await (0, async_1.fromSnapshot)(snapshot, options); + }; + binary.fromBinarySnapshot = fromBinarySnapshot; + + return binary; +} + +var json = {}; + +var JsonEncoder = {}; + +var toBase64Bin = {}; + +var createToBase64Bin = {}; + +var constants = {}; + +var hasRequiredConstants; + +function requireConstants () { + if (hasRequiredConstants) return constants; + hasRequiredConstants = 1; + Object.defineProperty(constants, "__esModule", { value: true }); + constants.hasBuffer = constants.alphabet = void 0; + constants.alphabet = 'ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789+/'; + constants.hasBuffer = typeof Buffer === 'function' && typeof Buffer.from === 'function'; + + return constants; +} + +var hasRequiredCreateToBase64Bin; + +function requireCreateToBase64Bin () { + if (hasRequiredCreateToBase64Bin) return createToBase64Bin; + hasRequiredCreateToBase64Bin = 1; + Object.defineProperty(createToBase64Bin, "__esModule", { value: true }); + createToBase64Bin.createToBase64Bin = void 0; + const constants_1 = requireConstants(); + const createToBase64Bin$1 = (chars = constants_1.alphabet, pad = '=') => { + if (chars.length !== 64) + throw new Error('chars must be 64 characters long'); + const table = chars.split('').map((c) => c.charCodeAt(0)); + const table2 = []; + for (const c1 of table) { + for (const c2 of table) { + const two = (c1 << 8) + c2; + table2.push(two); + } + } + const doAddPadding = pad.length === 1; + const E = doAddPadding ? pad.charCodeAt(0) : 0; + const EE = doAddPadding ? (E << 8) | E : 0; + return (uint8, start, length, dest, offset) => { + const extraLength = length % 3; + const baseLength = length - extraLength; + for (; start < baseLength; start += 3) { + const o1 = uint8[start]; + const o2 = uint8[start + 1]; + const o3 = uint8[start + 2]; + const v1 = (o1 << 4) | (o2 >> 4); + const v2 = ((o2 & 0b1111) << 8) | o3; + dest.setInt32(offset, (table2[v1] << 16) + table2[v2]); + offset += 4; + } + if (extraLength === 1) { + const o1 = uint8[baseLength]; + if (doAddPadding) { + dest.setInt32(offset, (table2[o1 << 4] << 16) + EE); + offset += 4; + } + else { + dest.setInt16(offset, table2[o1 << 4]); + offset += 2; + } + } + else if (extraLength) { + const o1 = uint8[baseLength]; + const o2 = uint8[baseLength + 1]; + const v1 = (o1 << 4) | (o2 >> 4); + const v2 = (o2 & 0b1111) << 2; + if (doAddPadding) { + dest.setInt32(offset, (table2[v1] << 16) + (table[v2] << 8) + E); + offset += 4; + } + else { + dest.setInt16(offset, table2[v1]); + offset += 2; + dest.setInt8(offset, table[v2]); + offset += 1; + } + } + return offset; + }; + }; + createToBase64Bin.createToBase64Bin = createToBase64Bin$1; + + return createToBase64Bin; +} + +var hasRequiredToBase64Bin; + +function requireToBase64Bin () { + if (hasRequiredToBase64Bin) return toBase64Bin; + hasRequiredToBase64Bin = 1; + Object.defineProperty(toBase64Bin, "__esModule", { value: true }); + toBase64Bin.toBase64Bin = void 0; + const createToBase64Bin_1 = requireCreateToBase64Bin(); + toBase64Bin.toBase64Bin = (0, createToBase64Bin_1.createToBase64Bin)(); + + return toBase64Bin; +} + +var hasRequiredJsonEncoder; + +function requireJsonEncoder () { + if (hasRequiredJsonEncoder) return JsonEncoder; + hasRequiredJsonEncoder = 1; + Object.defineProperty(JsonEncoder, "__esModule", { value: true }); + JsonEncoder.JsonEncoder = void 0; + const toBase64Bin_1 = requireToBase64Bin(); + let JsonEncoder$1 = class JsonEncoder { + constructor(writer) { + this.writer = writer; + } + encode(value) { + const writer = this.writer; + writer.reset(); + this.writeAny(value); + return writer.flush(); + } + /** + * Called when the encoder encounters a value that it does not know how to encode. + * + * @param value Some JavaScript value. + */ + writeUnknown(value) { + this.writeNull(); + } + writeAny(value) { + switch (typeof value) { + case 'boolean': + return this.writeBoolean(value); + case 'number': + return this.writeNumber(value); + case 'string': + return this.writeStr(value); + case 'object': { + if (value === null) + return this.writeNull(); + const constr = value.constructor; + switch (constr) { + case Object: + return this.writeObj(value); + case Array: + return this.writeArr(value); + case Uint8Array: + return this.writeBin(value); + default: + if (value instanceof Uint8Array) + return this.writeBin(value); + if (Array.isArray(value)) + return this.writeArr(value); + return this.writeUnknown(value); + } + } + case 'undefined': { + return this.writeUndef(); + } + default: + return this.writeUnknown(value); + } + } + writeNull() { + this.writer.u32(0x6e756c6c); // null + } + writeUndef() { + const writer = this.writer; + const length = 35; + writer.ensureCapacity(length); + // Write: "data:application/cbor,base64;9w==" + const view = writer.view; + let x = writer.x; + view.setUint32(x, 577003892); // "dat + x += 4; + view.setUint32(x, 1631215984); // a:ap + x += 4; + view.setUint32(x, 1886153059); // plic + x += 4; + view.setUint32(x, 1635019119); // atio + x += 4; + view.setUint32(x, 1848599394); // n/cb + x += 4; + view.setUint32(x, 1869753442); // or,b + x += 4; + view.setUint32(x, 1634952502); // ase6 + x += 4; + view.setUint32(x, 876296567); // 4;9w + x += 4; + view.setUint16(x, 15677); // == + x += 2; + writer.uint8[x++] = 0x22; // " + writer.x = x; + } + writeBoolean(bool) { + if (bool) + this.writer.u32(0x74727565); // true + else + this.writer.u8u32(0x66, 0x616c7365); // false + } + writeNumber(num) { + const str = num.toString(); + this.writer.ascii(str); + } + writeInteger(int) { + this.writeNumber(int >> 0 === int ? int : Math.trunc(int)); + } + writeUInteger(uint) { + this.writeInteger(uint < 0 ? -uint : uint); + } + writeFloat(float) { + this.writeNumber(float); + } + writeBin(buf) { + const writer = this.writer; + const length = buf.length; + writer.ensureCapacity(38 + 3 + (length << 1)); + // Write: "data:application/octet-stream;base64, - 22 64 61 74 61 3a 61 70 70 6c 69 63 61 74 69 6f 6e 2f 6f 63 74 65 74 2d 73 74 72 65 61 6d 3b 62 61 73 65 36 34 2c + const view = writer.view; + let x = writer.x; + view.setUint32(x, 577003892); // "dat + x += 4; + view.setUint32(x, 1631215984); // a:ap + x += 4; + view.setUint32(x, 1886153059); // plic + x += 4; + view.setUint32(x, 1635019119); // atio + x += 4; + view.setUint32(x, 1848602467); // n/oc + x += 4; + view.setUint32(x, 1952805933); // tet- + x += 4; + view.setUint32(x, 1937011301); // stre + x += 4; + view.setUint32(x, 1634548578); // am;b + x += 4; + view.setUint32(x, 1634952502); // ase6 + x += 4; + view.setUint16(x, 13356); // 4, + x += 2; + x = (0, toBase64Bin_1.toBase64Bin)(buf, 0, length, view, x); + writer.uint8[x++] = 0x22; // " + writer.x = x; + } + writeStr(str) { + const writer = this.writer; + const length = str.length; + writer.ensureCapacity(length * 4 + 2); + if (length < 256) { + const startX = writer.x; + let x = startX; + const uint8 = writer.uint8; + uint8[x++] = 0x22; // " + for (let i = 0; i < length; i++) { + const code = str.charCodeAt(i); + switch (code) { + case 34: // " + case 92: // \ + uint8[x++] = 0x5c; // \ + break; + } + if (code < 32 || code > 126) { + writer.x = startX; + const jsonStr = JSON.stringify(str); + writer.ensureCapacity(jsonStr.length * 4 + 4); + writer.utf8(jsonStr); + return; + } + else + uint8[x++] = code; + } + uint8[x++] = 0x22; // " + writer.x = x; + return; + } + const jsonStr = JSON.stringify(str); + writer.ensureCapacity(jsonStr.length * 4 + 4); + writer.utf8(jsonStr); + } + writeAsciiStr(str) { + const length = str.length; + const writer = this.writer; + writer.ensureCapacity(length * 2 + 2); + const uint8 = writer.uint8; + let x = writer.x; + uint8[x++] = 0x22; // " + for (let i = 0; i < length; i++) { + const code = str.charCodeAt(i); + switch (code) { + case 34: // " + case 92: // \ + uint8[x++] = 0x5c; // \ + break; + } + uint8[x++] = code; + } + uint8[x++] = 0x22; // " + writer.x = x; + } + writeArr(arr) { + const writer = this.writer; + writer.u8(0x5b); // [ + const length = arr.length; + const last = length - 1; + for (let i = 0; i < last; i++) { + this.writeAny(arr[i]); + writer.u8(0x2c); // , + } + if (last >= 0) + this.writeAny(arr[last]); + writer.u8(0x5d); // ] + } + writeArrSeparator() { + this.writer.u8(0x2c); // , + } + writeObj(obj) { + const writer = this.writer; + const keys = Object.keys(obj); + const length = keys.length; + if (!length) + return writer.u16(0x7b7d); // {} + writer.u8(0x7b); // { + for (let i = 0; i < length; i++) { + const key = keys[i]; + const value = obj[key]; + this.writeStr(key); + writer.u8(0x3a); // : + this.writeAny(value); + writer.u8(0x2c); // , + } + writer.uint8[writer.x - 1] = 0x7d; // } + } + writeObjSeparator() { + this.writer.u8(0x2c); // , + } + writeObjKeySeparator() { + this.writer.u8(0x3a); // : + } + // ------------------------------------------------------- Streaming encoding + writeStartStr() { + throw new Error('Method not implemented.'); + } + writeStrChunk(str) { + throw new Error('Method not implemented.'); + } + writeEndStr() { + throw new Error('Method not implemented.'); + } + writeStartBin() { + throw new Error('Method not implemented.'); + } + writeBinChunk(buf) { + throw new Error('Method not implemented.'); + } + writeEndBin() { + throw new Error('Method not implemented.'); + } + writeStartArr() { + this.writer.u8(0x5b); // [ + } + writeArrChunk(item) { + throw new Error('Method not implemented.'); + } + writeEndArr() { + this.writer.u8(0x5d); // ] + } + writeStartObj() { + this.writer.u8(0x7b); // { + } + writeObjChunk(key, value) { + throw new Error('Method not implemented.'); + } + writeEndObj() { + this.writer.u8(0x7d); // } + } + }; + JsonEncoder.JsonEncoder = JsonEncoder$1; + + return JsonEncoder; +} + +var JsonDecoder = {}; + +var fromBase64Bin = {}; + +var createFromBase64Bin = {}; + +var hasRequiredCreateFromBase64Bin; + +function requireCreateFromBase64Bin () { + if (hasRequiredCreateFromBase64Bin) return createFromBase64Bin; + hasRequiredCreateFromBase64Bin = 1; + Object.defineProperty(createFromBase64Bin, "__esModule", { value: true }); + createFromBase64Bin.createFromBase64Bin = void 0; + const constants_1 = requireConstants(); + const createFromBase64Bin$1 = (chars = constants_1.alphabet, pad = '=') => { + if (chars.length !== 64) + throw new Error('chars must be 64 characters long'); + let max = 0; + for (let i = 0; i < chars.length; i++) + max = Math.max(max, chars.charCodeAt(i)); + const table = []; + for (let i = 0; i <= max; i += 1) + table[i] = -1; + for (let i = 0; i < chars.length; i++) + table[chars.charCodeAt(i)] = i; + const doExpectPadding = pad.length === 1; + const PAD = doExpectPadding ? pad.charCodeAt(0) : 0; + return (view, offset, length) => { + if (!length) + return new Uint8Array(0); + let padding = 0; + if (length % 4 !== 0) { + padding = 4 - (length % 4); + length += padding; + } + else { + const end = offset + length; + const last = end - 1; + if (view.getUint8(last) === PAD) { + padding = 1; + if (length > 1 && view.getUint8(last - 1) === PAD) + padding = 2; + } + } + if (length % 4 !== 0) + throw new Error('Base64 string length must be a multiple of 4'); + const mainEnd = offset + length - (padding ? 4 : 0); + const bufferLength = (length >> 2) * 3 - padding; + const buf = new Uint8Array(bufferLength); + let j = 0; + let i = offset; + for (; i < mainEnd; i += 4) { + const word = view.getUint32(i); + const octet0 = word >>> 24; + const octet1 = (word >>> 16) & 0xff; + const octet2 = (word >>> 8) & 0xff; + const octet3 = word & 0xff; + const sextet0 = table[octet0]; + const sextet1 = table[octet1]; + const sextet2 = table[octet2]; + const sextet3 = table[octet3]; + if (sextet0 < 0 || sextet1 < 0 || sextet2 < 0 || sextet3 < 0) + throw new Error('INVALID_BASE64_SEQ'); + buf[j] = (sextet0 << 2) | (sextet1 >> 4); + buf[j + 1] = (sextet1 << 4) | (sextet2 >> 2); + buf[j + 2] = (sextet2 << 6) | sextet3; + j += 3; + } + if (!padding) + return buf; + if (padding === 1) { + const word = view.getUint16(mainEnd); + const octet0 = word >> 8; + const octet1 = word & 0xff; + const octet2 = view.getUint8(mainEnd + 2); + const sextet0 = table[octet0]; + const sextet1 = table[octet1]; + const sextet2 = table[octet2]; + if (sextet0 < 0 || sextet1 < 0 || sextet2 < 0) + throw new Error('INVALID_BASE64_SEQ'); + buf[j] = (sextet0 << 2) | (sextet1 >> 4); + buf[j + 1] = (sextet1 << 4) | (sextet2 >> 2); + return buf; + } + const word = view.getUint16(mainEnd); + const octet0 = word >> 8; + const octet1 = word & 0xff; + const sextet0 = table[octet0]; + const sextet1 = table[octet1]; + if (sextet0 < 0 || sextet1 < 0) + throw new Error('INVALID_BASE64_SEQ'); + buf[j] = (sextet0 << 2) | (sextet1 >> 4); + return buf; + }; + }; + createFromBase64Bin.createFromBase64Bin = createFromBase64Bin$1; + + return createFromBase64Bin; +} + +var hasRequiredFromBase64Bin; + +function requireFromBase64Bin () { + if (hasRequiredFromBase64Bin) return fromBase64Bin; + hasRequiredFromBase64Bin = 1; + Object.defineProperty(fromBase64Bin, "__esModule", { value: true }); + fromBase64Bin.fromBase64Bin = void 0; + const createFromBase64Bin_1 = requireCreateFromBase64Bin(); + fromBase64Bin.fromBase64Bin = (0, createFromBase64Bin_1.createFromBase64Bin)(); + + return fromBase64Bin; +} + +var util = {}; + +var hasRequiredUtil; + +function requireUtil () { + if (hasRequiredUtil) return util; + hasRequiredUtil = 1; + Object.defineProperty(util, "__esModule", { value: true }); + util.findEndingQuote = void 0; + const findEndingQuote = (uint8, x) => { + const len = uint8.length; + let char = uint8[x]; + let prev = 0; + while (x < len) { + if (char === 34 && prev !== 92) + break; + if (char === 92 && prev === 92) + prev = 0; + else + prev = char; + char = uint8[++x]; + } + if (x === len) + throw new Error('Invalid JSON'); + return x; + }; + util.findEndingQuote = findEndingQuote; + + return util; +} + +var hasRequiredJsonDecoder; + +function requireJsonDecoder () { + if (hasRequiredJsonDecoder) return JsonDecoder; + hasRequiredJsonDecoder = 1; + (function (exports) { + Object.defineProperty(exports, "__esModule", { value: true }); + exports.JsonDecoder = exports.readKey = void 0; + const decodeUtf8_1 = requireDecodeUtf8(); + const Reader_1 = requireReader(); + const fromBase64Bin_1 = requireFromBase64Bin(); + const util_1 = requireUtil(); + const REGEX_REPLACE_ESCAPED_CHARS = /\\(b|f|n|r|t|"|\/|\\)/g; + const escapedCharReplacer = (char) => { + switch (char) { + case '\\b': + return '\b'; + case '\\f': + return '\f'; + case '\\n': + return '\n'; + case '\\r': + return '\r'; + case '\\t': + return '\t'; + case '\\"': + return '"'; + case '\\/': + return '/'; + case '\\\\': + return '\\'; + } + return char; + }; + // Starts with data:application/octet-stream;base64, - 64 61 74 61 3a 61 70 70 6c 69 63 61 74 69 6f 6e 2f 6f 63 74 65 74 2d 73 74 72 65 61 6d 3b 62 61 73 65 36 34 2c + const hasBinaryPrefix = (u8, x) => u8[x] === 0x64 && + u8[x + 1] === 0x61 && + u8[x + 2] === 0x74 && + u8[x + 3] === 0x61 && + u8[x + 4] === 0x3a && + u8[x + 5] === 0x61 && + u8[x + 6] === 0x70 && + u8[x + 7] === 0x70 && + u8[x + 8] === 0x6c && + u8[x + 9] === 0x69 && + u8[x + 10] === 0x63 && + u8[x + 11] === 0x61 && + u8[x + 12] === 0x74 && + u8[x + 13] === 0x69 && + u8[x + 14] === 0x6f && + u8[x + 15] === 0x6e && + u8[x + 16] === 0x2f && + u8[x + 17] === 0x6f && + u8[x + 18] === 0x63 && + u8[x + 19] === 0x74 && + u8[x + 20] === 0x65 && + u8[x + 21] === 0x74 && + u8[x + 22] === 0x2d && + u8[x + 23] === 0x73 && + u8[x + 24] === 0x74 && + u8[x + 25] === 0x72 && + u8[x + 26] === 0x65 && + u8[x + 27] === 0x61 && + u8[x + 28] === 0x6d && + u8[x + 29] === 0x3b && + u8[x + 30] === 0x62 && + u8[x + 31] === 0x61 && + u8[x + 32] === 0x73 && + u8[x + 33] === 0x65 && + u8[x + 34] === 0x36 && + u8[x + 35] === 0x34 && + u8[x + 36] === 0x2c; + // Matches "data:application/cbor,base64;9w==" + const isUndefined = (u8, x) => + // u8[x++] === 0x22 && // " + // u8[x++] === 0x64 && // d + u8[x++] === 0x61 && // a + u8[x++] === 0x74 && // t + u8[x++] === 0x61 && // a + u8[x++] === 0x3a && // : + u8[x++] === 0x61 && // a + u8[x++] === 0x70 && // p + u8[x++] === 0x70 && // p + u8[x++] === 0x6c && // l + u8[x++] === 0x69 && // i + u8[x++] === 0x63 && // c + u8[x++] === 0x61 && // a + u8[x++] === 0x74 && // t + u8[x++] === 0x69 && // i + u8[x++] === 0x6f && // o + u8[x++] === 0x6e && // n + u8[x++] === 0x2f && // / + u8[x++] === 0x63 && // c + u8[x++] === 0x62 && // b + u8[x++] === 0x6f && // o + u8[x++] === 0x72 && // r + u8[x++] === 0x2c && // , + u8[x++] === 0x62 && // b + u8[x++] === 0x61 && // a + u8[x++] === 0x73 && // s + u8[x++] === 0x65 && // e + u8[x++] === 0x36 && // 6 + u8[x++] === 0x34 && // 4 + u8[x++] === 0x3b && // ; + u8[x++] === 0x39 && // 9 + u8[x++] === 0x77 && // w + u8[x++] === 0x3d && // = + u8[x++] === 0x3d && // = + u8[x++] === 0x22; // " + const fromCharCode = String.fromCharCode; + const readKey = (reader) => { + const buf = reader.uint8; + const len = buf.length; + const points = []; + let x = reader.x; + let prev = 0; + while (x < len) { + let code = buf[x++]; + if ((code & 0x80) === 0) { + if (prev === 92) { + switch (code) { + case 98: // \b + code = 8; + break; + case 102: // \f + code = 12; + break; + case 110: // \n + code = 10; + break; + case 114: // \r + code = 13; + break; + case 116: // \t + code = 9; + break; + case 34: // \" + code = 34; + break; + case 47: // \/ + code = 47; + break; + case 92: // \\ + code = 92; + break; + default: + throw new Error('Invalid JSON'); + } + prev = 0; + } + else { + if (code === 34) + break; + prev = code; + if (prev === 92) + continue; + } + } + else { + const octet2 = buf[x++] & 0x3f; + if ((code & 0xe0) === 0xc0) { + code = ((code & 0x1f) << 6) | octet2; + } + else { + const octet3 = buf[x++] & 0x3f; + if ((code & 0xf0) === 0xe0) { + code = ((code & 0x1f) << 12) | (octet2 << 6) | octet3; + } + else { + if ((code & 0xf8) === 0xf0) { + const octet4 = buf[x++] & 0x3f; + let unit = ((code & 0x07) << 0x12) | (octet2 << 0x0c) | (octet3 << 0x06) | octet4; + if (unit > 0xffff) { + unit -= 0x10000; + const unit0 = ((unit >>> 10) & 0x3ff) | 0xd800; + unit = 0xdc00 | (unit & 0x3ff); + points.push(unit0); + code = unit; + } + else { + code = unit; + } + } + } + } + } + points.push(code); + } + reader.x = x; + return fromCharCode.apply(String, points); + }; + exports.readKey = readKey; + class JsonDecoder { + constructor() { + this.reader = new Reader_1.Reader(); + } + read(uint8) { + this.reader.reset(uint8); + return this.readAny(); + } + decode(uint8) { + this.reader.reset(uint8); + return this.readAny(); + } + readAny() { + this.skipWhitespace(); + const reader = this.reader; + const x = reader.x; + const uint8 = reader.uint8; + const char = uint8[x]; + switch (char) { + case 34 /* " */: { + if (uint8[x + 1] === 0x64 /* d */) { + const bin = this.tryReadBin(); + if (bin) + return bin; + if (isUndefined(uint8, x + 2)) { + reader.x = x + 35; + return undefined; + } + } + return this.readStr(); + } + case 91 /* [ */: + return this.readArr(); + case 102 /* f */: + return this.readFalse(); + case 110 /* n */: + return this.readNull(); + case 116 /* t */: + return this.readTrue(); + case 123 /* { */: + return this.readObj(); + default: + if ((char >= 48 /* 0 */ && char <= 57) /* 9 */ || char === 45 /* - */) + return this.readNum(); + throw new Error('Invalid JSON'); + } + } + skipWhitespace() { + const reader = this.reader; + const uint8 = reader.uint8; + let x = reader.x; + let char = 0; + while (true) { + char = uint8[x]; + switch (char) { + case 32 /* */: + case 9 /* */: + case 10 /* */: + case 13 /* */: + x++; + continue; + default: + reader.x = x; + return; + } + } + } + readNull() { + if (this.reader.u32() !== 0x6e756c6c /* null */) + throw new Error('Invalid JSON'); + return null; + } + readTrue() { + if (this.reader.u32() !== 0x74727565 /* true */) + throw new Error('Invalid JSON'); + return true; + } + readFalse() { + const reader = this.reader; + if (reader.u8() !== 0x66 /* f */ || reader.u32() !== 0x616c7365 /* alse */) + throw new Error('Invalid JSON'); + return false; + } + readBool() { + const reader = this.reader; + switch (reader.uint8[reader.x]) { + case 102 /* f */: + return this.readFalse(); + case 116 /* t */: + return this.readTrue(); + default: + throw new Error('Invalid JSON'); + } + } + readNum() { + const reader = this.reader; + const uint8 = reader.uint8; + let x = reader.x; + let c = uint8[x++]; + const c1 = c; + c = uint8[x++]; + if (!c || ((c < 45 || c > 57) && c !== 43 && c !== 69 && c !== 101)) { + reader.x = x - 1; + const num = +fromCharCode(c1); + if (num !== num) + throw new Error('Invalid JSON'); + return num; + } + const c2 = c; + c = uint8[x++]; + if (!c || ((c < 45 || c > 57) && c !== 43 && c !== 69 && c !== 101)) { + reader.x = x - 1; + const num = +fromCharCode(c1, c2); + if (num !== num) + throw new Error('Invalid JSON'); + return num; + } + const c3 = c; + c = uint8[x++]; + if (!c || ((c < 45 || c > 57) && c !== 43 && c !== 69 && c !== 101)) { + reader.x = x - 1; + const num = +fromCharCode(c1, c2, c3); + if (num !== num) + throw new Error('Invalid JSON'); + return num; + } + const c4 = c; + c = uint8[x++]; + if (!c || ((c < 45 || c > 57) && c !== 43 && c !== 69 && c !== 101)) { + reader.x = x - 1; + const num = +fromCharCode(c1, c2, c3, c4); + if (num !== num) + throw new Error('Invalid JSON'); + return num; + } + const c5 = c; + c = uint8[x++]; + if (!c || ((c < 45 || c > 57) && c !== 43 && c !== 69 && c !== 101)) { + reader.x = x - 1; + const num = +fromCharCode(c1, c2, c3, c4, c5); + if (num !== num) + throw new Error('Invalid JSON'); + return num; + } + const c6 = c; + c = uint8[x++]; + if (!c || ((c < 45 || c > 57) && c !== 43 && c !== 69 && c !== 101)) { + reader.x = x - 1; + const num = +fromCharCode(c1, c2, c3, c4, c5, c6); + if (num !== num) + throw new Error('Invalid JSON'); + return num; + } + const c7 = c; + c = uint8[x++]; + if (!c || ((c < 45 || c > 57) && c !== 43 && c !== 69 && c !== 101)) { + reader.x = x - 1; + const num = +fromCharCode(c1, c2, c3, c4, c5, c6, c7); + if (num !== num) + throw new Error('Invalid JSON'); + return num; + } + const c8 = c; + c = uint8[x++]; + if (!c || ((c < 45 || c > 57) && c !== 43 && c !== 69 && c !== 101)) { + reader.x = x - 1; + const num = +fromCharCode(c1, c2, c3, c4, c5, c6, c7, c8); + if (num !== num) + throw new Error('Invalid JSON'); + return num; + } + const c9 = c; + c = uint8[x++]; + if (!c || ((c < 45 || c > 57) && c !== 43 && c !== 69 && c !== 101)) { + reader.x = x - 1; + const num = +fromCharCode(c1, c2, c3, c4, c5, c6, c7, c8, c9); + if (num !== num) + throw new Error('Invalid JSON'); + return num; + } + const c10 = c; + c = uint8[x++]; + if (!c || ((c < 45 || c > 57) && c !== 43 && c !== 69 && c !== 101)) { + reader.x = x - 1; + const num = +fromCharCode(c1, c2, c3, c4, c5, c6, c7, c8, c9, c10); + if (num !== num) + throw new Error('Invalid JSON'); + return num; + } + const c11 = c; + c = uint8[x++]; + if (!c || ((c < 45 || c > 57) && c !== 43 && c !== 69 && c !== 101)) { + reader.x = x - 1; + const num = +fromCharCode(c1, c2, c3, c4, c5, c6, c7, c8, c9, c10, c11); + if (num !== num) + throw new Error('Invalid JSON'); + return num; + } + const c12 = c; + c = uint8[x++]; + if (!c || ((c < 45 || c > 57) && c !== 43 && c !== 69 && c !== 101)) { + reader.x = x - 1; + const num = +fromCharCode(c1, c2, c3, c4, c5, c6, c7, c8, c9, c10, c11, c12); + if (num !== num) + throw new Error('Invalid JSON'); + return num; + } + const c13 = c; + c = uint8[x++]; + if (!c || ((c < 45 || c > 57) && c !== 43 && c !== 69 && c !== 101)) { + reader.x = x - 1; + const num = +fromCharCode(c1, c2, c3, c4, c5, c6, c7, c8, c9, c10, c11, c12, c13); + if (num !== num) + throw new Error('Invalid JSON'); + return num; + } + const c14 = c; + c = uint8[x++]; + if (!c || ((c < 45 || c > 57) && c !== 43 && c !== 69 && c !== 101)) { + reader.x = x - 1; + const num = +fromCharCode(c1, c2, c3, c4, c5, c6, c7, c8, c9, c10, c11, c12, c13, c14); + if (num !== num) + throw new Error('Invalid JSON'); + return num; + } + const c15 = c; + c = uint8[x++]; + if (!c || ((c < 45 || c > 57) && c !== 43 && c !== 69 && c !== 101)) { + reader.x = x - 1; + const num = +fromCharCode(c1, c2, c3, c4, c5, c6, c7, c8, c9, c10, c11, c12, c13, c14, c15); + if (num !== num) + throw new Error('Invalid JSON'); + return num; + } + const c16 = c; + c = uint8[x++]; + if (!c || ((c < 45 || c > 57) && c !== 43 && c !== 69 && c !== 101)) { + reader.x = x - 1; + const num = +fromCharCode(c1, c2, c3, c4, c5, c6, c7, c8, c9, c10, c11, c12, c13, c14, c15, c16); + if (num !== num) + throw new Error('Invalid JSON'); + return num; + } + const c17 = c; + c = uint8[x++]; + if (!c || ((c < 45 || c > 57) && c !== 43 && c !== 69 && c !== 101)) { + reader.x = x - 1; + const num = +fromCharCode(c1, c2, c3, c4, c5, c6, c7, c8, c9, c10, c11, c12, c13, c14, c15, c16, c17); + if (num !== num) + throw new Error('Invalid JSON'); + return num; + } + const c18 = c; + c = uint8[x++]; + if (!c || ((c < 45 || c > 57) && c !== 43 && c !== 69 && c !== 101)) { + reader.x = x - 1; + const num = +fromCharCode(c1, c2, c3, c4, c5, c6, c7, c8, c9, c10, c11, c12, c13, c14, c15, c16, c17, c18); + if (num !== num) + throw new Error('Invalid JSON'); + return num; + } + const c19 = c; + c = uint8[x++]; + if (!c || ((c < 45 || c > 57) && c !== 43 && c !== 69 && c !== 101)) { + reader.x = x - 1; + const num = +fromCharCode(c1, c2, c3, c4, c5, c6, c7, c8, c9, c10, c11, c12, c13, c14, c15, c16, c17, c18, c19); + if (num !== num) + throw new Error('Invalid JSON'); + return num; + } + const c20 = c; + c = uint8[x++]; + if (!c || ((c < 45 || c > 57) && c !== 43 && c !== 69 && c !== 101)) { + reader.x = x - 1; + const num = +fromCharCode(c1, c2, c3, c4, c5, c6, c7, c8, c9, c10, c11, c12, c13, c14, c15, c16, c17, c18, c19, c20); + if (num !== num) + throw new Error('Invalid JSON'); + return num; + } + const c21 = c; + c = uint8[x++]; + if (!c || ((c < 45 || c > 57) && c !== 43 && c !== 69 && c !== 101)) { + reader.x = x - 1; + const num = +fromCharCode(c1, c2, c3, c4, c5, c6, c7, c8, c9, c10, c11, c12, c13, c14, c15, c16, c17, c18, c19, c20, c21); + if (num !== num) + throw new Error('Invalid JSON'); + return num; + } + const c22 = c; + c = uint8[x++]; + if (!c || ((c < 45 || c > 57) && c !== 43 && c !== 69 && c !== 101)) { + reader.x = x - 1; + const num = +fromCharCode(c1, c2, c3, c4, c5, c6, c7, c8, c9, c10, c11, c12, c13, c14, c15, c16, c17, c18, c19, c20, c21, c22); + if (num !== num) + throw new Error('Invalid JSON'); + return num; + } + const c23 = c; + c = uint8[x++]; + if (!c || ((c < 45 || c > 57) && c !== 43 && c !== 69 && c !== 101)) { + reader.x = x - 1; + const num = +fromCharCode(c1, c2, c3, c4, c5, c6, c7, c8, c9, c10, c11, c12, c13, c14, c15, c16, c17, c18, c19, c20, c21, c22, c23); + if (num !== num) + throw new Error('Invalid JSON'); + return num; + } + const c24 = c; + c = uint8[x++]; + if (!c || ((c < 45 || c > 57) && c !== 43 && c !== 69 && c !== 101)) { + reader.x = x - 1; + const num = +fromCharCode(c1, c2, c3, c4, c5, c6, c7, c8, c9, c10, c11, c12, c13, c14, c15, c16, c17, c18, c19, c20, c21, c22, c23, c24); + if (num !== num) + throw new Error('Invalid JSON'); + return num; + } + throw new Error('Invalid JSON'); + } + readStr() { + const reader = this.reader; + const uint8 = reader.uint8; + const char = uint8[reader.x++]; + if (char !== 0x22) + throw new Error('Invalid JSON'); + const x0 = reader.x; + const x1 = (0, util_1.findEndingQuote)(uint8, x0); + let str = (0, decodeUtf8_1.decodeUtf8)(uint8, x0, x1 - x0); + /** @todo perf: maybe faster is to first check if there are any escaped chars. */ + str = str.replace(REGEX_REPLACE_ESCAPED_CHARS, escapedCharReplacer); + reader.x = x1 + 1; + return str; + } + tryReadBin() { + const reader = this.reader; + const u8 = reader.uint8; + let x = reader.x; + if (u8[x++] !== 0x22) + return undefined; + const hasDataUrlPrefix = hasBinaryPrefix(u8, x); + if (!hasDataUrlPrefix) + return undefined; + x += 37; + const x0 = x; + x = (0, util_1.findEndingQuote)(u8, x); + reader.x = x0; + const bin = (0, fromBase64Bin_1.fromBase64Bin)(reader.view, x0, x - x0); + reader.x = x + 1; + return bin; + } + readBin() { + const reader = this.reader; + const u8 = reader.uint8; + let x = reader.x; + if (u8[x++] !== 0x22) + throw new Error('Invalid JSON'); + const hasDataUrlPrefix = hasBinaryPrefix(u8, x); + if (!hasDataUrlPrefix) + throw new Error('Invalid JSON'); + x += 37; + const x0 = x; + x = (0, util_1.findEndingQuote)(u8, x); + reader.x = x0; + const bin = (0, fromBase64Bin_1.fromBase64Bin)(reader.view, x0, x - x0); + reader.x = x + 1; + return bin; + } + readArr() { + const reader = this.reader; + if (reader.u8() !== 0x5b /* [ */) + throw new Error('Invalid JSON'); + const arr = []; + const uint8 = reader.uint8; + let first = true; + while (true) { + this.skipWhitespace(); + const char = uint8[reader.x]; + if (char === 0x5d /* ] */) + return reader.x++, arr; + if (char === 0x2c /* , */) + reader.x++; + else if (!first) + throw new Error('Invalid JSON'); + this.skipWhitespace(); + arr.push(this.readAny()); + first = false; + } + } + readObj() { + const reader = this.reader; + if (reader.u8() !== 0x7b /* { */) + throw new Error('Invalid JSON'); + const obj = {}; + const uint8 = reader.uint8; + let first = true; + while (true) { + this.skipWhitespace(); + let char = uint8[reader.x]; + if (char === 0x7d /* } */) + return reader.x++, obj; + if (char === 0x2c /* , */) + reader.x++; + else if (!first) + throw new Error('Invalid JSON'); + this.skipWhitespace(); + char = uint8[reader.x++]; + if (char !== 0x22 /* " */) + throw new Error('Invalid JSON'); + const key = (0, exports.readKey)(reader); + if (key === '__proto__') + throw new Error('Invalid JSON'); + this.skipWhitespace(); + if (reader.u8() !== 0x3a /* : */) + throw new Error('Invalid JSON'); + this.skipWhitespace(); + obj[key] = this.readAny(); + first = false; + } + } + } + exports.JsonDecoder = JsonDecoder; + + } (JsonDecoder)); + return JsonDecoder; +} + +var hasRequiredJson; + +function requireJson () { + if (hasRequiredJson) return json; + hasRequiredJson = 1; + Object.defineProperty(json, "__esModule", { value: true }); + json.fromJsonSnapshot = json.toJsonSnapshot = json.fromJsonSnapshotSync = json.toJsonSnapshotSync = void 0; + const JsonEncoder_1 = requireJsonEncoder(); + const JsonDecoder_1 = requireJsonDecoder(); + const sync_1 = requireSync(); + const async_1 = requireAsync(); + const shared_1 = requireShared(); + const encoder = new JsonEncoder_1.JsonEncoder(shared_1.writer); + const decoder = new JsonDecoder_1.JsonDecoder(); + const toJsonSnapshotSync = (options) => { + const snapshot = (0, sync_1.toSnapshotSync)(options); + return encoder.encode(snapshot); + }; + json.toJsonSnapshotSync = toJsonSnapshotSync; + const fromJsonSnapshotSync = (uint8, options) => { + const snapshot = decoder.read(uint8); + (0, sync_1.fromSnapshotSync)(snapshot, options); + }; + json.fromJsonSnapshotSync = fromJsonSnapshotSync; + const toJsonSnapshot = async (options) => { + const snapshot = await (0, async_1.toSnapshot)(options); + return encoder.encode(snapshot); + }; + json.toJsonSnapshot = toJsonSnapshot; + const fromJsonSnapshot = async (uint8, options) => { + const snapshot = decoder.read(uint8); + await (0, async_1.fromSnapshot)(snapshot, options); + }; + json.fromJsonSnapshot = fromJsonSnapshot; + + return json; +} + +var hasRequiredLib$2; + +function requireLib$2 () { + if (hasRequiredLib$2) return lib; + hasRequiredLib$2 = 1; + (function (exports) { + Object.defineProperty(exports, "__esModule", { value: true }); + const tslib_1 = require$$0$2; + tslib_1.__exportStar(requireConstants$1(), exports); + tslib_1.__exportStar(requireSync(), exports); + tslib_1.__exportStar(requireBinary(), exports); + tslib_1.__exportStar(requireJson(), exports); + + } (lib)); + return lib; +} + +var options = {}; + +var hasRequiredOptions; + +function requireOptions () { + if (hasRequiredOptions) return options; + hasRequiredOptions = 1; + (function (exports) { + Object.defineProperty(exports, "__esModule", { value: true }); + exports.getWriteFileOptions = exports.writeFileDefaults = exports.getRealpathOptsAndCb = exports.getRealpathOptions = exports.getStatfsOptsAndCb = exports.getStatfsOptions = exports.getStatOptsAndCb = exports.getStatOptions = exports.getAppendFileOptsAndCb = exports.getAppendFileOpts = exports.getOpendirOptsAndCb = exports.getOpendirOptions = exports.getReaddirOptsAndCb = exports.getReaddirOptions = exports.getReadFileOptions = exports.getRmOptsAndCb = exports.getRmdirOptions = exports.getDefaultOptsAndCb = exports.getDefaultOpts = exports.optsDefaults = exports.getMkdirOptions = void 0; + exports.getOptions = getOptions; + exports.optsGenerator = optsGenerator; + exports.optsAndCbGenerator = optsAndCbGenerator; + const fs_node_utils_1 = requireLib$7(); + const util_1 = requireUtil$1(); + const mkdirDefaults = { + mode: 511 /* MODE.DIR */, + recursive: false, + }; + const getMkdirOptions = (options) => { + if (typeof options === 'number') + return Object.assign({}, mkdirDefaults, { mode: options }); + return Object.assign({}, mkdirDefaults, options); + }; + exports.getMkdirOptions = getMkdirOptions; + const ERRSTR_OPTS = tipeof => `Expected options to be either an object or a string, but got ${tipeof} instead`; + function getOptions(defaults, options) { + let opts; + if (!options) + return defaults; + else { + const tipeof = typeof options; + switch (tipeof) { + case 'string': + opts = Object.assign({}, defaults, { encoding: options }); + break; + case 'object': + opts = Object.assign({}, defaults, options); + break; + default: + throw TypeError(ERRSTR_OPTS(tipeof)); + } + } + if (opts.encoding !== 'buffer') + (0, fs_node_utils_1.assertEncoding)(opts.encoding); + return opts; + } + function optsGenerator(defaults) { + return options => getOptions(defaults, options); + } + function optsAndCbGenerator(getOpts) { + return (options, callback) => typeof options === 'function' ? [getOpts(), options] : [getOpts(options), (0, util_1.validateCallback)(callback)]; + } + exports.optsDefaults = { + encoding: 'utf8', + }; + exports.getDefaultOpts = optsGenerator(exports.optsDefaults); + exports.getDefaultOptsAndCb = optsAndCbGenerator(exports.getDefaultOpts); + const rmdirDefaults = { + recursive: false, + }; + const getRmdirOptions = (options) => { + return Object.assign({}, rmdirDefaults, options); + }; + exports.getRmdirOptions = getRmdirOptions; + const getRmOpts = optsGenerator(exports.optsDefaults); + exports.getRmOptsAndCb = optsAndCbGenerator(getRmOpts); + const readFileOptsDefaults = { + flag: 'r', + }; + exports.getReadFileOptions = optsGenerator(readFileOptsDefaults); + const readdirDefaults = { + encoding: 'utf8', + recursive: false, + withFileTypes: false, + }; + exports.getReaddirOptions = optsGenerator(readdirDefaults); + exports.getReaddirOptsAndCb = optsAndCbGenerator(exports.getReaddirOptions); + const opendirDefaults = { + encoding: 'utf8', + bufferSize: 32, + recursive: false, + }; + exports.getOpendirOptions = optsGenerator(opendirDefaults); + exports.getOpendirOptsAndCb = optsAndCbGenerator(exports.getOpendirOptions); + const appendFileDefaults = { + encoding: 'utf8', + mode: 438 /* MODE.DEFAULT */, + flag: fs_node_utils_1.FLAGS[fs_node_utils_1.FLAGS.a], + }; + exports.getAppendFileOpts = optsGenerator(appendFileDefaults); + exports.getAppendFileOptsAndCb = optsAndCbGenerator(exports.getAppendFileOpts); + const statDefaults = { + bigint: false, + }; + const getStatOptions = (options = {}) => Object.assign({}, statDefaults, options); + exports.getStatOptions = getStatOptions; + const getStatOptsAndCb = (options, callback) => typeof options === 'function' ? [(0, exports.getStatOptions)(), options] : [(0, exports.getStatOptions)(options), (0, util_1.validateCallback)(callback)]; + exports.getStatOptsAndCb = getStatOptsAndCb; + const statfsDefaults = { + bigint: false, + }; + const getStatfsOptions = (options = {}) => Object.assign({}, statfsDefaults, options); + exports.getStatfsOptions = getStatfsOptions; + const getStatfsOptsAndCb = (options, callback) => typeof options === 'function' + ? [(0, exports.getStatfsOptions)(), options] + : [(0, exports.getStatfsOptions)(options), (0, util_1.validateCallback)(callback)]; + exports.getStatfsOptsAndCb = getStatfsOptsAndCb; + const realpathDefaults = exports.optsDefaults; + exports.getRealpathOptions = optsGenerator(realpathDefaults); + exports.getRealpathOptsAndCb = optsAndCbGenerator(exports.getRealpathOptions); + exports.writeFileDefaults = { + encoding: 'utf8', + mode: 438 /* MODE.DEFAULT */, + flag: fs_node_utils_1.FLAGS[fs_node_utils_1.FLAGS.w], + }; + exports.getWriteFileOptions = optsGenerator(exports.writeFileDefaults); + + } (options)); + return options; +} + +var Dir = {}; + +var hasRequiredDir; + +function requireDir () { + if (hasRequiredDir) return Dir; + hasRequiredDir = 1; + Object.defineProperty(Dir, "__esModule", { value: true }); + Dir.Dir = void 0; + const util_1 = requireUtil$1(); + const Dirent_1 = requireDirent(); + const errors = requireErrors$1(); + /** + * A directory stream, like `fs.Dir`. + */ + let Dir$1 = class Dir { + constructor(link, options) { + this.link = link; + this.options = options; + this.iteratorInfo = []; + this.closed = false; + this.operationQueue = null; + this.path = link.getPath(); + this.iteratorInfo.push(link.children[Symbol.iterator]()); + } + closeBase() { + // In a real filesystem implementation, this would close file descriptors + // For memfs, we just need to mark as closed + } + readBase(iteratorInfo) { + let done; + let value; + let name; + let link; + do { + do { + ({ done, value } = iteratorInfo[iteratorInfo.length - 1].next()); + if (!done) { + [name, link] = value; + } + else { + break; + } + } while (name === '.' || name === '..'); + if (done) { + iteratorInfo.pop(); + if (iteratorInfo.length === 0) { + break; + } + else { + done = false; + } + } + else { + if (this.options.recursive && link.children.size) { + iteratorInfo.push(link.children[Symbol.iterator]()); + } + return Dirent_1.default.build(link, this.options.encoding); + } + } while (!done); + return null; + } + close(callback) { + // Promise-based close + if (callback === undefined) { + if (this.closed) { + return Promise.reject(new errors.Error('ERR_DIR_CLOSED')); + } + return new Promise((resolve, reject) => { + this.close(err => { + if (err) + reject(err); + else + resolve(); + }); + }); + } + // Callback-based close + (0, util_1.validateCallback)(callback); + if (this.closed) { + process$1.nextTick(callback, new errors.Error('ERR_DIR_CLOSED')); + return; + } + if (this.operationQueue !== null) { + this.operationQueue.push(() => { + this.close(callback); + }); + return; + } + this.closed = true; + try { + this.closeBase(); + process$1.nextTick(callback); + } + catch (err) { + process$1.nextTick(callback, err); + } + } + closeSync() { + if (this.closed) { + throw new errors.Error('ERR_DIR_CLOSED'); + } + if (this.operationQueue !== null) { + throw new errors.Error('ERR_DIR_CONCURRENT_OPERATION'); + } + this.closed = true; + this.closeBase(); + } + read(callback) { + // Promise-based read + if (callback === undefined) { + return new Promise((resolve, reject) => { + this.read((err, result) => { + if (err) + reject(err); + else + resolve(result ?? null); + }); + }); + } + // Callback-based read + (0, util_1.validateCallback)(callback); + if (this.closed) { + process$1.nextTick(callback, new errors.Error('ERR_DIR_CLOSED')); + return; + } + if (this.operationQueue !== null) { + this.operationQueue.push(() => { + this.read(callback); + }); + return; + } + this.operationQueue = []; + try { + const result = this.readBase(this.iteratorInfo); + process$1.nextTick(() => { + const queue = this.operationQueue; + this.operationQueue = null; + for (const op of queue) + op(); + callback(null, result); + }); + } + catch (err) { + process$1.nextTick(() => { + const queue = this.operationQueue; + this.operationQueue = null; + for (const op of queue) + op(); + callback(err); + }); + } + } + readSync() { + if (this.closed) { + throw new errors.Error('ERR_DIR_CLOSED'); + } + if (this.operationQueue !== null) { + throw new errors.Error('ERR_DIR_CONCURRENT_OPERATION'); + } + return this.readBase(this.iteratorInfo); + } + [Symbol.asyncIterator]() { + return { + next: async () => { + try { + const dirEnt = await this.read(); + if (dirEnt !== null) { + return { done: false, value: dirEnt }; + } + else { + return { done: true, value: undefined }; + } + } + catch (err) { + throw err; + } + }, + [Symbol.asyncIterator]() { + return this; + }, + }; + } + [Symbol.asyncDispose]() { + return this.close(); + } + [Symbol.dispose]() { + this.closeSync(); + } + }; + Dir.Dir = Dir$1; + + return Dir; +} + +var glob = {}; + +var hasRequiredGlob; + +function requireGlob () { + if (hasRequiredGlob) return glob; + hasRequiredGlob = 1; + Object.defineProperty(glob, "__esModule", { value: true }); + glob.globSync = globSync; + const path_1 = requirePath$1(); + const glob_to_regex_js_1 = requireLib$8(); + const util_1 = requireUtil$1(); + const pathJoin = path_1.posix.join; + const pathRelative = path_1.posix.relative; + const pathResolve = path_1.posix.resolve; + /** + * Check if a path matches a glob pattern + */ + function matchesPattern(path, pattern) { + const regex = (0, glob_to_regex_js_1.toRegex)(pattern); + return regex.test(path); + } + /** + * Check if a path should be excluded based on exclude patterns + */ + function isExcluded(path, exclude) { + if (!exclude) + return false; + if (typeof exclude === 'function') { + return exclude(path); + } + const patterns = Array.isArray(exclude) ? exclude : [exclude]; + return patterns.some(pattern => matchesPattern(path, pattern)); + } + /** + * Walk directory tree and collect matching paths + */ + function walkDirectory(fs, dir, patterns, options, currentDepth = 0) { + const results = []; + const maxDepth = options.maxdepth ?? Infinity; + const baseCwd = options.cwd ? (0, util_1.pathToFilename)(options.cwd) : process$1.cwd(); + if (currentDepth > maxDepth) { + return results; + } + try { + const entries = fs.readdirSync(dir, { withFileTypes: true }); + for (const entry of entries) { + const fullPath = pathJoin(dir, entry.name.toString()); + const relativePath = pathRelative(baseCwd, fullPath); + // Skip if excluded + if (isExcluded(relativePath, options.exclude)) { + continue; + } + // Check if this path matches any pattern + const matches = patterns.some(pattern => matchesPattern(relativePath, pattern)); + if (matches) { + results.push(relativePath); + } + // Recurse into directories + if (entry.isDirectory() && currentDepth < maxDepth) { + const subResults = walkDirectory(fs, fullPath, patterns, options, currentDepth + 1); + results.push(...subResults); + } + } + } + catch (err) { + // Skip directories we can't read + } + return results; + } + /** + * Main glob implementation + */ + function globSync(fs, pattern, options = {}) { + const cwd = options.cwd ? (0, util_1.pathToFilename)(options.cwd) : process$1.cwd(); + const resolvedCwd = pathResolve(cwd); + const globOptions = { + cwd: resolvedCwd, + exclude: options.exclude, + maxdepth: options.maxdepth, + withFileTypes: options.withFileTypes || false, + }; + let results = []; + // Handle absolute patterns + if (path_1.posix.isAbsolute(pattern)) { + const dir = path_1.posix.dirname(pattern); + const patternBasename = path_1.posix.basename(pattern); + const dirResults = walkDirectory(fs, dir, [patternBasename], { ...globOptions, cwd: dir }); + results.push(...dirResults.map(r => path_1.posix.resolve(dir, r))); + } + else { + // Handle relative patterns - normalize by stripping leading './' + const normalizedPattern = pattern.replace(/^\.\//, ''); + const dirResults = walkDirectory(fs, resolvedCwd, [normalizedPattern], globOptions); + results.push(...dirResults); + } + // Remove duplicates and sort + results = [...new Set(results)].sort(); + return results; + } + + return glob; +} + +var hasRequiredVolume; + +function requireVolume () { + if (hasRequiredVolume) return volume; + hasRequiredVolume = 1; + Object.defineProperty(volume, "__esModule", { value: true }); + volume.FSWatcher = volume.StatWatcher = volume.Volume = void 0; + volume.pathToSteps = pathToSteps; + volume.dataToStr = dataToStr; + volume.toUnixTimestamp = toUnixTimestamp; + const path_1 = requirePath$1(); + const fs_core_1 = requireLib$5(); + const util_1 = requireUtil$3(); + const Stats_1 = requireStats(); + const Dirent_1 = requireDirent(); + const StatFs_1 = requireStatFs(); + const buffer_1 = requireBuffer(); + const setTimeoutUnref_1 = requireSetTimeoutUnref(); + const stream_1 = requireStream(); + const fs_node_utils_1 = requireLib$7(); + const events_1 = requireEvents(); + const FileHandle_1 = requireFileHandle(); + const util_2 = requireUtil$4(); + const FsPromises_1 = requireFsPromises(); + const fs_print_1 = requireLib$3(); + const fsSnapshot = requireLib$2(); + const fs_node_utils_2 = requireLib$7(); + const errors = requireErrors$1(); + const options_1 = requireOptions(); + const util_3 = requireUtil$1(); + const Dir_1 = requireDir(); + const resolveCrossPlatform = path_1.resolve; + const { O_SYMLINK, F_OK, R_OK, W_OK, X_OK, COPYFILE_EXCL, COPYFILE_FICLONE_FORCE } = fs_node_utils_1.constants; + const pathSep = path_1.posix ? path_1.posix.sep : path_1.sep; + const pathRelative = path_1.posix ? path_1.posix.relative : path_1.relative; + const pathJoin = path_1.posix ? path_1.posix.join : path_1.join; + const pathDirname = path_1.posix ? path_1.posix.dirname : path_1.dirname; + const pathNormalize = path_1.posix ? path_1.posix.normalize : path_1.normalize; + // ------------------------------------------------------------------ Constants + const kMinPoolSpace = 128; + // ---------------------------------------------------------- Utility functions + function pathToSteps(path) { + return (0, fs_core_1.filenameToSteps)((0, util_3.pathToFilename)(path)); + } + function dataToStr(data, encoding = fs_node_utils_1.ENCODING_UTF8) { + if (buffer_1.Buffer.isBuffer(data)) + return data.toString(encoding); + else if (data instanceof Uint8Array) + return (0, buffer_1.bufferFrom)(data).toString(encoding); + else + return String(data); + } + // converts Date or number to a fractional UNIX timestamp + function toUnixTimestamp(time) { + // tslint:disable-next-line triple-equals + if (typeof time === 'string' && +time == time) { + return +time; + } + if (time instanceof Date) { + return time.getTime() / 1000; + } + if (isFinite(time)) { + if (time < 0) { + return Date.now() / 1000; + } + return time; + } + throw new Error('Cannot parse time: ' + time); + } + function validateUid(uid) { + if (typeof uid !== 'number') + throw TypeError(fs_node_utils_2.ERRSTR.UID); + } + function validateGid(gid) { + if (typeof gid !== 'number') + throw TypeError(fs_node_utils_2.ERRSTR.GID); + } + /** + * `Volume` represents a file system. + */ + class Volume { + get promises() { + if (this.promisesApi === null) + throw new Error('Promise is not supported in this environment.'); + return this.promisesApi; + } + constructor(_core = new fs_core_1.Superblock()) { + this._core = _core; + this.promisesApi = new FsPromises_1.FsPromises(this, FileHandle_1.FileHandle); + this.openSync = (path, flags, mode = 438 /* MODE.DEFAULT */) => { + // Validate (1) mode; (2) path; (3) flags - in that order. + const modeNum = (0, util_3.modeToNumber)(mode); + const fileName = (0, util_3.pathToFilename)(path); + const flagsNum = (0, util_3.flagsToNumber)(flags); + return this._core.open(fileName, flagsNum, modeNum, !(flagsNum & O_SYMLINK)); + }; + this.open = (path, flags, a, b) => { + let mode = a; + let callback = b; + if (typeof a === 'function') { + mode = 438 /* MODE.DEFAULT */; + callback = a; + } + mode = mode || 438 /* MODE.DEFAULT */; + const modeNum = (0, util_3.modeToNumber)(mode); + const fileName = (0, util_3.pathToFilename)(path); + const flagsNum = (0, util_3.flagsToNumber)(flags); + this.wrapAsync(this._core.open, [fileName, flagsNum, modeNum, !(flagsNum & O_SYMLINK)], callback); + }; + this.closeSync = (fd) => { + this._core.close(fd); + }; + this.close = (fd, callback) => { + (0, fs_core_1.validateFd)(fd); + const file = this._core.getFileByFdOrThrow(fd, 'close'); + this.wrapAsync(this._core.close, [file.fd], callback); + }; + this.readSync = (fd, buffer, offset, length, position) => { + (0, fs_core_1.validateFd)(fd); + return this._core.read(fd, buffer, offset, length, position); + }; + this.read = (fd, buffer, offset, length, position, callback) => { + (0, util_3.validateCallback)(callback); + if (length === 0) { + // This `if` branch is from Node.js + return queueMicrotask(() => { + if (callback) + callback(null, 0, buffer); + }); + } + Promise.resolve().then(() => { + try { + const bytes = this._core.read(fd, buffer, offset, length, position); + callback(null, bytes, buffer); + } + catch (err) { + callback(err); + } + }); + }; + this.readv = (fd, buffers, a, b) => { + let position = a; + let callback = b; + if (typeof a === 'function') + [position, callback] = [null, a]; + (0, util_3.validateCallback)(callback); + Promise.resolve().then(() => { + try { + const bytes = this._core.readv(fd, buffers, position); + callback(null, bytes, buffers); + } + catch (err) { + callback(err); + } + }); + }; + this.readvSync = (fd, buffers, position) => { + (0, fs_core_1.validateFd)(fd); + return this._core.readv(fd, buffers, position ?? null); + }; + this._readfile = (id, flagsNum, encoding) => { + let result; + const isUserFd = typeof id === 'number'; + const userOwnsFd = isUserFd && (0, fs_core_1.isFd)(id); + let fd; + if (userOwnsFd) + fd = id; + else { + const filename = (0, util_3.pathToFilename)(id); + // Check if original path had trailing slash (indicates directory intent) + const originalPath = String(id); + const hasTrailingSlash = originalPath.length > 1 && originalPath.endsWith('/'); + const link = this._core.getResolvedLinkOrThrow(filename, 'open'); + const node = link.getNode(); + if (node.isDirectory()) + throw (0, util_3.createError)("EISDIR" /* ERROR_CODE.EISDIR */, 'open', link.getPath()); + // If path had trailing slash but resolved to a file, throw ENOTDIR + if (hasTrailingSlash && node.isFile()) { + throw (0, util_3.createError)("ENOTDIR" /* ERROR_CODE.ENOTDIR */, 'open', originalPath); + } + fd = this.openSync(id, flagsNum); + } + try { + result = (0, util_3.bufferToEncoding)(this._core.getFileByFdOrThrow(fd).getBuffer(), encoding); + } + finally { + if (!userOwnsFd) { + this.closeSync(fd); + } + } + return result; + }; + this.readFileSync = (file, options) => { + const opts = (0, options_1.getReadFileOptions)(options); + const flagsNum = (0, util_3.flagsToNumber)(opts.flag); + return this._readfile(file, flagsNum, opts.encoding); + }; + this.readFile = (id, a, b) => { + const [opts, callback] = (0, options_1.optsAndCbGenerator)(options_1.getReadFileOptions)(a, b); + const flagsNum = (0, util_3.flagsToNumber)(opts.flag); + this.wrapAsync(this._readfile, [id, flagsNum, opts.encoding], callback); + }; + this.writeSync = (fd, a, b, c, d) => { + const [, buf, offset, length, position] = (0, util_3.getWriteSyncArgs)(fd, a, b, c, d); + return this._write(fd, buf, offset, length, position); + }; + this.write = (fd, a, b, c, d, e) => { + const [, asStr, buf, offset, length, position, cb] = (0, util_3.getWriteArgs)(fd, a, b, c, d, e); + Promise.resolve().then(() => { + try { + const bytes = this._write(fd, buf, offset, length, position); + if (!asStr) { + cb(null, bytes, buf); + } + else { + cb(null, bytes, a); + } + } + catch (err) { + cb(err); + } + }); + }; + this.writev = (fd, buffers, a, b) => { + let position = a; + let callback = b; + if (typeof a === 'function') + [position, callback] = [null, a]; + (0, util_3.validateCallback)(callback); + Promise.resolve().then(() => { + try { + const bytes = this.writevBase(fd, buffers, position); + callback(null, bytes, buffers); + } + catch (err) { + callback(err); + } + }); + }; + this.writevSync = (fd, buffers, position) => { + (0, fs_core_1.validateFd)(fd); + return this.writevBase(fd, buffers, position ?? null); + }; + this.writeFileSync = (id, data, options) => { + const opts = (0, options_1.getWriteFileOptions)(options); + const flagsNum = (0, util_3.flagsToNumber)(opts.flag); + const modeNum = (0, util_3.modeToNumber)(opts.mode); + const buf = (0, fs_core_1.dataToBuffer)(data, opts.encoding); + this._core.writeFile(id, buf, flagsNum, modeNum); + }; + this.writeFile = (id, data, a, b) => { + let options = a; + let callback = b; + if (typeof a === 'function') + [options, callback] = [options_1.writeFileDefaults, a]; + const cb = (0, util_3.validateCallback)(callback); + const opts = (0, options_1.getWriteFileOptions)(options); + const flagsNum = (0, util_3.flagsToNumber)(opts.flag); + const modeNum = (0, util_3.modeToNumber)(opts.mode); + const buf = (0, fs_core_1.dataToBuffer)(data, opts.encoding); + this.wrapAsync(this._core.writeFile, [id, buf, flagsNum, modeNum], cb); + }; + this.copyFileSync = (src, dest, flags) => { + const srcFilename = (0, util_3.pathToFilename)(src); + const destFilename = (0, util_3.pathToFilename)(dest); + return this._copyFile(srcFilename, destFilename, (flags || 0) | 0); + }; + this.copyFile = (src, dest, a, b) => { + const srcFilename = (0, util_3.pathToFilename)(src); + const destFilename = (0, util_3.pathToFilename)(dest); + let flags; + let callback; + if (typeof a === 'function') + [flags, callback] = [0, a]; + else + [flags, callback] = [a, b]; + (0, util_3.validateCallback)(callback); + this.wrapAsync(this._copyFile, [srcFilename, destFilename, flags], callback); + }; + this._cp = (src, dest, options) => { + if (options.filter && !options.filter(src, dest)) + return; + const srcStat = options.dereference ? this.statSync(src) : this.lstatSync(src); + let destStat = null; + try { + destStat = this.lstatSync(dest); + } + catch (err) { + if (err.code !== 'ENOENT') { + throw err; + } + } + // Check if src and dest are the same (both exist and have same inode) + if (destStat && srcStat.ino === destStat.ino && srcStat.dev === destStat.dev) + throw (0, util_3.createError)("EINVAL" /* ERROR_CODE.EINVAL */, 'cp', src, dest); + // Check type compatibility + if (destStat) { + if (srcStat.isDirectory() && !destStat.isDirectory()) + throw (0, util_3.createError)("EISDIR" /* ERROR_CODE.EISDIR */, 'cp', src, dest); + if (!srcStat.isDirectory() && destStat.isDirectory()) + throw (0, util_3.createError)("ENOTDIR" /* ERROR_CODE.ENOTDIR */, 'cp', src, dest); + } + // Check if trying to copy directory to subdirectory of itself + if (srcStat.isDirectory() && this.isSrcSubdir(src, dest)) + throw (0, util_3.createError)("EINVAL" /* ERROR_CODE.EINVAL */, 'cp', src, dest); + { + const parent = pathDirname(dest); + if (!this.existsSync(parent)) + this.mkdirSync(parent, { recursive: true }); + } + // Handle different file types + if (srcStat.isDirectory()) { + if (!options.recursive) + throw (0, util_3.createError)("EISDIR" /* ERROR_CODE.EISDIR */, 'cp', src); + this.cpDirSync(srcStat, destStat, src, dest, options); + } + else if (srcStat.isFile() || srcStat.isCharacterDevice() || srcStat.isBlockDevice()) { + this.cpFileSync(srcStat, destStat, src, dest, options); + } + else if (srcStat.isSymbolicLink() && !options.dereference) { + // Only handle as symlink if not dereferencing + this.cpSymlinkSync(destStat, src, dest, options); + } + else { + throw (0, util_3.createError)("EINVAL" /* ERROR_CODE.EINVAL */, 'cp', src); + } + }; + this.linkSync = (existingPath, newPath) => { + const existingPathFilename = (0, util_3.pathToFilename)(existingPath); + const newPathFilename = (0, util_3.pathToFilename)(newPath); + this._core.link(existingPathFilename, newPathFilename); + }; + this.link = (existingPath, newPath, callback) => { + const existingPathFilename = (0, util_3.pathToFilename)(existingPath); + const newPathFilename = (0, util_3.pathToFilename)(newPath); + this.wrapAsync(this._core.link, [existingPathFilename, newPathFilename], callback); + }; + this.unlinkSync = (path) => { + const filename = (0, util_3.pathToFilename)(path); + this._core.unlink(filename); + }; + this.unlink = (path, callback) => { + const filename = (0, util_3.pathToFilename)(path); + this.wrapAsync(this._core.unlink, [filename], callback); + }; + /** + * `type` argument works only on Windows. + * @param target + * @param path + * @param type + */ + this.symlinkSync = (target, path, type) => { + const targetFilename = (0, util_3.pathToFilename)(target); + const pathFilename = (0, util_3.pathToFilename)(path); + this._core.symlink(targetFilename, pathFilename); + }; + this.symlink = (target, path, a, b) => { + const callback = (0, util_3.validateCallback)(typeof a === 'function' ? a : b); + const targetFilename = (0, util_3.pathToFilename)(target); + const pathFilename = (0, util_3.pathToFilename)(path); + this.wrapAsync(this._core.symlink, [targetFilename, pathFilename], callback); + }; + this._lstat = (filename, bigint = false, throwIfNoEntry = false) => { + let link; + try { + link = this._core.getLinkOrThrow(filename, 'lstat'); + } + catch (err) { + if (err.code === "ENOENT" /* ERROR_CODE.ENOENT */ && !throwIfNoEntry) + return undefined; + else + throw err; + } + return Stats_1.default.build(link.getNode(), bigint); + }; + this.lstatSync = (path, options) => { + const { throwIfNoEntry = true, bigint = false } = (0, options_1.getStatOptions)(options); + return this._lstat((0, util_3.pathToFilename)(path), bigint, throwIfNoEntry); + }; + this.renameSync = (oldPath, newPath) => { + const oldPathFilename = (0, util_3.pathToFilename)(oldPath); + const newPathFilename = (0, util_3.pathToFilename)(newPath); + this._core.rename(oldPathFilename, newPathFilename); + }; + this.rename = (oldPath, newPath, callback) => { + const oldPathFilename = (0, util_3.pathToFilename)(oldPath); + const newPathFilename = (0, util_3.pathToFilename)(newPath); + this.wrapAsync(this._core.rename, [oldPathFilename, newPathFilename], callback); + }; + this.existsSync = (path) => { + try { + return this._exists((0, util_3.pathToFilename)(path)).ok; + } + catch (err) { + return false; + } + }; + this.exists = (path, callback) => { + const filename = (0, util_3.pathToFilename)(path); + if (typeof callback !== 'function') + throw Error(fs_node_utils_2.ERRSTR.CB); + Promise.resolve().then(() => { + try { + callback(this._exists(filename).ok); + } + catch (err) { + callback(false); + } + }); + }; + this.accessSync = (path, mode = F_OK) => { + const filename = (0, util_3.pathToFilename)(path); + mode = mode | 0; + this._access(filename, mode); + }; + this.access = (path, a, b) => { + let mode = F_OK; + let callback; + if (typeof a !== 'function') + [mode, callback] = [a | 0, (0, util_3.validateCallback)(b)]; + else + callback = a; + const filename = (0, util_3.pathToFilename)(path); + this.wrapAsync(this._access, [filename, mode], callback); + }; + this.appendFileSync = (id, data, options) => { + const opts = (0, options_1.getAppendFileOpts)(options); + // Force append behavior when using a supplied file descriptor. + if (!opts.flag || (0, fs_core_1.isFd)(id)) + opts.flag = 'a'; + this.writeFileSync(id, data, opts); + }; + this.appendFile = (id, data, a, b) => { + const [opts, callback] = (0, options_1.getAppendFileOptsAndCb)(a, b); + // Force append behavior when using a supplied file descriptor. + if (!opts.flag || (0, fs_core_1.isFd)(id)) + opts.flag = 'a'; + this.writeFile(id, data, opts, callback); + }; + this._readdir = (filename, options) => { + (0, fs_core_1.filenameToSteps)(filename); + const link = this._core.getResolvedLinkOrThrow(filename, 'scandir'); + const node = link.getNode(); + if (!node.isDirectory()) + throw (0, util_3.createError)("ENOTDIR" /* ERROR_CODE.ENOTDIR */, 'scandir', filename); + // Check we have permissions + if (!node.canRead()) + throw (0, util_3.createError)("EACCES" /* ERROR_CODE.EACCES */, 'scandir', filename); + const list = []; // output list + for (const name of link.children.keys()) { + const child = link.getChild(name); + if (!child || name === '.' || name === '..') + continue; + list.push(Dirent_1.default.build(child, options.encoding)); + // recursion + if (options.recursive && child.children.size) { + const recurseOptions = { ...options, recursive: true, withFileTypes: true }; + const childList = this._readdir(child.getPath(), recurseOptions); + list.push(...childList); + } + } + if (!util_1.isWin && options.encoding !== 'buffer') + list.sort((a, b) => { + if (a.name < b.name) + return -1; + if (a.name > b.name) + return 1; + return 0; + }); + if (options.withFileTypes) + return list; + let filename2 = filename; + if (util_1.isWin) + filename2 = filename2.replace(/\\/g, '/'); + return list.map(dirent => { + if (options.recursive) { + let fullPath = pathJoin(dirent.parentPath, dirent.name.toString()); + if (util_1.isWin) { + fullPath = fullPath.replace(/\\/g, '/'); + } + return fullPath.replace(filename2 + path_1.posix.sep, ''); + } + return dirent.name; + }); + }; + this.readdirSync = (path, options) => { + const opts = (0, options_1.getReaddirOptions)(options); + const filename = (0, util_3.pathToFilename)(path); + return this._readdir(filename, opts); + }; + this.readdir = (path, a, b) => { + const [options, callback] = (0, options_1.getReaddirOptsAndCb)(a, b); + const filename = (0, util_3.pathToFilename)(path); + this.wrapAsync(this._readdir, [filename, options], callback); + }; + this._readlink = (filename, encoding) => { + const link = this._core.getLinkOrThrow(filename, 'readlink'); + const node = link.getNode(); + if (!node.isSymlink()) + throw (0, util_3.createError)("EINVAL" /* ERROR_CODE.EINVAL */, 'readlink', filename); + return (0, fs_node_utils_1.strToEncoding)(node.symlink, encoding); + }; + this.readlinkSync = (path, options) => { + const opts = (0, options_1.getDefaultOpts)(options); + const filename = (0, util_3.pathToFilename)(path); + return this._readlink(filename, opts.encoding); + }; + this.readlink = (path, a, b) => { + const [opts, callback] = (0, options_1.getDefaultOptsAndCb)(a, b); + const filename = (0, util_3.pathToFilename)(path); + this.wrapAsync(this._readlink, [filename, opts.encoding], callback); + }; + this._fsync = (fd) => { + this._core.getFileByFdOrThrow(fd, 'fsync'); + }; + this.fsyncSync = (fd) => { + this._fsync(fd); + }; + this.fsync = (fd, callback) => { + this.wrapAsync(this._fsync, [fd], callback); + }; + this._fdatasync = (fd) => { + this._core.getFileByFdOrThrow(fd, 'fdatasync'); + }; + this.fdatasyncSync = (fd) => { + this._fdatasync(fd); + }; + this.fdatasync = (fd, callback) => { + this.wrapAsync(this._fdatasync, [fd], callback); + }; + this._ftruncate = (fd, len) => { + this._core.ftruncate(fd, len); + }; + this.ftruncateSync = (fd, len) => { + this._ftruncate(fd, len); + }; + this.ftruncate = (fd, a, b) => { + const len = typeof a === 'number' ? a : 0; + const callback = (0, util_3.validateCallback)(typeof a === 'number' ? b : a); + this.wrapAsync(this._ftruncate, [fd, len], callback); + }; + this._truncate = (path, len) => { + const fd = this.openSync(path, 'r+'); + try { + this.ftruncateSync(fd, len); + } + finally { + this.closeSync(fd); + } + }; + /** + * `id` should be a file descriptor or a path. `id` as file descriptor will + * not be supported soon. + */ + this.truncateSync = (id, len) => { + if ((0, fs_core_1.isFd)(id)) + return this.ftruncateSync(id, len); + this._truncate(id, len); + }; + this.truncate = (id, a, b) => { + const len = typeof a === 'number' ? a : 0; + const callback = (0, util_3.validateCallback)(typeof a === 'number' ? b : a); + if ((0, fs_core_1.isFd)(id)) + return this.ftruncate(id, len, callback); + this.wrapAsync(this._truncate, [id, len], callback); + }; + this._futimes = (fd, atime, mtime) => { + this._core.futimes(fd, atime, mtime); + }; + this.futimesSync = (fd, atime, mtime) => { + this._futimes(fd, toUnixTimestamp(atime), toUnixTimestamp(mtime)); + }; + this.futimes = (fd, atime, mtime, callback) => { + this.wrapAsync(this._futimes, [fd, toUnixTimestamp(atime), toUnixTimestamp(mtime)], callback); + }; + this._utimes = (filename, atime, mtime, followSymlinks = true) => { + this._core.utimes(filename, atime, mtime, followSymlinks); + }; + this.utimesSync = (path, atime, mtime) => { + this._utimes((0, util_3.pathToFilename)(path), toUnixTimestamp(atime), toUnixTimestamp(mtime), true); + }; + this.utimes = (path, atime, mtime, callback) => { + this.wrapAsync(this._utimes, [(0, util_3.pathToFilename)(path), toUnixTimestamp(atime), toUnixTimestamp(mtime), true], callback); + }; + this.lutimesSync = (path, atime, mtime) => { + this._utimes((0, util_3.pathToFilename)(path), toUnixTimestamp(atime), toUnixTimestamp(mtime), false); + }; + this.lutimes = (path, atime, mtime, callback) => { + this.wrapAsync(this._utimes, [(0, util_3.pathToFilename)(path), toUnixTimestamp(atime), toUnixTimestamp(mtime), false], callback); + }; + this.mkdirSync = (path, options) => { + const opts = (0, options_1.getMkdirOptions)(options); + const modeNum = (0, util_3.modeToNumber)(opts.mode, 0o777); + const filename = (0, util_3.pathToFilename)(path); + if (opts.recursive) + return this._core.mkdirp(filename, modeNum); + this._core.mkdir(filename, modeNum); + }; + this.mkdir = (path, a, b) => { + const opts = (0, options_1.getMkdirOptions)(a); + const callback = (0, util_3.validateCallback)(typeof a === 'function' ? a : b); + const modeNum = (0, util_3.modeToNumber)(opts.mode, 0o777); + const filename = (0, util_3.pathToFilename)(path); + if (opts.recursive) + this.wrapAsync(this._core.mkdirp, [filename, modeNum], callback); + else + this.wrapAsync(this._core.mkdir, [filename, modeNum], callback); + }; + this._mkdtemp = (prefix, encoding, retry = 5) => { + const filename = prefix + (0, util_3.genRndStr6)(); + try { + this._core.mkdir(filename, 511 /* MODE.DIR */); + return (0, fs_node_utils_1.strToEncoding)(filename, encoding); + } + catch (err) { + if (err.code === "EEXIST" /* ERROR_CODE.EEXIST */) { + if (retry > 1) + return this._mkdtemp(prefix, encoding, retry - 1); + else + throw Error('Could not create temp dir.'); + } + else + throw err; + } + }; + this.mkdtempSync = (prefix, options) => { + const { encoding } = (0, options_1.getDefaultOpts)(options); + if (!prefix || typeof prefix !== 'string') + throw new TypeError('filename prefix is required'); + (0, util_3.nullCheck)(prefix); + return this._mkdtemp(prefix, encoding); + }; + this.mkdtemp = (prefix, a, b) => { + const [{ encoding }, callback] = (0, options_1.getDefaultOptsAndCb)(a, b); + if (!prefix || typeof prefix !== 'string') + throw new TypeError('filename prefix is required'); + if (!(0, util_3.nullCheck)(prefix)) + return; + this.wrapAsync(this._mkdtemp, [prefix, encoding], callback); + }; + this.rmdirSync = (path, options) => { + const opts = (0, options_1.getRmdirOptions)(options); + this._core.rmdir((0, util_3.pathToFilename)(path), opts.recursive); + }; + this.rmdir = (path, a, b) => { + const opts = (0, options_1.getRmdirOptions)(a); + const callback = (0, util_3.validateCallback)(typeof a === 'function' ? a : b); + this.wrapAsync(this._core.rmdir, [(0, util_3.pathToFilename)(path), opts.recursive], callback); + }; + this.rmSync = (path, options) => { + this._core.rm((0, util_3.pathToFilename)(path), options?.force, options?.recursive); + }; + this.rm = (path, a, b) => { + const [opts, callback] = (0, options_1.getRmOptsAndCb)(a, b); + this.wrapAsync(this._core.rm, [(0, util_3.pathToFilename)(path), opts?.force, opts?.recursive], callback); + }; + this._fchmod = (fd, modeNum) => { + this._core.fchmod(fd, modeNum); + }; + this.fchmodSync = (fd, mode) => { + this._fchmod(fd, (0, util_3.modeToNumber)(mode)); + }; + this.fchmod = (fd, mode, callback) => { + this.wrapAsync(this._fchmod, [fd, (0, util_3.modeToNumber)(mode)], callback); + }; + this._chmod = (filename, modeNum, followSymlinks = true) => { + if (followSymlinks) { + this._core.chmod(filename, modeNum); + } + else { + this._core.lchmod(filename, modeNum); + } + }; + this.chmodSync = (path, mode) => { + const modeNum = (0, util_3.modeToNumber)(mode); + const filename = (0, util_3.pathToFilename)(path); + this._chmod(filename, modeNum, true); + }; + this.chmod = (path, mode, callback) => { + const modeNum = (0, util_3.modeToNumber)(mode); + const filename = (0, util_3.pathToFilename)(path); + this.wrapAsync(this._chmod, [filename, modeNum], callback); + }; + this._lchmod = (filename, modeNum) => { + this._core.lchmod(filename, modeNum); + }; + this.lchmodSync = (path, mode) => { + const modeNum = (0, util_3.modeToNumber)(mode); + const filename = (0, util_3.pathToFilename)(path); + this._lchmod(filename, modeNum); + }; + this.lchmod = (path, mode, callback) => { + const modeNum = (0, util_3.modeToNumber)(mode); + const filename = (0, util_3.pathToFilename)(path); + this.wrapAsync(this._lchmod, [filename, modeNum], callback); + }; + this._fchown = (fd, uid, gid) => { + this._core.fchown(fd, uid, gid); + }; + this.fchownSync = (fd, uid, gid) => { + validateUid(uid); + validateGid(gid); + this._fchown(fd, uid, gid); + }; + this.fchown = (fd, uid, gid, callback) => { + validateUid(uid); + validateGid(gid); + this.wrapAsync(this._fchown, [fd, uid, gid], callback); + }; + this._chown = (filename, uid, gid) => { + this._core.chown(filename, uid, gid); + }; + this.chownSync = (path, uid, gid) => { + validateUid(uid); + validateGid(gid); + this._chown((0, util_3.pathToFilename)(path), uid, gid); + }; + this.chown = (path, uid, gid, callback) => { + validateUid(uid); + validateGid(gid); + this.wrapAsync(this._chown, [(0, util_3.pathToFilename)(path), uid, gid], callback); + }; + this._lchown = (filename, uid, gid) => { + this._core.lchown(filename, uid, gid); + }; + this.lchownSync = (path, uid, gid) => { + validateUid(uid); + validateGid(gid); + this._lchown((0, util_3.pathToFilename)(path), uid, gid); + }; + this.lchown = (path, uid, gid, callback) => { + validateUid(uid); + validateGid(gid); + this.wrapAsync(this._lchown, [(0, util_3.pathToFilename)(path), uid, gid], callback); + }; + this.statWatchers = {}; + this.cpSync = (src, dest, options) => { + const srcFilename = (0, util_3.pathToFilename)(src); + const destFilename = (0, util_3.pathToFilename)(dest); + const opts_ = { + dereference: options?.dereference ?? false, + errorOnExist: options?.errorOnExist ?? false, + filter: options?.filter, + force: options?.force ?? true, + mode: options?.mode ?? 0, + preserveTimestamps: options?.preserveTimestamps ?? false, + recursive: options?.recursive ?? false, + verbatimSymlinks: options?.verbatimSymlinks ?? false, + }; + return this._cp(srcFilename, destFilename, opts_); + }; + this.cp = (src, dest, a, b) => { + const srcFilename = (0, util_3.pathToFilename)(src); + const destFilename = (0, util_3.pathToFilename)(dest); + let options; + let callback; + if (typeof a === 'function') + [options, callback] = [{}, a]; + else + [options, callback] = [a || {}, b]; + (0, util_3.validateCallback)(callback); + const opts_ = { + dereference: options?.dereference ?? false, + errorOnExist: options?.errorOnExist ?? false, + filter: options?.filter, + force: options?.force ?? true, + mode: options?.mode ?? 0, + preserveTimestamps: options?.preserveTimestamps ?? false, + recursive: options?.recursive ?? false, + verbatimSymlinks: options?.verbatimSymlinks ?? false, + }; + this.wrapAsync(this._cp, [srcFilename, destFilename, opts_], callback); + }; + this.openAsBlob = async (path, options) => { + const filename = (0, util_3.pathToFilename)(path); + let link; + try { + link = this._core.getResolvedLinkOrThrow(filename, 'open'); + } + catch (error) { + // Convert ENOENT to Node.js-compatible error for openAsBlob + if (error && typeof error === 'object' && error.code === 'ENOENT') { + const nodeError = new errors.TypeError('ERR_INVALID_ARG_VALUE'); + throw nodeError; + } + throw error; + } + const node = link.getNode(); + // Note: Node.js allows opening directories as blobs, so we don't throw EISDIR + const buffer = node.getBuffer(); + const type = options?.type || ''; + return new Blob([buffer], { type }); + }; + this.glob = (pattern, ...args) => { + const [options, callback] = args.length === 1 ? [{}, args[0]] : [args[0], args[1]]; + this.wrapAsync(this._globSync, [pattern, options || {}], callback); + }; + this.globSync = (pattern, options = {}) => { + return this._globSync(pattern, options); + }; + this._globSync = (pattern, options = {}) => { + const { globSync } = requireGlob(); + return globSync(this, pattern, options); + }; + this._opendir = (filename, options) => { + const link = this._core.getResolvedLinkOrThrow(filename, 'scandir'); + const node = link.getNode(); + if (!node.isDirectory()) + throw (0, util_3.createError)("ENOTDIR" /* ERROR_CODE.ENOTDIR */, 'scandir', filename); + return new Dir_1.Dir(link, options); + }; + this.opendirSync = (path, options) => { + const opts = (0, options_1.getOpendirOptions)(options); + const filename = (0, util_3.pathToFilename)(path); + return this._opendir(filename, opts); + }; + this.opendir = (path, a, b) => { + const [options, callback] = (0, options_1.getOpendirOptsAndCb)(a, b); + const filename = (0, util_3.pathToFilename)(path); + this.wrapAsync(this._opendir, [filename, options], callback); + }; + const self = this; // tslint:disable-line no-this-assignment + this.StatWatcher = class extends StatWatcher { + constructor() { + super(self); + } + }; + const _ReadStream = FsReadStream; + this.ReadStream = class extends _ReadStream { + constructor(...args) { + super(self, ...args); + } + }; + const _WriteStream = FsWriteStream; + this.WriteStream = class extends _WriteStream { + constructor(...args) { + super(self, ...args); + } + }; + this.FSWatcher = class extends FSWatcher { + constructor() { + super(self); + } + }; + const _realpath = (filename, encoding) => { + const realLink = this._core.getResolvedLinkOrThrow(filename, 'realpath'); + return (0, fs_node_utils_1.strToEncoding)(realLink.getPath() || '/', encoding); + }; + const realpathImpl = (path, a, b) => { + const [opts, callback] = (0, options_1.getRealpathOptsAndCb)(a, b); + const pathFilename = (0, util_3.pathToFilename)(path); + self.wrapAsync(_realpath, [pathFilename, opts.encoding], callback); + }; + const realpathSyncImpl = (path, options) => _realpath((0, util_3.pathToFilename)(path), (0, options_1.getRealpathOptions)(options).encoding); + this.realpath = realpathImpl; + this.realpath.native = realpathImpl; + this.realpathSync = realpathSyncImpl; + this.realpathSync.native = realpathSyncImpl; + } + wrapAsync(method, args, callback) { + (0, util_3.validateCallback)(callback); + Promise.resolve().then(() => { + let result; + try { + result = method.apply(this, args); + } + catch (err) { + callback(err); + return; + } + callback(null, result); + }); + } + reset() { + this._core.reset(); + } + toJSON(paths, json = {}, isRelative = false, asBuffer = false) { + return this._core.toJSON(paths, json, isRelative, asBuffer); + } + fromJSON(json, cwd) { + return this._core.fromJSON(json, cwd); + } + fromNestedJSON(json, cwd) { + return this._core.fromNestedJSON(json, cwd); + } + // Legacy interface + mountSync(mountpoint, json) { + this._core.fromJSON(json, mountpoint); + } + _write(fd, buf, offset, length, position) { + return this._core.write(fd, buf, offset, length, position); + } + writevBase(fd, buffers, position) { + this._core.getFileByFdOrThrow(fd); + let p = position ?? undefined; + if (p === -1) { + p = undefined; + } + let bytesWritten = 0; + for (const buffer of buffers) { + const nodeBuf = buffer_1.Buffer.from(buffer.buffer, buffer.byteOffset, buffer.byteLength); + const bytes = this._core.write(fd, nodeBuf, 0, nodeBuf.byteLength, p ?? null); + p = undefined; + bytesWritten += bytes; + if (bytes < nodeBuf.byteLength) + break; + } + return bytesWritten; + } + _copyFile(src, dest, flags) { + const buf = this.readFileSync(src); + if (flags & COPYFILE_EXCL && this.existsSync(dest)) + throw (0, util_3.createError)("EEXIST" /* ERROR_CODE.EEXIST */, 'copyFile', src, dest); + if (flags & COPYFILE_FICLONE_FORCE) + throw (0, util_3.createError)("ENOSYS" /* ERROR_CODE.ENOSYS */, 'copyFile', src, dest); + this._core.writeFile(dest, buf, fs_node_utils_2.FLAGS.w, 438 /* MODE.DEFAULT */); + } + isSrcSubdir(src, dest) { + try { + const normalizedSrc = pathNormalize(src.startsWith('/') ? src : '/' + src); + const normalizedDest = pathNormalize(dest.startsWith('/') ? dest : '/' + dest); + if (normalizedSrc === normalizedDest) + return true; + // Check if dest is under src by using relative path + // If dest is under src, the relative path from src to dest won't start with '..' + const relativePath = pathRelative(normalizedSrc, normalizedDest); + // If relative path is empty or doesn't start with '..', dest is under src + return relativePath === '' || (!relativePath.startsWith('..') && !(0, path_1.isAbsolute)(relativePath)); + } + catch (error) { + // If path operations fail, assume it's safe (don't block the copy) + return false; + } + } + cpFileSync(srcStat, destStat, src, dest, options) { + if (destStat) { + if (options.errorOnExist) + throw (0, util_3.createError)("EEXIST" /* ERROR_CODE.EEXIST */, 'cp', dest); + if (!options.force) + return; + this.unlinkSync(dest); + } + // Copy the file + this.copyFileSync(src, dest, options.mode); + // Preserve timestamps if requested + if (options.preserveTimestamps) + this.utimesSync(dest, srcStat.atime, srcStat.mtime); + // Set file mode + this.chmodSync(dest, Number(srcStat.mode)); + } + cpDirSync(srcStat, destStat, src, dest, options) { + if (!destStat) { + this.mkdirSync(dest); + } + // Read directory contents + const entries = this.readdirSync(src); + for (const entry of entries) { + const srcItem = pathJoin(src, String(entry)); + const destItem = pathJoin(dest, String(entry)); + // Apply filter to each item + if (options.filter && !options.filter(srcItem, destItem)) { + continue; + } + this._cp(srcItem, destItem, options); + } + // Set directory mode + this.chmodSync(dest, Number(srcStat.mode)); + } + cpSymlinkSync(destStat, src, dest, options) { + let linkTarget = String(this.readlinkSync(src)); + if (!options.verbatimSymlinks && !(0, path_1.isAbsolute)(linkTarget)) + linkTarget = resolveCrossPlatform(pathDirname(src), linkTarget); + if (destStat) + this.unlinkSync(dest); + this.symlinkSync(linkTarget, dest); + } + lstat(path, a, b) { + const [{ throwIfNoEntry = true, bigint = false }, callback] = (0, options_1.getStatOptsAndCb)(a, b); + this.wrapAsync(this._lstat, [(0, util_3.pathToFilename)(path), bigint, throwIfNoEntry], callback); + } + _stat(filename, bigint = false, throwIfNoEntry = true) { + const result = this._core.getResolvedLinkResult(filename, 'stat'); + if (result.ok) { + return (0, fs_core_1.Ok)(Stats_1.default.build(result.value.getNode(), bigint)); + } + if (result.err.code === "ENOENT" /* ERROR_CODE.ENOENT */ && !throwIfNoEntry) { + return (0, fs_core_1.Ok)(undefined); + } + else { + return result; + } + } + _statOrThrow(filename, bigint = false, throwIfNoEntry = true) { + const result = this._stat(filename, bigint, throwIfNoEntry); + if (result.ok) { + return result.value; + } + else { + throw result.err.toError(); + } + } + statSync(path, options) { + const { bigint = true, throwIfNoEntry = true } = (0, options_1.getStatOptions)(options); + const result = this._stat((0, util_3.pathToFilename)(path), bigint, throwIfNoEntry); + if (result.ok) { + return result.value; + } + else { + throw result.err.toError(); + } + } + stat(path, a, b) { + const [{ bigint = false, throwIfNoEntry = true }, callback] = (0, options_1.getStatOptsAndCb)(a, b); + this.wrapAsync(this._statOrThrow, [(0, util_3.pathToFilename)(path), bigint, throwIfNoEntry], callback); + } + fstatBase(fd, bigint = false) { + const file = this._core.getFileByFd(fd); + if (!file) + throw (0, util_3.createError)("EBADF" /* ERROR_CODE.EBADF */, 'fstat'); + return Stats_1.default.build(file.node, bigint); + } + fstatSync(fd, options) { + return this.fstatBase(fd, (0, options_1.getStatOptions)(options).bigint); + } + fstat(fd, a, b) { + const [opts, callback] = (0, options_1.getStatOptsAndCb)(a, b); + this.wrapAsync(this.fstatBase, [fd, opts.bigint], callback); + } + _exists(filename) { + const result = this._stat(filename); + return result.ok ? (0, fs_core_1.Ok)(true) : result; + } + _access(filename, mode) { + const link = this._core.getResolvedLinkOrThrow(filename, 'access'); + const node = link.getNode(); + // F_OK (0) just checks for existence, which we already confirmed above + if (mode === F_OK) { + return; + } + // Check read permission + if (mode & R_OK && !node.canRead()) { + throw (0, util_3.createError)("EACCES" /* ERROR_CODE.EACCES */, 'access', filename); + } + // Check write permission + if (mode & W_OK && !node.canWrite()) { + throw (0, util_3.createError)("EACCES" /* ERROR_CODE.EACCES */, 'access', filename); + } + // Check execute permission + if (mode & X_OK && !node.canExecute()) { + throw (0, util_3.createError)("EACCES" /* ERROR_CODE.EACCES */, 'access', filename); + } + } + watchFile(path, a, b) { + const filename = (0, util_3.pathToFilename)(path); + let options = a; + let listener = b; + if (typeof options === 'function') { + listener = a; + options = null; + } + if (typeof listener !== 'function') { + throw new TypeError('The "listener" argument must be of type function. Received ' + typeof listener); + } + let interval = 5007; + let persistent = true; + let bigint = false; + if (options && typeof options === 'object') { + if (options.interval !== undefined) { + if (typeof options.interval !== 'number') + throw new TypeError('The "options.interval" property must be of type number. Received ' + typeof options.interval); + if (!Number.isInteger(options.interval) || options.interval < 0 || options.interval > 0xffffffff) + throw new RangeError('The value of "options.interval" is out of range. ' + + `It must be an integer >= 0 && <= 4294967295. Received ${options.interval}`); + interval = options.interval; + } + if (typeof options.persistent === 'boolean') + persistent = options.persistent; + if (typeof options.bigint === 'boolean') + bigint = options.bigint; + } + let watcher = this.statWatchers[filename]; + if (!watcher) { + watcher = new this.StatWatcher(); + watcher.start(filename, persistent, interval, bigint); + this.statWatchers[filename] = watcher; + } + watcher.addListener('change', listener); + return watcher; + } + unwatchFile(path, listener) { + const filename = (0, util_3.pathToFilename)(path); + const watcher = this.statWatchers[filename]; + if (!watcher) + return; + if (typeof listener === 'function') { + watcher.removeListener('change', listener); + } + else { + watcher.removeAllListeners('change'); + } + if (watcher.listenerCount('change') === 0) { + watcher.stop(); + delete this.statWatchers[filename]; + } + } + createReadStream(path, options) { + return new this.ReadStream(path, options); + } + createWriteStream(path, options) { + return new this.WriteStream(path, options); + } + watch(path, options, listener) { + const filename = (0, util_3.pathToFilename)(path); + let givenOptions = options; + if (typeof options === 'function') { + listener = options; + givenOptions = null; + } + // tslint:disable-next-line prefer-const + let { persistent, recursive, encoding, signal, throwIfNoEntry, ignore } = (0, options_1.getDefaultOpts)(givenOptions); + if (persistent === undefined) + persistent = true; + if (recursive === undefined) + recursive = false; + const watcher = new this.FSWatcher(); + try { + watcher.start(filename, persistent, recursive, encoding, ignore); + } + catch (err) { + if (throwIfNoEntry === false && err.code === 'ENOENT') + return watcher; + throw err; + } + if (listener) { + watcher.addListener('change', listener); + } + if (signal) { + if (signal.aborted) { + watcher.close(); + } + else { + const onAbort = () => watcher.close(); + signal.addEventListener('abort', onAbort, { once: true }); + watcher.once('close', () => signal.removeEventListener('abort', onAbort)); + } + } + return watcher; + } + _statfs(filename, bigint = false) { + // Verify the path exists to match Node.js behavior + this._core.getResolvedLinkOrThrow(filename, 'statfs'); + return StatFs_1.default.build(this._core, bigint); + } + statfsSync(path, options) { + const { bigint = false } = (0, options_1.getStatfsOptions)(options); + return this._statfs((0, util_3.pathToFilename)(path), bigint); + } + statfs(path, a, b) { + const [{ bigint = false }, callback] = (0, options_1.getStatfsOptsAndCb)(a, b); + this.wrapAsync(this._statfs, [(0, util_3.pathToFilename)(path), bigint], callback); + } + // ---------------------------------------------------------------- Tree View + toTree(opts = { separator: path_1.sep }) { + return (0, fs_print_1.toTreeSync)(this, opts); + } + // ---------------------------------------------------------------- Snapshots + toSnapshot(path = '/') { + return fsSnapshot.toSnapshotSync({ fs: this, path }); + } + fromSnapshot(snapshot, path = '/') { + return fsSnapshot.fromSnapshotSync(snapshot, { fs: this, path }); + } + toBinarySnapshot(path = '/') { + return fsSnapshot.toBinarySnapshotSync({ fs: this, path }); + } + fromBinarySnapshot(binary, path = '/') { + return fsSnapshot.fromBinarySnapshotSync(binary, { fs: this, path }); + } + toJsonSnapshot(path = '/') { + const uint8 = fsSnapshot.toJsonSnapshotSync({ fs: this, path }); + return buffer_1.Buffer.from(uint8).toString('utf8'); + } + fromJsonSnapshot(json, path = '/') { + const uint8 = new Uint8Array(buffer_1.Buffer.from(json, 'utf8')); + return fsSnapshot.fromJsonSnapshotSync(uint8, { fs: this, path }); + } + } + volume.Volume = Volume; + Volume.fromJSON = (json, cwd, opts) => new Volume(fs_core_1.Superblock.fromJSON(json, cwd, opts)); + Volume.fromNestedJSON = (json, cwd, opts) => new Volume(fs_core_1.Superblock.fromNestedJSON(json, cwd, opts)); + function emitStop(self) { + self.emit('stop'); + } + /** All-zero stats passed to `watchFile` listeners when the file is missing, like in Node.js. */ + function buildZeroStats(bigint) { + const stats = new Stats_1.default(); + const zero = bigint ? BigInt(0) : 0; + const epoch = new Date(0); + stats.uid = zero; + stats.gid = zero; + stats.rdev = zero; + stats.blksize = zero; + stats.ino = zero; + stats.size = zero; + stats.blocks = zero; + stats.atime = epoch; + stats.mtime = epoch; + stats.ctime = epoch; + stats.birthtime = epoch; + stats.atimeMs = zero; + stats.mtimeMs = zero; + stats.ctimeMs = zero; + stats.birthtimeMs = zero; + if (bigint) { + stats.atimeNs = zero; + stats.mtimeNs = zero; + stats.ctimeNs = zero; + stats.birthtimeNs = zero; + } + stats.dev = zero; + stats.mode = zero; + stats.nlink = zero; + return stats; + } + class StatWatcher extends events_1.EventEmitter { + constructor(vol) { + super(); + this.bigint = false; + this.fileExists = false; + this.stopped = false; + this.onInterval = () => { + if (this.stopped) + return; + const stats = this.statSafe(); + if (stats) { + if (!this.fileExists) { + // Reappearance: `prev` is the stats from before the file disappeared, not the zeroed stats. + this.fileExists = true; + const prev = this.prev; + this.prev = stats; + this.emit('change', stats, prev); + } + else if (this.hasChanged(stats)) { + const prev = this.prev; + this.prev = stats; + this.emit('change', stats, prev); + } + } + else if (this.fileExists) { + // Disappearance is reported once, with zeroed current stats, `prev` + // keeps the last real stats for the eventual reappearance event. + this.fileExists = false; + this.emit('change', buildZeroStats(this.bigint), this.prev); + } + this.loop(); + }; + this.vol = vol; + } + loop() { + clearTimeout(this.timeoutRef); + this.timeoutRef = this.setTimeout(this.onInterval, this.interval); + } + hasChanged(stats) { + const prev = this.prev; + return (stats.mtimeMs !== prev.mtimeMs || + stats.ctimeMs !== prev.ctimeMs || + stats.size !== prev.size || + stats.ino !== prev.ino || + stats.mode !== prev.mode || + stats.uid !== prev.uid || + stats.gid !== prev.gid || + stats.nlink !== prev.nlink); + } + statSafe() { + try { + return (this.bigint ? this.vol.statSync(this.filename, { bigint: true }) : this.vol.statSync(this.filename)); + } + catch { + return null; + } + } + start(path, persistent = true, interval = 5007, bigint = false) { + this.filename = (0, util_3.pathToFilename)(path); + this.setTimeout = persistent + ? setTimeout.bind(typeof globalThis !== 'undefined' ? globalThis : commonjsGlobal) + : setTimeoutUnref_1.default; + this.interval = interval; + this.bigint = bigint; + const stats = this.statSafe(); + if (stats) { + this.prev = stats; + this.fileExists = true; + } + else { + // Watching a missing path does not throw, the listener is called once + // with zeroed stats, then again when the file is created. + this.prev = buildZeroStats(bigint); + this.fileExists = false; + queueMicrotask(() => { + if (!this.stopped) + this.emit('change', this.prev, this.prev); + }); + } + this.loop(); + } + stop() { + this.stopped = true; + clearTimeout(this.timeoutRef); + queueMicrotask(() => { + emitStop.call(this, this); + }); + } + /** + * Keep the event loop alive while the watcher is active. Polling continues + * either way; this only controls whether the process is kept running. + */ + ref() { + this.setTimeout = setTimeout.bind(typeof globalThis !== 'undefined' ? globalThis : commonjsGlobal); + const ref = this.timeoutRef; + if (ref && typeof ref === 'object' && typeof ref.ref === 'function') + ref.ref(); + return this; + } + /** Let the process exit while the watcher is active. Polling continues. */ + unref() { + this.setTimeout = setTimeoutUnref_1.default; + const ref = this.timeoutRef; + if (ref && typeof ref === 'object' && typeof ref.unref === 'function') + ref.unref(); + return this; + } + } + volume.StatWatcher = StatWatcher; + /* tslint:disable no-var-keyword prefer-const */ + // ---------------------------------------- ReadStream + var pool; + function allocNewPool(poolSize) { + pool = (0, buffer_1.bufferAllocUnsafe)(poolSize); + pool.used = 0; + } + (0, util_2.inherits)(FsReadStream, stream_1.Readable); + volume.ReadStream = FsReadStream; + function FsReadStream(vol, path, options) { + if (!(this instanceof FsReadStream)) + return new FsReadStream(vol, path, options); + this._vol = vol; + // a little bit bigger buffer and water marks by default + options = Object.assign({}, (0, options_1.getOptions)(options, {})); + if (options.highWaterMark === undefined) + options.highWaterMark = 64 * 1024; + stream_1.Readable.call(this, options); + this.path = (0, util_3.pathToFilename)(path); + this._fileHandle = options.fd && typeof options.fd !== 'number' ? options.fd : null; + this.fd = options.fd === undefined ? null : typeof options.fd !== 'number' ? options.fd.fd : options.fd; + this.flags = options.flags === undefined ? 'r' : options.flags; + this.mode = options.mode === undefined ? 0o666 : options.mode; + this.start = options.start; + this.end = options.end; + this.autoClose = options.autoClose === undefined ? true : options.autoClose; + this.pos = undefined; + this.bytesRead = 0; + if (this.start !== undefined) { + if (typeof this.start !== 'number') { + throw new TypeError('"start" option must be a Number'); + } + if (this.end === undefined) { + this.end = Infinity; + } + else if (typeof this.end !== 'number') { + throw new TypeError('"end" option must be a Number'); + } + if (this.start > this.end) { + throw new Error('"start" option must be <= "end" option'); + } + this.pos = this.start; + } + if (typeof this.fd !== 'number') + this.open(); + this.on('end', function () { + if (this.autoClose) { + if (this.destroy) + this.destroy(); + } + }); + } + FsReadStream.prototype.open = function () { + var self = this; // tslint:disable-line no-this-assignment + this._vol.open(this.path, this.flags, this.mode, (er, fd) => { + if (er) { + if (self.autoClose) { + if (self.destroy) + self.destroy(); + } + self.emit('error', er); + return; + } + self.fd = fd; + self.emit('open', fd); + // start the flow of data. + self.read(); + }); + }; + FsReadStream.prototype._read = function (n) { + if (typeof this.fd !== 'number') { + return this.once('open', function () { + this._read(n); + }); + } + if (this.destroyed) + return; + if (!pool || pool.length - pool.used < kMinPoolSpace) { + // discard the old pool. + allocNewPool(this._readableState.highWaterMark); + } + // Grab another reference to the pool in the case that while we're + // in the thread pool another read() finishes up the pool, and + // allocates a new one. + var thisPool = pool; + var toRead = Math.min(pool.length - pool.used, n); + var start = pool.used; + if (this.pos !== undefined) + toRead = Math.min(this.end - this.pos + 1, toRead); + // already read everything we were supposed to read! + // treat as EOF. + if (toRead <= 0) + return this.push(null); + // the actual read. + var self = this; // tslint:disable-line no-this-assignment + this._vol.read(this.fd, pool, pool.used, toRead, this.pos, onread); + // move the pool positions, and internal position for reading. + if (this.pos !== undefined) + this.pos += toRead; + pool.used += toRead; + function onread(er, bytesRead) { + if (er) { + if (self.autoClose && self.destroy) { + self.destroy(); + } + self.emit('error', er); + } + else { + var b = null; + if (bytesRead > 0) { + self.bytesRead += bytesRead; + b = thisPool.slice(start, start + bytesRead); + } + self.push(b); + } + } + }; + FsReadStream.prototype._destroy = function (err, cb) { + this.close(err2 => { + cb(err || err2); + }); + }; + FsReadStream.prototype.close = function (cb) { + if (cb) + this.once('close', cb); + if (this.closed || typeof this.fd !== 'number') { + if (typeof this.fd !== 'number') { + this.once('open', closeOnOpen); + return; + } + return queueMicrotask(() => this.emit('close')); + } + // Since Node 18, there is only a getter for '.closed'. + // The first branch mimics other setters from Readable. + // See https://github.com/nodejs/node/blob/v18.0.0/lib/internal/streams/readable.js#L1243 + if (typeof this._readableState?.closed === 'boolean') { + this._readableState.closed = true; + } + else { + this.closed = true; + } + if (this._fileHandle) { + this._fileHandle.close().then(() => this.emit('close'), er => this.emit('error', er)); + } + else { + this._vol.close(this.fd, er => { + if (er) + this.emit('error', er); + else + this.emit('close'); + }); + } + this.fd = null; + }; + // needed because as it will be called with arguments + // that does not match this.close() signature + function closeOnOpen(fd) { + this.close(); + } + (0, util_2.inherits)(FsWriteStream, stream_1.Writable); + volume.WriteStream = FsWriteStream; + function FsWriteStream(vol, path, options) { + if (!(this instanceof FsWriteStream)) + return new FsWriteStream(vol, path, options); + this._vol = vol; + options = Object.assign({}, (0, options_1.getOptions)(options, {})); + stream_1.Writable.call(this, options); + this.path = (0, util_3.pathToFilename)(path); + this._fileHandle = options.fd && typeof options.fd !== 'number' ? options.fd : null; + this.fd = options.fd === undefined ? null : typeof options.fd !== 'number' ? options.fd.fd : options.fd; + this.flags = options.flags === undefined ? 'w' : options.flags; + this.mode = options.mode === undefined ? 0o666 : options.mode; + this.start = options.start; + this.autoClose = options.autoClose === undefined ? true : !!options.autoClose; + this.pos = undefined; + this.bytesWritten = 0; + this.pending = true; + if (this.start !== undefined) { + if (typeof this.start !== 'number') { + throw new TypeError('"start" option must be a Number'); + } + if (this.start < 0) { + throw new Error('"start" must be >= zero'); + } + this.pos = this.start; + } + if (options.encoding) + this.setDefaultEncoding(options.encoding); + if (typeof this.fd !== 'number') + this.open(); + // dispose on finish. + this.once('finish', function () { + if (this.autoClose) { + this.close(); + } + }); + } + FsWriteStream.prototype.open = function () { + this._vol.open(this.path, this.flags, this.mode, function (er, fd) { + if (er) { + if (this.autoClose && this.destroy) { + this.destroy(); + } + this.emit('error', er); + return; + } + this.fd = fd; + this.pending = false; + this.emit('open', fd); + }.bind(this)); + }; + FsWriteStream.prototype._write = function (data, encoding, cb) { + if (!(data instanceof buffer_1.Buffer || data instanceof Uint8Array)) + return this.emit('error', new Error('Invalid data')); + if (typeof this.fd !== 'number') { + return this.once('open', function () { + this._write(data, encoding, cb); + }); + } + var self = this; // tslint:disable-line no-this-assignment + this._vol.write(this.fd, data, 0, data.length, this.pos, (er, bytes) => { + if (er) { + if (self.autoClose && self.destroy) { + self.destroy(); + } + return cb(er); + } + self.bytesWritten += bytes; + cb(); + }); + if (this.pos !== undefined) + this.pos += data.length; + }; + FsWriteStream.prototype._writev = function (data, cb) { + if (typeof this.fd !== 'number') { + return this.once('open', function () { + this._writev(data, cb); + }); + } + const self = this; // tslint:disable-line no-this-assignment + const len = data.length; + const chunks = new Array(len); + var size = 0; + for (var i = 0; i < len; i++) { + var chunk = data[i].chunk; + chunks[i] = chunk; + size += chunk.length; + } + const buf = buffer_1.Buffer.concat(chunks); + this._vol.write(this.fd, buf, 0, buf.length, this.pos, (er, bytes) => { + if (er) { + if (self.destroy) + self.destroy(); + return cb(er); + } + self.bytesWritten += bytes; + cb(); + }); + if (this.pos !== undefined) + this.pos += size; + }; + FsWriteStream.prototype.close = function (cb) { + if (cb) + this.once('close', cb); + if (this.closed || typeof this.fd !== 'number') { + if (typeof this.fd !== 'number') { + this.once('open', closeOnOpen); + return; + } + return queueMicrotask(() => this.emit('close')); + } + // Since Node 18, there is only a getter for '.closed'. + // The first branch mimics other setters from Writable. + // See https://github.com/nodejs/node/blob/v18.0.0/lib/internal/streams/writable.js#L766 + if (typeof this._writableState?.closed === 'boolean') { + this._writableState.closed = true; + } + else { + this.closed = true; + } + if (this._fileHandle) { + this._fileHandle.close().then(() => this.emit('close'), er => this.emit('error', er)); + } + else { + this._vol.close(this.fd, er => { + if (er) + this.emit('error', er); + else + this.emit('close'); + }); + } + this.fd = null; + }; + FsWriteStream.prototype._destroy = FsReadStream.prototype._destroy; + // There is no shutdown() for files. + FsWriteStream.prototype.destroySoon = FsWriteStream.prototype.end; + // ---------------------------------------- FSWatcher + class FSWatcher extends events_1.EventEmitter { + constructor(vol) { + super(); + this._filename = ''; + this._filenameEncoded = ''; + this._recursive = false; + this._encoding = fs_node_utils_1.ENCODING_UTF8; + this._closed = false; + this._onEvent = (event) => { + switch (event.type) { + case 0 /* FsEventType.CREATE */: + case 1 /* FsEventType.DELETE */: + this._emit('rename', event.steps); + break; + case 4 /* FsEventType.MOVE */: + if (event.oldSteps) + this._emit('rename', event.oldSteps); + this._emit('rename', event.steps); + break; + case 2 /* FsEventType.MODIFY */: + case 3 /* FsEventType.ATTRIB */: + this._emit('change', event.steps); + break; + } + }; + this._persist = () => { + this._timer = setTimeout(this._persist, 1e6); + }; + this._vol = vol; + } + _emit(type, relativeSteps) { + const filename = relativeSteps.length ? relativeSteps.join(pathSep) : this._watcher.link.getName(); + if (this._ignore && this._ignore(filename)) + return; + this.emit('change', type, (0, fs_node_utils_1.strToEncoding)(filename, this._encoding)); + } + /** + * Keep the event loop alive while the watcher is active. All watchers are + * ref'ed by default (unless started with `persistent: false`). No-op when + * already ref'ed, closed, or never started. + */ + ref() { + if (this._watcher && !this._closed && !this._timer) + this._persist(); + return this; + } + /** + * Let the process exit while the watcher is active. Events are still + * delivered. No-op when already unref'ed. + */ + unref() { + clearTimeout(this._timer); + this._timer = undefined; + return this; + } + start(path, persistent = true, recursive = false, encoding = fs_node_utils_1.ENCODING_UTF8, ignore) { + this._filename = (0, util_3.pathToFilename)(path); + this._steps = (0, fs_core_1.filenameToSteps)(this._filename); + this._filenameEncoded = (0, fs_node_utils_1.strToEncoding)(this._filename); + this._recursive = recursive; + this._encoding = encoding; + this._ignore = ignore === undefined ? undefined : (0, fs_node_utils_1.watchIgnoreToMatcher)(ignore); + try { + this._watcher = new fs_core_1.CoreWatcher(this._vol._core, this._filename, { recursive }); + } + catch (err) { + const error = new Error(`watch ${this._filename} ${err.code}`); + error.code = err.code; + error.errno = err.code; + throw error; + } + this._link = this._watcher.link; + this._watcher.changes.listen(this._onEvent); + if (persistent) + this._persist(); + } + close() { + clearTimeout(this._timer); + this._timer = undefined; + if (!this._watcher || this._closed) + return; + this._closed = true; + this._watcher.close(); + queueMicrotask(() => this.emit('close')); + } + } + volume.FSWatcher = FSWatcher; + + return volume; +} + +var fsCallbackApiList = {}; + +var hasRequiredFsCallbackApiList; + +function requireFsCallbackApiList () { + if (hasRequiredFsCallbackApiList) return fsCallbackApiList; + hasRequiredFsCallbackApiList = 1; + Object.defineProperty(fsCallbackApiList, "__esModule", { value: true }); + fsCallbackApiList.fsCallbackApiList = void 0; + fsCallbackApiList.fsCallbackApiList = [ + 'access', + 'appendFile', + 'chmod', + 'chown', + 'close', + 'copyFile', + 'cp', + 'createReadStream', + 'createWriteStream', + 'exists', + 'fchmod', + 'fchown', + 'fdatasync', + 'fstat', + 'fsync', + 'ftruncate', + 'futimes', + 'glob', + 'lchmod', + 'lchown', + 'link', + 'lstat', + 'mkdir', + 'mkdtemp', + 'open', + 'openAsBlob', + 'opendir', + 'read', + 'readv', + 'readdir', + 'readFile', + 'readlink', + 'realpath', + 'rename', + 'rm', + 'rmdir', + 'stat', + 'statfs', + 'symlink', + 'truncate', + 'unlink', + 'unwatchFile', + 'utimes', + 'lutimes', + 'watch', + 'watchFile', + 'write', + 'writev', + 'writeFile', + ]; + + return fsCallbackApiList; +} + +var fsSynchronousApiList = {}; + +var hasRequiredFsSynchronousApiList; + +function requireFsSynchronousApiList () { + if (hasRequiredFsSynchronousApiList) return fsSynchronousApiList; + hasRequiredFsSynchronousApiList = 1; + Object.defineProperty(fsSynchronousApiList, "__esModule", { value: true }); + fsSynchronousApiList.fsSynchronousApiList = void 0; + fsSynchronousApiList.fsSynchronousApiList = [ + 'accessSync', + 'appendFileSync', + 'chmodSync', + 'chownSync', + 'closeSync', + 'copyFileSync', + 'cpSync', + 'existsSync', + 'fchmodSync', + 'fchownSync', + 'fdatasyncSync', + 'fstatSync', + 'fsyncSync', + 'ftruncateSync', + 'futimesSync', + 'globSync', + 'lchmodSync', + 'lchownSync', + 'linkSync', + 'lstatSync', + 'mkdirSync', + 'mkdtempSync', + 'openSync', + 'opendirSync', + 'readdirSync', + 'readFileSync', + 'readlinkSync', + 'readSync', + 'readvSync', + 'realpathSync', + 'renameSync', + 'rmdirSync', + 'rmSync', + 'statfsSync', + 'statSync', + 'symlinkSync', + 'truncateSync', + 'unlinkSync', + 'utimesSync', + 'lutimesSync', + 'writeFileSync', + 'writeSync', + 'writevSync', + ]; + + return fsSynchronousApiList; +} + +var fsCommonObjectsList = {}; + +var hasRequiredFsCommonObjectsList; + +function requireFsCommonObjectsList () { + if (hasRequiredFsCommonObjectsList) return fsCommonObjectsList; + hasRequiredFsCommonObjectsList = 1; + Object.defineProperty(fsCommonObjectsList, "__esModule", { value: true }); + fsCommonObjectsList.fsCommonObjectsList = void 0; + fsCommonObjectsList.fsCommonObjectsList = [ + 'F_OK', + 'R_OK', + 'W_OK', + 'X_OK', + 'constants', + 'Stats', + 'StatFs', + 'Dir', + 'Dirent', + 'StatWatcher', + 'FSWatcher', + 'ReadStream', + 'WriteStream', + ]; + + return fsCommonObjectsList; +} + +var hasRequiredLib$1; + +function requireLib$1 () { + if (hasRequiredLib$1) return lib$7; + hasRequiredLib$1 = 1; + (function (exports) { + Object.defineProperty(exports, "__esModule", { value: true }); + exports.fsCommonObjectsList = exports.fsSynchronousApiList = exports.fsCallbackApiList = exports.FsPromises = exports.Dir = exports.FileHandle = exports.StatFs = exports.Dirent = exports.Stats = exports.toUnixTimestamp = exports.FSWatcher = exports.StatWatcher = exports.Volume = void 0; + const tslib_1 = require$$0$2; + var volume_1 = requireVolume(); + Object.defineProperty(exports, "Volume", { enumerable: true, get: function () { return volume_1.Volume; } }); + Object.defineProperty(exports, "StatWatcher", { enumerable: true, get: function () { return volume_1.StatWatcher; } }); + Object.defineProperty(exports, "FSWatcher", { enumerable: true, get: function () { return volume_1.FSWatcher; } }); + Object.defineProperty(exports, "toUnixTimestamp", { enumerable: true, get: function () { return volume_1.toUnixTimestamp; } }); + var Stats_1 = requireStats(); + Object.defineProperty(exports, "Stats", { enumerable: true, get: function () { return Stats_1.default; } }); + var Dirent_1 = requireDirent(); + Object.defineProperty(exports, "Dirent", { enumerable: true, get: function () { return Dirent_1.default; } }); + var StatFs_1 = requireStatFs(); + Object.defineProperty(exports, "StatFs", { enumerable: true, get: function () { return StatFs_1.default; } }); + var FileHandle_1 = requireFileHandle(); + Object.defineProperty(exports, "FileHandle", { enumerable: true, get: function () { return FileHandle_1.FileHandle; } }); + var Dir_1 = requireDir(); + Object.defineProperty(exports, "Dir", { enumerable: true, get: function () { return Dir_1.Dir; } }); + var FsPromises_1 = requireFsPromises(); + Object.defineProperty(exports, "FsPromises", { enumerable: true, get: function () { return FsPromises_1.FsPromises; } }); + tslib_1.__exportStar(requireOptions(), exports); + tslib_1.__exportStar(requireUtil$1(), exports); + tslib_1.__exportStar(requireGlob(), exports); + var fsCallbackApiList_1 = requireFsCallbackApiList(); + Object.defineProperty(exports, "fsCallbackApiList", { enumerable: true, get: function () { return fsCallbackApiList_1.fsCallbackApiList; } }); + var fsSynchronousApiList_1 = requireFsSynchronousApiList(); + Object.defineProperty(exports, "fsSynchronousApiList", { enumerable: true, get: function () { return fsSynchronousApiList_1.fsSynchronousApiList; } }); + var fsCommonObjectsList_1 = requireFsCommonObjectsList(); + Object.defineProperty(exports, "fsCommonObjectsList", { enumerable: true, get: function () { return fsCommonObjectsList_1.fsCommonObjectsList; } }); + + } (lib$7)); + return lib$7; +} + +var hasRequiredLib; + +function requireLib () { + if (hasRequiredLib) return lib$8.exports; + hasRequiredLib = 1; + (function (module, exports) { + Object.defineProperty(exports, "__esModule", { value: true }); + exports.memfs = exports.fs = exports.vol = exports.Volume = void 0; + exports.createFsFromVolume = createFsFromVolume; + const fs_node_1 = requireLib$1(); + Object.defineProperty(exports, "Volume", { enumerable: true, get: function () { return fs_node_1.Volume; } }); + const fs_node_utils_1 = requireLib$7(); + const { F_OK, R_OK, W_OK, X_OK } = fs_node_utils_1.constants; + // Default volume. + exports.vol = new fs_node_1.Volume(); + function createFsFromVolume(vol) { + const fs = { F_OK, R_OK, W_OK, X_OK, constants: fs_node_utils_1.constants, Stats: fs_node_1.Stats, Dirent: fs_node_1.Dirent }; + // Bind FS methods. + for (const method of fs_node_1.fsSynchronousApiList) + if (typeof vol[method] === 'function') + fs[method] = vol[method].bind(vol); + for (const method of fs_node_1.fsCallbackApiList) + if (typeof vol[method] === 'function') + fs[method] = vol[method].bind(vol); + fs.StatWatcher = vol.StatWatcher; + fs.FSWatcher = vol.FSWatcher; + fs.WriteStream = vol.WriteStream; + fs.ReadStream = vol.ReadStream; + fs.promises = vol.promises; + // Handle realpath and realpathSync with their .native properties + if (typeof vol.realpath === 'function') { + fs.realpath = vol.realpath.bind(vol); + if (typeof vol.realpath.native === 'function') { + fs.realpath.native = vol.realpath.native.bind(vol); + } + } + if (typeof vol.realpathSync === 'function') { + fs.realpathSync = vol.realpathSync.bind(vol); + if (typeof vol.realpathSync.native === 'function') { + fs.realpathSync.native = vol.realpathSync.native.bind(vol); + } + } + fs._toUnixTimestamp = fs_node_1.toUnixTimestamp; + fs.__vol = vol; + return fs; + } + exports.fs = createFsFromVolume(exports.vol); + /** + * Creates a new file system instance. + * + * @param json File system structure expressed as a JSON object. + * Use `null` for empty directories and empty string for empty files. + * @param cwdOrOpts Current working directory (string) or options object. + * The JSON structure will be created relative to the cwd path. + * @returns A `memfs` file system instance, which is a drop-in replacement for + * the `fs` module. + */ + const memfs = (json = {}, cwdOrOpts = '/') => { + const opts = typeof cwdOrOpts === 'string' ? { cwd: cwdOrOpts } : cwdOrOpts; + // When no explicit cwd is given but a custom process is provided, let the + // Superblock use that process's cwd(). Otherwise default to '/' so the + // convenience function keeps its opinionated virtual-root default. + const cwd = opts.cwd ?? (opts.process ? undefined : '/'); + const vol = fs_node_1.Volume.fromNestedJSON(json, cwd, { process: opts.process }); + const fs = createFsFromVolume(vol); + return { fs, vol }; + }; + exports.memfs = memfs; + module.exports = { ...module.exports, ...exports.fs }; + module.exports.semantic = true; + + } (lib$8, lib$8.exports)); + return lib$8.exports; +} + +var libExports = requireLib(); +var index = /*@__PURE__*/getDefaultExportFromCjs(libExports); + +var memfsExported = /*#__PURE__*/_mergeNamespaces({ + __proto__: null, + default: index +}, [libExports]); + +const { createFsFromVolume, Volume, fs, memfs } = memfsExported; + +export { Buffer, Volume, createFsFromVolume, fs, memfs, memfsExported }; diff --git a/dg-ui/node_modules/@tailwindcss/oxide-wasm32-wasi/node_modules/@napi-rs/wasm-runtime/fs-proxy.js b/dg-ui/node_modules/@tailwindcss/oxide-wasm32-wasi/node_modules/@napi-rs/wasm-runtime/fs-proxy.js new file mode 100644 index 0000000..4daf897 --- /dev/null +++ b/dg-ui/node_modules/@tailwindcss/oxide-wasm32-wasi/node_modules/@napi-rs/wasm-runtime/fs-proxy.js @@ -0,0 +1,316 @@ +// @ts-check + +/** + * @param {unknown} value + */ +const getType = (value) => { + if (value === undefined) return 0 + if (value === null) return 1 + if (isBuffer(value)) return 10 + const t = typeof value + if (t === 'boolean') return 2 + if (t === 'number') return 3 + if (t === 'string') return 4 + if (t === 'object') return 6 + if (t === 'bigint') return 9 + return -1 +} + +/** + * @param {unknown} value + * @returns {value is Uint8Array} + */ +const isBuffer = (value) => { + const BufferCtor = globalThis.Buffer + if (typeof BufferCtor?.isBuffer === 'function') { + return BufferCtor.isBuffer(value) + } + return value instanceof Uint8Array && value.constructor?.name === 'Buffer' +} + +const RESPONSE_HEADER_SIZE = 16 +const RESPONSE_PAYLOAD_SIZE = 10240 +const RESPONSE_BUFFER_SIZE = RESPONSE_HEADER_SIZE + RESPONSE_PAYLOAD_SIZE + +/** + * @param {Int32Array} sab + * @param {Uint8Array} payload + */ +const writeResponsePayload = (sab, payload) => { + if (payload.length > RESPONSE_PAYLOAD_SIZE) { + throw new RangeError('payload overflow') + } + new Uint8Array(sab.buffer).set(payload, RESPONSE_HEADER_SIZE) +} + +/** + * @param {import('memfs').IFs} memfs + * @param {any} value + * @param {ReturnType} type + * @returns {Uint8Array} + */ +const encodeValue = (memfs, value, type) => { + switch (type) { + case 0: + case 1: + return new Uint8Array(0) + case 2: { + const view = new Int32Array(1) + view[0] = value ? 1 : 0 + return new Uint8Array(view.buffer) + } + case 3: { + const view = new Float64Array(1) + view[0] = value + return new Uint8Array(view.buffer) + } + case 4: { + const view = new TextEncoder().encode(value) + return view + } + case 10: + return new Uint8Array(value) + case 6: { + function storeConstructor(obj, memfs, processed = new WeakSet()) { + if (!obj || typeof obj !== 'object') { + return + } + + if (processed.has(obj)) { + return + } + + processed.add(obj) + + const [entry] = + Object.entries(memfs).filter(([_, v]) => v === obj.constructor)[0] ?? + [] + if (entry) { + Object.defineProperty(obj, '__constructor__', { + configurable: true, + writable: true, + enumerable: true, + value: entry, + }) + } + + for (const value of Object.values(obj)) { + storeConstructor(value, memfs, processed) + } + } + + storeConstructor(value, memfs) + + const json = JSON.stringify(value, (_, value) => { + if (typeof value === 'bigint') { + return `BigInt(${String(value)})` + } + if (value instanceof Error) { + return { + ...value, + message: value.message, + stack: value.stack, + __error__: value.constructor.name, + } + } + return value + }) + const view = new TextEncoder().encode(json) + return view + } + case 9: { + return new TextEncoder().encode(String(value)) + } + case -1: + default: + throw new Error('unsupported data') + } +} + +/** + * @param {typeof import('memfs')} memfs + * @param {Uint8Array} payload + * @param {number} type + * @returns {any} + */ +const decodeValue = (memfs, payload, type) => { + if (type === 0) return undefined + if (type === 1) return null + if (type === 2) + return Boolean(new Int32Array(payload.buffer, payload.byteOffset, 1)[0]) + if (type === 3) + return new Float64Array(payload.buffer, payload.byteOffset, 1)[0] + if (type === 4) return new TextDecoder().decode(payload.slice()) + if (type === 10) { + const BufferCtor = globalThis.Buffer + if (typeof BufferCtor?.from === 'function') { + return BufferCtor.from(payload) + } + return payload.slice() + } + if (type === 6) { + const obj = JSON.parse( + new TextDecoder().decode(payload.slice()), + (_key, value) => { + if (typeof value === 'string') { + const matched = value.match(/^BigInt\((-?\d+)\)$/) + if (matched && matched[1]) { + return BigInt(matched[1]) + } + } + return value + }, + ) + + function loadConstructor(obj, memfs, processed = new WeakSet()) { + if (!obj || typeof obj !== 'object') { + return + } + + if (processed.has(obj)) { + return + } + + processed.add(obj) + + if (obj.__constructor__) { + const ctor = obj.__constructor__ + delete obj.__constructor__ + Object.setPrototypeOf(obj, memfs[ctor].prototype) + } + + for (const value of Object.values(obj)) { + loadConstructor(value, memfs, processed) + } + } + + loadConstructor(obj, memfs) + + if (obj.__error__) { + const name = obj.__error__ + const ErrorConstructor = globalThis[name] || Error + delete obj.__error__ + const err = new ErrorConstructor(obj.message) + Object.defineProperty(err, 'stack', { + configurable: true, + enumerable: false, + writable: true, + value: err.stack, + }) + Object.defineProperty(err, Symbol.toStringTag, { + configurable: true, + enumerable: false, + writable: true, + value: name, + }) + for (const [k, v] of Object.entries(obj)) { + if (k === 'message' || k === 'stack') continue + err[k] = v + } + return err + } + return obj + } + if (type === 9) { + return BigInt(new TextDecoder().decode(payload.slice())) + } + throw new Error('unsupported data') +} + +/** + * @param {import('memfs').IFs} fs + * @returns {(e: { data: { __fs__: { sab: Int32Array, type: keyof import('memfs').IFs, payload: any[] } } }) => void} + */ +// oxlint-disable-next-line no-unused-vars -- fixed in an upcoming release +export const createOnMessage = (fs) => + function onMessage(e) { + if (e.data.__fs__) { + /** + * 0..4 status(int32_t): 21(waiting) 0(success) 1(error) + * 5..8 type(napi_valuetype): 0(undefined) 1(null) 2(boolean) 3(number) 4(string) 6(jsonstring) 9(bigint) 10(buffer) -1(unsupported) + * 9..16 payload_size(uint32_t) <= 10240 + * 16..16 + payload_size payload_content + */ + const { sab, type, payload } = e.data.__fs__ + const fn = fs[type] + try { + const ret = fn.apply(fs, payload) + const t = getType(ret) + Atomics.store(sab, 1, t) + const v = encodeValue(fs, ret, t) + Atomics.store(sab, 2, v.length) + writeResponsePayload(sab, v) + Atomics.store(sab, 0, 0) // success + } catch (/** @type {any} */ err) { + let t = getType(err) + let v + try { + if (t === -1) { + throw new Error('unsupported data') + } + v = encodeValue(fs, err, t) + } catch { + const fallback = (() => { + try { + return String(err) + } catch { + return 'Unserializable thrown value' + } + })() + t = getType(fallback) + v = encodeValue(fs, fallback, t) + } + if (v.length > RESPONSE_PAYLOAD_SIZE) { + const overflowErr = new RangeError('payload overflow') + t = getType(overflowErr) + v = encodeValue(fs, overflowErr, t) + } + Atomics.store(sab, 1, t) + Atomics.store(sab, 2, v.length) + writeResponsePayload(sab, v) + Atomics.store(sab, 0, 1) // error + } finally { + Atomics.notify(sab, 0) + } + } + } + +/** + * @param {typeof import('memfs')} memfs + */ +export const createFsProxy = (memfs) => + new Proxy( + {}, + { + get(_target, p, _receiver) { + /** + * @param {any[]} args + */ + return function (...args) { + const sab = new SharedArrayBuffer(RESPONSE_BUFFER_SIZE) + const i32arr = new Int32Array(sab) + Atomics.store(i32arr, 0, 21) + + postMessage({ + __fs__: { + sab: i32arr, + type: p, + payload: args, + }, + }) + + Atomics.wait(i32arr, 0, 21) + + const status = Atomics.load(i32arr, 0) + const type = Atomics.load(i32arr, 1) + const size = Atomics.load(i32arr, 2) + const content = new Uint8Array(sab, RESPONSE_HEADER_SIZE, size) + const value = decodeValue(memfs, content, type) + if (status === 1) { + throw value + } + return value + } + }, + }, + ) diff --git a/dg-ui/node_modules/@tailwindcss/oxide-wasm32-wasi/node_modules/@napi-rs/wasm-runtime/package.json b/dg-ui/node_modules/@tailwindcss/oxide-wasm32-wasi/node_modules/@napi-rs/wasm-runtime/package.json new file mode 100644 index 0000000..1d9b41c --- /dev/null +++ b/dg-ui/node_modules/@tailwindcss/oxide-wasm32-wasi/node_modules/@napi-rs/wasm-runtime/package.json @@ -0,0 +1,74 @@ +{ + "name": "@napi-rs/wasm-runtime", + "version": "1.2.2", + "type": "module", + "description": "Runtime and polyfill for wasm targets", + "engines": { + "node": "^20.19.0 || ^22.13.0 || >=23.5.0" + }, + "homepage": "https://napi.rs/", + "author": { + "name": "LongYinan", + "url": "https://github.com/Brooooooklyn" + }, + "repository": { + "type": "git", + "url": "git+https://github.com/napi-rs/napi-rs.git", + "directory": "wasm-runtime" + }, + "license": "MIT", + "publishConfig": { + "registry": "https://registry.npmjs.org/", + "access": "public" + }, + "files": [ + "runtime.cjs", + "runtime.js", + "fs-proxy.js", + "dist/*.cjs", + "dist/*.js" + ], + "devDependencies": { + "@emnapi/core": "2.0.0-alpha.3", + "@rollup/plugin-alias": "^6.0.0", + "@rollup/plugin-commonjs": "^29.0.3", + "@rollup/plugin-inject": "^5.0.5", + "@rollup/plugin-json": "^6.1.0", + "@rollup/plugin-node-resolve": "^16.0.3", + "@rollup/plugin-replace": "^6.0.3", + "buffer": "^6.0.3", + "events": "^3.3.0", + "memfs": "^4.64.0", + "node-inspect-extracted": "^3.3.2", + "path-browserify": "^1.0.1", + "process": "^0.11.10", + "readable-stream": "^4.7.0", + "rollup": "^4.61.1", + "rollup-plugin-polyfill-node": "^0.13.0", + "tslib": "^2.8.1" + }, + "dependencies": { + "@tybys/wasm-util": "^0.10.3" + }, + "peerDependencies": { + "@emnapi/core": "^1.7.1 || ^2.0.0-alpha.3", + "@emnapi/runtime": "^1.7.1 || ^2.0.0-alpha.3" + }, + "scripts": { + "build": "rollup -c rollup.config.js", + "test": "yarn run build && node --test" + }, + "funding": { + "type": "github", + "url": "https://github.com/sponsors/Brooooooklyn" + }, + "exports": { + ".": { + "import": "./runtime.js", + "require": "./runtime.cjs" + }, + "./fs": { + "import": "./dist/fs.js" + } + } +} diff --git a/dg-ui/node_modules/@tailwindcss/oxide-wasm32-wasi/node_modules/@napi-rs/wasm-runtime/runtime.cjs b/dg-ui/node_modules/@tailwindcss/oxide-wasm32-wasi/node_modules/@napi-rs/wasm-runtime/runtime.cjs new file mode 100644 index 0000000..3dc0d97 --- /dev/null +++ b/dg-ui/node_modules/@tailwindcss/oxide-wasm32-wasi/node_modules/@napi-rs/wasm-runtime/runtime.cjs @@ -0,0 +1,39 @@ +const { + MessageHandler, + instantiateNapiModuleSync, + instantiateNapiModule, +} = require('@emnapi/core') +// Single-threaded (non-shared-memory) WASI builds link an emnapi archive +// without the C async-work and threadsafe-function implementations (they are +// unconditional `napi_generic_failure` stubs without threads), so the +// generated loaders provide the JavaScript implementations through these +// plugins instead. Raw `instantiateNapiModule(Sync)` callers instantiating a +// single-threaded napi-rs wasm must pass them too: +// `plugins: [emnapiAsyncWorkPlugin, emnapiTSFNPlugin]` — without them +// instantiation fails with a LinkError naming the missing import. Threaded +// (shared-memory) builds link the C implementations and need no plugins; +// this mirrors the upstream @emnapi/core v2 plugin split (v1 bundled these +// implementations in the core runtime). The plugins are bundled into this +// package so loading the runtime with @emnapi/core v1 does not resolve the +// v2-only `@emnapi/core/plugins` package export. +const { + emnapiAsyncWorkPlugin, + emnapiTSFNPlugin, +} = require('./dist/emnapi-plugins.cjs') +const { createContext, getDefaultContext } = require('@emnapi/runtime') +const { WASI } = require('@tybys/wasm-util') + +const { createFsProxy, createOnMessage } = require('./dist/fs-proxy.cjs') + +module.exports = { + MessageHandler, + createContext, + emnapiAsyncWorkPlugin, + emnapiTSFNPlugin, + instantiateNapiModule, + instantiateNapiModuleSync, + getDefaultContext, + WASI, + createFsProxy, + createOnMessage, +} diff --git a/dg-ui/node_modules/@tailwindcss/oxide-wasm32-wasi/node_modules/@napi-rs/wasm-runtime/runtime.js b/dg-ui/node_modules/@tailwindcss/oxide-wasm32-wasi/node_modules/@napi-rs/wasm-runtime/runtime.js new file mode 100644 index 0000000..7a727a0 --- /dev/null +++ b/dg-ui/node_modules/@tailwindcss/oxide-wasm32-wasi/node_modules/@napi-rs/wasm-runtime/runtime.js @@ -0,0 +1,36 @@ +import * as emnapiCore from '@emnapi/core' +import * as emnapiRuntime from '@emnapi/runtime' + +import { + emnapiAsyncWorkPlugin, + emnapiTSFNPlugin, +} from './dist/emnapi-plugins.js' + +const { instantiateNapiModuleSync, instantiateNapiModule, MessageHandler } = + emnapiCore +const { createContext, getDefaultContext } = emnapiRuntime + +// Single-threaded (non-shared-memory) WASI builds link an emnapi archive +// without the C async-work and threadsafe-function implementations (they are +// unconditional `napi_generic_failure` stubs without threads), so the +// generated loaders provide the JavaScript implementations through these +// plugins instead. Raw `instantiateNapiModule(Sync)` callers instantiating a +// single-threaded napi-rs wasm must pass them too: +// `plugins: [emnapiAsyncWorkPlugin, emnapiTSFNPlugin]` — without them +// instantiation fails with a LinkError naming the missing import. Threaded +// (shared-memory) builds link the C implementations and need no plugins; +// this mirrors the upstream @emnapi/core v2 plugin split (v1 bundled these +// implementations in the core runtime). The plugins are bundled into this +// package so loading the runtime with @emnapi/core v1 does not resolve the +// v2-only `@emnapi/core/plugins` package export. +export { + MessageHandler, + createContext, + emnapiAsyncWorkPlugin, + emnapiTSFNPlugin, + getDefaultContext, + instantiateNapiModule, + instantiateNapiModuleSync, +} +export * from '@tybys/wasm-util' +export { createOnMessage, createFsProxy } from './fs-proxy.js' diff --git a/dg-ui/node_modules/@tailwindcss/oxide-wasm32-wasi/node_modules/@tybys/wasm-util/README.md b/dg-ui/node_modules/@tailwindcss/oxide-wasm32-wasi/node_modules/@tybys/wasm-util/README.md new file mode 100644 index 0000000..b36fdf0 --- /dev/null +++ b/dg-ui/node_modules/@tailwindcss/oxide-wasm32-wasi/node_modules/@tybys/wasm-util/README.md @@ -0,0 +1,193 @@ +# @tybys/wasm-util + +WebAssembly related utils for browser environment + +**The output code is ES2019** + +## Features + +All example code below need to be bundled by ES module bundlers like `webpack` / `rollup`, or specify import map in browser native ES module runtime. + +### WASI polyfill for browser + +The API is similar to the `require('wasi').WASI` in Node.js. + +You can use `memfs-browser` to provide filesystem capability. + +- Example: [https://github.com/toyobayashi/wasi-wabt](https://github.com/toyobayashi/wasi-wabt) +- Demo: [https://toyobayashi.github.io/wasi-wabt/](https://toyobayashi.github.io/wasi-wabt/) + +```js +import { load, WASI } from '@tybys/wasm-util' +import { Volume, createFsFromVolume } from 'memfs-browser' + +const fs = createFsFromVolume(Volume.fromJSON({ + '/home/wasi': null +})) + +const wasi = new WASI({ + args: ['chrome', 'file.wasm'], + env: { + NODE_ENV: 'development', + WASI_SDK_PATH: '/opt/wasi-sdk' + }, + preopens: { + '/': '/' + }, + fs, + + // redirect stdout / stderr + + // print (text) { console.log(text) }, + // printErr (text) { console.error(text) } +}) + +const imports = { + wasi_snapshot_preview1: wasi.wasiImport +} + +const { module, instance } = await load('/path/to/file.wasm', imports) +wasi.start(instance) +// wasi.initialize(instance) +``` + +Implemented syscalls: [wasi_snapshot_preview1](#wasi_snapshot_preview1) + +### `load` / `loadSync` + +`loadSync` has 4KB wasm size limit in browser. + +```js +// bundler +import { load, loadSync } from '@tybys/wasm-util' + +const imports = { /* ... */ } + +// using path +const { module, instance } = await load('/path/to/file.wasm', imports) +const { module, instance } = loadSync('/path/to/file.wasm', imports) + +// using URL +const { module, instance } = await load(new URL('./file.wasm', import.meta.url), imports) +const { module, instance } = loadSync(new URL('./file.wasm', import.meta.url), imports) + +// using Uint8Array +const buffer = new Uint8Array([ + 0x00, 0x61, 0x73, 0x6d, + 0x01, 0x00, 0x00, 0x00 +]) +const { module, instance } = await load(buffer, imports) +const { module, instance } = loadSync(buffer, imports) + +// auto asyncify +const { + module, + instance: asyncifiedInstance +} = await load(buffer, imports, { /* asyncify options */}) +asyncifiedInstance.exports.fn() // => return Promise +``` + +### Extend Memory instance + +```js +import { Memory, extendMemory } from '@tybys/wasm-util' + +const memory = new WebAssembly.Memory({ initial: 256 }) +// const memory = instance.exports.memory + +extendMemory(memory) +console.log(memory instanceof Memory) +console.log(memory instanceof WebAssembly.Memory) +// expose memory view getters like Emscripten +const { HEAPU8, HEAPU32, view } = memory +``` + +### Asyncify wrap + +Build the C code using `clang`, `wasm-ld` and `wasm-opt` + +```c +void async_sleep(int ms); + +int main() { + async_sleep(200); + return 0; +} +``` + +```js +import { Asyncify } from '@tybys/wasm-util' + +const asyncify = new Asyncify() + +const imports = { + env: { + async_sleep: asyncify.wrapImportFunction(function (ms) { + return new Promise((resolve) => { + setTimeout(resolve, ms) + }) + }) + } +} + +// async_sleep(200) +const bytes = await (await fetch('/asyncfied_by_wasm-opt.wasm')).arrayBuffer() +const { instance } = await WebAssembly.instantiate(bytes, imports) +const asyncifiedInstance = asyncify.init(instance.exports.memory, instance, { + wrapExports: ['_start'] +}) + +const p = asyncifedInstance._start() +console.log(typeof p.then === 'function') +const now = Date.now() +await p +console.log(Date.now() - now >= 200) +``` + +### wasi_snapshot_preview1 + +- [x] args_get +- [x] args_sizes_get +- [x] environ_get +- [x] environ_sizes_get +- [x] clock_res_get +- [x] clock_time_get +- [ ] ~~fd_advise~~ +- [x] fd_allocate +- [x] fd_close +- [x] fd_datasync +- [x] fd_fdstat_get +- [ ] ~~fd_fdstat_set_flags~~ +- [x] fd_fdstat_set_rights +- [x] fd_filestat_get +- [x] fd_filestat_set_size +- [x] fd_filestat_set_times +- [x] fd_pread +- [x] fd_prestat_get +- [x] fd_prestat_dir_name +- [x] fd_pwrite +- [x] fd_read +- [x] fd_readdir +- [x] fd_renumber +- [x] fd_seek +- [x] fd_sync +- [x] fd_tell +- [x] fd_write +- [x] path_create_directory +- [x] path_filestat_get +- [x] path_filestat_set_times +- [x] path_link +- [x] path_open +- [x] path_readlink +- [x] path_remove_directory +- [x] path_rename +- [x] path_symlink +- [x] path_unlink_file +- [x] poll_oneoff (timer only) +- [x] proc_exit +- [ ] ~~proc_raise~~ +- [x] sched_yield +- [x] random_get +- [ ] ~~sock_recv~~ +- [ ] ~~sock_send~~ +- [ ] ~~sock_shutdown~~ diff --git a/dg-ui/node_modules/@tailwindcss/oxide-wasm32-wasi/node_modules/@tybys/wasm-util/dist/tsdoc-metadata.json b/dg-ui/node_modules/@tailwindcss/oxide-wasm32-wasi/node_modules/@tybys/wasm-util/dist/tsdoc-metadata.json new file mode 100644 index 0000000..a71c7d9 --- /dev/null +++ b/dg-ui/node_modules/@tailwindcss/oxide-wasm32-wasi/node_modules/@tybys/wasm-util/dist/tsdoc-metadata.json @@ -0,0 +1,11 @@ +// This file is read by tools that parse documentation comments conforming to the TSDoc standard. +// It should be published with your NPM package. It should not be tracked by Git. +{ + "tsdocVersion": "0.12", + "toolPackages": [ + { + "packageName": "@microsoft/api-extractor", + "packageVersion": "7.34.4" + } + ] +} diff --git a/dg-ui/node_modules/@tailwindcss/oxide-wasm32-wasi/node_modules/@tybys/wasm-util/dist/wasm-util.d.ts b/dg-ui/node_modules/@tailwindcss/oxide-wasm32-wasi/node_modules/@tybys/wasm-util/dist/wasm-util.d.ts new file mode 100644 index 0000000..db02e5d --- /dev/null +++ b/dg-ui/node_modules/@tailwindcss/oxide-wasm32-wasi/node_modules/@tybys/wasm-util/dist/wasm-util.d.ts @@ -0,0 +1,423 @@ +/** + * @packageDocumentation + */ + +/** @public */ +export declare class Asyncify { + private value; + private exports; + private dataPtr; + init>>(memory: WebAssembly.Memory, instance: { + readonly exports: T; + }, options: AsyncifyOptions): { + readonly exports: AsyncifyExports; + }; + private assertState; + wrapImportFunction(f: T): T; + wrapImports(imports: T): T; + wrapExportFunction(f: T): AsyncifyExportFunction; + wrapExports(exports: T): AsyncifyExports; + wrapExports>>(exports: T, needWrap: U): AsyncifyExports; +} + +/** @public */ +export declare type AsyncifyExportFunction = T extends Callable ? (...args: Parameters) => Promise> : T; + +/** @public */ +export declare type AsyncifyExportName = 'asyncify_get_state' | 'asyncify_start_unwind' | 'asyncify_stop_unwind' | 'asyncify_start_rewind' | 'asyncify_stop_rewind'; + +/** @public */ +export declare type AsyncifyExports = T extends Record ? { + [P in keyof T]: T[P] extends Callable ? U extends Array> ? P extends U[number] ? AsyncifyExportFunction : T[P] : AsyncifyExportFunction : T[P]; +} : T; + +/** @public */ +export declare function asyncifyLoad(asyncify: AsyncifyOptions, urlOrBuffer: string | URL | BufferSource | WebAssembly.Module, imports?: WebAssembly.Imports): Promise; + +/** @public */ +export declare function asyncifyLoadSync(asyncify: AsyncifyOptions, buffer: BufferSource | WebAssembly.Module, imports?: WebAssembly.Imports): WebAssembly.WebAssemblyInstantiatedSource; + +/** @public */ +export declare interface AsyncifyOptions { + wasm64?: boolean; + tryAllocate?: boolean | { + size?: number; + name?: string; + }; + wrapExports?: string[]; +} + +/** @public */ +export declare interface AsyncWASIOptions extends WASIOptions { + fs: { + promises: IFsPromises; + }; + asyncify?: Asyncify; +} + +/** @public */ +export declare interface BaseEncodingOptions { + encoding?: BufferEncoding_2; +} + +/** @public */ +export declare interface BigIntStats extends StatsBase { +} + +/** @public */ +declare type BufferEncoding_2 = 'ascii' | 'utf8' | 'utf-8' | 'utf16le' | 'ucs2' | 'ucs-2' | 'base64' | 'base64url' | 'latin1' | 'binary' | 'hex'; +export { BufferEncoding_2 as BufferEncoding } + +/** @public */ +export declare type BufferEncodingOption = 'buffer' | { + encoding: 'buffer'; +}; + +/** @public */ +export declare type Callable = (...args: any[]) => any; + +/** @public */ +export declare function createAsyncWASI(options?: AsyncWASIOptions): Promise; + +/** @public */ +export declare function extendMemory(memory: WebAssembly.Memory): Memory; + +/** @public */ +export declare interface FileHandle { + readonly fd: number; + datasync(): Promise; + sync(): Promise; + read(buffer: TBuffer, offset?: number, length?: number, position?: number): Promise<{ + bytesRead: number; + buffer: TBuffer; + }>; + stat(opts?: StatOptions & { + bigint?: false; + }): Promise; + stat(opts: StatOptions & { + bigint: true; + }): Promise; + stat(opts?: StatOptions): Promise; + truncate(len?: number): Promise; + utimes(atime: string | number | Date, mtime: string | number | Date): Promise; + write(buffer: TBuffer, offset?: number, length?: number, position?: number): Promise<{ + bytesWritten: number; + buffer: TBuffer; + }>; + write(data: string | Uint8Array, position?: number, encoding?: BufferEncoding_2): Promise<{ + bytesWritten: number; + buffer: string; + }>; + close(): Promise; +} + +/** @public */ +export declare interface FinalizeBindingsOptions { + memory?: WebAssembly.Memory; +} + +/** @public */ +export declare interface IDirent { + isFile(): boolean; + isDirectory(): boolean; + isBlockDevice(): boolean; + isCharacterDevice(): boolean; + isSymbolicLink(): boolean; + isFIFO(): boolean; + isSocket(): boolean; + name: string; +} + +/** @public */ +export declare interface IFs { + fstatSync(fd: number, options?: StatOptions & { + bigint?: false; + }): Stats; + fstatSync(fd: number, options: StatOptions & { + bigint: true; + }): BigIntStats; + fstatSync(fd: number, options?: StatOptions): Stats | BigIntStats; + statSync(path: PathLike, options?: StatOptions & { + bigint?: false; + }): Stats; + statSync(path: PathLike, options: StatOptions & { + bigint: true; + }): BigIntStats; + statSync(path: PathLike, options?: StatOptions): Stats | BigIntStats; + lstatSync(path: PathLike, options?: StatOptions & { + bigint?: false; + }): Stats; + lstatSync(path: PathLike, options: StatOptions & { + bigint: true; + }): BigIntStats; + lstatSync(path: PathLike, options?: StatOptions): Stats | BigIntStats; + utimesSync(path: PathLike, atime: string | number | Date, mtime: string | number | Date): void; + openSync(path: PathLike, flags: OpenMode, mode?: Mode): number; + readSync(fd: number, buffer: ArrayBufferView, offset: number, length: number, position: number | null): number; + readSync(fd: number, buffer: ArrayBufferView, opts?: ReadSyncOptions): number; + writeSync(fd: number, buffer: ArrayBufferView, offset?: number, length?: number, position?: number): number; + writeSync(fd: number, string: string, position?: number, encoding?: BufferEncoding_2): number; + closeSync(fd: number): void; + readlinkSync(path: PathLike, options?: BaseEncodingOptions | BufferEncoding_2): string; + readlinkSync(path: PathLike, options: BufferEncodingOption): Uint8Array; + readlinkSync(path: PathLike, options?: BaseEncodingOptions | string): string | Uint8Array; + realpathSync(path: PathLike, options?: BaseEncodingOptions | BufferEncoding_2): string; + realpathSync(path: PathLike, options: BufferEncodingOption): Uint8Array; + realpathSync(path: PathLike, options?: BaseEncodingOptions | string): string | Uint8Array; + truncateSync(path: PathLike, len?: number): void; + ftruncateSync(fd: number, len?: number): void; + fdatasyncSync(fd: number): void; + futimesSync(fd: number, atime: string | number | Date, mtime: string | number | Date): void; + readdirSync(path: PathLike, options?: { + encoding: BufferEncoding_2 | null; + withFileTypes?: false; + } | BufferEncoding_2): string[]; + readdirSync(path: PathLike, options: { + encoding: 'buffer'; + withFileTypes?: false; + } | 'buffer'): Uint8Array[]; + readdirSync(path: PathLike, options?: BaseEncodingOptions & { + withFileTypes?: false; + } | BufferEncoding_2): string[] | Uint8Array[]; + readdirSync(path: PathLike, options: BaseEncodingOptions & { + withFileTypes: true; + }): IDirent[]; + fsyncSync(fd: number): void; + mkdirSync(path: PathLike, options: MakeDirectoryOptions & { + recursive: true; + }): string | undefined; + mkdirSync(path: PathLike, options?: Mode | (MakeDirectoryOptions & { + recursive?: false; + })): void; + mkdirSync(path: PathLike, options?: Mode | MakeDirectoryOptions): string | undefined; + rmdirSync(path: PathLike, options?: RmDirOptions): void; + linkSync(existingPath: PathLike, newPath: PathLike): void; + unlinkSync(path: PathLike): void; + renameSync(oldPath: PathLike, newPath: PathLike): void; + symlinkSync(target: PathLike, path: PathLike, type?: 'dir' | 'file' | 'junction'): void; +} + +/** @public */ +export declare interface IFsPromises { + stat(path: PathLike, options?: StatOptions & { + bigint?: false; + }): Promise; + stat(path: PathLike, options: StatOptions & { + bigint: true; + }): Promise; + stat(path: PathLike, options?: StatOptions): Promise; + lstat(path: PathLike, options?: StatOptions & { + bigint?: false; + }): Promise; + lstat(path: PathLike, options: StatOptions & { + bigint: true; + }): Promise; + lstat(path: PathLike, options?: StatOptions): Promise; + utimes(path: PathLike, atime: string | number | Date, mtime: string | number | Date): Promise; + open(path: PathLike, flags: OpenMode, mode?: Mode): Promise; + read(handle: FileHandle, buffer: TBuffer, offset?: number, length?: number, position?: number): Promise<{ + bytesRead: number; + buffer: TBuffer; + }>; + write(handle: FileHandle, buffer: TBuffer, offset?: number, length?: number, position?: number): Promise<{ + bytesWritten: number; + buffer: TBuffer; + }>; + readlink(path: PathLike, options?: BaseEncodingOptions | BufferEncoding_2): Promise; + readlink(path: PathLike, options: BufferEncodingOption): Promise; + readlink(path: PathLike, options?: BaseEncodingOptions | string): Promise; + realpath(path: PathLike, options?: BaseEncodingOptions | BufferEncoding_2): Promise; + realpath(path: PathLike, options: BufferEncodingOption): Promise; + realpath(path: PathLike, options?: BaseEncodingOptions | string): Promise; + truncate(path: PathLike, len?: number): Promise; + ftruncate(handle: FileHandle, len?: number): Promise; + fdatasync(handle: FileHandle): Promise; + futimes(handle: FileHandle, atime: string | number | Date, mtime: string | number | Date): Promise; + readdir(path: PathLike, options?: { + encoding: BufferEncoding_2 | null; + withFileTypes?: false; + } | BufferEncoding_2): Promise; + readdir(path: PathLike, options: { + encoding: 'buffer'; + withFileTypes?: false; + } | 'buffer'): Promise; + readdir(path: PathLike, options?: BaseEncodingOptions & { + withFileTypes?: false; + } | BufferEncoding_2): Promise; + readdir(path: PathLike, options: BaseEncodingOptions & { + withFileTypes: true; + }): Promise; + fsync(handle: FileHandle): Promise; + mkdir(path: PathLike, options: MakeDirectoryOptions & { + recursive: true; + }): Promise; + mkdir(path: PathLike, options?: Mode | (MakeDirectoryOptions & { + recursive?: false; + })): Promise; + mkdir(path: PathLike, options?: Mode | MakeDirectoryOptions): Promise; + rmdir(path: PathLike, options?: RmDirOptions): Promise; + link(existingPath: PathLike, newPath: PathLike): Promise; + unlink(path: PathLike): Promise; + rename(oldPath: PathLike, newPath: PathLike): Promise; + symlink(target: PathLike, path: PathLike, type?: 'dir' | 'file' | 'junction'): Promise; +} + +declare const kBindingName: unique symbol; + +declare const kExitCode: unique symbol; + +declare const kInstance: unique symbol; + +declare const kSetMemory: unique symbol; + +declare const kStarted: unique symbol; + +/** @public */ +export declare function load(wasmInput: string | URL | BufferSource | WebAssembly.Module, imports?: WebAssembly.Imports): Promise; + +/** @public */ +export declare function loadSync(wasmInput: BufferSource | WebAssembly.Module, imports?: WebAssembly.Imports): WebAssembly.WebAssemblyInstantiatedSource; + +/** @public */ +export declare interface MakeDirectoryOptions { + recursive?: boolean; + mode?: Mode; +} + +/** @public */ +export declare class Memory extends WebAssemblyMemory { + constructor(descriptor: WebAssembly.MemoryDescriptor); + get HEAP8(): Int8Array; + get HEAPU8(): Uint8Array; + get HEAP16(): Int16Array; + get HEAPU16(): Uint16Array; + get HEAP32(): Int32Array; + get HEAPU32(): Uint32Array; + get HEAP64(): BigInt64Array; + get HEAPU64(): BigUint64Array; + get HEAPF32(): Float32Array; + get HEAPF64(): Float64Array; + get view(): DataView; +} + +/** @public */ +export declare type Mode = number | string; + +/** @public */ +export declare type OpenMode = number | string; + +/** @public */ +export declare type PathLike = string | Uint8Array | URL; + +/** @public */ +export declare type PromisifyExports = T extends Record ? { + [P in keyof T]: T[P] extends Callable ? U extends Array ? P extends U[number] ? AsyncifyExportFunction : T[P] : AsyncifyExportFunction : T[P]; +} : T; + +/** @public */ +export declare interface ReadSyncOptions { + offset?: number; + length?: number; + position?: number; +} + +/** @public */ +export declare interface RmDirOptions { + maxRetries?: number; + recursive?: boolean; + retryDelay?: number; +} + +/** @public */ +export declare interface StatOptions { + bigint?: boolean; +} + +/** @public */ +export declare interface Stats extends StatsBase { +} + +/** @public */ +export declare interface StatsBase { + isFile(): boolean; + isDirectory(): boolean; + isBlockDevice(): boolean; + isCharacterDevice(): boolean; + isSymbolicLink(): boolean; + isFIFO(): boolean; + isSocket(): boolean; + dev: T; + ino: T; + mode: T; + nlink: T; + uid: T; + gid: T; + rdev: T; + size: T; + blksize: T; + blocks: T; + atimeMs: T; + mtimeMs: T; + ctimeMs: T; + birthtimeMs: T; + atime: Date; + mtime: Date; + ctime: Date; + birthtime: Date; +} + +/** @public */ +export declare interface SyncWASIOptions extends WASIOptions { + fs?: IFs; +} + +/** @public */ +export declare class WASI { + private [kSetMemory]; + private [kStarted]; + private [kExitCode]; + private [kInstance]; + private [kBindingName]; + readonly wasiImport: Record; + constructor(options?: SyncWASIOptions); + finalizeBindings(instance: WebAssembly.Instance, { memory }?: FinalizeBindingsOptions): void; + start(instance: WebAssembly.Instance): number | undefined | Promise | Promise; + initialize(instance: WebAssembly.Instance): void | Promise; + getImportObject(): Record>; +} + +/** @public */ +export declare interface WASIOptions { + version?: 'unstable' | 'preview1'; + args?: string[] | undefined; + env?: Record | undefined; + preopens?: Record | undefined; + /** + * @defaultValue `false` + */ + returnOnExit?: boolean | undefined; + print?: (str: string) => void; + printErr?: (str: string) => void; +} + +/** @public */ +export declare const WebAssemblyMemory: { + new (descriptor: WebAssembly.MemoryDescriptor): WebAssembly.Memory; + prototype: WebAssembly.Memory; +}; + +/** @public */ +export declare function wrapAsyncExport(f: Function): T; + +/** @public */ +export declare function wrapAsyncImport any>(f: T, parameterType: WebAssembly.ValueType[], returnType: WebAssembly.ValueType[]): (...args: [object, ...Parameters]) => ReturnType; + +/** @public */ +export declare function wrapExports(exports: T): PromisifyExports; + +/** @public */ +export declare function wrapExports>(exports: T, needWrap: U): PromisifyExports; + +export { } + +export as namespace wasmUtil; diff --git a/dg-ui/node_modules/@tailwindcss/oxide-wasm32-wasi/node_modules/@tybys/wasm-util/dist/wasm-util.esm-bundler.js b/dg-ui/node_modules/@tailwindcss/oxide-wasm32-wasi/node_modules/@tybys/wasm-util/dist/wasm-util.esm-bundler.js new file mode 100644 index 0000000..a7ed474 --- /dev/null +++ b/dg-ui/node_modules/@tailwindcss/oxide-wasm32-wasi/node_modules/@tybys/wasm-util/dist/wasm-util.esm-bundler.js @@ -0,0 +1,2932 @@ +const _WebAssembly = typeof WebAssembly !== 'undefined' + ? WebAssembly + : typeof WXWebAssembly !== 'undefined' + ? WXWebAssembly + : undefined; +if (!_WebAssembly) { + throw new Error('WebAssembly is not supported in this environment'); +} + +/* eslint-disable spaced-comment */ + +function validateObject(value, name) { + if (value === null || typeof value !== 'object') { + throw new TypeError(`${name} must be an object. Received ${value === null ? 'null' : typeof value}`); + } +} +function validateArray(value, name) { + if (!Array.isArray(value)) { + throw new TypeError(`${name} must be an array. Received ${value === null ? 'null' : typeof value}`); + } +} +function validateBoolean(value, name) { + if (typeof value !== 'boolean') { + throw new TypeError(`${name} must be a boolean. Received ${value === null ? 'null' : typeof value}`); + } +} +function validateString(value, name) { + if (typeof value !== 'string') { + throw new TypeError(`${name} must be a string. Received ${value === null ? 'null' : typeof value}`); + } +} +function validateFunction(value, name) { + if (typeof value !== 'function') { + throw new TypeError(`${name} must be a function. Received ${value === null ? 'null' : typeof value}`); + } +} +function validateUndefined(value, name) { + if (value !== undefined) { + throw new TypeError(`${name} must be undefined. Received ${value === null ? 'null' : typeof value}`); + } +} +function isPromiseLike(obj) { + return !!(obj && (typeof obj === 'object' || typeof obj === 'function') && typeof obj.then === 'function'); +} +function wrapInstanceExports(exports, mapFn) { + const newExports = Object.create(null); + Object.keys(exports).forEach(name => { + const exportValue = exports[name]; + Object.defineProperty(newExports, name, { + enumerable: true, + value: mapFn(exportValue, name) + }); + }); + return newExports; +} +function sleepBreakIf(delay, breakIf) { + const start = Date.now(); + const end = start + delay; + let ret = false; + while (Date.now() < end) { + if (breakIf()) { + ret = true; + break; + } + } + return ret; +} +function unsharedSlice(view, start, end) { + return ((typeof SharedArrayBuffer === 'function' && view.buffer instanceof SharedArrayBuffer) || (Object.prototype.toString.call(view.buffer.constructor) === '[object SharedArrayBuffer]')) + ? view.slice(start, end) + : view.subarray(start, end); +} + +const ignoreNames = [ + 'asyncify_get_state', + 'asyncify_start_rewind', + 'asyncify_start_unwind', + 'asyncify_stop_rewind', + 'asyncify_stop_unwind' +]; +function tryAllocate(instance, wasm64, size, mallocName) { + if (typeof instance.exports[mallocName] !== 'function' || size <= 0) { + return { + wasm64, + dataPtr: 16, + start: wasm64 ? 32 : 24, + end: 1024 + }; + } + const malloc = instance.exports[mallocName]; + const dataPtr = wasm64 ? Number(malloc(BigInt(16) + BigInt(size))) : malloc(8 + size); + if (dataPtr === 0) { + throw new Error('Allocate asyncify data failed'); + } + return wasm64 + ? { wasm64, dataPtr, start: dataPtr + 16, end: dataPtr + 16 + size } + : { wasm64, dataPtr, start: dataPtr + 8, end: dataPtr + 8 + size }; +} +/** @public */ +class Asyncify { + constructor() { + this.value = undefined; + this.exports = undefined; + this.dataPtr = 0; + } + init(memory, instance, options) { + var _a, _b; + if (this.exports) { + throw new Error('Asyncify has been initialized'); + } + if (!(memory instanceof _WebAssembly.Memory)) { + throw new TypeError('Require WebAssembly.Memory object'); + } + const exports = instance.exports; + for (let i = 0; i < ignoreNames.length; ++i) { + if (typeof exports[ignoreNames[i]] !== 'function') { + throw new TypeError('Invalid asyncify wasm'); + } + } + let address; + const wasm64 = Boolean(options.wasm64); + if (!options.tryAllocate) { + address = { + wasm64, + dataPtr: 16, + start: wasm64 ? 32 : 24, + end: 1024 + }; + } + else { + if (options.tryAllocate === true) { + address = tryAllocate(instance, wasm64, 4096, 'malloc'); + } + else { + address = tryAllocate(instance, wasm64, (_a = options.tryAllocate.size) !== null && _a !== void 0 ? _a : 4096, (_b = options.tryAllocate.name) !== null && _b !== void 0 ? _b : 'malloc'); + } + } + this.dataPtr = address.dataPtr; + if (wasm64) { + new BigInt64Array(memory.buffer, this.dataPtr).set([BigInt(address.start), BigInt(address.end)]); + } + else { + new Int32Array(memory.buffer, this.dataPtr).set([address.start, address.end]); + } + this.exports = this.wrapExports(exports, options.wrapExports); + const asyncifiedInstance = Object.create(_WebAssembly.Instance.prototype); + Object.defineProperty(asyncifiedInstance, 'exports', { value: this.exports }); + // Object.setPrototypeOf(instance, Instance.prototype) + return asyncifiedInstance; + } + assertState() { + if (this.exports.asyncify_get_state() !== 0 /* AsyncifyState.NONE */) { + throw new Error('Asyncify state error'); + } + } + wrapImportFunction(f) { + // eslint-disable-next-line @typescript-eslint/no-this-alias + const _this = this; + return (function () { + // eslint-disable-next-line no-unreachable-loop + while (_this.exports.asyncify_get_state() === 2 /* AsyncifyState.REWINDING */) { + _this.exports.asyncify_stop_rewind(); + return _this.value; + } + _this.assertState(); + const v = f.apply(this, arguments); + if (!isPromiseLike(v)) + return v; + _this.exports.asyncify_start_unwind(_this.dataPtr); + _this.value = v; + }); + } + wrapImports(imports) { + const importObject = {}; + Object.keys(imports).forEach(k => { + const mod = imports[k]; + const newModule = {}; + Object.keys(mod).forEach(name => { + const importValue = mod[name]; + if (typeof importValue === 'function') { + newModule[name] = this.wrapImportFunction(importValue); + } + else { + newModule[name] = importValue; + } + }); + importObject[k] = newModule; + }); + return importObject; + } + wrapExportFunction(f) { + // eslint-disable-next-line @typescript-eslint/no-this-alias + const _this = this; + return (async function () { + _this.assertState(); + let ret = f.apply(this, arguments); + while (_this.exports.asyncify_get_state() === 1 /* AsyncifyState.UNWINDING */) { + _this.exports.asyncify_stop_unwind(); + _this.value = await _this.value; + _this.assertState(); + _this.exports.asyncify_start_rewind(_this.dataPtr); + ret = f.call(this); + } + _this.assertState(); + return ret; + }); + } + wrapExports(exports, needWrap) { + return wrapInstanceExports(exports, (exportValue, name) => { + let ignore = ignoreNames.indexOf(name) !== -1 || typeof exportValue !== 'function'; + if (Array.isArray(needWrap)) { + ignore = ignore || (needWrap.indexOf(name) === -1); + } + return ignore ? exportValue : this.wrapExportFunction(exportValue); + }); + } +} + +function validateImports(imports) { + if (imports && typeof imports !== 'object') { + throw new TypeError('imports must be an object or undefined'); + } +} +function fetchWasm(urlOrBuffer, imports) { + if (typeof wx !== 'undefined' && typeof __wxConfig !== 'undefined') { + return _WebAssembly.instantiate(urlOrBuffer, imports); + } + return fetch(urlOrBuffer) + .then(response => response.arrayBuffer()) + .then(buffer => _WebAssembly.instantiate(buffer, imports)); +} +/** @public */ +function load(wasmInput, imports) { + validateImports(imports); + imports = imports !== null && imports !== void 0 ? imports : {}; + let source; + if (wasmInput instanceof ArrayBuffer || ArrayBuffer.isView(wasmInput)) { + return _WebAssembly.instantiate(wasmInput, imports); + } + if (wasmInput instanceof _WebAssembly.Module) { + return _WebAssembly.instantiate(wasmInput, imports).then((instance) => { + return { instance, module: wasmInput }; + }); + } + if (typeof wasmInput !== 'string' && !(wasmInput instanceof URL)) { + throw new TypeError('Invalid source'); + } + if (typeof _WebAssembly.instantiateStreaming === 'function') { + let responsePromise; + try { + responsePromise = fetch(wasmInput); + source = _WebAssembly.instantiateStreaming(responsePromise, imports).catch(() => { + return fetchWasm(wasmInput, imports); + }); + } + catch (_) { + source = fetchWasm(wasmInput, imports); + } + } + else { + source = fetchWasm(wasmInput, imports); + } + return source; +} +/** @public */ +function asyncifyLoad(asyncify, urlOrBuffer, imports) { + validateImports(imports); + imports = imports !== null && imports !== void 0 ? imports : {}; + const asyncifyHelper = new Asyncify(); + imports = asyncifyHelper.wrapImports(imports); + return load(urlOrBuffer, imports).then(source => { + var _a; + const memory = source.instance.exports.memory || ((_a = imports.env) === null || _a === void 0 ? void 0 : _a.memory); + return { module: source.module, instance: asyncifyHelper.init(memory, source.instance, asyncify) }; + }); +} +/** @public */ +function loadSync(wasmInput, imports) { + validateImports(imports); + imports = imports !== null && imports !== void 0 ? imports : {}; + let module; + if ((wasmInput instanceof ArrayBuffer) || ArrayBuffer.isView(wasmInput)) { + module = new _WebAssembly.Module(wasmInput); + } + else if (wasmInput instanceof WebAssembly.Module) { + module = wasmInput; + } + else { + throw new TypeError('Invalid source'); + } + const instance = new _WebAssembly.Instance(module, imports); + const source = { instance, module }; + return source; +} +/** @public */ +function asyncifyLoadSync(asyncify, buffer, imports) { + var _a; + validateImports(imports); + imports = imports !== null && imports !== void 0 ? imports : {}; + const asyncifyHelper = new Asyncify(); + imports = asyncifyHelper.wrapImports(imports); + const source = loadSync(buffer, imports); + const memory = source.instance.exports.memory || ((_a = imports.env) === null || _a === void 0 ? void 0 : _a.memory); + return { module: source.module, instance: asyncifyHelper.init(memory, source.instance, asyncify) }; +} + +const CHAR_DOT = 46; /* . */ +const CHAR_FORWARD_SLASH = 47; /* / */ +const CHAR_BACKWARD_SLASH = 92; /* \ */ +const CHAR_COLON = 58; /* : */ +const CHAR_UPPERCASE_A = 65; /* A */ +const CHAR_UPPERCASE_Z = 90; /* Z */ +const CHAR_LOWERCASE_A = 97; /* a */ +const CHAR_LOWERCASE_Z = 122; /* z */ +function isPathSeparatorWin(code) { + return code === CHAR_FORWARD_SLASH || code === CHAR_BACKWARD_SLASH; +} +function isWindowsDeviceRoot(code) { + return (code >= CHAR_UPPERCASE_A && code <= CHAR_UPPERCASE_Z) || + (code >= CHAR_LOWERCASE_A && code <= CHAR_LOWERCASE_Z); +} +const _isWin32 = typeof process !== 'undefined' && process.platform === 'win32'; +/** + * Windows variant of `resolve()`. Mirrors Node's `path.win32.resolve` + * semantics enough for the WASI shim's needs (drive-letter absolutes + * + UNC paths + per-drive cwd lookups via `process.env`/`process.cwd`). + * + * Why this is needed: on Windows, `FileDescriptor.realPath` is the + * host realpath returned by `fs.realpathSync(realPath, 'utf8')` — the + * backslash form `D:\…`. The POSIX-only `resolveImpl` below only + * treats `/` as a separator, reads `D` as non-`/`, decides realPath + * is "relative", and produces a garbage joined path. Downstream + * `fs.openSync(garbage)` then returns `EINVAL` and the WASI caller + * sees a permanent failure. This function gives us the correct + * Windows-style resolution without taking a Node-only `path` import + * (which would break browser bundles of this package). + * + * Cribbed from Node's `lib/path.js` `win32.resolve()` (MIT-licensed), + * trimmed to what WASI realpath resolution actually exercises. + */ +function resolveWin32(args) { + let resolvedDevice = ''; + let resolvedTail = ''; + let resolvedAbsolute = false; + for (let i = args.length - 1; i >= -1; i--) { + let path; + if (i >= 0) { + path = args[i]; + validateString(path, 'path'); + if (path.length === 0) + continue; + } + else if (resolvedDevice.length === 0) { + path = (typeof process !== 'undefined' && typeof process.cwd === 'function') + ? process.cwd() + : ''; + } + else { + // Look up per-drive cwd via the `=X:` env var convention; fall back + // to the global cwd if absent. + const envKey = `=${resolvedDevice}`; + const env = (typeof process !== 'undefined') ? process.env : undefined; + path = (env && typeof env[envKey] === 'string') + ? env[envKey] + : (typeof process !== 'undefined' && typeof process.cwd === 'function') + ? process.cwd() + : ''; + if (path === undefined || + (path.slice(0, 2).toLowerCase() !== resolvedDevice.toLowerCase() && + path.charCodeAt(2) === CHAR_BACKWARD_SLASH)) { + path = `${resolvedDevice}\\`; + } + } + const len = path.length; + let rootEnd = 0; + let device = ''; + let isAbsolute = false; + const code = path.charCodeAt(0); + if (len === 1) { + if (isPathSeparatorWin(code)) { + rootEnd = 1; + isAbsolute = true; + } + } + else if (isPathSeparatorWin(code)) { + isAbsolute = true; + if (isPathSeparatorWin(path.charCodeAt(1))) { + // UNC path: `\\server\share\…` + let j = 2; + let last = j; + while (j < len && !isPathSeparatorWin(path.charCodeAt(j))) + j++; + if (j < len && j !== last) { + const firstPart = path.slice(last, j); + last = j; + while (j < len && isPathSeparatorWin(path.charCodeAt(j))) + j++; + if (j < len && j !== last) { + last = j; + while (j < len && !isPathSeparatorWin(path.charCodeAt(j))) + j++; + if (j === len || j !== last) { + device = `\\\\${firstPart}\\${path.slice(last, j)}`; + rootEnd = j; + } + } + } + } + else { + rootEnd = 1; + } + } + else if (isWindowsDeviceRoot(code) && path.charCodeAt(1) === CHAR_COLON) { + device = path.slice(0, 2); + rootEnd = 2; + if (len > 2 && isPathSeparatorWin(path.charCodeAt(2))) { + isAbsolute = true; + rootEnd = 3; + } + } + if (device.length > 0) { + if (resolvedDevice.length > 0) { + if (device.toLowerCase() !== resolvedDevice.toLowerCase()) + continue; + } + else { + resolvedDevice = device; + } + } + if (resolvedAbsolute) { + if (resolvedDevice.length > 0) + break; + } + else { + resolvedTail = `${path.slice(rootEnd)}\\${resolvedTail}`; + resolvedAbsolute = isAbsolute; + if (isAbsolute && resolvedDevice.length > 0) + break; + } + } + resolvedTail = normalizeString(resolvedTail, !resolvedAbsolute, '\\', isPathSeparatorWin); + return resolvedDevice + (resolvedAbsolute ? '\\' : '') + resolvedTail || '.'; +} +function isPosixPathSeparator(code) { + return code === CHAR_FORWARD_SLASH; +} +function normalizeString(path, allowAboveRoot, separator, isPathSeparator) { + let res = ''; + let lastSegmentLength = 0; + let lastSlash = -1; + let dots = 0; + let code = 0; + for (let i = 0; i <= path.length; ++i) { + if (i < path.length) { + code = path.charCodeAt(i); + } + else if (isPathSeparator(code)) { + break; + } + else { + code = CHAR_FORWARD_SLASH; + } + if (isPathSeparator(code)) { + if (lastSlash === i - 1 || dots === 1) ; + else if (dots === 2) { + if (res.length < 2 || lastSegmentLength !== 2 || + res.charCodeAt(res.length - 1) !== CHAR_DOT || + res.charCodeAt(res.length - 2) !== CHAR_DOT) { + if (res.length > 2) { + const lastSlashIndex = res.indexOf(separator); + if (lastSlashIndex === -1) { + res = ''; + lastSegmentLength = 0; + } + else { + res = res.slice(0, lastSlashIndex); + lastSegmentLength = + res.length - 1 - res.indexOf(separator); + } + lastSlash = i; + dots = 0; + continue; + } + else if (res.length !== 0) { + res = ''; + lastSegmentLength = 0; + lastSlash = i; + dots = 0; + continue; + } + } + if (allowAboveRoot) { + res += res.length > 0 ? `${separator}..` : '..'; + lastSegmentLength = 2; + } + } + else { + if (res.length > 0) { + res += `${separator}${path.slice(lastSlash + 1, i)}`; + } + else { + res = path.slice(lastSlash + 1, i); + } + lastSegmentLength = i - lastSlash - 1; + } + lastSlash = i; + dots = 0; + } + else if (code === CHAR_DOT && dots !== -1) { + ++dots; + } + else { + dots = -1; + } + } + return res; +} +function resolve(...args) { + // On Windows, host paths are `D:\…` style. The POSIX-only resolver + // below treats `D` as a non-`/` character and produces garbage; route + // to the Windows-aware variant. POSIX hosts (Linux/macOS/browser) + // run the original code path unchanged — `_isWin32` is constant-folded + // away on those targets. + if (_isWin32) + return resolveWin32(args); + let resolvedPath = ''; + let resolvedAbsolute = false; + for (let i = args.length - 1; i >= -1 && !resolvedAbsolute; i--) { + const path = i >= 0 ? args[i] : '/'; + validateString(path, 'path'); + // Skip empty entries + if (path.length === 0) { + continue; + } + resolvedPath = `${path}/${resolvedPath}`; + resolvedAbsolute = path.charCodeAt(0) === CHAR_FORWARD_SLASH; + } + // At this point the path should be resolved to a full absolute path, but + // handle relative paths to be safe (might happen when process.cwd() fails) + // Normalize the path + resolvedPath = normalizeString(resolvedPath, !resolvedAbsolute, '/', isPosixPathSeparator); + if (resolvedAbsolute) { + return `/${resolvedPath}`; + } + return resolvedPath.length > 0 ? resolvedPath : '.'; +} + +const FD_DATASYNC = ( /*#__PURE__*/BigInt(1) << /*#__PURE__*/ BigInt(0)); +const FD_READ = ( /*#__PURE__*/BigInt(1) << /*#__PURE__*/ BigInt(1)); +const FD_SEEK = ( /*#__PURE__*/BigInt(1) << /*#__PURE__*/ BigInt(2)); +const FD_FDSTAT_SET_FLAGS = ( /*#__PURE__*/BigInt(1) << /*#__PURE__*/ BigInt(3)); +const FD_SYNC = ( /*#__PURE__*/BigInt(1) << /*#__PURE__*/ BigInt(4)); +const FD_TELL = ( /*#__PURE__*/BigInt(1) << /*#__PURE__*/ BigInt(5)); +const FD_WRITE = ( /*#__PURE__*/BigInt(1) << /*#__PURE__*/ BigInt(6)); +const FD_ADVISE = ( /*#__PURE__*/BigInt(1) << /*#__PURE__*/ BigInt(7)); +const FD_ALLOCATE = ( /*#__PURE__*/BigInt(1) << /*#__PURE__*/ BigInt(8)); +const PATH_CREATE_DIRECTORY = ( /*#__PURE__*/BigInt(1) << /*#__PURE__*/ BigInt(9)); +const PATH_CREATE_FILE = ( /*#__PURE__*/BigInt(1) << /*#__PURE__*/ BigInt(10)); +const PATH_LINK_SOURCE = ( /*#__PURE__*/BigInt(1) << /*#__PURE__*/ BigInt(11)); +const PATH_LINK_TARGET = ( /*#__PURE__*/BigInt(1) << /*#__PURE__*/ BigInt(12)); +const PATH_OPEN = ( /*#__PURE__*/BigInt(1) << /*#__PURE__*/ BigInt(13)); +const FD_READDIR = ( /*#__PURE__*/BigInt(1) << /*#__PURE__*/ BigInt(14)); +const PATH_READLINK = ( /*#__PURE__*/BigInt(1) << /*#__PURE__*/ BigInt(15)); +const PATH_RENAME_SOURCE = ( /*#__PURE__*/BigInt(1) << /*#__PURE__*/ BigInt(16)); +const PATH_RENAME_TARGET = ( /*#__PURE__*/BigInt(1) << /*#__PURE__*/ BigInt(17)); +const PATH_FILESTAT_GET = ( /*#__PURE__*/BigInt(1) << /*#__PURE__*/ BigInt(18)); +const PATH_FILESTAT_SET_SIZE = ( /*#__PURE__*/BigInt(1) << /*#__PURE__*/ BigInt(19)); +const PATH_FILESTAT_SET_TIMES = ( /*#__PURE__*/BigInt(1) << /*#__PURE__*/ BigInt(20)); +const FD_FILESTAT_GET = ( /*#__PURE__*/BigInt(1) << /*#__PURE__*/ BigInt(21)); +const FD_FILESTAT_SET_SIZE = ( /*#__PURE__*/BigInt(1) << /*#__PURE__*/ BigInt(22)); +const FD_FILESTAT_SET_TIMES = ( /*#__PURE__*/BigInt(1) << /*#__PURE__*/ BigInt(23)); +const PATH_SYMLINK = ( /*#__PURE__*/BigInt(1) << /*#__PURE__*/ BigInt(24)); +const PATH_REMOVE_DIRECTORY = ( /*#__PURE__*/BigInt(1) << /*#__PURE__*/ BigInt(25)); +const PATH_UNLINK_FILE = ( /*#__PURE__*/BigInt(1) << /*#__PURE__*/ BigInt(26)); +const POLL_FD_READWRITE = ( /*#__PURE__*/BigInt(1) << /*#__PURE__*/ BigInt(27)); +const SOCK_SHUTDOWN = ( /*#__PURE__*/BigInt(1) << /*#__PURE__*/ BigInt(28)); +const SOCK_ACCEPT = ( /*#__PURE__*/BigInt(1) << /*#__PURE__*/ BigInt(29)); +const WasiRights = { + FD_DATASYNC, + FD_READ, + FD_SEEK, + FD_FDSTAT_SET_FLAGS, + FD_SYNC, + FD_TELL, + FD_WRITE, + FD_ADVISE, + FD_ALLOCATE, + PATH_CREATE_DIRECTORY, + PATH_CREATE_FILE, + PATH_LINK_SOURCE, + PATH_LINK_TARGET, + PATH_OPEN, + FD_READDIR, + PATH_READLINK, + PATH_RENAME_SOURCE, + PATH_RENAME_TARGET, + PATH_FILESTAT_GET, + PATH_FILESTAT_SET_SIZE, + PATH_FILESTAT_SET_TIMES, + FD_FILESTAT_GET, + FD_FILESTAT_SET_SIZE, + FD_FILESTAT_SET_TIMES, + PATH_SYMLINK, + PATH_REMOVE_DIRECTORY, + PATH_UNLINK_FILE, + POLL_FD_READWRITE, + SOCK_SHUTDOWN, + SOCK_ACCEPT +}; + +function strerror(errno) { + switch (errno) { + case 0 /* WasiErrno.ESUCCESS */: return 'Success'; + case 1 /* WasiErrno.E2BIG */: return 'Argument list too long'; + case 2 /* WasiErrno.EACCES */: return 'Permission denied'; + case 3 /* WasiErrno.EADDRINUSE */: return 'Address in use'; + case 4 /* WasiErrno.EADDRNOTAVAIL */: return 'Address not available'; + case 5 /* WasiErrno.EAFNOSUPPORT */: return 'Address family not supported by protocol'; + case 6 /* WasiErrno.EAGAIN */: return 'Resource temporarily unavailable'; + case 7 /* WasiErrno.EALREADY */: return 'Operation already in progress'; + case 8 /* WasiErrno.EBADF */: return 'Bad file descriptor'; + case 9 /* WasiErrno.EBADMSG */: return 'Bad message'; + case 10 /* WasiErrno.EBUSY */: return 'Resource busy'; + case 11 /* WasiErrno.ECANCELED */: return 'Operation canceled'; + case 12 /* WasiErrno.ECHILD */: return 'No child process'; + case 13 /* WasiErrno.ECONNABORTED */: return 'Connection aborted'; + case 14 /* WasiErrno.ECONNREFUSED */: return 'Connection refused'; + case 15 /* WasiErrno.ECONNRESET */: return 'Connection reset by peer'; + case 16 /* WasiErrno.EDEADLK */: return 'Resource deadlock would occur'; + case 17 /* WasiErrno.EDESTADDRREQ */: return 'Destination address required'; + case 18 /* WasiErrno.EDOM */: return 'Domain error'; + case 19 /* WasiErrno.EDQUOT */: return 'Quota exceeded'; + case 20 /* WasiErrno.EEXIST */: return 'File exists'; + case 21 /* WasiErrno.EFAULT */: return 'Bad address'; + case 22 /* WasiErrno.EFBIG */: return 'File too large'; + case 23 /* WasiErrno.EHOSTUNREACH */: return 'Host is unreachable'; + case 24 /* WasiErrno.EIDRM */: return 'Identifier removed'; + case 25 /* WasiErrno.EILSEQ */: return 'Illegal byte sequence'; + case 26 /* WasiErrno.EINPROGRESS */: return 'Operation in progress'; + case 27 /* WasiErrno.EINTR */: return 'Interrupted system call'; + case 28 /* WasiErrno.EINVAL */: return 'Invalid argument'; + case 29 /* WasiErrno.EIO */: return 'I/O error'; + case 30 /* WasiErrno.EISCONN */: return 'Socket is connected'; + case 31 /* WasiErrno.EISDIR */: return 'Is a directory'; + case 32 /* WasiErrno.ELOOP */: return 'Symbolic link loop'; + case 33 /* WasiErrno.EMFILE */: return 'No file descriptors available'; + case 34 /* WasiErrno.EMLINK */: return 'Too many links'; + case 35 /* WasiErrno.EMSGSIZE */: return 'Message too large'; + case 36 /* WasiErrno.EMULTIHOP */: return 'Multihop attempted'; + case 37 /* WasiErrno.ENAMETOOLONG */: return 'Filename too long'; + case 38 /* WasiErrno.ENETDOWN */: return 'Network is down'; + case 39 /* WasiErrno.ENETRESET */: return 'Connection reset by network'; + case 40 /* WasiErrno.ENETUNREACH */: return 'Network unreachable'; + case 41 /* WasiErrno.ENFILE */: return 'Too many files open in system'; + case 42 /* WasiErrno.ENOBUFS */: return 'No buffer space available'; + case 43 /* WasiErrno.ENODEV */: return 'No such device'; + case 44 /* WasiErrno.ENOENT */: return 'No such file or directory'; + case 45 /* WasiErrno.ENOEXEC */: return 'Exec format error'; + case 46 /* WasiErrno.ENOLCK */: return 'No locks available'; + case 47 /* WasiErrno.ENOLINK */: return 'Link has been severed'; + case 48 /* WasiErrno.ENOMEM */: return 'Out of memory'; + case 49 /* WasiErrno.ENOMSG */: return 'No message of the desired type'; + case 50 /* WasiErrno.ENOPROTOOPT */: return 'Protocol not available'; + case 51 /* WasiErrno.ENOSPC */: return 'No space left on device'; + case 52 /* WasiErrno.ENOSYS */: return 'Function not implemented'; + case 53 /* WasiErrno.ENOTCONN */: return 'Socket not connected'; + case 54 /* WasiErrno.ENOTDIR */: return 'Not a directory'; + case 55 /* WasiErrno.ENOTEMPTY */: return 'Directory not empty'; + case 56 /* WasiErrno.ENOTRECOVERABLE */: return 'State not recoverable'; + case 57 /* WasiErrno.ENOTSOCK */: return 'Not a socket'; + case 58 /* WasiErrno.ENOTSUP */: return 'Not supported'; + case 59 /* WasiErrno.ENOTTY */: return 'Not a tty'; + case 60 /* WasiErrno.ENXIO */: return 'No such device or address'; + case 61 /* WasiErrno.EOVERFLOW */: return 'Value too large for data type'; + case 62 /* WasiErrno.EOWNERDEAD */: return 'Previous owner died'; + case 63 /* WasiErrno.EPERM */: return 'Operation not permitted'; + case 64 /* WasiErrno.EPIPE */: return 'Broken pipe'; + case 65 /* WasiErrno.EPROTO */: return 'Protocol error'; + case 66 /* WasiErrno.EPROTONOSUPPORT */: return 'Protocol not supported'; + case 67 /* WasiErrno.EPROTOTYPE */: return 'Protocol wrong type for socket'; + case 68 /* WasiErrno.ERANGE */: return 'Result not representable'; + case 69 /* WasiErrno.EROFS */: return 'Read-only file system'; + case 70 /* WasiErrno.ESPIPE */: return 'Invalid seek'; + case 71 /* WasiErrno.ESRCH */: return 'No such process'; + case 72 /* WasiErrno.ESTALE */: return 'Stale file handle'; + case 73 /* WasiErrno.ETIMEDOUT */: return 'Operation timed out'; + case 74 /* WasiErrno.ETXTBSY */: return 'Text file busy'; + case 75 /* WasiErrno.EXDEV */: return 'Cross-device link'; + case 76 /* WasiErrno.ENOTCAPABLE */: return 'Capabilities insufficient'; + default: return 'Unknown error'; + } +} +class WasiError extends Error { + constructor(message, errno) { + super(message); + this.errno = errno; + } + getErrorMessage() { + return strerror(this.errno); + } +} +Object.defineProperty(WasiError.prototype, 'name', { + configurable: true, + writable: true, + value: 'WasiError' +}); + +const RIGHTS_ALL = WasiRights.FD_DATASYNC | + WasiRights.FD_READ | + WasiRights.FD_SEEK | + WasiRights.FD_FDSTAT_SET_FLAGS | + WasiRights.FD_SYNC | + WasiRights.FD_TELL | + WasiRights.FD_WRITE | + WasiRights.FD_ADVISE | + WasiRights.FD_ALLOCATE | + WasiRights.PATH_CREATE_DIRECTORY | + WasiRights.PATH_CREATE_FILE | + WasiRights.PATH_LINK_SOURCE | + WasiRights.PATH_LINK_TARGET | + WasiRights.PATH_OPEN | + WasiRights.FD_READDIR | + WasiRights.PATH_READLINK | + WasiRights.PATH_RENAME_SOURCE | + WasiRights.PATH_RENAME_TARGET | + WasiRights.PATH_FILESTAT_GET | + WasiRights.PATH_FILESTAT_SET_SIZE | + WasiRights.PATH_FILESTAT_SET_TIMES | + WasiRights.FD_FILESTAT_GET | + WasiRights.FD_FILESTAT_SET_TIMES | + WasiRights.FD_FILESTAT_SET_SIZE | + WasiRights.PATH_SYMLINK | + WasiRights.PATH_UNLINK_FILE | + WasiRights.PATH_REMOVE_DIRECTORY | + WasiRights.POLL_FD_READWRITE | + WasiRights.SOCK_SHUTDOWN | + WasiRights.SOCK_ACCEPT; +const BLOCK_DEVICE_BASE = RIGHTS_ALL; +const BLOCK_DEVICE_INHERITING = RIGHTS_ALL; +const CHARACTER_DEVICE_BASE = RIGHTS_ALL; +const CHARACTER_DEVICE_INHERITING = RIGHTS_ALL; +const REGULAR_FILE_BASE = WasiRights.FD_DATASYNC | + WasiRights.FD_READ | + WasiRights.FD_SEEK | + WasiRights.FD_FDSTAT_SET_FLAGS | + WasiRights.FD_SYNC | + WasiRights.FD_TELL | + WasiRights.FD_WRITE | + WasiRights.FD_ADVISE | + WasiRights.FD_ALLOCATE | + WasiRights.FD_FILESTAT_GET | + WasiRights.FD_FILESTAT_SET_SIZE | + WasiRights.FD_FILESTAT_SET_TIMES | + WasiRights.POLL_FD_READWRITE; +const REGULAR_FILE_INHERITING = /*#__PURE__*/ BigInt(0); +const DIRECTORY_BASE = WasiRights.FD_FDSTAT_SET_FLAGS | + WasiRights.FD_SYNC | + WasiRights.FD_ADVISE | + WasiRights.PATH_CREATE_DIRECTORY | + WasiRights.PATH_CREATE_FILE | + WasiRights.PATH_LINK_SOURCE | + WasiRights.PATH_LINK_TARGET | + WasiRights.PATH_OPEN | + WasiRights.FD_READDIR | + WasiRights.PATH_READLINK | + WasiRights.PATH_RENAME_SOURCE | + WasiRights.PATH_RENAME_TARGET | + WasiRights.PATH_FILESTAT_GET | + WasiRights.PATH_FILESTAT_SET_SIZE | + WasiRights.PATH_FILESTAT_SET_TIMES | + WasiRights.FD_FILESTAT_GET | + WasiRights.FD_FILESTAT_SET_TIMES | + WasiRights.PATH_SYMLINK | + WasiRights.PATH_UNLINK_FILE | + WasiRights.PATH_REMOVE_DIRECTORY | + WasiRights.POLL_FD_READWRITE; +const DIRECTORY_INHERITING = DIRECTORY_BASE | REGULAR_FILE_BASE; +const SOCKET_BASE = (WasiRights.FD_READ | + WasiRights.FD_FDSTAT_SET_FLAGS | + WasiRights.FD_WRITE | + WasiRights.FD_FILESTAT_GET | + WasiRights.POLL_FD_READWRITE | + WasiRights.SOCK_SHUTDOWN); +const SOCKET_INHERITING = RIGHTS_ALL; +const TTY_BASE = WasiRights.FD_READ | + WasiRights.FD_FDSTAT_SET_FLAGS | + WasiRights.FD_WRITE | + WasiRights.FD_FILESTAT_GET | + WasiRights.POLL_FD_READWRITE; +const TTY_INHERITING = /*#__PURE__*/ BigInt(0); +function getRights(stdio, fd, flags, type) { + const ret = { + base: BigInt(0), + inheriting: BigInt(0) + }; + if (type === 0 /* WasiFileType.UNKNOWN */) { + throw new WasiError('Unknown file type', 28 /* WasiErrno.EINVAL */); + } + switch (type) { + case 4 /* WasiFileType.REGULAR_FILE */: + ret.base = REGULAR_FILE_BASE; + ret.inheriting = REGULAR_FILE_INHERITING; + break; + case 3 /* WasiFileType.DIRECTORY */: + ret.base = DIRECTORY_BASE; + ret.inheriting = DIRECTORY_INHERITING; + break; + case 6 /* WasiFileType.SOCKET_STREAM */: + case 5 /* WasiFileType.SOCKET_DGRAM */: + ret.base = SOCKET_BASE; + ret.inheriting = SOCKET_INHERITING; + break; + case 2 /* WasiFileType.CHARACTER_DEVICE */: + if (stdio.indexOf(fd) !== -1) { + ret.base = TTY_BASE; + ret.inheriting = TTY_INHERITING; + } + else { + ret.base = CHARACTER_DEVICE_BASE; + ret.inheriting = CHARACTER_DEVICE_INHERITING; + } + break; + case 1 /* WasiFileType.BLOCK_DEVICE */: + ret.base = BLOCK_DEVICE_BASE; + ret.inheriting = BLOCK_DEVICE_INHERITING; + break; + default: + ret.base = BigInt(0); + ret.inheriting = BigInt(0); + } + /* Disable read/write bits depending on access mode. */ + const read_or_write_only = flags & (0 | 1 | 2); + if (read_or_write_only === 0) { + ret.base &= ~WasiRights.FD_WRITE; + } + else if (read_or_write_only === 1) { + ret.base &= ~WasiRights.FD_READ; + } + return ret; +} + +function concatBuffer(buffers, size) { + let total = 0; + if (typeof size === 'number' && size >= 0) { + total = size; + } + else { + for (let i = 0; i < buffers.length; i++) { + const buffer = buffers[i]; + total += buffer.length; + } + } + let pos = 0; + const ret = new Uint8Array(total); + for (let i = 0; i < buffers.length; i++) { + const buffer = buffers[i]; + ret.set(buffer, pos); + pos += buffer.length; + } + return ret; +} +class FileDescriptor { + constructor(id, fd, path, realPath, type, rightsBase, rightsInheriting, preopen) { + this.id = id; + this.fd = fd; + this.path = path; + this.realPath = realPath; + this.type = type; + this.rightsBase = rightsBase; + this.rightsInheriting = rightsInheriting; + this.preopen = preopen; + this.pos = BigInt(0); + this.size = BigInt(0); + } + seek(offset, whence) { + if (whence === 0 /* WasiWhence.SET */) { + this.pos = BigInt(offset); + } + else if (whence === 1 /* WasiWhence.CUR */) { + this.pos += BigInt(offset); + } + else if (whence === 2 /* WasiWhence.END */) { + this.pos = BigInt(this.size) - BigInt(offset); + } + else { + throw new WasiError('Unknown whence', 29 /* WasiErrno.EIO */); + } + return this.pos; + } +} +class StandardOutput extends FileDescriptor { + constructor(log, id, fd, path, realPath, type, rightsBase, rightsInheriting, preopen) { + super(id, fd, path, realPath, type, rightsBase, rightsInheriting, preopen); + this._log = log; + this._buf = null; + } + write(buffer) { + const originalBuffer = buffer; + if (this._buf) { + buffer = concatBuffer([this._buf, buffer]); + this._buf = null; + } + if (buffer.indexOf(10) === -1) { + this._buf = buffer; + return originalBuffer.byteLength; + } + let written = 0; + let lastBegin = 0; + let index; + while ((index = buffer.indexOf(10, written)) !== -1) { + const str = new TextDecoder().decode(buffer.subarray(lastBegin, index)); + this._log(str); + written += index - lastBegin + 1; + lastBegin = index + 1; + } + if (written < buffer.length) { + this._buf = buffer.slice(written); + } + return originalBuffer.byteLength; + } +} +function toFileType(stat) { + if (stat.isBlockDevice()) + return 1 /* WasiFileType.BLOCK_DEVICE */; + if (stat.isCharacterDevice()) + return 2 /* WasiFileType.CHARACTER_DEVICE */; + if (stat.isDirectory()) + return 3 /* WasiFileType.DIRECTORY */; + if (stat.isSocket()) + return 6 /* WasiFileType.SOCKET_STREAM */; + if (stat.isFile()) + return 4 /* WasiFileType.REGULAR_FILE */; + if (stat.isSymbolicLink()) + return 7 /* WasiFileType.SYMBOLIC_LINK */; + return 0 /* WasiFileType.UNKNOWN */; +} +function toFileStat(view, buf, stat) { + view.setBigUint64(buf, stat.dev, true); + view.setBigUint64(buf + 8, stat.ino, true); + view.setBigUint64(buf + 16, BigInt(toFileType(stat)), true); + view.setBigUint64(buf + 24, stat.nlink, true); + view.setBigUint64(buf + 32, stat.size, true); + view.setBigUint64(buf + 40, stat.atimeMs * BigInt(1000000), true); + view.setBigUint64(buf + 48, stat.mtimeMs * BigInt(1000000), true); + view.setBigUint64(buf + 56, stat.ctimeMs * BigInt(1000000), true); +} +class FileDescriptorTable { + constructor(options) { + this.used = 0; + this.size = options.size; + this.fds = Array(options.size); + this.stdio = [options.in, options.out, options.err]; + this.print = options.print; + this.printErr = options.printErr; + this.insertStdio(options.in, 0, ''); + this.insertStdio(options.out, 1, ''); + this.insertStdio(options.err, 2, ''); + } + insertStdio(fd, expected, name) { + const type = 2 /* WasiFileType.CHARACTER_DEVICE */; + const { base, inheriting } = getRights(this.stdio, fd, 2 /* FileControlFlag.O_RDWR */, type); + const wrap = this.insert(fd, name, name, type, base, inheriting, 0); + if (wrap.id !== expected) { + throw new WasiError(`id: ${wrap.id} !== expected: ${expected}`, 8 /* WasiErrno.EBADF */); + } + return wrap; + } + insert(fd, mappedPath, realPath, type, rightsBase, rightsInheriting, preopen) { + var _a, _b; + let index = -1; + if (this.used >= this.size) { + const newSize = this.size * 2; + this.fds.length = newSize; + index = this.size; + this.size = newSize; + } + else { + for (let i = 0; i < this.size; ++i) { + if (this.fds[i] == null) { + index = i; + break; + } + } + } + let entry; + if (mappedPath === '') { + entry = new StandardOutput((_a = this.print) !== null && _a !== void 0 ? _a : console.log, index, fd, mappedPath, realPath, type, rightsBase, rightsInheriting, preopen); + } + else if (mappedPath === '') { + entry = new StandardOutput((_b = this.printErr) !== null && _b !== void 0 ? _b : console.error, index, fd, mappedPath, realPath, type, rightsBase, rightsInheriting, preopen); + } + else { + entry = new FileDescriptor(index, fd, mappedPath, realPath, type, rightsBase, rightsInheriting, preopen); + } + this.fds[index] = entry; + this.used++; + return entry; + } + get(id, base, inheriting) { + if (id >= this.size) { + throw new WasiError('Invalid fd', 8 /* WasiErrno.EBADF */); + } + const entry = this.fds[id]; + if (!entry || entry.id !== id) { + throw new WasiError('Bad file descriptor', 8 /* WasiErrno.EBADF */); + } + /* Validate that the fd has the necessary rights. */ + if ((~entry.rightsBase & base) !== BigInt(0) || (~entry.rightsInheriting & inheriting) !== BigInt(0)) { + throw new WasiError('Capabilities insufficient', 76 /* WasiErrno.ENOTCAPABLE */); + } + return entry; + } + remove(id) { + if (id >= this.size) { + throw new WasiError('Invalid fd', 8 /* WasiErrno.EBADF */); + } + const entry = this.fds[id]; + if (!entry || entry.id !== id) { + throw new WasiError('Bad file descriptor', 8 /* WasiErrno.EBADF */); + } + this.fds[id] = undefined; + this.used--; + } +} +class SyncTable extends FileDescriptorTable { + constructor(options) { + super(options); + this.fs = options.fs; + } + getFileTypeByFd(fd) { + const stats = this.fs.fstatSync(fd, { bigint: true }); + return toFileType(stats); + } + insertPreopen(fd, mappedPath, realPath) { + const type = this.getFileTypeByFd(fd); + if (type !== 3 /* WasiFileType.DIRECTORY */) { + throw new WasiError(`Preopen not dir: ["${mappedPath}", "${realPath}"]`, 54 /* WasiErrno.ENOTDIR */); + } + const result = getRights(this.stdio, fd, 0, type); + return this.insert(fd, mappedPath, realPath, type, result.base, result.inheriting, 1); + } + renumber(dst, src) { + if (dst === src) + return; + if (dst >= this.size || src >= this.size) { + throw new WasiError('Invalid fd', 8 /* WasiErrno.EBADF */); + } + const dstEntry = this.fds[dst]; + const srcEntry = this.fds[src]; + if (!dstEntry || !srcEntry || dstEntry.id !== dst || srcEntry.id !== src) { + throw new WasiError('Invalid fd', 8 /* WasiErrno.EBADF */); + } + this.fs.closeSync(dstEntry.fd); + this.fds[dst] = this.fds[src]; + this.fds[dst].id = dst; + this.fds[src] = undefined; + this.used--; + } +} +class AsyncTable extends FileDescriptorTable { + // eslint-disable-next-line @typescript-eslint/no-useless-constructor + constructor(options) { + super(options); + } + async getFileTypeByFd(fd) { + const stats = await fd.stat({ bigint: true }); + return toFileType(stats); + } + async insertPreopen(fd, mappedPath, realPath) { + const type = await this.getFileTypeByFd(fd); + if (type !== 3 /* WasiFileType.DIRECTORY */) { + throw new WasiError(`Preopen not dir: ["${mappedPath}", "${realPath}"]`, 54 /* WasiErrno.ENOTDIR */); + } + const result = getRights(this.stdio, fd.fd, 0, type); + return this.insert(fd, mappedPath, realPath, type, result.base, result.inheriting, 1); + } + async renumber(dst, src) { + if (dst === src) + return; + if (dst >= this.size || src >= this.size) { + throw new WasiError('Invalid fd', 8 /* WasiErrno.EBADF */); + } + const dstEntry = this.fds[dst]; + const srcEntry = this.fds[src]; + if (!dstEntry || !srcEntry || dstEntry.id !== dst || srcEntry.id !== src) { + throw new WasiError('Invalid fd', 8 /* WasiErrno.EBADF */); + } + await dstEntry.fd.close(); + this.fds[dst] = this.fds[src]; + this.fds[dst].id = dst; + this.fds[src] = undefined; + this.used--; + } +} + +/** @public */ +const WebAssemblyMemory = /*#__PURE__*/ (function () { return _WebAssembly.Memory; })(); +/** @public */ +class Memory extends WebAssemblyMemory { + // eslint-disable-next-line @typescript-eslint/no-useless-constructor + constructor(descriptor) { + super(descriptor); + } + get HEAP8() { return new Int8Array(super.buffer); } + get HEAPU8() { return new Uint8Array(super.buffer); } + get HEAP16() { return new Int16Array(super.buffer); } + get HEAPU16() { return new Uint16Array(super.buffer); } + get HEAP32() { return new Int32Array(super.buffer); } + get HEAPU32() { return new Uint32Array(super.buffer); } + get HEAP64() { return new BigInt64Array(super.buffer); } + get HEAPU64() { return new BigUint64Array(super.buffer); } + get HEAPF32() { return new Float32Array(super.buffer); } + get HEAPF64() { return new Float64Array(super.buffer); } + get view() { return new DataView(super.buffer); } +} +/** @public */ +function extendMemory(memory) { + if (Object.getPrototypeOf(memory) === _WebAssembly.Memory.prototype) { + Object.setPrototypeOf(memory, Memory.prototype); + } + return memory; +} + +function checkWebAssemblyFunction() { + const WebAssemblyFunction = _WebAssembly.Function; + if (typeof WebAssemblyFunction !== 'function') { + throw new Error('WebAssembly.Function is not supported in this environment.' + + ' If you are using V8 based browser like Chrome, try to specify' + + ' --js-flags="--wasm-staging --experimental-wasm-stack-switching"'); + } + return WebAssemblyFunction; +} +/** @public */ +function wrapAsyncImport(f, parameterType, returnType) { + const WebAssemblyFunction = checkWebAssemblyFunction(); + if (typeof f !== 'function') { + throw new TypeError('Function required'); + } + const parameters = parameterType.slice(0); + parameters.unshift('externref'); + return new WebAssemblyFunction({ parameters, results: returnType }, f, { suspending: 'first' }); +} +/** @public */ +function wrapAsyncExport(f) { + const WebAssemblyFunction = checkWebAssemblyFunction(); + if (typeof f !== 'function') { + throw new TypeError('Function required'); + } + return new WebAssemblyFunction({ parameters: [...WebAssemblyFunction.type(f).parameters.slice(1)], results: ['externref'] }, f, { promising: 'first' }); +} +/** @public */ +function wrapExports(exports, needWrap) { + return wrapInstanceExports(exports, (exportValue, name) => { + let ignore = typeof exportValue !== 'function'; + if (Array.isArray(needWrap)) { + ignore = ignore || (needWrap.indexOf(name) === -1); + } + return ignore ? exportValue : wrapAsyncExport(exportValue); + }); +} + +// Linux fcntl flag bits ↔ Windows libuv flag bits. `pathOpen()` builds +// `flagsRes` using Linux constants (O_CREAT=0x40, O_EXCL=0x80, +// O_APPEND=0x400). Windows libuv expects different bits (O_CREAT=0x100, +// O_EXCL=0x400, O_APPEND=0x8). Without translation, +// `fs.openSync(path, 0x241 /* L:WRONLY|CREAT|TRUNC */)` is rejected +// with EINVAL because Linux's 0x40 happens to mean O_TEMPORARY on +// Windows — and O_TEMPORARY without O_CREAT is invalid. +const _isWin32Flags = typeof process !== 'undefined' && process.platform === 'win32'; +function _toWinOpenFlags(f) { + let r = f & 3; // RDONLY/WRONLY/RDWR — same on both + if ((f & 0x40) !== 0) + r |= 0x100; // O_CREAT: Linux 0x40 -> Windows 0x100 + if ((f & 0x80) !== 0) + r |= 0x400; // O_EXCL: Linux 0x80 -> Windows 0x400 + if ((f & 0x200) !== 0) + r |= 0x200; // O_TRUNC: same value on both + if ((f & 0x400) !== 0) + r |= 0x8; // O_APPEND: Linux 0x400 -> Windows 0x8 + return r; +} +function copyMemory(targets, src) { + if (targets.length === 0 || src.length === 0) + return 0; + let copied = 0; + let left = src.length - copied; + for (let i = 0; i < targets.length; ++i) { + const target = targets[i]; + if (left < target.length) { + target.set(src.subarray(copied, copied + left), 0); + copied += left; + left = 0; + return copied; + } + target.set(src.subarray(copied, copied + target.length), 0); + copied += target.length; + left -= target.length; + } + return copied; +} +const _memory = new WeakMap(); +const _wasi = new WeakMap(); +const _fs = new WeakMap(); +function ensureMemoryFor(memory, end) { + let buffer = memory.buffer; + if (end > buffer.byteLength) { + memory.grow(0); + buffer = memory.buffer; + } + return buffer; +} +function getMemory(wasi, end = 0) { + const memory = _memory.get(wasi); + ensureMemoryFor(memory, end); + return memory; +} +function getFs(wasi) { + const fs = _fs.get(wasi); + if (!fs) + throw new Error('filesystem is unavailable'); + return fs; +} +function handleError(err) { + if (err instanceof WasiError) { + if (((process.env.NODE_ENV)) !== 'production') { + console.warn(err); + } + return err.errno; + } + switch (err.code) { + case 'ENOENT': return 44 /* WasiErrno.ENOENT */; + case 'EBADF': return 8 /* WasiErrno.EBADF */; + case 'EINVAL': return 28 /* WasiErrno.EINVAL */; + case 'EPERM': return 63 /* WasiErrno.EPERM */; + case 'EPROTO': return 65 /* WasiErrno.EPROTO */; + case 'EEXIST': return 20 /* WasiErrno.EEXIST */; + case 'ENOTDIR': return 54 /* WasiErrno.ENOTDIR */; + case 'EMFILE': return 33 /* WasiErrno.EMFILE */; + case 'EACCES': return 2 /* WasiErrno.EACCES */; + case 'EISDIR': return 31 /* WasiErrno.EISDIR */; + case 'ENOTEMPTY': return 55 /* WasiErrno.ENOTEMPTY */; + case 'ENOSYS': return 52 /* WasiErrno.ENOSYS */; + } + throw err; +} +function defineName(name, f) { + Object.defineProperty(f, 'name', { value: name }); + return f; +} +function tryCall(f, wasi, args) { + let r; + try { + r = f.apply(wasi, args); + } + catch (err) { + return handleError(err); + } + if (isPromiseLike(r)) { + return r.then(_ => _, handleError); + } + return r; +} +function syscallWrap(self, name, f) { + let debug = false; + const NODE_DEBUG_NATIVE = (() => { + try { + return process.env.NODE_DEBUG_NATIVE; + } + catch (_) { + return undefined; + } + })(); + if (typeof NODE_DEBUG_NATIVE === 'string' && NODE_DEBUG_NATIVE.split(',').includes('wasi')) { + debug = true; + } + return debug + ? defineName(name, function () { + const args = Array.prototype.slice.call(arguments); + let debugArgs = [`${name}(${Array.from({ length: arguments.length }).map(() => '%d').join(', ')})`]; + debugArgs = debugArgs.concat(args); + console.debug.apply(console, debugArgs); + return tryCall(f, self, args); + }) + : defineName(name, function () { + return tryCall(f, self, arguments); + }); +} +function resolvePathSync(fs, fileDescriptor, path, flags) { + let resolvedPath = resolve(fileDescriptor.realPath, path); + if ((flags & 1) === 1) { + try { + resolvedPath = fs.readlinkSync(resolvedPath); + } + catch (err) { + if (err.code !== 'EINVAL' && err.code !== 'ENOENT') { + throw err; + } + } + } + return resolvedPath; +} +async function resolvePathAsync(fs, fileDescriptor, path, flags) { + let resolvedPath = resolve(fileDescriptor.realPath, path); + if ((flags & 1) === 1) { + try { + resolvedPath = await fs.promises.readlink(resolvedPath); + } + catch (err) { + if (err.code !== 'EINVAL' && err.code !== 'ENOENT') { + throw err; + } + } + } + return resolvedPath; +} +// eslint-disable-next-line spaced-comment +const encoder = /*#__PURE__*/ new TextEncoder(); +// eslint-disable-next-line spaced-comment +const decoder = /*#__PURE__*/ new TextDecoder(); +const INT64_MAX = (BigInt(1) << BigInt(63)) - BigInt(1); +function readStdin() { + const value = window.prompt(); + if (value === null) + return new Uint8Array(); + const buffer = new TextEncoder().encode(value + '\n'); + return buffer; +} +function validateFstFlagsOrReturn(flags) { + return (Boolean((flags) & ~(1 /* WasiFstFlag.SET_ATIM */ | 2 /* WasiFstFlag.SET_ATIM_NOW */ | + 4 /* WasiFstFlag.SET_MTIM */ | 8 /* WasiFstFlag.SET_MTIM_NOW */)) || + ((flags) & (1 /* WasiFstFlag.SET_ATIM */ | 2 /* WasiFstFlag.SET_ATIM_NOW */)) === + (1 /* WasiFstFlag.SET_ATIM */ | 2 /* WasiFstFlag.SET_ATIM_NOW */) || + ((flags) & (4 /* WasiFstFlag.SET_MTIM */ | 8 /* WasiFstFlag.SET_MTIM_NOW */)) === + (4 /* WasiFstFlag.SET_MTIM */ | 8 /* WasiFstFlag.SET_MTIM_NOW */)); +} +class WASI$1 { + constructor(args, env, fds, asyncFs, fs, asyncify) { + this.args_get = syscallWrap(this, 'args_get', function (argv, argv_buf) { + argv = Number(argv); + argv_buf = Number(argv_buf); + if (argv === 0 || argv_buf === 0) { + return 28 /* WasiErrno.EINVAL */; + } + const wasi = _wasi.get(this); + const args = wasi.args; + const argsSize = encoder.encode(args.join('\0') + '\0').length; + const { HEAPU8, view } = getMemory(this, Math.max(argv + args.length * 4, argv_buf + argsSize)); + for (let i = 0; i < args.length; ++i) { + const arg = args[i]; + view.setInt32(argv, argv_buf, true); + argv += 4; + const data = encoder.encode(arg + '\0'); + HEAPU8.set(data, argv_buf); + argv_buf += data.length; + } + return 0 /* WasiErrno.ESUCCESS */; + }); + this.args_sizes_get = syscallWrap(this, 'args_sizes_get', function (argc, argv_buf_size) { + argc = Number(argc); + argv_buf_size = Number(argv_buf_size); + if (argc === 0 || argv_buf_size === 0) { + return 28 /* WasiErrno.EINVAL */; + } + const { view } = getMemory(this, Math.max(argc + 4, argv_buf_size + 4)); + const wasi = _wasi.get(this); + const args = wasi.args; + view.setUint32(argc, args.length, true); + view.setUint32(argv_buf_size, encoder.encode(args.join('\0') + '\0').length, true); + return 0 /* WasiErrno.ESUCCESS */; + }); + this.environ_get = syscallWrap(this, 'environ_get', function (environ, environ_buf) { + environ = Number(environ); + environ_buf = Number(environ_buf); + if (environ === 0 || environ_buf === 0) { + return 28 /* WasiErrno.EINVAL */; + } + const wasi = _wasi.get(this); + const env = wasi.env; + const envSize = encoder.encode(env.join('\0') + '\0').length; + const { HEAPU8, view } = getMemory(this, Math.max(environ + env.length * 4, environ_buf + envSize)); + for (let i = 0; i < env.length; ++i) { + const pair = env[i]; + view.setInt32(environ, environ_buf, true); + environ += 4; + const data = encoder.encode(pair + '\0'); + HEAPU8.set(data, environ_buf); + environ_buf += data.length; + } + return 0 /* WasiErrno.ESUCCESS */; + }); + this.environ_sizes_get = syscallWrap(this, 'environ_sizes_get', function (len, buflen) { + len = Number(len); + buflen = Number(buflen); + if (len === 0 || buflen === 0) { + return 28 /* WasiErrno.EINVAL */; + } + const { view } = getMemory(this, Math.max(len + 4, buflen + 4)); + const wasi = _wasi.get(this); + view.setUint32(len, wasi.env.length, true); + view.setUint32(buflen, encoder.encode(wasi.env.join('\0') + '\0').length, true); + return 0 /* WasiErrno.ESUCCESS */; + }); + this.clock_res_get = syscallWrap(this, 'clock_res_get', function (id, resolution) { + resolution = Number(resolution); + if (resolution === 0) { + return 28 /* WasiErrno.EINVAL */; + } + const { view } = getMemory(this, resolution + 8); + switch (id) { + case 0 /* WasiClockid.REALTIME */: + view.setBigUint64(resolution, BigInt(1000000), true); + return 0 /* WasiErrno.ESUCCESS */; + case 1 /* WasiClockid.MONOTONIC */: + case 2 /* WasiClockid.PROCESS_CPUTIME_ID */: + case 3 /* WasiClockid.THREAD_CPUTIME_ID */: + view.setBigUint64(resolution, BigInt(1000), true); + return 0 /* WasiErrno.ESUCCESS */; + default: return 28 /* WasiErrno.EINVAL */; + } + }); + this.clock_time_get = syscallWrap(this, 'clock_time_get', function (id, _percision, time) { + time = Number(time); + if (time === 0) { + return 28 /* WasiErrno.EINVAL */; + } + const { view } = getMemory(this, time + 8); + switch (id) { + case 0 /* WasiClockid.REALTIME */: + view.setBigUint64(time, BigInt(Date.now()) * BigInt(1000000), true); + return 0 /* WasiErrno.ESUCCESS */; + case 1 /* WasiClockid.MONOTONIC */: + case 2 /* WasiClockid.PROCESS_CPUTIME_ID */: + case 3 /* WasiClockid.THREAD_CPUTIME_ID */: { + const t = performance.now() / 1000; + const s = Math.trunc(t); + const ms = Math.floor((t - s) * 1000); + const result = BigInt(s) * BigInt(1000000000) + BigInt(ms) * BigInt(1000000); + view.setBigUint64(time, result, true); + return 0 /* WasiErrno.ESUCCESS */; + } + default: return 28 /* WasiErrno.EINVAL */; + } + }); + this.fd_advise = syscallWrap(this, 'fd_advise', function (_fd, _offset, _len, _advice) { + return 52 /* WasiErrno.ENOSYS */; + }); + this.fd_fdstat_get = syscallWrap(this, 'fd_fdstat_get', function (fd, fdstat) { + fdstat = Number(fdstat); + if (fdstat === 0) { + return 28 /* WasiErrno.EINVAL */; + } + const wasi = _wasi.get(this); + const fileDescriptor = wasi.fds.get(fd, BigInt(0), BigInt(0)); + const { view } = getMemory(this, fdstat + 24); + view.setUint16(fdstat, fileDescriptor.type, true); + view.setUint16(fdstat + 2, 0, true); + view.setBigUint64(fdstat + 8, fileDescriptor.rightsBase, true); + view.setBigUint64(fdstat + 16, fileDescriptor.rightsInheriting, true); + return 0 /* WasiErrno.ESUCCESS */; + }); + this.fd_fdstat_set_flags = syscallWrap(this, 'fd_fdstat_set_flags', function (_fd, _flags) { + return 52 /* WasiErrno.ENOSYS */; + }); + this.fd_fdstat_set_rights = syscallWrap(this, 'fd_fdstat_set_rights', function (fd, rightsBase, rightsInheriting) { + const wasi = _wasi.get(this); + const fileDescriptor = wasi.fds.get(fd, BigInt(0), BigInt(0)); + if ((rightsBase | fileDescriptor.rightsBase) > fileDescriptor.rightsBase) { + return 76 /* WasiErrno.ENOTCAPABLE */; + } + if ((rightsInheriting | fileDescriptor.rightsInheriting) > + fileDescriptor.rightsInheriting) { + return 76 /* WasiErrno.ENOTCAPABLE */; + } + fileDescriptor.rightsBase = rightsBase; + fileDescriptor.rightsInheriting = rightsInheriting; + return 0 /* WasiErrno.ESUCCESS */; + }); + this.fd_prestat_get = syscallWrap(this, 'fd_prestat_get', function (fd, prestat) { + prestat = Number(prestat); + if (prestat === 0) { + return 28 /* WasiErrno.EINVAL */; + } + const wasi = _wasi.get(this); + let fileDescriptor; + try { + fileDescriptor = wasi.fds.get(fd, BigInt(0), BigInt(0)); + } + catch (err) { + if (err instanceof WasiError) + return err.errno; + throw err; + } + if (fileDescriptor.preopen !== 1) + return 28 /* WasiErrno.EINVAL */; + const { view } = getMemory(this, prestat + 8); + // preopen type is dir(0) + view.setUint32(prestat, 0, true); + view.setUint32(prestat + 4, encoder.encode(fileDescriptor.path).length, true); + return 0 /* WasiErrno.ESUCCESS */; + }); + this.fd_prestat_dir_name = syscallWrap(this, 'fd_prestat_dir_name', function (fd, path, path_len) { + path = Number(path); + path_len = Number(path_len); + if (path === 0) { + return 28 /* WasiErrno.EINVAL */; + } + const wasi = _wasi.get(this); + const fileDescriptor = wasi.fds.get(fd, BigInt(0), BigInt(0)); + if (fileDescriptor.preopen !== 1) + return 8 /* WasiErrno.EBADF */; + const buffer = encoder.encode(fileDescriptor.path); + const size = buffer.length; + if (size > path_len) + return 42 /* WasiErrno.ENOBUFS */; + const { HEAPU8 } = getMemory(this, path + size); + HEAPU8.set(buffer, path); + return 0 /* WasiErrno.ESUCCESS */; + }); + this.fd_seek = syscallWrap(this, 'fd_seek', function (fd, offset, whence, newOffset) { + newOffset = Number(newOffset); + if (newOffset === 0) { + return 28 /* WasiErrno.EINVAL */; + } + if (fd === 0 || fd === 1 || fd === 2) + return 0 /* WasiErrno.ESUCCESS */; + const wasi = _wasi.get(this); + const fileDescriptor = wasi.fds.get(fd, WasiRights.FD_SEEK, BigInt(0)); + const r = fileDescriptor.seek(offset, whence); + const { view } = getMemory(this, newOffset + 8); + view.setBigUint64(newOffset, r, true); + return 0 /* WasiErrno.ESUCCESS */; + }); + this.fd_tell = syscallWrap(this, 'fd_tell', function (fd, offset) { + const wasi = _wasi.get(this); + const fileDescriptor = wasi.fds.get(fd, WasiRights.FD_TELL, BigInt(0)); + const pos = BigInt(fileDescriptor.pos); + const { view } = getMemory(this, Number(offset) + 8); + view.setBigUint64(Number(offset), pos, true); + return 0 /* WasiErrno.ESUCCESS */; + }); + this.poll_oneoff = syscallWrap(this, 'poll_oneoff', function (in_ptr, out_ptr, nsubscriptions, nevents) { + in_ptr = Number(in_ptr); + out_ptr = Number(out_ptr); + nevents = Number(nevents); + nsubscriptions = Number(nsubscriptions); + nsubscriptions = nsubscriptions >>> 0; + if (in_ptr === 0 || out_ptr === 0 || nsubscriptions === 0 || nevents === 0) { + return 28 /* WasiErrno.EINVAL */; + } + const { view } = getMemory(this, Math.max(in_ptr + nsubscriptions * 48, out_ptr + nsubscriptions * 32, nevents + 4)); + view.setUint32(nevents, 0, true); + let i = 0; + let timer_userdata = BigInt(0); + let cur_timeout = BigInt(0); + let has_timeout = 0; + let min_timeout = BigInt(0); + let sub; + const subscriptions = Array(nsubscriptions); + for (i = 0; i < nsubscriptions; i++) { + sub = in_ptr + i * 48; + const userdata = view.getBigUint64(sub, true); + const type = view.getUint8(sub + 8); + const clockIdOrFd = view.getUint32(sub + 16, true); + const timeout = view.getBigUint64(sub + 24, true); + const precision = view.getBigUint64(sub + 32, true); + const flags = view.getUint16(sub + 40, true); + subscriptions[i] = { + userdata, + type, + u: { + clock: { + clock_id: clockIdOrFd, + timeout, + precision, + flags + }, + fd_readwrite: { + fd: clockIdOrFd + } + } + }; + } + const fdevents = []; + for (i = 0; i < nsubscriptions; i++) { + sub = subscriptions[i]; + switch (sub.type) { + case 0 /* WasiEventType.CLOCK */: { + if (sub.u.clock.flags === 1 /* WasiSubclockflags.ABSTIME */) { + /* Convert absolute time to relative delay. */ + const now = BigInt(Date.now()) * BigInt(1000000); + cur_timeout = sub.u.clock.timeout - now; + } + else { + cur_timeout = sub.u.clock.timeout; + } + if (has_timeout === 0 || cur_timeout < min_timeout) { + min_timeout = cur_timeout; + timer_userdata = sub.userdata; + has_timeout = 1; + } + break; + } + case 1 /* WasiEventType.FD_READ */: + case 2 /* WasiEventType.FD_WRITE */: + fdevents.push(sub); + break; + default: return 28 /* WasiErrno.EINVAL */; + } + } + if (fdevents.length > 0) { + for (i = 0; i < fdevents.length; i++) { + const fdevent = fdevents[i]; + const event = out_ptr + 32 * i; + view.setBigUint64(event, fdevent.userdata, true); + view.setUint32(event + 8, 52 /* WasiErrno.ENOSYS */, true); + view.setUint32(event + 12, fdevent.type, true); + view.setBigUint64(event + 16, BigInt(0), true); + view.setUint16(event + 24, 0, true); + view.setUint32(nevents, 1, true); + } + view.setUint32(nevents, fdevents.length, true); + return 0 /* WasiErrno.ESUCCESS */; + } + if (has_timeout) { + const delay = Number(min_timeout / BigInt(1000000)); + // if (isMainThread || typeof SharedArrayBuffer !== 'function') { + sleepBreakIf(delay, () => false); + // } else { + // const buf = new SharedArrayBuffer(4) + // const arr = new Int32Array(buf) + // postMsg({ + // __tybys_wasm_util_wasi__: { + // type: 'set-timeout', + // payload: { + // buffer: buf, + // delay + // } + // } + // }) + // Atomics.wait(arr, 0, 0) + // } + const event = out_ptr; + view.setBigUint64(event, timer_userdata, true); + view.setUint32(event + 8, 0 /* WasiErrno.ESUCCESS */, true); + view.setUint32(event + 12, 0 /* WasiEventType.CLOCK */, true); + view.setUint32(nevents, 1, true); + } + return 0 /* WasiErrno.ESUCCESS */; + }); + this.proc_exit = syscallWrap(this, 'proc_exit', function (rval) { + if ((typeof process === 'object') && (process !== null) && (typeof process.exit === 'function')) { + process.exit(rval); + } + return 0 /* WasiErrno.ESUCCESS */; + }); + this.proc_raise = syscallWrap(this, 'proc_raise', function (_sig) { + return 52 /* WasiErrno.ENOSYS */; + }); + this.sched_yield = syscallWrap(this, 'sched_yield', function () { + return 0 /* WasiErrno.ESUCCESS */; + }); + this.random_get = typeof crypto !== 'undefined' && typeof crypto.getRandomValues === 'function' + ? syscallWrap(this, 'random_get', function (buf, buf_len) { + buf = Number(buf); + if (buf === 0) { + return 28 /* WasiErrno.EINVAL */; + } + buf_len = Number(buf_len); + const { HEAPU8, view } = getMemory(this, buf + buf_len); + if ((typeof SharedArrayBuffer === 'function' && HEAPU8.buffer instanceof SharedArrayBuffer) || + (Object.prototype.toString.call(HEAPU8.buffer) === '[object SharedArrayBuffer]')) { + for (let i = buf; i < buf + buf_len; ++i) { + view.setUint8(i, Math.floor(Math.random() * 256)); + } + return 0 /* WasiErrno.ESUCCESS */; + } + let pos; + const stride = 65536; + for (pos = 0; pos + stride < buf_len; pos += stride) { + crypto.getRandomValues(HEAPU8.subarray(buf + pos, buf + pos + stride)); + } + crypto.getRandomValues(HEAPU8.subarray(buf + pos, buf + buf_len)); + return 0 /* WasiErrno.ESUCCESS */; + }) + : syscallWrap(this, 'random_get', function (buf, buf_len) { + buf = Number(buf); + if (buf === 0) { + return 28 /* WasiErrno.EINVAL */; + } + buf_len = Number(buf_len); + const { view } = getMemory(this, buf + buf_len); + for (let i = buf; i < buf + buf_len; ++i) { + view.setUint8(i, Math.floor(Math.random() * 256)); + } + return 0 /* WasiErrno.ESUCCESS */; + }); + this.sock_recv = syscallWrap(this, 'sock_recv', function () { + return 58 /* WasiErrno.ENOTSUP */; + }); + this.sock_send = syscallWrap(this, 'sock_send', function () { + return 58 /* WasiErrno.ENOTSUP */; + }); + this.sock_shutdown = syscallWrap(this, 'sock_shutdown', function () { + return 58 /* WasiErrno.ENOTSUP */; + }); + this.sock_accept = syscallWrap(this, 'sock_accept', function () { + return 58 /* WasiErrno.ENOTSUP */; + }); + _wasi.set(this, { + fds, + args, + env + }); + if (fs) + _fs.set(this, fs); + // eslint-disable-next-line @typescript-eslint/no-this-alias + const _this = this; + function defineImport(name, syncVersion, asyncVersion, parameterType, returnType) { + if (asyncFs) { + if (asyncify) { + _this[name] = asyncify.wrapImportFunction(syscallWrap(_this, name, asyncVersion)); + } + else { + _this[name] = wrapAsyncImport(syscallWrap(_this, name, asyncVersion), parameterType, returnType); + } + } + else { + _this[name] = syscallWrap(_this, name, syncVersion); + } + } + defineImport('fd_allocate', function fd_allocate(fd, offset, len) { + const wasi = _wasi.get(this); + const fs = getFs(this); + const fileDescriptor = wasi.fds.get(fd, WasiRights.FD_ALLOCATE, BigInt(0)); + const stat = fs.fstatSync(fileDescriptor.fd, { bigint: true }); + if (stat.size < offset + len) { + fs.ftruncateSync(fileDescriptor.fd, Number(offset + len)); + } + return 0 /* WasiErrno.ESUCCESS */; + }, async function fd_allocate(fd, offset, len) { + const wasi = _wasi.get(this); + const fileDescriptor = wasi.fds.get(fd, WasiRights.FD_ALLOCATE, BigInt(0)); + const h = fileDescriptor.fd; + const stat = await h.stat({ bigint: true }); + if (stat.size < offset + len) { + await h.truncate(Number(offset + len)); + } + return 0 /* WasiErrno.ESUCCESS */; + }, ['i32', 'i64', 'f64'], ['i32']); + defineImport('fd_close', function fd_close(fd) { + const wasi = _wasi.get(this); + const fileDescriptor = wasi.fds.get(fd, BigInt(0), BigInt(0)); + const fs = getFs(this); + fs.closeSync(fileDescriptor.fd); + wasi.fds.remove(fd); + return 0 /* WasiErrno.ESUCCESS */; + }, async function fd_close(fd) { + const wasi = _wasi.get(this); + const fileDescriptor = wasi.fds.get(fd, BigInt(0), BigInt(0)); + await fileDescriptor.fd.close(); + wasi.fds.remove(fd); + return 0 /* WasiErrno.ESUCCESS */; + }, ['i32'], ['i32']); + defineImport('fd_datasync', function fd_datasync(fd) { + const wasi = _wasi.get(this); + const fileDescriptor = wasi.fds.get(fd, WasiRights.FD_DATASYNC, BigInt(0)); + const fs = getFs(this); + fs.fdatasyncSync(fileDescriptor.fd); + return 0 /* WasiErrno.ESUCCESS */; + }, async function fd_datasync(fd) { + const wasi = _wasi.get(this); + const fileDescriptor = wasi.fds.get(fd, WasiRights.FD_DATASYNC, BigInt(0)); + await fileDescriptor.fd.datasync(); + return 0 /* WasiErrno.ESUCCESS */; + }, ['i32'], ['i32']); + defineImport('fd_filestat_get', function fd_filestat_get(fd, buf) { + buf = Number(buf); + if (buf === 0) + return 28 /* WasiErrno.EINVAL */; + const wasi = _wasi.get(this); + const fileDescriptor = wasi.fds.get(fd, WasiRights.FD_FILESTAT_GET, BigInt(0)); + const fs = getFs(this); + const stat = fs.fstatSync(fileDescriptor.fd, { bigint: true }); + const { view } = getMemory(this, buf + 64); + toFileStat(view, buf, stat); + return 0 /* WasiErrno.ESUCCESS */; + }, async function fd_filestat_get(fd, buf) { + buf = Number(buf); + if (buf === 0) + return 28 /* WasiErrno.EINVAL */; + const wasi = _wasi.get(this); + const fileDescriptor = wasi.fds.get(fd, WasiRights.FD_FILESTAT_GET, BigInt(0)); + const h = fileDescriptor.fd; + const stat = await h.stat({ bigint: true }); + const { view } = getMemory(this, buf + 64); + toFileStat(view, buf, stat); + return 0 /* WasiErrno.ESUCCESS */; + }, ['i32', 'i32'], ['i32']); + defineImport('fd_filestat_set_size', function fd_filestat_set_size(fd, size) { + const wasi = _wasi.get(this); + const fileDescriptor = wasi.fds.get(fd, WasiRights.FD_FILESTAT_SET_SIZE, BigInt(0)); + const fs = getFs(this); + fs.ftruncateSync(fileDescriptor.fd, Number(size)); + return 0 /* WasiErrno.ESUCCESS */; + }, async function fd_filestat_set_size(fd, size) { + const wasi = _wasi.get(this); + const fileDescriptor = wasi.fds.get(fd, WasiRights.FD_FILESTAT_SET_SIZE, BigInt(0)); + const h = fileDescriptor.fd; + await h.truncate(Number(size)); + return 0 /* WasiErrno.ESUCCESS */; + }, ['i32', 'i64'], ['i32']); + function fdFilestatGetTimes(fd, atim, mtim, flags) { + const wasi = _wasi.get(this); + const fileDescriptor = wasi.fds.get(fd, WasiRights.FD_FILESTAT_SET_TIMES, BigInt(0)); + if ((flags & 2 /* WasiFstFlag.SET_ATIM_NOW */) === 2 /* WasiFstFlag.SET_ATIM_NOW */) { + atim = BigInt(Date.now() * 1000000); + } + if ((flags & 8 /* WasiFstFlag.SET_MTIM_NOW */) === 8 /* WasiFstFlag.SET_MTIM_NOW */) { + mtim = BigInt(Date.now() * 1000000); + } + return { fileDescriptor, atim, mtim }; + } + defineImport('fd_filestat_set_times', function fd_filestat_set_times(fd, atim, mtim, flags) { + if (validateFstFlagsOrReturn(flags)) { + return 28 /* WasiErrno.EINVAL */; + } + const { fileDescriptor, atim: atimRes, mtim: mtimRes } = fdFilestatGetTimes.call(this, fd, atim, mtim, flags); + const fs = getFs(this); + fs.futimesSync(fileDescriptor.fd, Number(atimRes), Number(mtimRes)); + return 0 /* WasiErrno.ESUCCESS */; + }, async function fd_filestat_set_times(fd, atim, mtim, flags) { + if (validateFstFlagsOrReturn(flags)) { + return 28 /* WasiErrno.EINVAL */; + } + const { fileDescriptor, atim: atimRes, mtim: mtimRes } = fdFilestatGetTimes.call(this, fd, atim, mtim, flags); + const h = fileDescriptor.fd; + await h.utimes(Number(atimRes), Number(mtimRes)); + return 0 /* WasiErrno.ESUCCESS */; + }, ['i32', 'i64', 'i64', 'i32'], ['i32']); + defineImport('fd_pread', function fd_pread(fd, iovs, iovslen, offset, size) { + iovs = Number(iovs); + size = Number(size); + if ((iovs === 0 && iovslen) || size === 0 || offset > INT64_MAX) { + return 28 /* WasiErrno.EINVAL */; + } + const { HEAPU8, view } = getMemory(this, Math.max(iovs + Number(iovslen) * 8, size + 4)); + const wasi = _wasi.get(this); + const fileDescriptor = wasi.fds.get(fd, WasiRights.FD_READ | WasiRights.FD_SEEK, BigInt(0)); + if (!iovslen) { + view.setUint32(size, 0, true); + return 0 /* WasiErrno.ESUCCESS */; + } + let totalSize = 0; + const ioVecs = Array.from({ length: Number(iovslen) }, (_, i) => { + const offset = iovs + (i * 8); + const buf = view.getInt32(offset, true); + const bufLen = view.getUint32(offset + 4, true); + totalSize += bufLen; + return HEAPU8.subarray(buf, buf + bufLen); + }); + let nread = 0; + const buffer = (() => { + try { + return new Uint8Array(new SharedArrayBuffer(totalSize)); + } + catch (_) { + return new Uint8Array(totalSize); + } + })(); + buffer._isBuffer = true; + const fs = getFs(this); + const bytesRead = fs.readSync(fileDescriptor.fd, buffer, 0, buffer.length, Number(offset)); + nread = buffer ? copyMemory(ioVecs, buffer.subarray(0, bytesRead)) : 0; + view.setUint32(size, nread, true); + return 0 /* WasiErrno.ESUCCESS */; + }, async function (fd, iovs, iovslen, offset, size) { + iovs = Number(iovs); + size = Number(size); + if ((iovs === 0 && iovslen) || size === 0 || offset > INT64_MAX) { + return 28 /* WasiErrno.EINVAL */; + } + const { HEAPU8, view } = getMemory(this, Math.max(iovs + Number(iovslen) * 8, size + 4)); + const wasi = _wasi.get(this); + const fileDescriptor = wasi.fds.get(fd, WasiRights.FD_READ | WasiRights.FD_SEEK, BigInt(0)); + if (!iovslen) { + view.setUint32(size, 0, true); + return 0 /* WasiErrno.ESUCCESS */; + } + let totalSize = 0; + const ioVecs = Array.from({ length: Number(iovslen) }, (_, i) => { + const offset = iovs + (i * 8); + const buf = view.getInt32(offset, true); + const bufLen = view.getUint32(offset + 4, true); + totalSize += bufLen; + return HEAPU8.subarray(buf, buf + bufLen); + }); + let nread = 0; + const buffer = new Uint8Array(totalSize); + buffer._isBuffer = true; + const { bytesRead } = await fileDescriptor.fd.read(buffer, 0, buffer.length, Number(offset)); + nread = buffer ? copyMemory(ioVecs, buffer.subarray(0, bytesRead)) : 0; + view.setUint32(size, nread, true); + return 0 /* WasiErrno.ESUCCESS */; + }, ['i32', 'i32', 'i32', 'i64', 'i32'], ['i32']); + defineImport('fd_pwrite', function fd_pwrite(fd, iovs, iovslen, offset, size) { + iovs = Number(iovs); + size = Number(size); + if ((iovs === 0 && iovslen) || size === 0 || offset > INT64_MAX) { + return 28 /* WasiErrno.EINVAL */; + } + const { HEAPU8, view } = getMemory(this, Math.max(iovs + Number(iovslen) * 8, size + 4)); + const wasi = _wasi.get(this); + const fileDescriptor = wasi.fds.get(fd, WasiRights.FD_WRITE | WasiRights.FD_SEEK, BigInt(0)); + if (!iovslen) { + view.setUint32(size, 0, true); + return 0 /* WasiErrno.ESUCCESS */; + } + const buffer = concatBuffer(Array.from({ length: Number(iovslen) }, (_, i) => { + const offset = iovs + (i * 8); + const buf = view.getInt32(offset, true); + const bufLen = view.getUint32(offset + 4, true); + return HEAPU8.subarray(buf, buf + bufLen); + })); + const fs = getFs(this); + const nwritten = fs.writeSync(fileDescriptor.fd, buffer, 0, buffer.length, Number(offset)); + view.setUint32(size, nwritten, true); + return 0 /* WasiErrno.ESUCCESS */; + }, async function fd_pwrite(fd, iovs, iovslen, offset, size) { + iovs = Number(iovs); + size = Number(size); + if ((iovs === 0 && iovslen) || size === 0 || offset > INT64_MAX) { + return 28 /* WasiErrno.EINVAL */; + } + const { HEAPU8, view } = getMemory(this, Math.max(iovs + Number(iovslen) * 8, size + 4)); + const wasi = _wasi.get(this); + const fileDescriptor = wasi.fds.get(fd, WasiRights.FD_WRITE | WasiRights.FD_SEEK, BigInt(0)); + if (!iovslen) { + view.setUint32(size, 0, true); + return 0 /* WasiErrno.ESUCCESS */; + } + const buffer = concatBuffer(Array.from({ length: Number(iovslen) }, (_, i) => { + const offset = iovs + (i * 8); + const buf = view.getInt32(offset, true); + const bufLen = view.getUint32(offset + 4, true); + return HEAPU8.subarray(buf, buf + bufLen); + })); + const { bytesWritten } = await fileDescriptor.fd.write(buffer, 0, buffer.length, Number(offset)); + view.setUint32(size, bytesWritten, true); + return 0 /* WasiErrno.ESUCCESS */; + }, ['i32', 'i32', 'i32', 'i64', 'i32'], ['i32']); + defineImport('fd_read', function fd_read(fd, iovs, iovslen, size) { + iovs = Number(iovs); + size = Number(size); + if ((iovs === 0 && iovslen) || size === 0) { + return 28 /* WasiErrno.EINVAL */; + } + const { HEAPU8, view } = getMemory(this, Math.max(iovs + Number(iovslen) * 8, size + 4)); + const wasi = _wasi.get(this); + const fileDescriptor = wasi.fds.get(fd, WasiRights.FD_READ, BigInt(0)); + if (!iovslen) { + view.setUint32(size, 0, true); + return 0 /* WasiErrno.ESUCCESS */; + } + let totalSize = 0; + const ioVecs = Array.from({ length: Number(iovslen) }, (_, i) => { + const offset = iovs + (i * 8); + const buf = view.getInt32(offset, true); + const bufLen = view.getUint32(offset + 4, true); + totalSize += bufLen; + return HEAPU8.subarray(buf, buf + bufLen); + }); + let buffer; + let nread = 0; + if (fd === 0) { + if (typeof window === 'undefined' || typeof window.prompt !== 'function') { + return 58 /* WasiErrno.ENOTSUP */; + } + buffer = readStdin(); + nread = buffer ? copyMemory(ioVecs, buffer) : 0; + } + else { + buffer = (() => { + try { + return new Uint8Array(new SharedArrayBuffer(totalSize)); + } + catch (_) { + return new Uint8Array(totalSize); + } + })(); + buffer._isBuffer = true; + const fs = getFs(this); + const bytesRead = fs.readSync(fileDescriptor.fd, buffer, 0, buffer.length, Number(fileDescriptor.pos)); + nread = buffer ? copyMemory(ioVecs, buffer.subarray(0, bytesRead)) : 0; + fileDescriptor.pos += BigInt(nread); + } + view.setUint32(size, nread, true); + return 0 /* WasiErrno.ESUCCESS */; + }, async function fd_read(fd, iovs, iovslen, size) { + iovs = Number(iovs); + size = Number(size); + if ((iovs === 0 && iovslen) || size === 0) { + return 28 /* WasiErrno.EINVAL */; + } + const { HEAPU8, view } = getMemory(this, Math.max(iovs + Number(iovslen) * 8, size + 4)); + const wasi = _wasi.get(this); + const fileDescriptor = wasi.fds.get(fd, WasiRights.FD_READ, BigInt(0)); + if (!iovslen) { + view.setUint32(size, 0, true); + return 0 /* WasiErrno.ESUCCESS */; + } + let totalSize = 0; + const ioVecs = Array.from({ length: Number(iovslen) }, (_, i) => { + const offset = iovs + (i * 8); + const buf = view.getInt32(offset, true); + const bufLen = view.getUint32(offset + 4, true); + totalSize += bufLen; + return HEAPU8.subarray(buf, buf + bufLen); + }); + let buffer; + let nread = 0; + if (fd === 0) { + if (typeof window === 'undefined' || typeof window.prompt !== 'function') { + return 58 /* WasiErrno.ENOTSUP */; + } + buffer = readStdin(); + nread = buffer ? copyMemory(ioVecs, buffer) : 0; + } + else { + buffer = new Uint8Array(totalSize); + buffer._isBuffer = true; + const { bytesRead } = await fileDescriptor.fd.read(buffer, 0, buffer.length, Number(fileDescriptor.pos)); + nread = buffer ? copyMemory(ioVecs, buffer.subarray(0, bytesRead)) : 0; + fileDescriptor.pos += BigInt(nread); + } + view.setUint32(size, nread, true); + return 0 /* WasiErrno.ESUCCESS */; + }, ['i32', 'i32', 'i32', 'i32'], ['i32']); + defineImport('fd_readdir', function fd_readdir(fd, buf, buf_len, cookie, bufused) { + buf = Number(buf); + buf_len = Number(buf_len); + bufused = Number(bufused); + if (buf === 0 || bufused === 0) + return 0 /* WasiErrno.ESUCCESS */; + const wasi = _wasi.get(this); + const fileDescriptor = wasi.fds.get(fd, WasiRights.FD_READDIR, BigInt(0)); + const fs = getFs(this); + const entries = fs.readdirSync(fileDescriptor.realPath, { withFileTypes: true }); + const { HEAPU8, view } = getMemory(this, Math.max(buf + buf_len, bufused + 4)); + let bufferUsed = 0; + for (let i = Number(cookie); i < entries.length; i++) { + const nameData = encoder.encode(entries[i].name); + const entryInfo = fs.statSync(resolve(fileDescriptor.realPath, entries[i].name), { bigint: true }); + const entryData = new Uint8Array(24 + nameData.byteLength); + const entryView = new DataView(entryData.buffer); + entryView.setBigUint64(0, BigInt(i + 1), true); + entryView.setBigUint64(8, BigInt(entryInfo.ino ? entryInfo.ino : 0), true); + entryView.setUint32(16, nameData.byteLength, true); + let type; + if (entries[i].isFile()) { + type = 4 /* WasiFileType.REGULAR_FILE */; + } + else if (entries[i].isDirectory()) { + type = 3 /* WasiFileType.DIRECTORY */; + } + else if (entries[i].isSymbolicLink()) { + type = 7 /* WasiFileType.SYMBOLIC_LINK */; + } + else if (entries[i].isCharacterDevice()) { + type = 2 /* WasiFileType.CHARACTER_DEVICE */; + } + else if (entries[i].isBlockDevice()) { + type = 1 /* WasiFileType.BLOCK_DEVICE */; + } + else if (entries[i].isSocket()) { + type = 6 /* WasiFileType.SOCKET_STREAM */; + } + else { + type = 0 /* WasiFileType.UNKNOWN */; + } + entryView.setUint8(20, type); + entryData.set(nameData, 24); + const data = entryData.slice(0, Math.min(entryData.length, buf_len - bufferUsed)); + HEAPU8.set(data, buf + bufferUsed); + bufferUsed += data.byteLength; + } + view.setUint32(bufused, bufferUsed, true); + return 0 /* WasiErrno.ESUCCESS */; + }, async function fd_readdir(fd, buf, buf_len, cookie, bufused) { + buf = Number(buf); + buf_len = Number(buf_len); + bufused = Number(bufused); + if (buf === 0 || bufused === 0) + return 0 /* WasiErrno.ESUCCESS */; + const wasi = _wasi.get(this); + const fileDescriptor = wasi.fds.get(fd, WasiRights.FD_READDIR, BigInt(0)); + const fs = getFs(this); + const entries = await fs.promises.readdir(fileDescriptor.realPath, { withFileTypes: true }); + const { HEAPU8, view } = getMemory(this, Math.max(buf + buf_len, bufused + 4)); + let bufferUsed = 0; + for (let i = Number(cookie); i < entries.length; i++) { + const nameData = encoder.encode(entries[i].name); + const entryInfo = await fs.promises.stat(resolve(fileDescriptor.realPath, entries[i].name), { bigint: true }); + const entryData = new Uint8Array(24 + nameData.byteLength); + const entryView = new DataView(entryData.buffer); + entryView.setBigUint64(0, BigInt(i + 1), true); + entryView.setBigUint64(8, BigInt(entryInfo.ino ? entryInfo.ino : 0), true); + entryView.setUint32(16, nameData.byteLength, true); + let type; + if (entries[i].isFile()) { + type = 4 /* WasiFileType.REGULAR_FILE */; + } + else if (entries[i].isDirectory()) { + type = 3 /* WasiFileType.DIRECTORY */; + } + else if (entries[i].isSymbolicLink()) { + type = 7 /* WasiFileType.SYMBOLIC_LINK */; + } + else if (entries[i].isCharacterDevice()) { + type = 2 /* WasiFileType.CHARACTER_DEVICE */; + } + else if (entries[i].isBlockDevice()) { + type = 1 /* WasiFileType.BLOCK_DEVICE */; + } + else if (entries[i].isSocket()) { + type = 6 /* WasiFileType.SOCKET_STREAM */; + } + else { + type = 0 /* WasiFileType.UNKNOWN */; + } + entryView.setUint8(20, type); + entryData.set(nameData, 24); + const data = entryData.slice(0, Math.min(entryData.length, buf_len - bufferUsed)); + HEAPU8.set(data, buf + bufferUsed); + bufferUsed += data.byteLength; + } + view.setUint32(bufused, bufferUsed, true); + return 0 /* WasiErrno.ESUCCESS */; + }, ['i32', 'i32', 'i32', 'i64', 'i32'], ['i32']); + defineImport('fd_renumber', function fd_renumber(from, to) { + const wasi = _wasi.get(this); + wasi.fds.renumber(to, from); + return 0 /* WasiErrno.ESUCCESS */; + }, async function fd_renumber(from, to) { + const wasi = _wasi.get(this); + await wasi.fds.renumber(to, from); + return 0 /* WasiErrno.ESUCCESS */; + }, ['i32', 'i32'], ['i32']); + defineImport('fd_sync', function fd_sync(fd) { + const wasi = _wasi.get(this); + const fileDescriptor = wasi.fds.get(fd, WasiRights.FD_SYNC, BigInt(0)); + const fs = getFs(this); + fs.fsyncSync(fileDescriptor.fd); + return 0 /* WasiErrno.ESUCCESS */; + }, async function fd_sync(fd) { + const wasi = _wasi.get(this); + const fileDescriptor = wasi.fds.get(fd, WasiRights.FD_SYNC, BigInt(0)); + await fileDescriptor.fd.sync(); + return 0 /* WasiErrno.ESUCCESS */; + }, ['i32'], ['i32']); + defineImport('fd_write', function fd_write(fd, iovs, iovslen, size) { + iovs = Number(iovs); + size = Number(size); + if ((iovs === 0 && iovslen) || size === 0) { + return 28 /* WasiErrno.EINVAL */; + } + const { HEAPU8, view } = getMemory(this, Math.max(iovs + Number(iovslen) * 8, size + 4)); + const wasi = _wasi.get(this); + const fileDescriptor = wasi.fds.get(fd, WasiRights.FD_WRITE, BigInt(0)); + if (!iovslen) { + view.setUint32(size, 0, true); + return 0 /* WasiErrno.ESUCCESS */; + } + const buffer = concatBuffer(Array.from({ length: Number(iovslen) }, (_, i) => { + const offset = iovs + (i * 8); + const buf = view.getInt32(offset, true); + const bufLen = view.getUint32(offset + 4, true); + return HEAPU8.subarray(buf, buf + bufLen); + })); + let nwritten; + if (fd === 1 || fd === 2) { + nwritten = fileDescriptor.write(buffer); + } + else { + const fs = getFs(this); + nwritten = fs.writeSync(fileDescriptor.fd, buffer, 0, buffer.length, Number(fileDescriptor.pos)); + fileDescriptor.pos += BigInt(nwritten); + } + view.setUint32(size, nwritten, true); + return 0 /* WasiErrno.ESUCCESS */; + }, async function fd_write(fd, iovs, iovslen, size) { + iovs = Number(iovs); + size = Number(size); + if ((iovs === 0 && iovslen) || size === 0) { + return 28 /* WasiErrno.EINVAL */; + } + const { HEAPU8, view } = getMemory(this, Math.max(iovs + Number(iovslen) * 8, size + 4)); + const wasi = _wasi.get(this); + const fileDescriptor = wasi.fds.get(fd, WasiRights.FD_WRITE, BigInt(0)); + if (!iovslen) { + view.setUint32(size, 0, true); + return 0 /* WasiErrno.ESUCCESS */; + } + const buffer = concatBuffer(Array.from({ length: Number(iovslen) }, (_, i) => { + const offset = iovs + (i * 8); + const buf = view.getInt32(offset, true); + const bufLen = view.getUint32(offset + 4, true); + return HEAPU8.subarray(buf, buf + bufLen); + })); + let nwritten; + if (fd === 1 || fd === 2) { + nwritten = fileDescriptor.write(buffer); + } + else { + nwritten = await (await (fileDescriptor.fd.write(buffer, 0, buffer.length, Number(fileDescriptor.pos)))).bytesWritten; + fileDescriptor.pos += BigInt(nwritten); + } + view.setUint32(size, nwritten, true); + return 0 /* WasiErrno.ESUCCESS */; + }, ['i32', 'i32', 'i32', 'i32'], ['i32']); + defineImport('path_create_directory', function path_create_directory(fd, path, path_len) { + path = Number(path); + path_len = Number(path_len); + if (path === 0) { + return 28 /* WasiErrno.EINVAL */; + } + const { HEAPU8 } = getMemory(this, path + path_len); + const wasi = _wasi.get(this); + const fileDescriptor = wasi.fds.get(fd, WasiRights.PATH_CREATE_DIRECTORY, BigInt(0)); + let pathString = decoder.decode(unsharedSlice(HEAPU8, path, path + path_len)); + pathString = resolve(fileDescriptor.realPath, pathString); + const fs = getFs(this); + fs.mkdirSync(pathString); + return 0 /* WasiErrno.ESUCCESS */; + }, async function path_create_directory(fd, path, path_len) { + path = Number(path); + path_len = Number(path_len); + if (path === 0) { + return 28 /* WasiErrno.EINVAL */; + } + const { HEAPU8 } = getMemory(this, path + path_len); + const wasi = _wasi.get(this); + const fileDescriptor = wasi.fds.get(fd, WasiRights.PATH_CREATE_DIRECTORY, BigInt(0)); + let pathString = decoder.decode(unsharedSlice(HEAPU8, path, path + path_len)); + pathString = resolve(fileDescriptor.realPath, pathString); + const fs = getFs(this); + await fs.promises.mkdir(pathString); + return 0 /* WasiErrno.ESUCCESS */; + }, ['i32', 'i32', 'i32'], ['i32']); + defineImport('path_filestat_get', function path_filestat_get(fd, flags, path, path_len, filestat) { + path = Number(path); + path_len = Number(path_len); + filestat = Number(filestat); + if (path === 0 || filestat === 0) { + return 28 /* WasiErrno.EINVAL */; + } + const { HEAPU8, view } = getMemory(this, Math.max(path + path_len, filestat + 64)); + const wasi = _wasi.get(this); + const fileDescriptor = wasi.fds.get(fd, WasiRights.PATH_FILESTAT_GET, BigInt(0)); + let pathString = decoder.decode(unsharedSlice(HEAPU8, path, path + path_len)); + const fs = getFs(this); + pathString = resolve(fileDescriptor.realPath, pathString); + let stat; + if ((flags & 1) === 1) { + stat = fs.statSync(pathString, { bigint: true }); + } + else { + stat = fs.lstatSync(pathString, { bigint: true }); + } + toFileStat(view, filestat, stat); + return 0 /* WasiErrno.ESUCCESS */; + }, async function path_filestat_get(fd, flags, path, path_len, filestat) { + path = Number(path); + path_len = Number(path_len); + filestat = Number(filestat); + if (path === 0 || filestat === 0) { + return 28 /* WasiErrno.EINVAL */; + } + const { HEAPU8, view } = getMemory(this, Math.max(path + path_len, filestat + 64)); + const wasi = _wasi.get(this); + const fileDescriptor = wasi.fds.get(fd, WasiRights.PATH_FILESTAT_GET, BigInt(0)); + let pathString = decoder.decode(unsharedSlice(HEAPU8, path, path + path_len)); + const fs = getFs(this); + pathString = resolve(fileDescriptor.realPath, pathString); + let stat; + if ((flags & 1) === 1) { + stat = await fs.promises.stat(pathString, { bigint: true }); + } + else { + stat = await fs.promises.lstat(pathString, { bigint: true }); + } + toFileStat(view, filestat, stat); + return 0 /* WasiErrno.ESUCCESS */; + }, ['i32', 'i32', 'i32', 'i32', 'i32'], ['i32']); + defineImport('path_filestat_set_times', function path_filestat_set_times(fd, flags, path, path_len, atim, mtim, fst_flags) { + path = Number(path); + path_len = Number(path_len); + if (path === 0) + return 28 /* WasiErrno.EINVAL */; + const { HEAPU8 } = getMemory(this, path + path_len); + const wasi = _wasi.get(this); + const fileDescriptor = wasi.fds.get(fd, WasiRights.PATH_FILESTAT_SET_TIMES, BigInt(0)); + if (validateFstFlagsOrReturn(fst_flags)) { + return 28 /* WasiErrno.EINVAL */; + } + const fs = getFs(this); + const resolvedPath = resolvePathSync(fs, fileDescriptor, decoder.decode(unsharedSlice(HEAPU8, path, path + path_len)), flags); + if ((fst_flags & 2 /* WasiFstFlag.SET_ATIM_NOW */) === 2 /* WasiFstFlag.SET_ATIM_NOW */) { + atim = BigInt(Date.now() * 1000000); + } + if ((fst_flags & 8 /* WasiFstFlag.SET_MTIM_NOW */) === 8 /* WasiFstFlag.SET_MTIM_NOW */) { + mtim = BigInt(Date.now() * 1000000); + } + fs.utimesSync(resolvedPath, Number(atim), Number(mtim)); + return 0 /* WasiErrno.ESUCCESS */; + }, async function path_filestat_set_times(fd, flags, path, path_len, atim, mtim, fst_flags) { + path = Number(path); + path_len = Number(path_len); + if (path === 0) + return 28 /* WasiErrno.EINVAL */; + const { HEAPU8 } = getMemory(this, path + path_len); + const wasi = _wasi.get(this); + const fileDescriptor = wasi.fds.get(fd, WasiRights.PATH_FILESTAT_SET_TIMES, BigInt(0)); + if (validateFstFlagsOrReturn(fst_flags)) { + return 28 /* WasiErrno.EINVAL */; + } + const fs = getFs(this); + const resolvedPath = await resolvePathAsync(fs, fileDescriptor, decoder.decode(unsharedSlice(HEAPU8, path, path + path_len)), flags); + if ((fst_flags & 2 /* WasiFstFlag.SET_ATIM_NOW */) === 2 /* WasiFstFlag.SET_ATIM_NOW */) { + atim = BigInt(Date.now() * 1000000); + } + if ((fst_flags & 8 /* WasiFstFlag.SET_MTIM_NOW */) === 8 /* WasiFstFlag.SET_MTIM_NOW */) { + mtim = BigInt(Date.now() * 1000000); + } + await fs.promises.utimes(resolvedPath, Number(atim), Number(mtim)); + return 0 /* WasiErrno.ESUCCESS */; + }, ['i32', 'i32', 'i32', 'i32', 'i64', 'i64', 'i32'], ['i32']); + defineImport('path_link', function path_link(old_fd, old_flags, old_path, old_path_len, new_fd, new_path, new_path_len) { + old_path = Number(old_path); + old_path_len = Number(old_path_len); + new_path = Number(new_path); + new_path_len = Number(new_path_len); + if (old_path === 0 || new_path === 0) { + return 28 /* WasiErrno.EINVAL */; + } + const wasi = _wasi.get(this); + let oldWrap; + let newWrap; + if (old_fd === new_fd) { + oldWrap = newWrap = wasi.fds.get(old_fd, WasiRights.PATH_LINK_SOURCE | WasiRights.PATH_LINK_TARGET, BigInt(0)); + } + else { + oldWrap = wasi.fds.get(old_fd, WasiRights.PATH_LINK_SOURCE, BigInt(0)); + newWrap = wasi.fds.get(new_fd, WasiRights.PATH_LINK_TARGET, BigInt(0)); + } + const { HEAPU8 } = getMemory(this, Math.max(old_path + old_path_len, new_path + new_path_len)); + const fs = getFs(this); + const resolvedOldPath = resolvePathSync(fs, oldWrap, decoder.decode(unsharedSlice(HEAPU8, old_path, old_path + old_path_len)), old_flags); + const resolvedNewPath = resolve(newWrap.realPath, decoder.decode(unsharedSlice(HEAPU8, new_path, new_path + new_path_len))); + fs.linkSync(resolvedOldPath, resolvedNewPath); + return 0 /* WasiErrno.ESUCCESS */; + }, async function path_link(old_fd, old_flags, old_path, old_path_len, new_fd, new_path, new_path_len) { + old_path = Number(old_path); + old_path_len = Number(old_path_len); + new_path = Number(new_path); + new_path_len = Number(new_path_len); + if (old_path === 0 || new_path === 0) { + return 28 /* WasiErrno.EINVAL */; + } + const wasi = _wasi.get(this); + let oldWrap; + let newWrap; + if (old_fd === new_fd) { + oldWrap = newWrap = wasi.fds.get(old_fd, WasiRights.PATH_LINK_SOURCE | WasiRights.PATH_LINK_TARGET, BigInt(0)); + } + else { + oldWrap = wasi.fds.get(old_fd, WasiRights.PATH_LINK_SOURCE, BigInt(0)); + newWrap = wasi.fds.get(new_fd, WasiRights.PATH_LINK_TARGET, BigInt(0)); + } + const { HEAPU8 } = getMemory(this, Math.max(old_path + old_path_len, new_path + new_path_len)); + const fs = getFs(this); + const resolvedOldPath = await resolvePathAsync(fs, oldWrap, decoder.decode(unsharedSlice(HEAPU8, old_path, old_path + old_path_len)), old_flags); + const resolvedNewPath = resolve(newWrap.realPath, decoder.decode(unsharedSlice(HEAPU8, new_path, new_path + new_path_len))); + await fs.promises.link(resolvedOldPath, resolvedNewPath); + return 0 /* WasiErrno.ESUCCESS */; + }, ['i32', 'i32', 'i32', 'i32', 'i32', 'i32', 'i32'], ['i32']); + function pathOpen(o_flags, fs_rights_base, fs_rights_inheriting, fs_flags) { + const read = (fs_rights_base & (WasiRights.FD_READ | + WasiRights.FD_READDIR)) !== BigInt(0); + const write = (fs_rights_base & (WasiRights.FD_DATASYNC | + WasiRights.FD_WRITE | + WasiRights.FD_ALLOCATE | + WasiRights.FD_FILESTAT_SET_SIZE)) !== BigInt(0); + let flags = write ? read ? 2 /* FileControlFlag.O_RDWR */ : 1 /* FileControlFlag.O_WRONLY */ : 0 /* FileControlFlag.O_RDONLY */; + let needed_base = WasiRights.PATH_OPEN; + let needed_inheriting = fs_rights_base | fs_rights_inheriting; + if ((o_flags & 1 /* WasiFileControlFlag.O_CREAT */) !== 0) { + flags |= 64 /* FileControlFlag.O_CREAT */; + needed_base |= WasiRights.PATH_CREATE_FILE; + } + if ((o_flags & 2 /* WasiFileControlFlag.O_DIRECTORY */) !== 0) { + flags |= 65536 /* FileControlFlag.O_DIRECTORY */; + } + if ((o_flags & 4 /* WasiFileControlFlag.O_EXCL */) !== 0) { + flags |= 128 /* FileControlFlag.O_EXCL */; + } + if ((o_flags & 8 /* WasiFileControlFlag.O_TRUNC */) !== 0) { + flags |= 512 /* FileControlFlag.O_TRUNC */; + needed_base |= WasiRights.PATH_FILESTAT_SET_SIZE; + } + if ((fs_flags & 1 /* WasiFdFlag.APPEND */) !== 0) { + flags |= 1024 /* FileControlFlag.O_APPEND */; + } + if ((fs_flags & 2 /* WasiFdFlag.DSYNC */) !== 0) { + // flags |= FileControlFlag.O_DSYNC; + needed_inheriting |= WasiRights.FD_DATASYNC; + } + if ((fs_flags & 4 /* WasiFdFlag.NONBLOCK */) !== 0) { + flags |= 2048 /* FileControlFlag.O_NONBLOCK */; + } + if ((fs_flags & 8 /* WasiFdFlag.RSYNC */) !== 0) { + flags |= 1052672 /* FileControlFlag.O_SYNC */; + needed_inheriting |= WasiRights.FD_SYNC; + } + if ((fs_flags & 16 /* WasiFdFlag.SYNC */) !== 0) { + flags |= 1052672 /* FileControlFlag.O_SYNC */; + needed_inheriting |= WasiRights.FD_SYNC; + } + if (write && (flags & (1024 /* FileControlFlag.O_APPEND */ | 512 /* FileControlFlag.O_TRUNC */)) === 0) { + needed_inheriting |= WasiRights.FD_SEEK; + } + return { flags, needed_base, needed_inheriting }; + } + defineImport('path_open', function path_open(dirfd, dirflags, path, path_len, o_flags, fs_rights_base, fs_rights_inheriting, fs_flags, fd) { + path = Number(path); + fd = Number(fd); + if (path === 0 || fd === 0) { + return 28 /* WasiErrno.EINVAL */; + } + path_len = Number(path_len); + fs_rights_base = BigInt(fs_rights_base); + fs_rights_inheriting = BigInt(fs_rights_inheriting); + const { flags: flagsRes, needed_base: neededBase, needed_inheriting: neededInheriting } = pathOpen(o_flags, fs_rights_base, fs_rights_inheriting, fs_flags); + const wasi = _wasi.get(this); + const fileDescriptor = wasi.fds.get(dirfd, neededBase, neededInheriting); + const memory = getMemory(this, Math.max(path + path_len, fd + 4)); + const HEAPU8 = memory.HEAPU8; + const pathString = decoder.decode(unsharedSlice(HEAPU8, path, path + path_len)); + const fs = getFs(this); + const resolved_path = resolvePathSync(fs, fileDescriptor, pathString, dirflags); + const r = fs.openSync(resolved_path, _isWin32Flags ? _toWinOpenFlags(flagsRes) : flagsRes, 0o666); + const filetype = wasi.fds.getFileTypeByFd(r); + if ((filetype !== 3 /* WasiFileType.DIRECTORY */) && + ((o_flags & 2 /* WasiFileControlFlag.O_DIRECTORY */) !== 0 || + (resolved_path.endsWith('/')))) { + return 54 /* WasiErrno.ENOTDIR */; + } + const { base: max_base, inheriting: max_inheriting } = getRights(wasi.fds.stdio, r, flagsRes, filetype); + const wrap = wasi.fds.insert(r, resolved_path, resolved_path, filetype, fs_rights_base & max_base, fs_rights_inheriting & max_inheriting, 0); + const stat = fs.fstatSync(r, { bigint: true }); + if (stat.isFile()) { + wrap.size = stat.size; + if ((flagsRes & 1024 /* FileControlFlag.O_APPEND */) !== 0) { + wrap.pos = stat.size; + } + } + const view = memory.view; + view.setInt32(fd, wrap.id, true); + return 0 /* WasiErrno.ESUCCESS */; + }, async function path_open(dirfd, dirflags, path, path_len, o_flags, fs_rights_base, fs_rights_inheriting, fs_flags, fd) { + path = Number(path); + fd = Number(fd); + if (path === 0 || fd === 0) { + return 28 /* WasiErrno.EINVAL */; + } + path_len = Number(path_len); + fs_rights_base = BigInt(fs_rights_base); + fs_rights_inheriting = BigInt(fs_rights_inheriting); + const { flags: flagsRes, needed_base: neededBase, needed_inheriting: neededInheriting } = pathOpen(o_flags, fs_rights_base, fs_rights_inheriting, fs_flags); + const wasi = _wasi.get(this); + const fileDescriptor = wasi.fds.get(dirfd, neededBase, neededInheriting); + const memory = getMemory(this, Math.max(path + path_len, fd + 4)); + const HEAPU8 = memory.HEAPU8; + const pathString = decoder.decode(unsharedSlice(HEAPU8, path, path + path_len)); + const fs = getFs(this); + const resolved_path = await resolvePathAsync(fs, fileDescriptor, pathString, dirflags); + const r = await fs.promises.open(resolved_path, _isWin32Flags ? _toWinOpenFlags(flagsRes) : flagsRes, 0o666); + const filetype = await wasi.fds.getFileTypeByFd(r); + if ((o_flags & 2 /* WasiFileControlFlag.O_DIRECTORY */) !== 0 && filetype !== 3 /* WasiFileType.DIRECTORY */) { + return 54 /* WasiErrno.ENOTDIR */; + } + const { base: max_base, inheriting: max_inheriting } = getRights(wasi.fds.stdio, r.fd, flagsRes, filetype); + const wrap = wasi.fds.insert(r, resolved_path, resolved_path, filetype, fs_rights_base & max_base, fs_rights_inheriting & max_inheriting, 0); + const stat = await r.stat({ bigint: true }); + if (stat.isFile()) { + wrap.size = stat.size; + if ((flagsRes & 1024 /* FileControlFlag.O_APPEND */) !== 0) { + wrap.pos = stat.size; + } + } + const view = memory.view; + view.setInt32(fd, wrap.id, true); + return 0 /* WasiErrno.ESUCCESS */; + }, ['i32', 'i32', 'i32', 'i32', 'i32', 'i64', 'i64', 'i32', 'i32'], ['i32']); + defineImport('path_readlink', function path_readlink(fd, path, path_len, buf, buf_len, bufused) { + path = Number(path); + path_len = Number(path_len); + buf = Number(buf); + buf_len = Number(buf_len); + bufused = Number(bufused); + if (path === 0 || buf === 0 || bufused === 0) { + return 28 /* WasiErrno.EINVAL */; + } + const { HEAPU8, view } = getMemory(this, Math.max(path + path_len, buf + buf_len, bufused + 4)); + const wasi = _wasi.get(this); + const fileDescriptor = wasi.fds.get(fd, WasiRights.PATH_READLINK, BigInt(0)); + let pathString = decoder.decode(unsharedSlice(HEAPU8, path, path + path_len)); + pathString = resolve(fileDescriptor.realPath, pathString); + const fs = getFs(this); + const link = fs.readlinkSync(pathString); + const linkData = encoder.encode(link); + const len = Math.min(linkData.length, buf_len); + if (len >= buf_len) + return 42 /* WasiErrno.ENOBUFS */; + HEAPU8.set(linkData.subarray(0, len), buf); + HEAPU8[buf + len] = 0; + view.setUint32(bufused, len, true); + return 0 /* WasiErrno.ESUCCESS */; + }, async function path_readlink(fd, path, path_len, buf, buf_len, bufused) { + path = Number(path); + path_len = Number(path_len); + buf = Number(buf); + buf_len = Number(buf_len); + bufused = Number(bufused); + if (path === 0 || buf === 0 || bufused === 0) { + return 28 /* WasiErrno.EINVAL */; + } + const { HEAPU8, view } = getMemory(this, Math.max(path + path_len, buf + buf_len, bufused + 4)); + const wasi = _wasi.get(this); + const fileDescriptor = wasi.fds.get(fd, WasiRights.PATH_READLINK, BigInt(0)); + let pathString = decoder.decode(unsharedSlice(HEAPU8, path, path + path_len)); + pathString = resolve(fileDescriptor.realPath, pathString); + const fs = getFs(this); + const link = await fs.promises.readlink(pathString); + const linkData = encoder.encode(link); + const len = Math.min(linkData.length, buf_len); + if (len >= buf_len) + return 42 /* WasiErrno.ENOBUFS */; + HEAPU8.set(linkData.subarray(0, len), buf); + HEAPU8[buf + len] = 0; + view.setUint32(bufused, len, true); + return 0 /* WasiErrno.ESUCCESS */; + }, ['i32', 'i32', 'i32', 'i32', 'i32', 'i32'], ['i32']); + defineImport('path_remove_directory', function path_remove_directory(fd, path, path_len) { + path = Number(path); + path_len = Number(path_len); + if (path === 0) { + return 28 /* WasiErrno.EINVAL */; + } + const { HEAPU8 } = getMemory(this, path + path_len); + const wasi = _wasi.get(this); + const fileDescriptor = wasi.fds.get(fd, WasiRights.PATH_REMOVE_DIRECTORY, BigInt(0)); + let pathString = decoder.decode(unsharedSlice(HEAPU8, path, path + path_len)); + pathString = resolve(fileDescriptor.realPath, pathString); + const fs = getFs(this); + fs.rmdirSync(pathString); + return 0 /* WasiErrno.ESUCCESS */; + }, async function path_remove_directory(fd, path, path_len) { + path = Number(path); + path_len = Number(path_len); + if (path === 0) { + return 28 /* WasiErrno.EINVAL */; + } + const { HEAPU8 } = getMemory(this, path + path_len); + const wasi = _wasi.get(this); + const fileDescriptor = wasi.fds.get(fd, WasiRights.PATH_REMOVE_DIRECTORY, BigInt(0)); + let pathString = decoder.decode(unsharedSlice(HEAPU8, path, path + path_len)); + pathString = resolve(fileDescriptor.realPath, pathString); + const fs = getFs(this); + await fs.promises.rmdir(pathString); + return 0 /* WasiErrno.ESUCCESS */; + }, ['i32', 'i32', 'i32'], ['i32']); + defineImport('path_rename', function path_rename(old_fd, old_path, old_path_len, new_fd, new_path, new_path_len) { + old_path = Number(old_path); + old_path_len = Number(old_path_len); + new_path = Number(new_path); + new_path_len = Number(new_path_len); + if (old_path === 0 || new_path === 0) { + return 28 /* WasiErrno.EINVAL */; + } + const wasi = _wasi.get(this); + let oldWrap; + let newWrap; + if (old_fd === new_fd) { + oldWrap = newWrap = wasi.fds.get(old_fd, WasiRights.PATH_RENAME_SOURCE | WasiRights.PATH_RENAME_TARGET, BigInt(0)); + } + else { + oldWrap = wasi.fds.get(old_fd, WasiRights.PATH_RENAME_SOURCE, BigInt(0)); + newWrap = wasi.fds.get(new_fd, WasiRights.PATH_RENAME_TARGET, BigInt(0)); + } + const { HEAPU8 } = getMemory(this, Math.max(old_path + old_path_len, new_path + new_path_len)); + const resolvedOldPath = resolve(oldWrap.realPath, decoder.decode(unsharedSlice(HEAPU8, old_path, old_path + old_path_len))); + const resolvedNewPath = resolve(newWrap.realPath, decoder.decode(unsharedSlice(HEAPU8, new_path, new_path + new_path_len))); + const fs = getFs(this); + fs.renameSync(resolvedOldPath, resolvedNewPath); + return 0 /* WasiErrno.ESUCCESS */; + }, async function path_rename(old_fd, old_path, old_path_len, new_fd, new_path, new_path_len) { + old_path = Number(old_path); + old_path_len = Number(old_path_len); + new_path = Number(new_path); + new_path_len = Number(new_path_len); + if (old_path === 0 || new_path === 0) { + return 28 /* WasiErrno.EINVAL */; + } + const wasi = _wasi.get(this); + let oldWrap; + let newWrap; + if (old_fd === new_fd) { + oldWrap = newWrap = wasi.fds.get(old_fd, WasiRights.PATH_RENAME_SOURCE | WasiRights.PATH_RENAME_TARGET, BigInt(0)); + } + else { + oldWrap = wasi.fds.get(old_fd, WasiRights.PATH_RENAME_SOURCE, BigInt(0)); + newWrap = wasi.fds.get(new_fd, WasiRights.PATH_RENAME_TARGET, BigInt(0)); + } + const { HEAPU8 } = getMemory(this, Math.max(old_path + old_path_len, new_path + new_path_len)); + const resolvedOldPath = resolve(oldWrap.realPath, decoder.decode(unsharedSlice(HEAPU8, old_path, old_path + old_path_len))); + const resolvedNewPath = resolve(newWrap.realPath, decoder.decode(unsharedSlice(HEAPU8, new_path, new_path + new_path_len))); + const fs = getFs(this); + await fs.promises.rename(resolvedOldPath, resolvedNewPath); + return 0 /* WasiErrno.ESUCCESS */; + }, ['i32', 'i32', 'i32', 'i32', 'i32', 'i32'], ['i32']); + defineImport('path_symlink', function path_symlink(old_path, old_path_len, fd, new_path, new_path_len) { + old_path = Number(old_path); + old_path_len = Number(old_path_len); + new_path = Number(new_path); + new_path_len = Number(new_path_len); + if (old_path === 0 || new_path === 0) { + return 28 /* WasiErrno.EINVAL */; + } + const { HEAPU8 } = getMemory(this, Math.max(old_path + old_path_len, new_path + new_path_len)); + const wasi = _wasi.get(this); + const fileDescriptor = wasi.fds.get(fd, WasiRights.PATH_SYMLINK, BigInt(0)); + const oldPath = decoder.decode(unsharedSlice(HEAPU8, old_path, old_path + old_path_len)); + if (oldPath.length > 0 && oldPath[0] === '/') { + return 63 /* WasiErrno.EPERM */; + } + let newPath = decoder.decode(unsharedSlice(HEAPU8, new_path, new_path + new_path_len)); + newPath = resolve(fileDescriptor.realPath, newPath); + const fs = getFs(this); + fs.symlinkSync(oldPath, newPath); + return 0 /* WasiErrno.ESUCCESS */; + }, async function path_symlink(old_path, old_path_len, fd, new_path, new_path_len) { + old_path = Number(old_path); + old_path_len = Number(old_path_len); + new_path = Number(new_path); + new_path_len = Number(new_path_len); + if (old_path === 0 || new_path === 0) { + return 28 /* WasiErrno.EINVAL */; + } + const { HEAPU8 } = getMemory(this, Math.max(old_path + old_path_len, new_path + new_path_len)); + const wasi = _wasi.get(this); + const fileDescriptor = wasi.fds.get(fd, WasiRights.PATH_SYMLINK, BigInt(0)); + const oldPath = decoder.decode(unsharedSlice(HEAPU8, old_path, old_path + old_path_len)); + let newPath = decoder.decode(unsharedSlice(HEAPU8, new_path, new_path + new_path_len)); + newPath = resolve(fileDescriptor.realPath, newPath); + const fs = getFs(this); + await fs.promises.symlink(oldPath, newPath); + return 0 /* WasiErrno.ESUCCESS */; + }, ['i32', 'i32', 'i32', 'i32', 'i32'], ['i32']); + defineImport('path_unlink_file', function path_unlink_file(fd, path, path_len) { + path = Number(path); + path_len = Number(path_len); + if (path === 0) { + return 28 /* WasiErrno.EINVAL */; + } + const { HEAPU8 } = getMemory(this, path + path_len); + const wasi = _wasi.get(this); + const fileDescriptor = wasi.fds.get(fd, WasiRights.PATH_UNLINK_FILE, BigInt(0)); + let pathString = decoder.decode(unsharedSlice(HEAPU8, path, path + path_len)); + pathString = resolve(fileDescriptor.realPath, pathString); + const fs = getFs(this); + fs.unlinkSync(pathString); + return 0 /* WasiErrno.ESUCCESS */; + }, async function path_unlink_file(fd, path, path_len) { + path = Number(path); + path_len = Number(path_len); + if (path === 0) { + return 28 /* WasiErrno.EINVAL */; + } + const { HEAPU8 } = getMemory(this, path + path_len); + const wasi = _wasi.get(this); + const fileDescriptor = wasi.fds.get(fd, WasiRights.PATH_UNLINK_FILE, BigInt(0)); + let pathString = decoder.decode(unsharedSlice(HEAPU8, path, path + path_len)); + pathString = resolve(fileDescriptor.realPath, pathString); + const fs = getFs(this); + await fs.promises.unlink(pathString); + return 0 /* WasiErrno.ESUCCESS */; + }, ['i32', 'i32', 'i32'], ['i32']); + this._setMemory = function setMemory(m) { + if (!(m instanceof _WebAssembly.Memory)) { + throw new TypeError('"instance.exports.memory" property must be a WebAssembly.Memory'); + } + _memory.set(_this, extendMemory(m)); + }; + } + static createSync(args, env, preopens, stdio, fs, print, printErr) { + const fds = new SyncTable({ + size: 3, + in: stdio[0], + out: stdio[1], + err: stdio[2], + fs, + print, + printErr + }); + const _this = new WASI$1(args, env, fds, false, fs); + if (preopens.length > 0) { + for (let i = 0; i < preopens.length; ++i) { + const realPath = fs.realpathSync(preopens[i].realPath, 'utf8'); + const fd = fs.openSync(realPath, 'r', 0o666); + fds.insertPreopen(fd, preopens[i].mappedPath, realPath); + } + } + return _this; + } + static async createAsync(args, env, preopens, stdio, fs, print, printErr, asyncify) { + const fds = new AsyncTable({ + size: 3, + in: stdio[0], + out: stdio[1], + err: stdio[2], + print, + printErr + }); + const _this = new WASI$1(args, env, fds, true, fs, asyncify); + if (preopens.length > 0) { + for (let i = 0; i < preopens.length; ++i) { + const entry = preopens[i]; + const realPath = await fs.promises.realpath(entry.realPath); + const fd = await fs.promises.open(realPath, 'r', 0o666); + await fds.insertPreopen(fd, entry.mappedPath, realPath); + } + } + return _this; + } +} + +// eslint-disable-next-line spaced-comment +const kEmptyObject = /*#__PURE__*/ Object.freeze(/*#__PURE__*/ Object.create(null)); +const kExitCode = Symbol('kExitCode'); +const kSetMemory = Symbol('kSetMemory'); +const kStarted = Symbol('kStarted'); +const kInstance = Symbol('kInstance'); +const kBindingName = Symbol('kBindingName'); +function validateOptions(options) { + var _a; + validateObject(options, 'options'); + let _WASI; + if (options.version !== undefined) { + validateString(options.version, 'options.version'); + switch (options.version) { + case 'unstable': + _WASI = WASI$1; + this[kBindingName] = 'wasi_unstable'; + break; + case 'preview1': + _WASI = WASI$1; + this[kBindingName] = 'wasi_snapshot_preview1'; + break; + default: + throw new TypeError(`unsupported WASI version "${options.version}"`); + } + } + else { + _WASI = WASI$1; + this[kBindingName] = 'wasi_snapshot_preview1'; + } + if (options.args !== undefined) { + validateArray(options.args, 'options.args'); + } + const args = ((_a = options.args) !== null && _a !== void 0 ? _a : []).map(String); + const env = []; + if (options.env !== undefined) { + validateObject(options.env, 'options.env'); + Object.entries(options.env).forEach(({ 0: key, 1: value }) => { + if (value !== undefined) { + env.push(`${key}=${value}`); + } + }); + } + const preopens = []; + if (options.preopens !== undefined) { + validateObject(options.preopens, 'options.preopens'); + Object.entries(options.preopens).forEach(({ 0: key, 1: value }) => preopens.push({ mappedPath: String(key), realPath: String(value) })); + } + if (preopens.length > 0) { + if (options.fs === undefined) { + throw new Error('filesystem is disabled, can not preopen directory'); + } + try { + validateObject(options.fs, 'options.fs'); + } + catch (_) { + throw new TypeError('Node.js fs like implementation is not provided'); + } + } + // if (options.filesystem !== undefined) { + // validateObject(options.filesystem, 'options.filesystem') + // validateString(options.filesystem.type, 'options.filesystem.type') + // if (options.filesystem.type !== 'memfs' && options.filesystem.type !== 'file-system-access-api') { + // throw new Error(`Filesystem type ${(options.filesystem as any).type as string} is not supported, only "memfs" and "file-system-access-api" is supported currently`) + // } + // try { + // validateObject(options.filesystem.fs, 'options.filesystem.fs') + // } catch (_) { + // throw new Error('Node.js fs like implementation is not provided') + // } + // } + if (options.print !== undefined) + validateFunction(options.print, 'options.print'); + if (options.printErr !== undefined) + validateFunction(options.printErr, 'options.printErr'); + if (options.returnOnExit !== undefined) { + validateBoolean(options.returnOnExit, 'options.returnOnExit'); + } + // const { stdin = 0, stdout = 1, stderr = 2 } = options + // validateInt32(stdin, 'options.stdin', 0) + // validateInt32(stdout, 'options.stdout', 0) + // validateInt32(stderr, 'options.stderr', 0) + // const stdio = [stdin, stdout, stderr] as const + const stdio = [0, 1, 2]; + return { + args, + env, + preopens, + stdio, + _WASI + }; +} +function initWASI(setMemory, wrap) { + this[kSetMemory] = setMemory; + this.wasiImport = wrap; + this[kStarted] = false; + this[kExitCode] = 0; + this[kInstance] = undefined; +} +/** @public */ +class WASI { + constructor(options = kEmptyObject) { + const { args, env, preopens, stdio, _WASI } = validateOptions.call(this, options); + const wrap = _WASI.createSync(args, env, preopens, stdio, options.fs, options.print, options.printErr); + const setMemory = wrap._setMemory; + delete wrap._setMemory; + initWASI.call(this, setMemory, wrap); + if (options.returnOnExit) { + wrap.proc_exit = wasiReturnOnProcExit.bind(this); + } + } + finalizeBindings(instance, _a) { + var _b; + var { memory = (_b = instance === null || instance === void 0 ? void 0 : instance.exports) === null || _b === void 0 ? void 0 : _b.memory } = _a === void 0 ? {} : _a; + if (this[kStarted]) { + throw new Error('WASI instance has already started'); + } + validateObject(instance, 'instance'); + validateObject(instance.exports, 'instance.exports'); + this[kSetMemory](memory); + this[kInstance] = instance; + this[kStarted] = true; + } + // Must not export _initialize, must export _start + start(instance) { + this.finalizeBindings(instance); + const { _start, _initialize } = this[kInstance].exports; + validateFunction(_start, 'instance.exports._start'); + validateUndefined(_initialize, 'instance.exports._initialize'); + let ret; + try { + ret = _start(); + } + catch (err) { + if (err !== kExitCode) { + throw err; + } + } + if (ret instanceof Promise) { + return ret.then(() => this[kExitCode], (err) => { + if (err !== kExitCode) { + throw err; + } + return this[kExitCode]; + }); + } + return this[kExitCode]; + } + // Must not export _start, may optionally export _initialize + initialize(instance) { + this.finalizeBindings(instance); + const { _start, _initialize } = this[kInstance].exports; + validateUndefined(_start, 'instance.exports._start'); + if (_initialize !== undefined) { + validateFunction(_initialize, 'instance.exports._initialize'); + return _initialize(); + } + } + getImportObject() { + return { [this[kBindingName]]: this.wasiImport }; + } +} +function wasiReturnOnProcExit(rval) { + this[kExitCode] = rval; + // eslint-disable-next-line @typescript-eslint/no-throw-literal + throw kExitCode; +} +/** @public */ +async function createAsyncWASI(options = kEmptyObject) { + const _this = Object.create(WASI.prototype); + const { args, env, preopens, stdio, _WASI } = validateOptions.call(_this, options); + if (options.asyncify !== undefined) { + validateObject(options.asyncify, 'options.asyncify'); + validateFunction(options.asyncify.wrapImportFunction, 'options.asyncify.wrapImportFunction'); + } + const wrap = await _WASI.createAsync(args, env, preopens, stdio, options.fs, options.print, options.printErr, options.asyncify); + const setMemory = wrap._setMemory; + delete wrap._setMemory; + initWASI.call(_this, setMemory, wrap); + if (options.returnOnExit) { + wrap.proc_exit = wasiReturnOnProcExit.bind(_this); + } + return _this; +} + +export { Asyncify, Memory, WASI, WebAssemblyMemory, asyncifyLoad, asyncifyLoadSync, createAsyncWASI, extendMemory, load, loadSync, wrapAsyncExport, wrapAsyncImport, wrapExports }; diff --git a/dg-ui/node_modules/@tailwindcss/oxide-wasm32-wasi/node_modules/@tybys/wasm-util/dist/wasm-util.esm.js b/dg-ui/node_modules/@tailwindcss/oxide-wasm32-wasi/node_modules/@tybys/wasm-util/dist/wasm-util.esm.js new file mode 100644 index 0000000..42ad93d --- /dev/null +++ b/dg-ui/node_modules/@tailwindcss/oxide-wasm32-wasi/node_modules/@tybys/wasm-util/dist/wasm-util.esm.js @@ -0,0 +1,2932 @@ +const _WebAssembly = typeof WebAssembly !== 'undefined' + ? WebAssembly + : typeof WXWebAssembly !== 'undefined' + ? WXWebAssembly + : undefined; +if (!_WebAssembly) { + throw new Error('WebAssembly is not supported in this environment'); +} + +/* eslint-disable spaced-comment */ + +function validateObject(value, name) { + if (value === null || typeof value !== 'object') { + throw new TypeError(`${name} must be an object. Received ${value === null ? 'null' : typeof value}`); + } +} +function validateArray(value, name) { + if (!Array.isArray(value)) { + throw new TypeError(`${name} must be an array. Received ${value === null ? 'null' : typeof value}`); + } +} +function validateBoolean(value, name) { + if (typeof value !== 'boolean') { + throw new TypeError(`${name} must be a boolean. Received ${value === null ? 'null' : typeof value}`); + } +} +function validateString(value, name) { + if (typeof value !== 'string') { + throw new TypeError(`${name} must be a string. Received ${value === null ? 'null' : typeof value}`); + } +} +function validateFunction(value, name) { + if (typeof value !== 'function') { + throw new TypeError(`${name} must be a function. Received ${value === null ? 'null' : typeof value}`); + } +} +function validateUndefined(value, name) { + if (value !== undefined) { + throw new TypeError(`${name} must be undefined. Received ${value === null ? 'null' : typeof value}`); + } +} +function isPromiseLike(obj) { + return !!(obj && (typeof obj === 'object' || typeof obj === 'function') && typeof obj.then === 'function'); +} +function wrapInstanceExports(exports, mapFn) { + const newExports = Object.create(null); + Object.keys(exports).forEach(name => { + const exportValue = exports[name]; + Object.defineProperty(newExports, name, { + enumerable: true, + value: mapFn(exportValue, name) + }); + }); + return newExports; +} +function sleepBreakIf(delay, breakIf) { + const start = Date.now(); + const end = start + delay; + let ret = false; + while (Date.now() < end) { + if (breakIf()) { + ret = true; + break; + } + } + return ret; +} +function unsharedSlice(view, start, end) { + return ((typeof SharedArrayBuffer === 'function' && view.buffer instanceof SharedArrayBuffer) || (Object.prototype.toString.call(view.buffer.constructor) === '[object SharedArrayBuffer]')) + ? view.slice(start, end) + : view.subarray(start, end); +} + +const ignoreNames = [ + 'asyncify_get_state', + 'asyncify_start_rewind', + 'asyncify_start_unwind', + 'asyncify_stop_rewind', + 'asyncify_stop_unwind' +]; +function tryAllocate(instance, wasm64, size, mallocName) { + if (typeof instance.exports[mallocName] !== 'function' || size <= 0) { + return { + wasm64, + dataPtr: 16, + start: wasm64 ? 32 : 24, + end: 1024 + }; + } + const malloc = instance.exports[mallocName]; + const dataPtr = wasm64 ? Number(malloc(BigInt(16) + BigInt(size))) : malloc(8 + size); + if (dataPtr === 0) { + throw new Error('Allocate asyncify data failed'); + } + return wasm64 + ? { wasm64, dataPtr, start: dataPtr + 16, end: dataPtr + 16 + size } + : { wasm64, dataPtr, start: dataPtr + 8, end: dataPtr + 8 + size }; +} +/** @public */ +class Asyncify { + constructor() { + this.value = undefined; + this.exports = undefined; + this.dataPtr = 0; + } + init(memory, instance, options) { + var _a, _b; + if (this.exports) { + throw new Error('Asyncify has been initialized'); + } + if (!(memory instanceof _WebAssembly.Memory)) { + throw new TypeError('Require WebAssembly.Memory object'); + } + const exports = instance.exports; + for (let i = 0; i < ignoreNames.length; ++i) { + if (typeof exports[ignoreNames[i]] !== 'function') { + throw new TypeError('Invalid asyncify wasm'); + } + } + let address; + const wasm64 = Boolean(options.wasm64); + if (!options.tryAllocate) { + address = { + wasm64, + dataPtr: 16, + start: wasm64 ? 32 : 24, + end: 1024 + }; + } + else { + if (options.tryAllocate === true) { + address = tryAllocate(instance, wasm64, 4096, 'malloc'); + } + else { + address = tryAllocate(instance, wasm64, (_a = options.tryAllocate.size) !== null && _a !== void 0 ? _a : 4096, (_b = options.tryAllocate.name) !== null && _b !== void 0 ? _b : 'malloc'); + } + } + this.dataPtr = address.dataPtr; + if (wasm64) { + new BigInt64Array(memory.buffer, this.dataPtr).set([BigInt(address.start), BigInt(address.end)]); + } + else { + new Int32Array(memory.buffer, this.dataPtr).set([address.start, address.end]); + } + this.exports = this.wrapExports(exports, options.wrapExports); + const asyncifiedInstance = Object.create(_WebAssembly.Instance.prototype); + Object.defineProperty(asyncifiedInstance, 'exports', { value: this.exports }); + // Object.setPrototypeOf(instance, Instance.prototype) + return asyncifiedInstance; + } + assertState() { + if (this.exports.asyncify_get_state() !== 0 /* AsyncifyState.NONE */) { + throw new Error('Asyncify state error'); + } + } + wrapImportFunction(f) { + // eslint-disable-next-line @typescript-eslint/no-this-alias + const _this = this; + return (function () { + // eslint-disable-next-line no-unreachable-loop + while (_this.exports.asyncify_get_state() === 2 /* AsyncifyState.REWINDING */) { + _this.exports.asyncify_stop_rewind(); + return _this.value; + } + _this.assertState(); + const v = f.apply(this, arguments); + if (!isPromiseLike(v)) + return v; + _this.exports.asyncify_start_unwind(_this.dataPtr); + _this.value = v; + }); + } + wrapImports(imports) { + const importObject = {}; + Object.keys(imports).forEach(k => { + const mod = imports[k]; + const newModule = {}; + Object.keys(mod).forEach(name => { + const importValue = mod[name]; + if (typeof importValue === 'function') { + newModule[name] = this.wrapImportFunction(importValue); + } + else { + newModule[name] = importValue; + } + }); + importObject[k] = newModule; + }); + return importObject; + } + wrapExportFunction(f) { + // eslint-disable-next-line @typescript-eslint/no-this-alias + const _this = this; + return (async function () { + _this.assertState(); + let ret = f.apply(this, arguments); + while (_this.exports.asyncify_get_state() === 1 /* AsyncifyState.UNWINDING */) { + _this.exports.asyncify_stop_unwind(); + _this.value = await _this.value; + _this.assertState(); + _this.exports.asyncify_start_rewind(_this.dataPtr); + ret = f.call(this); + } + _this.assertState(); + return ret; + }); + } + wrapExports(exports, needWrap) { + return wrapInstanceExports(exports, (exportValue, name) => { + let ignore = ignoreNames.indexOf(name) !== -1 || typeof exportValue !== 'function'; + if (Array.isArray(needWrap)) { + ignore = ignore || (needWrap.indexOf(name) === -1); + } + return ignore ? exportValue : this.wrapExportFunction(exportValue); + }); + } +} + +function validateImports(imports) { + if (imports && typeof imports !== 'object') { + throw new TypeError('imports must be an object or undefined'); + } +} +function fetchWasm(urlOrBuffer, imports) { + if (typeof wx !== 'undefined' && typeof __wxConfig !== 'undefined') { + return _WebAssembly.instantiate(urlOrBuffer, imports); + } + return fetch(urlOrBuffer) + .then(response => response.arrayBuffer()) + .then(buffer => _WebAssembly.instantiate(buffer, imports)); +} +/** @public */ +function load(wasmInput, imports) { + validateImports(imports); + imports = imports !== null && imports !== void 0 ? imports : {}; + let source; + if (wasmInput instanceof ArrayBuffer || ArrayBuffer.isView(wasmInput)) { + return _WebAssembly.instantiate(wasmInput, imports); + } + if (wasmInput instanceof _WebAssembly.Module) { + return _WebAssembly.instantiate(wasmInput, imports).then((instance) => { + return { instance, module: wasmInput }; + }); + } + if (typeof wasmInput !== 'string' && !(wasmInput instanceof URL)) { + throw new TypeError('Invalid source'); + } + if (typeof _WebAssembly.instantiateStreaming === 'function') { + let responsePromise; + try { + responsePromise = fetch(wasmInput); + source = _WebAssembly.instantiateStreaming(responsePromise, imports).catch(() => { + return fetchWasm(wasmInput, imports); + }); + } + catch (_) { + source = fetchWasm(wasmInput, imports); + } + } + else { + source = fetchWasm(wasmInput, imports); + } + return source; +} +/** @public */ +function asyncifyLoad(asyncify, urlOrBuffer, imports) { + validateImports(imports); + imports = imports !== null && imports !== void 0 ? imports : {}; + const asyncifyHelper = new Asyncify(); + imports = asyncifyHelper.wrapImports(imports); + return load(urlOrBuffer, imports).then(source => { + var _a; + const memory = source.instance.exports.memory || ((_a = imports.env) === null || _a === void 0 ? void 0 : _a.memory); + return { module: source.module, instance: asyncifyHelper.init(memory, source.instance, asyncify) }; + }); +} +/** @public */ +function loadSync(wasmInput, imports) { + validateImports(imports); + imports = imports !== null && imports !== void 0 ? imports : {}; + let module; + if ((wasmInput instanceof ArrayBuffer) || ArrayBuffer.isView(wasmInput)) { + module = new _WebAssembly.Module(wasmInput); + } + else if (wasmInput instanceof WebAssembly.Module) { + module = wasmInput; + } + else { + throw new TypeError('Invalid source'); + } + const instance = new _WebAssembly.Instance(module, imports); + const source = { instance, module }; + return source; +} +/** @public */ +function asyncifyLoadSync(asyncify, buffer, imports) { + var _a; + validateImports(imports); + imports = imports !== null && imports !== void 0 ? imports : {}; + const asyncifyHelper = new Asyncify(); + imports = asyncifyHelper.wrapImports(imports); + const source = loadSync(buffer, imports); + const memory = source.instance.exports.memory || ((_a = imports.env) === null || _a === void 0 ? void 0 : _a.memory); + return { module: source.module, instance: asyncifyHelper.init(memory, source.instance, asyncify) }; +} + +const CHAR_DOT = 46; /* . */ +const CHAR_FORWARD_SLASH = 47; /* / */ +const CHAR_BACKWARD_SLASH = 92; /* \ */ +const CHAR_COLON = 58; /* : */ +const CHAR_UPPERCASE_A = 65; /* A */ +const CHAR_UPPERCASE_Z = 90; /* Z */ +const CHAR_LOWERCASE_A = 97; /* a */ +const CHAR_LOWERCASE_Z = 122; /* z */ +function isPathSeparatorWin(code) { + return code === CHAR_FORWARD_SLASH || code === CHAR_BACKWARD_SLASH; +} +function isWindowsDeviceRoot(code) { + return (code >= CHAR_UPPERCASE_A && code <= CHAR_UPPERCASE_Z) || + (code >= CHAR_LOWERCASE_A && code <= CHAR_LOWERCASE_Z); +} +const _isWin32 = typeof process !== 'undefined' && process.platform === 'win32'; +/** + * Windows variant of `resolve()`. Mirrors Node's `path.win32.resolve` + * semantics enough for the WASI shim's needs (drive-letter absolutes + * + UNC paths + per-drive cwd lookups via `process.env`/`process.cwd`). + * + * Why this is needed: on Windows, `FileDescriptor.realPath` is the + * host realpath returned by `fs.realpathSync(realPath, 'utf8')` — the + * backslash form `D:\…`. The POSIX-only `resolveImpl` below only + * treats `/` as a separator, reads `D` as non-`/`, decides realPath + * is "relative", and produces a garbage joined path. Downstream + * `fs.openSync(garbage)` then returns `EINVAL` and the WASI caller + * sees a permanent failure. This function gives us the correct + * Windows-style resolution without taking a Node-only `path` import + * (which would break browser bundles of this package). + * + * Cribbed from Node's `lib/path.js` `win32.resolve()` (MIT-licensed), + * trimmed to what WASI realpath resolution actually exercises. + */ +function resolveWin32(args) { + let resolvedDevice = ''; + let resolvedTail = ''; + let resolvedAbsolute = false; + for (let i = args.length - 1; i >= -1; i--) { + let path; + if (i >= 0) { + path = args[i]; + validateString(path, 'path'); + if (path.length === 0) + continue; + } + else if (resolvedDevice.length === 0) { + path = (typeof process !== 'undefined' && typeof process.cwd === 'function') + ? process.cwd() + : ''; + } + else { + // Look up per-drive cwd via the `=X:` env var convention; fall back + // to the global cwd if absent. + const envKey = `=${resolvedDevice}`; + const env = (typeof process !== 'undefined') ? process.env : undefined; + path = (env && typeof env[envKey] === 'string') + ? env[envKey] + : (typeof process !== 'undefined' && typeof process.cwd === 'function') + ? process.cwd() + : ''; + if (path === undefined || + (path.slice(0, 2).toLowerCase() !== resolvedDevice.toLowerCase() && + path.charCodeAt(2) === CHAR_BACKWARD_SLASH)) { + path = `${resolvedDevice}\\`; + } + } + const len = path.length; + let rootEnd = 0; + let device = ''; + let isAbsolute = false; + const code = path.charCodeAt(0); + if (len === 1) { + if (isPathSeparatorWin(code)) { + rootEnd = 1; + isAbsolute = true; + } + } + else if (isPathSeparatorWin(code)) { + isAbsolute = true; + if (isPathSeparatorWin(path.charCodeAt(1))) { + // UNC path: `\\server\share\…` + let j = 2; + let last = j; + while (j < len && !isPathSeparatorWin(path.charCodeAt(j))) + j++; + if (j < len && j !== last) { + const firstPart = path.slice(last, j); + last = j; + while (j < len && isPathSeparatorWin(path.charCodeAt(j))) + j++; + if (j < len && j !== last) { + last = j; + while (j < len && !isPathSeparatorWin(path.charCodeAt(j))) + j++; + if (j === len || j !== last) { + device = `\\\\${firstPart}\\${path.slice(last, j)}`; + rootEnd = j; + } + } + } + } + else { + rootEnd = 1; + } + } + else if (isWindowsDeviceRoot(code) && path.charCodeAt(1) === CHAR_COLON) { + device = path.slice(0, 2); + rootEnd = 2; + if (len > 2 && isPathSeparatorWin(path.charCodeAt(2))) { + isAbsolute = true; + rootEnd = 3; + } + } + if (device.length > 0) { + if (resolvedDevice.length > 0) { + if (device.toLowerCase() !== resolvedDevice.toLowerCase()) + continue; + } + else { + resolvedDevice = device; + } + } + if (resolvedAbsolute) { + if (resolvedDevice.length > 0) + break; + } + else { + resolvedTail = `${path.slice(rootEnd)}\\${resolvedTail}`; + resolvedAbsolute = isAbsolute; + if (isAbsolute && resolvedDevice.length > 0) + break; + } + } + resolvedTail = normalizeString(resolvedTail, !resolvedAbsolute, '\\', isPathSeparatorWin); + return resolvedDevice + (resolvedAbsolute ? '\\' : '') + resolvedTail || '.'; +} +function isPosixPathSeparator(code) { + return code === CHAR_FORWARD_SLASH; +} +function normalizeString(path, allowAboveRoot, separator, isPathSeparator) { + let res = ''; + let lastSegmentLength = 0; + let lastSlash = -1; + let dots = 0; + let code = 0; + for (let i = 0; i <= path.length; ++i) { + if (i < path.length) { + code = path.charCodeAt(i); + } + else if (isPathSeparator(code)) { + break; + } + else { + code = CHAR_FORWARD_SLASH; + } + if (isPathSeparator(code)) { + if (lastSlash === i - 1 || dots === 1) ; + else if (dots === 2) { + if (res.length < 2 || lastSegmentLength !== 2 || + res.charCodeAt(res.length - 1) !== CHAR_DOT || + res.charCodeAt(res.length - 2) !== CHAR_DOT) { + if (res.length > 2) { + const lastSlashIndex = res.indexOf(separator); + if (lastSlashIndex === -1) { + res = ''; + lastSegmentLength = 0; + } + else { + res = res.slice(0, lastSlashIndex); + lastSegmentLength = + res.length - 1 - res.indexOf(separator); + } + lastSlash = i; + dots = 0; + continue; + } + else if (res.length !== 0) { + res = ''; + lastSegmentLength = 0; + lastSlash = i; + dots = 0; + continue; + } + } + if (allowAboveRoot) { + res += res.length > 0 ? `${separator}..` : '..'; + lastSegmentLength = 2; + } + } + else { + if (res.length > 0) { + res += `${separator}${path.slice(lastSlash + 1, i)}`; + } + else { + res = path.slice(lastSlash + 1, i); + } + lastSegmentLength = i - lastSlash - 1; + } + lastSlash = i; + dots = 0; + } + else if (code === CHAR_DOT && dots !== -1) { + ++dots; + } + else { + dots = -1; + } + } + return res; +} +function resolve(...args) { + // On Windows, host paths are `D:\…` style. The POSIX-only resolver + // below treats `D` as a non-`/` character and produces garbage; route + // to the Windows-aware variant. POSIX hosts (Linux/macOS/browser) + // run the original code path unchanged — `_isWin32` is constant-folded + // away on those targets. + if (_isWin32) + return resolveWin32(args); + let resolvedPath = ''; + let resolvedAbsolute = false; + for (let i = args.length - 1; i >= -1 && !resolvedAbsolute; i--) { + const path = i >= 0 ? args[i] : '/'; + validateString(path, 'path'); + // Skip empty entries + if (path.length === 0) { + continue; + } + resolvedPath = `${path}/${resolvedPath}`; + resolvedAbsolute = path.charCodeAt(0) === CHAR_FORWARD_SLASH; + } + // At this point the path should be resolved to a full absolute path, but + // handle relative paths to be safe (might happen when process.cwd() fails) + // Normalize the path + resolvedPath = normalizeString(resolvedPath, !resolvedAbsolute, '/', isPosixPathSeparator); + if (resolvedAbsolute) { + return `/${resolvedPath}`; + } + return resolvedPath.length > 0 ? resolvedPath : '.'; +} + +const FD_DATASYNC = ( /*#__PURE__*/BigInt(1) << /*#__PURE__*/ BigInt(0)); +const FD_READ = ( /*#__PURE__*/BigInt(1) << /*#__PURE__*/ BigInt(1)); +const FD_SEEK = ( /*#__PURE__*/BigInt(1) << /*#__PURE__*/ BigInt(2)); +const FD_FDSTAT_SET_FLAGS = ( /*#__PURE__*/BigInt(1) << /*#__PURE__*/ BigInt(3)); +const FD_SYNC = ( /*#__PURE__*/BigInt(1) << /*#__PURE__*/ BigInt(4)); +const FD_TELL = ( /*#__PURE__*/BigInt(1) << /*#__PURE__*/ BigInt(5)); +const FD_WRITE = ( /*#__PURE__*/BigInt(1) << /*#__PURE__*/ BigInt(6)); +const FD_ADVISE = ( /*#__PURE__*/BigInt(1) << /*#__PURE__*/ BigInt(7)); +const FD_ALLOCATE = ( /*#__PURE__*/BigInt(1) << /*#__PURE__*/ BigInt(8)); +const PATH_CREATE_DIRECTORY = ( /*#__PURE__*/BigInt(1) << /*#__PURE__*/ BigInt(9)); +const PATH_CREATE_FILE = ( /*#__PURE__*/BigInt(1) << /*#__PURE__*/ BigInt(10)); +const PATH_LINK_SOURCE = ( /*#__PURE__*/BigInt(1) << /*#__PURE__*/ BigInt(11)); +const PATH_LINK_TARGET = ( /*#__PURE__*/BigInt(1) << /*#__PURE__*/ BigInt(12)); +const PATH_OPEN = ( /*#__PURE__*/BigInt(1) << /*#__PURE__*/ BigInt(13)); +const FD_READDIR = ( /*#__PURE__*/BigInt(1) << /*#__PURE__*/ BigInt(14)); +const PATH_READLINK = ( /*#__PURE__*/BigInt(1) << /*#__PURE__*/ BigInt(15)); +const PATH_RENAME_SOURCE = ( /*#__PURE__*/BigInt(1) << /*#__PURE__*/ BigInt(16)); +const PATH_RENAME_TARGET = ( /*#__PURE__*/BigInt(1) << /*#__PURE__*/ BigInt(17)); +const PATH_FILESTAT_GET = ( /*#__PURE__*/BigInt(1) << /*#__PURE__*/ BigInt(18)); +const PATH_FILESTAT_SET_SIZE = ( /*#__PURE__*/BigInt(1) << /*#__PURE__*/ BigInt(19)); +const PATH_FILESTAT_SET_TIMES = ( /*#__PURE__*/BigInt(1) << /*#__PURE__*/ BigInt(20)); +const FD_FILESTAT_GET = ( /*#__PURE__*/BigInt(1) << /*#__PURE__*/ BigInt(21)); +const FD_FILESTAT_SET_SIZE = ( /*#__PURE__*/BigInt(1) << /*#__PURE__*/ BigInt(22)); +const FD_FILESTAT_SET_TIMES = ( /*#__PURE__*/BigInt(1) << /*#__PURE__*/ BigInt(23)); +const PATH_SYMLINK = ( /*#__PURE__*/BigInt(1) << /*#__PURE__*/ BigInt(24)); +const PATH_REMOVE_DIRECTORY = ( /*#__PURE__*/BigInt(1) << /*#__PURE__*/ BigInt(25)); +const PATH_UNLINK_FILE = ( /*#__PURE__*/BigInt(1) << /*#__PURE__*/ BigInt(26)); +const POLL_FD_READWRITE = ( /*#__PURE__*/BigInt(1) << /*#__PURE__*/ BigInt(27)); +const SOCK_SHUTDOWN = ( /*#__PURE__*/BigInt(1) << /*#__PURE__*/ BigInt(28)); +const SOCK_ACCEPT = ( /*#__PURE__*/BigInt(1) << /*#__PURE__*/ BigInt(29)); +const WasiRights = { + FD_DATASYNC, + FD_READ, + FD_SEEK, + FD_FDSTAT_SET_FLAGS, + FD_SYNC, + FD_TELL, + FD_WRITE, + FD_ADVISE, + FD_ALLOCATE, + PATH_CREATE_DIRECTORY, + PATH_CREATE_FILE, + PATH_LINK_SOURCE, + PATH_LINK_TARGET, + PATH_OPEN, + FD_READDIR, + PATH_READLINK, + PATH_RENAME_SOURCE, + PATH_RENAME_TARGET, + PATH_FILESTAT_GET, + PATH_FILESTAT_SET_SIZE, + PATH_FILESTAT_SET_TIMES, + FD_FILESTAT_GET, + FD_FILESTAT_SET_SIZE, + FD_FILESTAT_SET_TIMES, + PATH_SYMLINK, + PATH_REMOVE_DIRECTORY, + PATH_UNLINK_FILE, + POLL_FD_READWRITE, + SOCK_SHUTDOWN, + SOCK_ACCEPT +}; + +function strerror(errno) { + switch (errno) { + case 0 /* WasiErrno.ESUCCESS */: return 'Success'; + case 1 /* WasiErrno.E2BIG */: return 'Argument list too long'; + case 2 /* WasiErrno.EACCES */: return 'Permission denied'; + case 3 /* WasiErrno.EADDRINUSE */: return 'Address in use'; + case 4 /* WasiErrno.EADDRNOTAVAIL */: return 'Address not available'; + case 5 /* WasiErrno.EAFNOSUPPORT */: return 'Address family not supported by protocol'; + case 6 /* WasiErrno.EAGAIN */: return 'Resource temporarily unavailable'; + case 7 /* WasiErrno.EALREADY */: return 'Operation already in progress'; + case 8 /* WasiErrno.EBADF */: return 'Bad file descriptor'; + case 9 /* WasiErrno.EBADMSG */: return 'Bad message'; + case 10 /* WasiErrno.EBUSY */: return 'Resource busy'; + case 11 /* WasiErrno.ECANCELED */: return 'Operation canceled'; + case 12 /* WasiErrno.ECHILD */: return 'No child process'; + case 13 /* WasiErrno.ECONNABORTED */: return 'Connection aborted'; + case 14 /* WasiErrno.ECONNREFUSED */: return 'Connection refused'; + case 15 /* WasiErrno.ECONNRESET */: return 'Connection reset by peer'; + case 16 /* WasiErrno.EDEADLK */: return 'Resource deadlock would occur'; + case 17 /* WasiErrno.EDESTADDRREQ */: return 'Destination address required'; + case 18 /* WasiErrno.EDOM */: return 'Domain error'; + case 19 /* WasiErrno.EDQUOT */: return 'Quota exceeded'; + case 20 /* WasiErrno.EEXIST */: return 'File exists'; + case 21 /* WasiErrno.EFAULT */: return 'Bad address'; + case 22 /* WasiErrno.EFBIG */: return 'File too large'; + case 23 /* WasiErrno.EHOSTUNREACH */: return 'Host is unreachable'; + case 24 /* WasiErrno.EIDRM */: return 'Identifier removed'; + case 25 /* WasiErrno.EILSEQ */: return 'Illegal byte sequence'; + case 26 /* WasiErrno.EINPROGRESS */: return 'Operation in progress'; + case 27 /* WasiErrno.EINTR */: return 'Interrupted system call'; + case 28 /* WasiErrno.EINVAL */: return 'Invalid argument'; + case 29 /* WasiErrno.EIO */: return 'I/O error'; + case 30 /* WasiErrno.EISCONN */: return 'Socket is connected'; + case 31 /* WasiErrno.EISDIR */: return 'Is a directory'; + case 32 /* WasiErrno.ELOOP */: return 'Symbolic link loop'; + case 33 /* WasiErrno.EMFILE */: return 'No file descriptors available'; + case 34 /* WasiErrno.EMLINK */: return 'Too many links'; + case 35 /* WasiErrno.EMSGSIZE */: return 'Message too large'; + case 36 /* WasiErrno.EMULTIHOP */: return 'Multihop attempted'; + case 37 /* WasiErrno.ENAMETOOLONG */: return 'Filename too long'; + case 38 /* WasiErrno.ENETDOWN */: return 'Network is down'; + case 39 /* WasiErrno.ENETRESET */: return 'Connection reset by network'; + case 40 /* WasiErrno.ENETUNREACH */: return 'Network unreachable'; + case 41 /* WasiErrno.ENFILE */: return 'Too many files open in system'; + case 42 /* WasiErrno.ENOBUFS */: return 'No buffer space available'; + case 43 /* WasiErrno.ENODEV */: return 'No such device'; + case 44 /* WasiErrno.ENOENT */: return 'No such file or directory'; + case 45 /* WasiErrno.ENOEXEC */: return 'Exec format error'; + case 46 /* WasiErrno.ENOLCK */: return 'No locks available'; + case 47 /* WasiErrno.ENOLINK */: return 'Link has been severed'; + case 48 /* WasiErrno.ENOMEM */: return 'Out of memory'; + case 49 /* WasiErrno.ENOMSG */: return 'No message of the desired type'; + case 50 /* WasiErrno.ENOPROTOOPT */: return 'Protocol not available'; + case 51 /* WasiErrno.ENOSPC */: return 'No space left on device'; + case 52 /* WasiErrno.ENOSYS */: return 'Function not implemented'; + case 53 /* WasiErrno.ENOTCONN */: return 'Socket not connected'; + case 54 /* WasiErrno.ENOTDIR */: return 'Not a directory'; + case 55 /* WasiErrno.ENOTEMPTY */: return 'Directory not empty'; + case 56 /* WasiErrno.ENOTRECOVERABLE */: return 'State not recoverable'; + case 57 /* WasiErrno.ENOTSOCK */: return 'Not a socket'; + case 58 /* WasiErrno.ENOTSUP */: return 'Not supported'; + case 59 /* WasiErrno.ENOTTY */: return 'Not a tty'; + case 60 /* WasiErrno.ENXIO */: return 'No such device or address'; + case 61 /* WasiErrno.EOVERFLOW */: return 'Value too large for data type'; + case 62 /* WasiErrno.EOWNERDEAD */: return 'Previous owner died'; + case 63 /* WasiErrno.EPERM */: return 'Operation not permitted'; + case 64 /* WasiErrno.EPIPE */: return 'Broken pipe'; + case 65 /* WasiErrno.EPROTO */: return 'Protocol error'; + case 66 /* WasiErrno.EPROTONOSUPPORT */: return 'Protocol not supported'; + case 67 /* WasiErrno.EPROTOTYPE */: return 'Protocol wrong type for socket'; + case 68 /* WasiErrno.ERANGE */: return 'Result not representable'; + case 69 /* WasiErrno.EROFS */: return 'Read-only file system'; + case 70 /* WasiErrno.ESPIPE */: return 'Invalid seek'; + case 71 /* WasiErrno.ESRCH */: return 'No such process'; + case 72 /* WasiErrno.ESTALE */: return 'Stale file handle'; + case 73 /* WasiErrno.ETIMEDOUT */: return 'Operation timed out'; + case 74 /* WasiErrno.ETXTBSY */: return 'Text file busy'; + case 75 /* WasiErrno.EXDEV */: return 'Cross-device link'; + case 76 /* WasiErrno.ENOTCAPABLE */: return 'Capabilities insufficient'; + default: return 'Unknown error'; + } +} +class WasiError extends Error { + constructor(message, errno) { + super(message); + this.errno = errno; + } + getErrorMessage() { + return strerror(this.errno); + } +} +Object.defineProperty(WasiError.prototype, 'name', { + configurable: true, + writable: true, + value: 'WasiError' +}); + +const RIGHTS_ALL = WasiRights.FD_DATASYNC | + WasiRights.FD_READ | + WasiRights.FD_SEEK | + WasiRights.FD_FDSTAT_SET_FLAGS | + WasiRights.FD_SYNC | + WasiRights.FD_TELL | + WasiRights.FD_WRITE | + WasiRights.FD_ADVISE | + WasiRights.FD_ALLOCATE | + WasiRights.PATH_CREATE_DIRECTORY | + WasiRights.PATH_CREATE_FILE | + WasiRights.PATH_LINK_SOURCE | + WasiRights.PATH_LINK_TARGET | + WasiRights.PATH_OPEN | + WasiRights.FD_READDIR | + WasiRights.PATH_READLINK | + WasiRights.PATH_RENAME_SOURCE | + WasiRights.PATH_RENAME_TARGET | + WasiRights.PATH_FILESTAT_GET | + WasiRights.PATH_FILESTAT_SET_SIZE | + WasiRights.PATH_FILESTAT_SET_TIMES | + WasiRights.FD_FILESTAT_GET | + WasiRights.FD_FILESTAT_SET_TIMES | + WasiRights.FD_FILESTAT_SET_SIZE | + WasiRights.PATH_SYMLINK | + WasiRights.PATH_UNLINK_FILE | + WasiRights.PATH_REMOVE_DIRECTORY | + WasiRights.POLL_FD_READWRITE | + WasiRights.SOCK_SHUTDOWN | + WasiRights.SOCK_ACCEPT; +const BLOCK_DEVICE_BASE = RIGHTS_ALL; +const BLOCK_DEVICE_INHERITING = RIGHTS_ALL; +const CHARACTER_DEVICE_BASE = RIGHTS_ALL; +const CHARACTER_DEVICE_INHERITING = RIGHTS_ALL; +const REGULAR_FILE_BASE = WasiRights.FD_DATASYNC | + WasiRights.FD_READ | + WasiRights.FD_SEEK | + WasiRights.FD_FDSTAT_SET_FLAGS | + WasiRights.FD_SYNC | + WasiRights.FD_TELL | + WasiRights.FD_WRITE | + WasiRights.FD_ADVISE | + WasiRights.FD_ALLOCATE | + WasiRights.FD_FILESTAT_GET | + WasiRights.FD_FILESTAT_SET_SIZE | + WasiRights.FD_FILESTAT_SET_TIMES | + WasiRights.POLL_FD_READWRITE; +const REGULAR_FILE_INHERITING = /*#__PURE__*/ BigInt(0); +const DIRECTORY_BASE = WasiRights.FD_FDSTAT_SET_FLAGS | + WasiRights.FD_SYNC | + WasiRights.FD_ADVISE | + WasiRights.PATH_CREATE_DIRECTORY | + WasiRights.PATH_CREATE_FILE | + WasiRights.PATH_LINK_SOURCE | + WasiRights.PATH_LINK_TARGET | + WasiRights.PATH_OPEN | + WasiRights.FD_READDIR | + WasiRights.PATH_READLINK | + WasiRights.PATH_RENAME_SOURCE | + WasiRights.PATH_RENAME_TARGET | + WasiRights.PATH_FILESTAT_GET | + WasiRights.PATH_FILESTAT_SET_SIZE | + WasiRights.PATH_FILESTAT_SET_TIMES | + WasiRights.FD_FILESTAT_GET | + WasiRights.FD_FILESTAT_SET_TIMES | + WasiRights.PATH_SYMLINK | + WasiRights.PATH_UNLINK_FILE | + WasiRights.PATH_REMOVE_DIRECTORY | + WasiRights.POLL_FD_READWRITE; +const DIRECTORY_INHERITING = DIRECTORY_BASE | REGULAR_FILE_BASE; +const SOCKET_BASE = (WasiRights.FD_READ | + WasiRights.FD_FDSTAT_SET_FLAGS | + WasiRights.FD_WRITE | + WasiRights.FD_FILESTAT_GET | + WasiRights.POLL_FD_READWRITE | + WasiRights.SOCK_SHUTDOWN); +const SOCKET_INHERITING = RIGHTS_ALL; +const TTY_BASE = WasiRights.FD_READ | + WasiRights.FD_FDSTAT_SET_FLAGS | + WasiRights.FD_WRITE | + WasiRights.FD_FILESTAT_GET | + WasiRights.POLL_FD_READWRITE; +const TTY_INHERITING = /*#__PURE__*/ BigInt(0); +function getRights(stdio, fd, flags, type) { + const ret = { + base: BigInt(0), + inheriting: BigInt(0) + }; + if (type === 0 /* WasiFileType.UNKNOWN */) { + throw new WasiError('Unknown file type', 28 /* WasiErrno.EINVAL */); + } + switch (type) { + case 4 /* WasiFileType.REGULAR_FILE */: + ret.base = REGULAR_FILE_BASE; + ret.inheriting = REGULAR_FILE_INHERITING; + break; + case 3 /* WasiFileType.DIRECTORY */: + ret.base = DIRECTORY_BASE; + ret.inheriting = DIRECTORY_INHERITING; + break; + case 6 /* WasiFileType.SOCKET_STREAM */: + case 5 /* WasiFileType.SOCKET_DGRAM */: + ret.base = SOCKET_BASE; + ret.inheriting = SOCKET_INHERITING; + break; + case 2 /* WasiFileType.CHARACTER_DEVICE */: + if (stdio.indexOf(fd) !== -1) { + ret.base = TTY_BASE; + ret.inheriting = TTY_INHERITING; + } + else { + ret.base = CHARACTER_DEVICE_BASE; + ret.inheriting = CHARACTER_DEVICE_INHERITING; + } + break; + case 1 /* WasiFileType.BLOCK_DEVICE */: + ret.base = BLOCK_DEVICE_BASE; + ret.inheriting = BLOCK_DEVICE_INHERITING; + break; + default: + ret.base = BigInt(0); + ret.inheriting = BigInt(0); + } + /* Disable read/write bits depending on access mode. */ + const read_or_write_only = flags & (0 | 1 | 2); + if (read_or_write_only === 0) { + ret.base &= ~WasiRights.FD_WRITE; + } + else if (read_or_write_only === 1) { + ret.base &= ~WasiRights.FD_READ; + } + return ret; +} + +function concatBuffer(buffers, size) { + let total = 0; + if (typeof size === 'number' && size >= 0) { + total = size; + } + else { + for (let i = 0; i < buffers.length; i++) { + const buffer = buffers[i]; + total += buffer.length; + } + } + let pos = 0; + const ret = new Uint8Array(total); + for (let i = 0; i < buffers.length; i++) { + const buffer = buffers[i]; + ret.set(buffer, pos); + pos += buffer.length; + } + return ret; +} +class FileDescriptor { + constructor(id, fd, path, realPath, type, rightsBase, rightsInheriting, preopen) { + this.id = id; + this.fd = fd; + this.path = path; + this.realPath = realPath; + this.type = type; + this.rightsBase = rightsBase; + this.rightsInheriting = rightsInheriting; + this.preopen = preopen; + this.pos = BigInt(0); + this.size = BigInt(0); + } + seek(offset, whence) { + if (whence === 0 /* WasiWhence.SET */) { + this.pos = BigInt(offset); + } + else if (whence === 1 /* WasiWhence.CUR */) { + this.pos += BigInt(offset); + } + else if (whence === 2 /* WasiWhence.END */) { + this.pos = BigInt(this.size) - BigInt(offset); + } + else { + throw new WasiError('Unknown whence', 29 /* WasiErrno.EIO */); + } + return this.pos; + } +} +class StandardOutput extends FileDescriptor { + constructor(log, id, fd, path, realPath, type, rightsBase, rightsInheriting, preopen) { + super(id, fd, path, realPath, type, rightsBase, rightsInheriting, preopen); + this._log = log; + this._buf = null; + } + write(buffer) { + const originalBuffer = buffer; + if (this._buf) { + buffer = concatBuffer([this._buf, buffer]); + this._buf = null; + } + if (buffer.indexOf(10) === -1) { + this._buf = buffer; + return originalBuffer.byteLength; + } + let written = 0; + let lastBegin = 0; + let index; + while ((index = buffer.indexOf(10, written)) !== -1) { + const str = new TextDecoder().decode(buffer.subarray(lastBegin, index)); + this._log(str); + written += index - lastBegin + 1; + lastBegin = index + 1; + } + if (written < buffer.length) { + this._buf = buffer.slice(written); + } + return originalBuffer.byteLength; + } +} +function toFileType(stat) { + if (stat.isBlockDevice()) + return 1 /* WasiFileType.BLOCK_DEVICE */; + if (stat.isCharacterDevice()) + return 2 /* WasiFileType.CHARACTER_DEVICE */; + if (stat.isDirectory()) + return 3 /* WasiFileType.DIRECTORY */; + if (stat.isSocket()) + return 6 /* WasiFileType.SOCKET_STREAM */; + if (stat.isFile()) + return 4 /* WasiFileType.REGULAR_FILE */; + if (stat.isSymbolicLink()) + return 7 /* WasiFileType.SYMBOLIC_LINK */; + return 0 /* WasiFileType.UNKNOWN */; +} +function toFileStat(view, buf, stat) { + view.setBigUint64(buf, stat.dev, true); + view.setBigUint64(buf + 8, stat.ino, true); + view.setBigUint64(buf + 16, BigInt(toFileType(stat)), true); + view.setBigUint64(buf + 24, stat.nlink, true); + view.setBigUint64(buf + 32, stat.size, true); + view.setBigUint64(buf + 40, stat.atimeMs * BigInt(1000000), true); + view.setBigUint64(buf + 48, stat.mtimeMs * BigInt(1000000), true); + view.setBigUint64(buf + 56, stat.ctimeMs * BigInt(1000000), true); +} +class FileDescriptorTable { + constructor(options) { + this.used = 0; + this.size = options.size; + this.fds = Array(options.size); + this.stdio = [options.in, options.out, options.err]; + this.print = options.print; + this.printErr = options.printErr; + this.insertStdio(options.in, 0, ''); + this.insertStdio(options.out, 1, ''); + this.insertStdio(options.err, 2, ''); + } + insertStdio(fd, expected, name) { + const type = 2 /* WasiFileType.CHARACTER_DEVICE */; + const { base, inheriting } = getRights(this.stdio, fd, 2 /* FileControlFlag.O_RDWR */, type); + const wrap = this.insert(fd, name, name, type, base, inheriting, 0); + if (wrap.id !== expected) { + throw new WasiError(`id: ${wrap.id} !== expected: ${expected}`, 8 /* WasiErrno.EBADF */); + } + return wrap; + } + insert(fd, mappedPath, realPath, type, rightsBase, rightsInheriting, preopen) { + var _a, _b; + let index = -1; + if (this.used >= this.size) { + const newSize = this.size * 2; + this.fds.length = newSize; + index = this.size; + this.size = newSize; + } + else { + for (let i = 0; i < this.size; ++i) { + if (this.fds[i] == null) { + index = i; + break; + } + } + } + let entry; + if (mappedPath === '') { + entry = new StandardOutput((_a = this.print) !== null && _a !== void 0 ? _a : console.log, index, fd, mappedPath, realPath, type, rightsBase, rightsInheriting, preopen); + } + else if (mappedPath === '') { + entry = new StandardOutput((_b = this.printErr) !== null && _b !== void 0 ? _b : console.error, index, fd, mappedPath, realPath, type, rightsBase, rightsInheriting, preopen); + } + else { + entry = new FileDescriptor(index, fd, mappedPath, realPath, type, rightsBase, rightsInheriting, preopen); + } + this.fds[index] = entry; + this.used++; + return entry; + } + get(id, base, inheriting) { + if (id >= this.size) { + throw new WasiError('Invalid fd', 8 /* WasiErrno.EBADF */); + } + const entry = this.fds[id]; + if (!entry || entry.id !== id) { + throw new WasiError('Bad file descriptor', 8 /* WasiErrno.EBADF */); + } + /* Validate that the fd has the necessary rights. */ + if ((~entry.rightsBase & base) !== BigInt(0) || (~entry.rightsInheriting & inheriting) !== BigInt(0)) { + throw new WasiError('Capabilities insufficient', 76 /* WasiErrno.ENOTCAPABLE */); + } + return entry; + } + remove(id) { + if (id >= this.size) { + throw new WasiError('Invalid fd', 8 /* WasiErrno.EBADF */); + } + const entry = this.fds[id]; + if (!entry || entry.id !== id) { + throw new WasiError('Bad file descriptor', 8 /* WasiErrno.EBADF */); + } + this.fds[id] = undefined; + this.used--; + } +} +class SyncTable extends FileDescriptorTable { + constructor(options) { + super(options); + this.fs = options.fs; + } + getFileTypeByFd(fd) { + const stats = this.fs.fstatSync(fd, { bigint: true }); + return toFileType(stats); + } + insertPreopen(fd, mappedPath, realPath) { + const type = this.getFileTypeByFd(fd); + if (type !== 3 /* WasiFileType.DIRECTORY */) { + throw new WasiError(`Preopen not dir: ["${mappedPath}", "${realPath}"]`, 54 /* WasiErrno.ENOTDIR */); + } + const result = getRights(this.stdio, fd, 0, type); + return this.insert(fd, mappedPath, realPath, type, result.base, result.inheriting, 1); + } + renumber(dst, src) { + if (dst === src) + return; + if (dst >= this.size || src >= this.size) { + throw new WasiError('Invalid fd', 8 /* WasiErrno.EBADF */); + } + const dstEntry = this.fds[dst]; + const srcEntry = this.fds[src]; + if (!dstEntry || !srcEntry || dstEntry.id !== dst || srcEntry.id !== src) { + throw new WasiError('Invalid fd', 8 /* WasiErrno.EBADF */); + } + this.fs.closeSync(dstEntry.fd); + this.fds[dst] = this.fds[src]; + this.fds[dst].id = dst; + this.fds[src] = undefined; + this.used--; + } +} +class AsyncTable extends FileDescriptorTable { + // eslint-disable-next-line @typescript-eslint/no-useless-constructor + constructor(options) { + super(options); + } + async getFileTypeByFd(fd) { + const stats = await fd.stat({ bigint: true }); + return toFileType(stats); + } + async insertPreopen(fd, mappedPath, realPath) { + const type = await this.getFileTypeByFd(fd); + if (type !== 3 /* WasiFileType.DIRECTORY */) { + throw new WasiError(`Preopen not dir: ["${mappedPath}", "${realPath}"]`, 54 /* WasiErrno.ENOTDIR */); + } + const result = getRights(this.stdio, fd.fd, 0, type); + return this.insert(fd, mappedPath, realPath, type, result.base, result.inheriting, 1); + } + async renumber(dst, src) { + if (dst === src) + return; + if (dst >= this.size || src >= this.size) { + throw new WasiError('Invalid fd', 8 /* WasiErrno.EBADF */); + } + const dstEntry = this.fds[dst]; + const srcEntry = this.fds[src]; + if (!dstEntry || !srcEntry || dstEntry.id !== dst || srcEntry.id !== src) { + throw new WasiError('Invalid fd', 8 /* WasiErrno.EBADF */); + } + await dstEntry.fd.close(); + this.fds[dst] = this.fds[src]; + this.fds[dst].id = dst; + this.fds[src] = undefined; + this.used--; + } +} + +/** @public */ +const WebAssemblyMemory = /*#__PURE__*/ (function () { return _WebAssembly.Memory; })(); +/** @public */ +class Memory extends WebAssemblyMemory { + // eslint-disable-next-line @typescript-eslint/no-useless-constructor + constructor(descriptor) { + super(descriptor); + } + get HEAP8() { return new Int8Array(super.buffer); } + get HEAPU8() { return new Uint8Array(super.buffer); } + get HEAP16() { return new Int16Array(super.buffer); } + get HEAPU16() { return new Uint16Array(super.buffer); } + get HEAP32() { return new Int32Array(super.buffer); } + get HEAPU32() { return new Uint32Array(super.buffer); } + get HEAP64() { return new BigInt64Array(super.buffer); } + get HEAPU64() { return new BigUint64Array(super.buffer); } + get HEAPF32() { return new Float32Array(super.buffer); } + get HEAPF64() { return new Float64Array(super.buffer); } + get view() { return new DataView(super.buffer); } +} +/** @public */ +function extendMemory(memory) { + if (Object.getPrototypeOf(memory) === _WebAssembly.Memory.prototype) { + Object.setPrototypeOf(memory, Memory.prototype); + } + return memory; +} + +function checkWebAssemblyFunction() { + const WebAssemblyFunction = _WebAssembly.Function; + if (typeof WebAssemblyFunction !== 'function') { + throw new Error('WebAssembly.Function is not supported in this environment.' + + ' If you are using V8 based browser like Chrome, try to specify' + + ' --js-flags="--wasm-staging --experimental-wasm-stack-switching"'); + } + return WebAssemblyFunction; +} +/** @public */ +function wrapAsyncImport(f, parameterType, returnType) { + const WebAssemblyFunction = checkWebAssemblyFunction(); + if (typeof f !== 'function') { + throw new TypeError('Function required'); + } + const parameters = parameterType.slice(0); + parameters.unshift('externref'); + return new WebAssemblyFunction({ parameters, results: returnType }, f, { suspending: 'first' }); +} +/** @public */ +function wrapAsyncExport(f) { + const WebAssemblyFunction = checkWebAssemblyFunction(); + if (typeof f !== 'function') { + throw new TypeError('Function required'); + } + return new WebAssemblyFunction({ parameters: [...WebAssemblyFunction.type(f).parameters.slice(1)], results: ['externref'] }, f, { promising: 'first' }); +} +/** @public */ +function wrapExports(exports, needWrap) { + return wrapInstanceExports(exports, (exportValue, name) => { + let ignore = typeof exportValue !== 'function'; + if (Array.isArray(needWrap)) { + ignore = ignore || (needWrap.indexOf(name) === -1); + } + return ignore ? exportValue : wrapAsyncExport(exportValue); + }); +} + +// Linux fcntl flag bits ↔ Windows libuv flag bits. `pathOpen()` builds +// `flagsRes` using Linux constants (O_CREAT=0x40, O_EXCL=0x80, +// O_APPEND=0x400). Windows libuv expects different bits (O_CREAT=0x100, +// O_EXCL=0x400, O_APPEND=0x8). Without translation, +// `fs.openSync(path, 0x241 /* L:WRONLY|CREAT|TRUNC */)` is rejected +// with EINVAL because Linux's 0x40 happens to mean O_TEMPORARY on +// Windows — and O_TEMPORARY without O_CREAT is invalid. +const _isWin32Flags = typeof process !== 'undefined' && process.platform === 'win32'; +function _toWinOpenFlags(f) { + let r = f & 3; // RDONLY/WRONLY/RDWR — same on both + if ((f & 0x40) !== 0) + r |= 0x100; // O_CREAT: Linux 0x40 -> Windows 0x100 + if ((f & 0x80) !== 0) + r |= 0x400; // O_EXCL: Linux 0x80 -> Windows 0x400 + if ((f & 0x200) !== 0) + r |= 0x200; // O_TRUNC: same value on both + if ((f & 0x400) !== 0) + r |= 0x8; // O_APPEND: Linux 0x400 -> Windows 0x8 + return r; +} +function copyMemory(targets, src) { + if (targets.length === 0 || src.length === 0) + return 0; + let copied = 0; + let left = src.length - copied; + for (let i = 0; i < targets.length; ++i) { + const target = targets[i]; + if (left < target.length) { + target.set(src.subarray(copied, copied + left), 0); + copied += left; + left = 0; + return copied; + } + target.set(src.subarray(copied, copied + target.length), 0); + copied += target.length; + left -= target.length; + } + return copied; +} +const _memory = new WeakMap(); +const _wasi = new WeakMap(); +const _fs = new WeakMap(); +function ensureMemoryFor(memory, end) { + let buffer = memory.buffer; + if (end > buffer.byteLength) { + memory.grow(0); + buffer = memory.buffer; + } + return buffer; +} +function getMemory(wasi, end = 0) { + const memory = _memory.get(wasi); + ensureMemoryFor(memory, end); + return memory; +} +function getFs(wasi) { + const fs = _fs.get(wasi); + if (!fs) + throw new Error('filesystem is unavailable'); + return fs; +} +function handleError(err) { + if (err instanceof WasiError) { + { + console.warn(err); + } + return err.errno; + } + switch (err.code) { + case 'ENOENT': return 44 /* WasiErrno.ENOENT */; + case 'EBADF': return 8 /* WasiErrno.EBADF */; + case 'EINVAL': return 28 /* WasiErrno.EINVAL */; + case 'EPERM': return 63 /* WasiErrno.EPERM */; + case 'EPROTO': return 65 /* WasiErrno.EPROTO */; + case 'EEXIST': return 20 /* WasiErrno.EEXIST */; + case 'ENOTDIR': return 54 /* WasiErrno.ENOTDIR */; + case 'EMFILE': return 33 /* WasiErrno.EMFILE */; + case 'EACCES': return 2 /* WasiErrno.EACCES */; + case 'EISDIR': return 31 /* WasiErrno.EISDIR */; + case 'ENOTEMPTY': return 55 /* WasiErrno.ENOTEMPTY */; + case 'ENOSYS': return 52 /* WasiErrno.ENOSYS */; + } + throw err; +} +function defineName(name, f) { + Object.defineProperty(f, 'name', { value: name }); + return f; +} +function tryCall(f, wasi, args) { + let r; + try { + r = f.apply(wasi, args); + } + catch (err) { + return handleError(err); + } + if (isPromiseLike(r)) { + return r.then(_ => _, handleError); + } + return r; +} +function syscallWrap(self, name, f) { + let debug = false; + const NODE_DEBUG_NATIVE = (() => { + try { + return "wasi"; + } + catch (_) { + return undefined; + } + })(); + if (typeof NODE_DEBUG_NATIVE === 'string' && NODE_DEBUG_NATIVE.split(',').includes('wasi')) { + debug = true; + } + return debug + ? defineName(name, function () { + const args = Array.prototype.slice.call(arguments); + let debugArgs = [`${name}(${Array.from({ length: arguments.length }).map(() => '%d').join(', ')})`]; + debugArgs = debugArgs.concat(args); + console.debug.apply(console, debugArgs); + return tryCall(f, self, args); + }) + : defineName(name, function () { + return tryCall(f, self, arguments); + }); +} +function resolvePathSync(fs, fileDescriptor, path, flags) { + let resolvedPath = resolve(fileDescriptor.realPath, path); + if ((flags & 1) === 1) { + try { + resolvedPath = fs.readlinkSync(resolvedPath); + } + catch (err) { + if (err.code !== 'EINVAL' && err.code !== 'ENOENT') { + throw err; + } + } + } + return resolvedPath; +} +async function resolvePathAsync(fs, fileDescriptor, path, flags) { + let resolvedPath = resolve(fileDescriptor.realPath, path); + if ((flags & 1) === 1) { + try { + resolvedPath = await fs.promises.readlink(resolvedPath); + } + catch (err) { + if (err.code !== 'EINVAL' && err.code !== 'ENOENT') { + throw err; + } + } + } + return resolvedPath; +} +// eslint-disable-next-line spaced-comment +const encoder = /*#__PURE__*/ new TextEncoder(); +// eslint-disable-next-line spaced-comment +const decoder = /*#__PURE__*/ new TextDecoder(); +const INT64_MAX = (BigInt(1) << BigInt(63)) - BigInt(1); +function readStdin() { + const value = window.prompt(); + if (value === null) + return new Uint8Array(); + const buffer = new TextEncoder().encode(value + '\n'); + return buffer; +} +function validateFstFlagsOrReturn(flags) { + return (Boolean((flags) & ~(1 /* WasiFstFlag.SET_ATIM */ | 2 /* WasiFstFlag.SET_ATIM_NOW */ | + 4 /* WasiFstFlag.SET_MTIM */ | 8 /* WasiFstFlag.SET_MTIM_NOW */)) || + ((flags) & (1 /* WasiFstFlag.SET_ATIM */ | 2 /* WasiFstFlag.SET_ATIM_NOW */)) === + (1 /* WasiFstFlag.SET_ATIM */ | 2 /* WasiFstFlag.SET_ATIM_NOW */) || + ((flags) & (4 /* WasiFstFlag.SET_MTIM */ | 8 /* WasiFstFlag.SET_MTIM_NOW */)) === + (4 /* WasiFstFlag.SET_MTIM */ | 8 /* WasiFstFlag.SET_MTIM_NOW */)); +} +class WASI$1 { + constructor(args, env, fds, asyncFs, fs, asyncify) { + this.args_get = syscallWrap(this, 'args_get', function (argv, argv_buf) { + argv = Number(argv); + argv_buf = Number(argv_buf); + if (argv === 0 || argv_buf === 0) { + return 28 /* WasiErrno.EINVAL */; + } + const wasi = _wasi.get(this); + const args = wasi.args; + const argsSize = encoder.encode(args.join('\0') + '\0').length; + const { HEAPU8, view } = getMemory(this, Math.max(argv + args.length * 4, argv_buf + argsSize)); + for (let i = 0; i < args.length; ++i) { + const arg = args[i]; + view.setInt32(argv, argv_buf, true); + argv += 4; + const data = encoder.encode(arg + '\0'); + HEAPU8.set(data, argv_buf); + argv_buf += data.length; + } + return 0 /* WasiErrno.ESUCCESS */; + }); + this.args_sizes_get = syscallWrap(this, 'args_sizes_get', function (argc, argv_buf_size) { + argc = Number(argc); + argv_buf_size = Number(argv_buf_size); + if (argc === 0 || argv_buf_size === 0) { + return 28 /* WasiErrno.EINVAL */; + } + const { view } = getMemory(this, Math.max(argc + 4, argv_buf_size + 4)); + const wasi = _wasi.get(this); + const args = wasi.args; + view.setUint32(argc, args.length, true); + view.setUint32(argv_buf_size, encoder.encode(args.join('\0') + '\0').length, true); + return 0 /* WasiErrno.ESUCCESS */; + }); + this.environ_get = syscallWrap(this, 'environ_get', function (environ, environ_buf) { + environ = Number(environ); + environ_buf = Number(environ_buf); + if (environ === 0 || environ_buf === 0) { + return 28 /* WasiErrno.EINVAL */; + } + const wasi = _wasi.get(this); + const env = wasi.env; + const envSize = encoder.encode(env.join('\0') + '\0').length; + const { HEAPU8, view } = getMemory(this, Math.max(environ + env.length * 4, environ_buf + envSize)); + for (let i = 0; i < env.length; ++i) { + const pair = env[i]; + view.setInt32(environ, environ_buf, true); + environ += 4; + const data = encoder.encode(pair + '\0'); + HEAPU8.set(data, environ_buf); + environ_buf += data.length; + } + return 0 /* WasiErrno.ESUCCESS */; + }); + this.environ_sizes_get = syscallWrap(this, 'environ_sizes_get', function (len, buflen) { + len = Number(len); + buflen = Number(buflen); + if (len === 0 || buflen === 0) { + return 28 /* WasiErrno.EINVAL */; + } + const { view } = getMemory(this, Math.max(len + 4, buflen + 4)); + const wasi = _wasi.get(this); + view.setUint32(len, wasi.env.length, true); + view.setUint32(buflen, encoder.encode(wasi.env.join('\0') + '\0').length, true); + return 0 /* WasiErrno.ESUCCESS */; + }); + this.clock_res_get = syscallWrap(this, 'clock_res_get', function (id, resolution) { + resolution = Number(resolution); + if (resolution === 0) { + return 28 /* WasiErrno.EINVAL */; + } + const { view } = getMemory(this, resolution + 8); + switch (id) { + case 0 /* WasiClockid.REALTIME */: + view.setBigUint64(resolution, BigInt(1000000), true); + return 0 /* WasiErrno.ESUCCESS */; + case 1 /* WasiClockid.MONOTONIC */: + case 2 /* WasiClockid.PROCESS_CPUTIME_ID */: + case 3 /* WasiClockid.THREAD_CPUTIME_ID */: + view.setBigUint64(resolution, BigInt(1000), true); + return 0 /* WasiErrno.ESUCCESS */; + default: return 28 /* WasiErrno.EINVAL */; + } + }); + this.clock_time_get = syscallWrap(this, 'clock_time_get', function (id, _percision, time) { + time = Number(time); + if (time === 0) { + return 28 /* WasiErrno.EINVAL */; + } + const { view } = getMemory(this, time + 8); + switch (id) { + case 0 /* WasiClockid.REALTIME */: + view.setBigUint64(time, BigInt(Date.now()) * BigInt(1000000), true); + return 0 /* WasiErrno.ESUCCESS */; + case 1 /* WasiClockid.MONOTONIC */: + case 2 /* WasiClockid.PROCESS_CPUTIME_ID */: + case 3 /* WasiClockid.THREAD_CPUTIME_ID */: { + const t = performance.now() / 1000; + const s = Math.trunc(t); + const ms = Math.floor((t - s) * 1000); + const result = BigInt(s) * BigInt(1000000000) + BigInt(ms) * BigInt(1000000); + view.setBigUint64(time, result, true); + return 0 /* WasiErrno.ESUCCESS */; + } + default: return 28 /* WasiErrno.EINVAL */; + } + }); + this.fd_advise = syscallWrap(this, 'fd_advise', function (_fd, _offset, _len, _advice) { + return 52 /* WasiErrno.ENOSYS */; + }); + this.fd_fdstat_get = syscallWrap(this, 'fd_fdstat_get', function (fd, fdstat) { + fdstat = Number(fdstat); + if (fdstat === 0) { + return 28 /* WasiErrno.EINVAL */; + } + const wasi = _wasi.get(this); + const fileDescriptor = wasi.fds.get(fd, BigInt(0), BigInt(0)); + const { view } = getMemory(this, fdstat + 24); + view.setUint16(fdstat, fileDescriptor.type, true); + view.setUint16(fdstat + 2, 0, true); + view.setBigUint64(fdstat + 8, fileDescriptor.rightsBase, true); + view.setBigUint64(fdstat + 16, fileDescriptor.rightsInheriting, true); + return 0 /* WasiErrno.ESUCCESS */; + }); + this.fd_fdstat_set_flags = syscallWrap(this, 'fd_fdstat_set_flags', function (_fd, _flags) { + return 52 /* WasiErrno.ENOSYS */; + }); + this.fd_fdstat_set_rights = syscallWrap(this, 'fd_fdstat_set_rights', function (fd, rightsBase, rightsInheriting) { + const wasi = _wasi.get(this); + const fileDescriptor = wasi.fds.get(fd, BigInt(0), BigInt(0)); + if ((rightsBase | fileDescriptor.rightsBase) > fileDescriptor.rightsBase) { + return 76 /* WasiErrno.ENOTCAPABLE */; + } + if ((rightsInheriting | fileDescriptor.rightsInheriting) > + fileDescriptor.rightsInheriting) { + return 76 /* WasiErrno.ENOTCAPABLE */; + } + fileDescriptor.rightsBase = rightsBase; + fileDescriptor.rightsInheriting = rightsInheriting; + return 0 /* WasiErrno.ESUCCESS */; + }); + this.fd_prestat_get = syscallWrap(this, 'fd_prestat_get', function (fd, prestat) { + prestat = Number(prestat); + if (prestat === 0) { + return 28 /* WasiErrno.EINVAL */; + } + const wasi = _wasi.get(this); + let fileDescriptor; + try { + fileDescriptor = wasi.fds.get(fd, BigInt(0), BigInt(0)); + } + catch (err) { + if (err instanceof WasiError) + return err.errno; + throw err; + } + if (fileDescriptor.preopen !== 1) + return 28 /* WasiErrno.EINVAL */; + const { view } = getMemory(this, prestat + 8); + // preopen type is dir(0) + view.setUint32(prestat, 0, true); + view.setUint32(prestat + 4, encoder.encode(fileDescriptor.path).length, true); + return 0 /* WasiErrno.ESUCCESS */; + }); + this.fd_prestat_dir_name = syscallWrap(this, 'fd_prestat_dir_name', function (fd, path, path_len) { + path = Number(path); + path_len = Number(path_len); + if (path === 0) { + return 28 /* WasiErrno.EINVAL */; + } + const wasi = _wasi.get(this); + const fileDescriptor = wasi.fds.get(fd, BigInt(0), BigInt(0)); + if (fileDescriptor.preopen !== 1) + return 8 /* WasiErrno.EBADF */; + const buffer = encoder.encode(fileDescriptor.path); + const size = buffer.length; + if (size > path_len) + return 42 /* WasiErrno.ENOBUFS */; + const { HEAPU8 } = getMemory(this, path + size); + HEAPU8.set(buffer, path); + return 0 /* WasiErrno.ESUCCESS */; + }); + this.fd_seek = syscallWrap(this, 'fd_seek', function (fd, offset, whence, newOffset) { + newOffset = Number(newOffset); + if (newOffset === 0) { + return 28 /* WasiErrno.EINVAL */; + } + if (fd === 0 || fd === 1 || fd === 2) + return 0 /* WasiErrno.ESUCCESS */; + const wasi = _wasi.get(this); + const fileDescriptor = wasi.fds.get(fd, WasiRights.FD_SEEK, BigInt(0)); + const r = fileDescriptor.seek(offset, whence); + const { view } = getMemory(this, newOffset + 8); + view.setBigUint64(newOffset, r, true); + return 0 /* WasiErrno.ESUCCESS */; + }); + this.fd_tell = syscallWrap(this, 'fd_tell', function (fd, offset) { + const wasi = _wasi.get(this); + const fileDescriptor = wasi.fds.get(fd, WasiRights.FD_TELL, BigInt(0)); + const pos = BigInt(fileDescriptor.pos); + const { view } = getMemory(this, Number(offset) + 8); + view.setBigUint64(Number(offset), pos, true); + return 0 /* WasiErrno.ESUCCESS */; + }); + this.poll_oneoff = syscallWrap(this, 'poll_oneoff', function (in_ptr, out_ptr, nsubscriptions, nevents) { + in_ptr = Number(in_ptr); + out_ptr = Number(out_ptr); + nevents = Number(nevents); + nsubscriptions = Number(nsubscriptions); + nsubscriptions = nsubscriptions >>> 0; + if (in_ptr === 0 || out_ptr === 0 || nsubscriptions === 0 || nevents === 0) { + return 28 /* WasiErrno.EINVAL */; + } + const { view } = getMemory(this, Math.max(in_ptr + nsubscriptions * 48, out_ptr + nsubscriptions * 32, nevents + 4)); + view.setUint32(nevents, 0, true); + let i = 0; + let timer_userdata = BigInt(0); + let cur_timeout = BigInt(0); + let has_timeout = 0; + let min_timeout = BigInt(0); + let sub; + const subscriptions = Array(nsubscriptions); + for (i = 0; i < nsubscriptions; i++) { + sub = in_ptr + i * 48; + const userdata = view.getBigUint64(sub, true); + const type = view.getUint8(sub + 8); + const clockIdOrFd = view.getUint32(sub + 16, true); + const timeout = view.getBigUint64(sub + 24, true); + const precision = view.getBigUint64(sub + 32, true); + const flags = view.getUint16(sub + 40, true); + subscriptions[i] = { + userdata, + type, + u: { + clock: { + clock_id: clockIdOrFd, + timeout, + precision, + flags + }, + fd_readwrite: { + fd: clockIdOrFd + } + } + }; + } + const fdevents = []; + for (i = 0; i < nsubscriptions; i++) { + sub = subscriptions[i]; + switch (sub.type) { + case 0 /* WasiEventType.CLOCK */: { + if (sub.u.clock.flags === 1 /* WasiSubclockflags.ABSTIME */) { + /* Convert absolute time to relative delay. */ + const now = BigInt(Date.now()) * BigInt(1000000); + cur_timeout = sub.u.clock.timeout - now; + } + else { + cur_timeout = sub.u.clock.timeout; + } + if (has_timeout === 0 || cur_timeout < min_timeout) { + min_timeout = cur_timeout; + timer_userdata = sub.userdata; + has_timeout = 1; + } + break; + } + case 1 /* WasiEventType.FD_READ */: + case 2 /* WasiEventType.FD_WRITE */: + fdevents.push(sub); + break; + default: return 28 /* WasiErrno.EINVAL */; + } + } + if (fdevents.length > 0) { + for (i = 0; i < fdevents.length; i++) { + const fdevent = fdevents[i]; + const event = out_ptr + 32 * i; + view.setBigUint64(event, fdevent.userdata, true); + view.setUint32(event + 8, 52 /* WasiErrno.ENOSYS */, true); + view.setUint32(event + 12, fdevent.type, true); + view.setBigUint64(event + 16, BigInt(0), true); + view.setUint16(event + 24, 0, true); + view.setUint32(nevents, 1, true); + } + view.setUint32(nevents, fdevents.length, true); + return 0 /* WasiErrno.ESUCCESS */; + } + if (has_timeout) { + const delay = Number(min_timeout / BigInt(1000000)); + // if (isMainThread || typeof SharedArrayBuffer !== 'function') { + sleepBreakIf(delay, () => false); + // } else { + // const buf = new SharedArrayBuffer(4) + // const arr = new Int32Array(buf) + // postMsg({ + // __tybys_wasm_util_wasi__: { + // type: 'set-timeout', + // payload: { + // buffer: buf, + // delay + // } + // } + // }) + // Atomics.wait(arr, 0, 0) + // } + const event = out_ptr; + view.setBigUint64(event, timer_userdata, true); + view.setUint32(event + 8, 0 /* WasiErrno.ESUCCESS */, true); + view.setUint32(event + 12, 0 /* WasiEventType.CLOCK */, true); + view.setUint32(nevents, 1, true); + } + return 0 /* WasiErrno.ESUCCESS */; + }); + this.proc_exit = syscallWrap(this, 'proc_exit', function (rval) { + if ((typeof process === 'object') && (process !== null) && (typeof process.exit === 'function')) { + process.exit(rval); + } + return 0 /* WasiErrno.ESUCCESS */; + }); + this.proc_raise = syscallWrap(this, 'proc_raise', function (_sig) { + return 52 /* WasiErrno.ENOSYS */; + }); + this.sched_yield = syscallWrap(this, 'sched_yield', function () { + return 0 /* WasiErrno.ESUCCESS */; + }); + this.random_get = typeof crypto !== 'undefined' && typeof crypto.getRandomValues === 'function' + ? syscallWrap(this, 'random_get', function (buf, buf_len) { + buf = Number(buf); + if (buf === 0) { + return 28 /* WasiErrno.EINVAL */; + } + buf_len = Number(buf_len); + const { HEAPU8, view } = getMemory(this, buf + buf_len); + if ((typeof SharedArrayBuffer === 'function' && HEAPU8.buffer instanceof SharedArrayBuffer) || + (Object.prototype.toString.call(HEAPU8.buffer) === '[object SharedArrayBuffer]')) { + for (let i = buf; i < buf + buf_len; ++i) { + view.setUint8(i, Math.floor(Math.random() * 256)); + } + return 0 /* WasiErrno.ESUCCESS */; + } + let pos; + const stride = 65536; + for (pos = 0; pos + stride < buf_len; pos += stride) { + crypto.getRandomValues(HEAPU8.subarray(buf + pos, buf + pos + stride)); + } + crypto.getRandomValues(HEAPU8.subarray(buf + pos, buf + buf_len)); + return 0 /* WasiErrno.ESUCCESS */; + }) + : syscallWrap(this, 'random_get', function (buf, buf_len) { + buf = Number(buf); + if (buf === 0) { + return 28 /* WasiErrno.EINVAL */; + } + buf_len = Number(buf_len); + const { view } = getMemory(this, buf + buf_len); + for (let i = buf; i < buf + buf_len; ++i) { + view.setUint8(i, Math.floor(Math.random() * 256)); + } + return 0 /* WasiErrno.ESUCCESS */; + }); + this.sock_recv = syscallWrap(this, 'sock_recv', function () { + return 58 /* WasiErrno.ENOTSUP */; + }); + this.sock_send = syscallWrap(this, 'sock_send', function () { + return 58 /* WasiErrno.ENOTSUP */; + }); + this.sock_shutdown = syscallWrap(this, 'sock_shutdown', function () { + return 58 /* WasiErrno.ENOTSUP */; + }); + this.sock_accept = syscallWrap(this, 'sock_accept', function () { + return 58 /* WasiErrno.ENOTSUP */; + }); + _wasi.set(this, { + fds, + args, + env + }); + if (fs) + _fs.set(this, fs); + // eslint-disable-next-line @typescript-eslint/no-this-alias + const _this = this; + function defineImport(name, syncVersion, asyncVersion, parameterType, returnType) { + if (asyncFs) { + if (asyncify) { + _this[name] = asyncify.wrapImportFunction(syscallWrap(_this, name, asyncVersion)); + } + else { + _this[name] = wrapAsyncImport(syscallWrap(_this, name, asyncVersion), parameterType, returnType); + } + } + else { + _this[name] = syscallWrap(_this, name, syncVersion); + } + } + defineImport('fd_allocate', function fd_allocate(fd, offset, len) { + const wasi = _wasi.get(this); + const fs = getFs(this); + const fileDescriptor = wasi.fds.get(fd, WasiRights.FD_ALLOCATE, BigInt(0)); + const stat = fs.fstatSync(fileDescriptor.fd, { bigint: true }); + if (stat.size < offset + len) { + fs.ftruncateSync(fileDescriptor.fd, Number(offset + len)); + } + return 0 /* WasiErrno.ESUCCESS */; + }, async function fd_allocate(fd, offset, len) { + const wasi = _wasi.get(this); + const fileDescriptor = wasi.fds.get(fd, WasiRights.FD_ALLOCATE, BigInt(0)); + const h = fileDescriptor.fd; + const stat = await h.stat({ bigint: true }); + if (stat.size < offset + len) { + await h.truncate(Number(offset + len)); + } + return 0 /* WasiErrno.ESUCCESS */; + }, ['i32', 'i64', 'f64'], ['i32']); + defineImport('fd_close', function fd_close(fd) { + const wasi = _wasi.get(this); + const fileDescriptor = wasi.fds.get(fd, BigInt(0), BigInt(0)); + const fs = getFs(this); + fs.closeSync(fileDescriptor.fd); + wasi.fds.remove(fd); + return 0 /* WasiErrno.ESUCCESS */; + }, async function fd_close(fd) { + const wasi = _wasi.get(this); + const fileDescriptor = wasi.fds.get(fd, BigInt(0), BigInt(0)); + await fileDescriptor.fd.close(); + wasi.fds.remove(fd); + return 0 /* WasiErrno.ESUCCESS */; + }, ['i32'], ['i32']); + defineImport('fd_datasync', function fd_datasync(fd) { + const wasi = _wasi.get(this); + const fileDescriptor = wasi.fds.get(fd, WasiRights.FD_DATASYNC, BigInt(0)); + const fs = getFs(this); + fs.fdatasyncSync(fileDescriptor.fd); + return 0 /* WasiErrno.ESUCCESS */; + }, async function fd_datasync(fd) { + const wasi = _wasi.get(this); + const fileDescriptor = wasi.fds.get(fd, WasiRights.FD_DATASYNC, BigInt(0)); + await fileDescriptor.fd.datasync(); + return 0 /* WasiErrno.ESUCCESS */; + }, ['i32'], ['i32']); + defineImport('fd_filestat_get', function fd_filestat_get(fd, buf) { + buf = Number(buf); + if (buf === 0) + return 28 /* WasiErrno.EINVAL */; + const wasi = _wasi.get(this); + const fileDescriptor = wasi.fds.get(fd, WasiRights.FD_FILESTAT_GET, BigInt(0)); + const fs = getFs(this); + const stat = fs.fstatSync(fileDescriptor.fd, { bigint: true }); + const { view } = getMemory(this, buf + 64); + toFileStat(view, buf, stat); + return 0 /* WasiErrno.ESUCCESS */; + }, async function fd_filestat_get(fd, buf) { + buf = Number(buf); + if (buf === 0) + return 28 /* WasiErrno.EINVAL */; + const wasi = _wasi.get(this); + const fileDescriptor = wasi.fds.get(fd, WasiRights.FD_FILESTAT_GET, BigInt(0)); + const h = fileDescriptor.fd; + const stat = await h.stat({ bigint: true }); + const { view } = getMemory(this, buf + 64); + toFileStat(view, buf, stat); + return 0 /* WasiErrno.ESUCCESS */; + }, ['i32', 'i32'], ['i32']); + defineImport('fd_filestat_set_size', function fd_filestat_set_size(fd, size) { + const wasi = _wasi.get(this); + const fileDescriptor = wasi.fds.get(fd, WasiRights.FD_FILESTAT_SET_SIZE, BigInt(0)); + const fs = getFs(this); + fs.ftruncateSync(fileDescriptor.fd, Number(size)); + return 0 /* WasiErrno.ESUCCESS */; + }, async function fd_filestat_set_size(fd, size) { + const wasi = _wasi.get(this); + const fileDescriptor = wasi.fds.get(fd, WasiRights.FD_FILESTAT_SET_SIZE, BigInt(0)); + const h = fileDescriptor.fd; + await h.truncate(Number(size)); + return 0 /* WasiErrno.ESUCCESS */; + }, ['i32', 'i64'], ['i32']); + function fdFilestatGetTimes(fd, atim, mtim, flags) { + const wasi = _wasi.get(this); + const fileDescriptor = wasi.fds.get(fd, WasiRights.FD_FILESTAT_SET_TIMES, BigInt(0)); + if ((flags & 2 /* WasiFstFlag.SET_ATIM_NOW */) === 2 /* WasiFstFlag.SET_ATIM_NOW */) { + atim = BigInt(Date.now() * 1000000); + } + if ((flags & 8 /* WasiFstFlag.SET_MTIM_NOW */) === 8 /* WasiFstFlag.SET_MTIM_NOW */) { + mtim = BigInt(Date.now() * 1000000); + } + return { fileDescriptor, atim, mtim }; + } + defineImport('fd_filestat_set_times', function fd_filestat_set_times(fd, atim, mtim, flags) { + if (validateFstFlagsOrReturn(flags)) { + return 28 /* WasiErrno.EINVAL */; + } + const { fileDescriptor, atim: atimRes, mtim: mtimRes } = fdFilestatGetTimes.call(this, fd, atim, mtim, flags); + const fs = getFs(this); + fs.futimesSync(fileDescriptor.fd, Number(atimRes), Number(mtimRes)); + return 0 /* WasiErrno.ESUCCESS */; + }, async function fd_filestat_set_times(fd, atim, mtim, flags) { + if (validateFstFlagsOrReturn(flags)) { + return 28 /* WasiErrno.EINVAL */; + } + const { fileDescriptor, atim: atimRes, mtim: mtimRes } = fdFilestatGetTimes.call(this, fd, atim, mtim, flags); + const h = fileDescriptor.fd; + await h.utimes(Number(atimRes), Number(mtimRes)); + return 0 /* WasiErrno.ESUCCESS */; + }, ['i32', 'i64', 'i64', 'i32'], ['i32']); + defineImport('fd_pread', function fd_pread(fd, iovs, iovslen, offset, size) { + iovs = Number(iovs); + size = Number(size); + if ((iovs === 0 && iovslen) || size === 0 || offset > INT64_MAX) { + return 28 /* WasiErrno.EINVAL */; + } + const { HEAPU8, view } = getMemory(this, Math.max(iovs + Number(iovslen) * 8, size + 4)); + const wasi = _wasi.get(this); + const fileDescriptor = wasi.fds.get(fd, WasiRights.FD_READ | WasiRights.FD_SEEK, BigInt(0)); + if (!iovslen) { + view.setUint32(size, 0, true); + return 0 /* WasiErrno.ESUCCESS */; + } + let totalSize = 0; + const ioVecs = Array.from({ length: Number(iovslen) }, (_, i) => { + const offset = iovs + (i * 8); + const buf = view.getInt32(offset, true); + const bufLen = view.getUint32(offset + 4, true); + totalSize += bufLen; + return HEAPU8.subarray(buf, buf + bufLen); + }); + let nread = 0; + const buffer = (() => { + try { + return new Uint8Array(new SharedArrayBuffer(totalSize)); + } + catch (_) { + return new Uint8Array(totalSize); + } + })(); + buffer._isBuffer = true; + const fs = getFs(this); + const bytesRead = fs.readSync(fileDescriptor.fd, buffer, 0, buffer.length, Number(offset)); + nread = buffer ? copyMemory(ioVecs, buffer.subarray(0, bytesRead)) : 0; + view.setUint32(size, nread, true); + return 0 /* WasiErrno.ESUCCESS */; + }, async function (fd, iovs, iovslen, offset, size) { + iovs = Number(iovs); + size = Number(size); + if ((iovs === 0 && iovslen) || size === 0 || offset > INT64_MAX) { + return 28 /* WasiErrno.EINVAL */; + } + const { HEAPU8, view } = getMemory(this, Math.max(iovs + Number(iovslen) * 8, size + 4)); + const wasi = _wasi.get(this); + const fileDescriptor = wasi.fds.get(fd, WasiRights.FD_READ | WasiRights.FD_SEEK, BigInt(0)); + if (!iovslen) { + view.setUint32(size, 0, true); + return 0 /* WasiErrno.ESUCCESS */; + } + let totalSize = 0; + const ioVecs = Array.from({ length: Number(iovslen) }, (_, i) => { + const offset = iovs + (i * 8); + const buf = view.getInt32(offset, true); + const bufLen = view.getUint32(offset + 4, true); + totalSize += bufLen; + return HEAPU8.subarray(buf, buf + bufLen); + }); + let nread = 0; + const buffer = new Uint8Array(totalSize); + buffer._isBuffer = true; + const { bytesRead } = await fileDescriptor.fd.read(buffer, 0, buffer.length, Number(offset)); + nread = buffer ? copyMemory(ioVecs, buffer.subarray(0, bytesRead)) : 0; + view.setUint32(size, nread, true); + return 0 /* WasiErrno.ESUCCESS */; + }, ['i32', 'i32', 'i32', 'i64', 'i32'], ['i32']); + defineImport('fd_pwrite', function fd_pwrite(fd, iovs, iovslen, offset, size) { + iovs = Number(iovs); + size = Number(size); + if ((iovs === 0 && iovslen) || size === 0 || offset > INT64_MAX) { + return 28 /* WasiErrno.EINVAL */; + } + const { HEAPU8, view } = getMemory(this, Math.max(iovs + Number(iovslen) * 8, size + 4)); + const wasi = _wasi.get(this); + const fileDescriptor = wasi.fds.get(fd, WasiRights.FD_WRITE | WasiRights.FD_SEEK, BigInt(0)); + if (!iovslen) { + view.setUint32(size, 0, true); + return 0 /* WasiErrno.ESUCCESS */; + } + const buffer = concatBuffer(Array.from({ length: Number(iovslen) }, (_, i) => { + const offset = iovs + (i * 8); + const buf = view.getInt32(offset, true); + const bufLen = view.getUint32(offset + 4, true); + return HEAPU8.subarray(buf, buf + bufLen); + })); + const fs = getFs(this); + const nwritten = fs.writeSync(fileDescriptor.fd, buffer, 0, buffer.length, Number(offset)); + view.setUint32(size, nwritten, true); + return 0 /* WasiErrno.ESUCCESS */; + }, async function fd_pwrite(fd, iovs, iovslen, offset, size) { + iovs = Number(iovs); + size = Number(size); + if ((iovs === 0 && iovslen) || size === 0 || offset > INT64_MAX) { + return 28 /* WasiErrno.EINVAL */; + } + const { HEAPU8, view } = getMemory(this, Math.max(iovs + Number(iovslen) * 8, size + 4)); + const wasi = _wasi.get(this); + const fileDescriptor = wasi.fds.get(fd, WasiRights.FD_WRITE | WasiRights.FD_SEEK, BigInt(0)); + if (!iovslen) { + view.setUint32(size, 0, true); + return 0 /* WasiErrno.ESUCCESS */; + } + const buffer = concatBuffer(Array.from({ length: Number(iovslen) }, (_, i) => { + const offset = iovs + (i * 8); + const buf = view.getInt32(offset, true); + const bufLen = view.getUint32(offset + 4, true); + return HEAPU8.subarray(buf, buf + bufLen); + })); + const { bytesWritten } = await fileDescriptor.fd.write(buffer, 0, buffer.length, Number(offset)); + view.setUint32(size, bytesWritten, true); + return 0 /* WasiErrno.ESUCCESS */; + }, ['i32', 'i32', 'i32', 'i64', 'i32'], ['i32']); + defineImport('fd_read', function fd_read(fd, iovs, iovslen, size) { + iovs = Number(iovs); + size = Number(size); + if ((iovs === 0 && iovslen) || size === 0) { + return 28 /* WasiErrno.EINVAL */; + } + const { HEAPU8, view } = getMemory(this, Math.max(iovs + Number(iovslen) * 8, size + 4)); + const wasi = _wasi.get(this); + const fileDescriptor = wasi.fds.get(fd, WasiRights.FD_READ, BigInt(0)); + if (!iovslen) { + view.setUint32(size, 0, true); + return 0 /* WasiErrno.ESUCCESS */; + } + let totalSize = 0; + const ioVecs = Array.from({ length: Number(iovslen) }, (_, i) => { + const offset = iovs + (i * 8); + const buf = view.getInt32(offset, true); + const bufLen = view.getUint32(offset + 4, true); + totalSize += bufLen; + return HEAPU8.subarray(buf, buf + bufLen); + }); + let buffer; + let nread = 0; + if (fd === 0) { + if (typeof window === 'undefined' || typeof window.prompt !== 'function') { + return 58 /* WasiErrno.ENOTSUP */; + } + buffer = readStdin(); + nread = buffer ? copyMemory(ioVecs, buffer) : 0; + } + else { + buffer = (() => { + try { + return new Uint8Array(new SharedArrayBuffer(totalSize)); + } + catch (_) { + return new Uint8Array(totalSize); + } + })(); + buffer._isBuffer = true; + const fs = getFs(this); + const bytesRead = fs.readSync(fileDescriptor.fd, buffer, 0, buffer.length, Number(fileDescriptor.pos)); + nread = buffer ? copyMemory(ioVecs, buffer.subarray(0, bytesRead)) : 0; + fileDescriptor.pos += BigInt(nread); + } + view.setUint32(size, nread, true); + return 0 /* WasiErrno.ESUCCESS */; + }, async function fd_read(fd, iovs, iovslen, size) { + iovs = Number(iovs); + size = Number(size); + if ((iovs === 0 && iovslen) || size === 0) { + return 28 /* WasiErrno.EINVAL */; + } + const { HEAPU8, view } = getMemory(this, Math.max(iovs + Number(iovslen) * 8, size + 4)); + const wasi = _wasi.get(this); + const fileDescriptor = wasi.fds.get(fd, WasiRights.FD_READ, BigInt(0)); + if (!iovslen) { + view.setUint32(size, 0, true); + return 0 /* WasiErrno.ESUCCESS */; + } + let totalSize = 0; + const ioVecs = Array.from({ length: Number(iovslen) }, (_, i) => { + const offset = iovs + (i * 8); + const buf = view.getInt32(offset, true); + const bufLen = view.getUint32(offset + 4, true); + totalSize += bufLen; + return HEAPU8.subarray(buf, buf + bufLen); + }); + let buffer; + let nread = 0; + if (fd === 0) { + if (typeof window === 'undefined' || typeof window.prompt !== 'function') { + return 58 /* WasiErrno.ENOTSUP */; + } + buffer = readStdin(); + nread = buffer ? copyMemory(ioVecs, buffer) : 0; + } + else { + buffer = new Uint8Array(totalSize); + buffer._isBuffer = true; + const { bytesRead } = await fileDescriptor.fd.read(buffer, 0, buffer.length, Number(fileDescriptor.pos)); + nread = buffer ? copyMemory(ioVecs, buffer.subarray(0, bytesRead)) : 0; + fileDescriptor.pos += BigInt(nread); + } + view.setUint32(size, nread, true); + return 0 /* WasiErrno.ESUCCESS */; + }, ['i32', 'i32', 'i32', 'i32'], ['i32']); + defineImport('fd_readdir', function fd_readdir(fd, buf, buf_len, cookie, bufused) { + buf = Number(buf); + buf_len = Number(buf_len); + bufused = Number(bufused); + if (buf === 0 || bufused === 0) + return 0 /* WasiErrno.ESUCCESS */; + const wasi = _wasi.get(this); + const fileDescriptor = wasi.fds.get(fd, WasiRights.FD_READDIR, BigInt(0)); + const fs = getFs(this); + const entries = fs.readdirSync(fileDescriptor.realPath, { withFileTypes: true }); + const { HEAPU8, view } = getMemory(this, Math.max(buf + buf_len, bufused + 4)); + let bufferUsed = 0; + for (let i = Number(cookie); i < entries.length; i++) { + const nameData = encoder.encode(entries[i].name); + const entryInfo = fs.statSync(resolve(fileDescriptor.realPath, entries[i].name), { bigint: true }); + const entryData = new Uint8Array(24 + nameData.byteLength); + const entryView = new DataView(entryData.buffer); + entryView.setBigUint64(0, BigInt(i + 1), true); + entryView.setBigUint64(8, BigInt(entryInfo.ino ? entryInfo.ino : 0), true); + entryView.setUint32(16, nameData.byteLength, true); + let type; + if (entries[i].isFile()) { + type = 4 /* WasiFileType.REGULAR_FILE */; + } + else if (entries[i].isDirectory()) { + type = 3 /* WasiFileType.DIRECTORY */; + } + else if (entries[i].isSymbolicLink()) { + type = 7 /* WasiFileType.SYMBOLIC_LINK */; + } + else if (entries[i].isCharacterDevice()) { + type = 2 /* WasiFileType.CHARACTER_DEVICE */; + } + else if (entries[i].isBlockDevice()) { + type = 1 /* WasiFileType.BLOCK_DEVICE */; + } + else if (entries[i].isSocket()) { + type = 6 /* WasiFileType.SOCKET_STREAM */; + } + else { + type = 0 /* WasiFileType.UNKNOWN */; + } + entryView.setUint8(20, type); + entryData.set(nameData, 24); + const data = entryData.slice(0, Math.min(entryData.length, buf_len - bufferUsed)); + HEAPU8.set(data, buf + bufferUsed); + bufferUsed += data.byteLength; + } + view.setUint32(bufused, bufferUsed, true); + return 0 /* WasiErrno.ESUCCESS */; + }, async function fd_readdir(fd, buf, buf_len, cookie, bufused) { + buf = Number(buf); + buf_len = Number(buf_len); + bufused = Number(bufused); + if (buf === 0 || bufused === 0) + return 0 /* WasiErrno.ESUCCESS */; + const wasi = _wasi.get(this); + const fileDescriptor = wasi.fds.get(fd, WasiRights.FD_READDIR, BigInt(0)); + const fs = getFs(this); + const entries = await fs.promises.readdir(fileDescriptor.realPath, { withFileTypes: true }); + const { HEAPU8, view } = getMemory(this, Math.max(buf + buf_len, bufused + 4)); + let bufferUsed = 0; + for (let i = Number(cookie); i < entries.length; i++) { + const nameData = encoder.encode(entries[i].name); + const entryInfo = await fs.promises.stat(resolve(fileDescriptor.realPath, entries[i].name), { bigint: true }); + const entryData = new Uint8Array(24 + nameData.byteLength); + const entryView = new DataView(entryData.buffer); + entryView.setBigUint64(0, BigInt(i + 1), true); + entryView.setBigUint64(8, BigInt(entryInfo.ino ? entryInfo.ino : 0), true); + entryView.setUint32(16, nameData.byteLength, true); + let type; + if (entries[i].isFile()) { + type = 4 /* WasiFileType.REGULAR_FILE */; + } + else if (entries[i].isDirectory()) { + type = 3 /* WasiFileType.DIRECTORY */; + } + else if (entries[i].isSymbolicLink()) { + type = 7 /* WasiFileType.SYMBOLIC_LINK */; + } + else if (entries[i].isCharacterDevice()) { + type = 2 /* WasiFileType.CHARACTER_DEVICE */; + } + else if (entries[i].isBlockDevice()) { + type = 1 /* WasiFileType.BLOCK_DEVICE */; + } + else if (entries[i].isSocket()) { + type = 6 /* WasiFileType.SOCKET_STREAM */; + } + else { + type = 0 /* WasiFileType.UNKNOWN */; + } + entryView.setUint8(20, type); + entryData.set(nameData, 24); + const data = entryData.slice(0, Math.min(entryData.length, buf_len - bufferUsed)); + HEAPU8.set(data, buf + bufferUsed); + bufferUsed += data.byteLength; + } + view.setUint32(bufused, bufferUsed, true); + return 0 /* WasiErrno.ESUCCESS */; + }, ['i32', 'i32', 'i32', 'i64', 'i32'], ['i32']); + defineImport('fd_renumber', function fd_renumber(from, to) { + const wasi = _wasi.get(this); + wasi.fds.renumber(to, from); + return 0 /* WasiErrno.ESUCCESS */; + }, async function fd_renumber(from, to) { + const wasi = _wasi.get(this); + await wasi.fds.renumber(to, from); + return 0 /* WasiErrno.ESUCCESS */; + }, ['i32', 'i32'], ['i32']); + defineImport('fd_sync', function fd_sync(fd) { + const wasi = _wasi.get(this); + const fileDescriptor = wasi.fds.get(fd, WasiRights.FD_SYNC, BigInt(0)); + const fs = getFs(this); + fs.fsyncSync(fileDescriptor.fd); + return 0 /* WasiErrno.ESUCCESS */; + }, async function fd_sync(fd) { + const wasi = _wasi.get(this); + const fileDescriptor = wasi.fds.get(fd, WasiRights.FD_SYNC, BigInt(0)); + await fileDescriptor.fd.sync(); + return 0 /* WasiErrno.ESUCCESS */; + }, ['i32'], ['i32']); + defineImport('fd_write', function fd_write(fd, iovs, iovslen, size) { + iovs = Number(iovs); + size = Number(size); + if ((iovs === 0 && iovslen) || size === 0) { + return 28 /* WasiErrno.EINVAL */; + } + const { HEAPU8, view } = getMemory(this, Math.max(iovs + Number(iovslen) * 8, size + 4)); + const wasi = _wasi.get(this); + const fileDescriptor = wasi.fds.get(fd, WasiRights.FD_WRITE, BigInt(0)); + if (!iovslen) { + view.setUint32(size, 0, true); + return 0 /* WasiErrno.ESUCCESS */; + } + const buffer = concatBuffer(Array.from({ length: Number(iovslen) }, (_, i) => { + const offset = iovs + (i * 8); + const buf = view.getInt32(offset, true); + const bufLen = view.getUint32(offset + 4, true); + return HEAPU8.subarray(buf, buf + bufLen); + })); + let nwritten; + if (fd === 1 || fd === 2) { + nwritten = fileDescriptor.write(buffer); + } + else { + const fs = getFs(this); + nwritten = fs.writeSync(fileDescriptor.fd, buffer, 0, buffer.length, Number(fileDescriptor.pos)); + fileDescriptor.pos += BigInt(nwritten); + } + view.setUint32(size, nwritten, true); + return 0 /* WasiErrno.ESUCCESS */; + }, async function fd_write(fd, iovs, iovslen, size) { + iovs = Number(iovs); + size = Number(size); + if ((iovs === 0 && iovslen) || size === 0) { + return 28 /* WasiErrno.EINVAL */; + } + const { HEAPU8, view } = getMemory(this, Math.max(iovs + Number(iovslen) * 8, size + 4)); + const wasi = _wasi.get(this); + const fileDescriptor = wasi.fds.get(fd, WasiRights.FD_WRITE, BigInt(0)); + if (!iovslen) { + view.setUint32(size, 0, true); + return 0 /* WasiErrno.ESUCCESS */; + } + const buffer = concatBuffer(Array.from({ length: Number(iovslen) }, (_, i) => { + const offset = iovs + (i * 8); + const buf = view.getInt32(offset, true); + const bufLen = view.getUint32(offset + 4, true); + return HEAPU8.subarray(buf, buf + bufLen); + })); + let nwritten; + if (fd === 1 || fd === 2) { + nwritten = fileDescriptor.write(buffer); + } + else { + nwritten = await (await (fileDescriptor.fd.write(buffer, 0, buffer.length, Number(fileDescriptor.pos)))).bytesWritten; + fileDescriptor.pos += BigInt(nwritten); + } + view.setUint32(size, nwritten, true); + return 0 /* WasiErrno.ESUCCESS */; + }, ['i32', 'i32', 'i32', 'i32'], ['i32']); + defineImport('path_create_directory', function path_create_directory(fd, path, path_len) { + path = Number(path); + path_len = Number(path_len); + if (path === 0) { + return 28 /* WasiErrno.EINVAL */; + } + const { HEAPU8 } = getMemory(this, path + path_len); + const wasi = _wasi.get(this); + const fileDescriptor = wasi.fds.get(fd, WasiRights.PATH_CREATE_DIRECTORY, BigInt(0)); + let pathString = decoder.decode(unsharedSlice(HEAPU8, path, path + path_len)); + pathString = resolve(fileDescriptor.realPath, pathString); + const fs = getFs(this); + fs.mkdirSync(pathString); + return 0 /* WasiErrno.ESUCCESS */; + }, async function path_create_directory(fd, path, path_len) { + path = Number(path); + path_len = Number(path_len); + if (path === 0) { + return 28 /* WasiErrno.EINVAL */; + } + const { HEAPU8 } = getMemory(this, path + path_len); + const wasi = _wasi.get(this); + const fileDescriptor = wasi.fds.get(fd, WasiRights.PATH_CREATE_DIRECTORY, BigInt(0)); + let pathString = decoder.decode(unsharedSlice(HEAPU8, path, path + path_len)); + pathString = resolve(fileDescriptor.realPath, pathString); + const fs = getFs(this); + await fs.promises.mkdir(pathString); + return 0 /* WasiErrno.ESUCCESS */; + }, ['i32', 'i32', 'i32'], ['i32']); + defineImport('path_filestat_get', function path_filestat_get(fd, flags, path, path_len, filestat) { + path = Number(path); + path_len = Number(path_len); + filestat = Number(filestat); + if (path === 0 || filestat === 0) { + return 28 /* WasiErrno.EINVAL */; + } + const { HEAPU8, view } = getMemory(this, Math.max(path + path_len, filestat + 64)); + const wasi = _wasi.get(this); + const fileDescriptor = wasi.fds.get(fd, WasiRights.PATH_FILESTAT_GET, BigInt(0)); + let pathString = decoder.decode(unsharedSlice(HEAPU8, path, path + path_len)); + const fs = getFs(this); + pathString = resolve(fileDescriptor.realPath, pathString); + let stat; + if ((flags & 1) === 1) { + stat = fs.statSync(pathString, { bigint: true }); + } + else { + stat = fs.lstatSync(pathString, { bigint: true }); + } + toFileStat(view, filestat, stat); + return 0 /* WasiErrno.ESUCCESS */; + }, async function path_filestat_get(fd, flags, path, path_len, filestat) { + path = Number(path); + path_len = Number(path_len); + filestat = Number(filestat); + if (path === 0 || filestat === 0) { + return 28 /* WasiErrno.EINVAL */; + } + const { HEAPU8, view } = getMemory(this, Math.max(path + path_len, filestat + 64)); + const wasi = _wasi.get(this); + const fileDescriptor = wasi.fds.get(fd, WasiRights.PATH_FILESTAT_GET, BigInt(0)); + let pathString = decoder.decode(unsharedSlice(HEAPU8, path, path + path_len)); + const fs = getFs(this); + pathString = resolve(fileDescriptor.realPath, pathString); + let stat; + if ((flags & 1) === 1) { + stat = await fs.promises.stat(pathString, { bigint: true }); + } + else { + stat = await fs.promises.lstat(pathString, { bigint: true }); + } + toFileStat(view, filestat, stat); + return 0 /* WasiErrno.ESUCCESS */; + }, ['i32', 'i32', 'i32', 'i32', 'i32'], ['i32']); + defineImport('path_filestat_set_times', function path_filestat_set_times(fd, flags, path, path_len, atim, mtim, fst_flags) { + path = Number(path); + path_len = Number(path_len); + if (path === 0) + return 28 /* WasiErrno.EINVAL */; + const { HEAPU8 } = getMemory(this, path + path_len); + const wasi = _wasi.get(this); + const fileDescriptor = wasi.fds.get(fd, WasiRights.PATH_FILESTAT_SET_TIMES, BigInt(0)); + if (validateFstFlagsOrReturn(fst_flags)) { + return 28 /* WasiErrno.EINVAL */; + } + const fs = getFs(this); + const resolvedPath = resolvePathSync(fs, fileDescriptor, decoder.decode(unsharedSlice(HEAPU8, path, path + path_len)), flags); + if ((fst_flags & 2 /* WasiFstFlag.SET_ATIM_NOW */) === 2 /* WasiFstFlag.SET_ATIM_NOW */) { + atim = BigInt(Date.now() * 1000000); + } + if ((fst_flags & 8 /* WasiFstFlag.SET_MTIM_NOW */) === 8 /* WasiFstFlag.SET_MTIM_NOW */) { + mtim = BigInt(Date.now() * 1000000); + } + fs.utimesSync(resolvedPath, Number(atim), Number(mtim)); + return 0 /* WasiErrno.ESUCCESS */; + }, async function path_filestat_set_times(fd, flags, path, path_len, atim, mtim, fst_flags) { + path = Number(path); + path_len = Number(path_len); + if (path === 0) + return 28 /* WasiErrno.EINVAL */; + const { HEAPU8 } = getMemory(this, path + path_len); + const wasi = _wasi.get(this); + const fileDescriptor = wasi.fds.get(fd, WasiRights.PATH_FILESTAT_SET_TIMES, BigInt(0)); + if (validateFstFlagsOrReturn(fst_flags)) { + return 28 /* WasiErrno.EINVAL */; + } + const fs = getFs(this); + const resolvedPath = await resolvePathAsync(fs, fileDescriptor, decoder.decode(unsharedSlice(HEAPU8, path, path + path_len)), flags); + if ((fst_flags & 2 /* WasiFstFlag.SET_ATIM_NOW */) === 2 /* WasiFstFlag.SET_ATIM_NOW */) { + atim = BigInt(Date.now() * 1000000); + } + if ((fst_flags & 8 /* WasiFstFlag.SET_MTIM_NOW */) === 8 /* WasiFstFlag.SET_MTIM_NOW */) { + mtim = BigInt(Date.now() * 1000000); + } + await fs.promises.utimes(resolvedPath, Number(atim), Number(mtim)); + return 0 /* WasiErrno.ESUCCESS */; + }, ['i32', 'i32', 'i32', 'i32', 'i64', 'i64', 'i32'], ['i32']); + defineImport('path_link', function path_link(old_fd, old_flags, old_path, old_path_len, new_fd, new_path, new_path_len) { + old_path = Number(old_path); + old_path_len = Number(old_path_len); + new_path = Number(new_path); + new_path_len = Number(new_path_len); + if (old_path === 0 || new_path === 0) { + return 28 /* WasiErrno.EINVAL */; + } + const wasi = _wasi.get(this); + let oldWrap; + let newWrap; + if (old_fd === new_fd) { + oldWrap = newWrap = wasi.fds.get(old_fd, WasiRights.PATH_LINK_SOURCE | WasiRights.PATH_LINK_TARGET, BigInt(0)); + } + else { + oldWrap = wasi.fds.get(old_fd, WasiRights.PATH_LINK_SOURCE, BigInt(0)); + newWrap = wasi.fds.get(new_fd, WasiRights.PATH_LINK_TARGET, BigInt(0)); + } + const { HEAPU8 } = getMemory(this, Math.max(old_path + old_path_len, new_path + new_path_len)); + const fs = getFs(this); + const resolvedOldPath = resolvePathSync(fs, oldWrap, decoder.decode(unsharedSlice(HEAPU8, old_path, old_path + old_path_len)), old_flags); + const resolvedNewPath = resolve(newWrap.realPath, decoder.decode(unsharedSlice(HEAPU8, new_path, new_path + new_path_len))); + fs.linkSync(resolvedOldPath, resolvedNewPath); + return 0 /* WasiErrno.ESUCCESS */; + }, async function path_link(old_fd, old_flags, old_path, old_path_len, new_fd, new_path, new_path_len) { + old_path = Number(old_path); + old_path_len = Number(old_path_len); + new_path = Number(new_path); + new_path_len = Number(new_path_len); + if (old_path === 0 || new_path === 0) { + return 28 /* WasiErrno.EINVAL */; + } + const wasi = _wasi.get(this); + let oldWrap; + let newWrap; + if (old_fd === new_fd) { + oldWrap = newWrap = wasi.fds.get(old_fd, WasiRights.PATH_LINK_SOURCE | WasiRights.PATH_LINK_TARGET, BigInt(0)); + } + else { + oldWrap = wasi.fds.get(old_fd, WasiRights.PATH_LINK_SOURCE, BigInt(0)); + newWrap = wasi.fds.get(new_fd, WasiRights.PATH_LINK_TARGET, BigInt(0)); + } + const { HEAPU8 } = getMemory(this, Math.max(old_path + old_path_len, new_path + new_path_len)); + const fs = getFs(this); + const resolvedOldPath = await resolvePathAsync(fs, oldWrap, decoder.decode(unsharedSlice(HEAPU8, old_path, old_path + old_path_len)), old_flags); + const resolvedNewPath = resolve(newWrap.realPath, decoder.decode(unsharedSlice(HEAPU8, new_path, new_path + new_path_len))); + await fs.promises.link(resolvedOldPath, resolvedNewPath); + return 0 /* WasiErrno.ESUCCESS */; + }, ['i32', 'i32', 'i32', 'i32', 'i32', 'i32', 'i32'], ['i32']); + function pathOpen(o_flags, fs_rights_base, fs_rights_inheriting, fs_flags) { + const read = (fs_rights_base & (WasiRights.FD_READ | + WasiRights.FD_READDIR)) !== BigInt(0); + const write = (fs_rights_base & (WasiRights.FD_DATASYNC | + WasiRights.FD_WRITE | + WasiRights.FD_ALLOCATE | + WasiRights.FD_FILESTAT_SET_SIZE)) !== BigInt(0); + let flags = write ? read ? 2 /* FileControlFlag.O_RDWR */ : 1 /* FileControlFlag.O_WRONLY */ : 0 /* FileControlFlag.O_RDONLY */; + let needed_base = WasiRights.PATH_OPEN; + let needed_inheriting = fs_rights_base | fs_rights_inheriting; + if ((o_flags & 1 /* WasiFileControlFlag.O_CREAT */) !== 0) { + flags |= 64 /* FileControlFlag.O_CREAT */; + needed_base |= WasiRights.PATH_CREATE_FILE; + } + if ((o_flags & 2 /* WasiFileControlFlag.O_DIRECTORY */) !== 0) { + flags |= 65536 /* FileControlFlag.O_DIRECTORY */; + } + if ((o_flags & 4 /* WasiFileControlFlag.O_EXCL */) !== 0) { + flags |= 128 /* FileControlFlag.O_EXCL */; + } + if ((o_flags & 8 /* WasiFileControlFlag.O_TRUNC */) !== 0) { + flags |= 512 /* FileControlFlag.O_TRUNC */; + needed_base |= WasiRights.PATH_FILESTAT_SET_SIZE; + } + if ((fs_flags & 1 /* WasiFdFlag.APPEND */) !== 0) { + flags |= 1024 /* FileControlFlag.O_APPEND */; + } + if ((fs_flags & 2 /* WasiFdFlag.DSYNC */) !== 0) { + // flags |= FileControlFlag.O_DSYNC; + needed_inheriting |= WasiRights.FD_DATASYNC; + } + if ((fs_flags & 4 /* WasiFdFlag.NONBLOCK */) !== 0) { + flags |= 2048 /* FileControlFlag.O_NONBLOCK */; + } + if ((fs_flags & 8 /* WasiFdFlag.RSYNC */) !== 0) { + flags |= 1052672 /* FileControlFlag.O_SYNC */; + needed_inheriting |= WasiRights.FD_SYNC; + } + if ((fs_flags & 16 /* WasiFdFlag.SYNC */) !== 0) { + flags |= 1052672 /* FileControlFlag.O_SYNC */; + needed_inheriting |= WasiRights.FD_SYNC; + } + if (write && (flags & (1024 /* FileControlFlag.O_APPEND */ | 512 /* FileControlFlag.O_TRUNC */)) === 0) { + needed_inheriting |= WasiRights.FD_SEEK; + } + return { flags, needed_base, needed_inheriting }; + } + defineImport('path_open', function path_open(dirfd, dirflags, path, path_len, o_flags, fs_rights_base, fs_rights_inheriting, fs_flags, fd) { + path = Number(path); + fd = Number(fd); + if (path === 0 || fd === 0) { + return 28 /* WasiErrno.EINVAL */; + } + path_len = Number(path_len); + fs_rights_base = BigInt(fs_rights_base); + fs_rights_inheriting = BigInt(fs_rights_inheriting); + const { flags: flagsRes, needed_base: neededBase, needed_inheriting: neededInheriting } = pathOpen(o_flags, fs_rights_base, fs_rights_inheriting, fs_flags); + const wasi = _wasi.get(this); + const fileDescriptor = wasi.fds.get(dirfd, neededBase, neededInheriting); + const memory = getMemory(this, Math.max(path + path_len, fd + 4)); + const HEAPU8 = memory.HEAPU8; + const pathString = decoder.decode(unsharedSlice(HEAPU8, path, path + path_len)); + const fs = getFs(this); + const resolved_path = resolvePathSync(fs, fileDescriptor, pathString, dirflags); + const r = fs.openSync(resolved_path, _isWin32Flags ? _toWinOpenFlags(flagsRes) : flagsRes, 0o666); + const filetype = wasi.fds.getFileTypeByFd(r); + if ((filetype !== 3 /* WasiFileType.DIRECTORY */) && + ((o_flags & 2 /* WasiFileControlFlag.O_DIRECTORY */) !== 0 || + (resolved_path.endsWith('/')))) { + return 54 /* WasiErrno.ENOTDIR */; + } + const { base: max_base, inheriting: max_inheriting } = getRights(wasi.fds.stdio, r, flagsRes, filetype); + const wrap = wasi.fds.insert(r, resolved_path, resolved_path, filetype, fs_rights_base & max_base, fs_rights_inheriting & max_inheriting, 0); + const stat = fs.fstatSync(r, { bigint: true }); + if (stat.isFile()) { + wrap.size = stat.size; + if ((flagsRes & 1024 /* FileControlFlag.O_APPEND */) !== 0) { + wrap.pos = stat.size; + } + } + const view = memory.view; + view.setInt32(fd, wrap.id, true); + return 0 /* WasiErrno.ESUCCESS */; + }, async function path_open(dirfd, dirflags, path, path_len, o_flags, fs_rights_base, fs_rights_inheriting, fs_flags, fd) { + path = Number(path); + fd = Number(fd); + if (path === 0 || fd === 0) { + return 28 /* WasiErrno.EINVAL */; + } + path_len = Number(path_len); + fs_rights_base = BigInt(fs_rights_base); + fs_rights_inheriting = BigInt(fs_rights_inheriting); + const { flags: flagsRes, needed_base: neededBase, needed_inheriting: neededInheriting } = pathOpen(o_flags, fs_rights_base, fs_rights_inheriting, fs_flags); + const wasi = _wasi.get(this); + const fileDescriptor = wasi.fds.get(dirfd, neededBase, neededInheriting); + const memory = getMemory(this, Math.max(path + path_len, fd + 4)); + const HEAPU8 = memory.HEAPU8; + const pathString = decoder.decode(unsharedSlice(HEAPU8, path, path + path_len)); + const fs = getFs(this); + const resolved_path = await resolvePathAsync(fs, fileDescriptor, pathString, dirflags); + const r = await fs.promises.open(resolved_path, _isWin32Flags ? _toWinOpenFlags(flagsRes) : flagsRes, 0o666); + const filetype = await wasi.fds.getFileTypeByFd(r); + if ((o_flags & 2 /* WasiFileControlFlag.O_DIRECTORY */) !== 0 && filetype !== 3 /* WasiFileType.DIRECTORY */) { + return 54 /* WasiErrno.ENOTDIR */; + } + const { base: max_base, inheriting: max_inheriting } = getRights(wasi.fds.stdio, r.fd, flagsRes, filetype); + const wrap = wasi.fds.insert(r, resolved_path, resolved_path, filetype, fs_rights_base & max_base, fs_rights_inheriting & max_inheriting, 0); + const stat = await r.stat({ bigint: true }); + if (stat.isFile()) { + wrap.size = stat.size; + if ((flagsRes & 1024 /* FileControlFlag.O_APPEND */) !== 0) { + wrap.pos = stat.size; + } + } + const view = memory.view; + view.setInt32(fd, wrap.id, true); + return 0 /* WasiErrno.ESUCCESS */; + }, ['i32', 'i32', 'i32', 'i32', 'i32', 'i64', 'i64', 'i32', 'i32'], ['i32']); + defineImport('path_readlink', function path_readlink(fd, path, path_len, buf, buf_len, bufused) { + path = Number(path); + path_len = Number(path_len); + buf = Number(buf); + buf_len = Number(buf_len); + bufused = Number(bufused); + if (path === 0 || buf === 0 || bufused === 0) { + return 28 /* WasiErrno.EINVAL */; + } + const { HEAPU8, view } = getMemory(this, Math.max(path + path_len, buf + buf_len, bufused + 4)); + const wasi = _wasi.get(this); + const fileDescriptor = wasi.fds.get(fd, WasiRights.PATH_READLINK, BigInt(0)); + let pathString = decoder.decode(unsharedSlice(HEAPU8, path, path + path_len)); + pathString = resolve(fileDescriptor.realPath, pathString); + const fs = getFs(this); + const link = fs.readlinkSync(pathString); + const linkData = encoder.encode(link); + const len = Math.min(linkData.length, buf_len); + if (len >= buf_len) + return 42 /* WasiErrno.ENOBUFS */; + HEAPU8.set(linkData.subarray(0, len), buf); + HEAPU8[buf + len] = 0; + view.setUint32(bufused, len, true); + return 0 /* WasiErrno.ESUCCESS */; + }, async function path_readlink(fd, path, path_len, buf, buf_len, bufused) { + path = Number(path); + path_len = Number(path_len); + buf = Number(buf); + buf_len = Number(buf_len); + bufused = Number(bufused); + if (path === 0 || buf === 0 || bufused === 0) { + return 28 /* WasiErrno.EINVAL */; + } + const { HEAPU8, view } = getMemory(this, Math.max(path + path_len, buf + buf_len, bufused + 4)); + const wasi = _wasi.get(this); + const fileDescriptor = wasi.fds.get(fd, WasiRights.PATH_READLINK, BigInt(0)); + let pathString = decoder.decode(unsharedSlice(HEAPU8, path, path + path_len)); + pathString = resolve(fileDescriptor.realPath, pathString); + const fs = getFs(this); + const link = await fs.promises.readlink(pathString); + const linkData = encoder.encode(link); + const len = Math.min(linkData.length, buf_len); + if (len >= buf_len) + return 42 /* WasiErrno.ENOBUFS */; + HEAPU8.set(linkData.subarray(0, len), buf); + HEAPU8[buf + len] = 0; + view.setUint32(bufused, len, true); + return 0 /* WasiErrno.ESUCCESS */; + }, ['i32', 'i32', 'i32', 'i32', 'i32', 'i32'], ['i32']); + defineImport('path_remove_directory', function path_remove_directory(fd, path, path_len) { + path = Number(path); + path_len = Number(path_len); + if (path === 0) { + return 28 /* WasiErrno.EINVAL */; + } + const { HEAPU8 } = getMemory(this, path + path_len); + const wasi = _wasi.get(this); + const fileDescriptor = wasi.fds.get(fd, WasiRights.PATH_REMOVE_DIRECTORY, BigInt(0)); + let pathString = decoder.decode(unsharedSlice(HEAPU8, path, path + path_len)); + pathString = resolve(fileDescriptor.realPath, pathString); + const fs = getFs(this); + fs.rmdirSync(pathString); + return 0 /* WasiErrno.ESUCCESS */; + }, async function path_remove_directory(fd, path, path_len) { + path = Number(path); + path_len = Number(path_len); + if (path === 0) { + return 28 /* WasiErrno.EINVAL */; + } + const { HEAPU8 } = getMemory(this, path + path_len); + const wasi = _wasi.get(this); + const fileDescriptor = wasi.fds.get(fd, WasiRights.PATH_REMOVE_DIRECTORY, BigInt(0)); + let pathString = decoder.decode(unsharedSlice(HEAPU8, path, path + path_len)); + pathString = resolve(fileDescriptor.realPath, pathString); + const fs = getFs(this); + await fs.promises.rmdir(pathString); + return 0 /* WasiErrno.ESUCCESS */; + }, ['i32', 'i32', 'i32'], ['i32']); + defineImport('path_rename', function path_rename(old_fd, old_path, old_path_len, new_fd, new_path, new_path_len) { + old_path = Number(old_path); + old_path_len = Number(old_path_len); + new_path = Number(new_path); + new_path_len = Number(new_path_len); + if (old_path === 0 || new_path === 0) { + return 28 /* WasiErrno.EINVAL */; + } + const wasi = _wasi.get(this); + let oldWrap; + let newWrap; + if (old_fd === new_fd) { + oldWrap = newWrap = wasi.fds.get(old_fd, WasiRights.PATH_RENAME_SOURCE | WasiRights.PATH_RENAME_TARGET, BigInt(0)); + } + else { + oldWrap = wasi.fds.get(old_fd, WasiRights.PATH_RENAME_SOURCE, BigInt(0)); + newWrap = wasi.fds.get(new_fd, WasiRights.PATH_RENAME_TARGET, BigInt(0)); + } + const { HEAPU8 } = getMemory(this, Math.max(old_path + old_path_len, new_path + new_path_len)); + const resolvedOldPath = resolve(oldWrap.realPath, decoder.decode(unsharedSlice(HEAPU8, old_path, old_path + old_path_len))); + const resolvedNewPath = resolve(newWrap.realPath, decoder.decode(unsharedSlice(HEAPU8, new_path, new_path + new_path_len))); + const fs = getFs(this); + fs.renameSync(resolvedOldPath, resolvedNewPath); + return 0 /* WasiErrno.ESUCCESS */; + }, async function path_rename(old_fd, old_path, old_path_len, new_fd, new_path, new_path_len) { + old_path = Number(old_path); + old_path_len = Number(old_path_len); + new_path = Number(new_path); + new_path_len = Number(new_path_len); + if (old_path === 0 || new_path === 0) { + return 28 /* WasiErrno.EINVAL */; + } + const wasi = _wasi.get(this); + let oldWrap; + let newWrap; + if (old_fd === new_fd) { + oldWrap = newWrap = wasi.fds.get(old_fd, WasiRights.PATH_RENAME_SOURCE | WasiRights.PATH_RENAME_TARGET, BigInt(0)); + } + else { + oldWrap = wasi.fds.get(old_fd, WasiRights.PATH_RENAME_SOURCE, BigInt(0)); + newWrap = wasi.fds.get(new_fd, WasiRights.PATH_RENAME_TARGET, BigInt(0)); + } + const { HEAPU8 } = getMemory(this, Math.max(old_path + old_path_len, new_path + new_path_len)); + const resolvedOldPath = resolve(oldWrap.realPath, decoder.decode(unsharedSlice(HEAPU8, old_path, old_path + old_path_len))); + const resolvedNewPath = resolve(newWrap.realPath, decoder.decode(unsharedSlice(HEAPU8, new_path, new_path + new_path_len))); + const fs = getFs(this); + await fs.promises.rename(resolvedOldPath, resolvedNewPath); + return 0 /* WasiErrno.ESUCCESS */; + }, ['i32', 'i32', 'i32', 'i32', 'i32', 'i32'], ['i32']); + defineImport('path_symlink', function path_symlink(old_path, old_path_len, fd, new_path, new_path_len) { + old_path = Number(old_path); + old_path_len = Number(old_path_len); + new_path = Number(new_path); + new_path_len = Number(new_path_len); + if (old_path === 0 || new_path === 0) { + return 28 /* WasiErrno.EINVAL */; + } + const { HEAPU8 } = getMemory(this, Math.max(old_path + old_path_len, new_path + new_path_len)); + const wasi = _wasi.get(this); + const fileDescriptor = wasi.fds.get(fd, WasiRights.PATH_SYMLINK, BigInt(0)); + const oldPath = decoder.decode(unsharedSlice(HEAPU8, old_path, old_path + old_path_len)); + if (oldPath.length > 0 && oldPath[0] === '/') { + return 63 /* WasiErrno.EPERM */; + } + let newPath = decoder.decode(unsharedSlice(HEAPU8, new_path, new_path + new_path_len)); + newPath = resolve(fileDescriptor.realPath, newPath); + const fs = getFs(this); + fs.symlinkSync(oldPath, newPath); + return 0 /* WasiErrno.ESUCCESS */; + }, async function path_symlink(old_path, old_path_len, fd, new_path, new_path_len) { + old_path = Number(old_path); + old_path_len = Number(old_path_len); + new_path = Number(new_path); + new_path_len = Number(new_path_len); + if (old_path === 0 || new_path === 0) { + return 28 /* WasiErrno.EINVAL */; + } + const { HEAPU8 } = getMemory(this, Math.max(old_path + old_path_len, new_path + new_path_len)); + const wasi = _wasi.get(this); + const fileDescriptor = wasi.fds.get(fd, WasiRights.PATH_SYMLINK, BigInt(0)); + const oldPath = decoder.decode(unsharedSlice(HEAPU8, old_path, old_path + old_path_len)); + let newPath = decoder.decode(unsharedSlice(HEAPU8, new_path, new_path + new_path_len)); + newPath = resolve(fileDescriptor.realPath, newPath); + const fs = getFs(this); + await fs.promises.symlink(oldPath, newPath); + return 0 /* WasiErrno.ESUCCESS */; + }, ['i32', 'i32', 'i32', 'i32', 'i32'], ['i32']); + defineImport('path_unlink_file', function path_unlink_file(fd, path, path_len) { + path = Number(path); + path_len = Number(path_len); + if (path === 0) { + return 28 /* WasiErrno.EINVAL */; + } + const { HEAPU8 } = getMemory(this, path + path_len); + const wasi = _wasi.get(this); + const fileDescriptor = wasi.fds.get(fd, WasiRights.PATH_UNLINK_FILE, BigInt(0)); + let pathString = decoder.decode(unsharedSlice(HEAPU8, path, path + path_len)); + pathString = resolve(fileDescriptor.realPath, pathString); + const fs = getFs(this); + fs.unlinkSync(pathString); + return 0 /* WasiErrno.ESUCCESS */; + }, async function path_unlink_file(fd, path, path_len) { + path = Number(path); + path_len = Number(path_len); + if (path === 0) { + return 28 /* WasiErrno.EINVAL */; + } + const { HEAPU8 } = getMemory(this, path + path_len); + const wasi = _wasi.get(this); + const fileDescriptor = wasi.fds.get(fd, WasiRights.PATH_UNLINK_FILE, BigInt(0)); + let pathString = decoder.decode(unsharedSlice(HEAPU8, path, path + path_len)); + pathString = resolve(fileDescriptor.realPath, pathString); + const fs = getFs(this); + await fs.promises.unlink(pathString); + return 0 /* WasiErrno.ESUCCESS */; + }, ['i32', 'i32', 'i32'], ['i32']); + this._setMemory = function setMemory(m) { + if (!(m instanceof _WebAssembly.Memory)) { + throw new TypeError('"instance.exports.memory" property must be a WebAssembly.Memory'); + } + _memory.set(_this, extendMemory(m)); + }; + } + static createSync(args, env, preopens, stdio, fs, print, printErr) { + const fds = new SyncTable({ + size: 3, + in: stdio[0], + out: stdio[1], + err: stdio[2], + fs, + print, + printErr + }); + const _this = new WASI$1(args, env, fds, false, fs); + if (preopens.length > 0) { + for (let i = 0; i < preopens.length; ++i) { + const realPath = fs.realpathSync(preopens[i].realPath, 'utf8'); + const fd = fs.openSync(realPath, 'r', 0o666); + fds.insertPreopen(fd, preopens[i].mappedPath, realPath); + } + } + return _this; + } + static async createAsync(args, env, preopens, stdio, fs, print, printErr, asyncify) { + const fds = new AsyncTable({ + size: 3, + in: stdio[0], + out: stdio[1], + err: stdio[2], + print, + printErr + }); + const _this = new WASI$1(args, env, fds, true, fs, asyncify); + if (preopens.length > 0) { + for (let i = 0; i < preopens.length; ++i) { + const entry = preopens[i]; + const realPath = await fs.promises.realpath(entry.realPath); + const fd = await fs.promises.open(realPath, 'r', 0o666); + await fds.insertPreopen(fd, entry.mappedPath, realPath); + } + } + return _this; + } +} + +// eslint-disable-next-line spaced-comment +const kEmptyObject = /*#__PURE__*/ Object.freeze(/*#__PURE__*/ Object.create(null)); +const kExitCode = Symbol('kExitCode'); +const kSetMemory = Symbol('kSetMemory'); +const kStarted = Symbol('kStarted'); +const kInstance = Symbol('kInstance'); +const kBindingName = Symbol('kBindingName'); +function validateOptions(options) { + var _a; + validateObject(options, 'options'); + let _WASI; + if (options.version !== undefined) { + validateString(options.version, 'options.version'); + switch (options.version) { + case 'unstable': + _WASI = WASI$1; + this[kBindingName] = 'wasi_unstable'; + break; + case 'preview1': + _WASI = WASI$1; + this[kBindingName] = 'wasi_snapshot_preview1'; + break; + default: + throw new TypeError(`unsupported WASI version "${options.version}"`); + } + } + else { + _WASI = WASI$1; + this[kBindingName] = 'wasi_snapshot_preview1'; + } + if (options.args !== undefined) { + validateArray(options.args, 'options.args'); + } + const args = ((_a = options.args) !== null && _a !== void 0 ? _a : []).map(String); + const env = []; + if (options.env !== undefined) { + validateObject(options.env, 'options.env'); + Object.entries(options.env).forEach(({ 0: key, 1: value }) => { + if (value !== undefined) { + env.push(`${key}=${value}`); + } + }); + } + const preopens = []; + if (options.preopens !== undefined) { + validateObject(options.preopens, 'options.preopens'); + Object.entries(options.preopens).forEach(({ 0: key, 1: value }) => preopens.push({ mappedPath: String(key), realPath: String(value) })); + } + if (preopens.length > 0) { + if (options.fs === undefined) { + throw new Error('filesystem is disabled, can not preopen directory'); + } + try { + validateObject(options.fs, 'options.fs'); + } + catch (_) { + throw new TypeError('Node.js fs like implementation is not provided'); + } + } + // if (options.filesystem !== undefined) { + // validateObject(options.filesystem, 'options.filesystem') + // validateString(options.filesystem.type, 'options.filesystem.type') + // if (options.filesystem.type !== 'memfs' && options.filesystem.type !== 'file-system-access-api') { + // throw new Error(`Filesystem type ${(options.filesystem as any).type as string} is not supported, only "memfs" and "file-system-access-api" is supported currently`) + // } + // try { + // validateObject(options.filesystem.fs, 'options.filesystem.fs') + // } catch (_) { + // throw new Error('Node.js fs like implementation is not provided') + // } + // } + if (options.print !== undefined) + validateFunction(options.print, 'options.print'); + if (options.printErr !== undefined) + validateFunction(options.printErr, 'options.printErr'); + if (options.returnOnExit !== undefined) { + validateBoolean(options.returnOnExit, 'options.returnOnExit'); + } + // const { stdin = 0, stdout = 1, stderr = 2 } = options + // validateInt32(stdin, 'options.stdin', 0) + // validateInt32(stdout, 'options.stdout', 0) + // validateInt32(stderr, 'options.stderr', 0) + // const stdio = [stdin, stdout, stderr] as const + const stdio = [0, 1, 2]; + return { + args, + env, + preopens, + stdio, + _WASI + }; +} +function initWASI(setMemory, wrap) { + this[kSetMemory] = setMemory; + this.wasiImport = wrap; + this[kStarted] = false; + this[kExitCode] = 0; + this[kInstance] = undefined; +} +/** @public */ +class WASI { + constructor(options = kEmptyObject) { + const { args, env, preopens, stdio, _WASI } = validateOptions.call(this, options); + const wrap = _WASI.createSync(args, env, preopens, stdio, options.fs, options.print, options.printErr); + const setMemory = wrap._setMemory; + delete wrap._setMemory; + initWASI.call(this, setMemory, wrap); + if (options.returnOnExit) { + wrap.proc_exit = wasiReturnOnProcExit.bind(this); + } + } + finalizeBindings(instance, _a) { + var _b; + var { memory = (_b = instance === null || instance === void 0 ? void 0 : instance.exports) === null || _b === void 0 ? void 0 : _b.memory } = _a === void 0 ? {} : _a; + if (this[kStarted]) { + throw new Error('WASI instance has already started'); + } + validateObject(instance, 'instance'); + validateObject(instance.exports, 'instance.exports'); + this[kSetMemory](memory); + this[kInstance] = instance; + this[kStarted] = true; + } + // Must not export _initialize, must export _start + start(instance) { + this.finalizeBindings(instance); + const { _start, _initialize } = this[kInstance].exports; + validateFunction(_start, 'instance.exports._start'); + validateUndefined(_initialize, 'instance.exports._initialize'); + let ret; + try { + ret = _start(); + } + catch (err) { + if (err !== kExitCode) { + throw err; + } + } + if (ret instanceof Promise) { + return ret.then(() => this[kExitCode], (err) => { + if (err !== kExitCode) { + throw err; + } + return this[kExitCode]; + }); + } + return this[kExitCode]; + } + // Must not export _start, may optionally export _initialize + initialize(instance) { + this.finalizeBindings(instance); + const { _start, _initialize } = this[kInstance].exports; + validateUndefined(_start, 'instance.exports._start'); + if (_initialize !== undefined) { + validateFunction(_initialize, 'instance.exports._initialize'); + return _initialize(); + } + } + getImportObject() { + return { [this[kBindingName]]: this.wasiImport }; + } +} +function wasiReturnOnProcExit(rval) { + this[kExitCode] = rval; + // eslint-disable-next-line @typescript-eslint/no-throw-literal + throw kExitCode; +} +/** @public */ +async function createAsyncWASI(options = kEmptyObject) { + const _this = Object.create(WASI.prototype); + const { args, env, preopens, stdio, _WASI } = validateOptions.call(_this, options); + if (options.asyncify !== undefined) { + validateObject(options.asyncify, 'options.asyncify'); + validateFunction(options.asyncify.wrapImportFunction, 'options.asyncify.wrapImportFunction'); + } + const wrap = await _WASI.createAsync(args, env, preopens, stdio, options.fs, options.print, options.printErr, options.asyncify); + const setMemory = wrap._setMemory; + delete wrap._setMemory; + initWASI.call(_this, setMemory, wrap); + if (options.returnOnExit) { + wrap.proc_exit = wasiReturnOnProcExit.bind(_this); + } + return _this; +} + +export { Asyncify, Memory, WASI, WebAssemblyMemory, asyncifyLoad, asyncifyLoadSync, createAsyncWASI, extendMemory, load, loadSync, wrapAsyncExport, wrapAsyncImport, wrapExports }; diff --git a/dg-ui/node_modules/@tailwindcss/oxide-wasm32-wasi/node_modules/@tybys/wasm-util/dist/wasm-util.esm.min.js b/dg-ui/node_modules/@tailwindcss/oxide-wasm32-wasi/node_modules/@tybys/wasm-util/dist/wasm-util.esm.min.js new file mode 100644 index 0000000..a9d7d86 --- /dev/null +++ b/dg-ui/node_modules/@tailwindcss/oxide-wasm32-wasi/node_modules/@tybys/wasm-util/dist/wasm-util.esm.min.js @@ -0,0 +1 @@ +const t="undefined"!=typeof WebAssembly?WebAssembly:"undefined"!=typeof WXWebAssembly?WXWebAssembly:void 0;if(!t)throw new Error("WebAssembly is not supported in this environment");function e(t,e){if(null===t||"object"!=typeof t)throw new TypeError(`${e} must be an object. Received ${null===t?"null":typeof t}`)}function n(t,e){if("string"!=typeof t)throw new TypeError(`${e} must be a string. Received ${null===t?"null":typeof t}`)}function r(t,e){if("function"!=typeof t)throw new TypeError(`${e} must be a function. Received ${null===t?"null":typeof t}`)}function i(t,e){if(void 0!==t)throw new TypeError(`${e} must be undefined. Received ${null===t?"null":typeof t}`)}function s(t){return!(!t||"object"!=typeof t&&"function"!=typeof t||"function"!=typeof t.then)}function o(t,e){const n=Object.create(null);return Object.keys(t).forEach((r=>{const i=t[r];Object.defineProperty(n,r,{enumerable:!0,value:e(i,r)})})),n}function a(t,e,n){return"function"==typeof SharedArrayBuffer&&t.buffer instanceof SharedArrayBuffer||"[object SharedArrayBuffer]"===Object.prototype.toString.call(t.buffer.constructor)?t.slice(e,n):t.subarray(e,n)}const c=["asyncify_get_state","asyncify_start_rewind","asyncify_start_unwind","asyncify_stop_rewind","asyncify_stop_unwind"];function u(t,e,n,r){if("function"!=typeof t.exports[r]||n<=0)return{wasm64:e,dataPtr:16,start:e?32:24,end:1024};const i=t.exports[r],s=e?Number(i(BigInt(16)+BigInt(n))):i(8+n);if(0===s)throw new Error("Allocate asyncify data failed");return e?{wasm64:e,dataPtr:s,start:s+16,end:s+16+n}:{wasm64:e,dataPtr:s,start:s+8,end:s+8+n}}class f{constructor(){this.value=void 0,this.exports=void 0,this.dataPtr=0}init(e,n,r){var i,s;if(this.exports)throw new Error("Asyncify has been initialized");if(!(e instanceof t.Memory))throw new TypeError("Require WebAssembly.Memory object");const o=n.exports;for(let t=0;t{const r=t[n],i={};Object.keys(r).forEach((t=>{const e=r[t];i[t]="function"==typeof e?this.wrapImportFunction(e):e})),e[n]=i})),e}wrapExportFunction(t){const e=this;return async function(){e.assertState();let n=t.apply(this,arguments);for(;1===e.exports.asyncify_get_state();)e.exports.asyncify_stop_unwind(),e.value=await e.value,e.assertState(),e.exports.asyncify_start_rewind(e.dataPtr),n=t.call(this);return e.assertState(),n}}wrapExports(t,e){return o(t,((t,n)=>{let r=-1!==c.indexOf(n)||"function"!=typeof t;return Array.isArray(e)&&(r=r||-1===e.indexOf(n)),r?t:this.wrapExportFunction(t)}))}}function h(t){if(t&&"object"!=typeof t)throw new TypeError("imports must be an object or undefined")}function d(e,n){return"undefined"!=typeof wx&&"undefined"!=typeof __wxConfig?t.instantiate(e,n):fetch(e).then((t=>t.arrayBuffer())).then((e=>t.instantiate(e,n)))}function g(e,n){let r;if(h(n),n=null!=n?n:{},e instanceof ArrayBuffer||ArrayBuffer.isView(e))return t.instantiate(e,n);if(e instanceof t.Module)return t.instantiate(e,n).then((t=>({instance:t,module:e})));if("string"!=typeof e&&!(e instanceof URL))throw new TypeError("Invalid source");if("function"==typeof t.instantiateStreaming){let i;try{i=fetch(e),r=t.instantiateStreaming(i,n).catch((()=>d(e,n)))}catch(t){r=d(e,n)}}else r=d(e,n);return r}function l(t,e,n){h(n),n=null!=n?n:{};const r=new f;return g(e,n=r.wrapImports(n)).then((e=>{var i;const s=e.instance.exports.memory||(null===(i=n.env)||void 0===i?void 0:i.memory);return{module:e.module,instance:r.init(s,e.instance,t)}}))}function _(e,n){let r;if(h(n),n=null!=n?n:{},e instanceof ArrayBuffer||ArrayBuffer.isView(e))r=new t.Module(e);else{if(!(e instanceof WebAssembly.Module))throw new TypeError("Invalid source");r=e}return{instance:new t.Instance(r,n),module:r}}function p(t,e,n){var r;h(n),n=null!=n?n:{};const i=new f,s=_(e,n=i.wrapImports(n)),o=s.instance.exports.memory||(null===(r=n.env)||void 0===r?void 0:r.memory);return{module:s.module,instance:i.init(o,s.instance,t)}}const y=46,E=47,m=92,I=58,b=65,A=90,T=97,w=122;function B(t){return t===E||t===m}function N(t){return t>=b&&t<=A||t>=T&&t<=w}const S="undefined"!=typeof process&&"win32"===process.platform;function P(t){return t===E}function D(t,e,n,r){let i="",s=0,o=-1,a=0,c=0;for(let u=0;u<=t.length;++u){if(u2){const t=i.indexOf(n);-1===t?(i="",s=0):(i=i.slice(0,t),s=i.length-1-i.indexOf(n)),o=u,a=0;continue}if(0!==i.length){i="",s=0,o=u,a=0;continue}}e&&(i+=i.length>0?`${n}..`:"..",s=2)}else i.length>0?i+=`${n}${t.slice(o+1,u)}`:i=t.slice(o+1,u),s=u-o-1;o=u,a=0}else c===y&&-1!==a?++a:a=-1}return i}function F(...t){if(S)return function(t){let e="",r="",i=!1;for(let s=t.length-1;s>=-1;s--){let o;if(s>=0){if(o=t[s],n(o,"path"),0===o.length)continue}else if(0===e.length)o="undefined"!=typeof process&&"function"==typeof process.cwd?process.cwd():"";else{const t=`=${e}`,n="undefined"!=typeof process?process.env:void 0;o=n&&"string"==typeof n[t]?n[t]:"undefined"!=typeof process&&"function"==typeof process.cwd?process.cwd():"",(void 0===o||o.slice(0,2).toLowerCase()!==e.toLowerCase()&&o.charCodeAt(2)===m)&&(o=`${e}\\`)}const a=o.length;let c=0,u="",f=!1;const h=o.charCodeAt(0);if(1===a)B(h)&&(c=1,f=!0);else if(B(h))if(f=!0,B(o.charCodeAt(1))){let t=2,e=t;for(;t2&&B(o.charCodeAt(2))&&(f=!0,c=3));if(u.length>0)if(e.length>0){if(u.toLowerCase()!==e.toLowerCase())continue}else e=u;if(i){if(e.length>0)break}else if(r=`${o.slice(c)}\\${r}`,i=f,f&&e.length>0)break}return r=D(r,!i,"\\",B),e+(i?"\\":"")+r||"."}(t);let e="",r=!1;for(let i=t.length-1;i>=-1&&!r;i--){const s=i>=0?t[i]:"/";n(s,"path"),0!==s.length&&(e=`${s}/${e}`,r=s.charCodeAt(0)===E)}return e=D(e,!r,"/",P),r?`/${e}`:e.length>0?e:"."}const v={FD_DATASYNC:BigInt(1)<=0)n=e;else for(let e=0;e"),this.insertStdio(t.out,1,""),this.insertStdio(t.err,2,"")}insertStdio(t,e,n){const{base:r,inheriting:i}=G(this.stdio,t,2,2),s=this.insert(t,n,n,2,r,i,0);if(s.id!==e)throw new U(`id: ${s.id} !== expected: ${e}`,8);return s}insert(t,e,n,r,i,s,o){var a,c;let u,f=-1;if(this.used>=this.size){const t=2*this.size;this.fds.length=t,f=this.size,this.size=t}else for(let t=0;t"===e?new Z(null!==(c=this.printErr)&&void 0!==c?c:console.error,f,t,e,n,r,i,s,o):new V(f,t,e,n,r,i,s,o),this.fds[f]=u,this.used++,u}get(t,e,n){if(t>=this.size)throw new U("Invalid fd",8);const r=this.fds[t];if(!r||r.id!==t)throw new U("Bad file descriptor",8);if((~r.rightsBase&e)!==BigInt(0)||(~r.rightsInheriting&n)!==BigInt(0))throw new U("Capabilities insufficient",76);return r}remove(t){if(t>=this.size)throw new U("Invalid fd",8);const e=this.fds[t];if(!e||e.id!==t)throw new U("Bad file descriptor",8);this.fds[t]=void 0,this.used--}}class J extends Q{constructor(t){super(t),this.fs=t.fs}getFileTypeByFd(t){return q(this.fs.fstatSync(t,{bigint:!0}))}insertPreopen(t,e,n){const r=this.getFileTypeByFd(t);if(3!==r)throw new U(`Preopen not dir: ["${e}", "${n}"]`,54);const i=G(this.stdio,t,0,r);return this.insert(t,e,n,r,i.base,i.inheriting,1)}renumber(t,e){if(t===e)return;if(t>=this.size||e>=this.size)throw new U("Invalid fd",8);const n=this.fds[t],r=this.fds[e];if(!n||!r||n.id!==t||r.id!==e)throw new U("Invalid fd",8);this.fs.closeSync(n.fd),this.fds[t]=this.fds[e],this.fds[t].id=t,this.fds[e]=void 0,this.used--}}class tt extends Q{constructor(t){super(t)}async getFileTypeByFd(t){return q(await t.stat({bigint:!0}))}async insertPreopen(t,e,n){const r=await this.getFileTypeByFd(t);if(3!==r)throw new U(`Preopen not dir: ["${e}", "${n}"]`,54);const i=G(this.stdio,t.fd,0,r);return this.insert(t,e,n,r,i.base,i.inheriting,1)}async renumber(t,e){if(t===e)return;if(t>=this.size||e>=this.size)throw new U("Invalid fd",8);const n=this.fds[t],r=this.fds[e];if(!n||!r||n.id!==t||r.id!==e)throw new U("Invalid fd",8);await n.fd.close(),this.fds[t]=this.fds[e],this.fds[t].id=t,this.fds[e]=void 0,this.used--}}const et=function(){return t.Memory}();class nt extends et{constructor(t){super(t)}get HEAP8(){return new Int8Array(super.buffer)}get HEAPU8(){return new Uint8Array(super.buffer)}get HEAP16(){return new Int16Array(super.buffer)}get HEAPU16(){return new Uint16Array(super.buffer)}get HEAP32(){return new Int32Array(super.buffer)}get HEAPU32(){return new Uint32Array(super.buffer)}get HEAP64(){return new BigInt64Array(super.buffer)}get HEAPU64(){return new BigUint64Array(super.buffer)}get HEAPF32(){return new Float32Array(super.buffer)}get HEAPF64(){return new Float64Array(super.buffer)}get view(){return new DataView(super.buffer)}}function rt(e){return Object.getPrototypeOf(e)===t.Memory.prototype&&Object.setPrototypeOf(e,nt.prototype),e}function it(){const e=t.Function;if("function"!=typeof e)throw new Error('WebAssembly.Function is not supported in this environment. If you are using V8 based browser like Chrome, try to specify --js-flags="--wasm-staging --experimental-wasm-stack-switching"');return e}function st(t,e,n){const r=it();if("function"!=typeof t)throw new TypeError("Function required");const i=e.slice(0);return i.unshift("externref"),new r({parameters:i,results:n},t,{suspending:"first"})}function ot(t){const e=it();if("function"!=typeof t)throw new TypeError("Function required");return new e({parameters:[...e.type(t).parameters.slice(1)],results:["externref"]},t,{promising:"first"})}function at(t,e){return o(t,((t,n)=>{let r="function"!=typeof t;return Array.isArray(e)&&(r=r||-1===e.indexOf(n)),r?t:ot(t)}))}const ct="undefined"!=typeof process&&"win32"===process.platform;function ut(t){let e=3&t;return 0!=(64&t)&&(e|=256),0!=(128&t)&&(e|=1024),0!=(512&t)&&(e|=512),0!=(1024&t)&&(e|=8),e}function ft(t,e){if(0===t.length||0===e.length)return 0;let n=0,r=e.length-n;for(let i=0;in.byteLength&&(t.grow(0),n=t.buffer)}(n,e),n}function _t(t){const e=gt.get(t);if(!e)throw new Error("filesystem is unavailable");return e}function pt(t){if(t instanceof U)return t.errno;switch(t.code){case"ENOENT":return 44;case"EBADF":return 8;case"EINVAL":return 28;case"EPERM":return 63;case"EPROTO":return 65;case"EEXIST":return 20;case"ENOTDIR":return 54;case"EMFILE":return 33;case"EACCES":return 2;case"EISDIR":return 31;case"ENOTEMPTY":return 55;case"ENOSYS":return 52}throw t}function yt(t,e){return Object.defineProperty(e,"name",{value:t}),e}function Et(t,e,n){let r;try{r=t.apply(e,n)}catch(t){return pt(t)}return s(r)?r.then((t=>t),pt):r}function mt(t,e,n){let r=!1;const i=(()=>{try{return}catch(t){return}})();return"string"==typeof i&&i.split(",").includes("wasi")&&(r=!0),yt(e,r?function(){const r=Array.prototype.slice.call(arguments);let i=[`${e}(${Array.from({length:arguments.length}).map((()=>"%d")).join(", ")})`];return i=i.concat(r),console.debug.apply(console,i),Et(n,t,r)}:function(){return Et(n,t,arguments)})}function It(t,e,n,r){let i=F(e.realPath,n);if(1==(1&r))try{i=t.readlinkSync(i)}catch(t){if("EINVAL"!==t.code&&"ENOENT"!==t.code)throw t}return i}async function bt(t,e,n,r){let i=F(e.realPath,n);if(1==(1&r))try{i=await t.promises.readlink(i)}catch(t){if("EINVAL"!==t.code&&"ENOENT"!==t.code)throw t}return i}const At=new TextEncoder,Tt=new TextDecoder,wt=(BigInt(1)<r.rightsBase||(n|r.rightsInheriting)>r.rightsInheriting?76:(r.rightsBase=e,r.rightsInheriting=n,0)})),this.fd_prestat_get=mt(this,"fd_prestat_get",(function(t,e){if(0===(e=Number(e)))return 28;const n=dt.get(this);let r;try{r=n.fds.get(t,BigInt(0),BigInt(0))}catch(t){if(t instanceof U)return t.errno;throw t}if(1!==r.preopen)return 28;const{view:i}=lt(this,e+8);return i.setUint32(e,0,!0),i.setUint32(e+4,At.encode(r.path).length,!0),0})),this.fd_prestat_dir_name=mt(this,"fd_prestat_dir_name",(function(t,e,n){if(e=Number(e),n=Number(n),0===e)return 28;const r=dt.get(this).fds.get(t,BigInt(0),BigInt(0));if(1!==r.preopen)return 8;const i=At.encode(r.path),s=i.length;if(s>n)return 42;const{HEAPU8:o}=lt(this,e+s);return o.set(i,e),0})),this.fd_seek=mt(this,"fd_seek",(function(t,e,n,r){if(0===(r=Number(r)))return 28;if(0===t||1===t||2===t)return 0;const i=dt.get(this).fds.get(t,v.FD_SEEK,BigInt(0)).seek(e,n),{view:s}=lt(this,r+8);return s.setBigUint64(r,i,!0),0})),this.fd_tell=mt(this,"fd_tell",(function(t,e){const n=dt.get(this).fds.get(t,v.FD_TELL,BigInt(0)),r=BigInt(n.pos),{view:i}=lt(this,Number(e)+8);return i.setBigUint64(Number(e),r,!0),0})),this.poll_oneoff=mt(this,"poll_oneoff",(function(t,e,n,r){if(t=Number(t),e=Number(e),r=Number(r),n=Number(n),n>>>=0,0===t||0===e||0===n||0===r)return 28;const{view:i}=lt(this,Math.max(t+48*n,e+32*n,r+4));i.setUint32(r,0,!0);let s,o=0,a=BigInt(0),c=BigInt(0),u=0,f=BigInt(0);const h=Array(n);for(o=0;o0){for(o=0;o!1));const t=e;i.setBigUint64(t,a,!0),i.setUint32(t+8,0,!0),i.setUint32(t+12,0,!0),i.setUint32(r,1,!0)}return 0})),this.proc_exit=mt(this,"proc_exit",(function(t){return"object"==typeof process&&null!==process&&"function"==typeof process.exit&&process.exit(t),0})),this.proc_raise=mt(this,"proc_raise",(function(t){return 52})),this.sched_yield=mt(this,"sched_yield",(function(){return 0})),this.random_get="undefined"!=typeof crypto&&"function"==typeof crypto.getRandomValues?mt(this,"random_get",(function(t,e){if(0===(t=Number(t)))return 28;e=Number(e);const{HEAPU8:n,view:r}=lt(this,t+e);if("function"==typeof SharedArrayBuffer&&n.buffer instanceof SharedArrayBuffer||"[object SharedArrayBuffer]"===Object.prototype.toString.call(n.buffer)){for(let n=t;nwt)return 28;const{HEAPU8:s,view:o}=lt(this,Math.max(e+8*Number(n),i+4)),a=dt.get(this).fds.get(t,v.FD_READ|v.FD_SEEK,BigInt(0));if(!n)return o.setUint32(i,0,!0),0;let c=0;const u=Array.from({length:Number(n)},((t,n)=>{const r=e+8*n,i=o.getInt32(r,!0),a=o.getUint32(r+4,!0);return c+=a,s.subarray(i,i+a)}));let f=0;const h=(()=>{try{return new Uint8Array(new SharedArrayBuffer(c))}catch(t){return new Uint8Array(c)}})();h._isBuffer=!0;const d=_t(this).readSync(a.fd,h,0,h.length,Number(r));return f=h?ft(u,h.subarray(0,d)):0,o.setUint32(i,f,!0),0}),(async function(t,e,n,r,i){if(e=Number(e),i=Number(i),0===e&&n||0===i||r>wt)return 28;const{HEAPU8:s,view:o}=lt(this,Math.max(e+8*Number(n),i+4)),a=dt.get(this).fds.get(t,v.FD_READ|v.FD_SEEK,BigInt(0));if(!n)return o.setUint32(i,0,!0),0;let c=0;const u=Array.from({length:Number(n)},((t,n)=>{const r=e+8*n,i=o.getInt32(r,!0),a=o.getUint32(r+4,!0);return c+=a,s.subarray(i,i+a)}));let f=0;const h=new Uint8Array(c);h._isBuffer=!0;const{bytesRead:d}=await a.fd.read(h,0,h.length,Number(r));return f=h?ft(u,h.subarray(0,d)):0,o.setUint32(i,f,!0),0}),["i32","i32","i32","i64","i32"],["i32"]),u("fd_pwrite",(function(t,e,n,r,i){if(e=Number(e),i=Number(i),0===e&&n||0===i||r>wt)return 28;const{HEAPU8:s,view:o}=lt(this,Math.max(e+8*Number(n),i+4)),a=dt.get(this).fds.get(t,v.FD_WRITE|v.FD_SEEK,BigInt(0));if(!n)return o.setUint32(i,0,!0),0;const c=Y(Array.from({length:Number(n)},((t,n)=>{const r=e+8*n,i=o.getInt32(r,!0),a=o.getUint32(r+4,!0);return s.subarray(i,i+a)}))),u=_t(this).writeSync(a.fd,c,0,c.length,Number(r));return o.setUint32(i,u,!0),0}),(async function(t,e,n,r,i){if(e=Number(e),i=Number(i),0===e&&n||0===i||r>wt)return 28;const{HEAPU8:s,view:o}=lt(this,Math.max(e+8*Number(n),i+4)),a=dt.get(this).fds.get(t,v.FD_WRITE|v.FD_SEEK,BigInt(0));if(!n)return o.setUint32(i,0,!0),0;const c=Y(Array.from({length:Number(n)},((t,n)=>{const r=e+8*n,i=o.getInt32(r,!0),a=o.getUint32(r+4,!0);return s.subarray(i,i+a)}))),{bytesWritten:u}=await a.fd.write(c,0,c.length,Number(r));return o.setUint32(i,u,!0),0}),["i32","i32","i32","i64","i32"],["i32"]),u("fd_read",(function(t,e,n,r){if(e=Number(e),r=Number(r),0===e&&n||0===r)return 28;const{HEAPU8:i,view:s}=lt(this,Math.max(e+8*Number(n),r+4)),o=dt.get(this).fds.get(t,v.FD_READ,BigInt(0));if(!n)return s.setUint32(r,0,!0),0;let a=0;const c=Array.from({length:Number(n)},((t,n)=>{const r=e+8*n,o=s.getInt32(r,!0),c=s.getUint32(r+4,!0);return a+=c,i.subarray(o,o+c)}));let u,f=0;if(0===t){if("undefined"==typeof window||"function"!=typeof window.prompt)return 58;u=Bt(),f=u?ft(c,u):0}else{u=(()=>{try{return new Uint8Array(new SharedArrayBuffer(a))}catch(t){return new Uint8Array(a)}})(),u._isBuffer=!0;const t=_t(this).readSync(o.fd,u,0,u.length,Number(o.pos));f=u?ft(c,u.subarray(0,t)):0,o.pos+=BigInt(f)}return s.setUint32(r,f,!0),0}),(async function(t,e,n,r){if(e=Number(e),r=Number(r),0===e&&n||0===r)return 28;const{HEAPU8:i,view:s}=lt(this,Math.max(e+8*Number(n),r+4)),o=dt.get(this).fds.get(t,v.FD_READ,BigInt(0));if(!n)return s.setUint32(r,0,!0),0;let a=0;const c=Array.from({length:Number(n)},((t,n)=>{const r=e+8*n,o=s.getInt32(r,!0),c=s.getUint32(r+4,!0);return a+=c,i.subarray(o,o+c)}));let u,f=0;if(0===t){if("undefined"==typeof window||"function"!=typeof window.prompt)return 58;u=Bt(),f=u?ft(c,u):0}else{u=new Uint8Array(a),u._isBuffer=!0;const{bytesRead:t}=await o.fd.read(u,0,u.length,Number(o.pos));f=u?ft(c,u.subarray(0,t)):0,o.pos+=BigInt(f)}return s.setUint32(r,f,!0),0}),["i32","i32","i32","i32"],["i32"]),u("fd_readdir",(function(t,e,n,r,i){if(e=Number(e),n=Number(n),i=Number(i),0===e||0===i)return 0;const s=dt.get(this).fds.get(t,v.FD_READDIR,BigInt(0)),o=_t(this),a=o.readdirSync(s.realPath,{withFileTypes:!0}),{HEAPU8:c,view:u}=lt(this,Math.max(e+n,i+4));let f=0;for(let t=Number(r);t{const r=e+8*n,o=s.getInt32(r,!0),a=s.getUint32(r+4,!0);return i.subarray(o,o+a)})));let c;if(1===t||2===t)c=o.write(a);else{c=_t(this).writeSync(o.fd,a,0,a.length,Number(o.pos)),o.pos+=BigInt(c)}return s.setUint32(r,c,!0),0}),(async function(t,e,n,r){if(e=Number(e),r=Number(r),0===e&&n||0===r)return 28;const{HEAPU8:i,view:s}=lt(this,Math.max(e+8*Number(n),r+4)),o=dt.get(this).fds.get(t,v.FD_WRITE,BigInt(0));if(!n)return s.setUint32(r,0,!0),0;const a=Y(Array.from({length:Number(n)},((t,n)=>{const r=e+8*n,o=s.getInt32(r,!0),a=s.getUint32(r+4,!0);return i.subarray(o,o+a)})));let c;return 1===t||2===t?c=o.write(a):(c=await(await o.fd.write(a,0,a.length,Number(o.pos))).bytesWritten,o.pos+=BigInt(c)),s.setUint32(r,c,!0),0}),["i32","i32","i32","i32"],["i32"]),u("path_create_directory",(function(t,e,n){if(e=Number(e),n=Number(n),0===e)return 28;const{HEAPU8:r}=lt(this,e+n),i=dt.get(this).fds.get(t,v.PATH_CREATE_DIRECTORY,BigInt(0));let s=Tt.decode(a(r,e,e+n));s=F(i.realPath,s);return _t(this).mkdirSync(s),0}),(async function(t,e,n){if(e=Number(e),n=Number(n),0===e)return 28;const{HEAPU8:r}=lt(this,e+n),i=dt.get(this).fds.get(t,v.PATH_CREATE_DIRECTORY,BigInt(0));let s=Tt.decode(a(r,e,e+n));s=F(i.realPath,s);const o=_t(this);return await o.promises.mkdir(s),0}),["i32","i32","i32"],["i32"]),u("path_filestat_get",(function(t,e,n,r,i){if(n=Number(n),r=Number(r),i=Number(i),0===n||0===i)return 28;const{HEAPU8:s,view:o}=lt(this,Math.max(n+r,i+64)),c=dt.get(this).fds.get(t,v.PATH_FILESTAT_GET,BigInt(0));let u=Tt.decode(a(s,n,n+r));const f=_t(this);let h;return u=F(c.realPath,u),h=1==(1&e)?f.statSync(u,{bigint:!0}):f.lstatSync(u,{bigint:!0}),X(o,i,h),0}),(async function(t,e,n,r,i){if(n=Number(n),r=Number(r),i=Number(i),0===n||0===i)return 28;const{HEAPU8:s,view:o}=lt(this,Math.max(n+r,i+64)),c=dt.get(this).fds.get(t,v.PATH_FILESTAT_GET,BigInt(0));let u=Tt.decode(a(s,n,n+r));const f=_t(this);let h;return u=F(c.realPath,u),h=1==(1&e)?await f.promises.stat(u,{bigint:!0}):await f.promises.lstat(u,{bigint:!0}),X(o,i,h),0}),["i32","i32","i32","i32","i32"],["i32"]),u("path_filestat_set_times",(function(t,e,n,r,i,s,o){if(n=Number(n),r=Number(r),0===n)return 28;const{HEAPU8:c}=lt(this,n+r),u=dt.get(this).fds.get(t,v.PATH_FILESTAT_SET_TIMES,BigInt(0));if(Nt(o))return 28;const f=_t(this),h=It(f,u,Tt.decode(a(c,n,n+r)),e);return 2==(2&o)&&(i=BigInt(1e6*Date.now())),8==(8&o)&&(s=BigInt(1e6*Date.now())),f.utimesSync(h,Number(i),Number(s)),0}),(async function(t,e,n,r,i,s,o){if(n=Number(n),r=Number(r),0===n)return 28;const{HEAPU8:c}=lt(this,n+r),u=dt.get(this).fds.get(t,v.PATH_FILESTAT_SET_TIMES,BigInt(0));if(Nt(o))return 28;const f=_t(this),h=await bt(f,u,Tt.decode(a(c,n,n+r)),e);return 2==(2&o)&&(i=BigInt(1e6*Date.now())),8==(8&o)&&(s=BigInt(1e6*Date.now())),await f.promises.utimes(h,Number(i),Number(s)),0}),["i32","i32","i32","i32","i64","i64","i32"],["i32"]),u("path_link",(function(t,e,n,r,i,s,o){if(n=Number(n),r=Number(r),s=Number(s),o=Number(o),0===n||0===s)return 28;const c=dt.get(this);let u,f;t===i?u=f=c.fds.get(t,v.PATH_LINK_SOURCE|v.PATH_LINK_TARGET,BigInt(0)):(u=c.fds.get(t,v.PATH_LINK_SOURCE,BigInt(0)),f=c.fds.get(i,v.PATH_LINK_TARGET,BigInt(0)));const{HEAPU8:h}=lt(this,Math.max(n+r,s+o)),d=_t(this),g=It(d,u,Tt.decode(a(h,n,n+r)),e),l=F(f.realPath,Tt.decode(a(h,s,s+o)));return d.linkSync(g,l),0}),(async function(t,e,n,r,i,s,o){if(n=Number(n),r=Number(r),s=Number(s),o=Number(o),0===n||0===s)return 28;const c=dt.get(this);let u,f;t===i?u=f=c.fds.get(t,v.PATH_LINK_SOURCE|v.PATH_LINK_TARGET,BigInt(0)):(u=c.fds.get(t,v.PATH_LINK_SOURCE,BigInt(0)),f=c.fds.get(i,v.PATH_LINK_TARGET,BigInt(0)));const{HEAPU8:h}=lt(this,Math.max(n+r,s+o)),d=_t(this),g=await bt(d,u,Tt.decode(a(h,n,n+r)),e),l=F(f.realPath,Tt.decode(a(h,s,s+o)));return await d.promises.link(g,l),0}),["i32","i32","i32","i32","i32","i32","i32"],["i32"]),u("path_open",(function(t,e,n,r,i,s,o,c,u){if(n=Number(n),u=Number(u),0===n||0===u)return 28;r=Number(r),s=BigInt(s),o=BigInt(o);const{flags:f,needed_base:d,needed_inheriting:g}=h(i,s,o,c),l=dt.get(this),_=l.fds.get(t,d,g),p=lt(this,Math.max(n+r,u+4)),y=p.HEAPU8,E=Tt.decode(a(y,n,n+r)),m=_t(this),I=It(m,_,E,e),b=m.openSync(I,ct?ut(f):f,438),A=l.fds.getFileTypeByFd(b);if(3!==A&&(0!=(2&i)||I.endsWith("/")))return 54;const{base:T,inheriting:w}=G(l.fds.stdio,b,f,A),B=l.fds.insert(b,I,I,A,s&T,o&w,0),N=m.fstatSync(b,{bigint:!0});N.isFile()&&(B.size=N.size,0!=(1024&f)&&(B.pos=N.size));return p.view.setInt32(u,B.id,!0),0}),(async function(t,e,n,r,i,s,o,c,u){if(n=Number(n),u=Number(u),0===n||0===u)return 28;r=Number(r),s=BigInt(s),o=BigInt(o);const{flags:f,needed_base:d,needed_inheriting:g}=h(i,s,o,c),l=dt.get(this),_=l.fds.get(t,d,g),p=lt(this,Math.max(n+r,u+4)),y=p.HEAPU8,E=Tt.decode(a(y,n,n+r)),m=_t(this),I=await bt(m,_,E,e),b=await m.promises.open(I,ct?ut(f):f,438),A=await l.fds.getFileTypeByFd(b);if(0!=(2&i)&&3!==A)return 54;const{base:T,inheriting:w}=G(l.fds.stdio,b.fd,f,A),B=l.fds.insert(b,I,I,A,s&T,o&w,0),N=await b.stat({bigint:!0});N.isFile()&&(B.size=N.size,0!=(1024&f)&&(B.pos=N.size));return p.view.setInt32(u,B.id,!0),0}),["i32","i32","i32","i32","i32","i64","i64","i32","i32"],["i32"]),u("path_readlink",(function(t,e,n,r,i,s){if(e=Number(e),n=Number(n),r=Number(r),i=Number(i),s=Number(s),0===e||0===r||0===s)return 28;const{HEAPU8:o,view:c}=lt(this,Math.max(e+n,r+i,s+4)),u=dt.get(this).fds.get(t,v.PATH_READLINK,BigInt(0));let f=Tt.decode(a(o,e,e+n));f=F(u.realPath,f);const h=_t(this).readlinkSync(f),d=At.encode(h),g=Math.min(d.length,i);return g>=i?42:(o.set(d.subarray(0,g),r),o[r+g]=0,c.setUint32(s,g,!0),0)}),(async function(t,e,n,r,i,s){if(e=Number(e),n=Number(n),r=Number(r),i=Number(i),s=Number(s),0===e||0===r||0===s)return 28;const{HEAPU8:o,view:c}=lt(this,Math.max(e+n,r+i,s+4)),u=dt.get(this).fds.get(t,v.PATH_READLINK,BigInt(0));let f=Tt.decode(a(o,e,e+n));f=F(u.realPath,f);const h=_t(this),d=await h.promises.readlink(f),g=At.encode(d),l=Math.min(g.length,i);return l>=i?42:(o.set(g.subarray(0,l),r),o[r+l]=0,c.setUint32(s,l,!0),0)}),["i32","i32","i32","i32","i32","i32"],["i32"]),u("path_remove_directory",(function(t,e,n){if(e=Number(e),n=Number(n),0===e)return 28;const{HEAPU8:r}=lt(this,e+n),i=dt.get(this).fds.get(t,v.PATH_REMOVE_DIRECTORY,BigInt(0));let s=Tt.decode(a(r,e,e+n));s=F(i.realPath,s);return _t(this).rmdirSync(s),0}),(async function(t,e,n){if(e=Number(e),n=Number(n),0===e)return 28;const{HEAPU8:r}=lt(this,e+n),i=dt.get(this).fds.get(t,v.PATH_REMOVE_DIRECTORY,BigInt(0));let s=Tt.decode(a(r,e,e+n));s=F(i.realPath,s);const o=_t(this);return await o.promises.rmdir(s),0}),["i32","i32","i32"],["i32"]),u("path_rename",(function(t,e,n,r,i,s){if(e=Number(e),n=Number(n),i=Number(i),s=Number(s),0===e||0===i)return 28;const o=dt.get(this);let c,u;t===r?c=u=o.fds.get(t,v.PATH_RENAME_SOURCE|v.PATH_RENAME_TARGET,BigInt(0)):(c=o.fds.get(t,v.PATH_RENAME_SOURCE,BigInt(0)),u=o.fds.get(r,v.PATH_RENAME_TARGET,BigInt(0)));const{HEAPU8:f}=lt(this,Math.max(e+n,i+s)),h=F(c.realPath,Tt.decode(a(f,e,e+n))),d=F(u.realPath,Tt.decode(a(f,i,i+s)));return _t(this).renameSync(h,d),0}),(async function(t,e,n,r,i,s){if(e=Number(e),n=Number(n),i=Number(i),s=Number(s),0===e||0===i)return 28;const o=dt.get(this);let c,u;t===r?c=u=o.fds.get(t,v.PATH_RENAME_SOURCE|v.PATH_RENAME_TARGET,BigInt(0)):(c=o.fds.get(t,v.PATH_RENAME_SOURCE,BigInt(0)),u=o.fds.get(r,v.PATH_RENAME_TARGET,BigInt(0)));const{HEAPU8:f}=lt(this,Math.max(e+n,i+s)),h=F(c.realPath,Tt.decode(a(f,e,e+n))),d=F(u.realPath,Tt.decode(a(f,i,i+s))),g=_t(this);return await g.promises.rename(h,d),0}),["i32","i32","i32","i32","i32","i32"],["i32"]),u("path_symlink",(function(t,e,n,r,i){if(t=Number(t),e=Number(e),r=Number(r),i=Number(i),0===t||0===r)return 28;const{HEAPU8:s}=lt(this,Math.max(t+e,r+i)),o=dt.get(this).fds.get(n,v.PATH_SYMLINK,BigInt(0)),c=Tt.decode(a(s,t,t+e));if(c.length>0&&"/"===c[0])return 63;let u=Tt.decode(a(s,r,r+i));u=F(o.realPath,u);return _t(this).symlinkSync(c,u),0}),(async function(t,e,n,r,i){if(t=Number(t),e=Number(e),r=Number(r),i=Number(i),0===t||0===r)return 28;const{HEAPU8:s}=lt(this,Math.max(t+e,r+i)),o=dt.get(this).fds.get(n,v.PATH_SYMLINK,BigInt(0)),c=Tt.decode(a(s,t,t+e));let u=Tt.decode(a(s,r,r+i));u=F(o.realPath,u);const f=_t(this);return await f.promises.symlink(c,u),0}),["i32","i32","i32","i32","i32"],["i32"]),u("path_unlink_file",(function(t,e,n){if(e=Number(e),n=Number(n),0===e)return 28;const{HEAPU8:r}=lt(this,e+n),i=dt.get(this).fds.get(t,v.PATH_UNLINK_FILE,BigInt(0));let s=Tt.decode(a(r,e,e+n));s=F(i.realPath,s);return _t(this).unlinkSync(s),0}),(async function(t,e,n){if(e=Number(e),n=Number(n),0===e)return 28;const{HEAPU8:r}=lt(this,e+n),i=dt.get(this).fds.get(t,v.PATH_UNLINK_FILE,BigInt(0));let s=Tt.decode(a(r,e,e+n));s=F(i.realPath,s);const o=_t(this);return await o.promises.unlink(s),0}),["i32","i32","i32"],["i32"]),this._setMemory=function(e){if(!(e instanceof t.Memory))throw new TypeError('"instance.exports.memory" property must be a WebAssembly.Memory');ht.set(c,rt(e))}}static createSync(t,e,n,r,i,s,o){const a=new J({size:3,in:r[0],out:r[1],err:r[2],fs:i,print:s,printErr:o}),c=new St(t,e,a,!1,i);if(n.length>0)for(let t=0;t0)for(let t=0;t{void 0!==e&&a.push(`${t}=${e}`)})));const c=[];if(void 0!==t.preopens&&(e(t.preopens,"options.preopens"),Object.entries(t.preopens).forEach((({0:t,1:e})=>c.push({mappedPath:String(t),realPath:String(e)})))),c.length>0){if(void 0===t.fs)throw new Error("filesystem is disabled, can not preopen directory");try{e(t.fs,"options.fs")}catch(t){throw new TypeError("Node.js fs like implementation is not provided")}}void 0!==t.print&&r(t.print,"options.print"),void 0!==t.printErr&&r(t.printErr,"options.printErr"),void 0!==t.returnOnExit&&function(t,e){if("boolean"!=typeof t)throw new TypeError(`${e} must be a boolean. Received ${null===t?"null":typeof t}`)}(t.returnOnExit,"options.returnOnExit");return{args:o,env:a,preopens:c,stdio:[0,1,2],_WASI:s}}function Ht(t,e){this[Ft]=t,this.wasiImport=e,this[vt]=!1,this[Dt]=0,this[Ut]=void 0}class Ot{constructor(t=Pt){const{args:e,env:n,preopens:r,stdio:i,_WASI:s}=Lt.call(this,t),o=s.createSync(e,n,r,i,t.fs,t.print,t.printErr),a=o._setMemory;delete o._setMemory,Ht.call(this,a,o),t.returnOnExit&&(o.proc_exit=xt.bind(this))}finalizeBindings(t,n){var r,{memory:i=(null===(r=null==t?void 0:t.exports)||void 0===r?void 0:r.memory)}=void 0===n?{}:n;if(this[vt])throw new Error("WASI instance has already started");e(t,"instance"),e(t.exports,"instance.exports"),this[Ft](i),this[Ut]=t,this[vt]=!0}start(t){this.finalizeBindings(t);const{_start:e,_initialize:n}=this[Ut].exports;let s;r(e,"instance.exports._start"),i(n,"instance.exports._initialize");try{s=e()}catch(t){if(t!==Dt)throw t}return s instanceof Promise?s.then((()=>this[Dt]),(t=>{if(t!==Dt)throw t;return this[Dt]})):this[Dt]}initialize(t){this.finalizeBindings(t);const{_start:e,_initialize:n}=this[Ut].exports;if(i(e,"instance.exports._start"),void 0!==n)return r(n,"instance.exports._initialize"),n()}getImportObject(){return{[this[Rt]]:this.wasiImport}}}function xt(t){throw this[Dt]=t,Dt}async function Mt(t=Pt){const n=Object.create(Ot.prototype),{args:i,env:s,preopens:o,stdio:a,_WASI:c}=Lt.call(n,t);void 0!==t.asyncify&&(e(t.asyncify,"options.asyncify"),r(t.asyncify.wrapImportFunction,"options.asyncify.wrapImportFunction"));const u=await c.createAsync(i,s,o,a,t.fs,t.print,t.printErr,t.asyncify),f=u._setMemory;return delete u._setMemory,Ht.call(n,f,u),t.returnOnExit&&(u.proc_exit=xt.bind(n)),n}export{f as Asyncify,nt as Memory,Ot as WASI,et as WebAssemblyMemory,l as asyncifyLoad,p as asyncifyLoadSync,Mt as createAsyncWASI,rt as extendMemory,g as load,_ as loadSync,ot as wrapAsyncExport,st as wrapAsyncImport,at as wrapExports}; diff --git a/dg-ui/node_modules/@tailwindcss/oxide-wasm32-wasi/node_modules/@tybys/wasm-util/dist/wasm-util.js b/dg-ui/node_modules/@tailwindcss/oxide-wasm32-wasi/node_modules/@tybys/wasm-util/dist/wasm-util.js new file mode 100644 index 0000000..8a1430d --- /dev/null +++ b/dg-ui/node_modules/@tailwindcss/oxide-wasm32-wasi/node_modules/@tybys/wasm-util/dist/wasm-util.js @@ -0,0 +1,2954 @@ +(function (global, factory) { + typeof exports === 'object' && typeof module !== 'undefined' ? factory(exports) : + typeof define === 'function' && define.amd ? define(['exports'], factory) : + (global = typeof globalThis !== 'undefined' ? globalThis : global || self, factory(global.wasmUtil = {})); +})(this, (function (exports) { 'use strict'; + + const _WebAssembly = typeof WebAssembly !== 'undefined' + ? WebAssembly + : typeof WXWebAssembly !== 'undefined' + ? WXWebAssembly + : undefined; + if (!_WebAssembly) { + throw new Error('WebAssembly is not supported in this environment'); + } + + /* eslint-disable spaced-comment */ + + function validateObject(value, name) { + if (value === null || typeof value !== 'object') { + throw new TypeError(`${name} must be an object. Received ${value === null ? 'null' : typeof value}`); + } + } + function validateArray(value, name) { + if (!Array.isArray(value)) { + throw new TypeError(`${name} must be an array. Received ${value === null ? 'null' : typeof value}`); + } + } + function validateBoolean(value, name) { + if (typeof value !== 'boolean') { + throw new TypeError(`${name} must be a boolean. Received ${value === null ? 'null' : typeof value}`); + } + } + function validateString(value, name) { + if (typeof value !== 'string') { + throw new TypeError(`${name} must be a string. Received ${value === null ? 'null' : typeof value}`); + } + } + function validateFunction(value, name) { + if (typeof value !== 'function') { + throw new TypeError(`${name} must be a function. Received ${value === null ? 'null' : typeof value}`); + } + } + function validateUndefined(value, name) { + if (value !== undefined) { + throw new TypeError(`${name} must be undefined. Received ${value === null ? 'null' : typeof value}`); + } + } + function isPromiseLike(obj) { + return !!(obj && (typeof obj === 'object' || typeof obj === 'function') && typeof obj.then === 'function'); + } + function wrapInstanceExports(exports, mapFn) { + const newExports = Object.create(null); + Object.keys(exports).forEach(name => { + const exportValue = exports[name]; + Object.defineProperty(newExports, name, { + enumerable: true, + value: mapFn(exportValue, name) + }); + }); + return newExports; + } + function sleepBreakIf(delay, breakIf) { + const start = Date.now(); + const end = start + delay; + let ret = false; + while (Date.now() < end) { + if (breakIf()) { + ret = true; + break; + } + } + return ret; + } + function unsharedSlice(view, start, end) { + return ((typeof SharedArrayBuffer === 'function' && view.buffer instanceof SharedArrayBuffer) || (Object.prototype.toString.call(view.buffer.constructor) === '[object SharedArrayBuffer]')) + ? view.slice(start, end) + : view.subarray(start, end); + } + + const ignoreNames = [ + 'asyncify_get_state', + 'asyncify_start_rewind', + 'asyncify_start_unwind', + 'asyncify_stop_rewind', + 'asyncify_stop_unwind' + ]; + function tryAllocate(instance, wasm64, size, mallocName) { + if (typeof instance.exports[mallocName] !== 'function' || size <= 0) { + return { + wasm64, + dataPtr: 16, + start: wasm64 ? 32 : 24, + end: 1024 + }; + } + const malloc = instance.exports[mallocName]; + const dataPtr = wasm64 ? Number(malloc(BigInt(16) + BigInt(size))) : malloc(8 + size); + if (dataPtr === 0) { + throw new Error('Allocate asyncify data failed'); + } + return wasm64 + ? { wasm64, dataPtr, start: dataPtr + 16, end: dataPtr + 16 + size } + : { wasm64, dataPtr, start: dataPtr + 8, end: dataPtr + 8 + size }; + } + /** @public */ + class Asyncify { + constructor() { + this.value = undefined; + this.exports = undefined; + this.dataPtr = 0; + } + init(memory, instance, options) { + var _a, _b; + if (this.exports) { + throw new Error('Asyncify has been initialized'); + } + if (!(memory instanceof _WebAssembly.Memory)) { + throw new TypeError('Require WebAssembly.Memory object'); + } + const exports = instance.exports; + for (let i = 0; i < ignoreNames.length; ++i) { + if (typeof exports[ignoreNames[i]] !== 'function') { + throw new TypeError('Invalid asyncify wasm'); + } + } + let address; + const wasm64 = Boolean(options.wasm64); + if (!options.tryAllocate) { + address = { + wasm64, + dataPtr: 16, + start: wasm64 ? 32 : 24, + end: 1024 + }; + } + else { + if (options.tryAllocate === true) { + address = tryAllocate(instance, wasm64, 4096, 'malloc'); + } + else { + address = tryAllocate(instance, wasm64, (_a = options.tryAllocate.size) !== null && _a !== void 0 ? _a : 4096, (_b = options.tryAllocate.name) !== null && _b !== void 0 ? _b : 'malloc'); + } + } + this.dataPtr = address.dataPtr; + if (wasm64) { + new BigInt64Array(memory.buffer, this.dataPtr).set([BigInt(address.start), BigInt(address.end)]); + } + else { + new Int32Array(memory.buffer, this.dataPtr).set([address.start, address.end]); + } + this.exports = this.wrapExports(exports, options.wrapExports); + const asyncifiedInstance = Object.create(_WebAssembly.Instance.prototype); + Object.defineProperty(asyncifiedInstance, 'exports', { value: this.exports }); + // Object.setPrototypeOf(instance, Instance.prototype) + return asyncifiedInstance; + } + assertState() { + if (this.exports.asyncify_get_state() !== 0 /* AsyncifyState.NONE */) { + throw new Error('Asyncify state error'); + } + } + wrapImportFunction(f) { + // eslint-disable-next-line @typescript-eslint/no-this-alias + const _this = this; + return (function () { + // eslint-disable-next-line no-unreachable-loop + while (_this.exports.asyncify_get_state() === 2 /* AsyncifyState.REWINDING */) { + _this.exports.asyncify_stop_rewind(); + return _this.value; + } + _this.assertState(); + const v = f.apply(this, arguments); + if (!isPromiseLike(v)) + return v; + _this.exports.asyncify_start_unwind(_this.dataPtr); + _this.value = v; + }); + } + wrapImports(imports) { + const importObject = {}; + Object.keys(imports).forEach(k => { + const mod = imports[k]; + const newModule = {}; + Object.keys(mod).forEach(name => { + const importValue = mod[name]; + if (typeof importValue === 'function') { + newModule[name] = this.wrapImportFunction(importValue); + } + else { + newModule[name] = importValue; + } + }); + importObject[k] = newModule; + }); + return importObject; + } + wrapExportFunction(f) { + // eslint-disable-next-line @typescript-eslint/no-this-alias + const _this = this; + return (async function () { + _this.assertState(); + let ret = f.apply(this, arguments); + while (_this.exports.asyncify_get_state() === 1 /* AsyncifyState.UNWINDING */) { + _this.exports.asyncify_stop_unwind(); + _this.value = await _this.value; + _this.assertState(); + _this.exports.asyncify_start_rewind(_this.dataPtr); + ret = f.call(this); + } + _this.assertState(); + return ret; + }); + } + wrapExports(exports, needWrap) { + return wrapInstanceExports(exports, (exportValue, name) => { + let ignore = ignoreNames.indexOf(name) !== -1 || typeof exportValue !== 'function'; + if (Array.isArray(needWrap)) { + ignore = ignore || (needWrap.indexOf(name) === -1); + } + return ignore ? exportValue : this.wrapExportFunction(exportValue); + }); + } + } + + function validateImports(imports) { + if (imports && typeof imports !== 'object') { + throw new TypeError('imports must be an object or undefined'); + } + } + function fetchWasm(urlOrBuffer, imports) { + if (typeof wx !== 'undefined' && typeof __wxConfig !== 'undefined') { + return _WebAssembly.instantiate(urlOrBuffer, imports); + } + return fetch(urlOrBuffer) + .then(response => response.arrayBuffer()) + .then(buffer => _WebAssembly.instantiate(buffer, imports)); + } + /** @public */ + function load(wasmInput, imports) { + validateImports(imports); + imports = imports !== null && imports !== void 0 ? imports : {}; + let source; + if (wasmInput instanceof ArrayBuffer || ArrayBuffer.isView(wasmInput)) { + return _WebAssembly.instantiate(wasmInput, imports); + } + if (wasmInput instanceof _WebAssembly.Module) { + return _WebAssembly.instantiate(wasmInput, imports).then((instance) => { + return { instance, module: wasmInput }; + }); + } + if (typeof wasmInput !== 'string' && !(wasmInput instanceof URL)) { + throw new TypeError('Invalid source'); + } + if (typeof _WebAssembly.instantiateStreaming === 'function') { + let responsePromise; + try { + responsePromise = fetch(wasmInput); + source = _WebAssembly.instantiateStreaming(responsePromise, imports).catch(() => { + return fetchWasm(wasmInput, imports); + }); + } + catch (_) { + source = fetchWasm(wasmInput, imports); + } + } + else { + source = fetchWasm(wasmInput, imports); + } + return source; + } + /** @public */ + function asyncifyLoad(asyncify, urlOrBuffer, imports) { + validateImports(imports); + imports = imports !== null && imports !== void 0 ? imports : {}; + const asyncifyHelper = new Asyncify(); + imports = asyncifyHelper.wrapImports(imports); + return load(urlOrBuffer, imports).then(source => { + var _a; + const memory = source.instance.exports.memory || ((_a = imports.env) === null || _a === void 0 ? void 0 : _a.memory); + return { module: source.module, instance: asyncifyHelper.init(memory, source.instance, asyncify) }; + }); + } + /** @public */ + function loadSync(wasmInput, imports) { + validateImports(imports); + imports = imports !== null && imports !== void 0 ? imports : {}; + let module; + if ((wasmInput instanceof ArrayBuffer) || ArrayBuffer.isView(wasmInput)) { + module = new _WebAssembly.Module(wasmInput); + } + else if (wasmInput instanceof WebAssembly.Module) { + module = wasmInput; + } + else { + throw new TypeError('Invalid source'); + } + const instance = new _WebAssembly.Instance(module, imports); + const source = { instance, module }; + return source; + } + /** @public */ + function asyncifyLoadSync(asyncify, buffer, imports) { + var _a; + validateImports(imports); + imports = imports !== null && imports !== void 0 ? imports : {}; + const asyncifyHelper = new Asyncify(); + imports = asyncifyHelper.wrapImports(imports); + const source = loadSync(buffer, imports); + const memory = source.instance.exports.memory || ((_a = imports.env) === null || _a === void 0 ? void 0 : _a.memory); + return { module: source.module, instance: asyncifyHelper.init(memory, source.instance, asyncify) }; + } + + const CHAR_DOT = 46; /* . */ + const CHAR_FORWARD_SLASH = 47; /* / */ + const CHAR_BACKWARD_SLASH = 92; /* \ */ + const CHAR_COLON = 58; /* : */ + const CHAR_UPPERCASE_A = 65; /* A */ + const CHAR_UPPERCASE_Z = 90; /* Z */ + const CHAR_LOWERCASE_A = 97; /* a */ + const CHAR_LOWERCASE_Z = 122; /* z */ + function isPathSeparatorWin(code) { + return code === CHAR_FORWARD_SLASH || code === CHAR_BACKWARD_SLASH; + } + function isWindowsDeviceRoot(code) { + return (code >= CHAR_UPPERCASE_A && code <= CHAR_UPPERCASE_Z) || + (code >= CHAR_LOWERCASE_A && code <= CHAR_LOWERCASE_Z); + } + const _isWin32 = typeof process !== 'undefined' && process.platform === 'win32'; + /** + * Windows variant of `resolve()`. Mirrors Node's `path.win32.resolve` + * semantics enough for the WASI shim's needs (drive-letter absolutes + * + UNC paths + per-drive cwd lookups via `process.env`/`process.cwd`). + * + * Why this is needed: on Windows, `FileDescriptor.realPath` is the + * host realpath returned by `fs.realpathSync(realPath, 'utf8')` — the + * backslash form `D:\…`. The POSIX-only `resolveImpl` below only + * treats `/` as a separator, reads `D` as non-`/`, decides realPath + * is "relative", and produces a garbage joined path. Downstream + * `fs.openSync(garbage)` then returns `EINVAL` and the WASI caller + * sees a permanent failure. This function gives us the correct + * Windows-style resolution without taking a Node-only `path` import + * (which would break browser bundles of this package). + * + * Cribbed from Node's `lib/path.js` `win32.resolve()` (MIT-licensed), + * trimmed to what WASI realpath resolution actually exercises. + */ + function resolveWin32(args) { + let resolvedDevice = ''; + let resolvedTail = ''; + let resolvedAbsolute = false; + for (let i = args.length - 1; i >= -1; i--) { + let path; + if (i >= 0) { + path = args[i]; + validateString(path, 'path'); + if (path.length === 0) + continue; + } + else if (resolvedDevice.length === 0) { + path = (typeof process !== 'undefined' && typeof process.cwd === 'function') + ? process.cwd() + : ''; + } + else { + // Look up per-drive cwd via the `=X:` env var convention; fall back + // to the global cwd if absent. + const envKey = `=${resolvedDevice}`; + const env = (typeof process !== 'undefined') ? process.env : undefined; + path = (env && typeof env[envKey] === 'string') + ? env[envKey] + : (typeof process !== 'undefined' && typeof process.cwd === 'function') + ? process.cwd() + : ''; + if (path === undefined || + (path.slice(0, 2).toLowerCase() !== resolvedDevice.toLowerCase() && + path.charCodeAt(2) === CHAR_BACKWARD_SLASH)) { + path = `${resolvedDevice}\\`; + } + } + const len = path.length; + let rootEnd = 0; + let device = ''; + let isAbsolute = false; + const code = path.charCodeAt(0); + if (len === 1) { + if (isPathSeparatorWin(code)) { + rootEnd = 1; + isAbsolute = true; + } + } + else if (isPathSeparatorWin(code)) { + isAbsolute = true; + if (isPathSeparatorWin(path.charCodeAt(1))) { + // UNC path: `\\server\share\…` + let j = 2; + let last = j; + while (j < len && !isPathSeparatorWin(path.charCodeAt(j))) + j++; + if (j < len && j !== last) { + const firstPart = path.slice(last, j); + last = j; + while (j < len && isPathSeparatorWin(path.charCodeAt(j))) + j++; + if (j < len && j !== last) { + last = j; + while (j < len && !isPathSeparatorWin(path.charCodeAt(j))) + j++; + if (j === len || j !== last) { + device = `\\\\${firstPart}\\${path.slice(last, j)}`; + rootEnd = j; + } + } + } + } + else { + rootEnd = 1; + } + } + else if (isWindowsDeviceRoot(code) && path.charCodeAt(1) === CHAR_COLON) { + device = path.slice(0, 2); + rootEnd = 2; + if (len > 2 && isPathSeparatorWin(path.charCodeAt(2))) { + isAbsolute = true; + rootEnd = 3; + } + } + if (device.length > 0) { + if (resolvedDevice.length > 0) { + if (device.toLowerCase() !== resolvedDevice.toLowerCase()) + continue; + } + else { + resolvedDevice = device; + } + } + if (resolvedAbsolute) { + if (resolvedDevice.length > 0) + break; + } + else { + resolvedTail = `${path.slice(rootEnd)}\\${resolvedTail}`; + resolvedAbsolute = isAbsolute; + if (isAbsolute && resolvedDevice.length > 0) + break; + } + } + resolvedTail = normalizeString(resolvedTail, !resolvedAbsolute, '\\', isPathSeparatorWin); + return resolvedDevice + (resolvedAbsolute ? '\\' : '') + resolvedTail || '.'; + } + function isPosixPathSeparator(code) { + return code === CHAR_FORWARD_SLASH; + } + function normalizeString(path, allowAboveRoot, separator, isPathSeparator) { + let res = ''; + let lastSegmentLength = 0; + let lastSlash = -1; + let dots = 0; + let code = 0; + for (let i = 0; i <= path.length; ++i) { + if (i < path.length) { + code = path.charCodeAt(i); + } + else if (isPathSeparator(code)) { + break; + } + else { + code = CHAR_FORWARD_SLASH; + } + if (isPathSeparator(code)) { + if (lastSlash === i - 1 || dots === 1) ; + else if (dots === 2) { + if (res.length < 2 || lastSegmentLength !== 2 || + res.charCodeAt(res.length - 1) !== CHAR_DOT || + res.charCodeAt(res.length - 2) !== CHAR_DOT) { + if (res.length > 2) { + const lastSlashIndex = res.indexOf(separator); + if (lastSlashIndex === -1) { + res = ''; + lastSegmentLength = 0; + } + else { + res = res.slice(0, lastSlashIndex); + lastSegmentLength = + res.length - 1 - res.indexOf(separator); + } + lastSlash = i; + dots = 0; + continue; + } + else if (res.length !== 0) { + res = ''; + lastSegmentLength = 0; + lastSlash = i; + dots = 0; + continue; + } + } + if (allowAboveRoot) { + res += res.length > 0 ? `${separator}..` : '..'; + lastSegmentLength = 2; + } + } + else { + if (res.length > 0) { + res += `${separator}${path.slice(lastSlash + 1, i)}`; + } + else { + res = path.slice(lastSlash + 1, i); + } + lastSegmentLength = i - lastSlash - 1; + } + lastSlash = i; + dots = 0; + } + else if (code === CHAR_DOT && dots !== -1) { + ++dots; + } + else { + dots = -1; + } + } + return res; + } + function resolve(...args) { + // On Windows, host paths are `D:\…` style. The POSIX-only resolver + // below treats `D` as a non-`/` character and produces garbage; route + // to the Windows-aware variant. POSIX hosts (Linux/macOS/browser) + // run the original code path unchanged — `_isWin32` is constant-folded + // away on those targets. + if (_isWin32) + return resolveWin32(args); + let resolvedPath = ''; + let resolvedAbsolute = false; + for (let i = args.length - 1; i >= -1 && !resolvedAbsolute; i--) { + const path = i >= 0 ? args[i] : '/'; + validateString(path, 'path'); + // Skip empty entries + if (path.length === 0) { + continue; + } + resolvedPath = `${path}/${resolvedPath}`; + resolvedAbsolute = path.charCodeAt(0) === CHAR_FORWARD_SLASH; + } + // At this point the path should be resolved to a full absolute path, but + // handle relative paths to be safe (might happen when process.cwd() fails) + // Normalize the path + resolvedPath = normalizeString(resolvedPath, !resolvedAbsolute, '/', isPosixPathSeparator); + if (resolvedAbsolute) { + return `/${resolvedPath}`; + } + return resolvedPath.length > 0 ? resolvedPath : '.'; + } + + const FD_DATASYNC = ( /*#__PURE__*/BigInt(1) << /*#__PURE__*/ BigInt(0)); + const FD_READ = ( /*#__PURE__*/BigInt(1) << /*#__PURE__*/ BigInt(1)); + const FD_SEEK = ( /*#__PURE__*/BigInt(1) << /*#__PURE__*/ BigInt(2)); + const FD_FDSTAT_SET_FLAGS = ( /*#__PURE__*/BigInt(1) << /*#__PURE__*/ BigInt(3)); + const FD_SYNC = ( /*#__PURE__*/BigInt(1) << /*#__PURE__*/ BigInt(4)); + const FD_TELL = ( /*#__PURE__*/BigInt(1) << /*#__PURE__*/ BigInt(5)); + const FD_WRITE = ( /*#__PURE__*/BigInt(1) << /*#__PURE__*/ BigInt(6)); + const FD_ADVISE = ( /*#__PURE__*/BigInt(1) << /*#__PURE__*/ BigInt(7)); + const FD_ALLOCATE = ( /*#__PURE__*/BigInt(1) << /*#__PURE__*/ BigInt(8)); + const PATH_CREATE_DIRECTORY = ( /*#__PURE__*/BigInt(1) << /*#__PURE__*/ BigInt(9)); + const PATH_CREATE_FILE = ( /*#__PURE__*/BigInt(1) << /*#__PURE__*/ BigInt(10)); + const PATH_LINK_SOURCE = ( /*#__PURE__*/BigInt(1) << /*#__PURE__*/ BigInt(11)); + const PATH_LINK_TARGET = ( /*#__PURE__*/BigInt(1) << /*#__PURE__*/ BigInt(12)); + const PATH_OPEN = ( /*#__PURE__*/BigInt(1) << /*#__PURE__*/ BigInt(13)); + const FD_READDIR = ( /*#__PURE__*/BigInt(1) << /*#__PURE__*/ BigInt(14)); + const PATH_READLINK = ( /*#__PURE__*/BigInt(1) << /*#__PURE__*/ BigInt(15)); + const PATH_RENAME_SOURCE = ( /*#__PURE__*/BigInt(1) << /*#__PURE__*/ BigInt(16)); + const PATH_RENAME_TARGET = ( /*#__PURE__*/BigInt(1) << /*#__PURE__*/ BigInt(17)); + const PATH_FILESTAT_GET = ( /*#__PURE__*/BigInt(1) << /*#__PURE__*/ BigInt(18)); + const PATH_FILESTAT_SET_SIZE = ( /*#__PURE__*/BigInt(1) << /*#__PURE__*/ BigInt(19)); + const PATH_FILESTAT_SET_TIMES = ( /*#__PURE__*/BigInt(1) << /*#__PURE__*/ BigInt(20)); + const FD_FILESTAT_GET = ( /*#__PURE__*/BigInt(1) << /*#__PURE__*/ BigInt(21)); + const FD_FILESTAT_SET_SIZE = ( /*#__PURE__*/BigInt(1) << /*#__PURE__*/ BigInt(22)); + const FD_FILESTAT_SET_TIMES = ( /*#__PURE__*/BigInt(1) << /*#__PURE__*/ BigInt(23)); + const PATH_SYMLINK = ( /*#__PURE__*/BigInt(1) << /*#__PURE__*/ BigInt(24)); + const PATH_REMOVE_DIRECTORY = ( /*#__PURE__*/BigInt(1) << /*#__PURE__*/ BigInt(25)); + const PATH_UNLINK_FILE = ( /*#__PURE__*/BigInt(1) << /*#__PURE__*/ BigInt(26)); + const POLL_FD_READWRITE = ( /*#__PURE__*/BigInt(1) << /*#__PURE__*/ BigInt(27)); + const SOCK_SHUTDOWN = ( /*#__PURE__*/BigInt(1) << /*#__PURE__*/ BigInt(28)); + const SOCK_ACCEPT = ( /*#__PURE__*/BigInt(1) << /*#__PURE__*/ BigInt(29)); + const WasiRights = { + FD_DATASYNC, + FD_READ, + FD_SEEK, + FD_FDSTAT_SET_FLAGS, + FD_SYNC, + FD_TELL, + FD_WRITE, + FD_ADVISE, + FD_ALLOCATE, + PATH_CREATE_DIRECTORY, + PATH_CREATE_FILE, + PATH_LINK_SOURCE, + PATH_LINK_TARGET, + PATH_OPEN, + FD_READDIR, + PATH_READLINK, + PATH_RENAME_SOURCE, + PATH_RENAME_TARGET, + PATH_FILESTAT_GET, + PATH_FILESTAT_SET_SIZE, + PATH_FILESTAT_SET_TIMES, + FD_FILESTAT_GET, + FD_FILESTAT_SET_SIZE, + FD_FILESTAT_SET_TIMES, + PATH_SYMLINK, + PATH_REMOVE_DIRECTORY, + PATH_UNLINK_FILE, + POLL_FD_READWRITE, + SOCK_SHUTDOWN, + SOCK_ACCEPT + }; + + function strerror(errno) { + switch (errno) { + case 0 /* WasiErrno.ESUCCESS */: return 'Success'; + case 1 /* WasiErrno.E2BIG */: return 'Argument list too long'; + case 2 /* WasiErrno.EACCES */: return 'Permission denied'; + case 3 /* WasiErrno.EADDRINUSE */: return 'Address in use'; + case 4 /* WasiErrno.EADDRNOTAVAIL */: return 'Address not available'; + case 5 /* WasiErrno.EAFNOSUPPORT */: return 'Address family not supported by protocol'; + case 6 /* WasiErrno.EAGAIN */: return 'Resource temporarily unavailable'; + case 7 /* WasiErrno.EALREADY */: return 'Operation already in progress'; + case 8 /* WasiErrno.EBADF */: return 'Bad file descriptor'; + case 9 /* WasiErrno.EBADMSG */: return 'Bad message'; + case 10 /* WasiErrno.EBUSY */: return 'Resource busy'; + case 11 /* WasiErrno.ECANCELED */: return 'Operation canceled'; + case 12 /* WasiErrno.ECHILD */: return 'No child process'; + case 13 /* WasiErrno.ECONNABORTED */: return 'Connection aborted'; + case 14 /* WasiErrno.ECONNREFUSED */: return 'Connection refused'; + case 15 /* WasiErrno.ECONNRESET */: return 'Connection reset by peer'; + case 16 /* WasiErrno.EDEADLK */: return 'Resource deadlock would occur'; + case 17 /* WasiErrno.EDESTADDRREQ */: return 'Destination address required'; + case 18 /* WasiErrno.EDOM */: return 'Domain error'; + case 19 /* WasiErrno.EDQUOT */: return 'Quota exceeded'; + case 20 /* WasiErrno.EEXIST */: return 'File exists'; + case 21 /* WasiErrno.EFAULT */: return 'Bad address'; + case 22 /* WasiErrno.EFBIG */: return 'File too large'; + case 23 /* WasiErrno.EHOSTUNREACH */: return 'Host is unreachable'; + case 24 /* WasiErrno.EIDRM */: return 'Identifier removed'; + case 25 /* WasiErrno.EILSEQ */: return 'Illegal byte sequence'; + case 26 /* WasiErrno.EINPROGRESS */: return 'Operation in progress'; + case 27 /* WasiErrno.EINTR */: return 'Interrupted system call'; + case 28 /* WasiErrno.EINVAL */: return 'Invalid argument'; + case 29 /* WasiErrno.EIO */: return 'I/O error'; + case 30 /* WasiErrno.EISCONN */: return 'Socket is connected'; + case 31 /* WasiErrno.EISDIR */: return 'Is a directory'; + case 32 /* WasiErrno.ELOOP */: return 'Symbolic link loop'; + case 33 /* WasiErrno.EMFILE */: return 'No file descriptors available'; + case 34 /* WasiErrno.EMLINK */: return 'Too many links'; + case 35 /* WasiErrno.EMSGSIZE */: return 'Message too large'; + case 36 /* WasiErrno.EMULTIHOP */: return 'Multihop attempted'; + case 37 /* WasiErrno.ENAMETOOLONG */: return 'Filename too long'; + case 38 /* WasiErrno.ENETDOWN */: return 'Network is down'; + case 39 /* WasiErrno.ENETRESET */: return 'Connection reset by network'; + case 40 /* WasiErrno.ENETUNREACH */: return 'Network unreachable'; + case 41 /* WasiErrno.ENFILE */: return 'Too many files open in system'; + case 42 /* WasiErrno.ENOBUFS */: return 'No buffer space available'; + case 43 /* WasiErrno.ENODEV */: return 'No such device'; + case 44 /* WasiErrno.ENOENT */: return 'No such file or directory'; + case 45 /* WasiErrno.ENOEXEC */: return 'Exec format error'; + case 46 /* WasiErrno.ENOLCK */: return 'No locks available'; + case 47 /* WasiErrno.ENOLINK */: return 'Link has been severed'; + case 48 /* WasiErrno.ENOMEM */: return 'Out of memory'; + case 49 /* WasiErrno.ENOMSG */: return 'No message of the desired type'; + case 50 /* WasiErrno.ENOPROTOOPT */: return 'Protocol not available'; + case 51 /* WasiErrno.ENOSPC */: return 'No space left on device'; + case 52 /* WasiErrno.ENOSYS */: return 'Function not implemented'; + case 53 /* WasiErrno.ENOTCONN */: return 'Socket not connected'; + case 54 /* WasiErrno.ENOTDIR */: return 'Not a directory'; + case 55 /* WasiErrno.ENOTEMPTY */: return 'Directory not empty'; + case 56 /* WasiErrno.ENOTRECOVERABLE */: return 'State not recoverable'; + case 57 /* WasiErrno.ENOTSOCK */: return 'Not a socket'; + case 58 /* WasiErrno.ENOTSUP */: return 'Not supported'; + case 59 /* WasiErrno.ENOTTY */: return 'Not a tty'; + case 60 /* WasiErrno.ENXIO */: return 'No such device or address'; + case 61 /* WasiErrno.EOVERFLOW */: return 'Value too large for data type'; + case 62 /* WasiErrno.EOWNERDEAD */: return 'Previous owner died'; + case 63 /* WasiErrno.EPERM */: return 'Operation not permitted'; + case 64 /* WasiErrno.EPIPE */: return 'Broken pipe'; + case 65 /* WasiErrno.EPROTO */: return 'Protocol error'; + case 66 /* WasiErrno.EPROTONOSUPPORT */: return 'Protocol not supported'; + case 67 /* WasiErrno.EPROTOTYPE */: return 'Protocol wrong type for socket'; + case 68 /* WasiErrno.ERANGE */: return 'Result not representable'; + case 69 /* WasiErrno.EROFS */: return 'Read-only file system'; + case 70 /* WasiErrno.ESPIPE */: return 'Invalid seek'; + case 71 /* WasiErrno.ESRCH */: return 'No such process'; + case 72 /* WasiErrno.ESTALE */: return 'Stale file handle'; + case 73 /* WasiErrno.ETIMEDOUT */: return 'Operation timed out'; + case 74 /* WasiErrno.ETXTBSY */: return 'Text file busy'; + case 75 /* WasiErrno.EXDEV */: return 'Cross-device link'; + case 76 /* WasiErrno.ENOTCAPABLE */: return 'Capabilities insufficient'; + default: return 'Unknown error'; + } + } + class WasiError extends Error { + constructor(message, errno) { + super(message); + this.errno = errno; + } + getErrorMessage() { + return strerror(this.errno); + } + } + Object.defineProperty(WasiError.prototype, 'name', { + configurable: true, + writable: true, + value: 'WasiError' + }); + + const RIGHTS_ALL = WasiRights.FD_DATASYNC | + WasiRights.FD_READ | + WasiRights.FD_SEEK | + WasiRights.FD_FDSTAT_SET_FLAGS | + WasiRights.FD_SYNC | + WasiRights.FD_TELL | + WasiRights.FD_WRITE | + WasiRights.FD_ADVISE | + WasiRights.FD_ALLOCATE | + WasiRights.PATH_CREATE_DIRECTORY | + WasiRights.PATH_CREATE_FILE | + WasiRights.PATH_LINK_SOURCE | + WasiRights.PATH_LINK_TARGET | + WasiRights.PATH_OPEN | + WasiRights.FD_READDIR | + WasiRights.PATH_READLINK | + WasiRights.PATH_RENAME_SOURCE | + WasiRights.PATH_RENAME_TARGET | + WasiRights.PATH_FILESTAT_GET | + WasiRights.PATH_FILESTAT_SET_SIZE | + WasiRights.PATH_FILESTAT_SET_TIMES | + WasiRights.FD_FILESTAT_GET | + WasiRights.FD_FILESTAT_SET_TIMES | + WasiRights.FD_FILESTAT_SET_SIZE | + WasiRights.PATH_SYMLINK | + WasiRights.PATH_UNLINK_FILE | + WasiRights.PATH_REMOVE_DIRECTORY | + WasiRights.POLL_FD_READWRITE | + WasiRights.SOCK_SHUTDOWN | + WasiRights.SOCK_ACCEPT; + const BLOCK_DEVICE_BASE = RIGHTS_ALL; + const BLOCK_DEVICE_INHERITING = RIGHTS_ALL; + const CHARACTER_DEVICE_BASE = RIGHTS_ALL; + const CHARACTER_DEVICE_INHERITING = RIGHTS_ALL; + const REGULAR_FILE_BASE = WasiRights.FD_DATASYNC | + WasiRights.FD_READ | + WasiRights.FD_SEEK | + WasiRights.FD_FDSTAT_SET_FLAGS | + WasiRights.FD_SYNC | + WasiRights.FD_TELL | + WasiRights.FD_WRITE | + WasiRights.FD_ADVISE | + WasiRights.FD_ALLOCATE | + WasiRights.FD_FILESTAT_GET | + WasiRights.FD_FILESTAT_SET_SIZE | + WasiRights.FD_FILESTAT_SET_TIMES | + WasiRights.POLL_FD_READWRITE; + const REGULAR_FILE_INHERITING = /*#__PURE__*/ BigInt(0); + const DIRECTORY_BASE = WasiRights.FD_FDSTAT_SET_FLAGS | + WasiRights.FD_SYNC | + WasiRights.FD_ADVISE | + WasiRights.PATH_CREATE_DIRECTORY | + WasiRights.PATH_CREATE_FILE | + WasiRights.PATH_LINK_SOURCE | + WasiRights.PATH_LINK_TARGET | + WasiRights.PATH_OPEN | + WasiRights.FD_READDIR | + WasiRights.PATH_READLINK | + WasiRights.PATH_RENAME_SOURCE | + WasiRights.PATH_RENAME_TARGET | + WasiRights.PATH_FILESTAT_GET | + WasiRights.PATH_FILESTAT_SET_SIZE | + WasiRights.PATH_FILESTAT_SET_TIMES | + WasiRights.FD_FILESTAT_GET | + WasiRights.FD_FILESTAT_SET_TIMES | + WasiRights.PATH_SYMLINK | + WasiRights.PATH_UNLINK_FILE | + WasiRights.PATH_REMOVE_DIRECTORY | + WasiRights.POLL_FD_READWRITE; + const DIRECTORY_INHERITING = DIRECTORY_BASE | REGULAR_FILE_BASE; + const SOCKET_BASE = (WasiRights.FD_READ | + WasiRights.FD_FDSTAT_SET_FLAGS | + WasiRights.FD_WRITE | + WasiRights.FD_FILESTAT_GET | + WasiRights.POLL_FD_READWRITE | + WasiRights.SOCK_SHUTDOWN); + const SOCKET_INHERITING = RIGHTS_ALL; + const TTY_BASE = WasiRights.FD_READ | + WasiRights.FD_FDSTAT_SET_FLAGS | + WasiRights.FD_WRITE | + WasiRights.FD_FILESTAT_GET | + WasiRights.POLL_FD_READWRITE; + const TTY_INHERITING = /*#__PURE__*/ BigInt(0); + function getRights(stdio, fd, flags, type) { + const ret = { + base: BigInt(0), + inheriting: BigInt(0) + }; + if (type === 0 /* WasiFileType.UNKNOWN */) { + throw new WasiError('Unknown file type', 28 /* WasiErrno.EINVAL */); + } + switch (type) { + case 4 /* WasiFileType.REGULAR_FILE */: + ret.base = REGULAR_FILE_BASE; + ret.inheriting = REGULAR_FILE_INHERITING; + break; + case 3 /* WasiFileType.DIRECTORY */: + ret.base = DIRECTORY_BASE; + ret.inheriting = DIRECTORY_INHERITING; + break; + case 6 /* WasiFileType.SOCKET_STREAM */: + case 5 /* WasiFileType.SOCKET_DGRAM */: + ret.base = SOCKET_BASE; + ret.inheriting = SOCKET_INHERITING; + break; + case 2 /* WasiFileType.CHARACTER_DEVICE */: + if (stdio.indexOf(fd) !== -1) { + ret.base = TTY_BASE; + ret.inheriting = TTY_INHERITING; + } + else { + ret.base = CHARACTER_DEVICE_BASE; + ret.inheriting = CHARACTER_DEVICE_INHERITING; + } + break; + case 1 /* WasiFileType.BLOCK_DEVICE */: + ret.base = BLOCK_DEVICE_BASE; + ret.inheriting = BLOCK_DEVICE_INHERITING; + break; + default: + ret.base = BigInt(0); + ret.inheriting = BigInt(0); + } + /* Disable read/write bits depending on access mode. */ + const read_or_write_only = flags & (0 | 1 | 2); + if (read_or_write_only === 0) { + ret.base &= ~WasiRights.FD_WRITE; + } + else if (read_or_write_only === 1) { + ret.base &= ~WasiRights.FD_READ; + } + return ret; + } + + function concatBuffer(buffers, size) { + let total = 0; + if (typeof size === 'number' && size >= 0) { + total = size; + } + else { + for (let i = 0; i < buffers.length; i++) { + const buffer = buffers[i]; + total += buffer.length; + } + } + let pos = 0; + const ret = new Uint8Array(total); + for (let i = 0; i < buffers.length; i++) { + const buffer = buffers[i]; + ret.set(buffer, pos); + pos += buffer.length; + } + return ret; + } + class FileDescriptor { + constructor(id, fd, path, realPath, type, rightsBase, rightsInheriting, preopen) { + this.id = id; + this.fd = fd; + this.path = path; + this.realPath = realPath; + this.type = type; + this.rightsBase = rightsBase; + this.rightsInheriting = rightsInheriting; + this.preopen = preopen; + this.pos = BigInt(0); + this.size = BigInt(0); + } + seek(offset, whence) { + if (whence === 0 /* WasiWhence.SET */) { + this.pos = BigInt(offset); + } + else if (whence === 1 /* WasiWhence.CUR */) { + this.pos += BigInt(offset); + } + else if (whence === 2 /* WasiWhence.END */) { + this.pos = BigInt(this.size) - BigInt(offset); + } + else { + throw new WasiError('Unknown whence', 29 /* WasiErrno.EIO */); + } + return this.pos; + } + } + class StandardOutput extends FileDescriptor { + constructor(log, id, fd, path, realPath, type, rightsBase, rightsInheriting, preopen) { + super(id, fd, path, realPath, type, rightsBase, rightsInheriting, preopen); + this._log = log; + this._buf = null; + } + write(buffer) { + const originalBuffer = buffer; + if (this._buf) { + buffer = concatBuffer([this._buf, buffer]); + this._buf = null; + } + if (buffer.indexOf(10) === -1) { + this._buf = buffer; + return originalBuffer.byteLength; + } + let written = 0; + let lastBegin = 0; + let index; + while ((index = buffer.indexOf(10, written)) !== -1) { + const str = new TextDecoder().decode(buffer.subarray(lastBegin, index)); + this._log(str); + written += index - lastBegin + 1; + lastBegin = index + 1; + } + if (written < buffer.length) { + this._buf = buffer.slice(written); + } + return originalBuffer.byteLength; + } + } + function toFileType(stat) { + if (stat.isBlockDevice()) + return 1 /* WasiFileType.BLOCK_DEVICE */; + if (stat.isCharacterDevice()) + return 2 /* WasiFileType.CHARACTER_DEVICE */; + if (stat.isDirectory()) + return 3 /* WasiFileType.DIRECTORY */; + if (stat.isSocket()) + return 6 /* WasiFileType.SOCKET_STREAM */; + if (stat.isFile()) + return 4 /* WasiFileType.REGULAR_FILE */; + if (stat.isSymbolicLink()) + return 7 /* WasiFileType.SYMBOLIC_LINK */; + return 0 /* WasiFileType.UNKNOWN */; + } + function toFileStat(view, buf, stat) { + view.setBigUint64(buf, stat.dev, true); + view.setBigUint64(buf + 8, stat.ino, true); + view.setBigUint64(buf + 16, BigInt(toFileType(stat)), true); + view.setBigUint64(buf + 24, stat.nlink, true); + view.setBigUint64(buf + 32, stat.size, true); + view.setBigUint64(buf + 40, stat.atimeMs * BigInt(1000000), true); + view.setBigUint64(buf + 48, stat.mtimeMs * BigInt(1000000), true); + view.setBigUint64(buf + 56, stat.ctimeMs * BigInt(1000000), true); + } + class FileDescriptorTable { + constructor(options) { + this.used = 0; + this.size = options.size; + this.fds = Array(options.size); + this.stdio = [options.in, options.out, options.err]; + this.print = options.print; + this.printErr = options.printErr; + this.insertStdio(options.in, 0, ''); + this.insertStdio(options.out, 1, ''); + this.insertStdio(options.err, 2, ''); + } + insertStdio(fd, expected, name) { + const type = 2 /* WasiFileType.CHARACTER_DEVICE */; + const { base, inheriting } = getRights(this.stdio, fd, 2 /* FileControlFlag.O_RDWR */, type); + const wrap = this.insert(fd, name, name, type, base, inheriting, 0); + if (wrap.id !== expected) { + throw new WasiError(`id: ${wrap.id} !== expected: ${expected}`, 8 /* WasiErrno.EBADF */); + } + return wrap; + } + insert(fd, mappedPath, realPath, type, rightsBase, rightsInheriting, preopen) { + var _a, _b; + let index = -1; + if (this.used >= this.size) { + const newSize = this.size * 2; + this.fds.length = newSize; + index = this.size; + this.size = newSize; + } + else { + for (let i = 0; i < this.size; ++i) { + if (this.fds[i] == null) { + index = i; + break; + } + } + } + let entry; + if (mappedPath === '') { + entry = new StandardOutput((_a = this.print) !== null && _a !== void 0 ? _a : console.log, index, fd, mappedPath, realPath, type, rightsBase, rightsInheriting, preopen); + } + else if (mappedPath === '') { + entry = new StandardOutput((_b = this.printErr) !== null && _b !== void 0 ? _b : console.error, index, fd, mappedPath, realPath, type, rightsBase, rightsInheriting, preopen); + } + else { + entry = new FileDescriptor(index, fd, mappedPath, realPath, type, rightsBase, rightsInheriting, preopen); + } + this.fds[index] = entry; + this.used++; + return entry; + } + get(id, base, inheriting) { + if (id >= this.size) { + throw new WasiError('Invalid fd', 8 /* WasiErrno.EBADF */); + } + const entry = this.fds[id]; + if (!entry || entry.id !== id) { + throw new WasiError('Bad file descriptor', 8 /* WasiErrno.EBADF */); + } + /* Validate that the fd has the necessary rights. */ + if ((~entry.rightsBase & base) !== BigInt(0) || (~entry.rightsInheriting & inheriting) !== BigInt(0)) { + throw new WasiError('Capabilities insufficient', 76 /* WasiErrno.ENOTCAPABLE */); + } + return entry; + } + remove(id) { + if (id >= this.size) { + throw new WasiError('Invalid fd', 8 /* WasiErrno.EBADF */); + } + const entry = this.fds[id]; + if (!entry || entry.id !== id) { + throw new WasiError('Bad file descriptor', 8 /* WasiErrno.EBADF */); + } + this.fds[id] = undefined; + this.used--; + } + } + class SyncTable extends FileDescriptorTable { + constructor(options) { + super(options); + this.fs = options.fs; + } + getFileTypeByFd(fd) { + const stats = this.fs.fstatSync(fd, { bigint: true }); + return toFileType(stats); + } + insertPreopen(fd, mappedPath, realPath) { + const type = this.getFileTypeByFd(fd); + if (type !== 3 /* WasiFileType.DIRECTORY */) { + throw new WasiError(`Preopen not dir: ["${mappedPath}", "${realPath}"]`, 54 /* WasiErrno.ENOTDIR */); + } + const result = getRights(this.stdio, fd, 0, type); + return this.insert(fd, mappedPath, realPath, type, result.base, result.inheriting, 1); + } + renumber(dst, src) { + if (dst === src) + return; + if (dst >= this.size || src >= this.size) { + throw new WasiError('Invalid fd', 8 /* WasiErrno.EBADF */); + } + const dstEntry = this.fds[dst]; + const srcEntry = this.fds[src]; + if (!dstEntry || !srcEntry || dstEntry.id !== dst || srcEntry.id !== src) { + throw new WasiError('Invalid fd', 8 /* WasiErrno.EBADF */); + } + this.fs.closeSync(dstEntry.fd); + this.fds[dst] = this.fds[src]; + this.fds[dst].id = dst; + this.fds[src] = undefined; + this.used--; + } + } + class AsyncTable extends FileDescriptorTable { + // eslint-disable-next-line @typescript-eslint/no-useless-constructor + constructor(options) { + super(options); + } + async getFileTypeByFd(fd) { + const stats = await fd.stat({ bigint: true }); + return toFileType(stats); + } + async insertPreopen(fd, mappedPath, realPath) { + const type = await this.getFileTypeByFd(fd); + if (type !== 3 /* WasiFileType.DIRECTORY */) { + throw new WasiError(`Preopen not dir: ["${mappedPath}", "${realPath}"]`, 54 /* WasiErrno.ENOTDIR */); + } + const result = getRights(this.stdio, fd.fd, 0, type); + return this.insert(fd, mappedPath, realPath, type, result.base, result.inheriting, 1); + } + async renumber(dst, src) { + if (dst === src) + return; + if (dst >= this.size || src >= this.size) { + throw new WasiError('Invalid fd', 8 /* WasiErrno.EBADF */); + } + const dstEntry = this.fds[dst]; + const srcEntry = this.fds[src]; + if (!dstEntry || !srcEntry || dstEntry.id !== dst || srcEntry.id !== src) { + throw new WasiError('Invalid fd', 8 /* WasiErrno.EBADF */); + } + await dstEntry.fd.close(); + this.fds[dst] = this.fds[src]; + this.fds[dst].id = dst; + this.fds[src] = undefined; + this.used--; + } + } + + /** @public */ + const WebAssemblyMemory = /*#__PURE__*/ (function () { return _WebAssembly.Memory; })(); + /** @public */ + class Memory extends WebAssemblyMemory { + // eslint-disable-next-line @typescript-eslint/no-useless-constructor + constructor(descriptor) { + super(descriptor); + } + get HEAP8() { return new Int8Array(super.buffer); } + get HEAPU8() { return new Uint8Array(super.buffer); } + get HEAP16() { return new Int16Array(super.buffer); } + get HEAPU16() { return new Uint16Array(super.buffer); } + get HEAP32() { return new Int32Array(super.buffer); } + get HEAPU32() { return new Uint32Array(super.buffer); } + get HEAP64() { return new BigInt64Array(super.buffer); } + get HEAPU64() { return new BigUint64Array(super.buffer); } + get HEAPF32() { return new Float32Array(super.buffer); } + get HEAPF64() { return new Float64Array(super.buffer); } + get view() { return new DataView(super.buffer); } + } + /** @public */ + function extendMemory(memory) { + if (Object.getPrototypeOf(memory) === _WebAssembly.Memory.prototype) { + Object.setPrototypeOf(memory, Memory.prototype); + } + return memory; + } + + function checkWebAssemblyFunction() { + const WebAssemblyFunction = _WebAssembly.Function; + if (typeof WebAssemblyFunction !== 'function') { + throw new Error('WebAssembly.Function is not supported in this environment.' + + ' If you are using V8 based browser like Chrome, try to specify' + + ' --js-flags="--wasm-staging --experimental-wasm-stack-switching"'); + } + return WebAssemblyFunction; + } + /** @public */ + function wrapAsyncImport(f, parameterType, returnType) { + const WebAssemblyFunction = checkWebAssemblyFunction(); + if (typeof f !== 'function') { + throw new TypeError('Function required'); + } + const parameters = parameterType.slice(0); + parameters.unshift('externref'); + return new WebAssemblyFunction({ parameters, results: returnType }, f, { suspending: 'first' }); + } + /** @public */ + function wrapAsyncExport(f) { + const WebAssemblyFunction = checkWebAssemblyFunction(); + if (typeof f !== 'function') { + throw new TypeError('Function required'); + } + return new WebAssemblyFunction({ parameters: [...WebAssemblyFunction.type(f).parameters.slice(1)], results: ['externref'] }, f, { promising: 'first' }); + } + /** @public */ + function wrapExports(exports, needWrap) { + return wrapInstanceExports(exports, (exportValue, name) => { + let ignore = typeof exportValue !== 'function'; + if (Array.isArray(needWrap)) { + ignore = ignore || (needWrap.indexOf(name) === -1); + } + return ignore ? exportValue : wrapAsyncExport(exportValue); + }); + } + + // Linux fcntl flag bits ↔ Windows libuv flag bits. `pathOpen()` builds + // `flagsRes` using Linux constants (O_CREAT=0x40, O_EXCL=0x80, + // O_APPEND=0x400). Windows libuv expects different bits (O_CREAT=0x100, + // O_EXCL=0x400, O_APPEND=0x8). Without translation, + // `fs.openSync(path, 0x241 /* L:WRONLY|CREAT|TRUNC */)` is rejected + // with EINVAL because Linux's 0x40 happens to mean O_TEMPORARY on + // Windows — and O_TEMPORARY without O_CREAT is invalid. + const _isWin32Flags = typeof process !== 'undefined' && process.platform === 'win32'; + function _toWinOpenFlags(f) { + let r = f & 3; // RDONLY/WRONLY/RDWR — same on both + if ((f & 0x40) !== 0) + r |= 0x100; // O_CREAT: Linux 0x40 -> Windows 0x100 + if ((f & 0x80) !== 0) + r |= 0x400; // O_EXCL: Linux 0x80 -> Windows 0x400 + if ((f & 0x200) !== 0) + r |= 0x200; // O_TRUNC: same value on both + if ((f & 0x400) !== 0) + r |= 0x8; // O_APPEND: Linux 0x400 -> Windows 0x8 + return r; + } + function copyMemory(targets, src) { + if (targets.length === 0 || src.length === 0) + return 0; + let copied = 0; + let left = src.length - copied; + for (let i = 0; i < targets.length; ++i) { + const target = targets[i]; + if (left < target.length) { + target.set(src.subarray(copied, copied + left), 0); + copied += left; + left = 0; + return copied; + } + target.set(src.subarray(copied, copied + target.length), 0); + copied += target.length; + left -= target.length; + } + return copied; + } + const _memory = new WeakMap(); + const _wasi = new WeakMap(); + const _fs = new WeakMap(); + function ensureMemoryFor(memory, end) { + let buffer = memory.buffer; + if (end > buffer.byteLength) { + memory.grow(0); + buffer = memory.buffer; + } + return buffer; + } + function getMemory(wasi, end = 0) { + const memory = _memory.get(wasi); + ensureMemoryFor(memory, end); + return memory; + } + function getFs(wasi) { + const fs = _fs.get(wasi); + if (!fs) + throw new Error('filesystem is unavailable'); + return fs; + } + function handleError(err) { + if (err instanceof WasiError) { + { + console.warn(err); + } + return err.errno; + } + switch (err.code) { + case 'ENOENT': return 44 /* WasiErrno.ENOENT */; + case 'EBADF': return 8 /* WasiErrno.EBADF */; + case 'EINVAL': return 28 /* WasiErrno.EINVAL */; + case 'EPERM': return 63 /* WasiErrno.EPERM */; + case 'EPROTO': return 65 /* WasiErrno.EPROTO */; + case 'EEXIST': return 20 /* WasiErrno.EEXIST */; + case 'ENOTDIR': return 54 /* WasiErrno.ENOTDIR */; + case 'EMFILE': return 33 /* WasiErrno.EMFILE */; + case 'EACCES': return 2 /* WasiErrno.EACCES */; + case 'EISDIR': return 31 /* WasiErrno.EISDIR */; + case 'ENOTEMPTY': return 55 /* WasiErrno.ENOTEMPTY */; + case 'ENOSYS': return 52 /* WasiErrno.ENOSYS */; + } + throw err; + } + function defineName(name, f) { + Object.defineProperty(f, 'name', { value: name }); + return f; + } + function tryCall(f, wasi, args) { + let r; + try { + r = f.apply(wasi, args); + } + catch (err) { + return handleError(err); + } + if (isPromiseLike(r)) { + return r.then(_ => _, handleError); + } + return r; + } + function syscallWrap(self, name, f) { + let debug = false; + const NODE_DEBUG_NATIVE = (() => { + try { + return "wasi"; + } + catch (_) { + return undefined; + } + })(); + if (typeof NODE_DEBUG_NATIVE === 'string' && NODE_DEBUG_NATIVE.split(',').includes('wasi')) { + debug = true; + } + return debug + ? defineName(name, function () { + const args = Array.prototype.slice.call(arguments); + let debugArgs = [`${name}(${Array.from({ length: arguments.length }).map(() => '%d').join(', ')})`]; + debugArgs = debugArgs.concat(args); + console.debug.apply(console, debugArgs); + return tryCall(f, self, args); + }) + : defineName(name, function () { + return tryCall(f, self, arguments); + }); + } + function resolvePathSync(fs, fileDescriptor, path, flags) { + let resolvedPath = resolve(fileDescriptor.realPath, path); + if ((flags & 1) === 1) { + try { + resolvedPath = fs.readlinkSync(resolvedPath); + } + catch (err) { + if (err.code !== 'EINVAL' && err.code !== 'ENOENT') { + throw err; + } + } + } + return resolvedPath; + } + async function resolvePathAsync(fs, fileDescriptor, path, flags) { + let resolvedPath = resolve(fileDescriptor.realPath, path); + if ((flags & 1) === 1) { + try { + resolvedPath = await fs.promises.readlink(resolvedPath); + } + catch (err) { + if (err.code !== 'EINVAL' && err.code !== 'ENOENT') { + throw err; + } + } + } + return resolvedPath; + } + // eslint-disable-next-line spaced-comment + const encoder = /*#__PURE__*/ new TextEncoder(); + // eslint-disable-next-line spaced-comment + const decoder = /*#__PURE__*/ new TextDecoder(); + const INT64_MAX = (BigInt(1) << BigInt(63)) - BigInt(1); + function readStdin() { + const value = window.prompt(); + if (value === null) + return new Uint8Array(); + const buffer = new TextEncoder().encode(value + '\n'); + return buffer; + } + function validateFstFlagsOrReturn(flags) { + return (Boolean((flags) & ~(1 /* WasiFstFlag.SET_ATIM */ | 2 /* WasiFstFlag.SET_ATIM_NOW */ | + 4 /* WasiFstFlag.SET_MTIM */ | 8 /* WasiFstFlag.SET_MTIM_NOW */)) || + ((flags) & (1 /* WasiFstFlag.SET_ATIM */ | 2 /* WasiFstFlag.SET_ATIM_NOW */)) === + (1 /* WasiFstFlag.SET_ATIM */ | 2 /* WasiFstFlag.SET_ATIM_NOW */) || + ((flags) & (4 /* WasiFstFlag.SET_MTIM */ | 8 /* WasiFstFlag.SET_MTIM_NOW */)) === + (4 /* WasiFstFlag.SET_MTIM */ | 8 /* WasiFstFlag.SET_MTIM_NOW */)); + } + class WASI$1 { + constructor(args, env, fds, asyncFs, fs, asyncify) { + this.args_get = syscallWrap(this, 'args_get', function (argv, argv_buf) { + argv = Number(argv); + argv_buf = Number(argv_buf); + if (argv === 0 || argv_buf === 0) { + return 28 /* WasiErrno.EINVAL */; + } + const wasi = _wasi.get(this); + const args = wasi.args; + const argsSize = encoder.encode(args.join('\0') + '\0').length; + const { HEAPU8, view } = getMemory(this, Math.max(argv + args.length * 4, argv_buf + argsSize)); + for (let i = 0; i < args.length; ++i) { + const arg = args[i]; + view.setInt32(argv, argv_buf, true); + argv += 4; + const data = encoder.encode(arg + '\0'); + HEAPU8.set(data, argv_buf); + argv_buf += data.length; + } + return 0 /* WasiErrno.ESUCCESS */; + }); + this.args_sizes_get = syscallWrap(this, 'args_sizes_get', function (argc, argv_buf_size) { + argc = Number(argc); + argv_buf_size = Number(argv_buf_size); + if (argc === 0 || argv_buf_size === 0) { + return 28 /* WasiErrno.EINVAL */; + } + const { view } = getMemory(this, Math.max(argc + 4, argv_buf_size + 4)); + const wasi = _wasi.get(this); + const args = wasi.args; + view.setUint32(argc, args.length, true); + view.setUint32(argv_buf_size, encoder.encode(args.join('\0') + '\0').length, true); + return 0 /* WasiErrno.ESUCCESS */; + }); + this.environ_get = syscallWrap(this, 'environ_get', function (environ, environ_buf) { + environ = Number(environ); + environ_buf = Number(environ_buf); + if (environ === 0 || environ_buf === 0) { + return 28 /* WasiErrno.EINVAL */; + } + const wasi = _wasi.get(this); + const env = wasi.env; + const envSize = encoder.encode(env.join('\0') + '\0').length; + const { HEAPU8, view } = getMemory(this, Math.max(environ + env.length * 4, environ_buf + envSize)); + for (let i = 0; i < env.length; ++i) { + const pair = env[i]; + view.setInt32(environ, environ_buf, true); + environ += 4; + const data = encoder.encode(pair + '\0'); + HEAPU8.set(data, environ_buf); + environ_buf += data.length; + } + return 0 /* WasiErrno.ESUCCESS */; + }); + this.environ_sizes_get = syscallWrap(this, 'environ_sizes_get', function (len, buflen) { + len = Number(len); + buflen = Number(buflen); + if (len === 0 || buflen === 0) { + return 28 /* WasiErrno.EINVAL */; + } + const { view } = getMemory(this, Math.max(len + 4, buflen + 4)); + const wasi = _wasi.get(this); + view.setUint32(len, wasi.env.length, true); + view.setUint32(buflen, encoder.encode(wasi.env.join('\0') + '\0').length, true); + return 0 /* WasiErrno.ESUCCESS */; + }); + this.clock_res_get = syscallWrap(this, 'clock_res_get', function (id, resolution) { + resolution = Number(resolution); + if (resolution === 0) { + return 28 /* WasiErrno.EINVAL */; + } + const { view } = getMemory(this, resolution + 8); + switch (id) { + case 0 /* WasiClockid.REALTIME */: + view.setBigUint64(resolution, BigInt(1000000), true); + return 0 /* WasiErrno.ESUCCESS */; + case 1 /* WasiClockid.MONOTONIC */: + case 2 /* WasiClockid.PROCESS_CPUTIME_ID */: + case 3 /* WasiClockid.THREAD_CPUTIME_ID */: + view.setBigUint64(resolution, BigInt(1000), true); + return 0 /* WasiErrno.ESUCCESS */; + default: return 28 /* WasiErrno.EINVAL */; + } + }); + this.clock_time_get = syscallWrap(this, 'clock_time_get', function (id, _percision, time) { + time = Number(time); + if (time === 0) { + return 28 /* WasiErrno.EINVAL */; + } + const { view } = getMemory(this, time + 8); + switch (id) { + case 0 /* WasiClockid.REALTIME */: + view.setBigUint64(time, BigInt(Date.now()) * BigInt(1000000), true); + return 0 /* WasiErrno.ESUCCESS */; + case 1 /* WasiClockid.MONOTONIC */: + case 2 /* WasiClockid.PROCESS_CPUTIME_ID */: + case 3 /* WasiClockid.THREAD_CPUTIME_ID */: { + const t = performance.now() / 1000; + const s = Math.trunc(t); + const ms = Math.floor((t - s) * 1000); + const result = BigInt(s) * BigInt(1000000000) + BigInt(ms) * BigInt(1000000); + view.setBigUint64(time, result, true); + return 0 /* WasiErrno.ESUCCESS */; + } + default: return 28 /* WasiErrno.EINVAL */; + } + }); + this.fd_advise = syscallWrap(this, 'fd_advise', function (_fd, _offset, _len, _advice) { + return 52 /* WasiErrno.ENOSYS */; + }); + this.fd_fdstat_get = syscallWrap(this, 'fd_fdstat_get', function (fd, fdstat) { + fdstat = Number(fdstat); + if (fdstat === 0) { + return 28 /* WasiErrno.EINVAL */; + } + const wasi = _wasi.get(this); + const fileDescriptor = wasi.fds.get(fd, BigInt(0), BigInt(0)); + const { view } = getMemory(this, fdstat + 24); + view.setUint16(fdstat, fileDescriptor.type, true); + view.setUint16(fdstat + 2, 0, true); + view.setBigUint64(fdstat + 8, fileDescriptor.rightsBase, true); + view.setBigUint64(fdstat + 16, fileDescriptor.rightsInheriting, true); + return 0 /* WasiErrno.ESUCCESS */; + }); + this.fd_fdstat_set_flags = syscallWrap(this, 'fd_fdstat_set_flags', function (_fd, _flags) { + return 52 /* WasiErrno.ENOSYS */; + }); + this.fd_fdstat_set_rights = syscallWrap(this, 'fd_fdstat_set_rights', function (fd, rightsBase, rightsInheriting) { + const wasi = _wasi.get(this); + const fileDescriptor = wasi.fds.get(fd, BigInt(0), BigInt(0)); + if ((rightsBase | fileDescriptor.rightsBase) > fileDescriptor.rightsBase) { + return 76 /* WasiErrno.ENOTCAPABLE */; + } + if ((rightsInheriting | fileDescriptor.rightsInheriting) > + fileDescriptor.rightsInheriting) { + return 76 /* WasiErrno.ENOTCAPABLE */; + } + fileDescriptor.rightsBase = rightsBase; + fileDescriptor.rightsInheriting = rightsInheriting; + return 0 /* WasiErrno.ESUCCESS */; + }); + this.fd_prestat_get = syscallWrap(this, 'fd_prestat_get', function (fd, prestat) { + prestat = Number(prestat); + if (prestat === 0) { + return 28 /* WasiErrno.EINVAL */; + } + const wasi = _wasi.get(this); + let fileDescriptor; + try { + fileDescriptor = wasi.fds.get(fd, BigInt(0), BigInt(0)); + } + catch (err) { + if (err instanceof WasiError) + return err.errno; + throw err; + } + if (fileDescriptor.preopen !== 1) + return 28 /* WasiErrno.EINVAL */; + const { view } = getMemory(this, prestat + 8); + // preopen type is dir(0) + view.setUint32(prestat, 0, true); + view.setUint32(prestat + 4, encoder.encode(fileDescriptor.path).length, true); + return 0 /* WasiErrno.ESUCCESS */; + }); + this.fd_prestat_dir_name = syscallWrap(this, 'fd_prestat_dir_name', function (fd, path, path_len) { + path = Number(path); + path_len = Number(path_len); + if (path === 0) { + return 28 /* WasiErrno.EINVAL */; + } + const wasi = _wasi.get(this); + const fileDescriptor = wasi.fds.get(fd, BigInt(0), BigInt(0)); + if (fileDescriptor.preopen !== 1) + return 8 /* WasiErrno.EBADF */; + const buffer = encoder.encode(fileDescriptor.path); + const size = buffer.length; + if (size > path_len) + return 42 /* WasiErrno.ENOBUFS */; + const { HEAPU8 } = getMemory(this, path + size); + HEAPU8.set(buffer, path); + return 0 /* WasiErrno.ESUCCESS */; + }); + this.fd_seek = syscallWrap(this, 'fd_seek', function (fd, offset, whence, newOffset) { + newOffset = Number(newOffset); + if (newOffset === 0) { + return 28 /* WasiErrno.EINVAL */; + } + if (fd === 0 || fd === 1 || fd === 2) + return 0 /* WasiErrno.ESUCCESS */; + const wasi = _wasi.get(this); + const fileDescriptor = wasi.fds.get(fd, WasiRights.FD_SEEK, BigInt(0)); + const r = fileDescriptor.seek(offset, whence); + const { view } = getMemory(this, newOffset + 8); + view.setBigUint64(newOffset, r, true); + return 0 /* WasiErrno.ESUCCESS */; + }); + this.fd_tell = syscallWrap(this, 'fd_tell', function (fd, offset) { + const wasi = _wasi.get(this); + const fileDescriptor = wasi.fds.get(fd, WasiRights.FD_TELL, BigInt(0)); + const pos = BigInt(fileDescriptor.pos); + const { view } = getMemory(this, Number(offset) + 8); + view.setBigUint64(Number(offset), pos, true); + return 0 /* WasiErrno.ESUCCESS */; + }); + this.poll_oneoff = syscallWrap(this, 'poll_oneoff', function (in_ptr, out_ptr, nsubscriptions, nevents) { + in_ptr = Number(in_ptr); + out_ptr = Number(out_ptr); + nevents = Number(nevents); + nsubscriptions = Number(nsubscriptions); + nsubscriptions = nsubscriptions >>> 0; + if (in_ptr === 0 || out_ptr === 0 || nsubscriptions === 0 || nevents === 0) { + return 28 /* WasiErrno.EINVAL */; + } + const { view } = getMemory(this, Math.max(in_ptr + nsubscriptions * 48, out_ptr + nsubscriptions * 32, nevents + 4)); + view.setUint32(nevents, 0, true); + let i = 0; + let timer_userdata = BigInt(0); + let cur_timeout = BigInt(0); + let has_timeout = 0; + let min_timeout = BigInt(0); + let sub; + const subscriptions = Array(nsubscriptions); + for (i = 0; i < nsubscriptions; i++) { + sub = in_ptr + i * 48; + const userdata = view.getBigUint64(sub, true); + const type = view.getUint8(sub + 8); + const clockIdOrFd = view.getUint32(sub + 16, true); + const timeout = view.getBigUint64(sub + 24, true); + const precision = view.getBigUint64(sub + 32, true); + const flags = view.getUint16(sub + 40, true); + subscriptions[i] = { + userdata, + type, + u: { + clock: { + clock_id: clockIdOrFd, + timeout, + precision, + flags + }, + fd_readwrite: { + fd: clockIdOrFd + } + } + }; + } + const fdevents = []; + for (i = 0; i < nsubscriptions; i++) { + sub = subscriptions[i]; + switch (sub.type) { + case 0 /* WasiEventType.CLOCK */: { + if (sub.u.clock.flags === 1 /* WasiSubclockflags.ABSTIME */) { + /* Convert absolute time to relative delay. */ + const now = BigInt(Date.now()) * BigInt(1000000); + cur_timeout = sub.u.clock.timeout - now; + } + else { + cur_timeout = sub.u.clock.timeout; + } + if (has_timeout === 0 || cur_timeout < min_timeout) { + min_timeout = cur_timeout; + timer_userdata = sub.userdata; + has_timeout = 1; + } + break; + } + case 1 /* WasiEventType.FD_READ */: + case 2 /* WasiEventType.FD_WRITE */: + fdevents.push(sub); + break; + default: return 28 /* WasiErrno.EINVAL */; + } + } + if (fdevents.length > 0) { + for (i = 0; i < fdevents.length; i++) { + const fdevent = fdevents[i]; + const event = out_ptr + 32 * i; + view.setBigUint64(event, fdevent.userdata, true); + view.setUint32(event + 8, 52 /* WasiErrno.ENOSYS */, true); + view.setUint32(event + 12, fdevent.type, true); + view.setBigUint64(event + 16, BigInt(0), true); + view.setUint16(event + 24, 0, true); + view.setUint32(nevents, 1, true); + } + view.setUint32(nevents, fdevents.length, true); + return 0 /* WasiErrno.ESUCCESS */; + } + if (has_timeout) { + const delay = Number(min_timeout / BigInt(1000000)); + // if (isMainThread || typeof SharedArrayBuffer !== 'function') { + sleepBreakIf(delay, () => false); + // } else { + // const buf = new SharedArrayBuffer(4) + // const arr = new Int32Array(buf) + // postMsg({ + // __tybys_wasm_util_wasi__: { + // type: 'set-timeout', + // payload: { + // buffer: buf, + // delay + // } + // } + // }) + // Atomics.wait(arr, 0, 0) + // } + const event = out_ptr; + view.setBigUint64(event, timer_userdata, true); + view.setUint32(event + 8, 0 /* WasiErrno.ESUCCESS */, true); + view.setUint32(event + 12, 0 /* WasiEventType.CLOCK */, true); + view.setUint32(nevents, 1, true); + } + return 0 /* WasiErrno.ESUCCESS */; + }); + this.proc_exit = syscallWrap(this, 'proc_exit', function (rval) { + if ((typeof process === 'object') && (process !== null) && (typeof process.exit === 'function')) { + process.exit(rval); + } + return 0 /* WasiErrno.ESUCCESS */; + }); + this.proc_raise = syscallWrap(this, 'proc_raise', function (_sig) { + return 52 /* WasiErrno.ENOSYS */; + }); + this.sched_yield = syscallWrap(this, 'sched_yield', function () { + return 0 /* WasiErrno.ESUCCESS */; + }); + this.random_get = typeof crypto !== 'undefined' && typeof crypto.getRandomValues === 'function' + ? syscallWrap(this, 'random_get', function (buf, buf_len) { + buf = Number(buf); + if (buf === 0) { + return 28 /* WasiErrno.EINVAL */; + } + buf_len = Number(buf_len); + const { HEAPU8, view } = getMemory(this, buf + buf_len); + if ((typeof SharedArrayBuffer === 'function' && HEAPU8.buffer instanceof SharedArrayBuffer) || + (Object.prototype.toString.call(HEAPU8.buffer) === '[object SharedArrayBuffer]')) { + for (let i = buf; i < buf + buf_len; ++i) { + view.setUint8(i, Math.floor(Math.random() * 256)); + } + return 0 /* WasiErrno.ESUCCESS */; + } + let pos; + const stride = 65536; + for (pos = 0; pos + stride < buf_len; pos += stride) { + crypto.getRandomValues(HEAPU8.subarray(buf + pos, buf + pos + stride)); + } + crypto.getRandomValues(HEAPU8.subarray(buf + pos, buf + buf_len)); + return 0 /* WasiErrno.ESUCCESS */; + }) + : syscallWrap(this, 'random_get', function (buf, buf_len) { + buf = Number(buf); + if (buf === 0) { + return 28 /* WasiErrno.EINVAL */; + } + buf_len = Number(buf_len); + const { view } = getMemory(this, buf + buf_len); + for (let i = buf; i < buf + buf_len; ++i) { + view.setUint8(i, Math.floor(Math.random() * 256)); + } + return 0 /* WasiErrno.ESUCCESS */; + }); + this.sock_recv = syscallWrap(this, 'sock_recv', function () { + return 58 /* WasiErrno.ENOTSUP */; + }); + this.sock_send = syscallWrap(this, 'sock_send', function () { + return 58 /* WasiErrno.ENOTSUP */; + }); + this.sock_shutdown = syscallWrap(this, 'sock_shutdown', function () { + return 58 /* WasiErrno.ENOTSUP */; + }); + this.sock_accept = syscallWrap(this, 'sock_accept', function () { + return 58 /* WasiErrno.ENOTSUP */; + }); + _wasi.set(this, { + fds, + args, + env + }); + if (fs) + _fs.set(this, fs); + // eslint-disable-next-line @typescript-eslint/no-this-alias + const _this = this; + function defineImport(name, syncVersion, asyncVersion, parameterType, returnType) { + if (asyncFs) { + if (asyncify) { + _this[name] = asyncify.wrapImportFunction(syscallWrap(_this, name, asyncVersion)); + } + else { + _this[name] = wrapAsyncImport(syscallWrap(_this, name, asyncVersion), parameterType, returnType); + } + } + else { + _this[name] = syscallWrap(_this, name, syncVersion); + } + } + defineImport('fd_allocate', function fd_allocate(fd, offset, len) { + const wasi = _wasi.get(this); + const fs = getFs(this); + const fileDescriptor = wasi.fds.get(fd, WasiRights.FD_ALLOCATE, BigInt(0)); + const stat = fs.fstatSync(fileDescriptor.fd, { bigint: true }); + if (stat.size < offset + len) { + fs.ftruncateSync(fileDescriptor.fd, Number(offset + len)); + } + return 0 /* WasiErrno.ESUCCESS */; + }, async function fd_allocate(fd, offset, len) { + const wasi = _wasi.get(this); + const fileDescriptor = wasi.fds.get(fd, WasiRights.FD_ALLOCATE, BigInt(0)); + const h = fileDescriptor.fd; + const stat = await h.stat({ bigint: true }); + if (stat.size < offset + len) { + await h.truncate(Number(offset + len)); + } + return 0 /* WasiErrno.ESUCCESS */; + }, ['i32', 'i64', 'f64'], ['i32']); + defineImport('fd_close', function fd_close(fd) { + const wasi = _wasi.get(this); + const fileDescriptor = wasi.fds.get(fd, BigInt(0), BigInt(0)); + const fs = getFs(this); + fs.closeSync(fileDescriptor.fd); + wasi.fds.remove(fd); + return 0 /* WasiErrno.ESUCCESS */; + }, async function fd_close(fd) { + const wasi = _wasi.get(this); + const fileDescriptor = wasi.fds.get(fd, BigInt(0), BigInt(0)); + await fileDescriptor.fd.close(); + wasi.fds.remove(fd); + return 0 /* WasiErrno.ESUCCESS */; + }, ['i32'], ['i32']); + defineImport('fd_datasync', function fd_datasync(fd) { + const wasi = _wasi.get(this); + const fileDescriptor = wasi.fds.get(fd, WasiRights.FD_DATASYNC, BigInt(0)); + const fs = getFs(this); + fs.fdatasyncSync(fileDescriptor.fd); + return 0 /* WasiErrno.ESUCCESS */; + }, async function fd_datasync(fd) { + const wasi = _wasi.get(this); + const fileDescriptor = wasi.fds.get(fd, WasiRights.FD_DATASYNC, BigInt(0)); + await fileDescriptor.fd.datasync(); + return 0 /* WasiErrno.ESUCCESS */; + }, ['i32'], ['i32']); + defineImport('fd_filestat_get', function fd_filestat_get(fd, buf) { + buf = Number(buf); + if (buf === 0) + return 28 /* WasiErrno.EINVAL */; + const wasi = _wasi.get(this); + const fileDescriptor = wasi.fds.get(fd, WasiRights.FD_FILESTAT_GET, BigInt(0)); + const fs = getFs(this); + const stat = fs.fstatSync(fileDescriptor.fd, { bigint: true }); + const { view } = getMemory(this, buf + 64); + toFileStat(view, buf, stat); + return 0 /* WasiErrno.ESUCCESS */; + }, async function fd_filestat_get(fd, buf) { + buf = Number(buf); + if (buf === 0) + return 28 /* WasiErrno.EINVAL */; + const wasi = _wasi.get(this); + const fileDescriptor = wasi.fds.get(fd, WasiRights.FD_FILESTAT_GET, BigInt(0)); + const h = fileDescriptor.fd; + const stat = await h.stat({ bigint: true }); + const { view } = getMemory(this, buf + 64); + toFileStat(view, buf, stat); + return 0 /* WasiErrno.ESUCCESS */; + }, ['i32', 'i32'], ['i32']); + defineImport('fd_filestat_set_size', function fd_filestat_set_size(fd, size) { + const wasi = _wasi.get(this); + const fileDescriptor = wasi.fds.get(fd, WasiRights.FD_FILESTAT_SET_SIZE, BigInt(0)); + const fs = getFs(this); + fs.ftruncateSync(fileDescriptor.fd, Number(size)); + return 0 /* WasiErrno.ESUCCESS */; + }, async function fd_filestat_set_size(fd, size) { + const wasi = _wasi.get(this); + const fileDescriptor = wasi.fds.get(fd, WasiRights.FD_FILESTAT_SET_SIZE, BigInt(0)); + const h = fileDescriptor.fd; + await h.truncate(Number(size)); + return 0 /* WasiErrno.ESUCCESS */; + }, ['i32', 'i64'], ['i32']); + function fdFilestatGetTimes(fd, atim, mtim, flags) { + const wasi = _wasi.get(this); + const fileDescriptor = wasi.fds.get(fd, WasiRights.FD_FILESTAT_SET_TIMES, BigInt(0)); + if ((flags & 2 /* WasiFstFlag.SET_ATIM_NOW */) === 2 /* WasiFstFlag.SET_ATIM_NOW */) { + atim = BigInt(Date.now() * 1000000); + } + if ((flags & 8 /* WasiFstFlag.SET_MTIM_NOW */) === 8 /* WasiFstFlag.SET_MTIM_NOW */) { + mtim = BigInt(Date.now() * 1000000); + } + return { fileDescriptor, atim, mtim }; + } + defineImport('fd_filestat_set_times', function fd_filestat_set_times(fd, atim, mtim, flags) { + if (validateFstFlagsOrReturn(flags)) { + return 28 /* WasiErrno.EINVAL */; + } + const { fileDescriptor, atim: atimRes, mtim: mtimRes } = fdFilestatGetTimes.call(this, fd, atim, mtim, flags); + const fs = getFs(this); + fs.futimesSync(fileDescriptor.fd, Number(atimRes), Number(mtimRes)); + return 0 /* WasiErrno.ESUCCESS */; + }, async function fd_filestat_set_times(fd, atim, mtim, flags) { + if (validateFstFlagsOrReturn(flags)) { + return 28 /* WasiErrno.EINVAL */; + } + const { fileDescriptor, atim: atimRes, mtim: mtimRes } = fdFilestatGetTimes.call(this, fd, atim, mtim, flags); + const h = fileDescriptor.fd; + await h.utimes(Number(atimRes), Number(mtimRes)); + return 0 /* WasiErrno.ESUCCESS */; + }, ['i32', 'i64', 'i64', 'i32'], ['i32']); + defineImport('fd_pread', function fd_pread(fd, iovs, iovslen, offset, size) { + iovs = Number(iovs); + size = Number(size); + if ((iovs === 0 && iovslen) || size === 0 || offset > INT64_MAX) { + return 28 /* WasiErrno.EINVAL */; + } + const { HEAPU8, view } = getMemory(this, Math.max(iovs + Number(iovslen) * 8, size + 4)); + const wasi = _wasi.get(this); + const fileDescriptor = wasi.fds.get(fd, WasiRights.FD_READ | WasiRights.FD_SEEK, BigInt(0)); + if (!iovslen) { + view.setUint32(size, 0, true); + return 0 /* WasiErrno.ESUCCESS */; + } + let totalSize = 0; + const ioVecs = Array.from({ length: Number(iovslen) }, (_, i) => { + const offset = iovs + (i * 8); + const buf = view.getInt32(offset, true); + const bufLen = view.getUint32(offset + 4, true); + totalSize += bufLen; + return HEAPU8.subarray(buf, buf + bufLen); + }); + let nread = 0; + const buffer = (() => { + try { + return new Uint8Array(new SharedArrayBuffer(totalSize)); + } + catch (_) { + return new Uint8Array(totalSize); + } + })(); + buffer._isBuffer = true; + const fs = getFs(this); + const bytesRead = fs.readSync(fileDescriptor.fd, buffer, 0, buffer.length, Number(offset)); + nread = buffer ? copyMemory(ioVecs, buffer.subarray(0, bytesRead)) : 0; + view.setUint32(size, nread, true); + return 0 /* WasiErrno.ESUCCESS */; + }, async function (fd, iovs, iovslen, offset, size) { + iovs = Number(iovs); + size = Number(size); + if ((iovs === 0 && iovslen) || size === 0 || offset > INT64_MAX) { + return 28 /* WasiErrno.EINVAL */; + } + const { HEAPU8, view } = getMemory(this, Math.max(iovs + Number(iovslen) * 8, size + 4)); + const wasi = _wasi.get(this); + const fileDescriptor = wasi.fds.get(fd, WasiRights.FD_READ | WasiRights.FD_SEEK, BigInt(0)); + if (!iovslen) { + view.setUint32(size, 0, true); + return 0 /* WasiErrno.ESUCCESS */; + } + let totalSize = 0; + const ioVecs = Array.from({ length: Number(iovslen) }, (_, i) => { + const offset = iovs + (i * 8); + const buf = view.getInt32(offset, true); + const bufLen = view.getUint32(offset + 4, true); + totalSize += bufLen; + return HEAPU8.subarray(buf, buf + bufLen); + }); + let nread = 0; + const buffer = new Uint8Array(totalSize); + buffer._isBuffer = true; + const { bytesRead } = await fileDescriptor.fd.read(buffer, 0, buffer.length, Number(offset)); + nread = buffer ? copyMemory(ioVecs, buffer.subarray(0, bytesRead)) : 0; + view.setUint32(size, nread, true); + return 0 /* WasiErrno.ESUCCESS */; + }, ['i32', 'i32', 'i32', 'i64', 'i32'], ['i32']); + defineImport('fd_pwrite', function fd_pwrite(fd, iovs, iovslen, offset, size) { + iovs = Number(iovs); + size = Number(size); + if ((iovs === 0 && iovslen) || size === 0 || offset > INT64_MAX) { + return 28 /* WasiErrno.EINVAL */; + } + const { HEAPU8, view } = getMemory(this, Math.max(iovs + Number(iovslen) * 8, size + 4)); + const wasi = _wasi.get(this); + const fileDescriptor = wasi.fds.get(fd, WasiRights.FD_WRITE | WasiRights.FD_SEEK, BigInt(0)); + if (!iovslen) { + view.setUint32(size, 0, true); + return 0 /* WasiErrno.ESUCCESS */; + } + const buffer = concatBuffer(Array.from({ length: Number(iovslen) }, (_, i) => { + const offset = iovs + (i * 8); + const buf = view.getInt32(offset, true); + const bufLen = view.getUint32(offset + 4, true); + return HEAPU8.subarray(buf, buf + bufLen); + })); + const fs = getFs(this); + const nwritten = fs.writeSync(fileDescriptor.fd, buffer, 0, buffer.length, Number(offset)); + view.setUint32(size, nwritten, true); + return 0 /* WasiErrno.ESUCCESS */; + }, async function fd_pwrite(fd, iovs, iovslen, offset, size) { + iovs = Number(iovs); + size = Number(size); + if ((iovs === 0 && iovslen) || size === 0 || offset > INT64_MAX) { + return 28 /* WasiErrno.EINVAL */; + } + const { HEAPU8, view } = getMemory(this, Math.max(iovs + Number(iovslen) * 8, size + 4)); + const wasi = _wasi.get(this); + const fileDescriptor = wasi.fds.get(fd, WasiRights.FD_WRITE | WasiRights.FD_SEEK, BigInt(0)); + if (!iovslen) { + view.setUint32(size, 0, true); + return 0 /* WasiErrno.ESUCCESS */; + } + const buffer = concatBuffer(Array.from({ length: Number(iovslen) }, (_, i) => { + const offset = iovs + (i * 8); + const buf = view.getInt32(offset, true); + const bufLen = view.getUint32(offset + 4, true); + return HEAPU8.subarray(buf, buf + bufLen); + })); + const { bytesWritten } = await fileDescriptor.fd.write(buffer, 0, buffer.length, Number(offset)); + view.setUint32(size, bytesWritten, true); + return 0 /* WasiErrno.ESUCCESS */; + }, ['i32', 'i32', 'i32', 'i64', 'i32'], ['i32']); + defineImport('fd_read', function fd_read(fd, iovs, iovslen, size) { + iovs = Number(iovs); + size = Number(size); + if ((iovs === 0 && iovslen) || size === 0) { + return 28 /* WasiErrno.EINVAL */; + } + const { HEAPU8, view } = getMemory(this, Math.max(iovs + Number(iovslen) * 8, size + 4)); + const wasi = _wasi.get(this); + const fileDescriptor = wasi.fds.get(fd, WasiRights.FD_READ, BigInt(0)); + if (!iovslen) { + view.setUint32(size, 0, true); + return 0 /* WasiErrno.ESUCCESS */; + } + let totalSize = 0; + const ioVecs = Array.from({ length: Number(iovslen) }, (_, i) => { + const offset = iovs + (i * 8); + const buf = view.getInt32(offset, true); + const bufLen = view.getUint32(offset + 4, true); + totalSize += bufLen; + return HEAPU8.subarray(buf, buf + bufLen); + }); + let buffer; + let nread = 0; + if (fd === 0) { + if (typeof window === 'undefined' || typeof window.prompt !== 'function') { + return 58 /* WasiErrno.ENOTSUP */; + } + buffer = readStdin(); + nread = buffer ? copyMemory(ioVecs, buffer) : 0; + } + else { + buffer = (() => { + try { + return new Uint8Array(new SharedArrayBuffer(totalSize)); + } + catch (_) { + return new Uint8Array(totalSize); + } + })(); + buffer._isBuffer = true; + const fs = getFs(this); + const bytesRead = fs.readSync(fileDescriptor.fd, buffer, 0, buffer.length, Number(fileDescriptor.pos)); + nread = buffer ? copyMemory(ioVecs, buffer.subarray(0, bytesRead)) : 0; + fileDescriptor.pos += BigInt(nread); + } + view.setUint32(size, nread, true); + return 0 /* WasiErrno.ESUCCESS */; + }, async function fd_read(fd, iovs, iovslen, size) { + iovs = Number(iovs); + size = Number(size); + if ((iovs === 0 && iovslen) || size === 0) { + return 28 /* WasiErrno.EINVAL */; + } + const { HEAPU8, view } = getMemory(this, Math.max(iovs + Number(iovslen) * 8, size + 4)); + const wasi = _wasi.get(this); + const fileDescriptor = wasi.fds.get(fd, WasiRights.FD_READ, BigInt(0)); + if (!iovslen) { + view.setUint32(size, 0, true); + return 0 /* WasiErrno.ESUCCESS */; + } + let totalSize = 0; + const ioVecs = Array.from({ length: Number(iovslen) }, (_, i) => { + const offset = iovs + (i * 8); + const buf = view.getInt32(offset, true); + const bufLen = view.getUint32(offset + 4, true); + totalSize += bufLen; + return HEAPU8.subarray(buf, buf + bufLen); + }); + let buffer; + let nread = 0; + if (fd === 0) { + if (typeof window === 'undefined' || typeof window.prompt !== 'function') { + return 58 /* WasiErrno.ENOTSUP */; + } + buffer = readStdin(); + nread = buffer ? copyMemory(ioVecs, buffer) : 0; + } + else { + buffer = new Uint8Array(totalSize); + buffer._isBuffer = true; + const { bytesRead } = await fileDescriptor.fd.read(buffer, 0, buffer.length, Number(fileDescriptor.pos)); + nread = buffer ? copyMemory(ioVecs, buffer.subarray(0, bytesRead)) : 0; + fileDescriptor.pos += BigInt(nread); + } + view.setUint32(size, nread, true); + return 0 /* WasiErrno.ESUCCESS */; + }, ['i32', 'i32', 'i32', 'i32'], ['i32']); + defineImport('fd_readdir', function fd_readdir(fd, buf, buf_len, cookie, bufused) { + buf = Number(buf); + buf_len = Number(buf_len); + bufused = Number(bufused); + if (buf === 0 || bufused === 0) + return 0 /* WasiErrno.ESUCCESS */; + const wasi = _wasi.get(this); + const fileDescriptor = wasi.fds.get(fd, WasiRights.FD_READDIR, BigInt(0)); + const fs = getFs(this); + const entries = fs.readdirSync(fileDescriptor.realPath, { withFileTypes: true }); + const { HEAPU8, view } = getMemory(this, Math.max(buf + buf_len, bufused + 4)); + let bufferUsed = 0; + for (let i = Number(cookie); i < entries.length; i++) { + const nameData = encoder.encode(entries[i].name); + const entryInfo = fs.statSync(resolve(fileDescriptor.realPath, entries[i].name), { bigint: true }); + const entryData = new Uint8Array(24 + nameData.byteLength); + const entryView = new DataView(entryData.buffer); + entryView.setBigUint64(0, BigInt(i + 1), true); + entryView.setBigUint64(8, BigInt(entryInfo.ino ? entryInfo.ino : 0), true); + entryView.setUint32(16, nameData.byteLength, true); + let type; + if (entries[i].isFile()) { + type = 4 /* WasiFileType.REGULAR_FILE */; + } + else if (entries[i].isDirectory()) { + type = 3 /* WasiFileType.DIRECTORY */; + } + else if (entries[i].isSymbolicLink()) { + type = 7 /* WasiFileType.SYMBOLIC_LINK */; + } + else if (entries[i].isCharacterDevice()) { + type = 2 /* WasiFileType.CHARACTER_DEVICE */; + } + else if (entries[i].isBlockDevice()) { + type = 1 /* WasiFileType.BLOCK_DEVICE */; + } + else if (entries[i].isSocket()) { + type = 6 /* WasiFileType.SOCKET_STREAM */; + } + else { + type = 0 /* WasiFileType.UNKNOWN */; + } + entryView.setUint8(20, type); + entryData.set(nameData, 24); + const data = entryData.slice(0, Math.min(entryData.length, buf_len - bufferUsed)); + HEAPU8.set(data, buf + bufferUsed); + bufferUsed += data.byteLength; + } + view.setUint32(bufused, bufferUsed, true); + return 0 /* WasiErrno.ESUCCESS */; + }, async function fd_readdir(fd, buf, buf_len, cookie, bufused) { + buf = Number(buf); + buf_len = Number(buf_len); + bufused = Number(bufused); + if (buf === 0 || bufused === 0) + return 0 /* WasiErrno.ESUCCESS */; + const wasi = _wasi.get(this); + const fileDescriptor = wasi.fds.get(fd, WasiRights.FD_READDIR, BigInt(0)); + const fs = getFs(this); + const entries = await fs.promises.readdir(fileDescriptor.realPath, { withFileTypes: true }); + const { HEAPU8, view } = getMemory(this, Math.max(buf + buf_len, bufused + 4)); + let bufferUsed = 0; + for (let i = Number(cookie); i < entries.length; i++) { + const nameData = encoder.encode(entries[i].name); + const entryInfo = await fs.promises.stat(resolve(fileDescriptor.realPath, entries[i].name), { bigint: true }); + const entryData = new Uint8Array(24 + nameData.byteLength); + const entryView = new DataView(entryData.buffer); + entryView.setBigUint64(0, BigInt(i + 1), true); + entryView.setBigUint64(8, BigInt(entryInfo.ino ? entryInfo.ino : 0), true); + entryView.setUint32(16, nameData.byteLength, true); + let type; + if (entries[i].isFile()) { + type = 4 /* WasiFileType.REGULAR_FILE */; + } + else if (entries[i].isDirectory()) { + type = 3 /* WasiFileType.DIRECTORY */; + } + else if (entries[i].isSymbolicLink()) { + type = 7 /* WasiFileType.SYMBOLIC_LINK */; + } + else if (entries[i].isCharacterDevice()) { + type = 2 /* WasiFileType.CHARACTER_DEVICE */; + } + else if (entries[i].isBlockDevice()) { + type = 1 /* WasiFileType.BLOCK_DEVICE */; + } + else if (entries[i].isSocket()) { + type = 6 /* WasiFileType.SOCKET_STREAM */; + } + else { + type = 0 /* WasiFileType.UNKNOWN */; + } + entryView.setUint8(20, type); + entryData.set(nameData, 24); + const data = entryData.slice(0, Math.min(entryData.length, buf_len - bufferUsed)); + HEAPU8.set(data, buf + bufferUsed); + bufferUsed += data.byteLength; + } + view.setUint32(bufused, bufferUsed, true); + return 0 /* WasiErrno.ESUCCESS */; + }, ['i32', 'i32', 'i32', 'i64', 'i32'], ['i32']); + defineImport('fd_renumber', function fd_renumber(from, to) { + const wasi = _wasi.get(this); + wasi.fds.renumber(to, from); + return 0 /* WasiErrno.ESUCCESS */; + }, async function fd_renumber(from, to) { + const wasi = _wasi.get(this); + await wasi.fds.renumber(to, from); + return 0 /* WasiErrno.ESUCCESS */; + }, ['i32', 'i32'], ['i32']); + defineImport('fd_sync', function fd_sync(fd) { + const wasi = _wasi.get(this); + const fileDescriptor = wasi.fds.get(fd, WasiRights.FD_SYNC, BigInt(0)); + const fs = getFs(this); + fs.fsyncSync(fileDescriptor.fd); + return 0 /* WasiErrno.ESUCCESS */; + }, async function fd_sync(fd) { + const wasi = _wasi.get(this); + const fileDescriptor = wasi.fds.get(fd, WasiRights.FD_SYNC, BigInt(0)); + await fileDescriptor.fd.sync(); + return 0 /* WasiErrno.ESUCCESS */; + }, ['i32'], ['i32']); + defineImport('fd_write', function fd_write(fd, iovs, iovslen, size) { + iovs = Number(iovs); + size = Number(size); + if ((iovs === 0 && iovslen) || size === 0) { + return 28 /* WasiErrno.EINVAL */; + } + const { HEAPU8, view } = getMemory(this, Math.max(iovs + Number(iovslen) * 8, size + 4)); + const wasi = _wasi.get(this); + const fileDescriptor = wasi.fds.get(fd, WasiRights.FD_WRITE, BigInt(0)); + if (!iovslen) { + view.setUint32(size, 0, true); + return 0 /* WasiErrno.ESUCCESS */; + } + const buffer = concatBuffer(Array.from({ length: Number(iovslen) }, (_, i) => { + const offset = iovs + (i * 8); + const buf = view.getInt32(offset, true); + const bufLen = view.getUint32(offset + 4, true); + return HEAPU8.subarray(buf, buf + bufLen); + })); + let nwritten; + if (fd === 1 || fd === 2) { + nwritten = fileDescriptor.write(buffer); + } + else { + const fs = getFs(this); + nwritten = fs.writeSync(fileDescriptor.fd, buffer, 0, buffer.length, Number(fileDescriptor.pos)); + fileDescriptor.pos += BigInt(nwritten); + } + view.setUint32(size, nwritten, true); + return 0 /* WasiErrno.ESUCCESS */; + }, async function fd_write(fd, iovs, iovslen, size) { + iovs = Number(iovs); + size = Number(size); + if ((iovs === 0 && iovslen) || size === 0) { + return 28 /* WasiErrno.EINVAL */; + } + const { HEAPU8, view } = getMemory(this, Math.max(iovs + Number(iovslen) * 8, size + 4)); + const wasi = _wasi.get(this); + const fileDescriptor = wasi.fds.get(fd, WasiRights.FD_WRITE, BigInt(0)); + if (!iovslen) { + view.setUint32(size, 0, true); + return 0 /* WasiErrno.ESUCCESS */; + } + const buffer = concatBuffer(Array.from({ length: Number(iovslen) }, (_, i) => { + const offset = iovs + (i * 8); + const buf = view.getInt32(offset, true); + const bufLen = view.getUint32(offset + 4, true); + return HEAPU8.subarray(buf, buf + bufLen); + })); + let nwritten; + if (fd === 1 || fd === 2) { + nwritten = fileDescriptor.write(buffer); + } + else { + nwritten = await (await (fileDescriptor.fd.write(buffer, 0, buffer.length, Number(fileDescriptor.pos)))).bytesWritten; + fileDescriptor.pos += BigInt(nwritten); + } + view.setUint32(size, nwritten, true); + return 0 /* WasiErrno.ESUCCESS */; + }, ['i32', 'i32', 'i32', 'i32'], ['i32']); + defineImport('path_create_directory', function path_create_directory(fd, path, path_len) { + path = Number(path); + path_len = Number(path_len); + if (path === 0) { + return 28 /* WasiErrno.EINVAL */; + } + const { HEAPU8 } = getMemory(this, path + path_len); + const wasi = _wasi.get(this); + const fileDescriptor = wasi.fds.get(fd, WasiRights.PATH_CREATE_DIRECTORY, BigInt(0)); + let pathString = decoder.decode(unsharedSlice(HEAPU8, path, path + path_len)); + pathString = resolve(fileDescriptor.realPath, pathString); + const fs = getFs(this); + fs.mkdirSync(pathString); + return 0 /* WasiErrno.ESUCCESS */; + }, async function path_create_directory(fd, path, path_len) { + path = Number(path); + path_len = Number(path_len); + if (path === 0) { + return 28 /* WasiErrno.EINVAL */; + } + const { HEAPU8 } = getMemory(this, path + path_len); + const wasi = _wasi.get(this); + const fileDescriptor = wasi.fds.get(fd, WasiRights.PATH_CREATE_DIRECTORY, BigInt(0)); + let pathString = decoder.decode(unsharedSlice(HEAPU8, path, path + path_len)); + pathString = resolve(fileDescriptor.realPath, pathString); + const fs = getFs(this); + await fs.promises.mkdir(pathString); + return 0 /* WasiErrno.ESUCCESS */; + }, ['i32', 'i32', 'i32'], ['i32']); + defineImport('path_filestat_get', function path_filestat_get(fd, flags, path, path_len, filestat) { + path = Number(path); + path_len = Number(path_len); + filestat = Number(filestat); + if (path === 0 || filestat === 0) { + return 28 /* WasiErrno.EINVAL */; + } + const { HEAPU8, view } = getMemory(this, Math.max(path + path_len, filestat + 64)); + const wasi = _wasi.get(this); + const fileDescriptor = wasi.fds.get(fd, WasiRights.PATH_FILESTAT_GET, BigInt(0)); + let pathString = decoder.decode(unsharedSlice(HEAPU8, path, path + path_len)); + const fs = getFs(this); + pathString = resolve(fileDescriptor.realPath, pathString); + let stat; + if ((flags & 1) === 1) { + stat = fs.statSync(pathString, { bigint: true }); + } + else { + stat = fs.lstatSync(pathString, { bigint: true }); + } + toFileStat(view, filestat, stat); + return 0 /* WasiErrno.ESUCCESS */; + }, async function path_filestat_get(fd, flags, path, path_len, filestat) { + path = Number(path); + path_len = Number(path_len); + filestat = Number(filestat); + if (path === 0 || filestat === 0) { + return 28 /* WasiErrno.EINVAL */; + } + const { HEAPU8, view } = getMemory(this, Math.max(path + path_len, filestat + 64)); + const wasi = _wasi.get(this); + const fileDescriptor = wasi.fds.get(fd, WasiRights.PATH_FILESTAT_GET, BigInt(0)); + let pathString = decoder.decode(unsharedSlice(HEAPU8, path, path + path_len)); + const fs = getFs(this); + pathString = resolve(fileDescriptor.realPath, pathString); + let stat; + if ((flags & 1) === 1) { + stat = await fs.promises.stat(pathString, { bigint: true }); + } + else { + stat = await fs.promises.lstat(pathString, { bigint: true }); + } + toFileStat(view, filestat, stat); + return 0 /* WasiErrno.ESUCCESS */; + }, ['i32', 'i32', 'i32', 'i32', 'i32'], ['i32']); + defineImport('path_filestat_set_times', function path_filestat_set_times(fd, flags, path, path_len, atim, mtim, fst_flags) { + path = Number(path); + path_len = Number(path_len); + if (path === 0) + return 28 /* WasiErrno.EINVAL */; + const { HEAPU8 } = getMemory(this, path + path_len); + const wasi = _wasi.get(this); + const fileDescriptor = wasi.fds.get(fd, WasiRights.PATH_FILESTAT_SET_TIMES, BigInt(0)); + if (validateFstFlagsOrReturn(fst_flags)) { + return 28 /* WasiErrno.EINVAL */; + } + const fs = getFs(this); + const resolvedPath = resolvePathSync(fs, fileDescriptor, decoder.decode(unsharedSlice(HEAPU8, path, path + path_len)), flags); + if ((fst_flags & 2 /* WasiFstFlag.SET_ATIM_NOW */) === 2 /* WasiFstFlag.SET_ATIM_NOW */) { + atim = BigInt(Date.now() * 1000000); + } + if ((fst_flags & 8 /* WasiFstFlag.SET_MTIM_NOW */) === 8 /* WasiFstFlag.SET_MTIM_NOW */) { + mtim = BigInt(Date.now() * 1000000); + } + fs.utimesSync(resolvedPath, Number(atim), Number(mtim)); + return 0 /* WasiErrno.ESUCCESS */; + }, async function path_filestat_set_times(fd, flags, path, path_len, atim, mtim, fst_flags) { + path = Number(path); + path_len = Number(path_len); + if (path === 0) + return 28 /* WasiErrno.EINVAL */; + const { HEAPU8 } = getMemory(this, path + path_len); + const wasi = _wasi.get(this); + const fileDescriptor = wasi.fds.get(fd, WasiRights.PATH_FILESTAT_SET_TIMES, BigInt(0)); + if (validateFstFlagsOrReturn(fst_flags)) { + return 28 /* WasiErrno.EINVAL */; + } + const fs = getFs(this); + const resolvedPath = await resolvePathAsync(fs, fileDescriptor, decoder.decode(unsharedSlice(HEAPU8, path, path + path_len)), flags); + if ((fst_flags & 2 /* WasiFstFlag.SET_ATIM_NOW */) === 2 /* WasiFstFlag.SET_ATIM_NOW */) { + atim = BigInt(Date.now() * 1000000); + } + if ((fst_flags & 8 /* WasiFstFlag.SET_MTIM_NOW */) === 8 /* WasiFstFlag.SET_MTIM_NOW */) { + mtim = BigInt(Date.now() * 1000000); + } + await fs.promises.utimes(resolvedPath, Number(atim), Number(mtim)); + return 0 /* WasiErrno.ESUCCESS */; + }, ['i32', 'i32', 'i32', 'i32', 'i64', 'i64', 'i32'], ['i32']); + defineImport('path_link', function path_link(old_fd, old_flags, old_path, old_path_len, new_fd, new_path, new_path_len) { + old_path = Number(old_path); + old_path_len = Number(old_path_len); + new_path = Number(new_path); + new_path_len = Number(new_path_len); + if (old_path === 0 || new_path === 0) { + return 28 /* WasiErrno.EINVAL */; + } + const wasi = _wasi.get(this); + let oldWrap; + let newWrap; + if (old_fd === new_fd) { + oldWrap = newWrap = wasi.fds.get(old_fd, WasiRights.PATH_LINK_SOURCE | WasiRights.PATH_LINK_TARGET, BigInt(0)); + } + else { + oldWrap = wasi.fds.get(old_fd, WasiRights.PATH_LINK_SOURCE, BigInt(0)); + newWrap = wasi.fds.get(new_fd, WasiRights.PATH_LINK_TARGET, BigInt(0)); + } + const { HEAPU8 } = getMemory(this, Math.max(old_path + old_path_len, new_path + new_path_len)); + const fs = getFs(this); + const resolvedOldPath = resolvePathSync(fs, oldWrap, decoder.decode(unsharedSlice(HEAPU8, old_path, old_path + old_path_len)), old_flags); + const resolvedNewPath = resolve(newWrap.realPath, decoder.decode(unsharedSlice(HEAPU8, new_path, new_path + new_path_len))); + fs.linkSync(resolvedOldPath, resolvedNewPath); + return 0 /* WasiErrno.ESUCCESS */; + }, async function path_link(old_fd, old_flags, old_path, old_path_len, new_fd, new_path, new_path_len) { + old_path = Number(old_path); + old_path_len = Number(old_path_len); + new_path = Number(new_path); + new_path_len = Number(new_path_len); + if (old_path === 0 || new_path === 0) { + return 28 /* WasiErrno.EINVAL */; + } + const wasi = _wasi.get(this); + let oldWrap; + let newWrap; + if (old_fd === new_fd) { + oldWrap = newWrap = wasi.fds.get(old_fd, WasiRights.PATH_LINK_SOURCE | WasiRights.PATH_LINK_TARGET, BigInt(0)); + } + else { + oldWrap = wasi.fds.get(old_fd, WasiRights.PATH_LINK_SOURCE, BigInt(0)); + newWrap = wasi.fds.get(new_fd, WasiRights.PATH_LINK_TARGET, BigInt(0)); + } + const { HEAPU8 } = getMemory(this, Math.max(old_path + old_path_len, new_path + new_path_len)); + const fs = getFs(this); + const resolvedOldPath = await resolvePathAsync(fs, oldWrap, decoder.decode(unsharedSlice(HEAPU8, old_path, old_path + old_path_len)), old_flags); + const resolvedNewPath = resolve(newWrap.realPath, decoder.decode(unsharedSlice(HEAPU8, new_path, new_path + new_path_len))); + await fs.promises.link(resolvedOldPath, resolvedNewPath); + return 0 /* WasiErrno.ESUCCESS */; + }, ['i32', 'i32', 'i32', 'i32', 'i32', 'i32', 'i32'], ['i32']); + function pathOpen(o_flags, fs_rights_base, fs_rights_inheriting, fs_flags) { + const read = (fs_rights_base & (WasiRights.FD_READ | + WasiRights.FD_READDIR)) !== BigInt(0); + const write = (fs_rights_base & (WasiRights.FD_DATASYNC | + WasiRights.FD_WRITE | + WasiRights.FD_ALLOCATE | + WasiRights.FD_FILESTAT_SET_SIZE)) !== BigInt(0); + let flags = write ? read ? 2 /* FileControlFlag.O_RDWR */ : 1 /* FileControlFlag.O_WRONLY */ : 0 /* FileControlFlag.O_RDONLY */; + let needed_base = WasiRights.PATH_OPEN; + let needed_inheriting = fs_rights_base | fs_rights_inheriting; + if ((o_flags & 1 /* WasiFileControlFlag.O_CREAT */) !== 0) { + flags |= 64 /* FileControlFlag.O_CREAT */; + needed_base |= WasiRights.PATH_CREATE_FILE; + } + if ((o_flags & 2 /* WasiFileControlFlag.O_DIRECTORY */) !== 0) { + flags |= 65536 /* FileControlFlag.O_DIRECTORY */; + } + if ((o_flags & 4 /* WasiFileControlFlag.O_EXCL */) !== 0) { + flags |= 128 /* FileControlFlag.O_EXCL */; + } + if ((o_flags & 8 /* WasiFileControlFlag.O_TRUNC */) !== 0) { + flags |= 512 /* FileControlFlag.O_TRUNC */; + needed_base |= WasiRights.PATH_FILESTAT_SET_SIZE; + } + if ((fs_flags & 1 /* WasiFdFlag.APPEND */) !== 0) { + flags |= 1024 /* FileControlFlag.O_APPEND */; + } + if ((fs_flags & 2 /* WasiFdFlag.DSYNC */) !== 0) { + // flags |= FileControlFlag.O_DSYNC; + needed_inheriting |= WasiRights.FD_DATASYNC; + } + if ((fs_flags & 4 /* WasiFdFlag.NONBLOCK */) !== 0) { + flags |= 2048 /* FileControlFlag.O_NONBLOCK */; + } + if ((fs_flags & 8 /* WasiFdFlag.RSYNC */) !== 0) { + flags |= 1052672 /* FileControlFlag.O_SYNC */; + needed_inheriting |= WasiRights.FD_SYNC; + } + if ((fs_flags & 16 /* WasiFdFlag.SYNC */) !== 0) { + flags |= 1052672 /* FileControlFlag.O_SYNC */; + needed_inheriting |= WasiRights.FD_SYNC; + } + if (write && (flags & (1024 /* FileControlFlag.O_APPEND */ | 512 /* FileControlFlag.O_TRUNC */)) === 0) { + needed_inheriting |= WasiRights.FD_SEEK; + } + return { flags, needed_base, needed_inheriting }; + } + defineImport('path_open', function path_open(dirfd, dirflags, path, path_len, o_flags, fs_rights_base, fs_rights_inheriting, fs_flags, fd) { + path = Number(path); + fd = Number(fd); + if (path === 0 || fd === 0) { + return 28 /* WasiErrno.EINVAL */; + } + path_len = Number(path_len); + fs_rights_base = BigInt(fs_rights_base); + fs_rights_inheriting = BigInt(fs_rights_inheriting); + const { flags: flagsRes, needed_base: neededBase, needed_inheriting: neededInheriting } = pathOpen(o_flags, fs_rights_base, fs_rights_inheriting, fs_flags); + const wasi = _wasi.get(this); + const fileDescriptor = wasi.fds.get(dirfd, neededBase, neededInheriting); + const memory = getMemory(this, Math.max(path + path_len, fd + 4)); + const HEAPU8 = memory.HEAPU8; + const pathString = decoder.decode(unsharedSlice(HEAPU8, path, path + path_len)); + const fs = getFs(this); + const resolved_path = resolvePathSync(fs, fileDescriptor, pathString, dirflags); + const r = fs.openSync(resolved_path, _isWin32Flags ? _toWinOpenFlags(flagsRes) : flagsRes, 0o666); + const filetype = wasi.fds.getFileTypeByFd(r); + if ((filetype !== 3 /* WasiFileType.DIRECTORY */) && + ((o_flags & 2 /* WasiFileControlFlag.O_DIRECTORY */) !== 0 || + (resolved_path.endsWith('/')))) { + return 54 /* WasiErrno.ENOTDIR */; + } + const { base: max_base, inheriting: max_inheriting } = getRights(wasi.fds.stdio, r, flagsRes, filetype); + const wrap = wasi.fds.insert(r, resolved_path, resolved_path, filetype, fs_rights_base & max_base, fs_rights_inheriting & max_inheriting, 0); + const stat = fs.fstatSync(r, { bigint: true }); + if (stat.isFile()) { + wrap.size = stat.size; + if ((flagsRes & 1024 /* FileControlFlag.O_APPEND */) !== 0) { + wrap.pos = stat.size; + } + } + const view = memory.view; + view.setInt32(fd, wrap.id, true); + return 0 /* WasiErrno.ESUCCESS */; + }, async function path_open(dirfd, dirflags, path, path_len, o_flags, fs_rights_base, fs_rights_inheriting, fs_flags, fd) { + path = Number(path); + fd = Number(fd); + if (path === 0 || fd === 0) { + return 28 /* WasiErrno.EINVAL */; + } + path_len = Number(path_len); + fs_rights_base = BigInt(fs_rights_base); + fs_rights_inheriting = BigInt(fs_rights_inheriting); + const { flags: flagsRes, needed_base: neededBase, needed_inheriting: neededInheriting } = pathOpen(o_flags, fs_rights_base, fs_rights_inheriting, fs_flags); + const wasi = _wasi.get(this); + const fileDescriptor = wasi.fds.get(dirfd, neededBase, neededInheriting); + const memory = getMemory(this, Math.max(path + path_len, fd + 4)); + const HEAPU8 = memory.HEAPU8; + const pathString = decoder.decode(unsharedSlice(HEAPU8, path, path + path_len)); + const fs = getFs(this); + const resolved_path = await resolvePathAsync(fs, fileDescriptor, pathString, dirflags); + const r = await fs.promises.open(resolved_path, _isWin32Flags ? _toWinOpenFlags(flagsRes) : flagsRes, 0o666); + const filetype = await wasi.fds.getFileTypeByFd(r); + if ((o_flags & 2 /* WasiFileControlFlag.O_DIRECTORY */) !== 0 && filetype !== 3 /* WasiFileType.DIRECTORY */) { + return 54 /* WasiErrno.ENOTDIR */; + } + const { base: max_base, inheriting: max_inheriting } = getRights(wasi.fds.stdio, r.fd, flagsRes, filetype); + const wrap = wasi.fds.insert(r, resolved_path, resolved_path, filetype, fs_rights_base & max_base, fs_rights_inheriting & max_inheriting, 0); + const stat = await r.stat({ bigint: true }); + if (stat.isFile()) { + wrap.size = stat.size; + if ((flagsRes & 1024 /* FileControlFlag.O_APPEND */) !== 0) { + wrap.pos = stat.size; + } + } + const view = memory.view; + view.setInt32(fd, wrap.id, true); + return 0 /* WasiErrno.ESUCCESS */; + }, ['i32', 'i32', 'i32', 'i32', 'i32', 'i64', 'i64', 'i32', 'i32'], ['i32']); + defineImport('path_readlink', function path_readlink(fd, path, path_len, buf, buf_len, bufused) { + path = Number(path); + path_len = Number(path_len); + buf = Number(buf); + buf_len = Number(buf_len); + bufused = Number(bufused); + if (path === 0 || buf === 0 || bufused === 0) { + return 28 /* WasiErrno.EINVAL */; + } + const { HEAPU8, view } = getMemory(this, Math.max(path + path_len, buf + buf_len, bufused + 4)); + const wasi = _wasi.get(this); + const fileDescriptor = wasi.fds.get(fd, WasiRights.PATH_READLINK, BigInt(0)); + let pathString = decoder.decode(unsharedSlice(HEAPU8, path, path + path_len)); + pathString = resolve(fileDescriptor.realPath, pathString); + const fs = getFs(this); + const link = fs.readlinkSync(pathString); + const linkData = encoder.encode(link); + const len = Math.min(linkData.length, buf_len); + if (len >= buf_len) + return 42 /* WasiErrno.ENOBUFS */; + HEAPU8.set(linkData.subarray(0, len), buf); + HEAPU8[buf + len] = 0; + view.setUint32(bufused, len, true); + return 0 /* WasiErrno.ESUCCESS */; + }, async function path_readlink(fd, path, path_len, buf, buf_len, bufused) { + path = Number(path); + path_len = Number(path_len); + buf = Number(buf); + buf_len = Number(buf_len); + bufused = Number(bufused); + if (path === 0 || buf === 0 || bufused === 0) { + return 28 /* WasiErrno.EINVAL */; + } + const { HEAPU8, view } = getMemory(this, Math.max(path + path_len, buf + buf_len, bufused + 4)); + const wasi = _wasi.get(this); + const fileDescriptor = wasi.fds.get(fd, WasiRights.PATH_READLINK, BigInt(0)); + let pathString = decoder.decode(unsharedSlice(HEAPU8, path, path + path_len)); + pathString = resolve(fileDescriptor.realPath, pathString); + const fs = getFs(this); + const link = await fs.promises.readlink(pathString); + const linkData = encoder.encode(link); + const len = Math.min(linkData.length, buf_len); + if (len >= buf_len) + return 42 /* WasiErrno.ENOBUFS */; + HEAPU8.set(linkData.subarray(0, len), buf); + HEAPU8[buf + len] = 0; + view.setUint32(bufused, len, true); + return 0 /* WasiErrno.ESUCCESS */; + }, ['i32', 'i32', 'i32', 'i32', 'i32', 'i32'], ['i32']); + defineImport('path_remove_directory', function path_remove_directory(fd, path, path_len) { + path = Number(path); + path_len = Number(path_len); + if (path === 0) { + return 28 /* WasiErrno.EINVAL */; + } + const { HEAPU8 } = getMemory(this, path + path_len); + const wasi = _wasi.get(this); + const fileDescriptor = wasi.fds.get(fd, WasiRights.PATH_REMOVE_DIRECTORY, BigInt(0)); + let pathString = decoder.decode(unsharedSlice(HEAPU8, path, path + path_len)); + pathString = resolve(fileDescriptor.realPath, pathString); + const fs = getFs(this); + fs.rmdirSync(pathString); + return 0 /* WasiErrno.ESUCCESS */; + }, async function path_remove_directory(fd, path, path_len) { + path = Number(path); + path_len = Number(path_len); + if (path === 0) { + return 28 /* WasiErrno.EINVAL */; + } + const { HEAPU8 } = getMemory(this, path + path_len); + const wasi = _wasi.get(this); + const fileDescriptor = wasi.fds.get(fd, WasiRights.PATH_REMOVE_DIRECTORY, BigInt(0)); + let pathString = decoder.decode(unsharedSlice(HEAPU8, path, path + path_len)); + pathString = resolve(fileDescriptor.realPath, pathString); + const fs = getFs(this); + await fs.promises.rmdir(pathString); + return 0 /* WasiErrno.ESUCCESS */; + }, ['i32', 'i32', 'i32'], ['i32']); + defineImport('path_rename', function path_rename(old_fd, old_path, old_path_len, new_fd, new_path, new_path_len) { + old_path = Number(old_path); + old_path_len = Number(old_path_len); + new_path = Number(new_path); + new_path_len = Number(new_path_len); + if (old_path === 0 || new_path === 0) { + return 28 /* WasiErrno.EINVAL */; + } + const wasi = _wasi.get(this); + let oldWrap; + let newWrap; + if (old_fd === new_fd) { + oldWrap = newWrap = wasi.fds.get(old_fd, WasiRights.PATH_RENAME_SOURCE | WasiRights.PATH_RENAME_TARGET, BigInt(0)); + } + else { + oldWrap = wasi.fds.get(old_fd, WasiRights.PATH_RENAME_SOURCE, BigInt(0)); + newWrap = wasi.fds.get(new_fd, WasiRights.PATH_RENAME_TARGET, BigInt(0)); + } + const { HEAPU8 } = getMemory(this, Math.max(old_path + old_path_len, new_path + new_path_len)); + const resolvedOldPath = resolve(oldWrap.realPath, decoder.decode(unsharedSlice(HEAPU8, old_path, old_path + old_path_len))); + const resolvedNewPath = resolve(newWrap.realPath, decoder.decode(unsharedSlice(HEAPU8, new_path, new_path + new_path_len))); + const fs = getFs(this); + fs.renameSync(resolvedOldPath, resolvedNewPath); + return 0 /* WasiErrno.ESUCCESS */; + }, async function path_rename(old_fd, old_path, old_path_len, new_fd, new_path, new_path_len) { + old_path = Number(old_path); + old_path_len = Number(old_path_len); + new_path = Number(new_path); + new_path_len = Number(new_path_len); + if (old_path === 0 || new_path === 0) { + return 28 /* WasiErrno.EINVAL */; + } + const wasi = _wasi.get(this); + let oldWrap; + let newWrap; + if (old_fd === new_fd) { + oldWrap = newWrap = wasi.fds.get(old_fd, WasiRights.PATH_RENAME_SOURCE | WasiRights.PATH_RENAME_TARGET, BigInt(0)); + } + else { + oldWrap = wasi.fds.get(old_fd, WasiRights.PATH_RENAME_SOURCE, BigInt(0)); + newWrap = wasi.fds.get(new_fd, WasiRights.PATH_RENAME_TARGET, BigInt(0)); + } + const { HEAPU8 } = getMemory(this, Math.max(old_path + old_path_len, new_path + new_path_len)); + const resolvedOldPath = resolve(oldWrap.realPath, decoder.decode(unsharedSlice(HEAPU8, old_path, old_path + old_path_len))); + const resolvedNewPath = resolve(newWrap.realPath, decoder.decode(unsharedSlice(HEAPU8, new_path, new_path + new_path_len))); + const fs = getFs(this); + await fs.promises.rename(resolvedOldPath, resolvedNewPath); + return 0 /* WasiErrno.ESUCCESS */; + }, ['i32', 'i32', 'i32', 'i32', 'i32', 'i32'], ['i32']); + defineImport('path_symlink', function path_symlink(old_path, old_path_len, fd, new_path, new_path_len) { + old_path = Number(old_path); + old_path_len = Number(old_path_len); + new_path = Number(new_path); + new_path_len = Number(new_path_len); + if (old_path === 0 || new_path === 0) { + return 28 /* WasiErrno.EINVAL */; + } + const { HEAPU8 } = getMemory(this, Math.max(old_path + old_path_len, new_path + new_path_len)); + const wasi = _wasi.get(this); + const fileDescriptor = wasi.fds.get(fd, WasiRights.PATH_SYMLINK, BigInt(0)); + const oldPath = decoder.decode(unsharedSlice(HEAPU8, old_path, old_path + old_path_len)); + if (oldPath.length > 0 && oldPath[0] === '/') { + return 63 /* WasiErrno.EPERM */; + } + let newPath = decoder.decode(unsharedSlice(HEAPU8, new_path, new_path + new_path_len)); + newPath = resolve(fileDescriptor.realPath, newPath); + const fs = getFs(this); + fs.symlinkSync(oldPath, newPath); + return 0 /* WasiErrno.ESUCCESS */; + }, async function path_symlink(old_path, old_path_len, fd, new_path, new_path_len) { + old_path = Number(old_path); + old_path_len = Number(old_path_len); + new_path = Number(new_path); + new_path_len = Number(new_path_len); + if (old_path === 0 || new_path === 0) { + return 28 /* WasiErrno.EINVAL */; + } + const { HEAPU8 } = getMemory(this, Math.max(old_path + old_path_len, new_path + new_path_len)); + const wasi = _wasi.get(this); + const fileDescriptor = wasi.fds.get(fd, WasiRights.PATH_SYMLINK, BigInt(0)); + const oldPath = decoder.decode(unsharedSlice(HEAPU8, old_path, old_path + old_path_len)); + let newPath = decoder.decode(unsharedSlice(HEAPU8, new_path, new_path + new_path_len)); + newPath = resolve(fileDescriptor.realPath, newPath); + const fs = getFs(this); + await fs.promises.symlink(oldPath, newPath); + return 0 /* WasiErrno.ESUCCESS */; + }, ['i32', 'i32', 'i32', 'i32', 'i32'], ['i32']); + defineImport('path_unlink_file', function path_unlink_file(fd, path, path_len) { + path = Number(path); + path_len = Number(path_len); + if (path === 0) { + return 28 /* WasiErrno.EINVAL */; + } + const { HEAPU8 } = getMemory(this, path + path_len); + const wasi = _wasi.get(this); + const fileDescriptor = wasi.fds.get(fd, WasiRights.PATH_UNLINK_FILE, BigInt(0)); + let pathString = decoder.decode(unsharedSlice(HEAPU8, path, path + path_len)); + pathString = resolve(fileDescriptor.realPath, pathString); + const fs = getFs(this); + fs.unlinkSync(pathString); + return 0 /* WasiErrno.ESUCCESS */; + }, async function path_unlink_file(fd, path, path_len) { + path = Number(path); + path_len = Number(path_len); + if (path === 0) { + return 28 /* WasiErrno.EINVAL */; + } + const { HEAPU8 } = getMemory(this, path + path_len); + const wasi = _wasi.get(this); + const fileDescriptor = wasi.fds.get(fd, WasiRights.PATH_UNLINK_FILE, BigInt(0)); + let pathString = decoder.decode(unsharedSlice(HEAPU8, path, path + path_len)); + pathString = resolve(fileDescriptor.realPath, pathString); + const fs = getFs(this); + await fs.promises.unlink(pathString); + return 0 /* WasiErrno.ESUCCESS */; + }, ['i32', 'i32', 'i32'], ['i32']); + this._setMemory = function setMemory(m) { + if (!(m instanceof _WebAssembly.Memory)) { + throw new TypeError('"instance.exports.memory" property must be a WebAssembly.Memory'); + } + _memory.set(_this, extendMemory(m)); + }; + } + static createSync(args, env, preopens, stdio, fs, print, printErr) { + const fds = new SyncTable({ + size: 3, + in: stdio[0], + out: stdio[1], + err: stdio[2], + fs, + print, + printErr + }); + const _this = new WASI$1(args, env, fds, false, fs); + if (preopens.length > 0) { + for (let i = 0; i < preopens.length; ++i) { + const realPath = fs.realpathSync(preopens[i].realPath, 'utf8'); + const fd = fs.openSync(realPath, 'r', 0o666); + fds.insertPreopen(fd, preopens[i].mappedPath, realPath); + } + } + return _this; + } + static async createAsync(args, env, preopens, stdio, fs, print, printErr, asyncify) { + const fds = new AsyncTable({ + size: 3, + in: stdio[0], + out: stdio[1], + err: stdio[2], + print, + printErr + }); + const _this = new WASI$1(args, env, fds, true, fs, asyncify); + if (preopens.length > 0) { + for (let i = 0; i < preopens.length; ++i) { + const entry = preopens[i]; + const realPath = await fs.promises.realpath(entry.realPath); + const fd = await fs.promises.open(realPath, 'r', 0o666); + await fds.insertPreopen(fd, entry.mappedPath, realPath); + } + } + return _this; + } + } + + // eslint-disable-next-line spaced-comment + const kEmptyObject = /*#__PURE__*/ Object.freeze(/*#__PURE__*/ Object.create(null)); + const kExitCode = Symbol('kExitCode'); + const kSetMemory = Symbol('kSetMemory'); + const kStarted = Symbol('kStarted'); + const kInstance = Symbol('kInstance'); + const kBindingName = Symbol('kBindingName'); + function validateOptions(options) { + var _a; + validateObject(options, 'options'); + let _WASI; + if (options.version !== undefined) { + validateString(options.version, 'options.version'); + switch (options.version) { + case 'unstable': + _WASI = WASI$1; + this[kBindingName] = 'wasi_unstable'; + break; + case 'preview1': + _WASI = WASI$1; + this[kBindingName] = 'wasi_snapshot_preview1'; + break; + default: + throw new TypeError(`unsupported WASI version "${options.version}"`); + } + } + else { + _WASI = WASI$1; + this[kBindingName] = 'wasi_snapshot_preview1'; + } + if (options.args !== undefined) { + validateArray(options.args, 'options.args'); + } + const args = ((_a = options.args) !== null && _a !== void 0 ? _a : []).map(String); + const env = []; + if (options.env !== undefined) { + validateObject(options.env, 'options.env'); + Object.entries(options.env).forEach(({ 0: key, 1: value }) => { + if (value !== undefined) { + env.push(`${key}=${value}`); + } + }); + } + const preopens = []; + if (options.preopens !== undefined) { + validateObject(options.preopens, 'options.preopens'); + Object.entries(options.preopens).forEach(({ 0: key, 1: value }) => preopens.push({ mappedPath: String(key), realPath: String(value) })); + } + if (preopens.length > 0) { + if (options.fs === undefined) { + throw new Error('filesystem is disabled, can not preopen directory'); + } + try { + validateObject(options.fs, 'options.fs'); + } + catch (_) { + throw new TypeError('Node.js fs like implementation is not provided'); + } + } + // if (options.filesystem !== undefined) { + // validateObject(options.filesystem, 'options.filesystem') + // validateString(options.filesystem.type, 'options.filesystem.type') + // if (options.filesystem.type !== 'memfs' && options.filesystem.type !== 'file-system-access-api') { + // throw new Error(`Filesystem type ${(options.filesystem as any).type as string} is not supported, only "memfs" and "file-system-access-api" is supported currently`) + // } + // try { + // validateObject(options.filesystem.fs, 'options.filesystem.fs') + // } catch (_) { + // throw new Error('Node.js fs like implementation is not provided') + // } + // } + if (options.print !== undefined) + validateFunction(options.print, 'options.print'); + if (options.printErr !== undefined) + validateFunction(options.printErr, 'options.printErr'); + if (options.returnOnExit !== undefined) { + validateBoolean(options.returnOnExit, 'options.returnOnExit'); + } + // const { stdin = 0, stdout = 1, stderr = 2 } = options + // validateInt32(stdin, 'options.stdin', 0) + // validateInt32(stdout, 'options.stdout', 0) + // validateInt32(stderr, 'options.stderr', 0) + // const stdio = [stdin, stdout, stderr] as const + const stdio = [0, 1, 2]; + return { + args, + env, + preopens, + stdio, + _WASI + }; + } + function initWASI(setMemory, wrap) { + this[kSetMemory] = setMemory; + this.wasiImport = wrap; + this[kStarted] = false; + this[kExitCode] = 0; + this[kInstance] = undefined; + } + /** @public */ + class WASI { + constructor(options = kEmptyObject) { + const { args, env, preopens, stdio, _WASI } = validateOptions.call(this, options); + const wrap = _WASI.createSync(args, env, preopens, stdio, options.fs, options.print, options.printErr); + const setMemory = wrap._setMemory; + delete wrap._setMemory; + initWASI.call(this, setMemory, wrap); + if (options.returnOnExit) { + wrap.proc_exit = wasiReturnOnProcExit.bind(this); + } + } + finalizeBindings(instance, _a) { + var _b; + var { memory = (_b = instance === null || instance === void 0 ? void 0 : instance.exports) === null || _b === void 0 ? void 0 : _b.memory } = _a === void 0 ? {} : _a; + if (this[kStarted]) { + throw new Error('WASI instance has already started'); + } + validateObject(instance, 'instance'); + validateObject(instance.exports, 'instance.exports'); + this[kSetMemory](memory); + this[kInstance] = instance; + this[kStarted] = true; + } + // Must not export _initialize, must export _start + start(instance) { + this.finalizeBindings(instance); + const { _start, _initialize } = this[kInstance].exports; + validateFunction(_start, 'instance.exports._start'); + validateUndefined(_initialize, 'instance.exports._initialize'); + let ret; + try { + ret = _start(); + } + catch (err) { + if (err !== kExitCode) { + throw err; + } + } + if (ret instanceof Promise) { + return ret.then(() => this[kExitCode], (err) => { + if (err !== kExitCode) { + throw err; + } + return this[kExitCode]; + }); + } + return this[kExitCode]; + } + // Must not export _start, may optionally export _initialize + initialize(instance) { + this.finalizeBindings(instance); + const { _start, _initialize } = this[kInstance].exports; + validateUndefined(_start, 'instance.exports._start'); + if (_initialize !== undefined) { + validateFunction(_initialize, 'instance.exports._initialize'); + return _initialize(); + } + } + getImportObject() { + return { [this[kBindingName]]: this.wasiImport }; + } + } + function wasiReturnOnProcExit(rval) { + this[kExitCode] = rval; + // eslint-disable-next-line @typescript-eslint/no-throw-literal + throw kExitCode; + } + /** @public */ + async function createAsyncWASI(options = kEmptyObject) { + const _this = Object.create(WASI.prototype); + const { args, env, preopens, stdio, _WASI } = validateOptions.call(_this, options); + if (options.asyncify !== undefined) { + validateObject(options.asyncify, 'options.asyncify'); + validateFunction(options.asyncify.wrapImportFunction, 'options.asyncify.wrapImportFunction'); + } + const wrap = await _WASI.createAsync(args, env, preopens, stdio, options.fs, options.print, options.printErr, options.asyncify); + const setMemory = wrap._setMemory; + delete wrap._setMemory; + initWASI.call(_this, setMemory, wrap); + if (options.returnOnExit) { + wrap.proc_exit = wasiReturnOnProcExit.bind(_this); + } + return _this; + } + + exports.Asyncify = Asyncify; + exports.Memory = Memory; + exports.WASI = WASI; + exports.WebAssemblyMemory = WebAssemblyMemory; + exports.asyncifyLoad = asyncifyLoad; + exports.asyncifyLoadSync = asyncifyLoadSync; + exports.createAsyncWASI = createAsyncWASI; + exports.extendMemory = extendMemory; + exports.load = load; + exports.loadSync = loadSync; + exports.wrapAsyncExport = wrapAsyncExport; + exports.wrapAsyncImport = wrapAsyncImport; + exports.wrapExports = wrapExports; + + Object.defineProperty(exports, '__esModule', { value: true }); + +})); diff --git a/dg-ui/node_modules/@tailwindcss/oxide-wasm32-wasi/node_modules/@tybys/wasm-util/dist/wasm-util.min.js b/dg-ui/node_modules/@tailwindcss/oxide-wasm32-wasi/node_modules/@tybys/wasm-util/dist/wasm-util.min.js new file mode 100644 index 0000000..96036e9 --- /dev/null +++ b/dg-ui/node_modules/@tailwindcss/oxide-wasm32-wasi/node_modules/@tybys/wasm-util/dist/wasm-util.min.js @@ -0,0 +1 @@ +!function(t,e){"object"==typeof exports&&"undefined"!=typeof module?e(exports):"function"==typeof define&&define.amd?define(["exports"],e):e((t="undefined"!=typeof globalThis?globalThis:t||self).wasmUtil={})}(this,(function(t){"use strict";const e="undefined"!=typeof WebAssembly?WebAssembly:"undefined"!=typeof WXWebAssembly?WXWebAssembly:void 0;if(!e)throw new Error("WebAssembly is not supported in this environment");function n(t,e){if(null===t||"object"!=typeof t)throw new TypeError(`${e} must be an object. Received ${null===t?"null":typeof t}`)}function r(t,e){if("string"!=typeof t)throw new TypeError(`${e} must be a string. Received ${null===t?"null":typeof t}`)}function i(t,e){if("function"!=typeof t)throw new TypeError(`${e} must be a function. Received ${null===t?"null":typeof t}`)}function s(t,e){if(void 0!==t)throw new TypeError(`${e} must be undefined. Received ${null===t?"null":typeof t}`)}function o(t){return!(!t||"object"!=typeof t&&"function"!=typeof t||"function"!=typeof t.then)}function a(t,e){const n=Object.create(null);return Object.keys(t).forEach((r=>{const i=t[r];Object.defineProperty(n,r,{enumerable:!0,value:e(i,r)})})),n}function c(t,e,n){return"function"==typeof SharedArrayBuffer&&t.buffer instanceof SharedArrayBuffer||"[object SharedArrayBuffer]"===Object.prototype.toString.call(t.buffer.constructor)?t.slice(e,n):t.subarray(e,n)}const u=["asyncify_get_state","asyncify_start_rewind","asyncify_start_unwind","asyncify_stop_rewind","asyncify_stop_unwind"];function f(t,e,n,r){if("function"!=typeof t.exports[r]||n<=0)return{wasm64:e,dataPtr:16,start:e?32:24,end:1024};const i=t.exports[r],s=e?Number(i(BigInt(16)+BigInt(n))):i(8+n);if(0===s)throw new Error("Allocate asyncify data failed");return e?{wasm64:e,dataPtr:s,start:s+16,end:s+16+n}:{wasm64:e,dataPtr:s,start:s+8,end:s+8+n}}class h{constructor(){this.value=void 0,this.exports=void 0,this.dataPtr=0}init(t,n,r){var i,s;if(this.exports)throw new Error("Asyncify has been initialized");if(!(t instanceof e.Memory))throw new TypeError("Require WebAssembly.Memory object");const o=n.exports;for(let t=0;t{const r=t[n],i={};Object.keys(r).forEach((t=>{const e=r[t];i[t]="function"==typeof e?this.wrapImportFunction(e):e})),e[n]=i})),e}wrapExportFunction(t){const e=this;return async function(){e.assertState();let n=t.apply(this,arguments);for(;1===e.exports.asyncify_get_state();)e.exports.asyncify_stop_unwind(),e.value=await e.value,e.assertState(),e.exports.asyncify_start_rewind(e.dataPtr),n=t.call(this);return e.assertState(),n}}wrapExports(t,e){return a(t,((t,n)=>{let r=-1!==u.indexOf(n)||"function"!=typeof t;return Array.isArray(e)&&(r=r||-1===e.indexOf(n)),r?t:this.wrapExportFunction(t)}))}}function d(t){if(t&&"object"!=typeof t)throw new TypeError("imports must be an object or undefined")}function g(t,n){return"undefined"!=typeof wx&&"undefined"!=typeof __wxConfig?e.instantiate(t,n):fetch(t).then((t=>t.arrayBuffer())).then((t=>e.instantiate(t,n)))}function l(t,n){let r;if(d(n),n=null!=n?n:{},t instanceof ArrayBuffer||ArrayBuffer.isView(t))return e.instantiate(t,n);if(t instanceof e.Module)return e.instantiate(t,n).then((e=>({instance:e,module:t})));if("string"!=typeof t&&!(t instanceof URL))throw new TypeError("Invalid source");if("function"==typeof e.instantiateStreaming){let i;try{i=fetch(t),r=e.instantiateStreaming(i,n).catch((()=>g(t,n)))}catch(e){r=g(t,n)}}else r=g(t,n);return r}function _(t,n){let r;if(d(n),n=null!=n?n:{},t instanceof ArrayBuffer||ArrayBuffer.isView(t))r=new e.Module(t);else{if(!(t instanceof WebAssembly.Module))throw new TypeError("Invalid source");r=t}return{instance:new e.Instance(r,n),module:r}}const p=46,y=47,m=92,E=58,I=65,b=90,A=97,T=122;function w(t){return t===y||t===m}function B(t){return t>=I&&t<=b||t>=A&&t<=T}const N="undefined"!=typeof process&&"win32"===process.platform;function S(t){return t===y}function P(t,e,n,r){let i="",s=0,o=-1,a=0,c=0;for(let u=0;u<=t.length;++u){if(u2){const t=i.indexOf(n);-1===t?(i="",s=0):(i=i.slice(0,t),s=i.length-1-i.indexOf(n)),o=u,a=0;continue}if(0!==i.length){i="",s=0,o=u,a=0;continue}}e&&(i+=i.length>0?`${n}..`:"..",s=2)}else i.length>0?i+=`${n}${t.slice(o+1,u)}`:i=t.slice(o+1,u),s=u-o-1;o=u,a=0}else c===p&&-1!==a?++a:a=-1}return i}function D(...t){if(N)return function(t){let e="",n="",i=!1;for(let s=t.length-1;s>=-1;s--){let o;if(s>=0){if(o=t[s],r(o,"path"),0===o.length)continue}else if(0===e.length)o="undefined"!=typeof process&&"function"==typeof process.cwd?process.cwd():"";else{const t=`=${e}`,n="undefined"!=typeof process?process.env:void 0;o=n&&"string"==typeof n[t]?n[t]:"undefined"!=typeof process&&"function"==typeof process.cwd?process.cwd():"",(void 0===o||o.slice(0,2).toLowerCase()!==e.toLowerCase()&&o.charCodeAt(2)===m)&&(o=`${e}\\`)}const a=o.length;let c=0,u="",f=!1;const h=o.charCodeAt(0);if(1===a)w(h)&&(c=1,f=!0);else if(w(h))if(f=!0,w(o.charCodeAt(1))){let t=2,e=t;for(;t2&&w(o.charCodeAt(2))&&(f=!0,c=3));if(u.length>0)if(e.length>0){if(u.toLowerCase()!==e.toLowerCase())continue}else e=u;if(i){if(e.length>0)break}else if(n=`${o.slice(c)}\\${n}`,i=f,f&&e.length>0)break}return n=P(n,!i,"\\",w),e+(i?"\\":"")+n||"."}(t);let e="",n=!1;for(let i=t.length-1;i>=-1&&!n;i--){const s=i>=0?t[i]:"/";r(s,"path"),0!==s.length&&(e=`${s}/${e}`,n=s.charCodeAt(0)===y)}return e=P(e,!n,"/",S),n?`/${e}`:e.length>0?e:"."}const F={FD_DATASYNC:BigInt(1)<=0)n=e;else for(let e=0;e"),this.insertStdio(t.out,1,""),this.insertStdio(t.err,2,"")}insertStdio(t,e,n){const{base:r,inheriting:i}=$(this.stdio,t,2,2),s=this.insert(t,n,n,2,r,i,0);if(s.id!==e)throw new v(`id: ${s.id} !== expected: ${e}`,8);return s}insert(t,e,n,r,i,s,o){var a,c;let u,f=-1;if(this.used>=this.size){const t=2*this.size;this.fds.length=t,f=this.size,this.size=t}else for(let t=0;t"===e?new V(null!==(c=this.printErr)&&void 0!==c?c:console.error,f,t,e,n,r,i,s,o):new Y(f,t,e,n,r,i,s,o),this.fds[f]=u,this.used++,u}get(t,e,n){if(t>=this.size)throw new v("Invalid fd",8);const r=this.fds[t];if(!r||r.id!==t)throw new v("Bad file descriptor",8);if((~r.rightsBase&e)!==BigInt(0)||(~r.rightsInheriting&n)!==BigInt(0))throw new v("Capabilities insufficient",76);return r}remove(t){if(t>=this.size)throw new v("Invalid fd",8);const e=this.fds[t];if(!e||e.id!==t)throw new v("Bad file descriptor",8);this.fds[t]=void 0,this.used--}}class Q extends X{constructor(t){super(t),this.fs=t.fs}getFileTypeByFd(t){return Z(this.fs.fstatSync(t,{bigint:!0}))}insertPreopen(t,e,n){const r=this.getFileTypeByFd(t);if(3!==r)throw new v(`Preopen not dir: ["${e}", "${n}"]`,54);const i=$(this.stdio,t,0,r);return this.insert(t,e,n,r,i.base,i.inheriting,1)}renumber(t,e){if(t===e)return;if(t>=this.size||e>=this.size)throw new v("Invalid fd",8);const n=this.fds[t],r=this.fds[e];if(!n||!r||n.id!==t||r.id!==e)throw new v("Invalid fd",8);this.fs.closeSync(n.fd),this.fds[t]=this.fds[e],this.fds[t].id=t,this.fds[e]=void 0,this.used--}}class J extends X{constructor(t){super(t)}async getFileTypeByFd(t){return Z(await t.stat({bigint:!0}))}async insertPreopen(t,e,n){const r=await this.getFileTypeByFd(t);if(3!==r)throw new v(`Preopen not dir: ["${e}", "${n}"]`,54);const i=$(this.stdio,t.fd,0,r);return this.insert(t,e,n,r,i.base,i.inheriting,1)}async renumber(t,e){if(t===e)return;if(t>=this.size||e>=this.size)throw new v("Invalid fd",8);const n=this.fds[t],r=this.fds[e];if(!n||!r||n.id!==t||r.id!==e)throw new v("Invalid fd",8);await n.fd.close(),this.fds[t]=this.fds[e],this.fds[t].id=t,this.fds[e]=void 0,this.used--}}const tt=function(){return e.Memory}();class et extends tt{constructor(t){super(t)}get HEAP8(){return new Int8Array(super.buffer)}get HEAPU8(){return new Uint8Array(super.buffer)}get HEAP16(){return new Int16Array(super.buffer)}get HEAPU16(){return new Uint16Array(super.buffer)}get HEAP32(){return new Int32Array(super.buffer)}get HEAPU32(){return new Uint32Array(super.buffer)}get HEAP64(){return new BigInt64Array(super.buffer)}get HEAPU64(){return new BigUint64Array(super.buffer)}get HEAPF32(){return new Float32Array(super.buffer)}get HEAPF64(){return new Float64Array(super.buffer)}get view(){return new DataView(super.buffer)}}function nt(t){return Object.getPrototypeOf(t)===e.Memory.prototype&&Object.setPrototypeOf(t,et.prototype),t}function rt(){const t=e.Function;if("function"!=typeof t)throw new Error('WebAssembly.Function is not supported in this environment. If you are using V8 based browser like Chrome, try to specify --js-flags="--wasm-staging --experimental-wasm-stack-switching"');return t}function it(t,e,n){const r=rt();if("function"!=typeof t)throw new TypeError("Function required");const i=e.slice(0);return i.unshift("externref"),new r({parameters:i,results:n},t,{suspending:"first"})}function st(t){const e=rt();if("function"!=typeof t)throw new TypeError("Function required");return new e({parameters:[...e.type(t).parameters.slice(1)],results:["externref"]},t,{promising:"first"})}const ot="undefined"!=typeof process&&"win32"===process.platform;function at(t){let e=3&t;return 0!=(64&t)&&(e|=256),0!=(128&t)&&(e|=1024),0!=(512&t)&&(e|=512),0!=(1024&t)&&(e|=8),e}function ct(t,e){if(0===t.length||0===e.length)return 0;let n=0,r=e.length-n;for(let i=0;in.byteLength&&(t.grow(0),n=t.buffer)}(n,e),n}function gt(t){const e=ht.get(t);if(!e)throw new Error("filesystem is unavailable");return e}function lt(t){if(t instanceof v)return t.errno;switch(t.code){case"ENOENT":return 44;case"EBADF":return 8;case"EINVAL":return 28;case"EPERM":return 63;case"EPROTO":return 65;case"EEXIST":return 20;case"ENOTDIR":return 54;case"EMFILE":return 33;case"EACCES":return 2;case"EISDIR":return 31;case"ENOTEMPTY":return 55;case"ENOSYS":return 52}throw t}function _t(t,e){return Object.defineProperty(e,"name",{value:t}),e}function pt(t,e,n){let r;try{r=t.apply(e,n)}catch(t){return lt(t)}return o(r)?r.then((t=>t),lt):r}function yt(t,e,n){let r=!1;const i=(()=>{try{return}catch(t){return}})();return"string"==typeof i&&i.split(",").includes("wasi")&&(r=!0),_t(e,r?function(){const r=Array.prototype.slice.call(arguments);let i=[`${e}(${Array.from({length:arguments.length}).map((()=>"%d")).join(", ")})`];return i=i.concat(r),console.debug.apply(console,i),pt(n,t,r)}:function(){return pt(n,t,arguments)})}function mt(t,e,n,r){let i=D(e.realPath,n);if(1==(1&r))try{i=t.readlinkSync(i)}catch(t){if("EINVAL"!==t.code&&"ENOENT"!==t.code)throw t}return i}async function Et(t,e,n,r){let i=D(e.realPath,n);if(1==(1&r))try{i=await t.promises.readlink(i)}catch(t){if("EINVAL"!==t.code&&"ENOENT"!==t.code)throw t}return i}const It=new TextEncoder,bt=new TextDecoder,At=(BigInt(1)<r.rightsBase||(n|r.rightsInheriting)>r.rightsInheriting?76:(r.rightsBase=e,r.rightsInheriting=n,0)})),this.fd_prestat_get=yt(this,"fd_prestat_get",(function(t,e){if(0===(e=Number(e)))return 28;const n=ft.get(this);let r;try{r=n.fds.get(t,BigInt(0),BigInt(0))}catch(t){if(t instanceof v)return t.errno;throw t}if(1!==r.preopen)return 28;const{view:i}=dt(this,e+8);return i.setUint32(e,0,!0),i.setUint32(e+4,It.encode(r.path).length,!0),0})),this.fd_prestat_dir_name=yt(this,"fd_prestat_dir_name",(function(t,e,n){if(e=Number(e),n=Number(n),0===e)return 28;const r=ft.get(this).fds.get(t,BigInt(0),BigInt(0));if(1!==r.preopen)return 8;const i=It.encode(r.path),s=i.length;if(s>n)return 42;const{HEAPU8:o}=dt(this,e+s);return o.set(i,e),0})),this.fd_seek=yt(this,"fd_seek",(function(t,e,n,r){if(0===(r=Number(r)))return 28;if(0===t||1===t||2===t)return 0;const i=ft.get(this).fds.get(t,F.FD_SEEK,BigInt(0)).seek(e,n),{view:s}=dt(this,r+8);return s.setBigUint64(r,i,!0),0})),this.fd_tell=yt(this,"fd_tell",(function(t,e){const n=ft.get(this).fds.get(t,F.FD_TELL,BigInt(0)),r=BigInt(n.pos),{view:i}=dt(this,Number(e)+8);return i.setBigUint64(Number(e),r,!0),0})),this.poll_oneoff=yt(this,"poll_oneoff",(function(t,e,n,r){if(t=Number(t),e=Number(e),r=Number(r),n=Number(n),n>>>=0,0===t||0===e||0===n||0===r)return 28;const{view:i}=dt(this,Math.max(t+48*n,e+32*n,r+4));i.setUint32(r,0,!0);let s,o=0,a=BigInt(0),c=BigInt(0),u=0,f=BigInt(0);const h=Array(n);for(o=0;o0){for(o=0;o!1));const t=e;i.setBigUint64(t,a,!0),i.setUint32(t+8,0,!0),i.setUint32(t+12,0,!0),i.setUint32(r,1,!0)}return 0})),this.proc_exit=yt(this,"proc_exit",(function(t){return"object"==typeof process&&null!==process&&"function"==typeof process.exit&&process.exit(t),0})),this.proc_raise=yt(this,"proc_raise",(function(t){return 52})),this.sched_yield=yt(this,"sched_yield",(function(){return 0})),this.random_get="undefined"!=typeof crypto&&"function"==typeof crypto.getRandomValues?yt(this,"random_get",(function(t,e){if(0===(t=Number(t)))return 28;e=Number(e);const{HEAPU8:n,view:r}=dt(this,t+e);if("function"==typeof SharedArrayBuffer&&n.buffer instanceof SharedArrayBuffer||"[object SharedArrayBuffer]"===Object.prototype.toString.call(n.buffer)){for(let n=t;nAt)return 28;const{HEAPU8:s,view:o}=dt(this,Math.max(e+8*Number(n),i+4)),a=ft.get(this).fds.get(t,F.FD_READ|F.FD_SEEK,BigInt(0));if(!n)return o.setUint32(i,0,!0),0;let c=0;const u=Array.from({length:Number(n)},((t,n)=>{const r=e+8*n,i=o.getInt32(r,!0),a=o.getUint32(r+4,!0);return c+=a,s.subarray(i,i+a)}));let f=0;const h=(()=>{try{return new Uint8Array(new SharedArrayBuffer(c))}catch(t){return new Uint8Array(c)}})();h._isBuffer=!0;const d=gt(this).readSync(a.fd,h,0,h.length,Number(r));return f=h?ct(u,h.subarray(0,d)):0,o.setUint32(i,f,!0),0}),(async function(t,e,n,r,i){if(e=Number(e),i=Number(i),0===e&&n||0===i||r>At)return 28;const{HEAPU8:s,view:o}=dt(this,Math.max(e+8*Number(n),i+4)),a=ft.get(this).fds.get(t,F.FD_READ|F.FD_SEEK,BigInt(0));if(!n)return o.setUint32(i,0,!0),0;let c=0;const u=Array.from({length:Number(n)},((t,n)=>{const r=e+8*n,i=o.getInt32(r,!0),a=o.getUint32(r+4,!0);return c+=a,s.subarray(i,i+a)}));let f=0;const h=new Uint8Array(c);h._isBuffer=!0;const{bytesRead:d}=await a.fd.read(h,0,h.length,Number(r));return f=h?ct(u,h.subarray(0,d)):0,o.setUint32(i,f,!0),0}),["i32","i32","i32","i64","i32"],["i32"]),u("fd_pwrite",(function(t,e,n,r,i){if(e=Number(e),i=Number(i),0===e&&n||0===i||r>At)return 28;const{HEAPU8:s,view:o}=dt(this,Math.max(e+8*Number(n),i+4)),a=ft.get(this).fds.get(t,F.FD_WRITE|F.FD_SEEK,BigInt(0));if(!n)return o.setUint32(i,0,!0),0;const c=G(Array.from({length:Number(n)},((t,n)=>{const r=e+8*n,i=o.getInt32(r,!0),a=o.getUint32(r+4,!0);return s.subarray(i,i+a)}))),u=gt(this).writeSync(a.fd,c,0,c.length,Number(r));return o.setUint32(i,u,!0),0}),(async function(t,e,n,r,i){if(e=Number(e),i=Number(i),0===e&&n||0===i||r>At)return 28;const{HEAPU8:s,view:o}=dt(this,Math.max(e+8*Number(n),i+4)),a=ft.get(this).fds.get(t,F.FD_WRITE|F.FD_SEEK,BigInt(0));if(!n)return o.setUint32(i,0,!0),0;const c=G(Array.from({length:Number(n)},((t,n)=>{const r=e+8*n,i=o.getInt32(r,!0),a=o.getUint32(r+4,!0);return s.subarray(i,i+a)}))),{bytesWritten:u}=await a.fd.write(c,0,c.length,Number(r));return o.setUint32(i,u,!0),0}),["i32","i32","i32","i64","i32"],["i32"]),u("fd_read",(function(t,e,n,r){if(e=Number(e),r=Number(r),0===e&&n||0===r)return 28;const{HEAPU8:i,view:s}=dt(this,Math.max(e+8*Number(n),r+4)),o=ft.get(this).fds.get(t,F.FD_READ,BigInt(0));if(!n)return s.setUint32(r,0,!0),0;let a=0;const c=Array.from({length:Number(n)},((t,n)=>{const r=e+8*n,o=s.getInt32(r,!0),c=s.getUint32(r+4,!0);return a+=c,i.subarray(o,o+c)}));let u,f=0;if(0===t){if("undefined"==typeof window||"function"!=typeof window.prompt)return 58;u=Tt(),f=u?ct(c,u):0}else{u=(()=>{try{return new Uint8Array(new SharedArrayBuffer(a))}catch(t){return new Uint8Array(a)}})(),u._isBuffer=!0;const t=gt(this).readSync(o.fd,u,0,u.length,Number(o.pos));f=u?ct(c,u.subarray(0,t)):0,o.pos+=BigInt(f)}return s.setUint32(r,f,!0),0}),(async function(t,e,n,r){if(e=Number(e),r=Number(r),0===e&&n||0===r)return 28;const{HEAPU8:i,view:s}=dt(this,Math.max(e+8*Number(n),r+4)),o=ft.get(this).fds.get(t,F.FD_READ,BigInt(0));if(!n)return s.setUint32(r,0,!0),0;let a=0;const c=Array.from({length:Number(n)},((t,n)=>{const r=e+8*n,o=s.getInt32(r,!0),c=s.getUint32(r+4,!0);return a+=c,i.subarray(o,o+c)}));let u,f=0;if(0===t){if("undefined"==typeof window||"function"!=typeof window.prompt)return 58;u=Tt(),f=u?ct(c,u):0}else{u=new Uint8Array(a),u._isBuffer=!0;const{bytesRead:t}=await o.fd.read(u,0,u.length,Number(o.pos));f=u?ct(c,u.subarray(0,t)):0,o.pos+=BigInt(f)}return s.setUint32(r,f,!0),0}),["i32","i32","i32","i32"],["i32"]),u("fd_readdir",(function(t,e,n,r,i){if(e=Number(e),n=Number(n),i=Number(i),0===e||0===i)return 0;const s=ft.get(this).fds.get(t,F.FD_READDIR,BigInt(0)),o=gt(this),a=o.readdirSync(s.realPath,{withFileTypes:!0}),{HEAPU8:c,view:u}=dt(this,Math.max(e+n,i+4));let f=0;for(let t=Number(r);t{const r=e+8*n,o=s.getInt32(r,!0),a=s.getUint32(r+4,!0);return i.subarray(o,o+a)})));let c;if(1===t||2===t)c=o.write(a);else{c=gt(this).writeSync(o.fd,a,0,a.length,Number(o.pos)),o.pos+=BigInt(c)}return s.setUint32(r,c,!0),0}),(async function(t,e,n,r){if(e=Number(e),r=Number(r),0===e&&n||0===r)return 28;const{HEAPU8:i,view:s}=dt(this,Math.max(e+8*Number(n),r+4)),o=ft.get(this).fds.get(t,F.FD_WRITE,BigInt(0));if(!n)return s.setUint32(r,0,!0),0;const a=G(Array.from({length:Number(n)},((t,n)=>{const r=e+8*n,o=s.getInt32(r,!0),a=s.getUint32(r+4,!0);return i.subarray(o,o+a)})));let c;return 1===t||2===t?c=o.write(a):(c=await(await o.fd.write(a,0,a.length,Number(o.pos))).bytesWritten,o.pos+=BigInt(c)),s.setUint32(r,c,!0),0}),["i32","i32","i32","i32"],["i32"]),u("path_create_directory",(function(t,e,n){if(e=Number(e),n=Number(n),0===e)return 28;const{HEAPU8:r}=dt(this,e+n),i=ft.get(this).fds.get(t,F.PATH_CREATE_DIRECTORY,BigInt(0));let s=bt.decode(c(r,e,e+n));s=D(i.realPath,s);return gt(this).mkdirSync(s),0}),(async function(t,e,n){if(e=Number(e),n=Number(n),0===e)return 28;const{HEAPU8:r}=dt(this,e+n),i=ft.get(this).fds.get(t,F.PATH_CREATE_DIRECTORY,BigInt(0));let s=bt.decode(c(r,e,e+n));s=D(i.realPath,s);const o=gt(this);return await o.promises.mkdir(s),0}),["i32","i32","i32"],["i32"]),u("path_filestat_get",(function(t,e,n,r,i){if(n=Number(n),r=Number(r),i=Number(i),0===n||0===i)return 28;const{HEAPU8:s,view:o}=dt(this,Math.max(n+r,i+64)),a=ft.get(this).fds.get(t,F.PATH_FILESTAT_GET,BigInt(0));let u=bt.decode(c(s,n,n+r));const f=gt(this);let h;return u=D(a.realPath,u),h=1==(1&e)?f.statSync(u,{bigint:!0}):f.lstatSync(u,{bigint:!0}),q(o,i,h),0}),(async function(t,e,n,r,i){if(n=Number(n),r=Number(r),i=Number(i),0===n||0===i)return 28;const{HEAPU8:s,view:o}=dt(this,Math.max(n+r,i+64)),a=ft.get(this).fds.get(t,F.PATH_FILESTAT_GET,BigInt(0));let u=bt.decode(c(s,n,n+r));const f=gt(this);let h;return u=D(a.realPath,u),h=1==(1&e)?await f.promises.stat(u,{bigint:!0}):await f.promises.lstat(u,{bigint:!0}),q(o,i,h),0}),["i32","i32","i32","i32","i32"],["i32"]),u("path_filestat_set_times",(function(t,e,n,r,i,s,o){if(n=Number(n),r=Number(r),0===n)return 28;const{HEAPU8:a}=dt(this,n+r),u=ft.get(this).fds.get(t,F.PATH_FILESTAT_SET_TIMES,BigInt(0));if(wt(o))return 28;const f=gt(this),h=mt(f,u,bt.decode(c(a,n,n+r)),e);return 2==(2&o)&&(i=BigInt(1e6*Date.now())),8==(8&o)&&(s=BigInt(1e6*Date.now())),f.utimesSync(h,Number(i),Number(s)),0}),(async function(t,e,n,r,i,s,o){if(n=Number(n),r=Number(r),0===n)return 28;const{HEAPU8:a}=dt(this,n+r),u=ft.get(this).fds.get(t,F.PATH_FILESTAT_SET_TIMES,BigInt(0));if(wt(o))return 28;const f=gt(this),h=await Et(f,u,bt.decode(c(a,n,n+r)),e);return 2==(2&o)&&(i=BigInt(1e6*Date.now())),8==(8&o)&&(s=BigInt(1e6*Date.now())),await f.promises.utimes(h,Number(i),Number(s)),0}),["i32","i32","i32","i32","i64","i64","i32"],["i32"]),u("path_link",(function(t,e,n,r,i,s,o){if(n=Number(n),r=Number(r),s=Number(s),o=Number(o),0===n||0===s)return 28;const a=ft.get(this);let u,f;t===i?u=f=a.fds.get(t,F.PATH_LINK_SOURCE|F.PATH_LINK_TARGET,BigInt(0)):(u=a.fds.get(t,F.PATH_LINK_SOURCE,BigInt(0)),f=a.fds.get(i,F.PATH_LINK_TARGET,BigInt(0)));const{HEAPU8:h}=dt(this,Math.max(n+r,s+o)),d=gt(this),g=mt(d,u,bt.decode(c(h,n,n+r)),e),l=D(f.realPath,bt.decode(c(h,s,s+o)));return d.linkSync(g,l),0}),(async function(t,e,n,r,i,s,o){if(n=Number(n),r=Number(r),s=Number(s),o=Number(o),0===n||0===s)return 28;const a=ft.get(this);let u,f;t===i?u=f=a.fds.get(t,F.PATH_LINK_SOURCE|F.PATH_LINK_TARGET,BigInt(0)):(u=a.fds.get(t,F.PATH_LINK_SOURCE,BigInt(0)),f=a.fds.get(i,F.PATH_LINK_TARGET,BigInt(0)));const{HEAPU8:h}=dt(this,Math.max(n+r,s+o)),d=gt(this),g=await Et(d,u,bt.decode(c(h,n,n+r)),e),l=D(f.realPath,bt.decode(c(h,s,s+o)));return await d.promises.link(g,l),0}),["i32","i32","i32","i32","i32","i32","i32"],["i32"]),u("path_open",(function(t,e,n,r,i,s,o,a,u){if(n=Number(n),u=Number(u),0===n||0===u)return 28;r=Number(r),s=BigInt(s),o=BigInt(o);const{flags:f,needed_base:d,needed_inheriting:g}=h(i,s,o,a),l=ft.get(this),_=l.fds.get(t,d,g),p=dt(this,Math.max(n+r,u+4)),y=p.HEAPU8,m=bt.decode(c(y,n,n+r)),E=gt(this),I=mt(E,_,m,e),b=E.openSync(I,ot?at(f):f,438),A=l.fds.getFileTypeByFd(b);if(3!==A&&(0!=(2&i)||I.endsWith("/")))return 54;const{base:T,inheriting:w}=$(l.fds.stdio,b,f,A),B=l.fds.insert(b,I,I,A,s&T,o&w,0),N=E.fstatSync(b,{bigint:!0});N.isFile()&&(B.size=N.size,0!=(1024&f)&&(B.pos=N.size));return p.view.setInt32(u,B.id,!0),0}),(async function(t,e,n,r,i,s,o,a,u){if(n=Number(n),u=Number(u),0===n||0===u)return 28;r=Number(r),s=BigInt(s),o=BigInt(o);const{flags:f,needed_base:d,needed_inheriting:g}=h(i,s,o,a),l=ft.get(this),_=l.fds.get(t,d,g),p=dt(this,Math.max(n+r,u+4)),y=p.HEAPU8,m=bt.decode(c(y,n,n+r)),E=gt(this),I=await Et(E,_,m,e),b=await E.promises.open(I,ot?at(f):f,438),A=await l.fds.getFileTypeByFd(b);if(0!=(2&i)&&3!==A)return 54;const{base:T,inheriting:w}=$(l.fds.stdio,b.fd,f,A),B=l.fds.insert(b,I,I,A,s&T,o&w,0),N=await b.stat({bigint:!0});N.isFile()&&(B.size=N.size,0!=(1024&f)&&(B.pos=N.size));return p.view.setInt32(u,B.id,!0),0}),["i32","i32","i32","i32","i32","i64","i64","i32","i32"],["i32"]),u("path_readlink",(function(t,e,n,r,i,s){if(e=Number(e),n=Number(n),r=Number(r),i=Number(i),s=Number(s),0===e||0===r||0===s)return 28;const{HEAPU8:o,view:a}=dt(this,Math.max(e+n,r+i,s+4)),u=ft.get(this).fds.get(t,F.PATH_READLINK,BigInt(0));let f=bt.decode(c(o,e,e+n));f=D(u.realPath,f);const h=gt(this).readlinkSync(f),d=It.encode(h),g=Math.min(d.length,i);return g>=i?42:(o.set(d.subarray(0,g),r),o[r+g]=0,a.setUint32(s,g,!0),0)}),(async function(t,e,n,r,i,s){if(e=Number(e),n=Number(n),r=Number(r),i=Number(i),s=Number(s),0===e||0===r||0===s)return 28;const{HEAPU8:o,view:a}=dt(this,Math.max(e+n,r+i,s+4)),u=ft.get(this).fds.get(t,F.PATH_READLINK,BigInt(0));let f=bt.decode(c(o,e,e+n));f=D(u.realPath,f);const h=gt(this),d=await h.promises.readlink(f),g=It.encode(d),l=Math.min(g.length,i);return l>=i?42:(o.set(g.subarray(0,l),r),o[r+l]=0,a.setUint32(s,l,!0),0)}),["i32","i32","i32","i32","i32","i32"],["i32"]),u("path_remove_directory",(function(t,e,n){if(e=Number(e),n=Number(n),0===e)return 28;const{HEAPU8:r}=dt(this,e+n),i=ft.get(this).fds.get(t,F.PATH_REMOVE_DIRECTORY,BigInt(0));let s=bt.decode(c(r,e,e+n));s=D(i.realPath,s);return gt(this).rmdirSync(s),0}),(async function(t,e,n){if(e=Number(e),n=Number(n),0===e)return 28;const{HEAPU8:r}=dt(this,e+n),i=ft.get(this).fds.get(t,F.PATH_REMOVE_DIRECTORY,BigInt(0));let s=bt.decode(c(r,e,e+n));s=D(i.realPath,s);const o=gt(this);return await o.promises.rmdir(s),0}),["i32","i32","i32"],["i32"]),u("path_rename",(function(t,e,n,r,i,s){if(e=Number(e),n=Number(n),i=Number(i),s=Number(s),0===e||0===i)return 28;const o=ft.get(this);let a,u;t===r?a=u=o.fds.get(t,F.PATH_RENAME_SOURCE|F.PATH_RENAME_TARGET,BigInt(0)):(a=o.fds.get(t,F.PATH_RENAME_SOURCE,BigInt(0)),u=o.fds.get(r,F.PATH_RENAME_TARGET,BigInt(0)));const{HEAPU8:f}=dt(this,Math.max(e+n,i+s)),h=D(a.realPath,bt.decode(c(f,e,e+n))),d=D(u.realPath,bt.decode(c(f,i,i+s)));return gt(this).renameSync(h,d),0}),(async function(t,e,n,r,i,s){if(e=Number(e),n=Number(n),i=Number(i),s=Number(s),0===e||0===i)return 28;const o=ft.get(this);let a,u;t===r?a=u=o.fds.get(t,F.PATH_RENAME_SOURCE|F.PATH_RENAME_TARGET,BigInt(0)):(a=o.fds.get(t,F.PATH_RENAME_SOURCE,BigInt(0)),u=o.fds.get(r,F.PATH_RENAME_TARGET,BigInt(0)));const{HEAPU8:f}=dt(this,Math.max(e+n,i+s)),h=D(a.realPath,bt.decode(c(f,e,e+n))),d=D(u.realPath,bt.decode(c(f,i,i+s))),g=gt(this);return await g.promises.rename(h,d),0}),["i32","i32","i32","i32","i32","i32"],["i32"]),u("path_symlink",(function(t,e,n,r,i){if(t=Number(t),e=Number(e),r=Number(r),i=Number(i),0===t||0===r)return 28;const{HEAPU8:s}=dt(this,Math.max(t+e,r+i)),o=ft.get(this).fds.get(n,F.PATH_SYMLINK,BigInt(0)),a=bt.decode(c(s,t,t+e));if(a.length>0&&"/"===a[0])return 63;let u=bt.decode(c(s,r,r+i));u=D(o.realPath,u);return gt(this).symlinkSync(a,u),0}),(async function(t,e,n,r,i){if(t=Number(t),e=Number(e),r=Number(r),i=Number(i),0===t||0===r)return 28;const{HEAPU8:s}=dt(this,Math.max(t+e,r+i)),o=ft.get(this).fds.get(n,F.PATH_SYMLINK,BigInt(0)),a=bt.decode(c(s,t,t+e));let u=bt.decode(c(s,r,r+i));u=D(o.realPath,u);const f=gt(this);return await f.promises.symlink(a,u),0}),["i32","i32","i32","i32","i32"],["i32"]),u("path_unlink_file",(function(t,e,n){if(e=Number(e),n=Number(n),0===e)return 28;const{HEAPU8:r}=dt(this,e+n),i=ft.get(this).fds.get(t,F.PATH_UNLINK_FILE,BigInt(0));let s=bt.decode(c(r,e,e+n));s=D(i.realPath,s);return gt(this).unlinkSync(s),0}),(async function(t,e,n){if(e=Number(e),n=Number(n),0===e)return 28;const{HEAPU8:r}=dt(this,e+n),i=ft.get(this).fds.get(t,F.PATH_UNLINK_FILE,BigInt(0));let s=bt.decode(c(r,e,e+n));s=D(i.realPath,s);const o=gt(this);return await o.promises.unlink(s),0}),["i32","i32","i32"],["i32"]),this._setMemory=function(t){if(!(t instanceof e.Memory))throw new TypeError('"instance.exports.memory" property must be a WebAssembly.Memory');ut.set(a,nt(t))}}static createSync(t,e,n,r,i,s,o){const a=new Q({size:3,in:r[0],out:r[1],err:r[2],fs:i,print:s,printErr:o}),c=new Bt(t,e,a,!1,i);if(n.length>0)for(let t=0;t0)for(let t=0;t{void 0!==e&&a.push(`${t}=${e}`)})));const c=[];if(void 0!==t.preopens&&(n(t.preopens,"options.preopens"),Object.entries(t.preopens).forEach((({0:t,1:e})=>c.push({mappedPath:String(t),realPath:String(e)})))),c.length>0){if(void 0===t.fs)throw new Error("filesystem is disabled, can not preopen directory");try{n(t.fs,"options.fs")}catch(t){throw new TypeError("Node.js fs like implementation is not provided")}}void 0!==t.print&&i(t.print,"options.print"),void 0!==t.printErr&&i(t.printErr,"options.printErr"),void 0!==t.returnOnExit&&function(t,e){if("boolean"!=typeof t)throw new TypeError(`${e} must be a boolean. Received ${null===t?"null":typeof t}`)}(t.returnOnExit,"options.returnOnExit");return{args:o,env:a,preopens:c,stdio:[0,1,2],_WASI:s}}function Rt(t,e){this[Pt]=t,this.wasiImport=e,this[Dt]=!1,this[St]=0,this[Ft]=void 0}class Lt{constructor(t=Nt){const{args:e,env:n,preopens:r,stdio:i,_WASI:s}=Ut.call(this,t),o=s.createSync(e,n,r,i,t.fs,t.print,t.printErr),a=o._setMemory;delete o._setMemory,Rt.call(this,a,o),t.returnOnExit&&(o.proc_exit=Ht.bind(this))}finalizeBindings(t,e){var r,{memory:i=(null===(r=null==t?void 0:t.exports)||void 0===r?void 0:r.memory)}=void 0===e?{}:e;if(this[Dt])throw new Error("WASI instance has already started");n(t,"instance"),n(t.exports,"instance.exports"),this[Pt](i),this[Ft]=t,this[Dt]=!0}start(t){this.finalizeBindings(t);const{_start:e,_initialize:n}=this[Ft].exports;let r;i(e,"instance.exports._start"),s(n,"instance.exports._initialize");try{r=e()}catch(t){if(t!==St)throw t}return r instanceof Promise?r.then((()=>this[St]),(t=>{if(t!==St)throw t;return this[St]})):this[St]}initialize(t){this.finalizeBindings(t);const{_start:e,_initialize:n}=this[Ft].exports;if(s(e,"instance.exports._start"),void 0!==n)return i(n,"instance.exports._initialize"),n()}getImportObject(){return{[this[vt]]:this.wasiImport}}}function Ht(t){throw this[St]=t,St}t.Asyncify=h,t.Memory=et,t.WASI=Lt,t.WebAssemblyMemory=tt,t.asyncifyLoad=function(t,e,n){d(n),n=null!=n?n:{};const r=new h;return l(e,n=r.wrapImports(n)).then((e=>{var i;const s=e.instance.exports.memory||(null===(i=n.env)||void 0===i?void 0:i.memory);return{module:e.module,instance:r.init(s,e.instance,t)}}))},t.asyncifyLoadSync=function(t,e,n){var r;d(n),n=null!=n?n:{};const i=new h,s=_(e,n=i.wrapImports(n)),o=s.instance.exports.memory||(null===(r=n.env)||void 0===r?void 0:r.memory);return{module:s.module,instance:i.init(o,s.instance,t)}},t.createAsyncWASI=async function(t=Nt){const e=Object.create(Lt.prototype),{args:r,env:s,preopens:o,stdio:a,_WASI:c}=Ut.call(e,t);void 0!==t.asyncify&&(n(t.asyncify,"options.asyncify"),i(t.asyncify.wrapImportFunction,"options.asyncify.wrapImportFunction"));const u=await c.createAsync(r,s,o,a,t.fs,t.print,t.printErr,t.asyncify),f=u._setMemory;return delete u._setMemory,Rt.call(e,f,u),t.returnOnExit&&(u.proc_exit=Ht.bind(e)),e},t.extendMemory=nt,t.load=l,t.loadSync=_,t.wrapAsyncExport=st,t.wrapAsyncImport=it,t.wrapExports=function(t,e){return a(t,((t,n)=>{let r="function"!=typeof t;return Array.isArray(e)&&(r=r||-1===e.indexOf(n)),r?t:st(t)}))},Object.defineProperty(t,"__esModule",{value:!0})})); diff --git a/dg-ui/node_modules/@tailwindcss/oxide-wasm32-wasi/node_modules/@tybys/wasm-util/lib/cjs/asyncify.js b/dg-ui/node_modules/@tailwindcss/oxide-wasm32-wasi/node_modules/@tybys/wasm-util/lib/cjs/asyncify.js new file mode 100644 index 0000000..cf66eb9 --- /dev/null +++ b/dg-ui/node_modules/@tailwindcss/oxide-wasm32-wasi/node_modules/@tybys/wasm-util/lib/cjs/asyncify.js @@ -0,0 +1,158 @@ +"use strict"; +Object.defineProperty(exports, "__esModule", { value: true }); +exports.Asyncify = void 0; +const webassembly_1 = require("./webassembly"); +const util_1 = require("./wasi/util"); +const ignoreNames = [ + 'asyncify_get_state', + 'asyncify_start_rewind', + 'asyncify_start_unwind', + 'asyncify_stop_rewind', + 'asyncify_stop_unwind' +]; +// const wrappedExports = new WeakMap() +var AsyncifyState; +(function (AsyncifyState) { + AsyncifyState[AsyncifyState["NONE"] = 0] = "NONE"; + AsyncifyState[AsyncifyState["UNWINDING"] = 1] = "UNWINDING"; + AsyncifyState[AsyncifyState["REWINDING"] = 2] = "REWINDING"; +})(AsyncifyState || (AsyncifyState = {})); +function tryAllocate(instance, wasm64, size, mallocName) { + if (typeof instance.exports[mallocName] !== 'function' || size <= 0) { + return { + wasm64, + dataPtr: 16, + start: wasm64 ? 32 : 24, + end: 1024 + }; + } + const malloc = instance.exports[mallocName]; + const dataPtr = wasm64 ? Number(malloc(BigInt(16) + BigInt(size))) : malloc(8 + size); + if (dataPtr === 0) { + throw new Error('Allocate asyncify data failed'); + } + return wasm64 + ? { wasm64, dataPtr, start: dataPtr + 16, end: dataPtr + 16 + size } + : { wasm64, dataPtr, start: dataPtr + 8, end: dataPtr + 8 + size }; +} +/** @public */ +class Asyncify { + constructor() { + this.value = undefined; + this.exports = undefined; + this.dataPtr = 0; + } + init(memory, instance, options) { + var _a, _b; + if (this.exports) { + throw new Error('Asyncify has been initialized'); + } + if (!(memory instanceof webassembly_1._WebAssembly.Memory)) { + throw new TypeError('Require WebAssembly.Memory object'); + } + const exports = instance.exports; + for (let i = 0; i < ignoreNames.length; ++i) { + if (typeof exports[ignoreNames[i]] !== 'function') { + throw new TypeError('Invalid asyncify wasm'); + } + } + let address; + const wasm64 = Boolean(options.wasm64); + if (!options.tryAllocate) { + address = { + wasm64, + dataPtr: 16, + start: wasm64 ? 32 : 24, + end: 1024 + }; + } + else { + if (options.tryAllocate === true) { + address = tryAllocate(instance, wasm64, 4096, 'malloc'); + } + else { + address = tryAllocate(instance, wasm64, (_a = options.tryAllocate.size) !== null && _a !== void 0 ? _a : 4096, (_b = options.tryAllocate.name) !== null && _b !== void 0 ? _b : 'malloc'); + } + } + this.dataPtr = address.dataPtr; + if (wasm64) { + new BigInt64Array(memory.buffer, this.dataPtr).set([BigInt(address.start), BigInt(address.end)]); + } + else { + new Int32Array(memory.buffer, this.dataPtr).set([address.start, address.end]); + } + this.exports = this.wrapExports(exports, options.wrapExports); + const asyncifiedInstance = Object.create(webassembly_1._WebAssembly.Instance.prototype); + Object.defineProperty(asyncifiedInstance, 'exports', { value: this.exports }); + // Object.setPrototypeOf(instance, Instance.prototype) + return asyncifiedInstance; + } + assertState() { + if (this.exports.asyncify_get_state() !== AsyncifyState.NONE) { + throw new Error('Asyncify state error'); + } + } + wrapImportFunction(f) { + // eslint-disable-next-line @typescript-eslint/no-this-alias + const _this = this; + return (function () { + // eslint-disable-next-line no-unreachable-loop + while (_this.exports.asyncify_get_state() === AsyncifyState.REWINDING) { + _this.exports.asyncify_stop_rewind(); + return _this.value; + } + _this.assertState(); + const v = f.apply(this, arguments); + if (!(0, util_1.isPromiseLike)(v)) + return v; + _this.exports.asyncify_start_unwind(_this.dataPtr); + _this.value = v; + }); + } + wrapImports(imports) { + const importObject = {}; + Object.keys(imports).forEach(k => { + const mod = imports[k]; + const newModule = {}; + Object.keys(mod).forEach(name => { + const importValue = mod[name]; + if (typeof importValue === 'function') { + newModule[name] = this.wrapImportFunction(importValue); + } + else { + newModule[name] = importValue; + } + }); + importObject[k] = newModule; + }); + return importObject; + } + wrapExportFunction(f) { + // eslint-disable-next-line @typescript-eslint/no-this-alias + const _this = this; + return (async function () { + _this.assertState(); + let ret = f.apply(this, arguments); + while (_this.exports.asyncify_get_state() === AsyncifyState.UNWINDING) { + _this.exports.asyncify_stop_unwind(); + _this.value = await _this.value; + _this.assertState(); + _this.exports.asyncify_start_rewind(_this.dataPtr); + ret = f.call(this); + } + _this.assertState(); + return ret; + }); + } + wrapExports(exports, needWrap) { + return (0, util_1.wrapInstanceExports)(exports, (exportValue, name) => { + let ignore = ignoreNames.indexOf(name) !== -1 || typeof exportValue !== 'function'; + if (Array.isArray(needWrap)) { + ignore = ignore || (needWrap.indexOf(name) === -1); + } + return ignore ? exportValue : this.wrapExportFunction(exportValue); + }); + } +} +exports.Asyncify = Asyncify; +//# sourceMappingURL=asyncify.js.map \ No newline at end of file diff --git a/dg-ui/node_modules/@tailwindcss/oxide-wasm32-wasi/node_modules/@tybys/wasm-util/lib/cjs/index.js b/dg-ui/node_modules/@tailwindcss/oxide-wasm32-wasi/node_modules/@tybys/wasm-util/lib/cjs/index.js new file mode 100644 index 0000000..67a4444 --- /dev/null +++ b/dg-ui/node_modules/@tailwindcss/oxide-wasm32-wasi/node_modules/@tybys/wasm-util/lib/cjs/index.js @@ -0,0 +1,13 @@ +"use strict"; +/** + * @packageDocumentation + */ +Object.defineProperty(exports, "__esModule", { value: true }); +const tslib_1 = require("tslib"); +tslib_1.__exportStar(require("./asyncify"), exports); +tslib_1.__exportStar(require("./load"), exports); +tslib_1.__exportStar(require("./wasi/index"), exports); +tslib_1.__exportStar(require("./memory"), exports); +tslib_1.__exportStar(require("./jspi"), exports); +tslib_1.__exportStar(require("./wasi/fs"), exports); +//# sourceMappingURL=index.js.map \ No newline at end of file diff --git a/dg-ui/node_modules/@tailwindcss/oxide-wasm32-wasi/node_modules/@tybys/wasm-util/lib/cjs/jspi.js b/dg-ui/node_modules/@tailwindcss/oxide-wasm32-wasi/node_modules/@tybys/wasm-util/lib/cjs/jspi.js new file mode 100644 index 0000000..1345bc7 --- /dev/null +++ b/dg-ui/node_modules/@tailwindcss/oxide-wasm32-wasi/node_modules/@tybys/wasm-util/lib/cjs/jspi.js @@ -0,0 +1,46 @@ +"use strict"; +Object.defineProperty(exports, "__esModule", { value: true }); +exports.wrapExports = exports.wrapAsyncExport = exports.wrapAsyncImport = void 0; +const util_1 = require("./wasi/util"); +const webassembly_1 = require("./webassembly"); +function checkWebAssemblyFunction() { + const WebAssemblyFunction = webassembly_1._WebAssembly.Function; + if (typeof WebAssemblyFunction !== 'function') { + throw new Error('WebAssembly.Function is not supported in this environment.' + + ' If you are using V8 based browser like Chrome, try to specify' + + ' --js-flags="--wasm-staging --experimental-wasm-stack-switching"'); + } + return WebAssemblyFunction; +} +/** @public */ +function wrapAsyncImport(f, parameterType, returnType) { + const WebAssemblyFunction = checkWebAssemblyFunction(); + if (typeof f !== 'function') { + throw new TypeError('Function required'); + } + const parameters = parameterType.slice(0); + parameters.unshift('externref'); + return new WebAssemblyFunction({ parameters, results: returnType }, f, { suspending: 'first' }); +} +exports.wrapAsyncImport = wrapAsyncImport; +/** @public */ +function wrapAsyncExport(f) { + const WebAssemblyFunction = checkWebAssemblyFunction(); + if (typeof f !== 'function') { + throw new TypeError('Function required'); + } + return new WebAssemblyFunction({ parameters: [...WebAssemblyFunction.type(f).parameters.slice(1)], results: ['externref'] }, f, { promising: 'first' }); +} +exports.wrapAsyncExport = wrapAsyncExport; +/** @public */ +function wrapExports(exports, needWrap) { + return (0, util_1.wrapInstanceExports)(exports, (exportValue, name) => { + let ignore = typeof exportValue !== 'function'; + if (Array.isArray(needWrap)) { + ignore = ignore || (needWrap.indexOf(name) === -1); + } + return ignore ? exportValue : wrapAsyncExport(exportValue); + }); +} +exports.wrapExports = wrapExports; +//# sourceMappingURL=jspi.js.map \ No newline at end of file diff --git a/dg-ui/node_modules/@tailwindcss/oxide-wasm32-wasi/node_modules/@tybys/wasm-util/lib/cjs/load.js b/dg-ui/node_modules/@tailwindcss/oxide-wasm32-wasi/node_modules/@tybys/wasm-util/lib/cjs/load.js new file mode 100644 index 0000000..9138345 --- /dev/null +++ b/dg-ui/node_modules/@tailwindcss/oxide-wasm32-wasi/node_modules/@tybys/wasm-util/lib/cjs/load.js @@ -0,0 +1,97 @@ +"use strict"; +Object.defineProperty(exports, "__esModule", { value: true }); +exports.asyncifyLoadSync = exports.loadSync = exports.asyncifyLoad = exports.load = void 0; +const webassembly_1 = require("./webassembly"); +const asyncify_1 = require("./asyncify"); +function validateImports(imports) { + if (imports && typeof imports !== 'object') { + throw new TypeError('imports must be an object or undefined'); + } +} +function fetchWasm(urlOrBuffer, imports) { + if (typeof wx !== 'undefined' && typeof __wxConfig !== 'undefined') { + return webassembly_1._WebAssembly.instantiate(urlOrBuffer, imports); + } + return fetch(urlOrBuffer) + .then(response => response.arrayBuffer()) + .then(buffer => webassembly_1._WebAssembly.instantiate(buffer, imports)); +} +/** @public */ +function load(wasmInput, imports) { + validateImports(imports); + imports = imports !== null && imports !== void 0 ? imports : {}; + let source; + if (wasmInput instanceof ArrayBuffer || ArrayBuffer.isView(wasmInput)) { + return webassembly_1._WebAssembly.instantiate(wasmInput, imports); + } + if (wasmInput instanceof webassembly_1._WebAssembly.Module) { + return webassembly_1._WebAssembly.instantiate(wasmInput, imports).then((instance) => { + return { instance, module: wasmInput }; + }); + } + if (typeof wasmInput !== 'string' && !(wasmInput instanceof URL)) { + throw new TypeError('Invalid source'); + } + if (typeof webassembly_1._WebAssembly.instantiateStreaming === 'function') { + let responsePromise; + try { + responsePromise = fetch(wasmInput); + source = webassembly_1._WebAssembly.instantiateStreaming(responsePromise, imports).catch(() => { + return fetchWasm(wasmInput, imports); + }); + } + catch (_) { + source = fetchWasm(wasmInput, imports); + } + } + else { + source = fetchWasm(wasmInput, imports); + } + return source; +} +exports.load = load; +/** @public */ +function asyncifyLoad(asyncify, urlOrBuffer, imports) { + validateImports(imports); + imports = imports !== null && imports !== void 0 ? imports : {}; + const asyncifyHelper = new asyncify_1.Asyncify(); + imports = asyncifyHelper.wrapImports(imports); + return load(urlOrBuffer, imports).then(source => { + var _a; + const memory = source.instance.exports.memory || ((_a = imports.env) === null || _a === void 0 ? void 0 : _a.memory); + return { module: source.module, instance: asyncifyHelper.init(memory, source.instance, asyncify) }; + }); +} +exports.asyncifyLoad = asyncifyLoad; +/** @public */ +function loadSync(wasmInput, imports) { + validateImports(imports); + imports = imports !== null && imports !== void 0 ? imports : {}; + let module; + if ((wasmInput instanceof ArrayBuffer) || ArrayBuffer.isView(wasmInput)) { + module = new webassembly_1._WebAssembly.Module(wasmInput); + } + else if (wasmInput instanceof WebAssembly.Module) { + module = wasmInput; + } + else { + throw new TypeError('Invalid source'); + } + const instance = new webassembly_1._WebAssembly.Instance(module, imports); + const source = { instance, module }; + return source; +} +exports.loadSync = loadSync; +/** @public */ +function asyncifyLoadSync(asyncify, buffer, imports) { + var _a; + validateImports(imports); + imports = imports !== null && imports !== void 0 ? imports : {}; + const asyncifyHelper = new asyncify_1.Asyncify(); + imports = asyncifyHelper.wrapImports(imports); + const source = loadSync(buffer, imports); + const memory = source.instance.exports.memory || ((_a = imports.env) === null || _a === void 0 ? void 0 : _a.memory); + return { module: source.module, instance: asyncifyHelper.init(memory, source.instance, asyncify) }; +} +exports.asyncifyLoadSync = asyncifyLoadSync; +//# sourceMappingURL=load.js.map \ No newline at end of file diff --git a/dg-ui/node_modules/@tailwindcss/oxide-wasm32-wasi/node_modules/@tybys/wasm-util/lib/cjs/memory.js b/dg-ui/node_modules/@tailwindcss/oxide-wasm32-wasi/node_modules/@tybys/wasm-util/lib/cjs/memory.js new file mode 100644 index 0000000..ca46ca5 --- /dev/null +++ b/dg-ui/node_modules/@tailwindcss/oxide-wasm32-wasi/node_modules/@tybys/wasm-util/lib/cjs/memory.js @@ -0,0 +1,35 @@ +"use strict"; +Object.defineProperty(exports, "__esModule", { value: true }); +exports.extendMemory = exports.Memory = exports.WebAssemblyMemory = void 0; +/* eslint-disable spaced-comment */ +const webassembly_1 = require("./webassembly"); +/** @public */ +exports.WebAssemblyMemory = (function () { return webassembly_1._WebAssembly.Memory; })(); +/** @public */ +class Memory extends exports.WebAssemblyMemory { + // eslint-disable-next-line @typescript-eslint/no-useless-constructor + constructor(descriptor) { + super(descriptor); + } + get HEAP8() { return new Int8Array(super.buffer); } + get HEAPU8() { return new Uint8Array(super.buffer); } + get HEAP16() { return new Int16Array(super.buffer); } + get HEAPU16() { return new Uint16Array(super.buffer); } + get HEAP32() { return new Int32Array(super.buffer); } + get HEAPU32() { return new Uint32Array(super.buffer); } + get HEAP64() { return new BigInt64Array(super.buffer); } + get HEAPU64() { return new BigUint64Array(super.buffer); } + get HEAPF32() { return new Float32Array(super.buffer); } + get HEAPF64() { return new Float64Array(super.buffer); } + get view() { return new DataView(super.buffer); } +} +exports.Memory = Memory; +/** @public */ +function extendMemory(memory) { + if (Object.getPrototypeOf(memory) === webassembly_1._WebAssembly.Memory.prototype) { + Object.setPrototypeOf(memory, Memory.prototype); + } + return memory; +} +exports.extendMemory = extendMemory; +//# sourceMappingURL=memory.js.map \ No newline at end of file diff --git a/dg-ui/node_modules/@tailwindcss/oxide-wasm32-wasi/node_modules/@tybys/wasm-util/lib/cjs/wasi/error.js b/dg-ui/node_modules/@tailwindcss/oxide-wasm32-wasi/node_modules/@tybys/wasm-util/lib/cjs/wasi/error.js new file mode 100644 index 0000000..e417da3 --- /dev/null +++ b/dg-ui/node_modules/@tailwindcss/oxide-wasm32-wasi/node_modules/@tybys/wasm-util/lib/cjs/wasi/error.js @@ -0,0 +1,103 @@ +"use strict"; +Object.defineProperty(exports, "__esModule", { value: true }); +exports.WasiError = exports.strerror = void 0; +const types_1 = require("./types"); +function strerror(errno) { + switch (errno) { + case types_1.WasiErrno.ESUCCESS: return 'Success'; + case types_1.WasiErrno.E2BIG: return 'Argument list too long'; + case types_1.WasiErrno.EACCES: return 'Permission denied'; + case types_1.WasiErrno.EADDRINUSE: return 'Address in use'; + case types_1.WasiErrno.EADDRNOTAVAIL: return 'Address not available'; + case types_1.WasiErrno.EAFNOSUPPORT: return 'Address family not supported by protocol'; + case types_1.WasiErrno.EAGAIN: return 'Resource temporarily unavailable'; + case types_1.WasiErrno.EALREADY: return 'Operation already in progress'; + case types_1.WasiErrno.EBADF: return 'Bad file descriptor'; + case types_1.WasiErrno.EBADMSG: return 'Bad message'; + case types_1.WasiErrno.EBUSY: return 'Resource busy'; + case types_1.WasiErrno.ECANCELED: return 'Operation canceled'; + case types_1.WasiErrno.ECHILD: return 'No child process'; + case types_1.WasiErrno.ECONNABORTED: return 'Connection aborted'; + case types_1.WasiErrno.ECONNREFUSED: return 'Connection refused'; + case types_1.WasiErrno.ECONNRESET: return 'Connection reset by peer'; + case types_1.WasiErrno.EDEADLK: return 'Resource deadlock would occur'; + case types_1.WasiErrno.EDESTADDRREQ: return 'Destination address required'; + case types_1.WasiErrno.EDOM: return 'Domain error'; + case types_1.WasiErrno.EDQUOT: return 'Quota exceeded'; + case types_1.WasiErrno.EEXIST: return 'File exists'; + case types_1.WasiErrno.EFAULT: return 'Bad address'; + case types_1.WasiErrno.EFBIG: return 'File too large'; + case types_1.WasiErrno.EHOSTUNREACH: return 'Host is unreachable'; + case types_1.WasiErrno.EIDRM: return 'Identifier removed'; + case types_1.WasiErrno.EILSEQ: return 'Illegal byte sequence'; + case types_1.WasiErrno.EINPROGRESS: return 'Operation in progress'; + case types_1.WasiErrno.EINTR: return 'Interrupted system call'; + case types_1.WasiErrno.EINVAL: return 'Invalid argument'; + case types_1.WasiErrno.EIO: return 'I/O error'; + case types_1.WasiErrno.EISCONN: return 'Socket is connected'; + case types_1.WasiErrno.EISDIR: return 'Is a directory'; + case types_1.WasiErrno.ELOOP: return 'Symbolic link loop'; + case types_1.WasiErrno.EMFILE: return 'No file descriptors available'; + case types_1.WasiErrno.EMLINK: return 'Too many links'; + case types_1.WasiErrno.EMSGSIZE: return 'Message too large'; + case types_1.WasiErrno.EMULTIHOP: return 'Multihop attempted'; + case types_1.WasiErrno.ENAMETOOLONG: return 'Filename too long'; + case types_1.WasiErrno.ENETDOWN: return 'Network is down'; + case types_1.WasiErrno.ENETRESET: return 'Connection reset by network'; + case types_1.WasiErrno.ENETUNREACH: return 'Network unreachable'; + case types_1.WasiErrno.ENFILE: return 'Too many files open in system'; + case types_1.WasiErrno.ENOBUFS: return 'No buffer space available'; + case types_1.WasiErrno.ENODEV: return 'No such device'; + case types_1.WasiErrno.ENOENT: return 'No such file or directory'; + case types_1.WasiErrno.ENOEXEC: return 'Exec format error'; + case types_1.WasiErrno.ENOLCK: return 'No locks available'; + case types_1.WasiErrno.ENOLINK: return 'Link has been severed'; + case types_1.WasiErrno.ENOMEM: return 'Out of memory'; + case types_1.WasiErrno.ENOMSG: return 'No message of the desired type'; + case types_1.WasiErrno.ENOPROTOOPT: return 'Protocol not available'; + case types_1.WasiErrno.ENOSPC: return 'No space left on device'; + case types_1.WasiErrno.ENOSYS: return 'Function not implemented'; + case types_1.WasiErrno.ENOTCONN: return 'Socket not connected'; + case types_1.WasiErrno.ENOTDIR: return 'Not a directory'; + case types_1.WasiErrno.ENOTEMPTY: return 'Directory not empty'; + case types_1.WasiErrno.ENOTRECOVERABLE: return 'State not recoverable'; + case types_1.WasiErrno.ENOTSOCK: return 'Not a socket'; + case types_1.WasiErrno.ENOTSUP: return 'Not supported'; + case types_1.WasiErrno.ENOTTY: return 'Not a tty'; + case types_1.WasiErrno.ENXIO: return 'No such device or address'; + case types_1.WasiErrno.EOVERFLOW: return 'Value too large for data type'; + case types_1.WasiErrno.EOWNERDEAD: return 'Previous owner died'; + case types_1.WasiErrno.EPERM: return 'Operation not permitted'; + case types_1.WasiErrno.EPIPE: return 'Broken pipe'; + case types_1.WasiErrno.EPROTO: return 'Protocol error'; + case types_1.WasiErrno.EPROTONOSUPPORT: return 'Protocol not supported'; + case types_1.WasiErrno.EPROTOTYPE: return 'Protocol wrong type for socket'; + case types_1.WasiErrno.ERANGE: return 'Result not representable'; + case types_1.WasiErrno.EROFS: return 'Read-only file system'; + case types_1.WasiErrno.ESPIPE: return 'Invalid seek'; + case types_1.WasiErrno.ESRCH: return 'No such process'; + case types_1.WasiErrno.ESTALE: return 'Stale file handle'; + case types_1.WasiErrno.ETIMEDOUT: return 'Operation timed out'; + case types_1.WasiErrno.ETXTBSY: return 'Text file busy'; + case types_1.WasiErrno.EXDEV: return 'Cross-device link'; + case types_1.WasiErrno.ENOTCAPABLE: return 'Capabilities insufficient'; + default: return 'Unknown error'; + } +} +exports.strerror = strerror; +class WasiError extends Error { + constructor(message, errno) { + super(message); + this.errno = errno; + } + getErrorMessage() { + return strerror(this.errno); + } +} +exports.WasiError = WasiError; +Object.defineProperty(WasiError.prototype, 'name', { + configurable: true, + writable: true, + value: 'WasiError' +}); +//# sourceMappingURL=error.js.map \ No newline at end of file diff --git a/dg-ui/node_modules/@tailwindcss/oxide-wasm32-wasi/node_modules/@tybys/wasm-util/lib/cjs/wasi/fd.js b/dg-ui/node_modules/@tailwindcss/oxide-wasm32-wasi/node_modules/@tybys/wasm-util/lib/cjs/wasi/fd.js new file mode 100644 index 0000000..4cc3fbc --- /dev/null +++ b/dg-ui/node_modules/@tailwindcss/oxide-wasm32-wasi/node_modules/@tybys/wasm-util/lib/cjs/wasi/fd.js @@ -0,0 +1,268 @@ +"use strict"; +Object.defineProperty(exports, "__esModule", { value: true }); +exports.AsyncTable = exports.SyncTable = exports.FileDescriptorTable = exports.toFileStat = exports.toFileType = exports.StandardOutput = exports.FileDescriptor = exports.concatBuffer = void 0; +const types_1 = require("./types"); +const rights_1 = require("./rights"); +const error_1 = require("./error"); +function concatBuffer(buffers, size) { + let total = 0; + if (typeof size === 'number' && size >= 0) { + total = size; + } + else { + for (let i = 0; i < buffers.length; i++) { + const buffer = buffers[i]; + total += buffer.length; + } + } + let pos = 0; + const ret = new Uint8Array(total); + for (let i = 0; i < buffers.length; i++) { + const buffer = buffers[i]; + ret.set(buffer, pos); + pos += buffer.length; + } + return ret; +} +exports.concatBuffer = concatBuffer; +class FileDescriptor { + constructor(id, fd, path, realPath, type, rightsBase, rightsInheriting, preopen) { + this.id = id; + this.fd = fd; + this.path = path; + this.realPath = realPath; + this.type = type; + this.rightsBase = rightsBase; + this.rightsInheriting = rightsInheriting; + this.preopen = preopen; + this.pos = BigInt(0); + this.size = BigInt(0); + } + seek(offset, whence) { + if (whence === types_1.WasiWhence.SET) { + this.pos = BigInt(offset); + } + else if (whence === types_1.WasiWhence.CUR) { + this.pos += BigInt(offset); + } + else if (whence === types_1.WasiWhence.END) { + this.pos = BigInt(this.size) - BigInt(offset); + } + else { + throw new error_1.WasiError('Unknown whence', types_1.WasiErrno.EIO); + } + return this.pos; + } +} +exports.FileDescriptor = FileDescriptor; +class StandardOutput extends FileDescriptor { + constructor(log, id, fd, path, realPath, type, rightsBase, rightsInheriting, preopen) { + super(id, fd, path, realPath, type, rightsBase, rightsInheriting, preopen); + this._log = log; + this._buf = null; + } + write(buffer) { + const originalBuffer = buffer; + if (this._buf) { + buffer = concatBuffer([this._buf, buffer]); + this._buf = null; + } + if (buffer.indexOf(10) === -1) { + this._buf = buffer; + return originalBuffer.byteLength; + } + let written = 0; + let lastBegin = 0; + let index; + while ((index = buffer.indexOf(10, written)) !== -1) { + const str = new TextDecoder().decode(buffer.subarray(lastBegin, index)); + this._log(str); + written += index - lastBegin + 1; + lastBegin = index + 1; + } + if (written < buffer.length) { + this._buf = buffer.slice(written); + } + return originalBuffer.byteLength; + } +} +exports.StandardOutput = StandardOutput; +function toFileType(stat) { + if (stat.isBlockDevice()) + return types_1.WasiFileType.BLOCK_DEVICE; + if (stat.isCharacterDevice()) + return types_1.WasiFileType.CHARACTER_DEVICE; + if (stat.isDirectory()) + return types_1.WasiFileType.DIRECTORY; + if (stat.isSocket()) + return types_1.WasiFileType.SOCKET_STREAM; + if (stat.isFile()) + return types_1.WasiFileType.REGULAR_FILE; + if (stat.isSymbolicLink()) + return types_1.WasiFileType.SYMBOLIC_LINK; + return types_1.WasiFileType.UNKNOWN; +} +exports.toFileType = toFileType; +function toFileStat(view, buf, stat) { + view.setBigUint64(buf, stat.dev, true); + view.setBigUint64(buf + 8, stat.ino, true); + view.setBigUint64(buf + 16, BigInt(toFileType(stat)), true); + view.setBigUint64(buf + 24, stat.nlink, true); + view.setBigUint64(buf + 32, stat.size, true); + view.setBigUint64(buf + 40, stat.atimeMs * BigInt(1000000), true); + view.setBigUint64(buf + 48, stat.mtimeMs * BigInt(1000000), true); + view.setBigUint64(buf + 56, stat.ctimeMs * BigInt(1000000), true); +} +exports.toFileStat = toFileStat; +class FileDescriptorTable { + constructor(options) { + this.used = 0; + this.size = options.size; + this.fds = Array(options.size); + this.stdio = [options.in, options.out, options.err]; + this.print = options.print; + this.printErr = options.printErr; + this.insertStdio(options.in, 0, ''); + this.insertStdio(options.out, 1, ''); + this.insertStdio(options.err, 2, ''); + } + insertStdio(fd, expected, name) { + const type = types_1.WasiFileType.CHARACTER_DEVICE; + const { base, inheriting } = (0, rights_1.getRights)(this.stdio, fd, types_1.FileControlFlag.O_RDWR, type); + const wrap = this.insert(fd, name, name, type, base, inheriting, 0); + if (wrap.id !== expected) { + throw new error_1.WasiError(`id: ${wrap.id} !== expected: ${expected}`, types_1.WasiErrno.EBADF); + } + return wrap; + } + insert(fd, mappedPath, realPath, type, rightsBase, rightsInheriting, preopen) { + var _a, _b; + let index = -1; + if (this.used >= this.size) { + const newSize = this.size * 2; + this.fds.length = newSize; + index = this.size; + this.size = newSize; + } + else { + for (let i = 0; i < this.size; ++i) { + if (this.fds[i] == null) { + index = i; + break; + } + } + } + let entry; + if (mappedPath === '') { + entry = new StandardOutput((_a = this.print) !== null && _a !== void 0 ? _a : console.log, index, fd, mappedPath, realPath, type, rightsBase, rightsInheriting, preopen); + } + else if (mappedPath === '') { + entry = new StandardOutput((_b = this.printErr) !== null && _b !== void 0 ? _b : console.error, index, fd, mappedPath, realPath, type, rightsBase, rightsInheriting, preopen); + } + else { + entry = new FileDescriptor(index, fd, mappedPath, realPath, type, rightsBase, rightsInheriting, preopen); + } + this.fds[index] = entry; + this.used++; + return entry; + } + get(id, base, inheriting) { + if (id >= this.size) { + throw new error_1.WasiError('Invalid fd', types_1.WasiErrno.EBADF); + } + const entry = this.fds[id]; + if (!entry || entry.id !== id) { + throw new error_1.WasiError('Bad file descriptor', types_1.WasiErrno.EBADF); + } + /* Validate that the fd has the necessary rights. */ + if ((~entry.rightsBase & base) !== BigInt(0) || (~entry.rightsInheriting & inheriting) !== BigInt(0)) { + throw new error_1.WasiError('Capabilities insufficient', types_1.WasiErrno.ENOTCAPABLE); + } + return entry; + } + remove(id) { + if (id >= this.size) { + throw new error_1.WasiError('Invalid fd', types_1.WasiErrno.EBADF); + } + const entry = this.fds[id]; + if (!entry || entry.id !== id) { + throw new error_1.WasiError('Bad file descriptor', types_1.WasiErrno.EBADF); + } + this.fds[id] = undefined; + this.used--; + } +} +exports.FileDescriptorTable = FileDescriptorTable; +class SyncTable extends FileDescriptorTable { + constructor(options) { + super(options); + this.fs = options.fs; + } + getFileTypeByFd(fd) { + const stats = this.fs.fstatSync(fd, { bigint: true }); + return toFileType(stats); + } + insertPreopen(fd, mappedPath, realPath) { + const type = this.getFileTypeByFd(fd); + if (type !== types_1.WasiFileType.DIRECTORY) { + throw new error_1.WasiError(`Preopen not dir: ["${mappedPath}", "${realPath}"]`, types_1.WasiErrno.ENOTDIR); + } + const result = (0, rights_1.getRights)(this.stdio, fd, 0, type); + return this.insert(fd, mappedPath, realPath, type, result.base, result.inheriting, 1); + } + renumber(dst, src) { + if (dst === src) + return; + if (dst >= this.size || src >= this.size) { + throw new error_1.WasiError('Invalid fd', types_1.WasiErrno.EBADF); + } + const dstEntry = this.fds[dst]; + const srcEntry = this.fds[src]; + if (!dstEntry || !srcEntry || dstEntry.id !== dst || srcEntry.id !== src) { + throw new error_1.WasiError('Invalid fd', types_1.WasiErrno.EBADF); + } + this.fs.closeSync(dstEntry.fd); + this.fds[dst] = this.fds[src]; + this.fds[dst].id = dst; + this.fds[src] = undefined; + this.used--; + } +} +exports.SyncTable = SyncTable; +class AsyncTable extends FileDescriptorTable { + // eslint-disable-next-line @typescript-eslint/no-useless-constructor + constructor(options) { + super(options); + } + async getFileTypeByFd(fd) { + const stats = await fd.stat({ bigint: true }); + return toFileType(stats); + } + async insertPreopen(fd, mappedPath, realPath) { + const type = await this.getFileTypeByFd(fd); + if (type !== types_1.WasiFileType.DIRECTORY) { + throw new error_1.WasiError(`Preopen not dir: ["${mappedPath}", "${realPath}"]`, types_1.WasiErrno.ENOTDIR); + } + const result = (0, rights_1.getRights)(this.stdio, fd.fd, 0, type); + return this.insert(fd, mappedPath, realPath, type, result.base, result.inheriting, 1); + } + async renumber(dst, src) { + if (dst === src) + return; + if (dst >= this.size || src >= this.size) { + throw new error_1.WasiError('Invalid fd', types_1.WasiErrno.EBADF); + } + const dstEntry = this.fds[dst]; + const srcEntry = this.fds[src]; + if (!dstEntry || !srcEntry || dstEntry.id !== dst || srcEntry.id !== src) { + throw new error_1.WasiError('Invalid fd', types_1.WasiErrno.EBADF); + } + await dstEntry.fd.close(); + this.fds[dst] = this.fds[src]; + this.fds[dst].id = dst; + this.fds[src] = undefined; + this.used--; + } +} +exports.AsyncTable = AsyncTable; +//# sourceMappingURL=fd.js.map \ No newline at end of file diff --git a/dg-ui/node_modules/@tailwindcss/oxide-wasm32-wasi/node_modules/@tybys/wasm-util/lib/cjs/wasi/fs.js b/dg-ui/node_modules/@tailwindcss/oxide-wasm32-wasi/node_modules/@tybys/wasm-util/lib/cjs/wasi/fs.js new file mode 100644 index 0000000..f9e16d9 --- /dev/null +++ b/dg-ui/node_modules/@tailwindcss/oxide-wasm32-wasi/node_modules/@tybys/wasm-util/lib/cjs/wasi/fs.js @@ -0,0 +1,3 @@ +"use strict"; +Object.defineProperty(exports, "__esModule", { value: true }); +//# sourceMappingURL=fs.js.map \ No newline at end of file diff --git a/dg-ui/node_modules/@tailwindcss/oxide-wasm32-wasi/node_modules/@tybys/wasm-util/lib/cjs/wasi/index.js b/dg-ui/node_modules/@tailwindcss/oxide-wasm32-wasi/node_modules/@tybys/wasm-util/lib/cjs/wasi/index.js new file mode 100644 index 0000000..44865ea --- /dev/null +++ b/dg-ui/node_modules/@tailwindcss/oxide-wasm32-wasi/node_modules/@tybys/wasm-util/lib/cjs/wasi/index.js @@ -0,0 +1,192 @@ +"use strict"; +Object.defineProperty(exports, "__esModule", { value: true }); +exports.createAsyncWASI = exports.WASI = void 0; +const preview1_1 = require("./preview1"); +const util_1 = require("./util"); +// eslint-disable-next-line spaced-comment +const kEmptyObject = /*#__PURE__*/ Object.freeze(/*#__PURE__*/ Object.create(null)); +const kExitCode = Symbol('kExitCode'); +const kSetMemory = Symbol('kSetMemory'); +const kStarted = Symbol('kStarted'); +const kInstance = Symbol('kInstance'); +const kBindingName = Symbol('kBindingName'); +function validateOptions(options) { + var _a; + (0, util_1.validateObject)(options, 'options'); + let _WASI; + if (options.version !== undefined) { + (0, util_1.validateString)(options.version, 'options.version'); + switch (options.version) { + case 'unstable': + _WASI = preview1_1.WASI; + this[kBindingName] = 'wasi_unstable'; + break; + case 'preview1': + _WASI = preview1_1.WASI; + this[kBindingName] = 'wasi_snapshot_preview1'; + break; + default: + throw new TypeError(`unsupported WASI version "${options.version}"`); + } + } + else { + _WASI = preview1_1.WASI; + this[kBindingName] = 'wasi_snapshot_preview1'; + } + if (options.args !== undefined) { + (0, util_1.validateArray)(options.args, 'options.args'); + } + const args = ((_a = options.args) !== null && _a !== void 0 ? _a : []).map(String); + const env = []; + if (options.env !== undefined) { + (0, util_1.validateObject)(options.env, 'options.env'); + Object.entries(options.env).forEach(({ 0: key, 1: value }) => { + if (value !== undefined) { + env.push(`${key}=${value}`); + } + }); + } + const preopens = []; + if (options.preopens !== undefined) { + (0, util_1.validateObject)(options.preopens, 'options.preopens'); + Object.entries(options.preopens).forEach(({ 0: key, 1: value }) => preopens.push({ mappedPath: String(key), realPath: String(value) })); + } + if (preopens.length > 0) { + if (options.fs === undefined) { + throw new Error('filesystem is disabled, can not preopen directory'); + } + try { + (0, util_1.validateObject)(options.fs, 'options.fs'); + } + catch (_) { + throw new TypeError('Node.js fs like implementation is not provided'); + } + } + // if (options.filesystem !== undefined) { + // validateObject(options.filesystem, 'options.filesystem') + // validateString(options.filesystem.type, 'options.filesystem.type') + // if (options.filesystem.type !== 'memfs' && options.filesystem.type !== 'file-system-access-api') { + // throw new Error(`Filesystem type ${(options.filesystem as any).type as string} is not supported, only "memfs" and "file-system-access-api" is supported currently`) + // } + // try { + // validateObject(options.filesystem.fs, 'options.filesystem.fs') + // } catch (_) { + // throw new Error('Node.js fs like implementation is not provided') + // } + // } + if (options.print !== undefined) + (0, util_1.validateFunction)(options.print, 'options.print'); + if (options.printErr !== undefined) + (0, util_1.validateFunction)(options.printErr, 'options.printErr'); + if (options.returnOnExit !== undefined) { + (0, util_1.validateBoolean)(options.returnOnExit, 'options.returnOnExit'); + } + // const { stdin = 0, stdout = 1, stderr = 2 } = options + // validateInt32(stdin, 'options.stdin', 0) + // validateInt32(stdout, 'options.stdout', 0) + // validateInt32(stderr, 'options.stderr', 0) + // const stdio = [stdin, stdout, stderr] as const + const stdio = [0, 1, 2]; + return { + args, + env, + preopens, + stdio, + _WASI + }; +} +function initWASI(setMemory, wrap) { + this[kSetMemory] = setMemory; + this.wasiImport = wrap; + this[kStarted] = false; + this[kExitCode] = 0; + this[kInstance] = undefined; +} +/** @public */ +class WASI { + constructor(options = kEmptyObject) { + const { args, env, preopens, stdio, _WASI } = validateOptions.call(this, options); + const wrap = _WASI.createSync(args, env, preopens, stdio, options.fs, options.print, options.printErr); + const setMemory = wrap._setMemory; + delete wrap._setMemory; + initWASI.call(this, setMemory, wrap); + if (options.returnOnExit) { + wrap.proc_exit = wasiReturnOnProcExit.bind(this); + } + } + finalizeBindings(instance, _a) { + var _b; + var { memory = (_b = instance === null || instance === void 0 ? void 0 : instance.exports) === null || _b === void 0 ? void 0 : _b.memory } = _a === void 0 ? {} : _a; + if (this[kStarted]) { + throw new Error('WASI instance has already started'); + } + (0, util_1.validateObject)(instance, 'instance'); + (0, util_1.validateObject)(instance.exports, 'instance.exports'); + this[kSetMemory](memory); + this[kInstance] = instance; + this[kStarted] = true; + } + // Must not export _initialize, must export _start + start(instance) { + this.finalizeBindings(instance); + const { _start, _initialize } = this[kInstance].exports; + (0, util_1.validateFunction)(_start, 'instance.exports._start'); + (0, util_1.validateUndefined)(_initialize, 'instance.exports._initialize'); + let ret; + try { + ret = _start(); + } + catch (err) { + if (err !== kExitCode) { + throw err; + } + } + if (ret instanceof Promise) { + return ret.then(() => this[kExitCode], (err) => { + if (err !== kExitCode) { + throw err; + } + return this[kExitCode]; + }); + } + return this[kExitCode]; + } + // Must not export _start, may optionally export _initialize + initialize(instance) { + this.finalizeBindings(instance); + const { _start, _initialize } = this[kInstance].exports; + (0, util_1.validateUndefined)(_start, 'instance.exports._start'); + if (_initialize !== undefined) { + (0, util_1.validateFunction)(_initialize, 'instance.exports._initialize'); + return _initialize(); + } + } + getImportObject() { + return { [this[kBindingName]]: this.wasiImport }; + } +} +exports.WASI = WASI; +function wasiReturnOnProcExit(rval) { + this[kExitCode] = rval; + // eslint-disable-next-line @typescript-eslint/no-throw-literal + throw kExitCode; +} +/** @public */ +async function createAsyncWASI(options = kEmptyObject) { + const _this = Object.create(WASI.prototype); + const { args, env, preopens, stdio, _WASI } = validateOptions.call(_this, options); + if (options.asyncify !== undefined) { + (0, util_1.validateObject)(options.asyncify, 'options.asyncify'); + (0, util_1.validateFunction)(options.asyncify.wrapImportFunction, 'options.asyncify.wrapImportFunction'); + } + const wrap = await _WASI.createAsync(args, env, preopens, stdio, options.fs, options.print, options.printErr, options.asyncify); + const setMemory = wrap._setMemory; + delete wrap._setMemory; + initWASI.call(_this, setMemory, wrap); + if (options.returnOnExit) { + wrap.proc_exit = wasiReturnOnProcExit.bind(_this); + } + return _this; +} +exports.createAsyncWASI = createAsyncWASI; +//# sourceMappingURL=index.js.map \ No newline at end of file diff --git a/dg-ui/node_modules/@tailwindcss/oxide-wasm32-wasi/node_modules/@tybys/wasm-util/lib/cjs/wasi/path.js b/dg-ui/node_modules/@tailwindcss/oxide-wasm32-wasi/node_modules/@tybys/wasm-util/lib/cjs/wasi/path.js new file mode 100644 index 0000000..280f454 --- /dev/null +++ b/dg-ui/node_modules/@tailwindcss/oxide-wasm32-wasi/node_modules/@tybys/wasm-util/lib/cjs/wasi/path.js @@ -0,0 +1,316 @@ +"use strict"; +Object.defineProperty(exports, "__esModule", { value: true }); +exports.relative = exports.resolve = void 0; +const util_1 = require("./util"); +const CHAR_DOT = 46; /* . */ +const CHAR_FORWARD_SLASH = 47; /* / */ +const CHAR_BACKWARD_SLASH = 92; /* \ */ +const CHAR_COLON = 58; /* : */ +const CHAR_UPPERCASE_A = 65; /* A */ +const CHAR_UPPERCASE_Z = 90; /* Z */ +const CHAR_LOWERCASE_A = 97; /* a */ +const CHAR_LOWERCASE_Z = 122; /* z */ +function isPathSeparatorWin(code) { + return code === CHAR_FORWARD_SLASH || code === CHAR_BACKWARD_SLASH; +} +function isWindowsDeviceRoot(code) { + return (code >= CHAR_UPPERCASE_A && code <= CHAR_UPPERCASE_Z) || + (code >= CHAR_LOWERCASE_A && code <= CHAR_LOWERCASE_Z); +} +const _isWin32 = typeof process !== 'undefined' && process.platform === 'win32'; +/** + * Windows variant of `resolve()`. Mirrors Node's `path.win32.resolve` + * semantics enough for the WASI shim's needs (drive-letter absolutes + * + UNC paths + per-drive cwd lookups via `process.env`/`process.cwd`). + * + * Why this is needed: on Windows, `FileDescriptor.realPath` is the + * host realpath returned by `fs.realpathSync(realPath, 'utf8')` — the + * backslash form `D:\…`. The POSIX-only `resolveImpl` below only + * treats `/` as a separator, reads `D` as non-`/`, decides realPath + * is "relative", and produces a garbage joined path. Downstream + * `fs.openSync(garbage)` then returns `EINVAL` and the WASI caller + * sees a permanent failure. This function gives us the correct + * Windows-style resolution without taking a Node-only `path` import + * (which would break browser bundles of this package). + * + * Cribbed from Node's `lib/path.js` `win32.resolve()` (MIT-licensed), + * trimmed to what WASI realpath resolution actually exercises. + */ +function resolveWin32(args) { + let resolvedDevice = ''; + let resolvedTail = ''; + let resolvedAbsolute = false; + for (let i = args.length - 1; i >= -1; i--) { + let path; + if (i >= 0) { + path = args[i]; + (0, util_1.validateString)(path, 'path'); + if (path.length === 0) + continue; + } + else if (resolvedDevice.length === 0) { + path = (typeof process !== 'undefined' && typeof process.cwd === 'function') + ? process.cwd() + : ''; + } + else { + // Look up per-drive cwd via the `=X:` env var convention; fall back + // to the global cwd if absent. + const envKey = `=${resolvedDevice}`; + const env = (typeof process !== 'undefined') ? process.env : undefined; + path = (env && typeof env[envKey] === 'string') + ? env[envKey] + : (typeof process !== 'undefined' && typeof process.cwd === 'function') + ? process.cwd() + : ''; + if (path === undefined || + (path.slice(0, 2).toLowerCase() !== resolvedDevice.toLowerCase() && + path.charCodeAt(2) === CHAR_BACKWARD_SLASH)) { + path = `${resolvedDevice}\\`; + } + } + const len = path.length; + let rootEnd = 0; + let device = ''; + let isAbsolute = false; + const code = path.charCodeAt(0); + if (len === 1) { + if (isPathSeparatorWin(code)) { + rootEnd = 1; + isAbsolute = true; + } + } + else if (isPathSeparatorWin(code)) { + isAbsolute = true; + if (isPathSeparatorWin(path.charCodeAt(1))) { + // UNC path: `\\server\share\…` + let j = 2; + let last = j; + while (j < len && !isPathSeparatorWin(path.charCodeAt(j))) + j++; + if (j < len && j !== last) { + const firstPart = path.slice(last, j); + last = j; + while (j < len && isPathSeparatorWin(path.charCodeAt(j))) + j++; + if (j < len && j !== last) { + last = j; + while (j < len && !isPathSeparatorWin(path.charCodeAt(j))) + j++; + if (j === len || j !== last) { + device = `\\\\${firstPart}\\${path.slice(last, j)}`; + rootEnd = j; + } + } + } + } + else { + rootEnd = 1; + } + } + else if (isWindowsDeviceRoot(code) && path.charCodeAt(1) === CHAR_COLON) { + device = path.slice(0, 2); + rootEnd = 2; + if (len > 2 && isPathSeparatorWin(path.charCodeAt(2))) { + isAbsolute = true; + rootEnd = 3; + } + } + if (device.length > 0) { + if (resolvedDevice.length > 0) { + if (device.toLowerCase() !== resolvedDevice.toLowerCase()) + continue; + } + else { + resolvedDevice = device; + } + } + if (resolvedAbsolute) { + if (resolvedDevice.length > 0) + break; + } + else { + resolvedTail = `${path.slice(rootEnd)}\\${resolvedTail}`; + resolvedAbsolute = isAbsolute; + if (isAbsolute && resolvedDevice.length > 0) + break; + } + } + resolvedTail = normalizeString(resolvedTail, !resolvedAbsolute, '\\', isPathSeparatorWin); + return resolvedDevice + (resolvedAbsolute ? '\\' : '') + resolvedTail || '.'; +} +function isPosixPathSeparator(code) { + return code === CHAR_FORWARD_SLASH; +} +function normalizeString(path, allowAboveRoot, separator, isPathSeparator) { + let res = ''; + let lastSegmentLength = 0; + let lastSlash = -1; + let dots = 0; + let code = 0; + for (let i = 0; i <= path.length; ++i) { + if (i < path.length) { + code = path.charCodeAt(i); + } + else if (isPathSeparator(code)) { + break; + } + else { + code = CHAR_FORWARD_SLASH; + } + if (isPathSeparator(code)) { + if (lastSlash === i - 1 || dots === 1) { + // NOOP + } + else if (dots === 2) { + if (res.length < 2 || lastSegmentLength !== 2 || + res.charCodeAt(res.length - 1) !== CHAR_DOT || + res.charCodeAt(res.length - 2) !== CHAR_DOT) { + if (res.length > 2) { + const lastSlashIndex = res.indexOf(separator); + if (lastSlashIndex === -1) { + res = ''; + lastSegmentLength = 0; + } + else { + res = res.slice(0, lastSlashIndex); + lastSegmentLength = + res.length - 1 - res.indexOf(separator); + } + lastSlash = i; + dots = 0; + continue; + } + else if (res.length !== 0) { + res = ''; + lastSegmentLength = 0; + lastSlash = i; + dots = 0; + continue; + } + } + if (allowAboveRoot) { + res += res.length > 0 ? `${separator}..` : '..'; + lastSegmentLength = 2; + } + } + else { + if (res.length > 0) { + res += `${separator}${path.slice(lastSlash + 1, i)}`; + } + else { + res = path.slice(lastSlash + 1, i); + } + lastSegmentLength = i - lastSlash - 1; + } + lastSlash = i; + dots = 0; + } + else if (code === CHAR_DOT && dots !== -1) { + ++dots; + } + else { + dots = -1; + } + } + return res; +} +function resolve(...args) { + // On Windows, host paths are `D:\…` style. The POSIX-only resolver + // below treats `D` as a non-`/` character and produces garbage; route + // to the Windows-aware variant. POSIX hosts (Linux/macOS/browser) + // run the original code path unchanged — `_isWin32` is constant-folded + // away on those targets. + if (_isWin32) + return resolveWin32(args); + let resolvedPath = ''; + let resolvedAbsolute = false; + for (let i = args.length - 1; i >= -1 && !resolvedAbsolute; i--) { + const path = i >= 0 ? args[i] : '/'; + (0, util_1.validateString)(path, 'path'); + // Skip empty entries + if (path.length === 0) { + continue; + } + resolvedPath = `${path}/${resolvedPath}`; + resolvedAbsolute = path.charCodeAt(0) === CHAR_FORWARD_SLASH; + } + // At this point the path should be resolved to a full absolute path, but + // handle relative paths to be safe (might happen when process.cwd() fails) + // Normalize the path + resolvedPath = normalizeString(resolvedPath, !resolvedAbsolute, '/', isPosixPathSeparator); + if (resolvedAbsolute) { + return `/${resolvedPath}`; + } + return resolvedPath.length > 0 ? resolvedPath : '.'; +} +exports.resolve = resolve; +function relative(from, to) { + (0, util_1.validateString)(from, 'from'); + (0, util_1.validateString)(to, 'to'); + if (from === to) + return ''; + // Trim leading forward slashes. + from = resolve(from); + to = resolve(to); + if (from === to) + return ''; + const fromStart = 1; + const fromEnd = from.length; + const fromLen = fromEnd - fromStart; + const toStart = 1; + const toLen = to.length - toStart; + // Compare paths to find the longest common path from root + const length = (fromLen < toLen ? fromLen : toLen); + let lastCommonSep = -1; + let i = 0; + for (; i < length; i++) { + const fromCode = from.charCodeAt(fromStart + i); + if (fromCode !== to.charCodeAt(toStart + i)) { + break; + } + else if (fromCode === CHAR_FORWARD_SLASH) { + lastCommonSep = i; + } + } + if (i === length) { + if (toLen > length) { + if (to.charCodeAt(toStart + i) === CHAR_FORWARD_SLASH) { + // We get here if `from` is the exact base path for `to`. + // For example: from='/foo/bar'; to='/foo/bar/baz' + return to.slice(toStart + i + 1); + } + if (i === 0) { + // We get here if `from` is the root + // For example: from='/'; to='/foo' + return to.slice(toStart + i); + } + } + else if (fromLen > length) { + if (from.charCodeAt(fromStart + i) === CHAR_FORWARD_SLASH) { + // We get here if `to` is the exact base path for `from`. + // For example: from='/foo/bar/baz'; to='/foo/bar' + lastCommonSep = i; + } + else if (i === 0) { + // We get here if `to` is the root. + // For example: from='/foo/bar'; to='/' + lastCommonSep = 0; + } + } + } + let out = ''; + // Generate the relative path based on the path difference between `to` + // and `from`. + for (i = fromStart + lastCommonSep + 1; i <= fromEnd; ++i) { + if (i === fromEnd || + from.charCodeAt(i) === CHAR_FORWARD_SLASH) { + out += out.length === 0 ? '..' : '/..'; + } + } + // Lastly, append the rest of the destination (`to`) path that comes after + // the common path parts. + return `${out}${to.slice(toStart + lastCommonSep)}`; +} +exports.relative = relative; +//# sourceMappingURL=path.js.map \ No newline at end of file diff --git a/dg-ui/node_modules/@tailwindcss/oxide-wasm32-wasi/node_modules/@tybys/wasm-util/lib/cjs/wasi/preview1.js b/dg-ui/node_modules/@tailwindcss/oxide-wasm32-wasi/node_modules/@tybys/wasm-util/lib/cjs/wasi/preview1.js new file mode 100644 index 0000000..df535a7 --- /dev/null +++ b/dg-ui/node_modules/@tailwindcss/oxide-wasm32-wasi/node_modules/@tybys/wasm-util/lib/cjs/wasi/preview1.js @@ -0,0 +1,1599 @@ +"use strict"; +Object.defineProperty(exports, "__esModule", { value: true }); +exports.WASI = exports.ensureMemoryFor = void 0; +const webassembly_1 = require("../webassembly"); +const path_1 = require("./path"); +// Linux fcntl flag bits ↔ Windows libuv flag bits. `pathOpen()` builds +// `flagsRes` using Linux constants (O_CREAT=0x40, O_EXCL=0x80, +// O_APPEND=0x400). Windows libuv expects different bits (O_CREAT=0x100, +// O_EXCL=0x400, O_APPEND=0x8). Without translation, +// `fs.openSync(path, 0x241 /* L:WRONLY|CREAT|TRUNC */)` is rejected +// with EINVAL because Linux's 0x40 happens to mean O_TEMPORARY on +// Windows — and O_TEMPORARY without O_CREAT is invalid. +const _isWin32Flags = typeof process !== 'undefined' && process.platform === 'win32'; +function _toWinOpenFlags(f) { + let r = f & 3; // RDONLY/WRONLY/RDWR — same on both + if ((f & 0x40) !== 0) + r |= 0x100; // O_CREAT: Linux 0x40 -> Windows 0x100 + if ((f & 0x80) !== 0) + r |= 0x400; // O_EXCL: Linux 0x80 -> Windows 0x400 + if ((f & 0x200) !== 0) + r |= 0x200; // O_TRUNC: same value on both + if ((f & 0x400) !== 0) + r |= 0x8; // O_APPEND: Linux 0x400 -> Windows 0x8 + return r; +} +const types_1 = require("./types"); +const fd_1 = require("./fd"); +const error_1 = require("./error"); +const util_1 = require("./util"); +const rights_1 = require("./rights"); +const memory_1 = require("../memory"); +const jspi_1 = require("../jspi"); +function copyMemory(targets, src) { + if (targets.length === 0 || src.length === 0) + return 0; + let copied = 0; + let left = src.length - copied; + for (let i = 0; i < targets.length; ++i) { + const target = targets[i]; + if (left < target.length) { + target.set(src.subarray(copied, copied + left), 0); + copied += left; + left = 0; + return copied; + } + target.set(src.subarray(copied, copied + target.length), 0); + copied += target.length; + left -= target.length; + } + return copied; +} +const _memory = new WeakMap(); +const _wasi = new WeakMap(); +const _fs = new WeakMap(); +function ensureMemoryFor(memory, end) { + let buffer = memory.buffer; + if (end > buffer.byteLength) { + memory.grow(0); + buffer = memory.buffer; + } + return buffer; +} +exports.ensureMemoryFor = ensureMemoryFor; +function getMemory(wasi, end = 0) { + const memory = _memory.get(wasi); + ensureMemoryFor(memory, end); + return memory; +} +function getFs(wasi) { + const fs = _fs.get(wasi); + if (!fs) + throw new Error('filesystem is unavailable'); + return fs; +} +function handleError(err) { + if (err instanceof error_1.WasiError) { + if (process.env.NODE_ENV !== 'production') { + console.warn(err); + } + return err.errno; + } + switch (err.code) { + case 'ENOENT': return types_1.WasiErrno.ENOENT; + case 'EBADF': return types_1.WasiErrno.EBADF; + case 'EINVAL': return types_1.WasiErrno.EINVAL; + case 'EPERM': return types_1.WasiErrno.EPERM; + case 'EPROTO': return types_1.WasiErrno.EPROTO; + case 'EEXIST': return types_1.WasiErrno.EEXIST; + case 'ENOTDIR': return types_1.WasiErrno.ENOTDIR; + case 'EMFILE': return types_1.WasiErrno.EMFILE; + case 'EACCES': return types_1.WasiErrno.EACCES; + case 'EISDIR': return types_1.WasiErrno.EISDIR; + case 'ENOTEMPTY': return types_1.WasiErrno.ENOTEMPTY; + case 'ENOSYS': return types_1.WasiErrno.ENOSYS; + } + throw err; +} +function defineName(name, f) { + Object.defineProperty(f, 'name', { value: name }); + return f; +} +function tryCall(f, wasi, args) { + let r; + try { + r = f.apply(wasi, args); + } + catch (err) { + return handleError(err); + } + if ((0, util_1.isPromiseLike)(r)) { + return r.then(_ => _, handleError); + } + return r; +} +function syscallWrap(self, name, f) { + let debug = false; + const NODE_DEBUG_NATIVE = (() => { + try { + return process.env.NODE_DEBUG_NATIVE; + } + catch (_) { + return undefined; + } + })(); + if (typeof NODE_DEBUG_NATIVE === 'string' && NODE_DEBUG_NATIVE.split(',').includes('wasi')) { + debug = true; + } + return debug + ? defineName(name, function () { + const args = Array.prototype.slice.call(arguments); + let debugArgs = [`${name}(${Array.from({ length: arguments.length }).map(() => '%d').join(', ')})`]; + debugArgs = debugArgs.concat(args); + console.debug.apply(console, debugArgs); + return tryCall(f, self, args); + }) + : defineName(name, function () { + return tryCall(f, self, arguments); + }); +} +function resolvePathSync(fs, fileDescriptor, path, flags) { + let resolvedPath = (0, path_1.resolve)(fileDescriptor.realPath, path); + if ((flags & 1) === 1) { + try { + resolvedPath = fs.readlinkSync(resolvedPath); + } + catch (err) { + if (err.code !== 'EINVAL' && err.code !== 'ENOENT') { + throw err; + } + } + } + return resolvedPath; +} +async function resolvePathAsync(fs, fileDescriptor, path, flags) { + let resolvedPath = (0, path_1.resolve)(fileDescriptor.realPath, path); + if ((flags & 1) === 1) { + try { + resolvedPath = await fs.promises.readlink(resolvedPath); + } + catch (err) { + if (err.code !== 'EINVAL' && err.code !== 'ENOENT') { + throw err; + } + } + } + return resolvedPath; +} +// eslint-disable-next-line spaced-comment +const encoder = /*#__PURE__*/ new TextEncoder(); +// eslint-disable-next-line spaced-comment +const decoder = /*#__PURE__*/ new TextDecoder(); +const INT64_MAX = (BigInt(1) << BigInt(63)) - BigInt(1); +function readStdin() { + const value = window.prompt(); + if (value === null) + return new Uint8Array(); + const buffer = new TextEncoder().encode(value + '\n'); + return buffer; +} +function validateFstFlagsOrReturn(flags) { + return (Boolean((flags) & ~(types_1.WasiFstFlag.SET_ATIM | types_1.WasiFstFlag.SET_ATIM_NOW | + types_1.WasiFstFlag.SET_MTIM | types_1.WasiFstFlag.SET_MTIM_NOW)) || + ((flags) & (types_1.WasiFstFlag.SET_ATIM | types_1.WasiFstFlag.SET_ATIM_NOW)) === + (types_1.WasiFstFlag.SET_ATIM | types_1.WasiFstFlag.SET_ATIM_NOW) || + ((flags) & (types_1.WasiFstFlag.SET_MTIM | types_1.WasiFstFlag.SET_MTIM_NOW)) === + (types_1.WasiFstFlag.SET_MTIM | types_1.WasiFstFlag.SET_MTIM_NOW)); +} +class WASI { + constructor(args, env, fds, asyncFs, fs, asyncify) { + this.args_get = syscallWrap(this, 'args_get', function (argv, argv_buf) { + argv = Number(argv); + argv_buf = Number(argv_buf); + if (argv === 0 || argv_buf === 0) { + return types_1.WasiErrno.EINVAL; + } + const wasi = _wasi.get(this); + const args = wasi.args; + const argsSize = encoder.encode(args.join('\0') + '\0').length; + const { HEAPU8, view } = getMemory(this, Math.max(argv + args.length * 4, argv_buf + argsSize)); + for (let i = 0; i < args.length; ++i) { + const arg = args[i]; + view.setInt32(argv, argv_buf, true); + argv += 4; + const data = encoder.encode(arg + '\0'); + HEAPU8.set(data, argv_buf); + argv_buf += data.length; + } + return types_1.WasiErrno.ESUCCESS; + }); + this.args_sizes_get = syscallWrap(this, 'args_sizes_get', function (argc, argv_buf_size) { + argc = Number(argc); + argv_buf_size = Number(argv_buf_size); + if (argc === 0 || argv_buf_size === 0) { + return types_1.WasiErrno.EINVAL; + } + const { view } = getMemory(this, Math.max(argc + 4, argv_buf_size + 4)); + const wasi = _wasi.get(this); + const args = wasi.args; + view.setUint32(argc, args.length, true); + view.setUint32(argv_buf_size, encoder.encode(args.join('\0') + '\0').length, true); + return types_1.WasiErrno.ESUCCESS; + }); + this.environ_get = syscallWrap(this, 'environ_get', function (environ, environ_buf) { + environ = Number(environ); + environ_buf = Number(environ_buf); + if (environ === 0 || environ_buf === 0) { + return types_1.WasiErrno.EINVAL; + } + const wasi = _wasi.get(this); + const env = wasi.env; + const envSize = encoder.encode(env.join('\0') + '\0').length; + const { HEAPU8, view } = getMemory(this, Math.max(environ + env.length * 4, environ_buf + envSize)); + for (let i = 0; i < env.length; ++i) { + const pair = env[i]; + view.setInt32(environ, environ_buf, true); + environ += 4; + const data = encoder.encode(pair + '\0'); + HEAPU8.set(data, environ_buf); + environ_buf += data.length; + } + return types_1.WasiErrno.ESUCCESS; + }); + this.environ_sizes_get = syscallWrap(this, 'environ_sizes_get', function (len, buflen) { + len = Number(len); + buflen = Number(buflen); + if (len === 0 || buflen === 0) { + return types_1.WasiErrno.EINVAL; + } + const { view } = getMemory(this, Math.max(len + 4, buflen + 4)); + const wasi = _wasi.get(this); + view.setUint32(len, wasi.env.length, true); + view.setUint32(buflen, encoder.encode(wasi.env.join('\0') + '\0').length, true); + return types_1.WasiErrno.ESUCCESS; + }); + this.clock_res_get = syscallWrap(this, 'clock_res_get', function (id, resolution) { + resolution = Number(resolution); + if (resolution === 0) { + return types_1.WasiErrno.EINVAL; + } + const { view } = getMemory(this, resolution + 8); + switch (id) { + case types_1.WasiClockid.REALTIME: + view.setBigUint64(resolution, BigInt(1000000), true); + return types_1.WasiErrno.ESUCCESS; + case types_1.WasiClockid.MONOTONIC: + case types_1.WasiClockid.PROCESS_CPUTIME_ID: + case types_1.WasiClockid.THREAD_CPUTIME_ID: + view.setBigUint64(resolution, BigInt(1000), true); + return types_1.WasiErrno.ESUCCESS; + default: return types_1.WasiErrno.EINVAL; + } + }); + this.clock_time_get = syscallWrap(this, 'clock_time_get', function (id, _percision, time) { + time = Number(time); + if (time === 0) { + return types_1.WasiErrno.EINVAL; + } + const { view } = getMemory(this, time + 8); + switch (id) { + case types_1.WasiClockid.REALTIME: + view.setBigUint64(time, BigInt(Date.now()) * BigInt(1000000), true); + return types_1.WasiErrno.ESUCCESS; + case types_1.WasiClockid.MONOTONIC: + case types_1.WasiClockid.PROCESS_CPUTIME_ID: + case types_1.WasiClockid.THREAD_CPUTIME_ID: { + const t = performance.now() / 1000; + const s = Math.trunc(t); + const ms = Math.floor((t - s) * 1000); + const result = BigInt(s) * BigInt(1000000000) + BigInt(ms) * BigInt(1000000); + view.setBigUint64(time, result, true); + return types_1.WasiErrno.ESUCCESS; + } + default: return types_1.WasiErrno.EINVAL; + } + }); + this.fd_advise = syscallWrap(this, 'fd_advise', function (_fd, _offset, _len, _advice) { + return types_1.WasiErrno.ENOSYS; + }); + this.fd_fdstat_get = syscallWrap(this, 'fd_fdstat_get', function (fd, fdstat) { + fdstat = Number(fdstat); + if (fdstat === 0) { + return types_1.WasiErrno.EINVAL; + } + const wasi = _wasi.get(this); + const fileDescriptor = wasi.fds.get(fd, BigInt(0), BigInt(0)); + const { view } = getMemory(this, fdstat + 24); + view.setUint16(fdstat, fileDescriptor.type, true); + view.setUint16(fdstat + 2, 0, true); + view.setBigUint64(fdstat + 8, fileDescriptor.rightsBase, true); + view.setBigUint64(fdstat + 16, fileDescriptor.rightsInheriting, true); + return types_1.WasiErrno.ESUCCESS; + }); + this.fd_fdstat_set_flags = syscallWrap(this, 'fd_fdstat_set_flags', function (_fd, _flags) { + return types_1.WasiErrno.ENOSYS; + }); + this.fd_fdstat_set_rights = syscallWrap(this, 'fd_fdstat_set_rights', function (fd, rightsBase, rightsInheriting) { + const wasi = _wasi.get(this); + const fileDescriptor = wasi.fds.get(fd, BigInt(0), BigInt(0)); + if ((rightsBase | fileDescriptor.rightsBase) > fileDescriptor.rightsBase) { + return types_1.WasiErrno.ENOTCAPABLE; + } + if ((rightsInheriting | fileDescriptor.rightsInheriting) > + fileDescriptor.rightsInheriting) { + return types_1.WasiErrno.ENOTCAPABLE; + } + fileDescriptor.rightsBase = rightsBase; + fileDescriptor.rightsInheriting = rightsInheriting; + return types_1.WasiErrno.ESUCCESS; + }); + this.fd_prestat_get = syscallWrap(this, 'fd_prestat_get', function (fd, prestat) { + prestat = Number(prestat); + if (prestat === 0) { + return types_1.WasiErrno.EINVAL; + } + const wasi = _wasi.get(this); + let fileDescriptor; + try { + fileDescriptor = wasi.fds.get(fd, BigInt(0), BigInt(0)); + } + catch (err) { + if (err instanceof error_1.WasiError) + return err.errno; + throw err; + } + if (fileDescriptor.preopen !== 1) + return types_1.WasiErrno.EINVAL; + const { view } = getMemory(this, prestat + 8); + // preopen type is dir(0) + view.setUint32(prestat, 0, true); + view.setUint32(prestat + 4, encoder.encode(fileDescriptor.path).length, true); + return types_1.WasiErrno.ESUCCESS; + }); + this.fd_prestat_dir_name = syscallWrap(this, 'fd_prestat_dir_name', function (fd, path, path_len) { + path = Number(path); + path_len = Number(path_len); + if (path === 0) { + return types_1.WasiErrno.EINVAL; + } + const wasi = _wasi.get(this); + const fileDescriptor = wasi.fds.get(fd, BigInt(0), BigInt(0)); + if (fileDescriptor.preopen !== 1) + return types_1.WasiErrno.EBADF; + const buffer = encoder.encode(fileDescriptor.path); + const size = buffer.length; + if (size > path_len) + return types_1.WasiErrno.ENOBUFS; + const { HEAPU8 } = getMemory(this, path + size); + HEAPU8.set(buffer, path); + return types_1.WasiErrno.ESUCCESS; + }); + this.fd_seek = syscallWrap(this, 'fd_seek', function (fd, offset, whence, newOffset) { + newOffset = Number(newOffset); + if (newOffset === 0) { + return types_1.WasiErrno.EINVAL; + } + if (fd === 0 || fd === 1 || fd === 2) + return types_1.WasiErrno.ESUCCESS; + const wasi = _wasi.get(this); + const fileDescriptor = wasi.fds.get(fd, types_1.WasiRights.FD_SEEK, BigInt(0)); + const r = fileDescriptor.seek(offset, whence); + const { view } = getMemory(this, newOffset + 8); + view.setBigUint64(newOffset, r, true); + return types_1.WasiErrno.ESUCCESS; + }); + this.fd_tell = syscallWrap(this, 'fd_tell', function (fd, offset) { + const wasi = _wasi.get(this); + const fileDescriptor = wasi.fds.get(fd, types_1.WasiRights.FD_TELL, BigInt(0)); + const pos = BigInt(fileDescriptor.pos); + const { view } = getMemory(this, Number(offset) + 8); + view.setBigUint64(Number(offset), pos, true); + return types_1.WasiErrno.ESUCCESS; + }); + this.poll_oneoff = syscallWrap(this, 'poll_oneoff', function (in_ptr, out_ptr, nsubscriptions, nevents) { + in_ptr = Number(in_ptr); + out_ptr = Number(out_ptr); + nevents = Number(nevents); + nsubscriptions = Number(nsubscriptions); + nsubscriptions = nsubscriptions >>> 0; + if (in_ptr === 0 || out_ptr === 0 || nsubscriptions === 0 || nevents === 0) { + return types_1.WasiErrno.EINVAL; + } + const { view } = getMemory(this, Math.max(in_ptr + nsubscriptions * 48, out_ptr + nsubscriptions * 32, nevents + 4)); + view.setUint32(nevents, 0, true); + let i = 0; + let timer_userdata = BigInt(0); + let cur_timeout = BigInt(0); + let has_timeout = 0; + let min_timeout = BigInt(0); + let sub; + const subscriptions = Array(nsubscriptions); + for (i = 0; i < nsubscriptions; i++) { + sub = in_ptr + i * 48; + const userdata = view.getBigUint64(sub, true); + const type = view.getUint8(sub + 8); + const clockIdOrFd = view.getUint32(sub + 16, true); + const timeout = view.getBigUint64(sub + 24, true); + const precision = view.getBigUint64(sub + 32, true); + const flags = view.getUint16(sub + 40, true); + subscriptions[i] = { + userdata, + type, + u: { + clock: { + clock_id: clockIdOrFd, + timeout, + precision, + flags + }, + fd_readwrite: { + fd: clockIdOrFd + } + } + }; + } + const fdevents = []; + for (i = 0; i < nsubscriptions; i++) { + sub = subscriptions[i]; + switch (sub.type) { + case types_1.WasiEventType.CLOCK: { + if (sub.u.clock.flags === types_1.WasiSubclockflags.ABSTIME) { + /* Convert absolute time to relative delay. */ + const now = BigInt(Date.now()) * BigInt(1000000); + cur_timeout = sub.u.clock.timeout - now; + } + else { + cur_timeout = sub.u.clock.timeout; + } + if (has_timeout === 0 || cur_timeout < min_timeout) { + min_timeout = cur_timeout; + timer_userdata = sub.userdata; + has_timeout = 1; + } + break; + } + case types_1.WasiEventType.FD_READ: + case types_1.WasiEventType.FD_WRITE: + fdevents.push(sub); + break; + default: return types_1.WasiErrno.EINVAL; + } + } + if (fdevents.length > 0) { + for (i = 0; i < fdevents.length; i++) { + const fdevent = fdevents[i]; + const event = out_ptr + 32 * i; + view.setBigUint64(event, fdevent.userdata, true); + view.setUint32(event + 8, types_1.WasiErrno.ENOSYS, true); + view.setUint32(event + 12, fdevent.type, true); + view.setBigUint64(event + 16, BigInt(0), true); + view.setUint16(event + 24, 0, true); + view.setUint32(nevents, 1, true); + } + view.setUint32(nevents, fdevents.length, true); + return types_1.WasiErrno.ESUCCESS; + } + if (has_timeout) { + const delay = Number(min_timeout / BigInt(1000000)); + // if (isMainThread || typeof SharedArrayBuffer !== 'function') { + (0, util_1.sleepBreakIf)(delay, () => false); + // } else { + // const buf = new SharedArrayBuffer(4) + // const arr = new Int32Array(buf) + // postMsg({ + // __tybys_wasm_util_wasi__: { + // type: 'set-timeout', + // payload: { + // buffer: buf, + // delay + // } + // } + // }) + // Atomics.wait(arr, 0, 0) + // } + const event = out_ptr; + view.setBigUint64(event, timer_userdata, true); + view.setUint32(event + 8, types_1.WasiErrno.ESUCCESS, true); + view.setUint32(event + 12, types_1.WasiEventType.CLOCK, true); + view.setUint32(nevents, 1, true); + } + return types_1.WasiErrno.ESUCCESS; + }); + this.proc_exit = syscallWrap(this, 'proc_exit', function (rval) { + if ((typeof process === 'object') && (process !== null) && (typeof process.exit === 'function')) { + process.exit(rval); + } + return types_1.WasiErrno.ESUCCESS; + }); + this.proc_raise = syscallWrap(this, 'proc_raise', function (_sig) { + return types_1.WasiErrno.ENOSYS; + }); + this.sched_yield = syscallWrap(this, 'sched_yield', function () { + return types_1.WasiErrno.ESUCCESS; + }); + this.random_get = typeof crypto !== 'undefined' && typeof crypto.getRandomValues === 'function' + ? syscallWrap(this, 'random_get', function (buf, buf_len) { + buf = Number(buf); + if (buf === 0) { + return types_1.WasiErrno.EINVAL; + } + buf_len = Number(buf_len); + const { HEAPU8, view } = getMemory(this, buf + buf_len); + if ((typeof SharedArrayBuffer === 'function' && HEAPU8.buffer instanceof SharedArrayBuffer) || + (Object.prototype.toString.call(HEAPU8.buffer) === '[object SharedArrayBuffer]')) { + for (let i = buf; i < buf + buf_len; ++i) { + view.setUint8(i, Math.floor(Math.random() * 256)); + } + return types_1.WasiErrno.ESUCCESS; + } + let pos; + const stride = 65536; + for (pos = 0; pos + stride < buf_len; pos += stride) { + crypto.getRandomValues(HEAPU8.subarray(buf + pos, buf + pos + stride)); + } + crypto.getRandomValues(HEAPU8.subarray(buf + pos, buf + buf_len)); + return types_1.WasiErrno.ESUCCESS; + }) + : syscallWrap(this, 'random_get', function (buf, buf_len) { + buf = Number(buf); + if (buf === 0) { + return types_1.WasiErrno.EINVAL; + } + buf_len = Number(buf_len); + const { view } = getMemory(this, buf + buf_len); + for (let i = buf; i < buf + buf_len; ++i) { + view.setUint8(i, Math.floor(Math.random() * 256)); + } + return types_1.WasiErrno.ESUCCESS; + }); + this.sock_recv = syscallWrap(this, 'sock_recv', function () { + return types_1.WasiErrno.ENOTSUP; + }); + this.sock_send = syscallWrap(this, 'sock_send', function () { + return types_1.WasiErrno.ENOTSUP; + }); + this.sock_shutdown = syscallWrap(this, 'sock_shutdown', function () { + return types_1.WasiErrno.ENOTSUP; + }); + this.sock_accept = syscallWrap(this, 'sock_accept', function () { + return types_1.WasiErrno.ENOTSUP; + }); + _wasi.set(this, { + fds, + args, + env + }); + if (fs) + _fs.set(this, fs); + // eslint-disable-next-line @typescript-eslint/no-this-alias + const _this = this; + function defineImport(name, syncVersion, asyncVersion, parameterType, returnType) { + if (asyncFs) { + if (asyncify) { + _this[name] = asyncify.wrapImportFunction(syscallWrap(_this, name, asyncVersion)); + } + else { + _this[name] = (0, jspi_1.wrapAsyncImport)(syscallWrap(_this, name, asyncVersion), parameterType, returnType); + } + } + else { + _this[name] = syscallWrap(_this, name, syncVersion); + } + } + defineImport('fd_allocate', function fd_allocate(fd, offset, len) { + const wasi = _wasi.get(this); + const fs = getFs(this); + const fileDescriptor = wasi.fds.get(fd, types_1.WasiRights.FD_ALLOCATE, BigInt(0)); + const stat = fs.fstatSync(fileDescriptor.fd, { bigint: true }); + if (stat.size < offset + len) { + fs.ftruncateSync(fileDescriptor.fd, Number(offset + len)); + } + return types_1.WasiErrno.ESUCCESS; + }, async function fd_allocate(fd, offset, len) { + const wasi = _wasi.get(this); + const fileDescriptor = wasi.fds.get(fd, types_1.WasiRights.FD_ALLOCATE, BigInt(0)); + const h = fileDescriptor.fd; + const stat = await h.stat({ bigint: true }); + if (stat.size < offset + len) { + await h.truncate(Number(offset + len)); + } + return types_1.WasiErrno.ESUCCESS; + }, ['i32', 'i64', 'f64'], ['i32']); + defineImport('fd_close', function fd_close(fd) { + const wasi = _wasi.get(this); + const fileDescriptor = wasi.fds.get(fd, BigInt(0), BigInt(0)); + const fs = getFs(this); + fs.closeSync(fileDescriptor.fd); + wasi.fds.remove(fd); + return types_1.WasiErrno.ESUCCESS; + }, async function fd_close(fd) { + const wasi = _wasi.get(this); + const fileDescriptor = wasi.fds.get(fd, BigInt(0), BigInt(0)); + await fileDescriptor.fd.close(); + wasi.fds.remove(fd); + return types_1.WasiErrno.ESUCCESS; + }, ['i32'], ['i32']); + defineImport('fd_datasync', function fd_datasync(fd) { + const wasi = _wasi.get(this); + const fileDescriptor = wasi.fds.get(fd, types_1.WasiRights.FD_DATASYNC, BigInt(0)); + const fs = getFs(this); + fs.fdatasyncSync(fileDescriptor.fd); + return types_1.WasiErrno.ESUCCESS; + }, async function fd_datasync(fd) { + const wasi = _wasi.get(this); + const fileDescriptor = wasi.fds.get(fd, types_1.WasiRights.FD_DATASYNC, BigInt(0)); + await fileDescriptor.fd.datasync(); + return types_1.WasiErrno.ESUCCESS; + }, ['i32'], ['i32']); + defineImport('fd_filestat_get', function fd_filestat_get(fd, buf) { + buf = Number(buf); + if (buf === 0) + return types_1.WasiErrno.EINVAL; + const wasi = _wasi.get(this); + const fileDescriptor = wasi.fds.get(fd, types_1.WasiRights.FD_FILESTAT_GET, BigInt(0)); + const fs = getFs(this); + const stat = fs.fstatSync(fileDescriptor.fd, { bigint: true }); + const { view } = getMemory(this, buf + 64); + (0, fd_1.toFileStat)(view, buf, stat); + return types_1.WasiErrno.ESUCCESS; + }, async function fd_filestat_get(fd, buf) { + buf = Number(buf); + if (buf === 0) + return types_1.WasiErrno.EINVAL; + const wasi = _wasi.get(this); + const fileDescriptor = wasi.fds.get(fd, types_1.WasiRights.FD_FILESTAT_GET, BigInt(0)); + const h = fileDescriptor.fd; + const stat = await h.stat({ bigint: true }); + const { view } = getMemory(this, buf + 64); + (0, fd_1.toFileStat)(view, buf, stat); + return types_1.WasiErrno.ESUCCESS; + }, ['i32', 'i32'], ['i32']); + defineImport('fd_filestat_set_size', function fd_filestat_set_size(fd, size) { + const wasi = _wasi.get(this); + const fileDescriptor = wasi.fds.get(fd, types_1.WasiRights.FD_FILESTAT_SET_SIZE, BigInt(0)); + const fs = getFs(this); + fs.ftruncateSync(fileDescriptor.fd, Number(size)); + return types_1.WasiErrno.ESUCCESS; + }, async function fd_filestat_set_size(fd, size) { + const wasi = _wasi.get(this); + const fileDescriptor = wasi.fds.get(fd, types_1.WasiRights.FD_FILESTAT_SET_SIZE, BigInt(0)); + const h = fileDescriptor.fd; + await h.truncate(Number(size)); + return types_1.WasiErrno.ESUCCESS; + }, ['i32', 'i64'], ['i32']); + function fdFilestatGetTimes(fd, atim, mtim, flags) { + const wasi = _wasi.get(this); + const fileDescriptor = wasi.fds.get(fd, types_1.WasiRights.FD_FILESTAT_SET_TIMES, BigInt(0)); + if ((flags & types_1.WasiFstFlag.SET_ATIM_NOW) === types_1.WasiFstFlag.SET_ATIM_NOW) { + atim = BigInt(Date.now() * 1000000); + } + if ((flags & types_1.WasiFstFlag.SET_MTIM_NOW) === types_1.WasiFstFlag.SET_MTIM_NOW) { + mtim = BigInt(Date.now() * 1000000); + } + return { fileDescriptor, atim, mtim }; + } + defineImport('fd_filestat_set_times', function fd_filestat_set_times(fd, atim, mtim, flags) { + if (validateFstFlagsOrReturn(flags)) { + return types_1.WasiErrno.EINVAL; + } + const { fileDescriptor, atim: atimRes, mtim: mtimRes } = fdFilestatGetTimes.call(this, fd, atim, mtim, flags); + const fs = getFs(this); + fs.futimesSync(fileDescriptor.fd, Number(atimRes), Number(mtimRes)); + return types_1.WasiErrno.ESUCCESS; + }, async function fd_filestat_set_times(fd, atim, mtim, flags) { + if (validateFstFlagsOrReturn(flags)) { + return types_1.WasiErrno.EINVAL; + } + const { fileDescriptor, atim: atimRes, mtim: mtimRes } = fdFilestatGetTimes.call(this, fd, atim, mtim, flags); + const h = fileDescriptor.fd; + await h.utimes(Number(atimRes), Number(mtimRes)); + return types_1.WasiErrno.ESUCCESS; + }, ['i32', 'i64', 'i64', 'i32'], ['i32']); + defineImport('fd_pread', function fd_pread(fd, iovs, iovslen, offset, size) { + iovs = Number(iovs); + size = Number(size); + if ((iovs === 0 && iovslen) || size === 0 || offset > INT64_MAX) { + return types_1.WasiErrno.EINVAL; + } + const { HEAPU8, view } = getMemory(this, Math.max(iovs + Number(iovslen) * 8, size + 4)); + const wasi = _wasi.get(this); + const fileDescriptor = wasi.fds.get(fd, types_1.WasiRights.FD_READ | types_1.WasiRights.FD_SEEK, BigInt(0)); + if (!iovslen) { + view.setUint32(size, 0, true); + return types_1.WasiErrno.ESUCCESS; + } + let totalSize = 0; + const ioVecs = Array.from({ length: Number(iovslen) }, (_, i) => { + const offset = iovs + (i * 8); + const buf = view.getInt32(offset, true); + const bufLen = view.getUint32(offset + 4, true); + totalSize += bufLen; + return HEAPU8.subarray(buf, buf + bufLen); + }); + let nread = 0; + const buffer = (() => { + try { + return new Uint8Array(new SharedArrayBuffer(totalSize)); + } + catch (_) { + return new Uint8Array(totalSize); + } + })(); + buffer._isBuffer = true; + const fs = getFs(this); + const bytesRead = fs.readSync(fileDescriptor.fd, buffer, 0, buffer.length, Number(offset)); + nread = buffer ? copyMemory(ioVecs, buffer.subarray(0, bytesRead)) : 0; + view.setUint32(size, nread, true); + return types_1.WasiErrno.ESUCCESS; + }, async function (fd, iovs, iovslen, offset, size) { + iovs = Number(iovs); + size = Number(size); + if ((iovs === 0 && iovslen) || size === 0 || offset > INT64_MAX) { + return types_1.WasiErrno.EINVAL; + } + const { HEAPU8, view } = getMemory(this, Math.max(iovs + Number(iovslen) * 8, size + 4)); + const wasi = _wasi.get(this); + const fileDescriptor = wasi.fds.get(fd, types_1.WasiRights.FD_READ | types_1.WasiRights.FD_SEEK, BigInt(0)); + if (!iovslen) { + view.setUint32(size, 0, true); + return types_1.WasiErrno.ESUCCESS; + } + let totalSize = 0; + const ioVecs = Array.from({ length: Number(iovslen) }, (_, i) => { + const offset = iovs + (i * 8); + const buf = view.getInt32(offset, true); + const bufLen = view.getUint32(offset + 4, true); + totalSize += bufLen; + return HEAPU8.subarray(buf, buf + bufLen); + }); + let nread = 0; + const buffer = new Uint8Array(totalSize); + buffer._isBuffer = true; + const { bytesRead } = await fileDescriptor.fd.read(buffer, 0, buffer.length, Number(offset)); + nread = buffer ? copyMemory(ioVecs, buffer.subarray(0, bytesRead)) : 0; + view.setUint32(size, nread, true); + return types_1.WasiErrno.ESUCCESS; + }, ['i32', 'i32', 'i32', 'i64', 'i32'], ['i32']); + defineImport('fd_pwrite', function fd_pwrite(fd, iovs, iovslen, offset, size) { + iovs = Number(iovs); + size = Number(size); + if ((iovs === 0 && iovslen) || size === 0 || offset > INT64_MAX) { + return types_1.WasiErrno.EINVAL; + } + const { HEAPU8, view } = getMemory(this, Math.max(iovs + Number(iovslen) * 8, size + 4)); + const wasi = _wasi.get(this); + const fileDescriptor = wasi.fds.get(fd, types_1.WasiRights.FD_WRITE | types_1.WasiRights.FD_SEEK, BigInt(0)); + if (!iovslen) { + view.setUint32(size, 0, true); + return types_1.WasiErrno.ESUCCESS; + } + const buffer = (0, fd_1.concatBuffer)(Array.from({ length: Number(iovslen) }, (_, i) => { + const offset = iovs + (i * 8); + const buf = view.getInt32(offset, true); + const bufLen = view.getUint32(offset + 4, true); + return HEAPU8.subarray(buf, buf + bufLen); + })); + const fs = getFs(this); + const nwritten = fs.writeSync(fileDescriptor.fd, buffer, 0, buffer.length, Number(offset)); + view.setUint32(size, nwritten, true); + return types_1.WasiErrno.ESUCCESS; + }, async function fd_pwrite(fd, iovs, iovslen, offset, size) { + iovs = Number(iovs); + size = Number(size); + if ((iovs === 0 && iovslen) || size === 0 || offset > INT64_MAX) { + return types_1.WasiErrno.EINVAL; + } + const { HEAPU8, view } = getMemory(this, Math.max(iovs + Number(iovslen) * 8, size + 4)); + const wasi = _wasi.get(this); + const fileDescriptor = wasi.fds.get(fd, types_1.WasiRights.FD_WRITE | types_1.WasiRights.FD_SEEK, BigInt(0)); + if (!iovslen) { + view.setUint32(size, 0, true); + return types_1.WasiErrno.ESUCCESS; + } + const buffer = (0, fd_1.concatBuffer)(Array.from({ length: Number(iovslen) }, (_, i) => { + const offset = iovs + (i * 8); + const buf = view.getInt32(offset, true); + const bufLen = view.getUint32(offset + 4, true); + return HEAPU8.subarray(buf, buf + bufLen); + })); + const { bytesWritten } = await fileDescriptor.fd.write(buffer, 0, buffer.length, Number(offset)); + view.setUint32(size, bytesWritten, true); + return types_1.WasiErrno.ESUCCESS; + }, ['i32', 'i32', 'i32', 'i64', 'i32'], ['i32']); + defineImport('fd_read', function fd_read(fd, iovs, iovslen, size) { + iovs = Number(iovs); + size = Number(size); + if ((iovs === 0 && iovslen) || size === 0) { + return types_1.WasiErrno.EINVAL; + } + const { HEAPU8, view } = getMemory(this, Math.max(iovs + Number(iovslen) * 8, size + 4)); + const wasi = _wasi.get(this); + const fileDescriptor = wasi.fds.get(fd, types_1.WasiRights.FD_READ, BigInt(0)); + if (!iovslen) { + view.setUint32(size, 0, true); + return types_1.WasiErrno.ESUCCESS; + } + let totalSize = 0; + const ioVecs = Array.from({ length: Number(iovslen) }, (_, i) => { + const offset = iovs + (i * 8); + const buf = view.getInt32(offset, true); + const bufLen = view.getUint32(offset + 4, true); + totalSize += bufLen; + return HEAPU8.subarray(buf, buf + bufLen); + }); + let buffer; + let nread = 0; + if (fd === 0) { + if (typeof window === 'undefined' || typeof window.prompt !== 'function') { + return types_1.WasiErrno.ENOTSUP; + } + buffer = readStdin(); + nread = buffer ? copyMemory(ioVecs, buffer) : 0; + } + else { + buffer = (() => { + try { + return new Uint8Array(new SharedArrayBuffer(totalSize)); + } + catch (_) { + return new Uint8Array(totalSize); + } + })(); + buffer._isBuffer = true; + const fs = getFs(this); + const bytesRead = fs.readSync(fileDescriptor.fd, buffer, 0, buffer.length, Number(fileDescriptor.pos)); + nread = buffer ? copyMemory(ioVecs, buffer.subarray(0, bytesRead)) : 0; + fileDescriptor.pos += BigInt(nread); + } + view.setUint32(size, nread, true); + return types_1.WasiErrno.ESUCCESS; + }, async function fd_read(fd, iovs, iovslen, size) { + iovs = Number(iovs); + size = Number(size); + if ((iovs === 0 && iovslen) || size === 0) { + return types_1.WasiErrno.EINVAL; + } + const { HEAPU8, view } = getMemory(this, Math.max(iovs + Number(iovslen) * 8, size + 4)); + const wasi = _wasi.get(this); + const fileDescriptor = wasi.fds.get(fd, types_1.WasiRights.FD_READ, BigInt(0)); + if (!iovslen) { + view.setUint32(size, 0, true); + return types_1.WasiErrno.ESUCCESS; + } + let totalSize = 0; + const ioVecs = Array.from({ length: Number(iovslen) }, (_, i) => { + const offset = iovs + (i * 8); + const buf = view.getInt32(offset, true); + const bufLen = view.getUint32(offset + 4, true); + totalSize += bufLen; + return HEAPU8.subarray(buf, buf + bufLen); + }); + let buffer; + let nread = 0; + if (fd === 0) { + if (typeof window === 'undefined' || typeof window.prompt !== 'function') { + return types_1.WasiErrno.ENOTSUP; + } + buffer = readStdin(); + nread = buffer ? copyMemory(ioVecs, buffer) : 0; + } + else { + buffer = new Uint8Array(totalSize); + buffer._isBuffer = true; + const { bytesRead } = await fileDescriptor.fd.read(buffer, 0, buffer.length, Number(fileDescriptor.pos)); + nread = buffer ? copyMemory(ioVecs, buffer.subarray(0, bytesRead)) : 0; + fileDescriptor.pos += BigInt(nread); + } + view.setUint32(size, nread, true); + return types_1.WasiErrno.ESUCCESS; + }, ['i32', 'i32', 'i32', 'i32'], ['i32']); + defineImport('fd_readdir', function fd_readdir(fd, buf, buf_len, cookie, bufused) { + buf = Number(buf); + buf_len = Number(buf_len); + bufused = Number(bufused); + if (buf === 0 || bufused === 0) + return types_1.WasiErrno.ESUCCESS; + const wasi = _wasi.get(this); + const fileDescriptor = wasi.fds.get(fd, types_1.WasiRights.FD_READDIR, BigInt(0)); + const fs = getFs(this); + const entries = fs.readdirSync(fileDescriptor.realPath, { withFileTypes: true }); + const { HEAPU8, view } = getMemory(this, Math.max(buf + buf_len, bufused + 4)); + let bufferUsed = 0; + for (let i = Number(cookie); i < entries.length; i++) { + const nameData = encoder.encode(entries[i].name); + const entryInfo = fs.statSync((0, path_1.resolve)(fileDescriptor.realPath, entries[i].name), { bigint: true }); + const entryData = new Uint8Array(24 + nameData.byteLength); + const entryView = new DataView(entryData.buffer); + entryView.setBigUint64(0, BigInt(i + 1), true); + entryView.setBigUint64(8, BigInt(entryInfo.ino ? entryInfo.ino : 0), true); + entryView.setUint32(16, nameData.byteLength, true); + let type; + if (entries[i].isFile()) { + type = types_1.WasiFileType.REGULAR_FILE; + } + else if (entries[i].isDirectory()) { + type = types_1.WasiFileType.DIRECTORY; + } + else if (entries[i].isSymbolicLink()) { + type = types_1.WasiFileType.SYMBOLIC_LINK; + } + else if (entries[i].isCharacterDevice()) { + type = types_1.WasiFileType.CHARACTER_DEVICE; + } + else if (entries[i].isBlockDevice()) { + type = types_1.WasiFileType.BLOCK_DEVICE; + } + else if (entries[i].isSocket()) { + type = types_1.WasiFileType.SOCKET_STREAM; + } + else { + type = types_1.WasiFileType.UNKNOWN; + } + entryView.setUint8(20, type); + entryData.set(nameData, 24); + const data = entryData.slice(0, Math.min(entryData.length, buf_len - bufferUsed)); + HEAPU8.set(data, buf + bufferUsed); + bufferUsed += data.byteLength; + } + view.setUint32(bufused, bufferUsed, true); + return types_1.WasiErrno.ESUCCESS; + }, async function fd_readdir(fd, buf, buf_len, cookie, bufused) { + buf = Number(buf); + buf_len = Number(buf_len); + bufused = Number(bufused); + if (buf === 0 || bufused === 0) + return types_1.WasiErrno.ESUCCESS; + const wasi = _wasi.get(this); + const fileDescriptor = wasi.fds.get(fd, types_1.WasiRights.FD_READDIR, BigInt(0)); + const fs = getFs(this); + const entries = await fs.promises.readdir(fileDescriptor.realPath, { withFileTypes: true }); + const { HEAPU8, view } = getMemory(this, Math.max(buf + buf_len, bufused + 4)); + let bufferUsed = 0; + for (let i = Number(cookie); i < entries.length; i++) { + const nameData = encoder.encode(entries[i].name); + const entryInfo = await fs.promises.stat((0, path_1.resolve)(fileDescriptor.realPath, entries[i].name), { bigint: true }); + const entryData = new Uint8Array(24 + nameData.byteLength); + const entryView = new DataView(entryData.buffer); + entryView.setBigUint64(0, BigInt(i + 1), true); + entryView.setBigUint64(8, BigInt(entryInfo.ino ? entryInfo.ino : 0), true); + entryView.setUint32(16, nameData.byteLength, true); + let type; + if (entries[i].isFile()) { + type = types_1.WasiFileType.REGULAR_FILE; + } + else if (entries[i].isDirectory()) { + type = types_1.WasiFileType.DIRECTORY; + } + else if (entries[i].isSymbolicLink()) { + type = types_1.WasiFileType.SYMBOLIC_LINK; + } + else if (entries[i].isCharacterDevice()) { + type = types_1.WasiFileType.CHARACTER_DEVICE; + } + else if (entries[i].isBlockDevice()) { + type = types_1.WasiFileType.BLOCK_DEVICE; + } + else if (entries[i].isSocket()) { + type = types_1.WasiFileType.SOCKET_STREAM; + } + else { + type = types_1.WasiFileType.UNKNOWN; + } + entryView.setUint8(20, type); + entryData.set(nameData, 24); + const data = entryData.slice(0, Math.min(entryData.length, buf_len - bufferUsed)); + HEAPU8.set(data, buf + bufferUsed); + bufferUsed += data.byteLength; + } + view.setUint32(bufused, bufferUsed, true); + return types_1.WasiErrno.ESUCCESS; + }, ['i32', 'i32', 'i32', 'i64', 'i32'], ['i32']); + defineImport('fd_renumber', function fd_renumber(from, to) { + const wasi = _wasi.get(this); + wasi.fds.renumber(to, from); + return types_1.WasiErrno.ESUCCESS; + }, async function fd_renumber(from, to) { + const wasi = _wasi.get(this); + await wasi.fds.renumber(to, from); + return types_1.WasiErrno.ESUCCESS; + }, ['i32', 'i32'], ['i32']); + defineImport('fd_sync', function fd_sync(fd) { + const wasi = _wasi.get(this); + const fileDescriptor = wasi.fds.get(fd, types_1.WasiRights.FD_SYNC, BigInt(0)); + const fs = getFs(this); + fs.fsyncSync(fileDescriptor.fd); + return types_1.WasiErrno.ESUCCESS; + }, async function fd_sync(fd) { + const wasi = _wasi.get(this); + const fileDescriptor = wasi.fds.get(fd, types_1.WasiRights.FD_SYNC, BigInt(0)); + await fileDescriptor.fd.sync(); + return types_1.WasiErrno.ESUCCESS; + }, ['i32'], ['i32']); + defineImport('fd_write', function fd_write(fd, iovs, iovslen, size) { + iovs = Number(iovs); + size = Number(size); + if ((iovs === 0 && iovslen) || size === 0) { + return types_1.WasiErrno.EINVAL; + } + const { HEAPU8, view } = getMemory(this, Math.max(iovs + Number(iovslen) * 8, size + 4)); + const wasi = _wasi.get(this); + const fileDescriptor = wasi.fds.get(fd, types_1.WasiRights.FD_WRITE, BigInt(0)); + if (!iovslen) { + view.setUint32(size, 0, true); + return types_1.WasiErrno.ESUCCESS; + } + const buffer = (0, fd_1.concatBuffer)(Array.from({ length: Number(iovslen) }, (_, i) => { + const offset = iovs + (i * 8); + const buf = view.getInt32(offset, true); + const bufLen = view.getUint32(offset + 4, true); + return HEAPU8.subarray(buf, buf + bufLen); + })); + let nwritten; + if (fd === 1 || fd === 2) { + nwritten = fileDescriptor.write(buffer); + } + else { + const fs = getFs(this); + nwritten = fs.writeSync(fileDescriptor.fd, buffer, 0, buffer.length, Number(fileDescriptor.pos)); + fileDescriptor.pos += BigInt(nwritten); + } + view.setUint32(size, nwritten, true); + return types_1.WasiErrno.ESUCCESS; + }, async function fd_write(fd, iovs, iovslen, size) { + iovs = Number(iovs); + size = Number(size); + if ((iovs === 0 && iovslen) || size === 0) { + return types_1.WasiErrno.EINVAL; + } + const { HEAPU8, view } = getMemory(this, Math.max(iovs + Number(iovslen) * 8, size + 4)); + const wasi = _wasi.get(this); + const fileDescriptor = wasi.fds.get(fd, types_1.WasiRights.FD_WRITE, BigInt(0)); + if (!iovslen) { + view.setUint32(size, 0, true); + return types_1.WasiErrno.ESUCCESS; + } + const buffer = (0, fd_1.concatBuffer)(Array.from({ length: Number(iovslen) }, (_, i) => { + const offset = iovs + (i * 8); + const buf = view.getInt32(offset, true); + const bufLen = view.getUint32(offset + 4, true); + return HEAPU8.subarray(buf, buf + bufLen); + })); + let nwritten; + if (fd === 1 || fd === 2) { + nwritten = fileDescriptor.write(buffer); + } + else { + nwritten = await (await (fileDescriptor.fd.write(buffer, 0, buffer.length, Number(fileDescriptor.pos)))).bytesWritten; + fileDescriptor.pos += BigInt(nwritten); + } + view.setUint32(size, nwritten, true); + return types_1.WasiErrno.ESUCCESS; + }, ['i32', 'i32', 'i32', 'i32'], ['i32']); + defineImport('path_create_directory', function path_create_directory(fd, path, path_len) { + path = Number(path); + path_len = Number(path_len); + if (path === 0) { + return types_1.WasiErrno.EINVAL; + } + const { HEAPU8 } = getMemory(this, path + path_len); + const wasi = _wasi.get(this); + const fileDescriptor = wasi.fds.get(fd, types_1.WasiRights.PATH_CREATE_DIRECTORY, BigInt(0)); + let pathString = decoder.decode((0, util_1.unsharedSlice)(HEAPU8, path, path + path_len)); + pathString = (0, path_1.resolve)(fileDescriptor.realPath, pathString); + const fs = getFs(this); + fs.mkdirSync(pathString); + return types_1.WasiErrno.ESUCCESS; + }, async function path_create_directory(fd, path, path_len) { + path = Number(path); + path_len = Number(path_len); + if (path === 0) { + return types_1.WasiErrno.EINVAL; + } + const { HEAPU8 } = getMemory(this, path + path_len); + const wasi = _wasi.get(this); + const fileDescriptor = wasi.fds.get(fd, types_1.WasiRights.PATH_CREATE_DIRECTORY, BigInt(0)); + let pathString = decoder.decode((0, util_1.unsharedSlice)(HEAPU8, path, path + path_len)); + pathString = (0, path_1.resolve)(fileDescriptor.realPath, pathString); + const fs = getFs(this); + await fs.promises.mkdir(pathString); + return types_1.WasiErrno.ESUCCESS; + }, ['i32', 'i32', 'i32'], ['i32']); + defineImport('path_filestat_get', function path_filestat_get(fd, flags, path, path_len, filestat) { + path = Number(path); + path_len = Number(path_len); + filestat = Number(filestat); + if (path === 0 || filestat === 0) { + return types_1.WasiErrno.EINVAL; + } + const { HEAPU8, view } = getMemory(this, Math.max(path + path_len, filestat + 64)); + const wasi = _wasi.get(this); + const fileDescriptor = wasi.fds.get(fd, types_1.WasiRights.PATH_FILESTAT_GET, BigInt(0)); + let pathString = decoder.decode((0, util_1.unsharedSlice)(HEAPU8, path, path + path_len)); + const fs = getFs(this); + pathString = (0, path_1.resolve)(fileDescriptor.realPath, pathString); + let stat; + if ((flags & 1) === 1) { + stat = fs.statSync(pathString, { bigint: true }); + } + else { + stat = fs.lstatSync(pathString, { bigint: true }); + } + (0, fd_1.toFileStat)(view, filestat, stat); + return types_1.WasiErrno.ESUCCESS; + }, async function path_filestat_get(fd, flags, path, path_len, filestat) { + path = Number(path); + path_len = Number(path_len); + filestat = Number(filestat); + if (path === 0 || filestat === 0) { + return types_1.WasiErrno.EINVAL; + } + const { HEAPU8, view } = getMemory(this, Math.max(path + path_len, filestat + 64)); + const wasi = _wasi.get(this); + const fileDescriptor = wasi.fds.get(fd, types_1.WasiRights.PATH_FILESTAT_GET, BigInt(0)); + let pathString = decoder.decode((0, util_1.unsharedSlice)(HEAPU8, path, path + path_len)); + const fs = getFs(this); + pathString = (0, path_1.resolve)(fileDescriptor.realPath, pathString); + let stat; + if ((flags & 1) === 1) { + stat = await fs.promises.stat(pathString, { bigint: true }); + } + else { + stat = await fs.promises.lstat(pathString, { bigint: true }); + } + (0, fd_1.toFileStat)(view, filestat, stat); + return types_1.WasiErrno.ESUCCESS; + }, ['i32', 'i32', 'i32', 'i32', 'i32'], ['i32']); + defineImport('path_filestat_set_times', function path_filestat_set_times(fd, flags, path, path_len, atim, mtim, fst_flags) { + path = Number(path); + path_len = Number(path_len); + if (path === 0) + return types_1.WasiErrno.EINVAL; + const { HEAPU8 } = getMemory(this, path + path_len); + const wasi = _wasi.get(this); + const fileDescriptor = wasi.fds.get(fd, types_1.WasiRights.PATH_FILESTAT_SET_TIMES, BigInt(0)); + if (validateFstFlagsOrReturn(fst_flags)) { + return types_1.WasiErrno.EINVAL; + } + const fs = getFs(this); + const resolvedPath = resolvePathSync(fs, fileDescriptor, decoder.decode((0, util_1.unsharedSlice)(HEAPU8, path, path + path_len)), flags); + if ((fst_flags & types_1.WasiFstFlag.SET_ATIM_NOW) === types_1.WasiFstFlag.SET_ATIM_NOW) { + atim = BigInt(Date.now() * 1000000); + } + if ((fst_flags & types_1.WasiFstFlag.SET_MTIM_NOW) === types_1.WasiFstFlag.SET_MTIM_NOW) { + mtim = BigInt(Date.now() * 1000000); + } + fs.utimesSync(resolvedPath, Number(atim), Number(mtim)); + return types_1.WasiErrno.ESUCCESS; + }, async function path_filestat_set_times(fd, flags, path, path_len, atim, mtim, fst_flags) { + path = Number(path); + path_len = Number(path_len); + if (path === 0) + return types_1.WasiErrno.EINVAL; + const { HEAPU8 } = getMemory(this, path + path_len); + const wasi = _wasi.get(this); + const fileDescriptor = wasi.fds.get(fd, types_1.WasiRights.PATH_FILESTAT_SET_TIMES, BigInt(0)); + if (validateFstFlagsOrReturn(fst_flags)) { + return types_1.WasiErrno.EINVAL; + } + const fs = getFs(this); + const resolvedPath = await resolvePathAsync(fs, fileDescriptor, decoder.decode((0, util_1.unsharedSlice)(HEAPU8, path, path + path_len)), flags); + if ((fst_flags & types_1.WasiFstFlag.SET_ATIM_NOW) === types_1.WasiFstFlag.SET_ATIM_NOW) { + atim = BigInt(Date.now() * 1000000); + } + if ((fst_flags & types_1.WasiFstFlag.SET_MTIM_NOW) === types_1.WasiFstFlag.SET_MTIM_NOW) { + mtim = BigInt(Date.now() * 1000000); + } + await fs.promises.utimes(resolvedPath, Number(atim), Number(mtim)); + return types_1.WasiErrno.ESUCCESS; + }, ['i32', 'i32', 'i32', 'i32', 'i64', 'i64', 'i32'], ['i32']); + defineImport('path_link', function path_link(old_fd, old_flags, old_path, old_path_len, new_fd, new_path, new_path_len) { + old_path = Number(old_path); + old_path_len = Number(old_path_len); + new_path = Number(new_path); + new_path_len = Number(new_path_len); + if (old_path === 0 || new_path === 0) { + return types_1.WasiErrno.EINVAL; + } + const wasi = _wasi.get(this); + let oldWrap; + let newWrap; + if (old_fd === new_fd) { + oldWrap = newWrap = wasi.fds.get(old_fd, types_1.WasiRights.PATH_LINK_SOURCE | types_1.WasiRights.PATH_LINK_TARGET, BigInt(0)); + } + else { + oldWrap = wasi.fds.get(old_fd, types_1.WasiRights.PATH_LINK_SOURCE, BigInt(0)); + newWrap = wasi.fds.get(new_fd, types_1.WasiRights.PATH_LINK_TARGET, BigInt(0)); + } + const { HEAPU8 } = getMemory(this, Math.max(old_path + old_path_len, new_path + new_path_len)); + const fs = getFs(this); + const resolvedOldPath = resolvePathSync(fs, oldWrap, decoder.decode((0, util_1.unsharedSlice)(HEAPU8, old_path, old_path + old_path_len)), old_flags); + const resolvedNewPath = (0, path_1.resolve)(newWrap.realPath, decoder.decode((0, util_1.unsharedSlice)(HEAPU8, new_path, new_path + new_path_len))); + fs.linkSync(resolvedOldPath, resolvedNewPath); + return types_1.WasiErrno.ESUCCESS; + }, async function path_link(old_fd, old_flags, old_path, old_path_len, new_fd, new_path, new_path_len) { + old_path = Number(old_path); + old_path_len = Number(old_path_len); + new_path = Number(new_path); + new_path_len = Number(new_path_len); + if (old_path === 0 || new_path === 0) { + return types_1.WasiErrno.EINVAL; + } + const wasi = _wasi.get(this); + let oldWrap; + let newWrap; + if (old_fd === new_fd) { + oldWrap = newWrap = wasi.fds.get(old_fd, types_1.WasiRights.PATH_LINK_SOURCE | types_1.WasiRights.PATH_LINK_TARGET, BigInt(0)); + } + else { + oldWrap = wasi.fds.get(old_fd, types_1.WasiRights.PATH_LINK_SOURCE, BigInt(0)); + newWrap = wasi.fds.get(new_fd, types_1.WasiRights.PATH_LINK_TARGET, BigInt(0)); + } + const { HEAPU8 } = getMemory(this, Math.max(old_path + old_path_len, new_path + new_path_len)); + const fs = getFs(this); + const resolvedOldPath = await resolvePathAsync(fs, oldWrap, decoder.decode((0, util_1.unsharedSlice)(HEAPU8, old_path, old_path + old_path_len)), old_flags); + const resolvedNewPath = (0, path_1.resolve)(newWrap.realPath, decoder.decode((0, util_1.unsharedSlice)(HEAPU8, new_path, new_path + new_path_len))); + await fs.promises.link(resolvedOldPath, resolvedNewPath); + return types_1.WasiErrno.ESUCCESS; + }, ['i32', 'i32', 'i32', 'i32', 'i32', 'i32', 'i32'], ['i32']); + function pathOpen(o_flags, fs_rights_base, fs_rights_inheriting, fs_flags) { + const read = (fs_rights_base & (types_1.WasiRights.FD_READ | + types_1.WasiRights.FD_READDIR)) !== BigInt(0); + const write = (fs_rights_base & (types_1.WasiRights.FD_DATASYNC | + types_1.WasiRights.FD_WRITE | + types_1.WasiRights.FD_ALLOCATE | + types_1.WasiRights.FD_FILESTAT_SET_SIZE)) !== BigInt(0); + let flags = write ? read ? types_1.FileControlFlag.O_RDWR : types_1.FileControlFlag.O_WRONLY : types_1.FileControlFlag.O_RDONLY; + let needed_base = types_1.WasiRights.PATH_OPEN; + let needed_inheriting = fs_rights_base | fs_rights_inheriting; + if ((o_flags & types_1.WasiFileControlFlag.O_CREAT) !== 0) { + flags |= types_1.FileControlFlag.O_CREAT; + needed_base |= types_1.WasiRights.PATH_CREATE_FILE; + } + if ((o_flags & types_1.WasiFileControlFlag.O_DIRECTORY) !== 0) { + flags |= types_1.FileControlFlag.O_DIRECTORY; + } + if ((o_flags & types_1.WasiFileControlFlag.O_EXCL) !== 0) { + flags |= types_1.FileControlFlag.O_EXCL; + } + if ((o_flags & types_1.WasiFileControlFlag.O_TRUNC) !== 0) { + flags |= types_1.FileControlFlag.O_TRUNC; + needed_base |= types_1.WasiRights.PATH_FILESTAT_SET_SIZE; + } + if ((fs_flags & types_1.WasiFdFlag.APPEND) !== 0) { + flags |= types_1.FileControlFlag.O_APPEND; + } + if ((fs_flags & types_1.WasiFdFlag.DSYNC) !== 0) { + // flags |= FileControlFlag.O_DSYNC; + needed_inheriting |= types_1.WasiRights.FD_DATASYNC; + } + if ((fs_flags & types_1.WasiFdFlag.NONBLOCK) !== 0) { + flags |= types_1.FileControlFlag.O_NONBLOCK; + } + if ((fs_flags & types_1.WasiFdFlag.RSYNC) !== 0) { + flags |= types_1.FileControlFlag.O_SYNC; + needed_inheriting |= types_1.WasiRights.FD_SYNC; + } + if ((fs_flags & types_1.WasiFdFlag.SYNC) !== 0) { + flags |= types_1.FileControlFlag.O_SYNC; + needed_inheriting |= types_1.WasiRights.FD_SYNC; + } + if (write && (flags & (types_1.FileControlFlag.O_APPEND | types_1.FileControlFlag.O_TRUNC)) === 0) { + needed_inheriting |= types_1.WasiRights.FD_SEEK; + } + return { flags, needed_base, needed_inheriting }; + } + defineImport('path_open', function path_open(dirfd, dirflags, path, path_len, o_flags, fs_rights_base, fs_rights_inheriting, fs_flags, fd) { + path = Number(path); + fd = Number(fd); + if (path === 0 || fd === 0) { + return types_1.WasiErrno.EINVAL; + } + path_len = Number(path_len); + fs_rights_base = BigInt(fs_rights_base); + fs_rights_inheriting = BigInt(fs_rights_inheriting); + const { flags: flagsRes, needed_base: neededBase, needed_inheriting: neededInheriting } = pathOpen(o_flags, fs_rights_base, fs_rights_inheriting, fs_flags); + const wasi = _wasi.get(this); + const fileDescriptor = wasi.fds.get(dirfd, neededBase, neededInheriting); + const memory = getMemory(this, Math.max(path + path_len, fd + 4)); + const HEAPU8 = memory.HEAPU8; + const pathString = decoder.decode((0, util_1.unsharedSlice)(HEAPU8, path, path + path_len)); + const fs = getFs(this); + const resolved_path = resolvePathSync(fs, fileDescriptor, pathString, dirflags); + const r = fs.openSync(resolved_path, _isWin32Flags ? _toWinOpenFlags(flagsRes) : flagsRes, 0o666); + const filetype = wasi.fds.getFileTypeByFd(r); + if ((filetype !== types_1.WasiFileType.DIRECTORY) && + ((o_flags & types_1.WasiFileControlFlag.O_DIRECTORY) !== 0 || + (resolved_path.endsWith('/')))) { + return types_1.WasiErrno.ENOTDIR; + } + const { base: max_base, inheriting: max_inheriting } = (0, rights_1.getRights)(wasi.fds.stdio, r, flagsRes, filetype); + const wrap = wasi.fds.insert(r, resolved_path, resolved_path, filetype, fs_rights_base & max_base, fs_rights_inheriting & max_inheriting, 0); + const stat = fs.fstatSync(r, { bigint: true }); + if (stat.isFile()) { + wrap.size = stat.size; + if ((flagsRes & types_1.FileControlFlag.O_APPEND) !== 0) { + wrap.pos = stat.size; + } + } + const view = memory.view; + view.setInt32(fd, wrap.id, true); + return types_1.WasiErrno.ESUCCESS; + }, async function path_open(dirfd, dirflags, path, path_len, o_flags, fs_rights_base, fs_rights_inheriting, fs_flags, fd) { + path = Number(path); + fd = Number(fd); + if (path === 0 || fd === 0) { + return types_1.WasiErrno.EINVAL; + } + path_len = Number(path_len); + fs_rights_base = BigInt(fs_rights_base); + fs_rights_inheriting = BigInt(fs_rights_inheriting); + const { flags: flagsRes, needed_base: neededBase, needed_inheriting: neededInheriting } = pathOpen(o_flags, fs_rights_base, fs_rights_inheriting, fs_flags); + const wasi = _wasi.get(this); + const fileDescriptor = wasi.fds.get(dirfd, neededBase, neededInheriting); + const memory = getMemory(this, Math.max(path + path_len, fd + 4)); + const HEAPU8 = memory.HEAPU8; + const pathString = decoder.decode((0, util_1.unsharedSlice)(HEAPU8, path, path + path_len)); + const fs = getFs(this); + const resolved_path = await resolvePathAsync(fs, fileDescriptor, pathString, dirflags); + const r = await fs.promises.open(resolved_path, _isWin32Flags ? _toWinOpenFlags(flagsRes) : flagsRes, 0o666); + const filetype = await wasi.fds.getFileTypeByFd(r); + if ((o_flags & types_1.WasiFileControlFlag.O_DIRECTORY) !== 0 && filetype !== types_1.WasiFileType.DIRECTORY) { + return types_1.WasiErrno.ENOTDIR; + } + const { base: max_base, inheriting: max_inheriting } = (0, rights_1.getRights)(wasi.fds.stdio, r.fd, flagsRes, filetype); + const wrap = wasi.fds.insert(r, resolved_path, resolved_path, filetype, fs_rights_base & max_base, fs_rights_inheriting & max_inheriting, 0); + const stat = await r.stat({ bigint: true }); + if (stat.isFile()) { + wrap.size = stat.size; + if ((flagsRes & types_1.FileControlFlag.O_APPEND) !== 0) { + wrap.pos = stat.size; + } + } + const view = memory.view; + view.setInt32(fd, wrap.id, true); + return types_1.WasiErrno.ESUCCESS; + }, ['i32', 'i32', 'i32', 'i32', 'i32', 'i64', 'i64', 'i32', 'i32'], ['i32']); + defineImport('path_readlink', function path_readlink(fd, path, path_len, buf, buf_len, bufused) { + path = Number(path); + path_len = Number(path_len); + buf = Number(buf); + buf_len = Number(buf_len); + bufused = Number(bufused); + if (path === 0 || buf === 0 || bufused === 0) { + return types_1.WasiErrno.EINVAL; + } + const { HEAPU8, view } = getMemory(this, Math.max(path + path_len, buf + buf_len, bufused + 4)); + const wasi = _wasi.get(this); + const fileDescriptor = wasi.fds.get(fd, types_1.WasiRights.PATH_READLINK, BigInt(0)); + let pathString = decoder.decode((0, util_1.unsharedSlice)(HEAPU8, path, path + path_len)); + pathString = (0, path_1.resolve)(fileDescriptor.realPath, pathString); + const fs = getFs(this); + const link = fs.readlinkSync(pathString); + const linkData = encoder.encode(link); + const len = Math.min(linkData.length, buf_len); + if (len >= buf_len) + return types_1.WasiErrno.ENOBUFS; + HEAPU8.set(linkData.subarray(0, len), buf); + HEAPU8[buf + len] = 0; + view.setUint32(bufused, len, true); + return types_1.WasiErrno.ESUCCESS; + }, async function path_readlink(fd, path, path_len, buf, buf_len, bufused) { + path = Number(path); + path_len = Number(path_len); + buf = Number(buf); + buf_len = Number(buf_len); + bufused = Number(bufused); + if (path === 0 || buf === 0 || bufused === 0) { + return types_1.WasiErrno.EINVAL; + } + const { HEAPU8, view } = getMemory(this, Math.max(path + path_len, buf + buf_len, bufused + 4)); + const wasi = _wasi.get(this); + const fileDescriptor = wasi.fds.get(fd, types_1.WasiRights.PATH_READLINK, BigInt(0)); + let pathString = decoder.decode((0, util_1.unsharedSlice)(HEAPU8, path, path + path_len)); + pathString = (0, path_1.resolve)(fileDescriptor.realPath, pathString); + const fs = getFs(this); + const link = await fs.promises.readlink(pathString); + const linkData = encoder.encode(link); + const len = Math.min(linkData.length, buf_len); + if (len >= buf_len) + return types_1.WasiErrno.ENOBUFS; + HEAPU8.set(linkData.subarray(0, len), buf); + HEAPU8[buf + len] = 0; + view.setUint32(bufused, len, true); + return types_1.WasiErrno.ESUCCESS; + }, ['i32', 'i32', 'i32', 'i32', 'i32', 'i32'], ['i32']); + defineImport('path_remove_directory', function path_remove_directory(fd, path, path_len) { + path = Number(path); + path_len = Number(path_len); + if (path === 0) { + return types_1.WasiErrno.EINVAL; + } + const { HEAPU8 } = getMemory(this, path + path_len); + const wasi = _wasi.get(this); + const fileDescriptor = wasi.fds.get(fd, types_1.WasiRights.PATH_REMOVE_DIRECTORY, BigInt(0)); + let pathString = decoder.decode((0, util_1.unsharedSlice)(HEAPU8, path, path + path_len)); + pathString = (0, path_1.resolve)(fileDescriptor.realPath, pathString); + const fs = getFs(this); + fs.rmdirSync(pathString); + return types_1.WasiErrno.ESUCCESS; + }, async function path_remove_directory(fd, path, path_len) { + path = Number(path); + path_len = Number(path_len); + if (path === 0) { + return types_1.WasiErrno.EINVAL; + } + const { HEAPU8 } = getMemory(this, path + path_len); + const wasi = _wasi.get(this); + const fileDescriptor = wasi.fds.get(fd, types_1.WasiRights.PATH_REMOVE_DIRECTORY, BigInt(0)); + let pathString = decoder.decode((0, util_1.unsharedSlice)(HEAPU8, path, path + path_len)); + pathString = (0, path_1.resolve)(fileDescriptor.realPath, pathString); + const fs = getFs(this); + await fs.promises.rmdir(pathString); + return types_1.WasiErrno.ESUCCESS; + }, ['i32', 'i32', 'i32'], ['i32']); + defineImport('path_rename', function path_rename(old_fd, old_path, old_path_len, new_fd, new_path, new_path_len) { + old_path = Number(old_path); + old_path_len = Number(old_path_len); + new_path = Number(new_path); + new_path_len = Number(new_path_len); + if (old_path === 0 || new_path === 0) { + return types_1.WasiErrno.EINVAL; + } + const wasi = _wasi.get(this); + let oldWrap; + let newWrap; + if (old_fd === new_fd) { + oldWrap = newWrap = wasi.fds.get(old_fd, types_1.WasiRights.PATH_RENAME_SOURCE | types_1.WasiRights.PATH_RENAME_TARGET, BigInt(0)); + } + else { + oldWrap = wasi.fds.get(old_fd, types_1.WasiRights.PATH_RENAME_SOURCE, BigInt(0)); + newWrap = wasi.fds.get(new_fd, types_1.WasiRights.PATH_RENAME_TARGET, BigInt(0)); + } + const { HEAPU8 } = getMemory(this, Math.max(old_path + old_path_len, new_path + new_path_len)); + const resolvedOldPath = (0, path_1.resolve)(oldWrap.realPath, decoder.decode((0, util_1.unsharedSlice)(HEAPU8, old_path, old_path + old_path_len))); + const resolvedNewPath = (0, path_1.resolve)(newWrap.realPath, decoder.decode((0, util_1.unsharedSlice)(HEAPU8, new_path, new_path + new_path_len))); + const fs = getFs(this); + fs.renameSync(resolvedOldPath, resolvedNewPath); + return types_1.WasiErrno.ESUCCESS; + }, async function path_rename(old_fd, old_path, old_path_len, new_fd, new_path, new_path_len) { + old_path = Number(old_path); + old_path_len = Number(old_path_len); + new_path = Number(new_path); + new_path_len = Number(new_path_len); + if (old_path === 0 || new_path === 0) { + return types_1.WasiErrno.EINVAL; + } + const wasi = _wasi.get(this); + let oldWrap; + let newWrap; + if (old_fd === new_fd) { + oldWrap = newWrap = wasi.fds.get(old_fd, types_1.WasiRights.PATH_RENAME_SOURCE | types_1.WasiRights.PATH_RENAME_TARGET, BigInt(0)); + } + else { + oldWrap = wasi.fds.get(old_fd, types_1.WasiRights.PATH_RENAME_SOURCE, BigInt(0)); + newWrap = wasi.fds.get(new_fd, types_1.WasiRights.PATH_RENAME_TARGET, BigInt(0)); + } + const { HEAPU8 } = getMemory(this, Math.max(old_path + old_path_len, new_path + new_path_len)); + const resolvedOldPath = (0, path_1.resolve)(oldWrap.realPath, decoder.decode((0, util_1.unsharedSlice)(HEAPU8, old_path, old_path + old_path_len))); + const resolvedNewPath = (0, path_1.resolve)(newWrap.realPath, decoder.decode((0, util_1.unsharedSlice)(HEAPU8, new_path, new_path + new_path_len))); + const fs = getFs(this); + await fs.promises.rename(resolvedOldPath, resolvedNewPath); + return types_1.WasiErrno.ESUCCESS; + }, ['i32', 'i32', 'i32', 'i32', 'i32', 'i32'], ['i32']); + defineImport('path_symlink', function path_symlink(old_path, old_path_len, fd, new_path, new_path_len) { + old_path = Number(old_path); + old_path_len = Number(old_path_len); + new_path = Number(new_path); + new_path_len = Number(new_path_len); + if (old_path === 0 || new_path === 0) { + return types_1.WasiErrno.EINVAL; + } + const { HEAPU8 } = getMemory(this, Math.max(old_path + old_path_len, new_path + new_path_len)); + const wasi = _wasi.get(this); + const fileDescriptor = wasi.fds.get(fd, types_1.WasiRights.PATH_SYMLINK, BigInt(0)); + const oldPath = decoder.decode((0, util_1.unsharedSlice)(HEAPU8, old_path, old_path + old_path_len)); + if (oldPath.length > 0 && oldPath[0] === '/') { + return types_1.WasiErrno.EPERM; + } + let newPath = decoder.decode((0, util_1.unsharedSlice)(HEAPU8, new_path, new_path + new_path_len)); + newPath = (0, path_1.resolve)(fileDescriptor.realPath, newPath); + const fs = getFs(this); + fs.symlinkSync(oldPath, newPath); + return types_1.WasiErrno.ESUCCESS; + }, async function path_symlink(old_path, old_path_len, fd, new_path, new_path_len) { + old_path = Number(old_path); + old_path_len = Number(old_path_len); + new_path = Number(new_path); + new_path_len = Number(new_path_len); + if (old_path === 0 || new_path === 0) { + return types_1.WasiErrno.EINVAL; + } + const { HEAPU8 } = getMemory(this, Math.max(old_path + old_path_len, new_path + new_path_len)); + const wasi = _wasi.get(this); + const fileDescriptor = wasi.fds.get(fd, types_1.WasiRights.PATH_SYMLINK, BigInt(0)); + const oldPath = decoder.decode((0, util_1.unsharedSlice)(HEAPU8, old_path, old_path + old_path_len)); + let newPath = decoder.decode((0, util_1.unsharedSlice)(HEAPU8, new_path, new_path + new_path_len)); + newPath = (0, path_1.resolve)(fileDescriptor.realPath, newPath); + const fs = getFs(this); + await fs.promises.symlink(oldPath, newPath); + return types_1.WasiErrno.ESUCCESS; + }, ['i32', 'i32', 'i32', 'i32', 'i32'], ['i32']); + defineImport('path_unlink_file', function path_unlink_file(fd, path, path_len) { + path = Number(path); + path_len = Number(path_len); + if (path === 0) { + return types_1.WasiErrno.EINVAL; + } + const { HEAPU8 } = getMemory(this, path + path_len); + const wasi = _wasi.get(this); + const fileDescriptor = wasi.fds.get(fd, types_1.WasiRights.PATH_UNLINK_FILE, BigInt(0)); + let pathString = decoder.decode((0, util_1.unsharedSlice)(HEAPU8, path, path + path_len)); + pathString = (0, path_1.resolve)(fileDescriptor.realPath, pathString); + const fs = getFs(this); + fs.unlinkSync(pathString); + return types_1.WasiErrno.ESUCCESS; + }, async function path_unlink_file(fd, path, path_len) { + path = Number(path); + path_len = Number(path_len); + if (path === 0) { + return types_1.WasiErrno.EINVAL; + } + const { HEAPU8 } = getMemory(this, path + path_len); + const wasi = _wasi.get(this); + const fileDescriptor = wasi.fds.get(fd, types_1.WasiRights.PATH_UNLINK_FILE, BigInt(0)); + let pathString = decoder.decode((0, util_1.unsharedSlice)(HEAPU8, path, path + path_len)); + pathString = (0, path_1.resolve)(fileDescriptor.realPath, pathString); + const fs = getFs(this); + await fs.promises.unlink(pathString); + return types_1.WasiErrno.ESUCCESS; + }, ['i32', 'i32', 'i32'], ['i32']); + this._setMemory = function setMemory(m) { + if (!(m instanceof webassembly_1._WebAssembly.Memory)) { + throw new TypeError('"instance.exports.memory" property must be a WebAssembly.Memory'); + } + _memory.set(_this, (0, memory_1.extendMemory)(m)); + }; + } + static createSync(args, env, preopens, stdio, fs, print, printErr) { + const fds = new fd_1.SyncTable({ + size: 3, + in: stdio[0], + out: stdio[1], + err: stdio[2], + fs, + print, + printErr + }); + const _this = new WASI(args, env, fds, false, fs); + if (preopens.length > 0) { + for (let i = 0; i < preopens.length; ++i) { + const realPath = fs.realpathSync(preopens[i].realPath, 'utf8'); + const fd = fs.openSync(realPath, 'r', 0o666); + fds.insertPreopen(fd, preopens[i].mappedPath, realPath); + } + } + return _this; + } + static async createAsync(args, env, preopens, stdio, fs, print, printErr, asyncify) { + const fds = new fd_1.AsyncTable({ + size: 3, + in: stdio[0], + out: stdio[1], + err: stdio[2], + print, + printErr + }); + const _this = new WASI(args, env, fds, true, fs, asyncify); + if (preopens.length > 0) { + for (let i = 0; i < preopens.length; ++i) { + const entry = preopens[i]; + const realPath = await fs.promises.realpath(entry.realPath); + const fd = await fs.promises.open(realPath, 'r', 0o666); + await fds.insertPreopen(fd, entry.mappedPath, realPath); + } + } + return _this; + } +} +exports.WASI = WASI; +//# sourceMappingURL=preview1.js.map \ No newline at end of file diff --git a/dg-ui/node_modules/@tailwindcss/oxide-wasm32-wasi/node_modules/@tybys/wasm-util/lib/cjs/wasi/rights.js b/dg-ui/node_modules/@tailwindcss/oxide-wasm32-wasi/node_modules/@tybys/wasm-util/lib/cjs/wasi/rights.js new file mode 100644 index 0000000..9713b4b --- /dev/null +++ b/dg-ui/node_modules/@tailwindcss/oxide-wasm32-wasi/node_modules/@tybys/wasm-util/lib/cjs/wasi/rights.js @@ -0,0 +1,141 @@ +"use strict"; +Object.defineProperty(exports, "__esModule", { value: true }); +exports.getRights = exports.TTY_INHERITING = exports.TTY_BASE = exports.SOCKET_INHERITING = exports.SOCKET_BASE = exports.DIRECTORY_INHERITING = exports.DIRECTORY_BASE = exports.REGULAR_FILE_INHERITING = exports.REGULAR_FILE_BASE = exports.CHARACTER_DEVICE_INHERITING = exports.CHARACTER_DEVICE_BASE = exports.BLOCK_DEVICE_INHERITING = exports.BLOCK_DEVICE_BASE = exports.RIGHTS_ALL = void 0; +/* eslint-disable spaced-comment */ +const error_1 = require("./error"); +const types_1 = require("./types"); +exports.RIGHTS_ALL = types_1.WasiRights.FD_DATASYNC | + types_1.WasiRights.FD_READ | + types_1.WasiRights.FD_SEEK | + types_1.WasiRights.FD_FDSTAT_SET_FLAGS | + types_1.WasiRights.FD_SYNC | + types_1.WasiRights.FD_TELL | + types_1.WasiRights.FD_WRITE | + types_1.WasiRights.FD_ADVISE | + types_1.WasiRights.FD_ALLOCATE | + types_1.WasiRights.PATH_CREATE_DIRECTORY | + types_1.WasiRights.PATH_CREATE_FILE | + types_1.WasiRights.PATH_LINK_SOURCE | + types_1.WasiRights.PATH_LINK_TARGET | + types_1.WasiRights.PATH_OPEN | + types_1.WasiRights.FD_READDIR | + types_1.WasiRights.PATH_READLINK | + types_1.WasiRights.PATH_RENAME_SOURCE | + types_1.WasiRights.PATH_RENAME_TARGET | + types_1.WasiRights.PATH_FILESTAT_GET | + types_1.WasiRights.PATH_FILESTAT_SET_SIZE | + types_1.WasiRights.PATH_FILESTAT_SET_TIMES | + types_1.WasiRights.FD_FILESTAT_GET | + types_1.WasiRights.FD_FILESTAT_SET_TIMES | + types_1.WasiRights.FD_FILESTAT_SET_SIZE | + types_1.WasiRights.PATH_SYMLINK | + types_1.WasiRights.PATH_UNLINK_FILE | + types_1.WasiRights.PATH_REMOVE_DIRECTORY | + types_1.WasiRights.POLL_FD_READWRITE | + types_1.WasiRights.SOCK_SHUTDOWN | + types_1.WasiRights.SOCK_ACCEPT; +exports.BLOCK_DEVICE_BASE = exports.RIGHTS_ALL; +exports.BLOCK_DEVICE_INHERITING = exports.RIGHTS_ALL; +exports.CHARACTER_DEVICE_BASE = exports.RIGHTS_ALL; +exports.CHARACTER_DEVICE_INHERITING = exports.RIGHTS_ALL; +exports.REGULAR_FILE_BASE = types_1.WasiRights.FD_DATASYNC | + types_1.WasiRights.FD_READ | + types_1.WasiRights.FD_SEEK | + types_1.WasiRights.FD_FDSTAT_SET_FLAGS | + types_1.WasiRights.FD_SYNC | + types_1.WasiRights.FD_TELL | + types_1.WasiRights.FD_WRITE | + types_1.WasiRights.FD_ADVISE | + types_1.WasiRights.FD_ALLOCATE | + types_1.WasiRights.FD_FILESTAT_GET | + types_1.WasiRights.FD_FILESTAT_SET_SIZE | + types_1.WasiRights.FD_FILESTAT_SET_TIMES | + types_1.WasiRights.POLL_FD_READWRITE; +exports.REGULAR_FILE_INHERITING = BigInt(0); +exports.DIRECTORY_BASE = types_1.WasiRights.FD_FDSTAT_SET_FLAGS | + types_1.WasiRights.FD_SYNC | + types_1.WasiRights.FD_ADVISE | + types_1.WasiRights.PATH_CREATE_DIRECTORY | + types_1.WasiRights.PATH_CREATE_FILE | + types_1.WasiRights.PATH_LINK_SOURCE | + types_1.WasiRights.PATH_LINK_TARGET | + types_1.WasiRights.PATH_OPEN | + types_1.WasiRights.FD_READDIR | + types_1.WasiRights.PATH_READLINK | + types_1.WasiRights.PATH_RENAME_SOURCE | + types_1.WasiRights.PATH_RENAME_TARGET | + types_1.WasiRights.PATH_FILESTAT_GET | + types_1.WasiRights.PATH_FILESTAT_SET_SIZE | + types_1.WasiRights.PATH_FILESTAT_SET_TIMES | + types_1.WasiRights.FD_FILESTAT_GET | + types_1.WasiRights.FD_FILESTAT_SET_TIMES | + types_1.WasiRights.PATH_SYMLINK | + types_1.WasiRights.PATH_UNLINK_FILE | + types_1.WasiRights.PATH_REMOVE_DIRECTORY | + types_1.WasiRights.POLL_FD_READWRITE; +exports.DIRECTORY_INHERITING = exports.DIRECTORY_BASE | exports.REGULAR_FILE_BASE; +exports.SOCKET_BASE = (types_1.WasiRights.FD_READ | + types_1.WasiRights.FD_FDSTAT_SET_FLAGS | + types_1.WasiRights.FD_WRITE | + types_1.WasiRights.FD_FILESTAT_GET | + types_1.WasiRights.POLL_FD_READWRITE | + types_1.WasiRights.SOCK_SHUTDOWN); +exports.SOCKET_INHERITING = exports.RIGHTS_ALL; +exports.TTY_BASE = types_1.WasiRights.FD_READ | + types_1.WasiRights.FD_FDSTAT_SET_FLAGS | + types_1.WasiRights.FD_WRITE | + types_1.WasiRights.FD_FILESTAT_GET | + types_1.WasiRights.POLL_FD_READWRITE; +exports.TTY_INHERITING = BigInt(0); +function getRights(stdio, fd, flags, type) { + const ret = { + base: BigInt(0), + inheriting: BigInt(0) + }; + if (type === types_1.WasiFileType.UNKNOWN) { + throw new error_1.WasiError('Unknown file type', types_1.WasiErrno.EINVAL); + } + switch (type) { + case types_1.WasiFileType.REGULAR_FILE: + ret.base = exports.REGULAR_FILE_BASE; + ret.inheriting = exports.REGULAR_FILE_INHERITING; + break; + case types_1.WasiFileType.DIRECTORY: + ret.base = exports.DIRECTORY_BASE; + ret.inheriting = exports.DIRECTORY_INHERITING; + break; + case types_1.WasiFileType.SOCKET_STREAM: + case types_1.WasiFileType.SOCKET_DGRAM: + ret.base = exports.SOCKET_BASE; + ret.inheriting = exports.SOCKET_INHERITING; + break; + case types_1.WasiFileType.CHARACTER_DEVICE: + if (stdio.indexOf(fd) !== -1) { + ret.base = exports.TTY_BASE; + ret.inheriting = exports.TTY_INHERITING; + } + else { + ret.base = exports.CHARACTER_DEVICE_BASE; + ret.inheriting = exports.CHARACTER_DEVICE_INHERITING; + } + break; + case types_1.WasiFileType.BLOCK_DEVICE: + ret.base = exports.BLOCK_DEVICE_BASE; + ret.inheriting = exports.BLOCK_DEVICE_INHERITING; + break; + default: + ret.base = BigInt(0); + ret.inheriting = BigInt(0); + } + /* Disable read/write bits depending on access mode. */ + const read_or_write_only = flags & (0 | 1 | 2); + if (read_or_write_only === 0) { + ret.base &= ~types_1.WasiRights.FD_WRITE; + } + else if (read_or_write_only === 1) { + ret.base &= ~types_1.WasiRights.FD_READ; + } + return ret; +} +exports.getRights = getRights; +//# sourceMappingURL=rights.js.map \ No newline at end of file diff --git a/dg-ui/node_modules/@tailwindcss/oxide-wasm32-wasi/node_modules/@tybys/wasm-util/lib/cjs/wasi/types.js b/dg-ui/node_modules/@tailwindcss/oxide-wasm32-wasi/node_modules/@tybys/wasm-util/lib/cjs/wasi/types.js new file mode 100644 index 0000000..442ad11 --- /dev/null +++ b/dg-ui/node_modules/@tailwindcss/oxide-wasm32-wasi/node_modules/@tybys/wasm-util/lib/cjs/wasi/types.js @@ -0,0 +1,220 @@ +"use strict"; +Object.defineProperty(exports, "__esModule", { value: true }); +exports.WasiSubclockflags = exports.WasiEventType = exports.WasiFstFlag = exports.WasiClockid = exports.WasiFdFlag = exports.WasiFileControlFlag = exports.FileControlFlag = exports.WasiWhence = exports.WasiRights = exports.WasiFileType = exports.WasiErrno = void 0; +/* eslint-disable spaced-comment */ +var WasiErrno; +(function (WasiErrno) { + WasiErrno[WasiErrno["ESUCCESS"] = 0] = "ESUCCESS"; + WasiErrno[WasiErrno["E2BIG"] = 1] = "E2BIG"; + WasiErrno[WasiErrno["EACCES"] = 2] = "EACCES"; + WasiErrno[WasiErrno["EADDRINUSE"] = 3] = "EADDRINUSE"; + WasiErrno[WasiErrno["EADDRNOTAVAIL"] = 4] = "EADDRNOTAVAIL"; + WasiErrno[WasiErrno["EAFNOSUPPORT"] = 5] = "EAFNOSUPPORT"; + WasiErrno[WasiErrno["EAGAIN"] = 6] = "EAGAIN"; + WasiErrno[WasiErrno["EALREADY"] = 7] = "EALREADY"; + WasiErrno[WasiErrno["EBADF"] = 8] = "EBADF"; + WasiErrno[WasiErrno["EBADMSG"] = 9] = "EBADMSG"; + WasiErrno[WasiErrno["EBUSY"] = 10] = "EBUSY"; + WasiErrno[WasiErrno["ECANCELED"] = 11] = "ECANCELED"; + WasiErrno[WasiErrno["ECHILD"] = 12] = "ECHILD"; + WasiErrno[WasiErrno["ECONNABORTED"] = 13] = "ECONNABORTED"; + WasiErrno[WasiErrno["ECONNREFUSED"] = 14] = "ECONNREFUSED"; + WasiErrno[WasiErrno["ECONNRESET"] = 15] = "ECONNRESET"; + WasiErrno[WasiErrno["EDEADLK"] = 16] = "EDEADLK"; + WasiErrno[WasiErrno["EDESTADDRREQ"] = 17] = "EDESTADDRREQ"; + WasiErrno[WasiErrno["EDOM"] = 18] = "EDOM"; + WasiErrno[WasiErrno["EDQUOT"] = 19] = "EDQUOT"; + WasiErrno[WasiErrno["EEXIST"] = 20] = "EEXIST"; + WasiErrno[WasiErrno["EFAULT"] = 21] = "EFAULT"; + WasiErrno[WasiErrno["EFBIG"] = 22] = "EFBIG"; + WasiErrno[WasiErrno["EHOSTUNREACH"] = 23] = "EHOSTUNREACH"; + WasiErrno[WasiErrno["EIDRM"] = 24] = "EIDRM"; + WasiErrno[WasiErrno["EILSEQ"] = 25] = "EILSEQ"; + WasiErrno[WasiErrno["EINPROGRESS"] = 26] = "EINPROGRESS"; + WasiErrno[WasiErrno["EINTR"] = 27] = "EINTR"; + WasiErrno[WasiErrno["EINVAL"] = 28] = "EINVAL"; + WasiErrno[WasiErrno["EIO"] = 29] = "EIO"; + WasiErrno[WasiErrno["EISCONN"] = 30] = "EISCONN"; + WasiErrno[WasiErrno["EISDIR"] = 31] = "EISDIR"; + WasiErrno[WasiErrno["ELOOP"] = 32] = "ELOOP"; + WasiErrno[WasiErrno["EMFILE"] = 33] = "EMFILE"; + WasiErrno[WasiErrno["EMLINK"] = 34] = "EMLINK"; + WasiErrno[WasiErrno["EMSGSIZE"] = 35] = "EMSGSIZE"; + WasiErrno[WasiErrno["EMULTIHOP"] = 36] = "EMULTIHOP"; + WasiErrno[WasiErrno["ENAMETOOLONG"] = 37] = "ENAMETOOLONG"; + WasiErrno[WasiErrno["ENETDOWN"] = 38] = "ENETDOWN"; + WasiErrno[WasiErrno["ENETRESET"] = 39] = "ENETRESET"; + WasiErrno[WasiErrno["ENETUNREACH"] = 40] = "ENETUNREACH"; + WasiErrno[WasiErrno["ENFILE"] = 41] = "ENFILE"; + WasiErrno[WasiErrno["ENOBUFS"] = 42] = "ENOBUFS"; + WasiErrno[WasiErrno["ENODEV"] = 43] = "ENODEV"; + WasiErrno[WasiErrno["ENOENT"] = 44] = "ENOENT"; + WasiErrno[WasiErrno["ENOEXEC"] = 45] = "ENOEXEC"; + WasiErrno[WasiErrno["ENOLCK"] = 46] = "ENOLCK"; + WasiErrno[WasiErrno["ENOLINK"] = 47] = "ENOLINK"; + WasiErrno[WasiErrno["ENOMEM"] = 48] = "ENOMEM"; + WasiErrno[WasiErrno["ENOMSG"] = 49] = "ENOMSG"; + WasiErrno[WasiErrno["ENOPROTOOPT"] = 50] = "ENOPROTOOPT"; + WasiErrno[WasiErrno["ENOSPC"] = 51] = "ENOSPC"; + WasiErrno[WasiErrno["ENOSYS"] = 52] = "ENOSYS"; + WasiErrno[WasiErrno["ENOTCONN"] = 53] = "ENOTCONN"; + WasiErrno[WasiErrno["ENOTDIR"] = 54] = "ENOTDIR"; + WasiErrno[WasiErrno["ENOTEMPTY"] = 55] = "ENOTEMPTY"; + WasiErrno[WasiErrno["ENOTRECOVERABLE"] = 56] = "ENOTRECOVERABLE"; + WasiErrno[WasiErrno["ENOTSOCK"] = 57] = "ENOTSOCK"; + WasiErrno[WasiErrno["ENOTSUP"] = 58] = "ENOTSUP"; + WasiErrno[WasiErrno["ENOTTY"] = 59] = "ENOTTY"; + WasiErrno[WasiErrno["ENXIO"] = 60] = "ENXIO"; + WasiErrno[WasiErrno["EOVERFLOW"] = 61] = "EOVERFLOW"; + WasiErrno[WasiErrno["EOWNERDEAD"] = 62] = "EOWNERDEAD"; + WasiErrno[WasiErrno["EPERM"] = 63] = "EPERM"; + WasiErrno[WasiErrno["EPIPE"] = 64] = "EPIPE"; + WasiErrno[WasiErrno["EPROTO"] = 65] = "EPROTO"; + WasiErrno[WasiErrno["EPROTONOSUPPORT"] = 66] = "EPROTONOSUPPORT"; + WasiErrno[WasiErrno["EPROTOTYPE"] = 67] = "EPROTOTYPE"; + WasiErrno[WasiErrno["ERANGE"] = 68] = "ERANGE"; + WasiErrno[WasiErrno["EROFS"] = 69] = "EROFS"; + WasiErrno[WasiErrno["ESPIPE"] = 70] = "ESPIPE"; + WasiErrno[WasiErrno["ESRCH"] = 71] = "ESRCH"; + WasiErrno[WasiErrno["ESTALE"] = 72] = "ESTALE"; + WasiErrno[WasiErrno["ETIMEDOUT"] = 73] = "ETIMEDOUT"; + WasiErrno[WasiErrno["ETXTBSY"] = 74] = "ETXTBSY"; + WasiErrno[WasiErrno["EXDEV"] = 75] = "EXDEV"; + WasiErrno[WasiErrno["ENOTCAPABLE"] = 76] = "ENOTCAPABLE"; +})(WasiErrno = exports.WasiErrno || (exports.WasiErrno = {})); +var WasiFileType; +(function (WasiFileType) { + WasiFileType[WasiFileType["UNKNOWN"] = 0] = "UNKNOWN"; + WasiFileType[WasiFileType["BLOCK_DEVICE"] = 1] = "BLOCK_DEVICE"; + WasiFileType[WasiFileType["CHARACTER_DEVICE"] = 2] = "CHARACTER_DEVICE"; + WasiFileType[WasiFileType["DIRECTORY"] = 3] = "DIRECTORY"; + WasiFileType[WasiFileType["REGULAR_FILE"] = 4] = "REGULAR_FILE"; + WasiFileType[WasiFileType["SOCKET_DGRAM"] = 5] = "SOCKET_DGRAM"; + WasiFileType[WasiFileType["SOCKET_STREAM"] = 6] = "SOCKET_STREAM"; + WasiFileType[WasiFileType["SYMBOLIC_LINK"] = 7] = "SYMBOLIC_LINK"; +})(WasiFileType = exports.WasiFileType || (exports.WasiFileType = {})); +const FD_DATASYNC = ( /*#__PURE__*/BigInt(1) << /*#__PURE__*/ BigInt(0)); +const FD_READ = ( /*#__PURE__*/BigInt(1) << /*#__PURE__*/ BigInt(1)); +const FD_SEEK = ( /*#__PURE__*/BigInt(1) << /*#__PURE__*/ BigInt(2)); +const FD_FDSTAT_SET_FLAGS = ( /*#__PURE__*/BigInt(1) << /*#__PURE__*/ BigInt(3)); +const FD_SYNC = ( /*#__PURE__*/BigInt(1) << /*#__PURE__*/ BigInt(4)); +const FD_TELL = ( /*#__PURE__*/BigInt(1) << /*#__PURE__*/ BigInt(5)); +const FD_WRITE = ( /*#__PURE__*/BigInt(1) << /*#__PURE__*/ BigInt(6)); +const FD_ADVISE = ( /*#__PURE__*/BigInt(1) << /*#__PURE__*/ BigInt(7)); +const FD_ALLOCATE = ( /*#__PURE__*/BigInt(1) << /*#__PURE__*/ BigInt(8)); +const PATH_CREATE_DIRECTORY = ( /*#__PURE__*/BigInt(1) << /*#__PURE__*/ BigInt(9)); +const PATH_CREATE_FILE = ( /*#__PURE__*/BigInt(1) << /*#__PURE__*/ BigInt(10)); +const PATH_LINK_SOURCE = ( /*#__PURE__*/BigInt(1) << /*#__PURE__*/ BigInt(11)); +const PATH_LINK_TARGET = ( /*#__PURE__*/BigInt(1) << /*#__PURE__*/ BigInt(12)); +const PATH_OPEN = ( /*#__PURE__*/BigInt(1) << /*#__PURE__*/ BigInt(13)); +const FD_READDIR = ( /*#__PURE__*/BigInt(1) << /*#__PURE__*/ BigInt(14)); +const PATH_READLINK = ( /*#__PURE__*/BigInt(1) << /*#__PURE__*/ BigInt(15)); +const PATH_RENAME_SOURCE = ( /*#__PURE__*/BigInt(1) << /*#__PURE__*/ BigInt(16)); +const PATH_RENAME_TARGET = ( /*#__PURE__*/BigInt(1) << /*#__PURE__*/ BigInt(17)); +const PATH_FILESTAT_GET = ( /*#__PURE__*/BigInt(1) << /*#__PURE__*/ BigInt(18)); +const PATH_FILESTAT_SET_SIZE = ( /*#__PURE__*/BigInt(1) << /*#__PURE__*/ BigInt(19)); +const PATH_FILESTAT_SET_TIMES = ( /*#__PURE__*/BigInt(1) << /*#__PURE__*/ BigInt(20)); +const FD_FILESTAT_GET = ( /*#__PURE__*/BigInt(1) << /*#__PURE__*/ BigInt(21)); +const FD_FILESTAT_SET_SIZE = ( /*#__PURE__*/BigInt(1) << /*#__PURE__*/ BigInt(22)); +const FD_FILESTAT_SET_TIMES = ( /*#__PURE__*/BigInt(1) << /*#__PURE__*/ BigInt(23)); +const PATH_SYMLINK = ( /*#__PURE__*/BigInt(1) << /*#__PURE__*/ BigInt(24)); +const PATH_REMOVE_DIRECTORY = ( /*#__PURE__*/BigInt(1) << /*#__PURE__*/ BigInt(25)); +const PATH_UNLINK_FILE = ( /*#__PURE__*/BigInt(1) << /*#__PURE__*/ BigInt(26)); +const POLL_FD_READWRITE = ( /*#__PURE__*/BigInt(1) << /*#__PURE__*/ BigInt(27)); +const SOCK_SHUTDOWN = ( /*#__PURE__*/BigInt(1) << /*#__PURE__*/ BigInt(28)); +const SOCK_ACCEPT = ( /*#__PURE__*/BigInt(1) << /*#__PURE__*/ BigInt(29)); +exports.WasiRights = { + FD_DATASYNC, + FD_READ, + FD_SEEK, + FD_FDSTAT_SET_FLAGS, + FD_SYNC, + FD_TELL, + FD_WRITE, + FD_ADVISE, + FD_ALLOCATE, + PATH_CREATE_DIRECTORY, + PATH_CREATE_FILE, + PATH_LINK_SOURCE, + PATH_LINK_TARGET, + PATH_OPEN, + FD_READDIR, + PATH_READLINK, + PATH_RENAME_SOURCE, + PATH_RENAME_TARGET, + PATH_FILESTAT_GET, + PATH_FILESTAT_SET_SIZE, + PATH_FILESTAT_SET_TIMES, + FD_FILESTAT_GET, + FD_FILESTAT_SET_SIZE, + FD_FILESTAT_SET_TIMES, + PATH_SYMLINK, + PATH_REMOVE_DIRECTORY, + PATH_UNLINK_FILE, + POLL_FD_READWRITE, + SOCK_SHUTDOWN, + SOCK_ACCEPT +}; +var WasiWhence; +(function (WasiWhence) { + WasiWhence[WasiWhence["SET"] = 0] = "SET"; + WasiWhence[WasiWhence["CUR"] = 1] = "CUR"; + WasiWhence[WasiWhence["END"] = 2] = "END"; +})(WasiWhence = exports.WasiWhence || (exports.WasiWhence = {})); +var FileControlFlag; +(function (FileControlFlag) { + FileControlFlag[FileControlFlag["O_RDONLY"] = 0] = "O_RDONLY"; + FileControlFlag[FileControlFlag["O_WRONLY"] = 1] = "O_WRONLY"; + FileControlFlag[FileControlFlag["O_RDWR"] = 2] = "O_RDWR"; + FileControlFlag[FileControlFlag["O_CREAT"] = 64] = "O_CREAT"; + FileControlFlag[FileControlFlag["O_EXCL"] = 128] = "O_EXCL"; + FileControlFlag[FileControlFlag["O_NOCTTY"] = 256] = "O_NOCTTY"; + FileControlFlag[FileControlFlag["O_TRUNC"] = 512] = "O_TRUNC"; + FileControlFlag[FileControlFlag["O_APPEND"] = 1024] = "O_APPEND"; + FileControlFlag[FileControlFlag["O_DIRECTORY"] = 65536] = "O_DIRECTORY"; + FileControlFlag[FileControlFlag["O_NOATIME"] = 262144] = "O_NOATIME"; + FileControlFlag[FileControlFlag["O_NOFOLLOW"] = 131072] = "O_NOFOLLOW"; + FileControlFlag[FileControlFlag["O_SYNC"] = 1052672] = "O_SYNC"; + FileControlFlag[FileControlFlag["O_DIRECT"] = 16384] = "O_DIRECT"; + FileControlFlag[FileControlFlag["O_NONBLOCK"] = 2048] = "O_NONBLOCK"; +})(FileControlFlag = exports.FileControlFlag || (exports.FileControlFlag = {})); +var WasiFileControlFlag; +(function (WasiFileControlFlag) { + WasiFileControlFlag[WasiFileControlFlag["O_CREAT"] = 1] = "O_CREAT"; + WasiFileControlFlag[WasiFileControlFlag["O_DIRECTORY"] = 2] = "O_DIRECTORY"; + WasiFileControlFlag[WasiFileControlFlag["O_EXCL"] = 4] = "O_EXCL"; + WasiFileControlFlag[WasiFileControlFlag["O_TRUNC"] = 8] = "O_TRUNC"; +})(WasiFileControlFlag = exports.WasiFileControlFlag || (exports.WasiFileControlFlag = {})); +var WasiFdFlag; +(function (WasiFdFlag) { + WasiFdFlag[WasiFdFlag["APPEND"] = 1] = "APPEND"; + WasiFdFlag[WasiFdFlag["DSYNC"] = 2] = "DSYNC"; + WasiFdFlag[WasiFdFlag["NONBLOCK"] = 4] = "NONBLOCK"; + WasiFdFlag[WasiFdFlag["RSYNC"] = 8] = "RSYNC"; + WasiFdFlag[WasiFdFlag["SYNC"] = 16] = "SYNC"; +})(WasiFdFlag = exports.WasiFdFlag || (exports.WasiFdFlag = {})); +var WasiClockid; +(function (WasiClockid) { + WasiClockid[WasiClockid["REALTIME"] = 0] = "REALTIME"; + WasiClockid[WasiClockid["MONOTONIC"] = 1] = "MONOTONIC"; + WasiClockid[WasiClockid["PROCESS_CPUTIME_ID"] = 2] = "PROCESS_CPUTIME_ID"; + WasiClockid[WasiClockid["THREAD_CPUTIME_ID"] = 3] = "THREAD_CPUTIME_ID"; +})(WasiClockid = exports.WasiClockid || (exports.WasiClockid = {})); +var WasiFstFlag; +(function (WasiFstFlag) { + WasiFstFlag[WasiFstFlag["SET_ATIM"] = 1] = "SET_ATIM"; + WasiFstFlag[WasiFstFlag["SET_ATIM_NOW"] = 2] = "SET_ATIM_NOW"; + WasiFstFlag[WasiFstFlag["SET_MTIM"] = 4] = "SET_MTIM"; + WasiFstFlag[WasiFstFlag["SET_MTIM_NOW"] = 8] = "SET_MTIM_NOW"; +})(WasiFstFlag = exports.WasiFstFlag || (exports.WasiFstFlag = {})); +var WasiEventType; +(function (WasiEventType) { + WasiEventType[WasiEventType["CLOCK"] = 0] = "CLOCK"; + WasiEventType[WasiEventType["FD_READ"] = 1] = "FD_READ"; + WasiEventType[WasiEventType["FD_WRITE"] = 2] = "FD_WRITE"; +})(WasiEventType = exports.WasiEventType || (exports.WasiEventType = {})); +var WasiSubclockflags; +(function (WasiSubclockflags) { + WasiSubclockflags[WasiSubclockflags["ABSTIME"] = 1] = "ABSTIME"; +})(WasiSubclockflags = exports.WasiSubclockflags || (exports.WasiSubclockflags = {})); +//# sourceMappingURL=types.js.map \ No newline at end of file diff --git a/dg-ui/node_modules/@tailwindcss/oxide-wasm32-wasi/node_modules/@tybys/wasm-util/lib/cjs/wasi/util.js b/dg-ui/node_modules/@tailwindcss/oxide-wasm32-wasi/node_modules/@tybys/wasm-util/lib/cjs/wasi/util.js new file mode 100644 index 0000000..4deaec0 --- /dev/null +++ b/dg-ui/node_modules/@tailwindcss/oxide-wasm32-wasi/node_modules/@tybys/wasm-util/lib/cjs/wasi/util.js @@ -0,0 +1,128 @@ +"use strict"; +Object.defineProperty(exports, "__esModule", { value: true }); +exports.unsharedSlice = exports.sleepBreakIf = exports.postMsg = exports.isMainThread = exports.wrapInstanceExports = exports.isPromiseLike = exports.validateInt32 = exports.validateUndefined = exports.validateFunction = exports.validateString = exports.validateBoolean = exports.validateArray = exports.validateObject = void 0; +/* eslint-disable spaced-comment */ +function validateObject(value, name) { + if (value === null || typeof value !== 'object') { + throw new TypeError(`${name} must be an object. Received ${value === null ? 'null' : typeof value}`); + } +} +exports.validateObject = validateObject; +function validateArray(value, name) { + if (!Array.isArray(value)) { + throw new TypeError(`${name} must be an array. Received ${value === null ? 'null' : typeof value}`); + } +} +exports.validateArray = validateArray; +function validateBoolean(value, name) { + if (typeof value !== 'boolean') { + throw new TypeError(`${name} must be a boolean. Received ${value === null ? 'null' : typeof value}`); + } +} +exports.validateBoolean = validateBoolean; +function validateString(value, name) { + if (typeof value !== 'string') { + throw new TypeError(`${name} must be a string. Received ${value === null ? 'null' : typeof value}`); + } +} +exports.validateString = validateString; +function validateFunction(value, name) { + if (typeof value !== 'function') { + throw new TypeError(`${name} must be a function. Received ${value === null ? 'null' : typeof value}`); + } +} +exports.validateFunction = validateFunction; +function validateUndefined(value, name) { + if (value !== undefined) { + throw new TypeError(`${name} must be undefined. Received ${value === null ? 'null' : typeof value}`); + } +} +exports.validateUndefined = validateUndefined; +function validateInt32(value, name, min = -2147483648, max = 2147483647) { + if (typeof value !== 'number') { + throw new TypeError(`${name} must be a number. Received ${value === null ? 'null' : typeof value}`); + } + if (!Number.isInteger(value)) { + throw new RangeError(`${name} must be a integer.`); + } + if (value < min || value > max) { + throw new RangeError(`${name} must be >= ${min} && <= ${max}. Received ${value}`); + } +} +exports.validateInt32 = validateInt32; +function isPromiseLike(obj) { + return !!(obj && (typeof obj === 'object' || typeof obj === 'function') && typeof obj.then === 'function'); +} +exports.isPromiseLike = isPromiseLike; +function wrapInstanceExports(exports, mapFn) { + const newExports = Object.create(null); + Object.keys(exports).forEach(name => { + const exportValue = exports[name]; + Object.defineProperty(newExports, name, { + enumerable: true, + value: mapFn(exportValue, name) + }); + }); + return newExports; +} +exports.wrapInstanceExports = wrapInstanceExports; +const _require = /*#__PURE__*/ (function () { + let nativeRequire; + if (typeof __webpack_public_path__ !== 'undefined') { + nativeRequire = (function () { + return typeof __non_webpack_require__ !== 'undefined' ? __non_webpack_require__ : undefined; + })(); + } + else { + nativeRequire = (function () { + return typeof __webpack_public_path__ !== 'undefined' ? (typeof __non_webpack_require__ !== 'undefined' ? __non_webpack_require__ : undefined) : (typeof require !== 'undefined' ? require : undefined); + })(); + } + return nativeRequire; +})(); +exports.isMainThread = (function () { + let worker_threads; + try { + worker_threads = _require('worker_threads'); + } + catch (_) { } + if (!worker_threads) { + return typeof importScripts === 'undefined'; + } + return worker_threads.isMainThread; +})(); +exports.postMsg = exports.isMainThread + ? () => { } + : /*#__PURE__*/ (function () { + let worker_threads; + try { + worker_threads = _require('worker_threads'); + } + catch (_) { } + if (!worker_threads) { + return postMessage; + } + return function postMessage(data) { + worker_threads.parentPort.postMessage({ data }); + }; + })(); +function sleepBreakIf(delay, breakIf) { + const start = Date.now(); + const end = start + delay; + let ret = false; + while (Date.now() < end) { + if (breakIf()) { + ret = true; + break; + } + } + return ret; +} +exports.sleepBreakIf = sleepBreakIf; +function unsharedSlice(view, start, end) { + return ((typeof SharedArrayBuffer === 'function' && view.buffer instanceof SharedArrayBuffer) || (Object.prototype.toString.call(view.buffer.constructor) === '[object SharedArrayBuffer]')) + ? view.slice(start, end) + : view.subarray(start, end); +} +exports.unsharedSlice = unsharedSlice; +//# sourceMappingURL=util.js.map \ No newline at end of file diff --git a/dg-ui/node_modules/@tailwindcss/oxide-wasm32-wasi/node_modules/@tybys/wasm-util/lib/cjs/webassembly.js b/dg-ui/node_modules/@tailwindcss/oxide-wasm32-wasi/node_modules/@tybys/wasm-util/lib/cjs/webassembly.js new file mode 100644 index 0000000..0ae8cf7 --- /dev/null +++ b/dg-ui/node_modules/@tailwindcss/oxide-wasm32-wasi/node_modules/@tybys/wasm-util/lib/cjs/webassembly.js @@ -0,0 +1,13 @@ +"use strict"; +Object.defineProperty(exports, "__esModule", { value: true }); +exports._WebAssembly = void 0; +const _WebAssembly = typeof WebAssembly !== 'undefined' + ? WebAssembly + : typeof WXWebAssembly !== 'undefined' + ? WXWebAssembly + : undefined; +exports._WebAssembly = _WebAssembly; +if (!_WebAssembly) { + throw new Error('WebAssembly is not supported in this environment'); +} +//# sourceMappingURL=webassembly.js.map \ No newline at end of file diff --git a/dg-ui/node_modules/@tailwindcss/oxide-wasm32-wasi/node_modules/@tybys/wasm-util/lib/mjs/asyncify.mjs b/dg-ui/node_modules/@tailwindcss/oxide-wasm32-wasi/node_modules/@tybys/wasm-util/lib/mjs/asyncify.mjs new file mode 100644 index 0000000..7655561 --- /dev/null +++ b/dg-ui/node_modules/@tailwindcss/oxide-wasm32-wasi/node_modules/@tybys/wasm-util/lib/mjs/asyncify.mjs @@ -0,0 +1,153 @@ +import { _WebAssembly } from "./webassembly.mjs"; +import { isPromiseLike, wrapInstanceExports } from "./wasi/util.mjs"; +const ignoreNames = [ + 'asyncify_get_state', + 'asyncify_start_rewind', + 'asyncify_start_unwind', + 'asyncify_stop_rewind', + 'asyncify_stop_unwind' +]; +// const wrappedExports = new WeakMap() +var AsyncifyState; +(function (AsyncifyState) { + AsyncifyState[AsyncifyState["NONE"] = 0] = "NONE"; + AsyncifyState[AsyncifyState["UNWINDING"] = 1] = "UNWINDING"; + AsyncifyState[AsyncifyState["REWINDING"] = 2] = "REWINDING"; +})(AsyncifyState || (AsyncifyState = {})); +function tryAllocate(instance, wasm64, size, mallocName) { + if (typeof instance.exports[mallocName] !== 'function' || size <= 0) { + return { + wasm64, + dataPtr: 16, + start: wasm64 ? 32 : 24, + end: 1024 + }; + } + const malloc = instance.exports[mallocName]; + const dataPtr = wasm64 ? Number(malloc(BigInt(16) + BigInt(size))) : malloc(8 + size); + if (dataPtr === 0) { + throw new Error('Allocate asyncify data failed'); + } + return wasm64 + ? { wasm64, dataPtr, start: dataPtr + 16, end: dataPtr + 16 + size } + : { wasm64, dataPtr, start: dataPtr + 8, end: dataPtr + 8 + size }; +} +/** @public */ +export class Asyncify { + constructor() { + this.value = undefined; + this.exports = undefined; + this.dataPtr = 0; + } + init(memory, instance, options) { + var _a, _b; + if (this.exports) { + throw new Error('Asyncify has been initialized'); + } + if (!(memory instanceof _WebAssembly.Memory)) { + throw new TypeError('Require WebAssembly.Memory object'); + } + const exports = instance.exports; + for (let i = 0; i < ignoreNames.length; ++i) { + if (typeof exports[ignoreNames[i]] !== 'function') { + throw new TypeError('Invalid asyncify wasm'); + } + } + let address; + const wasm64 = Boolean(options.wasm64); + if (!options.tryAllocate) { + address = { + wasm64, + dataPtr: 16, + start: wasm64 ? 32 : 24, + end: 1024 + }; + } + else { + if (options.tryAllocate === true) { + address = tryAllocate(instance, wasm64, 4096, 'malloc'); + } + else { + address = tryAllocate(instance, wasm64, (_a = options.tryAllocate.size) !== null && _a !== void 0 ? _a : 4096, (_b = options.tryAllocate.name) !== null && _b !== void 0 ? _b : 'malloc'); + } + } + this.dataPtr = address.dataPtr; + if (wasm64) { + new BigInt64Array(memory.buffer, this.dataPtr).set([BigInt(address.start), BigInt(address.end)]); + } + else { + new Int32Array(memory.buffer, this.dataPtr).set([address.start, address.end]); + } + this.exports = this.wrapExports(exports, options.wrapExports); + const asyncifiedInstance = Object.create(_WebAssembly.Instance.prototype); + Object.defineProperty(asyncifiedInstance, 'exports', { value: this.exports }); + // Object.setPrototypeOf(instance, Instance.prototype) + return asyncifiedInstance; + } + assertState() { + if (this.exports.asyncify_get_state() !== AsyncifyState.NONE) { + throw new Error('Asyncify state error'); + } + } + wrapImportFunction(f) { + // eslint-disable-next-line @typescript-eslint/no-this-alias + const _this = this; + return (function () { + // eslint-disable-next-line no-unreachable-loop + while (_this.exports.asyncify_get_state() === AsyncifyState.REWINDING) { + _this.exports.asyncify_stop_rewind(); + return _this.value; + } + _this.assertState(); + const v = f.apply(this, arguments); + if (!isPromiseLike(v)) + return v; + _this.exports.asyncify_start_unwind(_this.dataPtr); + _this.value = v; + }); + } + wrapImports(imports) { + const importObject = {}; + Object.keys(imports).forEach(k => { + const mod = imports[k]; + const newModule = {}; + Object.keys(mod).forEach(name => { + const importValue = mod[name]; + if (typeof importValue === 'function') { + newModule[name] = this.wrapImportFunction(importValue); + } + else { + newModule[name] = importValue; + } + }); + importObject[k] = newModule; + }); + return importObject; + } + wrapExportFunction(f) { + // eslint-disable-next-line @typescript-eslint/no-this-alias + const _this = this; + return (async function () { + _this.assertState(); + let ret = f.apply(this, arguments); + while (_this.exports.asyncify_get_state() === AsyncifyState.UNWINDING) { + _this.exports.asyncify_stop_unwind(); + _this.value = await _this.value; + _this.assertState(); + _this.exports.asyncify_start_rewind(_this.dataPtr); + ret = f.call(this); + } + _this.assertState(); + return ret; + }); + } + wrapExports(exports, needWrap) { + return wrapInstanceExports(exports, (exportValue, name) => { + let ignore = ignoreNames.indexOf(name) !== -1 || typeof exportValue !== 'function'; + if (Array.isArray(needWrap)) { + ignore = ignore || (needWrap.indexOf(name) === -1); + } + return ignore ? exportValue : this.wrapExportFunction(exportValue); + }); + } +} diff --git a/dg-ui/node_modules/@tailwindcss/oxide-wasm32-wasi/node_modules/@tybys/wasm-util/lib/mjs/index.mjs b/dg-ui/node_modules/@tailwindcss/oxide-wasm32-wasi/node_modules/@tybys/wasm-util/lib/mjs/index.mjs new file mode 100644 index 0000000..6ff30a1 --- /dev/null +++ b/dg-ui/node_modules/@tailwindcss/oxide-wasm32-wasi/node_modules/@tybys/wasm-util/lib/mjs/index.mjs @@ -0,0 +1,9 @@ +/** + * @packageDocumentation + */ +export * from "./asyncify.mjs"; +export * from "./load.mjs"; +export * from "./wasi/index.mjs"; +export * from "./memory.mjs"; +export * from "./jspi.mjs"; +export * from "./wasi/fs.mjs"; diff --git a/dg-ui/node_modules/@tailwindcss/oxide-wasm32-wasi/node_modules/@tybys/wasm-util/lib/mjs/jspi.mjs b/dg-ui/node_modules/@tailwindcss/oxide-wasm32-wasi/node_modules/@tybys/wasm-util/lib/mjs/jspi.mjs new file mode 100644 index 0000000..28b54c8 --- /dev/null +++ b/dg-ui/node_modules/@tailwindcss/oxide-wasm32-wasi/node_modules/@tybys/wasm-util/lib/mjs/jspi.mjs @@ -0,0 +1,39 @@ +import { wrapInstanceExports } from "./wasi/util.mjs"; +import { _WebAssembly } from "./webassembly.mjs"; +function checkWebAssemblyFunction() { + const WebAssemblyFunction = _WebAssembly.Function; + if (typeof WebAssemblyFunction !== 'function') { + throw new Error('WebAssembly.Function is not supported in this environment.' + + ' If you are using V8 based browser like Chrome, try to specify' + + ' --js-flags="--wasm-staging --experimental-wasm-stack-switching"'); + } + return WebAssemblyFunction; +} +/** @public */ +export function wrapAsyncImport(f, parameterType, returnType) { + const WebAssemblyFunction = checkWebAssemblyFunction(); + if (typeof f !== 'function') { + throw new TypeError('Function required'); + } + const parameters = parameterType.slice(0); + parameters.unshift('externref'); + return new WebAssemblyFunction({ parameters, results: returnType }, f, { suspending: 'first' }); +} +/** @public */ +export function wrapAsyncExport(f) { + const WebAssemblyFunction = checkWebAssemblyFunction(); + if (typeof f !== 'function') { + throw new TypeError('Function required'); + } + return new WebAssemblyFunction({ parameters: [...WebAssemblyFunction.type(f).parameters.slice(1)], results: ['externref'] }, f, { promising: 'first' }); +} +/** @public */ +export function wrapExports(exports, needWrap) { + return wrapInstanceExports(exports, (exportValue, name) => { + let ignore = typeof exportValue !== 'function'; + if (Array.isArray(needWrap)) { + ignore = ignore || (needWrap.indexOf(name) === -1); + } + return ignore ? exportValue : wrapAsyncExport(exportValue); + }); +} diff --git a/dg-ui/node_modules/@tailwindcss/oxide-wasm32-wasi/node_modules/@tybys/wasm-util/lib/mjs/load.mjs b/dg-ui/node_modules/@tailwindcss/oxide-wasm32-wasi/node_modules/@tybys/wasm-util/lib/mjs/load.mjs new file mode 100644 index 0000000..7fee16a --- /dev/null +++ b/dg-ui/node_modules/@tailwindcss/oxide-wasm32-wasi/node_modules/@tybys/wasm-util/lib/mjs/load.mjs @@ -0,0 +1,89 @@ +import { _WebAssembly } from "./webassembly.mjs"; +import { Asyncify } from "./asyncify.mjs"; +function validateImports(imports) { + if (imports && typeof imports !== 'object') { + throw new TypeError('imports must be an object or undefined'); + } +} +function fetchWasm(urlOrBuffer, imports) { + if (typeof wx !== 'undefined' && typeof __wxConfig !== 'undefined') { + return _WebAssembly.instantiate(urlOrBuffer, imports); + } + return fetch(urlOrBuffer) + .then(response => response.arrayBuffer()) + .then(buffer => _WebAssembly.instantiate(buffer, imports)); +} +/** @public */ +export function load(wasmInput, imports) { + validateImports(imports); + imports = imports !== null && imports !== void 0 ? imports : {}; + let source; + if (wasmInput instanceof ArrayBuffer || ArrayBuffer.isView(wasmInput)) { + return _WebAssembly.instantiate(wasmInput, imports); + } + if (wasmInput instanceof _WebAssembly.Module) { + return _WebAssembly.instantiate(wasmInput, imports).then((instance) => { + return { instance, module: wasmInput }; + }); + } + if (typeof wasmInput !== 'string' && !(wasmInput instanceof URL)) { + throw new TypeError('Invalid source'); + } + if (typeof _WebAssembly.instantiateStreaming === 'function') { + let responsePromise; + try { + responsePromise = fetch(wasmInput); + source = _WebAssembly.instantiateStreaming(responsePromise, imports).catch(() => { + return fetchWasm(wasmInput, imports); + }); + } + catch (_) { + source = fetchWasm(wasmInput, imports); + } + } + else { + source = fetchWasm(wasmInput, imports); + } + return source; +} +/** @public */ +export function asyncifyLoad(asyncify, urlOrBuffer, imports) { + validateImports(imports); + imports = imports !== null && imports !== void 0 ? imports : {}; + const asyncifyHelper = new Asyncify(); + imports = asyncifyHelper.wrapImports(imports); + return load(urlOrBuffer, imports).then(source => { + var _a; + const memory = source.instance.exports.memory || ((_a = imports.env) === null || _a === void 0 ? void 0 : _a.memory); + return { module: source.module, instance: asyncifyHelper.init(memory, source.instance, asyncify) }; + }); +} +/** @public */ +export function loadSync(wasmInput, imports) { + validateImports(imports); + imports = imports !== null && imports !== void 0 ? imports : {}; + let module; + if ((wasmInput instanceof ArrayBuffer) || ArrayBuffer.isView(wasmInput)) { + module = new _WebAssembly.Module(wasmInput); + } + else if (wasmInput instanceof WebAssembly.Module) { + module = wasmInput; + } + else { + throw new TypeError('Invalid source'); + } + const instance = new _WebAssembly.Instance(module, imports); + const source = { instance, module }; + return source; +} +/** @public */ +export function asyncifyLoadSync(asyncify, buffer, imports) { + var _a; + validateImports(imports); + imports = imports !== null && imports !== void 0 ? imports : {}; + const asyncifyHelper = new Asyncify(); + imports = asyncifyHelper.wrapImports(imports); + const source = loadSync(buffer, imports); + const memory = source.instance.exports.memory || ((_a = imports.env) === null || _a === void 0 ? void 0 : _a.memory); + return { module: source.module, instance: asyncifyHelper.init(memory, source.instance, asyncify) }; +} diff --git a/dg-ui/node_modules/@tailwindcss/oxide-wasm32-wasi/node_modules/@tybys/wasm-util/lib/mjs/memory.mjs b/dg-ui/node_modules/@tailwindcss/oxide-wasm32-wasi/node_modules/@tybys/wasm-util/lib/mjs/memory.mjs new file mode 100644 index 0000000..72050f7 --- /dev/null +++ b/dg-ui/node_modules/@tailwindcss/oxide-wasm32-wasi/node_modules/@tybys/wasm-util/lib/mjs/memory.mjs @@ -0,0 +1,28 @@ +import { _WebAssembly } from "./webassembly.mjs"; +/** @public */ +export const WebAssemblyMemory = /*#__PURE__*/ (function () { return _WebAssembly.Memory; })(); +/** @public */ +export class Memory extends WebAssemblyMemory { + // eslint-disable-next-line @typescript-eslint/no-useless-constructor + constructor(descriptor) { + super(descriptor); + } + get HEAP8() { return new Int8Array(super.buffer); } + get HEAPU8() { return new Uint8Array(super.buffer); } + get HEAP16() { return new Int16Array(super.buffer); } + get HEAPU16() { return new Uint16Array(super.buffer); } + get HEAP32() { return new Int32Array(super.buffer); } + get HEAPU32() { return new Uint32Array(super.buffer); } + get HEAP64() { return new BigInt64Array(super.buffer); } + get HEAPU64() { return new BigUint64Array(super.buffer); } + get HEAPF32() { return new Float32Array(super.buffer); } + get HEAPF64() { return new Float64Array(super.buffer); } + get view() { return new DataView(super.buffer); } +} +/** @public */ +export function extendMemory(memory) { + if (Object.getPrototypeOf(memory) === _WebAssembly.Memory.prototype) { + Object.setPrototypeOf(memory, Memory.prototype); + } + return memory; +} diff --git a/dg-ui/node_modules/@tailwindcss/oxide-wasm32-wasi/node_modules/@tybys/wasm-util/lib/mjs/wasi/error.mjs b/dg-ui/node_modules/@tailwindcss/oxide-wasm32-wasi/node_modules/@tybys/wasm-util/lib/mjs/wasi/error.mjs new file mode 100644 index 0000000..5c08120 --- /dev/null +++ b/dg-ui/node_modules/@tailwindcss/oxide-wasm32-wasi/node_modules/@tybys/wasm-util/lib/mjs/wasi/error.mjs @@ -0,0 +1,97 @@ +import { WasiErrno } from "./types.mjs"; +export function strerror(errno) { + switch (errno) { + case WasiErrno.ESUCCESS: return 'Success'; + case WasiErrno.E2BIG: return 'Argument list too long'; + case WasiErrno.EACCES: return 'Permission denied'; + case WasiErrno.EADDRINUSE: return 'Address in use'; + case WasiErrno.EADDRNOTAVAIL: return 'Address not available'; + case WasiErrno.EAFNOSUPPORT: return 'Address family not supported by protocol'; + case WasiErrno.EAGAIN: return 'Resource temporarily unavailable'; + case WasiErrno.EALREADY: return 'Operation already in progress'; + case WasiErrno.EBADF: return 'Bad file descriptor'; + case WasiErrno.EBADMSG: return 'Bad message'; + case WasiErrno.EBUSY: return 'Resource busy'; + case WasiErrno.ECANCELED: return 'Operation canceled'; + case WasiErrno.ECHILD: return 'No child process'; + case WasiErrno.ECONNABORTED: return 'Connection aborted'; + case WasiErrno.ECONNREFUSED: return 'Connection refused'; + case WasiErrno.ECONNRESET: return 'Connection reset by peer'; + case WasiErrno.EDEADLK: return 'Resource deadlock would occur'; + case WasiErrno.EDESTADDRREQ: return 'Destination address required'; + case WasiErrno.EDOM: return 'Domain error'; + case WasiErrno.EDQUOT: return 'Quota exceeded'; + case WasiErrno.EEXIST: return 'File exists'; + case WasiErrno.EFAULT: return 'Bad address'; + case WasiErrno.EFBIG: return 'File too large'; + case WasiErrno.EHOSTUNREACH: return 'Host is unreachable'; + case WasiErrno.EIDRM: return 'Identifier removed'; + case WasiErrno.EILSEQ: return 'Illegal byte sequence'; + case WasiErrno.EINPROGRESS: return 'Operation in progress'; + case WasiErrno.EINTR: return 'Interrupted system call'; + case WasiErrno.EINVAL: return 'Invalid argument'; + case WasiErrno.EIO: return 'I/O error'; + case WasiErrno.EISCONN: return 'Socket is connected'; + case WasiErrno.EISDIR: return 'Is a directory'; + case WasiErrno.ELOOP: return 'Symbolic link loop'; + case WasiErrno.EMFILE: return 'No file descriptors available'; + case WasiErrno.EMLINK: return 'Too many links'; + case WasiErrno.EMSGSIZE: return 'Message too large'; + case WasiErrno.EMULTIHOP: return 'Multihop attempted'; + case WasiErrno.ENAMETOOLONG: return 'Filename too long'; + case WasiErrno.ENETDOWN: return 'Network is down'; + case WasiErrno.ENETRESET: return 'Connection reset by network'; + case WasiErrno.ENETUNREACH: return 'Network unreachable'; + case WasiErrno.ENFILE: return 'Too many files open in system'; + case WasiErrno.ENOBUFS: return 'No buffer space available'; + case WasiErrno.ENODEV: return 'No such device'; + case WasiErrno.ENOENT: return 'No such file or directory'; + case WasiErrno.ENOEXEC: return 'Exec format error'; + case WasiErrno.ENOLCK: return 'No locks available'; + case WasiErrno.ENOLINK: return 'Link has been severed'; + case WasiErrno.ENOMEM: return 'Out of memory'; + case WasiErrno.ENOMSG: return 'No message of the desired type'; + case WasiErrno.ENOPROTOOPT: return 'Protocol not available'; + case WasiErrno.ENOSPC: return 'No space left on device'; + case WasiErrno.ENOSYS: return 'Function not implemented'; + case WasiErrno.ENOTCONN: return 'Socket not connected'; + case WasiErrno.ENOTDIR: return 'Not a directory'; + case WasiErrno.ENOTEMPTY: return 'Directory not empty'; + case WasiErrno.ENOTRECOVERABLE: return 'State not recoverable'; + case WasiErrno.ENOTSOCK: return 'Not a socket'; + case WasiErrno.ENOTSUP: return 'Not supported'; + case WasiErrno.ENOTTY: return 'Not a tty'; + case WasiErrno.ENXIO: return 'No such device or address'; + case WasiErrno.EOVERFLOW: return 'Value too large for data type'; + case WasiErrno.EOWNERDEAD: return 'Previous owner died'; + case WasiErrno.EPERM: return 'Operation not permitted'; + case WasiErrno.EPIPE: return 'Broken pipe'; + case WasiErrno.EPROTO: return 'Protocol error'; + case WasiErrno.EPROTONOSUPPORT: return 'Protocol not supported'; + case WasiErrno.EPROTOTYPE: return 'Protocol wrong type for socket'; + case WasiErrno.ERANGE: return 'Result not representable'; + case WasiErrno.EROFS: return 'Read-only file system'; + case WasiErrno.ESPIPE: return 'Invalid seek'; + case WasiErrno.ESRCH: return 'No such process'; + case WasiErrno.ESTALE: return 'Stale file handle'; + case WasiErrno.ETIMEDOUT: return 'Operation timed out'; + case WasiErrno.ETXTBSY: return 'Text file busy'; + case WasiErrno.EXDEV: return 'Cross-device link'; + case WasiErrno.ENOTCAPABLE: return 'Capabilities insufficient'; + default: return 'Unknown error'; + } +} +export class WasiError extends Error { + constructor(message, errno) { + super(message); + this.errno = errno; + } + getErrorMessage() { + return strerror(this.errno); + } +} +Object.defineProperty(WasiError.prototype, 'name', { + configurable: true, + writable: true, + value: 'WasiError' +}); diff --git a/dg-ui/node_modules/@tailwindcss/oxide-wasm32-wasi/node_modules/@tybys/wasm-util/lib/mjs/wasi/fd.mjs b/dg-ui/node_modules/@tailwindcss/oxide-wasm32-wasi/node_modules/@tybys/wasm-util/lib/mjs/wasi/fd.mjs new file mode 100644 index 0000000..9ff3d03 --- /dev/null +++ b/dg-ui/node_modules/@tailwindcss/oxide-wasm32-wasi/node_modules/@tybys/wasm-util/lib/mjs/wasi/fd.mjs @@ -0,0 +1,256 @@ +import { WasiErrno, FileControlFlag, WasiFileType, WasiWhence } from "./types.mjs"; +import { getRights } from "./rights.mjs"; +import { WasiError } from "./error.mjs"; +export function concatBuffer(buffers, size) { + let total = 0; + if (typeof size === 'number' && size >= 0) { + total = size; + } + else { + for (let i = 0; i < buffers.length; i++) { + const buffer = buffers[i]; + total += buffer.length; + } + } + let pos = 0; + const ret = new Uint8Array(total); + for (let i = 0; i < buffers.length; i++) { + const buffer = buffers[i]; + ret.set(buffer, pos); + pos += buffer.length; + } + return ret; +} +export class FileDescriptor { + constructor(id, fd, path, realPath, type, rightsBase, rightsInheriting, preopen) { + this.id = id; + this.fd = fd; + this.path = path; + this.realPath = realPath; + this.type = type; + this.rightsBase = rightsBase; + this.rightsInheriting = rightsInheriting; + this.preopen = preopen; + this.pos = BigInt(0); + this.size = BigInt(0); + } + seek(offset, whence) { + if (whence === WasiWhence.SET) { + this.pos = BigInt(offset); + } + else if (whence === WasiWhence.CUR) { + this.pos += BigInt(offset); + } + else if (whence === WasiWhence.END) { + this.pos = BigInt(this.size) - BigInt(offset); + } + else { + throw new WasiError('Unknown whence', WasiErrno.EIO); + } + return this.pos; + } +} +export class StandardOutput extends FileDescriptor { + constructor(log, id, fd, path, realPath, type, rightsBase, rightsInheriting, preopen) { + super(id, fd, path, realPath, type, rightsBase, rightsInheriting, preopen); + this._log = log; + this._buf = null; + } + write(buffer) { + const originalBuffer = buffer; + if (this._buf) { + buffer = concatBuffer([this._buf, buffer]); + this._buf = null; + } + if (buffer.indexOf(10) === -1) { + this._buf = buffer; + return originalBuffer.byteLength; + } + let written = 0; + let lastBegin = 0; + let index; + while ((index = buffer.indexOf(10, written)) !== -1) { + const str = new TextDecoder().decode(buffer.subarray(lastBegin, index)); + this._log(str); + written += index - lastBegin + 1; + lastBegin = index + 1; + } + if (written < buffer.length) { + this._buf = buffer.slice(written); + } + return originalBuffer.byteLength; + } +} +export function toFileType(stat) { + if (stat.isBlockDevice()) + return WasiFileType.BLOCK_DEVICE; + if (stat.isCharacterDevice()) + return WasiFileType.CHARACTER_DEVICE; + if (stat.isDirectory()) + return WasiFileType.DIRECTORY; + if (stat.isSocket()) + return WasiFileType.SOCKET_STREAM; + if (stat.isFile()) + return WasiFileType.REGULAR_FILE; + if (stat.isSymbolicLink()) + return WasiFileType.SYMBOLIC_LINK; + return WasiFileType.UNKNOWN; +} +export function toFileStat(view, buf, stat) { + view.setBigUint64(buf, stat.dev, true); + view.setBigUint64(buf + 8, stat.ino, true); + view.setBigUint64(buf + 16, BigInt(toFileType(stat)), true); + view.setBigUint64(buf + 24, stat.nlink, true); + view.setBigUint64(buf + 32, stat.size, true); + view.setBigUint64(buf + 40, stat.atimeMs * BigInt(1000000), true); + view.setBigUint64(buf + 48, stat.mtimeMs * BigInt(1000000), true); + view.setBigUint64(buf + 56, stat.ctimeMs * BigInt(1000000), true); +} +export class FileDescriptorTable { + constructor(options) { + this.used = 0; + this.size = options.size; + this.fds = Array(options.size); + this.stdio = [options.in, options.out, options.err]; + this.print = options.print; + this.printErr = options.printErr; + this.insertStdio(options.in, 0, ''); + this.insertStdio(options.out, 1, ''); + this.insertStdio(options.err, 2, ''); + } + insertStdio(fd, expected, name) { + const type = WasiFileType.CHARACTER_DEVICE; + const { base, inheriting } = getRights(this.stdio, fd, FileControlFlag.O_RDWR, type); + const wrap = this.insert(fd, name, name, type, base, inheriting, 0); + if (wrap.id !== expected) { + throw new WasiError(`id: ${wrap.id} !== expected: ${expected}`, WasiErrno.EBADF); + } + return wrap; + } + insert(fd, mappedPath, realPath, type, rightsBase, rightsInheriting, preopen) { + var _a, _b; + let index = -1; + if (this.used >= this.size) { + const newSize = this.size * 2; + this.fds.length = newSize; + index = this.size; + this.size = newSize; + } + else { + for (let i = 0; i < this.size; ++i) { + if (this.fds[i] == null) { + index = i; + break; + } + } + } + let entry; + if (mappedPath === '') { + entry = new StandardOutput((_a = this.print) !== null && _a !== void 0 ? _a : console.log, index, fd, mappedPath, realPath, type, rightsBase, rightsInheriting, preopen); + } + else if (mappedPath === '') { + entry = new StandardOutput((_b = this.printErr) !== null && _b !== void 0 ? _b : console.error, index, fd, mappedPath, realPath, type, rightsBase, rightsInheriting, preopen); + } + else { + entry = new FileDescriptor(index, fd, mappedPath, realPath, type, rightsBase, rightsInheriting, preopen); + } + this.fds[index] = entry; + this.used++; + return entry; + } + get(id, base, inheriting) { + if (id >= this.size) { + throw new WasiError('Invalid fd', WasiErrno.EBADF); + } + const entry = this.fds[id]; + if (!entry || entry.id !== id) { + throw new WasiError('Bad file descriptor', WasiErrno.EBADF); + } + /* Validate that the fd has the necessary rights. */ + if ((~entry.rightsBase & base) !== BigInt(0) || (~entry.rightsInheriting & inheriting) !== BigInt(0)) { + throw new WasiError('Capabilities insufficient', WasiErrno.ENOTCAPABLE); + } + return entry; + } + remove(id) { + if (id >= this.size) { + throw new WasiError('Invalid fd', WasiErrno.EBADF); + } + const entry = this.fds[id]; + if (!entry || entry.id !== id) { + throw new WasiError('Bad file descriptor', WasiErrno.EBADF); + } + this.fds[id] = undefined; + this.used--; + } +} +export class SyncTable extends FileDescriptorTable { + constructor(options) { + super(options); + this.fs = options.fs; + } + getFileTypeByFd(fd) { + const stats = this.fs.fstatSync(fd, { bigint: true }); + return toFileType(stats); + } + insertPreopen(fd, mappedPath, realPath) { + const type = this.getFileTypeByFd(fd); + if (type !== WasiFileType.DIRECTORY) { + throw new WasiError(`Preopen not dir: ["${mappedPath}", "${realPath}"]`, WasiErrno.ENOTDIR); + } + const result = getRights(this.stdio, fd, 0, type); + return this.insert(fd, mappedPath, realPath, type, result.base, result.inheriting, 1); + } + renumber(dst, src) { + if (dst === src) + return; + if (dst >= this.size || src >= this.size) { + throw new WasiError('Invalid fd', WasiErrno.EBADF); + } + const dstEntry = this.fds[dst]; + const srcEntry = this.fds[src]; + if (!dstEntry || !srcEntry || dstEntry.id !== dst || srcEntry.id !== src) { + throw new WasiError('Invalid fd', WasiErrno.EBADF); + } + this.fs.closeSync(dstEntry.fd); + this.fds[dst] = this.fds[src]; + this.fds[dst].id = dst; + this.fds[src] = undefined; + this.used--; + } +} +export class AsyncTable extends FileDescriptorTable { + // eslint-disable-next-line @typescript-eslint/no-useless-constructor + constructor(options) { + super(options); + } + async getFileTypeByFd(fd) { + const stats = await fd.stat({ bigint: true }); + return toFileType(stats); + } + async insertPreopen(fd, mappedPath, realPath) { + const type = await this.getFileTypeByFd(fd); + if (type !== WasiFileType.DIRECTORY) { + throw new WasiError(`Preopen not dir: ["${mappedPath}", "${realPath}"]`, WasiErrno.ENOTDIR); + } + const result = getRights(this.stdio, fd.fd, 0, type); + return this.insert(fd, mappedPath, realPath, type, result.base, result.inheriting, 1); + } + async renumber(dst, src) { + if (dst === src) + return; + if (dst >= this.size || src >= this.size) { + throw new WasiError('Invalid fd', WasiErrno.EBADF); + } + const dstEntry = this.fds[dst]; + const srcEntry = this.fds[src]; + if (!dstEntry || !srcEntry || dstEntry.id !== dst || srcEntry.id !== src) { + throw new WasiError('Invalid fd', WasiErrno.EBADF); + } + await dstEntry.fd.close(); + this.fds[dst] = this.fds[src]; + this.fds[dst].id = dst; + this.fds[src] = undefined; + this.used--; + } +} diff --git a/dg-ui/node_modules/@tailwindcss/oxide-wasm32-wasi/node_modules/@tybys/wasm-util/lib/mjs/wasi/fs.mjs b/dg-ui/node_modules/@tailwindcss/oxide-wasm32-wasi/node_modules/@tybys/wasm-util/lib/mjs/wasi/fs.mjs new file mode 100644 index 0000000..cb0ff5c --- /dev/null +++ b/dg-ui/node_modules/@tailwindcss/oxide-wasm32-wasi/node_modules/@tybys/wasm-util/lib/mjs/wasi/fs.mjs @@ -0,0 +1 @@ +export {}; diff --git a/dg-ui/node_modules/@tailwindcss/oxide-wasm32-wasi/node_modules/@tybys/wasm-util/lib/mjs/wasi/index.mjs b/dg-ui/node_modules/@tailwindcss/oxide-wasm32-wasi/node_modules/@tybys/wasm-util/lib/mjs/wasi/index.mjs new file mode 100644 index 0000000..127ff99 --- /dev/null +++ b/dg-ui/node_modules/@tailwindcss/oxide-wasm32-wasi/node_modules/@tybys/wasm-util/lib/mjs/wasi/index.mjs @@ -0,0 +1,186 @@ +import { WASI as WASIPreview1 } from "./preview1.mjs"; +import { validateObject, validateArray, validateBoolean, validateFunction, validateUndefined, validateString } from "./util.mjs"; +// eslint-disable-next-line spaced-comment +const kEmptyObject = /*#__PURE__*/ Object.freeze(/*#__PURE__*/ Object.create(null)); +const kExitCode = Symbol('kExitCode'); +const kSetMemory = Symbol('kSetMemory'); +const kStarted = Symbol('kStarted'); +const kInstance = Symbol('kInstance'); +const kBindingName = Symbol('kBindingName'); +function validateOptions(options) { + var _a; + validateObject(options, 'options'); + let _WASI; + if (options.version !== undefined) { + validateString(options.version, 'options.version'); + switch (options.version) { + case 'unstable': + _WASI = WASIPreview1; + this[kBindingName] = 'wasi_unstable'; + break; + case 'preview1': + _WASI = WASIPreview1; + this[kBindingName] = 'wasi_snapshot_preview1'; + break; + default: + throw new TypeError(`unsupported WASI version "${options.version}"`); + } + } + else { + _WASI = WASIPreview1; + this[kBindingName] = 'wasi_snapshot_preview1'; + } + if (options.args !== undefined) { + validateArray(options.args, 'options.args'); + } + const args = ((_a = options.args) !== null && _a !== void 0 ? _a : []).map(String); + const env = []; + if (options.env !== undefined) { + validateObject(options.env, 'options.env'); + Object.entries(options.env).forEach(({ 0: key, 1: value }) => { + if (value !== undefined) { + env.push(`${key}=${value}`); + } + }); + } + const preopens = []; + if (options.preopens !== undefined) { + validateObject(options.preopens, 'options.preopens'); + Object.entries(options.preopens).forEach(({ 0: key, 1: value }) => preopens.push({ mappedPath: String(key), realPath: String(value) })); + } + if (preopens.length > 0) { + if (options.fs === undefined) { + throw new Error('filesystem is disabled, can not preopen directory'); + } + try { + validateObject(options.fs, 'options.fs'); + } + catch (_) { + throw new TypeError('Node.js fs like implementation is not provided'); + } + } + // if (options.filesystem !== undefined) { + // validateObject(options.filesystem, 'options.filesystem') + // validateString(options.filesystem.type, 'options.filesystem.type') + // if (options.filesystem.type !== 'memfs' && options.filesystem.type !== 'file-system-access-api') { + // throw new Error(`Filesystem type ${(options.filesystem as any).type as string} is not supported, only "memfs" and "file-system-access-api" is supported currently`) + // } + // try { + // validateObject(options.filesystem.fs, 'options.filesystem.fs') + // } catch (_) { + // throw new Error('Node.js fs like implementation is not provided') + // } + // } + if (options.print !== undefined) + validateFunction(options.print, 'options.print'); + if (options.printErr !== undefined) + validateFunction(options.printErr, 'options.printErr'); + if (options.returnOnExit !== undefined) { + validateBoolean(options.returnOnExit, 'options.returnOnExit'); + } + // const { stdin = 0, stdout = 1, stderr = 2 } = options + // validateInt32(stdin, 'options.stdin', 0) + // validateInt32(stdout, 'options.stdout', 0) + // validateInt32(stderr, 'options.stderr', 0) + // const stdio = [stdin, stdout, stderr] as const + const stdio = [0, 1, 2]; + return { + args, + env, + preopens, + stdio, + _WASI + }; +} +function initWASI(setMemory, wrap) { + this[kSetMemory] = setMemory; + this.wasiImport = wrap; + this[kStarted] = false; + this[kExitCode] = 0; + this[kInstance] = undefined; +} +/** @public */ +export class WASI { + constructor(options = kEmptyObject) { + const { args, env, preopens, stdio, _WASI } = validateOptions.call(this, options); + const wrap = _WASI.createSync(args, env, preopens, stdio, options.fs, options.print, options.printErr); + const setMemory = wrap._setMemory; + delete wrap._setMemory; + initWASI.call(this, setMemory, wrap); + if (options.returnOnExit) { + wrap.proc_exit = wasiReturnOnProcExit.bind(this); + } + } + finalizeBindings(instance, _a) { + var _b; + var { memory = (_b = instance === null || instance === void 0 ? void 0 : instance.exports) === null || _b === void 0 ? void 0 : _b.memory } = _a === void 0 ? {} : _a; + if (this[kStarted]) { + throw new Error('WASI instance has already started'); + } + validateObject(instance, 'instance'); + validateObject(instance.exports, 'instance.exports'); + this[kSetMemory](memory); + this[kInstance] = instance; + this[kStarted] = true; + } + // Must not export _initialize, must export _start + start(instance) { + this.finalizeBindings(instance); + const { _start, _initialize } = this[kInstance].exports; + validateFunction(_start, 'instance.exports._start'); + validateUndefined(_initialize, 'instance.exports._initialize'); + let ret; + try { + ret = _start(); + } + catch (err) { + if (err !== kExitCode) { + throw err; + } + } + if (ret instanceof Promise) { + return ret.then(() => this[kExitCode], (err) => { + if (err !== kExitCode) { + throw err; + } + return this[kExitCode]; + }); + } + return this[kExitCode]; + } + // Must not export _start, may optionally export _initialize + initialize(instance) { + this.finalizeBindings(instance); + const { _start, _initialize } = this[kInstance].exports; + validateUndefined(_start, 'instance.exports._start'); + if (_initialize !== undefined) { + validateFunction(_initialize, 'instance.exports._initialize'); + return _initialize(); + } + } + getImportObject() { + return { [this[kBindingName]]: this.wasiImport }; + } +} +function wasiReturnOnProcExit(rval) { + this[kExitCode] = rval; + // eslint-disable-next-line @typescript-eslint/no-throw-literal + throw kExitCode; +} +/** @public */ +export async function createAsyncWASI(options = kEmptyObject) { + const _this = Object.create(WASI.prototype); + const { args, env, preopens, stdio, _WASI } = validateOptions.call(_this, options); + if (options.asyncify !== undefined) { + validateObject(options.asyncify, 'options.asyncify'); + validateFunction(options.asyncify.wrapImportFunction, 'options.asyncify.wrapImportFunction'); + } + const wrap = await _WASI.createAsync(args, env, preopens, stdio, options.fs, options.print, options.printErr, options.asyncify); + const setMemory = wrap._setMemory; + delete wrap._setMemory; + initWASI.call(_this, setMemory, wrap); + if (options.returnOnExit) { + wrap.proc_exit = wasiReturnOnProcExit.bind(_this); + } + return _this; +} diff --git a/dg-ui/node_modules/@tailwindcss/oxide-wasm32-wasi/node_modules/@tybys/wasm-util/lib/mjs/wasi/path.mjs b/dg-ui/node_modules/@tailwindcss/oxide-wasm32-wasi/node_modules/@tybys/wasm-util/lib/mjs/wasi/path.mjs new file mode 100644 index 0000000..34d92a6 --- /dev/null +++ b/dg-ui/node_modules/@tailwindcss/oxide-wasm32-wasi/node_modules/@tybys/wasm-util/lib/mjs/wasi/path.mjs @@ -0,0 +1,310 @@ +import { validateString } from "./util.mjs"; +const CHAR_DOT = 46; /* . */ +const CHAR_FORWARD_SLASH = 47; /* / */ +const CHAR_BACKWARD_SLASH = 92; /* \ */ +const CHAR_COLON = 58; /* : */ +const CHAR_UPPERCASE_A = 65; /* A */ +const CHAR_UPPERCASE_Z = 90; /* Z */ +const CHAR_LOWERCASE_A = 97; /* a */ +const CHAR_LOWERCASE_Z = 122; /* z */ +function isPathSeparatorWin(code) { + return code === CHAR_FORWARD_SLASH || code === CHAR_BACKWARD_SLASH; +} +function isWindowsDeviceRoot(code) { + return (code >= CHAR_UPPERCASE_A && code <= CHAR_UPPERCASE_Z) || + (code >= CHAR_LOWERCASE_A && code <= CHAR_LOWERCASE_Z); +} +const _isWin32 = typeof process !== 'undefined' && process.platform === 'win32'; +/** + * Windows variant of `resolve()`. Mirrors Node's `path.win32.resolve` + * semantics enough for the WASI shim's needs (drive-letter absolutes + * + UNC paths + per-drive cwd lookups via `process.env`/`process.cwd`). + * + * Why this is needed: on Windows, `FileDescriptor.realPath` is the + * host realpath returned by `fs.realpathSync(realPath, 'utf8')` — the + * backslash form `D:\…`. The POSIX-only `resolveImpl` below only + * treats `/` as a separator, reads `D` as non-`/`, decides realPath + * is "relative", and produces a garbage joined path. Downstream + * `fs.openSync(garbage)` then returns `EINVAL` and the WASI caller + * sees a permanent failure. This function gives us the correct + * Windows-style resolution without taking a Node-only `path` import + * (which would break browser bundles of this package). + * + * Cribbed from Node's `lib/path.js` `win32.resolve()` (MIT-licensed), + * trimmed to what WASI realpath resolution actually exercises. + */ +function resolveWin32(args) { + let resolvedDevice = ''; + let resolvedTail = ''; + let resolvedAbsolute = false; + for (let i = args.length - 1; i >= -1; i--) { + let path; + if (i >= 0) { + path = args[i]; + validateString(path, 'path'); + if (path.length === 0) + continue; + } + else if (resolvedDevice.length === 0) { + path = (typeof process !== 'undefined' && typeof process.cwd === 'function') + ? process.cwd() + : ''; + } + else { + // Look up per-drive cwd via the `=X:` env var convention; fall back + // to the global cwd if absent. + const envKey = `=${resolvedDevice}`; + const env = (typeof process !== 'undefined') ? process.env : undefined; + path = (env && typeof env[envKey] === 'string') + ? env[envKey] + : (typeof process !== 'undefined' && typeof process.cwd === 'function') + ? process.cwd() + : ''; + if (path === undefined || + (path.slice(0, 2).toLowerCase() !== resolvedDevice.toLowerCase() && + path.charCodeAt(2) === CHAR_BACKWARD_SLASH)) { + path = `${resolvedDevice}\\`; + } + } + const len = path.length; + let rootEnd = 0; + let device = ''; + let isAbsolute = false; + const code = path.charCodeAt(0); + if (len === 1) { + if (isPathSeparatorWin(code)) { + rootEnd = 1; + isAbsolute = true; + } + } + else if (isPathSeparatorWin(code)) { + isAbsolute = true; + if (isPathSeparatorWin(path.charCodeAt(1))) { + // UNC path: `\\server\share\…` + let j = 2; + let last = j; + while (j < len && !isPathSeparatorWin(path.charCodeAt(j))) + j++; + if (j < len && j !== last) { + const firstPart = path.slice(last, j); + last = j; + while (j < len && isPathSeparatorWin(path.charCodeAt(j))) + j++; + if (j < len && j !== last) { + last = j; + while (j < len && !isPathSeparatorWin(path.charCodeAt(j))) + j++; + if (j === len || j !== last) { + device = `\\\\${firstPart}\\${path.slice(last, j)}`; + rootEnd = j; + } + } + } + } + else { + rootEnd = 1; + } + } + else if (isWindowsDeviceRoot(code) && path.charCodeAt(1) === CHAR_COLON) { + device = path.slice(0, 2); + rootEnd = 2; + if (len > 2 && isPathSeparatorWin(path.charCodeAt(2))) { + isAbsolute = true; + rootEnd = 3; + } + } + if (device.length > 0) { + if (resolvedDevice.length > 0) { + if (device.toLowerCase() !== resolvedDevice.toLowerCase()) + continue; + } + else { + resolvedDevice = device; + } + } + if (resolvedAbsolute) { + if (resolvedDevice.length > 0) + break; + } + else { + resolvedTail = `${path.slice(rootEnd)}\\${resolvedTail}`; + resolvedAbsolute = isAbsolute; + if (isAbsolute && resolvedDevice.length > 0) + break; + } + } + resolvedTail = normalizeString(resolvedTail, !resolvedAbsolute, '\\', isPathSeparatorWin); + return resolvedDevice + (resolvedAbsolute ? '\\' : '') + resolvedTail || '.'; +} +function isPosixPathSeparator(code) { + return code === CHAR_FORWARD_SLASH; +} +function normalizeString(path, allowAboveRoot, separator, isPathSeparator) { + let res = ''; + let lastSegmentLength = 0; + let lastSlash = -1; + let dots = 0; + let code = 0; + for (let i = 0; i <= path.length; ++i) { + if (i < path.length) { + code = path.charCodeAt(i); + } + else if (isPathSeparator(code)) { + break; + } + else { + code = CHAR_FORWARD_SLASH; + } + if (isPathSeparator(code)) { + if (lastSlash === i - 1 || dots === 1) { + // NOOP + } + else if (dots === 2) { + if (res.length < 2 || lastSegmentLength !== 2 || + res.charCodeAt(res.length - 1) !== CHAR_DOT || + res.charCodeAt(res.length - 2) !== CHAR_DOT) { + if (res.length > 2) { + const lastSlashIndex = res.indexOf(separator); + if (lastSlashIndex === -1) { + res = ''; + lastSegmentLength = 0; + } + else { + res = res.slice(0, lastSlashIndex); + lastSegmentLength = + res.length - 1 - res.indexOf(separator); + } + lastSlash = i; + dots = 0; + continue; + } + else if (res.length !== 0) { + res = ''; + lastSegmentLength = 0; + lastSlash = i; + dots = 0; + continue; + } + } + if (allowAboveRoot) { + res += res.length > 0 ? `${separator}..` : '..'; + lastSegmentLength = 2; + } + } + else { + if (res.length > 0) { + res += `${separator}${path.slice(lastSlash + 1, i)}`; + } + else { + res = path.slice(lastSlash + 1, i); + } + lastSegmentLength = i - lastSlash - 1; + } + lastSlash = i; + dots = 0; + } + else if (code === CHAR_DOT && dots !== -1) { + ++dots; + } + else { + dots = -1; + } + } + return res; +} +export function resolve(...args) { + // On Windows, host paths are `D:\…` style. The POSIX-only resolver + // below treats `D` as a non-`/` character and produces garbage; route + // to the Windows-aware variant. POSIX hosts (Linux/macOS/browser) + // run the original code path unchanged — `_isWin32` is constant-folded + // away on those targets. + if (_isWin32) + return resolveWin32(args); + let resolvedPath = ''; + let resolvedAbsolute = false; + for (let i = args.length - 1; i >= -1 && !resolvedAbsolute; i--) { + const path = i >= 0 ? args[i] : '/'; + validateString(path, 'path'); + // Skip empty entries + if (path.length === 0) { + continue; + } + resolvedPath = `${path}/${resolvedPath}`; + resolvedAbsolute = path.charCodeAt(0) === CHAR_FORWARD_SLASH; + } + // At this point the path should be resolved to a full absolute path, but + // handle relative paths to be safe (might happen when process.cwd() fails) + // Normalize the path + resolvedPath = normalizeString(resolvedPath, !resolvedAbsolute, '/', isPosixPathSeparator); + if (resolvedAbsolute) { + return `/${resolvedPath}`; + } + return resolvedPath.length > 0 ? resolvedPath : '.'; +} +export function relative(from, to) { + validateString(from, 'from'); + validateString(to, 'to'); + if (from === to) + return ''; + // Trim leading forward slashes. + from = resolve(from); + to = resolve(to); + if (from === to) + return ''; + const fromStart = 1; + const fromEnd = from.length; + const fromLen = fromEnd - fromStart; + const toStart = 1; + const toLen = to.length - toStart; + // Compare paths to find the longest common path from root + const length = (fromLen < toLen ? fromLen : toLen); + let lastCommonSep = -1; + let i = 0; + for (; i < length; i++) { + const fromCode = from.charCodeAt(fromStart + i); + if (fromCode !== to.charCodeAt(toStart + i)) { + break; + } + else if (fromCode === CHAR_FORWARD_SLASH) { + lastCommonSep = i; + } + } + if (i === length) { + if (toLen > length) { + if (to.charCodeAt(toStart + i) === CHAR_FORWARD_SLASH) { + // We get here if `from` is the exact base path for `to`. + // For example: from='/foo/bar'; to='/foo/bar/baz' + return to.slice(toStart + i + 1); + } + if (i === 0) { + // We get here if `from` is the root + // For example: from='/'; to='/foo' + return to.slice(toStart + i); + } + } + else if (fromLen > length) { + if (from.charCodeAt(fromStart + i) === CHAR_FORWARD_SLASH) { + // We get here if `to` is the exact base path for `from`. + // For example: from='/foo/bar/baz'; to='/foo/bar' + lastCommonSep = i; + } + else if (i === 0) { + // We get here if `to` is the root. + // For example: from='/foo/bar'; to='/' + lastCommonSep = 0; + } + } + } + let out = ''; + // Generate the relative path based on the path difference between `to` + // and `from`. + for (i = fromStart + lastCommonSep + 1; i <= fromEnd; ++i) { + if (i === fromEnd || + from.charCodeAt(i) === CHAR_FORWARD_SLASH) { + out += out.length === 0 ? '..' : '/..'; + } + } + // Lastly, append the rest of the destination (`to`) path that comes after + // the common path parts. + return `${out}${to.slice(toStart + lastCommonSep)}`; +} diff --git a/dg-ui/node_modules/@tailwindcss/oxide-wasm32-wasi/node_modules/@tybys/wasm-util/lib/mjs/wasi/preview1.mjs b/dg-ui/node_modules/@tailwindcss/oxide-wasm32-wasi/node_modules/@tybys/wasm-util/lib/mjs/wasi/preview1.mjs new file mode 100644 index 0000000..d7f5b51 --- /dev/null +++ b/dg-ui/node_modules/@tailwindcss/oxide-wasm32-wasi/node_modules/@tybys/wasm-util/lib/mjs/wasi/preview1.mjs @@ -0,0 +1,1593 @@ +import { _WebAssembly } from "../webassembly.mjs"; +import { resolve } from "./path.mjs"; +// Linux fcntl flag bits ↔ Windows libuv flag bits. `pathOpen()` builds +// `flagsRes` using Linux constants (O_CREAT=0x40, O_EXCL=0x80, +// O_APPEND=0x400). Windows libuv expects different bits (O_CREAT=0x100, +// O_EXCL=0x400, O_APPEND=0x8). Without translation, +// `fs.openSync(path, 0x241 /* L:WRONLY|CREAT|TRUNC */)` is rejected +// with EINVAL because Linux's 0x40 happens to mean O_TEMPORARY on +// Windows — and O_TEMPORARY without O_CREAT is invalid. +const _isWin32Flags = typeof process !== 'undefined' && process.platform === 'win32'; +function _toWinOpenFlags(f) { + let r = f & 3; // RDONLY/WRONLY/RDWR — same on both + if ((f & 0x40) !== 0) + r |= 0x100; // O_CREAT: Linux 0x40 -> Windows 0x100 + if ((f & 0x80) !== 0) + r |= 0x400; // O_EXCL: Linux 0x80 -> Windows 0x400 + if ((f & 0x200) !== 0) + r |= 0x200; // O_TRUNC: same value on both + if ((f & 0x400) !== 0) + r |= 0x8; // O_APPEND: Linux 0x400 -> Windows 0x8 + return r; +} +import { WasiErrno, WasiRights, FileControlFlag, WasiFileControlFlag, WasiFdFlag, WasiFileType, WasiClockid, WasiFstFlag, WasiEventType, WasiSubclockflags } from "./types.mjs"; +import { concatBuffer, toFileStat, AsyncTable, SyncTable } from "./fd.mjs"; +import { WasiError } from "./error.mjs"; +import { isPromiseLike, sleepBreakIf, unsharedSlice } from "./util.mjs"; +import { getRights } from "./rights.mjs"; +import { extendMemory } from "../memory.mjs"; +import { wrapAsyncImport } from "../jspi.mjs"; +function copyMemory(targets, src) { + if (targets.length === 0 || src.length === 0) + return 0; + let copied = 0; + let left = src.length - copied; + for (let i = 0; i < targets.length; ++i) { + const target = targets[i]; + if (left < target.length) { + target.set(src.subarray(copied, copied + left), 0); + copied += left; + left = 0; + return copied; + } + target.set(src.subarray(copied, copied + target.length), 0); + copied += target.length; + left -= target.length; + } + return copied; +} +const _memory = new WeakMap(); +const _wasi = new WeakMap(); +const _fs = new WeakMap(); +export function ensureMemoryFor(memory, end) { + let buffer = memory.buffer; + if (end > buffer.byteLength) { + memory.grow(0); + buffer = memory.buffer; + } + return buffer; +} +function getMemory(wasi, end = 0) { + const memory = _memory.get(wasi); + ensureMemoryFor(memory, end); + return memory; +} +function getFs(wasi) { + const fs = _fs.get(wasi); + if (!fs) + throw new Error('filesystem is unavailable'); + return fs; +} +function handleError(err) { + if (err instanceof WasiError) { + if (process.env.NODE_ENV !== 'production') { + console.warn(err); + } + return err.errno; + } + switch (err.code) { + case 'ENOENT': return WasiErrno.ENOENT; + case 'EBADF': return WasiErrno.EBADF; + case 'EINVAL': return WasiErrno.EINVAL; + case 'EPERM': return WasiErrno.EPERM; + case 'EPROTO': return WasiErrno.EPROTO; + case 'EEXIST': return WasiErrno.EEXIST; + case 'ENOTDIR': return WasiErrno.ENOTDIR; + case 'EMFILE': return WasiErrno.EMFILE; + case 'EACCES': return WasiErrno.EACCES; + case 'EISDIR': return WasiErrno.EISDIR; + case 'ENOTEMPTY': return WasiErrno.ENOTEMPTY; + case 'ENOSYS': return WasiErrno.ENOSYS; + } + throw err; +} +function defineName(name, f) { + Object.defineProperty(f, 'name', { value: name }); + return f; +} +function tryCall(f, wasi, args) { + let r; + try { + r = f.apply(wasi, args); + } + catch (err) { + return handleError(err); + } + if (isPromiseLike(r)) { + return r.then(_ => _, handleError); + } + return r; +} +function syscallWrap(self, name, f) { + let debug = false; + const NODE_DEBUG_NATIVE = (() => { + try { + return process.env.NODE_DEBUG_NATIVE; + } + catch (_) { + return undefined; + } + })(); + if (typeof NODE_DEBUG_NATIVE === 'string' && NODE_DEBUG_NATIVE.split(',').includes('wasi')) { + debug = true; + } + return debug + ? defineName(name, function () { + const args = Array.prototype.slice.call(arguments); + let debugArgs = [`${name}(${Array.from({ length: arguments.length }).map(() => '%d').join(', ')})`]; + debugArgs = debugArgs.concat(args); + console.debug.apply(console, debugArgs); + return tryCall(f, self, args); + }) + : defineName(name, function () { + return tryCall(f, self, arguments); + }); +} +function resolvePathSync(fs, fileDescriptor, path, flags) { + let resolvedPath = resolve(fileDescriptor.realPath, path); + if ((flags & 1) === 1) { + try { + resolvedPath = fs.readlinkSync(resolvedPath); + } + catch (err) { + if (err.code !== 'EINVAL' && err.code !== 'ENOENT') { + throw err; + } + } + } + return resolvedPath; +} +async function resolvePathAsync(fs, fileDescriptor, path, flags) { + let resolvedPath = resolve(fileDescriptor.realPath, path); + if ((flags & 1) === 1) { + try { + resolvedPath = await fs.promises.readlink(resolvedPath); + } + catch (err) { + if (err.code !== 'EINVAL' && err.code !== 'ENOENT') { + throw err; + } + } + } + return resolvedPath; +} +// eslint-disable-next-line spaced-comment +const encoder = /*#__PURE__*/ new TextEncoder(); +// eslint-disable-next-line spaced-comment +const decoder = /*#__PURE__*/ new TextDecoder(); +const INT64_MAX = (BigInt(1) << BigInt(63)) - BigInt(1); +function readStdin() { + const value = window.prompt(); + if (value === null) + return new Uint8Array(); + const buffer = new TextEncoder().encode(value + '\n'); + return buffer; +} +function validateFstFlagsOrReturn(flags) { + return (Boolean((flags) & ~(WasiFstFlag.SET_ATIM | WasiFstFlag.SET_ATIM_NOW | + WasiFstFlag.SET_MTIM | WasiFstFlag.SET_MTIM_NOW)) || + ((flags) & (WasiFstFlag.SET_ATIM | WasiFstFlag.SET_ATIM_NOW)) === + (WasiFstFlag.SET_ATIM | WasiFstFlag.SET_ATIM_NOW) || + ((flags) & (WasiFstFlag.SET_MTIM | WasiFstFlag.SET_MTIM_NOW)) === + (WasiFstFlag.SET_MTIM | WasiFstFlag.SET_MTIM_NOW)); +} +export class WASI { + constructor(args, env, fds, asyncFs, fs, asyncify) { + this.args_get = syscallWrap(this, 'args_get', function (argv, argv_buf) { + argv = Number(argv); + argv_buf = Number(argv_buf); + if (argv === 0 || argv_buf === 0) { + return WasiErrno.EINVAL; + } + const wasi = _wasi.get(this); + const args = wasi.args; + const argsSize = encoder.encode(args.join('\0') + '\0').length; + const { HEAPU8, view } = getMemory(this, Math.max(argv + args.length * 4, argv_buf + argsSize)); + for (let i = 0; i < args.length; ++i) { + const arg = args[i]; + view.setInt32(argv, argv_buf, true); + argv += 4; + const data = encoder.encode(arg + '\0'); + HEAPU8.set(data, argv_buf); + argv_buf += data.length; + } + return WasiErrno.ESUCCESS; + }); + this.args_sizes_get = syscallWrap(this, 'args_sizes_get', function (argc, argv_buf_size) { + argc = Number(argc); + argv_buf_size = Number(argv_buf_size); + if (argc === 0 || argv_buf_size === 0) { + return WasiErrno.EINVAL; + } + const { view } = getMemory(this, Math.max(argc + 4, argv_buf_size + 4)); + const wasi = _wasi.get(this); + const args = wasi.args; + view.setUint32(argc, args.length, true); + view.setUint32(argv_buf_size, encoder.encode(args.join('\0') + '\0').length, true); + return WasiErrno.ESUCCESS; + }); + this.environ_get = syscallWrap(this, 'environ_get', function (environ, environ_buf) { + environ = Number(environ); + environ_buf = Number(environ_buf); + if (environ === 0 || environ_buf === 0) { + return WasiErrno.EINVAL; + } + const wasi = _wasi.get(this); + const env = wasi.env; + const envSize = encoder.encode(env.join('\0') + '\0').length; + const { HEAPU8, view } = getMemory(this, Math.max(environ + env.length * 4, environ_buf + envSize)); + for (let i = 0; i < env.length; ++i) { + const pair = env[i]; + view.setInt32(environ, environ_buf, true); + environ += 4; + const data = encoder.encode(pair + '\0'); + HEAPU8.set(data, environ_buf); + environ_buf += data.length; + } + return WasiErrno.ESUCCESS; + }); + this.environ_sizes_get = syscallWrap(this, 'environ_sizes_get', function (len, buflen) { + len = Number(len); + buflen = Number(buflen); + if (len === 0 || buflen === 0) { + return WasiErrno.EINVAL; + } + const { view } = getMemory(this, Math.max(len + 4, buflen + 4)); + const wasi = _wasi.get(this); + view.setUint32(len, wasi.env.length, true); + view.setUint32(buflen, encoder.encode(wasi.env.join('\0') + '\0').length, true); + return WasiErrno.ESUCCESS; + }); + this.clock_res_get = syscallWrap(this, 'clock_res_get', function (id, resolution) { + resolution = Number(resolution); + if (resolution === 0) { + return WasiErrno.EINVAL; + } + const { view } = getMemory(this, resolution + 8); + switch (id) { + case WasiClockid.REALTIME: + view.setBigUint64(resolution, BigInt(1000000), true); + return WasiErrno.ESUCCESS; + case WasiClockid.MONOTONIC: + case WasiClockid.PROCESS_CPUTIME_ID: + case WasiClockid.THREAD_CPUTIME_ID: + view.setBigUint64(resolution, BigInt(1000), true); + return WasiErrno.ESUCCESS; + default: return WasiErrno.EINVAL; + } + }); + this.clock_time_get = syscallWrap(this, 'clock_time_get', function (id, _percision, time) { + time = Number(time); + if (time === 0) { + return WasiErrno.EINVAL; + } + const { view } = getMemory(this, time + 8); + switch (id) { + case WasiClockid.REALTIME: + view.setBigUint64(time, BigInt(Date.now()) * BigInt(1000000), true); + return WasiErrno.ESUCCESS; + case WasiClockid.MONOTONIC: + case WasiClockid.PROCESS_CPUTIME_ID: + case WasiClockid.THREAD_CPUTIME_ID: { + const t = performance.now() / 1000; + const s = Math.trunc(t); + const ms = Math.floor((t - s) * 1000); + const result = BigInt(s) * BigInt(1000000000) + BigInt(ms) * BigInt(1000000); + view.setBigUint64(time, result, true); + return WasiErrno.ESUCCESS; + } + default: return WasiErrno.EINVAL; + } + }); + this.fd_advise = syscallWrap(this, 'fd_advise', function (_fd, _offset, _len, _advice) { + return WasiErrno.ENOSYS; + }); + this.fd_fdstat_get = syscallWrap(this, 'fd_fdstat_get', function (fd, fdstat) { + fdstat = Number(fdstat); + if (fdstat === 0) { + return WasiErrno.EINVAL; + } + const wasi = _wasi.get(this); + const fileDescriptor = wasi.fds.get(fd, BigInt(0), BigInt(0)); + const { view } = getMemory(this, fdstat + 24); + view.setUint16(fdstat, fileDescriptor.type, true); + view.setUint16(fdstat + 2, 0, true); + view.setBigUint64(fdstat + 8, fileDescriptor.rightsBase, true); + view.setBigUint64(fdstat + 16, fileDescriptor.rightsInheriting, true); + return WasiErrno.ESUCCESS; + }); + this.fd_fdstat_set_flags = syscallWrap(this, 'fd_fdstat_set_flags', function (_fd, _flags) { + return WasiErrno.ENOSYS; + }); + this.fd_fdstat_set_rights = syscallWrap(this, 'fd_fdstat_set_rights', function (fd, rightsBase, rightsInheriting) { + const wasi = _wasi.get(this); + const fileDescriptor = wasi.fds.get(fd, BigInt(0), BigInt(0)); + if ((rightsBase | fileDescriptor.rightsBase) > fileDescriptor.rightsBase) { + return WasiErrno.ENOTCAPABLE; + } + if ((rightsInheriting | fileDescriptor.rightsInheriting) > + fileDescriptor.rightsInheriting) { + return WasiErrno.ENOTCAPABLE; + } + fileDescriptor.rightsBase = rightsBase; + fileDescriptor.rightsInheriting = rightsInheriting; + return WasiErrno.ESUCCESS; + }); + this.fd_prestat_get = syscallWrap(this, 'fd_prestat_get', function (fd, prestat) { + prestat = Number(prestat); + if (prestat === 0) { + return WasiErrno.EINVAL; + } + const wasi = _wasi.get(this); + let fileDescriptor; + try { + fileDescriptor = wasi.fds.get(fd, BigInt(0), BigInt(0)); + } + catch (err) { + if (err instanceof WasiError) + return err.errno; + throw err; + } + if (fileDescriptor.preopen !== 1) + return WasiErrno.EINVAL; + const { view } = getMemory(this, prestat + 8); + // preopen type is dir(0) + view.setUint32(prestat, 0, true); + view.setUint32(prestat + 4, encoder.encode(fileDescriptor.path).length, true); + return WasiErrno.ESUCCESS; + }); + this.fd_prestat_dir_name = syscallWrap(this, 'fd_prestat_dir_name', function (fd, path, path_len) { + path = Number(path); + path_len = Number(path_len); + if (path === 0) { + return WasiErrno.EINVAL; + } + const wasi = _wasi.get(this); + const fileDescriptor = wasi.fds.get(fd, BigInt(0), BigInt(0)); + if (fileDescriptor.preopen !== 1) + return WasiErrno.EBADF; + const buffer = encoder.encode(fileDescriptor.path); + const size = buffer.length; + if (size > path_len) + return WasiErrno.ENOBUFS; + const { HEAPU8 } = getMemory(this, path + size); + HEAPU8.set(buffer, path); + return WasiErrno.ESUCCESS; + }); + this.fd_seek = syscallWrap(this, 'fd_seek', function (fd, offset, whence, newOffset) { + newOffset = Number(newOffset); + if (newOffset === 0) { + return WasiErrno.EINVAL; + } + if (fd === 0 || fd === 1 || fd === 2) + return WasiErrno.ESUCCESS; + const wasi = _wasi.get(this); + const fileDescriptor = wasi.fds.get(fd, WasiRights.FD_SEEK, BigInt(0)); + const r = fileDescriptor.seek(offset, whence); + const { view } = getMemory(this, newOffset + 8); + view.setBigUint64(newOffset, r, true); + return WasiErrno.ESUCCESS; + }); + this.fd_tell = syscallWrap(this, 'fd_tell', function (fd, offset) { + const wasi = _wasi.get(this); + const fileDescriptor = wasi.fds.get(fd, WasiRights.FD_TELL, BigInt(0)); + const pos = BigInt(fileDescriptor.pos); + const { view } = getMemory(this, Number(offset) + 8); + view.setBigUint64(Number(offset), pos, true); + return WasiErrno.ESUCCESS; + }); + this.poll_oneoff = syscallWrap(this, 'poll_oneoff', function (in_ptr, out_ptr, nsubscriptions, nevents) { + in_ptr = Number(in_ptr); + out_ptr = Number(out_ptr); + nevents = Number(nevents); + nsubscriptions = Number(nsubscriptions); + nsubscriptions = nsubscriptions >>> 0; + if (in_ptr === 0 || out_ptr === 0 || nsubscriptions === 0 || nevents === 0) { + return WasiErrno.EINVAL; + } + const { view } = getMemory(this, Math.max(in_ptr + nsubscriptions * 48, out_ptr + nsubscriptions * 32, nevents + 4)); + view.setUint32(nevents, 0, true); + let i = 0; + let timer_userdata = BigInt(0); + let cur_timeout = BigInt(0); + let has_timeout = 0; + let min_timeout = BigInt(0); + let sub; + const subscriptions = Array(nsubscriptions); + for (i = 0; i < nsubscriptions; i++) { + sub = in_ptr + i * 48; + const userdata = view.getBigUint64(sub, true); + const type = view.getUint8(sub + 8); + const clockIdOrFd = view.getUint32(sub + 16, true); + const timeout = view.getBigUint64(sub + 24, true); + const precision = view.getBigUint64(sub + 32, true); + const flags = view.getUint16(sub + 40, true); + subscriptions[i] = { + userdata, + type, + u: { + clock: { + clock_id: clockIdOrFd, + timeout, + precision, + flags + }, + fd_readwrite: { + fd: clockIdOrFd + } + } + }; + } + const fdevents = []; + for (i = 0; i < nsubscriptions; i++) { + sub = subscriptions[i]; + switch (sub.type) { + case WasiEventType.CLOCK: { + if (sub.u.clock.flags === WasiSubclockflags.ABSTIME) { + /* Convert absolute time to relative delay. */ + const now = BigInt(Date.now()) * BigInt(1000000); + cur_timeout = sub.u.clock.timeout - now; + } + else { + cur_timeout = sub.u.clock.timeout; + } + if (has_timeout === 0 || cur_timeout < min_timeout) { + min_timeout = cur_timeout; + timer_userdata = sub.userdata; + has_timeout = 1; + } + break; + } + case WasiEventType.FD_READ: + case WasiEventType.FD_WRITE: + fdevents.push(sub); + break; + default: return WasiErrno.EINVAL; + } + } + if (fdevents.length > 0) { + for (i = 0; i < fdevents.length; i++) { + const fdevent = fdevents[i]; + const event = out_ptr + 32 * i; + view.setBigUint64(event, fdevent.userdata, true); + view.setUint32(event + 8, WasiErrno.ENOSYS, true); + view.setUint32(event + 12, fdevent.type, true); + view.setBigUint64(event + 16, BigInt(0), true); + view.setUint16(event + 24, 0, true); + view.setUint32(nevents, 1, true); + } + view.setUint32(nevents, fdevents.length, true); + return WasiErrno.ESUCCESS; + } + if (has_timeout) { + const delay = Number(min_timeout / BigInt(1000000)); + // if (isMainThread || typeof SharedArrayBuffer !== 'function') { + sleepBreakIf(delay, () => false); + // } else { + // const buf = new SharedArrayBuffer(4) + // const arr = new Int32Array(buf) + // postMsg({ + // __tybys_wasm_util_wasi__: { + // type: 'set-timeout', + // payload: { + // buffer: buf, + // delay + // } + // } + // }) + // Atomics.wait(arr, 0, 0) + // } + const event = out_ptr; + view.setBigUint64(event, timer_userdata, true); + view.setUint32(event + 8, WasiErrno.ESUCCESS, true); + view.setUint32(event + 12, WasiEventType.CLOCK, true); + view.setUint32(nevents, 1, true); + } + return WasiErrno.ESUCCESS; + }); + this.proc_exit = syscallWrap(this, 'proc_exit', function (rval) { + if ((typeof process === 'object') && (process !== null) && (typeof process.exit === 'function')) { + process.exit(rval); + } + return WasiErrno.ESUCCESS; + }); + this.proc_raise = syscallWrap(this, 'proc_raise', function (_sig) { + return WasiErrno.ENOSYS; + }); + this.sched_yield = syscallWrap(this, 'sched_yield', function () { + return WasiErrno.ESUCCESS; + }); + this.random_get = typeof crypto !== 'undefined' && typeof crypto.getRandomValues === 'function' + ? syscallWrap(this, 'random_get', function (buf, buf_len) { + buf = Number(buf); + if (buf === 0) { + return WasiErrno.EINVAL; + } + buf_len = Number(buf_len); + const { HEAPU8, view } = getMemory(this, buf + buf_len); + if ((typeof SharedArrayBuffer === 'function' && HEAPU8.buffer instanceof SharedArrayBuffer) || + (Object.prototype.toString.call(HEAPU8.buffer) === '[object SharedArrayBuffer]')) { + for (let i = buf; i < buf + buf_len; ++i) { + view.setUint8(i, Math.floor(Math.random() * 256)); + } + return WasiErrno.ESUCCESS; + } + let pos; + const stride = 65536; + for (pos = 0; pos + stride < buf_len; pos += stride) { + crypto.getRandomValues(HEAPU8.subarray(buf + pos, buf + pos + stride)); + } + crypto.getRandomValues(HEAPU8.subarray(buf + pos, buf + buf_len)); + return WasiErrno.ESUCCESS; + }) + : syscallWrap(this, 'random_get', function (buf, buf_len) { + buf = Number(buf); + if (buf === 0) { + return WasiErrno.EINVAL; + } + buf_len = Number(buf_len); + const { view } = getMemory(this, buf + buf_len); + for (let i = buf; i < buf + buf_len; ++i) { + view.setUint8(i, Math.floor(Math.random() * 256)); + } + return WasiErrno.ESUCCESS; + }); + this.sock_recv = syscallWrap(this, 'sock_recv', function () { + return WasiErrno.ENOTSUP; + }); + this.sock_send = syscallWrap(this, 'sock_send', function () { + return WasiErrno.ENOTSUP; + }); + this.sock_shutdown = syscallWrap(this, 'sock_shutdown', function () { + return WasiErrno.ENOTSUP; + }); + this.sock_accept = syscallWrap(this, 'sock_accept', function () { + return WasiErrno.ENOTSUP; + }); + _wasi.set(this, { + fds, + args, + env + }); + if (fs) + _fs.set(this, fs); + // eslint-disable-next-line @typescript-eslint/no-this-alias + const _this = this; + function defineImport(name, syncVersion, asyncVersion, parameterType, returnType) { + if (asyncFs) { + if (asyncify) { + _this[name] = asyncify.wrapImportFunction(syscallWrap(_this, name, asyncVersion)); + } + else { + _this[name] = wrapAsyncImport(syscallWrap(_this, name, asyncVersion), parameterType, returnType); + } + } + else { + _this[name] = syscallWrap(_this, name, syncVersion); + } + } + defineImport('fd_allocate', function fd_allocate(fd, offset, len) { + const wasi = _wasi.get(this); + const fs = getFs(this); + const fileDescriptor = wasi.fds.get(fd, WasiRights.FD_ALLOCATE, BigInt(0)); + const stat = fs.fstatSync(fileDescriptor.fd, { bigint: true }); + if (stat.size < offset + len) { + fs.ftruncateSync(fileDescriptor.fd, Number(offset + len)); + } + return WasiErrno.ESUCCESS; + }, async function fd_allocate(fd, offset, len) { + const wasi = _wasi.get(this); + const fileDescriptor = wasi.fds.get(fd, WasiRights.FD_ALLOCATE, BigInt(0)); + const h = fileDescriptor.fd; + const stat = await h.stat({ bigint: true }); + if (stat.size < offset + len) { + await h.truncate(Number(offset + len)); + } + return WasiErrno.ESUCCESS; + }, ['i32', 'i64', 'f64'], ['i32']); + defineImport('fd_close', function fd_close(fd) { + const wasi = _wasi.get(this); + const fileDescriptor = wasi.fds.get(fd, BigInt(0), BigInt(0)); + const fs = getFs(this); + fs.closeSync(fileDescriptor.fd); + wasi.fds.remove(fd); + return WasiErrno.ESUCCESS; + }, async function fd_close(fd) { + const wasi = _wasi.get(this); + const fileDescriptor = wasi.fds.get(fd, BigInt(0), BigInt(0)); + await fileDescriptor.fd.close(); + wasi.fds.remove(fd); + return WasiErrno.ESUCCESS; + }, ['i32'], ['i32']); + defineImport('fd_datasync', function fd_datasync(fd) { + const wasi = _wasi.get(this); + const fileDescriptor = wasi.fds.get(fd, WasiRights.FD_DATASYNC, BigInt(0)); + const fs = getFs(this); + fs.fdatasyncSync(fileDescriptor.fd); + return WasiErrno.ESUCCESS; + }, async function fd_datasync(fd) { + const wasi = _wasi.get(this); + const fileDescriptor = wasi.fds.get(fd, WasiRights.FD_DATASYNC, BigInt(0)); + await fileDescriptor.fd.datasync(); + return WasiErrno.ESUCCESS; + }, ['i32'], ['i32']); + defineImport('fd_filestat_get', function fd_filestat_get(fd, buf) { + buf = Number(buf); + if (buf === 0) + return WasiErrno.EINVAL; + const wasi = _wasi.get(this); + const fileDescriptor = wasi.fds.get(fd, WasiRights.FD_FILESTAT_GET, BigInt(0)); + const fs = getFs(this); + const stat = fs.fstatSync(fileDescriptor.fd, { bigint: true }); + const { view } = getMemory(this, buf + 64); + toFileStat(view, buf, stat); + return WasiErrno.ESUCCESS; + }, async function fd_filestat_get(fd, buf) { + buf = Number(buf); + if (buf === 0) + return WasiErrno.EINVAL; + const wasi = _wasi.get(this); + const fileDescriptor = wasi.fds.get(fd, WasiRights.FD_FILESTAT_GET, BigInt(0)); + const h = fileDescriptor.fd; + const stat = await h.stat({ bigint: true }); + const { view } = getMemory(this, buf + 64); + toFileStat(view, buf, stat); + return WasiErrno.ESUCCESS; + }, ['i32', 'i32'], ['i32']); + defineImport('fd_filestat_set_size', function fd_filestat_set_size(fd, size) { + const wasi = _wasi.get(this); + const fileDescriptor = wasi.fds.get(fd, WasiRights.FD_FILESTAT_SET_SIZE, BigInt(0)); + const fs = getFs(this); + fs.ftruncateSync(fileDescriptor.fd, Number(size)); + return WasiErrno.ESUCCESS; + }, async function fd_filestat_set_size(fd, size) { + const wasi = _wasi.get(this); + const fileDescriptor = wasi.fds.get(fd, WasiRights.FD_FILESTAT_SET_SIZE, BigInt(0)); + const h = fileDescriptor.fd; + await h.truncate(Number(size)); + return WasiErrno.ESUCCESS; + }, ['i32', 'i64'], ['i32']); + function fdFilestatGetTimes(fd, atim, mtim, flags) { + const wasi = _wasi.get(this); + const fileDescriptor = wasi.fds.get(fd, WasiRights.FD_FILESTAT_SET_TIMES, BigInt(0)); + if ((flags & WasiFstFlag.SET_ATIM_NOW) === WasiFstFlag.SET_ATIM_NOW) { + atim = BigInt(Date.now() * 1000000); + } + if ((flags & WasiFstFlag.SET_MTIM_NOW) === WasiFstFlag.SET_MTIM_NOW) { + mtim = BigInt(Date.now() * 1000000); + } + return { fileDescriptor, atim, mtim }; + } + defineImport('fd_filestat_set_times', function fd_filestat_set_times(fd, atim, mtim, flags) { + if (validateFstFlagsOrReturn(flags)) { + return WasiErrno.EINVAL; + } + const { fileDescriptor, atim: atimRes, mtim: mtimRes } = fdFilestatGetTimes.call(this, fd, atim, mtim, flags); + const fs = getFs(this); + fs.futimesSync(fileDescriptor.fd, Number(atimRes), Number(mtimRes)); + return WasiErrno.ESUCCESS; + }, async function fd_filestat_set_times(fd, atim, mtim, flags) { + if (validateFstFlagsOrReturn(flags)) { + return WasiErrno.EINVAL; + } + const { fileDescriptor, atim: atimRes, mtim: mtimRes } = fdFilestatGetTimes.call(this, fd, atim, mtim, flags); + const h = fileDescriptor.fd; + await h.utimes(Number(atimRes), Number(mtimRes)); + return WasiErrno.ESUCCESS; + }, ['i32', 'i64', 'i64', 'i32'], ['i32']); + defineImport('fd_pread', function fd_pread(fd, iovs, iovslen, offset, size) { + iovs = Number(iovs); + size = Number(size); + if ((iovs === 0 && iovslen) || size === 0 || offset > INT64_MAX) { + return WasiErrno.EINVAL; + } + const { HEAPU8, view } = getMemory(this, Math.max(iovs + Number(iovslen) * 8, size + 4)); + const wasi = _wasi.get(this); + const fileDescriptor = wasi.fds.get(fd, WasiRights.FD_READ | WasiRights.FD_SEEK, BigInt(0)); + if (!iovslen) { + view.setUint32(size, 0, true); + return WasiErrno.ESUCCESS; + } + let totalSize = 0; + const ioVecs = Array.from({ length: Number(iovslen) }, (_, i) => { + const offset = iovs + (i * 8); + const buf = view.getInt32(offset, true); + const bufLen = view.getUint32(offset + 4, true); + totalSize += bufLen; + return HEAPU8.subarray(buf, buf + bufLen); + }); + let nread = 0; + const buffer = (() => { + try { + return new Uint8Array(new SharedArrayBuffer(totalSize)); + } + catch (_) { + return new Uint8Array(totalSize); + } + })(); + buffer._isBuffer = true; + const fs = getFs(this); + const bytesRead = fs.readSync(fileDescriptor.fd, buffer, 0, buffer.length, Number(offset)); + nread = buffer ? copyMemory(ioVecs, buffer.subarray(0, bytesRead)) : 0; + view.setUint32(size, nread, true); + return WasiErrno.ESUCCESS; + }, async function (fd, iovs, iovslen, offset, size) { + iovs = Number(iovs); + size = Number(size); + if ((iovs === 0 && iovslen) || size === 0 || offset > INT64_MAX) { + return WasiErrno.EINVAL; + } + const { HEAPU8, view } = getMemory(this, Math.max(iovs + Number(iovslen) * 8, size + 4)); + const wasi = _wasi.get(this); + const fileDescriptor = wasi.fds.get(fd, WasiRights.FD_READ | WasiRights.FD_SEEK, BigInt(0)); + if (!iovslen) { + view.setUint32(size, 0, true); + return WasiErrno.ESUCCESS; + } + let totalSize = 0; + const ioVecs = Array.from({ length: Number(iovslen) }, (_, i) => { + const offset = iovs + (i * 8); + const buf = view.getInt32(offset, true); + const bufLen = view.getUint32(offset + 4, true); + totalSize += bufLen; + return HEAPU8.subarray(buf, buf + bufLen); + }); + let nread = 0; + const buffer = new Uint8Array(totalSize); + buffer._isBuffer = true; + const { bytesRead } = await fileDescriptor.fd.read(buffer, 0, buffer.length, Number(offset)); + nread = buffer ? copyMemory(ioVecs, buffer.subarray(0, bytesRead)) : 0; + view.setUint32(size, nread, true); + return WasiErrno.ESUCCESS; + }, ['i32', 'i32', 'i32', 'i64', 'i32'], ['i32']); + defineImport('fd_pwrite', function fd_pwrite(fd, iovs, iovslen, offset, size) { + iovs = Number(iovs); + size = Number(size); + if ((iovs === 0 && iovslen) || size === 0 || offset > INT64_MAX) { + return WasiErrno.EINVAL; + } + const { HEAPU8, view } = getMemory(this, Math.max(iovs + Number(iovslen) * 8, size + 4)); + const wasi = _wasi.get(this); + const fileDescriptor = wasi.fds.get(fd, WasiRights.FD_WRITE | WasiRights.FD_SEEK, BigInt(0)); + if (!iovslen) { + view.setUint32(size, 0, true); + return WasiErrno.ESUCCESS; + } + const buffer = concatBuffer(Array.from({ length: Number(iovslen) }, (_, i) => { + const offset = iovs + (i * 8); + const buf = view.getInt32(offset, true); + const bufLen = view.getUint32(offset + 4, true); + return HEAPU8.subarray(buf, buf + bufLen); + })); + const fs = getFs(this); + const nwritten = fs.writeSync(fileDescriptor.fd, buffer, 0, buffer.length, Number(offset)); + view.setUint32(size, nwritten, true); + return WasiErrno.ESUCCESS; + }, async function fd_pwrite(fd, iovs, iovslen, offset, size) { + iovs = Number(iovs); + size = Number(size); + if ((iovs === 0 && iovslen) || size === 0 || offset > INT64_MAX) { + return WasiErrno.EINVAL; + } + const { HEAPU8, view } = getMemory(this, Math.max(iovs + Number(iovslen) * 8, size + 4)); + const wasi = _wasi.get(this); + const fileDescriptor = wasi.fds.get(fd, WasiRights.FD_WRITE | WasiRights.FD_SEEK, BigInt(0)); + if (!iovslen) { + view.setUint32(size, 0, true); + return WasiErrno.ESUCCESS; + } + const buffer = concatBuffer(Array.from({ length: Number(iovslen) }, (_, i) => { + const offset = iovs + (i * 8); + const buf = view.getInt32(offset, true); + const bufLen = view.getUint32(offset + 4, true); + return HEAPU8.subarray(buf, buf + bufLen); + })); + const { bytesWritten } = await fileDescriptor.fd.write(buffer, 0, buffer.length, Number(offset)); + view.setUint32(size, bytesWritten, true); + return WasiErrno.ESUCCESS; + }, ['i32', 'i32', 'i32', 'i64', 'i32'], ['i32']); + defineImport('fd_read', function fd_read(fd, iovs, iovslen, size) { + iovs = Number(iovs); + size = Number(size); + if ((iovs === 0 && iovslen) || size === 0) { + return WasiErrno.EINVAL; + } + const { HEAPU8, view } = getMemory(this, Math.max(iovs + Number(iovslen) * 8, size + 4)); + const wasi = _wasi.get(this); + const fileDescriptor = wasi.fds.get(fd, WasiRights.FD_READ, BigInt(0)); + if (!iovslen) { + view.setUint32(size, 0, true); + return WasiErrno.ESUCCESS; + } + let totalSize = 0; + const ioVecs = Array.from({ length: Number(iovslen) }, (_, i) => { + const offset = iovs + (i * 8); + const buf = view.getInt32(offset, true); + const bufLen = view.getUint32(offset + 4, true); + totalSize += bufLen; + return HEAPU8.subarray(buf, buf + bufLen); + }); + let buffer; + let nread = 0; + if (fd === 0) { + if (typeof window === 'undefined' || typeof window.prompt !== 'function') { + return WasiErrno.ENOTSUP; + } + buffer = readStdin(); + nread = buffer ? copyMemory(ioVecs, buffer) : 0; + } + else { + buffer = (() => { + try { + return new Uint8Array(new SharedArrayBuffer(totalSize)); + } + catch (_) { + return new Uint8Array(totalSize); + } + })(); + buffer._isBuffer = true; + const fs = getFs(this); + const bytesRead = fs.readSync(fileDescriptor.fd, buffer, 0, buffer.length, Number(fileDescriptor.pos)); + nread = buffer ? copyMemory(ioVecs, buffer.subarray(0, bytesRead)) : 0; + fileDescriptor.pos += BigInt(nread); + } + view.setUint32(size, nread, true); + return WasiErrno.ESUCCESS; + }, async function fd_read(fd, iovs, iovslen, size) { + iovs = Number(iovs); + size = Number(size); + if ((iovs === 0 && iovslen) || size === 0) { + return WasiErrno.EINVAL; + } + const { HEAPU8, view } = getMemory(this, Math.max(iovs + Number(iovslen) * 8, size + 4)); + const wasi = _wasi.get(this); + const fileDescriptor = wasi.fds.get(fd, WasiRights.FD_READ, BigInt(0)); + if (!iovslen) { + view.setUint32(size, 0, true); + return WasiErrno.ESUCCESS; + } + let totalSize = 0; + const ioVecs = Array.from({ length: Number(iovslen) }, (_, i) => { + const offset = iovs + (i * 8); + const buf = view.getInt32(offset, true); + const bufLen = view.getUint32(offset + 4, true); + totalSize += bufLen; + return HEAPU8.subarray(buf, buf + bufLen); + }); + let buffer; + let nread = 0; + if (fd === 0) { + if (typeof window === 'undefined' || typeof window.prompt !== 'function') { + return WasiErrno.ENOTSUP; + } + buffer = readStdin(); + nread = buffer ? copyMemory(ioVecs, buffer) : 0; + } + else { + buffer = new Uint8Array(totalSize); + buffer._isBuffer = true; + const { bytesRead } = await fileDescriptor.fd.read(buffer, 0, buffer.length, Number(fileDescriptor.pos)); + nread = buffer ? copyMemory(ioVecs, buffer.subarray(0, bytesRead)) : 0; + fileDescriptor.pos += BigInt(nread); + } + view.setUint32(size, nread, true); + return WasiErrno.ESUCCESS; + }, ['i32', 'i32', 'i32', 'i32'], ['i32']); + defineImport('fd_readdir', function fd_readdir(fd, buf, buf_len, cookie, bufused) { + buf = Number(buf); + buf_len = Number(buf_len); + bufused = Number(bufused); + if (buf === 0 || bufused === 0) + return WasiErrno.ESUCCESS; + const wasi = _wasi.get(this); + const fileDescriptor = wasi.fds.get(fd, WasiRights.FD_READDIR, BigInt(0)); + const fs = getFs(this); + const entries = fs.readdirSync(fileDescriptor.realPath, { withFileTypes: true }); + const { HEAPU8, view } = getMemory(this, Math.max(buf + buf_len, bufused + 4)); + let bufferUsed = 0; + for (let i = Number(cookie); i < entries.length; i++) { + const nameData = encoder.encode(entries[i].name); + const entryInfo = fs.statSync(resolve(fileDescriptor.realPath, entries[i].name), { bigint: true }); + const entryData = new Uint8Array(24 + nameData.byteLength); + const entryView = new DataView(entryData.buffer); + entryView.setBigUint64(0, BigInt(i + 1), true); + entryView.setBigUint64(8, BigInt(entryInfo.ino ? entryInfo.ino : 0), true); + entryView.setUint32(16, nameData.byteLength, true); + let type; + if (entries[i].isFile()) { + type = WasiFileType.REGULAR_FILE; + } + else if (entries[i].isDirectory()) { + type = WasiFileType.DIRECTORY; + } + else if (entries[i].isSymbolicLink()) { + type = WasiFileType.SYMBOLIC_LINK; + } + else if (entries[i].isCharacterDevice()) { + type = WasiFileType.CHARACTER_DEVICE; + } + else if (entries[i].isBlockDevice()) { + type = WasiFileType.BLOCK_DEVICE; + } + else if (entries[i].isSocket()) { + type = WasiFileType.SOCKET_STREAM; + } + else { + type = WasiFileType.UNKNOWN; + } + entryView.setUint8(20, type); + entryData.set(nameData, 24); + const data = entryData.slice(0, Math.min(entryData.length, buf_len - bufferUsed)); + HEAPU8.set(data, buf + bufferUsed); + bufferUsed += data.byteLength; + } + view.setUint32(bufused, bufferUsed, true); + return WasiErrno.ESUCCESS; + }, async function fd_readdir(fd, buf, buf_len, cookie, bufused) { + buf = Number(buf); + buf_len = Number(buf_len); + bufused = Number(bufused); + if (buf === 0 || bufused === 0) + return WasiErrno.ESUCCESS; + const wasi = _wasi.get(this); + const fileDescriptor = wasi.fds.get(fd, WasiRights.FD_READDIR, BigInt(0)); + const fs = getFs(this); + const entries = await fs.promises.readdir(fileDescriptor.realPath, { withFileTypes: true }); + const { HEAPU8, view } = getMemory(this, Math.max(buf + buf_len, bufused + 4)); + let bufferUsed = 0; + for (let i = Number(cookie); i < entries.length; i++) { + const nameData = encoder.encode(entries[i].name); + const entryInfo = await fs.promises.stat(resolve(fileDescriptor.realPath, entries[i].name), { bigint: true }); + const entryData = new Uint8Array(24 + nameData.byteLength); + const entryView = new DataView(entryData.buffer); + entryView.setBigUint64(0, BigInt(i + 1), true); + entryView.setBigUint64(8, BigInt(entryInfo.ino ? entryInfo.ino : 0), true); + entryView.setUint32(16, nameData.byteLength, true); + let type; + if (entries[i].isFile()) { + type = WasiFileType.REGULAR_FILE; + } + else if (entries[i].isDirectory()) { + type = WasiFileType.DIRECTORY; + } + else if (entries[i].isSymbolicLink()) { + type = WasiFileType.SYMBOLIC_LINK; + } + else if (entries[i].isCharacterDevice()) { + type = WasiFileType.CHARACTER_DEVICE; + } + else if (entries[i].isBlockDevice()) { + type = WasiFileType.BLOCK_DEVICE; + } + else if (entries[i].isSocket()) { + type = WasiFileType.SOCKET_STREAM; + } + else { + type = WasiFileType.UNKNOWN; + } + entryView.setUint8(20, type); + entryData.set(nameData, 24); + const data = entryData.slice(0, Math.min(entryData.length, buf_len - bufferUsed)); + HEAPU8.set(data, buf + bufferUsed); + bufferUsed += data.byteLength; + } + view.setUint32(bufused, bufferUsed, true); + return WasiErrno.ESUCCESS; + }, ['i32', 'i32', 'i32', 'i64', 'i32'], ['i32']); + defineImport('fd_renumber', function fd_renumber(from, to) { + const wasi = _wasi.get(this); + wasi.fds.renumber(to, from); + return WasiErrno.ESUCCESS; + }, async function fd_renumber(from, to) { + const wasi = _wasi.get(this); + await wasi.fds.renumber(to, from); + return WasiErrno.ESUCCESS; + }, ['i32', 'i32'], ['i32']); + defineImport('fd_sync', function fd_sync(fd) { + const wasi = _wasi.get(this); + const fileDescriptor = wasi.fds.get(fd, WasiRights.FD_SYNC, BigInt(0)); + const fs = getFs(this); + fs.fsyncSync(fileDescriptor.fd); + return WasiErrno.ESUCCESS; + }, async function fd_sync(fd) { + const wasi = _wasi.get(this); + const fileDescriptor = wasi.fds.get(fd, WasiRights.FD_SYNC, BigInt(0)); + await fileDescriptor.fd.sync(); + return WasiErrno.ESUCCESS; + }, ['i32'], ['i32']); + defineImport('fd_write', function fd_write(fd, iovs, iovslen, size) { + iovs = Number(iovs); + size = Number(size); + if ((iovs === 0 && iovslen) || size === 0) { + return WasiErrno.EINVAL; + } + const { HEAPU8, view } = getMemory(this, Math.max(iovs + Number(iovslen) * 8, size + 4)); + const wasi = _wasi.get(this); + const fileDescriptor = wasi.fds.get(fd, WasiRights.FD_WRITE, BigInt(0)); + if (!iovslen) { + view.setUint32(size, 0, true); + return WasiErrno.ESUCCESS; + } + const buffer = concatBuffer(Array.from({ length: Number(iovslen) }, (_, i) => { + const offset = iovs + (i * 8); + const buf = view.getInt32(offset, true); + const bufLen = view.getUint32(offset + 4, true); + return HEAPU8.subarray(buf, buf + bufLen); + })); + let nwritten; + if (fd === 1 || fd === 2) { + nwritten = fileDescriptor.write(buffer); + } + else { + const fs = getFs(this); + nwritten = fs.writeSync(fileDescriptor.fd, buffer, 0, buffer.length, Number(fileDescriptor.pos)); + fileDescriptor.pos += BigInt(nwritten); + } + view.setUint32(size, nwritten, true); + return WasiErrno.ESUCCESS; + }, async function fd_write(fd, iovs, iovslen, size) { + iovs = Number(iovs); + size = Number(size); + if ((iovs === 0 && iovslen) || size === 0) { + return WasiErrno.EINVAL; + } + const { HEAPU8, view } = getMemory(this, Math.max(iovs + Number(iovslen) * 8, size + 4)); + const wasi = _wasi.get(this); + const fileDescriptor = wasi.fds.get(fd, WasiRights.FD_WRITE, BigInt(0)); + if (!iovslen) { + view.setUint32(size, 0, true); + return WasiErrno.ESUCCESS; + } + const buffer = concatBuffer(Array.from({ length: Number(iovslen) }, (_, i) => { + const offset = iovs + (i * 8); + const buf = view.getInt32(offset, true); + const bufLen = view.getUint32(offset + 4, true); + return HEAPU8.subarray(buf, buf + bufLen); + })); + let nwritten; + if (fd === 1 || fd === 2) { + nwritten = fileDescriptor.write(buffer); + } + else { + nwritten = await (await (fileDescriptor.fd.write(buffer, 0, buffer.length, Number(fileDescriptor.pos)))).bytesWritten; + fileDescriptor.pos += BigInt(nwritten); + } + view.setUint32(size, nwritten, true); + return WasiErrno.ESUCCESS; + }, ['i32', 'i32', 'i32', 'i32'], ['i32']); + defineImport('path_create_directory', function path_create_directory(fd, path, path_len) { + path = Number(path); + path_len = Number(path_len); + if (path === 0) { + return WasiErrno.EINVAL; + } + const { HEAPU8 } = getMemory(this, path + path_len); + const wasi = _wasi.get(this); + const fileDescriptor = wasi.fds.get(fd, WasiRights.PATH_CREATE_DIRECTORY, BigInt(0)); + let pathString = decoder.decode(unsharedSlice(HEAPU8, path, path + path_len)); + pathString = resolve(fileDescriptor.realPath, pathString); + const fs = getFs(this); + fs.mkdirSync(pathString); + return WasiErrno.ESUCCESS; + }, async function path_create_directory(fd, path, path_len) { + path = Number(path); + path_len = Number(path_len); + if (path === 0) { + return WasiErrno.EINVAL; + } + const { HEAPU8 } = getMemory(this, path + path_len); + const wasi = _wasi.get(this); + const fileDescriptor = wasi.fds.get(fd, WasiRights.PATH_CREATE_DIRECTORY, BigInt(0)); + let pathString = decoder.decode(unsharedSlice(HEAPU8, path, path + path_len)); + pathString = resolve(fileDescriptor.realPath, pathString); + const fs = getFs(this); + await fs.promises.mkdir(pathString); + return WasiErrno.ESUCCESS; + }, ['i32', 'i32', 'i32'], ['i32']); + defineImport('path_filestat_get', function path_filestat_get(fd, flags, path, path_len, filestat) { + path = Number(path); + path_len = Number(path_len); + filestat = Number(filestat); + if (path === 0 || filestat === 0) { + return WasiErrno.EINVAL; + } + const { HEAPU8, view } = getMemory(this, Math.max(path + path_len, filestat + 64)); + const wasi = _wasi.get(this); + const fileDescriptor = wasi.fds.get(fd, WasiRights.PATH_FILESTAT_GET, BigInt(0)); + let pathString = decoder.decode(unsharedSlice(HEAPU8, path, path + path_len)); + const fs = getFs(this); + pathString = resolve(fileDescriptor.realPath, pathString); + let stat; + if ((flags & 1) === 1) { + stat = fs.statSync(pathString, { bigint: true }); + } + else { + stat = fs.lstatSync(pathString, { bigint: true }); + } + toFileStat(view, filestat, stat); + return WasiErrno.ESUCCESS; + }, async function path_filestat_get(fd, flags, path, path_len, filestat) { + path = Number(path); + path_len = Number(path_len); + filestat = Number(filestat); + if (path === 0 || filestat === 0) { + return WasiErrno.EINVAL; + } + const { HEAPU8, view } = getMemory(this, Math.max(path + path_len, filestat + 64)); + const wasi = _wasi.get(this); + const fileDescriptor = wasi.fds.get(fd, WasiRights.PATH_FILESTAT_GET, BigInt(0)); + let pathString = decoder.decode(unsharedSlice(HEAPU8, path, path + path_len)); + const fs = getFs(this); + pathString = resolve(fileDescriptor.realPath, pathString); + let stat; + if ((flags & 1) === 1) { + stat = await fs.promises.stat(pathString, { bigint: true }); + } + else { + stat = await fs.promises.lstat(pathString, { bigint: true }); + } + toFileStat(view, filestat, stat); + return WasiErrno.ESUCCESS; + }, ['i32', 'i32', 'i32', 'i32', 'i32'], ['i32']); + defineImport('path_filestat_set_times', function path_filestat_set_times(fd, flags, path, path_len, atim, mtim, fst_flags) { + path = Number(path); + path_len = Number(path_len); + if (path === 0) + return WasiErrno.EINVAL; + const { HEAPU8 } = getMemory(this, path + path_len); + const wasi = _wasi.get(this); + const fileDescriptor = wasi.fds.get(fd, WasiRights.PATH_FILESTAT_SET_TIMES, BigInt(0)); + if (validateFstFlagsOrReturn(fst_flags)) { + return WasiErrno.EINVAL; + } + const fs = getFs(this); + const resolvedPath = resolvePathSync(fs, fileDescriptor, decoder.decode(unsharedSlice(HEAPU8, path, path + path_len)), flags); + if ((fst_flags & WasiFstFlag.SET_ATIM_NOW) === WasiFstFlag.SET_ATIM_NOW) { + atim = BigInt(Date.now() * 1000000); + } + if ((fst_flags & WasiFstFlag.SET_MTIM_NOW) === WasiFstFlag.SET_MTIM_NOW) { + mtim = BigInt(Date.now() * 1000000); + } + fs.utimesSync(resolvedPath, Number(atim), Number(mtim)); + return WasiErrno.ESUCCESS; + }, async function path_filestat_set_times(fd, flags, path, path_len, atim, mtim, fst_flags) { + path = Number(path); + path_len = Number(path_len); + if (path === 0) + return WasiErrno.EINVAL; + const { HEAPU8 } = getMemory(this, path + path_len); + const wasi = _wasi.get(this); + const fileDescriptor = wasi.fds.get(fd, WasiRights.PATH_FILESTAT_SET_TIMES, BigInt(0)); + if (validateFstFlagsOrReturn(fst_flags)) { + return WasiErrno.EINVAL; + } + const fs = getFs(this); + const resolvedPath = await resolvePathAsync(fs, fileDescriptor, decoder.decode(unsharedSlice(HEAPU8, path, path + path_len)), flags); + if ((fst_flags & WasiFstFlag.SET_ATIM_NOW) === WasiFstFlag.SET_ATIM_NOW) { + atim = BigInt(Date.now() * 1000000); + } + if ((fst_flags & WasiFstFlag.SET_MTIM_NOW) === WasiFstFlag.SET_MTIM_NOW) { + mtim = BigInt(Date.now() * 1000000); + } + await fs.promises.utimes(resolvedPath, Number(atim), Number(mtim)); + return WasiErrno.ESUCCESS; + }, ['i32', 'i32', 'i32', 'i32', 'i64', 'i64', 'i32'], ['i32']); + defineImport('path_link', function path_link(old_fd, old_flags, old_path, old_path_len, new_fd, new_path, new_path_len) { + old_path = Number(old_path); + old_path_len = Number(old_path_len); + new_path = Number(new_path); + new_path_len = Number(new_path_len); + if (old_path === 0 || new_path === 0) { + return WasiErrno.EINVAL; + } + const wasi = _wasi.get(this); + let oldWrap; + let newWrap; + if (old_fd === new_fd) { + oldWrap = newWrap = wasi.fds.get(old_fd, WasiRights.PATH_LINK_SOURCE | WasiRights.PATH_LINK_TARGET, BigInt(0)); + } + else { + oldWrap = wasi.fds.get(old_fd, WasiRights.PATH_LINK_SOURCE, BigInt(0)); + newWrap = wasi.fds.get(new_fd, WasiRights.PATH_LINK_TARGET, BigInt(0)); + } + const { HEAPU8 } = getMemory(this, Math.max(old_path + old_path_len, new_path + new_path_len)); + const fs = getFs(this); + const resolvedOldPath = resolvePathSync(fs, oldWrap, decoder.decode(unsharedSlice(HEAPU8, old_path, old_path + old_path_len)), old_flags); + const resolvedNewPath = resolve(newWrap.realPath, decoder.decode(unsharedSlice(HEAPU8, new_path, new_path + new_path_len))); + fs.linkSync(resolvedOldPath, resolvedNewPath); + return WasiErrno.ESUCCESS; + }, async function path_link(old_fd, old_flags, old_path, old_path_len, new_fd, new_path, new_path_len) { + old_path = Number(old_path); + old_path_len = Number(old_path_len); + new_path = Number(new_path); + new_path_len = Number(new_path_len); + if (old_path === 0 || new_path === 0) { + return WasiErrno.EINVAL; + } + const wasi = _wasi.get(this); + let oldWrap; + let newWrap; + if (old_fd === new_fd) { + oldWrap = newWrap = wasi.fds.get(old_fd, WasiRights.PATH_LINK_SOURCE | WasiRights.PATH_LINK_TARGET, BigInt(0)); + } + else { + oldWrap = wasi.fds.get(old_fd, WasiRights.PATH_LINK_SOURCE, BigInt(0)); + newWrap = wasi.fds.get(new_fd, WasiRights.PATH_LINK_TARGET, BigInt(0)); + } + const { HEAPU8 } = getMemory(this, Math.max(old_path + old_path_len, new_path + new_path_len)); + const fs = getFs(this); + const resolvedOldPath = await resolvePathAsync(fs, oldWrap, decoder.decode(unsharedSlice(HEAPU8, old_path, old_path + old_path_len)), old_flags); + const resolvedNewPath = resolve(newWrap.realPath, decoder.decode(unsharedSlice(HEAPU8, new_path, new_path + new_path_len))); + await fs.promises.link(resolvedOldPath, resolvedNewPath); + return WasiErrno.ESUCCESS; + }, ['i32', 'i32', 'i32', 'i32', 'i32', 'i32', 'i32'], ['i32']); + function pathOpen(o_flags, fs_rights_base, fs_rights_inheriting, fs_flags) { + const read = (fs_rights_base & (WasiRights.FD_READ | + WasiRights.FD_READDIR)) !== BigInt(0); + const write = (fs_rights_base & (WasiRights.FD_DATASYNC | + WasiRights.FD_WRITE | + WasiRights.FD_ALLOCATE | + WasiRights.FD_FILESTAT_SET_SIZE)) !== BigInt(0); + let flags = write ? read ? FileControlFlag.O_RDWR : FileControlFlag.O_WRONLY : FileControlFlag.O_RDONLY; + let needed_base = WasiRights.PATH_OPEN; + let needed_inheriting = fs_rights_base | fs_rights_inheriting; + if ((o_flags & WasiFileControlFlag.O_CREAT) !== 0) { + flags |= FileControlFlag.O_CREAT; + needed_base |= WasiRights.PATH_CREATE_FILE; + } + if ((o_flags & WasiFileControlFlag.O_DIRECTORY) !== 0) { + flags |= FileControlFlag.O_DIRECTORY; + } + if ((o_flags & WasiFileControlFlag.O_EXCL) !== 0) { + flags |= FileControlFlag.O_EXCL; + } + if ((o_flags & WasiFileControlFlag.O_TRUNC) !== 0) { + flags |= FileControlFlag.O_TRUNC; + needed_base |= WasiRights.PATH_FILESTAT_SET_SIZE; + } + if ((fs_flags & WasiFdFlag.APPEND) !== 0) { + flags |= FileControlFlag.O_APPEND; + } + if ((fs_flags & WasiFdFlag.DSYNC) !== 0) { + // flags |= FileControlFlag.O_DSYNC; + needed_inheriting |= WasiRights.FD_DATASYNC; + } + if ((fs_flags & WasiFdFlag.NONBLOCK) !== 0) { + flags |= FileControlFlag.O_NONBLOCK; + } + if ((fs_flags & WasiFdFlag.RSYNC) !== 0) { + flags |= FileControlFlag.O_SYNC; + needed_inheriting |= WasiRights.FD_SYNC; + } + if ((fs_flags & WasiFdFlag.SYNC) !== 0) { + flags |= FileControlFlag.O_SYNC; + needed_inheriting |= WasiRights.FD_SYNC; + } + if (write && (flags & (FileControlFlag.O_APPEND | FileControlFlag.O_TRUNC)) === 0) { + needed_inheriting |= WasiRights.FD_SEEK; + } + return { flags, needed_base, needed_inheriting }; + } + defineImport('path_open', function path_open(dirfd, dirflags, path, path_len, o_flags, fs_rights_base, fs_rights_inheriting, fs_flags, fd) { + path = Number(path); + fd = Number(fd); + if (path === 0 || fd === 0) { + return WasiErrno.EINVAL; + } + path_len = Number(path_len); + fs_rights_base = BigInt(fs_rights_base); + fs_rights_inheriting = BigInt(fs_rights_inheriting); + const { flags: flagsRes, needed_base: neededBase, needed_inheriting: neededInheriting } = pathOpen(o_flags, fs_rights_base, fs_rights_inheriting, fs_flags); + const wasi = _wasi.get(this); + const fileDescriptor = wasi.fds.get(dirfd, neededBase, neededInheriting); + const memory = getMemory(this, Math.max(path + path_len, fd + 4)); + const HEAPU8 = memory.HEAPU8; + const pathString = decoder.decode(unsharedSlice(HEAPU8, path, path + path_len)); + const fs = getFs(this); + const resolved_path = resolvePathSync(fs, fileDescriptor, pathString, dirflags); + const r = fs.openSync(resolved_path, _isWin32Flags ? _toWinOpenFlags(flagsRes) : flagsRes, 0o666); + const filetype = wasi.fds.getFileTypeByFd(r); + if ((filetype !== WasiFileType.DIRECTORY) && + ((o_flags & WasiFileControlFlag.O_DIRECTORY) !== 0 || + (resolved_path.endsWith('/')))) { + return WasiErrno.ENOTDIR; + } + const { base: max_base, inheriting: max_inheriting } = getRights(wasi.fds.stdio, r, flagsRes, filetype); + const wrap = wasi.fds.insert(r, resolved_path, resolved_path, filetype, fs_rights_base & max_base, fs_rights_inheriting & max_inheriting, 0); + const stat = fs.fstatSync(r, { bigint: true }); + if (stat.isFile()) { + wrap.size = stat.size; + if ((flagsRes & FileControlFlag.O_APPEND) !== 0) { + wrap.pos = stat.size; + } + } + const view = memory.view; + view.setInt32(fd, wrap.id, true); + return WasiErrno.ESUCCESS; + }, async function path_open(dirfd, dirflags, path, path_len, o_flags, fs_rights_base, fs_rights_inheriting, fs_flags, fd) { + path = Number(path); + fd = Number(fd); + if (path === 0 || fd === 0) { + return WasiErrno.EINVAL; + } + path_len = Number(path_len); + fs_rights_base = BigInt(fs_rights_base); + fs_rights_inheriting = BigInt(fs_rights_inheriting); + const { flags: flagsRes, needed_base: neededBase, needed_inheriting: neededInheriting } = pathOpen(o_flags, fs_rights_base, fs_rights_inheriting, fs_flags); + const wasi = _wasi.get(this); + const fileDescriptor = wasi.fds.get(dirfd, neededBase, neededInheriting); + const memory = getMemory(this, Math.max(path + path_len, fd + 4)); + const HEAPU8 = memory.HEAPU8; + const pathString = decoder.decode(unsharedSlice(HEAPU8, path, path + path_len)); + const fs = getFs(this); + const resolved_path = await resolvePathAsync(fs, fileDescriptor, pathString, dirflags); + const r = await fs.promises.open(resolved_path, _isWin32Flags ? _toWinOpenFlags(flagsRes) : flagsRes, 0o666); + const filetype = await wasi.fds.getFileTypeByFd(r); + if ((o_flags & WasiFileControlFlag.O_DIRECTORY) !== 0 && filetype !== WasiFileType.DIRECTORY) { + return WasiErrno.ENOTDIR; + } + const { base: max_base, inheriting: max_inheriting } = getRights(wasi.fds.stdio, r.fd, flagsRes, filetype); + const wrap = wasi.fds.insert(r, resolved_path, resolved_path, filetype, fs_rights_base & max_base, fs_rights_inheriting & max_inheriting, 0); + const stat = await r.stat({ bigint: true }); + if (stat.isFile()) { + wrap.size = stat.size; + if ((flagsRes & FileControlFlag.O_APPEND) !== 0) { + wrap.pos = stat.size; + } + } + const view = memory.view; + view.setInt32(fd, wrap.id, true); + return WasiErrno.ESUCCESS; + }, ['i32', 'i32', 'i32', 'i32', 'i32', 'i64', 'i64', 'i32', 'i32'], ['i32']); + defineImport('path_readlink', function path_readlink(fd, path, path_len, buf, buf_len, bufused) { + path = Number(path); + path_len = Number(path_len); + buf = Number(buf); + buf_len = Number(buf_len); + bufused = Number(bufused); + if (path === 0 || buf === 0 || bufused === 0) { + return WasiErrno.EINVAL; + } + const { HEAPU8, view } = getMemory(this, Math.max(path + path_len, buf + buf_len, bufused + 4)); + const wasi = _wasi.get(this); + const fileDescriptor = wasi.fds.get(fd, WasiRights.PATH_READLINK, BigInt(0)); + let pathString = decoder.decode(unsharedSlice(HEAPU8, path, path + path_len)); + pathString = resolve(fileDescriptor.realPath, pathString); + const fs = getFs(this); + const link = fs.readlinkSync(pathString); + const linkData = encoder.encode(link); + const len = Math.min(linkData.length, buf_len); + if (len >= buf_len) + return WasiErrno.ENOBUFS; + HEAPU8.set(linkData.subarray(0, len), buf); + HEAPU8[buf + len] = 0; + view.setUint32(bufused, len, true); + return WasiErrno.ESUCCESS; + }, async function path_readlink(fd, path, path_len, buf, buf_len, bufused) { + path = Number(path); + path_len = Number(path_len); + buf = Number(buf); + buf_len = Number(buf_len); + bufused = Number(bufused); + if (path === 0 || buf === 0 || bufused === 0) { + return WasiErrno.EINVAL; + } + const { HEAPU8, view } = getMemory(this, Math.max(path + path_len, buf + buf_len, bufused + 4)); + const wasi = _wasi.get(this); + const fileDescriptor = wasi.fds.get(fd, WasiRights.PATH_READLINK, BigInt(0)); + let pathString = decoder.decode(unsharedSlice(HEAPU8, path, path + path_len)); + pathString = resolve(fileDescriptor.realPath, pathString); + const fs = getFs(this); + const link = await fs.promises.readlink(pathString); + const linkData = encoder.encode(link); + const len = Math.min(linkData.length, buf_len); + if (len >= buf_len) + return WasiErrno.ENOBUFS; + HEAPU8.set(linkData.subarray(0, len), buf); + HEAPU8[buf + len] = 0; + view.setUint32(bufused, len, true); + return WasiErrno.ESUCCESS; + }, ['i32', 'i32', 'i32', 'i32', 'i32', 'i32'], ['i32']); + defineImport('path_remove_directory', function path_remove_directory(fd, path, path_len) { + path = Number(path); + path_len = Number(path_len); + if (path === 0) { + return WasiErrno.EINVAL; + } + const { HEAPU8 } = getMemory(this, path + path_len); + const wasi = _wasi.get(this); + const fileDescriptor = wasi.fds.get(fd, WasiRights.PATH_REMOVE_DIRECTORY, BigInt(0)); + let pathString = decoder.decode(unsharedSlice(HEAPU8, path, path + path_len)); + pathString = resolve(fileDescriptor.realPath, pathString); + const fs = getFs(this); + fs.rmdirSync(pathString); + return WasiErrno.ESUCCESS; + }, async function path_remove_directory(fd, path, path_len) { + path = Number(path); + path_len = Number(path_len); + if (path === 0) { + return WasiErrno.EINVAL; + } + const { HEAPU8 } = getMemory(this, path + path_len); + const wasi = _wasi.get(this); + const fileDescriptor = wasi.fds.get(fd, WasiRights.PATH_REMOVE_DIRECTORY, BigInt(0)); + let pathString = decoder.decode(unsharedSlice(HEAPU8, path, path + path_len)); + pathString = resolve(fileDescriptor.realPath, pathString); + const fs = getFs(this); + await fs.promises.rmdir(pathString); + return WasiErrno.ESUCCESS; + }, ['i32', 'i32', 'i32'], ['i32']); + defineImport('path_rename', function path_rename(old_fd, old_path, old_path_len, new_fd, new_path, new_path_len) { + old_path = Number(old_path); + old_path_len = Number(old_path_len); + new_path = Number(new_path); + new_path_len = Number(new_path_len); + if (old_path === 0 || new_path === 0) { + return WasiErrno.EINVAL; + } + const wasi = _wasi.get(this); + let oldWrap; + let newWrap; + if (old_fd === new_fd) { + oldWrap = newWrap = wasi.fds.get(old_fd, WasiRights.PATH_RENAME_SOURCE | WasiRights.PATH_RENAME_TARGET, BigInt(0)); + } + else { + oldWrap = wasi.fds.get(old_fd, WasiRights.PATH_RENAME_SOURCE, BigInt(0)); + newWrap = wasi.fds.get(new_fd, WasiRights.PATH_RENAME_TARGET, BigInt(0)); + } + const { HEAPU8 } = getMemory(this, Math.max(old_path + old_path_len, new_path + new_path_len)); + const resolvedOldPath = resolve(oldWrap.realPath, decoder.decode(unsharedSlice(HEAPU8, old_path, old_path + old_path_len))); + const resolvedNewPath = resolve(newWrap.realPath, decoder.decode(unsharedSlice(HEAPU8, new_path, new_path + new_path_len))); + const fs = getFs(this); + fs.renameSync(resolvedOldPath, resolvedNewPath); + return WasiErrno.ESUCCESS; + }, async function path_rename(old_fd, old_path, old_path_len, new_fd, new_path, new_path_len) { + old_path = Number(old_path); + old_path_len = Number(old_path_len); + new_path = Number(new_path); + new_path_len = Number(new_path_len); + if (old_path === 0 || new_path === 0) { + return WasiErrno.EINVAL; + } + const wasi = _wasi.get(this); + let oldWrap; + let newWrap; + if (old_fd === new_fd) { + oldWrap = newWrap = wasi.fds.get(old_fd, WasiRights.PATH_RENAME_SOURCE | WasiRights.PATH_RENAME_TARGET, BigInt(0)); + } + else { + oldWrap = wasi.fds.get(old_fd, WasiRights.PATH_RENAME_SOURCE, BigInt(0)); + newWrap = wasi.fds.get(new_fd, WasiRights.PATH_RENAME_TARGET, BigInt(0)); + } + const { HEAPU8 } = getMemory(this, Math.max(old_path + old_path_len, new_path + new_path_len)); + const resolvedOldPath = resolve(oldWrap.realPath, decoder.decode(unsharedSlice(HEAPU8, old_path, old_path + old_path_len))); + const resolvedNewPath = resolve(newWrap.realPath, decoder.decode(unsharedSlice(HEAPU8, new_path, new_path + new_path_len))); + const fs = getFs(this); + await fs.promises.rename(resolvedOldPath, resolvedNewPath); + return WasiErrno.ESUCCESS; + }, ['i32', 'i32', 'i32', 'i32', 'i32', 'i32'], ['i32']); + defineImport('path_symlink', function path_symlink(old_path, old_path_len, fd, new_path, new_path_len) { + old_path = Number(old_path); + old_path_len = Number(old_path_len); + new_path = Number(new_path); + new_path_len = Number(new_path_len); + if (old_path === 0 || new_path === 0) { + return WasiErrno.EINVAL; + } + const { HEAPU8 } = getMemory(this, Math.max(old_path + old_path_len, new_path + new_path_len)); + const wasi = _wasi.get(this); + const fileDescriptor = wasi.fds.get(fd, WasiRights.PATH_SYMLINK, BigInt(0)); + const oldPath = decoder.decode(unsharedSlice(HEAPU8, old_path, old_path + old_path_len)); + if (oldPath.length > 0 && oldPath[0] === '/') { + return WasiErrno.EPERM; + } + let newPath = decoder.decode(unsharedSlice(HEAPU8, new_path, new_path + new_path_len)); + newPath = resolve(fileDescriptor.realPath, newPath); + const fs = getFs(this); + fs.symlinkSync(oldPath, newPath); + return WasiErrno.ESUCCESS; + }, async function path_symlink(old_path, old_path_len, fd, new_path, new_path_len) { + old_path = Number(old_path); + old_path_len = Number(old_path_len); + new_path = Number(new_path); + new_path_len = Number(new_path_len); + if (old_path === 0 || new_path === 0) { + return WasiErrno.EINVAL; + } + const { HEAPU8 } = getMemory(this, Math.max(old_path + old_path_len, new_path + new_path_len)); + const wasi = _wasi.get(this); + const fileDescriptor = wasi.fds.get(fd, WasiRights.PATH_SYMLINK, BigInt(0)); + const oldPath = decoder.decode(unsharedSlice(HEAPU8, old_path, old_path + old_path_len)); + let newPath = decoder.decode(unsharedSlice(HEAPU8, new_path, new_path + new_path_len)); + newPath = resolve(fileDescriptor.realPath, newPath); + const fs = getFs(this); + await fs.promises.symlink(oldPath, newPath); + return WasiErrno.ESUCCESS; + }, ['i32', 'i32', 'i32', 'i32', 'i32'], ['i32']); + defineImport('path_unlink_file', function path_unlink_file(fd, path, path_len) { + path = Number(path); + path_len = Number(path_len); + if (path === 0) { + return WasiErrno.EINVAL; + } + const { HEAPU8 } = getMemory(this, path + path_len); + const wasi = _wasi.get(this); + const fileDescriptor = wasi.fds.get(fd, WasiRights.PATH_UNLINK_FILE, BigInt(0)); + let pathString = decoder.decode(unsharedSlice(HEAPU8, path, path + path_len)); + pathString = resolve(fileDescriptor.realPath, pathString); + const fs = getFs(this); + fs.unlinkSync(pathString); + return WasiErrno.ESUCCESS; + }, async function path_unlink_file(fd, path, path_len) { + path = Number(path); + path_len = Number(path_len); + if (path === 0) { + return WasiErrno.EINVAL; + } + const { HEAPU8 } = getMemory(this, path + path_len); + const wasi = _wasi.get(this); + const fileDescriptor = wasi.fds.get(fd, WasiRights.PATH_UNLINK_FILE, BigInt(0)); + let pathString = decoder.decode(unsharedSlice(HEAPU8, path, path + path_len)); + pathString = resolve(fileDescriptor.realPath, pathString); + const fs = getFs(this); + await fs.promises.unlink(pathString); + return WasiErrno.ESUCCESS; + }, ['i32', 'i32', 'i32'], ['i32']); + this._setMemory = function setMemory(m) { + if (!(m instanceof _WebAssembly.Memory)) { + throw new TypeError('"instance.exports.memory" property must be a WebAssembly.Memory'); + } + _memory.set(_this, extendMemory(m)); + }; + } + static createSync(args, env, preopens, stdio, fs, print, printErr) { + const fds = new SyncTable({ + size: 3, + in: stdio[0], + out: stdio[1], + err: stdio[2], + fs, + print, + printErr + }); + const _this = new WASI(args, env, fds, false, fs); + if (preopens.length > 0) { + for (let i = 0; i < preopens.length; ++i) { + const realPath = fs.realpathSync(preopens[i].realPath, 'utf8'); + const fd = fs.openSync(realPath, 'r', 0o666); + fds.insertPreopen(fd, preopens[i].mappedPath, realPath); + } + } + return _this; + } + static async createAsync(args, env, preopens, stdio, fs, print, printErr, asyncify) { + const fds = new AsyncTable({ + size: 3, + in: stdio[0], + out: stdio[1], + err: stdio[2], + print, + printErr + }); + const _this = new WASI(args, env, fds, true, fs, asyncify); + if (preopens.length > 0) { + for (let i = 0; i < preopens.length; ++i) { + const entry = preopens[i]; + const realPath = await fs.promises.realpath(entry.realPath); + const fd = await fs.promises.open(realPath, 'r', 0o666); + await fds.insertPreopen(fd, entry.mappedPath, realPath); + } + } + return _this; + } +} diff --git a/dg-ui/node_modules/@tailwindcss/oxide-wasm32-wasi/node_modules/@tybys/wasm-util/lib/mjs/wasi/rights.mjs b/dg-ui/node_modules/@tailwindcss/oxide-wasm32-wasi/node_modules/@tybys/wasm-util/lib/mjs/wasi/rights.mjs new file mode 100644 index 0000000..b87351d --- /dev/null +++ b/dg-ui/node_modules/@tailwindcss/oxide-wasm32-wasi/node_modules/@tybys/wasm-util/lib/mjs/wasi/rights.mjs @@ -0,0 +1,135 @@ +import { WasiError } from "./error.mjs"; +import { WasiErrno, WasiRights, WasiFileType } from "./types.mjs"; +export const RIGHTS_ALL = WasiRights.FD_DATASYNC | + WasiRights.FD_READ | + WasiRights.FD_SEEK | + WasiRights.FD_FDSTAT_SET_FLAGS | + WasiRights.FD_SYNC | + WasiRights.FD_TELL | + WasiRights.FD_WRITE | + WasiRights.FD_ADVISE | + WasiRights.FD_ALLOCATE | + WasiRights.PATH_CREATE_DIRECTORY | + WasiRights.PATH_CREATE_FILE | + WasiRights.PATH_LINK_SOURCE | + WasiRights.PATH_LINK_TARGET | + WasiRights.PATH_OPEN | + WasiRights.FD_READDIR | + WasiRights.PATH_READLINK | + WasiRights.PATH_RENAME_SOURCE | + WasiRights.PATH_RENAME_TARGET | + WasiRights.PATH_FILESTAT_GET | + WasiRights.PATH_FILESTAT_SET_SIZE | + WasiRights.PATH_FILESTAT_SET_TIMES | + WasiRights.FD_FILESTAT_GET | + WasiRights.FD_FILESTAT_SET_TIMES | + WasiRights.FD_FILESTAT_SET_SIZE | + WasiRights.PATH_SYMLINK | + WasiRights.PATH_UNLINK_FILE | + WasiRights.PATH_REMOVE_DIRECTORY | + WasiRights.POLL_FD_READWRITE | + WasiRights.SOCK_SHUTDOWN | + WasiRights.SOCK_ACCEPT; +export const BLOCK_DEVICE_BASE = RIGHTS_ALL; +export const BLOCK_DEVICE_INHERITING = RIGHTS_ALL; +export const CHARACTER_DEVICE_BASE = RIGHTS_ALL; +export const CHARACTER_DEVICE_INHERITING = RIGHTS_ALL; +export const REGULAR_FILE_BASE = WasiRights.FD_DATASYNC | + WasiRights.FD_READ | + WasiRights.FD_SEEK | + WasiRights.FD_FDSTAT_SET_FLAGS | + WasiRights.FD_SYNC | + WasiRights.FD_TELL | + WasiRights.FD_WRITE | + WasiRights.FD_ADVISE | + WasiRights.FD_ALLOCATE | + WasiRights.FD_FILESTAT_GET | + WasiRights.FD_FILESTAT_SET_SIZE | + WasiRights.FD_FILESTAT_SET_TIMES | + WasiRights.POLL_FD_READWRITE; +export const REGULAR_FILE_INHERITING = /*#__PURE__*/ BigInt(0); +export const DIRECTORY_BASE = WasiRights.FD_FDSTAT_SET_FLAGS | + WasiRights.FD_SYNC | + WasiRights.FD_ADVISE | + WasiRights.PATH_CREATE_DIRECTORY | + WasiRights.PATH_CREATE_FILE | + WasiRights.PATH_LINK_SOURCE | + WasiRights.PATH_LINK_TARGET | + WasiRights.PATH_OPEN | + WasiRights.FD_READDIR | + WasiRights.PATH_READLINK | + WasiRights.PATH_RENAME_SOURCE | + WasiRights.PATH_RENAME_TARGET | + WasiRights.PATH_FILESTAT_GET | + WasiRights.PATH_FILESTAT_SET_SIZE | + WasiRights.PATH_FILESTAT_SET_TIMES | + WasiRights.FD_FILESTAT_GET | + WasiRights.FD_FILESTAT_SET_TIMES | + WasiRights.PATH_SYMLINK | + WasiRights.PATH_UNLINK_FILE | + WasiRights.PATH_REMOVE_DIRECTORY | + WasiRights.POLL_FD_READWRITE; +export const DIRECTORY_INHERITING = DIRECTORY_BASE | REGULAR_FILE_BASE; +export const SOCKET_BASE = (WasiRights.FD_READ | + WasiRights.FD_FDSTAT_SET_FLAGS | + WasiRights.FD_WRITE | + WasiRights.FD_FILESTAT_GET | + WasiRights.POLL_FD_READWRITE | + WasiRights.SOCK_SHUTDOWN); +export const SOCKET_INHERITING = RIGHTS_ALL; +export const TTY_BASE = WasiRights.FD_READ | + WasiRights.FD_FDSTAT_SET_FLAGS | + WasiRights.FD_WRITE | + WasiRights.FD_FILESTAT_GET | + WasiRights.POLL_FD_READWRITE; +export const TTY_INHERITING = /*#__PURE__*/ BigInt(0); +export function getRights(stdio, fd, flags, type) { + const ret = { + base: BigInt(0), + inheriting: BigInt(0) + }; + if (type === WasiFileType.UNKNOWN) { + throw new WasiError('Unknown file type', WasiErrno.EINVAL); + } + switch (type) { + case WasiFileType.REGULAR_FILE: + ret.base = REGULAR_FILE_BASE; + ret.inheriting = REGULAR_FILE_INHERITING; + break; + case WasiFileType.DIRECTORY: + ret.base = DIRECTORY_BASE; + ret.inheriting = DIRECTORY_INHERITING; + break; + case WasiFileType.SOCKET_STREAM: + case WasiFileType.SOCKET_DGRAM: + ret.base = SOCKET_BASE; + ret.inheriting = SOCKET_INHERITING; + break; + case WasiFileType.CHARACTER_DEVICE: + if (stdio.indexOf(fd) !== -1) { + ret.base = TTY_BASE; + ret.inheriting = TTY_INHERITING; + } + else { + ret.base = CHARACTER_DEVICE_BASE; + ret.inheriting = CHARACTER_DEVICE_INHERITING; + } + break; + case WasiFileType.BLOCK_DEVICE: + ret.base = BLOCK_DEVICE_BASE; + ret.inheriting = BLOCK_DEVICE_INHERITING; + break; + default: + ret.base = BigInt(0); + ret.inheriting = BigInt(0); + } + /* Disable read/write bits depending on access mode. */ + const read_or_write_only = flags & (0 | 1 | 2); + if (read_or_write_only === 0) { + ret.base &= ~WasiRights.FD_WRITE; + } + else if (read_or_write_only === 1) { + ret.base &= ~WasiRights.FD_READ; + } + return ret; +} diff --git a/dg-ui/node_modules/@tailwindcss/oxide-wasm32-wasi/node_modules/@tybys/wasm-util/lib/mjs/wasi/types.mjs b/dg-ui/node_modules/@tailwindcss/oxide-wasm32-wasi/node_modules/@tybys/wasm-util/lib/mjs/wasi/types.mjs new file mode 100644 index 0000000..c18bdd6 --- /dev/null +++ b/dg-ui/node_modules/@tailwindcss/oxide-wasm32-wasi/node_modules/@tybys/wasm-util/lib/mjs/wasi/types.mjs @@ -0,0 +1,216 @@ +/* eslint-disable spaced-comment */ +export var WasiErrno; +(function (WasiErrno) { + WasiErrno[WasiErrno["ESUCCESS"] = 0] = "ESUCCESS"; + WasiErrno[WasiErrno["E2BIG"] = 1] = "E2BIG"; + WasiErrno[WasiErrno["EACCES"] = 2] = "EACCES"; + WasiErrno[WasiErrno["EADDRINUSE"] = 3] = "EADDRINUSE"; + WasiErrno[WasiErrno["EADDRNOTAVAIL"] = 4] = "EADDRNOTAVAIL"; + WasiErrno[WasiErrno["EAFNOSUPPORT"] = 5] = "EAFNOSUPPORT"; + WasiErrno[WasiErrno["EAGAIN"] = 6] = "EAGAIN"; + WasiErrno[WasiErrno["EALREADY"] = 7] = "EALREADY"; + WasiErrno[WasiErrno["EBADF"] = 8] = "EBADF"; + WasiErrno[WasiErrno["EBADMSG"] = 9] = "EBADMSG"; + WasiErrno[WasiErrno["EBUSY"] = 10] = "EBUSY"; + WasiErrno[WasiErrno["ECANCELED"] = 11] = "ECANCELED"; + WasiErrno[WasiErrno["ECHILD"] = 12] = "ECHILD"; + WasiErrno[WasiErrno["ECONNABORTED"] = 13] = "ECONNABORTED"; + WasiErrno[WasiErrno["ECONNREFUSED"] = 14] = "ECONNREFUSED"; + WasiErrno[WasiErrno["ECONNRESET"] = 15] = "ECONNRESET"; + WasiErrno[WasiErrno["EDEADLK"] = 16] = "EDEADLK"; + WasiErrno[WasiErrno["EDESTADDRREQ"] = 17] = "EDESTADDRREQ"; + WasiErrno[WasiErrno["EDOM"] = 18] = "EDOM"; + WasiErrno[WasiErrno["EDQUOT"] = 19] = "EDQUOT"; + WasiErrno[WasiErrno["EEXIST"] = 20] = "EEXIST"; + WasiErrno[WasiErrno["EFAULT"] = 21] = "EFAULT"; + WasiErrno[WasiErrno["EFBIG"] = 22] = "EFBIG"; + WasiErrno[WasiErrno["EHOSTUNREACH"] = 23] = "EHOSTUNREACH"; + WasiErrno[WasiErrno["EIDRM"] = 24] = "EIDRM"; + WasiErrno[WasiErrno["EILSEQ"] = 25] = "EILSEQ"; + WasiErrno[WasiErrno["EINPROGRESS"] = 26] = "EINPROGRESS"; + WasiErrno[WasiErrno["EINTR"] = 27] = "EINTR"; + WasiErrno[WasiErrno["EINVAL"] = 28] = "EINVAL"; + WasiErrno[WasiErrno["EIO"] = 29] = "EIO"; + WasiErrno[WasiErrno["EISCONN"] = 30] = "EISCONN"; + WasiErrno[WasiErrno["EISDIR"] = 31] = "EISDIR"; + WasiErrno[WasiErrno["ELOOP"] = 32] = "ELOOP"; + WasiErrno[WasiErrno["EMFILE"] = 33] = "EMFILE"; + WasiErrno[WasiErrno["EMLINK"] = 34] = "EMLINK"; + WasiErrno[WasiErrno["EMSGSIZE"] = 35] = "EMSGSIZE"; + WasiErrno[WasiErrno["EMULTIHOP"] = 36] = "EMULTIHOP"; + WasiErrno[WasiErrno["ENAMETOOLONG"] = 37] = "ENAMETOOLONG"; + WasiErrno[WasiErrno["ENETDOWN"] = 38] = "ENETDOWN"; + WasiErrno[WasiErrno["ENETRESET"] = 39] = "ENETRESET"; + WasiErrno[WasiErrno["ENETUNREACH"] = 40] = "ENETUNREACH"; + WasiErrno[WasiErrno["ENFILE"] = 41] = "ENFILE"; + WasiErrno[WasiErrno["ENOBUFS"] = 42] = "ENOBUFS"; + WasiErrno[WasiErrno["ENODEV"] = 43] = "ENODEV"; + WasiErrno[WasiErrno["ENOENT"] = 44] = "ENOENT"; + WasiErrno[WasiErrno["ENOEXEC"] = 45] = "ENOEXEC"; + WasiErrno[WasiErrno["ENOLCK"] = 46] = "ENOLCK"; + WasiErrno[WasiErrno["ENOLINK"] = 47] = "ENOLINK"; + WasiErrno[WasiErrno["ENOMEM"] = 48] = "ENOMEM"; + WasiErrno[WasiErrno["ENOMSG"] = 49] = "ENOMSG"; + WasiErrno[WasiErrno["ENOPROTOOPT"] = 50] = "ENOPROTOOPT"; + WasiErrno[WasiErrno["ENOSPC"] = 51] = "ENOSPC"; + WasiErrno[WasiErrno["ENOSYS"] = 52] = "ENOSYS"; + WasiErrno[WasiErrno["ENOTCONN"] = 53] = "ENOTCONN"; + WasiErrno[WasiErrno["ENOTDIR"] = 54] = "ENOTDIR"; + WasiErrno[WasiErrno["ENOTEMPTY"] = 55] = "ENOTEMPTY"; + WasiErrno[WasiErrno["ENOTRECOVERABLE"] = 56] = "ENOTRECOVERABLE"; + WasiErrno[WasiErrno["ENOTSOCK"] = 57] = "ENOTSOCK"; + WasiErrno[WasiErrno["ENOTSUP"] = 58] = "ENOTSUP"; + WasiErrno[WasiErrno["ENOTTY"] = 59] = "ENOTTY"; + WasiErrno[WasiErrno["ENXIO"] = 60] = "ENXIO"; + WasiErrno[WasiErrno["EOVERFLOW"] = 61] = "EOVERFLOW"; + WasiErrno[WasiErrno["EOWNERDEAD"] = 62] = "EOWNERDEAD"; + WasiErrno[WasiErrno["EPERM"] = 63] = "EPERM"; + WasiErrno[WasiErrno["EPIPE"] = 64] = "EPIPE"; + WasiErrno[WasiErrno["EPROTO"] = 65] = "EPROTO"; + WasiErrno[WasiErrno["EPROTONOSUPPORT"] = 66] = "EPROTONOSUPPORT"; + WasiErrno[WasiErrno["EPROTOTYPE"] = 67] = "EPROTOTYPE"; + WasiErrno[WasiErrno["ERANGE"] = 68] = "ERANGE"; + WasiErrno[WasiErrno["EROFS"] = 69] = "EROFS"; + WasiErrno[WasiErrno["ESPIPE"] = 70] = "ESPIPE"; + WasiErrno[WasiErrno["ESRCH"] = 71] = "ESRCH"; + WasiErrno[WasiErrno["ESTALE"] = 72] = "ESTALE"; + WasiErrno[WasiErrno["ETIMEDOUT"] = 73] = "ETIMEDOUT"; + WasiErrno[WasiErrno["ETXTBSY"] = 74] = "ETXTBSY"; + WasiErrno[WasiErrno["EXDEV"] = 75] = "EXDEV"; + WasiErrno[WasiErrno["ENOTCAPABLE"] = 76] = "ENOTCAPABLE"; +})(WasiErrno || (WasiErrno = {})); +export var WasiFileType; +(function (WasiFileType) { + WasiFileType[WasiFileType["UNKNOWN"] = 0] = "UNKNOWN"; + WasiFileType[WasiFileType["BLOCK_DEVICE"] = 1] = "BLOCK_DEVICE"; + WasiFileType[WasiFileType["CHARACTER_DEVICE"] = 2] = "CHARACTER_DEVICE"; + WasiFileType[WasiFileType["DIRECTORY"] = 3] = "DIRECTORY"; + WasiFileType[WasiFileType["REGULAR_FILE"] = 4] = "REGULAR_FILE"; + WasiFileType[WasiFileType["SOCKET_DGRAM"] = 5] = "SOCKET_DGRAM"; + WasiFileType[WasiFileType["SOCKET_STREAM"] = 6] = "SOCKET_STREAM"; + WasiFileType[WasiFileType["SYMBOLIC_LINK"] = 7] = "SYMBOLIC_LINK"; +})(WasiFileType || (WasiFileType = {})); +const FD_DATASYNC = ( /*#__PURE__*/BigInt(1) << /*#__PURE__*/ BigInt(0)); +const FD_READ = ( /*#__PURE__*/BigInt(1) << /*#__PURE__*/ BigInt(1)); +const FD_SEEK = ( /*#__PURE__*/BigInt(1) << /*#__PURE__*/ BigInt(2)); +const FD_FDSTAT_SET_FLAGS = ( /*#__PURE__*/BigInt(1) << /*#__PURE__*/ BigInt(3)); +const FD_SYNC = ( /*#__PURE__*/BigInt(1) << /*#__PURE__*/ BigInt(4)); +const FD_TELL = ( /*#__PURE__*/BigInt(1) << /*#__PURE__*/ BigInt(5)); +const FD_WRITE = ( /*#__PURE__*/BigInt(1) << /*#__PURE__*/ BigInt(6)); +const FD_ADVISE = ( /*#__PURE__*/BigInt(1) << /*#__PURE__*/ BigInt(7)); +const FD_ALLOCATE = ( /*#__PURE__*/BigInt(1) << /*#__PURE__*/ BigInt(8)); +const PATH_CREATE_DIRECTORY = ( /*#__PURE__*/BigInt(1) << /*#__PURE__*/ BigInt(9)); +const PATH_CREATE_FILE = ( /*#__PURE__*/BigInt(1) << /*#__PURE__*/ BigInt(10)); +const PATH_LINK_SOURCE = ( /*#__PURE__*/BigInt(1) << /*#__PURE__*/ BigInt(11)); +const PATH_LINK_TARGET = ( /*#__PURE__*/BigInt(1) << /*#__PURE__*/ BigInt(12)); +const PATH_OPEN = ( /*#__PURE__*/BigInt(1) << /*#__PURE__*/ BigInt(13)); +const FD_READDIR = ( /*#__PURE__*/BigInt(1) << /*#__PURE__*/ BigInt(14)); +const PATH_READLINK = ( /*#__PURE__*/BigInt(1) << /*#__PURE__*/ BigInt(15)); +const PATH_RENAME_SOURCE = ( /*#__PURE__*/BigInt(1) << /*#__PURE__*/ BigInt(16)); +const PATH_RENAME_TARGET = ( /*#__PURE__*/BigInt(1) << /*#__PURE__*/ BigInt(17)); +const PATH_FILESTAT_GET = ( /*#__PURE__*/BigInt(1) << /*#__PURE__*/ BigInt(18)); +const PATH_FILESTAT_SET_SIZE = ( /*#__PURE__*/BigInt(1) << /*#__PURE__*/ BigInt(19)); +const PATH_FILESTAT_SET_TIMES = ( /*#__PURE__*/BigInt(1) << /*#__PURE__*/ BigInt(20)); +const FD_FILESTAT_GET = ( /*#__PURE__*/BigInt(1) << /*#__PURE__*/ BigInt(21)); +const FD_FILESTAT_SET_SIZE = ( /*#__PURE__*/BigInt(1) << /*#__PURE__*/ BigInt(22)); +const FD_FILESTAT_SET_TIMES = ( /*#__PURE__*/BigInt(1) << /*#__PURE__*/ BigInt(23)); +const PATH_SYMLINK = ( /*#__PURE__*/BigInt(1) << /*#__PURE__*/ BigInt(24)); +const PATH_REMOVE_DIRECTORY = ( /*#__PURE__*/BigInt(1) << /*#__PURE__*/ BigInt(25)); +const PATH_UNLINK_FILE = ( /*#__PURE__*/BigInt(1) << /*#__PURE__*/ BigInt(26)); +const POLL_FD_READWRITE = ( /*#__PURE__*/BigInt(1) << /*#__PURE__*/ BigInt(27)); +const SOCK_SHUTDOWN = ( /*#__PURE__*/BigInt(1) << /*#__PURE__*/ BigInt(28)); +const SOCK_ACCEPT = ( /*#__PURE__*/BigInt(1) << /*#__PURE__*/ BigInt(29)); +export const WasiRights = { + FD_DATASYNC, + FD_READ, + FD_SEEK, + FD_FDSTAT_SET_FLAGS, + FD_SYNC, + FD_TELL, + FD_WRITE, + FD_ADVISE, + FD_ALLOCATE, + PATH_CREATE_DIRECTORY, + PATH_CREATE_FILE, + PATH_LINK_SOURCE, + PATH_LINK_TARGET, + PATH_OPEN, + FD_READDIR, + PATH_READLINK, + PATH_RENAME_SOURCE, + PATH_RENAME_TARGET, + PATH_FILESTAT_GET, + PATH_FILESTAT_SET_SIZE, + PATH_FILESTAT_SET_TIMES, + FD_FILESTAT_GET, + FD_FILESTAT_SET_SIZE, + FD_FILESTAT_SET_TIMES, + PATH_SYMLINK, + PATH_REMOVE_DIRECTORY, + PATH_UNLINK_FILE, + POLL_FD_READWRITE, + SOCK_SHUTDOWN, + SOCK_ACCEPT +}; +export var WasiWhence; +(function (WasiWhence) { + WasiWhence[WasiWhence["SET"] = 0] = "SET"; + WasiWhence[WasiWhence["CUR"] = 1] = "CUR"; + WasiWhence[WasiWhence["END"] = 2] = "END"; +})(WasiWhence || (WasiWhence = {})); +export var FileControlFlag; +(function (FileControlFlag) { + FileControlFlag[FileControlFlag["O_RDONLY"] = 0] = "O_RDONLY"; + FileControlFlag[FileControlFlag["O_WRONLY"] = 1] = "O_WRONLY"; + FileControlFlag[FileControlFlag["O_RDWR"] = 2] = "O_RDWR"; + FileControlFlag[FileControlFlag["O_CREAT"] = 64] = "O_CREAT"; + FileControlFlag[FileControlFlag["O_EXCL"] = 128] = "O_EXCL"; + FileControlFlag[FileControlFlag["O_NOCTTY"] = 256] = "O_NOCTTY"; + FileControlFlag[FileControlFlag["O_TRUNC"] = 512] = "O_TRUNC"; + FileControlFlag[FileControlFlag["O_APPEND"] = 1024] = "O_APPEND"; + FileControlFlag[FileControlFlag["O_DIRECTORY"] = 65536] = "O_DIRECTORY"; + FileControlFlag[FileControlFlag["O_NOATIME"] = 262144] = "O_NOATIME"; + FileControlFlag[FileControlFlag["O_NOFOLLOW"] = 131072] = "O_NOFOLLOW"; + FileControlFlag[FileControlFlag["O_SYNC"] = 1052672] = "O_SYNC"; + FileControlFlag[FileControlFlag["O_DIRECT"] = 16384] = "O_DIRECT"; + FileControlFlag[FileControlFlag["O_NONBLOCK"] = 2048] = "O_NONBLOCK"; +})(FileControlFlag || (FileControlFlag = {})); +export var WasiFileControlFlag; +(function (WasiFileControlFlag) { + WasiFileControlFlag[WasiFileControlFlag["O_CREAT"] = 1] = "O_CREAT"; + WasiFileControlFlag[WasiFileControlFlag["O_DIRECTORY"] = 2] = "O_DIRECTORY"; + WasiFileControlFlag[WasiFileControlFlag["O_EXCL"] = 4] = "O_EXCL"; + WasiFileControlFlag[WasiFileControlFlag["O_TRUNC"] = 8] = "O_TRUNC"; +})(WasiFileControlFlag || (WasiFileControlFlag = {})); +export var WasiFdFlag; +(function (WasiFdFlag) { + WasiFdFlag[WasiFdFlag["APPEND"] = 1] = "APPEND"; + WasiFdFlag[WasiFdFlag["DSYNC"] = 2] = "DSYNC"; + WasiFdFlag[WasiFdFlag["NONBLOCK"] = 4] = "NONBLOCK"; + WasiFdFlag[WasiFdFlag["RSYNC"] = 8] = "RSYNC"; + WasiFdFlag[WasiFdFlag["SYNC"] = 16] = "SYNC"; +})(WasiFdFlag || (WasiFdFlag = {})); +export var WasiClockid; +(function (WasiClockid) { + WasiClockid[WasiClockid["REALTIME"] = 0] = "REALTIME"; + WasiClockid[WasiClockid["MONOTONIC"] = 1] = "MONOTONIC"; + WasiClockid[WasiClockid["PROCESS_CPUTIME_ID"] = 2] = "PROCESS_CPUTIME_ID"; + WasiClockid[WasiClockid["THREAD_CPUTIME_ID"] = 3] = "THREAD_CPUTIME_ID"; +})(WasiClockid || (WasiClockid = {})); +export var WasiFstFlag; +(function (WasiFstFlag) { + WasiFstFlag[WasiFstFlag["SET_ATIM"] = 1] = "SET_ATIM"; + WasiFstFlag[WasiFstFlag["SET_ATIM_NOW"] = 2] = "SET_ATIM_NOW"; + WasiFstFlag[WasiFstFlag["SET_MTIM"] = 4] = "SET_MTIM"; + WasiFstFlag[WasiFstFlag["SET_MTIM_NOW"] = 8] = "SET_MTIM_NOW"; +})(WasiFstFlag || (WasiFstFlag = {})); +export var WasiEventType; +(function (WasiEventType) { + WasiEventType[WasiEventType["CLOCK"] = 0] = "CLOCK"; + WasiEventType[WasiEventType["FD_READ"] = 1] = "FD_READ"; + WasiEventType[WasiEventType["FD_WRITE"] = 2] = "FD_WRITE"; +})(WasiEventType || (WasiEventType = {})); +export var WasiSubclockflags; +(function (WasiSubclockflags) { + WasiSubclockflags[WasiSubclockflags["ABSTIME"] = 1] = "ABSTIME"; +})(WasiSubclockflags || (WasiSubclockflags = {})); diff --git a/dg-ui/node_modules/@tailwindcss/oxide-wasm32-wasi/node_modules/@tybys/wasm-util/lib/mjs/wasi/util.mjs b/dg-ui/node_modules/@tailwindcss/oxide-wasm32-wasi/node_modules/@tybys/wasm-util/lib/mjs/wasi/util.mjs new file mode 100644 index 0000000..a8ba329 --- /dev/null +++ b/dg-ui/node_modules/@tailwindcss/oxide-wasm32-wasi/node_modules/@tybys/wasm-util/lib/mjs/wasi/util.mjs @@ -0,0 +1,113 @@ +/* eslint-disable spaced-comment */ +export function validateObject(value, name) { + if (value === null || typeof value !== 'object') { + throw new TypeError(`${name} must be an object. Received ${value === null ? 'null' : typeof value}`); + } +} +export function validateArray(value, name) { + if (!Array.isArray(value)) { + throw new TypeError(`${name} must be an array. Received ${value === null ? 'null' : typeof value}`); + } +} +export function validateBoolean(value, name) { + if (typeof value !== 'boolean') { + throw new TypeError(`${name} must be a boolean. Received ${value === null ? 'null' : typeof value}`); + } +} +export function validateString(value, name) { + if (typeof value !== 'string') { + throw new TypeError(`${name} must be a string. Received ${value === null ? 'null' : typeof value}`); + } +} +export function validateFunction(value, name) { + if (typeof value !== 'function') { + throw new TypeError(`${name} must be a function. Received ${value === null ? 'null' : typeof value}`); + } +} +export function validateUndefined(value, name) { + if (value !== undefined) { + throw new TypeError(`${name} must be undefined. Received ${value === null ? 'null' : typeof value}`); + } +} +export function validateInt32(value, name, min = -2147483648, max = 2147483647) { + if (typeof value !== 'number') { + throw new TypeError(`${name} must be a number. Received ${value === null ? 'null' : typeof value}`); + } + if (!Number.isInteger(value)) { + throw new RangeError(`${name} must be a integer.`); + } + if (value < min || value > max) { + throw new RangeError(`${name} must be >= ${min} && <= ${max}. Received ${value}`); + } +} +export function isPromiseLike(obj) { + return !!(obj && (typeof obj === 'object' || typeof obj === 'function') && typeof obj.then === 'function'); +} +export function wrapInstanceExports(exports, mapFn) { + const newExports = Object.create(null); + Object.keys(exports).forEach(name => { + const exportValue = exports[name]; + Object.defineProperty(newExports, name, { + enumerable: true, + value: mapFn(exportValue, name) + }); + }); + return newExports; +} +const _require = /*#__PURE__*/ (function () { + let nativeRequire; + if (typeof __webpack_public_path__ !== 'undefined') { + nativeRequire = (function () { + return typeof __non_webpack_require__ !== 'undefined' ? __non_webpack_require__ : undefined; + })(); + } + else { + nativeRequire = (function () { + return typeof __webpack_public_path__ !== 'undefined' ? (typeof __non_webpack_require__ !== 'undefined' ? __non_webpack_require__ : undefined) : (typeof require !== 'undefined' ? require : undefined); + })(); + } + return nativeRequire; +})(); +export const isMainThread = /*#__PURE__*/ (function () { + let worker_threads; + try { + worker_threads = _require('worker_threads'); + } + catch (_) { } + if (!worker_threads) { + return typeof importScripts === 'undefined'; + } + return worker_threads.isMainThread; +})(); +export const postMsg = isMainThread + ? () => { } + : /*#__PURE__*/ (function () { + let worker_threads; + try { + worker_threads = _require('worker_threads'); + } + catch (_) { } + if (!worker_threads) { + return postMessage; + } + return function postMessage(data) { + worker_threads.parentPort.postMessage({ data }); + }; + })(); +export function sleepBreakIf(delay, breakIf) { + const start = Date.now(); + const end = start + delay; + let ret = false; + while (Date.now() < end) { + if (breakIf()) { + ret = true; + break; + } + } + return ret; +} +export function unsharedSlice(view, start, end) { + return ((typeof SharedArrayBuffer === 'function' && view.buffer instanceof SharedArrayBuffer) || (Object.prototype.toString.call(view.buffer.constructor) === '[object SharedArrayBuffer]')) + ? view.slice(start, end) + : view.subarray(start, end); +} diff --git a/dg-ui/node_modules/@tailwindcss/oxide-wasm32-wasi/node_modules/@tybys/wasm-util/lib/mjs/webassembly.mjs b/dg-ui/node_modules/@tailwindcss/oxide-wasm32-wasi/node_modules/@tybys/wasm-util/lib/mjs/webassembly.mjs new file mode 100644 index 0000000..b4192f7 --- /dev/null +++ b/dg-ui/node_modules/@tailwindcss/oxide-wasm32-wasi/node_modules/@tybys/wasm-util/lib/mjs/webassembly.mjs @@ -0,0 +1,9 @@ +const _WebAssembly = typeof WebAssembly !== 'undefined' + ? WebAssembly + : typeof WXWebAssembly !== 'undefined' + ? WXWebAssembly + : undefined; +if (!_WebAssembly) { + throw new Error('WebAssembly is not supported in this environment'); +} +export { _WebAssembly }; diff --git a/dg-ui/node_modules/@tailwindcss/oxide-wasm32-wasi/node_modules/@tybys/wasm-util/package.json b/dg-ui/node_modules/@tailwindcss/oxide-wasm32-wasi/node_modules/@tybys/wasm-util/package.json new file mode 100644 index 0000000..9d01dd2 --- /dev/null +++ b/dg-ui/node_modules/@tailwindcss/oxide-wasm32-wasi/node_modules/@tybys/wasm-util/package.json @@ -0,0 +1,58 @@ +{ + "name": "@tybys/wasm-util", + "version": "0.10.3", + "description": "WASI polyfill for browser and some wasm util", + "main": "./lib/cjs/index.js", + "module": "./dist/wasm-util.esm-bundler.js", + "types": "./dist/wasm-util.d.ts", + "exports": { + ".": { + "module": "./dist/wasm-util.esm-bundler.js", + "import": "./lib/mjs/index.mjs", + "require": "./lib/cjs/index.js", + "types": "./dist/wasm-util.d.ts" + } + }, + "scripts": { + "build": "tsgo build", + "watch": "tsgo watch", + "test": "jest", + "lint": "eslint ./src/**/*.{ts,js} --fix", + "prepare": "npm run build" + }, + "publishConfig": { + "access": "public" + }, + "keywords": [ + "wasm", + "webassembly", + "wasi", + "polyfill" + ], + "repository": { + "type": "git", + "url": "https://github.com/toyobayashi/wasm-util.git" + }, + "author": "toyobayashi", + "license": "MIT", + "dependencies": { + "tslib": "^2.4.0" + }, + "devDependencies": { + "@tybys/ts-transform-module-specifier": "^0.0.2", + "@tybys/ts-transform-pure-class": "^0.1.1", + "@tybys/tsgo": "^1.1.0", + "@types/node": "^14.14.31", + "@typescript-eslint/eslint-plugin": "^5.40.1", + "@typescript-eslint/parser": "^5.40.1", + "eslint": "^8.25.0", + "eslint-config-standard-with-typescript": "^23.0.0", + "eslint-plugin-import": "^2.26.0", + "eslint-plugin-n": "^15.3.0", + "eslint-plugin-promise": "^6.1.0", + "memfs-browser": "^3.4.13000", + "mocha": "^10.1.0", + "ts-node": "^10.9.1", + "typescript": "~4.8.3" + } +} diff --git a/dg-ui/node_modules/@tailwindcss/oxide-wasm32-wasi/node_modules/tslib/CopyrightNotice.txt b/dg-ui/node_modules/@tailwindcss/oxide-wasm32-wasi/node_modules/tslib/CopyrightNotice.txt new file mode 100644 index 0000000..5d7d2d9 --- /dev/null +++ b/dg-ui/node_modules/@tailwindcss/oxide-wasm32-wasi/node_modules/tslib/CopyrightNotice.txt @@ -0,0 +1,15 @@ +/****************************************************************************** +Copyright (c) Microsoft Corporation. + +Permission to use, copy, modify, and/or distribute this software for any +purpose with or without fee is hereby granted. + +THE SOFTWARE IS PROVIDED "AS IS" AND THE AUTHOR DISCLAIMS ALL WARRANTIES WITH +REGARD TO THIS SOFTWARE INCLUDING ALL IMPLIED WARRANTIES OF MERCHANTABILITY +AND FITNESS. IN NO EVENT SHALL THE AUTHOR BE LIABLE FOR ANY SPECIAL, DIRECT, +INDIRECT, OR CONSEQUENTIAL DAMAGES OR ANY DAMAGES WHATSOEVER RESULTING FROM +LOSS OF USE, DATA OR PROFITS, WHETHER IN AN ACTION OF CONTRACT, NEGLIGENCE OR +OTHER TORTIOUS ACTION, ARISING OUT OF OR IN CONNECTION WITH THE USE OR +PERFORMANCE OF THIS SOFTWARE. +***************************************************************************** */ + diff --git a/dg-ui/node_modules/@tailwindcss/oxide-wasm32-wasi/node_modules/tslib/LICENSE.txt b/dg-ui/node_modules/@tailwindcss/oxide-wasm32-wasi/node_modules/tslib/LICENSE.txt new file mode 100644 index 0000000..fa7d1bd --- /dev/null +++ b/dg-ui/node_modules/@tailwindcss/oxide-wasm32-wasi/node_modules/tslib/LICENSE.txt @@ -0,0 +1,12 @@ +Copyright (c) Microsoft Corporation. + +Permission to use, copy, modify, and/or distribute this software for any +purpose with or without fee is hereby granted. + +THE SOFTWARE IS PROVIDED "AS IS" AND THE AUTHOR DISCLAIMS ALL WARRANTIES WITH +REGARD TO THIS SOFTWARE INCLUDING ALL IMPLIED WARRANTIES OF MERCHANTABILITY +AND FITNESS. IN NO EVENT SHALL THE AUTHOR BE LIABLE FOR ANY SPECIAL, DIRECT, +INDIRECT, OR CONSEQUENTIAL DAMAGES OR ANY DAMAGES WHATSOEVER RESULTING FROM +LOSS OF USE, DATA OR PROFITS, WHETHER IN AN ACTION OF CONTRACT, NEGLIGENCE OR +OTHER TORTIOUS ACTION, ARISING OUT OF OR IN CONNECTION WITH THE USE OR +PERFORMANCE OF THIS SOFTWARE. \ No newline at end of file diff --git a/dg-ui/node_modules/@tailwindcss/oxide-wasm32-wasi/node_modules/tslib/README.md b/dg-ui/node_modules/@tailwindcss/oxide-wasm32-wasi/node_modules/tslib/README.md new file mode 100644 index 0000000..14b9a83 --- /dev/null +++ b/dg-ui/node_modules/@tailwindcss/oxide-wasm32-wasi/node_modules/tslib/README.md @@ -0,0 +1,164 @@ +# tslib + +This is a runtime library for [TypeScript](https://www.typescriptlang.org/) that contains all of the TypeScript helper functions. + +This library is primarily used by the `--importHelpers` flag in TypeScript. +When using `--importHelpers`, a module that uses helper functions like `__extends` and `__assign` in the following emitted file: + +```ts +var __assign = (this && this.__assign) || Object.assign || function(t) { + for (var s, i = 1, n = arguments.length; i < n; i++) { + s = arguments[i]; + for (var p in s) if (Object.prototype.hasOwnProperty.call(s, p)) + t[p] = s[p]; + } + return t; +}; +exports.x = {}; +exports.y = __assign({}, exports.x); + +``` + +will instead be emitted as something like the following: + +```ts +var tslib_1 = require("tslib"); +exports.x = {}; +exports.y = tslib_1.__assign({}, exports.x); +``` + +Because this can avoid duplicate declarations of things like `__extends`, `__assign`, etc., this means delivering users smaller files on average, as well as less runtime overhead. +For optimized bundles with TypeScript, you should absolutely consider using `tslib` and `--importHelpers`. + +# Installing + +For the latest stable version, run: + +## npm + +```sh +# TypeScript 3.9.2 or later +npm install tslib + +# TypeScript 3.8.4 or earlier +npm install tslib@^1 + +# TypeScript 2.3.2 or earlier +npm install tslib@1.6.1 +``` + +## yarn + +```sh +# TypeScript 3.9.2 or later +yarn add tslib + +# TypeScript 3.8.4 or earlier +yarn add tslib@^1 + +# TypeScript 2.3.2 or earlier +yarn add tslib@1.6.1 +``` + +## bower + +```sh +# TypeScript 3.9.2 or later +bower install tslib + +# TypeScript 3.8.4 or earlier +bower install tslib@^1 + +# TypeScript 2.3.2 or earlier +bower install tslib@1.6.1 +``` + +## JSPM + +```sh +# TypeScript 3.9.2 or later +jspm install tslib + +# TypeScript 3.8.4 or earlier +jspm install tslib@^1 + +# TypeScript 2.3.2 or earlier +jspm install tslib@1.6.1 +``` + +# Usage + +Set the `importHelpers` compiler option on the command line: + +``` +tsc --importHelpers file.ts +``` + +or in your tsconfig.json: + +```json +{ + "compilerOptions": { + "importHelpers": true + } +} +``` + +#### For bower and JSPM users + +You will need to add a `paths` mapping for `tslib`, e.g. For Bower users: + +```json +{ + "compilerOptions": { + "module": "amd", + "importHelpers": true, + "baseUrl": "./", + "paths": { + "tslib" : ["bower_components/tslib/tslib.d.ts"] + } + } +} +``` + +For JSPM users: + +```json +{ + "compilerOptions": { + "module": "system", + "importHelpers": true, + "baseUrl": "./", + "paths": { + "tslib" : ["jspm_packages/npm/tslib@2.x.y/tslib.d.ts"] + } + } +} +``` + +## Deployment + +- Choose your new version number +- Set it in `package.json` and `bower.json` +- Create a tag: `git tag [version]` +- Push the tag: `git push --tags` +- Create a [release in GitHub](https://github.com/microsoft/tslib/releases) +- Run the [publish to npm](https://github.com/microsoft/tslib/actions?query=workflow%3A%22Publish+to+NPM%22) workflow + +Done. + +# Contribute + +There are many ways to [contribute](https://github.com/Microsoft/TypeScript/blob/master/CONTRIBUTING.md) to TypeScript. + +* [Submit bugs](https://github.com/Microsoft/TypeScript/issues) and help us verify fixes as they are checked in. +* Review the [source code changes](https://github.com/Microsoft/TypeScript/pulls). +* Engage with other TypeScript users and developers on [StackOverflow](http://stackoverflow.com/questions/tagged/typescript). +* Join the [#typescript](http://twitter.com/#!/search/realtime/%23typescript) discussion on Twitter. +* [Contribute bug fixes](https://github.com/Microsoft/TypeScript/blob/master/CONTRIBUTING.md). + +# Documentation + +* [Quick tutorial](http://www.typescriptlang.org/Tutorial) +* [Programming handbook](http://www.typescriptlang.org/Handbook) +* [Homepage](http://www.typescriptlang.org/) diff --git a/dg-ui/node_modules/@tailwindcss/oxide-wasm32-wasi/node_modules/tslib/SECURITY.md b/dg-ui/node_modules/@tailwindcss/oxide-wasm32-wasi/node_modules/tslib/SECURITY.md new file mode 100644 index 0000000..869fdfe --- /dev/null +++ b/dg-ui/node_modules/@tailwindcss/oxide-wasm32-wasi/node_modules/tslib/SECURITY.md @@ -0,0 +1,41 @@ + + +## Security + +Microsoft takes the security of our software products and services seriously, which includes all source code repositories managed through our GitHub organizations, which include [Microsoft](https://github.com/Microsoft), [Azure](https://github.com/Azure), [DotNet](https://github.com/dotnet), [AspNet](https://github.com/aspnet), [Xamarin](https://github.com/xamarin), and [our GitHub organizations](https://opensource.microsoft.com/). + +If you believe you have found a security vulnerability in any Microsoft-owned repository that meets [Microsoft's definition of a security vulnerability](https://aka.ms/opensource/security/definition), please report it to us as described below. + +## Reporting Security Issues + +**Please do not report security vulnerabilities through public GitHub issues.** + +Instead, please report them to the Microsoft Security Response Center (MSRC) at [https://msrc.microsoft.com/create-report](https://aka.ms/opensource/security/create-report). + +If you prefer to submit without logging in, send email to [secure@microsoft.com](mailto:secure@microsoft.com). If possible, encrypt your message with our PGP key; please download it from the [Microsoft Security Response Center PGP Key page](https://aka.ms/opensource/security/pgpkey). + +You should receive a response within 24 hours. If for some reason you do not, please follow up via email to ensure we received your original message. Additional information can be found at [microsoft.com/msrc](https://aka.ms/opensource/security/msrc). + +Please include the requested information listed below (as much as you can provide) to help us better understand the nature and scope of the possible issue: + + * Type of issue (e.g. buffer overflow, SQL injection, cross-site scripting, etc.) + * Full paths of source file(s) related to the manifestation of the issue + * The location of the affected source code (tag/branch/commit or direct URL) + * Any special configuration required to reproduce the issue + * Step-by-step instructions to reproduce the issue + * Proof-of-concept or exploit code (if possible) + * Impact of the issue, including how an attacker might exploit the issue + +This information will help us triage your report more quickly. + +If you are reporting for a bug bounty, more complete reports can contribute to a higher bounty award. Please visit our [Microsoft Bug Bounty Program](https://aka.ms/opensource/security/bounty) page for more details about our active programs. + +## Preferred Languages + +We prefer all communications to be in English. + +## Policy + +Microsoft follows the principle of [Coordinated Vulnerability Disclosure](https://aka.ms/opensource/security/cvd). + + diff --git a/dg-ui/node_modules/@tailwindcss/oxide-wasm32-wasi/node_modules/tslib/modules/index.d.ts b/dg-ui/node_modules/@tailwindcss/oxide-wasm32-wasi/node_modules/tslib/modules/index.d.ts new file mode 100644 index 0000000..3244fab --- /dev/null +++ b/dg-ui/node_modules/@tailwindcss/oxide-wasm32-wasi/node_modules/tslib/modules/index.d.ts @@ -0,0 +1,38 @@ +// Note: named reexports are used instead of `export *` because +// TypeScript itself doesn't resolve the `export *` when checking +// if a particular helper exists. +export { + __extends, + __assign, + __rest, + __decorate, + __param, + __esDecorate, + __runInitializers, + __propKey, + __setFunctionName, + __metadata, + __awaiter, + __generator, + __exportStar, + __values, + __read, + __spread, + __spreadArrays, + __spreadArray, + __await, + __asyncGenerator, + __asyncDelegator, + __asyncValues, + __makeTemplateObject, + __importStar, + __importDefault, + __classPrivateFieldGet, + __classPrivateFieldSet, + __classPrivateFieldIn, + __createBinding, + __addDisposableResource, + __disposeResources, + __rewriteRelativeImportExtension, +} from '../tslib.js'; +export * as default from '../tslib.js'; diff --git a/dg-ui/node_modules/@tailwindcss/oxide-wasm32-wasi/node_modules/tslib/modules/index.js b/dg-ui/node_modules/@tailwindcss/oxide-wasm32-wasi/node_modules/tslib/modules/index.js new file mode 100644 index 0000000..f4f9a06 --- /dev/null +++ b/dg-ui/node_modules/@tailwindcss/oxide-wasm32-wasi/node_modules/tslib/modules/index.js @@ -0,0 +1,70 @@ +import tslib from '../tslib.js'; +const { + __extends, + __assign, + __rest, + __decorate, + __param, + __esDecorate, + __runInitializers, + __propKey, + __setFunctionName, + __metadata, + __awaiter, + __generator, + __exportStar, + __createBinding, + __values, + __read, + __spread, + __spreadArrays, + __spreadArray, + __await, + __asyncGenerator, + __asyncDelegator, + __asyncValues, + __makeTemplateObject, + __importStar, + __importDefault, + __classPrivateFieldGet, + __classPrivateFieldSet, + __classPrivateFieldIn, + __addDisposableResource, + __disposeResources, + __rewriteRelativeImportExtension, +} = tslib; +export { + __extends, + __assign, + __rest, + __decorate, + __param, + __esDecorate, + __runInitializers, + __propKey, + __setFunctionName, + __metadata, + __awaiter, + __generator, + __exportStar, + __createBinding, + __values, + __read, + __spread, + __spreadArrays, + __spreadArray, + __await, + __asyncGenerator, + __asyncDelegator, + __asyncValues, + __makeTemplateObject, + __importStar, + __importDefault, + __classPrivateFieldGet, + __classPrivateFieldSet, + __classPrivateFieldIn, + __addDisposableResource, + __disposeResources, + __rewriteRelativeImportExtension, +}; +export default tslib; diff --git a/dg-ui/node_modules/@tailwindcss/oxide-wasm32-wasi/node_modules/tslib/modules/package.json b/dg-ui/node_modules/@tailwindcss/oxide-wasm32-wasi/node_modules/tslib/modules/package.json new file mode 100644 index 0000000..96ae6e5 --- /dev/null +++ b/dg-ui/node_modules/@tailwindcss/oxide-wasm32-wasi/node_modules/tslib/modules/package.json @@ -0,0 +1,3 @@ +{ + "type": "module" +} \ No newline at end of file diff --git a/dg-ui/node_modules/@tailwindcss/oxide-wasm32-wasi/node_modules/tslib/package.json b/dg-ui/node_modules/@tailwindcss/oxide-wasm32-wasi/node_modules/tslib/package.json new file mode 100644 index 0000000..57d0578 --- /dev/null +++ b/dg-ui/node_modules/@tailwindcss/oxide-wasm32-wasi/node_modules/tslib/package.json @@ -0,0 +1,47 @@ +{ + "name": "tslib", + "author": "Microsoft Corp.", + "homepage": "https://www.typescriptlang.org/", + "version": "2.8.1", + "license": "0BSD", + "description": "Runtime library for TypeScript helper functions", + "keywords": [ + "TypeScript", + "Microsoft", + "compiler", + "language", + "javascript", + "tslib", + "runtime" + ], + "bugs": { + "url": "https://github.com/Microsoft/TypeScript/issues" + }, + "repository": { + "type": "git", + "url": "https://github.com/Microsoft/tslib.git" + }, + "main": "tslib.js", + "module": "tslib.es6.js", + "jsnext:main": "tslib.es6.js", + "typings": "tslib.d.ts", + "sideEffects": false, + "exports": { + ".": { + "module": { + "types": "./modules/index.d.ts", + "default": "./tslib.es6.mjs" + }, + "import": { + "node": "./modules/index.js", + "default": { + "types": "./modules/index.d.ts", + "default": "./tslib.es6.mjs" + } + }, + "default": "./tslib.js" + }, + "./*": "./*", + "./": "./" + } +} diff --git a/dg-ui/node_modules/@tailwindcss/oxide-wasm32-wasi/node_modules/tslib/tslib.d.ts b/dg-ui/node_modules/@tailwindcss/oxide-wasm32-wasi/node_modules/tslib/tslib.d.ts new file mode 100644 index 0000000..9c27e05 --- /dev/null +++ b/dg-ui/node_modules/@tailwindcss/oxide-wasm32-wasi/node_modules/tslib/tslib.d.ts @@ -0,0 +1,460 @@ +/****************************************************************************** +Copyright (c) Microsoft Corporation. + +Permission to use, copy, modify, and/or distribute this software for any +purpose with or without fee is hereby granted. + +THE SOFTWARE IS PROVIDED "AS IS" AND THE AUTHOR DISCLAIMS ALL WARRANTIES WITH +REGARD TO THIS SOFTWARE INCLUDING ALL IMPLIED WARRANTIES OF MERCHANTABILITY +AND FITNESS. IN NO EVENT SHALL THE AUTHOR BE LIABLE FOR ANY SPECIAL, DIRECT, +INDIRECT, OR CONSEQUENTIAL DAMAGES OR ANY DAMAGES WHATSOEVER RESULTING FROM +LOSS OF USE, DATA OR PROFITS, WHETHER IN AN ACTION OF CONTRACT, NEGLIGENCE OR +OTHER TORTIOUS ACTION, ARISING OUT OF OR IN CONNECTION WITH THE USE OR +PERFORMANCE OF THIS SOFTWARE. +***************************************************************************** */ + +/** + * Used to shim class extends. + * + * @param d The derived class. + * @param b The base class. + */ +export declare function __extends(d: Function, b: Function): void; + +/** + * Copy the values of all of the enumerable own properties from one or more source objects to a + * target object. Returns the target object. + * + * @param t The target object to copy to. + * @param sources One or more source objects from which to copy properties + */ +export declare function __assign(t: any, ...sources: any[]): any; + +/** + * Performs a rest spread on an object. + * + * @param t The source value. + * @param propertyNames The property names excluded from the rest spread. + */ +export declare function __rest(t: any, propertyNames: (string | symbol)[]): any; + +/** + * Applies decorators to a target object + * + * @param decorators The set of decorators to apply. + * @param target The target object. + * @param key If specified, the own property to apply the decorators to. + * @param desc The property descriptor, defaults to fetching the descriptor from the target object. + * @experimental + */ +export declare function __decorate(decorators: Function[], target: any, key?: string | symbol, desc?: any): any; + +/** + * Creates an observing function decorator from a parameter decorator. + * + * @param paramIndex The parameter index to apply the decorator to. + * @param decorator The parameter decorator to apply. Note that the return value is ignored. + * @experimental + */ +export declare function __param(paramIndex: number, decorator: Function): Function; + +/** + * Applies decorators to a class or class member, following the native ECMAScript decorator specification. + * @param ctor For non-field class members, the class constructor. Otherwise, `null`. + * @param descriptorIn The `PropertyDescriptor` to use when unable to look up the property from `ctor`. + * @param decorators The decorators to apply + * @param contextIn The `DecoratorContext` to clone for each decorator application. + * @param initializers An array of field initializer mutation functions into which new initializers are written. + * @param extraInitializers An array of extra initializer functions into which new initializers are written. + */ +export declare function __esDecorate(ctor: Function | null, descriptorIn: object | null, decorators: Function[], contextIn: object, initializers: Function[] | null, extraInitializers: Function[]): void; + +/** + * Runs field initializers or extra initializers generated by `__esDecorate`. + * @param thisArg The `this` argument to use. + * @param initializers The array of initializers to evaluate. + * @param value The initial value to pass to the initializers. + */ +export declare function __runInitializers(thisArg: unknown, initializers: Function[], value?: any): any; + +/** + * Converts a computed property name into a `string` or `symbol` value. + */ +export declare function __propKey(x: any): string | symbol; + +/** + * Assigns the name of a function derived from the left-hand side of an assignment. + * @param f The function to rename. + * @param name The new name for the function. + * @param prefix A prefix (such as `"get"` or `"set"`) to insert before the name. + */ +export declare function __setFunctionName(f: Function, name: string | symbol, prefix?: string): Function; + +/** + * Creates a decorator that sets metadata. + * + * @param metadataKey The metadata key + * @param metadataValue The metadata value + * @experimental + */ +export declare function __metadata(metadataKey: any, metadataValue: any): Function; + +/** + * Converts a generator function into a pseudo-async function, by treating each `yield` as an `await`. + * + * @param thisArg The reference to use as the `this` value in the generator function + * @param _arguments The optional arguments array + * @param P The optional promise constructor argument, defaults to the `Promise` property of the global object. + * @param generator The generator function + */ +export declare function __awaiter(thisArg: any, _arguments: any, P: Function, generator: Function): any; + +/** + * Creates an Iterator object using the body as the implementation. + * + * @param thisArg The reference to use as the `this` value in the function + * @param body The generator state-machine based implementation. + * + * @see [./docs/generator.md] + */ +export declare function __generator(thisArg: any, body: Function): any; + +/** + * Creates bindings for all enumerable properties of `m` on `exports` + * + * @param m The source object + * @param o The `exports` object. + */ +export declare function __exportStar(m: any, o: any): void; + +/** + * Creates a value iterator from an `Iterable` or `ArrayLike` object. + * + * @param o The object. + * @throws {TypeError} If `o` is neither `Iterable`, nor an `ArrayLike`. + */ +export declare function __values(o: any): any; + +/** + * Reads values from an `Iterable` or `ArrayLike` object and returns the resulting array. + * + * @param o The object to read from. + * @param n The maximum number of arguments to read, defaults to `Infinity`. + */ +export declare function __read(o: any, n?: number): any[]; + +/** + * Creates an array from iterable spread. + * + * @param args The Iterable objects to spread. + * @deprecated since TypeScript 4.2 - Use `__spreadArray` + */ +export declare function __spread(...args: any[][]): any[]; + +/** + * Creates an array from array spread. + * + * @param args The ArrayLikes to spread into the resulting array. + * @deprecated since TypeScript 4.2 - Use `__spreadArray` + */ +export declare function __spreadArrays(...args: any[][]): any[]; + +/** + * Spreads the `from` array into the `to` array. + * + * @param pack Replace empty elements with `undefined`. + */ +export declare function __spreadArray(to: any[], from: any[], pack?: boolean): any[]; + +/** + * Creates an object that signals to `__asyncGenerator` that it shouldn't be yielded, + * and instead should be awaited and the resulting value passed back to the generator. + * + * @param v The value to await. + */ +export declare function __await(v: any): any; + +/** + * Converts a generator function into an async generator function, by using `yield __await` + * in place of normal `await`. + * + * @param thisArg The reference to use as the `this` value in the generator function + * @param _arguments The optional arguments array + * @param generator The generator function + */ +export declare function __asyncGenerator(thisArg: any, _arguments: any, generator: Function): any; + +/** + * Used to wrap a potentially async iterator in such a way so that it wraps the result + * of calling iterator methods of `o` in `__await` instances, and then yields the awaited values. + * + * @param o The potentially async iterator. + * @returns A synchronous iterator yielding `__await` instances on every odd invocation + * and returning the awaited `IteratorResult` passed to `next` every even invocation. + */ +export declare function __asyncDelegator(o: any): any; + +/** + * Creates a value async iterator from an `AsyncIterable`, `Iterable` or `ArrayLike` object. + * + * @param o The object. + * @throws {TypeError} If `o` is neither `AsyncIterable`, `Iterable`, nor an `ArrayLike`. + */ +export declare function __asyncValues(o: any): any; + +/** + * Creates a `TemplateStringsArray` frozen object from the `cooked` and `raw` arrays. + * + * @param cooked The cooked possibly-sparse array. + * @param raw The raw string content. + */ +export declare function __makeTemplateObject(cooked: string[], raw: string[]): TemplateStringsArray; + +/** + * Used to shim default and named imports in ECMAScript Modules transpiled to CommonJS. + * + * ```js + * import Default, { Named, Other } from "mod"; + * // or + * import { default as Default, Named, Other } from "mod"; + * ``` + * + * @param mod The CommonJS module exports object. + */ +export declare function __importStar(mod: T): T; + +/** + * Used to shim default imports in ECMAScript Modules transpiled to CommonJS. + * + * ```js + * import Default from "mod"; + * ``` + * + * @param mod The CommonJS module exports object. + */ +export declare function __importDefault(mod: T): T | { default: T }; + +/** + * Emulates reading a private instance field. + * + * @param receiver The instance from which to read the private field. + * @param state A WeakMap containing the private field value for an instance. + * @param kind Either `"f"` for a field, `"a"` for an accessor, or `"m"` for a method. + * + * @throws {TypeError} If `state` doesn't have an entry for `receiver`. + */ +export declare function __classPrivateFieldGet( + receiver: T, + state: { has(o: T): boolean, get(o: T): V | undefined }, + kind?: "f" +): V; + +/** + * Emulates reading a private static field. + * + * @param receiver The object from which to read the private static field. + * @param state The class constructor containing the definition of the static field. + * @param kind Either `"f"` for a field, `"a"` for an accessor, or `"m"` for a method. + * @param f The descriptor that holds the static field value. + * + * @throws {TypeError} If `receiver` is not `state`. + */ +export declare function __classPrivateFieldGet unknown, V>( + receiver: T, + state: T, + kind: "f", + f: { value: V } +): V; + +/** + * Emulates evaluating a private instance "get" accessor. + * + * @param receiver The instance on which to evaluate the private "get" accessor. + * @param state A WeakSet used to verify an instance supports the private "get" accessor. + * @param kind Either `"f"` for a field, `"a"` for an accessor, or `"m"` for a method. + * @param f The "get" accessor function to evaluate. + * + * @throws {TypeError} If `state` doesn't have an entry for `receiver`. + */ +export declare function __classPrivateFieldGet( + receiver: T, + state: { has(o: T): boolean }, + kind: "a", + f: () => V +): V; + +/** + * Emulates evaluating a private static "get" accessor. + * + * @param receiver The object on which to evaluate the private static "get" accessor. + * @param state The class constructor containing the definition of the static "get" accessor. + * @param kind Either `"f"` for a field, `"a"` for an accessor, or `"m"` for a method. + * @param f The "get" accessor function to evaluate. + * + * @throws {TypeError} If `receiver` is not `state`. + */ +export declare function __classPrivateFieldGet unknown, V>( + receiver: T, + state: T, + kind: "a", + f: () => V +): V; + +/** + * Emulates reading a private instance method. + * + * @param receiver The instance from which to read a private method. + * @param state A WeakSet used to verify an instance supports the private method. + * @param kind Either `"f"` for a field, `"a"` for an accessor, or `"m"` for a method. + * @param f The function to return as the private instance method. + * + * @throws {TypeError} If `state` doesn't have an entry for `receiver`. + */ +export declare function __classPrivateFieldGet unknown>( + receiver: T, + state: { has(o: T): boolean }, + kind: "m", + f: V +): V; + +/** + * Emulates reading a private static method. + * + * @param receiver The object from which to read the private static method. + * @param state The class constructor containing the definition of the static method. + * @param kind Either `"f"` for a field, `"a"` for an accessor, or `"m"` for a method. + * @param f The function to return as the private static method. + * + * @throws {TypeError} If `receiver` is not `state`. + */ +export declare function __classPrivateFieldGet unknown, V extends (...args: any[]) => unknown>( + receiver: T, + state: T, + kind: "m", + f: V +): V; + +/** + * Emulates writing to a private instance field. + * + * @param receiver The instance on which to set a private field value. + * @param state A WeakMap used to store the private field value for an instance. + * @param value The value to store in the private field. + * @param kind Either `"f"` for a field, `"a"` for an accessor, or `"m"` for a method. + * + * @throws {TypeError} If `state` doesn't have an entry for `receiver`. + */ +export declare function __classPrivateFieldSet( + receiver: T, + state: { has(o: T): boolean, set(o: T, value: V): unknown }, + value: V, + kind?: "f" +): V; + +/** + * Emulates writing to a private static field. + * + * @param receiver The object on which to set the private static field. + * @param state The class constructor containing the definition of the private static field. + * @param value The value to store in the private field. + * @param kind Either `"f"` for a field, `"a"` for an accessor, or `"m"` for a method. + * @param f The descriptor that holds the static field value. + * + * @throws {TypeError} If `receiver` is not `state`. + */ +export declare function __classPrivateFieldSet unknown, V>( + receiver: T, + state: T, + value: V, + kind: "f", + f: { value: V } +): V; + +/** + * Emulates writing to a private instance "set" accessor. + * + * @param receiver The instance on which to evaluate the private instance "set" accessor. + * @param state A WeakSet used to verify an instance supports the private "set" accessor. + * @param value The value to store in the private accessor. + * @param kind Either `"f"` for a field, `"a"` for an accessor, or `"m"` for a method. + * @param f The "set" accessor function to evaluate. + * + * @throws {TypeError} If `state` doesn't have an entry for `receiver`. + */ +export declare function __classPrivateFieldSet( + receiver: T, + state: { has(o: T): boolean }, + value: V, + kind: "a", + f: (v: V) => void +): V; + +/** + * Emulates writing to a private static "set" accessor. + * + * @param receiver The object on which to evaluate the private static "set" accessor. + * @param state The class constructor containing the definition of the static "set" accessor. + * @param value The value to store in the private field. + * @param kind Either `"f"` for a field, `"a"` for an accessor, or `"m"` for a method. + * @param f The "set" accessor function to evaluate. + * + * @throws {TypeError} If `receiver` is not `state`. + */ +export declare function __classPrivateFieldSet unknown, V>( + receiver: T, + state: T, + value: V, + kind: "a", + f: (v: V) => void +): V; + +/** + * Checks for the existence of a private field/method/accessor. + * + * @param state The class constructor containing the static member, or the WeakMap or WeakSet associated with a private instance member. + * @param receiver The object for which to test the presence of the private member. + */ +export declare function __classPrivateFieldIn( + state: (new (...args: any[]) => unknown) | { has(o: any): boolean }, + receiver: unknown, +): boolean; + +/** + * Creates a re-export binding on `object` with key `objectKey` that references `target[key]`. + * + * @param object The local `exports` object. + * @param target The object to re-export from. + * @param key The property key of `target` to re-export. + * @param objectKey The property key to re-export as. Defaults to `key`. + */ +export declare function __createBinding(object: object, target: object, key: PropertyKey, objectKey?: PropertyKey): void; + +/** + * Adds a disposable resource to a resource-tracking environment object. + * @param env A resource-tracking environment object. + * @param value Either a Disposable or AsyncDisposable object, `null`, or `undefined`. + * @param async When `true`, `AsyncDisposable` resources can be added. When `false`, `AsyncDisposable` resources cannot be added. + * @returns The {@link value} argument. + * + * @throws {TypeError} If {@link value} is not an object, or if either `Symbol.dispose` or `Symbol.asyncDispose` are not + * defined, or if {@link value} does not have an appropriate `Symbol.dispose` or `Symbol.asyncDispose` method. + */ +export declare function __addDisposableResource(env: { stack: { value?: unknown, dispose?: Function, async: boolean }[]; error: unknown; hasError: boolean; }, value: T, async: boolean): T; + +/** + * Disposes all resources in a resource-tracking environment object. + * @param env A resource-tracking environment object. + * @returns A {@link Promise} if any resources in the environment were marked as `async` when added; otherwise, `void`. + * + * @throws {SuppressedError} if an error thrown during disposal would have suppressed a prior error from disposal or the + * error recorded in the resource-tracking environment object. + * @seealso {@link __addDisposableResource} + */ +export declare function __disposeResources(env: { stack: { value?: unknown, dispose?: Function, async: boolean }[]; error: unknown; hasError: boolean; }): any; + +/** + * Transforms a relative import specifier ending in a non-declaration TypeScript file extension to its JavaScript file extension counterpart. + * @param path The import specifier. + * @param preserveJsx Causes '*.tsx' to transform to '*.jsx' instead of '*.js'. Should be true when `--jsx` is set to `preserve`. + */ +export declare function __rewriteRelativeImportExtension(path: string, preserveJsx?: boolean): string; \ No newline at end of file diff --git a/dg-ui/node_modules/@tailwindcss/oxide-wasm32-wasi/node_modules/tslib/tslib.es6.html b/dg-ui/node_modules/@tailwindcss/oxide-wasm32-wasi/node_modules/tslib/tslib.es6.html new file mode 100644 index 0000000..b122e41 --- /dev/null +++ b/dg-ui/node_modules/@tailwindcss/oxide-wasm32-wasi/node_modules/tslib/tslib.es6.html @@ -0,0 +1 @@ + \ No newline at end of file diff --git a/dg-ui/node_modules/@tailwindcss/oxide-wasm32-wasi/node_modules/tslib/tslib.es6.js b/dg-ui/node_modules/@tailwindcss/oxide-wasm32-wasi/node_modules/tslib/tslib.es6.js new file mode 100644 index 0000000..67ba5c5 --- /dev/null +++ b/dg-ui/node_modules/@tailwindcss/oxide-wasm32-wasi/node_modules/tslib/tslib.es6.js @@ -0,0 +1,402 @@ +/****************************************************************************** +Copyright (c) Microsoft Corporation. + +Permission to use, copy, modify, and/or distribute this software for any +purpose with or without fee is hereby granted. + +THE SOFTWARE IS PROVIDED "AS IS" AND THE AUTHOR DISCLAIMS ALL WARRANTIES WITH +REGARD TO THIS SOFTWARE INCLUDING ALL IMPLIED WARRANTIES OF MERCHANTABILITY +AND FITNESS. IN NO EVENT SHALL THE AUTHOR BE LIABLE FOR ANY SPECIAL, DIRECT, +INDIRECT, OR CONSEQUENTIAL DAMAGES OR ANY DAMAGES WHATSOEVER RESULTING FROM +LOSS OF USE, DATA OR PROFITS, WHETHER IN AN ACTION OF CONTRACT, NEGLIGENCE OR +OTHER TORTIOUS ACTION, ARISING OUT OF OR IN CONNECTION WITH THE USE OR +PERFORMANCE OF THIS SOFTWARE. +***************************************************************************** */ +/* global Reflect, Promise, SuppressedError, Symbol, Iterator */ + +var extendStatics = function(d, b) { + extendStatics = Object.setPrototypeOf || + ({ __proto__: [] } instanceof Array && function (d, b) { d.__proto__ = b; }) || + function (d, b) { for (var p in b) if (Object.prototype.hasOwnProperty.call(b, p)) d[p] = b[p]; }; + return extendStatics(d, b); +}; + +export function __extends(d, b) { + if (typeof b !== "function" && b !== null) + throw new TypeError("Class extends value " + String(b) + " is not a constructor or null"); + extendStatics(d, b); + function __() { this.constructor = d; } + d.prototype = b === null ? Object.create(b) : (__.prototype = b.prototype, new __()); +} + +export var __assign = function() { + __assign = Object.assign || function __assign(t) { + for (var s, i = 1, n = arguments.length; i < n; i++) { + s = arguments[i]; + for (var p in s) if (Object.prototype.hasOwnProperty.call(s, p)) t[p] = s[p]; + } + return t; + } + return __assign.apply(this, arguments); +} + +export function __rest(s, e) { + var t = {}; + for (var p in s) if (Object.prototype.hasOwnProperty.call(s, p) && e.indexOf(p) < 0) + t[p] = s[p]; + if (s != null && typeof Object.getOwnPropertySymbols === "function") + for (var i = 0, p = Object.getOwnPropertySymbols(s); i < p.length; i++) { + if (e.indexOf(p[i]) < 0 && Object.prototype.propertyIsEnumerable.call(s, p[i])) + t[p[i]] = s[p[i]]; + } + return t; +} + +export function __decorate(decorators, target, key, desc) { + var c = arguments.length, r = c < 3 ? target : desc === null ? desc = Object.getOwnPropertyDescriptor(target, key) : desc, d; + if (typeof Reflect === "object" && typeof Reflect.decorate === "function") r = Reflect.decorate(decorators, target, key, desc); + else for (var i = decorators.length - 1; i >= 0; i--) if (d = decorators[i]) r = (c < 3 ? d(r) : c > 3 ? d(target, key, r) : d(target, key)) || r; + return c > 3 && r && Object.defineProperty(target, key, r), r; +} + +export function __param(paramIndex, decorator) { + return function (target, key) { decorator(target, key, paramIndex); } +} + +export function __esDecorate(ctor, descriptorIn, decorators, contextIn, initializers, extraInitializers) { + function accept(f) { if (f !== void 0 && typeof f !== "function") throw new TypeError("Function expected"); return f; } + var kind = contextIn.kind, key = kind === "getter" ? "get" : kind === "setter" ? "set" : "value"; + var target = !descriptorIn && ctor ? contextIn["static"] ? ctor : ctor.prototype : null; + var descriptor = descriptorIn || (target ? Object.getOwnPropertyDescriptor(target, contextIn.name) : {}); + var _, done = false; + for (var i = decorators.length - 1; i >= 0; i--) { + var context = {}; + for (var p in contextIn) context[p] = p === "access" ? {} : contextIn[p]; + for (var p in contextIn.access) context.access[p] = contextIn.access[p]; + context.addInitializer = function (f) { if (done) throw new TypeError("Cannot add initializers after decoration has completed"); extraInitializers.push(accept(f || null)); }; + var result = (0, decorators[i])(kind === "accessor" ? { get: descriptor.get, set: descriptor.set } : descriptor[key], context); + if (kind === "accessor") { + if (result === void 0) continue; + if (result === null || typeof result !== "object") throw new TypeError("Object expected"); + if (_ = accept(result.get)) descriptor.get = _; + if (_ = accept(result.set)) descriptor.set = _; + if (_ = accept(result.init)) initializers.unshift(_); + } + else if (_ = accept(result)) { + if (kind === "field") initializers.unshift(_); + else descriptor[key] = _; + } + } + if (target) Object.defineProperty(target, contextIn.name, descriptor); + done = true; +}; + +export function __runInitializers(thisArg, initializers, value) { + var useValue = arguments.length > 2; + for (var i = 0; i < initializers.length; i++) { + value = useValue ? initializers[i].call(thisArg, value) : initializers[i].call(thisArg); + } + return useValue ? value : void 0; +}; + +export function __propKey(x) { + return typeof x === "symbol" ? x : "".concat(x); +}; + +export function __setFunctionName(f, name, prefix) { + if (typeof name === "symbol") name = name.description ? "[".concat(name.description, "]") : ""; + return Object.defineProperty(f, "name", { configurable: true, value: prefix ? "".concat(prefix, " ", name) : name }); +}; + +export function __metadata(metadataKey, metadataValue) { + if (typeof Reflect === "object" && typeof Reflect.metadata === "function") return Reflect.metadata(metadataKey, metadataValue); +} + +export function __awaiter(thisArg, _arguments, P, generator) { + function adopt(value) { return value instanceof P ? value : new P(function (resolve) { resolve(value); }); } + return new (P || (P = Promise))(function (resolve, reject) { + function fulfilled(value) { try { step(generator.next(value)); } catch (e) { reject(e); } } + function rejected(value) { try { step(generator["throw"](value)); } catch (e) { reject(e); } } + function step(result) { result.done ? resolve(result.value) : adopt(result.value).then(fulfilled, rejected); } + step((generator = generator.apply(thisArg, _arguments || [])).next()); + }); +} + +export function __generator(thisArg, body) { + var _ = { label: 0, sent: function() { if (t[0] & 1) throw t[1]; return t[1]; }, trys: [], ops: [] }, f, y, t, g = Object.create((typeof Iterator === "function" ? Iterator : Object).prototype); + return g.next = verb(0), g["throw"] = verb(1), g["return"] = verb(2), typeof Symbol === "function" && (g[Symbol.iterator] = function() { return this; }), g; + function verb(n) { return function (v) { return step([n, v]); }; } + function step(op) { + if (f) throw new TypeError("Generator is already executing."); + while (g && (g = 0, op[0] && (_ = 0)), _) try { + if (f = 1, y && (t = op[0] & 2 ? y["return"] : op[0] ? y["throw"] || ((t = y["return"]) && t.call(y), 0) : y.next) && !(t = t.call(y, op[1])).done) return t; + if (y = 0, t) op = [op[0] & 2, t.value]; + switch (op[0]) { + case 0: case 1: t = op; break; + case 4: _.label++; return { value: op[1], done: false }; + case 5: _.label++; y = op[1]; op = [0]; continue; + case 7: op = _.ops.pop(); _.trys.pop(); continue; + default: + if (!(t = _.trys, t = t.length > 0 && t[t.length - 1]) && (op[0] === 6 || op[0] === 2)) { _ = 0; continue; } + if (op[0] === 3 && (!t || (op[1] > t[0] && op[1] < t[3]))) { _.label = op[1]; break; } + if (op[0] === 6 && _.label < t[1]) { _.label = t[1]; t = op; break; } + if (t && _.label < t[2]) { _.label = t[2]; _.ops.push(op); break; } + if (t[2]) _.ops.pop(); + _.trys.pop(); continue; + } + op = body.call(thisArg, _); + } catch (e) { op = [6, e]; y = 0; } finally { f = t = 0; } + if (op[0] & 5) throw op[1]; return { value: op[0] ? op[1] : void 0, done: true }; + } +} + +export var __createBinding = Object.create ? (function(o, m, k, k2) { + if (k2 === undefined) k2 = k; + var desc = Object.getOwnPropertyDescriptor(m, k); + if (!desc || ("get" in desc ? !m.__esModule : desc.writable || desc.configurable)) { + desc = { enumerable: true, get: function() { return m[k]; } }; + } + Object.defineProperty(o, k2, desc); +}) : (function(o, m, k, k2) { + if (k2 === undefined) k2 = k; + o[k2] = m[k]; +}); + +export function __exportStar(m, o) { + for (var p in m) if (p !== "default" && !Object.prototype.hasOwnProperty.call(o, p)) __createBinding(o, m, p); +} + +export function __values(o) { + var s = typeof Symbol === "function" && Symbol.iterator, m = s && o[s], i = 0; + if (m) return m.call(o); + if (o && typeof o.length === "number") return { + next: function () { + if (o && i >= o.length) o = void 0; + return { value: o && o[i++], done: !o }; + } + }; + throw new TypeError(s ? "Object is not iterable." : "Symbol.iterator is not defined."); +} + +export function __read(o, n) { + var m = typeof Symbol === "function" && o[Symbol.iterator]; + if (!m) return o; + var i = m.call(o), r, ar = [], e; + try { + while ((n === void 0 || n-- > 0) && !(r = i.next()).done) ar.push(r.value); + } + catch (error) { e = { error: error }; } + finally { + try { + if (r && !r.done && (m = i["return"])) m.call(i); + } + finally { if (e) throw e.error; } + } + return ar; +} + +/** @deprecated */ +export function __spread() { + for (var ar = [], i = 0; i < arguments.length; i++) + ar = ar.concat(__read(arguments[i])); + return ar; +} + +/** @deprecated */ +export function __spreadArrays() { + for (var s = 0, i = 0, il = arguments.length; i < il; i++) s += arguments[i].length; + for (var r = Array(s), k = 0, i = 0; i < il; i++) + for (var a = arguments[i], j = 0, jl = a.length; j < jl; j++, k++) + r[k] = a[j]; + return r; +} + +export function __spreadArray(to, from, pack) { + if (pack || arguments.length === 2) for (var i = 0, l = from.length, ar; i < l; i++) { + if (ar || !(i in from)) { + if (!ar) ar = Array.prototype.slice.call(from, 0, i); + ar[i] = from[i]; + } + } + return to.concat(ar || Array.prototype.slice.call(from)); +} + +export function __await(v) { + return this instanceof __await ? (this.v = v, this) : new __await(v); +} + +export function __asyncGenerator(thisArg, _arguments, generator) { + if (!Symbol.asyncIterator) throw new TypeError("Symbol.asyncIterator is not defined."); + var g = generator.apply(thisArg, _arguments || []), i, q = []; + return i = Object.create((typeof AsyncIterator === "function" ? AsyncIterator : Object).prototype), verb("next"), verb("throw"), verb("return", awaitReturn), i[Symbol.asyncIterator] = function () { return this; }, i; + function awaitReturn(f) { return function (v) { return Promise.resolve(v).then(f, reject); }; } + function verb(n, f) { if (g[n]) { i[n] = function (v) { return new Promise(function (a, b) { q.push([n, v, a, b]) > 1 || resume(n, v); }); }; if (f) i[n] = f(i[n]); } } + function resume(n, v) { try { step(g[n](v)); } catch (e) { settle(q[0][3], e); } } + function step(r) { r.value instanceof __await ? Promise.resolve(r.value.v).then(fulfill, reject) : settle(q[0][2], r); } + function fulfill(value) { resume("next", value); } + function reject(value) { resume("throw", value); } + function settle(f, v) { if (f(v), q.shift(), q.length) resume(q[0][0], q[0][1]); } +} + +export function __asyncDelegator(o) { + var i, p; + return i = {}, verb("next"), verb("throw", function (e) { throw e; }), verb("return"), i[Symbol.iterator] = function () { return this; }, i; + function verb(n, f) { i[n] = o[n] ? function (v) { return (p = !p) ? { value: __await(o[n](v)), done: false } : f ? f(v) : v; } : f; } +} + +export function __asyncValues(o) { + if (!Symbol.asyncIterator) throw new TypeError("Symbol.asyncIterator is not defined."); + var m = o[Symbol.asyncIterator], i; + return m ? m.call(o) : (o = typeof __values === "function" ? __values(o) : o[Symbol.iterator](), i = {}, verb("next"), verb("throw"), verb("return"), i[Symbol.asyncIterator] = function () { return this; }, i); + function verb(n) { i[n] = o[n] && function (v) { return new Promise(function (resolve, reject) { v = o[n](v), settle(resolve, reject, v.done, v.value); }); }; } + function settle(resolve, reject, d, v) { Promise.resolve(v).then(function(v) { resolve({ value: v, done: d }); }, reject); } +} + +export function __makeTemplateObject(cooked, raw) { + if (Object.defineProperty) { Object.defineProperty(cooked, "raw", { value: raw }); } else { cooked.raw = raw; } + return cooked; +}; + +var __setModuleDefault = Object.create ? (function(o, v) { + Object.defineProperty(o, "default", { enumerable: true, value: v }); +}) : function(o, v) { + o["default"] = v; +}; + +var ownKeys = function(o) { + ownKeys = Object.getOwnPropertyNames || function (o) { + var ar = []; + for (var k in o) if (Object.prototype.hasOwnProperty.call(o, k)) ar[ar.length] = k; + return ar; + }; + return ownKeys(o); +}; + +export function __importStar(mod) { + if (mod && mod.__esModule) return mod; + var result = {}; + if (mod != null) for (var k = ownKeys(mod), i = 0; i < k.length; i++) if (k[i] !== "default") __createBinding(result, mod, k[i]); + __setModuleDefault(result, mod); + return result; +} + +export function __importDefault(mod) { + return (mod && mod.__esModule) ? mod : { default: mod }; +} + +export function __classPrivateFieldGet(receiver, state, kind, f) { + if (kind === "a" && !f) throw new TypeError("Private accessor was defined without a getter"); + if (typeof state === "function" ? receiver !== state || !f : !state.has(receiver)) throw new TypeError("Cannot read private member from an object whose class did not declare it"); + return kind === "m" ? f : kind === "a" ? f.call(receiver) : f ? f.value : state.get(receiver); +} + +export function __classPrivateFieldSet(receiver, state, value, kind, f) { + if (kind === "m") throw new TypeError("Private method is not writable"); + if (kind === "a" && !f) throw new TypeError("Private accessor was defined without a setter"); + if (typeof state === "function" ? receiver !== state || !f : !state.has(receiver)) throw new TypeError("Cannot write private member to an object whose class did not declare it"); + return (kind === "a" ? f.call(receiver, value) : f ? f.value = value : state.set(receiver, value)), value; +} + +export function __classPrivateFieldIn(state, receiver) { + if (receiver === null || (typeof receiver !== "object" && typeof receiver !== "function")) throw new TypeError("Cannot use 'in' operator on non-object"); + return typeof state === "function" ? receiver === state : state.has(receiver); +} + +export function __addDisposableResource(env, value, async) { + if (value !== null && value !== void 0) { + if (typeof value !== "object" && typeof value !== "function") throw new TypeError("Object expected."); + var dispose, inner; + if (async) { + if (!Symbol.asyncDispose) throw new TypeError("Symbol.asyncDispose is not defined."); + dispose = value[Symbol.asyncDispose]; + } + if (dispose === void 0) { + if (!Symbol.dispose) throw new TypeError("Symbol.dispose is not defined."); + dispose = value[Symbol.dispose]; + if (async) inner = dispose; + } + if (typeof dispose !== "function") throw new TypeError("Object not disposable."); + if (inner) dispose = function() { try { inner.call(this); } catch (e) { return Promise.reject(e); } }; + env.stack.push({ value: value, dispose: dispose, async: async }); + } + else if (async) { + env.stack.push({ async: true }); + } + return value; + +} + +var _SuppressedError = typeof SuppressedError === "function" ? SuppressedError : function (error, suppressed, message) { + var e = new Error(message); + return e.name = "SuppressedError", e.error = error, e.suppressed = suppressed, e; +}; + +export function __disposeResources(env) { + function fail(e) { + env.error = env.hasError ? new _SuppressedError(e, env.error, "An error was suppressed during disposal.") : e; + env.hasError = true; + } + var r, s = 0; + function next() { + while (r = env.stack.pop()) { + try { + if (!r.async && s === 1) return s = 0, env.stack.push(r), Promise.resolve().then(next); + if (r.dispose) { + var result = r.dispose.call(r.value); + if (r.async) return s |= 2, Promise.resolve(result).then(next, function(e) { fail(e); return next(); }); + } + else s |= 1; + } + catch (e) { + fail(e); + } + } + if (s === 1) return env.hasError ? Promise.reject(env.error) : Promise.resolve(); + if (env.hasError) throw env.error; + } + return next(); +} + +export function __rewriteRelativeImportExtension(path, preserveJsx) { + if (typeof path === "string" && /^\.\.?\//.test(path)) { + return path.replace(/\.(tsx)$|((?:\.d)?)((?:\.[^./]+?)?)\.([cm]?)ts$/i, function (m, tsx, d, ext, cm) { + return tsx ? preserveJsx ? ".jsx" : ".js" : d && (!ext || !cm) ? m : (d + ext + "." + cm.toLowerCase() + "js"); + }); + } + return path; +} + +export default { + __extends: __extends, + __assign: __assign, + __rest: __rest, + __decorate: __decorate, + __param: __param, + __esDecorate: __esDecorate, + __runInitializers: __runInitializers, + __propKey: __propKey, + __setFunctionName: __setFunctionName, + __metadata: __metadata, + __awaiter: __awaiter, + __generator: __generator, + __createBinding: __createBinding, + __exportStar: __exportStar, + __values: __values, + __read: __read, + __spread: __spread, + __spreadArrays: __spreadArrays, + __spreadArray: __spreadArray, + __await: __await, + __asyncGenerator: __asyncGenerator, + __asyncDelegator: __asyncDelegator, + __asyncValues: __asyncValues, + __makeTemplateObject: __makeTemplateObject, + __importStar: __importStar, + __importDefault: __importDefault, + __classPrivateFieldGet: __classPrivateFieldGet, + __classPrivateFieldSet: __classPrivateFieldSet, + __classPrivateFieldIn: __classPrivateFieldIn, + __addDisposableResource: __addDisposableResource, + __disposeResources: __disposeResources, + __rewriteRelativeImportExtension: __rewriteRelativeImportExtension, +}; diff --git a/dg-ui/node_modules/@tailwindcss/oxide-wasm32-wasi/node_modules/tslib/tslib.es6.mjs b/dg-ui/node_modules/@tailwindcss/oxide-wasm32-wasi/node_modules/tslib/tslib.es6.mjs new file mode 100644 index 0000000..c17990a --- /dev/null +++ b/dg-ui/node_modules/@tailwindcss/oxide-wasm32-wasi/node_modules/tslib/tslib.es6.mjs @@ -0,0 +1,401 @@ +/****************************************************************************** +Copyright (c) Microsoft Corporation. + +Permission to use, copy, modify, and/or distribute this software for any +purpose with or without fee is hereby granted. + +THE SOFTWARE IS PROVIDED "AS IS" AND THE AUTHOR DISCLAIMS ALL WARRANTIES WITH +REGARD TO THIS SOFTWARE INCLUDING ALL IMPLIED WARRANTIES OF MERCHANTABILITY +AND FITNESS. IN NO EVENT SHALL THE AUTHOR BE LIABLE FOR ANY SPECIAL, DIRECT, +INDIRECT, OR CONSEQUENTIAL DAMAGES OR ANY DAMAGES WHATSOEVER RESULTING FROM +LOSS OF USE, DATA OR PROFITS, WHETHER IN AN ACTION OF CONTRACT, NEGLIGENCE OR +OTHER TORTIOUS ACTION, ARISING OUT OF OR IN CONNECTION WITH THE USE OR +PERFORMANCE OF THIS SOFTWARE. +***************************************************************************** */ +/* global Reflect, Promise, SuppressedError, Symbol, Iterator */ + +var extendStatics = function(d, b) { + extendStatics = Object.setPrototypeOf || + ({ __proto__: [] } instanceof Array && function (d, b) { d.__proto__ = b; }) || + function (d, b) { for (var p in b) if (Object.prototype.hasOwnProperty.call(b, p)) d[p] = b[p]; }; + return extendStatics(d, b); +}; + +export function __extends(d, b) { + if (typeof b !== "function" && b !== null) + throw new TypeError("Class extends value " + String(b) + " is not a constructor or null"); + extendStatics(d, b); + function __() { this.constructor = d; } + d.prototype = b === null ? Object.create(b) : (__.prototype = b.prototype, new __()); +} + +export var __assign = function() { + __assign = Object.assign || function __assign(t) { + for (var s, i = 1, n = arguments.length; i < n; i++) { + s = arguments[i]; + for (var p in s) if (Object.prototype.hasOwnProperty.call(s, p)) t[p] = s[p]; + } + return t; + } + return __assign.apply(this, arguments); +} + +export function __rest(s, e) { + var t = {}; + for (var p in s) if (Object.prototype.hasOwnProperty.call(s, p) && e.indexOf(p) < 0) + t[p] = s[p]; + if (s != null && typeof Object.getOwnPropertySymbols === "function") + for (var i = 0, p = Object.getOwnPropertySymbols(s); i < p.length; i++) { + if (e.indexOf(p[i]) < 0 && Object.prototype.propertyIsEnumerable.call(s, p[i])) + t[p[i]] = s[p[i]]; + } + return t; +} + +export function __decorate(decorators, target, key, desc) { + var c = arguments.length, r = c < 3 ? target : desc === null ? desc = Object.getOwnPropertyDescriptor(target, key) : desc, d; + if (typeof Reflect === "object" && typeof Reflect.decorate === "function") r = Reflect.decorate(decorators, target, key, desc); + else for (var i = decorators.length - 1; i >= 0; i--) if (d = decorators[i]) r = (c < 3 ? d(r) : c > 3 ? d(target, key, r) : d(target, key)) || r; + return c > 3 && r && Object.defineProperty(target, key, r), r; +} + +export function __param(paramIndex, decorator) { + return function (target, key) { decorator(target, key, paramIndex); } +} + +export function __esDecorate(ctor, descriptorIn, decorators, contextIn, initializers, extraInitializers) { + function accept(f) { if (f !== void 0 && typeof f !== "function") throw new TypeError("Function expected"); return f; } + var kind = contextIn.kind, key = kind === "getter" ? "get" : kind === "setter" ? "set" : "value"; + var target = !descriptorIn && ctor ? contextIn["static"] ? ctor : ctor.prototype : null; + var descriptor = descriptorIn || (target ? Object.getOwnPropertyDescriptor(target, contextIn.name) : {}); + var _, done = false; + for (var i = decorators.length - 1; i >= 0; i--) { + var context = {}; + for (var p in contextIn) context[p] = p === "access" ? {} : contextIn[p]; + for (var p in contextIn.access) context.access[p] = contextIn.access[p]; + context.addInitializer = function (f) { if (done) throw new TypeError("Cannot add initializers after decoration has completed"); extraInitializers.push(accept(f || null)); }; + var result = (0, decorators[i])(kind === "accessor" ? { get: descriptor.get, set: descriptor.set } : descriptor[key], context); + if (kind === "accessor") { + if (result === void 0) continue; + if (result === null || typeof result !== "object") throw new TypeError("Object expected"); + if (_ = accept(result.get)) descriptor.get = _; + if (_ = accept(result.set)) descriptor.set = _; + if (_ = accept(result.init)) initializers.unshift(_); + } + else if (_ = accept(result)) { + if (kind === "field") initializers.unshift(_); + else descriptor[key] = _; + } + } + if (target) Object.defineProperty(target, contextIn.name, descriptor); + done = true; +}; + +export function __runInitializers(thisArg, initializers, value) { + var useValue = arguments.length > 2; + for (var i = 0; i < initializers.length; i++) { + value = useValue ? initializers[i].call(thisArg, value) : initializers[i].call(thisArg); + } + return useValue ? value : void 0; +}; + +export function __propKey(x) { + return typeof x === "symbol" ? x : "".concat(x); +}; + +export function __setFunctionName(f, name, prefix) { + if (typeof name === "symbol") name = name.description ? "[".concat(name.description, "]") : ""; + return Object.defineProperty(f, "name", { configurable: true, value: prefix ? "".concat(prefix, " ", name) : name }); +}; + +export function __metadata(metadataKey, metadataValue) { + if (typeof Reflect === "object" && typeof Reflect.metadata === "function") return Reflect.metadata(metadataKey, metadataValue); +} + +export function __awaiter(thisArg, _arguments, P, generator) { + function adopt(value) { return value instanceof P ? value : new P(function (resolve) { resolve(value); }); } + return new (P || (P = Promise))(function (resolve, reject) { + function fulfilled(value) { try { step(generator.next(value)); } catch (e) { reject(e); } } + function rejected(value) { try { step(generator["throw"](value)); } catch (e) { reject(e); } } + function step(result) { result.done ? resolve(result.value) : adopt(result.value).then(fulfilled, rejected); } + step((generator = generator.apply(thisArg, _arguments || [])).next()); + }); +} + +export function __generator(thisArg, body) { + var _ = { label: 0, sent: function() { if (t[0] & 1) throw t[1]; return t[1]; }, trys: [], ops: [] }, f, y, t, g = Object.create((typeof Iterator === "function" ? Iterator : Object).prototype); + return g.next = verb(0), g["throw"] = verb(1), g["return"] = verb(2), typeof Symbol === "function" && (g[Symbol.iterator] = function() { return this; }), g; + function verb(n) { return function (v) { return step([n, v]); }; } + function step(op) { + if (f) throw new TypeError("Generator is already executing."); + while (g && (g = 0, op[0] && (_ = 0)), _) try { + if (f = 1, y && (t = op[0] & 2 ? y["return"] : op[0] ? y["throw"] || ((t = y["return"]) && t.call(y), 0) : y.next) && !(t = t.call(y, op[1])).done) return t; + if (y = 0, t) op = [op[0] & 2, t.value]; + switch (op[0]) { + case 0: case 1: t = op; break; + case 4: _.label++; return { value: op[1], done: false }; + case 5: _.label++; y = op[1]; op = [0]; continue; + case 7: op = _.ops.pop(); _.trys.pop(); continue; + default: + if (!(t = _.trys, t = t.length > 0 && t[t.length - 1]) && (op[0] === 6 || op[0] === 2)) { _ = 0; continue; } + if (op[0] === 3 && (!t || (op[1] > t[0] && op[1] < t[3]))) { _.label = op[1]; break; } + if (op[0] === 6 && _.label < t[1]) { _.label = t[1]; t = op; break; } + if (t && _.label < t[2]) { _.label = t[2]; _.ops.push(op); break; } + if (t[2]) _.ops.pop(); + _.trys.pop(); continue; + } + op = body.call(thisArg, _); + } catch (e) { op = [6, e]; y = 0; } finally { f = t = 0; } + if (op[0] & 5) throw op[1]; return { value: op[0] ? op[1] : void 0, done: true }; + } +} + +export var __createBinding = Object.create ? (function(o, m, k, k2) { + if (k2 === undefined) k2 = k; + var desc = Object.getOwnPropertyDescriptor(m, k); + if (!desc || ("get" in desc ? !m.__esModule : desc.writable || desc.configurable)) { + desc = { enumerable: true, get: function() { return m[k]; } }; + } + Object.defineProperty(o, k2, desc); +}) : (function(o, m, k, k2) { + if (k2 === undefined) k2 = k; + o[k2] = m[k]; +}); + +export function __exportStar(m, o) { + for (var p in m) if (p !== "default" && !Object.prototype.hasOwnProperty.call(o, p)) __createBinding(o, m, p); +} + +export function __values(o) { + var s = typeof Symbol === "function" && Symbol.iterator, m = s && o[s], i = 0; + if (m) return m.call(o); + if (o && typeof o.length === "number") return { + next: function () { + if (o && i >= o.length) o = void 0; + return { value: o && o[i++], done: !o }; + } + }; + throw new TypeError(s ? "Object is not iterable." : "Symbol.iterator is not defined."); +} + +export function __read(o, n) { + var m = typeof Symbol === "function" && o[Symbol.iterator]; + if (!m) return o; + var i = m.call(o), r, ar = [], e; + try { + while ((n === void 0 || n-- > 0) && !(r = i.next()).done) ar.push(r.value); + } + catch (error) { e = { error: error }; } + finally { + try { + if (r && !r.done && (m = i["return"])) m.call(i); + } + finally { if (e) throw e.error; } + } + return ar; +} + +/** @deprecated */ +export function __spread() { + for (var ar = [], i = 0; i < arguments.length; i++) + ar = ar.concat(__read(arguments[i])); + return ar; +} + +/** @deprecated */ +export function __spreadArrays() { + for (var s = 0, i = 0, il = arguments.length; i < il; i++) s += arguments[i].length; + for (var r = Array(s), k = 0, i = 0; i < il; i++) + for (var a = arguments[i], j = 0, jl = a.length; j < jl; j++, k++) + r[k] = a[j]; + return r; +} + +export function __spreadArray(to, from, pack) { + if (pack || arguments.length === 2) for (var i = 0, l = from.length, ar; i < l; i++) { + if (ar || !(i in from)) { + if (!ar) ar = Array.prototype.slice.call(from, 0, i); + ar[i] = from[i]; + } + } + return to.concat(ar || Array.prototype.slice.call(from)); +} + +export function __await(v) { + return this instanceof __await ? (this.v = v, this) : new __await(v); +} + +export function __asyncGenerator(thisArg, _arguments, generator) { + if (!Symbol.asyncIterator) throw new TypeError("Symbol.asyncIterator is not defined."); + var g = generator.apply(thisArg, _arguments || []), i, q = []; + return i = Object.create((typeof AsyncIterator === "function" ? AsyncIterator : Object).prototype), verb("next"), verb("throw"), verb("return", awaitReturn), i[Symbol.asyncIterator] = function () { return this; }, i; + function awaitReturn(f) { return function (v) { return Promise.resolve(v).then(f, reject); }; } + function verb(n, f) { if (g[n]) { i[n] = function (v) { return new Promise(function (a, b) { q.push([n, v, a, b]) > 1 || resume(n, v); }); }; if (f) i[n] = f(i[n]); } } + function resume(n, v) { try { step(g[n](v)); } catch (e) { settle(q[0][3], e); } } + function step(r) { r.value instanceof __await ? Promise.resolve(r.value.v).then(fulfill, reject) : settle(q[0][2], r); } + function fulfill(value) { resume("next", value); } + function reject(value) { resume("throw", value); } + function settle(f, v) { if (f(v), q.shift(), q.length) resume(q[0][0], q[0][1]); } +} + +export function __asyncDelegator(o) { + var i, p; + return i = {}, verb("next"), verb("throw", function (e) { throw e; }), verb("return"), i[Symbol.iterator] = function () { return this; }, i; + function verb(n, f) { i[n] = o[n] ? function (v) { return (p = !p) ? { value: __await(o[n](v)), done: false } : f ? f(v) : v; } : f; } +} + +export function __asyncValues(o) { + if (!Symbol.asyncIterator) throw new TypeError("Symbol.asyncIterator is not defined."); + var m = o[Symbol.asyncIterator], i; + return m ? m.call(o) : (o = typeof __values === "function" ? __values(o) : o[Symbol.iterator](), i = {}, verb("next"), verb("throw"), verb("return"), i[Symbol.asyncIterator] = function () { return this; }, i); + function verb(n) { i[n] = o[n] && function (v) { return new Promise(function (resolve, reject) { v = o[n](v), settle(resolve, reject, v.done, v.value); }); }; } + function settle(resolve, reject, d, v) { Promise.resolve(v).then(function(v) { resolve({ value: v, done: d }); }, reject); } +} + +export function __makeTemplateObject(cooked, raw) { + if (Object.defineProperty) { Object.defineProperty(cooked, "raw", { value: raw }); } else { cooked.raw = raw; } + return cooked; +}; + +var __setModuleDefault = Object.create ? (function(o, v) { + Object.defineProperty(o, "default", { enumerable: true, value: v }); +}) : function(o, v) { + o["default"] = v; +}; + +var ownKeys = function(o) { + ownKeys = Object.getOwnPropertyNames || function (o) { + var ar = []; + for (var k in o) if (Object.prototype.hasOwnProperty.call(o, k)) ar[ar.length] = k; + return ar; + }; + return ownKeys(o); +}; + +export function __importStar(mod) { + if (mod && mod.__esModule) return mod; + var result = {}; + if (mod != null) for (var k = ownKeys(mod), i = 0; i < k.length; i++) if (k[i] !== "default") __createBinding(result, mod, k[i]); + __setModuleDefault(result, mod); + return result; +} + +export function __importDefault(mod) { + return (mod && mod.__esModule) ? mod : { default: mod }; +} + +export function __classPrivateFieldGet(receiver, state, kind, f) { + if (kind === "a" && !f) throw new TypeError("Private accessor was defined without a getter"); + if (typeof state === "function" ? receiver !== state || !f : !state.has(receiver)) throw new TypeError("Cannot read private member from an object whose class did not declare it"); + return kind === "m" ? f : kind === "a" ? f.call(receiver) : f ? f.value : state.get(receiver); +} + +export function __classPrivateFieldSet(receiver, state, value, kind, f) { + if (kind === "m") throw new TypeError("Private method is not writable"); + if (kind === "a" && !f) throw new TypeError("Private accessor was defined without a setter"); + if (typeof state === "function" ? receiver !== state || !f : !state.has(receiver)) throw new TypeError("Cannot write private member to an object whose class did not declare it"); + return (kind === "a" ? f.call(receiver, value) : f ? f.value = value : state.set(receiver, value)), value; +} + +export function __classPrivateFieldIn(state, receiver) { + if (receiver === null || (typeof receiver !== "object" && typeof receiver !== "function")) throw new TypeError("Cannot use 'in' operator on non-object"); + return typeof state === "function" ? receiver === state : state.has(receiver); +} + +export function __addDisposableResource(env, value, async) { + if (value !== null && value !== void 0) { + if (typeof value !== "object" && typeof value !== "function") throw new TypeError("Object expected."); + var dispose, inner; + if (async) { + if (!Symbol.asyncDispose) throw new TypeError("Symbol.asyncDispose is not defined."); + dispose = value[Symbol.asyncDispose]; + } + if (dispose === void 0) { + if (!Symbol.dispose) throw new TypeError("Symbol.dispose is not defined."); + dispose = value[Symbol.dispose]; + if (async) inner = dispose; + } + if (typeof dispose !== "function") throw new TypeError("Object not disposable."); + if (inner) dispose = function() { try { inner.call(this); } catch (e) { return Promise.reject(e); } }; + env.stack.push({ value: value, dispose: dispose, async: async }); + } + else if (async) { + env.stack.push({ async: true }); + } + return value; +} + +var _SuppressedError = typeof SuppressedError === "function" ? SuppressedError : function (error, suppressed, message) { + var e = new Error(message); + return e.name = "SuppressedError", e.error = error, e.suppressed = suppressed, e; +}; + +export function __disposeResources(env) { + function fail(e) { + env.error = env.hasError ? new _SuppressedError(e, env.error, "An error was suppressed during disposal.") : e; + env.hasError = true; + } + var r, s = 0; + function next() { + while (r = env.stack.pop()) { + try { + if (!r.async && s === 1) return s = 0, env.stack.push(r), Promise.resolve().then(next); + if (r.dispose) { + var result = r.dispose.call(r.value); + if (r.async) return s |= 2, Promise.resolve(result).then(next, function(e) { fail(e); return next(); }); + } + else s |= 1; + } + catch (e) { + fail(e); + } + } + if (s === 1) return env.hasError ? Promise.reject(env.error) : Promise.resolve(); + if (env.hasError) throw env.error; + } + return next(); +} + +export function __rewriteRelativeImportExtension(path, preserveJsx) { + if (typeof path === "string" && /^\.\.?\//.test(path)) { + return path.replace(/\.(tsx)$|((?:\.d)?)((?:\.[^./]+?)?)\.([cm]?)ts$/i, function (m, tsx, d, ext, cm) { + return tsx ? preserveJsx ? ".jsx" : ".js" : d && (!ext || !cm) ? m : (d + ext + "." + cm.toLowerCase() + "js"); + }); + } + return path; +} + +export default { + __extends, + __assign, + __rest, + __decorate, + __param, + __esDecorate, + __runInitializers, + __propKey, + __setFunctionName, + __metadata, + __awaiter, + __generator, + __createBinding, + __exportStar, + __values, + __read, + __spread, + __spreadArrays, + __spreadArray, + __await, + __asyncGenerator, + __asyncDelegator, + __asyncValues, + __makeTemplateObject, + __importStar, + __importDefault, + __classPrivateFieldGet, + __classPrivateFieldSet, + __classPrivateFieldIn, + __addDisposableResource, + __disposeResources, + __rewriteRelativeImportExtension, +}; diff --git a/dg-ui/node_modules/@tailwindcss/oxide-wasm32-wasi/node_modules/tslib/tslib.html b/dg-ui/node_modules/@tailwindcss/oxide-wasm32-wasi/node_modules/tslib/tslib.html new file mode 100644 index 0000000..44c9ba5 --- /dev/null +++ b/dg-ui/node_modules/@tailwindcss/oxide-wasm32-wasi/node_modules/tslib/tslib.html @@ -0,0 +1 @@ + \ No newline at end of file diff --git a/dg-ui/node_modules/@tailwindcss/oxide-wasm32-wasi/node_modules/tslib/tslib.js b/dg-ui/node_modules/@tailwindcss/oxide-wasm32-wasi/node_modules/tslib/tslib.js new file mode 100644 index 0000000..b6509f7 --- /dev/null +++ b/dg-ui/node_modules/@tailwindcss/oxide-wasm32-wasi/node_modules/tslib/tslib.js @@ -0,0 +1,484 @@ +/****************************************************************************** +Copyright (c) Microsoft Corporation. + +Permission to use, copy, modify, and/or distribute this software for any +purpose with or without fee is hereby granted. + +THE SOFTWARE IS PROVIDED "AS IS" AND THE AUTHOR DISCLAIMS ALL WARRANTIES WITH +REGARD TO THIS SOFTWARE INCLUDING ALL IMPLIED WARRANTIES OF MERCHANTABILITY +AND FITNESS. IN NO EVENT SHALL THE AUTHOR BE LIABLE FOR ANY SPECIAL, DIRECT, +INDIRECT, OR CONSEQUENTIAL DAMAGES OR ANY DAMAGES WHATSOEVER RESULTING FROM +LOSS OF USE, DATA OR PROFITS, WHETHER IN AN ACTION OF CONTRACT, NEGLIGENCE OR +OTHER TORTIOUS ACTION, ARISING OUT OF OR IN CONNECTION WITH THE USE OR +PERFORMANCE OF THIS SOFTWARE. +***************************************************************************** */ +/* global global, define, Symbol, Reflect, Promise, SuppressedError, Iterator */ +var __extends; +var __assign; +var __rest; +var __decorate; +var __param; +var __esDecorate; +var __runInitializers; +var __propKey; +var __setFunctionName; +var __metadata; +var __awaiter; +var __generator; +var __exportStar; +var __values; +var __read; +var __spread; +var __spreadArrays; +var __spreadArray; +var __await; +var __asyncGenerator; +var __asyncDelegator; +var __asyncValues; +var __makeTemplateObject; +var __importStar; +var __importDefault; +var __classPrivateFieldGet; +var __classPrivateFieldSet; +var __classPrivateFieldIn; +var __createBinding; +var __addDisposableResource; +var __disposeResources; +var __rewriteRelativeImportExtension; +(function (factory) { + var root = typeof global === "object" ? global : typeof self === "object" ? self : typeof this === "object" ? this : {}; + if (typeof define === "function" && define.amd) { + define("tslib", ["exports"], function (exports) { factory(createExporter(root, createExporter(exports))); }); + } + else if (typeof module === "object" && typeof module.exports === "object") { + factory(createExporter(root, createExporter(module.exports))); + } + else { + factory(createExporter(root)); + } + function createExporter(exports, previous) { + if (exports !== root) { + if (typeof Object.create === "function") { + Object.defineProperty(exports, "__esModule", { value: true }); + } + else { + exports.__esModule = true; + } + } + return function (id, v) { return exports[id] = previous ? previous(id, v) : v; }; + } +}) +(function (exporter) { + var extendStatics = Object.setPrototypeOf || + ({ __proto__: [] } instanceof Array && function (d, b) { d.__proto__ = b; }) || + function (d, b) { for (var p in b) if (Object.prototype.hasOwnProperty.call(b, p)) d[p] = b[p]; }; + + __extends = function (d, b) { + if (typeof b !== "function" && b !== null) + throw new TypeError("Class extends value " + String(b) + " is not a constructor or null"); + extendStatics(d, b); + function __() { this.constructor = d; } + d.prototype = b === null ? Object.create(b) : (__.prototype = b.prototype, new __()); + }; + + __assign = Object.assign || function (t) { + for (var s, i = 1, n = arguments.length; i < n; i++) { + s = arguments[i]; + for (var p in s) if (Object.prototype.hasOwnProperty.call(s, p)) t[p] = s[p]; + } + return t; + }; + + __rest = function (s, e) { + var t = {}; + for (var p in s) if (Object.prototype.hasOwnProperty.call(s, p) && e.indexOf(p) < 0) + t[p] = s[p]; + if (s != null && typeof Object.getOwnPropertySymbols === "function") + for (var i = 0, p = Object.getOwnPropertySymbols(s); i < p.length; i++) { + if (e.indexOf(p[i]) < 0 && Object.prototype.propertyIsEnumerable.call(s, p[i])) + t[p[i]] = s[p[i]]; + } + return t; + }; + + __decorate = function (decorators, target, key, desc) { + var c = arguments.length, r = c < 3 ? target : desc === null ? desc = Object.getOwnPropertyDescriptor(target, key) : desc, d; + if (typeof Reflect === "object" && typeof Reflect.decorate === "function") r = Reflect.decorate(decorators, target, key, desc); + else for (var i = decorators.length - 1; i >= 0; i--) if (d = decorators[i]) r = (c < 3 ? d(r) : c > 3 ? d(target, key, r) : d(target, key)) || r; + return c > 3 && r && Object.defineProperty(target, key, r), r; + }; + + __param = function (paramIndex, decorator) { + return function (target, key) { decorator(target, key, paramIndex); } + }; + + __esDecorate = function (ctor, descriptorIn, decorators, contextIn, initializers, extraInitializers) { + function accept(f) { if (f !== void 0 && typeof f !== "function") throw new TypeError("Function expected"); return f; } + var kind = contextIn.kind, key = kind === "getter" ? "get" : kind === "setter" ? "set" : "value"; + var target = !descriptorIn && ctor ? contextIn["static"] ? ctor : ctor.prototype : null; + var descriptor = descriptorIn || (target ? Object.getOwnPropertyDescriptor(target, contextIn.name) : {}); + var _, done = false; + for (var i = decorators.length - 1; i >= 0; i--) { + var context = {}; + for (var p in contextIn) context[p] = p === "access" ? {} : contextIn[p]; + for (var p in contextIn.access) context.access[p] = contextIn.access[p]; + context.addInitializer = function (f) { if (done) throw new TypeError("Cannot add initializers after decoration has completed"); extraInitializers.push(accept(f || null)); }; + var result = (0, decorators[i])(kind === "accessor" ? { get: descriptor.get, set: descriptor.set } : descriptor[key], context); + if (kind === "accessor") { + if (result === void 0) continue; + if (result === null || typeof result !== "object") throw new TypeError("Object expected"); + if (_ = accept(result.get)) descriptor.get = _; + if (_ = accept(result.set)) descriptor.set = _; + if (_ = accept(result.init)) initializers.unshift(_); + } + else if (_ = accept(result)) { + if (kind === "field") initializers.unshift(_); + else descriptor[key] = _; + } + } + if (target) Object.defineProperty(target, contextIn.name, descriptor); + done = true; + }; + + __runInitializers = function (thisArg, initializers, value) { + var useValue = arguments.length > 2; + for (var i = 0; i < initializers.length; i++) { + value = useValue ? initializers[i].call(thisArg, value) : initializers[i].call(thisArg); + } + return useValue ? value : void 0; + }; + + __propKey = function (x) { + return typeof x === "symbol" ? x : "".concat(x); + }; + + __setFunctionName = function (f, name, prefix) { + if (typeof name === "symbol") name = name.description ? "[".concat(name.description, "]") : ""; + return Object.defineProperty(f, "name", { configurable: true, value: prefix ? "".concat(prefix, " ", name) : name }); + }; + + __metadata = function (metadataKey, metadataValue) { + if (typeof Reflect === "object" && typeof Reflect.metadata === "function") return Reflect.metadata(metadataKey, metadataValue); + }; + + __awaiter = function (thisArg, _arguments, P, generator) { + function adopt(value) { return value instanceof P ? value : new P(function (resolve) { resolve(value); }); } + return new (P || (P = Promise))(function (resolve, reject) { + function fulfilled(value) { try { step(generator.next(value)); } catch (e) { reject(e); } } + function rejected(value) { try { step(generator["throw"](value)); } catch (e) { reject(e); } } + function step(result) { result.done ? resolve(result.value) : adopt(result.value).then(fulfilled, rejected); } + step((generator = generator.apply(thisArg, _arguments || [])).next()); + }); + }; + + __generator = function (thisArg, body) { + var _ = { label: 0, sent: function() { if (t[0] & 1) throw t[1]; return t[1]; }, trys: [], ops: [] }, f, y, t, g = Object.create((typeof Iterator === "function" ? Iterator : Object).prototype); + return g.next = verb(0), g["throw"] = verb(1), g["return"] = verb(2), typeof Symbol === "function" && (g[Symbol.iterator] = function() { return this; }), g; + function verb(n) { return function (v) { return step([n, v]); }; } + function step(op) { + if (f) throw new TypeError("Generator is already executing."); + while (g && (g = 0, op[0] && (_ = 0)), _) try { + if (f = 1, y && (t = op[0] & 2 ? y["return"] : op[0] ? y["throw"] || ((t = y["return"]) && t.call(y), 0) : y.next) && !(t = t.call(y, op[1])).done) return t; + if (y = 0, t) op = [op[0] & 2, t.value]; + switch (op[0]) { + case 0: case 1: t = op; break; + case 4: _.label++; return { value: op[1], done: false }; + case 5: _.label++; y = op[1]; op = [0]; continue; + case 7: op = _.ops.pop(); _.trys.pop(); continue; + default: + if (!(t = _.trys, t = t.length > 0 && t[t.length - 1]) && (op[0] === 6 || op[0] === 2)) { _ = 0; continue; } + if (op[0] === 3 && (!t || (op[1] > t[0] && op[1] < t[3]))) { _.label = op[1]; break; } + if (op[0] === 6 && _.label < t[1]) { _.label = t[1]; t = op; break; } + if (t && _.label < t[2]) { _.label = t[2]; _.ops.push(op); break; } + if (t[2]) _.ops.pop(); + _.trys.pop(); continue; + } + op = body.call(thisArg, _); + } catch (e) { op = [6, e]; y = 0; } finally { f = t = 0; } + if (op[0] & 5) throw op[1]; return { value: op[0] ? op[1] : void 0, done: true }; + } + }; + + __exportStar = function(m, o) { + for (var p in m) if (p !== "default" && !Object.prototype.hasOwnProperty.call(o, p)) __createBinding(o, m, p); + }; + + __createBinding = Object.create ? (function(o, m, k, k2) { + if (k2 === undefined) k2 = k; + var desc = Object.getOwnPropertyDescriptor(m, k); + if (!desc || ("get" in desc ? !m.__esModule : desc.writable || desc.configurable)) { + desc = { enumerable: true, get: function() { return m[k]; } }; + } + Object.defineProperty(o, k2, desc); + }) : (function(o, m, k, k2) { + if (k2 === undefined) k2 = k; + o[k2] = m[k]; + }); + + __values = function (o) { + var s = typeof Symbol === "function" && Symbol.iterator, m = s && o[s], i = 0; + if (m) return m.call(o); + if (o && typeof o.length === "number") return { + next: function () { + if (o && i >= o.length) o = void 0; + return { value: o && o[i++], done: !o }; + } + }; + throw new TypeError(s ? "Object is not iterable." : "Symbol.iterator is not defined."); + }; + + __read = function (o, n) { + var m = typeof Symbol === "function" && o[Symbol.iterator]; + if (!m) return o; + var i = m.call(o), r, ar = [], e; + try { + while ((n === void 0 || n-- > 0) && !(r = i.next()).done) ar.push(r.value); + } + catch (error) { e = { error: error }; } + finally { + try { + if (r && !r.done && (m = i["return"])) m.call(i); + } + finally { if (e) throw e.error; } + } + return ar; + }; + + /** @deprecated */ + __spread = function () { + for (var ar = [], i = 0; i < arguments.length; i++) + ar = ar.concat(__read(arguments[i])); + return ar; + }; + + /** @deprecated */ + __spreadArrays = function () { + for (var s = 0, i = 0, il = arguments.length; i < il; i++) s += arguments[i].length; + for (var r = Array(s), k = 0, i = 0; i < il; i++) + for (var a = arguments[i], j = 0, jl = a.length; j < jl; j++, k++) + r[k] = a[j]; + return r; + }; + + __spreadArray = function (to, from, pack) { + if (pack || arguments.length === 2) for (var i = 0, l = from.length, ar; i < l; i++) { + if (ar || !(i in from)) { + if (!ar) ar = Array.prototype.slice.call(from, 0, i); + ar[i] = from[i]; + } + } + return to.concat(ar || Array.prototype.slice.call(from)); + }; + + __await = function (v) { + return this instanceof __await ? (this.v = v, this) : new __await(v); + }; + + __asyncGenerator = function (thisArg, _arguments, generator) { + if (!Symbol.asyncIterator) throw new TypeError("Symbol.asyncIterator is not defined."); + var g = generator.apply(thisArg, _arguments || []), i, q = []; + return i = Object.create((typeof AsyncIterator === "function" ? AsyncIterator : Object).prototype), verb("next"), verb("throw"), verb("return", awaitReturn), i[Symbol.asyncIterator] = function () { return this; }, i; + function awaitReturn(f) { return function (v) { return Promise.resolve(v).then(f, reject); }; } + function verb(n, f) { if (g[n]) { i[n] = function (v) { return new Promise(function (a, b) { q.push([n, v, a, b]) > 1 || resume(n, v); }); }; if (f) i[n] = f(i[n]); } } + function resume(n, v) { try { step(g[n](v)); } catch (e) { settle(q[0][3], e); } } + function step(r) { r.value instanceof __await ? Promise.resolve(r.value.v).then(fulfill, reject) : settle(q[0][2], r); } + function fulfill(value) { resume("next", value); } + function reject(value) { resume("throw", value); } + function settle(f, v) { if (f(v), q.shift(), q.length) resume(q[0][0], q[0][1]); } + }; + + __asyncDelegator = function (o) { + var i, p; + return i = {}, verb("next"), verb("throw", function (e) { throw e; }), verb("return"), i[Symbol.iterator] = function () { return this; }, i; + function verb(n, f) { i[n] = o[n] ? function (v) { return (p = !p) ? { value: __await(o[n](v)), done: false } : f ? f(v) : v; } : f; } + }; + + __asyncValues = function (o) { + if (!Symbol.asyncIterator) throw new TypeError("Symbol.asyncIterator is not defined."); + var m = o[Symbol.asyncIterator], i; + return m ? m.call(o) : (o = typeof __values === "function" ? __values(o) : o[Symbol.iterator](), i = {}, verb("next"), verb("throw"), verb("return"), i[Symbol.asyncIterator] = function () { return this; }, i); + function verb(n) { i[n] = o[n] && function (v) { return new Promise(function (resolve, reject) { v = o[n](v), settle(resolve, reject, v.done, v.value); }); }; } + function settle(resolve, reject, d, v) { Promise.resolve(v).then(function(v) { resolve({ value: v, done: d }); }, reject); } + }; + + __makeTemplateObject = function (cooked, raw) { + if (Object.defineProperty) { Object.defineProperty(cooked, "raw", { value: raw }); } else { cooked.raw = raw; } + return cooked; + }; + + var __setModuleDefault = Object.create ? (function(o, v) { + Object.defineProperty(o, "default", { enumerable: true, value: v }); + }) : function(o, v) { + o["default"] = v; + }; + + var ownKeys = function(o) { + ownKeys = Object.getOwnPropertyNames || function (o) { + var ar = []; + for (var k in o) if (Object.prototype.hasOwnProperty.call(o, k)) ar[ar.length] = k; + return ar; + }; + return ownKeys(o); + }; + + __importStar = function (mod) { + if (mod && mod.__esModule) return mod; + var result = {}; + if (mod != null) for (var k = ownKeys(mod), i = 0; i < k.length; i++) if (k[i] !== "default") __createBinding(result, mod, k[i]); + __setModuleDefault(result, mod); + return result; + }; + + __importDefault = function (mod) { + return (mod && mod.__esModule) ? mod : { "default": mod }; + }; + + __classPrivateFieldGet = function (receiver, state, kind, f) { + if (kind === "a" && !f) throw new TypeError("Private accessor was defined without a getter"); + if (typeof state === "function" ? receiver !== state || !f : !state.has(receiver)) throw new TypeError("Cannot read private member from an object whose class did not declare it"); + return kind === "m" ? f : kind === "a" ? f.call(receiver) : f ? f.value : state.get(receiver); + }; + + __classPrivateFieldSet = function (receiver, state, value, kind, f) { + if (kind === "m") throw new TypeError("Private method is not writable"); + if (kind === "a" && !f) throw new TypeError("Private accessor was defined without a setter"); + if (typeof state === "function" ? receiver !== state || !f : !state.has(receiver)) throw new TypeError("Cannot write private member to an object whose class did not declare it"); + return (kind === "a" ? f.call(receiver, value) : f ? f.value = value : state.set(receiver, value)), value; + }; + + __classPrivateFieldIn = function (state, receiver) { + if (receiver === null || (typeof receiver !== "object" && typeof receiver !== "function")) throw new TypeError("Cannot use 'in' operator on non-object"); + return typeof state === "function" ? receiver === state : state.has(receiver); + }; + + __addDisposableResource = function (env, value, async) { + if (value !== null && value !== void 0) { + if (typeof value !== "object" && typeof value !== "function") throw new TypeError("Object expected."); + var dispose, inner; + if (async) { + if (!Symbol.asyncDispose) throw new TypeError("Symbol.asyncDispose is not defined."); + dispose = value[Symbol.asyncDispose]; + } + if (dispose === void 0) { + if (!Symbol.dispose) throw new TypeError("Symbol.dispose is not defined."); + dispose = value[Symbol.dispose]; + if (async) inner = dispose; + } + if (typeof dispose !== "function") throw new TypeError("Object not disposable."); + if (inner) dispose = function() { try { inner.call(this); } catch (e) { return Promise.reject(e); } }; + env.stack.push({ value: value, dispose: dispose, async: async }); + } + else if (async) { + env.stack.push({ async: true }); + } + return value; + }; + + var _SuppressedError = typeof SuppressedError === "function" ? SuppressedError : function (error, suppressed, message) { + var e = new Error(message); + return e.name = "SuppressedError", e.error = error, e.suppressed = suppressed, e; + }; + + __disposeResources = function (env) { + function fail(e) { + env.error = env.hasError ? new _SuppressedError(e, env.error, "An error was suppressed during disposal.") : e; + env.hasError = true; + } + var r, s = 0; + function next() { + while (r = env.stack.pop()) { + try { + if (!r.async && s === 1) return s = 0, env.stack.push(r), Promise.resolve().then(next); + if (r.dispose) { + var result = r.dispose.call(r.value); + if (r.async) return s |= 2, Promise.resolve(result).then(next, function(e) { fail(e); return next(); }); + } + else s |= 1; + } + catch (e) { + fail(e); + } + } + if (s === 1) return env.hasError ? Promise.reject(env.error) : Promise.resolve(); + if (env.hasError) throw env.error; + } + return next(); + }; + + __rewriteRelativeImportExtension = function (path, preserveJsx) { + if (typeof path === "string" && /^\.\.?\//.test(path)) { + return path.replace(/\.(tsx)$|((?:\.d)?)((?:\.[^./]+?)?)\.([cm]?)ts$/i, function (m, tsx, d, ext, cm) { + return tsx ? preserveJsx ? ".jsx" : ".js" : d && (!ext || !cm) ? m : (d + ext + "." + cm.toLowerCase() + "js"); + }); + } + return path; + }; + + exporter("__extends", __extends); + exporter("__assign", __assign); + exporter("__rest", __rest); + exporter("__decorate", __decorate); + exporter("__param", __param); + exporter("__esDecorate", __esDecorate); + exporter("__runInitializers", __runInitializers); + exporter("__propKey", __propKey); + exporter("__setFunctionName", __setFunctionName); + exporter("__metadata", __metadata); + exporter("__awaiter", __awaiter); + exporter("__generator", __generator); + exporter("__exportStar", __exportStar); + exporter("__createBinding", __createBinding); + exporter("__values", __values); + exporter("__read", __read); + exporter("__spread", __spread); + exporter("__spreadArrays", __spreadArrays); + exporter("__spreadArray", __spreadArray); + exporter("__await", __await); + exporter("__asyncGenerator", __asyncGenerator); + exporter("__asyncDelegator", __asyncDelegator); + exporter("__asyncValues", __asyncValues); + exporter("__makeTemplateObject", __makeTemplateObject); + exporter("__importStar", __importStar); + exporter("__importDefault", __importDefault); + exporter("__classPrivateFieldGet", __classPrivateFieldGet); + exporter("__classPrivateFieldSet", __classPrivateFieldSet); + exporter("__classPrivateFieldIn", __classPrivateFieldIn); + exporter("__addDisposableResource", __addDisposableResource); + exporter("__disposeResources", __disposeResources); + exporter("__rewriteRelativeImportExtension", __rewriteRelativeImportExtension); +}); + +0 && (module.exports = { + __extends: __extends, + __assign: __assign, + __rest: __rest, + __decorate: __decorate, + __param: __param, + __esDecorate: __esDecorate, + __runInitializers: __runInitializers, + __propKey: __propKey, + __setFunctionName: __setFunctionName, + __metadata: __metadata, + __awaiter: __awaiter, + __generator: __generator, + __exportStar: __exportStar, + __createBinding: __createBinding, + __values: __values, + __read: __read, + __spread: __spread, + __spreadArrays: __spreadArrays, + __spreadArray: __spreadArray, + __await: __await, + __asyncGenerator: __asyncGenerator, + __asyncDelegator: __asyncDelegator, + __asyncValues: __asyncValues, + __makeTemplateObject: __makeTemplateObject, + __importStar: __importStar, + __importDefault: __importDefault, + __classPrivateFieldGet: __classPrivateFieldGet, + __classPrivateFieldSet: __classPrivateFieldSet, + __classPrivateFieldIn: __classPrivateFieldIn, + __addDisposableResource: __addDisposableResource, + __disposeResources: __disposeResources, + __rewriteRelativeImportExtension: __rewriteRelativeImportExtension, +}); diff --git a/dg-ui/node_modules/@tailwindcss/oxide-wasm32-wasi/package.json b/dg-ui/node_modules/@tailwindcss/oxide-wasm32-wasi/package.json new file mode 100644 index 0000000..2d4f145 --- /dev/null +++ b/dg-ui/node_modules/@tailwindcss/oxide-wasm32-wasi/package.json @@ -0,0 +1,42 @@ +{ + "name": "@tailwindcss/oxide-wasm32-wasi", + "version": "4.3.5", + "main": "tailwindcss-oxide.wasi.cjs", + "files": [ + "tailwindcss-oxide.wasm32-wasi.wasm", + "tailwindcss-oxide.wasi.cjs", + "tailwindcss-oxide.wasi-browser.js", + "wasi-worker.mjs", + "wasi-worker-browser.mjs" + ], + "license": "MIT", + "engines": { + "node": "^20.19.0 || ^22.13.0 || >=23.5.0" + }, + "publishConfig": { + "provenance": true, + "access": "public" + }, + "repository": { + "type": "git", + "url": "git+https://github.com/tailwindlabs/tailwindcss.git", + "directory": "crates/node" + }, + "browser": "tailwindcss-oxide.wasi-browser.js", + "dependencies": { + "@napi-rs/wasm-runtime": "^1.2.2", + "@emnapi/core": "^1.11.3", + "@emnapi/runtime": "^1.11.3", + "@tybys/wasm-util": "^0.10.3", + "@emnapi/wasi-threads": "^1.2.3", + "tslib": "^2.8.1" + }, + "bundledDependencies": [ + "@napi-rs/wasm-runtime", + "@emnapi/core", + "@emnapi/runtime", + "@tybys/wasm-util", + "@emnapi/wasi-threads", + "tslib" + ] +} \ No newline at end of file diff --git a/dg-ui/node_modules/@tailwindcss/oxide-wasm32-wasi/tailwindcss-oxide.wasi-browser.js b/dg-ui/node_modules/@tailwindcss/oxide-wasm32-wasi/tailwindcss-oxide.wasi-browser.js new file mode 100644 index 0000000..b3b31bc --- /dev/null +++ b/dg-ui/node_modules/@tailwindcss/oxide-wasm32-wasi/tailwindcss-oxide.wasi-browser.js @@ -0,0 +1,67 @@ +import { + createOnMessage as __wasmCreateOnMessageForFsProxy, + getDefaultContext as __emnapiGetDefaultContext, + instantiateNapiModuleSync as __emnapiInstantiateNapiModuleSync, + WASI as __WASI, +} from '@napi-rs/wasm-runtime' +import { memfs } from '@napi-rs/wasm-runtime/fs' + + +export const { fs: __fs, vol: __volume } = memfs() + +const __wasi = new __WASI({ + version: 'preview1', + fs: __fs, + preopens: { + '/': '/', + }, +}) + +const __wasmUrl = new URL('./tailwindcss-oxide.wasm32-wasi.wasm', import.meta.url).href +const __emnapiContext = __emnapiGetDefaultContext() + + +const __sharedMemory = new WebAssembly.Memory({ + initial: 16384, + maximum: 65536, + shared: true, +}) + +const __wasmFile = await fetch(__wasmUrl).then((res) => res.arrayBuffer()) + +const { + instance: __napiInstance, + module: __wasiModule, + napiModule: __napiModule, +} = __emnapiInstantiateNapiModuleSync(__wasmFile, { + context: __emnapiContext, + asyncWorkPoolSize: 4, + wasi: __wasi, + onCreateWorker() { + const worker = new Worker(new URL('./wasi-worker-browser.mjs', import.meta.url), { + type: 'module', + }) + worker.addEventListener('message', __wasmCreateOnMessageForFsProxy(__fs)) + + + return worker + }, + overwriteImports(importObject) { + importObject.env = { + ...importObject.env, + ...importObject.napi, + ...importObject.emnapi, + memory: __sharedMemory, + } + return importObject + }, + beforeInit({ instance }) { + for (const name of Object.keys(instance.exports)) { + if (name.startsWith('__napi_register__')) { + instance.exports[name]() + } + } + }, +}) +export default __napiModule.exports +export const Scanner = __napiModule.exports.Scanner diff --git a/dg-ui/node_modules/@tailwindcss/oxide-wasm32-wasi/tailwindcss-oxide.wasi.cjs b/dg-ui/node_modules/@tailwindcss/oxide-wasm32-wasi/tailwindcss-oxide.wasi.cjs new file mode 100644 index 0000000..2d457c1 --- /dev/null +++ b/dg-ui/node_modules/@tailwindcss/oxide-wasm32-wasi/tailwindcss-oxide.wasi.cjs @@ -0,0 +1,123 @@ +/* eslint-disable */ +/* prettier-ignore */ + +/* auto-generated by NAPI-RS */ + +const __nodeFs = require('node:fs') +const __nodePath = require('node:path') +const { WASI: __nodeWASI } = require('node:wasi') +const { Worker } = require('node:worker_threads') + +const { + createOnMessage: __wasmCreateOnMessageForFsProxy, + getDefaultContext: __emnapiGetDefaultContext, + instantiateNapiModuleSync: __emnapiInstantiateNapiModuleSync, +} = require('@napi-rs/wasm-runtime') + +const __rootDir = __nodePath.parse(process.cwd()).root + +const __wasi = (() => { + // Preopening '/' fails with UVWASI_EACCES in sandboxed environments (e.g. + // OpenHarmony, Android), which would prevent the wasm binding from loading + // at all. Retry with narrower preopens instead. Without any preopens the + // binding still loads; only file system access is unavailable. + let lastError = null + for (const dir of [__rootDir, process.cwd(), null]) { + try { + return new __nodeWASI({ + version: 'preview1', + env: process.env, + preopens: dir === null ? {} : { [dir]: dir }, + }) + } catch (error) { + lastError = error + } + } + throw lastError +})() + +const __emnapiContext = __emnapiGetDefaultContext() + +const __sharedMemory = new WebAssembly.Memory({ + initial: 16384, + maximum: 65536, + shared: true, +}) + +let __wasmFilePath = __nodePath.join(__dirname, 'tailwindcss-oxide.wasm32-wasi.wasm') +const __wasmDebugFilePath = __nodePath.join(__dirname, 'tailwindcss-oxide.wasm32-wasi.debug.wasm') + +if (__nodeFs.existsSync(__wasmDebugFilePath)) { + __wasmFilePath = __wasmDebugFilePath +} else if (!__nodeFs.existsSync(__wasmFilePath)) { + try { + __wasmFilePath = require.resolve('@tailwindcss/oxide-wasm32-wasi/tailwindcss-oxide.wasm32-wasi.wasm') + } catch { + throw new Error('Cannot find tailwindcss-oxide.wasm32-wasi.wasm file, and @tailwindcss/oxide-wasm32-wasi package is not installed.') + } +} + +const { instance: __napiInstance, module: __wasiModule, napiModule: __napiModule } = __emnapiInstantiateNapiModuleSync(__nodeFs.readFileSync(__wasmFilePath), { + context: __emnapiContext, + asyncWorkPoolSize: (function() { + const threadsSizeFromEnv = Number(process.env.NAPI_RS_ASYNC_WORK_POOL_SIZE ?? process.env.UV_THREADPOOL_SIZE) + // NaN > 0 is false + if (threadsSizeFromEnv > 0) { + return threadsSizeFromEnv + } else { + return 4 + } + })(), + reuseWorker: true, + wasi: __wasi, + onCreateWorker() { + const worker = new Worker(__nodePath.join(__dirname, 'wasi-worker.mjs'), { + env: process.env, + }) + worker.onmessage = ({ data }) => { + __wasmCreateOnMessageForFsProxy(__nodeFs)(data) + } + + // The main thread of Node.js waits for all the active handles before exiting. + // But Rust threads are never waited without `thread::join`. + // So here we hack the code of Node.js to prevent the workers from being referenced (active). + // According to https://github.com/nodejs/node/blob/19e0d472728c79d418b74bddff588bea70a403d0/lib/internal/worker.js#L415, + // a worker is consist of two handles: kPublicPort and kHandle. + { + const kPublicPort = Object.getOwnPropertySymbols(worker).find(s => + s.toString().includes("kPublicPort") + ); + if (kPublicPort) { + worker[kPublicPort].ref = () => {}; + } + + const kHandle = Object.getOwnPropertySymbols(worker).find(s => + s.toString().includes("kHandle") + ); + if (kHandle) { + worker[kHandle].ref = () => {}; + } + + worker.unref(); + } + return worker + }, + overwriteImports(importObject) { + importObject.env = { + ...importObject.env, + ...importObject.napi, + ...importObject.emnapi, + memory: __sharedMemory, + } + return importObject + }, + beforeInit({ instance }) { + for (const name of Object.keys(instance.exports)) { + if (name.startsWith('__napi_register__')) { + instance.exports[name]() + } + } + }, +}) +module.exports = __napiModule.exports +module.exports.Scanner = __napiModule.exports.Scanner diff --git a/dg-ui/node_modules/@tailwindcss/oxide-wasm32-wasi/tailwindcss-oxide.wasm32-wasi.wasm b/dg-ui/node_modules/@tailwindcss/oxide-wasm32-wasi/tailwindcss-oxide.wasm32-wasi.wasm new file mode 100644 index 0000000..29a6bd4 Binary files /dev/null and b/dg-ui/node_modules/@tailwindcss/oxide-wasm32-wasi/tailwindcss-oxide.wasm32-wasi.wasm differ diff --git a/dg-ui/node_modules/@tailwindcss/oxide-wasm32-wasi/wasi-worker-browser.mjs b/dg-ui/node_modules/@tailwindcss/oxide-wasm32-wasi/wasi-worker-browser.mjs new file mode 100644 index 0000000..e41200f --- /dev/null +++ b/dg-ui/node_modules/@tailwindcss/oxide-wasm32-wasi/wasi-worker-browser.mjs @@ -0,0 +1,41 @@ +import { instantiateNapiModuleSync, MessageHandler, WASI, createFsProxy } from '@napi-rs/wasm-runtime' +import { memfsExported as __memfsExported } from '@napi-rs/wasm-runtime/fs' + +const fs = createFsProxy(__memfsExported) + +const handler = new MessageHandler({ + onLoad({ wasmModule, wasmMemory }) { + const wasi = new WASI({ + fs, + preopens: { + '/': '/', + }, + print: function () { + // eslint-disable-next-line no-console + console.log.apply(console, arguments) + }, + printErr: function() { + // eslint-disable-next-line no-console + console.error.apply(console, arguments) + + }, + }) + return instantiateNapiModuleSync(wasmModule, { + childThread: true, + wasi, + overwriteImports(importObject) { + importObject.env = { + ...importObject.env, + ...importObject.napi, + ...importObject.emnapi, + memory: wasmMemory, + } + }, + }) + }, + +}) + +globalThis.onmessage = function (e) { + handler.handle(e) +} diff --git a/dg-ui/node_modules/@tailwindcss/oxide-wasm32-wasi/wasi-worker.mjs b/dg-ui/node_modules/@tailwindcss/oxide-wasm32-wasi/wasi-worker.mjs new file mode 100644 index 0000000..649e2b0 --- /dev/null +++ b/dg-ui/node_modules/@tailwindcss/oxide-wasm32-wasi/wasi-worker.mjs @@ -0,0 +1,72 @@ +import fs from "node:fs"; +import { createRequire } from "node:module"; +import { parse } from "node:path"; +import { WASI } from "node:wasi"; +import { parentPort, Worker } from "node:worker_threads"; + +const require = createRequire(import.meta.url); + +const { instantiateNapiModuleSync, MessageHandler, getDefaultContext } = require("@napi-rs/wasm-runtime"); + +if (parentPort) { + parentPort.on("message", (data) => { + globalThis.onmessage({ data }); + }); +} + +Object.assign(globalThis, { + self: globalThis, + require, + Worker, + importScripts: function (f) { + ;(0, eval)(fs.readFileSync(f, "utf8") + "//# sourceURL=" + f); + }, + postMessage: function (msg) { + if (parentPort) { + parentPort.postMessage(msg); + } + }, +}); + +const emnapiContext = getDefaultContext(); + +const __rootDir = parse(process.cwd()).root; + +const handler = new MessageHandler({ + onLoad({ wasmModule, wasmMemory }) { + // Keep in sync with the preopen fallback in the main-thread loader. + const wasi = (() => { + let lastError = null; + for (const dir of [__rootDir, process.cwd(), null]) { + try { + return new WASI({ + version: 'preview1', + env: process.env, + preopens: dir === null ? {} : { [dir]: dir }, + }); + } catch (error) { + lastError = error; + } + } + throw lastError; + })(); + + return instantiateNapiModuleSync(wasmModule, { + childThread: true, + wasi, + context: emnapiContext, + overwriteImports(importObject) { + importObject.env = { + ...importObject.env, + ...importObject.napi, + ...importObject.emnapi, + memory: wasmMemory + }; + }, + }); + }, +}); + +globalThis.onmessage = function (e) { + handler.handle(e); +}; diff --git a/dg-ui/node_modules/@tailwindcss/oxide-win32-x64-msvc/LICENSE b/dg-ui/node_modules/@tailwindcss/oxide-win32-x64-msvc/LICENSE new file mode 100644 index 0000000..d6a8229 --- /dev/null +++ b/dg-ui/node_modules/@tailwindcss/oxide-win32-x64-msvc/LICENSE @@ -0,0 +1,21 @@ +MIT License + +Copyright (c) Tailwind Labs, Inc. + +Permission is hereby granted, free of charge, to any person obtaining a copy +of this software and associated documentation files (the "Software"), to deal +in the Software without restriction, including without limitation the rights +to use, copy, modify, merge, publish, distribute, sublicense, and/or sell +copies of the Software, and to permit persons to whom the Software is +furnished to do so, subject to the following conditions: + +The above copyright notice and this permission notice shall be included in all +copies or substantial portions of the Software. + +THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR +IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, +FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE +AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER +LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, +OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE +SOFTWARE. diff --git a/dg-ui/node_modules/@tailwindcss/oxide-win32-x64-msvc/README.md b/dg-ui/node_modules/@tailwindcss/oxide-win32-x64-msvc/README.md new file mode 100644 index 0000000..bb1c4ac --- /dev/null +++ b/dg-ui/node_modules/@tailwindcss/oxide-win32-x64-msvc/README.md @@ -0,0 +1,3 @@ +# `@tailwindcss/oxide-win32-x64-msvc` + +This is the **x86_64-pc-windows-msvc** binary for `@tailwindcss/oxide` diff --git a/dg-ui/node_modules/@tailwindcss/oxide-win32-x64-msvc/package.json b/dg-ui/node_modules/@tailwindcss/oxide-win32-x64-msvc/package.json new file mode 100644 index 0000000..f56f13c --- /dev/null +++ b/dg-ui/node_modules/@tailwindcss/oxide-win32-x64-msvc/package.json @@ -0,0 +1,27 @@ +{ + "name": "@tailwindcss/oxide-win32-x64-msvc", + "version": "4.3.5", + "repository": { + "type": "git", + "url": "git+https://github.com/tailwindlabs/tailwindcss.git", + "directory": "crates/node/npm/win32-x64-msvc" + }, + "os": [ + "win32" + ], + "cpu": [ + "x64" + ], + "main": "tailwindcss-oxide.win32-x64-msvc.node", + "files": [ + "tailwindcss-oxide.win32-x64-msvc.node" + ], + "publishConfig": { + "provenance": true, + "access": "public" + }, + "license": "MIT", + "engines": { + "node": ">= 20" + } +} \ No newline at end of file diff --git a/dg-ui/node_modules/@tailwindcss/oxide-win32-x64-msvc/tailwindcss-oxide.win32-x64-msvc.node b/dg-ui/node_modules/@tailwindcss/oxide-win32-x64-msvc/tailwindcss-oxide.win32-x64-msvc.node new file mode 100644 index 0000000..8c7f13e Binary files /dev/null and b/dg-ui/node_modules/@tailwindcss/oxide-win32-x64-msvc/tailwindcss-oxide.win32-x64-msvc.node differ diff --git a/dg-ui/node_modules/@tailwindcss/oxide/LICENSE b/dg-ui/node_modules/@tailwindcss/oxide/LICENSE new file mode 100644 index 0000000..d6a8229 --- /dev/null +++ b/dg-ui/node_modules/@tailwindcss/oxide/LICENSE @@ -0,0 +1,21 @@ +MIT License + +Copyright (c) Tailwind Labs, Inc. + +Permission is hereby granted, free of charge, to any person obtaining a copy +of this software and associated documentation files (the "Software"), to deal +in the Software without restriction, including without limitation the rights +to use, copy, modify, merge, publish, distribute, sublicense, and/or sell +copies of the Software, and to permit persons to whom the Software is +furnished to do so, subject to the following conditions: + +The above copyright notice and this permission notice shall be included in all +copies or substantial portions of the Software. + +THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR +IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, +FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE +AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER +LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, +OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE +SOFTWARE. diff --git a/dg-ui/node_modules/@tailwindcss/oxide/index.d.ts b/dg-ui/node_modules/@tailwindcss/oxide/index.d.ts new file mode 100644 index 0000000..f6d66ce --- /dev/null +++ b/dg-ui/node_modules/@tailwindcss/oxide/index.d.ts @@ -0,0 +1,49 @@ +/* auto-generated by NAPI-RS */ +/* eslint-disable */ +export declare class Scanner { + constructor(opts: ScannerOptions) + scan(): Array + scanFiles(input: Array): Array + getCandidatesWithPositions(input: ChangedContent): Array + get files(): Array + get scannedFiles(): Array + get globs(): Array + get normalizedSources(): Array +} + +export interface CandidateWithPosition { + /** The candidate string */ + candidate: string + /** The position of the candidate inside the content file */ + position: number +} + +export interface ChangedContent { + /** File path to the changed file */ + file?: string + /** Contents of the changed file */ + content?: string + /** File extension */ + extension: string +} + +export interface GlobEntry { + /** Base path of the glob */ + base: string + /** Glob pattern */ + pattern: string +} + +export interface ScannerOptions { + /** Glob sources */ + sources?: Array +} + +export interface SourceEntry { + /** Base path of the glob */ + base: string + /** Glob pattern */ + pattern: string + /** Negated flag */ + negated: boolean +} diff --git a/dg-ui/node_modules/@tailwindcss/oxide/index.js b/dg-ui/node_modules/@tailwindcss/oxide/index.js new file mode 100644 index 0000000..26eecb8 --- /dev/null +++ b/dg-ui/node_modules/@tailwindcss/oxide/index.js @@ -0,0 +1,590 @@ +// prettier-ignore +/* eslint-disable */ +// @ts-nocheck +/* auto-generated by NAPI-RS */ + +const { readFileSync } = require('fs') +let nativeBinding = null +const loadErrors = [] + +const isMusl = () => { + let musl = false + if (process.platform === 'linux') { + musl = isMuslFromFilesystem() + if (musl === null) { + musl = isMuslFromReport() + } + if (musl === null) { + musl = isMuslFromChildProcess() + } + } + return musl +} + +const isFileMusl = (f) => f.includes('libc.musl-') || f.includes('ld-musl-') + +const isMuslFromFilesystem = () => { + try { + return readFileSync('/usr/bin/ldd', 'utf-8').includes('musl') + } catch { + return null + } +} + +const isMuslFromReport = () => { + let report = null + if (process.report && typeof process.report.getReport === 'function') { + process.report.excludeNetwork = true + report = process.report.getReport() + } + if (!report) { + return null + } + if (report.header && report.header.glibcVersionRuntime) { + return false + } + if (Array.isArray(report.sharedObjects)) { + if (report.sharedObjects.some(isFileMusl)) { + return true + } + } + return false +} + +const isMuslFromChildProcess = () => { + try { + return require('child_process').execSync('ldd --version', { encoding: 'utf8' }).includes('musl') + } catch (e) { + // If we reach this case, we don't know if the system is musl or not, so is better to just fallback to false + return false + } +} + +function requireNative() { + if (process.env.NAPI_RS_NATIVE_LIBRARY_PATH) { + try { + return require(process.env.NAPI_RS_NATIVE_LIBRARY_PATH); + } catch (err) { + loadErrors.push(err) + } + } else if (process.platform === 'android') { + if (process.arch === 'arm64') { + try { + return require('./tailwindcss-oxide.android-arm64.node') + } catch (e) { + loadErrors.push(e) + } + try { + const binding = require('@tailwindcss/oxide-android-arm64') + const bindingPackageVersion = require('@tailwindcss/oxide-android-arm64/package.json').version + if (bindingPackageVersion !== '4.3.5' && process.env.NAPI_RS_ENFORCE_VERSION_CHECK && process.env.NAPI_RS_ENFORCE_VERSION_CHECK !== '0') { + throw new Error(`Native binding package version mismatch, expected 4.3.5 but got ${bindingPackageVersion}. You can reinstall dependencies to fix this issue.`) + } + return binding + } catch (e) { + loadErrors.push(e) + } + } else if (process.arch === 'arm') { + try { + return require('./tailwindcss-oxide.android-arm-eabi.node') + } catch (e) { + loadErrors.push(e) + } + try { + const binding = require('@tailwindcss/oxide-android-arm-eabi') + const bindingPackageVersion = require('@tailwindcss/oxide-android-arm-eabi/package.json').version + if (bindingPackageVersion !== '4.3.5' && process.env.NAPI_RS_ENFORCE_VERSION_CHECK && process.env.NAPI_RS_ENFORCE_VERSION_CHECK !== '0') { + throw new Error(`Native binding package version mismatch, expected 4.3.5 but got ${bindingPackageVersion}. You can reinstall dependencies to fix this issue.`) + } + return binding + } catch (e) { + loadErrors.push(e) + } + } else { + loadErrors.push(new Error(`Unsupported architecture on Android ${process.arch}`)) + } + } else if (process.platform === 'win32') { + if (process.arch === 'x64') { + if ((process.config && process.config.variables && process.config.variables.shlib_suffix === 'dll.a') || (process.config && process.config.variables && process.config.variables.node_target_type === 'shared_library')) { + try { + return require('./tailwindcss-oxide.win32-x64-gnu.node') + } catch (e) { + loadErrors.push(e) + } + try { + const binding = require('@tailwindcss/oxide-win32-x64-gnu') + const bindingPackageVersion = require('@tailwindcss/oxide-win32-x64-gnu/package.json').version + if (bindingPackageVersion !== '4.3.5' && process.env.NAPI_RS_ENFORCE_VERSION_CHECK && process.env.NAPI_RS_ENFORCE_VERSION_CHECK !== '0') { + throw new Error(`Native binding package version mismatch, expected 4.3.5 but got ${bindingPackageVersion}. You can reinstall dependencies to fix this issue.`) + } + return binding + } catch (e) { + loadErrors.push(e) + } + } else { + try { + return require('./tailwindcss-oxide.win32-x64-msvc.node') + } catch (e) { + loadErrors.push(e) + } + try { + const binding = require('@tailwindcss/oxide-win32-x64-msvc') + const bindingPackageVersion = require('@tailwindcss/oxide-win32-x64-msvc/package.json').version + if (bindingPackageVersion !== '4.3.5' && process.env.NAPI_RS_ENFORCE_VERSION_CHECK && process.env.NAPI_RS_ENFORCE_VERSION_CHECK !== '0') { + throw new Error(`Native binding package version mismatch, expected 4.3.5 but got ${bindingPackageVersion}. You can reinstall dependencies to fix this issue.`) + } + return binding + } catch (e) { + loadErrors.push(e) + } + } + } else if (process.arch === 'ia32') { + try { + return require('./tailwindcss-oxide.win32-ia32-msvc.node') + } catch (e) { + loadErrors.push(e) + } + try { + const binding = require('@tailwindcss/oxide-win32-ia32-msvc') + const bindingPackageVersion = require('@tailwindcss/oxide-win32-ia32-msvc/package.json').version + if (bindingPackageVersion !== '4.3.5' && process.env.NAPI_RS_ENFORCE_VERSION_CHECK && process.env.NAPI_RS_ENFORCE_VERSION_CHECK !== '0') { + throw new Error(`Native binding package version mismatch, expected 4.3.5 but got ${bindingPackageVersion}. You can reinstall dependencies to fix this issue.`) + } + return binding + } catch (e) { + loadErrors.push(e) + } + } else if (process.arch === 'arm64') { + try { + return require('./tailwindcss-oxide.win32-arm64-msvc.node') + } catch (e) { + loadErrors.push(e) + } + try { + const binding = require('@tailwindcss/oxide-win32-arm64-msvc') + const bindingPackageVersion = require('@tailwindcss/oxide-win32-arm64-msvc/package.json').version + if (bindingPackageVersion !== '4.3.5' && process.env.NAPI_RS_ENFORCE_VERSION_CHECK && process.env.NAPI_RS_ENFORCE_VERSION_CHECK !== '0') { + throw new Error(`Native binding package version mismatch, expected 4.3.5 but got ${bindingPackageVersion}. You can reinstall dependencies to fix this issue.`) + } + return binding + } catch (e) { + loadErrors.push(e) + } + } else { + loadErrors.push(new Error(`Unsupported architecture on Windows: ${process.arch}`)) + } + } else if (process.platform === 'darwin') { + try { + return require('./tailwindcss-oxide.darwin-universal.node') + } catch (e) { + loadErrors.push(e) + } + try { + const binding = require('@tailwindcss/oxide-darwin-universal') + const bindingPackageVersion = require('@tailwindcss/oxide-darwin-universal/package.json').version + if (bindingPackageVersion !== '4.3.5' && process.env.NAPI_RS_ENFORCE_VERSION_CHECK && process.env.NAPI_RS_ENFORCE_VERSION_CHECK !== '0') { + throw new Error(`Native binding package version mismatch, expected 4.3.5 but got ${bindingPackageVersion}. You can reinstall dependencies to fix this issue.`) + } + return binding + } catch (e) { + loadErrors.push(e) + } + if (process.arch === 'x64') { + try { + return require('./tailwindcss-oxide.darwin-x64.node') + } catch (e) { + loadErrors.push(e) + } + try { + const binding = require('@tailwindcss/oxide-darwin-x64') + const bindingPackageVersion = require('@tailwindcss/oxide-darwin-x64/package.json').version + if (bindingPackageVersion !== '4.3.5' && process.env.NAPI_RS_ENFORCE_VERSION_CHECK && process.env.NAPI_RS_ENFORCE_VERSION_CHECK !== '0') { + throw new Error(`Native binding package version mismatch, expected 4.3.5 but got ${bindingPackageVersion}. You can reinstall dependencies to fix this issue.`) + } + return binding + } catch (e) { + loadErrors.push(e) + } + } else if (process.arch === 'arm64') { + try { + return require('./tailwindcss-oxide.darwin-arm64.node') + } catch (e) { + loadErrors.push(e) + } + try { + const binding = require('@tailwindcss/oxide-darwin-arm64') + const bindingPackageVersion = require('@tailwindcss/oxide-darwin-arm64/package.json').version + if (bindingPackageVersion !== '4.3.5' && process.env.NAPI_RS_ENFORCE_VERSION_CHECK && process.env.NAPI_RS_ENFORCE_VERSION_CHECK !== '0') { + throw new Error(`Native binding package version mismatch, expected 4.3.5 but got ${bindingPackageVersion}. You can reinstall dependencies to fix this issue.`) + } + return binding + } catch (e) { + loadErrors.push(e) + } + } else { + loadErrors.push(new Error(`Unsupported architecture on macOS: ${process.arch}`)) + } + } else if (process.platform === 'freebsd') { + if (process.arch === 'x64') { + try { + return require('./tailwindcss-oxide.freebsd-x64.node') + } catch (e) { + loadErrors.push(e) + } + try { + const binding = require('@tailwindcss/oxide-freebsd-x64') + const bindingPackageVersion = require('@tailwindcss/oxide-freebsd-x64/package.json').version + if (bindingPackageVersion !== '4.3.5' && process.env.NAPI_RS_ENFORCE_VERSION_CHECK && process.env.NAPI_RS_ENFORCE_VERSION_CHECK !== '0') { + throw new Error(`Native binding package version mismatch, expected 4.3.5 but got ${bindingPackageVersion}. You can reinstall dependencies to fix this issue.`) + } + return binding + } catch (e) { + loadErrors.push(e) + } + } else if (process.arch === 'arm64') { + try { + return require('./tailwindcss-oxide.freebsd-arm64.node') + } catch (e) { + loadErrors.push(e) + } + try { + const binding = require('@tailwindcss/oxide-freebsd-arm64') + const bindingPackageVersion = require('@tailwindcss/oxide-freebsd-arm64/package.json').version + if (bindingPackageVersion !== '4.3.5' && process.env.NAPI_RS_ENFORCE_VERSION_CHECK && process.env.NAPI_RS_ENFORCE_VERSION_CHECK !== '0') { + throw new Error(`Native binding package version mismatch, expected 4.3.5 but got ${bindingPackageVersion}. You can reinstall dependencies to fix this issue.`) + } + return binding + } catch (e) { + loadErrors.push(e) + } + } else { + loadErrors.push(new Error(`Unsupported architecture on FreeBSD: ${process.arch}`)) + } + } else if (process.platform === 'linux') { + if (process.arch === 'x64') { + if (isMusl()) { + try { + return require('./tailwindcss-oxide.linux-x64-musl.node') + } catch (e) { + loadErrors.push(e) + } + try { + const binding = require('@tailwindcss/oxide-linux-x64-musl') + const bindingPackageVersion = require('@tailwindcss/oxide-linux-x64-musl/package.json').version + if (bindingPackageVersion !== '4.3.5' && process.env.NAPI_RS_ENFORCE_VERSION_CHECK && process.env.NAPI_RS_ENFORCE_VERSION_CHECK !== '0') { + throw new Error(`Native binding package version mismatch, expected 4.3.5 but got ${bindingPackageVersion}. You can reinstall dependencies to fix this issue.`) + } + return binding + } catch (e) { + loadErrors.push(e) + } + } else { + try { + return require('./tailwindcss-oxide.linux-x64-gnu.node') + } catch (e) { + loadErrors.push(e) + } + try { + const binding = require('@tailwindcss/oxide-linux-x64-gnu') + const bindingPackageVersion = require('@tailwindcss/oxide-linux-x64-gnu/package.json').version + if (bindingPackageVersion !== '4.3.5' && process.env.NAPI_RS_ENFORCE_VERSION_CHECK && process.env.NAPI_RS_ENFORCE_VERSION_CHECK !== '0') { + throw new Error(`Native binding package version mismatch, expected 4.3.5 but got ${bindingPackageVersion}. You can reinstall dependencies to fix this issue.`) + } + return binding + } catch (e) { + loadErrors.push(e) + } + } + } else if (process.arch === 'arm64') { + if (isMusl()) { + try { + return require('./tailwindcss-oxide.linux-arm64-musl.node') + } catch (e) { + loadErrors.push(e) + } + try { + const binding = require('@tailwindcss/oxide-linux-arm64-musl') + const bindingPackageVersion = require('@tailwindcss/oxide-linux-arm64-musl/package.json').version + if (bindingPackageVersion !== '4.3.5' && process.env.NAPI_RS_ENFORCE_VERSION_CHECK && process.env.NAPI_RS_ENFORCE_VERSION_CHECK !== '0') { + throw new Error(`Native binding package version mismatch, expected 4.3.5 but got ${bindingPackageVersion}. You can reinstall dependencies to fix this issue.`) + } + return binding + } catch (e) { + loadErrors.push(e) + } + } else { + try { + return require('./tailwindcss-oxide.linux-arm64-gnu.node') + } catch (e) { + loadErrors.push(e) + } + try { + const binding = require('@tailwindcss/oxide-linux-arm64-gnu') + const bindingPackageVersion = require('@tailwindcss/oxide-linux-arm64-gnu/package.json').version + if (bindingPackageVersion !== '4.3.5' && process.env.NAPI_RS_ENFORCE_VERSION_CHECK && process.env.NAPI_RS_ENFORCE_VERSION_CHECK !== '0') { + throw new Error(`Native binding package version mismatch, expected 4.3.5 but got ${bindingPackageVersion}. You can reinstall dependencies to fix this issue.`) + } + return binding + } catch (e) { + loadErrors.push(e) + } + } + } else if (process.arch === 'arm') { + if (isMusl()) { + try { + return require('./tailwindcss-oxide.linux-arm-musleabihf.node') + } catch (e) { + loadErrors.push(e) + } + try { + const binding = require('@tailwindcss/oxide-linux-arm-musleabihf') + const bindingPackageVersion = require('@tailwindcss/oxide-linux-arm-musleabihf/package.json').version + if (bindingPackageVersion !== '4.3.5' && process.env.NAPI_RS_ENFORCE_VERSION_CHECK && process.env.NAPI_RS_ENFORCE_VERSION_CHECK !== '0') { + throw new Error(`Native binding package version mismatch, expected 4.3.5 but got ${bindingPackageVersion}. You can reinstall dependencies to fix this issue.`) + } + return binding + } catch (e) { + loadErrors.push(e) + } + } else { + try { + return require('./tailwindcss-oxide.linux-arm-gnueabihf.node') + } catch (e) { + loadErrors.push(e) + } + try { + const binding = require('@tailwindcss/oxide-linux-arm-gnueabihf') + const bindingPackageVersion = require('@tailwindcss/oxide-linux-arm-gnueabihf/package.json').version + if (bindingPackageVersion !== '4.3.5' && process.env.NAPI_RS_ENFORCE_VERSION_CHECK && process.env.NAPI_RS_ENFORCE_VERSION_CHECK !== '0') { + throw new Error(`Native binding package version mismatch, expected 4.3.5 but got ${bindingPackageVersion}. You can reinstall dependencies to fix this issue.`) + } + return binding + } catch (e) { + loadErrors.push(e) + } + } + } else if (process.arch === 'loong64') { + if (isMusl()) { + try { + return require('./tailwindcss-oxide.linux-loong64-musl.node') + } catch (e) { + loadErrors.push(e) + } + try { + const binding = require('@tailwindcss/oxide-linux-loong64-musl') + const bindingPackageVersion = require('@tailwindcss/oxide-linux-loong64-musl/package.json').version + if (bindingPackageVersion !== '4.3.5' && process.env.NAPI_RS_ENFORCE_VERSION_CHECK && process.env.NAPI_RS_ENFORCE_VERSION_CHECK !== '0') { + throw new Error(`Native binding package version mismatch, expected 4.3.5 but got ${bindingPackageVersion}. You can reinstall dependencies to fix this issue.`) + } + return binding + } catch (e) { + loadErrors.push(e) + } + } else { + try { + return require('./tailwindcss-oxide.linux-loong64-gnu.node') + } catch (e) { + loadErrors.push(e) + } + try { + const binding = require('@tailwindcss/oxide-linux-loong64-gnu') + const bindingPackageVersion = require('@tailwindcss/oxide-linux-loong64-gnu/package.json').version + if (bindingPackageVersion !== '4.3.5' && process.env.NAPI_RS_ENFORCE_VERSION_CHECK && process.env.NAPI_RS_ENFORCE_VERSION_CHECK !== '0') { + throw new Error(`Native binding package version mismatch, expected 4.3.5 but got ${bindingPackageVersion}. You can reinstall dependencies to fix this issue.`) + } + return binding + } catch (e) { + loadErrors.push(e) + } + } + } else if (process.arch === 'riscv64') { + if (isMusl()) { + try { + return require('./tailwindcss-oxide.linux-riscv64-musl.node') + } catch (e) { + loadErrors.push(e) + } + try { + const binding = require('@tailwindcss/oxide-linux-riscv64-musl') + const bindingPackageVersion = require('@tailwindcss/oxide-linux-riscv64-musl/package.json').version + if (bindingPackageVersion !== '4.3.5' && process.env.NAPI_RS_ENFORCE_VERSION_CHECK && process.env.NAPI_RS_ENFORCE_VERSION_CHECK !== '0') { + throw new Error(`Native binding package version mismatch, expected 4.3.5 but got ${bindingPackageVersion}. You can reinstall dependencies to fix this issue.`) + } + return binding + } catch (e) { + loadErrors.push(e) + } + } else { + try { + return require('./tailwindcss-oxide.linux-riscv64-gnu.node') + } catch (e) { + loadErrors.push(e) + } + try { + const binding = require('@tailwindcss/oxide-linux-riscv64-gnu') + const bindingPackageVersion = require('@tailwindcss/oxide-linux-riscv64-gnu/package.json').version + if (bindingPackageVersion !== '4.3.5' && process.env.NAPI_RS_ENFORCE_VERSION_CHECK && process.env.NAPI_RS_ENFORCE_VERSION_CHECK !== '0') { + throw new Error(`Native binding package version mismatch, expected 4.3.5 but got ${bindingPackageVersion}. You can reinstall dependencies to fix this issue.`) + } + return binding + } catch (e) { + loadErrors.push(e) + } + } + } else if (process.arch === 'ppc64') { + try { + return require('./tailwindcss-oxide.linux-ppc64-gnu.node') + } catch (e) { + loadErrors.push(e) + } + try { + const binding = require('@tailwindcss/oxide-linux-ppc64-gnu') + const bindingPackageVersion = require('@tailwindcss/oxide-linux-ppc64-gnu/package.json').version + if (bindingPackageVersion !== '4.3.5' && process.env.NAPI_RS_ENFORCE_VERSION_CHECK && process.env.NAPI_RS_ENFORCE_VERSION_CHECK !== '0') { + throw new Error(`Native binding package version mismatch, expected 4.3.5 but got ${bindingPackageVersion}. You can reinstall dependencies to fix this issue.`) + } + return binding + } catch (e) { + loadErrors.push(e) + } + } else if (process.arch === 's390x') { + try { + return require('./tailwindcss-oxide.linux-s390x-gnu.node') + } catch (e) { + loadErrors.push(e) + } + try { + const binding = require('@tailwindcss/oxide-linux-s390x-gnu') + const bindingPackageVersion = require('@tailwindcss/oxide-linux-s390x-gnu/package.json').version + if (bindingPackageVersion !== '4.3.5' && process.env.NAPI_RS_ENFORCE_VERSION_CHECK && process.env.NAPI_RS_ENFORCE_VERSION_CHECK !== '0') { + throw new Error(`Native binding package version mismatch, expected 4.3.5 but got ${bindingPackageVersion}. You can reinstall dependencies to fix this issue.`) + } + return binding + } catch (e) { + loadErrors.push(e) + } + } else { + loadErrors.push(new Error(`Unsupported architecture on Linux: ${process.arch}`)) + } + } else if (process.platform === 'openharmony') { + if (process.arch === 'arm64') { + try { + return require('./tailwindcss-oxide.openharmony-arm64.node') + } catch (e) { + loadErrors.push(e) + } + try { + const binding = require('@tailwindcss/oxide-openharmony-arm64') + const bindingPackageVersion = require('@tailwindcss/oxide-openharmony-arm64/package.json').version + if (bindingPackageVersion !== '4.3.5' && process.env.NAPI_RS_ENFORCE_VERSION_CHECK && process.env.NAPI_RS_ENFORCE_VERSION_CHECK !== '0') { + throw new Error(`Native binding package version mismatch, expected 4.3.5 but got ${bindingPackageVersion}. You can reinstall dependencies to fix this issue.`) + } + return binding + } catch (e) { + loadErrors.push(e) + } + } else if (process.arch === 'x64') { + try { + return require('./tailwindcss-oxide.openharmony-x64.node') + } catch (e) { + loadErrors.push(e) + } + try { + const binding = require('@tailwindcss/oxide-openharmony-x64') + const bindingPackageVersion = require('@tailwindcss/oxide-openharmony-x64/package.json').version + if (bindingPackageVersion !== '4.3.5' && process.env.NAPI_RS_ENFORCE_VERSION_CHECK && process.env.NAPI_RS_ENFORCE_VERSION_CHECK !== '0') { + throw new Error(`Native binding package version mismatch, expected 4.3.5 but got ${bindingPackageVersion}. You can reinstall dependencies to fix this issue.`) + } + return binding + } catch (e) { + loadErrors.push(e) + } + } else if (process.arch === 'arm') { + try { + return require('./tailwindcss-oxide.openharmony-arm.node') + } catch (e) { + loadErrors.push(e) + } + try { + const binding = require('@tailwindcss/oxide-openharmony-arm') + const bindingPackageVersion = require('@tailwindcss/oxide-openharmony-arm/package.json').version + if (bindingPackageVersion !== '4.3.5' && process.env.NAPI_RS_ENFORCE_VERSION_CHECK && process.env.NAPI_RS_ENFORCE_VERSION_CHECK !== '0') { + throw new Error(`Native binding package version mismatch, expected 4.3.5 but got ${bindingPackageVersion}. You can reinstall dependencies to fix this issue.`) + } + return binding + } catch (e) { + loadErrors.push(e) + } + } else { + loadErrors.push(new Error(`Unsupported architecture on OpenHarmony: ${process.arch}`)) + } + } else { + loadErrors.push(new Error(`Unsupported OS: ${process.platform}, architecture: ${process.arch}`)) + } +} + +nativeBinding = requireNative() + +// NAPI_RS_FORCE_WASI is a tri-state flag: +// unset / any other value → native binding preferred, WASI is only a fallback +// 'true' → force WASI fallback even if native loaded +// 'error' → force WASI and throw if no WASI binding is found +// Treating any non-empty string as truthy (the historical behavior) meant +// NAPI_RS_FORCE_WASI=false, NAPI_RS_FORCE_WASI=0, etc. inadvertently triggered +// the WASI path, causing ENOENT for packages shipped without a .wasi.cjs file. +const forceWasi = + process.env.NAPI_RS_FORCE_WASI === 'true' || process.env.NAPI_RS_FORCE_WASI === 'error' + +if (!nativeBinding || forceWasi) { + let wasiBinding = null + let wasiBindingError = null + try { + wasiBinding = require('./tailwindcss-oxide.wasi.cjs') + nativeBinding = wasiBinding + } catch (err) { + if (forceWasi) { + wasiBindingError = err + } + } + if (!nativeBinding || forceWasi) { + try { + wasiBinding = require('@tailwindcss/oxide-wasm32-wasi') + nativeBinding = wasiBinding + } catch (err) { + if (forceWasi) { + if (!wasiBindingError) { + wasiBindingError = err + } else { + wasiBindingError.cause = err + } + loadErrors.push(err) + } + } + } + if (process.env.NAPI_RS_FORCE_WASI === 'error' && !wasiBinding) { + const error = new Error('WASI binding not found and NAPI_RS_FORCE_WASI is set to error') + error.cause = wasiBindingError + throw error + } +} + +if (!nativeBinding) { + if (loadErrors.length > 0) { + const error = new Error( + `Cannot find native binding. ` + + `npm has a bug related to optional dependencies (https://github.com/npm/cli/issues/4828). ` + + 'Please try `npm i` again after removing both package-lock.json and node_modules directory.', + ) + // assign instead of the `new Error(message, { cause })` options form, + // which Node < 16.9 silently ignores + error.cause = loadErrors.reduce((err, cur) => { + cur.cause = err + return cur + }) + throw error + } + throw new Error(`Failed to load native binding`) +} + +module.exports = nativeBinding +module.exports.Scanner = nativeBinding.Scanner diff --git a/dg-ui/node_modules/@tailwindcss/oxide/package.json b/dg-ui/node_modules/@tailwindcss/oxide/package.json new file mode 100644 index 0000000..e5da22d --- /dev/null +++ b/dg-ui/node_modules/@tailwindcss/oxide/package.json @@ -0,0 +1,77 @@ +{ + "name": "@tailwindcss/oxide", + "version": "4.3.5", + "repository": { + "type": "git", + "url": "git+https://github.com/tailwindlabs/tailwindcss.git", + "directory": "crates/node" + }, + "main": "index.js", + "types": "index.d.ts", + "napi": { + "binaryName": "tailwindcss-oxide", + "packageName": "@tailwindcss/oxide", + "targets": [ + "armv7-linux-androideabi", + "aarch64-linux-android", + "aarch64-apple-darwin", + "aarch64-unknown-linux-gnu", + "aarch64-unknown-linux-musl", + "armv7-unknown-linux-gnueabihf", + "x86_64-unknown-linux-musl", + "x86_64-unknown-freebsd", + "i686-pc-windows-msvc", + "aarch64-pc-windows-msvc", + "wasm32-wasip1-threads" + ], + "wasm": { + "initialMemory": 16384, + "browser": { + "fs": true + } + } + }, + "license": "MIT", + "devDependencies": { + "@emnapi/core": "1.11.3", + "@emnapi/runtime": "1.11.3", + "@napi-rs/cli": "3.7.4", + "@napi-rs/wasm-runtime": "^1.2.2", + "emnapi": "1.11.3" + }, + "engines": { + "node": ">= 20" + }, + "files": [ + "index.js", + "index.d.ts" + ], + "publishConfig": { + "provenance": true, + "access": "public" + }, + "optionalDependencies": { + "@tailwindcss/oxide-darwin-arm64": "4.3.5", + "@tailwindcss/oxide-darwin-x64": "4.3.5", + "@tailwindcss/oxide-linux-arm-gnueabihf": "4.3.5", + "@tailwindcss/oxide-linux-arm64-gnu": "4.3.5", + "@tailwindcss/oxide-android-arm64": "4.3.5", + "@tailwindcss/oxide-freebsd-x64": "4.3.5", + "@tailwindcss/oxide-linux-arm64-musl": "4.3.5", + "@tailwindcss/oxide-linux-x64-musl": "4.3.5", + "@tailwindcss/oxide-linux-x64-gnu": "4.3.5", + "@tailwindcss/oxide-wasm32-wasi": "4.3.5", + "@tailwindcss/oxide-win32-arm64-msvc": "4.3.5", + "@tailwindcss/oxide-win32-x64-msvc": "4.3.5" + }, + "scripts": { + "build": "pnpm run build:platform && pnpm run build:wasm", + "build:platform": "napi build --platform --release", + "postbuild:platform": "node ./scripts/move-artifacts.mjs", + "build:wasm": "napi build --release --target wasm32-wasip1-threads", + "postbuild:wasm": "node ./scripts/move-artifacts.mjs", + "dev": "cargo watch --quiet --shell 'npm run build'", + "build:debug": "napi build --platform", + "version": "napi version" + } +} \ No newline at end of file diff --git a/dg-ui/node_modules/detect-libc/LICENSE b/dg-ui/node_modules/detect-libc/LICENSE new file mode 100644 index 0000000..8dada3e --- /dev/null +++ b/dg-ui/node_modules/detect-libc/LICENSE @@ -0,0 +1,201 @@ + Apache License + Version 2.0, January 2004 + http://www.apache.org/licenses/ + + TERMS AND CONDITIONS FOR USE, REPRODUCTION, AND DISTRIBUTION + + 1. Definitions. + + "License" shall mean the terms and conditions for use, reproduction, + and distribution as defined by Sections 1 through 9 of this document. + + "Licensor" shall mean the copyright owner or entity authorized by + the copyright owner that is granting the License. + + "Legal Entity" shall mean the union of the acting entity and all + other entities that control, are controlled by, or are under common + control with that entity. For the purposes of this definition, + "control" means (i) the power, direct or indirect, to cause the + direction or management of such entity, whether by contract or + otherwise, or (ii) ownership of fifty percent (50%) or more of the + outstanding shares, or (iii) beneficial ownership of such entity. + + "You" (or "Your") shall mean an individual or Legal Entity + exercising permissions granted by this License. + + "Source" form shall mean the preferred form for making modifications, + including but not limited to software source code, documentation + source, and configuration files. + + "Object" form shall mean any form resulting from mechanical + transformation or translation of a Source form, including but + not limited to compiled object code, generated documentation, + and conversions to other media types. + + "Work" shall mean the work of authorship, whether in Source or + Object form, made available under the License, as indicated by a + copyright notice that is included in or attached to the work + (an example is provided in the Appendix below). + + "Derivative Works" shall mean any work, whether in Source or Object + form, that is based on (or derived from) the Work and for which the + editorial revisions, annotations, elaborations, or other modifications + represent, as a whole, an original work of authorship. For the purposes + of this License, Derivative Works shall not include works that remain + separable from, or merely link (or bind by name) to the interfaces of, + the Work and Derivative Works thereof. + + "Contribution" shall mean any work of authorship, including + the original version of the Work and any modifications or additions + to that Work or Derivative Works thereof, that is intentionally + submitted to Licensor for inclusion in the Work by the copyright owner + or by an individual or Legal Entity authorized to submit on behalf of + the copyright owner. For the purposes of this definition, "submitted" + means any form of electronic, verbal, or written communication sent + to the Licensor or its representatives, including but not limited to + communication on electronic mailing lists, source code control systems, + and issue tracking systems that are managed by, or on behalf of, the + Licensor for the purpose of discussing and improving the Work, but + excluding communication that is conspicuously marked or otherwise + designated in writing by the copyright owner as "Not a Contribution." + + "Contributor" shall mean Licensor and any individual or Legal Entity + on behalf of whom a Contribution has been received by Licensor and + subsequently incorporated within the Work. + + 2. Grant of Copyright License. Subject to the terms and conditions of + this License, each Contributor hereby grants to You a perpetual, + worldwide, non-exclusive, no-charge, royalty-free, irrevocable + copyright license to reproduce, prepare Derivative Works of, + publicly display, publicly perform, sublicense, and distribute the + Work and such Derivative Works in Source or Object form. + + 3. Grant of Patent License. Subject to the terms and conditions of + this License, each Contributor hereby grants to You a perpetual, + worldwide, non-exclusive, no-charge, royalty-free, irrevocable + (except as stated in this section) patent license to make, have made, + use, offer to sell, sell, import, and otherwise transfer the Work, + where such license applies only to those patent claims licensable + by such Contributor that are necessarily infringed by their + Contribution(s) alone or by combination of their Contribution(s) + with the Work to which such Contribution(s) was submitted. If You + institute patent litigation against any entity (including a + cross-claim or counterclaim in a lawsuit) alleging that the Work + or a Contribution incorporated within the Work constitutes direct + or contributory patent infringement, then any patent licenses + granted to You under this License for that Work shall terminate + as of the date such litigation is filed. + + 4. Redistribution. You may reproduce and distribute copies of the + Work or Derivative Works thereof in any medium, with or without + modifications, and in Source or Object form, provided that You + meet the following conditions: + + (a) You must give any other recipients of the Work or + Derivative Works a copy of this License; and + + (b) You must cause any modified files to carry prominent notices + stating that You changed the files; and + + (c) You must retain, in the Source form of any Derivative Works + that You distribute, all copyright, patent, trademark, and + attribution notices from the Source form of the Work, + excluding those notices that do not pertain to any part of + the Derivative Works; and + + (d) If the Work includes a "NOTICE" text file as part of its + distribution, then any Derivative Works that You distribute must + include a readable copy of the attribution notices contained + within such NOTICE file, excluding those notices that do not + pertain to any part of the Derivative Works, in at least one + of the following places: within a NOTICE text file distributed + as part of the Derivative Works; within the Source form or + documentation, if provided along with the Derivative Works; or, + within a display generated by the Derivative Works, if and + wherever such third-party notices normally appear. The contents + of the NOTICE file are for informational purposes only and + do not modify the License. You may add Your own attribution + notices within Derivative Works that You distribute, alongside + or as an addendum to the NOTICE text from the Work, provided + that such additional attribution notices cannot be construed + as modifying the License. + + You may add Your own copyright statement to Your modifications and + may provide additional or different license terms and conditions + for use, reproduction, or distribution of Your modifications, or + for any such Derivative Works as a whole, provided Your use, + reproduction, and distribution of the Work otherwise complies with + the conditions stated in this License. + + 5. Submission of Contributions. Unless You explicitly state otherwise, + any Contribution intentionally submitted for inclusion in the Work + by You to the Licensor shall be under the terms and conditions of + this License, without any additional terms or conditions. + Notwithstanding the above, nothing herein shall supersede or modify + the terms of any separate license agreement you may have executed + with Licensor regarding such Contributions. + + 6. Trademarks. This License does not grant permission to use the trade + names, trademarks, service marks, or product names of the Licensor, + except as required for reasonable and customary use in describing the + origin of the Work and reproducing the content of the NOTICE file. + + 7. Disclaimer of Warranty. Unless required by applicable law or + agreed to in writing, Licensor provides the Work (and each + Contributor provides its Contributions) on an "AS IS" BASIS, + WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or + implied, including, without limitation, any warranties or conditions + of TITLE, NON-INFRINGEMENT, MERCHANTABILITY, or FITNESS FOR A + PARTICULAR PURPOSE. You are solely responsible for determining the + appropriateness of using or redistributing the Work and assume any + risks associated with Your exercise of permissions under this License. + + 8. Limitation of Liability. In no event and under no legal theory, + whether in tort (including negligence), contract, or otherwise, + unless required by applicable law (such as deliberate and grossly + negligent acts) or agreed to in writing, shall any Contributor be + liable to You for damages, including any direct, indirect, special, + incidental, or consequential damages of any character arising as a + result of this License or out of the use or inability to use the + Work (including but not limited to damages for loss of goodwill, + work stoppage, computer failure or malfunction, or any and all + other commercial damages or losses), even if such Contributor + has been advised of the possibility of such damages. + + 9. Accepting Warranty or Additional Liability. While redistributing + the Work or Derivative Works thereof, You may choose to offer, + and charge a fee for, acceptance of support, warranty, indemnity, + or other liability obligations and/or rights consistent with this + License. However, in accepting such obligations, You may act only + on Your own behalf and on Your sole responsibility, not on behalf + of any other Contributor, and only if You agree to indemnify, + defend, and hold each Contributor harmless for any liability + incurred by, or claims asserted against, such Contributor by reason + of your accepting any such warranty or additional liability. + + END OF TERMS AND CONDITIONS + + APPENDIX: How to apply the Apache License to your work. + + To apply the Apache License to your work, attach the following + boilerplate notice, with the fields enclosed by brackets "{}" + replaced with your own identifying information. (Don't include + the brackets!) The text should be enclosed in the appropriate + comment syntax for the file format. We also recommend that a + file or class name and description of purpose be included on the + same "printed page" as the copyright notice for easier + identification within third-party archives. + + Copyright {yyyy} {name of copyright owner} + + Licensed under the Apache License, Version 2.0 (the "License"); + you may not use this file except in compliance with the License. + You may obtain a copy of the License at + + http://www.apache.org/licenses/LICENSE-2.0 + + Unless required by applicable law or agreed to in writing, software + distributed under the License is distributed on an "AS IS" BASIS, + WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + See the License for the specific language governing permissions and + limitations under the License. diff --git a/dg-ui/node_modules/detect-libc/README.md b/dg-ui/node_modules/detect-libc/README.md new file mode 100644 index 0000000..23212fd --- /dev/null +++ b/dg-ui/node_modules/detect-libc/README.md @@ -0,0 +1,163 @@ +# detect-libc + +Node.js module to detect details of the C standard library (libc) +implementation provided by a given Linux system. + +Currently supports detection of GNU glibc and MUSL libc. + +Provides asychronous and synchronous functions for the +family (e.g. `glibc`, `musl`) and version (e.g. `1.23`, `1.2.3`). + +The version numbers of libc implementations +are not guaranteed to be semver-compliant. + +For previous v1.x releases, please see the +[v1](https://github.com/lovell/detect-libc/tree/v1) branch. + +## Install + +```sh +npm install detect-libc +``` + +## API + +### GLIBC + +```ts +const GLIBC: string = 'glibc'; +``` + +A String constant containing the value `glibc`. + +### MUSL + +```ts +const MUSL: string = 'musl'; +``` + +A String constant containing the value `musl`. + +### family + +```ts +function family(): Promise; +``` + +Resolves asychronously with: + +* `glibc` or `musl` when the libc family can be determined +* `null` when the libc family cannot be determined +* `null` when run on a non-Linux platform + +```js +const { family, GLIBC, MUSL } = require('detect-libc'); + +switch (await family()) { + case GLIBC: ... + case MUSL: ... + case null: ... +} +``` + +### familySync + +```ts +function familySync(): string | null; +``` + +Synchronous version of `family()`. + +```js +const { familySync, GLIBC, MUSL } = require('detect-libc'); + +switch (familySync()) { + case GLIBC: ... + case MUSL: ... + case null: ... +} +``` + +### version + +```ts +function version(): Promise; +``` + +Resolves asychronously with: + +* The version when it can be determined +* `null` when the libc family cannot be determined +* `null` when run on a non-Linux platform + +```js +const { version } = require('detect-libc'); + +const v = await version(); +if (v) { + const [major, minor, patch] = v.split('.'); +} +``` + +### versionSync + +```ts +function versionSync(): string | null; +``` + +Synchronous version of `version()`. + +```js +const { versionSync } = require('detect-libc'); + +const v = versionSync(); +if (v) { + const [major, minor, patch] = v.split('.'); +} +``` + +### isNonGlibcLinux + +```ts +function isNonGlibcLinux(): Promise; +``` + +Resolves asychronously with: + +* `false` when the libc family is `glibc` +* `true` when the libc family is not `glibc` +* `false` when run on a non-Linux platform + +```js +const { isNonGlibcLinux } = require('detect-libc'); + +if (await isNonGlibcLinux()) { ... } +``` + +### isNonGlibcLinuxSync + +```ts +function isNonGlibcLinuxSync(): boolean; +``` + +Synchronous version of `isNonGlibcLinux()`. + +```js +const { isNonGlibcLinuxSync } = require('detect-libc'); + +if (isNonGlibcLinuxSync()) { ... } +``` + +## Licensing + +Copyright 2017 Lovell Fuller and others. + +Licensed under the Apache License, Version 2.0 (the "License"); +you may not use this file except in compliance with the License. +You may obtain a copy of the License at [http://www.apache.org/licenses/LICENSE-2.0](http://www.apache.org/licenses/LICENSE-2.0.html) + +Unless required by applicable law or agreed to in writing, software +distributed under the License is distributed on an "AS IS" BASIS, +WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. +See the License for the specific language governing permissions and +limitations under the License. diff --git a/dg-ui/node_modules/detect-libc/index.d.ts b/dg-ui/node_modules/detect-libc/index.d.ts new file mode 100644 index 0000000..4c0fb2b --- /dev/null +++ b/dg-ui/node_modules/detect-libc/index.d.ts @@ -0,0 +1,14 @@ +// Copyright 2017 Lovell Fuller and others. +// SPDX-License-Identifier: Apache-2.0 + +export const GLIBC: 'glibc'; +export const MUSL: 'musl'; + +export function family(): Promise; +export function familySync(): string | null; + +export function isNonGlibcLinux(): Promise; +export function isNonGlibcLinuxSync(): boolean; + +export function version(): Promise; +export function versionSync(): string | null; diff --git a/dg-ui/node_modules/detect-libc/lib/detect-libc.js b/dg-ui/node_modules/detect-libc/lib/detect-libc.js new file mode 100644 index 0000000..01299b4 --- /dev/null +++ b/dg-ui/node_modules/detect-libc/lib/detect-libc.js @@ -0,0 +1,313 @@ +// Copyright 2017 Lovell Fuller and others. +// SPDX-License-Identifier: Apache-2.0 + +'use strict'; + +const childProcess = require('child_process'); +const { isLinux, getReport } = require('./process'); +const { LDD_PATH, SELF_PATH, readFile, readFileSync } = require('./filesystem'); +const { interpreterPath } = require('./elf'); + +let cachedFamilyInterpreter; +let cachedFamilyFilesystem; +let cachedVersionFilesystem; + +const command = 'getconf GNU_LIBC_VERSION 2>&1 || true; ldd --version 2>&1 || true'; +let commandOut = ''; + +const safeCommand = () => { + if (!commandOut) { + return new Promise((resolve) => { + childProcess.exec(command, (err, out) => { + commandOut = err ? ' ' : out; + resolve(commandOut); + }); + }); + } + return commandOut; +}; + +const safeCommandSync = () => { + if (!commandOut) { + try { + commandOut = childProcess.execSync(command, { encoding: 'utf8' }); + } catch (_err) { + commandOut = ' '; + } + } + return commandOut; +}; + +/** + * A String constant containing the value `glibc`. + * @type {string} + * @public + */ +const GLIBC = 'glibc'; + +/** + * A Regexp constant to get the GLIBC Version. + * @type {string} + */ +const RE_GLIBC_VERSION = /LIBC[a-z0-9 \-).]*?(\d+\.\d+)/i; + +/** + * A String constant containing the value `musl`. + * @type {string} + * @public + */ +const MUSL = 'musl'; + +const isFileMusl = (f) => f.includes('libc.musl-') || f.includes('ld-musl-'); + +const familyFromReport = () => { + const report = getReport(); + if (report.header && report.header.glibcVersionRuntime) { + return GLIBC; + } + if (Array.isArray(report.sharedObjects)) { + if (report.sharedObjects.some(isFileMusl)) { + return MUSL; + } + } + return null; +}; + +const familyFromCommand = (out) => { + const [getconf, ldd1] = out.split(/[\r\n]+/); + if (getconf && getconf.includes(GLIBC)) { + return GLIBC; + } + if (ldd1 && ldd1.includes(MUSL)) { + return MUSL; + } + return null; +}; + +const familyFromInterpreterPath = (path) => { + if (path) { + if (path.includes('/ld-musl-')) { + return MUSL; + } else if (path.includes('/ld-linux-')) { + return GLIBC; + } + } + return null; +}; + +const getFamilyFromLddContent = (content) => { + content = content.toString(); + if (content.includes('musl')) { + return MUSL; + } + if (content.includes('GNU C Library')) { + return GLIBC; + } + return null; +}; + +const familyFromFilesystem = async () => { + if (cachedFamilyFilesystem !== undefined) { + return cachedFamilyFilesystem; + } + cachedFamilyFilesystem = null; + try { + const lddContent = await readFile(LDD_PATH); + cachedFamilyFilesystem = getFamilyFromLddContent(lddContent); + } catch (e) {} + return cachedFamilyFilesystem; +}; + +const familyFromFilesystemSync = () => { + if (cachedFamilyFilesystem !== undefined) { + return cachedFamilyFilesystem; + } + cachedFamilyFilesystem = null; + try { + const lddContent = readFileSync(LDD_PATH); + cachedFamilyFilesystem = getFamilyFromLddContent(lddContent); + } catch (e) {} + return cachedFamilyFilesystem; +}; + +const familyFromInterpreter = async () => { + if (cachedFamilyInterpreter !== undefined) { + return cachedFamilyInterpreter; + } + cachedFamilyInterpreter = null; + try { + const selfContent = await readFile(SELF_PATH); + const path = interpreterPath(selfContent); + cachedFamilyInterpreter = familyFromInterpreterPath(path); + } catch (e) {} + return cachedFamilyInterpreter; +}; + +const familyFromInterpreterSync = () => { + if (cachedFamilyInterpreter !== undefined) { + return cachedFamilyInterpreter; + } + cachedFamilyInterpreter = null; + try { + const selfContent = readFileSync(SELF_PATH); + const path = interpreterPath(selfContent); + cachedFamilyInterpreter = familyFromInterpreterPath(path); + } catch (e) {} + return cachedFamilyInterpreter; +}; + +/** + * Resolves with the libc family when it can be determined, `null` otherwise. + * @returns {Promise} + */ +const family = async () => { + let family = null; + if (isLinux()) { + family = await familyFromInterpreter(); + if (!family) { + family = await familyFromFilesystem(); + if (!family) { + family = familyFromReport(); + } + if (!family) { + const out = await safeCommand(); + family = familyFromCommand(out); + } + } + } + return family; +}; + +/** + * Returns the libc family when it can be determined, `null` otherwise. + * @returns {?string} + */ +const familySync = () => { + let family = null; + if (isLinux()) { + family = familyFromInterpreterSync(); + if (!family) { + family = familyFromFilesystemSync(); + if (!family) { + family = familyFromReport(); + } + if (!family) { + const out = safeCommandSync(); + family = familyFromCommand(out); + } + } + } + return family; +}; + +/** + * Resolves `true` only when the platform is Linux and the libc family is not `glibc`. + * @returns {Promise} + */ +const isNonGlibcLinux = async () => isLinux() && await family() !== GLIBC; + +/** + * Returns `true` only when the platform is Linux and the libc family is not `glibc`. + * @returns {boolean} + */ +const isNonGlibcLinuxSync = () => isLinux() && familySync() !== GLIBC; + +const versionFromFilesystem = async () => { + if (cachedVersionFilesystem !== undefined) { + return cachedVersionFilesystem; + } + cachedVersionFilesystem = null; + try { + const lddContent = await readFile(LDD_PATH); + const versionMatch = lddContent.match(RE_GLIBC_VERSION); + if (versionMatch) { + cachedVersionFilesystem = versionMatch[1]; + } + } catch (e) {} + return cachedVersionFilesystem; +}; + +const versionFromFilesystemSync = () => { + if (cachedVersionFilesystem !== undefined) { + return cachedVersionFilesystem; + } + cachedVersionFilesystem = null; + try { + const lddContent = readFileSync(LDD_PATH); + const versionMatch = lddContent.match(RE_GLIBC_VERSION); + if (versionMatch) { + cachedVersionFilesystem = versionMatch[1]; + } + } catch (e) {} + return cachedVersionFilesystem; +}; + +const versionFromReport = () => { + const report = getReport(); + if (report.header && report.header.glibcVersionRuntime) { + return report.header.glibcVersionRuntime; + } + return null; +}; + +const versionSuffix = (s) => s.trim().split(/\s+/)[1]; + +const versionFromCommand = (out) => { + const [getconf, ldd1, ldd2] = out.split(/[\r\n]+/); + if (getconf && getconf.includes(GLIBC)) { + return versionSuffix(getconf); + } + if (ldd1 && ldd2 && ldd1.includes(MUSL)) { + return versionSuffix(ldd2); + } + return null; +}; + +/** + * Resolves with the libc version when it can be determined, `null` otherwise. + * @returns {Promise} + */ +const version = async () => { + let version = null; + if (isLinux()) { + version = await versionFromFilesystem(); + if (!version) { + version = versionFromReport(); + } + if (!version) { + const out = await safeCommand(); + version = versionFromCommand(out); + } + } + return version; +}; + +/** + * Returns the libc version when it can be determined, `null` otherwise. + * @returns {?string} + */ +const versionSync = () => { + let version = null; + if (isLinux()) { + version = versionFromFilesystemSync(); + if (!version) { + version = versionFromReport(); + } + if (!version) { + const out = safeCommandSync(); + version = versionFromCommand(out); + } + } + return version; +}; + +module.exports = { + GLIBC, + MUSL, + family, + familySync, + isNonGlibcLinux, + isNonGlibcLinuxSync, + version, + versionSync +}; diff --git a/dg-ui/node_modules/detect-libc/lib/elf.js b/dg-ui/node_modules/detect-libc/lib/elf.js new file mode 100644 index 0000000..aa166aa --- /dev/null +++ b/dg-ui/node_modules/detect-libc/lib/elf.js @@ -0,0 +1,39 @@ +// Copyright 2017 Lovell Fuller and others. +// SPDX-License-Identifier: Apache-2.0 + +'use strict'; + +const interpreterPath = (elf) => { + if (elf.length < 64) { + return null; + } + if (elf.readUInt32BE(0) !== 0x7F454C46) { + // Unexpected magic bytes + return null; + } + if (elf.readUInt8(4) !== 2) { + // Not a 64-bit ELF + return null; + } + if (elf.readUInt8(5) !== 1) { + // Not little-endian + return null; + } + const offset = elf.readUInt32LE(32); + const size = elf.readUInt16LE(54); + const count = elf.readUInt16LE(56); + for (let i = 0; i < count; i++) { + const headerOffset = offset + (i * size); + const type = elf.readUInt32LE(headerOffset); + if (type === 3) { + const fileOffset = elf.readUInt32LE(headerOffset + 8); + const fileSize = elf.readUInt32LE(headerOffset + 32); + return elf.subarray(fileOffset, fileOffset + fileSize).toString().replace(/\0.*$/g, ''); + } + } + return null; +}; + +module.exports = { + interpreterPath +}; diff --git a/dg-ui/node_modules/detect-libc/lib/filesystem.js b/dg-ui/node_modules/detect-libc/lib/filesystem.js new file mode 100644 index 0000000..4c2443c --- /dev/null +++ b/dg-ui/node_modules/detect-libc/lib/filesystem.js @@ -0,0 +1,51 @@ +// Copyright 2017 Lovell Fuller and others. +// SPDX-License-Identifier: Apache-2.0 + +'use strict'; + +const fs = require('fs'); + +const LDD_PATH = '/usr/bin/ldd'; +const SELF_PATH = '/proc/self/exe'; +const MAX_LENGTH = 2048; + +/** + * Read the content of a file synchronous + * + * @param {string} path + * @returns {Buffer} + */ +const readFileSync = (path) => { + const fd = fs.openSync(path, 'r'); + const buffer = Buffer.alloc(MAX_LENGTH); + const bytesRead = fs.readSync(fd, buffer, 0, MAX_LENGTH, 0); + fs.close(fd, () => {}); + return buffer.subarray(0, bytesRead); +}; + +/** + * Read the content of a file + * + * @param {string} path + * @returns {Promise} + */ +const readFile = (path) => new Promise((resolve, reject) => { + fs.open(path, 'r', (err, fd) => { + if (err) { + reject(err); + } else { + const buffer = Buffer.alloc(MAX_LENGTH); + fs.read(fd, buffer, 0, MAX_LENGTH, 0, (_, bytesRead) => { + resolve(buffer.subarray(0, bytesRead)); + fs.close(fd, () => {}); + }); + } + }); +}); + +module.exports = { + LDD_PATH, + SELF_PATH, + readFileSync, + readFile +}; diff --git a/dg-ui/node_modules/detect-libc/lib/process.js b/dg-ui/node_modules/detect-libc/lib/process.js new file mode 100644 index 0000000..ee78ad2 --- /dev/null +++ b/dg-ui/node_modules/detect-libc/lib/process.js @@ -0,0 +1,24 @@ +// Copyright 2017 Lovell Fuller and others. +// SPDX-License-Identifier: Apache-2.0 + +'use strict'; + +const isLinux = () => process.platform === 'linux'; + +let report = null; +const getReport = () => { + if (!report) { + /* istanbul ignore next */ + if (isLinux() && process.report) { + const orig = process.report.excludeNetwork; + process.report.excludeNetwork = true; + report = process.report.getReport(); + process.report.excludeNetwork = orig; + } else { + report = {}; + } + } + return report; +}; + +module.exports = { isLinux, getReport }; diff --git a/dg-ui/node_modules/detect-libc/package.json b/dg-ui/node_modules/detect-libc/package.json new file mode 100644 index 0000000..36d0f2b --- /dev/null +++ b/dg-ui/node_modules/detect-libc/package.json @@ -0,0 +1,44 @@ +{ + "name": "detect-libc", + "version": "2.1.2", + "description": "Node.js module to detect the C standard library (libc) implementation family and version", + "main": "lib/detect-libc.js", + "files": [ + "lib/", + "index.d.ts" + ], + "scripts": { + "test": "semistandard && nyc --reporter=text --check-coverage --branches=100 ava test/unit.js", + "changelog": "conventional-changelog -i CHANGELOG.md -s", + "bench": "node benchmark/detect-libc", + "bench:calls": "node benchmark/call-familySync.js && sleep 1 && node benchmark/call-isNonGlibcLinuxSync.js && sleep 1 && node benchmark/call-versionSync.js" + }, + "repository": { + "type": "git", + "url": "git://github.com/lovell/detect-libc.git" + }, + "keywords": [ + "libc", + "glibc", + "musl" + ], + "author": "Lovell Fuller ", + "contributors": [ + "Niklas Salmoukas ", + "Vinícius Lourenço " + ], + "license": "Apache-2.0", + "devDependencies": { + "ava": "^2.4.0", + "benchmark": "^2.1.4", + "conventional-changelog-cli": "^5.0.0", + "eslint-config-standard": "^13.0.1", + "nyc": "^15.1.0", + "proxyquire": "^2.1.3", + "semistandard": "^14.2.3" + }, + "engines": { + "node": ">=8" + }, + "types": "index.d.ts" +} diff --git a/dg-ui/node_modules/enhanced-resolve/LICENSE b/dg-ui/node_modules/enhanced-resolve/LICENSE new file mode 100644 index 0000000..8c11fc7 --- /dev/null +++ b/dg-ui/node_modules/enhanced-resolve/LICENSE @@ -0,0 +1,20 @@ +Copyright JS Foundation and other contributors + +Permission is hereby granted, free of charge, to any person obtaining +a copy of this software and associated documentation files (the +'Software'), to deal in the Software without restriction, including +without limitation the rights to use, copy, modify, merge, publish, +distribute, sublicense, and/or sell copies of the Software, and to +permit persons to whom the Software is furnished to do so, subject to +the following conditions: + +The above copyright notice and this permission notice shall be +included in all copies or substantial portions of the Software. + +THE SOFTWARE IS PROVIDED 'AS IS', WITHOUT WARRANTY OF ANY KIND, +EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF +MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. +IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY +CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION OF CONTRACT, +TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION WITH THE +SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE. diff --git a/dg-ui/node_modules/enhanced-resolve/README.md b/dg-ui/node_modules/enhanced-resolve/README.md new file mode 100644 index 0000000..a1ac5c5 --- /dev/null +++ b/dg-ui/node_modules/enhanced-resolve/README.md @@ -0,0 +1,907 @@ +# enhanced-resolve + +[![npm][npm]][npm-url] +[![Build Status][build-status]][build-status-url] +[![codecov][codecov-badge]][codecov-url] +[![Install Size][size]][size-url] +[![GitHub Discussions][discussion]][discussion-url] + +Offers an async require.resolve function. It's highly configurable. + +## Features + +- plugin system +- provide a custom filesystem +- sync and async node.js filesystems included + +## Getting Started + +### Install + +```sh +# npm +npm install enhanced-resolve +# or Yarn +yarn add enhanced-resolve +# or pnpm +pnpm add enhanced-resolve +``` + +### Resolve + +There is a Node.js API which allows to resolve requests according to the Node.js resolving rules. +Sync, async (callback) and promise APIs are offered. A `create` method allows to create a custom resolve function. + +```js +const resolve = require("enhanced-resolve"); + +resolve("/some/path/to/folder", "module/dir", (err, result) => { + result; // === "/some/path/node_modules/module/dir/index.js" +}); + +resolve.sync("/some/path/to/folder", "../../dir"); +// === "/some/path/dir/index.js" + +const result = await resolve.promise("/some/path/to/folder", "../../dir"); +// === "/some/path/dir/index.js" + +const myResolve = resolve.create({ + // or resolve.create.sync / resolve.create.promise + extensions: [".ts", ".js"], + // see more options below +}); + +myResolve("/some/path/to/folder", "ts-module", (err, result) => { + result; // === "/some/node_modules/ts-module/index.ts" +}); +``` + +### Public API + +All of the following are exposed from `require("enhanced-resolve")`. + +#### `resolve(context?, parent, specifier, resolveContext?, callback)` + +Async Node-style resolver using the built-in defaults (`conditionNames: ["node"]`, `extensions: [".js", ".json", ".node"]`). Both `context` and `resolveContext` are optional, so the function accepts four shapes: + +```js +resolve(context, parent, specifier, resolveContext, callback); +resolve(context, parent, specifier, callback); +resolve(parent, specifier, resolveContext, callback); +resolve(parent, specifier, callback); // most common +``` + +The `parent` / `specifier` naming mirrors the ECMAScript resolution terms (as in `import.meta.resolve(specifier, parent)`): `parent` is the location you resolve **from**, and `specifier` is the string being resolved. + +##### Arguments — what each one is and when to pass it + +| Argument | Required | What it is | When to pass it | +| ---------------- | -------- | ---------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------- | ----------------------------------------------------------------------------------------------------------------------------- | +| `context` | no | Extra info about _who_ is requesting, e.g. `{ environments: ["node+es3+es5+process+native"] }`. Plugins can read arbitrary keys off it. When omitted, a built-in Node context is used. | Pass it only when a plugin you use reads from it. Most callers omit it. | +| `parent` | yes | The absolute directory to resolve **from** — the location the `specifier` is relative to (the ECMAScript "parent", historically called the "lookup start path"). | Always. | +| `specifier` | yes | The string to resolve — a relative specifier (`./utils`), a bare module (`lodash/merge`), an alias, etc. (the ECMAScript "specifier", historically called the "request"). | Always. | +| `resolveContext` | no | A collector object the resolver writes into / reads from: `fileDependencies`, `contextDependencies`, `missingDependencies` (`Set`s it fills in), `log` (a function it calls for trace output). | Pass it when you need to know which files/dirs were touched (e.g. to set up a watcher) or want a log of the resolution steps. | +| `callback` | yes | `(err, result, resolveRequest) => void`. `result` is the resolved absolute path (or `false` if the request resolves to an ignored module). `resolveRequest` is the full request object with `path`, `query`, `fragment`, `descriptionFilePath`, etc. | Always. | + +##### Minimal form — just `parent`, `specifier`, `callback` + +```js +const resolve = require("enhanced-resolve"); + +resolve(__dirname, "./utils", (err, result) => { + if (err) throw err; + result; // === "/abs/path/to/utils.js" +}); +``` + +##### Inspecting the full result via the third callback argument + +```js +resolve(__dirname, "./utils?query#frag", (err, result, resolveRequest) => { + result; // === "/abs/path/to/utils.js?query#frag" — path with query/fragment appended + resolveRequest.path; // === "/abs/path/to/utils.js" (the bare path, no query/fragment) + resolveRequest.query; // === "?query" (empty string if the request has none) + resolveRequest.fragment; // === "#frag" (empty string if the request has none) + resolveRequest.descriptionFilePath; // path to the nearest package.json, if any +}); +``` + +##### With `resolveContext` — collect dependencies and a log + +Pass a `resolveContext` when you need the resolver to report back _what it looked at_. The `Set`s you provide are filled in during resolution, and `log` is called with each step: + +```js +const fileDependencies = new Set(); +const missingDependencies = new Set(); +const contextDependencies = new Set(); +const logs = []; + +resolve( + __dirname, + "./utils", + { + fileDependencies, // files that were read/checked + missingDependencies, // paths that were probed but didn't exist + contextDependencies, // directories that were read + log: (msg) => logs.push(msg), // trace of each resolution step + }, + (err, result) => { + result; // === "/abs/path/to/utils.js" + fileDependencies; // Set { ".../utils.js", ".../package.json", ... } + missingDependencies; // Set { ".../utils", ".../utils.json", ... } (candidates tried) + // `fileDependencies` / `missingDependencies` are exactly what you'd feed + // a file watcher so a rebuild re-runs when any of them changes. + }, +); +``` + +##### With a custom `context` + +Pass a `context` when a plugin reads from it. The default resolver only uses `environments`, but custom plugins may key off anything you put here: + +```js +resolve( + { environments: ["node+es3+es5+process+native"] }, // context + __dirname, + "./utils", + (err, result) => { + result; // === "/abs/path/to/utils.js" + }, +); +``` + +#### `resolve.sync(context?, parent, specifier, resolveContext?) => string | false` + +Synchronous variant. Throws on failure, returns `false` when the resolve yields no result. + +```js +const file = resolve.sync(__dirname, "./utils"); +``` + +#### `resolve.promise(context?, parent, specifier, resolveContext?) => Promise` + +Promise variant of `resolve`. + +```js +const file = await resolve.promise(__dirname, "./utils"); +``` + +#### `resolve.create(options) => ResolveFunctionAsync` + +Builds a customized async resolve function. Options are the same as for [`ResolverFactory.createResolver`](#resolver-options); `fileSystem` defaults to the built-in Node.js filesystem. + +```js +const resolveTs = resolve.create({ extensions: [".ts", ".tsx", ".js"] }); + +resolveTs(__dirname, "./component", (err, result) => { + // result === "/abs/path/to/component.tsx" +}); +``` + +#### `resolve.create.sync(options) => ResolveFunction` + +Sync variant of `resolve.create`. + +```js +const resolveTsSync = resolve.create.sync({ extensions: [".ts", ".js"] }); +const file = resolveTsSync(__dirname, "./component"); +``` + +#### `resolve.create.promise(options) => ResolveFunctionPromise` + +Promise variant of `resolve.create`. + +```js +const resolveTsPromise = resolve.create.promise({ extensions: [".ts", ".js"] }); +const file = await resolveTsPromise(__dirname, "./component"); +``` + +#### `ResolverFactory.createResolver(options) => Resolver` + +Lower-level factory. Returns a `Resolver` whose `resolve`, `resolveSync`, and `resolvePromise` methods accept `(context, parent, specifier, resolveContext, [callback])`. Use this when you need a reusable resolver instance or access to its `hooks` (see the [Plugins](#plugins) section). `fileSystem` is required here — the high-level `resolve.create` defaults it for you. + +```js +const fs = require("fs"); +const { CachedInputFileSystem, ResolverFactory } = require("enhanced-resolve"); + +const resolver = ResolverFactory.createResolver({ + fileSystem: new CachedInputFileSystem(fs, 4000), + extensions: [".js", ".json"], +}); + +// callback +resolver.resolve({}, __dirname, "./utils", {}, (err, file) => { + // ... +}); + +// sync (requires a sync fileSystem) +const fileSync = resolver.resolveSync({}, __dirname, "./utils"); + +// promise +const filePromise = await resolver.resolvePromise({}, __dirname, "./utils", {}); +``` + +#### `CachedInputFileSystem(fileSystem, duration)` + +Wraps any Node-compatible `fs` to add an in-memory cache for `stat`, `readdir`, `readFile`, `readJson`, and `readlink`. `duration` is the cache TTL in milliseconds (typically `4000`). Call `.purge()` to invalidate, or `.purge(path)` / `.purge([path, ...])` to invalidate specific entries — do this whenever you know files changed (e.g. from a watcher). + +```js +const fs = require("fs"); +const { CachedInputFileSystem } = require("enhanced-resolve"); + +const cachedFs = new CachedInputFileSystem(fs, 4000); +// later, when files change: +cachedFs.purge("/abs/path/to/changed-file.js"); +``` + +#### Exported plugins & helpers + +For use with the `plugins` option or as standalone utilities: + +- `ResolverFactory` — see above. +- `CachedInputFileSystem` — see above. +- `CloneBasenamePlugin(source, target)` — joins the directory's basename onto the path. See [Built-in Plugins](#built-in-plugins). +- `LogInfoPlugin(source)` — logs pipeline state at a hook; enable by passing a `log` function on the `resolveContext`. +- `TsconfigPathsPlugin(options)` — applies `tsconfig.json` `paths` / `baseUrl` mappings; typically configured via the `tsconfig` resolver option instead. +- `forEachBail(array, iterator, callback)` — bail-style async iterator used internally; useful when authoring plugins that try several candidates in order. + +```js +const { LogInfoPlugin } = require("enhanced-resolve"); + +const resolver = ResolverFactory.createResolver({ + fileSystem: cachedFs, + extensions: [".js"], + plugins: [new LogInfoPlugin("described-resolve")], +}); + +resolver.resolve( + {}, + __dirname, + "./utils", + { log: (msg) => console.log(msg) }, + () => {}, +); +``` + +### Creating a Resolver + +The easiest way to create a resolver is to use the `createResolver` function on `ResolveFactory`, along with one of the supplied File System implementations. + +```js +const fs = require("fs"); +const { CachedInputFileSystem, ResolverFactory } = require("enhanced-resolve"); + +// create a resolver +const myResolver = ResolverFactory.createResolver({ + // Typical usage will consume the `fs` + `CachedInputFileSystem`, which wraps Node.js `fs` to add caching. + fileSystem: new CachedInputFileSystem(fs, 4000), + extensions: [".js", ".json"], + /* any other resolver options here. Options/defaults can be seen below */ +}); + +// resolve a file with the new resolver +const context = {}; +const parent = "/Users/webpack/some/root/dir"; // directory to resolve from +const specifier = "./path/to-look-up.js"; // string to resolve +const resolveContext = {}; + +// callback +myResolver.resolve( + context, + parent, + specifier, + resolveContext, + (err /* Error */, filepath /* string */) => { + // Do something with the path + }, +); + +// promise +try { + const filepath = await myResolver.resolvePromise( + context, + parent, + specifier, + resolveContext, + ); + // Do something with the path +} catch (err) { + // handle resolve failure +} + +// sync (requires a sync fileSystem, e.g. the default Node.js one) +const filepath = myResolver.resolveSync(context, parent, specifier); +``` + +#### Resolver Options + +| Field | Default | Description | +| ------------------------ | --------------------------- | ------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------- | +| alias | [] | A list of module alias configurations or an object which maps key to value | +| aliasFields | [] | A list of alias fields in description files | +| extensionAlias | {} | An object which maps extension to extension aliases | +| extensionAliasForExports | false | Also apply `extensionAlias` to paths resolved through the package.json `exports` field. Off by default (Node.js-aligned) | +| cachePredicate | function() { return true }; | A function which decides whether a request should be cached or not. An object is passed to the function with `path` and `request` properties. | +| cacheWithContext | true | If unsafe cache is enabled, includes `request.context` in the cache key | +| conditionNames | [] | A list of exports field condition names | +| descriptionFiles | ["package.json"] | A list of description files to read from | +| enforceExtension | false | Enforce that a extension from extensions must be used | +| exportsFields | ["exports"] | A list of exports fields in description files | +| extensions | [".js", ".json", ".node"] | A list of extensions which should be tried for files | +| fallback | [] | Same as `alias`, but only used if default resolving fails | +| fileSystem | | The file system which should be used | +| fullySpecified | false | Request passed to resolve is already fully specified and extensions or main files are not resolved for it (they are still resolved for internal requests) | +| mainFields | ["main"] | A list of main fields in description files | +| mainFiles | ["index"] | A list of main files in directories | +| modules | ["node_modules"] | A list of directories to resolve modules from, can be absolute path or folder name | +| packageMap | undefined | **Experimental.** A [Node.js package map](https://nodejs.org/api/packages.html#package-maps): a path (or `file:` URL) to the configuration file, or an object with `configFile` and already-parsed `packages`. Bare specifiers then resolve through the map instead of `node_modules`. | +| plugins | [] | A list of additional resolve plugins which should be applied | +| resolver | undefined | A prepared Resolver to which the plugins are attached | +| resolveToContext | false | Resolve to a context instead of a file | +| preferRelative | false | Prefer to resolve module requests as relative request and fallback to resolving as module | +| preferAbsolute | false | Prefer to resolve server-relative urls as absolute paths before falling back to resolve in roots | +| restrictions | [] | A list of resolve restrictions | +| roots | [] | A list of root paths | +| symlinks | true | Whether to resolve symlinks to their symlinked location | +| tsconfig | false | TypeScript config for paths mapping. Can be `false` (disabled), `true` (use default `tsconfig.json`), a string path to `tsconfig.json`, or an object with `configFile`, `references`, and `baseUrl` options. Supports JSONC format (comments and trailing commas) like TypeScript compiler. | +| tsconfig.configFile | tsconfig.json | Path to the tsconfig.json file | +| tsconfig.references | [] | Project references. `'auto'` to load from tsconfig, or an array of paths to referenced projects | +| tsconfig.baseUrl | undefined | Override baseUrl from tsconfig.json. If provided, this value will be used instead of the baseUrl in the tsconfig file | +| unsafeCache | false | Use this cache object to unsafely cache the successful requests | + +#### Option Examples + +Small snippets for the non-obvious options. All options are passed to `resolve.create({ ... })` or `ResolverFactory.createResolver({ ... })`. + +**`alias`** — rewrite matching requests to a target path, module, or to `false` to ignore them. Accepts an object or an array of entries (array form lets you specify ordering / `onlyModule`). + +```js +const options = { + alias: { + "@": path.resolve(__dirname, "src"), // @/utils → src/utils + lodash$: "lodash-es", // exact "lodash", not "lodash/foo" + "ignored-module": false, // short-circuit to an empty module + }, +}; +``` + +**`aliasFields`** — read alias maps from fields in `package.json`. The `browser` field is the common case: + +```js +const options = { aliasFields: ["browser"] }; +``` + +**`extensionAlias`** — maps one request extension to a list of candidate extensions. Useful for TypeScript ESM where imports are written with `.js` but the source is `.ts`. Applies both to direct requests (e.g. `./foo.js`) and to paths produced by the package.json `imports` field (e.g. `#foo` → `./foo.js` → `./foo.ts`). By default it does **not** apply to paths produced by the `exports` field (to stay aligned with Node.js, which does not substitute extensions on package-exported paths) — see `extensionAliasForExports` below to opt in: + +```js +const options = { + extensionAlias: { + ".js": [".ts", ".js"], + ".mjs": [".mts", ".mjs"], + }, +}; +``` + +**`extensionAliasForExports`** — when `true`, also apply `extensionAlias` to paths resolved through the package.json `exports` field. Off by default to match Node.js. Turn it on if you want full alignment with TypeScript's resolver for packages that ship `.ts` sources alongside the compiled `.js` files they list in `exports` (e.g. monorepo source packages, or the `eslint-import-resolver-typescript` use case): + +```js +const options = { + extensionAlias: { ".js": [".ts", ".js"] }, + extensionAliasForExports: true, +}; +``` + +**`conditionNames` + `exportsFields`** — pick which conditions to match in the `exports` field of `package.json`: + +```js +const options = { + conditionNames: ["import", "node", "default"], + exportsFields: ["exports"], +}; +``` + +**`extensions`** — extensions to try for extensionless requests, in order: + +```js +const options = { extensions: [".ts", ".tsx", ".js", ".json"] }; +``` + +**`fallback`** — same shape as `alias`, but only consulted when the primary resolve fails. Handy for polyfills: + +```js +const options = { + fallback: { + crypto: require.resolve("crypto-browserify"), + stream: false, + }, +}; +``` + +**`modules`** — where to look for bare-module requests. Entries can be folder names (searched hierarchically up the tree) or absolute paths (searched directly): + +```js +const options = { modules: [path.resolve(__dirname, "src"), "node_modules"] }; +``` + +**`mainFields` / `mainFiles`** — fields in `package.json` to try for a package entry point, and filenames to try inside a directory: + +```js +const options = { + mainFields: ["browser", "module", "main"], + mainFiles: ["index"], +}; +``` + +**`roots` + `preferAbsolute`** — resolve server-relative URLs (starting with `/`) against one or more root directories. With `preferAbsolute: true`, absolute-path resolution is tried before the roots are consulted. + +```js +const options = { + roots: [path.resolve(__dirname, "public")], + preferAbsolute: false, +}; +``` + +**`restrictions`** — reject results that don't satisfy at least one restriction. Accepts strings (path prefixes) or `RegExp`s: + +```js +const options = { + restrictions: [path.resolve(__dirname, "src"), /\.(js|ts)$/], +}; +``` + +**`tsconfig`** — apply TypeScript `paths` / `baseUrl` mappings. Either pass `true` to load `./tsconfig.json`, a path string, or a configuration object: + +```js +const options = { + tsconfig: { + configFile: path.resolve(__dirname, "tsconfig.json"), + references: "auto", // honor project references declared in tsconfig + }, +}; +``` + +**`symlinks`** — resolve to the real path by following symlinks. Set to `false` to keep the symlinked path (common for monorepo / pnpm layouts where you want module identity tied to the workspace location): + +```js +const options = { symlinks: false }; +``` + +**`fullySpecified`** — require fully-specified requests (no extension inference, no `index` lookup) for non-internal requests. Matches Node.js ESM semantics: + +```js +const options = { fullySpecified: true }; +``` + +**`unsafeCache`** — pass an object to use as an in-memory cache of successful resolves. Set to `true` to let the resolver allocate its own: + +```js +const options = { + unsafeCache: {}, // or true + cacheWithContext: false, // skip context in the cache key — faster, but only safe if context doesn't change the result +}; +``` + +To observe whether a request was served from the cache, wrap the cache object in a `Proxy`. `UnsafeCachePlugin` reads entries with `cache[id]` (cache lookup) and writes them with `cache[id] = result` (cache store), so trapping `get` and `set` is enough to distinguish hits from misses: + +```js +const cache = {}; +const observedCache = new Proxy(cache, { + get(target, name, receiver) { + const hit = name in target; + console.log(hit ? `[cache hit] ${name}` : `[cache miss] ${name}`); + return Reflect.get(target, name, receiver); + }, + set(target, name, value, receiver) { + console.log(`[cache set] ${name}`); + return Reflect.set(target, name, value, receiver); + }, +}); + +const resolver = ResolverFactory.createResolver({ + fileSystem: new CachedInputFileSystem(fs, 4000), + extensions: [".js", ".json"], + unsafeCache: observedCache, +}); +``` + +The `name` argument is the cache id — a `JSON.stringify`'d object containing `type`, `context`, `path`, `query`, `fragment`, and `request` — so you can parse it to report on specific resolves. Only successful resolves go through the cache; failures never touch it. + +**`fileSystem`** — any `fs`-compatible implementation. Usually `new CachedInputFileSystem(fs, 4000)`; can be a virtual filesystem (e.g. `memfs`) for testing: + +```js +const options = { fileSystem: new CachedInputFileSystem(require("fs"), 4000) }; +``` + +**`packageMap`** (**experimental**) — resolve bare specifiers through a [Node.js package map](https://nodejs.org/api/packages.html#package-maps) instead of walking `node_modules`. Each package entry declares where it lives and which package id every bare specifier of its own maps to: + +```json +{ + "packages": { + "app": { + "url": "./packages/app", + "dependencies": { "@acme/utils": "utils" } + }, + "utils": { "url": "./packages/utils" } + } +} +``` + +```js +const options = { packageMap: path.resolve("./package-map.json") }; +// or, with the map already in memory: +const options2 = { + packageMap: { + // relative `url` values are resolved against this path + configFile: path.resolve("./package-map.json"), + packages: {/* ... */}, + }, +}; +``` + +The map is authoritative: when it is set, a bare specifier that the importing package does not declare is reported as unresolved rather than looked up in `node_modules`. Relative and absolute requests, and `node:` builtins, are unaffected. + +Because a package map may point several package ids at the same `url` (the same sources used with different dependency tables), the importing package cannot always be derived from the file path alone. Pass the package id along to remove the ambiguity — it is available on every result as `packageId`: + +```js +resolver({}, parent, specifier, {}, (err, result, request) => { + // `request.packageId` is the package the request resolved into; pass it + // back in as `context.packageId` for resolutions made from `result`. + resolver({ packageId: request.packageId }, result, next, {}, callback); +}); +``` + +Resolution fails with an error (rather than silently picking one) when the importing file lies outside every mapped package (`ERR_PACKAGE_MAP_EXTERNAL_FILE`) or when several package ids share its location and no package id was given (`ERR_PACKAGE_MAP_AMBIGUOUS_PACKAGE`). + +> Package maps are stability 1 (experimental) in Node.js, where they are only reachable behind `--experimental-package-map`. This option tracks that specification and may change with it, including in a patch release. + +**`plugins`** — additional plugin instances appended to the pipeline. See [Plugins](#plugins): + +```js +const options = { + plugins: [new TsconfigPathsPlugin({ configFile: "./tsconfig.json" })], +}; +``` + +## Plugins + +Similar to `webpack`, the core of `enhanced-resolve` functionality is implemented as individual plugins that are executed using [`tapable`](https://github.com/webpack/tapable). +These plugins can extend the functionality of the library, adding other ways for files/contexts to be resolved. + +A plugin should be a `class` (or its ES5 equivalent) with an `apply` method. The `apply` method will receive a `resolver` instance, that can be used to hook in to the event system. + +Plugins are executed in a pipeline, and register which event they should be executed before/after. `source` is the name of the event that starts the pipeline, and `target` is what event this plugin should fire, which is what continues the execution of the pipeline. For a full view of how these plugin events form a chain, see `lib/ResolverFactory.js`, in the `//// pipeline ////` section. + +### Built-in Plugins + +`enhanced-resolve` ships with the following plugins. Most of them are wired up automatically by `ResolverFactory` based on the [resolver options](#resolver-options); the ones exported from the package entry (`TsconfigPathsPlugin`, `CloneBasenamePlugin`, `LogInfoPlugin`) are the ones you're most likely to use explicitly. + +| Plugin | Purpose | +| ---------------------------------------- | ------------------------------------------------------------------------------------------------------------------------------------ | +| `AliasPlugin` | Replaces a matching request with one or more alternative targets. Powers the `alias` and `fallback` options. | +| `AliasFieldPlugin` | Applies aliasing based on a field in the description file (e.g. the `browser` field). Powers `aliasFields`. | +| `AppendPlugin` | Appends a string (typically an extension) to the current path. Used for `extensions`. | +| `CloneBasenamePlugin` | Joins the current directory basename onto the path (e.g. `/foo/bar` → `/foo/bar/bar`). Useful for directory-named main-file schemes. | +| `ConditionalPlugin` | Forwards the request only when it matches a given partial request shape. | +| `DescriptionFilePlugin` | Finds and loads the nearest description file (e.g. `package.json`) so other plugins can read its fields. Powers `descriptionFiles`. | +| `DirectoryExistsPlugin` | Only continues the pipeline if the current path is an existing directory. | +| `ExportsFieldPlugin` | Resolves requests through the `exports` field of a package's description file. Powers `exportsFields` and `conditionNames`. | +| `ExtensionAliasPlugin` | Maps one extension to a list of alternative extensions (e.g. `.js` → `.ts`, `.js`). Powers `extensionAlias`. | +| `FileExistsPlugin` | Only continues the pipeline if the current path is an existing file, and records the file as a dependency. | +| `ImportsFieldPlugin` | Resolves `#name` requests through the `imports` field of the enclosing package. | +| `JoinRequestPlugin` | Joins the current path with the current request into a new path. | +| `JoinRequestPartPlugin` | Splits a module request into module name + inner request, joining the inner request onto the path. | +| `LogInfoPlugin` | Emits verbose log output at a given pipeline step. Handy for debugging resolves via `resolveContext.log`. | +| `MainFieldPlugin` | Uses a field in the description file (e.g. `main`) to point to the entry file of a package. Powers `mainFields`. | +| `ModulesInHierarchicalDirectoriesPlugin` | Searches for a module by walking up parent directories (the standard `node_modules` lookup). Powers `modules`. | +| `ModulesInRootPlugin` | Searches for a module in a single absolute directory. Powers absolute-path entries in `modules`. | +| `NextPlugin` | Forwards the request from one hook to another without modification — glue between pipeline steps. | +| `PackageMapPlugin` | Resolves bare specifiers through a Node.js package map instead of `node_modules`. Powers `packageMap`. **Experimental.** | +| `ParsePlugin` | Parses a raw request string into its components (path, query, fragment, module flag, etc.). | +| `PnpPlugin` | Resolves module requests through a Yarn PnP API when one is available. | +| `RestrictionsPlugin` | Rejects results that don't match a list of path restrictions (strings or regular expressions). Powers `restrictions`. | +| `ResultPlugin` | Terminal plugin that fires the `result` hook — signals a successful resolve. | +| `RootsPlugin` | Resolves server-relative URL requests (starting with `/`) against one or more root directories. Powers `roots`. | +| `SelfReferencePlugin` | Resolves a package self-reference (e.g. `my-pkg/foo` from within `my-pkg`). | +| `SymlinkPlugin` | Real paths the resolved file by following symlinks. Can be disabled via the `symlinks` option. | +| `TryNextPlugin` | Forwards the request to the next hook with a log message. Useful for trying alternative resolutions. | +| `TsconfigPathsPlugin` | Rewrites requests using the `paths` and `baseUrl` from a `tsconfig.json`. Powers the `tsconfig` option. | +| `UnsafeCachePlugin` | Caches successful resolves in an in-memory map to speed up repeated requests. Powers `unsafeCache`. | +| `UseFilePlugin` | Joins a fixed filename onto the current path (e.g. `index`). Powers `mainFiles`. | + +#### Plugin wiring and goals + +One-line goal and default wiring (`source → target`) for each plugin. `*` means the plugin is tapped on several hooks — the common ones are listed. Plugins without a fixed wiring are user-tapped. + +- **`AliasPlugin`** — Goal: redirect requests matching a configured key to an alternative target. `raw-resolve` → `internal-resolve` for `alias`; `file` → `internal-resolve` as a last-chance remap; `described-resolve` → `internal-resolve` for `fallback`. +- **`AliasFieldPlugin`** — Goal: apply aliases declared in a description-file field like `browser`, so environment-specific substitutions happen without user config. `raw-resolve` / `file` → `internal-resolve`. +- **`AppendPlugin`** — Goal: try appending a fixed string (usually an extension) to the current path. `raw-file` → `file`, one instance per entry in `extensions`. +- **`CloneBasenamePlugin`** — Goal: join the directory's basename onto the path (e.g. `/foo/bar` → `/foo/bar/bar`) for directory-named-main layouts. User-wired via `plugins`. +- **`ConditionalPlugin`** — Goal: gate a forward on a partial match of the request shape (e.g. `{ module: true }`), used to fan-out at branching hooks. Tapped on `after-normal-resolve`, `resolve-as-module`, `described-relative`, and `raw-file`. +- **`DescriptionFilePlugin`** — Goal: locate and attach the nearest description file (usually `package.json`) so downstream plugins can read its fields. `parsed-resolve` → `described-resolve`, `relative` → `described-relative`, `undescribed-resolve-in-package` → `resolve-in-package`, `undescribed-existing-directory` → `existing-directory`, `undescribed-raw-file` → `raw-file`. +- **`DirectoryExistsPlugin`** — Goal: only continue the pipeline if the current path exists as a directory. `resolve-as-module` → `undescribed-resolve-in-package`, `directory` → `undescribed-existing-directory`. +- **`ExportsFieldPlugin`** — Goal: map a request through the `exports` field of a package's description file (with `conditionNames`). `resolve-in-package` → `relative`. +- **`ExtensionAliasPlugin`** — Goal: rewrite a request's extension to a list of candidate extensions (e.g. `.js` → `.ts`, `.js`) for TypeScript ESM and similar. `raw-resolve` → `normal-resolve` for direct requests; also `imports-field-relative` → `relative` so extension substitution applies to `imports`-field targets. +- **`FileExistsPlugin`** — Goal: confirm a candidate path exists as a file and record it as a file dependency. `final-file` → `existing-file`. +- **`ImportsFieldPlugin`** — Goal: resolve `#name` requests through the `imports` field of the enclosing package. `internal` → `imports-field-relative` (relative target) or `imports-resolve` (bare target). +- **`JoinRequestPlugin`** — Goal: join the current path with the current request into a single concrete path. `after-normal-resolve` → `relative` (three stage-offset copies for `preferRelative`, `preferAbsolute`, and default), `resolve-in-existing-directory` → `relative`. +- **`JoinRequestPartPlugin`** — Goal: split a module request into module name + inner request, joining the inner part onto the path. `module` → `resolve-as-module`. +- **`LogInfoPlugin`** — Goal: emit verbose log output at a chosen hook; enable by passing a `log` function on `resolveContext`. User-wired via `plugins`. +- **`MainFieldPlugin`** — Goal: follow a description-file field (e.g. `main`, `module`, `browser`) to the entry file of a package. `existing-directory` → `resolve-in-existing-directory`, one instance per entry in `mainFields`. +- **`ModulesInHierarchicalDirectoriesPlugin`** — Goal: search for a module by walking up parent directories (the standard `node_modules` lookup). `raw-module` → `module`; when PnP is enabled, `alternate-raw-module` → `module` too. +- **`ModulesInRootPlugin`** — Goal: search for a module in a single absolute directory (powers absolute-path entries in `modules`). `raw-module` → `module`. +- **`NextPlugin`** — Goal: glue — forward the current request unchanged from one hook to another. Used across the pipeline wherever two hooks should run sequentially. +- **`PackageMapPlugin`** — Goal: resolve bare specifiers through a [Node.js package map](https://nodejs.org/api/packages.html#package-maps) rather than `node_modules` (powers `packageMap`, experimental). `raw-module` → `undescribed-resolve-in-package`. +- **`ParsePlugin`** — Goal: split the raw request string into path / query / fragment / `module` / `directory` / `internal` flags. `resolve` → `parsed-resolve`; also wired on `internal-resolve` and `imports-resolve`. +- **`PnpPlugin`** — Goal: resolve bare-module requests through Yarn's PnP API when available. `raw-module` → `undescribed-resolve-in-package` on hit, `alternate-raw-module` on miss. +- **`RestrictionsPlugin`** — Goal: reject resolved paths that don't satisfy at least one string prefix or RegExp. Tapped on `resolved`. +- **`ResultPlugin`** — Goal: terminal plugin — fires the `result` lifecycle hook and signals a successful resolve. Tapped on `resolved`. +- **`RootsPlugin`** — Goal: resolve server-relative URL requests (starting with `/`) against one or more root directories. `after-normal-resolve` → `relative`. +- **`SelfReferencePlugin`** — Goal: resolve a package self-reference (`my-pkg/foo` from inside `my-pkg`) via its own `exports`. `raw-module` → `resolve-as-module`. +- **`SymlinkPlugin`** — Goal: real-path the resolved file by following symlinks; can be disabled via `symlinks: false`. `existing-file` → `existing-file` (runs via a stage offset on the same hook). +- **`TryNextPlugin`** — Goal: forward the request to another hook with a log message, useful for trying an alternative candidate. `raw-file` → `file` (as the "no extension" attempt) and user-wired. +- **`TsconfigPathsPlugin`** — Goal: rewrite requests using the `paths` and `baseUrl` from a `tsconfig.json` (including project references). Taps `described-resolve` internally and forwards to `internal-resolve`; exported for direct use as well. +- **`UnsafeCachePlugin`** — Goal: cache successful resolves in an in-memory map for repeated requests. `described-resolve` → `raw-resolve` (only when `unsafeCache` is enabled). +- **`UseFilePlugin`** — Goal: join a fixed filename (e.g. `index`) onto the current path to try as an entry file. `existing-directory` / `undescribed-existing-directory` → `undescribed-raw-file`, one instance per entry in `mainFiles`. + +### Hooks + +A resolver exposes two kinds of [`tapable`](https://github.com/webpack/tapable) hooks: + +- **Lifecycle hooks** on `resolver.hooks` — fired by the resolver itself around each `resolve` call. Use these to observe, not to transform the request. +- **Pipeline hooks** — the named steps that plugins tap as `source` and forward to as `target`. Every pipeline hook is an `AsyncSeriesBailHook<[request, resolveContext], request | null>`: return `callback()` to pass on, `callback(err)` to fail, or `callback(null, request)` to short-circuit with a result. Obtain them with `resolver.ensureHook(name)` (creates if missing) or `resolver.getHook(name)` (throws if missing); names are kebab-case or camelCase and are interchangeable. + +#### Lifecycle hooks + +| Hook | Type | Fires when | +| ------------- | --------------------- | ------------------------------------------------------------------------------------------------------------------------------------ | +| `resolveStep` | `SyncHook` | Every time the resolver hands a request to a pipeline hook. Arguments: `(hook, request)`. Ideal for tracing. | +| `noResolve` | `SyncHook` | When a top-level `resolve()` call can't produce a result. Arguments: `(request, error)`. | +| `resolve` | `AsyncSeriesBailHook` | Entry point of the pipeline (also listed below). Tap this to intercept requests before parsing. | +| `result` | `AsyncSeriesHook` | After a successful resolve, with the final request. Fired by `ResultPlugin`. Tap to observe/record results without short-circuiting. | + +#### Pipeline hooks + +Listed roughly in the order the default pipeline visits them. Full wiring lives in `lib/ResolverFactory.js` under `//// pipeline ////`. + +| Hook | Role | +| -------------------------------- | ----------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------- | +| `resolve` | Entry point. `ParsePlugin` parses the raw request (path, query, fragment, module flag) and forwards to `parsed-resolve`. | +| `internal-resolve` | Re-entry point used by internal rewrites (e.g. after an `alias` fires). Same role as `resolve`, but `fullySpecified` is forced off. | +| `imports-resolve` | Re-entry point for the target of an `imports` field match; prevents recursive `#` resolution per the Node.js ESM spec. | +| `parsed-resolve` | Request has been parsed. `DescriptionFilePlugin` attaches the nearest `package.json`, then forwards to `described-resolve`. | +| `described-resolve` | Description file is attached. Where `unsafeCache`, `fallback`, and most user plugins (including `MyLibSrcPlugin` below) hook in. | +| `raw-resolve` | After description. Where `alias`, `aliasFields`, `tsconfig` paths, and `extensionAlias` rewrites fire before default resolution. | +| `normal-resolve` | Default resolution starts. Branches into `relative` (for `./`, `../`, absolute), `raw-module` (bare modules), or `internal` (`#imports`). | +| `internal` | `#name` imports-field entry. `ImportsFieldPlugin` maps the specifier and forwards to `imports-field-relative` or `imports-resolve`. | +| `imports-field-relative` | Concrete path from an `imports`-field match, before the normal `relative` flow. `ExtensionAliasPlugin` taps here so `.js` → `.ts` also fires for `#name` targets. Forwards to `relative`. | +| `raw-module` | Bare-module lookup. `SelfReferencePlugin`, `ModulesInHierarchicalDirectoriesPlugin`, `ModulesInRootPlugin`, `PackageMapPlugin`, and `PnpPlugin` all tap here. | +| `alternate-raw-module` | Fallback module lookup used by `PnpPlugin` when PnP can't resolve and `node_modules` should be tried. | +| `module` | A candidate module directory was built. `JoinRequestPartPlugin` splits off the inner request and forwards to `resolve-as-module`. | +| `resolve-as-module` | Treat candidate as a package. `DirectoryExistsPlugin` gates on existence; short single-file modules may re-enter via `undescribed-raw-file`. | +| `undescribed-resolve-in-package` | Inside a located package directory, before its `package.json` has been read. Loads the description, forwards to `resolve-in-package`. | +| `resolve-in-package` | Inside a package with its description loaded. `ExportsFieldPlugin` matches `exports`, otherwise forwards to `resolve-in-existing-directory`. | +| `resolve-in-existing-directory` | Package directory confirmed; join the remaining request onto it and continue at `relative`. | +| `relative` | A concrete path on disk. `DescriptionFilePlugin` loads the nearest `package.json` and forwards to `described-relative`. | +| `described-relative` | Branches to `raw-file` (treat as file) and `directory` (treat as directory). `resolveToContext` skips the file branch. | +| `directory` | Candidate directory. `DirectoryExistsPlugin` gates on existence and forwards to `undescribed-existing-directory`. | +| `undescribed-existing-directory` | Existing directory, before its `package.json` has been read. `UseFilePlugin` tries `mainFiles` via `undescribed-raw-file`. | +| `existing-directory` | Existing directory with description loaded. `MainFieldPlugin` tries `mainFields`; `UseFilePlugin` falls back to `mainFiles`. | +| `undescribed-raw-file` | Candidate file path, before description is read. Loads description, then forwards to `raw-file`. | +| `raw-file` | Apply extension handling: `ConditionalPlugin` short-circuits when `fullySpecified`, `TryNextPlugin` + `AppendPlugin` try each extension. | +| `file` | A specific file path. Last place `alias` and `aliasFields` can redirect; forwards to `final-file`. | +| `final-file` | `FileExistsPlugin` checks the file is real and records it as a file dependency, then forwards to `existing-file`. | +| `existing-file` | Real file on disk. `SymlinkPlugin` real-paths symlinks (unless `symlinks: false`), then forwards to `resolved`. | +| `resolved` | Terminal hook. `RestrictionsPlugin` enforces `restrictions`; `ResultPlugin` fires the `result` lifecycle hook. | + +#### `before-` and `after-` prefixes + +`ensureHook("before-foo")` and `getHook("before-foo")` return the `foo` hook with `stage: -10`; `after-foo` returns it with `stage: 10`. Use this to tap earlier or later than the default stage without creating a separate hook. You'll see `after-parsed-resolve`, `after-normal-resolve`, `after-relative`, and `after-undescribed-resolve-in-package` used this way inside `ResolverFactory`. + +#### Request flow by request type + +The same 26 pipeline hooks serve every request, but different request shapes take different paths through them. Each `➝` below is one `doResolve` / `NextPlugin` / plugin forward; `resolveStep` fires on every arrow, so tapping it (see [Hook examples](#hook-examples)) prints these chains live. + +Relative path (`./utils` from `/src/index.js`) — the default "resolve on disk" path: + +```text +resolve (ParsePlugin) + ➝ parsed-resolve (DescriptionFilePlugin attaches nearest package.json) + ➝ described-resolve (NextPlugin; or UnsafeCachePlugin short-circuit) + ➝ raw-resolve (NextPlugin; alias/tsconfig would branch here) + ➝ normal-resolve (JoinRequestPlugin: path=/src/utils, request="") + ➝ relative (DescriptionFilePlugin loads /src/package.json) + ➝ described-relative (branches to file and directory candidates) + ├─ ➝ raw-file (ConditionalPlugin / TryNextPlugin) + │ ➝ file (AppendPlugin tried each extension, e.g. .js) + │ ➝ final-file (FileExistsPlugin confirms the file) + │ ➝ existing-file (SymlinkPlugin real-paths it) + │ ➝ resolved (RestrictionsPlugin → ResultPlugin) + └─ ➝ directory (DirectoryExistsPlugin; used when path is a dir) + ➝ undescribed-existing-directory + ➝ existing-directory (MainFieldPlugin tries "main", UseFilePlugin tries "index") + ➝ undescribed-raw-file ➝ raw-file ➝ … +``` + +Bare module (`lodash/merge`) — walks up `node_modules`, then treats the hit as a package: + +```text +resolve ➝ parsed-resolve ➝ described-resolve ➝ raw-resolve ➝ normal-resolve + ➝ raw-module (ConditionalPlugin {module:true}) + ➝ module (ModulesInHierarchicalDirectoriesPlugin walks + /src/node_modules, /node_modules, …) + ➝ resolve-as-module (JoinRequestPartPlugin splits "lodash" / "./merge") + ➝ undescribed-resolve-in-package (DirectoryExistsPlugin gates on lodash/ existing) + ➝ resolve-in-package (DescriptionFilePlugin loads lodash/package.json) + ├─ ➝ relative (ExportsFieldPlugin, if "exports" matches) + └─ ➝ resolve-in-existing-directory (otherwise; JoinRequestPlugin joins "./merge") + ➝ relative ➝ … (same tail as the relative flow above) +``` + +Internal import (`#util` from inside a package) — re-enters the pipeline after mapping: + +```text +resolve ➝ parsed-resolve ➝ described-resolve ➝ raw-resolve ➝ normal-resolve + ➝ internal (ConditionalPlugin {internal:true}) + ➝ imports-resolve (ImportsFieldPlugin mapped "#util" to a bare target) + ➝ parsed-resolve ➝ … (fresh pipeline run, internal:false so # isn't remapped) +``` + +When the `imports` field maps to a relative target, the branch instead goes: + +```text + ➝ internal + ➝ imports-field-relative (ImportsFieldPlugin mapped "#util" to "./util.js"; + ExtensionAliasPlugin can swap .js → .ts here) + ➝ relative ➝ … (same tail as the relative flow above) +``` + +Alias hit (`@/button` with `alias: { "@": "/src" }`) — rewrites then restarts: + +```text +resolve ➝ parsed-resolve ➝ described-resolve + ➝ raw-resolve + ➝ internal-resolve (AliasPlugin rewrote request → "/src/button") + ➝ parsed-resolve ➝ … (fullySpecified forced off; AliasPlugin won't re-fire for the rewritten form) +``` + +`exports`-field hit inside a package (`pkg/feature` matching `"./feature"` in `exports`): + +```text +… ➝ raw-module ➝ module ➝ resolve-as-module ➝ undescribed-resolve-in-package + ➝ resolve-in-package + ➝ relative (ExportsFieldPlugin jumped to the exports target; + main-field / main-file logic is skipped) + ➝ described-relative ➝ raw-file ➝ file ➝ final-file ➝ existing-file ➝ resolved +``` + +Failure — every candidate opts out (`callback()`) and no handler ever short-circuits with a result. `noResolve` fires once, for the top-level request: + +```text +… ➝ final-file + ✗ FileExistsPlugin: ENOENT (opts out; no extension candidates left) + ⇠ bail hooks unwind, each tapped handler has already tried its alternatives + ⇒ top-level resolve() returns no result + ⇒ resolver.hooks.noResolve(request, error) (ResultPlugin never fires) +``` + +#### Hook examples + +Trace every pipeline step and observe failures via the lifecycle hooks: + +```js +resolver.hooks.resolveStep.tap("Trace", (hook, request) => { + console.log(`[step] ${hook.name}: ${request.request} @ ${request.path}`); +}); +resolver.hooks.noResolve.tap("Trace", (request, error) => { + console.log(`[fail] ${request.request}: ${error.message}`); +}); +resolver.hooks.result.tapAsync("Trace", (request, _ctx, callback) => { + console.log(`[done] ${request.path}`); + callback(); +}); +``` + +Short-circuit at `file` to redirect any `.css` request to a stub without continuing the pipeline: + +```js +class StubCssPlugin { + apply(resolver) { + resolver + .getHook("file") + .tapAsync("StubCssPlugin", (request, _ctx, callback) => { + if (!request.path || !request.path.endsWith(".css")) return callback(); + callback(null, { ...request, path: require.resolve("./empty.css") }); + }); + } +} +``` + +Forward to a different hook with `doResolve` to restart resolution with a rewritten request — see `MyLibSrcPlugin` in [Writing a Custom Plugin](#writing-a-custom-plugin) for the canonical pattern (`getHook("described-resolve")` → `doResolve(ensureHook("resolve"), …)`). + +### Writing a Custom Plugin + +The example below adds a plugin that rewrites any request starting with `my-lib/` to `my-lib/src/`. It taps the `described-resolve` hook (after the description file has been located) and forwards the rewritten request to `resolve`, so the pipeline restarts with the new request. + +```js +const fs = require("fs"); +const { CachedInputFileSystem, ResolverFactory } = require("enhanced-resolve"); + +class MyLibSrcPlugin { + apply(resolver) { + const target = resolver.ensureHook("resolve"); + resolver + .getHook("described-resolve") + .tapAsync("MyLibSrcPlugin", (request, resolveContext, callback) => { + if (!request.request || !request.request.startsWith("my-lib/")) { + return callback(); + } + const newRequest = { + ...request, + request: request.request.replace(/^my-lib\//, "my-lib/src/"), + }; + resolver.doResolve( + target, + newRequest, + "rewrote my-lib → my-lib/src", + resolveContext, + callback, + ); + }); + } +} + +const myResolver = ResolverFactory.createResolver({ + fileSystem: new CachedInputFileSystem(fs, 4000), + extensions: [".js", ".json"], + plugins: [new MyLibSrcPlugin()], +}); +``` + +Tips for writing your own plugin: + +- Call `callback()` with no arguments to pass the request on to the next tapped handler at the same `source` hook. This is how you "opt out" when a request doesn't apply. +- Call `resolver.doResolve(target, newRequest, message, resolveContext, callback)` to continue the pipeline at a different hook with a (possibly modified) request. +- Return early with `callback(null, result)` to short-circuit with a specific result, or `callback(err)` to fail the resolve. +- See [Hooks](#hooks) for the full list of pipeline hooks, their order, and the `before-` / `after-` stage modifiers. `lib/ResolverFactory.js` has the exact wiring under `//// pipeline ////`. + +## Escaping + +It's allowed to escape `#` as `\0#` to avoid parsing it as fragment. + +enhanced-resolve will try to resolve requests containing `#` as path and as fragment, so it will automatically figure out if `./some#thing` means `.../some.js#thing` or `.../some#thing.js`. When a `#` is resolved as path it will be escaped in the result. Here: `.../some\0#thing.js`. + +## Tests + +```sh +npm run test +``` + +## Passing options from webpack + +If you are using `webpack`, and you want to pass custom options to `enhanced-resolve`, the options are passed from the `resolve` key of your webpack configuration e.g.: + +``` +resolve: { + extensions: ['.js', '.jsx'], + modules: [path.resolve(__dirname, 'src'), 'node_modules'], + plugins: [new DirectoryNamedWebpackPlugin()] + ... +}, +``` + +## License + +Copyright (c) 2012-2019 JS Foundation and other contributors + +MIT (http://www.opensource.org/licenses/mit-license.php) + +[npm]: https://img.shields.io/npm/v/enhanced-resolve.svg +[npm-url]: https://www.npmjs.com/package/enhanced-resolve +[build-status]: https://github.com/webpack/enhanced-resolve/actions/workflows/test.yml/badge.svg +[build-status-url]: https://github.com/webpack/enhanced-resolve/actions +[codecov-badge]: https://codecov.io/gh/webpack/enhanced-resolve/branch/main/graph/badge.svg?token=6B6NxtsZc3 +[codecov-url]: https://codecov.io/gh/webpack/enhanced-resolve +[size]: https://packagephobia.com/badge?p=enhanced-resolve +[size-url]: https://packagephobia.com/result?p=enhanced-resolve +[discussion]: https://img.shields.io/github/discussions/webpack/webpack +[discussion-url]: https://github.com/webpack/webpack/discussions diff --git a/dg-ui/node_modules/enhanced-resolve/lib/AliasFieldPlugin.js b/dg-ui/node_modules/enhanced-resolve/lib/AliasFieldPlugin.js new file mode 100644 index 0000000..0e80347 --- /dev/null +++ b/dg-ui/node_modules/enhanced-resolve/lib/AliasFieldPlugin.js @@ -0,0 +1,123 @@ +/* + MIT License http://www.opensource.org/licenses/mit-license.php + Author Tobias Koppers @sokra +*/ + +"use strict"; + +const DescriptionFileUtils = require("./DescriptionFileUtils"); +const getInnerRequest = require("./getInnerRequest"); + +/** @typedef {import("./Resolver")} Resolver */ +/** @typedef {import("./Resolver").JsonPrimitive} JsonPrimitive */ +/** @typedef {import("./Resolver").ResolveRequest} ResolveRequest */ +/** @typedef {import("./Resolver").ResolveStepHook} ResolveStepHook */ + +// Sentinel stored in `_fieldDataCache` when a description file does not +// contain a usable alias field object. Lets us distinguish "not cached yet" +// from "no valid field" without calling back into `getField`. +const NO_FIELD_OBJECT = Symbol("NoFieldObject"); + +module.exports = class AliasFieldPlugin { + /** + * @param {string | ResolveStepHook} source source + * @param {string | string[]} field field + * @param {string | ResolveStepHook} target target + */ + constructor(source, field, target) { + this.source = source; + this.field = field; + this.target = target; + // `this.field` is fixed for the plugin's lifetime, so caching + // per description-file content is safe. The cached value is either + // the resolved alias-map object or the `NO_FIELD_OBJECT` sentinel + // meaning "description file has no usable alias field". + /** @type {WeakMap} */ + this._fieldDataCache = new WeakMap(); + } + + /** + * @param {Resolver} resolver the resolver + * @returns {void} + */ + apply(resolver) { + const target = resolver.ensureHook(this.target); + resolver + .getHook(this.source) + .tapAsync("AliasFieldPlugin", (request, resolveContext, callback) => { + if (!request.descriptionFileData) return callback(); + const innerRequest = getInnerRequest(resolver, request); + if (!innerRequest) return callback(); + const { descriptionFileData } = request; + let fieldData = this._fieldDataCache.get(descriptionFileData); + if (fieldData === undefined) { + const raw = DescriptionFileUtils.getField( + descriptionFileData, + this.field, + ); + fieldData = + raw === null || typeof raw !== "object" + ? NO_FIELD_OBJECT + : /** @type {{ [k: string]: JsonPrimitive }} */ (raw); + this._fieldDataCache.set(descriptionFileData, fieldData); + } + if (fieldData === NO_FIELD_OBJECT) { + if (resolveContext.log) { + resolveContext.log( + `Field '${this.field}' doesn't contain a valid alias configuration`, + ); + } + return callback(); + } + /** @type {JsonPrimitive | undefined} */ + const data = Object.prototype.hasOwnProperty.call( + fieldData, + innerRequest, + ) + ? /** @type {{ [Key in string]: JsonPrimitive }} */ (fieldData)[ + innerRequest + ] + : innerRequest.startsWith("./") + ? /** @type {{ [Key in string]: JsonPrimitive }} */ (fieldData)[ + innerRequest.slice(2) + ] + : undefined; + if (data === innerRequest) return callback(); + if (data === undefined) return callback(); + if (data === false) { + /** @type {ResolveRequest} */ + const ignoreObj = { + ...request, + path: false, + }; + if (typeof resolveContext.yield === "function") { + resolveContext.yield(ignoreObj); + return callback(null, null); + } + return callback(null, ignoreObj); + } + /** @type {ResolveRequest} */ + const obj = { + ...request, + path: /** @type {string} */ (request.descriptionFileRoot), + request: /** @type {string} */ (data), + fullySpecified: false, + }; + resolver.doResolve( + target, + obj, + `aliased from description file ${ + request.descriptionFilePath + } with mapping '${innerRequest}' to '${/** @type {string} */ data}'`, + resolveContext, + (err, result) => { + if (err) return callback(err); + + // Don't allow other aliasing or raw request + if (result === undefined) return callback(null, null); + callback(null, result); + }, + ); + }); + } +}; diff --git a/dg-ui/node_modules/enhanced-resolve/lib/AliasPlugin.js b/dg-ui/node_modules/enhanced-resolve/lib/AliasPlugin.js new file mode 100644 index 0000000..608d270 --- /dev/null +++ b/dg-ui/node_modules/enhanced-resolve/lib/AliasPlugin.js @@ -0,0 +1,63 @@ +/* + MIT License http://www.opensource.org/licenses/mit-license.php + Author Tobias Koppers @sokra +*/ + +"use strict"; + +/** @typedef {import("./Resolver")} Resolver */ +/** @typedef {import("./Resolver").ResolveStepHook} ResolveStepHook */ +/** @typedef {string | string[] | false} Alias */ +/** @typedef {{ alias: Alias, name: string, onlyModule?: boolean }} AliasOption */ + +const { aliasResolveHandler, compileAliasOptions } = require("./AliasUtils"); + +/** + * When `alias` is given as an array, the targets are tried in priority + * order and the first matching one wins. Tried-and-failed higher-priority + * targets are recorded on `resolveContext.missingDependencies` (via the + * downstream `FileExistsPlugin`) so that a consumer's watcher can + * invalidate the resolve once one of them appears. The winning target is + * recorded on `resolveContext.fileDependencies`; its removal triggers + * re-resolution, at which point the fallback target is returned. + * + * Callers that cache successful resolves (e.g. webpack's `unsafeCache`) + * are responsible for invalidating those entries when the tracked + * dependencies change -- otherwise a stale path may survive across + * rebuilds even though this plugin itself would return the correct + * fallback on a fresh resolve. + */ +module.exports = class AliasPlugin { + /** + * @param {string | ResolveStepHook} source source + * @param {AliasOption | AliasOption[]} options options + * @param {string | ResolveStepHook} target target + */ + constructor(source, options, target) { + this.source = source; + this.options = Array.isArray(options) ? options : [options]; + this.target = target; + } + + /** + * @param {Resolver} resolver the resolver + * @returns {void} + */ + apply(resolver) { + const target = resolver.ensureHook(this.target); + const compiled = compileAliasOptions(resolver, this.options); + + resolver + .getHook(this.source) + .tapAsync("AliasPlugin", (request, resolveContext, callback) => { + aliasResolveHandler( + resolver, + compiled, + target, + request, + resolveContext, + callback, + ); + }); + } +}; diff --git a/dg-ui/node_modules/enhanced-resolve/lib/AliasUtils.js b/dg-ui/node_modules/enhanced-resolve/lib/AliasUtils.js new file mode 100644 index 0000000..e4ab4cb --- /dev/null +++ b/dg-ui/node_modules/enhanced-resolve/lib/AliasUtils.js @@ -0,0 +1,333 @@ +/* + MIT License http://www.opensource.org/licenses/mit-license.php + Author Tobias Koppers @sokra +*/ + +"use strict"; + +const forEachBail = require("./forEachBail"); +const { PathType, getType } = require("./util/path"); + +/** @typedef {import("./Resolver")} Resolver */ +/** @typedef {import("./Resolver").ResolveRequest} ResolveRequest */ +/** @typedef {import("./Resolver").ResolveContext} ResolveContext */ +/** @typedef {import("./Resolver").ResolveStepHook} ResolveStepHook */ +/** @typedef {import("./Resolver").ResolveCallback} ResolveCallback */ +/** @typedef {string | string[] | false} Alias */ +/** @typedef {{ alias: Alias, name: string, onlyModule?: boolean }} AliasOption */ + +/** + * @typedef {object} CompiledAliasOption + * @property {string} name original alias name + * @property {string} nameWithSlash name + "/" — precomputed to avoid per-resolve concat + * @property {Alias} alias alias target(s) + * @property {boolean} onlyModule normalized onlyModule flag + * @property {string | null} absolutePath absolute form of `name` (with slash ending), null when not absolute + * @property {string | null} wildcardPrefix substring before the single "*" in `name`, null when no wildcard + * @property {string | null} wildcardSuffix substring after the single "*" in `name`, null when no wildcard + * @property {number} firstCharCode first character code of `name` — used as a cheap screen on the hot path. `-1` indicates "matches any first char" (empty wildcard prefix). + * @property {boolean} arrayAlias true when `alias` is an array — precomputed so the hot path skips `Array.isArray` + */ + +/** + * Bucketed view of compiled options used by `aliasResolveHandler` to avoid + * walking the full option list on every resolve. The `all` array preserves + * the legacy linear order (declaration order) for the fallback path. The + * `byFirstChar` map buckets options by the first char code of their `name` + * — each bucket preserves declaration order among its members. The + * `hasAnyFirstChar` flag is true when at least one option matches any + * first char (`firstCharCode === -1`), in which case resolve-time scans + * fall back to `all` to keep declaration-order semantics across buckets. + * The `useBuckets` flag is true only when bucketing would actually help — + * i.e. there are at least 2 distinct first chars AND no empty-prefix + * wildcard. When false, the resolve hot path skips the `Map.get` and + * iterates `all` directly with the per-option first-char-code screen + * (matching the pre-bucketing behavior). This avoids paying for `Map.get` + * on degenerate single-bucket lists like a long chain of aliases that + * all share one first char — the bucket lookup adds overhead without + * narrowing the candidate set, which showed up as a transient-memory + * regression on `pathological-deep-stack`. + * @typedef {object} CompiledAliasOptions + * @property {CompiledAliasOption[]} all declaration-ordered list + * @property {Map} byFirstChar bucketed by first char code + * @property {boolean} hasAnyFirstChar true when an empty-prefix wildcard is present + * @property {boolean} useBuckets true when the bucket fast-path should be used at resolve time + */ + +const EMPTY_LIST = /** @type {CompiledAliasOption[]} */ ([]); +const EMPTY_COMPILED_OPTIONS = /** @type {CompiledAliasOptions} */ ({ + all: EMPTY_LIST, + byFirstChar: new Map(), + hasAnyFirstChar: false, + useBuckets: false, +}); + +/** + * Precompute per-option strings used on every resolve so the hot path in + * `aliasResolveHandler` does no string concatenation / split work per entry. + * Called once per plugin apply — the returned structure is stable for the + * lifetime of the resolver. + * + * Beyond the per-option precompute step, this also partitions the list into + * a `byFirstChar` map so that, when no "empty-prefix" wildcards are + * present, the resolve-time scan only walks options whose `name` starts + * with the same char as the current request. For large alias lists (300+ + * entries) this turns an O(N) screen into O(K) where K is the bucket size + * for the request's first char. + * @param {Resolver} resolver resolver + * @param {AliasOption[]} options options + * @returns {CompiledAliasOptions} compiled options + */ +function compileAliasOptions(resolver, options) { + if (options.length === 0) return EMPTY_COMPILED_OPTIONS; + const all = /** @type {CompiledAliasOption[]} */ ( + Array.from({ length: options.length }) + ); + /** @type {Map} */ + const byFirstChar = new Map(); + let hasAnyFirstChar = false; + for (let i = 0; i < options.length; i++) { + const item = options[i]; + const { name } = item; + let absolutePath = null; + const type = getType(name); + if (type === PathType.AbsolutePosix || type === PathType.AbsoluteWin) { + absolutePath = resolver.join(name, "_").slice(0, -1); + } + const firstStar = name.indexOf("*"); + let wildcardPrefix = null; + let wildcardSuffix = null; + if (firstStar !== -1 && !name.includes("*", firstStar + 1)) { + wildcardPrefix = name.slice(0, firstStar); + wildcardSuffix = name.slice(firstStar + 1); + } + // firstCharCode: used by `aliasResolveHandler` to quickly skip aliases + // whose name can't possibly match the current innerRequest. For a plain + // alias (no wildcard) the first char of the name is also the first char + // of `nameWithSlash` and of `absolutePath` (since the latter is derived + // from name via `resolver.join(name, "_")`, which only appends). For a + // wildcard with a non-empty prefix, the first char of that prefix is + // also the first char of name. Only the `name === "*"` case (empty + // wildcard prefix) can match arbitrary first chars — encode that as -1. + let firstCharCode; + if (wildcardPrefix !== null && wildcardPrefix.length === 0) { + firstCharCode = -1; + } else { + firstCharCode = name.length > 0 ? name.charCodeAt(0) : -1; + } + const compiled = { + name, + nameWithSlash: `${name}/`, + alias: item.alias, + onlyModule: Boolean(item.onlyModule), + absolutePath, + wildcardPrefix, + wildcardSuffix, + firstCharCode, + arrayAlias: Array.isArray(item.alias), + }; + all[i] = compiled; + if (firstCharCode === -1) { + hasAnyFirstChar = true; + } else { + let bucket = byFirstChar.get(firstCharCode); + if (bucket === undefined) { + bucket = []; + byFirstChar.set(firstCharCode, bucket); + } + bucket.push(compiled); + } + } + // Only enable the bucket fast-path when it would actually help. With + // a single bucket (all aliases share one first char, e.g. a chain of + // `chain-0 -> chain-1 -> …` rewrites), the resolve-time `Map.get` + // does no discrimination — every request lands in that one bucket + // or in nothing — and the lookup is overhead compared to walking + // `all` with the per-option first-char-code screen. Requiring 2+ + // distinct first chars matches the cases where bucketing has + // measurable benefit (huge-alias-* / large-alias-list / stack-churn). + const useBuckets = !hasAnyFirstChar && byFirstChar.size >= 2; + return { all, byFirstChar, hasAnyFirstChar, useBuckets }; +} + +/** @typedef {(err?: null | Error, result?: null | ResolveRequest) => void} InnerCallback */ +/** + * @param {Resolver} resolver resolver + * @param {CompiledAliasOptions} options compiled options + * @param {ResolveStepHook} target target + * @param {ResolveRequest} request request + * @param {ResolveContext} resolveContext resolve context + * @param {InnerCallback} callback callback + * @returns {void} + */ +function aliasResolveHandler( + resolver, + options, + target, + request, + resolveContext, + callback, +) { + if (options.all.length === 0) return callback(); + const innerRequest = request.request || request.path; + if (!innerRequest) return callback(); + + // Precompute values used in the inner scan loop so we don't recompute + // them per option. This is meaningful when `options` has hundreds of + // entries (e.g. monorepos with generated alias lists) — see the + // `huge-alias-list` / `huge-alias-miss` benchmarks. + const innerFirstCharCode = innerRequest.charCodeAt(0); + const hasRequestString = Boolean(request.request); + + // Dispatch through the first-char-code bucket when it actually + // narrows the candidate set (`useBuckets` requires 2+ distinct + // first chars and no empty-prefix wildcard). When the field has + // only one first-char bucket — e.g. a long chain of `chain-N` + // aliases that all start with the same char — every request lands + // in that one bucket or nothing, so `Map.get` is overhead vs. just + // walking `all` with the per-option char-code screen. Walking + // `all` also matches the pre-bucketing behavior and keeps the + // `pathological-deep-stack` allocation profile flat. + let scan; + if (options.useBuckets) { + const bucket = options.byFirstChar.get(innerFirstCharCode); + if (bucket === undefined) return callback(); + scan = bucket; + } else { + scan = options.all; + } + + forEachBail( + scan, + (item, callback) => { + // Char-code screen left in for the fallback (`options.all`) path + // where the bucket dispatch above wasn't usable. In the bucket + // path this is always true and folds into a no-op. + const { firstCharCode } = item; + if (firstCharCode !== -1 && firstCharCode !== innerFirstCharCode) { + return callback(); + } + + /** @type {boolean} */ + let shouldStop = false; + + // For absolute-name aliases, accept the normalized + // `absolutePath` form as well as the raw `nameWithSlash`. + // `nameWithSlash` unconditionally appends `/`, so a raw + // windows request with native backslashes + // (e.g. `C:\\abs\\foo\\baz` against `name: "C:\\abs\\foo"`) + // otherwise fails `startsWith("C:\\abs\\foo/")` and is + // silently skipped. Mirroring the `absolutePath` check in + // both branches closes the gap without changing any + // existing matches. + const { absolutePath } = item; + const matchRequest = + innerRequest === item.name || + (!item.onlyModule && + ((hasRequestString && innerRequest.startsWith(item.nameWithSlash)) || + (absolutePath !== null && innerRequest.startsWith(absolutePath)))); + + const matchWildcard = !item.onlyModule && item.wildcardPrefix !== null; + + if (matchRequest || matchWildcard) { + /** + * @param {Alias} alias alias + * @param {(err?: null | Error, result?: null | ResolveRequest) => void} callback callback + * @returns {void} + */ + const resolveWithAlias = (alias, callback) => { + if (alias === false) { + /** @type {ResolveRequest} */ + const ignoreObj = { + ...request, + path: false, + }; + if (typeof resolveContext.yield === "function") { + resolveContext.yield(ignoreObj); + return callback(null, null); + } + return callback(null, ignoreObj); + } + + let newRequestStr; + + if ( + matchWildcard && + innerRequest.startsWith( + /** @type {string} */ (item.wildcardPrefix), + ) && + innerRequest.endsWith(/** @type {string} */ (item.wildcardSuffix)) + ) { + const match = innerRequest.slice( + /** @type {string} */ (item.wildcardPrefix).length, + innerRequest.length - + /** @type {string} */ (item.wildcardSuffix).length, + ); + newRequestStr = alias.toString().replace("*", match); + } + + if ( + matchRequest && + innerRequest !== alias && + !innerRequest.startsWith(`${alias}/`) + ) { + /** @type {string} */ + const remainingRequest = innerRequest.slice(item.name.length); + newRequestStr = alias + remainingRequest; + } + + if (newRequestStr !== undefined) { + shouldStop = true; + /** @type {ResolveRequest} */ + const obj = { + ...request, + request: newRequestStr, + fullySpecified: false, + }; + return resolver.doResolve( + target, + obj, + `aliased with mapping '${item.name}': '${alias}' to '${newRequestStr}'`, + resolveContext, + (err, result) => { + if (err) return callback(err); + if (result) return callback(null, result); + return callback(); + }, + ); + } + return callback(); + }; + + /** + * @param {(null | Error)=} err error + * @param {(null | ResolveRequest)=} result result + * @returns {void} + */ + const stoppingCallback = (err, result) => { + if (err) return callback(err); + + if (result) return callback(null, result); + // Don't allow other aliasing or raw request + if (shouldStop) return callback(null, null); + return callback(); + }; + + if (item.arrayAlias) { + return forEachBail( + /** @type {string[]} */ (item.alias), + resolveWithAlias, + stoppingCallback, + ); + } + return resolveWithAlias(item.alias, stoppingCallback); + } + + return callback(); + }, + callback, + ); +} + +module.exports.aliasResolveHandler = aliasResolveHandler; +module.exports.compileAliasOptions = compileAliasOptions; diff --git a/dg-ui/node_modules/enhanced-resolve/lib/AppendPlugin.js b/dg-ui/node_modules/enhanced-resolve/lib/AppendPlugin.js new file mode 100644 index 0000000..6763d52 --- /dev/null +++ b/dg-ui/node_modules/enhanced-resolve/lib/AppendPlugin.js @@ -0,0 +1,49 @@ +/* + MIT License http://www.opensource.org/licenses/mit-license.php + Author Tobias Koppers @sokra +*/ + +"use strict"; + +/** @typedef {import("./Resolver")} Resolver */ +/** @typedef {import("./Resolver").ResolveRequest} ResolveRequest */ +/** @typedef {import("./Resolver").ResolveStepHook} ResolveStepHook */ + +module.exports = class AppendPlugin { + /** + * @param {string | ResolveStepHook} source source + * @param {string} appending appending + * @param {string | ResolveStepHook} target target + */ + constructor(source, appending, target) { + this.source = source; + this.appending = appending; + this.target = target; + } + + /** + * @param {Resolver} resolver the resolver + * @returns {void} + */ + apply(resolver) { + const target = resolver.ensureHook(this.target); + resolver + .getHook(this.source) + .tapAsync("AppendPlugin", (request, resolveContext, callback) => { + /** @type {ResolveRequest} */ + const obj = { + ...request, + path: request.path + this.appending, + relativePath: + request.relativePath && request.relativePath + this.appending, + }; + resolver.doResolve( + target, + obj, + this.appending, + resolveContext, + callback, + ); + }); + } +}; diff --git a/dg-ui/node_modules/enhanced-resolve/lib/CachedInputFileSystem.js b/dg-ui/node_modules/enhanced-resolve/lib/CachedInputFileSystem.js new file mode 100644 index 0000000..5da2d4f --- /dev/null +++ b/dg-ui/node_modules/enhanced-resolve/lib/CachedInputFileSystem.js @@ -0,0 +1,849 @@ +/* + MIT License http://www.opensource.org/licenses/mit-license.php + Author Tobias Koppers @sokra +*/ + +"use strict"; + +// eslint-disable-next-line n/prefer-global/process +const { nextTick } = require("process"); + +/** @typedef {import("./Resolver").FileSystem} FileSystem */ +/** @typedef {import("./Resolver").PathLike} PathLike */ +/** @typedef {import("./Resolver").PathOrFileDescriptor} PathOrFileDescriptor */ +/** @typedef {import("./Resolver").SyncFileSystem} SyncFileSystem */ +/** @typedef {FileSystem & SyncFileSystem} BaseFileSystem */ + +/** + * @template T + * @typedef {import("./Resolver").FileSystemCallback} FileSystemCallback + */ + +/** + * @param {string} path path + * @returns {string} dirname + */ +const dirname = (path) => { + let idx = path.length - 1; + while (idx >= 0) { + const char = path.charCodeAt(idx); + // slash or backslash + if (char === 47 || char === 92) break; + idx--; + } + if (idx < 0) return ""; + return path.slice(0, idx); +}; + +/** + * @template T + * @param {FileSystemCallback[]} callbacks callbacks + * @param {Error | null} err error + * @param {T} result result + */ +const runCallbacks = (callbacks, err, result) => { + if (callbacks.length === 1) { + callbacks[0](err, result); + callbacks.length = 0; + return; + } + let error; + for (const callback of callbacks) { + try { + callback(err, result); + } catch (err) { + if (!error) error = err; + } + } + callbacks.length = 0; + if (error) throw error; +}; + +// eslint-disable-next-line jsdoc/reject-function-type +/** @typedef {Function} EXPECTED_FUNCTION */ +// eslint-disable-next-line jsdoc/reject-any-type +/** @typedef {any} EXPECTED_ANY */ + +/** + * The first pending cache hit is held in these slots (a scheduled tick is + * pending iff `firstCallback` is set); later hits from the same synchronous + * burst spill into `dispatchQueue` as flat [callback, err, result] triples + * and are drained by the same tick. This keeps the common single-hit case + * as cheap as a plain `nextTick` while bursts share one tick. + * @type {FileSystemCallback | undefined} + */ +let firstCallback; +/** @type {Error | null} */ +let firstErr = null; +/** @type {EXPECTED_ANY} */ +let firstResult; +/** @type {EXPECTED_ANY[]} */ +let dispatchQueue = []; +let dispatchQueueLength = 0; +/** @type {EXPECTED_ANY[]} */ +let spareQueue = []; +// upper bound on the spill-array capacity kept alive between bursts +const MAX_RETAINED_QUEUE_LENGTH = 1024; + +const runDispatch = () => { + const callback = /** @type {FileSystemCallback} */ ( + firstCallback + ); + const err = firstErr; + const result = firstResult; + // clear before calling: hits made from inside a callback start a new tick + firstCallback = undefined; + firstErr = null; + firstResult = undefined; + if (dispatchQueueLength === 0) { + // single hit: no queue bookkeeping, a throw affects nobody else + callback(err, result); + return; + } + const queue = dispatchQueue; + const length = dispatchQueueLength; + // ping-pong the two arrays so draining never allocates + dispatchQueue = spareQueue; + dispatchQueueLength = 0; + let i = -3; + try { + callback(err, result); + for (i = 0; i < length; i += 3) { + queue[i](queue[i + 1], queue[i + 2]); + } + } finally { + // a throwing callback must not starve the rest: re-schedule the + // remainder ahead of anything scheduled during this drain (matching + // the old per-tick FIFO order) and rethrow + i += 3; + if (i < length) { + if (firstCallback === undefined) { + // no reentrant hit took the slot, so `dispatchQueue` is empty + firstCallback = queue[i]; + firstErr = queue[i + 1]; + firstResult = queue[i + 2]; + nextTick(runDispatch); + for (let j = i + 3; j < length; j++) { + dispatchQueue[dispatchQueueLength++] = queue[j]; + } + } else { + // a reentrant hit claimed the slot (and scheduled the tick); + // displace it behind the remainder to keep FIFO order + const rest = queue.slice(i, length); + rest.push(firstCallback, firstErr, firstResult); + for (let j = 0; j < dispatchQueueLength; j++) { + rest.push(dispatchQueue[j]); + } + [firstCallback, firstErr, firstResult] = rest; + dispatchQueue = rest.slice(3); + dispatchQueueLength = dispatchQueue.length; + } + } + // release references but keep the backing store, so the next burst + // does not have to re-grow the array from scratch + for (let j = 0; j < length; j++) queue[j] = undefined; + // bound the permanently retained capacity after a rare giant burst + if (queue.length > MAX_RETAINED_QUEUE_LENGTH) { + queue.length = MAX_RETAINED_QUEUE_LENGTH; + } + spareQueue = queue; + } +}; + +/** + * Cache hits stay asynchronous, but all hits from the same synchronous + * execution share a single `nextTick` instead of scheduling one each. + * @param {FileSystemCallback} callback callback + * @param {Error | null} err error + * @param {EXPECTED_ANY} result result + */ +const scheduleDispatch = (callback, err, result) => { + if (firstCallback === undefined) { + firstCallback = callback; + firstErr = err; + firstResult = result; + nextTick(runDispatch); + } else { + const queue = dispatchQueue; + queue[dispatchQueueLength] = callback; + queue[dispatchQueueLength + 1] = err; + queue[dispatchQueueLength + 2] = result; + dispatchQueueLength += 3; + } +}; + +class OperationMergerBackend { + /** + * @param {EXPECTED_FUNCTION | undefined} provider async method in filesystem + * @param {EXPECTED_FUNCTION | undefined} syncProvider sync method in filesystem + * @param {BaseFileSystem} providerContext call context for the provider methods + */ + constructor(provider, syncProvider, providerContext) { + this._provider = provider; + this._syncProvider = syncProvider; + this._providerContext = providerContext; + this._activeAsyncOperations = new Map(); + + this.provide = this._provider + ? // Comment to align jsdoc + /** + * @param {PathLike | PathOrFileDescriptor} path path + * @param {object | FileSystemCallback | undefined} options options + * @param {FileSystemCallback=} callback callback + * @returns {EXPECTED_ANY} result + */ + (path, options, callback) => { + if (typeof options === "function") { + callback = + /** @type {FileSystemCallback} */ + (options); + options = undefined; + } + if ( + typeof path !== "string" && + !Buffer.isBuffer(path) && + !(path instanceof URL) && + typeof path !== "number" + ) { + /** @type {EXPECTED_FUNCTION} */ + (callback)( + new TypeError("path must be a string, Buffer, URL or number"), + ); + return; + } + if (options) { + return /** @type {EXPECTED_FUNCTION} */ (this._provider).call( + this._providerContext, + path, + options, + callback, + ); + } + let callbacks = this._activeAsyncOperations.get(path); + if (callbacks) { + callbacks.push(callback); + return; + } + this._activeAsyncOperations.set(path, (callbacks = [callback])); + /** @type {EXPECTED_FUNCTION} */ + (provider)( + path, + /** + * @param {Error} err error + * @param {EXPECTED_ANY} result result + */ + (err, result) => { + this._activeAsyncOperations.delete(path); + runCallbacks(callbacks, err, result); + }, + ); + } + : null; + this.provideSync = this._syncProvider + ? // Comment to align jsdoc + /** + * @param {PathLike | PathOrFileDescriptor} path path + * @param {object=} options options + * @returns {EXPECTED_ANY} result + */ + (path, options) => + /** @type {EXPECTED_FUNCTION} */ (this._syncProvider).call( + this._providerContext, + path, + options, + ) + : null; + } + + purge() {} + + purgeParent() {} +} + +/* + +IDLE: + insert data: goto SYNC + +SYNC: + before provide: run ticks + event loop tick: goto ASYNC_ACTIVE + +ASYNC: + timeout: run tick, goto ASYNC_PASSIVE + +ASYNC_PASSIVE: + before provide: run ticks + +IDLE --[insert data]--> SYNC --[event loop tick]--> ASYNC_ACTIVE --[interval tick]-> ASYNC_PASSIVE + ^ | + +---------[insert data]-------+ +*/ + +const STORAGE_MODE_IDLE = 0; +const STORAGE_MODE_SYNC = 1; +const STORAGE_MODE_ASYNC = 2; + +/** + * @callback Provide + * @param {PathLike | PathOrFileDescriptor} path path + * @param {EXPECTED_ANY} options options + * @param {FileSystemCallback} callback callback + * @returns {void} + */ + +class CacheBackend { + /** + * @param {number} duration max cache duration of items + * @param {EXPECTED_FUNCTION | undefined} provider async method + * @param {EXPECTED_FUNCTION | undefined} syncProvider sync method + * @param {BaseFileSystem} providerContext call context for the provider methods + */ + constructor(duration, provider, syncProvider, providerContext) { + this._duration = duration; + this._provider = provider; + this._syncProvider = syncProvider; + this._providerContext = providerContext; + /** @type {Map[]>} */ + this._activeAsyncOperations = new Map(); + /** @type {Map }>} */ + this._data = new Map(); + /** @type {Set[]} */ + this._levels = []; + for (let i = 0; i < 10; i++) this._levels.push(new Set()); + if (duration !== Infinity) { + for (let i = 5000; i < duration; i += 500) { + this._levels.push(new Set()); + } + } + this._currentLevel = 0; + this._tickInterval = Math.floor(duration / this._levels.length); + /** @type {STORAGE_MODE_IDLE | STORAGE_MODE_SYNC | STORAGE_MODE_ASYNC} */ + this._mode = STORAGE_MODE_IDLE; + + /** @type {NodeJS.Timeout | undefined} */ + this._timeout = undefined; + /** @type {number | undefined} */ + this._nextDecay = undefined; + + // eslint-disable-next-line no-warning-comments + // @ts-ignore + this.provide = provider ? this.provide.bind(this) : null; + // eslint-disable-next-line no-warning-comments + // @ts-ignore + this.provideSync = syncProvider ? this.provideSync.bind(this) : null; + } + + /** + * @param {PathLike | PathOrFileDescriptor} path path + * @param {EXPECTED_ANY} options options + * @param {FileSystemCallback} callback callback + * @returns {void} + */ + provide(path, options, callback) { + if (typeof options === "function") { + callback = options; + options = undefined; + } + if ( + typeof path !== "string" && + !Buffer.isBuffer(path) && + !(path instanceof URL) && + typeof path !== "number" + ) { + callback(new TypeError("path must be a string, Buffer, URL or number")); + return; + } + const strPath = typeof path !== "string" ? path.toString() : path; + if (options) { + return /** @type {EXPECTED_FUNCTION} */ (this._provider).call( + this._providerContext, + path, + options, + callback, + ); + } + + // When in sync mode we can move to async mode + if (this._mode === STORAGE_MODE_SYNC) { + this._enterAsyncMode(); + } + + // Check in cache + const cacheEntry = this._data.get(strPath); + if (cacheEntry !== undefined) { + if (cacheEntry.err) { + return scheduleDispatch(callback, cacheEntry.err, undefined); + } + return scheduleDispatch(callback, null, cacheEntry.result); + } + + // Check if there is already the same operation running + let callbacks = this._activeAsyncOperations.get(strPath); + if (callbacks !== undefined) { + callbacks.push(callback); + return; + } + this._activeAsyncOperations.set(strPath, (callbacks = [callback])); + + // Run the operation + /** @type {EXPECTED_FUNCTION} */ + (this._provider).call( + this._providerContext, + path, + /** + * @param {Error | null} err error + * @param {EXPECTED_ANY=} result result + */ + (err, result) => { + this._activeAsyncOperations.delete(strPath); + this._storeResult(strPath, err, result); + + // Enter async mode if not yet done + this._enterAsyncMode(); + + runCallbacks( + /** @type {FileSystemCallback[]} */ (callbacks), + err, + result, + ); + }, + ); + } + + /** + * @param {PathLike | PathOrFileDescriptor} path path + * @param {EXPECTED_ANY} options options + * @returns {EXPECTED_ANY} result + */ + provideSync(path, options) { + if ( + typeof path !== "string" && + !Buffer.isBuffer(path) && + !(path instanceof URL) && + typeof path !== "number" + ) { + throw new TypeError("path must be a string"); + } + const strPath = typeof path !== "string" ? path.toString() : path; + if (options) { + return /** @type {EXPECTED_FUNCTION} */ (this._syncProvider).call( + this._providerContext, + path, + options, + ); + } + + // In sync mode we may have to decay some cache items + if (this._mode === STORAGE_MODE_SYNC) { + this._runDecays(); + } + + // Check in cache + const cacheEntry = this._data.get(strPath); + if (cacheEntry !== undefined) { + if (cacheEntry.err) throw cacheEntry.err; + return cacheEntry.result; + } + + // Get all active async operations + // This sync operation will also complete them + const callbacks = this._activeAsyncOperations.get(strPath); + this._activeAsyncOperations.delete(strPath); + + // Run the operation + // When in idle mode, we will enter sync mode + let result; + try { + result = /** @type {EXPECTED_FUNCTION} */ (this._syncProvider).call( + this._providerContext, + path, + ); + } catch (err) { + this._storeResult(strPath, /** @type {Error} */ (err), undefined); + this._enterSyncModeWhenIdle(); + if (callbacks) { + runCallbacks(callbacks, /** @type {Error} */ (err), undefined); + } + throw err; + } + this._storeResult(strPath, null, result); + this._enterSyncModeWhenIdle(); + if (callbacks) { + runCallbacks(callbacks, null, result); + } + return result; + } + + /** + * @param {(string | Buffer | URL | number | (string | URL | Buffer | number)[] | Set)=} what what to purge + * @param {{ exact?: boolean }=} options options; `exact: true` removes only entries whose key matches `what` exactly instead of any entry whose key starts with `what` + */ + purge(what, options) { + if (what === undefined || what === null) { + if (this._mode !== STORAGE_MODE_IDLE) { + this._data.clear(); + for (const level of this._levels) { + level.clear(); + } + this._enterIdleMode(); + } + return; + } + const exact = + options !== undefined && options !== null && options.exact === true; + if (exact) { + if ( + typeof what === "string" || + Buffer.isBuffer(what) || + what instanceof URL || + typeof what === "number" + ) { + const strWhat = typeof what !== "string" ? what.toString() : what; + const data = this._data.get(strWhat); + if (data !== undefined) { + this._data.delete(strWhat); + data.level.delete(strWhat); + } + } else { + for (const item of what) { + const strItem = typeof item !== "string" ? item.toString() : item; + const data = this._data.get(strItem); + if (data !== undefined) { + this._data.delete(strItem); + data.level.delete(strItem); + } + } + } + if (this._data.size === 0) { + this._enterIdleMode(); + } + return; + } + if ( + typeof what === "string" || + Buffer.isBuffer(what) || + what instanceof URL || + typeof what === "number" + ) { + const strWhat = typeof what !== "string" ? what.toString() : what; + if (strWhat === "") { + // empty string is a prefix of every key — short-circuit the O(n) scan + if (this._mode !== STORAGE_MODE_IDLE) { + this._data.clear(); + for (const level of this._levels) { + level.clear(); + } + this._enterIdleMode(); + } + return; + } + for (const [key, data] of this._data) { + if (key.startsWith(strWhat)) { + this._data.delete(key); + data.level.delete(key); + } + } + if (this._data.size === 0) { + this._enterIdleMode(); + } + } else { + for (const [key, data] of this._data) { + for (const item of what) { + const strItem = typeof item !== "string" ? item.toString() : item; + if (key.startsWith(strItem)) { + this._data.delete(key); + data.level.delete(key); + break; + } + } + } + if (this._data.size === 0) { + this._enterIdleMode(); + } + } + } + + /** + * @param {(string | Buffer | URL | number | (string | URL | Buffer | number)[] | Set)=} what what to purge + */ + purgeParent(what) { + if (what === undefined || what === null) { + this.purge(); + } else if ( + typeof what === "string" || + Buffer.isBuffer(what) || + what instanceof URL || + typeof what === "number" + ) { + const strWhat = typeof what !== "string" ? what.toString() : what; + this.purge(dirname(strWhat)); + } else { + const set = new Set(); + for (const item of what) { + const strItem = typeof item !== "string" ? item.toString() : item; + set.add(dirname(strItem)); + } + this.purge(set); + } + } + + /** + * @param {string} path path + * @param {Error | null} err error + * @param {EXPECTED_ANY} result result + */ + _storeResult(path, err, result) { + if (this._data.has(path)) return; + const level = this._levels[this._currentLevel]; + this._data.set(path, { err, result, level }); + level.add(path); + } + + _decayLevel() { + const nextLevel = (this._currentLevel + 1) % this._levels.length; + const decay = this._levels[nextLevel]; + this._currentLevel = nextLevel; + for (const item of decay) { + this._data.delete(item); + } + decay.clear(); + if (this._data.size === 0) { + this._enterIdleMode(); + } else { + /** @type {number} */ + (this._nextDecay) += this._tickInterval; + } + } + + _runDecays() { + while ( + /** @type {number} */ (this._nextDecay) <= Date.now() && + this._mode !== STORAGE_MODE_IDLE + ) { + this._decayLevel(); + } + } + + _enterAsyncMode() { + let timeout = 0; + switch (this._mode) { + case STORAGE_MODE_ASYNC: + return; + case STORAGE_MODE_IDLE: + this._nextDecay = Date.now() + this._tickInterval; + timeout = this._tickInterval; + break; + case STORAGE_MODE_SYNC: + this._runDecays(); + // _runDecays may change the mode + if ( + /** @type {STORAGE_MODE_IDLE | STORAGE_MODE_SYNC | STORAGE_MODE_ASYNC} */ + (this._mode) === STORAGE_MODE_IDLE + ) { + return; + } + timeout = Math.max( + 0, + /** @type {number} */ (this._nextDecay) - Date.now(), + ); + break; + } + this._mode = STORAGE_MODE_ASYNC; + // When duration is Infinity, cache entries never expire, so there + // is no need to schedule a decay timer. + if (this._duration === Infinity) { + return; + } + const ref = setTimeout(() => { + this._mode = STORAGE_MODE_SYNC; + this._runDecays(); + }, timeout); + if (ref.unref) ref.unref(); + this._timeout = ref; + } + + _enterSyncModeWhenIdle() { + if (this._mode === STORAGE_MODE_IDLE) { + this._mode = STORAGE_MODE_SYNC; + this._nextDecay = Date.now() + this._tickInterval; + } + } + + _enterIdleMode() { + this._mode = STORAGE_MODE_IDLE; + this._nextDecay = undefined; + if (this._timeout) clearTimeout(this._timeout); + } +} + +/** + * @template {EXPECTED_FUNCTION} Provider + * @template {EXPECTED_FUNCTION} AsyncProvider + * @template FileSystem + * @param {number} duration duration in ms files are cached + * @param {Provider | undefined} provider provider + * @param {AsyncProvider | undefined} syncProvider sync provider + * @param {BaseFileSystem} providerContext provider context + * @returns {OperationMergerBackend | CacheBackend} backend + */ +const createBackend = (duration, provider, syncProvider, providerContext) => { + if (duration > 0) { + return new CacheBackend(duration, provider, syncProvider, providerContext); + } + return new OperationMergerBackend(provider, syncProvider, providerContext); +}; + +module.exports = class CachedInputFileSystem { + /** + * @param {BaseFileSystem} fileSystem file system + * @param {number} duration duration in ms files are cached + */ + constructor(fileSystem, duration) { + this.fileSystem = fileSystem; + + this._lstatBackend = createBackend( + duration, + this.fileSystem.lstat, + this.fileSystem.lstatSync, + this.fileSystem, + ); + const lstat = this._lstatBackend.provide; + this.lstat = /** @type {FileSystem["lstat"]} */ (lstat); + const lstatSync = this._lstatBackend.provideSync; + this.lstatSync = /** @type {SyncFileSystem["lstatSync"]} */ (lstatSync); + + this._statBackend = createBackend( + duration, + this.fileSystem.stat, + this.fileSystem.statSync, + this.fileSystem, + ); + const stat = this._statBackend.provide; + this.stat = /** @type {FileSystem["stat"]} */ (stat); + const statSync = this._statBackend.provideSync; + this.statSync = /** @type {SyncFileSystem["statSync"]} */ (statSync); + + this._readdirBackend = createBackend( + duration, + this.fileSystem.readdir, + this.fileSystem.readdirSync, + this.fileSystem, + ); + const readdir = this._readdirBackend.provide; + this.readdir = /** @type {FileSystem["readdir"]} */ (readdir); + const readdirSync = this._readdirBackend.provideSync; + this.readdirSync = /** @type {SyncFileSystem["readdirSync"]} */ ( + readdirSync + ); + + this._readFileBackend = createBackend( + duration, + this.fileSystem.readFile, + this.fileSystem.readFileSync, + this.fileSystem, + ); + const readFile = this._readFileBackend.provide; + this.readFile = /** @type {FileSystem["readFile"]} */ (readFile); + const readFileSync = this._readFileBackend.provideSync; + this.readFileSync = /** @type {SyncFileSystem["readFileSync"]} */ ( + readFileSync + ); + + this._readJsonBackend = createBackend( + duration, + // prettier-ignore + this.fileSystem.readJson || + (this.readFile && + ( + /** + * @param {string} path path + * @param {FileSystemCallback} callback callback + */ + (path, callback) => { + this.readFile(path, (err, buffer) => { + if (err) return callback(err); + if (!buffer || buffer.length === 0) + {return callback(new Error("No file content"));} + let data; + try { + data = JSON.parse(buffer.toString("utf8")); + } catch (err_) { + return callback(/** @type {Error} */ (err_)); + } + callback(null, data); + }); + }) + ), + // prettier-ignore + this.fileSystem.readJsonSync || + (this.readFileSync && + ( + /** + * @param {string} path path + * @returns {EXPECTED_ANY} result + */ + (path) => { + const buffer = this.readFileSync(path); + const data = JSON.parse(buffer.toString("utf8")); + return data; + } + )), + this.fileSystem, + ); + const readJson = this._readJsonBackend.provide; + this.readJson = /** @type {FileSystem["readJson"]} */ (readJson); + const readJsonSync = this._readJsonBackend.provideSync; + this.readJsonSync = /** @type {SyncFileSystem["readJsonSync"]} */ ( + readJsonSync + ); + + this._readlinkBackend = createBackend( + duration, + this.fileSystem.readlink, + this.fileSystem.readlinkSync, + this.fileSystem, + ); + const readlink = this._readlinkBackend.provide; + this.readlink = /** @type {FileSystem["readlink"]} */ (readlink); + const readlinkSync = this._readlinkBackend.provideSync; + this.readlinkSync = /** @type {SyncFileSystem["readlinkSync"]} */ ( + readlinkSync + ); + + this._realpathBackend = createBackend( + duration, + this.fileSystem.realpath, + this.fileSystem.realpathSync, + this.fileSystem, + ); + const realpath = this._realpathBackend.provide; + this.realpath = /** @type {FileSystem["realpath"]} */ (realpath); + const realpathSync = this._realpathBackend.provideSync; + this.realpathSync = /** @type {SyncFileSystem["realpathSync"]} */ ( + realpathSync + ); + } + + /** + * @param {(string | Buffer | URL | number | (string | URL | Buffer | number)[] | Set)=} what what to purge + * @param {{ exact?: boolean, readdirPrefix?: boolean }=} options options; `exact: true` removes only cache entries whose key matches `what` exactly instead of any entry whose key starts with `what`; with `exact: true`, `readdirPrefix: true` still removes every `readdir` entry whose key starts with `what`, so the listings of directories below a changed directory are dropped while their file stats are kept + */ + purge(what, options) { + this._statBackend.purge(what, options); + this._lstatBackend.purge(what, options); + if (options !== undefined && options !== null && options.exact === true) { + if (options.readdirPrefix === true) { + this._readdirBackend.purge(what); + } else { + this._readdirBackend.purge(what, options); + } + } else { + this._readdirBackend.purgeParent(what); + } + this._readFileBackend.purge(what, options); + this._readlinkBackend.purge(what, options); + this._readJsonBackend.purge(what, options); + this._realpathBackend.purge(what, options); + } +}; diff --git a/dg-ui/node_modules/enhanced-resolve/lib/CloneBasenamePlugin.js b/dg-ui/node_modules/enhanced-resolve/lib/CloneBasenamePlugin.js new file mode 100644 index 0000000..f608036 --- /dev/null +++ b/dg-ui/node_modules/enhanced-resolve/lib/CloneBasenamePlugin.js @@ -0,0 +1,51 @@ +/* + MIT License http://www.opensource.org/licenses/mit-license.php + Author Tobias Koppers @sokra +*/ + +"use strict"; + +/** @typedef {import("./Resolver")} Resolver */ +/** @typedef {import("./Resolver").ResolveRequest} ResolveRequest */ +/** @typedef {import("./Resolver").ResolveStepHook} ResolveStepHook */ + +module.exports = class CloneBasenamePlugin { + /** + * @param {string | ResolveStepHook} source source + * @param {string | ResolveStepHook} target target + */ + constructor(source, target) { + this.source = source; + this.target = target; + } + + /** + * @param {Resolver} resolver the resolver + * @returns {void} + */ + apply(resolver) { + const target = resolver.ensureHook(this.target); + resolver + .getHook(this.source) + .tapAsync("CloneBasenamePlugin", (request, resolveContext, callback) => { + const requestPath = /** @type {string} */ (request.path); + const filename = resolver.basename(requestPath); + const filePath = resolver.join(requestPath, filename); + /** @type {ResolveRequest} */ + const obj = { + ...request, + path: filePath, + relativePath: + request.relativePath && + resolver.join(request.relativePath, filename), + }; + resolver.doResolve( + target, + obj, + `using path: ${filePath}`, + resolveContext, + callback, + ); + }); + } +}; diff --git a/dg-ui/node_modules/enhanced-resolve/lib/ConditionalPlugin.js b/dg-ui/node_modules/enhanced-resolve/lib/ConditionalPlugin.js new file mode 100644 index 0000000..99cc09d --- /dev/null +++ b/dg-ui/node_modules/enhanced-resolve/lib/ConditionalPlugin.js @@ -0,0 +1,59 @@ +/* + MIT License http://www.opensource.org/licenses/mit-license.php + Author Tobias Koppers @sokra +*/ + +"use strict"; + +/** @typedef {import("./Resolver")} Resolver */ +/** @typedef {import("./Resolver").ResolveRequest} ResolveRequest */ +/** @typedef {import("./Resolver").ResolveStepHook} ResolveStepHook */ + +module.exports = class ConditionalPlugin { + /** + * @param {string | ResolveStepHook} source source + * @param {Partial} test compare object + * @param {string | null} message log message + * @param {boolean} allowAlternatives when false, do not continue with the current step when "test" matches + * @param {string | ResolveStepHook} target target + */ + constructor(source, test, message, allowAlternatives, target) { + this.source = source; + this.test = test; + this.message = message; + this.allowAlternatives = allowAlternatives; + this.target = target; + } + + /** + * @param {Resolver} resolver the resolver + * @returns {void} + */ + apply(resolver) { + const target = resolver.ensureHook(this.target); + const { test, message, allowAlternatives } = this; + const keys = /** @type {(keyof ResolveRequest)[]} */ (Object.keys(test)); + resolver + .getHook(this.source) + .tapAsync("ConditionalPlugin", (request, resolveContext, callback) => { + for (const prop of keys) { + if (request[prop] !== test[prop]) return callback(); + } + resolver.doResolve( + target, + request, + message, + resolveContext, + allowAlternatives + ? callback + : (err, result) => { + if (err) return callback(err); + + // Don't allow other alternatives + if (result === undefined) return callback(null, null); + callback(null, result); + }, + ); + }); + } +}; diff --git a/dg-ui/node_modules/enhanced-resolve/lib/DescriptionFilePlugin.js b/dg-ui/node_modules/enhanced-resolve/lib/DescriptionFilePlugin.js new file mode 100644 index 0000000..91a7f3b --- /dev/null +++ b/dg-ui/node_modules/enhanced-resolve/lib/DescriptionFilePlugin.js @@ -0,0 +1,103 @@ +/* + MIT License http://www.opensource.org/licenses/mit-license.php + Author Tobias Koppers @sokra +*/ + +"use strict"; + +const DescriptionFileUtils = require("./DescriptionFileUtils"); + +/** @typedef {import("./Resolver")} Resolver */ +/** @typedef {import("./Resolver").ResolveRequest} ResolveRequest */ +/** @typedef {import("./Resolver").ResolveStepHook} ResolveStepHook */ + +const BACKSLASH_G = /\\/g; + +module.exports = class DescriptionFilePlugin { + /** + * @param {string | ResolveStepHook} source source + * @param {string[]} filenames filenames + * @param {boolean} pathIsFile pathIsFile + * @param {string | ResolveStepHook} target target + */ + constructor(source, filenames, pathIsFile, target) { + this.source = source; + this.filenames = filenames; + this.pathIsFile = pathIsFile; + this.target = target; + } + + /** + * @param {Resolver} resolver the resolver + * @returns {void} + */ + apply(resolver) { + const target = resolver.ensureHook(this.target); + resolver + .getHook(this.source) + .tapAsync( + "DescriptionFilePlugin", + (request, resolveContext, callback) => { + const { path } = request; + if (!path) return callback(); + const directory = this.pathIsFile + ? DescriptionFileUtils.cdUp(path) + : path; + if (!directory) return callback(); + DescriptionFileUtils.loadDescriptionFile( + resolver, + directory, + this.filenames, + request.descriptionFilePath + ? { + path: request.descriptionFilePath, + content: request.descriptionFileData, + directory: + /** @type {string} */ + (request.descriptionFileRoot), + } + : undefined, + resolveContext, + (err, result) => { + if (err) return callback(err); + if (!result) { + if (resolveContext.log) { + resolveContext.log( + `No description file found in ${directory} or above`, + ); + } + return callback(); + } + const rawRelative = path.slice(result.directory.length); + const relativePath = `.${ + rawRelative.includes("\\") + ? rawRelative.replace(BACKSLASH_G, "/") + : rawRelative + }`; + /** @type {ResolveRequest} */ + const obj = { + ...request, + descriptionFilePath: result.path, + descriptionFileData: result.content, + descriptionFileRoot: result.directory, + relativePath, + }; + resolver.doResolve( + target, + obj, + `using description file: ${result.path} (relative path: ${relativePath})`, + resolveContext, + (err, result) => { + if (err) return callback(err); + + // Don't allow other processing + if (result === undefined) return callback(null, null); + callback(null, result); + }, + ); + }, + ); + }, + ); + } +}; diff --git a/dg-ui/node_modules/enhanced-resolve/lib/DescriptionFileUtils.js b/dg-ui/node_modules/enhanced-resolve/lib/DescriptionFileUtils.js new file mode 100644 index 0000000..18de52b --- /dev/null +++ b/dg-ui/node_modules/enhanced-resolve/lib/DescriptionFileUtils.js @@ -0,0 +1,232 @@ +/* + MIT License http://www.opensource.org/licenses/mit-license.php + Author Tobias Koppers @sokra +*/ + +"use strict"; + +const forEachBail = require("./forEachBail"); +const { decodeText } = require("./util/fs"); + +/** @typedef {import("./Resolver")} Resolver */ +/** @typedef {import("./Resolver").JsonObject} JsonObject */ +/** @typedef {import("./Resolver").JsonValue} JsonValue */ +/** @typedef {import("./Resolver").ResolveContext} ResolveContext */ +/** @typedef {import("./Resolver").ResolveRequest} ResolveRequest */ + +/** + * @typedef {object} DescriptionFileInfo + * @property {JsonObject=} content content + * @property {string} path path + * @property {string} directory directory + */ + +/** + * @callback ErrorFirstCallback + * @param {Error | null=} error + * @param {DescriptionFileInfo=} result + */ + +/** + * @typedef {object} Result + * @property {string} path path to description file + * @property {string} directory directory of description file + * @property {JsonObject} content content of description file + */ + +const CHAR_SLASH = 47; +const CHAR_BACKSLASH = 92; + +/** + * Walk up one directory. Called once per package-root candidate and once per + * `described-resolve` (to find the enclosing description file), so it's on + * the resolver's hot path. + * + * Previous implementation called `lastIndexOf("/")` and `lastIndexOf("\\")` + * separately and then picked the larger. For any non-trivial directory + * string on POSIX, `lastIndexOf("\\")` scans the full string just to return + * -1. A single reverse char-code scan does the same work in one pass. + * + * Any single-character directory is treated as a root — `directory.length + * <= 1` collapses the `"/"`, `"\\"` and `""` branches into one compare. + * Without the `"\\"` case, `cdUp("\\")` (reached from a UNC root or a DOS + * device path like `\\?\…`) would return itself via `slice(0, i || 1)` + * and trap `loadDescriptionFile` in an infinite loop. Once single-char + * roots are filtered up front, the reverse scan always produces a + * strictly shorter string. + * @param {string} directory directory + * @returns {string | null} parent directory or null + */ +function cdUp(directory) { + if (directory.length <= 1) return null; + for (let i = directory.length - 1; i >= 0; i--) { + const code = directory.charCodeAt(i); + if (code === CHAR_SLASH || code === CHAR_BACKSLASH) { + return directory.slice(0, i || 1); + } + } + return null; +} + +/** + * @param {Resolver} resolver resolver + * @param {string} directory directory + * @param {string[]} filenames filenames + * @param {DescriptionFileInfo | undefined} oldInfo oldInfo + * @param {ResolveContext} resolveContext resolveContext + * @param {ErrorFirstCallback} callback callback + */ +function loadDescriptionFile( + resolver, + directory, + filenames, + oldInfo, + resolveContext, + callback, +) { + // Hoist the per-filename iterator and the per-level done callback out + // of `findDescriptionFile`. They both close over `directory`, which we + // reassign as we walk up the tree, so the same closures keep working + // across every level — the previous implementation re-allocated both + // arrows on every recursion step, which adds up on deep walks (multiple + // `DescriptionFilePlugin` taps per resolve, each climbing several + // directories looking for `package.json`). + /** + * @param {string} filename filename + * @param {(err?: null | Error, result?: null | Result) => void} iterCallback callback + * @returns {void} + */ + const iterFilename = (filename, iterCallback) => { + const descriptionFilePath = resolver.join(directory, filename); + + /** + * @param {(null | Error)=} err error + * @param {JsonObject=} resolvedContent content + * @returns {void} + */ + function onJson(err, resolvedContent) { + if (err) { + if (resolveContext.log) { + resolveContext.log( + `${descriptionFilePath} (directory description file): ${err}`, + ); + } else { + err.message = `${descriptionFilePath} (directory description file): ${err}`; + } + return iterCallback(err); + } + iterCallback(null, { + content: /** @type {JsonObject} */ (resolvedContent), + directory, + path: descriptionFilePath, + }); + } + + if (resolver.fileSystem.readJson) { + resolver.fileSystem.readJson(descriptionFilePath, (err, content) => { + if (err) { + if ( + typeof (/** @type {NodeJS.ErrnoException} */ (err).code) !== + "undefined" + ) { + if (resolveContext.missingDependencies) { + resolveContext.missingDependencies.add(descriptionFilePath); + } + return iterCallback(); + } + if (resolveContext.fileDependencies) { + resolveContext.fileDependencies.add(descriptionFilePath); + } + return onJson(err); + } + if (resolveContext.fileDependencies) { + resolveContext.fileDependencies.add(descriptionFilePath); + } + onJson(null, content); + }); + } else { + resolver.fileSystem.readFile(descriptionFilePath, (err, content) => { + if (err) { + if (resolveContext.missingDependencies) { + resolveContext.missingDependencies.add(descriptionFilePath); + } + return iterCallback(); + } + if (resolveContext.fileDependencies) { + resolveContext.fileDependencies.add(descriptionFilePath); + } + + /** @type {JsonObject | undefined} */ + let json; + + if (content) { + try { + json = JSON.parse(decodeText(content)); + } catch (/** @type {unknown} */ err_) { + return onJson(/** @type {Error} */ (err_)); + } + } else { + return onJson(new Error("No content in file")); + } + + onJson(null, json); + }); + } + }; + // Forward-declared so the helpers below can reference each other + // without falling foul of `no-use-before-define`. + /** @type {() => void} */ + let findDescriptionFile; + /** + * @param {(null | Error)=} err error + * @param {(null | Result)=} result result + * @returns {void} + */ + const onLevelDone = (err, result) => { + if (err) return callback(err); + if (result) return callback(null, result); + const dir = cdUp(directory); + if (!dir) { + return callback(); + } + directory = dir; + return findDescriptionFile(); + }; + findDescriptionFile = () => { + if (oldInfo && oldInfo.directory === directory) { + // We already have info for this directory and can reuse it + return callback(null, oldInfo); + } + forEachBail(filenames, iterFilename, onLevelDone); + }; + findDescriptionFile(); +} + +/** + * @param {JsonObject} content content + * @param {string | string[]} field field + * @returns {JsonValue | undefined} field data + */ +function getField(content, field) { + if (!content) return undefined; + if (Array.isArray(field)) { + /** @type {JsonValue} */ + let current = content; + for (let j = 0; j < field.length; j++) { + if (current === null || typeof current !== "object") { + current = null; + break; + } + current = /** @type {JsonValue} */ ( + /** @type {JsonObject} */ + (current)[field[j]] + ); + } + return current; + } + return content[field]; +} + +module.exports.cdUp = cdUp; +module.exports.getField = getField; +module.exports.loadDescriptionFile = loadDescriptionFile; diff --git a/dg-ui/node_modules/enhanced-resolve/lib/DirectoryExistsPlugin.js b/dg-ui/node_modules/enhanced-resolve/lib/DirectoryExistsPlugin.js new file mode 100644 index 0000000..04069e4 --- /dev/null +++ b/dg-ui/node_modules/enhanced-resolve/lib/DirectoryExistsPlugin.js @@ -0,0 +1,68 @@ +/* + MIT License http://www.opensource.org/licenses/mit-license.php + Author Tobias Koppers @sokra +*/ + +"use strict"; + +/** @typedef {import("./Resolver")} Resolver */ +/** @typedef {import("./Resolver").ResolveStepHook} ResolveStepHook */ + +module.exports = class DirectoryExistsPlugin { + /** + * @param {string | ResolveStepHook} source source + * @param {string | ResolveStepHook} target target + */ + constructor(source, target) { + this.source = source; + this.target = target; + } + + /** + * @param {Resolver} resolver the resolver + * @returns {void} + */ + apply(resolver) { + const target = resolver.ensureHook(this.target); + resolver + .getHook(this.source) + .tapAsync( + "DirectoryExistsPlugin", + (request, resolveContext, callback) => { + const fs = resolver.fileSystem; + const directory = request.path; + if (!directory) return callback(); + fs.stat(directory, (err, stat) => { + // Combine the two miss branches: a stat failure and a + // "not a directory" result share the same handling — record + // the path on `missingDependencies`, log the right reason, + // then bail. The error-message ternary picks the wording + // that matched the failing condition. + if (err || !stat || !stat.isDirectory()) { + if (resolveContext.missingDependencies) { + resolveContext.missingDependencies.add(directory); + } + if (resolveContext.log) { + resolveContext.log( + err || !stat + ? `${directory} doesn't exist` + : `${directory} is not a directory`, + ); + } + return callback(); + } + if (resolveContext.fileDependencies) { + resolveContext.fileDependencies.add(directory); + } + resolver.doResolve( + target, + request, + `existing directory ${directory}`, + resolveContext, + callback, + ); + }); + }, + ); + } +}; diff --git a/dg-ui/node_modules/enhanced-resolve/lib/ExportsFieldPlugin.js b/dg-ui/node_modules/enhanced-resolve/lib/ExportsFieldPlugin.js new file mode 100644 index 0000000..8ff1bdb --- /dev/null +++ b/dg-ui/node_modules/enhanced-resolve/lib/ExportsFieldPlugin.js @@ -0,0 +1,279 @@ +/* + MIT License http://www.opensource.org/licenses/mit-license.php + Author Ivan Kopeykin @vankop +*/ + +"use strict"; + +const DescriptionFileUtils = require("./DescriptionFileUtils"); +const forEachBail = require("./forEachBail"); +const { + explainSubpathsInConditions, + processExportsField, +} = require("./util/entrypoints"); +const { parseIdentifier } = require("./util/identifier"); +const { + deprecatedInvalidSegmentRegEx, + invalidSegmentRegEx, +} = require("./util/path"); + +/** @typedef {import("./Resolver")} Resolver */ +/** @typedef {import("./Resolver").JsonObject} JsonObject */ +/** @typedef {import("./Resolver").ResolveRequest} ResolveRequest */ +/** @typedef {import("./Resolver").ResolveStepHook} ResolveStepHook */ +/** @typedef {import("./util/entrypoints").ExportsField} ExportsField */ +/** @typedef {import("./util/entrypoints").FieldProcessor} FieldProcessor */ + +module.exports = class ExportsFieldPlugin { + /** + * @param {string | ResolveStepHook} source source + * @param {Set} conditionNames condition names + * @param {string | string[]} fieldNamePath name path + * @param {string | ResolveStepHook} target target + * @param {boolean=} restrictions whether `restrictions` are configured (enables exports-target fallback when a target is filtered out) + */ + constructor(source, conditionNames, fieldNamePath, target, restrictions) { + this.source = source; + this.target = target; + this.conditionNames = conditionNames; + this.fieldName = fieldNamePath; + this.restrictions = Boolean(restrictions); + // `null` is cached for description files that have no exports field, + // so subsequent resolves against the same package.json skip the + // `DescriptionFileUtils.getField` walk entirely. + /** @type {WeakMap} */ + this._fieldProcessorCache = new WeakMap(); + } + + /** + * @param {Resolver} resolver the resolver + * @returns {void} + */ + apply(resolver) { + const target = resolver.ensureHook(this.target); + resolver + .getHook(this.source) + .tapAsync("ExportsFieldPlugin", (request, resolveContext, callback) => { + // When there is no description file, abort + if (!request.descriptionFileData) return callback(); + if ( + // When the description file is inherited from parent, abort + // (There is no description file inside of this package) + request.relativePath !== "." || + request.request === undefined + ) { + return callback(); + } + + const { descriptionFileData } = request; + const remainingRequest = + request.query || request.fragment + ? (request.request === "." ? "./" : request.request) + + request.query + + request.fragment + : request.request; + + /** @type {string[]} */ + let paths; + /** @type {string | null} */ + let usedField; + + try { + // Look up the cached processor first. On a cache hit we + // avoid re-walking the description file for the exports + // field — and `null` is cached for description files that + // have no exports field at all, so those skip the read + // entirely. `processExportsField` can throw on a malformed + // `exports` map (e.g. a key without a leading `.`), so + // building the processor must stay inside this try/catch. + let fieldProcessor = + this._fieldProcessorCache.get(descriptionFileData); + if ( + fieldProcessor === undefined && + !this._fieldProcessorCache.has(descriptionFileData) + ) { + const exportsField = + /** @type {ExportsField | null | undefined} */ + ( + DescriptionFileUtils.getField( + descriptionFileData, + this.fieldName, + ) + ); + fieldProcessor = exportsField + ? processExportsField(exportsField) + : null; + this._fieldProcessorCache.set(descriptionFileData, fieldProcessor); + } + if (!fieldProcessor) return callback(); + + if (request.directory) { + return callback( + new Error( + `Resolving to directories is not possible with the exports field (request was ${remainingRequest}/)`, + ), + ); + } + + [paths, usedField] = fieldProcessor( + remainingRequest, + this.conditionNames, + ); + } catch (/** @type {unknown} */ err) { + // Name the package.json in the error itself, not only in the + // log: a malformed field is a mistake in someone's package, + // and without the path there is nothing to go on. The + // original message is kept verbatim inside this one. + const error = new Error( + `${/** @type {Error} */ (err).message} (see exports field in ${ + request.descriptionFilePath + })`, + ); + if (resolveContext.log) { + resolveContext.log(error.message); + } + return callback(error); + } + + if (paths.length === 0) { + const conditions = [...this.conditionNames]; + const conditionsStr = + conditions.length === 1 + ? `the condition "${conditions[0]}"` + : `the conditions ${JSON.stringify(conditions)}`; + // Nothing matched. The usual reason is that the package + // really does not export this path, but a field whose + // conditions wrap subpaths matches nothing either - and + // then the message above points at the request rather than + // at the mistake. Only this failing branch pays for the + // check. See https://github.com/webpack/enhanced-resolve/issues/325. + const explanation = explainSubpathsInConditions( + /** @type {ExportsField | null | undefined} */ + ( + DescriptionFileUtils.getField(descriptionFileData, this.fieldName) + ), + true, + ); + return callback( + new Error( + `"${remainingRequest}" is not exported under ${conditionsStr} from package ${request.descriptionFileRoot} (see exports field in ${request.descriptionFilePath})${ + explanation ? `. In that exports field, ${explanation}` : "" + }`, + ), + ); + } + + // When `restrictions` are configured, share a marker down the + // chain so RestrictionsPlugin can tell us it filtered out an + // otherwise-valid target — then we fall back instead of erroring. + const restrictionsMarker = this.restrictions + ? { blocked: false } + : undefined; + + forEachBail( + paths, + /** + * @param {string} path path + * @param {(err?: null | Error, result?: null | ResolveRequest) => void} callback callback + * @param {number} i index + * @returns {void} + */ + (path, callback, i) => { + const parsedIdentifier = parseIdentifier(path); + + if (!parsedIdentifier) return callback(); + + const [relativePath, query, fragment] = parsedIdentifier; + + if (!relativePath.startsWith("./")) { + if (paths.length === i) { + return callback( + new Error( + `Invalid "exports" target "${path}" defined for "${usedField}" in the package config ${request.descriptionFilePath}, targets must start with "./"`, + ), + ); + } + + return callback(); + } + + const withoutDotSlash = relativePath.slice(2); + if ( + invalidSegmentRegEx.test(withoutDotSlash) && + deprecatedInvalidSegmentRegEx.test(withoutDotSlash) + ) { + if (paths.length === i) { + return callback( + new Error( + `Invalid "exports" target "${path}" defined for "${usedField}" in the package config ${request.descriptionFilePath}, targets must start with "./"`, + ), + ); + } + + return callback(); + } + + /** @type {ResolveRequest} */ + const obj = { + ...request, + request: undefined, + path: resolver.join( + /** @type {string} */ (request.descriptionFileRoot), + relativePath, + ), + relativePath, + query, + fragment, + }; + // Attach the marker only when restrictions are configured, so + // resolves without restrictions keep their request shape and + // never leak the property onto the result. + if (restrictionsMarker) { + obj.__restrictionsMarker = restrictionsMarker; + } + + resolver.doResolve( + target, + obj, + `using exports field: ${path}`, + resolveContext, + (err, result) => { + if (err) return callback(err); + // Don't allow to continue - https://github.com/webpack/enhanced-resolve/issues/400 + if (result === undefined) return callback(null, null); + callback(null, result); + }, + ); + }, + /** + * @param {(null | Error)=} err error + * @param {(null | ResolveRequest)=} result result + * @returns {void} + */ + (err, result) => { + if (err) return callback(err); + // When an exports field match was found but the target file doesn't exist, + // return an error to prevent fallback to parent node_modules directories. + // Per the Node.js ESM spec, a matched exports entry that fails to resolve + // is a hard error, not a signal to continue searching up the directory tree. + // See: https://github.com/webpack/enhanced-resolve/issues/399 + if (!result) { + // Exception: the target existed but `restrictions` filtered it + // out — return no result so the next `modules` entry is tried. + if (restrictionsMarker && restrictionsMarker.blocked) { + return callback(null, null); + } + return callback( + new Error( + `Package path ${remainingRequest} is exported from package ${request.descriptionFileRoot}, but no valid target file was found (see exports field in ${request.descriptionFilePath})`, + ), + ); + } + // Drop the internal marker before it reaches the result. + if (restrictionsMarker) delete result.__restrictionsMarker; + callback(null, result); + }, + ); + }); + } +}; diff --git a/dg-ui/node_modules/enhanced-resolve/lib/ExtensionAliasPlugin.js b/dg-ui/node_modules/enhanced-resolve/lib/ExtensionAliasPlugin.js new file mode 100644 index 0000000..1c17b98 --- /dev/null +++ b/dg-ui/node_modules/enhanced-resolve/lib/ExtensionAliasPlugin.js @@ -0,0 +1,137 @@ +/* + MIT License http://www.opensource.org/licenses/mit-license.php + Author Ivan Kopeykin @vankop +*/ + +"use strict"; + +const forEachBail = require("./forEachBail"); + +/** @typedef {import("./Resolver")} Resolver */ +/** @typedef {import("./Resolver").ResolveRequest} ResolveRequest */ +/** @typedef {import("./Resolver").ResolveStepHook} ResolveStepHook */ +/** @typedef {{ alias: string | string[], extension: string }} ExtensionAliasOption */ + +module.exports = class ExtensionAliasPlugin { + /** + * @param {string | ResolveStepHook} source source + * @param {ExtensionAliasOption} options options + * @param {string | ResolveStepHook} target target + */ + constructor(source, options, target) { + this.source = source; + this.options = options; + this.target = target; + } + + /** + * @param {Resolver} resolver the resolver + * @returns {void} + */ + apply(resolver) { + const target = resolver.ensureHook(this.target); + const { extension, alias } = this.options; + resolver + .getHook(this.source) + .tapAsync("ExtensionAliasPlugin", (request, resolveContext, callback) => { + // Two modes of operation: + // - "request" mode: original request specifier still carries the + // extension (e.g. user wrote `./foo.js`). We swap the extension + // on `request.request` and re-resolve. + // - "path" mode: the specifier has already been joined into an + // absolute `request.path` (e.g. produced by the imports field). + // We swap the extension on `request.path` and `request.relativePath`. + const useRequest = request.request !== undefined; + const source = useRequest + ? /** @type {string} */ (request.request) + : request.path; + if (!source || !source.endsWith(extension)) return callback(); + const isAliasString = typeof alias === "string"; + // Hoist the base (everything before the old extension) out of the + // per-alias `resolve` callback. For an array `alias`, the callback + // runs once per candidate extension; the base does not change + // between iterations, so there's no reason to recompute it. + const sourceBase = source.slice(0, -extension.length); + const relativePathBase = + !useRequest && + request.relativePath && + request.relativePath.endsWith(extension) + ? request.relativePath.slice(0, -extension.length) + : null; + /** + * @param {string} alias extension alias + * @param {(err?: null | Error, result?: null | ResolveRequest) => void} callback callback + * @param {number=} index index + * @returns {void} + */ + const resolve = (alias, callback, index) => { + const newValue = `${sourceBase}${alias}`; + const nextRequest = useRequest + ? { + ...request, + request: newValue, + fullySpecified: true, + } + : { + ...request, + path: newValue, + relativePath: + relativePathBase !== null + ? `${relativePathBase}${alias}` + : request.relativePath, + fullySpecified: true, + }; + + return resolver.doResolve( + target, + nextRequest, + `aliased from extension alias with mapping '${extension}' to '${alias}'`, + resolveContext, + (err, result) => { + // Throw error if we are on the last alias (for multiple aliases) and it failed, always throw if we are not an array or we have only one alias + if (!isAliasString && index) { + if (index !== this.options.alias.length) { + if (resolveContext.log) { + resolveContext.log( + `Failed to alias from extension alias with mapping '${extension}' to '${alias}' for '${newValue}': ${err}`, + ); + } + + return callback(null, result); + } + + return callback(err, result); + } + callback(err, result); + }, + ); + }; + /** + * @param {(null | Error)=} err error + * @param {(null | ResolveRequest)=} result result + * @returns {void} + */ + const stoppingCallback = (err, result) => { + if (err) return callback(err); + if (result) return callback(null, result); + // Listing the source extension among its own aliases keeps the + // original request valid, so it must still be resolvable in its + // normal (not fully specified) form: as a directory, or with + // extensions appended. Only a mapping that drops the source + // extension is strict. + if (isAliasString ? alias === extension : alias.includes(extension)) { + return callback(); + } + // Don't allow other aliasing or raw request + return callback(null, null); + }; + if (isAliasString) { + resolve(alias, stoppingCallback); + } else if (alias.length > 1) { + forEachBail(alias, resolve, stoppingCallback); + } else { + resolve(alias[0], stoppingCallback); + } + }); + } +}; diff --git a/dg-ui/node_modules/enhanced-resolve/lib/FileExistsPlugin.js b/dg-ui/node_modules/enhanced-resolve/lib/FileExistsPlugin.js new file mode 100644 index 0000000..c6343c8 --- /dev/null +++ b/dg-ui/node_modules/enhanced-resolve/lib/FileExistsPlugin.js @@ -0,0 +1,65 @@ +/* + MIT License http://www.opensource.org/licenses/mit-license.php + Author Tobias Koppers @sokra +*/ + +"use strict"; + +/** @typedef {import("./Resolver")} Resolver */ +/** @typedef {import("./Resolver").ResolveStepHook} ResolveStepHook */ + +module.exports = class FileExistsPlugin { + /** + * @param {string | ResolveStepHook} source source + * @param {string | ResolveStepHook} target target + */ + constructor(source, target) { + this.source = source; + this.target = target; + } + + /** + * @param {Resolver} resolver the resolver + * @returns {void} + */ + apply(resolver) { + const target = resolver.ensureHook(this.target); + const fs = resolver.fileSystem; + resolver + .getHook(this.source) + .tapAsync("FileExistsPlugin", (request, resolveContext, callback) => { + const file = request.path; + if (!file) return callback(); + fs.stat(file, (err, stat) => { + // Combine the two miss branches: a stat failure and a + // "not a file" result share the same handling — record the + // path on `missingDependencies`, log the right reason, then + // bail. The error-message ternary picks the wording that + // matched the failing condition. + if (err || !stat || !stat.isFile()) { + if (resolveContext.missingDependencies) { + resolveContext.missingDependencies.add(file); + } + if (resolveContext.log) { + resolveContext.log( + err || !stat + ? `${file} doesn't exist` + : `${file} is not a file`, + ); + } + return callback(); + } + if (resolveContext.fileDependencies) { + resolveContext.fileDependencies.add(file); + } + resolver.doResolve( + target, + request, + `existing file: ${file}`, + resolveContext, + callback, + ); + }); + }); + } +}; diff --git a/dg-ui/node_modules/enhanced-resolve/lib/ImportsFieldPlugin.js b/dg-ui/node_modules/enhanced-resolve/lib/ImportsFieldPlugin.js new file mode 100644 index 0000000..adb4815 --- /dev/null +++ b/dg-ui/node_modules/enhanced-resolve/lib/ImportsFieldPlugin.js @@ -0,0 +1,254 @@ +/* + MIT License http://www.opensource.org/licenses/mit-license.php + Author Ivan Kopeykin @vankop +*/ + +"use strict"; + +const DescriptionFileUtils = require("./DescriptionFileUtils"); +const forEachBail = require("./forEachBail"); +const { + explainSubpathsInConditions, + processImportsField, +} = require("./util/entrypoints"); +const { parseIdentifier } = require("./util/identifier"); +const { invalidSegmentRegEx } = require("./util/path"); + +/** @typedef {import("./Resolver")} Resolver */ +/** @typedef {import("./Resolver").JsonObject} JsonObject */ +/** @typedef {import("./Resolver").ResolveRequest} ResolveRequest */ +/** @typedef {import("./Resolver").ResolveStepHook} ResolveStepHook */ +/** @typedef {import("./util/entrypoints").FieldProcessor} FieldProcessor */ +/** @typedef {import("./util/entrypoints").ImportsField} ImportsField */ + +const dotCode = ".".charCodeAt(0); + +module.exports = class ImportsFieldPlugin { + /** + * @param {string | ResolveStepHook} source source + * @param {Set} conditionNames condition names + * @param {string | string[]} fieldNamePath name path + * @param {string | ResolveStepHook} targetFile target file + * @param {string | ResolveStepHook} targetPackage target package + */ + constructor( + source, + conditionNames, + fieldNamePath, + targetFile, + targetPackage, + ) { + this.source = source; + this.targetFile = targetFile; + this.targetPackage = targetPackage; + this.conditionNames = conditionNames; + this.fieldName = fieldNamePath; + // `null` is cached for description files that have no imports field, + // so subsequent resolves against the same package.json skip the + // `DescriptionFileUtils.getField` walk entirely. + /** @type {WeakMap} */ + this._fieldProcessorCache = new WeakMap(); + } + + /** + * @param {Resolver} resolver the resolver + * @returns {void} + */ + apply(resolver) { + const targetFile = resolver.ensureHook(this.targetFile); + const targetPackage = resolver.ensureHook(this.targetPackage); + + resolver + .getHook(this.source) + .tapAsync("ImportsFieldPlugin", (request, resolveContext, callback) => { + // When there is no description file, abort + if (!request.descriptionFileData || request.request === undefined) { + return callback(); + } + + const { descriptionFileData } = request; + // Skip the concat when there's nothing to append — the common + // case has empty query/fragment, so this avoids an allocation + // per resolve. Mirrors the pattern in ExportsFieldPlugin. + const remainingRequest = + request.query || request.fragment + ? request.request + request.query + request.fragment + : request.request; + + /** @type {string[]} */ + let paths; + /** @type {string | null} */ + let usedField; + + try { + // Look up the cached processor first. On a cache hit we + // avoid re-walking the description file for the imports + // field — and `null` is cached for description files that + // have no imports field at all, so those skip the read + // entirely. `processImportsField` can throw on a + // malformed `imports` map, so building the processor must + // stay inside this try/catch. + let fieldProcessor = + this._fieldProcessorCache.get(descriptionFileData); + if ( + fieldProcessor === undefined && + !this._fieldProcessorCache.has(descriptionFileData) + ) { + const importsField = + /** @type {ImportsField | null | undefined} */ + ( + DescriptionFileUtils.getField( + descriptionFileData, + this.fieldName, + ) + ); + fieldProcessor = importsField + ? processImportsField(importsField) + : null; + this._fieldProcessorCache.set(descriptionFileData, fieldProcessor); + } + if (!fieldProcessor) return callback(); + + if (request.directory) { + return callback( + new Error( + `Resolving to directories is not possible with the imports field (request was ${remainingRequest}/)`, + ), + ); + } + + [paths, usedField] = fieldProcessor( + remainingRequest, + this.conditionNames, + ); + } catch (/** @type {unknown} */ err) { + // Name the package.json in the error itself, not only in the + // log: a malformed field is a mistake in someone's package, + // and without the path there is nothing to go on. The + // original message is kept verbatim inside this one. + const error = new Error( + `${/** @type {Error} */ (err).message} (see imports field in ${ + request.descriptionFilePath + })`, + ); + if (resolveContext.log) { + resolveContext.log(error.message); + } + return callback(error); + } + + if (paths.length === 0) { + // See the matching comment in ExportsFieldPlugin: only this + // already-failing branch pays for the diagnosis. + const explanation = explainSubpathsInConditions( + /** @type {ImportsField | null | undefined} */ + ( + DescriptionFileUtils.getField(descriptionFileData, this.fieldName) + ), + false, + ); + return callback( + new Error( + `Package import ${remainingRequest} is not imported from package ${request.descriptionFileRoot} (see imports field in ${request.descriptionFilePath})${ + explanation ? `. In that imports field, ${explanation}` : "" + }`, + ), + ); + } + + forEachBail( + paths, + /** + * @param {string} path path + * @param {(err?: null | Error, result?: null | ResolveRequest) => void} callback callback + * @param {number} i index + * @returns {void} + */ + (path, callback, i) => { + const parsedIdentifier = parseIdentifier(path); + + if (!parsedIdentifier) return callback(); + + const [path_, query, fragment] = parsedIdentifier; + + switch (path_.charCodeAt(0)) { + // should be relative + case dotCode: { + const withoutDotSlash = path_.slice(2); + if (invalidSegmentRegEx.test(withoutDotSlash)) { + if (paths.length === i) { + return callback( + new Error( + `Invalid "imports" target "${path}" defined for "${usedField}" in the package config ${request.descriptionFilePath}, targets must start with "./"`, + ), + ); + } + + return callback(); + } + + /** @type {ResolveRequest} */ + const obj = { + ...request, + request: undefined, + path: resolver.join( + /** @type {string} */ (request.descriptionFileRoot), + path_, + ), + relativePath: path_, + query, + fragment, + }; + + resolver.doResolve( + targetFile, + obj, + `using imports field: ${path}`, + resolveContext, + (err, result) => { + if (err) return callback(err); + // Don't allow to continue - https://github.com/webpack/enhanced-resolve/issues/400 + if (result === undefined) return callback(null, null); + callback(null, result); + }, + ); + break; + } + + // package resolving + default: { + /** @type {ResolveRequest} */ + const obj = { + ...request, + request: path_, + relativePath: path_, + fullySpecified: true, + query, + fragment, + }; + + resolver.doResolve( + targetPackage, + obj, + `using imports field: ${path}`, + resolveContext, + (err, result) => { + if (err) return callback(err); + // Don't allow to continue - https://github.com/webpack/enhanced-resolve/issues/400 + if (result === undefined) return callback(null, null); + callback(null, result); + }, + ); + } + } + }, + /** + * @param {null | Error=} err error + * @param {null | ResolveRequest=} result result + * @returns {void} + */ + (err, result) => callback(err, result || null), + ); + }); + } +}; diff --git a/dg-ui/node_modules/enhanced-resolve/lib/JoinRequestPartPlugin.js b/dg-ui/node_modules/enhanced-resolve/lib/JoinRequestPartPlugin.js new file mode 100644 index 0000000..a171b98 --- /dev/null +++ b/dg-ui/node_modules/enhanced-resolve/lib/JoinRequestPartPlugin.js @@ -0,0 +1,75 @@ +/* + MIT License http://www.opensource.org/licenses/mit-license.php + Author Tobias Koppers @sokra +*/ + +"use strict"; + +/** @typedef {import("./Resolver")} Resolver */ +/** @typedef {import("./Resolver").ResolveRequest} ResolveRequest */ +/** @typedef {import("./Resolver").ResolveStepHook} ResolveStepHook */ + +const namespaceStartCharCode = "@".charCodeAt(0); + +module.exports = class JoinRequestPartPlugin { + /** + * @param {string | ResolveStepHook} source source + * @param {string | ResolveStepHook} target target + */ + constructor(source, target) { + this.source = source; + this.target = target; + } + + /** + * @param {Resolver} resolver the resolver + * @returns {void} + */ + apply(resolver) { + const target = resolver.ensureHook(this.target); + resolver + .getHook(this.source) + .tapAsync( + "JoinRequestPartPlugin", + (request, resolveContext, callback) => { + const req = request.request || ""; + let i = req.indexOf("/", 3); + + if (i >= 0 && req.charCodeAt(2) === namespaceStartCharCode) { + i = req.indexOf("/", i + 1); + } + + /** @type {string} */ + let moduleName; + /** @type {string} */ + let remainingRequest; + /** @type {boolean} */ + let fullySpecified; + if (i < 0) { + moduleName = req; + remainingRequest = "."; + fullySpecified = false; + } else { + moduleName = req.slice(0, i); + remainingRequest = `.${req.slice(i)}`; + fullySpecified = /** @type {boolean} */ (request.fullySpecified); + } + /** @type {ResolveRequest} */ + const obj = { + ...request, + path: resolver.join( + /** @type {string} */ + (request.path), + moduleName, + ), + relativePath: + request.relativePath && + resolver.join(request.relativePath, moduleName), + request: remainingRequest, + fullySpecified, + }; + resolver.doResolve(target, obj, null, resolveContext, callback); + }, + ); + } +}; diff --git a/dg-ui/node_modules/enhanced-resolve/lib/JoinRequestPlugin.js b/dg-ui/node_modules/enhanced-resolve/lib/JoinRequestPlugin.js new file mode 100644 index 0000000..108958e --- /dev/null +++ b/dg-ui/node_modules/enhanced-resolve/lib/JoinRequestPlugin.js @@ -0,0 +1,45 @@ +/* + MIT License http://www.opensource.org/licenses/mit-license.php + Author Tobias Koppers @sokra +*/ + +"use strict"; + +/** @typedef {import("./Resolver")} Resolver */ +/** @typedef {import("./Resolver").ResolveRequest} ResolveRequest */ +/** @typedef {import("./Resolver").ResolveStepHook} ResolveStepHook */ + +module.exports = class JoinRequestPlugin { + /** + * @param {string | ResolveStepHook} source source + * @param {string | ResolveStepHook} target target + */ + constructor(source, target) { + this.source = source; + this.target = target; + } + + /** + * @param {Resolver} resolver the resolver + * @returns {void} + */ + apply(resolver) { + const target = resolver.ensureHook(this.target); + resolver + .getHook(this.source) + .tapAsync("JoinRequestPlugin", (request, resolveContext, callback) => { + const requestPath = /** @type {string} */ (request.path); + const requestRequest = /** @type {string} */ (request.request); + /** @type {ResolveRequest} */ + const obj = { + ...request, + path: resolver.join(requestPath, requestRequest), + relativePath: + request.relativePath && + resolver.join(request.relativePath, requestRequest), + request: undefined, + }; + resolver.doResolve(target, obj, null, resolveContext, callback); + }); + } +}; diff --git a/dg-ui/node_modules/enhanced-resolve/lib/LogInfoPlugin.js b/dg-ui/node_modules/enhanced-resolve/lib/LogInfoPlugin.js new file mode 100644 index 0000000..5dbb688 --- /dev/null +++ b/dg-ui/node_modules/enhanced-resolve/lib/LogInfoPlugin.js @@ -0,0 +1,58 @@ +/* + MIT License http://www.opensource.org/licenses/mit-license.php + Author Tobias Koppers @sokra +*/ + +"use strict"; + +/** @typedef {import("./Resolver")} Resolver */ +/** @typedef {import("./Resolver").ResolveStepHook} ResolveStepHook */ + +module.exports = class LogInfoPlugin { + /** + * @param {string | ResolveStepHook} source source + */ + constructor(source) { + this.source = source; + } + + /** + * @param {Resolver} resolver the resolver + * @returns {void} + */ + apply(resolver) { + const { source } = this; + resolver + .getHook(this.source) + .tapAsync("LogInfoPlugin", (request, resolveContext, callback) => { + if (!resolveContext.log) return callback(); + const { log } = resolveContext; + const prefix = `[${source}] `; + if (request.path) { + log(`${prefix}Resolving in directory: ${request.path}`); + } + if (request.request) { + log(`${prefix}Resolving request: ${request.request}`); + } + if (request.module) log(`${prefix}Request is an module request.`); + if (request.directory) log(`${prefix}Request is a directory request.`); + if (request.query) { + log(`${prefix}Resolving request query: ${request.query}`); + } + if (request.fragment) { + log(`${prefix}Resolving request fragment: ${request.fragment}`); + } + if (request.descriptionFilePath) { + log( + `${prefix}Has description data from ${request.descriptionFilePath}`, + ); + } + if (request.relativePath) { + log( + `${prefix}Relative path from description file is: ${request.relativePath}`, + ); + } + callback(); + }); + } +}; diff --git a/dg-ui/node_modules/enhanced-resolve/lib/MainFieldPlugin.js b/dg-ui/node_modules/enhanced-resolve/lib/MainFieldPlugin.js new file mode 100644 index 0000000..7616b9e --- /dev/null +++ b/dg-ui/node_modules/enhanced-resolve/lib/MainFieldPlugin.js @@ -0,0 +1,97 @@ +/* + MIT License http://www.opensource.org/licenses/mit-license.php + Author Tobias Koppers @sokra +*/ + +"use strict"; + +const DescriptionFileUtils = require("./DescriptionFileUtils"); + +/** @typedef {import("./Resolver")} Resolver */ +/** @typedef {import("./Resolver").JsonObject} JsonObject */ +/** @typedef {import("./Resolver").ResolveRequest} ResolveRequest */ +/** @typedef {import("./Resolver").ResolveStepHook} ResolveStepHook */ + +/** @typedef {{ name: string | string[], forceRelative: boolean }} MainFieldOptions */ + +const alreadyTriedMainField = Symbol("alreadyTriedMainField"); + +// Sentinel cached for description files where the main field resolves to a +// value we cannot use (missing, non-string, ".", "./"). Cheaper to store and +// check than to re-walk the description file on every resolve. +const NO_MAIN = Symbol("NoMain"); + +module.exports = class MainFieldPlugin { + /** + * @param {string | ResolveStepHook} source source + * @param {MainFieldOptions} options options + * @param {string | ResolveStepHook} target target + */ + constructor(source, options, target) { + this.source = source; + this.options = options; + this.target = target; + // Cache the resolved `mainModule` per description-file content. The + // options (`name`, `forceRelative`) are fixed for this plugin + // instance, so caching against content alone is safe. Stores either + // the ready-to-use request string or the `NO_MAIN` sentinel. + /** @type {WeakMap} */ + this._mainModuleCache = new WeakMap(); + } + + /** + * @param {Resolver} resolver the resolver + * @returns {void} + */ + apply(resolver) { + const target = resolver.ensureHook(this.target); + resolver + .getHook(this.source) + .tapAsync("MainFieldPlugin", (request, resolveContext, callback) => { + if ( + request.path !== request.descriptionFileRoot || + /** @type {ResolveRequest & { [alreadyTriedMainField]?: string }} */ + (request)[alreadyTriedMainField] === request.descriptionFilePath || + !request.descriptionFilePath + ) { + return callback(); + } + const descFileData = /** @type {JsonObject} */ ( + request.descriptionFileData + ); + let mainModule = this._mainModuleCache.get(descFileData); + if (mainModule === undefined) { + let raw = + /** @type {string | null | undefined} */ + (DescriptionFileUtils.getField(descFileData, this.options.name)); + if (!raw || typeof raw !== "string" || raw === "." || raw === "./") { + this._mainModuleCache.set(descFileData, NO_MAIN); + return callback(); + } + if (this.options.forceRelative && !/^\.\.?\//.test(raw)) { + raw = `./${raw}`; + } + mainModule = raw; + this._mainModuleCache.set(descFileData, mainModule); + } else if (mainModule === NO_MAIN) { + return callback(); + } + const filename = resolver.basename(request.descriptionFilePath); + /** @type {ResolveRequest & { [alreadyTriedMainField]?: string }} */ + const obj = { + ...request, + request: mainModule, + module: false, + directory: mainModule.endsWith("/"), + [alreadyTriedMainField]: request.descriptionFilePath, + }; + return resolver.doResolve( + target, + obj, + `use ${mainModule} from ${this.options.name} in ${filename}`, + resolveContext, + callback, + ); + }); + } +}; diff --git a/dg-ui/node_modules/enhanced-resolve/lib/ModulesInHierachicDirectoriesPlugin.js b/dg-ui/node_modules/enhanced-resolve/lib/ModulesInHierachicDirectoriesPlugin.js new file mode 100644 index 0000000..06065e8 --- /dev/null +++ b/dg-ui/node_modules/enhanced-resolve/lib/ModulesInHierachicDirectoriesPlugin.js @@ -0,0 +1,9 @@ +/* + MIT License http://www.opensource.org/licenses/mit-license.php + Author Tobias Koppers @sokra +*/ + +"use strict"; + +// TODO remove in next major +module.exports = require("./ModulesInHierarchicalDirectoriesPlugin"); diff --git a/dg-ui/node_modules/enhanced-resolve/lib/ModulesInHierarchicalDirectoriesPlugin.js b/dg-ui/node_modules/enhanced-resolve/lib/ModulesInHierarchicalDirectoriesPlugin.js new file mode 100644 index 0000000..4f19fc3 --- /dev/null +++ b/dg-ui/node_modules/enhanced-resolve/lib/ModulesInHierarchicalDirectoriesPlugin.js @@ -0,0 +1,47 @@ +/* + MIT License http://www.opensource.org/licenses/mit-license.php + Author Tobias Koppers @sokra +*/ + +"use strict"; + +const { modulesResolveHandler } = require("./ModulesUtils"); + +/** @typedef {import("./Resolver")} Resolver */ +/** @typedef {import("./Resolver").ResolveStepHook} ResolveStepHook */ + +module.exports = class ModulesInHierarchicalDirectoriesPlugin { + /** + * @param {string | ResolveStepHook} source source + * @param {string | string[]} directories directories + * @param {string | ResolveStepHook} target target + */ + constructor(source, directories, target) { + this.source = source; + this.directories = /** @type {string[]} */ [...directories]; + this.target = target; + } + + /** + * @param {Resolver} resolver the resolver + * @returns {void} + */ + apply(resolver) { + const target = resolver.ensureHook(this.target); + resolver + .getHook(this.source) + .tapAsync( + "ModulesInHierarchicalDirectoriesPlugin", + (request, resolveContext, callback) => { + modulesResolveHandler( + resolver, + this.directories, + target, + request, + resolveContext, + callback, + ); + }, + ); + } +}; diff --git a/dg-ui/node_modules/enhanced-resolve/lib/ModulesInRootPlugin.js b/dg-ui/node_modules/enhanced-resolve/lib/ModulesInRootPlugin.js new file mode 100644 index 0000000..7797a11 --- /dev/null +++ b/dg-ui/node_modules/enhanced-resolve/lib/ModulesInRootPlugin.js @@ -0,0 +1,49 @@ +/* + MIT License http://www.opensource.org/licenses/mit-license.php + Author Tobias Koppers @sokra +*/ + +"use strict"; + +/** @typedef {import("./Resolver")} Resolver */ +/** @typedef {import("./Resolver").ResolveRequest} ResolveRequest */ +/** @typedef {import("./Resolver").ResolveStepHook} ResolveStepHook */ + +module.exports = class ModulesInRootPlugin { + /** + * @param {string | ResolveStepHook} source source + * @param {string} path path + * @param {string | ResolveStepHook} target target + */ + constructor(source, path, target) { + this.source = source; + this.path = path; + this.target = target; + } + + /** + * @param {Resolver} resolver the resolver + * @returns {void} + */ + apply(resolver) { + const target = resolver.ensureHook(this.target); + resolver + .getHook(this.source) + .tapAsync("ModulesInRootPlugin", (request, resolveContext, callback) => { + /** @type {ResolveRequest} */ + const obj = { + ...request, + path: this.path, + request: `./${request.request}`, + module: false, + }; + resolver.doResolve( + target, + obj, + `looking for modules in ${this.path}`, + resolveContext, + callback, + ); + }); + } +}; diff --git a/dg-ui/node_modules/enhanced-resolve/lib/ModulesUtils.js b/dg-ui/node_modules/enhanced-resolve/lib/ModulesUtils.js new file mode 100644 index 0000000..3de32da --- /dev/null +++ b/dg-ui/node_modules/enhanced-resolve/lib/ModulesUtils.js @@ -0,0 +1,132 @@ +/* + MIT License http://www.opensource.org/licenses/mit-license.php + Author Tobias Koppers @sokra +*/ + +"use strict"; + +const forEachBail = require("./forEachBail"); +const { getPathsCached } = require("./getPaths"); + +/** @typedef {import("./Resolver")} Resolver */ +/** @typedef {import("./Resolver").ResolveRequest} ResolveRequest */ +/** @typedef {import("./Resolver").ResolveStepHook} ResolveStepHook */ +/** @typedef {import("./Resolver").ResolveContext} ResolveContext */ +/** @typedef {(err?: null | Error, result?: null | ResolveRequest) => void} InnerCallback */ + +/** + * Per-(directories-array) cache of the flat `addrs` list produced for a given + * `request.path`. For a fixed directories configuration the fan-out of + * `ancestor × directory` is deterministic per request.path, and many resolves + * share the same starting directory (sibling files in one project, loops over + * a batch of imports, etc.) — caching avoids the `getPaths` regex split plus + * `len(paths) × len(directories)` join calls per resolve. + * + * The outer map is keyed on the directories array reference (plugin-owned, + * stable for the lifetime of the resolver), and the inner map on the + * starting `request.path`. Kept private to this module (rather than hung off + * `resolver.pathCache`) so the pathCache's hidden-class shape is unchanged — + * that avoids perturbing the interpreter-mode IC state for the + * `resolver.pathCache.{join,dirname,basename}.fn(...)` accesses that run on + * every resolve, which the CodSpeed instruction-count harness is sensitive to. + * @type {WeakMap>} + */ +const _addrsCacheByDirs = new WeakMap(); + +/** + * @param {Resolver} resolver resolver + * @param {string[]} directories directories + * @param {ResolveStepHook} target target + * @param {ResolveRequest} request request + * @param {ResolveContext} resolveContext resolve context + * @param {InnerCallback} callback callback + * @returns {void} + */ +function modulesResolveHandler( + resolver, + directories, + target, + request, + resolveContext, + callback, +) { + const fs = resolver.fileSystem; + const requestPath = /** @type {string} */ (request.path); + // Compute-or-reuse the flat `addrs` list. Inlined (rather than a helper + // function) so the cache-hit path — which is the vast majority of + // invocations — stays a single WeakMap + Map lookup with no function-call + // overhead. See `_addrsCacheByDirs` above for caching rationale. + let addrs; + let perPath = _addrsCacheByDirs.get(directories); + if (perPath === undefined) { + perPath = new Map(); + _addrsCacheByDirs.set(directories, perPath); + } else { + addrs = perPath.get(requestPath); + } + if (addrs === undefined) { + const { paths } = getPathsCached(fs, requestPath); + const pathsLen = paths.length; + const dirsLen = directories.length; + // Pre-size the flat array rather than going through `map().reduce()` + // with intermediate arrays + spreads. + // eslint-disable-next-line unicorn/no-new-array + addrs = new Array(pathsLen * dirsLen); + let idx = 0; + const joinFn = resolver.pathCache.join.fn; + for (let pi = 0; pi < pathsLen; pi++) { + const pathItem = paths[pi]; + for (let di = 0; di < dirsLen; di++) { + addrs[idx++] = joinFn(pathItem, directories[di]); + } + } + perPath.set(requestPath, addrs); + } + // Hoist the dot-prefixed request out of the per-addr iterator. `addrs` + // can have up to `paths.length × directories.length` entries (e.g. 36 + // for an 8-deep source dir × 4-module config), and concatenating the + // same `./${request.request}` string on every iteration is wasted + // work — it's constant for the whole fan-out. + const relRequest = `./${request.request}`; + forEachBail( + addrs, + /** + * @param {string} addr addr + * @param {(err?: null | Error, result?: null | ResolveRequest) => void} callback callback + * @returns {void} + */ + (addr, callback) => { + fs.stat(addr, (err, stat) => { + if (!err && stat && stat.isDirectory()) { + /** @type {ResolveRequest} */ + const obj = { + ...request, + path: addr, + request: relRequest, + module: false, + }; + const message = `looking for modules in ${addr}`; + return resolver.doResolve( + target, + obj, + message, + resolveContext, + callback, + ); + } + if (resolveContext.log) { + resolveContext.log(`${addr} doesn't exist or is not a directory`); + } + if (resolveContext.missingDependencies) { + resolveContext.missingDependencies.add(addr); + } + return callback(); + }); + }, + callback, + ); +} + +module.exports = { + modulesResolveHandler, +}; diff --git a/dg-ui/node_modules/enhanced-resolve/lib/NextPlugin.js b/dg-ui/node_modules/enhanced-resolve/lib/NextPlugin.js new file mode 100644 index 0000000..e59c56b --- /dev/null +++ b/dg-ui/node_modules/enhanced-resolve/lib/NextPlugin.js @@ -0,0 +1,33 @@ +/* + MIT License http://www.opensource.org/licenses/mit-license.php + Author Tobias Koppers @sokra +*/ + +"use strict"; + +/** @typedef {import("./Resolver")} Resolver */ +/** @typedef {import("./Resolver").ResolveStepHook} ResolveStepHook */ + +module.exports = class NextPlugin { + /** + * @param {string | ResolveStepHook} source source + * @param {string | ResolveStepHook} target target + */ + constructor(source, target) { + this.source = source; + this.target = target; + } + + /** + * @param {Resolver} resolver the resolver + * @returns {void} + */ + apply(resolver) { + const target = resolver.ensureHook(this.target); + resolver + .getHook(this.source) + .tapAsync("NextPlugin", (request, resolveContext, callback) => { + resolver.doResolve(target, request, null, resolveContext, callback); + }); + } +}; diff --git a/dg-ui/node_modules/enhanced-resolve/lib/PackageMapPlugin.js b/dg-ui/node_modules/enhanced-resolve/lib/PackageMapPlugin.js new file mode 100644 index 0000000..39377b3 --- /dev/null +++ b/dg-ui/node_modules/enhanced-resolve/lib/PackageMapPlugin.js @@ -0,0 +1,297 @@ +/* + MIT License http://www.opensource.org/licenses/mit-license.php +*/ + +"use strict"; + +const { readJson } = require("./util/fs"); +const { + createError, + findPackageIds, + parsePackageMap, +} = require("./util/packageMap"); + +/** @typedef {import("./Resolver")} Resolver */ +/** @typedef {import("./Resolver").ResolveContext} ResolveContext */ +/** @typedef {import("./Resolver").ResolveRequest} ResolveRequest */ +/** @typedef {import("./Resolver").ResolveStepHook} ResolveStepHook */ +/** @typedef {import("./util/packageMap").PackageMap} PackageMap */ +/** @typedef {import("./util/packageMap").PackageMapPackages} PackageMapPackages */ + +/** + * @typedef {object} PackageMapOptions + * @property {string} configFile absolute path of the configuration file, read lazily when `packages` is not given + * @property {PackageMapPackages | null} packages an already-parsed `packages` object, used instead of reading `configFile` + */ + +/** @typedef {(err: Error | null, packageMap?: PackageMap) => void} PackageMapCallback */ + +const PACKAGE_NAME_REGEXP = /^(@[^/]+\/)?[^/]+/; + +/** + * Resolves bare specifiers through a Node.js package map instead of walking + * `node_modules`: the importing package's `dependencies` table names the + * package id to use, and that entry's location is handed to the regular + * resolution pipeline to finish the job (`exports`, `main`, extensions...). + * + * The importing package is taken from an explicit package id when the caller + * propagates one (`context.packageId`, or `packageId` carried over from a + * previous result) and located by path otherwise. Two situations are hard + * errors rather than a miss, because guessing would silently resolve to the + * wrong package: the importer sitting outside every mapped package, and + * several package entries sharing the importer's location. A specifier that is + * simply absent from `dependencies` is reported as unresolved, and no + * `node_modules` fallback is attempted. + * @experimental Package maps are stability 1 (experimental) in Node.js and are + * only reachable there behind `--experimental-package-map`. This plugin tracks + * that specification and may change with it, including in a patch release. + */ +module.exports = class PackageMapPlugin { + /** + * @param {string | ResolveStepHook} source source + * @param {PackageMapOptions} options package map options + * @param {boolean} symlinks whether the resolver resolves symlinks + * @param {string | ResolveStepHook} target target + */ + constructor(source, options, symlinks, target) { + this.source = source; + this.options = options; + this.symlinks = symlinks; + this.target = target; + /** @type {PackageMap | undefined} */ + this._packageMap = undefined; + /** @type {PackageMapCallback[] | undefined} */ + this._pending = undefined; + } + + /** + * Read and parse the configuration file once, queueing every request that + * arrives while the read is in flight so a cold start does not re-read the + * same file for each of them. + * @param {Resolver} resolver the resolver + * @param {ResolveContext} resolveContext resolve context + * @param {PackageMapCallback} callback callback + * @returns {void} + */ + _getPackageMap(resolver, resolveContext, callback) { + const { configFile, packages } = this.options; + + if (configFile && resolveContext.fileDependencies) { + resolveContext.fileDependencies.add(configFile); + } + + if (this._packageMap !== undefined) { + return callback(null, this._packageMap); + } + + if (this._pending) { + this._pending.push(callback); + return; + } + this._pending = [callback]; + + /** + * @param {Error | null} error error + * @param {PackageMap=} packageMap package map + * @returns {void} + */ + const finish = (error, packageMap) => { + const pending = /** @type {PackageMapCallback[]} */ (this._pending); + this._pending = undefined; + for (const pendingCallback of pending) { + pendingCallback(error, packageMap); + } + }; + + // Package locations are matched against the paths the pipeline hands + // over, and those have their symlinks resolved when `symlinks` is on. + // Resolve the configuration file the same way so both sides are spelled + // alike; with `symlinks` off both keep the symlinked spelling instead. + this._resolveConfigFile(resolver, (realConfigFile) => { + if (packages) { + /** @type {PackageMap} */ + let packageMap; + try { + packageMap = parsePackageMap({ packages }, realConfigFile); + } catch (err) { + return finish(/** @type {Error} */ (err)); + } + this._packageMap = packageMap; + return finish(null, packageMap); + } + + readJson( + resolver.fileSystem, + realConfigFile, + { stripComments: false }, + (err, content) => { + /** @type {Error | null} */ + let error = err || null; + /** @type {PackageMap | undefined} */ + let packageMap; + + if (!error) { + try { + packageMap = parsePackageMap( + /** @type {import("./Resolver").JsonObject} */ (content), + realConfigFile, + ); + this._packageMap = packageMap; + } catch (parseErr) { + error = /** @type {Error} */ (parseErr); + } + } + + finish(error, packageMap); + }, + ); + }); + } + + /** + * Hand back the configuration file path package locations resolve against: + * its real path when the resolver follows symlinks, and the path as given + * otherwise. A configuration file whose real path cannot be read (it may not + * exist, or the file system may not implement it) is used as-is, so the + * read below reports the problem. + * @param {Resolver} resolver the resolver + * @param {(configFile: string) => void} callback callback + * @returns {void} + */ + _resolveConfigFile(resolver, callback) { + const { configFile } = this.options; + const { realpath } = resolver.fileSystem; + + if (!this.symlinks || !realpath) return callback(configFile); + + realpath(configFile, (err, result) => { + callback(err || !result ? configFile : String(result)); + }); + } + + /** + * @param {Resolver} resolver the resolver + * @returns {void} + */ + apply(resolver) { + /** @type {ResolveStepHook} */ + const target = resolver.ensureHook(this.target); + resolver + .getHook(this.source) + .tapAsync("PackageMapPlugin", (request, resolveContext, callback) => { + const req = request.request; + if (!req) return callback(); + // Builtins are not affected by package maps. + if (req.startsWith("node:")) return callback(); + + const packageMatch = PACKAGE_NAME_REGEXP.exec(req); + if (!packageMatch) return callback(); + + const [packageName] = packageMatch; + const innerRequest = `.${req.slice(packageName.length)}`; + + this._getPackageMap(resolver, resolveContext, (err, packageMap) => { + if (err) return callback(err); + + const { packages } = /** @type {PackageMap} */ (packageMap); + const issuerPath = request.path; + // A package id may be any key of the `packages` object, the empty + // string included, so distinguish "not provided" from falsy. + const contextId = + request.context && + /** @type {string | undefined} */ (request.context.packageId); + const explicitId = + request.packageId !== undefined ? request.packageId : contextId; + + /** @type {string} */ + let issuerId; + + if (explicitId !== undefined && explicitId !== null) { + if (!packages.has(explicitId)) { + return callback( + createError( + `Unknown package id "${explicitId}" for request "${req}"`, + "ERR_PACKAGE_MAP_UNKNOWN_PACKAGE", + ), + ); + } + issuerId = explicitId; + } else { + const ids = + issuerPath === false + ? [] + : findPackageIds( + /** @type {PackageMap} */ (packageMap), + issuerPath, + ); + + if (ids.length === 0) { + return callback( + createError( + `Cannot resolve "${req}" from "${issuerPath}": the importing file is not inside any package of the package map`, + "ERR_PACKAGE_MAP_EXTERNAL_FILE", + ), + ); + } + if (ids.length > 1) { + return callback( + createError( + `Cannot resolve "${req}" from "${issuerPath}": the package ids ${ids + .map((id) => `"${id}"`) + .join( + ", ", + )} share this location, so the importing package is ambiguous. Propagate the package id of the previous resolution to disambiguate.`, + "ERR_PACKAGE_MAP_AMBIGUOUS_PACKAGE", + ), + ); + } + [issuerId] = ids; + } + + const issuer = + /** @type {import("./util/packageMap").PackageMapEntry} */ ( + packages.get(issuerId) + ); + const targetId = issuer.dependencies.get(packageName); + + if (targetId === undefined) { + if (resolveContext.log) { + resolveContext.log( + `"${packageName}" is not a dependency of package "${issuerId}" in the package map`, + ); + } + // Bail without a result: the package map is authoritative, so + // there is no `node_modules` fallback to try. + return callback(null, null); + } + + const targetEntry = + /** @type {import("./util/packageMap").PackageMapEntry} */ ( + packages.get(targetId) + ); + + /** @type {ResolveRequest} */ + const obj = { + ...request, + path: targetEntry.path, + request: innerRequest, + packageId: targetId, + fullySpecified: request.fullySpecified && innerRequest !== ".", + }; + + resolver.doResolve( + target, + obj, + `resolved "${packageName}" to package "${targetId}" by the package map`, + resolveContext, + (resolveErr, result) => { + if (resolveErr) return callback(resolveErr); + if (result) return callback(null, result); + // Skip alternatives + return callback(null, null); + }, + ); + }); + }); + } +}; diff --git a/dg-ui/node_modules/enhanced-resolve/lib/ParsePlugin.js b/dg-ui/node_modules/enhanced-resolve/lib/ParsePlugin.js new file mode 100644 index 0000000..bcac8f6 --- /dev/null +++ b/dg-ui/node_modules/enhanced-resolve/lib/ParsePlugin.js @@ -0,0 +1,84 @@ +/* + MIT License http://www.opensource.org/licenses/mit-license.php + Author Tobias Koppers @sokra +*/ + +"use strict"; + +/** @typedef {import("./Resolver")} Resolver */ +/** @typedef {import("./Resolver").ResolveRequest} ResolveRequest */ +/** @typedef {import("./Resolver").ResolveStepHook} ResolveStepHook */ + +module.exports = class ParsePlugin { + /** + * @param {string | ResolveStepHook} source source + * @param {Partial} requestOptions request options + * @param {string | ResolveStepHook} target target + */ + constructor(source, requestOptions, target) { + this.source = source; + this.requestOptions = requestOptions; + this.target = target; + } + + /** + * @param {Resolver} resolver the resolver + * @returns {void} + */ + apply(resolver) { + const target = resolver.ensureHook(this.target); + const { requestOptions } = this; + resolver + .getHook(this.source) + .tapAsync("ParsePlugin", (request, resolveContext, callback) => { + const parsed = resolver.parse(/** @type {string} */ (request.request)); + /** @type {ResolveRequest} */ + // Single spread + direct field assignment instead of + // `{ ...request, ...parsed, ...requestOptions }` — avoids + // two extra property enumerations on every resolve. + // Keep in sync with Resolver.parse() output shape. + const obj = { ...request }; + obj.request = parsed.request; + obj.query = parsed.query || request.query || ""; + obj.fragment = parsed.fragment || request.fragment || ""; + obj.module = parsed.module; + obj.directory = parsed.directory; + obj.file = parsed.file; + obj.internal = parsed.internal; + Object.assign(obj, requestOptions); + if (parsed && resolveContext.log) { + if (parsed.module) resolveContext.log("Parsed request is a module"); + if (parsed.directory) { + resolveContext.log("Parsed request is a directory"); + } + } + // There is an edge-case where a request with # can be a path or a fragment -> try both + if (obj.request && !obj.query && obj.fragment) { + const directory = obj.fragment.endsWith("/"); + /** @type {ResolveRequest} */ + const alternative = { + ...obj, + directory, + request: + obj.request + + (obj.directory ? "/" : "") + + (directory ? obj.fragment.slice(0, -1) : obj.fragment), + fragment: "", + }; + resolver.doResolve( + target, + alternative, + null, + resolveContext, + (err, result) => { + if (err) return callback(err); + if (result) return callback(null, result); + resolver.doResolve(target, obj, null, resolveContext, callback); + }, + ); + return; + } + resolver.doResolve(target, obj, null, resolveContext, callback); + }); + } +}; diff --git a/dg-ui/node_modules/enhanced-resolve/lib/PnpPlugin.js b/dg-ui/node_modules/enhanced-resolve/lib/PnpPlugin.js new file mode 100644 index 0000000..42b230e --- /dev/null +++ b/dg-ui/node_modules/enhanced-resolve/lib/PnpPlugin.js @@ -0,0 +1,134 @@ +/* + MIT License http://www.opensource.org/licenses/mit-license.php + Author Maël Nison @arcanis +*/ + +"use strict"; + +/** @typedef {import("./Resolver")} Resolver */ +/** @typedef {import("./Resolver").ResolveStepHook} ResolveStepHook */ +/** @typedef {import("./Resolver").ResolveRequest} ResolveRequest */ +/** + * @typedef {object} PnpApiImpl + * @property {(packageName: string, issuer: string, options: { considerBuiltins: boolean }) => string | null} resolveToUnqualified resolve to unqualified + */ + +module.exports = class PnpPlugin { + /** + * @param {string | ResolveStepHook} source source + * @param {PnpApiImpl} pnpApi pnpApi + * @param {string | ResolveStepHook} target target + * @param {string | ResolveStepHook} alternateTarget alternateTarget + */ + constructor(source, pnpApi, target, alternateTarget) { + this.source = source; + this.pnpApi = pnpApi; + this.target = target; + this.alternateTarget = alternateTarget; + } + + /** + * @param {Resolver} resolver the resolver + * @returns {void} + */ + apply(resolver) { + /** @type {ResolveStepHook} */ + const target = resolver.ensureHook(this.target); + const alternateTarget = resolver.ensureHook(this.alternateTarget); + resolver + .getHook(this.source) + .tapAsync("PnpPlugin", (request, resolveContext, callback) => { + const req = request.request; + if (!req) return callback(); + + // The trailing slash indicates to PnP that this value is a folder rather than a file + const issuer = `${request.path}/`; + + const packageMatch = /^(@[^/]+\/)?[^/]+/.exec(req); + if (!packageMatch) return callback(); + + const [packageName] = packageMatch; + const innerRequest = `.${req.slice(packageName.length)}`; + + /** @type {string | undefined | null} */ + let resolution; + /** @type {string | undefined | null} */ + let apiResolution; + try { + resolution = this.pnpApi.resolveToUnqualified(packageName, issuer, { + considerBuiltins: false, + }); + + if (resolution === null) { + // This is either not a PnP managed issuer or it's a Node builtin + // Try to continue resolving with our alternatives + resolver.doResolve( + alternateTarget, + request, + "issuer is not managed by a pnpapi", + resolveContext, + (err, result) => { + if (err) return callback(err); + if (result) return callback(null, result); + // Skip alternatives + return callback(null, null); + }, + ); + return; + } + + if (resolveContext.fileDependencies) { + apiResolution = this.pnpApi.resolveToUnqualified("pnpapi", issuer, { + considerBuiltins: false, + }); + } + } catch (/** @type {unknown} */ error) { + if ( + /** @type {Error & { code: string }} */ + (error).code === "MODULE_NOT_FOUND" && + /** @type {Error & { pnpCode: string }} */ + (error).pnpCode === "UNDECLARED_DEPENDENCY" + ) { + // This is not a PnP managed dependency. + // Try to continue resolving with our alternatives + if (resolveContext.log) { + resolveContext.log("request is not managed by the pnpapi"); + for (const line of /** @type {Error} */ (error).message + .split("\n") + .filter(Boolean)) { + resolveContext.log(` ${line}`); + } + } + return callback(); + } + return callback(/** @type {Error} */ (error)); + } + + if (resolution === packageName) return callback(); + + if (apiResolution && resolveContext.fileDependencies) { + resolveContext.fileDependencies.add(apiResolution); + } + /** @type {ResolveRequest} */ + const obj = { + ...request, + path: resolution, + request: innerRequest, + ignoreSymlinks: true, + fullySpecified: request.fullySpecified && innerRequest !== ".", + }; + resolver.doResolve( + target, + obj, + `resolved by pnp to ${resolution}`, + resolveContext, + (err, result) => { + if (err) return callback(err); + if (result) return callback(null, result); + // Skip alternatives + return callback(null, null); + }, + ); + }); + } +}; diff --git a/dg-ui/node_modules/enhanced-resolve/lib/Resolver.js b/dg-ui/node_modules/enhanced-resolve/lib/Resolver.js new file mode 100644 index 0000000..96fa54a --- /dev/null +++ b/dg-ui/node_modules/enhanced-resolve/lib/Resolver.js @@ -0,0 +1,1254 @@ +/* + MIT License http://www.opensource.org/licenses/mit-license.php + Author Tobias Koppers @sokra +*/ + +"use strict"; + +const { AsyncSeriesBailHook, AsyncSeriesHook, SyncHook } = require("tapable"); +const createInnerContext = require("./createInnerContext"); +const { parseIdentifier } = require("./util/identifier"); +const { + PathType, + createCachedBasename, + createCachedDirname, + createCachedJoin, + getType, + isFileURL, + normalize, + toPath, +} = require("./util/path"); + +/* eslint-disable jsdoc/check-alignment */ +// TODO in the next major release use only `Promise.withResolvers()` +const _withResolvers = + // eslint-disable-next-line n/no-unsupported-features/es-syntax + Promise.withResolvers + ? /** + * @param {Resolver} self resolver + * @param {Context} context context information object + * @param {string | URL} path context path or a `file:` URL instance + * @param {string | URL} request request string or a `file:` URL instance + * @param {ResolveContext} resolveContext resolve context + * @returns {Promise} result + */ + (self, context, path, request, resolveContext) => { + // eslint-disable-next-line n/no-unsupported-features/es-syntax + const { promise, resolve, reject } = Promise.withResolvers(); + self.resolve(context, path, request, resolveContext, (err, res) => { + if (err) reject(err); + else resolve(/** @type {string | false} */ (res)); + }); + return promise; + } + : /** + * @param {Resolver} self resolver + * @param {Context} context context information object + * @param {string | URL} path context path or a `file:` URL instance + * @param {string | URL} request request string or a `file:` URL instance + * @param {ResolveContext} resolveContext resolve context + * @returns {Promise} result + */ + (self, context, path, request, resolveContext) => + new Promise((resolve, reject) => { + self.resolve(context, path, request, resolveContext, (err, res) => { + if (err) reject(err); + else resolve(/** @type {string | false} */ (res)); + }); + }); +/* eslint-enable jsdoc/check-alignment */ + +/** @typedef {import("./AliasUtils").AliasOption} AliasOption */ +/** @typedef {import("./util/path").CachedJoin} CachedJoin */ +/** @typedef {import("./util/path").CachedDirname} CachedDirname */ +/** @typedef {import("./util/path").CachedBasename} CachedBasename */ + +/** + * @typedef {object} JoinCacheEntry + * @property {CachedJoin["fn"]} fn cached join function + * @property {CachedJoin["cache"]} cache the underlying cache map + */ + +/** + * @typedef {object} DirnameCacheEntry + * @property {CachedDirname["fn"]} fn cached dirname function + * @property {CachedDirname["cache"]} cache the underlying cache map + */ + +/** + * @typedef {object} BasenameCacheEntry + * @property {CachedBasename["fn"]} fn cached dirname function + * @property {CachedBasename["cache"]} cache the underlying cache map + */ + +/** + * @typedef {object} PathCacheFunctions + * @property {JoinCacheEntry} join cached join + * @property {DirnameCacheEntry} dirname cached dirname + * @property {BasenameCacheEntry} basename cached basename + */ + +/** @type {WeakMap} */ +const _pathCacheByFs = new WeakMap(); + +const HASH_ESCAPE_RE = /#/g; + +/** @typedef {import("./ResolverFactory").ResolveOptions} ResolveOptions */ + +/** + * @typedef {object} KnownContext + * @property {string[]=} environments environments + * @property {string=} packageId package id of the importing file in the package map, propagated from a previous result to disambiguate package entries that share a location (`@experimental`, see the `packageMap` option) + */ + +// eslint-disable-next-line jsdoc/reject-any-type +/** @typedef {KnownContext & Record} Context */ + +/** @typedef {Error & { details?: string }} ErrorWithDetail */ + +/** @typedef {(err: ErrorWithDetail | null, res?: string | false, req?: ResolveRequest) => void} ResolveCallback */ + +/** + * @typedef {object} PossibleFileSystemError + * @property {string=} code code + * @property {number=} errno number + * @property {string=} path path + * @property {string=} syscall syscall + */ + +/** + * @template T + * @callback FileSystemCallback + * @param {PossibleFileSystemError & Error | null} err + * @param {T=} result + */ + +/** + * @typedef {string | Buffer | URL} PathLike + */ + +/** + * @typedef {PathLike | number} PathOrFileDescriptor + */ + +/** + * @typedef {object} ObjectEncodingOptions + * @property {BufferEncoding | null | undefined=} encoding encoding + */ + +/** + * @typedef {ObjectEncodingOptions | BufferEncoding | undefined | null} EncodingOption + */ + +/** @typedef {(err: NodeJS.ErrnoException | null, result?: string) => void} StringCallback */ +/** @typedef {(err: NodeJS.ErrnoException | null, result?: Buffer) => void} BufferCallback */ +/** @typedef {(err: NodeJS.ErrnoException | null, result?: (string | Buffer)) => void} StringOrBufferCallback */ +/** @typedef {(err: NodeJS.ErrnoException | null, result?: IStats) => void} StatsCallback */ +/** @typedef {(err: NodeJS.ErrnoException | null, result?: IBigIntStats) => void} BigIntStatsCallback */ +/** @typedef {(err: NodeJS.ErrnoException | null, result?: (IStats | IBigIntStats)) => void} StatsOrBigIntStatsCallback */ +/** @typedef {(err: NodeJS.ErrnoException | Error | null, result?: JsonObject) => void} ReadJsonCallback */ + +/** + * @template T + * @typedef {object} IStatsBase + * @property {() => boolean} isFile is file + * @property {() => boolean} isDirectory is directory + * @property {() => boolean} isBlockDevice is block device + * @property {() => boolean} isCharacterDevice is character device + * @property {() => boolean} isSymbolicLink is symbolic link + * @property {() => boolean} isFIFO is FIFO + * @property {() => boolean} isSocket is socket + * @property {T} dev dev + * @property {T} ino ino + * @property {T} mode mode + * @property {T} nlink nlink + * @property {T} uid uid + * @property {T} gid gid + * @property {T} rdev rdev + * @property {T} size size + * @property {T} blksize blksize + * @property {T} blocks blocks + * @property {T} atimeMs atime ms + * @property {T} mtimeMs mtime ms + * @property {T} ctimeMs ctime ms + * @property {T} birthtimeMs birthtime ms + * @property {Date} atime atime + * @property {Date} mtime mtime + * @property {Date} ctime ctime + * @property {Date} birthtime birthtime + */ + +/** + * @typedef {IStatsBase} IStats + */ + +/** + * @typedef {IStatsBase & { atimeNs: bigint, mtimeNs: bigint, ctimeNs: bigint, birthtimeNs: bigint }} IBigIntStats + */ + +/** + * @template {string | Buffer} [T=string] + * @typedef {object} Dirent + * @property {() => boolean} isFile true when is file, otherwise false + * @property {() => boolean} isDirectory true when is directory, otherwise false + * @property {() => boolean} isBlockDevice true when is block device, otherwise false + * @property {() => boolean} isCharacterDevice true when is character device, otherwise false + * @property {() => boolean} isSymbolicLink true when is symbolic link, otherwise false + * @property {() => boolean} isFIFO true when is FIFO, otherwise false + * @property {() => boolean} isSocket true when is socket, otherwise false + * @property {T} name name + * @property {string} parentPath path + * @property {string=} path path + */ + +/** + * @typedef {object} StatOptions + * @property {(boolean | undefined)=} bigint need bigint values + */ + +/** + * @typedef {object} StatSyncOptions + * @property {(boolean | undefined)=} bigint need bigint values + * @property {(boolean | undefined)=} throwIfNoEntry throw if no entry + */ + +/** + * @typedef {{ + * (path: PathOrFileDescriptor, options: ({ encoding?: null | undefined, flag?: string | undefined } & import("events").Abortable) | undefined | null, callback: BufferCallback): void, + * (path: PathOrFileDescriptor, options: ({ encoding: BufferEncoding, flag?: string | undefined } & import("events").Abortable) | BufferEncoding, callback: StringCallback): void, + * (path: PathOrFileDescriptor, options: (ObjectEncodingOptions & { flag?: string | undefined } & import("events").Abortable) | BufferEncoding | undefined | null, callback: StringOrBufferCallback): void, + * (path: PathOrFileDescriptor, callback: BufferCallback): void, + * }} ReadFile + */ + +/** + * @typedef {"buffer" | { encoding: "buffer" }} BufferEncodingOption + */ + +/** + * @typedef {{ + * (path: PathOrFileDescriptor, options?: { encoding?: null | undefined, flag?: string | undefined } | null): Buffer, + * (path: PathOrFileDescriptor, options: { encoding: BufferEncoding, flag?: string | undefined } | BufferEncoding): string, + * (path: PathOrFileDescriptor, options: ObjectEncodingOptions & { flag?: string | undefined }): string | Buffer, + * }} ReadFileSync + */ + +/** + * @typedef {{ + * (path: PathLike, options: { encoding: BufferEncoding | null, withFileTypes?: false | undefined, recursive?: boolean | undefined } | BufferEncoding | undefined | null, callback: (err: NodeJS.ErrnoException | null, files?: string[]) => void): void, + * (path: PathLike, options: { encoding: "buffer", withFileTypes?: false | undefined, recursive?: boolean | undefined } | "buffer", callback: (err: NodeJS.ErrnoException | null, files?: Buffer[]) => void): void, + * (path: PathLike, options: (ObjectEncodingOptions & { withFileTypes?: false | undefined, recursive?: boolean | undefined }) | BufferEncoding | undefined | null, callback: (err: NodeJS.ErrnoException | null, files?: string[] | Buffer[]) => void): void, + * (path: PathLike, callback: (err: NodeJS.ErrnoException | null, files?: string[]) => void): void, + * (path: PathLike, options: ObjectEncodingOptions & { withFileTypes: true, recursive?: boolean | undefined }, callback: (err: NodeJS.ErrnoException | null, files?: Dirent[]) => void): void, + * (path: PathLike, options: { encoding: "buffer", withFileTypes: true, recursive?: boolean | undefined }, callback: (err: NodeJS.ErrnoException | null, files: Dirent[]) => void): void, + * }} Readdir + */ + +/** + * @typedef {{ + * (path: PathLike, options?: { encoding: BufferEncoding | null, withFileTypes?: false | undefined, recursive?: boolean | undefined } | BufferEncoding | null): string[], + * (path: PathLike, options: { encoding: "buffer", withFileTypes?: false | undefined, recursive?: boolean | undefined } | "buffer"): Buffer[], + * (path: PathLike, options?: (ObjectEncodingOptions & { withFileTypes?: false | undefined, recursive?: boolean | undefined }) | BufferEncoding | null): string[] | Buffer[], + * (path: PathLike, options: ObjectEncodingOptions & { withFileTypes: true, recursive?: boolean | undefined }): Dirent[], + * (path: PathLike, options: { encoding: "buffer", withFileTypes: true, recursive?: boolean | undefined }): Dirent[], + * }} ReaddirSync + */ + +/** + * @typedef {(pathOrFileDescription: PathOrFileDescriptor, callback: ReadJsonCallback) => void} ReadJson + */ + +/** + * @typedef {(pathOrFileDescription: PathOrFileDescriptor) => JsonObject} ReadJsonSync + */ + +/** + * @typedef {{ + * (path: PathLike, options: EncodingOption, callback: StringCallback): void, + * (path: PathLike, options: BufferEncodingOption, callback: BufferCallback): void, + * (path: PathLike, options: EncodingOption, callback: StringOrBufferCallback): void, + * (path: PathLike, callback: StringCallback): void, + * }} Readlink + */ + +/** + * @typedef {{ + * (path: PathLike, options?: EncodingOption): string, + * (path: PathLike, options: BufferEncodingOption): Buffer, + * (path: PathLike, options?: EncodingOption): string | Buffer, + * }} ReadlinkSync + */ + +/** + * @typedef {{ + * (path: PathLike, callback: StatsCallback): void, + * (path: PathLike, options: (StatOptions & { bigint?: false | undefined }) | undefined, callback: StatsCallback): void, + * (path: PathLike, options: StatOptions & { bigint: true }, callback: BigIntStatsCallback): void, + * (path: PathLike, options: StatOptions | undefined, callback: StatsOrBigIntStatsCallback): void, + * }} LStat + */ + +/** + * @typedef {{ + * (path: PathLike, options?: undefined): IStats, + * (path: PathLike, options?: StatSyncOptions & { bigint?: false | undefined, throwIfNoEntry: false }): IStats | undefined, + * (path: PathLike, options: StatSyncOptions & { bigint: true, throwIfNoEntry: false }): IBigIntStats | undefined, + * (path: PathLike, options?: StatSyncOptions & { bigint?: false | undefined, throwIfNoEntry?: true | undefined }): IStats, + * (path: PathLike, options: StatSyncOptions & { bigint: true, throwIfNoEntry?: true | undefined }): IBigIntStats, + * (path: PathLike, options: StatSyncOptions & { bigint: boolean, throwIfNoEntry?: undefined }): IStats | IBigIntStats, + * (path: PathLike, options?: StatSyncOptions): IStats | IBigIntStats | undefined, + * }} LStatSync + */ + +/** + * @typedef {{ + * (path: PathLike, callback: StatsCallback): void, + * (path: PathLike, options: (StatOptions & { bigint?: false | undefined }) | undefined, callback: StatsCallback): void, + * (path: PathLike, options: StatOptions & { bigint: true }, callback: BigIntStatsCallback): void, + * (path: PathLike, options: StatOptions | undefined, callback: StatsOrBigIntStatsCallback): void, + * }} Stat + */ + +/** + * @typedef {{ + * (path: PathLike, options?: undefined): IStats, + * (path: PathLike, options?: StatSyncOptions & { bigint?: false | undefined, throwIfNoEntry: false }): IStats | undefined, + * (path: PathLike, options: StatSyncOptions & { bigint: true, throwIfNoEntry: false }): IBigIntStats | undefined, + * (path: PathLike, options?: StatSyncOptions & { bigint?: false | undefined, throwIfNoEntry?: true | undefined }): IStats, + * (path: PathLike, options: StatSyncOptions & { bigint: true, throwIfNoEntry?: true | undefined }): IBigIntStats, + * (path: PathLike, options: StatSyncOptions & { bigint: boolean, throwIfNoEntry?: undefined }): IStats | IBigIntStats, + * (path: PathLike, options?: StatSyncOptions): IStats | IBigIntStats | undefined, + * }} StatSync + */ + +/** + * @typedef {{ + * (path: PathLike, options: EncodingOption, callback: StringCallback): void, + * (path: PathLike, options: BufferEncodingOption, callback: BufferCallback): void, + * (path: PathLike, options: EncodingOption, callback: StringOrBufferCallback): void, + * (path: PathLike, callback: StringCallback): void, + * }} RealPath + */ + +/** + * @typedef {{ + * (path: PathLike, options?: EncodingOption): string, + * (path: PathLike, options: BufferEncodingOption): Buffer, + * (path: PathLike, options?: EncodingOption): string | Buffer, + * }} RealPathSync + */ + +/** + * @typedef {object} FileSystem + * @property {ReadFile} readFile read file method + * @property {Readdir} readdir readdir method + * @property {ReadJson=} readJson read json method + * @property {Readlink} readlink read link method + * @property {LStat=} lstat lstat method + * @property {Stat} stat stat method + * @property {RealPath=} realpath realpath method + */ + +/** + * @typedef {object} SyncFileSystem + * @property {ReadFileSync} readFileSync read file sync method + * @property {ReaddirSync} readdirSync read dir sync method + * @property {ReadJsonSync=} readJsonSync read json sync method + * @property {ReadlinkSync} readlinkSync read link sync method + * @property {LStatSync=} lstatSync lstat sync method + * @property {StatSync} statSync stat sync method + * @property {RealPathSync=} realpathSync real path sync method + */ + +/** + * @typedef {object} ParsedIdentifier + * @property {string} request request + * @property {string} query query + * @property {string} fragment fragment + * @property {boolean} directory is directory + * @property {boolean} module is module + * @property {boolean} file is file + * @property {boolean} internal is internal + */ + +/** @typedef {string | number | boolean | null} JsonPrimitive */ +/** @typedef {JsonValue[]} JsonArray */ +/** @typedef {JsonPrimitive | JsonObject | JsonArray} JsonValue */ +/** @typedef {{ [Key in string]?: JsonValue | undefined }} JsonObject */ + +/** + * @typedef {object} TsconfigPathsMap + * @property {TsconfigPathsData} main main tsconfig paths data + * @property {string} mainContext main tsconfig base URL (absolute path) + * @property {{ [baseUrl: string]: TsconfigPathsData }} refs referenced tsconfig paths data mapped by baseUrl + * @property {{ [context: string]: TsconfigPathsData }} allContexts all contexts (main + refs) for quick lookup + * @property {string[]} contextList precomputed `Object.keys(allContexts)` — read-only; used on the `_selectPathsDataForContext` hot path + * @property {Set} fileDependencies file dependencies + */ + +/** + * @typedef {object} TsconfigPathsData + * @property {import("./AliasUtils").CompiledAliasOptions} alias tsconfig file data + * @property {string[]} modules tsconfig file data + */ + +/** + * @typedef {object} BaseResolveRequest + * @property {string | false} path path + * @property {Context=} context content + * @property {string=} descriptionFilePath description file path + * @property {string=} descriptionFileRoot description file root + * @property {JsonObject=} descriptionFileData description file data + * @property {TsconfigPathsMap | null | undefined=} tsconfigPathsMap tsconfig paths map + * @property {string=} relativePath relative path + * @property {boolean=} ignoreSymlinks true when need to ignore symlinks, otherwise false + * @property {boolean=} fullySpecified true when full specified, otherwise false + * @property {string=} packageId package id the request was resolved to in the package map, to be propagated to resolutions made from the resulting file (`@experimental`, see the `packageMap` option) + * @property {string=} __innerRequest inner request for internal usage + * @property {string=} __innerRequest_request inner request for internal usage + * @property {string=} __innerRequest_relativePath inner relative path for internal usage + * @property {{ blocked: boolean }=} __restrictionsMarker internal: shared marker `RestrictionsPlugin` flips when it filters out an existing target, letting `ExportsFieldPlugin` fall back instead of erroring + */ + +/** @typedef {BaseResolveRequest & Partial} ResolveRequest */ + +/** + * @template T + * @typedef {{ add: (item: T) => void }} WriteOnlySet + */ + +/** @typedef {(request: ResolveRequest) => void} ResolveContextYield */ + +/** + * Singly-linked stack entry that also exposes a Set-like API + * (`has`, `size`, iteration). Each `doResolve` call prepends a new + * `StackEntry` that points at the previous tip via `.parent`, so pushing + * is O(1) in time and memory. Recursion detection walks the linked list + * (O(n)) but the stack is typically shallow, so this is cheaper overall + * than cloning a `Set` per call. + */ +class StackEntry { + /** + * @param {ResolveStepHook} hook hook + * @param {ResolveRequest} request request + * @param {StackEntry=} parent previous tip + * @param {Set=} preSeeded entries pre-seeded via the legacy `Set` API + */ + constructor(hook, request, parent, preSeeded) { + this.name = hook.name; + this.path = request.path; + this.request = request.request || ""; + this.query = request.query || ""; + this.fragment = request.fragment || ""; + this.directory = Boolean(request.directory); + this.module = Boolean(request.module); + /** @type {StackEntry | undefined} */ + this.parent = parent; + /** + * Strings seeded by callers that still pass `stack: new Set([...])`. + * Propagated through the chain so deeper `doResolve` calls still see + * them during recursion checks. `undefined` in the common case so + * there is no extra work on the hot path. + * @type {Set | undefined} + */ + this.preSeeded = preSeeded; + } + + /** + * Walk the linked list looking for an entry with the same request shape. + * Set-compatible: callers that used `stack.has(entry)` keep working. + * + * NOTE: kept monomorphic on purpose. An earlier draft accepted a string + * query too (so pre-5.21 plugins keeping their own `Set` of + * seen entries could probe the live stack with the formatted form), + * but adding the second shape regressed `doResolve`'s heap profile by + * ~1 MiB / 200 resolves on stack-churn — V8 keeps a polymorphic + * call-site state for `parent.has(stackEntry)` once `has` has two + * argument shapes. Plugins that need string membership can reach for + * `[...stack].find(e => e.includes(formattedString))` via the + * `String`-method proxies on `StackEntry` instead. + * @param {StackEntry} query entry to look for + * @returns {boolean} whether the stack already contains an equivalent entry + */ + has(query) { + /** @type {StackEntry | undefined} */ + let node = this; + while (node) { + if ( + node.name === query.name && + node.path === query.path && + node.request === query.request && + node.query === query.query && + node.fragment === query.fragment && + node.directory === query.directory && + node.module === query.module + ) { + return true; + } + node = node.parent; + } + return this.preSeeded !== undefined && this.preSeeded.has(query.toString()); + } + + /** + * Number of entries on the stack (oldest-to-newest length). + * @returns {number} size + */ + get size() { + let count = this.preSeeded ? this.preSeeded.size : 0; + /** @type {StackEntry | undefined} */ + let node = this; + while (node) { + count++; + node = node.parent; + } + return count; + } + + /** + * Iterate entries from oldest (root) to newest (tip), matching how a + * `Set` that was populated in insertion order would iterate. Pre-seeded + * legacy `Set` entries come first so error-message output stays + * ordered oldest-to-newest. + * + * Yields each entry as its formatted `toString()` form. Plugins written + * against the pre-5.21 `Set` shape — e.g. + * `[...resolveContext.stack].find(a => a.includes("module:"))` — keep + * working unchanged because each yielded value is a plain string with + * all of `String.prototype` available natively. Resolves that never + * iterate the stack pay nothing; iteration costs one `toString()` + * allocation per stack frame. + * @returns {IterableIterator} iterator + */ + *[Symbol.iterator]() { + if (this.preSeeded !== undefined) { + for (const entry of this.preSeeded) yield entry; + } + /** @type {StackEntry[]} */ + const entries = []; + /** @type {StackEntry | undefined} */ + let node = this; + while (node) { + entries.push(node); + node = node.parent; + } + for (let i = entries.length - 1; i >= 0; i--) yield entries[i].toString(); + } + + /** + * Human-readable form used in recursion error messages, logs, and the + * iterator above. Not memoized: caching would require an extra slot on + * every `StackEntry`, which costs heap even on resolves that never look + * at the formatted form. + * @returns {string} formatted entry + */ + toString() { + return `${this.name}: (${this.path}) ${this.request}${this.query}${ + this.fragment + }${this.directory ? " directory" : ""}${this.module ? " module" : ""}`; + } +} + +/** + * Resolve context + * @typedef {object} ResolveContext + * @property {WriteOnlySet=} contextDependencies directories that was found on file system + * @property {WriteOnlySet=} fileDependencies files that was found on file system + * @property {WriteOnlySet=} missingDependencies dependencies that was not found on file system + * @property {StackEntry | Set=} stack tip of the resolver call stack (a singly-linked list with Set-like API). For instance, `resolve → parsedResolve → describedResolve`. Accepts a legacy `Set` for back-compat with older callers; it is normalized internally without a hot-path branch. + * @property {((str: string) => void)=} log log function + * @property {ResolveContextYield=} yield yield result, if provided plugins can return several results + */ + +/** @typedef {AsyncSeriesBailHook<[ResolveRequest, ResolveContext], ResolveRequest | null>} ResolveStepHook */ + +/** + * @typedef {object} KnownHooks + * @property {SyncHook<[ResolveStepHook, ResolveRequest], void>} resolveStep resolve step hook + * @property {SyncHook<[ResolveRequest, Error]>} noResolve no resolve hook + * @property {ResolveStepHook} resolve resolve hook + * @property {AsyncSeriesHook<[ResolveRequest, ResolveContext]>} result result hook + */ + +/** + * @typedef {{ [key: string]: ResolveStepHook }} EnsuredHooks + */ + +/** + * @param {string} str input string + * @returns {string} in camel case + */ +function toCamelCase(str) { + return str.replace(/-([a-z])/g, (str) => str.slice(1).toUpperCase()); +} + +class Resolver { + /** + * @param {ResolveStepHook} hook hook + * @param {ResolveRequest} request request + * @param {StackEntry=} parent previous tip of the stack + * @param {Set=} preSeeded entries pre-seeded via the legacy `Set` API + * @returns {StackEntry} stack entry + */ + static createStackEntry(hook, request, parent, preSeeded) { + return new StackEntry(hook, request, parent, preSeeded); + } + + /** + * @param {FileSystem} fileSystem a filesystem + * @param {ResolveOptions} options options + */ + constructor(fileSystem, options) { + /** @type {FileSystem} */ + this.fileSystem = fileSystem; + /** @type {ResolveOptions} */ + this.options = options; + let pathCache = _pathCacheByFs.get(fileSystem); + if (!pathCache) { + pathCache = { + join: createCachedJoin(), + dirname: createCachedDirname(), + basename: createCachedBasename(), + }; + _pathCacheByFs.set(fileSystem, pathCache); + } + /** @type {PathCacheFunctions} */ + this.pathCache = pathCache; + /** @type {KnownHooks} */ + this.hooks = { + resolveStep: new SyncHook(["hook", "request"], "resolveStep"), + noResolve: new SyncHook(["request", "error"], "noResolve"), + resolve: new AsyncSeriesBailHook( + ["request", "resolveContext"], + "resolve", + ), + result: new AsyncSeriesHook(["result", "resolveContext"], "result"), + }; + } + + /** + * @param {string | ResolveStepHook} name hook name or hook itself + * @returns {ResolveStepHook} the hook + */ + ensureHook(name) { + if (typeof name !== "string") { + return name; + } + name = toCamelCase(name); + if (name.startsWith("before")) { + return /** @type {ResolveStepHook} */ ( + this.ensureHook(name[6].toLowerCase() + name.slice(7)).withOptions({ + stage: -10, + }) + ); + } + if (name.startsWith("after")) { + return /** @type {ResolveStepHook} */ ( + this.ensureHook(name[5].toLowerCase() + name.slice(6)).withOptions({ + stage: 10, + }) + ); + } + /** @type {ResolveStepHook} */ + const hook = /** @type {KnownHooks & EnsuredHooks} */ (this.hooks)[name]; + if (!hook) { + /** @type {KnownHooks & EnsuredHooks} */ + (this.hooks)[name] = new AsyncSeriesBailHook( + ["request", "resolveContext"], + name, + ); + + return /** @type {KnownHooks & EnsuredHooks} */ (this.hooks)[name]; + } + return hook; + } + + /** + * @param {string | ResolveStepHook} name hook name or hook itself + * @returns {ResolveStepHook} the hook + */ + getHook(name) { + if (typeof name !== "string") { + return name; + } + name = toCamelCase(name); + if (name.startsWith("before")) { + return /** @type {ResolveStepHook} */ ( + this.getHook(name[6].toLowerCase() + name.slice(7)).withOptions({ + stage: -10, + }) + ); + } + if (name.startsWith("after")) { + return /** @type {ResolveStepHook} */ ( + this.getHook(name[5].toLowerCase() + name.slice(6)).withOptions({ + stage: 10, + }) + ); + } + /** @type {ResolveStepHook} */ + const hook = /** @type {KnownHooks & EnsuredHooks} */ (this.hooks)[name]; + if (!hook) { + throw new Error(`Hook ${name} doesn't exist`); + } + return hook; + } + + /** + * @overload + * @param {string | URL} parent context path or a `file:` URL + * @param {string | URL} specifier request string or a `file:` URL + * @param {ResolveContext=} resolveContext resolve context + * @returns {string | false} result + */ + /** + * @overload + * @param {Context} context context information object + * @param {string | URL} parent context path or a `file:` URL + * @param {string | URL} specifier request string or a `file:` URL + * @param {ResolveContext=} resolveContext resolve context + * @returns {string | false} result + */ + /** + * @param {Context | string | URL} context context information object, or the context path (a path or a `file:` URL) when no context is provided + * @param {string | URL | ResolveContext=} parent context path (a path or a `file:` URL) or resolve context when no context is provided + * @param {string | URL | ResolveContext=} specifier request string (or a `file:` URL) or resolve context when no context is provided + * @param {ResolveContext=} resolveContext resolve context + * @returns {string | false} result + */ + resolveSync(context, parent, specifier, resolveContext) { + /** @type {Error | null | undefined} */ + let err; + /** @type {string | false | undefined} */ + let result; + let sync = false; + // `|| {}` so the underlying `resolve()` hits its 5-arg fast path + // (skips the overload-shifting prologue) regardless of whether the + // caller supplied a resolveContext. + this.resolve( + /** @type {Context} */ (context), + /** @type {string} */ (parent), + /** @type {string} */ (specifier), + /** @type {ResolveContext} */ (resolveContext) || {}, + (_err, r) => { + err = _err; + result = r; + sync = true; + }, + ); + if (!sync) { + throw new Error( + "Cannot 'resolveSync' because the fileSystem is not sync. Use 'resolve'!", + ); + } + if (err) throw err; + if (result === undefined) throw new Error("No result"); + return result; + } + + /** + * @overload + * @param {string | URL} parent context path or a `file:` URL + * @param {string | URL} specifier request string or a `file:` URL + * @param {ResolveContext=} resolveContext resolve context + * @returns {Promise} result + */ + /** + * @overload + * @param {Context} context context information object + * @param {string | URL} parent context path or a `file:` URL + * @param {string | URL} specifier request string or a `file:` URL + * @param {ResolveContext=} resolveContext resolve context + * @returns {Promise} result + */ + /** + * @param {Context | string | URL} context context information object, or the context path (a path or a `file:` URL) when no context is provided + * @param {string | URL | ResolveContext=} parent context path (a path or a `file:` URL) or resolve context when no context is provided + * @param {string | URL | ResolveContext=} specifier request string (or a `file:` URL) or resolve context when no context is provided + * @param {ResolveContext=} resolveContext resolve context + * @returns {Promise} result + */ + resolvePromise(context, parent, specifier, resolveContext) { + // `|| {}` ensures the 5-arg fast path inside `resolve()` is reached + // even when the caller doesn't pass a resolveContext. + return _withResolvers( + this, + /** @type {Context} */ (context), + /** @type {string} */ (parent), + /** @type {string} */ (specifier), + /** @type {ResolveContext} */ (resolveContext) || {}, + ); + } + + /** + * @overload + * @param {string | URL} parent context path or a `file:` URL + * @param {string | URL} specifier request string or a `file:` URL + * @param {ResolveCallback} callback callback function + * @returns {void} + */ + /** + * @overload + * @param {string | URL} parent context path or a `file:` URL + * @param {string | URL} specifier request string or a `file:` URL + * @param {ResolveContext} resolveContext resolve context + * @param {ResolveCallback} callback callback function + * @returns {void} + */ + /** + * @overload + * @param {Context} context context information object + * @param {string | URL} parent context path or a `file:` URL + * @param {string | URL} specifier request string or a `file:` URL + * @param {ResolveCallback} callback callback function + * @returns {void} + */ + /** + * @overload + * @param {Context} context context information object + * @param {string | URL} parent context path or a `file:` URL + * @param {string | URL} specifier request string or a `file:` URL + * @param {ResolveContext} resolveContext resolve context + * @param {ResolveCallback} callback callback function + * @returns {void} + */ + /** + * @param {Context | string | URL} context context information object, or the context path (a path or a `file:` URL) when no context is provided + * @param {string | URL | ResolveContext | ResolveCallback=} parent context path (a path or a `file:` URL) or (when no context) resolve context or callback + * @param {string | URL | ResolveContext | ResolveCallback=} specifier request string (or a `file:` URL) or (when no context) resolve context or callback + * @param {ResolveContext | ResolveCallback=} resolveContext resolve context or callback when no resolve context is provided + * @param {ResolveCallback=} callback callback function + * @returns {void} + */ + resolve(context, parent, specifier, resolveContext, callback) { + // Fast path for the common 5-arg call (`resolver.resolve(ctx, from, + // req, resolveCtx, cb)`) — every call from `resolveSync` / + // `resolvePromise` plus the vast majority of direct API callers. + // PR #536 added runtime overload-shifting to support optional + // `context` / `resolveContext`; that adds several `typeof` checks + // per resolve which show up as a measurable instruction-count + // regression on every benchmark that calls into this method. Skip + // the shifting entirely when all 5 args are already well-typed. + if ( + typeof callback === "function" && + typeof context === "object" && + context !== null && + typeof resolveContext === "object" && + resolveContext !== null + ) { + // proceed straight to per-arg validation below + } else { + // Slow path: shift positional args based on what was supplied. + // Shift when context is omitted (first positional arg is the parent, + // either a path or a `file:` URL). + if (typeof context === "string" || context instanceof URL) { + // Keep an already-supplied callback (resolveSync / resolvePromise + // always pass one in the 5th position). + if (typeof callback !== "function") { + callback = /** @type {ResolveCallback | undefined} */ ( + resolveContext + ); + } + resolveContext = + /** @type {ResolveContext | ResolveCallback | undefined} */ ( + specifier + ); + specifier = /** @type {string} */ (parent); + parent = context; + context = {}; + } + // 4-arg form: the resolveContext slot holds the callback. + if (typeof resolveContext === "function") { + callback = resolveContext; + resolveContext = {}; + } else if (!resolveContext || typeof resolveContext !== "object") { + resolveContext = {}; + } + if (typeof callback !== "function") { + throw new TypeError("callback argument is not a function"); + } + if (!context || typeof context !== "object") { + context = {}; + } + } + // Accept `file:` URLs for parent/specifier, converting to a filesystem + // path (mirrors the URL support in resolve options). The `instanceof` + // check sits on the error branch and `isFileURL` reads one character of + // a path, so the common string case stays cheap on this hot path. + // A `file:` specifier string needs nothing here — `parseIdentifier` + // converts it once the request is parsed. + if (typeof parent !== "string") { + if (parent instanceof URL) parent = toPath(parent); + else return callback(new Error("path argument is not a string")); + } else if (isFileURL(parent)) { + parent = toPath(parent); + } + if (typeof specifier !== "string") { + if (specifier instanceof URL) specifier = toPath(specifier); + else return callback(new Error("request argument is not a string")); + } + + /** @type {ResolveRequest} */ + const obj = { + context, + path: parent, + request: specifier, + }; + + /** @type {ResolveContextYield | undefined} */ + let yield_; + let yieldCalled = false; + /** @type {ResolveContextYield | undefined} */ + let finishYield; + if (typeof resolveContext.yield === "function") { + const old = resolveContext.yield; + /** + * @param {ResolveRequest} obj object + */ + yield_ = (obj) => { + old(obj); + yieldCalled = true; + }; + /** + * @param {ResolveRequest} result result + * @returns {void} + */ + finishYield = (result) => { + if (result) { + /** @type {ResolveContextYield} */ (yield_)(result); + } + callback(null); + }; + } + + /** + * @param {ResolveRequest} result result + * @returns {void} + */ + const finishResolved = (result) => { + const resultPath = result.path; + if (resultPath === false) return callback(null, false, result); + const escapedPath = resultPath.includes("#") + ? resultPath.replace(HASH_ESCAPE_RE, "\0#") + : resultPath; + const resultQuery = result.query; + let escapedQuery; + if (resultQuery) { + escapedQuery = resultQuery.includes("#") + ? resultQuery.replace(HASH_ESCAPE_RE, "\0#") + : resultQuery; + } else { + escapedQuery = ""; + } + return callback( + null, + `${escapedPath}${escapedQuery}${result.fragment || ""}`, + result, + ); + }; + + /** + * @param {string} message resolve message + * @param {string[]} log logs + * @returns {void} + */ + const finishWithoutResolve = (message, log) => { + /** + * @type {ErrorWithDetail} + */ + const error = new Error(`Can't ${message}`); + error.details = log.join("\n"); + this.hooks.noResolve.call(obj, error); + return callback(error); + }; + + if (resolveContext.log) { + const message = `resolve '${specifier}' in '${parent}'`; + // We need log anyway to capture it in case of an error + const parentLog = resolveContext.log; + /** @type {string[]} */ + const log = []; + return this.doResolve( + this.hooks.resolve, + obj, + message, + { + log: (msg) => { + parentLog(msg); + log.push(msg); + }, + yield: yield_, + fileDependencies: resolveContext.fileDependencies, + contextDependencies: resolveContext.contextDependencies, + missingDependencies: resolveContext.missingDependencies, + stack: resolveContext.stack, + }, + (err, result) => { + if (err) return callback(err); + + if (yieldCalled || (result && yield_)) { + return /** @type {ResolveContextYield} */ (finishYield)( + /** @type {ResolveRequest} */ (result), + ); + } + + if (result) return finishResolved(result); + + return finishWithoutResolve(message, log); + }, + ); + } + // Try to resolve assuming there is no error + // We don't log stuff in this case + // When there is no yield wrapper, the caller's resolveContext can + // be passed directly — its `log` is already falsy (we are in the + // !log branch) and `yield` is undefined, so a fresh wrapper would + // be an identical copy. + const rc = yield_ + ? { + log: undefined, + yield: yield_, + fileDependencies: resolveContext.fileDependencies, + contextDependencies: resolveContext.contextDependencies, + missingDependencies: resolveContext.missingDependencies, + stack: resolveContext.stack, + } + : resolveContext; + return this.doResolve(this.hooks.resolve, obj, null, rc, (err, result) => { + if (err) return callback(err); + + if (yieldCalled || (result && yield_)) { + return /** @type {ResolveContextYield} */ (finishYield)( + /** @type {ResolveRequest} */ (result), + ); + } + + if (result) return finishResolved(result); + + // log is missing for the error details + // so we redo the resolving for the log info + // this is more expensive to the success case + // is assumed by default + const message = `resolve '${specifier}' in '${parent}'`; + /** @type {string[]} */ + const log = []; + + return this.doResolve( + this.hooks.resolve, + obj, + message, + { + log: (msg) => log.push(msg), + yield: yield_, + stack: resolveContext.stack, + }, + (err, result) => { + if (err) return callback(err); + + // In a case that there is a race condition and yield will be called + if (yieldCalled || (result && yield_)) { + return /** @type {ResolveContextYield} */ (finishYield)( + /** @type {ResolveRequest} */ (result), + ); + } + + return finishWithoutResolve(message, log); + }, + ); + }); + } + + /** + * @param {ResolveStepHook} hook hook + * @param {ResolveRequest} request request + * @param {null | string} message string + * @param {ResolveContext} resolveContext resolver context + * @param {(err?: null | Error, result?: ResolveRequest) => void} callback callback + * @returns {void} + */ + doResolve(hook, request, message, resolveContext, callback) { + const rawStack = resolveContext.stack; + /** @type {StackEntry | undefined} */ + let parent; + /** @type {Set | undefined} */ + let preSeeded; + if (rawStack instanceof StackEntry) { + parent = rawStack; + preSeeded = rawStack.preSeeded; + } else if (rawStack) { + // TODO in the next major remove `Set` support in favor of `StackEntry` + // Legacy `stack: new Set()` API: don't link the Set into + // the parent chain (it would pollute iteration and field-compare + // walks). Carry the strings on the StackEntry itself instead so + // deeper `doResolve` calls keep seeing pre-seeded entries. + preSeeded = /** @type {Set} */ (rawStack); + } + // Prepend a new linked-list node. O(1) allocation, no Set clone. + const stackEntry = Resolver.createStackEntry( + hook, + request, + parent, + preSeeded, + ); + + // When `parent` exists, its `has()` already consults `preSeeded` + // (inherited from the same chain), so we only need the direct Set + // lookup on the very first `doResolve` call (no parent yet). + if ( + parent !== undefined + ? parent.has(stackEntry) + : preSeeded !== undefined && preSeeded.has(stackEntry.toString()) + ) { + /** + * Prevent recursion + * @type {Error & { recursion?: boolean }} + */ + const recursionError = new Error( + `Recursion in resolving\nStack:\n ${[...stackEntry].join("\n ")}`, + ); + recursionError.recursion = true; + if (resolveContext.log) { + resolveContext.log("abort resolving because of recursion"); + } + return callback(recursionError); + } + this.hooks.resolveStep.call(hook, request); + + if (hook.isUsed()) { + // No-log fast path: when the context was created internally + // (stack is already a StackEntry from a prior doResolve), we + // can mutate stack in-place and restore it in the callback, + // avoiding the createInnerContext allocation entirely. + if (!resolveContext.log && rawStack instanceof StackEntry) { + resolveContext.stack = stackEntry; + return hook.callAsync(request, resolveContext, (err, result) => { + resolveContext.stack = rawStack; + if (err) return callback(err); + if (result) return callback(null, result); + callback(); + }); + } + const innerContext = createInnerContext( + resolveContext, + stackEntry, + message, + ); + return hook.callAsync(request, innerContext, (err, result) => { + if (err) return callback(err); + if (result) return callback(null, result); + callback(); + }); + } + callback(); + } + + /** + * @param {string} identifier identifier + * @returns {ParsedIdentifier} parsed identifier + */ + parse(identifier) { + /** @type {ParsedIdentifier} */ + const part = { + request: "", + query: "", + fragment: "", + module: false, + directory: false, + file: false, + internal: false, + }; + + const parsedIdentifier = parseIdentifier(identifier); + + if (!parsedIdentifier) return part; + + [part.request, part.query, part.fragment] = parsedIdentifier; + + if (part.request.length > 0) { + // `getType` looks at the prefix of its input and the prefix is + // identical between `identifier` and `part.request` in every + // non-`\0`-escape case (slicing off `?query` / `#fragment` doesn't + // touch the head). `parseIdentifier`'s common fast path returns + // the same `identifier` reference as `parsedIdentifier[0]`, so a + // pointer-equality check detects the case where we can compute + // `getType` once and use it for both `module` and `internal`. The + // `\0#…` escape path produces a fresh `part.request` and falls + // through to the second `getType(identifier)` call to preserve + // the original `internal` flag. + const requestType = getType(part.request); + part.module = requestType === PathType.Normal; + part.internal = + identifier === part.request + ? requestType === PathType.Internal + : getType(identifier) === PathType.Internal; + // `isDirectory` is just `endsWith("/")` — inline so `parse()` + // doesn't pay for the extra method dispatch on every resolve. + part.directory = part.request.endsWith("/"); + if (part.directory) { + part.request = part.request.slice(0, -1); + } + } + + return part; + } + + /** + * @param {string} path path + * @returns {boolean} true, if the path is a module + */ + isModule(path) { + return getType(path) === PathType.Normal; + } + + /** + * @param {string} path path + * @returns {boolean} true, if the path is private + */ + isPrivate(path) { + return getType(path) === PathType.Internal; + } + + /** + * @param {string} path a path + * @returns {boolean} true, if the path is a directory path + */ + isDirectory(path) { + return path.endsWith("/"); + } + + /** + * @param {string} path path + * @returns {string} normalized path + */ + normalize(path) { + return normalize(path); + } + + /** + * @param {string} path path + * @param {string} request request + * @returns {string} joined path + */ + join(path, request) { + return this.pathCache.join.fn(path, request); + } + + /** + * @param {string} path path + * @returns {string} parent directory + */ + dirname(path) { + return this.pathCache.dirname.fn(path); + } + + /** + * @param {string} path the path to evaluate + * @param {string=} suffix an extension to remove from the result + * @returns {string} the last portion of a path + */ + basename(path, suffix) { + return this.pathCache.basename.fn(path, suffix); + } +} + +module.exports = Resolver; diff --git a/dg-ui/node_modules/enhanced-resolve/lib/ResolverFactory.js b/dg-ui/node_modules/enhanced-resolve/lib/ResolverFactory.js new file mode 100644 index 0000000..ceed58d --- /dev/null +++ b/dg-ui/node_modules/enhanced-resolve/lib/ResolverFactory.js @@ -0,0 +1,942 @@ +/* + MIT License http://www.opensource.org/licenses/mit-license.php + Author Tobias Koppers @sokra +*/ + +"use strict"; + +// eslint-disable-next-line n/prefer-global/process +const { cwd, versions } = require("process"); + +const AliasFieldPlugin = require("./AliasFieldPlugin"); +const AliasPlugin = require("./AliasPlugin"); +const AppendPlugin = require("./AppendPlugin"); +const ConditionalPlugin = require("./ConditionalPlugin"); +const DescriptionFilePlugin = require("./DescriptionFilePlugin"); +const DirectoryExistsPlugin = require("./DirectoryExistsPlugin"); +const ExportsFieldPlugin = require("./ExportsFieldPlugin"); +const ExtensionAliasPlugin = require("./ExtensionAliasPlugin"); +const FileExistsPlugin = require("./FileExistsPlugin"); +const ImportsFieldPlugin = require("./ImportsFieldPlugin"); +const JoinRequestPartPlugin = require("./JoinRequestPartPlugin"); +const JoinRequestPlugin = require("./JoinRequestPlugin"); +const MainFieldPlugin = require("./MainFieldPlugin"); +const ModulesInHierarchicalDirectoriesPlugin = require("./ModulesInHierarchicalDirectoriesPlugin"); +const ModulesInRootPlugin = require("./ModulesInRootPlugin"); +const NextPlugin = require("./NextPlugin"); +const PackageMapPlugin = require("./PackageMapPlugin"); +const ParsePlugin = require("./ParsePlugin"); +const PnpPlugin = require("./PnpPlugin"); +const Resolver = require("./Resolver"); +const RestrictionsPlugin = require("./RestrictionsPlugin"); +const ResultPlugin = require("./ResultPlugin"); +const RootsPlugin = require("./RootsPlugin"); +const SelfReferencePlugin = require("./SelfReferencePlugin"); +const SymlinkPlugin = require("./SymlinkPlugin"); +const SyncAsyncFileSystemDecorator = require("./SyncAsyncFileSystemDecorator"); +const TryNextPlugin = require("./TryNextPlugin"); +const TsconfigPathsPlugin = require("./TsconfigPathsPlugin"); +const UnsafeCachePlugin = require("./UnsafeCachePlugin"); +const UseFilePlugin = require("./UseFilePlugin"); +const { PathType, getType, join, toPath } = require("./util/path"); + +/** @typedef {import("./AliasPlugin").AliasOption} AliasOptionEntry */ +/** @typedef {import("./ExtensionAliasPlugin").ExtensionAliasOption} ExtensionAliasOption */ +/** @typedef {import("./PackageMapPlugin").PackageMapOptions} PackageMapOptions */ +/** @typedef {import("./util/packageMap").PackageMapPackages} PackageMapPackages */ +/** @typedef {import("./PnpPlugin").PnpApiImpl} PnpApi */ +/** @typedef {import("./Resolver").EnsuredHooks} EnsuredHooks */ +/** @typedef {import("./Resolver").FileSystem} FileSystem */ +/** @typedef {import("./Resolver").KnownHooks} KnownHooks */ +/** @typedef {import("./Resolver").ResolveRequest} ResolveRequest */ +/** @typedef {import("./Resolver").SyncFileSystem} SyncFileSystem */ +/** @typedef {import("./UnsafeCachePlugin").Cache} Cache */ + +/** @typedef {string | string[] | false} AliasOptionNewRequest */ +/** @typedef {{ [k: string]: AliasOptionNewRequest }} AliasOptions */ +/** @typedef {string | URL | (string | URL)[] | false} UserAliasOptionNewRequest */ +/** @typedef {{ [k: string]: UserAliasOptionNewRequest }} UserAliasOptions */ +/** @typedef {{ alias: UserAliasOptionNewRequest, name: string, onlyModule?: boolean }} UserAliasOptionEntry */ +/** @typedef {{ [k: string]: string | string[] }} ExtensionAliasOptions */ +/** @typedef {false | 0 | "" | null | undefined} Falsy */ +/** @typedef {{ apply: (resolver: Resolver) => void } | ((this: Resolver, resolver: Resolver) => void) | Falsy} Plugin */ + +/** + * @typedef {object} TsconfigOptions + * @property {string=} configFile A relative path to the tsconfig file based on cwd, or an absolute path of tsconfig file + * @property {string[] | "auto"=} references References to other tsconfig files. 'auto' inherits from TypeScript config, or an array of relative/absolute paths + * @property {string=} baseUrl Override baseUrl from tsconfig.json. If provided, this value will be used instead of the baseUrl in the tsconfig file + */ + +/** + * @typedef {object} UserTsconfigOptions + * @property {(string | URL)=} configFile A path, or `file:` URL, pointing at the tsconfig file + * @property {((string | URL)[] | "auto")=} references References to other tsconfig files. 'auto' inherits from TypeScript config, or an array of relative/absolute paths or `file:` URLs + * @property {(string | URL)=} baseUrl Override baseUrl from tsconfig.json with a path or `file:` URL + */ + +/** + * A Node.js package map (https://nodejs.org/api/packages.html#package-maps), + * either as the path of the configuration file or as its already-parsed + * contents. + * @experimental Package maps are stability 1 (experimental) in Node.js and are + * only reachable there behind `--experimental-package-map`. This option tracks + * that specification and may change with it, including in a patch release. + * @typedef {object} UserPackageMapOptions + * @property {(string | URL)=} configFile A path, or `file:` `URL` instance, pointing at the package map file. Required together with `packages`, whose relative `url` values are resolved against it + * @property {PackageMapPackages=} packages An already-parsed `packages` object, used instead of reading `configFile` from disk + */ + +/** + * @typedef {object} UserResolveOptions + * @property {(UserAliasOptions | UserAliasOptionEntry[])=} alias A list of module alias configurations or an object which maps key to value + * @property {(UserAliasOptions | UserAliasOptionEntry[])=} fallback A list of module alias configurations or an object which maps key to value, applied only after modules option + * @property {ExtensionAliasOptions=} extensionAlias An object which maps extension to extension aliases + * @property {boolean=} extensionAliasForExports Also apply `extensionAlias` to paths resolved through the package.json `exports` field. Off by default (Node.js-aligned); when enabled, matches TypeScript's behavior for packages that ship TS sources alongside compiled JS. + * @property {(string | string[])[]=} aliasFields A list of alias fields in description files + * @property {((predicate: ResolveRequest) => boolean)=} cachePredicate A function which decides whether a request should be cached or not. An object is passed with at least `path` and `request` properties. + * @property {boolean=} cacheWithContext Whether or not the unsafeCache should include request context as part of the cache key. + * @property {string[]=} descriptionFiles A list of description files to read from + * @property {string[]=} conditionNames A list of exports field condition names. + * @property {boolean=} enforceExtension Enforce that a extension from extensions must be used + * @property {(string | string[])[]=} exportsFields A list of exports fields in description files + * @property {(string | string[])[]=} importsFields A list of imports fields in description files + * @property {string[]=} extensions A list of extensions which should be tried for files + * @property {FileSystem} fileSystem The file system which should be used + * @property {(Cache | boolean)=} unsafeCache Use this cache object to unsafely cache the successful requests + * @property {boolean=} symlinks Resolve symlinks to their symlinked location + * @property {Resolver=} resolver A prepared Resolver to which the plugins are attached + * @property {(string | URL)[] | string | URL=} modules A list of directories to resolve modules from, can be absolute path, folder name, or a `file:` URL + * @property {(string | string[] | { name: string | string[], forceRelative: boolean })[]=} mainFields A list of main fields in description files + * @property {string[]=} mainFiles A list of main files in directories + * @property {Plugin[]=} plugins A list of additional resolve plugins which should be applied + * @property {(string | URL | UserPackageMapOptions)=} packageMap A Node.js package map file path (or `file:` `URL` instance), or an object with the already-parsed `packages`. When set, bare specifiers resolve through the map instead of `node_modules` (`@experimental`) + * @property {PnpApi | null=} pnpApi A PnP API that should be used - null is "never", undefined is "auto" + * @property {(string | URL)[]=} roots A list of root paths, each an absolute path or a `file:` URL + * @property {boolean=} fullySpecified The request is already fully specified and no extensions or directories are resolved for it + * @property {boolean=} resolveToContext Resolve to a context instead of a file + * @property {(string | URL | RegExp)[]=} restrictions A list of resolve restrictions, each an absolute path, a `file:` URL, or a RegExp + * @property {boolean=} useSyncFileSystemCalls Use only the sync constraints of the file system calls + * @property {boolean=} preferRelative Prefer to resolve module requests as relative requests before falling back to modules + * @property {boolean=} preferAbsolute Prefer to resolve server-relative urls as absolute paths before falling back to resolve in roots + * @property {string | URL | boolean | UserTsconfigOptions=} tsconfig TypeScript config file path (or `file:` URL) or config object with configFile and references + */ + +/** + * @typedef {object} ResolveOptions + * @property {AliasOptionEntry[]} alias alias + * @property {AliasOptionEntry[]} fallback fallback + * @property {Set} aliasFields alias fields + * @property {ExtensionAliasOption[]} extensionAlias extension alias + * @property {boolean} extensionAliasForExports apply extension alias to exports field targets + * @property {(predicate: ResolveRequest) => boolean} cachePredicate cache predicate + * @property {boolean} cacheWithContext cache with context + * @property {Set} conditionNames A list of exports field condition names. + * @property {string[]} descriptionFiles description files + * @property {boolean} enforceExtension enforce extension + * @property {Set} exportsFields exports fields + * @property {Set} importsFields imports fields + * @property {Set} extensions extensions + * @property {FileSystem} fileSystem fileSystem + * @property {Cache | false} unsafeCache unsafe cache + * @property {boolean} symlinks symlinks + * @property {Resolver=} resolver resolver + * @property {(string | string[])[]} modules modules + * @property {{ name: string[], forceRelative: boolean }[]} mainFields main fields + * @property {Set} mainFiles main files + * @property {Plugin[]} plugins plugins + * @property {PackageMapOptions | null} packageMap package map + * @property {PnpApi | null} pnpApi pnp API + * @property {Set} roots roots + * @property {boolean} fullySpecified fully specified + * @property {boolean} resolveToContext resolve to context + * @property {Set} restrictions restrictions + * @property {boolean} preferRelative prefer relative + * @property {boolean} preferAbsolute prefer absolute + * @property {string | boolean | TsconfigOptions} tsconfig tsconfig file path or config object + */ + +/** + * @param {PnpApi | null=} option option + * @returns {PnpApi | null} processed option + */ +function processPnpApiOption(option) { + if ( + option === undefined && + /** @type {NodeJS.ProcessVersions & { pnp: string }} */ versions.pnp + ) { + const _findPnpApi = + /** @type {(issuer: string) => PnpApi | null}} */ + ( + // @ts-expect-error maybe nothing + require("module").findPnpApi + ); + + if (_findPnpApi) { + return { + resolveToUnqualified(request, issuer, opts) { + const pnpapi = _findPnpApi(issuer); + + if (!pnpapi) { + // Issuer isn't managed by PnP + return null; + } + + return pnpapi.resolveToUnqualified(request, issuer, opts); + }, + }; + } + } + + return option || null; +} + +/** + * @param {UserAliasOptionNewRequest} alias alias target(s) + * @returns {AliasOptionNewRequest} target(s) with `file:` URLs converted to paths + */ +function toPathAlias(alias) { + if (alias === false) return false; + return Array.isArray(alias) ? alias.map(toPath) : toPath(alias); +} + +/** + * @param {UserAliasOptions | UserAliasOptionEntry[] | undefined} alias alias + * @returns {AliasOptionEntry[]} normalized aliases + */ +function normalizeAlias(alias) { + if (typeof alias === "object" && !Array.isArray(alias) && alias !== null) { + return Object.keys(alias).map((key) => { + /** @type {AliasOptionEntry} */ + const obj = { + name: key, + onlyModule: false, + alias: toPathAlias(alias[key]), + }; + + if (/\$$/.test(key)) { + obj.onlyModule = true; + obj.name = key.slice(0, -1); + } + + return obj; + }); + } + + return alias + ? alias.map((item) => ({ ...item, alias: toPathAlias(item.alias) })) + : []; +} + +/** + * @param {string | URL} configFile the `packageMap` configuration file option + * @returns {string} the absolute path of the configuration file + */ +function toPackageMapConfigFile(configFile) { + const file = toPath(configFile); + const type = getType(file); + + if (type === PathType.AbsolutePosix || type === PathType.AbsoluteWin) { + return file; + } + + // The configuration file is the base every package `url` resolves against, + // so it has to be absolute before it is turned into a URL. Relative paths + // are taken from the working directory, like `tsconfig` — where there is no + // working directory to take them from (the resolver also runs in browsers), + // say so instead of silently resolving against the filesystem root. + if (typeof cwd !== "function") { + throw new Error( + "The 'packageMap' option needs an absolute 'configFile' in an environment without a working directory", + ); + } + + return join(cwd(), file); +} + +/** + * @param {string | URL | UserPackageMapOptions | undefined} packageMap package map option + * @returns {PackageMapOptions | null} normalized package map, or `null` when the option is unset + */ +function normalizePackageMap(packageMap) { + if (packageMap === undefined) return null; + if (typeof packageMap === "string" || packageMap instanceof URL) { + return { configFile: toPackageMapConfigFile(packageMap), packages: null }; + } + + const { configFile, packages } = packageMap; + + // Relative `url` values are resolved against the configuration file, so an + // inline `packages` object still needs to say where it would have lived. + // There is no working directory to fall back on: the resolver runs in + // browsers too. + if (packages !== undefined && configFile === undefined) { + throw new Error( + "The 'packageMap' option needs a 'configFile' next to 'packages' to resolve the package urls against", + ); + } + if (configFile === undefined) { + throw new Error( + "The 'packageMap' option needs either a 'configFile' or 'packages'", + ); + } + + return { + configFile: toPackageMapConfigFile(configFile), + packages: packages === undefined ? null : packages, + }; +} + +/** + * @param {string | URL | boolean | UserTsconfigOptions | undefined} tsconfig tsconfig option + * @returns {string | boolean | TsconfigOptions} normalized tsconfig with `file:` URLs converted to paths + */ +function normalizeTsconfig(tsconfig) { + if (tsconfig === undefined) return false; + if (typeof tsconfig === "boolean") return tsconfig; + if (typeof tsconfig === "string" || tsconfig instanceof URL) { + return toPath(tsconfig); + } + + /** @type {TsconfigOptions} */ + const result = {}; + + if (tsconfig.configFile !== undefined) { + result.configFile = toPath(tsconfig.configFile); + } + if (tsconfig.baseUrl !== undefined) { + result.baseUrl = toPath(tsconfig.baseUrl); + } + if (tsconfig.references !== undefined) { + result.references = Array.isArray(tsconfig.references) + ? tsconfig.references.map(toPath) + : tsconfig.references; + } + + return result; +} + +/** + * Merging filtered elements + * @param {string[]} array source array + * @param {(item: string) => boolean} filter predicate + * @returns {(string | string[])[]} merge result + */ +function mergeFilteredToArray(array, filter) { + /** @type {(string | string[])[]} */ + const result = []; + const set = new Set(array); + + for (const item of set) { + if (filter(item)) { + const lastElement = + result.length > 0 ? result[result.length - 1] : undefined; + if (Array.isArray(lastElement)) { + lastElement.push(item); + } else { + result.push([item]); + } + } else { + result.push(item); + } + } + + return result; +} + +/** + * @param {UserResolveOptions} options input options + * @returns {ResolveOptions} output options + */ +function createOptions(options) { + const mainFieldsSet = new Set(options.mainFields || ["main"]); + /** @type {ResolveOptions["mainFields"]} */ + const mainFields = []; + + for (const item of mainFieldsSet) { + if (typeof item === "string") { + mainFields.push({ + name: [item], + forceRelative: true, + }); + } else if (Array.isArray(item)) { + mainFields.push({ + name: item, + forceRelative: true, + }); + } else { + mainFields.push({ + name: Array.isArray(item.name) ? item.name : [item.name], + forceRelative: item.forceRelative, + }); + } + } + + return { + alias: normalizeAlias(options.alias), + fallback: normalizeAlias(options.fallback), + aliasFields: new Set(options.aliasFields), + cachePredicate: + options.cachePredicate || + function trueFn() { + return true; + }, + cacheWithContext: + typeof options.cacheWithContext !== "undefined" + ? options.cacheWithContext + : true, + exportsFields: new Set(options.exportsFields || ["exports"]), + importsFields: new Set(options.importsFields || ["imports"]), + conditionNames: new Set(options.conditionNames), + descriptionFiles: [ + ...new Set(options.descriptionFiles || ["package.json"]), + ], + enforceExtension: + options.enforceExtension === undefined + ? Boolean(options.extensions && options.extensions.includes("")) + : options.enforceExtension, + extensions: new Set(options.extensions || [".js", ".json", ".node"]), + extensionAlias: options.extensionAlias + ? Object.keys(options.extensionAlias).map((k) => ({ + extension: k, + alias: /** @type {ExtensionAliasOptions} */ (options.extensionAlias)[ + k + ], + })) + : [], + extensionAliasForExports: options.extensionAliasForExports || false, + fileSystem: options.useSyncFileSystemCalls + ? new SyncAsyncFileSystemDecorator( + /** @type {SyncFileSystem} */ ( + /** @type {unknown} */ (options.fileSystem) + ), + ) + : options.fileSystem, + unsafeCache: + options.unsafeCache && typeof options.unsafeCache !== "object" + ? /** @type {Cache} */ ({}) + : options.unsafeCache || false, + symlinks: typeof options.symlinks !== "undefined" ? options.symlinks : true, + resolver: options.resolver, + modules: mergeFilteredToArray( + Array.isArray(options.modules) + ? options.modules.map(toPath) + : options.modules + ? [toPath(options.modules)] + : ["node_modules"], + (item) => { + const type = getType(item); + return type === PathType.Normal || type === PathType.Relative; + }, + ), + mainFields, + mainFiles: new Set(options.mainFiles || ["index"]), + plugins: options.plugins || [], + packageMap: normalizePackageMap(options.packageMap), + pnpApi: processPnpApiOption(options.pnpApi), + roots: new Set(options.roots ? options.roots.map(toPath) : undefined), + fullySpecified: options.fullySpecified || false, + resolveToContext: options.resolveToContext || false, + preferRelative: options.preferRelative || false, + preferAbsolute: options.preferAbsolute || false, + restrictions: new Set( + options.restrictions && + options.restrictions.map((r) => (r instanceof RegExp ? r : toPath(r))), + ), + tsconfig: normalizeTsconfig(options.tsconfig), + }; +} + +/** + * @param {UserResolveOptions} options resolve options + * @returns {Resolver} created resolver + */ +module.exports.createResolver = function createResolver(options) { + const normalizedOptions = createOptions(options); + + const { + alias, + fallback, + aliasFields, + extensionAliasForExports, + cachePredicate, + cacheWithContext, + conditionNames, + descriptionFiles, + enforceExtension, + exportsFields, + extensionAlias, + importsFields, + extensions, + fileSystem, + fullySpecified, + mainFields, + mainFiles, + modules, + packageMap, + plugins: userPlugins, + pnpApi, + resolveToContext, + preferRelative, + preferAbsolute, + symlinks, + unsafeCache, + resolver: customResolver, + restrictions, + roots, + tsconfig, + } = normalizedOptions; + + const plugins = [...userPlugins]; + + const resolver = + customResolver || new Resolver(fileSystem, normalizedOptions); + + // // pipeline //// + + resolver.ensureHook("resolve"); + resolver.ensureHook("internalResolve"); + resolver.ensureHook("newInternalResolve"); + resolver.ensureHook("importsResolve"); + resolver.ensureHook("parsedResolve"); + resolver.ensureHook("describedResolve"); + resolver.ensureHook("rawResolve"); + resolver.ensureHook("normalResolve"); + resolver.ensureHook("internal"); + resolver.ensureHook("rawModule"); + resolver.ensureHook("alternateRawModule"); + resolver.ensureHook("module"); + resolver.ensureHook("resolveAsModule"); + resolver.ensureHook("undescribedResolveInPackage"); + resolver.ensureHook("resolveInPackage"); + resolver.ensureHook("resolveInExistingDirectory"); + resolver.ensureHook("importsFieldRelative"); + if (extensionAliasForExports) { + resolver.ensureHook("exportsFieldRelative"); + } + resolver.ensureHook("relative"); + resolver.ensureHook("describedRelative"); + resolver.ensureHook("directory"); + resolver.ensureHook("undescribedExistingDirectory"); + resolver.ensureHook("existingDirectory"); + resolver.ensureHook("undescribedRawFile"); + resolver.ensureHook("rawFile"); + resolver.ensureHook("file"); + resolver.ensureHook("finalFile"); + resolver.ensureHook("existingFile"); + resolver.ensureHook("resolved"); + + // TODO remove in next major + // cspell:word Interal + // Backward-compat + // @ts-expect-error + resolver.hooks.newInteralResolve = resolver.hooks.newInternalResolve; + + // resolve + for (const { source, resolveOptions } of [ + { source: "resolve", resolveOptions: { fullySpecified } }, + { source: "internal-resolve", resolveOptions: { fullySpecified: false } }, + // Entry point for non-relative targets from the imports field. + // Sets internal: false to prevent re-entering imports resolution, + // aligning with the Node.js ESM spec where PACKAGE_IMPORTS_RESOLVE + // does not recursively resolve # specifiers. + // https://nodejs.org/api/esm.html#resolution-algorithm-specification + { + source: "imports-resolve", + resolveOptions: { fullySpecified: false, internal: false }, + }, + ]) { + plugins.push(new ParsePlugin(source, resolveOptions, "parsed-resolve")); + } + + // parsed-resolve + plugins.push( + new DescriptionFilePlugin( + "parsed-resolve", + descriptionFiles, + false, + "described-resolve", + ), + ); + plugins.push(new NextPlugin("after-parsed-resolve", "described-resolve")); + + // described-resolve + if (unsafeCache) { + plugins.push( + new UnsafeCachePlugin( + "described-resolve", + cachePredicate, + /** @type {import("./UnsafeCachePlugin").Cache} */ (unsafeCache), + cacheWithContext, + "raw-resolve", + ), + ); + } else { + plugins.push(new NextPlugin("described-resolve", "raw-resolve")); + } + if (fallback.length > 0) { + plugins.push( + new AliasPlugin("described-resolve", fallback, "internal-resolve"), + ); + } + // raw-resolve + if (alias.length > 0) { + plugins.push(new AliasPlugin("raw-resolve", alias, "internal-resolve")); + } + if (tsconfig) { + plugins.push(new TsconfigPathsPlugin(tsconfig)); + } + for (const item of aliasFields) { + plugins.push(new AliasFieldPlugin("raw-resolve", item, "internal-resolve")); + } + for (const item of extensionAlias) { + plugins.push( + new ExtensionAliasPlugin("raw-resolve", item, "normal-resolve"), + ); + } + plugins.push(new NextPlugin("raw-resolve", "normal-resolve")); + + // normal-resolve + if (preferRelative) { + plugins.push(new JoinRequestPlugin("after-normal-resolve", "relative")); + } + plugins.push( + new ConditionalPlugin( + "after-normal-resolve", + { module: true }, + "resolve as module", + false, + "raw-module", + ), + ); + plugins.push( + new ConditionalPlugin( + "after-normal-resolve", + { internal: true }, + "resolve as internal import", + false, + "internal", + ), + ); + if (preferAbsolute) { + plugins.push(new JoinRequestPlugin("after-normal-resolve", "relative")); + } + if (roots.size > 0) { + plugins.push(new RootsPlugin("after-normal-resolve", roots, "relative")); + } + if (!preferRelative && !preferAbsolute) { + plugins.push(new JoinRequestPlugin("after-normal-resolve", "relative")); + } + + // internal + for (const importsField of importsFields) { + plugins.push( + new ImportsFieldPlugin( + "internal", + conditionNames, + importsField, + "imports-field-relative", + "imports-resolve", + ), + ); + } + // imports-field-relative: apply extensionAlias to paths produced by the + // imports field (TypeScript-style extension substitution for self-package + // imports like `#foo` -> `./foo.js` -> `./foo.ts`). Unlike the exports + // field, the imports field is internal to the package, so applying the + // consumer's extension aliases does not expose files the package author + // did not intend to export. See issue #413. + for (const item of extensionAlias) { + plugins.push( + new ExtensionAliasPlugin("imports-field-relative", item, "relative"), + ); + } + plugins.push(new NextPlugin("imports-field-relative", "relative")); + + // raw-module + // A package map is authoritative for every bare specifier that is not a + // builtin, so it runs ahead of both self-reference and the `modules` + // directories below: a package that does not declare a dependency on + // itself must not reach its own `exports` through the self-reference + // shortcut, and nothing falls back to `node_modules`. + if (packageMap) { + plugins.push( + new PackageMapPlugin( + "raw-module", + packageMap, + symlinks, + "undescribed-resolve-in-package", + ), + ); + } + for (const exportsField of exportsFields) { + plugins.push( + new SelfReferencePlugin("raw-module", exportsField, "resolve-as-module"), + ); + } + for (const item of modules) { + if (Array.isArray(item)) { + if (item.includes("node_modules") && pnpApi) { + plugins.push( + new ModulesInHierarchicalDirectoriesPlugin( + "raw-module", + item.filter((i) => i !== "node_modules"), + "module", + ), + ); + plugins.push( + new PnpPlugin( + "raw-module", + pnpApi, + "undescribed-resolve-in-package", + "alternate-raw-module", + ), + ); + + plugins.push( + new ModulesInHierarchicalDirectoriesPlugin( + "alternate-raw-module", + ["node_modules"], + "module", + ), + ); + } else { + plugins.push( + new ModulesInHierarchicalDirectoriesPlugin( + "raw-module", + item, + "module", + ), + ); + } + } else { + plugins.push(new ModulesInRootPlugin("raw-module", item, "module")); + } + } + + // module + plugins.push(new JoinRequestPartPlugin("module", "resolve-as-module")); + + // resolve-as-module + if (!resolveToContext) { + plugins.push( + new ConditionalPlugin( + "resolve-as-module", + { directory: false, request: "." }, + "single file module", + true, + "undescribed-raw-file", + ), + ); + } + plugins.push( + new DirectoryExistsPlugin( + "resolve-as-module", + "undescribed-resolve-in-package", + ), + ); + + // undescribed-resolve-in-package + plugins.push( + new DescriptionFilePlugin( + "undescribed-resolve-in-package", + descriptionFiles, + false, + "resolve-in-package", + ), + ); + plugins.push( + new NextPlugin( + "after-undescribed-resolve-in-package", + "resolve-in-package", + ), + ); + + // resolve-in-package + const exportsFieldTarget = extensionAliasForExports + ? "exports-field-relative" + : "relative"; + for (const exportsField of exportsFields) { + plugins.push( + new ExportsFieldPlugin( + "resolve-in-package", + conditionNames, + exportsField, + exportsFieldTarget, + restrictions.size > 0, + ), + ); + } + plugins.push( + new NextPlugin("resolve-in-package", "resolve-in-existing-directory"), + ); + + // exports-field-relative (opt-in via `extensionAliasForExports`): + // apply `extensionAlias` to paths produced by the exports field. This is + // off by default to match Node.js (which does not substitute extensions on + // bare-module targets), and on opt-in aligns with TypeScript for packages + // that ship TS sources alongside the compiled JS they list in `exports`. + if (extensionAliasForExports) { + for (const item of extensionAlias) { + plugins.push( + new ExtensionAliasPlugin("exports-field-relative", item, "relative"), + ); + } + plugins.push(new NextPlugin("exports-field-relative", "relative")); + } + + // resolve-in-existing-directory + plugins.push( + new JoinRequestPlugin("resolve-in-existing-directory", "relative"), + ); + + // relative + plugins.push( + new DescriptionFilePlugin( + "relative", + descriptionFiles, + true, + "described-relative", + ), + ); + plugins.push(new NextPlugin("after-relative", "described-relative")); + + // described-relative + if (resolveToContext) { + plugins.push(new NextPlugin("described-relative", "directory")); + } else { + plugins.push( + new ConditionalPlugin( + "described-relative", + { directory: false }, + null, + true, + "raw-file", + ), + ); + plugins.push( + new ConditionalPlugin( + "described-relative", + { fullySpecified: false }, + "as directory", + true, + "directory", + ), + ); + } + + // directory + plugins.push( + new DirectoryExistsPlugin("directory", "undescribed-existing-directory"), + ); + + if (resolveToContext) { + // undescribed-existing-directory + plugins.push(new NextPlugin("undescribed-existing-directory", "resolved")); + } else { + // undescribed-existing-directory + plugins.push( + new DescriptionFilePlugin( + "undescribed-existing-directory", + descriptionFiles, + false, + "existing-directory", + ), + ); + for (const item of mainFiles) { + plugins.push( + new UseFilePlugin( + "undescribed-existing-directory", + item, + "undescribed-raw-file", + ), + ); + } + + // described-existing-directory + for (const item of mainFields) { + plugins.push( + new MainFieldPlugin( + "existing-directory", + item, + "resolve-in-existing-directory", + ), + ); + } + for (const item of mainFiles) { + plugins.push( + new UseFilePlugin("existing-directory", item, "undescribed-raw-file"), + ); + } + + // undescribed-raw-file + plugins.push( + new DescriptionFilePlugin( + "undescribed-raw-file", + descriptionFiles, + true, + "raw-file", + ), + ); + plugins.push(new NextPlugin("after-undescribed-raw-file", "raw-file")); + + // raw-file + plugins.push( + new ConditionalPlugin( + "raw-file", + { fullySpecified: true }, + null, + false, + "file", + ), + ); + if (!enforceExtension) { + plugins.push(new TryNextPlugin("raw-file", "no extension", "file")); + } + for (const item of extensions) { + plugins.push(new AppendPlugin("raw-file", item, "file")); + } + + // file + if (alias.length > 0) { + plugins.push(new AliasPlugin("file", alias, "internal-resolve")); + } + for (const item of aliasFields) { + plugins.push(new AliasFieldPlugin("file", item, "internal-resolve")); + } + plugins.push(new NextPlugin("file", "final-file")); + + // final-file + plugins.push(new FileExistsPlugin("final-file", "existing-file")); + + // existing-file + if (symlinks) { + plugins.push(new SymlinkPlugin("existing-file", "existing-file")); + } + plugins.push(new NextPlugin("existing-file", "resolved")); + } + + const { resolved } = + /** @type {KnownHooks & EnsuredHooks} */ + (resolver.hooks); + + // resolved + if (restrictions.size > 0) { + plugins.push(new RestrictionsPlugin(resolved, restrictions)); + } + + plugins.push(new ResultPlugin(resolved)); + + // // RESOLVER //// + + for (const plugin of plugins) { + if (typeof plugin === "function") { + /** @type {(this: Resolver, resolver: Resolver) => void} */ + (plugin).call(resolver, resolver); + } else if (plugin) { + plugin.apply(resolver); + } + } + + return resolver; +}; diff --git a/dg-ui/node_modules/enhanced-resolve/lib/RestrictionsPlugin.js b/dg-ui/node_modules/enhanced-resolve/lib/RestrictionsPlugin.js new file mode 100644 index 0000000..2605de4 --- /dev/null +++ b/dg-ui/node_modules/enhanced-resolve/lib/RestrictionsPlugin.js @@ -0,0 +1,86 @@ +/* + MIT License http://www.opensource.org/licenses/mit-license.php + Author Ivan Kopeykin @vankop +*/ + +"use strict"; + +const { isInside, normalize } = require("./util/path"); + +/** @typedef {import("./Resolver")} Resolver */ +/** @typedef {import("./Resolver").ResolveStepHook} ResolveStepHook */ + +/** + * @typedef {object} PathRestriction + * @property {"path"} type type of the restriction + * @property {string} rule normalized path the request has to be inside of + */ + +/** + * @typedef {object} RegExpRestriction + * @property {"regexp"} type type of the restriction + * @property {RegExp} rule pattern the request has to match + */ + +/** @typedef {PathRestriction | RegExpRestriction} Restriction */ + +module.exports = class RestrictionsPlugin { + /** + * @param {string | ResolveStepHook} source source + * @param {Set} restrictions restrictions + */ + constructor(source, restrictions) { + this.source = source; + this.restrictions = restrictions; + // Restrictions never change, so bringing them into the shape requests + // arrive in is done once here instead of on every request. + /** @type {Restriction[]} */ + this._restrictions = []; + for (const rule of restrictions) { + this._restrictions.push( + typeof rule === "string" + ? { type: "path", rule: normalize(rule) } + : { type: "regexp", rule }, + ); + } + } + + /** + * @param {Resolver} resolver the resolver + * @returns {void} + */ + apply(resolver) { + resolver + .getHook(this.source) + .tapAsync("RestrictionsPlugin", (request, resolveContext, callback) => { + if (typeof request.path === "string") { + const { path } = request; + for (const restriction of this._restrictions) { + if (restriction.type === "path") { + if (isInside(restriction.rule, path)) continue; + if (resolveContext.log) { + resolveContext.log( + `${path} is not inside of the restriction ${restriction.rule}`, + ); + } + } else { + if (restriction.rule.test(path)) continue; + if (resolveContext.log) { + resolveContext.log( + `${path} doesn't match the restriction ${restriction.rule}`, + ); + } + } + // Target existed (FileExistsPlugin already passed) but is + // outside the jail; signal ExportsFieldPlugin to fall back. + if (request.__restrictionsMarker) { + request.__restrictionsMarker.blocked = true; + } + return callback(null, null); + } + } + + callback(); + }); + } +}; diff --git a/dg-ui/node_modules/enhanced-resolve/lib/ResultPlugin.js b/dg-ui/node_modules/enhanced-resolve/lib/ResultPlugin.js new file mode 100644 index 0000000..57dbddd --- /dev/null +++ b/dg-ui/node_modules/enhanced-resolve/lib/ResultPlugin.js @@ -0,0 +1,43 @@ +/* + MIT License http://www.opensource.org/licenses/mit-license.php + Author Tobias Koppers @sokra +*/ + +"use strict"; + +/** @typedef {import("./Resolver")} Resolver */ +/** @typedef {import("./Resolver").ResolveStepHook} ResolveStepHook */ + +module.exports = class ResultPlugin { + /** + * @param {ResolveStepHook} source source + */ + constructor(source) { + this.source = source; + } + + /** + * @param {Resolver} resolver the resolver + * @returns {void} + */ + apply(resolver) { + this.source.tapAsync( + "ResultPlugin", + (request, resolverContext, callback) => { + const obj = { ...request }; + if (resolverContext.log) { + resolverContext.log(`reporting result ${obj.path}`); + } + resolver.hooks.result.callAsync(obj, resolverContext, (err) => { + if (err) return callback(err); + if (typeof resolverContext.yield === "function") { + resolverContext.yield(obj); + callback(null, null); + } else { + callback(null, obj); + } + }); + }, + ); + } +}; diff --git a/dg-ui/node_modules/enhanced-resolve/lib/RootsPlugin.js b/dg-ui/node_modules/enhanced-resolve/lib/RootsPlugin.js new file mode 100644 index 0000000..539e08b --- /dev/null +++ b/dg-ui/node_modules/enhanced-resolve/lib/RootsPlugin.js @@ -0,0 +1,69 @@ +/* + MIT License http://www.opensource.org/licenses/mit-license.php + Author Ivan Kopeykin @vankop +*/ + +"use strict"; + +const forEachBail = require("./forEachBail"); + +/** @typedef {import("./Resolver")} Resolver */ +/** @typedef {import("./Resolver").ResolveRequest} ResolveRequest */ +/** @typedef {import("./Resolver").ResolveStepHook} ResolveStepHook */ + +class RootsPlugin { + /** + * @param {string | ResolveStepHook} source source hook + * @param {Set} roots roots + * @param {string | ResolveStepHook} target target hook + */ + constructor(source, roots, target) { + this.roots = [...roots]; + this.source = source; + this.target = target; + } + + /** + * @param {Resolver} resolver the resolver + * @returns {void} + */ + apply(resolver) { + const target = resolver.ensureHook(this.target); + + resolver + .getHook(this.source) + .tapAsync("RootsPlugin", (request, resolveContext, callback) => { + const req = request.request; + if (!req) return callback(); + if (!req.startsWith("/")) return callback(); + + forEachBail( + this.roots, + /** + * @param {string} root root + * @param {(err?: null | Error, result?: null | ResolveRequest) => void} callback callback + * @returns {void} + */ + (root, callback) => { + const path = resolver.join(root, req.slice(1)); + /** @type {ResolveRequest} */ + const obj = { + ...request, + path, + relativePath: request.relativePath && path, + }; + resolver.doResolve( + target, + obj, + `root path ${root}`, + resolveContext, + callback, + ); + }, + callback, + ); + }); + } +} + +module.exports = RootsPlugin; diff --git a/dg-ui/node_modules/enhanced-resolve/lib/SelfReferencePlugin.js b/dg-ui/node_modules/enhanced-resolve/lib/SelfReferencePlugin.js new file mode 100644 index 0000000..b1ee64b --- /dev/null +++ b/dg-ui/node_modules/enhanced-resolve/lib/SelfReferencePlugin.js @@ -0,0 +1,106 @@ +/* + MIT License http://www.opensource.org/licenses/mit-license.php + Author Tobias Koppers @sokra +*/ + +"use strict"; + +const DescriptionFileUtils = require("./DescriptionFileUtils"); + +/** @typedef {import("./Resolver")} Resolver */ +/** @typedef {import("./Resolver").JsonObject} JsonObject */ +/** @typedef {import("./Resolver").ResolveRequest} ResolveRequest */ +/** @typedef {import("./Resolver").ResolveStepHook} ResolveStepHook */ + +const slashCode = "/".charCodeAt(0); + +// Sentinel stored in `_nameCache` when the description file either has no +// exports field (so self-reference can't apply) or no string `name`. +const NO_SELF_REF = Symbol("NoSelfRef"); + +module.exports = class SelfReferencePlugin { + /** + * @param {string | ResolveStepHook} source source + * @param {string | string[]} fieldNamePath name path + * @param {string | ResolveStepHook} target target + */ + constructor(source, fieldNamePath, target) { + this.source = source; + this.target = target; + this.fieldName = fieldNamePath; + // Self-reference needs both an exports field and a `"name"` string. + // Both are stable per description-file content, so cache the decision + // in one WeakMap: the resolved name when self-reference is possible, + // or `NO_SELF_REF` when it isn't. This skips the two per-resolve + // `DescriptionFileUtils.getField` walks for hot packages. + /** @type {WeakMap} */ + this._nameCache = new WeakMap(); + } + + /** + * @param {Resolver} resolver the resolver + * @returns {void} + */ + apply(resolver) { + const target = resolver.ensureHook(this.target); + resolver + .getHook(this.source) + .tapAsync("SelfReferencePlugin", (request, resolveContext, callback) => { + if (!request.descriptionFileData) return callback(); + + const req = request.request; + if (!req) return callback(); + + const { descriptionFileData } = request; + let name = this._nameCache.get(descriptionFileData); + if (name === undefined) { + // Feature is only enabled when an exports field is present + const exportsField = DescriptionFileUtils.getField( + descriptionFileData, + this.fieldName, + ); + if (!exportsField) { + this._nameCache.set(descriptionFileData, NO_SELF_REF); + return callback(); + } + const rawName = DescriptionFileUtils.getField( + descriptionFileData, + "name", + ); + if (typeof rawName !== "string") { + this._nameCache.set(descriptionFileData, NO_SELF_REF); + return callback(); + } + name = rawName; + this._nameCache.set(descriptionFileData, name); + } else if (name === NO_SELF_REF) { + return callback(); + } + + if ( + req.startsWith(name) && + (req.length === name.length || + req.charCodeAt(name.length) === slashCode) + ) { + const remainingRequest = `.${req.slice(name.length)}`; + /** @type {ResolveRequest} */ + const obj = { + ...request, + request: remainingRequest, + path: /** @type {string} */ (request.descriptionFileRoot), + relativePath: ".", + }; + + resolver.doResolve( + target, + obj, + "self reference", + resolveContext, + callback, + ); + } else { + return callback(); + } + }); + } +}; diff --git a/dg-ui/node_modules/enhanced-resolve/lib/SymlinkPlugin.js b/dg-ui/node_modules/enhanced-resolve/lib/SymlinkPlugin.js new file mode 100644 index 0000000..fb6c458 --- /dev/null +++ b/dg-ui/node_modules/enhanced-resolve/lib/SymlinkPlugin.js @@ -0,0 +1,132 @@ +/* + MIT License http://www.opensource.org/licenses/mit-license.php + Author Tobias Koppers @sokra +*/ + +"use strict"; + +const forEachBail = require("./forEachBail"); +const { getPathsCached } = require("./getPaths"); +const { PathType, getType } = require("./util/path"); + +/** @typedef {import("./Resolver")} Resolver */ +/** @typedef {import("./Resolver").ResolveRequest} ResolveRequest */ +/** @typedef {import("./Resolver").ResolveStepHook} ResolveStepHook */ + +module.exports = class SymlinkPlugin { + /** + * @param {string | ResolveStepHook} source source + * @param {string | ResolveStepHook} target target + */ + constructor(source, target) { + this.source = source; + this.target = target; + } + + /** + * @param {Resolver} resolver the resolver + * @returns {void} + */ + apply(resolver) { + const target = resolver.ensureHook(this.target); + const fs = resolver.fileSystem; + resolver + .getHook(this.source) + .tapAsync("SymlinkPlugin", (request, resolveContext, callback) => { + if (request.ignoreSymlinks) return callback(); + const pathsResult = getPathsCached( + fs, + /** @type {string} */ (request.path), + ); + const { paths, segments } = pathsResult; + // `pathsResult.segments` is shared across callers via the cache. + // The only place we need to mutate is `pathSegments[idx] = result` + // when `fs.readlink` succeeds — which is rare (the vast majority + // of paths contain no symlinks, e.g. every resolve on + // `cache-predicate`'s no-symlink fixture). Defer the copy until + // we actually see a symlink so the common no-symlink path stays + // allocation-free. + /** @type {string[] | null} */ + let pathSegments = null; + + let containsSymlink = false; + let idx = -1; + forEachBail( + paths, + /** + * @param {string} path path + * @param {(err?: null | Error, result?: null | number) => void} callback callback + * @returns {void} + */ + (path, callback) => { + idx++; + if (resolveContext.fileDependencies) { + resolveContext.fileDependencies.add(path); + } + fs.readlink(path, (err, result) => { + if (!err && result) { + // First symlink seen — take our own copy now, so + // the cached `segments` array stays pristine for + // sibling resolves. + if (pathSegments === null) { + pathSegments = [...segments]; + } + pathSegments[idx] = /** @type {string} */ (result); + containsSymlink = true; + // Shortcut when absolute symlink found + const resultType = getType(result.toString()); + if ( + resultType === PathType.AbsoluteWin || + resultType === PathType.AbsolutePosix + ) { + return callback(null, idx); + } + } + callback(); + }); + }, + /** + * @param {null | Error=} err error + * @param {null | number=} idx result + * @returns {void} + */ + (err, idx) => { + if (!containsSymlink) return callback(); + // `containsSymlink === true` implies we took a copy in + // `pathSegments` already, so it's non-null. The copy is + // our own, so `slice` to trim is fine and spreading to + // "unshare" is no longer necessary. + const own = /** @type {string[]} */ (pathSegments); + const resultSegments = + typeof idx === "number" ? own.slice(0, idx + 1) : own; + const result = resultSegments.reduceRight((a, b) => + resolver.join(a, b), + ); + /** @type {ResolveRequest} */ + const obj = { + ...request, + path: result, + }; + resolver.doResolve( + target, + obj, + `resolved symlink to ${result}`, + resolveContext, + (err, innerResult) => { + if (err) return callback(err); + // The symlink-resolved (real) path is authoritative. If + // resolving it produced a result, use it. If it did not — + // e.g. a `restrictions` rule rejected the real target — + // stop here with no result instead of letting the next + // plugin report the original in-root symlink path, which + // would leave the symlink unresolved and bypass + // `restrictions`. + if (innerResult) return callback(null, innerResult); + return callback(null, null); + }, + ); + }, + ); + }); + } +}; diff --git a/dg-ui/node_modules/enhanced-resolve/lib/SyncAsyncFileSystemDecorator.js b/dg-ui/node_modules/enhanced-resolve/lib/SyncAsyncFileSystemDecorator.js new file mode 100644 index 0000000..d365d1c --- /dev/null +++ b/dg-ui/node_modules/enhanced-resolve/lib/SyncAsyncFileSystemDecorator.js @@ -0,0 +1,282 @@ +/* + MIT License http://www.opensource.org/licenses/mit-license.php + Author Tobias Koppers @sokra +*/ + +"use strict"; + +/** @typedef {import("./Resolver").FileSystem} FileSystem */ +/** @typedef {import("./Resolver").StringCallback} StringCallback */ +/** @typedef {import("./Resolver").SyncFileSystem} SyncFileSystem */ + +// eslint-disable-next-line jsdoc/reject-function-type +/** @typedef {Function} SyncOrAsyncFunction */ +// eslint-disable-next-line jsdoc/reject-any-type +/** @typedef {any} ResultOfSyncOrAsyncFunction */ + +/** @typedef {import("./Resolver").ObjectEncodingOptions} ObjectEncodingOptions */ +/** @typedef {import("./Resolver").PathOrFileDescriptor} PathOrFileDescriptor */ + +/** + * Every option `readFileSync` accepts, as `readFile` passes it through. + * @typedef {(ObjectEncodingOptions & { flag?: string | undefined }) | BufferEncoding | null} ReadFileSyncOptions + */ + +/** + * Reads a file synchronously with whatever options came in. Each branch + * hands `options` to the `readFileSync` overload of its kind, so a file + * system typed with only those overloads (as Node's own are) fits. + * @param {SyncFileSystem} fs file system + * @param {PathOrFileDescriptor} path path + * @param {ReadFileSyncOptions=} options options + * @returns {string | Buffer} file content + */ +const readFileSyncWith = (fs, path, options) => + options === undefined || options === null + ? fs.readFileSync(path, options) + : typeof options === "string" + ? fs.readFileSync(path, options) + : fs.readFileSync(path, options); + +/** + * @param {SyncFileSystem} fs file system implementation + * @constructor + */ +function SyncAsyncFileSystemDecorator(fs) { + this.fs = fs; + + this.lstat = undefined; + this.lstatSync = undefined; + const { lstatSync } = fs; + if (lstatSync) { + this.lstat = + /** @type {FileSystem["lstat"]} */ + ( + (arg, options, callback) => { + let result; + try { + result = /** @type {SyncOrAsyncFunction | undefined} */ (callback) + ? lstatSync.call(fs, arg, options) + : lstatSync.call(fs, arg); + } catch (err) { + return (callback || options)( + /** @type {NodeJS.ErrnoException | null} */ + (err), + ); + } + + (callback || options)( + null, + /** @type {ResultOfSyncOrAsyncFunction} */ + (result), + ); + } + ); + this.lstatSync = + /** @type {SyncFileSystem["lstatSync"]} */ + ((arg, options) => lstatSync.call(fs, arg, options)); + } + + this.stat = + /** @type {FileSystem["stat"]} */ + ( + (arg, options, callback) => { + let result; + try { + result = /** @type {SyncOrAsyncFunction | undefined} */ (callback) + ? fs.statSync(arg, options) + : fs.statSync(arg); + } catch (err) { + return (callback || options)( + /** @type {NodeJS.ErrnoException | null} */ + (err), + ); + } + + (callback || options)( + null, + /** @type {ResultOfSyncOrAsyncFunction} */ + (result), + ); + } + ); + this.statSync = + /** @type {SyncFileSystem["statSync"]} */ + ((arg, options) => fs.statSync(arg, options)); + + this.readdir = + /** @type {FileSystem["readdir"]} */ + ( + (arg, options, callback) => { + let result; + try { + result = /** @type {SyncOrAsyncFunction | undefined} */ (callback) + ? fs.readdirSync( + arg, + /** @type {Exclude[1], (err: NodeJS.ErrnoException | null, files: string[]) => void>} */ + (options), + ) + : fs.readdirSync(arg); + } catch (err) { + return (callback || options)( + /** @type {NodeJS.ErrnoException | null} */ + (err), + [], + ); + } + + (callback || options)( + null, + /** @type {ResultOfSyncOrAsyncFunction} */ + (result), + ); + } + ); + this.readdirSync = + /** @type {SyncFileSystem["readdirSync"]} */ + ( + (arg, options) => + fs.readdirSync( + arg, + /** @type {Parameters[1]} */ (options), + ) + ); + + this.readFile = + /** @type {FileSystem["readFile"]} */ + ( + (arg, options, callback) => { + let result; + try { + result = /** @type {SyncOrAsyncFunction | undefined} */ (callback) + ? readFileSyncWith(fs, arg, options) + : fs.readFileSync(arg); + } catch (err) { + return (callback || options)( + /** @type {NodeJS.ErrnoException | null} */ + (err), + ); + } + + (callback || options)( + null, + /** @type {ResultOfSyncOrAsyncFunction} */ + (result), + ); + } + ); + this.readFileSync = + /** @type {SyncFileSystem["readFileSync"]} */ + ((arg, options) => readFileSyncWith(fs, arg, options)); + + this.readlink = + /** @type {FileSystem["readlink"]} */ + ( + (arg, options, callback) => { + let result; + try { + result = /** @type {SyncOrAsyncFunction | undefined} */ (callback) + ? fs.readlinkSync( + arg, + /** @type {Exclude[1], StringCallback>} */ + (options), + ) + : fs.readlinkSync(arg); + } catch (err) { + return (callback || options)( + /** @type {NodeJS.ErrnoException | null} */ + (err), + ); + } + + (callback || options)( + null, + /** @type {ResultOfSyncOrAsyncFunction} */ + (result), + ); + } + ); + this.readlinkSync = + /** @type {SyncFileSystem["readlinkSync"]} */ + ( + (arg, options) => + fs.readlinkSync( + arg, + /** @type {Parameters[1]} */ ( + options + ), + ) + ); + + this.readJson = undefined; + this.readJsonSync = undefined; + const { readJsonSync } = fs; + if (readJsonSync) { + this.readJson = + /** @type {FileSystem["readJson"]} */ + ( + (arg, callback) => { + let result; + try { + result = readJsonSync.call(fs, arg); + } catch (err) { + return callback( + /** @type {NodeJS.ErrnoException | Error | null} */ (err), + ); + } + + callback(null, result); + } + ); + this.readJsonSync = + /** @type {SyncFileSystem["readJsonSync"]} */ + ((arg) => readJsonSync.call(fs, arg)); + } + + this.realpath = undefined; + this.realpathSync = undefined; + const { realpathSync } = fs; + if (realpathSync) { + this.realpath = + /** @type {FileSystem["realpath"]} */ + ( + (arg, options, callback) => { + let result; + try { + result = /** @type {SyncOrAsyncFunction | undefined} */ (callback) + ? realpathSync.call( + fs, + arg, + /** @type {Exclude>[1], StringCallback>} */ + (options), + ) + : realpathSync.call(fs, arg); + } catch (err) { + return (callback || options)( + /** @type {NodeJS.ErrnoException | null} */ + (err), + ); + } + + (callback || options)( + null, + /** @type {ResultOfSyncOrAsyncFunction} */ + (result), + ); + } + ); + this.realpathSync = + /** @type {SyncFileSystem["realpathSync"]} */ + ( + (arg, options) => + realpathSync.call( + fs, + arg, + /** @type {Parameters>[1]} */ + (options), + ) + ); + } +} + +module.exports = SyncAsyncFileSystemDecorator; diff --git a/dg-ui/node_modules/enhanced-resolve/lib/TryNextPlugin.js b/dg-ui/node_modules/enhanced-resolve/lib/TryNextPlugin.js new file mode 100644 index 0000000..4b46787 --- /dev/null +++ b/dg-ui/node_modules/enhanced-resolve/lib/TryNextPlugin.js @@ -0,0 +1,41 @@ +/* + MIT License http://www.opensource.org/licenses/mit-license.php + Author Tobias Koppers @sokra +*/ + +"use strict"; + +/** @typedef {import("./Resolver")} Resolver */ +/** @typedef {import("./Resolver").ResolveStepHook} ResolveStepHook */ + +module.exports = class TryNextPlugin { + /** + * @param {string | ResolveStepHook} source source + * @param {string} message message + * @param {string | ResolveStepHook} target target + */ + constructor(source, message, target) { + this.source = source; + this.message = message; + this.target = target; + } + + /** + * @param {Resolver} resolver the resolver + * @returns {void} + */ + apply(resolver) { + const target = resolver.ensureHook(this.target); + resolver + .getHook(this.source) + .tapAsync("TryNextPlugin", (request, resolveContext, callback) => { + resolver.doResolve( + target, + request, + this.message, + resolveContext, + callback, + ); + }); + } +}; diff --git a/dg-ui/node_modules/enhanced-resolve/lib/TsconfigPathsPlugin.js b/dg-ui/node_modules/enhanced-resolve/lib/TsconfigPathsPlugin.js new file mode 100644 index 0000000..f09cabc --- /dev/null +++ b/dg-ui/node_modules/enhanced-resolve/lib/TsconfigPathsPlugin.js @@ -0,0 +1,915 @@ +/* + MIT License http://www.opensource.org/licenses/mit-license.php + Author Natsu @xiaoxiaojx +*/ + +"use strict"; + +const { aliasResolveHandler, compileAliasOptions } = require("./AliasUtils"); +const { modulesResolveHandler } = require("./ModulesUtils"); +const { readJson } = require("./util/fs"); +const { PathType, getType, isSubPath } = require("./util/path"); + +/** @typedef {import("./Resolver")} Resolver */ +/** @typedef {import("./Resolver").ResolveStepHook} ResolveStepHook */ +/** @typedef {import("./AliasUtils").AliasOption} AliasOption */ +/** @typedef {import("./Resolver").ResolveRequest} ResolveRequest */ +/** @typedef {import("./Resolver").ResolveContext} ResolveContext */ +/** @typedef {import("./Resolver").FileSystem} FileSystem */ +/** @typedef {import("./Resolver").TsconfigPathsData} TsconfigPathsData */ +/** @typedef {import("./Resolver").TsconfigPathsMap} TsconfigPathsMap */ +/** @typedef {import("./ResolverFactory").TsconfigOptions} TsconfigOptions */ + +// Sentinel stored in `_contextSelectionCache` for `requestPath`s whose +// scan returned `null` ("no context matched"). Using a non-null marker +// lets the cache-hit path be a single `Map.get()` — we distinguish +// "cached null" from "not cached yet" without a second `has` lookup. +const NULL_CONTEXT = Symbol("NULL_CONTEXT"); + +/** + * Per-`TsconfigPathsMap` memoization of `_selectPathsDataForContext`. + * + * Real-world builds resolve hundreds of requests per source file (every + * import in the file), and webpack-style resolvers walk the same + * `requestPath` (= source-file directory) for each one. Without this + * cache every resolve re-scans the full `contextList` even though the + * answer is invariant for a given `(map, requestPath)` pair. + * + * The outer key is the `TsconfigPathsMap` itself — rebuilt on every + * tsconfig change — so a `WeakMap` lets the inner map be collected + * automatically once the map goes away. The inner Map is keyed by + * `requestPath` (string); a `Symbol` sentinel stands in for "no + * matching context" so `Map.get` alone distinguishes the three states + * (cached data / cached null / not cached). + * @type {WeakMap>} + */ +const _contextSelectionCache = new WeakMap(); + +/** + * @typedef {object} TsconfigCompilerOptions + * @property {string=} baseUrl Base URL for resolving paths + * @property {{ [key: string]: string[] }=} paths TypeScript paths mapping + * @property {string=} pathsBasePath directory of the config file that declares `paths`, used when there is no `baseUrl` + */ + +/** + * @typedef {object} TsconfigReference + * @property {string} path Path to the referenced project + */ + +/** + * @typedef {object} Tsconfig + * @property {TsconfigCompilerOptions=} compilerOptions Compiler options + * @property {string | string[]=} extends Extended configuration paths + * @property {TsconfigReference[]=} references Project references + */ + +const DEFAULT_CONFIG_FILE = "tsconfig.json"; + +const READ_JSON_OPTIONS = { stripComments: true }; + +const BACKSLASH_RE = /\\/g; + +/** @type {WeakMap} */ +const extendsResolvers = new WeakMap(); + +// Trailing `/*` or `\*` segment of a tsconfig `paths` mapping (e.g. +// `./src/*` → `./src`). Hoisted so we don't allocate a fresh regex per +// path entry on every tsconfig load — and so the same regex object can be +// reused for the matching `test` + `replace` pair below. +const WILDCARD_TAIL_RE = /[/\\]\*$/; + +/** + * @param {string} pattern Path pattern + * @returns {number} Length of the prefix + */ +function getPrefixLength(pattern) { + const prefixLength = pattern.indexOf("*"); + if (prefixLength === -1) { + return pattern.length; + } + return prefixLength; +} + +/** + * Sort path patterns. + * If a module name can be matched with multiple patterns then pattern with the longest prefix will be picked. + * @param {string[]} arr Array of path patterns + * @returns {string[]} Array of path patterns sorted by longest prefix + */ +function sortByLongestPrefix(arr) { + return [...arr].sort((a, b) => getPrefixLength(b) - getPrefixLength(a)); +} + +/** + * Merge two tsconfig objects + * @param {Tsconfig | null} base base config + * @param {Tsconfig | null} config config to merge + * @returns {Tsconfig} merged config + */ +function mergeTsconfigs(base, config) { + base = base || {}; + config = config || {}; + + return { + ...base, + ...config, + compilerOptions: { + .../** @type {TsconfigCompilerOptions} */ (base.compilerOptions), + .../** @type {TsconfigCompilerOptions} */ (config.compilerOptions), + }, + }; +} + +/** + * Substitute ${configDir} template variable in path + * @param {string} pathValue the path value + * @param {string} configDir the config directory + * @returns {string} the path with substituted template + */ +function substituteConfigDir(pathValue, configDir) { + // eslint-disable-next-line no-template-curly-in-string + if (!pathValue.includes("${configDir}")) return pathValue; + return pathValue.replace(/\$\{configDir\}/g, configDir); +} + +/** + * Convert tsconfig paths to resolver options + * @param {string} configDir Config file directory + * @param {{ [key: string]: string[] }} paths TypeScript paths mapping + * @param {Resolver} resolver resolver instance + * @param {string=} baseUrl Base URL for resolving paths (relative to configDir) + * @param {string=} pathsBasePath directory of the config file that declares `paths` (defaults to configDir) + * @returns {TsconfigPathsData} the resolver options + */ +function tsconfigPathsToResolveOptions( + configDir, + paths, + resolver, + baseUrl, + pathsBasePath, +) { + // Substitute ${configDir} in baseUrl + if (baseUrl) baseUrl = substituteConfigDir(baseUrl, configDir); + + // Calculate absolute base URL. Without baseUrl, tsc resolves `paths` + // relative to the config file that declares them. An empty baseUrl is + // still a baseUrl: the directory of the config file. + const absoluteBaseUrl = + baseUrl === undefined + ? pathsBasePath || configDir + : resolver.join(configDir, baseUrl); + + /** @type {string[]} */ + const sortedKeys = sortByLongestPrefix(Object.keys(paths)); + /** @type {AliasOption[]} */ + const alias = []; + /** @type {string[]} */ + const modules = []; + + for (const pattern of sortedKeys) { + const mappings = paths[pattern]; + // Substitute ${configDir} in path mappings + const absolutePaths = mappings.map((mapping) => { + const substituted = substituteConfigDir(mapping, configDir); + return resolver.join(absoluteBaseUrl, substituted); + }); + + if (absolutePaths.length > 0) { + if (pattern === "*") { + // Pull `dir/*` entries directly into `modules` with their + // trailing wildcard stripped, skipping anything else. The + // previous `.map(...).filter(Boolean)` form allocated two + // throwaway arrays plus a spread iterator per `*` mapping. + for (let j = 0; j < absolutePaths.length; j++) { + const dir = absolutePaths[j]; + if (WILDCARD_TAIL_RE.test(dir)) { + modules.push(dir.replace(WILDCARD_TAIL_RE, "")); + } + } + } else { + alias.push({ name: pattern, alias: absolutePaths }); + } + } + } + + if (baseUrl !== undefined && !modules.includes(absoluteBaseUrl)) { + modules.push(absoluteBaseUrl); + } + + return { + alias: compileAliasOptions(resolver, alias), + modules, + }; +} + +/** + * Get the base context for the current project + * @param {string} context the context + * @param {Resolver} resolver resolver instance + * @param {string=} baseUrl base URL for resolving paths + * @returns {string} the base context + */ +function getAbsoluteBaseUrl(context, resolver, baseUrl) { + return !baseUrl ? context : resolver.join(context, baseUrl); +} + +/** + * @param {TsconfigPathsData} main main paths data + * @param {string} mainContext main context + * @param {{ [baseUrl: string]: TsconfigPathsData }} refs references map + * @param {Set} fileDependencies file dependencies + * @returns {TsconfigPathsMap} the tsconfig paths map + */ +function buildTsconfigPathsMap(main, mainContext, refs, fileDependencies) { + const allContexts = /** @type {{ [context: string]: TsconfigPathsData }} */ ({ + [mainContext]: main, + ...refs, + }); + // Precompute the key list once per tsconfig load. `_selectPathsDataForContext` + // runs per resolve and otherwise would call `Object.entries(allContexts)` + // each time, allocating a fresh [key, value][] array. + const contextList = Object.keys(allContexts); + return { + main, + mainContext, + refs, + allContexts, + contextList, + fileDependencies, + }; +} + +module.exports = class TsconfigPathsPlugin { + /** + * @param {true | string | TsconfigOptions} configFileOrOptions tsconfig file path or options object + */ + constructor(configFileOrOptions) { + if ( + typeof configFileOrOptions === "object" && + configFileOrOptions !== null + ) { + // Options object format + const { configFile } = configFileOrOptions; + /** @type {boolean} */ + this.isAutoConfigFile = typeof configFile !== "string"; + /** @type {string} */ + this.configFile = this.isAutoConfigFile + ? DEFAULT_CONFIG_FILE + : /** @type {string} */ (configFile); + /** @type {string[] | "auto"} */ + if (Array.isArray(configFileOrOptions.references)) { + /** @type {TsconfigReference[] | "auto"} */ + this.references = configFileOrOptions.references.map((ref) => ({ + path: ref, + })); + } else if (configFileOrOptions.references === "auto") { + this.references = "auto"; + } else { + this.references = []; + } + /** @type {string | undefined} */ + this.baseUrl = configFileOrOptions.baseUrl; + } else { + /** @type {boolean} */ + this.isAutoConfigFile = configFileOrOptions === true; + /** @type {string} */ + this.configFile = this.isAutoConfigFile + ? DEFAULT_CONFIG_FILE + : /** @type {string} */ (configFileOrOptions); + /** @type {TsconfigReference[] | "auto"} */ + this.references = []; + /** @type {string | undefined} */ + this.baseUrl = undefined; + } + } + + /** + * @param {Resolver} resolver the resolver + * @returns {void} + */ + apply(resolver) { + const aliasTarget = resolver.ensureHook("internal-resolve"); + const moduleTarget = resolver.ensureHook("module"); + + resolver + .getHook("raw-resolve") + .tapAsync("TsconfigPathsPlugin", (request, resolveContext, callback) => { + this._getTsconfigPathsMap( + resolver, + request, + resolveContext, + (err, tsconfigPathsMap) => { + if (err) return callback(err); + if (!tsconfigPathsMap) return callback(); + + const selectedData = this._selectPathsDataForContext( + request.path, + tsconfigPathsMap, + ); + + if (!selectedData) return callback(); + + aliasResolveHandler( + resolver, + selectedData.alias, + aliasTarget, + request, + resolveContext, + (err, result) => { + if (err) return callback(err); + if (result) return callback(null, result); + // https://github.com/webpack/webpack/issues/20944 + // Unlike resolve.alias, tsconfig paths should fall through + // when a pattern matches but the mapped path does not exist + // (matching TypeScript's native resolution behavior). + return callback(); + }, + ); + }, + ); + }); + + resolver + .getHook("raw-module") + .tapAsync("TsconfigPathsPlugin", (request, resolveContext, callback) => { + this._getTsconfigPathsMap( + resolver, + request, + resolveContext, + (err, tsconfigPathsMap) => { + if (err) return callback(err); + if (!tsconfigPathsMap) return callback(); + + const selectedData = this._selectPathsDataForContext( + request.path, + tsconfigPathsMap, + ); + + if (!selectedData) return callback(); + + modulesResolveHandler( + resolver, + selectedData.modules, + moduleTarget, + request, + resolveContext, + callback, + ); + }, + ); + }); + } + + /** + * Get TsconfigPathsMap for the request (with caching) + * @param {Resolver} resolver the resolver + * @param {ResolveRequest} request the request + * @param {ResolveContext} resolveContext the resolve context + * @param {(err: Error | null, result?: TsconfigPathsMap | null) => void} callback the callback + * @returns {void} + */ + _getTsconfigPathsMap(resolver, request, resolveContext, callback) { + if (typeof request.tsconfigPathsMap !== "undefined") { + const cached = request.tsconfigPathsMap; + if (!cached) return callback(null, null); + if (resolveContext.fileDependencies) { + for (const fileDependency of cached.fileDependencies) { + resolveContext.fileDependencies.add(fileDependency); + } + } + return callback(null, cached); + } + + if (this.isAutoConfigFile) { + this._findTsconfigUpward( + resolver, + request.path || process.cwd(), + (err, result) => { + if (err) { + request.tsconfigPathsMap = null; + return callback(err); + } + if (!result) { + request.tsconfigPathsMap = null; + return callback(null, null); + } + const map = /** @type {TsconfigPathsMap} */ (result); + request.tsconfigPathsMap = map; + if (resolveContext.fileDependencies) { + for (const fileDependency of map.fileDependencies) { + resolveContext.fileDependencies.add(fileDependency); + } + } + callback(null, map); + }, + ); + return; + } + + const absTsconfigPath = resolver.join( + request.path || process.cwd(), + this.configFile, + ); + this._loadTsconfigPathsMap(resolver, absTsconfigPath, (err, result) => { + if (err) { + request.tsconfigPathsMap = null; + return callback(err); + } + + const map = /** @type {TsconfigPathsMap} */ (result); + request.tsconfigPathsMap = map; + if (resolveContext.fileDependencies) { + for (const fileDependency of map.fileDependencies) { + resolveContext.fileDependencies.add(fileDependency); + } + } + callback(null, map); + }); + } + + /** + * Walk up from startDir to the filesystem root looking for tsconfig.json. + * Like TypeScript's own `findConfigFile` / `forEachAncestorDirectory`. + * @param {Resolver} resolver the resolver + * @param {string} startDir the directory to start searching from + * @param {(err: Error | null, result?: TsconfigPathsMap | null) => void} callback the callback + * @returns {void} + */ + _findTsconfigUpward(resolver, startDir, callback) { + const { fileSystem } = resolver; + const configFileName = this.configFile; + + /** + * @param {string} dir current directory + * @returns {void} + */ + const check = (dir) => { + const candidate = resolver.join(dir, configFileName); + fileSystem.stat(candidate, (statErr) => { + if (!statErr) { + // Found — load it + this._loadTsconfigPathsMap(resolver, candidate, (loadErr, result) => { + if (loadErr) { + // Auto mode: soft-fail silently. + return callback(null, null); + } + callback(null, result); + }); + return; + } + // Not found — move to parent + const parentDir = resolver.dirname(dir); + if (parentDir === dir) { + // Reached filesystem root, no tsconfig.json found + return callback(null, null); + } + check(parentDir); + }); + }; + + check(startDir); + } + + /** + * Load tsconfig.json and build complete TsconfigPathsMap + * Includes main project paths and all referenced projects + * @param {Resolver} resolver the resolver + * @param {string} absTsconfigPath absolute path to tsconfig.json + * @param {(err: Error | null, result?: TsconfigPathsMap) => void} callback the callback + * @returns {void} + */ + _loadTsconfigPathsMap(resolver, absTsconfigPath, callback) { + /** @type {Set} */ + const fileDependencies = new Set(); + + this._loadTsconfig( + resolver, + absTsconfigPath, + fileDependencies, + undefined, + (err, config) => { + if (err) return callback(err); + + const cfg = /** @type {Tsconfig} */ (config); + const compilerOptions = cfg.compilerOptions || {}; + const mainContext = resolver.dirname(absTsconfigPath); + + const baseUrl = + this.baseUrl !== undefined ? this.baseUrl : compilerOptions.baseUrl; + + const main = tsconfigPathsToResolveOptions( + mainContext, + compilerOptions.paths || {}, + resolver, + baseUrl, + compilerOptions.pathsBasePath, + ); + /** @type {{ [baseUrl: string]: TsconfigPathsData }} */ + const refs = {}; + + let referencesToUse = null; + if (this.references === "auto") { + referencesToUse = cfg.references; + } else if (Array.isArray(this.references)) { + referencesToUse = this.references; + } + + if (!Array.isArray(referencesToUse)) { + return callback( + null, + buildTsconfigPathsMap(main, mainContext, refs, fileDependencies), + ); + } + + this._loadTsconfigReferences( + resolver, + mainContext, + referencesToUse, + fileDependencies, + refs, + (refErr) => { + if (refErr) return callback(refErr); + callback( + null, + buildTsconfigPathsMap(main, mainContext, refs, fileDependencies), + ); + }, + ); + }, + ); + } + + /** + * Select the correct TsconfigPathsData based on request.path (context-aware) + * Matches the behavior of tsconfig-paths-webpack-plugin + * @param {string | false} requestPath the request path + * @param {TsconfigPathsMap} tsconfigPathsMap the tsconfig paths map + * @returns {TsconfigPathsData | null} the selected paths data + */ + _selectPathsDataForContext(requestPath, tsconfigPathsMap) { + const { main, allContexts, contextList } = tsconfigPathsMap; + if (!requestPath) { + return main; + } + // Single-context tsconfigs (no project references) hit the loop + // below at most once; in that case the cache lookup costs more + // than the loop itself. Only memoize when there are 2+ contexts + // — that's the monorepo / project-references shape where the + // scan actually walks multiple entries per resolve and the + // `(map, requestPath)` answer can be reused. + /** @type {Map | undefined} */ + let perMap; + if (contextList.length >= 2) { + perMap = _contextSelectionCache.get(tsconfigPathsMap); + if (perMap !== undefined) { + const cached = perMap.get(requestPath); + if (cached !== undefined) { + return cached === NULL_CONTEXT + ? null + : /** @type {TsconfigPathsData} */ (cached); + } + } else { + perMap = new Map(); + _contextSelectionCache.set(tsconfigPathsMap, perMap); + } + } + let longestMatchContext = null; + let longestMatchLength = 0; + // Iterate the pre-computed key list (the previous + // `Object.entries(allContexts)` form allocated a fresh + // `[key, value][]` per resolve). Defer the `allContexts[context]` + // lookup to after we know the context actually matches — non-matches + // are the common case and don't need the property access. + for (let i = 0; i < contextList.length; i++) { + const context = contextList[i]; + if (context === requestPath) { + const exact = allContexts[context]; + if (perMap !== undefined) perMap.set(requestPath, exact); + return exact; + } + // Cheap integer-compare gate first: a context can only beat the + // current longest match if its own length is strictly greater. + // Skipping `isSubPath` (a `startsWith` + char-code probe) when the + // length already disqualifies the candidate avoids the per-resolve + // scan over every shorter context. + if ( + context.length > longestMatchLength && + isSubPath(context, requestPath) + ) { + longestMatchContext = context; + longestMatchLength = context.length; + } + } + const result = + longestMatchContext === null ? null : allContexts[longestMatchContext]; + if (perMap !== undefined) { + perMap.set(requestPath, result === null ? NULL_CONTEXT : result); + } + return result; + } + + /** + * Load tsconfig from extends path + * @param {Resolver} resolver the resolver + * @param {string} configFilePath current config file path + * @param {string} extendedConfigValue extends value + * @param {Set} fileDependencies the file dependencies + * @param {Set} visitedConfigPaths config paths being loaded (for circular extends detection) + * @param {(err: Error | null, result?: Tsconfig) => void} callback callback + * @returns {void} + */ + _loadTsconfigFromExtends( + resolver, + configFilePath, + extendedConfigValue, + fileDependencies, + visitedConfigPaths, + callback, + ) { + const currentDir = resolver.dirname(configFilePath); + const extendedConfig = substituteConfigDir( + extendedConfigValue, + currentDir, + ).replace(BACKSLASH_RE, "/"); + + /** + * @param {string} extendedConfigPath resolved config path to load + */ + const loadExtended = (extendedConfigPath) => { + this._loadTsconfig( + resolver, + extendedConfigPath, + fileDependencies, + visitedConfigPaths, + (err, config) => { + if (err) return callback(err); + + // Copy instead of mutating: `readJson` caches the parsed object, + // so it is shared with every other load of the same file + const { references, ...cfg } = /** @type {Tsconfig} */ (config); + const { compilerOptions } = cfg; + + // ${configDir} stays as is: it means the directory of the + // root tsconfig, so it is substituted when the paths are built + if ( + compilerOptions && + typeof compilerOptions.baseUrl === "string" && + // eslint-disable-next-line no-template-curly-in-string + !compilerOptions.baseUrl.includes("${configDir}") + ) { + cfg.compilerOptions = { + ...compilerOptions, + baseUrl: getAbsoluteBaseUrl( + resolver.dirname(extendedConfigPath), + resolver, + compilerOptions.baseUrl, + ), + }; + } + + callback(null, cfg); + }, + ); + }; + + /** + * Load the value as a file path relative to the config, like tsc does. + * @returns {void} + */ + const loadRelative = () => { + const extendedConfigPath = resolver.join(currentDir, extendedConfig); + if (extendedConfigPath.endsWith(".json")) { + return loadExtended(extendedConfigPath); + } + resolver.fileSystem.stat(extendedConfigPath, (err, stats) => { + loadExtended( + stats && stats.isFile() + ? extendedConfigPath + : `${extendedConfigPath}.json`, + ); + }); + }; + + const type = getType(extendedConfig); + // Like tsc, a "./", "../" or absolute value names a file, with ".json" as + // a fallback. Anything else, "." and ".." included, resolves like a + // `require` of a config: `exports`, the `tsconfig` field, tsconfig.json. + if ( + type === PathType.AbsolutePosix || + type === PathType.AbsoluteWin || + extendedConfig.startsWith("./") || + extendedConfig.startsWith("../") + ) { + return loadRelative(); + } + + let extendsResolver = extendsResolvers.get(resolver); + if (extendsResolver === undefined) { + // Required lazily, since ResolverFactory requires this module. + extendsResolver = require("./ResolverFactory").createResolver({ + fileSystem: resolver.fileSystem, + conditionNames: ["require", "types", "node"], + extensions: [".json"], + mainFields: ["tsconfig"], + mainFiles: ["tsconfig"], + }); + extendsResolvers.set(resolver, extendsResolver); + } + // A trailing slash keeps "." and ".." directories, as in tsc, so a + // sibling ".json" never matches. + extendsResolver.resolve( + {}, + currentDir, + type === PathType.Relative ? `${extendedConfig}/` : extendedConfig, + {}, + (err, extendedConfigPath) => { + // tsc rejects a bare file name like "tsconfig.base.json", but it has + // always loaded from the config's directory here, so keep that. + if (err) return loadRelative(); + loadExtended(/** @type {string} */ (extendedConfigPath)); + }, + ); + } + + /** + * Load referenced tsconfig projects and store in referenceMatchMap + * Simple implementation matching tsconfig-paths-webpack-plugin: + * Just load each reference and store independently + * @param {Resolver} resolver the resolver + * @param {string} context the context + * @param {TsconfigReference[]} references array of references + * @param {Set} fileDependencies the file dependencies + * @param {{ [baseUrl: string]: TsconfigPathsData }} referenceMatchMap the map to populate + * @param {(err: Error | null) => void} callback callback + * @param {Set=} visitedRefPaths visited reference config paths (for circular reference detection) + * @returns {void} + */ + _loadTsconfigReferences( + resolver, + context, + references, + fileDependencies, + referenceMatchMap, + callback, + visitedRefPaths, + ) { + if (references.length === 0) return callback(null); + + const visited = visitedRefPaths || new Set(); + let pending = references.length; + const finishOne = () => { + if (--pending === 0) callback(null); + }; + + for (const ref of references) { + const refPath = substituteConfigDir(ref.path, context); + const refConfigPath = resolver.join( + resolver.join(context, refPath), + DEFAULT_CONFIG_FILE, + ); + + if (visited.has(refConfigPath)) { + finishOne(); + continue; + } + visited.add(refConfigPath); + + this._loadTsconfig( + resolver, + refConfigPath, + fileDependencies, + undefined, + (err, refConfig) => { + // Failures are swallowed to match tsconfig-paths-webpack-plugin: + // a broken reference must not abort the main project's resolution. + if (err) return finishOne(); + + const cfg = /** @type {Tsconfig} */ (refConfig); + if (cfg.compilerOptions && cfg.compilerOptions.paths) { + const refContext = resolver.dirname(refConfigPath); + + referenceMatchMap[refContext] = tsconfigPathsToResolveOptions( + refContext, + cfg.compilerOptions.paths || {}, + resolver, + cfg.compilerOptions.baseUrl, + cfg.compilerOptions.pathsBasePath, + ); + } + + if (this.references === "auto" && Array.isArray(cfg.references)) { + this._loadTsconfigReferences( + resolver, + resolver.dirname(refConfigPath), + cfg.references, + fileDependencies, + referenceMatchMap, + finishOne, + visited, + ); + } else { + finishOne(); + } + }, + ); + } + } + + /** + * Load tsconfig.json with extends support + * @param {Resolver} resolver the resolver + * @param {string} configFilePath absolute path to tsconfig.json + * @param {Set} fileDependencies the file dependencies + * @param {Set | undefined} visitedConfigPaths config paths being loaded (for circular extends detection) + * @param {(err: Error | null, result?: Tsconfig) => void} callback callback + * @returns {void} + */ + _loadTsconfig( + resolver, + configFilePath, + fileDependencies, + visitedConfigPaths, + callback, + ) { + const visited = visitedConfigPaths || new Set(); + + if (visited.has(configFilePath)) { + return callback(null, /** @type {Tsconfig} */ ({})); + } + visited.add(configFilePath); + + readJson( + resolver.fileSystem, + configFilePath, + READ_JSON_OPTIONS, + (err, parsed) => { + if (err) return callback(/** @type {Error} */ (err)); + + let config = /** @type {Tsconfig} */ (parsed); + fileDependencies.add(configFilePath); + + // Remember where `paths` is declared, so that paths inherited + // through `extends` resolve relative to their own config file + if (config.compilerOptions && config.compilerOptions.paths) { + config = { + ...config, + compilerOptions: { + ...config.compilerOptions, + pathsBasePath: resolver.dirname(configFilePath), + }, + }; + } + + const extendedConfig = config.extends; + if (!extendedConfig) return callback(null, config); + + if (!Array.isArray(extendedConfig)) { + this._loadTsconfigFromExtends( + resolver, + configFilePath, + extendedConfig, + fileDependencies, + visited, + (extErr, extendedTsconfig) => { + if (extErr) return callback(extErr); + callback( + null, + mergeTsconfigs( + /** @type {Tsconfig} */ (extendedTsconfig), + config, + ), + ); + }, + ); + return; + } + + /** @type {Tsconfig} */ + let base = {}; + let i = 0; + const next = () => { + if (i >= extendedConfig.length) { + return callback(null, mergeTsconfigs(base, config)); + } + this._loadTsconfigFromExtends( + resolver, + configFilePath, + extendedConfig[i++], + fileDependencies, + visited, + (extErr, extendedTsconfig) => { + if (extErr) return callback(extErr); + base = mergeTsconfigs( + base, + /** @type {Tsconfig} */ (extendedTsconfig), + ); + next(); + }, + ); + }; + next(); + }, + ); + } +}; diff --git a/dg-ui/node_modules/enhanced-resolve/lib/UnsafeCachePlugin.js b/dg-ui/node_modules/enhanced-resolve/lib/UnsafeCachePlugin.js new file mode 100644 index 0000000..d661c1c --- /dev/null +++ b/dg-ui/node_modules/enhanced-resolve/lib/UnsafeCachePlugin.js @@ -0,0 +1,200 @@ +/* + MIT License http://www.opensource.org/licenses/mit-license.php + Author Tobias Koppers @sokra +*/ + +"use strict"; + +const { isRelativeRequest } = require("./util/path"); + +/** @typedef {import("./Resolver")} Resolver */ +/** @typedef {import("./Resolver").ResolveRequest} ResolveRequest */ +/** @typedef {import("./Resolver").ResolveStepHook} ResolveStepHook */ +/** @typedef {import("./Resolver").ResolveContextYield} ResolveContextYield */ +/** @typedef {{ [k: string]: undefined | ResolveRequest | ResolveRequest[] }} Cache */ + +/** + * @param {string} relativePath relative path from package root + * @param {string} request relative request + * @param {Resolver} resolver resolver instance + * @returns {string} normalized request with a preserved leading dot + */ +function joinRelativePreservingLeadingDot(relativePath, request, resolver) { + const normalized = resolver.join(relativePath, request); + return isRelativeRequest(normalized) ? normalized : `./${normalized}`; +} + +/** + * @param {ResolveRequest} request request + * @returns {string | false | undefined} normalized path + */ +function getCachePath(request) { + if (request.descriptionFileRoot && !request.module) { + return request.descriptionFileRoot; + } + return request.path; +} + +/** + * @param {ResolveRequest} request request + * @param {Resolver} resolver resolver instance + * @returns {string | undefined} normalized request string + */ +function getCacheRequest(request, resolver) { + const requestString = request.request; + if ( + !requestString || + !request.relativePath || + !isRelativeRequest(requestString) + ) { + return requestString; + } + return joinRelativePreservingLeadingDot( + request.relativePath, + requestString, + resolver, + ); +} + +// Cache-key separator: `\0` is safe because paths, requests, queries and +// fragments produced by `parseIdentifier` never contain a raw NUL (the +// \0-escape in identifier.js is decoded back to the original char), and the +// context, when included, is passed through `JSON.stringify`, which escapes +// any NUL to \u0000. +// const SEP = "\0"; + +/** + * Build the cache id for a request. Called on every `described-resolve` + * invocation when `unsafeCache` is on, so it's a hot path. + * + * Equivalent in meaning to the previous `JSON.stringify({ ... })` form, but + * ~3–5× faster since we avoid the object allocation and JSON serializer for + * the fields that are already plain strings. + * @param {string} type type of cache + * @param {ResolveRequest} request request + * @param {boolean} withContext cache with context? + * @param {Resolver} resolver resolver instance + * @returns {string} cache id + */ +function getCacheId(type, request, withContext, resolver) { + // TODO use it in the next major release, it is faster + // const contextPart = withContext ? JSON.stringify(request.context) : ""; + // const path = getCachePath(request); + // const cacheRequest = getCacheRequest(request, resolver); + // return ( + // type + + // SEP + + // contextPart + + // SEP + + // (path || "") + + // SEP + + // (request.query || "") + + // SEP + + // (request.fragment || "") + + // SEP + + // (cacheRequest || "") + // ); + + return JSON.stringify({ + type, + context: withContext ? request.context : "", + path: getCachePath(request), + query: request.query, + fragment: request.fragment, + request: getCacheRequest(request, resolver), + }); +} + +module.exports = class UnsafeCachePlugin { + /** + * @param {string | ResolveStepHook} source source + * @param {(request: ResolveRequest) => boolean} filterPredicate filterPredicate + * @param {Cache} cache cache + * @param {boolean} withContext withContext + * @param {string | ResolveStepHook} target target + */ + constructor(source, filterPredicate, cache, withContext, target) { + this.source = source; + this.filterPredicate = filterPredicate; + this.withContext = withContext; + this.cache = cache; + this.target = target; + } + + /** + * @param {Resolver} resolver the resolver + * @returns {void} + */ + apply(resolver) { + const target = resolver.ensureHook(this.target); + resolver + .getHook(this.source) + .tapAsync("UnsafeCachePlugin", (request, resolveContext, callback) => { + if (!this.filterPredicate(request)) { + return resolver.doResolve( + target, + request, + null, + resolveContext, + callback, + ); + } + const isYield = typeof resolveContext.yield === "function"; + const cacheId = getCacheId( + isYield ? "yield" : "default", + request, + this.withContext, + resolver, + ); + const cacheEntry = this.cache[cacheId]; + if (cacheEntry) { + if (isYield) { + const yield_ = + /** @type {ResolveContextYield} */ + (resolveContext.yield); + if (Array.isArray(cacheEntry)) { + for (const result of cacheEntry) yield_(result); + } else { + yield_(cacheEntry); + } + return callback(null, null); + } + return callback(null, /** @type {ResolveRequest} */ (cacheEntry)); + } + + /** @type {ResolveContextYield | undefined} */ + let yieldFn; + /** @type {ResolveContextYield | undefined} */ + let yield_; + /** @type {ResolveRequest[]} */ + const yieldResult = []; + if (isYield) { + yieldFn = resolveContext.yield; + yield_ = (result) => { + yieldResult.push(result); + }; + } + + resolver.doResolve( + target, + request, + null, + yield_ ? { ...resolveContext, yield: yield_ } : resolveContext, + (err, result) => { + if (err) return callback(err); + if (isYield) { + if (result) yieldResult.push(result); + for (const result of yieldResult) { + /** @type {ResolveContextYield} */ + (yieldFn)(result); + } + this.cache[cacheId] = yieldResult; + return callback(null, null); + } + if (result) return callback(null, (this.cache[cacheId] = result)); + callback(); + }, + ); + }); + } +}; diff --git a/dg-ui/node_modules/enhanced-resolve/lib/UseFilePlugin.js b/dg-ui/node_modules/enhanced-resolve/lib/UseFilePlugin.js new file mode 100644 index 0000000..f81c27f --- /dev/null +++ b/dg-ui/node_modules/enhanced-resolve/lib/UseFilePlugin.js @@ -0,0 +1,55 @@ +/* + MIT License http://www.opensource.org/licenses/mit-license.php + Author Tobias Koppers @sokra +*/ + +"use strict"; + +/** @typedef {import("./Resolver")} Resolver */ +/** @typedef {import("./Resolver").ResolveRequest} ResolveRequest */ +/** @typedef {import("./Resolver").ResolveStepHook} ResolveStepHook */ + +module.exports = class UseFilePlugin { + /** + * @param {string | ResolveStepHook} source source + * @param {string} filename filename + * @param {string | ResolveStepHook} target target + */ + constructor(source, filename, target) { + this.source = source; + this.filename = filename; + this.target = target; + } + + /** + * @param {Resolver} resolver the resolver + * @returns {void} + */ + apply(resolver) { + const target = resolver.ensureHook(this.target); + resolver + .getHook(this.source) + .tapAsync("UseFilePlugin", (request, resolveContext, callback) => { + const filePath = resolver.join( + /** @type {string} */ (request.path), + this.filename, + ); + + /** @type {ResolveRequest} */ + const obj = { + ...request, + path: filePath, + relativePath: + request.relativePath && + resolver.join(request.relativePath, this.filename), + }; + resolver.doResolve( + target, + obj, + `using path: ${filePath}`, + resolveContext, + callback, + ); + }); + } +}; diff --git a/dg-ui/node_modules/enhanced-resolve/lib/createInnerContext.js b/dg-ui/node_modules/enhanced-resolve/lib/createInnerContext.js new file mode 100644 index 0000000..226d098 --- /dev/null +++ b/dg-ui/node_modules/enhanced-resolve/lib/createInnerContext.js @@ -0,0 +1,56 @@ +/* + MIT License http://www.opensource.org/licenses/mit-license.php + Author Tobias Koppers @sokra +*/ + +"use strict"; + +/** @typedef {import("./Resolver").ResolveContext} ResolveContext */ + +/** + * Build the `ResolveContext` passed into the next hook in the chain. + * + * The caller — `Resolver.doResolve` — runs on every resolve step, so we + * want to allocate as little as possible here. Previously the caller + * constructed a temporary `{ log, yield, fileDependencies, ... }` literal + * and handed it to this helper, which then copied those same fields into + * a second fresh object. That's two allocations per step for what is + * effectively a struct copy with one mutated field (`stack`) and one + * optionally-wrapped field (`log`). Taking the parent context and the + * two things we actually want to change (stack, message) as separate + * arguments lets us allocate exactly one inner context. + * @param {ResolveContext} parent parent resolve context to inherit dependency sets / yield from + * @param {ResolveContext["stack"]} stack new stack tip for the nested call + * @param {null | string} message log message prefix for this step + * @returns {ResolveContext} inner context + */ +module.exports = function createInnerContext(parent, stack, message) { + const parentLog = parent.log; + let innerLog; + if (parentLog) { + if (message) { + let messageReported = false; + /** + * @param {string} msg message + */ + innerLog = (msg) => { + if (!messageReported) { + parentLog(message); + messageReported = true; + } + parentLog(` ${msg}`); + }; + } else { + innerLog = parentLog; + } + } + + return { + log: innerLog, + yield: parent.yield, + fileDependencies: parent.fileDependencies, + contextDependencies: parent.contextDependencies, + missingDependencies: parent.missingDependencies, + stack, + }; +}; diff --git a/dg-ui/node_modules/enhanced-resolve/lib/forEachBail.js b/dg-ui/node_modules/enhanced-resolve/lib/forEachBail.js new file mode 100644 index 0000000..ec02184 --- /dev/null +++ b/dg-ui/node_modules/enhanced-resolve/lib/forEachBail.js @@ -0,0 +1,50 @@ +/* + MIT License http://www.opensource.org/licenses/mit-license.php + Author Tobias Koppers @sokra +*/ + +"use strict"; + +/** @typedef {import("./Resolver").ResolveRequest} ResolveRequest */ + +/** + * @template T + * @template Z + * @callback Iterator + * @param {T} item item + * @param {(err?: null | Error, result?: null | Z) => void} callback callback + * @param {number} i index + * @returns {void} + */ + +/** + * @template T + * @template Z + * @param {T[]} array array + * @param {Iterator} iterator iterator + * @param {(err?: null | Error, result?: null | Z, i?: number) => void} callback callback after all items are iterated + * @returns {void} + */ +module.exports = function forEachBail(array, iterator, callback) { + if (array.length === 0) return callback(); + + let i = 0; + const next = () => { + /** @type {boolean | undefined} */ + let loop; + iterator( + array[i++], + (err, result) => { + if (err || result !== undefined || i >= array.length) { + return callback(err, result, i); + } + if (loop === false) while (next()); + loop = true; + }, + i, + ); + if (!loop) loop = false; + return loop; + }; + while (next()); +}; diff --git a/dg-ui/node_modules/enhanced-resolve/lib/getInnerRequest.js b/dg-ui/node_modules/enhanced-resolve/lib/getInnerRequest.js new file mode 100644 index 0000000..affa6c4 --- /dev/null +++ b/dg-ui/node_modules/enhanced-resolve/lib/getInnerRequest.js @@ -0,0 +1,41 @@ +/* + MIT License http://www.opensource.org/licenses/mit-license.php + Author Tobias Koppers @sokra +*/ + +"use strict"; + +const { isRelativeRequest } = require("./util/path"); + +/** @typedef {import("./Resolver")} Resolver */ +/** @typedef {import("./Resolver").ResolveRequest} ResolveRequest */ + +/** + * @param {Resolver} resolver resolver + * @param {ResolveRequest} request string + * @returns {string} inner request + */ +module.exports = function getInnerRequest(resolver, request) { + if ( + typeof request.__innerRequest === "string" && + request.__innerRequest_request === request.request && + request.__innerRequest_relativePath === request.relativePath + ) { + return request.__innerRequest; + } + /** @type {string | undefined} */ + let innerRequest; + if (request.request) { + innerRequest = request.request; + if (request.relativePath && isRelativeRequest(innerRequest)) { + innerRequest = resolver.join(request.relativePath, innerRequest); + } + } else { + innerRequest = request.relativePath; + } + // eslint-disable-next-line camelcase + request.__innerRequest_request = request.request; + // eslint-disable-next-line camelcase + request.__innerRequest_relativePath = request.relativePath; + return (request.__innerRequest = /** @type {string} */ (innerRequest)); +}; diff --git a/dg-ui/node_modules/enhanced-resolve/lib/getPaths.js b/dg-ui/node_modules/enhanced-resolve/lib/getPaths.js new file mode 100644 index 0000000..4e40051 --- /dev/null +++ b/dg-ui/node_modules/enhanced-resolve/lib/getPaths.js @@ -0,0 +1,87 @@ +/* + MIT License http://www.opensource.org/licenses/mit-license.php + Author Tobias Koppers @sokra +*/ + +"use strict"; + +/** @typedef {import("./Resolver").FileSystem} FileSystem */ +/** @typedef {{ paths: string[], segments: string[] }} GetPathsResult */ + +/** + * Walk `path` from tip to root, returning every ancestor directory (plus the + * input itself) in `paths`, and each corresponding segment name in `segments`. + * + * The return value may be shared across callers via `getPathsCached` — treat + * it as read-only. Callers that need to mutate (currently only + * `SymlinkPlugin`) should `slice()` the arrays locally before writing. + * @param {string} path path + * @returns {GetPathsResult} paths and segments + */ +function getPaths(path) { + if (path === "/") return { paths: ["/"], segments: [""] }; + const parts = path.split(/(.*?[\\/]+)/); + const paths = [path]; + const segments = [parts[parts.length - 1]]; + let part = parts[parts.length - 1]; + path = path.slice(0, Math.max(0, path.length - part.length - 1)); + for (let i = parts.length - 2; i > 2; i -= 2) { + paths.push(path); + part = parts[i]; + path = path.slice(0, Math.max(0, path.length - part.length)) || "/"; + segments.push(part.slice(0, -1)); + } + [, part] = parts; + segments.push(part); + paths.push(part); + return { + paths, + segments, + }; +} + +/** + * Per-filesystem memoization of `getPaths`. Kept in a standalone WeakMap + * rather than being hung off `resolver.pathCache` so that adding this cache + * does not change the hidden-class shape of `pathCache` — which is accessed + * on the hot path of every resolve as `resolver.pathCache.{join,dirname, + * basename}.fn(...)`. CodSpeed caught that shape change as a ~1–2% + * instruction-count regression on `cache-predicate`, so we keep pathCache + * shape-stable by owning this cache here instead. + * + * The cache lifetime is tied to the filesystem object (same invariant as + * `_pathCacheByFs` in `Resolver.js`): when the user swaps filesystems the + * entries become unreachable and get collected. + * @type {WeakMap>} + */ +const _getPathsCacheByFs = new WeakMap(); + +/** + * Memoized `getPaths`. The returned object is shared across callers — do + * not mutate the `paths` or `segments` arrays in-place; `slice()` first if + * you need a mutable copy. + * @param {FileSystem} fileSystem filesystem used as the cache namespace + * @param {string} path path + * @returns {GetPathsResult} paths and segments + */ +function getPathsCached(fileSystem, path) { + let cache = _getPathsCacheByFs.get(fileSystem); + if (cache === undefined) { + cache = new Map(); + _getPathsCacheByFs.set(fileSystem, cache); + } else { + const cached = cache.get(path); + if (cached !== undefined) return cached; + } + const { paths, segments } = getPaths(path); + // `push` leaves a store sized for 17 entries while a path has a handful, and + // what is cached here is kept for the filesystem's lifetime. A copy sizes both + // to what they hold, and copying a pushed array keeps them packed, which is + // the element kind every reader of them is compiled for. + const result = { paths: [...paths], segments: [...segments] }; + cache.set(path, result); + return result; +} + +module.exports = getPaths; +module.exports.getPathsCached = getPathsCached; diff --git a/dg-ui/node_modules/enhanced-resolve/lib/index.js b/dg-ui/node_modules/enhanced-resolve/lib/index.js new file mode 100644 index 0000000..4902a75 --- /dev/null +++ b/dg-ui/node_modules/enhanced-resolve/lib/index.js @@ -0,0 +1,315 @@ +/* + MIT License http://www.opensource.org/licenses/mit-license.php + Author Tobias Koppers @sokra +*/ + +"use strict"; + +const memoize = require("./util/memoize"); + +/** @typedef {import("./CachedInputFileSystem")} CachedInputFileSystem */ +/** @typedef {import("./CachedInputFileSystem").BaseFileSystem} BaseFileSystem */ +/** @typedef {import("./CloneBasenamePlugin")} CloneBasenamePlugin */ +/** @typedef {import("./LogInfoPlugin")} LogInfoPlugin */ +/** @typedef {import("./PnpPlugin").PnpApiImpl} PnpApi */ +/** @typedef {import("./Resolver")} Resolver */ +/** @typedef {import("./Resolver").Context} Context */ +/** @typedef {import("./Resolver").FileSystem} FileSystem */ +/** @typedef {import("./Resolver").ResolveCallback} ResolveCallback */ +/** @typedef {import("./Resolver").ResolveContext} ResolveContext */ +/** @typedef {import("./Resolver").ResolveRequest} ResolveRequest */ +/** @typedef {import("./Resolver").SyncFileSystem} SyncFileSystem */ +/** @typedef {import("./ResolverFactory").Plugin} Plugin */ +/** @typedef {import("./ResolverFactory").UserResolveOptions} ResolveOptions */ +/** @typedef {import("./TsconfigPathsPlugin")} TsconfigPathsPlugin */ +/** @typedef {import("./UnsafeCachePlugin").Cache} UnsafeCache */ + +/** + * @typedef {{ + * (context: Context, parent: string | URL, specifier: string | URL, resolveContext: ResolveContext, callback: ResolveCallback): void, + * (context: Context, parent: string | URL, specifier: string | URL, callback: ResolveCallback): void, + * (parent: string | URL, specifier: string | URL, resolveContext: ResolveContext, callback: ResolveCallback): void, + * (parent: string | URL, specifier: string | URL, callback: ResolveCallback): void, + * }} ResolveFunctionAsync + */ + +/** + * @typedef {{ + * (context: Context, parent: string | URL, specifier: string | URL, resolveContext?: ResolveContext): string | false, + * (parent: string | URL, specifier: string | URL, resolveContext?: ResolveContext): string | false, + * }} ResolveFunction + */ + +/** + * @typedef {{ + * (context: Context, parent: string | URL, specifier: string | URL, resolveContext?: ResolveContext): Promise, + * (parent: string | URL, specifier: string | URL, resolveContext?: ResolveContext): Promise, + * }} ResolveFunctionPromise + */ + +const getCachedFileSystem = memoize(() => require("./CachedInputFileSystem")); + +const getNodeFileSystem = memoize(() => { + const fs = require("graceful-fs"); + + const CachedInputFileSystem = getCachedFileSystem(); + + return new CachedInputFileSystem(fs, 4000); +}); +const getNodeContext = memoize(() => ({ + environments: ["node+es3+es5+process+native"], +})); + +const getResolverFactory = memoize(() => require("./ResolverFactory")); + +const getAsyncResolver = memoize(() => + getResolverFactory().createResolver({ + conditionNames: ["node"], + extensions: [".js", ".json", ".node"], + fileSystem: getNodeFileSystem(), + }), +); + +/** + * @type {ResolveFunctionAsync} + */ +const resolve = + /** + * @param {object | string | URL} context context + * @param {string | URL} parent parent path + * @param {string | URL | ResolveContext | ResolveCallback} specifier specifier to resolve + * @param {ResolveContext | ResolveCallback=} resolveContext resolve context + * @param {ResolveCallback=} callback callback + */ + (context, parent, specifier, resolveContext, callback) => { + if (typeof context === "string" || context instanceof URL) { + callback = /** @type {ResolveCallback} */ (resolveContext); + resolveContext = /** @type {ResolveContext} */ (specifier); + specifier = parent; + parent = context; + context = getNodeContext(); + } + if (typeof callback !== "function") { + callback = /** @type {ResolveCallback} */ (resolveContext); + } + getAsyncResolver().resolve( + context, + parent, + /** @type {string} */ (specifier), + /** @type {ResolveContext} */ (resolveContext), + /** @type {ResolveCallback} */ (callback), + ); + }; + +const getSyncResolver = memoize(() => + getResolverFactory().createResolver({ + conditionNames: ["node"], + extensions: [".js", ".json", ".node"], + useSyncFileSystemCalls: true, + fileSystem: getNodeFileSystem(), + }), +); + +/** + * @type {ResolveFunction} + */ +const resolveSync = + /** + * @param {object | string | URL} context context + * @param {string | URL} parent parent path + * @param {string | URL | ResolveContext | undefined} specifier specifier to resolve + * @param {ResolveContext=} resolveContext resolve context + * @returns {string | false} resolved path + */ + (context, parent, specifier, resolveContext) => { + if (typeof context === "string" || context instanceof URL) { + resolveContext = /** @type {ResolveContext} */ (specifier); + specifier = parent; + parent = context; + context = getNodeContext(); + } + return getSyncResolver().resolveSync( + context, + parent, + /** @type {string} */ (specifier), + /** @type {ResolveContext} */ (resolveContext), + ); + }; + +/** + * @type {ResolveFunctionPromise} + */ +const resolvePromise = + /** + * @param {object | string | URL} context context + * @param {string | URL} parent parent path + * @param {string | URL | ResolveContext | undefined} specifier specifier to resolve + * @param {ResolveContext=} resolveContext resolve context + * @returns {Promise} resolved path + */ + (context, parent, specifier, resolveContext) => { + if (typeof context === "string" || context instanceof URL) { + resolveContext = /** @type {ResolveContext} */ (specifier); + specifier = parent; + parent = context; + context = getNodeContext(); + } + return getAsyncResolver().resolvePromise( + context, + parent, + /** @type {string} */ (specifier), + /** @type {ResolveContext} */ (resolveContext), + ); + }; + +/** @typedef {Omit & Partial>} ResolveOptionsOptionalFS */ + +/** + * @param {ResolveOptionsOptionalFS} options Resolver options + * @returns {ResolveFunctionAsync} Resolver function + */ +function create(options) { + const resolver = getResolverFactory().createResolver({ + ...options, + fileSystem: options.fileSystem || getNodeFileSystem(), + }); + /** + * @param {object | string | URL} context Custom context + * @param {string | URL} parent Base/parent path + * @param {string | URL | ResolveContext | ResolveCallback} specifier Specifier to resolve + * @param {ResolveContext | ResolveCallback=} resolveContext Resolve context + * @param {ResolveCallback=} callback Result callback + */ + return function create(context, parent, specifier, resolveContext, callback) { + if (typeof context === "string" || context instanceof URL) { + callback = /** @type {ResolveCallback} */ (resolveContext); + resolveContext = /** @type {ResolveContext} */ (specifier); + specifier = parent; + parent = context; + context = getNodeContext(); + } + if (typeof callback !== "function") { + callback = /** @type {ResolveCallback} */ (resolveContext); + } + resolver.resolve( + context, + parent, + /** @type {string} */ (specifier), + /** @type {ResolveContext} */ (resolveContext), + callback, + ); + }; +} + +/** + * @param {ResolveOptionsOptionalFS} options Resolver options + * @returns {ResolveFunction} Resolver function + */ +function createSync(options) { + const resolver = getResolverFactory().createResolver({ + useSyncFileSystemCalls: true, + ...options, + fileSystem: options.fileSystem || getNodeFileSystem(), + }); + /** + * @param {object | string | URL} context custom context + * @param {string | URL} parent base/parent path + * @param {string | URL | ResolveContext | undefined} specifier specifier to resolve + * @param {ResolveContext=} resolveContext Resolve context + * @returns {string | false} Resolved path or false + */ + return function createSync(context, parent, specifier, resolveContext) { + if (typeof context === "string" || context instanceof URL) { + resolveContext = /** @type {ResolveContext} */ (specifier); + specifier = parent; + parent = context; + context = getNodeContext(); + } + return resolver.resolveSync( + context, + parent, + /** @type {string} */ (specifier), + /** @type {ResolveContext} */ (resolveContext), + ); + }; +} + +/** + * @param {ResolveOptionsOptionalFS} options Resolver options + * @returns {ResolveFunctionPromise} Resolver function + */ +function createPromise(options) { + const resolver = getResolverFactory().createResolver({ + ...options, + fileSystem: options.fileSystem || getNodeFileSystem(), + }); + /** + * @param {object | string | URL} context Custom context + * @param {string | URL} parent Base/parent path + * @param {string | URL | ResolveContext | undefined} specifier Specifier to resolve + * @param {ResolveContext=} resolveContext Resolve context + * @returns {Promise} resolved path + */ + return function createPromise(context, parent, specifier, resolveContext) { + if (typeof context === "string" || context instanceof URL) { + resolveContext = /** @type {ResolveContext} */ (specifier); + specifier = parent; + parent = context; + context = getNodeContext(); + } + return resolver.resolvePromise( + context, + parent, + /** @type {string} */ (specifier), + /** @type {ResolveContext} */ (resolveContext), + ); + }; +} + +/** + * @template A + * @template B + * @param {A} obj input a + * @param {B} exports input b + * @returns {A & B} merged + */ +const mergeExports = (obj, exports) => { + const descriptors = Object.getOwnPropertyDescriptors(exports); + Object.defineProperties(obj, descriptors); + return /** @type {A & B} */ (Object.freeze(obj)); +}; + +module.exports = mergeExports(resolve, { + get sync() { + return resolveSync; + }, + get promise() { + return resolvePromise; + }, + create: mergeExports(create, { + get sync() { + return createSync; + }, + get promise() { + return createPromise; + }, + }), + get ResolverFactory() { + return getResolverFactory(); + }, + get CachedInputFileSystem() { + return getCachedFileSystem(); + }, + get CloneBasenamePlugin() { + return require("./CloneBasenamePlugin"); + }, + get LogInfoPlugin() { + return require("./LogInfoPlugin"); + }, + get TsconfigPathsPlugin() { + return require("./TsconfigPathsPlugin"); + }, + get forEachBail() { + return require("./forEachBail"); + }, +}); diff --git a/dg-ui/node_modules/enhanced-resolve/lib/util/entrypoints.js b/dg-ui/node_modules/enhanced-resolve/lib/util/entrypoints.js new file mode 100644 index 0000000..0b834f8 --- /dev/null +++ b/dg-ui/node_modules/enhanced-resolve/lib/util/entrypoints.js @@ -0,0 +1,849 @@ +/* + MIT License http://www.opensource.org/licenses/mit-license.php + Author Ivan Kopeykin @vankop +*/ + +"use strict"; + +const { parseIdentifier } = require("./identifier"); + +/** @typedef {string | (string | ConditionalMapping)[]} DirectMapping */ +/** @typedef {{ [k: string]: MappingValue }} ConditionalMapping */ +/** @typedef {ConditionalMapping | DirectMapping | null} MappingValue */ +/** @typedef {Record | ConditionalMapping | DirectMapping} ExportsField */ +/** @typedef {Record} ImportsField */ + +/** + * Processing exports/imports field + * @callback FieldProcessor + * @param {string} request request + * @param {Set} conditionNames condition names + * @returns {[string[], string | null]} resolved paths with used field + */ + +/* +Example exports field: +{ + ".": "./main.js", + "./feature": { + "browser": "./feature-browser.js", + "default": "./feature.js" + } +} +Terminology: + +Enhanced-resolve name keys ("." and "./feature") as exports field keys. + +If value is string or string[], mapping is called as a direct mapping +and value called as a direct export. + +If value is key-value object, mapping is called as a conditional mapping +and value called as a conditional export. + +Key in conditional mapping is called condition name. + +Conditional mapping nested in another conditional mapping is called nested mapping. + +---------- + +Example imports field: +{ + "#a": "./main.js", + "#moment": { + "browser": "./moment/index.js", + "default": "moment" + }, + "#moment/": { + "browser": "./moment/", + "default": "moment/" + } +} +Terminology: + +Enhanced-resolve name keys ("#a" and "#moment/", "#moment") as imports field keys. + +If value is string or string[], mapping is called as a direct mapping +and value called as a direct export. + +If value is key-value object, mapping is called as a conditional mapping +and value called as a conditional export. + +Key in conditional mapping is called condition name. + +Conditional mapping nested in another conditional mapping is called nested mapping. + +*/ + +const slashCode = "/".charCodeAt(0); +const dotCode = ".".charCodeAt(0); +const hashCode = "#".charCodeAt(0); +const patternRegEx = /\*/g; +const DOLLAR_ESCAPE_RE = /\$/g; + +/** @typedef {Record} RecordMapping */ + +/** + * Cached `Object.keys()` for objects whose shape does not change after the + * first observation — i.e. parsed `package.json` fields and the nested + * conditional mappings inside them. `Object.keys` allocates a fresh array + * on every call; since `findMatch` / `conditionalMapping` run on every + * bare-specifier resolve, the allocation adds up quickly. + * @type {WeakMap} + */ +const _keysCache = new WeakMap(); + +/** + * @param {RecordMapping} obj object to read keys from + * @returns {string[]} cached keys array (DO NOT mutate) + */ +function cachedKeys(obj) { + let keys = _keysCache.get(obj); + if (keys === undefined) { + keys = Object.keys(obj); + _keysCache.set(obj, keys); + } + return keys; +} + +/** + * Per-key precomputed info used by `findMatch`. Equivalent to what the + * previous implementation recomputed inline on every resolve. + * @typedef {object} FieldKeyInfo + * @property {string} key the original key + * @property {number} patternIndex position of the single "*" in the key, or -1 when absent + * @property {string} wildcardPrefix substring before "*" (empty when patternIndex === -1) + * @property {string} wildcardSuffix substring after "*" (empty when patternIndex === -1) + * @property {boolean} isLegacySubpath true when key is a legacy `./foo/`-style folder key with no "*" + * @property {boolean} isPattern true when key contains "*" + * @property {boolean} isSubpathMapping true when key ends with "/" + * @property {boolean} isValidPattern true when key has at most one "*" + */ + +/** + * Cached per-field key metadata, keyed by the exports/imports field + * object. Computed lazily on first `findMatch` call and reused forever. + * Safe because `package.json` fields are immutable JSON values. + * @type {WeakMap} + */ +const _fieldKeyInfoCache = new WeakMap(); + +/** + * @param {ExportsField | ImportsField} field field object + * @returns {FieldKeyInfo[]} precomputed per-key info + */ +function getFieldKeyInfos(field) { + const fieldKey = /** @type {RecordMapping} */ (field); + let infos = _fieldKeyInfoCache.get(fieldKey); + if (infos !== undefined) return infos; + const keys = Object.getOwnPropertyNames(field); + infos = Array.from({ length: keys.length }); + for (let i = 0; i < keys.length; i++) { + const key = keys[i]; + const patternIndex = key.indexOf("*"); + // `isValidPattern` is true when the key has at most one `*`. Searching + // from `patternIndex + 1` stops as soon as a second `*` is found, so + // we avoid the full-string scan that `lastIndexOf` would do — and the + // single-star common case finishes in one pass. + const isValidPattern = + patternIndex === -1 || !key.includes("*", patternIndex + 1); + const keyLen = key.length; + const endsWithSlash = + keyLen > 0 && key.charCodeAt(keyLen - 1) === slashCode; + infos[i] = { + key, + patternIndex, + wildcardPrefix: patternIndex === -1 ? "" : key.slice(0, patternIndex), + wildcardSuffix: patternIndex === -1 ? "" : key.slice(patternIndex + 1), + isLegacySubpath: patternIndex === -1 && endsWithSlash, + isPattern: patternIndex !== -1, + isSubpathMapping: endsWithSlash, + isValidPattern, + }; + } + _fieldKeyInfoCache.set(fieldKey, infos); + return infos; +} + +/** + * @param {string} a first string + * @param {string} b second string + * @returns {number} compare result + */ +function patternKeyCompare(a, b) { + const aPatternIndex = a.indexOf("*"); + const bPatternIndex = b.indexOf("*"); + const baseLenA = aPatternIndex === -1 ? a.length : aPatternIndex + 1; + const baseLenB = bPatternIndex === -1 ? b.length : bPatternIndex + 1; + + if (baseLenA > baseLenB) return -1; + if (baseLenB > baseLenA) return 1; + if (aPatternIndex === -1) return 1; + if (bPatternIndex === -1) return -1; + if (a.length > b.length) return -1; + if (b.length > a.length) return 1; + + return 0; +} + +/** @typedef {[MappingValue, string, boolean, boolean, string] | null} MatchTuple */ + +/** + * Per-field memoization of `findMatch(request, field)`. For a given field + * the result depends only on the `request` string (it does NOT depend on + * `conditionNames` — that's applied separately by `conditionalMapping`), + * so we can cache the tuple keyed by request. + * + * Typical build traffic runs the same request through the resolver + * repeatedly (same import re-resolved from different source files, module + * graph traversals that revisit a package, etc.), and every one of those + * hits walks the same key list and allocates the same tuple. Caching the + * tuple turns the second-and-onward call into a single Map lookup. + * + * Keyed on the field object via a module-level `WeakMap`, so the cache + * is freed automatically when the owning description file is GC'd. + * @type {WeakMap>} + */ +const _findMatchCache = new WeakMap(); + +/** + * @param {string} request request + * @param {ExportsField | ImportsField} field exports or import field + * @returns {MatchTuple} match result (uncached) + */ +function computeFindMatch(request, field) { + const requestLen = request.length; + const requestEndsWithSlash = + requestLen > 0 && request.charCodeAt(requestLen - 1) === slashCode; + const requestHasStar = request.includes("*"); + + if ( + !requestHasStar && + !requestEndsWithSlash && + Object.prototype.hasOwnProperty.call(field, request) + ) { + const target = /** @type {{ [k: string]: MappingValue }} */ (field)[ + request + ]; + + return [target, "", false, false, request]; + } + + /** @type {string} */ + let bestMatch = ""; + /** @type {FieldKeyInfo | null} */ + let bestMatchInfo = null; + /** @type {string | undefined} */ + let bestMatchSubpath; + + const infos = getFieldKeyInfos(field); + + for (let i = 0; i < infos.length; i++) { + const info = infos[i]; + const { key, patternIndex } = info; + + if (patternIndex !== -1) { + if ( + !info.isValidPattern || + !request.startsWith(info.wildcardPrefix) || + requestLen < key.length || + !request.endsWith(info.wildcardSuffix) || + patternKeyCompare(bestMatch, key) !== 1 + ) { + continue; + } + bestMatch = key; + bestMatchInfo = info; + bestMatchSubpath = request.slice( + patternIndex, + requestLen - info.wildcardSuffix.length, + ); + } else if ( + info.isLegacySubpath && + request.startsWith(key) && + patternKeyCompare(bestMatch, key) === 1 + ) { + bestMatch = key; + bestMatchInfo = info; + bestMatchSubpath = request.slice(key.length); + } + } + + if (bestMatch === "") return null; + + const target = + /** @type {{ [k: string]: MappingValue }} */ + (field)[bestMatch]; + + return [ + target, + /** @type {string} */ (bestMatchSubpath), + /** @type {FieldKeyInfo} */ (bestMatchInfo).isSubpathMapping, + /** @type {FieldKeyInfo} */ (bestMatchInfo).isPattern, + bestMatch, + ]; +} + +/** + * Trying to match request to field + * @param {string} request request + * @param {ExportsField | ImportsField} field exports or import field + * @returns {MatchTuple} match or null, number is negative and one less when it's a folder mapping, number is request.length + 1 for direct mappings + */ +function findMatch(request, field) { + const fieldKey = /** @type {RecordMapping} */ (field); + let perRequest = _findMatchCache.get(fieldKey); + if (perRequest === undefined) { + perRequest = new Map(); + _findMatchCache.set(fieldKey, perRequest); + } else { + // `computeFindMatch` only ever returns `MatchTuple | null` — never + // `undefined` — and `Map.set(k, null)` then `Map.get(k)` returns + // `null`, not `undefined`. So `get(...) === undefined` already + // unambiguously means "not cached yet"; one Map lookup is enough, + // no follow-up `has` needed to disambiguate "cached null". + const cached = perRequest.get(request); + if (cached !== undefined) return cached; + } + + const result = computeFindMatch(request, field); + perRequest.set(request, result); + return result; +} + +/** + * Sentinel stored in the conditional-mapping cache for inputs whose walk + * returns `null` ("no condition matched"). Using a non-null marker lets the + * cache-hit path be a single `WeakMap.get()` — we distinguish + * "cached null" from "not cached yet" without a second `has` call. + */ +const NULL_RESULT = Symbol("NULL_RESULT"); + +/** + * Memoization of `conditionalMapping(mapping, conditionNames)`. The result + * depends only on the mapping object (immutable — owned by a parsed + * `package.json`) and the `conditionNames` Set (owned by the resolver's + * options and stable for its lifetime), so it is safe to cache per (mapping, + * conditionNames) pair. + * + * A conditional `exports` entry that appears inside a `directMapping` array + * (the common `"browser": [...fallback list...]` shape, plus nested + * conditions) gets walked on every resolve that traverses the parent entry. + * Without this cache each of those walks re-reads `Object.keys` on the + * mapping and re-visits every condition until one matches, even though the + * inputs are identical. + * + * Outer key is the conditional mapping itself; inner key is the condition + * Set. Both are object references, so WeakMap-of-WeakMap lets both levels + * be collected automatically when the description file or resolver go away. + * @type {WeakMap, DirectMapping | typeof NULL_RESULT>>} + */ +const _conditionalMappingCache = new WeakMap(); + +/** + * @param {ConditionalMapping} conditionalMapping_ conditional mapping + * @param {Set} conditionNames condition names + * @returns {DirectMapping | null} direct mapping if found (uncached) + */ +function computeConditionalMapping(conditionalMapping_, conditionNames) { + /** @type {[ConditionalMapping, string[], number][]} */ + const lookup = [[conditionalMapping_, cachedKeys(conditionalMapping_), 0]]; + + loop: while (lookup.length > 0) { + const top = lookup[lookup.length - 1]; + const [mapping, conditions, j] = top; + + for (let i = j; i < conditions.length; i++) { + const condition = conditions[i]; + + if (condition === "default" || conditionNames.has(condition)) { + const innerMapping = mapping[condition]; + if ( + innerMapping !== null && + typeof innerMapping === "object" && + !Array.isArray(innerMapping) + ) { + const nested = /** @type {ConditionalMapping} */ (innerMapping); + top[2] = i + 1; + lookup.push([nested, cachedKeys(nested), 0]); + continue loop; + } + + return /** @type {DirectMapping} */ (innerMapping); + } + } + + lookup.pop(); + } + + return null; +} + +/** + * @param {ConditionalMapping} conditionalMapping_ conditional mapping + * @param {Set} conditionNames condition names + * @returns {DirectMapping | null} direct mapping if found + */ +function conditionalMapping(conditionalMapping_, conditionNames) { + let perSet = _conditionalMappingCache.get(conditionalMapping_); + if (perSet !== undefined) { + const cached = perSet.get(conditionNames); + if (cached !== undefined) { + return cached === NULL_RESULT + ? null + : /** @type {DirectMapping} */ (cached); + } + } else { + perSet = new WeakMap(); + _conditionalMappingCache.set(conditionalMapping_, perSet); + } + const result = computeConditionalMapping(conditionalMapping_, conditionNames); + perSet.set(conditionNames, result === null ? NULL_RESULT : result); + return result; +} + +/** + * @param {string | undefined} remainingRequest remaining request when folder mapping, undefined for file mappings + * @param {boolean} isPattern true, if mapping is a pattern (contains "*") + * @param {boolean} isSubpathMapping true, for subpath mappings + * @param {string} mappingTarget direct export + * @param {(d: string, f: boolean) => void} assert asserting direct value + * @returns {string} mapping result + */ +function targetMapping( + remainingRequest, + isPattern, + isSubpathMapping, + mappingTarget, + assert, +) { + if (remainingRequest === undefined) { + assert(mappingTarget, false); + + return mappingTarget; + } + + if (isSubpathMapping) { + assert(mappingTarget, true); + + return mappingTarget + remainingRequest; + } + + assert(mappingTarget, false); + + let result = mappingTarget; + + if (isPattern) { + const escapedRemainder = remainingRequest.includes("$") + ? remainingRequest.replace(DOLLAR_ESCAPE_RE, "$$") + : remainingRequest; + result = result.replace(patternRegEx, escapedRemainder); + } + + return result; +} + +/** + * @param {string | undefined} remainingRequest remaining request when folder mapping, undefined for file mappings + * @param {boolean} isPattern true, if mapping is a pattern (contains "*") + * @param {boolean} isSubpathMapping true, for subpath mappings + * @param {DirectMapping | null} mappingTarget direct export + * @param {Set} conditionNames condition names + * @param {(d: string, f: boolean) => void} assert asserting direct value + * @returns {string[]} mapping result + */ +function directMapping( + remainingRequest, + isPattern, + isSubpathMapping, + mappingTarget, + conditionNames, + assert, +) { + if (mappingTarget === null) return []; + + if (typeof mappingTarget === "string") { + return [ + targetMapping( + remainingRequest, + isPattern, + isSubpathMapping, + mappingTarget, + assert, + ), + ]; + } + + /** @type {string[]} */ + const targets = []; + + for (let i = 0, len = mappingTarget.length; i < len; i++) { + const exp = mappingTarget[i]; + if (typeof exp === "string") { + targets.push( + targetMapping( + remainingRequest, + isPattern, + isSubpathMapping, + exp, + assert, + ), + ); + continue; + } + + const mapping = conditionalMapping(exp, conditionNames); + if (!mapping) continue; + const innerExports = directMapping( + remainingRequest, + isPattern, + isSubpathMapping, + mapping, + conditionNames, + assert, + ); + for (let j = 0, innerLen = innerExports.length; j < innerLen; j++) { + targets.push(innerExports[j]); + } + } + + return targets; +} + +/** @type {[string[], null]} */ +const EMPTY_NO_MATCH = /** @type {[string[], null]} */ ([[], null]); + +/** + * @param {ExportsField | ImportsField} field root + * @param {(s: string) => string} normalizeRequest Normalize request, for `imports` field it adds `#`, for `exports` field it adds `.` or `./` + * @param {(s: string) => string} assertRequest assertRequest + * @param {(s: string, f: boolean) => void} assertTarget assertTarget + * @returns {FieldProcessor} field processor + */ +function createFieldProcessor( + field, + normalizeRequest, + assertRequest, + assertTarget, +) { + return function fieldProcessor(request, conditionNames) { + const match = findMatch(normalizeRequest(assertRequest(request)), field); + + if (match === null) return EMPTY_NO_MATCH; + + const [mapping, remainingRequest, isSubpathMapping, isPattern, usedField] = + match; + + /** @type {DirectMapping | null} */ + let direct; + if ( + mapping !== null && + typeof mapping === "object" && + !Array.isArray(mapping) + ) { + direct = conditionalMapping( + /** @type {ConditionalMapping} */ (mapping), + conditionNames, + ); + if (direct === null) return EMPTY_NO_MATCH; + } else { + direct = /** @type {DirectMapping} */ (mapping); + } + + return [ + directMapping( + remainingRequest, + isPattern, + isSubpathMapping, + direct, + conditionNames, + assertTarget, + ), + usedField, + ]; + }; +} + +/** + * @param {string} request request + * @returns {string} updated request + */ +function assertExportsFieldRequest(request) { + if (request.charCodeAt(0) !== dotCode) { + throw new Error('Request should be relative path and start with "."'); + } + if (request.length === 1) return ""; + if (request.charCodeAt(1) !== slashCode) { + throw new Error('Request should be relative path and start with "./"'); + } + if (request.charCodeAt(request.length - 1) === slashCode) { + throw new Error("Only requesting file allowed"); + } + + return request.slice(2); +} + +/** + * Looks for a conditional mapping whose keys are subpaths - the "conditions + * wrapping subpaths" shape from + * https://github.com/webpack/enhanced-resolve/issues/325, which Node.js does + * not support: the subpaths are read as condition names and match nothing. + * + * Diagnostic only, and deliberately not part of building the field. Walking + * every target of every package.json would cost a full tree walk per package + * to catch a mistake almost none of them make, and rejecting the field + * outright would break packages that resolve today under some conditions. + * Callers run this once a request has already failed, where the walk is free + * relative to the error being raised anyway. + * @param {MappingValue} mapping mapping in target position + * @param {number} subpathCode leading char code that marks a subpath key + * @param {string[]} trail keys walked from the field root down to `mapping` + * @returns {{ trail: string[], keys: string[] } | null} offending mapping + */ +function findSubpathsInConditions(mapping, subpathCode, trail) { + if (mapping === null || typeof mapping !== "object") return null; + + if (Array.isArray(mapping)) { + for (let i = 0; i < mapping.length; i++) { + const found = findSubpathsInConditions(mapping[i], subpathCode, trail); + if (found) return found; + } + return null; + } + + const keys = Object.keys(mapping); + + for (let i = 0; i < keys.length; i++) { + if (keys[i].charCodeAt(0) === subpathCode) { + return { trail: [...trail], keys }; + } + } + + for (let i = 0; i < keys.length; i++) { + const key = keys[i]; + trail.push(key); + const found = findSubpathsInConditions(mapping[key], subpathCode, trail); + if (found) return found; + trail.pop(); + } + + return null; +} + +/** + * Explains why nothing matched, when the reason is a conditional mapping that + * wraps subpaths. Returns `null` when the field does not have that shape, so + * the caller keeps its ordinary "not exported" wording. + * + * Only the top-level values are descended into, never the field's own keys: + * in both forms of `exports` and in `imports` those values are targets, while + * the keys are either subpaths or - for the `exports` shorthand, where the + * whole field is one conditional mapping - condition names that + * `buildExportsField` has already checked. + * @param {ExportsField | ImportsField | null | undefined} field the field + * @param {boolean} isExports true for `exports`, false for `imports` + * @returns {string | null} explanation to append to the error, if any + */ +module.exports.explainSubpathsInConditions = + function explainSubpathsInConditions(field, isExports) { + if (field === null || typeof field !== "object" || Array.isArray(field)) { + return null; + } + + const subpathCode = isExports ? dotCode : hashCode; + const keys = Object.keys(field); + /** @type {string[]} */ + const trail = []; + /** @type {{ trail: string[], keys: string[] } | null} */ + let found = null; + + for (let i = 0; i < keys.length && !found; i++) { + trail.push(keys[i]); + found = findSubpathsInConditions( + /** @type {Record} */ (field)[keys[i]], + subpathCode, + trail, + ); + trail.pop(); + } + + if (!found) return null; + + const quote = (/** @type {string} */ key) => JSON.stringify(key); + const subpathKeys = found.keys.filter( + (key) => key.charCodeAt(0) === subpathCode, + ); + const condition = found.trail[found.trail.length - 1]; + const example = subpathKeys + .map((key) => `${quote(key)}: { ${quote(condition)}: ... }`) + .join(", "); + + return `the value at ${found.trail + .map(quote) + .join(" -> ")} is an object with subpath keys (${subpathKeys + .map(quote) + .join( + ", ", + )}), which is not supported - a condition can only map to a target or to further conditions, so those subpaths never match. Put the subpaths at the top level and nest the conditions inside them instead, e.g. { ${example} }.`; + }; + +/** + * @param {ExportsField} field exports field + * @returns {ExportsField} normalized exports field + */ +function buildExportsField(field) { + // handle syntax sugar, if exports field is direct mapping for "." + if (typeof field === "string" || Array.isArray(field)) { + return { ".": field }; + } + + const keys = Object.keys(field); + + for (let i = 0; i < keys.length; i++) { + const key = keys[i]; + + if (key.charCodeAt(0) !== dotCode) { + // handle syntax sugar, if exports field is conditional mapping for "." + if (i === 0) { + while (i < keys.length) { + const charCode = keys[i].charCodeAt(0); + if (charCode === dotCode || charCode === slashCode) { + throw new Error( + `Exports field key should be relative path and start with "." (key: ${JSON.stringify( + key, + )})`, + ); + } + i++; + } + + return { ".": field }; + } + + throw new Error( + `Exports field key should be relative path and start with "." (key: ${JSON.stringify( + key, + )})`, + ); + } + + if (key.length === 1) { + continue; + } + + if (key.charCodeAt(1) !== slashCode) { + throw new Error( + `Exports field key should be relative path and start with "./" (key: ${JSON.stringify( + key, + )})`, + ); + } + } + + return field; +} + +/** + * @param {string} exp export target + * @param {boolean} expectFolder is folder expected + */ +function assertExportTarget(exp, expectFolder) { + const parsedIdentifier = parseIdentifier(exp); + + if (!parsedIdentifier) { + return; + } + + const [relativePath] = parsedIdentifier; + const isFolder = + relativePath.charCodeAt(relativePath.length - 1) === slashCode; + + if (isFolder !== expectFolder) { + throw new Error( + expectFolder + ? `Expecting folder to folder mapping. ${JSON.stringify( + exp, + )} should end with "/"` + : `Expecting file to file mapping. ${JSON.stringify( + exp, + )} should not end with "/"`, + ); + } +} + +/** + * @param {ExportsField} exportsField the exports field + * @returns {FieldProcessor} process callback + */ +module.exports.processExportsField = function processExportsField( + exportsField, +) { + return createFieldProcessor( + buildExportsField(exportsField), + (request) => (request.length === 0 ? "." : `./${request}`), + assertExportsFieldRequest, + assertExportTarget, + ); +}; + +/** + * @param {string} request request + * @returns {string} updated request + */ +function assertImportsFieldRequest(request) { + if (request.charCodeAt(0) !== hashCode) { + throw new Error('Request should start with "#"'); + } + if (request.length === 1) { + throw new Error("Request should have at least 2 characters"); + } + // Note: #/ patterns are now allowed per Node.js PR #60864 + // https://github.com/nodejs/node/pull/60864 + if (request.charCodeAt(request.length - 1) === slashCode) { + throw new Error("Only requesting file allowed"); + } + + return request.slice(1); +} + +/** + * @param {string} imp import target + * @param {boolean} expectFolder is folder expected + */ +function assertImportTarget(imp, expectFolder) { + const parsedIdentifier = parseIdentifier(imp); + + if (!parsedIdentifier) { + return; + } + + const [relativePath] = parsedIdentifier; + const isFolder = + relativePath.charCodeAt(relativePath.length - 1) === slashCode; + + if (isFolder !== expectFolder) { + throw new Error( + expectFolder + ? `Expecting folder to folder mapping. ${JSON.stringify( + imp, + )} should end with "/"` + : `Expecting file to file mapping. ${JSON.stringify( + imp, + )} should not end with "/"`, + ); + } +} + +/** + * @param {ImportsField} importsField the exports field + * @returns {FieldProcessor} process callback + */ +module.exports.processImportsField = function processImportsField( + importsField, +) { + return createFieldProcessor( + importsField, + (request) => `#${request}`, + assertImportsFieldRequest, + assertImportTarget, + ); +}; diff --git a/dg-ui/node_modules/enhanced-resolve/lib/util/fileURLToPath.js b/dg-ui/node_modules/enhanced-resolve/lib/util/fileURLToPath.js new file mode 100644 index 0000000..e96c24d --- /dev/null +++ b/dg-ui/node_modules/enhanced-resolve/lib/util/fileURLToPath.js @@ -0,0 +1,93 @@ +/* + MIT License http://www.opensource.org/licenses/mit-license.php +*/ + +"use strict"; + +// A runtime-agnostic port of Node's `url.fileURLToPath`, built on the global +// `URL` (available in Node, browsers, Deno and Bun) so the resolver does not +// depend on the Node `url` builtin. The platform branch can be forced via the +// `windows` option; otherwise it follows the host platform like Node does. + +const CHAR_LOWERCASE_A = 97; +const CHAR_LOWERCASE_Z = 122; + +const isWindows = + typeof process !== "undefined" && process.platform === "win32"; + +const forwardSlashRegEx = /\//g; + +/** + * @param {URL} url file: URL instance + * @returns {string} Windows filesystem path + */ +function getPathFromURLWin32(url) { + const { hostname } = url; + let { pathname } = url; + for (let n = 0; n < pathname.length; n++) { + if (pathname[n] === "%") { + const third = (pathname.codePointAt(n + 2) || 0) | 0x20; + if ( + (pathname[n + 1] === "2" && third === 102) || // 2f 2F (/) + (pathname[n + 1] === "5" && third === 99) // 5c 5C (\) + ) { + throw new TypeError( + "File URL path must not include encoded \\ or / characters", + ); + } + } + } + pathname = pathname.replace(forwardSlashRegEx, "\\"); + pathname = decodeURIComponent(pathname); + if (hostname !== "") { + // UNC path: `\\host\share\…`. Node runs the host through + // `domainToUnicode`; we keep the (already punycode) hostname as-is, + // which is identical for ASCII hosts and only differs for rare IDN UNC. + return `\\\\${hostname}${pathname}`; + } + const letter = (pathname.codePointAt(1) || 0) | 0x20; + const sep = pathname.charAt(2); + if (letter < CHAR_LOWERCASE_A || letter > CHAR_LOWERCASE_Z || sep !== ":") { + throw new TypeError("File URL path must be absolute"); + } + return pathname.slice(1); +} + +/** + * @param {URL} url file: URL instance + * @returns {string} POSIX filesystem path + */ +function getPathFromURLPosix(url) { + if (url.hostname !== "") { + throw new TypeError('File URL host must be "localhost" or empty'); + } + const { pathname } = url; + for (let n = 0; n < pathname.length; n++) { + if (pathname[n] === "%") { + const third = (pathname.codePointAt(n + 2) || 0) | 0x20; + if (pathname[n + 1] === "2" && third === 102) { + throw new TypeError( + "File URL path must not include encoded / characters", + ); + } + } + } + return decodeURIComponent(pathname); +} + +/** + * @param {string | URL} path a `file:` URL string or `URL` instance + * @param {{ windows?: boolean }=} options force the platform branch + * @returns {string} the filesystem path + */ +function fileURLToPath(path, options) { + const url = typeof path === "string" ? new URL(path) : path; + if (url.protocol !== "file:") { + throw new TypeError("The URL must be of scheme file"); + } + const windows = + options && options.windows !== undefined ? options.windows : isWindows; + return windows ? getPathFromURLWin32(url) : getPathFromURLPosix(url); +} + +module.exports = fileURLToPath; diff --git a/dg-ui/node_modules/enhanced-resolve/lib/util/fs.js b/dg-ui/node_modules/enhanced-resolve/lib/util/fs.js new file mode 100644 index 0000000..6c06b0a --- /dev/null +++ b/dg-ui/node_modules/enhanced-resolve/lib/util/fs.js @@ -0,0 +1,106 @@ +/* + MIT License http://www.opensource.org/licenses/mit-license.php + Author Natsu @xiaoxiaojx +*/ + +"use strict"; + +const memoize = require("./memoize"); +const stripJsonComments = require("./strip-json-comments"); + +/** @typedef {import("../Resolver").FileSystem} FileSystem */ +/** @typedef {import("../Resolver").JsonObject} JsonObject */ + +/** + * @typedef {object} ReadJsonOptions + * @property {boolean=} stripComments Whether to strip JSONC comments + */ + +/** @type {WeakMap} */ +const _stripCommentsCache = new WeakMap(); + +// Only constructed for non-Buffer input: on Node the `Buffer.isBuffer` branch +// in `decodeText` handles decoding, so the global `TextDecoder` (Node 11+, +// always present in browsers/Deno/Bun) is only reached off the Buffer path. +// `ignoreBOM: true` keeps a leading BOM in the output, matching +// `Buffer.toString("utf8")` so both decode paths behave identically. +// eslint-disable-next-line n/no-unsupported-features/node-builtins +const getDecoder = memoize(() => new TextDecoder("utf-8", { ignoreBOM: true })); + +/** + * Decode a file's raw contents to text without assuming a Node runtime. A + * `Buffer` (Node) uses its fast native `toString`; any other binary input + * (`Uint8Array` from a browser/Deno/Bun file system) goes through + * `TextDecoder`, and strings are returned as-is. + * @param {string | Buffer | Uint8Array} data raw file contents + * @returns {string} decoded text + */ +const decodeText = (data) => { + if (typeof data === "string") return data; + if (typeof Buffer !== "undefined" && Buffer.isBuffer(data)) { + return data.toString("utf8"); + } + return getDecoder().decode(data); +}; + +/** + * Read and parse JSON file (supports JSONC with comments). + * Callback-based so a synchronous `fileSystem` stays synchronous all the + * way through — Promise wrapping would defer resolution by a Promise tick + * and break `resolveSync` when `tsconfig` is used together with + * `useSyncFileSystemCalls: true`. + * @param {FileSystem} fileSystem the file system + * @param {string} jsonFilePath absolute path to JSON file + * @param {ReadJsonOptions} options Options + * @param {(err: NodeJS.ErrnoException | Error | null, content?: JsonObject) => void} callback callback + * @returns {void} + */ +function readJson(fileSystem, jsonFilePath, options, callback) { + const { stripComments = false } = options; + const { readJson: fsReadJson } = fileSystem; + if (fsReadJson && !stripComments) { + fsReadJson(jsonFilePath, (err, content) => { + if (err) return callback(err); + callback(null, /** @type {JsonObject} */ (content)); + }); + return; + } + + fileSystem.readFile(jsonFilePath, (err, data) => { + if (err) return callback(err); + const buf = /** @type {Buffer | Uint8Array | string} */ (data); + + // The strip-comments cache is keyed by the file-contents object; a file + // system may hand back a plain string, which cannot be a WeakMap key, so + // only cache when the contents are an object. + const cacheable = stripComments && typeof buf === "object"; + + if (cacheable) { + const cached = _stripCommentsCache.get(buf); + if (cached !== undefined) return callback(null, cached); + } + + let result; + try { + const jsonText = decodeText(buf); + const jsonWithoutComments = stripComments + ? stripJsonComments(jsonText, { + trailingCommas: true, + whitespace: true, + }) + : jsonText; + result = JSON.parse(jsonWithoutComments); + } catch (parseErr) { + return callback(/** @type {Error} */ (parseErr)); + } + + if (cacheable) { + _stripCommentsCache.set(buf, result); + } + + callback(null, result); + }); +} + +module.exports.decodeText = decodeText; +module.exports.readJson = readJson; diff --git a/dg-ui/node_modules/enhanced-resolve/lib/util/graceful-fs-browser.js b/dg-ui/node_modules/enhanced-resolve/lib/util/graceful-fs-browser.js new file mode 100644 index 0000000..63210c8 --- /dev/null +++ b/dg-ui/node_modules/enhanced-resolve/lib/util/graceful-fs-browser.js @@ -0,0 +1,44 @@ +/* + MIT License http://www.opensource.org/licenses/mit-license.php +*/ + +"use strict"; + +// Browser stub for the default `graceful-fs` file system. A browser has no +// ambient file system, so the convenience entry's default resolver has nothing +// to read — pass your own `fileSystem` to `create()` / +// `ResolverFactory.createResolver()` instead. Each method throws a clear error +// if the default is actually used, while keeping the package able to bundle for +// the browser (no Node `fs` dependency is pulled in). + +const message = + "enhanced-resolve: no default file system is available in the browser. " + + "Pass a `fileSystem` to `create()` or `ResolverFactory.createResolver()`."; + +/** + * Takes the arguments its callers pass - `readFile(path, callback)` and the + * rest - so the declaration describes a call that actually compiles, even + * though every one of them throws. + * @param {...unknown} _args arguments, ignored + * @returns {never} always throws + */ +const unavailable = (..._args) => { + throw new Error(message); +}; + +// The same set of methods `CachedInputFileSystem` reads from the file system +// (graceful-fs has no `readJson`/`readJsonSync`, so those stay undefined). +module.exports = { + lstat: unavailable, + lstatSync: unavailable, + readFile: unavailable, + readFileSync: unavailable, + readdir: unavailable, + readdirSync: unavailable, + readlink: unavailable, + readlinkSync: unavailable, + realpath: unavailable, + realpathSync: unavailable, + stat: unavailable, + statSync: unavailable, +}; diff --git a/dg-ui/node_modules/enhanced-resolve/lib/util/identifier.js b/dg-ui/node_modules/enhanced-resolve/lib/util/identifier.js new file mode 100644 index 0000000..5c71711 --- /dev/null +++ b/dg-ui/node_modules/enhanced-resolve/lib/util/identifier.js @@ -0,0 +1,103 @@ +/* + MIT License http://www.opensource.org/licenses/mit-license.php + Author Ivan Kopeykin @vankop +*/ + +"use strict"; + +const { fileURLToPath } = require("url"); +const { isFileURL } = require("./path"); + +const PATH_QUERY_FRAGMENT_REGEXP = + /^(#?(?:\0.|[^?#\0])*)(\?(?:\0.|[^#\0])*)?(#.*)?$/; +const ZERO_ESCAPE_REGEXP = /\0(.)/g; + +/** + * Index past a DOS device path prefix (`\\?\…` or `\\.\…`), or 0. Kept + * out of `parseIdentifier` on purpose: inlining it back bloats the caller + * beyond the size where V8's interpreter and JIT both handle it well + * (the cause of the description-files-multi CodSpeed regression). + * @param {string} identifier identifier known to start with `\` + * @returns {number} 4 if identifier starts with a DOS device prefix, else 0 + */ +function dosPrefixEnd(identifier) { + if ( + identifier.length >= 4 && + identifier.charCodeAt(1) === 92 && + identifier.charCodeAt(3) === 92 + ) { + const c2 = identifier.charCodeAt(2); + if (c2 === 63 || c2 === 46) return 4; + } + return 0; +} + +/** + * @param {string} identifier identifier + * @returns {[string, string, string] | null} parsed identifier + */ +function parseIdentifier(identifier) { + if (!identifier) { + return null; + } + + // Only a whole `file:` URL is one - a path segment spelled `file:`, which + // `/tmp/profile:1.js` also contains, stays the path it is. + if (isFileURL(identifier)) { + identifier = fileURLToPath(identifier); + } + + const firstEscape = identifier.indexOf("\0"); + + // Handle `\0` + if (firstEscape !== -1) { + const match = PATH_QUERY_FRAGMENT_REGEXP.exec(identifier); + + if (!match) return null; + + return [ + match[1].replace(ZERO_ESCAPE_REGEXP, "$1"), + match[2] ? match[2].replace(ZERO_ESCAPE_REGEXP, "$1") : "", + match[3] || "", + ]; + } + + // Fast path for inputs that don't use \0 escaping. DOS device paths + // (`\\?\…`, `\\.\…`) embed a literal `?` / `.` that must not be read + // as a query separator; skip past the prefix when the input actually + // starts with `\`. Gate is a single char-code compare so this function + // stays inside V8's inline budget for its hot callers (resolver parse). + const scanStart = + identifier.charCodeAt(0) === 92 ? dosPrefixEnd(identifier) : 0; + const queryStart = identifier.indexOf("?", scanStart); + // Start at index 1 (or past a DOS prefix) to ignore a possible leading hash. + const fragmentStart = identifier.indexOf("#", scanStart || 1); + + if (fragmentStart < 0) { + if (queryStart < 0) { + // No fragment, no query + return [identifier, "", ""]; + } + + // Query, no fragment + return [identifier.slice(0, queryStart), identifier.slice(queryStart), ""]; + } + + if (queryStart < 0 || fragmentStart < queryStart) { + // Fragment, no query + return [ + identifier.slice(0, fragmentStart), + "", + identifier.slice(fragmentStart), + ]; + } + + // Query and fragment + return [ + identifier.slice(0, queryStart), + identifier.slice(queryStart, fragmentStart), + identifier.slice(fragmentStart), + ]; +} + +module.exports.parseIdentifier = parseIdentifier; diff --git a/dg-ui/node_modules/enhanced-resolve/lib/util/memoize.js b/dg-ui/node_modules/enhanced-resolve/lib/util/memoize.js new file mode 100644 index 0000000..b46e252 --- /dev/null +++ b/dg-ui/node_modules/enhanced-resolve/lib/util/memoize.js @@ -0,0 +1,37 @@ +/* + MIT License http://www.opensource.org/licenses/mit-license.php + Author Tobias Koppers @sokra +*/ + +"use strict"; + +/** + * @template T + * @typedef {() => T} FunctionReturning + */ + +/** + * @template T + * @param {FunctionReturning} fn memorized function + * @returns {FunctionReturning} new function + */ +const memoize = (fn) => { + let cache = false; + /** @type {T | undefined} */ + let result; + return () => { + if (cache) { + return /** @type {T} */ (result); + } + + result = fn(); + cache = true; + // Allow to clean up memory for fn + // and all dependent resources + /** @type {FunctionReturning | undefined} */ + (fn) = undefined; + return /** @type {T} */ (result); + }; +}; + +module.exports = memoize; diff --git a/dg-ui/node_modules/enhanced-resolve/lib/util/module-browser.js b/dg-ui/node_modules/enhanced-resolve/lib/util/module-browser.js new file mode 100644 index 0000000..1258c22 --- /dev/null +++ b/dg-ui/node_modules/enhanced-resolve/lib/util/module-browser.js @@ -0,0 +1,8 @@ +/* + MIT License http://www.opensource.org/licenses/mit-license.php + Author Tobias Koppers @sokra +*/ + +"use strict"; + +module.exports = {}; diff --git a/dg-ui/node_modules/enhanced-resolve/lib/util/packageMap.js b/dg-ui/node_modules/enhanced-resolve/lib/util/packageMap.js new file mode 100644 index 0000000..7c1e67e --- /dev/null +++ b/dg-ui/node_modules/enhanced-resolve/lib/util/packageMap.js @@ -0,0 +1,224 @@ +/* + MIT License http://www.opensource.org/licenses/mit-license.php +*/ + +"use strict"; + +// Node.js package maps: https://nodejs.org/api/packages.html#package-maps +// +// A package map is a static table that maps bare specifiers to package +// locations per importing package, so resolution never has to walk +// `node_modules`. This module turns the configuration file into the lookup +// tables `PackageMapPlugin` needs; no file system access is involved beyond +// reading the file itself. +// +// @experimental Package maps are stability 1 (experimental) in Node.js and are +// only reachable there behind `--experimental-package-map`. This parser tracks +// that specification and may change with it, including in a patch release. + +const fileURLToPath = require("./fileURLToPath"); +const { isInside, normalize } = require("./path"); +const pathToFileURL = require("./pathToFileURL"); + +/** @typedef {import("../Resolver").JsonObject} JsonObject */ + +/** @typedef {{ [specifier: string]: string }} PackageMapDependencies */ + +/** + * A single entry of the configuration file's `packages` object. + * @typedef {object} PackageMapPackage + * @property {string} url an absolute or relative `file:` URL, resolved against the configuration file + * @property {PackageMapDependencies=} dependencies bare specifier to package id + */ + +/** @typedef {{ [id: string]: PackageMapPackage }} PackageMapPackages */ + +/** + * The parsed contents of a package map configuration file. + * @typedef {object} PackageMapJson + * @property {PackageMapPackages} packages package entries by package id + */ + +/** + * @typedef {object} PackageMapEntry + * @property {string} id the package id this entry is keyed by + * @property {string} path absolute filesystem path the entry's `url` points at + * @property {Map} dependencies bare specifier to package id + */ + +/** + * @typedef {object} PackageMap + * @property {Map} packages entries by package id + * @property {{ path: string, ids: string[] }[]} locations package ids by location, longest path first + */ + +/** + * @param {string} message message + * @param {string} code error code + * @returns {Error & { code: string }} the error + */ +function createError(message, code) { + const error = /** @type {Error & { code: string }} */ (new Error(message)); + error.code = code; + return error; +} + +/** + * Resolve an entry's `url` the way Node does: through the WHATWG `URL` parser + * with the configuration file as the base, accepting only `file:`. + * @param {string} url the entry's `url` value + * @param {URL} base the configuration file URL + * @param {string} id the package id, for error messages + * @returns {string} the absolute filesystem path + */ +function toPackagePath(url, base, id) { + let parsed; + try { + parsed = new URL(url, base); + } catch (_err) { + throw createError( + `Package map entry "${id}" has an invalid "url": ${url}`, + "ERR_INVALID_PACKAGE_MAP", + ); + } + if (parsed.protocol !== "file:") { + throw createError( + `Package map entry "${id}" must use a "file:" url, received: ${url}`, + "ERR_INVALID_PACKAGE_MAP", + ); + } + return normalize(fileURLToPath(parsed)); +} + +/** + * Parse and validate a package map configuration file. + * + * Dangling dependency targets are rejected here rather than at resolution + * time: the map is static, so a broken table is a configuration error that is + * better surfaced once and in full. + * @param {JsonObject} data the parsed configuration file contents + * @param {string} configFilePath absolute path of the configuration file, used as the base for relative urls + * @returns {PackageMap} the parsed package map + */ +function parsePackageMap(data, configFilePath) { + if (!data || typeof data !== "object" || Array.isArray(data)) { + throw createError( + `Package map "${configFilePath}" must contain a JSON object`, + "ERR_INVALID_PACKAGE_MAP", + ); + } + + const rawPackages = data.packages; + + if ( + !rawPackages || + typeof rawPackages !== "object" || + Array.isArray(rawPackages) + ) { + throw createError( + `Package map "${configFilePath}" must contain a "packages" object`, + "ERR_INVALID_PACKAGE_MAP", + ); + } + + const base = pathToFileURL(configFilePath); + /** @type {Map} */ + const packages = new Map(); + /** @type {Map} */ + const idsByPath = new Map(); + + for (const id of Object.keys(rawPackages)) { + const rawEntry = /** @type {JsonObject} */ (rawPackages[id]); + + if (!rawEntry || typeof rawEntry !== "object" || Array.isArray(rawEntry)) { + throw createError( + `Package map entry "${id}" must be an object`, + "ERR_INVALID_PACKAGE_MAP", + ); + } + // An empty `url` would resolve to the configuration file itself rather + // than to a package directory, so reject it like Node does. + if (typeof rawEntry.url !== "string" || rawEntry.url === "") { + throw createError( + `Package map entry "${id}" must have a non-empty string "url"`, + "ERR_INVALID_PACKAGE_MAP", + ); + } + + const packagePath = toPackagePath(rawEntry.url, base, id); + /** @type {Map} */ + const dependencies = new Map(); + const rawDependencies = rawEntry.dependencies; + + if (rawDependencies !== undefined) { + if ( + !rawDependencies || + typeof rawDependencies !== "object" || + Array.isArray(rawDependencies) + ) { + throw createError( + `Package map entry "${id}" has a non-object "dependencies"`, + "ERR_INVALID_PACKAGE_MAP", + ); + } + for (const specifier of Object.keys(rawDependencies)) { + const target = rawDependencies[specifier]; + + if (typeof target !== "string") { + throw createError( + `Package map entry "${id}" maps "${specifier}" to a non-string package id`, + "ERR_INVALID_PACKAGE_MAP", + ); + } + dependencies.set(specifier, target); + } + } + + packages.set(id, { id, path: packagePath, dependencies }); + + const ids = idsByPath.get(packagePath); + if (ids) { + ids.push(id); + } else { + idsByPath.set(packagePath, [id]); + } + } + + for (const entry of packages.values()) { + for (const [specifier, target] of entry.dependencies) { + if (!packages.has(target)) { + throw createError( + `Package map entry "${entry.id}" maps "${specifier}" to unknown package id "${target}"`, + "ERR_INVALID_PACKAGE_MAP", + ); + } + } + } + + // Longest path first so a package nested inside another one wins the + // containment lookup below. + const locations = [...idsByPath] + .map(([path, ids]) => ({ path, ids })) + .sort((a, b) => b.path.length - a.path.length); + + return { packages, locations }; +} + +/** + * Find the package ids whose location contains `filePath`. More than one id is + * returned when several package entries share the same `url`, which the caller + * has to disambiguate with an explicit package id. + * @param {PackageMap} packageMap the package map + * @param {string} filePath an absolute filesystem path + * @returns {string[]} the matching package ids, empty when the path is outside every package + */ +function findPackageIds(packageMap, filePath) { + for (const location of packageMap.locations) { + if (isInside(location.path, filePath)) return location.ids; + } + return []; +} + +module.exports.createError = createError; +module.exports.findPackageIds = findPackageIds; +module.exports.parsePackageMap = parsePackageMap; diff --git a/dg-ui/node_modules/enhanced-resolve/lib/util/path-browser.js b/dg-ui/node_modules/enhanced-resolve/lib/util/path-browser.js new file mode 100644 index 0000000..5b7fd4c --- /dev/null +++ b/dg-ui/node_modules/enhanced-resolve/lib/util/path-browser.js @@ -0,0 +1,407 @@ +/* + MIT License http://www.opensource.org/licenses/mit-license.php +*/ + +"use strict"; + +// A browser shim for the Node `path` builtin, exposing only the subset used by +// `lib/util/path.js`: `posix.normalize`, `posix.dirname`, `win32.normalize`, +// `win32.dirname` and a (posix) `basename`. It is a faithful port of Node's +// `path` implementation and is wired in through the package `browser` field, so +// Node, Deno and Bun keep using their native `path` and only browser bundles +// use this. Inputs are always strings here, so Node's `validateString` guards +// are omitted. + +const CHAR_UPPERCASE_A = 65; +const CHAR_UPPERCASE_Z = 90; +const CHAR_LOWERCASE_A = 97; +const CHAR_LOWERCASE_Z = 122; +const CHAR_DOT = 46; +const CHAR_FORWARD_SLASH = 47; +const CHAR_BACKWARD_SLASH = 92; +const CHAR_COLON = 58; + +/** + * @param {number} code char code + * @returns {boolean} true for `/` + */ +const isPosixPathSeparator = (code) => code === CHAR_FORWARD_SLASH; + +/** + * @param {number} code char code + * @returns {boolean} true for `/` or `\` + */ +const isPathSeparator = (code) => + code === CHAR_FORWARD_SLASH || code === CHAR_BACKWARD_SLASH; + +/** + * @param {number} code char code + * @returns {boolean} true for an ASCII letter (a windows device root) + */ +const isWindowsDeviceRoot = (code) => + (code >= CHAR_UPPERCASE_A && code <= CHAR_UPPERCASE_Z) || + (code >= CHAR_LOWERCASE_A && code <= CHAR_LOWERCASE_Z); + +/** + * Resolve `.` and `..` segments in a path. Ported from Node's internal + * `normalizeString`. + * @param {string} path path + * @param {boolean} allowAboveRoot whether leading `..` may be kept + * @param {string} separator path separator to emit + * @param {(code: number) => boolean} isSeparator separator predicate + * @returns {string} normalized path string (without root) + */ +function normalizeString(path, allowAboveRoot, separator, isSeparator) { + let res = ""; + let lastSegmentLength = 0; + let lastSlash = -1; + let dots = 0; + let code = 0; + for (let i = 0; i <= path.length; ++i) { + if (i < path.length) { + code = path.charCodeAt(i); + } else if (isSeparator(code)) { + break; + } else { + code = CHAR_FORWARD_SLASH; + } + + if (isSeparator(code)) { + if (lastSlash === i - 1 || dots === 1) { + // NOOP + } else if (dots === 2) { + if ( + res.length < 2 || + lastSegmentLength !== 2 || + res.charCodeAt(res.length - 1) !== CHAR_DOT || + res.charCodeAt(res.length - 2) !== CHAR_DOT + ) { + if (res.length > 2) { + const lastSlashIndex = res.lastIndexOf(separator); + if (lastSlashIndex === -1) { + res = ""; + lastSegmentLength = 0; + } else { + res = res.slice(0, lastSlashIndex); + lastSegmentLength = res.length - 1 - res.lastIndexOf(separator); + } + lastSlash = i; + dots = 0; + continue; + } else if (res.length !== 0) { + res = ""; + lastSegmentLength = 0; + lastSlash = i; + dots = 0; + continue; + } + } + if (allowAboveRoot) { + res += res.length > 0 ? `${separator}..` : ".."; + lastSegmentLength = 2; + } + } else { + if (res.length > 0) { + res += `${separator}${path.slice(lastSlash + 1, i)}`; + } else { + res = path.slice(lastSlash + 1, i); + } + lastSegmentLength = i - lastSlash - 1; + } + lastSlash = i; + dots = 0; + } else if (code === CHAR_DOT && dots !== -1) { + ++dots; + } else { + dots = -1; + } + } + return res; +} + +/** + * @param {string} path path + * @returns {string} normalized posix path + */ +function posixNormalize(path) { + if (path.length === 0) return "."; + + const isAbsolute = path.charCodeAt(0) === CHAR_FORWARD_SLASH; + const trailingSeparator = + path.charCodeAt(path.length - 1) === CHAR_FORWARD_SLASH; + + path = normalizeString(path, !isAbsolute, "/", isPosixPathSeparator); + + if (path.length === 0) { + if (isAbsolute) return "/"; + return trailingSeparator ? "./" : "."; + } + if (trailingSeparator) path += "/"; + + return isAbsolute ? `/${path}` : path; +} + +/** + * @param {string} path path + * @returns {string} posix dirname + */ +function posixDirname(path) { + if (path.length === 0) return "."; + const hasRoot = path.charCodeAt(0) === CHAR_FORWARD_SLASH; + let end = -1; + let matchedSlash = true; + for (let i = path.length - 1; i >= 1; --i) { + if (path.charCodeAt(i) === CHAR_FORWARD_SLASH) { + if (!matchedSlash) { + end = i; + break; + } + } else { + matchedSlash = false; + } + } + + if (end === -1) return hasRoot ? "/" : "."; + if (hasRoot && end === 1) return "//"; + return path.slice(0, end); +} + +/** + * Normalizes drive paths (`C:\…`), UNC paths (`\\server\share\…`), DOS device + * paths (`\\.\…`, `\\?\…`) and relative/normal segments like Node's + * `path.win32.normalize`, including the CVE-2024-36139 colon-segment guard. + * + * Scope note: reserved Windows device names (`CON`, `COM1`, `LPT1`, …) are not + * special-cased, so e.g. `\\.\COM1:` differs from Node. Such names cannot occur + * in a browser (the only place this shim is used) and the resolver never routes + * them to `win32.normalize`, so this does not affect resolution. + * @param {string} path path + * @returns {string} normalized win32 path + */ +function win32Normalize(path) { + const len = path.length; + if (len === 0) return "."; + let rootEnd = 0; + /** @type {string | undefined} */ + let device; + let isAbsolute = false; + const code = path.charCodeAt(0); + + if (len === 1) { + return isPosixPathSeparator(code) ? "\\" : path; + } + + if (isPathSeparator(code)) { + // Possible UNC root; an initial separator means an absolute path. + isAbsolute = true; + + if (isPathSeparator(path.charCodeAt(1))) { + // Matched double path separator at beginning + let j = 2; + let last = j; + while (j < len && !isPathSeparator(path.charCodeAt(j))) j++; + if (j < len && j !== last) { + const firstPart = path.slice(last, j); + last = j; + while (j < len && isPathSeparator(path.charCodeAt(j))) j++; + if (j < len && j !== last) { + last = j; + while (j < len && !isPathSeparator(path.charCodeAt(j))) j++; + if (j === len || j !== last) { + if (firstPart === "." || firstPart === "?") { + // Device root, e.g. `\\.\pipe\…` or `\\?\C:\…` + device = `\\\\${firstPart}`; + rootEnd = 4; + } else if (j === len) { + // Matched a UNC root only + return `\\\\${firstPart}\\${path.slice(last)}\\`; + } else { + // Matched a UNC root with leftovers + device = `\\\\${firstPart}\\${path.slice(last, j)}`; + rootEnd = j; + } + } + } + } + } else { + rootEnd = 1; + } + } else if (isWindowsDeviceRoot(code) && path.charCodeAt(1) === CHAR_COLON) { + // Possible device root + device = path.slice(0, 2); + rootEnd = 2; + if (len > 2 && isPathSeparator(path.charCodeAt(2))) { + isAbsolute = true; + rootEnd = 3; + } + } + + let tail = + rootEnd < len + ? normalizeString(path.slice(rootEnd), !isAbsolute, "\\", isPathSeparator) + : ""; + if (tail.length === 0 && !isAbsolute) tail = "."; + if (tail.length > 0 && isPathSeparator(path.charCodeAt(len - 1))) { + tail += "\\"; + } + if (!isAbsolute && device === undefined && path.includes(":")) { + // A relative path that wasn't resolved to a device must not turn into + // something Windows could read as an absolute/drive path (CVE-2024-36139). + if ( + tail.length >= 2 && + isWindowsDeviceRoot(tail.charCodeAt(0)) && + tail.charCodeAt(1) === CHAR_COLON + ) { + return `.\\${tail}`; + } + let index = path.indexOf(":"); + do { + if (index === len - 1 || isPathSeparator(path.charCodeAt(index + 1))) { + return `.\\${tail}`; + } + } while ((index = path.indexOf(":", index + 1)) !== -1); + } + if (device === undefined) { + return isAbsolute ? `\\${tail}` : tail; + } + return isAbsolute ? `${device}\\${tail}` : `${device}${tail}`; +} + +/** + * @param {string} path path + * @returns {string} win32 dirname + */ +function win32Dirname(path) { + const len = path.length; + if (len === 0) return "."; + let rootEnd = -1; + let offset = 0; + const code = path.charCodeAt(0); + + if (len === 1) { + return isPathSeparator(code) ? path : "."; + } + + if (isPathSeparator(code)) { + // Possible UNC root + rootEnd = offset = 1; + + if (isPathSeparator(path.charCodeAt(1))) { + let j = 2; + let last = j; + while (j < len && !isPathSeparator(path.charCodeAt(j))) j++; + if (j < len && j !== last) { + last = j; + while (j < len && isPathSeparator(path.charCodeAt(j))) j++; + if (j < len && j !== last) { + last = j; + while (j < len && !isPathSeparator(path.charCodeAt(j))) j++; + if (j === len) { + // Matched a UNC root only + return path; + } + if (j !== last) { + // Matched a UNC root with leftovers + rootEnd = offset = j + 1; + } + } + } + } + } else if (isWindowsDeviceRoot(code) && path.charCodeAt(1) === CHAR_COLON) { + rootEnd = len > 2 && isPathSeparator(path.charCodeAt(2)) ? 3 : 2; + offset = rootEnd; + } + + let end = -1; + let matchedSlash = true; + for (let i = len - 1; i >= offset; --i) { + if (isPathSeparator(path.charCodeAt(i))) { + if (!matchedSlash) { + end = i; + break; + } + } else { + matchedSlash = false; + } + } + + if (end === -1) { + if (rootEnd === -1) return "."; + end = rootEnd; + } + return path.slice(0, end); +} + +/** + * Posix `basename` — the browser is treated as a posix platform, matching how + * Node picks the posix variant for `path.basename` on non-Windows systems. + * @param {string} path path + * @param {string=} suffix optional suffix to strip + * @returns {string} basename + */ +function basename(path, suffix) { + let start = 0; + let end = -1; + let matchedSlash = true; + + if ( + suffix !== undefined && + suffix.length > 0 && + suffix.length <= path.length + ) { + if (suffix === path) return ""; + let extIdx = suffix.length - 1; + let firstNonSlashEnd = -1; + for (let i = path.length - 1; i >= 0; --i) { + const code = path.charCodeAt(i); + if (code === CHAR_FORWARD_SLASH) { + if (!matchedSlash) { + start = i + 1; + break; + } + } else { + if (firstNonSlashEnd === -1) { + matchedSlash = false; + firstNonSlashEnd = i + 1; + } + if (extIdx >= 0) { + if (code === suffix.charCodeAt(extIdx)) { + if (--extIdx === -1) { + end = i; + } + } else { + extIdx = -1; + end = firstNonSlashEnd; + } + } + } + } + + if (start === end) { + end = firstNonSlashEnd; + } else if (end === -1) { + end = path.length; + } + return path.slice(start, end); + } + for (let i = path.length - 1; i >= 0; --i) { + if (path.charCodeAt(i) === CHAR_FORWARD_SLASH) { + if (!matchedSlash) { + start = i + 1; + break; + } + } else if (end === -1) { + matchedSlash = false; + end = i + 1; + } + } + + if (end === -1) return ""; + return path.slice(start, end); +} + +module.exports = { + basename, + posix: { normalize: posixNormalize, dirname: posixDirname }, + win32: { normalize: win32Normalize, dirname: win32Dirname }, +}; diff --git a/dg-ui/node_modules/enhanced-resolve/lib/util/path.js b/dg-ui/node_modules/enhanced-resolve/lib/util/path.js new file mode 100644 index 0000000..daf1262 --- /dev/null +++ b/dg-ui/node_modules/enhanced-resolve/lib/util/path.js @@ -0,0 +1,471 @@ +/* + MIT License http://www.opensource.org/licenses/mit-license.php + Author Tobias Koppers @sokra +*/ + +"use strict"; + +const path = require("path"); +const { fileURLToPath } = require("url"); + +const CHAR_HASH = "#".charCodeAt(0); +const CHAR_SLASH = "/".charCodeAt(0); +const CHAR_BACKSLASH = "\\".charCodeAt(0); +const CHAR_A = "A".charCodeAt(0); +const CHAR_Z = "Z".charCodeAt(0); +const CHAR_LOWER_A = "a".charCodeAt(0); +const CHAR_LOWER_Z = "z".charCodeAt(0); +const CHAR_DOT = ".".charCodeAt(0); +const CHAR_COLON = ":".charCodeAt(0); +const CHAR_F = "F".charCodeAt(0); +const CHAR_LOWER_F = "f".charCodeAt(0); + +const FILE_URL_REGEXP = /^file:\//i; + +const posixNormalize = path.posix.normalize; +const winNormalize = path.win32.normalize; + +/** + * @enum {number} + */ +const PathType = Object.freeze({ + Empty: 0, + Normal: 1, + Relative: 2, + AbsoluteWin: 3, + AbsolutePosix: 4, + Internal: 5, +}); + +const deprecatedInvalidSegmentRegEx = + /(^|\\|\/)((\.|%2e)(\.|%2e)?|(n|%6e|%4e)(o|%6f|%4f)(d|%64|%44)(e|%65|%45)(_|%5f)(m|%6d|%4d)(o|%6f|%4f)(d|%64|%44)(u|%75|%55)(l|%6c|%4c)(e|%65|%45)(s|%73|%53))(\\|\/|$)/i; + +const invalidSegmentRegEx = + /(^|\\|\/)((\.|%2e)(\.|%2e)?|(n|%6e|%4e)(o|%6f|%4f)(d|%64|%44)(e|%65|%45)(_|%5f)(m|%6d|%4d)(o|%6f|%4f)(d|%64|%44)(u|%75|%55)(l|%6c|%4c)(e|%65|%45)(s|%73|%53))?(\\|\/|$)/i; + +/** + * @param {string} maybePath a path + * @returns {PathType} type of path + */ +const getType = (maybePath) => { + switch (maybePath.length) { + case 0: + return PathType.Empty; + case 1: { + const c0 = maybePath.charCodeAt(0); + switch (c0) { + case CHAR_DOT: + return PathType.Relative; + case CHAR_SLASH: + return PathType.AbsolutePosix; + case CHAR_HASH: + return PathType.Internal; + } + return PathType.Normal; + } + case 2: { + const c0 = maybePath.charCodeAt(0); + switch (c0) { + case CHAR_DOT: { + const c1 = maybePath.charCodeAt(1); + switch (c1) { + case CHAR_DOT: + case CHAR_SLASH: + return PathType.Relative; + } + return PathType.Normal; + } + case CHAR_SLASH: + return PathType.AbsolutePosix; + case CHAR_HASH: + return PathType.Internal; + } + const c1 = maybePath.charCodeAt(1); + if ( + c1 === CHAR_COLON && + ((c0 >= CHAR_A && c0 <= CHAR_Z) || + (c0 >= CHAR_LOWER_A && c0 <= CHAR_LOWER_Z)) + ) { + return PathType.AbsoluteWin; + } + if (c0 === CHAR_BACKSLASH && c1 === CHAR_BACKSLASH) { + return PathType.AbsoluteWin; + } + return PathType.Normal; + } + } + const c0 = maybePath.charCodeAt(0); + switch (c0) { + case CHAR_DOT: { + const c1 = maybePath.charCodeAt(1); + switch (c1) { + case CHAR_SLASH: + return PathType.Relative; + case CHAR_DOT: { + const c2 = maybePath.charCodeAt(2); + if (c2 === CHAR_SLASH) return PathType.Relative; + return PathType.Normal; + } + } + return PathType.Normal; + } + case CHAR_SLASH: + return PathType.AbsolutePosix; + case CHAR_HASH: + return PathType.Internal; + } + const c1 = maybePath.charCodeAt(1); + if (c1 === CHAR_COLON) { + const c2 = maybePath.charCodeAt(2); + if ( + (c2 === CHAR_BACKSLASH || c2 === CHAR_SLASH) && + ((c0 >= CHAR_A && c0 <= CHAR_Z) || + (c0 >= CHAR_LOWER_A && c0 <= CHAR_LOWER_Z)) + ) { + return PathType.AbsoluteWin; + } + } + // Two leading backslashes root a UNC share (`\\server\share`) or a DOS + // device path (`\\?\…`, `\\.\…`); `path.win32` reads either as absolute, + // so both belong on `path.win32` and not on posix. + if (c0 === CHAR_BACKSLASH && c1 === CHAR_BACKSLASH) { + return PathType.AbsoluteWin; + } + return PathType.Normal; +}; + +/** + * @param {string} maybePath a path + * @returns {string} the normalized path + */ +const normalize = (maybePath) => { + switch (getType(maybePath)) { + case PathType.Empty: + return maybePath; + case PathType.AbsoluteWin: + return winNormalize(maybePath); + case PathType.Relative: { + const r = posixNormalize(maybePath); + return getType(r) === PathType.Relative ? r : `./${r}`; + } + } + return posixNormalize(maybePath); +}; + +/** + * @param {string} rootPath the root path + * @param {string | undefined} request the request path + * @returns {string} the joined path + */ +const join = (rootPath, request) => { + if (!request) return normalize(rootPath); + const requestType = getType(request); + switch (requestType) { + case PathType.AbsolutePosix: + return posixNormalize(request); + case PathType.AbsoluteWin: + return winNormalize(request); + } + switch (getType(rootPath)) { + case PathType.Normal: + case PathType.Relative: + case PathType.AbsolutePosix: + return posixNormalize(`${rootPath}/${request}`); + case PathType.AbsoluteWin: + return winNormalize(`${rootPath}\\${request}`); + } + switch (requestType) { + case PathType.Empty: + return rootPath; + case PathType.Relative: { + const r = posixNormalize(rootPath); + return getType(r) === PathType.Relative ? r : `./${r}`; + } + } + return posixNormalize(rootPath); +}; + +/** + * @param {string} maybePath a path + * @returns {string} the directory name + */ +const dirname = (maybePath) => { + switch (getType(maybePath)) { + case PathType.AbsoluteWin: + return path.win32.dirname(maybePath); + } + return path.posix.dirname(maybePath); +}; + +/** @typedef {{ fn: (rootPath: string, request: string) => string, cache: Map> }} CachedJoin */ + +/** + * @returns {CachedJoin} cached join + */ +const createCachedJoin = () => { + /** @type {CachedJoin["cache"]} */ + const cache = new Map(); + /** @type {CachedJoin["fn"]} */ + const fn = (rootPath, request) => { + /** @type {string | undefined} */ + let cacheEntry; + let inner = cache.get(rootPath); + if (inner === undefined) { + cache.set(rootPath, (inner = new Map())); + } else { + cacheEntry = inner.get(request); + if (cacheEntry !== undefined) return cacheEntry; + } + cacheEntry = join(rootPath, request); + inner.set(request, cacheEntry); + return cacheEntry; + }; + return { fn, cache }; +}; + +/** @typedef {{ fn: (maybePath: string) => string, cache: Map }} CachedDirname */ + +/** + * @returns {CachedDirname} cached dirname + */ +const createCachedDirname = () => { + /** @type {CachedDirname["cache"]} */ + const cache = new Map(); + /** @type {CachedDirname["fn"]} */ + const fn = (maybePath) => { + const cacheEntry = cache.get(maybePath); + if (cacheEntry !== undefined) return cacheEntry; + const result = dirname(maybePath); + cache.set(maybePath, result); + return result; + }; + return { fn, cache }; +}; + +/** @typedef {{ fn: (maybePath: string, suffix?: string) => string, cache: Map> }} CachedBasename */ + +/** + * @returns {CachedBasename} cached basename + */ +const createCachedBasename = () => { + /** @type {CachedBasename["cache"]} */ + const cache = new Map(); + /** @type {CachedBasename["fn"]} */ + const fn = (maybePath, suffix) => { + /** @type {string | undefined} */ + let cacheEntry; + let inner = cache.get(maybePath); + if (inner === undefined) { + cache.set(maybePath, (inner = new Map())); + } else { + cacheEntry = inner.get(suffix); + if (cacheEntry !== undefined) return cacheEntry; + } + cacheEntry = path.basename(maybePath, suffix); + inner.set(suffix, cacheEntry); + return cacheEntry; + }; + return { fn, cache }; +}; + +/** + * Whether `request` is a relative request — i.e. matches `^\.\.?(?:\/|$)`. + * + * This is called on every `doResolve` via `UnsafeCachePlugin` and + * `getInnerRequest`, so the char-code form is meaningfully faster than the + * equivalent regex test: no regex state machine, no string object churn. + * @param {string} request request string + * @returns {boolean} true if request is relative + */ +const isRelativeRequest = (request) => { + const len = request.length; + if (len === 0 || request.charCodeAt(0) !== CHAR_DOT) return false; + if (len === 1) return true; // "." + const c1 = request.charCodeAt(1); + if (c1 === CHAR_SLASH) return true; // "./..." + if (c1 !== CHAR_DOT) return false; // ".x..." + if (len === 2) return true; // ".." + return request.charCodeAt(2) === CHAR_SLASH; // "../..." +}; + +/** + * Whether this is a Windows path, in which `/` and `\` are interchangeable and + * paths compare case-insensitively, as opposed to a posix path, in which `\` is + * an ordinary filename character. Decided by the root — a drive letter or a + * leading `\` — which is where `path.win32` and `path.posix` disagree about + * `parse(maybePath).root`, and never by the host platform, since Windows paths + * are resolved on posix hosts and in browsers too. A path starting with `//` + * stays posix: `path.win32` reads it as a UNC root, but here it cannot be told + * apart from a posix path, where `\` has to keep being a filename character. + * @param {string} maybePath a path + * @returns {boolean} true, when the path is a Windows path + */ +const isWindowsPath = (maybePath) => { + const c0 = maybePath.charCodeAt(0); + if (c0 === CHAR_BACKSLASH) return true; + if (maybePath.charCodeAt(1) !== CHAR_COLON) return false; + return ( + (c0 >= CHAR_A && c0 <= CHAR_Z) || (c0 >= CHAR_LOWER_A && c0 <= CHAR_LOWER_Z) + ); +}; + +/** + * @param {number} charCode a char code + * @param {boolean} windowsPath whether `\` separates segments + * @returns {boolean} true, when the char code separates path segments + */ +const isSeparator = (charCode, windowsPath) => + charCode === CHAR_SLASH || (windowsPath && charCode === CHAR_BACKSLASH); + +/** + * @param {string} parentPath parent directory path + * @param {boolean} windowsPath whether `parentPath` is a Windows path + * @returns {number} length of `parentPath` without its trailing separators + */ +const parentPathLength = (parentPath, windowsPath) => { + let end = parentPath.length; + while (end > 0 && isSeparator(parentPath.charCodeAt(end - 1), windowsPath)) { + end--; + } + return end; +}; + +/** + * Cold path of `startsWithPath`: Node lowercases whole paths rather than single + * characters, which only makes a difference outside of ASCII. + * @param {string} parentPath parent directory path + * @param {number} length number of characters to compare + * @param {string} childPath child path to check + * @returns {boolean} true, when both prefixes name the same Windows path + */ +const equalsWindowsPrefix = (parentPath, length, childPath) => + childPath.slice(0, length).replace(/\//g, "\\").toLowerCase() === + parentPath.slice(0, length).replace(/\//g, "\\").toLowerCase(); + +/** + * @param {string} parentPath parent directory path + * @param {number} length number of characters of `parentPath` to compare + * @param {string} childPath child path to check + * @param {boolean} windowsPath whether `parentPath` is a Windows path + * @returns {boolean} true, when `childPath` starts with that prefix + */ +const startsWithPath = (parentPath, length, childPath, windowsPath) => { + if (childPath.length < length) return false; + // The common case is an exact prefix of a parent without trailing + // separators, which `startsWith` answers natively and without a slice. For + // a posix parent that is the whole answer, only a Windows one has more + // spellings of the same path to try. + if (length === parentPath.length) { + if (childPath.startsWith(parentPath)) return true; + if (!windowsPath) return false; + } + for (let i = 0; i < length; i++) { + const childCharCode = childPath.charCodeAt(i); + const parentCharCode = parentPath.charCodeAt(i); + if (childCharCode === parentCharCode) continue; + if (!windowsPath) return false; + // Windows mixes `/` and `\` freely and compares case-insensitively. + if (isSeparator(childCharCode, true) && isSeparator(parentCharCode, true)) { + continue; + } + if (childCharCode > 127 || parentCharCode > 127) { + return equalsWindowsPrefix(parentPath, length, childPath); + } + const childLower = + childCharCode >= CHAR_A && childCharCode <= CHAR_Z + ? childCharCode + 32 + : childCharCode; + const parentLower = + parentCharCode >= CHAR_A && parentCharCode <= CHAR_Z + ? parentCharCode + 32 + : parentCharCode; + if (childLower !== parentLower) return false; + } + return true; +}; + +/** + * Whether childPath is parentPath itself or a path under it, the answer node's + * `relative(parentPath, childPath)` gives: not escaping upward and not + * absolute. A trailing separator on the parent is not part of the boundary, so + * `/a/b/` contains exactly what `/a/b` contains. + * @param {string} parentPath parent directory path + * @param {string} childPath child path to check + * @returns {boolean} true if childPath is parentPath or is under it + */ +const isInside = (parentPath, childPath) => { + const windowsPath = isWindowsPath(parentPath); + const length = parentPathLength(parentPath, windowsPath); + if (!startsWithPath(parentPath, length, childPath, windowsPath)) return false; + // The parent itself, or a segment boundary right after it so that `/a/b` + // does not contain the sibling `/a/b-other`. + return ( + childPath.length === length || + isSeparator(childPath.charCodeAt(length), windowsPath) + ); +}; + +/** + * Check if childPath is a subdirectory of parentPath. Compares like `isInside`, + * except that a path is not a subpath of itself. + * + * Called from `TsconfigPathsPlugin._selectPathsDataForContext` inside a loop + * over every tsconfig-paths context on every resolve, so it's worth keeping + * cheap: a native `startsWith` plus a separator char check answers it, and the + * character loop only runs for a Windows path that the prefix test missed. + * @param {string} parentPath parent directory path + * @param {string} childPath child path to check + * @returns {boolean} true if childPath is under parentPath + */ +const isSubPath = (parentPath, childPath) => { + const windowsPath = isWindowsPath(parentPath); + const length = parentPathLength(parentPath, windowsPath); + if (childPath.length <= length) return false; + if (!startsWithPath(parentPath, length, childPath, windowsPath)) return false; + return isSeparator(childPath.charCodeAt(length), windowsPath); +}; + +/** + * Whether a string names a `file:` URL rather than a path. The scheme has to + * open the string and be followed by a slash, as Node's own URL parser needs, + * so a path segment spelled `file:` stays a path and `file:x.js` — which Node + * reads as `/x.js` — stays the relative request it looks like. + * @param {string} maybePath a path or a `file:` URL string + * @returns {boolean} true when the string is a `file:` URL + */ +const isFileURL = (maybePath) => { + // The first character keeps every path not starting with `f` off the regexp + const c0 = maybePath.charCodeAt(0); + return ( + (c0 === CHAR_LOWER_F || c0 === CHAR_F) && FILE_URL_REGEXP.test(maybePath) + ); +}; + +/** + * Convert a `file:` URL — a `URL` instance or a `file:/` string, the form + * `import.meta.resolve` returns — to the path it names. Anything else is + * returned unchanged, so a path passes through. + * @param {string | URL} maybeURL a path, a `file:` URL string or a `file:` `URL` instance + * @returns {string} a filesystem path + */ +const toPath = (maybeURL) => { + if (maybeURL instanceof URL) return fileURLToPath(maybeURL); + return isFileURL(maybeURL) ? fileURLToPath(maybeURL) : maybeURL; +}; + +module.exports.PathType = PathType; +module.exports.createCachedBasename = createCachedBasename; +module.exports.createCachedDirname = createCachedDirname; +module.exports.createCachedJoin = createCachedJoin; +module.exports.deprecatedInvalidSegmentRegEx = deprecatedInvalidSegmentRegEx; +module.exports.dirname = dirname; +module.exports.getType = getType; +module.exports.invalidSegmentRegEx = invalidSegmentRegEx; +module.exports.isFileURL = isFileURL; +module.exports.isInside = isInside; +module.exports.isRelativeRequest = isRelativeRequest; +module.exports.isSubPath = isSubPath; +module.exports.isWindowsPath = isWindowsPath; +module.exports.join = join; +module.exports.normalize = normalize; +module.exports.toPath = toPath; diff --git a/dg-ui/node_modules/enhanced-resolve/lib/util/pathToFileURL.js b/dg-ui/node_modules/enhanced-resolve/lib/util/pathToFileURL.js new file mode 100644 index 0000000..a99714b --- /dev/null +++ b/dg-ui/node_modules/enhanced-resolve/lib/util/pathToFileURL.js @@ -0,0 +1,87 @@ +/* + MIT License http://www.opensource.org/licenses/mit-license.php +*/ + +"use strict"; + +// A runtime-agnostic port of Node's `url.pathToFileURL`, built on the global +// `URL` (available in Node, browsers, Deno and Bun) so the resolver does not +// depend on the Node `url` builtin. It is the inverse of `./fileURLToPath` and +// takes the same `windows` option to force the platform branch. +// +// Unlike Node's version this does not call `path.resolve` on the input: the +// resolver only ever converts paths it has already made absolute, and reaching +// for the current working directory would not work in a browser. + +const percentRegEx = /%/g; +const backslashRegEx = /\\/g; +const newlineRegEx = /\n/g; +const carriageReturnRegEx = /\r/g; +const tabRegEx = /\t/g; + +const isWindows = + typeof process !== "undefined" && process.platform === "win32"; + +/** + * Percent-encode the characters the `URL` pathname setter would otherwise + * interpret. Everything else is left to the setter itself. + * @param {string} filepath absolute filesystem path + * @param {boolean} windows true to follow the Windows branch + * @returns {string} the encoded path + */ +function encodePathChars(filepath, windows) { + if (filepath.includes("%")) { + filepath = filepath.replace(percentRegEx, "%25"); + } + // A backslash is a legal character in a POSIX file name, so it has to be + // encoded rather than treated as a separator. + if (!windows && filepath.includes("\\")) { + filepath = filepath.replace(backslashRegEx, "%5C"); + } + if (filepath.includes("\n")) { + filepath = filepath.replace(newlineRegEx, "%0A"); + } + if (filepath.includes("\r")) { + filepath = filepath.replace(carriageReturnRegEx, "%0D"); + } + if (filepath.includes("\t")) { + filepath = filepath.replace(tabRegEx, "%09"); + } + return filepath; +} + +/** + * @param {string} filepath an absolute filesystem path + * @param {{ windows?: boolean }=} options force the platform branch + * @returns {URL} the `file:` URL + */ +function pathToFileURL(filepath, options) { + const windows = + options && options.windows !== undefined ? options.windows : isWindows; + + if (windows && filepath.startsWith("\\\\")) { + // UNC path: `\\server\share\file` becomes `file://server/share/file`. + const hostnameEndIndex = filepath.indexOf("\\", 2); + if (hostnameEndIndex === -1) { + throw new TypeError( + `Missing UNC resource path in file path '${filepath}'`, + ); + } + if (hostnameEndIndex === 2) { + throw new TypeError(`Empty UNC servername in file path '${filepath}'`); + } + const url = new URL("file://"); + url.hostname = filepath.slice(2, hostnameEndIndex); + url.pathname = encodePathChars( + filepath.slice(hostnameEndIndex).replace(backslashRegEx, "/"), + windows, + ); + return url; + } + + const url = new URL("file://"); + url.pathname = encodePathChars(filepath, windows); + return url; +} + +module.exports = pathToFileURL; diff --git a/dg-ui/node_modules/enhanced-resolve/lib/util/process-browser.js b/dg-ui/node_modules/enhanced-resolve/lib/util/process-browser.js new file mode 100644 index 0000000..95f8d5e --- /dev/null +++ b/dg-ui/node_modules/enhanced-resolve/lib/util/process-browser.js @@ -0,0 +1,23 @@ +/* + MIT License http://www.opensource.org/licenses/mit-license.php + Author Tobias Koppers @sokra +*/ + +"use strict"; + +module.exports = { + /** + * @type {Record} + */ + versions: {}, + // eslint-disable-next-line jsdoc/reject-function-type + /** @param {Function} fn function */ + nextTick(fn) { + // eslint-disable-next-line prefer-rest-params + const args = Array.prototype.slice.call(arguments, 1); + Promise.resolve().then(() => { + // eslint-disable-next-line prefer-spread + fn.apply(null, args); + }); + }, +}; diff --git a/dg-ui/node_modules/enhanced-resolve/lib/util/strip-json-comments.js b/dg-ui/node_modules/enhanced-resolve/lib/util/strip-json-comments.js new file mode 100644 index 0000000..5096f8b --- /dev/null +++ b/dg-ui/node_modules/enhanced-resolve/lib/util/strip-json-comments.js @@ -0,0 +1,177 @@ +/* + MIT License http://www.opensource.org/licenses/mit-license.php + Author Natsu @xiaoxiaojx + + This file contains code ported from strip-json-comments: + https://github.com/sindresorhus/strip-json-comments + Original license: MIT + Original author: Sindre Sorhus +*/ + +"use strict"; + +/** + * @typedef {object} StripJsonCommentsOptions + * @property {boolean=} whitespace Replace comments with whitespace + * @property {boolean=} trailingCommas Strip trailing commas + */ + +const singleComment = Symbol("singleComment"); +const multiComment = Symbol("multiComment"); + +/** + * Strip without whitespace (returns empty string) + * @param {string} _string Unused + * @param {number} _start Unused + * @param {number} _end Unused + * @returns {string} Empty string for all input + */ +const stripWithoutWhitespace = (_string, _start, _end) => ""; + +/** + * Replace all characters except ASCII spaces, tabs and line endings with regular spaces to ensure valid JSON output. + * @param {string} string String to process + * @param {number} start Start index + * @param {number} end End index + * @returns {string} Processed string with comments replaced by whitespace + */ +const stripWithWhitespace = (string, start, end) => + string.slice(start, end).replace(/[^ \t\r\n]/g, " "); + +/** + * Check if a quote is escaped + * @param {string} jsonString JSON string + * @param {number} quotePosition Position of the quote + * @returns {boolean} True if the quote at the given position is escaped + */ +const isEscaped = (jsonString, quotePosition) => { + let index = quotePosition - 1; + let backslashCount = 0; + + while (jsonString[index] === "\\") { + index -= 1; + backslashCount += 1; + } + + return Boolean(backslashCount % 2); +}; + +/** + * Strip comments from JSON string + * @param {string} jsonString JSON string with potential comments + * @param {StripJsonCommentsOptions} options Options + * @returns {string} JSON string without comments + */ +function stripJsonComments( + jsonString, + { whitespace = true, trailingCommas = false } = {}, +) { + if (typeof jsonString !== "string") { + throw new TypeError( + `Expected argument \`jsonString\` to be a \`string\`, got \`${typeof jsonString}\``, + ); + } + + const strip = whitespace ? stripWithWhitespace : stripWithoutWhitespace; + + let isInsideString = false; + /** @type {false | typeof singleComment | typeof multiComment} */ + let isInsideComment = false; + let offset = 0; + let buffer = ""; + let result = ""; + let commaIndex = -1; + + for (let index = 0; index < jsonString.length; index++) { + const currentCharacter = jsonString[index]; + const nextCharacter = jsonString[index + 1]; + + if (!isInsideComment && currentCharacter === '"') { + // Enter or exit string + const escaped = isEscaped(jsonString, index); + if (!escaped) { + isInsideString = !isInsideString; + } + } + + if (isInsideString) { + continue; + } + + if (!isInsideComment && currentCharacter + nextCharacter === "//") { + // Enter single-line comment + buffer += jsonString.slice(offset, index); + offset = index; + isInsideComment = singleComment; + index++; + } else if ( + isInsideComment === singleComment && + currentCharacter + nextCharacter === "\r\n" + ) { + // Exit single-line comment via \r\n + index++; + isInsideComment = false; + buffer += strip(jsonString, offset, index); + offset = index; + continue; + } else if (isInsideComment === singleComment && currentCharacter === "\n") { + // Exit single-line comment via \n + isInsideComment = false; + buffer += strip(jsonString, offset, index); + offset = index; + } else if (!isInsideComment && currentCharacter + nextCharacter === "/*") { + // Enter multiline comment + buffer += jsonString.slice(offset, index); + offset = index; + isInsideComment = multiComment; + index++; + continue; + } else if ( + isInsideComment === multiComment && + currentCharacter + nextCharacter === "*/" + ) { + // Exit multiline comment + index++; + isInsideComment = false; + buffer += strip(jsonString, offset, index + 1); + offset = index + 1; + continue; + } else if (trailingCommas && !isInsideComment) { + if (commaIndex !== -1) { + if (currentCharacter === "}" || currentCharacter === "]") { + // Strip trailing comma + buffer += jsonString.slice(offset, index); + result += strip(buffer, 0, 1) + buffer.slice(1); + buffer = ""; + offset = index; + commaIndex = -1; + } else if ( + currentCharacter !== " " && + currentCharacter !== "\t" && + currentCharacter !== "\r" && + currentCharacter !== "\n" + ) { + // Hit non-whitespace following a comma; comma is not trailing + buffer += jsonString.slice(offset, index); + offset = index; + commaIndex = -1; + } + } else if (currentCharacter === ",") { + // Flush buffer prior to this point, and save new comma index + result += buffer + jsonString.slice(offset, index); + buffer = ""; + offset = index; + commaIndex = index; + } + } + } + + const remaining = + isInsideComment === singleComment + ? strip(jsonString, offset, jsonString.length) + : jsonString.slice(offset); + + return result + buffer + remaining; +} + +module.exports = stripJsonComments; diff --git a/dg-ui/node_modules/enhanced-resolve/lib/util/url-browser.js b/dg-ui/node_modules/enhanced-resolve/lib/util/url-browser.js new file mode 100644 index 0000000..3c23373 --- /dev/null +++ b/dg-ui/node_modules/enhanced-resolve/lib/util/url-browser.js @@ -0,0 +1,14 @@ +/* + MIT License http://www.opensource.org/licenses/mit-license.php +*/ + +"use strict"; + +// Browser shim for the Node `url` builtin, providing the `fileURLToPath` the +// resolver uses. Node, Deno and Bun use the native `url` (so they get the fully +// correct implementation); only browser bundles use this, wired in through the +// package `browser` field. The implementation is a URL-based port — see +// ./fileURLToPath. +module.exports = { + fileURLToPath: require("./fileURLToPath"), +}; diff --git a/dg-ui/node_modules/enhanced-resolve/package.json b/dg-ui/node_modules/enhanced-resolve/package.json new file mode 100644 index 0000000..4847258 --- /dev/null +++ b/dg-ui/node_modules/enhanced-resolve/package.json @@ -0,0 +1,84 @@ +{ + "name": "enhanced-resolve", + "version": "5.27.0", + "description": "Offers a async require.resolve function. It's highly configurable.", + "homepage": "https://github.com/webpack/enhanced-resolve#readme", + "repository": { + "type": "git", + "url": "git+https://github.com/webpack/enhanced-resolve.git" + }, + "license": "MIT", + "author": "Tobias Koppers @sokra", + "main": "lib/index.js", + "browser": { + "process": "./lib/util/process-browser.js", + "module": "./lib/util/module-browser.js", + "path": "./lib/util/path-browser.js", + "url": "./lib/util/url-browser.js", + "graceful-fs": "./lib/util/graceful-fs-browser.js" + }, + "types": "types.d.ts", + "files": [ + "lib", + "types", + "types.d.ts", + "LICENSE" + ], + "scripts": { + "prepare": "husky", + "lint": "npm run lint:code && npm run lint:types && npm run lint:types-test && npm run fmt:check && npm run lint:spellcheck", + "lint:code": "eslint --cache .", + "lint:types": "tsc", + "lint:types-test": "tsc -p tsconfig.types.test.json", + "lint:spellcheck": "cspell --cache --no-must-find-files --quiet \"**/*.*\"", + "fmt": "npm run fmt:base -- --log-level warn --write", + "fmt:check": "npm run fmt:base -- --check", + "fmt:base": "node_modules/prettier/bin/prettier.cjs --cache --ignore-unknown .", + "fix": "npm run fix:code && npm run build:types", + "fix:code": "npm run lint:code -- --fix", + "build:types": "node -e \"require('fs').rmSync('types', { recursive: true, force: true })\" && tsc -p tsconfig.types.json && prettier --log-level warn --write \"types/**/*.d.ts\"", + "type-report": "rimraf coverage && npm run cover:types && npm run cover:report && open-cli coverage/lcov-report/index.html", + "pretest": "npm run lint", + "test": "npm run test:only", + "test:only": "node scripts/test.js", + "test:watch": "node scripts/test.js --watch", + "test:coverage": "node scripts/test.js --experimental-test-coverage --test-coverage-include=\"lib/**\" --test-reporter=spec --test-reporter-destination=stdout --test-reporter=lcov --test-reporter-destination=coverage/lcov.info", + "test:browser": "node --experimental-vm-modules test/smoke/browser-run.cjs", + "version": "changeset version", + "release": "changeset publish", + "benchmark": "node --max-old-space-size=4096 --hash-seed=1 --random-seed=1 --no-opt --predictable --predictable-gc-schedule --interpreted-frames-native-stack --allow-natives-syntax --expose-gc --no-concurrent-sweeping ./benchmark/run.mjs" + }, + "lint-staged": { + "*.{js,cjs,mjs}": [ + "eslint --cache --fix" + ], + "*": [ + "prettier --cache --write --ignore-unknown", + "cspell --cache --no-must-find-files" + ] + }, + "dependencies": { + "graceful-fs": "^4.2.4", + "tapable": "^2.3.3" + }, + "devDependencies": { + "@changesets/cli": "^3.0.2", + "@changesets/get-github-info": "^1.0.1", + "@codspeed/core": "^6.1.0", + "@types/graceful-fs": "^4.1.6", + "@types/node": "^24.10.4", + "cspell": "^10.0.0", + "eslint": "^9.39.2", + "eslint-config-webpack": "^4.9.5", + "husky": "^9.1.7", + "lint-staged": "^17.0.4", + "memfs": "^4.56.11", + "prettier": "^3.7.4", + "tinybench": "^6.0.0", + "typescript": "^6.0.2", + "webpack": "^5.107.2" + }, + "engines": { + "node": ">=10.13.0" + } +} diff --git a/dg-ui/node_modules/enhanced-resolve/types.d.ts b/dg-ui/node_modules/enhanced-resolve/types.d.ts new file mode 100644 index 0000000..c8ec3d3 --- /dev/null +++ b/dg-ui/node_modules/enhanced-resolve/types.d.ts @@ -0,0 +1,9 @@ +/* + * The type declarations are generated from the JSDoc in `lib/` and live in + * `types/`. This file re-exports the entry point so that the `types` field and + * any direct reference to `enhanced-resolve/types.d.ts` keep resolving. + */ + +import resolve = require("./types/index"); + +export = resolve; diff --git a/dg-ui/node_modules/enhanced-resolve/types/AliasFieldPlugin.d.ts b/dg-ui/node_modules/enhanced-resolve/types/AliasFieldPlugin.d.ts new file mode 100644 index 0000000..f6ce204 --- /dev/null +++ b/dg-ui/node_modules/enhanced-resolve/types/AliasFieldPlugin.d.ts @@ -0,0 +1,41 @@ +export = AliasFieldPlugin; +declare class AliasFieldPlugin { + /** + * @param {string | ResolveStepHook} source source + * @param {string | string[]} field field + * @param {string | ResolveStepHook} target target + */ + constructor( + source: string | ResolveStepHook, + field: string | string[], + target: string | ResolveStepHook, + ); + source: string | import("./Resolver").ResolveStepHook; + field: string | string[]; + target: string | import("./Resolver").ResolveStepHook; + /** @type {WeakMap} */ + _fieldDataCache: WeakMap< + import("./Resolver").JsonObject, + | { + [k: string]: JsonPrimitive; + } + | typeof NO_FIELD_OBJECT + >; + /** + * @param {Resolver} resolver the resolver + * @returns {void} + */ + apply(resolver: Resolver): void; +} +declare namespace AliasFieldPlugin { + export { Resolver, JsonPrimitive, ResolveRequest, ResolveStepHook }; +} +/** @typedef {import("./Resolver")} Resolver */ +/** @typedef {import("./Resolver").JsonPrimitive} JsonPrimitive */ +/** @typedef {import("./Resolver").ResolveRequest} ResolveRequest */ +/** @typedef {import("./Resolver").ResolveStepHook} ResolveStepHook */ +declare const NO_FIELD_OBJECT: unique symbol; +type Resolver = import("./Resolver"); +type JsonPrimitive = import("./Resolver").JsonPrimitive; +type ResolveRequest = import("./Resolver").ResolveRequest; +type ResolveStepHook = import("./Resolver").ResolveStepHook; diff --git a/dg-ui/node_modules/enhanced-resolve/types/AliasPlugin.d.ts b/dg-ui/node_modules/enhanced-resolve/types/AliasPlugin.d.ts new file mode 100644 index 0000000..2aa1766 --- /dev/null +++ b/dg-ui/node_modules/enhanced-resolve/types/AliasPlugin.d.ts @@ -0,0 +1,32 @@ +export = AliasPlugin; +declare class AliasPlugin { + /** + * @param {string | ResolveStepHook} source source + * @param {AliasOption | AliasOption[]} options options + * @param {string | ResolveStepHook} target target + */ + constructor( + source: string | ResolveStepHook, + options: AliasOption | AliasOption[], + target: string | ResolveStepHook, + ); + source: string | import("./Resolver").ResolveStepHook; + options: AliasOption[]; + target: string | import("./Resolver").ResolveStepHook; + /** + * @param {Resolver} resolver the resolver + * @returns {void} + */ + apply(resolver: Resolver): void; +} +declare namespace AliasPlugin { + export { Resolver, ResolveStepHook, Alias, AliasOption }; +} +type Resolver = import("./Resolver"); +type ResolveStepHook = import("./Resolver").ResolveStepHook; +type Alias = string | string[] | false; +type AliasOption = { + alias: Alias; + name: string; + onlyModule?: boolean; +}; diff --git a/dg-ui/node_modules/enhanced-resolve/types/AliasUtils.d.ts b/dg-ui/node_modules/enhanced-resolve/types/AliasUtils.d.ts new file mode 100644 index 0000000..2bf58f3 --- /dev/null +++ b/dg-ui/node_modules/enhanced-resolve/types/AliasUtils.d.ts @@ -0,0 +1,128 @@ +export type InnerCallback = ( + err?: null | Error, + result?: null | ResolveRequest, +) => void; +export type Resolver = import("./Resolver"); +export type ResolveRequest = import("./Resolver").ResolveRequest; +export type ResolveContext = import("./Resolver").ResolveContext; +export type ResolveStepHook = import("./Resolver").ResolveStepHook; +export type ResolveCallback = import("./Resolver").ResolveCallback; +export type Alias = string | string[] | false; +export type AliasOption = { + alias: Alias; + name: string; + onlyModule?: boolean; +}; +export type CompiledAliasOption = { + /** + * original alias name + */ + name: string; + /** + * name + "/" — precomputed to avoid per-resolve concat + */ + nameWithSlash: string; + /** + * alias target(s) + */ + alias: Alias; + /** + * normalized onlyModule flag + */ + onlyModule: boolean; + /** + * absolute form of `name` (with slash ending), null when not absolute + */ + absolutePath: string | null; + /** + * substring before the single "*" in `name`, null when no wildcard + */ + wildcardPrefix: string | null; + /** + * substring after the single "*" in `name`, null when no wildcard + */ + wildcardSuffix: string | null; + /** + * first character code of `name` — used as a cheap screen on the hot path. `-1` indicates "matches any first char" (empty wildcard prefix). + */ + firstCharCode: number; + /** + * true when `alias` is an array — precomputed so the hot path skips `Array.isArray` + */ + arrayAlias: boolean; +}; +/** + * Bucketed view of compiled options used by `aliasResolveHandler` to avoid + * walking the full option list on every resolve. The `all` array preserves + * the legacy linear order (declaration order) for the fallback path. The + * `byFirstChar` map buckets options by the first char code of their `name` + * — each bucket preserves declaration order among its members. The + * `hasAnyFirstChar` flag is true when at least one option matches any + * first char (`firstCharCode === -1`), in which case resolve-time scans + * fall back to `all` to keep declaration-order semantics across buckets. + * The `useBuckets` flag is true only when bucketing would actually help — + * i.e. there are at least 2 distinct first chars AND no empty-prefix + * wildcard. When false, the resolve hot path skips the `Map.get` and + * iterates `all` directly with the per-option first-char-code screen + * (matching the pre-bucketing behavior). This avoids paying for `Map.get` + * on degenerate single-bucket lists like a long chain of aliases that + * all share one first char — the bucket lookup adds overhead without + * narrowing the candidate set, which showed up as a transient-memory + * regression on `pathological-deep-stack`. + */ +export type CompiledAliasOptions = { + /** + * declaration-ordered list + */ + all: CompiledAliasOption[]; + /** + * bucketed by first char code + */ + byFirstChar: Map; + /** + * true when an empty-prefix wildcard is present + */ + hasAnyFirstChar: boolean; + /** + * true when the bucket fast-path should be used at resolve time + */ + useBuckets: boolean; +}; +/** @typedef {(err?: null | Error, result?: null | ResolveRequest) => void} InnerCallback */ +/** + * @param {Resolver} resolver resolver + * @param {CompiledAliasOptions} options compiled options + * @param {ResolveStepHook} target target + * @param {ResolveRequest} request request + * @param {ResolveContext} resolveContext resolve context + * @param {InnerCallback} callback callback + * @returns {void} + */ +export function aliasResolveHandler( + resolver: Resolver, + options: CompiledAliasOptions, + target: ResolveStepHook, + request: ResolveRequest, + resolveContext: ResolveContext, + callback: InnerCallback, +): void; +/** + * Precompute per-option strings used on every resolve so the hot path in + * `aliasResolveHandler` does no string concatenation / split work per entry. + * Called once per plugin apply — the returned structure is stable for the + * lifetime of the resolver. + * + * Beyond the per-option precompute step, this also partitions the list into + * a `byFirstChar` map so that, when no "empty-prefix" wildcards are + * present, the resolve-time scan only walks options whose `name` starts + * with the same char as the current request. For large alias lists (300+ + * entries) this turns an O(N) screen into O(K) where K is the bucket size + * for the request's first char. + * @param {Resolver} resolver resolver + * @param {AliasOption[]} options options + * @returns {CompiledAliasOptions} compiled options + */ +export function compileAliasOptions( + resolver: Resolver, + options: AliasOption[], +): CompiledAliasOptions; diff --git a/dg-ui/node_modules/enhanced-resolve/types/AppendPlugin.d.ts b/dg-ui/node_modules/enhanced-resolve/types/AppendPlugin.d.ts new file mode 100644 index 0000000..97fcf62 --- /dev/null +++ b/dg-ui/node_modules/enhanced-resolve/types/AppendPlugin.d.ts @@ -0,0 +1,27 @@ +export = AppendPlugin; +declare class AppendPlugin { + /** + * @param {string | ResolveStepHook} source source + * @param {string} appending appending + * @param {string | ResolveStepHook} target target + */ + constructor( + source: string | ResolveStepHook, + appending: string, + target: string | ResolveStepHook, + ); + source: string | import("./Resolver").ResolveStepHook; + appending: string; + target: string | import("./Resolver").ResolveStepHook; + /** + * @param {Resolver} resolver the resolver + * @returns {void} + */ + apply(resolver: Resolver): void; +} +declare namespace AppendPlugin { + export { Resolver, ResolveRequest, ResolveStepHook }; +} +type Resolver = import("./Resolver"); +type ResolveRequest = import("./Resolver").ResolveRequest; +type ResolveStepHook = import("./Resolver").ResolveStepHook; diff --git a/dg-ui/node_modules/enhanced-resolve/types/CachedInputFileSystem.d.ts b/dg-ui/node_modules/enhanced-resolve/types/CachedInputFileSystem.d.ts new file mode 100644 index 0000000..5333d24 --- /dev/null +++ b/dg-ui/node_modules/enhanced-resolve/types/CachedInputFileSystem.d.ts @@ -0,0 +1,225 @@ +export = CachedInputFileSystem; +declare class CachedInputFileSystem { + /** + * @param {BaseFileSystem} fileSystem file system + * @param {number} duration duration in ms files are cached + */ + constructor(fileSystem: BaseFileSystem, duration: number); + fileSystem: BaseFileSystem; + _lstatBackend: OperationMergerBackend | CacheBackend; + lstat: import("./Resolver").LStat | undefined; + lstatSync: import("./Resolver").LStatSync | undefined; + _statBackend: OperationMergerBackend | CacheBackend; + stat: import("./Resolver").Stat; + statSync: import("./Resolver").StatSync; + _readdirBackend: OperationMergerBackend | CacheBackend; + readdir: import("./Resolver").Readdir; + readdirSync: import("./Resolver").ReaddirSync; + _readFileBackend: OperationMergerBackend | CacheBackend; + readFile: import("./Resolver").ReadFile; + readFileSync: import("./Resolver").ReadFileSync; + _readJsonBackend: OperationMergerBackend | CacheBackend; + readJson: import("./Resolver").ReadJson | undefined; + readJsonSync: import("./Resolver").ReadJsonSync | undefined; + _readlinkBackend: OperationMergerBackend | CacheBackend; + readlink: import("./Resolver").Readlink; + readlinkSync: import("./Resolver").ReadlinkSync; + _realpathBackend: OperationMergerBackend | CacheBackend; + realpath: import("./Resolver").RealPath | undefined; + realpathSync: import("./Resolver").RealPathSync | undefined; + /** + * @param {(string | Buffer | URL | number | (string | URL | Buffer | number)[] | Set)=} what what to purge + * @param {{ exact?: boolean, readdirPrefix?: boolean }=} options options; `exact: true` removes only cache entries whose key matches `what` exactly instead of any entry whose key starts with `what`; with `exact: true`, `readdirPrefix: true` still removes every `readdir` entry whose key starts with `what`, so the listings of directories below a changed directory are dropped while their file stats are kept + */ + purge( + what?: + | ( + | string + | Buffer + | URL + | number + | (string | URL | Buffer | number)[] + | Set + ) + | undefined, + options?: + | { + exact?: boolean; + readdirPrefix?: boolean; + } + | undefined, + ): void; +} +declare namespace CachedInputFileSystem { + export { + FileSystem, + PathLike, + PathOrFileDescriptor, + SyncFileSystem, + BaseFileSystem, + FileSystemCallback, + EXPECTED_FUNCTION, + EXPECTED_ANY, + Provide, + }; +} +declare class OperationMergerBackend { + /** + * @param {EXPECTED_FUNCTION | undefined} provider async method in filesystem + * @param {EXPECTED_FUNCTION | undefined} syncProvider sync method in filesystem + * @param {BaseFileSystem} providerContext call context for the provider methods + */ + constructor( + provider: EXPECTED_FUNCTION | undefined, + syncProvider: EXPECTED_FUNCTION | undefined, + providerContext: BaseFileSystem, + ); + _provider: Function | undefined; + _syncProvider: Function | undefined; + _providerContext: BaseFileSystem; + _activeAsyncOperations: Map; + provide: + | (( + path: PathLike | PathOrFileDescriptor, + options: object | FileSystemCallback | undefined, + callback?: FileSystemCallback | undefined, + ) => EXPECTED_ANY) + | null; + provideSync: + | (( + path: PathLike | PathOrFileDescriptor, + options?: object | undefined, + ) => EXPECTED_ANY) + | null; + purge(): void; + purgeParent(): void; +} +/** + * @callback Provide + * @param {PathLike | PathOrFileDescriptor} path path + * @param {EXPECTED_ANY} options options + * @param {FileSystemCallback} callback callback + * @returns {void} + */ +declare class CacheBackend { + /** + * @param {number} duration max cache duration of items + * @param {EXPECTED_FUNCTION | undefined} provider async method + * @param {EXPECTED_FUNCTION | undefined} syncProvider sync method + * @param {BaseFileSystem} providerContext call context for the provider methods + */ + constructor( + duration: number, + provider: EXPECTED_FUNCTION | undefined, + syncProvider: EXPECTED_FUNCTION | undefined, + providerContext: BaseFileSystem, + ); + _duration: number; + _provider: Function | undefined; + _syncProvider: Function | undefined; + _providerContext: BaseFileSystem; + /** @type {Map[]>} */ + _activeAsyncOperations: Map[]>; + /** @type {Map }>} */ + _data: Map< + string, + { + err: Error | null; + result?: EXPECTED_ANY; + level: Set; + } + >; + /** @type {Set[]} */ + _levels: Set[]; + _currentLevel: number; + _tickInterval: number; + /** @type {STORAGE_MODE_IDLE | STORAGE_MODE_SYNC | STORAGE_MODE_ASYNC} */ + _mode: 0 | 1 | 2; + /** @type {NodeJS.Timeout | undefined} */ + _timeout: NodeJS.Timeout | undefined; + /** @type {number | undefined} */ + _nextDecay: number | undefined; + /** + * @param {PathLike | PathOrFileDescriptor} path path + * @param {EXPECTED_ANY} options options + * @param {FileSystemCallback} callback callback + * @returns {void} + */ + provide( + path: PathLike | PathOrFileDescriptor, + options: EXPECTED_ANY, + callback: FileSystemCallback, + ): void; + /** + * @param {PathLike | PathOrFileDescriptor} path path + * @param {EXPECTED_ANY} options options + * @returns {EXPECTED_ANY} result + */ + provideSync( + path: PathLike | PathOrFileDescriptor, + options: EXPECTED_ANY, + ): EXPECTED_ANY; + /** + * @param {(string | Buffer | URL | number | (string | URL | Buffer | number)[] | Set)=} what what to purge + * @param {{ exact?: boolean }=} options options; `exact: true` removes only entries whose key matches `what` exactly instead of any entry whose key starts with `what` + */ + purge( + what?: + | ( + | string + | Buffer + | URL + | number + | (string | URL | Buffer | number)[] + | Set + ) + | undefined, + options?: + | { + exact?: boolean; + } + | undefined, + ): void; + /** + * @param {(string | Buffer | URL | number | (string | URL | Buffer | number)[] | Set)=} what what to purge + */ + purgeParent( + what?: + | ( + | string + | Buffer + | URL + | number + | (string | URL | Buffer | number)[] + | Set + ) + | undefined, + ): void; + /** + * @param {string} path path + * @param {Error | null} err error + * @param {EXPECTED_ANY} result result + */ + _storeResult(path: string, err: Error | null, result: EXPECTED_ANY): void; + _decayLevel(): void; + _runDecays(): void; + _enterAsyncMode(): void; + _enterSyncModeWhenIdle(): void; + _enterIdleMode(): void; +} +type FileSystem = import("./Resolver").FileSystem; +type PathLike = import("./Resolver").PathLike; +type PathOrFileDescriptor = import("./Resolver").PathOrFileDescriptor; +type SyncFileSystem = import("./Resolver").SyncFileSystem; +type BaseFileSystem = FileSystem & SyncFileSystem; +/** + * + */ +type FileSystemCallback = import("./Resolver").FileSystemCallback; +type EXPECTED_FUNCTION = Function; +type EXPECTED_ANY = any; +type Provide = ( + path: PathLike | PathOrFileDescriptor, + options: EXPECTED_ANY, + callback: FileSystemCallback, +) => void; diff --git a/dg-ui/node_modules/enhanced-resolve/types/CloneBasenamePlugin.d.ts b/dg-ui/node_modules/enhanced-resolve/types/CloneBasenamePlugin.d.ts new file mode 100644 index 0000000..a0b852d --- /dev/null +++ b/dg-ui/node_modules/enhanced-resolve/types/CloneBasenamePlugin.d.ts @@ -0,0 +1,24 @@ +export = CloneBasenamePlugin; +declare class CloneBasenamePlugin { + /** + * @param {string | ResolveStepHook} source source + * @param {string | ResolveStepHook} target target + */ + constructor( + source: string | ResolveStepHook, + target: string | ResolveStepHook, + ); + source: string | import("./Resolver").ResolveStepHook; + target: string | import("./Resolver").ResolveStepHook; + /** + * @param {Resolver} resolver the resolver + * @returns {void} + */ + apply(resolver: Resolver): void; +} +declare namespace CloneBasenamePlugin { + export { Resolver, ResolveRequest, ResolveStepHook }; +} +type Resolver = import("./Resolver"); +type ResolveRequest = import("./Resolver").ResolveRequest; +type ResolveStepHook = import("./Resolver").ResolveStepHook; diff --git a/dg-ui/node_modules/enhanced-resolve/types/ConditionalPlugin.d.ts b/dg-ui/node_modules/enhanced-resolve/types/ConditionalPlugin.d.ts new file mode 100644 index 0000000..a3c70e1 --- /dev/null +++ b/dg-ui/node_modules/enhanced-resolve/types/ConditionalPlugin.d.ts @@ -0,0 +1,33 @@ +export = ConditionalPlugin; +declare class ConditionalPlugin { + /** + * @param {string | ResolveStepHook} source source + * @param {Partial} test compare object + * @param {string | null} message log message + * @param {boolean} allowAlternatives when false, do not continue with the current step when "test" matches + * @param {string | ResolveStepHook} target target + */ + constructor( + source: string | ResolveStepHook, + test: Partial, + message: string | null, + allowAlternatives: boolean, + target: string | ResolveStepHook, + ); + source: string | import("./Resolver").ResolveStepHook; + test: Partial; + message: string | null; + allowAlternatives: boolean; + target: string | import("./Resolver").ResolveStepHook; + /** + * @param {Resolver} resolver the resolver + * @returns {void} + */ + apply(resolver: Resolver): void; +} +declare namespace ConditionalPlugin { + export { Resolver, ResolveRequest, ResolveStepHook }; +} +type Resolver = import("./Resolver"); +type ResolveRequest = import("./Resolver").ResolveRequest; +type ResolveStepHook = import("./Resolver").ResolveStepHook; diff --git a/dg-ui/node_modules/enhanced-resolve/types/DescriptionFilePlugin.d.ts b/dg-ui/node_modules/enhanced-resolve/types/DescriptionFilePlugin.d.ts new file mode 100644 index 0000000..c063cd7 --- /dev/null +++ b/dg-ui/node_modules/enhanced-resolve/types/DescriptionFilePlugin.d.ts @@ -0,0 +1,30 @@ +export = DescriptionFilePlugin; +declare class DescriptionFilePlugin { + /** + * @param {string | ResolveStepHook} source source + * @param {string[]} filenames filenames + * @param {boolean} pathIsFile pathIsFile + * @param {string | ResolveStepHook} target target + */ + constructor( + source: string | ResolveStepHook, + filenames: string[], + pathIsFile: boolean, + target: string | ResolveStepHook, + ); + source: string | import("./Resolver").ResolveStepHook; + filenames: string[]; + pathIsFile: boolean; + target: string | import("./Resolver").ResolveStepHook; + /** + * @param {Resolver} resolver the resolver + * @returns {void} + */ + apply(resolver: Resolver): void; +} +declare namespace DescriptionFilePlugin { + export { Resolver, ResolveRequest, ResolveStepHook }; +} +type Resolver = import("./Resolver"); +type ResolveRequest = import("./Resolver").ResolveRequest; +type ResolveStepHook = import("./Resolver").ResolveStepHook; diff --git a/dg-ui/node_modules/enhanced-resolve/types/DescriptionFileUtils.d.ts b/dg-ui/node_modules/enhanced-resolve/types/DescriptionFileUtils.d.ts new file mode 100644 index 0000000..2938564 --- /dev/null +++ b/dg-ui/node_modules/enhanced-resolve/types/DescriptionFileUtils.d.ts @@ -0,0 +1,83 @@ +export type Resolver = import("./Resolver"); +export type JsonObject = import("./Resolver").JsonObject; +export type JsonValue = import("./Resolver").JsonValue; +export type ResolveContext = import("./Resolver").ResolveContext; +export type ResolveRequest = import("./Resolver").ResolveRequest; +export type DescriptionFileInfo = { + /** + * content + */ + content?: JsonObject | undefined; + /** + * path + */ + path: string; + /** + * directory + */ + directory: string; +}; +export type ErrorFirstCallback = ( + error?: (Error | null) | undefined, + result?: DescriptionFileInfo | undefined, +) => any; +export type Result = { + /** + * path to description file + */ + path: string; + /** + * directory of description file + */ + directory: string; + /** + * content of description file + */ + content: JsonObject; +}; +/** + * Walk up one directory. Called once per package-root candidate and once per + * `described-resolve` (to find the enclosing description file), so it's on + * the resolver's hot path. + * + * Previous implementation called `lastIndexOf("/")` and `lastIndexOf("\\")` + * separately and then picked the larger. For any non-trivial directory + * string on POSIX, `lastIndexOf("\\")` scans the full string just to return + * -1. A single reverse char-code scan does the same work in one pass. + * + * Any single-character directory is treated as a root — `directory.length + * <= 1` collapses the `"/"`, `"\\"` and `""` branches into one compare. + * Without the `"\\"` case, `cdUp("\\")` (reached from a UNC root or a DOS + * device path like `\\?\…`) would return itself via `slice(0, i || 1)` + * and trap `loadDescriptionFile` in an infinite loop. Once single-char + * roots are filtered up front, the reverse scan always produces a + * strictly shorter string. + * @param {string} directory directory + * @returns {string | null} parent directory or null + */ +export function cdUp(directory: string): string | null; +/** + * @param {JsonObject} content content + * @param {string | string[]} field field + * @returns {JsonValue | undefined} field data + */ +export function getField( + content: JsonObject, + field: string | string[], +): JsonValue | undefined; +/** + * @param {Resolver} resolver resolver + * @param {string} directory directory + * @param {string[]} filenames filenames + * @param {DescriptionFileInfo | undefined} oldInfo oldInfo + * @param {ResolveContext} resolveContext resolveContext + * @param {ErrorFirstCallback} callback callback + */ +export function loadDescriptionFile( + resolver: Resolver, + directory: string, + filenames: string[], + oldInfo: DescriptionFileInfo | undefined, + resolveContext: ResolveContext, + callback: ErrorFirstCallback, +): void; diff --git a/dg-ui/node_modules/enhanced-resolve/types/DirectoryExistsPlugin.d.ts b/dg-ui/node_modules/enhanced-resolve/types/DirectoryExistsPlugin.d.ts new file mode 100644 index 0000000..025b53e --- /dev/null +++ b/dg-ui/node_modules/enhanced-resolve/types/DirectoryExistsPlugin.d.ts @@ -0,0 +1,23 @@ +export = DirectoryExistsPlugin; +declare class DirectoryExistsPlugin { + /** + * @param {string | ResolveStepHook} source source + * @param {string | ResolveStepHook} target target + */ + constructor( + source: string | ResolveStepHook, + target: string | ResolveStepHook, + ); + source: string | import("./Resolver").ResolveStepHook; + target: string | import("./Resolver").ResolveStepHook; + /** + * @param {Resolver} resolver the resolver + * @returns {void} + */ + apply(resolver: Resolver): void; +} +declare namespace DirectoryExistsPlugin { + export { Resolver, ResolveStepHook }; +} +type Resolver = import("./Resolver"); +type ResolveStepHook = import("./Resolver").ResolveStepHook; diff --git a/dg-ui/node_modules/enhanced-resolve/types/ExportsFieldPlugin.d.ts b/dg-ui/node_modules/enhanced-resolve/types/ExportsFieldPlugin.d.ts new file mode 100644 index 0000000..84b5375 --- /dev/null +++ b/dg-ui/node_modules/enhanced-resolve/types/ExportsFieldPlugin.d.ts @@ -0,0 +1,45 @@ +export = ExportsFieldPlugin; +declare class ExportsFieldPlugin { + /** + * @param {string | ResolveStepHook} source source + * @param {Set} conditionNames condition names + * @param {string | string[]} fieldNamePath name path + * @param {string | ResolveStepHook} target target + * @param {boolean=} restrictions whether `restrictions` are configured (enables exports-target fallback when a target is filtered out) + */ + constructor( + source: string | ResolveStepHook, + conditionNames: Set, + fieldNamePath: string | string[], + target: string | ResolveStepHook, + restrictions?: boolean | undefined, + ); + source: string | import("./Resolver").ResolveStepHook; + target: string | import("./Resolver").ResolveStepHook; + conditionNames: Set; + fieldName: string | string[]; + restrictions: boolean; + /** @type {WeakMap} */ + _fieldProcessorCache: WeakMap; + /** + * @param {Resolver} resolver the resolver + * @returns {void} + */ + apply(resolver: Resolver): void; +} +declare namespace ExportsFieldPlugin { + export { + Resolver, + JsonObject, + ResolveRequest, + ResolveStepHook, + ExportsField, + FieldProcessor, + }; +} +type Resolver = import("./Resolver"); +type JsonObject = import("./Resolver").JsonObject; +type ResolveRequest = import("./Resolver").ResolveRequest; +type ResolveStepHook = import("./Resolver").ResolveStepHook; +type ExportsField = import("./util/entrypoints").ExportsField; +type FieldProcessor = import("./util/entrypoints").FieldProcessor; diff --git a/dg-ui/node_modules/enhanced-resolve/types/ExtensionAliasPlugin.d.ts b/dg-ui/node_modules/enhanced-resolve/types/ExtensionAliasPlugin.d.ts new file mode 100644 index 0000000..39b3549 --- /dev/null +++ b/dg-ui/node_modules/enhanced-resolve/types/ExtensionAliasPlugin.d.ts @@ -0,0 +1,31 @@ +export = ExtensionAliasPlugin; +declare class ExtensionAliasPlugin { + /** + * @param {string | ResolveStepHook} source source + * @param {ExtensionAliasOption} options options + * @param {string | ResolveStepHook} target target + */ + constructor( + source: string | ResolveStepHook, + options: ExtensionAliasOption, + target: string | ResolveStepHook, + ); + source: string | import("./Resolver").ResolveStepHook; + options: ExtensionAliasOption; + target: string | import("./Resolver").ResolveStepHook; + /** + * @param {Resolver} resolver the resolver + * @returns {void} + */ + apply(resolver: Resolver): void; +} +declare namespace ExtensionAliasPlugin { + export { Resolver, ResolveRequest, ResolveStepHook, ExtensionAliasOption }; +} +type Resolver = import("./Resolver"); +type ResolveRequest = import("./Resolver").ResolveRequest; +type ResolveStepHook = import("./Resolver").ResolveStepHook; +type ExtensionAliasOption = { + alias: string | string[]; + extension: string; +}; diff --git a/dg-ui/node_modules/enhanced-resolve/types/FileExistsPlugin.d.ts b/dg-ui/node_modules/enhanced-resolve/types/FileExistsPlugin.d.ts new file mode 100644 index 0000000..d4f7aee --- /dev/null +++ b/dg-ui/node_modules/enhanced-resolve/types/FileExistsPlugin.d.ts @@ -0,0 +1,23 @@ +export = FileExistsPlugin; +declare class FileExistsPlugin { + /** + * @param {string | ResolveStepHook} source source + * @param {string | ResolveStepHook} target target + */ + constructor( + source: string | ResolveStepHook, + target: string | ResolveStepHook, + ); + source: string | import("./Resolver").ResolveStepHook; + target: string | import("./Resolver").ResolveStepHook; + /** + * @param {Resolver} resolver the resolver + * @returns {void} + */ + apply(resolver: Resolver): void; +} +declare namespace FileExistsPlugin { + export { Resolver, ResolveStepHook }; +} +type Resolver = import("./Resolver"); +type ResolveStepHook = import("./Resolver").ResolveStepHook; diff --git a/dg-ui/node_modules/enhanced-resolve/types/ImportsFieldPlugin.d.ts b/dg-ui/node_modules/enhanced-resolve/types/ImportsFieldPlugin.d.ts new file mode 100644 index 0000000..197d04b --- /dev/null +++ b/dg-ui/node_modules/enhanced-resolve/types/ImportsFieldPlugin.d.ts @@ -0,0 +1,45 @@ +export = ImportsFieldPlugin; +declare class ImportsFieldPlugin { + /** + * @param {string | ResolveStepHook} source source + * @param {Set} conditionNames condition names + * @param {string | string[]} fieldNamePath name path + * @param {string | ResolveStepHook} targetFile target file + * @param {string | ResolveStepHook} targetPackage target package + */ + constructor( + source: string | ResolveStepHook, + conditionNames: Set, + fieldNamePath: string | string[], + targetFile: string | ResolveStepHook, + targetPackage: string | ResolveStepHook, + ); + source: string | import("./Resolver").ResolveStepHook; + targetFile: string | import("./Resolver").ResolveStepHook; + targetPackage: string | import("./Resolver").ResolveStepHook; + conditionNames: Set; + fieldName: string | string[]; + /** @type {WeakMap} */ + _fieldProcessorCache: WeakMap; + /** + * @param {Resolver} resolver the resolver + * @returns {void} + */ + apply(resolver: Resolver): void; +} +declare namespace ImportsFieldPlugin { + export { + Resolver, + JsonObject, + ResolveRequest, + ResolveStepHook, + FieldProcessor, + ImportsField, + }; +} +type Resolver = import("./Resolver"); +type JsonObject = import("./Resolver").JsonObject; +type ResolveRequest = import("./Resolver").ResolveRequest; +type ResolveStepHook = import("./Resolver").ResolveStepHook; +type FieldProcessor = import("./util/entrypoints").FieldProcessor; +type ImportsField = import("./util/entrypoints").ImportsField; diff --git a/dg-ui/node_modules/enhanced-resolve/types/JoinRequestPartPlugin.d.ts b/dg-ui/node_modules/enhanced-resolve/types/JoinRequestPartPlugin.d.ts new file mode 100644 index 0000000..2783403 --- /dev/null +++ b/dg-ui/node_modules/enhanced-resolve/types/JoinRequestPartPlugin.d.ts @@ -0,0 +1,24 @@ +export = JoinRequestPartPlugin; +declare class JoinRequestPartPlugin { + /** + * @param {string | ResolveStepHook} source source + * @param {string | ResolveStepHook} target target + */ + constructor( + source: string | ResolveStepHook, + target: string | ResolveStepHook, + ); + source: string | import("./Resolver").ResolveStepHook; + target: string | import("./Resolver").ResolveStepHook; + /** + * @param {Resolver} resolver the resolver + * @returns {void} + */ + apply(resolver: Resolver): void; +} +declare namespace JoinRequestPartPlugin { + export { Resolver, ResolveRequest, ResolveStepHook }; +} +type Resolver = import("./Resolver"); +type ResolveRequest = import("./Resolver").ResolveRequest; +type ResolveStepHook = import("./Resolver").ResolveStepHook; diff --git a/dg-ui/node_modules/enhanced-resolve/types/JoinRequestPlugin.d.ts b/dg-ui/node_modules/enhanced-resolve/types/JoinRequestPlugin.d.ts new file mode 100644 index 0000000..b9fe526 --- /dev/null +++ b/dg-ui/node_modules/enhanced-resolve/types/JoinRequestPlugin.d.ts @@ -0,0 +1,24 @@ +export = JoinRequestPlugin; +declare class JoinRequestPlugin { + /** + * @param {string | ResolveStepHook} source source + * @param {string | ResolveStepHook} target target + */ + constructor( + source: string | ResolveStepHook, + target: string | ResolveStepHook, + ); + source: string | import("./Resolver").ResolveStepHook; + target: string | import("./Resolver").ResolveStepHook; + /** + * @param {Resolver} resolver the resolver + * @returns {void} + */ + apply(resolver: Resolver): void; +} +declare namespace JoinRequestPlugin { + export { Resolver, ResolveRequest, ResolveStepHook }; +} +type Resolver = import("./Resolver"); +type ResolveRequest = import("./Resolver").ResolveRequest; +type ResolveStepHook = import("./Resolver").ResolveStepHook; diff --git a/dg-ui/node_modules/enhanced-resolve/types/LogInfoPlugin.d.ts b/dg-ui/node_modules/enhanced-resolve/types/LogInfoPlugin.d.ts new file mode 100644 index 0000000..9fe3d72 --- /dev/null +++ b/dg-ui/node_modules/enhanced-resolve/types/LogInfoPlugin.d.ts @@ -0,0 +1,18 @@ +export = LogInfoPlugin; +declare class LogInfoPlugin { + /** + * @param {string | ResolveStepHook} source source + */ + constructor(source: string | ResolveStepHook); + source: string | import("./Resolver").ResolveStepHook; + /** + * @param {Resolver} resolver the resolver + * @returns {void} + */ + apply(resolver: Resolver): void; +} +declare namespace LogInfoPlugin { + export { Resolver, ResolveStepHook }; +} +type Resolver = import("./Resolver"); +type ResolveStepHook = import("./Resolver").ResolveStepHook; diff --git a/dg-ui/node_modules/enhanced-resolve/types/MainFieldPlugin.d.ts b/dg-ui/node_modules/enhanced-resolve/types/MainFieldPlugin.d.ts new file mode 100644 index 0000000..1b31126 --- /dev/null +++ b/dg-ui/node_modules/enhanced-resolve/types/MainFieldPlugin.d.ts @@ -0,0 +1,41 @@ +export = MainFieldPlugin; +declare class MainFieldPlugin { + /** + * @param {string | ResolveStepHook} source source + * @param {MainFieldOptions} options options + * @param {string | ResolveStepHook} target target + */ + constructor( + source: string | ResolveStepHook, + options: MainFieldOptions, + target: string | ResolveStepHook, + ); + source: string | import("./Resolver").ResolveStepHook; + options: MainFieldOptions; + target: string | import("./Resolver").ResolveStepHook; + /** @type {WeakMap} */ + _mainModuleCache: WeakMap; + /** + * @param {Resolver} resolver the resolver + * @returns {void} + */ + apply(resolver: Resolver): void; +} +declare namespace MainFieldPlugin { + export { + Resolver, + JsonObject, + ResolveRequest, + ResolveStepHook, + MainFieldOptions, + }; +} +declare const NO_MAIN: unique symbol; +type Resolver = import("./Resolver"); +type JsonObject = import("./Resolver").JsonObject; +type ResolveRequest = import("./Resolver").ResolveRequest; +type ResolveStepHook = import("./Resolver").ResolveStepHook; +type MainFieldOptions = { + name: string | string[]; + forceRelative: boolean; +}; diff --git a/dg-ui/node_modules/enhanced-resolve/types/ModulesInHierachicDirectoriesPlugin.d.ts b/dg-ui/node_modules/enhanced-resolve/types/ModulesInHierachicDirectoriesPlugin.d.ts new file mode 100644 index 0000000..2c30949 --- /dev/null +++ b/dg-ui/node_modules/enhanced-resolve/types/ModulesInHierachicDirectoriesPlugin.d.ts @@ -0,0 +1,2 @@ +declare const _exports: typeof import("./ModulesInHierarchicalDirectoriesPlugin"); +export = _exports; diff --git a/dg-ui/node_modules/enhanced-resolve/types/ModulesInHierarchicalDirectoriesPlugin.d.ts b/dg-ui/node_modules/enhanced-resolve/types/ModulesInHierarchicalDirectoriesPlugin.d.ts new file mode 100644 index 0000000..af501ce --- /dev/null +++ b/dg-ui/node_modules/enhanced-resolve/types/ModulesInHierarchicalDirectoriesPlugin.d.ts @@ -0,0 +1,26 @@ +export = ModulesInHierarchicalDirectoriesPlugin; +declare class ModulesInHierarchicalDirectoriesPlugin { + /** + * @param {string | ResolveStepHook} source source + * @param {string | string[]} directories directories + * @param {string | ResolveStepHook} target target + */ + constructor( + source: string | ResolveStepHook, + directories: string | string[], + target: string | ResolveStepHook, + ); + source: string | import("./Resolver").ResolveStepHook; + directories: string[]; + target: string | import("./Resolver").ResolveStepHook; + /** + * @param {Resolver} resolver the resolver + * @returns {void} + */ + apply(resolver: Resolver): void; +} +declare namespace ModulesInHierarchicalDirectoriesPlugin { + export { Resolver, ResolveStepHook }; +} +type Resolver = import("./Resolver"); +type ResolveStepHook = import("./Resolver").ResolveStepHook; diff --git a/dg-ui/node_modules/enhanced-resolve/types/ModulesInRootPlugin.d.ts b/dg-ui/node_modules/enhanced-resolve/types/ModulesInRootPlugin.d.ts new file mode 100644 index 0000000..87a61fd --- /dev/null +++ b/dg-ui/node_modules/enhanced-resolve/types/ModulesInRootPlugin.d.ts @@ -0,0 +1,27 @@ +export = ModulesInRootPlugin; +declare class ModulesInRootPlugin { + /** + * @param {string | ResolveStepHook} source source + * @param {string} path path + * @param {string | ResolveStepHook} target target + */ + constructor( + source: string | ResolveStepHook, + path: string, + target: string | ResolveStepHook, + ); + source: string | import("./Resolver").ResolveStepHook; + path: string; + target: string | import("./Resolver").ResolveStepHook; + /** + * @param {Resolver} resolver the resolver + * @returns {void} + */ + apply(resolver: Resolver): void; +} +declare namespace ModulesInRootPlugin { + export { Resolver, ResolveRequest, ResolveStepHook }; +} +type Resolver = import("./Resolver"); +type ResolveRequest = import("./Resolver").ResolveRequest; +type ResolveStepHook = import("./Resolver").ResolveStepHook; diff --git a/dg-ui/node_modules/enhanced-resolve/types/ModulesUtils.d.ts b/dg-ui/node_modules/enhanced-resolve/types/ModulesUtils.d.ts new file mode 100644 index 0000000..9a55bf7 --- /dev/null +++ b/dg-ui/node_modules/enhanced-resolve/types/ModulesUtils.d.ts @@ -0,0 +1,25 @@ +export type Resolver = import("./Resolver"); +export type ResolveRequest = import("./Resolver").ResolveRequest; +export type ResolveStepHook = import("./Resolver").ResolveStepHook; +export type ResolveContext = import("./Resolver").ResolveContext; +export type InnerCallback = ( + err?: null | Error, + result?: null | ResolveRequest, +) => void; +/** + * @param {Resolver} resolver resolver + * @param {string[]} directories directories + * @param {ResolveStepHook} target target + * @param {ResolveRequest} request request + * @param {ResolveContext} resolveContext resolve context + * @param {InnerCallback} callback callback + * @returns {void} + */ +export function modulesResolveHandler( + resolver: Resolver, + directories: string[], + target: ResolveStepHook, + request: ResolveRequest, + resolveContext: ResolveContext, + callback: InnerCallback, +): void; diff --git a/dg-ui/node_modules/enhanced-resolve/types/NextPlugin.d.ts b/dg-ui/node_modules/enhanced-resolve/types/NextPlugin.d.ts new file mode 100644 index 0000000..6a93aac --- /dev/null +++ b/dg-ui/node_modules/enhanced-resolve/types/NextPlugin.d.ts @@ -0,0 +1,23 @@ +export = NextPlugin; +declare class NextPlugin { + /** + * @param {string | ResolveStepHook} source source + * @param {string | ResolveStepHook} target target + */ + constructor( + source: string | ResolveStepHook, + target: string | ResolveStepHook, + ); + source: string | import("./Resolver").ResolveStepHook; + target: string | import("./Resolver").ResolveStepHook; + /** + * @param {Resolver} resolver the resolver + * @returns {void} + */ + apply(resolver: Resolver): void; +} +declare namespace NextPlugin { + export { Resolver, ResolveStepHook }; +} +type Resolver = import("./Resolver"); +type ResolveStepHook = import("./Resolver").ResolveStepHook; diff --git a/dg-ui/node_modules/enhanced-resolve/types/PackageMapPlugin.d.ts b/dg-ui/node_modules/enhanced-resolve/types/PackageMapPlugin.d.ts new file mode 100644 index 0000000..76a3777 --- /dev/null +++ b/dg-ui/node_modules/enhanced-resolve/types/PackageMapPlugin.d.ts @@ -0,0 +1,85 @@ +export = PackageMapPlugin; +declare class PackageMapPlugin { + /** + * @param {string | ResolveStepHook} source source + * @param {PackageMapOptions} options package map options + * @param {boolean} symlinks whether the resolver resolves symlinks + * @param {string | ResolveStepHook} target target + */ + constructor( + source: string | ResolveStepHook, + options: PackageMapOptions, + symlinks: boolean, + target: string | ResolveStepHook, + ); + source: string | import("./Resolver").ResolveStepHook; + options: PackageMapOptions; + symlinks: boolean; + target: string | import("./Resolver").ResolveStepHook; + /** @type {PackageMap | undefined} */ + _packageMap: PackageMap | undefined; + /** @type {PackageMapCallback[] | undefined} */ + _pending: PackageMapCallback[] | undefined; + /** + * Read and parse the configuration file once, queueing every request that + * arrives while the read is in flight so a cold start does not re-read the + * same file for each of them. + * @param {Resolver} resolver the resolver + * @param {ResolveContext} resolveContext resolve context + * @param {PackageMapCallback} callback callback + * @returns {void} + */ + _getPackageMap( + resolver: Resolver, + resolveContext: ResolveContext, + callback: PackageMapCallback, + ): void; + /** + * Hand back the configuration file path package locations resolve against: + * its real path when the resolver follows symlinks, and the path as given + * otherwise. A configuration file whose real path cannot be read (it may not + * exist, or the file system may not implement it) is used as-is, so the + * read below reports the problem. + * @param {Resolver} resolver the resolver + * @param {(configFile: string) => void} callback callback + * @returns {void} + */ + _resolveConfigFile( + resolver: Resolver, + callback: (configFile: string) => void, + ): void; + /** + * @param {Resolver} resolver the resolver + * @returns {void} + */ + apply(resolver: Resolver): void; +} +declare namespace PackageMapPlugin { + export { + Resolver, + ResolveContext, + ResolveRequest, + ResolveStepHook, + PackageMap, + PackageMapPackages, + PackageMapOptions, + PackageMapCallback, + }; +} +type Resolver = import("./Resolver"); +type ResolveContext = import("./Resolver").ResolveContext; +type ResolveRequest = import("./Resolver").ResolveRequest; +type ResolveStepHook = import("./Resolver").ResolveStepHook; +type PackageMap = import("./util/packageMap").PackageMap; +type PackageMapPackages = import("./util/packageMap").PackageMapPackages; +type PackageMapOptions = { + /** + * absolute path of the configuration file, read lazily when `packages` is not given + */ + configFile: string; + /** + * an already-parsed `packages` object, used instead of reading `configFile` + */ + packages: PackageMapPackages | null; +}; +type PackageMapCallback = (err: Error | null, packageMap?: PackageMap) => void; diff --git a/dg-ui/node_modules/enhanced-resolve/types/ParsePlugin.d.ts b/dg-ui/node_modules/enhanced-resolve/types/ParsePlugin.d.ts new file mode 100644 index 0000000..3997504 --- /dev/null +++ b/dg-ui/node_modules/enhanced-resolve/types/ParsePlugin.d.ts @@ -0,0 +1,27 @@ +export = ParsePlugin; +declare class ParsePlugin { + /** + * @param {string | ResolveStepHook} source source + * @param {Partial} requestOptions request options + * @param {string | ResolveStepHook} target target + */ + constructor( + source: string | ResolveStepHook, + requestOptions: Partial, + target: string | ResolveStepHook, + ); + source: string | import("./Resolver").ResolveStepHook; + requestOptions: Partial; + target: string | import("./Resolver").ResolveStepHook; + /** + * @param {Resolver} resolver the resolver + * @returns {void} + */ + apply(resolver: Resolver): void; +} +declare namespace ParsePlugin { + export { Resolver, ResolveRequest, ResolveStepHook }; +} +type Resolver = import("./Resolver"); +type ResolveRequest = import("./Resolver").ResolveRequest; +type ResolveStepHook = import("./Resolver").ResolveStepHook; diff --git a/dg-ui/node_modules/enhanced-resolve/types/PnpPlugin.d.ts b/dg-ui/node_modules/enhanced-resolve/types/PnpPlugin.d.ts new file mode 100644 index 0000000..18e1109 --- /dev/null +++ b/dg-ui/node_modules/enhanced-resolve/types/PnpPlugin.d.ts @@ -0,0 +1,42 @@ +export = PnpPlugin; +declare class PnpPlugin { + /** + * @param {string | ResolveStepHook} source source + * @param {PnpApiImpl} pnpApi pnpApi + * @param {string | ResolveStepHook} target target + * @param {string | ResolveStepHook} alternateTarget alternateTarget + */ + constructor( + source: string | ResolveStepHook, + pnpApi: PnpApiImpl, + target: string | ResolveStepHook, + alternateTarget: string | ResolveStepHook, + ); + source: string | import("./Resolver").ResolveStepHook; + pnpApi: PnpApiImpl; + target: string | import("./Resolver").ResolveStepHook; + alternateTarget: string | import("./Resolver").ResolveStepHook; + /** + * @param {Resolver} resolver the resolver + * @returns {void} + */ + apply(resolver: Resolver): void; +} +declare namespace PnpPlugin { + export { Resolver, ResolveStepHook, ResolveRequest, PnpApiImpl }; +} +type Resolver = import("./Resolver"); +type ResolveStepHook = import("./Resolver").ResolveStepHook; +type ResolveRequest = import("./Resolver").ResolveRequest; +type PnpApiImpl = { + /** + * resolve to unqualified + */ + resolveToUnqualified: ( + packageName: string, + issuer: string, + options: { + considerBuiltins: boolean; + }, + ) => string | null; +}; diff --git a/dg-ui/node_modules/enhanced-resolve/types/Resolver.d.ts b/dg-ui/node_modules/enhanced-resolve/types/Resolver.d.ts new file mode 100644 index 0000000..9fc54fc --- /dev/null +++ b/dg-ui/node_modules/enhanced-resolve/types/Resolver.d.ts @@ -0,0 +1,1546 @@ +export = Resolver; +declare class Resolver { + /** + * @param {ResolveStepHook} hook hook + * @param {ResolveRequest} request request + * @param {StackEntry=} parent previous tip of the stack + * @param {Set=} preSeeded entries pre-seeded via the legacy `Set` API + * @returns {StackEntry} stack entry + */ + static createStackEntry( + hook: ResolveStepHook, + request: ResolveRequest, + parent?: StackEntry | undefined, + preSeeded?: Set | undefined, + ): StackEntry; + /** + * @param {FileSystem} fileSystem a filesystem + * @param {ResolveOptions} options options + */ + constructor(fileSystem: FileSystem, options: ResolveOptions); + /** @type {FileSystem} */ + fileSystem: FileSystem; + /** @type {ResolveOptions} */ + options: ResolveOptions; + /** @type {PathCacheFunctions} */ + pathCache: PathCacheFunctions; + /** @type {KnownHooks} */ + hooks: KnownHooks; + /** + * @param {string | ResolveStepHook} name hook name or hook itself + * @returns {ResolveStepHook} the hook + */ + ensureHook(name: string | ResolveStepHook): ResolveStepHook; + /** + * @param {string | ResolveStepHook} name hook name or hook itself + * @returns {ResolveStepHook} the hook + */ + getHook(name: string | ResolveStepHook): ResolveStepHook; + /** + * @overload + * @param {string | URL} parent context path or a `file:` URL + * @param {string | URL} specifier request string or a `file:` URL + * @param {ResolveContext=} resolveContext resolve context + * @returns {string | false} result + */ + resolveSync( + parent: string | URL, + specifier: string | URL, + resolveContext?: ResolveContext | undefined, + ): string | false; + /** + * @overload + * @param {Context} context context information object + * @param {string | URL} parent context path or a `file:` URL + * @param {string | URL} specifier request string or a `file:` URL + * @param {ResolveContext=} resolveContext resolve context + * @returns {string | false} result + */ + resolveSync( + context: Context, + parent: string | URL, + specifier: string | URL, + resolveContext?: ResolveContext | undefined, + ): string | false; + /** + * @overload + * @param {string | URL} parent context path or a `file:` URL + * @param {string | URL} specifier request string or a `file:` URL + * @param {ResolveContext=} resolveContext resolve context + * @returns {Promise} result + */ + resolvePromise( + parent: string | URL, + specifier: string | URL, + resolveContext?: ResolveContext | undefined, + ): Promise; + /** + * @overload + * @param {Context} context context information object + * @param {string | URL} parent context path or a `file:` URL + * @param {string | URL} specifier request string or a `file:` URL + * @param {ResolveContext=} resolveContext resolve context + * @returns {Promise} result + */ + resolvePromise( + context: Context, + parent: string | URL, + specifier: string | URL, + resolveContext?: ResolveContext | undefined, + ): Promise; + /** + * @overload + * @param {string | URL} parent context path or a `file:` URL + * @param {string | URL} specifier request string or a `file:` URL + * @param {ResolveCallback} callback callback function + * @returns {void} + */ + resolve( + parent: string | URL, + specifier: string | URL, + callback: ResolveCallback, + ): void; + /** + * @overload + * @param {string | URL} parent context path or a `file:` URL + * @param {string | URL} specifier request string or a `file:` URL + * @param {ResolveContext} resolveContext resolve context + * @param {ResolveCallback} callback callback function + * @returns {void} + */ + resolve( + parent: string | URL, + specifier: string | URL, + resolveContext: ResolveContext, + callback: ResolveCallback, + ): void; + /** + * @overload + * @param {Context} context context information object + * @param {string | URL} parent context path or a `file:` URL + * @param {string | URL} specifier request string or a `file:` URL + * @param {ResolveCallback} callback callback function + * @returns {void} + */ + resolve( + context: Context, + parent: string | URL, + specifier: string | URL, + callback: ResolveCallback, + ): void; + /** + * @overload + * @param {Context} context context information object + * @param {string | URL} parent context path or a `file:` URL + * @param {string | URL} specifier request string or a `file:` URL + * @param {ResolveContext} resolveContext resolve context + * @param {ResolveCallback} callback callback function + * @returns {void} + */ + resolve( + context: Context, + parent: string | URL, + specifier: string | URL, + resolveContext: ResolveContext, + callback: ResolveCallback, + ): void; + /** + * @param {ResolveStepHook} hook hook + * @param {ResolveRequest} request request + * @param {null | string} message string + * @param {ResolveContext} resolveContext resolver context + * @param {(err?: null | Error, result?: ResolveRequest) => void} callback callback + * @returns {void} + */ + doResolve( + hook: ResolveStepHook, + request: ResolveRequest, + message: null | string, + resolveContext: ResolveContext, + callback: (err?: null | Error, result?: ResolveRequest) => void, + ): void; + /** + * @param {string} identifier identifier + * @returns {ParsedIdentifier} parsed identifier + */ + parse(identifier: string): ParsedIdentifier; + /** + * @param {string} path path + * @returns {boolean} true, if the path is a module + */ + isModule(path: string): boolean; + /** + * @param {string} path path + * @returns {boolean} true, if the path is private + */ + isPrivate(path: string): boolean; + /** + * @param {string} path a path + * @returns {boolean} true, if the path is a directory path + */ + isDirectory(path: string): boolean; + /** + * @param {string} path path + * @returns {string} normalized path + */ + normalize(path: string): string; + /** + * @param {string} path path + * @param {string} request request + * @returns {string} joined path + */ + join(path: string, request: string): string; + /** + * @param {string} path path + * @returns {string} parent directory + */ + dirname(path: string): string; + /** + * @param {string} path the path to evaluate + * @param {string=} suffix an extension to remove from the result + * @returns {string} the last portion of a path + */ + basename(path: string, suffix?: string | undefined): string; +} +declare namespace Resolver { + export { + ResolveContext, + ResolveStepHook, + KnownHooks, + EnsuredHooks, + AliasOption, + CachedJoin, + CachedDirname, + CachedBasename, + JoinCacheEntry, + DirnameCacheEntry, + BasenameCacheEntry, + PathCacheFunctions, + ResolveOptions, + KnownContext, + Context, + ErrorWithDetail, + ResolveCallback, + PossibleFileSystemError, + FileSystemCallback, + PathLike, + PathOrFileDescriptor, + ObjectEncodingOptions, + EncodingOption, + StringCallback, + BufferCallback, + StringOrBufferCallback, + StatsCallback, + BigIntStatsCallback, + StatsOrBigIntStatsCallback, + ReadJsonCallback, + IStatsBase, + IStats, + IBigIntStats, + Dirent, + StatOptions, + StatSyncOptions, + ReadFile, + BufferEncodingOption, + ReadFileSync, + Readdir, + ReaddirSync, + ReadJson, + ReadJsonSync, + Readlink, + ReadlinkSync, + LStat, + LStatSync, + Stat, + StatSync, + RealPath, + RealPathSync, + FileSystem, + SyncFileSystem, + ParsedIdentifier, + JsonPrimitive, + JsonArray, + JsonValue, + JsonObject, + TsconfigPathsMap, + TsconfigPathsData, + BaseResolveRequest, + ResolveRequest, + WriteOnlySet, + ResolveContextYield, + }; +} +/** @typedef {import("./ResolverFactory").ResolveOptions} ResolveOptions */ +/** + * @typedef {object} KnownContext + * @property {string[]=} environments environments + * @property {string=} packageId package id of the importing file in the package map, propagated from a previous result to disambiguate package entries that share a location (`@experimental`, see the `packageMap` option) + */ +/** @typedef {KnownContext & Record} Context */ +/** @typedef {Error & { details?: string }} ErrorWithDetail */ +/** @typedef {(err: ErrorWithDetail | null, res?: string | false, req?: ResolveRequest) => void} ResolveCallback */ +/** + * @typedef {object} PossibleFileSystemError + * @property {string=} code code + * @property {number=} errno number + * @property {string=} path path + * @property {string=} syscall syscall + */ +/** + * @template T + * @callback FileSystemCallback + * @param {PossibleFileSystemError & Error | null} err + * @param {T=} result + */ +/** + * @typedef {string | Buffer | URL} PathLike + */ +/** + * @typedef {PathLike | number} PathOrFileDescriptor + */ +/** + * @typedef {object} ObjectEncodingOptions + * @property {BufferEncoding | null | undefined=} encoding encoding + */ +/** + * @typedef {ObjectEncodingOptions | BufferEncoding | undefined | null} EncodingOption + */ +/** @typedef {(err: NodeJS.ErrnoException | null, result?: string) => void} StringCallback */ +/** @typedef {(err: NodeJS.ErrnoException | null, result?: Buffer) => void} BufferCallback */ +/** @typedef {(err: NodeJS.ErrnoException | null, result?: (string | Buffer)) => void} StringOrBufferCallback */ +/** @typedef {(err: NodeJS.ErrnoException | null, result?: IStats) => void} StatsCallback */ +/** @typedef {(err: NodeJS.ErrnoException | null, result?: IBigIntStats) => void} BigIntStatsCallback */ +/** @typedef {(err: NodeJS.ErrnoException | null, result?: (IStats | IBigIntStats)) => void} StatsOrBigIntStatsCallback */ +/** @typedef {(err: NodeJS.ErrnoException | Error | null, result?: JsonObject) => void} ReadJsonCallback */ +/** + * @template T + * @typedef {object} IStatsBase + * @property {() => boolean} isFile is file + * @property {() => boolean} isDirectory is directory + * @property {() => boolean} isBlockDevice is block device + * @property {() => boolean} isCharacterDevice is character device + * @property {() => boolean} isSymbolicLink is symbolic link + * @property {() => boolean} isFIFO is FIFO + * @property {() => boolean} isSocket is socket + * @property {T} dev dev + * @property {T} ino ino + * @property {T} mode mode + * @property {T} nlink nlink + * @property {T} uid uid + * @property {T} gid gid + * @property {T} rdev rdev + * @property {T} size size + * @property {T} blksize blksize + * @property {T} blocks blocks + * @property {T} atimeMs atime ms + * @property {T} mtimeMs mtime ms + * @property {T} ctimeMs ctime ms + * @property {T} birthtimeMs birthtime ms + * @property {Date} atime atime + * @property {Date} mtime mtime + * @property {Date} ctime ctime + * @property {Date} birthtime birthtime + */ +/** + * @typedef {IStatsBase} IStats + */ +/** + * @typedef {IStatsBase & { atimeNs: bigint, mtimeNs: bigint, ctimeNs: bigint, birthtimeNs: bigint }} IBigIntStats + */ +/** + * @template {string | Buffer} [T=string] + * @typedef {object} Dirent + * @property {() => boolean} isFile true when is file, otherwise false + * @property {() => boolean} isDirectory true when is directory, otherwise false + * @property {() => boolean} isBlockDevice true when is block device, otherwise false + * @property {() => boolean} isCharacterDevice true when is character device, otherwise false + * @property {() => boolean} isSymbolicLink true when is symbolic link, otherwise false + * @property {() => boolean} isFIFO true when is FIFO, otherwise false + * @property {() => boolean} isSocket true when is socket, otherwise false + * @property {T} name name + * @property {string} parentPath path + * @property {string=} path path + */ +/** + * @typedef {object} StatOptions + * @property {(boolean | undefined)=} bigint need bigint values + */ +/** + * @typedef {object} StatSyncOptions + * @property {(boolean | undefined)=} bigint need bigint values + * @property {(boolean | undefined)=} throwIfNoEntry throw if no entry + */ +/** + * @typedef {{ + * (path: PathOrFileDescriptor, options: ({ encoding?: null | undefined, flag?: string | undefined } & import("events").Abortable) | undefined | null, callback: BufferCallback): void, + * (path: PathOrFileDescriptor, options: ({ encoding: BufferEncoding, flag?: string | undefined } & import("events").Abortable) | BufferEncoding, callback: StringCallback): void, + * (path: PathOrFileDescriptor, options: (ObjectEncodingOptions & { flag?: string | undefined } & import("events").Abortable) | BufferEncoding | undefined | null, callback: StringOrBufferCallback): void, + * (path: PathOrFileDescriptor, callback: BufferCallback): void, + * }} ReadFile + */ +/** + * @typedef {"buffer" | { encoding: "buffer" }} BufferEncodingOption + */ +/** + * @typedef {{ + * (path: PathOrFileDescriptor, options?: { encoding?: null | undefined, flag?: string | undefined } | null): Buffer, + * (path: PathOrFileDescriptor, options: { encoding: BufferEncoding, flag?: string | undefined } | BufferEncoding): string, + * (path: PathOrFileDescriptor, options: ObjectEncodingOptions & { flag?: string | undefined }): string | Buffer, + * }} ReadFileSync + */ +/** + * @typedef {{ + * (path: PathLike, options: { encoding: BufferEncoding | null, withFileTypes?: false | undefined, recursive?: boolean | undefined } | BufferEncoding | undefined | null, callback: (err: NodeJS.ErrnoException | null, files?: string[]) => void): void, + * (path: PathLike, options: { encoding: "buffer", withFileTypes?: false | undefined, recursive?: boolean | undefined } | "buffer", callback: (err: NodeJS.ErrnoException | null, files?: Buffer[]) => void): void, + * (path: PathLike, options: (ObjectEncodingOptions & { withFileTypes?: false | undefined, recursive?: boolean | undefined }) | BufferEncoding | undefined | null, callback: (err: NodeJS.ErrnoException | null, files?: string[] | Buffer[]) => void): void, + * (path: PathLike, callback: (err: NodeJS.ErrnoException | null, files?: string[]) => void): void, + * (path: PathLike, options: ObjectEncodingOptions & { withFileTypes: true, recursive?: boolean | undefined }, callback: (err: NodeJS.ErrnoException | null, files?: Dirent[]) => void): void, + * (path: PathLike, options: { encoding: "buffer", withFileTypes: true, recursive?: boolean | undefined }, callback: (err: NodeJS.ErrnoException | null, files: Dirent[]) => void): void, + * }} Readdir + */ +/** + * @typedef {{ + * (path: PathLike, options?: { encoding: BufferEncoding | null, withFileTypes?: false | undefined, recursive?: boolean | undefined } | BufferEncoding | null): string[], + * (path: PathLike, options: { encoding: "buffer", withFileTypes?: false | undefined, recursive?: boolean | undefined } | "buffer"): Buffer[], + * (path: PathLike, options?: (ObjectEncodingOptions & { withFileTypes?: false | undefined, recursive?: boolean | undefined }) | BufferEncoding | null): string[] | Buffer[], + * (path: PathLike, options: ObjectEncodingOptions & { withFileTypes: true, recursive?: boolean | undefined }): Dirent[], + * (path: PathLike, options: { encoding: "buffer", withFileTypes: true, recursive?: boolean | undefined }): Dirent[], + * }} ReaddirSync + */ +/** + * @typedef {(pathOrFileDescription: PathOrFileDescriptor, callback: ReadJsonCallback) => void} ReadJson + */ +/** + * @typedef {(pathOrFileDescription: PathOrFileDescriptor) => JsonObject} ReadJsonSync + */ +/** + * @typedef {{ + * (path: PathLike, options: EncodingOption, callback: StringCallback): void, + * (path: PathLike, options: BufferEncodingOption, callback: BufferCallback): void, + * (path: PathLike, options: EncodingOption, callback: StringOrBufferCallback): void, + * (path: PathLike, callback: StringCallback): void, + * }} Readlink + */ +/** + * @typedef {{ + * (path: PathLike, options?: EncodingOption): string, + * (path: PathLike, options: BufferEncodingOption): Buffer, + * (path: PathLike, options?: EncodingOption): string | Buffer, + * }} ReadlinkSync + */ +/** + * @typedef {{ + * (path: PathLike, callback: StatsCallback): void, + * (path: PathLike, options: (StatOptions & { bigint?: false | undefined }) | undefined, callback: StatsCallback): void, + * (path: PathLike, options: StatOptions & { bigint: true }, callback: BigIntStatsCallback): void, + * (path: PathLike, options: StatOptions | undefined, callback: StatsOrBigIntStatsCallback): void, + * }} LStat + */ +/** + * @typedef {{ + * (path: PathLike, options?: undefined): IStats, + * (path: PathLike, options?: StatSyncOptions & { bigint?: false | undefined, throwIfNoEntry: false }): IStats | undefined, + * (path: PathLike, options: StatSyncOptions & { bigint: true, throwIfNoEntry: false }): IBigIntStats | undefined, + * (path: PathLike, options?: StatSyncOptions & { bigint?: false | undefined, throwIfNoEntry?: true | undefined }): IStats, + * (path: PathLike, options: StatSyncOptions & { bigint: true, throwIfNoEntry?: true | undefined }): IBigIntStats, + * (path: PathLike, options: StatSyncOptions & { bigint: boolean, throwIfNoEntry?: undefined }): IStats | IBigIntStats, + * (path: PathLike, options?: StatSyncOptions): IStats | IBigIntStats | undefined, + * }} LStatSync + */ +/** + * @typedef {{ + * (path: PathLike, callback: StatsCallback): void, + * (path: PathLike, options: (StatOptions & { bigint?: false | undefined }) | undefined, callback: StatsCallback): void, + * (path: PathLike, options: StatOptions & { bigint: true }, callback: BigIntStatsCallback): void, + * (path: PathLike, options: StatOptions | undefined, callback: StatsOrBigIntStatsCallback): void, + * }} Stat + */ +/** + * @typedef {{ + * (path: PathLike, options?: undefined): IStats, + * (path: PathLike, options?: StatSyncOptions & { bigint?: false | undefined, throwIfNoEntry: false }): IStats | undefined, + * (path: PathLike, options: StatSyncOptions & { bigint: true, throwIfNoEntry: false }): IBigIntStats | undefined, + * (path: PathLike, options?: StatSyncOptions & { bigint?: false | undefined, throwIfNoEntry?: true | undefined }): IStats, + * (path: PathLike, options: StatSyncOptions & { bigint: true, throwIfNoEntry?: true | undefined }): IBigIntStats, + * (path: PathLike, options: StatSyncOptions & { bigint: boolean, throwIfNoEntry?: undefined }): IStats | IBigIntStats, + * (path: PathLike, options?: StatSyncOptions): IStats | IBigIntStats | undefined, + * }} StatSync + */ +/** + * @typedef {{ + * (path: PathLike, options: EncodingOption, callback: StringCallback): void, + * (path: PathLike, options: BufferEncodingOption, callback: BufferCallback): void, + * (path: PathLike, options: EncodingOption, callback: StringOrBufferCallback): void, + * (path: PathLike, callback: StringCallback): void, + * }} RealPath + */ +/** + * @typedef {{ + * (path: PathLike, options?: EncodingOption): string, + * (path: PathLike, options: BufferEncodingOption): Buffer, + * (path: PathLike, options?: EncodingOption): string | Buffer, + * }} RealPathSync + */ +/** + * @typedef {object} FileSystem + * @property {ReadFile} readFile read file method + * @property {Readdir} readdir readdir method + * @property {ReadJson=} readJson read json method + * @property {Readlink} readlink read link method + * @property {LStat=} lstat lstat method + * @property {Stat} stat stat method + * @property {RealPath=} realpath realpath method + */ +/** + * @typedef {object} SyncFileSystem + * @property {ReadFileSync} readFileSync read file sync method + * @property {ReaddirSync} readdirSync read dir sync method + * @property {ReadJsonSync=} readJsonSync read json sync method + * @property {ReadlinkSync} readlinkSync read link sync method + * @property {LStatSync=} lstatSync lstat sync method + * @property {StatSync} statSync stat sync method + * @property {RealPathSync=} realpathSync real path sync method + */ +/** + * @typedef {object} ParsedIdentifier + * @property {string} request request + * @property {string} query query + * @property {string} fragment fragment + * @property {boolean} directory is directory + * @property {boolean} module is module + * @property {boolean} file is file + * @property {boolean} internal is internal + */ +/** @typedef {string | number | boolean | null} JsonPrimitive */ +/** @typedef {JsonValue[]} JsonArray */ +/** @typedef {JsonPrimitive | JsonObject | JsonArray} JsonValue */ +/** @typedef {{ [Key in string]?: JsonValue | undefined }} JsonObject */ +/** + * @typedef {object} TsconfigPathsMap + * @property {TsconfigPathsData} main main tsconfig paths data + * @property {string} mainContext main tsconfig base URL (absolute path) + * @property {{ [baseUrl: string]: TsconfigPathsData }} refs referenced tsconfig paths data mapped by baseUrl + * @property {{ [context: string]: TsconfigPathsData }} allContexts all contexts (main + refs) for quick lookup + * @property {string[]} contextList precomputed `Object.keys(allContexts)` — read-only; used on the `_selectPathsDataForContext` hot path + * @property {Set} fileDependencies file dependencies + */ +/** + * @typedef {object} TsconfigPathsData + * @property {import("./AliasUtils").CompiledAliasOptions} alias tsconfig file data + * @property {string[]} modules tsconfig file data + */ +/** + * @typedef {object} BaseResolveRequest + * @property {string | false} path path + * @property {Context=} context content + * @property {string=} descriptionFilePath description file path + * @property {string=} descriptionFileRoot description file root + * @property {JsonObject=} descriptionFileData description file data + * @property {TsconfigPathsMap | null | undefined=} tsconfigPathsMap tsconfig paths map + * @property {string=} relativePath relative path + * @property {boolean=} ignoreSymlinks true when need to ignore symlinks, otherwise false + * @property {boolean=} fullySpecified true when full specified, otherwise false + * @property {string=} packageId package id the request was resolved to in the package map, to be propagated to resolutions made from the resulting file (`@experimental`, see the `packageMap` option) + * @property {string=} __innerRequest inner request for internal usage + * @property {string=} __innerRequest_request inner request for internal usage + * @property {string=} __innerRequest_relativePath inner relative path for internal usage + * @property {{ blocked: boolean }=} __restrictionsMarker internal: shared marker `RestrictionsPlugin` flips when it filters out an existing target, letting `ExportsFieldPlugin` fall back instead of erroring + */ +/** @typedef {BaseResolveRequest & Partial} ResolveRequest */ +/** + * @template T + * @typedef {{ add: (item: T) => void }} WriteOnlySet + */ +/** @typedef {(request: ResolveRequest) => void} ResolveContextYield */ +/** + * Singly-linked stack entry that also exposes a Set-like API + * (`has`, `size`, iteration). Each `doResolve` call prepends a new + * `StackEntry` that points at the previous tip via `.parent`, so pushing + * is O(1) in time and memory. Recursion detection walks the linked list + * (O(n)) but the stack is typically shallow, so this is cheaper overall + * than cloning a `Set` per call. + */ +declare class StackEntry { + /** + * @param {ResolveStepHook} hook hook + * @param {ResolveRequest} request request + * @param {StackEntry=} parent previous tip + * @param {Set=} preSeeded entries pre-seeded via the legacy `Set` API + */ + constructor( + hook: ResolveStepHook, + request: ResolveRequest, + parent?: StackEntry | undefined, + preSeeded?: Set | undefined, + ); + name: string | undefined; + path: string | false; + request: string; + query: string; + fragment: string; + directory: boolean; + module: boolean; + /** @type {StackEntry | undefined} */ + parent: StackEntry | undefined; + /** + * Strings seeded by callers that still pass `stack: new Set([...])`. + * Propagated through the chain so deeper `doResolve` calls still see + * them during recursion checks. `undefined` in the common case so + * there is no extra work on the hot path. + * @type {Set | undefined} + */ + preSeeded: Set | undefined; + /** + * Walk the linked list looking for an entry with the same request shape. + * Set-compatible: callers that used `stack.has(entry)` keep working. + * + * NOTE: kept monomorphic on purpose. An earlier draft accepted a string + * query too (so pre-5.21 plugins keeping their own `Set` of + * seen entries could probe the live stack with the formatted form), + * but adding the second shape regressed `doResolve`'s heap profile by + * ~1 MiB / 200 resolves on stack-churn — V8 keeps a polymorphic + * call-site state for `parent.has(stackEntry)` once `has` has two + * argument shapes. Plugins that need string membership can reach for + * `[...stack].find(e => e.includes(formattedString))` via the + * `String`-method proxies on `StackEntry` instead. + * @param {StackEntry} query entry to look for + * @returns {boolean} whether the stack already contains an equivalent entry + */ + has(query: StackEntry): boolean; + /** + * Number of entries on the stack (oldest-to-newest length). + * @returns {number} size + */ + get size(): number; + /** + * Human-readable form used in recursion error messages, logs, and the + * iterator above. Not memoized: caching would require an extra slot on + * every `StackEntry`, which costs heap even on resolves that never look + * at the formatted form. + * @returns {string} formatted entry + */ + toString(): string; + /** + * Iterate entries from oldest (root) to newest (tip), matching how a + * `Set` that was populated in insertion order would iterate. Pre-seeded + * legacy `Set` entries come first so error-message output stays + * ordered oldest-to-newest. + * + * Yields each entry as its formatted `toString()` form. Plugins written + * against the pre-5.21 `Set` shape — e.g. + * `[...resolveContext.stack].find(a => a.includes("module:"))` — keep + * working unchanged because each yielded value is a plain string with + * all of `String.prototype` available natively. Resolves that never + * iterate the stack pay nothing; iteration costs one `toString()` + * allocation per stack frame. + * @returns {IterableIterator} iterator + */ + [Symbol.iterator](): IterableIterator; +} +/** + * Resolve context + */ +type ResolveContext = { + /** + * directories that was found on file system + */ + contextDependencies?: WriteOnlySet | undefined; + /** + * files that was found on file system + */ + fileDependencies?: WriteOnlySet | undefined; + /** + * dependencies that was not found on file system + */ + missingDependencies?: WriteOnlySet | undefined; + /** + * tip of the resolver call stack (a singly-linked list with Set-like API). For instance, `resolve → parsedResolve → describedResolve`. Accepts a legacy `Set` for back-compat with older callers; it is normalized internally without a hot-path branch. + */ + stack?: (StackEntry | Set) | undefined; + /** + * log function + */ + log?: ((str: string) => void) | undefined; + /** + * yield result, if provided plugins can return several results + */ + yield?: ResolveContextYield | undefined; +}; +type ResolveStepHook = AsyncSeriesBailHook< + [ResolveRequest, ResolveContext], + ResolveRequest | null +>; +type KnownHooks = { + /** + * resolve step hook + */ + resolveStep: SyncHook<[ResolveStepHook, ResolveRequest], void>; + /** + * no resolve hook + */ + noResolve: SyncHook<[ResolveRequest, Error]>; + /** + * resolve hook + */ + resolve: ResolveStepHook; + /** + * result hook + */ + result: AsyncSeriesHook<[ResolveRequest, ResolveContext]>; +}; +type EnsuredHooks = { + [key: string]: ResolveStepHook; +}; +type AliasOption = import("./AliasUtils").AliasOption; +type CachedJoin = import("./util/path").CachedJoin; +type CachedDirname = import("./util/path").CachedDirname; +type CachedBasename = import("./util/path").CachedBasename; +type JoinCacheEntry = { + /** + * cached join function + */ + fn: CachedJoin["fn"]; + /** + * the underlying cache map + */ + cache: CachedJoin["cache"]; +}; +type DirnameCacheEntry = { + /** + * cached dirname function + */ + fn: CachedDirname["fn"]; + /** + * the underlying cache map + */ + cache: CachedDirname["cache"]; +}; +type BasenameCacheEntry = { + /** + * cached dirname function + */ + fn: CachedBasename["fn"]; + /** + * the underlying cache map + */ + cache: CachedBasename["cache"]; +}; +type PathCacheFunctions = { + /** + * cached join + */ + join: JoinCacheEntry; + /** + * cached dirname + */ + dirname: DirnameCacheEntry; + /** + * cached basename + */ + basename: BasenameCacheEntry; +}; +type ResolveOptions = import("./ResolverFactory").ResolveOptions; +type KnownContext = { + /** + * environments + */ + environments?: string[] | undefined; + /** + * package id of the importing file in the package map, propagated from a previous result to disambiguate package entries that share a location (`@experimental`, see the `packageMap` option) + */ + packageId?: string | undefined; +}; +type Context = KnownContext & Record; +type ErrorWithDetail = Error & { + details?: string; +}; +type ResolveCallback = ( + err: ErrorWithDetail | null, + res?: string | false, + req?: ResolveRequest, +) => void; +type PossibleFileSystemError = { + /** + * code + */ + code?: string | undefined; + /** + * number + */ + errno?: number | undefined; + /** + * path + */ + path?: string | undefined; + /** + * syscall + */ + syscall?: string | undefined; +}; +type FileSystemCallback = ( + err: (PossibleFileSystemError & Error) | null, + result?: T | undefined, +) => any; +type PathLike = string | Buffer | URL; +type PathOrFileDescriptor = PathLike | number; +type ObjectEncodingOptions = { + /** + * encoding + */ + encoding?: (BufferEncoding | null | undefined) | undefined; +}; +type EncodingOption = ObjectEncodingOptions | BufferEncoding | undefined | null; +type StringCallback = ( + err: NodeJS.ErrnoException | null, + result?: string, +) => void; +type BufferCallback = ( + err: NodeJS.ErrnoException | null, + result?: Buffer, +) => void; +type StringOrBufferCallback = ( + err: NodeJS.ErrnoException | null, + result?: string | Buffer, +) => void; +type StatsCallback = ( + err: NodeJS.ErrnoException | null, + result?: IStats, +) => void; +type BigIntStatsCallback = ( + err: NodeJS.ErrnoException | null, + result?: IBigIntStats, +) => void; +type StatsOrBigIntStatsCallback = ( + err: NodeJS.ErrnoException | null, + result?: IStats | IBigIntStats, +) => void; +type ReadJsonCallback = ( + err: NodeJS.ErrnoException | Error | null, + result?: JsonObject, +) => void; +type IStatsBase = { + /** + * is file + */ + isFile: () => boolean; + /** + * is directory + */ + isDirectory: () => boolean; + /** + * is block device + */ + isBlockDevice: () => boolean; + /** + * is character device + */ + isCharacterDevice: () => boolean; + /** + * is symbolic link + */ + isSymbolicLink: () => boolean; + /** + * is FIFO + */ + isFIFO: () => boolean; + /** + * is socket + */ + isSocket: () => boolean; + /** + * dev + */ + dev: T; + /** + * ino + */ + ino: T; + /** + * mode + */ + mode: T; + /** + * nlink + */ + nlink: T; + /** + * uid + */ + uid: T; + /** + * gid + */ + gid: T; + /** + * rdev + */ + rdev: T; + /** + * size + */ + size: T; + /** + * blksize + */ + blksize: T; + /** + * blocks + */ + blocks: T; + /** + * atime ms + */ + atimeMs: T; + /** + * mtime ms + */ + mtimeMs: T; + /** + * ctime ms + */ + ctimeMs: T; + /** + * birthtime ms + */ + birthtimeMs: T; + /** + * atime + */ + atime: Date; + /** + * mtime + */ + mtime: Date; + /** + * ctime + */ + ctime: Date; + /** + * birthtime + */ + birthtime: Date; +}; +type IStats = IStatsBase; +type IBigIntStats = IStatsBase & { + atimeNs: bigint; + mtimeNs: bigint; + ctimeNs: bigint; + birthtimeNs: bigint; +}; +type Dirent = { + /** + * true when is file, otherwise false + */ + isFile: () => boolean; + /** + * true when is directory, otherwise false + */ + isDirectory: () => boolean; + /** + * true when is block device, otherwise false + */ + isBlockDevice: () => boolean; + /** + * true when is character device, otherwise false + */ + isCharacterDevice: () => boolean; + /** + * true when is symbolic link, otherwise false + */ + isSymbolicLink: () => boolean; + /** + * true when is FIFO, otherwise false + */ + isFIFO: () => boolean; + /** + * true when is socket, otherwise false + */ + isSocket: () => boolean; + /** + * name + */ + name: T; + /** + * path + */ + parentPath: string; + /** + * path + */ + path?: string | undefined; +}; +type StatOptions = { + /** + * need bigint values + */ + bigint?: (boolean | undefined) | undefined; +}; +type StatSyncOptions = { + /** + * need bigint values + */ + bigint?: (boolean | undefined) | undefined; + /** + * throw if no entry + */ + throwIfNoEntry?: (boolean | undefined) | undefined; +}; +type ReadFile = { + ( + path: PathOrFileDescriptor, + options: + | ({ + encoding?: null | undefined; + flag?: string | undefined; + } & import("events").Abortable) + | undefined + | null, + callback: BufferCallback, + ): void; + ( + path: PathOrFileDescriptor, + options: + | ({ + encoding: BufferEncoding; + flag?: string | undefined; + } & import("events").Abortable) + | BufferEncoding, + callback: StringCallback, + ): void; + ( + path: PathOrFileDescriptor, + options: + | (ObjectEncodingOptions & { + flag?: string | undefined; + } & import("events").Abortable) + | BufferEncoding + | undefined + | null, + callback: StringOrBufferCallback, + ): void; + (path: PathOrFileDescriptor, callback: BufferCallback): void; +}; +type BufferEncodingOption = + | "buffer" + | { + encoding: "buffer"; + }; +type ReadFileSync = { + ( + path: PathOrFileDescriptor, + options?: { + encoding?: null | undefined; + flag?: string | undefined; + } | null, + ): Buffer; + ( + path: PathOrFileDescriptor, + options: + | { + encoding: BufferEncoding; + flag?: string | undefined; + } + | BufferEncoding, + ): string; + ( + path: PathOrFileDescriptor, + options: ObjectEncodingOptions & { + flag?: string | undefined; + }, + ): string | Buffer; +}; +type Readdir = { + ( + path: PathLike, + options: + | { + encoding: BufferEncoding | null; + withFileTypes?: false | undefined; + recursive?: boolean | undefined; + } + | BufferEncoding + | undefined + | null, + callback: (err: NodeJS.ErrnoException | null, files?: string[]) => void, + ): void; + ( + path: PathLike, + options: + | { + encoding: "buffer"; + withFileTypes?: false | undefined; + recursive?: boolean | undefined; + } + | "buffer", + callback: (err: NodeJS.ErrnoException | null, files?: Buffer[]) => void, + ): void; + ( + path: PathLike, + options: + | (ObjectEncodingOptions & { + withFileTypes?: false | undefined; + recursive?: boolean | undefined; + }) + | BufferEncoding + | undefined + | null, + callback: ( + err: NodeJS.ErrnoException | null, + files?: string[] | Buffer[], + ) => void, + ): void; + ( + path: PathLike, + callback: (err: NodeJS.ErrnoException | null, files?: string[]) => void, + ): void; + ( + path: PathLike, + options: ObjectEncodingOptions & { + withFileTypes: true; + recursive?: boolean | undefined; + }, + callback: ( + err: NodeJS.ErrnoException | null, + files?: Dirent[], + ) => void, + ): void; + ( + path: PathLike, + options: { + encoding: "buffer"; + withFileTypes: true; + recursive?: boolean | undefined; + }, + callback: ( + err: NodeJS.ErrnoException | null, + files: Dirent[], + ) => void, + ): void; +}; +type ReaddirSync = { + ( + path: PathLike, + options?: + | { + encoding: BufferEncoding | null; + withFileTypes?: false | undefined; + recursive?: boolean | undefined; + } + | BufferEncoding + | null, + ): string[]; + ( + path: PathLike, + options: + | { + encoding: "buffer"; + withFileTypes?: false | undefined; + recursive?: boolean | undefined; + } + | "buffer", + ): Buffer[]; + ( + path: PathLike, + options?: + | (ObjectEncodingOptions & { + withFileTypes?: false | undefined; + recursive?: boolean | undefined; + }) + | BufferEncoding + | null, + ): string[] | Buffer[]; + ( + path: PathLike, + options: ObjectEncodingOptions & { + withFileTypes: true; + recursive?: boolean | undefined; + }, + ): Dirent[]; + ( + path: PathLike, + options: { + encoding: "buffer"; + withFileTypes: true; + recursive?: boolean | undefined; + }, + ): Dirent[]; +}; +type ReadJson = ( + pathOrFileDescription: PathOrFileDescriptor, + callback: ReadJsonCallback, +) => void; +type ReadJsonSync = (pathOrFileDescription: PathOrFileDescriptor) => JsonObject; +type Readlink = { + (path: PathLike, options: EncodingOption, callback: StringCallback): void; + ( + path: PathLike, + options: BufferEncodingOption, + callback: BufferCallback, + ): void; + ( + path: PathLike, + options: EncodingOption, + callback: StringOrBufferCallback, + ): void; + (path: PathLike, callback: StringCallback): void; +}; +type ReadlinkSync = { + (path: PathLike, options?: EncodingOption): string; + (path: PathLike, options: BufferEncodingOption): Buffer; + (path: PathLike, options?: EncodingOption): string | Buffer; +}; +type LStat = { + (path: PathLike, callback: StatsCallback): void; + ( + path: PathLike, + options: + | (StatOptions & { + bigint?: false | undefined; + }) + | undefined, + callback: StatsCallback, + ): void; + ( + path: PathLike, + options: StatOptions & { + bigint: true; + }, + callback: BigIntStatsCallback, + ): void; + ( + path: PathLike, + options: StatOptions | undefined, + callback: StatsOrBigIntStatsCallback, + ): void; +}; +type LStatSync = { + (path: PathLike, options?: undefined): IStats; + ( + path: PathLike, + options?: StatSyncOptions & { + bigint?: false | undefined; + throwIfNoEntry: false; + }, + ): IStats | undefined; + ( + path: PathLike, + options: StatSyncOptions & { + bigint: true; + throwIfNoEntry: false; + }, + ): IBigIntStats | undefined; + ( + path: PathLike, + options?: StatSyncOptions & { + bigint?: false | undefined; + throwIfNoEntry?: true | undefined; + }, + ): IStats; + ( + path: PathLike, + options: StatSyncOptions & { + bigint: true; + throwIfNoEntry?: true | undefined; + }, + ): IBigIntStats; + ( + path: PathLike, + options: StatSyncOptions & { + bigint: boolean; + throwIfNoEntry?: undefined; + }, + ): IStats | IBigIntStats; + ( + path: PathLike, + options?: StatSyncOptions, + ): IStats | IBigIntStats | undefined; +}; +type Stat = { + (path: PathLike, callback: StatsCallback): void; + ( + path: PathLike, + options: + | (StatOptions & { + bigint?: false | undefined; + }) + | undefined, + callback: StatsCallback, + ): void; + ( + path: PathLike, + options: StatOptions & { + bigint: true; + }, + callback: BigIntStatsCallback, + ): void; + ( + path: PathLike, + options: StatOptions | undefined, + callback: StatsOrBigIntStatsCallback, + ): void; +}; +type StatSync = { + (path: PathLike, options?: undefined): IStats; + ( + path: PathLike, + options?: StatSyncOptions & { + bigint?: false | undefined; + throwIfNoEntry: false; + }, + ): IStats | undefined; + ( + path: PathLike, + options: StatSyncOptions & { + bigint: true; + throwIfNoEntry: false; + }, + ): IBigIntStats | undefined; + ( + path: PathLike, + options?: StatSyncOptions & { + bigint?: false | undefined; + throwIfNoEntry?: true | undefined; + }, + ): IStats; + ( + path: PathLike, + options: StatSyncOptions & { + bigint: true; + throwIfNoEntry?: true | undefined; + }, + ): IBigIntStats; + ( + path: PathLike, + options: StatSyncOptions & { + bigint: boolean; + throwIfNoEntry?: undefined; + }, + ): IStats | IBigIntStats; + ( + path: PathLike, + options?: StatSyncOptions, + ): IStats | IBigIntStats | undefined; +}; +type RealPath = { + (path: PathLike, options: EncodingOption, callback: StringCallback): void; + ( + path: PathLike, + options: BufferEncodingOption, + callback: BufferCallback, + ): void; + ( + path: PathLike, + options: EncodingOption, + callback: StringOrBufferCallback, + ): void; + (path: PathLike, callback: StringCallback): void; +}; +type RealPathSync = { + (path: PathLike, options?: EncodingOption): string; + (path: PathLike, options: BufferEncodingOption): Buffer; + (path: PathLike, options?: EncodingOption): string | Buffer; +}; +type FileSystem = { + /** + * read file method + */ + readFile: ReadFile; + /** + * readdir method + */ + readdir: Readdir; + /** + * read json method + */ + readJson?: ReadJson | undefined; + /** + * read link method + */ + readlink: Readlink; + /** + * lstat method + */ + lstat?: LStat | undefined; + /** + * stat method + */ + stat: Stat; + /** + * realpath method + */ + realpath?: RealPath | undefined; +}; +type SyncFileSystem = { + /** + * read file sync method + */ + readFileSync: ReadFileSync; + /** + * read dir sync method + */ + readdirSync: ReaddirSync; + /** + * read json sync method + */ + readJsonSync?: ReadJsonSync | undefined; + /** + * read link sync method + */ + readlinkSync: ReadlinkSync; + /** + * lstat sync method + */ + lstatSync?: LStatSync | undefined; + /** + * stat sync method + */ + statSync: StatSync; + /** + * real path sync method + */ + realpathSync?: RealPathSync | undefined; +}; +type ParsedIdentifier = { + /** + * request + */ + request: string; + /** + * query + */ + query: string; + /** + * fragment + */ + fragment: string; + /** + * is directory + */ + directory: boolean; + /** + * is module + */ + module: boolean; + /** + * is file + */ + file: boolean; + /** + * is internal + */ + internal: boolean; +}; +type JsonPrimitive = string | number | boolean | null; +type JsonArray = JsonValue[]; +type JsonValue = JsonPrimitive | JsonObject | JsonArray; +type JsonObject = { [Key in string]?: JsonValue | undefined }; +type TsconfigPathsMap = { + /** + * main tsconfig paths data + */ + main: TsconfigPathsData; + /** + * main tsconfig base URL (absolute path) + */ + mainContext: string; + /** + * referenced tsconfig paths data mapped by baseUrl + */ + refs: { + [baseUrl: string]: TsconfigPathsData; + }; + /** + * all contexts (main + refs) for quick lookup + */ + allContexts: { + [context: string]: TsconfigPathsData; + }; + /** + * precomputed `Object.keys(allContexts)` — read-only; used on the `_selectPathsDataForContext` hot path + */ + contextList: string[]; + /** + * file dependencies + */ + fileDependencies: Set; +}; +type TsconfigPathsData = { + /** + * tsconfig file data + */ + alias: import("./AliasUtils").CompiledAliasOptions; + /** + * tsconfig file data + */ + modules: string[]; +}; +type BaseResolveRequest = { + /** + * path + */ + path: string | false; + /** + * content + */ + context?: Context | undefined; + /** + * description file path + */ + descriptionFilePath?: string | undefined; + /** + * description file root + */ + descriptionFileRoot?: string | undefined; + /** + * description file data + */ + descriptionFileData?: JsonObject | undefined; + /** + * tsconfig paths map + */ + tsconfigPathsMap?: (TsconfigPathsMap | null | undefined) | undefined; + /** + * relative path + */ + relativePath?: string | undefined; + /** + * true when need to ignore symlinks, otherwise false + */ + ignoreSymlinks?: boolean | undefined; + /** + * true when full specified, otherwise false + */ + fullySpecified?: boolean | undefined; + /** + * package id the request was resolved to in the package map, to be propagated to resolutions made from the resulting file (`@experimental`, see the `packageMap` option) + */ + packageId?: string | undefined; + /** + * inner request for internal usage + */ + __innerRequest?: string | undefined; + /** + * inner request for internal usage + */ + __innerRequest_request?: string | undefined; + /** + * inner relative path for internal usage + */ + __innerRequest_relativePath?: string | undefined; + /** + * internal: shared marker `RestrictionsPlugin` flips when it filters out an existing target, letting `ExportsFieldPlugin` fall back instead of erroring + */ + __restrictionsMarker?: + | { + blocked: boolean; + } + | undefined; +}; +type ResolveRequest = BaseResolveRequest & Partial; +type WriteOnlySet = { + add: (item: T) => void; +}; +type ResolveContextYield = (request: ResolveRequest) => void; +import { AsyncSeriesBailHook } from "tapable"; +import { SyncHook } from "tapable"; +import { AsyncSeriesHook } from "tapable"; diff --git a/dg-ui/node_modules/enhanced-resolve/types/ResolverFactory.d.ts b/dg-ui/node_modules/enhanced-resolve/types/ResolverFactory.d.ts new file mode 100644 index 0000000..bad1977 --- /dev/null +++ b/dg-ui/node_modules/enhanced-resolve/types/ResolverFactory.d.ts @@ -0,0 +1,340 @@ +export function createResolver(options: UserResolveOptions): Resolver; +export type AliasOptionEntry = import("./AliasPlugin").AliasOption; +export type ExtensionAliasOption = + import("./ExtensionAliasPlugin").ExtensionAliasOption; +export type PackageMapOptions = import("./PackageMapPlugin").PackageMapOptions; +export type PackageMapPackages = import("./util/packageMap").PackageMapPackages; +export type PnpApi = import("./PnpPlugin").PnpApiImpl; +export type EnsuredHooks = import("./Resolver").EnsuredHooks; +export type FileSystem = import("./Resolver").FileSystem; +export type KnownHooks = import("./Resolver").KnownHooks; +export type ResolveRequest = import("./Resolver").ResolveRequest; +export type SyncFileSystem = import("./Resolver").SyncFileSystem; +export type Cache = import("./UnsafeCachePlugin").Cache; +export type AliasOptionNewRequest = string | string[] | false; +export type AliasOptions = { + [k: string]: AliasOptionNewRequest; +}; +export type UserAliasOptionNewRequest = string | URL | (string | URL)[] | false; +export type UserAliasOptions = { + [k: string]: UserAliasOptionNewRequest; +}; +export type UserAliasOptionEntry = { + alias: UserAliasOptionNewRequest; + name: string; + onlyModule?: boolean; +}; +export type ExtensionAliasOptions = { + [k: string]: string | string[]; +}; +export type Falsy = false | 0 | "" | null | undefined; +export type Plugin = + | { + apply: (resolver: Resolver) => void; + } + | ((this: Resolver, resolver: Resolver) => void) + | Falsy; +export type TsconfigOptions = { + /** + * A relative path to the tsconfig file based on cwd, or an absolute path of tsconfig file + */ + configFile?: string | undefined; + /** + * References to other tsconfig files. 'auto' inherits from TypeScript config, or an array of relative/absolute paths + */ + references?: (string[] | "auto") | undefined; + /** + * Override baseUrl from tsconfig.json. If provided, this value will be used instead of the baseUrl in the tsconfig file + */ + baseUrl?: string | undefined; +}; +export type UserTsconfigOptions = { + /** + * A path, or `file:` URL, pointing at the tsconfig file + */ + configFile?: (string | URL) | undefined; + /** + * References to other tsconfig files. 'auto' inherits from TypeScript config, or an array of relative/absolute paths or `file:` URLs + */ + references?: ((string | URL)[] | "auto") | undefined; + /** + * Override baseUrl from tsconfig.json with a path or `file:` URL + */ + baseUrl?: (string | URL) | undefined; +}; +/** + * A Node.js package map (https://nodejs.org/api/packages.html#package-maps), + * either as the path of the configuration file or as its already-parsed + * contents. + */ +export type UserPackageMapOptions = { + /** + * A path, or `file:` `URL` instance, pointing at the package map file. Required together with `packages`, whose relative `url` values are resolved against it + */ + configFile?: (string | URL) | undefined; + /** + * An already-parsed `packages` object, used instead of reading `configFile` from disk + */ + packages?: PackageMapPackages | undefined; +}; +export type UserResolveOptions = { + /** + * A list of module alias configurations or an object which maps key to value + */ + alias?: (UserAliasOptions | UserAliasOptionEntry[]) | undefined; + /** + * A list of module alias configurations or an object which maps key to value, applied only after modules option + */ + fallback?: (UserAliasOptions | UserAliasOptionEntry[]) | undefined; + /** + * An object which maps extension to extension aliases + */ + extensionAlias?: ExtensionAliasOptions | undefined; + /** + * Also apply `extensionAlias` to paths resolved through the package.json `exports` field. Off by default (Node.js-aligned); when enabled, matches TypeScript's behavior for packages that ship TS sources alongside compiled JS. + */ + extensionAliasForExports?: boolean | undefined; + /** + * A list of alias fields in description files + */ + aliasFields?: (string | string[])[] | undefined; + /** + * A function which decides whether a request should be cached or not. An object is passed with at least `path` and `request` properties. + */ + cachePredicate?: ((predicate: ResolveRequest) => boolean) | undefined; + /** + * Whether or not the unsafeCache should include request context as part of the cache key. + */ + cacheWithContext?: boolean | undefined; + /** + * A list of description files to read from + */ + descriptionFiles?: string[] | undefined; + /** + * A list of exports field condition names. + */ + conditionNames?: string[] | undefined; + /** + * Enforce that a extension from extensions must be used + */ + enforceExtension?: boolean | undefined; + /** + * A list of exports fields in description files + */ + exportsFields?: (string | string[])[] | undefined; + /** + * A list of imports fields in description files + */ + importsFields?: (string | string[])[] | undefined; + /** + * A list of extensions which should be tried for files + */ + extensions?: string[] | undefined; + /** + * The file system which should be used + */ + fileSystem: FileSystem; + /** + * Use this cache object to unsafely cache the successful requests + */ + unsafeCache?: (Cache | boolean) | undefined; + /** + * Resolve symlinks to their symlinked location + */ + symlinks?: boolean | undefined; + /** + * A prepared Resolver to which the plugins are attached + */ + resolver?: Resolver | undefined; + /** + * A list of directories to resolve modules from, can be absolute path, folder name, or a `file:` URL + */ + modules?: ((string | URL)[] | string | URL) | undefined; + /** + * A list of main fields in description files + */ + mainFields?: + | ( + | string + | string[] + | { + name: string | string[]; + forceRelative: boolean; + } + )[] + | undefined; + /** + * A list of main files in directories + */ + mainFiles?: string[] | undefined; + /** + * A list of additional resolve plugins which should be applied + */ + plugins?: Plugin[] | undefined; + /** + * A Node.js package map file path (or `file:` `URL` instance), or an object with the already-parsed `packages`. When set, bare specifiers resolve through the map instead of `node_modules` (`@experimental`) + */ + packageMap?: (string | URL | UserPackageMapOptions) | undefined; + /** + * A PnP API that should be used - null is "never", undefined is "auto" + */ + pnpApi?: (PnpApi | null) | undefined; + /** + * A list of root paths, each an absolute path or a `file:` URL + */ + roots?: (string | URL)[] | undefined; + /** + * The request is already fully specified and no extensions or directories are resolved for it + */ + fullySpecified?: boolean | undefined; + /** + * Resolve to a context instead of a file + */ + resolveToContext?: boolean | undefined; + /** + * A list of resolve restrictions, each an absolute path, a `file:` URL, or a RegExp + */ + restrictions?: (string | URL | RegExp)[] | undefined; + /** + * Use only the sync constraints of the file system calls + */ + useSyncFileSystemCalls?: boolean | undefined; + /** + * Prefer to resolve module requests as relative requests before falling back to modules + */ + preferRelative?: boolean | undefined; + /** + * Prefer to resolve server-relative urls as absolute paths before falling back to resolve in roots + */ + preferAbsolute?: boolean | undefined; + /** + * TypeScript config file path (or `file:` URL) or config object with configFile and references + */ + tsconfig?: (string | URL | boolean | UserTsconfigOptions) | undefined; +}; +export type ResolveOptions = { + /** + * alias + */ + alias: AliasOptionEntry[]; + /** + * fallback + */ + fallback: AliasOptionEntry[]; + /** + * alias fields + */ + aliasFields: Set; + /** + * extension alias + */ + extensionAlias: ExtensionAliasOption[]; + /** + * apply extension alias to exports field targets + */ + extensionAliasForExports: boolean; + /** + * cache predicate + */ + cachePredicate: (predicate: ResolveRequest) => boolean; + /** + * cache with context + */ + cacheWithContext: boolean; + /** + * A list of exports field condition names. + */ + conditionNames: Set; + /** + * description files + */ + descriptionFiles: string[]; + /** + * enforce extension + */ + enforceExtension: boolean; + /** + * exports fields + */ + exportsFields: Set; + /** + * imports fields + */ + importsFields: Set; + /** + * extensions + */ + extensions: Set; + /** + * fileSystem + */ + fileSystem: FileSystem; + /** + * unsafe cache + */ + unsafeCache: Cache | false; + /** + * symlinks + */ + symlinks: boolean; + /** + * resolver + */ + resolver?: Resolver | undefined; + /** + * modules + */ + modules: (string | string[])[]; + /** + * main fields + */ + mainFields: { + name: string[]; + forceRelative: boolean; + }[]; + /** + * main files + */ + mainFiles: Set; + /** + * plugins + */ + plugins: Plugin[]; + /** + * package map + */ + packageMap: PackageMapOptions | null; + /** + * pnp API + */ + pnpApi: PnpApi | null; + /** + * roots + */ + roots: Set; + /** + * fully specified + */ + fullySpecified: boolean; + /** + * resolve to context + */ + resolveToContext: boolean; + /** + * restrictions + */ + restrictions: Set; + /** + * prefer relative + */ + preferRelative: boolean; + /** + * prefer absolute + */ + preferAbsolute: boolean; + /** + * tsconfig file path or config object + */ + tsconfig: string | boolean | TsconfigOptions; +}; +import Resolver = require("./Resolver"); diff --git a/dg-ui/node_modules/enhanced-resolve/types/RestrictionsPlugin.d.ts b/dg-ui/node_modules/enhanced-resolve/types/RestrictionsPlugin.d.ts new file mode 100644 index 0000000..ceb2fb6 --- /dev/null +++ b/dg-ui/node_modules/enhanced-resolve/types/RestrictionsPlugin.d.ts @@ -0,0 +1,52 @@ +export = RestrictionsPlugin; +declare class RestrictionsPlugin { + /** + * @param {string | ResolveStepHook} source source + * @param {Set} restrictions restrictions + */ + constructor( + source: string | ResolveStepHook, + restrictions: Set, + ); + source: string | import("./Resolver").ResolveStepHook; + restrictions: Set; + /** @type {Restriction[]} */ + _restrictions: Restriction[]; + /** + * @param {Resolver} resolver the resolver + * @returns {void} + */ + apply(resolver: Resolver): void; +} +declare namespace RestrictionsPlugin { + export { + Resolver, + ResolveStepHook, + PathRestriction, + RegExpRestriction, + Restriction, + }; +} +type Resolver = import("./Resolver"); +type ResolveStepHook = import("./Resolver").ResolveStepHook; +type PathRestriction = { + /** + * type of the restriction + */ + type: "path"; + /** + * normalized path the request has to be inside of + */ + rule: string; +}; +type RegExpRestriction = { + /** + * type of the restriction + */ + type: "regexp"; + /** + * pattern the request has to match + */ + rule: RegExp; +}; +type Restriction = PathRestriction | RegExpRestriction; diff --git a/dg-ui/node_modules/enhanced-resolve/types/ResultPlugin.d.ts b/dg-ui/node_modules/enhanced-resolve/types/ResultPlugin.d.ts new file mode 100644 index 0000000..94fe0b2 --- /dev/null +++ b/dg-ui/node_modules/enhanced-resolve/types/ResultPlugin.d.ts @@ -0,0 +1,18 @@ +export = ResultPlugin; +declare class ResultPlugin { + /** + * @param {ResolveStepHook} source source + */ + constructor(source: ResolveStepHook); + source: import("./Resolver").ResolveStepHook; + /** + * @param {Resolver} resolver the resolver + * @returns {void} + */ + apply(resolver: Resolver): void; +} +declare namespace ResultPlugin { + export { Resolver, ResolveStepHook }; +} +type Resolver = import("./Resolver"); +type ResolveStepHook = import("./Resolver").ResolveStepHook; diff --git a/dg-ui/node_modules/enhanced-resolve/types/RootsPlugin.d.ts b/dg-ui/node_modules/enhanced-resolve/types/RootsPlugin.d.ts new file mode 100644 index 0000000..72625d2 --- /dev/null +++ b/dg-ui/node_modules/enhanced-resolve/types/RootsPlugin.d.ts @@ -0,0 +1,30 @@ +export = RootsPlugin; +/** @typedef {import("./Resolver")} Resolver */ +/** @typedef {import("./Resolver").ResolveRequest} ResolveRequest */ +/** @typedef {import("./Resolver").ResolveStepHook} ResolveStepHook */ +declare class RootsPlugin { + /** + * @param {string | ResolveStepHook} source source hook + * @param {Set} roots roots + * @param {string | ResolveStepHook} target target hook + */ + constructor( + source: string | ResolveStepHook, + roots: Set, + target: string | ResolveStepHook, + ); + roots: string[]; + source: string | import("./Resolver").ResolveStepHook; + target: string | import("./Resolver").ResolveStepHook; + /** + * @param {Resolver} resolver the resolver + * @returns {void} + */ + apply(resolver: Resolver): void; +} +declare namespace RootsPlugin { + export { Resolver, ResolveRequest, ResolveStepHook }; +} +type Resolver = import("./Resolver"); +type ResolveRequest = import("./Resolver").ResolveRequest; +type ResolveStepHook = import("./Resolver").ResolveStepHook; diff --git a/dg-ui/node_modules/enhanced-resolve/types/SelfReferencePlugin.d.ts b/dg-ui/node_modules/enhanced-resolve/types/SelfReferencePlugin.d.ts new file mode 100644 index 0000000..642e7d9 --- /dev/null +++ b/dg-ui/node_modules/enhanced-resolve/types/SelfReferencePlugin.d.ts @@ -0,0 +1,31 @@ +export = SelfReferencePlugin; +declare class SelfReferencePlugin { + /** + * @param {string | ResolveStepHook} source source + * @param {string | string[]} fieldNamePath name path + * @param {string | ResolveStepHook} target target + */ + constructor( + source: string | ResolveStepHook, + fieldNamePath: string | string[], + target: string | ResolveStepHook, + ); + source: string | import("./Resolver").ResolveStepHook; + target: string | import("./Resolver").ResolveStepHook; + fieldName: string | string[]; + /** @type {WeakMap} */ + _nameCache: WeakMap; + /** + * @param {Resolver} resolver the resolver + * @returns {void} + */ + apply(resolver: Resolver): void; +} +declare namespace SelfReferencePlugin { + export { Resolver, JsonObject, ResolveRequest, ResolveStepHook }; +} +declare const NO_SELF_REF: unique symbol; +type Resolver = import("./Resolver"); +type JsonObject = import("./Resolver").JsonObject; +type ResolveRequest = import("./Resolver").ResolveRequest; +type ResolveStepHook = import("./Resolver").ResolveStepHook; diff --git a/dg-ui/node_modules/enhanced-resolve/types/SymlinkPlugin.d.ts b/dg-ui/node_modules/enhanced-resolve/types/SymlinkPlugin.d.ts new file mode 100644 index 0000000..09750b7 --- /dev/null +++ b/dg-ui/node_modules/enhanced-resolve/types/SymlinkPlugin.d.ts @@ -0,0 +1,24 @@ +export = SymlinkPlugin; +declare class SymlinkPlugin { + /** + * @param {string | ResolveStepHook} source source + * @param {string | ResolveStepHook} target target + */ + constructor( + source: string | ResolveStepHook, + target: string | ResolveStepHook, + ); + source: string | import("./Resolver").ResolveStepHook; + target: string | import("./Resolver").ResolveStepHook; + /** + * @param {Resolver} resolver the resolver + * @returns {void} + */ + apply(resolver: Resolver): void; +} +declare namespace SymlinkPlugin { + export { Resolver, ResolveRequest, ResolveStepHook }; +} +type Resolver = import("./Resolver"); +type ResolveRequest = import("./Resolver").ResolveRequest; +type ResolveStepHook = import("./Resolver").ResolveStepHook; diff --git a/dg-ui/node_modules/enhanced-resolve/types/SyncAsyncFileSystemDecorator.d.ts b/dg-ui/node_modules/enhanced-resolve/types/SyncAsyncFileSystemDecorator.d.ts new file mode 100644 index 0000000..de4eb66 --- /dev/null +++ b/dg-ui/node_modules/enhanced-resolve/types/SyncAsyncFileSystemDecorator.d.ts @@ -0,0 +1,56 @@ +export = SyncAsyncFileSystemDecorator; +/** + * @param {SyncFileSystem} fs file system implementation + * @constructor + */ +declare function SyncAsyncFileSystemDecorator(fs: SyncFileSystem): void; +declare class SyncAsyncFileSystemDecorator { + /** + * @param {SyncFileSystem} fs file system implementation + * @constructor + */ + constructor(fs: SyncFileSystem); + fs: import("./Resolver").SyncFileSystem; + lstat: import("./Resolver").LStat | undefined; + lstatSync: import("./Resolver").LStatSync | undefined; + stat: import("./Resolver").Stat; + statSync: import("./Resolver").StatSync; + readdir: import("./Resolver").Readdir; + readdirSync: import("./Resolver").ReaddirSync; + readFile: import("./Resolver").ReadFile; + readFileSync: import("./Resolver").ReadFileSync; + readlink: import("./Resolver").Readlink; + readlinkSync: import("./Resolver").ReadlinkSync; + readJson: import("./Resolver").ReadJson | undefined; + readJsonSync: import("./Resolver").ReadJsonSync | undefined; + realpath: import("./Resolver").RealPath | undefined; + realpathSync: import("./Resolver").RealPathSync | undefined; +} +declare namespace SyncAsyncFileSystemDecorator { + export { + FileSystem, + StringCallback, + SyncFileSystem, + SyncOrAsyncFunction, + ResultOfSyncOrAsyncFunction, + ObjectEncodingOptions, + PathOrFileDescriptor, + ReadFileSyncOptions, + }; +} +type FileSystem = import("./Resolver").FileSystem; +type StringCallback = import("./Resolver").StringCallback; +type SyncFileSystem = import("./Resolver").SyncFileSystem; +type SyncOrAsyncFunction = Function; +type ResultOfSyncOrAsyncFunction = any; +type ObjectEncodingOptions = import("./Resolver").ObjectEncodingOptions; +type PathOrFileDescriptor = import("./Resolver").PathOrFileDescriptor; +/** + * Every option `readFileSync` accepts, as `readFile` passes it through. + */ +type ReadFileSyncOptions = + | (ObjectEncodingOptions & { + flag?: string | undefined; + }) + | BufferEncoding + | null; diff --git a/dg-ui/node_modules/enhanced-resolve/types/TryNextPlugin.d.ts b/dg-ui/node_modules/enhanced-resolve/types/TryNextPlugin.d.ts new file mode 100644 index 0000000..c3ade87 --- /dev/null +++ b/dg-ui/node_modules/enhanced-resolve/types/TryNextPlugin.d.ts @@ -0,0 +1,26 @@ +export = TryNextPlugin; +declare class TryNextPlugin { + /** + * @param {string | ResolveStepHook} source source + * @param {string} message message + * @param {string | ResolveStepHook} target target + */ + constructor( + source: string | ResolveStepHook, + message: string, + target: string | ResolveStepHook, + ); + source: string | import("./Resolver").ResolveStepHook; + message: string; + target: string | import("./Resolver").ResolveStepHook; + /** + * @param {Resolver} resolver the resolver + * @returns {void} + */ + apply(resolver: Resolver): void; +} +declare namespace TryNextPlugin { + export { Resolver, ResolveStepHook }; +} +type Resolver = import("./Resolver"); +type ResolveStepHook = import("./Resolver").ResolveStepHook; diff --git a/dg-ui/node_modules/enhanced-resolve/types/TsconfigPathsPlugin.d.ts b/dg-ui/node_modules/enhanced-resolve/types/TsconfigPathsPlugin.d.ts new file mode 100644 index 0000000..0e5a4a4 --- /dev/null +++ b/dg-ui/node_modules/enhanced-resolve/types/TsconfigPathsPlugin.d.ts @@ -0,0 +1,192 @@ +export = TsconfigPathsPlugin; +declare class TsconfigPathsPlugin { + /** + * @param {true | string | TsconfigOptions} configFileOrOptions tsconfig file path or options object + */ + constructor(configFileOrOptions: true | string | TsconfigOptions); + /** @type {boolean} */ + isAutoConfigFile: boolean; + /** @type {string} */ + configFile: string; + /** @type {TsconfigReference[] | "auto"} */ + references: TsconfigReference[] | "auto"; + /** @type {string | undefined} */ + baseUrl: string | undefined; + /** + * @param {Resolver} resolver the resolver + * @returns {void} + */ + apply(resolver: Resolver): void; + /** + * Get TsconfigPathsMap for the request (with caching) + * @param {Resolver} resolver the resolver + * @param {ResolveRequest} request the request + * @param {ResolveContext} resolveContext the resolve context + * @param {(err: Error | null, result?: TsconfigPathsMap | null) => void} callback the callback + * @returns {void} + */ + _getTsconfigPathsMap( + resolver: Resolver, + request: ResolveRequest, + resolveContext: ResolveContext, + callback: (err: Error | null, result?: TsconfigPathsMap | null) => void, + ): void; + /** + * Walk up from startDir to the filesystem root looking for tsconfig.json. + * Like TypeScript's own `findConfigFile` / `forEachAncestorDirectory`. + * @param {Resolver} resolver the resolver + * @param {string} startDir the directory to start searching from + * @param {(err: Error | null, result?: TsconfigPathsMap | null) => void} callback the callback + * @returns {void} + */ + _findTsconfigUpward( + resolver: Resolver, + startDir: string, + callback: (err: Error | null, result?: TsconfigPathsMap | null) => void, + ): void; + /** + * Load tsconfig.json and build complete TsconfigPathsMap + * Includes main project paths and all referenced projects + * @param {Resolver} resolver the resolver + * @param {string} absTsconfigPath absolute path to tsconfig.json + * @param {(err: Error | null, result?: TsconfigPathsMap) => void} callback the callback + * @returns {void} + */ + _loadTsconfigPathsMap( + resolver: Resolver, + absTsconfigPath: string, + callback: (err: Error | null, result?: TsconfigPathsMap) => void, + ): void; + /** + * Select the correct TsconfigPathsData based on request.path (context-aware) + * Matches the behavior of tsconfig-paths-webpack-plugin + * @param {string | false} requestPath the request path + * @param {TsconfigPathsMap} tsconfigPathsMap the tsconfig paths map + * @returns {TsconfigPathsData | null} the selected paths data + */ + _selectPathsDataForContext( + requestPath: string | false, + tsconfigPathsMap: TsconfigPathsMap, + ): TsconfigPathsData | null; + /** + * Load tsconfig from extends path + * @param {Resolver} resolver the resolver + * @param {string} configFilePath current config file path + * @param {string} extendedConfigValue extends value + * @param {Set} fileDependencies the file dependencies + * @param {Set} visitedConfigPaths config paths being loaded (for circular extends detection) + * @param {(err: Error | null, result?: Tsconfig) => void} callback callback + * @returns {void} + */ + _loadTsconfigFromExtends( + resolver: Resolver, + configFilePath: string, + extendedConfigValue: string, + fileDependencies: Set, + visitedConfigPaths: Set, + callback: (err: Error | null, result?: Tsconfig) => void, + ): void; + /** + * Load referenced tsconfig projects and store in referenceMatchMap + * Simple implementation matching tsconfig-paths-webpack-plugin: + * Just load each reference and store independently + * @param {Resolver} resolver the resolver + * @param {string} context the context + * @param {TsconfigReference[]} references array of references + * @param {Set} fileDependencies the file dependencies + * @param {{ [baseUrl: string]: TsconfigPathsData }} referenceMatchMap the map to populate + * @param {(err: Error | null) => void} callback callback + * @param {Set=} visitedRefPaths visited reference config paths (for circular reference detection) + * @returns {void} + */ + _loadTsconfigReferences( + resolver: Resolver, + context: string, + references: TsconfigReference[], + fileDependencies: Set, + referenceMatchMap: { + [baseUrl: string]: TsconfigPathsData; + }, + callback: (err: Error | null) => void, + visitedRefPaths?: Set | undefined, + ): void; + /** + * Load tsconfig.json with extends support + * @param {Resolver} resolver the resolver + * @param {string} configFilePath absolute path to tsconfig.json + * @param {Set} fileDependencies the file dependencies + * @param {Set | undefined} visitedConfigPaths config paths being loaded (for circular extends detection) + * @param {(err: Error | null, result?: Tsconfig) => void} callback callback + * @returns {void} + */ + _loadTsconfig( + resolver: Resolver, + configFilePath: string, + fileDependencies: Set, + visitedConfigPaths: Set | undefined, + callback: (err: Error | null, result?: Tsconfig) => void, + ): void; +} +declare namespace TsconfigPathsPlugin { + export { + Resolver, + ResolveStepHook, + AliasOption, + ResolveRequest, + ResolveContext, + FileSystem, + TsconfigPathsData, + TsconfigPathsMap, + TsconfigOptions, + TsconfigCompilerOptions, + TsconfigReference, + Tsconfig, + }; +} +type Resolver = import("./Resolver"); +type ResolveStepHook = import("./Resolver").ResolveStepHook; +type AliasOption = import("./AliasUtils").AliasOption; +type ResolveRequest = import("./Resolver").ResolveRequest; +type ResolveContext = import("./Resolver").ResolveContext; +type FileSystem = import("./Resolver").FileSystem; +type TsconfigPathsData = import("./Resolver").TsconfigPathsData; +type TsconfigPathsMap = import("./Resolver").TsconfigPathsMap; +type TsconfigOptions = import("./ResolverFactory").TsconfigOptions; +type TsconfigCompilerOptions = { + /** + * Base URL for resolving paths + */ + baseUrl?: string | undefined; + /** + * TypeScript paths mapping + */ + paths?: + | { + [key: string]: string[]; + } + | undefined; + /** + * directory of the config file that declares `paths`, used when there is no `baseUrl` + */ + pathsBasePath?: string | undefined; +}; +type TsconfigReference = { + /** + * Path to the referenced project + */ + path: string; +}; +type Tsconfig = { + /** + * Compiler options + */ + compilerOptions?: TsconfigCompilerOptions | undefined; + /** + * Extended configuration paths + */ + extends?: (string | string[]) | undefined; + /** + * Project references + */ + references?: TsconfigReference[] | undefined; +}; diff --git a/dg-ui/node_modules/enhanced-resolve/types/UnsafeCachePlugin.d.ts b/dg-ui/node_modules/enhanced-resolve/types/UnsafeCachePlugin.d.ts new file mode 100644 index 0000000..efb46b7 --- /dev/null +++ b/dg-ui/node_modules/enhanced-resolve/types/UnsafeCachePlugin.d.ts @@ -0,0 +1,43 @@ +export = UnsafeCachePlugin; +declare class UnsafeCachePlugin { + /** + * @param {string | ResolveStepHook} source source + * @param {(request: ResolveRequest) => boolean} filterPredicate filterPredicate + * @param {Cache} cache cache + * @param {boolean} withContext withContext + * @param {string | ResolveStepHook} target target + */ + constructor( + source: string | ResolveStepHook, + filterPredicate: (request: ResolveRequest) => boolean, + cache: Cache, + withContext: boolean, + target: string | ResolveStepHook, + ); + source: string | import("./Resolver").ResolveStepHook; + filterPredicate: (request: ResolveRequest) => boolean; + withContext: boolean; + cache: Cache; + target: string | import("./Resolver").ResolveStepHook; + /** + * @param {Resolver} resolver the resolver + * @returns {void} + */ + apply(resolver: Resolver): void; +} +declare namespace UnsafeCachePlugin { + export { + Resolver, + ResolveRequest, + ResolveStepHook, + ResolveContextYield, + Cache, + }; +} +type Resolver = import("./Resolver"); +type ResolveRequest = import("./Resolver").ResolveRequest; +type ResolveStepHook = import("./Resolver").ResolveStepHook; +type ResolveContextYield = import("./Resolver").ResolveContextYield; +type Cache = { + [k: string]: undefined | ResolveRequest | ResolveRequest[]; +}; diff --git a/dg-ui/node_modules/enhanced-resolve/types/UseFilePlugin.d.ts b/dg-ui/node_modules/enhanced-resolve/types/UseFilePlugin.d.ts new file mode 100644 index 0000000..58fb940 --- /dev/null +++ b/dg-ui/node_modules/enhanced-resolve/types/UseFilePlugin.d.ts @@ -0,0 +1,27 @@ +export = UseFilePlugin; +declare class UseFilePlugin { + /** + * @param {string | ResolveStepHook} source source + * @param {string} filename filename + * @param {string | ResolveStepHook} target target + */ + constructor( + source: string | ResolveStepHook, + filename: string, + target: string | ResolveStepHook, + ); + source: string | import("./Resolver").ResolveStepHook; + filename: string; + target: string | import("./Resolver").ResolveStepHook; + /** + * @param {Resolver} resolver the resolver + * @returns {void} + */ + apply(resolver: Resolver): void; +} +declare namespace UseFilePlugin { + export { Resolver, ResolveRequest, ResolveStepHook }; +} +type Resolver = import("./Resolver"); +type ResolveRequest = import("./Resolver").ResolveRequest; +type ResolveStepHook = import("./Resolver").ResolveStepHook; diff --git a/dg-ui/node_modules/enhanced-resolve/types/createInnerContext.d.ts b/dg-ui/node_modules/enhanced-resolve/types/createInnerContext.d.ts new file mode 100644 index 0000000..25c4bf4 --- /dev/null +++ b/dg-ui/node_modules/enhanced-resolve/types/createInnerContext.d.ts @@ -0,0 +1,10 @@ +declare namespace _exports { + export { ResolveContext }; +} +declare function _exports( + parent: ResolveContext, + stack: ResolveContext["stack"], + message: null | string, +): ResolveContext; +export = _exports; +type ResolveContext = import("./Resolver").ResolveContext; diff --git a/dg-ui/node_modules/enhanced-resolve/types/forEachBail.d.ts b/dg-ui/node_modules/enhanced-resolve/types/forEachBail.d.ts new file mode 100644 index 0000000..472cae0 --- /dev/null +++ b/dg-ui/node_modules/enhanced-resolve/types/forEachBail.d.ts @@ -0,0 +1,15 @@ +declare namespace _exports { + export { ResolveRequest, Iterator }; +} +declare function _exports( + array: T[], + iterator: Iterator, + callback: (err?: null | Error, result?: null | Z, i?: number) => void, +): void; +export = _exports; +type ResolveRequest = import("./Resolver").ResolveRequest; +type Iterator = ( + item: T, + callback: (err?: null | Error, result?: null | Z) => void, + i: number, +) => void; diff --git a/dg-ui/node_modules/enhanced-resolve/types/getInnerRequest.d.ts b/dg-ui/node_modules/enhanced-resolve/types/getInnerRequest.d.ts new file mode 100644 index 0000000..1271b98 --- /dev/null +++ b/dg-ui/node_modules/enhanced-resolve/types/getInnerRequest.d.ts @@ -0,0 +1,7 @@ +declare namespace _exports { + export { Resolver, ResolveRequest }; +} +declare function _exports(resolver: Resolver, request: ResolveRequest): string; +export = _exports; +type Resolver = import("./Resolver"); +type ResolveRequest = import("./Resolver").ResolveRequest; diff --git a/dg-ui/node_modules/enhanced-resolve/types/getPaths.d.ts b/dg-ui/node_modules/enhanced-resolve/types/getPaths.d.ts new file mode 100644 index 0000000..f7fe471 --- /dev/null +++ b/dg-ui/node_modules/enhanced-resolve/types/getPaths.d.ts @@ -0,0 +1,34 @@ +export = getPaths; +/** @typedef {import("./Resolver").FileSystem} FileSystem */ +/** @typedef {{ paths: string[], segments: string[] }} GetPathsResult */ +/** + * Walk `path` from tip to root, returning every ancestor directory (plus the + * input itself) in `paths`, and each corresponding segment name in `segments`. + * + * The return value may be shared across callers via `getPathsCached` — treat + * it as read-only. Callers that need to mutate (currently only + * `SymlinkPlugin`) should `slice()` the arrays locally before writing. + * @param {string} path path + * @returns {GetPathsResult} paths and segments + */ +declare function getPaths(path: string): GetPathsResult; +declare namespace getPaths { + export { getPathsCached, FileSystem, GetPathsResult }; +} +/** + * Memoized `getPaths`. The returned object is shared across callers — do + * not mutate the `paths` or `segments` arrays in-place; `slice()` first if + * you need a mutable copy. + * @param {FileSystem} fileSystem filesystem used as the cache namespace + * @param {string} path path + * @returns {GetPathsResult} paths and segments + */ +declare function getPathsCached( + fileSystem: FileSystem, + path: string, +): GetPathsResult; +type FileSystem = import("./Resolver").FileSystem; +type GetPathsResult = { + paths: string[]; + segments: string[]; +}; diff --git a/dg-ui/node_modules/enhanced-resolve/types/index.d.ts b/dg-ui/node_modules/enhanced-resolve/types/index.d.ts new file mode 100644 index 0000000..b4b39fe --- /dev/null +++ b/dg-ui/node_modules/enhanced-resolve/types/index.d.ts @@ -0,0 +1,133 @@ +declare namespace _exports { + export { + ResolveOptionsOptionalFS, + CachedInputFileSystem, + BaseFileSystem, + CloneBasenamePlugin, + LogInfoPlugin, + PnpApi, + Resolver, + Context, + FileSystem, + ResolveCallback, + ResolveContext, + ResolveRequest, + SyncFileSystem, + Plugin, + ResolveOptions, + TsconfigPathsPlugin, + UnsafeCache, + ResolveFunctionAsync, + ResolveFunction, + ResolveFunctionPromise, + }; +} +declare const _exports: ResolveFunctionAsync & { + readonly sync: ResolveFunction; + readonly promise: ResolveFunctionPromise; + create: typeof create & { + readonly sync: typeof createSync; + readonly promise: typeof createPromise; + }; + readonly ResolverFactory: typeof import("./ResolverFactory"); + readonly CachedInputFileSystem: typeof import("./CachedInputFileSystem"); + readonly CloneBasenamePlugin: typeof import("./CloneBasenamePlugin"); + readonly LogInfoPlugin: typeof import("./LogInfoPlugin"); + readonly TsconfigPathsPlugin: typeof import("./TsconfigPathsPlugin"); + readonly forEachBail: ( + array: T[], + iterator: import("./forEachBail").Iterator, + callback: (err?: null | Error, result?: null | Z, i?: number) => void, + ) => void; +}; +export = _exports; +type ResolveOptionsOptionalFS = Omit & + Partial>; +type CachedInputFileSystem = import("./CachedInputFileSystem"); +type BaseFileSystem = import("./CachedInputFileSystem").BaseFileSystem; +type CloneBasenamePlugin = import("./CloneBasenamePlugin"); +type LogInfoPlugin = import("./LogInfoPlugin"); +type PnpApi = import("./PnpPlugin").PnpApiImpl; +type Resolver = import("./Resolver"); +type Context = import("./Resolver").Context; +type FileSystem = import("./Resolver").FileSystem; +type ResolveCallback = import("./Resolver").ResolveCallback; +type ResolveContext = import("./Resolver").ResolveContext; +type ResolveRequest = import("./Resolver").ResolveRequest; +type SyncFileSystem = import("./Resolver").SyncFileSystem; +type Plugin = import("./ResolverFactory").Plugin; +type ResolveOptions = import("./ResolverFactory").UserResolveOptions; +type TsconfigPathsPlugin = import("./TsconfigPathsPlugin"); +type UnsafeCache = import("./UnsafeCachePlugin").Cache; +type ResolveFunctionAsync = { + ( + context: Context, + parent: string | URL, + specifier: string | URL, + resolveContext: ResolveContext, + callback: ResolveCallback, + ): void; + ( + context: Context, + parent: string | URL, + specifier: string | URL, + callback: ResolveCallback, + ): void; + ( + parent: string | URL, + specifier: string | URL, + resolveContext: ResolveContext, + callback: ResolveCallback, + ): void; + ( + parent: string | URL, + specifier: string | URL, + callback: ResolveCallback, + ): void; +}; +type ResolveFunction = { + ( + context: Context, + parent: string | URL, + specifier: string | URL, + resolveContext?: ResolveContext, + ): string | false; + ( + parent: string | URL, + specifier: string | URL, + resolveContext?: ResolveContext, + ): string | false; +}; +type ResolveFunctionPromise = { + ( + context: Context, + parent: string | URL, + specifier: string | URL, + resolveContext?: ResolveContext, + ): Promise; + ( + parent: string | URL, + specifier: string | URL, + resolveContext?: ResolveContext, + ): Promise; +}; +/** @typedef {Omit & Partial>} ResolveOptionsOptionalFS */ +/** + * @param {ResolveOptionsOptionalFS} options Resolver options + * @returns {ResolveFunctionAsync} Resolver function + */ +declare function create( + options: ResolveOptionsOptionalFS, +): ResolveFunctionAsync; +/** + * @param {ResolveOptionsOptionalFS} options Resolver options + * @returns {ResolveFunction} Resolver function + */ +declare function createSync(options: ResolveOptionsOptionalFS): ResolveFunction; +/** + * @param {ResolveOptionsOptionalFS} options Resolver options + * @returns {ResolveFunctionPromise} Resolver function + */ +declare function createPromise( + options: ResolveOptionsOptionalFS, +): ResolveFunctionPromise; diff --git a/dg-ui/node_modules/enhanced-resolve/types/util/entrypoints.d.ts b/dg-ui/node_modules/enhanced-resolve/types/util/entrypoints.d.ts new file mode 100644 index 0000000..3ebe112 --- /dev/null +++ b/dg-ui/node_modules/enhanced-resolve/types/util/entrypoints.d.ts @@ -0,0 +1,62 @@ +export function explainSubpathsInConditions( + field: ExportsField | ImportsField | null | undefined, + isExports: boolean, +): string | null; +export function processExportsField(exportsField: ExportsField): FieldProcessor; +export function processImportsField(importsField: ImportsField): FieldProcessor; +export type DirectMapping = string | (string | ConditionalMapping)[]; +export type ConditionalMapping = { + [k: string]: MappingValue; +}; +export type MappingValue = ConditionalMapping | DirectMapping | null; +export type ExportsField = + Record | ConditionalMapping | DirectMapping; +export type ImportsField = Record; +/** + * Processing exports/imports field + */ +export type FieldProcessor = ( + request: string, + conditionNames: Set, +) => [string[], string | null]; +export type RecordMapping = Record; +/** + * Per-key precomputed info used by `findMatch`. Equivalent to what the + * previous implementation recomputed inline on every resolve. + */ +export type FieldKeyInfo = { + /** + * the original key + */ + key: string; + /** + * position of the single "*" in the key, or -1 when absent + */ + patternIndex: number; + /** + * substring before "*" (empty when patternIndex === -1) + */ + wildcardPrefix: string; + /** + * substring after "*" (empty when patternIndex === -1) + */ + wildcardSuffix: string; + /** + * true when key is a legacy `./foo/`-style folder key with no "*" + */ + isLegacySubpath: boolean; + /** + * true when key contains "*" + */ + isPattern: boolean; + /** + * true when key ends with "/" + */ + isSubpathMapping: boolean; + /** + * true when key has at most one "*" + */ + isValidPattern: boolean; +}; +export type MatchTuple = + [MappingValue, string, boolean, boolean, string] | null; diff --git a/dg-ui/node_modules/enhanced-resolve/types/util/fileURLToPath.d.ts b/dg-ui/node_modules/enhanced-resolve/types/util/fileURLToPath.d.ts new file mode 100644 index 0000000..a217605 --- /dev/null +++ b/dg-ui/node_modules/enhanced-resolve/types/util/fileURLToPath.d.ts @@ -0,0 +1,14 @@ +export = fileURLToPath; +/** + * @param {string | URL} path a `file:` URL string or `URL` instance + * @param {{ windows?: boolean }=} options force the platform branch + * @returns {string} the filesystem path + */ +declare function fileURLToPath( + path: string | URL, + options?: + | { + windows?: boolean; + } + | undefined, +): string; diff --git a/dg-ui/node_modules/enhanced-resolve/types/util/fs.d.ts b/dg-ui/node_modules/enhanced-resolve/types/util/fs.d.ts new file mode 100644 index 0000000..b191ce2 --- /dev/null +++ b/dg-ui/node_modules/enhanced-resolve/types/util/fs.d.ts @@ -0,0 +1,38 @@ +export type FileSystem = import("../Resolver").FileSystem; +export type JsonObject = import("../Resolver").JsonObject; +export type ReadJsonOptions = { + /** + * Whether to strip JSONC comments + */ + stripComments?: boolean | undefined; +}; +/** + * Decode a file's raw contents to text without assuming a Node runtime. A + * `Buffer` (Node) uses its fast native `toString`; any other binary input + * (`Uint8Array` from a browser/Deno/Bun file system) goes through + * `TextDecoder`, and strings are returned as-is. + * @param {string | Buffer | Uint8Array} data raw file contents + * @returns {string} decoded text + */ +export function decodeText(data: string | Buffer | Uint8Array): string; +/** + * Read and parse JSON file (supports JSONC with comments). + * Callback-based so a synchronous `fileSystem` stays synchronous all the + * way through — Promise wrapping would defer resolution by a Promise tick + * and break `resolveSync` when `tsconfig` is used together with + * `useSyncFileSystemCalls: true`. + * @param {FileSystem} fileSystem the file system + * @param {string} jsonFilePath absolute path to JSON file + * @param {ReadJsonOptions} options Options + * @param {(err: NodeJS.ErrnoException | Error | null, content?: JsonObject) => void} callback callback + * @returns {void} + */ +export function readJson( + fileSystem: FileSystem, + jsonFilePath: string, + options: ReadJsonOptions, + callback: ( + err: NodeJS.ErrnoException | Error | null, + content?: JsonObject, + ) => void, +): void; diff --git a/dg-ui/node_modules/enhanced-resolve/types/util/graceful-fs-browser.d.ts b/dg-ui/node_modules/enhanced-resolve/types/util/graceful-fs-browser.d.ts new file mode 100644 index 0000000..a8ee8eb --- /dev/null +++ b/dg-ui/node_modules/enhanced-resolve/types/util/graceful-fs-browser.d.ts @@ -0,0 +1,22 @@ +/** + * Takes the arguments its callers pass - `readFile(path, callback)` and the + * rest - so the declaration describes a call that actually compiles, even + * though every one of them throws. + * @param {...unknown} _args arguments, ignored + * @returns {never} always throws + */ +declare function unavailable(..._args: unknown[]): never; +export { + unavailable as lstat, + unavailable as lstatSync, + unavailable as readFile, + unavailable as readFileSync, + unavailable as readdir, + unavailable as readdirSync, + unavailable as readlink, + unavailable as readlinkSync, + unavailable as realpath, + unavailable as realpathSync, + unavailable as stat, + unavailable as statSync, +}; diff --git a/dg-ui/node_modules/enhanced-resolve/types/util/identifier.d.ts b/dg-ui/node_modules/enhanced-resolve/types/util/identifier.d.ts new file mode 100644 index 0000000..9964489 --- /dev/null +++ b/dg-ui/node_modules/enhanced-resolve/types/util/identifier.d.ts @@ -0,0 +1,7 @@ +/** + * @param {string} identifier identifier + * @returns {[string, string, string] | null} parsed identifier + */ +export function parseIdentifier( + identifier: string, +): [string, string, string] | null; diff --git a/dg-ui/node_modules/enhanced-resolve/types/util/memoize.d.ts b/dg-ui/node_modules/enhanced-resolve/types/util/memoize.d.ts new file mode 100644 index 0000000..4ada2d1 --- /dev/null +++ b/dg-ui/node_modules/enhanced-resolve/types/util/memoize.d.ts @@ -0,0 +1,15 @@ +export = memoize; +/** + * @template T + * @typedef {() => T} FunctionReturning + */ +/** + * @template T + * @param {FunctionReturning} fn memorized function + * @returns {FunctionReturning} new function + */ +declare function memoize(fn: FunctionReturning): FunctionReturning; +declare namespace memoize { + export { FunctionReturning }; +} +type FunctionReturning = () => T; diff --git a/dg-ui/node_modules/enhanced-resolve/types/util/module-browser.d.ts b/dg-ui/node_modules/enhanced-resolve/types/util/module-browser.d.ts new file mode 100644 index 0000000..cb0ff5c --- /dev/null +++ b/dg-ui/node_modules/enhanced-resolve/types/util/module-browser.d.ts @@ -0,0 +1 @@ +export {}; diff --git a/dg-ui/node_modules/enhanced-resolve/types/util/packageMap.d.ts b/dg-ui/node_modules/enhanced-resolve/types/util/packageMap.d.ts new file mode 100644 index 0000000..deca530 --- /dev/null +++ b/dg-ui/node_modules/enhanced-resolve/types/util/packageMap.d.ts @@ -0,0 +1,118 @@ +export type JsonObject = import("../Resolver").JsonObject; +export type PackageMapDependencies = { + [specifier: string]: string; +}; +/** + * A single entry of the configuration file's `packages` object. + */ +export type PackageMapPackage = { + /** + * an absolute or relative `file:` URL, resolved against the configuration file + */ + url: string; + /** + * bare specifier to package id + */ + dependencies?: PackageMapDependencies | undefined; +}; +export type PackageMapPackages = { + [id: string]: PackageMapPackage; +}; +/** + * The parsed contents of a package map configuration file. + */ +export type PackageMapJson = { + /** + * package entries by package id + */ + packages: PackageMapPackages; +}; +export type PackageMapEntry = { + /** + * the package id this entry is keyed by + */ + id: string; + /** + * absolute filesystem path the entry's `url` points at + */ + path: string; + /** + * bare specifier to package id + */ + dependencies: Map; +}; +export type PackageMap = { + /** + * entries by package id + */ + packages: Map; + /** + * package ids by location, longest path first + */ + locations: { + path: string; + ids: string[]; + }[]; +}; +/** @typedef {import("../Resolver").JsonObject} JsonObject */ +/** @typedef {{ [specifier: string]: string }} PackageMapDependencies */ +/** + * A single entry of the configuration file's `packages` object. + * @typedef {object} PackageMapPackage + * @property {string} url an absolute or relative `file:` URL, resolved against the configuration file + * @property {PackageMapDependencies=} dependencies bare specifier to package id + */ +/** @typedef {{ [id: string]: PackageMapPackage }} PackageMapPackages */ +/** + * The parsed contents of a package map configuration file. + * @typedef {object} PackageMapJson + * @property {PackageMapPackages} packages package entries by package id + */ +/** + * @typedef {object} PackageMapEntry + * @property {string} id the package id this entry is keyed by + * @property {string} path absolute filesystem path the entry's `url` points at + * @property {Map} dependencies bare specifier to package id + */ +/** + * @typedef {object} PackageMap + * @property {Map} packages entries by package id + * @property {{ path: string, ids: string[] }[]} locations package ids by location, longest path first + */ +/** + * @param {string} message message + * @param {string} code error code + * @returns {Error & { code: string }} the error + */ +export function createError( + message: string, + code: string, +): Error & { + code: string; +}; +/** + * Find the package ids whose location contains `filePath`. More than one id is + * returned when several package entries share the same `url`, which the caller + * has to disambiguate with an explicit package id. + * @param {PackageMap} packageMap the package map + * @param {string} filePath an absolute filesystem path + * @returns {string[]} the matching package ids, empty when the path is outside every package + */ +export function findPackageIds( + packageMap: PackageMap, + filePath: string, +): string[]; +/** + * Parse and validate a package map configuration file. + * + * Dangling dependency targets are rejected here rather than at resolution + * time: the map is static, so a broken table is a configuration error that is + * better surfaced once and in full. + * @param {JsonObject} data the parsed configuration file contents + * @param {string} configFilePath absolute path of the configuration file, used as the base for relative urls + * @returns {PackageMap} the parsed package map + */ +export function parsePackageMap( + data: JsonObject, + configFilePath: string, +): PackageMap; diff --git a/dg-ui/node_modules/enhanced-resolve/types/util/path-browser.d.ts b/dg-ui/node_modules/enhanced-resolve/types/util/path-browser.d.ts new file mode 100644 index 0000000..05a5d22 --- /dev/null +++ b/dg-ui/node_modules/enhanced-resolve/types/util/path-browser.d.ts @@ -0,0 +1,45 @@ +/** + * Posix `basename` — the browser is treated as a posix platform, matching how + * Node picks the posix variant for `path.basename` on non-Windows systems. + * @param {string} path path + * @param {string=} suffix optional suffix to strip + * @returns {string} basename + */ +export function basename(path: string, suffix?: string | undefined): string; +/** + * @param {string} path path + * @returns {string} normalized posix path + */ +declare function posixNormalize(path: string): string; +/** + * @param {string} path path + * @returns {string} posix dirname + */ +declare function posixDirname(path: string): string; +/** + * Normalizes drive paths (`C:\…`), UNC paths (`\\server\share\…`), DOS device + * paths (`\\.\…`, `\\?\…`) and relative/normal segments like Node's + * `path.win32.normalize`, including the CVE-2024-36139 colon-segment guard. + * + * Scope note: reserved Windows device names (`CON`, `COM1`, `LPT1`, …) are not + * special-cased, so e.g. `\\.\COM1:` differs from Node. Such names cannot occur + * in a browser (the only place this shim is used) and the resolver never routes + * them to `win32.normalize`, so this does not affect resolution. + * @param {string} path path + * @returns {string} normalized win32 path + */ +declare function win32Normalize(path: string): string; +/** + * @param {string} path path + * @returns {string} win32 dirname + */ +declare function win32Dirname(path: string): string; +export declare namespace posix { + export { posixNormalize as normalize }; + export { posixDirname as dirname }; +} +export declare namespace win32 { + export { win32Normalize as normalize }; + export { win32Dirname as dirname }; +} +export {}; diff --git a/dg-ui/node_modules/enhanced-resolve/types/util/path.d.ts b/dg-ui/node_modules/enhanced-resolve/types/util/path.d.ts new file mode 100644 index 0000000..572770b --- /dev/null +++ b/dg-ui/node_modules/enhanced-resolve/types/util/path.d.ts @@ -0,0 +1,125 @@ +export type CachedJoin = { + fn: (rootPath: string, request: string) => string; + cache: Map>; +}; +export type CachedDirname = { + fn: (maybePath: string) => string; + cache: Map; +}; +export type CachedBasename = { + fn: (maybePath: string, suffix?: string) => string; + cache: Map>; +}; +export type PathType = number; +/** + * @enum {number} + */ +export const PathType: Readonly<{ + Empty: 0; + Normal: 1; + Relative: 2; + AbsoluteWin: 3; + AbsolutePosix: 4; + Internal: 5; +}>; +/** @typedef {{ fn: (maybePath: string, suffix?: string) => string, cache: Map> }} CachedBasename */ +/** + * @returns {CachedBasename} cached basename + */ +export function createCachedBasename(): CachedBasename; +/** @typedef {{ fn: (maybePath: string) => string, cache: Map }} CachedDirname */ +/** + * @returns {CachedDirname} cached dirname + */ +export function createCachedDirname(): CachedDirname; +/** @typedef {{ fn: (rootPath: string, request: string) => string, cache: Map> }} CachedJoin */ +/** + * @returns {CachedJoin} cached join + */ +export function createCachedJoin(): CachedJoin; +export const deprecatedInvalidSegmentRegEx: RegExp; +/** + * @param {string} maybePath a path + * @returns {string} the directory name + */ +export function dirname(maybePath: string): string; +/** + * @param {string} maybePath a path + * @returns {PathType} type of path + */ +export function getType(maybePath: string): PathType; +export const invalidSegmentRegEx: RegExp; +/** + * Whether a string names a `file:` URL rather than a path. The scheme has to + * open the string and be followed by a slash, as Node's own URL parser needs, + * so a path segment spelled `file:` stays a path and `file:x.js` — which Node + * reads as `/x.js` — stays the relative request it looks like. + * @param {string} maybePath a path or a `file:` URL string + * @returns {boolean} true when the string is a `file:` URL + */ +export function isFileURL(maybePath: string): boolean; +/** + * Whether childPath is parentPath itself or a path under it, the answer node's + * `relative(parentPath, childPath)` gives: not escaping upward and not + * absolute. A trailing separator on the parent is not part of the boundary, so + * `/a/b/` contains exactly what `/a/b` contains. + * @param {string} parentPath parent directory path + * @param {string} childPath child path to check + * @returns {boolean} true if childPath is parentPath or is under it + */ +export function isInside(parentPath: string, childPath: string): boolean; +/** + * Whether `request` is a relative request — i.e. matches `^\.\.?(?:\/|$)`. + * + * This is called on every `doResolve` via `UnsafeCachePlugin` and + * `getInnerRequest`, so the char-code form is meaningfully faster than the + * equivalent regex test: no regex state machine, no string object churn. + * @param {string} request request string + * @returns {boolean} true if request is relative + */ +export function isRelativeRequest(request: string): boolean; +/** + * Check if childPath is a subdirectory of parentPath. Compares like `isInside`, + * except that a path is not a subpath of itself. + * + * Called from `TsconfigPathsPlugin._selectPathsDataForContext` inside a loop + * over every tsconfig-paths context on every resolve, so it's worth keeping + * cheap: a native `startsWith` plus a separator char check answers it, and the + * character loop only runs for a Windows path that the prefix test missed. + * @param {string} parentPath parent directory path + * @param {string} childPath child path to check + * @returns {boolean} true if childPath is under parentPath + */ +export function isSubPath(parentPath: string, childPath: string): boolean; +/** + * Whether this is a Windows path, in which `/` and `\` are interchangeable and + * paths compare case-insensitively, as opposed to a posix path, in which `\` is + * an ordinary filename character. Decided by the root — a drive letter or a + * leading `\` — which is where `path.win32` and `path.posix` disagree about + * `parse(maybePath).root`, and never by the host platform, since Windows paths + * are resolved on posix hosts and in browsers too. A path starting with `//` + * stays posix: `path.win32` reads it as a UNC root, but here it cannot be told + * apart from a posix path, where `\` has to keep being a filename character. + * @param {string} maybePath a path + * @returns {boolean} true, when the path is a Windows path + */ +export function isWindowsPath(maybePath: string): boolean; +/** + * @param {string} rootPath the root path + * @param {string | undefined} request the request path + * @returns {string} the joined path + */ +export function join(rootPath: string, request: string | undefined): string; +/** + * @param {string} maybePath a path + * @returns {string} the normalized path + */ +export function normalize(maybePath: string): string; +/** + * Convert a `file:` URL — a `URL` instance or a `file:/` string, the form + * `import.meta.resolve` returns — to the path it names. Anything else is + * returned unchanged, so a path passes through. + * @param {string | URL} maybeURL a path, a `file:` URL string or a `file:` `URL` instance + * @returns {string} a filesystem path + */ +export function toPath(maybeURL: string | URL): string; diff --git a/dg-ui/node_modules/enhanced-resolve/types/util/pathToFileURL.d.ts b/dg-ui/node_modules/enhanced-resolve/types/util/pathToFileURL.d.ts new file mode 100644 index 0000000..a12d55e --- /dev/null +++ b/dg-ui/node_modules/enhanced-resolve/types/util/pathToFileURL.d.ts @@ -0,0 +1,14 @@ +export = pathToFileURL; +/** + * @param {string} filepath an absolute filesystem path + * @param {{ windows?: boolean }=} options force the platform branch + * @returns {URL} the `file:` URL + */ +declare function pathToFileURL( + filepath: string, + options?: + | { + windows?: boolean; + } + | undefined, +): URL; diff --git a/dg-ui/node_modules/enhanced-resolve/types/util/process-browser.d.ts b/dg-ui/node_modules/enhanced-resolve/types/util/process-browser.d.ts new file mode 100644 index 0000000..11b331b --- /dev/null +++ b/dg-ui/node_modules/enhanced-resolve/types/util/process-browser.d.ts @@ -0,0 +1,3 @@ +export let versions: Record; +/** @param {Function} fn function */ +export function nextTick(fn: Function, ...args: any[]): void; diff --git a/dg-ui/node_modules/enhanced-resolve/types/util/strip-json-comments.d.ts b/dg-ui/node_modules/enhanced-resolve/types/util/strip-json-comments.d.ts new file mode 100644 index 0000000..cef87e3 --- /dev/null +++ b/dg-ui/node_modules/enhanced-resolve/types/util/strip-json-comments.d.ts @@ -0,0 +1,24 @@ +export = stripJsonComments; +/** + * Strip comments from JSON string + * @param {string} jsonString JSON string with potential comments + * @param {StripJsonCommentsOptions} options Options + * @returns {string} JSON string without comments + */ +declare function stripJsonComments( + jsonString: string, + { whitespace, trailingCommas }?: StripJsonCommentsOptions, +): string; +declare namespace stripJsonComments { + export { StripJsonCommentsOptions }; +} +type StripJsonCommentsOptions = { + /** + * Replace comments with whitespace + */ + whitespace?: boolean | undefined; + /** + * Strip trailing commas + */ + trailingCommas?: boolean | undefined; +}; diff --git a/dg-ui/node_modules/enhanced-resolve/types/util/url-browser.d.ts b/dg-ui/node_modules/enhanced-resolve/types/util/url-browser.d.ts new file mode 100644 index 0000000..9af30a4 --- /dev/null +++ b/dg-ui/node_modules/enhanced-resolve/types/util/url-browser.d.ts @@ -0,0 +1 @@ +export let fileURLToPath: typeof import("./fileURLToPath"); diff --git a/dg-ui/node_modules/graceful-fs/LICENSE.md b/dg-ui/node_modules/graceful-fs/LICENSE.md new file mode 100644 index 0000000..c5402b9 --- /dev/null +++ b/dg-ui/node_modules/graceful-fs/LICENSE.md @@ -0,0 +1,55 @@ +# Blue Oak Model License + +Version 1.0.0 + +## Purpose + +This license gives everyone as much permission to work with +this software as possible, while protecting contributors +from liability. + +## Acceptance + +In order to receive this license, you must agree to its +rules. The rules of this license are both obligations +under that agreement and conditions to your license. +You must not do anything with this software that triggers +a rule that you cannot or will not follow. + +## Copyright + +Each contributor licenses you to do everything with this +software that would otherwise infringe that contributor's +copyright in it. + +## Notices + +You must ensure that everyone who gets a copy of +any part of this software from you, with or without +changes, also gets the text of this license or a link to +. + +## Excuse + +If anyone notifies you in writing that you have not +complied with [Notices](#notices), you can keep your +license by taking all practical steps to comply within 30 +days after the notice. If you do not do so, your license +ends immediately. + +## Patent + +Each contributor licenses you to do everything with this +software that would otherwise infringe any patent claims +they can license or become able to license. + +## Reliability + +No contributor can revoke this license. + +## No Liability + +***As far as the law allows, this software comes as is, +without any warranty or condition, and no contributor +will be liable to anyone for any damages related to this +software or this license, under any kind of legal claim.*** diff --git a/dg-ui/node_modules/graceful-fs/README.md b/dg-ui/node_modules/graceful-fs/README.md new file mode 100644 index 0000000..82d6e4d --- /dev/null +++ b/dg-ui/node_modules/graceful-fs/README.md @@ -0,0 +1,143 @@ +# graceful-fs + +graceful-fs functions as a drop-in replacement for the fs module, +making various improvements. + +The improvements are meant to normalize behavior across different +platforms and environments, and to make filesystem access more +resilient to errors. + +## Improvements over [fs module](https://nodejs.org/api/fs.html) + +* Queues up `open` and `readdir` calls, and retries them once + something closes if there is an EMFILE error from too many file + descriptors. +* fixes `lchmod` for Node versions prior to 0.6.2. +* implements `fs.lutimes` if possible. Otherwise it becomes a noop. +* ignores `EINVAL` and `EPERM` errors in `chown`, `fchown` or + `lchown` if the user isn't root. +* makes `lchmod` and `lchown` become noops, if not available. +* retries reading a file if `read` results in EAGAIN error. + +On Windows, it retries renaming a file for up to one second if `EACCESS` +or `EPERM` error occurs, likely because antivirus software has locked +the directory. + +## USAGE + +```javascript +// use just like fs +var fs = require('graceful-fs') + +// now go and do stuff with it... +fs.readFile('some-file-or-whatever', (err, data) => { + // Do stuff here. +}) +``` + +## Sync methods + +This module cannot intercept or handle `EMFILE` or `ENFILE` errors from sync +methods. If you use sync methods which open file descriptors then you are +responsible for dealing with any errors. + +This is a known limitation, not a bug. + +## Global Patching + +If you want to patch the global fs module (or any other fs-like +module) you can do this: + +```javascript +// Make sure to read the caveat below. +var realFs = require('fs') +var gracefulFs = require('graceful-fs') +gracefulFs.gracefulify(realFs) +``` + +This should only ever be done at the top-level application layer, in +order to delay on EMFILE errors from any fs-using dependencies. You +should **not** do this in a library, because it can cause unexpected +delays in other parts of the program. + +## Changes + +This module is fairly stable at this point, and used by a lot of +things. That being said, because it implements a subtle behavior +change in a core part of the node API, even modest changes can be +extremely breaking, and the versioning is thus biased towards +bumping the major when in doubt. + +The main change between major versions has been switching between +providing a fully-patched `fs` module vs monkey-patching the node core +builtin, and the approach by which a non-monkey-patched `fs` was +created. + +The goal is to trade `EMFILE` errors for slower fs operations. So, if +you try to open a zillion files, rather than crashing, `open` +operations will be queued up and wait for something else to `close`. + +There are advantages to each approach. Monkey-patching the fs means +that no `EMFILE` errors can possibly occur anywhere in your +application, because everything is using the same core `fs` module, +which is patched. However, it can also obviously cause undesirable +side-effects, especially if the module is loaded multiple times. + +Implementing a separate-but-identical patched `fs` module is more +surgical (and doesn't run the risk of patching multiple times), but +also imposes the challenge of keeping in sync with the core module. + +The current approach loads the `fs` module, and then creates a +lookalike object that has all the same methods, except a few that are +patched. It is safe to use in all versions of Node from 0.8 through +7.0. + +### v4 + +* Do not monkey-patch the fs module. This module may now be used as a + drop-in dep, and users can opt into monkey-patching the fs builtin + if their app requires it. + +### v3 + +* Monkey-patch fs, because the eval approach no longer works on recent + node. +* fixed possible type-error throw if rename fails on windows +* verify that we *never* get EMFILE errors +* Ignore ENOSYS from chmod/chown +* clarify that graceful-fs must be used as a drop-in + +### v2.1.0 + +* Use eval rather than monkey-patching fs. +* readdir: Always sort the results +* win32: requeue a file if error has an OK status + +### v2.0 + +* A return to monkey patching +* wrap process.cwd + +### v1.1 + +* wrap readFile +* Wrap fs.writeFile. +* readdir protection +* Don't clobber the fs builtin +* Handle fs.read EAGAIN errors by trying again +* Expose the curOpen counter +* No-op lchown/lchmod if not implemented +* fs.rename patch only for win32 +* Patch fs.rename to handle AV software on Windows +* Close #4 Chown should not fail on einval or eperm if non-root +* Fix isaacs/fstream#1 Only wrap fs one time +* Fix #3 Start at 1024 max files, then back off on EMFILE +* lutimes that doens't blow up on Linux +* A full on-rewrite using a queue instead of just swallowing the EMFILE error +* Wrap Read/Write streams as well + +### 1.0 + +* Update engines for node 0.6 +* Be lstat-graceful on Windows +* first diff --git a/dg-ui/node_modules/graceful-fs/clone.js b/dg-ui/node_modules/graceful-fs/clone.js new file mode 100644 index 0000000..dff3cc8 --- /dev/null +++ b/dg-ui/node_modules/graceful-fs/clone.js @@ -0,0 +1,23 @@ +'use strict' + +module.exports = clone + +var getPrototypeOf = Object.getPrototypeOf || function (obj) { + return obj.__proto__ +} + +function clone (obj) { + if (obj === null || typeof obj !== 'object') + return obj + + if (obj instanceof Object) + var copy = { __proto__: getPrototypeOf(obj) } + else + var copy = Object.create(null) + + Object.getOwnPropertyNames(obj).forEach(function (key) { + Object.defineProperty(copy, key, Object.getOwnPropertyDescriptor(obj, key)) + }) + + return copy +} diff --git a/dg-ui/node_modules/graceful-fs/graceful-fs.js b/dg-ui/node_modules/graceful-fs/graceful-fs.js new file mode 100644 index 0000000..8d5b89e --- /dev/null +++ b/dg-ui/node_modules/graceful-fs/graceful-fs.js @@ -0,0 +1,448 @@ +var fs = require('fs') +var polyfills = require('./polyfills.js') +var legacy = require('./legacy-streams.js') +var clone = require('./clone.js') + +var util = require('util') + +/* istanbul ignore next - node 0.x polyfill */ +var gracefulQueue +var previousSymbol + +/* istanbul ignore else - node 0.x polyfill */ +if (typeof Symbol === 'function' && typeof Symbol.for === 'function') { + gracefulQueue = Symbol.for('graceful-fs.queue') + // This is used in testing by future versions + previousSymbol = Symbol.for('graceful-fs.previous') +} else { + gracefulQueue = '___graceful-fs.queue' + previousSymbol = '___graceful-fs.previous' +} + +function noop () {} + +function publishQueue(context, queue) { + Object.defineProperty(context, gracefulQueue, { + get: function() { + return queue + } + }) +} + +var debug = noop +if (util.debuglog) + debug = util.debuglog('gfs4') +else if (/\bgfs4\b/i.test(process.env.NODE_DEBUG || '')) + debug = function() { + var m = util.format.apply(util, arguments) + m = 'GFS4: ' + m.split(/\n/).join('\nGFS4: ') + console.error(m) + } + +// Once time initialization +if (!fs[gracefulQueue]) { + // This queue can be shared by multiple loaded instances + var queue = global[gracefulQueue] || [] + publishQueue(fs, queue) + + // Patch fs.close/closeSync to shared queue version, because we need + // to retry() whenever a close happens *anywhere* in the program. + // This is essential when multiple graceful-fs instances are + // in play at the same time. + fs.close = (function (fs$close) { + function close (fd, cb) { + return fs$close.call(fs, fd, function (err) { + // This function uses the graceful-fs shared queue + if (!err) { + resetQueue() + } + + if (typeof cb === 'function') + cb.apply(this, arguments) + }) + } + + Object.defineProperty(close, previousSymbol, { + value: fs$close + }) + return close + })(fs.close) + + fs.closeSync = (function (fs$closeSync) { + function closeSync (fd) { + // This function uses the graceful-fs shared queue + fs$closeSync.apply(fs, arguments) + resetQueue() + } + + Object.defineProperty(closeSync, previousSymbol, { + value: fs$closeSync + }) + return closeSync + })(fs.closeSync) + + if (/\bgfs4\b/i.test(process.env.NODE_DEBUG || '')) { + process.on('exit', function() { + debug(fs[gracefulQueue]) + require('assert').equal(fs[gracefulQueue].length, 0) + }) + } +} + +if (!global[gracefulQueue]) { + publishQueue(global, fs[gracefulQueue]); +} + +module.exports = patch(clone(fs)) +if (process.env.TEST_GRACEFUL_FS_GLOBAL_PATCH && !fs.__patched) { + module.exports = patch(fs) + fs.__patched = true; +} + +function patch (fs) { + // Everything that references the open() function needs to be in here + polyfills(fs) + fs.gracefulify = patch + + fs.createReadStream = createReadStream + fs.createWriteStream = createWriteStream + var fs$readFile = fs.readFile + fs.readFile = readFile + function readFile (path, options, cb) { + if (typeof options === 'function') + cb = options, options = null + + return go$readFile(path, options, cb) + + function go$readFile (path, options, cb, startTime) { + return fs$readFile(path, options, function (err) { + if (err && (err.code === 'EMFILE' || err.code === 'ENFILE')) + enqueue([go$readFile, [path, options, cb], err, startTime || Date.now(), Date.now()]) + else { + if (typeof cb === 'function') + cb.apply(this, arguments) + } + }) + } + } + + var fs$writeFile = fs.writeFile + fs.writeFile = writeFile + function writeFile (path, data, options, cb) { + if (typeof options === 'function') + cb = options, options = null + + return go$writeFile(path, data, options, cb) + + function go$writeFile (path, data, options, cb, startTime) { + return fs$writeFile(path, data, options, function (err) { + if (err && (err.code === 'EMFILE' || err.code === 'ENFILE')) + enqueue([go$writeFile, [path, data, options, cb], err, startTime || Date.now(), Date.now()]) + else { + if (typeof cb === 'function') + cb.apply(this, arguments) + } + }) + } + } + + var fs$appendFile = fs.appendFile + if (fs$appendFile) + fs.appendFile = appendFile + function appendFile (path, data, options, cb) { + if (typeof options === 'function') + cb = options, options = null + + return go$appendFile(path, data, options, cb) + + function go$appendFile (path, data, options, cb, startTime) { + return fs$appendFile(path, data, options, function (err) { + if (err && (err.code === 'EMFILE' || err.code === 'ENFILE')) + enqueue([go$appendFile, [path, data, options, cb], err, startTime || Date.now(), Date.now()]) + else { + if (typeof cb === 'function') + cb.apply(this, arguments) + } + }) + } + } + + var fs$copyFile = fs.copyFile + if (fs$copyFile) + fs.copyFile = copyFile + function copyFile (src, dest, flags, cb) { + if (typeof flags === 'function') { + cb = flags + flags = 0 + } + return go$copyFile(src, dest, flags, cb) + + function go$copyFile (src, dest, flags, cb, startTime) { + return fs$copyFile(src, dest, flags, function (err) { + if (err && (err.code === 'EMFILE' || err.code === 'ENFILE')) + enqueue([go$copyFile, [src, dest, flags, cb], err, startTime || Date.now(), Date.now()]) + else { + if (typeof cb === 'function') + cb.apply(this, arguments) + } + }) + } + } + + var fs$readdir = fs.readdir + fs.readdir = readdir + var noReaddirOptionVersions = /^v[0-5]\./ + function readdir (path, options, cb) { + if (typeof options === 'function') + cb = options, options = null + + var go$readdir = noReaddirOptionVersions.test(process.version) + ? function go$readdir (path, options, cb, startTime) { + return fs$readdir(path, fs$readdirCallback( + path, options, cb, startTime + )) + } + : function go$readdir (path, options, cb, startTime) { + return fs$readdir(path, options, fs$readdirCallback( + path, options, cb, startTime + )) + } + + return go$readdir(path, options, cb) + + function fs$readdirCallback (path, options, cb, startTime) { + return function (err, files) { + if (err && (err.code === 'EMFILE' || err.code === 'ENFILE')) + enqueue([ + go$readdir, + [path, options, cb], + err, + startTime || Date.now(), + Date.now() + ]) + else { + if (files && files.sort) + files.sort() + + if (typeof cb === 'function') + cb.call(this, err, files) + } + } + } + } + + if (process.version.substr(0, 4) === 'v0.8') { + var legStreams = legacy(fs) + ReadStream = legStreams.ReadStream + WriteStream = legStreams.WriteStream + } + + var fs$ReadStream = fs.ReadStream + if (fs$ReadStream) { + ReadStream.prototype = Object.create(fs$ReadStream.prototype) + ReadStream.prototype.open = ReadStream$open + } + + var fs$WriteStream = fs.WriteStream + if (fs$WriteStream) { + WriteStream.prototype = Object.create(fs$WriteStream.prototype) + WriteStream.prototype.open = WriteStream$open + } + + Object.defineProperty(fs, 'ReadStream', { + get: function () { + return ReadStream + }, + set: function (val) { + ReadStream = val + }, + enumerable: true, + configurable: true + }) + Object.defineProperty(fs, 'WriteStream', { + get: function () { + return WriteStream + }, + set: function (val) { + WriteStream = val + }, + enumerable: true, + configurable: true + }) + + // legacy names + var FileReadStream = ReadStream + Object.defineProperty(fs, 'FileReadStream', { + get: function () { + return FileReadStream + }, + set: function (val) { + FileReadStream = val + }, + enumerable: true, + configurable: true + }) + var FileWriteStream = WriteStream + Object.defineProperty(fs, 'FileWriteStream', { + get: function () { + return FileWriteStream + }, + set: function (val) { + FileWriteStream = val + }, + enumerable: true, + configurable: true + }) + + function ReadStream (path, options) { + if (this instanceof ReadStream) + return fs$ReadStream.apply(this, arguments), this + else + return ReadStream.apply(Object.create(ReadStream.prototype), arguments) + } + + function ReadStream$open () { + var that = this + open(that.path, that.flags, that.mode, function (err, fd) { + if (err) { + if (that.autoClose) + that.destroy() + + that.emit('error', err) + } else { + that.fd = fd + that.emit('open', fd) + that.read() + } + }) + } + + function WriteStream (path, options) { + if (this instanceof WriteStream) + return fs$WriteStream.apply(this, arguments), this + else + return WriteStream.apply(Object.create(WriteStream.prototype), arguments) + } + + function WriteStream$open () { + var that = this + open(that.path, that.flags, that.mode, function (err, fd) { + if (err) { + that.destroy() + that.emit('error', err) + } else { + that.fd = fd + that.emit('open', fd) + } + }) + } + + function createReadStream (path, options) { + return new fs.ReadStream(path, options) + } + + function createWriteStream (path, options) { + return new fs.WriteStream(path, options) + } + + var fs$open = fs.open + fs.open = open + function open (path, flags, mode, cb) { + if (typeof mode === 'function') + cb = mode, mode = null + + return go$open(path, flags, mode, cb) + + function go$open (path, flags, mode, cb, startTime) { + return fs$open(path, flags, mode, function (err, fd) { + if (err && (err.code === 'EMFILE' || err.code === 'ENFILE')) + enqueue([go$open, [path, flags, mode, cb], err, startTime || Date.now(), Date.now()]) + else { + if (typeof cb === 'function') + cb.apply(this, arguments) + } + }) + } + } + + return fs +} + +function enqueue (elem) { + debug('ENQUEUE', elem[0].name, elem[1]) + fs[gracefulQueue].push(elem) + retry() +} + +// keep track of the timeout between retry() calls +var retryTimer + +// reset the startTime and lastTime to now +// this resets the start of the 60 second overall timeout as well as the +// delay between attempts so that we'll retry these jobs sooner +function resetQueue () { + var now = Date.now() + for (var i = 0; i < fs[gracefulQueue].length; ++i) { + // entries that are only a length of 2 are from an older version, don't + // bother modifying those since they'll be retried anyway. + if (fs[gracefulQueue][i].length > 2) { + fs[gracefulQueue][i][3] = now // startTime + fs[gracefulQueue][i][4] = now // lastTime + } + } + // call retry to make sure we're actively processing the queue + retry() +} + +function retry () { + // clear the timer and remove it to help prevent unintended concurrency + clearTimeout(retryTimer) + retryTimer = undefined + + if (fs[gracefulQueue].length === 0) + return + + var elem = fs[gracefulQueue].shift() + var fn = elem[0] + var args = elem[1] + // these items may be unset if they were added by an older graceful-fs + var err = elem[2] + var startTime = elem[3] + var lastTime = elem[4] + + // if we don't have a startTime we have no way of knowing if we've waited + // long enough, so go ahead and retry this item now + if (startTime === undefined) { + debug('RETRY', fn.name, args) + fn.apply(null, args) + } else if (Date.now() - startTime >= 60000) { + // it's been more than 60 seconds total, bail now + debug('TIMEOUT', fn.name, args) + var cb = args.pop() + if (typeof cb === 'function') + cb.call(null, err) + } else { + // the amount of time between the last attempt and right now + var sinceAttempt = Date.now() - lastTime + // the amount of time between when we first tried, and when we last tried + // rounded up to at least 1 + var sinceStart = Math.max(lastTime - startTime, 1) + // backoff. wait longer than the total time we've been retrying, but only + // up to a maximum of 100ms + var desiredDelay = Math.min(sinceStart * 1.2, 100) + // it's been long enough since the last retry, do it again + if (sinceAttempt >= desiredDelay) { + debug('RETRY', fn.name, args) + fn.apply(null, args.concat([startTime])) + } else { + // if we can't do this job yet, push it to the end of the queue + // and let the next iteration check again + fs[gracefulQueue].push(elem) + } + } + + // schedule our next run if one isn't already scheduled + if (retryTimer === undefined) { + retryTimer = setTimeout(retry, 0) + } +} diff --git a/dg-ui/node_modules/graceful-fs/legacy-streams.js b/dg-ui/node_modules/graceful-fs/legacy-streams.js new file mode 100644 index 0000000..d617b50 --- /dev/null +++ b/dg-ui/node_modules/graceful-fs/legacy-streams.js @@ -0,0 +1,118 @@ +var Stream = require('stream').Stream + +module.exports = legacy + +function legacy (fs) { + return { + ReadStream: ReadStream, + WriteStream: WriteStream + } + + function ReadStream (path, options) { + if (!(this instanceof ReadStream)) return new ReadStream(path, options); + + Stream.call(this); + + var self = this; + + this.path = path; + this.fd = null; + this.readable = true; + this.paused = false; + + this.flags = 'r'; + this.mode = 438; /*=0666*/ + this.bufferSize = 64 * 1024; + + options = options || {}; + + // Mixin options into this + var keys = Object.keys(options); + for (var index = 0, length = keys.length; index < length; index++) { + var key = keys[index]; + this[key] = options[key]; + } + + if (this.encoding) this.setEncoding(this.encoding); + + if (this.start !== undefined) { + if ('number' !== typeof this.start) { + throw TypeError('start must be a Number'); + } + if (this.end === undefined) { + this.end = Infinity; + } else if ('number' !== typeof this.end) { + throw TypeError('end must be a Number'); + } + + if (this.start > this.end) { + throw new Error('start must be <= end'); + } + + this.pos = this.start; + } + + if (this.fd !== null) { + process.nextTick(function() { + self._read(); + }); + return; + } + + fs.open(this.path, this.flags, this.mode, function (err, fd) { + if (err) { + self.emit('error', err); + self.readable = false; + return; + } + + self.fd = fd; + self.emit('open', fd); + self._read(); + }) + } + + function WriteStream (path, options) { + if (!(this instanceof WriteStream)) return new WriteStream(path, options); + + Stream.call(this); + + this.path = path; + this.fd = null; + this.writable = true; + + this.flags = 'w'; + this.encoding = 'binary'; + this.mode = 438; /*=0666*/ + this.bytesWritten = 0; + + options = options || {}; + + // Mixin options into this + var keys = Object.keys(options); + for (var index = 0, length = keys.length; index < length; index++) { + var key = keys[index]; + this[key] = options[key]; + } + + if (this.start !== undefined) { + if ('number' !== typeof this.start) { + throw TypeError('start must be a Number'); + } + if (this.start < 0) { + throw new Error('start must be >= zero'); + } + + this.pos = this.start; + } + + this.busy = false; + this._queue = []; + + if (this.fd === null) { + this._open = fs.open; + this._queue.push([this._open, this.path, this.flags, this.mode, undefined]); + this.flush(); + } + } +} diff --git a/dg-ui/node_modules/graceful-fs/package.json b/dg-ui/node_modules/graceful-fs/package.json new file mode 100644 index 0000000..6ba7512 --- /dev/null +++ b/dg-ui/node_modules/graceful-fs/package.json @@ -0,0 +1,52 @@ +{ + "name": "graceful-fs", + "description": "A drop-in replacement for fs, making various improvements.", + "version": "4.2.12", + "repository": { + "type": "git", + "url": "https://github.com/isaacs/node-graceful-fs" + }, + "main": "graceful-fs.js", + "directories": { + "test": "test" + }, + "scripts": { + "preversion": "npm test", + "postversion": "git push origin --follow-tags", + "test": "nyc --silent node test.js | tap -c -", + "posttest": "nyc report" + }, + "keywords": [ + "fs", + "module", + "reading", + "retry", + "retries", + "queue", + "error", + "errors", + "handling", + "EMFILE", + "EAGAIN", + "EINVAL", + "EPERM", + "EACCESS" + ], + "license": "BlueOak-1.0.0", + "devDependencies": { + "import-fresh": "^2.0.0", + "mkdirp": "^0.5.0", + "rimraf": "^2.2.8", + "tap": "^16.3.4" + }, + "files": [ + "fs.js", + "graceful-fs.js", + "legacy-streams.js", + "polyfills.js", + "clone.js" + ], + "tap": { + "reporter": "classic" + } +} diff --git a/dg-ui/node_modules/graceful-fs/polyfills.js b/dg-ui/node_modules/graceful-fs/polyfills.js new file mode 100644 index 0000000..453f1a9 --- /dev/null +++ b/dg-ui/node_modules/graceful-fs/polyfills.js @@ -0,0 +1,355 @@ +var constants = require('constants') + +var origCwd = process.cwd +var cwd = null + +var platform = process.env.GRACEFUL_FS_PLATFORM || process.platform + +process.cwd = function() { + if (!cwd) + cwd = origCwd.call(process) + return cwd +} +try { + process.cwd() +} catch (er) {} + +// This check is needed until node.js 12 is required +if (typeof process.chdir === 'function') { + var chdir = process.chdir + process.chdir = function (d) { + cwd = null + chdir.call(process, d) + } + if (Object.setPrototypeOf) Object.setPrototypeOf(process.chdir, chdir) +} + +module.exports = patch + +function patch (fs) { + // (re-)implement some things that are known busted or missing. + + // lchmod, broken prior to 0.6.2 + // back-port the fix here. + if (constants.hasOwnProperty('O_SYMLINK') && + process.version.match(/^v0\.6\.[0-2]|^v0\.5\./)) { + patchLchmod(fs) + } + + // lutimes implementation, or no-op + if (!fs.lutimes) { + patchLutimes(fs) + } + + // https://github.com/isaacs/node-graceful-fs/issues/4 + // Chown should not fail on einval or eperm if non-root. + // It should not fail on enosys ever, as this just indicates + // that a fs doesn't support the intended operation. + + fs.chown = chownFix(fs.chown) + fs.fchown = chownFix(fs.fchown) + fs.lchown = chownFix(fs.lchown) + + fs.chmod = chmodFix(fs.chmod) + fs.fchmod = chmodFix(fs.fchmod) + fs.lchmod = chmodFix(fs.lchmod) + + fs.chownSync = chownFixSync(fs.chownSync) + fs.fchownSync = chownFixSync(fs.fchownSync) + fs.lchownSync = chownFixSync(fs.lchownSync) + + fs.chmodSync = chmodFixSync(fs.chmodSync) + fs.fchmodSync = chmodFixSync(fs.fchmodSync) + fs.lchmodSync = chmodFixSync(fs.lchmodSync) + + fs.stat = statFix(fs.stat) + fs.fstat = statFix(fs.fstat) + fs.lstat = statFix(fs.lstat) + + fs.statSync = statFixSync(fs.statSync) + fs.fstatSync = statFixSync(fs.fstatSync) + fs.lstatSync = statFixSync(fs.lstatSync) + + // if lchmod/lchown do not exist, then make them no-ops + if (fs.chmod && !fs.lchmod) { + fs.lchmod = function (path, mode, cb) { + if (cb) process.nextTick(cb) + } + fs.lchmodSync = function () {} + } + if (fs.chown && !fs.lchown) { + fs.lchown = function (path, uid, gid, cb) { + if (cb) process.nextTick(cb) + } + fs.lchownSync = function () {} + } + + // on Windows, A/V software can lock the directory, causing this + // to fail with an EACCES or EPERM if the directory contains newly + // created files. Try again on failure, for up to 60 seconds. + + // Set the timeout this long because some Windows Anti-Virus, such as Parity + // bit9, may lock files for up to a minute, causing npm package install + // failures. Also, take care to yield the scheduler. Windows scheduling gives + // CPU to a busy looping process, which can cause the program causing the lock + // contention to be starved of CPU by node, so the contention doesn't resolve. + if (platform === "win32") { + fs.rename = typeof fs.rename !== 'function' ? fs.rename + : (function (fs$rename) { + function rename (from, to, cb) { + var start = Date.now() + var backoff = 0; + fs$rename(from, to, function CB (er) { + if (er + && (er.code === "EACCES" || er.code === "EPERM" || er.code === "EBUSY") + && Date.now() - start < 60000) { + setTimeout(function() { + fs.stat(to, function (stater, st) { + if (stater && stater.code === "ENOENT") + fs$rename(from, to, CB); + else + cb(er) + }) + }, backoff) + if (backoff < 100) + backoff += 10; + return; + } + if (cb) cb(er) + }) + } + if (Object.setPrototypeOf) Object.setPrototypeOf(rename, fs$rename) + return rename + })(fs.rename) + } + + // if read() returns EAGAIN, then just try it again. + fs.read = typeof fs.read !== 'function' ? fs.read + : (function (fs$read) { + function read (fd, buffer, offset, length, position, callback_) { + var callback + if (callback_ && typeof callback_ === 'function') { + var eagCounter = 0 + callback = function (er, _, __) { + if (er && er.code === 'EAGAIN' && eagCounter < 10) { + eagCounter ++ + return fs$read.call(fs, fd, buffer, offset, length, position, callback) + } + callback_.apply(this, arguments) + } + } + return fs$read.call(fs, fd, buffer, offset, length, position, callback) + } + + // This ensures `util.promisify` works as it does for native `fs.read`. + if (Object.setPrototypeOf) Object.setPrototypeOf(read, fs$read) + return read + })(fs.read) + + fs.readSync = typeof fs.readSync !== 'function' ? fs.readSync + : (function (fs$readSync) { return function (fd, buffer, offset, length, position) { + var eagCounter = 0 + while (true) { + try { + return fs$readSync.call(fs, fd, buffer, offset, length, position) + } catch (er) { + if (er.code === 'EAGAIN' && eagCounter < 10) { + eagCounter ++ + continue + } + throw er + } + } + }})(fs.readSync) + + function patchLchmod (fs) { + fs.lchmod = function (path, mode, callback) { + fs.open( path + , constants.O_WRONLY | constants.O_SYMLINK + , mode + , function (err, fd) { + if (err) { + if (callback) callback(err) + return + } + // prefer to return the chmod error, if one occurs, + // but still try to close, and report closing errors if they occur. + fs.fchmod(fd, mode, function (err) { + fs.close(fd, function(err2) { + if (callback) callback(err || err2) + }) + }) + }) + } + + fs.lchmodSync = function (path, mode) { + var fd = fs.openSync(path, constants.O_WRONLY | constants.O_SYMLINK, mode) + + // prefer to return the chmod error, if one occurs, + // but still try to close, and report closing errors if they occur. + var threw = true + var ret + try { + ret = fs.fchmodSync(fd, mode) + threw = false + } finally { + if (threw) { + try { + fs.closeSync(fd) + } catch (er) {} + } else { + fs.closeSync(fd) + } + } + return ret + } + } + + function patchLutimes (fs) { + if (constants.hasOwnProperty("O_SYMLINK") && fs.futimes) { + fs.lutimes = function (path, at, mt, cb) { + fs.open(path, constants.O_SYMLINK, function (er, fd) { + if (er) { + if (cb) cb(er) + return + } + fs.futimes(fd, at, mt, function (er) { + fs.close(fd, function (er2) { + if (cb) cb(er || er2) + }) + }) + }) + } + + fs.lutimesSync = function (path, at, mt) { + var fd = fs.openSync(path, constants.O_SYMLINK) + var ret + var threw = true + try { + ret = fs.futimesSync(fd, at, mt) + threw = false + } finally { + if (threw) { + try { + fs.closeSync(fd) + } catch (er) {} + } else { + fs.closeSync(fd) + } + } + return ret + } + + } else if (fs.futimes) { + fs.lutimes = function (_a, _b, _c, cb) { if (cb) process.nextTick(cb) } + fs.lutimesSync = function () {} + } + } + + function chmodFix (orig) { + if (!orig) return orig + return function (target, mode, cb) { + return orig.call(fs, target, mode, function (er) { + if (chownErOk(er)) er = null + if (cb) cb.apply(this, arguments) + }) + } + } + + function chmodFixSync (orig) { + if (!orig) return orig + return function (target, mode) { + try { + return orig.call(fs, target, mode) + } catch (er) { + if (!chownErOk(er)) throw er + } + } + } + + + function chownFix (orig) { + if (!orig) return orig + return function (target, uid, gid, cb) { + return orig.call(fs, target, uid, gid, function (er) { + if (chownErOk(er)) er = null + if (cb) cb.apply(this, arguments) + }) + } + } + + function chownFixSync (orig) { + if (!orig) return orig + return function (target, uid, gid) { + try { + return orig.call(fs, target, uid, gid) + } catch (er) { + if (!chownErOk(er)) throw er + } + } + } + + function statFix (orig) { + if (!orig) return orig + // Older versions of Node erroneously returned signed integers for + // uid + gid. + return function (target, options, cb) { + if (typeof options === 'function') { + cb = options + options = null + } + function callback (er, stats) { + if (stats) { + if (stats.uid < 0) stats.uid += 0x100000000 + if (stats.gid < 0) stats.gid += 0x100000000 + } + if (cb) cb.apply(this, arguments) + } + return options ? orig.call(fs, target, options, callback) + : orig.call(fs, target, callback) + } + } + + function statFixSync (orig) { + if (!orig) return orig + // Older versions of Node erroneously returned signed integers for + // uid + gid. + return function (target, options) { + var stats = options ? orig.call(fs, target, options) + : orig.call(fs, target) + if (stats) { + if (stats.uid < 0) stats.uid += 0x100000000 + if (stats.gid < 0) stats.gid += 0x100000000 + } + return stats; + } + } + + // ENOSYS means that the fs doesn't support the op. Just ignore + // that, because it doesn't matter. + // + // if there's no getuid, or if getuid() is something other + // than 0, and the error is EINVAL or EPERM, then just ignore + // it. + // + // This specific case is a silent failure in cp, install, tar, + // and most other unix tools that manage permissions. + // + // When running as root, or if other types of errors are + // encountered, then it's strict. + function chownErOk (er) { + if (!er) + return true + + if (er.code === "ENOSYS") + return true + + var nonroot = !process.getuid || process.getuid() !== 0 + if (nonroot) { + if (er.code === "EINVAL" || er.code === "EPERM") + return true + } + + return false + } +} diff --git a/dg-ui/node_modules/is-extglob/LICENSE b/dg-ui/node_modules/is-extglob/LICENSE new file mode 100644 index 0000000..842218c --- /dev/null +++ b/dg-ui/node_modules/is-extglob/LICENSE @@ -0,0 +1,21 @@ +The MIT License (MIT) + +Copyright (c) 2014-2016, Jon Schlinkert + +Permission is hereby granted, free of charge, to any person obtaining a copy +of this software and associated documentation files (the "Software"), to deal +in the Software without restriction, including without limitation the rights +to use, copy, modify, merge, publish, distribute, sublicense, and/or sell +copies of the Software, and to permit persons to whom the Software is +furnished to do so, subject to the following conditions: + +The above copyright notice and this permission notice shall be included in +all copies or substantial portions of the Software. + +THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR +IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, +FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE +AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER +LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, +OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN +THE SOFTWARE. diff --git a/dg-ui/node_modules/is-extglob/README.md b/dg-ui/node_modules/is-extglob/README.md new file mode 100644 index 0000000..0416af5 --- /dev/null +++ b/dg-ui/node_modules/is-extglob/README.md @@ -0,0 +1,107 @@ +# is-extglob [![NPM version](https://img.shields.io/npm/v/is-extglob.svg?style=flat)](https://www.npmjs.com/package/is-extglob) [![NPM downloads](https://img.shields.io/npm/dm/is-extglob.svg?style=flat)](https://npmjs.org/package/is-extglob) [![Build Status](https://img.shields.io/travis/jonschlinkert/is-extglob.svg?style=flat)](https://travis-ci.org/jonschlinkert/is-extglob) + +> Returns true if a string has an extglob. + +## Install + +Install with [npm](https://www.npmjs.com/): + +```sh +$ npm install --save is-extglob +``` + +## Usage + +```js +var isExtglob = require('is-extglob'); +``` + +**True** + +```js +isExtglob('?(abc)'); +isExtglob('@(abc)'); +isExtglob('!(abc)'); +isExtglob('*(abc)'); +isExtglob('+(abc)'); +``` + +**False** + +Escaped extglobs: + +```js +isExtglob('\\?(abc)'); +isExtglob('\\@(abc)'); +isExtglob('\\!(abc)'); +isExtglob('\\*(abc)'); +isExtglob('\\+(abc)'); +``` + +Everything else... + +```js +isExtglob('foo.js'); +isExtglob('!foo.js'); +isExtglob('*.js'); +isExtglob('**/abc.js'); +isExtglob('abc/*.js'); +isExtglob('abc/(aaa|bbb).js'); +isExtglob('abc/[a-z].js'); +isExtglob('abc/{a,b}.js'); +isExtglob('abc/?.js'); +isExtglob('abc.js'); +isExtglob('abc/def/ghi.js'); +``` + +## History + +**v2.0** + +Adds support for escaping. Escaped exglobs no longer return true. + +## About + +### Related projects + +* [has-glob](https://www.npmjs.com/package/has-glob): Returns `true` if an array has a glob pattern. | [homepage](https://github.com/jonschlinkert/has-glob "Returns `true` if an array has a glob pattern.") +* [is-glob](https://www.npmjs.com/package/is-glob): Returns `true` if the given string looks like a glob pattern or an extglob pattern… [more](https://github.com/jonschlinkert/is-glob) | [homepage](https://github.com/jonschlinkert/is-glob "Returns `true` if the given string looks like a glob pattern or an extglob pattern. This makes it easy to create code that only uses external modules like node-glob when necessary, resulting in much faster code execution and initialization time, and a bet") +* [micromatch](https://www.npmjs.com/package/micromatch): Glob matching for javascript/node.js. A drop-in replacement and faster alternative to minimatch and multimatch. | [homepage](https://github.com/jonschlinkert/micromatch "Glob matching for javascript/node.js. A drop-in replacement and faster alternative to minimatch and multimatch.") + +### Contributing + +Pull requests and stars are always welcome. For bugs and feature requests, [please create an issue](../../issues/new). + +### Building docs + +_(This document was generated by [verb-generate-readme](https://github.com/verbose/verb-generate-readme) (a [verb](https://github.com/verbose/verb) generator), please don't edit the readme directly. Any changes to the readme must be made in [.verb.md](.verb.md).)_ + +To generate the readme and API documentation with [verb](https://github.com/verbose/verb): + +```sh +$ npm install -g verb verb-generate-readme && verb +``` + +### Running tests + +Install dev dependencies: + +```sh +$ npm install -d && npm test +``` + +### Author + +**Jon Schlinkert** + +* [github/jonschlinkert](https://github.com/jonschlinkert) +* [twitter/jonschlinkert](http://twitter.com/jonschlinkert) + +### License + +Copyright © 2016, [Jon Schlinkert](https://github.com/jonschlinkert). +Released under the [MIT license](https://github.com/jonschlinkert/is-extglob/blob/master/LICENSE). + +*** + +_This file was generated by [verb-generate-readme](https://github.com/verbose/verb-generate-readme), v0.1.31, on October 12, 2016._ \ No newline at end of file diff --git a/dg-ui/node_modules/is-extglob/index.js b/dg-ui/node_modules/is-extglob/index.js new file mode 100644 index 0000000..c1d986f --- /dev/null +++ b/dg-ui/node_modules/is-extglob/index.js @@ -0,0 +1,20 @@ +/*! + * is-extglob + * + * Copyright (c) 2014-2016, Jon Schlinkert. + * Licensed under the MIT License. + */ + +module.exports = function isExtglob(str) { + if (typeof str !== 'string' || str === '') { + return false; + } + + var match; + while ((match = /(\\).|([@?!+*]\(.*\))/g.exec(str))) { + if (match[2]) return true; + str = str.slice(match.index + match[0].length); + } + + return false; +}; diff --git a/dg-ui/node_modules/is-extglob/package.json b/dg-ui/node_modules/is-extglob/package.json new file mode 100644 index 0000000..7a90836 --- /dev/null +++ b/dg-ui/node_modules/is-extglob/package.json @@ -0,0 +1,69 @@ +{ + "name": "is-extglob", + "description": "Returns true if a string has an extglob.", + "version": "2.1.1", + "homepage": "https://github.com/jonschlinkert/is-extglob", + "author": "Jon Schlinkert (https://github.com/jonschlinkert)", + "repository": "jonschlinkert/is-extglob", + "bugs": { + "url": "https://github.com/jonschlinkert/is-extglob/issues" + }, + "license": "MIT", + "files": [ + "index.js" + ], + "main": "index.js", + "engines": { + "node": ">=0.10.0" + }, + "scripts": { + "test": "mocha" + }, + "devDependencies": { + "gulp-format-md": "^0.1.10", + "mocha": "^3.0.2" + }, + "keywords": [ + "bash", + "braces", + "check", + "exec", + "expression", + "extglob", + "glob", + "globbing", + "globstar", + "is", + "match", + "matches", + "pattern", + "regex", + "regular", + "string", + "test" + ], + "verb": { + "toc": false, + "layout": "default", + "tasks": [ + "readme" + ], + "plugins": [ + "gulp-format-md" + ], + "related": { + "list": [ + "has-glob", + "is-glob", + "micromatch" + ] + }, + "reflinks": [ + "verb", + "verb-generate-readme" + ], + "lint": { + "reflinks": true + } + } +} diff --git a/dg-ui/node_modules/is-glob/LICENSE b/dg-ui/node_modules/is-glob/LICENSE new file mode 100644 index 0000000..3f2eca1 --- /dev/null +++ b/dg-ui/node_modules/is-glob/LICENSE @@ -0,0 +1,21 @@ +The MIT License (MIT) + +Copyright (c) 2014-2017, Jon Schlinkert. + +Permission is hereby granted, free of charge, to any person obtaining a copy +of this software and associated documentation files (the "Software"), to deal +in the Software without restriction, including without limitation the rights +to use, copy, modify, merge, publish, distribute, sublicense, and/or sell +copies of the Software, and to permit persons to whom the Software is +furnished to do so, subject to the following conditions: + +The above copyright notice and this permission notice shall be included in +all copies or substantial portions of the Software. + +THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR +IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, +FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE +AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER +LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, +OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN +THE SOFTWARE. diff --git a/dg-ui/node_modules/is-glob/README.md b/dg-ui/node_modules/is-glob/README.md new file mode 100644 index 0000000..740724b --- /dev/null +++ b/dg-ui/node_modules/is-glob/README.md @@ -0,0 +1,206 @@ +# is-glob [![NPM version](https://img.shields.io/npm/v/is-glob.svg?style=flat)](https://www.npmjs.com/package/is-glob) [![NPM monthly downloads](https://img.shields.io/npm/dm/is-glob.svg?style=flat)](https://npmjs.org/package/is-glob) [![NPM total downloads](https://img.shields.io/npm/dt/is-glob.svg?style=flat)](https://npmjs.org/package/is-glob) [![Build Status](https://img.shields.io/github/workflow/status/micromatch/is-glob/dev)](https://github.com/micromatch/is-glob/actions) + +> Returns `true` if the given string looks like a glob pattern or an extglob pattern. This makes it easy to create code that only uses external modules like node-glob when necessary, resulting in much faster code execution and initialization time, and a better user experience. + +Please consider following this project's author, [Jon Schlinkert](https://github.com/jonschlinkert), and consider starring the project to show your :heart: and support. + +## Install + +Install with [npm](https://www.npmjs.com/): + +```sh +$ npm install --save is-glob +``` + +You might also be interested in [is-valid-glob](https://github.com/jonschlinkert/is-valid-glob) and [has-glob](https://github.com/jonschlinkert/has-glob). + +## Usage + +```js +var isGlob = require('is-glob'); +``` + +### Default behavior + +**True** + +Patterns that have glob characters or regex patterns will return `true`: + +```js +isGlob('!foo.js'); +isGlob('*.js'); +isGlob('**/abc.js'); +isGlob('abc/*.js'); +isGlob('abc/(aaa|bbb).js'); +isGlob('abc/[a-z].js'); +isGlob('abc/{a,b}.js'); +//=> true +``` + +Extglobs + +```js +isGlob('abc/@(a).js'); +isGlob('abc/!(a).js'); +isGlob('abc/+(a).js'); +isGlob('abc/*(a).js'); +isGlob('abc/?(a).js'); +//=> true +``` + +**False** + +Escaped globs or extglobs return `false`: + +```js +isGlob('abc/\\@(a).js'); +isGlob('abc/\\!(a).js'); +isGlob('abc/\\+(a).js'); +isGlob('abc/\\*(a).js'); +isGlob('abc/\\?(a).js'); +isGlob('\\!foo.js'); +isGlob('\\*.js'); +isGlob('\\*\\*/abc.js'); +isGlob('abc/\\*.js'); +isGlob('abc/\\(aaa|bbb).js'); +isGlob('abc/\\[a-z].js'); +isGlob('abc/\\{a,b}.js'); +//=> false +``` + +Patterns that do not have glob patterns return `false`: + +```js +isGlob('abc.js'); +isGlob('abc/def/ghi.js'); +isGlob('foo.js'); +isGlob('abc/@.js'); +isGlob('abc/+.js'); +isGlob('abc/?.js'); +isGlob(); +isGlob(null); +//=> false +``` + +Arrays are also `false` (If you want to check if an array has a glob pattern, use [has-glob](https://github.com/jonschlinkert/has-glob)): + +```js +isGlob(['**/*.js']); +isGlob(['foo.js']); +//=> false +``` + +### Option strict + +When `options.strict === false` the behavior is less strict in determining if a pattern is a glob. Meaning that +some patterns that would return `false` may return `true`. This is done so that matching libraries like [micromatch](https://github.com/micromatch/micromatch) have a chance at determining if the pattern is a glob or not. + +**True** + +Patterns that have glob characters or regex patterns will return `true`: + +```js +isGlob('!foo.js', {strict: false}); +isGlob('*.js', {strict: false}); +isGlob('**/abc.js', {strict: false}); +isGlob('abc/*.js', {strict: false}); +isGlob('abc/(aaa|bbb).js', {strict: false}); +isGlob('abc/[a-z].js', {strict: false}); +isGlob('abc/{a,b}.js', {strict: false}); +//=> true +``` + +Extglobs + +```js +isGlob('abc/@(a).js', {strict: false}); +isGlob('abc/!(a).js', {strict: false}); +isGlob('abc/+(a).js', {strict: false}); +isGlob('abc/*(a).js', {strict: false}); +isGlob('abc/?(a).js', {strict: false}); +//=> true +``` + +**False** + +Escaped globs or extglobs return `false`: + +```js +isGlob('\\!foo.js', {strict: false}); +isGlob('\\*.js', {strict: false}); +isGlob('\\*\\*/abc.js', {strict: false}); +isGlob('abc/\\*.js', {strict: false}); +isGlob('abc/\\(aaa|bbb).js', {strict: false}); +isGlob('abc/\\[a-z].js', {strict: false}); +isGlob('abc/\\{a,b}.js', {strict: false}); +//=> false +``` + +## About + +
+Contributing + +Pull requests and stars are always welcome. For bugs and feature requests, [please create an issue](../../issues/new). + +
+ +
+Running Tests + +Running and reviewing unit tests is a great way to get familiarized with a library and its API. You can install dependencies and run tests with the following command: + +```sh +$ npm install && npm test +``` + +
+ +
+Building docs + +_(This project's readme.md is generated by [verb](https://github.com/verbose/verb-generate-readme), please don't edit the readme directly. Any changes to the readme must be made in the [.verb.md](.verb.md) readme template.)_ + +To generate the readme, run the following command: + +```sh +$ npm install -g verbose/verb#dev verb-generate-readme && verb +``` + +
+ +### Related projects + +You might also be interested in these projects: + +* [assemble](https://www.npmjs.com/package/assemble): Get the rocks out of your socks! Assemble makes you fast at creating web projects… [more](https://github.com/assemble/assemble) | [homepage](https://github.com/assemble/assemble "Get the rocks out of your socks! Assemble makes you fast at creating web projects. Assemble is used by thousands of projects for rapid prototyping, creating themes, scaffolds, boilerplates, e-books, UI components, API documentation, blogs, building websit") +* [base](https://www.npmjs.com/package/base): Framework for rapidly creating high quality, server-side node.js applications, using plugins like building blocks | [homepage](https://github.com/node-base/base "Framework for rapidly creating high quality, server-side node.js applications, using plugins like building blocks") +* [update](https://www.npmjs.com/package/update): Be scalable! Update is a new, open source developer framework and CLI for automating updates… [more](https://github.com/update/update) | [homepage](https://github.com/update/update "Be scalable! Update is a new, open source developer framework and CLI for automating updates of any kind in code projects.") +* [verb](https://www.npmjs.com/package/verb): Documentation generator for GitHub projects. Verb is extremely powerful, easy to use, and is used… [more](https://github.com/verbose/verb) | [homepage](https://github.com/verbose/verb "Documentation generator for GitHub projects. Verb is extremely powerful, easy to use, and is used on hundreds of projects of all sizes to generate everything from API docs to readmes.") + +### Contributors + +| **Commits** | **Contributor** | +| --- | --- | +| 47 | [jonschlinkert](https://github.com/jonschlinkert) | +| 5 | [doowb](https://github.com/doowb) | +| 1 | [phated](https://github.com/phated) | +| 1 | [danhper](https://github.com/danhper) | +| 1 | [paulmillr](https://github.com/paulmillr) | + +### Author + +**Jon Schlinkert** + +* [GitHub Profile](https://github.com/jonschlinkert) +* [Twitter Profile](https://twitter.com/jonschlinkert) +* [LinkedIn Profile](https://linkedin.com/in/jonschlinkert) + +### License + +Copyright © 2019, [Jon Schlinkert](https://github.com/jonschlinkert). +Released under the [MIT License](LICENSE). + +*** + +_This file was generated by [verb-generate-readme](https://github.com/verbose/verb-generate-readme), v0.8.0, on March 27, 2019._ \ No newline at end of file diff --git a/dg-ui/node_modules/is-glob/index.js b/dg-ui/node_modules/is-glob/index.js new file mode 100644 index 0000000..620f563 --- /dev/null +++ b/dg-ui/node_modules/is-glob/index.js @@ -0,0 +1,150 @@ +/*! + * is-glob + * + * Copyright (c) 2014-2017, Jon Schlinkert. + * Released under the MIT License. + */ + +var isExtglob = require('is-extglob'); +var chars = { '{': '}', '(': ')', '[': ']'}; +var strictCheck = function(str) { + if (str[0] === '!') { + return true; + } + var index = 0; + var pipeIndex = -2; + var closeSquareIndex = -2; + var closeCurlyIndex = -2; + var closeParenIndex = -2; + var backSlashIndex = -2; + while (index < str.length) { + if (str[index] === '*') { + return true; + } + + if (str[index + 1] === '?' && /[\].+)]/.test(str[index])) { + return true; + } + + if (closeSquareIndex !== -1 && str[index] === '[' && str[index + 1] !== ']') { + if (closeSquareIndex < index) { + closeSquareIndex = str.indexOf(']', index); + } + if (closeSquareIndex > index) { + if (backSlashIndex === -1 || backSlashIndex > closeSquareIndex) { + return true; + } + backSlashIndex = str.indexOf('\\', index); + if (backSlashIndex === -1 || backSlashIndex > closeSquareIndex) { + return true; + } + } + } + + if (closeCurlyIndex !== -1 && str[index] === '{' && str[index + 1] !== '}') { + closeCurlyIndex = str.indexOf('}', index); + if (closeCurlyIndex > index) { + backSlashIndex = str.indexOf('\\', index); + if (backSlashIndex === -1 || backSlashIndex > closeCurlyIndex) { + return true; + } + } + } + + if (closeParenIndex !== -1 && str[index] === '(' && str[index + 1] === '?' && /[:!=]/.test(str[index + 2]) && str[index + 3] !== ')') { + closeParenIndex = str.indexOf(')', index); + if (closeParenIndex > index) { + backSlashIndex = str.indexOf('\\', index); + if (backSlashIndex === -1 || backSlashIndex > closeParenIndex) { + return true; + } + } + } + + if (pipeIndex !== -1 && str[index] === '(' && str[index + 1] !== '|') { + if (pipeIndex < index) { + pipeIndex = str.indexOf('|', index); + } + if (pipeIndex !== -1 && str[pipeIndex + 1] !== ')') { + closeParenIndex = str.indexOf(')', pipeIndex); + if (closeParenIndex > pipeIndex) { + backSlashIndex = str.indexOf('\\', pipeIndex); + if (backSlashIndex === -1 || backSlashIndex > closeParenIndex) { + return true; + } + } + } + } + + if (str[index] === '\\') { + var open = str[index + 1]; + index += 2; + var close = chars[open]; + + if (close) { + var n = str.indexOf(close, index); + if (n !== -1) { + index = n + 1; + } + } + + if (str[index] === '!') { + return true; + } + } else { + index++; + } + } + return false; +}; + +var relaxedCheck = function(str) { + if (str[0] === '!') { + return true; + } + var index = 0; + while (index < str.length) { + if (/[*?{}()[\]]/.test(str[index])) { + return true; + } + + if (str[index] === '\\') { + var open = str[index + 1]; + index += 2; + var close = chars[open]; + + if (close) { + var n = str.indexOf(close, index); + if (n !== -1) { + index = n + 1; + } + } + + if (str[index] === '!') { + return true; + } + } else { + index++; + } + } + return false; +}; + +module.exports = function isGlob(str, options) { + if (typeof str !== 'string' || str === '') { + return false; + } + + if (isExtglob(str)) { + return true; + } + + var check = strictCheck; + + // optionally relax check + if (options && options.strict === false) { + check = relaxedCheck; + } + + return check(str); +}; diff --git a/dg-ui/node_modules/is-glob/package.json b/dg-ui/node_modules/is-glob/package.json new file mode 100644 index 0000000..858af03 --- /dev/null +++ b/dg-ui/node_modules/is-glob/package.json @@ -0,0 +1,81 @@ +{ + "name": "is-glob", + "description": "Returns `true` if the given string looks like a glob pattern or an extglob pattern. This makes it easy to create code that only uses external modules like node-glob when necessary, resulting in much faster code execution and initialization time, and a better user experience.", + "version": "4.0.3", + "homepage": "https://github.com/micromatch/is-glob", + "author": "Jon Schlinkert (https://github.com/jonschlinkert)", + "contributors": [ + "Brian Woodward (https://twitter.com/doowb)", + "Daniel Perez (https://tuvistavie.com)", + "Jon Schlinkert (http://twitter.com/jonschlinkert)" + ], + "repository": "micromatch/is-glob", + "bugs": { + "url": "https://github.com/micromatch/is-glob/issues" + }, + "license": "MIT", + "files": [ + "index.js" + ], + "main": "index.js", + "engines": { + "node": ">=0.10.0" + }, + "scripts": { + "test": "mocha && node benchmark.js" + }, + "dependencies": { + "is-extglob": "^2.1.1" + }, + "devDependencies": { + "gulp-format-md": "^0.1.10", + "mocha": "^3.0.2" + }, + "keywords": [ + "bash", + "braces", + "check", + "exec", + "expression", + "extglob", + "glob", + "globbing", + "globstar", + "is", + "match", + "matches", + "pattern", + "regex", + "regular", + "string", + "test" + ], + "verb": { + "layout": "default", + "plugins": [ + "gulp-format-md" + ], + "related": { + "list": [ + "assemble", + "base", + "update", + "verb" + ] + }, + "reflinks": [ + "assemble", + "bach", + "base", + "composer", + "gulp", + "has-glob", + "is-valid-glob", + "micromatch", + "npm", + "scaffold", + "verb", + "vinyl" + ] + } +} diff --git a/dg-ui/node_modules/jiti/LICENSE b/dg-ui/node_modules/jiti/LICENSE new file mode 100644 index 0000000..e739abc --- /dev/null +++ b/dg-ui/node_modules/jiti/LICENSE @@ -0,0 +1,21 @@ +MIT License + +Copyright (c) Pooya Parsa + +Permission is hereby granted, free of charge, to any person obtaining a copy +of this software and associated documentation files (the "Software"), to deal +in the Software without restriction, including without limitation the rights +to use, copy, modify, merge, publish, distribute, sublicense, and/or sell +copies of the Software, and to permit persons to whom the Software is +furnished to do so, subject to the following conditions: + +The above copyright notice and this permission notice shall be included in all +copies or substantial portions of the Software. + +THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR +IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, +FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE +AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER +LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, +OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE +SOFTWARE. diff --git a/dg-ui/node_modules/jiti/README.md b/dg-ui/node_modules/jiti/README.md new file mode 100644 index 0000000..b3af483 --- /dev/null +++ b/dg-ui/node_modules/jiti/README.md @@ -0,0 +1,258 @@ +# jiti + + + +[![npm version](https://img.shields.io/npm/v/jiti?color=F0DB4F)](https://npmjs.com/package/jiti) +[![npm downloads](https://img.shields.io/npm/dm/jiti?color=F0DB4F)](https://npmjs.com/package/jiti) +[![bundle size](https://img.shields.io/bundlephobia/minzip/jiti?color=F0DB4F)](https://bundlephobia.com/package/jiti) + + + +> This is the active development branch. Check out [jiti/v1](https://github.com/unjs/jiti/tree/v1) for legacy v1 docs and code. + +## 🌟 Used in + +[Docusaurus](https://docusaurus.io/), [ESLint](https://github.com/eslint/eslint), [FormKit](https://formkit.com/), [Histoire](https://histoire.dev/), [Knip](https://knip.dev/), [Nitro](https://nitro.unjs.io/), [Nuxt](https://nuxt.com/), [PostCSS loader](https://github.com/webpack-contrib/postcss-loader), [Rsbuild](https://rsbuild.dev/), [Size Limit](https://github.com/ai/size-limit), [Slidev](https://sli.dev/), [Tailwindcss](https://tailwindcss.com/), [Tokenami](https://github.com/tokenami/tokenami), [UnoCSS](https://unocss.dev/), [WXT](https://wxt.dev/), [Winglang](https://www.winglang.io/), [Graphql code generator](https://the-guild.dev/graphql/codegen), [Lingui](https://lingui.dev/), [Scaffdog](https://scaff.dog/), [Storybook](https://storybook.js.org), [...UnJS ecosystem](https://unjs.io/), [...60M+ npm monthly downloads](https://npm.chart.dev/jiti), [...6M+ public repositories](https://github.com/unjs/jiti/network/dependents). + +## ✅ Features + +- Seamless TypeScript and ESM syntax support for Node.js +- Seamless interoperability between ESM and CommonJS +- Asynchronous API to replace `import()` +- Synchronous API to replace `require()` (deprecated) +- Super slim and zero dependency +- Custom resolve aliases +- Smart syntax detection to avoid extra transforms +- Node.js native `require.cache` integration +- Filesystem transpile with hard disk caches +- ESM Loader support +- JSX support (opt-in) + +> [!IMPORTANT] +> To enhance compatibility, jiti `>=2.1` enabled [`interopDefault`](#interopdefault) using a new Proxy method. If you migrated to `2.0.0` earlier, this might have caused behavior changes. In case of any issues during the upgrade, please [report](https://github.com/unjs/jiti/issues) so we can investigate to solve them. 🙏🏼 + +## 💡 Usage + +### CLI + +You can use `jiti` CLI to quickly run any script with TypeScript and native ESM support! + +```bash +npx jiti ./index.ts +``` + +### Programmatic + +Initialize a jiti instance: + +```js +// ESM +import { createJiti } from "jiti"; +const jiti = createJiti(import.meta.url); + +// CommonJS (deprecated) +const { createJiti } = require("jiti"); +const jiti = createJiti(__filename); +``` + +Import (async) and resolve with ESM compatibility: + +```js +// jiti.import(id) is similar to import(id) +const mod = await jiti.import("./path/to/file.ts"); + +// jiti.esmResolve(id) is similar to import.meta.resolve(id) +const resolvedPath = jiti.esmResolve("./src"); +``` + +If you need the default export of module, you can use `jiti.import(id, { default: true })` as shortcut to `mod?.default ?? mod`. + +```js +// shortcut to mod?.default ?? mod +const modDefault = await jiti.import("./path/to/file.ts", { default: true }); +``` + +CommonJS (sync & deprecated): + +```js +// jiti() is similar to require(id) +const mod = jiti("./path/to/file.ts"); + +// jiti.resolve() is similar to require.resolve(id) +const resolvedPath = jiti.resolve("./src"); +``` + +You can also pass options as the second argument: + +```js +const jiti = createJiti(import.meta.url, { debug: true }); +``` + +### Register global ESM loader + +You can globally register jiti using [global hooks](https://nodejs.org/api/module.html#initialize). (Important: Requires Node.js > 20) + +```js +import "jiti/register"; +``` + +Or: + +```bash +node --import jiti/register index.ts +``` + +## 🎈 `jiti/native` + +You can alias `jiti` to `jiti/native` to directly depend on runtime's [`import.meta.resolve`](https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Operators/import.meta/resolve) and dynamic [`import()`](https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Operators/import) support. This allows easing up the ecosystem transition to runtime native support by giving the same API of jiti. + +## ⚙️ Options + +### `debug` + +- Type: Boolean +- Default: `false` +- Environment variable: `JITI_DEBUG` + +Enable verbose logging. You can use `JITI_DEBUG=1 ` to enable it. + +### `fsCache` + +- Type: Boolean | String +- Default: `true` +- Environment variable: `JITI_FS_CACHE` + +Filesystem source cache (enabled by default) + +By default (when is `true`), jiti uses `node_modules/.cache/jiti` (if exists) or `{TMP_DIR}/jiti`. + +**Note:** It is recommended that this option be enabled for better performance. + +### `rebuildFsCache` + +- Type: Boolean +- Default: `false` +- Environment variable: `JITI_REBUILD_FS_CACHE` + +Rebuild filesystem source cache created by `fsCache`. + +### `moduleCache` + +- Type: String +- Default: `true` +- Environment variable: `JITI_MODULE_CACHE` + +Runtime module cache (enabled by default). + +Disabling allows editing code and importing the same module multiple times. + +When enabled, jiti integrates with Node.js native CommonJS cache-store. + +### `transform` + +- Type: Function +- Default: Babel (lazy loaded) + +Transform function. See [src/babel](./src/babel.ts) for more details + +### `sourceMaps` + +- Type: Boolean +- Default `false` +- Environment variable: `JITI_SOURCE_MAPS` + +Add inline source map to transformed source for better debugging. + +### `interopDefault` + +- Type: Boolean +- Default: `true` +- Environment variable: `JITI_INTEROP_DEFAULT` + +Jiti combines module exports with the `default` export using an internal Proxy to improve compatibility with mixed CJS/ESM usage. You can check the current implementation [here](https://github.com/unjs/jiti/blob/main/src/utils.ts#L105). + +> [!WARNING] +> This option wraps **all imported modules** in a Proxy, which adds ~25-50ns overhead per property access. For performance-critical hot paths where you access module exports very frequently, consider setting `interopDefault: false` or `JITI_INTEROP_DEFAULT=false`. + +### `alias` + +- Type: Object +- Default: - +- Environment variable: `JITI_ALIAS` + +You can also pass an object to the environment variable for inline config. Example: `JITI_ALIAS='{"~/*": "./src/*"}' jiti ...`. + +Custom alias map used to resolve IDs. + +### `tsconfigPaths` + +- Type: Boolean | String +- Default: `false` +- Environment variable: `JITI_TSCONFIG_PATHS` + +Enable TypeScript [`paths`](https://www.typescriptlang.org/tsconfig/#paths) resolution using [`get-tsconfig`](https://github.com/privatenumber/get-tsconfig). + +- `true`: Auto-discover `tsconfig.json` by walking up from the jiti instance's parent path. +- `string`: Explicit path to a `tsconfig.json` file. +- `false` (default): Disabled. + +### `nativeModules` + +- Type: Array +- Default: ['typescript'] +- Environment variable: `JITI_NATIVE_MODULES` + +List of modules (within `node_modules`) to always use native `require()` for them. + +### `transformModules` + +- Type: Array +- Default: [] +- Environment variable: `JITI_TRANSFORM_MODULES` + +List of modules (within `node_modules`) to transform them regardless of syntax. + +### `importMeta` + +Parent module's [`import.meta`](https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Operators/import.meta) context to use for ESM resolution. (only used for `jiti/native` import). + +### `tryNative` + +- Type: Boolean +- Default: Enabled if bun is detected +- Environment variable: `JITI_TRY_NATIVE` + +Try to use native require and import without jiti transformations first. + +### `jsx` + +- Type: Boolean | {options} +- Default: `false` +- Environment Variable: `JITI_JSX` + +Enable JSX support using [`@babel/plugin-transform-react-jsx`](https://babeljs.io/docs/babel-plugin-transform-react-jsx). + +See [`test/fixtures/jsx`](./test/fixtures/jsx) for framework integration examples. + +## Development + +- Clone this repository +- Enable [Corepack](https://github.com/nodejs/corepack) using `corepack enable` +- Install dependencies using `pnpm install` +- Run `pnpm dev` +- Run `pnpm jiti ./test/path/to/file.ts` + +## License + + + +Published under the [MIT](https://github.com/unjs/jiti/blob/main/LICENSE) license. +Made by [@pi0](https://github.com/pi0) and [community](https://github.com/unjs/jiti/graphs/contributors) 💛 +

+ + + + + + + diff --git a/dg-ui/node_modules/jiti/dist/babel.cjs b/dg-ui/node_modules/jiti/dist/babel.cjs new file mode 100644 index 0000000..1e6b684 --- /dev/null +++ b/dg-ui/node_modules/jiti/dist/babel.cjs @@ -0,0 +1,257 @@ +(()=>{var e={"./node_modules/.pnpm/@babel+core@7.29.0/node_modules/@babel/core/lib/config/files lazy recursive"(e){function webpackEmptyAsyncContext(e){return Promise.resolve().then(function(){var t=new Error("Cannot find module '"+e+"'");throw t.code="MODULE_NOT_FOUND",t})}webpackEmptyAsyncContext.keys=()=>[],webpackEmptyAsyncContext.resolve=webpackEmptyAsyncContext,webpackEmptyAsyncContext.id="./node_modules/.pnpm/@babel+core@7.29.0/node_modules/@babel/core/lib/config/files lazy recursive",e.exports=webpackEmptyAsyncContext},"./node_modules/.pnpm/@babel+core@7.29.0/node_modules/@babel/core/lib/config/files sync recursive"(e){function webpackEmptyContext(e){var t=new Error("Cannot find module '"+e+"'");throw t.code="MODULE_NOT_FOUND",t}webpackEmptyContext.keys=()=>[],webpackEmptyContext.resolve=webpackEmptyContext,webpackEmptyContext.id="./node_modules/.pnpm/@babel+core@7.29.0/node_modules/@babel/core/lib/config/files sync recursive",e.exports=webpackEmptyContext},"./node_modules/.pnpm/@babel+plugin-syntax-class-properties@7.12.13_@babel+core@7.29.0/node_modules/@babel/plugin-syntax-class-properties/lib/index.js"(e,t,r){"use strict";t.A=void 0;var n=(0,r("./node_modules/.pnpm/@babel+helper-plugin-utils@7.28.6/node_modules/@babel/helper-plugin-utils/lib/index.js").declare)(e=>(e.assertVersion(7),{name:"syntax-class-properties",manipulateOptions(e,t){t.plugins.push("classProperties","classPrivateProperties","classPrivateMethods")}}));t.A=n},"./node_modules/.pnpm/@jridgewell+gen-mapping@0.3.13/node_modules/@jridgewell/gen-mapping/dist/gen-mapping.umd.js"(e,t,r){var n;!function(e,t,r){"use strict";var n=Object.create,s=Object.defineProperty,i=Object.getOwnPropertyDescriptor,o=Object.getOwnPropertyNames,a=Object.getPrototypeOf,l=Object.prototype.hasOwnProperty,__commonJS=(e,t)=>function(){return t||(0,e[o(e)[0]])((t={exports:{}}).exports,t),t.exports},__export=(e,t)=>{for(var r in t)s(e,r,{get:t[r],enumerable:!0})},__copyProps=(e,t,r,n)=>{if(t&&"object"==typeof t||"function"==typeof t)for(let a of o(t))l.call(e,a)||a===r||s(e,a,{get:()=>t[a],enumerable:!(n=i(t,a))||n.enumerable});return e},__toESM=(e,t,r)=>(r=null!=e?n(a(e)):{},__copyProps(!t&&e&&e.__esModule?r:s(r,"default",{value:e,enumerable:!0}),e)),__toCommonJS=e=>__copyProps(s({},"__esModule",{value:!0}),e),p=__commonJS({"umd:@jridgewell/sourcemap-codec"(e,r){r.exports=t}}),c=__commonJS({"umd:@jridgewell/trace-mapping"(e,t){t.exports=r}}),u={};__export(u,{GenMapping:()=>E,addMapping:()=>addMapping,addSegment:()=>addSegment,allMappings:()=>allMappings,fromMap:()=>fromMap,maybeAddMapping:()=>maybeAddMapping,maybeAddSegment:()=>maybeAddSegment,setIgnore:()=>setIgnore,setSourceContent:()=>setSourceContent,toDecodedMap:()=>toDecodedMap,toEncodedMap:()=>toEncodedMap}),e.exports=__toCommonJS(u);var d=class{constructor(){this._indexes={__proto__:null},this.array=[]}};function cast(e){return e}function get(e,t){return cast(e)._indexes[t]}function put(e,t){const r=get(e,t);if(void 0!==r)return r;const{array:n,_indexes:s}=cast(e),i=n.push(t);return s[t]=i-1}function remove(e,t){const r=get(e,t);if(void 0===r)return;const{array:n,_indexes:s}=cast(e);for(let e=r+1;eaddSegmentInternal(!0,e,t,r,n,s,i,o,a),maybeAddMapping=(e,t)=>addMappingInternal(!0,e,t);function setSourceContent(e,t,r){const{_sources:n,_sourcesContent:s}=cast2(e);s[put(n,t)]=r}function setIgnore(e,t,r=!0){const{_sources:n,_sourcesContent:s,_ignoreList:i}=cast2(e),o=put(n,t);o===s.length&&(s[o]=null),r?put(i,o):remove(i,o)}function toDecodedMap(e){const{_mappings:t,_sources:r,_sourcesContent:n,_names:s,_ignoreList:i}=cast2(e);return removeEmptyFinalLines(t),{version:3,file:e.file||void 0,names:s.array,sourceRoot:e.sourceRoot||void 0,sources:r.array,sourcesContent:n,mappings:t,ignoreList:i.array}}function toEncodedMap(e){const t=toDecodedMap(e);return Object.assign({},t,{mappings:(0,h.encode)(t.mappings)})}function fromMap(e){const t=new m.TraceMap(e),r=new E({file:t.file,sourceRoot:t.sourceRoot});return putAll(cast2(r)._names,t.names),putAll(cast2(r)._sources,t.sources),cast2(r)._sourcesContent=t.sourcesContent||t.sources.map(()=>null),cast2(r)._mappings=(0,m.decodedMappings)(t),t.ignoreList&&putAll(cast2(r)._ignoreList,t.ignoreList),r}function allMappings(e){const t=[],{_mappings:r,_sources:n,_names:s}=cast2(e);for(let e=0;e=0&&!(t>=e[n][f]);r=n--);return r}function insert(e,t,r){for(let r=e.length;r>t;r--)e[r]=e[r-1];e[t]=r}function removeEmptyFinalLines(e){const{length:t}=e;let r=t;for(let t=r-1;t>=0&&!(e[t].length>0);r=t,t--);rfunction(){return t||(0,e[o(e)[0]])((t={exports:{}}).exports,t),t.exports},__export=(e,t)=>{for(var r in t)s(e,r,{get:t[r],enumerable:!0})},__copyProps=(e,t,r,n)=>{if(t&&"object"==typeof t||"function"==typeof t)for(let a of o(t))l.call(e,a)||a===r||s(e,a,{get:()=>t[a],enumerable:!(n=i(t,a))||n.enumerable});return e},__toESM=(e,t,r)=>(r=null!=e?n(a(e)):{},__copyProps(!t&&e&&e.__esModule?r:s(r,"default",{value:e,enumerable:!0}),e)),__toCommonJS=e=>__copyProps(s({},"__esModule",{value:!0}),e),p=__commonJS({"umd:@jridgewell/trace-mapping"(e,t){t.exports=r}}),c=__commonJS({"umd:@jridgewell/gen-mapping"(e,r){r.exports=t}}),u={};__export(u,{default:()=>remapping}),e.exports=__toCommonJS(u);var d=__toESM(p()),h=__toESM(c()),m=__toESM(p()),f=SegmentObject("",-1,-1,"",null,!1),y=[];function SegmentObject(e,t,r,n,s,i){return{source:e,line:t,column:r,name:n,content:s,ignore:i}}function Source(e,t,r,n,s){return{map:e,sources:t,source:r,content:n,ignore:s}}function MapSource(e,t){return Source(e,t,"",null,!1)}function OriginalSource(e,t,r){return Source(null,y,e,t,r)}function traceMappings(e){const t=new h.GenMapping({file:e.map.file}),{sources:r,map:n}=e,s=n.names,i=(0,m.decodedMappings)(n);for(let e=0;enew d.TraceMap(e,"")),n=r.pop();for(let e=0;e1)throw new Error(`Transformation map ${e} must have exactly one source file.\nDid you specify these with the most recent transformation maps first?`);let s=build(n,t,"",0);for(let e=r.length-1;e>=0;e--)s=MapSource(r[e],[s]);return s}function build(e,t,r,n){const{resolvedSources:s,sourcesContent:i,ignoreList:o}=e,a=n+1;return MapSource(e,s.map((e,n)=>{const s={importer:r,depth:a,source:e||"",content:void 0,ignore:void 0},l=t(s.source,s),{source:p,content:c,ignore:u}=s;return l?build(new d.TraceMap(l,p),t,p,a):OriginalSource(p,void 0!==c?c:i?i[n]:null,void 0!==u?u:!!o&&o.includes(n))}))}var b=__toESM(c()),g=class{constructor(e,t){const r=t.decodedMappings?(0,b.toDecodedMap)(e):(0,b.toEncodedMap)(e);this.version=r.version,this.file=r.file,this.mappings=r.mappings,this.names=r.names,this.ignoreList=r.ignoreList,this.sourceRoot=r.sourceRoot,this.sources=r.sources,t.excludeContent||(this.sourcesContent=r.sourcesContent)}toString(){return JSON.stringify(this)}};function remapping(e,t,r){const n="object"==typeof r?r:{excludeContent:!!r,decodedMappings:!1},s=buildSourceMapTree(e,t);return new g(traceMappings(s),n)}}(e=r.nmd(e),r("./node_modules/.pnpm/@jridgewell+gen-mapping@0.3.13/node_modules/@jridgewell/gen-mapping/dist/gen-mapping.umd.js"),r("./node_modules/.pnpm/@jridgewell+trace-mapping@0.3.31/node_modules/@jridgewell/trace-mapping/dist/trace-mapping.umd.js")),e.exports="default"in(n=e).exports?n.exports.default:n.exports},"./node_modules/.pnpm/@jridgewell+resolve-uri@3.1.2/node_modules/@jridgewell/resolve-uri/dist/resolve-uri.umd.js"(e){e.exports=function(){"use strict";const e=/^[\w+.-]+:\/\//,t=/^([\w+.-]+:)\/\/([^@/#?]*@)?([^:/#?]*)(:\d+)?(\/[^#?]*)?(\?[^#]*)?(#.*)?/,r=/^file:(?:\/\/((?![a-z]:)[^/#?]*)?)?(\/?[^#?]*)(\?[^#]*)?(#.*)?/i;function isAbsoluteUrl(t){return e.test(t)}function isSchemeRelativeUrl(e){return e.startsWith("//")}function isAbsolutePath(e){return e.startsWith("/")}function isFileUrl(e){return e.startsWith("file:")}function isRelative(e){return/^[.?#]/.test(e)}function parseAbsoluteUrl(e){const r=t.exec(e);return makeUrl(r[1],r[2]||"",r[3],r[4]||"",r[5]||"/",r[6]||"",r[7]||"")}function parseFileUrl(e){const t=r.exec(e),n=t[2];return makeUrl("file:","",t[1]||"","",isAbsolutePath(n)?n:"/"+n,t[3]||"",t[4]||"")}function makeUrl(e,t,r,n,s,i,o){return{scheme:e,user:t,host:r,port:n,path:s,query:i,hash:o,type:7}}function parseUrl(e){if(isSchemeRelativeUrl(e)){const t=parseAbsoluteUrl("http:"+e);return t.scheme="",t.type=6,t}if(isAbsolutePath(e)){const t=parseAbsoluteUrl("http://foo.com"+e);return t.scheme="",t.host="",t.type=5,t}if(isFileUrl(e))return parseFileUrl(e);if(isAbsoluteUrl(e))return parseAbsoluteUrl(e);const t=parseAbsoluteUrl("http://foo.com/"+e);return t.scheme="",t.host="",t.type=e?e.startsWith("?")?3:e.startsWith("#")?2:4:1,t}function stripPathFilename(e){if(e.endsWith("/.."))return e;const t=e.lastIndexOf("/");return e.slice(0,t+1)}function mergePaths(e,t){normalizePath(t,t.type),"/"===e.path?e.path=t.path:e.path=stripPathFilename(t.path)+e.path}function normalizePath(e,t){const r=t<=4,n=e.path.split("/");let s=1,i=0,o=!1;for(let e=1;en&&(n=s)}normalizePath(r,n);const s=r.query+r.hash;switch(n){case 2:case 3:return s;case 4:{const n=r.path.slice(1);return n?isRelative(t||e)&&!isRelative(n)?"./"+n+s:n+s:s||"."}case 5:return r.path+s;default:return r.scheme+"//"+r.user+r.host+r.port+r.path+s}}return resolve}()},"./node_modules/.pnpm/@jridgewell+sourcemap-codec@1.5.5/node_modules/@jridgewell/sourcemap-codec/dist/sourcemap-codec.umd.js"(e,t,r){var n;!function(e){"use strict";var t=Object.defineProperty,r=Object.getOwnPropertyDescriptor,n=Object.getOwnPropertyNames,s=Object.prototype.hasOwnProperty,__copyProps=(e,i,o,a)=>{if(i&&"object"==typeof i||"function"==typeof i)for(let l of n(i))s.call(e,l)||l===o||t(e,l,{get:()=>i[l],enumerable:!(a=r(i,l))||a.enumerable});return e},__toCommonJS=e=>__copyProps(t({},"__esModule",{value:!0}),e),i={};((e,r)=>{for(var n in r)t(e,n,{get:r[n],enumerable:!0})})(i,{decode:()=>decode,decodeGeneratedRanges:()=>decodeGeneratedRanges,decodeOriginalScopes:()=>decodeOriginalScopes,encode:()=>encode,encodeGeneratedRanges:()=>encodeGeneratedRanges,encodeOriginalScopes:()=>encodeOriginalScopes}),e.exports=__toCommonJS(i);var o=",".charCodeAt(0),a=";".charCodeAt(0),l="ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789+/",p=new Uint8Array(64),c=new Uint8Array(128);for(let e=0;e>>=1,i&&(r=-2147483648|-r),t+r}function encodeInteger(e,t,r){let n=t-r;n=n<0?-n<<1|1:n<<1;do{let t=31&n;n>>>=5,n>0&&(t|=32),e.write(p[t])}while(n>0);return t}function hasMoreVlq(e,t){return!(e.pos>=t)&&e.peek()!==o}var u=16384,d="undefined"!=typeof TextDecoder?new TextDecoder:"undefined"!=typeof Buffer?{decode:e=>Buffer.from(e.buffer,e.byteOffset,e.byteLength).toString()}:{decode(e){let t="";for(let r=0;r0?t+d.decode(e.subarray(0,r)):t}},m=class{constructor(e){this.pos=0,this.buffer=e}next(){return this.buffer.charCodeAt(this.pos++)}peek(){return this.buffer.charCodeAt(this.pos)}indexOf(e){const{buffer:t,pos:r}=this,n=t.indexOf(e,r);return-1===n?t.length:n}},f=[];function decodeOriginalScopes(e){const{length:t}=e,r=new m(e),n=[],s=[];let i=0;for(;r.pos0&&r.write(o),n[0]=encodeInteger(r,i,n[0]),encodeInteger(r,a,0),encodeInteger(r,c,0),encodeInteger(r,6===s.length?1:0,0),6===s.length&&encodeInteger(r,s[5],0);for(const e of u)encodeInteger(r,e,0);for(t++;tl||i===l&&o>=p)break;t=_encodeOriginalScopes(e,t,r,n)}return r.write(o),n[0]=encodeInteger(r,l,n[0]),encodeInteger(r,p,0),t}function decodeGeneratedRanges(e){const{length:t}=e,r=new m(e),n=[],s=[];let i=0,o=0,a=0,l=0,p=0,c=0,u=0,d=0;do{const e=r.indexOf(";");let t=0;for(;r.pose;t--){const e=u;u=decodeInteger(r,u),d=decodeInteger(r,u===e?d:0);const t=decodeInteger(r,0);n.push([t,u,d])}}else n=[[e]];x.push(n)}while(hasMoreVlq(r,e))}b.bindings=x,n.push(b),s.push(b)}i++,r.pos=e+1}while(r.pos0&&r.write(o),n[1]=encodeInteger(r,s[1],n[1]),encodeInteger(r,(6===s.length?1:0)|(u?2:0)|(c?4:0),0),6===s.length){const{4:e,5:t}=s;e!==n[2]&&(n[3]=0),n[2]=encodeInteger(r,e,n[2]),n[3]=encodeInteger(r,t,n[3])}if(u){const{0:e,1:t,2:i}=s.callsite;e!==n[4]?(n[5]=0,n[6]=0):t!==n[5]&&(n[6]=0),n[4]=encodeInteger(r,e,n[4]),n[5]=encodeInteger(r,t,n[5]),n[6]=encodeInteger(r,i,n[6])}if(d)for(const e of d){e.length>1&&encodeInteger(r,-e.length,0),encodeInteger(r,e[0][0],0);let t=i,n=a;for(let s=1;sl||i===l&&o>=p)break;t=_encodeGeneratedRanges(e,t,r,n)}return n[0]0&&t.write(a),0===p.length)continue;let c=0;for(let e=0;e0&&t.write(o),c=encodeInteger(t,a[0],c),1!==a.length&&(r=encodeInteger(t,a[1],r),n=encodeInteger(t,a[2],n),s=encodeInteger(t,a[3],s),4!==a.length&&(i=encodeInteger(t,a[4],i)))}}return t.flush()}}(e=r.nmd(e)),e.exports="default"in(n=e).exports?n.exports.default:n.exports},"./node_modules/.pnpm/@jridgewell+trace-mapping@0.3.31/node_modules/@jridgewell/trace-mapping/dist/trace-mapping.umd.js"(e,t,r){var n;!function(e,t,r){"use strict";var n=Object.create,s=Object.defineProperty,i=Object.getOwnPropertyDescriptor,o=Object.getOwnPropertyNames,a=Object.getPrototypeOf,l=Object.prototype.hasOwnProperty,__commonJS=(e,t)=>function(){return t||(0,e[o(e)[0]])((t={exports:{}}).exports,t),t.exports},__export=(e,t)=>{for(var r in t)s(e,r,{get:t[r],enumerable:!0})},__copyProps=(e,t,r,n)=>{if(t&&"object"==typeof t||"function"==typeof t)for(let a of o(t))l.call(e,a)||a===r||s(e,a,{get:()=>t[a],enumerable:!(n=i(t,a))||n.enumerable});return e},__toESM=(e,t,r)=>(r=null!=e?n(a(e)):{},__copyProps(!t&&e&&e.__esModule?r:s(r,"default",{value:e,enumerable:!0}),e)),__toCommonJS=e=>__copyProps(s({},"__esModule",{value:!0}),e),p=__commonJS({"umd:@jridgewell/sourcemap-codec"(e,t){t.exports=r}}),c=__commonJS({"umd:@jridgewell/resolve-uri"(e,r){r.exports=t}}),u={};__export(u,{AnyMap:()=>FlattenMap,FlattenMap:()=>FlattenMap,GREATEST_LOWER_BOUND:()=>_,LEAST_UPPER_BOUND:()=>P,TraceMap:()=>A,allGeneratedPositionsFor:()=>allGeneratedPositionsFor,decodedMap:()=>decodedMap,decodedMappings:()=>decodedMappings,eachMapping:()=>eachMapping,encodedMap:()=>encodedMap,encodedMappings:()=>encodedMappings,generatedPositionFor:()=>generatedPositionFor,isIgnored:()=>isIgnored,originalPositionFor:()=>originalPositionFor,presortedDecodedMap:()=>presortedDecodedMap,sourceContentFor:()=>sourceContentFor,traceSegment:()=>traceSegment}),e.exports=__toCommonJS(u);var d=__toESM(p()),h=__toESM(c());function stripFilename(e){if(!e)return"";const t=e.lastIndexOf("/");return e.slice(0,t+1)}function resolver(e,t){const r=stripFilename(e),n=t?t+"/":"";return e=>(0,h.default)(n+(e||""),r)}var m=0,f=1,y=2,b=3,g=4,x=1,v=2;function maybeSort(e,t){const r=nextUnsortedSegmentLine(e,0);if(r===e.length)return e;t||(e=e.slice());for(let n=r;n[]);for(let t=0;t>1),i=e[s][m]-t;if(0===i)return E=!0,s;i<0?r=s+1:n=s-1}return E=!1,r-1}function upperBound(e,t,r){for(let n=r+1;n=0&&e[n][m]===t;r=n--);return r}function memoizedState(){return{lastKey:-1,lastNeedle:-1,lastIndex:-1}}function memoizedBinarySearch(e,t,r,n){const{lastKey:s,lastNeedle:i,lastIndex:o}=r;let a=0,l=e.length-1;if(n===s){if(t===i)return E=-1!==o&&e[o][m]===t,o;t>=i?a=-1===o?0:o:l=o}return r.lastKey=n,r.lastNeedle=t,r.lastIndex=binarySearch(e,t,a,l)}function parse(e){return"string"==typeof e?JSON.parse(e):e}var FlattenMap=function(e,t){const r=parse(e);if(!("sections"in r))return new A(r,t);const n=[],s=[],i=[],o=[],a=[];return recurse(r,t,n,s,i,o,a,0,0,1/0,1/0),presortedDecodedMap({version:3,file:r.file,names:o,sources:s,sourcesContent:i,mappings:n,ignoreList:a})};function recurse(e,t,r,n,s,i,o,a,l,p,c){const{sections:u}=e;for(let e=0;ep)return;const n=getLine(r,t),s=0===e?l:0,i=v[e];for(let e=0;e=c)return;if(1===r.length){n.push([o]);continue}const a=h+r[f],l=r[y],u=r[b];n.push(4===r.length?[o,a,l,u]:[o,a,l,u,x+r[g]])}}}function append(e,t){for(let r=0;r=n.length)return null;const s=n[t],i=traceSegmentInternal(s,cast(e)._decodedMemo,t,r,_);return-1===i?null:s[i]}function originalPositionFor(e,t){let{line:r,column:n,bias:s}=t;if(r--,r<0)throw new Error(T);if(n<0)throw new Error(S);const i=decodedMappings(e);if(r>=i.length)return OMapping(null,null,null,null);const o=i[r],a=traceSegmentInternal(o,cast(e)._decodedMemo,r,n,s||_);if(-1===a)return OMapping(null,null,null,null);const l=o[a];if(1===l.length)return OMapping(null,null,null,null);const{names:p,resolvedSources:c}=e;return OMapping(c[l[f]],l[y]+1,l[b],5===l.length?p[l[g]]:null)}function generatedPositionFor(e,t){const{source:r,line:n,column:s,bias:i}=t;return generatedPosition(e,r,n,s,i||_,!1)}function allGeneratedPositionsFor(e,t){const{source:r,line:n,column:s,bias:i}=t;return generatedPosition(e,r,n,s,i||P,!0)}function eachMapping(e,t){const r=decodedMappings(e),{names:n,resolvedSources:s}=e;for(let e=0;e{"%%"!==e&&(n++,"%c"===e&&(s=n))}),t.splice(s,0,r)},t.save=function(e){try{e?t.storage.setItem("debug",e):t.storage.removeItem("debug")}catch(e){}},t.load=function(){let e;try{e=t.storage.getItem("debug")||t.storage.getItem("DEBUG")}catch(e){}!e&&"undefined"!=typeof process&&"env"in process&&(e=process.env.DEBUG);return e},t.useColors=function(){if("undefined"!=typeof window&&window.process&&("renderer"===window.process.type||window.process.__nwjs))return!0;if("undefined"!=typeof navigator&&navigator.userAgent&&navigator.userAgent.toLowerCase().match(/(edge|trident)\/(\d+)/))return!1;let e;return"undefined"!=typeof document&&document.documentElement&&document.documentElement.style&&document.documentElement.style.WebkitAppearance||"undefined"!=typeof window&&window.console&&(window.console.firebug||window.console.exception&&window.console.table)||"undefined"!=typeof navigator&&navigator.userAgent&&(e=navigator.userAgent.toLowerCase().match(/firefox\/(\d+)/))&&parseInt(e[1],10)>=31||"undefined"!=typeof navigator&&navigator.userAgent&&navigator.userAgent.toLowerCase().match(/applewebkit\/(\d+)/)},t.storage=function(){try{return localStorage}catch(e){}}(),t.destroy=(()=>{let e=!1;return()=>{e||(e=!0,console.warn("Instance method `debug.destroy()` is deprecated and no longer does anything. It will be removed in the next major version of `debug`."))}})(),t.colors=["#0000CC","#0000FF","#0033CC","#0033FF","#0066CC","#0066FF","#0099CC","#0099FF","#00CC00","#00CC33","#00CC66","#00CC99","#00CCCC","#00CCFF","#3300CC","#3300FF","#3333CC","#3333FF","#3366CC","#3366FF","#3399CC","#3399FF","#33CC00","#33CC33","#33CC66","#33CC99","#33CCCC","#33CCFF","#6600CC","#6600FF","#6633CC","#6633FF","#66CC00","#66CC33","#9900CC","#9900FF","#9933CC","#9933FF","#99CC00","#99CC33","#CC0000","#CC0033","#CC0066","#CC0099","#CC00CC","#CC00FF","#CC3300","#CC3333","#CC3366","#CC3399","#CC33CC","#CC33FF","#CC6600","#CC6633","#CC9900","#CC9933","#CCCC00","#CCCC33","#FF0000","#FF0033","#FF0066","#FF0099","#FF00CC","#FF00FF","#FF3300","#FF3333","#FF3366","#FF3399","#FF33CC","#FF33FF","#FF6600","#FF6633","#FF9900","#FF9933","#FFCC00","#FFCC33"],t.log=console.debug||console.log||(()=>{}),e.exports=r("./node_modules/.pnpm/debug@4.4.3/node_modules/debug/src/common.js")(t);const{formatters:n}=e.exports;n.j=function(e){try{return JSON.stringify(e)}catch(e){return"[UnexpectedJSONParseError]: "+e.message}}},"./node_modules/.pnpm/debug@4.4.3/node_modules/debug/src/common.js"(e,t,r){e.exports=function(e){function createDebug(e){let t,r,n,s=null;function debug(...e){if(!debug.enabled)return;const r=debug,n=Number(new Date),s=n-(t||n);r.diff=s,r.prev=t,r.curr=n,t=n,e[0]=createDebug.coerce(e[0]),"string"!=typeof e[0]&&e.unshift("%O");let i=0;e[0]=e[0].replace(/%([a-zA-Z%])/g,(t,n)=>{if("%%"===t)return"%";i++;const s=createDebug.formatters[n];if("function"==typeof s){const n=e[i];t=s.call(r,n),e.splice(i,1),i--}return t}),createDebug.formatArgs.call(r,e);(r.log||createDebug.log).apply(r,e)}return debug.namespace=e,debug.useColors=createDebug.useColors(),debug.color=createDebug.selectColor(e),debug.extend=extend,debug.destroy=createDebug.destroy,Object.defineProperty(debug,"enabled",{enumerable:!0,configurable:!1,get:()=>null!==s?s:(r!==createDebug.namespaces&&(r=createDebug.namespaces,n=createDebug.enabled(e)),n),set:e=>{s=e}}),"function"==typeof createDebug.init&&createDebug.init(debug),debug}function extend(e,t){const r=createDebug(this.namespace+(void 0===t?":":t)+e);return r.log=this.log,r}function matchesTemplate(e,t){let r=0,n=0,s=-1,i=0;for(;r"-"+e)].join(",");return createDebug.enable(""),e},createDebug.enable=function(e){createDebug.save(e),createDebug.namespaces=e,createDebug.names=[],createDebug.skips=[];const t=("string"==typeof e?e:"").trim().replace(/\s+/g,",").split(",").filter(Boolean);for(const e of t)"-"===e[0]?createDebug.skips.push(e.slice(1)):createDebug.names.push(e)},createDebug.enabled=function(e){for(const t of createDebug.skips)if(matchesTemplate(e,t))return!1;for(const t of createDebug.names)if(matchesTemplate(e,t))return!0;return!1},createDebug.humanize=r("./node_modules/.pnpm/ms@2.1.3/node_modules/ms/index.js"),createDebug.destroy=function(){console.warn("Instance method `debug.destroy()` is deprecated and no longer does anything. It will be removed in the next major version of `debug`.")},Object.keys(e).forEach(t=>{createDebug[t]=e[t]}),createDebug.names=[],createDebug.skips=[],createDebug.formatters={},createDebug.selectColor=function(e){let t=0;for(let r=0;r{},"Instance method `debug.destroy()` is deprecated and no longer does anything. It will be removed in the next major version of `debug`."),t.colors=[6,2,3,4,5,1];try{const e=r("./node_modules/.pnpm/supports-color@7.2.0/node_modules/supports-color/index.js");e&&(e.stderr||e).level>=2&&(t.colors=[20,21,26,27,32,33,38,39,40,41,42,43,44,45,56,57,62,63,68,69,74,75,76,77,78,79,80,81,92,93,98,99,112,113,128,129,134,135,148,149,160,161,162,163,164,165,166,167,168,169,170,171,172,173,178,179,184,185,196,197,198,199,200,201,202,203,204,205,206,207,208,209,214,215,220,221])}catch(e){}t.inspectOpts=Object.keys(process.env).filter(e=>/^debug_/i.test(e)).reduce((e,t)=>{const r=t.substring(6).toLowerCase().replace(/_([a-z])/g,(e,t)=>t.toUpperCase());let n=process.env[t];return n=!!/^(yes|on|true|enabled)$/i.test(n)||!/^(no|off|false|disabled)$/i.test(n)&&("null"===n?null:Number(n)),e[r]=n,e},{}),e.exports=r("./node_modules/.pnpm/debug@4.4.3/node_modules/debug/src/common.js")(t);const{formatters:i}=e.exports;i.o=function(e){return this.inspectOpts.colors=this.useColors,s.inspect(e,this.inspectOpts).split("\n").map(e=>e.trim()).join(" ")},i.O=function(e){return this.inspectOpts.colors=this.useColors,s.inspect(e,this.inspectOpts)}},"./node_modules/.pnpm/gensync@1.0.0-beta.2/node_modules/gensync/index.js"(e){"use strict";const t=Symbol.for("gensync:v1:start"),r=Symbol.for("gensync:v1:suspend"),n="GENSYNC_OPTIONS_ERROR",s="GENSYNC_RACE_NONEMPTY",i="GENSYNC_ERRBACK_NO_CALLBACK";function assertTypeof(e,t,r,s){if(typeof r===e||s&&void 0===r)return;let i;throw i=s?`Expected opts.${t} to be either a ${e}, or undefined.`:`Expected opts.${t} to be a ${e}.`,makeError(i,n)}function makeError(e,t){return Object.assign(new Error(e),{code:t})}function buildOperation({name:e,arity:n,sync:s,async:i}){return setFunctionMetadata(e,n,function*(...e){const n=yield t;if(!n){return s.call(this,e)}let o;try{i.call(this,e,e=>{o||(o={value:e},n())},e=>{o||(o={err:e},n())})}catch(e){o={err:e},n()}if(yield r,o.hasOwnProperty("err"))throw o.err;return o.value})}function evaluateSync(e){let t;for(;!({value:t}=e.next()).done;)assertStart(t,e);return t}function evaluateAsync(e,t,r){!function step(){try{let r;for(;!({value:r}=e.next()).done;){assertStart(r,e);let t=!0,n=!1;const s=e.next(()=>{t?n=!0:step()});if(t=!1,assertSuspend(s,e),!n)return}return t(r)}catch(e){return r(e)}}()}function assertStart(e,r){e!==t&&throwError(r,makeError(`Got unexpected yielded value in gensync generator: ${JSON.stringify(e)}. Did you perhaps mean to use 'yield*' instead of 'yield'?`,"GENSYNC_EXPECTED_START"))}function assertSuspend({value:e,done:t},n){(t||e!==r)&&throwError(n,makeError(t?"Unexpected generator completion. If you get this, it is probably a gensync bug.":`Expected GENSYNC_SUSPEND, got ${JSON.stringify(e)}. If you get this, it is probably a gensync bug.`,"GENSYNC_EXPECTED_SUSPEND"))}function throwError(e,t){throw e.throw&&e.throw(t),t}function setFunctionMetadata(e,t,r){if("string"==typeof e){const t=Object.getOwnPropertyDescriptor(r,"name");t&&!t.configurable||Object.defineProperty(r,"name",Object.assign(t||{},{configurable:!0,value:e}))}if("number"==typeof t){const e=Object.getOwnPropertyDescriptor(r,"length");e&&!e.configurable||Object.defineProperty(r,"length",Object.assign(e||{},{configurable:!0,value:t}))}return r}e.exports=Object.assign(function(e){let t=e;return t="function"!=typeof e?function({name:e,arity:t,sync:r,async:s,errback:i}){if(assertTypeof("string","name",e,!0),assertTypeof("number","arity",t,!0),assertTypeof("function","sync",r),assertTypeof("function","async",s,!0),assertTypeof("function","errback",i,!0),s&&i)throw makeError("Expected one of either opts.async or opts.errback, but got _both_.",n);if("string"!=typeof e){let t;i&&i.name&&"errback"!==i.name&&(t=i.name),s&&s.name&&"async"!==s.name&&(t=s.name.replace(/Async$/,"")),r&&r.name&&"sync"!==r.name&&(t=r.name.replace(/Sync$/,"")),"string"==typeof t&&(e=t)}"number"!=typeof t&&(t=r.length);return buildOperation({name:e,arity:t,sync:function(e){return r.apply(this,e)},async:function(e,t,n){s?s.apply(this,e).then(t,n):i?i.call(this,...e,(e,r)=>{null==e?t(r):n(e)}):t(r.apply(this,e))}})}(e):function(e){return setFunctionMetadata(e.name,e.length,function(...t){return e.apply(this,t)})}(e),Object.assign(t,function(e){const t={sync:function(...t){return evaluateSync(e.apply(this,t))},async:function(...t){return new Promise((r,n)=>{evaluateAsync(e.apply(this,t),r,n)})},errback:function(...t){const r=t.pop();if("function"!=typeof r)throw makeError("Asynchronous function called without callback",i);let n;try{n=e.apply(this,t)}catch(e){return void r(e)}evaluateAsync(n,e=>r(void 0,e),e=>r(e))}};return t}(t))},{all:buildOperation({name:"all",arity:1,sync:function(e){return Array.from(e[0]).map(e=>evaluateSync(e))},async:function(e,t,r){const n=Array.from(e[0]);if(0===n.length)return void Promise.resolve().then(()=>t([]));let s=0;const i=n.map(()=>{});n.forEach((e,n)=>{evaluateAsync(e,e=>{i[n]=e,s+=1,s===i.length&&t(i)},r)})}}),race:buildOperation({name:"race",arity:1,sync:function(e){const t=Array.from(e[0]);if(0===t.length)throw makeError("Must race at least 1 item",s);return evaluateSync(t[0])},async:function(e,t,r){const n=Array.from(e[0]);if(0===n.length)throw makeError("Must race at least 1 item",s);for(const e of n)evaluateAsync(e,t,r)}})})},"./node_modules/.pnpm/has-flag@4.0.0/node_modules/has-flag/index.js"(e){"use strict";e.exports=(e,t=process.argv)=>{const r=e.startsWith("-")?"":1===e.length?"-":"--",n=t.indexOf(r+e),s=t.indexOf("--");return-1!==n&&(-1===s||n{for(const n in e)r.call(e,n)&&t(n,e[n])},fourHexEscape=e=>"\\u"+("0000"+e).slice(-4),hexadecimal=(e,t)=>{let r=e.toString(16);return t?r:r.toUpperCase()},n=t.toString,s=Array.isArray,isBigInt=e=>"bigint"==typeof e,i={"\\":"\\\\","\b":"\\b","\f":"\\f","\n":"\\n","\r":"\\r","\t":"\\t"},o=/[\\\b\f\n\r\t]/,a=/[0-9]/,l=/[\xA0\u1680\u2000-\u200A\u2028\u2029\u202F\u205F\u3000]/,p=/([\uD800-\uDBFF][\uDC00-\uDFFF])|([\uD800-\uDFFF])|(['"`])|[^]/g,c=/([\uD800-\uDBFF][\uDC00-\uDFFF])|([\uD800-\uDFFF])|(['"`])|[^ !#-&\(-\[\]-_a-~]/g,jsesc=(e,t)=>{const increaseIndentation=()=>{g=b,++t.indentLevel,b=t.indent.repeat(t.indentLevel)},r={escapeEverything:!1,minimal:!1,isScriptContext:!1,quotes:"single",wrap:!1,es6:!1,json:!1,compact:!0,lowercaseHex:!1,numbers:"decimal",indent:"\t",indentLevel:0,__inline1__:!1,__inline2__:!1},u=t&&t.json;var d,h;u&&(r.quotes="double",r.wrap=!0),d=r,"single"!=(t=(h=t)?(forOwn(h,(e,t)=>{d[e]=t}),d):d).quotes&&"double"!=t.quotes&&"backtick"!=t.quotes&&(t.quotes="single");const m="double"==t.quotes?'"':"backtick"==t.quotes?"`":"'",f=t.compact,y=t.lowercaseHex;let b=t.indent.repeat(t.indentLevel),g="";const x=t.__inline1__,v=t.__inline2__,E=f?"":"\n";let T,S=!0;const P="binary"==t.numbers,_="octal"==t.numbers,A="decimal"==t.numbers,C="hexadecimal"==t.numbers;if(u&&e&&(e=>"function"==typeof e)(e.toJSON)&&(e=e.toJSON()),!(e=>"string"==typeof e||"[object String]"==n.call(e))(e)){if((e=>"[object Map]"==n.call(e))(e))return 0==e.size?"new Map()":(f||(t.__inline1__=!0,t.__inline2__=!1),"new Map("+jsesc(Array.from(e),t)+")");if((e=>"[object Set]"==n.call(e))(e))return 0==e.size?"new Set()":"new Set("+jsesc(Array.from(e),t)+")";if((e=>"function"==typeof Buffer&&Buffer.isBuffer(e))(e))return 0==e.length?"Buffer.from([])":"Buffer.from("+jsesc(Array.from(e),t)+")";if(s(e))return T=[],t.wrap=!0,x&&(t.__inline1__=!1,t.__inline2__=!0),v||increaseIndentation(),((e,t)=>{const r=e.length;let n=-1;for(;++n{S=!1,v&&(t.__inline2__=!1),T.push((f||v?"":b)+jsesc(e,t))}),S?"[]":v?"["+T.join(", ")+"]":"["+E+T.join(","+E)+E+(f?"":g)+"]";if((e=>"number"==typeof e||"[object Number]"==n.call(e))(e)||isBigInt(e)){if(u)return JSON.stringify(Number(e));let t;if(A)t=String(e);else if(C){let r=e.toString(16);y||(r=r.toUpperCase()),t="0x"+r}else P?t="0b"+e.toString(2):_&&(t="0o"+e.toString(8));return isBigInt(e)?t+"n":t}return isBigInt(e)?u?JSON.stringify(Number(e)):e+"n":(e=>"[object Object]"==n.call(e))(e)?(T=[],t.wrap=!0,increaseIndentation(),forOwn(e,(e,r)=>{S=!1,T.push((f?"":b)+jsesc(e,t)+":"+(f?"":" ")+jsesc(r,t))}),S?"{}":"{"+E+T.join(","+E)+E+(f?"":g)+"}"):u?JSON.stringify(e)||"null":String(e)}const w=t.escapeEverything?p:c;return T=e.replace(w,(e,r,n,s,p,c)=>{if(r){if(t.minimal)return r;const e=r.charCodeAt(0),n=r.charCodeAt(1);if(t.es6){return"\\u{"+hexadecimal(1024*(e-55296)+n-56320+65536,y)+"}"}return fourHexEscape(hexadecimal(e,y))+fourHexEscape(hexadecimal(n,y))}if(n)return fourHexEscape(hexadecimal(n.charCodeAt(0),y));if("\0"==e&&!u&&!a.test(c.charAt(p+1)))return"\\0";if(s)return s==m||t.escapeEverything?"\\"+s:s;if(o.test(e))return i[e];if(t.minimal&&!l.test(e))return e;const d=hexadecimal(e.charCodeAt(0),y);return u||d.length>2?fourHexEscape(d):"\\x"+("00"+d).slice(-2)}),"`"==m&&(T=T.replace(/\$\{/g,"\\${")),t.isScriptContext&&(T=T.replace(/<\/(script|style)/gi,"<\\/$1").replace(/ + +--- + + + + + + +## Table of Contents + +- [Examples](#examples) + - [Consuming a source map](#consuming-a-source-map) + - [Generating a source map](#generating-a-source-map) + - [With SourceNode (high level API)](#with-sourcenode-high-level-api) + - [With SourceMapGenerator (low level API)](#with-sourcemapgenerator-low-level-api) +- [API](#api) + - [SourceMapConsumer](#sourcemapconsumer) + - [new SourceMapConsumer(rawSourceMap)](#new-sourcemapconsumerrawsourcemap) + - [SourceMapConsumer.prototype.computeColumnSpans()](#sourcemapconsumerprototypecomputecolumnspans) + - [SourceMapConsumer.prototype.originalPositionFor(generatedPosition)](#sourcemapconsumerprototypeoriginalpositionforgeneratedposition) + - [SourceMapConsumer.prototype.generatedPositionFor(originalPosition)](#sourcemapconsumerprototypegeneratedpositionfororiginalposition) + - [SourceMapConsumer.prototype.allGeneratedPositionsFor(originalPosition)](#sourcemapconsumerprototypeallgeneratedpositionsfororiginalposition) + - [SourceMapConsumer.prototype.hasContentsOfAllSources()](#sourcemapconsumerprototypehascontentsofallsources) + - [SourceMapConsumer.prototype.sourceContentFor(source[, returnNullOnMissing])](#sourcemapconsumerprototypesourcecontentforsource-returnnullonmissing) + - [SourceMapConsumer.prototype.eachMapping(callback, context, order)](#sourcemapconsumerprototypeeachmappingcallback-context-order) + - [SourceMapGenerator](#sourcemapgenerator) + - [new SourceMapGenerator([startOfSourceMap])](#new-sourcemapgeneratorstartofsourcemap) + - [SourceMapGenerator.fromSourceMap(sourceMapConsumer, sourceMapGeneratorOptions)](#sourcemapgeneratorfromsourcemapsourcemapconsumer-sourcemapgeneratoroptions) + - [SourceMapGenerator.prototype.addMapping(mapping)](#sourcemapgeneratorprototypeaddmappingmapping) + - [SourceMapGenerator.prototype.setSourceContent(sourceFile, sourceContent)](#sourcemapgeneratorprototypesetsourcecontentsourcefile-sourcecontent) + - [SourceMapGenerator.prototype.applySourceMap(sourceMapConsumer[, sourceFile[, sourceMapPath]])](#sourcemapgeneratorprototypeapplysourcemapsourcemapconsumer-sourcefile-sourcemappath) + - [SourceMapGenerator.prototype.toString()](#sourcemapgeneratorprototypetostring) + - [SourceNode](#sourcenode) + - [new SourceNode([line, column, source[, chunk[, name]]])](#new-sourcenodeline-column-source-chunk-name) + - [SourceNode.fromStringWithSourceMap(code, sourceMapConsumer[, relativePath])](#sourcenodefromstringwithsourcemapcode-sourcemapconsumer-relativepath) + - [SourceNode.prototype.add(chunk)](#sourcenodeprototypeaddchunk) + - [SourceNode.prototype.prepend(chunk)](#sourcenodeprototypeprependchunk) + - [SourceNode.prototype.setSourceContent(sourceFile, sourceContent)](#sourcenodeprototypesetsourcecontentsourcefile-sourcecontent) + - [SourceNode.prototype.walk(fn)](#sourcenodeprototypewalkfn) + - [SourceNode.prototype.walkSourceContents(fn)](#sourcenodeprototypewalksourcecontentsfn) + - [SourceNode.prototype.join(sep)](#sourcenodeprototypejoinsep) + - [SourceNode.prototype.replaceRight(pattern, replacement)](#sourcenodeprototypereplacerightpattern-replacement) + - [SourceNode.prototype.toString()](#sourcenodeprototypetostring) + - [SourceNode.prototype.toStringWithSourceMap([startOfSourceMap])](#sourcenodeprototypetostringwithsourcemapstartofsourcemap) + + + +## Examples + +### Consuming a source map + +```js +var rawSourceMap = { + version: 3, + file: 'min.js', + names: ['bar', 'baz', 'n'], + sources: ['one.js', 'two.js'], + sourceRoot: 'http://example.com/www/js/', + mappings: + 'CAAC,IAAI,IAAM,SAAUA,GAClB,OAAOC,IAAID;CCDb,IAAI,IAAM,SAAUE,GAClB,OAAOA', +}; + +var smc = new SourceMapConsumer(rawSourceMap); + +console.log(smc.sources); +// [ 'http://example.com/www/js/one.js', +// 'http://example.com/www/js/two.js' ] + +console.log( + smc.originalPositionFor({ + line: 2, + column: 28, + }) +); +// { source: 'http://example.com/www/js/two.js', +// line: 2, +// column: 10, +// name: 'n' } + +console.log( + smc.generatedPositionFor({ + source: 'http://example.com/www/js/two.js', + line: 2, + column: 10, + }) +); +// { line: 2, column: 28 } + +smc.eachMapping(function (m) { + // ... +}); +``` + +### Generating a source map + +In depth guide: +[**Compiling to JavaScript, and Debugging with Source Maps**](https://hacks.mozilla.org/2013/05/compiling-to-javascript-and-debugging-with-source-maps/) + +#### With SourceNode (high level API) + +```js +function compile(ast) { + switch (ast.type) { + case 'BinaryExpression': + return new SourceNode( + ast.location.line, + ast.location.column, + ast.location.source, + [compile(ast.left), ' + ', compile(ast.right)] + ); + case 'Literal': + return new SourceNode( + ast.location.line, + ast.location.column, + ast.location.source, + String(ast.value) + ); + // ... + default: + throw new Error('Bad AST'); + } +} + +var ast = parse('40 + 2', 'add.js'); +console.log( + compile(ast).toStringWithSourceMap({ + file: 'add.js', + }) +); +// { code: '40 + 2', +// map: [object SourceMapGenerator] } +``` + +#### With SourceMapGenerator (low level API) + +```js +var map = new SourceMapGenerator({ + file: 'source-mapped.js', +}); + +map.addMapping({ + generated: { + line: 10, + column: 35, + }, + source: 'foo.js', + original: { + line: 33, + column: 2, + }, + name: 'christopher', +}); + +console.log(map.toString()); +// '{"version":3,"file":"source-mapped.js","sources":["foo.js"],"names":["christopher"],"mappings":";;;;;;;;;mCAgCEA"}' +``` + +## API + +Get a reference to the module: + +```js +// Node.js +var sourceMap = require('source-map'); + +// Browser builds +var sourceMap = window.sourceMap; + +// Inside Firefox +const sourceMap = require('devtools/toolkit/sourcemap/source-map.js'); +``` + +### SourceMapConsumer + +A SourceMapConsumer instance represents a parsed source map which we can query +for information about the original file positions by giving it a file position +in the generated source. + +#### new SourceMapConsumer(rawSourceMap) + +The only parameter is the raw source map (either as a string which can be +`JSON.parse`'d, or an object). According to the spec, source maps have the +following attributes: + +- `version`: Which version of the source map spec this map is following. + +- `sources`: An array of URLs to the original source files. + +- `names`: An array of identifiers which can be referenced by individual + mappings. + +- `sourceRoot`: Optional. The URL root from which all sources are relative. + +- `sourcesContent`: Optional. An array of contents of the original source files. + +- `mappings`: A string of base64 VLQs which contain the actual mappings. + +- `file`: Optional. The generated filename this source map is associated with. + +```js +var consumer = new sourceMap.SourceMapConsumer(rawSourceMapJsonData); +``` + +#### SourceMapConsumer.prototype.computeColumnSpans() + +Compute the last column for each generated mapping. The last column is +inclusive. + +```js +// Before: +consumer.allGeneratedPositionsFor({ line: 2, source: 'foo.coffee' }); +// [ { line: 2, +// column: 1 }, +// { line: 2, +// column: 10 }, +// { line: 2, +// column: 20 } ] + +consumer.computeColumnSpans(); + +// After: +consumer.allGeneratedPositionsFor({ line: 2, source: 'foo.coffee' }); +// [ { line: 2, +// column: 1, +// lastColumn: 9 }, +// { line: 2, +// column: 10, +// lastColumn: 19 }, +// { line: 2, +// column: 20, +// lastColumn: Infinity } ] +``` + +#### SourceMapConsumer.prototype.originalPositionFor(generatedPosition) + +Returns the original source, line, and column information for the generated +source's line and column positions provided. The only argument is an object with +the following properties: + +- `line`: The line number in the generated source. Line numbers in + this library are 1-based (note that the underlying source map + specification uses 0-based line numbers -- this library handles the + translation). + +- `column`: The column number in the generated source. Column numbers + in this library are 0-based. + +- `bias`: Either `SourceMapConsumer.GREATEST_LOWER_BOUND` or + `SourceMapConsumer.LEAST_UPPER_BOUND`. Specifies whether to return the closest + element that is smaller than or greater than the one we are searching for, + respectively, if the exact element cannot be found. Defaults to + `SourceMapConsumer.GREATEST_LOWER_BOUND`. + +and an object is returned with the following properties: + +- `source`: The original source file, or null if this information is not + available. + +- `line`: The line number in the original source, or null if this information is + not available. The line number is 1-based. + +- `column`: The column number in the original source, or null if this + information is not available. The column number is 0-based. + +- `name`: The original identifier, or null if this information is not available. + +```js +consumer.originalPositionFor({ line: 2, column: 10 }); +// { source: 'foo.coffee', +// line: 2, +// column: 2, +// name: null } + +consumer.originalPositionFor({ + line: 99999999999999999, + column: 999999999999999, +}); +// { source: null, +// line: null, +// column: null, +// name: null } +``` + +#### SourceMapConsumer.prototype.generatedPositionFor(originalPosition) + +Returns the generated line and column information for the original source, +line, and column positions provided. The only argument is an object with +the following properties: + +- `source`: The filename of the original source. + +- `line`: The line number in the original source. The line number is + 1-based. + +- `column`: The column number in the original source. The column + number is 0-based. + +and an object is returned with the following properties: + +- `line`: The line number in the generated source, or null. The line + number is 1-based. + +- `column`: The column number in the generated source, or null. The + column number is 0-based. + +```js +consumer.generatedPositionFor({ source: 'example.js', line: 2, column: 10 }); +// { line: 1, +// column: 56 } +``` + +#### SourceMapConsumer.prototype.allGeneratedPositionsFor(originalPosition) + +Returns all generated line and column information for the original source, line, +and column provided. If no column is provided, returns all mappings +corresponding to a either the line we are searching for or the next closest line +that has any mappings. Otherwise, returns all mappings corresponding to the +given line and either the column we are searching for or the next closest column +that has any offsets. + +The only argument is an object with the following properties: + +- `source`: The filename of the original source. + +- `line`: The line number in the original source. The line number is + 1-based. + +- `column`: Optional. The column number in the original source. The + column number is 0-based. + +and an array of objects is returned, each with the following properties: + +- `line`: The line number in the generated source, or null. The line + number is 1-based. + +- `column`: The column number in the generated source, or null. The + column number is 0-based. + +```js +consumer.allGeneratedpositionsfor({ line: 2, source: 'foo.coffee' }); +// [ { line: 2, +// column: 1 }, +// { line: 2, +// column: 10 }, +// { line: 2, +// column: 20 } ] +``` + +#### SourceMapConsumer.prototype.hasContentsOfAllSources() + +Return true if we have the embedded source content for every source listed in +the source map, false otherwise. + +In other words, if this method returns `true`, then +`consumer.sourceContentFor(s)` will succeed for every source `s` in +`consumer.sources`. + +```js +// ... +if (consumer.hasContentsOfAllSources()) { + consumerReadyCallback(consumer); +} else { + fetchSources(consumer, consumerReadyCallback); +} +// ... +``` + +#### SourceMapConsumer.prototype.sourceContentFor(source[, returnNullOnMissing]) + +Returns the original source content for the source provided. The only +argument is the URL of the original source file. + +If the source content for the given source is not found, then an error is +thrown. Optionally, pass `true` as the second param to have `null` returned +instead. + +```js +consumer.sources; +// [ "my-cool-lib.clj" ] + +consumer.sourceContentFor('my-cool-lib.clj'); +// "..." + +consumer.sourceContentFor('this is not in the source map'); +// Error: "this is not in the source map" is not in the source map + +consumer.sourceContentFor('this is not in the source map', true); +// null +``` + +#### SourceMapConsumer.prototype.eachMapping(callback, context, order) + +Iterate over each mapping between an original source/line/column and a +generated line/column in this source map. + +- `callback`: The function that is called with each mapping. Mappings have the + form `{ source, generatedLine, generatedColumn, originalLine, originalColumn, +name }` + +- `context`: Optional. If specified, this object will be the value of `this` + every time that `callback` is called. + +- `order`: Either `SourceMapConsumer.GENERATED_ORDER` or + `SourceMapConsumer.ORIGINAL_ORDER`. Specifies whether you want to iterate over + the mappings sorted by the generated file's line/column order or the + original's source/line/column order, respectively. Defaults to + `SourceMapConsumer.GENERATED_ORDER`. + +```js +consumer.eachMapping(function (m) { + console.log(m); +}); +// ... +// { source: 'illmatic.js', +// generatedLine: 1, +// generatedColumn: 0, +// originalLine: 1, +// originalColumn: 0, +// name: null } +// { source: 'illmatic.js', +// generatedLine: 2, +// generatedColumn: 0, +// originalLine: 2, +// originalColumn: 0, +// name: null } +// ... +``` + +### SourceMapGenerator + +An instance of the SourceMapGenerator represents a source map which is being +built incrementally. + +#### new SourceMapGenerator([startOfSourceMap]) + +You may pass an object with the following properties: + +- `file`: The filename of the generated source that this source map is + associated with. + +- `sourceRoot`: A root for all relative URLs in this source map. + +- `skipValidation`: Optional. When `true`, disables validation of mappings as + they are added. This can improve performance but should be used with + discretion, as a last resort. Even then, one should avoid using this flag when + running tests, if possible. + +- `ignoreInvalidMapping`: Optional. When `true`, instead of throwing error on + invalid mapping, it will be ignored. + +```js +var generator = new sourceMap.SourceMapGenerator({ + file: 'my-generated-javascript-file.js', + sourceRoot: 'http://example.com/app/js/', +}); +``` + +#### SourceMapGenerator.fromSourceMap(sourceMapConsumer, sourceMapGeneratorOptions) + +Creates a new `SourceMapGenerator` from an existing `SourceMapConsumer` instance. + +- `sourceMapConsumer` The SourceMap. + +- `sourceMapGeneratorOptions` options that will be passed to the SourceMapGenerator constructor which used under the hood. + +```js +var generator = sourceMap.SourceMapGenerator.fromSourceMap(consumer, { + ignoreInvalidMapping: true, +}); +``` + +#### SourceMapGenerator.prototype.addMapping(mapping) + +Add a single mapping from original source line and column to the generated +source's line and column for this source map being created. The mapping object +should have the following properties: + +- `generated`: An object with the generated line and column positions. + +- `original`: An object with the original line and column positions. + +- `source`: The original source file (relative to the sourceRoot). + +- `name`: An optional original token name for this mapping. + +```js +generator.addMapping({ + source: 'module-one.scm', + original: { line: 128, column: 0 }, + generated: { line: 3, column: 456 }, +}); +``` + +#### SourceMapGenerator.prototype.setSourceContent(sourceFile, sourceContent) + +Set the source content for an original source file. + +- `sourceFile` the URL of the original source file. + +- `sourceContent` the content of the source file. + +```js +generator.setSourceContent( + 'module-one.scm', + fs.readFileSync('path/to/module-one.scm') +); +``` + +#### SourceMapGenerator.prototype.applySourceMap(sourceMapConsumer[, sourceFile[, sourceMapPath]]) + +Applies a SourceMap for a source file to the SourceMap. +Each mapping to the supplied source file is rewritten using the +supplied SourceMap. Note: The resolution for the resulting mappings +is the minimum of this map and the supplied map. + +- `sourceMapConsumer`: The SourceMap to be applied. + +- `sourceFile`: Optional. The filename of the source file. + If omitted, sourceMapConsumer.file will be used, if it exists. + Otherwise an error will be thrown. + +- `sourceMapPath`: Optional. The dirname of the path to the SourceMap + to be applied. If relative, it is relative to the SourceMap. + + This parameter is needed when the two SourceMaps aren't in the same + directory, and the SourceMap to be applied contains relative source + paths. If so, those relative source paths need to be rewritten + relative to the SourceMap. + + If omitted, it is assumed that both SourceMaps are in the same directory, + thus not needing any rewriting. (Supplying `'.'` has the same effect.) + +#### SourceMapGenerator.prototype.toString() + +Renders the source map being generated to a string. + +```js +generator.toString(); +// '{"version":3,"sources":["module-one.scm"],"names":[],"mappings":"...snip...","file":"my-generated-javascript-file.js","sourceRoot":"http://example.com/app/js/"}' +``` + +### SourceNode + +SourceNodes provide a way to abstract over interpolating and/or concatenating +snippets of generated JavaScript source code, while maintaining the line and +column information associated between those snippets and the original source +code. This is useful as the final intermediate representation a compiler might +use before outputting the generated JS and source map. + +#### new SourceNode([line, column, source[, chunk[, name]]]) + +- `line`: The original line number associated with this source node, or null if + it isn't associated with an original line. The line number is 1-based. + +- `column`: The original column number associated with this source node, or null + if it isn't associated with an original column. The column number + is 0-based. + +- `source`: The original source's filename; null if no filename is provided. + +- `chunk`: Optional. Is immediately passed to `SourceNode.prototype.add`, see + below. + +- `name`: Optional. The original identifier. + +```js +var node = new SourceNode(1, 2, 'a.cpp', [ + new SourceNode(3, 4, 'b.cpp', 'extern int status;\n'), + new SourceNode(5, 6, 'c.cpp', 'std::string* make_string(size_t n);\n'), + new SourceNode(7, 8, 'd.cpp', 'int main(int argc, char** argv) {}\n'), +]); +``` + +#### SourceNode.fromStringWithSourceMap(code, sourceMapConsumer[, relativePath]) + +Creates a SourceNode from generated code and a SourceMapConsumer. + +- `code`: The generated code + +- `sourceMapConsumer` The SourceMap for the generated code + +- `relativePath` The optional path that relative sources in `sourceMapConsumer` + should be relative to. + +```js +var consumer = new SourceMapConsumer( + fs.readFileSync('path/to/my-file.js.map', 'utf8') +); +var node = SourceNode.fromStringWithSourceMap( + fs.readFileSync('path/to/my-file.js'), + consumer +); +``` + +#### SourceNode.prototype.add(chunk) + +Add a chunk of generated JS to this source node. + +- `chunk`: A string snippet of generated JS code, another instance of + `SourceNode`, or an array where each member is one of those things. + +```js +node.add(' + '); +node.add(otherNode); +node.add([leftHandOperandNode, ' + ', rightHandOperandNode]); +``` + +#### SourceNode.prototype.prepend(chunk) + +Prepend a chunk of generated JS to this source node. + +- `chunk`: A string snippet of generated JS code, another instance of + `SourceNode`, or an array where each member is one of those things. + +```js +node.prepend('/** Build Id: f783haef86324gf **/\n\n'); +``` + +#### SourceNode.prototype.setSourceContent(sourceFile, sourceContent) + +Set the source content for a source file. This will be added to the +`SourceMap` in the `sourcesContent` field. + +- `sourceFile`: The filename of the source file + +- `sourceContent`: The content of the source file + +```js +node.setSourceContent( + 'module-one.scm', + fs.readFileSync('path/to/module-one.scm') +); +``` + +#### SourceNode.prototype.walk(fn) + +Walk over the tree of JS snippets in this node and its children. The walking +function is called once for each snippet of JS and is passed that snippet and +the its original associated source's line/column location. + +- `fn`: The traversal function. + +```js +var node = new SourceNode(1, 2, 'a.js', [ + new SourceNode(3, 4, 'b.js', 'uno'), + 'dos', + ['tres', new SourceNode(5, 6, 'c.js', 'quatro')], +]); + +node.walk(function (code, loc) { + console.log('WALK:', code, loc); +}); +// WALK: uno { source: 'b.js', line: 3, column: 4, name: null } +// WALK: dos { source: 'a.js', line: 1, column: 2, name: null } +// WALK: tres { source: 'a.js', line: 1, column: 2, name: null } +// WALK: quatro { source: 'c.js', line: 5, column: 6, name: null } +``` + +#### SourceNode.prototype.walkSourceContents(fn) + +Walk over the tree of SourceNodes. The walking function is called for each +source file content and is passed the filename and source content. + +- `fn`: The traversal function. + +```js +var a = new SourceNode(1, 2, 'a.js', 'generated from a'); +a.setSourceContent('a.js', 'original a'); +var b = new SourceNode(1, 2, 'b.js', 'generated from b'); +b.setSourceContent('b.js', 'original b'); +var c = new SourceNode(1, 2, 'c.js', 'generated from c'); +c.setSourceContent('c.js', 'original c'); + +var node = new SourceNode(null, null, null, [a, b, c]); +node.walkSourceContents(function (source, contents) { + console.log('WALK:', source, ':', contents); +}); +// WALK: a.js : original a +// WALK: b.js : original b +// WALK: c.js : original c +``` + +#### SourceNode.prototype.join(sep) + +Like `Array.prototype.join` except for SourceNodes. Inserts the separator +between each of this source node's children. + +- `sep`: The separator. + +```js +var lhs = new SourceNode(1, 2, 'a.rs', 'my_copy'); +var operand = new SourceNode(3, 4, 'a.rs', '='); +var rhs = new SourceNode(5, 6, 'a.rs', 'orig.clone()'); + +var node = new SourceNode(null, null, null, [lhs, operand, rhs]); +var joinedNode = node.join(' '); +``` + +#### SourceNode.prototype.replaceRight(pattern, replacement) + +Call `String.prototype.replace` on the very right-most source snippet. Useful +for trimming white space from the end of a source node, etc. + +- `pattern`: The pattern to replace. + +- `replacement`: The thing to replace the pattern with. + +```js +// Trim trailing white space. +node.replaceRight(/\s*$/, ''); +``` + +#### SourceNode.prototype.toString() + +Return the string representation of this source node. Walks over the tree and +concatenates all the various snippets together to one string. + +```js +var node = new SourceNode(1, 2, 'a.js', [ + new SourceNode(3, 4, 'b.js', 'uno'), + 'dos', + ['tres', new SourceNode(5, 6, 'c.js', 'quatro')], +]); + +node.toString(); +// 'unodostresquatro' +``` + +#### SourceNode.prototype.toStringWithSourceMap([startOfSourceMap]) + +Returns the string representation of this tree of source nodes, plus a +SourceMapGenerator which contains all the mappings between the generated and +original sources. + +The arguments are the same as those to `new SourceMapGenerator`. + +```js +var node = new SourceNode(1, 2, 'a.js', [ + new SourceNode(3, 4, 'b.js', 'uno'), + 'dos', + ['tres', new SourceNode(5, 6, 'c.js', 'quatro')], +]); + +node.toStringWithSourceMap({ file: 'my-output-file.js' }); +// { code: 'unodostresquatro', +// map: [object SourceMapGenerator] } +``` diff --git a/dg-ui/node_modules/source-map-js/lib/array-set.js b/dg-ui/node_modules/source-map-js/lib/array-set.js new file mode 100644 index 0000000..7675e45 --- /dev/null +++ b/dg-ui/node_modules/source-map-js/lib/array-set.js @@ -0,0 +1,123 @@ +/* -*- Mode: js; js-indent-level: 2; -*- */ +/* + * Copyright 2011 Mozilla Foundation and contributors + * Licensed under the New BSD license. See LICENSE or: + * http://opensource.org/licenses/BSD-3-Clause + */ + +var util = require('./util'); +var has = Object.prototype.hasOwnProperty; +var hasNativeMap = typeof Map !== 'undefined'; + +/** + * A data structure which is a combination of an array and a set. Adding a new + * member is O(1), testing for membership is O(1), and finding the index of an + * element is O(1). Removing elements from the set is not supported. Only + * strings are supported for membership. + */ +function ArraySet() { + this._array = []; + this._set = hasNativeMap ? new Map() : Object.create(null); +} + +/** + * Static method for creating ArraySet instances from an existing array. + */ +ArraySet.fromArray = function ArraySet_fromArray(aArray, aAllowDuplicates) { + var set = new ArraySet(); + for (var i = 0, len = aArray.length; i < len; i++) { + set.add(aArray[i], aAllowDuplicates); + } + return set; +}; + +/** + * Return how many unique items are in this ArraySet. If duplicates have been + * added, than those do not count towards the size. + * + * @returns Number + */ +ArraySet.prototype.size = function ArraySet_size() { + return hasNativeMap + ? this._set.size + : Object.getOwnPropertyNames(this._set).length; +}; + +/** + * Add the given string to this set. + * + * @param String aStr + */ +ArraySet.prototype.add = function ArraySet_add(aStr, aAllowDuplicates) { + var sStr = hasNativeMap ? aStr : util.toSetString(aStr); + var isDuplicate = hasNativeMap ? this.has(aStr) : has.call(this._set, sStr); + var idx = this._array.length; + if (!isDuplicate || aAllowDuplicates) { + this._array.push(aStr); + } + if (!isDuplicate) { + if (hasNativeMap) { + this._set.set(aStr, idx); + } else { + this._set[sStr] = idx; + } + } +}; + +/** + * Is the given string a member of this set? + * + * @param String aStr + */ +ArraySet.prototype.has = function ArraySet_has(aStr) { + if (hasNativeMap) { + return this._set.has(aStr); + } else { + var sStr = util.toSetString(aStr); + return has.call(this._set, sStr); + } +}; + +/** + * What is the index of the given string in the array? + * + * @param String aStr + */ +ArraySet.prototype.indexOf = function ArraySet_indexOf(aStr) { + if (hasNativeMap) { + var idx = this._set.get(aStr); + if (idx >= 0) { + return idx; + } + } else { + var sStr = util.toSetString(aStr); + if (has.call(this._set, sStr)) { + return this._set[sStr]; + } + } + + throw new Error('"' + aStr + '" is not in the set.'); +}; + +/** + * What is the element at the given index? + * + * @param Number aIdx + */ +ArraySet.prototype.at = function ArraySet_at(aIdx) { + if (aIdx >= 0 && aIdx < this._array.length) { + return this._array[aIdx]; + } + throw new Error('No element indexed by ' + aIdx); +}; + +/** + * Returns the array representation of this set (which has the proper indices + * indicated by indexOf). Note that this is a copy of the internal array used + * for storing the members so that no one can mess with internal state. + */ +ArraySet.prototype.toArray = function ArraySet_toArray() { + return this._array.slice(); +}; + +exports.ArraySet = ArraySet; diff --git a/dg-ui/node_modules/source-map-js/lib/base64-vlq.js b/dg-ui/node_modules/source-map-js/lib/base64-vlq.js new file mode 100644 index 0000000..9026708 --- /dev/null +++ b/dg-ui/node_modules/source-map-js/lib/base64-vlq.js @@ -0,0 +1,136 @@ +/* -*- Mode: js; js-indent-level: 2; -*- */ +/* + * Copyright 2011 Mozilla Foundation and contributors + * Licensed under the New BSD license. See LICENSE or: + * http://opensource.org/licenses/BSD-3-Clause + * + * Based on the Base 64 VLQ implementation in Closure Compiler: + * https://code.google.com/p/closure-compiler/source/browse/trunk/src/com/google/debugging/sourcemap/Base64VLQ.java + * + * Copyright 2011 The Closure Compiler Authors. All rights reserved. + * Redistribution and use in source and binary forms, with or without + * modification, are permitted provided that the following conditions are + * met: + * + * * Redistributions of source code must retain the above copyright + * notice, this list of conditions and the following disclaimer. + * * Redistributions in binary form must reproduce the above + * copyright notice, this list of conditions and the following + * disclaimer in the documentation and/or other materials provided + * with the distribution. + * * Neither the name of Google Inc. nor the names of its + * contributors may be used to endorse or promote products derived + * from this software without specific prior written permission. + * + * THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS + * "AS IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT + * LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR + * A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT + * OWNER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, + * SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT + * LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, + * DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY + * THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT + * (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE + * OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE. + */ + +var base64 = require('./base64'); + +// A single base 64 digit can contain 6 bits of data. For the base 64 variable +// length quantities we use in the source map spec, the first bit is the sign, +// the next four bits are the actual value, and the 6th bit is the +// continuation bit. The continuation bit tells us whether there are more +// digits in this value following this digit. +// +// Continuation +// | Sign +// | | +// V V +// 101011 + +var VLQ_BASE_SHIFT = 5; + +// binary: 100000 +var VLQ_BASE = 1 << VLQ_BASE_SHIFT; + +// binary: 011111 +var VLQ_BASE_MASK = VLQ_BASE - 1; + +// binary: 100000 +var VLQ_CONTINUATION_BIT = VLQ_BASE; + +/** + * Converts from a two-complement value to a value where the sign bit is + * placed in the least significant bit. For example, as decimals: + * 1 becomes 2 (10 binary), -1 becomes 3 (11 binary) + * 2 becomes 4 (100 binary), -2 becomes 5 (101 binary) + */ +function toVLQSigned(aValue) { + return aValue < 0 ? (-aValue << 1) + 1 : (aValue << 1) + 0; +} + +/** + * Converts to a two-complement value from a value where the sign bit is + * placed in the least significant bit. For example, as decimals: + * 2 (10 binary) becomes 1, 3 (11 binary) becomes -1 + * 4 (100 binary) becomes 2, 5 (101 binary) becomes -2 + */ +function fromVLQSigned(aValue) { + var isNegative = (aValue & 1) === 1; + var shifted = aValue >> 1; + return isNegative ? -shifted : shifted; +} + +/** + * Returns the base 64 VLQ encoded value. + */ +exports.encode = function base64VLQ_encode(aValue) { + var encoded = ''; + var digit; + + var vlq = toVLQSigned(aValue); + + do { + digit = vlq & VLQ_BASE_MASK; + vlq >>>= VLQ_BASE_SHIFT; + if (vlq > 0) { + // There are still more digits in this value, so we must make sure the + // continuation bit is marked. + digit |= VLQ_CONTINUATION_BIT; + } + encoded += base64.encode(digit); + } while (vlq > 0); + + return encoded; +}; + +/** + * Decodes the next base 64 VLQ value from the given string and returns the + * value and the rest of the string via the out parameter. + */ +exports.decode = function base64VLQ_decode(aStr, aIndex, aOutParam) { + var strLen = aStr.length; + var result = 0; + var shift = 0; + var continuation, digit; + + do { + if (aIndex >= strLen) { + throw new Error('Expected more digits in base 64 VLQ value.'); + } + + digit = base64.decode(aStr.charCodeAt(aIndex++)); + if (digit === -1) { + throw new Error('Invalid base64 digit: ' + aStr.charAt(aIndex - 1)); + } + + continuation = !!(digit & VLQ_CONTINUATION_BIT); + digit &= VLQ_BASE_MASK; + result = result + (digit << shift); + shift += VLQ_BASE_SHIFT; + } while (continuation); + + aOutParam.value = fromVLQSigned(result); + aOutParam.rest = aIndex; +}; diff --git a/dg-ui/node_modules/source-map-js/lib/base64.js b/dg-ui/node_modules/source-map-js/lib/base64.js new file mode 100644 index 0000000..7e492bd --- /dev/null +++ b/dg-ui/node_modules/source-map-js/lib/base64.js @@ -0,0 +1,68 @@ +/* -*- Mode: js; js-indent-level: 2; -*- */ +/* + * Copyright 2011 Mozilla Foundation and contributors + * Licensed under the New BSD license. See LICENSE or: + * http://opensource.org/licenses/BSD-3-Clause + */ + +var intToCharMap = + 'ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789+/'.split(''); + +/** + * Encode an integer in the range of 0 to 63 to a single base 64 digit. + */ +exports.encode = function (number) { + if (0 <= number && number < intToCharMap.length) { + return intToCharMap[number]; + } + throw new TypeError('Must be between 0 and 63: ' + number); +}; + +/** + * Decode a single base 64 character code digit to an integer. Returns -1 on + * failure. + */ +exports.decode = function (charCode) { + var bigA = 65; // 'A' + var bigZ = 90; // 'Z' + + var littleA = 97; // 'a' + var littleZ = 122; // 'z' + + var zero = 48; // '0' + var nine = 57; // '9' + + var plus = 43; // '+' + var slash = 47; // '/' + + var littleOffset = 26; + var numberOffset = 52; + + // 0 - 25: ABCDEFGHIJKLMNOPQRSTUVWXYZ + if (bigA <= charCode && charCode <= bigZ) { + return charCode - bigA; + } + + // 26 - 51: abcdefghijklmnopqrstuvwxyz + if (littleA <= charCode && charCode <= littleZ) { + return charCode - littleA + littleOffset; + } + + // 52 - 61: 0123456789 + if (zero <= charCode && charCode <= nine) { + return charCode - zero + numberOffset; + } + + // 62: + + if (charCode == plus) { + return 62; + } + + // 63: / + if (charCode == slash) { + return 63; + } + + // Invalid base64 digit. + return -1; +}; diff --git a/dg-ui/node_modules/source-map-js/lib/binary-search.js b/dg-ui/node_modules/source-map-js/lib/binary-search.js new file mode 100644 index 0000000..794f7c1 --- /dev/null +++ b/dg-ui/node_modules/source-map-js/lib/binary-search.js @@ -0,0 +1,115 @@ +/* -*- Mode: js; js-indent-level: 2; -*- */ +/* + * Copyright 2011 Mozilla Foundation and contributors + * Licensed under the New BSD license. See LICENSE or: + * http://opensource.org/licenses/BSD-3-Clause + */ + +exports.GREATEST_LOWER_BOUND = 1; +exports.LEAST_UPPER_BOUND = 2; + +/** + * Recursive implementation of binary search. + * + * @param aLow Indices here and lower do not contain the needle. + * @param aHigh Indices here and higher do not contain the needle. + * @param aNeedle The element being searched for. + * @param aHaystack The non-empty array being searched. + * @param aCompare Function which takes two elements and returns -1, 0, or 1. + * @param aBias Either 'binarySearch.GREATEST_LOWER_BOUND' or + * 'binarySearch.LEAST_UPPER_BOUND'. Specifies whether to return the + * closest element that is smaller than or greater than the one we are + * searching for, respectively, if the exact element cannot be found. + */ +function recursiveSearch(aLow, aHigh, aNeedle, aHaystack, aCompare, aBias) { + // This function terminates when one of the following is true: + // + // 1. We find the exact element we are looking for. + // + // 2. We did not find the exact element, but we can return the index of + // the next-closest element. + // + // 3. We did not find the exact element, and there is no next-closest + // element than the one we are searching for, so we return -1. + var mid = Math.floor((aHigh - aLow) / 2) + aLow; + var cmp = aCompare(aNeedle, aHaystack[mid], true); + if (cmp === 0) { + // Found the element we are looking for. + return mid; + } else if (cmp > 0) { + // Our needle is greater than aHaystack[mid]. + if (aHigh - mid > 1) { + // The element is in the upper half. + return recursiveSearch(mid, aHigh, aNeedle, aHaystack, aCompare, aBias); + } + + // The exact needle element was not found in this haystack. Determine if + // we are in termination case (3) or (2) and return the appropriate thing. + if (aBias == exports.LEAST_UPPER_BOUND) { + return aHigh < aHaystack.length ? aHigh : -1; + } else { + return mid; + } + } else { + // Our needle is less than aHaystack[mid]. + if (mid - aLow > 1) { + // The element is in the lower half. + return recursiveSearch(aLow, mid, aNeedle, aHaystack, aCompare, aBias); + } + + // we are in termination case (3) or (2) and return the appropriate thing. + if (aBias == exports.LEAST_UPPER_BOUND) { + return mid; + } else { + return aLow < 0 ? -1 : aLow; + } + } +} + +/** + * This is an implementation of binary search which will always try and return + * the index of the closest element if there is no exact hit. This is because + * mappings between original and generated line/col pairs are single points, + * and there is an implicit region between each of them, so a miss just means + * that you aren't on the very start of a region. + * + * @param aNeedle The element you are looking for. + * @param aHaystack The array that is being searched. + * @param aCompare A function which takes the needle and an element in the + * array and returns -1, 0, or 1 depending on whether the needle is less + * than, equal to, or greater than the element, respectively. + * @param aBias Either 'binarySearch.GREATEST_LOWER_BOUND' or + * 'binarySearch.LEAST_UPPER_BOUND'. Specifies whether to return the + * closest element that is smaller than or greater than the one we are + * searching for, respectively, if the exact element cannot be found. + * Defaults to 'binarySearch.GREATEST_LOWER_BOUND'. + */ +exports.search = function search(aNeedle, aHaystack, aCompare, aBias) { + if (aHaystack.length === 0) { + return -1; + } + + var index = recursiveSearch( + -1, + aHaystack.length, + aNeedle, + aHaystack, + aCompare, + aBias || exports.GREATEST_LOWER_BOUND + ); + if (index < 0) { + return -1; + } + + // We have found either the exact element, or the next-closest element than + // the one we are searching for. However, there may be more than one such + // element. Make sure we always return the smallest of these. + while (index - 1 >= 0) { + if (aCompare(aHaystack[index], aHaystack[index - 1], true) !== 0) { + break; + } + --index; + } + + return index; +}; diff --git a/dg-ui/node_modules/source-map-js/lib/mapping-list.js b/dg-ui/node_modules/source-map-js/lib/mapping-list.js new file mode 100644 index 0000000..08c35c6 --- /dev/null +++ b/dg-ui/node_modules/source-map-js/lib/mapping-list.js @@ -0,0 +1,84 @@ +/* -*- Mode: js; js-indent-level: 2; -*- */ +/* + * Copyright 2014 Mozilla Foundation and contributors + * Licensed under the New BSD license. See LICENSE or: + * http://opensource.org/licenses/BSD-3-Clause + */ + +var util = require('./util'); + +/** + * Determine whether mappingB is after mappingA with respect to generated + * position. + */ +function generatedPositionAfter(mappingA, mappingB) { + // Optimized for most common case + var lineA = mappingA.generatedLine; + var lineB = mappingB.generatedLine; + var columnA = mappingA.generatedColumn; + var columnB = mappingB.generatedColumn; + return ( + lineB > lineA || + (lineB == lineA && columnB >= columnA) || + util.compareByGeneratedPositionsInflated(mappingA, mappingB) <= 0 + ); +} + +/** + * A data structure to provide a sorted view of accumulated mappings in a + * performance conscious manner. It trades a neglibable overhead in general + * case for a large speedup in case of mappings being added in order. + */ +function MappingList() { + this._array = []; + this._sorted = true; + // Serves as infimum + this._last = { generatedLine: -1, generatedColumn: 0 }; +} + +/** + * Iterate through internal items. This method takes the same arguments that + * `Array.prototype.forEach` takes. + * + * NOTE: The order of the mappings is NOT guaranteed. + */ +MappingList.prototype.unsortedForEach = function MappingList_forEach( + aCallback, + aThisArg +) { + this._array.forEach(aCallback, aThisArg); +}; + +/** + * Add the given source mapping. + * + * @param Object aMapping + */ +MappingList.prototype.add = function MappingList_add(aMapping) { + if (generatedPositionAfter(this._last, aMapping)) { + this._last = aMapping; + this._array.push(aMapping); + } else { + this._sorted = false; + this._array.push(aMapping); + } +}; + +/** + * Returns the flat, sorted array of mappings. The mappings are sorted by + * generated position. + * + * WARNING: This method returns internal data without copying, for + * performance. The return value must NOT be mutated, and should be treated as + * an immutable borrow. If you want to take ownership, you must make your own + * copy. + */ +MappingList.prototype.toArray = function MappingList_toArray() { + if (!this._sorted) { + this._array.sort(util.compareByGeneratedPositionsInflated); + this._sorted = true; + } + return this._array; +}; + +exports.MappingList = MappingList; diff --git a/dg-ui/node_modules/source-map-js/lib/quick-sort.js b/dg-ui/node_modules/source-map-js/lib/quick-sort.js new file mode 100644 index 0000000..a98cdcf --- /dev/null +++ b/dg-ui/node_modules/source-map-js/lib/quick-sort.js @@ -0,0 +1,211 @@ +/* -*- Mode: js; js-indent-level: 2; -*- */ +/* + * Copyright 2011 Mozilla Foundation and contributors + * Licensed under the New BSD license. See LICENSE or: + * http://opensource.org/licenses/BSD-3-Clause + */ + +// It turns out that some (most?) JavaScript engines don't self-host +// `Array.prototype.sort`. This makes sense because C++ will likely remain +// faster than JS when doing raw CPU-intensive sorting. However, when using a +// custom comparator function, calling back and forth between the VM's C++ and +// JIT'd JS is rather slow *and* loses JIT type information, resulting in +// worse generated code for the comparator function than would be optimal. In +// fact, when sorting with a comparator, these costs outweigh the benefits of +// sorting in C++. By using our own JS-implemented Quick Sort (below), we get +// a ~3500ms mean speed-up in `bench/bench.html`. +// +// That only pays off while the JIT can inline the comparator, i.e. while the +// comparator call site in the sort sees a single comparator. The library sorts +// with four different comparators, so each one gets its own copy of the sort +// function (`doQuickSort0` .. `doQuickSort3` below). The copies have to be +// separate function literals in the source: closures created from the same +// literal share type feedback, and so did copies cloned with `new Function` +// from identical source text. Cloning with `new Function` also violates +// Content Security Policies that don't allow 'unsafe-eval', so the copies are +// written out by hand. Keep them identical. See: +// https://github.com/7rulnik/source-map-js/pull/29 +// https://github.com/7rulnik/source-map-js/issues/81 + +/** + * Swap the elements indexed by `x` and `y` in the array `ary`. + * + * @param {Array} ary + * The array. + * @param {Number} x + * The index of the first item. + * @param {Number} y + * The index of the second item. + */ +function swap(ary, x, y) { + var temp = ary[x]; + ary[x] = ary[y]; + ary[y] = temp; +} + +/** + * Returns a random integer within the range `low .. high` inclusive. + * + * @param {Number} low + * The lower bound on the range. + * @param {Number} high + * The upper bound on the range. + */ +function randomIntInRange(low, high) { + return Math.round(low + Math.random() * (high - low)); +} + +/** + * The Quick Sort algorithm. + * + * @param {Array} ary + * An array to sort. + * @param {function} comparator + * Function to use to compare two items. + * @param {Number} p + * Start index of the array + * @param {Number} r + * End index of the array + */ +function doQuickSort0(ary, comparator, p, r) { + // If our lower bound is less than our upper bound, we (1) partition the + // array into two pieces and (2) recurse on each half. If it is not, this is + // the empty array and our base case. + + if (p < r) { + // (1) Partitioning. + // + // The partitioning chooses a pivot between `p` and `r` and moves all + // elements that are less than or equal to the pivot to the before it, and + // all the elements that are greater than it after it. The effect is that + // once partition is done, the pivot is in the exact place it will be when + // the array is put in sorted order, and it will not need to be moved + // again. This runs in O(n) time. + + // Always choose a random pivot so that an input array which is reverse + // sorted does not cause O(n^2) running time. + var pivotIndex = randomIntInRange(p, r); + var i = p - 1; + + swap(ary, pivotIndex, r); + var pivot = ary[r]; + + // Immediately after `j` is incremented in this loop, the following hold + // true: + // + // * Every element in `ary[p .. i]` is less than or equal to the pivot. + // + // * Every element in `ary[i+1 .. j-1]` is greater than the pivot. + for (var j = p; j < r; j++) { + if (comparator(ary[j], pivot, false) <= 0) { + i += 1; + swap(ary, i, j); + } + } + + swap(ary, i + 1, j); + var q = i + 1; + + // (2) Recurse on each half. + + doQuickSort0(ary, comparator, p, q - 1); + doQuickSort0(ary, comparator, q + 1, r); + } +} + +// Identical copies of `doQuickSort0`, see the comment at the top of the file. + +function doQuickSort1(ary, comparator, p, r) { + if (p < r) { + var pivotIndex = randomIntInRange(p, r); + var i = p - 1; + + swap(ary, pivotIndex, r); + var pivot = ary[r]; + + for (var j = p; j < r; j++) { + if (comparator(ary[j], pivot, false) <= 0) { + i += 1; + swap(ary, i, j); + } + } + + swap(ary, i + 1, j); + var q = i + 1; + + doQuickSort1(ary, comparator, p, q - 1); + doQuickSort1(ary, comparator, q + 1, r); + } +} + +function doQuickSort2(ary, comparator, p, r) { + if (p < r) { + var pivotIndex = randomIntInRange(p, r); + var i = p - 1; + + swap(ary, pivotIndex, r); + var pivot = ary[r]; + + for (var j = p; j < r; j++) { + if (comparator(ary[j], pivot, false) <= 0) { + i += 1; + swap(ary, i, j); + } + } + + swap(ary, i + 1, j); + var q = i + 1; + + doQuickSort2(ary, comparator, p, q - 1); + doQuickSort2(ary, comparator, q + 1, r); + } +} + +function doQuickSort3(ary, comparator, p, r) { + if (p < r) { + var pivotIndex = randomIntInRange(p, r); + var i = p - 1; + + swap(ary, pivotIndex, r); + var pivot = ary[r]; + + for (var j = p; j < r; j++) { + if (comparator(ary[j], pivot, false) <= 0) { + i += 1; + swap(ary, i, j); + } + } + + swap(ary, i + 1, j); + var q = i + 1; + + doQuickSort3(ary, comparator, p, q - 1); + doQuickSort3(ary, comparator, q + 1, r); + } +} + +var sortCopies = [doQuickSort0, doQuickSort1, doQuickSort2, doQuickSort3]; +var nextSortCopy = 0; +var sortCache = new WeakMap(); + +/** + * Sort the given array in-place with the given comparator function. + * + * @param {Array} ary + * An array to sort. + * @param {function} comparator + * Function to use to compare two items. + * @param {Number} start + * Index to start sorting from; items before it are left untouched. + */ +exports.quickSort = function (ary, comparator, start = 0) { + var doQuickSort = sortCache.get(comparator); + if (doQuickSort === undefined) { + // Each comparator claims the next free copy. Should there ever be more + // comparators than copies, the extra ones share the last copy: still + // correct, just slower for the comparators sharing it. + doQuickSort = sortCopies[Math.min(nextSortCopy++, sortCopies.length - 1)]; + sortCache.set(comparator, doQuickSort); + } + doQuickSort(ary, comparator, start, ary.length - 1); +}; diff --git a/dg-ui/node_modules/source-map-js/lib/source-map-consumer.d.ts b/dg-ui/node_modules/source-map-js/lib/source-map-consumer.d.ts new file mode 100644 index 0000000..744bda7 --- /dev/null +++ b/dg-ui/node_modules/source-map-js/lib/source-map-consumer.d.ts @@ -0,0 +1 @@ +export { SourceMapConsumer } from '..'; diff --git a/dg-ui/node_modules/source-map-js/lib/source-map-consumer.js b/dg-ui/node_modules/source-map-js/lib/source-map-consumer.js new file mode 100644 index 0000000..af2798b --- /dev/null +++ b/dg-ui/node_modules/source-map-js/lib/source-map-consumer.js @@ -0,0 +1,1314 @@ +/* -*- Mode: js; js-indent-level: 2; -*- */ +/* + * Copyright 2011 Mozilla Foundation and contributors + * Licensed under the New BSD license. See LICENSE or: + * http://opensource.org/licenses/BSD-3-Clause + */ + +var util = require('./util'); +var binarySearch = require('./binary-search'); +var ArraySet = require('./array-set').ArraySet; +var base64VLQ = require('./base64-vlq'); +var quickSort = require('./quick-sort').quickSort; + +// Upper bound for a section's `offset.line` in an indexed source map. A flat +// map spends one ';' per generated line, so a tiny indexed map with a huge +// offset.line turns into a huge amount of work and memory once its mappings +// are copied into a SourceMapGenerator (CVE-2026-93749). Ten million lines is +// far beyond any real generated file. Columns are VLQ-encoded as deltas and +// don't amplify, so they only need to be valid integers. +var MAX_SECTION_OFFSET_LINE = 1e7; + +function SourceMapConsumer(aSourceMap, aSourceMapURL) { + var sourceMap = aSourceMap; + if (typeof aSourceMap === 'string') { + sourceMap = util.parseSourceMapInput(aSourceMap); + } + + return sourceMap.sections != null + ? new IndexedSourceMapConsumer(sourceMap, aSourceMapURL) + : new BasicSourceMapConsumer(sourceMap, aSourceMapURL); +} + +SourceMapConsumer.fromSourceMap = function (aSourceMap, aSourceMapURL) { + return BasicSourceMapConsumer.fromSourceMap(aSourceMap, aSourceMapURL); +}; + +/** + * The version of the source mapping spec that we are consuming. + */ +SourceMapConsumer.prototype._version = 3; + +// `__generatedMappings` and `__originalMappings` are arrays that hold the +// parsed mapping coordinates from the source map's "mappings" attribute. They +// are lazily instantiated, accessed via the `_generatedMappings` and +// `_originalMappings` getters respectively, and we only parse the mappings +// and create these arrays once queried for a source location. We jump through +// these hoops because there can be many thousands of mappings, and parsing +// them is expensive, so we only want to do it if we must. +// +// Each object in the arrays is of the form: +// +// { +// generatedLine: The line number in the generated code, +// generatedColumn: The column number in the generated code, +// source: The path to the original source file that generated this +// chunk of code, +// originalLine: The line number in the original source that +// corresponds to this chunk of generated code, +// originalColumn: The column number in the original source that +// corresponds to this chunk of generated code, +// name: The name of the original symbol which generated this chunk of +// code. +// } +// +// All properties except for `generatedLine` and `generatedColumn` can be +// `null`. +// +// `_generatedMappings` is ordered by the generated positions. +// +// `_originalMappings` is ordered by the original positions. + +SourceMapConsumer.prototype.__generatedMappings = null; +Object.defineProperty(SourceMapConsumer.prototype, '_generatedMappings', { + configurable: true, + enumerable: true, + get: function () { + if (!this.__generatedMappings) { + this._parseMappings(this._mappings, this.sourceRoot); + } + + return this.__generatedMappings; + }, +}); + +SourceMapConsumer.prototype.__originalMappings = null; +Object.defineProperty(SourceMapConsumer.prototype, '_originalMappings', { + configurable: true, + enumerable: true, + get: function () { + if (!this.__originalMappings) { + this._parseMappings(this._mappings, this.sourceRoot); + } + + return this.__originalMappings; + }, +}); + +SourceMapConsumer.prototype._charIsMappingSeparator = + function SourceMapConsumer_charIsMappingSeparator(aStr, index) { + var c = aStr.charAt(index); + return c === ';' || c === ','; + }; + +/** + * Parse the mappings in a string in to a data structure which we can easily + * query (the ordered arrays in the `this.__generatedMappings` and + * `this.__originalMappings` properties). + */ +SourceMapConsumer.prototype._parseMappings = + function SourceMapConsumer_parseMappings(aStr, aSourceRoot) { + throw new Error('Subclasses must implement _parseMappings'); + }; + +SourceMapConsumer.GENERATED_ORDER = 1; +SourceMapConsumer.ORIGINAL_ORDER = 2; + +SourceMapConsumer.GREATEST_LOWER_BOUND = 1; +SourceMapConsumer.LEAST_UPPER_BOUND = 2; + +/** + * Iterate over each mapping between an original source/line/column and a + * generated line/column in this source map. + * + * @param Function aCallback + * The function that is called with each mapping. + * @param Object aContext + * Optional. If specified, this object will be the value of `this` every + * time that `aCallback` is called. + * @param aOrder + * Either `SourceMapConsumer.GENERATED_ORDER` or + * `SourceMapConsumer.ORIGINAL_ORDER`. Specifies whether you want to + * iterate over the mappings sorted by the generated file's line/column + * order or the original's source/line/column order, respectively. Defaults to + * `SourceMapConsumer.GENERATED_ORDER`. + */ +SourceMapConsumer.prototype.eachMapping = + function SourceMapConsumer_eachMapping(aCallback, aContext, aOrder) { + var context = aContext || null; + var order = aOrder || SourceMapConsumer.GENERATED_ORDER; + + var mappings; + switch (order) { + case SourceMapConsumer.GENERATED_ORDER: + mappings = this._generatedMappings; + break; + case SourceMapConsumer.ORIGINAL_ORDER: + mappings = this._originalMappings; + break; + default: + throw new Error('Unknown order of iteration.'); + } + + var sourceRoot = this.sourceRoot; + var boundCallback = aCallback.bind(context); + var names = this._names; + var sources = this._sources; + var sourceMapURL = this._sourceMapURL; + + for (var i = 0, n = mappings.length; i < n; i++) { + var mapping = mappings[i]; + var source = mapping.source === null ? null : sources.at(mapping.source); + if (source !== null) { + source = util.computeSourceURL(sourceRoot, source, sourceMapURL); + } + boundCallback({ + source: source, + generatedLine: mapping.generatedLine, + generatedColumn: mapping.generatedColumn, + originalLine: mapping.originalLine, + originalColumn: mapping.originalColumn, + name: mapping.name === null ? null : names.at(mapping.name), + }); + } + }; + +/** + * Returns all generated line and column information for the original source, + * line, and column provided. If no column is provided, returns all mappings + * corresponding to a either the line we are searching for or the next + * closest line that has any mappings. Otherwise, returns all mappings + * corresponding to the given line and either the column we are searching for + * or the next closest column that has any offsets. + * + * The only argument is an object with the following properties: + * + * - source: The filename of the original source. + * - line: The line number in the original source. The line number is 1-based. + * - column: Optional. the column number in the original source. + * The column number is 0-based. + * + * and an array of objects is returned, each with the following properties: + * + * - line: The line number in the generated source, or null. The + * line number is 1-based. + * - column: The column number in the generated source, or null. + * The column number is 0-based. + */ +SourceMapConsumer.prototype.allGeneratedPositionsFor = + function SourceMapConsumer_allGeneratedPositionsFor(aArgs) { + var line = util.getArg(aArgs, 'line'); + + // When there is no exact match, BasicSourceMapConsumer.prototype._findMapping + // returns the index of the closest mapping less than the needle. By + // setting needle.originalColumn to 0, we thus find the last mapping for + // the given line, provided such a mapping exists. + var needle = { + source: util.getArg(aArgs, 'source'), + originalLine: line, + originalColumn: util.getArg(aArgs, 'column', 0), + }; + + needle.source = this._findSourceIndex(needle.source); + if (needle.source < 0) { + return []; + } + + var mappings = []; + + var index = this._findMapping( + needle, + this._originalMappings, + 'originalLine', + 'originalColumn', + util.compareByOriginalPositions, + binarySearch.LEAST_UPPER_BOUND + ); + if (index >= 0) { + var mapping = this._originalMappings[index]; + + if (aArgs.column === undefined) { + var originalLine = mapping.originalLine; + + // Iterate until either we run out of mappings, or we run into + // a mapping for a different source or line than the one we found. + // Since mappings are sorted, this is guaranteed to find all mappings + // for the line we found. The source check also stops the search from + // continuing into the next source's mappings when this source has + // none at or after the requested line. + while ( + mapping && + mapping.source === needle.source && + mapping.originalLine === originalLine + ) { + mappings.push({ + line: util.getArg(mapping, 'generatedLine', null), + column: util.getArg(mapping, 'generatedColumn', null), + lastColumn: util.getArg(mapping, 'lastGeneratedColumn', null), + }); + + mapping = this._originalMappings[++index]; + } + } else { + var originalColumn = mapping.originalColumn; + + // Iterate until either we run out of mappings, or we run into + // a mapping for a different source or line than the one we were + // searching for. Since mappings are sorted, this is guaranteed to find + // all mappings for the line we are searching for. + while ( + mapping && + mapping.source === needle.source && + mapping.originalLine === line && + mapping.originalColumn == originalColumn + ) { + mappings.push({ + line: util.getArg(mapping, 'generatedLine', null), + column: util.getArg(mapping, 'generatedColumn', null), + lastColumn: util.getArg(mapping, 'lastGeneratedColumn', null), + }); + + mapping = this._originalMappings[++index]; + } + } + } + + return mappings; + }; + +exports.SourceMapConsumer = SourceMapConsumer; + +/** + * A BasicSourceMapConsumer instance represents a parsed source map which we can + * query for information about the original file positions by giving it a file + * position in the generated source. + * + * The first parameter is the raw source map (either as a JSON string, or + * already parsed to an object). According to the spec, source maps have the + * following attributes: + * + * - version: Which version of the source map spec this map is following. + * - sources: An array of URLs to the original source files. + * - names: An array of identifiers which can be referrenced by individual mappings. + * - sourceRoot: Optional. The URL root from which all sources are relative. + * - sourcesContent: Optional. An array of contents of the original source files. + * - mappings: A string of base64 VLQs which contain the actual mappings. + * - file: Optional. The generated file this source map is associated with. + * + * Here is an example source map, taken from the source map spec[0]: + * + * { + * version : 3, + * file: "out.js", + * sourceRoot : "", + * sources: ["foo.js", "bar.js"], + * names: ["src", "maps", "are", "fun"], + * mappings: "AA,AB;;ABCDE;" + * } + * + * The second parameter, if given, is a string whose value is the URL + * at which the source map was found. This URL is used to compute the + * sources array. + * + * [0]: https://docs.google.com/document/d/1U1RGAehQwRypUTovF1KRlpiOFze0b-_2gc6fAH0KY0k/edit?pli=1# + */ +function BasicSourceMapConsumer(aSourceMap, aSourceMapURL) { + var sourceMap = aSourceMap; + if (typeof aSourceMap === 'string') { + sourceMap = util.parseSourceMapInput(aSourceMap); + } + + var version = util.getArg(sourceMap, 'version'); + var sources = util.getArg(sourceMap, 'sources'); + // Sass 3.3 leaves out the 'names' array, so we deviate from the spec (which + // requires the array) to play nice here. + var names = util.getArg(sourceMap, 'names', []); + var sourceRoot = util.getArg(sourceMap, 'sourceRoot', null); + var sourcesContent = util.getArg(sourceMap, 'sourcesContent', null); + var mappings = util.getArg(sourceMap, 'mappings'); + var file = util.getArg(sourceMap, 'file', null); + + // Once again, Sass deviates from the spec and supplies the version as a + // string rather than a number, so we use loose equality checking here. + if (version != this._version) { + throw new Error('Unsupported version: ' + version); + } + + if (sourceRoot) { + sourceRoot = util.normalize(sourceRoot); + } + + sources = sources + .map(String) + // Some source maps produce relative source paths like "./foo.js" instead of + // "foo.js". Normalize these first so that future comparisons will succeed. + // See bugzil.la/1090768. + .map(util.normalize) + // Always ensure that absolute sources are internally stored relative to + // the source root, if the source root is absolute. Not doing this would + // be particularly problematic when the source root is a prefix of the + // source (valid, but why??). See github issue #199 and bugzil.la/1188982. + .map(function (source) { + return sourceRoot && + util.isAbsolute(sourceRoot) && + util.isAbsolute(source) + ? util.relative(sourceRoot, source) + : source; + }); + + // Pass `true` below to allow duplicate names and sources. While source maps + // are intended to be compressed and deduplicated, the TypeScript compiler + // sometimes generates source maps with duplicates in them. See Github issue + // #72 and bugzil.la/889492. + this._names = ArraySet.fromArray(names.map(String), true); + this._sources = ArraySet.fromArray(sources, true); + + this._absoluteSources = this._sources.toArray().map(function (s) { + return util.computeSourceURL(sourceRoot, s, aSourceMapURL); + }); + + this.sourceRoot = sourceRoot; + this.sourcesContent = sourcesContent; + this._mappings = mappings; + this._sourceMapURL = aSourceMapURL; + this.file = file; +} + +BasicSourceMapConsumer.prototype = Object.create(SourceMapConsumer.prototype); +BasicSourceMapConsumer.prototype.consumer = SourceMapConsumer; + +/** + * Utility function to find the index of a source. Returns -1 if not + * found. + */ +BasicSourceMapConsumer.prototype._findSourceIndex = function (aSource) { + var relativeSource = aSource; + if (this.sourceRoot != null) { + relativeSource = util.relative(this.sourceRoot, relativeSource); + } + + if (this._sources.has(relativeSource)) { + return this._sources.indexOf(relativeSource); + } + + // Maybe aSource is an absolute URL as returned by |sources|. In + // this case we can't simply undo the transform. + var i; + for (i = 0; i < this._absoluteSources.length; ++i) { + if (this._absoluteSources[i] == aSource) { + return i; + } + } + + return -1; +}; + +/** + * Create a BasicSourceMapConsumer from a SourceMapGenerator. + * + * @param SourceMapGenerator aSourceMap + * The source map that will be consumed. + * @param String aSourceMapURL + * The URL at which the source map can be found (optional) + * @returns BasicSourceMapConsumer + */ +BasicSourceMapConsumer.fromSourceMap = function SourceMapConsumer_fromSourceMap( + aSourceMap, + aSourceMapURL +) { + var smc = Object.create(BasicSourceMapConsumer.prototype); + + var names = (smc._names = ArraySet.fromArray( + aSourceMap._names.toArray(), + true + )); + var sources = (smc._sources = ArraySet.fromArray( + aSourceMap._sources.toArray(), + true + )); + smc.sourceRoot = aSourceMap._sourceRoot; + smc.sourcesContent = aSourceMap._generateSourcesContent( + smc._sources.toArray(), + smc.sourceRoot + ); + smc.file = aSourceMap._file; + smc._sourceMapURL = aSourceMapURL; + smc._absoluteSources = smc._sources.toArray().map(function (s) { + return util.computeSourceURL(smc.sourceRoot, s, aSourceMapURL); + }); + + // Because we are modifying the entries (by converting string sources and + // names to indices into the sources and names ArraySets), we have to make + // a copy of the entry or else bad things happen. Shared mutable state + // strikes again! See github issue #191. + + var generatedMappings = aSourceMap._mappings.toArray().slice(); + var destGeneratedMappings = (smc.__generatedMappings = []); + var destOriginalMappings = (smc.__originalMappings = []); + + for (var i = 0, length = generatedMappings.length; i < length; i++) { + var srcMapping = generatedMappings[i]; + var destMapping = new Mapping(); + destMapping.generatedLine = srcMapping.generatedLine; + destMapping.generatedColumn = srcMapping.generatedColumn; + + if (srcMapping.source) { + destMapping.source = sources.indexOf(srcMapping.source); + destMapping.originalLine = srcMapping.originalLine; + destMapping.originalColumn = srcMapping.originalColumn; + + if (srcMapping.name) { + destMapping.name = names.indexOf(srcMapping.name); + } + + destOriginalMappings.push(destMapping); + } + + destGeneratedMappings.push(destMapping); + } + + quickSort(smc.__originalMappings, util.compareByOriginalPositions); + + return smc; +}; + +/** + * The version of the source mapping spec that we are consuming. + */ +BasicSourceMapConsumer.prototype._version = 3; + +/** + * The list of original sources. + */ +Object.defineProperty(BasicSourceMapConsumer.prototype, 'sources', { + get: function () { + return this._absoluteSources.slice(); + }, +}); + +/** + * Provide the JIT with a nice shape / hidden class. + */ +function Mapping() { + this.generatedLine = 0; + this.generatedColumn = 0; + this.source = null; + this.originalLine = null; + this.originalColumn = null; + this.name = null; +} + +/** + * Parse the mappings in a string in to a data structure which we can easily + * query (the ordered arrays in the `this.__generatedMappings` and + * `this.__originalMappings` properties). + */ + +const compareGenerated = util.compareByGeneratedPositionsDeflatedNoLine; +function sortGenerated(array, start) { + let l = array.length; + let n = array.length - start; + if (n <= 1) { + return; + } else if (n == 2) { + let a = array[start]; + let b = array[start + 1]; + if (compareGenerated(a, b) > 0) { + array[start] = b; + array[start + 1] = a; + } + } else if (n < 20) { + for (let i = start; i < l; i++) { + for (let j = i; j > start; j--) { + let a = array[j - 1]; + let b = array[j]; + if (compareGenerated(a, b) <= 0) { + break; + } + array[j - 1] = b; + array[j] = a; + } + } + } else { + quickSort(array, compareGenerated, start); + } +} +BasicSourceMapConsumer.prototype._parseMappings = + function SourceMapConsumer_parseMappings(aStr, aSourceRoot) { + var generatedLine = 1; + var previousGeneratedColumn = 0; + var previousOriginalLine = 0; + var previousOriginalColumn = 0; + var previousSource = 0; + var previousName = 0; + var length = aStr.length; + var index = 0; + var cachedSegments = {}; + var temp = {}; + var originalMappings = []; + var generatedMappings = []; + var mapping, str, segment, end, value; + + let subarrayStart = 0; + while (index < length) { + if (aStr.charAt(index) === ';') { + generatedLine++; + index++; + previousGeneratedColumn = 0; + + sortGenerated(generatedMappings, subarrayStart); + subarrayStart = generatedMappings.length; + } else if (aStr.charAt(index) === ',') { + index++; + } else { + mapping = new Mapping(); + mapping.generatedLine = generatedLine; + + for (end = index; end < length; end++) { + if (this._charIsMappingSeparator(aStr, end)) { + break; + } + } + str = aStr.slice(index, end); + + segment = []; + while (index < end) { + base64VLQ.decode(aStr, index, temp); + value = temp.value; + index = temp.rest; + segment.push(value); + } + + if (segment.length === 2) { + throw new Error('Found a source, but no line and column'); + } + + if (segment.length === 3) { + throw new Error('Found a source and line, but no column'); + } + + // Generated column. + mapping.generatedColumn = previousGeneratedColumn + segment[0]; + previousGeneratedColumn = mapping.generatedColumn; + + if (segment.length > 1) { + // Original source. + mapping.source = previousSource + segment[1]; + previousSource += segment[1]; + + // Original line. + mapping.originalLine = previousOriginalLine + segment[2]; + previousOriginalLine = mapping.originalLine; + // Lines are stored 0-based + mapping.originalLine += 1; + + // Original column. + mapping.originalColumn = previousOriginalColumn + segment[3]; + previousOriginalColumn = mapping.originalColumn; + + if (segment.length > 4) { + // Original name. + mapping.name = previousName + segment[4]; + previousName += segment[4]; + } + } + + generatedMappings.push(mapping); + if (typeof mapping.originalLine === 'number') { + let currentSource = mapping.source; + while (originalMappings.length <= currentSource) { + originalMappings.push(null); + } + if (originalMappings[currentSource] === null) { + originalMappings[currentSource] = []; + } + originalMappings[currentSource].push(mapping); + } + } + } + + sortGenerated(generatedMappings, subarrayStart); + this.__generatedMappings = generatedMappings; + + // Sources without mappings have a null bucket. Leave those out, or the + // nulls end up in __originalMappings. + var sourceBuckets = []; + for (var i = 0; i < originalMappings.length; i++) { + if (originalMappings[i] != null) { + quickSort(originalMappings[i], util.compareByOriginalPositionsNoSource); + sourceBuckets.push(originalMappings[i]); + } + } + + // Spreading every bucket into a single concat call overflows the stack + // once a few hundred thousand sources have mappings, so concat at most + // 4096 buckets at a time. Most maps have fewer, and need a single call. + var sortedOriginalMappings = []; + for (var b = 0; b < sourceBuckets.length; b += 4096) { + sortedOriginalMappings = sortedOriginalMappings.concat( + ...sourceBuckets.slice(b, b + 4096) + ); + } + this.__originalMappings = sortedOriginalMappings; + }; + +/** + * Find the mapping that best matches the hypothetical "needle" mapping that + * we are searching for in the given "haystack" of mappings. + */ +BasicSourceMapConsumer.prototype._findMapping = + function SourceMapConsumer_findMapping( + aNeedle, + aMappings, + aLineName, + aColumnName, + aComparator, + aBias + ) { + // To return the position we are searching for, we must first find the + // mapping for the given position and then return the opposite position it + // points to. Because the mappings are sorted, we can use binary search to + // find the best mapping. + + if (aNeedle[aLineName] <= 0) { + throw new TypeError( + 'Line must be greater than or equal to 1, got ' + aNeedle[aLineName] + ); + } + if (aNeedle[aColumnName] < 0) { + throw new TypeError( + 'Column must be greater than or equal to 0, got ' + aNeedle[aColumnName] + ); + } + + return binarySearch.search(aNeedle, aMappings, aComparator, aBias); + }; + +/** + * Compute the last column for each generated mapping. The last column is + * inclusive. + */ +BasicSourceMapConsumer.prototype.computeColumnSpans = + function SourceMapConsumer_computeColumnSpans() { + for (var index = 0; index < this._generatedMappings.length; ++index) { + var mapping = this._generatedMappings[index]; + + // Mappings do not contain a field for the last generated columnt. We + // can come up with an optimistic estimate, however, by assuming that + // mappings are contiguous (i.e. given two consecutive mappings, the + // first mapping ends where the second one starts). + if (index + 1 < this._generatedMappings.length) { + var nextMapping = this._generatedMappings[index + 1]; + + if (mapping.generatedLine === nextMapping.generatedLine) { + mapping.lastGeneratedColumn = nextMapping.generatedColumn - 1; + continue; + } + } + + // The last mapping for each line spans the entire line. + mapping.lastGeneratedColumn = Infinity; + } + }; + +/** + * Returns the original source, line, and column information for the generated + * source's line and column positions provided. The only argument is an object + * with the following properties: + * + * - line: The line number in the generated source. The line number + * is 1-based. + * - column: The column number in the generated source. The column + * number is 0-based. + * - bias: Either 'SourceMapConsumer.GREATEST_LOWER_BOUND' or + * 'SourceMapConsumer.LEAST_UPPER_BOUND'. Specifies whether to return the + * closest element that is smaller than or greater than the one we are + * searching for, respectively, if the exact element cannot be found. + * Defaults to 'SourceMapConsumer.GREATEST_LOWER_BOUND'. + * + * and an object is returned with the following properties: + * + * - source: The original source file, or null. + * - line: The line number in the original source, or null. The + * line number is 1-based. + * - column: The column number in the original source, or null. The + * column number is 0-based. + * - name: The original identifier, or null. + */ +BasicSourceMapConsumer.prototype.originalPositionFor = + function SourceMapConsumer_originalPositionFor(aArgs) { + var needle = { + generatedLine: util.getArg(aArgs, 'line'), + generatedColumn: util.getArg(aArgs, 'column'), + }; + + var index = this._findMapping( + needle, + this._generatedMappings, + 'generatedLine', + 'generatedColumn', + util.compareByGeneratedPositionsDeflated, + util.getArg(aArgs, 'bias', SourceMapConsumer.GREATEST_LOWER_BOUND) + ); + + if (index >= 0) { + var mapping = this._generatedMappings[index]; + + if (mapping.generatedLine === needle.generatedLine) { + var source = util.getArg(mapping, 'source', null); + if (source !== null) { + source = this._sources.at(source); + source = util.computeSourceURL( + this.sourceRoot, + source, + this._sourceMapURL + ); + } + var name = util.getArg(mapping, 'name', null); + if (name !== null) { + name = this._names.at(name); + } + return { + source: source, + line: util.getArg(mapping, 'originalLine', null), + column: util.getArg(mapping, 'originalColumn', null), + name: name, + }; + } + } + + return { + source: null, + line: null, + column: null, + name: null, + }; + }; + +/** + * Return true if we have the source content for every source in the source + * map, false otherwise. + */ +BasicSourceMapConsumer.prototype.hasContentsOfAllSources = + function BasicSourceMapConsumer_hasContentsOfAllSources() { + if (!this.sourcesContent) { + return false; + } + return ( + this.sourcesContent.length >= this._sources.size() && + !this.sourcesContent.some(function (sc) { + return sc == null; + }) + ); + }; + +/** + * Returns the original source content. The only argument is the url of the + * original source file. Returns null if no original source content is + * available. + */ +BasicSourceMapConsumer.prototype.sourceContentFor = + function SourceMapConsumer_sourceContentFor(aSource, nullOnMissing) { + if (!this.sourcesContent) { + return null; + } + + var index = this._findSourceIndex(aSource); + if (index >= 0) { + return this.sourcesContent[index]; + } + + var relativeSource = aSource; + if (this.sourceRoot != null) { + relativeSource = util.relative(this.sourceRoot, relativeSource); + } + + var url; + if (this.sourceRoot != null && (url = util.urlParse(this.sourceRoot))) { + // XXX: file:// URIs and absolute paths lead to unexpected behavior for + // many users. We can help them out when they expect file:// URIs to + // behave like it would if they were running a local HTTP server. See + // https://bugzilla.mozilla.org/show_bug.cgi?id=885597. + var fileUriAbsPath = relativeSource.replace(/^file:\/\//, ''); + if (url.scheme == 'file' && this._sources.has(fileUriAbsPath)) { + return this.sourcesContent[this._sources.indexOf(fileUriAbsPath)]; + } + + if ( + (!url.path || url.path == '/') && + this._sources.has('/' + relativeSource) + ) { + return this.sourcesContent[this._sources.indexOf('/' + relativeSource)]; + } + } + + // This function is used recursively from + // IndexedSourceMapConsumer.prototype.sourceContentFor. In that case, we + // don't want to throw if we can't find the source - we just want to + // return null, so we provide a flag to exit gracefully. + if (nullOnMissing) { + return null; + } else { + throw new Error('"' + relativeSource + '" is not in the SourceMap.'); + } + }; + +/** + * Returns the generated line and column information for the original source, + * line, and column positions provided. The only argument is an object with + * the following properties: + * + * - source: The filename of the original source. + * - line: The line number in the original source. The line number + * is 1-based. + * - column: The column number in the original source. The column + * number is 0-based. + * - bias: Either 'SourceMapConsumer.GREATEST_LOWER_BOUND' or + * 'SourceMapConsumer.LEAST_UPPER_BOUND'. Specifies whether to return the + * closest element that is smaller than or greater than the one we are + * searching for, respectively, if the exact element cannot be found. + * Defaults to 'SourceMapConsumer.GREATEST_LOWER_BOUND'. + * + * and an object is returned with the following properties: + * + * - line: The line number in the generated source, or null. The + * line number is 1-based. + * - column: The column number in the generated source, or null. + * The column number is 0-based. + */ +BasicSourceMapConsumer.prototype.generatedPositionFor = + function SourceMapConsumer_generatedPositionFor(aArgs) { + var source = util.getArg(aArgs, 'source'); + source = this._findSourceIndex(source); + if (source < 0) { + return { + line: null, + column: null, + lastColumn: null, + }; + } + + var needle = { + source: source, + originalLine: util.getArg(aArgs, 'line'), + originalColumn: util.getArg(aArgs, 'column'), + }; + + var index = this._findMapping( + needle, + this._originalMappings, + 'originalLine', + 'originalColumn', + util.compareByOriginalPositions, + util.getArg(aArgs, 'bias', SourceMapConsumer.GREATEST_LOWER_BOUND) + ); + + if (index >= 0) { + var mapping = this._originalMappings[index]; + + if (mapping.source === needle.source) { + return { + line: util.getArg(mapping, 'generatedLine', null), + column: util.getArg(mapping, 'generatedColumn', null), + lastColumn: util.getArg(mapping, 'lastGeneratedColumn', null), + }; + } + } + + return { + line: null, + column: null, + lastColumn: null, + }; + }; + +exports.BasicSourceMapConsumer = BasicSourceMapConsumer; + +/** + * An IndexedSourceMapConsumer instance represents a parsed source map which + * we can query for information. It differs from BasicSourceMapConsumer in + * that it takes "indexed" source maps (i.e. ones with a "sections" field) as + * input. + * + * The first parameter is a raw source map (either as a JSON string, or already + * parsed to an object). According to the spec for indexed source maps, they + * have the following attributes: + * + * - version: Which version of the source map spec this map is following. + * - file: Optional. The generated file this source map is associated with. + * - sections: A list of section definitions. + * + * Each value under the "sections" field has two fields: + * - offset: The offset into the original specified at which this section + * begins to apply, defined as an object with a "line" and "column" + * field. + * - map: A source map definition. This source map could also be indexed, + * but doesn't have to be. + * + * Instead of the "map" field, it's also possible to have a "url" field + * specifying a URL to retrieve a source map from, but that's currently + * unsupported. + * + * Here's an example source map, taken from the source map spec[0], but + * modified to omit a section which uses the "url" field. + * + * { + * version : 3, + * file: "app.js", + * sections: [{ + * offset: {line:100, column:10}, + * map: { + * version : 3, + * file: "section.js", + * sources: ["foo.js", "bar.js"], + * names: ["src", "maps", "are", "fun"], + * mappings: "AAAA,E;;ABCDE;" + * } + * }], + * } + * + * The second parameter, if given, is a string whose value is the URL + * at which the source map was found. This URL is used to compute the + * sources array. + * + * [0]: https://docs.google.com/document/d/1U1RGAehQwRypUTovF1KRlpiOFze0b-_2gc6fAH0KY0k/edit#heading=h.535es3xeprgt + */ +function IndexedSourceMapConsumer(aSourceMap, aSourceMapURL) { + var sourceMap = aSourceMap; + if (typeof aSourceMap === 'string') { + sourceMap = util.parseSourceMapInput(aSourceMap); + } + + var version = util.getArg(sourceMap, 'version'); + var sections = util.getArg(sourceMap, 'sections'); + + if (version != this._version) { + throw new Error('Unsupported version: ' + version); + } + + this._sources = new ArraySet(); + this._names = new ArraySet(); + + var lastOffset = { + line: -1, + column: 0, + }; + var maxOffsetLine = 0; + this._sections = sections.map(function (s) { + if (s.url) { + // The url field will require support for asynchronicity. + // See https://github.com/mozilla/source-map/issues/16 + throw new Error('Support for url field in sections not implemented.'); + } + var offset = util.getArg(s, 'offset'); + var offsetLine = util.getArg(offset, 'line'); + var offsetColumn = util.getArg(offset, 'column'); + + if (!isValidOffset(offsetLine) || !isValidOffset(offsetColumn)) { + throw new Error( + 'Section offset line and column must be non-negative integers.' + ); + } + if (offsetLine > MAX_SECTION_OFFSET_LINE) { + throw new Error( + 'Section offset line must not exceed ' + MAX_SECTION_OFFSET_LINE + '.' + ); + } + + if ( + offsetLine < lastOffset.line || + (offsetLine === lastOffset.line && offsetColumn < lastOffset.column) + ) { + throw new Error('Section offsets must be ordered and non-overlapping.'); + } + lastOffset = offset; + + var consumer = new SourceMapConsumer(util.getArg(s, 'map'), aSourceMapURL); + + // Offsets of a nested indexed map add up with this one, so apply the + // bound to the total. + var totalOffsetLine = offsetLine + (consumer._maxOffsetLine || 0); + if (totalOffsetLine > MAX_SECTION_OFFSET_LINE) { + throw new Error( + 'Section offset line must not exceed ' + + MAX_SECTION_OFFSET_LINE + + ', including offsets of nested sections.' + ); + } + if (totalOffsetLine > maxOffsetLine) { + maxOffsetLine = totalOffsetLine; + } + + return { + generatedOffset: { + // The offset fields are 0-based, but we use 1-based indices when + // encoding/decoding from VLQ. + generatedLine: offsetLine + 1, + generatedColumn: offsetColumn + 1, + }, + consumer: consumer, + }; + }); + + // The largest offset.line of any section, including nested sections. + this._maxOffsetLine = maxOffsetLine; +} + +/** + * Section offsets come from untrusted input and are used as line/column + * numbers, so only accept non-negative safe integers (rejects NaN, Infinity, + * strings, fractions, etc). + */ +function isValidOffset(aValue) { + return ( + typeof aValue === 'number' && + aValue >= 0 && + aValue <= 9007199254740991 && // Number.MAX_SAFE_INTEGER + Math.floor(aValue) === aValue + ); +} + +IndexedSourceMapConsumer.prototype = Object.create(SourceMapConsumer.prototype); +IndexedSourceMapConsumer.prototype.constructor = SourceMapConsumer; + +/** + * The version of the source mapping spec that we are consuming. + */ +IndexedSourceMapConsumer.prototype._version = 3; + +/** + * The list of original sources. + */ +Object.defineProperty(IndexedSourceMapConsumer.prototype, 'sources', { + get: function () { + var sources = []; + for (var i = 0; i < this._sections.length; i++) { + // Read the getter once per section: for a nested indexed map it is + // itself this getter, and re-reading it per item is exponential in the + // nesting depth (CVE-2026-93749). + var sectionSources = this._sections[i].consumer.sources; + for (var j = 0; j < sectionSources.length; j++) { + sources.push(sectionSources[j]); + } + } + return sources; + }, +}); + +/** + * Returns the original source, line, and column information for the generated + * source's line and column positions provided. The only argument is an object + * with the following properties: + * + * - line: The line number in the generated source. The line number + * is 1-based. + * - column: The column number in the generated source. The column + * number is 0-based. + * + * and an object is returned with the following properties: + * + * - source: The original source file, or null. + * - line: The line number in the original source, or null. The + * line number is 1-based. + * - column: The column number in the original source, or null. The + * column number is 0-based. + * - name: The original identifier, or null. + */ +IndexedSourceMapConsumer.prototype.originalPositionFor = + function IndexedSourceMapConsumer_originalPositionFor(aArgs) { + var needle = { + generatedLine: util.getArg(aArgs, 'line'), + generatedColumn: util.getArg(aArgs, 'column'), + }; + + // Find the section containing the generated position we're trying to map + // to an original position. + var sectionIndex = binarySearch.search( + needle, + this._sections, + function (needle, section) { + var cmp = needle.generatedLine - section.generatedOffset.generatedLine; + if (cmp) { + return cmp; + } + + // The needle's column is 0-based, generatedOffset.generatedColumn is + // 1-based. + return ( + needle.generatedColumn - (section.generatedOffset.generatedColumn - 1) + ); + } + ); + var section = this._sections[sectionIndex]; + + if (!section) { + return { + source: null, + line: null, + column: null, + name: null, + }; + } + + return section.consumer.originalPositionFor({ + line: needle.generatedLine - (section.generatedOffset.generatedLine - 1), + column: + needle.generatedColumn - + (section.generatedOffset.generatedLine === needle.generatedLine + ? section.generatedOffset.generatedColumn - 1 + : 0), + bias: aArgs.bias, + }); + }; + +/** + * Return true if we have the source content for every source in the source + * map, false otherwise. + */ +IndexedSourceMapConsumer.prototype.hasContentsOfAllSources = + function IndexedSourceMapConsumer_hasContentsOfAllSources() { + return this._sections.every(function (s) { + return s.consumer.hasContentsOfAllSources(); + }); + }; + +/** + * Returns the original source content. The only argument is the url of the + * original source file. Returns null if no original source content is + * available. + */ +IndexedSourceMapConsumer.prototype.sourceContentFor = + function IndexedSourceMapConsumer_sourceContentFor(aSource, nullOnMissing) { + for (var i = 0; i < this._sections.length; i++) { + var section = this._sections[i]; + + var content = section.consumer.sourceContentFor(aSource, true); + if (content || content === '') { + return content; + } + } + if (nullOnMissing) { + return null; + } else { + throw new Error('"' + aSource + '" is not in the SourceMap.'); + } + }; + +// SourceMapConsumer.prototype.allGeneratedPositionsFor and +// BasicSourceMapConsumer.prototype.generatedPositionFor search +// this._originalMappings, which holds the mappings of every section with +// their generated positions already shifted by the section offset. They need +// these two methods. + +/** + * Returns the index of a source in this._sources, which holds the URLs of + * the sources that have mappings, or -1. Accepts any name a section + * accepts: relative to the section's sourceRoot or a URL from `sources`. + */ +IndexedSourceMapConsumer.prototype._findSourceIndex = function (aSource) { + // this._sources is filled in by _parseMappings, which runs on first access + // to the mappings. + this._generatedMappings; + + for (var i = 0; i < this._sections.length; i++) { + var consumer = this._sections[i].consumer; + var index = consumer._findSourceIndex(aSource); + if (index === -1) { + continue; + } + + // The same URL _parseMappings stores the source under. + var url = util.computeSourceURL( + consumer.sourceRoot, + consumer._sources.at(index), + this._sourceMapURL + ); + if (this._sources.has(url)) { + return this._sources.indexOf(url); + } + } + + return -1; +}; + +IndexedSourceMapConsumer.prototype._findMapping = + BasicSourceMapConsumer.prototype._findMapping; + +// Searching the mappings of all sections at once finds the closest mapping +// across sections, the same as for the map without sections. +IndexedSourceMapConsumer.prototype.generatedPositionFor = + BasicSourceMapConsumer.prototype.generatedPositionFor; + +// Computes the spans on this._generatedMappings, the offset-shifted mappings +// of all sections, which the lookups above return. A mapping's span ends +// where the next mapping starts, even if that one is in the next section. +IndexedSourceMapConsumer.prototype.computeColumnSpans = + BasicSourceMapConsumer.prototype.computeColumnSpans; + +/** + * Parse the mappings in a string in to a data structure which we can easily + * query (the ordered arrays in the `this.__generatedMappings` and + * `this.__originalMappings` properties). + */ +IndexedSourceMapConsumer.prototype._parseMappings = + function IndexedSourceMapConsumer_parseMappings(aStr, aSourceRoot) { + this.__generatedMappings = []; + this.__originalMappings = []; + for (var i = 0; i < this._sections.length; i++) { + var section = this._sections[i]; + var sectionMappings = section.consumer._generatedMappings; + for (var j = 0; j < sectionMappings.length; j++) { + var mapping = sectionMappings[j]; + + var source = section.consumer._sources.at(mapping.source); + if (source !== null) { + source = util.computeSourceURL( + section.consumer.sourceRoot, + source, + this._sourceMapURL + ); + } + this._sources.add(source); + source = this._sources.indexOf(source); + + var name = null; + if (mapping.name) { + name = section.consumer._names.at(mapping.name); + this._names.add(name); + name = this._names.indexOf(name); + } + + // The mappings coming from the consumer for the section have + // generated positions relative to the start of the section, so we + // need to offset them to be relative to the start of the concatenated + // generated file. The column offset only applies to the section's + // first line. + var adjustedMapping = { + source: source, + generatedLine: + mapping.generatedLine + (section.generatedOffset.generatedLine - 1), + generatedColumn: + mapping.generatedColumn + + (mapping.generatedLine === 1 + ? section.generatedOffset.generatedColumn - 1 + : 0), + originalLine: mapping.originalLine, + originalColumn: mapping.originalColumn, + name: name, + }; + + this.__generatedMappings.push(adjustedMapping); + if (typeof adjustedMapping.originalLine === 'number') { + this.__originalMappings.push(adjustedMapping); + } + } + } + + quickSort( + this.__generatedMappings, + util.compareByGeneratedPositionsDeflated + ); + quickSort(this.__originalMappings, util.compareByOriginalPositions); + }; + +exports.IndexedSourceMapConsumer = IndexedSourceMapConsumer; diff --git a/dg-ui/node_modules/source-map-js/lib/source-map-generator.d.ts b/dg-ui/node_modules/source-map-js/lib/source-map-generator.d.ts new file mode 100644 index 0000000..f59d70a --- /dev/null +++ b/dg-ui/node_modules/source-map-js/lib/source-map-generator.d.ts @@ -0,0 +1 @@ +export { SourceMapGenerator } from '..'; diff --git a/dg-ui/node_modules/source-map-js/lib/source-map-generator.js b/dg-ui/node_modules/source-map-js/lib/source-map-generator.js new file mode 100644 index 0000000..db6758d --- /dev/null +++ b/dg-ui/node_modules/source-map-js/lib/source-map-generator.js @@ -0,0 +1,486 @@ +/* -*- Mode: js; js-indent-level: 2; -*- */ +/* + * Copyright 2011 Mozilla Foundation and contributors + * Licensed under the New BSD license. See LICENSE or: + * http://opensource.org/licenses/BSD-3-Clause + */ + +var base64VLQ = require('./base64-vlq'); +var util = require('./util'); +var ArraySet = require('./array-set').ArraySet; +var MappingList = require('./mapping-list').MappingList; + +/** + * An instance of the SourceMapGenerator represents a source map which is + * being built incrementally. You may pass an object with the following + * properties: + * + * - file: The filename of the generated source. + * - sourceRoot: A root for all relative URLs in this source map. + */ +function SourceMapGenerator(aArgs) { + if (!aArgs) { + aArgs = {}; + } + this._file = util.getArg(aArgs, 'file', null); + this._sourceRoot = util.getArg(aArgs, 'sourceRoot', null); + this._skipValidation = util.getArg(aArgs, 'skipValidation', false); + this._ignoreInvalidMapping = util.getArg( + aArgs, + 'ignoreInvalidMapping', + false + ); + this._sources = new ArraySet(); + this._names = new ArraySet(); + this._mappings = new MappingList(); + this._sourcesContents = null; +} + +SourceMapGenerator.prototype._version = 3; + +/** + * Creates a new SourceMapGenerator based on a SourceMapConsumer + * + * @param aSourceMapConsumer The SourceMap. + */ +SourceMapGenerator.fromSourceMap = function SourceMapGenerator_fromSourceMap( + aSourceMapConsumer, + generatorOps +) { + var sourceRoot = aSourceMapConsumer.sourceRoot; + var generator = new SourceMapGenerator( + Object.assign(generatorOps || {}, { + file: aSourceMapConsumer.file, + sourceRoot: sourceRoot, + }) + ); + aSourceMapConsumer.eachMapping(function (mapping) { + var newMapping = { + generated: { + line: mapping.generatedLine, + column: mapping.generatedColumn, + }, + }; + + if (mapping.source != null) { + newMapping.source = mapping.source; + if (sourceRoot != null) { + newMapping.source = util.relative(sourceRoot, newMapping.source); + } + + newMapping.original = { + line: mapping.originalLine, + column: mapping.originalColumn, + }; + + if (mapping.name != null) { + newMapping.name = mapping.name; + } + } + + generator.addMapping(newMapping); + }); + aSourceMapConsumer.sources.forEach(function (sourceFile) { + var sourceRelative = sourceFile; + if (sourceRoot !== null) { + sourceRelative = util.relative(sourceRoot, sourceFile); + } + + if (!generator._sources.has(sourceRelative)) { + generator._sources.add(sourceRelative); + } + + var content = aSourceMapConsumer.sourceContentFor(sourceFile); + if (content != null) { + generator.setSourceContent(sourceFile, content); + } + }); + return generator; +}; + +/** + * Add a single mapping from original source line and column to the generated + * source's line and column for this source map being created. The mapping + * object should have the following properties: + * + * - generated: An object with the generated line and column positions. + * - original: An object with the original line and column positions. + * - source: The original source file (relative to the sourceRoot). + * - name: An optional original token name for this mapping. + */ +SourceMapGenerator.prototype.addMapping = + function SourceMapGenerator_addMapping(aArgs) { + var generated = util.getArg(aArgs, 'generated'); + var original = util.getArg(aArgs, 'original', null); + var source = util.getArg(aArgs, 'source', null); + var name = util.getArg(aArgs, 'name', null); + + if (!this._skipValidation) { + if (this._validateMapping(generated, original, source, name) === false) { + return; + } + } + + if (source != null) { + source = String(source); + if (!this._sources.has(source)) { + this._sources.add(source); + } + } + + if (name != null) { + name = String(name); + if (!this._names.has(name)) { + this._names.add(name); + } + } + + this._mappings.add({ + generatedLine: generated.line, + generatedColumn: generated.column, + originalLine: original != null && original.line, + originalColumn: original != null && original.column, + source: source, + name: name, + }); + }; + +/** + * Set the source content for a source file. + */ +SourceMapGenerator.prototype.setSourceContent = + function SourceMapGenerator_setSourceContent(aSourceFile, aSourceContent) { + var source = aSourceFile; + if (this._sourceRoot != null) { + source = util.relative(this._sourceRoot, source); + } + + if (aSourceContent != null) { + // Add the source content to the _sourcesContents map. + // Create a new _sourcesContents map if the property is null. + if (!this._sourcesContents) { + this._sourcesContents = Object.create(null); + } + this._sourcesContents[util.toSetString(source)] = aSourceContent; + } else if (this._sourcesContents) { + // Remove the source file from the _sourcesContents map. + // If the _sourcesContents map is empty, set the property to null. + delete this._sourcesContents[util.toSetString(source)]; + if (Object.keys(this._sourcesContents).length === 0) { + this._sourcesContents = null; + } + } + }; + +/** + * Applies the mappings of a sub-source-map for a specific source file to the + * source map being generated. Each mapping to the supplied source file is + * rewritten using the supplied source map. Note: The resolution for the + * resulting mappings is the minimium of this map and the supplied map. + * + * @param aSourceMapConsumer The source map to be applied. + * @param aSourceFile Optional. The filename of the source file. + * If omitted, SourceMapConsumer's file property will be used. + * @param aSourceMapPath Optional. The dirname of the path to the source map + * to be applied. If relative, it is relative to the SourceMapConsumer. + * This parameter is needed when the two source maps aren't in the same + * directory, and the source map to be applied contains relative source + * paths. If so, those relative source paths need to be rewritten + * relative to the SourceMapGenerator. + */ +SourceMapGenerator.prototype.applySourceMap = + function SourceMapGenerator_applySourceMap( + aSourceMapConsumer, + aSourceFile, + aSourceMapPath + ) { + var sourceFile = aSourceFile; + // If aSourceFile is omitted, we will use the file property of the SourceMap + if (aSourceFile == null) { + if (aSourceMapConsumer.file == null) { + throw new Error( + 'SourceMapGenerator.prototype.applySourceMap requires either an explicit source file, ' + + 'or the source map\'s "file" property. Both were omitted.' + ); + } + sourceFile = aSourceMapConsumer.file; + } + var sourceRoot = this._sourceRoot; + // Make "sourceFile" relative if an absolute Url is passed. + if (sourceRoot != null) { + sourceFile = util.relative(sourceRoot, sourceFile); + } + // Applying the SourceMap can add and remove items from the sources and + // the names array. + var newSources = new ArraySet(); + var newNames = new ArraySet(); + + // Find mappings for the "sourceFile" + this._mappings.unsortedForEach(function (mapping) { + if (mapping.source === sourceFile && mapping.originalLine != null) { + // Check if it can be mapped by the source map, then update the mapping. + var original = aSourceMapConsumer.originalPositionFor({ + line: mapping.originalLine, + column: mapping.originalColumn, + }); + if (original.source != null) { + // Copy mapping + mapping.source = original.source; + if (aSourceMapPath != null) { + mapping.source = util.join(aSourceMapPath, mapping.source); + } + if (sourceRoot != null) { + mapping.source = util.relative(sourceRoot, mapping.source); + } + mapping.originalLine = original.line; + mapping.originalColumn = original.column; + if (original.name != null) { + mapping.name = original.name; + } + } + } + + var source = mapping.source; + if (source != null && !newSources.has(source)) { + newSources.add(source); + } + + var name = mapping.name; + if (name != null && !newNames.has(name)) { + newNames.add(name); + } + }, this); + this._sources = newSources; + this._names = newNames; + + // Copy sourcesContents of applied map. + aSourceMapConsumer.sources.forEach(function (sourceFile) { + var content = aSourceMapConsumer.sourceContentFor(sourceFile); + if (content != null) { + if (aSourceMapPath != null) { + sourceFile = util.join(aSourceMapPath, sourceFile); + } + if (sourceRoot != null) { + sourceFile = util.relative(sourceRoot, sourceFile); + } + this.setSourceContent(sourceFile, content); + } + }, this); + }; + +/** + * A mapping can have one of the three levels of data: + * + * 1. Just the generated position. + * 2. The Generated position, original position, and original source. + * 3. Generated and original position, original source, as well as a name + * token. + * + * To maintain consistency, we validate that any new mapping being added falls + * in to one of these categories. + */ +SourceMapGenerator.prototype._validateMapping = + function SourceMapGenerator_validateMapping( + aGenerated, + aOriginal, + aSource, + aName + ) { + // When aOriginal is truthy but has empty values for .line and .column, + // it is most likely a programmer error. In this case we throw a very + // specific error message to try to guide them the right way. + // For example: https://github.com/Polymer/polymer-bundler/pull/519 + if ( + aOriginal && + typeof aOriginal.line !== 'number' && + typeof aOriginal.column !== 'number' + ) { + var message = + 'original.line and original.column are not numbers -- you probably meant to omit ' + + 'the original mapping entirely and only map the generated position. If so, pass ' + + 'null for the original mapping instead of an object with empty or null values.'; + + if (this._ignoreInvalidMapping) { + if (typeof console !== 'undefined' && console.warn) { + console.warn(message); + } + return false; + } else { + throw new Error(message); + } + } + + if ( + aGenerated && + 'line' in aGenerated && + 'column' in aGenerated && + aGenerated.line > 0 && + aGenerated.column >= 0 && + !aOriginal && + !aSource && + !aName + ) { + // Case 1. + return; + } else if ( + aGenerated && + 'line' in aGenerated && + 'column' in aGenerated && + aOriginal && + 'line' in aOriginal && + 'column' in aOriginal && + aGenerated.line > 0 && + aGenerated.column >= 0 && + aOriginal.line > 0 && + aOriginal.column >= 0 && + aSource + ) { + // Cases 2 and 3. + return; + } else { + var message = + 'Invalid mapping: ' + + JSON.stringify({ + generated: aGenerated, + source: aSource, + original: aOriginal, + name: aName, + }); + + if (this._ignoreInvalidMapping) { + if (typeof console !== 'undefined' && console.warn) { + console.warn(message); + } + return false; + } else { + throw new Error(message); + } + } + }; + +/** + * Serialize the accumulated mappings in to the stream of base 64 VLQs + * specified by the source map format. + */ +SourceMapGenerator.prototype._serializeMappings = + function SourceMapGenerator_serializeMappings() { + var previousGeneratedColumn = 0; + var previousGeneratedLine = 1; + var previousOriginalColumn = 0; + var previousOriginalLine = 0; + var previousName = 0; + var previousSource = 0; + var result = ''; + var next; + var mapping; + var nameIdx; + var sourceIdx; + + var mappings = this._mappings.toArray(); + for (var i = 0, len = mappings.length; i < len; i++) { + mapping = mappings[i]; + next = ''; + + if (mapping.generatedLine !== previousGeneratedLine) { + previousGeneratedColumn = 0; + // One ';' per skipped line. Build large gaps with a single flat + // string: appending ';' one by one creates a rope node per line, which + // can exhaust the heap for a big gap (CVE-2026-93749). + var lineDelta = mapping.generatedLine - previousGeneratedLine; + next += lineDelta === 1 ? ';' : ';'.repeat(lineDelta); + previousGeneratedLine = mapping.generatedLine; + } else { + if (i > 0) { + if ( + !util.compareByGeneratedPositionsInflated(mapping, mappings[i - 1]) + ) { + continue; + } + next += ','; + } + } + + next += base64VLQ.encode( + mapping.generatedColumn - previousGeneratedColumn + ); + previousGeneratedColumn = mapping.generatedColumn; + + if (mapping.source != null) { + sourceIdx = this._sources.indexOf(mapping.source); + next += base64VLQ.encode(sourceIdx - previousSource); + previousSource = sourceIdx; + + // lines are stored 0-based in SourceMap spec version 3 + next += base64VLQ.encode( + mapping.originalLine - 1 - previousOriginalLine + ); + previousOriginalLine = mapping.originalLine - 1; + + next += base64VLQ.encode( + mapping.originalColumn - previousOriginalColumn + ); + previousOriginalColumn = mapping.originalColumn; + + if (mapping.name != null) { + nameIdx = this._names.indexOf(mapping.name); + next += base64VLQ.encode(nameIdx - previousName); + previousName = nameIdx; + } + } + + result += next; + } + + return result; + }; + +SourceMapGenerator.prototype._generateSourcesContent = + function SourceMapGenerator_generateSourcesContent(aSources, aSourceRoot) { + return aSources.map(function (source) { + if (!this._sourcesContents) { + return null; + } + if (aSourceRoot != null) { + source = util.relative(aSourceRoot, source); + } + var key = util.toSetString(source); + return Object.prototype.hasOwnProperty.call(this._sourcesContents, key) + ? this._sourcesContents[key] + : null; + }, this); + }; + +/** + * Externalize the source map. + */ +SourceMapGenerator.prototype.toJSON = function SourceMapGenerator_toJSON() { + var map = { + version: this._version, + sources: this._sources.toArray(), + names: this._names.toArray(), + mappings: this._serializeMappings(), + }; + if (this._file != null) { + map.file = this._file; + } + if (this._sourceRoot != null) { + map.sourceRoot = this._sourceRoot; + } + if (this._sourcesContents) { + map.sourcesContent = this._generateSourcesContent( + map.sources, + map.sourceRoot + ); + } + + return map; +}; + +/** + * Render the source map being generated to a string. + */ +SourceMapGenerator.prototype.toString = function SourceMapGenerator_toString() { + return JSON.stringify(this.toJSON()); +}; + +exports.SourceMapGenerator = SourceMapGenerator; diff --git a/dg-ui/node_modules/source-map-js/lib/source-node.d.ts b/dg-ui/node_modules/source-map-js/lib/source-node.d.ts new file mode 100644 index 0000000..4df6a1a --- /dev/null +++ b/dg-ui/node_modules/source-map-js/lib/source-node.d.ts @@ -0,0 +1 @@ +export { SourceNode } from '..'; diff --git a/dg-ui/node_modules/source-map-js/lib/source-node.js b/dg-ui/node_modules/source-map-js/lib/source-node.js new file mode 100644 index 0000000..2bac0b9 --- /dev/null +++ b/dg-ui/node_modules/source-map-js/lib/source-node.js @@ -0,0 +1,446 @@ +/* -*- Mode: js; js-indent-level: 2; -*- */ +/* + * Copyright 2011 Mozilla Foundation and contributors + * Licensed under the New BSD license. See LICENSE or: + * http://opensource.org/licenses/BSD-3-Clause + */ + +var SourceMapGenerator = require('./source-map-generator').SourceMapGenerator; +var util = require('./util'); + +// Matches a Windows-style `\r\n` newline or a `\n` newline used by all other +// operating systems these days (capturing the result). +var REGEX_NEWLINE = /(\r?\n)/; + +// Newline character code for charCodeAt() comparisons +var NEWLINE_CODE = 10; + +// Private symbol for identifying `SourceNode`s when multiple versions of +// the source-map library are loaded. This MUST NOT CHANGE across +// versions! +var isSourceNode = '$$$isSourceNode$$$'; + +/** + * SourceNodes provide a way to abstract over interpolating/concatenating + * snippets of generated JavaScript source code while maintaining the line and + * column information associated with the original source code. + * + * @param aLine The original line number. + * @param aColumn The original column number. + * @param aSource The original source's filename. + * @param aChunks Optional. An array of strings which are snippets of + * generated JS, or other SourceNodes. + * @param aName The original identifier. + */ +function SourceNode(aLine, aColumn, aSource, aChunks, aName) { + this.children = []; + this.sourceContents = {}; + this.line = aLine == null ? null : aLine; + this.column = aColumn == null ? null : aColumn; + this.source = aSource == null ? null : aSource; + this.name = aName == null ? null : aName; + this[isSourceNode] = true; + if (aChunks != null) this.add(aChunks); +} + +/** + * Creates a SourceNode from generated code and a SourceMapConsumer. + * + * @param aGeneratedCode The generated code + * @param aSourceMapConsumer The SourceMap for the generated code + * @param aRelativePath Optional. The path that relative sources in the + * SourceMapConsumer should be relative to. + */ +SourceNode.fromStringWithSourceMap = + function SourceNode_fromStringWithSourceMap( + aGeneratedCode, + aSourceMapConsumer, + aRelativePath + ) { + // The SourceNode we want to fill with the generated code + // and the SourceMap + var node = new SourceNode(); + + // All even indices of this array are one line of the generated code, + // while all odd indices are the newlines between two adjacent lines + // (since `REGEX_NEWLINE` captures its match). + // Processed fragments are accessed by calling `shiftNextLine`. + var remainingLines = aGeneratedCode.split(REGEX_NEWLINE); + var remainingLinesIndex = 0; + var shiftNextLine = function () { + var lineContents = getNextLine(); + // The last line of a file might not have a newline. + var newLine = getNextLine() || ''; + return lineContents + newLine; + + function getNextLine() { + return remainingLinesIndex < remainingLines.length + ? remainingLines[remainingLinesIndex++] + : undefined; + } + }; + + // We need to remember the position of "remainingLines" + var lastGeneratedLine = 1, + lastGeneratedColumn = 0; + + // The generate SourceNodes we need a code range. + // To extract it current and last mapping is used. + // Here we store the last mapping. + var lastMapping = null; + + aSourceMapConsumer.eachMapping(function (mapping) { + if (lastMapping !== null) { + // We add the code from "lastMapping" to "mapping": + // First check if there is a new line in between. + if (lastGeneratedLine < mapping.generatedLine) { + // Associate first line with "lastMapping" + addMappingWithCode(lastMapping, shiftNextLine()); + lastGeneratedLine++; + lastGeneratedColumn = 0; + // The remaining code is added without mapping + } else { + // There is no new line in between. + // Associate the code between "lastGeneratedColumn" and + // "mapping.generatedColumn" with "lastMapping" + var nextLine = remainingLines[remainingLinesIndex] || ''; + var code = nextLine.substr( + 0, + mapping.generatedColumn - lastGeneratedColumn + ); + remainingLines[remainingLinesIndex] = nextLine.substr( + mapping.generatedColumn - lastGeneratedColumn + ); + lastGeneratedColumn = mapping.generatedColumn; + addMappingWithCode(lastMapping, code); + // No more remaining code, continue + lastMapping = mapping; + return; + } + } + // We add the generated code until the first mapping + // to the SourceNode without any mapping. + // Each line is added as separate string. + while (lastGeneratedLine < mapping.generatedLine) { + if (remainingLinesIndex >= remainingLines.length) { + // The generated code is exhausted. Skip the rest instead of adding + // empty lines one by one: a mapping may point far past the end of + // the code (e.g. an indexed map section with a huge offset.line). + lastGeneratedLine = mapping.generatedLine; + break; + } + node.add(shiftNextLine()); + lastGeneratedLine++; + } + if (lastGeneratedColumn < mapping.generatedColumn) { + var nextLine = remainingLines[remainingLinesIndex] || ''; + node.add(nextLine.substr(0, mapping.generatedColumn)); + remainingLines[remainingLinesIndex] = nextLine.substr( + mapping.generatedColumn + ); + lastGeneratedColumn = mapping.generatedColumn; + } + lastMapping = mapping; + }, this); + // We have processed all mappings. + if (remainingLinesIndex < remainingLines.length) { + if (lastMapping) { + // Associate the remaining code in the current line with "lastMapping" + addMappingWithCode(lastMapping, shiftNextLine()); + } + // and add the remaining lines without any mapping + node.add(remainingLines.splice(remainingLinesIndex).join('')); + } + + // Copy sourcesContent into SourceNode + aSourceMapConsumer.sources.forEach(function (sourceFile) { + var content = aSourceMapConsumer.sourceContentFor(sourceFile); + if (content != null) { + if (aRelativePath != null) { + sourceFile = util.join(aRelativePath, sourceFile); + } + node.setSourceContent(sourceFile, content); + } + }); + + return node; + + function addMappingWithCode(mapping, code) { + if (mapping === null || mapping.source === undefined) { + node.add(code); + } else { + var source = aRelativePath + ? util.join(aRelativePath, mapping.source) + : mapping.source; + node.add( + new SourceNode( + mapping.originalLine, + mapping.originalColumn, + source, + code, + mapping.name + ) + ); + } + } + }; + +/** + * Add a chunk of generated JS to this source node. + * + * @param aChunk A string snippet of generated JS code, another instance of + * SourceNode, or an array where each member is one of those things. + */ +SourceNode.prototype.add = function SourceNode_add(aChunk) { + if (Array.isArray(aChunk)) { + aChunk.forEach(function (chunk) { + this.add(chunk); + }, this); + } else if (aChunk[isSourceNode] || typeof aChunk === 'string') { + if (aChunk) { + this.children.push(aChunk); + } + } else { + throw new TypeError( + 'Expected a SourceNode, string, or an array of SourceNodes and strings. Got ' + + aChunk + ); + } + return this; +}; + +/** + * Add a chunk of generated JS to the beginning of this source node. + * + * @param aChunk A string snippet of generated JS code, another instance of + * SourceNode, or an array where each member is one of those things. + */ +SourceNode.prototype.prepend = function SourceNode_prepend(aChunk) { + if (Array.isArray(aChunk)) { + for (var i = aChunk.length - 1; i >= 0; i--) { + this.prepend(aChunk[i]); + } + } else if (aChunk[isSourceNode] || typeof aChunk === 'string') { + this.children.unshift(aChunk); + } else { + throw new TypeError( + 'Expected a SourceNode, string, or an array of SourceNodes and strings. Got ' + + aChunk + ); + } + return this; +}; + +/** + * Walk over the tree of JS snippets in this node and its children. The + * walking function is called once for each snippet of JS and is passed that + * snippet and the its original associated source's line/column location. + * + * @param aFn The traversal function. + */ +SourceNode.prototype.walk = function SourceNode_walk(aFn) { + var chunk; + for (var i = 0, len = this.children.length; i < len; i++) { + chunk = this.children[i]; + if (chunk[isSourceNode]) { + chunk.walk(aFn); + } else { + if (chunk !== '') { + aFn(chunk, { + source: this.source, + line: this.line, + column: this.column, + name: this.name, + }); + } + } + } +}; + +/** + * Like `String.prototype.join` except for SourceNodes. Inserts `aStr` between + * each of `this.children`. + * + * @param aSep The separator. + */ +SourceNode.prototype.join = function SourceNode_join(aSep) { + var newChildren; + var i; + var len = this.children.length; + if (len > 0) { + newChildren = []; + for (i = 0; i < len - 1; i++) { + newChildren.push(this.children[i]); + newChildren.push(aSep); + } + newChildren.push(this.children[i]); + this.children = newChildren; + } + return this; +}; + +/** + * Call String.prototype.replace on the very right-most source snippet. Useful + * for trimming whitespace from the end of a source node, etc. + * + * @param aPattern The pattern to replace. + * @param aReplacement The thing to replace the pattern with. + */ +SourceNode.prototype.replaceRight = function SourceNode_replaceRight( + aPattern, + aReplacement +) { + var lastChild = this.children[this.children.length - 1]; + // Without children, lastChild is undefined and the final branch applies. + if (lastChild && lastChild[isSourceNode]) { + lastChild.replaceRight(aPattern, aReplacement); + } else if (typeof lastChild === 'string') { + this.children[this.children.length - 1] = lastChild.replace( + aPattern, + aReplacement + ); + } else { + this.children.push(''.replace(aPattern, aReplacement)); + } + return this; +}; + +/** + * Set the source content for a source file. This will be added to the SourceMapGenerator + * in the sourcesContent field. + * + * @param aSourceFile The filename of the source file + * @param aSourceContent The content of the source file + */ +SourceNode.prototype.setSourceContent = function SourceNode_setSourceContent( + aSourceFile, + aSourceContent +) { + this.sourceContents[util.toSetString(aSourceFile)] = aSourceContent; +}; + +/** + * Walk over the tree of SourceNodes. The walking function is called for each + * source file content and is passed the filename and source content. + * + * @param aFn The traversal function. + */ +SourceNode.prototype.walkSourceContents = + function SourceNode_walkSourceContents(aFn) { + for (var i = 0, len = this.children.length; i < len; i++) { + if (this.children[i][isSourceNode]) { + this.children[i].walkSourceContents(aFn); + } + } + + var sources = Object.keys(this.sourceContents); + for (var i = 0, len = sources.length; i < len; i++) { + aFn(util.fromSetString(sources[i]), this.sourceContents[sources[i]]); + } + }; + +/** + * Return the string representation of this source node. Walks over the tree + * and concatenates all the various snippets together to one string. + */ +SourceNode.prototype.toString = function SourceNode_toString() { + var str = ''; + this.walk(function (chunk) { + str += chunk; + }); + return str; +}; + +/** + * Returns the string representation of this source node along with a source + * map. + */ +SourceNode.prototype.toStringWithSourceMap = + function SourceNode_toStringWithSourceMap(aArgs) { + var generated = { + code: '', + line: 1, + column: 0, + }; + var map = new SourceMapGenerator(aArgs); + var sourceMappingActive = false; + var lastOriginalSource = null; + var lastOriginalLine = null; + var lastOriginalColumn = null; + var lastOriginalName = null; + this.walk(function (chunk, original) { + generated.code += chunk; + if ( + original.source !== null && + original.line !== null && + original.column !== null + ) { + if ( + lastOriginalSource !== original.source || + lastOriginalLine !== original.line || + lastOriginalColumn !== original.column || + lastOriginalName !== original.name + ) { + map.addMapping({ + source: original.source, + original: { + line: original.line, + column: original.column, + }, + generated: { + line: generated.line, + column: generated.column, + }, + name: original.name, + }); + } + lastOriginalSource = original.source; + lastOriginalLine = original.line; + lastOriginalColumn = original.column; + lastOriginalName = original.name; + sourceMappingActive = true; + } else if (sourceMappingActive) { + map.addMapping({ + generated: { + line: generated.line, + column: generated.column, + }, + }); + lastOriginalSource = null; + sourceMappingActive = false; + } + for (var idx = 0, length = chunk.length; idx < length; idx++) { + if (chunk.charCodeAt(idx) === NEWLINE_CODE) { + generated.line++; + generated.column = 0; + // Mappings end at eol + if (idx + 1 === length) { + lastOriginalSource = null; + sourceMappingActive = false; + } else if (sourceMappingActive) { + map.addMapping({ + source: original.source, + original: { + line: original.line, + column: original.column, + }, + generated: { + line: generated.line, + column: generated.column, + }, + name: original.name, + }); + } + } else { + generated.column++; + } + } + }); + this.walkSourceContents(function (sourceFile, sourceContent) { + map.setSourceContent(sourceFile, sourceContent); + }); + + return { code: generated.code, map: map }; + }; + +exports.SourceNode = SourceNode; diff --git a/dg-ui/node_modules/source-map-js/lib/util.js b/dg-ui/node_modules/source-map-js/lib/util.js new file mode 100644 index 0000000..baa5c33 --- /dev/null +++ b/dg-ui/node_modules/source-map-js/lib/util.js @@ -0,0 +1,613 @@ +/* -*- Mode: js; js-indent-level: 2; -*- */ +/* + * Copyright 2011 Mozilla Foundation and contributors + * Licensed under the New BSD license. See LICENSE or: + * http://opensource.org/licenses/BSD-3-Clause + */ + +/** + * This is a helper function for getting values from parameter/options + * objects. + * + * @param args The object we are extracting values from + * @param name The name of the property we are getting. + * @param defaultValue An optional value to return if the property is missing + * from the object. If this is not specified and the property is missing, an + * error will be thrown. + */ +function getArg(aArgs, aName, aDefaultValue) { + if (aName in aArgs) { + return aArgs[aName]; + } else if (arguments.length === 3) { + return aDefaultValue; + } else { + throw new Error('"' + aName + '" is a required argument.'); + } +} +exports.getArg = getArg; + +var urlRegexp = + /^(?:([\w+\-.]+):)?\/\/(?:(\w+:\w+)@)?([\w.-]*)(?::(\d+))?(.*)$/; +var dataUrlRegexp = /^data:.+\,.+$/; + +function urlParse(aUrl) { + var match = aUrl.match(urlRegexp); + if (!match) { + return null; + } + return { + scheme: match[1], + auth: match[2], + host: match[3], + port: match[4], + path: match[5], + }; +} +exports.urlParse = urlParse; + +function urlGenerate(aParsedUrl) { + var url = ''; + if (aParsedUrl.scheme) { + url += aParsedUrl.scheme + ':'; + } + url += '//'; + if (aParsedUrl.auth) { + url += aParsedUrl.auth + '@'; + } + if (aParsedUrl.host) { + url += aParsedUrl.host; + } + if (aParsedUrl.port) { + url += ':' + aParsedUrl.port; + } + if (aParsedUrl.path) { + url += aParsedUrl.path; + } + return url; +} +exports.urlGenerate = urlGenerate; + +var MAX_CACHED_INPUTS = 32; + +/** + * Takes some function `f(input) -> result` and returns a memoized version of + * `f`. + * + * We keep at most `MAX_CACHED_INPUTS` memoized results of `f` alive. The + * memoization is a dumb-simple, linear least-recently-used cache. + */ +function lruMemoize(f) { + var cache = []; + + return function (input) { + for (var i = 0; i < cache.length; i++) { + if (cache[i].input === input) { + var temp = cache[0]; + cache[0] = cache[i]; + cache[i] = temp; + return cache[0].result; + } + } + + var result = f(input); + + cache.unshift({ + input, + result, + }); + + if (cache.length > MAX_CACHED_INPUTS) { + cache.pop(); + } + + return result; + }; +} + +/** + * Normalizes a path, or the path portion of a URL: + * + * - Replaces consecutive slashes with one slash. + * - Removes unnecessary '.' parts. + * - Removes unnecessary '/..' parts. + * + * Based on code in the Node.js 'path' core module. + * + * @param aPath The path or url to normalize. + */ +var normalize = lruMemoize(function normalize(aPath) { + var path = aPath; + var url = urlParse(aPath); + if (url) { + if (!url.path) { + return aPath; + } + path = url.path; + } + var isAbsolute = exports.isAbsolute(path); + // Split the path into parts between `/` characters. This is much faster than + // using `.split(/\/+/g)`. + var parts = []; + var start = 0; + var i = 0; + while (true) { + start = i; + i = path.indexOf('/', start); + if (i === -1) { + parts.push(path.slice(start)); + break; + } else { + parts.push(path.slice(start, i)); + while (i < path.length && path[i] === '/') { + i++; + } + } + } + + for (var part, up = 0, i = parts.length - 1; i >= 0; i--) { + part = parts[i]; + if (part === '.') { + parts.splice(i, 1); + } else if (part === '..') { + up++; + } else if (up > 0) { + if (part === '') { + // The first part is blank if the path is absolute. Trying to go + // above the root is a no-op. Therefore we can remove all '..' parts + // directly after the root. + parts.splice(i + 1, up); + up = 0; + } else { + parts.splice(i, 2); + up--; + } + } + } + path = parts.join('/'); + + if (path === '') { + path = isAbsolute ? '/' : '.'; + } + + if (url) { + url.path = path; + return urlGenerate(url); + } + return path; +}); +exports.normalize = normalize; + +/** + * Joins two paths/URLs. + * + * @param aRoot The root path or URL. + * @param aPath The path or URL to be joined with the root. + * + * - If aPath is a URL or a data URI, aPath is returned, unless aPath is a + * scheme-relative URL: Then the scheme of aRoot, if any, is prepended + * first. + * - Otherwise aPath is a path. If aRoot is a URL, then its path portion + * is updated with the result and aRoot is returned. Otherwise the result + * is returned. + * - If aPath is absolute, the result is aPath. + * - Otherwise the two paths are joined with a slash. + * - Joining for example 'http://' and 'www.example.com' is also supported. + */ +function join(aRoot, aPath) { + if (aRoot === '') { + aRoot = '.'; + } + if (aPath === '') { + aPath = '.'; + } + var aPathUrl = urlParse(aPath); + var aRootUrl = urlParse(aRoot); + if (aRootUrl) { + aRoot = aRootUrl.path || '/'; + } + + // `join(foo, '//www.example.org')` + if (aPathUrl && !aPathUrl.scheme) { + if (aRootUrl) { + aPathUrl.scheme = aRootUrl.scheme; + } + return urlGenerate(aPathUrl); + } + + if (aPathUrl || aPath.match(dataUrlRegexp)) { + return aPath; + } + + // `join('http://', 'www.example.com')` + if (aRootUrl && !aRootUrl.host && !aRootUrl.path) { + aRootUrl.host = aPath; + return urlGenerate(aRootUrl); + } + + var joined = + aPath.charAt(0) === '/' + ? aPath + : normalize(aRoot.replace(/\/+$/, '') + '/' + aPath); + + if (aRootUrl) { + aRootUrl.path = joined; + return urlGenerate(aRootUrl); + } + return joined; +} +exports.join = join; + +exports.isAbsolute = function (aPath) { + return aPath.charAt(0) === '/' || urlRegexp.test(aPath); +}; + +/** + * Make a path relative to a URL or another path. + * + * @param aRoot The root path or URL. + * @param aPath The path or URL to be made relative to aRoot. + */ +function relative(aRoot, aPath) { + if (aRoot === '') { + aRoot = '.'; + } + + aRoot = aRoot.replace(/\/$/, ''); + + // It is possible for the path to be above the root. In this case, simply + // checking whether the root is a prefix of the path won't work. Instead, we + // need to remove components from the root one by one, until either we find + // a prefix that fits, or we run out of components to remove. + var level = 0; + while (aPath.indexOf(aRoot + '/') !== 0) { + var index = aRoot.lastIndexOf('/'); + if (index < 0) { + return aPath; + } + + // If the only part of the root that is left is the scheme (i.e. http://, + // file:///, etc.), one or more slashes (/), or simply nothing at all, we + // have exhausted all components, so the path is not relative to the root. + aRoot = aRoot.slice(0, index); + if (aRoot.match(/^([^\/]+:\/)?\/*$/)) { + return aPath; + } + + ++level; + } + + // Make sure we add a "../" for each component we removed from the root. + return Array(level + 1).join('../') + aPath.substr(aRoot.length + 1); +} +exports.relative = relative; + +var supportsNullProto = (function () { + var obj = Object.create(null); + return !('__proto__' in obj); +})(); + +function identity(s) { + return s; +} + +/** + * Because behavior goes wacky when you set `__proto__` on objects, we + * have to prefix all the strings in our set with an arbitrary character. + * + * See https://github.com/mozilla/source-map/pull/31 and + * https://github.com/mozilla/source-map/issues/30 + * + * @param String aStr + */ +function toSetString(aStr) { + if (isProtoString(aStr)) { + return '$' + aStr; + } + + return aStr; +} +exports.toSetString = supportsNullProto ? identity : toSetString; + +function fromSetString(aStr) { + if (isProtoString(aStr)) { + return aStr.slice(1); + } + + return aStr; +} +exports.fromSetString = supportsNullProto ? identity : fromSetString; + +function isProtoString(s) { + if (!s) { + return false; + } + + var length = s.length; + + if (length < 9 /* "__proto__".length */) { + return false; + } + + if ( + s.charCodeAt(length - 1) !== 95 /* '_' */ || + s.charCodeAt(length - 2) !== 95 /* '_' */ || + s.charCodeAt(length - 3) !== 111 /* 'o' */ || + s.charCodeAt(length - 4) !== 116 /* 't' */ || + s.charCodeAt(length - 5) !== 111 /* 'o' */ || + s.charCodeAt(length - 6) !== 114 /* 'r' */ || + s.charCodeAt(length - 7) !== 112 /* 'p' */ || + s.charCodeAt(length - 8) !== 95 /* '_' */ || + s.charCodeAt(length - 9) !== 95 /* '_' */ + ) { + return false; + } + + for (var i = length - 10; i >= 0; i--) { + if (s.charCodeAt(i) !== 36 /* '$' */) { + return false; + } + } + + return true; +} + +/** + * Comparator between two mappings where the original positions are compared. + * + * Optionally pass in `true` as `onlyCompareGenerated` to consider two + * mappings with the same original source/line/column, but different generated + * line and column the same. Useful when searching for a mapping with a + * stubbed out mapping. + */ +function compareByOriginalPositions(mappingA, mappingB, onlyCompareOriginal) { + var cmp = strcmp(mappingA.source, mappingB.source); + if (cmp !== 0) { + return cmp; + } + + cmp = mappingA.originalLine - mappingB.originalLine; + if (cmp !== 0) { + return cmp; + } + + cmp = mappingA.originalColumn - mappingB.originalColumn; + if (cmp !== 0 || onlyCompareOriginal) { + return cmp; + } + + cmp = mappingA.generatedColumn - mappingB.generatedColumn; + if (cmp !== 0) { + return cmp; + } + + cmp = mappingA.generatedLine - mappingB.generatedLine; + if (cmp !== 0) { + return cmp; + } + + return strcmp(mappingA.name, mappingB.name); +} +exports.compareByOriginalPositions = compareByOriginalPositions; + +function compareByOriginalPositionsNoSource( + mappingA, + mappingB, + onlyCompareOriginal +) { + var cmp; + + cmp = mappingA.originalLine - mappingB.originalLine; + if (cmp !== 0) { + return cmp; + } + + cmp = mappingA.originalColumn - mappingB.originalColumn; + if (cmp !== 0 || onlyCompareOriginal) { + return cmp; + } + + cmp = mappingA.generatedColumn - mappingB.generatedColumn; + if (cmp !== 0) { + return cmp; + } + + cmp = mappingA.generatedLine - mappingB.generatedLine; + if (cmp !== 0) { + return cmp; + } + + return strcmp(mappingA.name, mappingB.name); +} +exports.compareByOriginalPositionsNoSource = compareByOriginalPositionsNoSource; + +/** + * Comparator between two mappings with deflated source and name indices where + * the generated positions are compared. + * + * Optionally pass in `true` as `onlyCompareGenerated` to consider two + * mappings with the same generated line and column, but different + * source/name/original line and column the same. Useful when searching for a + * mapping with a stubbed out mapping. + */ +function compareByGeneratedPositionsDeflated( + mappingA, + mappingB, + onlyCompareGenerated +) { + var cmp = mappingA.generatedLine - mappingB.generatedLine; + if (cmp !== 0) { + return cmp; + } + + cmp = mappingA.generatedColumn - mappingB.generatedColumn; + if (cmp !== 0 || onlyCompareGenerated) { + return cmp; + } + + cmp = strcmp(mappingA.source, mappingB.source); + if (cmp !== 0) { + return cmp; + } + + cmp = mappingA.originalLine - mappingB.originalLine; + if (cmp !== 0) { + return cmp; + } + + cmp = mappingA.originalColumn - mappingB.originalColumn; + if (cmp !== 0) { + return cmp; + } + + return strcmp(mappingA.name, mappingB.name); +} +exports.compareByGeneratedPositionsDeflated = + compareByGeneratedPositionsDeflated; + +function compareByGeneratedPositionsDeflatedNoLine( + mappingA, + mappingB, + onlyCompareGenerated +) { + var cmp = mappingA.generatedColumn - mappingB.generatedColumn; + if (cmp !== 0 || onlyCompareGenerated) { + return cmp; + } + + cmp = strcmp(mappingA.source, mappingB.source); + if (cmp !== 0) { + return cmp; + } + + cmp = mappingA.originalLine - mappingB.originalLine; + if (cmp !== 0) { + return cmp; + } + + cmp = mappingA.originalColumn - mappingB.originalColumn; + if (cmp !== 0) { + return cmp; + } + + return strcmp(mappingA.name, mappingB.name); +} +exports.compareByGeneratedPositionsDeflatedNoLine = + compareByGeneratedPositionsDeflatedNoLine; + +function strcmp(aStr1, aStr2) { + if (aStr1 === aStr2) { + return 0; + } + + if (aStr1 === null) { + return 1; // aStr2 !== null + } + + if (aStr2 === null) { + return -1; // aStr1 !== null + } + + if (aStr1 > aStr2) { + return 1; + } + + return -1; +} + +/** + * Comparator between two mappings with inflated source and name strings where + * the generated positions are compared. + */ +function compareByGeneratedPositionsInflated(mappingA, mappingB) { + var cmp = mappingA.generatedLine - mappingB.generatedLine; + if (cmp !== 0) { + return cmp; + } + + cmp = mappingA.generatedColumn - mappingB.generatedColumn; + if (cmp !== 0) { + return cmp; + } + + cmp = strcmp(mappingA.source, mappingB.source); + if (cmp !== 0) { + return cmp; + } + + cmp = mappingA.originalLine - mappingB.originalLine; + if (cmp !== 0) { + return cmp; + } + + cmp = mappingA.originalColumn - mappingB.originalColumn; + if (cmp !== 0) { + return cmp; + } + + return strcmp(mappingA.name, mappingB.name); +} +exports.compareByGeneratedPositionsInflated = + compareByGeneratedPositionsInflated; + +/** + * Strip any JSON XSSI avoidance prefix from the string (as documented + * in the source maps specification), and then parse the string as + * JSON. + */ +function parseSourceMapInput(str) { + return JSON.parse(str.replace(/^\)]}'[^\n]*\n/, '')); +} +exports.parseSourceMapInput = parseSourceMapInput; + +/** + * Compute the URL of a source given the the source root, the source's + * URL, and the source map's URL. + */ +function computeSourceURL(sourceRoot, sourceURL, sourceMapURL) { + sourceURL = sourceURL || ''; + + if (sourceRoot) { + // This follows what Chrome does. + if (sourceRoot[sourceRoot.length - 1] !== '/' && sourceURL[0] !== '/') { + sourceRoot += '/'; + } + // The spec says: + // Line 4: An optional source root, useful for relocating source + // files on a server or removing repeated values in the + // “sources” entry. This value is prepended to the individual + // entries in the “source” field. + sourceURL = sourceRoot + sourceURL; + } + + // Historically, SourceMapConsumer did not take the sourceMapURL as + // a parameter. This mode is still somewhat supported, which is why + // this code block is conditional. However, it's preferable to pass + // the source map URL to SourceMapConsumer, so that this function + // can implement the source URL resolution algorithm as outlined in + // the spec. This block is basically the equivalent of: + // new URL(sourceURL, sourceMapURL).toString() + // ... except it avoids using URL, which wasn't available in the + // older releases of node still supported by this library. + // + // The spec says: + // If the sources are not absolute URLs after prepending of the + // “sourceRoot”, the sources are resolved relative to the + // SourceMap (like resolving script src in a html document). + if (sourceMapURL) { + var parsed = urlParse(sourceMapURL); + if (!parsed) { + throw new Error('sourceMapURL could not be parsed'); + } + if (parsed.path) { + // Strip the last path component, but keep the "/". + var index = parsed.path.lastIndexOf('/'); + if (index >= 0) { + parsed.path = parsed.path.substring(0, index + 1); + } + } + sourceURL = join(urlGenerate(parsed), sourceURL); + } + + return normalize(sourceURL); +} +exports.computeSourceURL = computeSourceURL; diff --git a/dg-ui/node_modules/source-map-js/package.json b/dg-ui/node_modules/source-map-js/package.json new file mode 100644 index 0000000..0c7ec6a --- /dev/null +++ b/dg-ui/node_modules/source-map-js/package.json @@ -0,0 +1,78 @@ +{ + "name": "source-map-js", + "description": "Generates and consumes source maps", + "version": "1.2.4", + "homepage": "https://github.com/7rulnik/source-map-js", + "author": "Valentin 7rulnik Semirulnik ", + "contributors": [ + "Nick Fitzgerald ", + "Tobias Koppers ", + "Duncan Beevers ", + "Stephen Crane ", + "Ryan Seddon ", + "Miles Elam ", + "Mihai Bazon ", + "Michael Ficarra ", + "Todd Wolfson ", + "Alexander Solovyov ", + "Felix Gnass ", + "Conrad Irwin ", + "usrbincc ", + "David Glasser ", + "Chase Douglas ", + "Evan Wallace ", + "Heather Arthur ", + "Hugh Kennedy ", + "David Glasser ", + "Simon Lydell ", + "Jmeas Smith ", + "Michael Z Goddard ", + "azu ", + "John Gozde ", + "Adam Kirkton ", + "Chris Montgomery ", + "J. Ryan Stinnett ", + "Jack Herrington ", + "Chris Truter ", + "Daniel Espeset ", + "Jamie Wong ", + "Eddy Bruël ", + "Hawken Rives ", + "Gilad Peleg ", + "djchie ", + "Gary Ye ", + "Nicolas Lalevée " + ], + "repository": "7rulnik/source-map-js", + "main": "./source-map.js", + "files": [ + "source-map.js", + "source-map.d.ts", + "lib/" + ], + "engines": { + "node": ">=6.0.0" + }, + "license": "BSD-3-Clause", + "scripts": { + "test": "node --test --test-reporter=spec 'test/test-*.js'", + "test:coverage": "node --experimental-config-file=node.config.json --test --test-reporter=spec --experimental-test-coverage 'test/test-*.js'", + "format": "prettier --write .", + "format:check": "prettier --check .", + "toc": "doctoc --title '## Table of Contents' README.md && prettier --write README.md" + }, + "devDependencies": { + "clean-publish": "^3.1.0", + "doctoc": "^0.15.0", + "prettier": "3.10.1" + }, + "prettier": { + "singleQuote": true, + "trailingComma": "es5" + }, + "clean-publish": { + "cleanDocs": true + }, + "typings": "source-map.d.ts", + "packageManager": "pnpm@12.21.0" +} diff --git a/dg-ui/node_modules/source-map-js/source-map.d.ts b/dg-ui/node_modules/source-map-js/source-map.d.ts new file mode 100644 index 0000000..c973fd3 --- /dev/null +++ b/dg-ui/node_modules/source-map-js/source-map.d.ts @@ -0,0 +1,218 @@ +export interface StartOfSourceMap { + file?: string; + sourceRoot?: string; +} + +/** + * A source map as `SourceMapGenerator#toJSON` returns it. For a source map + * passed to `SourceMapConsumer`, use `RawSourceMapInput`. + */ +export interface RawSourceMap extends StartOfSourceMap { + /** The number `3` at runtime. Typed as a string for backward compatibility. */ + version: string; + sources: string[]; + names: string[]; + /** + * `null` for each source without content at runtime. Typed as `string[]` + * for backward compatibility. + */ + sourcesContent?: string[]; + mappings: string; +} + +/** + * A source map as `SourceMapConsumer` accepts it. Unlike `RawSourceMap`, the + * `version` can be a number, `sourcesContent` can have `null` entries, and + * `names` can be left out. + */ +export interface RawSourceMapInput extends StartOfSourceMap { + version: number | string; + sources: string[]; + names?: string[]; + sourcesContent?: (string | null)[]; + mappings: string; +} + +export interface RawSection { + /** Where the section starts in the generated code. Both are 0-based. */ + offset: Position; + map: RawSourceMapInput | RawIndexMap; +} + +/** A source map made of sections, each with its own source map. */ +export interface RawIndexMap { + version: number | string; + file?: string; + sections: RawSection[]; +} + +export interface Position { + line: number; + column: number; +} + +export interface LineRange extends Position { + lastColumn: number; +} + +export interface FindPosition extends Position { + // SourceMapConsumer.GREATEST_LOWER_BOUND or SourceMapConsumer.LEAST_UPPER_BOUND + bias?: number; +} + +export interface SourceFindPosition extends FindPosition { + source: string; +} + +export interface MappedPosition extends Position { + source: string; + name?: string; +} + +export interface MappingItem { + source: string | null; + generatedLine: number; + generatedColumn: number; + originalLine: number | null; + originalColumn: number | null; + name: string | null; +} + +export class SourceMapConsumer { + static GENERATED_ORDER: number; + static ORIGINAL_ORDER: number; + + static GREATEST_LOWER_BOUND: number; + static LEAST_UPPER_BOUND: number; + + /** + * @param rawSourceMap A source map or an index map, as an object or as a + * JSON string. + * @param sourceMapUrl The URL of the source map. Relative `sources` are + * resolved against it. + */ + constructor( + rawSourceMap: RawSourceMapInput | RawIndexMap | string, + sourceMapUrl?: string + ); + static fromSourceMap( + sourceMap: SourceMapGenerator, + sourceMapUrl?: string + ): SourceMapConsumer; + readonly file: string | undefined | null; + readonly sourceRoot: string | undefined | null; + /** Can have `null` entries at runtime: one for each source without content. */ + readonly sourcesContent: readonly string[] | null | undefined; + readonly sources: readonly string[]; + + computeColumnSpans(): void; + /** + * At runtime, `source`, `line`, `column` and `name` are all `null` when no + * mapping is found, and `name` is `null` when the mapping has no name. + */ + originalPositionFor(generatedPosition: FindPosition): MappedPosition; + /** + * At runtime, `line`, `column` and `lastColumn` are all `null` when no + * mapping is found, and `lastColumn` is `null` until `computeColumnSpans()` + * is called. + */ + generatedPositionFor(originalPosition: SourceFindPosition): LineRange; + /** + * Without a `column`, returns the mappings of the line, or of the next line + * that has mappings. `lastColumn` is `null` until `computeColumnSpans()` is + * called. + */ + allGeneratedPositionsFor( + originalPosition: + MappedPosition | { source: string; line: number; column?: number } + ): Array; + hasContentsOfAllSources(): boolean; + sourceContentFor( + source: string, + returnNullOnMissing?: boolean + ): string | null; + eachMapping( + callback: (mapping: MappingItem) => void, + context?: any, + order?: number + ): void; +} + +export interface Mapping { + generated: Position; + original?: Position | null; + source?: string | null; + name?: string | null; +} + +export interface SourceMapGeneratorOptions extends StartOfSourceMap { + /** Don't validate mappings in `addMapping`. */ + skipValidation?: boolean; + /** Warn about invalid mappings and skip them, instead of throwing. */ + ignoreInvalidMapping?: boolean; +} + +export class SourceMapGenerator { + constructor(startOfSourceMap?: SourceMapGeneratorOptions); + static fromSourceMap( + sourceMapConsumer: SourceMapConsumer, + startOfSourceMap?: SourceMapGeneratorOptions + ): SourceMapGenerator; + addMapping(mapping: Mapping): void; + setSourceContent( + sourceFile: string, + sourceContent: string | null | undefined + ): void; + applySourceMap( + sourceMapConsumer: SourceMapConsumer, + sourceFile?: string, + sourceMapPath?: string + ): void; + toString(): string; + toJSON(): RawSourceMap; +} + +export interface CodeWithSourceMap { + code: string; + map: SourceMapGenerator; +} + +/** A string of generated code, a `SourceNode`, or an array of chunks. */ +export type SourceNodeChunk = string | SourceNode | SourceNodeChunkArray; +export interface SourceNodeChunkArray extends Array {} + +export class SourceNode { + constructor(); + constructor( + line: number | null, + column: number | null, + source: string | null, + chunks?: SourceNodeChunk, + name?: string | null + ); + static fromStringWithSourceMap( + code: string, + sourceMapConsumer: SourceMapConsumer, + relativePath?: string + ): SourceNode; + /** Returns this node at runtime. */ + add(chunk: SourceNodeChunk): void; + /** Returns this node at runtime. */ + prepend(chunk: SourceNodeChunk): void; + setSourceContent(sourceFile: string, sourceContent: string): void; + /** + * At runtime, `source`, `line`, `column` and `name` are `null` for chunks + * without an original position, and `name` is `null` when there's no name. + */ + walk(fn: (chunk: string, mapping: MappedPosition) => void): void; + walkSourceContents(fn: (file: string, content: string) => void): void; + join(sep: string): SourceNode; + replaceRight( + pattern: string | RegExp, + replacement: string | ((substring: string, ...args: any[]) => string) + ): SourceNode; + toString(): string; + toStringWithSourceMap( + startOfSourceMap?: SourceMapGeneratorOptions + ): CodeWithSourceMap; +} diff --git a/dg-ui/node_modules/source-map-js/source-map.js b/dg-ui/node_modules/source-map-js/source-map.js new file mode 100644 index 0000000..db6a0a0 --- /dev/null +++ b/dg-ui/node_modules/source-map-js/source-map.js @@ -0,0 +1,10 @@ +/* + * Copyright 2009-2011 Mozilla Foundation and contributors + * Licensed under the New BSD license. See LICENSE.txt or: + * http://opensource.org/licenses/BSD-3-Clause + */ +exports.SourceMapGenerator = + require('./lib/source-map-generator').SourceMapGenerator; +exports.SourceMapConsumer = + require('./lib/source-map-consumer').SourceMapConsumer; +exports.SourceNode = require('./lib/source-node').SourceNode; diff --git a/dg-ui/node_modules/tailwindcss/LICENSE b/dg-ui/node_modules/tailwindcss/LICENSE new file mode 100644 index 0000000..d6a8229 --- /dev/null +++ b/dg-ui/node_modules/tailwindcss/LICENSE @@ -0,0 +1,21 @@ +MIT License + +Copyright (c) Tailwind Labs, Inc. + +Permission is hereby granted, free of charge, to any person obtaining a copy +of this software and associated documentation files (the "Software"), to deal +in the Software without restriction, including without limitation the rights +to use, copy, modify, merge, publish, distribute, sublicense, and/or sell +copies of the Software, and to permit persons to whom the Software is +furnished to do so, subject to the following conditions: + +The above copyright notice and this permission notice shall be included in all +copies or substantial portions of the Software. + +THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR +IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, +FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE +AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER +LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, +OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE +SOFTWARE. diff --git a/dg-ui/node_modules/tailwindcss/README.md b/dg-ui/node_modules/tailwindcss/README.md new file mode 100644 index 0000000..5f53260 --- /dev/null +++ b/dg-ui/node_modules/tailwindcss/README.md @@ -0,0 +1,36 @@ +

+ + + + + Tailwind CSS + + +

+ +

+ A utility-first CSS framework for rapidly building custom user interfaces. +

+ +

+ Build Status + Total Downloads + Latest Release + License +

+ +--- + +## Documentation + +For full documentation, visit [tailwindcss.com](https://tailwindcss.com). + +## Community + +For help, discussion about best practices, or feature ideas: + +[Discuss Tailwind CSS on GitHub](https://github.com/tailwindlabs/tailwindcss/discussions) + +## Contributing + +If you're interested in contributing to Tailwind CSS, please read our [contributing docs](https://github.com/tailwindlabs/tailwindcss/blob/main/.github/CONTRIBUTING.md) **before submitting a pull request**. diff --git a/dg-ui/node_modules/tailwindcss/dist/chunk-3IIMCCN4.mjs b/dg-ui/node_modules/tailwindcss/dist/chunk-3IIMCCN4.mjs new file mode 100644 index 0000000..409dd4e --- /dev/null +++ b/dg-ui/node_modules/tailwindcss/dist/chunk-3IIMCCN4.mjs @@ -0,0 +1 @@ +function h(n){if(arguments.length===0)throw new TypeError("`CSS.escape` requires an argument.");let e=String(n),r=e.length,i=-1,t,s="",l=e.charCodeAt(0);if(r===1&&l===45)return"\\"+e;for(;++i=1&&t<=31||t===127||i===0&&t>=48&&t<=57||i===1&&t>=48&&t<=57&&l===45){s+="\\"+t.toString(16)+" ";continue}if(t>=128||t===45||t===95||t>=48&&t<=57||t>=65&&t<=90||t>=97&&t<=122){s+=e.charAt(i);continue}s+="\\"+e.charAt(i)}return s}function a(n){return n.replace(/\\(?:([\dA-Fa-f]{1,6})[\t\n\f\r ]?|([\S\s]))/g,(e,r,i)=>{if(!r)return i;let t=Number.parseInt(r,16);return t===0||t>1114111||t>=55296&&t<=57343?"\uFFFD":String.fromCodePoint(t)})}var c=new Map([["--font",["--font-weight","--font-size"]],["--inset",["--inset-shadow","--inset-ring"]],["--text",["--text-color","--text-decoration-color","--text-decoration-thickness","--text-indent","--text-shadow","--text-underline-offset"]],["--grid-column",["--grid-column-start","--grid-column-end"]],["--grid-row",["--grid-row-start","--grid-row-end"]]]);function g(n,e){return(c.get(e)??[]).some(r=>n===r||n.startsWith(`${r}-`))}var p=class{constructor(e=new Map,r=new Set([])){this.values=e;this.keyframes=r}values;keyframes;prefix=null;get size(){return this.values.size}add(e,r,i=0,t){if(e.endsWith("-*")){if(r!=="initial")throw new Error(`Invalid theme value \`${r}\` for namespace \`${e}\``);e==="--*"?this.values.clear():this.clearNamespace(e.slice(0,-2),0)}if(i&4){let s=this.values.get(e);if(s&&!(s.options&4))return}r==="initial"?this.values.delete(e):this.values.set(e,{value:r,options:i,src:t})}keysInNamespaces(e){let r=[];for(let i of e){let t=`${i}-`;for(let s of this.values.keys())s.startsWith(t)&&s.indexOf("--",2)===-1&&(g(s,i)||r.push(s.slice(t.length)))}return r}get(e){for(let r of e){let i=this.values.get(r);if(i)return i.value}return null}hasDefault(e){return(this.getOptions(e)&4)===4}getOptions(e){return e=a(this.#i(e)),this.values.get(e)?.options??0}entries(){return this.prefix?Array.from(this.values,e=>(e[0]=this.prefixKey(e[0]),e)):this.values.entries()}prefixKey(e){return this.prefix?`--${this.prefix}-${e.slice(2)}`:e}#i(e){return this.prefix?`--${e.slice(3+this.prefix.length)}`:e}clearNamespace(e,r){let i=c.get(e)??[];e:for(let t of this.values.keys())if(t.startsWith(e)){if(r!==0&&(this.getOptions(t)&r)!==r)continue;for(let s of i)if(t.startsWith(s))continue e;this.values.delete(t)}}#e(e,r){for(let i of r){let t=e!==null?`${i}-${e}`:i;if(!this.values.has(t))if(e!==null&&e.includes(".")){if(t=`${i}-${e.replaceAll(".","_")}`,!this.values.has(t))continue}else continue;if(!g(t,i))return t}return null}#t(e){let r=this.values.get(e);if(!r)return null;let i=null;return r.options&2&&(i=r.value),`var(${h(this.prefixKey(e))}${i?`, ${i}`:""})`}markUsedVariable(e){let r=a(this.#i(e)),i=this.values.get(r);if(!i)return!1;let t=i.options&16;return i.options|=16,!t}resolve(e,r,i=0){let t=this.#e(e,r);if(!t)return null;let s=this.values.get(t);return(i|s.options)&1?s.value:this.#t(t)}resolveValue(e,r){let i=this.#e(e,r);return i?this.values.get(i).value:null}resolveWith(e,r,i=[]){let t=this.#e(e,r);if(!t)return null;let s={};for(let u of i){let f=`${t}${u}`,o=this.values.get(f);o&&(o.options&1?s[u]=o.value:s[u]=this.#t(f))}let l=this.values.get(t);return l.options&1?[l.value,s]:[this.#t(t),s]}namespace(e){let r=new Map,i=`${e}-`;for(let[t,s]of this.values)t===e?r.set(null,s.value):t.startsWith(`${i}-`)?r.set(t.slice(e.length),s.value):t.startsWith(i)&&r.set(t.slice(i.length),s.value);return r}addKeyframes(e){this.keyframes.add(e)}getKeyframes(){return Array.from(this.keyframes)}};export{h as a,a as b,p as c}; diff --git a/dg-ui/node_modules/tailwindcss/dist/chunk-DCG7AFIE.mjs b/dg-ui/node_modules/tailwindcss/dist/chunk-DCG7AFIE.mjs new file mode 100644 index 0000000..5c316db --- /dev/null +++ b/dg-ui/node_modules/tailwindcss/dist/chunk-DCG7AFIE.mjs @@ -0,0 +1 @@ +var o={inherit:"inherit",current:"currentcolor",transparent:"transparent",black:"#000",white:"#fff",slate:{50:"oklch(98.4% 0.003 247.858)",100:"oklch(96.8% 0.007 247.896)",200:"oklch(92.9% 0.013 255.508)",300:"oklch(86.9% 0.022 252.894)",400:"oklch(70.4% 0.04 256.788)",500:"oklch(55.4% 0.046 257.417)",600:"oklch(44.6% 0.043 257.281)",700:"oklch(37.2% 0.044 257.287)",800:"oklch(27.9% 0.041 260.031)",900:"oklch(20.8% 0.042 265.755)",950:"oklch(12.9% 0.042 264.695)"},gray:{50:"oklch(98.5% 0.002 247.839)",100:"oklch(96.7% 0.003 264.542)",200:"oklch(92.8% 0.006 264.531)",300:"oklch(87.2% 0.01 258.338)",400:"oklch(70.7% 0.022 261.325)",500:"oklch(55.1% 0.027 264.364)",600:"oklch(44.6% 0.03 256.802)",700:"oklch(37.3% 0.034 259.733)",800:"oklch(27.8% 0.033 256.848)",900:"oklch(21% 0.034 264.665)",950:"oklch(13% 0.028 261.692)"},zinc:{50:"oklch(98.5% 0 none)",100:"oklch(96.7% 0.001 286.375)",200:"oklch(92% 0.004 286.32)",300:"oklch(87.1% 0.006 286.286)",400:"oklch(70.5% 0.015 286.067)",500:"oklch(55.2% 0.016 285.938)",600:"oklch(44.2% 0.017 285.786)",700:"oklch(37% 0.013 285.805)",800:"oklch(27.4% 0.006 286.033)",900:"oklch(21% 0.006 285.885)",950:"oklch(14.1% 0.005 285.823)"},neutral:{50:"oklch(98.5% 0 none)",100:"oklch(97% 0 none)",200:"oklch(92.2% 0 none)",300:"oklch(87% 0 none)",400:"oklch(70.8% 0 none)",500:"oklch(55.6% 0 none)",600:"oklch(43.9% 0 none)",700:"oklch(37.1% 0 none)",800:"oklch(26.9% 0 none)",900:"oklch(20.5% 0 none)",950:"oklch(14.5% 0 none)"},stone:{50:"oklch(98.5% 0.001 106.423)",100:"oklch(97% 0.001 106.424)",200:"oklch(92.3% 0.003 48.717)",300:"oklch(86.9% 0.005 56.366)",400:"oklch(70.9% 0.01 56.259)",500:"oklch(55.3% 0.013 58.071)",600:"oklch(44.4% 0.011 73.639)",700:"oklch(37.4% 0.01 67.558)",800:"oklch(26.8% 0.007 34.298)",900:"oklch(21.6% 0.006 56.043)",950:"oklch(14.7% 0.004 49.25)"},mauve:{50:"oklch(98.5% 0 none)",100:"oklch(96% 0.003 325.6)",200:"oklch(92.2% 0.005 325.62)",300:"oklch(86.5% 0.012 325.68)",400:"oklch(71.1% 0.019 323.02)",500:"oklch(54.2% 0.034 322.5)",600:"oklch(43.5% 0.029 321.78)",700:"oklch(36.4% 0.029 323.89)",800:"oklch(26.3% 0.024 320.12)",900:"oklch(21.2% 0.019 322.12)",950:"oklch(14.5% 0.008 326)"},olive:{50:"oklch(98.8% 0.003 106.5)",100:"oklch(96.6% 0.005 106.5)",200:"oklch(93% 0.007 106.5)",300:"oklch(88% 0.011 106.6)",400:"oklch(73.7% 0.021 106.9)",500:"oklch(58% 0.031 107.3)",600:"oklch(46.6% 0.025 107.3)",700:"oklch(39.4% 0.023 107.4)",800:"oklch(28.6% 0.016 107.4)",900:"oklch(22.8% 0.013 107.4)",950:"oklch(15.3% 0.006 107.1)"},mist:{50:"oklch(98.7% 0.002 197.1)",100:"oklch(96.3% 0.002 197.1)",200:"oklch(92.5% 0.005 214.3)",300:"oklch(87.2% 0.007 219.6)",400:"oklch(72.3% 0.014 214.4)",500:"oklch(56% 0.021 213.5)",600:"oklch(45% 0.017 213.2)",700:"oklch(37.8% 0.015 216)",800:"oklch(27.5% 0.011 216.9)",900:"oklch(21.8% 0.008 223.9)",950:"oklch(14.8% 0.004 228.8)"},taupe:{50:"oklch(98.6% 0.002 67.8)",100:"oklch(96% 0.002 17.2)",200:"oklch(92.2% 0.005 34.3)",300:"oklch(86.8% 0.007 39.5)",400:"oklch(71.4% 0.014 41.2)",500:"oklch(54.7% 0.021 43.1)",600:"oklch(43.8% 0.017 39.3)",700:"oklch(36.7% 0.016 35.7)",800:"oklch(26.8% 0.011 36.5)",900:"oklch(21.4% 0.009 43.1)",950:"oklch(14.7% 0.004 49.3)"},red:{50:"oklch(97.1% 0.013 17.38)",100:"oklch(93.6% 0.032 17.717)",200:"oklch(88.5% 0.062 18.334)",300:"oklch(80.8% 0.114 19.571)",400:"oklch(70.4% 0.191 22.216)",500:"oklch(63.7% 0.237 25.331)",600:"oklch(57.7% 0.245 27.325)",700:"oklch(50.5% 0.213 27.518)",800:"oklch(44.4% 0.177 26.899)",900:"oklch(39.6% 0.141 25.723)",950:"oklch(25.8% 0.092 26.042)"},orange:{50:"oklch(98% 0.016 73.684)",100:"oklch(95.4% 0.038 75.164)",200:"oklch(90.1% 0.076 70.697)",300:"oklch(83.7% 0.128 66.29)",400:"oklch(75% 0.183 55.934)",500:"oklch(70.5% 0.213 47.604)",600:"oklch(64.6% 0.222 41.116)",700:"oklch(55.3% 0.195 38.402)",800:"oklch(47% 0.157 37.304)",900:"oklch(40.8% 0.123 38.172)",950:"oklch(26.6% 0.079 36.259)"},amber:{50:"oklch(98.7% 0.022 95.277)",100:"oklch(96.2% 0.059 95.617)",200:"oklch(92.4% 0.12 95.746)",300:"oklch(87.9% 0.169 91.605)",400:"oklch(82.8% 0.189 84.429)",500:"oklch(76.9% 0.188 70.08)",600:"oklch(66.6% 0.179 58.318)",700:"oklch(55.5% 0.163 48.998)",800:"oklch(47.3% 0.137 46.201)",900:"oklch(41.4% 0.112 45.904)",950:"oklch(27.9% 0.077 45.635)"},yellow:{50:"oklch(98.7% 0.026 102.212)",100:"oklch(97.3% 0.071 103.193)",200:"oklch(94.5% 0.129 101.54)",300:"oklch(90.5% 0.182 98.111)",400:"oklch(85.2% 0.199 91.936)",500:"oklch(79.5% 0.184 86.047)",600:"oklch(68.1% 0.162 75.834)",700:"oklch(55.4% 0.135 66.442)",800:"oklch(47.6% 0.114 61.907)",900:"oklch(42.1% 0.095 57.708)",950:"oklch(28.6% 0.066 53.813)"},lime:{50:"oklch(98.6% 0.031 120.757)",100:"oklch(96.7% 0.067 122.328)",200:"oklch(93.8% 0.127 124.321)",300:"oklch(89.7% 0.196 126.665)",400:"oklch(84.1% 0.238 128.85)",500:"oklch(76.8% 0.233 130.85)",600:"oklch(64.8% 0.2 131.684)",700:"oklch(53.2% 0.157 131.589)",800:"oklch(45.3% 0.124 130.933)",900:"oklch(40.5% 0.101 131.063)",950:"oklch(27.4% 0.072 132.109)"},green:{50:"oklch(98.2% 0.018 155.826)",100:"oklch(96.2% 0.044 156.743)",200:"oklch(92.5% 0.084 155.995)",300:"oklch(87.1% 0.15 154.449)",400:"oklch(79.2% 0.209 151.711)",500:"oklch(72.3% 0.219 149.579)",600:"oklch(62.7% 0.194 149.214)",700:"oklch(52.7% 0.154 150.069)",800:"oklch(44.8% 0.119 151.328)",900:"oklch(39.3% 0.095 152.535)",950:"oklch(26.6% 0.065 152.934)"},emerald:{50:"oklch(97.9% 0.021 166.113)",100:"oklch(95% 0.052 163.051)",200:"oklch(90.5% 0.093 164.15)",300:"oklch(84.5% 0.143 164.978)",400:"oklch(76.5% 0.177 163.223)",500:"oklch(69.6% 0.17 162.48)",600:"oklch(59.6% 0.145 163.225)",700:"oklch(50.8% 0.118 165.612)",800:"oklch(43.2% 0.095 166.913)",900:"oklch(37.8% 0.077 168.94)",950:"oklch(26.2% 0.051 172.552)"},teal:{50:"oklch(98.4% 0.014 180.72)",100:"oklch(95.3% 0.051 180.801)",200:"oklch(91% 0.096 180.426)",300:"oklch(85.5% 0.138 181.071)",400:"oklch(77.7% 0.152 181.912)",500:"oklch(70.4% 0.14 182.503)",600:"oklch(60% 0.118 184.704)",700:"oklch(51.1% 0.096 186.391)",800:"oklch(43.7% 0.078 188.216)",900:"oklch(38.6% 0.063 188.416)",950:"oklch(27.7% 0.046 192.524)"},cyan:{50:"oklch(98.4% 0.019 200.873)",100:"oklch(95.6% 0.045 203.388)",200:"oklch(91.7% 0.08 205.041)",300:"oklch(86.5% 0.127 207.078)",400:"oklch(78.9% 0.154 211.53)",500:"oklch(71.5% 0.143 215.221)",600:"oklch(60.9% 0.126 221.723)",700:"oklch(52% 0.105 223.128)",800:"oklch(45% 0.085 224.283)",900:"oklch(39.8% 0.07 227.392)",950:"oklch(30.2% 0.056 229.695)"},sky:{50:"oklch(97.7% 0.013 236.62)",100:"oklch(95.1% 0.026 236.824)",200:"oklch(90.1% 0.058 230.902)",300:"oklch(82.8% 0.111 230.318)",400:"oklch(74.6% 0.16 232.661)",500:"oklch(68.5% 0.169 237.323)",600:"oklch(58.8% 0.158 241.966)",700:"oklch(50% 0.134 242.749)",800:"oklch(44.3% 0.11 240.79)",900:"oklch(39.1% 0.09 240.876)",950:"oklch(29.3% 0.066 243.157)"},blue:{50:"oklch(97% 0.014 254.604)",100:"oklch(93.2% 0.032 255.585)",200:"oklch(88.2% 0.059 254.128)",300:"oklch(80.9% 0.105 251.813)",400:"oklch(70.7% 0.165 254.624)",500:"oklch(62.3% 0.214 259.815)",600:"oklch(54.6% 0.245 262.881)",700:"oklch(48.8% 0.243 264.376)",800:"oklch(42.4% 0.199 265.638)",900:"oklch(37.9% 0.146 265.522)",950:"oklch(28.2% 0.091 267.935)"},indigo:{50:"oklch(96.2% 0.018 272.314)",100:"oklch(93% 0.034 272.788)",200:"oklch(87% 0.065 274.039)",300:"oklch(78.5% 0.115 274.713)",400:"oklch(67.3% 0.182 276.935)",500:"oklch(58.5% 0.233 277.117)",600:"oklch(51.1% 0.262 276.966)",700:"oklch(45.7% 0.24 277.023)",800:"oklch(39.8% 0.195 277.366)",900:"oklch(35.9% 0.144 278.697)",950:"oklch(25.7% 0.09 281.288)"},violet:{50:"oklch(96.9% 0.016 293.756)",100:"oklch(94.3% 0.029 294.588)",200:"oklch(89.4% 0.057 293.283)",300:"oklch(81.1% 0.111 293.571)",400:"oklch(70.2% 0.183 293.541)",500:"oklch(60.6% 0.25 292.717)",600:"oklch(54.1% 0.281 293.009)",700:"oklch(49.1% 0.27 292.581)",800:"oklch(43.2% 0.232 292.759)",900:"oklch(38% 0.189 293.745)",950:"oklch(28.3% 0.141 291.089)"},purple:{50:"oklch(97.7% 0.014 308.299)",100:"oklch(94.6% 0.033 307.174)",200:"oklch(90.2% 0.063 306.703)",300:"oklch(82.7% 0.119 306.383)",400:"oklch(71.4% 0.203 305.504)",500:"oklch(62.7% 0.265 303.9)",600:"oklch(55.8% 0.288 302.321)",700:"oklch(49.6% 0.265 301.924)",800:"oklch(43.8% 0.218 303.724)",900:"oklch(38.1% 0.176 304.987)",950:"oklch(29.1% 0.149 302.717)"},fuchsia:{50:"oklch(97.7% 0.017 320.058)",100:"oklch(95.2% 0.037 318.852)",200:"oklch(90.3% 0.076 319.62)",300:"oklch(83.3% 0.145 321.434)",400:"oklch(74% 0.238 322.16)",500:"oklch(66.7% 0.295 322.15)",600:"oklch(59.1% 0.293 322.896)",700:"oklch(51.8% 0.253 323.949)",800:"oklch(45.2% 0.211 324.591)",900:"oklch(40.1% 0.17 325.612)",950:"oklch(29.3% 0.136 325.661)"},pink:{50:"oklch(97.1% 0.014 343.198)",100:"oklch(94.8% 0.028 342.258)",200:"oklch(89.9% 0.061 343.231)",300:"oklch(82.3% 0.12 346.018)",400:"oklch(71.8% 0.202 349.761)",500:"oklch(65.6% 0.241 354.308)",600:"oklch(59.2% 0.249 0.584)",700:"oklch(52.5% 0.223 3.958)",800:"oklch(45.9% 0.187 3.815)",900:"oklch(40.8% 0.153 2.432)",950:"oklch(28.4% 0.109 3.907)"},rose:{50:"oklch(96.9% 0.015 12.422)",100:"oklch(94.1% 0.03 12.58)",200:"oklch(89.2% 0.058 10.001)",300:"oklch(81% 0.117 11.638)",400:"oklch(71.2% 0.194 13.428)",500:"oklch(64.5% 0.246 16.439)",600:"oklch(58.6% 0.253 17.585)",700:"oklch(51.4% 0.222 16.935)",800:"oklch(45.5% 0.188 13.697)",900:"oklch(41% 0.159 10.272)",950:"oklch(27.1% 0.105 12.094)"}};export{o as a}; diff --git a/dg-ui/node_modules/tailwindcss/dist/chunk-JYLR5UAN.mjs b/dg-ui/node_modules/tailwindcss/dist/chunk-JYLR5UAN.mjs new file mode 100644 index 0000000..76b5fd8 --- /dev/null +++ b/dg-ui/node_modules/tailwindcss/dist/chunk-JYLR5UAN.mjs @@ -0,0 +1 @@ +import{a as v}from"./chunk-DCG7AFIE.mjs";var k=new Set(["black","silver","gray","white","maroon","red","purple","fuchsia","green","lime","olive","yellow","navy","blue","teal","aqua","aliceblue","antiquewhite","aqua","aquamarine","azure","beige","bisque","black","blanchedalmond","blue","blueviolet","brown","burlywood","cadetblue","chartreuse","chocolate","coral","cornflowerblue","cornsilk","crimson","cyan","darkblue","darkcyan","darkgoldenrod","darkgray","darkgreen","darkgrey","darkkhaki","darkmagenta","darkolivegreen","darkorange","darkorchid","darkred","darksalmon","darkseagreen","darkslateblue","darkslategray","darkslategrey","darkturquoise","darkviolet","deeppink","deepskyblue","dimgray","dimgrey","dodgerblue","firebrick","floralwhite","forestgreen","fuchsia","gainsboro","ghostwhite","gold","goldenrod","gray","green","greenyellow","grey","honeydew","hotpink","indianred","indigo","ivory","khaki","lavender","lavenderblush","lawngreen","lemonchiffon","lightblue","lightcoral","lightcyan","lightgoldenrodyellow","lightgray","lightgreen","lightgrey","lightpink","lightsalmon","lightseagreen","lightskyblue","lightslategray","lightslategrey","lightsteelblue","lightyellow","lime","limegreen","linen","magenta","maroon","mediumaquamarine","mediumblue","mediumorchid","mediumpurple","mediumseagreen","mediumslateblue","mediumspringgreen","mediumturquoise","mediumvioletred","midnightblue","mintcream","mistyrose","moccasin","navajowhite","navy","oldlace","olive","olivedrab","orange","orangered","orchid","palegoldenrod","palegreen","paleturquoise","palevioletred","papayawhip","peachpuff","peru","pink","plum","powderblue","purple","rebeccapurple","red","rosybrown","royalblue","saddlebrown","salmon","sandybrown","seagreen","seashell","sienna","silver","skyblue","slateblue","slategray","slategrey","snow","springgreen","steelblue","tan","teal","thistle","tomato","turquoise","violet","wheat","white","whitesmoke","yellow","yellowgreen","transparent","currentcolor","canvas","canvastext","linktext","visitedtext","activetext","buttonface","buttontext","buttonborder","field","fieldtext","highlight","highlighttext","selecteditem","selecteditemtext","mark","marktext","graytext","accentcolor","accentcolortext"]),U=/^(rgba?|hsla?|hwb|color|(ok)?(lab|lch)|light-dark|color-mix|--alpha)\(/i;function S(e){return e.charCodeAt(0)===35||U.test(e)||k.has(e.toLowerCase())}function oe(e){return k.has(e.toLowerCase())}var A=["calc","min","max","clamp","mod","rem","sin","cos","tan","asin","acos","atan","atan2","pow","sqrt","hypot","log","exp","round"];function h(e){return e.indexOf("(")!==-1&&A.some(t=>e.includes(`${t}(`))}function ae(e){if(!A.some(n=>e.includes(n)))return e;let t="",r=[],s=null,m=null;for(let n=0;n=48&&a<=57||s!==null&&(a===37||a>=97&&a<=122||a>=65&&a<=90)?s=n:(m=s,s=null),a===40){t+=e[n];let i=n;for(let p=n-1;p>=0;p--){let c=e.charCodeAt(p);if(c>=48&&c<=57)i=p;else if(c>=97&&c<=122)i=p;else break}let o=e.slice(i,n);if(A.includes(o)){r.unshift(!0);continue}else if(r[0]&&o===""){r.unshift(!0);continue}r.unshift(!1);continue}else if(a===41)t+=e[n],r.shift();else if(a===44&&r[0]){t+=", ";continue}else{if(a===32&&r[0]&&t.charCodeAt(t.length-1)===32)continue;if((a===43||a===42||a===47||a===45)&&r[0]){let i=t.trimEnd(),o=i.charCodeAt(i.length-1),p=i.charCodeAt(i.length-2),c=e.charCodeAt(n+1);if((o===101||o===69)&&p>=48&&p<=57){t+=e[n];continue}else if(o===43||o===42||o===47||o===45){t+=e[n];continue}else if(o===40||o===44){t+=e[n];continue}else e.charCodeAt(n-1)===32?t+=`${e[n]} `:o>=48&&o<=57||c>=48&&c<=57||o===41||c===40||c===43||c===42||c===47||c===45||m!==null&&m===n-1?t+=` ${e[n]} `:t+=e[n]}else t+=e[n]}}return t}var E=new Uint8Array(256);function u(e,t){let r=0,s=[],m=0,n=e.length,a=t.charCodeAt(0);for(let i=0;i0&&o===E[r-1]&&r--;break}}return s.push(e.slice(m)),s}var P={color:S,length:y,percentage:C,ratio:G,number:R,integer:d,url:N,position:Y,"bg-size":Q,"line-width":T,image:F,"family-name":M,"generic-name":H,"absolute-size":$,"relative-size":B,angle:ee,vector:re};function ge(e,t){if(e.startsWith("var("))return null;for(let r of t)if(P[r]?.(e))return r;return null}var z=/^url\(.*\)$/;function N(e){return z.test(e)}function T(e){return u(e," ").every(t=>y(t)||R(t)||t==="thin"||t==="medium"||t==="thick")}var I=/^(?:element|image|cross-fade|image-set)\(/,D=/^(repeating-)?(conic|linear|radial)-gradient\(/;function F(e){let t=0;for(let r of u(e,","))if(!r.startsWith("var(")){if(N(r)){t+=1;continue}if(D.test(r)){t+=1;continue}if(I.test(r)){t+=1;continue}return!1}return t>0}function H(e){return e==="serif"||e==="sans-serif"||e==="monospace"||e==="cursive"||e==="fantasy"||e==="system-ui"||e==="ui-serif"||e==="ui-sans-serif"||e==="ui-monospace"||e==="ui-rounded"||e==="math"||e==="emoji"||e==="fangsong"}function M(e){let t=0;for(let r of u(e,",")){let s=r.charCodeAt(0);if(s>=48&&s<=57)return!1;r.startsWith("var(")||(t+=1)}return t>0}function $(e){return e==="xx-small"||e==="x-small"||e==="small"||e==="medium"||e==="large"||e==="x-large"||e==="xx-large"||e==="xxx-large"}function B(e){return e==="larger"||e==="smaller"}var x=/[+-]?\d*\.?\d+(?:[eE][+-]?\d+)?/,W=new RegExp(`^${x.source}$`);function R(e){return W.test(e)||h(e)}var q=new RegExp(`^${x.source}%$`);function C(e){return q.test(e)||h(e)}var V=new RegExp(`^${x.source}\\s*/\\s*${x.source}$`);function G(e){return V.test(e)||h(e)}var Z=["cm","mm","Q","in","pc","pt","px","em","ex","ch","cap","ic","rem","rex","rch","rcap","ric","lh","rlh","vw","vh","vmin","vmax","vb","vi","svw","svh","svi","svb","svmin","svmax","lvw","lvh","lvi","lvb","lvmin","lvmax","dvw","dvh","dvi","dvb","dvmin","dvmax","cqw","cqh","cqi","cqb","cqmin","cqmax"],j=new RegExp(`^${x.source}(${Z.join("|")})$`),K=/^(--spacing)\(/i;function y(e){return j.test(e)||K.test(e)||h(e)}function Y(e){let t=0;for(let r of u(e," ")){if(r==="center"||r==="top"||r==="right"||r==="bottom"||r==="left"){t+=1;continue}if(!r.startsWith("var(")){if(y(r)||C(r)){t+=1;continue}return!1}}return t>0}function Q(e){let t=0;for(let r of u(e,",")){if(r==="cover"||r==="contain"){t+=1;continue}let s=u(r," ");if(s.length!==1&&s.length!==2)return!1;if(s.every(m=>m==="auto"||y(m)||C(m))){t+=1;continue}}return t>0}var J=["deg","rad","grad","turn"],X=new RegExp(`^${x.source}(${J.join("|")})$`);function ee(e){return X.test(e)}var te=new RegExp(`^${x.source} +${x.source} +${x.source}$`);function re(e){return te.test(e)}function d(e){let t=Number(e);return Number.isInteger(t)&&t>=0&&String(t)===String(e)}function de(e){let t=Number(e);return Number.isInteger(t)&&t>0&&String(t)===String(e)}function ue(e){return O(e,.25)}function xe(e){return O(e,.25)}function O(e,t){let r=Number(e);return r>=0&&r%t===0&&String(r)===String(e)}function b(e){return{__BARE_VALUE__:e}}var g=b(e=>{if(d(e.value))return e.value}),l=b(e=>{if(d(e.value))return`${e.value}%`}),f=b(e=>{if(d(e.value))return`${e.value}px`}),L=b(e=>{if(d(e.value))return`${e.value}ms`}),w=b(e=>{if(d(e.value))return`${e.value}deg`}),ne=b(e=>{if(e.fraction===null)return;let[t,r]=u(e.fraction,"/");if(!(!d(t)||!d(r)))return e.fraction}),_=b(e=>{if(d(Number(e.value)))return`repeat(${e.value}, minmax(0, 1fr))`}),ye={accentColor:({theme:e})=>e("colors"),animation:{none:"none",spin:"spin 1s linear infinite",ping:"ping 1s cubic-bezier(0, 0, 0.2, 1) infinite",pulse:"pulse 2s cubic-bezier(0.4, 0, 0.6, 1) infinite",bounce:"bounce 1s infinite"},aria:{busy:'busy="true"',checked:'checked="true"',disabled:'disabled="true"',expanded:'expanded="true"',hidden:'hidden="true"',pressed:'pressed="true"',readonly:'readonly="true"',required:'required="true"',selected:'selected="true"'},aspectRatio:{auto:"auto",square:"1 / 1",video:"16 / 9",...ne},backdropBlur:({theme:e})=>e("blur"),backdropBrightness:({theme:e})=>({...e("brightness"),...l}),backdropContrast:({theme:e})=>({...e("contrast"),...l}),backdropGrayscale:({theme:e})=>({...e("grayscale"),...l}),backdropHueRotate:({theme:e})=>({...e("hueRotate"),...w}),backdropInvert:({theme:e})=>({...e("invert"),...l}),backdropOpacity:({theme:e})=>({...e("opacity"),...l}),backdropSaturate:({theme:e})=>({...e("saturate"),...l}),backdropSepia:({theme:e})=>({...e("sepia"),...l}),backgroundColor:({theme:e})=>e("colors"),backgroundImage:{none:"none","gradient-to-t":"linear-gradient(to top, var(--tw-gradient-stops))","gradient-to-tr":"linear-gradient(to top right, var(--tw-gradient-stops))","gradient-to-r":"linear-gradient(to right, var(--tw-gradient-stops))","gradient-to-br":"linear-gradient(to bottom right, var(--tw-gradient-stops))","gradient-to-b":"linear-gradient(to bottom, var(--tw-gradient-stops))","gradient-to-bl":"linear-gradient(to bottom left, var(--tw-gradient-stops))","gradient-to-l":"linear-gradient(to left, var(--tw-gradient-stops))","gradient-to-tl":"linear-gradient(to top left, var(--tw-gradient-stops))"},backgroundOpacity:({theme:e})=>e("opacity"),backgroundPosition:{bottom:"bottom",center:"center",left:"left","left-bottom":"left bottom","left-top":"left top",right:"right","right-bottom":"right bottom","right-top":"right top",top:"top"},backgroundSize:{auto:"auto",cover:"cover",contain:"contain"},blur:{0:"0",none:"",sm:"4px",DEFAULT:"8px",md:"12px",lg:"16px",xl:"24px","2xl":"40px","3xl":"64px"},borderColor:({theme:e})=>({DEFAULT:"currentcolor",...e("colors")}),borderOpacity:({theme:e})=>e("opacity"),borderRadius:{none:"0px",sm:"0.125rem",DEFAULT:"0.25rem",md:"0.375rem",lg:"0.5rem",xl:"0.75rem","2xl":"1rem","3xl":"1.5rem",full:"9999px"},borderSpacing:({theme:e})=>e("spacing"),borderWidth:{DEFAULT:"1px",0:"0px",2:"2px",4:"4px",8:"8px",...f},boxShadow:{sm:"0 1px 2px 0 rgb(0 0 0 / 0.05)",DEFAULT:"0 1px 3px 0 rgb(0 0 0 / 0.1), 0 1px 2px -1px rgb(0 0 0 / 0.1)",md:"0 4px 6px -1px rgb(0 0 0 / 0.1), 0 2px 4px -2px rgb(0 0 0 / 0.1)",lg:"0 10px 15px -3px rgb(0 0 0 / 0.1), 0 4px 6px -4px rgb(0 0 0 / 0.1)",xl:"0 20px 25px -5px rgb(0 0 0 / 0.1), 0 8px 10px -6px rgb(0 0 0 / 0.1)","2xl":"0 25px 50px -12px rgb(0 0 0 / 0.25)",inner:"inset 0 2px 4px 0 rgb(0 0 0 / 0.05)",none:"none"},boxShadowColor:({theme:e})=>e("colors"),brightness:{0:"0",50:".5",75:".75",90:".9",95:".95",100:"1",105:"1.05",110:"1.1",125:"1.25",150:"1.5",200:"2",...l},caretColor:({theme:e})=>e("colors"),colors:()=>({...v}),columns:{auto:"auto",1:"1",2:"2",3:"3",4:"4",5:"5",6:"6",7:"7",8:"8",9:"9",10:"10",11:"11",12:"12","3xs":"16rem","2xs":"18rem",xs:"20rem",sm:"24rem",md:"28rem",lg:"32rem",xl:"36rem","2xl":"42rem","3xl":"48rem","4xl":"56rem","5xl":"64rem","6xl":"72rem","7xl":"80rem",...g},container:{},content:{none:"none"},contrast:{0:"0",50:".5",75:".75",100:"1",125:"1.25",150:"1.5",200:"2",...l},cursor:{auto:"auto",default:"default",pointer:"pointer",wait:"wait",text:"text",move:"move",help:"help","not-allowed":"not-allowed",none:"none","context-menu":"context-menu",progress:"progress",cell:"cell",crosshair:"crosshair","vertical-text":"vertical-text",alias:"alias",copy:"copy","no-drop":"no-drop",grab:"grab",grabbing:"grabbing","all-scroll":"all-scroll","col-resize":"col-resize","row-resize":"row-resize","n-resize":"n-resize","e-resize":"e-resize","s-resize":"s-resize","w-resize":"w-resize","ne-resize":"ne-resize","nw-resize":"nw-resize","se-resize":"se-resize","sw-resize":"sw-resize","ew-resize":"ew-resize","ns-resize":"ns-resize","nesw-resize":"nesw-resize","nwse-resize":"nwse-resize","zoom-in":"zoom-in","zoom-out":"zoom-out"},divideColor:({theme:e})=>e("borderColor"),divideOpacity:({theme:e})=>e("borderOpacity"),divideWidth:({theme:e})=>({...e("borderWidth"),...f}),dropShadow:{sm:"0 1px 1px rgb(0 0 0 / 0.05)",DEFAULT:["0 1px 2px rgb(0 0 0 / 0.1)","0 1px 1px rgb(0 0 0 / 0.06)"],md:["0 4px 3px rgb(0 0 0 / 0.07)","0 2px 2px rgb(0 0 0 / 0.06)"],lg:["0 10px 8px rgb(0 0 0 / 0.04)","0 4px 3px rgb(0 0 0 / 0.1)"],xl:["0 20px 13px rgb(0 0 0 / 0.03)","0 8px 5px rgb(0 0 0 / 0.08)"],"2xl":"0 25px 25px rgb(0 0 0 / 0.15)",none:"0 0 #0000"},fill:({theme:e})=>e("colors"),flex:{1:"1 1 0%",auto:"1 1 auto",initial:"0 1 auto",none:"none"},flexBasis:({theme:e})=>({auto:"auto","1/2":"50%","1/3":"33.333333%","2/3":"66.666667%","1/4":"25%","2/4":"50%","3/4":"75%","1/5":"20%","2/5":"40%","3/5":"60%","4/5":"80%","1/6":"16.666667%","2/6":"33.333333%","3/6":"50%","4/6":"66.666667%","5/6":"83.333333%","1/12":"8.333333%","2/12":"16.666667%","3/12":"25%","4/12":"33.333333%","5/12":"41.666667%","6/12":"50%","7/12":"58.333333%","8/12":"66.666667%","9/12":"75%","10/12":"83.333333%","11/12":"91.666667%",full:"100%",...e("spacing")}),flexGrow:{0:"0",DEFAULT:"1",...g},flexShrink:{0:"0",DEFAULT:"1",...g},fontFamily:{sans:["-apple-system","BlinkMacSystemFont",'"Segoe UI"',"Roboto",'"Helvetica Neue"','"Noto Sans"',"Arial","sans-serif",'"Apple Color Emoji"','"Segoe UI Emoji"','"Segoe UI Symbol"','"Noto Color Emoji"'],serif:["ui-serif","Georgia","Cambria",'"Times New Roman"',"Times","serif"],mono:["ui-monospace","SFMono-Regular","Menlo","Monaco","Consolas",'"Liberation Mono"','"Courier New"',"monospace"]},fontSize:{xs:["0.75rem",{lineHeight:"1rem"}],sm:["0.875rem",{lineHeight:"1.25rem"}],base:["1rem",{lineHeight:"1.5rem"}],lg:["1.125rem",{lineHeight:"1.75rem"}],xl:["1.25rem",{lineHeight:"1.75rem"}],"2xl":["1.5rem",{lineHeight:"2rem"}],"3xl":["1.875rem",{lineHeight:"2.25rem"}],"4xl":["2.25rem",{lineHeight:"2.5rem"}],"5xl":["3rem",{lineHeight:"1"}],"6xl":["3.75rem",{lineHeight:"1"}],"7xl":["4.5rem",{lineHeight:"1"}],"8xl":["6rem",{lineHeight:"1"}],"9xl":["8rem",{lineHeight:"1"}]},fontWeight:{thin:"100",extralight:"200",light:"300",normal:"400",medium:"500",semibold:"600",bold:"700",extrabold:"800",black:"900"},gap:({theme:e})=>e("spacing"),gradientColorStops:({theme:e})=>e("colors"),gradientColorStopPositions:{"0%":"0%","5%":"5%","10%":"10%","15%":"15%","20%":"20%","25%":"25%","30%":"30%","35%":"35%","40%":"40%","45%":"45%","50%":"50%","55%":"55%","60%":"60%","65%":"65%","70%":"70%","75%":"75%","80%":"80%","85%":"85%","90%":"90%","95%":"95%","100%":"100%",...l},grayscale:{0:"0",DEFAULT:"100%",...l},gridAutoColumns:{auto:"auto",min:"min-content",max:"max-content",fr:"minmax(0, 1fr)"},gridAutoRows:{auto:"auto",min:"min-content",max:"max-content",fr:"minmax(0, 1fr)"},gridColumn:{auto:"auto","span-1":"span 1 / span 1","span-2":"span 2 / span 2","span-3":"span 3 / span 3","span-4":"span 4 / span 4","span-5":"span 5 / span 5","span-6":"span 6 / span 6","span-7":"span 7 / span 7","span-8":"span 8 / span 8","span-9":"span 9 / span 9","span-10":"span 10 / span 10","span-11":"span 11 / span 11","span-12":"span 12 / span 12","span-full":"1 / -1"},gridColumnEnd:{auto:"auto",1:"1",2:"2",3:"3",4:"4",5:"5",6:"6",7:"7",8:"8",9:"9",10:"10",11:"11",12:"12",13:"13",...g},gridColumnStart:{auto:"auto",1:"1",2:"2",3:"3",4:"4",5:"5",6:"6",7:"7",8:"8",9:"9",10:"10",11:"11",12:"12",13:"13",...g},gridRow:{auto:"auto","span-1":"span 1 / span 1","span-2":"span 2 / span 2","span-3":"span 3 / span 3","span-4":"span 4 / span 4","span-5":"span 5 / span 5","span-6":"span 6 / span 6","span-7":"span 7 / span 7","span-8":"span 8 / span 8","span-9":"span 9 / span 9","span-10":"span 10 / span 10","span-11":"span 11 / span 11","span-12":"span 12 / span 12","span-full":"1 / -1"},gridRowEnd:{auto:"auto",1:"1",2:"2",3:"3",4:"4",5:"5",6:"6",7:"7",8:"8",9:"9",10:"10",11:"11",12:"12",13:"13",...g},gridRowStart:{auto:"auto",1:"1",2:"2",3:"3",4:"4",5:"5",6:"6",7:"7",8:"8",9:"9",10:"10",11:"11",12:"12",13:"13",...g},gridTemplateColumns:{none:"none",subgrid:"subgrid",1:"repeat(1, minmax(0, 1fr))",2:"repeat(2, minmax(0, 1fr))",3:"repeat(3, minmax(0, 1fr))",4:"repeat(4, minmax(0, 1fr))",5:"repeat(5, minmax(0, 1fr))",6:"repeat(6, minmax(0, 1fr))",7:"repeat(7, minmax(0, 1fr))",8:"repeat(8, minmax(0, 1fr))",9:"repeat(9, minmax(0, 1fr))",10:"repeat(10, minmax(0, 1fr))",11:"repeat(11, minmax(0, 1fr))",12:"repeat(12, minmax(0, 1fr))",..._},gridTemplateRows:{none:"none",subgrid:"subgrid",1:"repeat(1, minmax(0, 1fr))",2:"repeat(2, minmax(0, 1fr))",3:"repeat(3, minmax(0, 1fr))",4:"repeat(4, minmax(0, 1fr))",5:"repeat(5, minmax(0, 1fr))",6:"repeat(6, minmax(0, 1fr))",7:"repeat(7, minmax(0, 1fr))",8:"repeat(8, minmax(0, 1fr))",9:"repeat(9, minmax(0, 1fr))",10:"repeat(10, minmax(0, 1fr))",11:"repeat(11, minmax(0, 1fr))",12:"repeat(12, minmax(0, 1fr))",..._},height:({theme:e})=>({auto:"auto","1/2":"50%","1/3":"33.333333%","2/3":"66.666667%","1/4":"25%","2/4":"50%","3/4":"75%","1/5":"20%","2/5":"40%","3/5":"60%","4/5":"80%","1/6":"16.666667%","2/6":"33.333333%","3/6":"50%","4/6":"66.666667%","5/6":"83.333333%",full:"100%",screen:"100vh",svh:"100svh",lvh:"100lvh",dvh:"100dvh",min:"min-content",max:"max-content",fit:"fit-content",...e("spacing")}),hueRotate:{0:"0deg",15:"15deg",30:"30deg",60:"60deg",90:"90deg",180:"180deg",...w},inset:({theme:e})=>({auto:"auto","1/2":"50%","1/3":"33.333333%","2/3":"66.666667%","1/4":"25%","2/4":"50%","3/4":"75%",full:"100%",...e("spacing")}),invert:{0:"0",DEFAULT:"100%",...l},keyframes:{spin:{to:{transform:"rotate(360deg)"}},ping:{"75%, 100%":{transform:"scale(2)",opacity:"0"}},pulse:{"50%":{opacity:".5"}},bounce:{"0%, 100%":{transform:"translateY(-25%)",animationTimingFunction:"cubic-bezier(0.8,0,1,1)"},"50%":{transform:"none",animationTimingFunction:"cubic-bezier(0,0,0.2,1)"}}},letterSpacing:{tighter:"-0.05em",tight:"-0.025em",normal:"0em",wide:"0.025em",wider:"0.05em",widest:"0.1em"},lineHeight:{none:"1",tight:"1.25",snug:"1.375",normal:"1.5",relaxed:"1.625",loose:"2",3:".75rem",4:"1rem",5:"1.25rem",6:"1.5rem",7:"1.75rem",8:"2rem",9:"2.25rem",10:"2.5rem"},listStyleType:{none:"none",disc:"disc",decimal:"decimal"},listStyleImage:{none:"none"},margin:({theme:e})=>({auto:"auto",...e("spacing")}),lineClamp:{1:"1",2:"2",3:"3",4:"4",5:"5",6:"6",...g},maxHeight:({theme:e})=>({none:"none",full:"100%",screen:"100vh",svh:"100svh",lvh:"100lvh",dvh:"100dvh",min:"min-content",max:"max-content",fit:"fit-content",...e("spacing")}),maxWidth:({theme:e})=>({none:"none",xs:"20rem",sm:"24rem",md:"28rem",lg:"32rem",xl:"36rem","2xl":"42rem","3xl":"48rem","4xl":"56rem","5xl":"64rem","6xl":"72rem","7xl":"80rem",full:"100%",min:"min-content",max:"max-content",fit:"fit-content",prose:"65ch",...e("spacing")}),minHeight:({theme:e})=>({full:"100%",screen:"100vh",svh:"100svh",lvh:"100lvh",dvh:"100dvh",min:"min-content",max:"max-content",fit:"fit-content",...e("spacing")}),minWidth:({theme:e})=>({full:"100%",min:"min-content",max:"max-content",fit:"fit-content",...e("spacing")}),objectPosition:{bottom:"bottom",center:"center",left:"left","left-bottom":"left bottom","left-top":"left top",right:"right","right-bottom":"right bottom","right-top":"right top",top:"top"},opacity:{0:"0",5:"0.05",10:"0.1",15:"0.15",20:"0.2",25:"0.25",30:"0.3",35:"0.35",40:"0.4",45:"0.45",50:"0.5",55:"0.55",60:"0.6",65:"0.65",70:"0.7",75:"0.75",80:"0.8",85:"0.85",90:"0.9",95:"0.95",100:"1",...l},order:{first:"-9999",last:"9999",none:"0",1:"1",2:"2",3:"3",4:"4",5:"5",6:"6",7:"7",8:"8",9:"9",10:"10",11:"11",12:"12",...g},outlineColor:({theme:e})=>e("colors"),outlineOffset:{0:"0px",1:"1px",2:"2px",4:"4px",8:"8px",...f},outlineWidth:{0:"0px",1:"1px",2:"2px",4:"4px",8:"8px",...f},padding:({theme:e})=>e("spacing"),placeholderColor:({theme:e})=>e("colors"),placeholderOpacity:({theme:e})=>e("opacity"),ringColor:({theme:e})=>({DEFAULT:"currentcolor",...e("colors")}),ringOffsetColor:({theme:e})=>e("colors"),ringOffsetWidth:{0:"0px",1:"1px",2:"2px",4:"4px",8:"8px",...f},ringOpacity:({theme:e})=>({DEFAULT:"0.5",...e("opacity")}),ringWidth:{DEFAULT:"3px",0:"0px",1:"1px",2:"2px",4:"4px",8:"8px",...f},rotate:{0:"0deg",1:"1deg",2:"2deg",3:"3deg",6:"6deg",12:"12deg",45:"45deg",90:"90deg",180:"180deg",...w},saturate:{0:"0",50:".5",100:"1",150:"1.5",200:"2",...l},scale:{0:"0",50:".5",75:".75",90:".9",95:".95",100:"1",105:"1.05",110:"1.1",125:"1.25",150:"1.5",...l},screens:{sm:"40rem",md:"48rem",lg:"64rem",xl:"80rem","2xl":"96rem"},scrollMargin:({theme:e})=>e("spacing"),scrollPadding:({theme:e})=>e("spacing"),sepia:{0:"0",DEFAULT:"100%",...l},skew:{0:"0deg",1:"1deg",2:"2deg",3:"3deg",6:"6deg",12:"12deg",...w},space:({theme:e})=>e("spacing"),spacing:{px:"1px",0:"0px",.5:"0.125rem",1:"0.25rem",1.5:"0.375rem",2:"0.5rem",2.5:"0.625rem",3:"0.75rem",3.5:"0.875rem",4:"1rem",5:"1.25rem",6:"1.5rem",7:"1.75rem",8:"2rem",9:"2.25rem",10:"2.5rem",11:"2.75rem",12:"3rem",14:"3.5rem",16:"4rem",20:"5rem",24:"6rem",28:"7rem",32:"8rem",36:"9rem",40:"10rem",44:"11rem",48:"12rem",52:"13rem",56:"14rem",60:"15rem",64:"16rem",72:"18rem",80:"20rem",96:"24rem"},stroke:({theme:e})=>({none:"none",...e("colors")}),strokeWidth:{0:"0",1:"1",2:"2",...g},supports:{},data:{},textColor:({theme:e})=>e("colors"),textDecorationColor:({theme:e})=>e("colors"),textDecorationThickness:{auto:"auto","from-font":"from-font",0:"0px",1:"1px",2:"2px",4:"4px",8:"8px",...f},textIndent:({theme:e})=>e("spacing"),textOpacity:({theme:e})=>e("opacity"),textUnderlineOffset:{auto:"auto",0:"0px",1:"1px",2:"2px",4:"4px",8:"8px",...f},transformOrigin:{center:"center",top:"top","top-right":"top right",right:"right","bottom-right":"bottom right",bottom:"bottom","bottom-left":"bottom left",left:"left","top-left":"top left"},transitionDelay:{0:"0s",75:"75ms",100:"100ms",150:"150ms",200:"200ms",300:"300ms",500:"500ms",700:"700ms",1e3:"1000ms",...L},transitionDuration:{DEFAULT:"150ms",0:"0s",75:"75ms",100:"100ms",150:"150ms",200:"200ms",300:"300ms",500:"500ms",700:"700ms",1e3:"1000ms",...L},transitionProperty:{none:"none",all:"all",DEFAULT:"color, background-color, border-color, outline-color, text-decoration-color, fill, stroke, opacity, box-shadow, transform, filter, backdrop-filter",colors:"color, background-color, border-color, outline-color, text-decoration-color, fill, stroke",opacity:"opacity",shadow:"box-shadow",transform:"transform"},transitionTimingFunction:{DEFAULT:"cubic-bezier(0.4, 0, 0.2, 1)",linear:"linear",in:"cubic-bezier(0.4, 0, 1, 1)",out:"cubic-bezier(0, 0, 0.2, 1)","in-out":"cubic-bezier(0.4, 0, 0.2, 1)"},translate:({theme:e})=>({"1/2":"50%","1/3":"33.333333%","2/3":"66.666667%","1/4":"25%","2/4":"50%","3/4":"75%",full:"100%",...e("spacing")}),size:({theme:e})=>({auto:"auto","1/2":"50%","1/3":"33.333333%","2/3":"66.666667%","1/4":"25%","2/4":"50%","3/4":"75%","1/5":"20%","2/5":"40%","3/5":"60%","4/5":"80%","1/6":"16.666667%","2/6":"33.333333%","3/6":"50%","4/6":"66.666667%","5/6":"83.333333%","1/12":"8.333333%","2/12":"16.666667%","3/12":"25%","4/12":"33.333333%","5/12":"41.666667%","6/12":"50%","7/12":"58.333333%","8/12":"66.666667%","9/12":"75%","10/12":"83.333333%","11/12":"91.666667%",full:"100%",min:"min-content",max:"max-content",fit:"fit-content",...e("spacing")}),width:({theme:e})=>({auto:"auto","1/2":"50%","1/3":"33.333333%","2/3":"66.666667%","1/4":"25%","2/4":"50%","3/4":"75%","1/5":"20%","2/5":"40%","3/5":"60%","4/5":"80%","1/6":"16.666667%","2/6":"33.333333%","3/6":"50%","4/6":"66.666667%","5/6":"83.333333%","1/12":"8.333333%","2/12":"16.666667%","3/12":"25%","4/12":"33.333333%","5/12":"41.666667%","6/12":"50%","7/12":"58.333333%","8/12":"66.666667%","9/12":"75%","10/12":"83.333333%","11/12":"91.666667%",full:"100%",screen:"100vw",svw:"100svw",lvw:"100lvw",dvw:"100dvw",min:"min-content",max:"max-content",fit:"fit-content",...e("spacing")}),willChange:{auto:"auto",scroll:"scroll-position",contents:"contents",transform:"transform"},zIndex:{auto:"auto",0:"0",10:"10",20:"20",30:"30",40:"40",50:"50",...g}};export{u as a,ae as b,oe as c,ge as d,y as e,d as f,de as g,ue as h,xe as i,ye as j}; diff --git a/dg-ui/node_modules/tailwindcss/dist/colors-C__qRT83.d.ts b/dg-ui/node_modules/tailwindcss/dist/colors-C__qRT83.d.ts new file mode 100644 index 0000000..ca685d6 --- /dev/null +++ b/dg-ui/node_modules/tailwindcss/dist/colors-C__qRT83.d.ts @@ -0,0 +1,347 @@ +declare const _default: { + inherit: string; + current: string; + transparent: string; + black: string; + white: string; + slate: { + '50': string; + '100': string; + '200': string; + '300': string; + '400': string; + '500': string; + '600': string; + '700': string; + '800': string; + '900': string; + '950': string; + }; + gray: { + '50': string; + '100': string; + '200': string; + '300': string; + '400': string; + '500': string; + '600': string; + '700': string; + '800': string; + '900': string; + '950': string; + }; + zinc: { + '50': string; + '100': string; + '200': string; + '300': string; + '400': string; + '500': string; + '600': string; + '700': string; + '800': string; + '900': string; + '950': string; + }; + neutral: { + '50': string; + '100': string; + '200': string; + '300': string; + '400': string; + '500': string; + '600': string; + '700': string; + '800': string; + '900': string; + '950': string; + }; + stone: { + '50': string; + '100': string; + '200': string; + '300': string; + '400': string; + '500': string; + '600': string; + '700': string; + '800': string; + '900': string; + '950': string; + }; + mauve: { + '50': string; + '100': string; + '200': string; + '300': string; + '400': string; + '500': string; + '600': string; + '700': string; + '800': string; + '900': string; + '950': string; + }; + olive: { + '50': string; + '100': string; + '200': string; + '300': string; + '400': string; + '500': string; + '600': string; + '700': string; + '800': string; + '900': string; + '950': string; + }; + mist: { + '50': string; + '100': string; + '200': string; + '300': string; + '400': string; + '500': string; + '600': string; + '700': string; + '800': string; + '900': string; + '950': string; + }; + taupe: { + '50': string; + '100': string; + '200': string; + '300': string; + '400': string; + '500': string; + '600': string; + '700': string; + '800': string; + '900': string; + '950': string; + }; + red: { + '50': string; + '100': string; + '200': string; + '300': string; + '400': string; + '500': string; + '600': string; + '700': string; + '800': string; + '900': string; + '950': string; + }; + orange: { + '50': string; + '100': string; + '200': string; + '300': string; + '400': string; + '500': string; + '600': string; + '700': string; + '800': string; + '900': string; + '950': string; + }; + amber: { + '50': string; + '100': string; + '200': string; + '300': string; + '400': string; + '500': string; + '600': string; + '700': string; + '800': string; + '900': string; + '950': string; + }; + yellow: { + '50': string; + '100': string; + '200': string; + '300': string; + '400': string; + '500': string; + '600': string; + '700': string; + '800': string; + '900': string; + '950': string; + }; + lime: { + '50': string; + '100': string; + '200': string; + '300': string; + '400': string; + '500': string; + '600': string; + '700': string; + '800': string; + '900': string; + '950': string; + }; + green: { + '50': string; + '100': string; + '200': string; + '300': string; + '400': string; + '500': string; + '600': string; + '700': string; + '800': string; + '900': string; + '950': string; + }; + emerald: { + '50': string; + '100': string; + '200': string; + '300': string; + '400': string; + '500': string; + '600': string; + '700': string; + '800': string; + '900': string; + '950': string; + }; + teal: { + '50': string; + '100': string; + '200': string; + '300': string; + '400': string; + '500': string; + '600': string; + '700': string; + '800': string; + '900': string; + '950': string; + }; + cyan: { + '50': string; + '100': string; + '200': string; + '300': string; + '400': string; + '500': string; + '600': string; + '700': string; + '800': string; + '900': string; + '950': string; + }; + sky: { + '50': string; + '100': string; + '200': string; + '300': string; + '400': string; + '500': string; + '600': string; + '700': string; + '800': string; + '900': string; + '950': string; + }; + blue: { + '50': string; + '100': string; + '200': string; + '300': string; + '400': string; + '500': string; + '600': string; + '700': string; + '800': string; + '900': string; + '950': string; + }; + indigo: { + '50': string; + '100': string; + '200': string; + '300': string; + '400': string; + '500': string; + '600': string; + '700': string; + '800': string; + '900': string; + '950': string; + }; + violet: { + '50': string; + '100': string; + '200': string; + '300': string; + '400': string; + '500': string; + '600': string; + '700': string; + '800': string; + '900': string; + '950': string; + }; + purple: { + '50': string; + '100': string; + '200': string; + '300': string; + '400': string; + '500': string; + '600': string; + '700': string; + '800': string; + '900': string; + '950': string; + }; + fuchsia: { + '50': string; + '100': string; + '200': string; + '300': string; + '400': string; + '500': string; + '600': string; + '700': string; + '800': string; + '900': string; + '950': string; + }; + pink: { + '50': string; + '100': string; + '200': string; + '300': string; + '400': string; + '500': string; + '600': string; + '700': string; + '800': string; + '900': string; + '950': string; + }; + rose: { + '50': string; + '100': string; + '200': string; + '300': string; + '400': string; + '500': string; + '600': string; + '700': string; + '800': string; + '900': string; + '950': string; + }; +}; + +export { _default as _ }; diff --git a/dg-ui/node_modules/tailwindcss/dist/colors.d.mts b/dg-ui/node_modules/tailwindcss/dist/colors.d.mts new file mode 100644 index 0000000..96785cb --- /dev/null +++ b/dg-ui/node_modules/tailwindcss/dist/colors.d.mts @@ -0,0 +1,347 @@ +declare const _default: { + inherit: string; + current: string; + transparent: string; + black: string; + white: string; + slate: { + '50': string; + '100': string; + '200': string; + '300': string; + '400': string; + '500': string; + '600': string; + '700': string; + '800': string; + '900': string; + '950': string; + }; + gray: { + '50': string; + '100': string; + '200': string; + '300': string; + '400': string; + '500': string; + '600': string; + '700': string; + '800': string; + '900': string; + '950': string; + }; + zinc: { + '50': string; + '100': string; + '200': string; + '300': string; + '400': string; + '500': string; + '600': string; + '700': string; + '800': string; + '900': string; + '950': string; + }; + neutral: { + '50': string; + '100': string; + '200': string; + '300': string; + '400': string; + '500': string; + '600': string; + '700': string; + '800': string; + '900': string; + '950': string; + }; + stone: { + '50': string; + '100': string; + '200': string; + '300': string; + '400': string; + '500': string; + '600': string; + '700': string; + '800': string; + '900': string; + '950': string; + }; + mauve: { + '50': string; + '100': string; + '200': string; + '300': string; + '400': string; + '500': string; + '600': string; + '700': string; + '800': string; + '900': string; + '950': string; + }; + olive: { + '50': string; + '100': string; + '200': string; + '300': string; + '400': string; + '500': string; + '600': string; + '700': string; + '800': string; + '900': string; + '950': string; + }; + mist: { + '50': string; + '100': string; + '200': string; + '300': string; + '400': string; + '500': string; + '600': string; + '700': string; + '800': string; + '900': string; + '950': string; + }; + taupe: { + '50': string; + '100': string; + '200': string; + '300': string; + '400': string; + '500': string; + '600': string; + '700': string; + '800': string; + '900': string; + '950': string; + }; + red: { + '50': string; + '100': string; + '200': string; + '300': string; + '400': string; + '500': string; + '600': string; + '700': string; + '800': string; + '900': string; + '950': string; + }; + orange: { + '50': string; + '100': string; + '200': string; + '300': string; + '400': string; + '500': string; + '600': string; + '700': string; + '800': string; + '900': string; + '950': string; + }; + amber: { + '50': string; + '100': string; + '200': string; + '300': string; + '400': string; + '500': string; + '600': string; + '700': string; + '800': string; + '900': string; + '950': string; + }; + yellow: { + '50': string; + '100': string; + '200': string; + '300': string; + '400': string; + '500': string; + '600': string; + '700': string; + '800': string; + '900': string; + '950': string; + }; + lime: { + '50': string; + '100': string; + '200': string; + '300': string; + '400': string; + '500': string; + '600': string; + '700': string; + '800': string; + '900': string; + '950': string; + }; + green: { + '50': string; + '100': string; + '200': string; + '300': string; + '400': string; + '500': string; + '600': string; + '700': string; + '800': string; + '900': string; + '950': string; + }; + emerald: { + '50': string; + '100': string; + '200': string; + '300': string; + '400': string; + '500': string; + '600': string; + '700': string; + '800': string; + '900': string; + '950': string; + }; + teal: { + '50': string; + '100': string; + '200': string; + '300': string; + '400': string; + '500': string; + '600': string; + '700': string; + '800': string; + '900': string; + '950': string; + }; + cyan: { + '50': string; + '100': string; + '200': string; + '300': string; + '400': string; + '500': string; + '600': string; + '700': string; + '800': string; + '900': string; + '950': string; + }; + sky: { + '50': string; + '100': string; + '200': string; + '300': string; + '400': string; + '500': string; + '600': string; + '700': string; + '800': string; + '900': string; + '950': string; + }; + blue: { + '50': string; + '100': string; + '200': string; + '300': string; + '400': string; + '500': string; + '600': string; + '700': string; + '800': string; + '900': string; + '950': string; + }; + indigo: { + '50': string; + '100': string; + '200': string; + '300': string; + '400': string; + '500': string; + '600': string; + '700': string; + '800': string; + '900': string; + '950': string; + }; + violet: { + '50': string; + '100': string; + '200': string; + '300': string; + '400': string; + '500': string; + '600': string; + '700': string; + '800': string; + '900': string; + '950': string; + }; + purple: { + '50': string; + '100': string; + '200': string; + '300': string; + '400': string; + '500': string; + '600': string; + '700': string; + '800': string; + '900': string; + '950': string; + }; + fuchsia: { + '50': string; + '100': string; + '200': string; + '300': string; + '400': string; + '500': string; + '600': string; + '700': string; + '800': string; + '900': string; + '950': string; + }; + pink: { + '50': string; + '100': string; + '200': string; + '300': string; + '400': string; + '500': string; + '600': string; + '700': string; + '800': string; + '900': string; + '950': string; + }; + rose: { + '50': string; + '100': string; + '200': string; + '300': string; + '400': string; + '500': string; + '600': string; + '700': string; + '800': string; + '900': string; + '950': string; + }; +}; + +export { _default as default }; diff --git a/dg-ui/node_modules/tailwindcss/dist/colors.d.ts b/dg-ui/node_modules/tailwindcss/dist/colors.d.ts new file mode 100644 index 0000000..f99c955 --- /dev/null +++ b/dg-ui/node_modules/tailwindcss/dist/colors.d.ts @@ -0,0 +1,5 @@ +import { _ as _default } from './colors-C__qRT83.js'; + + + +export { _default as default }; diff --git a/dg-ui/node_modules/tailwindcss/dist/colors.js b/dg-ui/node_modules/tailwindcss/dist/colors.js new file mode 100644 index 0000000..b4b67ae --- /dev/null +++ b/dg-ui/node_modules/tailwindcss/dist/colors.js @@ -0,0 +1 @@ +"use strict";var o={inherit:"inherit",current:"currentcolor",transparent:"transparent",black:"#000",white:"#fff",slate:{50:"oklch(98.4% 0.003 247.858)",100:"oklch(96.8% 0.007 247.896)",200:"oklch(92.9% 0.013 255.508)",300:"oklch(86.9% 0.022 252.894)",400:"oklch(70.4% 0.04 256.788)",500:"oklch(55.4% 0.046 257.417)",600:"oklch(44.6% 0.043 257.281)",700:"oklch(37.2% 0.044 257.287)",800:"oklch(27.9% 0.041 260.031)",900:"oklch(20.8% 0.042 265.755)",950:"oklch(12.9% 0.042 264.695)"},gray:{50:"oklch(98.5% 0.002 247.839)",100:"oklch(96.7% 0.003 264.542)",200:"oklch(92.8% 0.006 264.531)",300:"oklch(87.2% 0.01 258.338)",400:"oklch(70.7% 0.022 261.325)",500:"oklch(55.1% 0.027 264.364)",600:"oklch(44.6% 0.03 256.802)",700:"oklch(37.3% 0.034 259.733)",800:"oklch(27.8% 0.033 256.848)",900:"oklch(21% 0.034 264.665)",950:"oklch(13% 0.028 261.692)"},zinc:{50:"oklch(98.5% 0 none)",100:"oklch(96.7% 0.001 286.375)",200:"oklch(92% 0.004 286.32)",300:"oklch(87.1% 0.006 286.286)",400:"oklch(70.5% 0.015 286.067)",500:"oklch(55.2% 0.016 285.938)",600:"oklch(44.2% 0.017 285.786)",700:"oklch(37% 0.013 285.805)",800:"oklch(27.4% 0.006 286.033)",900:"oklch(21% 0.006 285.885)",950:"oklch(14.1% 0.005 285.823)"},neutral:{50:"oklch(98.5% 0 none)",100:"oklch(97% 0 none)",200:"oklch(92.2% 0 none)",300:"oklch(87% 0 none)",400:"oklch(70.8% 0 none)",500:"oklch(55.6% 0 none)",600:"oklch(43.9% 0 none)",700:"oklch(37.1% 0 none)",800:"oklch(26.9% 0 none)",900:"oklch(20.5% 0 none)",950:"oklch(14.5% 0 none)"},stone:{50:"oklch(98.5% 0.001 106.423)",100:"oklch(97% 0.001 106.424)",200:"oklch(92.3% 0.003 48.717)",300:"oklch(86.9% 0.005 56.366)",400:"oklch(70.9% 0.01 56.259)",500:"oklch(55.3% 0.013 58.071)",600:"oklch(44.4% 0.011 73.639)",700:"oklch(37.4% 0.01 67.558)",800:"oklch(26.8% 0.007 34.298)",900:"oklch(21.6% 0.006 56.043)",950:"oklch(14.7% 0.004 49.25)"},mauve:{50:"oklch(98.5% 0 none)",100:"oklch(96% 0.003 325.6)",200:"oklch(92.2% 0.005 325.62)",300:"oklch(86.5% 0.012 325.68)",400:"oklch(71.1% 0.019 323.02)",500:"oklch(54.2% 0.034 322.5)",600:"oklch(43.5% 0.029 321.78)",700:"oklch(36.4% 0.029 323.89)",800:"oklch(26.3% 0.024 320.12)",900:"oklch(21.2% 0.019 322.12)",950:"oklch(14.5% 0.008 326)"},olive:{50:"oklch(98.8% 0.003 106.5)",100:"oklch(96.6% 0.005 106.5)",200:"oklch(93% 0.007 106.5)",300:"oklch(88% 0.011 106.6)",400:"oklch(73.7% 0.021 106.9)",500:"oklch(58% 0.031 107.3)",600:"oklch(46.6% 0.025 107.3)",700:"oklch(39.4% 0.023 107.4)",800:"oklch(28.6% 0.016 107.4)",900:"oklch(22.8% 0.013 107.4)",950:"oklch(15.3% 0.006 107.1)"},mist:{50:"oklch(98.7% 0.002 197.1)",100:"oklch(96.3% 0.002 197.1)",200:"oklch(92.5% 0.005 214.3)",300:"oklch(87.2% 0.007 219.6)",400:"oklch(72.3% 0.014 214.4)",500:"oklch(56% 0.021 213.5)",600:"oklch(45% 0.017 213.2)",700:"oklch(37.8% 0.015 216)",800:"oklch(27.5% 0.011 216.9)",900:"oklch(21.8% 0.008 223.9)",950:"oklch(14.8% 0.004 228.8)"},taupe:{50:"oklch(98.6% 0.002 67.8)",100:"oklch(96% 0.002 17.2)",200:"oklch(92.2% 0.005 34.3)",300:"oklch(86.8% 0.007 39.5)",400:"oklch(71.4% 0.014 41.2)",500:"oklch(54.7% 0.021 43.1)",600:"oklch(43.8% 0.017 39.3)",700:"oklch(36.7% 0.016 35.7)",800:"oklch(26.8% 0.011 36.5)",900:"oklch(21.4% 0.009 43.1)",950:"oklch(14.7% 0.004 49.3)"},red:{50:"oklch(97.1% 0.013 17.38)",100:"oklch(93.6% 0.032 17.717)",200:"oklch(88.5% 0.062 18.334)",300:"oklch(80.8% 0.114 19.571)",400:"oklch(70.4% 0.191 22.216)",500:"oklch(63.7% 0.237 25.331)",600:"oklch(57.7% 0.245 27.325)",700:"oklch(50.5% 0.213 27.518)",800:"oklch(44.4% 0.177 26.899)",900:"oklch(39.6% 0.141 25.723)",950:"oklch(25.8% 0.092 26.042)"},orange:{50:"oklch(98% 0.016 73.684)",100:"oklch(95.4% 0.038 75.164)",200:"oklch(90.1% 0.076 70.697)",300:"oklch(83.7% 0.128 66.29)",400:"oklch(75% 0.183 55.934)",500:"oklch(70.5% 0.213 47.604)",600:"oklch(64.6% 0.222 41.116)",700:"oklch(55.3% 0.195 38.402)",800:"oklch(47% 0.157 37.304)",900:"oklch(40.8% 0.123 38.172)",950:"oklch(26.6% 0.079 36.259)"},amber:{50:"oklch(98.7% 0.022 95.277)",100:"oklch(96.2% 0.059 95.617)",200:"oklch(92.4% 0.12 95.746)",300:"oklch(87.9% 0.169 91.605)",400:"oklch(82.8% 0.189 84.429)",500:"oklch(76.9% 0.188 70.08)",600:"oklch(66.6% 0.179 58.318)",700:"oklch(55.5% 0.163 48.998)",800:"oklch(47.3% 0.137 46.201)",900:"oklch(41.4% 0.112 45.904)",950:"oklch(27.9% 0.077 45.635)"},yellow:{50:"oklch(98.7% 0.026 102.212)",100:"oklch(97.3% 0.071 103.193)",200:"oklch(94.5% 0.129 101.54)",300:"oklch(90.5% 0.182 98.111)",400:"oklch(85.2% 0.199 91.936)",500:"oklch(79.5% 0.184 86.047)",600:"oklch(68.1% 0.162 75.834)",700:"oklch(55.4% 0.135 66.442)",800:"oklch(47.6% 0.114 61.907)",900:"oklch(42.1% 0.095 57.708)",950:"oklch(28.6% 0.066 53.813)"},lime:{50:"oklch(98.6% 0.031 120.757)",100:"oklch(96.7% 0.067 122.328)",200:"oklch(93.8% 0.127 124.321)",300:"oklch(89.7% 0.196 126.665)",400:"oklch(84.1% 0.238 128.85)",500:"oklch(76.8% 0.233 130.85)",600:"oklch(64.8% 0.2 131.684)",700:"oklch(53.2% 0.157 131.589)",800:"oklch(45.3% 0.124 130.933)",900:"oklch(40.5% 0.101 131.063)",950:"oklch(27.4% 0.072 132.109)"},green:{50:"oklch(98.2% 0.018 155.826)",100:"oklch(96.2% 0.044 156.743)",200:"oklch(92.5% 0.084 155.995)",300:"oklch(87.1% 0.15 154.449)",400:"oklch(79.2% 0.209 151.711)",500:"oklch(72.3% 0.219 149.579)",600:"oklch(62.7% 0.194 149.214)",700:"oklch(52.7% 0.154 150.069)",800:"oklch(44.8% 0.119 151.328)",900:"oklch(39.3% 0.095 152.535)",950:"oklch(26.6% 0.065 152.934)"},emerald:{50:"oklch(97.9% 0.021 166.113)",100:"oklch(95% 0.052 163.051)",200:"oklch(90.5% 0.093 164.15)",300:"oklch(84.5% 0.143 164.978)",400:"oklch(76.5% 0.177 163.223)",500:"oklch(69.6% 0.17 162.48)",600:"oklch(59.6% 0.145 163.225)",700:"oklch(50.8% 0.118 165.612)",800:"oklch(43.2% 0.095 166.913)",900:"oklch(37.8% 0.077 168.94)",950:"oklch(26.2% 0.051 172.552)"},teal:{50:"oklch(98.4% 0.014 180.72)",100:"oklch(95.3% 0.051 180.801)",200:"oklch(91% 0.096 180.426)",300:"oklch(85.5% 0.138 181.071)",400:"oklch(77.7% 0.152 181.912)",500:"oklch(70.4% 0.14 182.503)",600:"oklch(60% 0.118 184.704)",700:"oklch(51.1% 0.096 186.391)",800:"oklch(43.7% 0.078 188.216)",900:"oklch(38.6% 0.063 188.416)",950:"oklch(27.7% 0.046 192.524)"},cyan:{50:"oklch(98.4% 0.019 200.873)",100:"oklch(95.6% 0.045 203.388)",200:"oklch(91.7% 0.08 205.041)",300:"oklch(86.5% 0.127 207.078)",400:"oklch(78.9% 0.154 211.53)",500:"oklch(71.5% 0.143 215.221)",600:"oklch(60.9% 0.126 221.723)",700:"oklch(52% 0.105 223.128)",800:"oklch(45% 0.085 224.283)",900:"oklch(39.8% 0.07 227.392)",950:"oklch(30.2% 0.056 229.695)"},sky:{50:"oklch(97.7% 0.013 236.62)",100:"oklch(95.1% 0.026 236.824)",200:"oklch(90.1% 0.058 230.902)",300:"oklch(82.8% 0.111 230.318)",400:"oklch(74.6% 0.16 232.661)",500:"oklch(68.5% 0.169 237.323)",600:"oklch(58.8% 0.158 241.966)",700:"oklch(50% 0.134 242.749)",800:"oklch(44.3% 0.11 240.79)",900:"oklch(39.1% 0.09 240.876)",950:"oklch(29.3% 0.066 243.157)"},blue:{50:"oklch(97% 0.014 254.604)",100:"oklch(93.2% 0.032 255.585)",200:"oklch(88.2% 0.059 254.128)",300:"oklch(80.9% 0.105 251.813)",400:"oklch(70.7% 0.165 254.624)",500:"oklch(62.3% 0.214 259.815)",600:"oklch(54.6% 0.245 262.881)",700:"oklch(48.8% 0.243 264.376)",800:"oklch(42.4% 0.199 265.638)",900:"oklch(37.9% 0.146 265.522)",950:"oklch(28.2% 0.091 267.935)"},indigo:{50:"oklch(96.2% 0.018 272.314)",100:"oklch(93% 0.034 272.788)",200:"oklch(87% 0.065 274.039)",300:"oklch(78.5% 0.115 274.713)",400:"oklch(67.3% 0.182 276.935)",500:"oklch(58.5% 0.233 277.117)",600:"oklch(51.1% 0.262 276.966)",700:"oklch(45.7% 0.24 277.023)",800:"oklch(39.8% 0.195 277.366)",900:"oklch(35.9% 0.144 278.697)",950:"oklch(25.7% 0.09 281.288)"},violet:{50:"oklch(96.9% 0.016 293.756)",100:"oklch(94.3% 0.029 294.588)",200:"oklch(89.4% 0.057 293.283)",300:"oklch(81.1% 0.111 293.571)",400:"oklch(70.2% 0.183 293.541)",500:"oklch(60.6% 0.25 292.717)",600:"oklch(54.1% 0.281 293.009)",700:"oklch(49.1% 0.27 292.581)",800:"oklch(43.2% 0.232 292.759)",900:"oklch(38% 0.189 293.745)",950:"oklch(28.3% 0.141 291.089)"},purple:{50:"oklch(97.7% 0.014 308.299)",100:"oklch(94.6% 0.033 307.174)",200:"oklch(90.2% 0.063 306.703)",300:"oklch(82.7% 0.119 306.383)",400:"oklch(71.4% 0.203 305.504)",500:"oklch(62.7% 0.265 303.9)",600:"oklch(55.8% 0.288 302.321)",700:"oklch(49.6% 0.265 301.924)",800:"oklch(43.8% 0.218 303.724)",900:"oklch(38.1% 0.176 304.987)",950:"oklch(29.1% 0.149 302.717)"},fuchsia:{50:"oklch(97.7% 0.017 320.058)",100:"oklch(95.2% 0.037 318.852)",200:"oklch(90.3% 0.076 319.62)",300:"oklch(83.3% 0.145 321.434)",400:"oklch(74% 0.238 322.16)",500:"oklch(66.7% 0.295 322.15)",600:"oklch(59.1% 0.293 322.896)",700:"oklch(51.8% 0.253 323.949)",800:"oklch(45.2% 0.211 324.591)",900:"oklch(40.1% 0.17 325.612)",950:"oklch(29.3% 0.136 325.661)"},pink:{50:"oklch(97.1% 0.014 343.198)",100:"oklch(94.8% 0.028 342.258)",200:"oklch(89.9% 0.061 343.231)",300:"oklch(82.3% 0.12 346.018)",400:"oklch(71.8% 0.202 349.761)",500:"oklch(65.6% 0.241 354.308)",600:"oklch(59.2% 0.249 0.584)",700:"oklch(52.5% 0.223 3.958)",800:"oklch(45.9% 0.187 3.815)",900:"oklch(40.8% 0.153 2.432)",950:"oklch(28.4% 0.109 3.907)"},rose:{50:"oklch(96.9% 0.015 12.422)",100:"oklch(94.1% 0.03 12.58)",200:"oklch(89.2% 0.058 10.001)",300:"oklch(81% 0.117 11.638)",400:"oklch(71.2% 0.194 13.428)",500:"oklch(64.5% 0.246 16.439)",600:"oklch(58.6% 0.253 17.585)",700:"oklch(51.4% 0.222 16.935)",800:"oklch(45.5% 0.188 13.697)",900:"oklch(41% 0.159 10.272)",950:"oklch(27.1% 0.105 12.094)"}};module.exports=o; diff --git a/dg-ui/node_modules/tailwindcss/dist/colors.mjs b/dg-ui/node_modules/tailwindcss/dist/colors.mjs new file mode 100644 index 0000000..0e8c560 --- /dev/null +++ b/dg-ui/node_modules/tailwindcss/dist/colors.mjs @@ -0,0 +1 @@ +import{a}from"./chunk-DCG7AFIE.mjs";export{a as default}; diff --git a/dg-ui/node_modules/tailwindcss/dist/default-theme.d.mts b/dg-ui/node_modules/tailwindcss/dist/default-theme.d.mts new file mode 100644 index 0000000..ac3c6a4 --- /dev/null +++ b/dg-ui/node_modules/tailwindcss/dist/default-theme.d.mts @@ -0,0 +1,1199 @@ +import { P as PluginUtils, N as NamedUtilityValue } from './resolve-config-QUZ9b-Gn.mjs'; +import './colors.mjs'; + +declare const _default: { + accentColor: ({ theme }: PluginUtils) => any; + animation: { + none: string; + spin: string; + ping: string; + pulse: string; + bounce: string; + }; + aria: { + busy: string; + checked: string; + disabled: string; + expanded: string; + hidden: string; + pressed: string; + readonly: string; + required: string; + selected: string; + }; + aspectRatio: { + __BARE_VALUE__: (value: NamedUtilityValue) => string | undefined; + auto: string; + square: string; + video: string; + }; + backdropBlur: ({ theme }: PluginUtils) => any; + backdropBrightness: ({ theme }: PluginUtils) => any; + backdropContrast: ({ theme }: PluginUtils) => any; + backdropGrayscale: ({ theme }: PluginUtils) => any; + backdropHueRotate: ({ theme }: PluginUtils) => any; + backdropInvert: ({ theme }: PluginUtils) => any; + backdropOpacity: ({ theme }: PluginUtils) => any; + backdropSaturate: ({ theme }: PluginUtils) => any; + backdropSepia: ({ theme }: PluginUtils) => any; + backgroundColor: ({ theme }: PluginUtils) => any; + backgroundImage: { + none: string; + 'gradient-to-t': string; + 'gradient-to-tr': string; + 'gradient-to-r': string; + 'gradient-to-br': string; + 'gradient-to-b': string; + 'gradient-to-bl': string; + 'gradient-to-l': string; + 'gradient-to-tl': string; + }; + backgroundOpacity: ({ theme }: PluginUtils) => any; + backgroundPosition: { + bottom: string; + center: string; + left: string; + 'left-bottom': string; + 'left-top': string; + right: string; + 'right-bottom': string; + 'right-top': string; + top: string; + }; + backgroundSize: { + auto: string; + cover: string; + contain: string; + }; + blur: { + 0: string; + none: string; + sm: string; + DEFAULT: string; + md: string; + lg: string; + xl: string; + '2xl': string; + '3xl': string; + }; + borderColor: ({ theme }: PluginUtils) => any; + borderOpacity: ({ theme }: PluginUtils) => any; + borderRadius: { + none: string; + sm: string; + DEFAULT: string; + md: string; + lg: string; + xl: string; + '2xl': string; + '3xl': string; + full: string; + }; + borderSpacing: ({ theme }: PluginUtils) => any; + borderWidth: { + __BARE_VALUE__: (value: NamedUtilityValue) => string | undefined; + DEFAULT: string; + 0: string; + 2: string; + 4: string; + 8: string; + }; + boxShadow: { + sm: string; + DEFAULT: string; + md: string; + lg: string; + xl: string; + '2xl': string; + inner: string; + none: string; + }; + boxShadowColor: ({ theme }: PluginUtils) => any; + brightness: { + __BARE_VALUE__: (value: NamedUtilityValue) => string | undefined; + 0: string; + 50: string; + 75: string; + 90: string; + 95: string; + 100: string; + 105: string; + 110: string; + 125: string; + 150: string; + 200: string; + }; + caretColor: ({ theme }: PluginUtils) => any; + colors: () => { + inherit: string; + current: string; + transparent: string; + black: string; + white: string; + slate: { + '50': string; + '100': string; + '200': string; + '300': string; + '400': string; + '500': string; + '600': string; + '700': string; + '800': string; + '900': string; + '950': string; + }; + gray: { + '50': string; + '100': string; + '200': string; + '300': string; + '400': string; + '500': string; + '600': string; + '700': string; + '800': string; + '900': string; + '950': string; + }; + zinc: { + '50': string; + '100': string; + '200': string; + '300': string; + '400': string; + '500': string; + '600': string; + '700': string; + '800': string; + '900': string; + '950': string; + }; + neutral: { + '50': string; + '100': string; + '200': string; + '300': string; + '400': string; + '500': string; + '600': string; + '700': string; + '800': string; + '900': string; + '950': string; + }; + stone: { + '50': string; + '100': string; + '200': string; + '300': string; + '400': string; + '500': string; + '600': string; + '700': string; + '800': string; + '900': string; + '950': string; + }; + mauve: { + '50': string; + '100': string; + '200': string; + '300': string; + '400': string; + '500': string; + '600': string; + '700': string; + '800': string; + '900': string; + '950': string; + }; + olive: { + '50': string; + '100': string; + '200': string; + '300': string; + '400': string; + '500': string; + '600': string; + '700': string; + '800': string; + '900': string; + '950': string; + }; + mist: { + '50': string; + '100': string; + '200': string; + '300': string; + '400': string; + '500': string; + '600': string; + '700': string; + '800': string; + '900': string; + '950': string; + }; + taupe: { + '50': string; + '100': string; + '200': string; + '300': string; + '400': string; + '500': string; + '600': string; + '700': string; + '800': string; + '900': string; + '950': string; + }; + red: { + '50': string; + '100': string; + '200': string; + '300': string; + '400': string; + '500': string; + '600': string; + '700': string; + '800': string; + '900': string; + '950': string; + }; + orange: { + '50': string; + '100': string; + '200': string; + '300': string; + '400': string; + '500': string; + '600': string; + '700': string; + '800': string; + '900': string; + '950': string; + }; + amber: { + '50': string; + '100': string; + '200': string; + '300': string; + '400': string; + '500': string; + '600': string; + '700': string; + '800': string; + '900': string; + '950': string; + }; + yellow: { + '50': string; + '100': string; + '200': string; + '300': string; + '400': string; + '500': string; + '600': string; + '700': string; + '800': string; + '900': string; + '950': string; + }; + lime: { + '50': string; + '100': string; + '200': string; + '300': string; + '400': string; + '500': string; + '600': string; + '700': string; + '800': string; + '900': string; + '950': string; + }; + green: { + '50': string; + '100': string; + '200': string; + '300': string; + '400': string; + '500': string; + '600': string; + '700': string; + '800': string; + '900': string; + '950': string; + }; + emerald: { + '50': string; + '100': string; + '200': string; + '300': string; + '400': string; + '500': string; + '600': string; + '700': string; + '800': string; + '900': string; + '950': string; + }; + teal: { + '50': string; + '100': string; + '200': string; + '300': string; + '400': string; + '500': string; + '600': string; + '700': string; + '800': string; + '900': string; + '950': string; + }; + cyan: { + '50': string; + '100': string; + '200': string; + '300': string; + '400': string; + '500': string; + '600': string; + '700': string; + '800': string; + '900': string; + '950': string; + }; + sky: { + '50': string; + '100': string; + '200': string; + '300': string; + '400': string; + '500': string; + '600': string; + '700': string; + '800': string; + '900': string; + '950': string; + }; + blue: { + '50': string; + '100': string; + '200': string; + '300': string; + '400': string; + '500': string; + '600': string; + '700': string; + '800': string; + '900': string; + '950': string; + }; + indigo: { + '50': string; + '100': string; + '200': string; + '300': string; + '400': string; + '500': string; + '600': string; + '700': string; + '800': string; + '900': string; + '950': string; + }; + violet: { + '50': string; + '100': string; + '200': string; + '300': string; + '400': string; + '500': string; + '600': string; + '700': string; + '800': string; + '900': string; + '950': string; + }; + purple: { + '50': string; + '100': string; + '200': string; + '300': string; + '400': string; + '500': string; + '600': string; + '700': string; + '800': string; + '900': string; + '950': string; + }; + fuchsia: { + '50': string; + '100': string; + '200': string; + '300': string; + '400': string; + '500': string; + '600': string; + '700': string; + '800': string; + '900': string; + '950': string; + }; + pink: { + '50': string; + '100': string; + '200': string; + '300': string; + '400': string; + '500': string; + '600': string; + '700': string; + '800': string; + '900': string; + '950': string; + }; + rose: { + '50': string; + '100': string; + '200': string; + '300': string; + '400': string; + '500': string; + '600': string; + '700': string; + '800': string; + '900': string; + '950': string; + }; + }; + columns: { + __BARE_VALUE__: (value: NamedUtilityValue) => string | undefined; + auto: string; + 1: string; + 2: string; + 3: string; + 4: string; + 5: string; + 6: string; + 7: string; + 8: string; + 9: string; + 10: string; + 11: string; + 12: string; + '3xs': string; + '2xs': string; + xs: string; + sm: string; + md: string; + lg: string; + xl: string; + '2xl': string; + '3xl': string; + '4xl': string; + '5xl': string; + '6xl': string; + '7xl': string; + }; + container: {}; + content: { + none: string; + }; + contrast: { + __BARE_VALUE__: (value: NamedUtilityValue) => string | undefined; + 0: string; + 50: string; + 75: string; + 100: string; + 125: string; + 150: string; + 200: string; + }; + cursor: { + auto: string; + default: string; + pointer: string; + wait: string; + text: string; + move: string; + help: string; + 'not-allowed': string; + none: string; + 'context-menu': string; + progress: string; + cell: string; + crosshair: string; + 'vertical-text': string; + alias: string; + copy: string; + 'no-drop': string; + grab: string; + grabbing: string; + 'all-scroll': string; + 'col-resize': string; + 'row-resize': string; + 'n-resize': string; + 'e-resize': string; + 's-resize': string; + 'w-resize': string; + 'ne-resize': string; + 'nw-resize': string; + 'se-resize': string; + 'sw-resize': string; + 'ew-resize': string; + 'ns-resize': string; + 'nesw-resize': string; + 'nwse-resize': string; + 'zoom-in': string; + 'zoom-out': string; + }; + divideColor: ({ theme }: PluginUtils) => any; + divideOpacity: ({ theme }: PluginUtils) => any; + divideWidth: ({ theme }: PluginUtils) => any; + dropShadow: { + sm: string; + DEFAULT: string[]; + md: string[]; + lg: string[]; + xl: string[]; + '2xl': string; + none: string; + }; + fill: ({ theme }: PluginUtils) => any; + flex: { + 1: string; + auto: string; + initial: string; + none: string; + }; + flexBasis: ({ theme }: PluginUtils) => any; + flexGrow: { + __BARE_VALUE__: (value: NamedUtilityValue) => string | undefined; + 0: string; + DEFAULT: string; + }; + flexShrink: { + __BARE_VALUE__: (value: NamedUtilityValue) => string | undefined; + 0: string; + DEFAULT: string; + }; + fontFamily: { + sans: string[]; + serif: string[]; + mono: string[]; + }; + fontSize: { + xs: (string | { + lineHeight: string; + })[]; + sm: (string | { + lineHeight: string; + })[]; + base: (string | { + lineHeight: string; + })[]; + lg: (string | { + lineHeight: string; + })[]; + xl: (string | { + lineHeight: string; + })[]; + '2xl': (string | { + lineHeight: string; + })[]; + '3xl': (string | { + lineHeight: string; + })[]; + '4xl': (string | { + lineHeight: string; + })[]; + '5xl': (string | { + lineHeight: string; + })[]; + '6xl': (string | { + lineHeight: string; + })[]; + '7xl': (string | { + lineHeight: string; + })[]; + '8xl': (string | { + lineHeight: string; + })[]; + '9xl': (string | { + lineHeight: string; + })[]; + }; + fontWeight: { + thin: string; + extralight: string; + light: string; + normal: string; + medium: string; + semibold: string; + bold: string; + extrabold: string; + black: string; + }; + gap: ({ theme }: PluginUtils) => any; + gradientColorStops: ({ theme }: PluginUtils) => any; + gradientColorStopPositions: { + __BARE_VALUE__: (value: NamedUtilityValue) => string | undefined; + '0%': string; + '5%': string; + '10%': string; + '15%': string; + '20%': string; + '25%': string; + '30%': string; + '35%': string; + '40%': string; + '45%': string; + '50%': string; + '55%': string; + '60%': string; + '65%': string; + '70%': string; + '75%': string; + '80%': string; + '85%': string; + '90%': string; + '95%': string; + '100%': string; + }; + grayscale: { + __BARE_VALUE__: (value: NamedUtilityValue) => string | undefined; + 0: string; + DEFAULT: string; + }; + gridAutoColumns: { + auto: string; + min: string; + max: string; + fr: string; + }; + gridAutoRows: { + auto: string; + min: string; + max: string; + fr: string; + }; + gridColumn: { + auto: string; + 'span-1': string; + 'span-2': string; + 'span-3': string; + 'span-4': string; + 'span-5': string; + 'span-6': string; + 'span-7': string; + 'span-8': string; + 'span-9': string; + 'span-10': string; + 'span-11': string; + 'span-12': string; + 'span-full': string; + }; + gridColumnEnd: { + __BARE_VALUE__: (value: NamedUtilityValue) => string | undefined; + auto: string; + 1: string; + 2: string; + 3: string; + 4: string; + 5: string; + 6: string; + 7: string; + 8: string; + 9: string; + 10: string; + 11: string; + 12: string; + 13: string; + }; + gridColumnStart: { + __BARE_VALUE__: (value: NamedUtilityValue) => string | undefined; + auto: string; + 1: string; + 2: string; + 3: string; + 4: string; + 5: string; + 6: string; + 7: string; + 8: string; + 9: string; + 10: string; + 11: string; + 12: string; + 13: string; + }; + gridRow: { + auto: string; + 'span-1': string; + 'span-2': string; + 'span-3': string; + 'span-4': string; + 'span-5': string; + 'span-6': string; + 'span-7': string; + 'span-8': string; + 'span-9': string; + 'span-10': string; + 'span-11': string; + 'span-12': string; + 'span-full': string; + }; + gridRowEnd: { + __BARE_VALUE__: (value: NamedUtilityValue) => string | undefined; + auto: string; + 1: string; + 2: string; + 3: string; + 4: string; + 5: string; + 6: string; + 7: string; + 8: string; + 9: string; + 10: string; + 11: string; + 12: string; + 13: string; + }; + gridRowStart: { + __BARE_VALUE__: (value: NamedUtilityValue) => string | undefined; + auto: string; + 1: string; + 2: string; + 3: string; + 4: string; + 5: string; + 6: string; + 7: string; + 8: string; + 9: string; + 10: string; + 11: string; + 12: string; + 13: string; + }; + gridTemplateColumns: { + __BARE_VALUE__: (value: NamedUtilityValue) => string | undefined; + none: string; + subgrid: string; + 1: string; + 2: string; + 3: string; + 4: string; + 5: string; + 6: string; + 7: string; + 8: string; + 9: string; + 10: string; + 11: string; + 12: string; + }; + gridTemplateRows: { + __BARE_VALUE__: (value: NamedUtilityValue) => string | undefined; + none: string; + subgrid: string; + 1: string; + 2: string; + 3: string; + 4: string; + 5: string; + 6: string; + 7: string; + 8: string; + 9: string; + 10: string; + 11: string; + 12: string; + }; + height: ({ theme }: PluginUtils) => any; + hueRotate: { + __BARE_VALUE__: (value: NamedUtilityValue) => string | undefined; + 0: string; + 15: string; + 30: string; + 60: string; + 90: string; + 180: string; + }; + inset: ({ theme }: PluginUtils) => any; + invert: { + __BARE_VALUE__: (value: NamedUtilityValue) => string | undefined; + 0: string; + DEFAULT: string; + }; + keyframes: { + spin: { + to: { + transform: string; + }; + }; + ping: { + '75%, 100%': { + transform: string; + opacity: string; + }; + }; + pulse: { + '50%': { + opacity: string; + }; + }; + bounce: { + '0%, 100%': { + transform: string; + animationTimingFunction: string; + }; + '50%': { + transform: string; + animationTimingFunction: string; + }; + }; + }; + letterSpacing: { + tighter: string; + tight: string; + normal: string; + wide: string; + wider: string; + widest: string; + }; + lineHeight: { + none: string; + tight: string; + snug: string; + normal: string; + relaxed: string; + loose: string; + 3: string; + 4: string; + 5: string; + 6: string; + 7: string; + 8: string; + 9: string; + 10: string; + }; + listStyleType: { + none: string; + disc: string; + decimal: string; + }; + listStyleImage: { + none: string; + }; + margin: ({ theme }: PluginUtils) => any; + lineClamp: { + __BARE_VALUE__: (value: NamedUtilityValue) => string | undefined; + 1: string; + 2: string; + 3: string; + 4: string; + 5: string; + 6: string; + }; + maxHeight: ({ theme }: PluginUtils) => any; + maxWidth: ({ theme }: PluginUtils) => any; + minHeight: ({ theme }: PluginUtils) => any; + minWidth: ({ theme }: PluginUtils) => any; + objectPosition: { + bottom: string; + center: string; + left: string; + 'left-bottom': string; + 'left-top': string; + right: string; + 'right-bottom': string; + 'right-top': string; + top: string; + }; + opacity: { + __BARE_VALUE__: (value: NamedUtilityValue) => string | undefined; + 0: string; + 5: string; + 10: string; + 15: string; + 20: string; + 25: string; + 30: string; + 35: string; + 40: string; + 45: string; + 50: string; + 55: string; + 60: string; + 65: string; + 70: string; + 75: string; + 80: string; + 85: string; + 90: string; + 95: string; + 100: string; + }; + order: { + __BARE_VALUE__: (value: NamedUtilityValue) => string | undefined; + first: string; + last: string; + none: string; + 1: string; + 2: string; + 3: string; + 4: string; + 5: string; + 6: string; + 7: string; + 8: string; + 9: string; + 10: string; + 11: string; + 12: string; + }; + outlineColor: ({ theme }: PluginUtils) => any; + outlineOffset: { + __BARE_VALUE__: (value: NamedUtilityValue) => string | undefined; + 0: string; + 1: string; + 2: string; + 4: string; + 8: string; + }; + outlineWidth: { + __BARE_VALUE__: (value: NamedUtilityValue) => string | undefined; + 0: string; + 1: string; + 2: string; + 4: string; + 8: string; + }; + padding: ({ theme }: PluginUtils) => any; + placeholderColor: ({ theme }: PluginUtils) => any; + placeholderOpacity: ({ theme }: PluginUtils) => any; + ringColor: ({ theme }: PluginUtils) => any; + ringOffsetColor: ({ theme }: PluginUtils) => any; + ringOffsetWidth: { + __BARE_VALUE__: (value: NamedUtilityValue) => string | undefined; + 0: string; + 1: string; + 2: string; + 4: string; + 8: string; + }; + ringOpacity: ({ theme }: PluginUtils) => any; + ringWidth: { + __BARE_VALUE__: (value: NamedUtilityValue) => string | undefined; + DEFAULT: string; + 0: string; + 1: string; + 2: string; + 4: string; + 8: string; + }; + rotate: { + __BARE_VALUE__: (value: NamedUtilityValue) => string | undefined; + 0: string; + 1: string; + 2: string; + 3: string; + 6: string; + 12: string; + 45: string; + 90: string; + 180: string; + }; + saturate: { + __BARE_VALUE__: (value: NamedUtilityValue) => string | undefined; + 0: string; + 50: string; + 100: string; + 150: string; + 200: string; + }; + scale: { + __BARE_VALUE__: (value: NamedUtilityValue) => string | undefined; + 0: string; + 50: string; + 75: string; + 90: string; + 95: string; + 100: string; + 105: string; + 110: string; + 125: string; + 150: string; + }; + screens: { + sm: string; + md: string; + lg: string; + xl: string; + '2xl': string; + }; + scrollMargin: ({ theme }: PluginUtils) => any; + scrollPadding: ({ theme }: PluginUtils) => any; + sepia: { + __BARE_VALUE__: (value: NamedUtilityValue) => string | undefined; + 0: string; + DEFAULT: string; + }; + skew: { + __BARE_VALUE__: (value: NamedUtilityValue) => string | undefined; + 0: string; + 1: string; + 2: string; + 3: string; + 6: string; + 12: string; + }; + space: ({ theme }: PluginUtils) => any; + spacing: { + px: string; + 0: string; + 0.5: string; + 1: string; + 1.5: string; + 2: string; + 2.5: string; + 3: string; + 3.5: string; + 4: string; + 5: string; + 6: string; + 7: string; + 8: string; + 9: string; + 10: string; + 11: string; + 12: string; + 14: string; + 16: string; + 20: string; + 24: string; + 28: string; + 32: string; + 36: string; + 40: string; + 44: string; + 48: string; + 52: string; + 56: string; + 60: string; + 64: string; + 72: string; + 80: string; + 96: string; + }; + stroke: ({ theme }: PluginUtils) => any; + strokeWidth: { + __BARE_VALUE__: (value: NamedUtilityValue) => string | undefined; + 0: string; + 1: string; + 2: string; + }; + supports: {}; + data: {}; + textColor: ({ theme }: PluginUtils) => any; + textDecorationColor: ({ theme }: PluginUtils) => any; + textDecorationThickness: { + __BARE_VALUE__: (value: NamedUtilityValue) => string | undefined; + auto: string; + 'from-font': string; + 0: string; + 1: string; + 2: string; + 4: string; + 8: string; + }; + textIndent: ({ theme }: PluginUtils) => any; + textOpacity: ({ theme }: PluginUtils) => any; + textUnderlineOffset: { + __BARE_VALUE__: (value: NamedUtilityValue) => string | undefined; + auto: string; + 0: string; + 1: string; + 2: string; + 4: string; + 8: string; + }; + transformOrigin: { + center: string; + top: string; + 'top-right': string; + right: string; + 'bottom-right': string; + bottom: string; + 'bottom-left': string; + left: string; + 'top-left': string; + }; + transitionDelay: { + __BARE_VALUE__: (value: NamedUtilityValue) => string | undefined; + 0: string; + 75: string; + 100: string; + 150: string; + 200: string; + 300: string; + 500: string; + 700: string; + 1000: string; + }; + transitionDuration: { + __BARE_VALUE__: (value: NamedUtilityValue) => string | undefined; + DEFAULT: string; + 0: string; + 75: string; + 100: string; + 150: string; + 200: string; + 300: string; + 500: string; + 700: string; + 1000: string; + }; + transitionProperty: { + none: string; + all: string; + DEFAULT: string; + colors: string; + opacity: string; + shadow: string; + transform: string; + }; + transitionTimingFunction: { + DEFAULT: string; + linear: string; + in: string; + out: string; + 'in-out': string; + }; + translate: ({ theme }: PluginUtils) => any; + size: ({ theme }: PluginUtils) => any; + width: ({ theme }: PluginUtils) => any; + willChange: { + auto: string; + scroll: string; + contents: string; + transform: string; + }; + zIndex: { + __BARE_VALUE__: (value: NamedUtilityValue) => string | undefined; + auto: string; + 0: string; + 10: string; + 20: string; + 30: string; + 40: string; + 50: string; + }; +}; + +export { _default as default }; diff --git a/dg-ui/node_modules/tailwindcss/dist/default-theme.d.ts b/dg-ui/node_modules/tailwindcss/dist/default-theme.d.ts new file mode 100644 index 0000000..e9962f2 --- /dev/null +++ b/dg-ui/node_modules/tailwindcss/dist/default-theme.d.ts @@ -0,0 +1,1199 @@ +import { P as PluginUtils, N as NamedUtilityValue } from './resolve-config-B4yBzhca.js'; +import './colors-C__qRT83.js'; + +declare const _default: { + accentColor: ({ theme }: PluginUtils) => any; + animation: { + none: string; + spin: string; + ping: string; + pulse: string; + bounce: string; + }; + aria: { + busy: string; + checked: string; + disabled: string; + expanded: string; + hidden: string; + pressed: string; + readonly: string; + required: string; + selected: string; + }; + aspectRatio: { + __BARE_VALUE__: (value: NamedUtilityValue) => string | undefined; + auto: string; + square: string; + video: string; + }; + backdropBlur: ({ theme }: PluginUtils) => any; + backdropBrightness: ({ theme }: PluginUtils) => any; + backdropContrast: ({ theme }: PluginUtils) => any; + backdropGrayscale: ({ theme }: PluginUtils) => any; + backdropHueRotate: ({ theme }: PluginUtils) => any; + backdropInvert: ({ theme }: PluginUtils) => any; + backdropOpacity: ({ theme }: PluginUtils) => any; + backdropSaturate: ({ theme }: PluginUtils) => any; + backdropSepia: ({ theme }: PluginUtils) => any; + backgroundColor: ({ theme }: PluginUtils) => any; + backgroundImage: { + none: string; + 'gradient-to-t': string; + 'gradient-to-tr': string; + 'gradient-to-r': string; + 'gradient-to-br': string; + 'gradient-to-b': string; + 'gradient-to-bl': string; + 'gradient-to-l': string; + 'gradient-to-tl': string; + }; + backgroundOpacity: ({ theme }: PluginUtils) => any; + backgroundPosition: { + bottom: string; + center: string; + left: string; + 'left-bottom': string; + 'left-top': string; + right: string; + 'right-bottom': string; + 'right-top': string; + top: string; + }; + backgroundSize: { + auto: string; + cover: string; + contain: string; + }; + blur: { + 0: string; + none: string; + sm: string; + DEFAULT: string; + md: string; + lg: string; + xl: string; + '2xl': string; + '3xl': string; + }; + borderColor: ({ theme }: PluginUtils) => any; + borderOpacity: ({ theme }: PluginUtils) => any; + borderRadius: { + none: string; + sm: string; + DEFAULT: string; + md: string; + lg: string; + xl: string; + '2xl': string; + '3xl': string; + full: string; + }; + borderSpacing: ({ theme }: PluginUtils) => any; + borderWidth: { + __BARE_VALUE__: (value: NamedUtilityValue) => string | undefined; + DEFAULT: string; + 0: string; + 2: string; + 4: string; + 8: string; + }; + boxShadow: { + sm: string; + DEFAULT: string; + md: string; + lg: string; + xl: string; + '2xl': string; + inner: string; + none: string; + }; + boxShadowColor: ({ theme }: PluginUtils) => any; + brightness: { + __BARE_VALUE__: (value: NamedUtilityValue) => string | undefined; + 0: string; + 50: string; + 75: string; + 90: string; + 95: string; + 100: string; + 105: string; + 110: string; + 125: string; + 150: string; + 200: string; + }; + caretColor: ({ theme }: PluginUtils) => any; + colors: () => { + inherit: string; + current: string; + transparent: string; + black: string; + white: string; + slate: { + '50': string; + '100': string; + '200': string; + '300': string; + '400': string; + '500': string; + '600': string; + '700': string; + '800': string; + '900': string; + '950': string; + }; + gray: { + '50': string; + '100': string; + '200': string; + '300': string; + '400': string; + '500': string; + '600': string; + '700': string; + '800': string; + '900': string; + '950': string; + }; + zinc: { + '50': string; + '100': string; + '200': string; + '300': string; + '400': string; + '500': string; + '600': string; + '700': string; + '800': string; + '900': string; + '950': string; + }; + neutral: { + '50': string; + '100': string; + '200': string; + '300': string; + '400': string; + '500': string; + '600': string; + '700': string; + '800': string; + '900': string; + '950': string; + }; + stone: { + '50': string; + '100': string; + '200': string; + '300': string; + '400': string; + '500': string; + '600': string; + '700': string; + '800': string; + '900': string; + '950': string; + }; + mauve: { + '50': string; + '100': string; + '200': string; + '300': string; + '400': string; + '500': string; + '600': string; + '700': string; + '800': string; + '900': string; + '950': string; + }; + olive: { + '50': string; + '100': string; + '200': string; + '300': string; + '400': string; + '500': string; + '600': string; + '700': string; + '800': string; + '900': string; + '950': string; + }; + mist: { + '50': string; + '100': string; + '200': string; + '300': string; + '400': string; + '500': string; + '600': string; + '700': string; + '800': string; + '900': string; + '950': string; + }; + taupe: { + '50': string; + '100': string; + '200': string; + '300': string; + '400': string; + '500': string; + '600': string; + '700': string; + '800': string; + '900': string; + '950': string; + }; + red: { + '50': string; + '100': string; + '200': string; + '300': string; + '400': string; + '500': string; + '600': string; + '700': string; + '800': string; + '900': string; + '950': string; + }; + orange: { + '50': string; + '100': string; + '200': string; + '300': string; + '400': string; + '500': string; + '600': string; + '700': string; + '800': string; + '900': string; + '950': string; + }; + amber: { + '50': string; + '100': string; + '200': string; + '300': string; + '400': string; + '500': string; + '600': string; + '700': string; + '800': string; + '900': string; + '950': string; + }; + yellow: { + '50': string; + '100': string; + '200': string; + '300': string; + '400': string; + '500': string; + '600': string; + '700': string; + '800': string; + '900': string; + '950': string; + }; + lime: { + '50': string; + '100': string; + '200': string; + '300': string; + '400': string; + '500': string; + '600': string; + '700': string; + '800': string; + '900': string; + '950': string; + }; + green: { + '50': string; + '100': string; + '200': string; + '300': string; + '400': string; + '500': string; + '600': string; + '700': string; + '800': string; + '900': string; + '950': string; + }; + emerald: { + '50': string; + '100': string; + '200': string; + '300': string; + '400': string; + '500': string; + '600': string; + '700': string; + '800': string; + '900': string; + '950': string; + }; + teal: { + '50': string; + '100': string; + '200': string; + '300': string; + '400': string; + '500': string; + '600': string; + '700': string; + '800': string; + '900': string; + '950': string; + }; + cyan: { + '50': string; + '100': string; + '200': string; + '300': string; + '400': string; + '500': string; + '600': string; + '700': string; + '800': string; + '900': string; + '950': string; + }; + sky: { + '50': string; + '100': string; + '200': string; + '300': string; + '400': string; + '500': string; + '600': string; + '700': string; + '800': string; + '900': string; + '950': string; + }; + blue: { + '50': string; + '100': string; + '200': string; + '300': string; + '400': string; + '500': string; + '600': string; + '700': string; + '800': string; + '900': string; + '950': string; + }; + indigo: { + '50': string; + '100': string; + '200': string; + '300': string; + '400': string; + '500': string; + '600': string; + '700': string; + '800': string; + '900': string; + '950': string; + }; + violet: { + '50': string; + '100': string; + '200': string; + '300': string; + '400': string; + '500': string; + '600': string; + '700': string; + '800': string; + '900': string; + '950': string; + }; + purple: { + '50': string; + '100': string; + '200': string; + '300': string; + '400': string; + '500': string; + '600': string; + '700': string; + '800': string; + '900': string; + '950': string; + }; + fuchsia: { + '50': string; + '100': string; + '200': string; + '300': string; + '400': string; + '500': string; + '600': string; + '700': string; + '800': string; + '900': string; + '950': string; + }; + pink: { + '50': string; + '100': string; + '200': string; + '300': string; + '400': string; + '500': string; + '600': string; + '700': string; + '800': string; + '900': string; + '950': string; + }; + rose: { + '50': string; + '100': string; + '200': string; + '300': string; + '400': string; + '500': string; + '600': string; + '700': string; + '800': string; + '900': string; + '950': string; + }; + }; + columns: { + __BARE_VALUE__: (value: NamedUtilityValue) => string | undefined; + auto: string; + 1: string; + 2: string; + 3: string; + 4: string; + 5: string; + 6: string; + 7: string; + 8: string; + 9: string; + 10: string; + 11: string; + 12: string; + '3xs': string; + '2xs': string; + xs: string; + sm: string; + md: string; + lg: string; + xl: string; + '2xl': string; + '3xl': string; + '4xl': string; + '5xl': string; + '6xl': string; + '7xl': string; + }; + container: {}; + content: { + none: string; + }; + contrast: { + __BARE_VALUE__: (value: NamedUtilityValue) => string | undefined; + 0: string; + 50: string; + 75: string; + 100: string; + 125: string; + 150: string; + 200: string; + }; + cursor: { + auto: string; + default: string; + pointer: string; + wait: string; + text: string; + move: string; + help: string; + 'not-allowed': string; + none: string; + 'context-menu': string; + progress: string; + cell: string; + crosshair: string; + 'vertical-text': string; + alias: string; + copy: string; + 'no-drop': string; + grab: string; + grabbing: string; + 'all-scroll': string; + 'col-resize': string; + 'row-resize': string; + 'n-resize': string; + 'e-resize': string; + 's-resize': string; + 'w-resize': string; + 'ne-resize': string; + 'nw-resize': string; + 'se-resize': string; + 'sw-resize': string; + 'ew-resize': string; + 'ns-resize': string; + 'nesw-resize': string; + 'nwse-resize': string; + 'zoom-in': string; + 'zoom-out': string; + }; + divideColor: ({ theme }: PluginUtils) => any; + divideOpacity: ({ theme }: PluginUtils) => any; + divideWidth: ({ theme }: PluginUtils) => any; + dropShadow: { + sm: string; + DEFAULT: string[]; + md: string[]; + lg: string[]; + xl: string[]; + '2xl': string; + none: string; + }; + fill: ({ theme }: PluginUtils) => any; + flex: { + 1: string; + auto: string; + initial: string; + none: string; + }; + flexBasis: ({ theme }: PluginUtils) => any; + flexGrow: { + __BARE_VALUE__: (value: NamedUtilityValue) => string | undefined; + 0: string; + DEFAULT: string; + }; + flexShrink: { + __BARE_VALUE__: (value: NamedUtilityValue) => string | undefined; + 0: string; + DEFAULT: string; + }; + fontFamily: { + sans: string[]; + serif: string[]; + mono: string[]; + }; + fontSize: { + xs: (string | { + lineHeight: string; + })[]; + sm: (string | { + lineHeight: string; + })[]; + base: (string | { + lineHeight: string; + })[]; + lg: (string | { + lineHeight: string; + })[]; + xl: (string | { + lineHeight: string; + })[]; + '2xl': (string | { + lineHeight: string; + })[]; + '3xl': (string | { + lineHeight: string; + })[]; + '4xl': (string | { + lineHeight: string; + })[]; + '5xl': (string | { + lineHeight: string; + })[]; + '6xl': (string | { + lineHeight: string; + })[]; + '7xl': (string | { + lineHeight: string; + })[]; + '8xl': (string | { + lineHeight: string; + })[]; + '9xl': (string | { + lineHeight: string; + })[]; + }; + fontWeight: { + thin: string; + extralight: string; + light: string; + normal: string; + medium: string; + semibold: string; + bold: string; + extrabold: string; + black: string; + }; + gap: ({ theme }: PluginUtils) => any; + gradientColorStops: ({ theme }: PluginUtils) => any; + gradientColorStopPositions: { + __BARE_VALUE__: (value: NamedUtilityValue) => string | undefined; + '0%': string; + '5%': string; + '10%': string; + '15%': string; + '20%': string; + '25%': string; + '30%': string; + '35%': string; + '40%': string; + '45%': string; + '50%': string; + '55%': string; + '60%': string; + '65%': string; + '70%': string; + '75%': string; + '80%': string; + '85%': string; + '90%': string; + '95%': string; + '100%': string; + }; + grayscale: { + __BARE_VALUE__: (value: NamedUtilityValue) => string | undefined; + 0: string; + DEFAULT: string; + }; + gridAutoColumns: { + auto: string; + min: string; + max: string; + fr: string; + }; + gridAutoRows: { + auto: string; + min: string; + max: string; + fr: string; + }; + gridColumn: { + auto: string; + 'span-1': string; + 'span-2': string; + 'span-3': string; + 'span-4': string; + 'span-5': string; + 'span-6': string; + 'span-7': string; + 'span-8': string; + 'span-9': string; + 'span-10': string; + 'span-11': string; + 'span-12': string; + 'span-full': string; + }; + gridColumnEnd: { + __BARE_VALUE__: (value: NamedUtilityValue) => string | undefined; + auto: string; + 1: string; + 2: string; + 3: string; + 4: string; + 5: string; + 6: string; + 7: string; + 8: string; + 9: string; + 10: string; + 11: string; + 12: string; + 13: string; + }; + gridColumnStart: { + __BARE_VALUE__: (value: NamedUtilityValue) => string | undefined; + auto: string; + 1: string; + 2: string; + 3: string; + 4: string; + 5: string; + 6: string; + 7: string; + 8: string; + 9: string; + 10: string; + 11: string; + 12: string; + 13: string; + }; + gridRow: { + auto: string; + 'span-1': string; + 'span-2': string; + 'span-3': string; + 'span-4': string; + 'span-5': string; + 'span-6': string; + 'span-7': string; + 'span-8': string; + 'span-9': string; + 'span-10': string; + 'span-11': string; + 'span-12': string; + 'span-full': string; + }; + gridRowEnd: { + __BARE_VALUE__: (value: NamedUtilityValue) => string | undefined; + auto: string; + 1: string; + 2: string; + 3: string; + 4: string; + 5: string; + 6: string; + 7: string; + 8: string; + 9: string; + 10: string; + 11: string; + 12: string; + 13: string; + }; + gridRowStart: { + __BARE_VALUE__: (value: NamedUtilityValue) => string | undefined; + auto: string; + 1: string; + 2: string; + 3: string; + 4: string; + 5: string; + 6: string; + 7: string; + 8: string; + 9: string; + 10: string; + 11: string; + 12: string; + 13: string; + }; + gridTemplateColumns: { + __BARE_VALUE__: (value: NamedUtilityValue) => string | undefined; + none: string; + subgrid: string; + 1: string; + 2: string; + 3: string; + 4: string; + 5: string; + 6: string; + 7: string; + 8: string; + 9: string; + 10: string; + 11: string; + 12: string; + }; + gridTemplateRows: { + __BARE_VALUE__: (value: NamedUtilityValue) => string | undefined; + none: string; + subgrid: string; + 1: string; + 2: string; + 3: string; + 4: string; + 5: string; + 6: string; + 7: string; + 8: string; + 9: string; + 10: string; + 11: string; + 12: string; + }; + height: ({ theme }: PluginUtils) => any; + hueRotate: { + __BARE_VALUE__: (value: NamedUtilityValue) => string | undefined; + 0: string; + 15: string; + 30: string; + 60: string; + 90: string; + 180: string; + }; + inset: ({ theme }: PluginUtils) => any; + invert: { + __BARE_VALUE__: (value: NamedUtilityValue) => string | undefined; + 0: string; + DEFAULT: string; + }; + keyframes: { + spin: { + to: { + transform: string; + }; + }; + ping: { + '75%, 100%': { + transform: string; + opacity: string; + }; + }; + pulse: { + '50%': { + opacity: string; + }; + }; + bounce: { + '0%, 100%': { + transform: string; + animationTimingFunction: string; + }; + '50%': { + transform: string; + animationTimingFunction: string; + }; + }; + }; + letterSpacing: { + tighter: string; + tight: string; + normal: string; + wide: string; + wider: string; + widest: string; + }; + lineHeight: { + none: string; + tight: string; + snug: string; + normal: string; + relaxed: string; + loose: string; + 3: string; + 4: string; + 5: string; + 6: string; + 7: string; + 8: string; + 9: string; + 10: string; + }; + listStyleType: { + none: string; + disc: string; + decimal: string; + }; + listStyleImage: { + none: string; + }; + margin: ({ theme }: PluginUtils) => any; + lineClamp: { + __BARE_VALUE__: (value: NamedUtilityValue) => string | undefined; + 1: string; + 2: string; + 3: string; + 4: string; + 5: string; + 6: string; + }; + maxHeight: ({ theme }: PluginUtils) => any; + maxWidth: ({ theme }: PluginUtils) => any; + minHeight: ({ theme }: PluginUtils) => any; + minWidth: ({ theme }: PluginUtils) => any; + objectPosition: { + bottom: string; + center: string; + left: string; + 'left-bottom': string; + 'left-top': string; + right: string; + 'right-bottom': string; + 'right-top': string; + top: string; + }; + opacity: { + __BARE_VALUE__: (value: NamedUtilityValue) => string | undefined; + 0: string; + 5: string; + 10: string; + 15: string; + 20: string; + 25: string; + 30: string; + 35: string; + 40: string; + 45: string; + 50: string; + 55: string; + 60: string; + 65: string; + 70: string; + 75: string; + 80: string; + 85: string; + 90: string; + 95: string; + 100: string; + }; + order: { + __BARE_VALUE__: (value: NamedUtilityValue) => string | undefined; + first: string; + last: string; + none: string; + 1: string; + 2: string; + 3: string; + 4: string; + 5: string; + 6: string; + 7: string; + 8: string; + 9: string; + 10: string; + 11: string; + 12: string; + }; + outlineColor: ({ theme }: PluginUtils) => any; + outlineOffset: { + __BARE_VALUE__: (value: NamedUtilityValue) => string | undefined; + 0: string; + 1: string; + 2: string; + 4: string; + 8: string; + }; + outlineWidth: { + __BARE_VALUE__: (value: NamedUtilityValue) => string | undefined; + 0: string; + 1: string; + 2: string; + 4: string; + 8: string; + }; + padding: ({ theme }: PluginUtils) => any; + placeholderColor: ({ theme }: PluginUtils) => any; + placeholderOpacity: ({ theme }: PluginUtils) => any; + ringColor: ({ theme }: PluginUtils) => any; + ringOffsetColor: ({ theme }: PluginUtils) => any; + ringOffsetWidth: { + __BARE_VALUE__: (value: NamedUtilityValue) => string | undefined; + 0: string; + 1: string; + 2: string; + 4: string; + 8: string; + }; + ringOpacity: ({ theme }: PluginUtils) => any; + ringWidth: { + __BARE_VALUE__: (value: NamedUtilityValue) => string | undefined; + DEFAULT: string; + 0: string; + 1: string; + 2: string; + 4: string; + 8: string; + }; + rotate: { + __BARE_VALUE__: (value: NamedUtilityValue) => string | undefined; + 0: string; + 1: string; + 2: string; + 3: string; + 6: string; + 12: string; + 45: string; + 90: string; + 180: string; + }; + saturate: { + __BARE_VALUE__: (value: NamedUtilityValue) => string | undefined; + 0: string; + 50: string; + 100: string; + 150: string; + 200: string; + }; + scale: { + __BARE_VALUE__: (value: NamedUtilityValue) => string | undefined; + 0: string; + 50: string; + 75: string; + 90: string; + 95: string; + 100: string; + 105: string; + 110: string; + 125: string; + 150: string; + }; + screens: { + sm: string; + md: string; + lg: string; + xl: string; + '2xl': string; + }; + scrollMargin: ({ theme }: PluginUtils) => any; + scrollPadding: ({ theme }: PluginUtils) => any; + sepia: { + __BARE_VALUE__: (value: NamedUtilityValue) => string | undefined; + 0: string; + DEFAULT: string; + }; + skew: { + __BARE_VALUE__: (value: NamedUtilityValue) => string | undefined; + 0: string; + 1: string; + 2: string; + 3: string; + 6: string; + 12: string; + }; + space: ({ theme }: PluginUtils) => any; + spacing: { + px: string; + 0: string; + 0.5: string; + 1: string; + 1.5: string; + 2: string; + 2.5: string; + 3: string; + 3.5: string; + 4: string; + 5: string; + 6: string; + 7: string; + 8: string; + 9: string; + 10: string; + 11: string; + 12: string; + 14: string; + 16: string; + 20: string; + 24: string; + 28: string; + 32: string; + 36: string; + 40: string; + 44: string; + 48: string; + 52: string; + 56: string; + 60: string; + 64: string; + 72: string; + 80: string; + 96: string; + }; + stroke: ({ theme }: PluginUtils) => any; + strokeWidth: { + __BARE_VALUE__: (value: NamedUtilityValue) => string | undefined; + 0: string; + 1: string; + 2: string; + }; + supports: {}; + data: {}; + textColor: ({ theme }: PluginUtils) => any; + textDecorationColor: ({ theme }: PluginUtils) => any; + textDecorationThickness: { + __BARE_VALUE__: (value: NamedUtilityValue) => string | undefined; + auto: string; + 'from-font': string; + 0: string; + 1: string; + 2: string; + 4: string; + 8: string; + }; + textIndent: ({ theme }: PluginUtils) => any; + textOpacity: ({ theme }: PluginUtils) => any; + textUnderlineOffset: { + __BARE_VALUE__: (value: NamedUtilityValue) => string | undefined; + auto: string; + 0: string; + 1: string; + 2: string; + 4: string; + 8: string; + }; + transformOrigin: { + center: string; + top: string; + 'top-right': string; + right: string; + 'bottom-right': string; + bottom: string; + 'bottom-left': string; + left: string; + 'top-left': string; + }; + transitionDelay: { + __BARE_VALUE__: (value: NamedUtilityValue) => string | undefined; + 0: string; + 75: string; + 100: string; + 150: string; + 200: string; + 300: string; + 500: string; + 700: string; + 1000: string; + }; + transitionDuration: { + __BARE_VALUE__: (value: NamedUtilityValue) => string | undefined; + DEFAULT: string; + 0: string; + 75: string; + 100: string; + 150: string; + 200: string; + 300: string; + 500: string; + 700: string; + 1000: string; + }; + transitionProperty: { + none: string; + all: string; + DEFAULT: string; + colors: string; + opacity: string; + shadow: string; + transform: string; + }; + transitionTimingFunction: { + DEFAULT: string; + linear: string; + in: string; + out: string; + 'in-out': string; + }; + translate: ({ theme }: PluginUtils) => any; + size: ({ theme }: PluginUtils) => any; + width: ({ theme }: PluginUtils) => any; + willChange: { + auto: string; + scroll: string; + contents: string; + transform: string; + }; + zIndex: { + __BARE_VALUE__: (value: NamedUtilityValue) => string | undefined; + auto: string; + 0: string; + 10: string; + 20: string; + 30: string; + 40: string; + 50: string; + }; +}; + +export { _default as default }; diff --git a/dg-ui/node_modules/tailwindcss/dist/default-theme.js b/dg-ui/node_modules/tailwindcss/dist/default-theme.js new file mode 100644 index 0000000..bb72f93 --- /dev/null +++ b/dg-ui/node_modules/tailwindcss/dist/default-theme.js @@ -0,0 +1 @@ +"use strict";var m=new Uint8Array(256);function u(e,c){let t=0,g=[],k=0,d=e.length,w=c.charCodeAt(0);for(let n=0;n0&&h===m[t-1]&&t--;break}}return g.push(e.slice(k)),g}var l=/[+-]?\d*\.?\d+(?:[eE][+-]?\d+)?/,z=new RegExp(`^${l.source}$`);var T=new RegExp(`^${l.source}%$`);var I=new RegExp(`^${l.source}\\s*/\\s*${l.source}$`);var A=["cm","mm","Q","in","pc","pt","px","em","ex","ch","cap","ic","rem","rex","rch","rcap","ric","lh","rlh","vw","vh","vmin","vmax","vb","vi","svw","svh","svi","svb","svmin","svmax","lvw","lvh","lvi","lvb","lvmin","lvmax","dvw","dvh","dvi","dvb","dvmin","dvmax","cqw","cqh","cqi","cqb","cqmin","cqmax"],D=new RegExp(`^${l.source}(${A.join("|")})$`);var C=["deg","rad","grad","turn"],F=new RegExp(`^${l.source}(${C.join("|")})$`);var H=new RegExp(`^${l.source} +${l.source} +${l.source}$`);function i(e){let c=Number(e);return Number.isInteger(c)&&c>=0&&String(c)===String(e)}var f={inherit:"inherit",current:"currentcolor",transparent:"transparent",black:"#000",white:"#fff",slate:{50:"oklch(98.4% 0.003 247.858)",100:"oklch(96.8% 0.007 247.896)",200:"oklch(92.9% 0.013 255.508)",300:"oklch(86.9% 0.022 252.894)",400:"oklch(70.4% 0.04 256.788)",500:"oklch(55.4% 0.046 257.417)",600:"oklch(44.6% 0.043 257.281)",700:"oklch(37.2% 0.044 257.287)",800:"oklch(27.9% 0.041 260.031)",900:"oklch(20.8% 0.042 265.755)",950:"oklch(12.9% 0.042 264.695)"},gray:{50:"oklch(98.5% 0.002 247.839)",100:"oklch(96.7% 0.003 264.542)",200:"oklch(92.8% 0.006 264.531)",300:"oklch(87.2% 0.01 258.338)",400:"oklch(70.7% 0.022 261.325)",500:"oklch(55.1% 0.027 264.364)",600:"oklch(44.6% 0.03 256.802)",700:"oklch(37.3% 0.034 259.733)",800:"oklch(27.8% 0.033 256.848)",900:"oklch(21% 0.034 264.665)",950:"oklch(13% 0.028 261.692)"},zinc:{50:"oklch(98.5% 0 none)",100:"oklch(96.7% 0.001 286.375)",200:"oklch(92% 0.004 286.32)",300:"oklch(87.1% 0.006 286.286)",400:"oklch(70.5% 0.015 286.067)",500:"oklch(55.2% 0.016 285.938)",600:"oklch(44.2% 0.017 285.786)",700:"oklch(37% 0.013 285.805)",800:"oklch(27.4% 0.006 286.033)",900:"oklch(21% 0.006 285.885)",950:"oklch(14.1% 0.005 285.823)"},neutral:{50:"oklch(98.5% 0 none)",100:"oklch(97% 0 none)",200:"oklch(92.2% 0 none)",300:"oklch(87% 0 none)",400:"oklch(70.8% 0 none)",500:"oklch(55.6% 0 none)",600:"oklch(43.9% 0 none)",700:"oklch(37.1% 0 none)",800:"oklch(26.9% 0 none)",900:"oklch(20.5% 0 none)",950:"oklch(14.5% 0 none)"},stone:{50:"oklch(98.5% 0.001 106.423)",100:"oklch(97% 0.001 106.424)",200:"oklch(92.3% 0.003 48.717)",300:"oklch(86.9% 0.005 56.366)",400:"oklch(70.9% 0.01 56.259)",500:"oklch(55.3% 0.013 58.071)",600:"oklch(44.4% 0.011 73.639)",700:"oklch(37.4% 0.01 67.558)",800:"oklch(26.8% 0.007 34.298)",900:"oklch(21.6% 0.006 56.043)",950:"oklch(14.7% 0.004 49.25)"},mauve:{50:"oklch(98.5% 0 none)",100:"oklch(96% 0.003 325.6)",200:"oklch(92.2% 0.005 325.62)",300:"oklch(86.5% 0.012 325.68)",400:"oklch(71.1% 0.019 323.02)",500:"oklch(54.2% 0.034 322.5)",600:"oklch(43.5% 0.029 321.78)",700:"oklch(36.4% 0.029 323.89)",800:"oklch(26.3% 0.024 320.12)",900:"oklch(21.2% 0.019 322.12)",950:"oklch(14.5% 0.008 326)"},olive:{50:"oklch(98.8% 0.003 106.5)",100:"oklch(96.6% 0.005 106.5)",200:"oklch(93% 0.007 106.5)",300:"oklch(88% 0.011 106.6)",400:"oklch(73.7% 0.021 106.9)",500:"oklch(58% 0.031 107.3)",600:"oklch(46.6% 0.025 107.3)",700:"oklch(39.4% 0.023 107.4)",800:"oklch(28.6% 0.016 107.4)",900:"oklch(22.8% 0.013 107.4)",950:"oklch(15.3% 0.006 107.1)"},mist:{50:"oklch(98.7% 0.002 197.1)",100:"oklch(96.3% 0.002 197.1)",200:"oklch(92.5% 0.005 214.3)",300:"oklch(87.2% 0.007 219.6)",400:"oklch(72.3% 0.014 214.4)",500:"oklch(56% 0.021 213.5)",600:"oklch(45% 0.017 213.2)",700:"oklch(37.8% 0.015 216)",800:"oklch(27.5% 0.011 216.9)",900:"oklch(21.8% 0.008 223.9)",950:"oklch(14.8% 0.004 228.8)"},taupe:{50:"oklch(98.6% 0.002 67.8)",100:"oklch(96% 0.002 17.2)",200:"oklch(92.2% 0.005 34.3)",300:"oklch(86.8% 0.007 39.5)",400:"oklch(71.4% 0.014 41.2)",500:"oklch(54.7% 0.021 43.1)",600:"oklch(43.8% 0.017 39.3)",700:"oklch(36.7% 0.016 35.7)",800:"oklch(26.8% 0.011 36.5)",900:"oklch(21.4% 0.009 43.1)",950:"oklch(14.7% 0.004 49.3)"},red:{50:"oklch(97.1% 0.013 17.38)",100:"oklch(93.6% 0.032 17.717)",200:"oklch(88.5% 0.062 18.334)",300:"oklch(80.8% 0.114 19.571)",400:"oklch(70.4% 0.191 22.216)",500:"oklch(63.7% 0.237 25.331)",600:"oklch(57.7% 0.245 27.325)",700:"oklch(50.5% 0.213 27.518)",800:"oklch(44.4% 0.177 26.899)",900:"oklch(39.6% 0.141 25.723)",950:"oklch(25.8% 0.092 26.042)"},orange:{50:"oklch(98% 0.016 73.684)",100:"oklch(95.4% 0.038 75.164)",200:"oklch(90.1% 0.076 70.697)",300:"oklch(83.7% 0.128 66.29)",400:"oklch(75% 0.183 55.934)",500:"oklch(70.5% 0.213 47.604)",600:"oklch(64.6% 0.222 41.116)",700:"oklch(55.3% 0.195 38.402)",800:"oklch(47% 0.157 37.304)",900:"oklch(40.8% 0.123 38.172)",950:"oklch(26.6% 0.079 36.259)"},amber:{50:"oklch(98.7% 0.022 95.277)",100:"oklch(96.2% 0.059 95.617)",200:"oklch(92.4% 0.12 95.746)",300:"oklch(87.9% 0.169 91.605)",400:"oklch(82.8% 0.189 84.429)",500:"oklch(76.9% 0.188 70.08)",600:"oklch(66.6% 0.179 58.318)",700:"oklch(55.5% 0.163 48.998)",800:"oklch(47.3% 0.137 46.201)",900:"oklch(41.4% 0.112 45.904)",950:"oklch(27.9% 0.077 45.635)"},yellow:{50:"oklch(98.7% 0.026 102.212)",100:"oklch(97.3% 0.071 103.193)",200:"oklch(94.5% 0.129 101.54)",300:"oklch(90.5% 0.182 98.111)",400:"oklch(85.2% 0.199 91.936)",500:"oklch(79.5% 0.184 86.047)",600:"oklch(68.1% 0.162 75.834)",700:"oklch(55.4% 0.135 66.442)",800:"oklch(47.6% 0.114 61.907)",900:"oklch(42.1% 0.095 57.708)",950:"oklch(28.6% 0.066 53.813)"},lime:{50:"oklch(98.6% 0.031 120.757)",100:"oklch(96.7% 0.067 122.328)",200:"oklch(93.8% 0.127 124.321)",300:"oklch(89.7% 0.196 126.665)",400:"oklch(84.1% 0.238 128.85)",500:"oklch(76.8% 0.233 130.85)",600:"oklch(64.8% 0.2 131.684)",700:"oklch(53.2% 0.157 131.589)",800:"oklch(45.3% 0.124 130.933)",900:"oklch(40.5% 0.101 131.063)",950:"oklch(27.4% 0.072 132.109)"},green:{50:"oklch(98.2% 0.018 155.826)",100:"oklch(96.2% 0.044 156.743)",200:"oklch(92.5% 0.084 155.995)",300:"oklch(87.1% 0.15 154.449)",400:"oklch(79.2% 0.209 151.711)",500:"oklch(72.3% 0.219 149.579)",600:"oklch(62.7% 0.194 149.214)",700:"oklch(52.7% 0.154 150.069)",800:"oklch(44.8% 0.119 151.328)",900:"oklch(39.3% 0.095 152.535)",950:"oklch(26.6% 0.065 152.934)"},emerald:{50:"oklch(97.9% 0.021 166.113)",100:"oklch(95% 0.052 163.051)",200:"oklch(90.5% 0.093 164.15)",300:"oklch(84.5% 0.143 164.978)",400:"oklch(76.5% 0.177 163.223)",500:"oklch(69.6% 0.17 162.48)",600:"oklch(59.6% 0.145 163.225)",700:"oklch(50.8% 0.118 165.612)",800:"oklch(43.2% 0.095 166.913)",900:"oklch(37.8% 0.077 168.94)",950:"oklch(26.2% 0.051 172.552)"},teal:{50:"oklch(98.4% 0.014 180.72)",100:"oklch(95.3% 0.051 180.801)",200:"oklch(91% 0.096 180.426)",300:"oklch(85.5% 0.138 181.071)",400:"oklch(77.7% 0.152 181.912)",500:"oklch(70.4% 0.14 182.503)",600:"oklch(60% 0.118 184.704)",700:"oklch(51.1% 0.096 186.391)",800:"oklch(43.7% 0.078 188.216)",900:"oklch(38.6% 0.063 188.416)",950:"oklch(27.7% 0.046 192.524)"},cyan:{50:"oklch(98.4% 0.019 200.873)",100:"oklch(95.6% 0.045 203.388)",200:"oklch(91.7% 0.08 205.041)",300:"oklch(86.5% 0.127 207.078)",400:"oklch(78.9% 0.154 211.53)",500:"oklch(71.5% 0.143 215.221)",600:"oklch(60.9% 0.126 221.723)",700:"oklch(52% 0.105 223.128)",800:"oklch(45% 0.085 224.283)",900:"oklch(39.8% 0.07 227.392)",950:"oklch(30.2% 0.056 229.695)"},sky:{50:"oklch(97.7% 0.013 236.62)",100:"oklch(95.1% 0.026 236.824)",200:"oklch(90.1% 0.058 230.902)",300:"oklch(82.8% 0.111 230.318)",400:"oklch(74.6% 0.16 232.661)",500:"oklch(68.5% 0.169 237.323)",600:"oklch(58.8% 0.158 241.966)",700:"oklch(50% 0.134 242.749)",800:"oklch(44.3% 0.11 240.79)",900:"oklch(39.1% 0.09 240.876)",950:"oklch(29.3% 0.066 243.157)"},blue:{50:"oklch(97% 0.014 254.604)",100:"oklch(93.2% 0.032 255.585)",200:"oklch(88.2% 0.059 254.128)",300:"oklch(80.9% 0.105 251.813)",400:"oklch(70.7% 0.165 254.624)",500:"oklch(62.3% 0.214 259.815)",600:"oklch(54.6% 0.245 262.881)",700:"oklch(48.8% 0.243 264.376)",800:"oklch(42.4% 0.199 265.638)",900:"oklch(37.9% 0.146 265.522)",950:"oklch(28.2% 0.091 267.935)"},indigo:{50:"oklch(96.2% 0.018 272.314)",100:"oklch(93% 0.034 272.788)",200:"oklch(87% 0.065 274.039)",300:"oklch(78.5% 0.115 274.713)",400:"oklch(67.3% 0.182 276.935)",500:"oklch(58.5% 0.233 277.117)",600:"oklch(51.1% 0.262 276.966)",700:"oklch(45.7% 0.24 277.023)",800:"oklch(39.8% 0.195 277.366)",900:"oklch(35.9% 0.144 278.697)",950:"oklch(25.7% 0.09 281.288)"},violet:{50:"oklch(96.9% 0.016 293.756)",100:"oklch(94.3% 0.029 294.588)",200:"oklch(89.4% 0.057 293.283)",300:"oklch(81.1% 0.111 293.571)",400:"oklch(70.2% 0.183 293.541)",500:"oklch(60.6% 0.25 292.717)",600:"oklch(54.1% 0.281 293.009)",700:"oklch(49.1% 0.27 292.581)",800:"oklch(43.2% 0.232 292.759)",900:"oklch(38% 0.189 293.745)",950:"oklch(28.3% 0.141 291.089)"},purple:{50:"oklch(97.7% 0.014 308.299)",100:"oklch(94.6% 0.033 307.174)",200:"oklch(90.2% 0.063 306.703)",300:"oklch(82.7% 0.119 306.383)",400:"oklch(71.4% 0.203 305.504)",500:"oklch(62.7% 0.265 303.9)",600:"oklch(55.8% 0.288 302.321)",700:"oklch(49.6% 0.265 301.924)",800:"oklch(43.8% 0.218 303.724)",900:"oklch(38.1% 0.176 304.987)",950:"oklch(29.1% 0.149 302.717)"},fuchsia:{50:"oklch(97.7% 0.017 320.058)",100:"oklch(95.2% 0.037 318.852)",200:"oklch(90.3% 0.076 319.62)",300:"oklch(83.3% 0.145 321.434)",400:"oklch(74% 0.238 322.16)",500:"oklch(66.7% 0.295 322.15)",600:"oklch(59.1% 0.293 322.896)",700:"oklch(51.8% 0.253 323.949)",800:"oklch(45.2% 0.211 324.591)",900:"oklch(40.1% 0.17 325.612)",950:"oklch(29.3% 0.136 325.661)"},pink:{50:"oklch(97.1% 0.014 343.198)",100:"oklch(94.8% 0.028 342.258)",200:"oklch(89.9% 0.061 343.231)",300:"oklch(82.3% 0.12 346.018)",400:"oklch(71.8% 0.202 349.761)",500:"oklch(65.6% 0.241 354.308)",600:"oklch(59.2% 0.249 0.584)",700:"oklch(52.5% 0.223 3.958)",800:"oklch(45.9% 0.187 3.815)",900:"oklch(40.8% 0.153 2.432)",950:"oklch(28.4% 0.109 3.907)"},rose:{50:"oklch(96.9% 0.015 12.422)",100:"oklch(94.1% 0.03 12.58)",200:"oklch(89.2% 0.058 10.001)",300:"oklch(81% 0.117 11.638)",400:"oklch(71.2% 0.194 13.428)",500:"oklch(64.5% 0.246 16.439)",600:"oklch(58.6% 0.253 17.585)",700:"oklch(51.4% 0.222 16.935)",800:"oklch(45.5% 0.188 13.697)",900:"oklch(41% 0.159 10.272)",950:"oklch(27.1% 0.105 12.094)"}};function s(e){return{__BARE_VALUE__:e}}var r=s(e=>{if(i(e.value))return e.value}),o=s(e=>{if(i(e.value))return`${e.value}%`}),a=s(e=>{if(i(e.value))return`${e.value}px`}),b=s(e=>{if(i(e.value))return`${e.value}ms`}),p=s(e=>{if(i(e.value))return`${e.value}deg`}),v=s(e=>{if(e.fraction===null)return;let[c,t]=u(e.fraction,"/");if(!(!i(c)||!i(t)))return e.fraction}),E=s(e=>{if(i(Number(e.value)))return`repeat(${e.value}, minmax(0, 1fr))`}),y={accentColor:({theme:e})=>e("colors"),animation:{none:"none",spin:"spin 1s linear infinite",ping:"ping 1s cubic-bezier(0, 0, 0.2, 1) infinite",pulse:"pulse 2s cubic-bezier(0.4, 0, 0.6, 1) infinite",bounce:"bounce 1s infinite"},aria:{busy:'busy="true"',checked:'checked="true"',disabled:'disabled="true"',expanded:'expanded="true"',hidden:'hidden="true"',pressed:'pressed="true"',readonly:'readonly="true"',required:'required="true"',selected:'selected="true"'},aspectRatio:{auto:"auto",square:"1 / 1",video:"16 / 9",...v},backdropBlur:({theme:e})=>e("blur"),backdropBrightness:({theme:e})=>({...e("brightness"),...o}),backdropContrast:({theme:e})=>({...e("contrast"),...o}),backdropGrayscale:({theme:e})=>({...e("grayscale"),...o}),backdropHueRotate:({theme:e})=>({...e("hueRotate"),...p}),backdropInvert:({theme:e})=>({...e("invert"),...o}),backdropOpacity:({theme:e})=>({...e("opacity"),...o}),backdropSaturate:({theme:e})=>({...e("saturate"),...o}),backdropSepia:({theme:e})=>({...e("sepia"),...o}),backgroundColor:({theme:e})=>e("colors"),backgroundImage:{none:"none","gradient-to-t":"linear-gradient(to top, var(--tw-gradient-stops))","gradient-to-tr":"linear-gradient(to top right, var(--tw-gradient-stops))","gradient-to-r":"linear-gradient(to right, var(--tw-gradient-stops))","gradient-to-br":"linear-gradient(to bottom right, var(--tw-gradient-stops))","gradient-to-b":"linear-gradient(to bottom, var(--tw-gradient-stops))","gradient-to-bl":"linear-gradient(to bottom left, var(--tw-gradient-stops))","gradient-to-l":"linear-gradient(to left, var(--tw-gradient-stops))","gradient-to-tl":"linear-gradient(to top left, var(--tw-gradient-stops))"},backgroundOpacity:({theme:e})=>e("opacity"),backgroundPosition:{bottom:"bottom",center:"center",left:"left","left-bottom":"left bottom","left-top":"left top",right:"right","right-bottom":"right bottom","right-top":"right top",top:"top"},backgroundSize:{auto:"auto",cover:"cover",contain:"contain"},blur:{0:"0",none:"",sm:"4px",DEFAULT:"8px",md:"12px",lg:"16px",xl:"24px","2xl":"40px","3xl":"64px"},borderColor:({theme:e})=>({DEFAULT:"currentcolor",...e("colors")}),borderOpacity:({theme:e})=>e("opacity"),borderRadius:{none:"0px",sm:"0.125rem",DEFAULT:"0.25rem",md:"0.375rem",lg:"0.5rem",xl:"0.75rem","2xl":"1rem","3xl":"1.5rem",full:"9999px"},borderSpacing:({theme:e})=>e("spacing"),borderWidth:{DEFAULT:"1px",0:"0px",2:"2px",4:"4px",8:"8px",...a},boxShadow:{sm:"0 1px 2px 0 rgb(0 0 0 / 0.05)",DEFAULT:"0 1px 3px 0 rgb(0 0 0 / 0.1), 0 1px 2px -1px rgb(0 0 0 / 0.1)",md:"0 4px 6px -1px rgb(0 0 0 / 0.1), 0 2px 4px -2px rgb(0 0 0 / 0.1)",lg:"0 10px 15px -3px rgb(0 0 0 / 0.1), 0 4px 6px -4px rgb(0 0 0 / 0.1)",xl:"0 20px 25px -5px rgb(0 0 0 / 0.1), 0 8px 10px -6px rgb(0 0 0 / 0.1)","2xl":"0 25px 50px -12px rgb(0 0 0 / 0.25)",inner:"inset 0 2px 4px 0 rgb(0 0 0 / 0.05)",none:"none"},boxShadowColor:({theme:e})=>e("colors"),brightness:{0:"0",50:".5",75:".75",90:".9",95:".95",100:"1",105:"1.05",110:"1.1",125:"1.25",150:"1.5",200:"2",...o},caretColor:({theme:e})=>e("colors"),colors:()=>({...f}),columns:{auto:"auto",1:"1",2:"2",3:"3",4:"4",5:"5",6:"6",7:"7",8:"8",9:"9",10:"10",11:"11",12:"12","3xs":"16rem","2xs":"18rem",xs:"20rem",sm:"24rem",md:"28rem",lg:"32rem",xl:"36rem","2xl":"42rem","3xl":"48rem","4xl":"56rem","5xl":"64rem","6xl":"72rem","7xl":"80rem",...r},container:{},content:{none:"none"},contrast:{0:"0",50:".5",75:".75",100:"1",125:"1.25",150:"1.5",200:"2",...o},cursor:{auto:"auto",default:"default",pointer:"pointer",wait:"wait",text:"text",move:"move",help:"help","not-allowed":"not-allowed",none:"none","context-menu":"context-menu",progress:"progress",cell:"cell",crosshair:"crosshair","vertical-text":"vertical-text",alias:"alias",copy:"copy","no-drop":"no-drop",grab:"grab",grabbing:"grabbing","all-scroll":"all-scroll","col-resize":"col-resize","row-resize":"row-resize","n-resize":"n-resize","e-resize":"e-resize","s-resize":"s-resize","w-resize":"w-resize","ne-resize":"ne-resize","nw-resize":"nw-resize","se-resize":"se-resize","sw-resize":"sw-resize","ew-resize":"ew-resize","ns-resize":"ns-resize","nesw-resize":"nesw-resize","nwse-resize":"nwse-resize","zoom-in":"zoom-in","zoom-out":"zoom-out"},divideColor:({theme:e})=>e("borderColor"),divideOpacity:({theme:e})=>e("borderOpacity"),divideWidth:({theme:e})=>({...e("borderWidth"),...a}),dropShadow:{sm:"0 1px 1px rgb(0 0 0 / 0.05)",DEFAULT:["0 1px 2px rgb(0 0 0 / 0.1)","0 1px 1px rgb(0 0 0 / 0.06)"],md:["0 4px 3px rgb(0 0 0 / 0.07)","0 2px 2px rgb(0 0 0 / 0.06)"],lg:["0 10px 8px rgb(0 0 0 / 0.04)","0 4px 3px rgb(0 0 0 / 0.1)"],xl:["0 20px 13px rgb(0 0 0 / 0.03)","0 8px 5px rgb(0 0 0 / 0.08)"],"2xl":"0 25px 25px rgb(0 0 0 / 0.15)",none:"0 0 #0000"},fill:({theme:e})=>e("colors"),flex:{1:"1 1 0%",auto:"1 1 auto",initial:"0 1 auto",none:"none"},flexBasis:({theme:e})=>({auto:"auto","1/2":"50%","1/3":"33.333333%","2/3":"66.666667%","1/4":"25%","2/4":"50%","3/4":"75%","1/5":"20%","2/5":"40%","3/5":"60%","4/5":"80%","1/6":"16.666667%","2/6":"33.333333%","3/6":"50%","4/6":"66.666667%","5/6":"83.333333%","1/12":"8.333333%","2/12":"16.666667%","3/12":"25%","4/12":"33.333333%","5/12":"41.666667%","6/12":"50%","7/12":"58.333333%","8/12":"66.666667%","9/12":"75%","10/12":"83.333333%","11/12":"91.666667%",full:"100%",...e("spacing")}),flexGrow:{0:"0",DEFAULT:"1",...r},flexShrink:{0:"0",DEFAULT:"1",...r},fontFamily:{sans:["-apple-system","BlinkMacSystemFont",'"Segoe UI"',"Roboto",'"Helvetica Neue"','"Noto Sans"',"Arial","sans-serif",'"Apple Color Emoji"','"Segoe UI Emoji"','"Segoe UI Symbol"','"Noto Color Emoji"'],serif:["ui-serif","Georgia","Cambria",'"Times New Roman"',"Times","serif"],mono:["ui-monospace","SFMono-Regular","Menlo","Monaco","Consolas",'"Liberation Mono"','"Courier New"',"monospace"]},fontSize:{xs:["0.75rem",{lineHeight:"1rem"}],sm:["0.875rem",{lineHeight:"1.25rem"}],base:["1rem",{lineHeight:"1.5rem"}],lg:["1.125rem",{lineHeight:"1.75rem"}],xl:["1.25rem",{lineHeight:"1.75rem"}],"2xl":["1.5rem",{lineHeight:"2rem"}],"3xl":["1.875rem",{lineHeight:"2.25rem"}],"4xl":["2.25rem",{lineHeight:"2.5rem"}],"5xl":["3rem",{lineHeight:"1"}],"6xl":["3.75rem",{lineHeight:"1"}],"7xl":["4.5rem",{lineHeight:"1"}],"8xl":["6rem",{lineHeight:"1"}],"9xl":["8rem",{lineHeight:"1"}]},fontWeight:{thin:"100",extralight:"200",light:"300",normal:"400",medium:"500",semibold:"600",bold:"700",extrabold:"800",black:"900"},gap:({theme:e})=>e("spacing"),gradientColorStops:({theme:e})=>e("colors"),gradientColorStopPositions:{"0%":"0%","5%":"5%","10%":"10%","15%":"15%","20%":"20%","25%":"25%","30%":"30%","35%":"35%","40%":"40%","45%":"45%","50%":"50%","55%":"55%","60%":"60%","65%":"65%","70%":"70%","75%":"75%","80%":"80%","85%":"85%","90%":"90%","95%":"95%","100%":"100%",...o},grayscale:{0:"0",DEFAULT:"100%",...o},gridAutoColumns:{auto:"auto",min:"min-content",max:"max-content",fr:"minmax(0, 1fr)"},gridAutoRows:{auto:"auto",min:"min-content",max:"max-content",fr:"minmax(0, 1fr)"},gridColumn:{auto:"auto","span-1":"span 1 / span 1","span-2":"span 2 / span 2","span-3":"span 3 / span 3","span-4":"span 4 / span 4","span-5":"span 5 / span 5","span-6":"span 6 / span 6","span-7":"span 7 / span 7","span-8":"span 8 / span 8","span-9":"span 9 / span 9","span-10":"span 10 / span 10","span-11":"span 11 / span 11","span-12":"span 12 / span 12","span-full":"1 / -1"},gridColumnEnd:{auto:"auto",1:"1",2:"2",3:"3",4:"4",5:"5",6:"6",7:"7",8:"8",9:"9",10:"10",11:"11",12:"12",13:"13",...r},gridColumnStart:{auto:"auto",1:"1",2:"2",3:"3",4:"4",5:"5",6:"6",7:"7",8:"8",9:"9",10:"10",11:"11",12:"12",13:"13",...r},gridRow:{auto:"auto","span-1":"span 1 / span 1","span-2":"span 2 / span 2","span-3":"span 3 / span 3","span-4":"span 4 / span 4","span-5":"span 5 / span 5","span-6":"span 6 / span 6","span-7":"span 7 / span 7","span-8":"span 8 / span 8","span-9":"span 9 / span 9","span-10":"span 10 / span 10","span-11":"span 11 / span 11","span-12":"span 12 / span 12","span-full":"1 / -1"},gridRowEnd:{auto:"auto",1:"1",2:"2",3:"3",4:"4",5:"5",6:"6",7:"7",8:"8",9:"9",10:"10",11:"11",12:"12",13:"13",...r},gridRowStart:{auto:"auto",1:"1",2:"2",3:"3",4:"4",5:"5",6:"6",7:"7",8:"8",9:"9",10:"10",11:"11",12:"12",13:"13",...r},gridTemplateColumns:{none:"none",subgrid:"subgrid",1:"repeat(1, minmax(0, 1fr))",2:"repeat(2, minmax(0, 1fr))",3:"repeat(3, minmax(0, 1fr))",4:"repeat(4, minmax(0, 1fr))",5:"repeat(5, minmax(0, 1fr))",6:"repeat(6, minmax(0, 1fr))",7:"repeat(7, minmax(0, 1fr))",8:"repeat(8, minmax(0, 1fr))",9:"repeat(9, minmax(0, 1fr))",10:"repeat(10, minmax(0, 1fr))",11:"repeat(11, minmax(0, 1fr))",12:"repeat(12, minmax(0, 1fr))",...E},gridTemplateRows:{none:"none",subgrid:"subgrid",1:"repeat(1, minmax(0, 1fr))",2:"repeat(2, minmax(0, 1fr))",3:"repeat(3, minmax(0, 1fr))",4:"repeat(4, minmax(0, 1fr))",5:"repeat(5, minmax(0, 1fr))",6:"repeat(6, minmax(0, 1fr))",7:"repeat(7, minmax(0, 1fr))",8:"repeat(8, minmax(0, 1fr))",9:"repeat(9, minmax(0, 1fr))",10:"repeat(10, minmax(0, 1fr))",11:"repeat(11, minmax(0, 1fr))",12:"repeat(12, minmax(0, 1fr))",...E},height:({theme:e})=>({auto:"auto","1/2":"50%","1/3":"33.333333%","2/3":"66.666667%","1/4":"25%","2/4":"50%","3/4":"75%","1/5":"20%","2/5":"40%","3/5":"60%","4/5":"80%","1/6":"16.666667%","2/6":"33.333333%","3/6":"50%","4/6":"66.666667%","5/6":"83.333333%",full:"100%",screen:"100vh",svh:"100svh",lvh:"100lvh",dvh:"100dvh",min:"min-content",max:"max-content",fit:"fit-content",...e("spacing")}),hueRotate:{0:"0deg",15:"15deg",30:"30deg",60:"60deg",90:"90deg",180:"180deg",...p},inset:({theme:e})=>({auto:"auto","1/2":"50%","1/3":"33.333333%","2/3":"66.666667%","1/4":"25%","2/4":"50%","3/4":"75%",full:"100%",...e("spacing")}),invert:{0:"0",DEFAULT:"100%",...o},keyframes:{spin:{to:{transform:"rotate(360deg)"}},ping:{"75%, 100%":{transform:"scale(2)",opacity:"0"}},pulse:{"50%":{opacity:".5"}},bounce:{"0%, 100%":{transform:"translateY(-25%)",animationTimingFunction:"cubic-bezier(0.8,0,1,1)"},"50%":{transform:"none",animationTimingFunction:"cubic-bezier(0,0,0.2,1)"}}},letterSpacing:{tighter:"-0.05em",tight:"-0.025em",normal:"0em",wide:"0.025em",wider:"0.05em",widest:"0.1em"},lineHeight:{none:"1",tight:"1.25",snug:"1.375",normal:"1.5",relaxed:"1.625",loose:"2",3:".75rem",4:"1rem",5:"1.25rem",6:"1.5rem",7:"1.75rem",8:"2rem",9:"2.25rem",10:"2.5rem"},listStyleType:{none:"none",disc:"disc",decimal:"decimal"},listStyleImage:{none:"none"},margin:({theme:e})=>({auto:"auto",...e("spacing")}),lineClamp:{1:"1",2:"2",3:"3",4:"4",5:"5",6:"6",...r},maxHeight:({theme:e})=>({none:"none",full:"100%",screen:"100vh",svh:"100svh",lvh:"100lvh",dvh:"100dvh",min:"min-content",max:"max-content",fit:"fit-content",...e("spacing")}),maxWidth:({theme:e})=>({none:"none",xs:"20rem",sm:"24rem",md:"28rem",lg:"32rem",xl:"36rem","2xl":"42rem","3xl":"48rem","4xl":"56rem","5xl":"64rem","6xl":"72rem","7xl":"80rem",full:"100%",min:"min-content",max:"max-content",fit:"fit-content",prose:"65ch",...e("spacing")}),minHeight:({theme:e})=>({full:"100%",screen:"100vh",svh:"100svh",lvh:"100lvh",dvh:"100dvh",min:"min-content",max:"max-content",fit:"fit-content",...e("spacing")}),minWidth:({theme:e})=>({full:"100%",min:"min-content",max:"max-content",fit:"fit-content",...e("spacing")}),objectPosition:{bottom:"bottom",center:"center",left:"left","left-bottom":"left bottom","left-top":"left top",right:"right","right-bottom":"right bottom","right-top":"right top",top:"top"},opacity:{0:"0",5:"0.05",10:"0.1",15:"0.15",20:"0.2",25:"0.25",30:"0.3",35:"0.35",40:"0.4",45:"0.45",50:"0.5",55:"0.55",60:"0.6",65:"0.65",70:"0.7",75:"0.75",80:"0.8",85:"0.85",90:"0.9",95:"0.95",100:"1",...o},order:{first:"-9999",last:"9999",none:"0",1:"1",2:"2",3:"3",4:"4",5:"5",6:"6",7:"7",8:"8",9:"9",10:"10",11:"11",12:"12",...r},outlineColor:({theme:e})=>e("colors"),outlineOffset:{0:"0px",1:"1px",2:"2px",4:"4px",8:"8px",...a},outlineWidth:{0:"0px",1:"1px",2:"2px",4:"4px",8:"8px",...a},padding:({theme:e})=>e("spacing"),placeholderColor:({theme:e})=>e("colors"),placeholderOpacity:({theme:e})=>e("opacity"),ringColor:({theme:e})=>({DEFAULT:"currentcolor",...e("colors")}),ringOffsetColor:({theme:e})=>e("colors"),ringOffsetWidth:{0:"0px",1:"1px",2:"2px",4:"4px",8:"8px",...a},ringOpacity:({theme:e})=>({DEFAULT:"0.5",...e("opacity")}),ringWidth:{DEFAULT:"3px",0:"0px",1:"1px",2:"2px",4:"4px",8:"8px",...a},rotate:{0:"0deg",1:"1deg",2:"2deg",3:"3deg",6:"6deg",12:"12deg",45:"45deg",90:"90deg",180:"180deg",...p},saturate:{0:"0",50:".5",100:"1",150:"1.5",200:"2",...o},scale:{0:"0",50:".5",75:".75",90:".9",95:".95",100:"1",105:"1.05",110:"1.1",125:"1.25",150:"1.5",...o},screens:{sm:"40rem",md:"48rem",lg:"64rem",xl:"80rem","2xl":"96rem"},scrollMargin:({theme:e})=>e("spacing"),scrollPadding:({theme:e})=>e("spacing"),sepia:{0:"0",DEFAULT:"100%",...o},skew:{0:"0deg",1:"1deg",2:"2deg",3:"3deg",6:"6deg",12:"12deg",...p},space:({theme:e})=>e("spacing"),spacing:{px:"1px",0:"0px",.5:"0.125rem",1:"0.25rem",1.5:"0.375rem",2:"0.5rem",2.5:"0.625rem",3:"0.75rem",3.5:"0.875rem",4:"1rem",5:"1.25rem",6:"1.5rem",7:"1.75rem",8:"2rem",9:"2.25rem",10:"2.5rem",11:"2.75rem",12:"3rem",14:"3.5rem",16:"4rem",20:"5rem",24:"6rem",28:"7rem",32:"8rem",36:"9rem",40:"10rem",44:"11rem",48:"12rem",52:"13rem",56:"14rem",60:"15rem",64:"16rem",72:"18rem",80:"20rem",96:"24rem"},stroke:({theme:e})=>({none:"none",...e("colors")}),strokeWidth:{0:"0",1:"1",2:"2",...r},supports:{},data:{},textColor:({theme:e})=>e("colors"),textDecorationColor:({theme:e})=>e("colors"),textDecorationThickness:{auto:"auto","from-font":"from-font",0:"0px",1:"1px",2:"2px",4:"4px",8:"8px",...a},textIndent:({theme:e})=>e("spacing"),textOpacity:({theme:e})=>e("opacity"),textUnderlineOffset:{auto:"auto",0:"0px",1:"1px",2:"2px",4:"4px",8:"8px",...a},transformOrigin:{center:"center",top:"top","top-right":"top right",right:"right","bottom-right":"bottom right",bottom:"bottom","bottom-left":"bottom left",left:"left","top-left":"top left"},transitionDelay:{0:"0s",75:"75ms",100:"100ms",150:"150ms",200:"200ms",300:"300ms",500:"500ms",700:"700ms",1e3:"1000ms",...b},transitionDuration:{DEFAULT:"150ms",0:"0s",75:"75ms",100:"100ms",150:"150ms",200:"200ms",300:"300ms",500:"500ms",700:"700ms",1e3:"1000ms",...b},transitionProperty:{none:"none",all:"all",DEFAULT:"color, background-color, border-color, outline-color, text-decoration-color, fill, stroke, opacity, box-shadow, transform, filter, backdrop-filter",colors:"color, background-color, border-color, outline-color, text-decoration-color, fill, stroke",opacity:"opacity",shadow:"box-shadow",transform:"transform"},transitionTimingFunction:{DEFAULT:"cubic-bezier(0.4, 0, 0.2, 1)",linear:"linear",in:"cubic-bezier(0.4, 0, 1, 1)",out:"cubic-bezier(0, 0, 0.2, 1)","in-out":"cubic-bezier(0.4, 0, 0.2, 1)"},translate:({theme:e})=>({"1/2":"50%","1/3":"33.333333%","2/3":"66.666667%","1/4":"25%","2/4":"50%","3/4":"75%",full:"100%",...e("spacing")}),size:({theme:e})=>({auto:"auto","1/2":"50%","1/3":"33.333333%","2/3":"66.666667%","1/4":"25%","2/4":"50%","3/4":"75%","1/5":"20%","2/5":"40%","3/5":"60%","4/5":"80%","1/6":"16.666667%","2/6":"33.333333%","3/6":"50%","4/6":"66.666667%","5/6":"83.333333%","1/12":"8.333333%","2/12":"16.666667%","3/12":"25%","4/12":"33.333333%","5/12":"41.666667%","6/12":"50%","7/12":"58.333333%","8/12":"66.666667%","9/12":"75%","10/12":"83.333333%","11/12":"91.666667%",full:"100%",min:"min-content",max:"max-content",fit:"fit-content",...e("spacing")}),width:({theme:e})=>({auto:"auto","1/2":"50%","1/3":"33.333333%","2/3":"66.666667%","1/4":"25%","2/4":"50%","3/4":"75%","1/5":"20%","2/5":"40%","3/5":"60%","4/5":"80%","1/6":"16.666667%","2/6":"33.333333%","3/6":"50%","4/6":"66.666667%","5/6":"83.333333%","1/12":"8.333333%","2/12":"16.666667%","3/12":"25%","4/12":"33.333333%","5/12":"41.666667%","6/12":"50%","7/12":"58.333333%","8/12":"66.666667%","9/12":"75%","10/12":"83.333333%","11/12":"91.666667%",full:"100%",screen:"100vw",svw:"100svw",lvw:"100lvw",dvw:"100dvw",min:"min-content",max:"max-content",fit:"fit-content",...e("spacing")}),willChange:{auto:"auto",scroll:"scroll-position",contents:"contents",transform:"transform"},zIndex:{auto:"auto",0:"0",10:"10",20:"20",30:"30",40:"40",50:"50",...r}};module.exports=y; diff --git a/dg-ui/node_modules/tailwindcss/dist/default-theme.mjs b/dg-ui/node_modules/tailwindcss/dist/default-theme.mjs new file mode 100644 index 0000000..611c0b5 --- /dev/null +++ b/dg-ui/node_modules/tailwindcss/dist/default-theme.mjs @@ -0,0 +1 @@ +import{j as a}from"./chunk-JYLR5UAN.mjs";import"./chunk-DCG7AFIE.mjs";export{a as default}; diff --git a/dg-ui/node_modules/tailwindcss/dist/flatten-color-palette.d.mts b/dg-ui/node_modules/tailwindcss/dist/flatten-color-palette.d.mts new file mode 100644 index 0000000..1151604 --- /dev/null +++ b/dg-ui/node_modules/tailwindcss/dist/flatten-color-palette.d.mts @@ -0,0 +1,6 @@ +type Colors = { + [key: string | number]: string | Colors; +}; +declare function flattenColorPalette(colors: Colors): Record; + +export { flattenColorPalette as default }; diff --git a/dg-ui/node_modules/tailwindcss/dist/flatten-color-palette.d.ts b/dg-ui/node_modules/tailwindcss/dist/flatten-color-palette.d.ts new file mode 100644 index 0000000..1151604 --- /dev/null +++ b/dg-ui/node_modules/tailwindcss/dist/flatten-color-palette.d.ts @@ -0,0 +1,6 @@ +type Colors = { + [key: string | number]: string | Colors; +}; +declare function flattenColorPalette(colors: Colors): Record; + +export { flattenColorPalette as default }; diff --git a/dg-ui/node_modules/tailwindcss/dist/flatten-color-palette.js b/dg-ui/node_modules/tailwindcss/dist/flatten-color-palette.js new file mode 100644 index 0000000..09639d2 --- /dev/null +++ b/dg-ui/node_modules/tailwindcss/dist/flatten-color-palette.js @@ -0,0 +1 @@ +"use strict";function n(r){let i={};for(let[e,t]of Object.entries(r??{}))if(e!=="__CSS_VALUES__")if(typeof t=="object"&&t!==null)for(let[s,l]of Object.entries(n(t)))i[`${e}${s==="DEFAULT"?"":`-${s}`}`]=l;else i[e]=t;if("__CSS_VALUES__"in r)for(let[e,t]of Object.entries(r.__CSS_VALUES__))(Number(t)&4)===0&&(i[e]=r[e]);return i}module.exports=n; diff --git a/dg-ui/node_modules/tailwindcss/dist/flatten-color-palette.mjs b/dg-ui/node_modules/tailwindcss/dist/flatten-color-palette.mjs new file mode 100644 index 0000000..a47d4af --- /dev/null +++ b/dg-ui/node_modules/tailwindcss/dist/flatten-color-palette.mjs @@ -0,0 +1 @@ +import"./chunk-3IIMCCN4.mjs";function i(r){let n={};for(let[e,t]of Object.entries(r??{}))if(e!=="__CSS_VALUES__")if(typeof t=="object"&&t!==null)for(let[o,f]of Object.entries(i(t)))n[`${e}${o==="DEFAULT"?"":`-${o}`}`]=f;else n[e]=t;if("__CSS_VALUES__"in r)for(let[e,t]of Object.entries(r.__CSS_VALUES__))(Number(t)&4)===0&&(n[e]=r[e]);return n}export{i as default}; diff --git a/dg-ui/node_modules/tailwindcss/dist/lib.d.mts b/dg-ui/node_modules/tailwindcss/dist/lib.d.mts new file mode 100644 index 0000000..fdc3016 --- /dev/null +++ b/dg-ui/node_modules/tailwindcss/dist/lib.d.mts @@ -0,0 +1,379 @@ +import { S as SourceLocation, U as UserConfig, P as Plugin } from './types-DWdTiksJ.mjs'; +import { V as Variant, C as Candidate } from './resolve-config-QUZ9b-Gn.mjs'; +import './colors.mjs'; + +declare const enum ThemeOptions { + NONE = 0, + INLINE = 1, + REFERENCE = 2, + DEFAULT = 4, + STATIC = 8, + USED = 16 +} +declare class Theme { + #private; + private values; + private keyframes; + prefix: string | null; + constructor(values?: Map, keyframes?: Set); + get size(): number; + add(key: string, value: string, options?: ThemeOptions, src?: Declaration['src']): void; + keysInNamespaces(themeKeys: Iterable): string[]; + get(themeKeys: ThemeKey[]): string | null; + hasDefault(key: string): boolean; + getOptions(key: string): ThemeOptions; + entries(): MapIterator<[string, { + value: string; + options: ThemeOptions; + src: Declaration["src"]; + }]> | [string, { + value: string; + options: ThemeOptions; + src: Declaration["src"]; + }][]; + prefixKey(key: string): string; + clearNamespace(namespace: string, clearOptions: ThemeOptions): void; + markUsedVariable(themeKey: string): boolean; + resolve(candidateValue: string | null, themeKeys: ThemeKey[], options?: ThemeOptions): string | null; + resolveValue(candidateValue: string | null, themeKeys: ThemeKey[]): string | null; + resolveWith(candidateValue: string, themeKeys: ThemeKey[], nestedKeys?: `--${string}`[]): [string, Record] | null; + namespace(namespace: string): Map; + addKeyframes(value: AtRule): void; + getKeyframes(): AtRule[]; +} +type ThemeKey = `--${string}`; + +type VariantFn = (rule: Rule, variant: Extract) => null | void; +type CompareFn = (a: Variant, z: Variant) => number; +declare const enum Compounds { + Never = 0, + AtRules = 1, + StyleRules = 2 +} +declare class Variants { + compareFns: Map; + variants: Map; + compoundsWith: Compounds; + compounds: Compounds; + }>; + private completions; + /** + * Registering a group of variants should result in the same sort number for + * all the variants. This is to ensure that the variants are applied in the + * correct order. + */ + private groupOrder; + /** + * Keep track of the last sort order instead of using the size of the map to + * avoid unnecessarily skipping order numbers. + */ + private lastOrder; + static(name: string, applyFn: VariantFn<'static'>, { compounds, order }?: { + compounds?: Compounds; + order?: number; + }): void; + fromAst(name: string, ast: AstNode[], designSystem: DesignSystem): void; + functional(name: string, applyFn: VariantFn<'functional'>, { compounds, order }?: { + compounds?: Compounds; + order?: number; + }): void; + compound(name: string, compoundsWith: Compounds, applyFn: VariantFn<'compound'>, { compounds, order }?: { + compounds?: Compounds; + order?: number; + }): void; + group(fn: () => void, compareFn?: CompareFn): void; + has(name: string): boolean; + get(name: string): { + kind: Variant["kind"]; + order: number; + applyFn: VariantFn; + compoundsWith: Compounds; + compounds: Compounds; + } | undefined; + kind(name: string): "static" | "arbitrary" | "functional" | "compound"; + compoundsWith(parent: string, child: string | Variant): boolean; + suggest(name: string, suggestions: () => string[]): void; + getCompletions(name: string): string[]; + compare(a: Variant | null, z: Variant | null): number; + keys(): MapIterator; + entries(): MapIterator<[string, { + kind: Variant["kind"]; + order: number; + applyFn: VariantFn; + compoundsWith: Compounds; + compounds: Compounds; + }]>; + private set; + private nextOrder; +} + +declare function compileAstNodes(candidate: Candidate, designSystem: DesignSystem, flags: CompileAstFlags): { + node: AstNode; + propertySort: { + order: number[]; + count: number; + }; +}[]; + +interface CanonicalizeOptions { + /** + * The root font size in pixels. If provided, `rem` values will be normalized + * to `px` values. + * + * E.g.: `mt-[16px]` with `rem: 16` will become `mt-4` (assuming `--spacing: 0.25rem`). + */ + rem?: number; + /** + * Whether to collapse multiple utilities into a single utility if possible. + * + * E.g.: `mt-2 mr-2 mb-2 ml-2` → `m-2` + */ + collapse?: boolean; + /** + * Whether to convert between logical and physical properties when collapsing + * utilities. + * + * E.g.: `mr-2 ml-2` → `mx-2` + */ + logicalToPhysical?: boolean; +} + +interface ClassMetadata { + modifiers: string[]; +} +type ClassEntry = [string, ClassMetadata]; +interface SelectorOptions { + modifier?: string; + value?: string; +} +interface VariantEntry { + name: string; + isArbitrary: boolean; + values: string[]; + hasDash: boolean; + selectors: (options: SelectorOptions) => string[]; +} + +type CompileFn = (value: Extract) => AstNode[] | undefined | null; +interface SuggestionGroup { + supportsNegative?: boolean; + values: (string | null)[]; + modifiers: string[]; +} +type UtilityOptions = { + types: string[]; +}; +type Utility = { + kind: 'static' | 'functional'; + compileFn: CompileFn; + options?: UtilityOptions; +}; +declare class Utilities { + private utilities; + private completions; + static(name: string, compileFn: CompileFn<'static'>): void; + functional(name: string, compileFn: CompileFn<'functional'>, options?: UtilityOptions): void; + has(name: string, kind: 'static' | 'functional'): boolean; + get(name: string): Utility[]; + getCompletions(name: string): SuggestionGroup[]; + suggest(name: string, groups: () => SuggestionGroup[]): void; + keys(kind: 'static' | 'functional'): string[]; +} + +declare const enum CompileAstFlags { + None = 0, + RespectImportant = 1 +} +type DesignSystem = { + theme: Theme; + utilities: Utilities; + variants: Variants; + invalidCandidates: Set; + important: boolean; + getClassOrder(classes: string[]): [string, bigint | null][]; + getClassList(): ClassEntry[]; + getVariants(): VariantEntry[]; + parseCandidate(candidate: string): Readonly[]; + parseVariant(variant: string): Readonly | null; + compileAstNodes(candidate: Candidate, flags?: CompileAstFlags): ReturnType; + printCandidate(candidate: Candidate): string; + printVariant(variant: Variant): string; + getVariantOrder(): Map; + resolveThemeValue(path: string, forceInline?: boolean): string | undefined; + trackUsedVariables(raw: string): void; + canonicalizeCandidates(candidates: string[], options?: CanonicalizeOptions): string[]; + candidatesToCss(classes: string[]): (string | null)[]; + candidatesToAst(classes: string[]): AstNode[][]; + storage: Record; +}; + +type StyleRule = { + kind: 'rule'; + selector: string; + nodes: AstNode[]; + src?: SourceLocation; + dst?: SourceLocation; +}; +type AtRule = { + kind: 'at-rule'; + name: string; + params: string; + nodes: AstNode[]; + src?: SourceLocation; + dst?: SourceLocation; +}; +type Declaration = { + kind: 'declaration'; + property: string; + value: string | undefined; + important: boolean; + src?: SourceLocation; + dst?: SourceLocation; +}; +type Comment = { + kind: 'comment'; + value: string; + src?: SourceLocation; + dst?: SourceLocation; +}; +type Context = { + kind: 'context'; + context: Record; + nodes: AstNode[]; + src?: undefined; + dst?: undefined; +}; +type AtRoot = { + kind: 'at-root'; + nodes: AstNode[]; + src?: undefined; + dst?: undefined; +}; +type Rule = StyleRule | AtRule; +type AstNode = StyleRule | AtRule | Declaration | Comment | Context | AtRoot; + +/** + * Line offset tables are the key to generating our source maps. They allow us + * to store indexes with our AST nodes and later convert them into positions as + * when given the source that the indexes refer to. + */ +/** + * A position in source code + * + * https://tc39.es/ecma426/#sec-position-record-type + */ +interface Position { + /** The line number, one-based */ + line: number; + /** The column/character number, one-based */ + column: number; +} + +interface OriginalPosition extends Position { + source: DecodedSource; +} +/** + * A "decoded" sourcemap + * + * @see https://tc39.es/ecma426/#decoded-source-map-record + */ +interface DecodedSourceMap { + file: string | null; + sources: DecodedSource[]; + mappings: DecodedMapping[]; +} +/** + * A "decoded" source + * + * @see https://tc39.es/ecma426/#decoded-source-record + */ +interface DecodedSource { + url: string | null; + content: string | null; + ignore: boolean; +} +/** + * A "decoded" mapping + * + * @see https://tc39.es/ecma426/#decoded-mapping-record + */ +interface DecodedMapping { + originalPosition: OriginalPosition | null; + generatedPosition: Position; + name: string | null; +} + +interface Config extends UserConfig { +} +declare const enum Polyfills { + None = 0, + AtProperty = 1, + ColorMix = 2, + All = 3 +} +type CompileOptions = { + base?: string; + from?: string; + polyfills?: Polyfills; + loadModule?: (id: string, base: string, resourceHint: 'plugin' | 'config') => Promise<{ + path: string; + base: string; + module: Plugin | Config; + }>; + loadStylesheet?: (id: string, base: string) => Promise<{ + path: string; + base: string; + content: string; + }>; +}; +type Root = null | 'none' | { + base: string; + pattern: string; +}; +declare const enum Features { + None = 0, + AtApply = 1, + AtImport = 2, + JsPluginCompat = 4, + ThemeFunction = 8, + Utilities = 16, + Variants = 32, + AtTheme = 64 +} +declare function compileAst(input: AstNode[], opts?: CompileOptions): Promise<{ + sources: { + base: string; + pattern: string; + negated: boolean; + }[]; + root: Root; + features: Features; + build(candidates: string[]): AstNode[]; +}>; + +declare function compile(css: string, opts?: CompileOptions): Promise<{ + sources: { + base: string; + pattern: string; + negated: boolean; + }[]; + root: Root; + features: Features; + build(candidates: string[]): string; + buildSourceMap(): DecodedSourceMap; +}>; +declare function __unstable__loadDesignSystem(css: string, opts?: CompileOptions): Promise; +declare function postcssPluginWarning(): void; + +export { type Config, type DecodedSourceMap, Features, Polyfills, __unstable__loadDesignSystem, compile, compileAst, postcssPluginWarning as default }; diff --git a/dg-ui/node_modules/tailwindcss/dist/lib.d.ts b/dg-ui/node_modules/tailwindcss/dist/lib.d.ts new file mode 100644 index 0000000..411ce06 --- /dev/null +++ b/dg-ui/node_modules/tailwindcss/dist/lib.d.ts @@ -0,0 +1,3 @@ +declare function postcssPluginWarning(): void; + +export { postcssPluginWarning as default }; diff --git a/dg-ui/node_modules/tailwindcss/dist/lib.js b/dg-ui/node_modules/tailwindcss/dist/lib.js new file mode 100644 index 0000000..984818e --- /dev/null +++ b/dg-ui/node_modules/tailwindcss/dist/lib.js @@ -0,0 +1,38 @@ +"use strict";var Yn=Object.defineProperty;var qn=(e,r)=>{for(var i in r)Yn(e,i,{get:r[i],enumerable:!0})};var Zt={};qn(Zt,{Features:()=>Ue,Polyfills:()=>Et,__unstable__loadDesignSystem:()=>Ya,compile:()=>Ba,compileAst:()=>Bn,default:()=>ht});var Ur="4.3.5";function Gn(e){return{kind:"combinator",value:e}}function Jt(e){return{kind:"complex",nodes:e}}function Lr(e){return{kind:"compound",nodes:e}}function Zn(e,r){return{kind:"function",value:e,nodes:r}}function Qn(e){return{kind:"list",nodes:e}}function xe(e){return{kind:"selector",value:e}}function Kr(e){return{kind:"value",value:e}}function tt(e){return e.kind==="selector"&&e.value.charCodeAt(0)===nr}var Jn=new Set([":before",":after",":first-line",":first-letter"]);function vt(e){return e.kind!=="selector"&&e.kind!=="function"?!1:e.value.startsWith("::")||Jn.has(e.value.toLowerCase())}function kt(e){if(e.kind!=="selector")return!1;switch(e.value.charCodeAt(0)){case nr:case Gr:case qr:case Hr:case rr:case ir:return!1;default:return!0}}function se(e,r=!1){let i="";for(let t of e)switch(t.kind){case"selector":case"value":{i+=t.value;break}case"combinator":{r||t.value===" "?i+=t.value:i+=` ${t.value} `;break}case"function":{i+=`${t.value}(${se(t.nodes,r)})`;break}case"complex":case"compound":{i+=se(t.nodes,r);break}case"list":{i+=t.nodes.map(n=>se([n],r)).join(r?",":", ");break}}return i}var zr=92,Xn=93,Mr=41,rr=58,jr=44,el=34,qr=46,Fr=62,Xt=10,Hr=35,ir=91,Wr=40,Br=43,tl=39,er=32,tr=9,Yr=126,Gr=38,nr=42;function pe(e){e=e.replaceAll(`\r +`,` +`);let r=[],i=r,t=!1,n=[],o=null,l="",f;function u(d=i){return d.length===1?d[0]:t?Jt(d):Lr(d)}function c(d){let m=i[i.length-1];m?.kind==="compound"?m.nodes.push(d):m&&m.kind!=="list"&&m.kind!=="combinator"?i[i.length-1]=Lr([m,d]):i.push(d)}for(let d=0;d0&&(c(xe(l)),l="");d+10&&(c(xe(l)),l="");let p=d,h=d+1;for(;h=e.length||e.charCodeAt(h)===jr))break;i.push(Gn(k===""?" ":k)),t=!0;break}case Wr:{let p=Zn(l,[]);if(l="",p.value!==":not"&&p.value!==":where"&&p.value!==":has"&&p.value!==":is"&&p.value!==":-moz-any"&&p.value!==":-webkit-any"){let h=d+1,k=0;for(let A=d+1;A0&&(c(xe(l)),l=""),o?o.nodes.push(u()):t&&i.splice(0,i.length,Jt(i.splice(0)));let p=n.pop();i=p?.target??r,o=p?.currentList??null,t=p?.containsCombinator??!1;break}case qr:case rr:case Hr:{if(m===rr&&l===":"){l+=e[d];break}l.length>0&&c(xe(l)),l=e[d];break}case ir:{l.length>0&&(c(xe(l)),l="");let p=d,h=0;for(let k=d+1;k0&&(c(xe(l)),l=""),c(xe(e[d]));break}case zr:{l+=e[d]+e[d+1],d+=1;break}default:l+=e[d]}}return l.length>0&&c(xe(l)),o?o.nodes.push(u()):t&&i.splice(0,i.length,Jt(i.splice(0))),r}function bt(e){let r=[0];for(let n=0;n0;){let u=(l|0)>>1,c=o+u;r[c]<=n?(o=c+1,l=l-u-1):l=u}o-=1;let f=n-r[o];return{line:o+1,column:f}}function t({line:n,column:o}){n-=1,n=Math.min(Math.max(n,0),r.length-1);let l=r[n],f=r[n+1]??l;return Math.min(Math.max(l+o,0),f)}return{find:i,findOffset:t}}var Ct=92,wt=47,yt=42,Zr=34,Qr=39,rl=58,At=59,de=10,rt=13,je=32,Fe=9,Jr=123,or=125,ur=40,Xr=41,il=91,nl=93,Oe=45,ar=64,ei=33,ll=60,ol=62,ve=class e extends Error{loc;constructor(r,i){if(i){let t=i[0],n=bt(t.code).find(i[1]);r=`${t.file}:${n.line}:${n.column+1}: ${r}`}super(r),this.name="CssSyntaxError",this.loc=i,Error.captureStackTrace&&Error.captureStackTrace(this,e)}};function _e(e,r){let i=r?.from?{file:r.from,code:e}:null;e[0]==="\uFEFF"&&(e=" "+e.slice(1));let t=[],n=[],o=[],l=null,f=null,u="",c="",d=0,m;for(let p=0;p0&&e[y]===k[k.length-1]&&(k=k.slice(0,-1));m!==je&&m!==Fe&&m!==de&&m!==rt&&(A=y+1-w)}u.length===0&&(u=e.slice(w),p=e.length);let C=xt(u,b,A);if(!C)throw new ve("Invalid custom property, expected a value",i?[i,w,p]:null);i&&(C.src=[i,w,p],C.dst=[i,w,p]),l?l.nodes.push(C):t.push(C),u=""}else if(h===At&&u.charCodeAt(0)===ar)f=it(u),i&&(f.src=[i,d,p],f.dst=[i,d,p]),l?l.nodes.push(f):t.push(f),u="",f=null;else if(h===At&&c[c.length-1]!==")"){let k=xt(u);if(!k){if(u.length===0)continue;throw new ve(`Invalid declaration: \`${u.trim()}\``,i?[i,d,p]:null)}i&&(k.src=[i,d,p],k.dst=[i,d,p]),l?l.nodes.push(k):t.push(k),u=""}else if(h===Jr&&c[c.length-1]!==")")c+="}",f=J(u.trim()),i&&(f.src=[i,d,p],f.dst=[i,d,p]),l&&l.nodes.push(f),o.push(l),l=f,u="",f=null;else if(h===or&&c[c.length-1]!==")"){if(c==="")throw new ve("Missing opening {",i?[i,p,p]:null);if(c=c.slice(0,-1),u.length>0)if(u.charCodeAt(0)===ar)f=it(u),i&&(f.src=[i,d,p],f.dst=[i,d,p]),l?l.nodes.push(f):t.push(f),u="",f=null;else{let w=u.indexOf(":");if(l){let b=xt(u,w);if(!b)throw new ve(`Invalid declaration: \`${u.trim()}\``,i?[i,d,p]:null);i&&(b.src=[i,d,p],b.dst=[i,d,p]),l.nodes.push(b)}}let k=o.pop()??null;k===null&&l&&t.push(l),l=k,u="",f=null}else if(h===ur)c+=")",u+="(";else if(h===Xr){if(c[c.length-1]!==")")throw new ve("Missing opening (",i?[i,p,p]:null);c=c.slice(0,-1),u+=")"}else{if(u.length===0&&(h===je||h===de||h===Fe))continue;u===""&&(d=p),u+=String.fromCharCode(h)}}}if(u.charCodeAt(0)===ar){let p=it(u);i&&(p.src=[i,d,e.length],p.dst=[i,d,e.length]),t.push(p)}else if(u.length>0&&c.length===0){let p=xt(u);p&&(i&&(p.src=[i,d,e.length],p.dst=[i,d,e.length]),l?l.nodes.push(p):t.push(p))}if(c.length>0&&l){if(l.kind==="rule")throw new ve(`Missing closing } at ${l.selector}`,l.src?[l.src[0],l.src[1],l.src[1]]:null);if(l.kind==="at-rule")throw new ve(`Missing closing } at ${l.name} ${l.params}`,l.src?[l.src[0],l.src[1],l.src[1]]:null)}return n.length>0?n.concat(t):t}function it(e,r=[]){let i=e,t="";for(let n=5;n=1&&n<=31||n===127||t===0&&n>=48&&n<=57||t===1&&n>=48&&n<=57&&l===45){o+="\\"+n.toString(16)+" ";continue}if(n>=128||n===45||n===95||n>=48&&n<=57||n>=65&&n<=90||n>=97&&n<=122){o+=r.charAt(t);continue}o+="\\"+r.charAt(t)}return o}function Ae(e){return e.replace(/\\(?:([\dA-Fa-f]{1,6})[\t\n\f\r ]?|([\S\s]))/g,(r,i,t)=>{if(!i)return t;let n=Number.parseInt(i,16);return n===0||n>1114111||n>=55296&&n<=57343?"\uFFFD":String.fromCodePoint(n)})}var ni=new Map([["--font",["--font-weight","--font-size"]],["--inset",["--inset-shadow","--inset-ring"]],["--text",["--text-color","--text-decoration-color","--text-decoration-thickness","--text-indent","--text-shadow","--text-underline-offset"]],["--grid-column",["--grid-column-start","--grid-column-end"]],["--grid-row",["--grid-row-start","--grid-row-end"]]]);function ii(e,r){return(ni.get(r)??[]).some(i=>e===i||e.startsWith(`${i}-`))}var Vt=class{constructor(r=new Map,i=new Set([])){this.values=r;this.keyframes=i}values;keyframes;prefix=null;get size(){return this.values.size}add(r,i,t=0,n){if(r.endsWith("-*")){if(i!=="initial")throw new Error(`Invalid theme value \`${i}\` for namespace \`${r}\``);r==="--*"?this.values.clear():this.clearNamespace(r.slice(0,-2),0)}if(t&4){let o=this.values.get(r);if(o&&!(o.options&4))return}i==="initial"?this.values.delete(r):this.values.set(r,{value:i,options:t,src:n})}keysInNamespaces(r){let i=[];for(let t of r){let n=`${t}-`;for(let o of this.values.keys())o.startsWith(n)&&o.indexOf("--",2)===-1&&(ii(o,t)||i.push(o.slice(n.length)))}return i}get(r){for(let i of r){let t=this.values.get(i);if(t)return t.value}return null}hasDefault(r){return(this.getOptions(r)&4)===4}getOptions(r){return r=Ae(this.#r(r)),this.values.get(r)?.options??0}entries(){return this.prefix?Array.from(this.values,r=>(r[0]=this.prefixKey(r[0]),r)):this.values.entries()}prefixKey(r){return this.prefix?`--${this.prefix}-${r.slice(2)}`:r}#r(r){return this.prefix?`--${r.slice(3+this.prefix.length)}`:r}clearNamespace(r,i){let t=ni.get(r)??[];e:for(let n of this.values.keys())if(n.startsWith(r)){if(i!==0&&(this.getOptions(n)&i)!==i)continue;for(let o of t)if(n.startsWith(o))continue e;this.values.delete(n)}}#e(r,i){for(let t of i){let n=r!==null?`${t}-${r}`:t;if(!this.values.has(n))if(r!==null&&r.includes(".")){if(n=`${t}-${r.replaceAll(".","_")}`,!this.values.has(n))continue}else continue;if(!ii(n,t))return n}return null}#t(r){let i=this.values.get(r);if(!i)return null;let t=null;return i.options&2&&(t=i.value),`var(${Te(this.prefixKey(r))}${t?`, ${t}`:""})`}markUsedVariable(r){let i=Ae(this.#r(r)),t=this.values.get(i);if(!t)return!1;let n=t.options&16;return t.options|=16,!n}resolve(r,i,t=0){let n=this.#e(r,i);if(!n)return null;let o=this.values.get(n);return(t|o.options)&1?o.value:this.#t(n)}resolveValue(r,i){let t=this.#e(r,i);return t?this.values.get(t).value:null}resolveWith(r,i,t=[]){let n=this.#e(r,i);if(!n)return null;let o={};for(let f of t){let u=`${n}${f}`,c=this.values.get(u);c&&(c.options&1?o[f]=c.value:o[f]=this.#t(u))}let l=this.values.get(n);return l.options&1?[l.value,o]:[this.#t(n),o]}namespace(r){let i=new Map,t=`${r}-`;for(let[n,o]of this.values)n===r?i.set(null,o.value):n.startsWith(`${t}-`)?i.set(n.slice(r.length),o.value):n.startsWith(t)&&i.set(n.slice(t.length),o.value);return i}addKeyframes(r){this.keyframes.add(r)}getKeyframes(){return Array.from(this.keyframes)}};var K=class extends Map{constructor(i){super();this.factory=i}factory;get(i){let t=super.get(i);return t===void 0&&(t=this.factory(i,this),this.set(i,t)),t}};var Tt=new Uint8Array(256);function j(e,r){let i=0,t=[],n=0,o=e.length,l=r.charCodeAt(0);for(let f=0;f0&&u===Tt[i-1]&&i--;break}}return t.push(e.slice(n)),t}function re(e){return{kind:"word",value:e}}function al(e,r){return{kind:"function",value:e,nodes:r}}function sl(e){return{kind:"separator",value:e}}function B(e){let r="";for(let i of e)switch(i.kind){case"word":case"separator":{r+=i.value;break}case"function":r+=i.value+"("+B(i.nodes)+")"}return r}var li=92,ul=41,oi=58,ai=44,cl=34,si=61,ui=62,ci=60,fi=10,fl=40,pl=39,dl=47,pi=32,di=9;function Y(e){e=e.replaceAll(`\r +`,` +`);let r=[],i=[],t=null,n="",o;for(let l=0;l0){let c=re(n);t?t.nodes.push(c):r.push(c),n=""}let u=re(e[l]);t?t.nodes.push(u):r.push(u);break}case oi:case ai:case si:case ui:case ci:case fi:case pi:case di:{if(n.length>0){let m=re(n);t?t.nodes.push(m):r.push(m),n=""}let u=l,c=l+1;for(;c0){let c=re(n);u?.nodes.push(c),n=""}i.length>0?t=i[i.length-1]:t=null;break}default:n+=String.fromCharCode(f)}}return n.length>0&&r.push(re(n)),r}var fr=(l=>(l[l.Continue=0]="Continue",l[l.Skip=1]="Skip",l[l.Stop=2]="Stop",l[l.Replace=3]="Replace",l[l.ReplaceSkip=4]="ReplaceSkip",l[l.ReplaceStop=5]="ReplaceStop",l))(fr||{}),V={Continue:{kind:0},Skip:{kind:1},Stop:{kind:2},Replace:e=>({kind:3,nodes:Array.isArray(e)?e:[e]}),ReplaceSkip:e=>({kind:4,nodes:Array.isArray(e)?e:[e]}),ReplaceStop:e=>({kind:5,nodes:Array.isArray(e)?e:[e]})};function I(e,r){typeof r=="function"?mi(e,r):mi(e,r.enter,r.exit)}function mi(e,r=()=>V.Continue,i=()=>V.Continue){let t={value:[e,0,null],prev:null},n={parent:null,depth:0,index:0,siblings:e,path(){let o=[],l=t;for(;l;){let f=l.value[2];f&&o.push(f),l=l.prev}return o.reverse(),o}};for(;t!==null;){let o=t.value,l=o[0],f=o[1],u=o[2];if(f>=l.length){t=t.prev,n.depth-=1;continue}if(n.parent=u,n.siblings=l,f>=0){n.index=f;let p=l[f],h=r(p,n)??V.Continue;switch(h.kind){case 0:{p.nodes&&p.nodes.length>0&&(n.depth+=1,t={value:[p.nodes,0,p],prev:t}),o[1]=~f;continue}case 2:return;case 1:{o[1]=~f;continue}case 3:{l.splice(f,1,...h.nodes);continue}case 5:{l.splice(f,1,...h.nodes);return}case 4:{l.splice(f,1,...h.nodes),o[1]+=h.nodes.length;continue}default:throw new Error(`Invalid \`WalkAction.${fr[h.kind]??`Unknown(${h.kind})`}\` in enter.`)}}let c=~f;n.index=c;let d=l[c],m=i(d,n)??V.Continue;switch(m.kind){case 0:o[1]=c+1;continue;case 2:return;case 3:{l.splice(c,1,...m.nodes),o[1]=c+m.nodes.length;continue}case 5:{l.splice(c,1,...m.nodes);return}case 4:{l.splice(c,1,...m.nodes),o[1]=c+m.nodes.length;continue}default:throw new Error(`Invalid \`WalkAction.${fr[m.kind]??`Unknown(${m.kind})`}\` in exit.`)}}}var ml=new K(e=>{let r=[];return I(Y(e),i=>{if(!(i.kind!=="function"||i.value!=="var"))return I(i.nodes,t=>{t.kind!=="word"||t.value[0]!=="-"||t.value[1]!=="-"||r.push(t.value)}),V.Skip}),r});function $t(e){return ml.get(e)}var gl=64,hl=124;function Q(e,r=[]){return{kind:"rule",selector:e,nodes:r}}function H(e,r="",i=[]){return{kind:"at-rule",name:e,params:r,nodes:i}}function J(e,r=[]){return e.charCodeAt(0)===gl?it(e,r):Q(e,r)}function s(e,r,i=!1){return{kind:"declaration",property:e,value:r,important:i}}function St(e){return{kind:"comment",value:e}}function ee(e,r){return{kind:"context",context:e,nodes:r}}function G(e){return{kind:"at-root",nodes:e}}function le(e){switch(e.kind){case"rule":return{kind:e.kind,selector:e.selector,nodes:e.nodes.map(le),src:e.src,dst:e.dst};case"at-rule":return{kind:e.kind,name:e.name,params:e.params,nodes:e.nodes.map(le),src:e.src,dst:e.dst};case"at-root":return{kind:e.kind,nodes:e.nodes.map(le),src:e.src,dst:e.dst};case"context":return{kind:e.kind,context:{...e.context},nodes:e.nodes.map(le),src:e.src,dst:e.dst};case"declaration":return{kind:e.kind,property:e.property,value:e.value,important:e.important,src:e.src,dst:e.dst};case"comment":return{kind:e.kind,value:e.value,src:e.src,dst:e.dst};default:throw new Error(`Unknown node kind: ${e.kind}`)}}function lt(e){return{depth:e.depth,index:e.index,siblings:e.siblings,get context(){let r={};for(let i of e.path())i.kind==="context"&&Object.assign(r,i.context);return Object.defineProperty(this,"context",{value:r}),r},get parent(){let r=this.path().pop()??null;return Object.defineProperty(this,"parent",{value:r}),r},path(){return e.path().filter(r=>r.kind!=="context")}}}function Ie(e,r,i=3){let t=[],n=new Set,o=new K(()=>new Set),l=new K(()=>new Set),f=new Set,u=new Set,c=[],d=[],m=new K(()=>new Set);function p(k,w,b={},A=0){if(k.kind==="declaration"){if(k.property==="--tw-sort"||k.value===void 0||k.value===null)return;if(b.theme&&k.property[0]==="-"&&k.property[1]==="-"){if(k.value==="initial"){k.value=void 0;return}b.keyframes||o.get(w).add(k)}if(k.value.includes("var("))if(b.theme&&k.property[0]==="-"&&k.property[1]==="-")for(let C of $t(k.value))m.get(C).add(k.property);else r.trackUsedVariables(k.value);if(k.property==="animation")for(let C of hi(k.value))u.add(C);i&2&&!b.supportsColorMix&&!b.keyframes&&k.value.includes("color-mix(")&&l.get(w).add(k),w.push(k)}else if(k.kind==="rule"){let C=[];for(let y of k.nodes)p(y,C,b,A+1);C.length>0&&w.push({...k,nodes:C})}else if(k.kind==="at-rule"&&k.name==="@property"&&A===0){if(n.has(k.params))return;if(i&1){let y=k.params,E=null,O=!1;for(let L of k.nodes)L.kind==="declaration"&&(L.property==="initial-value"?E=L.value:L.property==="inherits"&&(O=L.value==="true"));let P=s(y,E??"initial");P.src=k.src,O?c.push(P):d.push(P)}n.add(k.params);let C={...k,nodes:[]};for(let y of k.nodes)p(y,C.nodes,b,A+1);w.push(C)}else if(k.kind==="at-rule"){k.name==="@keyframes"?b={...b,keyframes:!0}:k.name==="@supports"&&k.params.includes("color-mix(")&&(b={...b,supportsColorMix:!0});let C={...k,nodes:[]};for(let y of k.nodes)p(y,C.nodes,b,A+1);k.name==="@keyframes"&&b.theme&&f.add(C),(C.nodes.length>0||C.name==="@layer"||C.name==="@charset"||C.name==="@custom-media"||C.name==="@namespace"||C.name==="@import"||C.name==="@apply")&&w.push(C)}else if(k.kind==="at-root")for(let C of k.nodes){let y=[];p(C,y,b,0);for(let E of y)t.push(E)}else if(k.kind==="context"){if(k.context.reference)return;if(k.context.source){let C={...k,nodes:[]};for(let y of k.nodes)p(y,C.nodes,{...b,...k.context},A);C.nodes.length>0&&w.push(C)}else for(let C of k.nodes)p(C,w,{...b,...k.context},A)}else k.kind==="comment"&&w.push(k)}let h=[];for(let k of e)p(k,h,{},0);e:for(let[k,w]of o)for(let b of w){if(ki(b.property,r.theme,m)){if(b.property.startsWith(r.theme.prefixKey("--animate-")))for(let y of hi(b.value))u.add(y);continue}let C=k.indexOf(b);if(k.splice(C,1),k.length===0){let y=bl(h,E=>E.kind==="rule"&&E.nodes===k);if(!y||y.length===0)continue e;y.unshift({kind:"at-root",nodes:h});do{let E=y.pop();if(!E)break;let O=y[y.length-1];if(!O||O.kind!=="at-root"&&O.kind!=="at-rule")break;let P=O.nodes.indexOf(E);if(P===-1)break;O.nodes.splice(P,1)}while(!0);continue e}}for(let k of f)if(!u.has(k.params)){let w=t.indexOf(k);t.splice(w,1)}if(h=h.concat(t),i&2)for(let[k,w]of l)for(let b of w){let A=k.indexOf(b);if(A===-1||b.value==null)continue;let C=Y(b.value),y=!1;if(I(C,P=>{if(P.kind!=="function"||P.value!=="color-mix")return;let L=B(P.nodes);if(L.includes("/*")&&(L=L.replace(/\/\*[\s\S]*?\*\//g," "),P.nodes=Y(L)),!/^in\s/i.test(L.trimStart()))return;let R=!1,W=!1;if(I(P.nodes,U=>{if(U.kind=="word"&&U.value.toLowerCase()==="currentcolor"){W=!0,y=!0;return}let z=U,F=null,Z=new Set;do{if(z.kind!=="function"||z.value!=="var")return;let a=z.nodes[0];if(!a||a.kind!=="word")return;let g=a.value;if(Z.has(g)){R=!0;return}if(Z.add(g),y=!0,F=r.theme.resolveValue(null,[a.value]),!F){R=!0;return}if(F.toLowerCase()==="currentcolor"){W=!0;return}F.startsWith("var(")?z=Y(F)[0]:z=null}while(z);return V.Replace({kind:"word",value:F})}),R||W){let U=P.nodes.findIndex(F=>F.kind==="separator"&&F.value.trim().includes(","));if(U===-1)return;let z=P.nodes.length>U?P.nodes[U+1]:null;return z?V.Replace(z):void 0}else if(y){let U=P.nodes[P.nodes.findIndex(z=>z.kind!=="separator")+2];U?.kind==="word"&&(U.value==="oklab"||U.value==="oklch"||U.value==="lab"||U.value==="lch")&&(U.value="srgb")}}),!y)continue;let E={...b,value:B(C)},O=J("@supports (color: color-mix(in lab, red, red))",[b]);O.src=b.src,k.splice(A,1,E,O)}if(i&1){let k=[];if(c.length>0){let w=J(":root, :host",c);w.src=c[0].src,k.push(w)}if(d.length>0){let w=J("*, ::before, ::after, ::backdrop",d);w.src=d[0].src,k.push(w)}if(k.length>0){let w=h.findIndex(C=>!(C.kind==="comment"||C.kind==="at-rule"&&(C.name==="@charset"||C.name==="@import"))),b=H("@layer","properties",[]);b.src=k[0].src,h.splice(w<0?h.length:w,0,b);let A=J("@layer properties",[H("@supports","((-webkit-hyphens: none) and (not (margin-trim: block))) or ((-moz-orient: inline) and (not (color:rgb(from red r g b))))",k)]);A.src=k[0].src,A.nodes[0].src=k[0].src,h.push(A)}}return vl(h)}function vl(e){let r=new K(pe),i=new Set;{let b=function(A){let C=!1;for(let y of A)y.kind==="declaration"||y.kind==="comment"||(b(y.nodes)||y.kind==="at-rule"&&y.name==="@scope")&&(i.add(y),C=!0);return C};var w=b;b(e)}let t=[],n=[],o=null,l=new Set,f=new Set,u=[],c=new Set,d=[],m=new Map,p=new WeakSet;I(e,{enter(b){switch(b.kind){case"rule":{if(o=null,t.length===0)if(b.selector.includes("&")){let A=n.some(([E])=>E==="@scope")?":where(:scope)":":scope",C=pe(b.selector),y=!1;I(C,E=>{E.kind==="selector"&&E.value==="&"&&(y=!0,E.value=A)}),y?t.push([se(C),b.src,b.dst]):t.push([b.selector,b.src,b.dst])}else t.push([b.selector,b.src,b.dst]);else{if(b.selector==="&"){c.add(b);return}let A=t[t.length-1][0],C=j(b.selector,",").map(E=>k(E,A)),y=C.filter(E=>!pr(r.get(E)));if(y.length===0){let E=[C.join(", "),b.src,b.dst];p.add(E),t.push(E);break}t.push([y.join(", "),b.src,b.dst])}if(b.nodes.some(A=>A.kind==="declaration")&&!i.has(b)){for(let A of b.nodes)h(A);return V.Skip}break}case"at-rule":{o=null;{let A=t[t.length-1];if(A&&p.has(A)){if(b.name==="@layer"&&b.nodes.length===0){let C=t;return t=[],h(b),t=C,c.add(b),V.Skip}if(b.nodes.length===0||!gi.has(b.name))return c.add(b),V.Skip}}if(b.nodes.length===0&&!kl.has(b.name))return h(b),c.add(b),V.Skip;if(gi.has(b.name)){let A=b.params;if(b.name==="@scope"){let C=d[d.length-1]==="variant",y=t.length>0;{let E=[b];for(let O of E){let P=[],L=null;for(let R of O.nodes)R.kind==="context"&&E.push(R),R.kind==="declaration"||R.kind==="comment"?(L===null&&(L=[],P.push(Q("&",L))),L.push(R)):(L=null,P.push(R));O.nodes=P}}if(A.includes("&")||!C&&y){let E=y?t[t.length-1][0]:null,O=Y(A),P=!1,L=!1,R=null;for(let W of O){if(W.kind==="word"&&W.value==="to"){P=!0;continue}if(W.kind!=="function"||W.value!=="")continue;let U=B(W.nodes);if(!P&&!C&&E!==null)W.nodes=[re(j(U,",").map(z=>k(z.trim(),E)).join(", "))],L=!0;else if(U.includes("&")){let z=P?":where(:scope)":E??":scope";W.nodes=[re(k(U,z))],!P&&y&&(L=!0)}P||(R=B(W.nodes))}if(A=B(O),L&&R!==null){let W=t[t.length-1];if(W&&p.has(W)&&pr(r.get(R)))return c.add(b),V.Skip}L&&(m.set(b,t),t=[])}}n.push([b.name,A,b.src,b.dst])}else return h(b),c.add(b),V.Skip;break}case"declaration":case"comment":{let A=t[t.length-1];if(A&&p.has(A))break;h(b);break}case"context":b.context.source&&d.push(b.context.source);break;case"at-root":break;default:break}},exit(b){if(!c.delete(b))switch(b.kind){case"rule":{o=null,t.pop();break}case"at-rule":{o=null,n.pop();let A=m.get(b);A&&(t=A,m.delete(b));break}case"context":b.context.source&&d.pop();break;case"declaration":case"comment":case"at-root":break;default:break}}});for(let b of f){let A=new Set;for(let C=b.length-1;C>=0;--C){let y=b[C];if(y.kind!=="declaration")continue;let E=`${y.property}\0${y.value}\0${y.important}`;A.has(E)?b.splice(C,1):A.add(E)}}return u;function h(b){if(o){b.kind==="declaration"&&(l.has(b.property)?f.add(o):l.add(b.property)),o.push(b);return}{if(t.length===0&&n.length===0){let E=u,O=E[E.length-1];if(O&&O.kind==="at-rule"&&b.kind==="at-rule"&&O.nodes.length===0&&b.nodes.length===0&&O.name===b.name&&O.params===b.params)return;u.push(b);return}o=[b],l.clear(),b.kind==="declaration"&&l.add(b.property);let A=null,C=u,y=0;{let E=C[C.length-1];if(E&&E.kind==="at-rule")for(let O=0;O0){let[E,O,P]=t[t.length-1];if(n.length-y<=0){let L=C[C.length-1];if(L&&L.kind==="rule"&&L.selector===E){L.nodes.push(...o),o=L.nodes,f.add(o);return}}A=J(E,o),(O||P)&&Object.assign(A,{src:O,dst:P})}for(let E=n.length-1;E>=y;--E){let[O,P,L,R]=n[E];A=H(O,P,A?[A]:o),(L||R)&&Object.assign(A,{src:L,dst:R})}A?C.push(A):C.push(...o)}}function k(b,A){if(b.includes("&")){let y=pe(b),E=!1;if(I(y,{enter(O,P){if(O.kind!=="selector"||O.value!=="&"||(E=!0,O.value=`:is(${A})`,P.parent===null))return;let L=r.get(A);if(!(L.length===1&&L[0].kind==="list")){if(P.parent.kind==="complex")if(P.index===0){O.value=A;return}else if(P.index===P.siblings.length-1){if(L[0].kind==="complex")return;O.value=A;return}else{if(L[0].kind==="complex")return;O.value=A;return}else if(P.parent.kind==="compound"){if(L[0].kind==="complex"){let R=P.path(),W=R[R.length-2];if(W&&W.kind==="complex"&&W.nodes[0]!==P.parent)return}if(P.siblings.slice(P.index+1).some(R=>tt(R)||kt(R)))return;if(P.index===0){O.value=A;return}else if(P.index===P.siblings.length-1){if(L[0].kind==="complex"||tt(L[0])||kt(L[0]))return;O.value=A;return}else{if(L[0].kind==="complex"||tt(L[0])||kt(L[0]))return;O.value=A;return}}else if(P.parent.kind==="function"){O.value=A;return}}},exit(O,P){if(P.index===0&&P.siblings.length>1&&P.parent?.kind==="compound"&&tt(O)){let L=P.siblings[1];return L.kind==="selector"&&L.value.charCodeAt(0)===hl?void 0:V.ReplaceSkip([])}}}),E)return se(y)}let C=r.get(A);return`${C.length===1&&C[0].kind==="list"?`:is(${A})`:A} ${b}`}}var gi=new Set(["@container","@layer","@media","@page","@scope","@starting-style","@supports","@view-transition"]),kl=new Set(["@container","@media","@page","@scope","@starting-style","@supports","@view-transition"]);function ce(e,r){let i=0,t={file:null,code:""};function n(l,f=0){let u="",c=" ".repeat(f);if(l.kind==="declaration"){if(u+=`${c}${l.property}: ${l.value}${l.important?" !important":""}; +`,r){i+=c.length;let d=i;i+=l.property.length,i+=2,i+=l.value?.length??0,l.important&&(i+=11);let m=i;i+=2,l.dst=[t,d,m]}}else if(l.kind==="rule"){if(u+=`${c}${l.selector} { +`,r){i+=c.length;let d=i;i+=l.selector.length,i+=1;let m=i;l.dst=[t,d,m],i+=2}for(let d of l.nodes)u+=n(d,f+1);u+=`${c}} +`,r&&(i+=c.length,i+=2)}else if(l.kind==="at-rule"){if(l.nodes.length===0){let d=`${c}${l.name} ${l.params}; +`;if(r){i+=c.length;let m=i;i+=l.name.length,i+=1,i+=l.params.length;let p=i;i+=2,l.dst=[t,m,p]}return d}if(u+=`${c}${l.name}${l.params?` ${l.params} `:" "}{ +`,r){i+=c.length;let d=i;i+=l.name.length,l.params&&(i+=1,i+=l.params.length),i+=1;let m=i;l.dst=[t,d,m],i+=2}for(let d of l.nodes)u+=n(d,f+1);u+=`${c}} +`,r&&(i+=c.length,i+=2)}else if(l.kind==="comment"){if(u+=`${c}/*${l.value}*/ +`,r){i+=c.length;let d=i;i+=2+l.value.length+2;let m=i;l.dst=[t,d,m],i+=1}}else if(l.kind==="context"||l.kind==="at-root")return"";return u}let o="";for(let l of e)o+=n(l,0);return t.code=o,o}function bl(e,r){let i=[];return I(e,(t,n)=>{if(r(t))return i=n.path(),i.push(t),V.Stop}),i}function ki(e,r,i,t=new Set){if(t.has(e)||(t.add(e),r.getOptions(e)&24))return!0;{let o=i.get(e)??[];for(let l of o)if(ki(l,r,i,t))return!0}return!1}function hi(e){return e.split(/[\s,]+/)}function pr(e){return e.length>0&&e.every(Nt)}var wl=new Set(["::after","::backdrop","::before","::checkmark","::column","::cue","::cue-region","::details-content","::file-selector-button","::first-letter","::first-line","::grammar-error","::highlight","::marker","::part","::picker","::picker-icon","::placeholder","::scroll-button","::scroll-marker","::scroll-marker-group","::search-text","::selection","::slotted","::spelling-error","::target-text","::view-transition","::view-transition-group","::view-transition-group-children","::view-transition-image-pair","::view-transition-new","::view-transition-old"]);function vi(e){if(e.kind!=="selector"&&e.kind!=="function"||!vt(e))return!1;let r=e.value.toLowerCase();return!r.startsWith("::")||r.startsWith("::-")?!0:wl.has(r)}function Nt(e){switch(e.kind){case"list":return e.nodes.every(Nt);case"complex":for(let r=0;re.includes(`${r}(`))}function Rt(e){if(!dr.some(o=>e.includes(o)))return e;let r="",i=[],t=null,n=null;for(let o=0;o=48&&l<=57||t!==null&&(l===37||l>=97&&l<=122||l>=65&&l<=90)?t=o:(n=t,t=null),l===40){r+=e[o];let f=o;for(let c=o-1;c>=0;c--){let d=e.charCodeAt(c);if(d>=48&&d<=57)f=c;else if(d>=97&&d<=122)f=c;else break}let u=e.slice(f,o);if(dr.includes(u)){i.unshift(!0);continue}else if(i[0]&&u===""){i.unshift(!0);continue}i.unshift(!1);continue}else if(l===41)r+=e[o],i.shift();else if(l===44&&i[0]){r+=", ";continue}else{if(l===32&&i[0]&&r.charCodeAt(r.length-1)===32)continue;if((l===43||l===42||l===47||l===45)&&i[0]){let f=r.trimEnd(),u=f.charCodeAt(f.length-1),c=f.charCodeAt(f.length-2),d=e.charCodeAt(o+1);if((u===101||u===69)&&c>=48&&c<=57){r+=e[o];continue}else if(u===43||u===42||u===47||u===45){r+=e[o];continue}else if(u===40||u===44){r+=e[o];continue}else e.charCodeAt(o-1)===32?r+=`${e[o]} `:u>=48&&u<=57||d>=48&&d<=57||u===41||d===40||d===43||d===42||d===47||d===45||n!==null&&n===o-1?r+=` ${e[o]} `:r+=e[o]}else r+=e[o]}}return r}function gr(e){if(e.indexOf("(")===-1)return We(e);let r=Y(e);return mr(r),e=B(r),e=Rt(e),e}function We(e,r=!1){let i="";for(let t=0;t0&&n===hr[r-1])r--;else if(n!==125)return!1;break;case 59:if(r===0)return!1;break}}return r===0}var xl=58,bi=45,wi=97,yi=122,br=/^[a-zA-Z0-9_.%-]+$/;function qe(e){switch(e.kind){case"arbitrary":return{kind:e.kind,property:e.property,value:e.value,modifier:e.modifier?{kind:e.modifier.kind,value:e.modifier.value}:null,variants:e.variants.map(Be),important:e.important,raw:e.raw};case"static":return{kind:e.kind,root:e.root,variants:e.variants.map(Be),important:e.important,raw:e.raw};case"functional":return{kind:e.kind,root:e.root,value:e.value?e.value.kind==="arbitrary"?{kind:e.value.kind,dataType:e.value.dataType,value:e.value.value}:{kind:e.value.kind,value:e.value.value,fraction:e.value.fraction}:null,modifier:e.modifier?{kind:e.modifier.kind,value:e.modifier.value}:null,variants:e.variants.map(Be),important:e.important,raw:e.raw};default:throw new Error("Unknown candidate kind")}}function Be(e){switch(e.kind){case"arbitrary":return{kind:e.kind,selector:e.selector,relative:e.relative};case"static":return{kind:e.kind,root:e.root};case"functional":return{kind:e.kind,root:e.root,value:e.value?{kind:e.value.kind,value:e.value.value}:null,modifier:e.modifier?{kind:e.modifier.kind,value:e.modifier.value}:null};case"compound":return{kind:e.kind,root:e.root,variant:Be(e.variant),modifier:e.modifier?{kind:e.modifier.kind,value:e.modifier.value}:null};default:throw new Error("Unknown variant kind")}}function*xi(e,r){let i=j(e,":");if(r.theme.prefix){if(i.length===1||i[0]!==r.theme.prefix)return null;i.shift()}let t=i.pop(),n=[];for(let m=i.length-1;m>=0;--m){let p=r.parseVariant(i[m]);if(p===null)return;n.push(p)}let o=!1;t[t.length-1]==="!"?(o=!0,t=t.slice(0,-1)):t[0]==="!"&&(o=!0,t=t.slice(1)),r.utilities.has(t,"static")&&!t.includes("[")&&(yield{kind:"static",root:t,variants:n,important:o,raw:e});let l=j(t,"/");if(l.length>2)return;let[f,u=null]=l,c=u===null?null:vr(u);if(u!==null&&c===null)return;if(f[0]==="["){if(f[f.length-1]!=="]")return;let m=f.charCodeAt(1);if(m!==bi&&!(m>=wi&&m<=yi))return;f=f.slice(1,-1);let p=f.indexOf(":");if(p===-1||p===0||p===f.length-1)return;let h=f.slice(0,p),k=Ye(f.slice(p+1));if(k===null)return;yield{kind:"arbitrary",property:h,value:k,modifier:c,variants:n,important:o,raw:e};return}let d;if(f[f.length-1]==="]"){let m=f.indexOf("-[");if(m===-1)return;let p=f.slice(0,m);if(!r.utilities.has(p,"functional"))return;let h=f.slice(m+1);d=[[p,h]]}else if(f[f.length-1]===")"){let m=f.indexOf("-(");if(m===-1)return;let p=f.slice(0,m);if(!r.utilities.has(p,"functional"))return;let h=f.slice(m+2,-1),k=j(h,":"),w=null;if(k.length===2&&(w=k[0],h=k[1]),h[0]!=="-"||h[1]!=="-"||!Pt(h))return;d=[[p,w===null?`[var(${h})]`:`[${w}:var(${h})]`]]}else d=Ci(f,m=>r.utilities.has(m,"functional"));for(let[m,p]of d){let h={kind:"functional",root:m,modifier:c,value:null,variants:n,important:o,raw:e};if(p===null){yield h;continue}{let k=p.indexOf("[");if(k!==-1){if(p[p.length-1]!=="]")return;let b=Ye(p.slice(k+1,-1));if(b===null)continue;let A=null;for(let C=0;C=wi&&y<=yi))break}if(b.length===0||b.trim().length===0||A==="")continue;h.value={kind:"arbitrary",dataType:A||null,value:b}}else{let b=u===null||h.modifier?.kind==="arbitrary"?null:`${p}/${u}`;if(!br.test(p))continue;h.value={kind:"named",value:p,fraction:b}}}yield h}}function vr(e){if(e[0]==="["&&e[e.length-1]==="]"){let r=Ye(e.slice(1,-1));return r===null||r.length===0||r.trim().length===0?null:{kind:"arbitrary",value:r}}return e[0]==="("&&e[e.length-1]===")"?(e=e.slice(1,-1),e[0]!=="-"||e[1]!=="-"||!Pt(e)?null:(e=`var(${e})`,{kind:"arbitrary",value:gr(e)})):br.test(e)?{kind:"named",value:e}:null}function Ai(e,r){if(e[0]==="["&&e[e.length-1]==="]"){if(e[1]==="@"&&e.includes("&"))return null;let i=Ye(e.slice(1,-1));if(i===null||i.length===0||i.trim().length===0)return null;let t=i[0]===">"||i[0]==="+"||i[0]==="~";return!t&&i[0]!=="@"&&!i.includes("&")&&(i=`&:is(${i})`),{kind:"arbitrary",selector:i,relative:t}}{let i=j(e,"/");if(i.length>2)return null;let[t,n=null]=i,o=Ci(t,l=>r.variants.has(l));for(let[l,f]of o)switch(r.variants.kind(l)){case"static":return f!==null||n!==null?null:{kind:"static",root:l};case"functional":{let u=n===null?null:vr(n);if(n!==null&&u===null)return null;if(f===null)return{kind:"functional",root:l,modifier:u,value:null};if(f[f.length-1]==="]"){if(f[0]!=="[")continue;let c=Ye(f.slice(1,-1));return c===null||c.length===0||c.trim().length===0?null:{kind:"functional",root:l,modifier:u,value:{kind:"arbitrary",value:c}}}if(f[f.length-1]===")"){if(f[0]!=="(")continue;let c=Ye(f.slice(1,-1));return c===null||c.length===0||c.trim().length===0||c[0]!=="-"||c[1]!=="-"?null:{kind:"functional",root:l,modifier:u,value:{kind:"arbitrary",value:`var(${c})`}}}if(!br.test(f))continue;return{kind:"functional",root:l,modifier:u,value:{kind:"named",value:f}}}case"compound":{if(f===null)return null;n&&(l==="not"||l==="has"||l==="in")&&(f=`${f}/${n}`,n=null);let u=r.parseVariant(f);if(u===null||!r.variants.compoundsWith(l,u))return null;let c=n===null?null:vr(n);return n!==null&&c===null?null:{kind:"compound",root:l,modifier:c,variant:u}}}}return null}function*Ci(e,r){r(e)&&(yield[e,null]);let i=e.lastIndexOf("-");for(;i>0;){let t=e.slice(0,i);if(r(t)){let n=[t,e.slice(i+1)];if(n[1]===""||n[0]==="@"&&r("@")&&e[i]==="-")break;yield n}i=e.lastIndexOf("-",i-1)}e[0]==="@"&&r("@")&&(yield["@",e.slice(1)])}function Si(e,r){let i=[];for(let n of r.variants)i.unshift(Ot(n));e.theme.prefix&&i.unshift(e.theme.prefix);let t="";if(r.kind==="static"&&(t+=r.root),r.kind==="functional"&&(t+=r.root,r.value))if(r.value.kind==="arbitrary"){if(r.value!==null){let n=wr(r.value.value),o=n?r.value.value.slice(4,-1):r.value.value,[l,f]=n?["(",")"]:["[","]"];r.value.dataType?t+=`-${l}${r.value.dataType}:${$e(o)}${f}`:t+=`-${l}${$e(o)}${f}`}}else r.value.kind==="named"&&(t+=`-${r.value.value}`);return r.kind==="arbitrary"&&(t+=`[${r.property}:${$e(r.value)}]`),(r.kind==="arbitrary"||r.kind==="functional")&&(t+=st(r.modifier)),r.important&&(t+="!"),i.push(t),i.join(":")}function st(e){if(e===null)return"";let r=wr(e.value),i=r?e.value.slice(4,-1):e.value,[t,n]=r?["(",")"]:["[","]"];return e.kind==="arbitrary"?`/${t}${$e(i)}${n}`:e.kind==="named"?`/${e.value}`:""}function Ot(e){if(e.kind==="static")return e.root;if(e.kind==="arbitrary")return`[${$e(Sl(e.selector))}]`;let r="";if(e.kind==="functional"){r+=e.root;let i=e.root!=="@";if(e.value)if(e.value.kind==="arbitrary"){let t=wr(e.value.value),n=t?e.value.value.slice(4,-1):e.value.value,[o,l]=t?["(",")"]:["[","]"];r+=`${i?"-":""}${o}${$e(n)}${l}`}else e.value.kind==="named"&&(r+=`${i?"-":""}${e.value.value}`)}return e.kind==="compound"&&(r+=e.root,r+="-",r+=Ot(e.variant)),(e.kind==="functional"||e.kind==="compound")&&(r+=st(e.modifier)),r}var Al=new K(e=>{let r=Y(e),i=new Set,t=new Set(["~",">","+","-","*","/"]);return I(r,(n,o)=>{if(n.kind==="word"&&t.has(n.value)){let l=o.index;if(l===-1)return;let f=o.siblings[l-1];if(f?.kind!=="separator"||f.value!==" ")return;let u=o.siblings[l+1];if(u?.kind!=="separator"||u.value!==" ")return;let c=o.siblings[l-2];if(c&&t.has(c.value))return;let d=o.siblings[l+2];if(d&&t.has(d.value))return;i.add(f),i.add(u)}else if(n.kind==="separator"&&n.value.length>0&&n.value.trim()==="")(o.siblings[0]===n||o.siblings[o.siblings.length-1]===n)&&i.add(n);else if(n.kind==="separator"&&n.value.trim()===",")n.value=",";else if(n.kind==="function"&&n.value.startsWith("--")){let l=o.index;if(l<=0)return;let f=o.siblings[l-1];if(f?.kind==="separator"&&f.value===",")return;let u=o.siblings[l-2];return u&&!t.has(u.value)?void 0:V.ReplaceSkip({kind:"function",value:"",nodes:[n]})}}),i.size>0&&I(r,n=>{if(i.has(n))return i.delete(n),V.ReplaceSkip([])}),kr(r),B(r)});function $e(e){return Al.get(e)}var Cl=new K(e=>{let r=Y(e);return r.length===3&&r[0].kind==="word"&&r[0].value==="&"&&r[1].kind==="separator"&&r[1].value===":"&&r[2].kind==="function"&&r[2].value==="is"?B(r[2].nodes):e});function Sl(e){return Cl.get(e)}function kr(e){for(let r of e)switch(r.kind){case"function":{if(r.value==="url"||r.value.endsWith("_url")){r.value=at(r.value);break}if(r.value==="var"||r.value.endsWith("_var")||r.value==="theme"||r.value.endsWith("_theme")){r.value=at(r.value);for(let i=0;i{let r=Y(e);return r.length===1&&r[0].kind==="function"&&r[0].value==="var"});function wr(e){return Vl.get(e)}function Tl(e){throw new Error(`Unexpected value: ${e}`)}function at(e){return e.replaceAll("_",String.raw`\_`).replaceAll(" ","_")}function Ye(e){return Pt(e)?gr(e):null}function De(e,r,i){if(e===r)return 0;let t=e.indexOf("("),n=r.indexOf("("),o=t===-1?e.replace(/[\d.]+/g,""):e.slice(0,t),l=n===-1?r.replace(/[\d.]+/g,""):r.slice(0,n),f=(o===l?0:o[-+]?(?:\d*\.)?\d+)(?[a-z]+|%)?$/i,oe=new K(e=>{let r=$l.exec(e);if(!r)return null;let i=r.groups?.value;if(i===void 0)return null;let t=Number(i);if(Number.isNaN(t))return null;let n=r.groups?.unit;return n===void 0?[t,null]:[t,n]});var Vi=new Set(["black","silver","gray","white","maroon","red","purple","fuchsia","green","lime","olive","yellow","navy","blue","teal","aqua","aliceblue","antiquewhite","aqua","aquamarine","azure","beige","bisque","black","blanchedalmond","blue","blueviolet","brown","burlywood","cadetblue","chartreuse","chocolate","coral","cornflowerblue","cornsilk","crimson","cyan","darkblue","darkcyan","darkgoldenrod","darkgray","darkgreen","darkgrey","darkkhaki","darkmagenta","darkolivegreen","darkorange","darkorchid","darkred","darksalmon","darkseagreen","darkslateblue","darkslategray","darkslategrey","darkturquoise","darkviolet","deeppink","deepskyblue","dimgray","dimgrey","dodgerblue","firebrick","floralwhite","forestgreen","fuchsia","gainsboro","ghostwhite","gold","goldenrod","gray","green","greenyellow","grey","honeydew","hotpink","indianred","indigo","ivory","khaki","lavender","lavenderblush","lawngreen","lemonchiffon","lightblue","lightcoral","lightcyan","lightgoldenrodyellow","lightgray","lightgreen","lightgrey","lightpink","lightsalmon","lightseagreen","lightskyblue","lightslategray","lightslategrey","lightsteelblue","lightyellow","lime","limegreen","linen","magenta","maroon","mediumaquamarine","mediumblue","mediumorchid","mediumpurple","mediumseagreen","mediumslateblue","mediumspringgreen","mediumturquoise","mediumvioletred","midnightblue","mintcream","mistyrose","moccasin","navajowhite","navy","oldlace","olive","olivedrab","orange","orangered","orchid","palegoldenrod","palegreen","paleturquoise","palevioletred","papayawhip","peachpuff","peru","pink","plum","powderblue","purple","rebeccapurple","red","rosybrown","royalblue","saddlebrown","salmon","sandybrown","seagreen","seashell","sienna","silver","skyblue","slateblue","slategray","slategrey","snow","springgreen","steelblue","tan","teal","thistle","tomato","turquoise","violet","wheat","white","whitesmoke","yellow","yellowgreen","transparent","currentcolor","canvas","canvastext","linktext","visitedtext","activetext","buttonface","buttontext","buttonborder","field","fieldtext","highlight","highlighttext","selecteditem","selecteditemtext","mark","marktext","graytext","accentcolor","accentcolortext"]),Nl=/^(rgba?|hsla?|hwb|color|(ok)?(lab|lch)|light-dark|color-mix|--alpha)\(/i;function Ti(e){return e.charCodeAt(0)===35||Nl.test(e)||Vi.has(e.toLowerCase())}function $i(e){return Vi.has(e.toLowerCase())}var El={color:Ti,length:Se,percentage:yr,ratio:Fl,number:Ei,integer:D,url:Ni,position:ql,"bg-size":Hl,"line-width":Pl,image:Il,"family-name":Ul,"generic-name":Dl,"absolute-size":Ll,"relative-size":Kl,angle:Ql,vector:Xl};function X(e,r){if(e.startsWith("var("))return null;for(let i of r)if(El[i]?.(e))return i;return null}var Rl=/^url\(.*\)$/;function Ni(e){return Rl.test(e)}function Pl(e){return j(e," ").every(r=>Se(r)||Ei(r)||r==="thin"||r==="medium"||r==="thick")}var Ol=/^(?:element|image|cross-fade|image-set)\(/,_l=/^(repeating-)?(conic|linear|radial)-gradient\(/;function Il(e){let r=0;for(let i of j(e,","))if(!i.startsWith("var(")){if(Ni(i)){r+=1;continue}if(_l.test(i)){r+=1;continue}if(Ol.test(i)){r+=1;continue}return!1}return r>0}function Dl(e){return e==="serif"||e==="sans-serif"||e==="monospace"||e==="cursive"||e==="fantasy"||e==="system-ui"||e==="ui-serif"||e==="ui-sans-serif"||e==="ui-monospace"||e==="ui-rounded"||e==="math"||e==="emoji"||e==="fangsong"}function Ul(e){let r=0;for(let i of j(e,",")){let t=i.charCodeAt(0);if(t>=48&&t<=57)return!1;i.startsWith("var(")||(r+=1)}return r>0}function Ll(e){return e==="xx-small"||e==="x-small"||e==="small"||e==="medium"||e==="large"||e==="x-large"||e==="xx-large"||e==="xxx-large"}function Kl(e){return e==="larger"||e==="smaller"}var Ce=/[+-]?\d*\.?\d+(?:[eE][+-]?\d+)?/,zl=new RegExp(`^${Ce.source}$`);function Ei(e){return zl.test(e)||ot(e)}var Ml=new RegExp(`^${Ce.source}%$`);function yr(e){return Ml.test(e)||ot(e)}var jl=new RegExp(`^${Ce.source}\\s*/\\s*${Ce.source}$`);function Fl(e){return jl.test(e)||ot(e)}var Wl=["cm","mm","Q","in","pc","pt","px","em","ex","ch","cap","ic","rem","rex","rch","rcap","ric","lh","rlh","vw","vh","vmin","vmax","vb","vi","svw","svh","svi","svb","svmin","svmax","lvw","lvh","lvi","lvb","lvmin","lvmax","dvw","dvh","dvi","dvb","dvmin","dvmax","cqw","cqh","cqi","cqb","cqmin","cqmax"],Bl=new RegExp(`^${Ce.source}(${Wl.join("|")})$`),Yl=/^(--spacing)\(/i;function Se(e){return Bl.test(e)||Yl.test(e)||ot(e)}function ql(e){let r=0;for(let i of j(e," ")){if(i==="center"||i==="top"||i==="right"||i==="bottom"||i==="left"){r+=1;continue}if(!i.startsWith("var(")){if(Se(i)||yr(i)){r+=1;continue}return!1}}return r>0}function Hl(e){let r=0;for(let i of j(e,",")){if(i==="cover"||i==="contain"){r+=1;continue}let t=j(i," ");if(t.length!==1&&t.length!==2)return!1;if(t.every(n=>n==="auto"||Se(n)||yr(n))){r+=1;continue}}return r>0}var Gl=["deg","rad","grad","turn"],Zl=new RegExp(`^${Ce.source}(${Gl.join("|")})$`);function Ql(e){return Zl.test(e)}var Jl=new RegExp(`^${Ce.source} +${Ce.source} +${Ce.source}$`);function Xl(e){return Jl.test(e)}function D(e){let r=Number(e);return Number.isInteger(r)&&r>=0&&String(r)===String(e)}function xr(e){let r=Number(e);return Number.isInteger(r)&&r>0&&String(r)===String(e)}function te(e){return Ri(e,.25)}function Ne(e){return Ri(e,.25)}function Ri(e,r){let i=Number(e);return i>=0&&i%r===0&&String(i)===String(e)}var eo=new Set(["inset","inherit","initial","revert","unset"]),to=new Set(["calc","clamp","max","min","--spacing"]),ro=new Set(["color","color-mix","contrast-color","device-cmyk","hsl","hsla","hwb","lab","lch","light-dark","oklab","oklch","rgb","rgba","--alpha"]),io=/^-?(\d+|\.\d+)(.*?)$/;function ut(e,r){function i(n){let o=B([n]),l=r(o);return Y(l)}return j(e,",").map(n=>{n=n.trim();let o=Y(n),l=null,f=0,u=0,c=!1;return I(o,d=>{switch(d.kind){case"word":{if(eo.has(d.value.toLowerCase()))return V.Continue;if(io.test(d.value.toLowerCase()))return u++,V.Continue;if(d.value[0]==="#"||$i(d.value))return c=!0,V.ReplaceStop(i(d));l=d,f++;break}case"function":return ro.has(d.value.toLowerCase())?(c=!0,V.ReplaceStop(i(d))):to.has(d.value.toLowerCase())?(u++,V.Skip):(l=d,f++,V.Skip);case"separator":return V.Continue;default:}}),c?B(o):u<2?n:f===0?`${n} ${r("currentcolor")}`:(f===1&&I(o,d=>d===l?(c=!0,V.ReplaceStop(i(d))):V.Skip),c?B(o):n)}).join(", ")}var Ut=["0","0.5","1","1.5","2","2.5","3","3.5","4","5","6","7","8","9","10","11","12","14","16","20","24","28","32","36","40","44","48","52","56","60","64","72","80","96"],Ar=class{utilities=new K(()=>[]);completions=new Map;static(r,i){this.utilities.get(r).push({kind:"static",compileFn:i})}functional(r,i,t){this.utilities.get(r).push({kind:"functional",compileFn:i,options:t})}has(r,i){return this.utilities.has(r)&&this.utilities.get(r).some(t=>t.kind===i)}get(r){return this.utilities.has(r)?this.utilities.get(r):[]}getCompletions(r){return this.has(r,"static")?this.completions.get(r)?.()??[{supportsNegative:!1,values:[],modifiers:[]}]:this.completions.get(r)?.()??[]}suggest(r,i){let t=this.completions.get(r);t?this.completions.set(r,()=>[...t?.(),...i?.()]):this.completions.set(r,i)}keys(r){let i=[];for(let[t,n]of this.utilities.entries())for(let o of n)if(o.kind===r){i.push(t);break}return i}};function T(e,r,i){return H("@property",e,[s("syntax",i?`"${i}"`:'"*"'),s("inherits","false"),...r?[s("initial-value",r)]:[]])}function ie(e,r){if(r===null)return e;let i=Number(r);return Number.isNaN(i)||(r=`${i*100}%`),r==="100%"?e:`color-mix(in oklab, ${e} ${r}, transparent)`}function Oi(e,r){let i=Number(r);return Number.isNaN(i)||(r=`${i*100}%`),`oklab(from ${e} l a b / ${r})`}function ne(e,r,i){if(!r)return e;if(r.kind==="arbitrary")return ie(e,r.value);let t=i.resolve(r.value,["--opacity"]);return t?ie(e,t):Ne(r.value)?ie(e,`${r.value}%`):null}function ae(e,r,i){let t=null;switch(e.value.value){case"inherit":{t="inherit";break}case"transparent":{t="transparent";break}case"current":{t="currentcolor";break}default:{t=r.resolve(e.value.value,i);break}}return t?ne(t,e.modifier,r):null}var _i=/(\d+)_(\d+)/g;function Ii(e){let r=new Ar;function i(a,g){function*v(x){for(let $ of e.keysInNamespaces(x))yield $.replace(_i,(M,N,_)=>`${N}.${_}`)}let S=["1/2","1/3","2/3","1/4","2/4","3/4","1/5","2/5","3/5","4/5","1/6","2/6","3/6","4/6","5/6","1/12","2/12","3/12","4/12","5/12","6/12","7/12","8/12","9/12","10/12","11/12"];r.suggest(a,()=>{let x=[];for(let $ of g()){if(typeof $=="string"){x.push({values:[$],modifiers:[]});continue}let M=[...$.values??[],...v($.valueThemeKeys??[])],N=[...$.modifiers??[],...v($.modifierThemeKeys??[])];$.supportsFractions&&M.push(...S),$.hasDefaultValue&&M.unshift(null),x.push({supportsNegative:$.supportsNegative,values:M,modifiers:N})}return x})}function t(a,g){r.static(a,()=>g.map(v=>typeof v=="function"?v():s(v[0],v[1])))}function n(a,g){g.staticValues&&(g.staticValues=Object.assign(Object.create(null),g.staticValues));function v({negative:S}){return x=>{let $=null,M=null;if(x.value)if(x.value.kind==="arbitrary"){if(x.modifier)return;$=x.value.value,M=x.value.dataType}else{if($=e.resolve(x.value.fraction??x.value.value,g.themeKeys??[]),$!==null&&x.modifier&&!x.value.fraction)return;if($===null&&g.supportsFractions&&x.value.fraction){let[N,_]=j(x.value.fraction,"/");if(!D(N)||!D(_))return;$=`calc(${N} / ${_} * 100%)`}if($===null&&S&&g.handleNegativeBareValue){if($=g.handleNegativeBareValue(x.value),!$?.includes("/")&&x.modifier)return;if($!==null)return g.handle($,null)}if($===null&&g.handleBareValue&&($=g.handleBareValue(x.value),!$?.includes("/")&&x.modifier))return;if($===null&&!S&&g.staticValues&&!x.modifier){let N=g.staticValues[x.value.value];if(N)return N.map(le)}}else{if(x.modifier)return;$=g.defaultValue!==void 0?g.defaultValue:e.resolve(null,g.themeKeys??[])}if($!==null)return g.handle(S?Rt(`calc(${$} * -1)`):$,M)}}if(g.supportsNegative&&r.functional(`-${a}`,v({negative:!0})),r.functional(a,v({negative:!1})),i(a,()=>[{supportsNegative:g.supportsNegative,valueThemeKeys:g.themeKeys??[],hasDefaultValue:g.defaultValue!==void 0&&g.defaultValue!==null,supportsFractions:g.supportsFractions}]),g.staticValues&&Object.keys(g.staticValues).length>0){let S=Object.keys(g.staticValues);i(a,()=>[{values:S}])}}function o(a,g){r.functional(a,v=>{if(!v.value)return;let S=null;if(v.value.kind==="arbitrary"?(S=v.value.value,S=ne(S,v.modifier,e)):S=ae(v,e,g.themeKeys),S!==null)return g.handle(S)}),i(a,()=>[{values:["current","inherit","transparent"],valueThemeKeys:g.themeKeys,modifierThemeKeys:["--opacity"],modifiers:Array.from({length:21},(v,S)=>`${S*5}`)}])}function l(a,g,v,{supportsNegative:S=!1,supportsFractions:x=!1,staticValues:$}={}){S&&r.static(`-${a}-px`,()=>v("-1px")),r.static(`${a}-px`,()=>v("1px")),n(a,{themeKeys:g,supportsFractions:x,supportsNegative:S,defaultValue:null,handleBareValue:({value:M})=>!e.resolve(null,["--spacing"])||!te(M)?null:`--spacing(${M})`,handleNegativeBareValue:({value:M})=>!e.resolve(null,["--spacing"])||!te(M)?null:`--spacing(-${M})`,handle:v,staticValues:$}),i(a,()=>[{values:e.get(["--spacing"])?Ut:[],supportsNegative:S,supportsFractions:x,valueThemeKeys:g}])}t("sr-only",[["position","absolute"],["width","1px"],["height","1px"],["padding","0"],["margin","-1px"],["overflow","hidden"],["clip-path","inset(50%)"],["white-space","nowrap"],["border-width","0"]]),t("not-sr-only",[["position","static"],["width","auto"],["height","auto"],["padding","0"],["margin","0"],["overflow","visible"],["clip-path","none"],["white-space","normal"]]),t("pointer-events-none",[["pointer-events","none"]]),t("pointer-events-auto",[["pointer-events","auto"]]),t("visible",[["visibility","visible"]]),t("invisible",[["visibility","hidden"]]),t("collapse",[["visibility","collapse"]]),t("static",[["position","static"]]),t("fixed",[["position","fixed"]]),t("absolute",[["position","absolute"]]),t("relative",[["position","relative"]]),t("sticky",[["position","sticky"]]);for(let[a,g]of[["inset","inset"],["inset-x","inset-inline"],["inset-y","inset-block"],["inset-s","inset-inline-start"],["inset-e","inset-inline-end"],["inset-bs","inset-block-start"],["inset-be","inset-block-end"],["top","top"],["right","right"],["bottom","bottom"],["left","left"]])t(`${a}-auto`,[[g,"auto"]]),t(`${a}-full`,[[g,"100%"]]),t(`-${a}-full`,[[g,"-100%"]]),l(a,["--inset","--spacing"],v=>[s(g,v)],{supportsNegative:!0,supportsFractions:!0});t("isolate",[["isolation","isolate"]]),t("isolation-auto",[["isolation","auto"]]),n("z",{supportsNegative:!0,handleBareValue:({value:a})=>D(a)?a:null,themeKeys:["--z-index"],handle:a=>[s("z-index",a)],staticValues:{auto:[s("z-index","auto")]}}),i("z",()=>[{supportsNegative:!0,values:["0","10","20","30","40","50"],valueThemeKeys:["--z-index"]}]),n("order",{supportsNegative:!0,handleBareValue:({value:a})=>D(a)?a:null,themeKeys:["--order"],handle:a=>[s("order",a)],staticValues:{first:[s("order","-9999")],last:[s("order","9999")]}}),i("order",()=>[{supportsNegative:!0,values:Array.from({length:12},(a,g)=>`${g+1}`),valueThemeKeys:["--order"]}]),n("col",{supportsNegative:!0,handleBareValue:({value:a})=>D(a)?a:null,themeKeys:["--grid-column"],handle:a=>[s("grid-column",a)],staticValues:{auto:[s("grid-column","auto")]}}),n("col-span",{handleBareValue:({value:a})=>D(a)?a:null,handle:a=>[s("grid-column",`span ${a} / span ${a}`)],staticValues:{full:[s("grid-column","1 / -1")]}}),n("col-start",{supportsNegative:!0,handleBareValue:({value:a})=>D(a)?a:null,themeKeys:["--grid-column-start"],handle:a=>[s("grid-column-start",a)],staticValues:{auto:[s("grid-column-start","auto")]}}),n("col-end",{supportsNegative:!0,handleBareValue:({value:a})=>D(a)?a:null,themeKeys:["--grid-column-end"],handle:a=>[s("grid-column-end",a)],staticValues:{auto:[s("grid-column-end","auto")]}}),i("col-span",()=>[{values:Array.from({length:12},(a,g)=>`${g+1}`),valueThemeKeys:[]}]),i("col-start",()=>[{supportsNegative:!0,values:Array.from({length:13},(a,g)=>`${g+1}`),valueThemeKeys:["--grid-column-start"]}]),i("col-end",()=>[{supportsNegative:!0,values:Array.from({length:13},(a,g)=>`${g+1}`),valueThemeKeys:["--grid-column-end"]}]),n("row",{supportsNegative:!0,handleBareValue:({value:a})=>D(a)?a:null,themeKeys:["--grid-row"],handle:a=>[s("grid-row",a)],staticValues:{auto:[s("grid-row","auto")]}}),n("row-span",{themeKeys:[],handleBareValue:({value:a})=>D(a)?a:null,handle:a=>[s("grid-row",`span ${a} / span ${a}`)],staticValues:{full:[s("grid-row","1 / -1")]}}),n("row-start",{supportsNegative:!0,handleBareValue:({value:a})=>D(a)?a:null,themeKeys:["--grid-row-start"],handle:a=>[s("grid-row-start",a)],staticValues:{auto:[s("grid-row-start","auto")]}}),n("row-end",{supportsNegative:!0,handleBareValue:({value:a})=>D(a)?a:null,themeKeys:["--grid-row-end"],handle:a=>[s("grid-row-end",a)],staticValues:{auto:[s("grid-row-end","auto")]}}),i("row-span",()=>[{values:Array.from({length:12},(a,g)=>`${g+1}`),valueThemeKeys:[]}]),i("row-start",()=>[{supportsNegative:!0,values:Array.from({length:13},(a,g)=>`${g+1}`),valueThemeKeys:["--grid-row-start"]}]),i("row-end",()=>[{supportsNegative:!0,values:Array.from({length:13},(a,g)=>`${g+1}`),valueThemeKeys:["--grid-row-end"]}]),t("float-start",[["float","inline-start"]]),t("float-end",[["float","inline-end"]]),t("float-right",[["float","right"]]),t("float-left",[["float","left"]]),t("float-none",[["float","none"]]),t("clear-start",[["clear","inline-start"]]),t("clear-end",[["clear","inline-end"]]),t("clear-right",[["clear","right"]]),t("clear-left",[["clear","left"]]),t("clear-both",[["clear","both"]]),t("clear-none",[["clear","none"]]);for(let[a,g]of[["m","margin"],["mx","margin-inline"],["my","margin-block"],["ms","margin-inline-start"],["me","margin-inline-end"],["mbs","margin-block-start"],["mbe","margin-block-end"],["mt","margin-top"],["mr","margin-right"],["mb","margin-bottom"],["ml","margin-left"]])t(`${a}-auto`,[[g,"auto"]]),l(a,["--margin","--spacing"],v=>[s(g,v)],{supportsNegative:!0});t("box-border",[["box-sizing","border-box"]]),t("box-content",[["box-sizing","content-box"]]),n("line-clamp",{themeKeys:["--line-clamp"],handleBareValue:({value:a})=>D(a)?a:null,handle:a=>[s("overflow","hidden"),s("display","-webkit-box"),s("-webkit-box-orient","vertical"),s("-webkit-line-clamp",a)],staticValues:{none:[s("overflow","visible"),s("display","block"),s("-webkit-box-orient","horizontal"),s("-webkit-line-clamp","unset")]}}),i("line-clamp",()=>[{values:["1","2","3","4","5","6"],valueThemeKeys:["--line-clamp"]}]),t("block",[["display","block"]]),t("inline-block",[["display","inline-block"]]),t("inline",[["display","inline"]]),t("hidden",[["display","none"]]),t("inline-flex",[["display","inline-flex"]]),t("table",[["display","table"]]),t("inline-table",[["display","inline-table"]]),t("table-caption",[["display","table-caption"]]),t("table-cell",[["display","table-cell"]]),t("table-column",[["display","table-column"]]),t("table-column-group",[["display","table-column-group"]]),t("table-footer-group",[["display","table-footer-group"]]),t("table-header-group",[["display","table-header-group"]]),t("table-row-group",[["display","table-row-group"]]),t("table-row",[["display","table-row"]]),t("flow-root",[["display","flow-root"]]),t("flex",[["display","flex"]]),t("grid",[["display","grid"]]),t("inline-grid",[["display","inline-grid"]]),t("contents",[["display","contents"]]),t("list-item",[["display","list-item"]]),t("field-sizing-content",[["field-sizing","content"]]),t("field-sizing-fixed",[["field-sizing","fixed"]]),n("aspect",{themeKeys:["--aspect"],handleBareValue:({fraction:a})=>{if(a===null)return null;let[g,v]=j(a,"/");return!te(g)||!te(v)?null:a},handle:a=>[s("aspect-ratio",a)],staticValues:{auto:[s("aspect-ratio","auto")],square:[s("aspect-ratio","1 / 1")]}});for(let[a,g]of[["full","100%"],["svw","100svw"],["lvw","100lvw"],["dvw","100dvw"],["svh","100svh"],["lvh","100lvh"],["dvh","100dvh"],["min","min-content"],["max","max-content"],["fit","fit-content"]])t(`size-${a}`,[["--tw-sort","size"],["width",g],["height",g]]),t(`w-${a}`,[["width",g]]),t(`h-${a}`,[["height",g]]),t(`min-w-${a}`,[["min-width",g]]),t(`min-h-${a}`,[["min-height",g]]),t(`max-w-${a}`,[["max-width",g]]),t(`max-h-${a}`,[["max-height",g]]);t("size-auto",[["--tw-sort","size"],["width","auto"],["height","auto"]]),t("w-auto",[["width","auto"]]),t("h-auto",[["height","auto"]]),t("min-w-auto",[["min-width","auto"]]),t("min-h-auto",[["min-height","auto"]]),t("h-lh",[["height","1lh"]]),t("min-h-lh",[["min-height","1lh"]]),t("max-h-lh",[["max-height","1lh"]]),t("w-screen",[["width","100vw"]]),t("min-w-screen",[["min-width","100vw"]]),t("max-w-screen",[["max-width","100vw"]]),t("h-screen",[["height","100vh"]]),t("min-h-screen",[["min-height","100vh"]]),t("max-h-screen",[["max-height","100vh"]]),t("max-w-none",[["max-width","none"]]),t("max-h-none",[["max-height","none"]]),l("size",["--size","--spacing"],a=>[s("--tw-sort","size"),s("width",a),s("height",a)],{supportsFractions:!0});for(let[a,g,v]of[["w",["--width","--spacing","--container"],"width"],["min-w",["--min-width","--spacing","--container"],"min-width"],["max-w",["--max-width","--spacing","--container"],"max-width"],["h",["--height","--spacing"],"height"],["min-h",["--min-height","--height","--spacing"],"min-height"],["max-h",["--max-height","--height","--spacing"],"max-height"]])l(a,g,S=>[s(v,S)],{supportsFractions:!0});for(let[a,g]of[["full","100%"],["min","min-content"],["max","max-content"],["fit","fit-content"]])t(`inline-${a}`,[["inline-size",g]]),t(`block-${a}`,[["block-size",g]]),t(`min-inline-${a}`,[["min-inline-size",g]]),t(`min-block-${a}`,[["min-block-size",g]]),t(`max-inline-${a}`,[["max-inline-size",g]]),t(`max-block-${a}`,[["max-block-size",g]]);for(let[a,g]of[["svw","100svw"],["lvw","100lvw"],["dvw","100dvw"]])t(`inline-${a}`,[["inline-size",g]]),t(`min-inline-${a}`,[["min-inline-size",g]]),t(`max-inline-${a}`,[["max-inline-size",g]]);for(let[a,g]of[["svh","100svh"],["lvh","100lvh"],["dvh","100dvh"]])t(`block-${a}`,[["block-size",g]]),t(`min-block-${a}`,[["min-block-size",g]]),t(`max-block-${a}`,[["max-block-size",g]]);t("inline-auto",[["inline-size","auto"]]),t("block-auto",[["block-size","auto"]]),t("min-inline-auto",[["min-inline-size","auto"]]),t("min-block-auto",[["min-block-size","auto"]]),t("block-lh",[["block-size","1lh"]]),t("min-block-lh",[["min-block-size","1lh"]]),t("max-block-lh",[["max-block-size","1lh"]]),t("inline-screen",[["inline-size","100vw"]]),t("min-inline-screen",[["min-inline-size","100vw"]]),t("max-inline-screen",[["max-inline-size","100vw"]]),t("block-screen",[["block-size","100vh"]]),t("min-block-screen",[["min-block-size","100vh"]]),t("max-block-screen",[["max-block-size","100vh"]]),t("max-inline-none",[["max-inline-size","none"]]),t("max-block-none",[["max-block-size","none"]]);for(let[a,g,v]of[["inline",["--spacing","--container"],"inline-size"],["min-inline",["--spacing","--container"],"min-inline-size"],["max-inline",["--spacing","--container"],"max-inline-size"],["block",["--spacing"],"block-size"],["min-block",["--spacing"],"min-block-size"],["max-block",["--spacing"],"max-block-size"]])l(a,g,S=>[s(v,S)],{supportsFractions:!0});r.static("container",()=>{let a=[...e.namespace("--breakpoint").values()];a.sort((v,S)=>De(v,S,"asc"));let g=[s("--tw-sort","--tw-container-component"),s("width","100%")];for(let v of a)g.push(H("@media",`(width >= ${v})`,[s("max-width",v)]));return g}),t("flex-auto",[["flex","auto"]]),t("flex-initial",[["flex","0 auto"]]),t("flex-none",[["flex","none"]]),r.functional("flex",a=>{if(a.value){if(a.value.kind==="arbitrary")return a.modifier?void 0:[s("flex",a.value.value)];if(a.value.fraction){let[g,v]=j(a.value.fraction,"/");return!D(g)||!D(v)?void 0:[s("flex",`calc(${a.value.fraction} * 100%)`)]}if(D(a.value.value))return a.modifier?void 0:[s("flex",a.value.value)]}}),i("flex",()=>[{supportsFractions:!0},{values:Array.from({length:12},(a,g)=>`${g+1}`)}]),n("shrink",{defaultValue:"1",handleBareValue:({value:a})=>D(a)?a:null,handle:a=>[s("flex-shrink",a)]}),n("grow",{defaultValue:"1",handleBareValue:({value:a})=>D(a)?a:null,handle:a=>[s("flex-grow",a)]}),i("shrink",()=>[{values:["0"],valueThemeKeys:[],hasDefaultValue:!0}]),i("grow",()=>[{values:["0"],valueThemeKeys:[],hasDefaultValue:!0}]),t("basis-auto",[["flex-basis","auto"]]),t("basis-full",[["flex-basis","100%"]]),l("basis",["--flex-basis","--spacing","--container"],a=>[s("flex-basis",a)],{supportsFractions:!0}),t("table-auto",[["table-layout","auto"]]),t("table-fixed",[["table-layout","fixed"]]),t("caption-top",[["caption-side","top"]]),t("caption-bottom",[["caption-side","bottom"]]),t("border-collapse",[["border-collapse","collapse"]]),t("border-separate",[["border-collapse","separate"]]);let f=()=>G([T("--tw-border-spacing-x","0",""),T("--tw-border-spacing-y","0","")]);l("border-spacing",["--border-spacing","--spacing"],a=>[f(),s("--tw-border-spacing-x",a),s("--tw-border-spacing-y",a),s("border-spacing","var(--tw-border-spacing-x) var(--tw-border-spacing-y)")]),l("border-spacing-x",["--border-spacing","--spacing"],a=>[f(),s("--tw-border-spacing-x",a),s("border-spacing","var(--tw-border-spacing-x) var(--tw-border-spacing-y)")]),l("border-spacing-y",["--border-spacing","--spacing"],a=>[f(),s("--tw-border-spacing-y",a),s("border-spacing","var(--tw-border-spacing-x) var(--tw-border-spacing-y)")]),n("origin",{themeKeys:["--transform-origin"],handle:a=>[s("transform-origin",a)],staticValues:{center:[s("transform-origin","center")],top:[s("transform-origin","top")],"top-right":[s("transform-origin","100% 0")],right:[s("transform-origin","100%")],"bottom-right":[s("transform-origin","100% 100%")],bottom:[s("transform-origin","bottom")],"bottom-left":[s("transform-origin","0 100%")],left:[s("transform-origin","0")],"top-left":[s("transform-origin","0 0")]}}),n("perspective-origin",{themeKeys:["--perspective-origin"],handle:a=>[s("perspective-origin",a)],staticValues:{center:[s("perspective-origin","center")],top:[s("perspective-origin","top")],"top-right":[s("perspective-origin","100% 0")],right:[s("perspective-origin","100%")],"bottom-right":[s("perspective-origin","100% 100%")],bottom:[s("perspective-origin","bottom")],"bottom-left":[s("perspective-origin","0 100%")],left:[s("perspective-origin","0")],"top-left":[s("perspective-origin","0 0")]}}),n("perspective",{themeKeys:["--perspective"],handle:a=>[s("perspective",a)],staticValues:{none:[s("perspective","none")]}});let u=()=>G([T("--tw-translate-x","0"),T("--tw-translate-y","0"),T("--tw-translate-z","0")]);t("translate-none",[["translate","none"]]),t("-translate-full",[u,["--tw-translate-x","-100%"],["--tw-translate-y","-100%"],["translate","var(--tw-translate-x) var(--tw-translate-y)"]]),t("translate-full",[u,["--tw-translate-x","100%"],["--tw-translate-y","100%"],["translate","var(--tw-translate-x) var(--tw-translate-y)"]]),l("translate",["--translate","--spacing"],a=>[u(),s("--tw-translate-x",a),s("--tw-translate-y",a),s("translate","var(--tw-translate-x) var(--tw-translate-y)")],{supportsNegative:!0,supportsFractions:!0});for(let a of["x","y"])t(`-translate-${a}-full`,[u,[`--tw-translate-${a}`,"-100%"],["translate","var(--tw-translate-x) var(--tw-translate-y)"]]),t(`translate-${a}-full`,[u,[`--tw-translate-${a}`,"100%"],["translate","var(--tw-translate-x) var(--tw-translate-y)"]]),l(`translate-${a}`,["--translate","--spacing"],g=>[u(),s(`--tw-translate-${a}`,g),s("translate","var(--tw-translate-x) var(--tw-translate-y)")],{supportsNegative:!0,supportsFractions:!0});l("translate-z",["--translate","--spacing"],a=>[u(),s("--tw-translate-z",a),s("translate","var(--tw-translate-x) var(--tw-translate-y) var(--tw-translate-z)")],{supportsNegative:!0}),t("translate-3d",[u,["translate","var(--tw-translate-x) var(--tw-translate-y) var(--tw-translate-z)"]]);let c=()=>G([T("--tw-scale-x","1"),T("--tw-scale-y","1"),T("--tw-scale-z","1")]);t("scale-none",[["scale","none"]]);function d({negative:a}){return g=>{if(!g.value||g.modifier)return;let v;return g.value.kind==="arbitrary"?(v=g.value.value,v=a?`calc(${v} * -1)`:v,[s("scale",v)]):(v=e.resolve(g.value.value,["--scale"]),!v&&D(g.value.value)&&(v=`${g.value.value}%`),v?(v=a?`calc(${v} * -1)`:v,[c(),s("--tw-scale-x",v),s("--tw-scale-y",v),s("--tw-scale-z",v),s("scale","var(--tw-scale-x) var(--tw-scale-y)")]):void 0)}}r.functional("-scale",d({negative:!0})),r.functional("scale",d({negative:!1})),i("scale",()=>[{supportsNegative:!0,values:["0","50","75","90","95","100","105","110","125","150","200"],valueThemeKeys:["--scale"]}]);for(let a of["x","y","z"])n(`scale-${a}`,{supportsNegative:!0,themeKeys:["--scale"],handleBareValue:({value:g})=>D(g)?`${g}%`:null,handle:g=>[c(),s(`--tw-scale-${a}`,g),s("scale",`var(--tw-scale-x) var(--tw-scale-y)${a==="z"?" var(--tw-scale-z)":""}`)]}),i(`scale-${a}`,()=>[{supportsNegative:!0,values:["0","50","75","90","95","100","105","110","125","150","200"],valueThemeKeys:["--scale"]}]);t("scale-3d",[c,["scale","var(--tw-scale-x) var(--tw-scale-y) var(--tw-scale-z)"]]),t("rotate-none",[["rotate","none"]]);function m({negative:a}){return g=>{if(!g.value||g.modifier)return;let v;if(g.value.kind==="arbitrary"){v=g.value.value;let S=g.value.dataType??X(v,["angle","vector"]);if(S==="vector")return[s("rotate",`${v} var(--tw-rotate)`)];if(S!=="angle")return[s("rotate",a?`calc(${v} * -1)`:v)]}else if(v=e.resolve(g.value.value,["--rotate"]),!v&&D(g.value.value)&&(v=`${g.value.value}deg`),!v)return;return[s("rotate",a?`calc(${v} * -1)`:v)]}}r.functional("-rotate",m({negative:!0})),r.functional("rotate",m({negative:!1})),i("rotate",()=>[{supportsNegative:!0,values:["0","1","2","3","6","12","45","90","180"],valueThemeKeys:["--rotate"]}]);{let a=["var(--tw-rotate-x, )","var(--tw-rotate-y, )","var(--tw-rotate-z, )","var(--tw-skew-x, )","var(--tw-skew-y, )"].join(" "),g=()=>G([T("--tw-rotate-x"),T("--tw-rotate-y"),T("--tw-rotate-z"),T("--tw-skew-x"),T("--tw-skew-y")]);for(let v of["x","y","z"])n(`rotate-${v}`,{supportsNegative:!0,themeKeys:["--rotate"],handleBareValue:({value:S})=>D(S)?`${S}deg`:null,handle:S=>[g(),s(`--tw-rotate-${v}`,`rotate${v.toUpperCase()}(${S})`),s("transform",a)]}),i(`rotate-${v}`,()=>[{supportsNegative:!0,values:["0","1","2","3","6","12","45","90","180"],valueThemeKeys:["--rotate"]}]);n("skew",{supportsNegative:!0,themeKeys:["--skew"],handleBareValue:({value:v})=>D(v)?`${v}deg`:null,handle:v=>[g(),s("--tw-skew-x",`skewX(${v})`),s("--tw-skew-y",`skewY(${v})`),s("transform",a)]}),n("skew-x",{supportsNegative:!0,themeKeys:["--skew"],handleBareValue:({value:v})=>D(v)?`${v}deg`:null,handle:v=>[g(),s("--tw-skew-x",`skewX(${v})`),s("transform",a)]}),n("skew-y",{supportsNegative:!0,themeKeys:["--skew"],handleBareValue:({value:v})=>D(v)?`${v}deg`:null,handle:v=>[g(),s("--tw-skew-y",`skewY(${v})`),s("transform",a)]}),i("skew",()=>[{supportsNegative:!0,values:["0","1","2","3","6","12"],valueThemeKeys:["--skew"]}]),i("skew-x",()=>[{supportsNegative:!0,values:["0","1","2","3","6","12"],valueThemeKeys:["--skew"]}]),i("skew-y",()=>[{supportsNegative:!0,values:["0","1","2","3","6","12"],valueThemeKeys:["--skew"]}]),r.functional("transform",v=>{if(v.modifier)return;let S=null;if(v.value?v.value.kind==="arbitrary"&&(S=v.value.value):S=a,S!==null)return[g(),s("transform",S)]}),i("transform",()=>[{hasDefaultValue:!0}]),t("transform-cpu",[["transform",a]]),t("transform-gpu",[["transform",`translateZ(0) ${a}`]]),t("transform-none",[["transform","none"]])}n("zoom",{handleBareValue:({value:a})=>D(a)?`${a}%`:null,handle:a=>[s("zoom",a)]}),i("zoom",()=>[{values:["50","75","90","95","100","105","110","125","150","200"]}]),t("transform-flat",[["transform-style","flat"]]),t("transform-3d",[["transform-style","preserve-3d"]]),t("transform-content",[["transform-box","content-box"]]),t("transform-border",[["transform-box","border-box"]]),t("transform-fill",[["transform-box","fill-box"]]),t("transform-stroke",[["transform-box","stroke-box"]]),t("transform-view",[["transform-box","view-box"]]),t("backface-visible",[["backface-visibility","visible"]]),t("backface-hidden",[["backface-visibility","hidden"]]);for(let a of["auto","default","pointer","wait","text","move","help","not-allowed","none","context-menu","progress","cell","crosshair","vertical-text","alias","copy","no-drop","grab","grabbing","all-scroll","col-resize","row-resize","n-resize","e-resize","s-resize","w-resize","ne-resize","nw-resize","se-resize","sw-resize","ew-resize","ns-resize","nesw-resize","nwse-resize","zoom-in","zoom-out"])t(`cursor-${a}`,[["cursor",a]]);n("cursor",{themeKeys:["--cursor"],handle:a=>[s("cursor",a)]});for(let a of["auto","none","manipulation"])t(`touch-${a}`,[["touch-action",a]]);let p=()=>G([T("--tw-pan-x"),T("--tw-pan-y"),T("--tw-pinch-zoom")]);for(let a of["x","left","right"])t(`touch-pan-${a}`,[p,["--tw-pan-x",`pan-${a}`],["touch-action","var(--tw-pan-x, ) var(--tw-pan-y, ) var(--tw-pinch-zoom, )"]]);for(let a of["y","up","down"])t(`touch-pan-${a}`,[p,["--tw-pan-y",`pan-${a}`],["touch-action","var(--tw-pan-x, ) var(--tw-pan-y, ) var(--tw-pinch-zoom, )"]]);t("touch-pinch-zoom",[p,["--tw-pinch-zoom","pinch-zoom"],["touch-action","var(--tw-pan-x, ) var(--tw-pan-y, ) var(--tw-pinch-zoom, )"]]);for(let a of["none","text","all","auto"])t(`select-${a}`,[["-webkit-user-select",a],["user-select",a]]);t("resize-none",[["resize","none"]]),t("resize-x",[["resize","horizontal"]]),t("resize-y",[["resize","vertical"]]),t("resize",[["resize","both"]]),t("snap-none",[["scroll-snap-type","none"]]);let h=()=>G([T("--tw-scroll-snap-strictness","proximity","*")]);for(let a of["x","y","both"])t(`snap-${a}`,[h,["scroll-snap-type",`${a} var(--tw-scroll-snap-strictness)`]]);t("snap-mandatory",[h,["--tw-scroll-snap-strictness","mandatory"]]),t("snap-proximity",[h,["--tw-scroll-snap-strictness","proximity"]]),t("snap-align-none",[["scroll-snap-align","none"]]),t("snap-start",[["scroll-snap-align","start"]]),t("snap-end",[["scroll-snap-align","end"]]),t("snap-center",[["scroll-snap-align","center"]]),t("snap-normal",[["scroll-snap-stop","normal"]]),t("snap-always",[["scroll-snap-stop","always"]]);for(let[a,g]of[["scroll-m","scroll-margin"],["scroll-mx","scroll-margin-inline"],["scroll-my","scroll-margin-block"],["scroll-ms","scroll-margin-inline-start"],["scroll-me","scroll-margin-inline-end"],["scroll-mbs","scroll-margin-block-start"],["scroll-mbe","scroll-margin-block-end"],["scroll-mt","scroll-margin-top"],["scroll-mr","scroll-margin-right"],["scroll-mb","scroll-margin-bottom"],["scroll-ml","scroll-margin-left"]])l(a,["--scroll-margin","--spacing"],v=>[s(g,v)],{supportsNegative:!0});for(let[a,g]of[["scroll-p","scroll-padding"],["scroll-px","scroll-padding-inline"],["scroll-py","scroll-padding-block"],["scroll-ps","scroll-padding-inline-start"],["scroll-pe","scroll-padding-inline-end"],["scroll-pbs","scroll-padding-block-start"],["scroll-pbe","scroll-padding-block-end"],["scroll-pt","scroll-padding-top"],["scroll-pr","scroll-padding-right"],["scroll-pb","scroll-padding-bottom"],["scroll-pl","scroll-padding-left"]])l(a,["--scroll-padding","--spacing"],v=>[s(g,v)]);t("list-inside",[["list-style-position","inside"]]),t("list-outside",[["list-style-position","outside"]]),n("list",{themeKeys:["--list-style-type"],handle:a=>[s("list-style-type",a)],staticValues:{none:[s("list-style-type","none")],disc:[s("list-style-type","disc")],decimal:[s("list-style-type","decimal")]}}),n("list-image",{themeKeys:["--list-style-image"],handle:a=>[s("list-style-image",a)],staticValues:{none:[s("list-style-image","none")]}}),t("appearance-none",[["appearance","none"]]),t("appearance-auto",[["appearance","auto"]]),t("scheme-normal",[["color-scheme","normal"]]),t("scheme-dark",[["color-scheme","dark"]]),t("scheme-light",[["color-scheme","light"]]),t("scheme-light-dark",[["color-scheme","light dark"]]),t("scheme-only-dark",[["color-scheme","only dark"]]),t("scheme-only-light",[["color-scheme","only light"]]),n("columns",{themeKeys:["--columns","--container"],handleBareValue:({value:a})=>D(a)?a:null,handle:a=>[s("columns",a)],staticValues:{auto:[s("columns","auto")]}}),i("columns",()=>[{values:Array.from({length:12},(a,g)=>`${g+1}`),valueThemeKeys:["--columns","--container"]}]);for(let a of["auto","avoid","all","avoid-page","page","left","right","column"])t(`break-before-${a}`,[["break-before",a]]);for(let a of["auto","avoid","avoid-page","avoid-column"])t(`break-inside-${a}`,[["break-inside",a]]);for(let a of["auto","avoid","all","avoid-page","page","left","right","column"])t(`break-after-${a}`,[["break-after",a]]);t("grid-flow-row",[["grid-auto-flow","row"]]),t("grid-flow-col",[["grid-auto-flow","column"]]),t("grid-flow-dense",[["grid-auto-flow","dense"]]),t("grid-flow-row-dense",[["grid-auto-flow","row dense"]]),t("grid-flow-col-dense",[["grid-auto-flow","column dense"]]),n("auto-cols",{themeKeys:["--grid-auto-columns"],handleBareValue:({value:a})=>!e.resolve(null,["--spacing"])||!te(a)?null:`--spacing(${a})`,handle:a=>[s("grid-auto-columns",a)],staticValues:{auto:[s("grid-auto-columns","auto")],min:[s("grid-auto-columns","min-content")],max:[s("grid-auto-columns","max-content")],fr:[s("grid-auto-columns","minmax(0, 1fr)")]}}),n("auto-rows",{themeKeys:["--grid-auto-rows"],handleBareValue:({value:a})=>!e.resolve(null,["--spacing"])||!te(a)?null:`--spacing(${a})`,handle:a=>[s("grid-auto-rows",a)],staticValues:{auto:[s("grid-auto-rows","auto")],min:[s("grid-auto-rows","min-content")],max:[s("grid-auto-rows","max-content")],fr:[s("grid-auto-rows","minmax(0, 1fr)")]}}),n("grid-cols",{themeKeys:["--grid-template-columns"],handleBareValue:({value:a})=>xr(a)?`repeat(${a}, minmax(0, 1fr))`:null,handle:a=>[s("grid-template-columns",a)],staticValues:{none:[s("grid-template-columns","none")],subgrid:[s("grid-template-columns","subgrid")]}}),n("grid-rows",{themeKeys:["--grid-template-rows"],handleBareValue:({value:a})=>xr(a)?`repeat(${a}, minmax(0, 1fr))`:null,handle:a=>[s("grid-template-rows",a)],staticValues:{none:[s("grid-template-rows","none")],subgrid:[s("grid-template-rows","subgrid")]}}),i("grid-cols",()=>[{values:Array.from({length:12},(a,g)=>`${g+1}`),valueThemeKeys:["--grid-template-columns"]}]),i("grid-rows",()=>[{values:Array.from({length:12},(a,g)=>`${g+1}`),valueThemeKeys:["--grid-template-rows"]}]),t("flex-row",[["flex-direction","row"]]),t("flex-row-reverse",[["flex-direction","row-reverse"]]),t("flex-col",[["flex-direction","column"]]),t("flex-col-reverse",[["flex-direction","column-reverse"]]),t("flex-wrap",[["flex-wrap","wrap"]]),t("flex-nowrap",[["flex-wrap","nowrap"]]),t("flex-wrap-reverse",[["flex-wrap","wrap-reverse"]]),t("place-content-center",[["place-content","center"]]),t("place-content-start",[["place-content","start"]]),t("place-content-end",[["place-content","end"]]),t("place-content-center-safe",[["place-content","safe center"]]),t("place-content-end-safe",[["place-content","safe end"]]),t("place-content-between",[["place-content","space-between"]]),t("place-content-around",[["place-content","space-around"]]),t("place-content-evenly",[["place-content","space-evenly"]]),t("place-content-baseline",[["place-content","baseline"]]),t("place-content-stretch",[["place-content","stretch"]]),t("place-items-center",[["place-items","center"]]),t("place-items-start",[["place-items","start"]]),t("place-items-end",[["place-items","end"]]),t("place-items-center-safe",[["place-items","safe center"]]),t("place-items-end-safe",[["place-items","safe end"]]),t("place-items-baseline",[["place-items","baseline"]]),t("place-items-stretch",[["place-items","stretch"]]),t("content-normal",[["align-content","normal"]]),t("content-center",[["align-content","center"]]),t("content-start",[["align-content","flex-start"]]),t("content-end",[["align-content","flex-end"]]),t("content-center-safe",[["align-content","safe center"]]),t("content-end-safe",[["align-content","safe flex-end"]]),t("content-between",[["align-content","space-between"]]),t("content-around",[["align-content","space-around"]]),t("content-evenly",[["align-content","space-evenly"]]),t("content-baseline",[["align-content","baseline"]]),t("content-stretch",[["align-content","stretch"]]),t("items-center",[["align-items","center"]]),t("items-start",[["align-items","flex-start"]]),t("items-end",[["align-items","flex-end"]]),t("items-center-safe",[["align-items","safe center"]]),t("items-end-safe",[["align-items","safe flex-end"]]),t("items-baseline",[["align-items","baseline"]]),t("items-baseline-last",[["align-items","last baseline"]]),t("items-stretch",[["align-items","stretch"]]),t("justify-normal",[["justify-content","normal"]]),t("justify-center",[["justify-content","center"]]),t("justify-start",[["justify-content","flex-start"]]),t("justify-end",[["justify-content","flex-end"]]),t("justify-center-safe",[["justify-content","safe center"]]),t("justify-end-safe",[["justify-content","safe flex-end"]]),t("justify-between",[["justify-content","space-between"]]),t("justify-around",[["justify-content","space-around"]]),t("justify-evenly",[["justify-content","space-evenly"]]),t("justify-baseline",[["justify-content","baseline"]]),t("justify-stretch",[["justify-content","stretch"]]),t("justify-items-normal",[["justify-items","normal"]]),t("justify-items-center",[["justify-items","center"]]),t("justify-items-start",[["justify-items","start"]]),t("justify-items-end",[["justify-items","end"]]),t("justify-items-center-safe",[["justify-items","safe center"]]),t("justify-items-end-safe",[["justify-items","safe end"]]),t("justify-items-stretch",[["justify-items","stretch"]]),l("gap",["--gap","--spacing"],a=>[s("gap",a)]),l("gap-x",["--gap","--spacing"],a=>[s("column-gap",a)]),l("gap-y",["--gap","--spacing"],a=>[s("row-gap",a)]),l("space-x",["--space","--spacing"],a=>{let g=(()=>{if(a==="--spacing(0)"||a==="--spacing(-0)")return!0;let v=oe.get(a);return!!(v&&v[0]===0&&(v[1]===null||Se(a)))})();return[G([T("--tw-space-x-reverse","0")]),Q(":where(& > :not(:last-child))",[s("--tw-sort","row-gap"),s("--tw-space-x-reverse","0"),s("margin-inline-start",g?"0":`calc(${a} * var(--tw-space-x-reverse))`),s("margin-inline-end",g?"0":`calc(${a} * calc(1 - var(--tw-space-x-reverse)))`)])]},{supportsNegative:!0}),l("space-y",["--space","--spacing"],a=>{let g=(()=>{if(a==="--spacing(0)"||a==="--spacing(-0)")return!0;let v=oe.get(a);return!!(v&&v[0]===0&&(v[1]===null||Se(a)))})();return[G([T("--tw-space-y-reverse","0")]),Q(":where(& > :not(:last-child))",[s("--tw-sort","column-gap"),s("--tw-space-y-reverse","0"),s("margin-block-start",g?"0":`calc(${a} * var(--tw-space-y-reverse))`),s("margin-block-end",g?"0":`calc(${a} * calc(1 - var(--tw-space-y-reverse)))`)])]},{supportsNegative:!0}),t("space-x-reverse",[()=>G([T("--tw-space-x-reverse","0")]),()=>Q(":where(& > :not(:last-child))",[s("--tw-sort","row-gap"),s("--tw-space-x-reverse","1")])]),t("space-y-reverse",[()=>G([T("--tw-space-y-reverse","0")]),()=>Q(":where(& > :not(:last-child))",[s("--tw-sort","column-gap"),s("--tw-space-y-reverse","1")])]),t("accent-auto",[["accent-color","auto"]]),o("accent",{themeKeys:["--accent-color","--color"],handle:a=>[s("accent-color",a)]}),o("caret",{themeKeys:["--caret-color","--color"],handle:a=>[s("caret-color",a)]}),o("divide",{themeKeys:["--divide-color","--border-color","--color"],handle:a=>[Q(":where(& > :not(:last-child))",[s("--tw-sort","divide-color"),s("border-color",a)])]}),t("place-self-auto",[["place-self","auto"]]),t("place-self-start",[["place-self","start"]]),t("place-self-end",[["place-self","end"]]),t("place-self-center",[["place-self","center"]]),t("place-self-end-safe",[["place-self","safe end"]]),t("place-self-center-safe",[["place-self","safe center"]]),t("place-self-stretch",[["place-self","stretch"]]),t("self-auto",[["align-self","auto"]]),t("self-start",[["align-self","flex-start"]]),t("self-end",[["align-self","flex-end"]]),t("self-center",[["align-self","center"]]),t("self-end-safe",[["align-self","safe flex-end"]]),t("self-center-safe",[["align-self","safe center"]]),t("self-stretch",[["align-self","stretch"]]),t("self-baseline",[["align-self","baseline"]]),t("self-baseline-last",[["align-self","last baseline"]]),t("justify-self-auto",[["justify-self","auto"]]),t("justify-self-start",[["justify-self","flex-start"]]),t("justify-self-end",[["justify-self","flex-end"]]),t("justify-self-center",[["justify-self","center"]]),t("justify-self-end-safe",[["justify-self","safe flex-end"]]),t("justify-self-center-safe",[["justify-self","safe center"]]),t("justify-self-stretch",[["justify-self","stretch"]]);for(let a of["auto","hidden","clip","visible","scroll"])t(`overflow-${a}`,[["overflow",a]]),t(`overflow-x-${a}`,[["overflow-x",a]]),t(`overflow-y-${a}`,[["overflow-y",a]]);for(let a of["auto","contain","none"])t(`overscroll-${a}`,[["overscroll-behavior",a]]),t(`overscroll-x-${a}`,[["overscroll-behavior-x",a]]),t(`overscroll-y-${a}`,[["overscroll-behavior-y",a]]);t("scroll-auto",[["scroll-behavior","auto"]]),t("scroll-smooth",[["scroll-behavior","smooth"]]),t("scrollbar-auto",[["scrollbar-width","auto"]]),t("scrollbar-thin",[["scrollbar-width","thin"]]),t("scrollbar-none",[["scrollbar-width","none"]]);{let a=()=>G([T("--tw-scrollbar-thumb","#0000",""),T("--tw-scrollbar-track","#0000","")]);o("scrollbar-thumb",{themeKeys:["--color"],handle:g=>[a(),s("--tw-scrollbar-thumb",g),s("scrollbar-color","var(--tw-scrollbar-thumb) var(--tw-scrollbar-track)")]}),o("scrollbar-track",{themeKeys:["--color"],handle:g=>[a(),s("--tw-scrollbar-track",g),s("scrollbar-color","var(--tw-scrollbar-thumb) var(--tw-scrollbar-track)")]})}t("scrollbar-gutter-auto",[["scrollbar-gutter","auto"]]),t("scrollbar-gutter-stable",[["scrollbar-gutter","stable"]]),t("scrollbar-gutter-both",[["scrollbar-gutter","stable both-edges"]]),t("truncate",[["overflow","hidden"],["text-overflow","ellipsis"],["white-space","nowrap"]]),t("text-ellipsis",[["text-overflow","ellipsis"]]),t("text-clip",[["text-overflow","clip"]]),t("hyphens-none",[["-webkit-hyphens","none"],["hyphens","none"]]),t("hyphens-manual",[["-webkit-hyphens","manual"],["hyphens","manual"]]),t("hyphens-auto",[["-webkit-hyphens","auto"],["hyphens","auto"]]),t("whitespace-normal",[["white-space","normal"]]),t("whitespace-nowrap",[["white-space","nowrap"]]),t("whitespace-pre",[["white-space","pre"]]),t("whitespace-pre-line",[["white-space","pre-line"]]),t("whitespace-pre-wrap",[["white-space","pre-wrap"]]),t("whitespace-break-spaces",[["white-space","break-spaces"]]),n("tab",{handleBareValue:({value:a})=>D(a)?a:null,handle:a=>[s("tab-size",a)]}),i("tab",()=>[{values:["2","4","8"]}]),t("text-wrap",[["text-wrap","wrap"]]),t("text-nowrap",[["text-wrap","nowrap"]]),t("text-balance",[["text-wrap","balance"]]),t("text-pretty",[["text-wrap","pretty"]]),t("break-normal",[["overflow-wrap","normal"],["word-break","normal"]]),t("break-all",[["word-break","break-all"]]),t("break-keep",[["word-break","keep-all"]]),t("wrap-anywhere",[["overflow-wrap","anywhere"]]),t("wrap-break-word",[["overflow-wrap","break-word"]]),t("wrap-normal",[["overflow-wrap","normal"]]);for(let[a,g]of[["rounded",["border-radius"]],["rounded-s",["border-start-start-radius","border-end-start-radius"]],["rounded-e",["border-start-end-radius","border-end-end-radius"]],["rounded-t",["border-top-left-radius","border-top-right-radius"]],["rounded-r",["border-top-right-radius","border-bottom-right-radius"]],["rounded-b",["border-bottom-right-radius","border-bottom-left-radius"]],["rounded-l",["border-top-left-radius","border-bottom-left-radius"]],["rounded-ss",["border-start-start-radius"]],["rounded-se",["border-start-end-radius"]],["rounded-ee",["border-end-end-radius"]],["rounded-es",["border-end-start-radius"]],["rounded-tl",["border-top-left-radius"]],["rounded-tr",["border-top-right-radius"]],["rounded-br",["border-bottom-right-radius"]],["rounded-bl",["border-bottom-left-radius"]]])n(a,{themeKeys:["--radius"],handle:v=>g.map(S=>s(S,v)),staticValues:{none:g.map(v=>s(v,"0")),full:g.map(v=>s(v,"calc(infinity * 1px)"))}});t("border-solid",[["--tw-border-style","solid"],["border-style","solid"]]),t("border-dashed",[["--tw-border-style","dashed"],["border-style","dashed"]]),t("border-dotted",[["--tw-border-style","dotted"],["border-style","dotted"]]),t("border-double",[["--tw-border-style","double"],["border-style","double"]]),t("border-hidden",[["--tw-border-style","hidden"],["border-style","hidden"]]),t("border-none",[["--tw-border-style","none"],["border-style","none"]]);{let g=function(v,S){r.functional(v,x=>{if(!x.value){if(x.modifier)return;let $=e.get(["--default-border-width"])??"1px",M=S.width($);return M?[a(),...M]:void 0}if(x.value.kind==="arbitrary"){let $=x.value.value;switch(x.value.dataType??X($,["color","line-width","length"])){case"line-width":case"length":{if(x.modifier)return;let N=S.width($);return N?[a(),...N]:void 0}default:return $=ne($,x.modifier,e),$===null?void 0:S.color($)}}{let $=ae(x,e,["--border-color","--color"]);if($)return S.color($)}{if(x.modifier)return;let $=e.resolve(x.value.value,["--border-width"]);if($){let M=S.width($);return M?[a(),...M]:void 0}if(D(x.value.value)){let M=S.width(`${x.value.value}px`);return M?[a(),...M]:void 0}}}),i(v,()=>[{values:["current","inherit","transparent"],valueThemeKeys:["--border-color","--color"],modifierThemeKeys:["--opacity"],modifiers:Array.from({length:21},(x,$)=>`${$*5}`),hasDefaultValue:!0},{values:["0","2","4","8"],valueThemeKeys:["--border-width"]}])};var R=g;let a=()=>G([T("--tw-border-style","solid")]);g("border",{width:v=>[s("border-style","var(--tw-border-style)"),s("border-width",v)],color:v=>[s("border-color",v)]}),g("border-x",{width:v=>[s("border-inline-style","var(--tw-border-style)"),s("border-inline-width",v)],color:v=>[s("border-inline-color",v)]}),g("border-y",{width:v=>[s("border-block-style","var(--tw-border-style)"),s("border-block-width",v)],color:v=>[s("border-block-color",v)]}),g("border-s",{width:v=>[s("border-inline-start-style","var(--tw-border-style)"),s("border-inline-start-width",v)],color:v=>[s("border-inline-start-color",v)]}),g("border-e",{width:v=>[s("border-inline-end-style","var(--tw-border-style)"),s("border-inline-end-width",v)],color:v=>[s("border-inline-end-color",v)]}),g("border-bs",{width:v=>[s("border-block-start-style","var(--tw-border-style)"),s("border-block-start-width",v)],color:v=>[s("border-block-start-color",v)]}),g("border-be",{width:v=>[s("border-block-end-style","var(--tw-border-style)"),s("border-block-end-width",v)],color:v=>[s("border-block-end-color",v)]}),g("border-t",{width:v=>[s("border-top-style","var(--tw-border-style)"),s("border-top-width",v)],color:v=>[s("border-top-color",v)]}),g("border-r",{width:v=>[s("border-right-style","var(--tw-border-style)"),s("border-right-width",v)],color:v=>[s("border-right-color",v)]}),g("border-b",{width:v=>[s("border-bottom-style","var(--tw-border-style)"),s("border-bottom-width",v)],color:v=>[s("border-bottom-color",v)]}),g("border-l",{width:v=>[s("border-left-style","var(--tw-border-style)"),s("border-left-width",v)],color:v=>[s("border-left-color",v)]}),n("divide-x",{defaultValue:e.get(["--default-border-width"])??"1px",themeKeys:["--divide-width","--border-width"],handleBareValue:({value:v})=>D(v)?`${v}px`:null,handle:v=>[G([T("--tw-divide-x-reverse","0")]),Q(":where(& > :not(:last-child))",[s("--tw-sort","divide-x-width"),a(),s("--tw-divide-x-reverse","0"),s("border-inline-style","var(--tw-border-style)"),s("border-inline-start-width",`calc(${v} * var(--tw-divide-x-reverse))`),s("border-inline-end-width",`calc(${v} * calc(1 - var(--tw-divide-x-reverse)))`)])]}),n("divide-y",{defaultValue:e.get(["--default-border-width"])??"1px",themeKeys:["--divide-width","--border-width"],handleBareValue:({value:v})=>D(v)?`${v}px`:null,handle:v=>[G([T("--tw-divide-y-reverse","0")]),Q(":where(& > :not(:last-child))",[s("--tw-sort","divide-y-width"),a(),s("--tw-divide-y-reverse","0"),s("border-bottom-style","var(--tw-border-style)"),s("border-top-style","var(--tw-border-style)"),s("border-top-width",`calc(${v} * var(--tw-divide-y-reverse))`),s("border-bottom-width",`calc(${v} * calc(1 - var(--tw-divide-y-reverse)))`)])]}),i("divide-x",()=>[{values:["0","2","4","8"],valueThemeKeys:["--divide-width","--border-width"],hasDefaultValue:!0}]),i("divide-y",()=>[{values:["0","2","4","8"],valueThemeKeys:["--divide-width","--border-width"],hasDefaultValue:!0}]),t("divide-x-reverse",[()=>G([T("--tw-divide-x-reverse","0")]),()=>Q(":where(& > :not(:last-child))",[s("--tw-divide-x-reverse","1")])]),t("divide-y-reverse",[()=>G([T("--tw-divide-y-reverse","0")]),()=>Q(":where(& > :not(:last-child))",[s("--tw-divide-y-reverse","1")])]);for(let v of["solid","dashed","dotted","double","none"])t(`divide-${v}`,[()=>Q(":where(& > :not(:last-child))",[s("--tw-sort","divide-style"),s("--tw-border-style",v),s("border-style",v)])])}t("bg-auto",[["background-size","auto"]]),t("bg-cover",[["background-size","cover"]]),t("bg-contain",[["background-size","contain"]]),n("bg-size",{handle(a){if(a)return[s("background-size",a)]}}),t("bg-fixed",[["background-attachment","fixed"]]),t("bg-local",[["background-attachment","local"]]),t("bg-scroll",[["background-attachment","scroll"]]),t("bg-top",[["background-position","top"]]),t("bg-top-left",[["background-position","left top"]]),t("bg-top-right",[["background-position","right top"]]),t("bg-bottom",[["background-position","bottom"]]),t("bg-bottom-left",[["background-position","left bottom"]]),t("bg-bottom-right",[["background-position","right bottom"]]),t("bg-left",[["background-position","left"]]),t("bg-right",[["background-position","right"]]),t("bg-center",[["background-position","center"]]),n("bg-position",{handle(a){if(a)return[s("background-position",a)]}}),t("bg-repeat",[["background-repeat","repeat"]]),t("bg-no-repeat",[["background-repeat","no-repeat"]]),t("bg-repeat-x",[["background-repeat","repeat-x"]]),t("bg-repeat-y",[["background-repeat","repeat-y"]]),t("bg-repeat-round",[["background-repeat","round"]]),t("bg-repeat-space",[["background-repeat","space"]]),t("bg-none",[["background-image","none"]]);{let v=function($){let M="in oklab";if($?.kind==="named")switch($.value){case"longer":case"shorter":case"increasing":case"decreasing":M=`in oklch ${$.value} hue`;break;default:M=`in ${$.value}`}else $?.kind==="arbitrary"&&(M=$.value);return M},S=function({negative:$}){return M=>{if(!M.value)return;if(M.value.kind==="arbitrary"){if(M.modifier)return;let q=M.value.value;return(M.value.dataType??X(q,["angle"]))==="angle"?(q=$?`calc(${q} * -1)`:`${q}`,[s("--tw-gradient-position",q),s("background-image",`linear-gradient(var(--tw-gradient-stops,${q}))`)]):$?void 0:[s("--tw-gradient-position",q),s("background-image",`linear-gradient(var(--tw-gradient-stops,${q}))`)]}let N=M.value.value;if(!$&&g.has(N))N=g.get(N);else if(D(N))N=$?`calc(${N}deg * -1)`:`${N}deg`;else return;let _=v(M.modifier);return[s("--tw-gradient-position",`${N}`),J("@supports (background-image: linear-gradient(in lab, red, red))",[s("--tw-gradient-position",`${N} ${_}`)]),s("background-image","linear-gradient(var(--tw-gradient-stops))")]}},x=function({negative:$}){return M=>{if(M.value?.kind==="arbitrary"){if(M.modifier)return;let q=M.value.value;return[s("--tw-gradient-position",q),s("background-image",`conic-gradient(var(--tw-gradient-stops,${q}))`)]}let N=v(M.modifier);if(!M.value)return[s("--tw-gradient-position",N),s("background-image","conic-gradient(var(--tw-gradient-stops))")];let _=M.value.value;if(D(_))return _=$?`calc(${_}deg * -1)`:`${_}deg`,[s("--tw-gradient-position",`from ${_} ${N}`),s("background-image","conic-gradient(var(--tw-gradient-stops))")]}};var W=v,U=S,z=x;let a=["oklab","oklch","srgb","hsl","longer","shorter","increasing","decreasing"],g=new Map([["to-t","to top"],["to-tr","to top right"],["to-r","to right"],["to-br","to bottom right"],["to-b","to bottom"],["to-bl","to bottom left"],["to-l","to left"],["to-tl","to top left"]]);r.functional("-bg-linear",S({negative:!0})),r.functional("bg-linear",S({negative:!1})),i("bg-linear",()=>[{values:[...g.keys()],modifiers:a},{values:["0","30","60","90","120","150","180","210","240","270","300","330"],supportsNegative:!0,modifiers:a}]),r.functional("-bg-conic",x({negative:!0})),r.functional("bg-conic",x({negative:!1})),i("bg-conic",()=>[{hasDefaultValue:!0,modifiers:a},{values:["0","30","60","90","120","150","180","210","240","270","300","330"],supportsNegative:!0,modifiers:a}]),r.functional("bg-radial",$=>{if(!$.value){let M=v($.modifier);return[s("--tw-gradient-position",M),s("background-image","radial-gradient(var(--tw-gradient-stops))")]}if($.value.kind==="arbitrary"){if($.modifier)return;let M=$.value.value;return[s("--tw-gradient-position",M),s("background-image",`radial-gradient(var(--tw-gradient-stops,${M}))`)]}}),i("bg-radial",()=>[{hasDefaultValue:!0,modifiers:a}])}r.functional("bg",a=>{if(a.value){if(a.value.kind==="arbitrary"){let g=a.value.value;switch(a.value.dataType??X(g,["image","color","percentage","position","bg-size","length","url"])){case"percentage":case"position":return a.modifier?void 0:[s("background-position",g)];case"bg-size":case"length":case"size":return a.modifier?void 0:[s("background-size",g)];case"image":case"url":return a.modifier?void 0:[s("background-image",g)];default:return g=ne(g,a.modifier,e),g===null?void 0:[s("background-color",g)]}}{let g=ae(a,e,["--background-color","--color"]);if(g)return[s("background-color",g)]}{if(a.modifier)return;let g=e.resolve(a.value.value,["--background-image"]);if(g)return[s("background-image",g)]}}}),i("bg",()=>[{values:["current","inherit","transparent"],valueThemeKeys:["--background-color","--color"],modifierThemeKeys:["--opacity"],modifiers:Array.from({length:21},(a,g)=>`${g*5}`)},{values:[],valueThemeKeys:["--background-image"]}]);let k=()=>G([T("--tw-gradient-position"),T("--tw-gradient-from","#0000",""),T("--tw-gradient-via","#0000",""),T("--tw-gradient-to","#0000",""),T("--tw-gradient-stops"),T("--tw-gradient-via-stops"),T("--tw-gradient-from-position","0%",""),T("--tw-gradient-via-position","50%",""),T("--tw-gradient-to-position","100%","")]);function w(a,g){r.functional(a,v=>{if(v.value){if(v.value.kind==="arbitrary"){let S=v.value.value;switch(v.value.dataType??X(S,["color","length","percentage"])){case"length":case"percentage":return v.modifier?void 0:g.position(S);default:return S=ne(S,v.modifier,e),S===null?void 0:g.color(S)}}{let S=ae(v,e,["--background-color","--color"]);if(S)return g.color(S)}{if(v.modifier)return;let S=e.resolve(v.value.value,["--gradient-color-stop-positions"]);if(S)return g.position(S);if(v.value.value[v.value.value.length-1]==="%"&&D(v.value.value.slice(0,-1)))return g.position(v.value.value)}}}),i(a,()=>[{values:["current","inherit","transparent"],valueThemeKeys:["--background-color","--color"],modifierThemeKeys:["--opacity"],modifiers:Array.from({length:21},(v,S)=>`${S*5}`)},{values:Array.from({length:21},(v,S)=>`${S*5}%`),valueThemeKeys:["--gradient-color-stop-positions"]}])}w("from",{color:a=>[k(),s("--tw-sort","--tw-gradient-from"),s("--tw-gradient-from",a),s("--tw-gradient-stops","var(--tw-gradient-via-stops, var(--tw-gradient-position), var(--tw-gradient-from) var(--tw-gradient-from-position), var(--tw-gradient-to) var(--tw-gradient-to-position))")],position:a=>[k(),s("--tw-gradient-from-position",a)]}),t("via-none",[["--tw-gradient-via-stops","initial"]]),w("via",{color:a=>[k(),s("--tw-sort","--tw-gradient-via"),s("--tw-gradient-via",a),s("--tw-gradient-via-stops","var(--tw-gradient-position), var(--tw-gradient-from) var(--tw-gradient-from-position), var(--tw-gradient-via) var(--tw-gradient-via-position), var(--tw-gradient-to) var(--tw-gradient-to-position)"),s("--tw-gradient-stops","var(--tw-gradient-via-stops)")],position:a=>[k(),s("--tw-gradient-via-position",a)]}),w("to",{color:a=>[k(),s("--tw-sort","--tw-gradient-to"),s("--tw-gradient-to",a),s("--tw-gradient-stops","var(--tw-gradient-via-stops, var(--tw-gradient-position), var(--tw-gradient-from) var(--tw-gradient-from-position), var(--tw-gradient-to) var(--tw-gradient-to-position))")],position:a=>[k(),s("--tw-gradient-to-position",a)]}),t("mask-none",[["mask-image","none"]]),r.functional("mask",a=>{if(!a.value||a.modifier||a.value.kind!=="arbitrary")return;let g=a.value.value;switch(a.value.dataType??X(g,["image","percentage","position","bg-size","length","url"])){case"percentage":case"position":return a.modifier?void 0:[s("mask-position",g)];case"bg-size":case"length":case"size":return[s("mask-size",g)];default:return[s("mask-image",g)]}}),t("mask-add",[["mask-composite","add"]]),t("mask-subtract",[["mask-composite","subtract"]]),t("mask-intersect",[["mask-composite","intersect"]]),t("mask-exclude",[["mask-composite","exclude"]]),t("mask-alpha",[["mask-mode","alpha"]]),t("mask-luminance",[["mask-mode","luminance"]]),t("mask-match",[["mask-mode","match-source"]]),t("mask-type-alpha",[["mask-type","alpha"]]),t("mask-type-luminance",[["mask-type","luminance"]]),t("mask-auto",[["mask-size","auto"]]),t("mask-cover",[["mask-size","cover"]]),t("mask-contain",[["mask-size","contain"]]),n("mask-size",{handle(a){if(a)return[s("mask-size",a)]}}),t("mask-top",[["mask-position","top"]]),t("mask-top-left",[["mask-position","left top"]]),t("mask-top-right",[["mask-position","right top"]]),t("mask-bottom",[["mask-position","bottom"]]),t("mask-bottom-left",[["mask-position","left bottom"]]),t("mask-bottom-right",[["mask-position","right bottom"]]),t("mask-left",[["mask-position","left"]]),t("mask-right",[["mask-position","right"]]),t("mask-center",[["mask-position","center"]]),n("mask-position",{handle(a){if(a)return[s("mask-position",a)]}}),t("mask-repeat",[["mask-repeat","repeat"]]),t("mask-no-repeat",[["mask-repeat","no-repeat"]]),t("mask-repeat-x",[["mask-repeat","repeat-x"]]),t("mask-repeat-y",[["mask-repeat","repeat-y"]]),t("mask-repeat-round",[["mask-repeat","round"]]),t("mask-repeat-space",[["mask-repeat","space"]]),t("mask-clip-border",[["mask-clip","border-box"]]),t("mask-clip-padding",[["mask-clip","padding-box"]]),t("mask-clip-content",[["mask-clip","content-box"]]),t("mask-clip-fill",[["mask-clip","fill-box"]]),t("mask-clip-stroke",[["mask-clip","stroke-box"]]),t("mask-clip-view",[["mask-clip","view-box"]]),t("mask-no-clip",[["mask-clip","no-clip"]]),t("mask-origin-border",[["mask-origin","border-box"]]),t("mask-origin-padding",[["mask-origin","padding-box"]]),t("mask-origin-content",[["mask-origin","content-box"]]),t("mask-origin-fill",[["mask-origin","fill-box"]]),t("mask-origin-stroke",[["mask-origin","stroke-box"]]),t("mask-origin-view",[["mask-origin","view-box"]]);let b=()=>G([T("--tw-mask-linear","linear-gradient(#fff, #fff)"),T("--tw-mask-radial","linear-gradient(#fff, #fff)"),T("--tw-mask-conic","linear-gradient(#fff, #fff)")]);function A(a,g){r.functional(a,v=>{if(v.value){if(v.value.kind==="arbitrary"){let S=v.value.value;switch(v.value.dataType??X(S,["length","percentage","color"])){case"color":return S=ne(S,v.modifier,e),S===null?void 0:g.color(S);case"percentage":return v.modifier||!D(S.slice(0,-1))?void 0:g.position(S);default:return v.modifier?void 0:g.position(S)}}{let S=ae(v,e,["--background-color","--color"]);if(S)return g.color(S)}{if(v.modifier)return;let S=X(v.value.value,["number","percentage"]);if(!S)return;switch(S){case"number":return!e.resolve(null,["--spacing"])||!te(v.value.value)?void 0:g.position(`--spacing(${v.value.value})`);case"percentage":return D(v.value.value.slice(0,-1))?g.position(v.value.value):void 0;default:return}}}}),i(a,()=>[{values:["current","inherit","transparent"],valueThemeKeys:["--background-color","--color"],modifierThemeKeys:["--opacity"],modifiers:Array.from({length:21},(v,S)=>`${S*5}`)},{values:Array.from({length:21},(v,S)=>`${S*5}%`),valueThemeKeys:["--gradient-color-stop-positions"]}]),i(a,()=>[{values:Array.from({length:21},(v,S)=>`${S*5}%`)},{values:e.get(["--spacing"])?Ut:[]},{values:["current","inherit","transparent"],valueThemeKeys:["--background-color","--color"],modifierThemeKeys:["--opacity"],modifiers:Array.from({length:21},(v,S)=>`${S*5}`)}])}let C=()=>G([T("--tw-mask-left","linear-gradient(#fff, #fff)"),T("--tw-mask-right","linear-gradient(#fff, #fff)"),T("--tw-mask-bottom","linear-gradient(#fff, #fff)"),T("--tw-mask-top","linear-gradient(#fff, #fff)")]);function y(a,g,v){A(a,{color(S){let x=[b(),C(),s("mask-image","var(--tw-mask-linear), var(--tw-mask-radial), var(--tw-mask-conic)"),s("mask-composite","intersect"),s("--tw-mask-linear","var(--tw-mask-left), var(--tw-mask-right), var(--tw-mask-bottom), var(--tw-mask-top)")];for(let $ of["top","right","bottom","left"])v[$]&&(x.push(s(`--tw-mask-${$}`,`linear-gradient(to ${$}, var(--tw-mask-${$}-from-color) var(--tw-mask-${$}-from-position), var(--tw-mask-${$}-to-color) var(--tw-mask-${$}-to-position))`)),x.push(G([T(`--tw-mask-${$}-from-position`,"0%"),T(`--tw-mask-${$}-to-position`,"100%"),T(`--tw-mask-${$}-from-color`,"black"),T(`--tw-mask-${$}-to-color`,"transparent")])),x.push(s(`--tw-mask-${$}-${g}-color`,S)));return x},position(S){let x=[b(),C(),s("mask-image","var(--tw-mask-linear), var(--tw-mask-radial), var(--tw-mask-conic)"),s("mask-composite","intersect"),s("--tw-mask-linear","var(--tw-mask-left), var(--tw-mask-right), var(--tw-mask-bottom), var(--tw-mask-top)")];for(let $ of["top","right","bottom","left"])v[$]&&(x.push(s(`--tw-mask-${$}`,`linear-gradient(to ${$}, var(--tw-mask-${$}-from-color) var(--tw-mask-${$}-from-position), var(--tw-mask-${$}-to-color) var(--tw-mask-${$}-to-position))`)),x.push(G([T(`--tw-mask-${$}-from-position`,"0%"),T(`--tw-mask-${$}-to-position`,"100%"),T(`--tw-mask-${$}-from-color`,"black"),T(`--tw-mask-${$}-to-color`,"transparent")])),x.push(s(`--tw-mask-${$}-${g}-position`,S)));return x}})}y("mask-x-from","from",{top:!1,right:!0,bottom:!1,left:!0}),y("mask-x-to","to",{top:!1,right:!0,bottom:!1,left:!0}),y("mask-y-from","from",{top:!0,right:!1,bottom:!0,left:!1}),y("mask-y-to","to",{top:!0,right:!1,bottom:!0,left:!1}),y("mask-t-from","from",{top:!0,right:!1,bottom:!1,left:!1}),y("mask-t-to","to",{top:!0,right:!1,bottom:!1,left:!1}),y("mask-r-from","from",{top:!1,right:!0,bottom:!1,left:!1}),y("mask-r-to","to",{top:!1,right:!0,bottom:!1,left:!1}),y("mask-b-from","from",{top:!1,right:!1,bottom:!0,left:!1}),y("mask-b-to","to",{top:!1,right:!1,bottom:!0,left:!1}),y("mask-l-from","from",{top:!1,right:!1,bottom:!1,left:!0}),y("mask-l-to","to",{top:!1,right:!1,bottom:!1,left:!0});let E=()=>G([T("--tw-mask-linear-position","0deg"),T("--tw-mask-linear-from-position","0%"),T("--tw-mask-linear-to-position","100%"),T("--tw-mask-linear-from-color","black"),T("--tw-mask-linear-to-color","transparent")]);n("mask-linear",{defaultValue:null,supportsNegative:!0,supportsFractions:!1,handleBareValue({value:a}){if(!D(a))return null;let g=Number(a);return g===0?"0deg":g===1?"1deg":`calc(1deg * ${a})`},handleNegativeBareValue({value:a}){if(!D(a))return null;let g=Number(a);return g===0?"0deg":g===1?"-1deg":`calc(1deg * -${a})`},handle:a=>[b(),E(),s("mask-image","var(--tw-mask-linear), var(--tw-mask-radial), var(--tw-mask-conic)"),s("mask-composite","intersect"),s("--tw-mask-linear","linear-gradient(var(--tw-mask-linear-stops, var(--tw-mask-linear-position)))"),s("--tw-mask-linear-position",a)]}),i("mask-linear",()=>[{supportsNegative:!0,values:["0","1","2","3","6","12","45","90","180"]}]),A("mask-linear-from",{color:a=>[b(),E(),s("mask-image","var(--tw-mask-linear), var(--tw-mask-radial), var(--tw-mask-conic)"),s("mask-composite","intersect"),s("--tw-mask-linear-stops","var(--tw-mask-linear-position), var(--tw-mask-linear-from-color) var(--tw-mask-linear-from-position), var(--tw-mask-linear-to-color) var(--tw-mask-linear-to-position)"),s("--tw-mask-linear","linear-gradient(var(--tw-mask-linear-stops))"),s("--tw-mask-linear-from-color",a)],position:a=>[b(),E(),s("mask-image","var(--tw-mask-linear), var(--tw-mask-radial), var(--tw-mask-conic)"),s("mask-composite","intersect"),s("--tw-mask-linear-stops","var(--tw-mask-linear-position), var(--tw-mask-linear-from-color) var(--tw-mask-linear-from-position), var(--tw-mask-linear-to-color) var(--tw-mask-linear-to-position)"),s("--tw-mask-linear","linear-gradient(var(--tw-mask-linear-stops))"),s("--tw-mask-linear-from-position",a)]}),A("mask-linear-to",{color:a=>[b(),E(),s("mask-image","var(--tw-mask-linear), var(--tw-mask-radial), var(--tw-mask-conic)"),s("mask-composite","intersect"),s("--tw-mask-linear-stops","var(--tw-mask-linear-position), var(--tw-mask-linear-from-color) var(--tw-mask-linear-from-position), var(--tw-mask-linear-to-color) var(--tw-mask-linear-to-position)"),s("--tw-mask-linear","linear-gradient(var(--tw-mask-linear-stops))"),s("--tw-mask-linear-to-color",a)],position:a=>[b(),E(),s("mask-image","var(--tw-mask-linear), var(--tw-mask-radial), var(--tw-mask-conic)"),s("mask-composite","intersect"),s("--tw-mask-linear-stops","var(--tw-mask-linear-position), var(--tw-mask-linear-from-color) var(--tw-mask-linear-from-position), var(--tw-mask-linear-to-color) var(--tw-mask-linear-to-position)"),s("--tw-mask-linear","linear-gradient(var(--tw-mask-linear-stops))"),s("--tw-mask-linear-to-position",a)]});let O=()=>G([T("--tw-mask-radial-from-position","0%"),T("--tw-mask-radial-to-position","100%"),T("--tw-mask-radial-from-color","black"),T("--tw-mask-radial-to-color","transparent"),T("--tw-mask-radial-shape","ellipse"),T("--tw-mask-radial-size","farthest-corner"),T("--tw-mask-radial-position","center")]);t("mask-circle",[["--tw-mask-radial-shape","circle"]]),t("mask-ellipse",[["--tw-mask-radial-shape","ellipse"]]),t("mask-radial-closest-side",[["--tw-mask-radial-size","closest-side"]]),t("mask-radial-farthest-side",[["--tw-mask-radial-size","farthest-side"]]),t("mask-radial-closest-corner",[["--tw-mask-radial-size","closest-corner"]]),t("mask-radial-farthest-corner",[["--tw-mask-radial-size","farthest-corner"]]),t("mask-radial-at-top",[["--tw-mask-radial-position","top"]]),t("mask-radial-at-top-left",[["--tw-mask-radial-position","top left"]]),t("mask-radial-at-top-right",[["--tw-mask-radial-position","top right"]]),t("mask-radial-at-bottom",[["--tw-mask-radial-position","bottom"]]),t("mask-radial-at-bottom-left",[["--tw-mask-radial-position","bottom left"]]),t("mask-radial-at-bottom-right",[["--tw-mask-radial-position","bottom right"]]),t("mask-radial-at-left",[["--tw-mask-radial-position","left"]]),t("mask-radial-at-right",[["--tw-mask-radial-position","right"]]),t("mask-radial-at-center",[["--tw-mask-radial-position","center"]]),n("mask-radial-at",{defaultValue:null,supportsNegative:!1,supportsFractions:!1,handle:a=>[s("--tw-mask-radial-position",a)]}),n("mask-radial",{defaultValue:null,supportsNegative:!1,supportsFractions:!1,handle:a=>[b(),O(),s("mask-image","var(--tw-mask-linear), var(--tw-mask-radial), var(--tw-mask-conic)"),s("mask-composite","intersect"),s("--tw-mask-radial","radial-gradient(var(--tw-mask-radial-stops, var(--tw-mask-radial-size)))"),s("--tw-mask-radial-size",a)]}),A("mask-radial-from",{color:a=>[b(),O(),s("mask-image","var(--tw-mask-linear), var(--tw-mask-radial), var(--tw-mask-conic)"),s("mask-composite","intersect"),s("--tw-mask-radial-stops","var(--tw-mask-radial-shape) var(--tw-mask-radial-size) at var(--tw-mask-radial-position), var(--tw-mask-radial-from-color) var(--tw-mask-radial-from-position), var(--tw-mask-radial-to-color) var(--tw-mask-radial-to-position)"),s("--tw-mask-radial","radial-gradient(var(--tw-mask-radial-stops))"),s("--tw-mask-radial-from-color",a)],position:a=>[b(),O(),s("mask-image","var(--tw-mask-linear), var(--tw-mask-radial), var(--tw-mask-conic)"),s("mask-composite","intersect"),s("--tw-mask-radial-stops","var(--tw-mask-radial-shape) var(--tw-mask-radial-size) at var(--tw-mask-radial-position), var(--tw-mask-radial-from-color) var(--tw-mask-radial-from-position), var(--tw-mask-radial-to-color) var(--tw-mask-radial-to-position)"),s("--tw-mask-radial","radial-gradient(var(--tw-mask-radial-stops))"),s("--tw-mask-radial-from-position",a)]}),A("mask-radial-to",{color:a=>[b(),O(),s("mask-image","var(--tw-mask-linear), var(--tw-mask-radial), var(--tw-mask-conic)"),s("mask-composite","intersect"),s("--tw-mask-radial-stops","var(--tw-mask-radial-shape) var(--tw-mask-radial-size) at var(--tw-mask-radial-position), var(--tw-mask-radial-from-color) var(--tw-mask-radial-from-position), var(--tw-mask-radial-to-color) var(--tw-mask-radial-to-position)"),s("--tw-mask-radial","radial-gradient(var(--tw-mask-radial-stops))"),s("--tw-mask-radial-to-color",a)],position:a=>[b(),O(),s("mask-image","var(--tw-mask-linear), var(--tw-mask-radial), var(--tw-mask-conic)"),s("mask-composite","intersect"),s("--tw-mask-radial-stops","var(--tw-mask-radial-shape) var(--tw-mask-radial-size) at var(--tw-mask-radial-position), var(--tw-mask-radial-from-color) var(--tw-mask-radial-from-position), var(--tw-mask-radial-to-color) var(--tw-mask-radial-to-position)"),s("--tw-mask-radial","radial-gradient(var(--tw-mask-radial-stops))"),s("--tw-mask-radial-to-position",a)]});let P=()=>G([T("--tw-mask-conic-position","0deg"),T("--tw-mask-conic-from-position","0%"),T("--tw-mask-conic-to-position","100%"),T("--tw-mask-conic-from-color","black"),T("--tw-mask-conic-to-color","transparent")]);n("mask-conic",{defaultValue:null,supportsNegative:!0,supportsFractions:!1,handleBareValue({value:a}){if(!D(a))return null;let g=Number(a);return g===0?"0deg":g===1?"1deg":`calc(1deg * ${a})`},handleNegativeBareValue({value:a}){if(!D(a))return null;let g=Number(a);return g===0?"0deg":g===1?"-1deg":`calc(1deg * -${a})`},handle:a=>[b(),P(),s("mask-image","var(--tw-mask-linear), var(--tw-mask-radial), var(--tw-mask-conic)"),s("mask-composite","intersect"),s("--tw-mask-conic","conic-gradient(var(--tw-mask-conic-stops, var(--tw-mask-conic-position)))"),s("--tw-mask-conic-position",a)]}),i("mask-conic",()=>[{supportsNegative:!0,values:["0","1","2","3","6","12","45","90","180"]}]),A("mask-conic-from",{color:a=>[b(),P(),s("mask-image","var(--tw-mask-linear), var(--tw-mask-radial), var(--tw-mask-conic)"),s("mask-composite","intersect"),s("--tw-mask-conic-stops","from var(--tw-mask-conic-position), var(--tw-mask-conic-from-color) var(--tw-mask-conic-from-position), var(--tw-mask-conic-to-color) var(--tw-mask-conic-to-position)"),s("--tw-mask-conic","conic-gradient(var(--tw-mask-conic-stops))"),s("--tw-mask-conic-from-color",a)],position:a=>[b(),P(),s("mask-image","var(--tw-mask-linear), var(--tw-mask-radial), var(--tw-mask-conic)"),s("mask-composite","intersect"),s("--tw-mask-conic-stops","from var(--tw-mask-conic-position), var(--tw-mask-conic-from-color) var(--tw-mask-conic-from-position), var(--tw-mask-conic-to-color) var(--tw-mask-conic-to-position)"),s("--tw-mask-conic","conic-gradient(var(--tw-mask-conic-stops))"),s("--tw-mask-conic-from-position",a)]}),A("mask-conic-to",{color:a=>[b(),P(),s("mask-image","var(--tw-mask-linear), var(--tw-mask-radial), var(--tw-mask-conic)"),s("mask-composite","intersect"),s("--tw-mask-conic-stops","from var(--tw-mask-conic-position), var(--tw-mask-conic-from-color) var(--tw-mask-conic-from-position), var(--tw-mask-conic-to-color) var(--tw-mask-conic-to-position)"),s("--tw-mask-conic","conic-gradient(var(--tw-mask-conic-stops))"),s("--tw-mask-conic-to-color",a)],position:a=>[b(),P(),s("mask-image","var(--tw-mask-linear), var(--tw-mask-radial), var(--tw-mask-conic)"),s("mask-composite","intersect"),s("--tw-mask-conic-stops","from var(--tw-mask-conic-position), var(--tw-mask-conic-from-color) var(--tw-mask-conic-from-position), var(--tw-mask-conic-to-color) var(--tw-mask-conic-to-position)"),s("--tw-mask-conic","conic-gradient(var(--tw-mask-conic-stops))"),s("--tw-mask-conic-to-position",a)]}),t("box-decoration-slice",[["-webkit-box-decoration-break","slice"],["box-decoration-break","slice"]]),t("box-decoration-clone",[["-webkit-box-decoration-break","clone"],["box-decoration-break","clone"]]),t("bg-clip-text",[["background-clip","text"]]),t("bg-clip-border",[["background-clip","border-box"]]),t("bg-clip-padding",[["background-clip","padding-box"]]),t("bg-clip-content",[["background-clip","content-box"]]),t("bg-origin-border",[["background-origin","border-box"]]),t("bg-origin-padding",[["background-origin","padding-box"]]),t("bg-origin-content",[["background-origin","content-box"]]);for(let a of["normal","multiply","screen","overlay","darken","lighten","color-dodge","color-burn","hard-light","soft-light","difference","exclusion","hue","saturation","color","luminosity"])t(`bg-blend-${a}`,[["background-blend-mode",a]]),t(`mix-blend-${a}`,[["mix-blend-mode",a]]);t("mix-blend-plus-darker",[["mix-blend-mode","plus-darker"]]),t("mix-blend-plus-lighter",[["mix-blend-mode","plus-lighter"]]),t("fill-none",[["fill","none"]]),r.functional("fill",a=>{if(!a.value)return;if(a.value.kind==="arbitrary"){let v=ne(a.value.value,a.modifier,e);return v===null?void 0:[s("fill",v)]}let g=ae(a,e,["--fill","--color"]);if(g)return[s("fill",g)]}),i("fill",()=>[{values:["current","inherit","transparent"],valueThemeKeys:["--fill","--color"],modifierThemeKeys:["--opacity"],modifiers:Array.from({length:21},(a,g)=>`${g*5}`)}]),t("stroke-none",[["stroke","none"]]),r.functional("stroke",a=>{if(a.value){if(a.value.kind==="arbitrary"){let g=a.value.value;switch(a.value.dataType??X(g,["color","number","length","percentage"])){case"number":case"length":case"percentage":return a.modifier?void 0:[s("stroke-width",g)];default:return g=ne(a.value.value,a.modifier,e),g===null?void 0:[s("stroke",g)]}}{let g=ae(a,e,["--stroke","--color"]);if(g)return[s("stroke",g)]}{if(a.modifier)return;let g=e.resolve(a.value.value,["--stroke-width"]);if(g)return[s("stroke-width",g)];if(D(a.value.value))return[s("stroke-width",a.value.value)]}}}),i("stroke",()=>[{values:["current","inherit","transparent"],valueThemeKeys:["--stroke","--color"],modifierThemeKeys:["--opacity"],modifiers:Array.from({length:21},(a,g)=>`${g*5}`)},{values:["0","1","2","3"],valueThemeKeys:["--stroke-width"]}]),t("object-contain",[["object-fit","contain"]]),t("object-cover",[["object-fit","cover"]]),t("object-fill",[["object-fit","fill"]]),t("object-none",[["object-fit","none"]]),t("object-scale-down",[["object-fit","scale-down"]]),n("object",{themeKeys:["--object-position"],handle:a=>[s("object-position",a)],staticValues:{top:[s("object-position","top")],"top-left":[s("object-position","left top")],"top-right":[s("object-position","right top")],bottom:[s("object-position","bottom")],"bottom-left":[s("object-position","left bottom")],"bottom-right":[s("object-position","right bottom")],left:[s("object-position","left")],right:[s("object-position","right")],center:[s("object-position","center")]}});for(let[a,g]of[["p","padding"],["px","padding-inline"],["py","padding-block"],["ps","padding-inline-start"],["pe","padding-inline-end"],["pbs","padding-block-start"],["pbe","padding-block-end"],["pt","padding-top"],["pr","padding-right"],["pb","padding-bottom"],["pl","padding-left"]])l(a,["--padding","--spacing"],v=>[s(g,v)]);t("text-left",[["text-align","left"]]),t("text-center",[["text-align","center"]]),t("text-right",[["text-align","right"]]),t("text-justify",[["text-align","justify"]]),t("text-start",[["text-align","start"]]),t("text-end",[["text-align","end"]]),l("indent",["--text-indent","--spacing"],a=>[s("text-indent",a)],{supportsNegative:!0}),t("align-baseline",[["vertical-align","baseline"]]),t("align-top",[["vertical-align","top"]]),t("align-middle",[["vertical-align","middle"]]),t("align-bottom",[["vertical-align","bottom"]]),t("align-text-top",[["vertical-align","text-top"]]),t("align-text-bottom",[["vertical-align","text-bottom"]]),t("align-sub",[["vertical-align","sub"]]),t("align-super",[["vertical-align","super"]]),n("align",{themeKeys:[],handle:a=>[s("vertical-align",a)]}),r.functional("font",a=>{if(!(!a.value||a.modifier)){if(a.value.kind==="arbitrary"){let g=a.value.value;switch(a.value.dataType??X(g,["number","generic-name","family-name"])){case"generic-name":case"family-name":return[s("font-family",g)];default:return[G([T("--tw-font-weight")]),s("--tw-font-weight",g),s("font-weight",g)]}}{let g=e.resolveWith(a.value.value,["--font"],["--font-feature-settings","--font-variation-settings"]);if(g){let[v,S={}]=g;return[s("font-family",v),s("font-feature-settings",S["--font-feature-settings"]),s("font-variation-settings",S["--font-variation-settings"])]}}{let g=e.resolve(a.value.value,["--font-weight"]);if(g)return[G([T("--tw-font-weight")]),s("--tw-font-weight",g),s("font-weight",g)]}}}),i("font",()=>[{values:[],valueThemeKeys:["--font"]},{values:[],valueThemeKeys:["--font-weight"]}]),n("font-features",{themeKeys:[],handle:a=>[s("font-feature-settings",a)]}),t("uppercase",[["text-transform","uppercase"]]),t("lowercase",[["text-transform","lowercase"]]),t("capitalize",[["text-transform","capitalize"]]),t("normal-case",[["text-transform","none"]]),t("italic",[["font-style","italic"]]),t("not-italic",[["font-style","normal"]]),t("underline",[["text-decoration-line","underline"]]),t("overline",[["text-decoration-line","overline"]]),t("line-through",[["text-decoration-line","line-through"]]),t("no-underline",[["text-decoration-line","none"]]),t("font-stretch-normal",[["font-stretch","normal"]]),t("font-stretch-ultra-condensed",[["font-stretch","ultra-condensed"]]),t("font-stretch-extra-condensed",[["font-stretch","extra-condensed"]]),t("font-stretch-condensed",[["font-stretch","condensed"]]),t("font-stretch-semi-condensed",[["font-stretch","semi-condensed"]]),t("font-stretch-semi-expanded",[["font-stretch","semi-expanded"]]),t("font-stretch-expanded",[["font-stretch","expanded"]]),t("font-stretch-extra-expanded",[["font-stretch","extra-expanded"]]),t("font-stretch-ultra-expanded",[["font-stretch","ultra-expanded"]]),n("font-stretch",{handleBareValue:({value:a})=>{if(!a.endsWith("%"))return null;let g=Number(a.slice(0,-1));return!D(g)||Number.isNaN(g)||g<50||g>200?null:a},handle:a=>[s("font-stretch",a)]}),i("font-stretch",()=>[{values:["50%","75%","90%","95%","100%","105%","110%","125%","150%","200%"]}]),o("placeholder",{themeKeys:["--placeholder-color","--color"],handle:a=>[Q("&::placeholder",[s("--tw-sort","placeholder-color"),s("color",a)])]}),t("decoration-solid",[["text-decoration-style","solid"]]),t("decoration-double",[["text-decoration-style","double"]]),t("decoration-dotted",[["text-decoration-style","dotted"]]),t("decoration-dashed",[["text-decoration-style","dashed"]]),t("decoration-wavy",[["text-decoration-style","wavy"]]),t("decoration-auto",[["text-decoration-thickness","auto"]]),t("decoration-from-font",[["text-decoration-thickness","from-font"]]),r.functional("decoration",a=>{if(a.value){if(a.value.kind==="arbitrary"){let g=a.value.value;switch(a.value.dataType??X(g,["color","length","percentage"])){case"length":case"percentage":return a.modifier?void 0:[s("text-decoration-thickness",g)];default:return g=ne(g,a.modifier,e),g===null?void 0:[s("text-decoration-color",g)]}}{let g=e.resolve(a.value.value,["--text-decoration-thickness"]);if(g)return a.modifier?void 0:[s("text-decoration-thickness",g)];if(D(a.value.value))return a.modifier?void 0:[s("text-decoration-thickness",`${a.value.value}px`)]}{let g=ae(a,e,["--text-decoration-color","--color"]);if(g)return[s("text-decoration-color",g)]}}}),i("decoration",()=>[{values:["current","inherit","transparent"],valueThemeKeys:["--text-decoration-color","--color"],modifierThemeKeys:["--opacity"],modifiers:Array.from({length:21},(a,g)=>`${g*5}`)},{values:["0","1","2"],valueThemeKeys:["--text-decoration-thickness"]}]),n("animate",{themeKeys:["--animate"],handle:a=>[s("animation",a)],staticValues:{none:[s("animation","none")]}});{let a=["var(--tw-blur, )","var(--tw-brightness, )","var(--tw-contrast, )","var(--tw-grayscale, )","var(--tw-hue-rotate, )","var(--tw-invert, )","var(--tw-saturate, )","var(--tw-sepia, )","var(--tw-drop-shadow, )"].join(" "),g=["var(--tw-backdrop-blur, )","var(--tw-backdrop-brightness, )","var(--tw-backdrop-contrast, )","var(--tw-backdrop-grayscale, )","var(--tw-backdrop-hue-rotate, )","var(--tw-backdrop-invert, )","var(--tw-backdrop-opacity, )","var(--tw-backdrop-saturate, )","var(--tw-backdrop-sepia, )"].join(" "),v=()=>G([T("--tw-blur"),T("--tw-brightness"),T("--tw-contrast"),T("--tw-grayscale"),T("--tw-hue-rotate"),T("--tw-invert"),T("--tw-opacity"),T("--tw-saturate"),T("--tw-sepia"),T("--tw-drop-shadow"),T("--tw-drop-shadow-color"),T("--tw-drop-shadow-alpha","100%",""),T("--tw-drop-shadow-size")]),S=()=>G([T("--tw-backdrop-blur"),T("--tw-backdrop-brightness"),T("--tw-backdrop-contrast"),T("--tw-backdrop-grayscale"),T("--tw-backdrop-hue-rotate"),T("--tw-backdrop-invert"),T("--tw-backdrop-opacity"),T("--tw-backdrop-saturate"),T("--tw-backdrop-sepia")]);r.functional("filter",x=>{if(!x.modifier){if(x.value===null)return[v(),s("filter",a)];if(x.value.kind==="arbitrary")return[s("filter",x.value.value)];if(x.value.value==="none")return[s("filter","none")]}}),r.functional("backdrop-filter",x=>{if(!x.modifier){if(x.value===null)return[S(),s("-webkit-backdrop-filter",g),s("backdrop-filter",g)];if(x.value.kind==="arbitrary")return[s("-webkit-backdrop-filter",x.value.value),s("backdrop-filter",x.value.value)];if(x.value.value==="none")return[s("-webkit-backdrop-filter","none"),s("backdrop-filter","none")]}}),n("blur",{themeKeys:["--blur"],handle:x=>[v(),s("--tw-blur",`blur(${x})`),s("filter",a)],staticValues:{none:[v(),s("--tw-blur"," "),s("filter",a)]}}),n("backdrop-blur",{themeKeys:["--backdrop-blur","--blur"],handle:x=>[S(),s("--tw-backdrop-blur",`blur(${x})`),s("-webkit-backdrop-filter",g),s("backdrop-filter",g)],staticValues:{none:[S(),s("--tw-backdrop-blur"," "),s("-webkit-backdrop-filter",g),s("backdrop-filter",g)]}}),n("brightness",{themeKeys:["--brightness"],handleBareValue:({value:x})=>D(x)?`${x}%`:null,handle:x=>[v(),s("--tw-brightness",`brightness(${x})`),s("filter",a)]}),n("backdrop-brightness",{themeKeys:["--backdrop-brightness","--brightness"],handleBareValue:({value:x})=>D(x)?`${x}%`:null,handle:x=>[S(),s("--tw-backdrop-brightness",`brightness(${x})`),s("-webkit-backdrop-filter",g),s("backdrop-filter",g)]}),i("brightness",()=>[{values:["0","50","75","90","95","100","105","110","125","150","200"],valueThemeKeys:["--brightness"]}]),i("backdrop-brightness",()=>[{values:["0","50","75","90","95","100","105","110","125","150","200"],valueThemeKeys:["--backdrop-brightness","--brightness"]}]),n("contrast",{themeKeys:["--contrast"],handleBareValue:({value:x})=>D(x)?`${x}%`:null,handle:x=>[v(),s("--tw-contrast",`contrast(${x})`),s("filter",a)]}),n("backdrop-contrast",{themeKeys:["--backdrop-contrast","--contrast"],handleBareValue:({value:x})=>D(x)?`${x}%`:null,handle:x=>[S(),s("--tw-backdrop-contrast",`contrast(${x})`),s("-webkit-backdrop-filter",g),s("backdrop-filter",g)]}),i("contrast",()=>[{values:["0","50","75","100","125","150","200"],valueThemeKeys:["--contrast"]}]),i("backdrop-contrast",()=>[{values:["0","50","75","100","125","150","200"],valueThemeKeys:["--backdrop-contrast","--contrast"]}]),n("grayscale",{themeKeys:["--grayscale"],handleBareValue:({value:x})=>D(x)?`${x}%`:null,defaultValue:"100%",handle:x=>[v(),s("--tw-grayscale",`grayscale(${x})`),s("filter",a)]}),n("backdrop-grayscale",{themeKeys:["--backdrop-grayscale","--grayscale"],handleBareValue:({value:x})=>D(x)?`${x}%`:null,defaultValue:"100%",handle:x=>[S(),s("--tw-backdrop-grayscale",`grayscale(${x})`),s("-webkit-backdrop-filter",g),s("backdrop-filter",g)]}),i("grayscale",()=>[{values:["0","25","50","75","100"],valueThemeKeys:["--grayscale"],hasDefaultValue:!0}]),i("backdrop-grayscale",()=>[{values:["0","25","50","75","100"],valueThemeKeys:["--backdrop-grayscale","--grayscale"],hasDefaultValue:!0}]),n("hue-rotate",{supportsNegative:!0,themeKeys:["--hue-rotate"],handleBareValue:({value:x})=>D(x)?`${x}deg`:null,handle:x=>[v(),s("--tw-hue-rotate",`hue-rotate(${x})`),s("filter",a)]}),n("backdrop-hue-rotate",{supportsNegative:!0,themeKeys:["--backdrop-hue-rotate","--hue-rotate"],handleBareValue:({value:x})=>D(x)?`${x}deg`:null,handle:x=>[S(),s("--tw-backdrop-hue-rotate",`hue-rotate(${x})`),s("-webkit-backdrop-filter",g),s("backdrop-filter",g)]}),i("hue-rotate",()=>[{values:["0","15","30","60","90","180"],valueThemeKeys:["--hue-rotate"]}]),i("backdrop-hue-rotate",()=>[{values:["0","15","30","60","90","180"],valueThemeKeys:["--backdrop-hue-rotate","--hue-rotate"]}]),n("invert",{themeKeys:["--invert"],handleBareValue:({value:x})=>D(x)?`${x}%`:null,defaultValue:"100%",handle:x=>[v(),s("--tw-invert",`invert(${x})`),s("filter",a)]}),n("backdrop-invert",{themeKeys:["--backdrop-invert","--invert"],handleBareValue:({value:x})=>D(x)?`${x}%`:null,defaultValue:"100%",handle:x=>[S(),s("--tw-backdrop-invert",`invert(${x})`),s("-webkit-backdrop-filter",g),s("backdrop-filter",g)]}),i("invert",()=>[{values:["0","25","50","75","100"],valueThemeKeys:["--invert"],hasDefaultValue:!0}]),i("backdrop-invert",()=>[{values:["0","25","50","75","100"],valueThemeKeys:["--backdrop-invert","--invert"],hasDefaultValue:!0}]),n("saturate",{themeKeys:["--saturate"],handleBareValue:({value:x})=>D(x)?`${x}%`:null,handle:x=>[v(),s("--tw-saturate",`saturate(${x})`),s("filter",a)]}),n("backdrop-saturate",{themeKeys:["--backdrop-saturate","--saturate"],handleBareValue:({value:x})=>D(x)?`${x}%`:null,handle:x=>[S(),s("--tw-backdrop-saturate",`saturate(${x})`),s("-webkit-backdrop-filter",g),s("backdrop-filter",g)]}),i("saturate",()=>[{values:["0","50","100","150","200"],valueThemeKeys:["--saturate"]}]),i("backdrop-saturate",()=>[{values:["0","50","100","150","200"],valueThemeKeys:["--backdrop-saturate","--saturate"]}]),n("sepia",{themeKeys:["--sepia"],handleBareValue:({value:x})=>D(x)?`${x}%`:null,defaultValue:"100%",handle:x=>[v(),s("--tw-sepia",`sepia(${x})`),s("filter",a)]}),n("backdrop-sepia",{themeKeys:["--backdrop-sepia","--sepia"],handleBareValue:({value:x})=>D(x)?`${x}%`:null,defaultValue:"100%",handle:x=>[S(),s("--tw-backdrop-sepia",`sepia(${x})`),s("-webkit-backdrop-filter",g),s("backdrop-filter",g)]}),i("sepia",()=>[{values:["0","50","100"],valueThemeKeys:["--sepia"],hasDefaultValue:!0}]),i("backdrop-sepia",()=>[{values:["0","50","100"],valueThemeKeys:["--backdrop-sepia","--sepia"],hasDefaultValue:!0}]),t("drop-shadow-none",[v,["--tw-drop-shadow"," "],["filter",a]]),r.functional("drop-shadow",x=>{let $;if(x.modifier&&(x.modifier.kind==="arbitrary"?$=x.modifier.value:Ne(x.modifier.value)&&($=`${x.modifier.value}%`)),!x.value){let M=e.get(["--drop-shadow"]),N=e.resolve(null,["--drop-shadow"]);return M===null||N===null||x.modifier&&!$?void 0:[v(),s("--tw-drop-shadow-alpha",$),..._t("--tw-drop-shadow-size",M,$,_=>`var(--tw-drop-shadow-color, ${_})`),s("--tw-drop-shadow",j(N,",").map(_=>`drop-shadow(${_})`).join(" ")),s("filter",a)]}if(x.value.kind==="arbitrary"){let M=x.value.value;return(x.value.dataType??X(M,["color"]))==="color"?(M=ne(M,x.modifier,e),M===null?void 0:[v(),s("--tw-drop-shadow-color",ie(M,"var(--tw-drop-shadow-alpha)")),s("--tw-drop-shadow","var(--tw-drop-shadow-size)")]):x.modifier&&!$?void 0:[v(),s("--tw-drop-shadow-alpha",$),..._t("--tw-drop-shadow-size",M,$,_=>`var(--tw-drop-shadow-color, ${_})`),s("--tw-drop-shadow","var(--tw-drop-shadow-size)"),s("filter",a)]}{let M=e.get([`--drop-shadow-${x.value.value}`]),N=e.resolve(x.value.value,["--drop-shadow"]);if(M&&N)return x.modifier&&!$?void 0:$?[v(),s("--tw-drop-shadow-alpha",$),..._t("--tw-drop-shadow-size",M,$,_=>`var(--tw-drop-shadow-color, ${_})`),s("--tw-drop-shadow","var(--tw-drop-shadow-size)"),s("filter",a)]:[v(),s("--tw-drop-shadow-alpha",$),..._t("--tw-drop-shadow-size",M,$,_=>`var(--tw-drop-shadow-color, ${_})`),s("--tw-drop-shadow",j(N,",").map(_=>`drop-shadow(${_})`).join(" ")),s("filter",a)]}{let M=ae(x,e,["--drop-shadow-color","--color"]);if(M)return M==="inherit"?[v(),s("--tw-drop-shadow-color","inherit"),s("--tw-drop-shadow","var(--tw-drop-shadow-size)")]:[v(),s("--tw-drop-shadow-color",ie(M,"var(--tw-drop-shadow-alpha)")),s("--tw-drop-shadow","var(--tw-drop-shadow-size)")]}}),i("drop-shadow",()=>[{values:["current","inherit","transparent"],valueThemeKeys:["--drop-shadow-color","--color"],modifierThemeKeys:["--opacity"],modifiers:Array.from({length:21},(x,$)=>`${$*5}`)},{valueThemeKeys:["--drop-shadow"]}]),n("backdrop-opacity",{themeKeys:["--backdrop-opacity","--opacity"],handleBareValue:({value:x})=>Ne(x)?`${x}%`:null,handle:x=>[S(),s("--tw-backdrop-opacity",`opacity(${x})`),s("-webkit-backdrop-filter",g),s("backdrop-filter",g)]}),i("backdrop-opacity",()=>[{values:Array.from({length:21},(x,$)=>`${$*5}`),valueThemeKeys:["--backdrop-opacity","--opacity"]}])}{let a=`var(--tw-ease, ${e.resolve(null,["--default-transition-timing-function"])??"ease"})`,g=`var(--tw-duration, ${e.resolve(null,["--default-transition-duration"])??"0s"})`;n("transition",{defaultValue:"color, background-color, border-color, outline-color, text-decoration-color, fill, stroke, --tw-gradient-from, --tw-gradient-via, --tw-gradient-to, opacity, box-shadow, transform, translate, scale, rotate, filter, -webkit-backdrop-filter, backdrop-filter, display, content-visibility, overlay, pointer-events",themeKeys:["--transition-property"],handle:v=>[s("transition-property",v),s("transition-timing-function",a),s("transition-duration",g)],staticValues:{none:[s("transition-property","none")],all:[s("transition-property","all"),s("transition-timing-function",a),s("transition-duration",g)],colors:[s("transition-property","color, background-color, border-color, outline-color, text-decoration-color, fill, stroke, --tw-gradient-from, --tw-gradient-via, --tw-gradient-to"),s("transition-timing-function",a),s("transition-duration",g)],opacity:[s("transition-property","opacity"),s("transition-timing-function",a),s("transition-duration",g)],shadow:[s("transition-property","box-shadow"),s("transition-timing-function",a),s("transition-duration",g)],transform:[s("transition-property","transform, translate, scale, rotate"),s("transition-timing-function",a),s("transition-duration",g)]}}),t("transition-discrete",[["transition-behavior","allow-discrete"]]),t("transition-normal",[["transition-behavior","normal"]]),n("delay",{handleBareValue:({value:v})=>D(v)?`${v}ms`:null,themeKeys:["--transition-delay"],handle:v=>[s("transition-delay",v)]});{let v=()=>G([T("--tw-duration")]);t("duration-initial",[v,["--tw-duration","initial"]]),r.functional("duration",S=>{if(S.modifier||!S.value)return;let x=null;if(S.value.kind==="arbitrary"?x=S.value.value:(x=e.resolve(S.value.fraction??S.value.value,["--transition-duration"]),x===null&&D(S.value.value)&&(x=`${S.value.value}ms`)),x!==null)return[v(),s("--tw-duration",x),s("transition-duration",x)]})}i("delay",()=>[{values:["75","100","150","200","300","500","700","1000"],valueThemeKeys:["--transition-delay"]}]),i("duration",()=>[{values:["75","100","150","200","300","500","700","1000"],valueThemeKeys:["--transition-duration"]}])}{let a=()=>G([T("--tw-ease")]);n("ease",{themeKeys:["--ease"],handle:g=>[a(),s("--tw-ease",g),s("transition-timing-function",g)],staticValues:{initial:[a(),s("--tw-ease","initial")],linear:[a(),s("--tw-ease","linear"),s("transition-timing-function","linear")]}})}t("will-change-auto",[["will-change","auto"]]),t("will-change-scroll",[["will-change","scroll-position"]]),t("will-change-contents",[["will-change","contents"]]),t("will-change-transform",[["will-change","transform"]]),n("will-change",{themeKeys:[],handle:a=>[s("will-change",a)]}),t("content-none",[["--tw-content","none"],["content","none"]]),n("content",{themeKeys:["--content"],handle:a=>[G([T("--tw-content",'""')]),s("--tw-content",a),s("content","var(--tw-content)")]});{let a="var(--tw-contain-size, ) var(--tw-contain-layout, ) var(--tw-contain-paint, ) var(--tw-contain-style, )",g=()=>G([T("--tw-contain-size"),T("--tw-contain-layout"),T("--tw-contain-paint"),T("--tw-contain-style")]);t("contain-none",[["contain","none"]]),t("contain-content",[["contain","content"]]),t("contain-strict",[["contain","strict"]]),t("contain-size",[g,["--tw-contain-size","size"],["contain",a]]),t("contain-inline-size",[g,["--tw-contain-size","inline-size"],["contain",a]]),t("contain-layout",[g,["--tw-contain-layout","layout"],["contain",a]]),t("contain-paint",[g,["--tw-contain-paint","paint"],["contain",a]]),t("contain-style",[g,["--tw-contain-style","style"],["contain",a]]),n("contain",{themeKeys:[],handle:v=>[s("contain",v)]})}t("forced-color-adjust-none",[["forced-color-adjust","none"]]),t("forced-color-adjust-auto",[["forced-color-adjust","auto"]]),l("leading",["--leading","--spacing"],a=>[G([T("--tw-leading")]),s("--tw-leading",a),s("line-height",a)],{staticValues:{none:[G([T("--tw-leading")]),s("--tw-leading","1"),s("line-height","1")]}}),n("tracking",{supportsNegative:!0,themeKeys:["--tracking"],handle:a=>[G([T("--tw-tracking")]),s("--tw-tracking",a),s("letter-spacing",a)]}),t("antialiased",[["-webkit-font-smoothing","antialiased"],["-moz-osx-font-smoothing","grayscale"]]),t("subpixel-antialiased",[["-webkit-font-smoothing","auto"],["-moz-osx-font-smoothing","auto"]]);{let a="var(--tw-ordinal, ) var(--tw-slashed-zero, ) var(--tw-numeric-figure, ) var(--tw-numeric-spacing, ) var(--tw-numeric-fraction, )",g=()=>G([T("--tw-ordinal"),T("--tw-slashed-zero"),T("--tw-numeric-figure"),T("--tw-numeric-spacing"),T("--tw-numeric-fraction")]);t("normal-nums",[["font-variant-numeric","normal"]]),t("ordinal",[g,["--tw-ordinal","ordinal"],["font-variant-numeric",a]]),t("slashed-zero",[g,["--tw-slashed-zero","slashed-zero"],["font-variant-numeric",a]]),t("lining-nums",[g,["--tw-numeric-figure","lining-nums"],["font-variant-numeric",a]]),t("oldstyle-nums",[g,["--tw-numeric-figure","oldstyle-nums"],["font-variant-numeric",a]]),t("proportional-nums",[g,["--tw-numeric-spacing","proportional-nums"],["font-variant-numeric",a]]),t("tabular-nums",[g,["--tw-numeric-spacing","tabular-nums"],["font-variant-numeric",a]]),t("diagonal-fractions",[g,["--tw-numeric-fraction","diagonal-fractions"],["font-variant-numeric",a]]),t("stacked-fractions",[g,["--tw-numeric-fraction","stacked-fractions"],["font-variant-numeric",a]])}{let a=()=>G([T("--tw-outline-style","solid")]);r.static("outline-hidden",()=>[s("--tw-outline-style","none"),s("outline-style","none"),H("@media","(forced-colors: active)",[s("outline","2px solid transparent"),s("outline-offset","2px")])]),t("outline-none",[["--tw-outline-style","none"],["outline-style","none"]]),t("outline-solid",[["--tw-outline-style","solid"],["outline-style","solid"]]),t("outline-dashed",[["--tw-outline-style","dashed"],["outline-style","dashed"]]),t("outline-dotted",[["--tw-outline-style","dotted"],["outline-style","dotted"]]),t("outline-double",[["--tw-outline-style","double"],["outline-style","double"]]),r.functional("outline",g=>{if(g.value===null){if(g.modifier)return;let v=e.get(["--default-outline-width"])??"1px";return[a(),s("outline-style","var(--tw-outline-style)"),s("outline-width",v)]}if(g.value.kind==="arbitrary"){let v=g.value.value;switch(g.value.dataType??X(v,["color","length","number","percentage"])){case"length":case"number":case"percentage":return g.modifier?void 0:[a(),s("outline-style","var(--tw-outline-style)"),s("outline-width",v)];default:return v=ne(v,g.modifier,e),v===null?void 0:[s("outline-color",v)]}}{let v=ae(g,e,["--outline-color","--color"]);if(v)return[s("outline-color",v)]}{if(g.modifier)return;let v=e.resolve(g.value.value,["--outline-width"]);if(v)return[a(),s("outline-style","var(--tw-outline-style)"),s("outline-width",v)];if(D(g.value.value))return[a(),s("outline-style","var(--tw-outline-style)"),s("outline-width",`${g.value.value}px`)]}}),i("outline",()=>[{values:["current","inherit","transparent"],valueThemeKeys:["--outline-color","--color"],modifierThemeKeys:["--opacity"],modifiers:Array.from({length:21},(g,v)=>`${v*5}`),hasDefaultValue:!0},{values:["0","1","2","4","8"],valueThemeKeys:["--outline-width"]}]),n("outline-offset",{supportsNegative:!0,themeKeys:["--outline-offset"],handleBareValue:({value:g})=>D(g)?`${g}px`:null,handle:g=>[s("outline-offset",g)]}),i("outline-offset",()=>[{supportsNegative:!0,values:["0","1","2","4","8"],valueThemeKeys:["--outline-offset"]}])}n("opacity",{themeKeys:["--opacity"],handleBareValue:({value:a})=>Ne(a)?`${a}%`:null,handle:a=>[s("opacity",a)]}),i("opacity",()=>[{values:Array.from({length:21},(a,g)=>`${g*5}`),valueThemeKeys:["--opacity"]}]),n("underline-offset",{supportsNegative:!0,themeKeys:["--text-underline-offset"],handleBareValue:({value:a})=>D(a)?`${a}px`:null,handle:a=>[s("text-underline-offset",a)],staticValues:{auto:[s("text-underline-offset","auto")]}}),i("underline-offset",()=>[{supportsNegative:!0,values:["0","1","2","4","8"],valueThemeKeys:["--text-underline-offset"]}]),r.functional("text",a=>{if(a.value){if(a.value.kind==="arbitrary"){let g=a.value.value;switch(a.value.dataType??X(g,["color","length","percentage","absolute-size","relative-size"])){case"size":case"length":case"percentage":case"absolute-size":case"relative-size":{if(a.modifier){let S=a.modifier.kind==="arbitrary"?a.modifier.value:e.resolve(a.modifier.value,["--leading"]);if(!S&&te(a.modifier.value)){if(!e.resolve(null,["--spacing"]))return null;S=`--spacing(${a.modifier.value})`}return!S&&a.modifier.value==="none"&&(S="1"),S?[s("font-size",g),s("line-height",S)]:null}return[s("font-size",g)]}default:return g=ne(g,a.modifier,e),g===null?void 0:[s("color",g)]}}{let g=ae(a,e,["--text-color","--color"]);if(g)return[s("color",g)]}{let g=e.resolveWith(a.value.value,["--text"],["--line-height","--letter-spacing","--font-weight"]);if(g){let[v,S={}]=Array.isArray(g)?g:[g];if(a.modifier){let x=a.modifier.kind==="arbitrary"?a.modifier.value:e.resolve(a.modifier.value,["--leading"]);if(!x&&te(a.modifier.value)){if(!e.resolve(null,["--spacing"]))return null;x=`--spacing(${a.modifier.value})`}if(!x&&a.modifier.value==="none"&&(x="1"),!x)return null;let $=[s("font-size",v)];return x&&$.push(s("line-height",x)),$}return typeof S=="string"?[s("font-size",v),s("line-height",S)]:[s("font-size",v),s("line-height",S["--line-height"]?`var(--tw-leading, ${S["--line-height"]})`:void 0),s("letter-spacing",S["--letter-spacing"]?`var(--tw-tracking, ${S["--letter-spacing"]})`:void 0),s("font-weight",S["--font-weight"]?`var(--tw-font-weight, ${S["--font-weight"]})`:void 0)]}}}}),i("text",()=>[{values:["current","inherit","transparent"],valueThemeKeys:["--text-color","--color"],modifierThemeKeys:["--opacity"],modifiers:Array.from({length:21},(a,g)=>`${g*5}`)},{values:[],valueThemeKeys:["--text"],modifiers:[],modifierThemeKeys:["--leading"]}]);let L=()=>G([T("--tw-text-shadow-color"),T("--tw-text-shadow-alpha","100%","")]);t("text-shadow-initial",[L,["--tw-text-shadow-color","initial"]]),r.functional("text-shadow",a=>{let g;if(a.modifier&&(a.modifier.kind==="arbitrary"?g=a.modifier.value:Ne(a.modifier.value)&&(g=`${a.modifier.value}%`)),!a.value){let v=e.get(["--text-shadow"]);return v===null||a.modifier&&!g?void 0:[L(),s("--tw-text-shadow-alpha",g),...Ve("text-shadow",v,g,S=>`var(--tw-text-shadow-color, ${S})`)]}if(a.value.kind==="arbitrary"){let v=a.value.value;return(a.value.dataType??X(v,["color"]))==="color"?(v=ne(v,a.modifier,e),v===null?void 0:[L(),s("--tw-text-shadow-color",ie(v,"var(--tw-text-shadow-alpha)"))]):a.modifier&&!g?void 0:[L(),s("--tw-text-shadow-alpha",g),...Ve("text-shadow",v,g,x=>`var(--tw-text-shadow-color, ${x})`)]}switch(a.value.value){case"none":return a.modifier?void 0:[L(),s("text-shadow","none")];case"inherit":return a.modifier?void 0:[L(),s("--tw-text-shadow-color","inherit")]}{let v=e.get([`--text-shadow-${a.value.value}`]);if(v)return a.modifier&&!g?void 0:[L(),s("--tw-text-shadow-alpha",g),...Ve("text-shadow",v,g,S=>`var(--tw-text-shadow-color, ${S})`)]}{let v=ae(a,e,["--text-shadow-color","--color"]);if(v)return[L(),s("--tw-text-shadow-color",ie(v,"var(--tw-text-shadow-alpha)"))]}}),i("text-shadow",()=>[{values:["current","inherit","transparent"],valueThemeKeys:["--text-shadow-color","--color"],modifierThemeKeys:["--opacity"],modifiers:Array.from({length:21},(a,g)=>`${g*5}`)},{values:["none"]},{valueThemeKeys:["--text-shadow"],modifiers:Array.from({length:21},(a,g)=>`${g*5}`),hasDefaultValue:e.get(["--text-shadow"])!==null}]);{let x=function(N){return`var(--tw-ring-inset, ) 0 0 0 calc(${N} + var(--tw-ring-offset-width)) var(--tw-ring-color, ${S})`},$=function(N){return`inset 0 0 0 ${N} var(--tw-inset-ring-color, currentcolor)`};var F=x,Z=$;let a=["var(--tw-inset-shadow)","var(--tw-inset-ring-shadow)","var(--tw-ring-offset-shadow)","var(--tw-ring-shadow)","var(--tw-shadow)"].join(", "),g="0 0 #0000",v=()=>G([T("--tw-shadow",g),T("--tw-shadow-color"),T("--tw-shadow-alpha","100%",""),T("--tw-inset-shadow",g),T("--tw-inset-shadow-color"),T("--tw-inset-shadow-alpha","100%",""),T("--tw-ring-color"),T("--tw-ring-shadow",g),T("--tw-inset-ring-color"),T("--tw-inset-ring-shadow",g),T("--tw-ring-inset"),T("--tw-ring-offset-width","0px",""),T("--tw-ring-offset-color","#fff"),T("--tw-ring-offset-shadow",g)]);t("shadow-initial",[v,["--tw-shadow-color","initial"]]),r.functional("shadow",N=>{let _;if(N.modifier&&(N.modifier.kind==="arbitrary"?_=N.modifier.value:Ne(N.modifier.value)&&(_=`${N.modifier.value}%`)),!N.value){let q=e.get(["--shadow"]);return q===null||N.modifier&&!_?void 0:[v(),s("--tw-shadow-alpha",_),...Ve("--tw-shadow",q,_,be=>`var(--tw-shadow-color, ${be})`),s("box-shadow",a)]}if(N.value.kind==="arbitrary"){let q=N.value.value;return(N.value.dataType??X(q,["color"]))==="color"?(q=ne(q,N.modifier,e),q===null?void 0:[v(),s("--tw-shadow-color",ie(q,"var(--tw-shadow-alpha)"))]):N.modifier&&!_?void 0:[v(),s("--tw-shadow-alpha",_),...Ve("--tw-shadow",q,_,Qt=>`var(--tw-shadow-color, ${Qt})`),s("box-shadow",a)]}switch(N.value.value){case"none":return N.modifier?void 0:[v(),s("--tw-shadow",g),s("box-shadow",a)];case"inherit":return N.modifier?void 0:[v(),s("--tw-shadow-color","inherit")]}{let q=e.get([`--shadow-${N.value.value}`]);if(q)return N.modifier&&!_?void 0:[v(),s("--tw-shadow-alpha",_),...Ve("--tw-shadow",q,_,be=>`var(--tw-shadow-color, ${be})`),s("box-shadow",a)]}{let q=ae(N,e,["--box-shadow-color","--color"]);if(q)return[v(),s("--tw-shadow-color",ie(q,"var(--tw-shadow-alpha)"))]}}),i("shadow",()=>[{values:["current","inherit","transparent"],valueThemeKeys:["--box-shadow-color","--color"],modifierThemeKeys:["--opacity"],modifiers:Array.from({length:21},(N,_)=>`${_*5}`)},{values:["none"]},{valueThemeKeys:["--shadow"],modifiers:Array.from({length:21},(N,_)=>`${_*5}`),hasDefaultValue:e.get(["--shadow"])!==null}]),t("inset-shadow-initial",[v,["--tw-inset-shadow-color","initial"]]),r.functional("inset-shadow",N=>{let _;if(N.modifier&&(N.modifier.kind==="arbitrary"?_=N.modifier.value:Ne(N.modifier.value)&&(_=`${N.modifier.value}%`)),!N.value){let q=e.get(["--inset-shadow"]);return q===null||N.modifier&&!_?void 0:[v(),s("--tw-inset-shadow-alpha",_),...Ve("--tw-inset-shadow",q,_,be=>`var(--tw-inset-shadow-color, ${be})`),s("box-shadow",a)]}if(N.value.kind==="arbitrary"){let q=N.value.value;return(N.value.dataType??X(q,["color"]))==="color"?(q=ne(q,N.modifier,e),q===null?void 0:[v(),s("--tw-inset-shadow-color",ie(q,"var(--tw-inset-shadow-alpha)"))]):N.modifier&&!_?void 0:[v(),s("--tw-inset-shadow-alpha",_),...Ve("--tw-inset-shadow",q,_,Qt=>`var(--tw-inset-shadow-color, ${Qt})`,"inset"),s("box-shadow",a)]}switch(N.value.value){case"none":return N.modifier?void 0:[v(),s("--tw-inset-shadow",`inset ${g}`),s("box-shadow",a)];case"inherit":return N.modifier?void 0:[v(),s("--tw-inset-shadow-color","inherit")]}{let q=e.get([`--inset-shadow-${N.value.value}`]);if(q)return N.modifier&&!_?void 0:[v(),s("--tw-inset-shadow-alpha",_),...Ve("--tw-inset-shadow",q,_,be=>`var(--tw-inset-shadow-color, ${be})`),s("box-shadow",a)]}{let q=ae(N,e,["--box-shadow-color","--color"]);if(q)return[v(),s("--tw-inset-shadow-color",ie(q,"var(--tw-inset-shadow-alpha)"))]}}),i("inset-shadow",()=>[{values:["current","inherit","transparent"],valueThemeKeys:["--box-shadow-color","--color"],modifierThemeKeys:["--opacity"],modifiers:Array.from({length:21},(N,_)=>`${_*5}`)},{values:["none"]},{valueThemeKeys:["--inset-shadow"],modifiers:Array.from({length:21},(N,_)=>`${_*5}`),hasDefaultValue:e.get(["--inset-shadow"])!==null}]),t("ring-inset",[v,["--tw-ring-inset","inset"]]);let S=e.get(["--default-ring-color"])??"currentcolor";r.functional("ring",N=>{if(!N.value){if(N.modifier)return;let _=e.get(["--default-ring-width"])??"1px";return[v(),s("--tw-ring-shadow",x(_)),s("box-shadow",a)]}if(N.value.kind==="arbitrary"){let _=N.value.value;return(N.value.dataType??X(_,["color","length"]))==="length"?N.modifier?void 0:[v(),s("--tw-ring-shadow",x(_)),s("box-shadow",a)]:(_=ne(_,N.modifier,e),_===null?void 0:[s("--tw-ring-color",_)])}{let _=ae(N,e,["--ring-color","--color"]);if(_)return[s("--tw-ring-color",_)]}{if(N.modifier)return;let _=e.resolve(N.value.value,["--ring-width"]);if(_===null&&D(N.value.value)&&(_=`${N.value.value}px`),_)return[v(),s("--tw-ring-shadow",x(_)),s("box-shadow",a)]}}),i("ring",()=>[{values:["current","inherit","transparent"],valueThemeKeys:["--ring-color","--color"],modifierThemeKeys:["--opacity"],modifiers:Array.from({length:21},(N,_)=>`${_*5}`)},{values:["0","1","2","4","8"],valueThemeKeys:["--ring-width"],hasDefaultValue:!0}]),r.functional("inset-ring",N=>{if(!N.value)return N.modifier?void 0:[v(),s("--tw-inset-ring-shadow",$("1px")),s("box-shadow",a)];if(N.value.kind==="arbitrary"){let _=N.value.value;return(N.value.dataType??X(_,["color","length"]))==="length"?N.modifier?void 0:[v(),s("--tw-inset-ring-shadow",$(_)),s("box-shadow",a)]:(_=ne(_,N.modifier,e),_===null?void 0:[s("--tw-inset-ring-color",_)])}{let _=ae(N,e,["--ring-color","--color"]);if(_)return[s("--tw-inset-ring-color",_)]}{if(N.modifier)return;let _=e.resolve(N.value.value,["--ring-width"]);if(_===null&&D(N.value.value)&&(_=`${N.value.value}px`),_)return[v(),s("--tw-inset-ring-shadow",$(_)),s("box-shadow",a)]}}),i("inset-ring",()=>[{values:["current","inherit","transparent"],valueThemeKeys:["--ring-color","--color"],modifierThemeKeys:["--opacity"],modifiers:Array.from({length:21},(N,_)=>`${_*5}`)},{values:["0","1","2","4","8"],valueThemeKeys:["--ring-width"],hasDefaultValue:!0}]);let M="var(--tw-ring-inset, ) 0 0 0 var(--tw-ring-offset-width) var(--tw-ring-offset-color)";r.functional("ring-offset",N=>{if(N.value){if(N.value.kind==="arbitrary"){let _=N.value.value;return(N.value.dataType??X(_,["color","length"]))==="length"?N.modifier?void 0:[s("--tw-ring-offset-width",_),s("--tw-ring-offset-shadow",M)]:(_=ne(_,N.modifier,e),_===null?void 0:[s("--tw-ring-offset-color",_)])}{let _=e.resolve(N.value.value,["--ring-offset-width"]);if(_)return N.modifier?void 0:[s("--tw-ring-offset-width",_),s("--tw-ring-offset-shadow",M)];if(D(N.value.value))return N.modifier?void 0:[s("--tw-ring-offset-width",`${N.value.value}px`),s("--tw-ring-offset-shadow",M)]}{let _=ae(N,e,["--ring-offset-color","--color"]);if(_)return[s("--tw-ring-offset-color",_)]}}})}return i("ring-offset",()=>[{values:["current","inherit","transparent"],valueThemeKeys:["--ring-offset-color","--color"],modifierThemeKeys:["--opacity"],modifiers:Array.from({length:21},(a,g)=>`${g*5}`)},{values:["0","1","2","4","8"],valueThemeKeys:["--ring-offset-width"]}]),r.functional("@container",a=>{let g=null;if(a.value===null?g="inline-size":a.value.kind==="arbitrary"?g=a.value.value:a.value.kind==="named"&&a.value.value==="normal"?g="normal":a.value.kind==="named"&&a.value.value==="size"&&(g="size"),g!==null)return a.modifier?[s("container-type",g),s("container-name",a.modifier.value)]:[s("container-type",g)]}),i("@container",()=>[{values:["normal"],valueThemeKeys:[],hasDefaultValue:!0}]),r}var Cr=["number","integer","ratio","percentage"];function Di(e){let r=Ae(e.params);return go(r)?i=>{let t={"--value":{usedSpacingInteger:!1,usedSpacingNumber:!1,themeKeys:new Set,literals:new Set},"--modifier":{usedSpacingInteger:!1,usedSpacingNumber:!1,themeKeys:new Set,literals:new Set}};I(e.nodes,n=>{if(n.kind!=="declaration"||!n.value||!n.value.includes("--value(")&&!n.value.includes("--modifier("))return;let o=Y(n.value);I(o,l=>{if(l.kind!=="function")return;if(l.value==="--spacing"&&!(t["--modifier"].usedSpacingNumber&&t["--value"].usedSpacingNumber))return I(l.nodes,u=>{if(u.kind!=="function"||u.value!=="--value"&&u.value!=="--modifier")return;let c=u.value;for(let d of u.nodes)if(d.kind==="word"){if(d.value==="integer")t[c].usedSpacingInteger||=!0;else if(d.value==="number"&&(t[c].usedSpacingNumber||=!0,t["--modifier"].usedSpacingNumber&&t["--value"].usedSpacingNumber))return V.Stop}}),V.Continue;if(l.value!=="--value"&&l.value!=="--modifier")return;let f=j(B(l.nodes),",");for(let[u,c]of f.entries()){if(c=c.trim(),c.startsWith("--default(")){f[u]=c;continue}c=c.replace(/\\\*/g,"*"),c=c.replace(/--(.*?)\s--(.*?)/g,"--$1-*--$2"),c=c.replace(/\s+/g,""),c=c.replace(/(-\*){2,}/g,"-*"),c[0]==="-"&&c[1]==="-"&&!c.includes("(")&&!c.includes("-*")&&(c+="-*"),f[u]=c}l.nodes=Y(f.join(","));for(let[u,c]of l.nodes.entries())if(c.kind==="word"&&(c.value[0]==='"'||c.value[0]==="'")&&c.value[0]===c.value[c.value.length-1]){let d=c.value.slice(1,-1);t[l.value].literals.add(d)}else if(c.kind==="word"&&c.value[0]==="-"&&c.value[1]==="-"){let d=c.value.replace(/-\*.*$/g,"");t[l.value].themeKeys.add(d)}else if(c.kind==="word"&&!(c.value[0]==="["&&c.value[c.value.length-1]==="]")&&!Cr.includes(c.value)){console.warn(`Unsupported bare value data type: "${c.value}". +Only valid data types are: ${Cr.map(p=>`"${p}"`).join(", ")}. +`);let d=l.value.length+1+B(l.nodes.slice(0,u)).length,m=["```css",B([l])," ".repeat(d)+"^".repeat(c.value.length),"```"].join(` +`);console.warn(m)}}),n.value=B(o)}),i.utilities.functional(r.slice(0,-2),n=>{let o=le(e),l=n.value,f=n.modifier,u=!1,c=!1,d=!1,m=!1,p=new Map,h=!1;if(I([o],(k,w)=>{let b=w.parent;if(b?.kind!=="rule"&&b?.kind!=="at-rule"||k.kind!=="declaration"||!k.value)return;let A=!1,C=Y(k.value);if(I(C,y=>{if(y.kind==="function"){if(y.value==="--value"){u=!0;let E=Pi(l,y,i);return E?(c=!0,E.ratio?h=!0:p.set(k,b),V.ReplaceSkip(E.nodes)):(A=!0,V.Stop)}else if(y.value==="--modifier"){d=!0;let E=Pi(f,y,i);return E?(m=!0,V.ReplaceSkip(E.nodes)):(A=!0,V.Stop)}}}),A)return V.ReplaceSkip([]);k.value=B(C)}),!u||!c||d&&!m&&f!==null||h&&m||f&&!h&&!m)return null;if(h)for(let[k,w]of p){let b=w.nodes.indexOf(k);b!==-1&&w.nodes.splice(b,1)}return o.nodes}),i.utilities.suggest(r.slice(0,-2),()=>{let n=[],o=[];for(let[l,{literals:f,usedSpacingNumber:u,usedSpacingInteger:c,themeKeys:d}]of[[n,t["--value"]],[o,t["--modifier"]]]){for(let m of f)l.push(m);if(u)l.push(...Ut);else if(c)for(let m of Ut)D(m)&&l.push(m);for(let m of i.theme.keysInNamespaces(d))l.push(m.replace(_i,(p,h,k)=>`${h}.${k}`))}return[{values:n,modifiers:o}]})}:mo(r)?i=>{i.utilities.static(r,()=>e.nodes.map(le))}:null}function Pi(e,r,i){if(e===null){for(let t of r.nodes)if(t.kind==="function"&&t.value==="--default")return{nodes:t.nodes};return}for(let t of r.nodes){if(e.kind==="named"&&t.kind==="word"&&(t.value[0]==="'"||t.value[0]==='"')&&t.value[t.value.length-1]===t.value[0]&&t.value.slice(1,-1)===e.value)return{nodes:Y(e.value)};if(e.kind==="named"&&t.kind==="word"&&t.value[0]==="-"&&t.value[1]==="-"){let n=t.value;if(n.endsWith("-*")){n=n.slice(0,-2);let o=i.theme.resolve(e.value,[n]);if(o)return{nodes:Y(o)}}else{let o=n.split("-*");if(o.length<=1)continue;let l=[o.shift()],f=i.theme.resolveWith(e.value,l,o);if(f){let[,u={}]=f;{let c=u[o.pop()];if(c)return{nodes:Y(c)}}}}}else if(e.kind==="named"&&t.kind==="word"){if(!Cr.includes(t.value))continue;let n=t.value==="ratio"&&"fraction"in e?e.fraction:e.value;if(!n)continue;let o=X(n,[t.value]);if(o===null)continue;if(o==="ratio"){let[l,f]=j(n,"/").map(Number);if(!D(l)||!D(f))continue}else{if(o==="number"&&!te(n))continue;if(o==="percentage"&&!D(n.slice(0,-1)))continue}if(o==="ratio"){let[l,f]=j(n,"/");return{nodes:Y(`${l.trim()} / ${f.trim()}`),ratio:!0}}return{nodes:Y(n),ratio:!1}}else if(e.kind==="arbitrary"&&t.kind==="word"&&t.value[0]==="["&&t.value[t.value.length-1]==="]"){let n=t.value.slice(1,-1);if(n==="*")return{nodes:Y(e.value)};if("dataType"in e&&e.dataType&&e.dataType!==n)continue;if("dataType"in e&&e.dataType)return{nodes:Y(e.value)};if(X(e.value,[n])!==null)return{nodes:Y(e.value)}}}}function Ve(e,r,i,t,n=""){let o=!1,l=ut(r,u=>i==null?t(u):u.startsWith("current")?t(ie(u,i)):((u.startsWith("var(")||i.startsWith("var("))&&(o=!0),t(Oi(u,i))));function f(u){return n?j(u,",").map(c=>n.trim()+" "+c.trim()).join(", "):u}return o?[s(e,f(ut(r,t))),J("@supports (color: lab(from red l a b))",[s(e,f(l))])]:[s(e,f(l))]}function _t(e,r,i,t,n=""){let o=!1,l=j(r,",").map(f=>ut(f,u=>i==null?t(u):u.startsWith("current")?t(ie(u,i)):((u.startsWith("var(")||i.startsWith("var("))&&(o=!0),t(Oi(u,i))))).map(f=>`drop-shadow(${f})`).join(" ");return o?[s(e,n+j(r,",").map(f=>`drop-shadow(${ut(f,t)})`).join(" ")),J("@supports (color: lab(from red l a b))",[s(e,n+l)])]:[s(e,n+l)]}var Ui=/^-?[a-z][a-zA-Z0-9_-]*/,no=37,lo=47,oo=46,ao=97,so=122,uo=65,co=90,It=48,Dt=57,fo=95,po=45;function mo(e){let r=Ui.exec(e);if(r===null)return!1;let i=r[0],t=e.slice(i.length);if(t.length===0&&i.endsWith("-"))return!1;if(t.length===0)return!0;let n=!1;for(let o=0;oDt)return!1;break}case lo:{if(o===t.length-1||n)return!1;n=!0;break}case oo:{let u=(t[o-1]||i[i.length-1]||"").charCodeAt(0);if(uDt)return!1;let d=(t[o+1]||"").charCodeAt(0);if(dDt)return!1;break}case fo:case po:continue;default:{if(l>=ao&&l<=so||l>=uo&&l<=co||l>=It&&l<=Dt)continue;return!1}}}return!0}function go(e){if(!e.endsWith("-*"))return!1;e=e.slice(0,-2);let r=Ui.exec(e);if(r===null)return!1;let i=r[0];return e.slice(i.length).length===0}var Sr={"--alpha":ho,"--spacing":vo,"--theme":ko,theme:bo};function ho(e,r,i,...t){let[n,o]=j(i,"/").map(l=>l.trim());if(!n||!o)throw new Error(`The --alpha(\u2026) function requires a color and an alpha value, e.g.: \`--alpha(${n||"var(--my-color)"} / ${o||"50%"})\``);if(t.length>0)throw new Error(`The --alpha(\u2026) function only accepts one argument, e.g.: \`--alpha(${n||"var(--my-color)"} / ${o||"50%"})\``);return ie(n,o)}function vo(e,r,i,...t){if(!i)throw new Error("The --spacing(\u2026) function requires an argument, but received none.");if(t.length>0)throw new Error(`The --spacing(\u2026) function only accepts a single argument, but received ${t.length+1}.`);let n=e.theme.resolve(null,["--spacing"]);if(!n)throw new Error("The --spacing(\u2026) function requires that the `--spacing` theme variable exists, but it was not found.");let o=oe.get(i);if(o){if(o[0]===0)return"0px";if(o[0]===1)return n}return`calc(${n} * ${i})`}function ko(e,r,i,...t){if(!i.startsWith("--"))throw new Error("The --theme(\u2026) function can only be used with CSS variables from your theme.");let n=!1;i.endsWith(" inline")&&(n=!0,i=i.slice(0,-7)),r.kind==="at-rule"&&(n=!0);let o=e.resolveThemeValue(i,n);if(!o){if(t.length>0)return t.join(", ");throw new Error(`Could not resolve value for theme function: \`theme(${i})\`. Consider checking if the variable name is correct or provide a fallback value to silence this error.`)}if(t.length===0)return o;let l=t.join(", ");if(l==="initial")return o;if(o==="initial")return l;if(o.startsWith("var(")||o.startsWith("theme(")||o.startsWith("--theme(")){let f=Y(o);return yo(f,l),B(f)}return o}function bo(e,r,i,...t){i=wo(i);let n=e.resolveThemeValue(i);if(!n&&t.length>0)return t.join(", ");if(!n)throw new Error(`Could not resolve value for theme function: \`theme(${i})\`. Consider checking if the path is correct or provide a fallback value to silence this error.`);return n}var Li=new RegExp(Object.keys(Sr).map(e=>`${e}\\(`).join("|"));function He(e,r){let i=0;return I(e,t=>{if(t.kind==="declaration"&&t.value&&Li.test(t.value)){i|=8,t.value=Ki(t.value,t,r);return}t.kind==="at-rule"&&(t.name==="@media"||t.name==="@custom-media"||t.name==="@container"||t.name==="@supports")&&Li.test(t.params)&&(i|=8,t.params=Ki(t.params,t,r))}),i}function Ki(e,r,i){let t=Y(e);return I(t,n=>{if(n.kind==="function"&&n.value in Sr){let o=j(B(n.nodes).trim(),",").map(f=>f.trim()),l=Sr[n.value](i,r,...o);return V.Replace(Y(l))}}),B(t)}function wo(e){if(e[0]!=="'"&&e[0]!=='"')return e;let r="",i=e[0];for(let t=1;t{if(i.kind==="function"&&!(i.value!=="var"&&i.value!=="theme"&&i.value!=="--theme"))if(i.nodes.length===1)i.nodes.push({kind:"word",value:`, ${r}`});else{let t=i.nodes[i.nodes.length-1];t.kind==="word"&&t.value==="initial"&&(t.value=r)}})}function Lt(e,r){let i=e.length,t=r.length,n=i=48&&l<=57&&f>=48&&f<=57){let u=o,c=o+1,d=o,m=o+1;for(l=e.charCodeAt(c);l>=48&&l<=57;)l=e.charCodeAt(++c);for(f=r.charCodeAt(m);f>=48&&f<=57;)f=r.charCodeAt(++m);let p=e.slice(u,c),h=r.slice(d,m),k=Number(p)-Number(h);if(k)return k;if(ph)return 1;continue}if(l!==f)return l-f}return e.length-r.length}function Ze(e){if(e[0]!=="["||e[e.length-1]!=="]")return null;let r=1,i=r,t=e.length-1;for(;Ge(e.charCodeAt(r));)r++;{for(i=r;r=65&&d<=90)&&!(d>=97&&d<=122)&&!(d>=48&&d<=57)&&!(d===45||d===95)&&!(d>=128))break}if(i===r)return null}let n=e.slice(i,r);for(;Ge(e.charCodeAt(r));)r++;if(r===t)return{attribute:n,operator:null,quote:null,value:null,sensitivity:null};let o=null,l=e.charCodeAt(r);if(l===61)o="=",r++;else if((l===126||l===124||l===94||l===36||l===42)&&e.charCodeAt(r+1)===61)o=e[r]+"=",r+=2;else return null;for(;Ge(e.charCodeAt(r));)r++;if(r===t)return null;let f="",u=null;if(l=e.charCodeAt(r),l===39||l===34){u=e[r],r++,i=r;for(let d=r;d0;if(o!==f)return(o??"").localeCompare(f??"")>0}return B([e]).localeCompare(B([r]))>0}function Qe(e,r=null){return Array.isArray(e)&&e.length===2&&typeof e[1]=="object"&&typeof e[1]!==null?r?e[1][r]??null:e[0]:Array.isArray(e)&&r===null?e.join(", "):typeof e=="string"&&r===null?e:null}function ji(e,{theme:r},i){for(let t of i){let n=Je([t]);n&&e.theme.clearNamespace(`--${n}`,4)}for(let[t,n]of Ao(r)){if(typeof n!="string"&&typeof n!="number")continue;if(typeof n=="string"&&(n=n.replace(//g,"1")),t[0]==="opacity"&&(typeof n=="number"||typeof n=="string")){let l=typeof n=="string"?parseFloat(n):n;l>=0&&l<=1&&(n=l*100+"%")}let o=Je(t);o&&e.theme.add(`--${o}`,""+n,7)}if(Object.hasOwn(r,"fontFamily")){let t=5;{let n=Qe(r.fontFamily.sans);n&&e.theme.hasDefault("--font-sans")&&(e.theme.add("--default-font-family",n,t),e.theme.add("--default-font-feature-settings",Qe(r.fontFamily.sans,"fontFeatureSettings")??"normal",t),e.theme.add("--default-font-variation-settings",Qe(r.fontFamily.sans,"fontVariationSettings")??"normal",t))}{let n=Qe(r.fontFamily.mono);n&&e.theme.hasDefault("--font-mono")&&(e.theme.add("--default-mono-font-family",n,t),e.theme.add("--default-mono-font-feature-settings",Qe(r.fontFamily.mono,"fontFeatureSettings")??"normal",t),e.theme.add("--default-mono-font-variation-settings",Qe(r.fontFamily.mono,"fontVariationSettings")??"normal",t))}}return r}function Ao(e){let r=[];return Fi(e,[],(i,t)=>{if(To(i))return r.push([t,i]),1;if($o(i)){r.push([t,i[0]]);for(let n of Reflect.ownKeys(i[1]))r.push([[...t,`-${n}`],i[1][n]]);return 1}if(Array.isArray(i)&&i.every(n=>typeof n=="string"))return t[0]==="fontSize"?(r.push([t,i[0]]),i.length>=2&&r.push([[...t,"-line-height"],i[1]])):r.push([t,i.join(", ")]),1}),r}var Co={borderWidth:"border-width",outlineWidth:"outline-width",ringColor:"ring-color",ringWidth:"ring-width",transitionDuration:"transition-duration",transitionTimingFunction:"transition-timing-function"},So={animation:"animate",aspectRatio:"aspect",borderRadius:"radius",boxShadow:"shadow",colors:"color",containers:"container",fontFamily:"font",fontSize:"text",letterSpacing:"tracking",lineHeight:"leading",maxWidth:"container",screens:"breakpoint",transitionTimingFunction:"ease"},Vo=/^[a-zA-Z0-9-_%/.]+$/;function Je(e){let r=Co[e[0]];if(r&&e[1]==="DEFAULT")return`default-${r}`;if(e[0]==="container")return null;for(let t of e)if(!Vo.test(t))return null;let i=So[e[0]];return i&&(e=e.slice(),e[0]=i),e.map((t,n,o)=>t==="1"&&n!==o.length-1?"":t).map((t,n)=>(t=t.replaceAll(".","_"),(n===0||t.startsWith("-")||t==="lineHeight")&&(t=t.replace(/([a-z])([A-Z])/g,(l,f,u)=>`${f}-${u.toLowerCase()}`)),t)).filter((t,n)=>t!=="DEFAULT"||n!==e.length-1).join("-")}function To(e){return typeof e=="number"||typeof e=="string"}function $o(e){if(!Array.isArray(e)||e.length!==2||typeof e[0]!="string"&&typeof e[0]!="number"||e[1]===void 0||e[1]===null||typeof e[1]!="object")return!1;for(let r of Reflect.ownKeys(e[1]))if(typeof r!="string"||typeof e[1][r]!="string"&&typeof e[1][r]!="number")return!1;return!0}function Fi(e,r=[],i){for(let t of Reflect.ownKeys(e)){let n=e[t];if(n==null)continue;let o=[...r,t],l=i(n,o)??0;if(l!==1){if(l===2)return 2;if(!(!Array.isArray(n)&&typeof n!="object")&&Fi(n,o,i)===2)return 2}}}function ct(e,r=null,i=!0){let[t,n]=ft(Y(e),r,i);return t?B(n):e}function ft(e,r=null,i=!0){let t=!1;return I(e,{exit(n,o){if(n.kind==="word"&&n.value!=="0"){let l=Wi(n.value,r,i);if(l===null||l===n.value)return;if(l==="0"&&o.parent?.kind==="function"){let f=Wi(n.value,r,!1);return f===null?void 0:(t=!0,V.ReplaceSkip(re(f)))}return t=!0,V.ReplaceSkip(re(l))}else if(n.kind==="function"&&(n.value==="calc"||n.value==="")){if(n.nodes.length!==5||n.nodes[2].kind!=="word")return;let l=n.nodes[0],f=n.nodes[2].value,u=n.nodes[4],c=l.kind==="word"?oe.get(l.value):null,d=u.kind==="word"?oe.get(u.value):null;if(f==="*"&&(c?.[0]===0&&c?.[1]===null||d?.[0]===0&&d?.[1]===null))return t=!0,V.ReplaceSkip(re("0"));if(f==="*"&&c?.[0]===0&&c?.[1]!==null&&d?.[1]===null)return t=!0,o.parent?.kind==="function"?V.ReplaceSkip(re(`0${c[1]}`)):V.ReplaceSkip(re("0"));if(f==="*"&&d?.[0]===0&&d?.[1]!==null&&c?.[1]===null)return t=!0,o.parent?.kind==="function"?V.ReplaceSkip(re(`0${d[1]}`)):V.ReplaceSkip(re("0"));if(f==="*"){if(c?.[0]===1&&c?.[1]===null)return t=!0,V.ReplaceSkip(u);if(d?.[0]===1&&d?.[1]===null)return t=!0,V.ReplaceSkip(l)}if(f==="*"||f==="+"){let m=c??d,p=c===null?l:d===null?u:null;if(m!==null&&p!==null&&p.kind==="function"&&(p.value==="calc"||p.value==="")&&p.nodes.length===5&&p.nodes[2].kind==="word"&&p.nodes[2].value===f){let h=p.nodes[0],k=p.nodes[4],w=h.kind==="word"?oe.get(h.value):null,b=k.kind==="word"?oe.get(k.value):null,A=w??b,C=w===null?h:b===null?k:null;if(A!==null&&C!==null){if(f==="*"&&!(m[1]===null&&A[1]===null||m[1]===null&&A[1]!==null||m[1]!==null&&A[1]===null)||f==="+"&&m[1]!==A[1])return;let y;switch(f){case"*":{y=`${m[0]*A[0]}${m[1]??A[1]??""}`;break}case"+":{y=`${m[0]+A[0]}${m[1]??A[1]??""}`;break}default:return}if(t=!0,f==="*"&&y==="1")return V.ReplaceSkip(C);let E={kind:"function",value:n.value,nodes:[re(y),n.nodes[1],n.nodes[2],n.nodes[3],C]};return V.ReplaceSkip(E)}}}if(c===null||d===null)return;switch(f){case"*":{if(c[1]===d[1]||c[1]===null&&d[1]!==null||c[1]!==null&&d[1]===null)return t=!0,V.ReplaceSkip(re(`${c[0]*d[0]}${c[1]??d[1]??""}`));break}case"+":{if(c[1]===d[1])return t=!0,V.ReplaceSkip(re(`${c[0]+d[0]}${c[1]??""}`));break}case"-":{if(c[1]===d[1])return t=!0,V.ReplaceSkip(re(`${c[0]-d[0]}${c[1]??""}`));break}case"/":{if(d[0]!==0&&(c[1]===null&&d[1]===null||c[1]!==null&&d[1]===null)){let m=c[0]/d[0];if(Math.round(m*100)/100!==m)break;return t=!0,V.ReplaceSkip(re(`${m}${c[1]??""}`))}break}}}}}),[t,e]}function Wi(e,r=null,i=!0){let t=oe.get(e);if(t===null)return null;let[n,o]=t;if(o===null)return`${n}`;if(n===0&&Se(e))return i?"0":`0${o}`;if(!i)return`${e}`;switch(o.toLowerCase()){case"in":return`${n*96}px`;case"cm":return`${n*96/2.54}px`;case"mm":return`${n*96/2.54/10}px`;case"q":return`${n*96/2.54/10/4}px`;case"pc":return`${n*96/6}px`;case"pt":return`${n*96/72}px`;case"rem":return r!==null?`${n*r}px`:null;case"grad":return`${n*.9}deg`;case"rad":return`${n*180/Math.PI}deg`;case"turn":return`${n*360}deg`;case"ms":return`${n/1e3}s`;case"khz":return`${n*1e3}hz`;default:return`${n}${o}`}}function Le(e,r="top",i="right",t="bottom",n="left"){return Hi(`${e}-${r}`,`${e}-${i}`,`${e}-${t}`,`${e}-${n}`)}function Hi(e="top",r="right",i="bottom",t="left"){return{1:[[e,0],[r,0],[i,0],[t,0]],2:[[e,0],[r,1],[i,0],[t,1]],3:[[e,0],[r,1],[i,2],[t,1]],4:[[e,0],[r,1],[i,2],[t,3]]}}function fe(e,r){return{1:[[e,0],[r,0]],2:[[e,0],[r,1]]}}var Bi={inset:Hi(),margin:Le("margin"),padding:Le("padding"),"scroll-margin":Le("scroll-margin"),"scroll-padding":Le("scroll-padding"),"border-width":Le("border","top-width","right-width","bottom-width","left-width"),"border-style":Le("border","top-style","right-style","bottom-style","left-style"),"border-color":Le("border","top-color","right-color","bottom-color","left-color"),gap:fe("row-gap","column-gap"),overflow:fe("overflow-x","overflow-y"),"overscroll-behavior":fe("overscroll-behavior-x","overscroll-behavior-y")},Yi={"inset-block":fe("top","bottom"),"inset-inline":fe("left","right"),"margin-block":fe("margin-top","margin-bottom"),"margin-inline":fe("margin-left","margin-right"),"padding-block":fe("padding-top","padding-bottom"),"padding-inline":fe("padding-left","padding-right"),"scroll-margin-block":fe("scroll-margin-top","scroll-margin-bottom"),"scroll-margin-inline":fe("scroll-margin-left","scroll-margin-right"),"scroll-padding-block":fe("scroll-padding-top","scroll-padding-bottom"),"scroll-padding-inline":fe("scroll-padding-left","scroll-padding-right")},qi={"border-block":["border-bottom","border-top"],"border-block-color":["border-bottom-color","border-top-color"],"border-block-style":["border-bottom-style","border-top-style"],"border-block-width":["border-bottom-width","border-top-width"],"border-inline":["border-left","border-right"],"border-inline-color":["border-left-color","border-right-color"],"border-inline-style":["border-left-style","border-right-style"],"border-inline-width":["border-left-width","border-right-width"]};function Gi(e,r){if(r&2){if(e.property in Yi){let i=j(e.value," ");return Yi[e.property][i.length]?.map(([t,n])=>s(t,i[n],e.important))}if(e.property in qi)return qi[e.property]?.map(i=>s(i,e.value,e.important))}if(e.property in Bi){let i=j(e.value," ");return Bi[e.property][i.length]?.map(([t,n])=>s(t,i[n],e.important))}return null}function ge(e,r){for(let i in e)delete e[i];return Object.assign(e,r)}function Ke(e){let r=[];for(let i of j(e,".")){if(!i.includes("[")){r.push(i);continue}let t=0;for(;;){let n=i.indexOf("[",t),o=i.indexOf("]",n);if(n===-1||o===-1)break;n>t&&r.push(i.slice(t,n)),r.push(i.slice(n+1,o)),t=o+1}t<=i.length-1&&r.push(i.slice(t))}return r}function Vr(e,r){let i=e;return i.storage[tn]??=No(),i.storage[rn]??=Po(i),i.storage[nn]??=Do(),i.storage[ln]??=Lo(),i.storage[on]??=zo(),i.storage[$r]??=Yo(i),i.storage[Mt]??=Go(i,r),i.storage[we]??=ca(i),i.storage[cn]??=fa(i),i.storage[Nr]??=ga(),i.storage[jt]??=ha(i),i.storage[Er]??=va(i),i.storage[Wt]??=ka(i),i.storage[dn]??=ba(i),i.storage[pt]??=Eo(i),i}var tn=Symbol();function No(){return new K(e=>new K(r=>({rem:e,features:r})))}var pt=Symbol();function Eo(e){return new K(r=>{let i=e.storage[we].get(r);return function(n,o){let l=typeof n=="string"?n:e.printCandidate(n),f=i.get(l);if(typeof f!="string")return!1;let u=typeof o=="string"?o:e.printCandidate(o),c=i.get(u);return typeof c!="string"?!1:f===c}})}function Ro(e,r){let i=0;return r?.collapse&&(i|=1),r?.logicalToPhysical&&(i|=2),Vr(e,r).storage[tn].get(r?.rem??null).get(i)}var rn=Symbol();function Po(e){return new K(r=>new K(i=>({features:i,designSystem:e,signatureOptions:r})))}function Oo(e,r,i){let t=0;return i?.collapse&&(t|=1),Vr(e).storage[rn].get(r).get(t)}function Tr(e,r,i){let t=Ro(e,i),n=Oo(e,t,i),o=Vr(e),l=new Set,f=o.storage[nn].get(n);for(let u of r)l.add(f.get(u));return l.size<=1||!(n.features&1)?Array.from(l):_o(n,Array.from(l))}function _o(e,r){let i=e.designSystem,t=new K(f=>new K(u=>new Set)),n=e.designSystem.theme.prefix?`${e.designSystem.theme.prefix}:`:"";for(let f of r){let u=j(f,":"),c=u.pop(),d=c.endsWith("!");d&&(c=c.slice(0,-1));let m=u.length>0?`${u.join(":")}:`:"",p=d?"!":"";t.get(m).get(p).add(`${n}${c}`)}let o=new Set;for(let[f,u]of t.entries())for(let[c,d]of u.entries())for(let m of l(Array.from(d)))n&&m.startsWith(n)&&(m=m.slice(n.length)),o.add(`${f}${m}${c}`);return Array.from(o);function l(f){let u=e.signatureOptions,c=i.storage[jt].get(u),d=i.storage[Nr].get(u),m=i.storage[cn].get(u),p=f.map(U=>c.get(U));if(p.some(U=>U.has("line-height"))){let U=i.theme.keysInNamespaces(["--text"]);if(U.length>0){let z=new Set,F=new Set;for(let a of p)if(a.has("line-height"))for(let g of a.get("line-height")){if(F.has(g))continue;F.add(g);let v=i.storage[Mt]?.get(g)??null;if(v!==null)if(te(v)){z.add(v);for(let S of U)c.get(`text-${S}/${v}`)}else{z.add(g);for(let S of U)c.get(`text-${S}/[${g}]`)}}let Z=new Set;for(let a of p)if(a.has("font-size")){for(let g of a.get("font-size"))if(!Z.has(g)){Z.add(g);for(let v of z)te(v)?c.get(`text-[${g}]/${v}`):c.get(`text-[${g}]/[${v}]`)}}}}let h=new K(U=>{let z=new K(Z=>new K(a=>new Set)),F=new Set(c.get(U).keys());if(F.size===0)return z;for(let Z of he(i,U))if(!(Z.kind!=="functional"||Z.value===null)){for(let a of i.utilities.keys("functional")){if(a===Z.root)continue;let g=an(i,{...qe(Z),root:a}),v=c.get(g);for(let[S,x]of v)if(F.has(S))for(let $ of x)z.get(S).get($).add(g)}return z}return z}),k=p.map((U,z)=>{let F=null;for(let Z of U.keys()){let a=new Set;for(let g of d.get(Z).values())for(let v of g)a.add(v);for(let g of U.get(Z))for(let v of h.get(f[z]).get(Z).get(g))a.add(v);if(F===null?F=a:F=en(F,a),F.size===0)return F}return F??new Set}),w=new Set,b=new Set;for(let U of k)for(let z of U)w.has(z)?b.add(z):w.add(z);let A=new K(U=>new Set);for(let[U,z]of k.entries())for(let F of z){if(!b.has(F))continue;let Z=A.get(F);for(let a of p[U].keys())Z.add(a)}let C=new K(U=>{let z=A.get(U);for(let F of c.get(U).keys())if(!z.has(F))return!1;return!0});k=k.map(U=>{let z=new Set;for(let F of U)b.has(F)&&C.get(F)&&z.add(F);return z});let y=new K(U=>new Set([U]));for(let U=0;UU.split(",").map(Number));for(let U of y.values()){let z=Array.from(U).sort((F,Z)=>F-Z);E.get(z.join(","))}let O=[];for(let U of y.keys())try{i.getClassOrder([f[U]]),O.push(f[U])}catch{}let P=new Map(i.getClassOrder(O));function L(U,z){return U===z?0:U===null?1:z===null||UW.has(f[v])))continue;let F=z.flatMap(v=>k[v]).reduce(en);if(F.size===0)continue;let Z=z.map(v=>f[v]).sort((v,S)=>v.localeCompare(S)).join(" "),a=i.storage[we].get(u).get(Z),g=new Set(z.map(v=>f[v]).sort((v,S)=>L(P.get(S)??null,P.get(v)??null)));for(let v of F)g.add(v);for(let v of g)if(i.storage[we].get(u).get(v)===a&&Io(m.get(Z),m.get(v))){R.add(v);for(let x of z)f[x]!==v&&W.add(f[x]);break}}for(let U of W)R.delete(U);return Array.from(R)}}function Io(e,r){return e===null||r===null||e.length!==r.length?!1:e.every((i,t)=>i===""||i===r[t])}var nn=Symbol();function Do(){return new K(e=>{let r=e.designSystem,i=r.theme.prefix?`${r.theme.prefix}:`:"",t=r.storage[ln].get(e),n=r.storage[on].get(e);return new K((o,l)=>{for(let f of r.parseCandidate(o)){let u=f.variants.slice().reverse().flatMap(m=>t.get(m)),c=f.important;if(c||u.length>0){let p=l.get(r.printCandidate({...f,variants:[],important:!1}));return r.theme.prefix!==null&&u.length>0&&(p=p.slice(i.length)),u.length>0&&(p=`${u.map(h=>r.printVariant(h)).join(":")}:${p}`),c&&(p+="!"),r.theme.prefix!==null&&u.length>0&&(p=`${i}${p}`),p}let d=n.get(o);if(d!==o)return d}return o})})}var Uo=[Wo,oa,aa,ia],ln=Symbol();function Lo(){return new K(e=>new K(r=>{let i=[r];for(let t of Uo)for(let n of i.splice(0)){let o=t(Be(n),e);if(Array.isArray(o)){i.push(...o);continue}else i.push(o)}return i}))}var Ko=[jo,Fo,Bo,sa,Zo,Jo,ra,na,la,ua],on=Symbol();function zo(){return new K(e=>{let r=e.designSystem;return new K(i=>{for(let t of r.parseCandidate(i)){let n=qe(t);for(let l of Ko)n=l(n,e);let o=r.printCandidate(n);if(i!==o)return o}return i})})}var Mo=["t","tr","r","br","b","bl","l","tl"];function jo(e){if(e.kind==="static"&&e.root.startsWith("bg-gradient-to-")){let r=e.root.slice(15);return Mo.includes(r)&&(e.root=`bg-linear-to-${r}`),e}return e}function Fo(e,r){let i=r.designSystem.storage[$r];if(e.kind==="arbitrary"){let[t,n]=i(e.value,e.modifier===null?1:0);t!==e.value&&(e.value=t,n!==null&&(e.modifier=n))}else if(e.kind==="functional"&&e.value?.kind==="arbitrary"){let[t,n]=i(e.value.value,e.modifier===null?1:0);t!==e.value.value&&(e.value.value=t,n!==null&&(e.modifier=n))}return e}function Wo(e,r){let i=r.designSystem.storage[$r],t=Ft(e);for(let[n]of t)if(n.kind==="arbitrary"){let[o]=i(n.selector,2);o!==n.selector&&(n.selector=o)}else if(n.kind==="functional"&&n.value?.kind==="arbitrary"){let[o]=i(n.value.value,2);o!==n.value.value&&(n.value.value=o)}return e}function Bo(e,r){return e.kind==="arbitrary"?e.value=Zi(e.value,r.designSystem):e.kind==="functional"&&e.value?.kind==="arbitrary"&&(e.value.value=Zi(e.value.value,r.designSystem)),e}function Zi(e,r){let i=r.theme.prefix?`--${r.theme.prefix}-spacing`:"--spacing",t=Y(e);return I(t,n=>{if(!(n.kind!=="function"||n.value!=="calc")&&n.nodes.length===5&&!(n.nodes[2].kind!=="word"||n.nodes[2].value!=="*")&&!(n.nodes[0].kind!=="function"||n.nodes[0].value!=="var"||n.nodes[0].nodes.length!==1||n.nodes[0].nodes[0].kind!=="word"||n.nodes[0].nodes[0].value!==i))return V.Replace(Y(`--spacing(${B([n.nodes[4]])})`))}),B(t)}var $r=Symbol();function Yo(e){return r(e);function r(i){function t(c,d=0){let m=Y(c);if(d&2)return[Kt(m,u),null];let p=0,h=0;if(I(m,b=>{b.kind==="function"&&b.value==="theme"&&(p+=1,I(b.nodes,A=>A.kind==="separator"&&A.value.includes(",")?V.Stop:A.kind==="word"&&A.value==="/"?(h+=1,V.Stop):V.Skip))}),p===0)return[c,null];if(h===0)return[Kt(m,f),null];if(h>1)return[Kt(m,u),null];let k=null;return[Kt(m,(b,A)=>{let C=j(b,"/").map(y=>y.trim());if(C.length>2)return null;if(m.length===1&&C.length===2&&d&1){let[y,E]=C;/^\d+%$/.test(E)?k=n(Number(E.slice(0,-1))):/^0?\.\d+$/.test(E)?k=n(o(Number(E))):k={kind:"arbitrary",value:E},b=y}return f(b,A)||u(b,A)}),k]}function n(c){if(Number.isInteger(c)){let d=i.theme.resolveValue(`${c}`,["--opacity"]);if(d===null)return{kind:"named",value:`${c}`};if((d.endsWith("%")?Number(d.slice(0,-1)):o(Number(d)))===c)return{kind:"named",value:`${c}`}}return{kind:"arbitrary",value:`${c}%`}}function o(c){return Number((c*100).toFixed(10))}function l(c,d=!0){let m=`--${Je(Ke(c))}`;return i.theme.get([m])?d&&i.theme.prefix?`--${i.theme.prefix}-${m.slice(2)}`:m:null}function f(c,d){let m=l(c);if(m)return d?`var(${m}, ${d})`:`var(${m})`;let p=Ke(c);if(p[0]==="spacing"&&i.theme.get(["--spacing"])){let h=p[1];return te(h)?`--spacing(${h})`:null}return null}function u(c,d){let m=j(c,"/").map(k=>k.trim());c=m.shift();let p=l(c,!1);if(!p)return null;let h=m.length>0?`/${m.join("/")}`:"";return d?`--theme(${p}${h}, ${d})`:`--theme(${p}${h})`}return t}}function Kt(e,r){return I(e,(i,t)=>{if(i.kind==="function"&&i.value==="theme"){if(i.nodes.length<1)return;i.nodes[0].kind==="separator"&&i.nodes[0].value.trim()===""&&i.nodes.shift();let n=i.nodes[0];if(n.kind!=="word")return;let o=n.value,l=1;for(let c=l;c0?r(o,B(f)):r(o);if(u===null)return;{let c=t.index-1;for(;c!==-1;){let d=t.siblings[c];if(d.kind==="separator"&&d.value.trim()===""){c-=1;continue}/^[-+*/]$/.test(d.value.trim())&&(u=`(${u})`);break}}return V.Replace(Y(u))}}),B(e)}function qo(e){if(e[0]!=="'"&&e[0]!=='"')return e;let r="",i=e[0];for(let t=1;t{if(n===0)return null;let f=oe.get(ct(l,r?.rem??null));if(!f)return null;let[u,c]=f;return c!==o?null:u/n})}function Zo(e,r){if(e.kind!=="arbitrary"&&!(e.kind==="functional"&&e.value?.kind==="arbitrary"))return e;let i=r.designSystem,t=i.storage[Er].get(r.signatureOptions),n=i.storage[we].get(r.signatureOptions),o=i.storage[pt].get(r.signatureOptions),l=i.printCandidate(e),f=n.get(l);if(typeof f!="string")return e;for(let c of u(f,e))if(o(e,c)&&Qo(i,e,c))return c;return e;function*u(c,d){let m=t.get(c);if(m.length>1){let p;for(let h of m)if(h[0]!=="-"){if(p)return;p=h}if(p)for(let h of he(i,p))yield h;return}if(m.length===0&&d.modifier){let p={...d,modifier:null},h=n.get(i.printCandidate(p));if(typeof h=="string")for(let k of u(h,p))yield Object.assign({},k,{modifier:d.modifier})}if(m.length===1)for(let p of he(i,m[0]))yield p;else if(m.length===0){let p=d.kind==="arbitrary"?d.value:d.value?.value??null;if(p===null)return;if(r.signatureOptions.rem!==null&&d.kind==="functional"&&d.value?.kind==="arbitrary"){let w=i.storage[Mt]?.get(p)??null;w!==null&&te(w)&&Qi(w,i,r.signatureOptions.rem)&&(yield Object.assign({},d,{value:{kind:"named",value:w,fraction:null}}))}let h=i.storage[Mt]?.get(p)??null,k="";h!==null&&h<0&&(k="-",h=Math.abs(h));for(let w of Array.from(i.utilities.keys("functional")).sort((b,A)=>+(b[0]==="-")-+(A[0]==="-"))){k&&(w=`${k}${w}`);for(let b of he(i,`${w}-${p}`))yield b;if(d.modifier)for(let b of he(i,`${w}-${p}${d.modifier}`))yield b;if(h!==null&&te(h)&&Qi(h,i,r.signatureOptions.rem)){for(let b of he(i,`${w}-${h}`))yield b;if(d.modifier)for(let b of he(i,`${w}-${h}${st(d.modifier)}`))yield b}for(let b of he(i,`${w}-[${p}]`))yield b;if(d.modifier)for(let b of he(i,`${w}-[${p}]${st(d.modifier)}`))yield b}}}}function Qo(e,r,i){let t=null;if(r.kind==="functional"&&r.value?.kind==="arbitrary"&&r.value.value.includes("var(--")?t=r.value.value:r.kind==="arbitrary"&&r.value.includes("var(--")&&(t=r.value),t===null)return!0;let n=e.candidatesToCss([e.printCandidate(i)]).join(` +`),o=!0;return I(Y(t),l=>{if(l.kind==="function"&&l.value==="var"){let f=l.nodes[0].value;if(!new RegExp(`var\\(${f}[,)]\\s*`,"g").test(n)||n.includes(`${f}:`))return o=!1,V.Stop}}),o}function Jo(e,r){if(e.kind!=="functional"||e.value?.kind!=="named")return e;let i=r.designSystem,t=i.storage[Er].get(r.signatureOptions),n=i.storage[we].get(r.signatureOptions),o=i.storage[pt].get(r.signatureOptions),l=i.printCandidate(e),f=n.get(l);if(typeof f!="string")return e;for(let c of u(f,e))if(o(e,c))return c;return e;function*u(c,d){let m=t.get(c);if(m.length>1){let p;for(let h of m)if(h[0]!=="-"){if(p)return;p=h}if(p)for(let h of he(i,p))yield h;return}if(m.length===0&&d.modifier){let p={...d,modifier:null},h=n.get(i.printCandidate(p));if(typeof h=="string")for(let k of u(h,p))yield Object.assign({},k,{modifier:d.modifier})}if(m.length===1)for(let p of he(i,m[0]))yield p}}var Xo=new Map([["order-none","order-0"],["break-words","wrap-break-word"],["overflow-ellipsis","text-ellipsis"]]),ea=new Map([[/^(-)?start-(.*?)$/,"$1inset-s-$2"],[/^(-)?end-(.*?)$/,"$1inset-e-$2"]]);function*ta(e){let r=Xo.get(e);r&&(yield r);for(let[i,t]of ea){let n=e.replace(i,t);n!==e&&(yield n)}}function ra(e,r){let i=r.designSystem,t=i.storage[pt].get(r.signatureOptions),n=an(i,e);for(let o of ta(n)){if(!t(e,o))continue;let[l]=he(i,o);return l}return e}function ia(e,r){let i=r.designSystem,t=i.storage[Wt].get(r.signatureOptions.rem),n=i.storage[dn].get(r.signatureOptions.rem),o=Ft(e);for(let[l]of o){if(l.kind==="compound")continue;let f=i.printVariant(l),u=t.get(f);if(typeof u!="string")continue;let c=n.get(u);if(c.length===0||c.includes(f))continue;let d=c[0],m=i.parseVariant(d);m!==null&&ge(l,m)}return e}function na(e,r){let i=r.designSystem,t=i.storage[we].get(r.signatureOptions);if(e.kind==="functional"&&e.value?.kind==="arbitrary"&&e.value.dataType!==null){let n=i.printCandidate({...e,value:{...e.value,dataType:null}});t.get(i.printCandidate(e))===t.get(n)&&(e.value.dataType=null)}return e}function la(e,r){if(e.kind!=="functional"||e.value?.kind!=="arbitrary")return e;let i=r.designSystem,t=i.storage[we].get(r.signatureOptions),n=t.get(i.printCandidate(e));if(n===null)return e;for(let o of un(e))if(t.get(i.printCandidate({...e,value:o}))===n)return e.value=o,e;return e}function oa(e){let r=Ft(e);for(let[i]of r)if(i.kind==="functional"&&i.root==="data"&&i.value?.kind==="arbitrary"&&!i.value.value.includes("="))i.value={kind:"named",value:i.value.value};else if(i.kind==="functional"&&i.root==="aria"&&i.value?.kind==="arbitrary"&&(i.value.value.endsWith("=true")||i.value.value.endsWith('="true"')||i.value.value.endsWith("='true'"))){let[t,n]=j(i.value.value,"=");if(t[t.length-1]==="~"||t[t.length-1]==="|"||t[t.length-1]==="^"||t[t.length-1]==="$"||t[t.length-1]==="*")continue;i.value={kind:"named",value:i.value.value.slice(0,i.value.value.indexOf("="))}}else i.kind==="functional"&&i.root==="supports"&&i.value?.kind==="arbitrary"&&/^[a-z-][a-z0-9-]*$/i.test(i.value.value)&&(i.value={kind:"named",value:i.value.value});return e}function*un(e,r=e.value?.value??"",i=new Set){if(i.has(r))return;if(i.add(r),yield{kind:"named",value:r,fraction:null},r.endsWith("%")&&te(r.slice(0,-1))&&(yield{kind:"named",value:r.slice(0,-1),fraction:null}),r.includes("/")){let[o,l]=r.split("/");D(o)&&D(l)&&(yield{kind:"named",value:o,fraction:`${o}/${l}`})}let t=new Set;for(let o of r.matchAll(/(\d+\/\d+)|(\d+\.?\d+)/g))t.add(o[0].trim());let n=Array.from(t).sort((o,l)=>o.length-l.length);for(let o of n)yield*un(e,o,i)}function Ji(e){return!(e.length===1&&e[0].kind==="list")}function zt(e){return e.value[0]==="["&&e.value[e.value.length-1]==="]"}function aa(e,r){let i=[e],t=r.designSystem,n=t.storage[Wt].get(r.signatureOptions.rem),o=Ft(e);for(let[l,f]of o)if(l.kind==="compound"&&(l.root==="has"||l.root==="not"||l.root==="in")&&l.modifier!==null&&"modifier"in l.variant&&(l.variant.modifier=l.modifier,l.modifier=null),l.kind==="arbitrary"){if(l.relative)continue;let u=pe(l.selector);if(!Ji(u))continue;if(u.length===1&&u[0].kind==="complex"&&(u=u[0].nodes),f===null&&u.length===3&&u[0].kind==="selector"&&u[0].value==="&"&&u[1].kind==="combinator"&&u[1].value===">"&&u[2].kind==="selector"&&u[2].value==="*"){ge(l,t.parseVariant("*"));continue}if(f===null&&u.length===3&&u[0].kind==="selector"&&u[0].value==="&"&&u[1].kind==="combinator"&&u[1].value===" "&&u[2].kind==="selector"&&u[2].value==="*"){ge(l,t.parseVariant("**"));continue}if(f===null&&u.length===1&&u[0].kind==="compound"&&u[0].nodes.length===2&&u[0].nodes[0].kind==="selector"&&u[0].nodes[0].value==="&"&&u[0].nodes[1].kind==="function"&&u[0].nodes[1].value===":has"&&u[0].nodes[1].nodes.length===1&&u[0].nodes[1].nodes[0].kind==="selector"){ge(l,t.parseVariant(`has-[${se(u[0].nodes[1].nodes,!0)}]`));continue}if(f===null&&u.length===3&&u[0].kind==="selector"&&u[1].kind==="combinator"&&u[1].value===" "&&u[2].kind==="selector"&&u[2].value==="&"){u.pop(),u.pop(),ge(l,t.parseVariant(`in-[${se(u,!0)}]`));continue}if(f===null&&u[0].kind==="selector"&&(u[0].value==="@media"||u[0].value==="@supports")){let p=n.get(t.printVariant(l)),h=Y(se(u,!0)),k=!1;if(I(h,w=>{if(w.kind==="word"&&w.value==="not")return k=!0,V.Replace([])}),h=Y(B(h)),I(h,w=>{w.kind==="separator"&&w.value!==" "&&w.value.trim()===""&&(w.value=" ")}),k){let w=t.parseVariant(`not-[${B(h)}]`);if(w===null)continue;let b=n.get(t.printVariant(w));if(p===b){ge(l,w);continue}}}let c=null;f===null&&u.length===3&&u[0].kind==="selector"&&u[0].value==="&"&&u[1].kind==="combinator"&&u[1].value===">"&&u[2].kind==="selector"&&(u[2].value[0]===":"||zt(u[2]))&&(u=[u[2]],c=t.parseVariant("*")),f===null&&u.length===3&&u[0].kind==="selector"&&u[0].value==="&"&&u[1].kind==="combinator"&&u[1].value===" "&&u[2].kind==="selector"&&(u[2].value[0]===":"||zt(u[2]))&&(u=[u[2]],c=t.parseVariant("**"));let d=u;if(I(d,{enter(p){if(p.kind==="selector"&&p.value==="&")return V.Replace([]);if(p.kind==="function")return V.Skip},exit(p){if(p.kind==="compound"&&p.nodes.length===1)return V.ReplaceSkip(p.nodes)}}),d.length!==1)continue;let m=d[0];if(m.kind==="function"&&m.value===":is"){if(!Ji(m.nodes)||m.nodes.length!==1||m.nodes[0].kind==="selector"&&!zt(m.nodes[0]))continue;m=m.nodes[0]}if(m.kind==="function"&&m.value[0]===":"||m.kind==="selector"&&m.value[0]===":"){let p=m,h=!1;if(p.kind==="function"&&p.value===":not"){if(h=!0,p.nodes.length!==1||p.nodes[0].kind!=="selector"&&p.nodes[0].kind!=="function"||p.nodes[0].value[0]!==":")continue;p=p.nodes[0]}let k=(b=>{if(b===":nth-child"&&p.kind==="function"&&p.nodes.length===1&&p.nodes[0].kind==="value"&&p.nodes[0].value==="odd")return h?(h=!1,"even"):"odd";if(b===":nth-child"&&p.kind==="function"&&p.nodes.length===1&&p.nodes[0].kind==="value"&&p.nodes[0].value==="even")return h?(h=!1,"odd"):"even";for(let[A,C]of[[":nth-child","nth"],[":nth-last-child","nth-last"],[":nth-of-type","nth-of-type"],[":nth-last-of-type","nth-of-last-type"]])if(b===A&&p.kind==="function"&&p.nodes.length===1)return p.nodes.length===1&&p.nodes[0].kind==="value"&&D(p.nodes[0].value)?`${C}-${p.nodes[0].value}`:`${C}-[${se(p.nodes,!0)}]`;if(h){let A=n.get(t.printVariant(l)),C=n.get(`not-[${b}]`);if(A===C)return`[&${b}]`}return null})(p.value);if(k===null){if(c)return ge(l,{kind:"arbitrary",selector:vt(m)?`&${m.value}`:m.value,relative:!1}),[c,l];continue}h&&(k=`not-${k}`);let w=t.parseVariant(k);if(w===null)continue;ge(l,w)}else if(m.kind==="selector"&&zt(m)){let p=Ze(m.value);if(p===null)continue;if(p.attribute.startsWith("data-")){let h=p.attribute.slice(5);ge(l,{kind:"functional",root:"data",modifier:null,value:p.value===null?{kind:"named",value:h}:{kind:"arbitrary",value:`${h}${p.operator}${p.quote??""}${p.value}${p.quote??""}${p.sensitivity?` ${p.sensitivity}`:""}`}})}else if(p.attribute.startsWith("aria-")){let h=p.attribute.slice(5);ge(l,{kind:"functional",root:"aria",modifier:null,value:p.value===null?{kind:"arbitrary",value:h}:p.operator==="="&&p.value==="true"&&p.sensitivity===null?{kind:"named",value:h}:{kind:"arbitrary",value:`${p.attribute}${p.operator}${p.quote??""}${p.value}${p.quote??""}${p.sensitivity?` ${p.sensitivity}`:""}`}})}else ge(l,{kind:"arbitrary",selector:m.value,relative:!1})}if(c)return[c,l]}return i}function sa(e,r){if(e.kind!=="functional"||e.value?.kind!=="arbitrary")return e;let t=r.designSystem.storage[pt].get(r.signatureOptions),n=Y(e.value.value);if(n.length===1&&n[0].kind==="function"&&n[0].value==="calc"){let[o,l]=ft(n,null,!1);if(o){let f=qe(e);f.value.value=B(l),t(e,f)&&(e=f,n=l)}}if(e.root[0]==="-"){if(n.length===1&&n[0].kind==="function"&&n[0].value==="var")return e;let o=Y(`calc(${e.value.value} * -1)`),[l,f]=ft(o,null,!1);if(l){let u=qe(e);u.root=u.root.slice(1),u.value.value=B(f),t(e,u)&&(e=u,n=f)}}if(n.length===1&&n[0].kind==="function"&&n[0].value==="calc"){let o=n[0].nodes;if(o.length===5&&o[1].kind==="separator"&&o[1].value===" "&&o[2].kind==="word"&&o[2].value==="*"&&o[3].kind==="separator"&&o[3].value===" "){let l=o[4].kind==="word"&&o[4].value==="-1"?o[0]:o[0].kind==="word"&&o[0].value==="-1"?o[4]:null;if(l){let f=qe(e);f.root=`-${e.root}`,f.value.value=B([l]),t(e,f)&&(e=f)}}}return e}function ua(e,r){if(e.kind!=="functional"&&e.kind!=="arbitrary"||e.modifier===null)return e;let i=r.designSystem,t=i.storage[we].get(r.signatureOptions),n=t.get(i.printCandidate(e)),o=e.modifier;if(n===t.get(i.printCandidate({...e,modifier:null})))return e.modifier=null,e;{let l={kind:"named",value:o.value.endsWith("%")?o.value.includes(".")?`${Number(o.value.slice(0,-1))}`:o.value.slice(0,-1):o.value,fraction:null};if(n===t.get(i.printCandidate({...e,modifier:l})))return e.modifier=l,e}{let l={kind:"named",value:`${parseFloat(o.value)*100}`,fraction:null};if(n===t.get(i.printCandidate({...e,modifier:l})))return e.modifier=l,e}return e}var we=Symbol();function ca(e){return new K(r=>new K(i=>{try{return ce(fn(e,i,r))}catch{return Symbol()}}))}var cn=Symbol();function fa(e){return new K(r=>new K(i=>{try{let t=new K(()=>new Set),n=fn(e,i,r,t),o=[];return I(n,l=>{l.kind==="declaration"&&o.push(Array.from(t.get(l)).sort().join(" "))}),o}catch{return null}}))}function fn(e,r,i,t){r=e.theme.prefix&&!r.startsWith(e.theme.prefix)?`${e.theme.prefix}:${r}`:r;let n=[Q(".x",[H("@apply",r)])];return wa(e,()=>{for(let o of e.parseCandidate(r))e.compileAstNodes(o,1);Ee(n,e)}),pn(e,n,i,t),n}var Xi=/#(?:[a-f0-9]{8}|[a-f0-9]{6}|[a-f0-9]{4}|[a-f0-9]{3})/gi,pa={"--tw-duration":"transition-duration","--tw-ease":"transition-timing-function","--tw-leading":"line-height","--tw-tracking":"letter-spacing"};function pn(e,r,i,t){let{rem:n}=i;return I(r,{enter(o,l){if(o.kind==="declaration"){if(o.value===void 0||o.property==="--tw-sort")return V.Replace([]);if(o.property.startsWith("--tw-")){let p=pa[o.property]??o.property.slice(5);if(l.siblings.some(h=>h.kind==="declaration"&&h.property===p&&o.value===h.value&&o.important===h.important))return V.Replace([])}if(i.features&1){let p=Gi(o,i.features);if(p)return V.Replace(p)}o.value.includes("var(")&&(o.value=ma(o.value,e,t?.get(o)));let f=Y(o.value),[u,c]=ft(f,n),[d,m]=Mi(c);(u||d)&&(o.value=B(m)),o.value=$e(o.value)}else{if(o.kind==="context"||o.kind==="at-root")return V.Replace(o.nodes);if(o.kind==="comment")return V.Replace([]);if(o.kind==="at-rule"&&o.name==="@property")return V.Replace([])}},exit(o){if(o.kind==="rule"||o.kind==="at-rule"){if(o.nodes.length>1){let l=new Set;for(let f=o.nodes.length-1;f>=0;f--){let u=o.nodes[f];u.kind==="declaration"&&u.value!==void 0&&(l.has(u.property)&&o.nodes.splice(f,1),l.add(u.property))}}o.nodes.sort((l,f)=>l.kind!=="declaration"||f.kind!=="declaration"?0:l.property.localeCompare(f.property))}else if(o.kind==="declaration"&&o.value){if(o.property[0]==="-"&&o.property[1]==="-")return;Xi.lastIndex=0,o.value=o.value.replace(Xi,l=>l.toLowerCase())}}}),r}var da=["initial","inherit","revert","revert-layer","revert-rule","unset"];function ma(e,r,i){let t=!1,n=Y(e),o=new Set;return I(n,l=>{if(l.kind!=="function"||l.value!=="var"||l.nodes.length!==1&&l.nodes.length<3)return;let f=l.nodes[0].value;r.theme.prefix&&f.startsWith(`--${r.theme.prefix}-`)&&(f=f.slice(`--${r.theme.prefix}-`.length));let u=r.resolveThemeValue(f);if(!o.has(f)&&(o.add(f),u!==void 0&&!da.includes(u.toLowerCase())&&(l.nodes.length===1&&(t=!0,l.nodes.push(...Y(`,${u}`))),l.nodes.length>=3))){let c=B(l.nodes),d=`${l.nodes[0].value},${u}`;if(c===d)return t=!0,i?.add(f),V.Replace(Y(u))}}),t?B(n):e}var Nr=Symbol();function ga(){return new K(e=>new K(r=>new K(i=>new Set)))}var jt=Symbol();function ha(e){return new K(r=>new K(i=>{let t=new K(o=>new Set);e.theme.prefix&&!i.startsWith(e.theme.prefix)&&(i=`${e.theme.prefix}:${i}`);let n=e.parseCandidate(i);if(n.length===0)return t;try{let o=e.compileAstNodes(n[0]).map(l=>le(l.node));I(pn(e,o,r),l=>{l.kind==="declaration"&&(t.get(l.property).add(l.value),e.storage[Nr].get(r).get(l.property).get(l.value).add(i))})}catch{}return t}))}var Er=Symbol();function va(e){return new K(r=>{let i=e.storage[we].get(r),t=new K(()=>[]);for(let[n,o]of e.getClassList()){let l=i.get(n);if(typeof l=="string"){if(n[0]==="-"&&n.endsWith("-0")){let f=i.get(n.slice(1));if(typeof f=="string"&&l===f)continue}t.get(l).push(n),e.storage[jt].get(r).get(n);for(let f of o.modifiers){if(te(f))continue;let u=`${n}/${f}`,c=i.get(u);typeof c=="string"&&(t.get(c).push(u),e.storage[jt].get(r).get(u))}}}return t})}var Wt=Symbol();function ka(e){return new K(r=>new K(i=>{try{i=e.theme.prefix&&!i.startsWith(e.theme.prefix)?`${e.theme.prefix}:${i}`:i;let t=[Q(".x",[H("@apply",`${i}:flex`)])];return Ee(t,e),I(t,o=>{if(o.kind==="at-rule")o.params=ct(o.params,r),o.params.includes(" ")&&(o.params=o.params.replaceAll(" ",""));else if(o.kind==="rule"){let l=pe(o.selector),f=!1;I(l,u=>{if(u.kind==="list"||u.kind==="combinator")f=!0;else if(u.kind==="function"&&u.value===":is"){if(u.nodes.length===1)return f=!0,V.Replace(u.nodes);if(u.nodes.length===2&&u.nodes[0].kind==="selector"&&u.nodes[0].value==="*"&&u.nodes[1].kind==="selector"&&u.nodes[1].value[0]===":")return f=!0,V.Replace(u.nodes[1])}else u.kind==="function"&&u.value[0]===":"&&u.nodes[0]?.kind==="selector"&&u.nodes[0]?.value[0]===":"&&(f=!0,u.nodes.unshift({kind:"selector",value:"*"}))}),f&&(o.selector=se(l,!0))}}),ce(t)}catch{return Symbol()}}))}var dn=Symbol();function ba(e){return new K(r=>{let i=e.storage[Wt].get(r),t=new K(()=>[]);for(let[n,o]of e.variants.entries())if(o.kind==="static"){let l=i.get(n);if(typeof l!="string")continue;t.get(l).push(n)}else if(o.kind==="functional")for(let l of e.variants.getCompletions(n)){let f=n==="@"?`@${l}`:`${n}-${l}`,u=i.get(f);typeof u=="string"&&t.get(u).push(f)}return t})}function wa(e,r){let i=e.theme.values.get,t=new Set;e.theme.values.get=n=>{let o=i.call(e.theme.values,n);return o===void 0||o.options&1&&(t.add(o),o.options&=-2),o};try{return r()}finally{e.theme.values.get=i;for(let n of t)n.options|=1}}function*ya(e){let r=e.length,i=1n<=2;t--){let n=(1n<>BigInt(u)&1n&&o.push(e[u]);yield o;let l=n&-n,f=n+l;n=((f^n)>>2n)/l|f}}}function en(e,r){if(typeof e.intersection=="function")return e.intersection(r);if(e.size===0||r.size===0)return new Set;let i=new Set;for(let t of e)r.has(t)&&i.add(t);return i}var Aa=/^\d+\/\d+$/;function mn(e){let r=new K(n=>({name:n,utility:n,fraction:!1,modifiers:[]}));for(let n of e.utilities.keys("static")){if(e.utilities.getCompletions(n).length===0)continue;let l=r.get(n);l.fraction=!1,l.modifiers=[]}for(let n of e.utilities.keys("functional")){let o=e.utilities.getCompletions(n);for(let l of o)for(let f of l.values){let u=f!==null&&Aa.test(f),c=f===null?n:`${n}-${f}`,d=r.get(c);if(d.utility=n,d.fraction||=u,d.modifiers.push(...l.modifiers),l.supportsNegative){let m=r.get(`-${c}`);m.utility=`-${n}`,m.fraction||=u,m.modifiers.push(...l.modifiers)}d.modifiers=Array.from(new Set(d.modifiers))}}if(r.size===0)return[];let i=Array.from(r.values());return i.sort((n,o)=>Lt(n.name,o.name)),Ca(i)}function Ca(e){let r=[],i=null,t=new Map,n=new K(()=>[]);for(let l of e){let{utility:f,fraction:u}=l;i||(i={utility:f,items:[]},t.set(f,i)),f!==i.utility&&(r.push(i),i={utility:f,items:[]},t.set(f,i)),u?n.get(f).push(l):i.items.push(l)}i&&r[r.length-1]!==i&&r.push(i);for(let[l,f]of n){let u=t.get(l);u&&u.items.push(...f)}let o=[];for(let l of r)for(let f of l.items)o.push([f.name,{modifiers:f.modifiers}]);return o}function gn(e){let r=[];for(let[t,n]of e.variants.entries()){let f=function({value:u,modifier:c}={}){let d=t;u&&(d+=o?`-${u}`:u),c&&(d+=`/${c}`);let m=e.parseVariant(d);if(!m)return[];let p=Q(".__placeholder__",[]);if(Xe(p,m,e.variants)===null)return[];let h=[];return I(p.nodes,{exit(k,w){if(k.kind!=="rule"&&k.kind!=="at-rule"||k.nodes.length>0)return;let b=w.path();b.push(k),b.sort((y,E)=>{let O=y.kind==="at-rule",P=E.kind==="at-rule";return O&&!P?-1:!O&&P?1:0});let A=b.flatMap(y=>y.kind==="rule"?y.selector==="&"?[]:[y.selector]:y.kind==="at-rule"?[`${y.name} ${y.params}`]:[]),C="";for(let y=A.length-1;y>=0;y--)C=C===""?A[y]:`${A[y]} { ${C} }`;h.push(C)}}),h};var i=f;if(n.kind==="arbitrary")continue;let o=t!=="@",l=e.variants.getCompletions(t);switch(n.kind){case"static":{r.push({name:t,values:l,isArbitrary:!1,hasDash:o,selectors:f});break}case"functional":{r.push({name:t,values:l,isArbitrary:!0,hasDash:o,selectors:f});break}case"compound":{r.push({name:t,values:l,isArbitrary:!0,hasDash:o,selectors:f});break}}}return r}function hn(e,r){let{astNodes:i,nodeSorting:t}=Re(Array.from(r),e),n=new Map(r.map(l=>[l,null])),o=0n;for(let l of i){let f=t.get(l)?.candidate;f&&n.set(f,n.get(f)??o++)}return r.map(l=>[l,n.get(l)??null])}var Bt=/^@?[a-z0-9][a-zA-Z0-9_-]*(?{f.kind==="rule"?n.push(f.selector):f.kind==="at-rule"&&f.name==="@variant"?o=!0:f.kind==="at-rule"&&f.name!=="@slot"&&(f.name==="@scope"&&(l=!0),n.push(`${f.name} ${f.params}`))}),this.static(r,f=>{let u=i.map(le);o&&mt(u,t),l?(dt(u,[ee({source:"user"},f.nodes)]),f.nodes=[ee({source:"variant"},u)]):(dt(u,f.nodes),f.nodes=u)},{compounds:ze(n)})}functional(r,i,{compounds:t,order:n}={}){this.set(r,{kind:"functional",applyFn:i,compoundsWith:0,compounds:t??2,order:n})}compound(r,i,t,{compounds:n,order:o}={}){this.set(r,{kind:"compound",applyFn:t,compoundsWith:i,compounds:n??2,order:o})}group(r,i){this.groupOrder=this.nextOrder(),i&&this.compareFns.set(this.groupOrder,i),r(),this.groupOrder=null}has(r){return this.variants.has(r)}get(r){return this.variants.get(r)}kind(r){return this.variants.get(r)?.kind}compoundsWith(r,i){let t=this.variants.get(r),n=typeof i=="string"?this.variants.get(i):i.kind==="arbitrary"?{compounds:ze([i.selector])}:this.variants.get(i.root);return!(!t||!n||t.kind!=="compound"||n.compounds===0||t.compoundsWith===0||(t.compoundsWith&n.compounds)===0)}suggest(r,i){this.completions.set(r,i)}getCompletions(r){return this.completions.get(r)?.()??[]}compare(r,i){if(r===i)return 0;if(r===null)return-1;if(i===null)return 1;if(r.kind==="arbitrary"&&i.kind==="arbitrary")return r.selector{p.nodes=d.map(h=>J(h,p.nodes))},{compounds:m})}i("*",[":is(& > *)"],{compounds:0}),i("**",[":is(& *)"],{compounds:0});function t(c,d){return d.map(m=>{if(c==="@container"){let p=Y(m.trim());return p.length>=1&&p[0].kind==="function"?`not ${m}`:p.length>=3&&p[0].kind==="word"&&p[0].value==="not"&&p[2].kind==="function"?(p.splice(0,2),B(p)):p.length>=5&&p[0].kind==="word"&&p[2].kind==="word"&&p[2].value==="not"&&p[4].kind==="function"?(p.splice(2,2),B(p)):p.length>=3&&p[0].kind==="word"&&p[0].value!=="not"&&p[2].kind==="function"?(p.splice(1,0,{kind:"separator",value:" "},{kind:"word",value:"not"}),B(p)):`not ${m}`}else{m=m.trim();let p=j(m," ");return p[0]==="not"?p.slice(1).join(" "):`not ${m}`}})}let n=["@media","@supports","@container"];function o(c){for(let d of n){if(d!==c.name)continue;let m=j(c.params,",");return m.length>1?null:(m=t(c.name,m),H(c.name,m.join(", ")))}return null}function l(c){return c.includes("::")?null:`&:not(${j(c,",").map(m=>(m=m.replaceAll("&","*"),m)).join(", ")})`}r.compound("not",3,(c,d)=>{if(d.variant.kind==="arbitrary"&&d.variant.relative||d.modifier)return null;let m=!1;if(I([c],(p,h)=>{if(p.kind!=="rule"&&p.kind!=="at-rule")return V.Continue;if(p.nodes.length>0)return V.Continue;let k=[],w=[],b=h.path();b.push(p);for(let C of b)C.kind==="at-rule"?k.push(C):C.kind==="rule"&&w.push(C);if(k.length>1)return V.Stop;if(w.length>1)return V.Stop;let A=[];for(let C of w){let y=l(C.selector);if(!y)return m=!1,V.Stop;A.push(Q(y,[]))}for(let C of k){let y=o(C);if(!y)return m=!1,V.Stop;A.push(y)}return Object.assign(c,Q("&",A)),m=!0,V.Skip}),c.kind==="rule"&&c.selector==="&"&&c.nodes.length===1&&Object.assign(c,c.nodes[0]),!m)return null}),r.suggest("not",()=>Array.from(r.keys()).filter(c=>r.compoundsWith("not",c))),r.compound("group",2,(c,d)=>{if(d.variant.kind==="arbitrary"&&d.variant.relative)return null;let m=d.modifier?`:where(.${e.prefix?`${e.prefix}\\:`:""}group\\/${d.modifier.value})`:`:where(.${e.prefix?`${e.prefix}\\:`:""}group)`,p=!1;if(I([c],(h,k)=>{if(h.kind!=="rule")return V.Continue;for(let b of k.path())if(b.kind==="rule")return p=!1,V.Stop;let w=h.selector.replaceAll("&",m);j(w,",").length>1&&(w=`:is(${w})`),h.selector=`:is(${w} &)`,p=!0}),!p)return null}),r.suggest("group",()=>Array.from(r.keys()).filter(c=>r.compoundsWith("group",c))),r.compound("peer",2,(c,d)=>{if(d.variant.kind==="arbitrary"&&d.variant.relative)return null;let m=d.modifier?`:where(.${e.prefix?`${e.prefix}\\:`:""}peer\\/${d.modifier.value})`:`:where(.${e.prefix?`${e.prefix}\\:`:""}peer)`,p=!1;if(I([c],(h,k)=>{if(h.kind!=="rule")return V.Continue;for(let b of k.path())if(b.kind==="rule")return p=!1,V.Stop;let w=h.selector.replaceAll("&",m);j(w,",").length>1&&(w=`:is(${w})`),h.selector=`:is(${w} ~ &)`,p=!0}),!p)return null}),r.suggest("peer",()=>Array.from(r.keys()).filter(c=>r.compoundsWith("peer",c))),i("first-letter",["&::first-letter"]),i("first-line",["&::first-line"]),i("marker",["& *::marker","&::marker","& *::-webkit-details-marker","&::-webkit-details-marker"]),i("selection",["& *::selection","&::selection"]),i("file",["&::file-selector-button"]),i("placeholder",["&::placeholder"]),i("backdrop",["&::backdrop"]),i("details-content",["&::details-content"]);{let c=function(){return G([H("@property","--tw-content",[s("syntax",'"*"'),s("initial-value",'""'),s("inherits","false")])])};var f=c;r.static("before",d=>{d.nodes=[Q("&::before",[c(),s("content","var(--tw-content)"),...d.nodes])]},{compounds:0}),r.static("after",d=>{d.nodes=[Q("&::after",[c(),s("content","var(--tw-content)"),...d.nodes])]},{compounds:0})}i("first",["&:first-child"]),i("last",["&:last-child"]),i("only",["&:only-child"]),i("odd",["&:nth-child(odd)"]),i("even",["&:nth-child(even)"]),i("first-of-type",["&:first-of-type"]),i("last-of-type",["&:last-of-type"]),i("only-of-type",["&:only-of-type"]),i("visited",["&:visited"]),i("target",["&:target"]),i("open",["&:is([open], :popover-open, :open)"]),i("default",["&:default"]),i("checked",["&:checked"]),i("indeterminate",["&:indeterminate"]),i("placeholder-shown",["&:placeholder-shown"]),i("autofill",["&:autofill"]),i("optional",["&:optional"]),i("required",["&:required"]),i("valid",["&:valid"]),i("invalid",["&:invalid"]),i("user-valid",["&:user-valid"]),i("user-invalid",["&:user-invalid"]),i("in-range",["&:in-range"]),i("out-of-range",["&:out-of-range"]),i("read-only",["&:read-only"]),i("empty",["&:empty"]),i("focus-within",["&:focus-within"]),r.static("hover",c=>{c.nodes=[Q("&:hover",[H("@media","(hover: hover)",c.nodes)])]}),i("focus",["&:focus"]),i("focus-visible",["&:focus-visible"]),i("active",["&:active"]),i("enabled",["&:enabled"]),i("disabled",["&:disabled"]),i("inert",["&:is([inert], [inert] *)"]),r.compound("in",2,(c,d)=>{if(d.modifier)return null;let m=!1;if(I([c],(p,h)=>{if(p.kind!=="rule")return V.Continue;for(let k of h.path())if(k.kind==="rule")return m=!1,V.Stop;p.selector=`:where(${p.selector.replaceAll("&","*")}) &`,m=!0}),!m)return null}),r.suggest("in",()=>Array.from(r.keys()).filter(c=>r.compoundsWith("in",c))),r.compound("has",2,(c,d)=>{if(d.modifier)return null;let m=!1;if(I([c],(p,h)=>{if(p.kind!=="rule")return V.Continue;for(let k of h.path())if(k.kind==="rule")return m=!1,V.Stop;p.selector=`&:has(${p.selector.replaceAll("&","*")})`,m=!0}),!m)return null}),r.suggest("has",()=>Array.from(r.keys()).filter(c=>r.compoundsWith("has",c))),r.functional("aria",(c,d)=>{if(!d.value||d.modifier)return null;if(d.value.kind==="arbitrary"){let m=`[aria-${vn(d.value.value)}]`;if(Ze(m)===null)return null;c.nodes=[Q(`&${m}`,c.nodes)]}else{let m=`[aria-${d.value.value}="true"]`;if(Ze(m)===null)return null;c.nodes=[Q(`&${m}`,c.nodes)]}}),r.suggest("aria",()=>["busy","checked","disabled","expanded","hidden","pressed","readonly","required","selected"]),r.functional("data",(c,d)=>{if(!d.value||d.modifier)return null;let m=`[data-${vn(d.value.value)}]`;if(Ze(m)===null)return null;c.nodes=[Q(`&${m}`,c.nodes)]}),r.functional("nth",(c,d)=>{if(!d.value||d.modifier||d.value.kind==="named"&&!D(d.value.value))return null;c.nodes=[Q(`&:nth-child(${d.value.value})`,c.nodes)]}),r.functional("nth-last",(c,d)=>{if(!d.value||d.modifier||d.value.kind==="named"&&!D(d.value.value))return null;c.nodes=[Q(`&:nth-last-child(${d.value.value})`,c.nodes)]}),r.functional("nth-of-type",(c,d)=>{if(!d.value||d.modifier||d.value.kind==="named"&&!D(d.value.value))return null;c.nodes=[Q(`&:nth-of-type(${d.value.value})`,c.nodes)]}),r.functional("nth-last-of-type",(c,d)=>{if(!d.value||d.modifier||d.value.kind==="named"&&!D(d.value.value))return null;c.nodes=[Q(`&:nth-last-of-type(${d.value.value})`,c.nodes)]}),r.functional("supports",(c,d)=>{if(!d.value||d.modifier)return null;let m=d.value.value;if(m===null)return null;if(/^[\w-]*\s*\(/.test(m)){let p=!1,h=Y(m);I(h,w=>{if(w.kind==="function"){if(w.value==="selector")return V.Skip;(w.value==="and"||w.value==="or"||w.value==="not")&&(p=!0,w.value=` ${w.value} `)}});let k=p?B(h):m;c.nodes=[H("@supports",k,c.nodes)];return}m.includes(":")||(m=`${m}: var(--tw)`),(m[0]!=="("||m[m.length-1]!==")")&&(m=`(${m})`),c.nodes=[H("@supports",m,c.nodes)]},{compounds:1}),i("motion-safe",["@media (prefers-reduced-motion: no-preference)"]),i("motion-reduce",["@media (prefers-reduced-motion: reduce)"]),i("contrast-more",["@media (prefers-contrast: more)"]),i("contrast-less",["@media (prefers-contrast: less)"]);{let c=function(d,m,p,h){if(d===m)return 0;let k=h.get(d);if(k===null)return p==="asc"?-1:1;let w=h.get(m);return w===null?p==="asc"?1:-1:De(k,w,p)};var u=c;{let d=e.namespace("--breakpoint"),m=new K(p=>{switch(p.kind){case"static":return e.resolveValue(p.root,["--breakpoint"])??null;case"functional":{if(!p.value||p.modifier)return null;let h=null;return p.value.kind==="arbitrary"?h=p.value.value:p.value.kind==="named"&&(h=e.resolveValue(p.value.value,["--breakpoint"])),!h||h.includes("var(")?null:h}case"arbitrary":case"compound":return null}});r.group(()=>{r.functional("max",(p,h)=>{if(h.modifier)return null;let k=m.get(h);if(k===null)return null;p.nodes=[H("@media",`(width < ${k})`,p.nodes)]},{compounds:1})},(p,h)=>c(p,h,"desc",m)),r.suggest("max",()=>Array.from(d.keys()).filter(p=>p!==null)),r.group(()=>{for(let[p,h]of e.namespace("--breakpoint"))p!==null&&r.static(p,k=>{k.nodes=[H("@media",`(width >= ${h})`,k.nodes)]},{compounds:1});r.functional("min",(p,h)=>{if(h.modifier)return null;let k=m.get(h);if(k===null)return null;p.nodes=[H("@media",`(width >= ${k})`,p.nodes)]},{compounds:1})},(p,h)=>c(p,h,"asc",m)),r.suggest("min",()=>Array.from(d.keys()).filter(p=>p!==null))}{let d=e.namespace("--container"),m=new K(p=>{switch(p.kind){case"functional":{if(p.value===null)return null;let h=null;return p.value.kind==="arbitrary"?h=p.value.value:p.value.kind==="named"&&(h=e.resolveValue(p.value.value,["--container"])),!h||h.includes("var(")?null:h}case"static":case"arbitrary":case"compound":return null}});r.group(()=>{r.functional("@max",(p,h)=>{let k=m.get(h);if(k===null)return null;p.nodes=[H("@container",h.modifier?`${h.modifier.value} (width < ${k})`:`(width < ${k})`,p.nodes)]},{compounds:1})},(p,h)=>c(p,h,"desc",m)),r.suggest("@max",()=>Array.from(d.keys()).filter(p=>p!==null)),r.group(()=>{r.functional("@",(p,h)=>{let k=m.get(h);if(k===null)return null;p.nodes=[H("@container",h.modifier?`${h.modifier.value} (width >= ${k})`:`(width >= ${k})`,p.nodes)]},{compounds:1}),r.functional("@min",(p,h)=>{let k=m.get(h);if(k===null)return null;p.nodes=[H("@container",h.modifier?`${h.modifier.value} (width >= ${k})`:`(width >= ${k})`,p.nodes)]},{compounds:1})},(p,h)=>c(p,h,"asc",m)),r.suggest("@min",()=>Array.from(d.keys()).filter(p=>p!==null)),r.suggest("@",()=>Array.from(d.keys()).filter(p=>p!==null))}}return i("portrait",["@media (orientation: portrait)"]),i("landscape",["@media (orientation: landscape)"]),i("ltr",['&:where(:dir(ltr), [dir="ltr"], [dir="ltr"] *)']),i("rtl",['&:where(:dir(rtl), [dir="rtl"], [dir="rtl"] *)']),i("dark",["@media (prefers-color-scheme: dark)"]),i("starting",["@starting-style"]),i("print",["@media print"]),i("forced-colors",["@media (forced-colors: active)"]),i("inverted-colors",["@media (inverted-colors: inverted)"]),i("pointer-none",["@media (pointer: none)"]),i("pointer-coarse",["@media (pointer: coarse)"]),i("pointer-fine",["@media (pointer: fine)"]),i("any-pointer-none",["@media (any-pointer: none)"]),i("any-pointer-coarse",["@media (any-pointer: coarse)"]),i("any-pointer-fine",["@media (any-pointer: fine)"]),i("noscript",["@media (scripting: none)"]),r}function vn(e){if(e.includes("=")){let[r,...i]=j(e,"="),t=i.join("=").trim();if(t[0]==="'"||t[0]==='"')return e;if(t.length>1){let n=t[t.length-1];if(t[t.length-2]===" "&&(n==="i"||n==="I"||n==="s"||n==="S"))return`${r}="${t.slice(0,-2)}" ${n}`}return`${r}="${t}"`}return e}function dt(e,r){I(e,i=>{if(i.kind==="at-rule"&&i.name==="@slot")return V.ReplaceSkip(r);if(i.kind==="at-rule"&&(i.name==="@keyframes"||i.name==="@property"))return Object.assign(i,G([H(i.name,i.params,i.nodes)])),V.Skip})}function mt(e,r){let i=0;return I(e,t=>{if(t.kind!=="at-rule"||t.name!=="@variant")return;let n=[],o=j(t.params,",");for(let[l,f]of o.entries()){let u=Q("&",l===o.length-1?t.nodes:t.nodes.map(le)),c=j(f,":");for(let d=c.length-1;d>=0;--d){let m=c[d].trim();if(!m)throw new Error("Cannot use `@variant` with empty variant");let p=r.parseVariant(m);if(p===null)throw new Error(`Cannot use \`@variant\` with unknown variant: ${m}`);if(Xe(u,p,r.variants)===null)throw new Error(`Cannot use \`@variant\` with variant: ${m}`)}u.selector==="&"?n.push(...u.nodes):n.push(u)}return i|=32,V.Replace(n)}),i}function bn(e,r){let i=Ii(e),t=kn(e),n=new K(h=>Ai(h,p)),o=null,l=-1,f=new K(h=>Array.from(xi(h,p))),u=new K(h=>new K(k=>{let w=wn(k,p,h);try{let b=w.map(A=>A.node);He(b,p),mt(b,p)}catch{return[]}return w})),c=new K(h=>{for(let k of $t(h))e.markUsedVariable(k)});function d(h){let k=[];for(let w of h){let b=!0,{astNodes:A}=Re([w],p,{onInvalidCandidate(){b=!1}});r&&I(A,C=>(C.src??=r,V.Continue)),A=Ie(A,p,0),k.push(b?A:[])}return k}function m(h){return d(h).map(k=>k.length>0?ce(k):null)}let p={theme:e,utilities:i,variants:t,invalidCandidates:new Set,important:!1,candidatesToCss:m,candidatesToAst:d,getClassOrder(h){return hn(this,h)},getClassList(){return mn(this)},getVariants(){return gn(this)},parseCandidate(h){return f.get(h)},parseVariant(h){return n.get(h)},compileAstNodes(h,k=1){return u.get(k).get(h)},printCandidate(h){return Si(p,h)},printVariant(h){return Ot(h)},getVariantOrder(){if(o!==null&&l===n.size)return o;let h=Array.from(n.values());h.sort((A,C)=>this.variants.compare(A,C));let k=new Map,w,b=0;for(let A of h)A!==null&&(w!==void 0&&this.variants.compare(w,A)!==0&&b++,k.set(A,b),w=A);return o=k,l=n.size,k},resolveThemeValue(h,k=!0){let w=h.lastIndexOf("/"),b=null;w!==-1&&(b=h.slice(w+1).trim(),h=h.slice(0,w).trim());let A=e.resolve(null,[h],k?1:0)??void 0;return b&&A?ie(A,b):A},trackUsedVariables(h){c.get(h)},canonicalizeCandidates(h,k){return Tr(this,h,k)},storage:{}};return p}var Pr=["container-type","pointer-events","visibility","position","inset","inset-inline","inset-block","inset-inline-start","inset-inline-end","inset-block-start","inset-block-end","top","right","bottom","left","isolation","z-index","order","grid-column","grid-column-start","grid-column-end","grid-row","grid-row-start","grid-row-end","float","clear","--tw-container-component","margin","margin-inline","margin-block","margin-inline-start","margin-inline-end","margin-block-start","margin-block-end","margin-top","margin-right","margin-bottom","margin-left","box-sizing","display","field-sizing","aspect-ratio","height","max-height","min-height","width","max-width","min-width","flex","flex-shrink","flex-grow","flex-basis","table-layout","caption-side","border-collapse","border-spacing","transform-origin","translate","--tw-translate-x","--tw-translate-y","--tw-translate-z","scale","--tw-scale-x","--tw-scale-y","--tw-scale-z","rotate","--tw-rotate-x","--tw-rotate-y","--tw-rotate-z","--tw-skew-x","--tw-skew-y","transform","zoom","animation","cursor","touch-action","--tw-pan-x","--tw-pan-y","--tw-pinch-zoom","resize","scroll-snap-type","--tw-scroll-snap-strictness","scroll-snap-align","scroll-snap-stop","scroll-margin","scroll-margin-inline","scroll-margin-block","scroll-margin-inline-start","scroll-margin-inline-end","scroll-margin-block-start","scroll-margin-block-end","scroll-margin-top","scroll-margin-right","scroll-margin-bottom","scroll-margin-left","scroll-padding","scroll-padding-inline","scroll-padding-block","scroll-padding-inline-start","scroll-padding-inline-end","scroll-padding-block-start","scroll-padding-block-end","scroll-padding-top","scroll-padding-right","scroll-padding-bottom","scroll-padding-left","scrollbar-width","scrollbar-color","scrollbar-gutter","list-style-position","list-style-type","list-style-image","appearance","columns","break-before","break-inside","break-after","grid-auto-columns","grid-auto-flow","grid-auto-rows","grid-template-columns","grid-template-rows","flex-direction","flex-wrap","place-content","place-items","align-content","align-items","justify-content","justify-items","gap","column-gap","row-gap","--tw-space-x-reverse","--tw-space-y-reverse","divide-x-width","divide-y-width","--tw-divide-y-reverse","divide-style","divide-color","place-self","align-self","justify-self","overflow","overflow-x","overflow-y","overscroll-behavior","overscroll-behavior-x","overscroll-behavior-y","scroll-behavior","border-radius","border-start-radius","border-end-radius","border-top-radius","border-right-radius","border-bottom-radius","border-left-radius","border-start-start-radius","border-start-end-radius","border-end-end-radius","border-end-start-radius","border-top-left-radius","border-top-right-radius","border-bottom-right-radius","border-bottom-left-radius","border-width","border-inline-width","border-block-width","border-inline-start-width","border-inline-end-width","border-block-start-width","border-block-end-width","border-top-width","border-right-width","border-bottom-width","border-left-width","border-style","border-inline-style","border-block-style","border-inline-start-style","border-inline-end-style","border-block-start-style","border-block-end-style","border-top-style","border-right-style","border-bottom-style","border-left-style","border-color","border-inline-color","border-block-color","border-inline-start-color","border-inline-end-color","border-block-start-color","border-block-end-color","border-top-color","border-right-color","border-bottom-color","border-left-color","background-color","background-image","--tw-gradient-position","--tw-gradient-stops","--tw-gradient-via-stops","--tw-gradient-from","--tw-gradient-from-position","--tw-gradient-via","--tw-gradient-via-position","--tw-gradient-to","--tw-gradient-to-position","mask-image","--tw-mask-top","--tw-mask-top-from-color","--tw-mask-top-from-position","--tw-mask-top-to-color","--tw-mask-top-to-position","--tw-mask-right","--tw-mask-right-from-color","--tw-mask-right-from-position","--tw-mask-right-to-color","--tw-mask-right-to-position","--tw-mask-bottom","--tw-mask-bottom-from-color","--tw-mask-bottom-from-position","--tw-mask-bottom-to-color","--tw-mask-bottom-to-position","--tw-mask-left","--tw-mask-left-from-color","--tw-mask-left-from-position","--tw-mask-left-to-color","--tw-mask-left-to-position","--tw-mask-linear","--tw-mask-linear-position","--tw-mask-linear-from-color","--tw-mask-linear-from-position","--tw-mask-linear-to-color","--tw-mask-linear-to-position","--tw-mask-radial","--tw-mask-radial-shape","--tw-mask-radial-size","--tw-mask-radial-position","--tw-mask-radial-from-color","--tw-mask-radial-from-position","--tw-mask-radial-to-color","--tw-mask-radial-to-position","--tw-mask-conic","--tw-mask-conic-position","--tw-mask-conic-from-color","--tw-mask-conic-from-position","--tw-mask-conic-to-color","--tw-mask-conic-to-position","box-decoration-break","background-size","background-attachment","background-clip","background-position","background-repeat","background-origin","mask-composite","mask-mode","mask-type","mask-size","mask-clip","mask-position","mask-repeat","mask-origin","fill","stroke","stroke-width","object-fit","object-position","padding","padding-inline","padding-block","padding-inline-start","padding-inline-end","padding-block-start","padding-block-end","padding-top","padding-right","padding-bottom","padding-left","text-align","text-indent","vertical-align","font-family","font-feature-settings","font-size","line-height","font-weight","letter-spacing","text-wrap","overflow-wrap","word-break","text-overflow","hyphens","white-space","tab-size","color","text-transform","font-style","font-stretch","font-variant-numeric","text-decoration-line","text-decoration-color","text-decoration-style","text-decoration-thickness","text-underline-offset","-webkit-font-smoothing","placeholder-color","caret-color","accent-color","color-scheme","opacity","background-blend-mode","mix-blend-mode","box-shadow","--tw-shadow","--tw-shadow-color","--tw-ring-shadow","--tw-ring-color","--tw-inset-shadow","--tw-inset-shadow-color","--tw-inset-ring-shadow","--tw-inset-ring-color","--tw-ring-offset-width","--tw-ring-offset-color","outline","outline-width","outline-offset","outline-color","--tw-blur","--tw-brightness","--tw-contrast","--tw-drop-shadow","--tw-grayscale","--tw-hue-rotate","--tw-invert","--tw-saturate","--tw-sepia","filter","--tw-backdrop-blur","--tw-backdrop-brightness","--tw-backdrop-contrast","--tw-backdrop-grayscale","--tw-backdrop-hue-rotate","--tw-backdrop-invert","--tw-backdrop-opacity","--tw-backdrop-saturate","--tw-backdrop-sepia","backdrop-filter","transition-property","transition-behavior","transition-delay","transition-duration","transition-timing-function","will-change","contain","content","forced-color-adjust"];function Re(e,r,{onInvalidCandidate:i,respectImportant:t}={}){let n=new Map,o=[],l=new Map;for(let c of e){if(r.invalidCandidates.has(c)){i?.(c);continue}let d=r.parseCandidate(c);if(d.length===0){i?.(c);continue}l.set(c,d)}let f=0;(t??!0)&&(f|=1);let u=l.size>1?r.getVariantOrder():null;for(let[c,d]of l){let m=!1;for(let p of d){let h=r.compileAstNodes(p,f);if(h.length!==0){m=!0;for(let{node:k,propertySort:w}of h){let b=0n;if(u!==null)for(let A of p.variants)b|=1n<{let m=n.get(c),p=n.get(d);if(m.variants-p.variants!==0n)return Number(m.variants-p.variants);let h=0;for(;h1)return null;for(let u of l.nodes)if(u.kind!=="rule"&&u.kind!=="at-rule"||n(u,r)===null)return null;I(l.nodes,u=>{if((u.kind==="rule"||u.kind==="at-rule")&&u.nodes.length<=0)return u.nodes=e.nodes,V.Skip}),e.nodes=l.nodes;return}if(n(e,r)===null)return null}function yn(e){let r=e.options?.types??[];return r.length>1&&r.includes("any")}function Sa(e,r){if(e.kind==="arbitrary"){let l=e.value;return e.modifier&&(l=ne(l,e.modifier,r.theme)),l===null?[]:[[s(e.property,l)]]}let i=r.utilities.get(e.root)??[],t=[],n=i.filter(l=>!yn(l));for(let l of n){if(l.kind!==e.kind)continue;let f=l.compileFn(e);if(f!==void 0){if(f===null){if(l.options?.types?.length)return t;continue}t.push(f)}}if(t.length>0)return t;let o=i.filter(l=>yn(l));for(let l of o){if(l.kind!==e.kind)continue;let f=l.compileFn(e);if(f!==void 0){if(f===null){if(l.options?.types?.length)return t;continue}t.push(f)}}return t}function xn(e){for(let r of e)r.kind!=="at-root"&&(r.kind==="declaration"?r.important=!0:(r.kind==="rule"||r.kind==="at-rule")&&xn(r.nodes))}function Va(e){let r=new Set,i=0,t=e.slice(),n=!1;for(;t.length>0;){let o=t.shift();if(o.kind==="declaration"){if(o.value===void 0||(i++,n))continue;if(o.property==="--tw-sort"){let f=Pr.indexOf(o.value??"");if(f!==-1){r.add(f),n=!0;continue}}let l=Pr.indexOf(o.property);l!==-1&&r.add(l)}else if(o.kind==="rule"||o.kind==="at-rule")for(let l of o.nodes)t.push(l)}return{order:Array.from(r).sort((o,l)=>o-l),count:i}}function Ee(e,r){let i=0,t=J("&",e),n=new Set,o=new K(()=>new Set),l=new K(()=>new Set);I([t],(m,p)=>{if(m.kind==="at-rule"){if(m.name==="@keyframes")return I(m.nodes,h=>{if(h.kind==="at-rule"&&h.name==="@apply")throw new Error("You cannot use `@apply` inside `@keyframes`.")}),V.Skip;if(m.name==="@utility"){let h=m.params.replace(/-\*$/,"");l.get(h).add(m),I(m.nodes,k=>{if(!(k.kind!=="at-rule"||k.name!=="@apply")){n.add(m);for(let w of An(k,r))o.get(m).add(w)}});return}if(m.name==="@apply"){if(p.parent===null)return;i|=1,n.add(p.parent);for(let h of An(m,r))for(let k of p.path())n.has(k)&&o.get(k).add(h)}}});let f=new Set,u=[],c=new Set;function d(m,p=[]){if(!f.has(m)){if(c.has(m)){let h=p[(p.indexOf(m)+1)%p.length];throw m.kind==="at-rule"&&m.name==="@utility"&&h.kind==="at-rule"&&h.name==="@utility"&&I(m.nodes,k=>{if(k.kind!=="at-rule"||k.name!=="@apply")return;let w=k.params.split(/\s+/g);for(let b of w)for(let A of r.parseCandidate(b))switch(A.kind){case"arbitrary":break;case"static":case"functional":if(h.params.replace(/-\*$/,"")===A.root)throw new Error(`You cannot \`@apply\` the \`${b}\` utility here because it creates a circular dependency.`);break;default:}}),new Error(`Circular dependency detected: + +${ce([m])} +Relies on: + +${ce([h])}`)}c.add(m);for(let h of o.get(m))for(let k of l.get(h))p.push(m),d(k,p),p.pop();f.add(m),c.delete(m),u.push(m)}}for(let m of n)d(m);for(let m of u)"nodes"in m&&I(m.nodes,p=>{if(p.kind!=="at-rule"||p.name!=="@apply")return;let h=p.params.split(/(\s+)/g),k={},w=[],b=[],A=0;for(let[y,E]of h.entries())y%2===0&&(E[0]==="-"&&E[1]==="-"?b.push(E):w.push(E),k[E]=A),A+=E.length;if(b.length){if(w.length===0)return V.Skip;let y=b.join(" ");throw new Error(`You cannot use \`@apply\` with both mixins and utilities. Please move \`@apply ${y}\` into a separate rule.`)}if(p.nodes.length>0&&w.length){let y=w.join(" ");throw new Error(`The rule \`@apply ${y}\` must not have a body.`)}{let y=Object.keys(k),E=Re(y,r,{respectImportant:!1,onInvalidCandidate:R=>{if(r.theme.prefix&&!R.startsWith(r.theme.prefix))throw new Error(`Cannot apply unprefixed utility class \`${R}\`. Did you mean \`${r.theme.prefix}:${R}\`?`);if(r.invalidCandidates.has(R))throw new Error(`Cannot apply utility class \`${R}\` because it has been explicitly disabled: https://tailwindcss.com/docs/detecting-classes-in-source-files#explicitly-excluding-classes`);let W=j(R,":");if(W.length>1){let U=W.pop();if(r.candidatesToCss([U])[0]){let z=r.candidatesToCss(W.map(Z=>`${Z}:[--tw-variant-check:1]`)),F=W.filter((Z,a)=>z[a]===null);if(F.length>0){if(F.length===1)throw new Error(`Cannot apply utility class \`${R}\` because the ${F.map(Z=>`\`${Z}\``)} variant does not exist.`);{let Z=new Intl.ListFormat("en",{style:"long",type:"conjunction"});throw new Error(`Cannot apply utility class \`${R}\` because the ${Z.format(F.map(a=>`\`${a}\``))} variants do not exist.`)}}}}throw r.theme.size===0?new Error(`Cannot apply unknown utility class \`${R}\`. Are you using CSS modules or similar and missing \`@reference\`? https://tailwindcss.com/docs/functions-and-directives#reference-directive`):new Error(`Cannot apply unknown utility class \`${R}\``)}}),O=p.src,P=E.astNodes.map(R=>{let W=E.nodeSorting.get(R)?.candidate,U=W?k[W]:void 0;if(R=le(R),!O||!W||U===void 0)return I([R],F=>{F.src=O}),R;let z=[O[0],O[1],O[2]];return z[1]+=7+U,z[2]=z[1]+W.length,I([R],F=>{F.src=z}),R}),L=[];for(let R of P)if(R.kind==="rule")for(let W of R.nodes)L.push(W);else L.push(R);return V.Replace(L)}});return i}function*An(e,r){for(let i of e.params.split(/\s+/g))for(let t of r.parseCandidate(i))switch(t.kind){case"arbitrary":break;case"static":case"functional":yield t.root;break;default:}}async function Or(e,r,i,t=0,n=!1){let o=0,l=[];return I(e,f=>{if(f.kind==="at-rule"&&(f.name==="@import"||f.name==="@reference")){let u=Ta(Y(f.params));if(u===null)return;f.name==="@reference"&&(u.media="reference"),o|=2;let{uri:c,layer:d,media:m,supports:p}=u;if(c.startsWith("data:")||c.startsWith("http://")||c.startsWith("https://"))return;let h=ee({},[]);return l.push((async()=>{if(t>100)throw new Error(`Exceeded maximum recursion depth while resolving \`${c}\` in \`${r}\`)`);let k=await i(c,r),w=_e(k.content,{from:n?k.path:void 0});await Or(w,k.base,i,t+1,n),h.nodes=$a(f,[ee({base:k.base},w)],d,m,p)})()),V.ReplaceSkip(h)}}),l.length>0&&await Promise.all(l),o}function Ta(e){let r,i=null,t=null,n=null;for(let o=0;o{let c=Ke(n),[d,m]=Na(e.theme,c),p=i(Cn(r()??{},c)??null);if(typeof p=="string"&&(p=p.replace("","1")),typeof d!="object")return typeof m!="object"&&m&4?p??d:d;if(p!==null&&typeof p=="object"&&!Array.isArray(p)){let h=gt({},[p],(k,w)=>w);if(d===null&&Object.hasOwn(p,"__CSS_VALUES__")){let k={};for(let w in p.__CSS_VALUES__)k[w]=p[w],delete h[w];d=k}for(let k in d)k!=="__CSS_VALUES__"&&(p?.__CSS_VALUES__?.[k]&4&&Cn(h,k.split("-"))!==void 0||(h[Ae(k)]=d[k]));return h}if(Array.isArray(d)&&Array.isArray(m)&&Array.isArray(p)){let h=d[0],k=d[1];m[0]&4&&(h=p[0]??h);for(let w of Object.keys(k))m[1][w]&4&&(k[w]=p[1][w]??k[w]);return[h,k]}return c.length>1&&d!==null&&typeof d=="object"&&!Array.isArray(d)&&"DEFAULT"in d?d.DEFAULT:d??p})();return f&&typeof u=="string"&&(u=ie(u,f)),u??o}}function Na(e,r){if(r.length===1&&r[0].startsWith("--"))return[e.get([r[0]]),e.getOptions(r[0])];let i=Je(r),t=new Map,n=new K(()=>new Map),o=e.namespace(`--${i}`);if(o.size===0)return[null,0];let l=new Map;for(let[d,m]of o){if(!d||!d.includes("--")){t.set(d,m),l.set(d,e.getOptions(d?`--${i}-${d}`:`--${i}`));continue}let p=d.indexOf("--"),h=d.slice(0,p),k=d.slice(p+2);k=k.replace(/-([a-z])/g,(w,b)=>b.toUpperCase()),n.get(h===""?null:h).set(k,[m,e.getOptions(`--${i}${d}`)])}let f=e.getOptions(`--${i}`);for(let[d,m]of n){let p=t.get(d);if(typeof p!="string")continue;let h={},k={};for(let[w,[b,A]]of m)h[w]=b,k[w]=A;t.set(d,[p,h]),l.set(d,[f,k])}let u={},c={};for(let[d,m]of t)Sn(u,[d??"DEFAULT"],m);for(let[d,m]of l)Sn(c,[d??"DEFAULT"],m);return r[r.length-1]==="DEFAULT"?[u?.DEFAULT??null,c.DEFAULT??0]:r.length>1&&"DEFAULT"in u&&Object.keys(u).length===1?[u.DEFAULT,c.DEFAULT??0]:(u.__CSS_VALUES__=c,[u,c])}function Cn(e,r){for(let i=0;i{d.src=o}),r.push(c)},addVariant(f,u){if(!Bt.test(f))throw new Error(`\`addVariant('${f}')\` defines an invalid variant name. Variants should only contain alphanumeric, dashes, or underscore characters and start with a lowercase letter or number.`);if(typeof u=="string"){if(u.includes(":merge("))return}else if(Array.isArray(u)){if(u.some(d=>d.includes(":merge(")))return}else if(typeof u=="object"){let d=function(m,p){return Object.entries(m).some(([h,k])=>h.includes(p)||typeof k=="object"&&d(k,p))};var c=d;if(d(u,":merge("))return}typeof u=="string"||Array.isArray(u)?e.variants.static(f,d=>{d.nodes=Tn(u,d.nodes)},{compounds:ze(typeof u=="string"?[u]:u)}):typeof u=="object"&&e.variants.fromAst(f,ye(u),e)},matchVariant(f,u,c){function d(p,h,k){let w=u(p,{modifier:h?.value??null});return Tn(w,k)}try{let p=u("a",{modifier:null});if(typeof p=="string"&&p.includes(":merge("))return;if(Array.isArray(p)&&p.some(h=>h.includes(":merge(")))return}catch{}let m=Object.keys(c?.values??{});e.variants.group(()=>{e.variants.functional(f,(p,h)=>{if(!h.value){if(c?.values&&"DEFAULT"in c.values){p.nodes=d(c.values.DEFAULT,h.modifier,p.nodes);return}return null}if(h.value.kind==="arbitrary")p.nodes=d(h.value.value,h.modifier,p.nodes);else if(h.value.kind==="named"&&c?.values){if(!Object.hasOwn(c.values,h.value.value))return null;let k=c.values[h.value.value];if(typeof k!="string")return null;p.nodes=d(k,h.modifier,p.nodes)}else return null})},(p,h)=>{if(p.kind!=="functional"||h.kind!=="functional")return 0;let k=p.value?p.value.value:"DEFAULT",w=h.value?h.value.value:"DEFAULT",b=(c?.values&&Object.hasOwn(c.values,k)?c.values[k]:void 0)??k,A=(c?.values&&Object.hasOwn(c.values,w)?c.values[w]:void 0)??w;if(c&&typeof c.sort=="function")return c.sort({value:b,modifier:p.modifier?.value??null},{value:A,modifier:h.modifier?.value??null});let C=m.indexOf(k),y=m.indexOf(w);return C=C===-1?m.length:C,y=y===-1?m.length:y,C!==y?C-y:bObject.keys(c?.values??{}).filter(p=>p!=="DEFAULT"))},addUtilities(f){f=Array.isArray(f)?f:[f];let u=f.flatMap(d=>Object.entries(d));u=u.flatMap(([d,m])=>j(d,",").map(p=>[p.trim(),m]));let c=new K(()=>[]);for(let[d,m]of u){if(d.startsWith("@keyframes ")){if(!n){let k=J(d,ye(m));I([k],w=>{w.src=o}),r.push(k)}continue}let p=pe(d),h=!1;if(I(p,k=>{if(k.kind==="selector"&&k.value[0]==="."&&Vn.test(k.value.slice(1))){let w=k.value;k.value="&";let b=se(p),A=w.slice(1),C=b==="&"?ye(m):[J(b,ye(m))];c.get(A).push(...C),h=!0,k.value=w;return}if(k.kind==="function"&&(k.value===":not"||k.value===":nth-child"||k.value===":nth-last-child"))return V.Skip}),!h)throw new Error(`\`addUtilities({ '${d}' : \u2026 })\` defines an invalid utility selector. Utilities must be a single class name and start with a lowercase letter, eg. \`.scrollbar-none\`.`)}for(let[d,m]of c)e.theme.prefix&&I(m,p=>{if(p.kind==="rule"){let h=pe(p.selector);I(h,k=>{k.kind==="selector"&&k.value[0]==="."&&(k.value=`.${e.theme.prefix}\\:${k.value.slice(1)}`)}),p.selector=se(h)}}),e.utilities.static(d,p=>{let h=m.map(le);return $n(h,d,p.raw),t.current|=Ee(h,e),h})},matchUtilities(f,u){let c=u?.type?Array.isArray(u?.type)?u.type:[u.type]:["any"];for(let[m,p]of Object.entries(f)){let h=function({negative:k}){return w=>{if(w.value?.kind==="arbitrary"&&c.length>0&&!c.includes("any")&&(w.value.dataType&&!c.includes(w.value.dataType)||!w.value.dataType&&!X(w.value.value,c)))return;let b=c.includes("color"),A=null,C=!1;{let O=u?.values??{};b&&(O=Object.assign({inherit:"inherit",transparent:"transparent",current:"currentcolor"},O)),w.value?w.value.kind==="arbitrary"?A=w.value.value:w.value.fraction&&Object.hasOwn(O,w.value.fraction)?(A=O[w.value.fraction],C=!0):Object.hasOwn(O,w.value.value)?A=O[w.value.value]:O.__BARE_VALUE__&&(A=O.__BARE_VALUE__(w.value)??null,C=(w.value.fraction!==null&&A?.includes("/"))??!1):A=O.DEFAULT??null}if(A===null)return;let y;{let O=u?.modifiers??null;w.modifier?O==="any"||w.modifier.kind==="arbitrary"?y=w.modifier.value:O&&Object.hasOwn(O,w.modifier.value)?y=O[w.modifier.value]:b&&!Number.isNaN(Number(w.modifier.value))?y=`${w.modifier.value}%`:y=null:y=null}if(w.modifier&&y===null&&!C)return w.value?.kind==="arbitrary"?null:void 0;b&&y!==null&&(A=ie(A,y)),k&&(A=`calc(${A} * -1)`);let E=ye(p(A,{modifier:y}));return $n(E,m,w.raw),t.current|=Ee(E,e),E}};var d=h;if(!Vn.test(m))throw new Error(`\`matchUtilities({ '${m}' : \u2026 })\` defines an invalid utility name. Utilities should be alphanumeric and start with a lowercase letter, eg. \`scrollbar\`.`);u?.supportsNegativeValues&&e.utilities.functional(`-${m}`,h({negative:!0}),{types:c}),e.utilities.functional(m,h({negative:!1}),{types:c}),e.utilities.suggest(m,()=>{let k=u?.values??{},w=new Set(Object.keys(k));w.delete("__BARE_VALUE__"),w.delete("__CSS_VALUES__"),w.has("DEFAULT")&&(w.delete("DEFAULT"),w.add(null));let b=u?.modifiers??{},A=b==="any"?[]:Object.keys(b);return[{supportsNegative:u?.supportsNegativeValues??!1,values:Array.from(w),modifiers:A}]})}},addComponents(f,u){this.addUtilities(f,u)},matchComponents(f,u){this.matchUtilities(f,u)},theme:Yt(e,()=>i.theme??{},f=>f),prefix(f){return f},config(f,u){let c=i;if(!f)return c;let d=Ke(f);for(let m=0;mObject.entries(t));for(let[t,n]of i)if(n!=null&&n!==!1)if(typeof n!="object"){if(!t.startsWith("--")){if(n==="@slot"){r.push(J(t,[H("@slot")]));continue}t=t.replace(/([A-Z])/g,"-$1").toLowerCase()}r.push(s(t,String(n)))}else if(Array.isArray(n))for(let o of n)typeof o=="string"?r.push(s(t,o)):r.push(J(t,ye(o)));else r.push(J(t,ye(n)));return r}function Tn(e,r){return(typeof e=="string"?[e]:e).flatMap(t=>{if(t.trim().endsWith("}")){let n=t.includes("@scope"),o=t.replace("}","{@slot}}"),l=_e(o);return n?(dt(l,[ee({source:"user"},r)]),ee({source:"variant"},l)):(dt(l,r),l)}else{let n=J(t,r);return n.kind==="at-rule"&&n.name==="@scope"?(n.nodes=[ee({source:"user"},r)],ee({source:"variant"},[n])):n}})}function $n(e,r,i){I(e,t=>{if(t.kind==="rule"){let n=pe(t.selector);I(n,o=>{o.kind==="selector"&&o.value===`.${r}`&&(o.value=`.${Te(i)}`)}),t.selector=se(n)}})}function Nn(e,r){for(let i of Ea(r))e.theme.addKeyframes(i)}function Ea(e){let r=[];if("keyframes"in e.theme)for(let[i,t]of Object.entries(e.theme.keyframes))r.push(H("@keyframes",i,ye(t)));return r}var qt={inherit:"inherit",current:"currentcolor",transparent:"transparent",black:"#000",white:"#fff",slate:{50:"oklch(98.4% 0.003 247.858)",100:"oklch(96.8% 0.007 247.896)",200:"oklch(92.9% 0.013 255.508)",300:"oklch(86.9% 0.022 252.894)",400:"oklch(70.4% 0.04 256.788)",500:"oklch(55.4% 0.046 257.417)",600:"oklch(44.6% 0.043 257.281)",700:"oklch(37.2% 0.044 257.287)",800:"oklch(27.9% 0.041 260.031)",900:"oklch(20.8% 0.042 265.755)",950:"oklch(12.9% 0.042 264.695)"},gray:{50:"oklch(98.5% 0.002 247.839)",100:"oklch(96.7% 0.003 264.542)",200:"oklch(92.8% 0.006 264.531)",300:"oklch(87.2% 0.01 258.338)",400:"oklch(70.7% 0.022 261.325)",500:"oklch(55.1% 0.027 264.364)",600:"oklch(44.6% 0.03 256.802)",700:"oklch(37.3% 0.034 259.733)",800:"oklch(27.8% 0.033 256.848)",900:"oklch(21% 0.034 264.665)",950:"oklch(13% 0.028 261.692)"},zinc:{50:"oklch(98.5% 0 none)",100:"oklch(96.7% 0.001 286.375)",200:"oklch(92% 0.004 286.32)",300:"oklch(87.1% 0.006 286.286)",400:"oklch(70.5% 0.015 286.067)",500:"oklch(55.2% 0.016 285.938)",600:"oklch(44.2% 0.017 285.786)",700:"oklch(37% 0.013 285.805)",800:"oklch(27.4% 0.006 286.033)",900:"oklch(21% 0.006 285.885)",950:"oklch(14.1% 0.005 285.823)"},neutral:{50:"oklch(98.5% 0 none)",100:"oklch(97% 0 none)",200:"oklch(92.2% 0 none)",300:"oklch(87% 0 none)",400:"oklch(70.8% 0 none)",500:"oklch(55.6% 0 none)",600:"oklch(43.9% 0 none)",700:"oklch(37.1% 0 none)",800:"oklch(26.9% 0 none)",900:"oklch(20.5% 0 none)",950:"oklch(14.5% 0 none)"},stone:{50:"oklch(98.5% 0.001 106.423)",100:"oklch(97% 0.001 106.424)",200:"oklch(92.3% 0.003 48.717)",300:"oklch(86.9% 0.005 56.366)",400:"oklch(70.9% 0.01 56.259)",500:"oklch(55.3% 0.013 58.071)",600:"oklch(44.4% 0.011 73.639)",700:"oklch(37.4% 0.01 67.558)",800:"oklch(26.8% 0.007 34.298)",900:"oklch(21.6% 0.006 56.043)",950:"oklch(14.7% 0.004 49.25)"},mauve:{50:"oklch(98.5% 0 none)",100:"oklch(96% 0.003 325.6)",200:"oklch(92.2% 0.005 325.62)",300:"oklch(86.5% 0.012 325.68)",400:"oklch(71.1% 0.019 323.02)",500:"oklch(54.2% 0.034 322.5)",600:"oklch(43.5% 0.029 321.78)",700:"oklch(36.4% 0.029 323.89)",800:"oklch(26.3% 0.024 320.12)",900:"oklch(21.2% 0.019 322.12)",950:"oklch(14.5% 0.008 326)"},olive:{50:"oklch(98.8% 0.003 106.5)",100:"oklch(96.6% 0.005 106.5)",200:"oklch(93% 0.007 106.5)",300:"oklch(88% 0.011 106.6)",400:"oklch(73.7% 0.021 106.9)",500:"oklch(58% 0.031 107.3)",600:"oklch(46.6% 0.025 107.3)",700:"oklch(39.4% 0.023 107.4)",800:"oklch(28.6% 0.016 107.4)",900:"oklch(22.8% 0.013 107.4)",950:"oklch(15.3% 0.006 107.1)"},mist:{50:"oklch(98.7% 0.002 197.1)",100:"oklch(96.3% 0.002 197.1)",200:"oklch(92.5% 0.005 214.3)",300:"oklch(87.2% 0.007 219.6)",400:"oklch(72.3% 0.014 214.4)",500:"oklch(56% 0.021 213.5)",600:"oklch(45% 0.017 213.2)",700:"oklch(37.8% 0.015 216)",800:"oklch(27.5% 0.011 216.9)",900:"oklch(21.8% 0.008 223.9)",950:"oklch(14.8% 0.004 228.8)"},taupe:{50:"oklch(98.6% 0.002 67.8)",100:"oklch(96% 0.002 17.2)",200:"oklch(92.2% 0.005 34.3)",300:"oklch(86.8% 0.007 39.5)",400:"oklch(71.4% 0.014 41.2)",500:"oklch(54.7% 0.021 43.1)",600:"oklch(43.8% 0.017 39.3)",700:"oklch(36.7% 0.016 35.7)",800:"oklch(26.8% 0.011 36.5)",900:"oklch(21.4% 0.009 43.1)",950:"oklch(14.7% 0.004 49.3)"},red:{50:"oklch(97.1% 0.013 17.38)",100:"oklch(93.6% 0.032 17.717)",200:"oklch(88.5% 0.062 18.334)",300:"oklch(80.8% 0.114 19.571)",400:"oklch(70.4% 0.191 22.216)",500:"oklch(63.7% 0.237 25.331)",600:"oklch(57.7% 0.245 27.325)",700:"oklch(50.5% 0.213 27.518)",800:"oklch(44.4% 0.177 26.899)",900:"oklch(39.6% 0.141 25.723)",950:"oklch(25.8% 0.092 26.042)"},orange:{50:"oklch(98% 0.016 73.684)",100:"oklch(95.4% 0.038 75.164)",200:"oklch(90.1% 0.076 70.697)",300:"oklch(83.7% 0.128 66.29)",400:"oklch(75% 0.183 55.934)",500:"oklch(70.5% 0.213 47.604)",600:"oklch(64.6% 0.222 41.116)",700:"oklch(55.3% 0.195 38.402)",800:"oklch(47% 0.157 37.304)",900:"oklch(40.8% 0.123 38.172)",950:"oklch(26.6% 0.079 36.259)"},amber:{50:"oklch(98.7% 0.022 95.277)",100:"oklch(96.2% 0.059 95.617)",200:"oklch(92.4% 0.12 95.746)",300:"oklch(87.9% 0.169 91.605)",400:"oklch(82.8% 0.189 84.429)",500:"oklch(76.9% 0.188 70.08)",600:"oklch(66.6% 0.179 58.318)",700:"oklch(55.5% 0.163 48.998)",800:"oklch(47.3% 0.137 46.201)",900:"oklch(41.4% 0.112 45.904)",950:"oklch(27.9% 0.077 45.635)"},yellow:{50:"oklch(98.7% 0.026 102.212)",100:"oklch(97.3% 0.071 103.193)",200:"oklch(94.5% 0.129 101.54)",300:"oklch(90.5% 0.182 98.111)",400:"oklch(85.2% 0.199 91.936)",500:"oklch(79.5% 0.184 86.047)",600:"oklch(68.1% 0.162 75.834)",700:"oklch(55.4% 0.135 66.442)",800:"oklch(47.6% 0.114 61.907)",900:"oklch(42.1% 0.095 57.708)",950:"oklch(28.6% 0.066 53.813)"},lime:{50:"oklch(98.6% 0.031 120.757)",100:"oklch(96.7% 0.067 122.328)",200:"oklch(93.8% 0.127 124.321)",300:"oklch(89.7% 0.196 126.665)",400:"oklch(84.1% 0.238 128.85)",500:"oklch(76.8% 0.233 130.85)",600:"oklch(64.8% 0.2 131.684)",700:"oklch(53.2% 0.157 131.589)",800:"oklch(45.3% 0.124 130.933)",900:"oklch(40.5% 0.101 131.063)",950:"oklch(27.4% 0.072 132.109)"},green:{50:"oklch(98.2% 0.018 155.826)",100:"oklch(96.2% 0.044 156.743)",200:"oklch(92.5% 0.084 155.995)",300:"oklch(87.1% 0.15 154.449)",400:"oklch(79.2% 0.209 151.711)",500:"oklch(72.3% 0.219 149.579)",600:"oklch(62.7% 0.194 149.214)",700:"oklch(52.7% 0.154 150.069)",800:"oklch(44.8% 0.119 151.328)",900:"oklch(39.3% 0.095 152.535)",950:"oklch(26.6% 0.065 152.934)"},emerald:{50:"oklch(97.9% 0.021 166.113)",100:"oklch(95% 0.052 163.051)",200:"oklch(90.5% 0.093 164.15)",300:"oklch(84.5% 0.143 164.978)",400:"oklch(76.5% 0.177 163.223)",500:"oklch(69.6% 0.17 162.48)",600:"oklch(59.6% 0.145 163.225)",700:"oklch(50.8% 0.118 165.612)",800:"oklch(43.2% 0.095 166.913)",900:"oklch(37.8% 0.077 168.94)",950:"oklch(26.2% 0.051 172.552)"},teal:{50:"oklch(98.4% 0.014 180.72)",100:"oklch(95.3% 0.051 180.801)",200:"oklch(91% 0.096 180.426)",300:"oklch(85.5% 0.138 181.071)",400:"oklch(77.7% 0.152 181.912)",500:"oklch(70.4% 0.14 182.503)",600:"oklch(60% 0.118 184.704)",700:"oklch(51.1% 0.096 186.391)",800:"oklch(43.7% 0.078 188.216)",900:"oklch(38.6% 0.063 188.416)",950:"oklch(27.7% 0.046 192.524)"},cyan:{50:"oklch(98.4% 0.019 200.873)",100:"oklch(95.6% 0.045 203.388)",200:"oklch(91.7% 0.08 205.041)",300:"oklch(86.5% 0.127 207.078)",400:"oklch(78.9% 0.154 211.53)",500:"oklch(71.5% 0.143 215.221)",600:"oklch(60.9% 0.126 221.723)",700:"oklch(52% 0.105 223.128)",800:"oklch(45% 0.085 224.283)",900:"oklch(39.8% 0.07 227.392)",950:"oklch(30.2% 0.056 229.695)"},sky:{50:"oklch(97.7% 0.013 236.62)",100:"oklch(95.1% 0.026 236.824)",200:"oklch(90.1% 0.058 230.902)",300:"oklch(82.8% 0.111 230.318)",400:"oklch(74.6% 0.16 232.661)",500:"oklch(68.5% 0.169 237.323)",600:"oklch(58.8% 0.158 241.966)",700:"oklch(50% 0.134 242.749)",800:"oklch(44.3% 0.11 240.79)",900:"oklch(39.1% 0.09 240.876)",950:"oklch(29.3% 0.066 243.157)"},blue:{50:"oklch(97% 0.014 254.604)",100:"oklch(93.2% 0.032 255.585)",200:"oklch(88.2% 0.059 254.128)",300:"oklch(80.9% 0.105 251.813)",400:"oklch(70.7% 0.165 254.624)",500:"oklch(62.3% 0.214 259.815)",600:"oklch(54.6% 0.245 262.881)",700:"oklch(48.8% 0.243 264.376)",800:"oklch(42.4% 0.199 265.638)",900:"oklch(37.9% 0.146 265.522)",950:"oklch(28.2% 0.091 267.935)"},indigo:{50:"oklch(96.2% 0.018 272.314)",100:"oklch(93% 0.034 272.788)",200:"oklch(87% 0.065 274.039)",300:"oklch(78.5% 0.115 274.713)",400:"oklch(67.3% 0.182 276.935)",500:"oklch(58.5% 0.233 277.117)",600:"oklch(51.1% 0.262 276.966)",700:"oklch(45.7% 0.24 277.023)",800:"oklch(39.8% 0.195 277.366)",900:"oklch(35.9% 0.144 278.697)",950:"oklch(25.7% 0.09 281.288)"},violet:{50:"oklch(96.9% 0.016 293.756)",100:"oklch(94.3% 0.029 294.588)",200:"oklch(89.4% 0.057 293.283)",300:"oklch(81.1% 0.111 293.571)",400:"oklch(70.2% 0.183 293.541)",500:"oklch(60.6% 0.25 292.717)",600:"oklch(54.1% 0.281 293.009)",700:"oklch(49.1% 0.27 292.581)",800:"oklch(43.2% 0.232 292.759)",900:"oklch(38% 0.189 293.745)",950:"oklch(28.3% 0.141 291.089)"},purple:{50:"oklch(97.7% 0.014 308.299)",100:"oklch(94.6% 0.033 307.174)",200:"oklch(90.2% 0.063 306.703)",300:"oklch(82.7% 0.119 306.383)",400:"oklch(71.4% 0.203 305.504)",500:"oklch(62.7% 0.265 303.9)",600:"oklch(55.8% 0.288 302.321)",700:"oklch(49.6% 0.265 301.924)",800:"oklch(43.8% 0.218 303.724)",900:"oklch(38.1% 0.176 304.987)",950:"oklch(29.1% 0.149 302.717)"},fuchsia:{50:"oklch(97.7% 0.017 320.058)",100:"oklch(95.2% 0.037 318.852)",200:"oklch(90.3% 0.076 319.62)",300:"oklch(83.3% 0.145 321.434)",400:"oklch(74% 0.238 322.16)",500:"oklch(66.7% 0.295 322.15)",600:"oklch(59.1% 0.293 322.896)",700:"oklch(51.8% 0.253 323.949)",800:"oklch(45.2% 0.211 324.591)",900:"oklch(40.1% 0.17 325.612)",950:"oklch(29.3% 0.136 325.661)"},pink:{50:"oklch(97.1% 0.014 343.198)",100:"oklch(94.8% 0.028 342.258)",200:"oklch(89.9% 0.061 343.231)",300:"oklch(82.3% 0.12 346.018)",400:"oklch(71.8% 0.202 349.761)",500:"oklch(65.6% 0.241 354.308)",600:"oklch(59.2% 0.249 0.584)",700:"oklch(52.5% 0.223 3.958)",800:"oklch(45.9% 0.187 3.815)",900:"oklch(40.8% 0.153 2.432)",950:"oklch(28.4% 0.109 3.907)"},rose:{50:"oklch(96.9% 0.015 12.422)",100:"oklch(94.1% 0.03 12.58)",200:"oklch(89.2% 0.058 10.001)",300:"oklch(81% 0.117 11.638)",400:"oklch(71.2% 0.194 13.428)",500:"oklch(64.5% 0.246 16.439)",600:"oklch(58.6% 0.253 17.585)",700:"oklch(51.4% 0.222 16.935)",800:"oklch(45.5% 0.188 13.697)",900:"oklch(41% 0.159 10.272)",950:"oklch(27.1% 0.105 12.094)"}};function Me(e){return{__BARE_VALUE__:e}}var ke=Me(e=>{if(D(e.value))return e.value}),ue=Me(e=>{if(D(e.value))return`${e.value}%`}),Pe=Me(e=>{if(D(e.value))return`${e.value}px`}),En=Me(e=>{if(D(e.value))return`${e.value}ms`}),Ht=Me(e=>{if(D(e.value))return`${e.value}deg`}),Ra=Me(e=>{if(e.fraction===null)return;let[r,i]=j(e.fraction,"/");if(!(!D(r)||!D(i)))return e.fraction}),Rn=Me(e=>{if(D(Number(e.value)))return`repeat(${e.value}, minmax(0, 1fr))`}),Pn={accentColor:({theme:e})=>e("colors"),animation:{none:"none",spin:"spin 1s linear infinite",ping:"ping 1s cubic-bezier(0, 0, 0.2, 1) infinite",pulse:"pulse 2s cubic-bezier(0.4, 0, 0.6, 1) infinite",bounce:"bounce 1s infinite"},aria:{busy:'busy="true"',checked:'checked="true"',disabled:'disabled="true"',expanded:'expanded="true"',hidden:'hidden="true"',pressed:'pressed="true"',readonly:'readonly="true"',required:'required="true"',selected:'selected="true"'},aspectRatio:{auto:"auto",square:"1 / 1",video:"16 / 9",...Ra},backdropBlur:({theme:e})=>e("blur"),backdropBrightness:({theme:e})=>({...e("brightness"),...ue}),backdropContrast:({theme:e})=>({...e("contrast"),...ue}),backdropGrayscale:({theme:e})=>({...e("grayscale"),...ue}),backdropHueRotate:({theme:e})=>({...e("hueRotate"),...Ht}),backdropInvert:({theme:e})=>({...e("invert"),...ue}),backdropOpacity:({theme:e})=>({...e("opacity"),...ue}),backdropSaturate:({theme:e})=>({...e("saturate"),...ue}),backdropSepia:({theme:e})=>({...e("sepia"),...ue}),backgroundColor:({theme:e})=>e("colors"),backgroundImage:{none:"none","gradient-to-t":"linear-gradient(to top, var(--tw-gradient-stops))","gradient-to-tr":"linear-gradient(to top right, var(--tw-gradient-stops))","gradient-to-r":"linear-gradient(to right, var(--tw-gradient-stops))","gradient-to-br":"linear-gradient(to bottom right, var(--tw-gradient-stops))","gradient-to-b":"linear-gradient(to bottom, var(--tw-gradient-stops))","gradient-to-bl":"linear-gradient(to bottom left, var(--tw-gradient-stops))","gradient-to-l":"linear-gradient(to left, var(--tw-gradient-stops))","gradient-to-tl":"linear-gradient(to top left, var(--tw-gradient-stops))"},backgroundOpacity:({theme:e})=>e("opacity"),backgroundPosition:{bottom:"bottom",center:"center",left:"left","left-bottom":"left bottom","left-top":"left top",right:"right","right-bottom":"right bottom","right-top":"right top",top:"top"},backgroundSize:{auto:"auto",cover:"cover",contain:"contain"},blur:{0:"0",none:"",sm:"4px",DEFAULT:"8px",md:"12px",lg:"16px",xl:"24px","2xl":"40px","3xl":"64px"},borderColor:({theme:e})=>({DEFAULT:"currentcolor",...e("colors")}),borderOpacity:({theme:e})=>e("opacity"),borderRadius:{none:"0px",sm:"0.125rem",DEFAULT:"0.25rem",md:"0.375rem",lg:"0.5rem",xl:"0.75rem","2xl":"1rem","3xl":"1.5rem",full:"9999px"},borderSpacing:({theme:e})=>e("spacing"),borderWidth:{DEFAULT:"1px",0:"0px",2:"2px",4:"4px",8:"8px",...Pe},boxShadow:{sm:"0 1px 2px 0 rgb(0 0 0 / 0.05)",DEFAULT:"0 1px 3px 0 rgb(0 0 0 / 0.1), 0 1px 2px -1px rgb(0 0 0 / 0.1)",md:"0 4px 6px -1px rgb(0 0 0 / 0.1), 0 2px 4px -2px rgb(0 0 0 / 0.1)",lg:"0 10px 15px -3px rgb(0 0 0 / 0.1), 0 4px 6px -4px rgb(0 0 0 / 0.1)",xl:"0 20px 25px -5px rgb(0 0 0 / 0.1), 0 8px 10px -6px rgb(0 0 0 / 0.1)","2xl":"0 25px 50px -12px rgb(0 0 0 / 0.25)",inner:"inset 0 2px 4px 0 rgb(0 0 0 / 0.05)",none:"none"},boxShadowColor:({theme:e})=>e("colors"),brightness:{0:"0",50:".5",75:".75",90:".9",95:".95",100:"1",105:"1.05",110:"1.1",125:"1.25",150:"1.5",200:"2",...ue},caretColor:({theme:e})=>e("colors"),colors:()=>({...qt}),columns:{auto:"auto",1:"1",2:"2",3:"3",4:"4",5:"5",6:"6",7:"7",8:"8",9:"9",10:"10",11:"11",12:"12","3xs":"16rem","2xs":"18rem",xs:"20rem",sm:"24rem",md:"28rem",lg:"32rem",xl:"36rem","2xl":"42rem","3xl":"48rem","4xl":"56rem","5xl":"64rem","6xl":"72rem","7xl":"80rem",...ke},container:{},content:{none:"none"},contrast:{0:"0",50:".5",75:".75",100:"1",125:"1.25",150:"1.5",200:"2",...ue},cursor:{auto:"auto",default:"default",pointer:"pointer",wait:"wait",text:"text",move:"move",help:"help","not-allowed":"not-allowed",none:"none","context-menu":"context-menu",progress:"progress",cell:"cell",crosshair:"crosshair","vertical-text":"vertical-text",alias:"alias",copy:"copy","no-drop":"no-drop",grab:"grab",grabbing:"grabbing","all-scroll":"all-scroll","col-resize":"col-resize","row-resize":"row-resize","n-resize":"n-resize","e-resize":"e-resize","s-resize":"s-resize","w-resize":"w-resize","ne-resize":"ne-resize","nw-resize":"nw-resize","se-resize":"se-resize","sw-resize":"sw-resize","ew-resize":"ew-resize","ns-resize":"ns-resize","nesw-resize":"nesw-resize","nwse-resize":"nwse-resize","zoom-in":"zoom-in","zoom-out":"zoom-out"},divideColor:({theme:e})=>e("borderColor"),divideOpacity:({theme:e})=>e("borderOpacity"),divideWidth:({theme:e})=>({...e("borderWidth"),...Pe}),dropShadow:{sm:"0 1px 1px rgb(0 0 0 / 0.05)",DEFAULT:["0 1px 2px rgb(0 0 0 / 0.1)","0 1px 1px rgb(0 0 0 / 0.06)"],md:["0 4px 3px rgb(0 0 0 / 0.07)","0 2px 2px rgb(0 0 0 / 0.06)"],lg:["0 10px 8px rgb(0 0 0 / 0.04)","0 4px 3px rgb(0 0 0 / 0.1)"],xl:["0 20px 13px rgb(0 0 0 / 0.03)","0 8px 5px rgb(0 0 0 / 0.08)"],"2xl":"0 25px 25px rgb(0 0 0 / 0.15)",none:"0 0 #0000"},fill:({theme:e})=>e("colors"),flex:{1:"1 1 0%",auto:"1 1 auto",initial:"0 1 auto",none:"none"},flexBasis:({theme:e})=>({auto:"auto","1/2":"50%","1/3":"33.333333%","2/3":"66.666667%","1/4":"25%","2/4":"50%","3/4":"75%","1/5":"20%","2/5":"40%","3/5":"60%","4/5":"80%","1/6":"16.666667%","2/6":"33.333333%","3/6":"50%","4/6":"66.666667%","5/6":"83.333333%","1/12":"8.333333%","2/12":"16.666667%","3/12":"25%","4/12":"33.333333%","5/12":"41.666667%","6/12":"50%","7/12":"58.333333%","8/12":"66.666667%","9/12":"75%","10/12":"83.333333%","11/12":"91.666667%",full:"100%",...e("spacing")}),flexGrow:{0:"0",DEFAULT:"1",...ke},flexShrink:{0:"0",DEFAULT:"1",...ke},fontFamily:{sans:["-apple-system","BlinkMacSystemFont",'"Segoe UI"',"Roboto",'"Helvetica Neue"','"Noto Sans"',"Arial","sans-serif",'"Apple Color Emoji"','"Segoe UI Emoji"','"Segoe UI Symbol"','"Noto Color Emoji"'],serif:["ui-serif","Georgia","Cambria",'"Times New Roman"',"Times","serif"],mono:["ui-monospace","SFMono-Regular","Menlo","Monaco","Consolas",'"Liberation Mono"','"Courier New"',"monospace"]},fontSize:{xs:["0.75rem",{lineHeight:"1rem"}],sm:["0.875rem",{lineHeight:"1.25rem"}],base:["1rem",{lineHeight:"1.5rem"}],lg:["1.125rem",{lineHeight:"1.75rem"}],xl:["1.25rem",{lineHeight:"1.75rem"}],"2xl":["1.5rem",{lineHeight:"2rem"}],"3xl":["1.875rem",{lineHeight:"2.25rem"}],"4xl":["2.25rem",{lineHeight:"2.5rem"}],"5xl":["3rem",{lineHeight:"1"}],"6xl":["3.75rem",{lineHeight:"1"}],"7xl":["4.5rem",{lineHeight:"1"}],"8xl":["6rem",{lineHeight:"1"}],"9xl":["8rem",{lineHeight:"1"}]},fontWeight:{thin:"100",extralight:"200",light:"300",normal:"400",medium:"500",semibold:"600",bold:"700",extrabold:"800",black:"900"},gap:({theme:e})=>e("spacing"),gradientColorStops:({theme:e})=>e("colors"),gradientColorStopPositions:{"0%":"0%","5%":"5%","10%":"10%","15%":"15%","20%":"20%","25%":"25%","30%":"30%","35%":"35%","40%":"40%","45%":"45%","50%":"50%","55%":"55%","60%":"60%","65%":"65%","70%":"70%","75%":"75%","80%":"80%","85%":"85%","90%":"90%","95%":"95%","100%":"100%",...ue},grayscale:{0:"0",DEFAULT:"100%",...ue},gridAutoColumns:{auto:"auto",min:"min-content",max:"max-content",fr:"minmax(0, 1fr)"},gridAutoRows:{auto:"auto",min:"min-content",max:"max-content",fr:"minmax(0, 1fr)"},gridColumn:{auto:"auto","span-1":"span 1 / span 1","span-2":"span 2 / span 2","span-3":"span 3 / span 3","span-4":"span 4 / span 4","span-5":"span 5 / span 5","span-6":"span 6 / span 6","span-7":"span 7 / span 7","span-8":"span 8 / span 8","span-9":"span 9 / span 9","span-10":"span 10 / span 10","span-11":"span 11 / span 11","span-12":"span 12 / span 12","span-full":"1 / -1"},gridColumnEnd:{auto:"auto",1:"1",2:"2",3:"3",4:"4",5:"5",6:"6",7:"7",8:"8",9:"9",10:"10",11:"11",12:"12",13:"13",...ke},gridColumnStart:{auto:"auto",1:"1",2:"2",3:"3",4:"4",5:"5",6:"6",7:"7",8:"8",9:"9",10:"10",11:"11",12:"12",13:"13",...ke},gridRow:{auto:"auto","span-1":"span 1 / span 1","span-2":"span 2 / span 2","span-3":"span 3 / span 3","span-4":"span 4 / span 4","span-5":"span 5 / span 5","span-6":"span 6 / span 6","span-7":"span 7 / span 7","span-8":"span 8 / span 8","span-9":"span 9 / span 9","span-10":"span 10 / span 10","span-11":"span 11 / span 11","span-12":"span 12 / span 12","span-full":"1 / -1"},gridRowEnd:{auto:"auto",1:"1",2:"2",3:"3",4:"4",5:"5",6:"6",7:"7",8:"8",9:"9",10:"10",11:"11",12:"12",13:"13",...ke},gridRowStart:{auto:"auto",1:"1",2:"2",3:"3",4:"4",5:"5",6:"6",7:"7",8:"8",9:"9",10:"10",11:"11",12:"12",13:"13",...ke},gridTemplateColumns:{none:"none",subgrid:"subgrid",1:"repeat(1, minmax(0, 1fr))",2:"repeat(2, minmax(0, 1fr))",3:"repeat(3, minmax(0, 1fr))",4:"repeat(4, minmax(0, 1fr))",5:"repeat(5, minmax(0, 1fr))",6:"repeat(6, minmax(0, 1fr))",7:"repeat(7, minmax(0, 1fr))",8:"repeat(8, minmax(0, 1fr))",9:"repeat(9, minmax(0, 1fr))",10:"repeat(10, minmax(0, 1fr))",11:"repeat(11, minmax(0, 1fr))",12:"repeat(12, minmax(0, 1fr))",...Rn},gridTemplateRows:{none:"none",subgrid:"subgrid",1:"repeat(1, minmax(0, 1fr))",2:"repeat(2, minmax(0, 1fr))",3:"repeat(3, minmax(0, 1fr))",4:"repeat(4, minmax(0, 1fr))",5:"repeat(5, minmax(0, 1fr))",6:"repeat(6, minmax(0, 1fr))",7:"repeat(7, minmax(0, 1fr))",8:"repeat(8, minmax(0, 1fr))",9:"repeat(9, minmax(0, 1fr))",10:"repeat(10, minmax(0, 1fr))",11:"repeat(11, minmax(0, 1fr))",12:"repeat(12, minmax(0, 1fr))",...Rn},height:({theme:e})=>({auto:"auto","1/2":"50%","1/3":"33.333333%","2/3":"66.666667%","1/4":"25%","2/4":"50%","3/4":"75%","1/5":"20%","2/5":"40%","3/5":"60%","4/5":"80%","1/6":"16.666667%","2/6":"33.333333%","3/6":"50%","4/6":"66.666667%","5/6":"83.333333%",full:"100%",screen:"100vh",svh:"100svh",lvh:"100lvh",dvh:"100dvh",min:"min-content",max:"max-content",fit:"fit-content",...e("spacing")}),hueRotate:{0:"0deg",15:"15deg",30:"30deg",60:"60deg",90:"90deg",180:"180deg",...Ht},inset:({theme:e})=>({auto:"auto","1/2":"50%","1/3":"33.333333%","2/3":"66.666667%","1/4":"25%","2/4":"50%","3/4":"75%",full:"100%",...e("spacing")}),invert:{0:"0",DEFAULT:"100%",...ue},keyframes:{spin:{to:{transform:"rotate(360deg)"}},ping:{"75%, 100%":{transform:"scale(2)",opacity:"0"}},pulse:{"50%":{opacity:".5"}},bounce:{"0%, 100%":{transform:"translateY(-25%)",animationTimingFunction:"cubic-bezier(0.8,0,1,1)"},"50%":{transform:"none",animationTimingFunction:"cubic-bezier(0,0,0.2,1)"}}},letterSpacing:{tighter:"-0.05em",tight:"-0.025em",normal:"0em",wide:"0.025em",wider:"0.05em",widest:"0.1em"},lineHeight:{none:"1",tight:"1.25",snug:"1.375",normal:"1.5",relaxed:"1.625",loose:"2",3:".75rem",4:"1rem",5:"1.25rem",6:"1.5rem",7:"1.75rem",8:"2rem",9:"2.25rem",10:"2.5rem"},listStyleType:{none:"none",disc:"disc",decimal:"decimal"},listStyleImage:{none:"none"},margin:({theme:e})=>({auto:"auto",...e("spacing")}),lineClamp:{1:"1",2:"2",3:"3",4:"4",5:"5",6:"6",...ke},maxHeight:({theme:e})=>({none:"none",full:"100%",screen:"100vh",svh:"100svh",lvh:"100lvh",dvh:"100dvh",min:"min-content",max:"max-content",fit:"fit-content",...e("spacing")}),maxWidth:({theme:e})=>({none:"none",xs:"20rem",sm:"24rem",md:"28rem",lg:"32rem",xl:"36rem","2xl":"42rem","3xl":"48rem","4xl":"56rem","5xl":"64rem","6xl":"72rem","7xl":"80rem",full:"100%",min:"min-content",max:"max-content",fit:"fit-content",prose:"65ch",...e("spacing")}),minHeight:({theme:e})=>({full:"100%",screen:"100vh",svh:"100svh",lvh:"100lvh",dvh:"100dvh",min:"min-content",max:"max-content",fit:"fit-content",...e("spacing")}),minWidth:({theme:e})=>({full:"100%",min:"min-content",max:"max-content",fit:"fit-content",...e("spacing")}),objectPosition:{bottom:"bottom",center:"center",left:"left","left-bottom":"left bottom","left-top":"left top",right:"right","right-bottom":"right bottom","right-top":"right top",top:"top"},opacity:{0:"0",5:"0.05",10:"0.1",15:"0.15",20:"0.2",25:"0.25",30:"0.3",35:"0.35",40:"0.4",45:"0.45",50:"0.5",55:"0.55",60:"0.6",65:"0.65",70:"0.7",75:"0.75",80:"0.8",85:"0.85",90:"0.9",95:"0.95",100:"1",...ue},order:{first:"-9999",last:"9999",none:"0",1:"1",2:"2",3:"3",4:"4",5:"5",6:"6",7:"7",8:"8",9:"9",10:"10",11:"11",12:"12",...ke},outlineColor:({theme:e})=>e("colors"),outlineOffset:{0:"0px",1:"1px",2:"2px",4:"4px",8:"8px",...Pe},outlineWidth:{0:"0px",1:"1px",2:"2px",4:"4px",8:"8px",...Pe},padding:({theme:e})=>e("spacing"),placeholderColor:({theme:e})=>e("colors"),placeholderOpacity:({theme:e})=>e("opacity"),ringColor:({theme:e})=>({DEFAULT:"currentcolor",...e("colors")}),ringOffsetColor:({theme:e})=>e("colors"),ringOffsetWidth:{0:"0px",1:"1px",2:"2px",4:"4px",8:"8px",...Pe},ringOpacity:({theme:e})=>({DEFAULT:"0.5",...e("opacity")}),ringWidth:{DEFAULT:"3px",0:"0px",1:"1px",2:"2px",4:"4px",8:"8px",...Pe},rotate:{0:"0deg",1:"1deg",2:"2deg",3:"3deg",6:"6deg",12:"12deg",45:"45deg",90:"90deg",180:"180deg",...Ht},saturate:{0:"0",50:".5",100:"1",150:"1.5",200:"2",...ue},scale:{0:"0",50:".5",75:".75",90:".9",95:".95",100:"1",105:"1.05",110:"1.1",125:"1.25",150:"1.5",...ue},screens:{sm:"40rem",md:"48rem",lg:"64rem",xl:"80rem","2xl":"96rem"},scrollMargin:({theme:e})=>e("spacing"),scrollPadding:({theme:e})=>e("spacing"),sepia:{0:"0",DEFAULT:"100%",...ue},skew:{0:"0deg",1:"1deg",2:"2deg",3:"3deg",6:"6deg",12:"12deg",...Ht},space:({theme:e})=>e("spacing"),spacing:{px:"1px",0:"0px",.5:"0.125rem",1:"0.25rem",1.5:"0.375rem",2:"0.5rem",2.5:"0.625rem",3:"0.75rem",3.5:"0.875rem",4:"1rem",5:"1.25rem",6:"1.5rem",7:"1.75rem",8:"2rem",9:"2.25rem",10:"2.5rem",11:"2.75rem",12:"3rem",14:"3.5rem",16:"4rem",20:"5rem",24:"6rem",28:"7rem",32:"8rem",36:"9rem",40:"10rem",44:"11rem",48:"12rem",52:"13rem",56:"14rem",60:"15rem",64:"16rem",72:"18rem",80:"20rem",96:"24rem"},stroke:({theme:e})=>({none:"none",...e("colors")}),strokeWidth:{0:"0",1:"1",2:"2",...ke},supports:{},data:{},textColor:({theme:e})=>e("colors"),textDecorationColor:({theme:e})=>e("colors"),textDecorationThickness:{auto:"auto","from-font":"from-font",0:"0px",1:"1px",2:"2px",4:"4px",8:"8px",...Pe},textIndent:({theme:e})=>e("spacing"),textOpacity:({theme:e})=>e("opacity"),textUnderlineOffset:{auto:"auto",0:"0px",1:"1px",2:"2px",4:"4px",8:"8px",...Pe},transformOrigin:{center:"center",top:"top","top-right":"top right",right:"right","bottom-right":"bottom right",bottom:"bottom","bottom-left":"bottom left",left:"left","top-left":"top left"},transitionDelay:{0:"0s",75:"75ms",100:"100ms",150:"150ms",200:"200ms",300:"300ms",500:"500ms",700:"700ms",1e3:"1000ms",...En},transitionDuration:{DEFAULT:"150ms",0:"0s",75:"75ms",100:"100ms",150:"150ms",200:"200ms",300:"300ms",500:"500ms",700:"700ms",1e3:"1000ms",...En},transitionProperty:{none:"none",all:"all",DEFAULT:"color, background-color, border-color, outline-color, text-decoration-color, fill, stroke, opacity, box-shadow, transform, filter, backdrop-filter",colors:"color, background-color, border-color, outline-color, text-decoration-color, fill, stroke",opacity:"opacity",shadow:"box-shadow",transform:"transform"},transitionTimingFunction:{DEFAULT:"cubic-bezier(0.4, 0, 0.2, 1)",linear:"linear",in:"cubic-bezier(0.4, 0, 1, 1)",out:"cubic-bezier(0, 0, 0.2, 1)","in-out":"cubic-bezier(0.4, 0, 0.2, 1)"},translate:({theme:e})=>({"1/2":"50%","1/3":"33.333333%","2/3":"66.666667%","1/4":"25%","2/4":"50%","3/4":"75%",full:"100%",...e("spacing")}),size:({theme:e})=>({auto:"auto","1/2":"50%","1/3":"33.333333%","2/3":"66.666667%","1/4":"25%","2/4":"50%","3/4":"75%","1/5":"20%","2/5":"40%","3/5":"60%","4/5":"80%","1/6":"16.666667%","2/6":"33.333333%","3/6":"50%","4/6":"66.666667%","5/6":"83.333333%","1/12":"8.333333%","2/12":"16.666667%","3/12":"25%","4/12":"33.333333%","5/12":"41.666667%","6/12":"50%","7/12":"58.333333%","8/12":"66.666667%","9/12":"75%","10/12":"83.333333%","11/12":"91.666667%",full:"100%",min:"min-content",max:"max-content",fit:"fit-content",...e("spacing")}),width:({theme:e})=>({auto:"auto","1/2":"50%","1/3":"33.333333%","2/3":"66.666667%","1/4":"25%","2/4":"50%","3/4":"75%","1/5":"20%","2/5":"40%","3/5":"60%","4/5":"80%","1/6":"16.666667%","2/6":"33.333333%","3/6":"50%","4/6":"66.666667%","5/6":"83.333333%","1/12":"8.333333%","2/12":"16.666667%","3/12":"25%","4/12":"33.333333%","5/12":"41.666667%","6/12":"50%","7/12":"58.333333%","8/12":"66.666667%","9/12":"75%","10/12":"83.333333%","11/12":"91.666667%",full:"100%",screen:"100vw",svw:"100svw",lvw:"100lvw",dvw:"100dvw",min:"min-content",max:"max-content",fit:"fit-content",...e("spacing")}),willChange:{auto:"auto",scroll:"scroll-position",contents:"contents",transform:"transform"},zIndex:{auto:"auto",0:"0",10:"10",20:"20",30:"30",40:"40",50:"50",...ke}};function On(e){return{theme:{...Pn,colors:({theme:r})=>r("color",{}),extend:{fontSize:({theme:r})=>({...r("text",{})}),boxShadow:({theme:r})=>({...r("shadow",{})}),animation:({theme:r})=>({...r("animate",{})}),aspectRatio:({theme:r})=>({...r("aspect",{})}),borderRadius:({theme:r})=>({...r("radius",{})}),screens:({theme:r})=>({...r("breakpoint",{})}),letterSpacing:({theme:r})=>({...r("tracking",{})}),lineHeight:({theme:r})=>({...r("leading",{})}),transitionDuration:{DEFAULT:e.get(["--default-transition-duration"])??null},transitionTimingFunction:{DEFAULT:e.get(["--default-transition-timing-function"])??null},maxWidth:({theme:r})=>({...r("container",{})})}}}}var Pa={blocklist:[],future:{},experimental:{},prefix:"",important:!1,darkMode:null,theme:{},plugins:[],content:{files:[]}};function Dr(e,r){let i={design:e,configs:[],plugins:[],content:{files:[]},theme:{},extend:{},result:structuredClone(Pa)};for(let n of r)Ir(i,n);for(let n of i.configs)"darkMode"in n&&n.darkMode!==void 0&&(i.result.darkMode=n.darkMode??null),"prefix"in n&&n.prefix!==void 0&&(i.result.prefix=n.prefix??""),"blocklist"in n&&n.blocklist!==void 0&&(i.result.blocklist=n.blocklist??[]),"important"in n&&n.important!==void 0&&(i.result.important=n.important??!1);let t=_a(i);return{resolvedConfig:{...i.result,content:i.content,theme:i.theme,plugins:i.plugins},replacedThemeKeys:t}}function Oa(e,r){if(Array.isArray(e)&&et(e[0]))return e.concat(r);if(Array.isArray(r)&&et(r[0])&&et(e))return[e,...r];if(Array.isArray(r))return r}function Ir(e,{config:r,base:i,path:t,reference:n,src:o}){let l=[];for(let c of r.plugins??[])"__isOptionsFunction"in c?l.push({...c(),reference:n,src:o}):"handler"in c?l.push({...c,reference:n,src:o}):l.push({handler:c,reference:n,src:o});if(Array.isArray(r.presets)&&r.presets.length===0)throw new Error("Error in the config file/plugin/preset. An empty preset (`preset: []`) is not currently supported.");for(let c of r.presets??[])Ir(e,{path:t,base:i,config:c,reference:n,src:o});for(let c of l)e.plugins.push(c),c.config&&Ir(e,{path:t,base:i,config:c.config,reference:!!c.reference,src:c.src??o});let f=r.content??[],u=Array.isArray(f)?f:f.files;for(let c of u)e.content.files.push(typeof c=="object"?c:{base:i,pattern:c});e.configs.push(r)}function _a(e){let r=new Set,i=Yt(e.design,()=>e.theme,n),t=Object.assign(i,{theme:i,colors:qt});function n(o){return typeof o=="function"?o(t)??null:o??null}for(let o of e.configs){let l=o.theme??{},f=l.extend??{};for(let u in l)u!=="extend"&&r.add(u);Object.assign(e.theme,l);for(let u in f)e.extend[u]??=[],e.extend[u].push(f[u])}delete e.theme.extend;for(let o in e.extend){let l=[e.theme[o],...e.extend[o]];e.theme[o]=()=>{let f=l.map(n);return gt({},f,Oa)}}for(let o in e.theme)e.theme[o]=n(e.theme[o]);if(e.theme.screens&&typeof e.theme.screens=="object")for(let o of Object.keys(e.theme.screens)){let l=e.theme.screens[o];l&&typeof l=="object"&&("raw"in l||"max"in l||"min"in l&&(e.theme.screens[o]=l.min))}return r}function _n(e,r){let i=e.theme.container||{};if(typeof i!="object"||i===null)return;let t=Ia(i,r);t.length!==0&&r.utilities.static("container",()=>t.map(le))}function Ia({center:e,padding:r,screens:i},t){let n=[],o=null;if(e&&n.push(s("margin-inline","auto")),(typeof r=="string"||typeof r=="object"&&r!==null&&"DEFAULT"in r)&&n.push(s("padding-inline",typeof r=="string"?r:r.DEFAULT)),typeof i=="object"&&i!==null){o=new Map;let l=Array.from(t.theme.namespace("--breakpoint").entries());if(l.sort((f,u)=>De(f[1],u[1],"asc")),l.length>0){let[f]=l[0];n.push(H("@media",`(width >= --theme(--breakpoint-${f}))`,[s("max-width","none")]))}for(let[f,u]of Object.entries(i)){if(typeof u=="object")if("min"in u)u=u.min;else continue;o.set(f,H("@media",`(width >= ${u})`,[s("max-width",u)]))}}if(typeof r=="object"&&r!==null){let l=Object.entries(r).filter(([f])=>f!=="DEFAULT").map(([f,u])=>[f,t.theme.resolveValue(f,["--breakpoint"]),u]).filter(Boolean);l.sort((f,u)=>De(f[1],u[1],"asc"));for(let[f,,u]of l)if(o&&o.has(f))o.get(f).nodes.push(s("padding-inline",u));else{if(o)continue;n.push(H("@media",`(width >= theme(--breakpoint-${f}))`,[s("padding-inline",u)]))}}if(o)for(let[,l]of o)n.push(l);return n}function In({addVariant:e,config:r}){let i=r("darkMode",null),[t,n=".dark"]=Array.isArray(i)?i:[i];if(t==="variant"){let o;if(Array.isArray(n)||typeof n=="function"?o=n:typeof n=="string"&&(o=[n]),Array.isArray(o))for(let l of o)l===".dark"?(t=!1,console.warn('When using `variant` for `darkMode`, you must provide a selector.\nExample: `darkMode: ["variant", ".your-selector &"]`')):l.includes("&")||(t=!1,console.warn('When using `variant` for `darkMode`, your selector must contain `&`.\nExample `darkMode: ["variant", ".your-selector &"]`'));n=o}t===null||(t==="selector"?e("dark",`&:where(${n}, ${n} *)`):t==="media"?e("dark","@media (prefers-color-scheme: dark)"):t==="variant"?e("dark",n):t==="class"&&e("dark",`&:is(${n} *)`))}function Dn(e){for(let[i,t]of[["t","top"],["tr","top right"],["r","right"],["br","bottom right"],["b","bottom"],["bl","bottom left"],["l","left"],["tl","top left"]])e.utilities.suggest(`bg-gradient-to-${i}`,()=>[]),e.utilities.static(`bg-gradient-to-${i}`,()=>[s("--tw-gradient-position",`to ${t} in oklab`),s("background-image","linear-gradient(var(--tw-gradient-stops))")]);e.utilities.suggest("bg-left-top",()=>[]),e.utilities.static("bg-left-top",()=>[s("background-position","left top")]),e.utilities.suggest("bg-right-top",()=>[]),e.utilities.static("bg-right-top",()=>[s("background-position","right top")]),e.utilities.suggest("bg-left-bottom",()=>[]),e.utilities.static("bg-left-bottom",()=>[s("background-position","left bottom")]),e.utilities.suggest("bg-right-bottom",()=>[]),e.utilities.static("bg-right-bottom",()=>[s("background-position","right bottom")]),e.utilities.suggest("object-left-top",()=>[]),e.utilities.static("object-left-top",()=>[s("object-position","left top")]),e.utilities.suggest("object-right-top",()=>[]),e.utilities.static("object-right-top",()=>[s("object-position","right top")]),e.utilities.suggest("object-left-bottom",()=>[]),e.utilities.static("object-left-bottom",()=>[s("object-position","left bottom")]),e.utilities.suggest("object-right-bottom",()=>[]),e.utilities.static("object-right-bottom",()=>[s("object-position","right bottom")]),e.utilities.suggest("max-w-screen",()=>[]),e.utilities.functional("max-w-screen",i=>{if(!i.value||i.value.kind==="arbitrary")return;let t=e.theme.resolve(i.value.value,["--breakpoint"]);if(t)return[s("max-width",t)]}),e.utilities.suggest("overflow-ellipsis",()=>[]),e.utilities.static("overflow-ellipsis",()=>[s("text-overflow","ellipsis")]),e.utilities.suggest("decoration-slice",()=>[]),e.utilities.static("decoration-slice",()=>[s("-webkit-box-decoration-break","slice"),s("box-decoration-break","slice")]),e.utilities.suggest("decoration-clone",()=>[]),e.utilities.static("decoration-clone",()=>[s("-webkit-box-decoration-break","clone"),s("box-decoration-break","clone")]),e.utilities.suggest("flex-shrink",()=>[]),e.utilities.functional("flex-shrink",i=>{if(!i.modifier){if(!i.value)return[s("flex-shrink","1")];if(i.value.kind==="arbitrary")return[s("flex-shrink",i.value.value)];if(D(i.value.value))return[s("flex-shrink",i.value.value)]}}),e.utilities.suggest("flex-grow",()=>[]),e.utilities.functional("flex-grow",i=>{if(!i.modifier){if(!i.value)return[s("flex-grow","1")];if(i.value.kind==="arbitrary")return[s("flex-grow",i.value.value)];if(D(i.value.value))return[s("flex-grow",i.value.value)]}}),e.utilities.suggest("order-none",()=>[]),e.utilities.static("order-none",()=>[s("order","0")]),e.utilities.suggest("break-words",()=>[]),e.utilities.static("break-words",()=>[s("overflow-wrap","break-word")]);for(let[i,t]of[["start","inset-inline-start"],["end","inset-inline-end"]]){let n=function({negative:o}){return l=>{if(l.value===null)return;if(l.value.kind==="arbitrary"){if(l.modifier)return;let u=l.value.value;return[s(t,o?`calc(${u} * -1)`:u)]}let f=e.theme.resolve(l.value.fraction??l.value.value,["--inset","--spacing"]);if(f===null&&l.value.fraction){let[u,c]=j(l.value.fraction,"/");if(!D(u)||!D(c))return;f=`calc(${l.value.fraction} * 100%)`}if(f===null&&o){let u=e.theme.resolve(null,["--spacing"]);if(u&&te(l.value.value)&&(f=`calc(${u} * -${l.value.value})`,f!==null))return[s(t,f)]}if(f===null){let u=e.theme.resolve(null,["--spacing"]);u&&te(l.value.value)&&(f=`calc(${u} * ${l.value.value})`)}if(f!==null)return[s(t,o?`calc(${f} * -1)`:f)]}};var r=n;e.utilities.static(`${i}-auto`,()=>[s(t,"auto")]),e.utilities.static(`${i}-full`,()=>[s(t,"100%")]),e.utilities.static(`-${i}-full`,()=>[s(t,"-100%")]),e.utilities.static(`${i}-px`,()=>[s(t,"1px")]),e.utilities.static(`-${i}-px`,()=>[s(t,"-1px")]),e.utilities.functional(`-${i}`,n({negative:!0})),e.utilities.functional(i,n({negative:!1}))}}function Un(e,r){let i=e.theme.screens||{},t=r.variants.get("min")?.order??0,n=[];for(let[l,f]of Object.entries(i)){let p=function(h){r.variants.static(l,k=>{k.nodes=[H("@media",m,k.nodes)]},{order:h})};var o=p;let u=r.variants.get(l),c=r.theme.resolveValue(l,["--breakpoint"]);if(u&&c&&!r.theme.hasDefault(`--breakpoint-${l}`))continue;let d=!0;typeof f=="string"&&(d=!1);let m=Da(f);d?n.push(p):p(t)}if(n.length!==0){for(let[,l]of r.variants.variants)l.order>t&&(l.order+=n.length);r.variants.compareFns=new Map(Array.from(r.variants.compareFns).map(([l,f])=>(l>t&&(l+=n.length),[l,f])));for(let[l,f]of n.entries())f(t+l+1)}}function Da(e){return(Array.isArray(e)?e:[e]).map(i=>typeof i=="string"?{min:i}:i&&typeof i=="object"?i:null).map(i=>{if(i===null)return null;if("raw"in i)return i.raw;let t="";return i.max!==void 0&&(t+=`${i.max} >= `),t+="width",i.min!==void 0&&(t+=` >= ${i.min}`),`(${t})`}).filter(Boolean).join(", ")}function Ln(e,r){let i=e.theme.aria||{},t=e.theme.supports||{},n=e.theme.data||{};if(Object.keys(i).length>0){let o=r.variants.get("aria"),l=o?.applyFn,f=o?.compounds;r.variants.functional("aria",(u,c)=>{let d=c.value;return d&&d.kind==="named"&&d.value in i?l?.(u,{...c,value:{kind:"arbitrary",value:i[d.value]}}):l?.(u,c)},{compounds:f})}if(Object.keys(t).length>0){let o=r.variants.get("supports"),l=o?.applyFn,f=o?.compounds;r.variants.functional("supports",(u,c)=>{let d=c.value;return d&&d.kind==="named"&&d.value in t?l?.(u,{...c,value:{kind:"arbitrary",value:t[d.value]}}):l?.(u,c)},{compounds:f})}if(Object.keys(n).length>0){let o=r.variants.get("data"),l=o?.applyFn,f=o?.compounds;r.variants.functional("data",(u,c)=>{let d=c.value;return d&&d.kind==="named"&&d.value in n?l?.(u,{...c,value:{kind:"arbitrary",value:n[d.value]}}):l?.(u,c)},{compounds:f})}}var Ua=/^[a-z]+$/;async function zn({designSystem:e,base:r,ast:i,loadModule:t,sources:n}){let o=0,l=[],f=[];I(i,(m,p)=>{if(m.kind!=="at-rule")return;let h=lt(p);if(m.name==="@plugin"){if(h.parent!==null)throw new Error("`@plugin` cannot be nested.");let k=m.params.slice(1,-1);if(k.length===0)throw new Error("`@plugin` must have a path.");let w={};for(let b of m.nodes??[]){if(b.kind!=="declaration")throw new Error(`Unexpected \`@plugin\` option: + +${ce([b])} + +\`@plugin\` options must be a flat list of declarations.`);if(b.value===void 0)continue;let A=b.value,C=j(A,",").map(y=>{if(y=y.trim(),y==="null")return null;if(y==="true")return!0;if(y==="false")return!1;if(Number.isNaN(Number(y))){if(y[0]==='"'&&y[y.length-1]==='"'||y[0]==="'"&&y[y.length-1]==="'")return y.slice(1,-1);if(y[0]==="{"&&y[y.length-1]==="}")throw new Error(`Unexpected \`@plugin\` option: Value of declaration \`${ce([b]).trim()}\` is not supported. + +Using an object as a plugin option is currently only supported in JavaScript configuration files.`)}else return Number(y);return y});w[b.property]=C.length===1?C[0]:C}return l.push([{id:k,base:h.context.base,reference:!!h.context.reference,src:m.src},Object.keys(w).length>0?w:null]),o|=4,V.Replace([])}if(m.name==="@config"){if(m.nodes.length>0)throw new Error("`@config` cannot have a body.");if(h.parent!==null)throw new Error("`@config` cannot be nested.");return f.push({id:m.params.slice(1,-1),base:h.context.base,reference:!!h.context.reference,src:m.src}),o|=4,V.Replace([])}}),Dn(e);let u=e.resolveThemeValue;if(e.resolveThemeValue=function(p,h){return p.startsWith("--")?u(p,h):(o|=Kn({designSystem:e,base:r,ast:i,sources:n,configs:[],pluginDetails:[]}),e.resolveThemeValue(p,h))},!l.length&&!f.length)return 0;let[c,d]=await La(t,f,l);return o|=Kn({designSystem:e,base:r,ast:i,sources:n,configs:c,pluginDetails:d}),o}function La(e,r,i){return Promise.all([Promise.all(r.map(async({id:t,base:n,reference:o,src:l})=>{let f=await e(t,n,"config");return{path:t,base:f.base,config:f.module,reference:o,src:l}})),Promise.all(i.map(async([{id:t,base:n,reference:o,src:l},f])=>{let u=await e(t,n,"plugin");return{path:t,base:u.base,plugin:u.module,options:f,reference:o,src:l}}))])}function Kn({designSystem:e,base:r,ast:i,sources:t,configs:n,pluginDetails:o}){let l=0,u=[...o.map(w=>{if(!w.options)return{config:{plugins:[w.plugin]},base:w.base,reference:w.reference,src:w.src};if("__isOptionsFunction"in w.plugin)return{config:{plugins:[w.plugin(w.options)]},base:w.base,reference:w.reference,src:w.src};throw new Error(`The plugin "${w.path}" does not accept options`)}),...n],{resolvedConfig:c}=Dr(e,[{config:On(e.theme),base:r,reference:!0,src:void 0},...u,{config:{plugins:[In]},base:r,reference:!0,src:void 0}]),{resolvedConfig:d,replacedThemeKeys:m}=Dr(e,u),p={designSystem:e,ast:i,resolvedConfig:c,featuresRef:{set current(w){l|=w}}},h=_r({...p,referenceMode:!1,src:void 0}),k=e.resolveThemeValue;e.resolveThemeValue=function(b,A){if(b[0]==="-"&&b[1]==="-")return k(b,A);let C=h.theme(b,void 0);if(typeof C=="object"&&C!==null&&!Array.isArray(C)&&"DEFAULT"in C&&(C=C.DEFAULT),Array.isArray(C)&&C.length===2)return C[0];if(Array.isArray(C))return C.join(", ");if(typeof C=="string")return C};for(let{handler:w,reference:b,src:A}of c.plugins){let C=_r({...p,referenceMode:b??!1,src:A});w(C)}if(ji(e,d,m),Nn(e,d),Ln(d,e),Un(d,e),_n(d,e),!e.theme.prefix&&c.prefix){if(c.prefix.endsWith("-")&&(c.prefix=c.prefix.slice(0,-1),console.warn(`The prefix "${c.prefix}" is invalid. Prefixes must be lowercase ASCII letters (a-z) only and is written as a variant before all utilities. We have fixed up the prefix for you. Remove the trailing \`-\` to silence this warning.`)),!Ua.test(c.prefix))throw new Error(`The prefix "${c.prefix}" is invalid. Prefixes must be lowercase ASCII letters (a-z) only.`);e.theme.prefix=c.prefix}if(!e.important&&c.important===!0&&(e.important=!0),typeof c.important=="string"){let w=c.important;I(i,(b,A)=>{if(b.kind!=="at-rule"||b.name!=="@tailwind"||b.params!=="utilities")return;let C=lt(A);return C.parent?.kind==="rule"&&C.parent.selector===w?V.Stop:V.ReplaceStop(Q(w,[b]))})}for(let w of c.blocklist)e.invalidCandidates.add(w);for(let w of c.content.files){if("raw"in w)throw new Error(`Error in the config file/plugin/preset. The \`content\` key contains a \`raw\` entry: + +${JSON.stringify(w,null,2)} + +This feature is not currently supported.`);let b=!1;w.pattern[0]=="!"&&(b=!0,w.pattern=w.pattern.slice(1)),t.push({...w,negated:b})}return l}function Mn({ast:e}){let r=new K(n=>bt(n.code)),i=new K(n=>({url:n.file,content:n.code,ignore:!1})),t={file:null,sources:[],mappings:[]};I(e,n=>{if(!n.src||!n.dst)return;let o=i.get(n.src[0]);if(!o.content)return;let l=r.get(n.src[0]),f=r.get(n.dst[0]),u=o.content.slice(n.src[1],n.src[2]),c=0;for(let p of u.split(` +`)){if(p.trim()!==""){let h=l.find(n.src[1]+c),k=f.find(n.dst[1]);t.mappings.push({name:null,originalPosition:{source:o,...h},generatedPosition:k})}c+=p.length,c+=1}let d=l.find(n.src[2]),m=f.find(n.dst[2]);t.mappings.push({name:null,originalPosition:{source:o,...d},generatedPosition:m})});for(let n of r.keys())t.sources.push(i.get(n));return t.mappings.sort((n,o)=>n.generatedPosition.line-o.generatedPosition.line||n.generatedPosition.column-o.generatedPosition.column||(n.originalPosition?.line??0)-(o.originalPosition?.line??0)||(n.originalPosition?.column??0)-(o.originalPosition?.column??0)),t}var jn=/^(-?\d+)\.\.(-?\d+)(?:\.\.(-?\d+))?$/;function Gt(e){let r=e.indexOf("{");if(r===-1)return[e];let i=[],t=e.slice(0,r),n=e.slice(r),o=0,l=n.lastIndexOf("}");for(let m=0;mGt(m));let d=Gt(u);for(let m of d)for(let p of c)i.push(t+p+m);return i}function Ka(e){return jn.test(e)}function za(e){let r=e.match(jn);if(!r)return[e];let[,i,t,n]=r,o=n?parseInt(n,10):void 0,l=[];if(/^-?\d+$/.test(i)&&/^-?\d+$/.test(t)){let f=parseInt(i,10),u=parseInt(t,10);if(o===void 0&&(o=f<=u?1:-1),o===0)throw new Error("Step cannot be zero in sequence expansion.");let c=f0&&(o=-o);for(let d=f;c?d<=u:d>=u;d+=o)l.push(d.toString())}return l}function Fn(e,r){let i=new Set,t=new Set,n=[];function o(l,f=[]){if(e.has(l)&&!i.has(l)){t.has(l)&&r.onCircularDependency?.(f,l),t.add(l);for(let u of e.get(l)??[])f.push(l),o(u,f),f.pop();i.add(l),t.delete(l),n.push(l)}}for(let l of e.keys())o(l);return n}var Ma=/^[a-z]+$/,Et=(n=>(n[n.None=0]="None",n[n.AtProperty=1]="AtProperty",n[n.ColorMix=2]="ColorMix",n[n.All=3]="All",n))(Et||{});function ja(){throw new Error("No `loadModule` function provided to `compile`")}function Fa(){throw new Error("No `loadStylesheet` function provided to `compile`")}function Wa(e){let r=0,i=null;for(let t of j(e," "))t==="reference"?r|=2:t==="inline"?r|=1:t==="default"?r|=4:t==="static"?r|=8:t.startsWith("prefix(")&&t.endsWith(")")&&(i=t.slice(7,-1));return[r,i]}var Ue=(u=>(u[u.None=0]="None",u[u.AtApply=1]="AtApply",u[u.AtImport=2]="AtImport",u[u.JsPluginCompat=4]="JsPluginCompat",u[u.ThemeFunction=8]="ThemeFunction",u[u.Utilities=16]="Utilities",u[u.Variants=32]="Variants",u[u.AtTheme=64]="AtTheme",u))(Ue||{});async function Wn(e,{base:r="",from:i,loadModule:t=ja,loadStylesheet:n=Fa}={}){let o=0;e=[ee({base:r},e)],o|=await Or(e,r,n,0,i!==void 0);let l=null,f=new Vt,u=new Map,c=new Map,d=[],m=null,p=null,h=[],k=[],w=[],b=[],A=null;I(e,(y,E)=>{if(y.kind!=="at-rule")return;let O=lt(E);if(y.name==="@tailwind"&&(y.params==="utilities"||y.params.startsWith("utilities"))){if(p!==null)return V.Replace([]);if(O.context.reference)return V.Replace([]);let P=j(y.params," ");for(let L of P)if(L.startsWith("source(")){let R=L.slice(7,-1);if(R==="none"){A=R;continue}if(R[0]==='"'&&R[R.length-1]!=='"'||R[0]==="'"&&R[R.length-1]!=="'"||R[0]!=="'"&&R[0]!=='"')throw new Error("`source(\u2026)` paths must be quoted.");A={base:O.context.sourceBase??O.context.base,pattern:R.slice(1,-1)}}p=y,o|=16}if(y.name==="@utility"){if(O.parent!==null)throw new Error("`@utility` cannot be nested.");if(y.nodes.length===0)throw new Error(`\`@utility ${y.params}\` is empty. Utilities should include at least one property.`);let P=Di(y);if(P===null){if(!y.params.endsWith("-*")){if(y.params.endsWith("*"))throw new Error(`\`@utility ${y.params}\` defines an invalid utility name. A functional utility must end in \`-*\`.`);if(y.params.includes("*"))throw new Error(`\`@utility ${y.params}\` defines an invalid utility name. The dynamic portion marked by \`-*\` must appear once at the end.`)}throw new Error(`\`@utility ${y.params}\` defines an invalid utility name. Utilities should be alphanumeric and start with a lowercase letter.`)}d.push(P)}if(y.name==="@source"){if(y.nodes.length>0)throw new Error("`@source` cannot have a body.");if(O.parent!==null)throw new Error("`@source` cannot be nested.");let P=!1,L=!1,R=y.params;if(R[0]==="n"&&R.startsWith("not ")&&(P=!0,R=R.slice(4)),R[0]==="i"&&R.startsWith("inline(")&&(L=!0,R=R.slice(7,-1).trim()),R[0]==='"'&&R[R.length-1]!=='"'||R[0]==="'"&&R[R.length-1]!=="'"||R[0]!=="'"&&R[0]!=='"')throw new Error("`@source` paths must be quoted.");let W=R.slice(1,-1);if(L){let U=P?b:w,z=j(W," ");for(let F of z)for(let Z of Gt(F))U.push(Z)}else k.push({base:O.context.base,pattern:W,negated:P});return V.ReplaceSkip([])}if(y.name==="@variant"&&(O.parent===null?y.nodes.length===0?y.name="@custom-variant":(I(y.nodes,P=>{if(P.kind==="at-rule"&&P.name==="@slot")return y.name="@custom-variant",V.Stop}),y.name==="@variant"&&h.push(y)):h.push(y)),y.name==="@custom-variant"){if(O.parent!==null)throw new Error("`@custom-variant` cannot be nested.");let[P,L]=j(y.params," ");if(!Bt.test(P))throw new Error(`\`@custom-variant ${P}\` defines an invalid variant name. Variants should only contain alphanumeric, dashes, or underscore characters and start with a lowercase letter or number.`);if(y.nodes.length>0&&L)throw new Error(`\`@custom-variant ${P}\` cannot have both a selector and a body.`);if(y.nodes.length===0){if(!L)throw new Error(`\`@custom-variant ${P}\` has no selector or body.`);let R=j(L.slice(1,-1),",");if(R.length===0||R.some(F=>F.trim()===""))throw new Error(`\`@custom-variant ${P} (${R.join(",")})\` selector is invalid.`);let W=[],U=[];for(let F of R)F=F.trim(),F[0]==="@"?W.push(F):U.push(F);let z=W.some(F=>F.startsWith("@scope"));u.set(P,F=>{F.variants.static(P,Z=>{let a=z?[ee({source:"user"},Z.nodes)]:Z.nodes,g=[];U.length>0&&g.push(Q(U.join(", "),a));for(let v of W)g.push(J(v,a));Z.nodes=z?[ee({source:"variant"},g)]:g},{compounds:ze([...U,...W])})}),c.set(P,new Set)}else{let R=new Set;I(y.nodes,W=>{W.kind==="at-rule"&&W.name==="@variant"&&R.add(W.params)}),u.set(P,W=>{W.variants.fromAst(P,y.nodes,W)}),c.set(P,R)}return V.ReplaceSkip([])}if(y.name==="@media"){let P=j(y.params," "),L=[];for(let R of P)if(R.startsWith("source(")){let W=R.slice(7,-1);I(y.nodes,U=>{if(U.kind==="at-rule"&&U.name==="@tailwind"&&U.params==="utilities")return U.params+=` source(${W})`,V.ReplaceStop([ee({sourceBase:O.context.base},[U])])})}else if(R.startsWith("theme(")){let W=R.slice(6,-1),U=W.includes("reference");I(y.nodes,z=>{if(z.kind!=="context"){if(z.kind!=="at-rule"){if(U)throw new Error('Files imported with `@import "\u2026" theme(reference)` must only contain `@theme` blocks.\nUse `@reference "\u2026";` instead.');return V.Continue}if(z.name==="@theme")return z.params+=" "+W,V.Skip}})}else if(R.startsWith("prefix(")){let W=R.slice(7,-1);I(y.nodes,U=>{if(U.kind==="at-rule"&&U.name==="@theme")return U.params+=` prefix(${W})`,V.Skip})}else R==="important"?l=!0:R==="reference"?y.nodes=[ee({reference:!0},y.nodes)]:L.push(R);if(L.length>0)y.params=L.join(" ");else if(P.length>0)return V.Replace(y.nodes);return V.Continue}if(y.name==="@theme"){let[P,L]=Wa(y.params);if(o|=64,O.context.reference&&(P|=2),L){if(!Ma.test(L))throw new Error(`The prefix "${L}" is invalid. Prefixes must be lowercase ASCII letters (a-z) only.`);f.prefix=L}return I(y.nodes,R=>{if(R.kind==="at-rule"&&R.name==="@keyframes")return f.addKeyframes(R),V.Skip;if(R.kind==="comment")return;if(R.kind==="declaration"&&R.property.startsWith("--")){f.add(Ae(R.property),R.value??"",P,R.src);return}let W=ce([H(y.name,y.params,[R])]).split(` +`).map((U,z,F)=>`${z===0||z>=F.length-2?" ":">"} ${U}`).join(` +`);throw new Error(`\`@theme\` blocks must only contain custom properties or \`@keyframes\`. + +${W}`)}),m?V.ReplaceSkip([]):(m=Q(":root, :host",[]),m.src=y.src,V.ReplaceSkip(m))}});let C=bn(f,p?.src);if(l&&(C.important=l),b.length>0)for(let y of b)C.invalidCandidates.add(y);o|=await zn({designSystem:C,base:r,ast:e,loadModule:t,sources:k});for(let y of u.keys())C.variants.static(y,()=>{});for(let y of Fn(c,{onCircularDependency(E,O){let P=ce(E.map((L,R)=>H("@custom-variant",L,[H("@variant",E[R+1]??O,[])]))).replaceAll(";"," { \u2026 }").replace(`@custom-variant ${O} {`,`@custom-variant ${O} { /* \u2190 */`);throw new Error(`Circular dependency detected in custom variants: + +${P}`)}}))u.get(y)?.(C);for(let y of d)y(C);if(m){let y=[];for(let[O,P]of C.theme.entries()){if(P.options&2)continue;let L=s(Te(O),P.value);L.src=P.src,y.push(L)}let E=C.theme.getKeyframes();for(let O of E)e.push(ee({theme:!0},[G([O])]));m.nodes=[ee({theme:!0},y)]}if(o|=mt(e,C),o|=He(e,C),o|=Ee(e,C),p){let y=p;y.kind="context",y.context={}}return I(e,y=>{if(y.kind==="at-rule")return y.name==="@utility"?V.Replace([]):V.Skip}),{designSystem:C,ast:e,sources:k,root:A,utilitiesNode:p,features:o,inlineCandidates:w}}async function Bn(e,r={}){let{designSystem:i,ast:t,sources:n,root:o,utilitiesNode:l,features:f,inlineCandidates:u}=await Wn(e,r);t.unshift(St(`! tailwindcss v${Ur} | MIT License | https://tailwindcss.com `));function c(b){i.invalidCandidates.add(b)}let d=new Set,m=null,p=0,h=!1;for(let b of u)i.invalidCandidates.has(b)||(d.add(b),h=!0);let{from:k,polyfills:w}=r;return{sources:n,root:o,features:f,build(b){if(f===0)return e;if(!l)return m??=Ie(t,i,w),m;let A=h,C=!1;h=!1;let y=d.size;for(let O of b)if(!i.invalidCandidates.has(O))if(O[0]==="-"&&O[1]==="-"){let P=i.theme.markUsedVariable(O);A||=P,C||=P}else d.add(O),A||=d.size!==y;if(!A)return m??=Ie(t,i,w),m;let E=Re(d,i,{onInvalidCandidate:c}).astNodes;return k&&I(E,O=>{O.src??=l.src}),!C&&p===E.length?(m??=Ie(t,i,w),m):(p=E.length,l.nodes=E,m=Ie(t,i,w),m)}}}async function Ba(e,r={}){let i=_e(e,{from:r.from}),t=await Bn(i,r),n=i,o=e,l=r.from;return{...t,build(f){let u=t.build(f);return u===n||(o=ce(u,!!l),n=u),o},buildSourceMap(){return Mn({ast:n})}}}async function Ya(e,r={}){return(await Wn(_e(e,{from:r.from}),r)).designSystem}function ht(){throw new Error("It looks like you're trying to use `tailwindcss` directly as a PostCSS plugin. The PostCSS plugin has moved to a separate package, so to continue using Tailwind CSS with PostCSS you'll need to install `@tailwindcss/postcss` and update your PostCSS configuration.")}for(let e in Zt)e!=="default"&&(ht[e]=Zt[e]);module.exports=ht; diff --git a/dg-ui/node_modules/tailwindcss/dist/lib.mjs b/dg-ui/node_modules/tailwindcss/dist/lib.mjs new file mode 100644 index 0000000..7d7cfb7 --- /dev/null +++ b/dg-ui/node_modules/tailwindcss/dist/lib.mjs @@ -0,0 +1,38 @@ +import{a as F,b as ft,c as Cr,d as X,e as He,f as U,g as Lt,h as te,i as xe,j as Vr}from"./chunk-JYLR5UAN.mjs";import{a as Sr}from"./chunk-DCG7AFIE.mjs";import{a as Oe,b as _e,c as Ar}from"./chunk-3IIMCCN4.mjs";var $r="4.3.5";function Sn(e){return{kind:"combinator",value:e}}function zt(e){return{kind:"complex",nodes:e}}function Tr(e){return{kind:"compound",nodes:e}}function Vn(e,i){return{kind:"function",value:e,nodes:i}}function $n(e){return{kind:"list",nodes:e}}function be(e){return{kind:"selector",value:e}}function Nr(e){return{kind:"value",value:e}}function Ze(e){return e.kind==="selector"&&e.value.charCodeAt(0)===Yt}var Tn=new Set([":before",":after",":first-line",":first-letter"]);function ct(e){return e.kind!=="selector"&&e.kind!=="function"?!1:e.value.startsWith("::")||Tn.has(e.value.toLowerCase())}function pt(e){if(e.kind!=="selector")return!1;switch(e.value.charCodeAt(0)){case Yt:case Lr:case Kr:case Ur:case Wt:case Bt:return!1;default:return!0}}function se(e,i=!1){let r="";for(let t of e)switch(t.kind){case"selector":case"value":{r+=t.value;break}case"combinator":{i||t.value===" "?r+=t.value:r+=` ${t.value} `;break}case"function":{r+=`${t.value}(${se(t.nodes,i)})`;break}case"complex":case"compound":{r+=se(t.nodes,i);break}case"list":{r+=t.nodes.map(n=>se([n],i)).join(i?",":", ");break}}return r}var Er=92,Nn=93,Rr=41,Wt=58,Pr=44,En=34,Kr=46,Or=62,Mt=10,Ur=35,Bt=91,_r=40,Ir=43,Rn=39,jt=32,Ft=9,Dr=126,Lr=38,Yt=42;function ce(e){e=e.replaceAll(`\r +`,` +`);let i=[],r=i,t=!1,n=[],s=null,l="",p;function u(d=r){return d.length===1?d[0]:t?zt(d):Tr(d)}function c(d){let m=r[r.length-1];m?.kind==="compound"?m.nodes.push(d):m&&m.kind!=="list"&&m.kind!=="combinator"?r[r.length-1]=Tr([m,d]):r.push(d)}for(let d=0;d0&&(c(be(l)),l="");d+10&&(c(be(l)),l="");let f=d,h=d+1;for(;h=e.length||e.charCodeAt(h)===Pr))break;r.push(Sn(w===""?" ":w)),t=!0;break}case _r:{let f=Vn(l,[]);if(l="",f.value!==":not"&&f.value!==":where"&&f.value!==":has"&&f.value!==":is"&&f.value!==":-moz-any"&&f.value!==":-webkit-any"){let h=d+1,w=0;for(let A=d+1;A0&&(c(be(l)),l=""),s?s.nodes.push(u()):t&&r.splice(0,r.length,zt(r.splice(0)));let f=n.pop();r=f?.target??i,s=f?.currentList??null,t=f?.containsCombinator??!1;break}case Kr:case Wt:case Ur:{if(m===Wt&&l===":"){l+=e[d];break}l.length>0&&c(be(l)),l=e[d];break}case Bt:{l.length>0&&(c(be(l)),l="");let f=d,h=0;for(let w=d+1;w0&&(c(be(l)),l=""),c(be(e[d]));break}case Er:{l+=e[d]+e[d+1],d+=1;break}default:l+=e[d]}}return l.length>0&&c(be(l)),s?s.nodes.push(u()):t&&r.splice(0,r.length,zt(r.splice(0))),i}function dt(e){let i=[0];for(let n=0;n0;){let u=(l|0)>>1,c=s+u;i[c]<=n?(s=c+1,l=l-u-1):l=u}s-=1;let p=n-i[s];return{line:s+1,column:p}}function t({line:n,column:s}){n-=1,n=Math.min(Math.max(n,0),i.length-1);let l=i[n],p=i[n+1]??l;return Math.min(Math.max(l+s,0),p)}return{find:r,findOffset:t}}var wt=92,mt=47,gt=42,zr=34,Mr=39,Pn=58,vt=59,pe=10,Je=13,Ie=32,De=9,jr=123,qt=125,Jt=40,Fr=41,On=91,_n=93,Ve=45,Ht=64,Wr=33,In=60,Dn=62,he=class e extends Error{loc;constructor(i,r){if(r){let t=r[0],n=dt(t.code).find(r[1]);i=`${t.file}:${n.line}:${n.column+1}: ${i}`}super(i),this.name="CssSyntaxError",this.loc=r,Error.captureStackTrace&&Error.captureStackTrace(this,e)}};function $e(e,i){let r=i?.from?{file:i.from,code:e}:null;e[0]==="\uFEFF"&&(e=" "+e.slice(1));let t=[],n=[],s=[],l=null,p=null,u="",c="",d=0,m;for(let f=0;f0&&e[y]===w[w.length-1]&&(w=w.slice(0,-1));m!==Ie&&m!==De&&m!==pe&&m!==Je&&(A=y+1-b)}u.length===0&&(u=e.slice(b),f=e.length);let C=ht(u,k,A);if(!C)throw new he("Invalid custom property, expected a value",r?[r,b,f]:null);r&&(C.src=[r,b,f],C.dst=[r,b,f]),l?l.nodes.push(C):t.push(C),u=""}else if(h===vt&&u.charCodeAt(0)===Ht)p=Qe(u),r&&(p.src=[r,d,f],p.dst=[r,d,f]),l?l.nodes.push(p):t.push(p),u="",p=null;else if(h===vt&&c[c.length-1]!==")"){let w=ht(u);if(!w){if(u.length===0)continue;throw new he(`Invalid declaration: \`${u.trim()}\``,r?[r,d,f]:null)}r&&(w.src=[r,d,f],w.dst=[r,d,f]),l?l.nodes.push(w):t.push(w),u=""}else if(h===jr&&c[c.length-1]!==")")c+="}",p=Q(u.trim()),r&&(p.src=[r,d,f],p.dst=[r,d,f]),l&&l.nodes.push(p),s.push(l),l=p,u="",p=null;else if(h===qt&&c[c.length-1]!==")"){if(c==="")throw new he("Missing opening {",r?[r,f,f]:null);if(c=c.slice(0,-1),u.length>0)if(u.charCodeAt(0)===Ht)p=Qe(u),r&&(p.src=[r,d,f],p.dst=[r,d,f]),l?l.nodes.push(p):t.push(p),u="",p=null;else{let b=u.indexOf(":");if(l){let k=ht(u,b);if(!k)throw new he(`Invalid declaration: \`${u.trim()}\``,r?[r,d,f]:null);r&&(k.src=[r,d,f],k.dst=[r,d,f]),l.nodes.push(k)}}let w=s.pop()??null;w===null&&l&&t.push(l),l=w,u="",p=null}else if(h===Jt)c+=")",u+="(";else if(h===Fr){if(c[c.length-1]!==")")throw new he("Missing opening (",r?[r,f,f]:null);c=c.slice(0,-1),u+=")"}else{if(u.length===0&&(h===Ie||h===pe||h===De))continue;u===""&&(d=f),u+=String.fromCharCode(h)}}}if(u.charCodeAt(0)===Ht){let f=Qe(u);r&&(f.src=[r,d,e.length],f.dst=[r,d,e.length]),t.push(f)}else if(u.length>0&&c.length===0){let f=ht(u);f&&(r&&(f.src=[r,d,e.length],f.dst=[r,d,e.length]),l?l.nodes.push(f):t.push(f))}if(c.length>0&&l){if(l.kind==="rule")throw new he(`Missing closing } at ${l.selector}`,l.src?[l.src[0],l.src[1],l.src[1]]:null);if(l.kind==="at-rule")throw new he(`Missing closing } at ${l.name} ${l.params}`,l.src?[l.src[0],l.src[1],l.src[1]]:null)}return n.length>0?n.concat(t):t}function Qe(e,i=[]){let r=e,t="";for(let n=5;n0){let c=re(n);t?t.nodes.push(c):i.push(c),n=""}let u=re(e[l]);t?t.nodes.push(u):i.push(u);break}case qr:case Hr:case Zr:case Jr:case Qr:case Xr:case ei:case ti:{if(n.length>0){let m=re(n);t?t.nodes.push(m):i.push(m),n=""}let u=l,c=l+1;for(;c0){let c=re(n);u?.nodes.push(c),n=""}r.length>0?t=r[r.length-1]:t=null;break}default:n+=String.fromCharCode(p)}}return n.length>0&&i.push(re(n)),i}var Xt=(l=>(l[l.Continue=0]="Continue",l[l.Skip=1]="Skip",l[l.Stop=2]="Stop",l[l.Replace=3]="Replace",l[l.ReplaceSkip=4]="ReplaceSkip",l[l.ReplaceStop=5]="ReplaceStop",l))(Xt||{}),V={Continue:{kind:0},Skip:{kind:1},Stop:{kind:2},Replace:e=>({kind:3,nodes:Array.isArray(e)?e:[e]}),ReplaceSkip:e=>({kind:4,nodes:Array.isArray(e)?e:[e]}),ReplaceStop:e=>({kind:5,nodes:Array.isArray(e)?e:[e]})};function I(e,i){typeof i=="function"?ri(e,i):ri(e,i.enter,i.exit)}function ri(e,i=()=>V.Continue,r=()=>V.Continue){let t={value:[e,0,null],prev:null},n={parent:null,depth:0,index:0,siblings:e,path(){let s=[],l=t;for(;l;){let p=l.value[2];p&&s.push(p),l=l.prev}return s.reverse(),s}};for(;t!==null;){let s=t.value,l=s[0],p=s[1],u=s[2];if(p>=l.length){t=t.prev,n.depth-=1;continue}if(n.parent=u,n.siblings=l,p>=0){n.index=p;let f=l[p],h=i(f,n)??V.Continue;switch(h.kind){case 0:{f.nodes&&f.nodes.length>0&&(n.depth+=1,t={value:[f.nodes,0,f],prev:t}),s[1]=~p;continue}case 2:return;case 1:{s[1]=~p;continue}case 3:{l.splice(p,1,...h.nodes);continue}case 5:{l.splice(p,1,...h.nodes);return}case 4:{l.splice(p,1,...h.nodes),s[1]+=h.nodes.length;continue}default:throw new Error(`Invalid \`WalkAction.${Xt[h.kind]??`Unknown(${h.kind})`}\` in enter.`)}}let c=~p;n.index=c;let d=l[c],m=r(d,n)??V.Continue;switch(m.kind){case 0:s[1]=c+1;continue;case 2:return;case 3:{l.splice(c,1,...m.nodes),s[1]=c+m.nodes.length;continue}case 5:{l.splice(c,1,...m.nodes);return}case 4:{l.splice(c,1,...m.nodes),s[1]=c+m.nodes.length;continue}default:throw new Error(`Invalid \`WalkAction.${Xt[m.kind]??`Unknown(${m.kind})`}\` in exit.`)}}}var Wn=new L(e=>{let i=[];return I(Y(e),r=>{if(!(r.kind!=="function"||r.value!=="var"))return I(r.nodes,t=>{t.kind!=="word"||t.value[0]!=="-"||t.value[1]!=="-"||i.push(t.value)}),V.Skip}),i});function bt(e){return Wn.get(e)}var Bn=64,Yn=124;function J(e,i=[]){return{kind:"rule",selector:e,nodes:i}}function q(e,i="",r=[]){return{kind:"at-rule",name:e,params:i,nodes:r}}function Q(e,i=[]){return e.charCodeAt(0)===Bn?Qe(e,i):J(e,i)}function o(e,i,r=!1){return{kind:"declaration",property:e,value:i,important:r}}function kt(e){return{kind:"comment",value:e}}function ee(e,i){return{kind:"context",context:e,nodes:i}}function H(e){return{kind:"at-root",nodes:e}}function le(e){switch(e.kind){case"rule":return{kind:e.kind,selector:e.selector,nodes:e.nodes.map(le),src:e.src,dst:e.dst};case"at-rule":return{kind:e.kind,name:e.name,params:e.params,nodes:e.nodes.map(le),src:e.src,dst:e.dst};case"at-root":return{kind:e.kind,nodes:e.nodes.map(le),src:e.src,dst:e.dst};case"context":return{kind:e.kind,context:{...e.context},nodes:e.nodes.map(le),src:e.src,dst:e.dst};case"declaration":return{kind:e.kind,property:e.property,value:e.value,important:e.important,src:e.src,dst:e.dst};case"comment":return{kind:e.kind,value:e.value,src:e.src,dst:e.dst};default:throw new Error(`Unknown node kind: ${e.kind}`)}}function et(e){return{depth:e.depth,index:e.index,siblings:e.siblings,get context(){let i={};for(let r of e.path())r.kind==="context"&&Object.assign(i,r.context);return Object.defineProperty(this,"context",{value:i}),i},get parent(){let i=this.path().pop()??null;return Object.defineProperty(this,"parent",{value:i}),i},path(){return e.path().filter(i=>i.kind!=="context")}}}function Te(e,i,r=3){let t=[],n=new Set,s=new L(()=>new Set),l=new L(()=>new Set),p=new Set,u=new Set,c=[],d=[],m=new L(()=>new Set);function f(w,b,k={},A=0){if(w.kind==="declaration"){if(w.property==="--tw-sort"||w.value===void 0||w.value===null)return;if(k.theme&&w.property[0]==="-"&&w.property[1]==="-"){if(w.value==="initial"){w.value=void 0;return}k.keyframes||s.get(b).add(w)}if(w.value.includes("var("))if(k.theme&&w.property[0]==="-"&&w.property[1]==="-")for(let C of bt(w.value))m.get(C).add(w.property);else i.trackUsedVariables(w.value);if(w.property==="animation")for(let C of ni(w.value))u.add(C);r&2&&!k.supportsColorMix&&!k.keyframes&&w.value.includes("color-mix(")&&l.get(b).add(w),b.push(w)}else if(w.kind==="rule"){let C=[];for(let y of w.nodes)f(y,C,k,A+1);C.length>0&&b.push({...w,nodes:C})}else if(w.kind==="at-rule"&&w.name==="@property"&&A===0){if(n.has(w.params))return;if(r&1){let y=w.params,E=null,O=!1;for(let K of w.nodes)K.kind==="declaration"&&(K.property==="initial-value"?E=K.value:K.property==="inherits"&&(O=K.value==="true"));let P=o(y,E??"initial");P.src=w.src,O?c.push(P):d.push(P)}n.add(w.params);let C={...w,nodes:[]};for(let y of w.nodes)f(y,C.nodes,k,A+1);b.push(C)}else if(w.kind==="at-rule"){w.name==="@keyframes"?k={...k,keyframes:!0}:w.name==="@supports"&&w.params.includes("color-mix(")&&(k={...k,supportsColorMix:!0});let C={...w,nodes:[]};for(let y of w.nodes)f(y,C.nodes,k,A+1);w.name==="@keyframes"&&k.theme&&p.add(C),(C.nodes.length>0||C.name==="@layer"||C.name==="@charset"||C.name==="@custom-media"||C.name==="@namespace"||C.name==="@import"||C.name==="@apply")&&b.push(C)}else if(w.kind==="at-root")for(let C of w.nodes){let y=[];f(C,y,k,0);for(let E of y)t.push(E)}else if(w.kind==="context"){if(w.context.reference)return;if(w.context.source){let C={...w,nodes:[]};for(let y of w.nodes)f(y,C.nodes,{...k,...w.context},A);C.nodes.length>0&&b.push(C)}else for(let C of w.nodes)f(C,b,{...k,...w.context},A)}else w.kind==="comment"&&b.push(w)}let h=[];for(let w of e)f(w,h,{},0);e:for(let[w,b]of s)for(let k of b){if(ai(k.property,i.theme,m)){if(k.property.startsWith(i.theme.prefixKey("--animate-")))for(let y of ni(k.value))u.add(y);continue}let C=w.indexOf(k);if(w.splice(C,1),w.length===0){let y=Hn(h,E=>E.kind==="rule"&&E.nodes===w);if(!y||y.length===0)continue e;y.unshift({kind:"at-root",nodes:h});do{let E=y.pop();if(!E)break;let O=y[y.length-1];if(!O||O.kind!=="at-root"&&O.kind!=="at-rule")break;let P=O.nodes.indexOf(E);if(P===-1)break;O.nodes.splice(P,1)}while(!0);continue e}}for(let w of p)if(!u.has(w.params)){let b=t.indexOf(w);t.splice(b,1)}if(h=h.concat(t),r&2)for(let[w,b]of l)for(let k of b){let A=w.indexOf(k);if(A===-1||k.value==null)continue;let C=Y(k.value),y=!1;if(I(C,P=>{if(P.kind!=="function"||P.value!=="color-mix")return;let K=B(P.nodes);if(K.includes("/*")&&(K=K.replace(/\/\*[\s\S]*?\*\//g," "),P.nodes=Y(K)),!/^in\s/i.test(K.trimStart()))return;let R=!1,W=!1;if(I(P.nodes,D=>{if(D.kind=="word"&&D.value.toLowerCase()==="currentcolor"){W=!0,y=!0;return}let z=D,j=null,Z=new Set;do{if(z.kind!=="function"||z.value!=="var")return;let a=z.nodes[0];if(!a||a.kind!=="word")return;let g=a.value;if(Z.has(g)){R=!0;return}if(Z.add(g),y=!0,j=i.theme.resolveValue(null,[a.value]),!j){R=!0;return}if(j.toLowerCase()==="currentcolor"){W=!0;return}j.startsWith("var(")?z=Y(j)[0]:z=null}while(z);return V.Replace({kind:"word",value:j})}),R||W){let D=P.nodes.findIndex(j=>j.kind==="separator"&&j.value.trim().includes(","));if(D===-1)return;let z=P.nodes.length>D?P.nodes[D+1]:null;return z?V.Replace(z):void 0}else if(y){let D=P.nodes[P.nodes.findIndex(z=>z.kind!=="separator")+2];D?.kind==="word"&&(D.value==="oklab"||D.value==="oklch"||D.value==="lab"||D.value==="lch")&&(D.value="srgb")}}),!y)continue;let E={...k,value:B(C)},O=Q("@supports (color: color-mix(in lab, red, red))",[k]);O.src=k.src,w.splice(A,1,E,O)}if(r&1){let w=[];if(c.length>0){let b=Q(":root, :host",c);b.src=c[0].src,w.push(b)}if(d.length>0){let b=Q("*, ::before, ::after, ::backdrop",d);b.src=d[0].src,w.push(b)}if(w.length>0){let b=h.findIndex(C=>!(C.kind==="comment"||C.kind==="at-rule"&&(C.name==="@charset"||C.name==="@import"))),k=q("@layer","properties",[]);k.src=w[0].src,h.splice(b<0?h.length:b,0,k);let A=Q("@layer properties",[q("@supports","((-webkit-hyphens: none) and (not (margin-trim: block))) or ((-moz-orient: inline) and (not (color:rgb(from red r g b))))",w)]);A.src=w[0].src,A.nodes[0].src=w[0].src,h.push(A)}}return Gn(h)}function Gn(e){let i=new L(ce),r=new Set;{let k=function(A){let C=!1;for(let y of A)y.kind==="declaration"||y.kind==="comment"||(k(y.nodes)||y.kind==="at-rule"&&y.name==="@scope")&&(r.add(y),C=!0);return C};var b=k;k(e)}let t=[],n=[],s=null,l=new Set,p=new Set,u=[],c=new Set,d=[],m=new Map,f=new WeakSet;I(e,{enter(k){switch(k.kind){case"rule":{if(s=null,t.length===0)if(k.selector.includes("&")){let A=n.some(([E])=>E==="@scope")?":where(:scope)":":scope",C=ce(k.selector),y=!1;I(C,E=>{E.kind==="selector"&&E.value==="&"&&(y=!0,E.value=A)}),y?t.push([se(C),k.src,k.dst]):t.push([k.selector,k.src,k.dst])}else t.push([k.selector,k.src,k.dst]);else{if(k.selector==="&"){c.add(k);return}let A=t[t.length-1][0],C=F(k.selector,",").map(E=>w(E,A)),y=C.filter(E=>!er(i.get(E)));if(y.length===0){let E=[C.join(", "),k.src,k.dst];f.add(E),t.push(E);break}t.push([y.join(", "),k.src,k.dst])}if(k.nodes.some(A=>A.kind==="declaration")&&!r.has(k)){for(let A of k.nodes)h(A);return V.Skip}break}case"at-rule":{s=null;{let A=t[t.length-1];if(A&&f.has(A)){if(k.name==="@layer"&&k.nodes.length===0){let C=t;return t=[],h(k),t=C,c.add(k),V.Skip}if(k.nodes.length===0||!ii.has(k.name))return c.add(k),V.Skip}}if(k.nodes.length===0&&!qn.has(k.name))return h(k),c.add(k),V.Skip;if(ii.has(k.name)){let A=k.params;if(k.name==="@scope"){let C=d[d.length-1]==="variant",y=t.length>0;{let E=[k];for(let O of E){let P=[],K=null;for(let R of O.nodes)R.kind==="context"&&E.push(R),R.kind==="declaration"||R.kind==="comment"?(K===null&&(K=[],P.push(J("&",K))),K.push(R)):(K=null,P.push(R));O.nodes=P}}if(A.includes("&")||!C&&y){let E=y?t[t.length-1][0]:null,O=Y(A),P=!1,K=!1,R=null;for(let W of O){if(W.kind==="word"&&W.value==="to"){P=!0;continue}if(W.kind!=="function"||W.value!=="")continue;let D=B(W.nodes);if(!P&&!C&&E!==null)W.nodes=[re(F(D,",").map(z=>w(z.trim(),E)).join(", "))],K=!0;else if(D.includes("&")){let z=P?":where(:scope)":E??":scope";W.nodes=[re(w(D,z))],!P&&y&&(K=!0)}P||(R=B(W.nodes))}if(A=B(O),K&&R!==null){let W=t[t.length-1];if(W&&f.has(W)&&er(i.get(R)))return c.add(k),V.Skip}K&&(m.set(k,t),t=[])}}n.push([k.name,A,k.src,k.dst])}else return h(k),c.add(k),V.Skip;break}case"declaration":case"comment":{let A=t[t.length-1];if(A&&f.has(A))break;h(k);break}case"context":k.context.source&&d.push(k.context.source);break;case"at-root":break;default:break}},exit(k){if(!c.delete(k))switch(k.kind){case"rule":{s=null,t.pop();break}case"at-rule":{s=null,n.pop();let A=m.get(k);A&&(t=A,m.delete(k));break}case"context":k.context.source&&d.pop();break;case"declaration":case"comment":case"at-root":break;default:break}}});for(let k of p){let A=new Set;for(let C=k.length-1;C>=0;--C){let y=k[C];if(y.kind!=="declaration")continue;let E=`${y.property}\0${y.value}\0${y.important}`;A.has(E)?k.splice(C,1):A.add(E)}}return u;function h(k){if(s){k.kind==="declaration"&&(l.has(k.property)?p.add(s):l.add(k.property)),s.push(k);return}{if(t.length===0&&n.length===0){let E=u,O=E[E.length-1];if(O&&O.kind==="at-rule"&&k.kind==="at-rule"&&O.nodes.length===0&&k.nodes.length===0&&O.name===k.name&&O.params===k.params)return;u.push(k);return}s=[k],l.clear(),k.kind==="declaration"&&l.add(k.property);let A=null,C=u,y=0;{let E=C[C.length-1];if(E&&E.kind==="at-rule")for(let O=0;O0){let[E,O,P]=t[t.length-1];if(n.length-y<=0){let K=C[C.length-1];if(K&&K.kind==="rule"&&K.selector===E){K.nodes.push(...s),s=K.nodes,p.add(s);return}}A=Q(E,s),(O||P)&&Object.assign(A,{src:O,dst:P})}for(let E=n.length-1;E>=y;--E){let[O,P,K,R]=n[E];A=q(O,P,A?[A]:s),(K||R)&&Object.assign(A,{src:K,dst:R})}A?C.push(A):C.push(...s)}}function w(k,A){if(k.includes("&")){let y=ce(k),E=!1;if(I(y,{enter(O,P){if(O.kind!=="selector"||O.value!=="&"||(E=!0,O.value=`:is(${A})`,P.parent===null))return;let K=i.get(A);if(!(K.length===1&&K[0].kind==="list")){if(P.parent.kind==="complex")if(P.index===0){O.value=A;return}else if(P.index===P.siblings.length-1){if(K[0].kind==="complex")return;O.value=A;return}else{if(K[0].kind==="complex")return;O.value=A;return}else if(P.parent.kind==="compound"){if(K[0].kind==="complex"){let R=P.path(),W=R[R.length-2];if(W&&W.kind==="complex"&&W.nodes[0]!==P.parent)return}if(P.siblings.slice(P.index+1).some(R=>Ze(R)||pt(R)))return;if(P.index===0){O.value=A;return}else if(P.index===P.siblings.length-1){if(K[0].kind==="complex"||Ze(K[0])||pt(K[0]))return;O.value=A;return}else{if(K[0].kind==="complex"||Ze(K[0])||pt(K[0]))return;O.value=A;return}}else if(P.parent.kind==="function"){O.value=A;return}}},exit(O,P){if(P.index===0&&P.siblings.length>1&&P.parent?.kind==="compound"&&Ze(O)){let K=P.siblings[1];return K.kind==="selector"&&K.value.charCodeAt(0)===Yn?void 0:V.ReplaceSkip([])}}}),E)return se(y)}let C=i.get(A);return`${C.length===1&&C[0].kind==="list"?`:is(${A})`:A} ${k}`}}var ii=new Set(["@container","@layer","@media","@page","@scope","@starting-style","@supports","@view-transition"]),qn=new Set(["@container","@media","@page","@scope","@starting-style","@supports","@view-transition"]);function ue(e,i){let r=0,t={file:null,code:""};function n(l,p=0){let u="",c=" ".repeat(p);if(l.kind==="declaration"){if(u+=`${c}${l.property}: ${l.value}${l.important?" !important":""}; +`,i){r+=c.length;let d=r;r+=l.property.length,r+=2,r+=l.value?.length??0,l.important&&(r+=11);let m=r;r+=2,l.dst=[t,d,m]}}else if(l.kind==="rule"){if(u+=`${c}${l.selector} { +`,i){r+=c.length;let d=r;r+=l.selector.length,r+=1;let m=r;l.dst=[t,d,m],r+=2}for(let d of l.nodes)u+=n(d,p+1);u+=`${c}} +`,i&&(r+=c.length,r+=2)}else if(l.kind==="at-rule"){if(l.nodes.length===0){let d=`${c}${l.name} ${l.params}; +`;if(i){r+=c.length;let m=r;r+=l.name.length,r+=1,r+=l.params.length;let f=r;r+=2,l.dst=[t,m,f]}return d}if(u+=`${c}${l.name}${l.params?` ${l.params} `:" "}{ +`,i){r+=c.length;let d=r;r+=l.name.length,l.params&&(r+=1,r+=l.params.length),r+=1;let m=r;l.dst=[t,d,m],r+=2}for(let d of l.nodes)u+=n(d,p+1);u+=`${c}} +`,i&&(r+=c.length,r+=2)}else if(l.kind==="comment"){if(u+=`${c}/*${l.value}*/ +`,i){r+=c.length;let d=r;r+=2+l.value.length+2;let m=r;l.dst=[t,d,m],r+=1}}else if(l.kind==="context"||l.kind==="at-root")return"";return u}let s="";for(let l of e)s+=n(l,0);return t.code=s,s}function Hn(e,i){let r=[];return I(e,(t,n)=>{if(i(t))return r=n.path(),r.push(t),V.Stop}),r}function ai(e,i,r,t=new Set){if(t.has(e)||(t.add(e),i.getOptions(e)&24))return!0;{let s=r.get(e)??[];for(let l of s)if(ai(l,i,r,t))return!0}return!1}function ni(e){return e.split(/[\s,]+/)}function er(e){return e.length>0&&e.every(yt)}var Zn=new Set(["::after","::backdrop","::before","::checkmark","::column","::cue","::cue-region","::details-content","::file-selector-button","::first-letter","::first-line","::grammar-error","::highlight","::marker","::part","::picker","::picker-icon","::placeholder","::scroll-button","::scroll-marker","::scroll-marker-group","::search-text","::selection","::slotted","::spelling-error","::target-text","::view-transition","::view-transition-group","::view-transition-group-children","::view-transition-image-pair","::view-transition-new","::view-transition-old"]);function li(e){if(e.kind!=="selector"&&e.kind!=="function"||!ct(e))return!1;let i=e.value.toLowerCase();return!i.startsWith("::")||i.startsWith("::-")?!0:Zn.has(i)}function yt(e){switch(e.kind){case"list":return e.nodes.every(yt);case"complex":for(let i=0;i0&&n===nr[i-1])i--;else if(n!==125)return!1;break;case 59:if(i===0)return!1;break}}return i===0}var Qn=58,oi=45,si=97,ui=122,or=/^[a-zA-Z0-9_.%-]+$/;function ze(e){switch(e.kind){case"arbitrary":return{kind:e.kind,property:e.property,value:e.value,modifier:e.modifier?{kind:e.modifier.kind,value:e.modifier.value}:null,variants:e.variants.map(Ue),important:e.important,raw:e.raw};case"static":return{kind:e.kind,root:e.root,variants:e.variants.map(Ue),important:e.important,raw:e.raw};case"functional":return{kind:e.kind,root:e.root,value:e.value?e.value.kind==="arbitrary"?{kind:e.value.kind,dataType:e.value.dataType,value:e.value.value}:{kind:e.value.kind,value:e.value.value,fraction:e.value.fraction}:null,modifier:e.modifier?{kind:e.modifier.kind,value:e.modifier.value}:null,variants:e.variants.map(Ue),important:e.important,raw:e.raw};default:throw new Error("Unknown candidate kind")}}function Ue(e){switch(e.kind){case"arbitrary":return{kind:e.kind,selector:e.selector,relative:e.relative};case"static":return{kind:e.kind,root:e.root};case"functional":return{kind:e.kind,root:e.root,value:e.value?{kind:e.value.kind,value:e.value.value}:null,modifier:e.modifier?{kind:e.modifier.kind,value:e.modifier.value}:null};case"compound":return{kind:e.kind,root:e.root,variant:Ue(e.variant),modifier:e.modifier?{kind:e.modifier.kind,value:e.modifier.value}:null};default:throw new Error("Unknown variant kind")}}function*fi(e,i){let r=F(e,":");if(i.theme.prefix){if(r.length===1||r[0]!==i.theme.prefix)return null;r.shift()}let t=r.pop(),n=[];for(let m=r.length-1;m>=0;--m){let f=i.parseVariant(r[m]);if(f===null)return;n.push(f)}let s=!1;t[t.length-1]==="!"?(s=!0,t=t.slice(0,-1)):t[0]==="!"&&(s=!0,t=t.slice(1)),i.utilities.has(t,"static")&&!t.includes("[")&&(yield{kind:"static",root:t,variants:n,important:s,raw:e});let l=F(t,"/");if(l.length>2)return;let[p,u=null]=l,c=u===null?null:lr(u);if(u!==null&&c===null)return;if(p[0]==="["){if(p[p.length-1]!=="]")return;let m=p.charCodeAt(1);if(m!==oi&&!(m>=si&&m<=ui))return;p=p.slice(1,-1);let f=p.indexOf(":");if(f===-1||f===0||f===p.length-1)return;let h=p.slice(0,f),w=Le(p.slice(f+1));if(w===null)return;yield{kind:"arbitrary",property:h,value:w,modifier:c,variants:n,important:s,raw:e};return}let d;if(p[p.length-1]==="]"){let m=p.indexOf("-[");if(m===-1)return;let f=p.slice(0,m);if(!i.utilities.has(f,"functional"))return;let h=p.slice(m+1);d=[[f,h]]}else if(p[p.length-1]===")"){let m=p.indexOf("-(");if(m===-1)return;let f=p.slice(0,m);if(!i.utilities.has(f,"functional"))return;let h=p.slice(m+2,-1),w=F(h,":"),b=null;if(w.length===2&&(b=w[0],h=w[1]),h[0]!=="-"||h[1]!=="-"||!xt(h))return;d=[[f,b===null?`[var(${h})]`:`[${b}:var(${h})]`]]}else d=pi(p,m=>i.utilities.has(m,"functional"));for(let[m,f]of d){let h={kind:"functional",root:m,modifier:c,value:null,variants:n,important:s,raw:e};if(f===null){yield h;continue}{let w=f.indexOf("[");if(w!==-1){if(f[f.length-1]!=="]")return;let k=Le(f.slice(w+1,-1));if(k===null)continue;let A=null;for(let C=0;C=si&&y<=ui))break}if(k.length===0||k.trim().length===0||A==="")continue;h.value={kind:"arbitrary",dataType:A||null,value:k}}else{let k=u===null||h.modifier?.kind==="arbitrary"?null:`${f}/${u}`;if(!or.test(f))continue;h.value={kind:"named",value:f,fraction:k}}}yield h}}function lr(e){if(e[0]==="["&&e[e.length-1]==="]"){let i=Le(e.slice(1,-1));return i===null||i.length===0||i.trim().length===0?null:{kind:"arbitrary",value:i}}return e[0]==="("&&e[e.length-1]===")"?(e=e.slice(1,-1),e[0]!=="-"||e[1]!=="-"||!xt(e)?null:(e=`var(${e})`,{kind:"arbitrary",value:ir(e)})):or.test(e)?{kind:"named",value:e}:null}function ci(e,i){if(e[0]==="["&&e[e.length-1]==="]"){if(e[1]==="@"&&e.includes("&"))return null;let r=Le(e.slice(1,-1));if(r===null||r.length===0||r.trim().length===0)return null;let t=r[0]===">"||r[0]==="+"||r[0]==="~";return!t&&r[0]!=="@"&&!r.includes("&")&&(r=`&:is(${r})`),{kind:"arbitrary",selector:r,relative:t}}{let r=F(e,"/");if(r.length>2)return null;let[t,n=null]=r,s=pi(t,l=>i.variants.has(l));for(let[l,p]of s)switch(i.variants.kind(l)){case"static":return p!==null||n!==null?null:{kind:"static",root:l};case"functional":{let u=n===null?null:lr(n);if(n!==null&&u===null)return null;if(p===null)return{kind:"functional",root:l,modifier:u,value:null};if(p[p.length-1]==="]"){if(p[0]!=="[")continue;let c=Le(p.slice(1,-1));return c===null||c.length===0||c.trim().length===0?null:{kind:"functional",root:l,modifier:u,value:{kind:"arbitrary",value:c}}}if(p[p.length-1]===")"){if(p[0]!=="(")continue;let c=Le(p.slice(1,-1));return c===null||c.length===0||c.trim().length===0||c[0]!=="-"||c[1]!=="-"?null:{kind:"functional",root:l,modifier:u,value:{kind:"arbitrary",value:`var(${c})`}}}if(!or.test(p))continue;return{kind:"functional",root:l,modifier:u,value:{kind:"named",value:p}}}case"compound":{if(p===null)return null;n&&(l==="not"||l==="has"||l==="in")&&(p=`${p}/${n}`,n=null);let u=i.parseVariant(p);if(u===null||!i.variants.compoundsWith(l,u))return null;let c=n===null?null:lr(n);return n!==null&&c===null?null:{kind:"compound",root:l,modifier:c,variant:u}}}}return null}function*pi(e,i){i(e)&&(yield[e,null]);let r=e.lastIndexOf("-");for(;r>0;){let t=e.slice(0,r);if(i(t)){let n=[t,e.slice(r+1)];if(n[1]===""||n[0]==="@"&&i("@")&&e[r]==="-")break;yield n}r=e.lastIndexOf("-",r-1)}e[0]==="@"&&i("@")&&(yield["@",e.slice(1)])}function di(e,i){let r=[];for(let n of i.variants)r.unshift(At(n));e.theme.prefix&&r.unshift(e.theme.prefix);let t="";if(i.kind==="static"&&(t+=i.root),i.kind==="functional"&&(t+=i.root,i.value))if(i.value.kind==="arbitrary"){if(i.value!==null){let n=sr(i.value.value),s=n?i.value.value.slice(4,-1):i.value.value,[l,p]=n?["(",")"]:["[","]"];i.value.dataType?t+=`-${l}${i.value.dataType}:${Ae(s)}${p}`:t+=`-${l}${Ae(s)}${p}`}}else i.value.kind==="named"&&(t+=`-${i.value.value}`);return i.kind==="arbitrary"&&(t+=`[${i.property}:${Ae(i.value)}]`),(i.kind==="arbitrary"||i.kind==="functional")&&(t+=rt(i.modifier)),i.important&&(t+="!"),r.push(t),r.join(":")}function rt(e){if(e===null)return"";let i=sr(e.value),r=i?e.value.slice(4,-1):e.value,[t,n]=i?["(",")"]:["[","]"];return e.kind==="arbitrary"?`/${t}${Ae(r)}${n}`:e.kind==="named"?`/${e.value}`:""}function At(e){if(e.kind==="static")return e.root;if(e.kind==="arbitrary")return`[${Ae(tl(e.selector))}]`;let i="";if(e.kind==="functional"){i+=e.root;let r=e.root!=="@";if(e.value)if(e.value.kind==="arbitrary"){let t=sr(e.value.value),n=t?e.value.value.slice(4,-1):e.value.value,[s,l]=t?["(",")"]:["[","]"];i+=`${r?"-":""}${s}${Ae(n)}${l}`}else e.value.kind==="named"&&(i+=`${r?"-":""}${e.value.value}`)}return e.kind==="compound"&&(i+=e.root,i+="-",i+=At(e.variant)),(e.kind==="functional"||e.kind==="compound")&&(i+=rt(e.modifier)),i}var Xn=new L(e=>{let i=Y(e),r=new Set,t=new Set(["~",">","+","-","*","/"]);return I(i,(n,s)=>{if(n.kind==="word"&&t.has(n.value)){let l=s.index;if(l===-1)return;let p=s.siblings[l-1];if(p?.kind!=="separator"||p.value!==" ")return;let u=s.siblings[l+1];if(u?.kind!=="separator"||u.value!==" ")return;let c=s.siblings[l-2];if(c&&t.has(c.value))return;let d=s.siblings[l+2];if(d&&t.has(d.value))return;r.add(p),r.add(u)}else if(n.kind==="separator"&&n.value.length>0&&n.value.trim()==="")(s.siblings[0]===n||s.siblings[s.siblings.length-1]===n)&&r.add(n);else if(n.kind==="separator"&&n.value.trim()===",")n.value=",";else if(n.kind==="function"&&n.value.startsWith("--")){let l=s.index;if(l<=0)return;let p=s.siblings[l-1];if(p?.kind==="separator"&&p.value===",")return;let u=s.siblings[l-2];return u&&!t.has(u.value)?void 0:V.ReplaceSkip({kind:"function",value:"",nodes:[n]})}}),r.size>0&&I(i,n=>{if(r.has(n))return r.delete(n),V.ReplaceSkip([])}),ar(i),B(i)});function Ae(e){return Xn.get(e)}var el=new L(e=>{let i=Y(e);return i.length===3&&i[0].kind==="word"&&i[0].value==="&"&&i[1].kind==="separator"&&i[1].value===":"&&i[2].kind==="function"&&i[2].value==="is"?B(i[2].nodes):e});function tl(e){return el.get(e)}function ar(e){for(let i of e)switch(i.kind){case"function":{if(i.value==="url"||i.value.endsWith("_url")){i.value=tt(i.value);break}if(i.value==="var"||i.value.endsWith("_var")||i.value==="theme"||i.value.endsWith("_theme")){i.value=tt(i.value);for(let r=0;r{let i=Y(e);return i.length===1&&i[0].kind==="function"&&i[0].value==="var"});function sr(e){return rl.get(e)}function il(e){throw new Error(`Unexpected value: ${e}`)}function tt(e){return e.replaceAll("_",String.raw`\_`).replaceAll(" ","_")}function Le(e){return xt(e)?ir(e):null}function Ne(e,i,r){if(e===i)return 0;let t=e.indexOf("("),n=i.indexOf("("),s=t===-1?e.replace(/[\d.]+/g,""):e.slice(0,t),l=n===-1?i.replace(/[\d.]+/g,""):i.slice(0,n),p=(s===l?0:s[-+]?(?:\d*\.)?\d+)(?[a-z]+|%)?$/i,ae=new L(e=>{let i=nl.exec(e);if(!i)return null;let r=i.groups?.value;if(r===void 0)return null;let t=Number(r);if(Number.isNaN(t))return null;let n=i.groups?.unit;return n===void 0?[t,null]:[t,n]});var ll=new Set(["inset","inherit","initial","revert","unset"]),al=new Set(["calc","clamp","max","min","--spacing"]),ol=new Set(["color","color-mix","contrast-color","device-cmyk","hsl","hsla","hwb","lab","lch","light-dark","oklab","oklch","rgb","rgba","--alpha"]),sl=/^-?(\d+|\.\d+)(.*?)$/;function it(e,i){function r(n){let s=B([n]),l=i(s);return Y(l)}return F(e,",").map(n=>{n=n.trim();let s=Y(n),l=null,p=0,u=0,c=!1;return I(s,d=>{switch(d.kind){case"word":{if(ll.has(d.value.toLowerCase()))return V.Continue;if(sl.test(d.value.toLowerCase()))return u++,V.Continue;if(d.value[0]==="#"||Cr(d.value))return c=!0,V.ReplaceStop(r(d));l=d,p++;break}case"function":return ol.has(d.value.toLowerCase())?(c=!0,V.ReplaceStop(r(d))):al.has(d.value.toLowerCase())?(u++,V.Skip):(l=d,p++,V.Skip);case"separator":return V.Continue;default:}}),c?B(s):u<2?n:p===0?`${n} ${i("currentcolor")}`:(p===1&&I(s,d=>d===l?(c=!0,V.ReplaceStop(r(d))):V.Skip),c?B(s):n)}).join(", ")}var $t=["0","0.5","1","1.5","2","2.5","3","3.5","4","5","6","7","8","9","10","11","12","14","16","20","24","28","32","36","40","44","48","52","56","60","64","72","80","96"],ur=class{utilities=new L(()=>[]);completions=new Map;static(i,r){this.utilities.get(i).push({kind:"static",compileFn:r})}functional(i,r,t){this.utilities.get(i).push({kind:"functional",compileFn:r,options:t})}has(i,r){return this.utilities.has(i)&&this.utilities.get(i).some(t=>t.kind===r)}get(i){return this.utilities.has(i)?this.utilities.get(i):[]}getCompletions(i){return this.has(i,"static")?this.completions.get(i)?.()??[{supportsNegative:!1,values:[],modifiers:[]}]:this.completions.get(i)?.()??[]}suggest(i,r){let t=this.completions.get(i);t?this.completions.set(i,()=>[...t?.(),...r?.()]):this.completions.set(i,r)}keys(i){let r=[];for(let[t,n]of this.utilities.entries())for(let s of n)if(s.kind===i){r.push(t);break}return r}};function $(e,i,r){return q("@property",e,[o("syntax",r?`"${r}"`:'"*"'),o("inherits","false"),...i?[o("initial-value",i)]:[]])}function ie(e,i){if(i===null)return e;let r=Number(i);return Number.isNaN(r)||(i=`${r*100}%`),i==="100%"?e:`color-mix(in oklab, ${e} ${i}, transparent)`}function gi(e,i){let r=Number(i);return Number.isNaN(r)||(i=`${r*100}%`),`oklab(from ${e} l a b / ${i})`}function ne(e,i,r){if(!i)return e;if(i.kind==="arbitrary")return ie(e,i.value);let t=r.resolve(i.value,["--opacity"]);return t?ie(e,t):xe(i.value)?ie(e,`${i.value}%`):null}function oe(e,i,r){let t=null;switch(e.value.value){case"inherit":{t="inherit";break}case"transparent":{t="transparent";break}case"current":{t="currentcolor";break}default:{t=i.resolve(e.value.value,r);break}}return t?ne(t,e.modifier,i):null}var hi=/(\d+)_(\d+)/g;function vi(e){let i=new ur;function r(a,g){function*v(x){for(let T of e.keysInNamespaces(x))yield T.replace(hi,(M,N,_)=>`${N}.${_}`)}let S=["1/2","1/3","2/3","1/4","2/4","3/4","1/5","2/5","3/5","4/5","1/6","2/6","3/6","4/6","5/6","1/12","2/12","3/12","4/12","5/12","6/12","7/12","8/12","9/12","10/12","11/12"];i.suggest(a,()=>{let x=[];for(let T of g()){if(typeof T=="string"){x.push({values:[T],modifiers:[]});continue}let M=[...T.values??[],...v(T.valueThemeKeys??[])],N=[...T.modifiers??[],...v(T.modifierThemeKeys??[])];T.supportsFractions&&M.push(...S),T.hasDefaultValue&&M.unshift(null),x.push({supportsNegative:T.supportsNegative,values:M,modifiers:N})}return x})}function t(a,g){i.static(a,()=>g.map(v=>typeof v=="function"?v():o(v[0],v[1])))}function n(a,g){g.staticValues&&(g.staticValues=Object.assign(Object.create(null),g.staticValues));function v({negative:S}){return x=>{let T=null,M=null;if(x.value)if(x.value.kind==="arbitrary"){if(x.modifier)return;T=x.value.value,M=x.value.dataType}else{if(T=e.resolve(x.value.fraction??x.value.value,g.themeKeys??[]),T!==null&&x.modifier&&!x.value.fraction)return;if(T===null&&g.supportsFractions&&x.value.fraction){let[N,_]=F(x.value.fraction,"/");if(!U(N)||!U(_))return;T=`calc(${N} / ${_} * 100%)`}if(T===null&&S&&g.handleNegativeBareValue){if(T=g.handleNegativeBareValue(x.value),!T?.includes("/")&&x.modifier)return;if(T!==null)return g.handle(T,null)}if(T===null&&g.handleBareValue&&(T=g.handleBareValue(x.value),!T?.includes("/")&&x.modifier))return;if(T===null&&!S&&g.staticValues&&!x.modifier){let N=g.staticValues[x.value.value];if(N)return N.map(le)}}else{if(x.modifier)return;T=g.defaultValue!==void 0?g.defaultValue:e.resolve(null,g.themeKeys??[])}if(T!==null)return g.handle(S?ft(`calc(${T} * -1)`):T,M)}}if(g.supportsNegative&&i.functional(`-${a}`,v({negative:!0})),i.functional(a,v({negative:!1})),r(a,()=>[{supportsNegative:g.supportsNegative,valueThemeKeys:g.themeKeys??[],hasDefaultValue:g.defaultValue!==void 0&&g.defaultValue!==null,supportsFractions:g.supportsFractions}]),g.staticValues&&Object.keys(g.staticValues).length>0){let S=Object.keys(g.staticValues);r(a,()=>[{values:S}])}}function s(a,g){i.functional(a,v=>{if(!v.value)return;let S=null;if(v.value.kind==="arbitrary"?(S=v.value.value,S=ne(S,v.modifier,e)):S=oe(v,e,g.themeKeys),S!==null)return g.handle(S)}),r(a,()=>[{values:["current","inherit","transparent"],valueThemeKeys:g.themeKeys,modifierThemeKeys:["--opacity"],modifiers:Array.from({length:21},(v,S)=>`${S*5}`)}])}function l(a,g,v,{supportsNegative:S=!1,supportsFractions:x=!1,staticValues:T}={}){S&&i.static(`-${a}-px`,()=>v("-1px")),i.static(`${a}-px`,()=>v("1px")),n(a,{themeKeys:g,supportsFractions:x,supportsNegative:S,defaultValue:null,handleBareValue:({value:M})=>!e.resolve(null,["--spacing"])||!te(M)?null:`--spacing(${M})`,handleNegativeBareValue:({value:M})=>!e.resolve(null,["--spacing"])||!te(M)?null:`--spacing(-${M})`,handle:v,staticValues:T}),r(a,()=>[{values:e.get(["--spacing"])?$t:[],supportsNegative:S,supportsFractions:x,valueThemeKeys:g}])}t("sr-only",[["position","absolute"],["width","1px"],["height","1px"],["padding","0"],["margin","-1px"],["overflow","hidden"],["clip-path","inset(50%)"],["white-space","nowrap"],["border-width","0"]]),t("not-sr-only",[["position","static"],["width","auto"],["height","auto"],["padding","0"],["margin","0"],["overflow","visible"],["clip-path","none"],["white-space","normal"]]),t("pointer-events-none",[["pointer-events","none"]]),t("pointer-events-auto",[["pointer-events","auto"]]),t("visible",[["visibility","visible"]]),t("invisible",[["visibility","hidden"]]),t("collapse",[["visibility","collapse"]]),t("static",[["position","static"]]),t("fixed",[["position","fixed"]]),t("absolute",[["position","absolute"]]),t("relative",[["position","relative"]]),t("sticky",[["position","sticky"]]);for(let[a,g]of[["inset","inset"],["inset-x","inset-inline"],["inset-y","inset-block"],["inset-s","inset-inline-start"],["inset-e","inset-inline-end"],["inset-bs","inset-block-start"],["inset-be","inset-block-end"],["top","top"],["right","right"],["bottom","bottom"],["left","left"]])t(`${a}-auto`,[[g,"auto"]]),t(`${a}-full`,[[g,"100%"]]),t(`-${a}-full`,[[g,"-100%"]]),l(a,["--inset","--spacing"],v=>[o(g,v)],{supportsNegative:!0,supportsFractions:!0});t("isolate",[["isolation","isolate"]]),t("isolation-auto",[["isolation","auto"]]),n("z",{supportsNegative:!0,handleBareValue:({value:a})=>U(a)?a:null,themeKeys:["--z-index"],handle:a=>[o("z-index",a)],staticValues:{auto:[o("z-index","auto")]}}),r("z",()=>[{supportsNegative:!0,values:["0","10","20","30","40","50"],valueThemeKeys:["--z-index"]}]),n("order",{supportsNegative:!0,handleBareValue:({value:a})=>U(a)?a:null,themeKeys:["--order"],handle:a=>[o("order",a)],staticValues:{first:[o("order","-9999")],last:[o("order","9999")]}}),r("order",()=>[{supportsNegative:!0,values:Array.from({length:12},(a,g)=>`${g+1}`),valueThemeKeys:["--order"]}]),n("col",{supportsNegative:!0,handleBareValue:({value:a})=>U(a)?a:null,themeKeys:["--grid-column"],handle:a=>[o("grid-column",a)],staticValues:{auto:[o("grid-column","auto")]}}),n("col-span",{handleBareValue:({value:a})=>U(a)?a:null,handle:a=>[o("grid-column",`span ${a} / span ${a}`)],staticValues:{full:[o("grid-column","1 / -1")]}}),n("col-start",{supportsNegative:!0,handleBareValue:({value:a})=>U(a)?a:null,themeKeys:["--grid-column-start"],handle:a=>[o("grid-column-start",a)],staticValues:{auto:[o("grid-column-start","auto")]}}),n("col-end",{supportsNegative:!0,handleBareValue:({value:a})=>U(a)?a:null,themeKeys:["--grid-column-end"],handle:a=>[o("grid-column-end",a)],staticValues:{auto:[o("grid-column-end","auto")]}}),r("col-span",()=>[{values:Array.from({length:12},(a,g)=>`${g+1}`),valueThemeKeys:[]}]),r("col-start",()=>[{supportsNegative:!0,values:Array.from({length:13},(a,g)=>`${g+1}`),valueThemeKeys:["--grid-column-start"]}]),r("col-end",()=>[{supportsNegative:!0,values:Array.from({length:13},(a,g)=>`${g+1}`),valueThemeKeys:["--grid-column-end"]}]),n("row",{supportsNegative:!0,handleBareValue:({value:a})=>U(a)?a:null,themeKeys:["--grid-row"],handle:a=>[o("grid-row",a)],staticValues:{auto:[o("grid-row","auto")]}}),n("row-span",{themeKeys:[],handleBareValue:({value:a})=>U(a)?a:null,handle:a=>[o("grid-row",`span ${a} / span ${a}`)],staticValues:{full:[o("grid-row","1 / -1")]}}),n("row-start",{supportsNegative:!0,handleBareValue:({value:a})=>U(a)?a:null,themeKeys:["--grid-row-start"],handle:a=>[o("grid-row-start",a)],staticValues:{auto:[o("grid-row-start","auto")]}}),n("row-end",{supportsNegative:!0,handleBareValue:({value:a})=>U(a)?a:null,themeKeys:["--grid-row-end"],handle:a=>[o("grid-row-end",a)],staticValues:{auto:[o("grid-row-end","auto")]}}),r("row-span",()=>[{values:Array.from({length:12},(a,g)=>`${g+1}`),valueThemeKeys:[]}]),r("row-start",()=>[{supportsNegative:!0,values:Array.from({length:13},(a,g)=>`${g+1}`),valueThemeKeys:["--grid-row-start"]}]),r("row-end",()=>[{supportsNegative:!0,values:Array.from({length:13},(a,g)=>`${g+1}`),valueThemeKeys:["--grid-row-end"]}]),t("float-start",[["float","inline-start"]]),t("float-end",[["float","inline-end"]]),t("float-right",[["float","right"]]),t("float-left",[["float","left"]]),t("float-none",[["float","none"]]),t("clear-start",[["clear","inline-start"]]),t("clear-end",[["clear","inline-end"]]),t("clear-right",[["clear","right"]]),t("clear-left",[["clear","left"]]),t("clear-both",[["clear","both"]]),t("clear-none",[["clear","none"]]);for(let[a,g]of[["m","margin"],["mx","margin-inline"],["my","margin-block"],["ms","margin-inline-start"],["me","margin-inline-end"],["mbs","margin-block-start"],["mbe","margin-block-end"],["mt","margin-top"],["mr","margin-right"],["mb","margin-bottom"],["ml","margin-left"]])t(`${a}-auto`,[[g,"auto"]]),l(a,["--margin","--spacing"],v=>[o(g,v)],{supportsNegative:!0});t("box-border",[["box-sizing","border-box"]]),t("box-content",[["box-sizing","content-box"]]),n("line-clamp",{themeKeys:["--line-clamp"],handleBareValue:({value:a})=>U(a)?a:null,handle:a=>[o("overflow","hidden"),o("display","-webkit-box"),o("-webkit-box-orient","vertical"),o("-webkit-line-clamp",a)],staticValues:{none:[o("overflow","visible"),o("display","block"),o("-webkit-box-orient","horizontal"),o("-webkit-line-clamp","unset")]}}),r("line-clamp",()=>[{values:["1","2","3","4","5","6"],valueThemeKeys:["--line-clamp"]}]),t("block",[["display","block"]]),t("inline-block",[["display","inline-block"]]),t("inline",[["display","inline"]]),t("hidden",[["display","none"]]),t("inline-flex",[["display","inline-flex"]]),t("table",[["display","table"]]),t("inline-table",[["display","inline-table"]]),t("table-caption",[["display","table-caption"]]),t("table-cell",[["display","table-cell"]]),t("table-column",[["display","table-column"]]),t("table-column-group",[["display","table-column-group"]]),t("table-footer-group",[["display","table-footer-group"]]),t("table-header-group",[["display","table-header-group"]]),t("table-row-group",[["display","table-row-group"]]),t("table-row",[["display","table-row"]]),t("flow-root",[["display","flow-root"]]),t("flex",[["display","flex"]]),t("grid",[["display","grid"]]),t("inline-grid",[["display","inline-grid"]]),t("contents",[["display","contents"]]),t("list-item",[["display","list-item"]]),t("field-sizing-content",[["field-sizing","content"]]),t("field-sizing-fixed",[["field-sizing","fixed"]]),n("aspect",{themeKeys:["--aspect"],handleBareValue:({fraction:a})=>{if(a===null)return null;let[g,v]=F(a,"/");return!te(g)||!te(v)?null:a},handle:a=>[o("aspect-ratio",a)],staticValues:{auto:[o("aspect-ratio","auto")],square:[o("aspect-ratio","1 / 1")]}});for(let[a,g]of[["full","100%"],["svw","100svw"],["lvw","100lvw"],["dvw","100dvw"],["svh","100svh"],["lvh","100lvh"],["dvh","100dvh"],["min","min-content"],["max","max-content"],["fit","fit-content"]])t(`size-${a}`,[["--tw-sort","size"],["width",g],["height",g]]),t(`w-${a}`,[["width",g]]),t(`h-${a}`,[["height",g]]),t(`min-w-${a}`,[["min-width",g]]),t(`min-h-${a}`,[["min-height",g]]),t(`max-w-${a}`,[["max-width",g]]),t(`max-h-${a}`,[["max-height",g]]);t("size-auto",[["--tw-sort","size"],["width","auto"],["height","auto"]]),t("w-auto",[["width","auto"]]),t("h-auto",[["height","auto"]]),t("min-w-auto",[["min-width","auto"]]),t("min-h-auto",[["min-height","auto"]]),t("h-lh",[["height","1lh"]]),t("min-h-lh",[["min-height","1lh"]]),t("max-h-lh",[["max-height","1lh"]]),t("w-screen",[["width","100vw"]]),t("min-w-screen",[["min-width","100vw"]]),t("max-w-screen",[["max-width","100vw"]]),t("h-screen",[["height","100vh"]]),t("min-h-screen",[["min-height","100vh"]]),t("max-h-screen",[["max-height","100vh"]]),t("max-w-none",[["max-width","none"]]),t("max-h-none",[["max-height","none"]]),l("size",["--size","--spacing"],a=>[o("--tw-sort","size"),o("width",a),o("height",a)],{supportsFractions:!0});for(let[a,g,v]of[["w",["--width","--spacing","--container"],"width"],["min-w",["--min-width","--spacing","--container"],"min-width"],["max-w",["--max-width","--spacing","--container"],"max-width"],["h",["--height","--spacing"],"height"],["min-h",["--min-height","--height","--spacing"],"min-height"],["max-h",["--max-height","--height","--spacing"],"max-height"]])l(a,g,S=>[o(v,S)],{supportsFractions:!0});for(let[a,g]of[["full","100%"],["min","min-content"],["max","max-content"],["fit","fit-content"]])t(`inline-${a}`,[["inline-size",g]]),t(`block-${a}`,[["block-size",g]]),t(`min-inline-${a}`,[["min-inline-size",g]]),t(`min-block-${a}`,[["min-block-size",g]]),t(`max-inline-${a}`,[["max-inline-size",g]]),t(`max-block-${a}`,[["max-block-size",g]]);for(let[a,g]of[["svw","100svw"],["lvw","100lvw"],["dvw","100dvw"]])t(`inline-${a}`,[["inline-size",g]]),t(`min-inline-${a}`,[["min-inline-size",g]]),t(`max-inline-${a}`,[["max-inline-size",g]]);for(let[a,g]of[["svh","100svh"],["lvh","100lvh"],["dvh","100dvh"]])t(`block-${a}`,[["block-size",g]]),t(`min-block-${a}`,[["min-block-size",g]]),t(`max-block-${a}`,[["max-block-size",g]]);t("inline-auto",[["inline-size","auto"]]),t("block-auto",[["block-size","auto"]]),t("min-inline-auto",[["min-inline-size","auto"]]),t("min-block-auto",[["min-block-size","auto"]]),t("block-lh",[["block-size","1lh"]]),t("min-block-lh",[["min-block-size","1lh"]]),t("max-block-lh",[["max-block-size","1lh"]]),t("inline-screen",[["inline-size","100vw"]]),t("min-inline-screen",[["min-inline-size","100vw"]]),t("max-inline-screen",[["max-inline-size","100vw"]]),t("block-screen",[["block-size","100vh"]]),t("min-block-screen",[["min-block-size","100vh"]]),t("max-block-screen",[["max-block-size","100vh"]]),t("max-inline-none",[["max-inline-size","none"]]),t("max-block-none",[["max-block-size","none"]]);for(let[a,g,v]of[["inline",["--spacing","--container"],"inline-size"],["min-inline",["--spacing","--container"],"min-inline-size"],["max-inline",["--spacing","--container"],"max-inline-size"],["block",["--spacing"],"block-size"],["min-block",["--spacing"],"min-block-size"],["max-block",["--spacing"],"max-block-size"]])l(a,g,S=>[o(v,S)],{supportsFractions:!0});i.static("container",()=>{let a=[...e.namespace("--breakpoint").values()];a.sort((v,S)=>Ne(v,S,"asc"));let g=[o("--tw-sort","--tw-container-component"),o("width","100%")];for(let v of a)g.push(q("@media",`(width >= ${v})`,[o("max-width",v)]));return g}),t("flex-auto",[["flex","auto"]]),t("flex-initial",[["flex","0 auto"]]),t("flex-none",[["flex","none"]]),i.functional("flex",a=>{if(a.value){if(a.value.kind==="arbitrary")return a.modifier?void 0:[o("flex",a.value.value)];if(a.value.fraction){let[g,v]=F(a.value.fraction,"/");return!U(g)||!U(v)?void 0:[o("flex",`calc(${a.value.fraction} * 100%)`)]}if(U(a.value.value))return a.modifier?void 0:[o("flex",a.value.value)]}}),r("flex",()=>[{supportsFractions:!0},{values:Array.from({length:12},(a,g)=>`${g+1}`)}]),n("shrink",{defaultValue:"1",handleBareValue:({value:a})=>U(a)?a:null,handle:a=>[o("flex-shrink",a)]}),n("grow",{defaultValue:"1",handleBareValue:({value:a})=>U(a)?a:null,handle:a=>[o("flex-grow",a)]}),r("shrink",()=>[{values:["0"],valueThemeKeys:[],hasDefaultValue:!0}]),r("grow",()=>[{values:["0"],valueThemeKeys:[],hasDefaultValue:!0}]),t("basis-auto",[["flex-basis","auto"]]),t("basis-full",[["flex-basis","100%"]]),l("basis",["--flex-basis","--spacing","--container"],a=>[o("flex-basis",a)],{supportsFractions:!0}),t("table-auto",[["table-layout","auto"]]),t("table-fixed",[["table-layout","fixed"]]),t("caption-top",[["caption-side","top"]]),t("caption-bottom",[["caption-side","bottom"]]),t("border-collapse",[["border-collapse","collapse"]]),t("border-separate",[["border-collapse","separate"]]);let p=()=>H([$("--tw-border-spacing-x","0",""),$("--tw-border-spacing-y","0","")]);l("border-spacing",["--border-spacing","--spacing"],a=>[p(),o("--tw-border-spacing-x",a),o("--tw-border-spacing-y",a),o("border-spacing","var(--tw-border-spacing-x) var(--tw-border-spacing-y)")]),l("border-spacing-x",["--border-spacing","--spacing"],a=>[p(),o("--tw-border-spacing-x",a),o("border-spacing","var(--tw-border-spacing-x) var(--tw-border-spacing-y)")]),l("border-spacing-y",["--border-spacing","--spacing"],a=>[p(),o("--tw-border-spacing-y",a),o("border-spacing","var(--tw-border-spacing-x) var(--tw-border-spacing-y)")]),n("origin",{themeKeys:["--transform-origin"],handle:a=>[o("transform-origin",a)],staticValues:{center:[o("transform-origin","center")],top:[o("transform-origin","top")],"top-right":[o("transform-origin","100% 0")],right:[o("transform-origin","100%")],"bottom-right":[o("transform-origin","100% 100%")],bottom:[o("transform-origin","bottom")],"bottom-left":[o("transform-origin","0 100%")],left:[o("transform-origin","0")],"top-left":[o("transform-origin","0 0")]}}),n("perspective-origin",{themeKeys:["--perspective-origin"],handle:a=>[o("perspective-origin",a)],staticValues:{center:[o("perspective-origin","center")],top:[o("perspective-origin","top")],"top-right":[o("perspective-origin","100% 0")],right:[o("perspective-origin","100%")],"bottom-right":[o("perspective-origin","100% 100%")],bottom:[o("perspective-origin","bottom")],"bottom-left":[o("perspective-origin","0 100%")],left:[o("perspective-origin","0")],"top-left":[o("perspective-origin","0 0")]}}),n("perspective",{themeKeys:["--perspective"],handle:a=>[o("perspective",a)],staticValues:{none:[o("perspective","none")]}});let u=()=>H([$("--tw-translate-x","0"),$("--tw-translate-y","0"),$("--tw-translate-z","0")]);t("translate-none",[["translate","none"]]),t("-translate-full",[u,["--tw-translate-x","-100%"],["--tw-translate-y","-100%"],["translate","var(--tw-translate-x) var(--tw-translate-y)"]]),t("translate-full",[u,["--tw-translate-x","100%"],["--tw-translate-y","100%"],["translate","var(--tw-translate-x) var(--tw-translate-y)"]]),l("translate",["--translate","--spacing"],a=>[u(),o("--tw-translate-x",a),o("--tw-translate-y",a),o("translate","var(--tw-translate-x) var(--tw-translate-y)")],{supportsNegative:!0,supportsFractions:!0});for(let a of["x","y"])t(`-translate-${a}-full`,[u,[`--tw-translate-${a}`,"-100%"],["translate","var(--tw-translate-x) var(--tw-translate-y)"]]),t(`translate-${a}-full`,[u,[`--tw-translate-${a}`,"100%"],["translate","var(--tw-translate-x) var(--tw-translate-y)"]]),l(`translate-${a}`,["--translate","--spacing"],g=>[u(),o(`--tw-translate-${a}`,g),o("translate","var(--tw-translate-x) var(--tw-translate-y)")],{supportsNegative:!0,supportsFractions:!0});l("translate-z",["--translate","--spacing"],a=>[u(),o("--tw-translate-z",a),o("translate","var(--tw-translate-x) var(--tw-translate-y) var(--tw-translate-z)")],{supportsNegative:!0}),t("translate-3d",[u,["translate","var(--tw-translate-x) var(--tw-translate-y) var(--tw-translate-z)"]]);let c=()=>H([$("--tw-scale-x","1"),$("--tw-scale-y","1"),$("--tw-scale-z","1")]);t("scale-none",[["scale","none"]]);function d({negative:a}){return g=>{if(!g.value||g.modifier)return;let v;return g.value.kind==="arbitrary"?(v=g.value.value,v=a?`calc(${v} * -1)`:v,[o("scale",v)]):(v=e.resolve(g.value.value,["--scale"]),!v&&U(g.value.value)&&(v=`${g.value.value}%`),v?(v=a?`calc(${v} * -1)`:v,[c(),o("--tw-scale-x",v),o("--tw-scale-y",v),o("--tw-scale-z",v),o("scale","var(--tw-scale-x) var(--tw-scale-y)")]):void 0)}}i.functional("-scale",d({negative:!0})),i.functional("scale",d({negative:!1})),r("scale",()=>[{supportsNegative:!0,values:["0","50","75","90","95","100","105","110","125","150","200"],valueThemeKeys:["--scale"]}]);for(let a of["x","y","z"])n(`scale-${a}`,{supportsNegative:!0,themeKeys:["--scale"],handleBareValue:({value:g})=>U(g)?`${g}%`:null,handle:g=>[c(),o(`--tw-scale-${a}`,g),o("scale",`var(--tw-scale-x) var(--tw-scale-y)${a==="z"?" var(--tw-scale-z)":""}`)]}),r(`scale-${a}`,()=>[{supportsNegative:!0,values:["0","50","75","90","95","100","105","110","125","150","200"],valueThemeKeys:["--scale"]}]);t("scale-3d",[c,["scale","var(--tw-scale-x) var(--tw-scale-y) var(--tw-scale-z)"]]),t("rotate-none",[["rotate","none"]]);function m({negative:a}){return g=>{if(!g.value||g.modifier)return;let v;if(g.value.kind==="arbitrary"){v=g.value.value;let S=g.value.dataType??X(v,["angle","vector"]);if(S==="vector")return[o("rotate",`${v} var(--tw-rotate)`)];if(S!=="angle")return[o("rotate",a?`calc(${v} * -1)`:v)]}else if(v=e.resolve(g.value.value,["--rotate"]),!v&&U(g.value.value)&&(v=`${g.value.value}deg`),!v)return;return[o("rotate",a?`calc(${v} * -1)`:v)]}}i.functional("-rotate",m({negative:!0})),i.functional("rotate",m({negative:!1})),r("rotate",()=>[{supportsNegative:!0,values:["0","1","2","3","6","12","45","90","180"],valueThemeKeys:["--rotate"]}]);{let a=["var(--tw-rotate-x, )","var(--tw-rotate-y, )","var(--tw-rotate-z, )","var(--tw-skew-x, )","var(--tw-skew-y, )"].join(" "),g=()=>H([$("--tw-rotate-x"),$("--tw-rotate-y"),$("--tw-rotate-z"),$("--tw-skew-x"),$("--tw-skew-y")]);for(let v of["x","y","z"])n(`rotate-${v}`,{supportsNegative:!0,themeKeys:["--rotate"],handleBareValue:({value:S})=>U(S)?`${S}deg`:null,handle:S=>[g(),o(`--tw-rotate-${v}`,`rotate${v.toUpperCase()}(${S})`),o("transform",a)]}),r(`rotate-${v}`,()=>[{supportsNegative:!0,values:["0","1","2","3","6","12","45","90","180"],valueThemeKeys:["--rotate"]}]);n("skew",{supportsNegative:!0,themeKeys:["--skew"],handleBareValue:({value:v})=>U(v)?`${v}deg`:null,handle:v=>[g(),o("--tw-skew-x",`skewX(${v})`),o("--tw-skew-y",`skewY(${v})`),o("transform",a)]}),n("skew-x",{supportsNegative:!0,themeKeys:["--skew"],handleBareValue:({value:v})=>U(v)?`${v}deg`:null,handle:v=>[g(),o("--tw-skew-x",`skewX(${v})`),o("transform",a)]}),n("skew-y",{supportsNegative:!0,themeKeys:["--skew"],handleBareValue:({value:v})=>U(v)?`${v}deg`:null,handle:v=>[g(),o("--tw-skew-y",`skewY(${v})`),o("transform",a)]}),r("skew",()=>[{supportsNegative:!0,values:["0","1","2","3","6","12"],valueThemeKeys:["--skew"]}]),r("skew-x",()=>[{supportsNegative:!0,values:["0","1","2","3","6","12"],valueThemeKeys:["--skew"]}]),r("skew-y",()=>[{supportsNegative:!0,values:["0","1","2","3","6","12"],valueThemeKeys:["--skew"]}]),i.functional("transform",v=>{if(v.modifier)return;let S=null;if(v.value?v.value.kind==="arbitrary"&&(S=v.value.value):S=a,S!==null)return[g(),o("transform",S)]}),r("transform",()=>[{hasDefaultValue:!0}]),t("transform-cpu",[["transform",a]]),t("transform-gpu",[["transform",`translateZ(0) ${a}`]]),t("transform-none",[["transform","none"]])}n("zoom",{handleBareValue:({value:a})=>U(a)?`${a}%`:null,handle:a=>[o("zoom",a)]}),r("zoom",()=>[{values:["50","75","90","95","100","105","110","125","150","200"]}]),t("transform-flat",[["transform-style","flat"]]),t("transform-3d",[["transform-style","preserve-3d"]]),t("transform-content",[["transform-box","content-box"]]),t("transform-border",[["transform-box","border-box"]]),t("transform-fill",[["transform-box","fill-box"]]),t("transform-stroke",[["transform-box","stroke-box"]]),t("transform-view",[["transform-box","view-box"]]),t("backface-visible",[["backface-visibility","visible"]]),t("backface-hidden",[["backface-visibility","hidden"]]);for(let a of["auto","default","pointer","wait","text","move","help","not-allowed","none","context-menu","progress","cell","crosshair","vertical-text","alias","copy","no-drop","grab","grabbing","all-scroll","col-resize","row-resize","n-resize","e-resize","s-resize","w-resize","ne-resize","nw-resize","se-resize","sw-resize","ew-resize","ns-resize","nesw-resize","nwse-resize","zoom-in","zoom-out"])t(`cursor-${a}`,[["cursor",a]]);n("cursor",{themeKeys:["--cursor"],handle:a=>[o("cursor",a)]});for(let a of["auto","none","manipulation"])t(`touch-${a}`,[["touch-action",a]]);let f=()=>H([$("--tw-pan-x"),$("--tw-pan-y"),$("--tw-pinch-zoom")]);for(let a of["x","left","right"])t(`touch-pan-${a}`,[f,["--tw-pan-x",`pan-${a}`],["touch-action","var(--tw-pan-x, ) var(--tw-pan-y, ) var(--tw-pinch-zoom, )"]]);for(let a of["y","up","down"])t(`touch-pan-${a}`,[f,["--tw-pan-y",`pan-${a}`],["touch-action","var(--tw-pan-x, ) var(--tw-pan-y, ) var(--tw-pinch-zoom, )"]]);t("touch-pinch-zoom",[f,["--tw-pinch-zoom","pinch-zoom"],["touch-action","var(--tw-pan-x, ) var(--tw-pan-y, ) var(--tw-pinch-zoom, )"]]);for(let a of["none","text","all","auto"])t(`select-${a}`,[["-webkit-user-select",a],["user-select",a]]);t("resize-none",[["resize","none"]]),t("resize-x",[["resize","horizontal"]]),t("resize-y",[["resize","vertical"]]),t("resize",[["resize","both"]]),t("snap-none",[["scroll-snap-type","none"]]);let h=()=>H([$("--tw-scroll-snap-strictness","proximity","*")]);for(let a of["x","y","both"])t(`snap-${a}`,[h,["scroll-snap-type",`${a} var(--tw-scroll-snap-strictness)`]]);t("snap-mandatory",[h,["--tw-scroll-snap-strictness","mandatory"]]),t("snap-proximity",[h,["--tw-scroll-snap-strictness","proximity"]]),t("snap-align-none",[["scroll-snap-align","none"]]),t("snap-start",[["scroll-snap-align","start"]]),t("snap-end",[["scroll-snap-align","end"]]),t("snap-center",[["scroll-snap-align","center"]]),t("snap-normal",[["scroll-snap-stop","normal"]]),t("snap-always",[["scroll-snap-stop","always"]]);for(let[a,g]of[["scroll-m","scroll-margin"],["scroll-mx","scroll-margin-inline"],["scroll-my","scroll-margin-block"],["scroll-ms","scroll-margin-inline-start"],["scroll-me","scroll-margin-inline-end"],["scroll-mbs","scroll-margin-block-start"],["scroll-mbe","scroll-margin-block-end"],["scroll-mt","scroll-margin-top"],["scroll-mr","scroll-margin-right"],["scroll-mb","scroll-margin-bottom"],["scroll-ml","scroll-margin-left"]])l(a,["--scroll-margin","--spacing"],v=>[o(g,v)],{supportsNegative:!0});for(let[a,g]of[["scroll-p","scroll-padding"],["scroll-px","scroll-padding-inline"],["scroll-py","scroll-padding-block"],["scroll-ps","scroll-padding-inline-start"],["scroll-pe","scroll-padding-inline-end"],["scroll-pbs","scroll-padding-block-start"],["scroll-pbe","scroll-padding-block-end"],["scroll-pt","scroll-padding-top"],["scroll-pr","scroll-padding-right"],["scroll-pb","scroll-padding-bottom"],["scroll-pl","scroll-padding-left"]])l(a,["--scroll-padding","--spacing"],v=>[o(g,v)]);t("list-inside",[["list-style-position","inside"]]),t("list-outside",[["list-style-position","outside"]]),n("list",{themeKeys:["--list-style-type"],handle:a=>[o("list-style-type",a)],staticValues:{none:[o("list-style-type","none")],disc:[o("list-style-type","disc")],decimal:[o("list-style-type","decimal")]}}),n("list-image",{themeKeys:["--list-style-image"],handle:a=>[o("list-style-image",a)],staticValues:{none:[o("list-style-image","none")]}}),t("appearance-none",[["appearance","none"]]),t("appearance-auto",[["appearance","auto"]]),t("scheme-normal",[["color-scheme","normal"]]),t("scheme-dark",[["color-scheme","dark"]]),t("scheme-light",[["color-scheme","light"]]),t("scheme-light-dark",[["color-scheme","light dark"]]),t("scheme-only-dark",[["color-scheme","only dark"]]),t("scheme-only-light",[["color-scheme","only light"]]),n("columns",{themeKeys:["--columns","--container"],handleBareValue:({value:a})=>U(a)?a:null,handle:a=>[o("columns",a)],staticValues:{auto:[o("columns","auto")]}}),r("columns",()=>[{values:Array.from({length:12},(a,g)=>`${g+1}`),valueThemeKeys:["--columns","--container"]}]);for(let a of["auto","avoid","all","avoid-page","page","left","right","column"])t(`break-before-${a}`,[["break-before",a]]);for(let a of["auto","avoid","avoid-page","avoid-column"])t(`break-inside-${a}`,[["break-inside",a]]);for(let a of["auto","avoid","all","avoid-page","page","left","right","column"])t(`break-after-${a}`,[["break-after",a]]);t("grid-flow-row",[["grid-auto-flow","row"]]),t("grid-flow-col",[["grid-auto-flow","column"]]),t("grid-flow-dense",[["grid-auto-flow","dense"]]),t("grid-flow-row-dense",[["grid-auto-flow","row dense"]]),t("grid-flow-col-dense",[["grid-auto-flow","column dense"]]),n("auto-cols",{themeKeys:["--grid-auto-columns"],handleBareValue:({value:a})=>!e.resolve(null,["--spacing"])||!te(a)?null:`--spacing(${a})`,handle:a=>[o("grid-auto-columns",a)],staticValues:{auto:[o("grid-auto-columns","auto")],min:[o("grid-auto-columns","min-content")],max:[o("grid-auto-columns","max-content")],fr:[o("grid-auto-columns","minmax(0, 1fr)")]}}),n("auto-rows",{themeKeys:["--grid-auto-rows"],handleBareValue:({value:a})=>!e.resolve(null,["--spacing"])||!te(a)?null:`--spacing(${a})`,handle:a=>[o("grid-auto-rows",a)],staticValues:{auto:[o("grid-auto-rows","auto")],min:[o("grid-auto-rows","min-content")],max:[o("grid-auto-rows","max-content")],fr:[o("grid-auto-rows","minmax(0, 1fr)")]}}),n("grid-cols",{themeKeys:["--grid-template-columns"],handleBareValue:({value:a})=>Lt(a)?`repeat(${a}, minmax(0, 1fr))`:null,handle:a=>[o("grid-template-columns",a)],staticValues:{none:[o("grid-template-columns","none")],subgrid:[o("grid-template-columns","subgrid")]}}),n("grid-rows",{themeKeys:["--grid-template-rows"],handleBareValue:({value:a})=>Lt(a)?`repeat(${a}, minmax(0, 1fr))`:null,handle:a=>[o("grid-template-rows",a)],staticValues:{none:[o("grid-template-rows","none")],subgrid:[o("grid-template-rows","subgrid")]}}),r("grid-cols",()=>[{values:Array.from({length:12},(a,g)=>`${g+1}`),valueThemeKeys:["--grid-template-columns"]}]),r("grid-rows",()=>[{values:Array.from({length:12},(a,g)=>`${g+1}`),valueThemeKeys:["--grid-template-rows"]}]),t("flex-row",[["flex-direction","row"]]),t("flex-row-reverse",[["flex-direction","row-reverse"]]),t("flex-col",[["flex-direction","column"]]),t("flex-col-reverse",[["flex-direction","column-reverse"]]),t("flex-wrap",[["flex-wrap","wrap"]]),t("flex-nowrap",[["flex-wrap","nowrap"]]),t("flex-wrap-reverse",[["flex-wrap","wrap-reverse"]]),t("place-content-center",[["place-content","center"]]),t("place-content-start",[["place-content","start"]]),t("place-content-end",[["place-content","end"]]),t("place-content-center-safe",[["place-content","safe center"]]),t("place-content-end-safe",[["place-content","safe end"]]),t("place-content-between",[["place-content","space-between"]]),t("place-content-around",[["place-content","space-around"]]),t("place-content-evenly",[["place-content","space-evenly"]]),t("place-content-baseline",[["place-content","baseline"]]),t("place-content-stretch",[["place-content","stretch"]]),t("place-items-center",[["place-items","center"]]),t("place-items-start",[["place-items","start"]]),t("place-items-end",[["place-items","end"]]),t("place-items-center-safe",[["place-items","safe center"]]),t("place-items-end-safe",[["place-items","safe end"]]),t("place-items-baseline",[["place-items","baseline"]]),t("place-items-stretch",[["place-items","stretch"]]),t("content-normal",[["align-content","normal"]]),t("content-center",[["align-content","center"]]),t("content-start",[["align-content","flex-start"]]),t("content-end",[["align-content","flex-end"]]),t("content-center-safe",[["align-content","safe center"]]),t("content-end-safe",[["align-content","safe flex-end"]]),t("content-between",[["align-content","space-between"]]),t("content-around",[["align-content","space-around"]]),t("content-evenly",[["align-content","space-evenly"]]),t("content-baseline",[["align-content","baseline"]]),t("content-stretch",[["align-content","stretch"]]),t("items-center",[["align-items","center"]]),t("items-start",[["align-items","flex-start"]]),t("items-end",[["align-items","flex-end"]]),t("items-center-safe",[["align-items","safe center"]]),t("items-end-safe",[["align-items","safe flex-end"]]),t("items-baseline",[["align-items","baseline"]]),t("items-baseline-last",[["align-items","last baseline"]]),t("items-stretch",[["align-items","stretch"]]),t("justify-normal",[["justify-content","normal"]]),t("justify-center",[["justify-content","center"]]),t("justify-start",[["justify-content","flex-start"]]),t("justify-end",[["justify-content","flex-end"]]),t("justify-center-safe",[["justify-content","safe center"]]),t("justify-end-safe",[["justify-content","safe flex-end"]]),t("justify-between",[["justify-content","space-between"]]),t("justify-around",[["justify-content","space-around"]]),t("justify-evenly",[["justify-content","space-evenly"]]),t("justify-baseline",[["justify-content","baseline"]]),t("justify-stretch",[["justify-content","stretch"]]),t("justify-items-normal",[["justify-items","normal"]]),t("justify-items-center",[["justify-items","center"]]),t("justify-items-start",[["justify-items","start"]]),t("justify-items-end",[["justify-items","end"]]),t("justify-items-center-safe",[["justify-items","safe center"]]),t("justify-items-end-safe",[["justify-items","safe end"]]),t("justify-items-stretch",[["justify-items","stretch"]]),l("gap",["--gap","--spacing"],a=>[o("gap",a)]),l("gap-x",["--gap","--spacing"],a=>[o("column-gap",a)]),l("gap-y",["--gap","--spacing"],a=>[o("row-gap",a)]),l("space-x",["--space","--spacing"],a=>{let g=(()=>{if(a==="--spacing(0)"||a==="--spacing(-0)")return!0;let v=ae.get(a);return!!(v&&v[0]===0&&(v[1]===null||He(a)))})();return[H([$("--tw-space-x-reverse","0")]),J(":where(& > :not(:last-child))",[o("--tw-sort","row-gap"),o("--tw-space-x-reverse","0"),o("margin-inline-start",g?"0":`calc(${a} * var(--tw-space-x-reverse))`),o("margin-inline-end",g?"0":`calc(${a} * calc(1 - var(--tw-space-x-reverse)))`)])]},{supportsNegative:!0}),l("space-y",["--space","--spacing"],a=>{let g=(()=>{if(a==="--spacing(0)"||a==="--spacing(-0)")return!0;let v=ae.get(a);return!!(v&&v[0]===0&&(v[1]===null||He(a)))})();return[H([$("--tw-space-y-reverse","0")]),J(":where(& > :not(:last-child))",[o("--tw-sort","column-gap"),o("--tw-space-y-reverse","0"),o("margin-block-start",g?"0":`calc(${a} * var(--tw-space-y-reverse))`),o("margin-block-end",g?"0":`calc(${a} * calc(1 - var(--tw-space-y-reverse)))`)])]},{supportsNegative:!0}),t("space-x-reverse",[()=>H([$("--tw-space-x-reverse","0")]),()=>J(":where(& > :not(:last-child))",[o("--tw-sort","row-gap"),o("--tw-space-x-reverse","1")])]),t("space-y-reverse",[()=>H([$("--tw-space-y-reverse","0")]),()=>J(":where(& > :not(:last-child))",[o("--tw-sort","column-gap"),o("--tw-space-y-reverse","1")])]),t("accent-auto",[["accent-color","auto"]]),s("accent",{themeKeys:["--accent-color","--color"],handle:a=>[o("accent-color",a)]}),s("caret",{themeKeys:["--caret-color","--color"],handle:a=>[o("caret-color",a)]}),s("divide",{themeKeys:["--divide-color","--border-color","--color"],handle:a=>[J(":where(& > :not(:last-child))",[o("--tw-sort","divide-color"),o("border-color",a)])]}),t("place-self-auto",[["place-self","auto"]]),t("place-self-start",[["place-self","start"]]),t("place-self-end",[["place-self","end"]]),t("place-self-center",[["place-self","center"]]),t("place-self-end-safe",[["place-self","safe end"]]),t("place-self-center-safe",[["place-self","safe center"]]),t("place-self-stretch",[["place-self","stretch"]]),t("self-auto",[["align-self","auto"]]),t("self-start",[["align-self","flex-start"]]),t("self-end",[["align-self","flex-end"]]),t("self-center",[["align-self","center"]]),t("self-end-safe",[["align-self","safe flex-end"]]),t("self-center-safe",[["align-self","safe center"]]),t("self-stretch",[["align-self","stretch"]]),t("self-baseline",[["align-self","baseline"]]),t("self-baseline-last",[["align-self","last baseline"]]),t("justify-self-auto",[["justify-self","auto"]]),t("justify-self-start",[["justify-self","flex-start"]]),t("justify-self-end",[["justify-self","flex-end"]]),t("justify-self-center",[["justify-self","center"]]),t("justify-self-end-safe",[["justify-self","safe flex-end"]]),t("justify-self-center-safe",[["justify-self","safe center"]]),t("justify-self-stretch",[["justify-self","stretch"]]);for(let a of["auto","hidden","clip","visible","scroll"])t(`overflow-${a}`,[["overflow",a]]),t(`overflow-x-${a}`,[["overflow-x",a]]),t(`overflow-y-${a}`,[["overflow-y",a]]);for(let a of["auto","contain","none"])t(`overscroll-${a}`,[["overscroll-behavior",a]]),t(`overscroll-x-${a}`,[["overscroll-behavior-x",a]]),t(`overscroll-y-${a}`,[["overscroll-behavior-y",a]]);t("scroll-auto",[["scroll-behavior","auto"]]),t("scroll-smooth",[["scroll-behavior","smooth"]]),t("scrollbar-auto",[["scrollbar-width","auto"]]),t("scrollbar-thin",[["scrollbar-width","thin"]]),t("scrollbar-none",[["scrollbar-width","none"]]);{let a=()=>H([$("--tw-scrollbar-thumb","#0000",""),$("--tw-scrollbar-track","#0000","")]);s("scrollbar-thumb",{themeKeys:["--color"],handle:g=>[a(),o("--tw-scrollbar-thumb",g),o("scrollbar-color","var(--tw-scrollbar-thumb) var(--tw-scrollbar-track)")]}),s("scrollbar-track",{themeKeys:["--color"],handle:g=>[a(),o("--tw-scrollbar-track",g),o("scrollbar-color","var(--tw-scrollbar-thumb) var(--tw-scrollbar-track)")]})}t("scrollbar-gutter-auto",[["scrollbar-gutter","auto"]]),t("scrollbar-gutter-stable",[["scrollbar-gutter","stable"]]),t("scrollbar-gutter-both",[["scrollbar-gutter","stable both-edges"]]),t("truncate",[["overflow","hidden"],["text-overflow","ellipsis"],["white-space","nowrap"]]),t("text-ellipsis",[["text-overflow","ellipsis"]]),t("text-clip",[["text-overflow","clip"]]),t("hyphens-none",[["-webkit-hyphens","none"],["hyphens","none"]]),t("hyphens-manual",[["-webkit-hyphens","manual"],["hyphens","manual"]]),t("hyphens-auto",[["-webkit-hyphens","auto"],["hyphens","auto"]]),t("whitespace-normal",[["white-space","normal"]]),t("whitespace-nowrap",[["white-space","nowrap"]]),t("whitespace-pre",[["white-space","pre"]]),t("whitespace-pre-line",[["white-space","pre-line"]]),t("whitespace-pre-wrap",[["white-space","pre-wrap"]]),t("whitespace-break-spaces",[["white-space","break-spaces"]]),n("tab",{handleBareValue:({value:a})=>U(a)?a:null,handle:a=>[o("tab-size",a)]}),r("tab",()=>[{values:["2","4","8"]}]),t("text-wrap",[["text-wrap","wrap"]]),t("text-nowrap",[["text-wrap","nowrap"]]),t("text-balance",[["text-wrap","balance"]]),t("text-pretty",[["text-wrap","pretty"]]),t("break-normal",[["overflow-wrap","normal"],["word-break","normal"]]),t("break-all",[["word-break","break-all"]]),t("break-keep",[["word-break","keep-all"]]),t("wrap-anywhere",[["overflow-wrap","anywhere"]]),t("wrap-break-word",[["overflow-wrap","break-word"]]),t("wrap-normal",[["overflow-wrap","normal"]]);for(let[a,g]of[["rounded",["border-radius"]],["rounded-s",["border-start-start-radius","border-end-start-radius"]],["rounded-e",["border-start-end-radius","border-end-end-radius"]],["rounded-t",["border-top-left-radius","border-top-right-radius"]],["rounded-r",["border-top-right-radius","border-bottom-right-radius"]],["rounded-b",["border-bottom-right-radius","border-bottom-left-radius"]],["rounded-l",["border-top-left-radius","border-bottom-left-radius"]],["rounded-ss",["border-start-start-radius"]],["rounded-se",["border-start-end-radius"]],["rounded-ee",["border-end-end-radius"]],["rounded-es",["border-end-start-radius"]],["rounded-tl",["border-top-left-radius"]],["rounded-tr",["border-top-right-radius"]],["rounded-br",["border-bottom-right-radius"]],["rounded-bl",["border-bottom-left-radius"]]])n(a,{themeKeys:["--radius"],handle:v=>g.map(S=>o(S,v)),staticValues:{none:g.map(v=>o(v,"0")),full:g.map(v=>o(v,"calc(infinity * 1px)"))}});t("border-solid",[["--tw-border-style","solid"],["border-style","solid"]]),t("border-dashed",[["--tw-border-style","dashed"],["border-style","dashed"]]),t("border-dotted",[["--tw-border-style","dotted"],["border-style","dotted"]]),t("border-double",[["--tw-border-style","double"],["border-style","double"]]),t("border-hidden",[["--tw-border-style","hidden"],["border-style","hidden"]]),t("border-none",[["--tw-border-style","none"],["border-style","none"]]);{let g=function(v,S){i.functional(v,x=>{if(!x.value){if(x.modifier)return;let T=e.get(["--default-border-width"])??"1px",M=S.width(T);return M?[a(),...M]:void 0}if(x.value.kind==="arbitrary"){let T=x.value.value;switch(x.value.dataType??X(T,["color","line-width","length"])){case"line-width":case"length":{if(x.modifier)return;let N=S.width(T);return N?[a(),...N]:void 0}default:return T=ne(T,x.modifier,e),T===null?void 0:S.color(T)}}{let T=oe(x,e,["--border-color","--color"]);if(T)return S.color(T)}{if(x.modifier)return;let T=e.resolve(x.value.value,["--border-width"]);if(T){let M=S.width(T);return M?[a(),...M]:void 0}if(U(x.value.value)){let M=S.width(`${x.value.value}px`);return M?[a(),...M]:void 0}}}),r(v,()=>[{values:["current","inherit","transparent"],valueThemeKeys:["--border-color","--color"],modifierThemeKeys:["--opacity"],modifiers:Array.from({length:21},(x,T)=>`${T*5}`),hasDefaultValue:!0},{values:["0","2","4","8"],valueThemeKeys:["--border-width"]}])};var R=g;let a=()=>H([$("--tw-border-style","solid")]);g("border",{width:v=>[o("border-style","var(--tw-border-style)"),o("border-width",v)],color:v=>[o("border-color",v)]}),g("border-x",{width:v=>[o("border-inline-style","var(--tw-border-style)"),o("border-inline-width",v)],color:v=>[o("border-inline-color",v)]}),g("border-y",{width:v=>[o("border-block-style","var(--tw-border-style)"),o("border-block-width",v)],color:v=>[o("border-block-color",v)]}),g("border-s",{width:v=>[o("border-inline-start-style","var(--tw-border-style)"),o("border-inline-start-width",v)],color:v=>[o("border-inline-start-color",v)]}),g("border-e",{width:v=>[o("border-inline-end-style","var(--tw-border-style)"),o("border-inline-end-width",v)],color:v=>[o("border-inline-end-color",v)]}),g("border-bs",{width:v=>[o("border-block-start-style","var(--tw-border-style)"),o("border-block-start-width",v)],color:v=>[o("border-block-start-color",v)]}),g("border-be",{width:v=>[o("border-block-end-style","var(--tw-border-style)"),o("border-block-end-width",v)],color:v=>[o("border-block-end-color",v)]}),g("border-t",{width:v=>[o("border-top-style","var(--tw-border-style)"),o("border-top-width",v)],color:v=>[o("border-top-color",v)]}),g("border-r",{width:v=>[o("border-right-style","var(--tw-border-style)"),o("border-right-width",v)],color:v=>[o("border-right-color",v)]}),g("border-b",{width:v=>[o("border-bottom-style","var(--tw-border-style)"),o("border-bottom-width",v)],color:v=>[o("border-bottom-color",v)]}),g("border-l",{width:v=>[o("border-left-style","var(--tw-border-style)"),o("border-left-width",v)],color:v=>[o("border-left-color",v)]}),n("divide-x",{defaultValue:e.get(["--default-border-width"])??"1px",themeKeys:["--divide-width","--border-width"],handleBareValue:({value:v})=>U(v)?`${v}px`:null,handle:v=>[H([$("--tw-divide-x-reverse","0")]),J(":where(& > :not(:last-child))",[o("--tw-sort","divide-x-width"),a(),o("--tw-divide-x-reverse","0"),o("border-inline-style","var(--tw-border-style)"),o("border-inline-start-width",`calc(${v} * var(--tw-divide-x-reverse))`),o("border-inline-end-width",`calc(${v} * calc(1 - var(--tw-divide-x-reverse)))`)])]}),n("divide-y",{defaultValue:e.get(["--default-border-width"])??"1px",themeKeys:["--divide-width","--border-width"],handleBareValue:({value:v})=>U(v)?`${v}px`:null,handle:v=>[H([$("--tw-divide-y-reverse","0")]),J(":where(& > :not(:last-child))",[o("--tw-sort","divide-y-width"),a(),o("--tw-divide-y-reverse","0"),o("border-bottom-style","var(--tw-border-style)"),o("border-top-style","var(--tw-border-style)"),o("border-top-width",`calc(${v} * var(--tw-divide-y-reverse))`),o("border-bottom-width",`calc(${v} * calc(1 - var(--tw-divide-y-reverse)))`)])]}),r("divide-x",()=>[{values:["0","2","4","8"],valueThemeKeys:["--divide-width","--border-width"],hasDefaultValue:!0}]),r("divide-y",()=>[{values:["0","2","4","8"],valueThemeKeys:["--divide-width","--border-width"],hasDefaultValue:!0}]),t("divide-x-reverse",[()=>H([$("--tw-divide-x-reverse","0")]),()=>J(":where(& > :not(:last-child))",[o("--tw-divide-x-reverse","1")])]),t("divide-y-reverse",[()=>H([$("--tw-divide-y-reverse","0")]),()=>J(":where(& > :not(:last-child))",[o("--tw-divide-y-reverse","1")])]);for(let v of["solid","dashed","dotted","double","none"])t(`divide-${v}`,[()=>J(":where(& > :not(:last-child))",[o("--tw-sort","divide-style"),o("--tw-border-style",v),o("border-style",v)])])}t("bg-auto",[["background-size","auto"]]),t("bg-cover",[["background-size","cover"]]),t("bg-contain",[["background-size","contain"]]),n("bg-size",{handle(a){if(a)return[o("background-size",a)]}}),t("bg-fixed",[["background-attachment","fixed"]]),t("bg-local",[["background-attachment","local"]]),t("bg-scroll",[["background-attachment","scroll"]]),t("bg-top",[["background-position","top"]]),t("bg-top-left",[["background-position","left top"]]),t("bg-top-right",[["background-position","right top"]]),t("bg-bottom",[["background-position","bottom"]]),t("bg-bottom-left",[["background-position","left bottom"]]),t("bg-bottom-right",[["background-position","right bottom"]]),t("bg-left",[["background-position","left"]]),t("bg-right",[["background-position","right"]]),t("bg-center",[["background-position","center"]]),n("bg-position",{handle(a){if(a)return[o("background-position",a)]}}),t("bg-repeat",[["background-repeat","repeat"]]),t("bg-no-repeat",[["background-repeat","no-repeat"]]),t("bg-repeat-x",[["background-repeat","repeat-x"]]),t("bg-repeat-y",[["background-repeat","repeat-y"]]),t("bg-repeat-round",[["background-repeat","round"]]),t("bg-repeat-space",[["background-repeat","space"]]),t("bg-none",[["background-image","none"]]);{let v=function(T){let M="in oklab";if(T?.kind==="named")switch(T.value){case"longer":case"shorter":case"increasing":case"decreasing":M=`in oklch ${T.value} hue`;break;default:M=`in ${T.value}`}else T?.kind==="arbitrary"&&(M=T.value);return M},S=function({negative:T}){return M=>{if(!M.value)return;if(M.value.kind==="arbitrary"){if(M.modifier)return;let G=M.value.value;return(M.value.dataType??X(G,["angle"]))==="angle"?(G=T?`calc(${G} * -1)`:`${G}`,[o("--tw-gradient-position",G),o("background-image",`linear-gradient(var(--tw-gradient-stops,${G}))`)]):T?void 0:[o("--tw-gradient-position",G),o("background-image",`linear-gradient(var(--tw-gradient-stops,${G}))`)]}let N=M.value.value;if(!T&&g.has(N))N=g.get(N);else if(U(N))N=T?`calc(${N}deg * -1)`:`${N}deg`;else return;let _=v(M.modifier);return[o("--tw-gradient-position",`${N}`),Q("@supports (background-image: linear-gradient(in lab, red, red))",[o("--tw-gradient-position",`${N} ${_}`)]),o("background-image","linear-gradient(var(--tw-gradient-stops))")]}},x=function({negative:T}){return M=>{if(M.value?.kind==="arbitrary"){if(M.modifier)return;let G=M.value.value;return[o("--tw-gradient-position",G),o("background-image",`conic-gradient(var(--tw-gradient-stops,${G}))`)]}let N=v(M.modifier);if(!M.value)return[o("--tw-gradient-position",N),o("background-image","conic-gradient(var(--tw-gradient-stops))")];let _=M.value.value;if(U(_))return _=T?`calc(${_}deg * -1)`:`${_}deg`,[o("--tw-gradient-position",`from ${_} ${N}`),o("background-image","conic-gradient(var(--tw-gradient-stops))")]}};var W=v,D=S,z=x;let a=["oklab","oklch","srgb","hsl","longer","shorter","increasing","decreasing"],g=new Map([["to-t","to top"],["to-tr","to top right"],["to-r","to right"],["to-br","to bottom right"],["to-b","to bottom"],["to-bl","to bottom left"],["to-l","to left"],["to-tl","to top left"]]);i.functional("-bg-linear",S({negative:!0})),i.functional("bg-linear",S({negative:!1})),r("bg-linear",()=>[{values:[...g.keys()],modifiers:a},{values:["0","30","60","90","120","150","180","210","240","270","300","330"],supportsNegative:!0,modifiers:a}]),i.functional("-bg-conic",x({negative:!0})),i.functional("bg-conic",x({negative:!1})),r("bg-conic",()=>[{hasDefaultValue:!0,modifiers:a},{values:["0","30","60","90","120","150","180","210","240","270","300","330"],supportsNegative:!0,modifiers:a}]),i.functional("bg-radial",T=>{if(!T.value){let M=v(T.modifier);return[o("--tw-gradient-position",M),o("background-image","radial-gradient(var(--tw-gradient-stops))")]}if(T.value.kind==="arbitrary"){if(T.modifier)return;let M=T.value.value;return[o("--tw-gradient-position",M),o("background-image",`radial-gradient(var(--tw-gradient-stops,${M}))`)]}}),r("bg-radial",()=>[{hasDefaultValue:!0,modifiers:a}])}i.functional("bg",a=>{if(a.value){if(a.value.kind==="arbitrary"){let g=a.value.value;switch(a.value.dataType??X(g,["image","color","percentage","position","bg-size","length","url"])){case"percentage":case"position":return a.modifier?void 0:[o("background-position",g)];case"bg-size":case"length":case"size":return a.modifier?void 0:[o("background-size",g)];case"image":case"url":return a.modifier?void 0:[o("background-image",g)];default:return g=ne(g,a.modifier,e),g===null?void 0:[o("background-color",g)]}}{let g=oe(a,e,["--background-color","--color"]);if(g)return[o("background-color",g)]}{if(a.modifier)return;let g=e.resolve(a.value.value,["--background-image"]);if(g)return[o("background-image",g)]}}}),r("bg",()=>[{values:["current","inherit","transparent"],valueThemeKeys:["--background-color","--color"],modifierThemeKeys:["--opacity"],modifiers:Array.from({length:21},(a,g)=>`${g*5}`)},{values:[],valueThemeKeys:["--background-image"]}]);let w=()=>H([$("--tw-gradient-position"),$("--tw-gradient-from","#0000",""),$("--tw-gradient-via","#0000",""),$("--tw-gradient-to","#0000",""),$("--tw-gradient-stops"),$("--tw-gradient-via-stops"),$("--tw-gradient-from-position","0%",""),$("--tw-gradient-via-position","50%",""),$("--tw-gradient-to-position","100%","")]);function b(a,g){i.functional(a,v=>{if(v.value){if(v.value.kind==="arbitrary"){let S=v.value.value;switch(v.value.dataType??X(S,["color","length","percentage"])){case"length":case"percentage":return v.modifier?void 0:g.position(S);default:return S=ne(S,v.modifier,e),S===null?void 0:g.color(S)}}{let S=oe(v,e,["--background-color","--color"]);if(S)return g.color(S)}{if(v.modifier)return;let S=e.resolve(v.value.value,["--gradient-color-stop-positions"]);if(S)return g.position(S);if(v.value.value[v.value.value.length-1]==="%"&&U(v.value.value.slice(0,-1)))return g.position(v.value.value)}}}),r(a,()=>[{values:["current","inherit","transparent"],valueThemeKeys:["--background-color","--color"],modifierThemeKeys:["--opacity"],modifiers:Array.from({length:21},(v,S)=>`${S*5}`)},{values:Array.from({length:21},(v,S)=>`${S*5}%`),valueThemeKeys:["--gradient-color-stop-positions"]}])}b("from",{color:a=>[w(),o("--tw-sort","--tw-gradient-from"),o("--tw-gradient-from",a),o("--tw-gradient-stops","var(--tw-gradient-via-stops, var(--tw-gradient-position), var(--tw-gradient-from) var(--tw-gradient-from-position), var(--tw-gradient-to) var(--tw-gradient-to-position))")],position:a=>[w(),o("--tw-gradient-from-position",a)]}),t("via-none",[["--tw-gradient-via-stops","initial"]]),b("via",{color:a=>[w(),o("--tw-sort","--tw-gradient-via"),o("--tw-gradient-via",a),o("--tw-gradient-via-stops","var(--tw-gradient-position), var(--tw-gradient-from) var(--tw-gradient-from-position), var(--tw-gradient-via) var(--tw-gradient-via-position), var(--tw-gradient-to) var(--tw-gradient-to-position)"),o("--tw-gradient-stops","var(--tw-gradient-via-stops)")],position:a=>[w(),o("--tw-gradient-via-position",a)]}),b("to",{color:a=>[w(),o("--tw-sort","--tw-gradient-to"),o("--tw-gradient-to",a),o("--tw-gradient-stops","var(--tw-gradient-via-stops, var(--tw-gradient-position), var(--tw-gradient-from) var(--tw-gradient-from-position), var(--tw-gradient-to) var(--tw-gradient-to-position))")],position:a=>[w(),o("--tw-gradient-to-position",a)]}),t("mask-none",[["mask-image","none"]]),i.functional("mask",a=>{if(!a.value||a.modifier||a.value.kind!=="arbitrary")return;let g=a.value.value;switch(a.value.dataType??X(g,["image","percentage","position","bg-size","length","url"])){case"percentage":case"position":return a.modifier?void 0:[o("mask-position",g)];case"bg-size":case"length":case"size":return[o("mask-size",g)];default:return[o("mask-image",g)]}}),t("mask-add",[["mask-composite","add"]]),t("mask-subtract",[["mask-composite","subtract"]]),t("mask-intersect",[["mask-composite","intersect"]]),t("mask-exclude",[["mask-composite","exclude"]]),t("mask-alpha",[["mask-mode","alpha"]]),t("mask-luminance",[["mask-mode","luminance"]]),t("mask-match",[["mask-mode","match-source"]]),t("mask-type-alpha",[["mask-type","alpha"]]),t("mask-type-luminance",[["mask-type","luminance"]]),t("mask-auto",[["mask-size","auto"]]),t("mask-cover",[["mask-size","cover"]]),t("mask-contain",[["mask-size","contain"]]),n("mask-size",{handle(a){if(a)return[o("mask-size",a)]}}),t("mask-top",[["mask-position","top"]]),t("mask-top-left",[["mask-position","left top"]]),t("mask-top-right",[["mask-position","right top"]]),t("mask-bottom",[["mask-position","bottom"]]),t("mask-bottom-left",[["mask-position","left bottom"]]),t("mask-bottom-right",[["mask-position","right bottom"]]),t("mask-left",[["mask-position","left"]]),t("mask-right",[["mask-position","right"]]),t("mask-center",[["mask-position","center"]]),n("mask-position",{handle(a){if(a)return[o("mask-position",a)]}}),t("mask-repeat",[["mask-repeat","repeat"]]),t("mask-no-repeat",[["mask-repeat","no-repeat"]]),t("mask-repeat-x",[["mask-repeat","repeat-x"]]),t("mask-repeat-y",[["mask-repeat","repeat-y"]]),t("mask-repeat-round",[["mask-repeat","round"]]),t("mask-repeat-space",[["mask-repeat","space"]]),t("mask-clip-border",[["mask-clip","border-box"]]),t("mask-clip-padding",[["mask-clip","padding-box"]]),t("mask-clip-content",[["mask-clip","content-box"]]),t("mask-clip-fill",[["mask-clip","fill-box"]]),t("mask-clip-stroke",[["mask-clip","stroke-box"]]),t("mask-clip-view",[["mask-clip","view-box"]]),t("mask-no-clip",[["mask-clip","no-clip"]]),t("mask-origin-border",[["mask-origin","border-box"]]),t("mask-origin-padding",[["mask-origin","padding-box"]]),t("mask-origin-content",[["mask-origin","content-box"]]),t("mask-origin-fill",[["mask-origin","fill-box"]]),t("mask-origin-stroke",[["mask-origin","stroke-box"]]),t("mask-origin-view",[["mask-origin","view-box"]]);let k=()=>H([$("--tw-mask-linear","linear-gradient(#fff, #fff)"),$("--tw-mask-radial","linear-gradient(#fff, #fff)"),$("--tw-mask-conic","linear-gradient(#fff, #fff)")]);function A(a,g){i.functional(a,v=>{if(v.value){if(v.value.kind==="arbitrary"){let S=v.value.value;switch(v.value.dataType??X(S,["length","percentage","color"])){case"color":return S=ne(S,v.modifier,e),S===null?void 0:g.color(S);case"percentage":return v.modifier||!U(S.slice(0,-1))?void 0:g.position(S);default:return v.modifier?void 0:g.position(S)}}{let S=oe(v,e,["--background-color","--color"]);if(S)return g.color(S)}{if(v.modifier)return;let S=X(v.value.value,["number","percentage"]);if(!S)return;switch(S){case"number":return!e.resolve(null,["--spacing"])||!te(v.value.value)?void 0:g.position(`--spacing(${v.value.value})`);case"percentage":return U(v.value.value.slice(0,-1))?g.position(v.value.value):void 0;default:return}}}}),r(a,()=>[{values:["current","inherit","transparent"],valueThemeKeys:["--background-color","--color"],modifierThemeKeys:["--opacity"],modifiers:Array.from({length:21},(v,S)=>`${S*5}`)},{values:Array.from({length:21},(v,S)=>`${S*5}%`),valueThemeKeys:["--gradient-color-stop-positions"]}]),r(a,()=>[{values:Array.from({length:21},(v,S)=>`${S*5}%`)},{values:e.get(["--spacing"])?$t:[]},{values:["current","inherit","transparent"],valueThemeKeys:["--background-color","--color"],modifierThemeKeys:["--opacity"],modifiers:Array.from({length:21},(v,S)=>`${S*5}`)}])}let C=()=>H([$("--tw-mask-left","linear-gradient(#fff, #fff)"),$("--tw-mask-right","linear-gradient(#fff, #fff)"),$("--tw-mask-bottom","linear-gradient(#fff, #fff)"),$("--tw-mask-top","linear-gradient(#fff, #fff)")]);function y(a,g,v){A(a,{color(S){let x=[k(),C(),o("mask-image","var(--tw-mask-linear), var(--tw-mask-radial), var(--tw-mask-conic)"),o("mask-composite","intersect"),o("--tw-mask-linear","var(--tw-mask-left), var(--tw-mask-right), var(--tw-mask-bottom), var(--tw-mask-top)")];for(let T of["top","right","bottom","left"])v[T]&&(x.push(o(`--tw-mask-${T}`,`linear-gradient(to ${T}, var(--tw-mask-${T}-from-color) var(--tw-mask-${T}-from-position), var(--tw-mask-${T}-to-color) var(--tw-mask-${T}-to-position))`)),x.push(H([$(`--tw-mask-${T}-from-position`,"0%"),$(`--tw-mask-${T}-to-position`,"100%"),$(`--tw-mask-${T}-from-color`,"black"),$(`--tw-mask-${T}-to-color`,"transparent")])),x.push(o(`--tw-mask-${T}-${g}-color`,S)));return x},position(S){let x=[k(),C(),o("mask-image","var(--tw-mask-linear), var(--tw-mask-radial), var(--tw-mask-conic)"),o("mask-composite","intersect"),o("--tw-mask-linear","var(--tw-mask-left), var(--tw-mask-right), var(--tw-mask-bottom), var(--tw-mask-top)")];for(let T of["top","right","bottom","left"])v[T]&&(x.push(o(`--tw-mask-${T}`,`linear-gradient(to ${T}, var(--tw-mask-${T}-from-color) var(--tw-mask-${T}-from-position), var(--tw-mask-${T}-to-color) var(--tw-mask-${T}-to-position))`)),x.push(H([$(`--tw-mask-${T}-from-position`,"0%"),$(`--tw-mask-${T}-to-position`,"100%"),$(`--tw-mask-${T}-from-color`,"black"),$(`--tw-mask-${T}-to-color`,"transparent")])),x.push(o(`--tw-mask-${T}-${g}-position`,S)));return x}})}y("mask-x-from","from",{top:!1,right:!0,bottom:!1,left:!0}),y("mask-x-to","to",{top:!1,right:!0,bottom:!1,left:!0}),y("mask-y-from","from",{top:!0,right:!1,bottom:!0,left:!1}),y("mask-y-to","to",{top:!0,right:!1,bottom:!0,left:!1}),y("mask-t-from","from",{top:!0,right:!1,bottom:!1,left:!1}),y("mask-t-to","to",{top:!0,right:!1,bottom:!1,left:!1}),y("mask-r-from","from",{top:!1,right:!0,bottom:!1,left:!1}),y("mask-r-to","to",{top:!1,right:!0,bottom:!1,left:!1}),y("mask-b-from","from",{top:!1,right:!1,bottom:!0,left:!1}),y("mask-b-to","to",{top:!1,right:!1,bottom:!0,left:!1}),y("mask-l-from","from",{top:!1,right:!1,bottom:!1,left:!0}),y("mask-l-to","to",{top:!1,right:!1,bottom:!1,left:!0});let E=()=>H([$("--tw-mask-linear-position","0deg"),$("--tw-mask-linear-from-position","0%"),$("--tw-mask-linear-to-position","100%"),$("--tw-mask-linear-from-color","black"),$("--tw-mask-linear-to-color","transparent")]);n("mask-linear",{defaultValue:null,supportsNegative:!0,supportsFractions:!1,handleBareValue({value:a}){if(!U(a))return null;let g=Number(a);return g===0?"0deg":g===1?"1deg":`calc(1deg * ${a})`},handleNegativeBareValue({value:a}){if(!U(a))return null;let g=Number(a);return g===0?"0deg":g===1?"-1deg":`calc(1deg * -${a})`},handle:a=>[k(),E(),o("mask-image","var(--tw-mask-linear), var(--tw-mask-radial), var(--tw-mask-conic)"),o("mask-composite","intersect"),o("--tw-mask-linear","linear-gradient(var(--tw-mask-linear-stops, var(--tw-mask-linear-position)))"),o("--tw-mask-linear-position",a)]}),r("mask-linear",()=>[{supportsNegative:!0,values:["0","1","2","3","6","12","45","90","180"]}]),A("mask-linear-from",{color:a=>[k(),E(),o("mask-image","var(--tw-mask-linear), var(--tw-mask-radial), var(--tw-mask-conic)"),o("mask-composite","intersect"),o("--tw-mask-linear-stops","var(--tw-mask-linear-position), var(--tw-mask-linear-from-color) var(--tw-mask-linear-from-position), var(--tw-mask-linear-to-color) var(--tw-mask-linear-to-position)"),o("--tw-mask-linear","linear-gradient(var(--tw-mask-linear-stops))"),o("--tw-mask-linear-from-color",a)],position:a=>[k(),E(),o("mask-image","var(--tw-mask-linear), var(--tw-mask-radial), var(--tw-mask-conic)"),o("mask-composite","intersect"),o("--tw-mask-linear-stops","var(--tw-mask-linear-position), var(--tw-mask-linear-from-color) var(--tw-mask-linear-from-position), var(--tw-mask-linear-to-color) var(--tw-mask-linear-to-position)"),o("--tw-mask-linear","linear-gradient(var(--tw-mask-linear-stops))"),o("--tw-mask-linear-from-position",a)]}),A("mask-linear-to",{color:a=>[k(),E(),o("mask-image","var(--tw-mask-linear), var(--tw-mask-radial), var(--tw-mask-conic)"),o("mask-composite","intersect"),o("--tw-mask-linear-stops","var(--tw-mask-linear-position), var(--tw-mask-linear-from-color) var(--tw-mask-linear-from-position), var(--tw-mask-linear-to-color) var(--tw-mask-linear-to-position)"),o("--tw-mask-linear","linear-gradient(var(--tw-mask-linear-stops))"),o("--tw-mask-linear-to-color",a)],position:a=>[k(),E(),o("mask-image","var(--tw-mask-linear), var(--tw-mask-radial), var(--tw-mask-conic)"),o("mask-composite","intersect"),o("--tw-mask-linear-stops","var(--tw-mask-linear-position), var(--tw-mask-linear-from-color) var(--tw-mask-linear-from-position), var(--tw-mask-linear-to-color) var(--tw-mask-linear-to-position)"),o("--tw-mask-linear","linear-gradient(var(--tw-mask-linear-stops))"),o("--tw-mask-linear-to-position",a)]});let O=()=>H([$("--tw-mask-radial-from-position","0%"),$("--tw-mask-radial-to-position","100%"),$("--tw-mask-radial-from-color","black"),$("--tw-mask-radial-to-color","transparent"),$("--tw-mask-radial-shape","ellipse"),$("--tw-mask-radial-size","farthest-corner"),$("--tw-mask-radial-position","center")]);t("mask-circle",[["--tw-mask-radial-shape","circle"]]),t("mask-ellipse",[["--tw-mask-radial-shape","ellipse"]]),t("mask-radial-closest-side",[["--tw-mask-radial-size","closest-side"]]),t("mask-radial-farthest-side",[["--tw-mask-radial-size","farthest-side"]]),t("mask-radial-closest-corner",[["--tw-mask-radial-size","closest-corner"]]),t("mask-radial-farthest-corner",[["--tw-mask-radial-size","farthest-corner"]]),t("mask-radial-at-top",[["--tw-mask-radial-position","top"]]),t("mask-radial-at-top-left",[["--tw-mask-radial-position","top left"]]),t("mask-radial-at-top-right",[["--tw-mask-radial-position","top right"]]),t("mask-radial-at-bottom",[["--tw-mask-radial-position","bottom"]]),t("mask-radial-at-bottom-left",[["--tw-mask-radial-position","bottom left"]]),t("mask-radial-at-bottom-right",[["--tw-mask-radial-position","bottom right"]]),t("mask-radial-at-left",[["--tw-mask-radial-position","left"]]),t("mask-radial-at-right",[["--tw-mask-radial-position","right"]]),t("mask-radial-at-center",[["--tw-mask-radial-position","center"]]),n("mask-radial-at",{defaultValue:null,supportsNegative:!1,supportsFractions:!1,handle:a=>[o("--tw-mask-radial-position",a)]}),n("mask-radial",{defaultValue:null,supportsNegative:!1,supportsFractions:!1,handle:a=>[k(),O(),o("mask-image","var(--tw-mask-linear), var(--tw-mask-radial), var(--tw-mask-conic)"),o("mask-composite","intersect"),o("--tw-mask-radial","radial-gradient(var(--tw-mask-radial-stops, var(--tw-mask-radial-size)))"),o("--tw-mask-radial-size",a)]}),A("mask-radial-from",{color:a=>[k(),O(),o("mask-image","var(--tw-mask-linear), var(--tw-mask-radial), var(--tw-mask-conic)"),o("mask-composite","intersect"),o("--tw-mask-radial-stops","var(--tw-mask-radial-shape) var(--tw-mask-radial-size) at var(--tw-mask-radial-position), var(--tw-mask-radial-from-color) var(--tw-mask-radial-from-position), var(--tw-mask-radial-to-color) var(--tw-mask-radial-to-position)"),o("--tw-mask-radial","radial-gradient(var(--tw-mask-radial-stops))"),o("--tw-mask-radial-from-color",a)],position:a=>[k(),O(),o("mask-image","var(--tw-mask-linear), var(--tw-mask-radial), var(--tw-mask-conic)"),o("mask-composite","intersect"),o("--tw-mask-radial-stops","var(--tw-mask-radial-shape) var(--tw-mask-radial-size) at var(--tw-mask-radial-position), var(--tw-mask-radial-from-color) var(--tw-mask-radial-from-position), var(--tw-mask-radial-to-color) var(--tw-mask-radial-to-position)"),o("--tw-mask-radial","radial-gradient(var(--tw-mask-radial-stops))"),o("--tw-mask-radial-from-position",a)]}),A("mask-radial-to",{color:a=>[k(),O(),o("mask-image","var(--tw-mask-linear), var(--tw-mask-radial), var(--tw-mask-conic)"),o("mask-composite","intersect"),o("--tw-mask-radial-stops","var(--tw-mask-radial-shape) var(--tw-mask-radial-size) at var(--tw-mask-radial-position), var(--tw-mask-radial-from-color) var(--tw-mask-radial-from-position), var(--tw-mask-radial-to-color) var(--tw-mask-radial-to-position)"),o("--tw-mask-radial","radial-gradient(var(--tw-mask-radial-stops))"),o("--tw-mask-radial-to-color",a)],position:a=>[k(),O(),o("mask-image","var(--tw-mask-linear), var(--tw-mask-radial), var(--tw-mask-conic)"),o("mask-composite","intersect"),o("--tw-mask-radial-stops","var(--tw-mask-radial-shape) var(--tw-mask-radial-size) at var(--tw-mask-radial-position), var(--tw-mask-radial-from-color) var(--tw-mask-radial-from-position), var(--tw-mask-radial-to-color) var(--tw-mask-radial-to-position)"),o("--tw-mask-radial","radial-gradient(var(--tw-mask-radial-stops))"),o("--tw-mask-radial-to-position",a)]});let P=()=>H([$("--tw-mask-conic-position","0deg"),$("--tw-mask-conic-from-position","0%"),$("--tw-mask-conic-to-position","100%"),$("--tw-mask-conic-from-color","black"),$("--tw-mask-conic-to-color","transparent")]);n("mask-conic",{defaultValue:null,supportsNegative:!0,supportsFractions:!1,handleBareValue({value:a}){if(!U(a))return null;let g=Number(a);return g===0?"0deg":g===1?"1deg":`calc(1deg * ${a})`},handleNegativeBareValue({value:a}){if(!U(a))return null;let g=Number(a);return g===0?"0deg":g===1?"-1deg":`calc(1deg * -${a})`},handle:a=>[k(),P(),o("mask-image","var(--tw-mask-linear), var(--tw-mask-radial), var(--tw-mask-conic)"),o("mask-composite","intersect"),o("--tw-mask-conic","conic-gradient(var(--tw-mask-conic-stops, var(--tw-mask-conic-position)))"),o("--tw-mask-conic-position",a)]}),r("mask-conic",()=>[{supportsNegative:!0,values:["0","1","2","3","6","12","45","90","180"]}]),A("mask-conic-from",{color:a=>[k(),P(),o("mask-image","var(--tw-mask-linear), var(--tw-mask-radial), var(--tw-mask-conic)"),o("mask-composite","intersect"),o("--tw-mask-conic-stops","from var(--tw-mask-conic-position), var(--tw-mask-conic-from-color) var(--tw-mask-conic-from-position), var(--tw-mask-conic-to-color) var(--tw-mask-conic-to-position)"),o("--tw-mask-conic","conic-gradient(var(--tw-mask-conic-stops))"),o("--tw-mask-conic-from-color",a)],position:a=>[k(),P(),o("mask-image","var(--tw-mask-linear), var(--tw-mask-radial), var(--tw-mask-conic)"),o("mask-composite","intersect"),o("--tw-mask-conic-stops","from var(--tw-mask-conic-position), var(--tw-mask-conic-from-color) var(--tw-mask-conic-from-position), var(--tw-mask-conic-to-color) var(--tw-mask-conic-to-position)"),o("--tw-mask-conic","conic-gradient(var(--tw-mask-conic-stops))"),o("--tw-mask-conic-from-position",a)]}),A("mask-conic-to",{color:a=>[k(),P(),o("mask-image","var(--tw-mask-linear), var(--tw-mask-radial), var(--tw-mask-conic)"),o("mask-composite","intersect"),o("--tw-mask-conic-stops","from var(--tw-mask-conic-position), var(--tw-mask-conic-from-color) var(--tw-mask-conic-from-position), var(--tw-mask-conic-to-color) var(--tw-mask-conic-to-position)"),o("--tw-mask-conic","conic-gradient(var(--tw-mask-conic-stops))"),o("--tw-mask-conic-to-color",a)],position:a=>[k(),P(),o("mask-image","var(--tw-mask-linear), var(--tw-mask-radial), var(--tw-mask-conic)"),o("mask-composite","intersect"),o("--tw-mask-conic-stops","from var(--tw-mask-conic-position), var(--tw-mask-conic-from-color) var(--tw-mask-conic-from-position), var(--tw-mask-conic-to-color) var(--tw-mask-conic-to-position)"),o("--tw-mask-conic","conic-gradient(var(--tw-mask-conic-stops))"),o("--tw-mask-conic-to-position",a)]}),t("box-decoration-slice",[["-webkit-box-decoration-break","slice"],["box-decoration-break","slice"]]),t("box-decoration-clone",[["-webkit-box-decoration-break","clone"],["box-decoration-break","clone"]]),t("bg-clip-text",[["background-clip","text"]]),t("bg-clip-border",[["background-clip","border-box"]]),t("bg-clip-padding",[["background-clip","padding-box"]]),t("bg-clip-content",[["background-clip","content-box"]]),t("bg-origin-border",[["background-origin","border-box"]]),t("bg-origin-padding",[["background-origin","padding-box"]]),t("bg-origin-content",[["background-origin","content-box"]]);for(let a of["normal","multiply","screen","overlay","darken","lighten","color-dodge","color-burn","hard-light","soft-light","difference","exclusion","hue","saturation","color","luminosity"])t(`bg-blend-${a}`,[["background-blend-mode",a]]),t(`mix-blend-${a}`,[["mix-blend-mode",a]]);t("mix-blend-plus-darker",[["mix-blend-mode","plus-darker"]]),t("mix-blend-plus-lighter",[["mix-blend-mode","plus-lighter"]]),t("fill-none",[["fill","none"]]),i.functional("fill",a=>{if(!a.value)return;if(a.value.kind==="arbitrary"){let v=ne(a.value.value,a.modifier,e);return v===null?void 0:[o("fill",v)]}let g=oe(a,e,["--fill","--color"]);if(g)return[o("fill",g)]}),r("fill",()=>[{values:["current","inherit","transparent"],valueThemeKeys:["--fill","--color"],modifierThemeKeys:["--opacity"],modifiers:Array.from({length:21},(a,g)=>`${g*5}`)}]),t("stroke-none",[["stroke","none"]]),i.functional("stroke",a=>{if(a.value){if(a.value.kind==="arbitrary"){let g=a.value.value;switch(a.value.dataType??X(g,["color","number","length","percentage"])){case"number":case"length":case"percentage":return a.modifier?void 0:[o("stroke-width",g)];default:return g=ne(a.value.value,a.modifier,e),g===null?void 0:[o("stroke",g)]}}{let g=oe(a,e,["--stroke","--color"]);if(g)return[o("stroke",g)]}{if(a.modifier)return;let g=e.resolve(a.value.value,["--stroke-width"]);if(g)return[o("stroke-width",g)];if(U(a.value.value))return[o("stroke-width",a.value.value)]}}}),r("stroke",()=>[{values:["current","inherit","transparent"],valueThemeKeys:["--stroke","--color"],modifierThemeKeys:["--opacity"],modifiers:Array.from({length:21},(a,g)=>`${g*5}`)},{values:["0","1","2","3"],valueThemeKeys:["--stroke-width"]}]),t("object-contain",[["object-fit","contain"]]),t("object-cover",[["object-fit","cover"]]),t("object-fill",[["object-fit","fill"]]),t("object-none",[["object-fit","none"]]),t("object-scale-down",[["object-fit","scale-down"]]),n("object",{themeKeys:["--object-position"],handle:a=>[o("object-position",a)],staticValues:{top:[o("object-position","top")],"top-left":[o("object-position","left top")],"top-right":[o("object-position","right top")],bottom:[o("object-position","bottom")],"bottom-left":[o("object-position","left bottom")],"bottom-right":[o("object-position","right bottom")],left:[o("object-position","left")],right:[o("object-position","right")],center:[o("object-position","center")]}});for(let[a,g]of[["p","padding"],["px","padding-inline"],["py","padding-block"],["ps","padding-inline-start"],["pe","padding-inline-end"],["pbs","padding-block-start"],["pbe","padding-block-end"],["pt","padding-top"],["pr","padding-right"],["pb","padding-bottom"],["pl","padding-left"]])l(a,["--padding","--spacing"],v=>[o(g,v)]);t("text-left",[["text-align","left"]]),t("text-center",[["text-align","center"]]),t("text-right",[["text-align","right"]]),t("text-justify",[["text-align","justify"]]),t("text-start",[["text-align","start"]]),t("text-end",[["text-align","end"]]),l("indent",["--text-indent","--spacing"],a=>[o("text-indent",a)],{supportsNegative:!0}),t("align-baseline",[["vertical-align","baseline"]]),t("align-top",[["vertical-align","top"]]),t("align-middle",[["vertical-align","middle"]]),t("align-bottom",[["vertical-align","bottom"]]),t("align-text-top",[["vertical-align","text-top"]]),t("align-text-bottom",[["vertical-align","text-bottom"]]),t("align-sub",[["vertical-align","sub"]]),t("align-super",[["vertical-align","super"]]),n("align",{themeKeys:[],handle:a=>[o("vertical-align",a)]}),i.functional("font",a=>{if(!(!a.value||a.modifier)){if(a.value.kind==="arbitrary"){let g=a.value.value;switch(a.value.dataType??X(g,["number","generic-name","family-name"])){case"generic-name":case"family-name":return[o("font-family",g)];default:return[H([$("--tw-font-weight")]),o("--tw-font-weight",g),o("font-weight",g)]}}{let g=e.resolveWith(a.value.value,["--font"],["--font-feature-settings","--font-variation-settings"]);if(g){let[v,S={}]=g;return[o("font-family",v),o("font-feature-settings",S["--font-feature-settings"]),o("font-variation-settings",S["--font-variation-settings"])]}}{let g=e.resolve(a.value.value,["--font-weight"]);if(g)return[H([$("--tw-font-weight")]),o("--tw-font-weight",g),o("font-weight",g)]}}}),r("font",()=>[{values:[],valueThemeKeys:["--font"]},{values:[],valueThemeKeys:["--font-weight"]}]),n("font-features",{themeKeys:[],handle:a=>[o("font-feature-settings",a)]}),t("uppercase",[["text-transform","uppercase"]]),t("lowercase",[["text-transform","lowercase"]]),t("capitalize",[["text-transform","capitalize"]]),t("normal-case",[["text-transform","none"]]),t("italic",[["font-style","italic"]]),t("not-italic",[["font-style","normal"]]),t("underline",[["text-decoration-line","underline"]]),t("overline",[["text-decoration-line","overline"]]),t("line-through",[["text-decoration-line","line-through"]]),t("no-underline",[["text-decoration-line","none"]]),t("font-stretch-normal",[["font-stretch","normal"]]),t("font-stretch-ultra-condensed",[["font-stretch","ultra-condensed"]]),t("font-stretch-extra-condensed",[["font-stretch","extra-condensed"]]),t("font-stretch-condensed",[["font-stretch","condensed"]]),t("font-stretch-semi-condensed",[["font-stretch","semi-condensed"]]),t("font-stretch-semi-expanded",[["font-stretch","semi-expanded"]]),t("font-stretch-expanded",[["font-stretch","expanded"]]),t("font-stretch-extra-expanded",[["font-stretch","extra-expanded"]]),t("font-stretch-ultra-expanded",[["font-stretch","ultra-expanded"]]),n("font-stretch",{handleBareValue:({value:a})=>{if(!a.endsWith("%"))return null;let g=Number(a.slice(0,-1));return!U(g)||Number.isNaN(g)||g<50||g>200?null:a},handle:a=>[o("font-stretch",a)]}),r("font-stretch",()=>[{values:["50%","75%","90%","95%","100%","105%","110%","125%","150%","200%"]}]),s("placeholder",{themeKeys:["--placeholder-color","--color"],handle:a=>[J("&::placeholder",[o("--tw-sort","placeholder-color"),o("color",a)])]}),t("decoration-solid",[["text-decoration-style","solid"]]),t("decoration-double",[["text-decoration-style","double"]]),t("decoration-dotted",[["text-decoration-style","dotted"]]),t("decoration-dashed",[["text-decoration-style","dashed"]]),t("decoration-wavy",[["text-decoration-style","wavy"]]),t("decoration-auto",[["text-decoration-thickness","auto"]]),t("decoration-from-font",[["text-decoration-thickness","from-font"]]),i.functional("decoration",a=>{if(a.value){if(a.value.kind==="arbitrary"){let g=a.value.value;switch(a.value.dataType??X(g,["color","length","percentage"])){case"length":case"percentage":return a.modifier?void 0:[o("text-decoration-thickness",g)];default:return g=ne(g,a.modifier,e),g===null?void 0:[o("text-decoration-color",g)]}}{let g=e.resolve(a.value.value,["--text-decoration-thickness"]);if(g)return a.modifier?void 0:[o("text-decoration-thickness",g)];if(U(a.value.value))return a.modifier?void 0:[o("text-decoration-thickness",`${a.value.value}px`)]}{let g=oe(a,e,["--text-decoration-color","--color"]);if(g)return[o("text-decoration-color",g)]}}}),r("decoration",()=>[{values:["current","inherit","transparent"],valueThemeKeys:["--text-decoration-color","--color"],modifierThemeKeys:["--opacity"],modifiers:Array.from({length:21},(a,g)=>`${g*5}`)},{values:["0","1","2"],valueThemeKeys:["--text-decoration-thickness"]}]),n("animate",{themeKeys:["--animate"],handle:a=>[o("animation",a)],staticValues:{none:[o("animation","none")]}});{let a=["var(--tw-blur, )","var(--tw-brightness, )","var(--tw-contrast, )","var(--tw-grayscale, )","var(--tw-hue-rotate, )","var(--tw-invert, )","var(--tw-saturate, )","var(--tw-sepia, )","var(--tw-drop-shadow, )"].join(" "),g=["var(--tw-backdrop-blur, )","var(--tw-backdrop-brightness, )","var(--tw-backdrop-contrast, )","var(--tw-backdrop-grayscale, )","var(--tw-backdrop-hue-rotate, )","var(--tw-backdrop-invert, )","var(--tw-backdrop-opacity, )","var(--tw-backdrop-saturate, )","var(--tw-backdrop-sepia, )"].join(" "),v=()=>H([$("--tw-blur"),$("--tw-brightness"),$("--tw-contrast"),$("--tw-grayscale"),$("--tw-hue-rotate"),$("--tw-invert"),$("--tw-opacity"),$("--tw-saturate"),$("--tw-sepia"),$("--tw-drop-shadow"),$("--tw-drop-shadow-color"),$("--tw-drop-shadow-alpha","100%",""),$("--tw-drop-shadow-size")]),S=()=>H([$("--tw-backdrop-blur"),$("--tw-backdrop-brightness"),$("--tw-backdrop-contrast"),$("--tw-backdrop-grayscale"),$("--tw-backdrop-hue-rotate"),$("--tw-backdrop-invert"),$("--tw-backdrop-opacity"),$("--tw-backdrop-saturate"),$("--tw-backdrop-sepia")]);i.functional("filter",x=>{if(!x.modifier){if(x.value===null)return[v(),o("filter",a)];if(x.value.kind==="arbitrary")return[o("filter",x.value.value)];if(x.value.value==="none")return[o("filter","none")]}}),i.functional("backdrop-filter",x=>{if(!x.modifier){if(x.value===null)return[S(),o("-webkit-backdrop-filter",g),o("backdrop-filter",g)];if(x.value.kind==="arbitrary")return[o("-webkit-backdrop-filter",x.value.value),o("backdrop-filter",x.value.value)];if(x.value.value==="none")return[o("-webkit-backdrop-filter","none"),o("backdrop-filter","none")]}}),n("blur",{themeKeys:["--blur"],handle:x=>[v(),o("--tw-blur",`blur(${x})`),o("filter",a)],staticValues:{none:[v(),o("--tw-blur"," "),o("filter",a)]}}),n("backdrop-blur",{themeKeys:["--backdrop-blur","--blur"],handle:x=>[S(),o("--tw-backdrop-blur",`blur(${x})`),o("-webkit-backdrop-filter",g),o("backdrop-filter",g)],staticValues:{none:[S(),o("--tw-backdrop-blur"," "),o("-webkit-backdrop-filter",g),o("backdrop-filter",g)]}}),n("brightness",{themeKeys:["--brightness"],handleBareValue:({value:x})=>U(x)?`${x}%`:null,handle:x=>[v(),o("--tw-brightness",`brightness(${x})`),o("filter",a)]}),n("backdrop-brightness",{themeKeys:["--backdrop-brightness","--brightness"],handleBareValue:({value:x})=>U(x)?`${x}%`:null,handle:x=>[S(),o("--tw-backdrop-brightness",`brightness(${x})`),o("-webkit-backdrop-filter",g),o("backdrop-filter",g)]}),r("brightness",()=>[{values:["0","50","75","90","95","100","105","110","125","150","200"],valueThemeKeys:["--brightness"]}]),r("backdrop-brightness",()=>[{values:["0","50","75","90","95","100","105","110","125","150","200"],valueThemeKeys:["--backdrop-brightness","--brightness"]}]),n("contrast",{themeKeys:["--contrast"],handleBareValue:({value:x})=>U(x)?`${x}%`:null,handle:x=>[v(),o("--tw-contrast",`contrast(${x})`),o("filter",a)]}),n("backdrop-contrast",{themeKeys:["--backdrop-contrast","--contrast"],handleBareValue:({value:x})=>U(x)?`${x}%`:null,handle:x=>[S(),o("--tw-backdrop-contrast",`contrast(${x})`),o("-webkit-backdrop-filter",g),o("backdrop-filter",g)]}),r("contrast",()=>[{values:["0","50","75","100","125","150","200"],valueThemeKeys:["--contrast"]}]),r("backdrop-contrast",()=>[{values:["0","50","75","100","125","150","200"],valueThemeKeys:["--backdrop-contrast","--contrast"]}]),n("grayscale",{themeKeys:["--grayscale"],handleBareValue:({value:x})=>U(x)?`${x}%`:null,defaultValue:"100%",handle:x=>[v(),o("--tw-grayscale",`grayscale(${x})`),o("filter",a)]}),n("backdrop-grayscale",{themeKeys:["--backdrop-grayscale","--grayscale"],handleBareValue:({value:x})=>U(x)?`${x}%`:null,defaultValue:"100%",handle:x=>[S(),o("--tw-backdrop-grayscale",`grayscale(${x})`),o("-webkit-backdrop-filter",g),o("backdrop-filter",g)]}),r("grayscale",()=>[{values:["0","25","50","75","100"],valueThemeKeys:["--grayscale"],hasDefaultValue:!0}]),r("backdrop-grayscale",()=>[{values:["0","25","50","75","100"],valueThemeKeys:["--backdrop-grayscale","--grayscale"],hasDefaultValue:!0}]),n("hue-rotate",{supportsNegative:!0,themeKeys:["--hue-rotate"],handleBareValue:({value:x})=>U(x)?`${x}deg`:null,handle:x=>[v(),o("--tw-hue-rotate",`hue-rotate(${x})`),o("filter",a)]}),n("backdrop-hue-rotate",{supportsNegative:!0,themeKeys:["--backdrop-hue-rotate","--hue-rotate"],handleBareValue:({value:x})=>U(x)?`${x}deg`:null,handle:x=>[S(),o("--tw-backdrop-hue-rotate",`hue-rotate(${x})`),o("-webkit-backdrop-filter",g),o("backdrop-filter",g)]}),r("hue-rotate",()=>[{values:["0","15","30","60","90","180"],valueThemeKeys:["--hue-rotate"]}]),r("backdrop-hue-rotate",()=>[{values:["0","15","30","60","90","180"],valueThemeKeys:["--backdrop-hue-rotate","--hue-rotate"]}]),n("invert",{themeKeys:["--invert"],handleBareValue:({value:x})=>U(x)?`${x}%`:null,defaultValue:"100%",handle:x=>[v(),o("--tw-invert",`invert(${x})`),o("filter",a)]}),n("backdrop-invert",{themeKeys:["--backdrop-invert","--invert"],handleBareValue:({value:x})=>U(x)?`${x}%`:null,defaultValue:"100%",handle:x=>[S(),o("--tw-backdrop-invert",`invert(${x})`),o("-webkit-backdrop-filter",g),o("backdrop-filter",g)]}),r("invert",()=>[{values:["0","25","50","75","100"],valueThemeKeys:["--invert"],hasDefaultValue:!0}]),r("backdrop-invert",()=>[{values:["0","25","50","75","100"],valueThemeKeys:["--backdrop-invert","--invert"],hasDefaultValue:!0}]),n("saturate",{themeKeys:["--saturate"],handleBareValue:({value:x})=>U(x)?`${x}%`:null,handle:x=>[v(),o("--tw-saturate",`saturate(${x})`),o("filter",a)]}),n("backdrop-saturate",{themeKeys:["--backdrop-saturate","--saturate"],handleBareValue:({value:x})=>U(x)?`${x}%`:null,handle:x=>[S(),o("--tw-backdrop-saturate",`saturate(${x})`),o("-webkit-backdrop-filter",g),o("backdrop-filter",g)]}),r("saturate",()=>[{values:["0","50","100","150","200"],valueThemeKeys:["--saturate"]}]),r("backdrop-saturate",()=>[{values:["0","50","100","150","200"],valueThemeKeys:["--backdrop-saturate","--saturate"]}]),n("sepia",{themeKeys:["--sepia"],handleBareValue:({value:x})=>U(x)?`${x}%`:null,defaultValue:"100%",handle:x=>[v(),o("--tw-sepia",`sepia(${x})`),o("filter",a)]}),n("backdrop-sepia",{themeKeys:["--backdrop-sepia","--sepia"],handleBareValue:({value:x})=>U(x)?`${x}%`:null,defaultValue:"100%",handle:x=>[S(),o("--tw-backdrop-sepia",`sepia(${x})`),o("-webkit-backdrop-filter",g),o("backdrop-filter",g)]}),r("sepia",()=>[{values:["0","50","100"],valueThemeKeys:["--sepia"],hasDefaultValue:!0}]),r("backdrop-sepia",()=>[{values:["0","50","100"],valueThemeKeys:["--backdrop-sepia","--sepia"],hasDefaultValue:!0}]),t("drop-shadow-none",[v,["--tw-drop-shadow"," "],["filter",a]]),i.functional("drop-shadow",x=>{let T;if(x.modifier&&(x.modifier.kind==="arbitrary"?T=x.modifier.value:xe(x.modifier.value)&&(T=`${x.modifier.value}%`)),!x.value){let M=e.get(["--drop-shadow"]),N=e.resolve(null,["--drop-shadow"]);return M===null||N===null||x.modifier&&!T?void 0:[v(),o("--tw-drop-shadow-alpha",T),...Ct("--tw-drop-shadow-size",M,T,_=>`var(--tw-drop-shadow-color, ${_})`),o("--tw-drop-shadow",F(N,",").map(_=>`drop-shadow(${_})`).join(" ")),o("filter",a)]}if(x.value.kind==="arbitrary"){let M=x.value.value;return(x.value.dataType??X(M,["color"]))==="color"?(M=ne(M,x.modifier,e),M===null?void 0:[v(),o("--tw-drop-shadow-color",ie(M,"var(--tw-drop-shadow-alpha)")),o("--tw-drop-shadow","var(--tw-drop-shadow-size)")]):x.modifier&&!T?void 0:[v(),o("--tw-drop-shadow-alpha",T),...Ct("--tw-drop-shadow-size",M,T,_=>`var(--tw-drop-shadow-color, ${_})`),o("--tw-drop-shadow","var(--tw-drop-shadow-size)"),o("filter",a)]}{let M=e.get([`--drop-shadow-${x.value.value}`]),N=e.resolve(x.value.value,["--drop-shadow"]);if(M&&N)return x.modifier&&!T?void 0:T?[v(),o("--tw-drop-shadow-alpha",T),...Ct("--tw-drop-shadow-size",M,T,_=>`var(--tw-drop-shadow-color, ${_})`),o("--tw-drop-shadow","var(--tw-drop-shadow-size)"),o("filter",a)]:[v(),o("--tw-drop-shadow-alpha",T),...Ct("--tw-drop-shadow-size",M,T,_=>`var(--tw-drop-shadow-color, ${_})`),o("--tw-drop-shadow",F(N,",").map(_=>`drop-shadow(${_})`).join(" ")),o("filter",a)]}{let M=oe(x,e,["--drop-shadow-color","--color"]);if(M)return M==="inherit"?[v(),o("--tw-drop-shadow-color","inherit"),o("--tw-drop-shadow","var(--tw-drop-shadow-size)")]:[v(),o("--tw-drop-shadow-color",ie(M,"var(--tw-drop-shadow-alpha)")),o("--tw-drop-shadow","var(--tw-drop-shadow-size)")]}}),r("drop-shadow",()=>[{values:["current","inherit","transparent"],valueThemeKeys:["--drop-shadow-color","--color"],modifierThemeKeys:["--opacity"],modifiers:Array.from({length:21},(x,T)=>`${T*5}`)},{valueThemeKeys:["--drop-shadow"]}]),n("backdrop-opacity",{themeKeys:["--backdrop-opacity","--opacity"],handleBareValue:({value:x})=>xe(x)?`${x}%`:null,handle:x=>[S(),o("--tw-backdrop-opacity",`opacity(${x})`),o("-webkit-backdrop-filter",g),o("backdrop-filter",g)]}),r("backdrop-opacity",()=>[{values:Array.from({length:21},(x,T)=>`${T*5}`),valueThemeKeys:["--backdrop-opacity","--opacity"]}])}{let a=`var(--tw-ease, ${e.resolve(null,["--default-transition-timing-function"])??"ease"})`,g=`var(--tw-duration, ${e.resolve(null,["--default-transition-duration"])??"0s"})`;n("transition",{defaultValue:"color, background-color, border-color, outline-color, text-decoration-color, fill, stroke, --tw-gradient-from, --tw-gradient-via, --tw-gradient-to, opacity, box-shadow, transform, translate, scale, rotate, filter, -webkit-backdrop-filter, backdrop-filter, display, content-visibility, overlay, pointer-events",themeKeys:["--transition-property"],handle:v=>[o("transition-property",v),o("transition-timing-function",a),o("transition-duration",g)],staticValues:{none:[o("transition-property","none")],all:[o("transition-property","all"),o("transition-timing-function",a),o("transition-duration",g)],colors:[o("transition-property","color, background-color, border-color, outline-color, text-decoration-color, fill, stroke, --tw-gradient-from, --tw-gradient-via, --tw-gradient-to"),o("transition-timing-function",a),o("transition-duration",g)],opacity:[o("transition-property","opacity"),o("transition-timing-function",a),o("transition-duration",g)],shadow:[o("transition-property","box-shadow"),o("transition-timing-function",a),o("transition-duration",g)],transform:[o("transition-property","transform, translate, scale, rotate"),o("transition-timing-function",a),o("transition-duration",g)]}}),t("transition-discrete",[["transition-behavior","allow-discrete"]]),t("transition-normal",[["transition-behavior","normal"]]),n("delay",{handleBareValue:({value:v})=>U(v)?`${v}ms`:null,themeKeys:["--transition-delay"],handle:v=>[o("transition-delay",v)]});{let v=()=>H([$("--tw-duration")]);t("duration-initial",[v,["--tw-duration","initial"]]),i.functional("duration",S=>{if(S.modifier||!S.value)return;let x=null;if(S.value.kind==="arbitrary"?x=S.value.value:(x=e.resolve(S.value.fraction??S.value.value,["--transition-duration"]),x===null&&U(S.value.value)&&(x=`${S.value.value}ms`)),x!==null)return[v(),o("--tw-duration",x),o("transition-duration",x)]})}r("delay",()=>[{values:["75","100","150","200","300","500","700","1000"],valueThemeKeys:["--transition-delay"]}]),r("duration",()=>[{values:["75","100","150","200","300","500","700","1000"],valueThemeKeys:["--transition-duration"]}])}{let a=()=>H([$("--tw-ease")]);n("ease",{themeKeys:["--ease"],handle:g=>[a(),o("--tw-ease",g),o("transition-timing-function",g)],staticValues:{initial:[a(),o("--tw-ease","initial")],linear:[a(),o("--tw-ease","linear"),o("transition-timing-function","linear")]}})}t("will-change-auto",[["will-change","auto"]]),t("will-change-scroll",[["will-change","scroll-position"]]),t("will-change-contents",[["will-change","contents"]]),t("will-change-transform",[["will-change","transform"]]),n("will-change",{themeKeys:[],handle:a=>[o("will-change",a)]}),t("content-none",[["--tw-content","none"],["content","none"]]),n("content",{themeKeys:["--content"],handle:a=>[H([$("--tw-content",'""')]),o("--tw-content",a),o("content","var(--tw-content)")]});{let a="var(--tw-contain-size, ) var(--tw-contain-layout, ) var(--tw-contain-paint, ) var(--tw-contain-style, )",g=()=>H([$("--tw-contain-size"),$("--tw-contain-layout"),$("--tw-contain-paint"),$("--tw-contain-style")]);t("contain-none",[["contain","none"]]),t("contain-content",[["contain","content"]]),t("contain-strict",[["contain","strict"]]),t("contain-size",[g,["--tw-contain-size","size"],["contain",a]]),t("contain-inline-size",[g,["--tw-contain-size","inline-size"],["contain",a]]),t("contain-layout",[g,["--tw-contain-layout","layout"],["contain",a]]),t("contain-paint",[g,["--tw-contain-paint","paint"],["contain",a]]),t("contain-style",[g,["--tw-contain-style","style"],["contain",a]]),n("contain",{themeKeys:[],handle:v=>[o("contain",v)]})}t("forced-color-adjust-none",[["forced-color-adjust","none"]]),t("forced-color-adjust-auto",[["forced-color-adjust","auto"]]),l("leading",["--leading","--spacing"],a=>[H([$("--tw-leading")]),o("--tw-leading",a),o("line-height",a)],{staticValues:{none:[H([$("--tw-leading")]),o("--tw-leading","1"),o("line-height","1")]}}),n("tracking",{supportsNegative:!0,themeKeys:["--tracking"],handle:a=>[H([$("--tw-tracking")]),o("--tw-tracking",a),o("letter-spacing",a)]}),t("antialiased",[["-webkit-font-smoothing","antialiased"],["-moz-osx-font-smoothing","grayscale"]]),t("subpixel-antialiased",[["-webkit-font-smoothing","auto"],["-moz-osx-font-smoothing","auto"]]);{let a="var(--tw-ordinal, ) var(--tw-slashed-zero, ) var(--tw-numeric-figure, ) var(--tw-numeric-spacing, ) var(--tw-numeric-fraction, )",g=()=>H([$("--tw-ordinal"),$("--tw-slashed-zero"),$("--tw-numeric-figure"),$("--tw-numeric-spacing"),$("--tw-numeric-fraction")]);t("normal-nums",[["font-variant-numeric","normal"]]),t("ordinal",[g,["--tw-ordinal","ordinal"],["font-variant-numeric",a]]),t("slashed-zero",[g,["--tw-slashed-zero","slashed-zero"],["font-variant-numeric",a]]),t("lining-nums",[g,["--tw-numeric-figure","lining-nums"],["font-variant-numeric",a]]),t("oldstyle-nums",[g,["--tw-numeric-figure","oldstyle-nums"],["font-variant-numeric",a]]),t("proportional-nums",[g,["--tw-numeric-spacing","proportional-nums"],["font-variant-numeric",a]]),t("tabular-nums",[g,["--tw-numeric-spacing","tabular-nums"],["font-variant-numeric",a]]),t("diagonal-fractions",[g,["--tw-numeric-fraction","diagonal-fractions"],["font-variant-numeric",a]]),t("stacked-fractions",[g,["--tw-numeric-fraction","stacked-fractions"],["font-variant-numeric",a]])}{let a=()=>H([$("--tw-outline-style","solid")]);i.static("outline-hidden",()=>[o("--tw-outline-style","none"),o("outline-style","none"),q("@media","(forced-colors: active)",[o("outline","2px solid transparent"),o("outline-offset","2px")])]),t("outline-none",[["--tw-outline-style","none"],["outline-style","none"]]),t("outline-solid",[["--tw-outline-style","solid"],["outline-style","solid"]]),t("outline-dashed",[["--tw-outline-style","dashed"],["outline-style","dashed"]]),t("outline-dotted",[["--tw-outline-style","dotted"],["outline-style","dotted"]]),t("outline-double",[["--tw-outline-style","double"],["outline-style","double"]]),i.functional("outline",g=>{if(g.value===null){if(g.modifier)return;let v=e.get(["--default-outline-width"])??"1px";return[a(),o("outline-style","var(--tw-outline-style)"),o("outline-width",v)]}if(g.value.kind==="arbitrary"){let v=g.value.value;switch(g.value.dataType??X(v,["color","length","number","percentage"])){case"length":case"number":case"percentage":return g.modifier?void 0:[a(),o("outline-style","var(--tw-outline-style)"),o("outline-width",v)];default:return v=ne(v,g.modifier,e),v===null?void 0:[o("outline-color",v)]}}{let v=oe(g,e,["--outline-color","--color"]);if(v)return[o("outline-color",v)]}{if(g.modifier)return;let v=e.resolve(g.value.value,["--outline-width"]);if(v)return[a(),o("outline-style","var(--tw-outline-style)"),o("outline-width",v)];if(U(g.value.value))return[a(),o("outline-style","var(--tw-outline-style)"),o("outline-width",`${g.value.value}px`)]}}),r("outline",()=>[{values:["current","inherit","transparent"],valueThemeKeys:["--outline-color","--color"],modifierThemeKeys:["--opacity"],modifiers:Array.from({length:21},(g,v)=>`${v*5}`),hasDefaultValue:!0},{values:["0","1","2","4","8"],valueThemeKeys:["--outline-width"]}]),n("outline-offset",{supportsNegative:!0,themeKeys:["--outline-offset"],handleBareValue:({value:g})=>U(g)?`${g}px`:null,handle:g=>[o("outline-offset",g)]}),r("outline-offset",()=>[{supportsNegative:!0,values:["0","1","2","4","8"],valueThemeKeys:["--outline-offset"]}])}n("opacity",{themeKeys:["--opacity"],handleBareValue:({value:a})=>xe(a)?`${a}%`:null,handle:a=>[o("opacity",a)]}),r("opacity",()=>[{values:Array.from({length:21},(a,g)=>`${g*5}`),valueThemeKeys:["--opacity"]}]),n("underline-offset",{supportsNegative:!0,themeKeys:["--text-underline-offset"],handleBareValue:({value:a})=>U(a)?`${a}px`:null,handle:a=>[o("text-underline-offset",a)],staticValues:{auto:[o("text-underline-offset","auto")]}}),r("underline-offset",()=>[{supportsNegative:!0,values:["0","1","2","4","8"],valueThemeKeys:["--text-underline-offset"]}]),i.functional("text",a=>{if(a.value){if(a.value.kind==="arbitrary"){let g=a.value.value;switch(a.value.dataType??X(g,["color","length","percentage","absolute-size","relative-size"])){case"size":case"length":case"percentage":case"absolute-size":case"relative-size":{if(a.modifier){let S=a.modifier.kind==="arbitrary"?a.modifier.value:e.resolve(a.modifier.value,["--leading"]);if(!S&&te(a.modifier.value)){if(!e.resolve(null,["--spacing"]))return null;S=`--spacing(${a.modifier.value})`}return!S&&a.modifier.value==="none"&&(S="1"),S?[o("font-size",g),o("line-height",S)]:null}return[o("font-size",g)]}default:return g=ne(g,a.modifier,e),g===null?void 0:[o("color",g)]}}{let g=oe(a,e,["--text-color","--color"]);if(g)return[o("color",g)]}{let g=e.resolveWith(a.value.value,["--text"],["--line-height","--letter-spacing","--font-weight"]);if(g){let[v,S={}]=Array.isArray(g)?g:[g];if(a.modifier){let x=a.modifier.kind==="arbitrary"?a.modifier.value:e.resolve(a.modifier.value,["--leading"]);if(!x&&te(a.modifier.value)){if(!e.resolve(null,["--spacing"]))return null;x=`--spacing(${a.modifier.value})`}if(!x&&a.modifier.value==="none"&&(x="1"),!x)return null;let T=[o("font-size",v)];return x&&T.push(o("line-height",x)),T}return typeof S=="string"?[o("font-size",v),o("line-height",S)]:[o("font-size",v),o("line-height",S["--line-height"]?`var(--tw-leading, ${S["--line-height"]})`:void 0),o("letter-spacing",S["--letter-spacing"]?`var(--tw-tracking, ${S["--letter-spacing"]})`:void 0),o("font-weight",S["--font-weight"]?`var(--tw-font-weight, ${S["--font-weight"]})`:void 0)]}}}}),r("text",()=>[{values:["current","inherit","transparent"],valueThemeKeys:["--text-color","--color"],modifierThemeKeys:["--opacity"],modifiers:Array.from({length:21},(a,g)=>`${g*5}`)},{values:[],valueThemeKeys:["--text"],modifiers:[],modifierThemeKeys:["--leading"]}]);let K=()=>H([$("--tw-text-shadow-color"),$("--tw-text-shadow-alpha","100%","")]);t("text-shadow-initial",[K,["--tw-text-shadow-color","initial"]]),i.functional("text-shadow",a=>{let g;if(a.modifier&&(a.modifier.kind==="arbitrary"?g=a.modifier.value:xe(a.modifier.value)&&(g=`${a.modifier.value}%`)),!a.value){let v=e.get(["--text-shadow"]);return v===null||a.modifier&&!g?void 0:[K(),o("--tw-text-shadow-alpha",g),...ye("text-shadow",v,g,S=>`var(--tw-text-shadow-color, ${S})`)]}if(a.value.kind==="arbitrary"){let v=a.value.value;return(a.value.dataType??X(v,["color"]))==="color"?(v=ne(v,a.modifier,e),v===null?void 0:[K(),o("--tw-text-shadow-color",ie(v,"var(--tw-text-shadow-alpha)"))]):a.modifier&&!g?void 0:[K(),o("--tw-text-shadow-alpha",g),...ye("text-shadow",v,g,x=>`var(--tw-text-shadow-color, ${x})`)]}switch(a.value.value){case"none":return a.modifier?void 0:[K(),o("text-shadow","none")];case"inherit":return a.modifier?void 0:[K(),o("--tw-text-shadow-color","inherit")]}{let v=e.get([`--text-shadow-${a.value.value}`]);if(v)return a.modifier&&!g?void 0:[K(),o("--tw-text-shadow-alpha",g),...ye("text-shadow",v,g,S=>`var(--tw-text-shadow-color, ${S})`)]}{let v=oe(a,e,["--text-shadow-color","--color"]);if(v)return[K(),o("--tw-text-shadow-color",ie(v,"var(--tw-text-shadow-alpha)"))]}}),r("text-shadow",()=>[{values:["current","inherit","transparent"],valueThemeKeys:["--text-shadow-color","--color"],modifierThemeKeys:["--opacity"],modifiers:Array.from({length:21},(a,g)=>`${g*5}`)},{values:["none"]},{valueThemeKeys:["--text-shadow"],modifiers:Array.from({length:21},(a,g)=>`${g*5}`),hasDefaultValue:e.get(["--text-shadow"])!==null}]);{let x=function(N){return`var(--tw-ring-inset, ) 0 0 0 calc(${N} + var(--tw-ring-offset-width)) var(--tw-ring-color, ${S})`},T=function(N){return`inset 0 0 0 ${N} var(--tw-inset-ring-color, currentcolor)`};var j=x,Z=T;let a=["var(--tw-inset-shadow)","var(--tw-inset-ring-shadow)","var(--tw-ring-offset-shadow)","var(--tw-ring-shadow)","var(--tw-shadow)"].join(", "),g="0 0 #0000",v=()=>H([$("--tw-shadow",g),$("--tw-shadow-color"),$("--tw-shadow-alpha","100%",""),$("--tw-inset-shadow",g),$("--tw-inset-shadow-color"),$("--tw-inset-shadow-alpha","100%",""),$("--tw-ring-color"),$("--tw-ring-shadow",g),$("--tw-inset-ring-color"),$("--tw-inset-ring-shadow",g),$("--tw-ring-inset"),$("--tw-ring-offset-width","0px",""),$("--tw-ring-offset-color","#fff"),$("--tw-ring-offset-shadow",g)]);t("shadow-initial",[v,["--tw-shadow-color","initial"]]),i.functional("shadow",N=>{let _;if(N.modifier&&(N.modifier.kind==="arbitrary"?_=N.modifier.value:xe(N.modifier.value)&&(_=`${N.modifier.value}%`)),!N.value){let G=e.get(["--shadow"]);return G===null||N.modifier&&!_?void 0:[v(),o("--tw-shadow-alpha",_),...ye("--tw-shadow",G,_,ve=>`var(--tw-shadow-color, ${ve})`),o("box-shadow",a)]}if(N.value.kind==="arbitrary"){let G=N.value.value;return(N.value.dataType??X(G,["color"]))==="color"?(G=ne(G,N.modifier,e),G===null?void 0:[v(),o("--tw-shadow-color",ie(G,"var(--tw-shadow-alpha)"))]):N.modifier&&!_?void 0:[v(),o("--tw-shadow-alpha",_),...ye("--tw-shadow",G,_,Ut=>`var(--tw-shadow-color, ${Ut})`),o("box-shadow",a)]}switch(N.value.value){case"none":return N.modifier?void 0:[v(),o("--tw-shadow",g),o("box-shadow",a)];case"inherit":return N.modifier?void 0:[v(),o("--tw-shadow-color","inherit")]}{let G=e.get([`--shadow-${N.value.value}`]);if(G)return N.modifier&&!_?void 0:[v(),o("--tw-shadow-alpha",_),...ye("--tw-shadow",G,_,ve=>`var(--tw-shadow-color, ${ve})`),o("box-shadow",a)]}{let G=oe(N,e,["--box-shadow-color","--color"]);if(G)return[v(),o("--tw-shadow-color",ie(G,"var(--tw-shadow-alpha)"))]}}),r("shadow",()=>[{values:["current","inherit","transparent"],valueThemeKeys:["--box-shadow-color","--color"],modifierThemeKeys:["--opacity"],modifiers:Array.from({length:21},(N,_)=>`${_*5}`)},{values:["none"]},{valueThemeKeys:["--shadow"],modifiers:Array.from({length:21},(N,_)=>`${_*5}`),hasDefaultValue:e.get(["--shadow"])!==null}]),t("inset-shadow-initial",[v,["--tw-inset-shadow-color","initial"]]),i.functional("inset-shadow",N=>{let _;if(N.modifier&&(N.modifier.kind==="arbitrary"?_=N.modifier.value:xe(N.modifier.value)&&(_=`${N.modifier.value}%`)),!N.value){let G=e.get(["--inset-shadow"]);return G===null||N.modifier&&!_?void 0:[v(),o("--tw-inset-shadow-alpha",_),...ye("--tw-inset-shadow",G,_,ve=>`var(--tw-inset-shadow-color, ${ve})`),o("box-shadow",a)]}if(N.value.kind==="arbitrary"){let G=N.value.value;return(N.value.dataType??X(G,["color"]))==="color"?(G=ne(G,N.modifier,e),G===null?void 0:[v(),o("--tw-inset-shadow-color",ie(G,"var(--tw-inset-shadow-alpha)"))]):N.modifier&&!_?void 0:[v(),o("--tw-inset-shadow-alpha",_),...ye("--tw-inset-shadow",G,_,Ut=>`var(--tw-inset-shadow-color, ${Ut})`,"inset"),o("box-shadow",a)]}switch(N.value.value){case"none":return N.modifier?void 0:[v(),o("--tw-inset-shadow",`inset ${g}`),o("box-shadow",a)];case"inherit":return N.modifier?void 0:[v(),o("--tw-inset-shadow-color","inherit")]}{let G=e.get([`--inset-shadow-${N.value.value}`]);if(G)return N.modifier&&!_?void 0:[v(),o("--tw-inset-shadow-alpha",_),...ye("--tw-inset-shadow",G,_,ve=>`var(--tw-inset-shadow-color, ${ve})`),o("box-shadow",a)]}{let G=oe(N,e,["--box-shadow-color","--color"]);if(G)return[v(),o("--tw-inset-shadow-color",ie(G,"var(--tw-inset-shadow-alpha)"))]}}),r("inset-shadow",()=>[{values:["current","inherit","transparent"],valueThemeKeys:["--box-shadow-color","--color"],modifierThemeKeys:["--opacity"],modifiers:Array.from({length:21},(N,_)=>`${_*5}`)},{values:["none"]},{valueThemeKeys:["--inset-shadow"],modifiers:Array.from({length:21},(N,_)=>`${_*5}`),hasDefaultValue:e.get(["--inset-shadow"])!==null}]),t("ring-inset",[v,["--tw-ring-inset","inset"]]);let S=e.get(["--default-ring-color"])??"currentcolor";i.functional("ring",N=>{if(!N.value){if(N.modifier)return;let _=e.get(["--default-ring-width"])??"1px";return[v(),o("--tw-ring-shadow",x(_)),o("box-shadow",a)]}if(N.value.kind==="arbitrary"){let _=N.value.value;return(N.value.dataType??X(_,["color","length"]))==="length"?N.modifier?void 0:[v(),o("--tw-ring-shadow",x(_)),o("box-shadow",a)]:(_=ne(_,N.modifier,e),_===null?void 0:[o("--tw-ring-color",_)])}{let _=oe(N,e,["--ring-color","--color"]);if(_)return[o("--tw-ring-color",_)]}{if(N.modifier)return;let _=e.resolve(N.value.value,["--ring-width"]);if(_===null&&U(N.value.value)&&(_=`${N.value.value}px`),_)return[v(),o("--tw-ring-shadow",x(_)),o("box-shadow",a)]}}),r("ring",()=>[{values:["current","inherit","transparent"],valueThemeKeys:["--ring-color","--color"],modifierThemeKeys:["--opacity"],modifiers:Array.from({length:21},(N,_)=>`${_*5}`)},{values:["0","1","2","4","8"],valueThemeKeys:["--ring-width"],hasDefaultValue:!0}]),i.functional("inset-ring",N=>{if(!N.value)return N.modifier?void 0:[v(),o("--tw-inset-ring-shadow",T("1px")),o("box-shadow",a)];if(N.value.kind==="arbitrary"){let _=N.value.value;return(N.value.dataType??X(_,["color","length"]))==="length"?N.modifier?void 0:[v(),o("--tw-inset-ring-shadow",T(_)),o("box-shadow",a)]:(_=ne(_,N.modifier,e),_===null?void 0:[o("--tw-inset-ring-color",_)])}{let _=oe(N,e,["--ring-color","--color"]);if(_)return[o("--tw-inset-ring-color",_)]}{if(N.modifier)return;let _=e.resolve(N.value.value,["--ring-width"]);if(_===null&&U(N.value.value)&&(_=`${N.value.value}px`),_)return[v(),o("--tw-inset-ring-shadow",T(_)),o("box-shadow",a)]}}),r("inset-ring",()=>[{values:["current","inherit","transparent"],valueThemeKeys:["--ring-color","--color"],modifierThemeKeys:["--opacity"],modifiers:Array.from({length:21},(N,_)=>`${_*5}`)},{values:["0","1","2","4","8"],valueThemeKeys:["--ring-width"],hasDefaultValue:!0}]);let M="var(--tw-ring-inset, ) 0 0 0 var(--tw-ring-offset-width) var(--tw-ring-offset-color)";i.functional("ring-offset",N=>{if(N.value){if(N.value.kind==="arbitrary"){let _=N.value.value;return(N.value.dataType??X(_,["color","length"]))==="length"?N.modifier?void 0:[o("--tw-ring-offset-width",_),o("--tw-ring-offset-shadow",M)]:(_=ne(_,N.modifier,e),_===null?void 0:[o("--tw-ring-offset-color",_)])}{let _=e.resolve(N.value.value,["--ring-offset-width"]);if(_)return N.modifier?void 0:[o("--tw-ring-offset-width",_),o("--tw-ring-offset-shadow",M)];if(U(N.value.value))return N.modifier?void 0:[o("--tw-ring-offset-width",`${N.value.value}px`),o("--tw-ring-offset-shadow",M)]}{let _=oe(N,e,["--ring-offset-color","--color"]);if(_)return[o("--tw-ring-offset-color",_)]}}})}return r("ring-offset",()=>[{values:["current","inherit","transparent"],valueThemeKeys:["--ring-offset-color","--color"],modifierThemeKeys:["--opacity"],modifiers:Array.from({length:21},(a,g)=>`${g*5}`)},{values:["0","1","2","4","8"],valueThemeKeys:["--ring-offset-width"]}]),i.functional("@container",a=>{let g=null;if(a.value===null?g="inline-size":a.value.kind==="arbitrary"?g=a.value.value:a.value.kind==="named"&&a.value.value==="normal"?g="normal":a.value.kind==="named"&&a.value.value==="size"&&(g="size"),g!==null)return a.modifier?[o("container-type",g),o("container-name",a.modifier.value)]:[o("container-type",g)]}),r("@container",()=>[{values:["normal"],valueThemeKeys:[],hasDefaultValue:!0}]),i}var fr=["number","integer","ratio","percentage"];function wi(e){let i=_e(e.params);return kl(i)?r=>{let t={"--value":{usedSpacingInteger:!1,usedSpacingNumber:!1,themeKeys:new Set,literals:new Set},"--modifier":{usedSpacingInteger:!1,usedSpacingNumber:!1,themeKeys:new Set,literals:new Set}};I(e.nodes,n=>{if(n.kind!=="declaration"||!n.value||!n.value.includes("--value(")&&!n.value.includes("--modifier("))return;let s=Y(n.value);I(s,l=>{if(l.kind!=="function")return;if(l.value==="--spacing"&&!(t["--modifier"].usedSpacingNumber&&t["--value"].usedSpacingNumber))return I(l.nodes,u=>{if(u.kind!=="function"||u.value!=="--value"&&u.value!=="--modifier")return;let c=u.value;for(let d of u.nodes)if(d.kind==="word"){if(d.value==="integer")t[c].usedSpacingInteger||=!0;else if(d.value==="number"&&(t[c].usedSpacingNumber||=!0,t["--modifier"].usedSpacingNumber&&t["--value"].usedSpacingNumber))return V.Stop}}),V.Continue;if(l.value!=="--value"&&l.value!=="--modifier")return;let p=F(B(l.nodes),",");for(let[u,c]of p.entries()){if(c=c.trim(),c.startsWith("--default(")){p[u]=c;continue}c=c.replace(/\\\*/g,"*"),c=c.replace(/--(.*?)\s--(.*?)/g,"--$1-*--$2"),c=c.replace(/\s+/g,""),c=c.replace(/(-\*){2,}/g,"-*"),c[0]==="-"&&c[1]==="-"&&!c.includes("(")&&!c.includes("-*")&&(c+="-*"),p[u]=c}l.nodes=Y(p.join(","));for(let[u,c]of l.nodes.entries())if(c.kind==="word"&&(c.value[0]==='"'||c.value[0]==="'")&&c.value[0]===c.value[c.value.length-1]){let d=c.value.slice(1,-1);t[l.value].literals.add(d)}else if(c.kind==="word"&&c.value[0]==="-"&&c.value[1]==="-"){let d=c.value.replace(/-\*.*$/g,"");t[l.value].themeKeys.add(d)}else if(c.kind==="word"&&!(c.value[0]==="["&&c.value[c.value.length-1]==="]")&&!fr.includes(c.value)){console.warn(`Unsupported bare value data type: "${c.value}". +Only valid data types are: ${fr.map(f=>`"${f}"`).join(", ")}. +`);let d=l.value.length+1+B(l.nodes.slice(0,u)).length,m=["```css",B([l])," ".repeat(d)+"^".repeat(c.value.length),"```"].join(` +`);console.warn(m)}}),n.value=B(s)}),r.utilities.functional(i.slice(0,-2),n=>{let s=le(e),l=n.value,p=n.modifier,u=!1,c=!1,d=!1,m=!1,f=new Map,h=!1;if(I([s],(w,b)=>{let k=b.parent;if(k?.kind!=="rule"&&k?.kind!=="at-rule"||w.kind!=="declaration"||!w.value)return;let A=!1,C=Y(w.value);if(I(C,y=>{if(y.kind==="function"){if(y.value==="--value"){u=!0;let E=mi(l,y,r);return E?(c=!0,E.ratio?h=!0:f.set(w,k),V.ReplaceSkip(E.nodes)):(A=!0,V.Stop)}else if(y.value==="--modifier"){d=!0;let E=mi(p,y,r);return E?(m=!0,V.ReplaceSkip(E.nodes)):(A=!0,V.Stop)}}}),A)return V.ReplaceSkip([]);w.value=B(C)}),!u||!c||d&&!m&&p!==null||h&&m||p&&!h&&!m)return null;if(h)for(let[w,b]of f){let k=b.nodes.indexOf(w);k!==-1&&b.nodes.splice(k,1)}return s.nodes}),r.utilities.suggest(i.slice(0,-2),()=>{let n=[],s=[];for(let[l,{literals:p,usedSpacingNumber:u,usedSpacingInteger:c,themeKeys:d}]of[[n,t["--value"]],[s,t["--modifier"]]]){for(let m of p)l.push(m);if(u)l.push(...$t);else if(c)for(let m of $t)U(m)&&l.push(m);for(let m of r.theme.keysInNamespaces(d))l.push(m.replace(hi,(f,h,w)=>`${h}.${w}`))}return[{values:n,modifiers:s}]})}:wl(i)?r=>{r.utilities.static(i,()=>e.nodes.map(le))}:null}function mi(e,i,r){if(e===null){for(let t of i.nodes)if(t.kind==="function"&&t.value==="--default")return{nodes:t.nodes};return}for(let t of i.nodes){if(e.kind==="named"&&t.kind==="word"&&(t.value[0]==="'"||t.value[0]==='"')&&t.value[t.value.length-1]===t.value[0]&&t.value.slice(1,-1)===e.value)return{nodes:Y(e.value)};if(e.kind==="named"&&t.kind==="word"&&t.value[0]==="-"&&t.value[1]==="-"){let n=t.value;if(n.endsWith("-*")){n=n.slice(0,-2);let s=r.theme.resolve(e.value,[n]);if(s)return{nodes:Y(s)}}else{let s=n.split("-*");if(s.length<=1)continue;let l=[s.shift()],p=r.theme.resolveWith(e.value,l,s);if(p){let[,u={}]=p;{let c=u[s.pop()];if(c)return{nodes:Y(c)}}}}}else if(e.kind==="named"&&t.kind==="word"){if(!fr.includes(t.value))continue;let n=t.value==="ratio"&&"fraction"in e?e.fraction:e.value;if(!n)continue;let s=X(n,[t.value]);if(s===null)continue;if(s==="ratio"){let[l,p]=F(n,"/").map(Number);if(!U(l)||!U(p))continue}else{if(s==="number"&&!te(n))continue;if(s==="percentage"&&!U(n.slice(0,-1)))continue}if(s==="ratio"){let[l,p]=F(n,"/");return{nodes:Y(`${l.trim()} / ${p.trim()}`),ratio:!0}}return{nodes:Y(n),ratio:!1}}else if(e.kind==="arbitrary"&&t.kind==="word"&&t.value[0]==="["&&t.value[t.value.length-1]==="]"){let n=t.value.slice(1,-1);if(n==="*")return{nodes:Y(e.value)};if("dataType"in e&&e.dataType&&e.dataType!==n)continue;if("dataType"in e&&e.dataType)return{nodes:Y(e.value)};if(X(e.value,[n])!==null)return{nodes:Y(e.value)}}}}function ye(e,i,r,t,n=""){let s=!1,l=it(i,u=>r==null?t(u):u.startsWith("current")?t(ie(u,r)):((u.startsWith("var(")||r.startsWith("var("))&&(s=!0),t(gi(u,r))));function p(u){return n?F(u,",").map(c=>n.trim()+" "+c.trim()).join(", "):u}return s?[o(e,p(it(i,t))),Q("@supports (color: lab(from red l a b))",[o(e,p(l))])]:[o(e,p(l))]}function Ct(e,i,r,t,n=""){let s=!1,l=F(i,",").map(p=>it(p,u=>r==null?t(u):u.startsWith("current")?t(ie(u,r)):((u.startsWith("var(")||r.startsWith("var("))&&(s=!0),t(gi(u,r))))).map(p=>`drop-shadow(${p})`).join(" ");return s?[o(e,n+F(i,",").map(p=>`drop-shadow(${it(p,t)})`).join(" ")),Q("@supports (color: lab(from red l a b))",[o(e,n+l)])]:[o(e,n+l)]}var ki=/^-?[a-z][a-zA-Z0-9_-]*/,ul=37,fl=47,cl=46,pl=97,dl=122,ml=65,gl=90,St=48,Vt=57,hl=95,vl=45;function wl(e){let i=ki.exec(e);if(i===null)return!1;let r=i[0],t=e.slice(r.length);if(t.length===0&&r.endsWith("-"))return!1;if(t.length===0)return!0;let n=!1;for(let s=0;sVt)return!1;break}case fl:{if(s===t.length-1||n)return!1;n=!0;break}case cl:{let u=(t[s-1]||r[r.length-1]||"").charCodeAt(0);if(uVt)return!1;let d=(t[s+1]||"").charCodeAt(0);if(dVt)return!1;break}case hl:case vl:continue;default:{if(l>=pl&&l<=dl||l>=ml&&l<=gl||l>=St&&l<=Vt)continue;return!1}}}return!0}function kl(e){if(!e.endsWith("-*"))return!1;e=e.slice(0,-2);let i=ki.exec(e);if(i===null)return!1;let r=i[0];return e.slice(r.length).length===0}var cr={"--alpha":bl,"--spacing":yl,"--theme":xl,theme:Al};function bl(e,i,r,...t){let[n,s]=F(r,"/").map(l=>l.trim());if(!n||!s)throw new Error(`The --alpha(\u2026) function requires a color and an alpha value, e.g.: \`--alpha(${n||"var(--my-color)"} / ${s||"50%"})\``);if(t.length>0)throw new Error(`The --alpha(\u2026) function only accepts one argument, e.g.: \`--alpha(${n||"var(--my-color)"} / ${s||"50%"})\``);return ie(n,s)}function yl(e,i,r,...t){if(!r)throw new Error("The --spacing(\u2026) function requires an argument, but received none.");if(t.length>0)throw new Error(`The --spacing(\u2026) function only accepts a single argument, but received ${t.length+1}.`);let n=e.theme.resolve(null,["--spacing"]);if(!n)throw new Error("The --spacing(\u2026) function requires that the `--spacing` theme variable exists, but it was not found.");let s=ae.get(r);if(s){if(s[0]===0)return"0px";if(s[0]===1)return n}return`calc(${n} * ${r})`}function xl(e,i,r,...t){if(!r.startsWith("--"))throw new Error("The --theme(\u2026) function can only be used with CSS variables from your theme.");let n=!1;r.endsWith(" inline")&&(n=!0,r=r.slice(0,-7)),i.kind==="at-rule"&&(n=!0);let s=e.resolveThemeValue(r,n);if(!s){if(t.length>0)return t.join(", ");throw new Error(`Could not resolve value for theme function: \`theme(${r})\`. Consider checking if the variable name is correct or provide a fallback value to silence this error.`)}if(t.length===0)return s;let l=t.join(", ");if(l==="initial")return s;if(s==="initial")return l;if(s.startsWith("var(")||s.startsWith("theme(")||s.startsWith("--theme(")){let p=Y(s);return Sl(p,l),B(p)}return s}function Al(e,i,r,...t){r=Cl(r);let n=e.resolveThemeValue(r);if(!n&&t.length>0)return t.join(", ");if(!n)throw new Error(`Could not resolve value for theme function: \`theme(${r})\`. Consider checking if the path is correct or provide a fallback value to silence this error.`);return n}var bi=new RegExp(Object.keys(cr).map(e=>`${e}\\(`).join("|"));function Me(e,i){let r=0;return I(e,t=>{if(t.kind==="declaration"&&t.value&&bi.test(t.value)){r|=8,t.value=yi(t.value,t,i);return}t.kind==="at-rule"&&(t.name==="@media"||t.name==="@custom-media"||t.name==="@container"||t.name==="@supports")&&bi.test(t.params)&&(r|=8,t.params=yi(t.params,t,i))}),r}function yi(e,i,r){let t=Y(e);return I(t,n=>{if(n.kind==="function"&&n.value in cr){let s=F(B(n.nodes).trim(),",").map(p=>p.trim()),l=cr[n.value](r,i,...s);return V.Replace(Y(l))}}),B(t)}function Cl(e){if(e[0]!=="'"&&e[0]!=='"')return e;let i="",r=e[0];for(let t=1;t{if(r.kind==="function"&&!(r.value!=="var"&&r.value!=="theme"&&r.value!=="--theme"))if(r.nodes.length===1)r.nodes.push({kind:"word",value:`, ${i}`});else{let t=r.nodes[r.nodes.length-1];t.kind==="word"&&t.value==="initial"&&(t.value=i)}})}function Tt(e,i){let r=e.length,t=i.length,n=r=48&&l<=57&&p>=48&&p<=57){let u=s,c=s+1,d=s,m=s+1;for(l=e.charCodeAt(c);l>=48&&l<=57;)l=e.charCodeAt(++c);for(p=i.charCodeAt(m);p>=48&&p<=57;)p=i.charCodeAt(++m);let f=e.slice(u,c),h=i.slice(d,m),w=Number(f)-Number(h);if(w)return w;if(fh)return 1;continue}if(l!==p)return l-p}return e.length-i.length}function We(e){if(e[0]!=="["||e[e.length-1]!=="]")return null;let i=1,r=i,t=e.length-1;for(;Fe(e.charCodeAt(i));)i++;{for(r=i;i=65&&d<=90)&&!(d>=97&&d<=122)&&!(d>=48&&d<=57)&&!(d===45||d===95)&&!(d>=128))break}if(r===i)return null}let n=e.slice(r,i);for(;Fe(e.charCodeAt(i));)i++;if(i===t)return{attribute:n,operator:null,quote:null,value:null,sensitivity:null};let s=null,l=e.charCodeAt(i);if(l===61)s="=",i++;else if((l===126||l===124||l===94||l===36||l===42)&&e.charCodeAt(i+1)===61)s=e[i]+"=",i+=2;else return null;for(;Fe(e.charCodeAt(i));)i++;if(i===t)return null;let p="",u=null;if(l=e.charCodeAt(i),l===39||l===34){u=e[i],i++,r=i;for(let d=i;d0;if(s!==p)return(s??"").localeCompare(p??"")>0}return B([e]).localeCompare(B([i]))>0}function Be(e,i=null){return Array.isArray(e)&&e.length===2&&typeof e[1]=="object"&&typeof e[1]!==null?i?e[1][i]??null:e[0]:Array.isArray(e)&&i===null?e.join(", "):typeof e=="string"&&i===null?e:null}function Ci(e,{theme:i},r){for(let t of r){let n=Ye([t]);n&&e.theme.clearNamespace(`--${n}`,4)}for(let[t,n]of $l(i)){if(typeof n!="string"&&typeof n!="number")continue;if(typeof n=="string"&&(n=n.replace(//g,"1")),t[0]==="opacity"&&(typeof n=="number"||typeof n=="string")){let l=typeof n=="string"?parseFloat(n):n;l>=0&&l<=1&&(n=l*100+"%")}let s=Ye(t);s&&e.theme.add(`--${s}`,""+n,7)}if(Object.hasOwn(i,"fontFamily")){let t=5;{let n=Be(i.fontFamily.sans);n&&e.theme.hasDefault("--font-sans")&&(e.theme.add("--default-font-family",n,t),e.theme.add("--default-font-feature-settings",Be(i.fontFamily.sans,"fontFeatureSettings")??"normal",t),e.theme.add("--default-font-variation-settings",Be(i.fontFamily.sans,"fontVariationSettings")??"normal",t))}{let n=Be(i.fontFamily.mono);n&&e.theme.hasDefault("--font-mono")&&(e.theme.add("--default-mono-font-family",n,t),e.theme.add("--default-mono-font-feature-settings",Be(i.fontFamily.mono,"fontFeatureSettings")??"normal",t),e.theme.add("--default-mono-font-variation-settings",Be(i.fontFamily.mono,"fontVariationSettings")??"normal",t))}}return i}function $l(e){let i=[];return Si(e,[],(r,t)=>{if(Rl(r))return i.push([t,r]),1;if(Pl(r)){i.push([t,r[0]]);for(let n of Reflect.ownKeys(r[1]))i.push([[...t,`-${n}`],r[1][n]]);return 1}if(Array.isArray(r)&&r.every(n=>typeof n=="string"))return t[0]==="fontSize"?(i.push([t,r[0]]),r.length>=2&&i.push([[...t,"-line-height"],r[1]])):i.push([t,r.join(", ")]),1}),i}var Tl={borderWidth:"border-width",outlineWidth:"outline-width",ringColor:"ring-color",ringWidth:"ring-width",transitionDuration:"transition-duration",transitionTimingFunction:"transition-timing-function"},Nl={animation:"animate",aspectRatio:"aspect",borderRadius:"radius",boxShadow:"shadow",colors:"color",containers:"container",fontFamily:"font",fontSize:"text",letterSpacing:"tracking",lineHeight:"leading",maxWidth:"container",screens:"breakpoint",transitionTimingFunction:"ease"},El=/^[a-zA-Z0-9-_%/.]+$/;function Ye(e){let i=Tl[e[0]];if(i&&e[1]==="DEFAULT")return`default-${i}`;if(e[0]==="container")return null;for(let t of e)if(!El.test(t))return null;let r=Nl[e[0]];return r&&(e=e.slice(),e[0]=r),e.map((t,n,s)=>t==="1"&&n!==s.length-1?"":t).map((t,n)=>(t=t.replaceAll(".","_"),(n===0||t.startsWith("-")||t==="lineHeight")&&(t=t.replace(/([a-z])([A-Z])/g,(l,p,u)=>`${p}-${u.toLowerCase()}`)),t)).filter((t,n)=>t!=="DEFAULT"||n!==e.length-1).join("-")}function Rl(e){return typeof e=="number"||typeof e=="string"}function Pl(e){if(!Array.isArray(e)||e.length!==2||typeof e[0]!="string"&&typeof e[0]!="number"||e[1]===void 0||e[1]===null||typeof e[1]!="object")return!1;for(let i of Reflect.ownKeys(e[1]))if(typeof i!="string"||typeof e[1][i]!="string"&&typeof e[1][i]!="number")return!1;return!0}function Si(e,i=[],r){for(let t of Reflect.ownKeys(e)){let n=e[t];if(n==null)continue;let s=[...i,t],l=r(n,s)??0;if(l!==1){if(l===2)return 2;if(!(!Array.isArray(n)&&typeof n!="object")&&Si(n,s,r)===2)return 2}}}function nt(e,i=null,r=!0){let[t,n]=lt(Y(e),i,r);return t?B(n):e}function lt(e,i=null,r=!0){let t=!1;return I(e,{exit(n,s){if(n.kind==="word"&&n.value!=="0"){let l=Vi(n.value,i,r);if(l===null||l===n.value)return;if(l==="0"&&s.parent?.kind==="function"){let p=Vi(n.value,i,!1);return p===null?void 0:(t=!0,V.ReplaceSkip(re(p)))}return t=!0,V.ReplaceSkip(re(l))}else if(n.kind==="function"&&(n.value==="calc"||n.value==="")){if(n.nodes.length!==5||n.nodes[2].kind!=="word")return;let l=n.nodes[0],p=n.nodes[2].value,u=n.nodes[4],c=l.kind==="word"?ae.get(l.value):null,d=u.kind==="word"?ae.get(u.value):null;if(p==="*"&&(c?.[0]===0&&c?.[1]===null||d?.[0]===0&&d?.[1]===null))return t=!0,V.ReplaceSkip(re("0"));if(p==="*"&&c?.[0]===0&&c?.[1]!==null&&d?.[1]===null)return t=!0,s.parent?.kind==="function"?V.ReplaceSkip(re(`0${c[1]}`)):V.ReplaceSkip(re("0"));if(p==="*"&&d?.[0]===0&&d?.[1]!==null&&c?.[1]===null)return t=!0,s.parent?.kind==="function"?V.ReplaceSkip(re(`0${d[1]}`)):V.ReplaceSkip(re("0"));if(p==="*"){if(c?.[0]===1&&c?.[1]===null)return t=!0,V.ReplaceSkip(u);if(d?.[0]===1&&d?.[1]===null)return t=!0,V.ReplaceSkip(l)}if(p==="*"||p==="+"){let m=c??d,f=c===null?l:d===null?u:null;if(m!==null&&f!==null&&f.kind==="function"&&(f.value==="calc"||f.value==="")&&f.nodes.length===5&&f.nodes[2].kind==="word"&&f.nodes[2].value===p){let h=f.nodes[0],w=f.nodes[4],b=h.kind==="word"?ae.get(h.value):null,k=w.kind==="word"?ae.get(w.value):null,A=b??k,C=b===null?h:k===null?w:null;if(A!==null&&C!==null){if(p==="*"&&!(m[1]===null&&A[1]===null||m[1]===null&&A[1]!==null||m[1]!==null&&A[1]===null)||p==="+"&&m[1]!==A[1])return;let y;switch(p){case"*":{y=`${m[0]*A[0]}${m[1]??A[1]??""}`;break}case"+":{y=`${m[0]+A[0]}${m[1]??A[1]??""}`;break}default:return}if(t=!0,p==="*"&&y==="1")return V.ReplaceSkip(C);let E={kind:"function",value:n.value,nodes:[re(y),n.nodes[1],n.nodes[2],n.nodes[3],C]};return V.ReplaceSkip(E)}}}if(c===null||d===null)return;switch(p){case"*":{if(c[1]===d[1]||c[1]===null&&d[1]!==null||c[1]!==null&&d[1]===null)return t=!0,V.ReplaceSkip(re(`${c[0]*d[0]}${c[1]??d[1]??""}`));break}case"+":{if(c[1]===d[1])return t=!0,V.ReplaceSkip(re(`${c[0]+d[0]}${c[1]??""}`));break}case"-":{if(c[1]===d[1])return t=!0,V.ReplaceSkip(re(`${c[0]-d[0]}${c[1]??""}`));break}case"/":{if(d[0]!==0&&(c[1]===null&&d[1]===null||c[1]!==null&&d[1]===null)){let m=c[0]/d[0];if(Math.round(m*100)/100!==m)break;return t=!0,V.ReplaceSkip(re(`${m}${c[1]??""}`))}break}}}}}),[t,e]}function Vi(e,i=null,r=!0){let t=ae.get(e);if(t===null)return null;let[n,s]=t;if(s===null)return`${n}`;if(n===0&&He(e))return r?"0":`0${s}`;if(!r)return`${e}`;switch(s.toLowerCase()){case"in":return`${n*96}px`;case"cm":return`${n*96/2.54}px`;case"mm":return`${n*96/2.54/10}px`;case"q":return`${n*96/2.54/10/4}px`;case"pc":return`${n*96/6}px`;case"pt":return`${n*96/72}px`;case"rem":return i!==null?`${n*i}px`:null;case"grad":return`${n*.9}deg`;case"rad":return`${n*180/Math.PI}deg`;case"turn":return`${n*360}deg`;case"ms":return`${n/1e3}s`;case"khz":return`${n*1e3}hz`;default:return`${n}${s}`}}function Ee(e,i="top",r="right",t="bottom",n="left"){return Ei(`${e}-${i}`,`${e}-${r}`,`${e}-${t}`,`${e}-${n}`)}function Ei(e="top",i="right",r="bottom",t="left"){return{1:[[e,0],[i,0],[r,0],[t,0]],2:[[e,0],[i,1],[r,0],[t,1]],3:[[e,0],[i,1],[r,2],[t,1]],4:[[e,0],[i,1],[r,2],[t,3]]}}function fe(e,i){return{1:[[e,0],[i,0]],2:[[e,0],[i,1]]}}var $i={inset:Ei(),margin:Ee("margin"),padding:Ee("padding"),"scroll-margin":Ee("scroll-margin"),"scroll-padding":Ee("scroll-padding"),"border-width":Ee("border","top-width","right-width","bottom-width","left-width"),"border-style":Ee("border","top-style","right-style","bottom-style","left-style"),"border-color":Ee("border","top-color","right-color","bottom-color","left-color"),gap:fe("row-gap","column-gap"),overflow:fe("overflow-x","overflow-y"),"overscroll-behavior":fe("overscroll-behavior-x","overscroll-behavior-y")},Ti={"inset-block":fe("top","bottom"),"inset-inline":fe("left","right"),"margin-block":fe("margin-top","margin-bottom"),"margin-inline":fe("margin-left","margin-right"),"padding-block":fe("padding-top","padding-bottom"),"padding-inline":fe("padding-left","padding-right"),"scroll-margin-block":fe("scroll-margin-top","scroll-margin-bottom"),"scroll-margin-inline":fe("scroll-margin-left","scroll-margin-right"),"scroll-padding-block":fe("scroll-padding-top","scroll-padding-bottom"),"scroll-padding-inline":fe("scroll-padding-left","scroll-padding-right")},Ni={"border-block":["border-bottom","border-top"],"border-block-color":["border-bottom-color","border-top-color"],"border-block-style":["border-bottom-style","border-top-style"],"border-block-width":["border-bottom-width","border-top-width"],"border-inline":["border-left","border-right"],"border-inline-color":["border-left-color","border-right-color"],"border-inline-style":["border-left-style","border-right-style"],"border-inline-width":["border-left-width","border-right-width"]};function Ri(e,i){if(i&2){if(e.property in Ti){let r=F(e.value," ");return Ti[e.property][r.length]?.map(([t,n])=>o(t,r[n],e.important))}if(e.property in Ni)return Ni[e.property]?.map(r=>o(r,e.value,e.important))}if(e.property in $i){let r=F(e.value," ");return $i[e.property][r.length]?.map(([t,n])=>o(t,r[n],e.important))}return null}function me(e,i){for(let r in e)delete e[r];return Object.assign(e,i)}function Re(e){let i=[];for(let r of F(e,".")){if(!r.includes("[")){i.push(r);continue}let t=0;for(;;){let n=r.indexOf("[",t),s=r.indexOf("]",n);if(n===-1||s===-1)break;n>t&&i.push(r.slice(t,n)),i.push(r.slice(n+1,s)),t=s+1}t<=r.length-1&&i.push(r.slice(t))}return i}function pr(e,i){let r=e;return r.storage[Ki]??=Ol(),r.storage[Ui]??=Dl(r),r.storage[Li]??=zl(),r.storage[zi]??=jl(),r.storage[Mi]??=Wl(),r.storage[mr]??=Zl(r),r.storage[Rt]??=Xl(r,i),r.storage[we]??=ma(r),r.storage[Bi]??=ga(r),r.storage[gr]??=ka(),r.storage[Pt]??=ba(r),r.storage[hr]??=ya(r),r.storage[_t]??=xa(r),r.storage[qi]??=Aa(r),r.storage[at]??=_l(r),r}var Ki=Symbol();function Ol(){return new L(e=>new L(i=>({rem:e,features:i})))}var at=Symbol();function _l(e){return new L(i=>{let r=e.storage[we].get(i);return function(n,s){let l=typeof n=="string"?n:e.printCandidate(n),p=r.get(l);if(typeof p!="string")return!1;let u=typeof s=="string"?s:e.printCandidate(s),c=r.get(u);return typeof c!="string"?!1:p===c}})}function Il(e,i){let r=0;return i?.collapse&&(r|=1),i?.logicalToPhysical&&(r|=2),pr(e,i).storage[Ki].get(i?.rem??null).get(r)}var Ui=Symbol();function Dl(e){return new L(i=>new L(r=>({features:r,designSystem:e,signatureOptions:i})))}function Kl(e,i,r){let t=0;return r?.collapse&&(t|=1),pr(e).storage[Ui].get(i).get(t)}function dr(e,i,r){let t=Il(e,r),n=Kl(e,t,r),s=pr(e),l=new Set,p=s.storage[Li].get(n);for(let u of i)l.add(p.get(u));return l.size<=1||!(n.features&1)?Array.from(l):Ul(n,Array.from(l))}function Ul(e,i){let r=e.designSystem,t=new L(p=>new L(u=>new Set)),n=e.designSystem.theme.prefix?`${e.designSystem.theme.prefix}:`:"";for(let p of i){let u=F(p,":"),c=u.pop(),d=c.endsWith("!");d&&(c=c.slice(0,-1));let m=u.length>0?`${u.join(":")}:`:"",f=d?"!":"";t.get(m).get(f).add(`${n}${c}`)}let s=new Set;for(let[p,u]of t.entries())for(let[c,d]of u.entries())for(let m of l(Array.from(d)))n&&m.startsWith(n)&&(m=m.slice(n.length)),s.add(`${p}${m}${c}`);return Array.from(s);function l(p){let u=e.signatureOptions,c=r.storage[Pt].get(u),d=r.storage[gr].get(u),m=r.storage[Bi].get(u),f=p.map(D=>c.get(D));if(f.some(D=>D.has("line-height"))){let D=r.theme.keysInNamespaces(["--text"]);if(D.length>0){let z=new Set,j=new Set;for(let a of f)if(a.has("line-height"))for(let g of a.get("line-height")){if(j.has(g))continue;j.add(g);let v=r.storage[Rt]?.get(g)??null;if(v!==null)if(te(v)){z.add(v);for(let S of D)c.get(`text-${S}/${v}`)}else{z.add(g);for(let S of D)c.get(`text-${S}/[${g}]`)}}let Z=new Set;for(let a of f)if(a.has("font-size")){for(let g of a.get("font-size"))if(!Z.has(g)){Z.add(g);for(let v of z)te(v)?c.get(`text-[${g}]/${v}`):c.get(`text-[${g}]/[${v}]`)}}}}let h=new L(D=>{let z=new L(Z=>new L(a=>new Set)),j=new Set(c.get(D).keys());if(j.size===0)return z;for(let Z of ge(r,D))if(!(Z.kind!=="functional"||Z.value===null)){for(let a of r.utilities.keys("functional")){if(a===Z.root)continue;let g=ji(r,{...ze(Z),root:a}),v=c.get(g);for(let[S,x]of v)if(j.has(S))for(let T of x)z.get(S).get(T).add(g)}return z}return z}),w=f.map((D,z)=>{let j=null;for(let Z of D.keys()){let a=new Set;for(let g of d.get(Z).values())for(let v of g)a.add(v);for(let g of D.get(Z))for(let v of h.get(p[z]).get(Z).get(g))a.add(v);if(j===null?j=a:j=Di(j,a),j.size===0)return j}return j??new Set}),b=new Set,k=new Set;for(let D of w)for(let z of D)b.has(z)?k.add(z):b.add(z);let A=new L(D=>new Set);for(let[D,z]of w.entries())for(let j of z){if(!k.has(j))continue;let Z=A.get(j);for(let a of f[D].keys())Z.add(a)}let C=new L(D=>{let z=A.get(D);for(let j of c.get(D).keys())if(!z.has(j))return!1;return!0});w=w.map(D=>{let z=new Set;for(let j of D)k.has(j)&&C.get(j)&&z.add(j);return z});let y=new L(D=>new Set([D]));for(let D=0;DD.split(",").map(Number));for(let D of y.values()){let z=Array.from(D).sort((j,Z)=>j-Z);E.get(z.join(","))}let O=[];for(let D of y.keys())try{r.getClassOrder([p[D]]),O.push(p[D])}catch{}let P=new Map(r.getClassOrder(O));function K(D,z){return D===z?0:D===null?1:z===null||DW.has(p[v])))continue;let j=z.flatMap(v=>w[v]).reduce(Di);if(j.size===0)continue;let Z=z.map(v=>p[v]).sort((v,S)=>v.localeCompare(S)).join(" "),a=r.storage[we].get(u).get(Z),g=new Set(z.map(v=>p[v]).sort((v,S)=>K(P.get(S)??null,P.get(v)??null)));for(let v of j)g.add(v);for(let v of g)if(r.storage[we].get(u).get(v)===a&&Ll(m.get(Z),m.get(v))){R.add(v);for(let x of z)p[x]!==v&&W.add(p[x]);break}}for(let D of W)R.delete(D);return Array.from(R)}}function Ll(e,i){return e===null||i===null||e.length!==i.length?!1:e.every((r,t)=>r===""||r===i[t])}var Li=Symbol();function zl(){return new L(e=>{let i=e.designSystem,r=i.theme.prefix?`${i.theme.prefix}:`:"",t=i.storage[zi].get(e),n=i.storage[Mi].get(e);return new L((s,l)=>{for(let p of i.parseCandidate(s)){let u=p.variants.slice().reverse().flatMap(m=>t.get(m)),c=p.important;if(c||u.length>0){let f=l.get(i.printCandidate({...p,variants:[],important:!1}));return i.theme.prefix!==null&&u.length>0&&(f=f.slice(r.length)),u.length>0&&(f=`${u.map(h=>i.printVariant(h)).join(":")}:${f}`),c&&(f+="!"),i.theme.prefix!==null&&u.length>0&&(f=`${r}${f}`),f}let d=n.get(s);if(d!==s)return d}return s})})}var Ml=[ql,fa,ca,oa],zi=Symbol();function jl(){return new L(e=>new L(i=>{let r=[i];for(let t of Ml)for(let n of r.splice(0)){let s=t(Ue(n),e);if(Array.isArray(s)){r.push(...s);continue}else r.push(s)}return r}))}var Fl=[Yl,Gl,Hl,pa,ea,ra,aa,sa,ua,da],Mi=Symbol();function Wl(){return new L(e=>{let i=e.designSystem;return new L(r=>{for(let t of i.parseCandidate(r)){let n=ze(t);for(let l of Fl)n=l(n,e);let s=i.printCandidate(n);if(r!==s)return s}return r})})}var Bl=["t","tr","r","br","b","bl","l","tl"];function Yl(e){if(e.kind==="static"&&e.root.startsWith("bg-gradient-to-")){let i=e.root.slice(15);return Bl.includes(i)&&(e.root=`bg-linear-to-${i}`),e}return e}function Gl(e,i){let r=i.designSystem.storage[mr];if(e.kind==="arbitrary"){let[t,n]=r(e.value,e.modifier===null?1:0);t!==e.value&&(e.value=t,n!==null&&(e.modifier=n))}else if(e.kind==="functional"&&e.value?.kind==="arbitrary"){let[t,n]=r(e.value.value,e.modifier===null?1:0);t!==e.value.value&&(e.value.value=t,n!==null&&(e.modifier=n))}return e}function ql(e,i){let r=i.designSystem.storage[mr],t=Ot(e);for(let[n]of t)if(n.kind==="arbitrary"){let[s]=r(n.selector,2);s!==n.selector&&(n.selector=s)}else if(n.kind==="functional"&&n.value?.kind==="arbitrary"){let[s]=r(n.value.value,2);s!==n.value.value&&(n.value.value=s)}return e}function Hl(e,i){return e.kind==="arbitrary"?e.value=Pi(e.value,i.designSystem):e.kind==="functional"&&e.value?.kind==="arbitrary"&&(e.value.value=Pi(e.value.value,i.designSystem)),e}function Pi(e,i){let r=i.theme.prefix?`--${i.theme.prefix}-spacing`:"--spacing",t=Y(e);return I(t,n=>{if(!(n.kind!=="function"||n.value!=="calc")&&n.nodes.length===5&&!(n.nodes[2].kind!=="word"||n.nodes[2].value!=="*")&&!(n.nodes[0].kind!=="function"||n.nodes[0].value!=="var"||n.nodes[0].nodes.length!==1||n.nodes[0].nodes[0].kind!=="word"||n.nodes[0].nodes[0].value!==r))return V.Replace(Y(`--spacing(${B([n.nodes[4]])})`))}),B(t)}var mr=Symbol();function Zl(e){return i(e);function i(r){function t(c,d=0){let m=Y(c);if(d&2)return[Nt(m,u),null];let f=0,h=0;if(I(m,k=>{k.kind==="function"&&k.value==="theme"&&(f+=1,I(k.nodes,A=>A.kind==="separator"&&A.value.includes(",")?V.Stop:A.kind==="word"&&A.value==="/"?(h+=1,V.Stop):V.Skip))}),f===0)return[c,null];if(h===0)return[Nt(m,p),null];if(h>1)return[Nt(m,u),null];let w=null;return[Nt(m,(k,A)=>{let C=F(k,"/").map(y=>y.trim());if(C.length>2)return null;if(m.length===1&&C.length===2&&d&1){let[y,E]=C;/^\d+%$/.test(E)?w=n(Number(E.slice(0,-1))):/^0?\.\d+$/.test(E)?w=n(s(Number(E))):w={kind:"arbitrary",value:E},k=y}return p(k,A)||u(k,A)}),w]}function n(c){if(Number.isInteger(c)){let d=r.theme.resolveValue(`${c}`,["--opacity"]);if(d===null)return{kind:"named",value:`${c}`};if((d.endsWith("%")?Number(d.slice(0,-1)):s(Number(d)))===c)return{kind:"named",value:`${c}`}}return{kind:"arbitrary",value:`${c}%`}}function s(c){return Number((c*100).toFixed(10))}function l(c,d=!0){let m=`--${Ye(Re(c))}`;return r.theme.get([m])?d&&r.theme.prefix?`--${r.theme.prefix}-${m.slice(2)}`:m:null}function p(c,d){let m=l(c);if(m)return d?`var(${m}, ${d})`:`var(${m})`;let f=Re(c);if(f[0]==="spacing"&&r.theme.get(["--spacing"])){let h=f[1];return te(h)?`--spacing(${h})`:null}return null}function u(c,d){let m=F(c,"/").map(w=>w.trim());c=m.shift();let f=l(c,!1);if(!f)return null;let h=m.length>0?`/${m.join("/")}`:"";return d?`--theme(${f}${h}, ${d})`:`--theme(${f}${h})`}return t}}function Nt(e,i){return I(e,(r,t)=>{if(r.kind==="function"&&r.value==="theme"){if(r.nodes.length<1)return;r.nodes[0].kind==="separator"&&r.nodes[0].value.trim()===""&&r.nodes.shift();let n=r.nodes[0];if(n.kind!=="word")return;let s=n.value,l=1;for(let c=l;c0?i(s,B(p)):i(s);if(u===null)return;{let c=t.index-1;for(;c!==-1;){let d=t.siblings[c];if(d.kind==="separator"&&d.value.trim()===""){c-=1;continue}/^[-+*/]$/.test(d.value.trim())&&(u=`(${u})`);break}}return V.Replace(Y(u))}}),B(e)}function Jl(e){if(e[0]!=="'"&&e[0]!=='"')return e;let i="",r=e[0];for(let t=1;t{if(n===0)return null;let p=ae.get(nt(l,i?.rem??null));if(!p)return null;let[u,c]=p;return c!==s?null:u/n})}function ea(e,i){if(e.kind!=="arbitrary"&&!(e.kind==="functional"&&e.value?.kind==="arbitrary"))return e;let r=i.designSystem,t=r.storage[hr].get(i.signatureOptions),n=r.storage[we].get(i.signatureOptions),s=r.storage[at].get(i.signatureOptions),l=r.printCandidate(e),p=n.get(l);if(typeof p!="string")return e;for(let c of u(p,e))if(s(e,c)&&ta(r,e,c))return c;return e;function*u(c,d){let m=t.get(c);if(m.length>1){let f;for(let h of m)if(h[0]!=="-"){if(f)return;f=h}if(f)for(let h of ge(r,f))yield h;return}if(m.length===0&&d.modifier){let f={...d,modifier:null},h=n.get(r.printCandidate(f));if(typeof h=="string")for(let w of u(h,f))yield Object.assign({},w,{modifier:d.modifier})}if(m.length===1)for(let f of ge(r,m[0]))yield f;else if(m.length===0){let f=d.kind==="arbitrary"?d.value:d.value?.value??null;if(f===null)return;if(i.signatureOptions.rem!==null&&d.kind==="functional"&&d.value?.kind==="arbitrary"){let b=r.storage[Rt]?.get(f)??null;b!==null&&te(b)&&Oi(b,r,i.signatureOptions.rem)&&(yield Object.assign({},d,{value:{kind:"named",value:b,fraction:null}}))}let h=r.storage[Rt]?.get(f)??null,w="";h!==null&&h<0&&(w="-",h=Math.abs(h));for(let b of Array.from(r.utilities.keys("functional")).sort((k,A)=>+(k[0]==="-")-+(A[0]==="-"))){w&&(b=`${w}${b}`);for(let k of ge(r,`${b}-${f}`))yield k;if(d.modifier)for(let k of ge(r,`${b}-${f}${d.modifier}`))yield k;if(h!==null&&te(h)&&Oi(h,r,i.signatureOptions.rem)){for(let k of ge(r,`${b}-${h}`))yield k;if(d.modifier)for(let k of ge(r,`${b}-${h}${rt(d.modifier)}`))yield k}for(let k of ge(r,`${b}-[${f}]`))yield k;if(d.modifier)for(let k of ge(r,`${b}-[${f}]${rt(d.modifier)}`))yield k}}}}function ta(e,i,r){let t=null;if(i.kind==="functional"&&i.value?.kind==="arbitrary"&&i.value.value.includes("var(--")?t=i.value.value:i.kind==="arbitrary"&&i.value.includes("var(--")&&(t=i.value),t===null)return!0;let n=e.candidatesToCss([e.printCandidate(r)]).join(` +`),s=!0;return I(Y(t),l=>{if(l.kind==="function"&&l.value==="var"){let p=l.nodes[0].value;if(!new RegExp(`var\\(${p}[,)]\\s*`,"g").test(n)||n.includes(`${p}:`))return s=!1,V.Stop}}),s}function ra(e,i){if(e.kind!=="functional"||e.value?.kind!=="named")return e;let r=i.designSystem,t=r.storage[hr].get(i.signatureOptions),n=r.storage[we].get(i.signatureOptions),s=r.storage[at].get(i.signatureOptions),l=r.printCandidate(e),p=n.get(l);if(typeof p!="string")return e;for(let c of u(p,e))if(s(e,c))return c;return e;function*u(c,d){let m=t.get(c);if(m.length>1){let f;for(let h of m)if(h[0]!=="-"){if(f)return;f=h}if(f)for(let h of ge(r,f))yield h;return}if(m.length===0&&d.modifier){let f={...d,modifier:null},h=n.get(r.printCandidate(f));if(typeof h=="string")for(let w of u(h,f))yield Object.assign({},w,{modifier:d.modifier})}if(m.length===1)for(let f of ge(r,m[0]))yield f}}var ia=new Map([["order-none","order-0"],["break-words","wrap-break-word"],["overflow-ellipsis","text-ellipsis"]]),na=new Map([[/^(-)?start-(.*?)$/,"$1inset-s-$2"],[/^(-)?end-(.*?)$/,"$1inset-e-$2"]]);function*la(e){let i=ia.get(e);i&&(yield i);for(let[r,t]of na){let n=e.replace(r,t);n!==e&&(yield n)}}function aa(e,i){let r=i.designSystem,t=r.storage[at].get(i.signatureOptions),n=ji(r,e);for(let s of la(n)){if(!t(e,s))continue;let[l]=ge(r,s);return l}return e}function oa(e,i){let r=i.designSystem,t=r.storage[_t].get(i.signatureOptions.rem),n=r.storage[qi].get(i.signatureOptions.rem),s=Ot(e);for(let[l]of s){if(l.kind==="compound")continue;let p=r.printVariant(l),u=t.get(p);if(typeof u!="string")continue;let c=n.get(u);if(c.length===0||c.includes(p))continue;let d=c[0],m=r.parseVariant(d);m!==null&&me(l,m)}return e}function sa(e,i){let r=i.designSystem,t=r.storage[we].get(i.signatureOptions);if(e.kind==="functional"&&e.value?.kind==="arbitrary"&&e.value.dataType!==null){let n=r.printCandidate({...e,value:{...e.value,dataType:null}});t.get(r.printCandidate(e))===t.get(n)&&(e.value.dataType=null)}return e}function ua(e,i){if(e.kind!=="functional"||e.value?.kind!=="arbitrary")return e;let r=i.designSystem,t=r.storage[we].get(i.signatureOptions),n=t.get(r.printCandidate(e));if(n===null)return e;for(let s of Wi(e))if(t.get(r.printCandidate({...e,value:s}))===n)return e.value=s,e;return e}function fa(e){let i=Ot(e);for(let[r]of i)if(r.kind==="functional"&&r.root==="data"&&r.value?.kind==="arbitrary"&&!r.value.value.includes("="))r.value={kind:"named",value:r.value.value};else if(r.kind==="functional"&&r.root==="aria"&&r.value?.kind==="arbitrary"&&(r.value.value.endsWith("=true")||r.value.value.endsWith('="true"')||r.value.value.endsWith("='true'"))){let[t,n]=F(r.value.value,"=");if(t[t.length-1]==="~"||t[t.length-1]==="|"||t[t.length-1]==="^"||t[t.length-1]==="$"||t[t.length-1]==="*")continue;r.value={kind:"named",value:r.value.value.slice(0,r.value.value.indexOf("="))}}else r.kind==="functional"&&r.root==="supports"&&r.value?.kind==="arbitrary"&&/^[a-z-][a-z0-9-]*$/i.test(r.value.value)&&(r.value={kind:"named",value:r.value.value});return e}function*Wi(e,i=e.value?.value??"",r=new Set){if(r.has(i))return;if(r.add(i),yield{kind:"named",value:i,fraction:null},i.endsWith("%")&&te(i.slice(0,-1))&&(yield{kind:"named",value:i.slice(0,-1),fraction:null}),i.includes("/")){let[s,l]=i.split("/");U(s)&&U(l)&&(yield{kind:"named",value:s,fraction:`${s}/${l}`})}let t=new Set;for(let s of i.matchAll(/(\d+\/\d+)|(\d+\.?\d+)/g))t.add(s[0].trim());let n=Array.from(t).sort((s,l)=>s.length-l.length);for(let s of n)yield*Wi(e,s,r)}function _i(e){return!(e.length===1&&e[0].kind==="list")}function Et(e){return e.value[0]==="["&&e.value[e.value.length-1]==="]"}function ca(e,i){let r=[e],t=i.designSystem,n=t.storage[_t].get(i.signatureOptions.rem),s=Ot(e);for(let[l,p]of s)if(l.kind==="compound"&&(l.root==="has"||l.root==="not"||l.root==="in")&&l.modifier!==null&&"modifier"in l.variant&&(l.variant.modifier=l.modifier,l.modifier=null),l.kind==="arbitrary"){if(l.relative)continue;let u=ce(l.selector);if(!_i(u))continue;if(u.length===1&&u[0].kind==="complex"&&(u=u[0].nodes),p===null&&u.length===3&&u[0].kind==="selector"&&u[0].value==="&"&&u[1].kind==="combinator"&&u[1].value===">"&&u[2].kind==="selector"&&u[2].value==="*"){me(l,t.parseVariant("*"));continue}if(p===null&&u.length===3&&u[0].kind==="selector"&&u[0].value==="&"&&u[1].kind==="combinator"&&u[1].value===" "&&u[2].kind==="selector"&&u[2].value==="*"){me(l,t.parseVariant("**"));continue}if(p===null&&u.length===1&&u[0].kind==="compound"&&u[0].nodes.length===2&&u[0].nodes[0].kind==="selector"&&u[0].nodes[0].value==="&"&&u[0].nodes[1].kind==="function"&&u[0].nodes[1].value===":has"&&u[0].nodes[1].nodes.length===1&&u[0].nodes[1].nodes[0].kind==="selector"){me(l,t.parseVariant(`has-[${se(u[0].nodes[1].nodes,!0)}]`));continue}if(p===null&&u.length===3&&u[0].kind==="selector"&&u[1].kind==="combinator"&&u[1].value===" "&&u[2].kind==="selector"&&u[2].value==="&"){u.pop(),u.pop(),me(l,t.parseVariant(`in-[${se(u,!0)}]`));continue}if(p===null&&u[0].kind==="selector"&&(u[0].value==="@media"||u[0].value==="@supports")){let f=n.get(t.printVariant(l)),h=Y(se(u,!0)),w=!1;if(I(h,b=>{if(b.kind==="word"&&b.value==="not")return w=!0,V.Replace([])}),h=Y(B(h)),I(h,b=>{b.kind==="separator"&&b.value!==" "&&b.value.trim()===""&&(b.value=" ")}),w){let b=t.parseVariant(`not-[${B(h)}]`);if(b===null)continue;let k=n.get(t.printVariant(b));if(f===k){me(l,b);continue}}}let c=null;p===null&&u.length===3&&u[0].kind==="selector"&&u[0].value==="&"&&u[1].kind==="combinator"&&u[1].value===">"&&u[2].kind==="selector"&&(u[2].value[0]===":"||Et(u[2]))&&(u=[u[2]],c=t.parseVariant("*")),p===null&&u.length===3&&u[0].kind==="selector"&&u[0].value==="&"&&u[1].kind==="combinator"&&u[1].value===" "&&u[2].kind==="selector"&&(u[2].value[0]===":"||Et(u[2]))&&(u=[u[2]],c=t.parseVariant("**"));let d=u;if(I(d,{enter(f){if(f.kind==="selector"&&f.value==="&")return V.Replace([]);if(f.kind==="function")return V.Skip},exit(f){if(f.kind==="compound"&&f.nodes.length===1)return V.ReplaceSkip(f.nodes)}}),d.length!==1)continue;let m=d[0];if(m.kind==="function"&&m.value===":is"){if(!_i(m.nodes)||m.nodes.length!==1||m.nodes[0].kind==="selector"&&!Et(m.nodes[0]))continue;m=m.nodes[0]}if(m.kind==="function"&&m.value[0]===":"||m.kind==="selector"&&m.value[0]===":"){let f=m,h=!1;if(f.kind==="function"&&f.value===":not"){if(h=!0,f.nodes.length!==1||f.nodes[0].kind!=="selector"&&f.nodes[0].kind!=="function"||f.nodes[0].value[0]!==":")continue;f=f.nodes[0]}let w=(k=>{if(k===":nth-child"&&f.kind==="function"&&f.nodes.length===1&&f.nodes[0].kind==="value"&&f.nodes[0].value==="odd")return h?(h=!1,"even"):"odd";if(k===":nth-child"&&f.kind==="function"&&f.nodes.length===1&&f.nodes[0].kind==="value"&&f.nodes[0].value==="even")return h?(h=!1,"odd"):"even";for(let[A,C]of[[":nth-child","nth"],[":nth-last-child","nth-last"],[":nth-of-type","nth-of-type"],[":nth-last-of-type","nth-of-last-type"]])if(k===A&&f.kind==="function"&&f.nodes.length===1)return f.nodes.length===1&&f.nodes[0].kind==="value"&&U(f.nodes[0].value)?`${C}-${f.nodes[0].value}`:`${C}-[${se(f.nodes,!0)}]`;if(h){let A=n.get(t.printVariant(l)),C=n.get(`not-[${k}]`);if(A===C)return`[&${k}]`}return null})(f.value);if(w===null){if(c)return me(l,{kind:"arbitrary",selector:ct(m)?`&${m.value}`:m.value,relative:!1}),[c,l];continue}h&&(w=`not-${w}`);let b=t.parseVariant(w);if(b===null)continue;me(l,b)}else if(m.kind==="selector"&&Et(m)){let f=We(m.value);if(f===null)continue;if(f.attribute.startsWith("data-")){let h=f.attribute.slice(5);me(l,{kind:"functional",root:"data",modifier:null,value:f.value===null?{kind:"named",value:h}:{kind:"arbitrary",value:`${h}${f.operator}${f.quote??""}${f.value}${f.quote??""}${f.sensitivity?` ${f.sensitivity}`:""}`}})}else if(f.attribute.startsWith("aria-")){let h=f.attribute.slice(5);me(l,{kind:"functional",root:"aria",modifier:null,value:f.value===null?{kind:"arbitrary",value:h}:f.operator==="="&&f.value==="true"&&f.sensitivity===null?{kind:"named",value:h}:{kind:"arbitrary",value:`${f.attribute}${f.operator}${f.quote??""}${f.value}${f.quote??""}${f.sensitivity?` ${f.sensitivity}`:""}`}})}else me(l,{kind:"arbitrary",selector:m.value,relative:!1})}if(c)return[c,l]}return r}function pa(e,i){if(e.kind!=="functional"||e.value?.kind!=="arbitrary")return e;let t=i.designSystem.storage[at].get(i.signatureOptions),n=Y(e.value.value);if(n.length===1&&n[0].kind==="function"&&n[0].value==="calc"){let[s,l]=lt(n,null,!1);if(s){let p=ze(e);p.value.value=B(l),t(e,p)&&(e=p,n=l)}}if(e.root[0]==="-"){if(n.length===1&&n[0].kind==="function"&&n[0].value==="var")return e;let s=Y(`calc(${e.value.value} * -1)`),[l,p]=lt(s,null,!1);if(l){let u=ze(e);u.root=u.root.slice(1),u.value.value=B(p),t(e,u)&&(e=u,n=p)}}if(n.length===1&&n[0].kind==="function"&&n[0].value==="calc"){let s=n[0].nodes;if(s.length===5&&s[1].kind==="separator"&&s[1].value===" "&&s[2].kind==="word"&&s[2].value==="*"&&s[3].kind==="separator"&&s[3].value===" "){let l=s[4].kind==="word"&&s[4].value==="-1"?s[0]:s[0].kind==="word"&&s[0].value==="-1"?s[4]:null;if(l){let p=ze(e);p.root=`-${e.root}`,p.value.value=B([l]),t(e,p)&&(e=p)}}}return e}function da(e,i){if(e.kind!=="functional"&&e.kind!=="arbitrary"||e.modifier===null)return e;let r=i.designSystem,t=r.storage[we].get(i.signatureOptions),n=t.get(r.printCandidate(e)),s=e.modifier;if(n===t.get(r.printCandidate({...e,modifier:null})))return e.modifier=null,e;{let l={kind:"named",value:s.value.endsWith("%")?s.value.includes(".")?`${Number(s.value.slice(0,-1))}`:s.value.slice(0,-1):s.value,fraction:null};if(n===t.get(r.printCandidate({...e,modifier:l})))return e.modifier=l,e}{let l={kind:"named",value:`${parseFloat(s.value)*100}`,fraction:null};if(n===t.get(r.printCandidate({...e,modifier:l})))return e.modifier=l,e}return e}var we=Symbol();function ma(e){return new L(i=>new L(r=>{try{return ue(Yi(e,r,i))}catch{return Symbol()}}))}var Bi=Symbol();function ga(e){return new L(i=>new L(r=>{try{let t=new L(()=>new Set),n=Yi(e,r,i,t),s=[];return I(n,l=>{l.kind==="declaration"&&s.push(Array.from(t.get(l)).sort().join(" "))}),s}catch{return null}}))}function Yi(e,i,r,t){i=e.theme.prefix&&!i.startsWith(e.theme.prefix)?`${e.theme.prefix}:${i}`:i;let n=[J(".x",[q("@apply",i)])];return Ca(e,()=>{for(let s of e.parseCandidate(i))e.compileAstNodes(s,1);Ce(n,e)}),Gi(e,n,r,t),n}var Ii=/#(?:[a-f0-9]{8}|[a-f0-9]{6}|[a-f0-9]{4}|[a-f0-9]{3})/gi,ha={"--tw-duration":"transition-duration","--tw-ease":"transition-timing-function","--tw-leading":"line-height","--tw-tracking":"letter-spacing"};function Gi(e,i,r,t){let{rem:n}=r;return I(i,{enter(s,l){if(s.kind==="declaration"){if(s.value===void 0||s.property==="--tw-sort")return V.Replace([]);if(s.property.startsWith("--tw-")){let f=ha[s.property]??s.property.slice(5);if(l.siblings.some(h=>h.kind==="declaration"&&h.property===f&&s.value===h.value&&s.important===h.important))return V.Replace([])}if(r.features&1){let f=Ri(s,r.features);if(f)return V.Replace(f)}s.value.includes("var(")&&(s.value=wa(s.value,e,t?.get(s)));let p=Y(s.value),[u,c]=lt(p,n),[d,m]=Ai(c);(u||d)&&(s.value=B(m)),s.value=Ae(s.value)}else{if(s.kind==="context"||s.kind==="at-root")return V.Replace(s.nodes);if(s.kind==="comment")return V.Replace([]);if(s.kind==="at-rule"&&s.name==="@property")return V.Replace([])}},exit(s){if(s.kind==="rule"||s.kind==="at-rule"){if(s.nodes.length>1){let l=new Set;for(let p=s.nodes.length-1;p>=0;p--){let u=s.nodes[p];u.kind==="declaration"&&u.value!==void 0&&(l.has(u.property)&&s.nodes.splice(p,1),l.add(u.property))}}s.nodes.sort((l,p)=>l.kind!=="declaration"||p.kind!=="declaration"?0:l.property.localeCompare(p.property))}else if(s.kind==="declaration"&&s.value){if(s.property[0]==="-"&&s.property[1]==="-")return;Ii.lastIndex=0,s.value=s.value.replace(Ii,l=>l.toLowerCase())}}}),i}var va=["initial","inherit","revert","revert-layer","revert-rule","unset"];function wa(e,i,r){let t=!1,n=Y(e),s=new Set;return I(n,l=>{if(l.kind!=="function"||l.value!=="var"||l.nodes.length!==1&&l.nodes.length<3)return;let p=l.nodes[0].value;i.theme.prefix&&p.startsWith(`--${i.theme.prefix}-`)&&(p=p.slice(`--${i.theme.prefix}-`.length));let u=i.resolveThemeValue(p);if(!s.has(p)&&(s.add(p),u!==void 0&&!va.includes(u.toLowerCase())&&(l.nodes.length===1&&(t=!0,l.nodes.push(...Y(`,${u}`))),l.nodes.length>=3))){let c=B(l.nodes),d=`${l.nodes[0].value},${u}`;if(c===d)return t=!0,r?.add(p),V.Replace(Y(u))}}),t?B(n):e}var gr=Symbol();function ka(){return new L(e=>new L(i=>new L(r=>new Set)))}var Pt=Symbol();function ba(e){return new L(i=>new L(r=>{let t=new L(s=>new Set);e.theme.prefix&&!r.startsWith(e.theme.prefix)&&(r=`${e.theme.prefix}:${r}`);let n=e.parseCandidate(r);if(n.length===0)return t;try{let s=e.compileAstNodes(n[0]).map(l=>le(l.node));I(Gi(e,s,i),l=>{l.kind==="declaration"&&(t.get(l.property).add(l.value),e.storage[gr].get(i).get(l.property).get(l.value).add(r))})}catch{}return t}))}var hr=Symbol();function ya(e){return new L(i=>{let r=e.storage[we].get(i),t=new L(()=>[]);for(let[n,s]of e.getClassList()){let l=r.get(n);if(typeof l=="string"){if(n[0]==="-"&&n.endsWith("-0")){let p=r.get(n.slice(1));if(typeof p=="string"&&l===p)continue}t.get(l).push(n),e.storage[Pt].get(i).get(n);for(let p of s.modifiers){if(te(p))continue;let u=`${n}/${p}`,c=r.get(u);typeof c=="string"&&(t.get(c).push(u),e.storage[Pt].get(i).get(u))}}}return t})}var _t=Symbol();function xa(e){return new L(i=>new L(r=>{try{r=e.theme.prefix&&!r.startsWith(e.theme.prefix)?`${e.theme.prefix}:${r}`:r;let t=[J(".x",[q("@apply",`${r}:flex`)])];return Ce(t,e),I(t,s=>{if(s.kind==="at-rule")s.params=nt(s.params,i),s.params.includes(" ")&&(s.params=s.params.replaceAll(" ",""));else if(s.kind==="rule"){let l=ce(s.selector),p=!1;I(l,u=>{if(u.kind==="list"||u.kind==="combinator")p=!0;else if(u.kind==="function"&&u.value===":is"){if(u.nodes.length===1)return p=!0,V.Replace(u.nodes);if(u.nodes.length===2&&u.nodes[0].kind==="selector"&&u.nodes[0].value==="*"&&u.nodes[1].kind==="selector"&&u.nodes[1].value[0]===":")return p=!0,V.Replace(u.nodes[1])}else u.kind==="function"&&u.value[0]===":"&&u.nodes[0]?.kind==="selector"&&u.nodes[0]?.value[0]===":"&&(p=!0,u.nodes.unshift({kind:"selector",value:"*"}))}),p&&(s.selector=se(l,!0))}}),ue(t)}catch{return Symbol()}}))}var qi=Symbol();function Aa(e){return new L(i=>{let r=e.storage[_t].get(i),t=new L(()=>[]);for(let[n,s]of e.variants.entries())if(s.kind==="static"){let l=r.get(n);if(typeof l!="string")continue;t.get(l).push(n)}else if(s.kind==="functional")for(let l of e.variants.getCompletions(n)){let p=n==="@"?`@${l}`:`${n}-${l}`,u=r.get(p);typeof u=="string"&&t.get(u).push(p)}return t})}function Ca(e,i){let r=e.theme.values.get,t=new Set;e.theme.values.get=n=>{let s=r.call(e.theme.values,n);return s===void 0||s.options&1&&(t.add(s),s.options&=-2),s};try{return i()}finally{e.theme.values.get=r;for(let n of t)n.options|=1}}function*Sa(e){let i=e.length,r=1n<=2;t--){let n=(1n<>BigInt(u)&1n&&s.push(e[u]);yield s;let l=n&-n,p=n+l;n=((p^n)>>2n)/l|p}}}function Di(e,i){if(typeof e.intersection=="function")return e.intersection(i);if(e.size===0||i.size===0)return new Set;let r=new Set;for(let t of e)i.has(t)&&r.add(t);return r}var $a=/^\d+\/\d+$/;function Hi(e){let i=new L(n=>({name:n,utility:n,fraction:!1,modifiers:[]}));for(let n of e.utilities.keys("static")){if(e.utilities.getCompletions(n).length===0)continue;let l=i.get(n);l.fraction=!1,l.modifiers=[]}for(let n of e.utilities.keys("functional")){let s=e.utilities.getCompletions(n);for(let l of s)for(let p of l.values){let u=p!==null&&$a.test(p),c=p===null?n:`${n}-${p}`,d=i.get(c);if(d.utility=n,d.fraction||=u,d.modifiers.push(...l.modifiers),l.supportsNegative){let m=i.get(`-${c}`);m.utility=`-${n}`,m.fraction||=u,m.modifiers.push(...l.modifiers)}d.modifiers=Array.from(new Set(d.modifiers))}}if(i.size===0)return[];let r=Array.from(i.values());return r.sort((n,s)=>Tt(n.name,s.name)),Ta(r)}function Ta(e){let i=[],r=null,t=new Map,n=new L(()=>[]);for(let l of e){let{utility:p,fraction:u}=l;r||(r={utility:p,items:[]},t.set(p,r)),p!==r.utility&&(i.push(r),r={utility:p,items:[]},t.set(p,r)),u?n.get(p).push(l):r.items.push(l)}r&&i[i.length-1]!==r&&i.push(r);for(let[l,p]of n){let u=t.get(l);u&&u.items.push(...p)}let s=[];for(let l of i)for(let p of l.items)s.push([p.name,{modifiers:p.modifiers}]);return s}function Zi(e){let i=[];for(let[t,n]of e.variants.entries()){let p=function({value:u,modifier:c}={}){let d=t;u&&(d+=s?`-${u}`:u),c&&(d+=`/${c}`);let m=e.parseVariant(d);if(!m)return[];let f=J(".__placeholder__",[]);if(Ge(f,m,e.variants)===null)return[];let h=[];return I(f.nodes,{exit(w,b){if(w.kind!=="rule"&&w.kind!=="at-rule"||w.nodes.length>0)return;let k=b.path();k.push(w),k.sort((y,E)=>{let O=y.kind==="at-rule",P=E.kind==="at-rule";return O&&!P?-1:!O&&P?1:0});let A=k.flatMap(y=>y.kind==="rule"?y.selector==="&"?[]:[y.selector]:y.kind==="at-rule"?[`${y.name} ${y.params}`]:[]),C="";for(let y=A.length-1;y>=0;y--)C=C===""?A[y]:`${A[y]} { ${C} }`;h.push(C)}}),h};var r=p;if(n.kind==="arbitrary")continue;let s=t!=="@",l=e.variants.getCompletions(t);switch(n.kind){case"static":{i.push({name:t,values:l,isArbitrary:!1,hasDash:s,selectors:p});break}case"functional":{i.push({name:t,values:l,isArbitrary:!0,hasDash:s,selectors:p});break}case"compound":{i.push({name:t,values:l,isArbitrary:!0,hasDash:s,selectors:p});break}}}return i}function Ji(e,i){let{astNodes:r,nodeSorting:t}=Se(Array.from(i),e),n=new Map(i.map(l=>[l,null])),s=0n;for(let l of r){let p=t.get(l)?.candidate;p&&n.set(p,n.get(p)??s++)}return i.map(l=>[l,n.get(l)??null])}var It=/^@?[a-z0-9][a-zA-Z0-9_-]*(?{p.kind==="rule"?n.push(p.selector):p.kind==="at-rule"&&p.name==="@variant"?s=!0:p.kind==="at-rule"&&p.name!=="@slot"&&(p.name==="@scope"&&(l=!0),n.push(`${p.name} ${p.params}`))}),this.static(i,p=>{let u=r.map(le);s&&st(u,t),l?(ot(u,[ee({source:"user"},p.nodes)]),p.nodes=[ee({source:"variant"},u)]):(ot(u,p.nodes),p.nodes=u)},{compounds:Pe(n)})}functional(i,r,{compounds:t,order:n}={}){this.set(i,{kind:"functional",applyFn:r,compoundsWith:0,compounds:t??2,order:n})}compound(i,r,t,{compounds:n,order:s}={}){this.set(i,{kind:"compound",applyFn:t,compoundsWith:r,compounds:n??2,order:s})}group(i,r){this.groupOrder=this.nextOrder(),r&&this.compareFns.set(this.groupOrder,r),i(),this.groupOrder=null}has(i){return this.variants.has(i)}get(i){return this.variants.get(i)}kind(i){return this.variants.get(i)?.kind}compoundsWith(i,r){let t=this.variants.get(i),n=typeof r=="string"?this.variants.get(r):r.kind==="arbitrary"?{compounds:Pe([r.selector])}:this.variants.get(r.root);return!(!t||!n||t.kind!=="compound"||n.compounds===0||t.compoundsWith===0||(t.compoundsWith&n.compounds)===0)}suggest(i,r){this.completions.set(i,r)}getCompletions(i){return this.completions.get(i)?.()??[]}compare(i,r){if(i===r)return 0;if(i===null)return-1;if(r===null)return 1;if(i.kind==="arbitrary"&&r.kind==="arbitrary")return i.selector{f.nodes=d.map(h=>Q(h,f.nodes))},{compounds:m})}r("*",[":is(& > *)"],{compounds:0}),r("**",[":is(& *)"],{compounds:0});function t(c,d){return d.map(m=>{if(c==="@container"){let f=Y(m.trim());return f.length>=1&&f[0].kind==="function"?`not ${m}`:f.length>=3&&f[0].kind==="word"&&f[0].value==="not"&&f[2].kind==="function"?(f.splice(0,2),B(f)):f.length>=5&&f[0].kind==="word"&&f[2].kind==="word"&&f[2].value==="not"&&f[4].kind==="function"?(f.splice(2,2),B(f)):f.length>=3&&f[0].kind==="word"&&f[0].value!=="not"&&f[2].kind==="function"?(f.splice(1,0,{kind:"separator",value:" "},{kind:"word",value:"not"}),B(f)):`not ${m}`}else{m=m.trim();let f=F(m," ");return f[0]==="not"?f.slice(1).join(" "):`not ${m}`}})}let n=["@media","@supports","@container"];function s(c){for(let d of n){if(d!==c.name)continue;let m=F(c.params,",");return m.length>1?null:(m=t(c.name,m),q(c.name,m.join(", ")))}return null}function l(c){return c.includes("::")?null:`&:not(${F(c,",").map(m=>(m=m.replaceAll("&","*"),m)).join(", ")})`}i.compound("not",3,(c,d)=>{if(d.variant.kind==="arbitrary"&&d.variant.relative||d.modifier)return null;let m=!1;if(I([c],(f,h)=>{if(f.kind!=="rule"&&f.kind!=="at-rule")return V.Continue;if(f.nodes.length>0)return V.Continue;let w=[],b=[],k=h.path();k.push(f);for(let C of k)C.kind==="at-rule"?w.push(C):C.kind==="rule"&&b.push(C);if(w.length>1)return V.Stop;if(b.length>1)return V.Stop;let A=[];for(let C of b){let y=l(C.selector);if(!y)return m=!1,V.Stop;A.push(J(y,[]))}for(let C of w){let y=s(C);if(!y)return m=!1,V.Stop;A.push(y)}return Object.assign(c,J("&",A)),m=!0,V.Skip}),c.kind==="rule"&&c.selector==="&"&&c.nodes.length===1&&Object.assign(c,c.nodes[0]),!m)return null}),i.suggest("not",()=>Array.from(i.keys()).filter(c=>i.compoundsWith("not",c))),i.compound("group",2,(c,d)=>{if(d.variant.kind==="arbitrary"&&d.variant.relative)return null;let m=d.modifier?`:where(.${e.prefix?`${e.prefix}\\:`:""}group\\/${d.modifier.value})`:`:where(.${e.prefix?`${e.prefix}\\:`:""}group)`,f=!1;if(I([c],(h,w)=>{if(h.kind!=="rule")return V.Continue;for(let k of w.path())if(k.kind==="rule")return f=!1,V.Stop;let b=h.selector.replaceAll("&",m);F(b,",").length>1&&(b=`:is(${b})`),h.selector=`:is(${b} &)`,f=!0}),!f)return null}),i.suggest("group",()=>Array.from(i.keys()).filter(c=>i.compoundsWith("group",c))),i.compound("peer",2,(c,d)=>{if(d.variant.kind==="arbitrary"&&d.variant.relative)return null;let m=d.modifier?`:where(.${e.prefix?`${e.prefix}\\:`:""}peer\\/${d.modifier.value})`:`:where(.${e.prefix?`${e.prefix}\\:`:""}peer)`,f=!1;if(I([c],(h,w)=>{if(h.kind!=="rule")return V.Continue;for(let k of w.path())if(k.kind==="rule")return f=!1,V.Stop;let b=h.selector.replaceAll("&",m);F(b,",").length>1&&(b=`:is(${b})`),h.selector=`:is(${b} ~ &)`,f=!0}),!f)return null}),i.suggest("peer",()=>Array.from(i.keys()).filter(c=>i.compoundsWith("peer",c))),r("first-letter",["&::first-letter"]),r("first-line",["&::first-line"]),r("marker",["& *::marker","&::marker","& *::-webkit-details-marker","&::-webkit-details-marker"]),r("selection",["& *::selection","&::selection"]),r("file",["&::file-selector-button"]),r("placeholder",["&::placeholder"]),r("backdrop",["&::backdrop"]),r("details-content",["&::details-content"]);{let c=function(){return H([q("@property","--tw-content",[o("syntax",'"*"'),o("initial-value",'""'),o("inherits","false")])])};var p=c;i.static("before",d=>{d.nodes=[J("&::before",[c(),o("content","var(--tw-content)"),...d.nodes])]},{compounds:0}),i.static("after",d=>{d.nodes=[J("&::after",[c(),o("content","var(--tw-content)"),...d.nodes])]},{compounds:0})}r("first",["&:first-child"]),r("last",["&:last-child"]),r("only",["&:only-child"]),r("odd",["&:nth-child(odd)"]),r("even",["&:nth-child(even)"]),r("first-of-type",["&:first-of-type"]),r("last-of-type",["&:last-of-type"]),r("only-of-type",["&:only-of-type"]),r("visited",["&:visited"]),r("target",["&:target"]),r("open",["&:is([open], :popover-open, :open)"]),r("default",["&:default"]),r("checked",["&:checked"]),r("indeterminate",["&:indeterminate"]),r("placeholder-shown",["&:placeholder-shown"]),r("autofill",["&:autofill"]),r("optional",["&:optional"]),r("required",["&:required"]),r("valid",["&:valid"]),r("invalid",["&:invalid"]),r("user-valid",["&:user-valid"]),r("user-invalid",["&:user-invalid"]),r("in-range",["&:in-range"]),r("out-of-range",["&:out-of-range"]),r("read-only",["&:read-only"]),r("empty",["&:empty"]),r("focus-within",["&:focus-within"]),i.static("hover",c=>{c.nodes=[J("&:hover",[q("@media","(hover: hover)",c.nodes)])]}),r("focus",["&:focus"]),r("focus-visible",["&:focus-visible"]),r("active",["&:active"]),r("enabled",["&:enabled"]),r("disabled",["&:disabled"]),r("inert",["&:is([inert], [inert] *)"]),i.compound("in",2,(c,d)=>{if(d.modifier)return null;let m=!1;if(I([c],(f,h)=>{if(f.kind!=="rule")return V.Continue;for(let w of h.path())if(w.kind==="rule")return m=!1,V.Stop;f.selector=`:where(${f.selector.replaceAll("&","*")}) &`,m=!0}),!m)return null}),i.suggest("in",()=>Array.from(i.keys()).filter(c=>i.compoundsWith("in",c))),i.compound("has",2,(c,d)=>{if(d.modifier)return null;let m=!1;if(I([c],(f,h)=>{if(f.kind!=="rule")return V.Continue;for(let w of h.path())if(w.kind==="rule")return m=!1,V.Stop;f.selector=`&:has(${f.selector.replaceAll("&","*")})`,m=!0}),!m)return null}),i.suggest("has",()=>Array.from(i.keys()).filter(c=>i.compoundsWith("has",c))),i.functional("aria",(c,d)=>{if(!d.value||d.modifier)return null;if(d.value.kind==="arbitrary"){let m=`[aria-${Qi(d.value.value)}]`;if(We(m)===null)return null;c.nodes=[J(`&${m}`,c.nodes)]}else{let m=`[aria-${d.value.value}="true"]`;if(We(m)===null)return null;c.nodes=[J(`&${m}`,c.nodes)]}}),i.suggest("aria",()=>["busy","checked","disabled","expanded","hidden","pressed","readonly","required","selected"]),i.functional("data",(c,d)=>{if(!d.value||d.modifier)return null;let m=`[data-${Qi(d.value.value)}]`;if(We(m)===null)return null;c.nodes=[J(`&${m}`,c.nodes)]}),i.functional("nth",(c,d)=>{if(!d.value||d.modifier||d.value.kind==="named"&&!U(d.value.value))return null;c.nodes=[J(`&:nth-child(${d.value.value})`,c.nodes)]}),i.functional("nth-last",(c,d)=>{if(!d.value||d.modifier||d.value.kind==="named"&&!U(d.value.value))return null;c.nodes=[J(`&:nth-last-child(${d.value.value})`,c.nodes)]}),i.functional("nth-of-type",(c,d)=>{if(!d.value||d.modifier||d.value.kind==="named"&&!U(d.value.value))return null;c.nodes=[J(`&:nth-of-type(${d.value.value})`,c.nodes)]}),i.functional("nth-last-of-type",(c,d)=>{if(!d.value||d.modifier||d.value.kind==="named"&&!U(d.value.value))return null;c.nodes=[J(`&:nth-last-of-type(${d.value.value})`,c.nodes)]}),i.functional("supports",(c,d)=>{if(!d.value||d.modifier)return null;let m=d.value.value;if(m===null)return null;if(/^[\w-]*\s*\(/.test(m)){let f=!1,h=Y(m);I(h,b=>{if(b.kind==="function"){if(b.value==="selector")return V.Skip;(b.value==="and"||b.value==="or"||b.value==="not")&&(f=!0,b.value=` ${b.value} `)}});let w=f?B(h):m;c.nodes=[q("@supports",w,c.nodes)];return}m.includes(":")||(m=`${m}: var(--tw)`),(m[0]!=="("||m[m.length-1]!==")")&&(m=`(${m})`),c.nodes=[q("@supports",m,c.nodes)]},{compounds:1}),r("motion-safe",["@media (prefers-reduced-motion: no-preference)"]),r("motion-reduce",["@media (prefers-reduced-motion: reduce)"]),r("contrast-more",["@media (prefers-contrast: more)"]),r("contrast-less",["@media (prefers-contrast: less)"]);{let c=function(d,m,f,h){if(d===m)return 0;let w=h.get(d);if(w===null)return f==="asc"?-1:1;let b=h.get(m);return b===null?f==="asc"?1:-1:Ne(w,b,f)};var u=c;{let d=e.namespace("--breakpoint"),m=new L(f=>{switch(f.kind){case"static":return e.resolveValue(f.root,["--breakpoint"])??null;case"functional":{if(!f.value||f.modifier)return null;let h=null;return f.value.kind==="arbitrary"?h=f.value.value:f.value.kind==="named"&&(h=e.resolveValue(f.value.value,["--breakpoint"])),!h||h.includes("var(")?null:h}case"arbitrary":case"compound":return null}});i.group(()=>{i.functional("max",(f,h)=>{if(h.modifier)return null;let w=m.get(h);if(w===null)return null;f.nodes=[q("@media",`(width < ${w})`,f.nodes)]},{compounds:1})},(f,h)=>c(f,h,"desc",m)),i.suggest("max",()=>Array.from(d.keys()).filter(f=>f!==null)),i.group(()=>{for(let[f,h]of e.namespace("--breakpoint"))f!==null&&i.static(f,w=>{w.nodes=[q("@media",`(width >= ${h})`,w.nodes)]},{compounds:1});i.functional("min",(f,h)=>{if(h.modifier)return null;let w=m.get(h);if(w===null)return null;f.nodes=[q("@media",`(width >= ${w})`,f.nodes)]},{compounds:1})},(f,h)=>c(f,h,"asc",m)),i.suggest("min",()=>Array.from(d.keys()).filter(f=>f!==null))}{let d=e.namespace("--container"),m=new L(f=>{switch(f.kind){case"functional":{if(f.value===null)return null;let h=null;return f.value.kind==="arbitrary"?h=f.value.value:f.value.kind==="named"&&(h=e.resolveValue(f.value.value,["--container"])),!h||h.includes("var(")?null:h}case"static":case"arbitrary":case"compound":return null}});i.group(()=>{i.functional("@max",(f,h)=>{let w=m.get(h);if(w===null)return null;f.nodes=[q("@container",h.modifier?`${h.modifier.value} (width < ${w})`:`(width < ${w})`,f.nodes)]},{compounds:1})},(f,h)=>c(f,h,"desc",m)),i.suggest("@max",()=>Array.from(d.keys()).filter(f=>f!==null)),i.group(()=>{i.functional("@",(f,h)=>{let w=m.get(h);if(w===null)return null;f.nodes=[q("@container",h.modifier?`${h.modifier.value} (width >= ${w})`:`(width >= ${w})`,f.nodes)]},{compounds:1}),i.functional("@min",(f,h)=>{let w=m.get(h);if(w===null)return null;f.nodes=[q("@container",h.modifier?`${h.modifier.value} (width >= ${w})`:`(width >= ${w})`,f.nodes)]},{compounds:1})},(f,h)=>c(f,h,"asc",m)),i.suggest("@min",()=>Array.from(d.keys()).filter(f=>f!==null)),i.suggest("@",()=>Array.from(d.keys()).filter(f=>f!==null))}}return r("portrait",["@media (orientation: portrait)"]),r("landscape",["@media (orientation: landscape)"]),r("ltr",['&:where(:dir(ltr), [dir="ltr"], [dir="ltr"] *)']),r("rtl",['&:where(:dir(rtl), [dir="rtl"], [dir="rtl"] *)']),r("dark",["@media (prefers-color-scheme: dark)"]),r("starting",["@starting-style"]),r("print",["@media print"]),r("forced-colors",["@media (forced-colors: active)"]),r("inverted-colors",["@media (inverted-colors: inverted)"]),r("pointer-none",["@media (pointer: none)"]),r("pointer-coarse",["@media (pointer: coarse)"]),r("pointer-fine",["@media (pointer: fine)"]),r("any-pointer-none",["@media (any-pointer: none)"]),r("any-pointer-coarse",["@media (any-pointer: coarse)"]),r("any-pointer-fine",["@media (any-pointer: fine)"]),r("noscript",["@media (scripting: none)"]),i}function Qi(e){if(e.includes("=")){let[i,...r]=F(e,"="),t=r.join("=").trim();if(t[0]==="'"||t[0]==='"')return e;if(t.length>1){let n=t[t.length-1];if(t[t.length-2]===" "&&(n==="i"||n==="I"||n==="s"||n==="S"))return`${i}="${t.slice(0,-2)}" ${n}`}return`${i}="${t}"`}return e}function ot(e,i){I(e,r=>{if(r.kind==="at-rule"&&r.name==="@slot")return V.ReplaceSkip(i);if(r.kind==="at-rule"&&(r.name==="@keyframes"||r.name==="@property"))return Object.assign(r,H([q(r.name,r.params,r.nodes)])),V.Skip})}function st(e,i){let r=0;return I(e,t=>{if(t.kind!=="at-rule"||t.name!=="@variant")return;let n=[],s=F(t.params,",");for(let[l,p]of s.entries()){let u=J("&",l===s.length-1?t.nodes:t.nodes.map(le)),c=F(p,":");for(let d=c.length-1;d>=0;--d){let m=c[d].trim();if(!m)throw new Error("Cannot use `@variant` with empty variant");let f=i.parseVariant(m);if(f===null)throw new Error(`Cannot use \`@variant\` with unknown variant: ${m}`);if(Ge(u,f,i.variants)===null)throw new Error(`Cannot use \`@variant\` with variant: ${m}`)}u.selector==="&"?n.push(...u.nodes):n.push(u)}return r|=32,V.Replace(n)}),r}function en(e,i){let r=vi(e),t=Xi(e),n=new L(h=>ci(h,f)),s=null,l=-1,p=new L(h=>Array.from(fi(h,f))),u=new L(h=>new L(w=>{let b=tn(w,f,h);try{let k=b.map(A=>A.node);Me(k,f),st(k,f)}catch{return[]}return b})),c=new L(h=>{for(let w of bt(h))e.markUsedVariable(w)});function d(h){let w=[];for(let b of h){let k=!0,{astNodes:A}=Se([b],f,{onInvalidCandidate(){k=!1}});i&&I(A,C=>(C.src??=i,V.Continue)),A=Te(A,f,0),w.push(k?A:[])}return w}function m(h){return d(h).map(w=>w.length>0?ue(w):null)}let f={theme:e,utilities:r,variants:t,invalidCandidates:new Set,important:!1,candidatesToCss:m,candidatesToAst:d,getClassOrder(h){return Ji(this,h)},getClassList(){return Hi(this)},getVariants(){return Zi(this)},parseCandidate(h){return p.get(h)},parseVariant(h){return n.get(h)},compileAstNodes(h,w=1){return u.get(w).get(h)},printCandidate(h){return di(f,h)},printVariant(h){return At(h)},getVariantOrder(){if(s!==null&&l===n.size)return s;let h=Array.from(n.values());h.sort((A,C)=>this.variants.compare(A,C));let w=new Map,b,k=0;for(let A of h)A!==null&&(b!==void 0&&this.variants.compare(b,A)!==0&&k++,w.set(A,k),b=A);return s=w,l=n.size,w},resolveThemeValue(h,w=!0){let b=h.lastIndexOf("/"),k=null;b!==-1&&(k=h.slice(b+1).trim(),h=h.slice(0,b).trim());let A=e.resolve(null,[h],w?1:0)??void 0;return k&&A?ie(A,k):A},trackUsedVariables(h){c.get(h)},canonicalizeCandidates(h,w){return dr(this,h,w)},storage:{}};return f}var wr=["container-type","pointer-events","visibility","position","inset","inset-inline","inset-block","inset-inline-start","inset-inline-end","inset-block-start","inset-block-end","top","right","bottom","left","isolation","z-index","order","grid-column","grid-column-start","grid-column-end","grid-row","grid-row-start","grid-row-end","float","clear","--tw-container-component","margin","margin-inline","margin-block","margin-inline-start","margin-inline-end","margin-block-start","margin-block-end","margin-top","margin-right","margin-bottom","margin-left","box-sizing","display","field-sizing","aspect-ratio","height","max-height","min-height","width","max-width","min-width","flex","flex-shrink","flex-grow","flex-basis","table-layout","caption-side","border-collapse","border-spacing","transform-origin","translate","--tw-translate-x","--tw-translate-y","--tw-translate-z","scale","--tw-scale-x","--tw-scale-y","--tw-scale-z","rotate","--tw-rotate-x","--tw-rotate-y","--tw-rotate-z","--tw-skew-x","--tw-skew-y","transform","zoom","animation","cursor","touch-action","--tw-pan-x","--tw-pan-y","--tw-pinch-zoom","resize","scroll-snap-type","--tw-scroll-snap-strictness","scroll-snap-align","scroll-snap-stop","scroll-margin","scroll-margin-inline","scroll-margin-block","scroll-margin-inline-start","scroll-margin-inline-end","scroll-margin-block-start","scroll-margin-block-end","scroll-margin-top","scroll-margin-right","scroll-margin-bottom","scroll-margin-left","scroll-padding","scroll-padding-inline","scroll-padding-block","scroll-padding-inline-start","scroll-padding-inline-end","scroll-padding-block-start","scroll-padding-block-end","scroll-padding-top","scroll-padding-right","scroll-padding-bottom","scroll-padding-left","scrollbar-width","scrollbar-color","scrollbar-gutter","list-style-position","list-style-type","list-style-image","appearance","columns","break-before","break-inside","break-after","grid-auto-columns","grid-auto-flow","grid-auto-rows","grid-template-columns","grid-template-rows","flex-direction","flex-wrap","place-content","place-items","align-content","align-items","justify-content","justify-items","gap","column-gap","row-gap","--tw-space-x-reverse","--tw-space-y-reverse","divide-x-width","divide-y-width","--tw-divide-y-reverse","divide-style","divide-color","place-self","align-self","justify-self","overflow","overflow-x","overflow-y","overscroll-behavior","overscroll-behavior-x","overscroll-behavior-y","scroll-behavior","border-radius","border-start-radius","border-end-radius","border-top-radius","border-right-radius","border-bottom-radius","border-left-radius","border-start-start-radius","border-start-end-radius","border-end-end-radius","border-end-start-radius","border-top-left-radius","border-top-right-radius","border-bottom-right-radius","border-bottom-left-radius","border-width","border-inline-width","border-block-width","border-inline-start-width","border-inline-end-width","border-block-start-width","border-block-end-width","border-top-width","border-right-width","border-bottom-width","border-left-width","border-style","border-inline-style","border-block-style","border-inline-start-style","border-inline-end-style","border-block-start-style","border-block-end-style","border-top-style","border-right-style","border-bottom-style","border-left-style","border-color","border-inline-color","border-block-color","border-inline-start-color","border-inline-end-color","border-block-start-color","border-block-end-color","border-top-color","border-right-color","border-bottom-color","border-left-color","background-color","background-image","--tw-gradient-position","--tw-gradient-stops","--tw-gradient-via-stops","--tw-gradient-from","--tw-gradient-from-position","--tw-gradient-via","--tw-gradient-via-position","--tw-gradient-to","--tw-gradient-to-position","mask-image","--tw-mask-top","--tw-mask-top-from-color","--tw-mask-top-from-position","--tw-mask-top-to-color","--tw-mask-top-to-position","--tw-mask-right","--tw-mask-right-from-color","--tw-mask-right-from-position","--tw-mask-right-to-color","--tw-mask-right-to-position","--tw-mask-bottom","--tw-mask-bottom-from-color","--tw-mask-bottom-from-position","--tw-mask-bottom-to-color","--tw-mask-bottom-to-position","--tw-mask-left","--tw-mask-left-from-color","--tw-mask-left-from-position","--tw-mask-left-to-color","--tw-mask-left-to-position","--tw-mask-linear","--tw-mask-linear-position","--tw-mask-linear-from-color","--tw-mask-linear-from-position","--tw-mask-linear-to-color","--tw-mask-linear-to-position","--tw-mask-radial","--tw-mask-radial-shape","--tw-mask-radial-size","--tw-mask-radial-position","--tw-mask-radial-from-color","--tw-mask-radial-from-position","--tw-mask-radial-to-color","--tw-mask-radial-to-position","--tw-mask-conic","--tw-mask-conic-position","--tw-mask-conic-from-color","--tw-mask-conic-from-position","--tw-mask-conic-to-color","--tw-mask-conic-to-position","box-decoration-break","background-size","background-attachment","background-clip","background-position","background-repeat","background-origin","mask-composite","mask-mode","mask-type","mask-size","mask-clip","mask-position","mask-repeat","mask-origin","fill","stroke","stroke-width","object-fit","object-position","padding","padding-inline","padding-block","padding-inline-start","padding-inline-end","padding-block-start","padding-block-end","padding-top","padding-right","padding-bottom","padding-left","text-align","text-indent","vertical-align","font-family","font-feature-settings","font-size","line-height","font-weight","letter-spacing","text-wrap","overflow-wrap","word-break","text-overflow","hyphens","white-space","tab-size","color","text-transform","font-style","font-stretch","font-variant-numeric","text-decoration-line","text-decoration-color","text-decoration-style","text-decoration-thickness","text-underline-offset","-webkit-font-smoothing","placeholder-color","caret-color","accent-color","color-scheme","opacity","background-blend-mode","mix-blend-mode","box-shadow","--tw-shadow","--tw-shadow-color","--tw-ring-shadow","--tw-ring-color","--tw-inset-shadow","--tw-inset-shadow-color","--tw-inset-ring-shadow","--tw-inset-ring-color","--tw-ring-offset-width","--tw-ring-offset-color","outline","outline-width","outline-offset","outline-color","--tw-blur","--tw-brightness","--tw-contrast","--tw-drop-shadow","--tw-grayscale","--tw-hue-rotate","--tw-invert","--tw-saturate","--tw-sepia","filter","--tw-backdrop-blur","--tw-backdrop-brightness","--tw-backdrop-contrast","--tw-backdrop-grayscale","--tw-backdrop-hue-rotate","--tw-backdrop-invert","--tw-backdrop-opacity","--tw-backdrop-saturate","--tw-backdrop-sepia","backdrop-filter","transition-property","transition-behavior","transition-delay","transition-duration","transition-timing-function","will-change","contain","content","forced-color-adjust"];function Se(e,i,{onInvalidCandidate:r,respectImportant:t}={}){let n=new Map,s=[],l=new Map;for(let c of e){if(i.invalidCandidates.has(c)){r?.(c);continue}let d=i.parseCandidate(c);if(d.length===0){r?.(c);continue}l.set(c,d)}let p=0;(t??!0)&&(p|=1);let u=l.size>1?i.getVariantOrder():null;for(let[c,d]of l){let m=!1;for(let f of d){let h=i.compileAstNodes(f,p);if(h.length!==0){m=!0;for(let{node:w,propertySort:b}of h){let k=0n;if(u!==null)for(let A of f.variants)k|=1n<{let m=n.get(c),f=n.get(d);if(m.variants-f.variants!==0n)return Number(m.variants-f.variants);let h=0;for(;h1)return null;for(let u of l.nodes)if(u.kind!=="rule"&&u.kind!=="at-rule"||n(u,i)===null)return null;I(l.nodes,u=>{if((u.kind==="rule"||u.kind==="at-rule")&&u.nodes.length<=0)return u.nodes=e.nodes,V.Skip}),e.nodes=l.nodes;return}if(n(e,i)===null)return null}function rn(e){let i=e.options?.types??[];return i.length>1&&i.includes("any")}function Na(e,i){if(e.kind==="arbitrary"){let l=e.value;return e.modifier&&(l=ne(l,e.modifier,i.theme)),l===null?[]:[[o(e.property,l)]]}let r=i.utilities.get(e.root)??[],t=[],n=r.filter(l=>!rn(l));for(let l of n){if(l.kind!==e.kind)continue;let p=l.compileFn(e);if(p!==void 0){if(p===null){if(l.options?.types?.length)return t;continue}t.push(p)}}if(t.length>0)return t;let s=r.filter(l=>rn(l));for(let l of s){if(l.kind!==e.kind)continue;let p=l.compileFn(e);if(p!==void 0){if(p===null){if(l.options?.types?.length)return t;continue}t.push(p)}}return t}function nn(e){for(let i of e)i.kind!=="at-root"&&(i.kind==="declaration"?i.important=!0:(i.kind==="rule"||i.kind==="at-rule")&&nn(i.nodes))}function Ea(e){let i=new Set,r=0,t=e.slice(),n=!1;for(;t.length>0;){let s=t.shift();if(s.kind==="declaration"){if(s.value===void 0||(r++,n))continue;if(s.property==="--tw-sort"){let p=wr.indexOf(s.value??"");if(p!==-1){i.add(p),n=!0;continue}}let l=wr.indexOf(s.property);l!==-1&&i.add(l)}else if(s.kind==="rule"||s.kind==="at-rule")for(let l of s.nodes)t.push(l)}return{order:Array.from(i).sort((s,l)=>s-l),count:r}}function Ce(e,i){let r=0,t=Q("&",e),n=new Set,s=new L(()=>new Set),l=new L(()=>new Set);I([t],(m,f)=>{if(m.kind==="at-rule"){if(m.name==="@keyframes")return I(m.nodes,h=>{if(h.kind==="at-rule"&&h.name==="@apply")throw new Error("You cannot use `@apply` inside `@keyframes`.")}),V.Skip;if(m.name==="@utility"){let h=m.params.replace(/-\*$/,"");l.get(h).add(m),I(m.nodes,w=>{if(!(w.kind!=="at-rule"||w.name!=="@apply")){n.add(m);for(let b of ln(w,i))s.get(m).add(b)}});return}if(m.name==="@apply"){if(f.parent===null)return;r|=1,n.add(f.parent);for(let h of ln(m,i))for(let w of f.path())n.has(w)&&s.get(w).add(h)}}});let p=new Set,u=[],c=new Set;function d(m,f=[]){if(!p.has(m)){if(c.has(m)){let h=f[(f.indexOf(m)+1)%f.length];throw m.kind==="at-rule"&&m.name==="@utility"&&h.kind==="at-rule"&&h.name==="@utility"&&I(m.nodes,w=>{if(w.kind!=="at-rule"||w.name!=="@apply")return;let b=w.params.split(/\s+/g);for(let k of b)for(let A of i.parseCandidate(k))switch(A.kind){case"arbitrary":break;case"static":case"functional":if(h.params.replace(/-\*$/,"")===A.root)throw new Error(`You cannot \`@apply\` the \`${k}\` utility here because it creates a circular dependency.`);break;default:}}),new Error(`Circular dependency detected: + +${ue([m])} +Relies on: + +${ue([h])}`)}c.add(m);for(let h of s.get(m))for(let w of l.get(h))f.push(m),d(w,f),f.pop();p.add(m),c.delete(m),u.push(m)}}for(let m of n)d(m);for(let m of u)"nodes"in m&&I(m.nodes,f=>{if(f.kind!=="at-rule"||f.name!=="@apply")return;let h=f.params.split(/(\s+)/g),w={},b=[],k=[],A=0;for(let[y,E]of h.entries())y%2===0&&(E[0]==="-"&&E[1]==="-"?k.push(E):b.push(E),w[E]=A),A+=E.length;if(k.length){if(b.length===0)return V.Skip;let y=k.join(" ");throw new Error(`You cannot use \`@apply\` with both mixins and utilities. Please move \`@apply ${y}\` into a separate rule.`)}if(f.nodes.length>0&&b.length){let y=b.join(" ");throw new Error(`The rule \`@apply ${y}\` must not have a body.`)}{let y=Object.keys(w),E=Se(y,i,{respectImportant:!1,onInvalidCandidate:R=>{if(i.theme.prefix&&!R.startsWith(i.theme.prefix))throw new Error(`Cannot apply unprefixed utility class \`${R}\`. Did you mean \`${i.theme.prefix}:${R}\`?`);if(i.invalidCandidates.has(R))throw new Error(`Cannot apply utility class \`${R}\` because it has been explicitly disabled: https://tailwindcss.com/docs/detecting-classes-in-source-files#explicitly-excluding-classes`);let W=F(R,":");if(W.length>1){let D=W.pop();if(i.candidatesToCss([D])[0]){let z=i.candidatesToCss(W.map(Z=>`${Z}:[--tw-variant-check:1]`)),j=W.filter((Z,a)=>z[a]===null);if(j.length>0){if(j.length===1)throw new Error(`Cannot apply utility class \`${R}\` because the ${j.map(Z=>`\`${Z}\``)} variant does not exist.`);{let Z=new Intl.ListFormat("en",{style:"long",type:"conjunction"});throw new Error(`Cannot apply utility class \`${R}\` because the ${Z.format(j.map(a=>`\`${a}\``))} variants do not exist.`)}}}}throw i.theme.size===0?new Error(`Cannot apply unknown utility class \`${R}\`. Are you using CSS modules or similar and missing \`@reference\`? https://tailwindcss.com/docs/functions-and-directives#reference-directive`):new Error(`Cannot apply unknown utility class \`${R}\``)}}),O=f.src,P=E.astNodes.map(R=>{let W=E.nodeSorting.get(R)?.candidate,D=W?w[W]:void 0;if(R=le(R),!O||!W||D===void 0)return I([R],j=>{j.src=O}),R;let z=[O[0],O[1],O[2]];return z[1]+=7+D,z[2]=z[1]+W.length,I([R],j=>{j.src=z}),R}),K=[];for(let R of P)if(R.kind==="rule")for(let W of R.nodes)K.push(W);else K.push(R);return V.Replace(K)}});return r}function*ln(e,i){for(let r of e.params.split(/\s+/g))for(let t of i.parseCandidate(r))switch(t.kind){case"arbitrary":break;case"static":case"functional":yield t.root;break;default:}}async function kr(e,i,r,t=0,n=!1){let s=0,l=[];return I(e,p=>{if(p.kind==="at-rule"&&(p.name==="@import"||p.name==="@reference")){let u=Ra(Y(p.params));if(u===null)return;p.name==="@reference"&&(u.media="reference"),s|=2;let{uri:c,layer:d,media:m,supports:f}=u;if(c.startsWith("data:")||c.startsWith("http://")||c.startsWith("https://"))return;let h=ee({},[]);return l.push((async()=>{if(t>100)throw new Error(`Exceeded maximum recursion depth while resolving \`${c}\` in \`${i}\`)`);let w=await r(c,i),b=$e(w.content,{from:n?w.path:void 0});await kr(b,w.base,r,t+1,n),h.nodes=Pa(p,[ee({base:w.base},b)],d,m,f)})()),V.ReplaceSkip(h)}}),l.length>0&&await Promise.all(l),s}function Ra(e){let i,r=null,t=null,n=null;for(let s=0;s{let c=Re(n),[d,m]=Oa(e.theme,c),f=r(an(i()??{},c)??null);if(typeof f=="string"&&(f=f.replace("","1")),typeof d!="object")return typeof m!="object"&&m&4?f??d:d;if(f!==null&&typeof f=="object"&&!Array.isArray(f)){let h=ut({},[f],(w,b)=>b);if(d===null&&Object.hasOwn(f,"__CSS_VALUES__")){let w={};for(let b in f.__CSS_VALUES__)w[b]=f[b],delete h[b];d=w}for(let w in d)w!=="__CSS_VALUES__"&&(f?.__CSS_VALUES__?.[w]&4&&an(h,w.split("-"))!==void 0||(h[_e(w)]=d[w]));return h}if(Array.isArray(d)&&Array.isArray(m)&&Array.isArray(f)){let h=d[0],w=d[1];m[0]&4&&(h=f[0]??h);for(let b of Object.keys(w))m[1][b]&4&&(w[b]=f[1][b]??w[b]);return[h,w]}return c.length>1&&d!==null&&typeof d=="object"&&!Array.isArray(d)&&"DEFAULT"in d?d.DEFAULT:d??f})();return p&&typeof u=="string"&&(u=ie(u,p)),u??s}}function Oa(e,i){if(i.length===1&&i[0].startsWith("--"))return[e.get([i[0]]),e.getOptions(i[0])];let r=Ye(i),t=new Map,n=new L(()=>new Map),s=e.namespace(`--${r}`);if(s.size===0)return[null,0];let l=new Map;for(let[d,m]of s){if(!d||!d.includes("--")){t.set(d,m),l.set(d,e.getOptions(d?`--${r}-${d}`:`--${r}`));continue}let f=d.indexOf("--"),h=d.slice(0,f),w=d.slice(f+2);w=w.replace(/-([a-z])/g,(b,k)=>k.toUpperCase()),n.get(h===""?null:h).set(w,[m,e.getOptions(`--${r}${d}`)])}let p=e.getOptions(`--${r}`);for(let[d,m]of n){let f=t.get(d);if(typeof f!="string")continue;let h={},w={};for(let[b,[k,A]]of m)h[b]=k,w[b]=A;t.set(d,[f,h]),l.set(d,[p,w])}let u={},c={};for(let[d,m]of t)on(u,[d??"DEFAULT"],m);for(let[d,m]of l)on(c,[d??"DEFAULT"],m);return i[i.length-1]==="DEFAULT"?[u?.DEFAULT??null,c.DEFAULT??0]:i.length>1&&"DEFAULT"in u&&Object.keys(u).length===1?[u.DEFAULT,c.DEFAULT??0]:(u.__CSS_VALUES__=c,[u,c])}function an(e,i){for(let r=0;r{d.src=s}),i.push(c)},addVariant(p,u){if(!It.test(p))throw new Error(`\`addVariant('${p}')\` defines an invalid variant name. Variants should only contain alphanumeric, dashes, or underscore characters and start with a lowercase letter or number.`);if(typeof u=="string"){if(u.includes(":merge("))return}else if(Array.isArray(u)){if(u.some(d=>d.includes(":merge(")))return}else if(typeof u=="object"){let d=function(m,f){return Object.entries(m).some(([h,w])=>h.includes(f)||typeof w=="object"&&d(w,f))};var c=d;if(d(u,":merge("))return}typeof u=="string"||Array.isArray(u)?e.variants.static(p,d=>{d.nodes=un(u,d.nodes)},{compounds:Pe(typeof u=="string"?[u]:u)}):typeof u=="object"&&e.variants.fromAst(p,ke(u),e)},matchVariant(p,u,c){function d(f,h,w){let b=u(f,{modifier:h?.value??null});return un(b,w)}try{let f=u("a",{modifier:null});if(typeof f=="string"&&f.includes(":merge("))return;if(Array.isArray(f)&&f.some(h=>h.includes(":merge(")))return}catch{}let m=Object.keys(c?.values??{});e.variants.group(()=>{e.variants.functional(p,(f,h)=>{if(!h.value){if(c?.values&&"DEFAULT"in c.values){f.nodes=d(c.values.DEFAULT,h.modifier,f.nodes);return}return null}if(h.value.kind==="arbitrary")f.nodes=d(h.value.value,h.modifier,f.nodes);else if(h.value.kind==="named"&&c?.values){if(!Object.hasOwn(c.values,h.value.value))return null;let w=c.values[h.value.value];if(typeof w!="string")return null;f.nodes=d(w,h.modifier,f.nodes)}else return null})},(f,h)=>{if(f.kind!=="functional"||h.kind!=="functional")return 0;let w=f.value?f.value.value:"DEFAULT",b=h.value?h.value.value:"DEFAULT",k=(c?.values&&Object.hasOwn(c.values,w)?c.values[w]:void 0)??w,A=(c?.values&&Object.hasOwn(c.values,b)?c.values[b]:void 0)??b;if(c&&typeof c.sort=="function")return c.sort({value:k,modifier:f.modifier?.value??null},{value:A,modifier:h.modifier?.value??null});let C=m.indexOf(w),y=m.indexOf(b);return C=C===-1?m.length:C,y=y===-1?m.length:y,C!==y?C-y:kObject.keys(c?.values??{}).filter(f=>f!=="DEFAULT"))},addUtilities(p){p=Array.isArray(p)?p:[p];let u=p.flatMap(d=>Object.entries(d));u=u.flatMap(([d,m])=>F(d,",").map(f=>[f.trim(),m]));let c=new L(()=>[]);for(let[d,m]of u){if(d.startsWith("@keyframes ")){if(!n){let w=Q(d,ke(m));I([w],b=>{b.src=s}),i.push(w)}continue}let f=ce(d),h=!1;if(I(f,w=>{if(w.kind==="selector"&&w.value[0]==="."&&sn.test(w.value.slice(1))){let b=w.value;w.value="&";let k=se(f),A=b.slice(1),C=k==="&"?ke(m):[Q(k,ke(m))];c.get(A).push(...C),h=!0,w.value=b;return}if(w.kind==="function"&&(w.value===":not"||w.value===":nth-child"||w.value===":nth-last-child"))return V.Skip}),!h)throw new Error(`\`addUtilities({ '${d}' : \u2026 })\` defines an invalid utility selector. Utilities must be a single class name and start with a lowercase letter, eg. \`.scrollbar-none\`.`)}for(let[d,m]of c)e.theme.prefix&&I(m,f=>{if(f.kind==="rule"){let h=ce(f.selector);I(h,w=>{w.kind==="selector"&&w.value[0]==="."&&(w.value=`.${e.theme.prefix}\\:${w.value.slice(1)}`)}),f.selector=se(h)}}),e.utilities.static(d,f=>{let h=m.map(le);return fn(h,d,f.raw),t.current|=Ce(h,e),h})},matchUtilities(p,u){let c=u?.type?Array.isArray(u?.type)?u.type:[u.type]:["any"];for(let[m,f]of Object.entries(p)){let h=function({negative:w}){return b=>{if(b.value?.kind==="arbitrary"&&c.length>0&&!c.includes("any")&&(b.value.dataType&&!c.includes(b.value.dataType)||!b.value.dataType&&!X(b.value.value,c)))return;let k=c.includes("color"),A=null,C=!1;{let O=u?.values??{};k&&(O=Object.assign({inherit:"inherit",transparent:"transparent",current:"currentcolor"},O)),b.value?b.value.kind==="arbitrary"?A=b.value.value:b.value.fraction&&Object.hasOwn(O,b.value.fraction)?(A=O[b.value.fraction],C=!0):Object.hasOwn(O,b.value.value)?A=O[b.value.value]:O.__BARE_VALUE__&&(A=O.__BARE_VALUE__(b.value)??null,C=(b.value.fraction!==null&&A?.includes("/"))??!1):A=O.DEFAULT??null}if(A===null)return;let y;{let O=u?.modifiers??null;b.modifier?O==="any"||b.modifier.kind==="arbitrary"?y=b.modifier.value:O&&Object.hasOwn(O,b.modifier.value)?y=O[b.modifier.value]:k&&!Number.isNaN(Number(b.modifier.value))?y=`${b.modifier.value}%`:y=null:y=null}if(b.modifier&&y===null&&!C)return b.value?.kind==="arbitrary"?null:void 0;k&&y!==null&&(A=ie(A,y)),w&&(A=`calc(${A} * -1)`);let E=ke(f(A,{modifier:y}));return fn(E,m,b.raw),t.current|=Ce(E,e),E}};var d=h;if(!sn.test(m))throw new Error(`\`matchUtilities({ '${m}' : \u2026 })\` defines an invalid utility name. Utilities should be alphanumeric and start with a lowercase letter, eg. \`scrollbar\`.`);u?.supportsNegativeValues&&e.utilities.functional(`-${m}`,h({negative:!0}),{types:c}),e.utilities.functional(m,h({negative:!1}),{types:c}),e.utilities.suggest(m,()=>{let w=u?.values??{},b=new Set(Object.keys(w));b.delete("__BARE_VALUE__"),b.delete("__CSS_VALUES__"),b.has("DEFAULT")&&(b.delete("DEFAULT"),b.add(null));let k=u?.modifiers??{},A=k==="any"?[]:Object.keys(k);return[{supportsNegative:u?.supportsNegativeValues??!1,values:Array.from(b),modifiers:A}]})}},addComponents(p,u){this.addUtilities(p,u)},matchComponents(p,u){this.matchUtilities(p,u)},theme:Dt(e,()=>r.theme??{},p=>p),prefix(p){return p},config(p,u){let c=r;if(!p)return c;let d=Re(p);for(let m=0;mObject.entries(t));for(let[t,n]of r)if(n!=null&&n!==!1)if(typeof n!="object"){if(!t.startsWith("--")){if(n==="@slot"){i.push(Q(t,[q("@slot")]));continue}t=t.replace(/([A-Z])/g,"-$1").toLowerCase()}i.push(o(t,String(n)))}else if(Array.isArray(n))for(let s of n)typeof s=="string"?i.push(o(t,s)):i.push(Q(t,ke(s)));else i.push(Q(t,ke(n)));return i}function un(e,i){return(typeof e=="string"?[e]:e).flatMap(t=>{if(t.trim().endsWith("}")){let n=t.includes("@scope"),s=t.replace("}","{@slot}}"),l=$e(s);return n?(ot(l,[ee({source:"user"},i)]),ee({source:"variant"},l)):(ot(l,i),l)}else{let n=Q(t,i);return n.kind==="at-rule"&&n.name==="@scope"?(n.nodes=[ee({source:"user"},i)],ee({source:"variant"},[n])):n}})}function fn(e,i,r){I(e,t=>{if(t.kind==="rule"){let n=ce(t.selector);I(n,s=>{s.kind==="selector"&&s.value===`.${i}`&&(s.value=`.${Oe(r)}`)}),t.selector=se(n)}})}function cn(e,i){for(let r of _a(i))e.theme.addKeyframes(r)}function _a(e){let i=[];if("keyframes"in e.theme)for(let[r,t]of Object.entries(e.theme.keyframes))i.push(q("@keyframes",r,ke(t)));return i}function pn(e){return{theme:{...Vr,colors:({theme:i})=>i("color",{}),extend:{fontSize:({theme:i})=>({...i("text",{})}),boxShadow:({theme:i})=>({...i("shadow",{})}),animation:({theme:i})=>({...i("animate",{})}),aspectRatio:({theme:i})=>({...i("aspect",{})}),borderRadius:({theme:i})=>({...i("radius",{})}),screens:({theme:i})=>({...i("breakpoint",{})}),letterSpacing:({theme:i})=>({...i("tracking",{})}),lineHeight:({theme:i})=>({...i("leading",{})}),transitionDuration:{DEFAULT:e.get(["--default-transition-duration"])??null},transitionTimingFunction:{DEFAULT:e.get(["--default-transition-timing-function"])??null},maxWidth:({theme:i})=>({...i("container",{})})}}}}var Ia={blocklist:[],future:{},experimental:{},prefix:"",important:!1,darkMode:null,theme:{},plugins:[],content:{files:[]}};function xr(e,i){let r={design:e,configs:[],plugins:[],content:{files:[]},theme:{},extend:{},result:structuredClone(Ia)};for(let n of i)yr(r,n);for(let n of r.configs)"darkMode"in n&&n.darkMode!==void 0&&(r.result.darkMode=n.darkMode??null),"prefix"in n&&n.prefix!==void 0&&(r.result.prefix=n.prefix??""),"blocklist"in n&&n.blocklist!==void 0&&(r.result.blocklist=n.blocklist??[]),"important"in n&&n.important!==void 0&&(r.result.important=n.important??!1);let t=Ka(r);return{resolvedConfig:{...r.result,content:r.content,theme:r.theme,plugins:r.plugins},replacedThemeKeys:t}}function Da(e,i){if(Array.isArray(e)&&qe(e[0]))return e.concat(i);if(Array.isArray(i)&&qe(i[0])&&qe(e))return[e,...i];if(Array.isArray(i))return i}function yr(e,{config:i,base:r,path:t,reference:n,src:s}){let l=[];for(let c of i.plugins??[])"__isOptionsFunction"in c?l.push({...c(),reference:n,src:s}):"handler"in c?l.push({...c,reference:n,src:s}):l.push({handler:c,reference:n,src:s});if(Array.isArray(i.presets)&&i.presets.length===0)throw new Error("Error in the config file/plugin/preset. An empty preset (`preset: []`) is not currently supported.");for(let c of i.presets??[])yr(e,{path:t,base:r,config:c,reference:n,src:s});for(let c of l)e.plugins.push(c),c.config&&yr(e,{path:t,base:r,config:c.config,reference:!!c.reference,src:c.src??s});let p=i.content??[],u=Array.isArray(p)?p:p.files;for(let c of u)e.content.files.push(typeof c=="object"?c:{base:r,pattern:c});e.configs.push(i)}function Ka(e){let i=new Set,r=Dt(e.design,()=>e.theme,n),t=Object.assign(r,{theme:r,colors:Sr});function n(s){return typeof s=="function"?s(t)??null:s??null}for(let s of e.configs){let l=s.theme??{},p=l.extend??{};for(let u in l)u!=="extend"&&i.add(u);Object.assign(e.theme,l);for(let u in p)e.extend[u]??=[],e.extend[u].push(p[u])}delete e.theme.extend;for(let s in e.extend){let l=[e.theme[s],...e.extend[s]];e.theme[s]=()=>{let p=l.map(n);return ut({},p,Da)}}for(let s in e.theme)e.theme[s]=n(e.theme[s]);if(e.theme.screens&&typeof e.theme.screens=="object")for(let s of Object.keys(e.theme.screens)){let l=e.theme.screens[s];l&&typeof l=="object"&&("raw"in l||"max"in l||"min"in l&&(e.theme.screens[s]=l.min))}return i}function dn(e,i){let r=e.theme.container||{};if(typeof r!="object"||r===null)return;let t=Ua(r,i);t.length!==0&&i.utilities.static("container",()=>t.map(le))}function Ua({center:e,padding:i,screens:r},t){let n=[],s=null;if(e&&n.push(o("margin-inline","auto")),(typeof i=="string"||typeof i=="object"&&i!==null&&"DEFAULT"in i)&&n.push(o("padding-inline",typeof i=="string"?i:i.DEFAULT)),typeof r=="object"&&r!==null){s=new Map;let l=Array.from(t.theme.namespace("--breakpoint").entries());if(l.sort((p,u)=>Ne(p[1],u[1],"asc")),l.length>0){let[p]=l[0];n.push(q("@media",`(width >= --theme(--breakpoint-${p}))`,[o("max-width","none")]))}for(let[p,u]of Object.entries(r)){if(typeof u=="object")if("min"in u)u=u.min;else continue;s.set(p,q("@media",`(width >= ${u})`,[o("max-width",u)]))}}if(typeof i=="object"&&i!==null){let l=Object.entries(i).filter(([p])=>p!=="DEFAULT").map(([p,u])=>[p,t.theme.resolveValue(p,["--breakpoint"]),u]).filter(Boolean);l.sort((p,u)=>Ne(p[1],u[1],"asc"));for(let[p,,u]of l)if(s&&s.has(p))s.get(p).nodes.push(o("padding-inline",u));else{if(s)continue;n.push(q("@media",`(width >= theme(--breakpoint-${p}))`,[o("padding-inline",u)]))}}if(s)for(let[,l]of s)n.push(l);return n}function mn({addVariant:e,config:i}){let r=i("darkMode",null),[t,n=".dark"]=Array.isArray(r)?r:[r];if(t==="variant"){let s;if(Array.isArray(n)||typeof n=="function"?s=n:typeof n=="string"&&(s=[n]),Array.isArray(s))for(let l of s)l===".dark"?(t=!1,console.warn('When using `variant` for `darkMode`, you must provide a selector.\nExample: `darkMode: ["variant", ".your-selector &"]`')):l.includes("&")||(t=!1,console.warn('When using `variant` for `darkMode`, your selector must contain `&`.\nExample `darkMode: ["variant", ".your-selector &"]`'));n=s}t===null||(t==="selector"?e("dark",`&:where(${n}, ${n} *)`):t==="media"?e("dark","@media (prefers-color-scheme: dark)"):t==="variant"?e("dark",n):t==="class"&&e("dark",`&:is(${n} *)`))}function gn(e){for(let[r,t]of[["t","top"],["tr","top right"],["r","right"],["br","bottom right"],["b","bottom"],["bl","bottom left"],["l","left"],["tl","top left"]])e.utilities.suggest(`bg-gradient-to-${r}`,()=>[]),e.utilities.static(`bg-gradient-to-${r}`,()=>[o("--tw-gradient-position",`to ${t} in oklab`),o("background-image","linear-gradient(var(--tw-gradient-stops))")]);e.utilities.suggest("bg-left-top",()=>[]),e.utilities.static("bg-left-top",()=>[o("background-position","left top")]),e.utilities.suggest("bg-right-top",()=>[]),e.utilities.static("bg-right-top",()=>[o("background-position","right top")]),e.utilities.suggest("bg-left-bottom",()=>[]),e.utilities.static("bg-left-bottom",()=>[o("background-position","left bottom")]),e.utilities.suggest("bg-right-bottom",()=>[]),e.utilities.static("bg-right-bottom",()=>[o("background-position","right bottom")]),e.utilities.suggest("object-left-top",()=>[]),e.utilities.static("object-left-top",()=>[o("object-position","left top")]),e.utilities.suggest("object-right-top",()=>[]),e.utilities.static("object-right-top",()=>[o("object-position","right top")]),e.utilities.suggest("object-left-bottom",()=>[]),e.utilities.static("object-left-bottom",()=>[o("object-position","left bottom")]),e.utilities.suggest("object-right-bottom",()=>[]),e.utilities.static("object-right-bottom",()=>[o("object-position","right bottom")]),e.utilities.suggest("max-w-screen",()=>[]),e.utilities.functional("max-w-screen",r=>{if(!r.value||r.value.kind==="arbitrary")return;let t=e.theme.resolve(r.value.value,["--breakpoint"]);if(t)return[o("max-width",t)]}),e.utilities.suggest("overflow-ellipsis",()=>[]),e.utilities.static("overflow-ellipsis",()=>[o("text-overflow","ellipsis")]),e.utilities.suggest("decoration-slice",()=>[]),e.utilities.static("decoration-slice",()=>[o("-webkit-box-decoration-break","slice"),o("box-decoration-break","slice")]),e.utilities.suggest("decoration-clone",()=>[]),e.utilities.static("decoration-clone",()=>[o("-webkit-box-decoration-break","clone"),o("box-decoration-break","clone")]),e.utilities.suggest("flex-shrink",()=>[]),e.utilities.functional("flex-shrink",r=>{if(!r.modifier){if(!r.value)return[o("flex-shrink","1")];if(r.value.kind==="arbitrary")return[o("flex-shrink",r.value.value)];if(U(r.value.value))return[o("flex-shrink",r.value.value)]}}),e.utilities.suggest("flex-grow",()=>[]),e.utilities.functional("flex-grow",r=>{if(!r.modifier){if(!r.value)return[o("flex-grow","1")];if(r.value.kind==="arbitrary")return[o("flex-grow",r.value.value)];if(U(r.value.value))return[o("flex-grow",r.value.value)]}}),e.utilities.suggest("order-none",()=>[]),e.utilities.static("order-none",()=>[o("order","0")]),e.utilities.suggest("break-words",()=>[]),e.utilities.static("break-words",()=>[o("overflow-wrap","break-word")]);for(let[r,t]of[["start","inset-inline-start"],["end","inset-inline-end"]]){let n=function({negative:s}){return l=>{if(l.value===null)return;if(l.value.kind==="arbitrary"){if(l.modifier)return;let u=l.value.value;return[o(t,s?`calc(${u} * -1)`:u)]}let p=e.theme.resolve(l.value.fraction??l.value.value,["--inset","--spacing"]);if(p===null&&l.value.fraction){let[u,c]=F(l.value.fraction,"/");if(!U(u)||!U(c))return;p=`calc(${l.value.fraction} * 100%)`}if(p===null&&s){let u=e.theme.resolve(null,["--spacing"]);if(u&&te(l.value.value)&&(p=`calc(${u} * -${l.value.value})`,p!==null))return[o(t,p)]}if(p===null){let u=e.theme.resolve(null,["--spacing"]);u&&te(l.value.value)&&(p=`calc(${u} * ${l.value.value})`)}if(p!==null)return[o(t,s?`calc(${p} * -1)`:p)]}};var i=n;e.utilities.static(`${r}-auto`,()=>[o(t,"auto")]),e.utilities.static(`${r}-full`,()=>[o(t,"100%")]),e.utilities.static(`-${r}-full`,()=>[o(t,"-100%")]),e.utilities.static(`${r}-px`,()=>[o(t,"1px")]),e.utilities.static(`-${r}-px`,()=>[o(t,"-1px")]),e.utilities.functional(`-${r}`,n({negative:!0})),e.utilities.functional(r,n({negative:!1}))}}function hn(e,i){let r=e.theme.screens||{},t=i.variants.get("min")?.order??0,n=[];for(let[l,p]of Object.entries(r)){let f=function(h){i.variants.static(l,w=>{w.nodes=[q("@media",m,w.nodes)]},{order:h})};var s=f;let u=i.variants.get(l),c=i.theme.resolveValue(l,["--breakpoint"]);if(u&&c&&!i.theme.hasDefault(`--breakpoint-${l}`))continue;let d=!0;typeof p=="string"&&(d=!1);let m=La(p);d?n.push(f):f(t)}if(n.length!==0){for(let[,l]of i.variants.variants)l.order>t&&(l.order+=n.length);i.variants.compareFns=new Map(Array.from(i.variants.compareFns).map(([l,p])=>(l>t&&(l+=n.length),[l,p])));for(let[l,p]of n.entries())p(t+l+1)}}function La(e){return(Array.isArray(e)?e:[e]).map(r=>typeof r=="string"?{min:r}:r&&typeof r=="object"?r:null).map(r=>{if(r===null)return null;if("raw"in r)return r.raw;let t="";return r.max!==void 0&&(t+=`${r.max} >= `),t+="width",r.min!==void 0&&(t+=` >= ${r.min}`),`(${t})`}).filter(Boolean).join(", ")}function vn(e,i){let r=e.theme.aria||{},t=e.theme.supports||{},n=e.theme.data||{};if(Object.keys(r).length>0){let s=i.variants.get("aria"),l=s?.applyFn,p=s?.compounds;i.variants.functional("aria",(u,c)=>{let d=c.value;return d&&d.kind==="named"&&d.value in r?l?.(u,{...c,value:{kind:"arbitrary",value:r[d.value]}}):l?.(u,c)},{compounds:p})}if(Object.keys(t).length>0){let s=i.variants.get("supports"),l=s?.applyFn,p=s?.compounds;i.variants.functional("supports",(u,c)=>{let d=c.value;return d&&d.kind==="named"&&d.value in t?l?.(u,{...c,value:{kind:"arbitrary",value:t[d.value]}}):l?.(u,c)},{compounds:p})}if(Object.keys(n).length>0){let s=i.variants.get("data"),l=s?.applyFn,p=s?.compounds;i.variants.functional("data",(u,c)=>{let d=c.value;return d&&d.kind==="named"&&d.value in n?l?.(u,{...c,value:{kind:"arbitrary",value:n[d.value]}}):l?.(u,c)},{compounds:p})}}var za=/^[a-z]+$/;async function kn({designSystem:e,base:i,ast:r,loadModule:t,sources:n}){let s=0,l=[],p=[];I(r,(m,f)=>{if(m.kind!=="at-rule")return;let h=et(f);if(m.name==="@plugin"){if(h.parent!==null)throw new Error("`@plugin` cannot be nested.");let w=m.params.slice(1,-1);if(w.length===0)throw new Error("`@plugin` must have a path.");let b={};for(let k of m.nodes??[]){if(k.kind!=="declaration")throw new Error(`Unexpected \`@plugin\` option: + +${ue([k])} + +\`@plugin\` options must be a flat list of declarations.`);if(k.value===void 0)continue;let A=k.value,C=F(A,",").map(y=>{if(y=y.trim(),y==="null")return null;if(y==="true")return!0;if(y==="false")return!1;if(Number.isNaN(Number(y))){if(y[0]==='"'&&y[y.length-1]==='"'||y[0]==="'"&&y[y.length-1]==="'")return y.slice(1,-1);if(y[0]==="{"&&y[y.length-1]==="}")throw new Error(`Unexpected \`@plugin\` option: Value of declaration \`${ue([k]).trim()}\` is not supported. + +Using an object as a plugin option is currently only supported in JavaScript configuration files.`)}else return Number(y);return y});b[k.property]=C.length===1?C[0]:C}return l.push([{id:w,base:h.context.base,reference:!!h.context.reference,src:m.src},Object.keys(b).length>0?b:null]),s|=4,V.Replace([])}if(m.name==="@config"){if(m.nodes.length>0)throw new Error("`@config` cannot have a body.");if(h.parent!==null)throw new Error("`@config` cannot be nested.");return p.push({id:m.params.slice(1,-1),base:h.context.base,reference:!!h.context.reference,src:m.src}),s|=4,V.Replace([])}}),gn(e);let u=e.resolveThemeValue;if(e.resolveThemeValue=function(f,h){return f.startsWith("--")?u(f,h):(s|=wn({designSystem:e,base:i,ast:r,sources:n,configs:[],pluginDetails:[]}),e.resolveThemeValue(f,h))},!l.length&&!p.length)return 0;let[c,d]=await Ma(t,p,l);return s|=wn({designSystem:e,base:i,ast:r,sources:n,configs:c,pluginDetails:d}),s}function Ma(e,i,r){return Promise.all([Promise.all(i.map(async({id:t,base:n,reference:s,src:l})=>{let p=await e(t,n,"config");return{path:t,base:p.base,config:p.module,reference:s,src:l}})),Promise.all(r.map(async([{id:t,base:n,reference:s,src:l},p])=>{let u=await e(t,n,"plugin");return{path:t,base:u.base,plugin:u.module,options:p,reference:s,src:l}}))])}function wn({designSystem:e,base:i,ast:r,sources:t,configs:n,pluginDetails:s}){let l=0,u=[...s.map(b=>{if(!b.options)return{config:{plugins:[b.plugin]},base:b.base,reference:b.reference,src:b.src};if("__isOptionsFunction"in b.plugin)return{config:{plugins:[b.plugin(b.options)]},base:b.base,reference:b.reference,src:b.src};throw new Error(`The plugin "${b.path}" does not accept options`)}),...n],{resolvedConfig:c}=xr(e,[{config:pn(e.theme),base:i,reference:!0,src:void 0},...u,{config:{plugins:[mn]},base:i,reference:!0,src:void 0}]),{resolvedConfig:d,replacedThemeKeys:m}=xr(e,u),f={designSystem:e,ast:r,resolvedConfig:c,featuresRef:{set current(b){l|=b}}},h=br({...f,referenceMode:!1,src:void 0}),w=e.resolveThemeValue;e.resolveThemeValue=function(k,A){if(k[0]==="-"&&k[1]==="-")return w(k,A);let C=h.theme(k,void 0);if(typeof C=="object"&&C!==null&&!Array.isArray(C)&&"DEFAULT"in C&&(C=C.DEFAULT),Array.isArray(C)&&C.length===2)return C[0];if(Array.isArray(C))return C.join(", ");if(typeof C=="string")return C};for(let{handler:b,reference:k,src:A}of c.plugins){let C=br({...f,referenceMode:k??!1,src:A});b(C)}if(Ci(e,d,m),cn(e,d),vn(d,e),hn(d,e),dn(d,e),!e.theme.prefix&&c.prefix){if(c.prefix.endsWith("-")&&(c.prefix=c.prefix.slice(0,-1),console.warn(`The prefix "${c.prefix}" is invalid. Prefixes must be lowercase ASCII letters (a-z) only and is written as a variant before all utilities. We have fixed up the prefix for you. Remove the trailing \`-\` to silence this warning.`)),!za.test(c.prefix))throw new Error(`The prefix "${c.prefix}" is invalid. Prefixes must be lowercase ASCII letters (a-z) only.`);e.theme.prefix=c.prefix}if(!e.important&&c.important===!0&&(e.important=!0),typeof c.important=="string"){let b=c.important;I(r,(k,A)=>{if(k.kind!=="at-rule"||k.name!=="@tailwind"||k.params!=="utilities")return;let C=et(A);return C.parent?.kind==="rule"&&C.parent.selector===b?V.Stop:V.ReplaceStop(J(b,[k]))})}for(let b of c.blocklist)e.invalidCandidates.add(b);for(let b of c.content.files){if("raw"in b)throw new Error(`Error in the config file/plugin/preset. The \`content\` key contains a \`raw\` entry: + +${JSON.stringify(b,null,2)} + +This feature is not currently supported.`);let k=!1;b.pattern[0]=="!"&&(k=!0,b.pattern=b.pattern.slice(1)),t.push({...b,negated:k})}return l}function bn({ast:e}){let i=new L(n=>dt(n.code)),r=new L(n=>({url:n.file,content:n.code,ignore:!1})),t={file:null,sources:[],mappings:[]};I(e,n=>{if(!n.src||!n.dst)return;let s=r.get(n.src[0]);if(!s.content)return;let l=i.get(n.src[0]),p=i.get(n.dst[0]),u=s.content.slice(n.src[1],n.src[2]),c=0;for(let f of u.split(` +`)){if(f.trim()!==""){let h=l.find(n.src[1]+c),w=p.find(n.dst[1]);t.mappings.push({name:null,originalPosition:{source:s,...h},generatedPosition:w})}c+=f.length,c+=1}let d=l.find(n.src[2]),m=p.find(n.dst[2]);t.mappings.push({name:null,originalPosition:{source:s,...d},generatedPosition:m})});for(let n of i.keys())t.sources.push(r.get(n));return t.mappings.sort((n,s)=>n.generatedPosition.line-s.generatedPosition.line||n.generatedPosition.column-s.generatedPosition.column||(n.originalPosition?.line??0)-(s.originalPosition?.line??0)||(n.originalPosition?.column??0)-(s.originalPosition?.column??0)),t}var yn=/^(-?\d+)\.\.(-?\d+)(?:\.\.(-?\d+))?$/;function Kt(e){let i=e.indexOf("{");if(i===-1)return[e];let r=[],t=e.slice(0,i),n=e.slice(i),s=0,l=n.lastIndexOf("}");for(let m=0;mKt(m));let d=Kt(u);for(let m of d)for(let f of c)r.push(t+f+m);return r}function ja(e){return yn.test(e)}function Fa(e){let i=e.match(yn);if(!i)return[e];let[,r,t,n]=i,s=n?parseInt(n,10):void 0,l=[];if(/^-?\d+$/.test(r)&&/^-?\d+$/.test(t)){let p=parseInt(r,10),u=parseInt(t,10);if(s===void 0&&(s=p<=u?1:-1),s===0)throw new Error("Step cannot be zero in sequence expansion.");let c=p0&&(s=-s);for(let d=p;c?d<=u:d>=u;d+=s)l.push(d.toString())}return l}function xn(e,i){let r=new Set,t=new Set,n=[];function s(l,p=[]){if(e.has(l)&&!r.has(l)){t.has(l)&&i.onCircularDependency?.(p,l),t.add(l);for(let u of e.get(l)??[])p.push(l),s(u,p),p.pop();r.add(l),t.delete(l),n.push(l)}}for(let l of e.keys())s(l);return n}var Wa=/^[a-z]+$/,tr=(n=>(n[n.None=0]="None",n[n.AtProperty=1]="AtProperty",n[n.ColorMix=2]="ColorMix",n[n.All=3]="All",n))(tr||{});function Ba(){throw new Error("No `loadModule` function provided to `compile`")}function Ya(){throw new Error("No `loadStylesheet` function provided to `compile`")}function Ga(e){let i=0,r=null;for(let t of F(e," "))t==="reference"?i|=2:t==="inline"?i|=1:t==="default"?i|=4:t==="static"?i|=8:t.startsWith("prefix(")&&t.endsWith(")")&&(r=t.slice(7,-1));return[i,r]}var je=(u=>(u[u.None=0]="None",u[u.AtApply=1]="AtApply",u[u.AtImport=2]="AtImport",u[u.JsPluginCompat=4]="JsPluginCompat",u[u.ThemeFunction=8]="ThemeFunction",u[u.Utilities=16]="Utilities",u[u.Variants=32]="Variants",u[u.AtTheme=64]="AtTheme",u))(je||{});async function An(e,{base:i="",from:r,loadModule:t=Ba,loadStylesheet:n=Ya}={}){let s=0;e=[ee({base:i},e)],s|=await kr(e,i,n,0,r!==void 0);let l=null,p=new Ar,u=new Map,c=new Map,d=[],m=null,f=null,h=[],w=[],b=[],k=[],A=null;I(e,(y,E)=>{if(y.kind!=="at-rule")return;let O=et(E);if(y.name==="@tailwind"&&(y.params==="utilities"||y.params.startsWith("utilities"))){if(f!==null)return V.Replace([]);if(O.context.reference)return V.Replace([]);let P=F(y.params," ");for(let K of P)if(K.startsWith("source(")){let R=K.slice(7,-1);if(R==="none"){A=R;continue}if(R[0]==='"'&&R[R.length-1]!=='"'||R[0]==="'"&&R[R.length-1]!=="'"||R[0]!=="'"&&R[0]!=='"')throw new Error("`source(\u2026)` paths must be quoted.");A={base:O.context.sourceBase??O.context.base,pattern:R.slice(1,-1)}}f=y,s|=16}if(y.name==="@utility"){if(O.parent!==null)throw new Error("`@utility` cannot be nested.");if(y.nodes.length===0)throw new Error(`\`@utility ${y.params}\` is empty. Utilities should include at least one property.`);let P=wi(y);if(P===null){if(!y.params.endsWith("-*")){if(y.params.endsWith("*"))throw new Error(`\`@utility ${y.params}\` defines an invalid utility name. A functional utility must end in \`-*\`.`);if(y.params.includes("*"))throw new Error(`\`@utility ${y.params}\` defines an invalid utility name. The dynamic portion marked by \`-*\` must appear once at the end.`)}throw new Error(`\`@utility ${y.params}\` defines an invalid utility name. Utilities should be alphanumeric and start with a lowercase letter.`)}d.push(P)}if(y.name==="@source"){if(y.nodes.length>0)throw new Error("`@source` cannot have a body.");if(O.parent!==null)throw new Error("`@source` cannot be nested.");let P=!1,K=!1,R=y.params;if(R[0]==="n"&&R.startsWith("not ")&&(P=!0,R=R.slice(4)),R[0]==="i"&&R.startsWith("inline(")&&(K=!0,R=R.slice(7,-1).trim()),R[0]==='"'&&R[R.length-1]!=='"'||R[0]==="'"&&R[R.length-1]!=="'"||R[0]!=="'"&&R[0]!=='"')throw new Error("`@source` paths must be quoted.");let W=R.slice(1,-1);if(K){let D=P?k:b,z=F(W," ");for(let j of z)for(let Z of Kt(j))D.push(Z)}else w.push({base:O.context.base,pattern:W,negated:P});return V.ReplaceSkip([])}if(y.name==="@variant"&&(O.parent===null?y.nodes.length===0?y.name="@custom-variant":(I(y.nodes,P=>{if(P.kind==="at-rule"&&P.name==="@slot")return y.name="@custom-variant",V.Stop}),y.name==="@variant"&&h.push(y)):h.push(y)),y.name==="@custom-variant"){if(O.parent!==null)throw new Error("`@custom-variant` cannot be nested.");let[P,K]=F(y.params," ");if(!It.test(P))throw new Error(`\`@custom-variant ${P}\` defines an invalid variant name. Variants should only contain alphanumeric, dashes, or underscore characters and start with a lowercase letter or number.`);if(y.nodes.length>0&&K)throw new Error(`\`@custom-variant ${P}\` cannot have both a selector and a body.`);if(y.nodes.length===0){if(!K)throw new Error(`\`@custom-variant ${P}\` has no selector or body.`);let R=F(K.slice(1,-1),",");if(R.length===0||R.some(j=>j.trim()===""))throw new Error(`\`@custom-variant ${P} (${R.join(",")})\` selector is invalid.`);let W=[],D=[];for(let j of R)j=j.trim(),j[0]==="@"?W.push(j):D.push(j);let z=W.some(j=>j.startsWith("@scope"));u.set(P,j=>{j.variants.static(P,Z=>{let a=z?[ee({source:"user"},Z.nodes)]:Z.nodes,g=[];D.length>0&&g.push(J(D.join(", "),a));for(let v of W)g.push(Q(v,a));Z.nodes=z?[ee({source:"variant"},g)]:g},{compounds:Pe([...D,...W])})}),c.set(P,new Set)}else{let R=new Set;I(y.nodes,W=>{W.kind==="at-rule"&&W.name==="@variant"&&R.add(W.params)}),u.set(P,W=>{W.variants.fromAst(P,y.nodes,W)}),c.set(P,R)}return V.ReplaceSkip([])}if(y.name==="@media"){let P=F(y.params," "),K=[];for(let R of P)if(R.startsWith("source(")){let W=R.slice(7,-1);I(y.nodes,D=>{if(D.kind==="at-rule"&&D.name==="@tailwind"&&D.params==="utilities")return D.params+=` source(${W})`,V.ReplaceStop([ee({sourceBase:O.context.base},[D])])})}else if(R.startsWith("theme(")){let W=R.slice(6,-1),D=W.includes("reference");I(y.nodes,z=>{if(z.kind!=="context"){if(z.kind!=="at-rule"){if(D)throw new Error('Files imported with `@import "\u2026" theme(reference)` must only contain `@theme` blocks.\nUse `@reference "\u2026";` instead.');return V.Continue}if(z.name==="@theme")return z.params+=" "+W,V.Skip}})}else if(R.startsWith("prefix(")){let W=R.slice(7,-1);I(y.nodes,D=>{if(D.kind==="at-rule"&&D.name==="@theme")return D.params+=` prefix(${W})`,V.Skip})}else R==="important"?l=!0:R==="reference"?y.nodes=[ee({reference:!0},y.nodes)]:K.push(R);if(K.length>0)y.params=K.join(" ");else if(P.length>0)return V.Replace(y.nodes);return V.Continue}if(y.name==="@theme"){let[P,K]=Ga(y.params);if(s|=64,O.context.reference&&(P|=2),K){if(!Wa.test(K))throw new Error(`The prefix "${K}" is invalid. Prefixes must be lowercase ASCII letters (a-z) only.`);p.prefix=K}return I(y.nodes,R=>{if(R.kind==="at-rule"&&R.name==="@keyframes")return p.addKeyframes(R),V.Skip;if(R.kind==="comment")return;if(R.kind==="declaration"&&R.property.startsWith("--")){p.add(_e(R.property),R.value??"",P,R.src);return}let W=ue([q(y.name,y.params,[R])]).split(` +`).map((D,z,j)=>`${z===0||z>=j.length-2?" ":">"} ${D}`).join(` +`);throw new Error(`\`@theme\` blocks must only contain custom properties or \`@keyframes\`. + +${W}`)}),m?V.ReplaceSkip([]):(m=J(":root, :host",[]),m.src=y.src,V.ReplaceSkip(m))}});let C=en(p,f?.src);if(l&&(C.important=l),k.length>0)for(let y of k)C.invalidCandidates.add(y);s|=await kn({designSystem:C,base:i,ast:e,loadModule:t,sources:w});for(let y of u.keys())C.variants.static(y,()=>{});for(let y of xn(c,{onCircularDependency(E,O){let P=ue(E.map((K,R)=>q("@custom-variant",K,[q("@variant",E[R+1]??O,[])]))).replaceAll(";"," { \u2026 }").replace(`@custom-variant ${O} {`,`@custom-variant ${O} { /* \u2190 */`);throw new Error(`Circular dependency detected in custom variants: + +${P}`)}}))u.get(y)?.(C);for(let y of d)y(C);if(m){let y=[];for(let[O,P]of C.theme.entries()){if(P.options&2)continue;let K=o(Oe(O),P.value);K.src=P.src,y.push(K)}let E=C.theme.getKeyframes();for(let O of E)e.push(ee({theme:!0},[H([O])]));m.nodes=[ee({theme:!0},y)]}if(s|=st(e,C),s|=Me(e,C),s|=Ce(e,C),f){let y=f;y.kind="context",y.context={}}return I(e,y=>{if(y.kind==="at-rule")return y.name==="@utility"?V.Replace([]):V.Skip}),{designSystem:C,ast:e,sources:w,root:A,utilitiesNode:f,features:s,inlineCandidates:b}}async function qa(e,i={}){let{designSystem:r,ast:t,sources:n,root:s,utilitiesNode:l,features:p,inlineCandidates:u}=await An(e,i);t.unshift(kt(`! tailwindcss v${$r} | MIT License | https://tailwindcss.com `));function c(k){r.invalidCandidates.add(k)}let d=new Set,m=null,f=0,h=!1;for(let k of u)r.invalidCandidates.has(k)||(d.add(k),h=!0);let{from:w,polyfills:b}=i;return{sources:n,root:s,features:p,build(k){if(p===0)return e;if(!l)return m??=Te(t,r,b),m;let A=h,C=!1;h=!1;let y=d.size;for(let O of k)if(!r.invalidCandidates.has(O))if(O[0]==="-"&&O[1]==="-"){let P=r.theme.markUsedVariable(O);A||=P,C||=P}else d.add(O),A||=d.size!==y;if(!A)return m??=Te(t,r,b),m;let E=Se(d,r,{onInvalidCandidate:c}).astNodes;return w&&I(E,O=>{O.src??=l.src}),!C&&f===E.length?(m??=Te(t,r,b),m):(f=E.length,l.nodes=E,m=Te(t,r,b),m)}}}async function nc(e,i={}){let r=$e(e,{from:i.from}),t=await qa(r,i),n=r,s=e,l=i.from;return{...t,build(p){let u=t.build(p);return u===n||(s=ue(u,!!l),n=u),s},buildSourceMap(){return bn({ast:n})}}}async function lc(e,i={}){return(await An($e(e,{from:i.from}),i)).designSystem}function Ha(){throw new Error("It looks like you're trying to use `tailwindcss` directly as a PostCSS plugin. The PostCSS plugin has moved to a separate package, so to continue using Tailwind CSS with PostCSS you'll need to install `@tailwindcss/postcss` and update your PostCSS configuration.")}export{je as Features,tr as Polyfills,lc as __unstable__loadDesignSystem,nc as compile,qa as compileAst,Ha as default}; diff --git a/dg-ui/node_modules/tailwindcss/dist/plugin.d.mts b/dg-ui/node_modules/tailwindcss/dist/plugin.d.mts new file mode 100644 index 0000000..fe3e3a5 --- /dev/null +++ b/dg-ui/node_modules/tailwindcss/dist/plugin.d.mts @@ -0,0 +1,11 @@ +export { P as PluginUtils } from './resolve-config-QUZ9b-Gn.mjs'; +import { b as PluginFn, C as Config, c as PluginWithConfig, d as PluginWithOptions } from './types-DWdTiksJ.mjs'; +export { a as PluginAPI, P as PluginsConfig, T as ThemeConfig } from './types-DWdTiksJ.mjs'; +import './colors.mjs'; + +declare function createPlugin(handler: PluginFn, config?: Partial): PluginWithConfig; +declare namespace createPlugin { + var withOptions: (pluginFunction: (options?: T) => PluginFn, configFunction?: (options?: T) => Partial) => PluginWithOptions; +} + +export { Config, PluginFn as PluginCreator, PluginWithConfig, createPlugin as default }; diff --git a/dg-ui/node_modules/tailwindcss/dist/plugin.d.ts b/dg-ui/node_modules/tailwindcss/dist/plugin.d.ts new file mode 100644 index 0000000..8715495 --- /dev/null +++ b/dg-ui/node_modules/tailwindcss/dist/plugin.d.ts @@ -0,0 +1,134 @@ +import { N as NamedUtilityValue, P as PluginUtils } from './resolve-config-B4yBzhca.js'; +import './colors-C__qRT83.js'; + +/** + * The source code for one or more nodes in the AST + * + * This generally corresponds to a stylesheet + */ +interface Source { + /** + * The path to the file that contains the referenced source code + * + * If this references the *output* source code, this is `null`. + */ + file: string | null; + /** + * The referenced source code + */ + code: string; +} +/** + * The file and offsets within it that this node covers + * + * This can represent either: + * - A location in the original CSS which caused this node to be created + * - A location in the output CSS where this node resides + */ +type SourceLocation = [source: Source, start: number, end: number]; + +type Config = UserConfig; +type PluginFn = (api: PluginAPI) => void; +type PluginWithConfig = { + handler: PluginFn; + config?: UserConfig; + /** @internal */ + reference?: boolean; + src?: SourceLocation | undefined; +}; +type PluginWithOptions = { + (options?: T): PluginWithConfig; + __isOptionsFunction: true; +}; +type Plugin = PluginFn | PluginWithConfig | PluginWithOptions; +type PluginAPI = { + addBase(base: CssInJs): void; + addVariant(name: string, variant: string | string[] | CssInJs): void; + matchVariant(name: string, cb: (value: T | string, extra: { + modifier: string | null; + }) => string | string[], options?: { + values?: Record; + sort?(a: { + value: T | string; + modifier: string | null; + }, b: { + value: T | string; + modifier: string | null; + }): number; + }): void; + addUtilities(utilities: Record | Record[], options?: {}): void; + matchUtilities(utilities: Record CssInJs | CssInJs[]>, options?: Partial<{ + type: string | string[]; + supportsNegativeValues: boolean; + values: Record & { + __BARE_VALUE__?: (value: NamedUtilityValue) => string | undefined; + }; + modifiers: 'any' | Record; + }>): void; + addComponents(utilities: Record | Record[], options?: {}): void; + matchComponents(utilities: Record CssInJs>, options?: Partial<{ + type: string | string[]; + supportsNegativeValues: boolean; + values: Record & { + __BARE_VALUE__?: (value: NamedUtilityValue) => string | undefined; + }; + modifiers: 'any' | Record; + }>): void; + theme(path: string, defaultValue?: any): any; + config(path?: string, defaultValue?: any): any; + prefix(className: string): string; +}; +type CssInJs = { + [key: string]: string | string[] | CssInJs | CssInJs[]; +}; + +type ResolvableTo = T | ((utils: PluginUtils) => T); +type ThemeValue = ResolvableTo> | null | undefined; +type ThemeConfig = Record & { + extend?: Record; +}; +type ContentFile = string | { + raw: string; + extension?: string; +}; +type DarkModeStrategy = false | 'media' | 'class' | ['class', string] | 'selector' | ['selector', string] | ['variant', string | string[]]; +interface UserConfig { + presets?: UserConfig[]; + theme?: ThemeConfig; + plugins?: Plugin[]; +} +interface UserConfig { + content?: ContentFile[] | { + relative?: boolean; + files: ContentFile[]; + }; +} +interface UserConfig { + darkMode?: DarkModeStrategy; +} +interface UserConfig { + prefix?: string; +} +interface UserConfig { + blocklist?: string[]; +} +interface UserConfig { + important?: boolean | string; +} +interface UserConfig { + future?: 'all' | Record; +} +interface UserConfig { + experimental?: 'all' | Record; +} + +declare function createPlugin(handler: PluginFn, config?: Partial): PluginWithConfig; +declare namespace createPlugin { + var withOptions: (pluginFunction: (options?: T) => PluginFn, configFunction?: (options?: T) => Partial) => PluginWithOptions; +} + +export { createPlugin as default }; diff --git a/dg-ui/node_modules/tailwindcss/dist/plugin.js b/dg-ui/node_modules/tailwindcss/dist/plugin.js new file mode 100644 index 0000000..eca100c --- /dev/null +++ b/dg-ui/node_modules/tailwindcss/dist/plugin.js @@ -0,0 +1 @@ +"use strict";function g(i,n){return{handler:i,config:n}}g.withOptions=function(i,n=()=>({})){function t(o){return{handler:i(o),config:n(o)}}return t.__isOptionsFunction=!0,t};var u=g;module.exports=u; diff --git a/dg-ui/node_modules/tailwindcss/dist/plugin.mjs b/dg-ui/node_modules/tailwindcss/dist/plugin.mjs new file mode 100644 index 0000000..430fa25 --- /dev/null +++ b/dg-ui/node_modules/tailwindcss/dist/plugin.mjs @@ -0,0 +1 @@ +function g(i,n){return{handler:i,config:n}}g.withOptions=function(i,n=()=>({})){function t(o){return{handler:i(o),config:n(o)}}return t.__isOptionsFunction=!0,t};var u=g;export{u as default}; diff --git a/dg-ui/node_modules/tailwindcss/dist/resolve-config-B4yBzhca.d.ts b/dg-ui/node_modules/tailwindcss/dist/resolve-config-B4yBzhca.d.ts new file mode 100644 index 0000000..de182ef --- /dev/null +++ b/dg-ui/node_modules/tailwindcss/dist/resolve-config-B4yBzhca.d.ts @@ -0,0 +1,29 @@ +import { _ as _default } from './colors-C__qRT83.js'; + +type NamedUtilityValue = { + kind: 'named'; + /** + * ``` + * bg-red-500 + * ^^^^^^^ + * + * w-1/2 + * ^ + * ``` + */ + value: string; + /** + * ``` + * w-1/2 + * ^^^ + * ``` + */ + fraction: string | null; +}; + +type PluginUtils = { + theme: (keypath: string, defaultValue?: any) => any; + colors: typeof _default; +}; + +export type { NamedUtilityValue as N, PluginUtils as P }; diff --git a/dg-ui/node_modules/tailwindcss/dist/resolve-config-QUZ9b-Gn.d.mts b/dg-ui/node_modules/tailwindcss/dist/resolve-config-QUZ9b-Gn.d.mts new file mode 100644 index 0000000..e1cde16 --- /dev/null +++ b/dg-ui/node_modules/tailwindcss/dist/resolve-config-QUZ9b-Gn.d.mts @@ -0,0 +1,190 @@ +import _default from './colors.mjs'; + +type ArbitraryUtilityValue = { + kind: 'arbitrary'; + /** + * ``` + * bg-[color:var(--my-color)] + * ^^^^^ + * + * bg-(color:--my-color) + * ^^^^^ + * ``` + */ + dataType: string | null; + /** + * ``` + * bg-[#0088cc] + * ^^^^^^^ + * + * bg-[var(--my_variable)] + * ^^^^^^^^^^^^^^^^^^ + * + * bg-(--my_variable) + * ^^^^^^^^^^^^^^ + * ``` + */ + value: string; +}; +type NamedUtilityValue = { + kind: 'named'; + /** + * ``` + * bg-red-500 + * ^^^^^^^ + * + * w-1/2 + * ^ + * ``` + */ + value: string; + /** + * ``` + * w-1/2 + * ^^^ + * ``` + */ + fraction: string | null; +}; +type ArbitraryModifier = { + kind: 'arbitrary'; + /** + * ``` + * bg-red-500/[50%] + * ^^^ + * ``` + */ + value: string; +}; +type NamedModifier = { + kind: 'named'; + /** + * ``` + * bg-red-500/50 + * ^^ + * ``` + */ + value: string; +}; +type ArbitraryVariantValue = { + kind: 'arbitrary'; + value: string; +}; +type NamedVariantValue = { + kind: 'named'; + value: string; +}; +type Variant = +/** + * Arbitrary variants are variants that take a selector and generate a variant + * on the fly. + * + * E.g.: `[&_p]` + */ +{ + kind: 'arbitrary'; + selector: string; + relative: boolean; +} +/** + * Static variants are variants that don't take any arguments. + * + * E.g.: `hover` + */ + | { + kind: 'static'; + root: string; +} +/** + * Functional variants are variants that can take an argument. The argument is + * either a named variant value or an arbitrary variant value. + * + * E.g.: + * + * - `aria-disabled` + * - `aria-[disabled]` + * - `@container-size` -> @container, with named value `size` + * - `@container-[inline-size]` -> @container, with arbitrary variant value `inline-size` + * - `@container` -> @container, with no value + */ + | { + kind: 'functional'; + root: string; + value: ArbitraryVariantValue | NamedVariantValue | null; + modifier: ArbitraryModifier | NamedModifier | null; +} +/** + * Compound variants are variants that take another variant as an argument. + * + * E.g.: + * + * - `has-[&_p]` + * - `group-*` + * - `peer-*` + */ + | { + kind: 'compound'; + root: string; + modifier: ArbitraryModifier | NamedModifier | null; + variant: Variant; +}; +type Candidate = +/** + * Arbitrary candidates are candidates that register utilities on the fly with + * a property and a value. + * + * E.g.: + * + * - `[color:red]` + * - `[color:red]/50` + * - `[color:red]/50!` + */ +{ + kind: 'arbitrary'; + property: string; + value: string; + modifier: ArbitraryModifier | NamedModifier | null; + variants: Variant[]; + important: boolean; + raw: string; +} +/** + * Static candidates are candidates that don't take any arguments. + * + * E.g.: + * + * - `underline` + * - `box-border` + */ + | { + kind: 'static'; + root: string; + variants: Variant[]; + important: boolean; + raw: string; +} +/** + * Functional candidates are candidates that can take an argument. + * + * E.g.: + * + * - `bg-red-500` + * - `bg-[#0088cc]` + * - `w-1/2` + */ + | { + kind: 'functional'; + root: string; + value: ArbitraryUtilityValue | NamedUtilityValue | null; + modifier: ArbitraryModifier | NamedModifier | null; + variants: Variant[]; + important: boolean; + raw: string; +}; + +type PluginUtils = { + theme: (keypath: string, defaultValue?: any) => any; + colors: typeof _default; +}; + +export type { Candidate as C, NamedUtilityValue as N, PluginUtils as P, Variant as V }; diff --git a/dg-ui/node_modules/tailwindcss/dist/types-DWdTiksJ.d.mts b/dg-ui/node_modules/tailwindcss/dist/types-DWdTiksJ.d.mts new file mode 100644 index 0000000..718219a --- /dev/null +++ b/dg-ui/node_modules/tailwindcss/dist/types-DWdTiksJ.d.mts @@ -0,0 +1,128 @@ +import { N as NamedUtilityValue, P as PluginUtils } from './resolve-config-QUZ9b-Gn.mjs'; + +/** + * The source code for one or more nodes in the AST + * + * This generally corresponds to a stylesheet + */ +interface Source { + /** + * The path to the file that contains the referenced source code + * + * If this references the *output* source code, this is `null`. + */ + file: string | null; + /** + * The referenced source code + */ + code: string; +} +/** + * The file and offsets within it that this node covers + * + * This can represent either: + * - A location in the original CSS which caused this node to be created + * - A location in the output CSS where this node resides + */ +type SourceLocation = [source: Source, start: number, end: number]; + +type Config = UserConfig; +type PluginFn = (api: PluginAPI) => void; +type PluginWithConfig = { + handler: PluginFn; + config?: UserConfig; + /** @internal */ + reference?: boolean; + src?: SourceLocation | undefined; +}; +type PluginWithOptions = { + (options?: T): PluginWithConfig; + __isOptionsFunction: true; +}; +type Plugin = PluginFn | PluginWithConfig | PluginWithOptions; +type PluginAPI = { + addBase(base: CssInJs): void; + addVariant(name: string, variant: string | string[] | CssInJs): void; + matchVariant(name: string, cb: (value: T | string, extra: { + modifier: string | null; + }) => string | string[], options?: { + values?: Record; + sort?(a: { + value: T | string; + modifier: string | null; + }, b: { + value: T | string; + modifier: string | null; + }): number; + }): void; + addUtilities(utilities: Record | Record[], options?: {}): void; + matchUtilities(utilities: Record CssInJs | CssInJs[]>, options?: Partial<{ + type: string | string[]; + supportsNegativeValues: boolean; + values: Record & { + __BARE_VALUE__?: (value: NamedUtilityValue) => string | undefined; + }; + modifiers: 'any' | Record; + }>): void; + addComponents(utilities: Record | Record[], options?: {}): void; + matchComponents(utilities: Record CssInJs>, options?: Partial<{ + type: string | string[]; + supportsNegativeValues: boolean; + values: Record & { + __BARE_VALUE__?: (value: NamedUtilityValue) => string | undefined; + }; + modifiers: 'any' | Record; + }>): void; + theme(path: string, defaultValue?: any): any; + config(path?: string, defaultValue?: any): any; + prefix(className: string): string; +}; +type CssInJs = { + [key: string]: string | string[] | CssInJs | CssInJs[]; +}; + +type ResolvableTo = T | ((utils: PluginUtils) => T); +type ThemeValue = ResolvableTo> | null | undefined; +type ThemeConfig = Record & { + extend?: Record; +}; +type ContentFile = string | { + raw: string; + extension?: string; +}; +type DarkModeStrategy = false | 'media' | 'class' | ['class', string] | 'selector' | ['selector', string] | ['variant', string | string[]]; +interface UserConfig { + presets?: UserConfig[]; + theme?: ThemeConfig; + plugins?: Plugin[]; +} +interface UserConfig { + content?: ContentFile[] | { + relative?: boolean; + files: ContentFile[]; + }; +} +interface UserConfig { + darkMode?: DarkModeStrategy; +} +interface UserConfig { + prefix?: string; +} +interface UserConfig { + blocklist?: string[]; +} +interface UserConfig { + important?: boolean | string; +} +interface UserConfig { + future?: 'all' | Record; +} +interface UserConfig { + experimental?: 'all' | Record; +} + +export type { Config as C, Plugin as P, SourceLocation as S, ThemeConfig as T, UserConfig as U, PluginAPI as a, PluginFn as b, PluginWithConfig as c, PluginWithOptions as d }; diff --git a/dg-ui/node_modules/tailwindcss/index.css b/dg-ui/node_modules/tailwindcss/index.css new file mode 100644 index 0000000..74c779a --- /dev/null +++ b/dg-ui/node_modules/tailwindcss/index.css @@ -0,0 +1,950 @@ +@layer theme, base, components, utilities; + +@layer theme { + @theme default { + --font-sans: + -apple-system, BlinkMacSystemFont, "Segoe UI", Roboto, "Helvetica Neue", + "Noto Sans", Arial, sans-serif, "Apple Color Emoji", "Segoe UI Emoji", + "Segoe UI Symbol", "Noto Color Emoji"; + --font-serif: ui-serif, Georgia, Cambria, "Times New Roman", Times, serif; + --font-mono: + ui-monospace, SFMono-Regular, Menlo, Monaco, Consolas, "Liberation Mono", + "Courier New", monospace; + + --color-red-50: oklch(97.1% 0.013 17.38); + --color-red-100: oklch(93.6% 0.032 17.717); + --color-red-200: oklch(88.5% 0.062 18.334); + --color-red-300: oklch(80.8% 0.114 19.571); + --color-red-400: oklch(70.4% 0.191 22.216); + --color-red-500: oklch(63.7% 0.237 25.331); + --color-red-600: oklch(57.7% 0.245 27.325); + --color-red-700: oklch(50.5% 0.213 27.518); + --color-red-800: oklch(44.4% 0.177 26.899); + --color-red-900: oklch(39.6% 0.141 25.723); + --color-red-950: oklch(25.8% 0.092 26.042); + + --color-orange-50: oklch(98% 0.016 73.684); + --color-orange-100: oklch(95.4% 0.038 75.164); + --color-orange-200: oklch(90.1% 0.076 70.697); + --color-orange-300: oklch(83.7% 0.128 66.29); + --color-orange-400: oklch(75% 0.183 55.934); + --color-orange-500: oklch(70.5% 0.213 47.604); + --color-orange-600: oklch(64.6% 0.222 41.116); + --color-orange-700: oklch(55.3% 0.195 38.402); + --color-orange-800: oklch(47% 0.157 37.304); + --color-orange-900: oklch(40.8% 0.123 38.172); + --color-orange-950: oklch(26.6% 0.079 36.259); + + --color-amber-50: oklch(98.7% 0.022 95.277); + --color-amber-100: oklch(96.2% 0.059 95.617); + --color-amber-200: oklch(92.4% 0.12 95.746); + --color-amber-300: oklch(87.9% 0.169 91.605); + --color-amber-400: oklch(82.8% 0.189 84.429); + --color-amber-500: oklch(76.9% 0.188 70.08); + --color-amber-600: oklch(66.6% 0.179 58.318); + --color-amber-700: oklch(55.5% 0.163 48.998); + --color-amber-800: oklch(47.3% 0.137 46.201); + --color-amber-900: oklch(41.4% 0.112 45.904); + --color-amber-950: oklch(27.9% 0.077 45.635); + + --color-yellow-50: oklch(98.7% 0.026 102.212); + --color-yellow-100: oklch(97.3% 0.071 103.193); + --color-yellow-200: oklch(94.5% 0.129 101.54); + --color-yellow-300: oklch(90.5% 0.182 98.111); + --color-yellow-400: oklch(85.2% 0.199 91.936); + --color-yellow-500: oklch(79.5% 0.184 86.047); + --color-yellow-600: oklch(68.1% 0.162 75.834); + --color-yellow-700: oklch(55.4% 0.135 66.442); + --color-yellow-800: oklch(47.6% 0.114 61.907); + --color-yellow-900: oklch(42.1% 0.095 57.708); + --color-yellow-950: oklch(28.6% 0.066 53.813); + + --color-lime-50: oklch(98.6% 0.031 120.757); + --color-lime-100: oklch(96.7% 0.067 122.328); + --color-lime-200: oklch(93.8% 0.127 124.321); + --color-lime-300: oklch(89.7% 0.196 126.665); + --color-lime-400: oklch(84.1% 0.238 128.85); + --color-lime-500: oklch(76.8% 0.233 130.85); + --color-lime-600: oklch(64.8% 0.2 131.684); + --color-lime-700: oklch(53.2% 0.157 131.589); + --color-lime-800: oklch(45.3% 0.124 130.933); + --color-lime-900: oklch(40.5% 0.101 131.063); + --color-lime-950: oklch(27.4% 0.072 132.109); + + --color-green-50: oklch(98.2% 0.018 155.826); + --color-green-100: oklch(96.2% 0.044 156.743); + --color-green-200: oklch(92.5% 0.084 155.995); + --color-green-300: oklch(87.1% 0.15 154.449); + --color-green-400: oklch(79.2% 0.209 151.711); + --color-green-500: oklch(72.3% 0.219 149.579); + --color-green-600: oklch(62.7% 0.194 149.214); + --color-green-700: oklch(52.7% 0.154 150.069); + --color-green-800: oklch(44.8% 0.119 151.328); + --color-green-900: oklch(39.3% 0.095 152.535); + --color-green-950: oklch(26.6% 0.065 152.934); + + --color-emerald-50: oklch(97.9% 0.021 166.113); + --color-emerald-100: oklch(95% 0.052 163.051); + --color-emerald-200: oklch(90.5% 0.093 164.15); + --color-emerald-300: oklch(84.5% 0.143 164.978); + --color-emerald-400: oklch(76.5% 0.177 163.223); + --color-emerald-500: oklch(69.6% 0.17 162.48); + --color-emerald-600: oklch(59.6% 0.145 163.225); + --color-emerald-700: oklch(50.8% 0.118 165.612); + --color-emerald-800: oklch(43.2% 0.095 166.913); + --color-emerald-900: oklch(37.8% 0.077 168.94); + --color-emerald-950: oklch(26.2% 0.051 172.552); + + --color-teal-50: oklch(98.4% 0.014 180.72); + --color-teal-100: oklch(95.3% 0.051 180.801); + --color-teal-200: oklch(91% 0.096 180.426); + --color-teal-300: oklch(85.5% 0.138 181.071); + --color-teal-400: oklch(77.7% 0.152 181.912); + --color-teal-500: oklch(70.4% 0.14 182.503); + --color-teal-600: oklch(60% 0.118 184.704); + --color-teal-700: oklch(51.1% 0.096 186.391); + --color-teal-800: oklch(43.7% 0.078 188.216); + --color-teal-900: oklch(38.6% 0.063 188.416); + --color-teal-950: oklch(27.7% 0.046 192.524); + + --color-cyan-50: oklch(98.4% 0.019 200.873); + --color-cyan-100: oklch(95.6% 0.045 203.388); + --color-cyan-200: oklch(91.7% 0.08 205.041); + --color-cyan-300: oklch(86.5% 0.127 207.078); + --color-cyan-400: oklch(78.9% 0.154 211.53); + --color-cyan-500: oklch(71.5% 0.143 215.221); + --color-cyan-600: oklch(60.9% 0.126 221.723); + --color-cyan-700: oklch(52% 0.105 223.128); + --color-cyan-800: oklch(45% 0.085 224.283); + --color-cyan-900: oklch(39.8% 0.07 227.392); + --color-cyan-950: oklch(30.2% 0.056 229.695); + + --color-sky-50: oklch(97.7% 0.013 236.62); + --color-sky-100: oklch(95.1% 0.026 236.824); + --color-sky-200: oklch(90.1% 0.058 230.902); + --color-sky-300: oklch(82.8% 0.111 230.318); + --color-sky-400: oklch(74.6% 0.16 232.661); + --color-sky-500: oklch(68.5% 0.169 237.323); + --color-sky-600: oklch(58.8% 0.158 241.966); + --color-sky-700: oklch(50% 0.134 242.749); + --color-sky-800: oklch(44.3% 0.11 240.79); + --color-sky-900: oklch(39.1% 0.09 240.876); + --color-sky-950: oklch(29.3% 0.066 243.157); + + --color-blue-50: oklch(97% 0.014 254.604); + --color-blue-100: oklch(93.2% 0.032 255.585); + --color-blue-200: oklch(88.2% 0.059 254.128); + --color-blue-300: oklch(80.9% 0.105 251.813); + --color-blue-400: oklch(70.7% 0.165 254.624); + --color-blue-500: oklch(62.3% 0.214 259.815); + --color-blue-600: oklch(54.6% 0.245 262.881); + --color-blue-700: oklch(48.8% 0.243 264.376); + --color-blue-800: oklch(42.4% 0.199 265.638); + --color-blue-900: oklch(37.9% 0.146 265.522); + --color-blue-950: oklch(28.2% 0.091 267.935); + + --color-indigo-50: oklch(96.2% 0.018 272.314); + --color-indigo-100: oklch(93% 0.034 272.788); + --color-indigo-200: oklch(87% 0.065 274.039); + --color-indigo-300: oklch(78.5% 0.115 274.713); + --color-indigo-400: oklch(67.3% 0.182 276.935); + --color-indigo-500: oklch(58.5% 0.233 277.117); + --color-indigo-600: oklch(51.1% 0.262 276.966); + --color-indigo-700: oklch(45.7% 0.24 277.023); + --color-indigo-800: oklch(39.8% 0.195 277.366); + --color-indigo-900: oklch(35.9% 0.144 278.697); + --color-indigo-950: oklch(25.7% 0.09 281.288); + + --color-violet-50: oklch(96.9% 0.016 293.756); + --color-violet-100: oklch(94.3% 0.029 294.588); + --color-violet-200: oklch(89.4% 0.057 293.283); + --color-violet-300: oklch(81.1% 0.111 293.571); + --color-violet-400: oklch(70.2% 0.183 293.541); + --color-violet-500: oklch(60.6% 0.25 292.717); + --color-violet-600: oklch(54.1% 0.281 293.009); + --color-violet-700: oklch(49.1% 0.27 292.581); + --color-violet-800: oklch(43.2% 0.232 292.759); + --color-violet-900: oklch(38% 0.189 293.745); + --color-violet-950: oklch(28.3% 0.141 291.089); + + --color-purple-50: oklch(97.7% 0.014 308.299); + --color-purple-100: oklch(94.6% 0.033 307.174); + --color-purple-200: oklch(90.2% 0.063 306.703); + --color-purple-300: oklch(82.7% 0.119 306.383); + --color-purple-400: oklch(71.4% 0.203 305.504); + --color-purple-500: oklch(62.7% 0.265 303.9); + --color-purple-600: oklch(55.8% 0.288 302.321); + --color-purple-700: oklch(49.6% 0.265 301.924); + --color-purple-800: oklch(43.8% 0.218 303.724); + --color-purple-900: oklch(38.1% 0.176 304.987); + --color-purple-950: oklch(29.1% 0.149 302.717); + + --color-fuchsia-50: oklch(97.7% 0.017 320.058); + --color-fuchsia-100: oklch(95.2% 0.037 318.852); + --color-fuchsia-200: oklch(90.3% 0.076 319.62); + --color-fuchsia-300: oklch(83.3% 0.145 321.434); + --color-fuchsia-400: oklch(74% 0.238 322.16); + --color-fuchsia-500: oklch(66.7% 0.295 322.15); + --color-fuchsia-600: oklch(59.1% 0.293 322.896); + --color-fuchsia-700: oklch(51.8% 0.253 323.949); + --color-fuchsia-800: oklch(45.2% 0.211 324.591); + --color-fuchsia-900: oklch(40.1% 0.17 325.612); + --color-fuchsia-950: oklch(29.3% 0.136 325.661); + + --color-pink-50: oklch(97.1% 0.014 343.198); + --color-pink-100: oklch(94.8% 0.028 342.258); + --color-pink-200: oklch(89.9% 0.061 343.231); + --color-pink-300: oklch(82.3% 0.12 346.018); + --color-pink-400: oklch(71.8% 0.202 349.761); + --color-pink-500: oklch(65.6% 0.241 354.308); + --color-pink-600: oklch(59.2% 0.249 0.584); + --color-pink-700: oklch(52.5% 0.223 3.958); + --color-pink-800: oklch(45.9% 0.187 3.815); + --color-pink-900: oklch(40.8% 0.153 2.432); + --color-pink-950: oklch(28.4% 0.109 3.907); + + --color-rose-50: oklch(96.9% 0.015 12.422); + --color-rose-100: oklch(94.1% 0.03 12.58); + --color-rose-200: oklch(89.2% 0.058 10.001); + --color-rose-300: oklch(81% 0.117 11.638); + --color-rose-400: oklch(71.2% 0.194 13.428); + --color-rose-500: oklch(64.5% 0.246 16.439); + --color-rose-600: oklch(58.6% 0.253 17.585); + --color-rose-700: oklch(51.4% 0.222 16.935); + --color-rose-800: oklch(45.5% 0.188 13.697); + --color-rose-900: oklch(41% 0.159 10.272); + --color-rose-950: oklch(27.1% 0.105 12.094); + + --color-slate-50: oklch(98.4% 0.003 247.858); + --color-slate-100: oklch(96.8% 0.007 247.896); + --color-slate-200: oklch(92.9% 0.013 255.508); + --color-slate-300: oklch(86.9% 0.022 252.894); + --color-slate-400: oklch(70.4% 0.04 256.788); + --color-slate-500: oklch(55.4% 0.046 257.417); + --color-slate-600: oklch(44.6% 0.043 257.281); + --color-slate-700: oklch(37.2% 0.044 257.287); + --color-slate-800: oklch(27.9% 0.041 260.031); + --color-slate-900: oklch(20.8% 0.042 265.755); + --color-slate-950: oklch(12.9% 0.042 264.695); + + --color-gray-50: oklch(98.5% 0.002 247.839); + --color-gray-100: oklch(96.7% 0.003 264.542); + --color-gray-200: oklch(92.8% 0.006 264.531); + --color-gray-300: oklch(87.2% 0.01 258.338); + --color-gray-400: oklch(70.7% 0.022 261.325); + --color-gray-500: oklch(55.1% 0.027 264.364); + --color-gray-600: oklch(44.6% 0.03 256.802); + --color-gray-700: oklch(37.3% 0.034 259.733); + --color-gray-800: oklch(27.8% 0.033 256.848); + --color-gray-900: oklch(21% 0.034 264.665); + --color-gray-950: oklch(13% 0.028 261.692); + + --color-zinc-50: oklch(98.5% 0 none); + --color-zinc-100: oklch(96.7% 0.001 286.375); + --color-zinc-200: oklch(92% 0.004 286.32); + --color-zinc-300: oklch(87.1% 0.006 286.286); + --color-zinc-400: oklch(70.5% 0.015 286.067); + --color-zinc-500: oklch(55.2% 0.016 285.938); + --color-zinc-600: oklch(44.2% 0.017 285.786); + --color-zinc-700: oklch(37% 0.013 285.805); + --color-zinc-800: oklch(27.4% 0.006 286.033); + --color-zinc-900: oklch(21% 0.006 285.885); + --color-zinc-950: oklch(14.1% 0.005 285.823); + + --color-neutral-50: oklch(98.5% 0 none); + --color-neutral-100: oklch(97% 0 none); + --color-neutral-200: oklch(92.2% 0 none); + --color-neutral-300: oklch(87% 0 none); + --color-neutral-400: oklch(70.8% 0 none); + --color-neutral-500: oklch(55.6% 0 none); + --color-neutral-600: oklch(43.9% 0 none); + --color-neutral-700: oklch(37.1% 0 none); + --color-neutral-800: oklch(26.9% 0 none); + --color-neutral-900: oklch(20.5% 0 none); + --color-neutral-950: oklch(14.5% 0 none); + + --color-stone-50: oklch(98.5% 0.001 106.423); + --color-stone-100: oklch(97% 0.001 106.424); + --color-stone-200: oklch(92.3% 0.003 48.717); + --color-stone-300: oklch(86.9% 0.005 56.366); + --color-stone-400: oklch(70.9% 0.01 56.259); + --color-stone-500: oklch(55.3% 0.013 58.071); + --color-stone-600: oklch(44.4% 0.011 73.639); + --color-stone-700: oklch(37.4% 0.01 67.558); + --color-stone-800: oklch(26.8% 0.007 34.298); + --color-stone-900: oklch(21.6% 0.006 56.043); + --color-stone-950: oklch(14.7% 0.004 49.25); + + --color-mauve-50: oklch(98.5% 0 none); + --color-mauve-100: oklch(96% 0.003 325.6); + --color-mauve-200: oklch(92.2% 0.005 325.62); + --color-mauve-300: oklch(86.5% 0.012 325.68); + --color-mauve-400: oklch(71.1% 0.019 323.02); + --color-mauve-500: oklch(54.2% 0.034 322.5); + --color-mauve-600: oklch(43.5% 0.029 321.78); + --color-mauve-700: oklch(36.4% 0.029 323.89); + --color-mauve-800: oklch(26.3% 0.024 320.12); + --color-mauve-900: oklch(21.2% 0.019 322.12); + --color-mauve-950: oklch(14.5% 0.008 326); + + --color-olive-50: oklch(98.8% 0.003 106.5); + --color-olive-100: oklch(96.6% 0.005 106.5); + --color-olive-200: oklch(93% 0.007 106.5); + --color-olive-300: oklch(88% 0.011 106.6); + --color-olive-400: oklch(73.7% 0.021 106.9); + --color-olive-500: oklch(58% 0.031 107.3); + --color-olive-600: oklch(46.6% 0.025 107.3); + --color-olive-700: oklch(39.4% 0.023 107.4); + --color-olive-800: oklch(28.6% 0.016 107.4); + --color-olive-900: oklch(22.8% 0.013 107.4); + --color-olive-950: oklch(15.3% 0.006 107.1); + + --color-mist-50: oklch(98.7% 0.002 197.1); + --color-mist-100: oklch(96.3% 0.002 197.1); + --color-mist-200: oklch(92.5% 0.005 214.3); + --color-mist-300: oklch(87.2% 0.007 219.6); + --color-mist-400: oklch(72.3% 0.014 214.4); + --color-mist-500: oklch(56% 0.021 213.5); + --color-mist-600: oklch(45% 0.017 213.2); + --color-mist-700: oklch(37.8% 0.015 216); + --color-mist-800: oklch(27.5% 0.011 216.9); + --color-mist-900: oklch(21.8% 0.008 223.9); + --color-mist-950: oklch(14.8% 0.004 228.8); + + --color-taupe-50: oklch(98.6% 0.002 67.8); + --color-taupe-100: oklch(96% 0.002 17.2); + --color-taupe-200: oklch(92.2% 0.005 34.3); + --color-taupe-300: oklch(86.8% 0.007 39.5); + --color-taupe-400: oklch(71.4% 0.014 41.2); + --color-taupe-500: oklch(54.7% 0.021 43.1); + --color-taupe-600: oklch(43.8% 0.017 39.3); + --color-taupe-700: oklch(36.7% 0.016 35.7); + --color-taupe-800: oklch(26.8% 0.011 36.5); + --color-taupe-900: oklch(21.4% 0.009 43.1); + --color-taupe-950: oklch(14.7% 0.004 49.3); + + --color-black: #000; + --color-white: #fff; + + --spacing: 0.25rem; + + --breakpoint-sm: 40rem; + --breakpoint-md: 48rem; + --breakpoint-lg: 64rem; + --breakpoint-xl: 80rem; + --breakpoint-2xl: 96rem; + + --container-3xs: 16rem; + --container-2xs: 18rem; + --container-xs: 20rem; + --container-sm: 24rem; + --container-md: 28rem; + --container-lg: 32rem; + --container-xl: 36rem; + --container-2xl: 42rem; + --container-3xl: 48rem; + --container-4xl: 56rem; + --container-5xl: 64rem; + --container-6xl: 72rem; + --container-7xl: 80rem; + + --text-xs: 0.75rem; + --text-xs--line-height: calc(1 / 0.75); + --text-sm: 0.875rem; + --text-sm--line-height: calc(1.25 / 0.875); + --text-base: 1rem; + --text-base--line-height: calc(1.5 / 1); + --text-lg: 1.125rem; + --text-lg--line-height: calc(1.75 / 1.125); + --text-xl: 1.25rem; + --text-xl--line-height: calc(1.75 / 1.25); + --text-2xl: 1.5rem; + --text-2xl--line-height: calc(2 / 1.5); + --text-3xl: 1.875rem; + --text-3xl--line-height: calc(2.25 / 1.875); + --text-4xl: 2.25rem; + --text-4xl--line-height: calc(2.5 / 2.25); + --text-5xl: 3rem; + --text-5xl--line-height: 1; + --text-6xl: 3.75rem; + --text-6xl--line-height: 1; + --text-7xl: 4.5rem; + --text-7xl--line-height: 1; + --text-8xl: 6rem; + --text-8xl--line-height: 1; + --text-9xl: 8rem; + --text-9xl--line-height: 1; + + --font-weight-thin: 100; + --font-weight-extralight: 200; + --font-weight-light: 300; + --font-weight-normal: 400; + --font-weight-medium: 500; + --font-weight-semibold: 600; + --font-weight-bold: 700; + --font-weight-extrabold: 800; + --font-weight-black: 900; + + --tracking-tighter: -0.05em; + --tracking-tight: -0.025em; + --tracking-normal: 0em; + --tracking-wide: 0.025em; + --tracking-wider: 0.05em; + --tracking-widest: 0.1em; + + --leading-tight: 1.25; + --leading-snug: 1.375; + --leading-normal: 1.5; + --leading-relaxed: 1.625; + --leading-loose: 2; + + --radius-xs: 0.125rem; + --radius-sm: 0.25rem; + --radius-md: 0.375rem; + --radius-lg: 0.5rem; + --radius-xl: 0.75rem; + --radius-2xl: 1rem; + --radius-3xl: 1.5rem; + --radius-4xl: 2rem; + + --shadow-2xs: 0 1px rgb(0 0 0 / 0.05); + --shadow-xs: 0 1px 2px 0 rgb(0 0 0 / 0.05); + --shadow-sm: 0 1px 3px 0 rgb(0 0 0 / 0.1), 0 1px 2px -1px rgb(0 0 0 / 0.1); + --shadow-md: + 0 4px 6px -1px rgb(0 0 0 / 0.1), 0 2px 4px -2px rgb(0 0 0 / 0.1); + --shadow-lg: + 0 10px 15px -3px rgb(0 0 0 / 0.1), 0 4px 6px -4px rgb(0 0 0 / 0.1); + --shadow-xl: + 0 20px 25px -5px rgb(0 0 0 / 0.1), 0 8px 10px -6px rgb(0 0 0 / 0.1); + --shadow-2xl: 0 25px 50px -12px rgb(0 0 0 / 0.25); + + --inset-shadow-2xs: inset 0 1px rgb(0 0 0 / 0.05); + --inset-shadow-xs: inset 0 1px 1px rgb(0 0 0 / 0.05); + --inset-shadow-sm: inset 0 2px 4px rgb(0 0 0 / 0.05); + + --drop-shadow-xs: 0 1px 1px rgb(0 0 0 / 0.05); + --drop-shadow-sm: 0 1px 2px rgb(0 0 0 / 0.15); + --drop-shadow-md: 0 3px 3px rgb(0 0 0 / 0.12); + --drop-shadow-lg: 0 4px 4px rgb(0 0 0 / 0.15); + --drop-shadow-xl: 0 9px 7px rgb(0 0 0 / 0.1); + --drop-shadow-2xl: 0 25px 25px rgb(0 0 0 / 0.15); + + --text-shadow-2xs: 0px 1px 0px rgb(0 0 0 / 0.15); + --text-shadow-xs: 0px 1px 1px rgb(0 0 0 / 0.2); + --text-shadow-sm: + 0px 1px 0px rgb(0 0 0 / 0.075), 0px 1px 1px rgb(0 0 0 / 0.075), + 0px 2px 2px rgb(0 0 0 / 0.075); + --text-shadow-md: + 0px 1px 1px rgb(0 0 0 / 0.1), 0px 1px 2px rgb(0 0 0 / 0.1), + 0px 2px 4px rgb(0 0 0 / 0.1); + --text-shadow-lg: + 0px 1px 2px rgb(0 0 0 / 0.1), 0px 3px 2px rgb(0 0 0 / 0.1), + 0px 4px 8px rgb(0 0 0 / 0.1); + + --ease-in: cubic-bezier(0.4, 0, 1, 1); + --ease-out: cubic-bezier(0, 0, 0.2, 1); + --ease-in-out: cubic-bezier(0.4, 0, 0.2, 1); + + --animate-spin: spin 1s linear infinite; + --animate-ping: ping 1s cubic-bezier(0, 0, 0.2, 1) infinite; + --animate-pulse: pulse 2s cubic-bezier(0.4, 0, 0.6, 1) infinite; + --animate-bounce: bounce 1s infinite; + + @keyframes spin { + to { + transform: rotate(360deg); + } + } + + @keyframes ping { + 75%, + 100% { + transform: scale(2); + opacity: 0; + } + } + + @keyframes pulse { + 50% { + opacity: 0.5; + } + } + + @keyframes bounce { + 0%, + 100% { + transform: translateY(-25%); + animation-timing-function: cubic-bezier(0.8, 0, 1, 1); + } + + 50% { + transform: none; + animation-timing-function: cubic-bezier(0, 0, 0.2, 1); + } + } + + --blur-xs: 4px; + --blur-sm: 8px; + --blur-md: 12px; + --blur-lg: 16px; + --blur-xl: 24px; + --blur-2xl: 40px; + --blur-3xl: 64px; + + --perspective-dramatic: 100px; + --perspective-near: 300px; + --perspective-normal: 500px; + --perspective-midrange: 800px; + --perspective-distant: 1200px; + + --aspect-video: 16 / 9; + + --default-transition-duration: 150ms; + --default-transition-timing-function: cubic-bezier(0.4, 0, 0.2, 1); + --default-font-family: --theme(--font-sans, initial); + --default-font-feature-settings: --theme( + --font-sans--font-feature-settings, + initial + ); + --default-font-variation-settings: --theme( + --font-sans--font-variation-settings, + initial + ); + --default-mono-font-family: --theme(--font-mono, initial); + --default-mono-font-feature-settings: --theme( + --font-mono--font-feature-settings, + initial + ); + --default-mono-font-variation-settings: --theme( + --font-mono--font-variation-settings, + initial + ); + } + + /* Deprecated */ + @theme default inline reference { + --blur: 8px; + --shadow: 0 1px 3px 0 rgb(0 0 0 / 0.1), 0 1px 2px -1px rgb(0 0 0 / 0.1); + --shadow-inner: inset 0 2px 4px 0 rgb(0 0 0 / 0.05); + --drop-shadow: 0 1px 2px rgb(0 0 0 / 0.1), 0 1px 1px rgb(0 0 0 / 0.06); + --radius: 0.25rem; + --max-width-prose: 65ch; + } +} + +@layer base { + /* + 1. Prevent padding and border from affecting element width. (https://github.com/mozdevs/cssremedy/issues/4) + 2. Remove default margins and padding + 3. Reset all borders. +*/ + + *, + ::after, + ::before, + ::backdrop, + ::file-selector-button { + box-sizing: border-box; /* 1 */ + margin: 0; /* 2 */ + padding: 0; /* 2 */ + border: 0 solid; /* 3 */ + } + + /* + 1. Use a consistent sensible line-height in all browsers. + 2. Prevent adjustments of font size after orientation changes in iOS. + 3. Use a more readable tab size. + 4. Use the user's configured `sans` font-family by default. + 5. Use the user's configured `sans` font-feature-settings by default. + 6. Use the user's configured `sans` font-variation-settings by default. + 7. Disable tap highlights on iOS. +*/ + + html, + :host { + line-height: 1.5; /* 1 */ + -webkit-text-size-adjust: 100%; /* 2 */ + tab-size: 4; /* 3 */ + font-family: --theme( + --default-font-family, + -apple-system, + BlinkMacSystemFont, + "Segoe UI", + Roboto, + "Helvetica Neue", + "Noto Sans", + Arial, + sans-serif, + "Apple Color Emoji", + "Segoe UI Emoji", + "Segoe UI Symbol", + "Noto Color Emoji" + ); /* 4 */ + font-feature-settings: --theme( + --default-font-feature-settings, + normal + ); /* 5 */ + font-variation-settings: --theme( + --default-font-variation-settings, + normal + ); /* 6 */ + -webkit-tap-highlight-color: transparent; /* 7 */ + } + + /* + 1. Add the correct height in Firefox. + 2. Correct the inheritance of border color in Firefox. (https://bugzilla.mozilla.org/show_bug.cgi?id=190655) + 3. Reset the default border style to a 1px solid border. +*/ + + hr { + height: 0; /* 1 */ + color: inherit; /* 2 */ + border-top-width: 1px; /* 3 */ + } + + /* + Add the correct text decoration in Chrome, Edge, and Safari. +*/ + + abbr:where([title]) { + -webkit-text-decoration: underline dotted; + text-decoration: underline dotted; + } + + /* + Remove the default font size and weight for headings. +*/ + + h1, + h2, + h3, + h4, + h5, + h6 { + font-size: inherit; + font-weight: inherit; + } + + /* + Reset links to optimize for opt-in styling instead of opt-out. +*/ + + a { + color: inherit; + -webkit-text-decoration: inherit; + text-decoration: inherit; + } + + /* + Add the correct font weight in Edge and Safari. +*/ + + b, + strong { + font-weight: bolder; + } + + /* + 1. Use the user's configured `mono` font-family by default. + 2. Use the user's configured `mono` font-feature-settings by default. + 3. Use the user's configured `mono` font-variation-settings by default. + 4. Correct the odd `em` font sizing in all browsers. +*/ + + code, + kbd, + samp, + pre { + font-family: --theme( + --default-mono-font-family, + ui-monospace, + SFMono-Regular, + Menlo, + Monaco, + Consolas, + "Liberation Mono", + "Courier New", + monospace + ); /* 1 */ + font-feature-settings: --theme( + --default-mono-font-feature-settings, + normal + ); /* 2 */ + font-variation-settings: --theme( + --default-mono-font-variation-settings, + normal + ); /* 3 */ + font-size: 1em; /* 4 */ + } + + /* + Add the correct font size in all browsers. +*/ + + small { + font-size: 80%; + } + + /* + Prevent `sub` and `sup` elements from affecting the line height in all browsers. +*/ + + sub, + sup { + font-size: 75%; + line-height: 0; + position: relative; + vertical-align: baseline; + } + + sub { + bottom: -0.25em; + } + + sup { + top: -0.5em; + } + + /* + 1. Remove text indentation from table contents in Chrome and Safari. (https://bugs.chromium.org/p/chromium/issues/detail?id=999088, https://bugs.webkit.org/show_bug.cgi?id=201297) + 2. Correct table border color inheritance in all Chrome and Safari. (https://bugs.chromium.org/p/chromium/issues/detail?id=935729, https://bugs.webkit.org/show_bug.cgi?id=195016) + 3. Remove gaps between table borders by default. +*/ + + table { + text-indent: 0; /* 1 */ + border-color: inherit; /* 2 */ + border-collapse: collapse; /* 3 */ + } + + /* + Use the modern Firefox focus style for all focusable elements. +*/ + + :-moz-focusring:where(:not(iframe)) { + outline: auto; + } + + /* + Add the correct vertical alignment in Chrome and Firefox. +*/ + + progress { + vertical-align: baseline; + } + + /* + Add the correct display in Chrome and Safari. +*/ + + summary { + display: list-item; + } + + /* + Make lists unstyled by default. +*/ + + ol, + ul, + menu { + list-style: none; + } + + /* + 1. Make replaced elements `display: block` by default. (https://github.com/mozdevs/cssremedy/issues/14) + 2. Add `vertical-align: middle` to align replaced elements more sensibly by default. (https://github.com/jensimmons/cssremedy/issues/14#issuecomment-634934210) + This can trigger a poorly considered lint error in some tools but is included by design. +*/ + + img, + svg, + video, + canvas, + audio, + iframe, + embed, + object { + display: block; /* 1 */ + vertical-align: middle; /* 2 */ + } + + /* + Constrain images and videos to the parent width and preserve their intrinsic aspect ratio. (https://github.com/mozdevs/cssremedy/issues/14) +*/ + + img, + video { + max-width: 100%; + height: auto; + } + + /* + 1. Inherit font styles in all browsers. + 2. Remove border radius in all browsers. + 3. Remove background color in all browsers. + 4. Ensure consistent opacity for disabled states in all browsers. +*/ + + button, + input, + select, + optgroup, + textarea, + ::file-selector-button { + font: inherit; /* 1 */ + font-feature-settings: inherit; /* 1 */ + font-variation-settings: inherit; /* 1 */ + letter-spacing: inherit; /* 1 */ + color: inherit; /* 1 */ + border-radius: 0; /* 2 */ + background-color: transparent; /* 3 */ + opacity: 1; /* 4 */ + } + + /* + Restore default font weight. +*/ + + :where(select:is([multiple], [size])) optgroup { + font-weight: bolder; + } + + /* + Restore indentation. +*/ + + :where(select:is([multiple], [size])) optgroup option { + padding-inline-start: 20px; + } + + /* + Restore space after button. +*/ + + ::file-selector-button { + margin-inline-end: 4px; + } + + /* + Reset the default placeholder opacity in Firefox. (https://github.com/tailwindlabs/tailwindcss/issues/3300) +*/ + + ::placeholder { + opacity: 1; + } + + /* + Set the default placeholder color to a semi-transparent version of the current text color in browsers that do not + crash when using `color-mix(…)` with `currentcolor`. (https://github.com/tailwindlabs/tailwindcss/issues/17194) +*/ + + @supports (not (-webkit-appearance: -apple-pay-button)) /* Not Safari */ or + (contain-intrinsic-size: 1px) /* Safari 17+ */ { + ::placeholder { + color: color-mix(in oklab, currentcolor 50%, transparent); + } + } + + /* + Prevent resizing textareas horizontally by default. +*/ + + textarea { + resize: vertical; + } + + /* + Remove the inner padding in Chrome and Safari on macOS. +*/ + + ::-webkit-search-decoration { + -webkit-appearance: none; + } + + /* + 1. Ensure date/time inputs have the same height when empty in iOS Safari. + 2. Ensure text alignment can be changed on date/time inputs in iOS Safari. +*/ + + ::-webkit-date-and-time-value { + min-height: 1lh; /* 1 */ + text-align: inherit; /* 2 */ + } + + /* + Prevent height from changing on date/time inputs in macOS Safari when the input is set to `display: block`. +*/ + + ::-webkit-datetime-edit { + display: inline-flex; + } + + /* + Remove excess padding from pseudo-elements in date/time inputs to ensure consistent height across browsers. +*/ + + ::-webkit-datetime-edit-fields-wrapper { + padding: 0; + } + + ::-webkit-datetime-edit, + ::-webkit-datetime-edit-year-field, + ::-webkit-datetime-edit-month-field, + ::-webkit-datetime-edit-day-field, + ::-webkit-datetime-edit-hour-field, + ::-webkit-datetime-edit-minute-field, + ::-webkit-datetime-edit-second-field, + ::-webkit-datetime-edit-millisecond-field, + ::-webkit-datetime-edit-meridiem-field { + padding-block: 0; + } + + /* + Center dropdown marker shown on inputs with paired ``s in Chrome. (https://github.com/tailwindlabs/tailwindcss/issues/18499) +*/ + + ::-webkit-calendar-picker-indicator { + line-height: 1; + } + + /* + Remove the additional `:invalid` styles in Firefox. (https://github.com/mozilla/gecko-dev/blob/2f9eacd9d3d995c937b4251a5557d95d494c9be1/layout/style/res/forms.css#L728-L737) +*/ + + :-moz-ui-invalid { + box-shadow: none; + } + + /* + Correct the inability to style the border radius in iOS Safari. +*/ + + button, + input:where([type="button"], [type="reset"], [type="submit"]), + ::file-selector-button { + appearance: button; + } + + /* + Correct the cursor style of increment and decrement buttons in Safari. +*/ + + ::-webkit-inner-spin-button, + ::-webkit-outer-spin-button { + height: auto; + } + + /* + Make elements with the HTML hidden attribute stay hidden by default. +*/ + + [hidden]:where(:not([hidden="until-found"])) { + display: none !important; + } +} + +@layer utilities { + @tailwind utilities; +} diff --git a/dg-ui/node_modules/tailwindcss/package.json b/dg-ui/node_modules/tailwindcss/package.json new file mode 100644 index 0000000..aed674f --- /dev/null +++ b/dg-ui/node_modules/tailwindcss/package.json @@ -0,0 +1,89 @@ +{ + "name": "tailwindcss", + "version": "4.3.5", + "description": "A utility-first CSS framework for rapidly building custom user interfaces.", + "license": "MIT", + "repository": { + "type": "git", + "url": "https://github.com/tailwindlabs/tailwindcss.git", + "directory": "packages/tailwindcss" + }, + "bugs": "https://github.com/tailwindlabs/tailwindcss/issues", + "homepage": "https://tailwindcss.com", + "exports": { + ".": { + "types": "./dist/lib.d.mts", + "style": "./index.css", + "require": "./dist/lib.js", + "import": "./dist/lib.mjs" + }, + "./plugin": { + "require": "./dist/plugin.js", + "import": "./dist/plugin.mjs" + }, + "./plugin.js": { + "require": "./dist/plugin.js", + "import": "./dist/plugin.mjs" + }, + "./defaultTheme": { + "require": "./dist/default-theme.js", + "import": "./dist/default-theme.mjs" + }, + "./defaultTheme.js": { + "require": "./dist/default-theme.js", + "import": "./dist/default-theme.mjs" + }, + "./colors": { + "require": "./dist/colors.js", + "import": "./dist/colors.mjs" + }, + "./colors.js": { + "require": "./dist/colors.js", + "import": "./dist/colors.mjs" + }, + "./lib/util/flattenColorPalette": { + "require": "./dist/flatten-color-palette.js", + "import": "./dist/flatten-color-palette.mjs" + }, + "./lib/util/flattenColorPalette.js": { + "require": "./dist/flatten-color-palette.js", + "import": "./dist/flatten-color-palette.mjs" + }, + "./package.json": "./package.json", + "./index.css": "./index.css", + "./index": "./index.css", + "./preflight.css": "./preflight.css", + "./preflight": "./preflight.css", + "./theme.css": "./theme.css", + "./theme": "./theme.css", + "./utilities.css": "./utilities.css", + "./utilities": "./utilities.css" + }, + "publishConfig": { + "provenance": true, + "access": "public" + }, + "style": "index.css", + "files": [ + "dist", + "index.css", + "preflight.css", + "theme.css", + "utilities.css" + ], + "devDependencies": { + "@jridgewell/remapping": "^2.3.5", + "@types/node": "22.20.1", + "dedent": "1.7.2", + "lightningcss": "1.33.0", + "magic-string": "^1.1.0", + "source-map-js": "^1.2.1", + "@tailwindcss/oxide": "^4.3.5" + }, + "scripts": { + "lint": "tsc --noEmit", + "build": "tsup-node --env.NODE_ENV production", + "dev": "tsup-node --env.NODE_ENV development --watch", + "test:ui": "playwright test" + } +} \ No newline at end of file diff --git a/dg-ui/node_modules/tailwindcss/preflight.css b/dg-ui/node_modules/tailwindcss/preflight.css new file mode 100644 index 0000000..04e8790 --- /dev/null +++ b/dg-ui/node_modules/tailwindcss/preflight.css @@ -0,0 +1,398 @@ +/* + 1. Prevent padding and border from affecting element width. (https://github.com/mozdevs/cssremedy/issues/4) + 2. Remove default margins and padding + 3. Reset all borders. +*/ + +*, +::after, +::before, +::backdrop, +::file-selector-button { + box-sizing: border-box; /* 1 */ + margin: 0; /* 2 */ + padding: 0; /* 2 */ + border: 0 solid; /* 3 */ +} + +/* + 1. Use a consistent sensible line-height in all browsers. + 2. Prevent adjustments of font size after orientation changes in iOS. + 3. Use a more readable tab size. + 4. Use the user's configured `sans` font-family by default. + 5. Use the user's configured `sans` font-feature-settings by default. + 6. Use the user's configured `sans` font-variation-settings by default. + 7. Disable tap highlights on iOS. +*/ + +html, +:host { + line-height: 1.5; /* 1 */ + -webkit-text-size-adjust: 100%; /* 2 */ + tab-size: 4; /* 3 */ + font-family: --theme( + --default-font-family, + -apple-system, + BlinkMacSystemFont, + 'Segoe UI', + Roboto, + 'Helvetica Neue', + 'Noto Sans', + Arial, + sans-serif, + 'Apple Color Emoji', + 'Segoe UI Emoji', + 'Segoe UI Symbol', + 'Noto Color Emoji' + ); /* 4 */ + font-feature-settings: --theme(--default-font-feature-settings, normal); /* 5 */ + font-variation-settings: --theme(--default-font-variation-settings, normal); /* 6 */ + -webkit-tap-highlight-color: transparent; /* 7 */ +} + +/* + 1. Add the correct height in Firefox. + 2. Correct the inheritance of border color in Firefox. (https://bugzilla.mozilla.org/show_bug.cgi?id=190655) + 3. Reset the default border style to a 1px solid border. +*/ + +hr { + height: 0; /* 1 */ + color: inherit; /* 2 */ + border-top-width: 1px; /* 3 */ +} + +/* + Add the correct text decoration in Chrome, Edge, and Safari. +*/ + +abbr:where([title]) { + -webkit-text-decoration: underline dotted; + text-decoration: underline dotted; +} + +/* + Remove the default font size and weight for headings. +*/ + +h1, +h2, +h3, +h4, +h5, +h6 { + font-size: inherit; + font-weight: inherit; +} + +/* + Reset links to optimize for opt-in styling instead of opt-out. +*/ + +a { + color: inherit; + -webkit-text-decoration: inherit; + text-decoration: inherit; +} + +/* + Add the correct font weight in Edge and Safari. +*/ + +b, +strong { + font-weight: bolder; +} + +/* + 1. Use the user's configured `mono` font-family by default. + 2. Use the user's configured `mono` font-feature-settings by default. + 3. Use the user's configured `mono` font-variation-settings by default. + 4. Correct the odd `em` font sizing in all browsers. +*/ + +code, +kbd, +samp, +pre { + font-family: --theme( + --default-mono-font-family, + ui-monospace, + SFMono-Regular, + Menlo, + Monaco, + Consolas, + 'Liberation Mono', + 'Courier New', + monospace + ); /* 1 */ + font-feature-settings: --theme(--default-mono-font-feature-settings, normal); /* 2 */ + font-variation-settings: --theme(--default-mono-font-variation-settings, normal); /* 3 */ + font-size: 1em; /* 4 */ +} + +/* + Add the correct font size in all browsers. +*/ + +small { + font-size: 80%; +} + +/* + Prevent `sub` and `sup` elements from affecting the line height in all browsers. +*/ + +sub, +sup { + font-size: 75%; + line-height: 0; + position: relative; + vertical-align: baseline; +} + +sub { + bottom: -0.25em; +} + +sup { + top: -0.5em; +} + +/* + 1. Remove text indentation from table contents in Chrome and Safari. (https://bugs.chromium.org/p/chromium/issues/detail?id=999088, https://bugs.webkit.org/show_bug.cgi?id=201297) + 2. Correct table border color inheritance in all Chrome and Safari. (https://bugs.chromium.org/p/chromium/issues/detail?id=935729, https://bugs.webkit.org/show_bug.cgi?id=195016) + 3. Remove gaps between table borders by default. +*/ + +table { + text-indent: 0; /* 1 */ + border-color: inherit; /* 2 */ + border-collapse: collapse; /* 3 */ +} + +/* + Use the modern Firefox focus style for all focusable elements. +*/ + +:-moz-focusring:where(:not(iframe)) { + outline: auto; +} + +/* + Add the correct vertical alignment in Chrome and Firefox. +*/ + +progress { + vertical-align: baseline; +} + +/* + Add the correct display in Chrome and Safari. +*/ + +summary { + display: list-item; +} + +/* + Make lists unstyled by default. +*/ + +ol, +ul, +menu { + list-style: none; +} + +/* + 1. Make replaced elements `display: block` by default. (https://github.com/mozdevs/cssremedy/issues/14) + 2. Add `vertical-align: middle` to align replaced elements more sensibly by default. (https://github.com/jensimmons/cssremedy/issues/14#issuecomment-634934210) + This can trigger a poorly considered lint error in some tools but is included by design. +*/ + +img, +svg, +video, +canvas, +audio, +iframe, +embed, +object { + display: block; /* 1 */ + vertical-align: middle; /* 2 */ +} + +/* + Constrain images and videos to the parent width and preserve their intrinsic aspect ratio. (https://github.com/mozdevs/cssremedy/issues/14) +*/ + +img, +video { + max-width: 100%; + height: auto; +} + +/* + 1. Inherit font styles in all browsers. + 2. Remove border radius in all browsers. + 3. Remove background color in all browsers. + 4. Ensure consistent opacity for disabled states in all browsers. +*/ + +button, +input, +select, +optgroup, +textarea, +::file-selector-button { + font: inherit; /* 1 */ + font-feature-settings: inherit; /* 1 */ + font-variation-settings: inherit; /* 1 */ + letter-spacing: inherit; /* 1 */ + color: inherit; /* 1 */ + border-radius: 0; /* 2 */ + background-color: transparent; /* 3 */ + opacity: 1; /* 4 */ +} + +/* + Restore default font weight. +*/ + +:where(select:is([multiple], [size])) optgroup { + font-weight: bolder; +} + +/* + Restore indentation. +*/ + +:where(select:is([multiple], [size])) optgroup option { + padding-inline-start: 20px; +} + +/* + Restore space after button. +*/ + +::file-selector-button { + margin-inline-end: 4px; +} + +/* + Reset the default placeholder opacity in Firefox. (https://github.com/tailwindlabs/tailwindcss/issues/3300) +*/ + +::placeholder { + opacity: 1; +} + +/* + Set the default placeholder color to a semi-transparent version of the current text color in browsers that do not + crash when using `color-mix(…)` with `currentcolor`. (https://github.com/tailwindlabs/tailwindcss/issues/17194) +*/ + +@supports (not (-webkit-appearance: -apple-pay-button)) /* Not Safari */ or + (contain-intrinsic-size: 1px) /* Safari 17+ */ { + ::placeholder { + color: color-mix(in oklab, currentcolor 50%, transparent); + } +} + +/* + Prevent resizing textareas horizontally by default. +*/ + +textarea { + resize: vertical; +} + +/* + Remove the inner padding in Chrome and Safari on macOS. +*/ + +::-webkit-search-decoration { + -webkit-appearance: none; +} + +/* + 1. Ensure date/time inputs have the same height when empty in iOS Safari. + 2. Ensure text alignment can be changed on date/time inputs in iOS Safari. +*/ + +::-webkit-date-and-time-value { + min-height: 1lh; /* 1 */ + text-align: inherit; /* 2 */ +} + +/* + Prevent height from changing on date/time inputs in macOS Safari when the input is set to `display: block`. +*/ + +::-webkit-datetime-edit { + display: inline-flex; +} + +/* + Remove excess padding from pseudo-elements in date/time inputs to ensure consistent height across browsers. +*/ + +::-webkit-datetime-edit-fields-wrapper { + padding: 0; +} + +::-webkit-datetime-edit, +::-webkit-datetime-edit-year-field, +::-webkit-datetime-edit-month-field, +::-webkit-datetime-edit-day-field, +::-webkit-datetime-edit-hour-field, +::-webkit-datetime-edit-minute-field, +::-webkit-datetime-edit-second-field, +::-webkit-datetime-edit-millisecond-field, +::-webkit-datetime-edit-meridiem-field { + padding-block: 0; +} + +/* + Center dropdown marker shown on inputs with paired ``s in Chrome. (https://github.com/tailwindlabs/tailwindcss/issues/18499) +*/ + +::-webkit-calendar-picker-indicator { + line-height: 1; +} + +/* + Remove the additional `:invalid` styles in Firefox. (https://github.com/mozilla/gecko-dev/blob/2f9eacd9d3d995c937b4251a5557d95d494c9be1/layout/style/res/forms.css#L728-L737) +*/ + +:-moz-ui-invalid { + box-shadow: none; +} + +/* + Correct the inability to style the border radius in iOS Safari. +*/ + +button, +input:where([type='button'], [type='reset'], [type='submit']), +::file-selector-button { + appearance: button; +} + +/* + Correct the cursor style of increment and decrement buttons in Safari. +*/ + +::-webkit-inner-spin-button, +::-webkit-outer-spin-button { + height: auto; +} + +/* + Make elements with the HTML hidden attribute stay hidden by default. +*/ + +[hidden]:where(:not([hidden='until-found'])) { + display: none !important; +} diff --git a/dg-ui/node_modules/tailwindcss/theme.css b/dg-ui/node_modules/tailwindcss/theme.css new file mode 100644 index 0000000..05364f5 --- /dev/null +++ b/dg-ui/node_modules/tailwindcss/theme.css @@ -0,0 +1,510 @@ +@theme default { + --font-sans: + -apple-system, BlinkMacSystemFont, 'Segoe UI', Roboto, 'Helvetica Neue', 'Noto Sans', Arial, + sans-serif, 'Apple Color Emoji', 'Segoe UI Emoji', 'Segoe UI Symbol', 'Noto Color Emoji'; + --font-serif: ui-serif, Georgia, Cambria, 'Times New Roman', Times, serif; + --font-mono: + ui-monospace, SFMono-Regular, Menlo, Monaco, Consolas, 'Liberation Mono', 'Courier New', + monospace; + + --color-red-50: oklch(97.1% 0.013 17.38); + --color-red-100: oklch(93.6% 0.032 17.717); + --color-red-200: oklch(88.5% 0.062 18.334); + --color-red-300: oklch(80.8% 0.114 19.571); + --color-red-400: oklch(70.4% 0.191 22.216); + --color-red-500: oklch(63.7% 0.237 25.331); + --color-red-600: oklch(57.7% 0.245 27.325); + --color-red-700: oklch(50.5% 0.213 27.518); + --color-red-800: oklch(44.4% 0.177 26.899); + --color-red-900: oklch(39.6% 0.141 25.723); + --color-red-950: oklch(25.8% 0.092 26.042); + + --color-orange-50: oklch(98% 0.016 73.684); + --color-orange-100: oklch(95.4% 0.038 75.164); + --color-orange-200: oklch(90.1% 0.076 70.697); + --color-orange-300: oklch(83.7% 0.128 66.29); + --color-orange-400: oklch(75% 0.183 55.934); + --color-orange-500: oklch(70.5% 0.213 47.604); + --color-orange-600: oklch(64.6% 0.222 41.116); + --color-orange-700: oklch(55.3% 0.195 38.402); + --color-orange-800: oklch(47% 0.157 37.304); + --color-orange-900: oklch(40.8% 0.123 38.172); + --color-orange-950: oklch(26.6% 0.079 36.259); + + --color-amber-50: oklch(98.7% 0.022 95.277); + --color-amber-100: oklch(96.2% 0.059 95.617); + --color-amber-200: oklch(92.4% 0.12 95.746); + --color-amber-300: oklch(87.9% 0.169 91.605); + --color-amber-400: oklch(82.8% 0.189 84.429); + --color-amber-500: oklch(76.9% 0.188 70.08); + --color-amber-600: oklch(66.6% 0.179 58.318); + --color-amber-700: oklch(55.5% 0.163 48.998); + --color-amber-800: oklch(47.3% 0.137 46.201); + --color-amber-900: oklch(41.4% 0.112 45.904); + --color-amber-950: oklch(27.9% 0.077 45.635); + + --color-yellow-50: oklch(98.7% 0.026 102.212); + --color-yellow-100: oklch(97.3% 0.071 103.193); + --color-yellow-200: oklch(94.5% 0.129 101.54); + --color-yellow-300: oklch(90.5% 0.182 98.111); + --color-yellow-400: oklch(85.2% 0.199 91.936); + --color-yellow-500: oklch(79.5% 0.184 86.047); + --color-yellow-600: oklch(68.1% 0.162 75.834); + --color-yellow-700: oklch(55.4% 0.135 66.442); + --color-yellow-800: oklch(47.6% 0.114 61.907); + --color-yellow-900: oklch(42.1% 0.095 57.708); + --color-yellow-950: oklch(28.6% 0.066 53.813); + + --color-lime-50: oklch(98.6% 0.031 120.757); + --color-lime-100: oklch(96.7% 0.067 122.328); + --color-lime-200: oklch(93.8% 0.127 124.321); + --color-lime-300: oklch(89.7% 0.196 126.665); + --color-lime-400: oklch(84.1% 0.238 128.85); + --color-lime-500: oklch(76.8% 0.233 130.85); + --color-lime-600: oklch(64.8% 0.2 131.684); + --color-lime-700: oklch(53.2% 0.157 131.589); + --color-lime-800: oklch(45.3% 0.124 130.933); + --color-lime-900: oklch(40.5% 0.101 131.063); + --color-lime-950: oklch(27.4% 0.072 132.109); + + --color-green-50: oklch(98.2% 0.018 155.826); + --color-green-100: oklch(96.2% 0.044 156.743); + --color-green-200: oklch(92.5% 0.084 155.995); + --color-green-300: oklch(87.1% 0.15 154.449); + --color-green-400: oklch(79.2% 0.209 151.711); + --color-green-500: oklch(72.3% 0.219 149.579); + --color-green-600: oklch(62.7% 0.194 149.214); + --color-green-700: oklch(52.7% 0.154 150.069); + --color-green-800: oklch(44.8% 0.119 151.328); + --color-green-900: oklch(39.3% 0.095 152.535); + --color-green-950: oklch(26.6% 0.065 152.934); + + --color-emerald-50: oklch(97.9% 0.021 166.113); + --color-emerald-100: oklch(95% 0.052 163.051); + --color-emerald-200: oklch(90.5% 0.093 164.15); + --color-emerald-300: oklch(84.5% 0.143 164.978); + --color-emerald-400: oklch(76.5% 0.177 163.223); + --color-emerald-500: oklch(69.6% 0.17 162.48); + --color-emerald-600: oklch(59.6% 0.145 163.225); + --color-emerald-700: oklch(50.8% 0.118 165.612); + --color-emerald-800: oklch(43.2% 0.095 166.913); + --color-emerald-900: oklch(37.8% 0.077 168.94); + --color-emerald-950: oklch(26.2% 0.051 172.552); + + --color-teal-50: oklch(98.4% 0.014 180.72); + --color-teal-100: oklch(95.3% 0.051 180.801); + --color-teal-200: oklch(91% 0.096 180.426); + --color-teal-300: oklch(85.5% 0.138 181.071); + --color-teal-400: oklch(77.7% 0.152 181.912); + --color-teal-500: oklch(70.4% 0.14 182.503); + --color-teal-600: oklch(60% 0.118 184.704); + --color-teal-700: oklch(51.1% 0.096 186.391); + --color-teal-800: oklch(43.7% 0.078 188.216); + --color-teal-900: oklch(38.6% 0.063 188.416); + --color-teal-950: oklch(27.7% 0.046 192.524); + + --color-cyan-50: oklch(98.4% 0.019 200.873); + --color-cyan-100: oklch(95.6% 0.045 203.388); + --color-cyan-200: oklch(91.7% 0.08 205.041); + --color-cyan-300: oklch(86.5% 0.127 207.078); + --color-cyan-400: oklch(78.9% 0.154 211.53); + --color-cyan-500: oklch(71.5% 0.143 215.221); + --color-cyan-600: oklch(60.9% 0.126 221.723); + --color-cyan-700: oklch(52% 0.105 223.128); + --color-cyan-800: oklch(45% 0.085 224.283); + --color-cyan-900: oklch(39.8% 0.07 227.392); + --color-cyan-950: oklch(30.2% 0.056 229.695); + + --color-sky-50: oklch(97.7% 0.013 236.62); + --color-sky-100: oklch(95.1% 0.026 236.824); + --color-sky-200: oklch(90.1% 0.058 230.902); + --color-sky-300: oklch(82.8% 0.111 230.318); + --color-sky-400: oklch(74.6% 0.16 232.661); + --color-sky-500: oklch(68.5% 0.169 237.323); + --color-sky-600: oklch(58.8% 0.158 241.966); + --color-sky-700: oklch(50% 0.134 242.749); + --color-sky-800: oklch(44.3% 0.11 240.79); + --color-sky-900: oklch(39.1% 0.09 240.876); + --color-sky-950: oklch(29.3% 0.066 243.157); + + --color-blue-50: oklch(97% 0.014 254.604); + --color-blue-100: oklch(93.2% 0.032 255.585); + --color-blue-200: oklch(88.2% 0.059 254.128); + --color-blue-300: oklch(80.9% 0.105 251.813); + --color-blue-400: oklch(70.7% 0.165 254.624); + --color-blue-500: oklch(62.3% 0.214 259.815); + --color-blue-600: oklch(54.6% 0.245 262.881); + --color-blue-700: oklch(48.8% 0.243 264.376); + --color-blue-800: oklch(42.4% 0.199 265.638); + --color-blue-900: oklch(37.9% 0.146 265.522); + --color-blue-950: oklch(28.2% 0.091 267.935); + + --color-indigo-50: oklch(96.2% 0.018 272.314); + --color-indigo-100: oklch(93% 0.034 272.788); + --color-indigo-200: oklch(87% 0.065 274.039); + --color-indigo-300: oklch(78.5% 0.115 274.713); + --color-indigo-400: oklch(67.3% 0.182 276.935); + --color-indigo-500: oklch(58.5% 0.233 277.117); + --color-indigo-600: oklch(51.1% 0.262 276.966); + --color-indigo-700: oklch(45.7% 0.24 277.023); + --color-indigo-800: oklch(39.8% 0.195 277.366); + --color-indigo-900: oklch(35.9% 0.144 278.697); + --color-indigo-950: oklch(25.7% 0.09 281.288); + + --color-violet-50: oklch(96.9% 0.016 293.756); + --color-violet-100: oklch(94.3% 0.029 294.588); + --color-violet-200: oklch(89.4% 0.057 293.283); + --color-violet-300: oklch(81.1% 0.111 293.571); + --color-violet-400: oklch(70.2% 0.183 293.541); + --color-violet-500: oklch(60.6% 0.25 292.717); + --color-violet-600: oklch(54.1% 0.281 293.009); + --color-violet-700: oklch(49.1% 0.27 292.581); + --color-violet-800: oklch(43.2% 0.232 292.759); + --color-violet-900: oklch(38% 0.189 293.745); + --color-violet-950: oklch(28.3% 0.141 291.089); + + --color-purple-50: oklch(97.7% 0.014 308.299); + --color-purple-100: oklch(94.6% 0.033 307.174); + --color-purple-200: oklch(90.2% 0.063 306.703); + --color-purple-300: oklch(82.7% 0.119 306.383); + --color-purple-400: oklch(71.4% 0.203 305.504); + --color-purple-500: oklch(62.7% 0.265 303.9); + --color-purple-600: oklch(55.8% 0.288 302.321); + --color-purple-700: oklch(49.6% 0.265 301.924); + --color-purple-800: oklch(43.8% 0.218 303.724); + --color-purple-900: oklch(38.1% 0.176 304.987); + --color-purple-950: oklch(29.1% 0.149 302.717); + + --color-fuchsia-50: oklch(97.7% 0.017 320.058); + --color-fuchsia-100: oklch(95.2% 0.037 318.852); + --color-fuchsia-200: oklch(90.3% 0.076 319.62); + --color-fuchsia-300: oklch(83.3% 0.145 321.434); + --color-fuchsia-400: oklch(74% 0.238 322.16); + --color-fuchsia-500: oklch(66.7% 0.295 322.15); + --color-fuchsia-600: oklch(59.1% 0.293 322.896); + --color-fuchsia-700: oklch(51.8% 0.253 323.949); + --color-fuchsia-800: oklch(45.2% 0.211 324.591); + --color-fuchsia-900: oklch(40.1% 0.17 325.612); + --color-fuchsia-950: oklch(29.3% 0.136 325.661); + + --color-pink-50: oklch(97.1% 0.014 343.198); + --color-pink-100: oklch(94.8% 0.028 342.258); + --color-pink-200: oklch(89.9% 0.061 343.231); + --color-pink-300: oklch(82.3% 0.12 346.018); + --color-pink-400: oklch(71.8% 0.202 349.761); + --color-pink-500: oklch(65.6% 0.241 354.308); + --color-pink-600: oklch(59.2% 0.249 0.584); + --color-pink-700: oklch(52.5% 0.223 3.958); + --color-pink-800: oklch(45.9% 0.187 3.815); + --color-pink-900: oklch(40.8% 0.153 2.432); + --color-pink-950: oklch(28.4% 0.109 3.907); + + --color-rose-50: oklch(96.9% 0.015 12.422); + --color-rose-100: oklch(94.1% 0.03 12.58); + --color-rose-200: oklch(89.2% 0.058 10.001); + --color-rose-300: oklch(81% 0.117 11.638); + --color-rose-400: oklch(71.2% 0.194 13.428); + --color-rose-500: oklch(64.5% 0.246 16.439); + --color-rose-600: oklch(58.6% 0.253 17.585); + --color-rose-700: oklch(51.4% 0.222 16.935); + --color-rose-800: oklch(45.5% 0.188 13.697); + --color-rose-900: oklch(41% 0.159 10.272); + --color-rose-950: oklch(27.1% 0.105 12.094); + + --color-slate-50: oklch(98.4% 0.003 247.858); + --color-slate-100: oklch(96.8% 0.007 247.896); + --color-slate-200: oklch(92.9% 0.013 255.508); + --color-slate-300: oklch(86.9% 0.022 252.894); + --color-slate-400: oklch(70.4% 0.04 256.788); + --color-slate-500: oklch(55.4% 0.046 257.417); + --color-slate-600: oklch(44.6% 0.043 257.281); + --color-slate-700: oklch(37.2% 0.044 257.287); + --color-slate-800: oklch(27.9% 0.041 260.031); + --color-slate-900: oklch(20.8% 0.042 265.755); + --color-slate-950: oklch(12.9% 0.042 264.695); + + --color-gray-50: oklch(98.5% 0.002 247.839); + --color-gray-100: oklch(96.7% 0.003 264.542); + --color-gray-200: oklch(92.8% 0.006 264.531); + --color-gray-300: oklch(87.2% 0.01 258.338); + --color-gray-400: oklch(70.7% 0.022 261.325); + --color-gray-500: oklch(55.1% 0.027 264.364); + --color-gray-600: oklch(44.6% 0.03 256.802); + --color-gray-700: oklch(37.3% 0.034 259.733); + --color-gray-800: oklch(27.8% 0.033 256.848); + --color-gray-900: oklch(21% 0.034 264.665); + --color-gray-950: oklch(13% 0.028 261.692); + + --color-zinc-50: oklch(98.5% 0 none); + --color-zinc-100: oklch(96.7% 0.001 286.375); + --color-zinc-200: oklch(92% 0.004 286.32); + --color-zinc-300: oklch(87.1% 0.006 286.286); + --color-zinc-400: oklch(70.5% 0.015 286.067); + --color-zinc-500: oklch(55.2% 0.016 285.938); + --color-zinc-600: oklch(44.2% 0.017 285.786); + --color-zinc-700: oklch(37% 0.013 285.805); + --color-zinc-800: oklch(27.4% 0.006 286.033); + --color-zinc-900: oklch(21% 0.006 285.885); + --color-zinc-950: oklch(14.1% 0.005 285.823); + + --color-neutral-50: oklch(98.5% 0 none); + --color-neutral-100: oklch(97% 0 none); + --color-neutral-200: oklch(92.2% 0 none); + --color-neutral-300: oklch(87% 0 none); + --color-neutral-400: oklch(70.8% 0 none); + --color-neutral-500: oklch(55.6% 0 none); + --color-neutral-600: oklch(43.9% 0 none); + --color-neutral-700: oklch(37.1% 0 none); + --color-neutral-800: oklch(26.9% 0 none); + --color-neutral-900: oklch(20.5% 0 none); + --color-neutral-950: oklch(14.5% 0 none); + + --color-stone-50: oklch(98.5% 0.001 106.423); + --color-stone-100: oklch(97% 0.001 106.424); + --color-stone-200: oklch(92.3% 0.003 48.717); + --color-stone-300: oklch(86.9% 0.005 56.366); + --color-stone-400: oklch(70.9% 0.01 56.259); + --color-stone-500: oklch(55.3% 0.013 58.071); + --color-stone-600: oklch(44.4% 0.011 73.639); + --color-stone-700: oklch(37.4% 0.01 67.558); + --color-stone-800: oklch(26.8% 0.007 34.298); + --color-stone-900: oklch(21.6% 0.006 56.043); + --color-stone-950: oklch(14.7% 0.004 49.25); + + --color-mauve-50: oklch(98.5% 0 none); + --color-mauve-100: oklch(96% 0.003 325.6); + --color-mauve-200: oklch(92.2% 0.005 325.62); + --color-mauve-300: oklch(86.5% 0.012 325.68); + --color-mauve-400: oklch(71.1% 0.019 323.02); + --color-mauve-500: oklch(54.2% 0.034 322.5); + --color-mauve-600: oklch(43.5% 0.029 321.78); + --color-mauve-700: oklch(36.4% 0.029 323.89); + --color-mauve-800: oklch(26.3% 0.024 320.12); + --color-mauve-900: oklch(21.2% 0.019 322.12); + --color-mauve-950: oklch(14.5% 0.008 326); + + --color-olive-50: oklch(98.8% 0.003 106.5); + --color-olive-100: oklch(96.6% 0.005 106.5); + --color-olive-200: oklch(93% 0.007 106.5); + --color-olive-300: oklch(88% 0.011 106.6); + --color-olive-400: oklch(73.7% 0.021 106.9); + --color-olive-500: oklch(58% 0.031 107.3); + --color-olive-600: oklch(46.6% 0.025 107.3); + --color-olive-700: oklch(39.4% 0.023 107.4); + --color-olive-800: oklch(28.6% 0.016 107.4); + --color-olive-900: oklch(22.8% 0.013 107.4); + --color-olive-950: oklch(15.3% 0.006 107.1); + + --color-mist-50: oklch(98.7% 0.002 197.1); + --color-mist-100: oklch(96.3% 0.002 197.1); + --color-mist-200: oklch(92.5% 0.005 214.3); + --color-mist-300: oklch(87.2% 0.007 219.6); + --color-mist-400: oklch(72.3% 0.014 214.4); + --color-mist-500: oklch(56% 0.021 213.5); + --color-mist-600: oklch(45% 0.017 213.2); + --color-mist-700: oklch(37.8% 0.015 216); + --color-mist-800: oklch(27.5% 0.011 216.9); + --color-mist-900: oklch(21.8% 0.008 223.9); + --color-mist-950: oklch(14.8% 0.004 228.8); + + --color-taupe-50: oklch(98.6% 0.002 67.8); + --color-taupe-100: oklch(96% 0.002 17.2); + --color-taupe-200: oklch(92.2% 0.005 34.3); + --color-taupe-300: oklch(86.8% 0.007 39.5); + --color-taupe-400: oklch(71.4% 0.014 41.2); + --color-taupe-500: oklch(54.7% 0.021 43.1); + --color-taupe-600: oklch(43.8% 0.017 39.3); + --color-taupe-700: oklch(36.7% 0.016 35.7); + --color-taupe-800: oklch(26.8% 0.011 36.5); + --color-taupe-900: oklch(21.4% 0.009 43.1); + --color-taupe-950: oklch(14.7% 0.004 49.3); + + --color-black: #000; + --color-white: #fff; + + --spacing: 0.25rem; + + --breakpoint-sm: 40rem; + --breakpoint-md: 48rem; + --breakpoint-lg: 64rem; + --breakpoint-xl: 80rem; + --breakpoint-2xl: 96rem; + + --container-3xs: 16rem; + --container-2xs: 18rem; + --container-xs: 20rem; + --container-sm: 24rem; + --container-md: 28rem; + --container-lg: 32rem; + --container-xl: 36rem; + --container-2xl: 42rem; + --container-3xl: 48rem; + --container-4xl: 56rem; + --container-5xl: 64rem; + --container-6xl: 72rem; + --container-7xl: 80rem; + + --text-xs: 0.75rem; + --text-xs--line-height: calc(1 / 0.75); + --text-sm: 0.875rem; + --text-sm--line-height: calc(1.25 / 0.875); + --text-base: 1rem; + --text-base--line-height: calc(1.5 / 1); + --text-lg: 1.125rem; + --text-lg--line-height: calc(1.75 / 1.125); + --text-xl: 1.25rem; + --text-xl--line-height: calc(1.75 / 1.25); + --text-2xl: 1.5rem; + --text-2xl--line-height: calc(2 / 1.5); + --text-3xl: 1.875rem; + --text-3xl--line-height: calc(2.25 / 1.875); + --text-4xl: 2.25rem; + --text-4xl--line-height: calc(2.5 / 2.25); + --text-5xl: 3rem; + --text-5xl--line-height: 1; + --text-6xl: 3.75rem; + --text-6xl--line-height: 1; + --text-7xl: 4.5rem; + --text-7xl--line-height: 1; + --text-8xl: 6rem; + --text-8xl--line-height: 1; + --text-9xl: 8rem; + --text-9xl--line-height: 1; + + --font-weight-thin: 100; + --font-weight-extralight: 200; + --font-weight-light: 300; + --font-weight-normal: 400; + --font-weight-medium: 500; + --font-weight-semibold: 600; + --font-weight-bold: 700; + --font-weight-extrabold: 800; + --font-weight-black: 900; + + --tracking-tighter: -0.05em; + --tracking-tight: -0.025em; + --tracking-normal: 0em; + --tracking-wide: 0.025em; + --tracking-wider: 0.05em; + --tracking-widest: 0.1em; + + --leading-tight: 1.25; + --leading-snug: 1.375; + --leading-normal: 1.5; + --leading-relaxed: 1.625; + --leading-loose: 2; + + --radius-xs: 0.125rem; + --radius-sm: 0.25rem; + --radius-md: 0.375rem; + --radius-lg: 0.5rem; + --radius-xl: 0.75rem; + --radius-2xl: 1rem; + --radius-3xl: 1.5rem; + --radius-4xl: 2rem; + + --shadow-2xs: 0 1px rgb(0 0 0 / 0.05); + --shadow-xs: 0 1px 2px 0 rgb(0 0 0 / 0.05); + --shadow-sm: 0 1px 3px 0 rgb(0 0 0 / 0.1), 0 1px 2px -1px rgb(0 0 0 / 0.1); + --shadow-md: 0 4px 6px -1px rgb(0 0 0 / 0.1), 0 2px 4px -2px rgb(0 0 0 / 0.1); + --shadow-lg: 0 10px 15px -3px rgb(0 0 0 / 0.1), 0 4px 6px -4px rgb(0 0 0 / 0.1); + --shadow-xl: 0 20px 25px -5px rgb(0 0 0 / 0.1), 0 8px 10px -6px rgb(0 0 0 / 0.1); + --shadow-2xl: 0 25px 50px -12px rgb(0 0 0 / 0.25); + + --inset-shadow-2xs: inset 0 1px rgb(0 0 0 / 0.05); + --inset-shadow-xs: inset 0 1px 1px rgb(0 0 0 / 0.05); + --inset-shadow-sm: inset 0 2px 4px rgb(0 0 0 / 0.05); + + --drop-shadow-xs: 0 1px 1px rgb(0 0 0 / 0.05); + --drop-shadow-sm: 0 1px 2px rgb(0 0 0 / 0.15); + --drop-shadow-md: 0 3px 3px rgb(0 0 0 / 0.12); + --drop-shadow-lg: 0 4px 4px rgb(0 0 0 / 0.15); + --drop-shadow-xl: 0 9px 7px rgb(0 0 0 / 0.1); + --drop-shadow-2xl: 0 25px 25px rgb(0 0 0 / 0.15); + + --text-shadow-2xs: 0px 1px 0px rgb(0 0 0 / 0.15); + --text-shadow-xs: 0px 1px 1px rgb(0 0 0 / 0.2); + --text-shadow-sm: + 0px 1px 0px rgb(0 0 0 / 0.075), 0px 1px 1px rgb(0 0 0 / 0.075), 0px 2px 2px rgb(0 0 0 / 0.075); + --text-shadow-md: + 0px 1px 1px rgb(0 0 0 / 0.1), 0px 1px 2px rgb(0 0 0 / 0.1), 0px 2px 4px rgb(0 0 0 / 0.1); + --text-shadow-lg: + 0px 1px 2px rgb(0 0 0 / 0.1), 0px 3px 2px rgb(0 0 0 / 0.1), 0px 4px 8px rgb(0 0 0 / 0.1); + + --ease-in: cubic-bezier(0.4, 0, 1, 1); + --ease-out: cubic-bezier(0, 0, 0.2, 1); + --ease-in-out: cubic-bezier(0.4, 0, 0.2, 1); + + --animate-spin: spin 1s linear infinite; + --animate-ping: ping 1s cubic-bezier(0, 0, 0.2, 1) infinite; + --animate-pulse: pulse 2s cubic-bezier(0.4, 0, 0.6, 1) infinite; + --animate-bounce: bounce 1s infinite; + + @keyframes spin { + to { + transform: rotate(360deg); + } + } + + @keyframes ping { + 75%, + 100% { + transform: scale(2); + opacity: 0; + } + } + + @keyframes pulse { + 50% { + opacity: 0.5; + } + } + + @keyframes bounce { + 0%, + 100% { + transform: translateY(-25%); + animation-timing-function: cubic-bezier(0.8, 0, 1, 1); + } + + 50% { + transform: none; + animation-timing-function: cubic-bezier(0, 0, 0.2, 1); + } + } + + --blur-xs: 4px; + --blur-sm: 8px; + --blur-md: 12px; + --blur-lg: 16px; + --blur-xl: 24px; + --blur-2xl: 40px; + --blur-3xl: 64px; + + --perspective-dramatic: 100px; + --perspective-near: 300px; + --perspective-normal: 500px; + --perspective-midrange: 800px; + --perspective-distant: 1200px; + + --aspect-video: 16 / 9; + + --default-transition-duration: 150ms; + --default-transition-timing-function: cubic-bezier(0.4, 0, 0.2, 1); + --default-font-family: --theme(--font-sans, initial); + --default-font-feature-settings: --theme(--font-sans--font-feature-settings, initial); + --default-font-variation-settings: --theme(--font-sans--font-variation-settings, initial); + --default-mono-font-family: --theme(--font-mono, initial); + --default-mono-font-feature-settings: --theme(--font-mono--font-feature-settings, initial); + --default-mono-font-variation-settings: --theme(--font-mono--font-variation-settings, initial); +} + +/* Deprecated */ +@theme default inline reference { + --blur: 8px; + --shadow: 0 1px 3px 0 rgb(0 0 0 / 0.1), 0 1px 2px -1px rgb(0 0 0 / 0.1); + --shadow-inner: inset 0 2px 4px 0 rgb(0 0 0 / 0.05); + --drop-shadow: 0 1px 2px rgb(0 0 0 / 0.1), 0 1px 1px rgb(0 0 0 / 0.06); + --radius: 0.25rem; + --max-width-prose: 65ch; +} diff --git a/dg-ui/node_modules/tailwindcss/utilities.css b/dg-ui/node_modules/tailwindcss/utilities.css new file mode 100644 index 0000000..65dd5f6 --- /dev/null +++ b/dg-ui/node_modules/tailwindcss/utilities.css @@ -0,0 +1 @@ +@tailwind utilities; diff --git a/dg-ui/node_modules/tapable/LICENSE b/dg-ui/node_modules/tapable/LICENSE new file mode 100644 index 0000000..03c083c --- /dev/null +++ b/dg-ui/node_modules/tapable/LICENSE @@ -0,0 +1,21 @@ +The MIT License + +Copyright JS Foundation and other contributors + +Permission is hereby granted, free of charge, to any person obtaining a copy +of this software and associated documentation files (the "Software"), to deal +in the Software without restriction, including without limitation the rights +to use, copy, modify, merge, publish, distribute, sublicense, and/or sell +copies of the Software, and to permit persons to whom the Software is +furnished to do so, subject to the following conditions: + +The above copyright notice and this permission notice shall be included in +all copies or substantial portions of the Software. + +THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR +IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, +FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE +AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER +LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, +OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN +THE SOFTWARE. diff --git a/dg-ui/node_modules/tapable/README.md b/dg-ui/node_modules/tapable/README.md new file mode 100644 index 0000000..1415a31 --- /dev/null +++ b/dg-ui/node_modules/tapable/README.md @@ -0,0 +1,715 @@ +# Tapable + +The tapable package exposes many Hook classes, which can be used to create hooks for plugins. + +```javascript +const { + AsyncParallelBailHook, + AsyncParallelHook, + AsyncSeriesBailHook, + AsyncSeriesHook, + AsyncSeriesWaterfallHook, + SyncBailHook, + SyncHook, + SyncLoopHook, + SyncWaterfallHook +} = require("tapable"); +``` + +## Installation + +```shell +npm install --save tapable +``` + +## Usage + +All Hook constructors take one optional argument, which is a list of argument names as strings. + +```js +const hook = new SyncHook(["arg1", "arg2", "arg3"]); +``` + +The best practice is to expose all hooks of a class in a `hooks` property: + +```js +class Car { + constructor() { + this.hooks = { + accelerate: new SyncHook(["newSpeed"]), + brake: new SyncHook(), + calculateRoutes: new AsyncParallelHook(["source", "target", "routesList"]) + }; + } + + /* ... */ +} +``` + +Other people can now use these hooks: + +```js +const myCar = new Car(); + +// Use the tap method to add a consumer (plugin) +myCar.hooks.brake.tap("WarningLampPlugin", () => warningLamp.on()); +``` + +It's required to pass a name to identify the plugin/reason. + +You may receive arguments: + +```js +myCar.hooks.accelerate.tap("LoggerPlugin", (newSpeed) => + console.log(`Accelerating to ${newSpeed}`) +); +``` + +For sync hooks, `tap` is the only valid method to add a plugin. Async hooks also support async plugins: + +```js +myCar.hooks.calculateRoutes.tapPromise( + "GoogleMapsPlugin", + (source, target, routesList) => + // return a promise + google.maps.findRoute(source, target).then((route) => { + routesList.add(route); + }) +); +myCar.hooks.calculateRoutes.tapAsync( + "BingMapsPlugin", + (source, target, routesList, callback) => { + bing.findRoute(source, target, (err, route) => { + if (err) return callback(err); + routesList.add(route); + // call the callback + callback(); + }); + } +); + +// You can still use sync plugins +myCar.hooks.calculateRoutes.tap( + "CachedRoutesPlugin", + (source, target, routesList) => { + const cachedRoute = cache.get(source, target); + if (cachedRoute) routesList.add(cachedRoute); + } +); +``` + +The class declaring these hooks needs to call them: + +```js +class Car { + /** + * You won't get returned value from SyncHook or AsyncParallelHook, + * to do that, use SyncWaterfallHook and AsyncSeriesWaterfallHook respectively + */ + + setSpeed(newSpeed) { + // following call returns undefined even when you returned values + this.hooks.accelerate.call(newSpeed); + } + + useNavigationSystemPromise(source, target) { + const routesList = new List(); + return this.hooks.calculateRoutes + .promise(source, target, routesList) + .then((res) => + // res is undefined for AsyncParallelHook + routesList.getRoutes() + ); + } + + useNavigationSystemAsync(source, target, callback) { + const routesList = new List(); + this.hooks.calculateRoutes.callAsync(source, target, routesList, (err) => { + if (err) return callback(err); + callback(null, routesList.getRoutes()); + }); + } +} +``` + +The Hook will compile a method with the most efficient way of running your plugins. It generates code depending on: + +- The number of registered plugins (none, one, many) +- The kind of registered plugins (sync, async, promise) +- The used call method (sync, async, promise) +- The number of arguments +- Whether interception is used + +This ensures fastest possible execution. See [Code generation](#code-generation) for more details on the runtime compilation. + +## Plugin API + +A plugin registers a callback on a hook using one of the `tap*` methods. The hook type determines which of these are valid (see [Hook classes](#hook-classes)): + +- `hook.tap(nameOrOptions, fn)` — register a synchronous callback. +- `hook.tapAsync(nameOrOptions, fn)` — register a callback-based async callback. The last argument passed to `fn` is a node-style callback `(err, result)`. +- `hook.tapPromise(nameOrOptions, fn)` — register a promise-returning async callback. If `fn` returns something that is not thenable, the hook throws. + +The first argument can be either a string (the plugin name) or an options object that also allows influencing the order in which taps run: + +```js +hook.tap( + { + name: "MyPlugin", + stage: -10, // lower stages run earlier, default is 0 + before: "OtherPlugin" // run before a named tap (string or string[]) + }, + (...args) => { + /* ... */ + } +); +``` + +| Option | Type | Description | +| -------- | ---------------------- | ------------------------------------------------------------------------------------------------------------------------------------------------------------------------------ | +| `name` | `string` | Required. Identifies the tap for debugging, interceptors, and the `before` option. | +| `stage` | `number` | Defaults to `0`. Taps with a lower stage run before taps with a higher stage. Taps with the same stage run in registration order. | +| `before` | `string` \| `string[]` | The tap is inserted before the named tap(s). Unknown names are ignored. Combined with `stage`, `before` wins for the taps it targets; other taps are still ordered by `stage`. | + +The `name` is also used by some ecosystems (like webpack) for profiling and error messages. Within a single tap registration, later interceptors' `register` hooks may still replace the tap object (see [Interception](#interception)). + +### `hook.withOptions(options)` + +`withOptions` returns a facade around the hook whose `tap*` methods automatically merge `options` into every registration. It is useful for libraries that want to pre-configure a `stage` or `before` for all the taps they add: + +```js +const lateHook = myCar.hooks.accelerate.withOptions({ stage: 10 }); +lateHook.tap("LogAfterOthers", (speed) => console.log("final speed", speed)); +// equivalent to: myCar.hooks.accelerate.tap({ name: "LogAfterOthers", stage: 10 }, ...) +``` + +The returned object does not expose the `call*` methods, so it is safe to hand out to plugins. + +A runnable example showing how `withOptions` influences tap ordering: + +```js +const { SyncHook } = require("tapable"); + +const hook = new SyncHook(["value"]); + +hook.tap("Default", (v) => console.log("default", v)); + +// Pre-configure stage: 10 so all taps registered through `late` run last. +const late = hook.withOptions({ stage: 10 }); +late.tap("RunLast", (v) => console.log("last", v)); + +// Pre-configure stage: -10 so these taps run first. Each facade can also +// be further narrowed via `withOptions`. +const early = hook.withOptions({ stage: -10 }); +early.tap("RunFirst", (v) => console.log("first", v)); + +hook.call(1); +// first 1 +// default 1 +// last 1 +``` + +Per-tap options override values from `withOptions`. For example, `late.tap({ name: "Override", stage: 0 }, fn)` ignores the facade's `stage: 10` and registers `fn` at stage `0`. + +## Hook types + +Each hook can be tapped with one or several functions. How they are executed depends on the hook type: + +- Basic hook (without “Waterfall”, “Bail” or “Loop” in its name). This hook simply calls every function it tapped in a row. + +- **Waterfall**. A waterfall hook also calls each tapped function in a row. Unlike the basic hook, it passes a return value from each function to the next function. + +- **Bail**. A bail hook allows exiting early. When any of the tapped function returns anything, the bail hook will stop executing the remaining ones. + +- **Loop**. When a plugin in a loop hook returns a non-undefined value the hook will restart from the first plugin. It will loop until all plugins return undefined. + +Additionally, hooks can be synchronous or asynchronous. To reflect this, there’re “Sync”, “AsyncSeries”, and “AsyncParallel” hook classes: + +- **Sync**. A sync hook can only be tapped with synchronous functions (using `myHook.tap()`). + +- **AsyncSeries**. An async-series hook can be tapped with synchronous, callback-based and promise-based functions (using `myHook.tap()`, `myHook.tapAsync()` and `myHook.tapPromise()`). They call each async method in a row. + +- **AsyncParallel**. An async-parallel hook can also be tapped with synchronous, callback-based and promise-based functions (using `myHook.tap()`, `myHook.tapAsync()` and `myHook.tapPromise()`). However, they run each async method in parallel. + +The hook type is reflected in its class name. E.g., `AsyncSeriesWaterfallHook` allows asynchronous functions and runs them in series, passing each function’s return value into the next function. + +## Hook classes + +The table below summarizes the 9 built-in hook classes. For each class: + +- **Tap methods** are the `tapX` variants that may be used to register a handler. +- **Call methods** are the ways the owner of the hook can trigger it. +- **Result** is the value returned from `call` (or passed to the `callAsync` callback / resolved from the `promise` call). +- **Returned value from tap** describes whether the value returned from a tapped function has an effect. + +| Class | Tap methods | Call methods | Result | Returned value from tap | +| -------------------------- | ------------------------------- | ---------------------- | ----------------------------------------------- | ---------------------------------------------------- | +| `SyncHook` | `tap` | `call` | `undefined` | ignored | +| `SyncBailHook` | `tap` | `call` | first non-`undefined` value, or `undefined` | short-circuits the hook | +| `SyncWaterfallHook` | `tap` | `call` | final value (first argument after the last tap) | passed as first argument to the next tap | +| `SyncLoopHook` | `tap` | `call` | `undefined` | non-`undefined` restarts the loop from the first tap | +| `AsyncParallelHook` | `tap`, `tapAsync`, `tapPromise` | `callAsync`, `promise` | `undefined` | ignored | +| `AsyncParallelBailHook` | `tap`, `tapAsync`, `tapPromise` | `callAsync`, `promise` | first non-`undefined` value, or `undefined` | short-circuits the hook | +| `AsyncSeriesHook` | `tap`, `tapAsync`, `tapPromise` | `callAsync`, `promise` | `undefined` | ignored | +| `AsyncSeriesBailHook` | `tap`, `tapAsync`, `tapPromise` | `callAsync`, `promise` | first non-`undefined` value, or `undefined` | short-circuits the hook | +| `AsyncSeriesLoopHook` | `tap`, `tapAsync`, `tapPromise` | `callAsync`, `promise` | `undefined` | non-`undefined` restarts the loop from the first tap | +| `AsyncSeriesWaterfallHook` | `tap`, `tapAsync`, `tapPromise` | `callAsync`, `promise` | final value (first argument after the last tap) | passed as first argument to the next tap | + +Detailed behavior of each class: + +### SyncHook + +A basic synchronous hook. Every tapped function is called in registration order with the arguments passed to `call`. Return values from tapped functions are ignored and `call` returns `undefined`. + +- Tap methods: `tap` +- Call methods: `call` +- `tapAsync` and `tapPromise` throw an error. + +```js +const hook = new SyncHook(["name"]); +hook.tap("A", (name) => console.log(`hello ${name}`)); +hook.tap("B", (name) => console.log(`hi ${name}`)); +hook.call("world"); +// hello world +// hi world +``` + +### SyncBailHook + +A synchronous hook that allows exiting early. Every tapped function is called in order until one returns a non-`undefined` value; that value becomes the result of `call` and the remaining taps are skipped. If all taps return `undefined`, `call` returns `undefined`. + +- Tap methods: `tap` +- Call methods: `call` + +```js +const hook = new SyncBailHook(["value"]); +hook.tap("Negative", (v) => (v < 0 ? "negative" : undefined)); +hook.tap("Zero", (v) => (v === 0 ? "zero" : undefined)); +hook.tap("Positive", (v) => "positive"); + +hook.call(-1); // "negative" (later taps skipped) +hook.call(5); // "positive" +``` + +### SyncWaterfallHook + +A synchronous hook that threads a value through its tapped functions. The first argument passed to `call` is forwarded to the first tap. If a tap returns a non-`undefined` value it replaces that argument for the next tap; otherwise the previous value is kept. `call` returns the value after the last tap has run. Additional arguments (if any) are passed through unchanged. + +- Tap methods: `tap` +- Call methods: `call` + +```js +const hook = new SyncWaterfallHook(["value"]); +hook.tap("Double", (v) => v * 2); +hook.tap("PlusOne", (v) => v + 1); + +hook.call(3); // 7 -> (3 * 2) + 1 +``` + +### SyncLoopHook + +A synchronous hook that keeps re-running its taps until all of them return `undefined` for a full pass. Whenever a tap returns a non-`undefined` value the hook restarts from the first tap. `call` returns `undefined`. + +- Tap methods: `tap` +- Call methods: `call` + +```js +const hook = new SyncLoopHook(["state"]); +let retries = 3; +hook.tap("Retry", () => { + if (retries-- > 0) return true; // non-undefined restarts the loop +}); +hook.tap("Log", () => console.log("pass")); + +hook.call({}); +// pass (runs once all taps return undefined) +``` + +### AsyncParallelHook + +An asynchronous hook that runs all of its tapped functions in parallel. It completes when every tap has signalled completion (sync return, callback, or promise resolution). Return values and resolution values are ignored; `callAsync`'s callback is invoked with no result and `promise()` resolves to `undefined`. If any tap errors, the error is forwarded and remaining taps still complete but their results are discarded. + +- Tap methods: `tap`, `tapAsync`, `tapPromise` +- Call methods: `callAsync`, `promise` + +```js +const hook = new AsyncParallelHook(["source"]); +hook.tapPromise("Fetch", (src) => fetch(src)); +hook.tapAsync("Log", (src, cb) => { + console.log("fetching", src); + cb(); +}); + +await hook.promise("https://example.com"); +``` + +### AsyncParallelBailHook + +Like `AsyncParallelHook`, but designed to bail out with a result. All tapped functions start in parallel; the first tap to produce a non-`undefined` value (synchronously, via its callback, or by resolving its promise) determines the hook’s result. The remaining taps continue to run but their results are ignored. Order is determined by tap registration order: an earlier tap’s value takes precedence over a later one’s, even if the later one finishes first. + +- Tap methods: `tap`, `tapAsync`, `tapPromise` +- Call methods: `callAsync`, `promise` + +```js +const hook = new AsyncParallelBailHook(["key"]); +hook.tapPromise("Cache", async (key) => cache.get(key)); +hook.tapPromise("Db", async (key) => db.lookup(key)); + +const value = await hook.promise("user:42"); +// First non-undefined result (by registration order) wins. +``` + +### AsyncSeriesHook + +An asynchronous hook that runs tapped functions one after another, waiting for each to finish before starting the next. Results are ignored; `callAsync`'s callback is invoked with no result and `promise()` resolves to `undefined`. The first error aborts the series. + +- Tap methods: `tap`, `tapAsync`, `tapPromise` +- Call methods: `callAsync`, `promise` + +```js +const hook = new AsyncSeriesHook(["request"]); +hook.tapPromise("Authenticate", async (req) => authenticate(req)); +hook.tapPromise("Log", async (req) => logger.info(req.url)); + +await hook.promise(request); +``` + +### AsyncSeriesBailHook + +An asynchronous series hook that allows exiting early. Tapped functions run one after another; as soon as one produces a non-`undefined` value, that value becomes the hook’s result and the remaining taps are skipped. + +- Tap methods: `tap`, `tapAsync`, `tapPromise` +- Call methods: `callAsync`, `promise` + +```js +const hook = new AsyncSeriesBailHook(["id"]); +hook.tapPromise("Memory", async (id) => memory.get(id)); +hook.tapPromise("Disk", async (id) => disk.read(id)); + +const value = await hook.promise("doc-1"); +// Stops at the first tap that produces a value. +``` + +### AsyncSeriesLoopHook + +An asynchronous series hook that loops. Tapped functions run one after another; whenever a tap produces a non-`undefined` value the hook restarts from the first tap. The hook completes once a full pass yields `undefined` from every tap. The result is always `undefined`. + +- Tap methods: `tap`, `tapAsync`, `tapPromise` +- Call methods: `callAsync`, `promise` + +```js +const hook = new AsyncSeriesLoopHook(["job"]); +hook.tapPromise("Process", async (job) => { + const more = await job.step(); + if (more) return true; // restart the loop +}); + +await hook.promise(job); +``` + +### AsyncSeriesWaterfallHook + +An asynchronous series hook that threads a value through its taps. The first argument passed to `callAsync` / `promise` is forwarded to the first tap. A tap's non-`undefined` return / callback / resolution value replaces it for the next tap; `undefined` keeps the previous value. The hook completes with the value after the last tap. + +- Tap methods: `tap`, `tapAsync`, `tapPromise` +- Call methods: `callAsync`, `promise` + +```js +const hook = new AsyncSeriesWaterfallHook(["source"]); +hook.tapPromise("Read", async (src) => fs.readFile(src, "utf8")); +hook.tapPromise("Trim", async (text) => text.trim()); + +const output = await hook.promise("./input.txt"); +``` + +## Interception + +All hooks expose an `intercept(interceptor)` method. An interceptor is a plain object whose methods are invoked at specific points during the lifetime of the hook. Interceptors are invoked in registration order before the taps, and are useful for logging, tracing, profiling, or re-mapping tap options. + +```js +myCar.hooks.calculateRoutes.intercept({ + name: "LoggingInterceptor", + call: (source, target, routesList) => { + console.log("Starting to calculate routes"); + }, + tap: (tapInfo) => { + // tapInfo = { type: "promise", name: "GoogleMapsPlugin", fn: ..., stage: 0 } + console.log(`${tapInfo.name} is running`); + }, + register: (tapInfo) => { + // Called once per tap (and for each tap already registered when the + // interceptor is added). Return a new tapInfo object to replace it. + console.log(`${tapInfo.name} is registered`); + + return tapInfo; + } +}); +``` + +| Handler | Signature | When it runs | +| ---------- | -------------------------------- | ------------------------------------------------------------------------------------------------------------------------------------------ | +| `call` | `(...args) => void` | Before the hook starts executing its taps. Receives the arguments passed to `call` / `callAsync` / `promise`. | +| `tap` | `(tap: Tap) => void` | Before each tap runs. The `tap` object is a snapshot — mutations are ignored. | +| `loop` | `(...args) => void` | At the start of each iteration of a `SyncLoopHook` / `AsyncSeriesLoopHook`. | +| `error` | `(err: Error) => void` | Whenever a tap throws, rejects, or calls its callback with an error. | +| `result` | `(result: any) => void` | When a bail or waterfall hook produces a value, or when a tap produces one for a loop hook. | +| `done` | `() => void` | When the hook finishes successfully (no error, no early bail). | +| `register` | `(tap: Tap) => Tap \| undefined` | Once per tap at registration time (including taps that existed before the interceptor was added). Return a new `Tap` object to replace it. | +| `name` | `string` | Optional label used by ecosystems for debugging. | +| `context` | `boolean` | Opt into the shared `context` object. See [Context](#context). | + +Adding an interceptor invalidates the hook's compiled call function — the next `call` / `callAsync` / `promise` recompiles it so that the new interceptor is woven in. + +## Context + +Plugins and interceptors can opt-in to access an optional `context` object, which can be used to pass arbitrary values to subsequent plugins and interceptors. + +```js +myCar.hooks.accelerate.intercept({ + context: true, + tap: (context, tapInfo) => { + // tapInfo = { type: "sync", name: "NoisePlugin", fn: ... } + console.log(`${tapInfo.name} is doing it's job`); + + // `context` starts as an empty object if at least one plugin uses `context: true`. + // If no plugins use `context: true`, then `context` is undefined. + if (context) { + // Arbitrary properties can be added to `context`, which plugins can then access. + context.hasMuffler = true; + } + } +}); + +myCar.hooks.accelerate.tap( + { + name: "NoisePlugin", + context: true + }, + (context, newSpeed) => { + if (context && context.hasMuffler) { + console.log("Silence..."); + } else { + console.log("Vroom!"); + } + } +); +``` + +## HookMap + +A `HookMap` is a helper class that lazily creates hooks per key. The constructor takes a factory function; the first time a key is requested via `for(key)`, the factory is called and the resulting hook is cached. + +```js +const keyedHook = new HookMap((key) => new SyncHook(["arg"])); +``` + +Plugins use `for(key)` to obtain the hook for a specific key (creating it on demand) and then `tap` on it as usual: + +```js +keyedHook.for("some-key").tap("MyPlugin", (arg) => { + /* ... */ +}); +keyedHook.for("some-key").tapAsync("MyPlugin", (arg, callback) => { + /* ... */ +}); +keyedHook.for("some-key").tapPromise("MyPlugin", (arg) => { + /* ... */ +}); +``` + +The owner of the `HookMap` uses `get(key)` to look up an existing hook without creating one. This is typically preferred on the calling side so that keys no plugin cares about are never materialized: + +```js +const hook = keyedHook.get("some-key"); +if (hook !== undefined) { + hook.callAsync("arg", (err) => { + /* ... */ + }); +} +``` + +A `HookMap` can also be intercepted. `intercept({ factory })` wraps the factory so you can customize or replace the hook returned for each new key. + +## Code generation + +Tapable does not iterate over taps at call time. Instead, the first time `call`, `callAsync` or `promise` is invoked after the hook has been modified, the hook compiles a specialized function using `new Function(...)` and caches it on the instance. This is what the README means by "evals in code": the hook's dispatch logic is generated as a string and turned into a real JavaScript function the engine can inline and optimize. + +The generated function is tailored to: + +- **Call type** — whether the owner called `call` (sync), `callAsync` (callback), or `promise`. Each produces a different skeleton — e.g. `promise()` wraps the body in `new Promise((_resolve, _reject) => { ... })`. +- **Tap types** — for each tap, the generator emits the right invocation pattern: direct call for `tap`, node-style callback wrapping for `tapAsync`, and `.then(...)` chaining for `tapPromise`. +- **Hook class** — `SyncHook` emits a straight-line sequence of calls; `SyncBailHook` emits early-return checks; `SyncWaterfallHook` threads a value through calls; loop hooks wrap the body in a re-entry loop; `AsyncParallel*` fans the taps out and counts completions; `AsyncSeries*` chains them. +- **Interceptors** — if interceptors are attached, calls to their `call`/`tap`/`loop`/`error`/`result`/`done` handlers are spliced into the generated body; otherwise they cost nothing. +- **Context** — a `_context` object is only created when at least one tap or interceptor opts into it with `context: true`. +- **Arity** — the generated code hard-codes the number of arguments declared when the hook was constructed, so no `arguments`/rest handling happens at runtime. + +The compiled function is invalidated (reset back to a one-shot "recompile then call" trampoline) whenever the hook's shape changes — i.e. on any new `tap*` or `intercept` call. Steady-state calls therefore run straight through the cached function with no per-tap branching. + +### Why this matters + +- You only pay for features you use. An interceptor-free, sync-only hook compiles down to a short sequence of direct function calls. +- Debugging a hook means reading the generated source. If you need to see it, `Hook.prototype.compile` returns the `new Function(...)` result — log `hook._createCall("sync").toString()` (or `"async"` / `"promise"`) to inspect the body. +- Because the dispatch is code-generated, a hook's behavior is fully determined at compile time. Mutating tap options after registration (for example, changing `stage` on an existing `Tap` object) will not reorder taps until you cause a recompile. + +## Hook/HookMap interface + +Public (callable by anyone holding a reference to the hook, i.e. the plugins): + +```ts +interface Hook { + tap: (name: string | Tap, fn: (context?, ...args) => Result) => void; + tapAsync: ( + name: string | Tap, + fn: ( + context?, + ...args, + callback: (err: Error | null, result: Result) => void + ) => void + ) => void; + tapPromise: ( + name: string | Tap, + fn: (context?, ...args) => Promise + ) => void; + intercept: (interceptor: HookInterceptor) => void; + withOptions: ( + options: TapOptions + ) => Omit; +} + +interface HookInterceptor { + name?: string; + call?: (context?, ...args) => void; + loop?: (context?, ...args) => void; + tap?: (context?, tap: Tap) => void; + error?: (err: Error) => void; + result?: (result: any) => void; + done?: () => void; + register?: (tap: Tap) => Tap | undefined; + context?: boolean; +} + +interface HookMap { + for: (key: any) => Hook; + intercept: (interceptor: HookMapInterceptor) => void; +} + +interface HookMapInterceptor { + factory: (key: any, hook: Hook) => Hook; +} + +interface Tap { + name: string; + type: "sync" | "async" | "promise"; + fn: Function; + stage: number; + context: boolean; + before?: string | Array; +} +``` + +Protected (only for the class containing the hook — it owns the right to trigger it): + +```ts +interface Hook { + isUsed: () => boolean; + call: (...args) => Result; + promise: (...args) => Promise; + callAsync: ( + ...args, + callback: (err: Error | null, result: Result) => void + ) => void; +} + +interface HookMap { + get: (key: any) => Hook | undefined; + for: (key: any) => Hook; +} +``` + +`isUsed()` returns `true` when the hook has at least one tap or interceptor registered. Hook owners can use it to skip expensive argument preparation when no plugin is listening: + +```js +class Car { + // ... + setSpeed(newSpeed) { + if (this.hooks.accelerate.isUsed()) { + this.hooks.accelerate.call(newSpeed); + } + } + // ... +} +``` + +## MultiHook + +A `MultiHook` is a Hook-like facade that forwards `tap`, `tapAsync`, `tapPromise`, `intercept`, and `withOptions` to several underlying hooks at once. It does not expose `call*` methods — only the owners of the wrapped hooks decide when each of them runs. It is the typical way a class exposes a "happens on any of these events" listening surface without having the plugin wire itself up to every hook individually. + +### Fan out a tap to several hooks + +```js +const { MultiHook, SyncHook } = require("tapable"); + +class Car { + constructor() { + const accelerate = new SyncHook(["newSpeed"]); + const brake = new SyncHook(); + this.hooks = { + accelerate, + brake, + // `anyMovement` is not a real hook — it simply re-registers taps + // on both `accelerate` and `brake`. + anyMovement: new MultiHook([accelerate, brake]) + }; + } +} + +const car = new Car(); +car.hooks.anyMovement.tap("Telemetry", () => console.log("car moved")); + +car.hooks.accelerate.call(42); // "car moved" +car.hooks.brake.call(); // "car moved" +``` + +The `MultiHook` has no state of its own: the tap above ends up inside `accelerate.taps` and `brake.taps`. + +### Forwarding async taps + +`tapAsync` / `tapPromise` forward to every wrapped hook — it is the plugin's job to make sure they are all compatible. Registering a `tapPromise` on a `MultiHook` that wraps a `SyncHook` will throw at registration time for that hook. + +```js +const build = new AsyncSeriesHook(["stats"]); +const rebuild = new AsyncSeriesHook(["stats"]); +const anyBuild = new MultiHook([build, rebuild]); + +anyBuild.tapPromise("Report", async (stats) => report.send(stats)); +``` + +### Shared interceptors and options + +`intercept` and `withOptions` are also forwarded, so a `MultiHook` can be used to attach the same interceptor or pre-configured options to a group of hooks: + +```js +const anyBuild = new MultiHook([build, rebuild]); + +anyBuild.intercept({ + call: () => console.log("build started"), + done: () => console.log("build done") +}); + +// Every tap added through `late` is staged late on both underlying hooks. +const late = anyBuild.withOptions({ stage: 10 }); +late.tap("RunLast", () => { + /* ... */ +}); +``` + +### `isUsed` + +`isUsed()` returns `true` if any of the wrapped hooks has at least one tap or interceptor, which lets the owner cheaply skip work when no one is listening on any of them: + +```js +if (this.hooks.anyMovement.isUsed()) { + // expensive telemetry payload is only built when a plugin actually cares + this.hooks.accelerate.call(computeSpeed()); +} +``` diff --git a/dg-ui/node_modules/tapable/lib/AsyncParallelBailHook.js b/dg-ui/node_modules/tapable/lib/AsyncParallelBailHook.js new file mode 100644 index 0000000..d5f1bad --- /dev/null +++ b/dg-ui/node_modules/tapable/lib/AsyncParallelBailHook.js @@ -0,0 +1,140 @@ +/* + MIT License http://www.opensource.org/licenses/mit-license.php + Author Tobias Koppers @sokra +*/ +"use strict"; + +const Hook = require("./Hook"); +const HookCodeFactory = require("./HookCodeFactory"); + +/** @typedef {import("./Hook").EXPECTED_ANY} EXPECTED_ANY */ +/** @typedef {import("./Hook").EXPECTED_FUNCTION} EXPECTED_FUNCTION */ +/** @typedef {import("./Hook").UnsetAdditionalOptions} UnsetAdditionalOptions */ +/** @typedef {import("./Hook").CompileOptions} CompileOptions */ +/** @typedef {import("./HookCodeFactory").ContentOptions} ContentOptions */ +/** + * @template {EXPECTED_ANY[]} T + * @typedef {import("./Hook").ArgumentNames} ArgumentNames + */ +/** + * @template T + * @typedef {import("./Hook").AsArray} AsArray + */ + +/** + * Mirror of the `AsyncParallelBailHook` class declared in `tapable.d.ts` for + * use as the factory function's return type, so `new AsyncParallelBailHook(...)` + * resolves to the specific subclass type instead of the generic `Hook`. + * @template T + * @template R + * @template [AdditionalOptions=UnsetAdditionalOptions] + * @typedef {import("../tapable").AsyncParallelBailHook} AsyncParallelBailHookType + */ + +class AsyncParallelBailHookCodeFactory extends HookCodeFactory { + /** + * @param {ContentOptions} options content generation options + * @returns {string} generated body code + */ + content({ onError, onResult, onDone }) { + const opts = /** @type {CompileOptions} */ (this.options); + let code = ""; + code += `var _results = new Array(${opts.taps.length});\n`; + code += "var _checkDone = function() {\n"; + code += "for(var i = 0; i < _results.length; i++) {\n"; + code += "var item = _results[i];\n"; + code += "if(item === undefined) return false;\n"; + code += "if(item.result !== undefined) {\n"; + code += onResult("item.result"); + code += "return true;\n"; + code += "}\n"; + code += "if(item.error) {\n"; + code += onError("item.error"); + code += "return true;\n"; + code += "}\n"; + code += "}\n"; + code += "return false;\n"; + code += "}\n"; + code += this.callTapsParallel({ + onError: (i, err, done, doneBreak) => { + let code = ""; + code += `if(${i} < _results.length && ((_results.length = ${ + i + 1 + }), (_results[${i}] = { error: ${err} }), _checkDone())) {\n`; + code += doneBreak(true); + code += "} else {\n"; + code += done(); + code += "}\n"; + return code; + }, + onResult: (i, result, done, doneBreak) => { + let code = ""; + code += `if(${i} < _results.length && (${result} !== undefined && (_results.length = ${ + i + 1 + }), (_results[${i}] = { result: ${result} }), _checkDone())) {\n`; + code += doneBreak(true); + code += "} else {\n"; + code += done(); + code += "}\n"; + return code; + }, + onTap: (i, run, done, _doneBreak) => { + let code = ""; + if (i > 0) { + code += `if(${i} >= _results.length) {\n`; + code += done(); + code += "} else {\n"; + } + code += run(); + if (i > 0) code += "}\n"; + return code; + }, + onDone + }); + return code; + } +} + +const factory = new AsyncParallelBailHookCodeFactory(); + +/** + * @template T + * @template R + * @template [AdditionalOptions=UnsetAdditionalOptions] + * @this {Hook} + * @param {CompileOptions} options compile options + * @returns {EXPECTED_FUNCTION} the compiled call function + */ +function COMPILE(options) { + factory.setup(this, options); + return factory.create(options); +} + +/** + * @constructor + * @template T + * @template R + * @template [AdditionalOptions=UnsetAdditionalOptions] + * @param {ArgumentNames>=} args argument names of the hook + * @param {string=} name name of the hook + * @returns {AsyncParallelBailHookType} a new AsyncParallelBailHook instance + */ +function AsyncParallelBailHook( + args = /** @type {ArgumentNames>} */ (/** @type {unknown} */ ([])), + name = undefined +) { + const hook = new Hook(args, name); + hook.constructor = AsyncParallelBailHook; + hook.compile = COMPILE; + // @ts-expect-error for performance reasons + hook._call = undefined; + hook.call = undefined; + return /** @type {AsyncParallelBailHookType} */ ( + /** @type {unknown} */ (hook) + ); +} + +/** @type {EXPECTED_ANY} */ +AsyncParallelBailHook.prototype = null; + +module.exports = AsyncParallelBailHook; diff --git a/dg-ui/node_modules/tapable/lib/AsyncParallelHook.js b/dg-ui/node_modules/tapable/lib/AsyncParallelHook.js new file mode 100644 index 0000000..34327b5 --- /dev/null +++ b/dg-ui/node_modules/tapable/lib/AsyncParallelHook.js @@ -0,0 +1,84 @@ +/* + MIT License http://www.opensource.org/licenses/mit-license.php + Author Tobias Koppers @sokra +*/ +"use strict"; + +const Hook = require("./Hook"); +const HookCodeFactory = require("./HookCodeFactory"); + +/** @typedef {import("./Hook").EXPECTED_ANY} EXPECTED_ANY */ +/** @typedef {import("./Hook").EXPECTED_FUNCTION} EXPECTED_FUNCTION */ +/** @typedef {import("./Hook").CompileOptions} CompileOptions */ +/** @typedef {import("./Hook").UnsetAdditionalOptions} UnsetAdditionalOptions */ +/** @typedef {import("./HookCodeFactory").ContentOptions} ContentOptions */ +/** + * @template {EXPECTED_ANY[]} T + * @typedef {import("./Hook").ArgumentNames} ArgumentNames + */ +/** + * @template T + * @typedef {import("./Hook").AsArray} AsArray + */ + +/** + * Mirror of the `AsyncParallelHook` class declared in `tapable.d.ts` for use + * as the factory function's return type, so `new AsyncParallelHook(...)` + * resolves to the specific subclass type instead of the generic `Hook`. + * @template T + * @template [AdditionalOptions=UnsetAdditionalOptions] + * @typedef {import("../tapable").AsyncParallelHook} AsyncParallelHookType + */ + +class AsyncParallelHookCodeFactory extends HookCodeFactory { + /** + * @param {ContentOptions} options content generation options + * @returns {string} generated body code + */ + content({ onError, onDone }) { + return this.callTapsParallel({ + onError: (i, err, done, doneBreak) => onError(err) + doneBreak(true), + onDone + }); + } +} + +const factory = new AsyncParallelHookCodeFactory(); + +/** + * @this {Hook} + * @param {CompileOptions} options compile options + * @returns {EXPECTED_FUNCTION} the compiled call function + */ +function COMPILE(options) { + factory.setup(this, options); + return factory.create(options); +} + +/** + * @constructor + * @template T + * @template [AdditionalOptions=UnsetAdditionalOptions] + * @param {ArgumentNames>=} args argument names of the hook + * @param {string=} name name of the hook + * @returns {AsyncParallelHookType} a new AsyncParallelHook instance + */ +function AsyncParallelHook( + args = /** @type {ArgumentNames>} */ (/** @type {unknown} */ ([])), + name = undefined +) { + const hook = new Hook(args, name); + hook.constructor = AsyncParallelHook; + hook.compile = COMPILE; + // @ts-expect-error for performance reasons + hook._call = undefined; + hook.call = undefined; + return /** @type {AsyncParallelHookType} */ ( + /** @type {unknown} */ (hook) + ); +} + +/** @type {EXPECTED_ANY} */ +AsyncParallelHook.prototype = null; + +module.exports = AsyncParallelHook; diff --git a/dg-ui/node_modules/tapable/lib/AsyncSeriesBailHook.js b/dg-ui/node_modules/tapable/lib/AsyncSeriesBailHook.js new file mode 100644 index 0000000..f247b43 --- /dev/null +++ b/dg-ui/node_modules/tapable/lib/AsyncSeriesBailHook.js @@ -0,0 +1,91 @@ +/* + MIT License http://www.opensource.org/licenses/mit-license.php + Author Tobias Koppers @sokra +*/ +"use strict"; + +const Hook = require("./Hook"); +const HookCodeFactory = require("./HookCodeFactory"); + +/** @typedef {import("./Hook").EXPECTED_ANY} EXPECTED_ANY */ +/** @typedef {import("./Hook").EXPECTED_FUNCTION} EXPECTED_FUNCTION */ +/** @typedef {import("./Hook").CompileOptions} CompileOptions */ +/** @typedef {import("./Hook").UnsetAdditionalOptions} UnsetAdditionalOptions */ +/** @typedef {import("./HookCodeFactory").ContentOptions} ContentOptions */ +/** + * @template {EXPECTED_ANY[]} T + * @typedef {import("./Hook").ArgumentNames} ArgumentNames + */ +/** + * @template T + * @typedef {import("./Hook").AsArray} AsArray + */ + +/** + * Mirror of the `AsyncSeriesBailHook` class declared in `tapable.d.ts` for + * use as the factory function's return type, so `new AsyncSeriesBailHook(...)` + * resolves to the specific subclass type instead of the generic `Hook`. + * @template T + * @template R + * @template [AdditionalOptions=UnsetAdditionalOptions] + * @typedef {import("../tapable").AsyncSeriesBailHook} AsyncSeriesBailHookType + */ + +class AsyncSeriesBailHookCodeFactory extends HookCodeFactory { + /** + * @param {ContentOptions} options content generation options + * @returns {string} generated body code + */ + content({ onError, onResult, resultReturns, onDone }) { + return this.callTapsSeries({ + onError: (i, err, next, doneBreak) => onError(err) + doneBreak(true), + onResult: (i, result, next) => + `if(${result} !== undefined) {\n${onResult( + result + )}\n} else {\n${next()}}\n`, + resultReturns, + onDone + }); + } +} + +const factory = new AsyncSeriesBailHookCodeFactory(); + +/** + * @this {Hook} + * @param {CompileOptions} options compile options + * @returns {EXPECTED_FUNCTION} the compiled call function + */ +function COMPILE(options) { + factory.setup(this, options); + return factory.create(options); +} + +/** + * @constructor + * @template T + * @template R + * @template [AdditionalOptions=UnsetAdditionalOptions] + * @param {ArgumentNames>=} args argument names of the hook + * @param {string=} name name of the hook + * @returns {AsyncSeriesBailHookType} a new AsyncSeriesBailHook instance + */ +function AsyncSeriesBailHook( + args = /** @type {ArgumentNames>} */ (/** @type {unknown} */ ([])), + name = undefined +) { + const hook = new Hook(args, name); + hook.constructor = AsyncSeriesBailHook; + hook.compile = COMPILE; + // @ts-expect-error for performance reasons + hook._call = undefined; + hook.call = undefined; + return /** @type {AsyncSeriesBailHookType} */ ( + /** @type {unknown} */ (hook) + ); +} + +/** @type {EXPECTED_ANY} */ +AsyncSeriesBailHook.prototype = null; + +module.exports = AsyncSeriesBailHook; diff --git a/dg-ui/node_modules/tapable/lib/AsyncSeriesHook.js b/dg-ui/node_modules/tapable/lib/AsyncSeriesHook.js new file mode 100644 index 0000000..d23ff9a --- /dev/null +++ b/dg-ui/node_modules/tapable/lib/AsyncSeriesHook.js @@ -0,0 +1,84 @@ +/* + MIT License http://www.opensource.org/licenses/mit-license.php + Author Tobias Koppers @sokra +*/ +"use strict"; + +const Hook = require("./Hook"); +const HookCodeFactory = require("./HookCodeFactory"); + +/** @typedef {import("./Hook").EXPECTED_ANY} EXPECTED_ANY */ +/** @typedef {import("./Hook").EXPECTED_FUNCTION} EXPECTED_FUNCTION */ +/** @typedef {import("./Hook").CompileOptions} CompileOptions */ +/** @typedef {import("./Hook").UnsetAdditionalOptions} UnsetAdditionalOptions */ +/** @typedef {import("./HookCodeFactory").ContentOptions} ContentOptions */ +/** + * @template {EXPECTED_ANY[]} T + * @typedef {import("./Hook").ArgumentNames} ArgumentNames + */ +/** + * @template T + * @typedef {import("./Hook").AsArray} AsArray + */ + +/** + * Mirror of the `AsyncSeriesHook` class declared in `tapable.d.ts` for use + * as the factory function's return type, so `new AsyncSeriesHook(...)` + * resolves to the specific subclass type instead of the generic `Hook`. + * @template T + * @template [AdditionalOptions=UnsetAdditionalOptions] + * @typedef {import("../tapable").AsyncSeriesHook} AsyncSeriesHookType + */ + +class AsyncSeriesHookCodeFactory extends HookCodeFactory { + /** + * @param {ContentOptions} options content generation options + * @returns {string} generated body code + */ + content({ onError, onDone }) { + return this.callTapsSeries({ + onError: (i, err, next, doneBreak) => onError(err) + doneBreak(true), + onDone + }); + } +} + +const factory = new AsyncSeriesHookCodeFactory(); + +/** + * @this {Hook} + * @param {CompileOptions} options compile options + * @returns {EXPECTED_FUNCTION} the compiled call function + */ +function COMPILE(options) { + factory.setup(this, options); + return factory.create(options); +} + +/** + * @constructor + * @template T + * @template [AdditionalOptions=UnsetAdditionalOptions] + * @param {ArgumentNames>=} args argument names of the hook + * @param {string=} name name of the hook + * @returns {AsyncSeriesHookType} a new AsyncSeriesHook instance + */ +function AsyncSeriesHook( + args = /** @type {ArgumentNames>} */ (/** @type {unknown} */ ([])), + name = undefined +) { + const hook = new Hook(args, name); + hook.constructor = AsyncSeriesHook; + hook.compile = COMPILE; + // @ts-expect-error for performance reasons + hook._call = undefined; + hook.call = undefined; + return /** @type {AsyncSeriesHookType} */ ( + /** @type {unknown} */ (hook) + ); +} + +/** @type {EXPECTED_ANY} */ +AsyncSeriesHook.prototype = null; + +module.exports = AsyncSeriesHook; diff --git a/dg-ui/node_modules/tapable/lib/AsyncSeriesLoopHook.js b/dg-ui/node_modules/tapable/lib/AsyncSeriesLoopHook.js new file mode 100644 index 0000000..5765eb3 --- /dev/null +++ b/dg-ui/node_modules/tapable/lib/AsyncSeriesLoopHook.js @@ -0,0 +1,84 @@ +/* + MIT License http://www.opensource.org/licenses/mit-license.php + Author Tobias Koppers @sokra +*/ +"use strict"; + +const Hook = require("./Hook"); +const HookCodeFactory = require("./HookCodeFactory"); + +/** @typedef {import("./Hook").EXPECTED_ANY} EXPECTED_ANY */ +/** @typedef {import("./Hook").EXPECTED_FUNCTION} EXPECTED_FUNCTION */ +/** @typedef {import("./Hook").CompileOptions} CompileOptions */ +/** @typedef {import("./Hook").UnsetAdditionalOptions} UnsetAdditionalOptions */ +/** @typedef {import("./HookCodeFactory").ContentOptions} ContentOptions */ +/** + * @template {EXPECTED_ANY[]} T + * @typedef {import("./Hook").ArgumentNames} ArgumentNames + */ +/** + * @template T + * @typedef {import("./Hook").AsArray} AsArray + */ + +/** + * Mirror of the `AsyncSeriesLoopHook` class declared in `tapable.d.ts` for + * use as the factory function's return type, so `new AsyncSeriesLoopHook(...)` + * resolves to the specific subclass type instead of the generic `Hook`. + * @template T + * @template [AdditionalOptions=UnsetAdditionalOptions] + * @typedef {import("../tapable").AsyncSeriesLoopHook} AsyncSeriesLoopHookType + */ + +class AsyncSeriesLoopHookCodeFactory extends HookCodeFactory { + /** + * @param {ContentOptions} options content generation options + * @returns {string} generated body code + */ + content({ onError, onDone }) { + return this.callTapsLooping({ + onError: (i, err, next, doneBreak) => onError(err) + doneBreak(true), + onDone + }); + } +} + +const factory = new AsyncSeriesLoopHookCodeFactory(); + +/** + * @this {Hook} + * @param {CompileOptions} options compile options + * @returns {EXPECTED_FUNCTION} the compiled call function + */ +function COMPILE(options) { + factory.setup(this, options); + return factory.create(options); +} + +/** + * @constructor + * @template T + * @template [AdditionalOptions=UnsetAdditionalOptions] + * @param {ArgumentNames>=} args argument names of the hook + * @param {string=} name name of the hook + * @returns {AsyncSeriesLoopHookType} a new AsyncSeriesLoopHook instance + */ +function AsyncSeriesLoopHook( + args = /** @type {ArgumentNames>} */ (/** @type {unknown} */ ([])), + name = undefined +) { + const hook = new Hook(args, name); + hook.constructor = AsyncSeriesLoopHook; + hook.compile = COMPILE; + // @ts-expect-error for performance reasons + hook._call = undefined; + hook.call = undefined; + return /** @type {AsyncSeriesLoopHookType} */ ( + /** @type {unknown} */ (hook) + ); +} + +/** @type {EXPECTED_ANY} */ +AsyncSeriesLoopHook.prototype = null; + +module.exports = AsyncSeriesLoopHook; diff --git a/dg-ui/node_modules/tapable/lib/AsyncSeriesWaterfallHook.js b/dg-ui/node_modules/tapable/lib/AsyncSeriesWaterfallHook.js new file mode 100644 index 0000000..4cc48c0 --- /dev/null +++ b/dg-ui/node_modules/tapable/lib/AsyncSeriesWaterfallHook.js @@ -0,0 +1,98 @@ +/* + MIT License http://www.opensource.org/licenses/mit-license.php + Author Tobias Koppers @sokra +*/ +"use strict"; + +const Hook = require("./Hook"); +const HookCodeFactory = require("./HookCodeFactory"); + +/** @typedef {import("./Hook").EXPECTED_ANY} EXPECTED_ANY */ +/** @typedef {import("./Hook").EXPECTED_FUNCTION} EXPECTED_FUNCTION */ +/** @typedef {import("./Hook").CompileOptions} CompileOptions */ +/** @typedef {import("./Hook").UnsetAdditionalOptions} UnsetAdditionalOptions */ +/** @typedef {import("./HookCodeFactory").ContentOptions} ContentOptions */ +/** + * @template {EXPECTED_ANY[]} T + * @typedef {import("./Hook").ArgumentNames} ArgumentNames + */ +/** + * @template T + * @typedef {import("./Hook").AsArray} AsArray + */ + +/** + * Mirror of the `AsyncSeriesWaterfallHook` class declared in `tapable.d.ts` + * for use as the factory function's return type, so + * `new AsyncSeriesWaterfallHook(...)` resolves to the specific subclass type + * instead of the generic `Hook`. + * @template T + * @template [R=AsArray[0]] + * @template [AdditionalOptions=UnsetAdditionalOptions] + * @typedef {import("../tapable").AsyncSeriesWaterfallHook} AsyncSeriesWaterfallHookType + */ + +class AsyncSeriesWaterfallHookCodeFactory extends HookCodeFactory { + /** + * @param {ContentOptions} options content generation options + * @returns {string} generated body code + */ + content({ onError, onResult }) { + return this.callTapsSeries({ + onError: (i, err, next, doneBreak) => onError(err) + doneBreak(true), + onResult: (i, result, next) => { + let code = ""; + code += `if(${result} !== undefined) {\n`; + code += `${/** @type {string[]} */ (this._args)[0]} = ${result};\n`; + code += "}\n"; + code += next(); + return code; + }, + onDone: () => onResult(/** @type {string[]} */ (this._args)[0]) + }); + } +} + +const factory = new AsyncSeriesWaterfallHookCodeFactory(); + +/** + * @this {Hook} + * @param {CompileOptions} options compile options + * @returns {EXPECTED_FUNCTION} the compiled call function + */ +function COMPILE(options) { + factory.setup(this, options); + return factory.create(options); +} + +/** + * @constructor + * @template T + * @template [R=AsArray[0]] + * @template [AdditionalOptions=UnsetAdditionalOptions] + * @param {ArgumentNames>=} args argument names of the hook + * @param {string=} name name of the hook + * @returns {AsyncSeriesWaterfallHookType} a new AsyncSeriesWaterfallHook instance + */ +function AsyncSeriesWaterfallHook( + args = /** @type {ArgumentNames>} */ (/** @type {unknown} */ ([])), + name = undefined +) { + if (args.length < 1) { + throw new Error("Waterfall hooks must have at least one argument"); + } + const hook = new Hook(args, name); + hook.constructor = AsyncSeriesWaterfallHook; + hook.compile = COMPILE; + // @ts-expect-error for performance reasons + hook._call = undefined; + hook.call = undefined; + return /** @type {AsyncSeriesWaterfallHookType} */ ( + /** @type {unknown} */ (hook) + ); +} + +/** @type {EXPECTED_ANY} */ +AsyncSeriesWaterfallHook.prototype = null; + +module.exports = AsyncSeriesWaterfallHook; diff --git a/dg-ui/node_modules/tapable/lib/Hook.js b/dg-ui/node_modules/tapable/lib/Hook.js new file mode 100644 index 0000000..851fb3c --- /dev/null +++ b/dg-ui/node_modules/tapable/lib/Hook.js @@ -0,0 +1,500 @@ +/* + MIT License http://www.opensource.org/licenses/mit-license.php + Author Tobias Koppers @sokra +*/ +"use strict"; + +const util = require("util"); + +// eslint-disable-next-line jsdoc/reject-function-type +/** @typedef {Function} EXPECTED_FUNCTION */ +// eslint-disable-next-line jsdoc/reject-any-type +/** @typedef {any} EXPECTED_ANY */ +/** @typedef {Record} EXPECTED_OBJECT */ + +/** + * @template T + * @typedef {T extends EXPECTED_ANY[] ? T : [T]} AsArray + */ + +/** + * @template {number} T + * @typedef {T extends 0 | 1 | 2 | 3 | 4 | 5 | 6 | 7 | 8 ? T : never} Measure + */ + +/** + * @template {EXPECTED_ANY[]} T + * @template U + * @typedef {{ + * 0: [U]; + * 1: [T[0], U]; + * 2: [T[0], T[1], U]; + * 3: [T[0], T[1], T[2], U]; + * 4: [T[0], T[1], T[2], T[3], U]; + * 5: [T[0], T[1], T[2], T[3], T[4], U]; + * 6: [T[0], T[1], T[2], T[3], T[4], T[5], U]; + * 7: [T[0], T[1], T[2], T[3], T[4], T[5], T[6], U]; + * 8: [T[0], T[1], T[2], T[3], T[4], T[5], T[6], T[7], U]; + * }[Measure]} Append + */ + +/* eslint-disable jsdoc/ts-no-empty-object-type */ +/** + * @template X + * @typedef {X extends UnsetAdditionalOptions ? { } : X} IfSet + */ +/* eslint-enable jsdoc/ts-no-empty-object-type */ + +/** + * @template {number} T + * @template U + * @typedef {T extends 0 ? void[] : ReadonlyArray & { 0: U, length: T }} FixedSizeArray + */ + +/** + * @template {EXPECTED_ANY[]} T + * @typedef {FixedSizeArray} ArgumentNames + */ + +/** + * @typedef {object} TapOptions + * @property {string=} before name of an earlier tap to insert this tap before + * @property {number=} stage stage to schedule the tap in (lower runs earlier) + */ + +/** + * @typedef {TapOptions & { name: string }} Tap + */ + +/** + * @typedef {Tap & { type: "sync" | "async" | "promise", fn: EXPECTED_FUNCTION }} FullTap + */ + +/** + * @template E, T + * @typedef {(error: E | null, result?: T) => void} Callback + */ + +/** + * @template E, T + * @typedef {(error?: E | null | false, result?: T) => void} InnerCallback + */ + +// TODO remove context in the next major release, deprecated +/** + * @template T + * @template R + * @template [AdditionalOptions=UnsetAdditionalOptions] + * @typedef {object} HookInterceptor + * @property {string=} name optional name of the interceptor + * @property {((tap: FullTap & IfSet) => void)=} tap called for each tap before it runs + * @property {((...args: EXPECTED_ANY[]) => void)=} call called when the hook is called + * @property {((...args: EXPECTED_ANY[]) => void)=} loop called for each loop iteration of looping hooks + * @property {((err: Error) => void)=} error called when an error occurs + * @property {((result: R) => void)=} result called with the hook's result + * @property {(() => void)=} done called when the hook is fully done + * @property {((tap: FullTap & IfSet) => FullTap & IfSet)=} register called whenever a tap is registered + * @property {boolean=} context true to pass a `_context` argument to interceptor callbacks + */ + +/** + * @typedef {object} UnsetAdditionalOptions + * @property {true} _UnsetAdditionalOptions unset + */ + +/** + * @template T + * @template R + * @template [AdditionalOptions=UnsetAdditionalOptions] + * @typedef {object} CompileOptions + * @property {FullTap[]} taps the registered taps + * @property {HookInterceptor[]} interceptors the registered interceptors + * @property {ArgumentNames>} args names of the hook arguments (used for code generation) + * @property {"sync" | "async" | "promise"} type call type + */ + +const deprecateContext = util.deprecate( + () => {}, + "Hook.context is deprecated and will be removed" +); + +/** + * @template T, R + * @callback CallDelegate + * @param {...AsArray} args + * @returns {R} + */ + +/** + * @template T, R + * @type {CallDelegate} + * @this {Hook} + */ +function CALL_DELEGATE(...args) { + // @ts-expect-error for performance reasons + this.call = this._createCall("sync"); + // @ts-expect-error for performance reasons + return this.call(...args); +} + +/** + * @template T, R + * @callback CallAsyncDelegate + * @param {...Append, Callback>} args + * @returns void + */ + +/** + * @template T, R + * @type {CallAsyncDelegate} + * @this {Hook} + */ +function CALL_ASYNC_DELEGATE(...args) { + // @ts-expect-error for performance reasons + this.callAsync = this._createCall("async"); + return this.callAsync(...args); +} + +/** + * @template T, R + * @callback PromiseDeledate + * @param {...AsArray} args + * @returns {Promise} + */ + +/** + * @template T, R + * @type {PromiseDeledate} + * @this {Hook} + */ +function PROMISE_DELEGATE(...args) { + // @ts-expect-error for performance reasons + this.promise = this._createCall("promise"); + return this.promise(...args); +} + +/** + * @template T + * @template R + * @template [AdditionalOptions=UnsetAdditionalOptions] + */ +class Hook { + /** + * @param {ArgumentNames>=} args argument names of the hook (used for code generation) + * @param {string=} name name of the hook + */ + constructor( + args = /** @type {ArgumentNames>} */ ( + /** @type {unknown} */ ([]) + ), + name = undefined + ) { + /** + * @private + * @type {ArgumentNames>} + */ + this._args = args; + /** @type {string | undefined} */ + this.name = name; + /** @type {FullTap[]} */ + this.taps = []; + /** @type {HookInterceptor[]} */ + this.interceptors = []; + /** + * @private + * @type {CallDelegate | undefined} + */ + this._call = CALL_DELEGATE; + /** @type {CallDelegate | undefined} */ + this.call = CALL_DELEGATE; + /** + * @private + * @type {CallAsyncDelegate} + */ + this._callAsync = CALL_ASYNC_DELEGATE; + /** @type {CallAsyncDelegate} */ + this.callAsync = CALL_ASYNC_DELEGATE; + /** + * @private + * @type {PromiseDeledate} + */ + this._promise = PROMISE_DELEGATE; + /** @type {PromiseDeledate} */ + this.promise = PROMISE_DELEGATE; + /** @type {EXPECTED_FUNCTION[] | undefined} */ + this._x = undefined; + + // eslint-disable-next-line no-self-assign + this.compile = this.compile; + // eslint-disable-next-line no-self-assign + this.tap = this.tap; + // eslint-disable-next-line no-self-assign + this.tapAsync = this.tapAsync; + // eslint-disable-next-line no-self-assign + this.tapPromise = this.tapPromise; + } + + /** + * @abstract + * @param {CompileOptions} _options compile options + * @returns {EXPECTED_FUNCTION} the compiled call function + */ + compile(_options) { + throw new Error("Abstract: should be overridden"); + } + + /** + * @private + * @param {"sync" | "async" | "promise"} type the call type + * @returns {EXPECTED_FUNCTION} the compiled call function + */ + _createCall(type) { + return this.compile({ + taps: this.taps, + interceptors: this.interceptors, + args: this._args, + type + }); + } + + /** + * @private + * @param {"sync" | "async" | "promise"} type the tap type + * @param {string | (Tap & IfSet)} options name or full tap options + * @param {EXPECTED_FUNCTION} fn callback registered with the tap + * @returns {void} + */ + _tap(type, options, fn) { + if (typeof options === "string") { + // Fast path: a string options ("name") is by far the most common + // case. Build the final descriptor in a single allocation instead + // of creating `{ name }` and then `Object.assign`ing it. + const name = options.trim(); + if (name === "") { + throw new Error("Missing name for tap"); + } + options = + /** @type {FullTap & IfSet} */ + ({ type, fn, name }); + } else { + if (typeof options !== "object" || options === null) { + throw new Error("Invalid tap options"); + } + let { name } = options; + if (typeof name === "string") { + name = name.trim(); + } + if (typeof name !== "string" || name === "") { + throw new Error("Missing name for tap"); + } + if ( + typeof (/** @type {{ context?: unknown }} */ (options).context) !== + "undefined" + ) { + deprecateContext(); + } + // Fast path: only `name` is set. Build the descriptor as a literal + // so `_insert` and downstream consumers see the same hidden class + // as the string-options path, avoiding a polymorphic call site. + // Scan with `for...in` (cheaper than allocating `Object.keys`) + // to verify no other user-provided properties exist - e.g. + // webpack's `additionalAssets` - otherwise they'd be dropped. + let onlyName = true; + for (const key in options) { + if (key !== "name") { + onlyName = false; + break; + } + } + if (onlyName) { + options = + /** @type {FullTap & IfSet} */ + ({ type, fn, name }); + } else { + options.name = name; + // Preserve previous precedence: user-provided keys win over the internal `type`/`fn`. + options = Object.assign({ type, fn }, options); + } + } + options = this._runRegisterInterceptors( + /** @type {FullTap & IfSet} */ + (options) + ); + this._insert( + /** @type {FullTap & IfSet} */ + (options) + ); + } + + /** + * @param {string | (Tap & IfSet)} options tap name or full tap options + * @param {(...args: AsArray) => R} fn the function to register + * @returns {void} + */ + tap(options, fn) { + this._tap("sync", options, fn); + } + + /** + * @param {string | (Tap & IfSet)} options tap name or full tap options + * @param {(...args: Append, InnerCallback>) => void} fn the function to register + * @returns {void} + */ + tapAsync(options, fn) { + this._tap("async", options, fn); + } + + /** + * @param {string | (Tap & IfSet)} options tap name or full tap options + * @param {(...args: AsArray) => Promise} fn the function to register + * @returns {void} + */ + tapPromise(options, fn) { + this._tap("promise", options, fn); + } + + /** + * @private + * @param {FullTap & IfSet} options the tap descriptor + * @returns {FullTap & IfSet} possibly transformed options + */ + _runRegisterInterceptors(options) { + const { interceptors } = this; + const { length } = interceptors; + // Common case: no interceptors. + if (length === 0) return options; + for (let i = 0; i < length; i++) { + const interceptor = interceptors[i]; + if (interceptor.register) { + const newOptions = interceptor.register(options); + if (newOptions !== undefined) { + options = newOptions; + } + } + } + return options; + } + + /** + * @param {TapOptions & IfSet} options the options to merge into each tap + * @returns {Omit} a wrapper that pre-applies the options + */ + withOptions(options) { + /** + * @param {string | (TapOptions & IfSet)} opt options + * @returns {Tap & IfSet} merged options + */ + const mergeOptions = (opt) => + /** @type {Tap & IfSet} */ ( + Object.assign( + {}, + options, + typeof opt === "string" ? { name: opt } : opt + ) + ); + + return /** @type {Omit} */ ({ + name: this.name, + tap: (opt, fn) => this.tap(mergeOptions(opt), fn), + tapAsync: (opt, fn) => this.tapAsync(mergeOptions(opt), fn), + tapPromise: (opt, fn) => this.tapPromise(mergeOptions(opt), fn), + intercept: (interceptor) => this.intercept(interceptor), + isUsed: () => this.isUsed(), + withOptions: (opt) => this.withOptions(mergeOptions(opt)) + }); + } + + /** + * @returns {boolean} true if the hook has any taps or interceptors registered + */ + isUsed() { + return this.taps.length > 0 || this.interceptors.length > 0; + } + + /** + * @param {HookInterceptor} interceptor the interceptor to register + * @returns {void} + */ + intercept(interceptor) { + this._resetCompilation(); + this.interceptors.push(Object.assign({}, interceptor)); + if (interceptor.register) { + for (let i = 0; i < this.taps.length; i++) { + this.taps[i] = interceptor.register( + /** @type {FullTap & IfSet} */ (this.taps[i]) + ); + } + } + } + + /** + * @private + * @returns {void} + */ + _resetCompilation() { + this.call = this._call; + this.callAsync = this._callAsync; + this.promise = this._promise; + } + + /** + * @private + * @param {FullTap & IfSet} item the tap to insert into the ordered taps list + * @returns {void} + */ + _insert(item) { + this._resetCompilation(); + const { taps } = this; + const stage = typeof item.stage === "number" ? item.stage : 0; + + // Fast path: the overwhelmingly common `hook.tap("name", fn)` case + // has no `before` and default stage 0. If the list is empty or the + // last tap's stage is <= the new item's stage the item belongs at + // the end - append in O(1), skipping the Set allocation and the + // shift loop. + if (!(typeof item.before === "string" || Array.isArray(item.before))) { + const n = taps.length; + if (n === 0 || (taps[n - 1].stage || 0) <= stage) { + taps[n] = item; + return; + } + } + + /** @type {Set | undefined} */ + let before; + + if (typeof item.before === "string") { + before = new Set([item.before]); + } else if (Array.isArray(item.before)) { + before = new Set(item.before); + } + + let i = taps.length; + + while (i > 0) { + i--; + const tap = taps[i]; + taps[i + 1] = tap; + const xStage = tap.stage || 0; + if (before) { + if (before.has(tap.name)) { + before.delete(tap.name); + continue; + } + if (before.size > 0) { + continue; + } + } + if (xStage > stage) { + continue; + } + i++; + break; + } + taps[i] = item; + } +} + +Object.setPrototypeOf(Hook.prototype, null); + +module.exports = Hook; diff --git a/dg-ui/node_modules/tapable/lib/HookCodeFactory.js b/dg-ui/node_modules/tapable/lib/HookCodeFactory.js new file mode 100644 index 0000000..598ceab --- /dev/null +++ b/dg-ui/node_modules/tapable/lib/HookCodeFactory.js @@ -0,0 +1,649 @@ +/* + MIT License http://www.opensource.org/licenses/mit-license.php + Author Tobias Koppers @sokra +*/ +"use strict"; + +/** @typedef {import("./Hook").EXPECTED_ANY} EXPECTED_ANY */ +/** @typedef {import("./Hook").EXPECTED_OBJECT} EXPECTED_OBJECT */ +/** @typedef {import("./Hook").EXPECTED_FUNCTION} EXPECTED_FUNCTION */ +/** @typedef {import("./Hook").FullTap} FullTap */ +/** @typedef {import("./Hook").CompileOptions} CompileOptions */ + +/** + * @template T, R, AdditionalOptions + * @typedef {import("./Hook").HookInterceptor} HookInterceptor + */ + +/** + * @template T, R, AdditionalOptions + * @typedef {import("./Hook")} Hook + */ + +/** + * @typedef {(error: string) => string} OnErrorCallback + */ + +/** + * @typedef {(result: string) => string} OnResultCallback + */ + +/** + * @typedef {() => string} OnDoneCallback + */ + +/** + * @typedef {object} ContentOptions + * @property {OnErrorCallback} onError generates code for handling an error + * @property {OnResultCallback} onResult generates code for handling a result + * @property {OnDoneCallback} onDone generates code for completion + * @property {boolean=} resultReturns true if the generated function returns a result + * @property {boolean=} doneReturns true if the generated function returns when done + * @property {boolean=} rethrowIfPossible true to rethrow errors when safe + */ + +/** + * @typedef {object} CallTapOptions + * @property {OnErrorCallback} onError generates code for handling an error + * @property {OnResultCallback=} onResult generates code for handling a result + * @property {OnDoneCallback=} onDone generates code for completion + * @property {boolean=} rethrowIfPossible true to rethrow errors when safe + */ + +/** + * @typedef {object} CallTapsOptions + * @property {((tapIndex: number, error: string, next: () => string, doneBreak: (skipDone: boolean) => string) => string)} onError generates code for handling an error + * @property {((tapIndex: number, result: string, next: () => string, doneBreak: (skipDone: boolean) => string) => string)=} onResult generates code for handling a result + * @property {OnDoneCallback} onDone generates code for completion + * @property {boolean=} rethrowIfPossible true to rethrow errors when safe + * @property {boolean=} doneReturns true if the generated function returns when done + * @property {boolean=} resultReturns true if the generated function returns a result + */ + +/** + * @typedef {object} CallTapsParallelOptions + * @property {((tapIndex: number, error: string, next: () => string, doneBreak: (skipDone: boolean) => string) => string)} onError generates code for handling an error + * @property {((tapIndex: number, result: string, next: () => string, doneBreak: (skipDone: boolean) => string) => string)=} onResult generates code for handling a result + * @property {(tapIndex: number, run: () => string, done: () => string, doneBreak: (skipDone: boolean) => string) => string=} onTap options + * @property {OnDoneCallback=} onDone generates code for completion + * @property {boolean=} rethrowIfPossible true to rethrow errors when safe + */ + +class HookCodeFactory { + constructor() { + /** @type {CompileOptions | undefined} */ + this.options = undefined; + /** @type {string[] | undefined} */ + this._args = undefined; + } + + /** + * @param {CompileOptions} options compile options + * @returns {EXPECTED_FUNCTION} the compiled hook function + */ + create(options) { + this.init(options); + /** @type {EXPECTED_FUNCTION} */ + let fn; + switch (options.type) { + case "sync": + fn = new Function( + this.args(), + `"use strict";\n${this.header()}${this.contentWithInterceptors({ + onError: (err) => `throw ${err};\n`, + onResult: (result) => `return ${result};\n`, + onDone: () => "", + resultReturns: true, + rethrowIfPossible: true + })}` + ); + break; + case "async": + fn = new Function( + this.args({ + after: "_callback" + }), + `"use strict";\n${this.header()}${this.contentWithInterceptors({ + onError: (err) => `_callback(${err});\n`, + onResult: (result) => `_callback(null, ${result});\n`, + onDone: () => "_callback();\n" + })}` + ); + break; + case "promise": { + let errorHelperUsed = false; + const content = this.contentWithInterceptors({ + onError: (err) => { + errorHelperUsed = true; + return `_error(${err});\n`; + }, + onResult: (result) => `_resolve(${result});\n`, + onDone: () => "_resolve();\n" + }); + let code = ""; + code += '"use strict";\n'; + code += this.header(); + code += "return new Promise((function(_resolve, _reject) {\n"; + if (errorHelperUsed) { + code += "var _sync = true;\n"; + code += "function _error(_err) {\n"; + code += "if(_sync)\n"; + code += + "_resolve(Promise.resolve().then((function() { throw _err; })));\n"; + code += "else\n"; + code += "_reject(_err);\n"; + code += "};\n"; + } + code += content; + if (errorHelperUsed) { + code += "_sync = false;\n"; + } + code += "}));\n"; + fn = new Function(this.args(), code); + break; + } + } + this.deinit(); + return fn; + } + + /** + * @param {Hook} instance the hook instance to attach the resolved tap function array to + * @param {CompileOptions} options compile options containing the taps + * @returns {void} + */ + setup(instance, options) { + const { taps } = options; + const { length } = taps; + /** @type {EXPECTED_FUNCTION[]}} */ + const fns = Array.from({ length }); + for (let i = 0; i < length; i++) { + fns[i] = taps[i].fn; + } + instance._x = fns; + } + + /** + * @param {CompileOptions} options compile options + * @returns {void} + */ + init(options) { + this.options = options; + // `_args` is only read (length / join / [0]) - never mutated - so we + // can share the caller's array directly instead of paying for a copy + // on every compile. + this._args = /** @type {string[]} */ ( + /** @type {unknown} */ (options.args) + ); + /** @type {string | undefined} */ + this._joinedArgs = undefined; + } + + /** + * @returns {void} + */ + deinit() { + this.options = undefined; + this._args = undefined; + this._joinedArgs = undefined; + } + + /** + * @param {ContentOptions} options content generation options + * @returns {string} generated code with interceptor calls wrapped around content + */ + contentWithInterceptors(options) { + if (/** @type {CompileOptions} */ (this.options).interceptors.length > 0) { + const { onError, onResult, onDone } = options; + let code = ""; + const opts = /** @type {CompileOptions} */ (this.options); + for (let i = 0; i < opts.interceptors.length; i++) { + const interceptor = opts.interceptors[i]; + if (interceptor.call) { + code += `${this.getInterceptor(i)}.call(${this.args({ + before: interceptor.context ? "_context" : undefined + })});\n`; + } + } + // `content` is intentionally not declared on the base class - it's + // abstract and provided by every subclass. Skipping the runtime + // stub keeps the prototype chain mononomorphic on the hot compile + // path: subclass `content` is the only one V8 sees, no shadowing. + // @ts-expect-error abstract method, provided by subclasses for performance reasons + code += this.content( + Object.assign(options, { + onError: + onError && + /** @type {OnErrorCallback} */ + ( + (err) => { + let code = ""; + for (let i = 0; i < opts.interceptors.length; i++) { + const interceptor = opts.interceptors[i]; + if (interceptor.error) { + code += `${this.getInterceptor(i)}.error(${err});\n`; + } + } + code += onError(err); + return code; + } + ), + onResult: + onResult && + /** @type {OnResultCallback} */ + ( + (result) => { + let code = ""; + for (let i = 0; i < opts.interceptors.length; i++) { + const interceptor = opts.interceptors[i]; + if (interceptor.result) { + code += `${this.getInterceptor(i)}.result(${result});\n`; + } + } + code += onResult(result); + return code; + } + ), + onDone: + onDone && + /** @type {OnDoneCallback} */ + ( + () => { + let code = ""; + for (let i = 0; i < opts.interceptors.length; i++) { + const interceptor = opts.interceptors[i]; + if (interceptor.done) { + code += `${this.getInterceptor(i)}.done();\n`; + } + } + code += onDone(); + return code; + } + ) + }) + ); + return code; + } + // @ts-expect-error abstract method, provided by subclasses for performance reasons + return this.content(options); + } + + /** + * @returns {string} generated header preamble shared across all call types + */ + header() { + let code = ""; + code += this.needContext() ? "var _context = {};\n" : "var _context;\n"; + code += "var _x = this._x;\n"; + if (/** @type {CompileOptions} */ (this.options).interceptors.length > 0) { + code += "var _taps = this.taps;\n"; + code += "var _interceptors = this.interceptors;\n"; + } + return code; + } + + /** + * @returns {boolean} true if any tap requested a `_context` + */ + needContext() { + const { taps } = /** @type {CompileOptions} */ (this.options); + for (let i = 0; i < taps.length; i++) { + if (/** @type {{ context?: boolean }} */ (taps[i]).context) return true; + } + return false; + } + + /** + * @param {number} tapIndex index of the tap to call + * @param {CallTapOptions} options content generation options + * @returns {string} generated code that invokes the tap + */ + callTap(tapIndex, { onError, onResult, onDone, rethrowIfPossible }) { + let code = ""; + let hasTapCached = false; + const opts = /** @type {CompileOptions} */ (this.options); + for (let i = 0; i < opts.interceptors.length; i++) { + const interceptor = opts.interceptors[i]; + if (interceptor.tap) { + if (!hasTapCached) { + code += `var _tap${tapIndex} = ${this.getTap(tapIndex)};\n`; + hasTapCached = true; + } + code += `${this.getInterceptor(i)}.tap(${ + interceptor.context ? "_context, " : "" + }_tap${tapIndex});\n`; + } + } + code += `var _fn${tapIndex} = ${this.getTapFn(tapIndex)};\n`; + const tap = + /** @type {FullTap & { context?: boolean }} */ + (opts.taps[tapIndex]); + switch (tap.type) { + case "sync": + if (!rethrowIfPossible) { + code += `var _hasError${tapIndex} = false;\n`; + code += "try {\n"; + } + if (onResult) { + code += `var _result${tapIndex} = _fn${tapIndex}(${this.args({ + before: tap.context ? "_context" : undefined + })});\n`; + } else { + code += `_fn${tapIndex}(${this.args({ + before: tap.context ? "_context" : undefined + })});\n`; + } + if (!rethrowIfPossible) { + code += "} catch(_err) {\n"; + code += `_hasError${tapIndex} = true;\n`; + code += onError("_err"); + code += "}\n"; + code += `if(!_hasError${tapIndex}) {\n`; + } + if (onResult) { + code += onResult(`_result${tapIndex}`); + } + if (onDone) { + code += onDone(); + } + if (!rethrowIfPossible) { + code += "}\n"; + } + break; + case "async": { + let cbCode = ""; + cbCode += onResult + ? `(function(_err${tapIndex}, _result${tapIndex}) {\n` + : `(function(_err${tapIndex}) {\n`; + cbCode += `if(_err${tapIndex}) {\n`; + cbCode += onError(`_err${tapIndex}`); + cbCode += "} else {\n"; + if (onResult) { + cbCode += onResult(`_result${tapIndex}`); + } + if (onDone) { + cbCode += onDone(); + } + cbCode += "}\n"; + cbCode += "})"; + code += `_fn${tapIndex}(${this.args({ + before: tap.context ? "_context" : undefined, + after: cbCode + })});\n`; + break; + } + case "promise": + code += `var _hasResult${tapIndex} = false;\n`; + code += `var _promise${tapIndex} = _fn${tapIndex}(${this.args({ + before: tap.context ? "_context" : undefined + })});\n`; + code += `if (!_promise${tapIndex} || !_promise${tapIndex}.then)\n`; + code += ` throw new Error('Tap function (tapPromise) did not return promise (returned ' + _promise${tapIndex} + ')');\n`; + code += `_promise${tapIndex}.then((function(_result${tapIndex}) {\n`; + code += `_hasResult${tapIndex} = true;\n`; + if (onResult) { + code += onResult(`_result${tapIndex}`); + } + if (onDone) { + code += onDone(); + } + code += `}), function(_err${tapIndex}) {\n`; + code += `if(_hasResult${tapIndex}) throw _err${tapIndex};\n`; + code += onError( + `!_err${tapIndex} ? new Error('Tap function (tapPromise) rejects "' + _err${tapIndex} + '" value') : _err${tapIndex}` + ); + code += "});\n"; + break; + } + return code; + } + + /** + * @param {CallTapsOptions} options series-call options + * @returns {string} generated code calling all taps in series + */ + callTapsSeries({ + onError, + onResult, + resultReturns, + onDone, + doneReturns, + rethrowIfPossible + }) { + const { taps } = /** @type {CompileOptions} */ (this.options); + const tapsLength = taps.length; + if (tapsLength === 0) return onDone(); + // Inlined findIndex to avoid the callback allocation. + let firstAsync = -1; + for (let i = 0; i < tapsLength; i++) { + if (taps[i].type !== "sync") { + firstAsync = i; + break; + } + } + const somethingReturns = resultReturns || doneReturns; + // doneBreak doesn't depend on the loop variable - hoist to allocate once. + /** + * @param {boolean} skipDone true when need to skip done, otherwise false + * @returns {string} code + */ + const doneBreak = (skipDone) => { + if (skipDone) return ""; + return onDone(); + }; + let code = ""; + let current = onDone; + let unrollCounter = 0; + for (let j = tapsLength - 1; j >= 0; j--) { + const i = j; + const unroll = + current !== onDone && (taps[i].type !== "sync" || unrollCounter++ > 20); + if (unroll) { + unrollCounter = 0; + code += `function _next${i}() {\n`; + code += current(); + code += "}\n"; + current = () => `${somethingReturns ? "return " : ""}_next${i}();\n`; + } + const done = current; + const content = this.callTap(i, { + onError: (error) => onError(i, error, done, doneBreak), + onResult: + onResult && ((result) => onResult(i, result, done, doneBreak)), + onDone: !onResult ? done : undefined, + rethrowIfPossible: + rethrowIfPossible && (firstAsync < 0 || i < firstAsync) + }); + current = () => content; + } + code += current(); + return code; + } + + /** + * @param {CallTapsOptions} options looping-call options + * @returns {string} generated code that calls taps in a loop + */ + callTapsLooping({ onError, onDone, rethrowIfPossible }) { + const opts = /** @type {CompileOptions} */ (this.options); + if (opts.taps.length === 0) return onDone(); + const syncOnly = opts.taps.every((t) => t.type === "sync"); + let code = ""; + if (!syncOnly) { + code += "var _looper = (function() {\n"; + code += "var _loopAsync = false;\n"; + } + code += "var _loop;\n"; + code += "do {\n"; + code += "_loop = false;\n"; + for (let i = 0; i < opts.interceptors.length; i++) { + const interceptor = opts.interceptors[i]; + if (interceptor.loop) { + code += `${this.getInterceptor(i)}.loop(${this.args({ + before: interceptor.context ? "_context" : undefined + })});\n`; + } + } + code += this.callTapsSeries({ + onError, + onResult: (i, result, next, doneBreak) => { + let code = ""; + code += `if(${result} !== undefined) {\n`; + code += "_loop = true;\n"; + if (!syncOnly) code += "if(_loopAsync) _looper();\n"; + code += doneBreak(true); + code += "} else {\n"; + code += next(); + code += "}\n"; + return code; + }, + onDone: + onDone && + (() => { + let code = ""; + code += "if(!_loop) {\n"; + code += onDone(); + code += "}\n"; + return code; + }), + rethrowIfPossible: rethrowIfPossible && syncOnly + }); + code += "} while(_loop);\n"; + if (!syncOnly) { + code += "_loopAsync = true;\n"; + code += "});\n"; + code += "_looper();\n"; + } + return code; + } + + /** + * @param {CallTapsParallelOptions} options parallel-call options + * @returns {string} generated code that calls all taps in parallel + */ + callTapsParallel({ + onError, + onResult, + onDone, + rethrowIfPossible, + onTap = (i, run) => run() + }) { + const { taps } = /** @type {CompileOptions} */ (this.options); + const tapsLength = taps.length; + if (tapsLength <= 1) { + return this.callTapsSeries({ + onError, + onResult, + // @ts-expect-error is it a bug? + onDone, + rethrowIfPossible + }); + } + // done and doneBreak don't depend on the loop variable - hoist them + // so they're allocated once per compile instead of once per tap. + const done = () => { + if (onDone) return "if(--_counter === 0) _done();\n"; + return "--_counter;"; + }; + /** + * @param {boolean} skipDone true when need to skip done, otherwise false + * @returns {string} code + */ + const doneBreak = (skipDone) => { + if (skipDone || !onDone) return "_counter = 0;\n"; + return "_counter = 0;\n_done();\n"; + }; + let code = ""; + code += "do {\n"; + code += `var _counter = ${tapsLength};\n`; + if (onDone) { + code += "var _done = (function() {\n"; + code += onDone(); + code += "});\n"; + } + for (let i = 0; i < tapsLength; i++) { + code += "if(_counter <= 0) break;\n"; + code += onTap( + i, + () => + this.callTap(i, { + onError: (error) => { + let code = ""; + code += "if(_counter > 0) {\n"; + code += onError(i, error, done, doneBreak); + code += "}\n"; + return code; + }, + onResult: + onResult && + ((result) => { + let code = ""; + code += "if(_counter > 0) {\n"; + code += onResult(i, result, done, doneBreak); + code += "}\n"; + return code; + }), + onDone: !onResult ? () => done() : undefined, + rethrowIfPossible + }), + done, + doneBreak + ); + } + code += "} while(false);\n"; + return code; + } + + /** + * @param {{ before?: string, after?: string }=} options optional arguments to prepend or append + * @returns {string} comma-separated argument list as JS source + */ + args({ before, after } = {}) { + // Hot during code generation. Join `_args` once and cache the result, + // then build the customized variants via string concat instead of + // allocating temporary `[before, ...allArgs]` / `[...allArgs, after]` + // arrays and re-joining. + let joined = this._joinedArgs; + if (joined === undefined) { + joined = + /** @type {string[]} */ (this._args).length === 0 + ? "" + : /** @type {string[]} */ (this._args).join(", "); + this._joinedArgs = joined; + } + if (!before && !after) return joined; + if (joined.length === 0) { + if (before && after) return `${before}, ${after}`; + return /** @type {string} */ (before || after); + } + if (before && after) return `${before}, ${joined}, ${after}`; + if (before) return `${before}, ${joined}`; + return `${joined}, ${after}`; + } + + /** + * @param {number} idx tap index + * @returns {string} JS expression that resolves to the registered tap function at index `idx` + */ + getTapFn(idx) { + return `_x[${idx}]`; + } + + /** + * @param {number} idx tap index + * @returns {string} JS expression that resolves to the tap descriptor at index `idx` + */ + getTap(idx) { + return `_taps[${idx}]`; + } + + /** + * @param {number} idx interceptor index + * @returns {string} JS expression that resolves to the interceptor at index `idx` + */ + getInterceptor(idx) { + return `_interceptors[${idx}]`; + } +} + +module.exports = HookCodeFactory; diff --git a/dg-ui/node_modules/tapable/lib/HookMap.js b/dg-ui/node_modules/tapable/lib/HookMap.js new file mode 100644 index 0000000..a083584 --- /dev/null +++ b/dg-ui/node_modules/tapable/lib/HookMap.js @@ -0,0 +1,120 @@ +/* + MIT License http://www.opensource.org/licenses/mit-license.php + Author Tobias Koppers @sokra +*/ +"use strict"; + +const util = require("util"); + +/** @typedef {import("./Hook").EXPECTED_ANY} EXPECTED_ANY */ + +/** + * @template H + * @template [K=EXPECTED_ANY] + * @typedef {(key: K) => H} HookFactory + */ + +/** + * @template H + * @template [K=EXPECTED_ANY] + * @typedef {object} HookMapInterceptor + * @property {((key: K, hook: H) => H)=} factory called when a hook is created for a new key + */ + +/** + * @template H, K + * @param {K} key key passed through unchanged + * @param {H} hook hook returned unchanged + * @returns {H} the hook unchanged + */ +const defaultFactory = (key, hook) => hook; + +/** + * @template H + */ +class HookMap { + /** + * @param {HookFactory} factory factory creating new hooks for unknown keys + * @param {string=} name name of the hook map + */ + constructor(factory, name = undefined) { + /** @type {Map} */ + this._map = new Map(); + /** @type {string | undefined} */ + this.name = name; + /** @type {HookFactory} */ + this._factory = factory; + /** @type {HookMapInterceptor[]} */ + this._interceptors = []; + } + + /** + * @param {EXPECTED_ANY} key the key to look up + * @returns {H | undefined} the hook stored for `key`, if any + */ + get(key) { + return this._map.get(key); + } + + /** + * @param {EXPECTED_ANY} key the key to look up or create + * @returns {H} the hook stored for `key`, creating one via the factory if missing + */ + for(key) { + // Hot path: inline the map lookup to skip the `this.get(key)` + // indirection. This gets hit on every hook access in consumers + // like webpack. + const map = this._map; + const hook = map.get(key); + if (hook !== undefined) { + return hook; + } + let newHook = this._factory(key); + const interceptors = this._interceptors; + for (let i = 0; i < interceptors.length; i++) { + newHook = + /** @type {NonNullable["factory"]>} */ + (interceptors[i].factory)(key, newHook); + } + map.set(key, newHook); + return newHook; + } + + /** + * @param {HookMapInterceptor} interceptor the interceptor to register + * @returns {void} + */ + intercept(interceptor) { + this._interceptors.push( + Object.assign( + { + factory: defaultFactory + }, + interceptor + ) + ); + } +} + +HookMap.prototype.tap = + // @ts-expect-error deprecated + util.deprecate(function tap(key, options, fn) { + // @ts-expect-error deprecated + return this.for(key).tap(options, fn); + }, "HookMap#tap(key,…) is deprecated. Use HookMap#for(key).tap(…) instead."); + +HookMap.prototype.tapAsync = + // @ts-expect-error deprecated + util.deprecate(function tapAsync(key, options, fn) { + // @ts-expect-error deprecated + return this.for(key).tapAsync(options, fn); + }, "HookMap#tapAsync(key,…) is deprecated. Use HookMap#for(key).tapAsync(…) instead."); + +HookMap.prototype.tapPromise = + // @ts-expect-error deprecated + util.deprecate(function tapPromise(key, options, fn) { + // @ts-expect-error deprecated + return this.for(key).tapPromise(options, fn); + }, "HookMap#tapPromise(key,…) is deprecated. Use HookMap#for(key).tapPromise(…) instead."); + +module.exports = HookMap; diff --git a/dg-ui/node_modules/tapable/lib/MultiHook.js b/dg-ui/node_modules/tapable/lib/MultiHook.js new file mode 100644 index 0000000..051dbd9 --- /dev/null +++ b/dg-ui/node_modules/tapable/lib/MultiHook.js @@ -0,0 +1,137 @@ +/* + MIT License http://www.opensource.org/licenses/mit-license.php + Author Tobias Koppers @sokra +*/ +"use strict"; + +/** @typedef {import("./Hook").EXPECTED_ANY} EXPECTED_ANY */ +/** @typedef {import("./Hook").EXPECTED_FUNCTION} EXPECTED_FUNCTION */ +/** @typedef {import("./Hook").Tap} Tap */ +/** @typedef {import("./Hook").TapOptions} TapOptions */ + +/** + * @template T + * @typedef {import("./Hook").AsArray} AsArray + */ + +/** + * @template {EXPECTED_ANY[]} T + * @template U + * @typedef {import("./Hook").Append} Append + */ + +/** + * @template E, T + * @typedef {import("./Hook").InnerCallback} InnerCallback + */ + +/** + * @template T + * @template [R=void] + * @template [AdditionalOptions=object] + * @typedef {import("./Hook")} Hook + */ + +/** + * @template T, R, AdditionalOptions + * @typedef {import("./Hook").HookInterceptor} HookInterceptor + */ + +/** + * @template {Hook} H + */ +class MultiHook { + /** + * @param {H[]} hooks the underlying hooks to multiplex tap calls across + * @param {string=} name name of the multi hook + */ + constructor(hooks, name = undefined) { + /** @type {H[]} */ + this.hooks = hooks; + /** @type {string | undefined} */ + this.name = name; + } + + /** + * @template T, R + * @param {string | Tap} options tap name or full tap options + * @param {(...args: AsArray) => R} fn the function to register + * @returns {void} + */ + tap(options, fn) { + const { hooks } = this; + for (let i = 0; i < hooks.length; i++) { + hooks[i].tap(options, fn); + } + } + + /** + * @template T, R + * @param {string | Tap} options tap name or full tap options + * @param {(...args: Append, InnerCallback>) => void} fn the function to register + * @returns {void} + */ + tapAsync(options, fn) { + const { hooks } = this; + for (let i = 0; i < hooks.length; i++) { + hooks[i].tapAsync(options, fn); + } + } + + /** + * @template T, R + * @param {string | Tap} options tap name or full tap options + * @param {(...args: AsArray) => Promise} fn the function to register + * @returns {void} + */ + tapPromise(options, fn) { + const { hooks } = this; + for (let i = 0; i < hooks.length; i++) { + hooks[i].tapPromise(options, /** @type {EXPECTED_ANY} */ (fn)); + } + } + + /** + * @returns {boolean} true if any of the underlying hooks reports usage + */ + isUsed() { + const { hooks } = this; + for (let i = 0; i < hooks.length; i++) { + if (hooks[i].isUsed()) { + return true; + } + } + return false; + } + + /** + * @param {HookInterceptor} interceptor the interceptor to register + * @returns {void} + */ + intercept(interceptor) { + const { hooks } = this; + for (let i = 0; i < hooks.length; i++) { + hooks[i].intercept(interceptor); + } + } + + /** + * @param {TapOptions} options the options to merge into each tap + * @returns {MultiHook} a new MultiHook wrapping each underlying hook with the options + */ + withOptions(options) { + return /** @type {MultiHook} */ ( + new MultiHook( + this.hooks.map( + (hook) => + /** @type {H} */ ( + /** @type {unknown} */ (hook.withOptions(options)) + ) + ), + this.name + ) + ); + } +} + +module.exports = MultiHook; diff --git a/dg-ui/node_modules/tapable/lib/SyncBailHook.js b/dg-ui/node_modules/tapable/lib/SyncBailHook.js new file mode 100644 index 0000000..4e970e9 --- /dev/null +++ b/dg-ui/node_modules/tapable/lib/SyncBailHook.js @@ -0,0 +1,100 @@ +/* + MIT License http://www.opensource.org/licenses/mit-license.php + Author Tobias Koppers @sokra +*/ +"use strict"; + +const Hook = require("./Hook"); +const HookCodeFactory = require("./HookCodeFactory"); + +/** @typedef {import("./Hook").EXPECTED_ANY} EXPECTED_ANY */ +/** @typedef {import("./Hook").EXPECTED_FUNCTION} EXPECTED_FUNCTION */ +/** @typedef {import("./Hook").UnsetAdditionalOptions} UnsetAdditionalOptions */ +/** @typedef {import("./Hook").CompileOptions} CompileOptions */ +/** @typedef {import("./HookCodeFactory").ContentOptions} ContentOptions */ + +/** + * @template T + * @typedef {import("./Hook").AsArray} AsArray + */ +/** + * @template {EXPECTED_ANY[]} T + * @typedef {import("./Hook").ArgumentNames} ArgumentNames + */ + +/** + * Mirror of the `SyncBailHook` class declared in `tapable.d.ts` for use as + * the factory function's return type, so `new SyncBailHook(...)` resolves to + * the specific subclass type instead of the generic `Hook`. + * @template T + * @template R + * @template [AdditionalOptions=UnsetAdditionalOptions] + * @typedef {import("../tapable").SyncBailHook} SyncBailHookType + */ + +class SyncBailHookCodeFactory extends HookCodeFactory { + /** + * @param {ContentOptions} options content generation options + * @returns {string} generated body code + */ + content({ onError, onResult, resultReturns, onDone, rethrowIfPossible }) { + return this.callTapsSeries({ + onError: (i, err) => onError(err), + onResult: (i, result, next) => + `if(${result} !== undefined) {\n${onResult( + result + )};\n} else {\n${next()}}\n`, + resultReturns, + onDone, + rethrowIfPossible + }); + } +} + +const factory = new SyncBailHookCodeFactory(); + +const TAP_ASYNC = () => { + throw new Error("tapAsync is not supported on a SyncBailHook"); +}; + +const TAP_PROMISE = () => { + throw new Error("tapPromise is not supported on a SyncBailHook"); +}; + +/** + * @this {Hook} + * @param {CompileOptions} options compile options + * @returns {EXPECTED_FUNCTION} the compiled call function + */ +function COMPILE(options) { + factory.setup(this, options); + return factory.create(options); +} + +/** + * @constructor + * @template T + * @template R + * @template [AdditionalOptions=UnsetAdditionalOptions] + * @param {ArgumentNames>=} args argument names of the hook + * @param {string=} name name of the hook + * @returns {SyncBailHookType} a new SyncBailHook instance + */ +function SyncBailHook( + args = /** @type {ArgumentNames>} */ (/** @type {unknown} */ ([])), + name = undefined +) { + const hook = new Hook(args, name); + hook.constructor = SyncBailHook; + hook.tapAsync = TAP_ASYNC; + hook.tapPromise = TAP_PROMISE; + hook.compile = COMPILE; + return /** @type {SyncBailHookType} */ ( + /** @type {unknown} */ (hook) + ); +} + +/** @type {EXPECTED_ANY} */ +SyncBailHook.prototype = null; + +module.exports = SyncBailHook; diff --git a/dg-ui/node_modules/tapable/lib/SyncHook.js b/dg-ui/node_modules/tapable/lib/SyncHook.js new file mode 100644 index 0000000..9260fc1 --- /dev/null +++ b/dg-ui/node_modules/tapable/lib/SyncHook.js @@ -0,0 +1,95 @@ +/* + MIT License http://www.opensource.org/licenses/mit-license.php + Author Tobias Koppers @sokra +*/ +"use strict"; + +const Hook = require("./Hook"); +const HookCodeFactory = require("./HookCodeFactory"); + +/** @typedef {import("./Hook").EXPECTED_ANY} EXPECTED_ANY */ +/** @typedef {import("./Hook").EXPECTED_FUNCTION} EXPECTED_FUNCTION */ +/** @typedef {import("./Hook").UnsetAdditionalOptions} UnsetAdditionalOptions */ +/** @typedef {import("./Hook").CompileOptions} CompileOptions */ +/** @typedef {import("./HookCodeFactory").ContentOptions} ContentOptions */ + +/** + * @template T + * @typedef {import("./Hook").AsArray} AsArray + */ +/** + * @template {EXPECTED_ANY[]} T + * @typedef {import("./Hook").ArgumentNames} ArgumentNames + */ + +/** + * Mirror of the `SyncHook` class declared in `tapable.d.ts` for use as the + * factory function's return type, so `new SyncHook(...)` resolves to the + * specific subclass type instead of the generic `Hook`. + * @template T + * @template [R=void] + * @template [AdditionalOptions=UnsetAdditionalOptions] + * @typedef {import("../tapable").SyncHook} SyncHookType + */ + +class SyncHookCodeFactory extends HookCodeFactory { + /** + * @param {ContentOptions} options content generation options + * @returns {string} generated body code + */ + content({ onError, onDone, rethrowIfPossible }) { + return this.callTapsSeries({ + onError: (i, err) => onError(err), + onDone, + rethrowIfPossible + }); + } +} + +const factory = new SyncHookCodeFactory(); + +const TAP_ASYNC = () => { + throw new Error("tapAsync is not supported on a SyncHook"); +}; + +const TAP_PROMISE = () => { + throw new Error("tapPromise is not supported on a SyncHook"); +}; + +/** + * @this {Hook} + * @param {CompileOptions} options compile options + * @returns {EXPECTED_FUNCTION} the compiled call function + */ +function COMPILE(options) { + factory.setup(this, options); + return factory.create(options); +} + +/** + * @constructor + * @template T + * @template [R=void] + * @template [AdditionalOptions=UnsetAdditionalOptions] + * @param {ArgumentNames>=} args argument names of the hook + * @param {string=} name name of the hook + * @returns {SyncHookType} a new SyncHook instance + */ +function SyncHook( + args = /** @type {ArgumentNames>} */ (/** @type {unknown} */ ([])), + name = undefined +) { + const hook = new Hook(args, name); + hook.constructor = SyncHook; + hook.tapAsync = TAP_ASYNC; + hook.tapPromise = TAP_PROMISE; + hook.compile = COMPILE; + return /** @type {SyncHookType} */ ( + /** @type {unknown} */ (hook) + ); +} + +/** @type {EXPECTED_ANY} */ +SyncHook.prototype = null; + +module.exports = SyncHook; diff --git a/dg-ui/node_modules/tapable/lib/SyncLoopHook.js b/dg-ui/node_modules/tapable/lib/SyncLoopHook.js new file mode 100644 index 0000000..86e769b --- /dev/null +++ b/dg-ui/node_modules/tapable/lib/SyncLoopHook.js @@ -0,0 +1,92 @@ +/* + MIT License http://www.opensource.org/licenses/mit-license.php + Author Tobias Koppers @sokra +*/ +"use strict"; + +const Hook = require("./Hook"); +const HookCodeFactory = require("./HookCodeFactory"); + +/** @typedef {import("./Hook").EXPECTED_ANY} EXPECTED_ANY */ +/** @typedef {import("./Hook").EXPECTED_FUNCTION} EXPECTED_FUNCTION */ +/** @typedef {import("./Hook").CompileOptions} CompileOptions */ +/** @typedef {import("./Hook").UnsetAdditionalOptions} UnsetAdditionalOptions */ +/** @typedef {import("./HookCodeFactory").ContentOptions} ContentOptions */ +/** + * @template T + * @typedef {import("./Hook").AsArray} AsArray + */ +/** + * @template {EXPECTED_ANY[]} T + * @typedef {import("./Hook").ArgumentNames} ArgumentNames + */ + +/** + * Mirror of the `SyncLoopHook` class declared in `tapable.d.ts` for use as + * the factory function's return type, so `new SyncLoopHook(...)` resolves + * to the specific subclass type instead of the generic `Hook`. + * @template T + * @template [AdditionalOptions=UnsetAdditionalOptions] + * @typedef {import("../tapable").SyncLoopHook} SyncLoopHookType + */ + +class SyncLoopHookCodeFactory extends HookCodeFactory { + /** + * @param {ContentOptions} options content generation options + * @returns {string} generated body code + */ + content({ onError, onDone, rethrowIfPossible }) { + return this.callTapsLooping({ + onError: (i, err) => onError(err), + onDone, + rethrowIfPossible + }); + } +} + +const factory = new SyncLoopHookCodeFactory(); + +const TAP_ASYNC = () => { + throw new Error("tapAsync is not supported on a SyncLoopHook"); +}; + +const TAP_PROMISE = () => { + throw new Error("tapPromise is not supported on a SyncLoopHook"); +}; + +/** + * @this {Hook} + * @param {CompileOptions} options compile options + * @returns {EXPECTED_FUNCTION} the compiled call function + */ +function COMPILE(options) { + factory.setup(this, options); + return factory.create(options); +} + +/** + * @constructor + * @template T + * @template [AdditionalOptions=UnsetAdditionalOptions] + * @param {ArgumentNames>=} args argument names of the hook + * @param {string=} name name of the hook + * @returns {SyncLoopHookType} a new SyncLoopHook instance + */ +function SyncLoopHook( + args = /** @type {ArgumentNames>} */ (/** @type {unknown} */ ([])), + name = undefined +) { + const hook = new Hook(args, name); + hook.constructor = SyncLoopHook; + hook.tapAsync = TAP_ASYNC; + hook.tapPromise = TAP_PROMISE; + hook.compile = COMPILE; + return /** @type {SyncLoopHookType} */ ( + /** @type {unknown} */ (hook) + ); +} + +/** @type {EXPECTED_ANY} */ +SyncLoopHook.prototype = null; + +module.exports = SyncLoopHook; diff --git a/dg-ui/node_modules/tapable/lib/SyncWaterfallHook.js b/dg-ui/node_modules/tapable/lib/SyncWaterfallHook.js new file mode 100644 index 0000000..de4f2a8 --- /dev/null +++ b/dg-ui/node_modules/tapable/lib/SyncWaterfallHook.js @@ -0,0 +1,106 @@ +/* + MIT License http://www.opensource.org/licenses/mit-license.php + Author Tobias Koppers @sokra +*/ +"use strict"; + +const Hook = require("./Hook"); +const HookCodeFactory = require("./HookCodeFactory"); + +/** @typedef {import("./Hook").EXPECTED_ANY} EXPECTED_ANY */ +/** @typedef {import("./Hook").EXPECTED_FUNCTION} EXPECTED_FUNCTION */ +/** @typedef {import("./Hook").CompileOptions} CompileOptions */ +/** @typedef {import("./Hook").UnsetAdditionalOptions} UnsetAdditionalOptions */ +/** @typedef {import("./HookCodeFactory").ContentOptions} ContentOptions */ +/** + * @template T + * @typedef {import("./Hook").AsArray} AsArray + */ +/** + * @template {EXPECTED_ANY[]} T + * @typedef {import("./Hook").ArgumentNames} ArgumentNames + */ + +/** + * Mirror of the `SyncWaterfallHook` class declared in `tapable.d.ts` for use + * as the factory function's return type, so `new SyncWaterfallHook(...)` + * resolves to the specific subclass type instead of the generic `Hook`. + * @template T + * @template [R=AsArray[0]] + * @template [AdditionalOptions=UnsetAdditionalOptions] + * @typedef {import("../tapable").SyncWaterfallHook} SyncWaterfallHookType + */ + +class SyncWaterfallHookCodeFactory extends HookCodeFactory { + /** + * @param {ContentOptions} options content generation options + * @returns {string} generated body code + */ + content({ onError, onResult, resultReturns, rethrowIfPossible }) { + return this.callTapsSeries({ + onError: (i, err) => onError(err), + onResult: (i, result, next) => { + let code = ""; + code += `if(${result} !== undefined) {\n`; + code += `${/** @type {string[]} */ (this._args)[0]} = ${result};\n`; + code += "}\n"; + code += next(); + return code; + }, + onDone: () => onResult(/** @type {string[]} */ (this._args)[0]), + doneReturns: resultReturns, + rethrowIfPossible + }); + } +} + +const factory = new SyncWaterfallHookCodeFactory(); + +const TAP_ASYNC = () => { + throw new Error("tapAsync is not supported on a SyncWaterfallHook"); +}; + +const TAP_PROMISE = () => { + throw new Error("tapPromise is not supported on a SyncWaterfallHook"); +}; + +/** + * @this {Hook} + * @param {CompileOptions} options compile options + * @returns {EXPECTED_FUNCTION} the compiled call function + */ +function COMPILE(options) { + factory.setup(this, options); + return factory.create(options); +} + +/** + * @constructor + * @template T + * @template [R=AsArray[0]] + * @template [AdditionalOptions=UnsetAdditionalOptions] + * @param {ArgumentNames>=} args argument names of the hook + * @param {string=} name name of the hook + * @returns {SyncWaterfallHookType} a new SyncWaterfallHook instance + */ +function SyncWaterfallHook( + args = /** @type {ArgumentNames>} */ (/** @type {unknown} */ ([])), + name = undefined +) { + if (args.length < 1) { + throw new Error("Waterfall hooks must have at least one argument"); + } + const hook = new Hook(args, name); + hook.constructor = SyncWaterfallHook; + hook.tapAsync = TAP_ASYNC; + hook.tapPromise = TAP_PROMISE; + hook.compile = COMPILE; + return /** @type {SyncWaterfallHookType} */ ( + /** @type {unknown} */ (hook) + ); +} + +/** @type {EXPECTED_ANY} */ +SyncWaterfallHook.prototype = null; + +module.exports = SyncWaterfallHook; diff --git a/dg-ui/node_modules/tapable/lib/index.js b/dg-ui/node_modules/tapable/lib/index.js new file mode 100644 index 0000000..3a0dc67 --- /dev/null +++ b/dg-ui/node_modules/tapable/lib/index.js @@ -0,0 +1,19 @@ +/* + MIT License http://www.opensource.org/licenses/mit-license.php + Author Tobias Koppers @sokra +*/ +"use strict"; + +module.exports.AsyncParallelBailHook = require("./AsyncParallelBailHook"); +module.exports.AsyncParallelHook = require("./AsyncParallelHook"); +module.exports.AsyncSeriesBailHook = require("./AsyncSeriesBailHook"); +module.exports.AsyncSeriesHook = require("./AsyncSeriesHook"); +module.exports.AsyncSeriesLoopHook = require("./AsyncSeriesLoopHook"); +module.exports.AsyncSeriesWaterfallHook = require("./AsyncSeriesWaterfallHook"); +module.exports.HookMap = require("./HookMap"); +module.exports.MultiHook = require("./MultiHook"); +module.exports.SyncBailHook = require("./SyncBailHook"); +module.exports.SyncHook = require("./SyncHook"); +module.exports.SyncLoopHook = require("./SyncLoopHook"); +module.exports.SyncWaterfallHook = require("./SyncWaterfallHook"); +module.exports.__esModule = true; diff --git a/dg-ui/node_modules/tapable/lib/util-browser.js b/dg-ui/node_modules/tapable/lib/util-browser.js new file mode 100644 index 0000000..9cfb733 --- /dev/null +++ b/dg-ui/node_modules/tapable/lib/util-browser.js @@ -0,0 +1,28 @@ +/* + MIT License http://www.opensource.org/licenses/mit-license.php + Author Tobias Koppers @sokra +*/ +"use strict"; + +/** @typedef {import("./Hook").EXPECTED_FUNCTION} EXPECTED_FUNCTION */ + +/** + * Browser shim for `util.deprecate`. Logs the deprecation message once on the + * first call, then forwards arguments to `fn`. + * @param {EXPECTED_FUNCTION} fn the function to wrap + * @param {string} msg the deprecation message + * @returns {EXPECTED_FUNCTION} the wrapped function + */ +module.exports.deprecate = (fn, msg) => { + let once = true; + return function deprecate() { + if (once) { + // eslint-disable-next-line no-console + console.warn(`DeprecationWarning: ${msg}`); + once = false; + } + // @ts-expect-error expected + // eslint-disable-next-line prefer-rest-params + return fn.apply(this, arguments); + }; +}; diff --git a/dg-ui/node_modules/tapable/package.json b/dg-ui/node_modules/tapable/package.json new file mode 100644 index 0000000..ec3eae0 --- /dev/null +++ b/dg-ui/node_modules/tapable/package.json @@ -0,0 +1,67 @@ +{ + "name": "tapable", + "version": "2.3.4", + "description": "Just a little module for plugins.", + "homepage": "https://github.com/webpack/tapable", + "repository": { + "type": "git", + "url": "http://github.com/webpack/tapable.git" + }, + "funding": { + "type": "opencollective", + "url": "https://opencollective.com/webpack" + }, + "license": "MIT", + "author": "Tobias Koppers @sokra", + "main": "lib/index.js", + "browser": { + "util": "./lib/util-browser.js" + }, + "types": "./tapable.d.ts", + "files": [ + "lib", + "tapable.d.ts" + ], + "scripts": { + "lint": "npm run lint:code && npm run lint:types && npm run fmt:check", + "lint:types": "tsc --pretty --noEmit", + "lint:code": "eslint --cache .", + "fmt": "npm run fmt:base -- --log-level warn --write", + "fmt:check": "npm run fmt:base -- --check", + "fmt:base": "node ./node_modules/prettier/bin/prettier.cjs --cache --ignore-unknown .", + "fix": "npm run fix:code && npm run fmt", + "fix:code": "npm run lint:code -- --fix", + "test": "jest", + "benchmark": "node --max-old-space-size=4096 --hash-seed=1 --random-seed=1 --no-opt --predictable --predictable-gc-schedule --interpreted-frames-native-stack --allow-natives-syntax --expose-gc --no-concurrent-sweeping ./benchmark/run.mjs", + "version": "changeset version", + "release": "changeset publish" + }, + "jest": { + "transform": { + "test[\\\\/].+\\.js$": "babel-jest" + }, + "snapshotFormat": { + "escapeString": true, + "printBasicPrototype": true + } + }, + "devDependencies": { + "@babel/core": "^7.4.4", + "@babel/preset-env": "^7.4.4", + "@changesets/cli": "^3.0.3", + "@changesets/get-github-info": "^1.0.1", + "@codspeed/core": "^6.1.1", + "@stylistic/eslint-plugin": "^5.2.3", + "babel-jest": "^30.3.0", + "eslint": "^9.28.0", + "eslint-config-webpack": "^4.6.3", + "jest": "^30.3.0", + "prettier": "^3.8.3", + "prettier-1": "npm:prettier@^1", + "tinybench": "^6.0.0", + "typescript": "^6.0.3" + }, + "engines": { + "node": ">=6" + } +} diff --git a/dg-ui/node_modules/tapable/tapable.d.ts b/dg-ui/node_modules/tapable/tapable.d.ts new file mode 100644 index 0000000..55f9a07 --- /dev/null +++ b/dg-ui/node_modules/tapable/tapable.d.ts @@ -0,0 +1,175 @@ +type FixedSizeArray = T extends 0 + ? void[] + : ReadonlyArray & { + 0: U; + length: T; + }; +type Measure = T extends 0 | 1 | 2 | 3 | 4 | 5 | 6 | 7 | 8 + ? T + : never; +type Append = { + 0: [U]; + 1: [T[0], U]; + 2: [T[0], T[1], U]; + 3: [T[0], T[1], T[2], U]; + 4: [T[0], T[1], T[2], T[3], U]; + 5: [T[0], T[1], T[2], T[3], T[4], U]; + 6: [T[0], T[1], T[2], T[3], T[4], T[5], U]; + 7: [T[0], T[1], T[2], T[3], T[4], T[5], T[6], U]; + 8: [T[0], T[1], T[2], T[3], T[4], T[5], T[6], T[7], U]; +}[Measure]; +type AsArray = T extends any[] ? T : [T]; + +declare class UnsetAdditionalOptions { + _UnsetAdditionalOptions: true; +} +type IfSet = X extends UnsetAdditionalOptions ? {} : X; + +type Callback = (error: E | null, result?: T) => void; +type InnerCallback = (error?: E | null | false, result?: T) => void; + +type FullTap = Tap & { + type: "sync" | "async" | "promise"; + fn: Function; +}; + +type Tap = TapOptions & { + name: string; +}; + +type TapOptions = { + before?: string; + stage?: number; +}; + +interface HookInterceptor { + name?: string; + tap?: (tap: FullTap & IfSet) => void; + call?: (...args: AsArray) => void; + loop?: (...args: AsArray) => void; + error?: (err: Error) => void; + result?: (result: R) => void; + done?: () => void; + register?: ( + tap: FullTap & IfSet + ) => FullTap & IfSet; +} + +type ArgumentNames = FixedSizeArray; + +declare class Hook { + constructor(args?: ArgumentNames>, name?: string); + name: string | undefined; + interceptors: HookInterceptor[]; + taps: FullTap[]; + intercept(interceptor: HookInterceptor): void; + isUsed(): boolean; + callAsync(...args: Append, Callback>): void; + promise(...args: AsArray): Promise; + tap( + options: string | (Tap & IfSet), + fn: (...args: AsArray) => R + ): void; + withOptions( + options: TapOptions & IfSet + ): Omit; +} + +export class SyncHook< + T, + R = void, + AdditionalOptions = UnsetAdditionalOptions +> extends Hook { + call(...args: AsArray): R; +} + +export class SyncBailHook< + T, + R, + AdditionalOptions = UnsetAdditionalOptions +> extends SyncHook {} +export class SyncLoopHook< + T, + AdditionalOptions = UnsetAdditionalOptions +> extends SyncHook {} +export class SyncWaterfallHook< + T, + R = AsArray[0], + AdditionalOptions = UnsetAdditionalOptions +> extends SyncHook {} + +declare class AsyncHook< + T, + R, + AdditionalOptions = UnsetAdditionalOptions +> extends Hook { + tapAsync( + options: string | (Tap & IfSet), + fn: (...args: Append, InnerCallback>) => void + ): void; + tapPromise( + options: string | (Tap & IfSet), + fn: (...args: AsArray) => Promise + ): void; +} + +export class AsyncParallelHook< + T, + AdditionalOptions = UnsetAdditionalOptions +> extends AsyncHook {} +export class AsyncParallelBailHook< + T, + R, + AdditionalOptions = UnsetAdditionalOptions +> extends AsyncHook {} +export class AsyncSeriesHook< + T, + AdditionalOptions = UnsetAdditionalOptions +> extends AsyncHook {} +export class AsyncSeriesBailHook< + T, + R, + AdditionalOptions = UnsetAdditionalOptions +> extends AsyncHook {} +export class AsyncSeriesLoopHook< + T, + AdditionalOptions = UnsetAdditionalOptions +> extends AsyncHook {} +export class AsyncSeriesWaterfallHook< + T, + R = AsArray[0], + AdditionalOptions = UnsetAdditionalOptions +> extends AsyncHook {} + +type HookFactory = (key: K) => H; + +interface HookMapInterceptor { + factory?: (key: K, hook: H) => H; +} + +export class HookMap { + constructor(factory: HookFactory, name?: string); + name: string | undefined; + get(key: any): H | undefined; + for(key: any): H; + intercept(interceptor: HookMapInterceptor): void; +} + +/** + * A `HookMap` whose keys are typed: each key `K` of `M` maps to the hook `M[K]`. + * It is a type only, for annotating a `HookMap`; create one with `new HookMap()`. + */ +export interface TypedHookMap { + name: string | undefined; + get(key: K): M[K] | undefined; + for(key: K): M[K]; + intercept(interceptor: HookMapInterceptor): void; +} + +export class MultiHook { + constructor(hooks: H[], name?: string); + name: string | undefined; + tap(options: string | Tap, fn?: Function): void; + tapAsync(options: string | Tap, fn?: Function): void; + tapPromise(options: string | Tap, fn?: Function): void; +} diff --git a/dg-ui/package-lock.json b/dg-ui/package-lock.json new file mode 100644 index 0000000..abcd68d --- /dev/null +++ b/dg-ui/package-lock.json @@ -0,0 +1,1072 @@ +{ + "name": "dg-ui", + "lockfileVersion": 3, + "requires": true, + "packages": { + "": { + "dependencies": { + "@tailwindcss/cli": "^4.3.5", + "tailwindcss": "^4.3.5" + } + }, + "node_modules/@jridgewell/gen-mapping": { + "version": "0.3.13", + "resolved": "https://registry.npmjs.org/@jridgewell/gen-mapping/-/gen-mapping-0.3.13.tgz", + "integrity": "sha512-2kkt/7niJ6MgEPxF0bYdQ6etZaA+fQvDcLKckhy1yIQOzaoKjBBjSj63/aLVjYE3qhRt5dvM+uUyfCg6UKCBbA==", + "license": "MIT", + "dependencies": { + "@jridgewell/sourcemap-codec": "^1.5.0", + "@jridgewell/trace-mapping": "^0.3.24" + } + }, + "node_modules/@jridgewell/remapping": { + "version": "2.3.5", + "resolved": "https://registry.npmjs.org/@jridgewell/remapping/-/remapping-2.3.5.tgz", + "integrity": "sha512-LI9u/+laYG4Ds1TDKSJW2YPrIlcVYOwi2fUC6xB43lueCjgxV4lffOCZCtYFiH6TNOX+tQKXx97T4IKHbhyHEQ==", + "license": "MIT", + "dependencies": { + "@jridgewell/gen-mapping": "^0.3.5", + "@jridgewell/trace-mapping": "^0.3.24" + } + }, + "node_modules/@jridgewell/resolve-uri": { + "version": "3.1.3", + "resolved": "https://registry.npmjs.org/@jridgewell/resolve-uri/-/resolve-uri-3.1.3.tgz", + "integrity": "sha512-lhTtjtoEArWBjismtfS761S9Hlyn+nIZqOZVYoZ1Xn82PMNMVnk+jj/NhC4fAXGTs7ydONcJiR5vyQBTMDu27g==", + "license": "MIT", + "engines": { + "node": ">=6.0.0" + } + }, + "node_modules/@jridgewell/sourcemap-codec": { + "version": "1.6.0", + "resolved": "https://registry.npmjs.org/@jridgewell/sourcemap-codec/-/sourcemap-codec-1.6.0.tgz", + "integrity": "sha512-T7jf+5zgsZHwNJ4lvQ7/aezbyk0nNX+zJVWpmHA7VYsEx7a7qr5Rg5IbtJFqkgze5Y2sruq1RUY8Q837Od7iFw==", + "license": "MIT" + }, + "node_modules/@jridgewell/trace-mapping": { + "version": "0.3.31", + "resolved": "https://registry.npmjs.org/@jridgewell/trace-mapping/-/trace-mapping-0.3.31.tgz", + "integrity": "sha512-zzNR+SdQSDJzc8joaeP8QQoCQr8NuYx2dIIytl1QeBEZHJ9uW6hebsrYgbz8hJwUQao3TWCMtmfV8Nu1twOLAw==", + "license": "MIT", + "dependencies": { + "@jridgewell/resolve-uri": "^3.1.0", + "@jridgewell/sourcemap-codec": "^1.4.14" + } + }, + "node_modules/@parcel/watcher": { + "version": "2.6.0", + "resolved": "https://registry.npmjs.org/@parcel/watcher/-/watcher-2.6.0.tgz", + "integrity": "sha512-7FNeNl8NCE7aINx7WXiKQrPYZWC/hvrTsmk6zmxbI7LTXE7hVek/n8AfVgpe2y82zl3w0HvCHN0bVKMBoJcC0w==", + "hasInstallScript": true, + "license": "MIT", + "dependencies": { + "detect-libc": "^2.0.3", + "is-glob": "^4.0.3", + "node-addon-api": "^7.0.0", + "picomatch": "^4.0.4" + }, + "engines": { + "node": ">= 10.0.0" + }, + "funding": { + "type": "opencollective", + "url": "https://opencollective.com/parcel" + }, + "optionalDependencies": { + "@parcel/watcher-android-arm64": "2.6.0", + "@parcel/watcher-darwin-arm64": "2.6.0", + "@parcel/watcher-darwin-x64": "2.6.0", + "@parcel/watcher-freebsd-x64": "2.6.0", + "@parcel/watcher-linux-arm-glibc": "2.6.0", + "@parcel/watcher-linux-arm-musl": "2.6.0", + "@parcel/watcher-linux-arm64-glibc": "2.6.0", + "@parcel/watcher-linux-arm64-musl": "2.6.0", + "@parcel/watcher-linux-x64-glibc": "2.6.0", + "@parcel/watcher-linux-x64-musl": "2.6.0", + "@parcel/watcher-win32-arm64": "2.6.0", + "@parcel/watcher-win32-x64": "2.6.0" + } + }, + "node_modules/@parcel/watcher-android-arm64": { + "version": "2.6.0", + "resolved": "https://registry.npmjs.org/@parcel/watcher-android-arm64/-/watcher-android-arm64-2.6.0.tgz", + "integrity": "sha512-trgpLSCKRC/huFjXX/Smh+0sWe4+YtKfktIToiMl59ghz7z+qkH6kMvNnUbLyRs9N11t8l4svSCs1+5B3rOAhA==", + "cpu": [ + "arm64" + ], + "license": "MIT", + "optional": true, + "os": [ + "android" + ], + "engines": { + "node": ">= 10.0.0" + }, + "funding": { + "type": "opencollective", + "url": "https://opencollective.com/parcel" + } + }, + "node_modules/@parcel/watcher-darwin-arm64": { + "version": "2.6.0", + "resolved": "https://registry.npmjs.org/@parcel/watcher-darwin-arm64/-/watcher-darwin-arm64-2.6.0.tgz", + "integrity": "sha512-Y3QV0gl7Q1zbfueunkWIERICbEojQFCgpyG7YqOGNFLsckXyI1xu9mAIUpKY9QBYzBtSkN8dBPwd3yiAO9ovMw==", + "cpu": [ + "arm64" + ], + "license": "MIT", + "optional": true, + "os": [ + "darwin" + ], + "engines": { + "node": ">= 10.0.0" + }, + "funding": { + "type": "opencollective", + "url": "https://opencollective.com/parcel" + } + }, + "node_modules/@parcel/watcher-darwin-x64": { + "version": "2.6.0", + "resolved": "https://registry.npmjs.org/@parcel/watcher-darwin-x64/-/watcher-darwin-x64-2.6.0.tgz", + "integrity": "sha512-Ohv6OpzhUfKYD7Beb8kDvG0jbIxORCYY1JRdZnaBtnjjkJxgD7ZVL0nw2sCYd0yTMKTvz3nnTnOF3cDifK+kvw==", + "cpu": [ + "x64" + ], + "license": "MIT", + "optional": true, + "os": [ + "darwin" + ], + "engines": { + "node": ">= 10.0.0" + }, + "funding": { + "type": "opencollective", + "url": "https://opencollective.com/parcel" + } + }, + "node_modules/@parcel/watcher-freebsd-x64": { + "version": "2.6.0", + "resolved": "https://registry.npmjs.org/@parcel/watcher-freebsd-x64/-/watcher-freebsd-x64-2.6.0.tgz", + "integrity": "sha512-5HmXvDgs8VK+74jF9y9/2FE3/OnlcKmc56tjmSrEuZjpSZOGL+fvAu+HKJBdPs9uwoP2hE6TlSUpXZ/C5jUFmQ==", + "cpu": [ + "x64" + ], + "license": "MIT", + "optional": true, + "os": [ + "freebsd" + ], + "engines": { + "node": ">= 10.0.0" + }, + "funding": { + "type": "opencollective", + "url": "https://opencollective.com/parcel" + } + }, + "node_modules/@parcel/watcher-linux-arm-glibc": { + "version": "2.6.0", + "resolved": "https://registry.npmjs.org/@parcel/watcher-linux-arm-glibc/-/watcher-linux-arm-glibc-2.6.0.tgz", + "integrity": "sha512-Ps/hui3A+vMbjdqlqAowK2ZL8+BO8dBjxeWXj6npTBs3jx4wWmbPpaLuqwrQrSqIVMCnpWo238bJ1U37GhQOYg==", + "cpu": [ + "arm" + ], + "libc": [ + "glibc" + ], + "license": "MIT", + "optional": true, + "os": [ + "linux" + ], + "engines": { + "node": ">= 10.0.0" + }, + "funding": { + "type": "opencollective", + "url": "https://opencollective.com/parcel" + } + }, + "node_modules/@parcel/watcher-linux-arm-musl": { + "version": "2.6.0", + "resolved": "https://registry.npmjs.org/@parcel/watcher-linux-arm-musl/-/watcher-linux-arm-musl-2.6.0.tgz", + "integrity": "sha512-9c6AUHgHoG+IY88MRIHupztQiQnrbqHYQjkM2btA+Bf/wQnQMuiD0Wfk1EVv3TlNT3x41uU71rn6E4xh/+zvkw==", + "cpu": [ + "arm" + ], + "libc": [ + "musl" + ], + "license": "MIT", + "optional": true, + "os": [ + "linux" + ], + "engines": { + "node": ">= 10.0.0" + }, + "funding": { + "type": "opencollective", + "url": "https://opencollective.com/parcel" + } + }, + "node_modules/@parcel/watcher-linux-arm64-glibc": { + "version": "2.6.0", + "resolved": "https://registry.npmjs.org/@parcel/watcher-linux-arm64-glibc/-/watcher-linux-arm64-glibc-2.6.0.tgz", + "integrity": "sha512-yHRqS2owEXe6Hic9z6Mh1ECsCd+ODVOGvZDyciqRd21+v+o+DnXMOrw50DSpIG2sb8GPEaPPmfeCAWKPJdq46g==", + "cpu": [ + "arm64" + ], + "libc": [ + "glibc" + ], + "license": "MIT", + "optional": true, + "os": [ + "linux" + ], + "engines": { + "node": ">= 10.0.0" + }, + "funding": { + "type": "opencollective", + "url": "https://opencollective.com/parcel" + } + }, + "node_modules/@parcel/watcher-linux-arm64-musl": { + "version": "2.6.0", + "resolved": "https://registry.npmjs.org/@parcel/watcher-linux-arm64-musl/-/watcher-linux-arm64-musl-2.6.0.tgz", + "integrity": "sha512-WhB2e/V7rqdHHWZusBSPuy5Ei8S6lSz6FE5TKKQz5h3a0O+C+mhY7vxU9b/stqvMb8beLnPY82ZrFTLKs+SrKA==", + "cpu": [ + "arm64" + ], + "libc": [ + "musl" + ], + "license": "MIT", + "optional": true, + "os": [ + "linux" + ], + "engines": { + "node": ">= 10.0.0" + }, + "funding": { + "type": "opencollective", + "url": "https://opencollective.com/parcel" + } + }, + "node_modules/@parcel/watcher-linux-x64-glibc": { + "version": "2.6.0", + "resolved": "https://registry.npmjs.org/@parcel/watcher-linux-x64-glibc/-/watcher-linux-x64-glibc-2.6.0.tgz", + "integrity": "sha512-ulGE6x6Oz6iAwg75T8YQSoguBWasniIbX+QWpaYPcCnDOpdWX3k+4xbEYPZVLxOuoJI+svJJPD3sEj8G7lrQ3A==", + "cpu": [ + "x64" + ], + "libc": [ + "glibc" + ], + "license": "MIT", + "optional": true, + "os": [ + "linux" + ], + "engines": { + "node": ">= 10.0.0" + }, + "funding": { + "type": "opencollective", + "url": "https://opencollective.com/parcel" + } + }, + "node_modules/@parcel/watcher-linux-x64-musl": { + "version": "2.6.0", + "resolved": "https://registry.npmjs.org/@parcel/watcher-linux-x64-musl/-/watcher-linux-x64-musl-2.6.0.tgz", + "integrity": "sha512-tkBYKt7YQrjIJWYDnto2YgO8MRkjlMTSNoRHzsXinBqbLdeOM3L32wPZJvIZxqaLMfSlS/4sUjH/6STVP/XDLw==", + "cpu": [ + "x64" + ], + "libc": [ + "musl" + ], + "license": "MIT", + "optional": true, + "os": [ + "linux" + ], + "engines": { + "node": ">= 10.0.0" + }, + "funding": { + "type": "opencollective", + "url": "https://opencollective.com/parcel" + } + }, + "node_modules/@parcel/watcher-win32-arm64": { + "version": "2.6.0", + "resolved": "https://registry.npmjs.org/@parcel/watcher-win32-arm64/-/watcher-win32-arm64-2.6.0.tgz", + "integrity": "sha512-gIZAP23jaHjGWasY/TY6yL7NHFClf0Ga7FN+iINvk+KN94rhm94lYZhFsbYFNcA04/onvGD9kKmiJLJB2HbNwQ==", + "cpu": [ + "arm64" + ], + "license": "MIT", + "optional": true, + "os": [ + "win32" + ], + "engines": { + "node": ">= 10.0.0" + }, + "funding": { + "type": "opencollective", + "url": "https://opencollective.com/parcel" + } + }, + "node_modules/@parcel/watcher-win32-x64": { + "version": "2.6.0", + "resolved": "https://registry.npmjs.org/@parcel/watcher-win32-x64/-/watcher-win32-x64-2.6.0.tgz", + "integrity": "sha512-cA+/pXV2YkfxlIcXOQ5fSWqAzzPyD78/x5qbK/I0vUkrlYHA8TIz+MXjAbGouguKVSI4bOmkTSJ1/poVSsgt+A==", + "cpu": [ + "x64" + ], + "license": "MIT", + "optional": true, + "os": [ + "win32" + ], + "engines": { + "node": ">= 10.0.0" + }, + "funding": { + "type": "opencollective", + "url": "https://opencollective.com/parcel" + } + }, + "node_modules/@tailwindcss/cli": { + "version": "4.3.5", + "resolved": "https://registry.npmjs.org/@tailwindcss/cli/-/cli-4.3.5.tgz", + "integrity": "sha512-+evrrLZEgNPDXgdIxD6Zfc23WhSYZQeGwniO5u9M4zC92kbEtIjKd8l2QWeO7du8kl4gF8z7YArnUGHG4y2Jzg==", + "license": "MIT", + "dependencies": { + "@parcel/watcher": "2.6.0", + "@tailwindcss/node": "4.3.5", + "@tailwindcss/oxide": "4.3.5", + "enhanced-resolve": "^5.24.5", + "mri": "^1.2.0", + "picocolors": "^1.1.1", + "tailwindcss": "4.3.5" + }, + "bin": { + "tailwindcss": "dist/index.mjs" + } + }, + "node_modules/@tailwindcss/node": { + "version": "4.3.5", + "resolved": "https://registry.npmjs.org/@tailwindcss/node/-/node-4.3.5.tgz", + "integrity": "sha512-yT53FzV4ke0cr/BguDxhWMpm5MJu1O2muzk+tKw6lKHjODAsYArBbWwFbJiaksfzFv1tpkO9QHGzmfs1hJT66g==", + "license": "MIT", + "dependencies": { + "@jridgewell/remapping": "^2.3.5", + "enhanced-resolve": "^5.24.5", + "jiti": "^2.7.0", + "lightningcss": "1.33.0", + "magic-string": "^1.1.0", + "source-map-js": "^1.2.1", + "tailwindcss": "4.3.5" + } + }, + "node_modules/@tailwindcss/oxide": { + "version": "4.3.5", + "resolved": "https://registry.npmjs.org/@tailwindcss/oxide/-/oxide-4.3.5.tgz", + "integrity": "sha512-PynqGLZsZvwM9tqD/CUxkOIfyd6K5elZ2MooauzJryP/UqXYgi3yYbtt3N0Xe+MHV/eFKPFQCEfIKAqlAS1CBg==", + "license": "MIT", + "engines": { + "node": ">= 20" + }, + "optionalDependencies": { + "@tailwindcss/oxide-android-arm64": "4.3.5", + "@tailwindcss/oxide-darwin-arm64": "4.3.5", + "@tailwindcss/oxide-darwin-x64": "4.3.5", + "@tailwindcss/oxide-freebsd-x64": "4.3.5", + "@tailwindcss/oxide-linux-arm-gnueabihf": "4.3.5", + "@tailwindcss/oxide-linux-arm64-gnu": "4.3.5", + "@tailwindcss/oxide-linux-arm64-musl": "4.3.5", + "@tailwindcss/oxide-linux-x64-gnu": "4.3.5", + "@tailwindcss/oxide-linux-x64-musl": "4.3.5", + "@tailwindcss/oxide-wasm32-wasi": "4.3.5", + "@tailwindcss/oxide-win32-arm64-msvc": "4.3.5", + "@tailwindcss/oxide-win32-x64-msvc": "4.3.5" + } + }, + "node_modules/@tailwindcss/oxide-android-arm64": { + "version": "4.3.5", + "resolved": "https://registry.npmjs.org/@tailwindcss/oxide-android-arm64/-/oxide-android-arm64-4.3.5.tgz", + "integrity": "sha512-Se0z5xMqcSQanJD1IYmO0cGpK3iv0fp3ZsIT7xRJZ1Da5PghvNoc46zz4jIQn+aan3dV9T8AermFNN9QPmsh0Q==", + "cpu": [ + "arm64" + ], + "license": "MIT", + "optional": true, + "os": [ + "android" + ], + "engines": { + "node": ">= 20" + } + }, + "node_modules/@tailwindcss/oxide-darwin-arm64": { + "version": "4.3.5", + "resolved": "https://registry.npmjs.org/@tailwindcss/oxide-darwin-arm64/-/oxide-darwin-arm64-4.3.5.tgz", + "integrity": "sha512-UPrgTDuUbvmqGMZuCnmI3FKee/tYKzKdp00/kuB4oSGB213VYg8QTdF7lVhnPoBXq/mIfJ+ILoBFqNOboWcMwQ==", + "cpu": [ + "arm64" + ], + "license": "MIT", + "optional": true, + "os": [ + "darwin" + ], + "engines": { + "node": ">= 20" + } + }, + "node_modules/@tailwindcss/oxide-darwin-x64": { + "version": "4.3.5", + "resolved": "https://registry.npmjs.org/@tailwindcss/oxide-darwin-x64/-/oxide-darwin-x64-4.3.5.tgz", + "integrity": "sha512-E+p7HEtjI0b8D7kbbWxH067cGui6d4c79COGko9fAPVE3rwc1E7ld2HFCbaG86AOGWS5VKQYqZOaf38ya4uxTQ==", + "cpu": [ + "x64" + ], + "license": "MIT", + "optional": true, + "os": [ + "darwin" + ], + "engines": { + "node": ">= 20" + } + }, + "node_modules/@tailwindcss/oxide-freebsd-x64": { + "version": "4.3.5", + "resolved": "https://registry.npmjs.org/@tailwindcss/oxide-freebsd-x64/-/oxide-freebsd-x64-4.3.5.tgz", + "integrity": "sha512-yWEWcWyAG7rWOcTpJTjdhQ3pcaFY2h+0bqTRfgU3G2fz87ZU3AKdvdZKhslD+kyHnjBUWKvNdRYwIYC5dI1tIg==", + "cpu": [ + "x64" + ], + "license": "MIT", + "optional": true, + "os": [ + "freebsd" + ], + "engines": { + "node": ">= 20" + } + }, + "node_modules/@tailwindcss/oxide-linux-arm-gnueabihf": { + "version": "4.3.5", + "resolved": "https://registry.npmjs.org/@tailwindcss/oxide-linux-arm-gnueabihf/-/oxide-linux-arm-gnueabihf-4.3.5.tgz", + "integrity": "sha512-WmeVjtJhZlr+smpqcdR2kQkkn6arHIJnUIBxTO2EJcTLGY1ecVXNo2hbSn8xc0IH2aEtys936iMWKGyj0GaKnA==", + "cpu": [ + "arm" + ], + "license": "MIT", + "optional": true, + "os": [ + "linux" + ], + "engines": { + "node": ">= 20" + } + }, + "node_modules/@tailwindcss/oxide-linux-arm64-gnu": { + "version": "4.3.5", + "resolved": "https://registry.npmjs.org/@tailwindcss/oxide-linux-arm64-gnu/-/oxide-linux-arm64-gnu-4.3.5.tgz", + "integrity": "sha512-DTCSyucc6ShMp1QMqV5R94Z7xlgNgUzkGmFF1rL5HH2Qjy4eSmEqy+YLGkqqYvWa4sILtgrBt1JjRKbneQtiFQ==", + "cpu": [ + "arm64" + ], + "libc": [ + "glibc" + ], + "license": "MIT", + "optional": true, + "os": [ + "linux" + ], + "engines": { + "node": ">= 20" + } + }, + "node_modules/@tailwindcss/oxide-linux-arm64-musl": { + "version": "4.3.5", + "resolved": "https://registry.npmjs.org/@tailwindcss/oxide-linux-arm64-musl/-/oxide-linux-arm64-musl-4.3.5.tgz", + "integrity": "sha512-H9lsvO4x9E4nE4Hi8h7NHHw0O/kcVSu+iOyFHNGdYzazGgDjFHZbE6S3hQ8kMcbNXSBlMdNi67LV5EVqtpaJtw==", + "cpu": [ + "arm64" + ], + "libc": [ + "musl" + ], + "license": "MIT", + "optional": true, + "os": [ + "linux" + ], + "engines": { + "node": ">= 20" + } + }, + "node_modules/@tailwindcss/oxide-linux-x64-gnu": { + "version": "4.3.5", + "resolved": "https://registry.npmjs.org/@tailwindcss/oxide-linux-x64-gnu/-/oxide-linux-x64-gnu-4.3.5.tgz", + "integrity": "sha512-4uxQvtBvPuIdl13WfUBj9xMZHH14PtHZ8OZdtLmdyDtG66sCa1t599NZT+jagkUzRtWhuul1qRZQ1nAJscXN5g==", + "cpu": [ + "x64" + ], + "libc": [ + "glibc" + ], + "license": "MIT", + "optional": true, + "os": [ + "linux" + ], + "engines": { + "node": ">= 20" + } + }, + "node_modules/@tailwindcss/oxide-linux-x64-musl": { + "version": "4.3.5", + "resolved": "https://registry.npmjs.org/@tailwindcss/oxide-linux-x64-musl/-/oxide-linux-x64-musl-4.3.5.tgz", + "integrity": "sha512-0JQAzs7jwbA7O6+z/adU+Jk3AXwsu3npAhtr5escXS7TqEqWcaDV7qHuI+0Vy/KQRuVGnLQREcSJWYauyV3oqg==", + "cpu": [ + "x64" + ], + "libc": [ + "musl" + ], + "license": "MIT", + "optional": true, + "os": [ + "linux" + ], + "engines": { + "node": ">= 20" + } + }, + "node_modules/@tailwindcss/oxide-wasm32-wasi": { + "version": "4.3.5", + "resolved": "https://registry.npmjs.org/@tailwindcss/oxide-wasm32-wasi/-/oxide-wasm32-wasi-4.3.5.tgz", + "integrity": "sha512-OJhFmlEfdzMr+avACdi40RPtnkW0B6hXyxL/8r+tnEHBWZji36CYRjEXrrvgBmaYsD3oEOBqwYFRKsYvzFe7Bw==", + "bundleDependencies": [ + "@napi-rs/wasm-runtime", + "@emnapi/core", + "@emnapi/runtime", + "@tybys/wasm-util", + "@emnapi/wasi-threads", + "tslib" + ], + "license": "MIT", + "optional": true, + "dependencies": { + "@emnapi/core": "^1.11.3", + "@emnapi/runtime": "^1.11.3", + "@emnapi/wasi-threads": "^1.2.3", + "@napi-rs/wasm-runtime": "^1.2.2", + "@tybys/wasm-util": "^0.10.3", + "tslib": "^2.8.1" + }, + "engines": { + "node": "^20.19.0 || ^22.13.0 || >=23.5.0" + } + }, + "node_modules/@tailwindcss/oxide-wasm32-wasi/node_modules/@emnapi/core": { + "version": "1.11.3", + "inBundle": true, + "license": "MIT", + "optional": true, + "dependencies": { + "@emnapi/wasi-threads": "1.2.3", + "tslib": "^2.4.0" + } + }, + "node_modules/@tailwindcss/oxide-wasm32-wasi/node_modules/@emnapi/runtime": { + "version": "1.11.3", + "inBundle": true, + "license": "MIT", + "optional": true, + "dependencies": { + "tslib": "^2.4.0" + } + }, + "node_modules/@tailwindcss/oxide-wasm32-wasi/node_modules/@emnapi/wasi-threads": { + "version": "1.2.3", + "inBundle": true, + "license": "MIT", + "optional": true, + "dependencies": { + "tslib": "^2.4.0" + } + }, + "node_modules/@tailwindcss/oxide-wasm32-wasi/node_modules/@napi-rs/wasm-runtime": { + "version": "1.2.2", + "inBundle": true, + "license": "MIT", + "optional": true, + "dependencies": { + "@tybys/wasm-util": "^0.10.3" + }, + "engines": { + "node": "^20.19.0 || ^22.13.0 || >=23.5.0" + }, + "funding": { + "type": "github", + "url": "https://github.com/sponsors/Brooooooklyn" + }, + "peerDependencies": { + "@emnapi/core": "^1.7.1 || ^2.0.0-alpha.3", + "@emnapi/runtime": "^1.7.1 || ^2.0.0-alpha.3" + } + }, + "node_modules/@tailwindcss/oxide-wasm32-wasi/node_modules/@tybys/wasm-util": { + "version": "0.10.3", + "inBundle": true, + "license": "MIT", + "optional": true, + "dependencies": { + "tslib": "^2.4.0" + } + }, + "node_modules/@tailwindcss/oxide-wasm32-wasi/node_modules/tslib": { + "version": "2.8.1", + "inBundle": true, + "license": "0BSD", + "optional": true + }, + "node_modules/@tailwindcss/oxide-win32-arm64-msvc": { + "version": "4.3.5", + "resolved": "https://registry.npmjs.org/@tailwindcss/oxide-win32-arm64-msvc/-/oxide-win32-arm64-msvc-4.3.5.tgz", + "integrity": "sha512-9o8jgthi+QE5eandnboiJT64VQfnIArfZzSTdgbhEK5aafdiu2jTW9Honi/mwYHxBZuH1vAC57IFyrh+0iK5Gg==", + "cpu": [ + "arm64" + ], + "license": "MIT", + "optional": true, + "os": [ + "win32" + ], + "engines": { + "node": ">= 20" + } + }, + "node_modules/@tailwindcss/oxide-win32-x64-msvc": { + "version": "4.3.5", + "resolved": "https://registry.npmjs.org/@tailwindcss/oxide-win32-x64-msvc/-/oxide-win32-x64-msvc-4.3.5.tgz", + "integrity": "sha512-XiKFfIy1RWe7qK4WqByxNW7Oz1/nkOy8o/BWhHminyV1PmpUd8Eedj5v2A8h2kpqeVlz6xRnwk9Fr/ZXNLcZfg==", + "cpu": [ + "x64" + ], + "license": "MIT", + "optional": true, + "os": [ + "win32" + ], + "engines": { + "node": ">= 20" + } + }, + "node_modules/detect-libc": { + "version": "2.1.2", + "resolved": "https://registry.npmjs.org/detect-libc/-/detect-libc-2.1.2.tgz", + "integrity": "sha512-Btj2BOOO83o3WyH59e8MgXsxEQVcarkUOpEYrubB0urwnN10yQ364rsiByU11nZlqWYZm05i/of7io4mzihBtQ==", + "license": "Apache-2.0", + "engines": { + "node": ">=8" + } + }, + "node_modules/enhanced-resolve": { + "version": "5.27.0", + "resolved": "https://registry.npmjs.org/enhanced-resolve/-/enhanced-resolve-5.27.0.tgz", + "integrity": "sha512-Do6BB2xzlcc/odFg+XEYyneAx4T/WfywO71yw9ePS2tVfRsf7JVR4mUeELadIeHzixkzbG5DpluiEFPi2WGfYQ==", + "license": "MIT", + "dependencies": { + "graceful-fs": "^4.2.4", + "tapable": "^2.3.3" + }, + "engines": { + "node": ">=10.13.0" + } + }, + "node_modules/graceful-fs": { + "version": "4.2.12", + "resolved": "https://registry.npmjs.org/graceful-fs/-/graceful-fs-4.2.12.tgz", + "integrity": "sha512-iuyGF2E4oafQfPsRrG2wtY2ILupMhvtdrhzrxB+0VcjsPpSPttpfYdjnGFGsTi5MaJFjI1jOKHPQ6UTbTj9TAw==", + "license": "BlueOak-1.0.0" + }, + "node_modules/is-extglob": { + "version": "2.1.1", + "resolved": "https://registry.npmjs.org/is-extglob/-/is-extglob-2.1.1.tgz", + "integrity": "sha512-SbKbANkN603Vi4jEZv49LeVJMn4yGwsbzZworEoyEiutsN3nJYdbO36zfhGJ6QEDpOZIFkDtnq5JRxmvl3jsoQ==", + "license": "MIT", + "engines": { + "node": ">=0.10.0" + } + }, + "node_modules/is-glob": { + "version": "4.0.3", + "resolved": "https://registry.npmjs.org/is-glob/-/is-glob-4.0.3.tgz", + "integrity": "sha512-xelSayHH36ZgE7ZWhli7pW34hNbNl8Ojv5KVmkJD4hBdD3th8Tfk9vYasLM+mXWOZhFkgZfxhLSnrwRr4elSSg==", + "license": "MIT", + "dependencies": { + "is-extglob": "^2.1.1" + }, + "engines": { + "node": ">=0.10.0" + } + }, + "node_modules/jiti": { + "version": "2.7.0", + "resolved": "https://registry.npmjs.org/jiti/-/jiti-2.7.0.tgz", + "integrity": "sha512-AC/7JofJvZGrrneWNaEnJeOLUx+JlGt7tNa0wZiRPT4MY1wmfKjt2+6O2p2uz2+skll8OZZmJMNqeke7kKbNgQ==", + "license": "MIT", + "bin": { + "jiti": "lib/jiti-cli.mjs" + } + }, + "node_modules/lightningcss": { + "version": "1.33.0", + "resolved": "https://registry.npmjs.org/lightningcss/-/lightningcss-1.33.0.tgz", + "integrity": "sha512-WkUDrojuJs0xkgGf2udWxa3yGBRxPtxUkB79i6aCZLRgc7PM8fZe9TosfPDcvEpQZbuFASnHYmRLBLUbmLOIIA==", + "license": "MPL-2.0", + "dependencies": { + "detect-libc": "^2.0.3" + }, + "engines": { + "node": ">= 12.0.0" + }, + "funding": { + "type": "opencollective", + "url": "https://opencollective.com/parcel" + }, + "optionalDependencies": { + "lightningcss-android-arm64": "1.33.0", + "lightningcss-darwin-arm64": "1.33.0", + "lightningcss-darwin-x64": "1.33.0", + "lightningcss-freebsd-x64": "1.33.0", + "lightningcss-linux-arm-gnueabihf": "1.33.0", + "lightningcss-linux-arm64-gnu": "1.33.0", + "lightningcss-linux-arm64-musl": "1.33.0", + "lightningcss-linux-x64-gnu": "1.33.0", + "lightningcss-linux-x64-musl": "1.33.0", + "lightningcss-win32-arm64-msvc": "1.33.0", + "lightningcss-win32-x64-msvc": "1.33.0" + } + }, + "node_modules/lightningcss-android-arm64": { + "version": "1.33.0", + "resolved": "https://registry.npmjs.org/lightningcss-android-arm64/-/lightningcss-android-arm64-1.33.0.tgz", + "integrity": "sha512-gEpRTalKdosp4Bb8qWtc2iOgE5SeIHlpS1up9bFq2wAyYhl1UdTObYiHe98zEM9SQvSoqQZ1IQD0JNpg3Ml5pg==", + "cpu": [ + "arm64" + ], + "license": "MPL-2.0", + "optional": true, + "os": [ + "android" + ], + "engines": { + "node": ">= 12.0.0" + }, + "funding": { + "type": "opencollective", + "url": "https://opencollective.com/parcel" + } + }, + "node_modules/lightningcss-darwin-arm64": { + "version": "1.33.0", + "resolved": "https://registry.npmjs.org/lightningcss-darwin-arm64/-/lightningcss-darwin-arm64-1.33.0.tgz", + "integrity": "sha512-Sciaz8eenNTKn9b3t7+xr0ipTp9YxKQY4npwQ3mrRuL0BAVHBLyZxofhaKBAVtzmtRZ/zTyo0/to4B1uWG/Djg==", + "cpu": [ + "arm64" + ], + "license": "MPL-2.0", + "optional": true, + "os": [ + "darwin" + ], + "engines": { + "node": ">= 12.0.0" + }, + "funding": { + "type": "opencollective", + "url": "https://opencollective.com/parcel" + } + }, + "node_modules/lightningcss-darwin-x64": { + "version": "1.33.0", + "resolved": "https://registry.npmjs.org/lightningcss-darwin-x64/-/lightningcss-darwin-x64-1.33.0.tgz", + "integrity": "sha512-Z5UPAxzrjlWNNyGy6i65cJzzvgJ5D3T6wMvs+gWpY9d7qRhANrxqAp6LhxIgZhWEw18RfJTGcRxjuLIBr+m8XQ==", + "cpu": [ + "x64" + ], + "license": "MPL-2.0", + "optional": true, + "os": [ + "darwin" + ], + "engines": { + "node": ">= 12.0.0" + }, + "funding": { + "type": "opencollective", + "url": "https://opencollective.com/parcel" + } + }, + "node_modules/lightningcss-freebsd-x64": { + "version": "1.33.0", + "resolved": "https://registry.npmjs.org/lightningcss-freebsd-x64/-/lightningcss-freebsd-x64-1.33.0.tgz", + "integrity": "sha512-QQM/Ti/hQajJwCY+RiWuCZ9sdtI/XQk7nDK5vC8kkdwixezOlDgvDx7+RT+QjK6FcFT4MpsuoBnHIo/O3StRRg==", + "cpu": [ + "x64" + ], + "license": "MPL-2.0", + "optional": true, + "os": [ + "freebsd" + ], + "engines": { + "node": ">= 12.0.0" + }, + "funding": { + "type": "opencollective", + "url": "https://opencollective.com/parcel" + } + }, + "node_modules/lightningcss-linux-arm-gnueabihf": { + "version": "1.33.0", + "resolved": "https://registry.npmjs.org/lightningcss-linux-arm-gnueabihf/-/lightningcss-linux-arm-gnueabihf-1.33.0.tgz", + "integrity": "sha512-N7FVBe6iS24MlM6R/4RBTxGhQheZGs7tiQ9U32UtF75NzP5Q7xWPRqLBCKxlRQRk3rY1jCIPLzx7WzOhuUIRLQ==", + "cpu": [ + "arm" + ], + "license": "MPL-2.0", + "optional": true, + "os": [ + "linux" + ], + "engines": { + "node": ">= 12.0.0" + }, + "funding": { + "type": "opencollective", + "url": "https://opencollective.com/parcel" + } + }, + "node_modules/lightningcss-linux-arm64-gnu": { + "version": "1.33.0", + "resolved": "https://registry.npmjs.org/lightningcss-linux-arm64-gnu/-/lightningcss-linux-arm64-gnu-1.33.0.tgz", + "integrity": "sha512-j2v/itmy4HlNxlc6voKXYgBqNi0Ng2LShg4z7GufpEgs05P+2suBVyi9I6YHq5uoVFx9ETin3eCEhLVyXGQnKg==", + "cpu": [ + "arm64" + ], + "libc": [ + "glibc" + ], + "license": "MPL-2.0", + "optional": true, + "os": [ + "linux" + ], + "engines": { + "node": ">= 12.0.0" + }, + "funding": { + "type": "opencollective", + "url": "https://opencollective.com/parcel" + } + }, + "node_modules/lightningcss-linux-arm64-musl": { + "version": "1.33.0", + "resolved": "https://registry.npmjs.org/lightningcss-linux-arm64-musl/-/lightningcss-linux-arm64-musl-1.33.0.tgz", + "integrity": "sha512-yiO5ROMuYQgXbC60yjZU5CYSFZGKXL0HFATXt9mHJn1+zW55oCtMI9NfcVhYLMFDL7gV7oBPon/EmMMGg2OvtQ==", + "cpu": [ + "arm64" + ], + "libc": [ + "musl" + ], + "license": "MPL-2.0", + "optional": true, + "os": [ + "linux" + ], + "engines": { + "node": ">= 12.0.0" + }, + "funding": { + "type": "opencollective", + "url": "https://opencollective.com/parcel" + } + }, + "node_modules/lightningcss-linux-x64-gnu": { + "version": "1.33.0", + "resolved": "https://registry.npmjs.org/lightningcss-linux-x64-gnu/-/lightningcss-linux-x64-gnu-1.33.0.tgz", + "integrity": "sha512-ar+Ju7LmcN0Jo4FpL4hpFybwNG9/3A/Br5KW2n2jyODg3MEZXaDYADdemoNS+BDNfMgKvylJLj4S5tyRActuAg==", + "cpu": [ + "x64" + ], + "libc": [ + "glibc" + ], + "license": "MPL-2.0", + "optional": true, + "os": [ + "linux" + ], + "engines": { + "node": ">= 12.0.0" + }, + "funding": { + "type": "opencollective", + "url": "https://opencollective.com/parcel" + } + }, + "node_modules/lightningcss-linux-x64-musl": { + "version": "1.33.0", + "resolved": "https://registry.npmjs.org/lightningcss-linux-x64-musl/-/lightningcss-linux-x64-musl-1.33.0.tgz", + "integrity": "sha512-RYiYbkokw0trfKqqzfF55lginwEPrD3OJDfTuJzFs1MK6iFnDenaz1fqLLtX4ITG3OktJQXOeTaw1awrBAlZPw==", + "cpu": [ + "x64" + ], + "libc": [ + "musl" + ], + "license": "MPL-2.0", + "optional": true, + "os": [ + "linux" + ], + "engines": { + "node": ">= 12.0.0" + }, + "funding": { + "type": "opencollective", + "url": "https://opencollective.com/parcel" + } + }, + "node_modules/lightningcss-win32-arm64-msvc": { + "version": "1.33.0", + "resolved": "https://registry.npmjs.org/lightningcss-win32-arm64-msvc/-/lightningcss-win32-arm64-msvc-1.33.0.tgz", + "integrity": "sha512-1K+MPfLSFVpphzpdbfkhlWk6wBrTObBzS2T6db10PNOZgR9GoVsAWzwNyuhUYYbTp23j+4RrncfujZ4uAzXvwA==", + "cpu": [ + "arm64" + ], + "license": "MPL-2.0", + "optional": true, + "os": [ + "win32" + ], + "engines": { + "node": ">= 12.0.0" + }, + "funding": { + "type": "opencollective", + "url": "https://opencollective.com/parcel" + } + }, + "node_modules/lightningcss-win32-x64-msvc": { + "version": "1.33.0", + "resolved": "https://registry.npmjs.org/lightningcss-win32-x64-msvc/-/lightningcss-win32-x64-msvc-1.33.0.tgz", + "integrity": "sha512-OlEICDx/Xl0FqSp4bry8zFnCvGpig3Gl4gCquvYwHuqJKEC1+n9NgDniFvqHGmMv1ZkqDJrDqKKSykTDX+ehuA==", + "cpu": [ + "x64" + ], + "license": "MPL-2.0", + "optional": true, + "os": [ + "win32" + ], + "engines": { + "node": ">= 12.0.0" + }, + "funding": { + "type": "opencollective", + "url": "https://opencollective.com/parcel" + } + }, + "node_modules/magic-string": { + "version": "1.4.5", + "resolved": "https://registry.npmjs.org/magic-string/-/magic-string-1.4.5.tgz", + "integrity": "sha512-oLLC2+YvQUfAa+vxoufE/yc1icb87M9iXIRqAoR/2EhE/8cb3SF/+Gi0c2By1B+5Vz2e2vQtUvHiu1+63Znh+w==", + "license": "MIT", + "dependencies": { + "@jridgewell/sourcemap-codec": "^1.6.0" + } + }, + "node_modules/mri": { + "version": "1.2.0", + "resolved": "https://registry.npmjs.org/mri/-/mri-1.2.0.tgz", + "integrity": "sha512-tzzskb3bG8LvYGFF/mDTpq3jpI6Q9wc3LEmBaghu+DdCssd1FakN7Bc0hVNmEyGq1bq3RgfkCb3cmQLpNPOroA==", + "license": "MIT", + "engines": { + "node": ">=4" + } + }, + "node_modules/node-addon-api": { + "version": "7.1.1", + "resolved": "https://registry.npmjs.org/node-addon-api/-/node-addon-api-7.1.1.tgz", + "integrity": "sha512-5m3bsyrjFWE1xf7nz7YXdN4udnVtXK6/Yfgn5qnahL6bCkf2yKt4k3nuTKAtT4r3IG8JNR2ncsIMdZuAzJjHQQ==", + "license": "MIT" + }, + "node_modules/picocolors": { + "version": "1.1.1", + "resolved": "https://registry.npmjs.org/picocolors/-/picocolors-1.1.1.tgz", + "integrity": "sha512-xceH2snhtb5M9liqDsmEw56le376mTZkEX/jEb/RxNFyegNul7eNslCXP9FDj/Lcu0X8KEyMceP2ntpaHrDEVA==", + "license": "ISC" + }, + "node_modules/picomatch": { + "version": "4.0.7", + "resolved": "https://registry.npmjs.org/picomatch/-/picomatch-4.0.7.tgz", + "integrity": "sha512-qcJu88Q2IWqJsDD529JKMdwGm/dvInW4HvQnRwiH9JtihJvzGOscDtHE3x1pBKeUOTysQ8kVmLnJ2kJu7yhcGA==", + "license": "MIT", + "engines": { + "node": ">=12" + }, + "funding": { + "url": "https://github.com/sponsors/jonschlinkert" + } + }, + "node_modules/source-map-js": { + "version": "1.2.4", + "resolved": "https://registry.npmjs.org/source-map-js/-/source-map-js-1.2.4.tgz", + "integrity": "sha512-J7ZjMvHd9O1fcT/5V09QWaaSl2BbWx3F6O08spde82Namf9UB0GxRVIPiNbVsdKkoizHiSpTodo3vp2bAy91MA==", + "license": "BSD-3-Clause", + "engines": { + "node": ">=6.0.0" + } + }, + "node_modules/tailwindcss": { + "version": "4.3.5", + "resolved": "https://registry.npmjs.org/tailwindcss/-/tailwindcss-4.3.5.tgz", + "integrity": "sha512-FcQk9BuffmEHJP2G0XmB2SplU1aLTI7j07Kunk+U74Ny+XiWOtzXz9aujFZ/avntw1e2cOv/3PkgzflQ7gX2vQ==", + "license": "MIT" + }, + "node_modules/tapable": { + "version": "2.3.4", + "resolved": "https://registry.npmjs.org/tapable/-/tapable-2.3.4.tgz", + "integrity": "sha512-NHFiWnAbMJxNNpBwiO7jJVGDuqMxT9/oV8v57RR+fgBQShkJil5inGD8/xWy0hjLyHQyX1tu27QANhlz3KBqCg==", + "license": "MIT", + "engines": { + "node": ">=6" + }, + "funding": { + "type": "opencollective", + "url": "https://opencollective.com/webpack" + } + } + } +} diff --git a/dg-ui/package.json b/dg-ui/package.json new file mode 100644 index 0000000..5c138de --- /dev/null +++ b/dg-ui/package.json @@ -0,0 +1,6 @@ +{ + "dependencies": { + "@tailwindcss/cli": "^4.3.5", + "tailwindcss": "^4.3.5" + } +} diff --git a/hot-dog/packages/ui/src/hero.rs b/dg-ui/src/main.rs similarity index 56% rename from hot-dog/packages/ui/src/hero.rs rename to dg-ui/src/main.rs index 9d1a331..db212e0 100644 --- a/hot-dog/packages/ui/src/hero.rs +++ b/dg-ui/src/main.rs @@ -1,22 +1,35 @@ use dioxus::prelude::*; +const MAIN_CSS: Asset = asset!("/assets/main.css"); +const TAILWIND_CSS: Asset = asset!("/assets/tailwind.css"); -const HERO_CSS: Asset = asset!("/assets/styling/hero.css"); -const HEADER_SVG: Asset = asset!("/assets/header.svg"); +fn main() { + dioxus::launch(App); + let a: String; + print!("{}", a) +} + +#[component] +fn App() -> Element { + rsx! { + document::Link { rel: "stylesheet", href: MAIN_CSS } + document::Link { rel: "stylesheet", href: TAILWIND_CSS } + Hero {} + + } +} #[component] pub fn Hero() -> Element { rsx! { - document::Link { rel: "stylesheet", href: HERO_CSS } - - div { - id: "hero", - img { src: HEADER_SVG, id: "header" } + div { id: "hero", div { id: "links", a { href: "https://dioxuslabs.com/learn/0.7/", "📚 Learn Dioxus" } a { href: "https://dioxuslabs.com/awesome", "🚀 Awesome Dioxus" } a { href: "https://github.com/dioxus-community/", "📡 Community Libraries" } a { href: "https://github.com/DioxusLabs/sdk", "⚙️ Dioxus Development Kit" } - a { href: "https://marketplace.visualstudio.com/items?itemName=DioxusLabs.dioxus", "💫 VSCode Extension" } + a { href: "https://marketplace.visualstudio.com/items?itemName=DioxusLabs.dioxus", + "💫 VSCode Extension" + } a { href: "https://discord.gg/XgGxMSkvUM", "👋 Community Discord" } } } diff --git a/dg-ui/src/style-recipes/item-size-recipe.rs b/dg-ui/src/style-recipes/item-size-recipe.rs new file mode 100644 index 0000000..92cd56f --- /dev/null +++ b/dg-ui/src/style-recipes/item-size-recipe.rs @@ -0,0 +1,11 @@ +enum SizeEnum { + XS, + SM, + MD, + LG, + XL, + XXL, + +} + +pub fn itemSizeRecipe(size: Option, shape: Option) {} diff --git a/dg-ui/tailwind.css b/dg-ui/tailwind.css new file mode 100644 index 0000000..f1d8c73 --- /dev/null +++ b/dg-ui/tailwind.css @@ -0,0 +1 @@ +@import "tailwindcss"; diff --git a/hot-dog/Cargo.toml b/hot-dog/Cargo.toml deleted file mode 100644 index 1011c80..0000000 --- a/hot-dog/Cargo.toml +++ /dev/null @@ -1,15 +0,0 @@ -[workspace] -resolver = "2" -members = [ - "packages/ui", - "packages/web", - "packages/desktop", - "packages/mobile", -] - -[workspace.dependencies] -dioxus = { version = "0.7.1" } - -# workspace -ui = { path = "packages/ui" } - diff --git a/hot-dog/README.md b/hot-dog/README.md deleted file mode 100644 index 54b041c..0000000 --- a/hot-dog/README.md +++ /dev/null @@ -1,60 +0,0 @@ -# Development - -Your new workspace contains a member crate for each of the web, desktop and mobile platforms, and a `ui` crate for components that are shared between multiple platforms: - -``` -your_project/ -├─ README.md -├─ Cargo.toml -└─ packages/ - ├─ web/ - │ └─ ... # Web specific UI/logic - ├─ desktop/ - │ └─ ... # Desktop specific UI/logic - ├─ mobile/ - │ └─ ... # Mobile specific UI/logic - └─ ui/ - └─ ... # Component shared between multiple platforms -``` - -## Platform crates - -Each platform crate contains the entry point for the platform, and any assets, components and dependencies that are specific to that platform. For example, the desktop crate in the workspace looks something like this: - -``` -desktop/ # The desktop crate contains all platform specific UI, logic and dependencies for the desktop app -├─ assets/ # Assets used by the desktop app - Any platform specific assets should go in this folder -├─ src/ -│ ├─ main.rs # The entrypoint for the desktop app. -├─ Cargo.toml # The desktop crate's Cargo.toml - This should include all desktop specific dependencies -``` - -When you start developing with the workspace setup each of the platform crates will look almost identical. The UI starts out exactly the same on all platforms. However, as you continue developing your application, this setup makes it easy to let the views for each platform change independently. - -## Shared UI crate - -The workspace contains a `ui` crate with components that are shared between multiple platforms. You should put any UI elements you want to use in multiple platforms in this crate. You can also put some shared client side logic in this crate, but be careful to not pull in platform specific dependencies. The `ui` crate starts out something like this: - -``` -ui/ -├─ src/ -│ ├─ lib.rs # The entrypoint for the ui crate -│ ├─ hero.rs # The Hero component that will be used in every platform -``` - - - -### Serving Your App - -Navigate to the platform crate of your choice: -```bash -cd web -``` - -and serve: - -```bash -dx serve -``` - - diff --git a/hot-dog/packages/api/Cargo.toml b/hot-dog/packages/api/Cargo.toml deleted file mode 100644 index bca3c11..0000000 --- a/hot-dog/packages/api/Cargo.toml +++ /dev/null @@ -1,10 +0,0 @@ -[package] -name = "api" -version = "0.1.0" -edition = "2021" - -[dependencies] -dioxus = { workspace = true, features = ["fullstack"] } - -[features] -server = ["dioxus/server"] diff --git a/hot-dog/packages/api/README.md b/hot-dog/packages/api/README.md deleted file mode 100644 index 0bd19eb..0000000 --- a/hot-dog/packages/api/README.md +++ /dev/null @@ -1,13 +0,0 @@ -# API - -This crate contains all shared fullstack server functions. This is a great place to place any server-only logic you would like to expose in multiple platforms like a method that accesses your database or a method that sends an email. - -This crate will be built twice: -1. Once for the server build with the `dioxus/server` feature enabled -2. Once for the client build with the client feature disabled - -During the server build, the server functions will be collected and hosted on a public API for the client to call. During the client build, the server functions will be compiled into the client build. - -## Dependencies - -Most server dependencies (like sqlx and tokio) will not compile on client platforms like WASM. To avoid building server dependencies on the client, you should add platform specific dependencies under the `server` feature in the [Cargo.toml](../Cargo.toml) file. More details about managing server only dependencies can be found in the [Dioxus guide](https://dioxuslabs.com/learn/0.7/guides/fullstack/managing_dependencies#adding-server-only-dependencies). diff --git a/hot-dog/packages/api/src/lib.rs b/hot-dog/packages/api/src/lib.rs deleted file mode 100644 index e507148..0000000 --- a/hot-dog/packages/api/src/lib.rs +++ /dev/null @@ -1,8 +0,0 @@ -//! This crate contains all shared fullstack server functions. -use dioxus::prelude::*; - -/// Echo the user input on the server. -#[post("/api/echo")] -pub async fn echo(input: String) -> Result { - Ok(input) -} diff --git a/hot-dog/packages/desktop/Cargo.toml b/hot-dog/packages/desktop/Cargo.toml deleted file mode 100644 index 294e514..0000000 --- a/hot-dog/packages/desktop/Cargo.toml +++ /dev/null @@ -1,13 +0,0 @@ -[package] -name = "desktop" -version = "0.1.0" -edition = "2021" - -[dependencies] -dioxus = { workspace = true, features = [] } -ui = { workspace = true } - -[features] -default = ["desktop"] -desktop = ["dioxus/desktop"] - diff --git a/hot-dog/packages/desktop/README.md b/hot-dog/packages/desktop/README.md deleted file mode 100644 index 8b72dfb..0000000 --- a/hot-dog/packages/desktop/README.md +++ /dev/null @@ -1,22 +0,0 @@ -# Development - -The desktop crate defines the entrypoint for the desktop app along with any assets, components and dependencies that are specific to desktop builds. The desktop crate starts out something like this: - -``` -desktop/ -├─ assets/ # Assets used by the desktop app - Any platform specific assets should go in this folder -├─ src/ -│ ├─ main.rs # The entrypoint for the desktop app. -├─ Cargo.toml # The desktop crate's Cargo.toml - This should include all desktop specific dependencies -``` - -## Dependencies -This crate will only be included in the desktop build, so you should add all desktop specific dependencies to this crate's [Cargo.toml](../Cargo.toml) file instead of the shared [ui](../ui/Cargo.toml) crate. - -### Serving Your Desktop App - -You can start your desktop app with the following command: - -```bash -dx serve -``` diff --git a/hot-dog/packages/desktop/assets/blog.css b/hot-dog/packages/desktop/assets/blog.css deleted file mode 100644 index f27f060..0000000 --- a/hot-dog/packages/desktop/assets/blog.css +++ /dev/null @@ -1,8 +0,0 @@ -#blog { - margin-top: 50px; -} - -#blog a { - color: #ffffff; - margin-top: 50px; -} \ No newline at end of file diff --git a/hot-dog/packages/desktop/assets/main.css b/hot-dog/packages/desktop/assets/main.css deleted file mode 100644 index ef6e674..0000000 --- a/hot-dog/packages/desktop/assets/main.css +++ /dev/null @@ -1,6 +0,0 @@ -body { - background-color: #0f1116; - color: #ffffff; - font-family: 'Segoe UI', Tahoma, Geneva, Verdana, sans-serif; - margin: 20px; -} \ No newline at end of file diff --git a/hot-dog/packages/desktop/src/main.rs b/hot-dog/packages/desktop/src/main.rs deleted file mode 100644 index ef99ebe..0000000 --- a/hot-dog/packages/desktop/src/main.rs +++ /dev/null @@ -1,22 +0,0 @@ -use dioxus::prelude::*; - -use ui::Hero; - -const MAIN_CSS: Asset = asset!("/assets/main.css"); - -fn main() { - dioxus::launch(App); -} - -#[component] -fn App() -> Element { - // Build cool things ✌️ - - rsx! { - // Global app resources - document::Link { rel: "stylesheet", href: MAIN_CSS } - - Hero {} - - } -} diff --git a/hot-dog/packages/desktop/src/views/blog.rs b/hot-dog/packages/desktop/src/views/blog.rs deleted file mode 100644 index c114f5e..0000000 --- a/hot-dog/packages/desktop/src/views/blog.rs +++ /dev/null @@ -1,30 +0,0 @@ -use crate::Route; -use dioxus::prelude::*; - -const BLOG_CSS: Asset = asset!("/assets/blog.css"); - -#[component] -pub fn Blog(id: i32) -> Element { - rsx! { - document::Link { rel: "stylesheet", href: BLOG_CSS} - - div { - id: "blog", - - // Content - h1 { "This is blog #{id}!" } - p { "In blog #{id}, we show how the Dioxus router works and how URL parameters can be passed as props to our route components." } - - // Navigation links - Link { - to: Route::Blog { id: id - 1 }, - "Previous" - } - span { " <---> " } - Link { - to: Route::Blog { id: id + 1 }, - "Next" - } - } - } -} diff --git a/hot-dog/packages/desktop/src/views/home.rs b/hot-dog/packages/desktop/src/views/home.rs deleted file mode 100644 index 8708179..0000000 --- a/hot-dog/packages/desktop/src/views/home.rs +++ /dev/null @@ -1,10 +0,0 @@ -use dioxus::prelude::*; -use ui::Hero; - -#[component] -pub fn Home() -> Element { - rsx! { - Hero {} - - } -} diff --git a/hot-dog/packages/desktop/src/views/mod.rs b/hot-dog/packages/desktop/src/views/mod.rs deleted file mode 100644 index 6e40d5b..0000000 --- a/hot-dog/packages/desktop/src/views/mod.rs +++ /dev/null @@ -1,5 +0,0 @@ -mod home; -pub use home::Home; - -mod blog; -pub use blog::Blog; \ No newline at end of file diff --git a/hot-dog/packages/mobile/Cargo.toml b/hot-dog/packages/mobile/Cargo.toml deleted file mode 100644 index 9fcf1cb..0000000 --- a/hot-dog/packages/mobile/Cargo.toml +++ /dev/null @@ -1,13 +0,0 @@ -[package] -name = "mobile" -version = "0.1.0" -edition = "2021" - -[dependencies] -dioxus = { workspace = true, features = [] } -ui = { workspace = true } - -[features] -default = ["mobile"] -mobile = ["dioxus/mobile"] - diff --git a/hot-dog/packages/mobile/README.md b/hot-dog/packages/mobile/README.md deleted file mode 100644 index 0b4625a..0000000 --- a/hot-dog/packages/mobile/README.md +++ /dev/null @@ -1,22 +0,0 @@ -# Development - -The mobile crate defines the entrypoint for the mobile app along with any assets, components and dependencies that are specific to mobile builds. The mobile crate starts out something like this: - -``` -mobile/ -├─ assets/ # Assets used by the mobile app - Any platform specific assets should go in this folder -├─ src/ -│ ├─ main.rs # The entrypoint for the mobile app. -├─ Cargo.toml # The mobile crate's Cargo.toml - This should include all mobile specific dependencies -``` - -## Dependencies -This crate will only be included in the mobile build, so you should add all mobile specific dependencies to this crate's [Cargo.toml](../Cargo.toml) file instead of the shared [ui](../ui/Cargo.toml) crate. - -### Serving Your Mobile App - -Mobile platforms are shared in a single crate. To serve mobile, you need to explicitly set your target device to `android` or `ios`: - -```bash -dx serve --platform android -``` \ No newline at end of file diff --git a/hot-dog/packages/mobile/assets/blog.css b/hot-dog/packages/mobile/assets/blog.css deleted file mode 100644 index f27f060..0000000 --- a/hot-dog/packages/mobile/assets/blog.css +++ /dev/null @@ -1,8 +0,0 @@ -#blog { - margin-top: 50px; -} - -#blog a { - color: #ffffff; - margin-top: 50px; -} \ No newline at end of file diff --git a/hot-dog/packages/mobile/assets/main.css b/hot-dog/packages/mobile/assets/main.css deleted file mode 100644 index ef6e674..0000000 --- a/hot-dog/packages/mobile/assets/main.css +++ /dev/null @@ -1,6 +0,0 @@ -body { - background-color: #0f1116; - color: #ffffff; - font-family: 'Segoe UI', Tahoma, Geneva, Verdana, sans-serif; - margin: 20px; -} \ No newline at end of file diff --git a/hot-dog/packages/mobile/src/main.rs b/hot-dog/packages/mobile/src/main.rs deleted file mode 100644 index ef99ebe..0000000 --- a/hot-dog/packages/mobile/src/main.rs +++ /dev/null @@ -1,22 +0,0 @@ -use dioxus::prelude::*; - -use ui::Hero; - -const MAIN_CSS: Asset = asset!("/assets/main.css"); - -fn main() { - dioxus::launch(App); -} - -#[component] -fn App() -> Element { - // Build cool things ✌️ - - rsx! { - // Global app resources - document::Link { rel: "stylesheet", href: MAIN_CSS } - - Hero {} - - } -} diff --git a/hot-dog/packages/mobile/src/views/blog.rs b/hot-dog/packages/mobile/src/views/blog.rs deleted file mode 100644 index c114f5e..0000000 --- a/hot-dog/packages/mobile/src/views/blog.rs +++ /dev/null @@ -1,30 +0,0 @@ -use crate::Route; -use dioxus::prelude::*; - -const BLOG_CSS: Asset = asset!("/assets/blog.css"); - -#[component] -pub fn Blog(id: i32) -> Element { - rsx! { - document::Link { rel: "stylesheet", href: BLOG_CSS} - - div { - id: "blog", - - // Content - h1 { "This is blog #{id}!" } - p { "In blog #{id}, we show how the Dioxus router works and how URL parameters can be passed as props to our route components." } - - // Navigation links - Link { - to: Route::Blog { id: id - 1 }, - "Previous" - } - span { " <---> " } - Link { - to: Route::Blog { id: id + 1 }, - "Next" - } - } - } -} diff --git a/hot-dog/packages/mobile/src/views/home.rs b/hot-dog/packages/mobile/src/views/home.rs deleted file mode 100644 index 8708179..0000000 --- a/hot-dog/packages/mobile/src/views/home.rs +++ /dev/null @@ -1,10 +0,0 @@ -use dioxus::prelude::*; -use ui::Hero; - -#[component] -pub fn Home() -> Element { - rsx! { - Hero {} - - } -} diff --git a/hot-dog/packages/mobile/src/views/mod.rs b/hot-dog/packages/mobile/src/views/mod.rs deleted file mode 100644 index 6e40d5b..0000000 --- a/hot-dog/packages/mobile/src/views/mod.rs +++ /dev/null @@ -1,5 +0,0 @@ -mod home; -pub use home::Home; - -mod blog; -pub use blog::Blog; \ No newline at end of file diff --git a/hot-dog/packages/ui/Cargo.toml b/hot-dog/packages/ui/Cargo.toml deleted file mode 100644 index dfff444..0000000 --- a/hot-dog/packages/ui/Cargo.toml +++ /dev/null @@ -1,8 +0,0 @@ -[package] -name = "ui" -version = "0.1.0" -edition = "2021" - -[dependencies] -dioxus = { workspace = true } - diff --git a/hot-dog/packages/ui/README.md b/hot-dog/packages/ui/README.md deleted file mode 100644 index 9a74d89..0000000 --- a/hot-dog/packages/ui/README.md +++ /dev/null @@ -1,14 +0,0 @@ -# UI - -This crate contains all shared components for the workspace. This is a great place to place any UI you would like to use in multiple platforms like a common `Button` or `Navbar` component. - -``` -ui/ -├─ src/ -│ ├─ lib.rs # The entrypoint for the ui crate -│ ├─ hero.rs # The Hero component that will be used in every platform -``` - -## Dependencies - -Since this crate is shared between multiple platforms, it should not pull in any platform specific dependencies. For example, if you want to use the `web_sys` crate in the web build of your app, you should not add it to this crate. Instead, you should add platform specific dependencies to the [web](../web/Cargo.toml), [desktop](../desktop/Cargo.toml), or [mobile](../mobile/Cargo.toml) crates. diff --git a/hot-dog/packages/ui/assets/header.svg b/hot-dog/packages/ui/assets/header.svg deleted file mode 100644 index 59c96f2..0000000 --- a/hot-dog/packages/ui/assets/header.svg +++ /dev/null @@ -1,20 +0,0 @@ - \ No newline at end of file diff --git a/hot-dog/packages/ui/assets/styling/echo.css b/hot-dog/packages/ui/assets/styling/echo.css deleted file mode 100644 index 67d9b2b..0000000 --- a/hot-dog/packages/ui/assets/styling/echo.css +++ /dev/null @@ -1,34 +0,0 @@ -#echo { - width: 360px; - margin-left: auto; - margin-right: auto; - margin-top: 50px; - background-color: #1e222d; - padding: 20px; - border-radius: 10px; -} - -#echo>h4 { - margin: 0px 0px 15px 0px; -} - - -#echo>input { - border: none; - border-bottom: 1px white solid; - background-color: transparent; - color: #ffffff; - transition: border-bottom-color 0.2s ease; - outline: none; - display: block; - padding: 0px 0px 5px 0px; - width: 100%; -} - -#echo>input:focus { - border-bottom-color: #6d85c6; -} - -#echo>p { - margin: 20px 0px 0px auto; -} \ No newline at end of file diff --git a/hot-dog/packages/ui/assets/styling/hero.css b/hot-dog/packages/ui/assets/styling/hero.css deleted file mode 100644 index 79db803..0000000 --- a/hot-dog/packages/ui/assets/styling/hero.css +++ /dev/null @@ -1,35 +0,0 @@ -#hero { - margin: 0; - display: flex; - flex-direction: column; - justify-content: center; - align-items: center; -} - -#links { - width: 400px; - text-align: left; - font-size: x-large; - color: white; - display: flex; - flex-direction: column; -} - -#links a { - color: white; - text-decoration: none; - margin-top: 20px; - margin: 10px 0px; - border: white 1px solid; - border-radius: 5px; - padding: 10px; -} - -#links a:hover { - background-color: #1f1f1f; - cursor: pointer; -} - -#header { - max-width: 1200px; -} \ No newline at end of file diff --git a/hot-dog/packages/ui/assets/styling/navbar.css b/hot-dog/packages/ui/assets/styling/navbar.css deleted file mode 100644 index 7372c63..0000000 --- a/hot-dog/packages/ui/assets/styling/navbar.css +++ /dev/null @@ -1,16 +0,0 @@ -#navbar { - display: flex; - flex-direction: row; -} - -#navbar a { - color: #ffffff; - margin-right: 20px; - text-decoration: none; - transition: color 0.2s ease; -} - -#navbar a:hover { - cursor: pointer; - color: #91a4d2; -} \ No newline at end of file diff --git a/hot-dog/packages/ui/src/echo.rs b/hot-dog/packages/ui/src/echo.rs deleted file mode 100644 index 9583091..0000000 --- a/hot-dog/packages/ui/src/echo.rs +++ /dev/null @@ -1,31 +0,0 @@ -use dioxus::prelude::*; - -const ECHO_CSS: Asset = asset!("/assets/styling/echo.css"); - -/// Echo component that demonstrates fullstack server functions. -#[component] -pub fn Echo() -> Element { - let mut response = use_signal(|| String::new()); - - rsx! { - document::Link { rel: "stylesheet", href: ECHO_CSS } - div { - id: "echo", - h4 { "ServerFn Echo" } - input { - placeholder: "Type here to echo...", - oninput: move |event| async move { - let data = api::echo(event.value()).await.unwrap(); - response.set(data); - }, - } - - if !response().is_empty() { - p { - "Server echoed: " - i { "{response}" } - } - } - } - } -} \ No newline at end of file diff --git a/hot-dog/packages/ui/src/lib.rs b/hot-dog/packages/ui/src/lib.rs deleted file mode 100644 index 550ffd4..0000000 --- a/hot-dog/packages/ui/src/lib.rs +++ /dev/null @@ -1,4 +0,0 @@ -//! This crate contains all shared UI for the workspace. - -mod hero; -pub use hero::Hero; diff --git a/hot-dog/packages/ui/src/navbar.rs b/hot-dog/packages/ui/src/navbar.rs deleted file mode 100644 index c169782..0000000 --- a/hot-dog/packages/ui/src/navbar.rs +++ /dev/null @@ -1,15 +0,0 @@ -use dioxus::prelude::*; - -const NAVBAR_CSS: Asset = asset!("/assets/styling/navbar.css"); - -#[component] -pub fn Navbar(children: Element) -> Element { - rsx! { - document::Link { rel: "stylesheet", href: NAVBAR_CSS } - - div { - id: "navbar", - {children} - } - } -} diff --git a/hot-dog/packages/web/Cargo.toml b/hot-dog/packages/web/Cargo.toml deleted file mode 100644 index 302adae..0000000 --- a/hot-dog/packages/web/Cargo.toml +++ /dev/null @@ -1,13 +0,0 @@ -[package] -name = "web" -version = "0.1.0" -edition = "2021" - -[dependencies] -dioxus = { workspace = true, features = [] } -ui = { workspace = true } - -[features] -default = ["web"] -web = ["dioxus/web"] - diff --git a/hot-dog/packages/web/README.md b/hot-dog/packages/web/README.md deleted file mode 100644 index 7b29ee6..0000000 --- a/hot-dog/packages/web/README.md +++ /dev/null @@ -1,22 +0,0 @@ -# Development - -The web crate defines the entrypoint for the web app along with any assets, components and dependencies that are specific to web builds. The web crate starts out something like this: - -``` -web/ -├─ assets/ # Assets used by the web app - Any platform specific assets should go in this folder -├─ src/ -│ ├─ main.rs # The entrypoint for the web app. -├─ Cargo.toml # The web crate's Cargo.toml - This should include all web specific dependencies -``` - -## Dependencies -This crate will only be included in the web build, so you should add all web specific dependencies to this crate's [Cargo.toml](../Cargo.toml) file instead of the shared [ui](../ui/Cargo.toml) crate. - -### Serving Your Web App - -You can start your web app with the following command: - -```bash -dx serve -``` diff --git a/hot-dog/packages/web/assets/blog.css b/hot-dog/packages/web/assets/blog.css deleted file mode 100644 index f27f060..0000000 --- a/hot-dog/packages/web/assets/blog.css +++ /dev/null @@ -1,8 +0,0 @@ -#blog { - margin-top: 50px; -} - -#blog a { - color: #ffffff; - margin-top: 50px; -} \ No newline at end of file diff --git a/hot-dog/packages/web/assets/favicon.ico b/hot-dog/packages/web/assets/favicon.ico deleted file mode 100644 index eed0c09..0000000 Binary files a/hot-dog/packages/web/assets/favicon.ico and /dev/null differ diff --git a/hot-dog/packages/web/assets/main.css b/hot-dog/packages/web/assets/main.css deleted file mode 100644 index ef6e674..0000000 --- a/hot-dog/packages/web/assets/main.css +++ /dev/null @@ -1,6 +0,0 @@ -body { - background-color: #0f1116; - color: #ffffff; - font-family: 'Segoe UI', Tahoma, Geneva, Verdana, sans-serif; - margin: 20px; -} \ No newline at end of file diff --git a/hot-dog/packages/web/src/main.rs b/hot-dog/packages/web/src/main.rs deleted file mode 100644 index a03a2a6..0000000 --- a/hot-dog/packages/web/src/main.rs +++ /dev/null @@ -1,24 +0,0 @@ -use dioxus::prelude::*; - -use ui::Hero; - -const FAVICON: Asset = asset!("/assets/favicon.ico"); -const MAIN_CSS: Asset = asset!("/assets/main.css"); - -fn main() { - dioxus::launch(App); -} - -#[component] -fn App() -> Element { - // Build cool things ✌️ - - rsx! { - // Global app resources - document::Link { rel: "icon", href: FAVICON } - document::Link { rel: "stylesheet", href: MAIN_CSS } - - Hero {} - - } -} diff --git a/hot-dog/packages/web/src/views/blog.rs b/hot-dog/packages/web/src/views/blog.rs deleted file mode 100644 index c114f5e..0000000 --- a/hot-dog/packages/web/src/views/blog.rs +++ /dev/null @@ -1,30 +0,0 @@ -use crate::Route; -use dioxus::prelude::*; - -const BLOG_CSS: Asset = asset!("/assets/blog.css"); - -#[component] -pub fn Blog(id: i32) -> Element { - rsx! { - document::Link { rel: "stylesheet", href: BLOG_CSS} - - div { - id: "blog", - - // Content - h1 { "This is blog #{id}!" } - p { "In blog #{id}, we show how the Dioxus router works and how URL parameters can be passed as props to our route components." } - - // Navigation links - Link { - to: Route::Blog { id: id - 1 }, - "Previous" - } - span { " <---> " } - Link { - to: Route::Blog { id: id + 1 }, - "Next" - } - } - } -} diff --git a/hot-dog/packages/web/src/views/home.rs b/hot-dog/packages/web/src/views/home.rs deleted file mode 100644 index 8708179..0000000 --- a/hot-dog/packages/web/src/views/home.rs +++ /dev/null @@ -1,10 +0,0 @@ -use dioxus::prelude::*; -use ui::Hero; - -#[component] -pub fn Home() -> Element { - rsx! { - Hero {} - - } -} diff --git a/hot-dog/packages/web/src/views/mod.rs b/hot-dog/packages/web/src/views/mod.rs deleted file mode 100644 index 6e40d5b..0000000 --- a/hot-dog/packages/web/src/views/mod.rs +++ /dev/null @@ -1,5 +0,0 @@ -mod home; -pub use home::Home; - -mod blog; -pub use blog::Blog; \ No newline at end of file diff --git a/note/一些重要概念.md b/note/一些重要概念.md new file mode 100644 index 0000000..967cf6f --- /dev/null +++ b/note/一些重要概念.md @@ -0,0 +1,153 @@ +# Rust 和 TypeScript 的重要区别 + +## 三种传值方式 &A,mut &A, A + +不可变借用 &A,就是性能优化,我只读值,不需要复制一份值,直接给我引用就可以了,我称为 “使用型”。 + +唯一可变借用,mut &A,也是性能优化,我读写,由于文件太大,复制一份不值得,但我上了锁,我称为 “加工型”。 + +复制传值 A,复制一份值,有计算开销,我称为 “隔离型”。 + +## 键值对 + +在 TypeScript 里,一个对象是可以数量不确定的键值对的,也就是 Record 类型,Map 类型也是类似的,不过 Record 类型本身就是 json 写法,免去很多方法调用。 + +例如, +``` +const aReco: Record = { one:"1",two:"2"}; +if( aReco.a? != undefined ) { aReco.a = "1" }; +``` +在 Rust 里,对象就是 struct,struct 的键值对数量是固定的,因此只能用 HashMap 类型。 + +``` +cosnt key = "one"; +const map = HashMap::new(); +cosnt valueOp = map.get(key); +// valueOp 的类型是 Option, enum Option { Some(T), None} +// 这就像 TS 里的 string | undefined + +// 模仿 TS 类型收窄,但这里戳断了 Undefined,后面的变量就永远不可能是 None 了 +if(valueOp != None){ + const arg = valueOp.unwrap() // arg 永远也不可能是 None 了. +} + +``` +## 初始化问题 + +有时候,我们希望一个 prop 是可以没有值的, 凡是 Undefied,都一律使用 Option 包装。 + +## 交叉类型和联合类型 + +TS 中。 + +``` +// 这种叫做联合类型,即不相交的意思 +type Size = "xs" | "sm"; + +// 交叉类型,即相交,必须同时满足 +type Props = { class:string } & { + size:Size +}; +``` + +## Rust 中的联合类型 enum + +不要用 union,因为 union 被标记为 unsafe。 + +Rust 的 Enum 可以是组元或者结构体,而 C 的 enum 只能是常量值。 + +``` +enum SizeEnum { + String("XS"), + String("SM"), +} +``` + +## Rust 中的交叉类型 + +// 不存在交叉类型,直接用 struct 组合,也就是组合优于继承 。 + +``` +struct AnimalCommon { + name:String, + age:number, +} + +struct Dog { + animalCommon:Animal, + favorite_food:String, +} + +``` + +## Rust Enum 详解 + +``` + +// 1. 无数据变体(类似 C 的 enum) + +enum Color { + +Red, + +Green, + +Blue, + +} + + + + +// 2. 元组变体(匿名数据) + +enum Status { + +Ok, // 无数据 + +Err(String), // 单个字符串 + +Code(i32, String), // 两个匿名值 + +} + + + + +// 3. 结构体变体(具名字段) + +enum Message { + +Quit, // 无数据 + +Move { x: i32, y: i32 }, // 命名字段 + +Write(String), // 元组变体 + +ChangeColor { r: u8, g: u8, b: u8 }, // 命名字段 + +} + +``` + +## 继承的本质是变体,也就是 is-a,但你可以选择不变,以此复用数据 + +会破坏封装性,例如,子类的 add 方法,内部调用了 super.add 。 + +父类的 count 字段,和子类的 count 字段,其实是同一个。 + +add 方法被调用了2次,子类 add(2), 内部 super.add(2), 最后 count 加了 4 。 + +一个规避方法,父类决不能是一个实现类,只能是一个未被实现的 interface。 + +但这样,每次子类都要重新实现一边逻辑,与我们试图复用 “已实现的代码” 的目的不符。 + +我们要的是复用 “已实现的代码”,因此 override 里面不应该 写 super.add + +## 组合的本质是 has-a,只是复用麻烦了点。 + +## C++ RAII 与 Rust 生命周期的区别 + +RAII 即 把变量绑定到对象上,利用构造函数和析构函数,自动处理内存安全。 + +也就是说,从传统的获取变量,变成了获取对象。