A lightweight, macOS-style dock for Windows 11, with glass visuals, smooth magnification, and Genie effect.
first commit
CristianOlivera19f94779c427d
diff --git a/.agents/skills/rust-best-practices/SKILL.md b/.agents/skills/rust-best-practices/SKILL.mdnew file mode 100644index 0000000..5a44d1c--- /dev/null+++ b/.agents/skills/rust-best-practices/SKILL.md@@ -0,0 +1,94 @@+---+name: rust-best-practices+description: >+ Guide for writing idiomatic Rust code based on Apollo GraphQL's best practices handbook. Use this skill when:+ (1) writing new Rust code or functions,+ (2) reviewing or refactoring existing Rust code,+ (3) deciding between borrowing vs cloning or ownership patterns,+ (4) implementing error handling with Result types,+ (5) optimizing Rust code for performance,+ (6) writing tests or documentation for Rust projects.+license: MIT+compatibility: Rust 1.70+, Cargo+metadata:+ author: apollographql+ version: "1.1.2"+allowed-tools: Bash(cargo:*) Bash(rustc:*) Bash(rustfmt:*) Bash(clippy:*) Read Write Edit Glob Grep+---++# Rust Best Practices++Apply these guidelines when writing or reviewing Rust code. Based on Apollo GraphQL's [Rust Best Practices Handbook](https://github.com/apollographql/rust-best-practices).++## Best Practices Reference++Before reviewing, familiarize yourself with Apollo's Rust best practices. Read ALL relevant chapters in the same turn in parallel. Reference these files when providing feedback:++- [Chapter 1 - Coding Styles and Idioms](references/chapter_01.md): Borrowing vs cloning, Copy trait, Option/Result handling, iterators, comments, when to extract a function (duplication vs. wrong abstraction)+- [Chapter 2 - Clippy and Linting](references/chapter_02.md): Clippy configuration, important lints, workspace lint setup+- [Chapter 3 - Performance Mindset](references/chapter_03.md): Profiling, avoiding redundant clones, stack vs heap, zero-cost abstractions+- [Chapter 4 - Error Handling](references/chapter_04.md): Result vs panic, thiserror vs anyhow, error hierarchies+- [Chapter 5 - Automated Testing](references/chapter_05.md): Test naming, one assertion per test, snapshot testing+- [Chapter 6 - Generics and Dispatch](references/chapter_06.md): Static vs dynamic dispatch, trait objects+- [Chapter 7 - Type State Pattern](references/chapter_07.md): Compile-time state safety, when to use it+- [Chapter 8 - Comments vs Documentation](references/chapter_08.md): When to comment, doc comments, rustdoc+- [Chapter 9 - Understanding Pointers](references/chapter_09.md): Thread safety, Send/Sync, pointer types++## Quick Reference++### Borrowing & Ownership+- Prefer `&T` over `.clone()` unless ownership transfer is required+- Use `&str` over `String`, `&[T]` over `Vec<T>` in function parameters+- Small `Copy` types (≤24 bytes) can be passed by value+- Use `Cow<'_, T>` when ownership is ambiguous++### Error Handling+- Return `Result<T, E>` for fallible operations; avoid `panic!` in production+- Never use `unwrap()`/`expect()` outside tests+- Use `thiserror` for library errors, `anyhow` for binaries only+- Prefer `?` operator over match chains for error propagation++### Performance+- Always benchmark with `--release` flag+- Run `cargo clippy -- -D clippy::perf` for performance hints+- Avoid cloning in loops; use `.iter()` instead of `.into_iter()` for Copy types+- Prefer iterators over manual loops; avoid intermediate `.collect()` calls++### Linting+Run regularly: `cargo clippy --all-targets --all-features --locked -- -D warnings`++Key lints to watch:+- `redundant_clone` - unnecessary cloning+- `large_enum_variant` - oversized variants (consider boxing)+- `needless_collect` - premature collection++Use `#[expect(clippy::lint)]` over `#[allow(...)]` with justification comment.++### Testing+- Name tests descriptively: `process_should_return_error_when_input_empty()`+- One assertion per test when possible+- Use doc tests (`///`) for public API examples+- Consider `cargo insta` for snapshot testing generated output++### Generics & Dispatch+- Prefer generics (static dispatch) for performance-critical code+- Use `dyn Trait` only when heterogeneous collections are needed+- Box at API boundaries, not internally++### Type State Pattern+Encode valid states in the type system to catch invalid operations at compile time:+```rust+struct Connection<State> { /* ... */ _state: PhantomData<State> }+struct Disconnected;+struct Connected;++impl Connection<Connected> {+ fn send(&self, data: &[u8]) { /* only connected can send */ }+}+```++### Documentation+- `//` comments explain *why* (safety, workarounds, design rationale)+- `///` doc comments explain *what* and *how* for public APIs+- Every `TODO` needs a linked issue: `// TODO(#42): ...`+- Enable `#![deny(missing_docs)]` for librariesdiff --git a/.agents/skills/rust-best-practices/references/chapter_01.md b/.agents/skills/rust-best-practices/references/chapter_01.mdnew file mode 100644index 0000000..1269642--- /dev/null+++ b/.agents/skills/rust-best-practices/references/chapter_01.md@@ -0,0 +1,657 @@+# Chapter 1 - Coding Styles and Idioms++## 1.1 Borrowing Over Cloning++Rust's ownership system encourages **borrow** (`&T`) instead of **cloning** (`T.clone()`).+> ❗ Performance recommendation++### ✅ When to `Clone`:++* You need to change the object AND preserve the original object (immutable snapshots).+* When you have `Arc` or `Rc` pointers.+* When data is shared across threads, usually `Arc`.+* Avoid massive refactoring of non performance critical code.+* When caching results (dummy example below):+```rust+fn get_config(&self) -> Config {+ self.cached_config.clone()+}+```+* When the underlying API expects Owned Data.++### 🚨 `Clone` traps to avoid:++* Auto-cloning inside loops `.map(|x| x.clone)`, prefer to call `.cloned()` or `.copied()` at the end of the iterator.+* Cloning large data structures like `Vec<T>` or `HashMap<K, V>`.+* Clone because of bad API design instead of adjusting lifetimes.+* Prefer `&[T]` instead of `Vec<T>` or `&Vec<T>`.+* Prefer `&str` or `&String` instead of `String`.+* Prefer `&T` instead of `T`.+* Clone a reference argument, if you need ownership, make it explicit in the arguments for the caller. Example:+```rust+fn take_a_borrow(thing: &Thing) {+ let thing_cloned = thing.clone(); // the caller should have passed ownership instead+}+```++### ✅ Prefer borrowing:+```rust+fn process(name: &str) {+ println!("Hello {name}");+}++let user = String::from("foo");+process(&user);+```++### ❌ Avoid redundant cloning:+```rust+fn process_string(name: String) {+ println!("Hello {name}");+}++let user = String::from("foo");+process(user.clone()); // Unnecessary clone+```++## 1.2 When to pass by value? (Copy trait)++Not all types should be passed by reference (`&T`). If a type is **small** and it is **cheap to copy**, it is often better to **pass it by value**. Rust makes it explicit via the `Copy` trait.++### ✅ When to pass by value, `Copy`:+* The type **implements** `Copy` (`u32`, `bool`, `f32`, small structs).+* The cost of moving the value is negligible.++```rust+fn increment(x: u32) -> u32 {+ x + 1+}++let num = 1;+let new_num = increment(num); // `num` still usable after this point+```++### ❓ Which structs should be `Copy`?+* When to consider declaring `Copy` on your own types:+* All fields are `Copy` themselves.+* The struct is `small`, up to 2 (maybe 3) words of memory or 24 bytes (each word is 64 bits/8bytes).+* The struct **represents a "plain data object"**, without resorting to ownership (no heap allocations. Example: `Vec` and `Strings`).+* ❗**The type does not also implement `Iterator`.** Even if every field is `Copy`, never put `Copy` and `Iterator` on the same type (see [§1.5](#15-iterator-iter-vs-for)).++❗**Rust Arrays are stack allocated.** Which means they can be copied if their underlying type is `Copy`, but this will be allocated in the program stack which can easily become a stack overflow. More on [Chapter 3 - Stack vs Heap](./chapter_03.md#33-stack-vs-heap-be-size-smart)++For reference, each primitive type size in bytes:++#### Integers:++| Type | Size |+|------------- |---------- |+| i8 u8 | 1 byte |+| i16 u16 | 2 bytes |+| i32 u32 | 4 bytes |+| i64 u64 | 8 bytes |+| isize usize | Arch |+| i128 u128 | 16 bytes |++#### Floating Point:++| Type | Size |+|---------- |---------- |+| f32 | 4 bytes |+| f64 | 8 bytes |+++#### Other:++| Type | Size |+|---------- |---------- |+| bool | 1 byte |+| char | 4 bytes |+++### ✅ Good struct to derive `Copy`:+```rust+#[derive(Debug, Copy, Clone)]+struct Point {+ x: f32,+ y: f32,+ z: f32+}+```++### ❌ Bad struct to derive `Copy`:+```rust+#[derive(Debug, Clone)]+struct BadIdea {+ age: i32,+ name: String, // String is not `Copy`+}+```++### ❓Which Enums should be `Copy`?+* If your enum acts like tags and atoms.+* The enum payloads are all `Copy`.+* **❗Enums size are based on their largest element.**++### ✅ Good Enum to derive+```rust+#[derive(Debug, Copy, Clone)]+enum Direction {+ North,+ South,+ East,+ West,+}+```++## 1.3 Handling `Option<T>` and `Result<T, E>`+Rust 1.65 introduced a better way to safely unpack Option and Result types with the `let Some(x) = … else { … }` or `let Ok(x) = … else { … }` when you have a default `return` value, `continue` or `break` default else case. It allows early returns when the missing case is **expected and normal**, not exceptional.++### ✅ Cases to use each pattern matching for Option and Result+* Use `match` when you want to pattern match against the inner types `T` and `E`+```rust+match self {+ Ok(Direction::South) => { … },+ Ok(Direction::North) => { … },+ Ok(Direction::East) => { … },+ Ok(Direction::West) => { … },+ Err(E::One) => { … },+ Err(E::Two) => { … },+}++match self {+ Some(3|5) => { … }+ Some(x) if x > 10 => { … }+ Some(x) => { … }+ None => { … }+}+```++* Use `match` when your type is transformed into something more complex Like `Result<T, E>` becoming `Result<Option<U>, E>`.+```rust+match self {+ Ok(t) => Ok(Some(t)),+ Err(E::Empty) => Ok(None),+ Err(err) => Err(err),+}+```++* Use `let PATTERN = EXPRESSION else { DIVERGING_CODE; }` when the divergent code doesn't need to know about the failed pattern matches or doesn't need extra computation:+```rust+let Some(&Direction::North) = self.direction.as_ref() else {+ return Err(DirectionNotAvailable(self.direction));+}+```++* Use `let PATTERN = EXPRESSION else { DIVERGING_CODE; }` when you want to break or continue a pattern match+```rust+for x in self {+ let Some(x) = x else {+ continue;+ }+}+```++* Use `if let PATTERN = EXPRESSION else { DIVERGING_CODE; }` when `DIVERGING_CODE` needs extra computation:+```rust+if let Some(x) = self.next() {+ // computation+} else {+ // computation when `None/Err` or not matched+}+```++❗**If you don't care about the value of the `Err` case, please use `?` to propagate the `Err` to the caller.**++### ❌ Bad Option/Result pattern matching:++* Conversion between Result and Option (prefer `.ok()`,`.ok_or()`, and `ok_or_else()`)+```rust+match self {+ Ok(t) => Some(t),+ Err(_) => None+}+```++* `if let PATTERN = EXPRESSION else { DIVERGING_CODE; }` when divergent code is a default or pre-computed value (prefer `let PATTERN = EXPRESSION else { DIVERGING_CODE; }`):+```rust+if let Some(values) = self.next() {+ // computation+ (Some(..), values)+} else {+ (None, Vec::new())+}+```++* Using `unwrap` or `expect` outside tests:+```rust+let port = config.port.unwrap();+```++## 1.4 Prevent Early Allocation++When dealing with functions like `or`, `map_or`, `unwrap_or`, `ok_or`, consider that they have special cases for when memory allocation is required, like creating a new string, creating a collection or even calling functions that manage some state, so they can be replaced with their `_else` counter-part:++### ✅ Good cases++```rust+let x = None;+assert_eq!(x.ok_or(ParseError::ValueAbsent), Err(ParseError::ValueAbsent));++let x = None;+assert_eq!(x.ok_or_else(|| ParseError::ValueAbsent(format!("this is a value {x}"))), Err(ParseError::ValueAbsent));+++let x: Result<_, &str> = Ok("foo");+assert_eq!(x.map_or(42, |v| v.len()), 3);+++let x : Result<_, String> = Ok("foo");+assert_eq!(x.map_or_else(|e|format!("Error: {e}"), |v| v.len()), 3);++let x = "1,2,3,4";+assert_eq!(x.parse_to_option_vec.unwrap_or_else(Vec::new), Ok(vec![1, 2, 3, 4]));+```++### ❌ Bad cases++```rust+let x : Result<_, String> = Ok("foo");+assert_eq!(x.map_or(format!("Error with uninformed content"), |v| v.len()), 3);++let x = "1,2,3,4";+assert_eq!(x.parse_to_option_vec.unwrap_or(Vec::new()), Ok(vec![1, 2, 3, 4])); // could be replaced with `.unwrap_or_default`++let x = None;+assert_eq!(x.ok_or(ParseError::ValueAbsent(format!("this is a value {x}"))), Err(ParseError::ValueAbsent));+```++### Mapping Err++When dealing with Result::Err, sometimes is necessary to log and transform the Err into a more abstract or more detailed error, this can be done with `inspect_err` and `map_err`:++```rust+let x = Err(ParseError::InvalidContent(...));++x+.inspect_err(|err| tracing::error!("function_name: {err}"))+.map_err(|err| GeneralError::from(("function_name", err)))?;+```++## 1.5 Iterator, `.iter` vs `for`++First we need to understand a basic loop with each one of them. Let's consider the following problem, we need to sum all even numbers between 0 and 10 incremented by 1:++* `for`:+```rust+let mut sum = 0;+for x in 0..=10 {+ if x % 2 == 0 {+ sum += x + 1;+ }+}+```++* `iter`:+```rust+let sum: i32 = (0..=10)+ .filter(|x| x % 2 == 0)+ .map(|x| x + 1)+ .sum();+```++> Both versions do the same thing and are correct and idiomatic, but each shines in different contexts.++### When to prefer `for` loops+* When you need **early exits** (`break`, `continue`, `return`).+* **Simple iteration** with side-effects (e.g., logging, IO)+ * logging can be done correctly in `Iterators` using `inspect` and `inspect_err` functions.+* When readability matters more than simplicity or chaining.++#### Example:+```rust+for value in &mut value {+ if *value == 0 {+ break;+ }+ *value += fancy_equation();+}+```++### When to prefer `iterators` loops (`.iter()` and `.into_iter()`)+* When you are `transforming collections` or `Option/Results`.+* You can **compose multiple steps** elegantly.+* No need for early exits.+* You need support for indexed values with `.enumerate`.+```rust+let values: Vec<_> = vec.into_iter()+ .enumerate()+ .filter(|(_index, value)| value % 2 == 0)+ .map(|(index, value)| value % index)+ .collect()+```+* You need to use collections functions like `.windows` or `chunks`.+* You need to combine data from multiple sources and don't want to allocate multiple collections.+* Iterators can be combined with `for` loops:+```rust+for value in vec.iter().enumerate()+ .filter(|(index, value)| value % index == 0) {+ // ...+}++```++> #### ❗REMEMBER: Iterators are Lazy+>+> * `.iter`, `.map`, `.filter` don't do anything until you call its consumer, e.g. `.collect`, `.sum`, `.for_each`.+> * **Lazy Evaluation** means that iterator chains are fused into one loop at compile time.++### 🚨 Anti-patterns to AVOID++* Don't chain without formatting. Prefer each chained function on its own line with the correct indentation (`rustfmt` should take care of this).+* Don't chain if it makes the code unreadable.+* Avoid needlessly collect/allocate of a collection (e.g. vector) just to throw it away later by some larger operation or by another iteration.+* Prefer `iter` over `into_iter` unless you don't need the ownership of the collection.+* Prefer `iter` over `into_iter` for collections that inner type implements `Copy`, e.g. `Vec<T: Copy>`.+* **Never implement (or derive) both `Copy` and `Iterator` on the same type.** Copying an iterator and advancing one copy leaves the other untouched, which silently yields wrong results -- it is a well-known footgun. The standard library hit exactly this: it is why `Range` historically could not be `Copy`, and why the new `core::range` types (stabilized in Rust 1.96) implement `IntoIterator` instead of `Iterator` so they *can* be `Copy`. If you need an iterator on a `Copy` type, implement `IntoIterator` and return a separate iterator struct.+* For summing numbers prefer `.sum` over `.fold`. `.sum` is specialized for summing values, so the compiler knows it can make optimizations on that front, while fold has a blackbox closure that needs to be applied at every step. If you need to sum by an initial value, just add it in the expression `let my_sum = [1, 2, 3].sum() + 3`.++## 1.6 Comments: Context, not Clutter++> "Comments are for why, not what or how"++Well-written Rust code, with expressive types and good naming, often speaks for itself. Many high-quality codebases thrive on **few or no comments**. And that's a good thing.++Still, there are **moments where code alone isn't enough** - when there are performance quirks, external constraints, or non-obvious tradeoffs that require a nudge to the reader. In those cases, a concise comment can prevent hours of head-scratching or searching git history.++### ✅ Good comments++* Safety concerns:+```rust+// SAFETY: We have checked that the pointer is valid and non-null. @Function xyz.+unsafe { std::ptr::copy_nonoverlapping(src, dst, len); }+```++* Performance quirks:+```rust+// This algorithm is a fast square root approximation+const THREE_HALVES: f32 = 1.5;+fn q_rsqrt(number: f32 ) -> f32 {+ let mut i: i32 = number.to_bits() as i32;+i = 0x5F375A86_i32.wrapping_sub(i >> 1);+let y = f32::from_bits(i as u32);+y * (THREE_HALVES - (number * 0.5 * y * y))+}+```++* Clear code beats comments. However, when the why isn't obvious, say it plainly - or link to where:+```rust+// PERF: Generating the root store per subgraph caused high TLS startup latency on MacOS+// This works as a caching alternative. See: [ADR-123](link/to/adr-123)+let subgraph_tls_root_store: RootCertStore = configuration+ .tls+ .subgraph+ .all+ .create_certificate_store()+ .transpose()?+ .unwrap_or_else(crate::services::http::HttpClientService::native_roots_store);+let connector_tls_root_store: RootCertStore = configuration+ .tls+ .connector+ .all+ .create_certificate_store()+ .transpose()?+ .unwrap_or_else(crate::services::http::HttpClientService::native_roots_store);+```++* ❗ More use cases to come in their appropriate sections.++### ❌ Bad comments++* Wall-of-text explanations: long comments and multiline comments+```rust+// Lorem Ipsum is simply dummy text of the printing and typesetting industry.+// Lorem Ipsum has been the industry's standard dummy text ever since the 1500s,+// when an unknown printer took a galley+fn do_something_odd() {+ …+}+```+> Prefer `/// doc` comment if it's describing the function.++* Comments that could be better represented as functions or are plain obvious+```rust+fn computation() {+ // increment i by 1+ i += 1;+}+```++### ✅ Breaking up long functions over commenting them++If you find yourself writing a long comment explaining "what", "how" or "each step" in a function, it might be time to split it. So the suggestion is to refactor. This can be beneficial not only for readability, but testability:++#### ❌ Instead of:+```rust+fn process_request(request: T) {+ // We first need to validate request, because of corner case x, y, z+ // As the payload can only be decoded when they are valid+ // Then we can perform authorization on the payload+ // lastly with the authorized payload we can dispatch to handler+}+```++#### ✅ Prefer+```rust+fn process_request(request: T) -> Result<(), Error> {+ validate_request_headers(&request)?;+ let payload = decode_payload(&request);+ authorize(&payload)?;+ dispatch_to_handler(payload)+}++#[cfg(test)]+mod tests {+ #[test]+ fn validate_request_happy_path() { ... }++ #[test]+ fn validate_request_fails_on_x() { ... }++ #[test]+ fn validate_request_fails_on_y() { ... }++ #[test]+ fn decode_validated_request() { ... }++ #[test]+ fn authorize_payload_xyz() { ... }+}+```++Let **structure** and **naming** replace commentary, and enhance its documentation with **tests as living documentation**.++> ❗ Splitting is about **naming and clarity**, not deduplication. Before extracting a helper to remove *duplicated* lines, check [§1.8](#18-when-to-extract-a-function-and-when-not-to).++### 📝 TODOs are not comments - track them properly++Avoid leaving lingering `// TODO: Lorem Ipsum` comments in the code. Instead:+* Turn them into Jira or Github Issues.+* If needed, to avoid future confusion, reference the issue in the code and the code in the issue.++```rust+// See issue #123: support hyper 2.0+```++This helps keeping the code clean and making sure tasks are not forgotten.++### Comments as Living Documentation++There are a few gotchas when calling comments "living documentation":+* Code evolves.+* Context changes.+* Comments get stale.+* Many large comments make people avoid reading them.+* Team becomes fearful of deleting irrelevant comments.++If you find a comment, **don't trust it blindly**. Read it in context. If it's wrong or outdated, fix or remove it. A misleading comment is worse than no comments at all.++> Comments should bother you - they demand re-verification, just like stale tests.++When deeper justification is needed, prefer to:+* **Link to a Design Doc or an ADR**, business logic lives well in design docs while performance tradeoffs live well in ADRs.+* Move runtime example and usage docs into Rust Docs, `/// doc comment`, where they can be tested and kept up-to-date by tools like `cargo doc`.++> Doc-comments and Doc-testing, `///` and `//!` in [Chapter 8 - Comments vs Documentation](./chapter_08.md)++## 1.7 Use Declarations - "imports"++Different languages have different ways of sorting their imports, in the Rust ecosystem the [standard way](https://github.com/rust-lang/rustfmt/issues/4107) is:++- `std` (`core`, `alloc` would also fit here).+- External crates (what is in your Cargo.toml `[dependencies]`).+- Workspace crates (workspace member crates).+- This module `super::`.+- This module `crate::`.++```rust+// std+use std::sync::Arc;++// external crates+use chrono::Utc;+use juniper::{FieldError, FieldResult};+use uuid::Uuid;++// crate code lives in workspace+use broker::database::PooledConnection;++// super:: / crate::+use super::schema::{Context, Payload};+use super::update::convert_publish_payload;+use crate::models::Event;+```++Some enterprise solutions opt to include their core packages after `std`, so all external packages that start with enterprise name are located before the others:++```rust+// std+use std::sync::Arc;++// enterprise external crates+use enterprise_crate_name::some_module::SomeThing;++// external crates+use chrono::Utc;+use juniper::{FieldError, FieldResult};+use uuid::Uuid;++// crate code lives in workspace+use broker::database::PooledConnection;++// super:: / crate::+use super::schema::{Context, Payload};+use super::update::convert_publish_payload;+use crate::models::Event;+```++One way of not having to manually control this is using the following arguments in your `rustfmt.toml`:++```toml+reorder_imports = true+imports_granularity = "Crate"+group_imports = "StdExternalCrate"+```++> As of Rust version 1.88, it is necessary to execute rustfmt in nightly to correctly reorder code `cargo +nightly fmt`.++## 1.8 When to Extract a Function (and When Not To)++This chapter ([§1.6](#-breaking-up-long-functions-over-commenting-them)) and [Chapter 8](./chapter_08.md#85-replace-comments-with-code) recommend splitting long functions and replacing narrative comments with named helpers. That advice is about **naming and clarity** -- it is *not* a license to hunt down every repeated line. Extraction has a cost: every helper adds indirection, and a **wrong abstraction is much harder to remove than a little duplication**.++> "Duplication is far cheaper than the wrong abstraction." -- [Sandi Metz, The Wrong Abstraction](https://sandimetz.com/blog/2016/1/20/the-wrong-abstraction)++### 📏 The Rule of Three++From [Martin Fowler's *Refactoring*](https://martinfowler.com/books/refactoring.html), attributed to Don Roberts:++> The first time you do something, you just do it. The second time you do something similar, you wince at the duplication, but you do the duplicate thing anyway. The third time you do something similar, you refactor.++Two occurrences of a couple of lines are usually **fine**. Wait for the third before reaching for a helper -- by then you will know what the abstraction actually *is*, instead of guessing at it.++### 🧠 DRY is about knowledge, not text++[DRY](https://en.wikipedia.org/wiki/Don%27t_repeat_yourself) (*The Pragmatic Programmer*) says every piece of **knowledge** should have a single representation. It does **not** say "no two code fragments may look alike". Two blocks that *happen* to look the same today, but represent **different decisions**, will evolve in different directions. Forcing them into one helper couples code that should be free to diverge -- this is **coincidental duplication**, and deduplicating it is how wrong abstractions are born.++### 🧪 Examples++How these principles play out in code:++#### ✅ Coincidental duplication -- leave it inline:+```rust+// Similar-looking lines, but the `.env` and `.toml` formats are+// unrelated decisions that will evolve independently:+writeln!(env_file, "{key}={value}")?;+// ... elsewhere ...+writeln!(toml_file, "{key} = \"{value}\"")?;+```++#### ❌ Deduplicating it forces a flag parameter -- the classic smell:+```rust+// One helper, two behaviors, and a `bool` to pick between them:+fn write_entry(out: &mut impl Write, key: &str, value: &str, quoted: bool) -> io::Result<()> {+ if quoted {+ writeln!(out, "{key} = \"{value}\"")+ } else {+ writeln!(out, "{key}={value}")+ }+}+```++Every new variant will grow another parameter or branch. And the `bool` is a smell in its own right: `write_entry(out, key, value, true)` tells the reader nothing at the call site -- Martin Fowler calls this a [Flag Argument](https://martinfowler.com/bliki/FlagArgument.html). When a mode selector is genuinely warranted, a two-variant enum (`Quoting::Quoted`) keeps call sites readable, and Clippy's [`fn_params_excessive_bools`](https://rust-lang.github.io/rust-clippy/master/index.html#fn_params_excessive_bools) lints against accumulating them. No enum rescues *this* design, though: its variants would exist only to encode the callers' differences.++#### ✅ Shared knowledge -- extract it:+```rust+// The definition of "retryable" is ONE business decision used in many+// places. If it changes, it must change everywhere at once:+fn is_retryable(status: StatusCode) -> bool {+ status == StatusCode::TOO_MANY_REQUESTS || status.is_server_error()+}+```++### 🔧 Unwinding a wrong abstraction++If you find yourself maintaining an abstraction like `write_entry`, [Sandi Metz's advice](https://sandimetz.com/blog/2016/1/20/the-wrong-abstraction) is to **unwind it, not patch it**:++1. **Re-inline** the helper's body into every caller, substituting each call site's concrete arguments.+2. **Reduce** each call site -- with the parameters now literal, dead branches and unused generality fall away.+3. **Reevaluate** what the callers *actually* share, now that every one of them is explicit.+4. **Reconstruct** one or more abstractions from what remains -- or none, if the sharing turns out to be coincidental.++> 🤖 Doing this by hand is tedious, which is why wrong abstractions survive on sunk cost. For an AI coding agent, unwinding is fast, mechanical work -- ask for it explicitly instead of letting the agent keep patching a helper that fights back.++### ✅ Extract a function when:+* The logic appears in **3+ places** *and* represents the **same decision** (Rule of Three).+* The name **adds meaning** the code alone does not (`is_retryable`, `authorize`) -- rather than restating it (`add_one_to_counter`).+* It produces a **unit worth testing** in isolation (see [§1.6](#-breaking-up-long-functions-over-commenting-them)).+* It hides genuine complexity behind a **small, honest signature** -- few parameters, no flags.++### ❌ Don't extract when:+* It is **1-2 lines used in fewer than 3 places** -- the helper is pure indirection.+* The call sites are only *almost* identical, and unifying them requires **flag parameters** or extra branches.+* The only motivation is **line count**. A single-caller helper pays off when its *name* clarifies intent ([§1.6](#-breaking-up-long-functions-over-commenting-them), [§8.5](./chapter_08.md#85-replace-comments-with-code)) -- not when it merely relocates code.+* You are **guessing** at a future abstraction. Wait for the third usage to reveal its real shape.++### 🧫 Test code: readability beats DRY++In tests, be **even more tolerant of duplication**. The Google Testing Blog calls this [DAMP -- "Descriptive And Meaningful Phrases"](https://testing.googleblog.com/2019/12/testing-on-toilet-tests-too-dry-make.html) ([*Software Engineering at Google*, ch. 12](https://abseil.io/resources/swe-book/html/ch12.html)): each test should read as a **self-contained story** -- setup, action, assertion -- without the reader chasing helpers to reconstruct what actually happened.++* **Tests have no tests.** Logic moved into a shared helper (loops, branches, clever parametrization) is itself untested -- a bug there silently weakens every test built on it.+* **A failing test should be diagnosable on sight.** The reader is usually debugging a broken build; make the expected behavior visible in the test body, not three helpers away.+* **Shared test helpers couple unrelated tests.** Change one behavior and dozens of tests fail at once -- for the helper's sake, not the behavior's.++Where to draw the line:+* ✅ Share **setup and fixtures** -- a shared setup function or `rstest` cases, as [Chapter 5](./chapter_05.md#51-tests-as-living-documentation) recommends. Constructing a test server twice is boilerplate, not knowledge.+* ❌ Keep each test's **action and assertion inline**, even when they look repetitive across tests.++> 🚨 When in doubt, **prefer duplication**. A duplicated line is trivially fixed later; a wrong abstraction accretes parameters and conditionals, because each maintainer keeps patching it instead of undoing it.diff --git a/.agents/skills/rust-best-practices/references/chapter_02.md b/.agents/skills/rust-best-practices/references/chapter_02.mdnew file mode 100644index 0000000..8fbd985--- /dev/null+++ b/.agents/skills/rust-best-practices/references/chapter_02.md@@ -0,0 +1,117 @@+# Chapter 2 - Clippy and Linting Discipline++Be sure to have `cargo clippy` installed with your rust compiler, run `cargo clippy -V` in your terminal for a rust project and you should get something like this `clippy 0.1.86 (05f9846f89 2025-03-31)`. If terminal fails to show a clippy version, please run the following code `rustup update && rustup component add clippy`.++Clippy documentation can be found [here](https://doc.rust-lang.org/clippy/usage.html).++## 2.1 Why care about linting?++Rust compiler is a powerful tool that catches many mistakes. However, some more in-depth analysis require extra tools, that is where `cargo clippy` comes into play. Clippy checks for:+* Performance pitfalls.+* Style issues.+* Redundant code.+* Potential bugs.+* Non-idiomatic Rust.++## 2.2 Always run `cargo clippy`++Add the following to your daily workflow:++```shell+$ cargo clippy --all-targets --all-features --locked -- -D warnings+```++* `--all-targets`: checks library, tests, benches and examples.+* `--all-features`: checks code with all features enabled; it does not auto-solve conflicting features.+* `--locked`: Requires `Cargo.lock` to be up-to-date, can be solved with `$ cargo update`.+* `-D warnings`: treats warnings as errors++Potential additional elements to add:++* `-- -W clippy::pedantic`: lints which are rather strict or have occasional false positives.+* `-- -W clippy::nursery`: Optionally can be added to check for new lints that are still under development.+* ❗ Add this to your Makefile, Justfile, xtask or CI Pipeline.++> Example at ApolloGraphQL+>+> In the `Router` project there is a `xtask` configured for linting that can be executed with `cargo xtask lint`.++## 2.3 Important Clippy Lints to Respect++| Lint Name | Why | Link |+| --------- | ----| -----|+| `redundant_clone` | Detects unnecessary `clones`, has performance impact | [link (nursery + perf)](https://rust-lang.github.io/rust-clippy/master/#redundant_clone) |+| `needless_borrow` group | Removes redundant `&` borrowing | [link (style)](https://rust-lang.github.io/rust-clippy/master/#needless_borrow) |+| `map_unwrap_or` / `map_or` | Simplifies nested `Option/Result` handling | [`map_unwrap_or`](https://rust-lang.github.io/rust-clippy/master/#map_unwrap_or) [`unnecessary_map_or`](https://rust-lang.github.io/rust-clippy/master/#unnecessary_map_or) [`unnecessary_result_map_or_else`](https://rust-lang.github.io/rust-clippy/master/#unnecessary_result_map_or_else) |+| `manual_ok_or` | Suggest using `.ok_or_else` instead of `match` | [link (style)](https://rust-lang.github.io/rust-clippy/master/#manual_ok_or) |+| `large_enum_variant` | Warns if an enum has very large variant which is bad for memory. Suggests `Boxing` it | [link (perf)](https://rust-lang.github.io/rust-clippy/master/#large_enum_variant) |+| `unnecessary_wraps` | If your function always returns `Some` or `Ok`, you don't need `Option`/`Result` | [link (pedantic)](https://rust-lang.github.io/rust-clippy/master/#unnecessary_wraps) |+| `clone_on_copy` | Catches accidental `.clone()` on `Copy` types like `u32` and `bool` | [link (complexity)](https://rust-lang.github.io/rust-clippy/master/#clone_on_copy) |+| `needless_collect` | Prevents collecting and allocating an iterator, when allocation is not needed | [link (nursery)](https://rust-lang.github.io/rust-clippy/master/#needless_collect) |++## 2.4 Fix warnings, don't silence them!++**NEVER** just `#[allow(clippy::lint_something)]` unless:++* You **truly understand** why the warning happens and you have a reason why it is better that way.+* You **document** why it is being ignored.+* ❗ Don't use `allow`, but `expect`, it will give a warning in case the lint is not true anymore, `#[expect(clippy::lint_something)]`.++### Example:++```rust+// Faster matching is preferred over size efficiency+#[expect(clippy::large_enum_variant)]+enum Message {+ Code(u8),+ Content([u8; 1024]),+}+```++> The fix would be:+>+> ```rust+> // Faster matching is preferred over size efficiency+> #[expect(clippy::large_enum_variant)]+> enum Message {+> Code(u8),+> Content(Box<[u8; 1024]>),+> }+> ```++### Handling false positives++Sometimes Clippy complains even when your code is correct, in those cases there are two solutions:+1. Try to refactor the code, so it improves the warning.+2. **Locally** override the lint with `#[expect(clippy::lint_name)]` and a comment with the reason.+3. Avoid global overrides, unless it is core crate issue, a good example of this is the Bevy Engine that has a set of lints that should be allowed by default.++## 2.5 Configure workspace/package lints++In your `Cargo.toml` file it is possible to determine which lints and their priorities over each other. In case of 2 or more conflicting lints, the higher priority one will be chosen. Example configuration for a package:++```toml+[lints.rust]+future-incompatible = "warn"+nonstandard_style = "deny"++[lints.clippy]+all = { level = "deny", priority = 10 }+redundant_clone = { level = "deny", priority = 9 }+manual_while_let_some = { level = "deny", priority = 4 }+pedantic = { level = "warn", priority = 3 }+```++And for a workspace:++```toml+[workspace.lints.rust]+future-incompatible = "warn"+nonstandard_style = "deny"++[workspace.lints.clippy]+all = { level = "deny", priority = 10 }+redundant_clone = { level = "deny", priority = 9 }+manual_while_let_some = { level = "deny", priority = 4 }+pedantic = { level = "warn", priority = 3 }+```\ No newline at end of filediff --git a/.agents/skills/rust-best-practices/references/chapter_03.md b/.agents/skills/rust-best-practices/references/chapter_03.mdnew file mode 100644index 0000000..2613314--- /dev/null+++ b/.agents/skills/rust-best-practices/references/chapter_03.md@@ -0,0 +1,211 @@+# Chapter 3 - Performance Mindset++The **golden rule** of performance work:++> Don't guess, measure.++Rust code is often already pretty fast - don't "optimize" without evidence. Optimize only after finding bottlenecks.++### A good first steps+* Use `--release` flag on your builds (might sound dummy, but it is quite common to hear people complaining that their Rust code is slower than their X language code, and 99% of the time is because they didn't use the `--release` flag).+* `$ cargo clippy -- -D clippy::perf` gives you important tips on best practices for performance.+* [`cargo bench`](https://doc.rust-lang.org/cargo/commands/cargo-bench.html) is a cargo tool to create micro-benchmarks and test different code solutions. Write a test scenario and bench your solution against the original code, if your improvement is larger than 5%, might be a good performance improvement.+* [`cargo flamegraph`](https://github.com/flamegraph-rs/flamegraph) a powerful profiler for Rust code. For MacOS, [samply](https://github.com/mstange/samply) might be a better DX option.++> #### Further reading on Benchmarking:+> - [How to build a Custom Benchmarking Harness in Rust](https://bencher.dev/learn/benchmarking/rust/custom-harness/)+++## 3.1 Flamegraph++Flamegraph helps you visualize how much time CPU spent on each task.++```shell+# Installing flamegraph+cargo install flamegraph++# cargo support provided through the cargo-flamegraph binary!+# defaults to profiling cargo run --release+cargo flamegraph++# by default, `--release` profile is used,+# but you can override this:+cargo flamegraph --dev++# if you'd like to profile a specific binary:+cargo flamegraph --bin=stress2++# Profile unit tests.+# Note that a separating `--` is necessary if `--unit-test` is the last flag.+cargo flamegraph --unit-test -- test::in::package::with::single::crate+cargo flamegraph --unit-test crate_name -- test::in::package::with::multiple:crate++# Profile integration tests.+cargo flamegraph --test test_name++# Run criterion benchmark+# Note that the last --bench is required for `criterion 0.3` to run in benchmark mode, instead of test mode.+cargo flamegraph --bench some_benchmark --features some_features -- --bench++# Run workspace example+cargo flamegraph --example some_example --features some_features+```++> ❗ Always run your profiles with `--release` enabled, the `--dev` flag isn't realistic as it doesn't have optimizations enabled.++The result will look like a flame graph where:+++* The `y-axis` shows the **stack depth number**. When looking at a flamegraph, the main function of your program will be closer to the bottom, and the called functions will be stacked on top, with the functions that they call stacked on top of them.++* The `width of each box` shows the **total time that that function** is on the CPU or is part of the call stack. If a function's box is wider than others, that means that it consumes more CPU per execution than other functions, or that it is called more than other functions.++> ❗ The **color of each box** isn't significant, and **is chosen at random**.++### 🚨 Remember+* Thick stacks: heavy CPU usage+* Thin stacks: low intensity (cheap)++## 3.2 Avoid Redundant Cloning++> Cloning is cheap... **until it isn't**++In sections [Borrowing over Cloning](./chapter_01.md#11-borrowing-over-cloning) and [Important Clippy lints to respect](./chapter_02.md#23-important-clippy-lints-to-respect) we mentioned the impacts of cloning and the relevant clippy lint [`redundant_clone`](https://rust-lang.github.io/rust-clippy/master/#redundant_clone), so in this section we will explore a bit "when to pass ownership".++* 🚨 If you really need to clone, leave it to the last moment.++### When to pass ownership?++* Only `.clone()` if you truly need a new owned copy. A few examples:+ * Crate API Design requires owned data.+ * Have overloaded `std::ops` but still need ownership to the old data:+ ```rust+ use std::ops::Add;++ #[derive(Debug, Copy, Clone, PartialEq)]+ struct Point {+ x: i32,+ y: i32,+ }++ impl Add for Point {+ type Output = Self;++ fn add(self, other: Self) -> Self {+ Self {+ x: self.x + other.x,+ y: self.y + other.y,+ }+ }+ }++ assert_eq!(Point { x: 1, y: 0 } + Point { x: 2, y: 3 },+ Point { x: 3, y: 3 });+ ```+ * Need to do comparison snapshots or due to API you need multiple owned instances of the data.+ ```rust+ fn snapshot(a: &MyValue, b:&MyValue) -> MyValueDiff {+ a - b+ }++ impl Sub for MyValue {+ type Output = MyValueDiff;++ fn sub(self, other: Self) -> MyValue {+ ...+ }+ }++ fn main() {+ let mut a = MyValue::default();+ let b = a.clone();++ a.magical_update();+ println!("{:?}", snapshot(&a, &b));+ }+ ```+* You have reference counted pointers (`Arc, Rc`).+* You have small structs that are too big to `Copy` but as costly as `std::collections`. An example is HTTP client like `hyper_util::client::legacy::Client` that cloning allows you to share the connection pool.+* You have a chained struct modifier that needs owned mutation, some **builders** require owned mutation, but most custom builders can be done with `pub fn with_xyz(&mut self, value: Xyz) -> &mut Self`.+```rust+// Inline `HashMap` insertion extension++fn insert_owned(mut self, key: K, value: V) -> Self {+ self.insert(key, value);+ self+}++```+* Ownership can also be a good way to model business logic / state. For example:+```rust+let not_validated: String = ...;// some user source+let validated = Validate::try_from(not_validated)?;+// Technically that `try_from` maybe didn't need ownership, but taking it lets us model intent+```++### When **NOT** to pass ownership?++* Prefer API designs that take reference (`fn process(values: &[T])`), instead of ownership (`fn process(values: Vec<T>)`).+* If you only need read access to elements, prefer `.iter` or slices:+```rust+for item in &some_vec {+ ...+}+```+* You need to mutate data that is owned by another thread, use `&mut MyStruct`.++### Use `Cow` for `Maybe Owned` data++Sometimes you don't actually need owned data, but that is not clear from the API perspective, so using [`std::borrow::Cow`](https://doc.rust-lang.org/std/borrow/enum.Cow.html) is a way to efficiently address this case:++```rust+use std::borrow::Cow;++fn hello_greet(name: Cow<'_, str>) {+ println!("Hello {name}");+}++hello_greet(Cow::Borrowed("Julia"));+hello_greet(Cow::Owned("Naomi".to_string()));+```++## 3.3 Stack vs Heap: Be size-smart!++### ✅ Good Practices++* Keep small types (`impl Copy`, `usize`, `bool`, etc) **on the stack**.+* Avoid passing huge types (`> 512 bytes`) by value or transferring ownership. Prefer pass by reference (e.g. `&T` and `&mut T`).+* Heap allocate recursive data structures:+```rust+enum OctreeNode<T> {+ Node(T),+ Children(Box<[Node<T>; 8]>),+}+```+* Return small types by value, types that implement `Copy` or a cheaply Cloned are efficient to return by value (e.g. `struct Vector2 {x: f32, y: f32}`).++### ❗ Be Mindful++* Only use `#[inline]` when benchmark proves beneficial, Rust is already pretty good at inlining **without** hints.+* Avoid massive stack allocations, box them. Example `let buffer: Box<[u8; 65536]> = Box::new(..)` would first allocate `[u8; 65536]` on the stack then box it, a non-const solution to this would be `let buffer: Box<[u8]> = vec![0; 65536].into_boxed_slice()`.+* For large `const` arrays, considering using [crate smallvec](https://docs.rs/smallvec/latest/smallvec/) as it behaves like an array, but is smart enough to allocate large arrays on the heap.++## 3.4 Iterators and Zero-Cost Abstractions++Rust iterators are lazy, but eventually compiled away into very efficient tight loops that are only called when consumed. Chaining `.filter()`, `.map()`, `.rev()`, `.skip()`, `.take()`, `.collect()` usually doesn't cost extra and the compiler can reason well enough how to optimize them.+* Prefer `iterators` over manual `for` loops when working with collections, the compiler can optimize them better than manually doing it.+* Calling `.iter()` only creates a **reference** to the original collection, this allows you to hold multiple iterators of the same collection.++#### ❗ Avoid creating intermediate collections unless it is really needed:++* Consider that `process` accepts an `iterator`.+* ❌ BAD - useless intermediate collection:+```rust+let doubled: Vec<_> = items.iter().map(|x| x * 2).collect();+process(doubled);+```+* ✅ GOOD - pass the iterator (`fn process(arg: impl Iterator<Item = u32>)`):+```rust+let doubled_iter = items.iter().map(|x| x * 2);+process(doubled_iter);+```\ No newline at end of filediff --git a/.agents/skills/rust-best-practices/references/chapter_04.md b/.agents/skills/rust-best-practices/references/chapter_04.mdnew file mode 100644index 0000000..fb252f4--- /dev/null+++ b/.agents/skills/rust-best-practices/references/chapter_04.md@@ -0,0 +1,181 @@+# Chapter 4 - Errors Handling++Rust enforces a strict error handling approach, but *how* you handle them defines where your code feels ergonomic, consistent and safe - as opposed to cryptic and painful. This chapter dives into best practices for modeling and managing fallible operations across libraries and binaries.++> Even if you decide to crash your application with `unwrap` or `expect`, Rust forces you to declare that intentionally.++## 4.1 Prefer `Result`, avoid panic 🫨++Rust has a powerful type that wraps fallible data, [`Result`](https://doc.rust-lang.org/std/result/), this allows us to handle Error cases according to our needs and manage the state of the application based on that.++* If your function can fail, prefer to return a `Result`:+```rust+fn divide(x: f64, y: f64) -> Result<f64, DivisionError> {+ if y == 0.0 {+ Err(DivisionError::DividedByZero)+ } else {+ Ok(x / y)+ }+}+```++* Use `panic!` only in unrecoverable conditions - typically tests, assertions, bugs or a need to crash the application for some explicit reason.+* There are 3 relevant macros that can replace `panic!` in appropriate conditions:+ * `todo!`, similar to panic, but alerts the compiler that you are aware that there is code missing.+ * `unreachable!`, you have reasoned about the code block and are sure that condition `xyz` is not possible and if ever becomes possible you want to be alerted.+ * `unimplemented!`, specially useful for alerting that a block is not yet implemented with a reason.++## 4.2 Avoid `unwrap`/`expect` in Production++Although `expect` is preferred to `unwrap`, as it can have context, they should be avoided in production code as there are smarter alternatives to them. Considering that, they should be used in the following scenarios:+- In tests, assertions or test helper functions.+- When failure is impossible.+- When the smarter options can't handle the specific case.++### 🚨 Alternative ways of handling `unwrap`/`expect`:++* If your `Result` (or `Option`) can have a predefined early return value in case of `Result::Err`, that doesn't need to know the `Err` value, use `let Ok(..) = else { return ... }` pattern, as it helps with flatten functions:+```rust+let Ok(json) = serde_json::from_str(&input) else {+ return Err(MyError::InvalidJson);+}+```+* If your `Result` (or `Option`) needs error recovery in case of `Result::Err`, that doesn't need to know the `Err` value, use `if let Ok(..) else { ... }` pattern:+```rust+if let Ok(json) = serde_json::from_str(&input) else {+ ...+} else {+ Err(do_something_with_input(&input))+}+```+* Functions that can have to handle `Option::None` values are recommended to return `Result<T, E>`, where `E` is a crate or module level error, like the examples above.+* Lastly `unwrap_or`, `unwrap_or_else` or `unwrap_or_default`, these functions help you create alternative exits to unwrap that manage the uninitialized values.++## 4.3 `thiserror` for Crate level errors++Deriving Error manually is verbose and error prone, the rust ecosystem has a really good crate to help with this, `thiserror`. It allows you to create error types that easily implement `From` trait as well as easy error message (`Display`), improving developer experience while working seamlessly with `?` and integrating with `std::error::Error`:++```rust+#[derive(Debug, thiserror::Error)]+pub enum MyError {+ #[error("Network Timeout")]+ Timeout,+ #[error("Invalid data: {0}")]+ InvalidData(String),+ #[error(transparent)]+ Serialization(#[from] serde_json::Error),+ #[error("Invalid request information. Header: {headers}, Metadata: {metadata}")]+ InvalidRequest {+ headers: Headers,+ metadata: Metadata+ }+}+```++### Error Hierarchies and Wrapping++For layered systems the best practice is to use nested `enum/struct` errors with `#[from]`:++```rust+use crate::database::DbError;+use crate::external_services::ExternalHttpError;++#[derive(Debug, thiserror::Error)]+pub enum ServiceError {+ #[error("Database handler error: {0}")]+ Db(#[from] DbError),+ #[error("External services error: {0}")]+ ExternalServices(#[from] ExternalHttpError)++}+```++## 4.4 Reserve `anyhow` for Binaries++`anyhow` is an amazing crate, and quite useful for projects that are beginning and need accelerated speed. However, there is a turning point where it just painfully propagates through your code, considering this, `anyhow` is recommended only for **binaries**, where ergonomic error handling is needed and there is no need for precise error types:++```rust+use anyhow::{Context, Result, anyhow};++fn main() -> Result<Config> {+ let content = std::fs::read_to_string("config.json")+ .context("Failed to read config file")?;+ Config::from_str(&content)+ .map_err(|err| anyhow!("Config parsing error: {err}"))+}+```++### 🚨 `Anyhow` Gotchas++* Keeping the `context` and `anyhow` strings up-to-date in all code base is harder than keeping `thiserror` messages as you don't have a single point of entry.+* `anyhow::Result` erases context that a caller might need, so avoid using it in a library.+* test helper functions can use `anyhow` with little to no issues.++## 4.5 Use `?` to Bubble Errors++Prefer using `?` over verbose alternatives like `match` chains:+```rust+fn handle_request(req: &Request) -> Result<ValidatedRequest, RequestValidationError> {+ validate_headers(req)?;+ validate_body_format(req)?;+ validate_credentials(req)?;+ let body = Body::try_from(req)?;++ Ok(ValidatedRequest::try_from((req, body))?)+}+```++> In case error recovery is needed, use `or_else`, `map_err`, `if let Ok(..) else`. To **inspect or log your error**, use `inspect_err`.++## 4.6 Unit Test should exercise errors++While many errors don't implement PartialEq and Eq, making it hard to do direct assertions between them, it is possible to check the error messages with `format!` or `to_string()`, making the errors meaningful and test validated:++```rust+#[test]+fn error_does_not_implement_partial_eq() {+ let err = divide(10., 0.0).unwrap_err();+ assert_eq!(err.to_string(), "division by zero");+}++#[test]+fn error_implements_partial_eq() {+ let err = process(my_value).unwrap_err();++ assert_eq!(+ err,+ MyError {+ ..+ }+ )+}+```++## 4.7 Important Topics++### Custom Error Structs++Sometimes you don't need an enum to handle your errors, as there is only one type of error that your module can have. This can be solved with `struct Errors`:++```rust+#[derive(Debug, thiserror::Error, PartialEq)]+#[error("Request failed with code `{code}`: {message}")]+struct HttpError {+ code: u16,+ message: String+}+```++### Async Errors++When using async runtimes, like Tokio, make sure that your errors implement `Send + Sync + 'static` where needed, specially in tasks or across `.await` boundaries:++```rust+#[tokio::main]+async fn main() -> Result<(), Box<dyn std::error::Error + Send + Sync>> {+ ...+ Ok(())+}+```++> Avoid `Box<dyn std::error::Error>` in libraries unless it is really needed\ No newline at end of filediff --git a/.agents/skills/rust-best-practices/references/chapter_05.md b/.agents/skills/rust-best-practices/references/chapter_05.mdnew file mode 100644index 0000000..20a39b8--- /dev/null+++ b/.agents/skills/rust-best-practices/references/chapter_05.md@@ -0,0 +1,390 @@+# Chapter 5 - Automated Testing++> Tests are not just for correctness. They are the first place people look to understand how your code works.++* Tests in rust are declared with the attribute macro `#[test]`. Most code editors can compile and run the functions declared under the macro individually or blocks of them.+* Test can have special compilation flags with `#[cfg(test)]`. Also executable in code editors if it contained `#[test]`, it is a good way to mock complicated functions or override traits.++## 5.1 Tests as Living Documentation++In Rust, as in many other languages, tests often show how the functions are meant to be used. If a test is clear and targeted, it's often more helpful than reading the function body, when combined with other tests, they serve as living documentation.++### Use descriptive names++> In the unit test name we should see the following:+> * `unit_of_work`: which *function* we are calling. The **action** that will be executed. This is often the name of the test `mod` where the function is being tested.+```rust+#[cfg(test)]+mod test {+ mod function_name {+ #[test]+ fn returns_y_when_x() { ... }+ }+}+```+> * `expected_behavior`: the set of **assertions** that we need to verify that the test works.+> * `state_that_the_test_will_check`: the general **arrangement**, or setup, of the specific test case.++#### ❌ Don't use a generic name for a test+```rust+#[test]+fn test_add_happy_path() {+ assert_eq!(add(2, 2), 4);+}+```+#### ✅ Use a name which reads like a sentence, describing the desired behavior+> Alternatively, if your function has too many tests, you can blob them together in a `mod`, it makes it easier to read and navigate.++```rust+// OPTION 1+#[test]+fn process_should_return_blob_when_larger_than_b() {+ let a = setup_a_to_be_xyz();+ let b = Some(2);+ let expected = MyExpectedStruct { ... };++ let result = process(a, b).unwrap();++ assert_eq!(result, expected);+}++// OPTION 2+mod process {+ #[test]+ fn should_return_blob_when_larger_than_b() {+ let a = setup_a_to_be_xyz();+ let b = Some(2);+ let expected = MyExpectedStruct { ... };++ let result = process(a, b).unwrap();++ assert_eq!(result, expected);+ }+}+```++> When executing `cargo test` the test output for each option will look like:+> Option 1: `process_should_return_blob_when_larger_than_b`.+> Option 2: `process::should_return_blob_when_larger_than_b`.++### Use modules for organization++Most IDEs can run a single module of tests all together.+The test name in the output will also contain the name of the module.+Together, that means you can use the module name to group related tests together:++```rust+#[cfg(test)]+mod test { // IDEs will provide a ▶️ button here++ mod process {+ #[test] // IDEs will provide a ▶️ button here+ fn returns_error_xyz_when_b_is_negative() {+ let a = setup_a_to_be_xyz();+ let b = Some(-5);+ let expected = MyError::Xyz;++ let result = process(a, b).unwrap_err();++ assert_eq!(result, expected);+ }++ #[test] // IDEs will provide a ▶️ button here+ fn returns_invalid_input_error_when_a_and_b_not_present() {+ let a = None;+ let b = None;+ let expected = MyError::InvalidInput;++ let result = process(a, b).unwrap_err();++ assert_eq!(result, expected);+ }+ }+}+```++### Only test one behavior per function++To keep tests clear, they should describe _one_ thing that the unit does.+This makes it easier to understand why a test is failing.++#### ❌ Don't test multiple things in the same test+```rust+fn test_thing_parser(...) {+ assert!(Thing::parse("abcd").is_ok());+ assert!(Thing::parse("ABCD").is_err());+}+```++#### ✅ Test one thing per test+```rust+#[cfg(test)]+mod test_thing_parser {+ #[test]+ fn lowercase_letters_are_valid() {+ assert!(+ Thing::parse("abcd").is_ok(),+ // Works like `eprintln`, `format` and `println` macros+ "Thing parse error: {:?}",+ Thing::parse("abcd").unwrap_err()+ );+ }++ #[test]+ fn capital_letters_are_invalid() {+ assert!(Thing::parse("ABCD").is_err());+ }+}+```++> `Ok` scenarios should have an `eprintln` of the `Err` case.++### Use very few, ideally one, assertion per test++When there are multiple assertions per test, it's both harder to understand the intended behavior and+often requires many iterations to fix a broken test, as you work through assertions one by one.++❌ Don't include many assertions in one test:++```rust+#[test]+fn test_valid_inputs() {+ assert!(the_function("a").is_ok());+ assert!(the_function("ab").is_ok());+ assert!(the_function("ba").is_ok());+ assert!(the_function("bab").is_ok());+}+```++If you are testing separate behaviors, make multiple tests each with descriptive names.+To avoid boilerplate, either use a shared setup function or [rstest](https://crates.io/crates/rstest) cases *with descriptive test names*:+```rust+#[rstest]+#[case::single("a")]+#[case::first_letter("ab")]+#[case::last_letter("ba")]+#[case::in_the_middle("bab")]+fn the_function_accepts_all_strings_with_a(#[case] input: &str) {+ assert!(the_function(input).is_ok());+}+```++> Considerations when using `rstest`+>+> * It's harder for both IDEs and humans to run/locate specific tests.+> * Expectation vs condition naming is now visually inverted (expectation first).++> ❗ Share **setup**, not the test itself: keep each test's action and assertion inline, even when repetitive. Tests tolerate duplication better than production code -- see [Chapter 1, §1.8](./chapter_01.md#-test-code-readability-beats-dry).++## 5.2 Add Test Examples to your Docs++We will deep dive into docs at a later stage, so in this section we will just briefly go over how to add tests to your docs. Rustdoc can turn examples into executable tests using `///` with a few advantages:++* These tests run with `cargo test` **BUT NOT** `cargo nextest run`. If using `nextest`, make sure to run `cargo t --doc` separately.+* They serve both as documentation and correctness checks, and are kept up to date by changes, due to the fact that the compiler checks them.+* No extra testing boilerplate. You can easily hide test sections by prefixing the line with `#`.+* ❗ There is no issue if you have test duplication between doc-tests and other non-public facing tests.++```rust+/// Helper function that adds any two numeric values together.+/// This function reasons about which would be the correct type to parse based on the type+/// and the size of the numeric value.+///+/// # Examples+///+/// ```rust+/// # use crate_name::generic_add;+/// use num::numeric;+///+/// # assert_eq!(+/// generic_add(5.2, 4) // => 9.2+/// # , 9.2)+///+/// # assert_eq!(+/// generic_add(2, 2.0) // => 4+/// # , 4)+/// ```+```++This documentation code would look like:+```rust+use num::numeric;++generic_add(5.2, 4) // => 9.2+generic_add(2, 2.0) // => 4+```++## 5.3 Unit Test vs Integration Tests vs Doc tests++As a general rule, without delving into *test pyramid naming*, rust has 3 sets of tests:++### Unit Test++Tests that go in the **same module** as the **tested unit** was declared, this allows the test runner to have visibility over private functions and parent `use` declarations. They can also consume `pub(crate)` functions from other modules if needed. Unit tests can be more focused on **implementation and edge-cases checks**.++* They should be as simple as possible, testing one state and one behavior of the unit. KISS.+* They should test for errors and edge cases.+* Different tests of the same unit can be combined under a single `#[cfg(test)] mod test_unit_of_work {...}`, allowing multiple submodules for different `units_of_work`.+* Try to keep external states/side effects to your API to minimum and focus those tests on the `mod.rs` files.+* Tests that are not yet fully implemented can be ignored with the `#[ignore = "optional message"]` attribute.+* Tests that intentionally panic should be annotated with the attribute `#[should_panic]`.++```rust+#[cfg(test)]+mod unit_of_work_tests {+ use super::*;++ #[test]+ fn unit_state_behavior() {+ let expected = ...;+ let result = ...;+ assert_eq!(result, expected, "Failed because {}", result - expected);+ }+}+```++### Integration Tests++Tests that go under the `tests/` directory, they are entirely external to your library and use the same code as any other code would use, not have access to private and crate level functions, which means they can **only test** functions on your **public API**.++> Their purpose is to test whether many parts of the code work together correctly, units of code that work correctly on their own could have problems when integrated.++* Test for happy paths and common use cases.+* Allow external states and side effects, [testcontainers](https://rust.testcontainers.org/) might help.+* if testing binaries, try to break **executable** and **functions** into `src/main.rs` and `src/lib.rs`, respectively.++```+├── Cargo.lock+├── Cargo.toml+├── src+│ └── lib.rs+└── tests+ ├── mod.rs+ ├── common+ │ └── mod.rs+ └── integration_test.rs+```++### Doc Testing++As mentioned in section [5.2](#52-add-test-examples-to-your-docs), doc tests should have happy paths, general public API usage and more powerful attributes that improve documentation, like custom CSS for the code blocks.++### Attributes:++* `ignore`: tells rust to ignore the code, usually not recommended, if you want just a code formatted text, use `text`.+* `should_panic`: tells the rust compiler that this example block will panic.+* `no_run`: compiles but doesn't execute the code, similar to `cargo check`. Very useful when dealing with side-effects for documentation.+* `compile_fail`: Test rustdoc that this block should cause a compilation fail, important when you want to demonstrate wrong use cases.++## 5.4 How to `assert!`++Rust comes with 2 macros to make assertions:+* `assert!` for asserting boolean values like `assert!(value.is_ok(), "'value' is not Ok: {value:?}")`+* `assert_eq!` for checking equality between two different values, `assert_eq!(result, expected, "'result' differs from 'expected': {}", result.diff(expected))`.++### 🚨 `assert!` reminders+* Rust asserts support formatted strings, like the previous examples, those strings will be printed in case of failure, so it is a good practice to add what the actual state was and how it differs from the expected.+* If you don't care about the exact pattern matching value, using `matches!` combined with `assert!` might be a good alternative. Note the message string is an argument to `assert!`, not to `matches!`:+```rust+assert!(matches!(error, MyError::BadInput(_)), "Expected `BadInput`, found {error}");+```+* Since Rust 1.96 prefer the stabilized [`assert_matches!`](https://doc.rust-lang.org/std/macro.assert_matches.html) (and [`debug_assert_matches!`](https://doc.rust-lang.org/std/macro.debug_assert_matches.html)) over `assert!(matches!(..))`. It prints the actual value on failure for free, so you don't have to write the message yourself:+```rust+use std::assert_matches::assert_matches;++assert_matches!(error, MyError::BadInput(_));+```+* Use `#[should_panic]` wisely. It should only be used when panic is the desired behavior, prefer result instead of panic.+* There are some other that can enhance your testing experience like:+ * [`rstest`](https://crates.io/crates/rstest): fixture based test framework with procedural macros.+ * [`pretty_assertions`](https://crates.io/crates/pretty_assertions): overrides `assert_eq` and `assert_ne`, and creates colorful diffs between them.++## 5.5 Snapshot Testing with `cargo insta`++> When correctness is visual or structural, snapshots tell the story better than asserts.++1. Add to your dependencies:+```toml+insta = { version = "1.42.2", features = ["yaml"] }+```+> For most real world applications the recommendation is to use YAML snapshots of serializable values. This is because they look best under version control and the diff viewer and support redaction. To use this enable the yaml feature of insta.++2. For a better review experience, add the CLI `cargo install cargo-insta`.+++3. Writing a simple test:+```rust+fn split_words(s: &str) -> Vec<&str> {+ s.split_whitespace().collect()+}++#[test]+fn test_split_words() {+ let words = split_words("hello from the other side");+ insta::assert_yaml_snapshot!(words);+}+```++4. Run `cargo insta test` to execute, and `cargo insta review` to review conflicts.++To learn more about `cargo insta` check out its [documentation](https://insta.rs/docs/quickstart/) as it is a very complete and well documented tool.++### What is snapshot testing?++Snapshot testing compares your output (text, Json, HTML, YAML, etc) against a saved "golden" version. On future runs, the test fails if the output changes, unless humanly approved. It is perfect for:+* Generate code.+* Serializing complex data.+* Rendered HTML.+* CLI output.++#### ❌ What not to test with snapshot+* Very stable, numeric-only or small structured data associated logic (prefer `assert_eq!`).+* Critical path logic (prefer precise unit tests).+* Flaky tests, randomly generated output, unless redacted.+* Snapshots of external resources, use mocks and stubs.++## 5.6 ✅ Snapshot Best Practices++* Named snapshots, it gives meaningful snapshot files names, e.g. `snapshots/this_is_a_named_snapshot.snap`+```rust+assert_snapshot!("this_is_a_named_snapshot", output);+```++* Keep snapshots small and clear.+```rust+// ✅ Best case:+assert_snapshot!("app_config/http", whole_app_config.http);++// ❌ Worst case:+assert_snapshot!("app_config", whole_app_config); // Huge object+```++> #### 🚨 Avoid snapshotting huge objects+> Huge objects become hard to review and reason about.++* Avoid snapshotting simple types (primitives, flat enums, small structs):+```rust+// ✅ Better:+assert_eq!(meaning_of_life, 42);++// ❌ OVERKILL:+assert_snapshot!("the_meaning_of_life", meaning_of_life); // meaning_of_life == 42+```++* Use [redactions](https://insta.rs/docs/redactions/) for unstable fields (randomly generated, timestamps, uuid, etc):+```rust+use insta::assert_json_snapshot;++#[test]+fn endpoint_get_user_data() {+ let data = http::client.get_user_data();+ assert_json_snapshot!(+ "endpoints/subroute/get_user_data",+ data,+ ".created_at" => "[timestamp]",+ ".id" => "[uuid]"+ );+}+```+* Commit your snapshots into git. They will be stored in `snapshots/` alongside your tests.+* Review changes carefully before accepting.\ No newline at end of filediff --git a/.agents/skills/rust-best-practices/references/chapter_06.md b/.agents/skills/rust-best-practices/references/chapter_06.mdnew file mode 100644index 0000000..bf609c4--- /dev/null+++ b/.agents/skills/rust-best-practices/references/chapter_06.md@@ -0,0 +1,161 @@+# Chapter 6 - Generics, Dynamic Dispatch and Static Dispatch++> Static where you can, dynamic where you must++Rust allows you to handle polymorphic code in two ways:+* **Generics / Static Dispatch**: compile-time, monomorphized per use.+* **Trait Objects / Dynamic Dispatch**: runtime vtable, single implementation.++Understanding the trade-offs lets you write faster, smaller and more flexible code.++## 6.1 [Generics](https://doc.rust-lang.org/book/ch10-00-generics.html)++Every programming language has tools for effectively handling the duplication of concepts. In Rust, one such tool is generics: abstract stand-ins for concrete types or other properties. We can express the behavior of generics or how they relate to other generics without knowing what will be in their place when compiling and running the code.++We use generics to create definitions for items like function signatures or structs, which we can then use with many different concrete data types. Let's first look at how to define functions, structs, enums, and methods using generics. Generics can also be used to implement Type State Pattern and constrain a struct functionality to certain expected types, more on type state on [chapter 7](./chapter_07.md).++[Generics by Examples](https://doc.rust-lang.org/rust-by-example/generics.html).++### Generics Performance++You might be wondering whether there is a runtime cost when using generic type parameters. The good news is that using generic types won't make your program run any slower than it would with concrete types. Rust accomplishes this by performing monomorphization of the code using generics at compile time. Monomorphization is the process of turning generic code into specific code by filling in the concrete types that are used when compiled. The compiler checks for all occurrences of the generic parameter and generates code for the concrete types the generic code is called with.++## 6.2 Static Dispatch: `impl Trait` or `<T: Trait>`++A static dispatch is basically a constrained version of generics, a trait bounded generic, at compile-time it is able to check if your generic satisfies the declared traits.++### ✅ Best when:+* You want **zero runtime cost**, by paying the compile time cost.+* You need **tight loops or performance**.+* Your types are **known at compile time**.+* You are working with **single-use implementations** (monomorphized).++### 🏎️ Example: High-performance function with generic+```rust+fn specialized_sum<U: Sum + RandomMapping, T: Iterator<Item = U>>(iter: T) -> U {+ iter.map(|x| x.random_mapping()).sum()+}++// or, equivalent, more modern+fn specialized_sum<U: Sum + RandomMapping>(iter: impl Iterator<Item = U>) -> U {+ iter.map(|x| x.random_mapping()).sum()+}+```++This is compiled into **specialized machine code** for each usage, fast and inlined.++## 6.3 Dynamic Dispatch: `dyn Trait`++Usually dynamic dispatch is used with some kind of pointer or a reference, like `Box<dyn Trait>`, `Arc<dyn Trait>` or `&dyn trait`.++### ✅ Best when:+* You absolutely need runtime polymorphism.+* You need to **store different implementations** in one collection.+* You want to **abstract internals behind a stable interface**.+* You are writing a **plugin-style architecture**.++> ❗ Closer to what you would get in an object oriented language and can have some heavy costs associated to it. Can avoid generics entirely and let you mix types that implement the same traits.++### 🚚 Example: Heterogeneous collection++```rust+trait Animal {+ fn greet(&self) -> String;+}++struct Dog;+impl Animal for Dog {+ fn greet(&self) -> String {+ "woof".to_string()+ }+}++struct Cat;+impl Animal for Cat {+ fn greet(&self) -> String {+ "meow".to_string()+ }+}++fn all_animals_greeting(animals: Vec<Box<dyn Animal>>) {+ for animal in animals {+ println!("{}", animal.greet())+ }+}+```++## 6.4 Trade-off summary++| | Static Dispatch (impl Trait) | Dynamic Dispatch (dyn Trait) |+|------------------- |------------------------------ |---------------------------------- |+| Performance | ✅ Faster, inlined | ❌ Slower: vtable indirection |+| Compile time | ❌ Slower: monomorphization | ✅ Faster: shared code |+| Binary size | ❌ Larger: per-type codegen | ✅ Smaller |+| Flexibility | ❌ Rigid, one type at a time | ✅ Can mix types in collections |+| Use in trait fn() | ❌ Traits must be object-safe | ✅ Works with trait objects |+| Errors | ✅ Clearer | ❌ Erased types can confuse errors |++* Prefer generics/static dispatch when you control the call site and want performance.+* Use dynamic dispatch when you need abstraction, plugins or mixed types. 🚨 Runtime cost.+* If you are not sure, start with generics, trait bound them - then use `Box<dyn Trait>` when flexibility outweighs speed.++> Favor static dispatch until your trait needs to live behind a pointer.++## 6.5 Best Practices for Dynamic Dispatch++Dynamic dispatch `Ptr<dyn Trait>` is a powerful tool, but it also has significant performance trade-offs. You should only reach for it when **type erasure or runtime polymorphism** are essential. It is important to know when you need Trait Objects:++### ✅ Use Dynamic Dispatch When:++* You need heterogeneous types in a collection:+```rust+fn all_animals_greeting(animals: Vec<Box<dyn Animal>>) {+ for animal in animals {+ println!("{}", animal.greet())+ }+}+```++* You want runtime plugins or hot-swappable components.+* You want to abstract internals from the caller (library design).+++### ❌ Avoid Dynamic Dispatch When:++* You control the concrete types.+* You are writing code in performance critical paths.+* You can express the same logic in other ways while keeping simplicity, e.g. generics.++## 6.6 🚨 Trait Objects Ergonomics++* Prefer `&dyn Trait` over `Box<dyn Trait>` when you don't need ownership.+* Use `Arc<dyn Trait + Send + Sync>` for shared access across threads.+* Don't use `dyn Trait` if the trait has methods that return `Self`.+* **Avoid boxing too early**. Don't box inside structs unless you are sure it'll be beneficial or is required (recursive).+```rust+// ✅ Use generics when possible+struct Renderer<B: RenderBackend> {+ backend: B+}++// ❌ Premature Boxing+struct Renderer {+ backend: Box<dyn RenderBackend> // Boxing too early+}+```+* If you must expose a `dyn trait` in a public API, `Box` at the boundary, not internally.+* **Object Safety**: You can only create `dyn Traits` from object-safe traits:+ * It has **no generic methods**.+ * It doesn't require `Self: Sized`.+ * All method signatures use `&self`, `&mut self` or `self`.+ ```rust+ // ✅ Object Safe+ trait Runnable {+ fn run(&self);+ }++ // ❌ Not Object Safe+ trait Factory {+ fn create<T>() -> T; // generic methods are not allowed+ }+ ```\ No newline at end of filediff --git a/.agents/skills/rust-best-practices/references/chapter_07.md b/.agents/skills/rust-best-practices/references/chapter_07.mdnew file mode 100644index 0000000..2fe7644--- /dev/null+++ b/.agents/skills/rust-best-practices/references/chapter_07.md@@ -0,0 +1,222 @@+# Chapter 7 - Type State Pattern++Models state at compile time, preventing bugs by making illegal states unrepresentable. It takes advantage of the Rust generics and type system to create sub-types that can only be reached if a certain condition is achieved, making some operations illegal at compile time.++> Recently it became the standard design pattern of Rust programming. However, it is not exclusive to Rust, as it is achievable and has inspired other languages to do the same [swift](https://swiftology.io/articles/typestate/) and [typescript](https://catchts.com/type-state).++## 7.1 What is Type State Pattern?++**Type State Pattern** is a design pattern where you encode different **states** of the system as **types**, not as runtime flags or enums. This allows the compiler to enforce state transitions and prevent illegal actions at compile time. It also improves the developer experience, as developers only have access to certain functions based on the state of the type.++> Invalid states become compile errors instead of runtime bugs.++## 7.2 Why use it?++* Avoids runtime checks for state validity. If you reach certain states, you can make certain assumptions of the data you have.+* Models state transitions as type transitions. This is similar to a state machine, but in compile time.+* Prevents data misuse, e.g. using uninitialized objects.+* Improves API safety and correctness.+* The phantom data field is removed after compilation so no extra memory is allocated.++## 7.3 Simple Example: File State++[Github Example](https://github.com/apollographql/rust-best-practices/tree/main/examples/simple-type-state)+```rust+use std::{io, path::{Path, PathBuf}};++struct FileNotOpened;+struct FileOpened;++#[derive(Debug)]+struct File<State> {+ /// Path to the opened file+ path: PathBuf,+ /// Open `File` handler+ handle: Option<std::fs::File>,+ /// Type state manager+ _state: std::marker::PhantomData<State>+}++impl File<FileNotOpened> {+ /// `open` is the only entry point for this struct.+ /// * When called with a valid path, it will return a `File<FileOpened>` with a valid `handler` and `path`+ /// * `open` serves as an alternative to `new` and `defaults` methods (usable when your struct needs valid data to exist).+ fn open(path: &Path) -> io::Result<File<FileOpened>> {+ // If file is invalid, it will return `std::io::Error`+ let file = std::fs::File::open(path)?;+ Ok(+ File {+ path: path.to_path_buf(),+ // Always valid+ handle: Some(file),+ _state: std::marker::PhantomData::<FileOpened>+ }+ )+ }+}++impl File<FileOpened> {+ /// Reads the content of the `File` as a `String`.+ /// `read` can only be called by state `File<FileOpened>`+ fn read(&mut self) -> io::Result<String> {+ use io::Read;++ let mut content = String::new();+ let Some(handle)= self.handle.as_mut() else {+ unreachable!("Safe to unwrap as state can only be reached when file is open");+ };+ handle.read_to_string(&mut content)?;+ Ok(content)+ }++ /// Returns the valid path buffer.+ fn path(&self) -> &PathBuf {+ &self.path+ }+}+```++## 7.4 Real-World Examples++### Builder Pattern with Compile-Time Guarantees++> Forces the user to **set required fields** before calling `.build()`.++[Github Example](https://github.com/apollographql/rust-best-practices/tree/main/examples/type-state-builder)++A type-state pattern can have more than one associated states:++```rust+use std::marker::PhantomData;++struct Unset;+struct Set;++#[derive(Debug)]+struct Person {+ name: String,+ age: u8,+ email: Option<String>,+}++struct Builder<NameState = Unset, AgeState = Unset> {+ name: Option<String>,+ age: u8,+ email: Option<String>,+ _maker_state: PhantomData<(NameState, AgeState)>,+}++impl Builder<Unset, Unset> {+ const fn new() -> Self {+ Self { name: None, age: 0, email: None, _maker_state: PhantomData }+ }+}++impl<NameState> Builder<NameState, Unset> {+ fn age(self, age: u8) -> Builder<NameState, Set> {+ Builder { age, name: self.name, email: self.email, _maker_state: PhantomData }+ }+}++impl<AgeState> Builder<Unset, AgeState> {+ fn name(self, name: String) -> Builder<Set, AgeState> {+ Builder { name: Some(name), age: self.age, email: self.email, _maker_state: PhantomData }+ }+}++impl<NameState, AgeState> Builder<NameState, AgeState> {+ fn email(self, email: String) -> Self {+ Self { name: self.name, age: self.age, email: Some(email), _maker_state: PhantomData }+ }+}++impl Builder<Set, Set> {+ fn build(self) -> Person {+ Person {+ name: self.name.unwrap_or_else(|| unreachable!("Name is guaranteed to be set")),+ age: self.age,+ email: self.email,+ }+ }+}+```++Although a bit more verbose than a usual builder, this guarantees that all necessary fields are present (note that e-mail is optional field only present in the final builder).++#### Usage:+```rust+// ✅ Valid cases+let person: Person = Builder::new().name("name".to_string()).age(30).build();+let person: Person = Builder::new().age(30).name("name".to_string()).build();+let person: Person = Builder::new().age(30).name("name".to_string()).email("[email protected]".to_string()).build();++// ❌ Invalid cases+let person: Person = Builder::new().name("name".to_string()).build(); // ❌ Compile error: Age required to `build`+let person: Person = Builder::new().age(30).build(); // ❌ Compile error: Name required to `build`+let person: Person = Builder::new().age(30).email("[email protected]".to_string()).build(); // ❌ Compile error: Name required to `build`+let person: Person = Builder::new().age(10).age(15); // ❌ Compile error: Age was already set+let person: Person = Builder::new().build();// ❌ Compile error: Name and Age required to `build`+```++### Crates implementing Builder pattern++Some libraries are already implementing the builder pattern, like [bon-rs](https://docs.rs/bon/latest/bon/)++### Network Protocol State Machine++Illegal transitions like sending a message before connecting **simply don't compile**:++```rust+// Mock example+struct Disconnected;+struct Connected;++struct Client<State> {+ stream: Option<std::net::TcpStream>,+ _state: std::marker::PhantomData<State>+}++impl Client<Disconnected> {+ fn connect(addr: &str) -> std::io::Result<Client<Connected>> {+ let stream = std::net::TcpStream::connect(addr)?;+ Ok(Client {+ stream: Some(stream),+ _state: std::marker::PhantomData::<Connected>+ })+ }+}++impl Client<Connected> {+ fn send(&mut self, msg: &str) {+ use std::io::Write;+ let Some(stream) = self.stream.as_mut() else {+ unreachable!("Stream is guaranteed to be set");+ };+ stream.write_all(msg.as_bytes())+ }+}+```++## 7.5 Pros and Cons++### ✅ Use Type-State Pattern When:+* You want **compile-time state safety**.+* You need to enforce **API constraints**.+* You are writing a library/crate that is heavily dependent on variants.+* You want to replace runtime booleans or enums with **type-safe code paths**.+* You need compile time correctness.++### ❌ Avoid it when:+* Writing trivial states like enums.+* Don't need type-safety.+* When it leads to overcomplicated generics.+* When runtime flexibility is required.++### 🚨 Downsides and Cautions+* Can lead to more **verbose solutions**.+* Can lead to **complex type signatures**.+* May require **unsafe** to return **variant outputs** based on different states.+* May require a bunch of duplication (e.g. same struct field reused).+* PhantomData is not intuitive for beginners and can feel a bit hacky.++> Use this pattern when it **saves bugs, increases safety or simplifies logic**, not just for cleverness.\ No newline at end of filediff --git a/.agents/skills/rust-best-practices/references/chapter_08.md b/.agents/skills/rust-best-practices/references/chapter_08.mdnew file mode 100644index 0000000..ebdd04a--- /dev/null+++ b/.agents/skills/rust-best-practices/references/chapter_08.md@@ -0,0 +1,252 @@+# Chapter 8 - Comments vs Documentation++> Clear code beats clear comments. However, when the why isn't obvious, comment it plainly - or link to where you can read more context.++## 8.1 Comments vs Documentation: Know the Difference++| Purpose | Use `// comment` | Use `/// doc` or `//! crate doc` |+|-------------- |------------------------------------------- |---------------------------------------------------------------- |+| Describe Why | ✅ Yes - explains tricky reasoning | ❌ Not for documentation |+| Describe API | ❌ Not useful | ✅ Yes - public interfaces, usage, details, errors, panics |+| Maintainable | 🚨 Often becomes obsolete and hard to reason | ✅ Tied to code, appears in generated docs and can run test cases |+| Visibility | Local development only | Exported to users and tools like `cargo doc` |++## 8.2 When to use comments++Use `//` comments (double slashed) when something can't be expressed clearly in code, like:+* **Safety Guarantees**, some of which can be better expressed with code conditionals.+* Workarounds or **Optimizations**.+* Legacy or **platform-specific** behaviors. Some of them can be expressed with `#[cfg(..)]`.+* Links to **Design Docs** or **ADRs**.+* Assumptions or **gotchas** that aren't obvious.++> Name your comments! For example, a comment regarding a safety guarantee should start with `// SAFETY: ...`.++### ✅ Good comment:+```rust+// SAFETY: `ptr` is guaranteed to be non-null and aligned by caller+unsafe { std::ptr::copy_nonoverlapping(src, dst, len); }+```++### ✅ Design context comment:+```rust+// CONTEXT: Reuse root cert store across subgraphs to avoid duplicate OS calls:+// [ADR-12](link/to/adr-12): TLS Performance on MacOS+```++## 8.3 When comments get in the way++Avoid comments that:+* Restate obvious things (`// increment i by 1 for the next loop`).+* Can grow stale over time.+* `TODO`s without actions (links to some versioned issue).+* Could be replaced by better naming or smaller functions.++### ❌ Bad comment:+```rust+fn compute(counter: &mut usize) {+ // increment by 1+ *counter += 1;+}+```++### ❌ Too long or outdated+```rust+// Originally written in 2028 for some now-defunct platform+```++## 8.4 Don't Write Living Documentation (living comments)++Comments as a "living documentation" is a **dangerous myth**, as comments are **not free**:+* They **rot** - nobody compiles comments.+* They **mislead** - readers usually assume they are true with no critique, e.g. "the other developer knows this code better than I do".+* They **go stale** - unless maintained with the code, they become irrelevant.+* They are **noisy** - comments can clutter your code with multiple unnecessary lines.++If something deserves to live beyond a PR, put it in:+* An **ADR** (Architectural Design Record).+* A Design Document.+* Document it **in code** by using types, doc comments, examples, renaming code blocks into cleaner functions.+* Add tests to cover and explain the change.++> ### 🚨 If you find a comment, **read it in context**. Does it still make sense? If not, remove or update it, or ask for help. Comments should bother you.++## 8.5 Replace Comments with Code++Instead of long commented blocks, break logic into named helper functions:++#### ❌ Commented code block:+```rust+fn save_user(&self) -> Result<(), MyError> {+ // check if the user is authenticated+ if self.is_authenticated() {+ // serialize user data+ let data = serde_json::to_string(self)?;+ // write to file+ std::fs::write(self.path(), data)?;+ }+}++```+**✅ Extract for clarity**:++```rust+fn save_auth_user(&self) -> Result<PathBuf, MyError> {+ if self.is_authenticated() {+ let path = self.path();+ let serialized_user = serde_json::to_string(self)?;+ std::fs::write(path, serialized_user)?;+ Ok(path)+ } else {+ Err(MyError::UserNotAuthenticated)+ }+}+```++> ❗ Extract when the **name adds meaning** -- not to deduplicate a couple of similar-looking lines. See [Chapter 1, §1.8](./chapter_01.md#18-when-to-extract-a-function-and-when-not-to) for when duplication is the better trade-off.++## 8.6 `TODO` should become issues++Don't leave `// TODO:` scattered around the codebase with no owner. Instead:+1. File Github Issue or Jira Ticket. (Prefer github issues on public repositories).+2. Reference the issue in the code:++```rust+// TODO(issue #42): Remove workaround after bugfix+```++This makes `TODO`s trackable, actionable and visible to everyone.++## 8.7 When to use doc comments++Use `///` doc comments to document:+* All **public functions, structs, traits, enums**.+* Their purpose, their usage and their behaviors.+* Anything developers need to understand how to use it correctly.+* Add context that related to `Errors` and `Panics`.+* Plenty of examples.++### ✅ Good doc comment:++```rust+/// Loads [`User`] profile from disk+///+/// # Error+/// - Returns [`MyError`] if the file is missing [`MyError::FileNotFound`].+/// - Returns [`MyError`] if the content is an invalid Json, [`MyError::InvalidJson`].+fn load_user(path: &Path) -> Result<User, MyError> {...}+```++**Doc comments can also include examples, links and even tests:**++```rust+/// Returns the square of the integer part of any number.+/// Square is limited to `u128`.+///+/// # Examples+///+/// ```rust+/// assert_eq!(square(4.3), 16)+/// ```+fn square(x: impl ToInt) -> u128 { ... }+```++## 8.8 Documentation in Rust: How, When and Why++Rust provides **first-class documentation tooling** via rustdoc, which makes documenting your code a key part of writing idiomatic and maintainable rust. There are doc specific lints to help with documentation, like:++| Lint | Description |+|-------------- |------------------------------------------- |+| [missing_docs](https://doc.rust-lang.org/rustdoc/lints.html#missing_docs) | Warns that a public functions, struct, const, enum has missing documentation |+| [broken_intra_doc_links](https://doc.rust-lang.org/rustdoc/lints.html#broken_intra_doc_links) | Detects if an internal documentation link is broken. Especially useful when things are renamed. |+| [empty_docs](https://rust-lang.github.io/rust-clippy/master/#empty_docs) | Disallow empty docs - preventing bypass of `missing_docs` |+| [missing_panics_doc](https://rust-lang.github.io/rust-clippy/master/#missing_panics_doc) | Warns that documentation should have a `# Panics` section if function can panic |+| [missing_errors_doc](https://rust-lang.github.io/rust-clippy/master/#missing_errors_doc) | Warns that documentation should have a `# Errors` section if function returns a `Result` explaining `Err` conditions |+| [missing_safety_doc](https://rust-lang.github.io/rust-clippy/master/#missing_safety_doc) | Warns that documentation should have a `# Safety` section if public facing functions have visible unsafe blocks |+++### Difference between `///` and `//!`++| Style | Used for | Scope |Example |+|---------- |------------------------------ |------------------------------------------- |---------------------------------------------------------------- |+| `///` | Line doc comment | Public items like struct, fn, enum, consts | Documenting, giving context and usage to `fn`, `struct`, `enum`, etc |+| `//!` | Module level doc comment | Modules or entire crates | Explaining crate/module purpose with common use cases and quickstart |++### `///` Item level documentation++Use `///` for functions, structs, traits, enums, const, etc:++```rust+/// Adds two numbers together.+///+/// # Examples+///+/// ```+/// let result = my_crate::add(2, 3);+/// assert_eq!(result, 5);+/// ```+pub fn add(a: i32, b: i32) -> i32 {+ a + b+}+```+* ✅ Write clear and descriptive **What it does** and **how to use it**.+* ✅ Use `# Examples` section to better explain **how to use it**.+* ✅ Prefer writing examples that can be tested via `cargo test`, even if you have to hide their output with starting `#`:+```rust+/// ```+/// let result = my_crate::add(2, 3);+/// # assert_eq!(result, 5);+/// ```+```+* ✅ Use `# Panics`, `# Errors` and `# Safety` sections when relevant.+* Add relevant context to the type.++### `//!` Module/Crate level Documentation++Use `//!` when you want to document the **purpose of a module or a crate**. It is placed at the top of a `lib.rs` or `mod.rs` file, for example `engine/mod.rs`:+```rust+//! This module implements a custom chess engine.+//!+//! It handles board state, move generation and check detection.+//!+//! # Example+//! ```+//! let board = chess::engine::Board::default();+//! assert!(board.is_valid());+//! ```+```++## 8.9 Checklist for Documentation coverage++📦 Crate-Level (lib.rs)+- [ ] `//!` doc at top explains **what the crate does**, and **what problems it solves**.+- [ ] Includes crate-level `# Examples` or pointers to modules.+📁 Modules (mod.rs or inline)+- [ ] `//!` doc explains **what this module is for**, its **exports**, and **invariants**.+- [ ] Avoid repeating doc comments on re-exported items unless clarification is needed.+🧱 Structs, Enums, Traits+- `///` doc explains:+ - [ ] The role this type plays.+ - [ ] Invariants or expectations.+ - [ ] Example construction or usage.+- [ ] Consider using [`#[non_exhaustive]`](https://doc.rust-lang.org/reference/attributes/type_system.html#the-non_exhaustive-attribute) if external users may match on it.+🔧 Functions and Methods+- `///` doc covers:+ - [ ] What it does.+ - [ ] Parameters and their meaning.+ - [ ] Return value behavior.+ - [ ] Edge cases (`# Panics`, `# Errors`).+ - [ ] Usage example, `# Examples`.+📑 Traits+- [ ] Explain the **purpose** of the trait (marker? dynamic dispatch?).+- [ ] Doc for each method -- include **when/why** to implement it.+- [ ] Document clearly default implemented methods and when to override.+📦 Public Constants+- [ ] Document what they configure and when you'd want to use them.++### 📌 Best Practices+* ✅ Use examples generously -- they double as test cases.+* ✅ Prefer clarity over formality -- it's for humans, not machines.+* ✅ Prefer doc comments to explain usage, and leave implementation details to code comments if needed.+* ✅ Use `cargo doc --open` to check your output often.+* ✅ Add `#![deny(missing_docs)]` and other relevant doc lints in top-level modules if you want to enforce full doc coverage.\ No newline at end of filediff --git a/.agents/skills/rust-best-practices/references/chapter_09.md b/.agents/skills/rust-best-practices/references/chapter_09.mdnew file mode 100644index 0000000..f9453b9--- /dev/null+++ b/.agents/skills/rust-best-practices/references/chapter_09.md@@ -0,0 +1,256 @@+# Chapter 9 - Understanding Pointers++Many higher level languages hide memory management, typically **passing by value** (copy data) or **passing by reference** (reference to shared data) without worrying about allocation, heap, stack, ownership and lifetimes, it is all delegated to the garbage collector or VM. Here is a comparison on this topic between a few languages:++### 📌 Language Comparison++| Language | Value Types | Reference/Pointer Types | Async Model & Types | Manual Memory |+|------------ |------------------------------------- |----------------------------------------------------------- |---------------------------------------------------------------------------- |------------------------------ |+| Python | None | Everything is a reference | async def, await, Task, coroutines and asyncio.Future | ❌ Not Allowed |+| Javascript | Primitives | Objects | `async/await`, `Promise`, `setTimeout`. single threaded event loop | ❌ Not Allowed |+| Java | Primitives | Objects | `Future<T>`, threads, Loom (green threads) | ❌ Almost none & not recommended |+| Go | Values are copied unless using `&T` | Pointers (`*T`, `&T`), escape analysis | goroutines, `channels`, `sync.Mutex`, `context.Context` | ⚠️ Limited |+| C | Primitives and structs supported | Raw pointers `T*` and `*void` | Threads, event loops (`libuv`, `libevent`) | ✅ Fully |+| C++ | Primitives and references | Raw `T*` and smart pointers `shared_ptr` and `unique_ptr` | threads, `std::future`, `std::async`, (since c++ 20 `co_await/coroutines`) | ✅ Mostly |+| Rust | Primitives, Arrays, `impl Copy` | `&T`, `&mut T`, `Box<T>`, `Arc<T>` | `async/await`, `tokio`, `Future`, `JoinHandle`, `Send + Sync` | ✅🔒 Safe and Explicit |++## 9.1 Thread Safety++Rust tracks pointers using `Send` and `Sync` traits:+- `Send` means data can move across threads.+- `Sync` means data can be referenced from multiple threads.++> A pointer is thread-safe only if the data behind it is.++| Pointer Type | Short Description | Send + Sync? | Main Use |+|---------------- |--------------------------------------------------------------------------- |-------------------------------------- |------------ |+| `&T` | Shared reference | Yes | Shared access |+| `&mut T` | Exclusive mutable reference | No, not Send | Exclusive mutation |+| `Box<T>` | Heap-allocated owning pointer | Yes, if T: Send + Sync | Heap allocation |+| `Rc<T>` | Single-threaded ref counted pointer | No, neither | Multiple owners (single-thread) |+| `Arc<T>` | Atomic ref counter pointer | Yes | Multiple owners (multi-thread) |+| `Cell<T>` | Interior mutability for copy types | No, not Sync | Shared mutable, non-threaded |+| `RefCell<T>` | Interior mutability (dynamic borrow checker) | No, not Sync | Shared mutable, non-threaded |+| `Mutex<T>` | Thread-safe interior mutability with exclusive access | Yes | Shared mutable, threaded |+| `RwLock<T>` | Thread-safe shared readonly access OR exclusive mutable access | Yes | Shared mutable, threaded |+| `OnceCell<T>` | Single-thread one-time initialization container (interior mutability ONCE) | No, not Sync | Simple lazy value initialization |+| `LazyCell<T>` | A lazy version of `OnceCell<T>` that calls function closure to initialize | No, not Sync | Complex lazy value initialization+| `OnceLock<T>` | Thread-safe version of `OnceCell<T>` | Yes | Multi-thread single init |+| `LazyLock<T>` | Thread-safe version of `LazyCell<T>` | Yes | Multi-thread complex init |+| `*const T/*mut T` | Raw Pointers | No, user must ensure safety manually | Raw memory / FFI |++## 9.2 When to use pointers:++### `&T` - Shared Borrow:++Probably the most common type in a Rust code base, it is **Safe, with no mutation** and allows **multiple readers**.++```rust+let data: String = String::from_str("this is a string").unwrap();++print_len(&data);+print_capacity(&data);+print_bytes(&data);++fn print_len(s: &str) {+ println!("{}", s.len())+}++fn print_capacity(s: &String) {+ println!("{}", s.capacity())+}++fn print_bytes(s: &String) {+ println!("{:?}", s.as_bytes())+}+```+### `&mut T` - Exclusive Borrow:++Probably the most common *mutable* type in a Rust code base, it is **Safe, but only allows one mutable borrow at a time**.++```rust+let mut data: String = String::from_str("this is a string").unwrap();+mark_update(&mut data);++fn mark_update(s: &mut String) {+ s.push_str("_update");+}+```++### [`Box<T>`](https://doc.rust-lang.org/std/boxed/struct.Box.html) - Heap Allocated++Single-owner heap-allocated data, great for recursive types and large structs.++```rust+pub enum MySubBoxedEnum<T> {+ Single(T),+ Double(Box<MySubBoxedEnum<T>>, Box<MySubBoxedEnum<T>>),+ Multi(Vec<T>), // Note that Vec is already a boxed value+}+```++### [`Rc<T>`](https://doc.rust-lang.org/std/rc/struct.Rc.html) - Reference Counter (single-thread)++You need multiple references to data in a single thread. Most common example is linked-list implementation.++### [`Arc<T>`](https://doc.rust-lang.org/std/sync/struct.Arc.html) - Atomic Reference Counter (multi-thread)++You need multiple references to data in multiple threads. Most common use case is sharing readonly Vec across thread with `Arc<[T]>` and wrapping a `Mutex` so it can be easily shared across threads, `Arc<Mutex<T>>`.++### [`RefCell<T>`](https://doc.rust-lang.org/std/cell/struct.RefCell.html) - Runtime checked interior mutability++Used when you need shared access and the ability to mutate data, borrow rules are enforced at runtime. **It may panic!**.++```rust+use std::cell::RefCell;+let x = RefCell::new(42);+*x.borrow_mut() += 1;++assert_eq!(&*x.borrow(), 42, "Not meaning of life");+```++Panic example:+```rust+use std::cell::RefCell;+let x = RefCell::new(42);++let borrow = x.borrow();++let mutable = x.borrow_mut();+```++### [`Cell<T>`](https://doc.rust-lang.org/std/cell/struct.Cell.html) - Copy-only interior mutability++Somewhat the fast and safe version of `RefCell`, but it is limited to types that implement the `Copy` trait:++```rust+use std::cell::Cell;++struct SomeStruct {+ regular_field: u8,+ special_field: Cell<u8>,+}++let my_struct = SomeStruct {+ regular_field: 0,+ special_field: Cell::new(1),+};++let new_value = 100;++// ERROR: `my_struct` is immutable+// my_struct.regular_field = new_value;++// WORKS: although `my_struct` is immutable, `special_field` is a `Cell`,+// which can always be mutated with copy values+my_struct.special_field.set(new_value);+assert_eq!(my_struct.special_field.get(), new_value);+```++### [`Mutex<T>`](https://doc.rust-lang.org/std/sync/struct.Mutex.html) - Thread-safe mutability++An exclusive access pointer that allows a thread to read/write the data contained inside. It is usually wrapped in an `Arc` to allow shared access to the Mutex.++### [`RwLock<T>`](https://doc.rust-lang.org/std/sync/struct.RwLock.html) - Thread-safe mutability++Similar to a `Mutex`, but it allows multiple threads to read it OR a single thread to write. It is usually wrapped in an `Arc` to allow shared access to the RwLock.+++### [`*const T/*mut T`](https://doc.rust-lang.org/std/primitive.pointer.html) - Raw pointers++Inherently **unsafe** and necessary for FFI. Rust makes their usage explicit to avoid accidental misuse and unwilling manual memory management.++```rust+let x = 5;+let ptr = &x as *const i32+unsafe {+ println!("PTR is {}", *ptr)+}+```++### [`OnceCell`](https://doc.rust-lang.org/std/cell/struct.OnceCell.html) - Single-thread single initialization container++Most useful when you need to share a configuration between multiple data structures.++```rust+use std::{cell::OnceCell, rc::Rc};++#[derive(Debug, Default)]+struct MyStruct {+ distance: usize,+ root: Option<Rc<OnceCell<MyStruct>>>,+}++fn main() {+ let root = MyStruct::default();+ let root_cell = Rc::new(OnceCell::new());+ if let Err(previous) = root_cell.set(root) {+ eprintln!("Previous Root {previous:?}");+ }+ let child_1 = MyStruct{+ distance: 1,+ root: Some(root_cell.clone())+ };++ let child_2 = MyStruct{+ distance: 2,+ root: Some(root_cell.clone())+ };+++ println!("Child 1: {child_1:?}");+ println!("Child 2: {child_2:?}");+}+```++### [`LazyCell`](https://doc.rust-lang.org/std/cell/struct.LazyCell.html) - Lazy initialization of `OnceCell`++Useful when the initialized data can be delayed to when it is actually being called.++### [`OnceLock`](https://doc.rust-lang.org/std/sync/struct.OnceLock.html) - thread-safe `OnceCell`++Useful when you need a `static` value.++```rust+use std::sync::OnceLock;++static CELL: OnceLock<usize> = OnceLock::new();++// `OnceLock` has not been written to yet.+assert!(CELL.get().is_none());++// Spawn a thread and write to `OnceLock`.+std::thread::spawn(|| {+ let value = CELL.get_or_init(|| 12345);+ assert_eq!(value, &12345);+})+.join()+.unwrap();++// `OnceLock` now contains the value.+assert_eq!(+ CELL.get(),+ Some(&12345),+);+```++### [`LazyLock`](https://doc.rust-lang.org/std/sync/struct.LazyLock.html) - thread-safe `LazyCell`++Similar to `OnceLock`, but the static value is a bit more complex to initialize.++```rust+use std::sync::LazyLock;++static CONFIG: LazyLock<HashMap<String, T>> = LazyLock::new(|| {+ let data = read_config();+ let mut config: HashMap<String, T> = data.into();+ config.insert("special_case", T::Default());+ config+});++let _ = &*CONFIG;+```++## References+- [Mara Bos - Rust Atomics and Locks](https://marabos.nl/atomics/)+- [Semicolon video on pointers](https://www.youtube.com/watch?v=Ag_6Q44PBNs)\ No newline at end of filediff --git a/.agents/skills/vercel-react-best-practices/AGENTS.md b/.agents/skills/vercel-react-best-practices/AGENTS.mdnew file mode 100644index 0000000..4e340a5--- /dev/null+++ b/.agents/skills/vercel-react-best-practices/AGENTS.md@@ -0,0 +1,3810 @@+# React Best Practices++**Version 1.0.0**+Vercel Engineering+January 2026++> **Note:**+> This document is mainly for agents and LLMs to follow when maintaining,+> generating, or refactoring React and Next.js codebases. Humans+> may also find it useful, but guidance here is optimized for automation+> and consistency by AI-assisted workflows.++---++## Abstract++Comprehensive performance optimization guide for React and Next.js applications, designed for AI agents and LLMs. Contains 40+ rules across 8 categories, prioritized by impact from critical (eliminating waterfalls, reducing bundle size) to incremental (advanced patterns). Each rule includes detailed explanations, real-world examples comparing incorrect vs. correct implementations, and specific impact metrics to guide automated refactoring and code generation.++---++## Table of Contents++1. [Eliminating Waterfalls](#1-eliminating-waterfalls) — **CRITICAL**+ - 1.1 [Check Cheap Conditions Before Async Flags](#11-check-cheap-conditions-before-async-flags)+ - 1.2 [Defer Await Until Needed](#12-defer-await-until-needed)+ - 1.3 [Dependency-Based Parallelization](#13-dependency-based-parallelization)+ - 1.4 [Prevent Waterfall Chains in API Routes](#14-prevent-waterfall-chains-in-api-routes)+ - 1.5 [Promise.all() for Independent Operations](#15-promiseall-for-independent-operations)+ - 1.6 [Strategic Suspense Boundaries](#16-strategic-suspense-boundaries)+2. [Bundle Size Optimization](#2-bundle-size-optimization) — **CRITICAL**+ - 2.1 [Avoid Barrel File Imports](#21-avoid-barrel-file-imports)+ - 2.2 [Conditional Module Loading](#22-conditional-module-loading)+ - 2.3 [Defer Non-Critical Third-Party Libraries](#23-defer-non-critical-third-party-libraries)+ - 2.4 [Dynamic Imports for Heavy Components](#24-dynamic-imports-for-heavy-components)+ - 2.5 [Prefer Statically Analyzable Paths](#25-prefer-statically-analyzable-paths)+ - 2.6 [Preload Based on User Intent](#26-preload-based-on-user-intent)+3. [Server-Side Performance](#3-server-side-performance) — **HIGH**+ - 3.1 [Authenticate Server Actions Like API Routes](#31-authenticate-server-actions-like-api-routes)+ - 3.2 [Avoid Duplicate Serialization in RSC Props](#32-avoid-duplicate-serialization-in-rsc-props)+ - 3.3 [Avoid Shared Module State for Request Data](#33-avoid-shared-module-state-for-request-data)+ - 3.4 [Cross-Request LRU Caching](#34-cross-request-lru-caching)+ - 3.5 [Hoist Static I/O to Module Level](#35-hoist-static-io-to-module-level)+ - 3.6 [Minimize Serialization at RSC Boundaries](#36-minimize-serialization-at-rsc-boundaries)+ - 3.7 [Parallel Data Fetching with Component Composition](#37-parallel-data-fetching-with-component-composition)+ - 3.8 [Parallel Nested Data Fetching](#38-parallel-nested-data-fetching)+ - 3.9 [Per-Request Deduplication with React.cache()](#39-per-request-deduplication-with-reactcache)+ - 3.10 [Use after() for Non-Blocking Operations](#310-use-after-for-non-blocking-operations)+4. [Client-Side Data Fetching](#4-client-side-data-fetching) — **MEDIUM-HIGH**+ - 4.1 [Deduplicate Global Event Listeners](#41-deduplicate-global-event-listeners)+ - 4.2 [Use Passive Event Listeners for Scrolling Performance](#42-use-passive-event-listeners-for-scrolling-performance)+ - 4.3 [Use SWR for Automatic Deduplication](#43-use-swr-for-automatic-deduplication)+ - 4.4 [Version and Minimize localStorage Data](#44-version-and-minimize-localstorage-data)+5. [Re-render Optimization](#5-re-render-optimization) — **MEDIUM**+ - 5.1 [Calculate Derived State During Rendering](#51-calculate-derived-state-during-rendering)+ - 5.2 [Defer State Reads to Usage Point](#52-defer-state-reads-to-usage-point)+ - 5.3 [Do not wrap a simple expression with a primitive result type in useMemo](#53-do-not-wrap-a-simple-expression-with-a-primitive-result-type-in-usememo)+ - 5.4 [Don't Define Components Inside Components](#54-dont-define-components-inside-components)+ - 5.5 [Extract Default Non-primitive Parameter Value from Memoized Component to Constant](#55-extract-default-non-primitive-parameter-value-from-memoized-component-to-constant)+ - 5.6 [Extract to Memoized Components](#56-extract-to-memoized-components)+ - 5.7 [Narrow Effect Dependencies](#57-narrow-effect-dependencies)+ - 5.8 [Put Interaction Logic in Event Handlers](#58-put-interaction-logic-in-event-handlers)+ - 5.9 [Split Combined Hook Computations](#59-split-combined-hook-computations)+ - 5.10 [Subscribe to Derived State](#510-subscribe-to-derived-state)+ - 5.11 [Use Functional setState Updates](#511-use-functional-setstate-updates)+ - 5.12 [Use Lazy State Initialization](#512-use-lazy-state-initialization)+ - 5.13 [Use Transitions for Non-Urgent Updates](#513-use-transitions-for-non-urgent-updates)+ - 5.14 [Use useDeferredValue for Expensive Derived Renders](#514-use-usedeferredvalue-for-expensive-derived-renders)+ - 5.15 [Use useRef for Transient Values](#515-use-useref-for-transient-values)+6. [Rendering Performance](#6-rendering-performance) — **MEDIUM**+ - 6.1 [Animate SVG Wrapper Instead of SVG Element](#61-animate-svg-wrapper-instead-of-svg-element)+ - 6.2 [CSS content-visibility for Long Lists](#62-css-content-visibility-for-long-lists)+ - 6.3 [Hoist Static JSX Elements](#63-hoist-static-jsx-elements)+ - 6.4 [Optimize SVG Precision](#64-optimize-svg-precision)+ - 6.5 [Prevent Hydration Mismatch Without Flickering](#65-prevent-hydration-mismatch-without-flickering)+ - 6.6 [Suppress Expected Hydration Mismatches](#66-suppress-expected-hydration-mismatches)+ - 6.7 [Use Activity Component for Show/Hide](#67-use-activity-component-for-showhide)+ - 6.8 [Use defer or async on Script Tags](#68-use-defer-or-async-on-script-tags)+ - 6.9 [Use Explicit Conditional Rendering](#69-use-explicit-conditional-rendering)+ - 6.10 [Use React DOM Resource Hints](#610-use-react-dom-resource-hints)+ - 6.11 [Use useTransition Over Manual Loading States](#611-use-usetransition-over-manual-loading-states)+7. [JavaScript Performance](#7-javascript-performance) — **LOW-MEDIUM**+ - 7.1 [Avoid Layout Thrashing](#71-avoid-layout-thrashing)+ - 7.2 [Build Index Maps for Repeated Lookups](#72-build-index-maps-for-repeated-lookups)+ - 7.3 [Cache Property Access in Loops](#73-cache-property-access-in-loops)+ - 7.4 [Cache Repeated Function Calls](#74-cache-repeated-function-calls)+ - 7.5 [Cache Storage API Calls](#75-cache-storage-api-calls)+ - 7.6 [Combine Multiple Array Iterations](#76-combine-multiple-array-iterations)+ - 7.7 [Defer Non-Critical Work with requestIdleCallback](#77-defer-non-critical-work-with-requestidlecallback)+ - 7.8 [Early Length Check for Array Comparisons](#78-early-length-check-for-array-comparisons)+ - 7.9 [Early Return from Functions](#79-early-return-from-functions)+ - 7.10 [Hoist RegExp Creation](#710-hoist-regexp-creation)+ - 7.11 [Use flatMap to Map and Filter in One Pass](#711-use-flatmap-to-map-and-filter-in-one-pass)+ - 7.12 [Use Loop for Min/Max Instead of Sort](#712-use-loop-for-minmax-instead-of-sort)+ - 7.13 [Use Set/Map for O(1) Lookups](#713-use-setmap-for-o1-lookups)+ - 7.14 [Use toSorted() Instead of sort() for Immutability](#714-use-tosorted-instead-of-sort-for-immutability)+8. [Advanced Patterns](#8-advanced-patterns) — **LOW**+ - 8.1 [Do Not Put Effect Events in Dependency Arrays](#81-do-not-put-effect-events-in-dependency-arrays)+ - 8.2 [Initialize App Once, Not Per Mount](#82-initialize-app-once-not-per-mount)+ - 8.3 [Store Event Handlers in Refs](#83-store-event-handlers-in-refs)+ - 8.4 [useEffectEvent for Stable Callback Refs](#84-useeffectevent-for-stable-callback-refs)++---++## 1. Eliminating Waterfalls++**Impact: CRITICAL**++Waterfalls are the #1 performance killer. Each sequential await adds full network latency. Eliminating them yields the largest gains.++### 1.1 Check Cheap Conditions Before Async Flags++**Impact: HIGH (avoids unnecessary async work when a synchronous guard already fails)**++When a branch uses `await` for a flag or remote value and also requires a **cheap synchronous** condition (local props, request metadata, already-loaded state), evaluate the cheap condition **first**. Otherwise you pay for the async call even when the compound condition can never be true.++This is a specialization of [Defer Await Until Needed](./async-defer-await.md) for `flag && cheapCondition` style checks.++**Incorrect:**++```typescript+const someFlag = await getFlag()++if (someFlag && someCondition) {+ // ...+}+```++**Correct:**++```typescript+if (someCondition) {+ const someFlag = await getFlag()+ if (someFlag) {+ // ...+ }+}+```++This matters when `getFlag` hits the network, a feature-flag service, or `React.cache` / DB work: skipping it when `someCondition` is false removes that cost on the cold path.++Keep the original order if `someCondition` is expensive, depends on the flag, or you must run side effects in a fixed order.++### 1.2 Defer Await Until Needed++**Impact: HIGH (avoids blocking unused code paths)**++Move `await` operations into the branches where they're actually used to avoid blocking code paths that don't need them.++**Incorrect: blocks both branches**++```typescript+async function handleRequest(userId: string, skipProcessing: boolean) {+ const userData = await fetchUserData(userId)++ if (skipProcessing) {+ // Returns immediately but still waited for userData+ return { skipped: true }+ }++ // Only this branch uses userData+ return processUserData(userData)+}+```++**Correct: only blocks when needed**++```typescript+async function handleRequest(userId: string, skipProcessing: boolean) {+ if (skipProcessing) {+ // Returns immediately without waiting+ return { skipped: true }+ }++ // Fetch only when needed+ const userData = await fetchUserData(userId)+ return processUserData(userData)+}+```++**Another example: early return optimization**++```typescript+// Incorrect: always fetches permissions+async function updateResource(resourceId: string, userId: string) {+ const permissions = await fetchPermissions(userId)+ const resource = await getResource(resourceId)++ if (!resource) {+ return { error: 'Not found' }+ }++ if (!permissions.canEdit) {+ return { error: 'Forbidden' }+ }++ return await updateResourceData(resource, permissions)+}++// Correct: fetches only when needed+async function updateResource(resourceId: string, userId: string) {+ const resource = await getResource(resourceId)++ if (!resource) {+ return { error: 'Not found' }+ }++ const permissions = await fetchPermissions(userId)++ if (!permissions.canEdit) {+ return { error: 'Forbidden' }+ }++ return await updateResourceData(resource, permissions)+}+```++This optimization is especially valuable when the skipped branch is frequently taken, or when the deferred operation is expensive.++For `await getFlag()` combined with a cheap synchronous guard (`flag && someCondition`), see [Check Cheap Conditions Before Async Flags](./async-cheap-condition-before-await.md).++### 1.3 Dependency-Based Parallelization++**Impact: CRITICAL (2-10× improvement)**++For operations with partial dependencies, use `better-all` to maximize parallelism. It automatically starts each task at the earliest possible moment.++**Incorrect: profile waits for config unnecessarily**++```typescript+const [user, config] = await Promise.all([+ fetchUser(),+ fetchConfig()+])+const profile = await fetchProfile(user.id)+```++**Correct: config and profile run in parallel**++```typescript+import { all } from 'better-all'++const { user, config, profile } = await all({+ async user() { return fetchUser() },+ async config() { return fetchConfig() },+ async profile() {+ return fetchProfile((await this.$.user).id)+ }+})+```++**Alternative without extra dependencies:**++```typescript+const userPromise = fetchUser()+const profilePromise = userPromise.then(user => fetchProfile(user.id))++const [user, config, profile] = await Promise.all([+ userPromise,+ fetchConfig(),+ profilePromise+])+```++We can also create all the promises first, and do `Promise.all()` at the end.++Reference: [https://github.com/shuding/better-all](https://github.com/shuding/better-all)++### 1.4 Prevent Waterfall Chains in API Routes++**Impact: CRITICAL (2-10× improvement)**++In API routes and Server Actions, start independent operations immediately, even if you don't await them yet.++**Incorrect: config waits for auth, data waits for both**++```typescript+export async function GET(request: Request) {+ const session = await auth()+ const config = await fetchConfig()+ const data = await fetchData(session.user.id)+ return Response.json({ data, config })+}+```++**Correct: auth and config start immediately**++```typescript+export async function GET(request: Request) {+ const sessionPromise = auth()+ const configPromise = fetchConfig()+ const session = await sessionPromise+ const [config, data] = await Promise.all([+ configPromise,+ fetchData(session.user.id)+ ])+ return Response.json({ data, config })+}+```++For operations with more complex dependency chains, use `better-all` to automatically maximize parallelism (see Dependency-Based Parallelization).++### 1.5 Promise.all() for Independent Operations++**Impact: CRITICAL (2-10× improvement)**++When async operations have no interdependencies, execute them concurrently using `Promise.all()`.++**Incorrect: sequential execution, 3 round trips**++```typescript+const user = await fetchUser()+const posts = await fetchPosts()+const comments = await fetchComments()+```++**Correct: parallel execution, 1 round trip**++```typescript+const [user, posts, comments] = await Promise.all([+ fetchUser(),+ fetchPosts(),+ fetchComments()+])+```++### 1.6 Strategic Suspense Boundaries++**Impact: HIGH (faster initial paint)**++Instead of awaiting data in async components before returning JSX, use Suspense boundaries to show the wrapper UI faster while data loads.++**Incorrect: wrapper blocked by data fetching**++```tsx+async function Page() {+ const data = await fetchData() // Blocks entire page++ return (+ <div>+ <div>Sidebar</div>+ <div>Header</div>+ <div>+ <DataDisplay data={data} />+ </div>+ <div>Footer</div>+ </div>+ )+}+```++The entire layout waits for data even though only the middle section needs it.++**Correct: wrapper shows immediately, data streams in**++```tsx+function Page() {+ return (+ <div>+ <div>Sidebar</div>+ <div>Header</div>+ <div>+ <Suspense fallback={<Skeleton />}>+ <DataDisplay />+ </Suspense>+ </div>+ <div>Footer</div>+ </div>+ )+}++async function DataDisplay() {+ const data = await fetchData() // Only blocks this component+ return <div>{data.content}</div>+}+```++Sidebar, Header, and Footer render immediately. Only DataDisplay waits for data.++**Alternative: share promise across components**++```tsx+function Page() {+ // Start fetch immediately, but don't await+ const dataPromise = fetchData()++ return (+ <div>+ <div>Sidebar</div>+ <div>Header</div>+ <Suspense fallback={<Skeleton />}>+ <DataDisplay dataPromise={dataPromise} />+ <DataSummary dataPromise={dataPromise} />+ </Suspense>+ <div>Footer</div>+ </div>+ )+}++function DataDisplay({ dataPromise }: { dataPromise: Promise<Data> }) {+ const data = use(dataPromise) // Unwraps the promise+ return <div>{data.content}</div>+}++function DataSummary({ dataPromise }: { dataPromise: Promise<Data> }) {+ const data = use(dataPromise) // Reuses the same promise+ return <div>{data.summary}</div>+}+```++Both components share the same promise, so only one fetch occurs. Layout renders immediately while both components wait together.++**When NOT to use this pattern:**++- Critical data needed for layout decisions (affects positioning)++- SEO-critical content above the fold++- Small, fast queries where suspense overhead isn't worth it++- When you want to avoid layout shift (loading → content jump)++**Trade-off:** Faster initial paint vs potential layout shift. Choose based on your UX priorities.++---++## 2. Bundle Size Optimization++**Impact: CRITICAL**++Reducing initial bundle size improves Time to Interactive and Largest Contentful Paint.++### 2.1 Avoid Barrel File Imports++**Impact: CRITICAL (200-800ms import cost, slow builds)**++Import directly from source files instead of barrel files to avoid loading thousands of unused modules. **Barrel files** are entry points that re-export multiple modules (e.g., `index.js` that does `export * from './module'`).++Popular icon and component libraries can have **up to 10,000 re-exports** in their entry file. For many React packages, **it takes 200-800ms just to import them**, affecting both development speed and production cold starts.++**Why tree-shaking doesn't help:** When a library is marked as external (not bundled), the bundler can't optimize it. If you bundle it to enable tree-shaking, builds become substantially slower analyzing the entire module graph.++**Incorrect: imports entire library**++```tsx+import { Check, X, Menu } from 'lucide-react'+// Loads 1,583 modules, takes ~2.8s extra in dev+// Runtime cost: 200-800ms on every cold start++import { Button, TextField } from '@mui/material'+// Loads 2,225 modules, takes ~4.2s extra in dev+```++**Correct - Next.js 13.5+ (recommended):**++```tsx+// Keep the standard imports - Next.js transforms them to direct imports+import { Check, X, Menu } from 'lucide-react'+// Full TypeScript support, no manual path wrangling+```++This is the recommended approach because it preserves TypeScript type safety and editor autocompletion while still eliminating the barrel import cost.++**Correct - Direct imports (non-Next.js projects):**++```tsx+import Button from '@mui/material/Button'+import TextField from '@mui/material/TextField'+// Loads only what you use+```++> **TypeScript warning:** Some libraries (notably `lucide-react`) don't ship `.d.ts` files for their deep import paths. Importing from `lucide-react/dist/esm/icons/check` resolves to an implicit `any` type, causing errors under `strict` or `noImplicitAny`. Prefer `optimizePackageImports` when available, or verify the library exports types for its subpaths before using direct imports.++These optimizations provide 15-70% faster dev boot, 28% faster builds, 40% faster cold starts, and significantly faster HMR.++Libraries commonly affected: `lucide-react`, `@mui/material`, `@mui/icons-material`, `@tabler/icons-react`, `react-icons`, `@headlessui/react`, `@radix-ui/react-*`, `lodash`, `ramda`, `date-fns`, `rxjs`, `react-use`.++Reference: [https://vercel.com/blog/how-we-optimized-package-imports-in-next-js](https://vercel.com/blog/how-we-optimized-package-imports-in-next-js)++### 2.2 Conditional Module Loading++**Impact: HIGH (loads large data only when needed)**++Load large data or modules only when a feature is activated.++**Example: lazy-load animation frames**++```tsx+function AnimationPlayer({ enabled, setEnabled }: { enabled: boolean; setEnabled: React.Dispatch<React.SetStateAction<boolean>> }) {+ const [frames, setFrames] = useState<Frame[] | null>(null)++ useEffect(() => {+ if (enabled && !frames && typeof window !== 'undefined') {+ import('./animation-frames.js')+ .then(mod => setFrames(mod.frames))+ .catch(() => setEnabled(false))+ }+ }, [enabled, frames, setEnabled])++ if (!frames) return <Skeleton />+ return <Canvas frames={frames} />+}+```++The `typeof window !== 'undefined'` check prevents bundling this module for SSR, optimizing server bundle size and build speed.++### 2.3 Defer Non-Critical Third-Party Libraries++**Impact: MEDIUM (loads after hydration)**++Analytics, logging, and error tracking don't block user interaction. Load them after hydration.++**Incorrect: blocks initial bundle**++```tsx+import { Analytics } from '@vercel/analytics/react'++export default function RootLayout({ children }) {+ return (+ <html>+ <body>+ {children}+ <Analytics />+ </body>+ </html>+ )+}+```++**Correct: loads after hydration**++```tsx+import dynamic from 'next/dynamic'++const Analytics = dynamic(+ () => import('@vercel/analytics/react').then(m => m.Analytics),+ { ssr: false }+)++export default function RootLayout({ children }) {+ return (+ <html>+ <body>+ {children}+ <Analytics />+ </body>+ </html>+ )+}+```++### 2.4 Dynamic Imports for Heavy Components++**Impact: CRITICAL (directly affects TTI and LCP)**++Use `next/dynamic` to lazy-load large components not needed on initial render.++**Incorrect: Monaco bundles with main chunk ~300KB**++```tsx+import { MonacoEditor } from './monaco-editor'++function CodePanel({ code }: { code: string }) {+ return <MonacoEditor value={code} />+}+```++**Correct: Monaco loads on demand**++```tsx+import dynamic from 'next/dynamic'++const MonacoEditor = dynamic(+ () => import('./monaco-editor').then(m => m.MonacoEditor),+ { ssr: false }+)++function CodePanel({ code }: { code: string }) {+ return <MonacoEditor value={code} />+}+```++### 2.5 Prefer Statically Analyzable Paths++**Impact: HIGH (avoids accidental broad bundles and file traces)**++Build tools work best when import and file-system paths are obvious at build time. If you hide the real path inside a variable or compose it too dynamically, the tool either has to include a broad set of possible files, warn that it cannot analyze the import, or widen file tracing to stay safe.++Prefer explicit maps or literal paths so the set of reachable files stays narrow and predictable. This is the same rule whether you are choosing modules with `import()` or reading files in server/build code.++When analysis becomes too broad, the cost is real:++- Larger server bundles++- Slower builds++- Worse cold starts++- More memory use++**Incorrect: the bundler cannot tell what may be imported**++```ts+const PAGE_MODULES = {+ home: './pages/home',+ settings: './pages/settings',+} as const++const Page = await import(PAGE_MODULES[pageName])+```++**Correct: use an explicit map of allowed modules**++```ts+const PAGE_MODULES = {+ home: () => import('./pages/home'),+ settings: () => import('./pages/settings'),+} as const++const Page = await PAGE_MODULES[pageName]()+```++**Incorrect: a 2-value enum still hides the final path from static analysis**++```ts+const baseDir = path.join(process.cwd(), 'content/' + contentKind)+```++**Correct: make each final path literal at the callsite**++```ts+const baseDir =+ kind === ContentKind.Blog+ ? path.join(process.cwd(), 'content/blog')+ : path.join(process.cwd(), 'content/docs')+```++In Next.js server code, this matters for output file tracing too. `path.join(process.cwd(), someVar)` can widen the traced file set because Next.js statically analyze `import`, `require`, and `fs` usage.++Reference: [https://nextjs.org/docs/app/api-reference/config/next-config-js/output](https://nextjs.org/docs/app/api-reference/config/next-config-js/output), [https://nextjs.org/learn/seo/dynamic-imports](https://nextjs.org/learn/seo/dynamic-imports), [https://vite.dev/guide/features.html](https://vite.dev/guide/features.html), [https://esbuild.github.io/api/](https://esbuild.github.io/api/), [https://www.npmjs.com/package/@rollup/plugin-dynamic-import-vars](https://www.npmjs.com/package/@rollup/plugin-dynamic-import-vars), [https://webpack.js.org/guides/dependency-management/](https://webpack.js.org/guides/dependency-management/)++### 2.6 Preload Based on User Intent++**Impact: MEDIUM (reduces perceived latency)**++Preload heavy bundles before they're needed to reduce perceived latency.++**Example: preload on hover/focus**++```tsx+function EditorButton({ onClick }: { onClick: () => void }) {+ const preload = () => {+ if (typeof window !== 'undefined') {+ void import('./monaco-editor')+ }+ }++ return (+ <button+ onMouseEnter={preload}+ onFocus={preload}+ onClick={onClick}+ >+ Open Editor+ </button>+ )+}+```++**Example: preload when feature flag is enabled**++```tsx+function FlagsProvider({ children, flags }: Props) {+ useEffect(() => {+ if (flags.editorEnabled && typeof window !== 'undefined') {+ void import('./monaco-editor').then(mod => mod.init())+ }+ }, [flags.editorEnabled])++ return <FlagsContext.Provider value={flags}>+ {children}+ </FlagsContext.Provider>+}+```++The `typeof window !== 'undefined'` check prevents bundling preloaded modules for SSR, optimizing server bundle size and build speed.++---++## 3. Server-Side Performance++**Impact: HIGH**++Optimizing server-side rendering and data fetching eliminates server-side waterfalls and reduces response times.++### 3.1 Authenticate Server Actions Like API Routes++**Impact: CRITICAL (prevents unauthorized access to server mutations)**++Server Actions (functions with `"use server"`) are exposed as public endpoints, just like API routes. Always verify authentication and authorization **inside** each Server Action—do not rely solely on middleware, layout guards, or page-level checks, as Server Actions can be invoked directly.++Next.js documentation explicitly states: "Treat Server Actions with the same security considerations as public-facing API endpoints, and verify if the user is allowed to perform a mutation."++**Incorrect: no authentication check**++```typescript+'use server'++export async function deleteUser(userId: string) {+ // Anyone can call this! No auth check+ await db.user.delete({ where: { id: userId } })+ return { success: true }+}+```++**Correct: authentication inside the action**++```typescript+'use server'++import { verifySession } from '@/lib/auth'+import { unauthorized } from '@/lib/errors'++export async function deleteUser(userId: string) {+ // Always check auth inside the action+ const session = await verifySession()++ if (!session) {+ throw unauthorized('Must be logged in')+ }++ // Check authorization too+ if (session.user.role !== 'admin' && session.user.id !== userId) {+ throw unauthorized('Cannot delete other users')+ }++ await db.user.delete({ where: { id: userId } })+ return { success: true }+}+```++**With input validation:**++```typescript+'use server'++import { verifySession } from '@/lib/auth'+import { z } from 'zod'++const updateProfileSchema = z.object({+ userId: z.string().uuid(),+ name: z.string().min(1).max(100),+ email: z.string().email()+})++export async function updateProfile(data: unknown) {+ // Validate input first+ const validated = updateProfileSchema.parse(data)++ // Then authenticate+ const session = await verifySession()+ if (!session) {+ throw new Error('Unauthorized')+ }++ // Then authorize+ if (session.user.id !== validated.userId) {+ throw new Error('Can only update own profile')+ }++ // Finally perform the mutation+ await db.user.update({+ where: { id: validated.userId },+ data: {+ name: validated.name,+ email: validated.email+ }+ })++ return { success: true }+}+```++Reference: [https://nextjs.org/docs/app/guides/authentication](https://nextjs.org/docs/app/guides/authentication)++### 3.2 Avoid Duplicate Serialization in RSC Props++**Impact: LOW (reduces network payload by avoiding duplicate serialization)**++RSC→client serialization deduplicates by object reference, not value. Same reference = serialized once; new reference = serialized again. Do transformations (`.toSorted()`, `.filter()`, `.map()`) in client, not server.++**Incorrect: duplicates array**++```tsx+// RSC: sends 6 strings (2 arrays × 3 items)+<ClientList usernames={usernames} usernamesOrdered={usernames.toSorted()} />+```++**Correct: sends 3 strings**++```tsx+// RSC: send once+<ClientList usernames={usernames} />++// Client: transform there+'use client'+const sorted = useMemo(() => [...usernames].sort(), [usernames])+```++**Nested deduplication behavior:**++```tsx+// string[] - duplicates everything+usernames={['a','b']} sorted={usernames.toSorted()} // sends 4 strings++// object[] - duplicates array structure only+users={[{id:1},{id:2}]} sorted={users.toSorted()} // sends 2 arrays + 2 unique objects (not 4)+```++Deduplication works recursively. Impact varies by data type:++- `string[]`, `number[]`, `boolean[]`: **HIGH impact** - array + all primitives fully duplicated++- `object[]`: **LOW impact** - array duplicated, but nested objects deduplicated by reference++**Operations breaking deduplication: create new references**++- Arrays: `.toSorted()`, `.filter()`, `.map()`, `.slice()`, `[...arr]`++- Objects: `{...obj}`, `Object.assign()`, `structuredClone()`, `JSON.parse(JSON.stringify())`++**More examples:**++```tsx+// ❌ Bad+<C users={users} active={users.filter(u => u.active)} />+<C product={product} productName={product.name} />++// ✅ Good+<C users={users} />+<C product={product} />+// Do filtering/destructuring in client+```++**Exception:** Pass derived data when transformation is expensive or client doesn't need original.++### 3.3 Avoid Shared Module State for Request Data++**Impact: HIGH (prevents concurrency bugs and request data leaks)**++For React Server Components and client components rendered during SSR, avoid using mutable module-level variables to share request-scoped data. Server renders can run concurrently in the same process. If one render writes to shared module state and another render reads it, you can get race conditions, cross-request contamination, and security bugs where one user's data appears in another user's response.++Treat module scope on the server as process-wide shared memory, not request-local state.++**Incorrect: request data leaks across concurrent renders**++```tsx+let currentUser: User | null = null++export default async function Page() {+ currentUser = await auth()+ return <Dashboard />+}++async function Dashboard() {+ return <div>{currentUser?.name}</div>+}+```++If two requests overlap, request A can set `currentUser`, then request B overwrites it before request A finishes rendering `Dashboard`.++**Correct: keep request data local to the render tree**++```tsx+export default async function Page() {+ const user = await auth()+ return <Dashboard user={user} />+}++function Dashboard({ user }: { user: User | null }) {+ return <div>{user?.name}</div>+}+```++Safe exceptions:++- Immutable static assets or config loaded once at module scope++- Shared caches intentionally designed for cross-request reuse and keyed correctly++- Process-wide singletons that do not store request- or user-specific mutable data++For static assets and config, see [Hoist Static I/O to Module Level](./server-hoist-static-io.md).++### 3.4 Cross-Request LRU Caching++**Impact: HIGH (caches across requests)**++`React.cache()` only works within one request. For data shared across sequential requests (user clicks button A then button B), use an LRU cache.++**Implementation:**++```typescript+import { LRUCache } from 'lru-cache'++const cache = new LRUCache<string, any>({+ max: 1000,+ ttl: 5 * 60 * 1000 // 5 minutes+})++export async function getUser(id: string) {+ const cached = cache.get(id)+ if (cached) return cached++ const user = await db.user.findUnique({ where: { id } })+ cache.set(id, user)+ return user+}++// Request 1: DB query, result cached+// Request 2: cache hit, no DB query+```++Use when sequential user actions hit multiple endpoints needing the same data within seconds.++**With Vercel's [Fluid Compute](https://vercel.com/docs/fluid-compute):** LRU caching is especially effective because multiple concurrent requests can share the same function instance and cache. This means the cache persists across requests without needing external storage like Redis.++**In traditional serverless:** Each invocation runs in isolation, so consider Redis for cross-process caching.++Reference: [https://github.com/isaacs/node-lru-cache](https://github.com/isaacs/node-lru-cache)++### 3.5 Hoist Static I/O to Module Level++**Impact: HIGH (avoids repeated file/network I/O per request)**++When loading static assets (fonts, logos, images, config files) in route handlers or server functions, hoist the I/O operation to module level. Module-level code runs once when the module is first imported, not on every request. This eliminates redundant file system reads or network fetches that would otherwise run on every invocation.++**Incorrect: reads font file on every request**++```typescript+// app/api/og/route.tsx+import { ImageResponse } from 'next/og'++export async function GET(request: Request) {+ // Runs on EVERY request - expensive!+ const fontData = await fetch(+ new URL('./fonts/Inter.ttf', import.meta.url)+ ).then(res => res.arrayBuffer())++ const logoData = await fetch(+ new URL('./images/logo.png', import.meta.url)+ ).then(res => res.arrayBuffer())++ return new ImageResponse(+ <div style={{ fontFamily: 'Inter' }}>+ <img src={logoData} />+ Hello World+ </div>,+ { fonts: [{ name: 'Inter', data: fontData }] }+ )+}+```++**Correct: loads once at module initialization**++```typescript+// app/api/og/route.tsx+import { ImageResponse } from 'next/og'++// Module-level: runs ONCE when module is first imported+const fontData = fetch(+ new URL('./fonts/Inter.ttf', import.meta.url)+).then(res => res.arrayBuffer())++const logoData = fetch(+ new URL('./images/logo.png', import.meta.url)+).then(res => res.arrayBuffer())++export async function GET(request: Request) {+ // Await the already-started promises+ const [font, logo] = await Promise.all([fontData, logoData])++ return new ImageResponse(+ <div style={{ fontFamily: 'Inter' }}>+ <img src={logo} />+ Hello World+ </div>,+ { fonts: [{ name: 'Inter', data: font }] }+ )+}+```++**Correct: synchronous fs at module level**++```typescript+// app/api/og/route.tsx+import { ImageResponse } from 'next/og'+import { readFileSync } from 'fs'+import { join } from 'path'++// Synchronous read at module level - blocks only during module init+const fontData = readFileSync(+ join(process.cwd(), 'public/fonts/Inter.ttf')+)++const logoData = readFileSync(+ join(process.cwd(), 'public/images/logo.png')+)++export async function GET(request: Request) {+ return new ImageResponse(+ <div style={{ fontFamily: 'Inter' }}>+ <img src={logoData} />+ Hello World+ </div>,+ { fonts: [{ name: 'Inter', data: fontData }] }+ )+}+```++**Incorrect: reads config on every call**++```typescript+import fs from 'node:fs/promises'++export async function processRequest(data: Data) {+ const config = JSON.parse(+ await fs.readFile('./config.json', 'utf-8')+ )+ const template = await fs.readFile('./template.html', 'utf-8')++ return render(template, data, config)+}+```++**Correct: hoists config and template to module level**++```typescript+import fs from 'node:fs/promises'++const configPromise = fs+ .readFile('./config.json', 'utf-8')+ .then(JSON.parse)+const templatePromise = fs.readFile('./template.html', 'utf-8')++export async function processRequest(data: Data) {+ const [config, template] = await Promise.all([+ configPromise,+ templatePromise,+ ])++ return render(template, data, config)+}+```++When to use this pattern:++- Loading fonts for OG image generation++- Loading static logos, icons, or watermarks++- Reading configuration files that don't change at runtime++- Loading email templates or other static templates++- Any static asset that's the same across all requests++When not to use this pattern:++- Assets that vary per request or user++- Files that may change during runtime (use caching with TTL instead)++- Large files that would consume too much memory if kept loaded++- Sensitive data that shouldn't persist in memory++With Vercel's [Fluid Compute](https://vercel.com/docs/fluid-compute), module-level caching is especially effective because multiple concurrent requests share the same function instance. The static assets stay loaded in memory across requests without cold start penalties.++In traditional serverless, each cold start re-executes module-level code, but subsequent warm invocations reuse the loaded assets until the instance is recycled.++### 3.6 Minimize Serialization at RSC Boundaries++**Impact: HIGH (reduces data transfer size)**++The React Server/Client boundary serializes all object properties into strings and embeds them in the HTML response and subsequent RSC requests. This serialized data directly impacts page weight and load time, so **size matters a lot**. Only pass fields that the client actually uses.++**Incorrect: serializes all 50 fields**++```tsx+async function Page() {+ const user = await fetchUser() // 50 fields+ return <Profile user={user} />+}++'use client'+function Profile({ user }: { user: User }) {+ return <div>{user.name}</div> // uses 1 field+}+```++**Correct: serializes only 1 field**++```tsx+async function Page() {+ const user = await fetchUser()+ return <Profile name={user.name} />+}++'use client'+function Profile({ name }: { name: string }) {+ return <div>{name}</div>+}+```++### 3.7 Parallel Data Fetching with Component Composition++**Impact: CRITICAL (eliminates server-side waterfalls)**++React Server Components execute sequentially within a tree. Restructure with composition to parallelize data fetching.++**Incorrect: Sidebar waits for Page's fetch to complete**++```tsx+export default async function Page() {+ const header = await fetchHeader()+ return (+ <div>+ <div>{header}</div>+ <Sidebar />+ </div>+ )+}++async function Sidebar() {+ const items = await fetchSidebarItems()+ return <nav>{items.map(renderItem)}</nav>+}+```++**Correct: both fetch simultaneously**++```tsx+async function Header() {+ const data = await fetchHeader()+ return <div>{data}</div>+}++async function Sidebar() {+ const items = await fetchSidebarItems()+ return <nav>{items.map(renderItem)}</nav>+}++export default function Page() {+ return (+ <div>+ <Header />+ <Sidebar />+ </div>+ )+}+```++**Alternative with children prop:**++```tsx+async function Header() {+ const data = await fetchHeader()+ return <div>{data}</div>+}++async function Sidebar() {+ const items = await fetchSidebarItems()+ return <nav>{items.map(renderItem)}</nav>+}++function Layout({ children }: { children: ReactNode }) {+ return (+ <div>+ <Header />+ {children}+ </div>+ )+}++export default function Page() {+ return (+ <Layout>+ <Sidebar />+ </Layout>+ )+}+```++### 3.8 Parallel Nested Data Fetching++**Impact: CRITICAL (eliminates server-side waterfalls)**++When fetching nested data in parallel, chain dependent fetches within each item's promise so a slow item doesn't block the rest.++**Incorrect: a single slow item blocks all nested fetches**++```tsx+const chats = await Promise.all(+ chatIds.map(id => getChat(id))+)++const chatAuthors = await Promise.all(+ chats.map(chat => getUser(chat.author))+)+```++If one `getChat(id)` out of 100 is extremely slow, the authors of the other 99 chats can't start loading even though their data is ready.++**Correct: each item chains its own nested fetch**++```tsx+const chatAuthors = await Promise.all(+ chatIds.map(id => getChat(id).then(chat => getUser(chat.author)))+)+```++Each item independently chains `getChat` → `getUser`, so a slow chat doesn't block author fetches for the others.++### 3.9 Per-Request Deduplication with React.cache()++**Impact: MEDIUM (deduplicates within request)**++Use `React.cache()` for server-side request deduplication. Authentication and database queries benefit most.++**Usage:**++```typescript+import { cache } from 'react'++export const getCurrentUser = cache(async () => {+ const session = await auth()+ if (!session?.user?.id) return null+ return await db.user.findUnique({+ where: { id: session.user.id }+ })+})+```++Within a single request, multiple calls to `getCurrentUser()` execute the query only once.++**Avoid inline objects as arguments:**++`React.cache()` uses shallow equality (`Object.is`) to determine cache hits. Inline objects create new references each call, preventing cache hits.++**Incorrect: always cache miss**++```typescript+const getUser = cache(async (params: { uid: number }) => {+ return await db.user.findUnique({ where: { id: params.uid } })+})++// Each call creates new object, never hits cache+getUser({ uid: 1 })+getUser({ uid: 1 }) // Cache miss, runs query again+```++**Correct: cache hit**++```typescript+const params = { uid: 1 }+getUser(params) // Query runs+getUser(params) // Cache hit (same reference)+```++If you must pass objects, pass the same reference:++**Next.js-Specific Note:**++In Next.js, the `fetch` API is automatically extended with request memoization. Requests with the same URL and options are automatically deduplicated within a single request, so you don't need `React.cache()` for `fetch` calls. However, `React.cache()` is still essential for other async tasks:++- Database queries (Prisma, Drizzle, etc.)++- Heavy computations++- Authentication checks++- File system operations++- Any non-fetch async work++Use `React.cache()` to deduplicate these operations across your component tree.++Reference: [https://react.dev/reference/react/cache](https://react.dev/reference/react/cache)++### 3.10 Use after() for Non-Blocking Operations++**Impact: MEDIUM (faster response times)**++Use Next.js's `after()` to schedule work that should execute after a response is sent. This prevents logging, analytics, and other side effects from blocking the response.++**Incorrect: blocks response**++```tsx+import { logUserAction } from '@/app/utils'++export async function POST(request: Request) {+ // Perform mutation+ await updateDatabase(request)++ // Logging blocks the response+ const userAgent = request.headers.get('user-agent') || 'unknown'+ await logUserAction({ userAgent })++ return new Response(JSON.stringify({ status: 'success' }), {+ status: 200,+ headers: { 'Content-Type': 'application/json' }+ })+}+```++**Correct: non-blocking**++```tsx+import { after } from 'next/server'+import { headers, cookies } from 'next/headers'+import { logUserAction } from '@/app/utils'++export async function POST(request: Request) {+ // Perform mutation+ await updateDatabase(request)++ // Log after response is sent+ after(async () => {+ const userAgent = (await headers()).get('user-agent') || 'unknown'+ const sessionCookie = (await cookies()).get('session-id')?.value || 'anonymous'++ logUserAction({ sessionCookie, userAgent })+ })++ return new Response(JSON.stringify({ status: 'success' }), {+ status: 200,+ headers: { 'Content-Type': 'application/json' }+ })+}+```++The response is sent immediately while logging happens in the background.++**Common use cases:**++- Analytics tracking++- Audit logging++- Sending notifications++- Cache invalidation++- Cleanup tasks++**Important notes:**++- `after()` runs even if the response fails or redirects++- Works in Server Actions, Route Handlers, and Server Components++Reference: [https://nextjs.org/docs/app/api-reference/functions/after](https://nextjs.org/docs/app/api-reference/functions/after)++---++## 4. Client-Side Data Fetching++**Impact: MEDIUM-HIGH**++Automatic deduplication and efficient data fetching patterns reduce redundant network requests.++### 4.1 Deduplicate Global Event Listeners++**Impact: LOW (single listener for N components)**++Use `useSWRSubscription()` to share global event listeners across component instances.++**Incorrect: N instances = N listeners**++```tsx+function useKeyboardShortcut(key: string, callback: () => void) {+ useEffect(() => {+ const handler = (e: KeyboardEvent) => {+ if (e.metaKey && e.key === key) {+ callback()+ }+ }+ window.addEventListener('keydown', handler)+ return () => window.removeEventListener('keydown', handler)+ }, [key, callback])+}+```++When using the `useKeyboardShortcut` hook multiple times, each instance will register a new listener.++**Correct: N instances = 1 listener**++```tsx+import useSWRSubscription from 'swr/subscription'++// Module-level Map to track callbacks per key+const keyCallbacks = new Map<string, Set<() => void>>()++function useKeyboardShortcut(key: string, callback: () => void) {+ // Register this callback in the Map+ useEffect(() => {+ if (!keyCallbacks.has(key)) {+ keyCallbacks.set(key, new Set())+ }+ keyCallbacks.get(key)!.add(callback)++ return () => {+ const set = keyCallbacks.get(key)+ if (set) {+ set.delete(callback)+ if (set.size === 0) {+ keyCallbacks.delete(key)+ }+ }+ }+ }, [key, callback])++ useSWRSubscription('global-keydown', () => {+ const handler = (e: KeyboardEvent) => {+ if (e.metaKey && keyCallbacks.has(e.key)) {+ keyCallbacks.get(e.key)!.forEach(cb => cb())+ }+ }+ window.addEventListener('keydown', handler)+ return () => window.removeEventListener('keydown', handler)+ })+}++function Profile() {+ // Multiple shortcuts will share the same listener+ useKeyboardShortcut('p', () => { /* ... */ })+ useKeyboardShortcut('k', () => { /* ... */ })+ // ...+}+```++### 4.2 Use Passive Event Listeners for Scrolling Performance++**Impact: MEDIUM (eliminates scroll delay caused by event listeners)**++Add `{ passive: true }` to touch and wheel event listeners to enable immediate scrolling. Browsers normally wait for listeners to finish to check if `preventDefault()` is called, causing scroll delay.++**Incorrect:**++```typescript+useEffect(() => {+ const handleTouch = (e: TouchEvent) => console.log(e.touches[0].clientX)+ const handleWheel = (e: WheelEvent) => console.log(e.deltaY)++ document.addEventListener('touchstart', handleTouch)+ document.addEventListener('wheel', handleWheel)++ return () => {+ document.removeEventListener('touchstart', handleTouch)+ document.removeEventListener('wheel', handleWheel)+ }+}, [])+```++**Correct:**++```typescript+useEffect(() => {+ const handleTouch = (e: TouchEvent) => console.log(e.touches[0].clientX)+ const handleWheel = (e: WheelEvent) => console.log(e.deltaY)++ document.addEventListener('touchstart', handleTouch, { passive: true })+ document.addEventListener('wheel', handleWheel, { passive: true })++ return () => {+ document.removeEventListener('touchstart', handleTouch)+ document.removeEventListener('wheel', handleWheel)+ }+}, [])+```++**Use passive when:** tracking/analytics, logging, any listener that doesn't call `preventDefault()`.++**Don't use passive when:** implementing custom swipe gestures, custom zoom controls, or any listener that needs `preventDefault()`.++### 4.3 Use SWR for Automatic Deduplication++**Impact: MEDIUM-HIGH (automatic deduplication)**++SWR enables request deduplication, caching, and revalidation across component instances.++**Incorrect: no deduplication, each instance fetches**++```tsx+function UserList() {+ const [users, setUsers] = useState([])+ useEffect(() => {+ fetch('/api/users')+ .then(r => r.json())+ .then(setUsers)+ }, [])+}+```++**Correct: multiple instances share one request**++```tsx+import useSWR from 'swr'++function UserList() {+ const { data: users } = useSWR('/api/users', fetcher)+}+```++**For immutable data:**++```tsx+import { useImmutableSWR } from '@/lib/swr'++function StaticContent() {+ const { data } = useImmutableSWR('/api/config', fetcher)+}+```++**For mutations:**++```tsx+import { useSWRMutation } from 'swr/mutation'++function UpdateButton() {+ const { trigger } = useSWRMutation('/api/user', updateUser)+ return <button onClick={() => trigger()}>Update</button>+}+```++Reference: [https://swr.vercel.app](https://swr.vercel.app)++### 4.4 Version and Minimize localStorage Data++**Impact: MEDIUM (prevents schema conflicts, reduces storage size)**++Add version prefix to keys and store only needed fields. Prevents schema conflicts and accidental storage of sensitive data.++**Incorrect:**++```typescript+// No version, stores everything, no error handling+localStorage.setItem('userConfig', JSON.stringify(fullUserObject))+const data = localStorage.getItem('userConfig')+```++**Correct:**++```typescript+const VERSION = 'v2'++function saveConfig(config: { theme: string; language: string }) {+ try {+ localStorage.setItem(`userConfig:${VERSION}`, JSON.stringify(config))+ } catch {+ // Throws in incognito/private browsing, quota exceeded, or disabled+ }+}++function loadConfig() {+ try {+ const data = localStorage.getItem(`userConfig:${VERSION}`)+ return data ? JSON.parse(data) : null+ } catch {+ return null+ }+}++// Migration from v1 to v2+function migrate() {+ try {+ const v1 = localStorage.getItem('userConfig:v1')+ if (v1) {+ const old = JSON.parse(v1)+ saveConfig({ theme: old.darkMode ? 'dark' : 'light', language: old.lang })+ localStorage.removeItem('userConfig:v1')+ }+ } catch {}+}+```++**Store minimal fields from server responses:**++```typescript+// User object has 20+ fields, only store what UI needs+function cachePrefs(user: FullUser) {+ try {+ localStorage.setItem('prefs:v1', JSON.stringify({+ theme: user.preferences.theme,+ notifications: user.preferences.notifications+ }))+ } catch {}+}+```++**Always wrap in try-catch:** `getItem()` and `setItem()` throw in incognito/private browsing (Safari, Firefox), when quota exceeded, or when disabled.++**Benefits:** Schema evolution via versioning, reduced storage size, prevents storing tokens/PII/internal flags.++---++## 5. Re-render Optimization++**Impact: MEDIUM**++Reducing unnecessary re-renders minimizes wasted computation and improves UI responsiveness.++### 5.1 Calculate Derived State During Rendering++**Impact: MEDIUM (avoids redundant renders and state drift)**++If a value can be computed from current props/state, do not store it in state or update it in an effect. Derive it during render to avoid extra renders and state drift. Do not set state in effects solely in response to prop changes; prefer derived values or keyed resets instead.++**Incorrect: redundant state and effect**++```tsx+function Form() {+ const [firstName, setFirstName] = useState('First')+ const [lastName, setLastName] = useState('Last')+ const [fullName, setFullName] = useState('')++ useEffect(() => {+ setFullName(firstName + ' ' + lastName)+ }, [firstName, lastName])++ return <p>{fullName}</p>+}+```++**Correct: derive during render**++```tsx+function Form() {+ const [firstName, setFirstName] = useState('First')+ const [lastName, setLastName] = useState('Last')+ const fullName = firstName + ' ' + lastName++ return <p>{fullName}</p>+}+```++Reference: [https://react.dev/learn/you-might-not-need-an-effect](https://react.dev/learn/you-might-not-need-an-effect)++### 5.2 Defer State Reads to Usage Point++**Impact: MEDIUM (avoids unnecessary subscriptions)**++Don't subscribe to dynamic state (searchParams, localStorage) if you only read it inside callbacks.++**Incorrect: subscribes to all searchParams changes**++```tsx+function ShareButton({ chatId }: { chatId: string }) {+ const searchParams = useSearchParams()++ const handleShare = () => {+ const ref = searchParams.get('ref')+ shareChat(chatId, { ref })+ }++ return <button onClick={handleShare}>Share</button>+}+```++**Correct: reads on demand, no subscription**++```tsx+function ShareButton({ chatId }: { chatId: string }) {+ const handleShare = () => {+ const params = new URLSearchParams(window.location.search)+ const ref = params.get('ref')+ shareChat(chatId, { ref })+ }++ return <button onClick={handleShare}>Share</button>+}+```++### 5.3 Do not wrap a simple expression with a primitive result type in useMemo++**Impact: LOW-MEDIUM (wasted computation on every render)**++When an expression is simple (few logical or arithmetical operators) and has a primitive result type (boolean, number, string), do not wrap it in `useMemo`.++Calling `useMemo` and comparing hook dependencies may consume more resources than the expression itself.++**Incorrect:**++```tsx+function Header({ user, notifications }: Props) {+ const isLoading = useMemo(() => {+ return user.isLoading || notifications.isLoading+ }, [user.isLoading, notifications.isLoading])++ if (isLoading) return <Skeleton />+ // return some markup+}+```++**Correct:**++```tsx+function Header({ user, notifications }: Props) {+ const isLoading = user.isLoading || notifications.isLoading++ if (isLoading) return <Skeleton />+ // return some markup+}+```++### 5.4 Don't Define Components Inside Components++**Impact: HIGH (prevents remount on every render)**++Defining a component inside another component creates a new component type on every render. React sees a different component each time and fully remounts it, destroying all state and DOM.++A common reason developers do this is to access parent variables without passing props. Always pass props instead.++**Incorrect: remounts on every render**++```tsx+function UserProfile({ user, theme }) {+ // Defined inside to access `theme` - BAD+ const Avatar = () => (+ <img+ src={user.avatarUrl}+ className={theme === 'dark' ? 'avatar-dark' : 'avatar-light'}+ />+ )++ // Defined inside to access `user` - BAD+ const Stats = () => (+ <div>+ <span>{user.followers} followers</span>+ <span>{user.posts} posts</span>+ </div>+ )++ return (+ <div>+ <Avatar />+ <Stats />+ </div>+ )+}+```++Every time `UserProfile` renders, `Avatar` and `Stats` are new component types. React unmounts the old instances and mounts new ones, losing any internal state, running effects again, and recreating DOM nodes.++**Correct: pass props instead**++```tsx+function Avatar({ src, theme }: { src: string; theme: string }) {+ return (+ <img+ src={src}+ className={theme === 'dark' ? 'avatar-dark' : 'avatar-light'}+ />+ )+}++function Stats({ followers, posts }: { followers: number; posts: number }) {+ return (+ <div>+ <span>{followers} followers</span>+ <span>{posts} posts</span>+ </div>+ )+}++function UserProfile({ user, theme }) {+ return (+ <div>+ <Avatar src={user.avatarUrl} theme={theme} />+ <Stats followers={user.followers} posts={user.posts} />+ </div>+ )+}+```++**Symptoms of this bug:**++- Input fields lose focus on every keystroke++- Animations restart unexpectedly++- `useEffect` cleanup/setup runs on every parent render++- Scroll position resets inside the component++### 5.5 Extract Default Non-primitive Parameter Value from Memoized Component to Constant++**Impact: MEDIUM (restores memoization by using a constant for default value)**++When memoized component has a default value for some non-primitive optional parameter, such as an array, function, or object, calling the component without that parameter results in broken memoization. This is because new value instances are created on every rerender, and they do not pass strict equality comparison in `memo()`.++To address this issue, extract the default value into a constant.++**Incorrect: `onClick` has different values on every rerender**++```tsx+const UserAvatar = memo(function UserAvatar({ onClick = () => {} }: { onClick?: () => void }) {+ // ...+})++// Used without optional onClick+<UserAvatar />+```++**Correct: stable default value**++```tsx+const NOOP = () => {};++const UserAvatar = memo(function UserAvatar({ onClick = NOOP }: { onClick?: () => void }) {+ // ...+})++// Used without optional onClick+<UserAvatar />+```++### 5.6 Extract to Memoized Components++**Impact: MEDIUM (enables early returns)**++Extract expensive work into memoized components to enable early returns before computation.++**Incorrect: computes avatar even when loading**++```tsx+function Profile({ user, loading }: Props) {+ const avatar = useMemo(() => {+ const id = computeAvatarId(user)+ return <Avatar id={id} />+ }, [user])++ if (loading) return <Skeleton />+ return <div>{avatar}</div>+}+```++**Correct: skips computation when loading**++```tsx+const UserAvatar = memo(function UserAvatar({ user }: { user: User }) {+ const id = useMemo(() => computeAvatarId(user), [user])+ return <Avatar id={id} />+})++function Profile({ user, loading }: Props) {+ if (loading) return <Skeleton />+ return (+ <div>+ <UserAvatar user={user} />+ </div>+ )+}+```++**Note:** If your project has [React Compiler](https://react.dev/learn/react-compiler) enabled, manual memoization with `memo()` and `useMemo()` is not necessary. The compiler automatically optimizes re-renders.++### 5.7 Narrow Effect Dependencies++**Impact: LOW (minimizes effect re-runs)**++Specify primitive dependencies instead of objects to minimize effect re-runs.++**Incorrect: re-runs on any user field change**++```tsx+useEffect(() => {+ console.log(user.id)+}, [user])+```++**Correct: re-runs only when id changes**++```tsx+useEffect(() => {+ console.log(user.id)+}, [user.id])+```++**For derived state, compute outside effect:**++```tsx+// Incorrect: runs on width=767, 766, 765...+useEffect(() => {+ if (width < 768) {+ enableMobileMode()+ }+}, [width])++// Correct: runs only on boolean transition+const isMobile = width < 768+useEffect(() => {+ if (isMobile) {+ enableMobileMode()+ }+}, [isMobile])+```++### 5.8 Put Interaction Logic in Event Handlers++**Impact: MEDIUM (avoids effect re-runs and duplicate side effects)**++If a side effect is triggered by a specific user action (submit, click, drag), run it in that event handler. Do not model the action as state + effect; it makes effects re-run on unrelated changes and can duplicate the action.++**Incorrect: event modeled as state + effect**++```tsx+function Form() {+ const [submitted, setSubmitted] = useState(false)+ const theme = useContext(ThemeContext)++ useEffect(() => {+ if (submitted) {+ post('/api/register')+ showToast('Registered', theme)+ }+ }, [submitted, theme])++ return <button onClick={() => setSubmitted(true)}>Submit</button>+}+```++**Correct: do it in the handler**++```tsx+function Form() {+ const theme = useContext(ThemeContext)++ function handleSubmit() {+ post('/api/register')+ showToast('Registered', theme)+ }++ return <button onClick={handleSubmit}>Submit</button>+}+```++Reference: [https://react.dev/learn/removing-effect-dependencies#should-this-code-move-to-an-event-handler](https://react.dev/learn/removing-effect-dependencies#should-this-code-move-to-an-event-handler)++### 5.9 Split Combined Hook Computations++**Impact: MEDIUM (avoids recomputing independent steps)**++When a hook contains multiple independent tasks with different dependencies, split them into separate hooks. A combined hook reruns all tasks when any dependency changes, even if some tasks don't use the changed value.++**Incorrect: changing `sortOrder` recomputes filtering**++```tsx+const sortedProducts = useMemo(() => {+ const filtered = products.filter((p) => p.category === category)+ const sorted = filtered.toSorted((a, b) =>+ sortOrder === "asc" ? a.price - b.price : b.price - a.price+ )+ return sorted+}, [products, category, sortOrder])+```++**Correct: filtering only recomputes when products or category change**++```tsx+const filteredProducts = useMemo(+ () => products.filter((p) => p.category === category),+ [products, category]+)++const sortedProducts = useMemo(+ () =>+ filteredProducts.toSorted((a, b) =>+ sortOrder === "asc" ? a.price - b.price : b.price - a.price+ ),+ [filteredProducts, sortOrder]+)+```++This pattern also applies to `useEffect` when combining unrelated side effects:++**Incorrect: both effects run when either dependency changes**++```tsx+useEffect(() => {+ analytics.trackPageView(pathname)+ document.title = `${pageTitle} | My App`+}, [pathname, pageTitle])+```++**Correct: effects run independently**++```tsx+useEffect(() => {+ analytics.trackPageView(pathname)+}, [pathname])++useEffect(() => {+ document.title = `${pageTitle} | My App`+}, [pageTitle])+```++**Note:** If your project has [React Compiler](https://react.dev/learn/react-compiler) enabled, it automatically optimizes dependency tracking and may handle some of these cases for you.++### 5.10 Subscribe to Derived State++**Impact: MEDIUM (reduces re-render frequency)**++Subscribe to derived boolean state instead of continuous values to reduce re-render frequency.++**Incorrect: re-renders on every pixel change**++```tsx+function Sidebar() {+ const width = useWindowWidth() // updates continuously+ const isMobile = width < 768+ return <nav className={isMobile ? 'mobile' : 'desktop'} />+}+```++**Correct: re-renders only when boolean changes**++```tsx+function Sidebar() {+ const isMobile = useMediaQuery('(max-width: 767px)')+ return <nav className={isMobile ? 'mobile' : 'desktop'} />+}+```++### 5.11 Use Functional setState Updates++**Impact: MEDIUM (prevents stale closures and unnecessary callback recreations)**++When updating state based on the current state value, use the functional update form of setState instead of directly referencing the state variable. This prevents stale closures, eliminates unnecessary dependencies, and creates stable callback references.++**Incorrect: requires state as dependency**++```tsx+function TodoList() {+ const [items, setItems] = useState(initialItems)++ // Callback must depend on items, recreated on every items change+ const addItems = useCallback((newItems: Item[]) => {+ setItems([...items, ...newItems])+ }, [items]) // ❌ items dependency causes recreations++ // Risk of stale closure if dependency is forgotten+ const removeItem = useCallback((id: string) => {+ setItems(items.filter(item => item.id !== id))+ }, []) // ❌ Missing items dependency - will use stale items!++ return <ItemsEditor items={items} onAdd={addItems} onRemove={removeItem} />+}+```++The first callback is recreated every time `items` changes, which can cause child components to re-render unnecessarily. The second callback has a stale closure bug—it will always reference the initial `items` value.++**Correct: stable callbacks, no stale closures**++```tsx+function TodoList() {+ const [items, setItems] = useState(initialItems)++ // Stable callback, never recreated+ const addItems = useCallback((newItems: Item[]) => {+ setItems(curr => [...curr, ...newItems])+ }, []) // ✅ No dependencies needed++ // Always uses latest state, no stale closure risk+ const removeItem = useCallback((id: string) => {+ setItems(curr => curr.filter(item => item.id !== id))+ }, []) // ✅ Safe and stable++ return <ItemsEditor items={items} onAdd={addItems} onRemove={removeItem} />+}+```++**Benefits:**++1. **Stable callback references** - Callbacks don't need to be recreated when state changes++2. **No stale closures** - Always operates on the latest state value++3. **Fewer dependencies** - Simplifies dependency arrays and reduces memory leaks++4. **Prevents bugs** - Eliminates the most common source of React closure bugs++**When to use functional updates:**++- Any setState that depends on the current state value++- Inside useCallback/useMemo when state is needed++- Event handlers that reference state++- Async operations that update state++**When direct updates are fine:**++- Setting state to a static value: `setCount(0)`++- Setting state from props/arguments only: `setName(newName)`++- State doesn't depend on previous value++**Note:** If your project has [React Compiler](https://react.dev/learn/react-compiler) enabled, the compiler can automatically optimize some cases, but functional updates are still recommended for correctness and to prevent stale closure bugs.++### 5.12 Use Lazy State Initialization++**Impact: MEDIUM (wasted computation on every render)**++Pass a function to `useState` for expensive initial values. Without the function form, the initializer runs on every render even though the value is only used once.++**Incorrect: runs on every render**++```tsx+function FilteredList({ items }: { items: Item[] }) {+ // buildSearchIndex() runs on EVERY render, even after initialization+ const [searchIndex, setSearchIndex] = useState(buildSearchIndex(items))+ const [query, setQuery] = useState('')++ // When query changes, buildSearchIndex runs again unnecessarily+ return <SearchResults index={searchIndex} query={query} />+}++function UserProfile() {+ // JSON.parse runs on every render+ const [settings, setSettings] = useState(+ JSON.parse(localStorage.getItem('settings') || '{}')+ )++ return <SettingsForm settings={settings} onChange={setSettings} />+}+```++**Correct: runs only once**++```tsx+function FilteredList({ items }: { items: Item[] }) {+ // buildSearchIndex() runs ONLY on initial render+ const [searchIndex, setSearchIndex] = useState(() => buildSearchIndex(items))+ const [query, setQuery] = useState('')++ return <SearchResults index={searchIndex} query={query} />+}++function UserProfile() {+ // JSON.parse runs only on initial render+ const [settings, setSettings] = useState(() => {+ const stored = localStorage.getItem('settings')+ return stored ? JSON.parse(stored) : {}+ })++ return <SettingsForm settings={settings} onChange={setSettings} />+}+```++Use lazy initialization when computing initial values from localStorage/sessionStorage, building data structures (indexes, maps), reading from the DOM, or performing heavy transformations.++For simple primitives (`useState(0)`), direct references (`useState(props.value)`), or cheap literals (`useState({})`), the function form is unnecessary.++### 5.13 Use Transitions for Non-Urgent Updates++**Impact: MEDIUM (maintains UI responsiveness)**++Mark frequent, non-urgent state updates as transitions to maintain UI responsiveness.++**Incorrect: blocks UI on every scroll**++```tsx+function ScrollTracker() {+ const [scrollY, setScrollY] = useState(0)+ useEffect(() => {+ const handler = () => setScrollY(window.scrollY)+ window.addEventListener('scroll', handler, { passive: true })+ return () => window.removeEventListener('scroll', handler)+ }, [])+}+```++**Correct: non-blocking updates**++```tsx+import { startTransition } from 'react'++function ScrollTracker() {+ const [scrollY, setScrollY] = useState(0)+ useEffect(() => {+ const handler = () => {+ startTransition(() => setScrollY(window.scrollY))+ }+ window.addEventListener('scroll', handler, { passive: true })+ return () => window.removeEventListener('scroll', handler)+ }, [])+}+```++### 5.14 Use useDeferredValue for Expensive Derived Renders++**Impact: MEDIUM (keeps input responsive during heavy computation)**++When user input triggers expensive computations or renders, use `useDeferredValue` to keep the input responsive. The deferred value lags behind, allowing React to prioritize the input update and render the expensive result when idle.++**Incorrect: input feels laggy while filtering**++```tsx+function Search({ items }: { items: Item[] }) {+ const [query, setQuery] = useState('')+ const filtered = items.filter(item => fuzzyMatch(item, query))++ return (+ <>+ <input value={query} onChange={e => setQuery(e.target.value)} />+ <ResultsList results={filtered} />+ </>+ )+}+```++**Correct: input stays snappy, results render when ready**++```tsx+function Search({ items }: { items: Item[] }) {+ const [query, setQuery] = useState('')+ const deferredQuery = useDeferredValue(query)+ const filtered = useMemo(+ () => items.filter(item => fuzzyMatch(item, deferredQuery)),+ [items, deferredQuery]+ )+ const isStale = query !== deferredQuery++ return (+ <>+ <input value={query} onChange={e => setQuery(e.target.value)} />+ <div style={{ opacity: isStale ? 0.7 : 1 }}>+ <ResultsList results={filtered} />+ </div>+ </>+ )+}+```++**When to use:**++- Filtering/searching large lists++- Expensive visualizations (charts, graphs) reacting to input++- Any derived state that causes noticeable render delays++**Note:** Wrap the expensive computation in `useMemo` with the deferred value as a dependency, otherwise it still runs on every render.++Reference: [https://react.dev/reference/react/useDeferredValue](https://react.dev/reference/react/useDeferredValue)++### 5.15 Use useRef for Transient Values++**Impact: MEDIUM (avoids unnecessary re-renders on frequent updates)**++When a value changes frequently and you don't want a re-render on every update (e.g., mouse trackers, intervals, transient flags), store it in `useRef` instead of `useState`. Keep component state for UI; use refs for temporary DOM-adjacent values. Updating a ref does not trigger a re-render.++**Incorrect: renders every update**++```tsx+function Tracker() {+ const [lastX, setLastX] = useState(0)++ useEffect(() => {+ const onMove = (e: MouseEvent) => setLastX(e.clientX)+ window.addEventListener('mousemove', onMove)+ return () => window.removeEventListener('mousemove', onMove)+ }, [])++ return (+ <div+ style={{+ position: 'fixed',+ top: 0,+ left: lastX,+ width: 8,+ height: 8,+ background: 'black',+ }}+ />+ )+}+```++**Correct: no re-render for tracking**++```tsx+function Tracker() {+ const lastXRef = useRef(0)+ const dotRef = useRef<HTMLDivElement>(null)++ useEffect(() => {+ const onMove = (e: MouseEvent) => {+ lastXRef.current = e.clientX+ const node = dotRef.current+ if (node) {+ node.style.transform = `translateX(${e.clientX}px)`+ }+ }+ window.addEventListener('mousemove', onMove)+ return () => window.removeEventListener('mousemove', onMove)+ }, [])++ return (+ <div+ ref={dotRef}+ style={{+ position: 'fixed',+ top: 0,+ left: 0,+ width: 8,+ height: 8,+ background: 'black',+ transform: 'translateX(0px)',+ }}+ />+ )+}+```++---++## 6. Rendering Performance++**Impact: MEDIUM**++Optimizing the rendering process reduces the work the browser needs to do.++### 6.1 Animate SVG Wrapper Instead of SVG Element++**Impact: LOW (enables hardware acceleration)**++Many browsers don't have hardware acceleration for CSS3 animations on SVG elements. Wrap SVG in a `<div>` and animate the wrapper instead.++**Incorrect: animating SVG directly - no hardware acceleration**++```tsx+function LoadingSpinner() {+ return (+ <svg+ className="animate-spin"+ width="24"+ height="24"+ viewBox="0 0 24 24"+ >+ <circle cx="12" cy="12" r="10" stroke="currentColor" />+ </svg>+ )+}+```++**Correct: animating wrapper div - hardware accelerated**++```tsx+function LoadingSpinner() {+ return (+ <div className="animate-spin">+ <svg+ width="24"+ height="24"+ viewBox="0 0 24 24"+ >+ <circle cx="12" cy="12" r="10" stroke="currentColor" />+ </svg>+ </div>+ )+}+```++This applies to all CSS transforms and transitions (`transform`, `opacity`, `translate`, `scale`, `rotate`). The wrapper div allows browsers to use GPU acceleration for smoother animations.++### 6.2 CSS content-visibility for Long Lists++**Impact: HIGH (faster initial render)**++Apply `content-visibility: auto` to defer off-screen rendering.++**CSS:**++```css+.message-item {+ content-visibility: auto;+ contain-intrinsic-size: 0 80px;+}+```++**Example:**++```tsx+function MessageList({ messages }: { messages: Message[] }) {+ return (+ <div className="overflow-y-auto h-screen">+ {messages.map(msg => (+ <div key={msg.id} className="message-item">+ <Avatar user={msg.author} />+ <div>{msg.content}</div>+ </div>+ ))}+ </div>+ )+}+```++For 1000 messages, browser skips layout/paint for ~990 off-screen items (10× faster initial render).++### 6.3 Hoist Static JSX Elements++**Impact: LOW (avoids re-creation)**++Extract static JSX outside components to avoid re-creation.++**Incorrect: recreates element every render**++```tsx+function LoadingSkeleton() {+ return <div className="animate-pulse h-20 bg-gray-200" />+}++function Container() {+ return (+ <div>+ {loading && <LoadingSkeleton />}+ </div>+ )+}+```++**Correct: reuses same element**++```tsx+const loadingSkeleton = (+ <div className="animate-pulse h-20 bg-gray-200" />+)++function Container() {+ return (+ <div>+ {loading && loadingSkeleton}+ </div>+ )+}+```++This is especially helpful for large and static SVG nodes, which can be expensive to recreate on every render.++**Note:** If your project has [React Compiler](https://react.dev/learn/react-compiler) enabled, the compiler automatically hoists static JSX elements and optimizes component re-renders, making manual hoisting unnecessary.++### 6.4 Optimize SVG Precision++**Impact: LOW (reduces file size)**++Reduce SVG coordinate precision to decrease file size. The optimal precision depends on the viewBox size, but in general reducing precision should be considered.++**Incorrect: excessive precision**++```svg+<path d="M 10.293847 20.847362 L 30.938472 40.192837" />+```++**Correct: 1 decimal place**++```svg+<path d="M 10.3 20.8 L 30.9 40.2" />+```++**Automate with SVGO:**++```bash+npx svgo --precision=1 --multipass icon.svg+```++### 6.5 Prevent Hydration Mismatch Without Flickering++**Impact: MEDIUM (avoids visual flicker and hydration errors)**++When rendering content that depends on client-side storage (localStorage, cookies), avoid both SSR breakage and post-hydration flickering by injecting a synchronous script that updates the DOM before React hydrates.++**Incorrect: breaks SSR**++```tsx+function ThemeWrapper({ children }: { children: ReactNode }) {+ // localStorage is not available on server - throws error+ const theme = localStorage.getItem('theme') || 'light'++ return (+ <div className={theme}>+ {children}+ </div>+ )+}+```++Server-side rendering will fail because `localStorage` is undefined.++**Incorrect: visual flickering**++```tsx+function ThemeWrapper({ children }: { children: ReactNode }) {+ const [theme, setTheme] = useState('light')++ useEffect(() => {+ // Runs after hydration - causes visible flash+ const stored = localStorage.getItem('theme')+ if (stored) {+ setTheme(stored)+ }+ }, [])++ return (+ <div className={theme}>+ {children}+ </div>+ )+}+```++Component first renders with default value (`light`), then updates after hydration, causing a visible flash of incorrect content.++**Correct: no flicker, no hydration mismatch**++```tsx+function ThemeWrapper({ children }: { children: ReactNode }) {+ return (+ <>+ <div id="theme-wrapper">+ {children}+ </div>+ <script+ dangerouslySetInnerHTML={{+ __html: `+ (function() {+ try {+ var theme = localStorage.getItem('theme') || 'light';+ var el = document.getElementById('theme-wrapper');+ if (el) el.className = theme;+ } catch (e) {}+ })();+ `,+ }}+ />+ </>+ )+}+```++The inline script executes synchronously before showing the element, ensuring the DOM already has the correct value. No flickering, no hydration mismatch.++This pattern is especially useful for theme toggles, user preferences, authentication states, and any client-only data that should render immediately without flashing default values.++### 6.6 Suppress Expected Hydration Mismatches++**Impact: LOW-MEDIUM (avoids noisy hydration warnings for known differences)**++In SSR frameworks (e.g., Next.js), some values are intentionally different on server vs client (random IDs, dates, locale/timezone formatting). For these *expected* mismatches, wrap the dynamic text in an element with `suppressHydrationWarning` to prevent noisy warnings. Do not use this to hide real bugs. Don’t overuse it.++**Incorrect: known mismatch warnings**++```tsx+function Timestamp() {+ return <span>{new Date().toLocaleString()}</span>+}+```++**Correct: suppress expected mismatch only**++```tsx+function Timestamp() {+ return (+ <span suppressHydrationWarning>+ {new Date().toLocaleString()}+ </span>+ )+}+```++### 6.7 Use Activity Component for Show/Hide++**Impact: MEDIUM (preserves state/DOM)**++Use React's `<Activity>` to preserve state/DOM for expensive components that frequently toggle visibility.++**Usage:**++```tsx+import { Activity } from 'react'++function Dropdown({ isOpen }: Props) {+ return (+ <Activity mode={isOpen ? 'visible' : 'hidden'}>+ <ExpensiveMenu />+ </Activity>+ )+}+```++Avoids expensive re-renders and state loss.++### 6.8 Use defer or async on Script Tags++**Impact: HIGH (eliminates render-blocking)**++Script tags without `defer` or `async` block HTML parsing while the script downloads and executes. This delays First Contentful Paint and Time to Interactive.++- **`defer`**: Downloads in parallel, executes after HTML parsing completes, maintains execution order++- **`async`**: Downloads in parallel, executes immediately when ready, no guaranteed order++Use `defer` for scripts that depend on DOM or other scripts. Use `async` for independent scripts like analytics.++**Incorrect: blocks rendering**++```tsx+export default function Document() {+ return (+ <html>+ <head>+ <script src="https://example.com/analytics.js" />+ <script src="/scripts/utils.js" />+ </head>+ <body>{/* content */}</body>+ </html>+ )+}+```++**Correct: non-blocking**++```tsx+import Script from 'next/script'++export default function Page() {+ return (+ <>+ <Script src="https://example.com/analytics.js" strategy="afterInteractive" />+ <Script src="/scripts/utils.js" strategy="beforeInteractive" />+ </>+ )+}+```++**Note:** In Next.js, prefer the `next/script` component with `strategy` prop instead of raw script tags:++Reference: [https://developer.mozilla.org/en-US/docs/Web/HTML/Element/script#defer](https://developer.mozilla.org/en-US/docs/Web/HTML/Element/script#defer)++### 6.9 Use Explicit Conditional Rendering++**Impact: LOW (prevents rendering 0 or NaN)**++Use explicit ternary operators (`? :`) instead of `&&` for conditional rendering when the condition can be `0`, `NaN`, or other falsy values that render.++**Incorrect: renders "0" when count is 0**++```tsx+function Badge({ count }: { count: number }) {+ return (+ <div>+ {count && <span className="badge">{count}</span>}+ </div>+ )+}++// When count = 0, renders: <div>0</div>+// When count = 5, renders: <div><span class="badge">5</span></div>+```++**Correct: renders nothing when count is 0**++```tsx+function Badge({ count }: { count: number }) {+ return (+ <div>+ {count > 0 ? <span className="badge">{count}</span> : null}+ </div>+ )+}++// When count = 0, renders: <div></div>+// When count = 5, renders: <div><span class="badge">5</span></div>+```++### 6.10 Use React DOM Resource Hints++**Impact: HIGH (reduces load time for critical resources)**++React DOM provides APIs to hint the browser about resources it will need. These are especially useful in server components to start loading resources before the client even receives the HTML.++- **`prefetchDNS(href)`**: Resolve DNS for a domain you expect to connect to++- **`preconnect(href)`**: Establish connection (DNS + TCP + TLS) to a server++- **`preload(href, options)`**: Fetch a resource (stylesheet, font, script, image) you'll use soon++- **`preloadModule(href)`**: Fetch an ES module you'll use soon++- **`preinit(href, options)`**: Fetch and evaluate a stylesheet or script++- **`preinitModule(href)`**: Fetch and evaluate an ES module++**Example: preconnect to third-party APIs**++```tsx+import { preconnect, prefetchDNS } from 'react-dom'++export default function App() {+ prefetchDNS('https://analytics.example.com')+ preconnect('https://api.example.com')++ return <main>{/* content */}</main>+}+```++**Example: preload critical fonts and styles**++```tsx+import { preload, preinit } from 'react-dom'++export default function RootLayout({ children }) {+ // Preload font file+ preload('/fonts/inter.woff2', { as: 'font', type: 'font/woff2', crossOrigin: 'anonymous' })++ // Fetch and apply critical stylesheet immediately+ preinit('/styles/critical.css', { as: 'style' })++ return (+ <html>+ <body>{children}</body>+ </html>+ )+}+```++**Example: preload modules for code-split routes**++```tsx+import { preloadModule, preinitModule } from 'react-dom'++function Navigation() {+ const preloadDashboard = () => {+ preloadModule('/dashboard.js', { as: 'script' })+ }++ return (+ <nav>+ <a href="/dashboard" onMouseEnter={preloadDashboard}>+ Dashboard+ </a>+ </nav>+ )+}+```++**When to use each:**++| API | Use case |++|-----|----------|++| `prefetchDNS` | Third-party domains you'll connect to later |++| `preconnect` | APIs or CDNs you'll fetch from immediately |++| `preload` | Critical resources needed for current page |++| `preloadModule` | JS modules for likely next navigation |++| `preinit` | Stylesheets/scripts that must execute early |++| `preinitModule` | ES modules that must execute early |++Reference: [https://react.dev/reference/react-dom#resource-preloading-apis](https://react.dev/reference/react-dom#resource-preloading-apis)++### 6.11 Use useTransition Over Manual Loading States++**Impact: LOW (reduces re-renders and improves code clarity)**++Use `useTransition` instead of manual `useState` for loading states. This provides built-in `isPending` state and automatically manages transitions.++**Incorrect: manual loading state**++```tsx+function SearchResults() {+ const [query, setQuery] = useState('')+ const [results, setResults] = useState([])+ const [isLoading, setIsLoading] = useState(false)++ const handleSearch = async (value: string) => {+ setIsLoading(true)+ setQuery(value)+ const data = await fetchResults(value)+ setResults(data)+ setIsLoading(false)+ }++ return (+ <>+ <input onChange={(e) => handleSearch(e.target.value)} />+ {isLoading && <Spinner />}+ <ResultsList results={results} />+ </>+ )+}+```++**Correct: useTransition with built-in pending state**++```tsx+import { useTransition, useState } from 'react'++function SearchResults() {+ const [query, setQuery] = useState('')+ const [results, setResults] = useState([])+ const [isPending, startTransition] = useTransition()++ const handleSearch = (value: string) => {+ setQuery(value) // Update input immediately++ startTransition(async () => {+ // Fetch and update results+ const data = await fetchResults(value)+ setResults(data)+ })+ }++ return (+ <>+ <input onChange={(e) => handleSearch(e.target.value)} />+ {isPending && <Spinner />}+ <ResultsList results={results} />+ </>+ )+}+```++**Benefits:**++- **Automatic pending state**: No need to manually manage `setIsLoading(true/false)`++- **Error resilience**: Pending state correctly resets even if the transition throws++- **Better responsiveness**: Keeps the UI responsive during updates++- **Interrupt handling**: New transitions automatically cancel pending ones++Reference: [https://react.dev/reference/react/useTransition](https://react.dev/reference/react/useTransition)++---++## 7. JavaScript Performance++**Impact: LOW-MEDIUM**++Micro-optimizations for hot paths can add up to meaningful improvements.++### 7.1 Avoid Layout Thrashing++**Impact: MEDIUM (prevents forced synchronous layouts and reduces performance bottlenecks)**++Avoid interleaving style writes with layout reads. When you read a layout property (like `offsetWidth`, `getBoundingClientRect()`, or `getComputedStyle()`) between style changes, the browser is forced to trigger a synchronous reflow.++**This is OK: browser batches style changes**++```typescript+function updateElementStyles(element: HTMLElement) {+ // Each line invalidates style, but browser batches the recalculation+ element.style.width = '100px'+ element.style.height = '200px'+ element.style.backgroundColor = 'blue'+ element.style.border = '1px solid black'+}+```++**Incorrect: interleaved reads and writes force reflows**++```typescript+function layoutThrashing(element: HTMLElement) {+ element.style.width = '100px'+ const width = element.offsetWidth // Forces reflow+ element.style.height = '200px'+ const height = element.offsetHeight // Forces another reflow+}+```++**Correct: batch writes, then read once**++```typescript+function updateElementStyles(element: HTMLElement) {+ // Batch all writes together+ element.style.width = '100px'+ element.style.height = '200px'+ element.style.backgroundColor = 'blue'+ element.style.border = '1px solid black'++ // Read after all writes are done (single reflow)+ const { width, height } = element.getBoundingClientRect()+}+```++**Correct: batch reads, then writes**++```typescript+function updateElementStyles(element: HTMLElement) {+ element.classList.add('highlighted-box')++ const { width, height } = element.getBoundingClientRect()+}+```++**Better: use CSS classes**++**React example:**++```tsx+// Incorrect: interleaving style changes with layout queries+function Box({ isHighlighted }: { isHighlighted: boolean }) {+ const ref = useRef<HTMLDivElement>(null)++ useEffect(() => {+ if (ref.current && isHighlighted) {+ ref.current.style.width = '100px'+ const width = ref.current.offsetWidth // Forces layout+ ref.current.style.height = '200px'+ }+ }, [isHighlighted])++ return <div ref={ref}>Content</div>+}++// Correct: toggle class+function Box({ isHighlighted }: { isHighlighted: boolean }) {+ return (+ <div className={isHighlighted ? 'highlighted-box' : ''}>+ Content+ </div>+ )+}+```++Prefer CSS classes over inline styles when possible. CSS files are cached by the browser, and classes provide better separation of concerns and are easier to maintain.++See [this gist](https://gist.github.com/paulirish/5d52fb081b3570c81e3a) and [CSS Triggers](https://csstriggers.com/) for more information on layout-forcing operations.++### 7.2 Build Index Maps for Repeated Lookups++**Impact: LOW-MEDIUM (1M ops to 2K ops)**++Multiple `.find()` calls by the same key should use a Map.++**Incorrect (O(n) per lookup):**++```typescript+function processOrders(orders: Order[], users: User[]) {+ return orders.map(order => ({+ ...order,+ user: users.find(u => u.id === order.userId)+ }))+}+```++**Correct (O(1) per lookup):**++```typescript+function processOrders(orders: Order[], users: User[]) {+ const userById = new Map(users.map(u => [u.id, u]))++ return orders.map(order => ({+ ...order,+ user: userById.get(order.userId)+ }))+}+```++Build map once (O(n)), then all lookups are O(1).++For 1000 orders × 1000 users: 1M ops → 2K ops.++### 7.3 Cache Property Access in Loops++**Impact: LOW-MEDIUM (reduces lookups)**++Cache object property lookups in hot paths.++**Incorrect: 3 lookups × N iterations**++```typescript+for (let i = 0; i < arr.length; i++) {+ process(obj.config.settings.value)+}+```++**Correct: 1 lookup total**++```typescript+const value = obj.config.settings.value+const len = arr.length+for (let i = 0; i < len; i++) {+ process(value)+}+```++### 7.4 Cache Repeated Function Calls++**Impact: MEDIUM (avoid redundant computation)**++Use a module-level Map to cache function results when the same function is called repeatedly with the same inputs during render.++**Incorrect: redundant computation**++```typescript+function ProjectList({ projects }: { projects: Project[] }) {+ return (+ <div>+ {projects.map(project => {+ // slugify() called 100+ times for same project names+ const slug = slugify(project.name)++ return <ProjectCard key={project.id} slug={slug} />+ })}+ </div>+ )+}+```++**Correct: cached results**++```typescript+// Module-level cache+const slugifyCache = new Map<string, string>()++function cachedSlugify(text: string): string {+ if (slugifyCache.has(text)) {+ return slugifyCache.get(text)!+ }+ const result = slugify(text)+ slugifyCache.set(text, result)+ return result+}++function ProjectList({ projects }: { projects: Project[] }) {+ return (+ <div>+ {projects.map(project => {+ // Computed only once per unique project name+ const slug = cachedSlugify(project.name)++ return <ProjectCard key={project.id} slug={slug} />+ })}+ </div>+ )+}+```++**Simpler pattern for single-value functions:**++```typescript+let isLoggedInCache: boolean | null = null++function isLoggedIn(): boolean {+ if (isLoggedInCache !== null) {+ return isLoggedInCache+ }++ isLoggedInCache = document.cookie.includes('auth=')+ return isLoggedInCache+}++// Clear cache when auth changes+function onAuthChange() {+ isLoggedInCache = null+}+```++Use a Map (not a hook) so it works everywhere: utilities, event handlers, not just React components.++Reference: [https://vercel.com/blog/how-we-made-the-vercel-dashboard-twice-as-fast](https://vercel.com/blog/how-we-made-the-vercel-dashboard-twice-as-fast)++### 7.5 Cache Storage API Calls++**Impact: LOW-MEDIUM (reduces expensive I/O)**++`localStorage`, `sessionStorage`, and `document.cookie` are synchronous and expensive. Cache reads in memory.++**Incorrect: reads storage on every call**++```typescript+function getTheme() {+ return localStorage.getItem('theme') ?? 'light'+}+// Called 10 times = 10 storage reads+```++**Correct: Map cache**++```typescript+const storageCache = new Map<string, string | null>()++function getLocalStorage(key: string) {+ if (!storageCache.has(key)) {+ storageCache.set(key, localStorage.getItem(key))+ }+ return storageCache.get(key)+}++function setLocalStorage(key: string, value: string) {+ localStorage.setItem(key, value)+ storageCache.set(key, value) // keep cache in sync+}+```++Use a Map (not a hook) so it works everywhere: utilities, event handlers, not just React components.++**Cookie caching:**++```typescript+let cookieCache: Record<string, string> | null = null++function getCookie(name: string) {+ if (!cookieCache) {+ cookieCache = Object.fromEntries(+ document.cookie.split('; ').map(c => c.split('='))+ )+ }+ return cookieCache[name]+}+```++**Important: invalidate on external changes**++```typescript+window.addEventListener('storage', (e) => {+ if (e.key) storageCache.delete(e.key)+})++document.addEventListener('visibilitychange', () => {+ if (document.visibilityState === 'visible') {+ storageCache.clear()+ }+})+```++If storage can change externally (another tab, server-set cookies), invalidate cache:++### 7.6 Combine Multiple Array Iterations++**Impact: LOW-MEDIUM (reduces iterations)**++Multiple `.filter()` or `.map()` calls iterate the array multiple times. Combine into one loop.++**Incorrect: 3 iterations**++```typescript+const admins = users.filter(u => u.isAdmin)+const testers = users.filter(u => u.isTester)+const inactive = users.filter(u => !u.isActive)+```++**Correct: 1 iteration**++```typescript+const admins: User[] = []+const testers: User[] = []+const inactive: User[] = []++for (const user of users) {+ if (user.isAdmin) admins.push(user)+ if (user.isTester) testers.push(user)+ if (!user.isActive) inactive.push(user)+}+```++### 7.7 Defer Non-Critical Work with requestIdleCallback++**Impact: MEDIUM (keeps UI responsive during background tasks)**++Use `requestIdleCallback()` to schedule non-critical work during browser idle periods. This keeps the main thread free for user interactions and animations, reducing jank and improving perceived performance.++**Incorrect: blocks main thread during user interaction**++```typescript+function handleSearch(query: string) {+ const results = searchItems(query)+ setResults(results)++ // These block the main thread immediately+ analytics.track('search', { query })+ saveToRecentSearches(query)+ prefetchTopResults(results.slice(0, 3))+}+```++**Correct: defers non-critical work to idle time**++```typescript+function handleSearch(query: string) {+ const results = searchItems(query)+ setResults(results)++ // Defer non-critical work to idle periods+ requestIdleCallback(() => {+ analytics.track('search', { query })+ })++ requestIdleCallback(() => {+ saveToRecentSearches(query)+ })++ requestIdleCallback(() => {+ prefetchTopResults(results.slice(0, 3))+ })+}+```++**With timeout for required work:**++```typescript+// Ensure analytics fires within 2 seconds even if browser stays busy+requestIdleCallback(+ () => analytics.track('page_view', { path: location.pathname }),+ { timeout: 2000 }+)+```++**Chunking large tasks:**++```typescript+function processLargeDataset(items: Item[]) {+ let index = 0++ function processChunk(deadline: IdleDeadline) {+ // Process items while we have idle time (aim for <50ms chunks)+ while (index < items.length && deadline.timeRemaining() > 0) {+ processItem(items[index])+ index+++ }++ // Schedule next chunk if more items remain+ if (index < items.length) {+ requestIdleCallback(processChunk)+ }+ }++ requestIdleCallback(processChunk)+}+```++**With fallback for unsupported browsers:**++```typescript+const scheduleIdleWork = window.requestIdleCallback ?? ((cb: () => void) => setTimeout(cb, 1))++scheduleIdleWork(() => {+ // Non-critical work+})+```++**When to use:**++- Analytics and telemetry++- Saving state to localStorage/IndexedDB++- Prefetching resources for likely next actions++- Processing non-urgent data transformations++- Lazy initialization of non-critical features++**When NOT to use:**++- User-initiated actions that need immediate feedback++- Rendering updates the user is waiting for++- Time-sensitive operations++### 7.8 Early Length Check for Array Comparisons++**Impact: MEDIUM-HIGH (avoids expensive operations when lengths differ)**++When comparing arrays with expensive operations (sorting, deep equality, serialization), check lengths first. If lengths differ, the arrays cannot be equal.++In real-world applications, this optimization is especially valuable when the comparison runs in hot paths (event handlers, render loops).++**Incorrect: always runs expensive comparison**++```typescript+function hasChanges(current: string[], original: string[]) {+ // Always sorts and joins, even when lengths differ+ return current.sort().join() !== original.sort().join()+}+```++Two O(n log n) sorts run even when `current.length` is 5 and `original.length` is 100. There is also overhead of joining the arrays and comparing the strings.++**Correct (O(1) length check first):**++```typescript+function hasChanges(current: string[], original: string[]) {+ // Early return if lengths differ+ if (current.length !== original.length) {+ return true+ }+ // Only sort when lengths match+ const currentSorted = current.toSorted()+ const originalSorted = original.toSorted()+ for (let i = 0; i < currentSorted.length; i++) {+ if (currentSorted[i] !== originalSorted[i]) {+ return true+ }+ }+ return false+}+```++This new approach is more efficient because:++- It avoids the overhead of sorting and joining the arrays when lengths differ++- It avoids consuming memory for the joined strings (especially important for large arrays)++- It avoids mutating the original arrays++- It returns early when a difference is found++### 7.9 Early Return from Functions++**Impact: LOW-MEDIUM (avoids unnecessary computation)**++Return early when result is determined to skip unnecessary processing.++**Incorrect: processes all items even after finding answer**++```typescript+function validateUsers(users: User[]) {+ let hasError = false+ let errorMessage = ''++ for (const user of users) {+ if (!user.email) {+ hasError = true+ errorMessage = 'Email required'+ }+ if (!user.name) {+ hasError = true+ errorMessage = 'Name required'+ }+ // Continues checking all users even after error found+ }++ return hasError ? { valid: false, error: errorMessage } : { valid: true }+}+```++**Correct: returns immediately on first error**++```typescript+function validateUsers(users: User[]) {+ for (const user of users) {+ if (!user.email) {+ return { valid: false, error: 'Email required' }+ }+ if (!user.name) {+ return { valid: false, error: 'Name required' }+ }+ }++ return { valid: true }+}+```++### 7.10 Hoist RegExp Creation++**Impact: LOW-MEDIUM (avoids recreation)**++Don't create RegExp inside render. Hoist to module scope or memoize with `useMemo()`.++**Incorrect: new RegExp every render**++```tsx+function Highlighter({ text, query }: Props) {+ const regex = new RegExp(`(${query})`, 'gi')+ const parts = text.split(regex)+ return <>{parts.map((part, i) => ...)}</>+}+```++**Correct: memoize or hoist**++```tsx+const EMAIL_REGEX = /^[^\s@]+@[^\s@]+\.[^\s@]+$/++function Highlighter({ text, query }: Props) {+ const regex = useMemo(+ () => new RegExp(`(${escapeRegex(query)})`, 'gi'),+ [query]+ )+ const parts = text.split(regex)+ return <>{parts.map((part, i) => ...)}</>+}+```++**Warning: global regex has mutable state**++```typescript+const regex = /foo/g+regex.test('foo') // true, lastIndex = 3+regex.test('foo') // false, lastIndex = 0+```++Global regex (`/g`) has mutable `lastIndex` state:++### 7.11 Use flatMap to Map and Filter in One Pass++**Impact: LOW-MEDIUM (eliminates intermediate array)**++Chaining `.map().filter(Boolean)` creates an intermediate array and iterates twice. Use `.flatMap()` to transform and filter in a single pass.++**Incorrect: 2 iterations, intermediate array**++```typescript+const userNames = users+ .map(user => user.isActive ? user.name : null)+ .filter(Boolean)+```++**Correct: 1 iteration, no intermediate array**++```typescript+const userNames = users.flatMap(user =>+ user.isActive ? [user.name] : []+)+```++**More examples:**++```typescript+// Extract valid emails from responses+// Before+const emails = responses+ .map(r => r.success ? r.data.email : null)+ .filter(Boolean)++// After+const emails = responses.flatMap(r =>+ r.success ? [r.data.email] : []+)++// Parse and filter valid numbers+// Before+const numbers = strings+ .map(s => parseInt(s, 10))+ .filter(n => !isNaN(n))++// After+const numbers = strings.flatMap(s => {+ const n = parseInt(s, 10)+ return isNaN(n) ? [] : [n]+})+```++**When to use:**++- Transforming items while filtering some out++- Conditional mapping where some inputs produce no output++- Parsing/validating where invalid inputs should be skipped++### 7.12 Use Loop for Min/Max Instead of Sort++**Impact: LOW (O(n) instead of O(n log n))**++Finding the smallest or largest element only requires a single pass through the array. Sorting is wasteful and slower.++**Incorrect (O(n log n) - sort to find latest):**++```typescript+interface Project {+ id: string+ name: string+ updatedAt: number+}++function getLatestProject(projects: Project[]) {+ const sorted = [...projects].sort((a, b) => b.updatedAt - a.updatedAt)+ return sorted[0]+}+```++Sorts the entire array just to find the maximum value.++**Incorrect (O(n log n) - sort for oldest and newest):**++```typescript+function getOldestAndNewest(projects: Project[]) {+ const sorted = [...projects].sort((a, b) => a.updatedAt - b.updatedAt)+ return { oldest: sorted[0], newest: sorted[sorted.length - 1] }+}+```++Still sorts unnecessarily when only min/max are needed.++**Correct (O(n) - single loop):**++```typescript+function getLatestProject(projects: Project[]) {+ if (projects.length === 0) return null++ let latest = projects[0]++ for (let i = 1; i < projects.length; i++) {+ if (projects[i].updatedAt > latest.updatedAt) {+ latest = projects[i]+ }+ }++ return latest+}++function getOldestAndNewest(projects: Project[]) {+ if (projects.length === 0) return { oldest: null, newest: null }++ let oldest = projects[0]+ let newest = projects[0]++ for (let i = 1; i < projects.length; i++) {+ if (projects[i].updatedAt < oldest.updatedAt) oldest = projects[i]+ if (projects[i].updatedAt > newest.updatedAt) newest = projects[i]+ }++ return { oldest, newest }+}+```++Single pass through the array, no copying, no sorting.++**Alternative: Math.min/Math.max for small arrays**++```typescript+const numbers = [5, 2, 8, 1, 9]+const min = Math.min(...numbers)+const max = Math.max(...numbers)+```++This works for small arrays, but can be slower or just throw an error for very large arrays due to spread operator limitations. Maximal array length is approximately 124000 in Chrome 143 and 638000 in Safari 18; exact numbers may vary - see [the fiddle](https://jsfiddle.net/qw1jabsx/4/). Use the loop approach for reliability.++### 7.13 Use Set/Map for O(1) Lookups++**Impact: LOW-MEDIUM (O(n) to O(1))**++Convert arrays to Set/Map for repeated membership checks.++**Incorrect (O(n) per check):**++```typescript+const allowedIds = ['a', 'b', 'c', ...]+items.filter(item => allowedIds.includes(item.id))+```++**Correct (O(1) per check):**++```typescript+const allowedIds = new Set(['a', 'b', 'c', ...])+items.filter(item => allowedIds.has(item.id))+```++### 7.14 Use toSorted() Instead of sort() for Immutability++**Impact: MEDIUM-HIGH (prevents mutation bugs in React state)**++`.sort()` mutates the array in place, which can cause bugs with React state and props. Use `.toSorted()` to create a new sorted array without mutation.++**Incorrect: mutates original array**++```typescript+function UserList({ users }: { users: User[] }) {+ // Mutates the users prop array!+ const sorted = useMemo(+ () => users.sort((a, b) => a.name.localeCompare(b.name)),+ [users]+ )+ return <div>{sorted.map(renderUser)}</div>+}+```++**Correct: creates new array**++```typescript+function UserList({ users }: { users: User[] }) {+ // Creates new sorted array, original unchanged+ const sorted = useMemo(+ () => users.toSorted((a, b) => a.name.localeCompare(b.name)),+ [users]+ )+ return <div>{sorted.map(renderUser)}</div>+}+```++**Why this matters in React:**++1. Props/state mutations break React's immutability model - React expects props and state to be treated as read-only++2. Causes stale closure bugs - Mutating arrays inside closures (callbacks, effects) can lead to unexpected behavior++**Browser support: fallback for older browsers**++```typescript+// Fallback for older browsers+const sorted = [...items].sort((a, b) => a.value - b.value)+```++`.toSorted()` is available in all modern browsers (Chrome 110+, Safari 16+, Firefox 115+, Node.js 20+). For older environments, use spread operator:++**Other immutable array methods:**++- `.toSorted()` - immutable sort++- `.toReversed()` - immutable reverse++- `.toSpliced()` - immutable splice++- `.with()` - immutable element replacement++---++## 8. Advanced Patterns++**Impact: LOW**++Advanced patterns for specific cases that require careful implementation.++### 8.1 Do Not Put Effect Events in Dependency Arrays++**Impact: LOW (avoids unnecessary effect re-runs and lint errors)**++Effect Event functions do not have a stable identity. Their identity intentionally changes on every render. Do not include the function returned by `useEffectEvent` in a `useEffect` dependency array. Keep the actual reactive values as dependencies and call the Effect Event from inside the effect body or subscriptions created by that effect.++**Incorrect: Effect Event added as a dependency**++```tsx+import { useEffect, useEffectEvent } from 'react'++function ChatRoom({ roomId, onConnected }: {+ roomId: string+ onConnected: () => void+}) {+ const handleConnected = useEffectEvent(onConnected)++ useEffect(() => {+ const connection = createConnection(roomId)+ connection.on('connected', handleConnected)+ connection.connect()++ return () => connection.disconnect()+ }, [roomId, handleConnected])+}+```++Including the Effect Event in dependencies makes the effect re-run every render and triggers the React Hooks lint rule.++**Correct: depend on reactive values, not the Effect Event**++```tsx+import { useEffect, useEffectEvent } from 'react'++function ChatRoom({ roomId, onConnected }: {+ roomId: string+ onConnected: () => void+}) {+ const handleConnected = useEffectEvent(onConnected)++ useEffect(() => {+ const connection = createConnection(roomId)+ connection.on('connected', handleConnected)+ connection.connect()++ return () => connection.disconnect()+ }, [roomId])+}+```++Reference: [https://react.dev/reference/react/useEffectEvent#effect-event-in-deps](https://react.dev/reference/react/useEffectEvent#effect-event-in-deps)++### 8.2 Initialize App Once, Not Per Mount++**Impact: LOW-MEDIUM (avoids duplicate init in development)**++Do not put app-wide initialization that must run once per app load inside `useEffect([])` of a component. Components can remount and effects will re-run. Use a module-level guard or top-level init in the entry module instead.++**Incorrect: runs twice in dev, re-runs on remount**++```tsx+function Comp() {+ useEffect(() => {+ loadFromStorage()+ checkAuthToken()+ }, [])++ // ...+}+```++**Correct: once per app load**++```tsx+let didInit = false++function Comp() {+ useEffect(() => {+ if (didInit) return+ didInit = true+ loadFromStorage()+ checkAuthToken()+ }, [])++ // ...+}+```++Reference: [https://react.dev/learn/you-might-not-need-an-effect#initializing-the-application](https://react.dev/learn/you-might-not-need-an-effect#initializing-the-application)++### 8.3 Store Event Handlers in Refs++**Impact: LOW (stable subscriptions)**++Store callbacks in refs when used in effects that shouldn't re-subscribe on callback changes.++**Incorrect: re-subscribes on every render**++```tsx+function useWindowEvent(event: string, handler: (e) => void) {+ useEffect(() => {+ window.addEventListener(event, handler)+ return () => window.removeEventListener(event, handler)+ }, [event, handler])+}+```++**Correct: stable subscription**++```tsx+import { useEffectEvent } from 'react'++function useWindowEvent(event: string, handler: (e) => void) {+ const onEvent = useEffectEvent(handler)++ useEffect(() => {+ window.addEventListener(event, onEvent)+ return () => window.removeEventListener(event, onEvent)+ }, [event])+}+```++**Alternative: use `useEffectEvent` if you're on latest React:**++`useEffectEvent` provides a cleaner API for the same pattern: it creates a stable function reference that always calls the latest version of the handler.++### 8.4 useEffectEvent for Stable Callback Refs++**Impact: LOW (prevents effect re-runs)**++Access latest values in callbacks without adding them to dependency arrays. Prevents effect re-runs while avoiding stale closures.++**Incorrect: effect re-runs on every callback change**++```tsx+function SearchInput({ onSearch }: { onSearch: (q: string) => void }) {+ const [query, setQuery] = useState('')++ useEffect(() => {+ const timeout = setTimeout(() => onSearch(query), 300)+ return () => clearTimeout(timeout)+ }, [query, onSearch])+}+```++**Correct: using React's useEffectEvent**++```tsx+import { useEffectEvent } from 'react';++function SearchInput({ onSearch }: { onSearch: (q: string) => void }) {+ const [query, setQuery] = useState('')+ const onSearchEvent = useEffectEvent(onSearch)++ useEffect(() => {+ const timeout = setTimeout(() => onSearchEvent(query), 300)+ return () => clearTimeout(timeout)+ }, [query])+}+```++---++## References++1. [https://react.dev](https://react.dev)+2. [https://nextjs.org](https://nextjs.org)+3. [https://swr.vercel.app](https://swr.vercel.app)+4. [https://github.com/shuding/better-all](https://github.com/shuding/better-all)+5. [https://github.com/isaacs/node-lru-cache](https://github.com/isaacs/node-lru-cache)+6. [https://vercel.com/blog/how-we-optimized-package-imports-in-next-js](https://vercel.com/blog/how-we-optimized-package-imports-in-next-js)+7. [https://vercel.com/blog/how-we-made-the-vercel-dashboard-twice-as-fast](https://vercel.com/blog/how-we-made-the-vercel-dashboard-twice-as-fast)diff --git a/.agents/skills/vercel-react-best-practices/README.md b/.agents/skills/vercel-react-best-practices/README.mdnew file mode 100644index 0000000..f283e1c--- /dev/null+++ b/.agents/skills/vercel-react-best-practices/README.md@@ -0,0 +1,123 @@+# React Best Practices++A structured repository for creating and maintaining React Best Practices optimized for agents and LLMs.++## Structure++- `rules/` - Individual rule files (one per rule)+ - `_sections.md` - Section metadata (titles, impacts, descriptions)+ - `_template.md` - Template for creating new rules+ - `area-description.md` - Individual rule files+- `src/` - Build scripts and utilities+- `metadata.json` - Document metadata (version, organization, abstract)+- __`AGENTS.md`__ - Compiled output (generated)+- __`test-cases.json`__ - Test cases for LLM evaluation (generated)++## Getting Started++1. Install dependencies:+ ```bash+ pnpm install+ ```++2. Build AGENTS.md from rules:+ ```bash+ pnpm build+ ```++3. Validate rule files:+ ```bash+ pnpm validate+ ```++4. Extract test cases:+ ```bash+ pnpm extract-tests+ ```++## Creating a New Rule++1. Copy `rules/_template.md` to `rules/area-description.md`+2. Choose the appropriate area prefix:+ - `async-` for Eliminating Waterfalls (Section 1)+ - `bundle-` for Bundle Size Optimization (Section 2)+ - `server-` for Server-Side Performance (Section 3)+ - `client-` for Client-Side Data Fetching (Section 4)+ - `rerender-` for Re-render Optimization (Section 5)+ - `rendering-` for Rendering Performance (Section 6)+ - `js-` for JavaScript Performance (Section 7)+ - `advanced-` for Advanced Patterns (Section 8)+3. Fill in the frontmatter and content+4. Ensure you have clear examples with explanations+5. Run `pnpm build` to regenerate AGENTS.md and test-cases.json++## Rule File Structure++Each rule file should follow this structure:++```markdown+---+title: Rule Title Here+impact: MEDIUM+impactDescription: Optional description+tags: tag1, tag2, tag3+---++## Rule Title Here++Brief explanation of the rule and why it matters.++**Incorrect (description of what's wrong):**++```typescript+// Bad code example+```++**Correct (description of what's right):**++```typescript+// Good code example+```++Optional explanatory text after examples.++Reference: [Link](https://example.com)++## File Naming Convention++- Files starting with `_` are special (excluded from build)+- Rule files: `area-description.md` (e.g., `async-parallel.md`)+- Section is automatically inferred from filename prefix+- Rules are sorted alphabetically by title within each section+- IDs (e.g., 1.1, 1.2) are auto-generated during build++## Impact Levels++- `CRITICAL` - Highest priority, major performance gains+- `HIGH` - Significant performance improvements+- `MEDIUM-HIGH` - Moderate-high gains+- `MEDIUM` - Moderate performance improvements+- `LOW-MEDIUM` - Low-medium gains+- `LOW` - Incremental improvements++## Scripts++- `pnpm build` - Compile rules into AGENTS.md+- `pnpm validate` - Validate all rule files+- `pnpm extract-tests` - Extract test cases for LLM evaluation+- `pnpm dev` - Build and validate++## Contributing++When adding or modifying rules:++1. Use the correct filename prefix for your section+2. Follow the `_template.md` structure+3. Include clear bad/good examples with explanations+4. Add appropriate tags+5. Run `pnpm build` to regenerate AGENTS.md and test-cases.json+6. Rules are automatically sorted by title - no need to manage numbers!++## Acknowledgments++Originally created by [@shuding](https://x.com/shuding) at [Vercel](https://vercel.com).diff --git a/.agents/skills/vercel-react-best-practices/SKILL.md b/.agents/skills/vercel-react-best-practices/SKILL.mdnew file mode 100644index 0000000..237988d--- /dev/null+++ b/.agents/skills/vercel-react-best-practices/SKILL.md@@ -0,0 +1,149 @@+---+name: vercel-react-best-practices+description: React and Next.js performance optimization guidelines from Vercel Engineering. This skill should be used when writing, reviewing, or refactoring React/Next.js code to ensure optimal performance patterns. Triggers on tasks involving React components, Next.js pages, data fetching, bundle optimization, or performance improvements.+license: MIT+metadata:+ author: vercel+ version: "1.0.0"+---++# Vercel React Best Practices++Comprehensive performance optimization guide for React and Next.js applications, maintained by Vercel. Contains 70 rules across 8 categories, prioritized by impact to guide automated refactoring and code generation.++## When to Apply++Reference these guidelines when:+- Writing new React components or Next.js pages+- Implementing data fetching (client or server-side)+- Reviewing code for performance issues+- Refactoring existing React/Next.js code+- Optimizing bundle size or load times++## Rule Categories by Priority++| Priority | Category | Impact | Prefix |+|----------|----------|--------|--------|+| 1 | Eliminating Waterfalls | CRITICAL | `async-` |+| 2 | Bundle Size Optimization | CRITICAL | `bundle-` |+| 3 | Server-Side Performance | HIGH | `server-` |+| 4 | Client-Side Data Fetching | MEDIUM-HIGH | `client-` |+| 5 | Re-render Optimization | MEDIUM | `rerender-` |+| 6 | Rendering Performance | MEDIUM | `rendering-` |+| 7 | JavaScript Performance | LOW-MEDIUM | `js-` |+| 8 | Advanced Patterns | LOW | `advanced-` |++## Quick Reference++### 1. Eliminating Waterfalls (CRITICAL)++- `async-cheap-condition-before-await` - Check cheap sync conditions before awaiting flags or remote values+- `async-defer-await` - Move await into branches where actually used+- `async-parallel` - Use Promise.all() for independent operations+- `async-dependencies` - Use better-all for partial dependencies+- `async-api-routes` - Start promises early, await late in API routes+- `async-suspense-boundaries` - Use Suspense to stream content++### 2. Bundle Size Optimization (CRITICAL)++- `bundle-barrel-imports` - Import directly, avoid barrel files+- `bundle-analyzable-paths` - Prefer statically analyzable import and file-system paths to avoid broad bundles and traces+- `bundle-dynamic-imports` - Use next/dynamic for heavy components+- `bundle-defer-third-party` - Load analytics/logging after hydration+- `bundle-conditional` - Load modules only when feature is activated+- `bundle-preload` - Preload on hover/focus for perceived speed++### 3. Server-Side Performance (HIGH)++- `server-auth-actions` - Authenticate server actions like API routes+- `server-cache-react` - Use React.cache() for per-request deduplication+- `server-cache-lru` - Use LRU cache for cross-request caching+- `server-dedup-props` - Avoid duplicate serialization in RSC props+- `server-hoist-static-io` - Hoist static I/O (fonts, logos) to module level+- `server-no-shared-module-state` - Avoid module-level mutable request state in RSC/SSR+- `server-serialization` - Minimize data passed to client components+- `server-parallel-fetching` - Restructure components to parallelize fetches+- `server-parallel-nested-fetching` - Chain nested fetches per item in Promise.all+- `server-after-nonblocking` - Use after() for non-blocking operations++### 4. Client-Side Data Fetching (MEDIUM-HIGH)++- `client-swr-dedup` - Use SWR for automatic request deduplication+- `client-event-listeners` - Deduplicate global event listeners+- `client-passive-event-listeners` - Use passive listeners for scroll+- `client-localstorage-schema` - Version and minimize localStorage data++### 5. Re-render Optimization (MEDIUM)++- `rerender-defer-reads` - Don't subscribe to state only used in callbacks+- `rerender-memo` - Extract expensive work into memoized components+- `rerender-memo-with-default-value` - Hoist default non-primitive props+- `rerender-dependencies` - Use primitive dependencies in effects+- `rerender-derived-state` - Subscribe to derived booleans, not raw values+- `rerender-derived-state-no-effect` - Derive state during render, not effects+- `rerender-functional-setstate` - Use functional setState for stable callbacks+- `rerender-lazy-state-init` - Pass function to useState for expensive values+- `rerender-simple-expression-in-memo` - Avoid memo for simple primitives+- `rerender-split-combined-hooks` - Split hooks with independent dependencies+- `rerender-move-effect-to-event` - Put interaction logic in event handlers+- `rerender-transitions` - Use startTransition for non-urgent updates+- `rerender-use-deferred-value` - Defer expensive renders to keep input responsive+- `rerender-use-ref-transient-values` - Use refs for transient frequent values+- `rerender-no-inline-components` - Don't define components inside components++### 6. Rendering Performance (MEDIUM)++- `rendering-animate-svg-wrapper` - Animate div wrapper, not SVG element+- `rendering-content-visibility` - Use content-visibility for long lists+- `rendering-hoist-jsx` - Extract static JSX outside components+- `rendering-svg-precision` - Reduce SVG coordinate precision+- `rendering-hydration-no-flicker` - Use inline script for client-only data+- `rendering-hydration-suppress-warning` - Suppress expected mismatches+- `rendering-activity` - Use Activity component for show/hide+- `rendering-conditional-render` - Use ternary, not && for conditionals+- `rendering-usetransition-loading` - Prefer useTransition for loading state+- `rendering-resource-hints` - Use React DOM resource hints for preloading+- `rendering-script-defer-async` - Use defer or async on script tags++### 7. JavaScript Performance (LOW-MEDIUM)++- `js-batch-dom-css` - Group CSS changes via classes or cssText+- `js-index-maps` - Build Map for repeated lookups+- `js-cache-property-access` - Cache object properties in loops+- `js-cache-function-results` - Cache function results in module-level Map+- `js-cache-storage` - Cache localStorage/sessionStorage reads+- `js-combine-iterations` - Combine multiple filter/map into one loop+- `js-length-check-first` - Check array length before expensive comparison+- `js-early-exit` - Return early from functions+- `js-hoist-regexp` - Hoist RegExp creation outside loops+- `js-min-max-loop` - Use loop for min/max instead of sort+- `js-set-map-lookups` - Use Set/Map for O(1) lookups+- `js-tosorted-immutable` - Use toSorted() for immutability+- `js-flatmap-filter` - Use flatMap to map and filter in one pass+- `js-request-idle-callback` - Defer non-critical work to browser idle time++### 8. Advanced Patterns (LOW)++- `advanced-effect-event-deps` - Don't put `useEffectEvent` results in effect deps+- `advanced-event-handler-refs` - Store event handlers in refs+- `advanced-init-once` - Initialize app once per app load+- `advanced-use-latest` - useLatest for stable callback refs++## How to Use++Read individual rule files for detailed explanations and code examples:++```+rules/async-parallel.md+rules/bundle-barrel-imports.md+```++Each rule file contains:+- Brief explanation of why it matters+- Incorrect code example with explanation+- Correct code example with explanation+- Additional context and references++## Full Compiled Document++For the complete guide with all rules expanded: `AGENTS.md`diff --git a/.agents/skills/vercel-react-best-practices/rules/_sections.md b/.agents/skills/vercel-react-best-practices/rules/_sections.mdnew file mode 100644index 0000000..4d20c14--- /dev/null+++ b/.agents/skills/vercel-react-best-practices/rules/_sections.md@@ -0,0 +1,46 @@+# Sections++This file defines all sections, their ordering, impact levels, and descriptions.+The section ID (in parentheses) is the filename prefix used to group rules.++---++## 1. Eliminating Waterfalls (async)++**Impact:** CRITICAL+**Description:** Waterfalls are the #1 performance killer. Each sequential await adds full network latency. Eliminating them yields the largest gains.++## 2. Bundle Size Optimization (bundle)++**Impact:** CRITICAL+**Description:** Reducing initial bundle size improves Time to Interactive and Largest Contentful Paint.++## 3. Server-Side Performance (server)++**Impact:** HIGH+**Description:** Optimizing server-side rendering and data fetching eliminates server-side waterfalls and reduces response times.++## 4. Client-Side Data Fetching (client)++**Impact:** MEDIUM-HIGH+**Description:** Automatic deduplication and efficient data fetching patterns reduce redundant network requests.++## 5. Re-render Optimization (rerender)++**Impact:** MEDIUM+**Description:** Reducing unnecessary re-renders minimizes wasted computation and improves UI responsiveness.++## 6. Rendering Performance (rendering)++**Impact:** MEDIUM+**Description:** Optimizing the rendering process reduces the work the browser needs to do.++## 7. JavaScript Performance (js)++**Impact:** LOW-MEDIUM+**Description:** Micro-optimizations for hot paths can add up to meaningful improvements.++## 8. Advanced Patterns (advanced)++**Impact:** LOW+**Description:** Advanced patterns for specific cases that require careful implementation.diff --git a/.agents/skills/vercel-react-best-practices/rules/_template.md b/.agents/skills/vercel-react-best-practices/rules/_template.mdnew file mode 100644index 0000000..1e9e707--- /dev/null+++ b/.agents/skills/vercel-react-best-practices/rules/_template.md@@ -0,0 +1,28 @@+---+title: Rule Title Here+impact: MEDIUM+impactDescription: Optional description of impact (e.g., "20-50% improvement")+tags: tag1, tag2+---++## Rule Title Here++**Impact: MEDIUM (optional impact description)**++Brief explanation of the rule and why it matters. This should be clear and concise, explaining the performance implications.++**Incorrect (description of what's wrong):**++```typescript+// Bad code example here+const bad = example()+```++**Correct (description of what's right):**++```typescript+// Good code example here+const good = example()+```++Reference: [Link to documentation or resource](https://example.com)diff --git a/.agents/skills/vercel-react-best-practices/rules/advanced-effect-event-deps.md b/.agents/skills/vercel-react-best-practices/rules/advanced-effect-event-deps.mdnew file mode 100644index 0000000..24d901b--- /dev/null+++ b/.agents/skills/vercel-react-best-practices/rules/advanced-effect-event-deps.md@@ -0,0 +1,56 @@+---+title: Do Not Put Effect Events in Dependency Arrays+impact: LOW+impactDescription: avoids unnecessary effect re-runs and lint errors+tags: advanced, hooks, useEffectEvent, dependencies, effects+---++## Do Not Put Effect Events in Dependency Arrays++Effect Event functions do not have a stable identity. Their identity intentionally changes on every render. Do not include the function returned by `useEffectEvent` in a `useEffect` dependency array. Keep the actual reactive values as dependencies and call the Effect Event from inside the effect body or subscriptions created by that effect.++**Incorrect (Effect Event added as a dependency):**++```tsx+import { useEffect, useEffectEvent } from 'react'++function ChatRoom({ roomId, onConnected }: {+ roomId: string+ onConnected: () => void+}) {+ const handleConnected = useEffectEvent(onConnected)++ useEffect(() => {+ const connection = createConnection(roomId)+ connection.on('connected', handleConnected)+ connection.connect()++ return () => connection.disconnect()+ }, [roomId, handleConnected])+}+```++Including the Effect Event in dependencies makes the effect re-run every render and triggers the React Hooks lint rule.++**Correct (depend on reactive values, not the Effect Event):**++```tsx+import { useEffect, useEffectEvent } from 'react'++function ChatRoom({ roomId, onConnected }: {+ roomId: string+ onConnected: () => void+}) {+ const handleConnected = useEffectEvent(onConnected)++ useEffect(() => {+ const connection = createConnection(roomId)+ connection.on('connected', handleConnected)+ connection.connect()++ return () => connection.disconnect()+ }, [roomId])+}+```++Reference: [React useEffectEvent: Effect Event in deps](https://react.dev/reference/react/useEffectEvent#effect-event-in-deps)diff --git a/.agents/skills/vercel-react-best-practices/rules/advanced-event-handler-refs.md b/.agents/skills/vercel-react-best-practices/rules/advanced-event-handler-refs.mdnew file mode 100644index 0000000..97e7ade--- /dev/null+++ b/.agents/skills/vercel-react-best-practices/rules/advanced-event-handler-refs.md@@ -0,0 +1,55 @@+---+title: Store Event Handlers in Refs+impact: LOW+impactDescription: stable subscriptions+tags: advanced, hooks, refs, event-handlers, optimization+---++## Store Event Handlers in Refs++Store callbacks in refs when used in effects that shouldn't re-subscribe on callback changes.++**Incorrect (re-subscribes on every render):**++```tsx+function useWindowEvent(event: string, handler: (e) => void) {+ useEffect(() => {+ window.addEventListener(event, handler)+ return () => window.removeEventListener(event, handler)+ }, [event, handler])+}+```++**Correct (stable subscription):**++```tsx+function useWindowEvent(event: string, handler: (e) => void) {+ const handlerRef = useRef(handler)+ useEffect(() => {+ handlerRef.current = handler+ }, [handler])++ useEffect(() => {+ const listener = (e) => handlerRef.current(e)+ window.addEventListener(event, listener)+ return () => window.removeEventListener(event, listener)+ }, [event])+}+```++**Alternative: use `useEffectEvent` if you're on latest React:**++```tsx+import { useEffectEvent } from 'react'++function useWindowEvent(event: string, handler: (e) => void) {+ const onEvent = useEffectEvent(handler)++ useEffect(() => {+ window.addEventListener(event, onEvent)+ return () => window.removeEventListener(event, onEvent)+ }, [event])+}+```++`useEffectEvent` provides a cleaner API for the same pattern: it creates a stable function reference that always calls the latest version of the handler.diff --git a/.agents/skills/vercel-react-best-practices/rules/advanced-init-once.md b/.agents/skills/vercel-react-best-practices/rules/advanced-init-once.mdnew file mode 100644index 0000000..73ee38e--- /dev/null+++ b/.agents/skills/vercel-react-best-practices/rules/advanced-init-once.md@@ -0,0 +1,42 @@+---+title: Initialize App Once, Not Per Mount+impact: LOW-MEDIUM+impactDescription: avoids duplicate init in development+tags: initialization, useEffect, app-startup, side-effects+---++## Initialize App Once, Not Per Mount++Do not put app-wide initialization that must run once per app load inside `useEffect([])` of a component. Components can remount and effects will re-run. Use a module-level guard or top-level init in the entry module instead.++**Incorrect (runs twice in dev, re-runs on remount):**++```tsx+function Comp() {+ useEffect(() => {+ loadFromStorage()+ checkAuthToken()+ }, [])++ // ...+}+```++**Correct (once per app load):**++```tsx+let didInit = false++function Comp() {+ useEffect(() => {+ if (didInit) return+ didInit = true+ loadFromStorage()+ checkAuthToken()+ }, [])++ // ...+}+```++Reference: [Initializing the application](https://react.dev/learn/you-might-not-need-an-effect#initializing-the-application)diff --git a/.agents/skills/vercel-react-best-practices/rules/advanced-use-latest.md b/.agents/skills/vercel-react-best-practices/rules/advanced-use-latest.mdnew file mode 100644index 0000000..9c7cb50--- /dev/null+++ b/.agents/skills/vercel-react-best-practices/rules/advanced-use-latest.md@@ -0,0 +1,39 @@+---+title: useEffectEvent for Stable Callback Refs+impact: LOW+impactDescription: prevents effect re-runs+tags: advanced, hooks, useEffectEvent, refs, optimization+---++## useEffectEvent for Stable Callback Refs++Access latest values in callbacks without adding them to dependency arrays. Prevents effect re-runs while avoiding stale closures.++**Incorrect (effect re-runs on every callback change):**++```tsx+function SearchInput({ onSearch }: { onSearch: (q: string) => void }) {+ const [query, setQuery] = useState('')++ useEffect(() => {+ const timeout = setTimeout(() => onSearch(query), 300)+ return () => clearTimeout(timeout)+ }, [query, onSearch])+}+```++**Correct (using React's useEffectEvent):**++```tsx+import { useEffectEvent } from 'react';++function SearchInput({ onSearch }: { onSearch: (q: string) => void }) {+ const [query, setQuery] = useState('')+ const onSearchEvent = useEffectEvent(onSearch)++ useEffect(() => {+ const timeout = setTimeout(() => onSearchEvent(query), 300)+ return () => clearTimeout(timeout)+ }, [query])+}+```diff --git a/.agents/skills/vercel-react-best-practices/rules/async-api-routes.md b/.agents/skills/vercel-react-best-practices/rules/async-api-routes.mdnew file mode 100644index 0000000..6feda1e--- /dev/null+++ b/.agents/skills/vercel-react-best-practices/rules/async-api-routes.md@@ -0,0 +1,38 @@+---+title: Prevent Waterfall Chains in API Routes+impact: CRITICAL+impactDescription: 2-10× improvement+tags: api-routes, server-actions, waterfalls, parallelization+---++## Prevent Waterfall Chains in API Routes++In API routes and Server Actions, start independent operations immediately, even if you don't await them yet.++**Incorrect (config waits for auth, data waits for both):**++```typescript+export async function GET(request: Request) {+ const session = await auth()+ const config = await fetchConfig()+ const data = await fetchData(session.user.id)+ return Response.json({ data, config })+}+```++**Correct (auth and config start immediately):**++```typescript+export async function GET(request: Request) {+ const sessionPromise = auth()+ const configPromise = fetchConfig()+ const session = await sessionPromise+ const [config, data] = await Promise.all([+ configPromise,+ fetchData(session.user.id)+ ])+ return Response.json({ data, config })+}+```++For operations with more complex dependency chains, use `better-all` to automatically maximize parallelism (see Dependency-Based Parallelization).diff --git a/.agents/skills/vercel-react-best-practices/rules/async-cheap-condition-before-await.md b/.agents/skills/vercel-react-best-practices/rules/async-cheap-condition-before-await.mdnew file mode 100644index 0000000..5799d7f--- /dev/null+++ b/.agents/skills/vercel-react-best-practices/rules/async-cheap-condition-before-await.md@@ -0,0 +1,37 @@+---+title: Check Cheap Conditions Before Async Flags+impact: HIGH+impactDescription: avoids unnecessary async work when a synchronous guard already fails+tags: async, await, feature-flags, short-circuit, conditional+---++## Check Cheap Conditions Before Async Flags++When a branch uses `await` for a flag or remote value and also requires a **cheap synchronous** condition (local props, request metadata, already-loaded state), evaluate the cheap condition **first**. Otherwise you pay for the async call even when the compound condition can never be true.++This is a specialization of [Defer Await Until Needed](./async-defer-await.md) for `flag && cheapCondition` style checks.++**Incorrect:**++```typescript+const someFlag = await getFlag()++if (someFlag && someCondition) {+ // ...+}+```++**Correct:**++```typescript+if (someCondition) {+ const someFlag = await getFlag()+ if (someFlag) {+ // ...+ }+}+```++This matters when `getFlag` hits the network, a feature-flag service, or `React.cache` / DB work: skipping it when `someCondition` is false removes that cost on the cold path.++Keep the original order if `someCondition` is expensive, depends on the flag, or you must run side effects in a fixed order.diff --git a/.agents/skills/vercel-react-best-practices/rules/async-defer-await.md b/.agents/skills/vercel-react-best-practices/rules/async-defer-await.mdnew file mode 100644index 0000000..460b5e1--- /dev/null+++ b/.agents/skills/vercel-react-best-practices/rules/async-defer-await.md@@ -0,0 +1,82 @@+---+title: Defer Await Until Needed+impact: HIGH+impactDescription: avoids blocking unused code paths+tags: async, await, conditional, optimization+---++## Defer Await Until Needed++Move `await` operations into the branches where they're actually used to avoid blocking code paths that don't need them.++**Incorrect (blocks both branches):**++```typescript+async function handleRequest(userId: string, skipProcessing: boolean) {+ const userData = await fetchUserData(userId)++ if (skipProcessing) {+ // Returns immediately but still waited for userData+ return { skipped: true }+ }++ // Only this branch uses userData+ return processUserData(userData)+}+```++**Correct (only blocks when needed):**++```typescript+async function handleRequest(userId: string, skipProcessing: boolean) {+ if (skipProcessing) {+ // Returns immediately without waiting+ return { skipped: true }+ }++ // Fetch only when needed+ const userData = await fetchUserData(userId)+ return processUserData(userData)+}+```++**Another example (early return optimization):**++```typescript+// Incorrect: always fetches permissions+async function updateResource(resourceId: string, userId: string) {+ const permissions = await fetchPermissions(userId)+ const resource = await getResource(resourceId)++ if (!resource) {+ return { error: 'Not found' }+ }++ if (!permissions.canEdit) {+ return { error: 'Forbidden' }+ }++ return await updateResourceData(resource, permissions)+}++// Correct: fetches only when needed+async function updateResource(resourceId: string, userId: string) {+ const resource = await getResource(resourceId)++ if (!resource) {+ return { error: 'Not found' }+ }++ const permissions = await fetchPermissions(userId)++ if (!permissions.canEdit) {+ return { error: 'Forbidden' }+ }++ return await updateResourceData(resource, permissions)+}+```++This optimization is especially valuable when the skipped branch is frequently taken, or when the deferred operation is expensive.++For `await getFlag()` combined with a cheap synchronous guard (`flag && someCondition`), see [Check Cheap Conditions Before Async Flags](./async-cheap-condition-before-await.md).diff --git a/.agents/skills/vercel-react-best-practices/rules/async-dependencies.md b/.agents/skills/vercel-react-best-practices/rules/async-dependencies.mdnew file mode 100644index 0000000..0484eba--- /dev/null+++ b/.agents/skills/vercel-react-best-practices/rules/async-dependencies.md@@ -0,0 +1,51 @@+---+title: Dependency-Based Parallelization+impact: CRITICAL+impactDescription: 2-10× improvement+tags: async, parallelization, dependencies, better-all+---++## Dependency-Based Parallelization++For operations with partial dependencies, use `better-all` to maximize parallelism. It automatically starts each task at the earliest possible moment.++**Incorrect (profile waits for config unnecessarily):**++```typescript+const [user, config] = await Promise.all([+ fetchUser(),+ fetchConfig()+])+const profile = await fetchProfile(user.id)+```++**Correct (config and profile run in parallel):**++```typescript+import { all } from 'better-all'++const { user, config, profile } = await all({+ async user() { return fetchUser() },+ async config() { return fetchConfig() },+ async profile() {+ return fetchProfile((await this.$.user).id)+ }+})+```++**Alternative without extra dependencies:**++We can also create all the promises first, and do `Promise.all()` at the end.++```typescript+const userPromise = fetchUser()+const profilePromise = userPromise.then(user => fetchProfile(user.id))++const [user, config, profile] = await Promise.all([+ userPromise,+ fetchConfig(),+ profilePromise+])+```++Reference: [https://github.com/shuding/better-all](https://github.com/shuding/better-all)diff --git a/.agents/skills/vercel-react-best-practices/rules/async-parallel.md b/.agents/skills/vercel-react-best-practices/rules/async-parallel.mdnew file mode 100644index 0000000..64133f6--- /dev/null+++ b/.agents/skills/vercel-react-best-practices/rules/async-parallel.md@@ -0,0 +1,28 @@+---+title: Promise.all() for Independent Operations+impact: CRITICAL+impactDescription: 2-10× improvement+tags: async, parallelization, promises, waterfalls+---++## Promise.all() for Independent Operations++When async operations have no interdependencies, execute them concurrently using `Promise.all()`.++**Incorrect (sequential execution, 3 round trips):**++```typescript+const user = await fetchUser()+const posts = await fetchPosts()+const comments = await fetchComments()+```++**Correct (parallel execution, 1 round trip):**++```typescript+const [user, posts, comments] = await Promise.all([+ fetchUser(),+ fetchPosts(),+ fetchComments()+])+```diff --git a/.agents/skills/vercel-react-best-practices/rules/async-suspense-boundaries.md b/.agents/skills/vercel-react-best-practices/rules/async-suspense-boundaries.mdnew file mode 100644index 0000000..1fbc05b--- /dev/null+++ b/.agents/skills/vercel-react-best-practices/rules/async-suspense-boundaries.md@@ -0,0 +1,99 @@+---+title: Strategic Suspense Boundaries+impact: HIGH+impactDescription: faster initial paint+tags: async, suspense, streaming, layout-shift+---++## Strategic Suspense Boundaries++Instead of awaiting data in async components before returning JSX, use Suspense boundaries to show the wrapper UI faster while data loads.++**Incorrect (wrapper blocked by data fetching):**++```tsx+async function Page() {+ const data = await fetchData() // Blocks entire page++ return (+ <div>+ <div>Sidebar</div>+ <div>Header</div>+ <div>+ <DataDisplay data={data} />+ </div>+ <div>Footer</div>+ </div>+ )+}+```++The entire layout waits for data even though only the middle section needs it.++**Correct (wrapper shows immediately, data streams in):**++```tsx+function Page() {+ return (+ <div>+ <div>Sidebar</div>+ <div>Header</div>+ <div>+ <Suspense fallback={<Skeleton />}>+ <DataDisplay />+ </Suspense>+ </div>+ <div>Footer</div>+ </div>+ )+}++async function DataDisplay() {+ const data = await fetchData() // Only blocks this component+ return <div>{data.content}</div>+}+```++Sidebar, Header, and Footer render immediately. Only DataDisplay waits for data.++**Alternative (share promise across components):**++```tsx+function Page() {+ // Start fetch immediately, but don't await+ const dataPromise = fetchData()++ return (+ <div>+ <div>Sidebar</div>+ <div>Header</div>+ <Suspense fallback={<Skeleton />}>+ <DataDisplay dataPromise={dataPromise} />+ <DataSummary dataPromise={dataPromise} />+ </Suspense>+ <div>Footer</div>+ </div>+ )+}++function DataDisplay({ dataPromise }: { dataPromise: Promise<Data> }) {+ const data = use(dataPromise) // Unwraps the promise+ return <div>{data.content}</div>+}++function DataSummary({ dataPromise }: { dataPromise: Promise<Data> }) {+ const data = use(dataPromise) // Reuses the same promise+ return <div>{data.summary}</div>+}+```++Both components share the same promise, so only one fetch occurs. Layout renders immediately while both components wait together.++**When NOT to use this pattern:**++- Critical data needed for layout decisions (affects positioning)+- SEO-critical content above the fold+- Small, fast queries where suspense overhead isn't worth it+- When you want to avoid layout shift (loading → content jump)++**Trade-off:** Faster initial paint vs potential layout shift. Choose based on your UX priorities.diff --git a/.agents/skills/vercel-react-best-practices/rules/bundle-analyzable-paths.md b/.agents/skills/vercel-react-best-practices/rules/bundle-analyzable-paths.mdnew file mode 100644index 0000000..8276f15--- /dev/null+++ b/.agents/skills/vercel-react-best-practices/rules/bundle-analyzable-paths.md@@ -0,0 +1,63 @@+---+title: Prefer Statically Analyzable Paths+impact: HIGH+impactDescription: avoids accidental broad bundles and file traces+tags: bundle, nextjs, vite, webpack, rollup, esbuild, path+---++## Prefer Statically Analyzable Paths++Build tools work best when import and file-system paths are obvious at build time. If you hide the real path inside a variable or compose it too dynamically, the tool either has to include a broad set of possible files, warn that it cannot analyze the import, or widen file tracing to stay safe.++Prefer explicit maps or literal paths so the set of reachable files stays narrow and predictable. This is the same rule whether you are choosing modules with `import()` or reading files in server/build code.++When analysis becomes too broad, the cost is real:+- Larger server bundles+- Slower builds+- Worse cold starts+- More memory use++### Import Paths++**Incorrect (the bundler cannot tell what may be imported):**++```ts+const PAGE_MODULES = {+ home: './pages/home',+ settings: './pages/settings',+} as const++const Page = await import(PAGE_MODULES[pageName])+```++**Correct (use an explicit map of allowed modules):**++```ts+const PAGE_MODULES = {+ home: () => import('./pages/home'),+ settings: () => import('./pages/settings'),+} as const++const Page = await PAGE_MODULES[pageName]()+```++### File-System Paths++**Incorrect (a 2-value enum still hides the final path from static analysis):**++```ts+const baseDir = path.join(process.cwd(), 'content/' + contentKind)+```++**Correct (make each final path literal at the callsite):**++```ts+const baseDir =+ kind === ContentKind.Blog+ ? path.join(process.cwd(), 'content/blog')+ : path.join(process.cwd(), 'content/docs')+```++In Next.js server code, this matters for output file tracing too. `path.join(process.cwd(), someVar)` can widen the traced file set because Next.js statically analyze `import`, `require`, and `fs` usage.++Reference: [Next.js output](https://nextjs.org/docs/app/api-reference/config/next-config-js/output), [Next.js dynamic imports](https://nextjs.org/learn/seo/dynamic-imports), [Vite features](https://vite.dev/guide/features.html), [esbuild API](https://esbuild.github.io/api/), [Rollup dynamic import vars](https://www.npmjs.com/package/@rollup/plugin-dynamic-import-vars), [Webpack dependency management](https://webpack.js.org/guides/dependency-management/)diff --git a/.agents/skills/vercel-react-best-practices/rules/bundle-barrel-imports.md b/.agents/skills/vercel-react-best-practices/rules/bundle-barrel-imports.mdnew file mode 100644index 0000000..22d1050--- /dev/null+++ b/.agents/skills/vercel-react-best-practices/rules/bundle-barrel-imports.md@@ -0,0 +1,60 @@+---+title: Avoid Barrel File Imports+impact: CRITICAL+impactDescription: 200-800ms import cost, slow builds+tags: bundle, imports, tree-shaking, barrel-files, performance+---++## Avoid Barrel File Imports++Import directly from source files instead of barrel files to avoid loading thousands of unused modules. **Barrel files** are entry points that re-export multiple modules (e.g., `index.js` that does `export * from './module'`).++Popular icon and component libraries can have **up to 10,000 re-exports** in their entry file. For many React packages, **it takes 200-800ms just to import them**, affecting both development speed and production cold starts.++**Why tree-shaking doesn't help:** When a library is marked as external (not bundled), the bundler can't optimize it. If you bundle it to enable tree-shaking, builds become substantially slower analyzing the entire module graph.++**Incorrect (imports entire library):**++```tsx+import { Check, X, Menu } from 'lucide-react'+// Loads 1,583 modules, takes ~2.8s extra in dev+// Runtime cost: 200-800ms on every cold start++import { Button, TextField } from '@mui/material'+// Loads 2,225 modules, takes ~4.2s extra in dev+```++**Correct - Next.js 13.5+ (recommended):**++```js+// next.config.js - automatically optimizes barrel imports at build time+module.exports = {+ experimental: {+ optimizePackageImports: ['lucide-react', '@mui/material']+ }+}+```++```tsx+// Keep the standard imports - Next.js transforms them to direct imports+import { Check, X, Menu } from 'lucide-react'+// Full TypeScript support, no manual path wrangling+```++This is the recommended approach because it preserves TypeScript type safety and editor autocompletion while still eliminating the barrel import cost.++**Correct - Direct imports (non-Next.js projects):**++```tsx+import Button from '@mui/material/Button'+import TextField from '@mui/material/TextField'+// Loads only what you use+```++> **TypeScript warning:** Some libraries (notably `lucide-react`) don't ship `.d.ts` files for their deep import paths. Importing from `lucide-react/dist/esm/icons/check` resolves to an implicit `any` type, causing errors under `strict` or `noImplicitAny`. Prefer `optimizePackageImports` when available, or verify the library exports types for its subpaths before using direct imports.++These optimizations provide 15-70% faster dev boot, 28% faster builds, 40% faster cold starts, and significantly faster HMR.++Libraries commonly affected: `lucide-react`, `@mui/material`, `@mui/icons-material`, `@tabler/icons-react`, `react-icons`, `@headlessui/react`, `@radix-ui/react-*`, `lodash`, `ramda`, `date-fns`, `rxjs`, `react-use`.++Reference: [How we optimized package imports in Next.js](https://vercel.com/blog/how-we-optimized-package-imports-in-next-js)diff --git a/.agents/skills/vercel-react-best-practices/rules/bundle-conditional.md b/.agents/skills/vercel-react-best-practices/rules/bundle-conditional.mdnew file mode 100644index 0000000..99d6fc9--- /dev/null+++ b/.agents/skills/vercel-react-best-practices/rules/bundle-conditional.md@@ -0,0 +1,31 @@+---+title: Conditional Module Loading+impact: HIGH+impactDescription: loads large data only when needed+tags: bundle, conditional-loading, lazy-loading+---++## Conditional Module Loading++Load large data or modules only when a feature is activated.++**Example (lazy-load animation frames):**++```tsx+function AnimationPlayer({ enabled, setEnabled }: { enabled: boolean; setEnabled: React.Dispatch<React.SetStateAction<boolean>> }) {+ const [frames, setFrames] = useState<Frame[] | null>(null)++ useEffect(() => {+ if (enabled && !frames && typeof window !== 'undefined') {+ import('./animation-frames.js')+ .then(mod => setFrames(mod.frames))+ .catch(() => setEnabled(false))+ }+ }, [enabled, frames, setEnabled])++ if (!frames) return <Skeleton />+ return <Canvas frames={frames} />+}+```++The `typeof window !== 'undefined'` check prevents bundling this module for SSR, optimizing server bundle size and build speed.diff --git a/.agents/skills/vercel-react-best-practices/rules/bundle-defer-third-party.md b/.agents/skills/vercel-react-best-practices/rules/bundle-defer-third-party.mdnew file mode 100644index 0000000..db041d1--- /dev/null+++ b/.agents/skills/vercel-react-best-practices/rules/bundle-defer-third-party.md@@ -0,0 +1,49 @@+---+title: Defer Non-Critical Third-Party Libraries+impact: MEDIUM+impactDescription: loads after hydration+tags: bundle, third-party, analytics, defer+---++## Defer Non-Critical Third-Party Libraries++Analytics, logging, and error tracking don't block user interaction. Load them after hydration.++**Incorrect (blocks initial bundle):**++```tsx+import { Analytics } from '@vercel/analytics/react'++export default function RootLayout({ children }) {+ return (+ <html>+ <body>+ {children}+ <Analytics />+ </body>+ </html>+ )+}+```++**Correct (loads after hydration):**++```tsx+import dynamic from 'next/dynamic'++const Analytics = dynamic(+ () => import('@vercel/analytics/react').then(m => m.Analytics),+ { ssr: false }+)++export default function RootLayout({ children }) {+ return (+ <html>+ <body>+ {children}+ <Analytics />+ </body>+ </html>+ )+}+```diff --git a/.agents/skills/vercel-react-best-practices/rules/bundle-dynamic-imports.md b/.agents/skills/vercel-react-best-practices/rules/bundle-dynamic-imports.mdnew file mode 100644index 0000000..60b6269--- /dev/null+++ b/.agents/skills/vercel-react-best-practices/rules/bundle-dynamic-imports.md@@ -0,0 +1,35 @@+---+title: Dynamic Imports for Heavy Components+impact: CRITICAL+impactDescription: directly affects TTI and LCP+tags: bundle, dynamic-import, code-splitting, next-dynamic+---++## Dynamic Imports for Heavy Components++Use `next/dynamic` to lazy-load large components not needed on initial render.++**Incorrect (Monaco bundles with main chunk ~300KB):**++```tsx+import { MonacoEditor } from './monaco-editor'++function CodePanel({ code }: { code: string }) {+ return <MonacoEditor value={code} />+}+```++**Correct (Monaco loads on demand):**++```tsx+import dynamic from 'next/dynamic'++const MonacoEditor = dynamic(+ () => import('./monaco-editor').then(m => m.MonacoEditor),+ { ssr: false }+)++function CodePanel({ code }: { code: string }) {+ return <MonacoEditor value={code} />+}+```diff --git a/.agents/skills/vercel-react-best-practices/rules/bundle-preload.md b/.agents/skills/vercel-react-best-practices/rules/bundle-preload.mdnew file mode 100644index 0000000..7000504--- /dev/null+++ b/.agents/skills/vercel-react-best-practices/rules/bundle-preload.md@@ -0,0 +1,50 @@+---+title: Preload Based on User Intent+impact: MEDIUM+impactDescription: reduces perceived latency+tags: bundle, preload, user-intent, hover+---++## Preload Based on User Intent++Preload heavy bundles before they're needed to reduce perceived latency.++**Example (preload on hover/focus):**++```tsx+function EditorButton({ onClick }: { onClick: () => void }) {+ const preload = () => {+ if (typeof window !== 'undefined') {+ void import('./monaco-editor')+ }+ }++ return (+ <button+ onMouseEnter={preload}+ onFocus={preload}+ onClick={onClick}+ >+ Open Editor+ </button>+ )+}+```++**Example (preload when feature flag is enabled):**++```tsx+function FlagsProvider({ children, flags }: Props) {+ useEffect(() => {+ if (flags.editorEnabled && typeof window !== 'undefined') {+ void import('./monaco-editor').then(mod => mod.init())+ }+ }, [flags.editorEnabled])++ return <FlagsContext.Provider value={flags}>+ {children}+ </FlagsContext.Provider>+}+```++The `typeof window !== 'undefined'` check prevents bundling preloaded modules for SSR, optimizing server bundle size and build speed.diff --git a/.agents/skills/vercel-react-best-practices/rules/client-event-listeners.md b/.agents/skills/vercel-react-best-practices/rules/client-event-listeners.mdnew file mode 100644index 0000000..aad4ae9--- /dev/null+++ b/.agents/skills/vercel-react-best-practices/rules/client-event-listeners.md@@ -0,0 +1,74 @@+---+title: Deduplicate Global Event Listeners+impact: LOW+impactDescription: single listener for N components+tags: client, swr, event-listeners, subscription+---++## Deduplicate Global Event Listeners++Use `useSWRSubscription()` to share global event listeners across component instances.++**Incorrect (N instances = N listeners):**++```tsx+function useKeyboardShortcut(key: string, callback: () => void) {+ useEffect(() => {+ const handler = (e: KeyboardEvent) => {+ if (e.metaKey && e.key === key) {+ callback()+ }+ }+ window.addEventListener('keydown', handler)+ return () => window.removeEventListener('keydown', handler)+ }, [key, callback])+}+```++When using the `useKeyboardShortcut` hook multiple times, each instance will register a new listener.++**Correct (N instances = 1 listener):**++```tsx+import useSWRSubscription from 'swr/subscription'++// Module-level Map to track callbacks per key+const keyCallbacks = new Map<string, Set<() => void>>()++function useKeyboardShortcut(key: string, callback: () => void) {+ // Register this callback in the Map+ useEffect(() => {+ if (!keyCallbacks.has(key)) {+ keyCallbacks.set(key, new Set())+ }+ keyCallbacks.get(key)!.add(callback)++ return () => {+ const set = keyCallbacks.get(key)+ if (set) {+ set.delete(callback)+ if (set.size === 0) {+ keyCallbacks.delete(key)+ }+ }+ }+ }, [key, callback])++ useSWRSubscription('global-keydown', () => {+ const handler = (e: KeyboardEvent) => {+ if (e.metaKey && keyCallbacks.has(e.key)) {+ keyCallbacks.get(e.key)!.forEach(cb => cb())+ }+ }+ window.addEventListener('keydown', handler)+ return () => window.removeEventListener('keydown', handler)+ })+}++function Profile() {+ // Multiple shortcuts will share the same listener+ useKeyboardShortcut('p', () => { /* ... */ })+ useKeyboardShortcut('k', () => { /* ... */ })+ // ...+}+```diff --git a/.agents/skills/vercel-react-best-practices/rules/client-localstorage-schema.md b/.agents/skills/vercel-react-best-practices/rules/client-localstorage-schema.mdnew file mode 100644index 0000000..d30a1a7--- /dev/null+++ b/.agents/skills/vercel-react-best-practices/rules/client-localstorage-schema.md@@ -0,0 +1,71 @@+---+title: Version and Minimize localStorage Data+impact: MEDIUM+impactDescription: prevents schema conflicts, reduces storage size+tags: client, localStorage, storage, versioning, data-minimization+---++## Version and Minimize localStorage Data++Add version prefix to keys and store only needed fields. Prevents schema conflicts and accidental storage of sensitive data.++**Incorrect:**++```typescript+// No version, stores everything, no error handling+localStorage.setItem('userConfig', JSON.stringify(fullUserObject))+const data = localStorage.getItem('userConfig')+```++**Correct:**++```typescript+const VERSION = 'v2'++function saveConfig(config: { theme: string; language: string }) {+ try {+ localStorage.setItem(`userConfig:${VERSION}`, JSON.stringify(config))+ } catch {+ // Throws in incognito/private browsing, quota exceeded, or disabled+ }+}++function loadConfig() {+ try {+ const data = localStorage.getItem(`userConfig:${VERSION}`)+ return data ? JSON.parse(data) : null+ } catch {+ return null+ }+}++// Migration from v1 to v2+function migrate() {+ try {+ const v1 = localStorage.getItem('userConfig:v1')+ if (v1) {+ const old = JSON.parse(v1)+ saveConfig({ theme: old.darkMode ? 'dark' : 'light', language: old.lang })+ localStorage.removeItem('userConfig:v1')+ }+ } catch {}+}+```++**Store minimal fields from server responses:**++```typescript+// User object has 20+ fields, only store what UI needs+function cachePrefs(user: FullUser) {+ try {+ localStorage.setItem('prefs:v1', JSON.stringify({+ theme: user.preferences.theme,+ notifications: user.preferences.notifications+ }))+ } catch {}+}+```++**Always wrap in try-catch:** `getItem()` and `setItem()` throw in incognito/private browsing (Safari, Firefox), when quota exceeded, or when disabled.++**Benefits:** Schema evolution via versioning, reduced storage size, prevents storing tokens/PII/internal flags.diff --git a/.agents/skills/vercel-react-best-practices/rules/client-passive-event-listeners.md b/.agents/skills/vercel-react-best-practices/rules/client-passive-event-listeners.mdnew file mode 100644index 0000000..ce39a88--- /dev/null+++ b/.agents/skills/vercel-react-best-practices/rules/client-passive-event-listeners.md@@ -0,0 +1,48 @@+---+title: Use Passive Event Listeners for Scrolling Performance+impact: MEDIUM+impactDescription: eliminates scroll delay caused by event listeners+tags: client, event-listeners, scrolling, performance, touch, wheel+---++## Use Passive Event Listeners for Scrolling Performance++Add `{ passive: true }` to touch and wheel event listeners to enable immediate scrolling. Browsers normally wait for listeners to finish to check if `preventDefault()` is called, causing scroll delay.++**Incorrect:**++```typescript+useEffect(() => {+ const handleTouch = (e: TouchEvent) => console.log(e.touches[0].clientX)+ const handleWheel = (e: WheelEvent) => console.log(e.deltaY)++ document.addEventListener('touchstart', handleTouch)+ document.addEventListener('wheel', handleWheel)++ return () => {+ document.removeEventListener('touchstart', handleTouch)+ document.removeEventListener('wheel', handleWheel)+ }+}, [])+```++**Correct:**++```typescript+useEffect(() => {+ const handleTouch = (e: TouchEvent) => console.log(e.touches[0].clientX)+ const handleWheel = (e: WheelEvent) => console.log(e.deltaY)++ document.addEventListener('touchstart', handleTouch, { passive: true })+ document.addEventListener('wheel', handleWheel, { passive: true })++ return () => {+ document.removeEventListener('touchstart', handleTouch)+ document.removeEventListener('wheel', handleWheel)+ }+}, [])+```++**Use passive when:** tracking/analytics, logging, any listener that doesn't call `preventDefault()`.++**Don't use passive when:** implementing custom swipe gestures, custom zoom controls, or any listener that needs `preventDefault()`.diff --git a/.agents/skills/vercel-react-best-practices/rules/client-swr-dedup.md b/.agents/skills/vercel-react-best-practices/rules/client-swr-dedup.mdnew file mode 100644index 0000000..2a430f2--- /dev/null+++ b/.agents/skills/vercel-react-best-practices/rules/client-swr-dedup.md@@ -0,0 +1,56 @@+---+title: Use SWR for Automatic Deduplication+impact: MEDIUM-HIGH+impactDescription: automatic deduplication+tags: client, swr, deduplication, data-fetching+---++## Use SWR for Automatic Deduplication++SWR enables request deduplication, caching, and revalidation across component instances.++**Incorrect (no deduplication, each instance fetches):**++```tsx+function UserList() {+ const [users, setUsers] = useState([])+ useEffect(() => {+ fetch('/api/users')+ .then(r => r.json())+ .then(setUsers)+ }, [])+}+```++**Correct (multiple instances share one request):**++```tsx+import useSWR from 'swr'++function UserList() {+ const { data: users } = useSWR('/api/users', fetcher)+}+```++**For immutable data:**++```tsx+import { useImmutableSWR } from '@/lib/swr'++function StaticContent() {+ const { data } = useImmutableSWR('/api/config', fetcher)+}+```++**For mutations:**++```tsx+import { useSWRMutation } from 'swr/mutation'++function UpdateButton() {+ const { trigger } = useSWRMutation('/api/user', updateUser)+ return <button onClick={() => trigger()}>Update</button>+}+```++Reference: [https://swr.vercel.app](https://swr.vercel.app)diff --git a/.agents/skills/vercel-react-best-practices/rules/js-batch-dom-css.md b/.agents/skills/vercel-react-best-practices/rules/js-batch-dom-css.mdnew file mode 100644index 0000000..a62d84e--- /dev/null+++ b/.agents/skills/vercel-react-best-practices/rules/js-batch-dom-css.md@@ -0,0 +1,107 @@+---+title: Avoid Layout Thrashing+impact: MEDIUM+impactDescription: prevents forced synchronous layouts and reduces performance bottlenecks+tags: javascript, dom, css, performance, reflow, layout-thrashing+---++## Avoid Layout Thrashing++Avoid interleaving style writes with layout reads. When you read a layout property (like `offsetWidth`, `getBoundingClientRect()`, or `getComputedStyle()`) between style changes, the browser is forced to trigger a synchronous reflow.++**This is OK (browser batches style changes):**+```typescript+function updateElementStyles(element: HTMLElement) {+ // Each line invalidates style, but browser batches the recalculation+ element.style.width = '100px'+ element.style.height = '200px'+ element.style.backgroundColor = 'blue'+ element.style.border = '1px solid black'+}+```++**Incorrect (interleaved reads and writes force reflows):**+```typescript+function layoutThrashing(element: HTMLElement) {+ element.style.width = '100px'+ const width = element.offsetWidth // Forces reflow+ element.style.height = '200px'+ const height = element.offsetHeight // Forces another reflow+}+```++**Correct (batch writes, then read once):**+```typescript+function updateElementStyles(element: HTMLElement) {+ // Batch all writes together+ element.style.width = '100px'+ element.style.height = '200px'+ element.style.backgroundColor = 'blue'+ element.style.border = '1px solid black'++ // Read after all writes are done (single reflow)+ const { width, height } = element.getBoundingClientRect()+}+```++**Correct (batch reads, then writes):**+```typescript+function avoidThrashing(element: HTMLElement) {+ // Read phase - all layout queries first+ const rect1 = element.getBoundingClientRect()+ const offsetWidth = element.offsetWidth+ const offsetHeight = element.offsetHeight++ // Write phase - all style changes after+ element.style.width = '100px'+ element.style.height = '200px'+}+```++**Better: use CSS classes**+```css+.highlighted-box {+ width: 100px;+ height: 200px;+ background-color: blue;+ border: 1px solid black;+}+```+```typescript+function updateElementStyles(element: HTMLElement) {+ element.classList.add('highlighted-box')++ const { width, height } = element.getBoundingClientRect()+}+```++**React example:**+```tsx+// Incorrect: interleaving style changes with layout queries+function Box({ isHighlighted }: { isHighlighted: boolean }) {+ const ref = useRef<HTMLDivElement>(null)++ useEffect(() => {+ if (ref.current && isHighlighted) {+ ref.current.style.width = '100px'+ const width = ref.current.offsetWidth // Forces layout+ ref.current.style.height = '200px'+ }+ }, [isHighlighted])++ return <div ref={ref}>Content</div>+}++// Correct: toggle class+function Box({ isHighlighted }: { isHighlighted: boolean }) {+ return (+ <div className={isHighlighted ? 'highlighted-box' : ''}>+ Content+ </div>+ )+}+```++Prefer CSS classes over inline styles when possible. CSS files are cached by the browser, and classes provide better separation of concerns and are easier to maintain.++See [this gist](https://gist.github.com/paulirish/5d52fb081b3570c81e3a) and [CSS Triggers](https://csstriggers.com/) for more information on layout-forcing operations.diff --git a/.agents/skills/vercel-react-best-practices/rules/js-cache-function-results.md b/.agents/skills/vercel-react-best-practices/rules/js-cache-function-results.mdnew file mode 100644index 0000000..180f8ac--- /dev/null+++ b/.agents/skills/vercel-react-best-practices/rules/js-cache-function-results.md@@ -0,0 +1,80 @@+---+title: Cache Repeated Function Calls+impact: MEDIUM+impactDescription: avoid redundant computation+tags: javascript, cache, memoization, performance+---++## Cache Repeated Function Calls++Use a module-level Map to cache function results when the same function is called repeatedly with the same inputs during render.++**Incorrect (redundant computation):**++```typescript+function ProjectList({ projects }: { projects: Project[] }) {+ return (+ <div>+ {projects.map(project => {+ // slugify() called 100+ times for same project names+ const slug = slugify(project.name)++ return <ProjectCard key={project.id} slug={slug} />+ })}+ </div>+ )+}+```++**Correct (cached results):**++```typescript+// Module-level cache+const slugifyCache = new Map<string, string>()++function cachedSlugify(text: string): string {+ if (slugifyCache.has(text)) {+ return slugifyCache.get(text)!+ }+ const result = slugify(text)+ slugifyCache.set(text, result)+ return result+}++function ProjectList({ projects }: { projects: Project[] }) {+ return (+ <div>+ {projects.map(project => {+ // Computed only once per unique project name+ const slug = cachedSlugify(project.name)++ return <ProjectCard key={project.id} slug={slug} />+ })}+ </div>+ )+}+```++**Simpler pattern for single-value functions:**++```typescript+let isLoggedInCache: boolean | null = null++function isLoggedIn(): boolean {+ if (isLoggedInCache !== null) {+ return isLoggedInCache+ }++ isLoggedInCache = document.cookie.includes('auth=')+ return isLoggedInCache+}++// Clear cache when auth changes+function onAuthChange() {+ isLoggedInCache = null+}+```++Use a Map (not a hook) so it works everywhere: utilities, event handlers, not just React components.++Reference: [How we made the Vercel Dashboard twice as fast](https://vercel.com/blog/how-we-made-the-vercel-dashboard-twice-as-fast)diff --git a/.agents/skills/vercel-react-best-practices/rules/js-cache-property-access.md b/.agents/skills/vercel-react-best-practices/rules/js-cache-property-access.mdnew file mode 100644index 0000000..39eec90--- /dev/null+++ b/.agents/skills/vercel-react-best-practices/rules/js-cache-property-access.md@@ -0,0 +1,28 @@+---+title: Cache Property Access in Loops+impact: LOW-MEDIUM+impactDescription: reduces lookups+tags: javascript, loops, optimization, caching+---++## Cache Property Access in Loops++Cache object property lookups in hot paths.++**Incorrect (3 lookups × N iterations):**++```typescript+for (let i = 0; i < arr.length; i++) {+ process(obj.config.settings.value)+}+```++**Correct (1 lookup total):**++```typescript+const value = obj.config.settings.value+const len = arr.length+for (let i = 0; i < len; i++) {+ process(value)+}+```diff --git a/.agents/skills/vercel-react-best-practices/rules/js-cache-storage.md b/.agents/skills/vercel-react-best-practices/rules/js-cache-storage.mdnew file mode 100644index 0000000..aa4a30c--- /dev/null+++ b/.agents/skills/vercel-react-best-practices/rules/js-cache-storage.md@@ -0,0 +1,70 @@+---+title: Cache Storage API Calls+impact: LOW-MEDIUM+impactDescription: reduces expensive I/O+tags: javascript, localStorage, storage, caching, performance+---++## Cache Storage API Calls++`localStorage`, `sessionStorage`, and `document.cookie` are synchronous and expensive. Cache reads in memory.++**Incorrect (reads storage on every call):**++```typescript+function getTheme() {+ return localStorage.getItem('theme') ?? 'light'+}+// Called 10 times = 10 storage reads+```++**Correct (Map cache):**++```typescript+const storageCache = new Map<string, string | null>()++function getLocalStorage(key: string) {+ if (!storageCache.has(key)) {+ storageCache.set(key, localStorage.getItem(key))+ }+ return storageCache.get(key)+}++function setLocalStorage(key: string, value: string) {+ localStorage.setItem(key, value)+ storageCache.set(key, value) // keep cache in sync+}+```++Use a Map (not a hook) so it works everywhere: utilities, event handlers, not just React components.++**Cookie caching:**++```typescript+let cookieCache: Record<string, string> | null = null++function getCookie(name: string) {+ if (!cookieCache) {+ cookieCache = Object.fromEntries(+ document.cookie.split('; ').map(c => c.split('='))+ )+ }+ return cookieCache[name]+}+```++**Important (invalidate on external changes):**++If storage can change externally (another tab, server-set cookies), invalidate cache:++```typescript+window.addEventListener('storage', (e) => {+ if (e.key) storageCache.delete(e.key)+})++document.addEventListener('visibilitychange', () => {+ if (document.visibilityState === 'visible') {+ storageCache.clear()+ }+})+```diff --git a/.agents/skills/vercel-react-best-practices/rules/js-combine-iterations.md b/.agents/skills/vercel-react-best-practices/rules/js-combine-iterations.mdnew file mode 100644index 0000000..044d017--- /dev/null+++ b/.agents/skills/vercel-react-best-practices/rules/js-combine-iterations.md@@ -0,0 +1,32 @@+---+title: Combine Multiple Array Iterations+impact: LOW-MEDIUM+impactDescription: reduces iterations+tags: javascript, arrays, loops, performance+---++## Combine Multiple Array Iterations++Multiple `.filter()` or `.map()` calls iterate the array multiple times. Combine into one loop.++**Incorrect (3 iterations):**++```typescript+const admins = users.filter(u => u.isAdmin)+const testers = users.filter(u => u.isTester)+const inactive = users.filter(u => !u.isActive)+```++**Correct (1 iteration):**++```typescript+const admins: User[] = []+const testers: User[] = []+const inactive: User[] = []++for (const user of users) {+ if (user.isAdmin) admins.push(user)+ if (user.isTester) testers.push(user)+ if (!user.isActive) inactive.push(user)+}+```diff --git a/.agents/skills/vercel-react-best-practices/rules/js-early-exit.md b/.agents/skills/vercel-react-best-practices/rules/js-early-exit.mdnew file mode 100644index 0000000..f46cb89--- /dev/null+++ b/.agents/skills/vercel-react-best-practices/rules/js-early-exit.md@@ -0,0 +1,50 @@+---+title: Early Return from Functions+impact: LOW-MEDIUM+impactDescription: avoids unnecessary computation+tags: javascript, functions, optimization, early-return+---++## Early Return from Functions++Return early when result is determined to skip unnecessary processing.++**Incorrect (processes all items even after finding answer):**++```typescript+function validateUsers(users: User[]) {+ let hasError = false+ let errorMessage = ''++ for (const user of users) {+ if (!user.email) {+ hasError = true+ errorMessage = 'Email required'+ }+ if (!user.name) {+ hasError = true+ errorMessage = 'Name required'+ }+ // Continues checking all users even after error found+ }++ return hasError ? { valid: false, error: errorMessage } : { valid: true }+}+```++**Correct (returns immediately on first error):**++```typescript+function validateUsers(users: User[]) {+ for (const user of users) {+ if (!user.email) {+ return { valid: false, error: 'Email required' }+ }+ if (!user.name) {+ return { valid: false, error: 'Name required' }+ }+ }++ return { valid: true }+}+```diff --git a/.agents/skills/vercel-react-best-practices/rules/js-flatmap-filter.md b/.agents/skills/vercel-react-best-practices/rules/js-flatmap-filter.mdnew file mode 100644index 0000000..ee0edf0--- /dev/null+++ b/.agents/skills/vercel-react-best-practices/rules/js-flatmap-filter.md@@ -0,0 +1,60 @@+---+title: Use flatMap to Map and Filter in One Pass+impact: LOW-MEDIUM+impactDescription: eliminates intermediate array+tags: javascript, arrays, flatMap, filter, performance+---++## Use flatMap to Map and Filter in One Pass++**Impact: LOW-MEDIUM (eliminates intermediate array)**++Chaining `.map().filter(Boolean)` creates an intermediate array and iterates twice. Use `.flatMap()` to transform and filter in a single pass.++**Incorrect (2 iterations, intermediate array):**++```typescript+const userNames = users+ .map(user => user.isActive ? user.name : null)+ .filter(Boolean)+```++**Correct (1 iteration, no intermediate array):**++```typescript+const userNames = users.flatMap(user =>+ user.isActive ? [user.name] : []+)+```++**More examples:**++```typescript+// Extract valid emails from responses+// Before+const emails = responses+ .map(r => r.success ? r.data.email : null)+ .filter(Boolean)++// After+const emails = responses.flatMap(r =>+ r.success ? [r.data.email] : []+)++// Parse and filter valid numbers+// Before+const numbers = strings+ .map(s => parseInt(s, 10))+ .filter(n => !isNaN(n))++// After+const numbers = strings.flatMap(s => {+ const n = parseInt(s, 10)+ return isNaN(n) ? [] : [n]+})+```++**When to use:**+- Transforming items while filtering some out+- Conditional mapping where some inputs produce no output+- Parsing/validating where invalid inputs should be skippeddiff --git a/.agents/skills/vercel-react-best-practices/rules/js-hoist-regexp.md b/.agents/skills/vercel-react-best-practices/rules/js-hoist-regexp.mdnew file mode 100644index 0000000..dae3fef--- /dev/null+++ b/.agents/skills/vercel-react-best-practices/rules/js-hoist-regexp.md@@ -0,0 +1,45 @@+---+title: Hoist RegExp Creation+impact: LOW-MEDIUM+impactDescription: avoids recreation+tags: javascript, regexp, optimization, memoization+---++## Hoist RegExp Creation++Don't create RegExp inside render. Hoist to module scope or memoize with `useMemo()`.++**Incorrect (new RegExp every render):**++```tsx+function Highlighter({ text, query }: Props) {+ const regex = new RegExp(`(${query})`, 'gi')+ const parts = text.split(regex)+ return <>{parts.map((part, i) => ...)}</>+}+```++**Correct (memoize or hoist):**++```tsx+const EMAIL_REGEX = /^[^\s@]+@[^\s@]+\.[^\s@]+$/++function Highlighter({ text, query }: Props) {+ const regex = useMemo(+ () => new RegExp(`(${escapeRegex(query)})`, 'gi'),+ [query]+ )+ const parts = text.split(regex)+ return <>{parts.map((part, i) => ...)}</>+}+```++**Warning (global regex has mutable state):**++Global regex (`/g`) has mutable `lastIndex` state:++```typescript+const regex = /foo/g+regex.test('foo') // true, lastIndex = 3+regex.test('foo') // false, lastIndex = 0+```diff --git a/.agents/skills/vercel-react-best-practices/rules/js-index-maps.md b/.agents/skills/vercel-react-best-practices/rules/js-index-maps.mdnew file mode 100644index 0000000..9d357a0--- /dev/null+++ b/.agents/skills/vercel-react-best-practices/rules/js-index-maps.md@@ -0,0 +1,37 @@+---+title: Build Index Maps for Repeated Lookups+impact: LOW-MEDIUM+impactDescription: 1M ops to 2K ops+tags: javascript, map, indexing, optimization, performance+---++## Build Index Maps for Repeated Lookups++Multiple `.find()` calls by the same key should use a Map.++**Incorrect (O(n) per lookup):**++```typescript+function processOrders(orders: Order[], users: User[]) {+ return orders.map(order => ({+ ...order,+ user: users.find(u => u.id === order.userId)+ }))+}+```++**Correct (O(1) per lookup):**++```typescript+function processOrders(orders: Order[], users: User[]) {+ const userById = new Map(users.map(u => [u.id, u]))++ return orders.map(order => ({+ ...order,+ user: userById.get(order.userId)+ }))+}+```++Build map once (O(n)), then all lookups are O(1).+For 1000 orders × 1000 users: 1M ops → 2K ops.diff --git a/.agents/skills/vercel-react-best-practices/rules/js-length-check-first.md b/.agents/skills/vercel-react-best-practices/rules/js-length-check-first.mdnew file mode 100644index 0000000..8b89573--- /dev/null+++ b/.agents/skills/vercel-react-best-practices/rules/js-length-check-first.md@@ -0,0 +1,49 @@+---+title: Early Length Check for Array Comparisons+impact: MEDIUM-HIGH+impactDescription: avoids expensive operations when lengths differ+tags: javascript, arrays, performance, optimization, comparison+---++## Early Length Check for Array Comparisons++When comparing arrays with expensive operations (sorting, deep equality, serialization), check lengths first. If lengths differ, the arrays cannot be equal.++In real-world applications, this optimization is especially valuable when the comparison runs in hot paths (event handlers, render loops).++**Incorrect (always runs expensive comparison):**++```typescript+function hasChanges(current: string[], original: string[]) {+ // Always sorts and joins, even when lengths differ+ return current.sort().join() !== original.sort().join()+}+```++Two O(n log n) sorts run even when `current.length` is 5 and `original.length` is 100. There is also overhead of joining the arrays and comparing the strings.++**Correct (O(1) length check first):**++```typescript+function hasChanges(current: string[], original: string[]) {+ // Early return if lengths differ+ if (current.length !== original.length) {+ return true+ }+ // Only sort when lengths match+ const currentSorted = current.toSorted()+ const originalSorted = original.toSorted()+ for (let i = 0; i < currentSorted.length; i++) {+ if (currentSorted[i] !== originalSorted[i]) {+ return true+ }+ }+ return false+}+```++This new approach is more efficient because:+- It avoids the overhead of sorting and joining the arrays when lengths differ+- It avoids consuming memory for the joined strings (especially important for large arrays)+- It avoids mutating the original arrays+- It returns early when a difference is founddiff --git a/.agents/skills/vercel-react-best-practices/rules/js-min-max-loop.md b/.agents/skills/vercel-react-best-practices/rules/js-min-max-loop.mdnew file mode 100644index 0000000..4b6656e--- /dev/null+++ b/.agents/skills/vercel-react-best-practices/rules/js-min-max-loop.md@@ -0,0 +1,82 @@+---+title: Use Loop for Min/Max Instead of Sort+impact: LOW+impactDescription: O(n) instead of O(n log n)+tags: javascript, arrays, performance, sorting, algorithms+---++## Use Loop for Min/Max Instead of Sort++Finding the smallest or largest element only requires a single pass through the array. Sorting is wasteful and slower.++**Incorrect (O(n log n) - sort to find latest):**++```typescript+interface Project {+ id: string+ name: string+ updatedAt: number+}++function getLatestProject(projects: Project[]) {+ const sorted = [...projects].sort((a, b) => b.updatedAt - a.updatedAt)+ return sorted[0]+}+```++Sorts the entire array just to find the maximum value.++**Incorrect (O(n log n) - sort for oldest and newest):**++```typescript+function getOldestAndNewest(projects: Project[]) {+ const sorted = [...projects].sort((a, b) => a.updatedAt - b.updatedAt)+ return { oldest: sorted[0], newest: sorted[sorted.length - 1] }+}+```++Still sorts unnecessarily when only min/max are needed.++**Correct (O(n) - single loop):**++```typescript+function getLatestProject(projects: Project[]) {+ if (projects.length === 0) return null++ let latest = projects[0]++ for (let i = 1; i < projects.length; i++) {+ if (projects[i].updatedAt > latest.updatedAt) {+ latest = projects[i]+ }+ }++ return latest+}++function getOldestAndNewest(projects: Project[]) {+ if (projects.length === 0) return { oldest: null, newest: null }++ let oldest = projects[0]+ let newest = projects[0]++ for (let i = 1; i < projects.length; i++) {+ if (projects[i].updatedAt < oldest.updatedAt) oldest = projects[i]+ if (projects[i].updatedAt > newest.updatedAt) newest = projects[i]+ }++ return { oldest, newest }+}+```++Single pass through the array, no copying, no sorting.++**Alternative (Math.min/Math.max for small arrays):**++```typescript+const numbers = [5, 2, 8, 1, 9]+const min = Math.min(...numbers)+const max = Math.max(...numbers)+```++This works for small arrays, but can be slower or just throw an error for very large arrays due to spread operator limitations. Maximal array length is approximately 124000 in Chrome 143 and 638000 in Safari 18; exact numbers may vary - see [the fiddle](https://jsfiddle.net/qw1jabsx/4/). Use the loop approach for reliability.diff --git a/.agents/skills/vercel-react-best-practices/rules/js-request-idle-callback.md b/.agents/skills/vercel-react-best-practices/rules/js-request-idle-callback.mdnew file mode 100644index 0000000..d81927e--- /dev/null+++ b/.agents/skills/vercel-react-best-practices/rules/js-request-idle-callback.md@@ -0,0 +1,105 @@+---+title: Defer Non-Critical Work with requestIdleCallback+impact: MEDIUM+impactDescription: keeps UI responsive during background tasks+tags: javascript, performance, idle, scheduling, analytics+---++## Defer Non-Critical Work with requestIdleCallback++**Impact: MEDIUM (keeps UI responsive during background tasks)**++Use `requestIdleCallback()` to schedule non-critical work during browser idle periods. This keeps the main thread free for user interactions and animations, reducing jank and improving perceived performance.++**Incorrect (blocks main thread during user interaction):**++```typescript+function handleSearch(query: string) {+ const results = searchItems(query)+ setResults(results)++ // These block the main thread immediately+ analytics.track('search', { query })+ saveToRecentSearches(query)+ prefetchTopResults(results.slice(0, 3))+}+```++**Correct (defers non-critical work to idle time):**++```typescript+function handleSearch(query: string) {+ const results = searchItems(query)+ setResults(results)++ // Defer non-critical work to idle periods+ requestIdleCallback(() => {+ analytics.track('search', { query })+ })++ requestIdleCallback(() => {+ saveToRecentSearches(query)+ })++ requestIdleCallback(() => {+ prefetchTopResults(results.slice(0, 3))+ })+}+```++**With timeout for required work:**++```typescript+// Ensure analytics fires within 2 seconds even if browser stays busy+requestIdleCallback(+ () => analytics.track('page_view', { path: location.pathname }),+ { timeout: 2000 }+)+```++**Chunking large tasks:**++```typescript+function processLargeDataset(items: Item[]) {+ let index = 0++ function processChunk(deadline: IdleDeadline) {+ // Process items while we have idle time (aim for <50ms chunks)+ while (index < items.length && deadline.timeRemaining() > 0) {+ processItem(items[index])+ index+++ }++ // Schedule next chunk if more items remain+ if (index < items.length) {+ requestIdleCallback(processChunk)+ }+ }++ requestIdleCallback(processChunk)+}+```++**With fallback for unsupported browsers:**++```typescript+const scheduleIdleWork = window.requestIdleCallback ?? ((cb: () => void) => setTimeout(cb, 1))++scheduleIdleWork(() => {+ // Non-critical work+})+```++**When to use:**++- Analytics and telemetry+- Saving state to localStorage/IndexedDB+- Prefetching resources for likely next actions+- Processing non-urgent data transformations+- Lazy initialization of non-critical features++**When NOT to use:**++- User-initiated actions that need immediate feedback+- Rendering updates the user is waiting for+- Time-sensitive operationsdiff --git a/.agents/skills/vercel-react-best-practices/rules/js-set-map-lookups.md b/.agents/skills/vercel-react-best-practices/rules/js-set-map-lookups.mdnew file mode 100644index 0000000..680a489--- /dev/null+++ b/.agents/skills/vercel-react-best-practices/rules/js-set-map-lookups.md@@ -0,0 +1,24 @@+---+title: Use Set/Map for O(1) Lookups+impact: LOW-MEDIUM+impactDescription: O(n) to O(1)+tags: javascript, set, map, data-structures, performance+---++## Use Set/Map for O(1) Lookups++Convert arrays to Set/Map for repeated membership checks.++**Incorrect (O(n) per check):**++```typescript+const allowedIds = ['a', 'b', 'c', ...]+items.filter(item => allowedIds.includes(item.id))+```++**Correct (O(1) per check):**++```typescript+const allowedIds = new Set(['a', 'b', 'c', ...])+items.filter(item => allowedIds.has(item.id))+```diff --git a/.agents/skills/vercel-react-best-practices/rules/js-tosorted-immutable.md b/.agents/skills/vercel-react-best-practices/rules/js-tosorted-immutable.mdnew file mode 100644index 0000000..eae8b3f--- /dev/null+++ b/.agents/skills/vercel-react-best-practices/rules/js-tosorted-immutable.md@@ -0,0 +1,57 @@+---+title: Use toSorted() Instead of sort() for Immutability+impact: MEDIUM-HIGH+impactDescription: prevents mutation bugs in React state+tags: javascript, arrays, immutability, react, state, mutation+---++## Use toSorted() Instead of sort() for Immutability++`.sort()` mutates the array in place, which can cause bugs with React state and props. Use `.toSorted()` to create a new sorted array without mutation.++**Incorrect (mutates original array):**++```typescript+function UserList({ users }: { users: User[] }) {+ // Mutates the users prop array!+ const sorted = useMemo(+ () => users.sort((a, b) => a.name.localeCompare(b.name)),+ [users]+ )+ return <div>{sorted.map(renderUser)}</div>+}+```++**Correct (creates new array):**++```typescript+function UserList({ users }: { users: User[] }) {+ // Creates new sorted array, original unchanged+ const sorted = useMemo(+ () => users.toSorted((a, b) => a.name.localeCompare(b.name)),+ [users]+ )+ return <div>{sorted.map(renderUser)}</div>+}+```++**Why this matters in React:**++1. Props/state mutations break React's immutability model - React expects props and state to be treated as read-only+2. Causes stale closure bugs - Mutating arrays inside closures (callbacks, effects) can lead to unexpected behavior++**Browser support (fallback for older browsers):**++`.toSorted()` is available in all modern browsers (Chrome 110+, Safari 16+, Firefox 115+, Node.js 20+). For older environments, use spread operator:++```typescript+// Fallback for older browsers+const sorted = [...items].sort((a, b) => a.value - b.value)+```++**Other immutable array methods:**++- `.toSorted()` - immutable sort+- `.toReversed()` - immutable reverse+- `.toSpliced()` - immutable splice+- `.with()` - immutable element replacementdiff --git a/.agents/skills/vercel-react-best-practices/rules/rendering-activity.md b/.agents/skills/vercel-react-best-practices/rules/rendering-activity.mdnew file mode 100644index 0000000..c957a49--- /dev/null+++ b/.agents/skills/vercel-react-best-practices/rules/rendering-activity.md@@ -0,0 +1,26 @@+---+title: Use Activity Component for Show/Hide+impact: MEDIUM+impactDescription: preserves state/DOM+tags: rendering, activity, visibility, state-preservation+---++## Use Activity Component for Show/Hide++Use React's `<Activity>` to preserve state/DOM for expensive components that frequently toggle visibility.++**Usage:**++```tsx+import { Activity } from 'react'++function Dropdown({ isOpen }: Props) {+ return (+ <Activity mode={isOpen ? 'visible' : 'hidden'}>+ <ExpensiveMenu />+ </Activity>+ )+}+```++Avoids expensive re-renders and state loss.diff --git a/.agents/skills/vercel-react-best-practices/rules/rendering-animate-svg-wrapper.md b/.agents/skills/vercel-react-best-practices/rules/rendering-animate-svg-wrapper.mdnew file mode 100644index 0000000..646744c--- /dev/null+++ b/.agents/skills/vercel-react-best-practices/rules/rendering-animate-svg-wrapper.md@@ -0,0 +1,47 @@+---+title: Animate SVG Wrapper Instead of SVG Element+impact: LOW+impactDescription: enables hardware acceleration+tags: rendering, svg, css, animation, performance+---++## Animate SVG Wrapper Instead of SVG Element++Many browsers don't have hardware acceleration for CSS3 animations on SVG elements. Wrap SVG in a `<div>` and animate the wrapper instead.++**Incorrect (animating SVG directly - no hardware acceleration):**++```tsx+function LoadingSpinner() {+ return (+ <svg+ className="animate-spin"+ width="24"+ height="24"+ viewBox="0 0 24 24"+ >+ <circle cx="12" cy="12" r="10" stroke="currentColor" />+ </svg>+ )+}+```++**Correct (animating wrapper div - hardware accelerated):**++```tsx+function LoadingSpinner() {+ return (+ <div className="animate-spin">+ <svg+ width="24"+ height="24"+ viewBox="0 0 24 24"+ >+ <circle cx="12" cy="12" r="10" stroke="currentColor" />+ </svg>+ </div>+ )+}+```++This applies to all CSS transforms and transitions (`transform`, `opacity`, `translate`, `scale`, `rotate`). The wrapper div allows browsers to use GPU acceleration for smoother animations.diff --git a/.agents/skills/vercel-react-best-practices/rules/rendering-conditional-render.md b/.agents/skills/vercel-react-best-practices/rules/rendering-conditional-render.mdnew file mode 100644index 0000000..7e866f5--- /dev/null+++ b/.agents/skills/vercel-react-best-practices/rules/rendering-conditional-render.md@@ -0,0 +1,40 @@+---+title: Use Explicit Conditional Rendering+impact: LOW+impactDescription: prevents rendering 0 or NaN+tags: rendering, conditional, jsx, falsy-values+---++## Use Explicit Conditional Rendering++Use explicit ternary operators (`? :`) instead of `&&` for conditional rendering when the condition can be `0`, `NaN`, or other falsy values that render.++**Incorrect (renders "0" when count is 0):**++```tsx+function Badge({ count }: { count: number }) {+ return (+ <div>+ {count && <span className="badge">{count}</span>}+ </div>+ )+}++// When count = 0, renders: <div>0</div>+// When count = 5, renders: <div><span class="badge">5</span></div>+```++**Correct (renders nothing when count is 0):**++```tsx+function Badge({ count }: { count: number }) {+ return (+ <div>+ {count > 0 ? <span className="badge">{count}</span> : null}+ </div>+ )+}++// When count = 0, renders: <div></div>+// When count = 5, renders: <div><span class="badge">5</span></div>+```diff --git a/.agents/skills/vercel-react-best-practices/rules/rendering-content-visibility.md b/.agents/skills/vercel-react-best-practices/rules/rendering-content-visibility.mdnew file mode 100644index 0000000..aa66563--- /dev/null+++ b/.agents/skills/vercel-react-best-practices/rules/rendering-content-visibility.md@@ -0,0 +1,38 @@+---+title: CSS content-visibility for Long Lists+impact: HIGH+impactDescription: faster initial render+tags: rendering, css, content-visibility, long-lists+---++## CSS content-visibility for Long Lists++Apply `content-visibility: auto` to defer off-screen rendering.++**CSS:**++```css+.message-item {+ content-visibility: auto;+ contain-intrinsic-size: 0 80px;+}+```++**Example:**++```tsx+function MessageList({ messages }: { messages: Message[] }) {+ return (+ <div className="overflow-y-auto h-screen">+ {messages.map(msg => (+ <div key={msg.id} className="message-item">+ <Avatar user={msg.author} />+ <div>{msg.content}</div>+ </div>+ ))}+ </div>+ )+}+```++For 1000 messages, browser skips layout/paint for ~990 off-screen items (10× faster initial render).diff --git a/.agents/skills/vercel-react-best-practices/rules/rendering-hoist-jsx.md b/.agents/skills/vercel-react-best-practices/rules/rendering-hoist-jsx.mdnew file mode 100644index 0000000..32d2f3f--- /dev/null+++ b/.agents/skills/vercel-react-best-practices/rules/rendering-hoist-jsx.md@@ -0,0 +1,46 @@+---+title: Hoist Static JSX Elements+impact: LOW+impactDescription: avoids re-creation+tags: rendering, jsx, static, optimization+---++## Hoist Static JSX Elements++Extract static JSX outside components to avoid re-creation.++**Incorrect (recreates element every render):**++```tsx+function LoadingSkeleton() {+ return <div className="animate-pulse h-20 bg-gray-200" />+}++function Container() {+ return (+ <div>+ {loading && <LoadingSkeleton />}+ </div>+ )+}+```++**Correct (reuses same element):**++```tsx+const loadingSkeleton = (+ <div className="animate-pulse h-20 bg-gray-200" />+)++function Container() {+ return (+ <div>+ {loading && loadingSkeleton}+ </div>+ )+}+```++This is especially helpful for large and static SVG nodes, which can be expensive to recreate on every render.++**Note:** If your project has [React Compiler](https://react.dev/learn/react-compiler) enabled, the compiler automatically hoists static JSX elements and optimizes component re-renders, making manual hoisting unnecessary.diff --git a/.agents/skills/vercel-react-best-practices/rules/rendering-hydration-no-flicker.md b/.agents/skills/vercel-react-best-practices/rules/rendering-hydration-no-flicker.mdnew file mode 100644index 0000000..5cf0e79--- /dev/null+++ b/.agents/skills/vercel-react-best-practices/rules/rendering-hydration-no-flicker.md@@ -0,0 +1,82 @@+---+title: Prevent Hydration Mismatch Without Flickering+impact: MEDIUM+impactDescription: avoids visual flicker and hydration errors+tags: rendering, ssr, hydration, localStorage, flicker+---++## Prevent Hydration Mismatch Without Flickering++When rendering content that depends on client-side storage (localStorage, cookies), avoid both SSR breakage and post-hydration flickering by injecting a synchronous script that updates the DOM before React hydrates.++**Incorrect (breaks SSR):**++```tsx+function ThemeWrapper({ children }: { children: ReactNode }) {+ // localStorage is not available on server - throws error+ const theme = localStorage.getItem('theme') || 'light'++ return (+ <div className={theme}>+ {children}+ </div>+ )+}+```++Server-side rendering will fail because `localStorage` is undefined.++**Incorrect (visual flickering):**++```tsx+function ThemeWrapper({ children }: { children: ReactNode }) {+ const [theme, setTheme] = useState('light')++ useEffect(() => {+ // Runs after hydration - causes visible flash+ const stored = localStorage.getItem('theme')+ if (stored) {+ setTheme(stored)+ }+ }, [])++ return (+ <div className={theme}>+ {children}+ </div>+ )+}+```++Component first renders with default value (`light`), then updates after hydration, causing a visible flash of incorrect content.++**Correct (no flicker, no hydration mismatch):**++```tsx+function ThemeWrapper({ children }: { children: ReactNode }) {+ return (+ <>+ <div id="theme-wrapper">+ {children}+ </div>+ <script+ dangerouslySetInnerHTML={{+ __html: `+ (function() {+ try {+ var theme = localStorage.getItem('theme') || 'light';+ var el = document.getElementById('theme-wrapper');+ if (el) el.className = theme;+ } catch (e) {}+ })();+ `,+ }}+ />+ </>+ )+}+```++The inline script executes synchronously before showing the element, ensuring the DOM already has the correct value. No flickering, no hydration mismatch.++This pattern is especially useful for theme toggles, user preferences, authentication states, and any client-only data that should render immediately without flashing default values.diff --git a/.agents/skills/vercel-react-best-practices/rules/rendering-hydration-suppress-warning.md b/.agents/skills/vercel-react-best-practices/rules/rendering-hydration-suppress-warning.mdnew file mode 100644index 0000000..24ba251--- /dev/null+++ b/.agents/skills/vercel-react-best-practices/rules/rendering-hydration-suppress-warning.md@@ -0,0 +1,30 @@+---+title: Suppress Expected Hydration Mismatches+impact: LOW-MEDIUM+impactDescription: avoids noisy hydration warnings for known differences+tags: rendering, hydration, ssr, nextjs+---++## Suppress Expected Hydration Mismatches++In SSR frameworks (e.g., Next.js), some values are intentionally different on server vs client (random IDs, dates, locale/timezone formatting). For these *expected* mismatches, wrap the dynamic text in an element with `suppressHydrationWarning` to prevent noisy warnings. Do not use this to hide real bugs. Don’t overuse it.++**Incorrect (known mismatch warnings):**++```tsx+function Timestamp() {+ return <span>{new Date().toLocaleString()}</span>+}+```++**Correct (suppress expected mismatch only):**++```tsx+function Timestamp() {+ return (+ <span suppressHydrationWarning>+ {new Date().toLocaleString()}+ </span>+ )+}+```diff --git a/.agents/skills/vercel-react-best-practices/rules/rendering-resource-hints.md b/.agents/skills/vercel-react-best-practices/rules/rendering-resource-hints.mdnew file mode 100644index 0000000..1290bef--- /dev/null+++ b/.agents/skills/vercel-react-best-practices/rules/rendering-resource-hints.md@@ -0,0 +1,85 @@+---+title: Use React DOM Resource Hints+impact: HIGH+impactDescription: reduces load time for critical resources+tags: rendering, preload, preconnect, prefetch, resource-hints+---++## Use React DOM Resource Hints++**Impact: HIGH (reduces load time for critical resources)**++React DOM provides APIs to hint the browser about resources it will need. These are especially useful in server components to start loading resources before the client even receives the HTML.++- **`prefetchDNS(href)`**: Resolve DNS for a domain you expect to connect to+- **`preconnect(href)`**: Establish connection (DNS + TCP + TLS) to a server+- **`preload(href, options)`**: Fetch a resource (stylesheet, font, script, image) you'll use soon+- **`preloadModule(href)`**: Fetch an ES module you'll use soon+- **`preinit(href, options)`**: Fetch and evaluate a stylesheet or script+- **`preinitModule(href)`**: Fetch and evaluate an ES module++**Example (preconnect to third-party APIs):**++```tsx+import { preconnect, prefetchDNS } from 'react-dom'++export default function App() {+ prefetchDNS('https://analytics.example.com')+ preconnect('https://api.example.com')++ return <main>{/* content */}</main>+}+```++**Example (preload critical fonts and styles):**++```tsx+import { preload, preinit } from 'react-dom'++export default function RootLayout({ children }) {+ // Preload font file+ preload('/fonts/inter.woff2', { as: 'font', type: 'font/woff2', crossOrigin: 'anonymous' })++ // Fetch and apply critical stylesheet immediately+ preinit('/styles/critical.css', { as: 'style' })++ return (+ <html>+ <body>{children}</body>+ </html>+ )+}+```++**Example (preload modules for code-split routes):**++```tsx+import { preloadModule, preinitModule } from 'react-dom'++function Navigation() {+ const preloadDashboard = () => {+ preloadModule('/dashboard.js', { as: 'script' })+ }++ return (+ <nav>+ <a href="/dashboard" onMouseEnter={preloadDashboard}>+ Dashboard+ </a>+ </nav>+ )+}+```++**When to use each:**++| API | Use case |+|-----|----------|+| `prefetchDNS` | Third-party domains you'll connect to later |+| `preconnect` | APIs or CDNs you'll fetch from immediately |+| `preload` | Critical resources needed for current page |+| `preloadModule` | JS modules for likely next navigation |+| `preinit` | Stylesheets/scripts that must execute early |+| `preinitModule` | ES modules that must execute early |++Reference: [React DOM Resource Preloading APIs](https://react.dev/reference/react-dom#resource-preloading-apis)diff --git a/.agents/skills/vercel-react-best-practices/rules/rendering-script-defer-async.md b/.agents/skills/vercel-react-best-practices/rules/rendering-script-defer-async.mdnew file mode 100644index 0000000..ee275ed--- /dev/null+++ b/.agents/skills/vercel-react-best-practices/rules/rendering-script-defer-async.md@@ -0,0 +1,68 @@+---+title: Use defer or async on Script Tags+impact: HIGH+impactDescription: eliminates render-blocking+tags: rendering, script, defer, async, performance+---++## Use defer or async on Script Tags++**Impact: HIGH (eliminates render-blocking)**++Script tags without `defer` or `async` block HTML parsing while the script downloads and executes. This delays First Contentful Paint and Time to Interactive.++- **`defer`**: Downloads in parallel, executes after HTML parsing completes, maintains execution order+- **`async`**: Downloads in parallel, executes immediately when ready, no guaranteed order++Use `defer` for scripts that depend on DOM or other scripts. Use `async` for independent scripts like analytics.++**Incorrect (blocks rendering):**++```tsx+export default function Document() {+ return (+ <html>+ <head>+ <script src="https://example.com/analytics.js" />+ <script src="/scripts/utils.js" />+ </head>+ <body>{/* content */}</body>+ </html>+ )+}+```++**Correct (non-blocking):**++```tsx+export default function Document() {+ return (+ <html>+ <head>+ {/* Independent script - use async */}+ <script src="https://example.com/analytics.js" async />+ {/* DOM-dependent script - use defer */}+ <script src="/scripts/utils.js" defer />+ </head>+ <body>{/* content */}</body>+ </html>+ )+}+```++**Note:** In Next.js, prefer the `next/script` component with `strategy` prop instead of raw script tags:++```tsx+import Script from 'next/script'++export default function Page() {+ return (+ <>+ <Script src="https://example.com/analytics.js" strategy="afterInteractive" />+ <Script src="/scripts/utils.js" strategy="beforeInteractive" />+ </>+ )+}+```++Reference: [MDN - Script element](https://developer.mozilla.org/en-US/docs/Web/HTML/Element/script#defer)diff --git a/.agents/skills/vercel-react-best-practices/rules/rendering-svg-precision.md b/.agents/skills/vercel-react-best-practices/rules/rendering-svg-precision.mdnew file mode 100644index 0000000..6d77128--- /dev/null+++ b/.agents/skills/vercel-react-best-practices/rules/rendering-svg-precision.md@@ -0,0 +1,28 @@+---+title: Optimize SVG Precision+impact: LOW+impactDescription: reduces file size+tags: rendering, svg, optimization, svgo+---++## Optimize SVG Precision++Reduce SVG coordinate precision to decrease file size. The optimal precision depends on the viewBox size, but in general reducing precision should be considered.++**Incorrect (excessive precision):**++```svg+<path d="M 10.293847 20.847362 L 30.938472 40.192837" />+```++**Correct (1 decimal place):**++```svg+<path d="M 10.3 20.8 L 30.9 40.2" />+```++**Automate with SVGO:**++```bash+npx svgo --precision=1 --multipass icon.svg+```diff --git a/.agents/skills/vercel-react-best-practices/rules/rendering-usetransition-loading.md b/.agents/skills/vercel-react-best-practices/rules/rendering-usetransition-loading.mdnew file mode 100644index 0000000..0c1b0b9--- /dev/null+++ b/.agents/skills/vercel-react-best-practices/rules/rendering-usetransition-loading.md@@ -0,0 +1,75 @@+---+title: Use useTransition Over Manual Loading States+impact: LOW+impactDescription: reduces re-renders and improves code clarity+tags: rendering, transitions, useTransition, loading, state+---++## Use useTransition Over Manual Loading States++Use `useTransition` instead of manual `useState` for loading states. This provides built-in `isPending` state and automatically manages transitions.++**Incorrect (manual loading state):**++```tsx+function SearchResults() {+ const [query, setQuery] = useState('')+ const [results, setResults] = useState([])+ const [isLoading, setIsLoading] = useState(false)++ const handleSearch = async (value: string) => {+ setIsLoading(true)+ setQuery(value)+ const data = await fetchResults(value)+ setResults(data)+ setIsLoading(false)+ }++ return (+ <>+ <input onChange={(e) => handleSearch(e.target.value)} />+ {isLoading && <Spinner />}+ <ResultsList results={results} />+ </>+ )+}+```++**Correct (useTransition with built-in pending state):**++```tsx+import { useTransition, useState } from 'react'++function SearchResults() {+ const [query, setQuery] = useState('')+ const [results, setResults] = useState([])+ const [isPending, startTransition] = useTransition()++ const handleSearch = (value: string) => {+ setQuery(value) // Update input immediately++ startTransition(async () => {+ // Fetch and update results+ const data = await fetchResults(value)+ setResults(data)+ })+ }++ return (+ <>+ <input onChange={(e) => handleSearch(e.target.value)} />+ {isPending && <Spinner />}+ <ResultsList results={results} />+ </>+ )+}+```++**Benefits:**++- **Automatic pending state**: No need to manually manage `setIsLoading(true/false)`+- **Error resilience**: Pending state correctly resets even if the transition throws+- **Better responsiveness**: Keeps the UI responsive during updates+- **Interrupt handling**: New transitions automatically cancel pending ones++Reference: [useTransition](https://react.dev/reference/react/useTransition)diff --git a/.agents/skills/vercel-react-best-practices/rules/rerender-defer-reads.md b/.agents/skills/vercel-react-best-practices/rules/rerender-defer-reads.mdnew file mode 100644index 0000000..e867c95--- /dev/null+++ b/.agents/skills/vercel-react-best-practices/rules/rerender-defer-reads.md@@ -0,0 +1,39 @@+---+title: Defer State Reads to Usage Point+impact: MEDIUM+impactDescription: avoids unnecessary subscriptions+tags: rerender, searchParams, localStorage, optimization+---++## Defer State Reads to Usage Point++Don't subscribe to dynamic state (searchParams, localStorage) if you only read it inside callbacks.++**Incorrect (subscribes to all searchParams changes):**++```tsx+function ShareButton({ chatId }: { chatId: string }) {+ const searchParams = useSearchParams()++ const handleShare = () => {+ const ref = searchParams.get('ref')+ shareChat(chatId, { ref })+ }++ return <button onClick={handleShare}>Share</button>+}+```++**Correct (reads on demand, no subscription):**++```tsx+function ShareButton({ chatId }: { chatId: string }) {+ const handleShare = () => {+ const params = new URLSearchParams(window.location.search)+ const ref = params.get('ref')+ shareChat(chatId, { ref })+ }++ return <button onClick={handleShare}>Share</button>+}+```diff --git a/.agents/skills/vercel-react-best-practices/rules/rerender-dependencies.md b/.agents/skills/vercel-react-best-practices/rules/rerender-dependencies.mdnew file mode 100644index 0000000..47a4d92--- /dev/null+++ b/.agents/skills/vercel-react-best-practices/rules/rerender-dependencies.md@@ -0,0 +1,45 @@+---+title: Narrow Effect Dependencies+impact: LOW+impactDescription: minimizes effect re-runs+tags: rerender, useEffect, dependencies, optimization+---++## Narrow Effect Dependencies++Specify primitive dependencies instead of objects to minimize effect re-runs.++**Incorrect (re-runs on any user field change):**++```tsx+useEffect(() => {+ console.log(user.id)+}, [user])+```++**Correct (re-runs only when id changes):**++```tsx+useEffect(() => {+ console.log(user.id)+}, [user.id])+```++**For derived state, compute outside effect:**++```tsx+// Incorrect: runs on width=767, 766, 765...+useEffect(() => {+ if (width < 768) {+ enableMobileMode()+ }+}, [width])++// Correct: runs only on boolean transition+const isMobile = width < 768+useEffect(() => {+ if (isMobile) {+ enableMobileMode()+ }+}, [isMobile])+```diff --git a/.agents/skills/vercel-react-best-practices/rules/rerender-derived-state-no-effect.md b/.agents/skills/vercel-react-best-practices/rules/rerender-derived-state-no-effect.mdnew file mode 100644index 0000000..3d9fe40--- /dev/null+++ b/.agents/skills/vercel-react-best-practices/rules/rerender-derived-state-no-effect.md@@ -0,0 +1,40 @@+---+title: Calculate Derived State During Rendering+impact: MEDIUM+impactDescription: avoids redundant renders and state drift+tags: rerender, derived-state, useEffect, state+---++## Calculate Derived State During Rendering++If a value can be computed from current props/state, do not store it in state or update it in an effect. Derive it during render to avoid extra renders and state drift. Do not set state in effects solely in response to prop changes; prefer derived values or keyed resets instead.++**Incorrect (redundant state and effect):**++```tsx+function Form() {+ const [firstName, setFirstName] = useState('First')+ const [lastName, setLastName] = useState('Last')+ const [fullName, setFullName] = useState('')++ useEffect(() => {+ setFullName(firstName + ' ' + lastName)+ }, [firstName, lastName])++ return <p>{fullName}</p>+}+```++**Correct (derive during render):**++```tsx+function Form() {+ const [firstName, setFirstName] = useState('First')+ const [lastName, setLastName] = useState('Last')+ const fullName = firstName + ' ' + lastName++ return <p>{fullName}</p>+}+```++References: [You Might Not Need an Effect](https://react.dev/learn/you-might-not-need-an-effect)diff --git a/.agents/skills/vercel-react-best-practices/rules/rerender-derived-state.md b/.agents/skills/vercel-react-best-practices/rules/rerender-derived-state.mdnew file mode 100644index 0000000..e5c899f--- /dev/null+++ b/.agents/skills/vercel-react-best-practices/rules/rerender-derived-state.md@@ -0,0 +1,29 @@+---+title: Subscribe to Derived State+impact: MEDIUM+impactDescription: reduces re-render frequency+tags: rerender, derived-state, media-query, optimization+---++## Subscribe to Derived State++Subscribe to derived boolean state instead of continuous values to reduce re-render frequency.++**Incorrect (re-renders on every pixel change):**++```tsx+function Sidebar() {+ const width = useWindowWidth() // updates continuously+ const isMobile = width < 768+ return <nav className={isMobile ? 'mobile' : 'desktop'} />+}+```++**Correct (re-renders only when boolean changes):**++```tsx+function Sidebar() {+ const isMobile = useMediaQuery('(max-width: 767px)')+ return <nav className={isMobile ? 'mobile' : 'desktop'} />+}+```diff --git a/.agents/skills/vercel-react-best-practices/rules/rerender-functional-setstate.md b/.agents/skills/vercel-react-best-practices/rules/rerender-functional-setstate.mdnew file mode 100644index 0000000..b004ef4--- /dev/null+++ b/.agents/skills/vercel-react-best-practices/rules/rerender-functional-setstate.md@@ -0,0 +1,74 @@+---+title: Use Functional setState Updates+impact: MEDIUM+impactDescription: prevents stale closures and unnecessary callback recreations+tags: react, hooks, useState, useCallback, callbacks, closures+---++## Use Functional setState Updates++When updating state based on the current state value, use the functional update form of setState instead of directly referencing the state variable. This prevents stale closures, eliminates unnecessary dependencies, and creates stable callback references.++**Incorrect (requires state as dependency):**++```tsx+function TodoList() {+ const [items, setItems] = useState(initialItems)++ // Callback must depend on items, recreated on every items change+ const addItems = useCallback((newItems: Item[]) => {+ setItems([...items, ...newItems])+ }, [items]) // ❌ items dependency causes recreations++ // Risk of stale closure if dependency is forgotten+ const removeItem = useCallback((id: string) => {+ setItems(items.filter(item => item.id !== id))+ }, []) // ❌ Missing items dependency - will use stale items!++ return <ItemsEditor items={items} onAdd={addItems} onRemove={removeItem} />+}+```++The first callback is recreated every time `items` changes, which can cause child components to re-render unnecessarily. The second callback has a stale closure bug—it will always reference the initial `items` value.++**Correct (stable callbacks, no stale closures):**++```tsx+function TodoList() {+ const [items, setItems] = useState(initialItems)++ // Stable callback, never recreated+ const addItems = useCallback((newItems: Item[]) => {+ setItems(curr => [...curr, ...newItems])+ }, []) // ✅ No dependencies needed++ // Always uses latest state, no stale closure risk+ const removeItem = useCallback((id: string) => {+ setItems(curr => curr.filter(item => item.id !== id))+ }, []) // ✅ Safe and stable++ return <ItemsEditor items={items} onAdd={addItems} onRemove={removeItem} />+}+```++**Benefits:**++1. **Stable callback references** - Callbacks don't need to be recreated when state changes+2. **No stale closures** - Always operates on the latest state value+3. **Fewer dependencies** - Simplifies dependency arrays and reduces memory leaks+4. **Prevents bugs** - Eliminates the most common source of React closure bugs++**When to use functional updates:**++- Any setState that depends on the current state value+- Inside useCallback/useMemo when state is needed+- Event handlers that reference state+- Async operations that update state++**When direct updates are fine:**++- Setting state to a static value: `setCount(0)`+- Setting state from props/arguments only: `setName(newName)`+- State doesn't depend on previous value++**Note:** If your project has [React Compiler](https://react.dev/learn/react-compiler) enabled, the compiler can automatically optimize some cases, but functional updates are still recommended for correctness and to prevent stale closure bugs.diff --git a/.agents/skills/vercel-react-best-practices/rules/rerender-lazy-state-init.md b/.agents/skills/vercel-react-best-practices/rules/rerender-lazy-state-init.mdnew file mode 100644index 0000000..4ecb350--- /dev/null+++ b/.agents/skills/vercel-react-best-practices/rules/rerender-lazy-state-init.md@@ -0,0 +1,58 @@+---+title: Use Lazy State Initialization+impact: MEDIUM+impactDescription: wasted computation on every render+tags: react, hooks, useState, performance, initialization+---++## Use Lazy State Initialization++Pass a function to `useState` for expensive initial values. Without the function form, the initializer runs on every render even though the value is only used once.++**Incorrect (runs on every render):**++```tsx+function FilteredList({ items }: { items: Item[] }) {+ // buildSearchIndex() runs on EVERY render, even after initialization+ const [searchIndex, setSearchIndex] = useState(buildSearchIndex(items))+ const [query, setQuery] = useState('')++ // When query changes, buildSearchIndex runs again unnecessarily+ return <SearchResults index={searchIndex} query={query} />+}++function UserProfile() {+ // JSON.parse runs on every render+ const [settings, setSettings] = useState(+ JSON.parse(localStorage.getItem('settings') || '{}')+ )++ return <SettingsForm settings={settings} onChange={setSettings} />+}+```++**Correct (runs only once):**++```tsx+function FilteredList({ items }: { items: Item[] }) {+ // buildSearchIndex() runs ONLY on initial render+ const [searchIndex, setSearchIndex] = useState(() => buildSearchIndex(items))+ const [query, setQuery] = useState('')++ return <SearchResults index={searchIndex} query={query} />+}++function UserProfile() {+ // JSON.parse runs only on initial render+ const [settings, setSettings] = useState(() => {+ const stored = localStorage.getItem('settings')+ return stored ? JSON.parse(stored) : {}+ })++ return <SettingsForm settings={settings} onChange={setSettings} />+}+```++Use lazy initialization when computing initial values from localStorage/sessionStorage, building data structures (indexes, maps), reading from the DOM, or performing heavy transformations.++For simple primitives (`useState(0)`), direct references (`useState(props.value)`), or cheap literals (`useState({})`), the function form is unnecessary.diff --git a/.agents/skills/vercel-react-best-practices/rules/rerender-memo-with-default-value.md b/.agents/skills/vercel-react-best-practices/rules/rerender-memo-with-default-value.mdnew file mode 100644index 0000000..6357049--- /dev/null+++ b/.agents/skills/vercel-react-best-practices/rules/rerender-memo-with-default-value.md@@ -0,0 +1,38 @@+---++title: Extract Default Non-primitive Parameter Value from Memoized Component to Constant+impact: MEDIUM+impactDescription: restores memoization by using a constant for default value+tags: rerender, memo, optimization++---++## Extract Default Non-primitive Parameter Value from Memoized Component to Constant++When memoized component has a default value for some non-primitive optional parameter, such as an array, function, or object, calling the component without that parameter results in broken memoization. This is because new value instances are created on every rerender, and they do not pass strict equality comparison in `memo()`.++To address this issue, extract the default value into a constant.++**Incorrect (`onClick` has different values on every rerender):**++```tsx+const UserAvatar = memo(function UserAvatar({ onClick = () => {} }: { onClick?: () => void }) {+ // ...+})++// Used without optional onClick+<UserAvatar />+```++**Correct (stable default value):**++```tsx+const NOOP = () => {};++const UserAvatar = memo(function UserAvatar({ onClick = NOOP }: { onClick?: () => void }) {+ // ...+})++// Used without optional onClick+<UserAvatar />+```diff --git a/.agents/skills/vercel-react-best-practices/rules/rerender-memo.md b/.agents/skills/vercel-react-best-practices/rules/rerender-memo.mdnew file mode 100644index 0000000..f8982ab--- /dev/null+++ b/.agents/skills/vercel-react-best-practices/rules/rerender-memo.md@@ -0,0 +1,44 @@+---+title: Extract to Memoized Components+impact: MEDIUM+impactDescription: enables early returns+tags: rerender, memo, useMemo, optimization+---++## Extract to Memoized Components++Extract expensive work into memoized components to enable early returns before computation.++**Incorrect (computes avatar even when loading):**++```tsx+function Profile({ user, loading }: Props) {+ const avatar = useMemo(() => {+ const id = computeAvatarId(user)+ return <Avatar id={id} />+ }, [user])++ if (loading) return <Skeleton />+ return <div>{avatar}</div>+}+```++**Correct (skips computation when loading):**++```tsx+const UserAvatar = memo(function UserAvatar({ user }: { user: User }) {+ const id = useMemo(() => computeAvatarId(user), [user])+ return <Avatar id={id} />+})++function Profile({ user, loading }: Props) {+ if (loading) return <Skeleton />+ return (+ <div>+ <UserAvatar user={user} />+ </div>+ )+}+```++**Note:** If your project has [React Compiler](https://react.dev/learn/react-compiler) enabled, manual memoization with `memo()` and `useMemo()` is not necessary. The compiler automatically optimizes re-renders.diff --git a/.agents/skills/vercel-react-best-practices/rules/rerender-move-effect-to-event.md b/.agents/skills/vercel-react-best-practices/rules/rerender-move-effect-to-event.mdnew file mode 100644index 0000000..dd58a1a--- /dev/null+++ b/.agents/skills/vercel-react-best-practices/rules/rerender-move-effect-to-event.md@@ -0,0 +1,45 @@+---+title: Put Interaction Logic in Event Handlers+impact: MEDIUM+impactDescription: avoids effect re-runs and duplicate side effects+tags: rerender, useEffect, events, side-effects, dependencies+---++## Put Interaction Logic in Event Handlers++If a side effect is triggered by a specific user action (submit, click, drag), run it in that event handler. Do not model the action as state + effect; it makes effects re-run on unrelated changes and can duplicate the action.++**Incorrect (event modeled as state + effect):**++```tsx+function Form() {+ const [submitted, setSubmitted] = useState(false)+ const theme = useContext(ThemeContext)++ useEffect(() => {+ if (submitted) {+ post('/api/register')+ showToast('Registered', theme)+ }+ }, [submitted, theme])++ return <button onClick={() => setSubmitted(true)}>Submit</button>+}+```++**Correct (do it in the handler):**++```tsx+function Form() {+ const theme = useContext(ThemeContext)++ function handleSubmit() {+ post('/api/register')+ showToast('Registered', theme)+ }++ return <button onClick={handleSubmit}>Submit</button>+}+```++Reference: [Should this code move to an event handler?](https://react.dev/learn/removing-effect-dependencies#should-this-code-move-to-an-event-handler)diff --git a/.agents/skills/vercel-react-best-practices/rules/rerender-no-inline-components.md b/.agents/skills/vercel-react-best-practices/rules/rerender-no-inline-components.mdnew file mode 100644index 0000000..d97592a--- /dev/null+++ b/.agents/skills/vercel-react-best-practices/rules/rerender-no-inline-components.md@@ -0,0 +1,82 @@+---+title: Don't Define Components Inside Components+impact: HIGH+impactDescription: prevents remount on every render+tags: rerender, components, remount, performance+---++## Don't Define Components Inside Components++**Impact: HIGH (prevents remount on every render)**++Defining a component inside another component creates a new component type on every render. React sees a different component each time and fully remounts it, destroying all state and DOM.++A common reason developers do this is to access parent variables without passing props. Always pass props instead.++**Incorrect (remounts on every render):**++```tsx+function UserProfile({ user, theme }) {+ // Defined inside to access `theme` - BAD+ const Avatar = () => (+ <img+ src={user.avatarUrl}+ className={theme === 'dark' ? 'avatar-dark' : 'avatar-light'}+ />+ )++ // Defined inside to access `user` - BAD+ const Stats = () => (+ <div>+ <span>{user.followers} followers</span>+ <span>{user.posts} posts</span>+ </div>+ )++ return (+ <div>+ <Avatar />+ <Stats />+ </div>+ )+}+```++Every time `UserProfile` renders, `Avatar` and `Stats` are new component types. React unmounts the old instances and mounts new ones, losing any internal state, running effects again, and recreating DOM nodes.++**Correct (pass props instead):**++```tsx+function Avatar({ src, theme }: { src: string; theme: string }) {+ return (+ <img+ src={src}+ className={theme === 'dark' ? 'avatar-dark' : 'avatar-light'}+ />+ )+}++function Stats({ followers, posts }: { followers: number; posts: number }) {+ return (+ <div>+ <span>{followers} followers</span>+ <span>{posts} posts</span>+ </div>+ )+}++function UserProfile({ user, theme }) {+ return (+ <div>+ <Avatar src={user.avatarUrl} theme={theme} />+ <Stats followers={user.followers} posts={user.posts} />+ </div>+ )+}+```++**Symptoms of this bug:**+- Input fields lose focus on every keystroke+- Animations restart unexpectedly+- `useEffect` cleanup/setup runs on every parent render+- Scroll position resets inside the componentdiff --git a/.agents/skills/vercel-react-best-practices/rules/rerender-simple-expression-in-memo.md b/.agents/skills/vercel-react-best-practices/rules/rerender-simple-expression-in-memo.mdnew file mode 100644index 0000000..59dfab0--- /dev/null+++ b/.agents/skills/vercel-react-best-practices/rules/rerender-simple-expression-in-memo.md@@ -0,0 +1,35 @@+---+title: Do not wrap a simple expression with a primitive result type in useMemo+impact: LOW-MEDIUM+impactDescription: wasted computation on every render+tags: rerender, useMemo, optimization+---++## Do not wrap a simple expression with a primitive result type in useMemo++When an expression is simple (few logical or arithmetical operators) and has a primitive result type (boolean, number, string), do not wrap it in `useMemo`.+Calling `useMemo` and comparing hook dependencies may consume more resources than the expression itself.++**Incorrect:**++```tsx+function Header({ user, notifications }: Props) {+ const isLoading = useMemo(() => {+ return user.isLoading || notifications.isLoading+ }, [user.isLoading, notifications.isLoading])++ if (isLoading) return <Skeleton />+ // return some markup+}+```++**Correct:**++```tsx+function Header({ user, notifications }: Props) {+ const isLoading = user.isLoading || notifications.isLoading++ if (isLoading) return <Skeleton />+ // return some markup+}+```diff --git a/.agents/skills/vercel-react-best-practices/rules/rerender-split-combined-hooks.md b/.agents/skills/vercel-react-best-practices/rules/rerender-split-combined-hooks.mdnew file mode 100644index 0000000..89d8056--- /dev/null+++ b/.agents/skills/vercel-react-best-practices/rules/rerender-split-combined-hooks.md@@ -0,0 +1,64 @@+---+title: Split Combined Hook Computations+impact: MEDIUM+impactDescription: avoids recomputing independent steps+tags: rerender, useMemo, useEffect, dependencies, optimization+---++## Split Combined Hook Computations++When a hook contains multiple independent tasks with different dependencies, split them into separate hooks. A combined hook reruns all tasks when any dependency changes, even if some tasks don't use the changed value.++**Incorrect (changing `sortOrder` recomputes filtering):**++```tsx+const sortedProducts = useMemo(() => {+ const filtered = products.filter((p) => p.category === category)+ const sorted = filtered.toSorted((a, b) =>+ sortOrder === "asc" ? a.price - b.price : b.price - a.price+ )+ return sorted+}, [products, category, sortOrder])+```++**Correct (filtering only recomputes when products or category change):**++```tsx+const filteredProducts = useMemo(+ () => products.filter((p) => p.category === category),+ [products, category]+)++const sortedProducts = useMemo(+ () =>+ filteredProducts.toSorted((a, b) =>+ sortOrder === "asc" ? a.price - b.price : b.price - a.price+ ),+ [filteredProducts, sortOrder]+)+```++This pattern also applies to `useEffect` when combining unrelated side effects:++**Incorrect (both effects run when either dependency changes):**++```tsx+useEffect(() => {+ analytics.trackPageView(pathname)+ document.title = `${pageTitle} | My App`+}, [pathname, pageTitle])+```++**Correct (effects run independently):**++```tsx+useEffect(() => {+ analytics.trackPageView(pathname)+}, [pathname])++useEffect(() => {+ document.title = `${pageTitle} | My App`+}, [pageTitle])+```++**Note:** If your project has [React Compiler](https://react.dev/learn/react-compiler) enabled, it automatically optimizes dependency tracking and may handle some of these cases for you.diff --git a/.agents/skills/vercel-react-best-practices/rules/rerender-transitions.md b/.agents/skills/vercel-react-best-practices/rules/rerender-transitions.mdnew file mode 100644index 0000000..d99f43f--- /dev/null+++ b/.agents/skills/vercel-react-best-practices/rules/rerender-transitions.md@@ -0,0 +1,40 @@+---+title: Use Transitions for Non-Urgent Updates+impact: MEDIUM+impactDescription: maintains UI responsiveness+tags: rerender, transitions, startTransition, performance+---++## Use Transitions for Non-Urgent Updates++Mark frequent, non-urgent state updates as transitions to maintain UI responsiveness.++**Incorrect (blocks UI on every scroll):**++```tsx+function ScrollTracker() {+ const [scrollY, setScrollY] = useState(0)+ useEffect(() => {+ const handler = () => setScrollY(window.scrollY)+ window.addEventListener('scroll', handler, { passive: true })+ return () => window.removeEventListener('scroll', handler)+ }, [])+}+```++**Correct (non-blocking updates):**++```tsx+import { startTransition } from 'react'++function ScrollTracker() {+ const [scrollY, setScrollY] = useState(0)+ useEffect(() => {+ const handler = () => {+ startTransition(() => setScrollY(window.scrollY))+ }+ window.addEventListener('scroll', handler, { passive: true })+ return () => window.removeEventListener('scroll', handler)+ }, [])+}+```diff --git a/.agents/skills/vercel-react-best-practices/rules/rerender-use-deferred-value.md b/.agents/skills/vercel-react-best-practices/rules/rerender-use-deferred-value.mdnew file mode 100644index 0000000..619c04b--- /dev/null+++ b/.agents/skills/vercel-react-best-practices/rules/rerender-use-deferred-value.md@@ -0,0 +1,59 @@+---+title: Use useDeferredValue for Expensive Derived Renders+impact: MEDIUM+impactDescription: keeps input responsive during heavy computation+tags: rerender, useDeferredValue, optimization, concurrent+---++## Use useDeferredValue for Expensive Derived Renders++When user input triggers expensive computations or renders, use `useDeferredValue` to keep the input responsive. The deferred value lags behind, allowing React to prioritize the input update and render the expensive result when idle.++**Incorrect (input feels laggy while filtering):**++```tsx+function Search({ items }: { items: Item[] }) {+ const [query, setQuery] = useState('')+ const filtered = items.filter(item => fuzzyMatch(item, query))++ return (+ <>+ <input value={query} onChange={e => setQuery(e.target.value)} />+ <ResultsList results={filtered} />+ </>+ )+}+```++**Correct (input stays snappy, results render when ready):**++```tsx+function Search({ items }: { items: Item[] }) {+ const [query, setQuery] = useState('')+ const deferredQuery = useDeferredValue(query)+ const filtered = useMemo(+ () => items.filter(item => fuzzyMatch(item, deferredQuery)),+ [items, deferredQuery]+ )+ const isStale = query !== deferredQuery++ return (+ <>+ <input value={query} onChange={e => setQuery(e.target.value)} />+ <div style={{ opacity: isStale ? 0.7 : 1 }}>+ <ResultsList results={filtered} />+ </div>+ </>+ )+}+```++**When to use:**++- Filtering/searching large lists+- Expensive visualizations (charts, graphs) reacting to input+- Any derived state that causes noticeable render delays++**Note:** Wrap the expensive computation in `useMemo` with the deferred value as a dependency, otherwise it still runs on every render.++Reference: [React useDeferredValue](https://react.dev/reference/react/useDeferredValue)diff --git a/.agents/skills/vercel-react-best-practices/rules/rerender-use-ref-transient-values.md b/.agents/skills/vercel-react-best-practices/rules/rerender-use-ref-transient-values.mdnew file mode 100644index 0000000..cf04b81--- /dev/null+++ b/.agents/skills/vercel-react-best-practices/rules/rerender-use-ref-transient-values.md@@ -0,0 +1,73 @@+---+title: Use useRef for Transient Values+impact: MEDIUM+impactDescription: avoids unnecessary re-renders on frequent updates+tags: rerender, useref, state, performance+---++## Use useRef for Transient Values++When a value changes frequently and you don't want a re-render on every update (e.g., mouse trackers, intervals, transient flags), store it in `useRef` instead of `useState`. Keep component state for UI; use refs for temporary DOM-adjacent values. Updating a ref does not trigger a re-render.++**Incorrect (renders every update):**++```tsx+function Tracker() {+ const [lastX, setLastX] = useState(0)++ useEffect(() => {+ const onMove = (e: MouseEvent) => setLastX(e.clientX)+ window.addEventListener('mousemove', onMove)+ return () => window.removeEventListener('mousemove', onMove)+ }, [])++ return (+ <div+ style={{+ position: 'fixed',+ top: 0,+ left: lastX,+ width: 8,+ height: 8,+ background: 'black',+ }}+ />+ )+}+```++**Correct (no re-render for tracking):**++```tsx+function Tracker() {+ const lastXRef = useRef(0)+ const dotRef = useRef<HTMLDivElement>(null)++ useEffect(() => {+ const onMove = (e: MouseEvent) => {+ lastXRef.current = e.clientX+ const node = dotRef.current+ if (node) {+ node.style.transform = `translateX(${e.clientX}px)`+ }+ }+ window.addEventListener('mousemove', onMove)+ return () => window.removeEventListener('mousemove', onMove)+ }, [])++ return (+ <div+ ref={dotRef}+ style={{+ position: 'fixed',+ top: 0,+ left: 0,+ width: 8,+ height: 8,+ background: 'black',+ transform: 'translateX(0px)',+ }}+ />+ )+}+```diff --git a/.agents/skills/vercel-react-best-practices/rules/server-after-nonblocking.md b/.agents/skills/vercel-react-best-practices/rules/server-after-nonblocking.mdnew file mode 100644index 0000000..e8f5b26--- /dev/null+++ b/.agents/skills/vercel-react-best-practices/rules/server-after-nonblocking.md@@ -0,0 +1,73 @@+---+title: Use after() for Non-Blocking Operations+impact: MEDIUM+impactDescription: faster response times+tags: server, async, logging, analytics, side-effects+---++## Use after() for Non-Blocking Operations++Use Next.js's `after()` to schedule work that should execute after a response is sent. This prevents logging, analytics, and other side effects from blocking the response.++**Incorrect (blocks response):**++```tsx+import { logUserAction } from '@/app/utils'++export async function POST(request: Request) {+ // Perform mutation+ await updateDatabase(request)++ // Logging blocks the response+ const userAgent = request.headers.get('user-agent') || 'unknown'+ await logUserAction({ userAgent })++ return new Response(JSON.stringify({ status: 'success' }), {+ status: 200,+ headers: { 'Content-Type': 'application/json' }+ })+}+```++**Correct (non-blocking):**++```tsx+import { after } from 'next/server'+import { headers, cookies } from 'next/headers'+import { logUserAction } from '@/app/utils'++export async function POST(request: Request) {+ // Perform mutation+ await updateDatabase(request)++ // Log after response is sent+ after(async () => {+ const userAgent = (await headers()).get('user-agent') || 'unknown'+ const sessionCookie = (await cookies()).get('session-id')?.value || 'anonymous'++ logUserAction({ sessionCookie, userAgent })+ })++ return new Response(JSON.stringify({ status: 'success' }), {+ status: 200,+ headers: { 'Content-Type': 'application/json' }+ })+}+```++The response is sent immediately while logging happens in the background.++**Common use cases:**++- Analytics tracking+- Audit logging+- Sending notifications+- Cache invalidation+- Cleanup tasks++**Important notes:**++- `after()` runs even if the response fails or redirects+- Works in Server Actions, Route Handlers, and Server Components++Reference: [https://nextjs.org/docs/app/api-reference/functions/after](https://nextjs.org/docs/app/api-reference/functions/after)diff --git a/.agents/skills/vercel-react-best-practices/rules/server-auth-actions.md b/.agents/skills/vercel-react-best-practices/rules/server-auth-actions.mdnew file mode 100644index 0000000..ee82c04--- /dev/null+++ b/.agents/skills/vercel-react-best-practices/rules/server-auth-actions.md@@ -0,0 +1,96 @@+---+title: Authenticate Server Actions Like API Routes+impact: CRITICAL+impactDescription: prevents unauthorized access to server mutations+tags: server, server-actions, authentication, security, authorization+---++## Authenticate Server Actions Like API Routes++**Impact: CRITICAL (prevents unauthorized access to server mutations)**++Server Actions (functions with `"use server"`) are exposed as public endpoints, just like API routes. Always verify authentication and authorization **inside** each Server Action—do not rely solely on middleware, layout guards, or page-level checks, as Server Actions can be invoked directly.++Next.js documentation explicitly states: "Treat Server Actions with the same security considerations as public-facing API endpoints, and verify if the user is allowed to perform a mutation."++**Incorrect (no authentication check):**++```typescript+'use server'++export async function deleteUser(userId: string) {+ // Anyone can call this! No auth check+ await db.user.delete({ where: { id: userId } })+ return { success: true }+}+```++**Correct (authentication inside the action):**++```typescript+'use server'++import { verifySession } from '@/lib/auth'+import { unauthorized } from '@/lib/errors'++export async function deleteUser(userId: string) {+ // Always check auth inside the action+ const session = await verifySession()++ if (!session) {+ throw unauthorized('Must be logged in')+ }++ // Check authorization too+ if (session.user.role !== 'admin' && session.user.id !== userId) {+ throw unauthorized('Cannot delete other users')+ }++ await db.user.delete({ where: { id: userId } })+ return { success: true }+}+```++**With input validation:**++```typescript+'use server'++import { verifySession } from '@/lib/auth'+import { z } from 'zod'++const updateProfileSchema = z.object({+ userId: z.string().uuid(),+ name: z.string().min(1).max(100),+ email: z.string().email()+})++export async function updateProfile(data: unknown) {+ // Validate input first+ const validated = updateProfileSchema.parse(data)++ // Then authenticate+ const session = await verifySession()+ if (!session) {+ throw new Error('Unauthorized')+ }++ // Then authorize+ if (session.user.id !== validated.userId) {+ throw new Error('Can only update own profile')+ }++ // Finally perform the mutation+ await db.user.update({+ where: { id: validated.userId },+ data: {+ name: validated.name,+ email: validated.email+ }+ })++ return { success: true }+}+```++Reference: [https://nextjs.org/docs/app/guides/authentication](https://nextjs.org/docs/app/guides/authentication)diff --git a/.agents/skills/vercel-react-best-practices/rules/server-cache-lru.md b/.agents/skills/vercel-react-best-practices/rules/server-cache-lru.mdnew file mode 100644index 0000000..ef6938a--- /dev/null+++ b/.agents/skills/vercel-react-best-practices/rules/server-cache-lru.md@@ -0,0 +1,41 @@+---+title: Cross-Request LRU Caching+impact: HIGH+impactDescription: caches across requests+tags: server, cache, lru, cross-request+---++## Cross-Request LRU Caching++`React.cache()` only works within one request. For data shared across sequential requests (user clicks button A then button B), use an LRU cache.++**Implementation:**++```typescript+import { LRUCache } from 'lru-cache'++const cache = new LRUCache<string, any>({+ max: 1000,+ ttl: 5 * 60 * 1000 // 5 minutes+})++export async function getUser(id: string) {+ const cached = cache.get(id)+ if (cached) return cached++ const user = await db.user.findUnique({ where: { id } })+ cache.set(id, user)+ return user+}++// Request 1: DB query, result cached+// Request 2: cache hit, no DB query+```++Use when sequential user actions hit multiple endpoints needing the same data within seconds.++**With Vercel's [Fluid Compute](https://vercel.com/docs/fluid-compute):** LRU caching is especially effective because multiple concurrent requests can share the same function instance and cache. This means the cache persists across requests without needing external storage like Redis.++**In traditional serverless:** Each invocation runs in isolation, so consider Redis for cross-process caching.++Reference: [https://github.com/isaacs/node-lru-cache](https://github.com/isaacs/node-lru-cache)diff --git a/.agents/skills/vercel-react-best-practices/rules/server-cache-react.md b/.agents/skills/vercel-react-best-practices/rules/server-cache-react.mdnew file mode 100644index 0000000..87c9ca3--- /dev/null+++ b/.agents/skills/vercel-react-best-practices/rules/server-cache-react.md@@ -0,0 +1,76 @@+---+title: Per-Request Deduplication with React.cache()+impact: MEDIUM+impactDescription: deduplicates within request+tags: server, cache, react-cache, deduplication+---++## Per-Request Deduplication with React.cache()++Use `React.cache()` for server-side request deduplication. Authentication and database queries benefit most.++**Usage:**++```typescript+import { cache } from 'react'++export const getCurrentUser = cache(async () => {+ const session = await auth()+ if (!session?.user?.id) return null+ return await db.user.findUnique({+ where: { id: session.user.id }+ })+})+```++Within a single request, multiple calls to `getCurrentUser()` execute the query only once.++**Avoid inline objects as arguments:**++`React.cache()` uses shallow equality (`Object.is`) to determine cache hits. Inline objects create new references each call, preventing cache hits.++**Incorrect (always cache miss):**++```typescript+const getUser = cache(async (params: { uid: number }) => {+ return await db.user.findUnique({ where: { id: params.uid } })+})++// Each call creates new object, never hits cache+getUser({ uid: 1 })+getUser({ uid: 1 }) // Cache miss, runs query again+```++**Correct (cache hit):**++```typescript+const getUser = cache(async (uid: number) => {+ return await db.user.findUnique({ where: { id: uid } })+})++// Primitive args use value equality+getUser(1)+getUser(1) // Cache hit, returns cached result+```++If you must pass objects, pass the same reference:++```typescript+const params = { uid: 1 }+getUser(params) // Query runs+getUser(params) // Cache hit (same reference)+```++**Next.js-Specific Note:**++In Next.js, the `fetch` API is automatically extended with request memoization. Requests with the same URL and options are automatically deduplicated within a single request, so you don't need `React.cache()` for `fetch` calls. However, `React.cache()` is still essential for other async tasks:++- Database queries (Prisma, Drizzle, etc.)+- Heavy computations+- Authentication checks+- File system operations+- Any non-fetch async work++Use `React.cache()` to deduplicate these operations across your component tree.++Reference: [React.cache documentation](https://react.dev/reference/react/cache)diff --git a/.agents/skills/vercel-react-best-practices/rules/server-dedup-props.md b/.agents/skills/vercel-react-best-practices/rules/server-dedup-props.mdnew file mode 100644index 0000000..fb24a25--- /dev/null+++ b/.agents/skills/vercel-react-best-practices/rules/server-dedup-props.md@@ -0,0 +1,65 @@+---+title: Avoid Duplicate Serialization in RSC Props+impact: LOW+impactDescription: reduces network payload by avoiding duplicate serialization+tags: server, rsc, serialization, props, client-components+---++## Avoid Duplicate Serialization in RSC Props++**Impact: LOW (reduces network payload by avoiding duplicate serialization)**++RSC→client serialization deduplicates by object reference, not value. Same reference = serialized once; new reference = serialized again. Do transformations (`.toSorted()`, `.filter()`, `.map()`) in client, not server.++**Incorrect (duplicates array):**++```tsx+// RSC: sends 6 strings (2 arrays × 3 items)+<ClientList usernames={usernames} usernamesOrdered={usernames.toSorted()} />+```++**Correct (sends 3 strings):**++```tsx+// RSC: send once+<ClientList usernames={usernames} />++// Client: transform there+'use client'+const sorted = useMemo(() => [...usernames].sort(), [usernames])+```++**Nested deduplication behavior:**++Deduplication works recursively. Impact varies by data type:++- `string[]`, `number[]`, `boolean[]`: **HIGH impact** - array + all primitives fully duplicated+- `object[]`: **LOW impact** - array duplicated, but nested objects deduplicated by reference++```tsx+// string[] - duplicates everything+usernames={['a','b']} sorted={usernames.toSorted()} // sends 4 strings++// object[] - duplicates array structure only+users={[{id:1},{id:2}]} sorted={users.toSorted()} // sends 2 arrays + 2 unique objects (not 4)+```++**Operations breaking deduplication (create new references):**++- Arrays: `.toSorted()`, `.filter()`, `.map()`, `.slice()`, `[...arr]`+- Objects: `{...obj}`, `Object.assign()`, `structuredClone()`, `JSON.parse(JSON.stringify())`++**More examples:**++```tsx+// ❌ Bad+<C users={users} active={users.filter(u => u.active)} />+<C product={product} productName={product.name} />++// ✅ Good+<C users={users} />+<C product={product} />+// Do filtering/destructuring in client+```++**Exception:** Pass derived data when transformation is expensive or client doesn't need original.diff --git a/.agents/skills/vercel-react-best-practices/rules/server-hoist-static-io.md b/.agents/skills/vercel-react-best-practices/rules/server-hoist-static-io.mdnew file mode 100644index 0000000..25205c2--- /dev/null+++ b/.agents/skills/vercel-react-best-practices/rules/server-hoist-static-io.md@@ -0,0 +1,149 @@+---+title: Hoist Static I/O to Module Level+impact: HIGH+impactDescription: avoids repeated file/network I/O per request+tags: server, io, performance, next.js, route-handlers, og-image+---++## Hoist Static I/O to Module Level++**Impact: HIGH (avoids repeated file/network I/O per request)**++When loading static assets (fonts, logos, images, config files) in route handlers or server functions, hoist the I/O operation to module level. Module-level code runs once when the module is first imported, not on every request. This eliminates redundant file system reads or network fetches that would otherwise run on every invocation.++**Incorrect (reads font file on every request):**++```typescript+// app/api/og/route.tsx+import { ImageResponse } from 'next/og'++export async function GET(request: Request) {+ // Runs on EVERY request - expensive!+ const fontData = await fetch(+ new URL('./fonts/Inter.ttf', import.meta.url)+ ).then(res => res.arrayBuffer())++ const logoData = await fetch(+ new URL('./images/logo.png', import.meta.url)+ ).then(res => res.arrayBuffer())++ return new ImageResponse(+ <div style={{ fontFamily: 'Inter' }}>+ <img src={logoData} />+ Hello World+ </div>,+ { fonts: [{ name: 'Inter', data: fontData }] }+ )+}+```++**Correct (loads once at module initialization):**++```typescript+// app/api/og/route.tsx+import { ImageResponse } from 'next/og'++// Module-level: runs ONCE when module is first imported+const fontData = fetch(+ new URL('./fonts/Inter.ttf', import.meta.url)+).then(res => res.arrayBuffer())++const logoData = fetch(+ new URL('./images/logo.png', import.meta.url)+).then(res => res.arrayBuffer())++export async function GET(request: Request) {+ // Await the already-started promises+ const [font, logo] = await Promise.all([fontData, logoData])++ return new ImageResponse(+ <div style={{ fontFamily: 'Inter' }}>+ <img src={logo} />+ Hello World+ </div>,+ { fonts: [{ name: 'Inter', data: font }] }+ )+}+```++**Correct (synchronous fs at module level):**++```typescript+// app/api/og/route.tsx+import { ImageResponse } from 'next/og'+import { readFileSync } from 'fs'+import { join } from 'path'++// Synchronous read at module level - blocks only during module init+const fontData = readFileSync(+ join(process.cwd(), 'public/fonts/Inter.ttf')+)++const logoData = readFileSync(+ join(process.cwd(), 'public/images/logo.png')+)++export async function GET(request: Request) {+ return new ImageResponse(+ <div style={{ fontFamily: 'Inter' }}>+ <img src={logoData} />+ Hello World+ </div>,+ { fonts: [{ name: 'Inter', data: fontData }] }+ )+}+```++**Incorrect (reads config on every call):**++```typescript+import fs from 'node:fs/promises'++export async function processRequest(data: Data) {+ const config = JSON.parse(+ await fs.readFile('./config.json', 'utf-8')+ )+ const template = await fs.readFile('./template.html', 'utf-8')++ return render(template, data, config)+}+```++**Correct (hoists config and template to module level):**++```typescript+import fs from 'node:fs/promises'++const configPromise = fs+ .readFile('./config.json', 'utf-8')+ .then(JSON.parse)+const templatePromise = fs.readFile('./template.html', 'utf-8')++export async function processRequest(data: Data) {+ const [config, template] = await Promise.all([+ configPromise,+ templatePromise,+ ])++ return render(template, data, config)+}+```++When to use this pattern:++- Loading fonts for OG image generation+- Loading static logos, icons, or watermarks+- Reading configuration files that don't change at runtime+- Loading email templates or other static templates+- Any static asset that's the same across all requests++When not to use this pattern:++- Assets that vary per request or user+- Files that may change during runtime (use caching with TTL instead)+- Large files that would consume too much memory if kept loaded+- Sensitive data that shouldn't persist in memory++With Vercel's [Fluid Compute](https://vercel.com/docs/fluid-compute), module-level caching is especially effective because multiple concurrent requests share the same function instance. The static assets stay loaded in memory across requests without cold start penalties.++In traditional serverless, each cold start re-executes module-level code, but subsequent warm invocations reuse the loaded assets until the instance is recycled.diff --git a/.agents/skills/vercel-react-best-practices/rules/server-no-shared-module-state.md b/.agents/skills/vercel-react-best-practices/rules/server-no-shared-module-state.mdnew file mode 100644index 0000000..ff7d9f2--- /dev/null+++ b/.agents/skills/vercel-react-best-practices/rules/server-no-shared-module-state.md@@ -0,0 +1,50 @@+---+title: Avoid Shared Module State for Request Data+impact: HIGH+impactDescription: prevents concurrency bugs and request data leaks+tags: server, rsc, ssr, concurrency, security, state+---++## Avoid Shared Module State for Request Data++For React Server Components and client components rendered during SSR, avoid using mutable module-level variables to share request-scoped data. Server renders can run concurrently in the same process. If one render writes to shared module state and another render reads it, you can get race conditions, cross-request contamination, and security bugs where one user's data appears in another user's response.++Treat module scope on the server as process-wide shared memory, not request-local state.++**Incorrect (request data leaks across concurrent renders):**++```tsx+let currentUser: User | null = null++export default async function Page() {+ currentUser = await auth()+ return <Dashboard />+}++async function Dashboard() {+ return <div>{currentUser?.name}</div>+}+```++If two requests overlap, request A can set `currentUser`, then request B overwrites it before request A finishes rendering `Dashboard`.++**Correct (keep request data local to the render tree):**++```tsx+export default async function Page() {+ const user = await auth()+ return <Dashboard user={user} />+}++function Dashboard({ user }: { user: User | null }) {+ return <div>{user?.name}</div>+}+```++Safe exceptions:++- Immutable static assets or config loaded once at module scope+- Shared caches intentionally designed for cross-request reuse and keyed correctly+- Process-wide singletons that do not store request- or user-specific mutable data++For static assets and config, see [Hoist Static I/O to Module Level](./server-hoist-static-io.md).diff --git a/.agents/skills/vercel-react-best-practices/rules/server-parallel-fetching.md b/.agents/skills/vercel-react-best-practices/rules/server-parallel-fetching.mdnew file mode 100644index 0000000..1affc83--- /dev/null+++ b/.agents/skills/vercel-react-best-practices/rules/server-parallel-fetching.md@@ -0,0 +1,83 @@+---+title: Parallel Data Fetching with Component Composition+impact: CRITICAL+impactDescription: eliminates server-side waterfalls+tags: server, rsc, parallel-fetching, composition+---++## Parallel Data Fetching with Component Composition++React Server Components execute sequentially within a tree. Restructure with composition to parallelize data fetching.++**Incorrect (Sidebar waits for Page's fetch to complete):**++```tsx+export default async function Page() {+ const header = await fetchHeader()+ return (+ <div>+ <div>{header}</div>+ <Sidebar />+ </div>+ )+}++async function Sidebar() {+ const items = await fetchSidebarItems()+ return <nav>{items.map(renderItem)}</nav>+}+```++**Correct (both fetch simultaneously):**++```tsx+async function Header() {+ const data = await fetchHeader()+ return <div>{data}</div>+}++async function Sidebar() {+ const items = await fetchSidebarItems()+ return <nav>{items.map(renderItem)}</nav>+}++export default function Page() {+ return (+ <div>+ <Header />+ <Sidebar />+ </div>+ )+}+```++**Alternative with children prop:**++```tsx+async function Header() {+ const data = await fetchHeader()+ return <div>{data}</div>+}++async function Sidebar() {+ const items = await fetchSidebarItems()+ return <nav>{items.map(renderItem)}</nav>+}++function Layout({ children }: { children: ReactNode }) {+ return (+ <div>+ <Header />+ {children}+ </div>+ )+}++export default function Page() {+ return (+ <Layout>+ <Sidebar />+ </Layout>+ )+}+```diff --git a/.agents/skills/vercel-react-best-practices/rules/server-parallel-nested-fetching.md b/.agents/skills/vercel-react-best-practices/rules/server-parallel-nested-fetching.mdnew file mode 100644index 0000000..be1dc25--- /dev/null+++ b/.agents/skills/vercel-react-best-practices/rules/server-parallel-nested-fetching.md@@ -0,0 +1,34 @@+---+title: Parallel Nested Data Fetching+impact: CRITICAL+impactDescription: eliminates server-side waterfalls+tags: server, rsc, parallel-fetching, promise-chaining+---++## Parallel Nested Data Fetching++When fetching nested data in parallel, chain dependent fetches within each item's promise so a slow item doesn't block the rest.++**Incorrect (a single slow item blocks all nested fetches):**++```tsx+const chats = await Promise.all(+ chatIds.map(id => getChat(id))+)++const chatAuthors = await Promise.all(+ chats.map(chat => getUser(chat.author))+)+```++If one `getChat(id)` out of 100 is extremely slow, the authors of the other 99 chats can't start loading even though their data is ready.++**Correct (each item chains its own nested fetch):**++```tsx+const chatAuthors = await Promise.all(+ chatIds.map(id => getChat(id).then(chat => getUser(chat.author)))+)+```++Each item independently chains `getChat` → `getUser`, so a slow chat doesn't block author fetches for the others.diff --git a/.agents/skills/vercel-react-best-practices/rules/server-serialization.md b/.agents/skills/vercel-react-best-practices/rules/server-serialization.mdnew file mode 100644index 0000000..39c5c41--- /dev/null+++ b/.agents/skills/vercel-react-best-practices/rules/server-serialization.md@@ -0,0 +1,38 @@+---+title: Minimize Serialization at RSC Boundaries+impact: HIGH+impactDescription: reduces data transfer size+tags: server, rsc, serialization, props+---++## Minimize Serialization at RSC Boundaries++The React Server/Client boundary serializes all object properties into strings and embeds them in the HTML response and subsequent RSC requests. This serialized data directly impacts page weight and load time, so **size matters a lot**. Only pass fields that the client actually uses.++**Incorrect (serializes all 50 fields):**++```tsx+async function Page() {+ const user = await fetchUser() // 50 fields+ return <Profile user={user} />+}++'use client'+function Profile({ user }: { user: User }) {+ return <div>{user.name}</div> // uses 1 field+}+```++**Correct (serializes only 1 field):**++```tsx+async function Page() {+ const user = await fetchUser()+ return <Profile name={user.name} />+}++'use client'+function Profile({ name }: { name: string }) {+ return <div>{name}</div>+}+```diff --git a/.claude/skills/rust-best-practices/SKILL.md b/.claude/skills/rust-best-practices/SKILL.mdnew file mode 100644index 0000000..5a44d1c--- /dev/null+++ b/.claude/skills/rust-best-practices/SKILL.md@@ -0,0 +1,94 @@+---+name: rust-best-practices+description: >+ Guide for writing idiomatic Rust code based on Apollo GraphQL's best practices handbook. Use this skill when:+ (1) writing new Rust code or functions,+ (2) reviewing or refactoring existing Rust code,+ (3) deciding between borrowing vs cloning or ownership patterns,+ (4) implementing error handling with Result types,+ (5) optimizing Rust code for performance,+ (6) writing tests or documentation for Rust projects.+license: MIT+compatibility: Rust 1.70+, Cargo+metadata:+ author: apollographql+ version: "1.1.2"+allowed-tools: Bash(cargo:*) Bash(rustc:*) Bash(rustfmt:*) Bash(clippy:*) Read Write Edit Glob Grep+---++# Rust Best Practices++Apply these guidelines when writing or reviewing Rust code. Based on Apollo GraphQL's [Rust Best Practices Handbook](https://github.com/apollographql/rust-best-practices).++## Best Practices Reference++Before reviewing, familiarize yourself with Apollo's Rust best practices. Read ALL relevant chapters in the same turn in parallel. Reference these files when providing feedback:++- [Chapter 1 - Coding Styles and Idioms](references/chapter_01.md): Borrowing vs cloning, Copy trait, Option/Result handling, iterators, comments, when to extract a function (duplication vs. wrong abstraction)+- [Chapter 2 - Clippy and Linting](references/chapter_02.md): Clippy configuration, important lints, workspace lint setup+- [Chapter 3 - Performance Mindset](references/chapter_03.md): Profiling, avoiding redundant clones, stack vs heap, zero-cost abstractions+- [Chapter 4 - Error Handling](references/chapter_04.md): Result vs panic, thiserror vs anyhow, error hierarchies+- [Chapter 5 - Automated Testing](references/chapter_05.md): Test naming, one assertion per test, snapshot testing+- [Chapter 6 - Generics and Dispatch](references/chapter_06.md): Static vs dynamic dispatch, trait objects+- [Chapter 7 - Type State Pattern](references/chapter_07.md): Compile-time state safety, when to use it+- [Chapter 8 - Comments vs Documentation](references/chapter_08.md): When to comment, doc comments, rustdoc+- [Chapter 9 - Understanding Pointers](references/chapter_09.md): Thread safety, Send/Sync, pointer types++## Quick Reference++### Borrowing & Ownership+- Prefer `&T` over `.clone()` unless ownership transfer is required+- Use `&str` over `String`, `&[T]` over `Vec<T>` in function parameters+- Small `Copy` types (≤24 bytes) can be passed by value+- Use `Cow<'_, T>` when ownership is ambiguous++### Error Handling+- Return `Result<T, E>` for fallible operations; avoid `panic!` in production+- Never use `unwrap()`/`expect()` outside tests+- Use `thiserror` for library errors, `anyhow` for binaries only+- Prefer `?` operator over match chains for error propagation++### Performance+- Always benchmark with `--release` flag+- Run `cargo clippy -- -D clippy::perf` for performance hints+- Avoid cloning in loops; use `.iter()` instead of `.into_iter()` for Copy types+- Prefer iterators over manual loops; avoid intermediate `.collect()` calls++### Linting+Run regularly: `cargo clippy --all-targets --all-features --locked -- -D warnings`++Key lints to watch:+- `redundant_clone` - unnecessary cloning+- `large_enum_variant` - oversized variants (consider boxing)+- `needless_collect` - premature collection++Use `#[expect(clippy::lint)]` over `#[allow(...)]` with justification comment.++### Testing+- Name tests descriptively: `process_should_return_error_when_input_empty()`+- One assertion per test when possible+- Use doc tests (`///`) for public API examples+- Consider `cargo insta` for snapshot testing generated output++### Generics & Dispatch+- Prefer generics (static dispatch) for performance-critical code+- Use `dyn Trait` only when heterogeneous collections are needed+- Box at API boundaries, not internally++### Type State Pattern+Encode valid states in the type system to catch invalid operations at compile time:+```rust+struct Connection<State> { /* ... */ _state: PhantomData<State> }+struct Disconnected;+struct Connected;++impl Connection<Connected> {+ fn send(&self, data: &[u8]) { /* only connected can send */ }+}+```++### Documentation+- `//` comments explain *why* (safety, workarounds, design rationale)+- `///` doc comments explain *what* and *how* for public APIs+- Every `TODO` needs a linked issue: `// TODO(#42): ...`+- Enable `#![deny(missing_docs)]` for librariesdiff --git a/.claude/skills/rust-best-practices/references/chapter_01.md b/.claude/skills/rust-best-practices/references/chapter_01.mdnew file mode 100644index 0000000..1269642--- /dev/null+++ b/.claude/skills/rust-best-practices/references/chapter_01.md@@ -0,0 +1,657 @@+# Chapter 1 - Coding Styles and Idioms++## 1.1 Borrowing Over Cloning++Rust's ownership system encourages **borrow** (`&T`) instead of **cloning** (`T.clone()`).+> ❗ Performance recommendation++### ✅ When to `Clone`:++* You need to change the object AND preserve the original object (immutable snapshots).+* When you have `Arc` or `Rc` pointers.+* When data is shared across threads, usually `Arc`.+* Avoid massive refactoring of non performance critical code.+* When caching results (dummy example below):+```rust+fn get_config(&self) -> Config {+ self.cached_config.clone()+}+```+* When the underlying API expects Owned Data.++### 🚨 `Clone` traps to avoid:++* Auto-cloning inside loops `.map(|x| x.clone)`, prefer to call `.cloned()` or `.copied()` at the end of the iterator.+* Cloning large data structures like `Vec<T>` or `HashMap<K, V>`.+* Clone because of bad API design instead of adjusting lifetimes.+* Prefer `&[T]` instead of `Vec<T>` or `&Vec<T>`.+* Prefer `&str` or `&String` instead of `String`.+* Prefer `&T` instead of `T`.+* Clone a reference argument, if you need ownership, make it explicit in the arguments for the caller. Example:+```rust+fn take_a_borrow(thing: &Thing) {+ let thing_cloned = thing.clone(); // the caller should have passed ownership instead+}+```++### ✅ Prefer borrowing:+```rust+fn process(name: &str) {+ println!("Hello {name}");+}++let user = String::from("foo");+process(&user);+```++### ❌ Avoid redundant cloning:+```rust+fn process_string(name: String) {+ println!("Hello {name}");+}++let user = String::from("foo");+process(user.clone()); // Unnecessary clone+```++## 1.2 When to pass by value? (Copy trait)++Not all types should be passed by reference (`&T`). If a type is **small** and it is **cheap to copy**, it is often better to **pass it by value**. Rust makes it explicit via the `Copy` trait.++### ✅ When to pass by value, `Copy`:+* The type **implements** `Copy` (`u32`, `bool`, `f32`, small structs).+* The cost of moving the value is negligible.++```rust+fn increment(x: u32) -> u32 {+ x + 1+}++let num = 1;+let new_num = increment(num); // `num` still usable after this point+```++### ❓ Which structs should be `Copy`?+* When to consider declaring `Copy` on your own types:+* All fields are `Copy` themselves.+* The struct is `small`, up to 2 (maybe 3) words of memory or 24 bytes (each word is 64 bits/8bytes).+* The struct **represents a "plain data object"**, without resorting to ownership (no heap allocations. Example: `Vec` and `Strings`).+* ❗**The type does not also implement `Iterator`.** Even if every field is `Copy`, never put `Copy` and `Iterator` on the same type (see [§1.5](#15-iterator-iter-vs-for)).++❗**Rust Arrays are stack allocated.** Which means they can be copied if their underlying type is `Copy`, but this will be allocated in the program stack which can easily become a stack overflow. More on [Chapter 3 - Stack vs Heap](./chapter_03.md#33-stack-vs-heap-be-size-smart)++For reference, each primitive type size in bytes:++#### Integers:++| Type | Size |+|------------- |---------- |+| i8 u8 | 1 byte |+| i16 u16 | 2 bytes |+| i32 u32 | 4 bytes |+| i64 u64 | 8 bytes |+| isize usize | Arch |+| i128 u128 | 16 bytes |++#### Floating Point:++| Type | Size |+|---------- |---------- |+| f32 | 4 bytes |+| f64 | 8 bytes |+++#### Other:++| Type | Size |+|---------- |---------- |+| bool | 1 byte |+| char | 4 bytes |+++### ✅ Good struct to derive `Copy`:+```rust+#[derive(Debug, Copy, Clone)]+struct Point {+ x: f32,+ y: f32,+ z: f32+}+```++### ❌ Bad struct to derive `Copy`:+```rust+#[derive(Debug, Clone)]+struct BadIdea {+ age: i32,+ name: String, // String is not `Copy`+}+```++### ❓Which Enums should be `Copy`?+* If your enum acts like tags and atoms.+* The enum payloads are all `Copy`.+* **❗Enums size are based on their largest element.**++### ✅ Good Enum to derive+```rust+#[derive(Debug, Copy, Clone)]+enum Direction {+ North,+ South,+ East,+ West,+}+```++## 1.3 Handling `Option<T>` and `Result<T, E>`+Rust 1.65 introduced a better way to safely unpack Option and Result types with the `let Some(x) = … else { … }` or `let Ok(x) = … else { … }` when you have a default `return` value, `continue` or `break` default else case. It allows early returns when the missing case is **expected and normal**, not exceptional.++### ✅ Cases to use each pattern matching for Option and Result+* Use `match` when you want to pattern match against the inner types `T` and `E`+```rust+match self {+ Ok(Direction::South) => { … },+ Ok(Direction::North) => { … },+ Ok(Direction::East) => { … },+ Ok(Direction::West) => { … },+ Err(E::One) => { … },+ Err(E::Two) => { … },+}++match self {+ Some(3|5) => { … }+ Some(x) if x > 10 => { … }+ Some(x) => { … }+ None => { … }+}+```++* Use `match` when your type is transformed into something more complex Like `Result<T, E>` becoming `Result<Option<U>, E>`.+```rust+match self {+ Ok(t) => Ok(Some(t)),+ Err(E::Empty) => Ok(None),+ Err(err) => Err(err),+}+```++* Use `let PATTERN = EXPRESSION else { DIVERGING_CODE; }` when the divergent code doesn't need to know about the failed pattern matches or doesn't need extra computation:+```rust+let Some(&Direction::North) = self.direction.as_ref() else {+ return Err(DirectionNotAvailable(self.direction));+}+```++* Use `let PATTERN = EXPRESSION else { DIVERGING_CODE; }` when you want to break or continue a pattern match+```rust+for x in self {+ let Some(x) = x else {+ continue;+ }+}+```++* Use `if let PATTERN = EXPRESSION else { DIVERGING_CODE; }` when `DIVERGING_CODE` needs extra computation:+```rust+if let Some(x) = self.next() {+ // computation+} else {+ // computation when `None/Err` or not matched+}+```++❗**If you don't care about the value of the `Err` case, please use `?` to propagate the `Err` to the caller.**++### ❌ Bad Option/Result pattern matching:++* Conversion between Result and Option (prefer `.ok()`,`.ok_or()`, and `ok_or_else()`)+```rust+match self {+ Ok(t) => Some(t),+ Err(_) => None+}+```++* `if let PATTERN = EXPRESSION else { DIVERGING_CODE; }` when divergent code is a default or pre-computed value (prefer `let PATTERN = EXPRESSION else { DIVERGING_CODE; }`):+```rust+if let Some(values) = self.next() {+ // computation+ (Some(..), values)+} else {+ (None, Vec::new())+}+```++* Using `unwrap` or `expect` outside tests:+```rust+let port = config.port.unwrap();+```++## 1.4 Prevent Early Allocation++When dealing with functions like `or`, `map_or`, `unwrap_or`, `ok_or`, consider that they have special cases for when memory allocation is required, like creating a new string, creating a collection or even calling functions that manage some state, so they can be replaced with their `_else` counter-part:++### ✅ Good cases++```rust+let x = None;+assert_eq!(x.ok_or(ParseError::ValueAbsent), Err(ParseError::ValueAbsent));++let x = None;+assert_eq!(x.ok_or_else(|| ParseError::ValueAbsent(format!("this is a value {x}"))), Err(ParseError::ValueAbsent));+++let x: Result<_, &str> = Ok("foo");+assert_eq!(x.map_or(42, |v| v.len()), 3);+++let x : Result<_, String> = Ok("foo");+assert_eq!(x.map_or_else(|e|format!("Error: {e}"), |v| v.len()), 3);++let x = "1,2,3,4";+assert_eq!(x.parse_to_option_vec.unwrap_or_else(Vec::new), Ok(vec![1, 2, 3, 4]));+```++### ❌ Bad cases++```rust+let x : Result<_, String> = Ok("foo");+assert_eq!(x.map_or(format!("Error with uninformed content"), |v| v.len()), 3);++let x = "1,2,3,4";+assert_eq!(x.parse_to_option_vec.unwrap_or(Vec::new()), Ok(vec![1, 2, 3, 4])); // could be replaced with `.unwrap_or_default`++let x = None;+assert_eq!(x.ok_or(ParseError::ValueAbsent(format!("this is a value {x}"))), Err(ParseError::ValueAbsent));+```++### Mapping Err++When dealing with Result::Err, sometimes is necessary to log and transform the Err into a more abstract or more detailed error, this can be done with `inspect_err` and `map_err`:++```rust+let x = Err(ParseError::InvalidContent(...));++x+.inspect_err(|err| tracing::error!("function_name: {err}"))+.map_err(|err| GeneralError::from(("function_name", err)))?;+```++## 1.5 Iterator, `.iter` vs `for`++First we need to understand a basic loop with each one of them. Let's consider the following problem, we need to sum all even numbers between 0 and 10 incremented by 1:++* `for`:+```rust+let mut sum = 0;+for x in 0..=10 {+ if x % 2 == 0 {+ sum += x + 1;+ }+}+```++* `iter`:+```rust+let sum: i32 = (0..=10)+ .filter(|x| x % 2 == 0)+ .map(|x| x + 1)+ .sum();+```++> Both versions do the same thing and are correct and idiomatic, but each shines in different contexts.++### When to prefer `for` loops+* When you need **early exits** (`break`, `continue`, `return`).+* **Simple iteration** with side-effects (e.g., logging, IO)+ * logging can be done correctly in `Iterators` using `inspect` and `inspect_err` functions.+* When readability matters more than simplicity or chaining.++#### Example:+```rust+for value in &mut value {+ if *value == 0 {+ break;+ }+ *value += fancy_equation();+}+```++### When to prefer `iterators` loops (`.iter()` and `.into_iter()`)+* When you are `transforming collections` or `Option/Results`.+* You can **compose multiple steps** elegantly.+* No need for early exits.+* You need support for indexed values with `.enumerate`.+```rust+let values: Vec<_> = vec.into_iter()+ .enumerate()+ .filter(|(_index, value)| value % 2 == 0)+ .map(|(index, value)| value % index)+ .collect()+```+* You need to use collections functions like `.windows` or `chunks`.+* You need to combine data from multiple sources and don't want to allocate multiple collections.+* Iterators can be combined with `for` loops:+```rust+for value in vec.iter().enumerate()+ .filter(|(index, value)| value % index == 0) {+ // ...+}++```++> #### ❗REMEMBER: Iterators are Lazy+>+> * `.iter`, `.map`, `.filter` don't do anything until you call its consumer, e.g. `.collect`, `.sum`, `.for_each`.+> * **Lazy Evaluation** means that iterator chains are fused into one loop at compile time.++### 🚨 Anti-patterns to AVOID++* Don't chain without formatting. Prefer each chained function on its own line with the correct indentation (`rustfmt` should take care of this).+* Don't chain if it makes the code unreadable.+* Avoid needlessly collect/allocate of a collection (e.g. vector) just to throw it away later by some larger operation or by another iteration.+* Prefer `iter` over `into_iter` unless you don't need the ownership of the collection.+* Prefer `iter` over `into_iter` for collections that inner type implements `Copy`, e.g. `Vec<T: Copy>`.+* **Never implement (or derive) both `Copy` and `Iterator` on the same type.** Copying an iterator and advancing one copy leaves the other untouched, which silently yields wrong results -- it is a well-known footgun. The standard library hit exactly this: it is why `Range` historically could not be `Copy`, and why the new `core::range` types (stabilized in Rust 1.96) implement `IntoIterator` instead of `Iterator` so they *can* be `Copy`. If you need an iterator on a `Copy` type, implement `IntoIterator` and return a separate iterator struct.+* For summing numbers prefer `.sum` over `.fold`. `.sum` is specialized for summing values, so the compiler knows it can make optimizations on that front, while fold has a blackbox closure that needs to be applied at every step. If you need to sum by an initial value, just add it in the expression `let my_sum = [1, 2, 3].sum() + 3`.++## 1.6 Comments: Context, not Clutter++> "Comments are for why, not what or how"++Well-written Rust code, with expressive types and good naming, often speaks for itself. Many high-quality codebases thrive on **few or no comments**. And that's a good thing.++Still, there are **moments where code alone isn't enough** - when there are performance quirks, external constraints, or non-obvious tradeoffs that require a nudge to the reader. In those cases, a concise comment can prevent hours of head-scratching or searching git history.++### ✅ Good comments++* Safety concerns:+```rust+// SAFETY: We have checked that the pointer is valid and non-null. @Function xyz.+unsafe { std::ptr::copy_nonoverlapping(src, dst, len); }+```++* Performance quirks:+```rust+// This algorithm is a fast square root approximation+const THREE_HALVES: f32 = 1.5;+fn q_rsqrt(number: f32 ) -> f32 {+ let mut i: i32 = number.to_bits() as i32;+i = 0x5F375A86_i32.wrapping_sub(i >> 1);+let y = f32::from_bits(i as u32);+y * (THREE_HALVES - (number * 0.5 * y * y))+}+```++* Clear code beats comments. However, when the why isn't obvious, say it plainly - or link to where:+```rust+// PERF: Generating the root store per subgraph caused high TLS startup latency on MacOS+// This works as a caching alternative. See: [ADR-123](link/to/adr-123)+let subgraph_tls_root_store: RootCertStore = configuration+ .tls+ .subgraph+ .all+ .create_certificate_store()+ .transpose()?+ .unwrap_or_else(crate::services::http::HttpClientService::native_roots_store);+let connector_tls_root_store: RootCertStore = configuration+ .tls+ .connector+ .all+ .create_certificate_store()+ .transpose()?+ .unwrap_or_else(crate::services::http::HttpClientService::native_roots_store);+```++* ❗ More use cases to come in their appropriate sections.++### ❌ Bad comments++* Wall-of-text explanations: long comments and multiline comments+```rust+// Lorem Ipsum is simply dummy text of the printing and typesetting industry.+// Lorem Ipsum has been the industry's standard dummy text ever since the 1500s,+// when an unknown printer took a galley+fn do_something_odd() {+ …+}+```+> Prefer `/// doc` comment if it's describing the function.++* Comments that could be better represented as functions or are plain obvious+```rust+fn computation() {+ // increment i by 1+ i += 1;+}+```++### ✅ Breaking up long functions over commenting them++If you find yourself writing a long comment explaining "what", "how" or "each step" in a function, it might be time to split it. So the suggestion is to refactor. This can be beneficial not only for readability, but testability:++#### ❌ Instead of:+```rust+fn process_request(request: T) {+ // We first need to validate request, because of corner case x, y, z+ // As the payload can only be decoded when they are valid+ // Then we can perform authorization on the payload+ // lastly with the authorized payload we can dispatch to handler+}+```++#### ✅ Prefer+```rust+fn process_request(request: T) -> Result<(), Error> {+ validate_request_headers(&request)?;+ let payload = decode_payload(&request);+ authorize(&payload)?;+ dispatch_to_handler(payload)+}++#[cfg(test)]+mod tests {+ #[test]+ fn validate_request_happy_path() { ... }++ #[test]+ fn validate_request_fails_on_x() { ... }++ #[test]+ fn validate_request_fails_on_y() { ... }++ #[test]+ fn decode_validated_request() { ... }++ #[test]+ fn authorize_payload_xyz() { ... }+}+```++Let **structure** and **naming** replace commentary, and enhance its documentation with **tests as living documentation**.++> ❗ Splitting is about **naming and clarity**, not deduplication. Before extracting a helper to remove *duplicated* lines, check [§1.8](#18-when-to-extract-a-function-and-when-not-to).++### 📝 TODOs are not comments - track them properly++Avoid leaving lingering `// TODO: Lorem Ipsum` comments in the code. Instead:+* Turn them into Jira or Github Issues.+* If needed, to avoid future confusion, reference the issue in the code and the code in the issue.++```rust+// See issue #123: support hyper 2.0+```++This helps keeping the code clean and making sure tasks are not forgotten.++### Comments as Living Documentation++There are a few gotchas when calling comments "living documentation":+* Code evolves.+* Context changes.+* Comments get stale.+* Many large comments make people avoid reading them.+* Team becomes fearful of deleting irrelevant comments.++If you find a comment, **don't trust it blindly**. Read it in context. If it's wrong or outdated, fix or remove it. A misleading comment is worse than no comments at all.++> Comments should bother you - they demand re-verification, just like stale tests.++When deeper justification is needed, prefer to:+* **Link to a Design Doc or an ADR**, business logic lives well in design docs while performance tradeoffs live well in ADRs.+* Move runtime example and usage docs into Rust Docs, `/// doc comment`, where they can be tested and kept up-to-date by tools like `cargo doc`.++> Doc-comments and Doc-testing, `///` and `//!` in [Chapter 8 - Comments vs Documentation](./chapter_08.md)++## 1.7 Use Declarations - "imports"++Different languages have different ways of sorting their imports, in the Rust ecosystem the [standard way](https://github.com/rust-lang/rustfmt/issues/4107) is:++- `std` (`core`, `alloc` would also fit here).+- External crates (what is in your Cargo.toml `[dependencies]`).+- Workspace crates (workspace member crates).+- This module `super::`.+- This module `crate::`.++```rust+// std+use std::sync::Arc;++// external crates+use chrono::Utc;+use juniper::{FieldError, FieldResult};+use uuid::Uuid;++// crate code lives in workspace+use broker::database::PooledConnection;++// super:: / crate::+use super::schema::{Context, Payload};+use super::update::convert_publish_payload;+use crate::models::Event;+```++Some enterprise solutions opt to include their core packages after `std`, so all external packages that start with enterprise name are located before the others:++```rust+// std+use std::sync::Arc;++// enterprise external crates+use enterprise_crate_name::some_module::SomeThing;++// external crates+use chrono::Utc;+use juniper::{FieldError, FieldResult};+use uuid::Uuid;++// crate code lives in workspace+use broker::database::PooledConnection;++// super:: / crate::+use super::schema::{Context, Payload};+use super::update::convert_publish_payload;+use crate::models::Event;+```++One way of not having to manually control this is using the following arguments in your `rustfmt.toml`:++```toml+reorder_imports = true+imports_granularity = "Crate"+group_imports = "StdExternalCrate"+```++> As of Rust version 1.88, it is necessary to execute rustfmt in nightly to correctly reorder code `cargo +nightly fmt`.++## 1.8 When to Extract a Function (and When Not To)++This chapter ([§1.6](#-breaking-up-long-functions-over-commenting-them)) and [Chapter 8](./chapter_08.md#85-replace-comments-with-code) recommend splitting long functions and replacing narrative comments with named helpers. That advice is about **naming and clarity** -- it is *not* a license to hunt down every repeated line. Extraction has a cost: every helper adds indirection, and a **wrong abstraction is much harder to remove than a little duplication**.++> "Duplication is far cheaper than the wrong abstraction." -- [Sandi Metz, The Wrong Abstraction](https://sandimetz.com/blog/2016/1/20/the-wrong-abstraction)++### 📏 The Rule of Three++From [Martin Fowler's *Refactoring*](https://martinfowler.com/books/refactoring.html), attributed to Don Roberts:++> The first time you do something, you just do it. The second time you do something similar, you wince at the duplication, but you do the duplicate thing anyway. The third time you do something similar, you refactor.++Two occurrences of a couple of lines are usually **fine**. Wait for the third before reaching for a helper -- by then you will know what the abstraction actually *is*, instead of guessing at it.++### 🧠 DRY is about knowledge, not text++[DRY](https://en.wikipedia.org/wiki/Don%27t_repeat_yourself) (*The Pragmatic Programmer*) says every piece of **knowledge** should have a single representation. It does **not** say "no two code fragments may look alike". Two blocks that *happen* to look the same today, but represent **different decisions**, will evolve in different directions. Forcing them into one helper couples code that should be free to diverge -- this is **coincidental duplication**, and deduplicating it is how wrong abstractions are born.++### 🧪 Examples++How these principles play out in code:++#### ✅ Coincidental duplication -- leave it inline:+```rust+// Similar-looking lines, but the `.env` and `.toml` formats are+// unrelated decisions that will evolve independently:+writeln!(env_file, "{key}={value}")?;+// ... elsewhere ...+writeln!(toml_file, "{key} = \"{value}\"")?;+```++#### ❌ Deduplicating it forces a flag parameter -- the classic smell:+```rust+// One helper, two behaviors, and a `bool` to pick between them:+fn write_entry(out: &mut impl Write, key: &str, value: &str, quoted: bool) -> io::Result<()> {+ if quoted {+ writeln!(out, "{key} = \"{value}\"")+ } else {+ writeln!(out, "{key}={value}")+ }+}+```++Every new variant will grow another parameter or branch. And the `bool` is a smell in its own right: `write_entry(out, key, value, true)` tells the reader nothing at the call site -- Martin Fowler calls this a [Flag Argument](https://martinfowler.com/bliki/FlagArgument.html). When a mode selector is genuinely warranted, a two-variant enum (`Quoting::Quoted`) keeps call sites readable, and Clippy's [`fn_params_excessive_bools`](https://rust-lang.github.io/rust-clippy/master/index.html#fn_params_excessive_bools) lints against accumulating them. No enum rescues *this* design, though: its variants would exist only to encode the callers' differences.++#### ✅ Shared knowledge -- extract it:+```rust+// The definition of "retryable" is ONE business decision used in many+// places. If it changes, it must change everywhere at once:+fn is_retryable(status: StatusCode) -> bool {+ status == StatusCode::TOO_MANY_REQUESTS || status.is_server_error()+}+```++### 🔧 Unwinding a wrong abstraction++If you find yourself maintaining an abstraction like `write_entry`, [Sandi Metz's advice](https://sandimetz.com/blog/2016/1/20/the-wrong-abstraction) is to **unwind it, not patch it**:++1. **Re-inline** the helper's body into every caller, substituting each call site's concrete arguments.+2. **Reduce** each call site -- with the parameters now literal, dead branches and unused generality fall away.+3. **Reevaluate** what the callers *actually* share, now that every one of them is explicit.+4. **Reconstruct** one or more abstractions from what remains -- or none, if the sharing turns out to be coincidental.++> 🤖 Doing this by hand is tedious, which is why wrong abstractions survive on sunk cost. For an AI coding agent, unwinding is fast, mechanical work -- ask for it explicitly instead of letting the agent keep patching a helper that fights back.++### ✅ Extract a function when:+* The logic appears in **3+ places** *and* represents the **same decision** (Rule of Three).+* The name **adds meaning** the code alone does not (`is_retryable`, `authorize`) -- rather than restating it (`add_one_to_counter`).+* It produces a **unit worth testing** in isolation (see [§1.6](#-breaking-up-long-functions-over-commenting-them)).+* It hides genuine complexity behind a **small, honest signature** -- few parameters, no flags.++### ❌ Don't extract when:+* It is **1-2 lines used in fewer than 3 places** -- the helper is pure indirection.+* The call sites are only *almost* identical, and unifying them requires **flag parameters** or extra branches.+* The only motivation is **line count**. A single-caller helper pays off when its *name* clarifies intent ([§1.6](#-breaking-up-long-functions-over-commenting-them), [§8.5](./chapter_08.md#85-replace-comments-with-code)) -- not when it merely relocates code.+* You are **guessing** at a future abstraction. Wait for the third usage to reveal its real shape.++### 🧫 Test code: readability beats DRY++In tests, be **even more tolerant of duplication**. The Google Testing Blog calls this [DAMP -- "Descriptive And Meaningful Phrases"](https://testing.googleblog.com/2019/12/testing-on-toilet-tests-too-dry-make.html) ([*Software Engineering at Google*, ch. 12](https://abseil.io/resources/swe-book/html/ch12.html)): each test should read as a **self-contained story** -- setup, action, assertion -- without the reader chasing helpers to reconstruct what actually happened.++* **Tests have no tests.** Logic moved into a shared helper (loops, branches, clever parametrization) is itself untested -- a bug there silently weakens every test built on it.+* **A failing test should be diagnosable on sight.** The reader is usually debugging a broken build; make the expected behavior visible in the test body, not three helpers away.+* **Shared test helpers couple unrelated tests.** Change one behavior and dozens of tests fail at once -- for the helper's sake, not the behavior's.++Where to draw the line:+* ✅ Share **setup and fixtures** -- a shared setup function or `rstest` cases, as [Chapter 5](./chapter_05.md#51-tests-as-living-documentation) recommends. Constructing a test server twice is boilerplate, not knowledge.+* ❌ Keep each test's **action and assertion inline**, even when they look repetitive across tests.++> 🚨 When in doubt, **prefer duplication**. A duplicated line is trivially fixed later; a wrong abstraction accretes parameters and conditionals, because each maintainer keeps patching it instead of undoing it.diff --git a/.claude/skills/rust-best-practices/references/chapter_02.md b/.claude/skills/rust-best-practices/references/chapter_02.mdnew file mode 100644index 0000000..8fbd985--- /dev/null+++ b/.claude/skills/rust-best-practices/references/chapter_02.md@@ -0,0 +1,117 @@+# Chapter 2 - Clippy and Linting Discipline++Be sure to have `cargo clippy` installed with your rust compiler, run `cargo clippy -V` in your terminal for a rust project and you should get something like this `clippy 0.1.86 (05f9846f89 2025-03-31)`. If terminal fails to show a clippy version, please run the following code `rustup update && rustup component add clippy`.++Clippy documentation can be found [here](https://doc.rust-lang.org/clippy/usage.html).++## 2.1 Why care about linting?++Rust compiler is a powerful tool that catches many mistakes. However, some more in-depth analysis require extra tools, that is where `cargo clippy` comes into play. Clippy checks for:+* Performance pitfalls.+* Style issues.+* Redundant code.+* Potential bugs.+* Non-idiomatic Rust.++## 2.2 Always run `cargo clippy`++Add the following to your daily workflow:++```shell+$ cargo clippy --all-targets --all-features --locked -- -D warnings+```++* `--all-targets`: checks library, tests, benches and examples.+* `--all-features`: checks code with all features enabled; it does not auto-solve conflicting features.+* `--locked`: Requires `Cargo.lock` to be up-to-date, can be solved with `$ cargo update`.+* `-D warnings`: treats warnings as errors++Potential additional elements to add:++* `-- -W clippy::pedantic`: lints which are rather strict or have occasional false positives.+* `-- -W clippy::nursery`: Optionally can be added to check for new lints that are still under development.+* ❗ Add this to your Makefile, Justfile, xtask or CI Pipeline.++> Example at ApolloGraphQL+>+> In the `Router` project there is a `xtask` configured for linting that can be executed with `cargo xtask lint`.++## 2.3 Important Clippy Lints to Respect++| Lint Name | Why | Link |+| --------- | ----| -----|+| `redundant_clone` | Detects unnecessary `clones`, has performance impact | [link (nursery + perf)](https://rust-lang.github.io/rust-clippy/master/#redundant_clone) |+| `needless_borrow` group | Removes redundant `&` borrowing | [link (style)](https://rust-lang.github.io/rust-clippy/master/#needless_borrow) |+| `map_unwrap_or` / `map_or` | Simplifies nested `Option/Result` handling | [`map_unwrap_or`](https://rust-lang.github.io/rust-clippy/master/#map_unwrap_or) [`unnecessary_map_or`](https://rust-lang.github.io/rust-clippy/master/#unnecessary_map_or) [`unnecessary_result_map_or_else`](https://rust-lang.github.io/rust-clippy/master/#unnecessary_result_map_or_else) |+| `manual_ok_or` | Suggest using `.ok_or_else` instead of `match` | [link (style)](https://rust-lang.github.io/rust-clippy/master/#manual_ok_or) |+| `large_enum_variant` | Warns if an enum has very large variant which is bad for memory. Suggests `Boxing` it | [link (perf)](https://rust-lang.github.io/rust-clippy/master/#large_enum_variant) |+| `unnecessary_wraps` | If your function always returns `Some` or `Ok`, you don't need `Option`/`Result` | [link (pedantic)](https://rust-lang.github.io/rust-clippy/master/#unnecessary_wraps) |+| `clone_on_copy` | Catches accidental `.clone()` on `Copy` types like `u32` and `bool` | [link (complexity)](https://rust-lang.github.io/rust-clippy/master/#clone_on_copy) |+| `needless_collect` | Prevents collecting and allocating an iterator, when allocation is not needed | [link (nursery)](https://rust-lang.github.io/rust-clippy/master/#needless_collect) |++## 2.4 Fix warnings, don't silence them!++**NEVER** just `#[allow(clippy::lint_something)]` unless:++* You **truly understand** why the warning happens and you have a reason why it is better that way.+* You **document** why it is being ignored.+* ❗ Don't use `allow`, but `expect`, it will give a warning in case the lint is not true anymore, `#[expect(clippy::lint_something)]`.++### Example:++```rust+// Faster matching is preferred over size efficiency+#[expect(clippy::large_enum_variant)]+enum Message {+ Code(u8),+ Content([u8; 1024]),+}+```++> The fix would be:+>+> ```rust+> // Faster matching is preferred over size efficiency+> #[expect(clippy::large_enum_variant)]+> enum Message {+> Code(u8),+> Content(Box<[u8; 1024]>),+> }+> ```++### Handling false positives++Sometimes Clippy complains even when your code is correct, in those cases there are two solutions:+1. Try to refactor the code, so it improves the warning.+2. **Locally** override the lint with `#[expect(clippy::lint_name)]` and a comment with the reason.+3. Avoid global overrides, unless it is core crate issue, a good example of this is the Bevy Engine that has a set of lints that should be allowed by default.++## 2.5 Configure workspace/package lints++In your `Cargo.toml` file it is possible to determine which lints and their priorities over each other. In case of 2 or more conflicting lints, the higher priority one will be chosen. Example configuration for a package:++```toml+[lints.rust]+future-incompatible = "warn"+nonstandard_style = "deny"++[lints.clippy]+all = { level = "deny", priority = 10 }+redundant_clone = { level = "deny", priority = 9 }+manual_while_let_some = { level = "deny", priority = 4 }+pedantic = { level = "warn", priority = 3 }+```++And for a workspace:++```toml+[workspace.lints.rust]+future-incompatible = "warn"+nonstandard_style = "deny"++[workspace.lints.clippy]+all = { level = "deny", priority = 10 }+redundant_clone = { level = "deny", priority = 9 }+manual_while_let_some = { level = "deny", priority = 4 }+pedantic = { level = "warn", priority = 3 }+```\ No newline at end of filediff --git a/.claude/skills/rust-best-practices/references/chapter_03.md b/.claude/skills/rust-best-practices/references/chapter_03.mdnew file mode 100644index 0000000..2613314--- /dev/null+++ b/.claude/skills/rust-best-practices/references/chapter_03.md@@ -0,0 +1,211 @@+# Chapter 3 - Performance Mindset++The **golden rule** of performance work:++> Don't guess, measure.++Rust code is often already pretty fast - don't "optimize" without evidence. Optimize only after finding bottlenecks.++### A good first steps+* Use `--release` flag on your builds (might sound dummy, but it is quite common to hear people complaining that their Rust code is slower than their X language code, and 99% of the time is because they didn't use the `--release` flag).+* `$ cargo clippy -- -D clippy::perf` gives you important tips on best practices for performance.+* [`cargo bench`](https://doc.rust-lang.org/cargo/commands/cargo-bench.html) is a cargo tool to create micro-benchmarks and test different code solutions. Write a test scenario and bench your solution against the original code, if your improvement is larger than 5%, might be a good performance improvement.+* [`cargo flamegraph`](https://github.com/flamegraph-rs/flamegraph) a powerful profiler for Rust code. For MacOS, [samply](https://github.com/mstange/samply) might be a better DX option.++> #### Further reading on Benchmarking:+> - [How to build a Custom Benchmarking Harness in Rust](https://bencher.dev/learn/benchmarking/rust/custom-harness/)+++## 3.1 Flamegraph++Flamegraph helps you visualize how much time CPU spent on each task.++```shell+# Installing flamegraph+cargo install flamegraph++# cargo support provided through the cargo-flamegraph binary!+# defaults to profiling cargo run --release+cargo flamegraph++# by default, `--release` profile is used,+# but you can override this:+cargo flamegraph --dev++# if you'd like to profile a specific binary:+cargo flamegraph --bin=stress2++# Profile unit tests.+# Note that a separating `--` is necessary if `--unit-test` is the last flag.+cargo flamegraph --unit-test -- test::in::package::with::single::crate+cargo flamegraph --unit-test crate_name -- test::in::package::with::multiple:crate++# Profile integration tests.+cargo flamegraph --test test_name++# Run criterion benchmark+# Note that the last --bench is required for `criterion 0.3` to run in benchmark mode, instead of test mode.+cargo flamegraph --bench some_benchmark --features some_features -- --bench++# Run workspace example+cargo flamegraph --example some_example --features some_features+```++> ❗ Always run your profiles with `--release` enabled, the `--dev` flag isn't realistic as it doesn't have optimizations enabled.++The result will look like a flame graph where:+++* The `y-axis` shows the **stack depth number**. When looking at a flamegraph, the main function of your program will be closer to the bottom, and the called functions will be stacked on top, with the functions that they call stacked on top of them.++* The `width of each box` shows the **total time that that function** is on the CPU or is part of the call stack. If a function's box is wider than others, that means that it consumes more CPU per execution than other functions, or that it is called more than other functions.++> ❗ The **color of each box** isn't significant, and **is chosen at random**.++### 🚨 Remember+* Thick stacks: heavy CPU usage+* Thin stacks: low intensity (cheap)++## 3.2 Avoid Redundant Cloning++> Cloning is cheap... **until it isn't**++In sections [Borrowing over Cloning](./chapter_01.md#11-borrowing-over-cloning) and [Important Clippy lints to respect](./chapter_02.md#23-important-clippy-lints-to-respect) we mentioned the impacts of cloning and the relevant clippy lint [`redundant_clone`](https://rust-lang.github.io/rust-clippy/master/#redundant_clone), so in this section we will explore a bit "when to pass ownership".++* 🚨 If you really need to clone, leave it to the last moment.++### When to pass ownership?++* Only `.clone()` if you truly need a new owned copy. A few examples:+ * Crate API Design requires owned data.+ * Have overloaded `std::ops` but still need ownership to the old data:+ ```rust+ use std::ops::Add;++ #[derive(Debug, Copy, Clone, PartialEq)]+ struct Point {+ x: i32,+ y: i32,+ }++ impl Add for Point {+ type Output = Self;++ fn add(self, other: Self) -> Self {+ Self {+ x: self.x + other.x,+ y: self.y + other.y,+ }+ }+ }++ assert_eq!(Point { x: 1, y: 0 } + Point { x: 2, y: 3 },+ Point { x: 3, y: 3 });+ ```+ * Need to do comparison snapshots or due to API you need multiple owned instances of the data.+ ```rust+ fn snapshot(a: &MyValue, b:&MyValue) -> MyValueDiff {+ a - b+ }++ impl Sub for MyValue {+ type Output = MyValueDiff;++ fn sub(self, other: Self) -> MyValue {+ ...+ }+ }++ fn main() {+ let mut a = MyValue::default();+ let b = a.clone();++ a.magical_update();+ println!("{:?}", snapshot(&a, &b));+ }+ ```+* You have reference counted pointers (`Arc, Rc`).+* You have small structs that are too big to `Copy` but as costly as `std::collections`. An example is HTTP client like `hyper_util::client::legacy::Client` that cloning allows you to share the connection pool.+* You have a chained struct modifier that needs owned mutation, some **builders** require owned mutation, but most custom builders can be done with `pub fn with_xyz(&mut self, value: Xyz) -> &mut Self`.+```rust+// Inline `HashMap` insertion extension++fn insert_owned(mut self, key: K, value: V) -> Self {+ self.insert(key, value);+ self+}++```+* Ownership can also be a good way to model business logic / state. For example:+```rust+let not_validated: String = ...;// some user source+let validated = Validate::try_from(not_validated)?;+// Technically that `try_from` maybe didn't need ownership, but taking it lets us model intent+```++### When **NOT** to pass ownership?++* Prefer API designs that take reference (`fn process(values: &[T])`), instead of ownership (`fn process(values: Vec<T>)`).+* If you only need read access to elements, prefer `.iter` or slices:+```rust+for item in &some_vec {+ ...+}+```+* You need to mutate data that is owned by another thread, use `&mut MyStruct`.++### Use `Cow` for `Maybe Owned` data++Sometimes you don't actually need owned data, but that is not clear from the API perspective, so using [`std::borrow::Cow`](https://doc.rust-lang.org/std/borrow/enum.Cow.html) is a way to efficiently address this case:++```rust+use std::borrow::Cow;++fn hello_greet(name: Cow<'_, str>) {+ println!("Hello {name}");+}++hello_greet(Cow::Borrowed("Julia"));+hello_greet(Cow::Owned("Naomi".to_string()));+```++## 3.3 Stack vs Heap: Be size-smart!++### ✅ Good Practices++* Keep small types (`impl Copy`, `usize`, `bool`, etc) **on the stack**.+* Avoid passing huge types (`> 512 bytes`) by value or transferring ownership. Prefer pass by reference (e.g. `&T` and `&mut T`).+* Heap allocate recursive data structures:+```rust+enum OctreeNode<T> {+ Node(T),+ Children(Box<[Node<T>; 8]>),+}+```+* Return small types by value, types that implement `Copy` or a cheaply Cloned are efficient to return by value (e.g. `struct Vector2 {x: f32, y: f32}`).++### ❗ Be Mindful++* Only use `#[inline]` when benchmark proves beneficial, Rust is already pretty good at inlining **without** hints.+* Avoid massive stack allocations, box them. Example `let buffer: Box<[u8; 65536]> = Box::new(..)` would first allocate `[u8; 65536]` on the stack then box it, a non-const solution to this would be `let buffer: Box<[u8]> = vec![0; 65536].into_boxed_slice()`.+* For large `const` arrays, considering using [crate smallvec](https://docs.rs/smallvec/latest/smallvec/) as it behaves like an array, but is smart enough to allocate large arrays on the heap.++## 3.4 Iterators and Zero-Cost Abstractions++Rust iterators are lazy, but eventually compiled away into very efficient tight loops that are only called when consumed. Chaining `.filter()`, `.map()`, `.rev()`, `.skip()`, `.take()`, `.collect()` usually doesn't cost extra and the compiler can reason well enough how to optimize them.+* Prefer `iterators` over manual `for` loops when working with collections, the compiler can optimize them better than manually doing it.+* Calling `.iter()` only creates a **reference** to the original collection, this allows you to hold multiple iterators of the same collection.++#### ❗ Avoid creating intermediate collections unless it is really needed:++* Consider that `process` accepts an `iterator`.+* ❌ BAD - useless intermediate collection:+```rust+let doubled: Vec<_> = items.iter().map(|x| x * 2).collect();+process(doubled);+```+* ✅ GOOD - pass the iterator (`fn process(arg: impl Iterator<Item = u32>)`):+```rust+let doubled_iter = items.iter().map(|x| x * 2);+process(doubled_iter);+```\ No newline at end of filediff --git a/.claude/skills/rust-best-practices/references/chapter_04.md b/.claude/skills/rust-best-practices/references/chapter_04.mdnew file mode 100644index 0000000..fb252f4--- /dev/null+++ b/.claude/skills/rust-best-practices/references/chapter_04.md@@ -0,0 +1,181 @@+# Chapter 4 - Errors Handling++Rust enforces a strict error handling approach, but *how* you handle them defines where your code feels ergonomic, consistent and safe - as opposed to cryptic and painful. This chapter dives into best practices for modeling and managing fallible operations across libraries and binaries.++> Even if you decide to crash your application with `unwrap` or `expect`, Rust forces you to declare that intentionally.++## 4.1 Prefer `Result`, avoid panic 🫨++Rust has a powerful type that wraps fallible data, [`Result`](https://doc.rust-lang.org/std/result/), this allows us to handle Error cases according to our needs and manage the state of the application based on that.++* If your function can fail, prefer to return a `Result`:+```rust+fn divide(x: f64, y: f64) -> Result<f64, DivisionError> {+ if y == 0.0 {+ Err(DivisionError::DividedByZero)+ } else {+ Ok(x / y)+ }+}+```++* Use `panic!` only in unrecoverable conditions - typically tests, assertions, bugs or a need to crash the application for some explicit reason.+* There are 3 relevant macros that can replace `panic!` in appropriate conditions:+ * `todo!`, similar to panic, but alerts the compiler that you are aware that there is code missing.+ * `unreachable!`, you have reasoned about the code block and are sure that condition `xyz` is not possible and if ever becomes possible you want to be alerted.+ * `unimplemented!`, specially useful for alerting that a block is not yet implemented with a reason.++## 4.2 Avoid `unwrap`/`expect` in Production++Although `expect` is preferred to `unwrap`, as it can have context, they should be avoided in production code as there are smarter alternatives to them. Considering that, they should be used in the following scenarios:+- In tests, assertions or test helper functions.+- When failure is impossible.+- When the smarter options can't handle the specific case.++### 🚨 Alternative ways of handling `unwrap`/`expect`:++* If your `Result` (or `Option`) can have a predefined early return value in case of `Result::Err`, that doesn't need to know the `Err` value, use `let Ok(..) = else { return ... }` pattern, as it helps with flatten functions:+```rust+let Ok(json) = serde_json::from_str(&input) else {+ return Err(MyError::InvalidJson);+}+```+* If your `Result` (or `Option`) needs error recovery in case of `Result::Err`, that doesn't need to know the `Err` value, use `if let Ok(..) else { ... }` pattern:+```rust+if let Ok(json) = serde_json::from_str(&input) else {+ ...+} else {+ Err(do_something_with_input(&input))+}+```+* Functions that can have to handle `Option::None` values are recommended to return `Result<T, E>`, where `E` is a crate or module level error, like the examples above.+* Lastly `unwrap_or`, `unwrap_or_else` or `unwrap_or_default`, these functions help you create alternative exits to unwrap that manage the uninitialized values.++## 4.3 `thiserror` for Crate level errors++Deriving Error manually is verbose and error prone, the rust ecosystem has a really good crate to help with this, `thiserror`. It allows you to create error types that easily implement `From` trait as well as easy error message (`Display`), improving developer experience while working seamlessly with `?` and integrating with `std::error::Error`:++```rust+#[derive(Debug, thiserror::Error)]+pub enum MyError {+ #[error("Network Timeout")]+ Timeout,+ #[error("Invalid data: {0}")]+ InvalidData(String),+ #[error(transparent)]+ Serialization(#[from] serde_json::Error),+ #[error("Invalid request information. Header: {headers}, Metadata: {metadata}")]+ InvalidRequest {+ headers: Headers,+ metadata: Metadata+ }+}+```++### Error Hierarchies and Wrapping++For layered systems the best practice is to use nested `enum/struct` errors with `#[from]`:++```rust+use crate::database::DbError;+use crate::external_services::ExternalHttpError;++#[derive(Debug, thiserror::Error)]+pub enum ServiceError {+ #[error("Database handler error: {0}")]+ Db(#[from] DbError),+ #[error("External services error: {0}")]+ ExternalServices(#[from] ExternalHttpError)++}+```++## 4.4 Reserve `anyhow` for Binaries++`anyhow` is an amazing crate, and quite useful for projects that are beginning and need accelerated speed. However, there is a turning point where it just painfully propagates through your code, considering this, `anyhow` is recommended only for **binaries**, where ergonomic error handling is needed and there is no need for precise error types:++```rust+use anyhow::{Context, Result, anyhow};++fn main() -> Result<Config> {+ let content = std::fs::read_to_string("config.json")+ .context("Failed to read config file")?;+ Config::from_str(&content)+ .map_err(|err| anyhow!("Config parsing error: {err}"))+}+```++### 🚨 `Anyhow` Gotchas++* Keeping the `context` and `anyhow` strings up-to-date in all code base is harder than keeping `thiserror` messages as you don't have a single point of entry.+* `anyhow::Result` erases context that a caller might need, so avoid using it in a library.+* test helper functions can use `anyhow` with little to no issues.++## 4.5 Use `?` to Bubble Errors++Prefer using `?` over verbose alternatives like `match` chains:+```rust+fn handle_request(req: &Request) -> Result<ValidatedRequest, RequestValidationError> {+ validate_headers(req)?;+ validate_body_format(req)?;+ validate_credentials(req)?;+ let body = Body::try_from(req)?;++ Ok(ValidatedRequest::try_from((req, body))?)+}+```++> In case error recovery is needed, use `or_else`, `map_err`, `if let Ok(..) else`. To **inspect or log your error**, use `inspect_err`.++## 4.6 Unit Test should exercise errors++While many errors don't implement PartialEq and Eq, making it hard to do direct assertions between them, it is possible to check the error messages with `format!` or `to_string()`, making the errors meaningful and test validated:++```rust+#[test]+fn error_does_not_implement_partial_eq() {+ let err = divide(10., 0.0).unwrap_err();+ assert_eq!(err.to_string(), "division by zero");+}++#[test]+fn error_implements_partial_eq() {+ let err = process(my_value).unwrap_err();++ assert_eq!(+ err,+ MyError {+ ..+ }+ )+}+```++## 4.7 Important Topics++### Custom Error Structs++Sometimes you don't need an enum to handle your errors, as there is only one type of error that your module can have. This can be solved with `struct Errors`:++```rust+#[derive(Debug, thiserror::Error, PartialEq)]+#[error("Request failed with code `{code}`: {message}")]+struct HttpError {+ code: u16,+ message: String+}+```++### Async Errors++When using async runtimes, like Tokio, make sure that your errors implement `Send + Sync + 'static` where needed, specially in tasks or across `.await` boundaries:++```rust+#[tokio::main]+async fn main() -> Result<(), Box<dyn std::error::Error + Send + Sync>> {+ ...+ Ok(())+}+```++> Avoid `Box<dyn std::error::Error>` in libraries unless it is really needed\ No newline at end of filediff --git a/.claude/skills/rust-best-practices/references/chapter_05.md b/.claude/skills/rust-best-practices/references/chapter_05.mdnew file mode 100644index 0000000..20a39b8--- /dev/null+++ b/.claude/skills/rust-best-practices/references/chapter_05.md@@ -0,0 +1,390 @@+# Chapter 5 - Automated Testing++> Tests are not just for correctness. They are the first place people look to understand how your code works.++* Tests in rust are declared with the attribute macro `#[test]`. Most code editors can compile and run the functions declared under the macro individually or blocks of them.+* Test can have special compilation flags with `#[cfg(test)]`. Also executable in code editors if it contained `#[test]`, it is a good way to mock complicated functions or override traits.++## 5.1 Tests as Living Documentation++In Rust, as in many other languages, tests often show how the functions are meant to be used. If a test is clear and targeted, it's often more helpful than reading the function body, when combined with other tests, they serve as living documentation.++### Use descriptive names++> In the unit test name we should see the following:+> * `unit_of_work`: which *function* we are calling. The **action** that will be executed. This is often the name of the test `mod` where the function is being tested.+```rust+#[cfg(test)]+mod test {+ mod function_name {+ #[test]+ fn returns_y_when_x() { ... }+ }+}+```+> * `expected_behavior`: the set of **assertions** that we need to verify that the test works.+> * `state_that_the_test_will_check`: the general **arrangement**, or setup, of the specific test case.++#### ❌ Don't use a generic name for a test+```rust+#[test]+fn test_add_happy_path() {+ assert_eq!(add(2, 2), 4);+}+```+#### ✅ Use a name which reads like a sentence, describing the desired behavior+> Alternatively, if your function has too many tests, you can blob them together in a `mod`, it makes it easier to read and navigate.++```rust+// OPTION 1+#[test]+fn process_should_return_blob_when_larger_than_b() {+ let a = setup_a_to_be_xyz();+ let b = Some(2);+ let expected = MyExpectedStruct { ... };++ let result = process(a, b).unwrap();++ assert_eq!(result, expected);+}++// OPTION 2+mod process {+ #[test]+ fn should_return_blob_when_larger_than_b() {+ let a = setup_a_to_be_xyz();+ let b = Some(2);+ let expected = MyExpectedStruct { ... };++ let result = process(a, b).unwrap();++ assert_eq!(result, expected);+ }+}+```++> When executing `cargo test` the test output for each option will look like:+> Option 1: `process_should_return_blob_when_larger_than_b`.+> Option 2: `process::should_return_blob_when_larger_than_b`.++### Use modules for organization++Most IDEs can run a single module of tests all together.+The test name in the output will also contain the name of the module.+Together, that means you can use the module name to group related tests together:++```rust+#[cfg(test)]+mod test { // IDEs will provide a ▶️ button here++ mod process {+ #[test] // IDEs will provide a ▶️ button here+ fn returns_error_xyz_when_b_is_negative() {+ let a = setup_a_to_be_xyz();+ let b = Some(-5);+ let expected = MyError::Xyz;++ let result = process(a, b).unwrap_err();++ assert_eq!(result, expected);+ }++ #[test] // IDEs will provide a ▶️ button here+ fn returns_invalid_input_error_when_a_and_b_not_present() {+ let a = None;+ let b = None;+ let expected = MyError::InvalidInput;++ let result = process(a, b).unwrap_err();++ assert_eq!(result, expected);+ }+ }+}+```++### Only test one behavior per function++To keep tests clear, they should describe _one_ thing that the unit does.+This makes it easier to understand why a test is failing.++#### ❌ Don't test multiple things in the same test+```rust+fn test_thing_parser(...) {+ assert!(Thing::parse("abcd").is_ok());+ assert!(Thing::parse("ABCD").is_err());+}+```++#### ✅ Test one thing per test+```rust+#[cfg(test)]+mod test_thing_parser {+ #[test]+ fn lowercase_letters_are_valid() {+ assert!(+ Thing::parse("abcd").is_ok(),+ // Works like `eprintln`, `format` and `println` macros+ "Thing parse error: {:?}",+ Thing::parse("abcd").unwrap_err()+ );+ }++ #[test]+ fn capital_letters_are_invalid() {+ assert!(Thing::parse("ABCD").is_err());+ }+}+```++> `Ok` scenarios should have an `eprintln` of the `Err` case.++### Use very few, ideally one, assertion per test++When there are multiple assertions per test, it's both harder to understand the intended behavior and+often requires many iterations to fix a broken test, as you work through assertions one by one.++❌ Don't include many assertions in one test:++```rust+#[test]+fn test_valid_inputs() {+ assert!(the_function("a").is_ok());+ assert!(the_function("ab").is_ok());+ assert!(the_function("ba").is_ok());+ assert!(the_function("bab").is_ok());+}+```++If you are testing separate behaviors, make multiple tests each with descriptive names.+To avoid boilerplate, either use a shared setup function or [rstest](https://crates.io/crates/rstest) cases *with descriptive test names*:+```rust+#[rstest]+#[case::single("a")]+#[case::first_letter("ab")]+#[case::last_letter("ba")]+#[case::in_the_middle("bab")]+fn the_function_accepts_all_strings_with_a(#[case] input: &str) {+ assert!(the_function(input).is_ok());+}+```++> Considerations when using `rstest`+>+> * It's harder for both IDEs and humans to run/locate specific tests.+> * Expectation vs condition naming is now visually inverted (expectation first).++> ❗ Share **setup**, not the test itself: keep each test's action and assertion inline, even when repetitive. Tests tolerate duplication better than production code -- see [Chapter 1, §1.8](./chapter_01.md#-test-code-readability-beats-dry).++## 5.2 Add Test Examples to your Docs++We will deep dive into docs at a later stage, so in this section we will just briefly go over how to add tests to your docs. Rustdoc can turn examples into executable tests using `///` with a few advantages:++* These tests run with `cargo test` **BUT NOT** `cargo nextest run`. If using `nextest`, make sure to run `cargo t --doc` separately.+* They serve both as documentation and correctness checks, and are kept up to date by changes, due to the fact that the compiler checks them.+* No extra testing boilerplate. You can easily hide test sections by prefixing the line with `#`.+* ❗ There is no issue if you have test duplication between doc-tests and other non-public facing tests.++```rust+/// Helper function that adds any two numeric values together.+/// This function reasons about which would be the correct type to parse based on the type+/// and the size of the numeric value.+///+/// # Examples+///+/// ```rust+/// # use crate_name::generic_add;+/// use num::numeric;+///+/// # assert_eq!(+/// generic_add(5.2, 4) // => 9.2+/// # , 9.2)+///+/// # assert_eq!(+/// generic_add(2, 2.0) // => 4+/// # , 4)+/// ```+```++This documentation code would look like:+```rust+use num::numeric;++generic_add(5.2, 4) // => 9.2+generic_add(2, 2.0) // => 4+```++## 5.3 Unit Test vs Integration Tests vs Doc tests++As a general rule, without delving into *test pyramid naming*, rust has 3 sets of tests:++### Unit Test++Tests that go in the **same module** as the **tested unit** was declared, this allows the test runner to have visibility over private functions and parent `use` declarations. They can also consume `pub(crate)` functions from other modules if needed. Unit tests can be more focused on **implementation and edge-cases checks**.++* They should be as simple as possible, testing one state and one behavior of the unit. KISS.+* They should test for errors and edge cases.+* Different tests of the same unit can be combined under a single `#[cfg(test)] mod test_unit_of_work {...}`, allowing multiple submodules for different `units_of_work`.+* Try to keep external states/side effects to your API to minimum and focus those tests on the `mod.rs` files.+* Tests that are not yet fully implemented can be ignored with the `#[ignore = "optional message"]` attribute.+* Tests that intentionally panic should be annotated with the attribute `#[should_panic]`.++```rust+#[cfg(test)]+mod unit_of_work_tests {+ use super::*;++ #[test]+ fn unit_state_behavior() {+ let expected = ...;+ let result = ...;+ assert_eq!(result, expected, "Failed because {}", result - expected);+ }+}+```++### Integration Tests++Tests that go under the `tests/` directory, they are entirely external to your library and use the same code as any other code would use, not have access to private and crate level functions, which means they can **only test** functions on your **public API**.++> Their purpose is to test whether many parts of the code work together correctly, units of code that work correctly on their own could have problems when integrated.++* Test for happy paths and common use cases.+* Allow external states and side effects, [testcontainers](https://rust.testcontainers.org/) might help.+* if testing binaries, try to break **executable** and **functions** into `src/main.rs` and `src/lib.rs`, respectively.++```+├── Cargo.lock+├── Cargo.toml+├── src+│ └── lib.rs+└── tests+ ├── mod.rs+ ├── common+ │ └── mod.rs+ └── integration_test.rs+```++### Doc Testing++As mentioned in section [5.2](#52-add-test-examples-to-your-docs), doc tests should have happy paths, general public API usage and more powerful attributes that improve documentation, like custom CSS for the code blocks.++### Attributes:++* `ignore`: tells rust to ignore the code, usually not recommended, if you want just a code formatted text, use `text`.+* `should_panic`: tells the rust compiler that this example block will panic.+* `no_run`: compiles but doesn't execute the code, similar to `cargo check`. Very useful when dealing with side-effects for documentation.+* `compile_fail`: Test rustdoc that this block should cause a compilation fail, important when you want to demonstrate wrong use cases.++## 5.4 How to `assert!`++Rust comes with 2 macros to make assertions:+* `assert!` for asserting boolean values like `assert!(value.is_ok(), "'value' is not Ok: {value:?}")`+* `assert_eq!` for checking equality between two different values, `assert_eq!(result, expected, "'result' differs from 'expected': {}", result.diff(expected))`.++### 🚨 `assert!` reminders+* Rust asserts support formatted strings, like the previous examples, those strings will be printed in case of failure, so it is a good practice to add what the actual state was and how it differs from the expected.+* If you don't care about the exact pattern matching value, using `matches!` combined with `assert!` might be a good alternative. Note the message string is an argument to `assert!`, not to `matches!`:+```rust+assert!(matches!(error, MyError::BadInput(_)), "Expected `BadInput`, found {error}");+```+* Since Rust 1.96 prefer the stabilized [`assert_matches!`](https://doc.rust-lang.org/std/macro.assert_matches.html) (and [`debug_assert_matches!`](https://doc.rust-lang.org/std/macro.debug_assert_matches.html)) over `assert!(matches!(..))`. It prints the actual value on failure for free, so you don't have to write the message yourself:+```rust+use std::assert_matches::assert_matches;++assert_matches!(error, MyError::BadInput(_));+```+* Use `#[should_panic]` wisely. It should only be used when panic is the desired behavior, prefer result instead of panic.+* There are some other that can enhance your testing experience like:+ * [`rstest`](https://crates.io/crates/rstest): fixture based test framework with procedural macros.+ * [`pretty_assertions`](https://crates.io/crates/pretty_assertions): overrides `assert_eq` and `assert_ne`, and creates colorful diffs between them.++## 5.5 Snapshot Testing with `cargo insta`++> When correctness is visual or structural, snapshots tell the story better than asserts.++1. Add to your dependencies:+```toml+insta = { version = "1.42.2", features = ["yaml"] }+```+> For most real world applications the recommendation is to use YAML snapshots of serializable values. This is because they look best under version control and the diff viewer and support redaction. To use this enable the yaml feature of insta.++2. For a better review experience, add the CLI `cargo install cargo-insta`.+++3. Writing a simple test:+```rust+fn split_words(s: &str) -> Vec<&str> {+ s.split_whitespace().collect()+}++#[test]+fn test_split_words() {+ let words = split_words("hello from the other side");+ insta::assert_yaml_snapshot!(words);+}+```++4. Run `cargo insta test` to execute, and `cargo insta review` to review conflicts.++To learn more about `cargo insta` check out its [documentation](https://insta.rs/docs/quickstart/) as it is a very complete and well documented tool.++### What is snapshot testing?++Snapshot testing compares your output (text, Json, HTML, YAML, etc) against a saved "golden" version. On future runs, the test fails if the output changes, unless humanly approved. It is perfect for:+* Generate code.+* Serializing complex data.+* Rendered HTML.+* CLI output.++#### ❌ What not to test with snapshot+* Very stable, numeric-only or small structured data associated logic (prefer `assert_eq!`).+* Critical path logic (prefer precise unit tests).+* Flaky tests, randomly generated output, unless redacted.+* Snapshots of external resources, use mocks and stubs.++## 5.6 ✅ Snapshot Best Practices++* Named snapshots, it gives meaningful snapshot files names, e.g. `snapshots/this_is_a_named_snapshot.snap`+```rust+assert_snapshot!("this_is_a_named_snapshot", output);+```++* Keep snapshots small and clear.+```rust+// ✅ Best case:+assert_snapshot!("app_config/http", whole_app_config.http);++// ❌ Worst case:+assert_snapshot!("app_config", whole_app_config); // Huge object+```++> #### 🚨 Avoid snapshotting huge objects+> Huge objects become hard to review and reason about.++* Avoid snapshotting simple types (primitives, flat enums, small structs):+```rust+// ✅ Better:+assert_eq!(meaning_of_life, 42);++// ❌ OVERKILL:+assert_snapshot!("the_meaning_of_life", meaning_of_life); // meaning_of_life == 42+```++* Use [redactions](https://insta.rs/docs/redactions/) for unstable fields (randomly generated, timestamps, uuid, etc):+```rust+use insta::assert_json_snapshot;++#[test]+fn endpoint_get_user_data() {+ let data = http::client.get_user_data();+ assert_json_snapshot!(+ "endpoints/subroute/get_user_data",+ data,+ ".created_at" => "[timestamp]",+ ".id" => "[uuid]"+ );+}+```+* Commit your snapshots into git. They will be stored in `snapshots/` alongside your tests.+* Review changes carefully before accepting.\ No newline at end of filediff --git a/.claude/skills/rust-best-practices/references/chapter_06.md b/.claude/skills/rust-best-practices/references/chapter_06.mdnew file mode 100644index 0000000..bf609c4--- /dev/null+++ b/.claude/skills/rust-best-practices/references/chapter_06.md@@ -0,0 +1,161 @@+# Chapter 6 - Generics, Dynamic Dispatch and Static Dispatch++> Static where you can, dynamic where you must++Rust allows you to handle polymorphic code in two ways:+* **Generics / Static Dispatch**: compile-time, monomorphized per use.+* **Trait Objects / Dynamic Dispatch**: runtime vtable, single implementation.++Understanding the trade-offs lets you write faster, smaller and more flexible code.++## 6.1 [Generics](https://doc.rust-lang.org/book/ch10-00-generics.html)++Every programming language has tools for effectively handling the duplication of concepts. In Rust, one such tool is generics: abstract stand-ins for concrete types or other properties. We can express the behavior of generics or how they relate to other generics without knowing what will be in their place when compiling and running the code.++We use generics to create definitions for items like function signatures or structs, which we can then use with many different concrete data types. Let's first look at how to define functions, structs, enums, and methods using generics. Generics can also be used to implement Type State Pattern and constrain a struct functionality to certain expected types, more on type state on [chapter 7](./chapter_07.md).++[Generics by Examples](https://doc.rust-lang.org/rust-by-example/generics.html).++### Generics Performance++You might be wondering whether there is a runtime cost when using generic type parameters. The good news is that using generic types won't make your program run any slower than it would with concrete types. Rust accomplishes this by performing monomorphization of the code using generics at compile time. Monomorphization is the process of turning generic code into specific code by filling in the concrete types that are used when compiled. The compiler checks for all occurrences of the generic parameter and generates code for the concrete types the generic code is called with.++## 6.2 Static Dispatch: `impl Trait` or `<T: Trait>`++A static dispatch is basically a constrained version of generics, a trait bounded generic, at compile-time it is able to check if your generic satisfies the declared traits.++### ✅ Best when:+* You want **zero runtime cost**, by paying the compile time cost.+* You need **tight loops or performance**.+* Your types are **known at compile time**.+* You are working with **single-use implementations** (monomorphized).++### 🏎️ Example: High-performance function with generic+```rust+fn specialized_sum<U: Sum + RandomMapping, T: Iterator<Item = U>>(iter: T) -> U {+ iter.map(|x| x.random_mapping()).sum()+}++// or, equivalent, more modern+fn specialized_sum<U: Sum + RandomMapping>(iter: impl Iterator<Item = U>) -> U {+ iter.map(|x| x.random_mapping()).sum()+}+```++This is compiled into **specialized machine code** for each usage, fast and inlined.++## 6.3 Dynamic Dispatch: `dyn Trait`++Usually dynamic dispatch is used with some kind of pointer or a reference, like `Box<dyn Trait>`, `Arc<dyn Trait>` or `&dyn trait`.++### ✅ Best when:+* You absolutely need runtime polymorphism.+* You need to **store different implementations** in one collection.+* You want to **abstract internals behind a stable interface**.+* You are writing a **plugin-style architecture**.++> ❗ Closer to what you would get in an object oriented language and can have some heavy costs associated to it. Can avoid generics entirely and let you mix types that implement the same traits.++### 🚚 Example: Heterogeneous collection++```rust+trait Animal {+ fn greet(&self) -> String;+}++struct Dog;+impl Animal for Dog {+ fn greet(&self) -> String {+ "woof".to_string()+ }+}++struct Cat;+impl Animal for Cat {+ fn greet(&self) -> String {+ "meow".to_string()+ }+}++fn all_animals_greeting(animals: Vec<Box<dyn Animal>>) {+ for animal in animals {+ println!("{}", animal.greet())+ }+}+```++## 6.4 Trade-off summary++| | Static Dispatch (impl Trait) | Dynamic Dispatch (dyn Trait) |+|------------------- |------------------------------ |---------------------------------- |+| Performance | ✅ Faster, inlined | ❌ Slower: vtable indirection |+| Compile time | ❌ Slower: monomorphization | ✅ Faster: shared code |+| Binary size | ❌ Larger: per-type codegen | ✅ Smaller |+| Flexibility | ❌ Rigid, one type at a time | ✅ Can mix types in collections |+| Use in trait fn() | ❌ Traits must be object-safe | ✅ Works with trait objects |+| Errors | ✅ Clearer | ❌ Erased types can confuse errors |++* Prefer generics/static dispatch when you control the call site and want performance.+* Use dynamic dispatch when you need abstraction, plugins or mixed types. 🚨 Runtime cost.+* If you are not sure, start with generics, trait bound them - then use `Box<dyn Trait>` when flexibility outweighs speed.++> Favor static dispatch until your trait needs to live behind a pointer.++## 6.5 Best Practices for Dynamic Dispatch++Dynamic dispatch `Ptr<dyn Trait>` is a powerful tool, but it also has significant performance trade-offs. You should only reach for it when **type erasure or runtime polymorphism** are essential. It is important to know when you need Trait Objects:++### ✅ Use Dynamic Dispatch When:++* You need heterogeneous types in a collection:+```rust+fn all_animals_greeting(animals: Vec<Box<dyn Animal>>) {+ for animal in animals {+ println!("{}", animal.greet())+ }+}+```++* You want runtime plugins or hot-swappable components.+* You want to abstract internals from the caller (library design).+++### ❌ Avoid Dynamic Dispatch When:++* You control the concrete types.+* You are writing code in performance critical paths.+* You can express the same logic in other ways while keeping simplicity, e.g. generics.++## 6.6 🚨 Trait Objects Ergonomics++* Prefer `&dyn Trait` over `Box<dyn Trait>` when you don't need ownership.+* Use `Arc<dyn Trait + Send + Sync>` for shared access across threads.+* Don't use `dyn Trait` if the trait has methods that return `Self`.+* **Avoid boxing too early**. Don't box inside structs unless you are sure it'll be beneficial or is required (recursive).+```rust+// ✅ Use generics when possible+struct Renderer<B: RenderBackend> {+ backend: B+}++// ❌ Premature Boxing+struct Renderer {+ backend: Box<dyn RenderBackend> // Boxing too early+}+```+* If you must expose a `dyn trait` in a public API, `Box` at the boundary, not internally.+* **Object Safety**: You can only create `dyn Traits` from object-safe traits:+ * It has **no generic methods**.+ * It doesn't require `Self: Sized`.+ * All method signatures use `&self`, `&mut self` or `self`.+ ```rust+ // ✅ Object Safe+ trait Runnable {+ fn run(&self);+ }++ // ❌ Not Object Safe+ trait Factory {+ fn create<T>() -> T; // generic methods are not allowed+ }+ ```\ No newline at end of filediff --git a/.claude/skills/rust-best-practices/references/chapter_07.md b/.claude/skills/rust-best-practices/references/chapter_07.mdnew file mode 100644index 0000000..2fe7644--- /dev/null+++ b/.claude/skills/rust-best-practices/references/chapter_07.md@@ -0,0 +1,222 @@+# Chapter 7 - Type State Pattern++Models state at compile time, preventing bugs by making illegal states unrepresentable. It takes advantage of the Rust generics and type system to create sub-types that can only be reached if a certain condition is achieved, making some operations illegal at compile time.++> Recently it became the standard design pattern of Rust programming. However, it is not exclusive to Rust, as it is achievable and has inspired other languages to do the same [swift](https://swiftology.io/articles/typestate/) and [typescript](https://catchts.com/type-state).++## 7.1 What is Type State Pattern?++**Type State Pattern** is a design pattern where you encode different **states** of the system as **types**, not as runtime flags or enums. This allows the compiler to enforce state transitions and prevent illegal actions at compile time. It also improves the developer experience, as developers only have access to certain functions based on the state of the type.++> Invalid states become compile errors instead of runtime bugs.++## 7.2 Why use it?++* Avoids runtime checks for state validity. If you reach certain states, you can make certain assumptions of the data you have.+* Models state transitions as type transitions. This is similar to a state machine, but in compile time.+* Prevents data misuse, e.g. using uninitialized objects.+* Improves API safety and correctness.+* The phantom data field is removed after compilation so no extra memory is allocated.++## 7.3 Simple Example: File State++[Github Example](https://github.com/apollographql/rust-best-practices/tree/main/examples/simple-type-state)+```rust+use std::{io, path::{Path, PathBuf}};++struct FileNotOpened;+struct FileOpened;++#[derive(Debug)]+struct File<State> {+ /// Path to the opened file+ path: PathBuf,+ /// Open `File` handler+ handle: Option<std::fs::File>,+ /// Type state manager+ _state: std::marker::PhantomData<State>+}++impl File<FileNotOpened> {+ /// `open` is the only entry point for this struct.+ /// * When called with a valid path, it will return a `File<FileOpened>` with a valid `handler` and `path`+ /// * `open` serves as an alternative to `new` and `defaults` methods (usable when your struct needs valid data to exist).+ fn open(path: &Path) -> io::Result<File<FileOpened>> {+ // If file is invalid, it will return `std::io::Error`+ let file = std::fs::File::open(path)?;+ Ok(+ File {+ path: path.to_path_buf(),+ // Always valid+ handle: Some(file),+ _state: std::marker::PhantomData::<FileOpened>+ }+ )+ }+}++impl File<FileOpened> {+ /// Reads the content of the `File` as a `String`.+ /// `read` can only be called by state `File<FileOpened>`+ fn read(&mut self) -> io::Result<String> {+ use io::Read;++ let mut content = String::new();+ let Some(handle)= self.handle.as_mut() else {+ unreachable!("Safe to unwrap as state can only be reached when file is open");+ };+ handle.read_to_string(&mut content)?;+ Ok(content)+ }++ /// Returns the valid path buffer.+ fn path(&self) -> &PathBuf {+ &self.path+ }+}+```++## 7.4 Real-World Examples++### Builder Pattern with Compile-Time Guarantees++> Forces the user to **set required fields** before calling `.build()`.++[Github Example](https://github.com/apollographql/rust-best-practices/tree/main/examples/type-state-builder)++A type-state pattern can have more than one associated states:++```rust+use std::marker::PhantomData;++struct Unset;+struct Set;++#[derive(Debug)]+struct Person {+ name: String,+ age: u8,+ email: Option<String>,+}++struct Builder<NameState = Unset, AgeState = Unset> {+ name: Option<String>,+ age: u8,+ email: Option<String>,+ _maker_state: PhantomData<(NameState, AgeState)>,+}++impl Builder<Unset, Unset> {+ const fn new() -> Self {+ Self { name: None, age: 0, email: None, _maker_state: PhantomData }+ }+}++impl<NameState> Builder<NameState, Unset> {+ fn age(self, age: u8) -> Builder<NameState, Set> {+ Builder { age, name: self.name, email: self.email, _maker_state: PhantomData }+ }+}++impl<AgeState> Builder<Unset, AgeState> {+ fn name(self, name: String) -> Builder<Set, AgeState> {+ Builder { name: Some(name), age: self.age, email: self.email, _maker_state: PhantomData }+ }+}++impl<NameState, AgeState> Builder<NameState, AgeState> {+ fn email(self, email: String) -> Self {+ Self { name: self.name, age: self.age, email: Some(email), _maker_state: PhantomData }+ }+}++impl Builder<Set, Set> {+ fn build(self) -> Person {+ Person {+ name: self.name.unwrap_or_else(|| unreachable!("Name is guaranteed to be set")),+ age: self.age,+ email: self.email,+ }+ }+}+```++Although a bit more verbose than a usual builder, this guarantees that all necessary fields are present (note that e-mail is optional field only present in the final builder).++#### Usage:+```rust+// ✅ Valid cases+let person: Person = Builder::new().name("name".to_string()).age(30).build();+let person: Person = Builder::new().age(30).name("name".to_string()).build();+let person: Person = Builder::new().age(30).name("name".to_string()).email("[email protected]".to_string()).build();++// ❌ Invalid cases+let person: Person = Builder::new().name("name".to_string()).build(); // ❌ Compile error: Age required to `build`+let person: Person = Builder::new().age(30).build(); // ❌ Compile error: Name required to `build`+let person: Person = Builder::new().age(30).email("[email protected]".to_string()).build(); // ❌ Compile error: Name required to `build`+let person: Person = Builder::new().age(10).age(15); // ❌ Compile error: Age was already set+let person: Person = Builder::new().build();// ❌ Compile error: Name and Age required to `build`+```++### Crates implementing Builder pattern++Some libraries are already implementing the builder pattern, like [bon-rs](https://docs.rs/bon/latest/bon/)++### Network Protocol State Machine++Illegal transitions like sending a message before connecting **simply don't compile**:++```rust+// Mock example+struct Disconnected;+struct Connected;++struct Client<State> {+ stream: Option<std::net::TcpStream>,+ _state: std::marker::PhantomData<State>+}++impl Client<Disconnected> {+ fn connect(addr: &str) -> std::io::Result<Client<Connected>> {+ let stream = std::net::TcpStream::connect(addr)?;+ Ok(Client {+ stream: Some(stream),+ _state: std::marker::PhantomData::<Connected>+ })+ }+}++impl Client<Connected> {+ fn send(&mut self, msg: &str) {+ use std::io::Write;+ let Some(stream) = self.stream.as_mut() else {+ unreachable!("Stream is guaranteed to be set");+ };+ stream.write_all(msg.as_bytes())+ }+}+```++## 7.5 Pros and Cons++### ✅ Use Type-State Pattern When:+* You want **compile-time state safety**.+* You need to enforce **API constraints**.+* You are writing a library/crate that is heavily dependent on variants.+* You want to replace runtime booleans or enums with **type-safe code paths**.+* You need compile time correctness.++### ❌ Avoid it when:+* Writing trivial states like enums.+* Don't need type-safety.+* When it leads to overcomplicated generics.+* When runtime flexibility is required.++### 🚨 Downsides and Cautions+* Can lead to more **verbose solutions**.+* Can lead to **complex type signatures**.+* May require **unsafe** to return **variant outputs** based on different states.+* May require a bunch of duplication (e.g. same struct field reused).+* PhantomData is not intuitive for beginners and can feel a bit hacky.++> Use this pattern when it **saves bugs, increases safety or simplifies logic**, not just for cleverness.\ No newline at end of filediff --git a/.claude/skills/rust-best-practices/references/chapter_08.md b/.claude/skills/rust-best-practices/references/chapter_08.mdnew file mode 100644index 0000000..ebdd04a--- /dev/null+++ b/.claude/skills/rust-best-practices/references/chapter_08.md@@ -0,0 +1,252 @@+# Chapter 8 - Comments vs Documentation++> Clear code beats clear comments. However, when the why isn't obvious, comment it plainly - or link to where you can read more context.++## 8.1 Comments vs Documentation: Know the Difference++| Purpose | Use `// comment` | Use `/// doc` or `//! crate doc` |+|-------------- |------------------------------------------- |---------------------------------------------------------------- |+| Describe Why | ✅ Yes - explains tricky reasoning | ❌ Not for documentation |+| Describe API | ❌ Not useful | ✅ Yes - public interfaces, usage, details, errors, panics |+| Maintainable | 🚨 Often becomes obsolete and hard to reason | ✅ Tied to code, appears in generated docs and can run test cases |+| Visibility | Local development only | Exported to users and tools like `cargo doc` |++## 8.2 When to use comments++Use `//` comments (double slashed) when something can't be expressed clearly in code, like:+* **Safety Guarantees**, some of which can be better expressed with code conditionals.+* Workarounds or **Optimizations**.+* Legacy or **platform-specific** behaviors. Some of them can be expressed with `#[cfg(..)]`.+* Links to **Design Docs** or **ADRs**.+* Assumptions or **gotchas** that aren't obvious.++> Name your comments! For example, a comment regarding a safety guarantee should start with `// SAFETY: ...`.++### ✅ Good comment:+```rust+// SAFETY: `ptr` is guaranteed to be non-null and aligned by caller+unsafe { std::ptr::copy_nonoverlapping(src, dst, len); }+```++### ✅ Design context comment:+```rust+// CONTEXT: Reuse root cert store across subgraphs to avoid duplicate OS calls:+// [ADR-12](link/to/adr-12): TLS Performance on MacOS+```++## 8.3 When comments get in the way++Avoid comments that:+* Restate obvious things (`// increment i by 1 for the next loop`).+* Can grow stale over time.+* `TODO`s without actions (links to some versioned issue).+* Could be replaced by better naming or smaller functions.++### ❌ Bad comment:+```rust+fn compute(counter: &mut usize) {+ // increment by 1+ *counter += 1;+}+```++### ❌ Too long or outdated+```rust+// Originally written in 2028 for some now-defunct platform+```++## 8.4 Don't Write Living Documentation (living comments)++Comments as a "living documentation" is a **dangerous myth**, as comments are **not free**:+* They **rot** - nobody compiles comments.+* They **mislead** - readers usually assume they are true with no critique, e.g. "the other developer knows this code better than I do".+* They **go stale** - unless maintained with the code, they become irrelevant.+* They are **noisy** - comments can clutter your code with multiple unnecessary lines.++If something deserves to live beyond a PR, put it in:+* An **ADR** (Architectural Design Record).+* A Design Document.+* Document it **in code** by using types, doc comments, examples, renaming code blocks into cleaner functions.+* Add tests to cover and explain the change.++> ### 🚨 If you find a comment, **read it in context**. Does it still make sense? If not, remove or update it, or ask for help. Comments should bother you.++## 8.5 Replace Comments with Code++Instead of long commented blocks, break logic into named helper functions:++#### ❌ Commented code block:+```rust+fn save_user(&self) -> Result<(), MyError> {+ // check if the user is authenticated+ if self.is_authenticated() {+ // serialize user data+ let data = serde_json::to_string(self)?;+ // write to file+ std::fs::write(self.path(), data)?;+ }+}++```+**✅ Extract for clarity**:++```rust+fn save_auth_user(&self) -> Result<PathBuf, MyError> {+ if self.is_authenticated() {+ let path = self.path();+ let serialized_user = serde_json::to_string(self)?;+ std::fs::write(path, serialized_user)?;+ Ok(path)+ } else {+ Err(MyError::UserNotAuthenticated)+ }+}+```++> ❗ Extract when the **name adds meaning** -- not to deduplicate a couple of similar-looking lines. See [Chapter 1, §1.8](./chapter_01.md#18-when-to-extract-a-function-and-when-not-to) for when duplication is the better trade-off.++## 8.6 `TODO` should become issues++Don't leave `// TODO:` scattered around the codebase with no owner. Instead:+1. File Github Issue or Jira Ticket. (Prefer github issues on public repositories).+2. Reference the issue in the code:++```rust+// TODO(issue #42): Remove workaround after bugfix+```++This makes `TODO`s trackable, actionable and visible to everyone.++## 8.7 When to use doc comments++Use `///` doc comments to document:+* All **public functions, structs, traits, enums**.+* Their purpose, their usage and their behaviors.+* Anything developers need to understand how to use it correctly.+* Add context that related to `Errors` and `Panics`.+* Plenty of examples.++### ✅ Good doc comment:++```rust+/// Loads [`User`] profile from disk+///+/// # Error+/// - Returns [`MyError`] if the file is missing [`MyError::FileNotFound`].+/// - Returns [`MyError`] if the content is an invalid Json, [`MyError::InvalidJson`].+fn load_user(path: &Path) -> Result<User, MyError> {...}+```++**Doc comments can also include examples, links and even tests:**++```rust+/// Returns the square of the integer part of any number.+/// Square is limited to `u128`.+///+/// # Examples+///+/// ```rust+/// assert_eq!(square(4.3), 16)+/// ```+fn square(x: impl ToInt) -> u128 { ... }+```++## 8.8 Documentation in Rust: How, When and Why++Rust provides **first-class documentation tooling** via rustdoc, which makes documenting your code a key part of writing idiomatic and maintainable rust. There are doc specific lints to help with documentation, like:++| Lint | Description |+|-------------- |------------------------------------------- |+| [missing_docs](https://doc.rust-lang.org/rustdoc/lints.html#missing_docs) | Warns that a public functions, struct, const, enum has missing documentation |+| [broken_intra_doc_links](https://doc.rust-lang.org/rustdoc/lints.html#broken_intra_doc_links) | Detects if an internal documentation link is broken. Especially useful when things are renamed. |+| [empty_docs](https://rust-lang.github.io/rust-clippy/master/#empty_docs) | Disallow empty docs - preventing bypass of `missing_docs` |+| [missing_panics_doc](https://rust-lang.github.io/rust-clippy/master/#missing_panics_doc) | Warns that documentation should have a `# Panics` section if function can panic |+| [missing_errors_doc](https://rust-lang.github.io/rust-clippy/master/#missing_errors_doc) | Warns that documentation should have a `# Errors` section if function returns a `Result` explaining `Err` conditions |+| [missing_safety_doc](https://rust-lang.github.io/rust-clippy/master/#missing_safety_doc) | Warns that documentation should have a `# Safety` section if public facing functions have visible unsafe blocks |+++### Difference between `///` and `//!`++| Style | Used for | Scope |Example |+|---------- |------------------------------ |------------------------------------------- |---------------------------------------------------------------- |+| `///` | Line doc comment | Public items like struct, fn, enum, consts | Documenting, giving context and usage to `fn`, `struct`, `enum`, etc |+| `//!` | Module level doc comment | Modules or entire crates | Explaining crate/module purpose with common use cases and quickstart |++### `///` Item level documentation++Use `///` for functions, structs, traits, enums, const, etc:++```rust+/// Adds two numbers together.+///+/// # Examples+///+/// ```+/// let result = my_crate::add(2, 3);+/// assert_eq!(result, 5);+/// ```+pub fn add(a: i32, b: i32) -> i32 {+ a + b+}+```+* ✅ Write clear and descriptive **What it does** and **how to use it**.+* ✅ Use `# Examples` section to better explain **how to use it**.+* ✅ Prefer writing examples that can be tested via `cargo test`, even if you have to hide their output with starting `#`:+```rust+/// ```+/// let result = my_crate::add(2, 3);+/// # assert_eq!(result, 5);+/// ```+```+* ✅ Use `# Panics`, `# Errors` and `# Safety` sections when relevant.+* Add relevant context to the type.++### `//!` Module/Crate level Documentation++Use `//!` when you want to document the **purpose of a module or a crate**. It is placed at the top of a `lib.rs` or `mod.rs` file, for example `engine/mod.rs`:+```rust+//! This module implements a custom chess engine.+//!+//! It handles board state, move generation and check detection.+//!+//! # Example+//! ```+//! let board = chess::engine::Board::default();+//! assert!(board.is_valid());+//! ```+```++## 8.9 Checklist for Documentation coverage++📦 Crate-Level (lib.rs)+- [ ] `//!` doc at top explains **what the crate does**, and **what problems it solves**.+- [ ] Includes crate-level `# Examples` or pointers to modules.+📁 Modules (mod.rs or inline)+- [ ] `//!` doc explains **what this module is for**, its **exports**, and **invariants**.+- [ ] Avoid repeating doc comments on re-exported items unless clarification is needed.+🧱 Structs, Enums, Traits+- `///` doc explains:+ - [ ] The role this type plays.+ - [ ] Invariants or expectations.+ - [ ] Example construction or usage.+- [ ] Consider using [`#[non_exhaustive]`](https://doc.rust-lang.org/reference/attributes/type_system.html#the-non_exhaustive-attribute) if external users may match on it.+🔧 Functions and Methods+- `///` doc covers:+ - [ ] What it does.+ - [ ] Parameters and their meaning.+ - [ ] Return value behavior.+ - [ ] Edge cases (`# Panics`, `# Errors`).+ - [ ] Usage example, `# Examples`.+📑 Traits+- [ ] Explain the **purpose** of the trait (marker? dynamic dispatch?).+- [ ] Doc for each method -- include **when/why** to implement it.+- [ ] Document clearly default implemented methods and when to override.+📦 Public Constants+- [ ] Document what they configure and when you'd want to use them.++### 📌 Best Practices+* ✅ Use examples generously -- they double as test cases.+* ✅ Prefer clarity over formality -- it's for humans, not machines.+* ✅ Prefer doc comments to explain usage, and leave implementation details to code comments if needed.+* ✅ Use `cargo doc --open` to check your output often.+* ✅ Add `#![deny(missing_docs)]` and other relevant doc lints in top-level modules if you want to enforce full doc coverage.\ No newline at end of filediff --git a/.claude/skills/rust-best-practices/references/chapter_09.md b/.claude/skills/rust-best-practices/references/chapter_09.mdnew file mode 100644index 0000000..f9453b9--- /dev/null+++ b/.claude/skills/rust-best-practices/references/chapter_09.md@@ -0,0 +1,256 @@+# Chapter 9 - Understanding Pointers++Many higher level languages hide memory management, typically **passing by value** (copy data) or **passing by reference** (reference to shared data) without worrying about allocation, heap, stack, ownership and lifetimes, it is all delegated to the garbage collector or VM. Here is a comparison on this topic between a few languages:++### 📌 Language Comparison++| Language | Value Types | Reference/Pointer Types | Async Model & Types | Manual Memory |+|------------ |------------------------------------- |----------------------------------------------------------- |---------------------------------------------------------------------------- |------------------------------ |+| Python | None | Everything is a reference | async def, await, Task, coroutines and asyncio.Future | ❌ Not Allowed |+| Javascript | Primitives | Objects | `async/await`, `Promise`, `setTimeout`. single threaded event loop | ❌ Not Allowed |+| Java | Primitives | Objects | `Future<T>`, threads, Loom (green threads) | ❌ Almost none & not recommended |+| Go | Values are copied unless using `&T` | Pointers (`*T`, `&T`), escape analysis | goroutines, `channels`, `sync.Mutex`, `context.Context` | ⚠️ Limited |+| C | Primitives and structs supported | Raw pointers `T*` and `*void` | Threads, event loops (`libuv`, `libevent`) | ✅ Fully |+| C++ | Primitives and references | Raw `T*` and smart pointers `shared_ptr` and `unique_ptr` | threads, `std::future`, `std::async`, (since c++ 20 `co_await/coroutines`) | ✅ Mostly |+| Rust | Primitives, Arrays, `impl Copy` | `&T`, `&mut T`, `Box<T>`, `Arc<T>` | `async/await`, `tokio`, `Future`, `JoinHandle`, `Send + Sync` | ✅🔒 Safe and Explicit |++## 9.1 Thread Safety++Rust tracks pointers using `Send` and `Sync` traits:+- `Send` means data can move across threads.+- `Sync` means data can be referenced from multiple threads.++> A pointer is thread-safe only if the data behind it is.++| Pointer Type | Short Description | Send + Sync? | Main Use |+|---------------- |--------------------------------------------------------------------------- |-------------------------------------- |------------ |+| `&T` | Shared reference | Yes | Shared access |+| `&mut T` | Exclusive mutable reference | No, not Send | Exclusive mutation |+| `Box<T>` | Heap-allocated owning pointer | Yes, if T: Send + Sync | Heap allocation |+| `Rc<T>` | Single-threaded ref counted pointer | No, neither | Multiple owners (single-thread) |+| `Arc<T>` | Atomic ref counter pointer | Yes | Multiple owners (multi-thread) |+| `Cell<T>` | Interior mutability for copy types | No, not Sync | Shared mutable, non-threaded |+| `RefCell<T>` | Interior mutability (dynamic borrow checker) | No, not Sync | Shared mutable, non-threaded |+| `Mutex<T>` | Thread-safe interior mutability with exclusive access | Yes | Shared mutable, threaded |+| `RwLock<T>` | Thread-safe shared readonly access OR exclusive mutable access | Yes | Shared mutable, threaded |+| `OnceCell<T>` | Single-thread one-time initialization container (interior mutability ONCE) | No, not Sync | Simple lazy value initialization |+| `LazyCell<T>` | A lazy version of `OnceCell<T>` that calls function closure to initialize | No, not Sync | Complex lazy value initialization+| `OnceLock<T>` | Thread-safe version of `OnceCell<T>` | Yes | Multi-thread single init |+| `LazyLock<T>` | Thread-safe version of `LazyCell<T>` | Yes | Multi-thread complex init |+| `*const T/*mut T` | Raw Pointers | No, user must ensure safety manually | Raw memory / FFI |++## 9.2 When to use pointers:++### `&T` - Shared Borrow:++Probably the most common type in a Rust code base, it is **Safe, with no mutation** and allows **multiple readers**.++```rust+let data: String = String::from_str("this is a string").unwrap();++print_len(&data);+print_capacity(&data);+print_bytes(&data);++fn print_len(s: &str) {+ println!("{}", s.len())+}++fn print_capacity(s: &String) {+ println!("{}", s.capacity())+}++fn print_bytes(s: &String) {+ println!("{:?}", s.as_bytes())+}+```+### `&mut T` - Exclusive Borrow:++Probably the most common *mutable* type in a Rust code base, it is **Safe, but only allows one mutable borrow at a time**.++```rust+let mut data: String = String::from_str("this is a string").unwrap();+mark_update(&mut data);++fn mark_update(s: &mut String) {+ s.push_str("_update");+}+```++### [`Box<T>`](https://doc.rust-lang.org/std/boxed/struct.Box.html) - Heap Allocated++Single-owner heap-allocated data, great for recursive types and large structs.++```rust+pub enum MySubBoxedEnum<T> {+ Single(T),+ Double(Box<MySubBoxedEnum<T>>, Box<MySubBoxedEnum<T>>),+ Multi(Vec<T>), // Note that Vec is already a boxed value+}+```++### [`Rc<T>`](https://doc.rust-lang.org/std/rc/struct.Rc.html) - Reference Counter (single-thread)++You need multiple references to data in a single thread. Most common example is linked-list implementation.++### [`Arc<T>`](https://doc.rust-lang.org/std/sync/struct.Arc.html) - Atomic Reference Counter (multi-thread)++You need multiple references to data in multiple threads. Most common use case is sharing readonly Vec across thread with `Arc<[T]>` and wrapping a `Mutex` so it can be easily shared across threads, `Arc<Mutex<T>>`.++### [`RefCell<T>`](https://doc.rust-lang.org/std/cell/struct.RefCell.html) - Runtime checked interior mutability++Used when you need shared access and the ability to mutate data, borrow rules are enforced at runtime. **It may panic!**.++```rust+use std::cell::RefCell;+let x = RefCell::new(42);+*x.borrow_mut() += 1;++assert_eq!(&*x.borrow(), 42, "Not meaning of life");+```++Panic example:+```rust+use std::cell::RefCell;+let x = RefCell::new(42);++let borrow = x.borrow();++let mutable = x.borrow_mut();+```++### [`Cell<T>`](https://doc.rust-lang.org/std/cell/struct.Cell.html) - Copy-only interior mutability++Somewhat the fast and safe version of `RefCell`, but it is limited to types that implement the `Copy` trait:++```rust+use std::cell::Cell;++struct SomeStruct {+ regular_field: u8,+ special_field: Cell<u8>,+}++let my_struct = SomeStruct {+ regular_field: 0,+ special_field: Cell::new(1),+};++let new_value = 100;++// ERROR: `my_struct` is immutable+// my_struct.regular_field = new_value;++// WORKS: although `my_struct` is immutable, `special_field` is a `Cell`,+// which can always be mutated with copy values+my_struct.special_field.set(new_value);+assert_eq!(my_struct.special_field.get(), new_value);+```++### [`Mutex<T>`](https://doc.rust-lang.org/std/sync/struct.Mutex.html) - Thread-safe mutability++An exclusive access pointer that allows a thread to read/write the data contained inside. It is usually wrapped in an `Arc` to allow shared access to the Mutex.++### [`RwLock<T>`](https://doc.rust-lang.org/std/sync/struct.RwLock.html) - Thread-safe mutability++Similar to a `Mutex`, but it allows multiple threads to read it OR a single thread to write. It is usually wrapped in an `Arc` to allow shared access to the RwLock.+++### [`*const T/*mut T`](https://doc.rust-lang.org/std/primitive.pointer.html) - Raw pointers++Inherently **unsafe** and necessary for FFI. Rust makes their usage explicit to avoid accidental misuse and unwilling manual memory management.++```rust+let x = 5;+let ptr = &x as *const i32+unsafe {+ println!("PTR is {}", *ptr)+}+```++### [`OnceCell`](https://doc.rust-lang.org/std/cell/struct.OnceCell.html) - Single-thread single initialization container++Most useful when you need to share a configuration between multiple data structures.++```rust+use std::{cell::OnceCell, rc::Rc};++#[derive(Debug, Default)]+struct MyStruct {+ distance: usize,+ root: Option<Rc<OnceCell<MyStruct>>>,+}++fn main() {+ let root = MyStruct::default();+ let root_cell = Rc::new(OnceCell::new());+ if let Err(previous) = root_cell.set(root) {+ eprintln!("Previous Root {previous:?}");+ }+ let child_1 = MyStruct{+ distance: 1,+ root: Some(root_cell.clone())+ };++ let child_2 = MyStruct{+ distance: 2,+ root: Some(root_cell.clone())+ };+++ println!("Child 1: {child_1:?}");+ println!("Child 2: {child_2:?}");+}+```++### [`LazyCell`](https://doc.rust-lang.org/std/cell/struct.LazyCell.html) - Lazy initialization of `OnceCell`++Useful when the initialized data can be delayed to when it is actually being called.++### [`OnceLock`](https://doc.rust-lang.org/std/sync/struct.OnceLock.html) - thread-safe `OnceCell`++Useful when you need a `static` value.++```rust+use std::sync::OnceLock;++static CELL: OnceLock<usize> = OnceLock::new();++// `OnceLock` has not been written to yet.+assert!(CELL.get().is_none());++// Spawn a thread and write to `OnceLock`.+std::thread::spawn(|| {+ let value = CELL.get_or_init(|| 12345);+ assert_eq!(value, &12345);+})+.join()+.unwrap();++// `OnceLock` now contains the value.+assert_eq!(+ CELL.get(),+ Some(&12345),+);+```++### [`LazyLock`](https://doc.rust-lang.org/std/sync/struct.LazyLock.html) - thread-safe `LazyCell`++Similar to `OnceLock`, but the static value is a bit more complex to initialize.++```rust+use std::sync::LazyLock;++static CONFIG: LazyLock<HashMap<String, T>> = LazyLock::new(|| {+ let data = read_config();+ let mut config: HashMap<String, T> = data.into();+ config.insert("special_case", T::Default());+ config+});++let _ = &*CONFIG;+```++## References+- [Mara Bos - Rust Atomics and Locks](https://marabos.nl/atomics/)+- [Semicolon video on pointers](https://www.youtube.com/watch?v=Ag_6Q44PBNs)\ No newline at end of filediff --git a/.claude/skills/vercel-react-best-practices/AGENTS.md b/.claude/skills/vercel-react-best-practices/AGENTS.mdnew file mode 100644index 0000000..4e340a5--- /dev/null+++ b/.claude/skills/vercel-react-best-practices/AGENTS.md@@ -0,0 +1,3810 @@+# React Best Practices++**Version 1.0.0**+Vercel Engineering+January 2026++> **Note:**+> This document is mainly for agents and LLMs to follow when maintaining,+> generating, or refactoring React and Next.js codebases. Humans+> may also find it useful, but guidance here is optimized for automation+> and consistency by AI-assisted workflows.++---++## Abstract++Comprehensive performance optimization guide for React and Next.js applications, designed for AI agents and LLMs. Contains 40+ rules across 8 categories, prioritized by impact from critical (eliminating waterfalls, reducing bundle size) to incremental (advanced patterns). Each rule includes detailed explanations, real-world examples comparing incorrect vs. correct implementations, and specific impact metrics to guide automated refactoring and code generation.++---++## Table of Contents++1. [Eliminating Waterfalls](#1-eliminating-waterfalls) — **CRITICAL**+ - 1.1 [Check Cheap Conditions Before Async Flags](#11-check-cheap-conditions-before-async-flags)+ - 1.2 [Defer Await Until Needed](#12-defer-await-until-needed)+ - 1.3 [Dependency-Based Parallelization](#13-dependency-based-parallelization)+ - 1.4 [Prevent Waterfall Chains in API Routes](#14-prevent-waterfall-chains-in-api-routes)+ - 1.5 [Promise.all() for Independent Operations](#15-promiseall-for-independent-operations)+ - 1.6 [Strategic Suspense Boundaries](#16-strategic-suspense-boundaries)+2. [Bundle Size Optimization](#2-bundle-size-optimization) — **CRITICAL**+ - 2.1 [Avoid Barrel File Imports](#21-avoid-barrel-file-imports)+ - 2.2 [Conditional Module Loading](#22-conditional-module-loading)+ - 2.3 [Defer Non-Critical Third-Party Libraries](#23-defer-non-critical-third-party-libraries)+ - 2.4 [Dynamic Imports for Heavy Components](#24-dynamic-imports-for-heavy-components)+ - 2.5 [Prefer Statically Analyzable Paths](#25-prefer-statically-analyzable-paths)+ - 2.6 [Preload Based on User Intent](#26-preload-based-on-user-intent)+3. [Server-Side Performance](#3-server-side-performance) — **HIGH**+ - 3.1 [Authenticate Server Actions Like API Routes](#31-authenticate-server-actions-like-api-routes)+ - 3.2 [Avoid Duplicate Serialization in RSC Props](#32-avoid-duplicate-serialization-in-rsc-props)+ - 3.3 [Avoid Shared Module State for Request Data](#33-avoid-shared-module-state-for-request-data)+ - 3.4 [Cross-Request LRU Caching](#34-cross-request-lru-caching)+ - 3.5 [Hoist Static I/O to Module Level](#35-hoist-static-io-to-module-level)+ - 3.6 [Minimize Serialization at RSC Boundaries](#36-minimize-serialization-at-rsc-boundaries)+ - 3.7 [Parallel Data Fetching with Component Composition](#37-parallel-data-fetching-with-component-composition)+ - 3.8 [Parallel Nested Data Fetching](#38-parallel-nested-data-fetching)+ - 3.9 [Per-Request Deduplication with React.cache()](#39-per-request-deduplication-with-reactcache)+ - 3.10 [Use after() for Non-Blocking Operations](#310-use-after-for-non-blocking-operations)+4. [Client-Side Data Fetching](#4-client-side-data-fetching) — **MEDIUM-HIGH**+ - 4.1 [Deduplicate Global Event Listeners](#41-deduplicate-global-event-listeners)+ - 4.2 [Use Passive Event Listeners for Scrolling Performance](#42-use-passive-event-listeners-for-scrolling-performance)+ - 4.3 [Use SWR for Automatic Deduplication](#43-use-swr-for-automatic-deduplication)+ - 4.4 [Version and Minimize localStorage Data](#44-version-and-minimize-localstorage-data)+5. [Re-render Optimization](#5-re-render-optimization) — **MEDIUM**+ - 5.1 [Calculate Derived State During Rendering](#51-calculate-derived-state-during-rendering)+ - 5.2 [Defer State Reads to Usage Point](#52-defer-state-reads-to-usage-point)+ - 5.3 [Do not wrap a simple expression with a primitive result type in useMemo](#53-do-not-wrap-a-simple-expression-with-a-primitive-result-type-in-usememo)+ - 5.4 [Don't Define Components Inside Components](#54-dont-define-components-inside-components)+ - 5.5 [Extract Default Non-primitive Parameter Value from Memoized Component to Constant](#55-extract-default-non-primitive-parameter-value-from-memoized-component-to-constant)+ - 5.6 [Extract to Memoized Components](#56-extract-to-memoized-components)+ - 5.7 [Narrow Effect Dependencies](#57-narrow-effect-dependencies)+ - 5.8 [Put Interaction Logic in Event Handlers](#58-put-interaction-logic-in-event-handlers)+ - 5.9 [Split Combined Hook Computations](#59-split-combined-hook-computations)+ - 5.10 [Subscribe to Derived State](#510-subscribe-to-derived-state)+ - 5.11 [Use Functional setState Updates](#511-use-functional-setstate-updates)+ - 5.12 [Use Lazy State Initialization](#512-use-lazy-state-initialization)+ - 5.13 [Use Transitions for Non-Urgent Updates](#513-use-transitions-for-non-urgent-updates)+ - 5.14 [Use useDeferredValue for Expensive Derived Renders](#514-use-usedeferredvalue-for-expensive-derived-renders)+ - 5.15 [Use useRef for Transient Values](#515-use-useref-for-transient-values)+6. [Rendering Performance](#6-rendering-performance) — **MEDIUM**+ - 6.1 [Animate SVG Wrapper Instead of SVG Element](#61-animate-svg-wrapper-instead-of-svg-element)+ - 6.2 [CSS content-visibility for Long Lists](#62-css-content-visibility-for-long-lists)+ - 6.3 [Hoist Static JSX Elements](#63-hoist-static-jsx-elements)+ - 6.4 [Optimize SVG Precision](#64-optimize-svg-precision)+ - 6.5 [Prevent Hydration Mismatch Without Flickering](#65-prevent-hydration-mismatch-without-flickering)+ - 6.6 [Suppress Expected Hydration Mismatches](#66-suppress-expected-hydration-mismatches)+ - 6.7 [Use Activity Component for Show/Hide](#67-use-activity-component-for-showhide)+ - 6.8 [Use defer or async on Script Tags](#68-use-defer-or-async-on-script-tags)+ - 6.9 [Use Explicit Conditional Rendering](#69-use-explicit-conditional-rendering)+ - 6.10 [Use React DOM Resource Hints](#610-use-react-dom-resource-hints)+ - 6.11 [Use useTransition Over Manual Loading States](#611-use-usetransition-over-manual-loading-states)+7. [JavaScript Performance](#7-javascript-performance) — **LOW-MEDIUM**+ - 7.1 [Avoid Layout Thrashing](#71-avoid-layout-thrashing)+ - 7.2 [Build Index Maps for Repeated Lookups](#72-build-index-maps-for-repeated-lookups)+ - 7.3 [Cache Property Access in Loops](#73-cache-property-access-in-loops)+ - 7.4 [Cache Repeated Function Calls](#74-cache-repeated-function-calls)+ - 7.5 [Cache Storage API Calls](#75-cache-storage-api-calls)+ - 7.6 [Combine Multiple Array Iterations](#76-combine-multiple-array-iterations)+ - 7.7 [Defer Non-Critical Work with requestIdleCallback](#77-defer-non-critical-work-with-requestidlecallback)+ - 7.8 [Early Length Check for Array Comparisons](#78-early-length-check-for-array-comparisons)+ - 7.9 [Early Return from Functions](#79-early-return-from-functions)+ - 7.10 [Hoist RegExp Creation](#710-hoist-regexp-creation)+ - 7.11 [Use flatMap to Map and Filter in One Pass](#711-use-flatmap-to-map-and-filter-in-one-pass)+ - 7.12 [Use Loop for Min/Max Instead of Sort](#712-use-loop-for-minmax-instead-of-sort)+ - 7.13 [Use Set/Map for O(1) Lookups](#713-use-setmap-for-o1-lookups)+ - 7.14 [Use toSorted() Instead of sort() for Immutability](#714-use-tosorted-instead-of-sort-for-immutability)+8. [Advanced Patterns](#8-advanced-patterns) — **LOW**+ - 8.1 [Do Not Put Effect Events in Dependency Arrays](#81-do-not-put-effect-events-in-dependency-arrays)+ - 8.2 [Initialize App Once, Not Per Mount](#82-initialize-app-once-not-per-mount)+ - 8.3 [Store Event Handlers in Refs](#83-store-event-handlers-in-refs)+ - 8.4 [useEffectEvent for Stable Callback Refs](#84-useeffectevent-for-stable-callback-refs)++---++## 1. Eliminating Waterfalls++**Impact: CRITICAL**++Waterfalls are the #1 performance killer. Each sequential await adds full network latency. Eliminating them yields the largest gains.++### 1.1 Check Cheap Conditions Before Async Flags++**Impact: HIGH (avoids unnecessary async work when a synchronous guard already fails)**++When a branch uses `await` for a flag or remote value and also requires a **cheap synchronous** condition (local props, request metadata, already-loaded state), evaluate the cheap condition **first**. Otherwise you pay for the async call even when the compound condition can never be true.++This is a specialization of [Defer Await Until Needed](./async-defer-await.md) for `flag && cheapCondition` style checks.++**Incorrect:**++```typescript+const someFlag = await getFlag()++if (someFlag && someCondition) {+ // ...+}+```++**Correct:**++```typescript+if (someCondition) {+ const someFlag = await getFlag()+ if (someFlag) {+ // ...+ }+}+```++This matters when `getFlag` hits the network, a feature-flag service, or `React.cache` / DB work: skipping it when `someCondition` is false removes that cost on the cold path.++Keep the original order if `someCondition` is expensive, depends on the flag, or you must run side effects in a fixed order.++### 1.2 Defer Await Until Needed++**Impact: HIGH (avoids blocking unused code paths)**++Move `await` operations into the branches where they're actually used to avoid blocking code paths that don't need them.++**Incorrect: blocks both branches**++```typescript+async function handleRequest(userId: string, skipProcessing: boolean) {+ const userData = await fetchUserData(userId)++ if (skipProcessing) {+ // Returns immediately but still waited for userData+ return { skipped: true }+ }++ // Only this branch uses userData+ return processUserData(userData)+}+```++**Correct: only blocks when needed**++```typescript+async function handleRequest(userId: string, skipProcessing: boolean) {+ if (skipProcessing) {+ // Returns immediately without waiting+ return { skipped: true }+ }++ // Fetch only when needed+ const userData = await fetchUserData(userId)+ return processUserData(userData)+}+```++**Another example: early return optimization**++```typescript+// Incorrect: always fetches permissions+async function updateResource(resourceId: string, userId: string) {+ const permissions = await fetchPermissions(userId)+ const resource = await getResource(resourceId)++ if (!resource) {+ return { error: 'Not found' }+ }++ if (!permissions.canEdit) {+ return { error: 'Forbidden' }+ }++ return await updateResourceData(resource, permissions)+}++// Correct: fetches only when needed+async function updateResource(resourceId: string, userId: string) {+ const resource = await getResource(resourceId)++ if (!resource) {+ return { error: 'Not found' }+ }++ const permissions = await fetchPermissions(userId)++ if (!permissions.canEdit) {+ return { error: 'Forbidden' }+ }++ return await updateResourceData(resource, permissions)+}+```++This optimization is especially valuable when the skipped branch is frequently taken, or when the deferred operation is expensive.++For `await getFlag()` combined with a cheap synchronous guard (`flag && someCondition`), see [Check Cheap Conditions Before Async Flags](./async-cheap-condition-before-await.md).++### 1.3 Dependency-Based Parallelization++**Impact: CRITICAL (2-10× improvement)**++For operations with partial dependencies, use `better-all` to maximize parallelism. It automatically starts each task at the earliest possible moment.++**Incorrect: profile waits for config unnecessarily**++```typescript+const [user, config] = await Promise.all([+ fetchUser(),+ fetchConfig()+])+const profile = await fetchProfile(user.id)+```++**Correct: config and profile run in parallel**++```typescript+import { all } from 'better-all'++const { user, config, profile } = await all({+ async user() { return fetchUser() },+ async config() { return fetchConfig() },+ async profile() {+ return fetchProfile((await this.$.user).id)+ }+})+```++**Alternative without extra dependencies:**++```typescript+const userPromise = fetchUser()+const profilePromise = userPromise.then(user => fetchProfile(user.id))++const [user, config, profile] = await Promise.all([+ userPromise,+ fetchConfig(),+ profilePromise+])+```++We can also create all the promises first, and do `Promise.all()` at the end.++Reference: [https://github.com/shuding/better-all](https://github.com/shuding/better-all)++### 1.4 Prevent Waterfall Chains in API Routes++**Impact: CRITICAL (2-10× improvement)**++In API routes and Server Actions, start independent operations immediately, even if you don't await them yet.++**Incorrect: config waits for auth, data waits for both**++```typescript+export async function GET(request: Request) {+ const session = await auth()+ const config = await fetchConfig()+ const data = await fetchData(session.user.id)+ return Response.json({ data, config })+}+```++**Correct: auth and config start immediately**++```typescript+export async function GET(request: Request) {+ const sessionPromise = auth()+ const configPromise = fetchConfig()+ const session = await sessionPromise+ const [config, data] = await Promise.all([+ configPromise,+ fetchData(session.user.id)+ ])+ return Response.json({ data, config })+}+```++For operations with more complex dependency chains, use `better-all` to automatically maximize parallelism (see Dependency-Based Parallelization).++### 1.5 Promise.all() for Independent Operations++**Impact: CRITICAL (2-10× improvement)**++When async operations have no interdependencies, execute them concurrently using `Promise.all()`.++**Incorrect: sequential execution, 3 round trips**++```typescript+const user = await fetchUser()+const posts = await fetchPosts()+const comments = await fetchComments()+```++**Correct: parallel execution, 1 round trip**++```typescript+const [user, posts, comments] = await Promise.all([+ fetchUser(),+ fetchPosts(),+ fetchComments()+])+```++### 1.6 Strategic Suspense Boundaries++**Impact: HIGH (faster initial paint)**++Instead of awaiting data in async components before returning JSX, use Suspense boundaries to show the wrapper UI faster while data loads.++**Incorrect: wrapper blocked by data fetching**++```tsx+async function Page() {+ const data = await fetchData() // Blocks entire page++ return (+ <div>+ <div>Sidebar</div>+ <div>Header</div>+ <div>+ <DataDisplay data={data} />+ </div>+ <div>Footer</div>+ </div>+ )+}+```++The entire layout waits for data even though only the middle section needs it.++**Correct: wrapper shows immediately, data streams in**++```tsx+function Page() {+ return (+ <div>+ <div>Sidebar</div>+ <div>Header</div>+ <div>+ <Suspense fallback={<Skeleton />}>+ <DataDisplay />+ </Suspense>+ </div>+ <div>Footer</div>+ </div>+ )+}++async function DataDisplay() {+ const data = await fetchData() // Only blocks this component+ return <div>{data.content}</div>+}+```++Sidebar, Header, and Footer render immediately. Only DataDisplay waits for data.++**Alternative: share promise across components**++```tsx+function Page() {+ // Start fetch immediately, but don't await+ const dataPromise = fetchData()++ return (+ <div>+ <div>Sidebar</div>+ <div>Header</div>+ <Suspense fallback={<Skeleton />}>+ <DataDisplay dataPromise={dataPromise} />+ <DataSummary dataPromise={dataPromise} />+ </Suspense>+ <div>Footer</div>+ </div>+ )+}++function DataDisplay({ dataPromise }: { dataPromise: Promise<Data> }) {+ const data = use(dataPromise) // Unwraps the promise+ return <div>{data.content}</div>+}++function DataSummary({ dataPromise }: { dataPromise: Promise<Data> }) {+ const data = use(dataPromise) // Reuses the same promise+ return <div>{data.summary}</div>+}+```++Both components share the same promise, so only one fetch occurs. Layout renders immediately while both components wait together.++**When NOT to use this pattern:**++- Critical data needed for layout decisions (affects positioning)++- SEO-critical content above the fold++- Small, fast queries where suspense overhead isn't worth it++- When you want to avoid layout shift (loading → content jump)++**Trade-off:** Faster initial paint vs potential layout shift. Choose based on your UX priorities.++---++## 2. Bundle Size Optimization++**Impact: CRITICAL**++Reducing initial bundle size improves Time to Interactive and Largest Contentful Paint.++### 2.1 Avoid Barrel File Imports++**Impact: CRITICAL (200-800ms import cost, slow builds)**++Import directly from source files instead of barrel files to avoid loading thousands of unused modules. **Barrel files** are entry points that re-export multiple modules (e.g., `index.js` that does `export * from './module'`).++Popular icon and component libraries can have **up to 10,000 re-exports** in their entry file. For many React packages, **it takes 200-800ms just to import them**, affecting both development speed and production cold starts.++**Why tree-shaking doesn't help:** When a library is marked as external (not bundled), the bundler can't optimize it. If you bundle it to enable tree-shaking, builds become substantially slower analyzing the entire module graph.++**Incorrect: imports entire library**++```tsx+import { Check, X, Menu } from 'lucide-react'+// Loads 1,583 modules, takes ~2.8s extra in dev+// Runtime cost: 200-800ms on every cold start++import { Button, TextField } from '@mui/material'+// Loads 2,225 modules, takes ~4.2s extra in dev+```++**Correct - Next.js 13.5+ (recommended):**++```tsx+// Keep the standard imports - Next.js transforms them to direct imports+import { Check, X, Menu } from 'lucide-react'+// Full TypeScript support, no manual path wrangling+```++This is the recommended approach because it preserves TypeScript type safety and editor autocompletion while still eliminating the barrel import cost.++**Correct - Direct imports (non-Next.js projects):**++```tsx+import Button from '@mui/material/Button'+import TextField from '@mui/material/TextField'+// Loads only what you use+```++> **TypeScript warning:** Some libraries (notably `lucide-react`) don't ship `.d.ts` files for their deep import paths. Importing from `lucide-react/dist/esm/icons/check` resolves to an implicit `any` type, causing errors under `strict` or `noImplicitAny`. Prefer `optimizePackageImports` when available, or verify the library exports types for its subpaths before using direct imports.++These optimizations provide 15-70% faster dev boot, 28% faster builds, 40% faster cold starts, and significantly faster HMR.++Libraries commonly affected: `lucide-react`, `@mui/material`, `@mui/icons-material`, `@tabler/icons-react`, `react-icons`, `@headlessui/react`, `@radix-ui/react-*`, `lodash`, `ramda`, `date-fns`, `rxjs`, `react-use`.++Reference: [https://vercel.com/blog/how-we-optimized-package-imports-in-next-js](https://vercel.com/blog/how-we-optimized-package-imports-in-next-js)++### 2.2 Conditional Module Loading++**Impact: HIGH (loads large data only when needed)**++Load large data or modules only when a feature is activated.++**Example: lazy-load animation frames**++```tsx+function AnimationPlayer({ enabled, setEnabled }: { enabled: boolean; setEnabled: React.Dispatch<React.SetStateAction<boolean>> }) {+ const [frames, setFrames] = useState<Frame[] | null>(null)++ useEffect(() => {+ if (enabled && !frames && typeof window !== 'undefined') {+ import('./animation-frames.js')+ .then(mod => setFrames(mod.frames))+ .catch(() => setEnabled(false))+ }+ }, [enabled, frames, setEnabled])++ if (!frames) return <Skeleton />+ return <Canvas frames={frames} />+}+```++The `typeof window !== 'undefined'` check prevents bundling this module for SSR, optimizing server bundle size and build speed.++### 2.3 Defer Non-Critical Third-Party Libraries++**Impact: MEDIUM (loads after hydration)**++Analytics, logging, and error tracking don't block user interaction. Load them after hydration.++**Incorrect: blocks initial bundle**++```tsx+import { Analytics } from '@vercel/analytics/react'++export default function RootLayout({ children }) {+ return (+ <html>+ <body>+ {children}+ <Analytics />+ </body>+ </html>+ )+}+```++**Correct: loads after hydration**++```tsx+import dynamic from 'next/dynamic'++const Analytics = dynamic(+ () => import('@vercel/analytics/react').then(m => m.Analytics),+ { ssr: false }+)++export default function RootLayout({ children }) {+ return (+ <html>+ <body>+ {children}+ <Analytics />+ </body>+ </html>+ )+}+```++### 2.4 Dynamic Imports for Heavy Components++**Impact: CRITICAL (directly affects TTI and LCP)**++Use `next/dynamic` to lazy-load large components not needed on initial render.++**Incorrect: Monaco bundles with main chunk ~300KB**++```tsx+import { MonacoEditor } from './monaco-editor'++function CodePanel({ code }: { code: string }) {+ return <MonacoEditor value={code} />+}+```++**Correct: Monaco loads on demand**++```tsx+import dynamic from 'next/dynamic'++const MonacoEditor = dynamic(+ () => import('./monaco-editor').then(m => m.MonacoEditor),+ { ssr: false }+)++function CodePanel({ code }: { code: string }) {+ return <MonacoEditor value={code} />+}+```++### 2.5 Prefer Statically Analyzable Paths++**Impact: HIGH (avoids accidental broad bundles and file traces)**++Build tools work best when import and file-system paths are obvious at build time. If you hide the real path inside a variable or compose it too dynamically, the tool either has to include a broad set of possible files, warn that it cannot analyze the import, or widen file tracing to stay safe.++Prefer explicit maps or literal paths so the set of reachable files stays narrow and predictable. This is the same rule whether you are choosing modules with `import()` or reading files in server/build code.++When analysis becomes too broad, the cost is real:++- Larger server bundles++- Slower builds++- Worse cold starts++- More memory use++**Incorrect: the bundler cannot tell what may be imported**++```ts+const PAGE_MODULES = {+ home: './pages/home',+ settings: './pages/settings',+} as const++const Page = await import(PAGE_MODULES[pageName])+```++**Correct: use an explicit map of allowed modules**++```ts+const PAGE_MODULES = {+ home: () => import('./pages/home'),+ settings: () => import('./pages/settings'),+} as const++const Page = await PAGE_MODULES[pageName]()+```++**Incorrect: a 2-value enum still hides the final path from static analysis**++```ts+const baseDir = path.join(process.cwd(), 'content/' + contentKind)+```++**Correct: make each final path literal at the callsite**++```ts+const baseDir =+ kind === ContentKind.Blog+ ? path.join(process.cwd(), 'content/blog')+ : path.join(process.cwd(), 'content/docs')+```++In Next.js server code, this matters for output file tracing too. `path.join(process.cwd(), someVar)` can widen the traced file set because Next.js statically analyze `import`, `require`, and `fs` usage.++Reference: [https://nextjs.org/docs/app/api-reference/config/next-config-js/output](https://nextjs.org/docs/app/api-reference/config/next-config-js/output), [https://nextjs.org/learn/seo/dynamic-imports](https://nextjs.org/learn/seo/dynamic-imports), [https://vite.dev/guide/features.html](https://vite.dev/guide/features.html), [https://esbuild.github.io/api/](https://esbuild.github.io/api/), [https://www.npmjs.com/package/@rollup/plugin-dynamic-import-vars](https://www.npmjs.com/package/@rollup/plugin-dynamic-import-vars), [https://webpack.js.org/guides/dependency-management/](https://webpack.js.org/guides/dependency-management/)++### 2.6 Preload Based on User Intent++**Impact: MEDIUM (reduces perceived latency)**++Preload heavy bundles before they're needed to reduce perceived latency.++**Example: preload on hover/focus**++```tsx+function EditorButton({ onClick }: { onClick: () => void }) {+ const preload = () => {+ if (typeof window !== 'undefined') {+ void import('./monaco-editor')+ }+ }++ return (+ <button+ onMouseEnter={preload}+ onFocus={preload}+ onClick={onClick}+ >+ Open Editor+ </button>+ )+}+```++**Example: preload when feature flag is enabled**++```tsx+function FlagsProvider({ children, flags }: Props) {+ useEffect(() => {+ if (flags.editorEnabled && typeof window !== 'undefined') {+ void import('./monaco-editor').then(mod => mod.init())+ }+ }, [flags.editorEnabled])++ return <FlagsContext.Provider value={flags}>+ {children}+ </FlagsContext.Provider>+}+```++The `typeof window !== 'undefined'` check prevents bundling preloaded modules for SSR, optimizing server bundle size and build speed.++---++## 3. Server-Side Performance++**Impact: HIGH**++Optimizing server-side rendering and data fetching eliminates server-side waterfalls and reduces response times.++### 3.1 Authenticate Server Actions Like API Routes++**Impact: CRITICAL (prevents unauthorized access to server mutations)**++Server Actions (functions with `"use server"`) are exposed as public endpoints, just like API routes. Always verify authentication and authorization **inside** each Server Action—do not rely solely on middleware, layout guards, or page-level checks, as Server Actions can be invoked directly.++Next.js documentation explicitly states: "Treat Server Actions with the same security considerations as public-facing API endpoints, and verify if the user is allowed to perform a mutation."++**Incorrect: no authentication check**++```typescript+'use server'++export async function deleteUser(userId: string) {+ // Anyone can call this! No auth check+ await db.user.delete({ where: { id: userId } })+ return { success: true }+}+```++**Correct: authentication inside the action**++```typescript+'use server'++import { verifySession } from '@/lib/auth'+import { unauthorized } from '@/lib/errors'++export async function deleteUser(userId: string) {+ // Always check auth inside the action+ const session = await verifySession()++ if (!session) {+ throw unauthorized('Must be logged in')+ }++ // Check authorization too+ if (session.user.role !== 'admin' && session.user.id !== userId) {+ throw unauthorized('Cannot delete other users')+ }++ await db.user.delete({ where: { id: userId } })+ return { success: true }+}+```++**With input validation:**++```typescript+'use server'++import { verifySession } from '@/lib/auth'+import { z } from 'zod'++const updateProfileSchema = z.object({+ userId: z.string().uuid(),+ name: z.string().min(1).max(100),+ email: z.string().email()+})++export async function updateProfile(data: unknown) {+ // Validate input first+ const validated = updateProfileSchema.parse(data)++ // Then authenticate+ const session = await verifySession()+ if (!session) {+ throw new Error('Unauthorized')+ }++ // Then authorize+ if (session.user.id !== validated.userId) {+ throw new Error('Can only update own profile')+ }++ // Finally perform the mutation+ await db.user.update({+ where: { id: validated.userId },+ data: {+ name: validated.name,+ email: validated.email+ }+ })++ return { success: true }+}+```++Reference: [https://nextjs.org/docs/app/guides/authentication](https://nextjs.org/docs/app/guides/authentication)++### 3.2 Avoid Duplicate Serialization in RSC Props++**Impact: LOW (reduces network payload by avoiding duplicate serialization)**++RSC→client serialization deduplicates by object reference, not value. Same reference = serialized once; new reference = serialized again. Do transformations (`.toSorted()`, `.filter()`, `.map()`) in client, not server.++**Incorrect: duplicates array**++```tsx+// RSC: sends 6 strings (2 arrays × 3 items)+<ClientList usernames={usernames} usernamesOrdered={usernames.toSorted()} />+```++**Correct: sends 3 strings**++```tsx+// RSC: send once+<ClientList usernames={usernames} />++// Client: transform there+'use client'+const sorted = useMemo(() => [...usernames].sort(), [usernames])+```++**Nested deduplication behavior:**++```tsx+// string[] - duplicates everything+usernames={['a','b']} sorted={usernames.toSorted()} // sends 4 strings++// object[] - duplicates array structure only+users={[{id:1},{id:2}]} sorted={users.toSorted()} // sends 2 arrays + 2 unique objects (not 4)+```++Deduplication works recursively. Impact varies by data type:++- `string[]`, `number[]`, `boolean[]`: **HIGH impact** - array + all primitives fully duplicated++- `object[]`: **LOW impact** - array duplicated, but nested objects deduplicated by reference++**Operations breaking deduplication: create new references**++- Arrays: `.toSorted()`, `.filter()`, `.map()`, `.slice()`, `[...arr]`++- Objects: `{...obj}`, `Object.assign()`, `structuredClone()`, `JSON.parse(JSON.stringify())`++**More examples:**++```tsx+// ❌ Bad+<C users={users} active={users.filter(u => u.active)} />+<C product={product} productName={product.name} />++// ✅ Good+<C users={users} />+<C product={product} />+// Do filtering/destructuring in client+```++**Exception:** Pass derived data when transformation is expensive or client doesn't need original.++### 3.3 Avoid Shared Module State for Request Data++**Impact: HIGH (prevents concurrency bugs and request data leaks)**++For React Server Components and client components rendered during SSR, avoid using mutable module-level variables to share request-scoped data. Server renders can run concurrently in the same process. If one render writes to shared module state and another render reads it, you can get race conditions, cross-request contamination, and security bugs where one user's data appears in another user's response.++Treat module scope on the server as process-wide shared memory, not request-local state.++**Incorrect: request data leaks across concurrent renders**++```tsx+let currentUser: User | null = null++export default async function Page() {+ currentUser = await auth()+ return <Dashboard />+}++async function Dashboard() {+ return <div>{currentUser?.name}</div>+}+```++If two requests overlap, request A can set `currentUser`, then request B overwrites it before request A finishes rendering `Dashboard`.++**Correct: keep request data local to the render tree**++```tsx+export default async function Page() {+ const user = await auth()+ return <Dashboard user={user} />+}++function Dashboard({ user }: { user: User | null }) {+ return <div>{user?.name}</div>+}+```++Safe exceptions:++- Immutable static assets or config loaded once at module scope++- Shared caches intentionally designed for cross-request reuse and keyed correctly++- Process-wide singletons that do not store request- or user-specific mutable data++For static assets and config, see [Hoist Static I/O to Module Level](./server-hoist-static-io.md).++### 3.4 Cross-Request LRU Caching++**Impact: HIGH (caches across requests)**++`React.cache()` only works within one request. For data shared across sequential requests (user clicks button A then button B), use an LRU cache.++**Implementation:**++```typescript+import { LRUCache } from 'lru-cache'++const cache = new LRUCache<string, any>({+ max: 1000,+ ttl: 5 * 60 * 1000 // 5 minutes+})++export async function getUser(id: string) {+ const cached = cache.get(id)+ if (cached) return cached++ const user = await db.user.findUnique({ where: { id } })+ cache.set(id, user)+ return user+}++// Request 1: DB query, result cached+// Request 2: cache hit, no DB query+```++Use when sequential user actions hit multiple endpoints needing the same data within seconds.++**With Vercel's [Fluid Compute](https://vercel.com/docs/fluid-compute):** LRU caching is especially effective because multiple concurrent requests can share the same function instance and cache. This means the cache persists across requests without needing external storage like Redis.++**In traditional serverless:** Each invocation runs in isolation, so consider Redis for cross-process caching.++Reference: [https://github.com/isaacs/node-lru-cache](https://github.com/isaacs/node-lru-cache)++### 3.5 Hoist Static I/O to Module Level++**Impact: HIGH (avoids repeated file/network I/O per request)**++When loading static assets (fonts, logos, images, config files) in route handlers or server functions, hoist the I/O operation to module level. Module-level code runs once when the module is first imported, not on every request. This eliminates redundant file system reads or network fetches that would otherwise run on every invocation.++**Incorrect: reads font file on every request**++```typescript+// app/api/og/route.tsx+import { ImageResponse } from 'next/og'++export async function GET(request: Request) {+ // Runs on EVERY request - expensive!+ const fontData = await fetch(+ new URL('./fonts/Inter.ttf', import.meta.url)+ ).then(res => res.arrayBuffer())++ const logoData = await fetch(+ new URL('./images/logo.png', import.meta.url)+ ).then(res => res.arrayBuffer())++ return new ImageResponse(+ <div style={{ fontFamily: 'Inter' }}>+ <img src={logoData} />+ Hello World+ </div>,+ { fonts: [{ name: 'Inter', data: fontData }] }+ )+}+```++**Correct: loads once at module initialization**++```typescript+// app/api/og/route.tsx+import { ImageResponse } from 'next/og'++// Module-level: runs ONCE when module is first imported+const fontData = fetch(+ new URL('./fonts/Inter.ttf', import.meta.url)+).then(res => res.arrayBuffer())++const logoData = fetch(+ new URL('./images/logo.png', import.meta.url)+).then(res => res.arrayBuffer())++export async function GET(request: Request) {+ // Await the already-started promises+ const [font, logo] = await Promise.all([fontData, logoData])++ return new ImageResponse(+ <div style={{ fontFamily: 'Inter' }}>+ <img src={logo} />+ Hello World+ </div>,+ { fonts: [{ name: 'Inter', data: font }] }+ )+}+```++**Correct: synchronous fs at module level**++```typescript+// app/api/og/route.tsx+import { ImageResponse } from 'next/og'+import { readFileSync } from 'fs'+import { join } from 'path'++// Synchronous read at module level - blocks only during module init+const fontData = readFileSync(+ join(process.cwd(), 'public/fonts/Inter.ttf')+)++const logoData = readFileSync(+ join(process.cwd(), 'public/images/logo.png')+)++export async function GET(request: Request) {+ return new ImageResponse(+ <div style={{ fontFamily: 'Inter' }}>+ <img src={logoData} />+ Hello World+ </div>,+ { fonts: [{ name: 'Inter', data: fontData }] }+ )+}+```++**Incorrect: reads config on every call**++```typescript+import fs from 'node:fs/promises'++export async function processRequest(data: Data) {+ const config = JSON.parse(+ await fs.readFile('./config.json', 'utf-8')+ )+ const template = await fs.readFile('./template.html', 'utf-8')++ return render(template, data, config)+}+```++**Correct: hoists config and template to module level**++```typescript+import fs from 'node:fs/promises'++const configPromise = fs+ .readFile('./config.json', 'utf-8')+ .then(JSON.parse)+const templatePromise = fs.readFile('./template.html', 'utf-8')++export async function processRequest(data: Data) {+ const [config, template] = await Promise.all([+ configPromise,+ templatePromise,+ ])++ return render(template, data, config)+}+```++When to use this pattern:++- Loading fonts for OG image generation++- Loading static logos, icons, or watermarks++- Reading configuration files that don't change at runtime++- Loading email templates or other static templates++- Any static asset that's the same across all requests++When not to use this pattern:++- Assets that vary per request or user++- Files that may change during runtime (use caching with TTL instead)++- Large files that would consume too much memory if kept loaded++- Sensitive data that shouldn't persist in memory++With Vercel's [Fluid Compute](https://vercel.com/docs/fluid-compute), module-level caching is especially effective because multiple concurrent requests share the same function instance. The static assets stay loaded in memory across requests without cold start penalties.++In traditional serverless, each cold start re-executes module-level code, but subsequent warm invocations reuse the loaded assets until the instance is recycled.++### 3.6 Minimize Serialization at RSC Boundaries++**Impact: HIGH (reduces data transfer size)**++The React Server/Client boundary serializes all object properties into strings and embeds them in the HTML response and subsequent RSC requests. This serialized data directly impacts page weight and load time, so **size matters a lot**. Only pass fields that the client actually uses.++**Incorrect: serializes all 50 fields**++```tsx+async function Page() {+ const user = await fetchUser() // 50 fields+ return <Profile user={user} />+}++'use client'+function Profile({ user }: { user: User }) {+ return <div>{user.name}</div> // uses 1 field+}+```++**Correct: serializes only 1 field**++```tsx+async function Page() {+ const user = await fetchUser()+ return <Profile name={user.name} />+}++'use client'+function Profile({ name }: { name: string }) {+ return <div>{name}</div>+}+```++### 3.7 Parallel Data Fetching with Component Composition++**Impact: CRITICAL (eliminates server-side waterfalls)**++React Server Components execute sequentially within a tree. Restructure with composition to parallelize data fetching.++**Incorrect: Sidebar waits for Page's fetch to complete**++```tsx+export default async function Page() {+ const header = await fetchHeader()+ return (+ <div>+ <div>{header}</div>+ <Sidebar />+ </div>+ )+}++async function Sidebar() {+ const items = await fetchSidebarItems()+ return <nav>{items.map(renderItem)}</nav>+}+```++**Correct: both fetch simultaneously**++```tsx+async function Header() {+ const data = await fetchHeader()+ return <div>{data}</div>+}++async function Sidebar() {+ const items = await fetchSidebarItems()+ return <nav>{items.map(renderItem)}</nav>+}++export default function Page() {+ return (+ <div>+ <Header />+ <Sidebar />+ </div>+ )+}+```++**Alternative with children prop:**++```tsx+async function Header() {+ const data = await fetchHeader()+ return <div>{data}</div>+}++async function Sidebar() {+ const items = await fetchSidebarItems()+ return <nav>{items.map(renderItem)}</nav>+}++function Layout({ children }: { children: ReactNode }) {+ return (+ <div>+ <Header />+ {children}+ </div>+ )+}++export default function Page() {+ return (+ <Layout>+ <Sidebar />+ </Layout>+ )+}+```++### 3.8 Parallel Nested Data Fetching++**Impact: CRITICAL (eliminates server-side waterfalls)**++When fetching nested data in parallel, chain dependent fetches within each item's promise so a slow item doesn't block the rest.++**Incorrect: a single slow item blocks all nested fetches**++```tsx+const chats = await Promise.all(+ chatIds.map(id => getChat(id))+)++const chatAuthors = await Promise.all(+ chats.map(chat => getUser(chat.author))+)+```++If one `getChat(id)` out of 100 is extremely slow, the authors of the other 99 chats can't start loading even though their data is ready.++**Correct: each item chains its own nested fetch**++```tsx+const chatAuthors = await Promise.all(+ chatIds.map(id => getChat(id).then(chat => getUser(chat.author)))+)+```++Each item independently chains `getChat` → `getUser`, so a slow chat doesn't block author fetches for the others.++### 3.9 Per-Request Deduplication with React.cache()++**Impact: MEDIUM (deduplicates within request)**++Use `React.cache()` for server-side request deduplication. Authentication and database queries benefit most.++**Usage:**++```typescript+import { cache } from 'react'++export const getCurrentUser = cache(async () => {+ const session = await auth()+ if (!session?.user?.id) return null+ return await db.user.findUnique({+ where: { id: session.user.id }+ })+})+```++Within a single request, multiple calls to `getCurrentUser()` execute the query only once.++**Avoid inline objects as arguments:**++`React.cache()` uses shallow equality (`Object.is`) to determine cache hits. Inline objects create new references each call, preventing cache hits.++**Incorrect: always cache miss**++```typescript+const getUser = cache(async (params: { uid: number }) => {+ return await db.user.findUnique({ where: { id: params.uid } })+})++// Each call creates new object, never hits cache+getUser({ uid: 1 })+getUser({ uid: 1 }) // Cache miss, runs query again+```++**Correct: cache hit**++```typescript+const params = { uid: 1 }+getUser(params) // Query runs+getUser(params) // Cache hit (same reference)+```++If you must pass objects, pass the same reference:++**Next.js-Specific Note:**++In Next.js, the `fetch` API is automatically extended with request memoization. Requests with the same URL and options are automatically deduplicated within a single request, so you don't need `React.cache()` for `fetch` calls. However, `React.cache()` is still essential for other async tasks:++- Database queries (Prisma, Drizzle, etc.)++- Heavy computations++- Authentication checks++- File system operations++- Any non-fetch async work++Use `React.cache()` to deduplicate these operations across your component tree.++Reference: [https://react.dev/reference/react/cache](https://react.dev/reference/react/cache)++### 3.10 Use after() for Non-Blocking Operations++**Impact: MEDIUM (faster response times)**++Use Next.js's `after()` to schedule work that should execute after a response is sent. This prevents logging, analytics, and other side effects from blocking the response.++**Incorrect: blocks response**++```tsx+import { logUserAction } from '@/app/utils'++export async function POST(request: Request) {+ // Perform mutation+ await updateDatabase(request)++ // Logging blocks the response+ const userAgent = request.headers.get('user-agent') || 'unknown'+ await logUserAction({ userAgent })++ return new Response(JSON.stringify({ status: 'success' }), {+ status: 200,+ headers: { 'Content-Type': 'application/json' }+ })+}+```++**Correct: non-blocking**++```tsx+import { after } from 'next/server'+import { headers, cookies } from 'next/headers'+import { logUserAction } from '@/app/utils'++export async function POST(request: Request) {+ // Perform mutation+ await updateDatabase(request)++ // Log after response is sent+ after(async () => {+ const userAgent = (await headers()).get('user-agent') || 'unknown'+ const sessionCookie = (await cookies()).get('session-id')?.value || 'anonymous'++ logUserAction({ sessionCookie, userAgent })+ })++ return new Response(JSON.stringify({ status: 'success' }), {+ status: 200,+ headers: { 'Content-Type': 'application/json' }+ })+}+```++The response is sent immediately while logging happens in the background.++**Common use cases:**++- Analytics tracking++- Audit logging++- Sending notifications++- Cache invalidation++- Cleanup tasks++**Important notes:**++- `after()` runs even if the response fails or redirects++- Works in Server Actions, Route Handlers, and Server Components++Reference: [https://nextjs.org/docs/app/api-reference/functions/after](https://nextjs.org/docs/app/api-reference/functions/after)++---++## 4. Client-Side Data Fetching++**Impact: MEDIUM-HIGH**++Automatic deduplication and efficient data fetching patterns reduce redundant network requests.++### 4.1 Deduplicate Global Event Listeners++**Impact: LOW (single listener for N components)**++Use `useSWRSubscription()` to share global event listeners across component instances.++**Incorrect: N instances = N listeners**++```tsx+function useKeyboardShortcut(key: string, callback: () => void) {+ useEffect(() => {+ const handler = (e: KeyboardEvent) => {+ if (e.metaKey && e.key === key) {+ callback()+ }+ }+ window.addEventListener('keydown', handler)+ return () => window.removeEventListener('keydown', handler)+ }, [key, callback])+}+```++When using the `useKeyboardShortcut` hook multiple times, each instance will register a new listener.++**Correct: N instances = 1 listener**++```tsx+import useSWRSubscription from 'swr/subscription'++// Module-level Map to track callbacks per key+const keyCallbacks = new Map<string, Set<() => void>>()++function useKeyboardShortcut(key: string, callback: () => void) {+ // Register this callback in the Map+ useEffect(() => {+ if (!keyCallbacks.has(key)) {+ keyCallbacks.set(key, new Set())+ }+ keyCallbacks.get(key)!.add(callback)++ return () => {+ const set = keyCallbacks.get(key)+ if (set) {+ set.delete(callback)+ if (set.size === 0) {+ keyCallbacks.delete(key)+ }+ }+ }+ }, [key, callback])++ useSWRSubscription('global-keydown', () => {+ const handler = (e: KeyboardEvent) => {+ if (e.metaKey && keyCallbacks.has(e.key)) {+ keyCallbacks.get(e.key)!.forEach(cb => cb())+ }+ }+ window.addEventListener('keydown', handler)+ return () => window.removeEventListener('keydown', handler)+ })+}++function Profile() {+ // Multiple shortcuts will share the same listener+ useKeyboardShortcut('p', () => { /* ... */ })+ useKeyboardShortcut('k', () => { /* ... */ })+ // ...+}+```++### 4.2 Use Passive Event Listeners for Scrolling Performance++**Impact: MEDIUM (eliminates scroll delay caused by event listeners)**++Add `{ passive: true }` to touch and wheel event listeners to enable immediate scrolling. Browsers normally wait for listeners to finish to check if `preventDefault()` is called, causing scroll delay.++**Incorrect:**++```typescript+useEffect(() => {+ const handleTouch = (e: TouchEvent) => console.log(e.touches[0].clientX)+ const handleWheel = (e: WheelEvent) => console.log(e.deltaY)++ document.addEventListener('touchstart', handleTouch)+ document.addEventListener('wheel', handleWheel)++ return () => {+ document.removeEventListener('touchstart', handleTouch)+ document.removeEventListener('wheel', handleWheel)+ }+}, [])+```++**Correct:**++```typescript+useEffect(() => {+ const handleTouch = (e: TouchEvent) => console.log(e.touches[0].clientX)+ const handleWheel = (e: WheelEvent) => console.log(e.deltaY)++ document.addEventListener('touchstart', handleTouch, { passive: true })+ document.addEventListener('wheel', handleWheel, { passive: true })++ return () => {+ document.removeEventListener('touchstart', handleTouch)+ document.removeEventListener('wheel', handleWheel)+ }+}, [])+```++**Use passive when:** tracking/analytics, logging, any listener that doesn't call `preventDefault()`.++**Don't use passive when:** implementing custom swipe gestures, custom zoom controls, or any listener that needs `preventDefault()`.++### 4.3 Use SWR for Automatic Deduplication++**Impact: MEDIUM-HIGH (automatic deduplication)**++SWR enables request deduplication, caching, and revalidation across component instances.++**Incorrect: no deduplication, each instance fetches**++```tsx+function UserList() {+ const [users, setUsers] = useState([])+ useEffect(() => {+ fetch('/api/users')+ .then(r => r.json())+ .then(setUsers)+ }, [])+}+```++**Correct: multiple instances share one request**++```tsx+import useSWR from 'swr'++function UserList() {+ const { data: users } = useSWR('/api/users', fetcher)+}+```++**For immutable data:**++```tsx+import { useImmutableSWR } from '@/lib/swr'++function StaticContent() {+ const { data } = useImmutableSWR('/api/config', fetcher)+}+```++**For mutations:**++```tsx+import { useSWRMutation } from 'swr/mutation'++function UpdateButton() {+ const { trigger } = useSWRMutation('/api/user', updateUser)+ return <button onClick={() => trigger()}>Update</button>+}+```++Reference: [https://swr.vercel.app](https://swr.vercel.app)++### 4.4 Version and Minimize localStorage Data++**Impact: MEDIUM (prevents schema conflicts, reduces storage size)**++Add version prefix to keys and store only needed fields. Prevents schema conflicts and accidental storage of sensitive data.++**Incorrect:**++```typescript+// No version, stores everything, no error handling+localStorage.setItem('userConfig', JSON.stringify(fullUserObject))+const data = localStorage.getItem('userConfig')+```++**Correct:**++```typescript+const VERSION = 'v2'++function saveConfig(config: { theme: string; language: string }) {+ try {+ localStorage.setItem(`userConfig:${VERSION}`, JSON.stringify(config))+ } catch {+ // Throws in incognito/private browsing, quota exceeded, or disabled+ }+}++function loadConfig() {+ try {+ const data = localStorage.getItem(`userConfig:${VERSION}`)+ return data ? JSON.parse(data) : null+ } catch {+ return null+ }+}++// Migration from v1 to v2+function migrate() {+ try {+ const v1 = localStorage.getItem('userConfig:v1')+ if (v1) {+ const old = JSON.parse(v1)+ saveConfig({ theme: old.darkMode ? 'dark' : 'light', language: old.lang })+ localStorage.removeItem('userConfig:v1')+ }+ } catch {}+}+```++**Store minimal fields from server responses:**++```typescript+// User object has 20+ fields, only store what UI needs+function cachePrefs(user: FullUser) {+ try {+ localStorage.setItem('prefs:v1', JSON.stringify({+ theme: user.preferences.theme,+ notifications: user.preferences.notifications+ }))+ } catch {}+}+```++**Always wrap in try-catch:** `getItem()` and `setItem()` throw in incognito/private browsing (Safari, Firefox), when quota exceeded, or when disabled.++**Benefits:** Schema evolution via versioning, reduced storage size, prevents storing tokens/PII/internal flags.++---++## 5. Re-render Optimization++**Impact: MEDIUM**++Reducing unnecessary re-renders minimizes wasted computation and improves UI responsiveness.++### 5.1 Calculate Derived State During Rendering++**Impact: MEDIUM (avoids redundant renders and state drift)**++If a value can be computed from current props/state, do not store it in state or update it in an effect. Derive it during render to avoid extra renders and state drift. Do not set state in effects solely in response to prop changes; prefer derived values or keyed resets instead.++**Incorrect: redundant state and effect**++```tsx+function Form() {+ const [firstName, setFirstName] = useState('First')+ const [lastName, setLastName] = useState('Last')+ const [fullName, setFullName] = useState('')++ useEffect(() => {+ setFullName(firstName + ' ' + lastName)+ }, [firstName, lastName])++ return <p>{fullName}</p>+}+```++**Correct: derive during render**++```tsx+function Form() {+ const [firstName, setFirstName] = useState('First')+ const [lastName, setLastName] = useState('Last')+ const fullName = firstName + ' ' + lastName++ return <p>{fullName}</p>+}+```++Reference: [https://react.dev/learn/you-might-not-need-an-effect](https://react.dev/learn/you-might-not-need-an-effect)++### 5.2 Defer State Reads to Usage Point++**Impact: MEDIUM (avoids unnecessary subscriptions)**++Don't subscribe to dynamic state (searchParams, localStorage) if you only read it inside callbacks.++**Incorrect: subscribes to all searchParams changes**++```tsx+function ShareButton({ chatId }: { chatId: string }) {+ const searchParams = useSearchParams()++ const handleShare = () => {+ const ref = searchParams.get('ref')+ shareChat(chatId, { ref })+ }++ return <button onClick={handleShare}>Share</button>+}+```++**Correct: reads on demand, no subscription**++```tsx+function ShareButton({ chatId }: { chatId: string }) {+ const handleShare = () => {+ const params = new URLSearchParams(window.location.search)+ const ref = params.get('ref')+ shareChat(chatId, { ref })+ }++ return <button onClick={handleShare}>Share</button>+}+```++### 5.3 Do not wrap a simple expression with a primitive result type in useMemo++**Impact: LOW-MEDIUM (wasted computation on every render)**++When an expression is simple (few logical or arithmetical operators) and has a primitive result type (boolean, number, string), do not wrap it in `useMemo`.++Calling `useMemo` and comparing hook dependencies may consume more resources than the expression itself.++**Incorrect:**++```tsx+function Header({ user, notifications }: Props) {+ const isLoading = useMemo(() => {+ return user.isLoading || notifications.isLoading+ }, [user.isLoading, notifications.isLoading])++ if (isLoading) return <Skeleton />+ // return some markup+}+```++**Correct:**++```tsx+function Header({ user, notifications }: Props) {+ const isLoading = user.isLoading || notifications.isLoading++ if (isLoading) return <Skeleton />+ // return some markup+}+```++### 5.4 Don't Define Components Inside Components++**Impact: HIGH (prevents remount on every render)**++Defining a component inside another component creates a new component type on every render. React sees a different component each time and fully remounts it, destroying all state and DOM.++A common reason developers do this is to access parent variables without passing props. Always pass props instead.++**Incorrect: remounts on every render**++```tsx+function UserProfile({ user, theme }) {+ // Defined inside to access `theme` - BAD+ const Avatar = () => (+ <img+ src={user.avatarUrl}+ className={theme === 'dark' ? 'avatar-dark' : 'avatar-light'}+ />+ )++ // Defined inside to access `user` - BAD+ const Stats = () => (+ <div>+ <span>{user.followers} followers</span>+ <span>{user.posts} posts</span>+ </div>+ )++ return (+ <div>+ <Avatar />+ <Stats />+ </div>+ )+}+```++Every time `UserProfile` renders, `Avatar` and `Stats` are new component types. React unmounts the old instances and mounts new ones, losing any internal state, running effects again, and recreating DOM nodes.++**Correct: pass props instead**++```tsx+function Avatar({ src, theme }: { src: string; theme: string }) {+ return (+ <img+ src={src}+ className={theme === 'dark' ? 'avatar-dark' : 'avatar-light'}+ />+ )+}++function Stats({ followers, posts }: { followers: number; posts: number }) {+ return (+ <div>+ <span>{followers} followers</span>+ <span>{posts} posts</span>+ </div>+ )+}++function UserProfile({ user, theme }) {+ return (+ <div>+ <Avatar src={user.avatarUrl} theme={theme} />+ <Stats followers={user.followers} posts={user.posts} />+ </div>+ )+}+```++**Symptoms of this bug:**++- Input fields lose focus on every keystroke++- Animations restart unexpectedly++- `useEffect` cleanup/setup runs on every parent render++- Scroll position resets inside the component++### 5.5 Extract Default Non-primitive Parameter Value from Memoized Component to Constant++**Impact: MEDIUM (restores memoization by using a constant for default value)**++When memoized component has a default value for some non-primitive optional parameter, such as an array, function, or object, calling the component without that parameter results in broken memoization. This is because new value instances are created on every rerender, and they do not pass strict equality comparison in `memo()`.++To address this issue, extract the default value into a constant.++**Incorrect: `onClick` has different values on every rerender**++```tsx+const UserAvatar = memo(function UserAvatar({ onClick = () => {} }: { onClick?: () => void }) {+ // ...+})++// Used without optional onClick+<UserAvatar />+```++**Correct: stable default value**++```tsx+const NOOP = () => {};++const UserAvatar = memo(function UserAvatar({ onClick = NOOP }: { onClick?: () => void }) {+ // ...+})++// Used without optional onClick+<UserAvatar />+```++### 5.6 Extract to Memoized Components++**Impact: MEDIUM (enables early returns)**++Extract expensive work into memoized components to enable early returns before computation.++**Incorrect: computes avatar even when loading**++```tsx+function Profile({ user, loading }: Props) {+ const avatar = useMemo(() => {+ const id = computeAvatarId(user)+ return <Avatar id={id} />+ }, [user])++ if (loading) return <Skeleton />+ return <div>{avatar}</div>+}+```++**Correct: skips computation when loading**++```tsx+const UserAvatar = memo(function UserAvatar({ user }: { user: User }) {+ const id = useMemo(() => computeAvatarId(user), [user])+ return <Avatar id={id} />+})++function Profile({ user, loading }: Props) {+ if (loading) return <Skeleton />+ return (+ <div>+ <UserAvatar user={user} />+ </div>+ )+}+```++**Note:** If your project has [React Compiler](https://react.dev/learn/react-compiler) enabled, manual memoization with `memo()` and `useMemo()` is not necessary. The compiler automatically optimizes re-renders.++### 5.7 Narrow Effect Dependencies++**Impact: LOW (minimizes effect re-runs)**++Specify primitive dependencies instead of objects to minimize effect re-runs.++**Incorrect: re-runs on any user field change**++```tsx+useEffect(() => {+ console.log(user.id)+}, [user])+```++**Correct: re-runs only when id changes**++```tsx+useEffect(() => {+ console.log(user.id)+}, [user.id])+```++**For derived state, compute outside effect:**++```tsx+// Incorrect: runs on width=767, 766, 765...+useEffect(() => {+ if (width < 768) {+ enableMobileMode()+ }+}, [width])++// Correct: runs only on boolean transition+const isMobile = width < 768+useEffect(() => {+ if (isMobile) {+ enableMobileMode()+ }+}, [isMobile])+```++### 5.8 Put Interaction Logic in Event Handlers++**Impact: MEDIUM (avoids effect re-runs and duplicate side effects)**++If a side effect is triggered by a specific user action (submit, click, drag), run it in that event handler. Do not model the action as state + effect; it makes effects re-run on unrelated changes and can duplicate the action.++**Incorrect: event modeled as state + effect**++```tsx+function Form() {+ const [submitted, setSubmitted] = useState(false)+ const theme = useContext(ThemeContext)++ useEffect(() => {+ if (submitted) {+ post('/api/register')+ showToast('Registered', theme)+ }+ }, [submitted, theme])++ return <button onClick={() => setSubmitted(true)}>Submit</button>+}+```++**Correct: do it in the handler**++```tsx+function Form() {+ const theme = useContext(ThemeContext)++ function handleSubmit() {+ post('/api/register')+ showToast('Registered', theme)+ }++ return <button onClick={handleSubmit}>Submit</button>+}+```++Reference: [https://react.dev/learn/removing-effect-dependencies#should-this-code-move-to-an-event-handler](https://react.dev/learn/removing-effect-dependencies#should-this-code-move-to-an-event-handler)++### 5.9 Split Combined Hook Computations++**Impact: MEDIUM (avoids recomputing independent steps)**++When a hook contains multiple independent tasks with different dependencies, split them into separate hooks. A combined hook reruns all tasks when any dependency changes, even if some tasks don't use the changed value.++**Incorrect: changing `sortOrder` recomputes filtering**++```tsx+const sortedProducts = useMemo(() => {+ const filtered = products.filter((p) => p.category === category)+ const sorted = filtered.toSorted((a, b) =>+ sortOrder === "asc" ? a.price - b.price : b.price - a.price+ )+ return sorted+}, [products, category, sortOrder])+```++**Correct: filtering only recomputes when products or category change**++```tsx+const filteredProducts = useMemo(+ () => products.filter((p) => p.category === category),+ [products, category]+)++const sortedProducts = useMemo(+ () =>+ filteredProducts.toSorted((a, b) =>+ sortOrder === "asc" ? a.price - b.price : b.price - a.price+ ),+ [filteredProducts, sortOrder]+)+```++This pattern also applies to `useEffect` when combining unrelated side effects:++**Incorrect: both effects run when either dependency changes**++```tsx+useEffect(() => {+ analytics.trackPageView(pathname)+ document.title = `${pageTitle} | My App`+}, [pathname, pageTitle])+```++**Correct: effects run independently**++```tsx+useEffect(() => {+ analytics.trackPageView(pathname)+}, [pathname])++useEffect(() => {+ document.title = `${pageTitle} | My App`+}, [pageTitle])+```++**Note:** If your project has [React Compiler](https://react.dev/learn/react-compiler) enabled, it automatically optimizes dependency tracking and may handle some of these cases for you.++### 5.10 Subscribe to Derived State++**Impact: MEDIUM (reduces re-render frequency)**++Subscribe to derived boolean state instead of continuous values to reduce re-render frequency.++**Incorrect: re-renders on every pixel change**++```tsx+function Sidebar() {+ const width = useWindowWidth() // updates continuously+ const isMobile = width < 768+ return <nav className={isMobile ? 'mobile' : 'desktop'} />+}+```++**Correct: re-renders only when boolean changes**++```tsx+function Sidebar() {+ const isMobile = useMediaQuery('(max-width: 767px)')+ return <nav className={isMobile ? 'mobile' : 'desktop'} />+}+```++### 5.11 Use Functional setState Updates++**Impact: MEDIUM (prevents stale closures and unnecessary callback recreations)**++When updating state based on the current state value, use the functional update form of setState instead of directly referencing the state variable. This prevents stale closures, eliminates unnecessary dependencies, and creates stable callback references.++**Incorrect: requires state as dependency**++```tsx+function TodoList() {+ const [items, setItems] = useState(initialItems)++ // Callback must depend on items, recreated on every items change+ const addItems = useCallback((newItems: Item[]) => {+ setItems([...items, ...newItems])+ }, [items]) // ❌ items dependency causes recreations++ // Risk of stale closure if dependency is forgotten+ const removeItem = useCallback((id: string) => {+ setItems(items.filter(item => item.id !== id))+ }, []) // ❌ Missing items dependency - will use stale items!++ return <ItemsEditor items={items} onAdd={addItems} onRemove={removeItem} />+}+```++The first callback is recreated every time `items` changes, which can cause child components to re-render unnecessarily. The second callback has a stale closure bug—it will always reference the initial `items` value.++**Correct: stable callbacks, no stale closures**++```tsx+function TodoList() {+ const [items, setItems] = useState(initialItems)++ // Stable callback, never recreated+ const addItems = useCallback((newItems: Item[]) => {+ setItems(curr => [...curr, ...newItems])+ }, []) // ✅ No dependencies needed++ // Always uses latest state, no stale closure risk+ const removeItem = useCallback((id: string) => {+ setItems(curr => curr.filter(item => item.id !== id))+ }, []) // ✅ Safe and stable++ return <ItemsEditor items={items} onAdd={addItems} onRemove={removeItem} />+}+```++**Benefits:**++1. **Stable callback references** - Callbacks don't need to be recreated when state changes++2. **No stale closures** - Always operates on the latest state value++3. **Fewer dependencies** - Simplifies dependency arrays and reduces memory leaks++4. **Prevents bugs** - Eliminates the most common source of React closure bugs++**When to use functional updates:**++- Any setState that depends on the current state value++- Inside useCallback/useMemo when state is needed++- Event handlers that reference state++- Async operations that update state++**When direct updates are fine:**++- Setting state to a static value: `setCount(0)`++- Setting state from props/arguments only: `setName(newName)`++- State doesn't depend on previous value++**Note:** If your project has [React Compiler](https://react.dev/learn/react-compiler) enabled, the compiler can automatically optimize some cases, but functional updates are still recommended for correctness and to prevent stale closure bugs.++### 5.12 Use Lazy State Initialization++**Impact: MEDIUM (wasted computation on every render)**++Pass a function to `useState` for expensive initial values. Without the function form, the initializer runs on every render even though the value is only used once.++**Incorrect: runs on every render**++```tsx+function FilteredList({ items }: { items: Item[] }) {+ // buildSearchIndex() runs on EVERY render, even after initialization+ const [searchIndex, setSearchIndex] = useState(buildSearchIndex(items))+ const [query, setQuery] = useState('')++ // When query changes, buildSearchIndex runs again unnecessarily+ return <SearchResults index={searchIndex} query={query} />+}++function UserProfile() {+ // JSON.parse runs on every render+ const [settings, setSettings] = useState(+ JSON.parse(localStorage.getItem('settings') || '{}')+ )++ return <SettingsForm settings={settings} onChange={setSettings} />+}+```++**Correct: runs only once**++```tsx+function FilteredList({ items }: { items: Item[] }) {+ // buildSearchIndex() runs ONLY on initial render+ const [searchIndex, setSearchIndex] = useState(() => buildSearchIndex(items))+ const [query, setQuery] = useState('')++ return <SearchResults index={searchIndex} query={query} />+}++function UserProfile() {+ // JSON.parse runs only on initial render+ const [settings, setSettings] = useState(() => {+ const stored = localStorage.getItem('settings')+ return stored ? JSON.parse(stored) : {}+ })++ return <SettingsForm settings={settings} onChange={setSettings} />+}+```++Use lazy initialization when computing initial values from localStorage/sessionStorage, building data structures (indexes, maps), reading from the DOM, or performing heavy transformations.++For simple primitives (`useState(0)`), direct references (`useState(props.value)`), or cheap literals (`useState({})`), the function form is unnecessary.++### 5.13 Use Transitions for Non-Urgent Updates++**Impact: MEDIUM (maintains UI responsiveness)**++Mark frequent, non-urgent state updates as transitions to maintain UI responsiveness.++**Incorrect: blocks UI on every scroll**++```tsx+function ScrollTracker() {+ const [scrollY, setScrollY] = useState(0)+ useEffect(() => {+ const handler = () => setScrollY(window.scrollY)+ window.addEventListener('scroll', handler, { passive: true })+ return () => window.removeEventListener('scroll', handler)+ }, [])+}+```++**Correct: non-blocking updates**++```tsx+import { startTransition } from 'react'++function ScrollTracker() {+ const [scrollY, setScrollY] = useState(0)+ useEffect(() => {+ const handler = () => {+ startTransition(() => setScrollY(window.scrollY))+ }+ window.addEventListener('scroll', handler, { passive: true })+ return () => window.removeEventListener('scroll', handler)+ }, [])+}+```++### 5.14 Use useDeferredValue for Expensive Derived Renders++**Impact: MEDIUM (keeps input responsive during heavy computation)**++When user input triggers expensive computations or renders, use `useDeferredValue` to keep the input responsive. The deferred value lags behind, allowing React to prioritize the input update and render the expensive result when idle.++**Incorrect: input feels laggy while filtering**++```tsx+function Search({ items }: { items: Item[] }) {+ const [query, setQuery] = useState('')+ const filtered = items.filter(item => fuzzyMatch(item, query))++ return (+ <>+ <input value={query} onChange={e => setQuery(e.target.value)} />+ <ResultsList results={filtered} />+ </>+ )+}+```++**Correct: input stays snappy, results render when ready**++```tsx+function Search({ items }: { items: Item[] }) {+ const [query, setQuery] = useState('')+ const deferredQuery = useDeferredValue(query)+ const filtered = useMemo(+ () => items.filter(item => fuzzyMatch(item, deferredQuery)),+ [items, deferredQuery]+ )+ const isStale = query !== deferredQuery++ return (+ <>+ <input value={query} onChange={e => setQuery(e.target.value)} />+ <div style={{ opacity: isStale ? 0.7 : 1 }}>+ <ResultsList results={filtered} />+ </div>+ </>+ )+}+```++**When to use:**++- Filtering/searching large lists++- Expensive visualizations (charts, graphs) reacting to input++- Any derived state that causes noticeable render delays++**Note:** Wrap the expensive computation in `useMemo` with the deferred value as a dependency, otherwise it still runs on every render.++Reference: [https://react.dev/reference/react/useDeferredValue](https://react.dev/reference/react/useDeferredValue)++### 5.15 Use useRef for Transient Values++**Impact: MEDIUM (avoids unnecessary re-renders on frequent updates)**++When a value changes frequently and you don't want a re-render on every update (e.g., mouse trackers, intervals, transient flags), store it in `useRef` instead of `useState`. Keep component state for UI; use refs for temporary DOM-adjacent values. Updating a ref does not trigger a re-render.++**Incorrect: renders every update**++```tsx+function Tracker() {+ const [lastX, setLastX] = useState(0)++ useEffect(() => {+ const onMove = (e: MouseEvent) => setLastX(e.clientX)+ window.addEventListener('mousemove', onMove)+ return () => window.removeEventListener('mousemove', onMove)+ }, [])++ return (+ <div+ style={{+ position: 'fixed',+ top: 0,+ left: lastX,+ width: 8,+ height: 8,+ background: 'black',+ }}+ />+ )+}+```++**Correct: no re-render for tracking**++```tsx+function Tracker() {+ const lastXRef = useRef(0)+ const dotRef = useRef<HTMLDivElement>(null)++ useEffect(() => {+ const onMove = (e: MouseEvent) => {+ lastXRef.current = e.clientX+ const node = dotRef.current+ if (node) {+ node.style.transform = `translateX(${e.clientX}px)`+ }+ }+ window.addEventListener('mousemove', onMove)+ return () => window.removeEventListener('mousemove', onMove)+ }, [])++ return (+ <div+ ref={dotRef}+ style={{+ position: 'fixed',+ top: 0,+ left: 0,+ width: 8,+ height: 8,+ background: 'black',+ transform: 'translateX(0px)',+ }}+ />+ )+}+```++---++## 6. Rendering Performance++**Impact: MEDIUM**++Optimizing the rendering process reduces the work the browser needs to do.++### 6.1 Animate SVG Wrapper Instead of SVG Element++**Impact: LOW (enables hardware acceleration)**++Many browsers don't have hardware acceleration for CSS3 animations on SVG elements. Wrap SVG in a `<div>` and animate the wrapper instead.++**Incorrect: animating SVG directly - no hardware acceleration**++```tsx+function LoadingSpinner() {+ return (+ <svg+ className="animate-spin"+ width="24"+ height="24"+ viewBox="0 0 24 24"+ >+ <circle cx="12" cy="12" r="10" stroke="currentColor" />+ </svg>+ )+}+```++**Correct: animating wrapper div - hardware accelerated**++```tsx+function LoadingSpinner() {+ return (+ <div className="animate-spin">+ <svg+ width="24"+ height="24"+ viewBox="0 0 24 24"+ >+ <circle cx="12" cy="12" r="10" stroke="currentColor" />+ </svg>+ </div>+ )+}+```++This applies to all CSS transforms and transitions (`transform`, `opacity`, `translate`, `scale`, `rotate`). The wrapper div allows browsers to use GPU acceleration for smoother animations.++### 6.2 CSS content-visibility for Long Lists++**Impact: HIGH (faster initial render)**++Apply `content-visibility: auto` to defer off-screen rendering.++**CSS:**++```css+.message-item {+ content-visibility: auto;+ contain-intrinsic-size: 0 80px;+}+```++**Example:**++```tsx+function MessageList({ messages }: { messages: Message[] }) {+ return (+ <div className="overflow-y-auto h-screen">+ {messages.map(msg => (+ <div key={msg.id} className="message-item">+ <Avatar user={msg.author} />+ <div>{msg.content}</div>+ </div>+ ))}+ </div>+ )+}+```++For 1000 messages, browser skips layout/paint for ~990 off-screen items (10× faster initial render).++### 6.3 Hoist Static JSX Elements++**Impact: LOW (avoids re-creation)**++Extract static JSX outside components to avoid re-creation.++**Incorrect: recreates element every render**++```tsx+function LoadingSkeleton() {+ return <div className="animate-pulse h-20 bg-gray-200" />+}++function Container() {+ return (+ <div>+ {loading && <LoadingSkeleton />}+ </div>+ )+}+```++**Correct: reuses same element**++```tsx+const loadingSkeleton = (+ <div className="animate-pulse h-20 bg-gray-200" />+)++function Container() {+ return (+ <div>+ {loading && loadingSkeleton}+ </div>+ )+}+```++This is especially helpful for large and static SVG nodes, which can be expensive to recreate on every render.++**Note:** If your project has [React Compiler](https://react.dev/learn/react-compiler) enabled, the compiler automatically hoists static JSX elements and optimizes component re-renders, making manual hoisting unnecessary.++### 6.4 Optimize SVG Precision++**Impact: LOW (reduces file size)**++Reduce SVG coordinate precision to decrease file size. The optimal precision depends on the viewBox size, but in general reducing precision should be considered.++**Incorrect: excessive precision**++```svg+<path d="M 10.293847 20.847362 L 30.938472 40.192837" />+```++**Correct: 1 decimal place**++```svg+<path d="M 10.3 20.8 L 30.9 40.2" />+```++**Automate with SVGO:**++```bash+npx svgo --precision=1 --multipass icon.svg+```++### 6.5 Prevent Hydration Mismatch Without Flickering++**Impact: MEDIUM (avoids visual flicker and hydration errors)**++When rendering content that depends on client-side storage (localStorage, cookies), avoid both SSR breakage and post-hydration flickering by injecting a synchronous script that updates the DOM before React hydrates.++**Incorrect: breaks SSR**++```tsx+function ThemeWrapper({ children }: { children: ReactNode }) {+ // localStorage is not available on server - throws error+ const theme = localStorage.getItem('theme') || 'light'++ return (+ <div className={theme}>+ {children}+ </div>+ )+}+```++Server-side rendering will fail because `localStorage` is undefined.++**Incorrect: visual flickering**++```tsx+function ThemeWrapper({ children }: { children: ReactNode }) {+ const [theme, setTheme] = useState('light')++ useEffect(() => {+ // Runs after hydration - causes visible flash+ const stored = localStorage.getItem('theme')+ if (stored) {+ setTheme(stored)+ }+ }, [])++ return (+ <div className={theme}>+ {children}+ </div>+ )+}+```++Component first renders with default value (`light`), then updates after hydration, causing a visible flash of incorrect content.++**Correct: no flicker, no hydration mismatch**++```tsx+function ThemeWrapper({ children }: { children: ReactNode }) {+ return (+ <>+ <div id="theme-wrapper">+ {children}+ </div>+ <script+ dangerouslySetInnerHTML={{+ __html: `+ (function() {+ try {+ var theme = localStorage.getItem('theme') || 'light';+ var el = document.getElementById('theme-wrapper');+ if (el) el.className = theme;+ } catch (e) {}+ })();+ `,+ }}+ />+ </>+ )+}+```++The inline script executes synchronously before showing the element, ensuring the DOM already has the correct value. No flickering, no hydration mismatch.++This pattern is especially useful for theme toggles, user preferences, authentication states, and any client-only data that should render immediately without flashing default values.++### 6.6 Suppress Expected Hydration Mismatches++**Impact: LOW-MEDIUM (avoids noisy hydration warnings for known differences)**++In SSR frameworks (e.g., Next.js), some values are intentionally different on server vs client (random IDs, dates, locale/timezone formatting). For these *expected* mismatches, wrap the dynamic text in an element with `suppressHydrationWarning` to prevent noisy warnings. Do not use this to hide real bugs. Don’t overuse it.++**Incorrect: known mismatch warnings**++```tsx+function Timestamp() {+ return <span>{new Date().toLocaleString()}</span>+}+```++**Correct: suppress expected mismatch only**++```tsx+function Timestamp() {+ return (+ <span suppressHydrationWarning>+ {new Date().toLocaleString()}+ </span>+ )+}+```++### 6.7 Use Activity Component for Show/Hide++**Impact: MEDIUM (preserves state/DOM)**++Use React's `<Activity>` to preserve state/DOM for expensive components that frequently toggle visibility.++**Usage:**++```tsx+import { Activity } from 'react'++function Dropdown({ isOpen }: Props) {+ return (+ <Activity mode={isOpen ? 'visible' : 'hidden'}>+ <ExpensiveMenu />+ </Activity>+ )+}+```++Avoids expensive re-renders and state loss.++### 6.8 Use defer or async on Script Tags++**Impact: HIGH (eliminates render-blocking)**++Script tags without `defer` or `async` block HTML parsing while the script downloads and executes. This delays First Contentful Paint and Time to Interactive.++- **`defer`**: Downloads in parallel, executes after HTML parsing completes, maintains execution order++- **`async`**: Downloads in parallel, executes immediately when ready, no guaranteed order++Use `defer` for scripts that depend on DOM or other scripts. Use `async` for independent scripts like analytics.++**Incorrect: blocks rendering**++```tsx+export default function Document() {+ return (+ <html>+ <head>+ <script src="https://example.com/analytics.js" />+ <script src="/scripts/utils.js" />+ </head>+ <body>{/* content */}</body>+ </html>+ )+}+```++**Correct: non-blocking**++```tsx+import Script from 'next/script'++export default function Page() {+ return (+ <>+ <Script src="https://example.com/analytics.js" strategy="afterInteractive" />+ <Script src="/scripts/utils.js" strategy="beforeInteractive" />+ </>+ )+}+```++**Note:** In Next.js, prefer the `next/script` component with `strategy` prop instead of raw script tags:++Reference: [https://developer.mozilla.org/en-US/docs/Web/HTML/Element/script#defer](https://developer.mozilla.org/en-US/docs/Web/HTML/Element/script#defer)++### 6.9 Use Explicit Conditional Rendering++**Impact: LOW (prevents rendering 0 or NaN)**++Use explicit ternary operators (`? :`) instead of `&&` for conditional rendering when the condition can be `0`, `NaN`, or other falsy values that render.++**Incorrect: renders "0" when count is 0**++```tsx+function Badge({ count }: { count: number }) {+ return (+ <div>+ {count && <span className="badge">{count}</span>}+ </div>+ )+}++// When count = 0, renders: <div>0</div>+// When count = 5, renders: <div><span class="badge">5</span></div>+```++**Correct: renders nothing when count is 0**++```tsx+function Badge({ count }: { count: number }) {+ return (+ <div>+ {count > 0 ? <span className="badge">{count}</span> : null}+ </div>+ )+}++// When count = 0, renders: <div></div>+// When count = 5, renders: <div><span class="badge">5</span></div>+```++### 6.10 Use React DOM Resource Hints++**Impact: HIGH (reduces load time for critical resources)**++React DOM provides APIs to hint the browser about resources it will need. These are especially useful in server components to start loading resources before the client even receives the HTML.++- **`prefetchDNS(href)`**: Resolve DNS for a domain you expect to connect to++- **`preconnect(href)`**: Establish connection (DNS + TCP + TLS) to a server++- **`preload(href, options)`**: Fetch a resource (stylesheet, font, script, image) you'll use soon++- **`preloadModule(href)`**: Fetch an ES module you'll use soon++- **`preinit(href, options)`**: Fetch and evaluate a stylesheet or script++- **`preinitModule(href)`**: Fetch and evaluate an ES module++**Example: preconnect to third-party APIs**++```tsx+import { preconnect, prefetchDNS } from 'react-dom'++export default function App() {+ prefetchDNS('https://analytics.example.com')+ preconnect('https://api.example.com')++ return <main>{/* content */}</main>+}+```++**Example: preload critical fonts and styles**++```tsx+import { preload, preinit } from 'react-dom'++export default function RootLayout({ children }) {+ // Preload font file+ preload('/fonts/inter.woff2', { as: 'font', type: 'font/woff2', crossOrigin: 'anonymous' })++ // Fetch and apply critical stylesheet immediately+ preinit('/styles/critical.css', { as: 'style' })++ return (+ <html>+ <body>{children}</body>+ </html>+ )+}+```++**Example: preload modules for code-split routes**++```tsx+import { preloadModule, preinitModule } from 'react-dom'++function Navigation() {+ const preloadDashboard = () => {+ preloadModule('/dashboard.js', { as: 'script' })+ }++ return (+ <nav>+ <a href="/dashboard" onMouseEnter={preloadDashboard}>+ Dashboard+ </a>+ </nav>+ )+}+```++**When to use each:**++| API | Use case |++|-----|----------|++| `prefetchDNS` | Third-party domains you'll connect to later |++| `preconnect` | APIs or CDNs you'll fetch from immediately |++| `preload` | Critical resources needed for current page |++| `preloadModule` | JS modules for likely next navigation |++| `preinit` | Stylesheets/scripts that must execute early |++| `preinitModule` | ES modules that must execute early |++Reference: [https://react.dev/reference/react-dom#resource-preloading-apis](https://react.dev/reference/react-dom#resource-preloading-apis)++### 6.11 Use useTransition Over Manual Loading States++**Impact: LOW (reduces re-renders and improves code clarity)**++Use `useTransition` instead of manual `useState` for loading states. This provides built-in `isPending` state and automatically manages transitions.++**Incorrect: manual loading state**++```tsx+function SearchResults() {+ const [query, setQuery] = useState('')+ const [results, setResults] = useState([])+ const [isLoading, setIsLoading] = useState(false)++ const handleSearch = async (value: string) => {+ setIsLoading(true)+ setQuery(value)+ const data = await fetchResults(value)+ setResults(data)+ setIsLoading(false)+ }++ return (+ <>+ <input onChange={(e) => handleSearch(e.target.value)} />+ {isLoading && <Spinner />}+ <ResultsList results={results} />+ </>+ )+}+```++**Correct: useTransition with built-in pending state**++```tsx+import { useTransition, useState } from 'react'++function SearchResults() {+ const [query, setQuery] = useState('')+ const [results, setResults] = useState([])+ const [isPending, startTransition] = useTransition()++ const handleSearch = (value: string) => {+ setQuery(value) // Update input immediately++ startTransition(async () => {+ // Fetch and update results+ const data = await fetchResults(value)+ setResults(data)+ })+ }++ return (+ <>+ <input onChange={(e) => handleSearch(e.target.value)} />+ {isPending && <Spinner />}+ <ResultsList results={results} />+ </>+ )+}+```++**Benefits:**++- **Automatic pending state**: No need to manually manage `setIsLoading(true/false)`++- **Error resilience**: Pending state correctly resets even if the transition throws++- **Better responsiveness**: Keeps the UI responsive during updates++- **Interrupt handling**: New transitions automatically cancel pending ones++Reference: [https://react.dev/reference/react/useTransition](https://react.dev/reference/react/useTransition)++---++## 7. JavaScript Performance++**Impact: LOW-MEDIUM**++Micro-optimizations for hot paths can add up to meaningful improvements.++### 7.1 Avoid Layout Thrashing++**Impact: MEDIUM (prevents forced synchronous layouts and reduces performance bottlenecks)**++Avoid interleaving style writes with layout reads. When you read a layout property (like `offsetWidth`, `getBoundingClientRect()`, or `getComputedStyle()`) between style changes, the browser is forced to trigger a synchronous reflow.++**This is OK: browser batches style changes**++```typescript+function updateElementStyles(element: HTMLElement) {+ // Each line invalidates style, but browser batches the recalculation+ element.style.width = '100px'+ element.style.height = '200px'+ element.style.backgroundColor = 'blue'+ element.style.border = '1px solid black'+}+```++**Incorrect: interleaved reads and writes force reflows**++```typescript+function layoutThrashing(element: HTMLElement) {+ element.style.width = '100px'+ const width = element.offsetWidth // Forces reflow+ element.style.height = '200px'+ const height = element.offsetHeight // Forces another reflow+}+```++**Correct: batch writes, then read once**++```typescript+function updateElementStyles(element: HTMLElement) {+ // Batch all writes together+ element.style.width = '100px'+ element.style.height = '200px'+ element.style.backgroundColor = 'blue'+ element.style.border = '1px solid black'++ // Read after all writes are done (single reflow)+ const { width, height } = element.getBoundingClientRect()+}+```++**Correct: batch reads, then writes**++```typescript+function updateElementStyles(element: HTMLElement) {+ element.classList.add('highlighted-box')++ const { width, height } = element.getBoundingClientRect()+}+```++**Better: use CSS classes**++**React example:**++```tsx+// Incorrect: interleaving style changes with layout queries+function Box({ isHighlighted }: { isHighlighted: boolean }) {+ const ref = useRef<HTMLDivElement>(null)++ useEffect(() => {+ if (ref.current && isHighlighted) {+ ref.current.style.width = '100px'+ const width = ref.current.offsetWidth // Forces layout+ ref.current.style.height = '200px'+ }+ }, [isHighlighted])++ return <div ref={ref}>Content</div>+}++// Correct: toggle class+function Box({ isHighlighted }: { isHighlighted: boolean }) {+ return (+ <div className={isHighlighted ? 'highlighted-box' : ''}>+ Content+ </div>+ )+}+```++Prefer CSS classes over inline styles when possible. CSS files are cached by the browser, and classes provide better separation of concerns and are easier to maintain.++See [this gist](https://gist.github.com/paulirish/5d52fb081b3570c81e3a) and [CSS Triggers](https://csstriggers.com/) for more information on layout-forcing operations.++### 7.2 Build Index Maps for Repeated Lookups++**Impact: LOW-MEDIUM (1M ops to 2K ops)**++Multiple `.find()` calls by the same key should use a Map.++**Incorrect (O(n) per lookup):**++```typescript+function processOrders(orders: Order[], users: User[]) {+ return orders.map(order => ({+ ...order,+ user: users.find(u => u.id === order.userId)+ }))+}+```++**Correct (O(1) per lookup):**++```typescript+function processOrders(orders: Order[], users: User[]) {+ const userById = new Map(users.map(u => [u.id, u]))++ return orders.map(order => ({+ ...order,+ user: userById.get(order.userId)+ }))+}+```++Build map once (O(n)), then all lookups are O(1).++For 1000 orders × 1000 users: 1M ops → 2K ops.++### 7.3 Cache Property Access in Loops++**Impact: LOW-MEDIUM (reduces lookups)**++Cache object property lookups in hot paths.++**Incorrect: 3 lookups × N iterations**++```typescript+for (let i = 0; i < arr.length; i++) {+ process(obj.config.settings.value)+}+```++**Correct: 1 lookup total**++```typescript+const value = obj.config.settings.value+const len = arr.length+for (let i = 0; i < len; i++) {+ process(value)+}+```++### 7.4 Cache Repeated Function Calls++**Impact: MEDIUM (avoid redundant computation)**++Use a module-level Map to cache function results when the same function is called repeatedly with the same inputs during render.++**Incorrect: redundant computation**++```typescript+function ProjectList({ projects }: { projects: Project[] }) {+ return (+ <div>+ {projects.map(project => {+ // slugify() called 100+ times for same project names+ const slug = slugify(project.name)++ return <ProjectCard key={project.id} slug={slug} />+ })}+ </div>+ )+}+```++**Correct: cached results**++```typescript+// Module-level cache+const slugifyCache = new Map<string, string>()++function cachedSlugify(text: string): string {+ if (slugifyCache.has(text)) {+ return slugifyCache.get(text)!+ }+ const result = slugify(text)+ slugifyCache.set(text, result)+ return result+}++function ProjectList({ projects }: { projects: Project[] }) {+ return (+ <div>+ {projects.map(project => {+ // Computed only once per unique project name+ const slug = cachedSlugify(project.name)++ return <ProjectCard key={project.id} slug={slug} />+ })}+ </div>+ )+}+```++**Simpler pattern for single-value functions:**++```typescript+let isLoggedInCache: boolean | null = null++function isLoggedIn(): boolean {+ if (isLoggedInCache !== null) {+ return isLoggedInCache+ }++ isLoggedInCache = document.cookie.includes('auth=')+ return isLoggedInCache+}++// Clear cache when auth changes+function onAuthChange() {+ isLoggedInCache = null+}+```++Use a Map (not a hook) so it works everywhere: utilities, event handlers, not just React components.++Reference: [https://vercel.com/blog/how-we-made-the-vercel-dashboard-twice-as-fast](https://vercel.com/blog/how-we-made-the-vercel-dashboard-twice-as-fast)++### 7.5 Cache Storage API Calls++**Impact: LOW-MEDIUM (reduces expensive I/O)**++`localStorage`, `sessionStorage`, and `document.cookie` are synchronous and expensive. Cache reads in memory.++**Incorrect: reads storage on every call**++```typescript+function getTheme() {+ return localStorage.getItem('theme') ?? 'light'+}+// Called 10 times = 10 storage reads+```++**Correct: Map cache**++```typescript+const storageCache = new Map<string, string | null>()++function getLocalStorage(key: string) {+ if (!storageCache.has(key)) {+ storageCache.set(key, localStorage.getItem(key))+ }+ return storageCache.get(key)+}++function setLocalStorage(key: string, value: string) {+ localStorage.setItem(key, value)+ storageCache.set(key, value) // keep cache in sync+}+```++Use a Map (not a hook) so it works everywhere: utilities, event handlers, not just React components.++**Cookie caching:**++```typescript+let cookieCache: Record<string, string> | null = null++function getCookie(name: string) {+ if (!cookieCache) {+ cookieCache = Object.fromEntries(+ document.cookie.split('; ').map(c => c.split('='))+ )+ }+ return cookieCache[name]+}+```++**Important: invalidate on external changes**++```typescript+window.addEventListener('storage', (e) => {+ if (e.key) storageCache.delete(e.key)+})++document.addEventListener('visibilitychange', () => {+ if (document.visibilityState === 'visible') {+ storageCache.clear()+ }+})+```++If storage can change externally (another tab, server-set cookies), invalidate cache:++### 7.6 Combine Multiple Array Iterations++**Impact: LOW-MEDIUM (reduces iterations)**++Multiple `.filter()` or `.map()` calls iterate the array multiple times. Combine into one loop.++**Incorrect: 3 iterations**++```typescript+const admins = users.filter(u => u.isAdmin)+const testers = users.filter(u => u.isTester)+const inactive = users.filter(u => !u.isActive)+```++**Correct: 1 iteration**++```typescript+const admins: User[] = []+const testers: User[] = []+const inactive: User[] = []++for (const user of users) {+ if (user.isAdmin) admins.push(user)+ if (user.isTester) testers.push(user)+ if (!user.isActive) inactive.push(user)+}+```++### 7.7 Defer Non-Critical Work with requestIdleCallback++**Impact: MEDIUM (keeps UI responsive during background tasks)**++Use `requestIdleCallback()` to schedule non-critical work during browser idle periods. This keeps the main thread free for user interactions and animations, reducing jank and improving perceived performance.++**Incorrect: blocks main thread during user interaction**++```typescript+function handleSearch(query: string) {+ const results = searchItems(query)+ setResults(results)++ // These block the main thread immediately+ analytics.track('search', { query })+ saveToRecentSearches(query)+ prefetchTopResults(results.slice(0, 3))+}+```++**Correct: defers non-critical work to idle time**++```typescript+function handleSearch(query: string) {+ const results = searchItems(query)+ setResults(results)++ // Defer non-critical work to idle periods+ requestIdleCallback(() => {+ analytics.track('search', { query })+ })++ requestIdleCallback(() => {+ saveToRecentSearches(query)+ })++ requestIdleCallback(() => {+ prefetchTopResults(results.slice(0, 3))+ })+}+```++**With timeout for required work:**++```typescript+// Ensure analytics fires within 2 seconds even if browser stays busy+requestIdleCallback(+ () => analytics.track('page_view', { path: location.pathname }),+ { timeout: 2000 }+)+```++**Chunking large tasks:**++```typescript+function processLargeDataset(items: Item[]) {+ let index = 0++ function processChunk(deadline: IdleDeadline) {+ // Process items while we have idle time (aim for <50ms chunks)+ while (index < items.length && deadline.timeRemaining() > 0) {+ processItem(items[index])+ index+++ }++ // Schedule next chunk if more items remain+ if (index < items.length) {+ requestIdleCallback(processChunk)+ }+ }++ requestIdleCallback(processChunk)+}+```++**With fallback for unsupported browsers:**++```typescript+const scheduleIdleWork = window.requestIdleCallback ?? ((cb: () => void) => setTimeout(cb, 1))++scheduleIdleWork(() => {+ // Non-critical work+})+```++**When to use:**++- Analytics and telemetry++- Saving state to localStorage/IndexedDB++- Prefetching resources for likely next actions++- Processing non-urgent data transformations++- Lazy initialization of non-critical features++**When NOT to use:**++- User-initiated actions that need immediate feedback++- Rendering updates the user is waiting for++- Time-sensitive operations++### 7.8 Early Length Check for Array Comparisons++**Impact: MEDIUM-HIGH (avoids expensive operations when lengths differ)**++When comparing arrays with expensive operations (sorting, deep equality, serialization), check lengths first. If lengths differ, the arrays cannot be equal.++In real-world applications, this optimization is especially valuable when the comparison runs in hot paths (event handlers, render loops).++**Incorrect: always runs expensive comparison**++```typescript+function hasChanges(current: string[], original: string[]) {+ // Always sorts and joins, even when lengths differ+ return current.sort().join() !== original.sort().join()+}+```++Two O(n log n) sorts run even when `current.length` is 5 and `original.length` is 100. There is also overhead of joining the arrays and comparing the strings.++**Correct (O(1) length check first):**++```typescript+function hasChanges(current: string[], original: string[]) {+ // Early return if lengths differ+ if (current.length !== original.length) {+ return true+ }+ // Only sort when lengths match+ const currentSorted = current.toSorted()+ const originalSorted = original.toSorted()+ for (let i = 0; i < currentSorted.length; i++) {+ if (currentSorted[i] !== originalSorted[i]) {+ return true+ }+ }+ return false+}+```++This new approach is more efficient because:++- It avoids the overhead of sorting and joining the arrays when lengths differ++- It avoids consuming memory for the joined strings (especially important for large arrays)++- It avoids mutating the original arrays++- It returns early when a difference is found++### 7.9 Early Return from Functions++**Impact: LOW-MEDIUM (avoids unnecessary computation)**++Return early when result is determined to skip unnecessary processing.++**Incorrect: processes all items even after finding answer**++```typescript+function validateUsers(users: User[]) {+ let hasError = false+ let errorMessage = ''++ for (const user of users) {+ if (!user.email) {+ hasError = true+ errorMessage = 'Email required'+ }+ if (!user.name) {+ hasError = true+ errorMessage = 'Name required'+ }+ // Continues checking all users even after error found+ }++ return hasError ? { valid: false, error: errorMessage } : { valid: true }+}+```++**Correct: returns immediately on first error**++```typescript+function validateUsers(users: User[]) {+ for (const user of users) {+ if (!user.email) {+ return { valid: false, error: 'Email required' }+ }+ if (!user.name) {+ return { valid: false, error: 'Name required' }+ }+ }++ return { valid: true }+}+```++### 7.10 Hoist RegExp Creation++**Impact: LOW-MEDIUM (avoids recreation)**++Don't create RegExp inside render. Hoist to module scope or memoize with `useMemo()`.++**Incorrect: new RegExp every render**++```tsx+function Highlighter({ text, query }: Props) {+ const regex = new RegExp(`(${query})`, 'gi')+ const parts = text.split(regex)+ return <>{parts.map((part, i) => ...)}</>+}+```++**Correct: memoize or hoist**++```tsx+const EMAIL_REGEX = /^[^\s@]+@[^\s@]+\.[^\s@]+$/++function Highlighter({ text, query }: Props) {+ const regex = useMemo(+ () => new RegExp(`(${escapeRegex(query)})`, 'gi'),+ [query]+ )+ const parts = text.split(regex)+ return <>{parts.map((part, i) => ...)}</>+}+```++**Warning: global regex has mutable state**++```typescript+const regex = /foo/g+regex.test('foo') // true, lastIndex = 3+regex.test('foo') // false, lastIndex = 0+```++Global regex (`/g`) has mutable `lastIndex` state:++### 7.11 Use flatMap to Map and Filter in One Pass++**Impact: LOW-MEDIUM (eliminates intermediate array)**++Chaining `.map().filter(Boolean)` creates an intermediate array and iterates twice. Use `.flatMap()` to transform and filter in a single pass.++**Incorrect: 2 iterations, intermediate array**++```typescript+const userNames = users+ .map(user => user.isActive ? user.name : null)+ .filter(Boolean)+```++**Correct: 1 iteration, no intermediate array**++```typescript+const userNames = users.flatMap(user =>+ user.isActive ? [user.name] : []+)+```++**More examples:**++```typescript+// Extract valid emails from responses+// Before+const emails = responses+ .map(r => r.success ? r.data.email : null)+ .filter(Boolean)++// After+const emails = responses.flatMap(r =>+ r.success ? [r.data.email] : []+)++// Parse and filter valid numbers+// Before+const numbers = strings+ .map(s => parseInt(s, 10))+ .filter(n => !isNaN(n))++// After+const numbers = strings.flatMap(s => {+ const n = parseInt(s, 10)+ return isNaN(n) ? [] : [n]+})+```++**When to use:**++- Transforming items while filtering some out++- Conditional mapping where some inputs produce no output++- Parsing/validating where invalid inputs should be skipped++### 7.12 Use Loop for Min/Max Instead of Sort++**Impact: LOW (O(n) instead of O(n log n))**++Finding the smallest or largest element only requires a single pass through the array. Sorting is wasteful and slower.++**Incorrect (O(n log n) - sort to find latest):**++```typescript+interface Project {+ id: string+ name: string+ updatedAt: number+}++function getLatestProject(projects: Project[]) {+ const sorted = [...projects].sort((a, b) => b.updatedAt - a.updatedAt)+ return sorted[0]+}+```++Sorts the entire array just to find the maximum value.++**Incorrect (O(n log n) - sort for oldest and newest):**++```typescript+function getOldestAndNewest(projects: Project[]) {+ const sorted = [...projects].sort((a, b) => a.updatedAt - b.updatedAt)+ return { oldest: sorted[0], newest: sorted[sorted.length - 1] }+}+```++Still sorts unnecessarily when only min/max are needed.++**Correct (O(n) - single loop):**++```typescript+function getLatestProject(projects: Project[]) {+ if (projects.length === 0) return null++ let latest = projects[0]++ for (let i = 1; i < projects.length; i++) {+ if (projects[i].updatedAt > latest.updatedAt) {+ latest = projects[i]+ }+ }++ return latest+}++function getOldestAndNewest(projects: Project[]) {+ if (projects.length === 0) return { oldest: null, newest: null }++ let oldest = projects[0]+ let newest = projects[0]++ for (let i = 1; i < projects.length; i++) {+ if (projects[i].updatedAt < oldest.updatedAt) oldest = projects[i]+ if (projects[i].updatedAt > newest.updatedAt) newest = projects[i]+ }++ return { oldest, newest }+}+```++Single pass through the array, no copying, no sorting.++**Alternative: Math.min/Math.max for small arrays**++```typescript+const numbers = [5, 2, 8, 1, 9]+const min = Math.min(...numbers)+const max = Math.max(...numbers)+```++This works for small arrays, but can be slower or just throw an error for very large arrays due to spread operator limitations. Maximal array length is approximately 124000 in Chrome 143 and 638000 in Safari 18; exact numbers may vary - see [the fiddle](https://jsfiddle.net/qw1jabsx/4/). Use the loop approach for reliability.++### 7.13 Use Set/Map for O(1) Lookups++**Impact: LOW-MEDIUM (O(n) to O(1))**++Convert arrays to Set/Map for repeated membership checks.++**Incorrect (O(n) per check):**++```typescript+const allowedIds = ['a', 'b', 'c', ...]+items.filter(item => allowedIds.includes(item.id))+```++**Correct (O(1) per check):**++```typescript+const allowedIds = new Set(['a', 'b', 'c', ...])+items.filter(item => allowedIds.has(item.id))+```++### 7.14 Use toSorted() Instead of sort() for Immutability++**Impact: MEDIUM-HIGH (prevents mutation bugs in React state)**++`.sort()` mutates the array in place, which can cause bugs with React state and props. Use `.toSorted()` to create a new sorted array without mutation.++**Incorrect: mutates original array**++```typescript+function UserList({ users }: { users: User[] }) {+ // Mutates the users prop array!+ const sorted = useMemo(+ () => users.sort((a, b) => a.name.localeCompare(b.name)),+ [users]+ )+ return <div>{sorted.map(renderUser)}</div>+}+```++**Correct: creates new array**++```typescript+function UserList({ users }: { users: User[] }) {+ // Creates new sorted array, original unchanged+ const sorted = useMemo(+ () => users.toSorted((a, b) => a.name.localeCompare(b.name)),+ [users]+ )+ return <div>{sorted.map(renderUser)}</div>+}+```++**Why this matters in React:**++1. Props/state mutations break React's immutability model - React expects props and state to be treated as read-only++2. Causes stale closure bugs - Mutating arrays inside closures (callbacks, effects) can lead to unexpected behavior++**Browser support: fallback for older browsers**++```typescript+// Fallback for older browsers+const sorted = [...items].sort((a, b) => a.value - b.value)+```++`.toSorted()` is available in all modern browsers (Chrome 110+, Safari 16+, Firefox 115+, Node.js 20+). For older environments, use spread operator:++**Other immutable array methods:**++- `.toSorted()` - immutable sort++- `.toReversed()` - immutable reverse++- `.toSpliced()` - immutable splice++- `.with()` - immutable element replacement++---++## 8. Advanced Patterns++**Impact: LOW**++Advanced patterns for specific cases that require careful implementation.++### 8.1 Do Not Put Effect Events in Dependency Arrays++**Impact: LOW (avoids unnecessary effect re-runs and lint errors)**++Effect Event functions do not have a stable identity. Their identity intentionally changes on every render. Do not include the function returned by `useEffectEvent` in a `useEffect` dependency array. Keep the actual reactive values as dependencies and call the Effect Event from inside the effect body or subscriptions created by that effect.++**Incorrect: Effect Event added as a dependency**++```tsx+import { useEffect, useEffectEvent } from 'react'++function ChatRoom({ roomId, onConnected }: {+ roomId: string+ onConnected: () => void+}) {+ const handleConnected = useEffectEvent(onConnected)++ useEffect(() => {+ const connection = createConnection(roomId)+ connection.on('connected', handleConnected)+ connection.connect()++ return () => connection.disconnect()+ }, [roomId, handleConnected])+}+```++Including the Effect Event in dependencies makes the effect re-run every render and triggers the React Hooks lint rule.++**Correct: depend on reactive values, not the Effect Event**++```tsx+import { useEffect, useEffectEvent } from 'react'++function ChatRoom({ roomId, onConnected }: {+ roomId: string+ onConnected: () => void+}) {+ const handleConnected = useEffectEvent(onConnected)++ useEffect(() => {+ const connection = createConnection(roomId)+ connection.on('connected', handleConnected)+ connection.connect()++ return () => connection.disconnect()+ }, [roomId])+}+```++Reference: [https://react.dev/reference/react/useEffectEvent#effect-event-in-deps](https://react.dev/reference/react/useEffectEvent#effect-event-in-deps)++### 8.2 Initialize App Once, Not Per Mount++**Impact: LOW-MEDIUM (avoids duplicate init in development)**++Do not put app-wide initialization that must run once per app load inside `useEffect([])` of a component. Components can remount and effects will re-run. Use a module-level guard or top-level init in the entry module instead.++**Incorrect: runs twice in dev, re-runs on remount**++```tsx+function Comp() {+ useEffect(() => {+ loadFromStorage()+ checkAuthToken()+ }, [])++ // ...+}+```++**Correct: once per app load**++```tsx+let didInit = false++function Comp() {+ useEffect(() => {+ if (didInit) return+ didInit = true+ loadFromStorage()+ checkAuthToken()+ }, [])++ // ...+}+```++Reference: [https://react.dev/learn/you-might-not-need-an-effect#initializing-the-application](https://react.dev/learn/you-might-not-need-an-effect#initializing-the-application)++### 8.3 Store Event Handlers in Refs++**Impact: LOW (stable subscriptions)**++Store callbacks in refs when used in effects that shouldn't re-subscribe on callback changes.++**Incorrect: re-subscribes on every render**++```tsx+function useWindowEvent(event: string, handler: (e) => void) {+ useEffect(() => {+ window.addEventListener(event, handler)+ return () => window.removeEventListener(event, handler)+ }, [event, handler])+}+```++**Correct: stable subscription**++```tsx+import { useEffectEvent } from 'react'++function useWindowEvent(event: string, handler: (e) => void) {+ const onEvent = useEffectEvent(handler)++ useEffect(() => {+ window.addEventListener(event, onEvent)+ return () => window.removeEventListener(event, onEvent)+ }, [event])+}+```++**Alternative: use `useEffectEvent` if you're on latest React:**++`useEffectEvent` provides a cleaner API for the same pattern: it creates a stable function reference that always calls the latest version of the handler.++### 8.4 useEffectEvent for Stable Callback Refs++**Impact: LOW (prevents effect re-runs)**++Access latest values in callbacks without adding them to dependency arrays. Prevents effect re-runs while avoiding stale closures.++**Incorrect: effect re-runs on every callback change**++```tsx+function SearchInput({ onSearch }: { onSearch: (q: string) => void }) {+ const [query, setQuery] = useState('')++ useEffect(() => {+ const timeout = setTimeout(() => onSearch(query), 300)+ return () => clearTimeout(timeout)+ }, [query, onSearch])+}+```++**Correct: using React's useEffectEvent**++```tsx+import { useEffectEvent } from 'react';++function SearchInput({ onSearch }: { onSearch: (q: string) => void }) {+ const [query, setQuery] = useState('')+ const onSearchEvent = useEffectEvent(onSearch)++ useEffect(() => {+ const timeout = setTimeout(() => onSearchEvent(query), 300)+ return () => clearTimeout(timeout)+ }, [query])+}+```++---++## References++1. [https://react.dev](https://react.dev)+2. [https://nextjs.org](https://nextjs.org)+3. [https://swr.vercel.app](https://swr.vercel.app)+4. [https://github.com/shuding/better-all](https://github.com/shuding/better-all)+5. [https://github.com/isaacs/node-lru-cache](https://github.com/isaacs/node-lru-cache)+6. [https://vercel.com/blog/how-we-optimized-package-imports-in-next-js](https://vercel.com/blog/how-we-optimized-package-imports-in-next-js)+7. [https://vercel.com/blog/how-we-made-the-vercel-dashboard-twice-as-fast](https://vercel.com/blog/how-we-made-the-vercel-dashboard-twice-as-fast)diff --git a/.claude/skills/vercel-react-best-practices/README.md b/.claude/skills/vercel-react-best-practices/README.mdnew file mode 100644index 0000000..f283e1c--- /dev/null+++ b/.claude/skills/vercel-react-best-practices/README.md@@ -0,0 +1,123 @@+# React Best Practices++A structured repository for creating and maintaining React Best Practices optimized for agents and LLMs.++## Structure++- `rules/` - Individual rule files (one per rule)+ - `_sections.md` - Section metadata (titles, impacts, descriptions)+ - `_template.md` - Template for creating new rules+ - `area-description.md` - Individual rule files+- `src/` - Build scripts and utilities+- `metadata.json` - Document metadata (version, organization, abstract)+- __`AGENTS.md`__ - Compiled output (generated)+- __`test-cases.json`__ - Test cases for LLM evaluation (generated)++## Getting Started++1. Install dependencies:+ ```bash+ pnpm install+ ```++2. Build AGENTS.md from rules:+ ```bash+ pnpm build+ ```++3. Validate rule files:+ ```bash+ pnpm validate+ ```++4. Extract test cases:+ ```bash+ pnpm extract-tests+ ```++## Creating a New Rule++1. Copy `rules/_template.md` to `rules/area-description.md`+2. Choose the appropriate area prefix:+ - `async-` for Eliminating Waterfalls (Section 1)+ - `bundle-` for Bundle Size Optimization (Section 2)+ - `server-` for Server-Side Performance (Section 3)+ - `client-` for Client-Side Data Fetching (Section 4)+ - `rerender-` for Re-render Optimization (Section 5)+ - `rendering-` for Rendering Performance (Section 6)+ - `js-` for JavaScript Performance (Section 7)+ - `advanced-` for Advanced Patterns (Section 8)+3. Fill in the frontmatter and content+4. Ensure you have clear examples with explanations+5. Run `pnpm build` to regenerate AGENTS.md and test-cases.json++## Rule File Structure++Each rule file should follow this structure:++```markdown+---+title: Rule Title Here+impact: MEDIUM+impactDescription: Optional description+tags: tag1, tag2, tag3+---++## Rule Title Here++Brief explanation of the rule and why it matters.++**Incorrect (description of what's wrong):**++```typescript+// Bad code example+```++**Correct (description of what's right):**++```typescript+// Good code example+```++Optional explanatory text after examples.++Reference: [Link](https://example.com)++## File Naming Convention++- Files starting with `_` are special (excluded from build)+- Rule files: `area-description.md` (e.g., `async-parallel.md`)+- Section is automatically inferred from filename prefix+- Rules are sorted alphabetically by title within each section+- IDs (e.g., 1.1, 1.2) are auto-generated during build++## Impact Levels++- `CRITICAL` - Highest priority, major performance gains+- `HIGH` - Significant performance improvements+- `MEDIUM-HIGH` - Moderate-high gains+- `MEDIUM` - Moderate performance improvements+- `LOW-MEDIUM` - Low-medium gains+- `LOW` - Incremental improvements++## Scripts++- `pnpm build` - Compile rules into AGENTS.md+- `pnpm validate` - Validate all rule files+- `pnpm extract-tests` - Extract test cases for LLM evaluation+- `pnpm dev` - Build and validate++## Contributing++When adding or modifying rules:++1. Use the correct filename prefix for your section+2. Follow the `_template.md` structure+3. Include clear bad/good examples with explanations+4. Add appropriate tags+5. Run `pnpm build` to regenerate AGENTS.md and test-cases.json+6. Rules are automatically sorted by title - no need to manage numbers!++## Acknowledgments++Originally created by [@shuding](https://x.com/shuding) at [Vercel](https://vercel.com).diff --git a/.claude/skills/vercel-react-best-practices/SKILL.md b/.claude/skills/vercel-react-best-practices/SKILL.mdnew file mode 100644index 0000000..237988d--- /dev/null+++ b/.claude/skills/vercel-react-best-practices/SKILL.md@@ -0,0 +1,149 @@+---+name: vercel-react-best-practices+description: React and Next.js performance optimization guidelines from Vercel Engineering. This skill should be used when writing, reviewing, or refactoring React/Next.js code to ensure optimal performance patterns. Triggers on tasks involving React components, Next.js pages, data fetching, bundle optimization, or performance improvements.+license: MIT+metadata:+ author: vercel+ version: "1.0.0"+---++# Vercel React Best Practices++Comprehensive performance optimization guide for React and Next.js applications, maintained by Vercel. Contains 70 rules across 8 categories, prioritized by impact to guide automated refactoring and code generation.++## When to Apply++Reference these guidelines when:+- Writing new React components or Next.js pages+- Implementing data fetching (client or server-side)+- Reviewing code for performance issues+- Refactoring existing React/Next.js code+- Optimizing bundle size or load times++## Rule Categories by Priority++| Priority | Category | Impact | Prefix |+|----------|----------|--------|--------|+| 1 | Eliminating Waterfalls | CRITICAL | `async-` |+| 2 | Bundle Size Optimization | CRITICAL | `bundle-` |+| 3 | Server-Side Performance | HIGH | `server-` |+| 4 | Client-Side Data Fetching | MEDIUM-HIGH | `client-` |+| 5 | Re-render Optimization | MEDIUM | `rerender-` |+| 6 | Rendering Performance | MEDIUM | `rendering-` |+| 7 | JavaScript Performance | LOW-MEDIUM | `js-` |+| 8 | Advanced Patterns | LOW | `advanced-` |++## Quick Reference++### 1. Eliminating Waterfalls (CRITICAL)++- `async-cheap-condition-before-await` - Check cheap sync conditions before awaiting flags or remote values+- `async-defer-await` - Move await into branches where actually used+- `async-parallel` - Use Promise.all() for independent operations+- `async-dependencies` - Use better-all for partial dependencies+- `async-api-routes` - Start promises early, await late in API routes+- `async-suspense-boundaries` - Use Suspense to stream content++### 2. Bundle Size Optimization (CRITICAL)++- `bundle-barrel-imports` - Import directly, avoid barrel files+- `bundle-analyzable-paths` - Prefer statically analyzable import and file-system paths to avoid broad bundles and traces+- `bundle-dynamic-imports` - Use next/dynamic for heavy components+- `bundle-defer-third-party` - Load analytics/logging after hydration+- `bundle-conditional` - Load modules only when feature is activated+- `bundle-preload` - Preload on hover/focus for perceived speed++### 3. Server-Side Performance (HIGH)++- `server-auth-actions` - Authenticate server actions like API routes+- `server-cache-react` - Use React.cache() for per-request deduplication+- `server-cache-lru` - Use LRU cache for cross-request caching+- `server-dedup-props` - Avoid duplicate serialization in RSC props+- `server-hoist-static-io` - Hoist static I/O (fonts, logos) to module level+- `server-no-shared-module-state` - Avoid module-level mutable request state in RSC/SSR+- `server-serialization` - Minimize data passed to client components+- `server-parallel-fetching` - Restructure components to parallelize fetches+- `server-parallel-nested-fetching` - Chain nested fetches per item in Promise.all+- `server-after-nonblocking` - Use after() for non-blocking operations++### 4. Client-Side Data Fetching (MEDIUM-HIGH)++- `client-swr-dedup` - Use SWR for automatic request deduplication+- `client-event-listeners` - Deduplicate global event listeners+- `client-passive-event-listeners` - Use passive listeners for scroll+- `client-localstorage-schema` - Version and minimize localStorage data++### 5. Re-render Optimization (MEDIUM)++- `rerender-defer-reads` - Don't subscribe to state only used in callbacks+- `rerender-memo` - Extract expensive work into memoized components+- `rerender-memo-with-default-value` - Hoist default non-primitive props+- `rerender-dependencies` - Use primitive dependencies in effects+- `rerender-derived-state` - Subscribe to derived booleans, not raw values+- `rerender-derived-state-no-effect` - Derive state during render, not effects+- `rerender-functional-setstate` - Use functional setState for stable callbacks+- `rerender-lazy-state-init` - Pass function to useState for expensive values+- `rerender-simple-expression-in-memo` - Avoid memo for simple primitives+- `rerender-split-combined-hooks` - Split hooks with independent dependencies+- `rerender-move-effect-to-event` - Put interaction logic in event handlers+- `rerender-transitions` - Use startTransition for non-urgent updates+- `rerender-use-deferred-value` - Defer expensive renders to keep input responsive+- `rerender-use-ref-transient-values` - Use refs for transient frequent values+- `rerender-no-inline-components` - Don't define components inside components++### 6. Rendering Performance (MEDIUM)++- `rendering-animate-svg-wrapper` - Animate div wrapper, not SVG element+- `rendering-content-visibility` - Use content-visibility for long lists+- `rendering-hoist-jsx` - Extract static JSX outside components+- `rendering-svg-precision` - Reduce SVG coordinate precision+- `rendering-hydration-no-flicker` - Use inline script for client-only data+- `rendering-hydration-suppress-warning` - Suppress expected mismatches+- `rendering-activity` - Use Activity component for show/hide+- `rendering-conditional-render` - Use ternary, not && for conditionals+- `rendering-usetransition-loading` - Prefer useTransition for loading state+- `rendering-resource-hints` - Use React DOM resource hints for preloading+- `rendering-script-defer-async` - Use defer or async on script tags++### 7. JavaScript Performance (LOW-MEDIUM)++- `js-batch-dom-css` - Group CSS changes via classes or cssText+- `js-index-maps` - Build Map for repeated lookups+- `js-cache-property-access` - Cache object properties in loops+- `js-cache-function-results` - Cache function results in module-level Map+- `js-cache-storage` - Cache localStorage/sessionStorage reads+- `js-combine-iterations` - Combine multiple filter/map into one loop+- `js-length-check-first` - Check array length before expensive comparison+- `js-early-exit` - Return early from functions+- `js-hoist-regexp` - Hoist RegExp creation outside loops+- `js-min-max-loop` - Use loop for min/max instead of sort+- `js-set-map-lookups` - Use Set/Map for O(1) lookups+- `js-tosorted-immutable` - Use toSorted() for immutability+- `js-flatmap-filter` - Use flatMap to map and filter in one pass+- `js-request-idle-callback` - Defer non-critical work to browser idle time++### 8. Advanced Patterns (LOW)++- `advanced-effect-event-deps` - Don't put `useEffectEvent` results in effect deps+- `advanced-event-handler-refs` - Store event handlers in refs+- `advanced-init-once` - Initialize app once per app load+- `advanced-use-latest` - useLatest for stable callback refs++## How to Use++Read individual rule files for detailed explanations and code examples:++```+rules/async-parallel.md+rules/bundle-barrel-imports.md+```++Each rule file contains:+- Brief explanation of why it matters+- Incorrect code example with explanation+- Correct code example with explanation+- Additional context and references++## Full Compiled Document++For the complete guide with all rules expanded: `AGENTS.md`diff --git a/.claude/skills/vercel-react-best-practices/rules/_sections.md b/.claude/skills/vercel-react-best-practices/rules/_sections.mdnew file mode 100644index 0000000..4d20c14--- /dev/null+++ b/.claude/skills/vercel-react-best-practices/rules/_sections.md@@ -0,0 +1,46 @@+# Sections++This file defines all sections, their ordering, impact levels, and descriptions.+The section ID (in parentheses) is the filename prefix used to group rules.++---++## 1. Eliminating Waterfalls (async)++**Impact:** CRITICAL+**Description:** Waterfalls are the #1 performance killer. Each sequential await adds full network latency. Eliminating them yields the largest gains.++## 2. Bundle Size Optimization (bundle)++**Impact:** CRITICAL+**Description:** Reducing initial bundle size improves Time to Interactive and Largest Contentful Paint.++## 3. Server-Side Performance (server)++**Impact:** HIGH+**Description:** Optimizing server-side rendering and data fetching eliminates server-side waterfalls and reduces response times.++## 4. Client-Side Data Fetching (client)++**Impact:** MEDIUM-HIGH+**Description:** Automatic deduplication and efficient data fetching patterns reduce redundant network requests.++## 5. Re-render Optimization (rerender)++**Impact:** MEDIUM+**Description:** Reducing unnecessary re-renders minimizes wasted computation and improves UI responsiveness.++## 6. Rendering Performance (rendering)++**Impact:** MEDIUM+**Description:** Optimizing the rendering process reduces the work the browser needs to do.++## 7. JavaScript Performance (js)++**Impact:** LOW-MEDIUM+**Description:** Micro-optimizations for hot paths can add up to meaningful improvements.++## 8. Advanced Patterns (advanced)++**Impact:** LOW+**Description:** Advanced patterns for specific cases that require careful implementation.diff --git a/.claude/skills/vercel-react-best-practices/rules/_template.md b/.claude/skills/vercel-react-best-practices/rules/_template.mdnew file mode 100644index 0000000..1e9e707--- /dev/null+++ b/.claude/skills/vercel-react-best-practices/rules/_template.md@@ -0,0 +1,28 @@+---+title: Rule Title Here+impact: MEDIUM+impactDescription: Optional description of impact (e.g., "20-50% improvement")+tags: tag1, tag2+---++## Rule Title Here++**Impact: MEDIUM (optional impact description)**++Brief explanation of the rule and why it matters. This should be clear and concise, explaining the performance implications.++**Incorrect (description of what's wrong):**++```typescript+// Bad code example here+const bad = example()+```++**Correct (description of what's right):**++```typescript+// Good code example here+const good = example()+```++Reference: [Link to documentation or resource](https://example.com)diff --git a/.claude/skills/vercel-react-best-practices/rules/advanced-effect-event-deps.md b/.claude/skills/vercel-react-best-practices/rules/advanced-effect-event-deps.mdnew file mode 100644index 0000000..24d901b--- /dev/null+++ b/.claude/skills/vercel-react-best-practices/rules/advanced-effect-event-deps.md@@ -0,0 +1,56 @@+---+title: Do Not Put Effect Events in Dependency Arrays+impact: LOW+impactDescription: avoids unnecessary effect re-runs and lint errors+tags: advanced, hooks, useEffectEvent, dependencies, effects+---++## Do Not Put Effect Events in Dependency Arrays++Effect Event functions do not have a stable identity. Their identity intentionally changes on every render. Do not include the function returned by `useEffectEvent` in a `useEffect` dependency array. Keep the actual reactive values as dependencies and call the Effect Event from inside the effect body or subscriptions created by that effect.++**Incorrect (Effect Event added as a dependency):**++```tsx+import { useEffect, useEffectEvent } from 'react'++function ChatRoom({ roomId, onConnected }: {+ roomId: string+ onConnected: () => void+}) {+ const handleConnected = useEffectEvent(onConnected)++ useEffect(() => {+ const connection = createConnection(roomId)+ connection.on('connected', handleConnected)+ connection.connect()++ return () => connection.disconnect()+ }, [roomId, handleConnected])+}+```++Including the Effect Event in dependencies makes the effect re-run every render and triggers the React Hooks lint rule.++**Correct (depend on reactive values, not the Effect Event):**++```tsx+import { useEffect, useEffectEvent } from 'react'++function ChatRoom({ roomId, onConnected }: {+ roomId: string+ onConnected: () => void+}) {+ const handleConnected = useEffectEvent(onConnected)++ useEffect(() => {+ const connection = createConnection(roomId)+ connection.on('connected', handleConnected)+ connection.connect()++ return () => connection.disconnect()+ }, [roomId])+}+```++Reference: [React useEffectEvent: Effect Event in deps](https://react.dev/reference/react/useEffectEvent#effect-event-in-deps)diff --git a/.claude/skills/vercel-react-best-practices/rules/advanced-event-handler-refs.md b/.claude/skills/vercel-react-best-practices/rules/advanced-event-handler-refs.mdnew file mode 100644index 0000000..97e7ade--- /dev/null+++ b/.claude/skills/vercel-react-best-practices/rules/advanced-event-handler-refs.md@@ -0,0 +1,55 @@+---+title: Store Event Handlers in Refs+impact: LOW+impactDescription: stable subscriptions+tags: advanced, hooks, refs, event-handlers, optimization+---++## Store Event Handlers in Refs++Store callbacks in refs when used in effects that shouldn't re-subscribe on callback changes.++**Incorrect (re-subscribes on every render):**++```tsx+function useWindowEvent(event: string, handler: (e) => void) {+ useEffect(() => {+ window.addEventListener(event, handler)+ return () => window.removeEventListener(event, handler)+ }, [event, handler])+}+```++**Correct (stable subscription):**++```tsx+function useWindowEvent(event: string, handler: (e) => void) {+ const handlerRef = useRef(handler)+ useEffect(() => {+ handlerRef.current = handler+ }, [handler])++ useEffect(() => {+ const listener = (e) => handlerRef.current(e)+ window.addEventListener(event, listener)+ return () => window.removeEventListener(event, listener)+ }, [event])+}+```++**Alternative: use `useEffectEvent` if you're on latest React:**++```tsx+import { useEffectEvent } from 'react'++function useWindowEvent(event: string, handler: (e) => void) {+ const onEvent = useEffectEvent(handler)++ useEffect(() => {+ window.addEventListener(event, onEvent)+ return () => window.removeEventListener(event, onEvent)+ }, [event])+}+```++`useEffectEvent` provides a cleaner API for the same pattern: it creates a stable function reference that always calls the latest version of the handler.diff --git a/.claude/skills/vercel-react-best-practices/rules/advanced-init-once.md b/.claude/skills/vercel-react-best-practices/rules/advanced-init-once.mdnew file mode 100644index 0000000..73ee38e--- /dev/null+++ b/.claude/skills/vercel-react-best-practices/rules/advanced-init-once.md@@ -0,0 +1,42 @@+---+title: Initialize App Once, Not Per Mount+impact: LOW-MEDIUM+impactDescription: avoids duplicate init in development+tags: initialization, useEffect, app-startup, side-effects+---++## Initialize App Once, Not Per Mount++Do not put app-wide initialization that must run once per app load inside `useEffect([])` of a component. Components can remount and effects will re-run. Use a module-level guard or top-level init in the entry module instead.++**Incorrect (runs twice in dev, re-runs on remount):**++```tsx+function Comp() {+ useEffect(() => {+ loadFromStorage()+ checkAuthToken()+ }, [])++ // ...+}+```++**Correct (once per app load):**++```tsx+let didInit = false++function Comp() {+ useEffect(() => {+ if (didInit) return+ didInit = true+ loadFromStorage()+ checkAuthToken()+ }, [])++ // ...+}+```++Reference: [Initializing the application](https://react.dev/learn/you-might-not-need-an-effect#initializing-the-application)diff --git a/.claude/skills/vercel-react-best-practices/rules/advanced-use-latest.md b/.claude/skills/vercel-react-best-practices/rules/advanced-use-latest.mdnew file mode 100644index 0000000..9c7cb50--- /dev/null+++ b/.claude/skills/vercel-react-best-practices/rules/advanced-use-latest.md@@ -0,0 +1,39 @@+---+title: useEffectEvent for Stable Callback Refs+impact: LOW+impactDescription: prevents effect re-runs+tags: advanced, hooks, useEffectEvent, refs, optimization+---++## useEffectEvent for Stable Callback Refs++Access latest values in callbacks without adding them to dependency arrays. Prevents effect re-runs while avoiding stale closures.++**Incorrect (effect re-runs on every callback change):**++```tsx+function SearchInput({ onSearch }: { onSearch: (q: string) => void }) {+ const [query, setQuery] = useState('')++ useEffect(() => {+ const timeout = setTimeout(() => onSearch(query), 300)+ return () => clearTimeout(timeout)+ }, [query, onSearch])+}+```++**Correct (using React's useEffectEvent):**++```tsx+import { useEffectEvent } from 'react';++function SearchInput({ onSearch }: { onSearch: (q: string) => void }) {+ const [query, setQuery] = useState('')+ const onSearchEvent = useEffectEvent(onSearch)++ useEffect(() => {+ const timeout = setTimeout(() => onSearchEvent(query), 300)+ return () => clearTimeout(timeout)+ }, [query])+}+```diff --git a/.claude/skills/vercel-react-best-practices/rules/async-api-routes.md b/.claude/skills/vercel-react-best-practices/rules/async-api-routes.mdnew file mode 100644index 0000000..6feda1e--- /dev/null+++ b/.claude/skills/vercel-react-best-practices/rules/async-api-routes.md@@ -0,0 +1,38 @@+---+title: Prevent Waterfall Chains in API Routes+impact: CRITICAL+impactDescription: 2-10× improvement+tags: api-routes, server-actions, waterfalls, parallelization+---++## Prevent Waterfall Chains in API Routes++In API routes and Server Actions, start independent operations immediately, even if you don't await them yet.++**Incorrect (config waits for auth, data waits for both):**++```typescript+export async function GET(request: Request) {+ const session = await auth()+ const config = await fetchConfig()+ const data = await fetchData(session.user.id)+ return Response.json({ data, config })+}+```++**Correct (auth and config start immediately):**++```typescript+export async function GET(request: Request) {+ const sessionPromise = auth()+ const configPromise = fetchConfig()+ const session = await sessionPromise+ const [config, data] = await Promise.all([+ configPromise,+ fetchData(session.user.id)+ ])+ return Response.json({ data, config })+}+```++For operations with more complex dependency chains, use `better-all` to automatically maximize parallelism (see Dependency-Based Parallelization).diff --git a/.claude/skills/vercel-react-best-practices/rules/async-cheap-condition-before-await.md b/.claude/skills/vercel-react-best-practices/rules/async-cheap-condition-before-await.mdnew file mode 100644index 0000000..5799d7f--- /dev/null+++ b/.claude/skills/vercel-react-best-practices/rules/async-cheap-condition-before-await.md@@ -0,0 +1,37 @@+---+title: Check Cheap Conditions Before Async Flags+impact: HIGH+impactDescription: avoids unnecessary async work when a synchronous guard already fails+tags: async, await, feature-flags, short-circuit, conditional+---++## Check Cheap Conditions Before Async Flags++When a branch uses `await` for a flag or remote value and also requires a **cheap synchronous** condition (local props, request metadata, already-loaded state), evaluate the cheap condition **first**. Otherwise you pay for the async call even when the compound condition can never be true.++This is a specialization of [Defer Await Until Needed](./async-defer-await.md) for `flag && cheapCondition` style checks.++**Incorrect:**++```typescript+const someFlag = await getFlag()++if (someFlag && someCondition) {+ // ...+}+```++**Correct:**++```typescript+if (someCondition) {+ const someFlag = await getFlag()+ if (someFlag) {+ // ...+ }+}+```++This matters when `getFlag` hits the network, a feature-flag service, or `React.cache` / DB work: skipping it when `someCondition` is false removes that cost on the cold path.++Keep the original order if `someCondition` is expensive, depends on the flag, or you must run side effects in a fixed order.diff --git a/.claude/skills/vercel-react-best-practices/rules/async-defer-await.md b/.claude/skills/vercel-react-best-practices/rules/async-defer-await.mdnew file mode 100644index 0000000..460b5e1--- /dev/null+++ b/.claude/skills/vercel-react-best-practices/rules/async-defer-await.md@@ -0,0 +1,82 @@+---+title: Defer Await Until Needed+impact: HIGH+impactDescription: avoids blocking unused code paths+tags: async, await, conditional, optimization+---++## Defer Await Until Needed++Move `await` operations into the branches where they're actually used to avoid blocking code paths that don't need them.++**Incorrect (blocks both branches):**++```typescript+async function handleRequest(userId: string, skipProcessing: boolean) {+ const userData = await fetchUserData(userId)++ if (skipProcessing) {+ // Returns immediately but still waited for userData+ return { skipped: true }+ }++ // Only this branch uses userData+ return processUserData(userData)+}+```++**Correct (only blocks when needed):**++```typescript+async function handleRequest(userId: string, skipProcessing: boolean) {+ if (skipProcessing) {+ // Returns immediately without waiting+ return { skipped: true }+ }++ // Fetch only when needed+ const userData = await fetchUserData(userId)+ return processUserData(userData)+}+```++**Another example (early return optimization):**++```typescript+// Incorrect: always fetches permissions+async function updateResource(resourceId: string, userId: string) {+ const permissions = await fetchPermissions(userId)+ const resource = await getResource(resourceId)++ if (!resource) {+ return { error: 'Not found' }+ }++ if (!permissions.canEdit) {+ return { error: 'Forbidden' }+ }++ return await updateResourceData(resource, permissions)+}++// Correct: fetches only when needed+async function updateResource(resourceId: string, userId: string) {+ const resource = await getResource(resourceId)++ if (!resource) {+ return { error: 'Not found' }+ }++ const permissions = await fetchPermissions(userId)++ if (!permissions.canEdit) {+ return { error: 'Forbidden' }+ }++ return await updateResourceData(resource, permissions)+}+```++This optimization is especially valuable when the skipped branch is frequently taken, or when the deferred operation is expensive.++For `await getFlag()` combined with a cheap synchronous guard (`flag && someCondition`), see [Check Cheap Conditions Before Async Flags](./async-cheap-condition-before-await.md).diff --git a/.claude/skills/vercel-react-best-practices/rules/async-dependencies.md b/.claude/skills/vercel-react-best-practices/rules/async-dependencies.mdnew file mode 100644index 0000000..0484eba--- /dev/null+++ b/.claude/skills/vercel-react-best-practices/rules/async-dependencies.md@@ -0,0 +1,51 @@+---+title: Dependency-Based Parallelization+impact: CRITICAL+impactDescription: 2-10× improvement+tags: async, parallelization, dependencies, better-all+---++## Dependency-Based Parallelization++For operations with partial dependencies, use `better-all` to maximize parallelism. It automatically starts each task at the earliest possible moment.++**Incorrect (profile waits for config unnecessarily):**++```typescript+const [user, config] = await Promise.all([+ fetchUser(),+ fetchConfig()+])+const profile = await fetchProfile(user.id)+```++**Correct (config and profile run in parallel):**++```typescript+import { all } from 'better-all'++const { user, config, profile } = await all({+ async user() { return fetchUser() },+ async config() { return fetchConfig() },+ async profile() {+ return fetchProfile((await this.$.user).id)+ }+})+```++**Alternative without extra dependencies:**++We can also create all the promises first, and do `Promise.all()` at the end.++```typescript+const userPromise = fetchUser()+const profilePromise = userPromise.then(user => fetchProfile(user.id))++const [user, config, profile] = await Promise.all([+ userPromise,+ fetchConfig(),+ profilePromise+])+```++Reference: [https://github.com/shuding/better-all](https://github.com/shuding/better-all)diff --git a/.claude/skills/vercel-react-best-practices/rules/async-parallel.md b/.claude/skills/vercel-react-best-practices/rules/async-parallel.mdnew file mode 100644index 0000000..64133f6--- /dev/null+++ b/.claude/skills/vercel-react-best-practices/rules/async-parallel.md@@ -0,0 +1,28 @@+---+title: Promise.all() for Independent Operations+impact: CRITICAL+impactDescription: 2-10× improvement+tags: async, parallelization, promises, waterfalls+---++## Promise.all() for Independent Operations++When async operations have no interdependencies, execute them concurrently using `Promise.all()`.++**Incorrect (sequential execution, 3 round trips):**++```typescript+const user = await fetchUser()+const posts = await fetchPosts()+const comments = await fetchComments()+```++**Correct (parallel execution, 1 round trip):**++```typescript+const [user, posts, comments] = await Promise.all([+ fetchUser(),+ fetchPosts(),+ fetchComments()+])+```diff --git a/.claude/skills/vercel-react-best-practices/rules/async-suspense-boundaries.md b/.claude/skills/vercel-react-best-practices/rules/async-suspense-boundaries.mdnew file mode 100644index 0000000..1fbc05b--- /dev/null+++ b/.claude/skills/vercel-react-best-practices/rules/async-suspense-boundaries.md@@ -0,0 +1,99 @@+---+title: Strategic Suspense Boundaries+impact: HIGH+impactDescription: faster initial paint+tags: async, suspense, streaming, layout-shift+---++## Strategic Suspense Boundaries++Instead of awaiting data in async components before returning JSX, use Suspense boundaries to show the wrapper UI faster while data loads.++**Incorrect (wrapper blocked by data fetching):**++```tsx+async function Page() {+ const data = await fetchData() // Blocks entire page++ return (+ <div>+ <div>Sidebar</div>+ <div>Header</div>+ <div>+ <DataDisplay data={data} />+ </div>+ <div>Footer</div>+ </div>+ )+}+```++The entire layout waits for data even though only the middle section needs it.++**Correct (wrapper shows immediately, data streams in):**++```tsx+function Page() {+ return (+ <div>+ <div>Sidebar</div>+ <div>Header</div>+ <div>+ <Suspense fallback={<Skeleton />}>+ <DataDisplay />+ </Suspense>+ </div>+ <div>Footer</div>+ </div>+ )+}++async function DataDisplay() {+ const data = await fetchData() // Only blocks this component+ return <div>{data.content}</div>+}+```++Sidebar, Header, and Footer render immediately. Only DataDisplay waits for data.++**Alternative (share promise across components):**++```tsx+function Page() {+ // Start fetch immediately, but don't await+ const dataPromise = fetchData()++ return (+ <div>+ <div>Sidebar</div>+ <div>Header</div>+ <Suspense fallback={<Skeleton />}>+ <DataDisplay dataPromise={dataPromise} />+ <DataSummary dataPromise={dataPromise} />+ </Suspense>+ <div>Footer</div>+ </div>+ )+}++function DataDisplay({ dataPromise }: { dataPromise: Promise<Data> }) {+ const data = use(dataPromise) // Unwraps the promise+ return <div>{data.content}</div>+}++function DataSummary({ dataPromise }: { dataPromise: Promise<Data> }) {+ const data = use(dataPromise) // Reuses the same promise+ return <div>{data.summary}</div>+}+```++Both components share the same promise, so only one fetch occurs. Layout renders immediately while both components wait together.++**When NOT to use this pattern:**++- Critical data needed for layout decisions (affects positioning)+- SEO-critical content above the fold+- Small, fast queries where suspense overhead isn't worth it+- When you want to avoid layout shift (loading → content jump)++**Trade-off:** Faster initial paint vs potential layout shift. Choose based on your UX priorities.diff --git a/.claude/skills/vercel-react-best-practices/rules/bundle-analyzable-paths.md b/.claude/skills/vercel-react-best-practices/rules/bundle-analyzable-paths.mdnew file mode 100644index 0000000..8276f15--- /dev/null+++ b/.claude/skills/vercel-react-best-practices/rules/bundle-analyzable-paths.md@@ -0,0 +1,63 @@+---+title: Prefer Statically Analyzable Paths+impact: HIGH+impactDescription: avoids accidental broad bundles and file traces+tags: bundle, nextjs, vite, webpack, rollup, esbuild, path+---++## Prefer Statically Analyzable Paths++Build tools work best when import and file-system paths are obvious at build time. If you hide the real path inside a variable or compose it too dynamically, the tool either has to include a broad set of possible files, warn that it cannot analyze the import, or widen file tracing to stay safe.++Prefer explicit maps or literal paths so the set of reachable files stays narrow and predictable. This is the same rule whether you are choosing modules with `import()` or reading files in server/build code.++When analysis becomes too broad, the cost is real:+- Larger server bundles+- Slower builds+- Worse cold starts+- More memory use++### Import Paths++**Incorrect (the bundler cannot tell what may be imported):**++```ts+const PAGE_MODULES = {+ home: './pages/home',+ settings: './pages/settings',+} as const++const Page = await import(PAGE_MODULES[pageName])+```++**Correct (use an explicit map of allowed modules):**++```ts+const PAGE_MODULES = {+ home: () => import('./pages/home'),+ settings: () => import('./pages/settings'),+} as const++const Page = await PAGE_MODULES[pageName]()+```++### File-System Paths++**Incorrect (a 2-value enum still hides the final path from static analysis):**++```ts+const baseDir = path.join(process.cwd(), 'content/' + contentKind)+```++**Correct (make each final path literal at the callsite):**++```ts+const baseDir =+ kind === ContentKind.Blog+ ? path.join(process.cwd(), 'content/blog')+ : path.join(process.cwd(), 'content/docs')+```++In Next.js server code, this matters for output file tracing too. `path.join(process.cwd(), someVar)` can widen the traced file set because Next.js statically analyze `import`, `require`, and `fs` usage.++Reference: [Next.js output](https://nextjs.org/docs/app/api-reference/config/next-config-js/output), [Next.js dynamic imports](https://nextjs.org/learn/seo/dynamic-imports), [Vite features](https://vite.dev/guide/features.html), [esbuild API](https://esbuild.github.io/api/), [Rollup dynamic import vars](https://www.npmjs.com/package/@rollup/plugin-dynamic-import-vars), [Webpack dependency management](https://webpack.js.org/guides/dependency-management/)diff --git a/.claude/skills/vercel-react-best-practices/rules/bundle-barrel-imports.md b/.claude/skills/vercel-react-best-practices/rules/bundle-barrel-imports.mdnew file mode 100644index 0000000..22d1050--- /dev/null+++ b/.claude/skills/vercel-react-best-practices/rules/bundle-barrel-imports.md@@ -0,0 +1,60 @@+---+title: Avoid Barrel File Imports+impact: CRITICAL+impactDescription: 200-800ms import cost, slow builds+tags: bundle, imports, tree-shaking, barrel-files, performance+---++## Avoid Barrel File Imports++Import directly from source files instead of barrel files to avoid loading thousands of unused modules. **Barrel files** are entry points that re-export multiple modules (e.g., `index.js` that does `export * from './module'`).++Popular icon and component libraries can have **up to 10,000 re-exports** in their entry file. For many React packages, **it takes 200-800ms just to import them**, affecting both development speed and production cold starts.++**Why tree-shaking doesn't help:** When a library is marked as external (not bundled), the bundler can't optimize it. If you bundle it to enable tree-shaking, builds become substantially slower analyzing the entire module graph.++**Incorrect (imports entire library):**++```tsx+import { Check, X, Menu } from 'lucide-react'+// Loads 1,583 modules, takes ~2.8s extra in dev+// Runtime cost: 200-800ms on every cold start++import { Button, TextField } from '@mui/material'+// Loads 2,225 modules, takes ~4.2s extra in dev+```++**Correct - Next.js 13.5+ (recommended):**++```js+// next.config.js - automatically optimizes barrel imports at build time+module.exports = {+ experimental: {+ optimizePackageImports: ['lucide-react', '@mui/material']+ }+}+```++```tsx+// Keep the standard imports - Next.js transforms them to direct imports+import { Check, X, Menu } from 'lucide-react'+// Full TypeScript support, no manual path wrangling+```++This is the recommended approach because it preserves TypeScript type safety and editor autocompletion while still eliminating the barrel import cost.++**Correct - Direct imports (non-Next.js projects):**++```tsx+import Button from '@mui/material/Button'+import TextField from '@mui/material/TextField'+// Loads only what you use+```++> **TypeScript warning:** Some libraries (notably `lucide-react`) don't ship `.d.ts` files for their deep import paths. Importing from `lucide-react/dist/esm/icons/check` resolves to an implicit `any` type, causing errors under `strict` or `noImplicitAny`. Prefer `optimizePackageImports` when available, or verify the library exports types for its subpaths before using direct imports.++These optimizations provide 15-70% faster dev boot, 28% faster builds, 40% faster cold starts, and significantly faster HMR.++Libraries commonly affected: `lucide-react`, `@mui/material`, `@mui/icons-material`, `@tabler/icons-react`, `react-icons`, `@headlessui/react`, `@radix-ui/react-*`, `lodash`, `ramda`, `date-fns`, `rxjs`, `react-use`.++Reference: [How we optimized package imports in Next.js](https://vercel.com/blog/how-we-optimized-package-imports-in-next-js)diff --git a/.claude/skills/vercel-react-best-practices/rules/bundle-conditional.md b/.claude/skills/vercel-react-best-practices/rules/bundle-conditional.mdnew file mode 100644index 0000000..99d6fc9--- /dev/null+++ b/.claude/skills/vercel-react-best-practices/rules/bundle-conditional.md@@ -0,0 +1,31 @@+---+title: Conditional Module Loading+impact: HIGH+impactDescription: loads large data only when needed+tags: bundle, conditional-loading, lazy-loading+---++## Conditional Module Loading++Load large data or modules only when a feature is activated.++**Example (lazy-load animation frames):**++```tsx+function AnimationPlayer({ enabled, setEnabled }: { enabled: boolean; setEnabled: React.Dispatch<React.SetStateAction<boolean>> }) {+ const [frames, setFrames] = useState<Frame[] | null>(null)++ useEffect(() => {+ if (enabled && !frames && typeof window !== 'undefined') {+ import('./animation-frames.js')+ .then(mod => setFrames(mod.frames))+ .catch(() => setEnabled(false))+ }+ }, [enabled, frames, setEnabled])++ if (!frames) return <Skeleton />+ return <Canvas frames={frames} />+}+```++The `typeof window !== 'undefined'` check prevents bundling this module for SSR, optimizing server bundle size and build speed.diff --git a/.claude/skills/vercel-react-best-practices/rules/bundle-defer-third-party.md b/.claude/skills/vercel-react-best-practices/rules/bundle-defer-third-party.mdnew file mode 100644index 0000000..db041d1--- /dev/null+++ b/.claude/skills/vercel-react-best-practices/rules/bundle-defer-third-party.md@@ -0,0 +1,49 @@+---+title: Defer Non-Critical Third-Party Libraries+impact: MEDIUM+impactDescription: loads after hydration+tags: bundle, third-party, analytics, defer+---++## Defer Non-Critical Third-Party Libraries++Analytics, logging, and error tracking don't block user interaction. Load them after hydration.++**Incorrect (blocks initial bundle):**++```tsx+import { Analytics } from '@vercel/analytics/react'++export default function RootLayout({ children }) {+ return (+ <html>+ <body>+ {children}+ <Analytics />+ </body>+ </html>+ )+}+```++**Correct (loads after hydration):**++```tsx+import dynamic from 'next/dynamic'++const Analytics = dynamic(+ () => import('@vercel/analytics/react').then(m => m.Analytics),+ { ssr: false }+)++export default function RootLayout({ children }) {+ return (+ <html>+ <body>+ {children}+ <Analytics />+ </body>+ </html>+ )+}+```diff --git a/.claude/skills/vercel-react-best-practices/rules/bundle-dynamic-imports.md b/.claude/skills/vercel-react-best-practices/rules/bundle-dynamic-imports.mdnew file mode 100644index 0000000..60b6269--- /dev/null+++ b/.claude/skills/vercel-react-best-practices/rules/bundle-dynamic-imports.md@@ -0,0 +1,35 @@+---+title: Dynamic Imports for Heavy Components+impact: CRITICAL+impactDescription: directly affects TTI and LCP+tags: bundle, dynamic-import, code-splitting, next-dynamic+---++## Dynamic Imports for Heavy Components++Use `next/dynamic` to lazy-load large components not needed on initial render.++**Incorrect (Monaco bundles with main chunk ~300KB):**++```tsx+import { MonacoEditor } from './monaco-editor'++function CodePanel({ code }: { code: string }) {+ return <MonacoEditor value={code} />+}+```++**Correct (Monaco loads on demand):**++```tsx+import dynamic from 'next/dynamic'++const MonacoEditor = dynamic(+ () => import('./monaco-editor').then(m => m.MonacoEditor),+ { ssr: false }+)++function CodePanel({ code }: { code: string }) {+ return <MonacoEditor value={code} />+}+```diff --git a/.claude/skills/vercel-react-best-practices/rules/bundle-preload.md b/.claude/skills/vercel-react-best-practices/rules/bundle-preload.mdnew file mode 100644index 0000000..7000504--- /dev/null+++ b/.claude/skills/vercel-react-best-practices/rules/bundle-preload.md@@ -0,0 +1,50 @@+---+title: Preload Based on User Intent+impact: MEDIUM+impactDescription: reduces perceived latency+tags: bundle, preload, user-intent, hover+---++## Preload Based on User Intent++Preload heavy bundles before they're needed to reduce perceived latency.++**Example (preload on hover/focus):**++```tsx+function EditorButton({ onClick }: { onClick: () => void }) {+ const preload = () => {+ if (typeof window !== 'undefined') {+ void import('./monaco-editor')+ }+ }++ return (+ <button+ onMouseEnter={preload}+ onFocus={preload}+ onClick={onClick}+ >+ Open Editor+ </button>+ )+}+```++**Example (preload when feature flag is enabled):**++```tsx+function FlagsProvider({ children, flags }: Props) {+ useEffect(() => {+ if (flags.editorEnabled && typeof window !== 'undefined') {+ void import('./monaco-editor').then(mod => mod.init())+ }+ }, [flags.editorEnabled])++ return <FlagsContext.Provider value={flags}>+ {children}+ </FlagsContext.Provider>+}+```++The `typeof window !== 'undefined'` check prevents bundling preloaded modules for SSR, optimizing server bundle size and build speed.diff --git a/.claude/skills/vercel-react-best-practices/rules/client-event-listeners.md b/.claude/skills/vercel-react-best-practices/rules/client-event-listeners.mdnew file mode 100644index 0000000..aad4ae9--- /dev/null+++ b/.claude/skills/vercel-react-best-practices/rules/client-event-listeners.md@@ -0,0 +1,74 @@+---+title: Deduplicate Global Event Listeners+impact: LOW+impactDescription: single listener for N components+tags: client, swr, event-listeners, subscription+---++## Deduplicate Global Event Listeners++Use `useSWRSubscription()` to share global event listeners across component instances.++**Incorrect (N instances = N listeners):**++```tsx+function useKeyboardShortcut(key: string, callback: () => void) {+ useEffect(() => {+ const handler = (e: KeyboardEvent) => {+ if (e.metaKey && e.key === key) {+ callback()+ }+ }+ window.addEventListener('keydown', handler)+ return () => window.removeEventListener('keydown', handler)+ }, [key, callback])+}+```++When using the `useKeyboardShortcut` hook multiple times, each instance will register a new listener.++**Correct (N instances = 1 listener):**++```tsx+import useSWRSubscription from 'swr/subscription'++// Module-level Map to track callbacks per key+const keyCallbacks = new Map<string, Set<() => void>>()++function useKeyboardShortcut(key: string, callback: () => void) {+ // Register this callback in the Map+ useEffect(() => {+ if (!keyCallbacks.has(key)) {+ keyCallbacks.set(key, new Set())+ }+ keyCallbacks.get(key)!.add(callback)++ return () => {+ const set = keyCallbacks.get(key)+ if (set) {+ set.delete(callback)+ if (set.size === 0) {+ keyCallbacks.delete(key)+ }+ }+ }+ }, [key, callback])++ useSWRSubscription('global-keydown', () => {+ const handler = (e: KeyboardEvent) => {+ if (e.metaKey && keyCallbacks.has(e.key)) {+ keyCallbacks.get(e.key)!.forEach(cb => cb())+ }+ }+ window.addEventListener('keydown', handler)+ return () => window.removeEventListener('keydown', handler)+ })+}++function Profile() {+ // Multiple shortcuts will share the same listener+ useKeyboardShortcut('p', () => { /* ... */ })+ useKeyboardShortcut('k', () => { /* ... */ })+ // ...+}+```diff --git a/.claude/skills/vercel-react-best-practices/rules/client-localstorage-schema.md b/.claude/skills/vercel-react-best-practices/rules/client-localstorage-schema.mdnew file mode 100644index 0000000..d30a1a7--- /dev/null+++ b/.claude/skills/vercel-react-best-practices/rules/client-localstorage-schema.md@@ -0,0 +1,71 @@+---+title: Version and Minimize localStorage Data+impact: MEDIUM+impactDescription: prevents schema conflicts, reduces storage size+tags: client, localStorage, storage, versioning, data-minimization+---++## Version and Minimize localStorage Data++Add version prefix to keys and store only needed fields. Prevents schema conflicts and accidental storage of sensitive data.++**Incorrect:**++```typescript+// No version, stores everything, no error handling+localStorage.setItem('userConfig', JSON.stringify(fullUserObject))+const data = localStorage.getItem('userConfig')+```++**Correct:**++```typescript+const VERSION = 'v2'++function saveConfig(config: { theme: string; language: string }) {+ try {+ localStorage.setItem(`userConfig:${VERSION}`, JSON.stringify(config))+ } catch {+ // Throws in incognito/private browsing, quota exceeded, or disabled+ }+}++function loadConfig() {+ try {+ const data = localStorage.getItem(`userConfig:${VERSION}`)+ return data ? JSON.parse(data) : null+ } catch {+ return null+ }+}++// Migration from v1 to v2+function migrate() {+ try {+ const v1 = localStorage.getItem('userConfig:v1')+ if (v1) {+ const old = JSON.parse(v1)+ saveConfig({ theme: old.darkMode ? 'dark' : 'light', language: old.lang })+ localStorage.removeItem('userConfig:v1')+ }+ } catch {}+}+```++**Store minimal fields from server responses:**++```typescript+// User object has 20+ fields, only store what UI needs+function cachePrefs(user: FullUser) {+ try {+ localStorage.setItem('prefs:v1', JSON.stringify({+ theme: user.preferences.theme,+ notifications: user.preferences.notifications+ }))+ } catch {}+}+```++**Always wrap in try-catch:** `getItem()` and `setItem()` throw in incognito/private browsing (Safari, Firefox), when quota exceeded, or when disabled.++**Benefits:** Schema evolution via versioning, reduced storage size, prevents storing tokens/PII/internal flags.diff --git a/.claude/skills/vercel-react-best-practices/rules/client-passive-event-listeners.md b/.claude/skills/vercel-react-best-practices/rules/client-passive-event-listeners.mdnew file mode 100644index 0000000..ce39a88--- /dev/null+++ b/.claude/skills/vercel-react-best-practices/rules/client-passive-event-listeners.md@@ -0,0 +1,48 @@+---+title: Use Passive Event Listeners for Scrolling Performance+impact: MEDIUM+impactDescription: eliminates scroll delay caused by event listeners+tags: client, event-listeners, scrolling, performance, touch, wheel+---++## Use Passive Event Listeners for Scrolling Performance++Add `{ passive: true }` to touch and wheel event listeners to enable immediate scrolling. Browsers normally wait for listeners to finish to check if `preventDefault()` is called, causing scroll delay.++**Incorrect:**++```typescript+useEffect(() => {+ const handleTouch = (e: TouchEvent) => console.log(e.touches[0].clientX)+ const handleWheel = (e: WheelEvent) => console.log(e.deltaY)++ document.addEventListener('touchstart', handleTouch)+ document.addEventListener('wheel', handleWheel)++ return () => {+ document.removeEventListener('touchstart', handleTouch)+ document.removeEventListener('wheel', handleWheel)+ }+}, [])+```++**Correct:**++```typescript+useEffect(() => {+ const handleTouch = (e: TouchEvent) => console.log(e.touches[0].clientX)+ const handleWheel = (e: WheelEvent) => console.log(e.deltaY)++ document.addEventListener('touchstart', handleTouch, { passive: true })+ document.addEventListener('wheel', handleWheel, { passive: true })++ return () => {+ document.removeEventListener('touchstart', handleTouch)+ document.removeEventListener('wheel', handleWheel)+ }+}, [])+```++**Use passive when:** tracking/analytics, logging, any listener that doesn't call `preventDefault()`.++**Don't use passive when:** implementing custom swipe gestures, custom zoom controls, or any listener that needs `preventDefault()`.diff --git a/.claude/skills/vercel-react-best-practices/rules/client-swr-dedup.md b/.claude/skills/vercel-react-best-practices/rules/client-swr-dedup.mdnew file mode 100644index 0000000..2a430f2--- /dev/null+++ b/.claude/skills/vercel-react-best-practices/rules/client-swr-dedup.md@@ -0,0 +1,56 @@+---+title: Use SWR for Automatic Deduplication+impact: MEDIUM-HIGH+impactDescription: automatic deduplication+tags: client, swr, deduplication, data-fetching+---++## Use SWR for Automatic Deduplication++SWR enables request deduplication, caching, and revalidation across component instances.++**Incorrect (no deduplication, each instance fetches):**++```tsx+function UserList() {+ const [users, setUsers] = useState([])+ useEffect(() => {+ fetch('/api/users')+ .then(r => r.json())+ .then(setUsers)+ }, [])+}+```++**Correct (multiple instances share one request):**++```tsx+import useSWR from 'swr'++function UserList() {+ const { data: users } = useSWR('/api/users', fetcher)+}+```++**For immutable data:**++```tsx+import { useImmutableSWR } from '@/lib/swr'++function StaticContent() {+ const { data } = useImmutableSWR('/api/config', fetcher)+}+```++**For mutations:**++```tsx+import { useSWRMutation } from 'swr/mutation'++function UpdateButton() {+ const { trigger } = useSWRMutation('/api/user', updateUser)+ return <button onClick={() => trigger()}>Update</button>+}+```++Reference: [https://swr.vercel.app](https://swr.vercel.app)diff --git a/.claude/skills/vercel-react-best-practices/rules/js-batch-dom-css.md b/.claude/skills/vercel-react-best-practices/rules/js-batch-dom-css.mdnew file mode 100644index 0000000..a62d84e--- /dev/null+++ b/.claude/skills/vercel-react-best-practices/rules/js-batch-dom-css.md@@ -0,0 +1,107 @@+---+title: Avoid Layout Thrashing+impact: MEDIUM+impactDescription: prevents forced synchronous layouts and reduces performance bottlenecks+tags: javascript, dom, css, performance, reflow, layout-thrashing+---++## Avoid Layout Thrashing++Avoid interleaving style writes with layout reads. When you read a layout property (like `offsetWidth`, `getBoundingClientRect()`, or `getComputedStyle()`) between style changes, the browser is forced to trigger a synchronous reflow.++**This is OK (browser batches style changes):**+```typescript+function updateElementStyles(element: HTMLElement) {+ // Each line invalidates style, but browser batches the recalculation+ element.style.width = '100px'+ element.style.height = '200px'+ element.style.backgroundColor = 'blue'+ element.style.border = '1px solid black'+}+```++**Incorrect (interleaved reads and writes force reflows):**+```typescript+function layoutThrashing(element: HTMLElement) {+ element.style.width = '100px'+ const width = element.offsetWidth // Forces reflow+ element.style.height = '200px'+ const height = element.offsetHeight // Forces another reflow+}+```++**Correct (batch writes, then read once):**+```typescript+function updateElementStyles(element: HTMLElement) {+ // Batch all writes together+ element.style.width = '100px'+ element.style.height = '200px'+ element.style.backgroundColor = 'blue'+ element.style.border = '1px solid black'++ // Read after all writes are done (single reflow)+ const { width, height } = element.getBoundingClientRect()+}+```++**Correct (batch reads, then writes):**+```typescript+function avoidThrashing(element: HTMLElement) {+ // Read phase - all layout queries first+ const rect1 = element.getBoundingClientRect()+ const offsetWidth = element.offsetWidth+ const offsetHeight = element.offsetHeight++ // Write phase - all style changes after+ element.style.width = '100px'+ element.style.height = '200px'+}+```++**Better: use CSS classes**+```css+.highlighted-box {+ width: 100px;+ height: 200px;+ background-color: blue;+ border: 1px solid black;+}+```+```typescript+function updateElementStyles(element: HTMLElement) {+ element.classList.add('highlighted-box')++ const { width, height } = element.getBoundingClientRect()+}+```++**React example:**+```tsx+// Incorrect: interleaving style changes with layout queries+function Box({ isHighlighted }: { isHighlighted: boolean }) {+ const ref = useRef<HTMLDivElement>(null)++ useEffect(() => {+ if (ref.current && isHighlighted) {+ ref.current.style.width = '100px'+ const width = ref.current.offsetWidth // Forces layout+ ref.current.style.height = '200px'+ }+ }, [isHighlighted])++ return <div ref={ref}>Content</div>+}++// Correct: toggle class+function Box({ isHighlighted }: { isHighlighted: boolean }) {+ return (+ <div className={isHighlighted ? 'highlighted-box' : ''}>+ Content+ </div>+ )+}+```++Prefer CSS classes over inline styles when possible. CSS files are cached by the browser, and classes provide better separation of concerns and are easier to maintain.++See [this gist](https://gist.github.com/paulirish/5d52fb081b3570c81e3a) and [CSS Triggers](https://csstriggers.com/) for more information on layout-forcing operations.diff --git a/.claude/skills/vercel-react-best-practices/rules/js-cache-function-results.md b/.claude/skills/vercel-react-best-practices/rules/js-cache-function-results.mdnew file mode 100644index 0000000..180f8ac--- /dev/null+++ b/.claude/skills/vercel-react-best-practices/rules/js-cache-function-results.md@@ -0,0 +1,80 @@+---+title: Cache Repeated Function Calls+impact: MEDIUM+impactDescription: avoid redundant computation+tags: javascript, cache, memoization, performance+---++## Cache Repeated Function Calls++Use a module-level Map to cache function results when the same function is called repeatedly with the same inputs during render.++**Incorrect (redundant computation):**++```typescript+function ProjectList({ projects }: { projects: Project[] }) {+ return (+ <div>+ {projects.map(project => {+ // slugify() called 100+ times for same project names+ const slug = slugify(project.name)++ return <ProjectCard key={project.id} slug={slug} />+ })}+ </div>+ )+}+```++**Correct (cached results):**++```typescript+// Module-level cache+const slugifyCache = new Map<string, string>()++function cachedSlugify(text: string): string {+ if (slugifyCache.has(text)) {+ return slugifyCache.get(text)!+ }+ const result = slugify(text)+ slugifyCache.set(text, result)+ return result+}++function ProjectList({ projects }: { projects: Project[] }) {+ return (+ <div>+ {projects.map(project => {+ // Computed only once per unique project name+ const slug = cachedSlugify(project.name)++ return <ProjectCard key={project.id} slug={slug} />+ })}+ </div>+ )+}+```++**Simpler pattern for single-value functions:**++```typescript+let isLoggedInCache: boolean | null = null++function isLoggedIn(): boolean {+ if (isLoggedInCache !== null) {+ return isLoggedInCache+ }++ isLoggedInCache = document.cookie.includes('auth=')+ return isLoggedInCache+}++// Clear cache when auth changes+function onAuthChange() {+ isLoggedInCache = null+}+```++Use a Map (not a hook) so it works everywhere: utilities, event handlers, not just React components.++Reference: [How we made the Vercel Dashboard twice as fast](https://vercel.com/blog/how-we-made-the-vercel-dashboard-twice-as-fast)diff --git a/.claude/skills/vercel-react-best-practices/rules/js-cache-property-access.md b/.claude/skills/vercel-react-best-practices/rules/js-cache-property-access.mdnew file mode 100644index 0000000..39eec90--- /dev/null+++ b/.claude/skills/vercel-react-best-practices/rules/js-cache-property-access.md@@ -0,0 +1,28 @@+---+title: Cache Property Access in Loops+impact: LOW-MEDIUM+impactDescription: reduces lookups+tags: javascript, loops, optimization, caching+---++## Cache Property Access in Loops++Cache object property lookups in hot paths.++**Incorrect (3 lookups × N iterations):**++```typescript+for (let i = 0; i < arr.length; i++) {+ process(obj.config.settings.value)+}+```++**Correct (1 lookup total):**++```typescript+const value = obj.config.settings.value+const len = arr.length+for (let i = 0; i < len; i++) {+ process(value)+}+```diff --git a/.claude/skills/vercel-react-best-practices/rules/js-cache-storage.md b/.claude/skills/vercel-react-best-practices/rules/js-cache-storage.mdnew file mode 100644index 0000000..aa4a30c--- /dev/null+++ b/.claude/skills/vercel-react-best-practices/rules/js-cache-storage.md@@ -0,0 +1,70 @@+---+title: Cache Storage API Calls+impact: LOW-MEDIUM+impactDescription: reduces expensive I/O+tags: javascript, localStorage, storage, caching, performance+---++## Cache Storage API Calls++`localStorage`, `sessionStorage`, and `document.cookie` are synchronous and expensive. Cache reads in memory.++**Incorrect (reads storage on every call):**++```typescript+function getTheme() {+ return localStorage.getItem('theme') ?? 'light'+}+// Called 10 times = 10 storage reads+```++**Correct (Map cache):**++```typescript+const storageCache = new Map<string, string | null>()++function getLocalStorage(key: string) {+ if (!storageCache.has(key)) {+ storageCache.set(key, localStorage.getItem(key))+ }+ return storageCache.get(key)+}++function setLocalStorage(key: string, value: string) {+ localStorage.setItem(key, value)+ storageCache.set(key, value) // keep cache in sync+}+```++Use a Map (not a hook) so it works everywhere: utilities, event handlers, not just React components.++**Cookie caching:**++```typescript+let cookieCache: Record<string, string> | null = null++function getCookie(name: string) {+ if (!cookieCache) {+ cookieCache = Object.fromEntries(+ document.cookie.split('; ').map(c => c.split('='))+ )+ }+ return cookieCache[name]+}+```++**Important (invalidate on external changes):**++If storage can change externally (another tab, server-set cookies), invalidate cache:++```typescript+window.addEventListener('storage', (e) => {+ if (e.key) storageCache.delete(e.key)+})++document.addEventListener('visibilitychange', () => {+ if (document.visibilityState === 'visible') {+ storageCache.clear()+ }+})+```diff --git a/.claude/skills/vercel-react-best-practices/rules/js-combine-iterations.md b/.claude/skills/vercel-react-best-practices/rules/js-combine-iterations.mdnew file mode 100644index 0000000..044d017--- /dev/null+++ b/.claude/skills/vercel-react-best-practices/rules/js-combine-iterations.md@@ -0,0 +1,32 @@+---+title: Combine Multiple Array Iterations+impact: LOW-MEDIUM+impactDescription: reduces iterations+tags: javascript, arrays, loops, performance+---++## Combine Multiple Array Iterations++Multiple `.filter()` or `.map()` calls iterate the array multiple times. Combine into one loop.++**Incorrect (3 iterations):**++```typescript+const admins = users.filter(u => u.isAdmin)+const testers = users.filter(u => u.isTester)+const inactive = users.filter(u => !u.isActive)+```++**Correct (1 iteration):**++```typescript+const admins: User[] = []+const testers: User[] = []+const inactive: User[] = []++for (const user of users) {+ if (user.isAdmin) admins.push(user)+ if (user.isTester) testers.push(user)+ if (!user.isActive) inactive.push(user)+}+```diff --git a/.claude/skills/vercel-react-best-practices/rules/js-early-exit.md b/.claude/skills/vercel-react-best-practices/rules/js-early-exit.mdnew file mode 100644index 0000000..f46cb89--- /dev/null+++ b/.claude/skills/vercel-react-best-practices/rules/js-early-exit.md@@ -0,0 +1,50 @@+---+title: Early Return from Functions+impact: LOW-MEDIUM+impactDescription: avoids unnecessary computation+tags: javascript, functions, optimization, early-return+---++## Early Return from Functions++Return early when result is determined to skip unnecessary processing.++**Incorrect (processes all items even after finding answer):**++```typescript+function validateUsers(users: User[]) {+ let hasError = false+ let errorMessage = ''++ for (const user of users) {+ if (!user.email) {+ hasError = true+ errorMessage = 'Email required'+ }+ if (!user.name) {+ hasError = true+ errorMessage = 'Name required'+ }+ // Continues checking all users even after error found+ }++ return hasError ? { valid: false, error: errorMessage } : { valid: true }+}+```++**Correct (returns immediately on first error):**++```typescript+function validateUsers(users: User[]) {+ for (const user of users) {+ if (!user.email) {+ return { valid: false, error: 'Email required' }+ }+ if (!user.name) {+ return { valid: false, error: 'Name required' }+ }+ }++ return { valid: true }+}+```diff --git a/.claude/skills/vercel-react-best-practices/rules/js-flatmap-filter.md b/.claude/skills/vercel-react-best-practices/rules/js-flatmap-filter.mdnew file mode 100644index 0000000..ee0edf0--- /dev/null+++ b/.claude/skills/vercel-react-best-practices/rules/js-flatmap-filter.md@@ -0,0 +1,60 @@+---+title: Use flatMap to Map and Filter in One Pass+impact: LOW-MEDIUM+impactDescription: eliminates intermediate array+tags: javascript, arrays, flatMap, filter, performance+---++## Use flatMap to Map and Filter in One Pass++**Impact: LOW-MEDIUM (eliminates intermediate array)**++Chaining `.map().filter(Boolean)` creates an intermediate array and iterates twice. Use `.flatMap()` to transform and filter in a single pass.++**Incorrect (2 iterations, intermediate array):**++```typescript+const userNames = users+ .map(user => user.isActive ? user.name : null)+ .filter(Boolean)+```++**Correct (1 iteration, no intermediate array):**++```typescript+const userNames = users.flatMap(user =>+ user.isActive ? [user.name] : []+)+```++**More examples:**++```typescript+// Extract valid emails from responses+// Before+const emails = responses+ .map(r => r.success ? r.data.email : null)+ .filter(Boolean)++// After+const emails = responses.flatMap(r =>+ r.success ? [r.data.email] : []+)++// Parse and filter valid numbers+// Before+const numbers = strings+ .map(s => parseInt(s, 10))+ .filter(n => !isNaN(n))++// After+const numbers = strings.flatMap(s => {+ const n = parseInt(s, 10)+ return isNaN(n) ? [] : [n]+})+```++**When to use:**+- Transforming items while filtering some out+- Conditional mapping where some inputs produce no output+- Parsing/validating where invalid inputs should be skippeddiff --git a/.claude/skills/vercel-react-best-practices/rules/js-hoist-regexp.md b/.claude/skills/vercel-react-best-practices/rules/js-hoist-regexp.mdnew file mode 100644index 0000000..dae3fef--- /dev/null+++ b/.claude/skills/vercel-react-best-practices/rules/js-hoist-regexp.md@@ -0,0 +1,45 @@+---+title: Hoist RegExp Creation+impact: LOW-MEDIUM+impactDescription: avoids recreation+tags: javascript, regexp, optimization, memoization+---++## Hoist RegExp Creation++Don't create RegExp inside render. Hoist to module scope or memoize with `useMemo()`.++**Incorrect (new RegExp every render):**++```tsx+function Highlighter({ text, query }: Props) {+ const regex = new RegExp(`(${query})`, 'gi')+ const parts = text.split(regex)+ return <>{parts.map((part, i) => ...)}</>+}+```++**Correct (memoize or hoist):**++```tsx+const EMAIL_REGEX = /^[^\s@]+@[^\s@]+\.[^\s@]+$/++function Highlighter({ text, query }: Props) {+ const regex = useMemo(+ () => new RegExp(`(${escapeRegex(query)})`, 'gi'),+ [query]+ )+ const parts = text.split(regex)+ return <>{parts.map((part, i) => ...)}</>+}+```++**Warning (global regex has mutable state):**++Global regex (`/g`) has mutable `lastIndex` state:++```typescript+const regex = /foo/g+regex.test('foo') // true, lastIndex = 3+regex.test('foo') // false, lastIndex = 0+```diff --git a/.claude/skills/vercel-react-best-practices/rules/js-index-maps.md b/.claude/skills/vercel-react-best-practices/rules/js-index-maps.mdnew file mode 100644index 0000000..9d357a0--- /dev/null+++ b/.claude/skills/vercel-react-best-practices/rules/js-index-maps.md@@ -0,0 +1,37 @@+---+title: Build Index Maps for Repeated Lookups+impact: LOW-MEDIUM+impactDescription: 1M ops to 2K ops+tags: javascript, map, indexing, optimization, performance+---++## Build Index Maps for Repeated Lookups++Multiple `.find()` calls by the same key should use a Map.++**Incorrect (O(n) per lookup):**++```typescript+function processOrders(orders: Order[], users: User[]) {+ return orders.map(order => ({+ ...order,+ user: users.find(u => u.id === order.userId)+ }))+}+```++**Correct (O(1) per lookup):**++```typescript+function processOrders(orders: Order[], users: User[]) {+ const userById = new Map(users.map(u => [u.id, u]))++ return orders.map(order => ({+ ...order,+ user: userById.get(order.userId)+ }))+}+```++Build map once (O(n)), then all lookups are O(1).+For 1000 orders × 1000 users: 1M ops → 2K ops.diff --git a/.claude/skills/vercel-react-best-practices/rules/js-length-check-first.md b/.claude/skills/vercel-react-best-practices/rules/js-length-check-first.mdnew file mode 100644index 0000000..8b89573--- /dev/null+++ b/.claude/skills/vercel-react-best-practices/rules/js-length-check-first.md@@ -0,0 +1,49 @@+---+title: Early Length Check for Array Comparisons+impact: MEDIUM-HIGH+impactDescription: avoids expensive operations when lengths differ+tags: javascript, arrays, performance, optimization, comparison+---++## Early Length Check for Array Comparisons++When comparing arrays with expensive operations (sorting, deep equality, serialization), check lengths first. If lengths differ, the arrays cannot be equal.++In real-world applications, this optimization is especially valuable when the comparison runs in hot paths (event handlers, render loops).++**Incorrect (always runs expensive comparison):**++```typescript+function hasChanges(current: string[], original: string[]) {+ // Always sorts and joins, even when lengths differ+ return current.sort().join() !== original.sort().join()+}+```++Two O(n log n) sorts run even when `current.length` is 5 and `original.length` is 100. There is also overhead of joining the arrays and comparing the strings.++**Correct (O(1) length check first):**++```typescript+function hasChanges(current: string[], original: string[]) {+ // Early return if lengths differ+ if (current.length !== original.length) {+ return true+ }+ // Only sort when lengths match+ const currentSorted = current.toSorted()+ const originalSorted = original.toSorted()+ for (let i = 0; i < currentSorted.length; i++) {+ if (currentSorted[i] !== originalSorted[i]) {+ return true+ }+ }+ return false+}+```++This new approach is more efficient because:+- It avoids the overhead of sorting and joining the arrays when lengths differ+- It avoids consuming memory for the joined strings (especially important for large arrays)+- It avoids mutating the original arrays+- It returns early when a difference is founddiff --git a/.claude/skills/vercel-react-best-practices/rules/js-min-max-loop.md b/.claude/skills/vercel-react-best-practices/rules/js-min-max-loop.mdnew file mode 100644index 0000000..4b6656e--- /dev/null+++ b/.claude/skills/vercel-react-best-practices/rules/js-min-max-loop.md@@ -0,0 +1,82 @@+---+title: Use Loop for Min/Max Instead of Sort+impact: LOW+impactDescription: O(n) instead of O(n log n)+tags: javascript, arrays, performance, sorting, algorithms+---++## Use Loop for Min/Max Instead of Sort++Finding the smallest or largest element only requires a single pass through the array. Sorting is wasteful and slower.++**Incorrect (O(n log n) - sort to find latest):**++```typescript+interface Project {+ id: string+ name: string+ updatedAt: number+}++function getLatestProject(projects: Project[]) {+ const sorted = [...projects].sort((a, b) => b.updatedAt - a.updatedAt)+ return sorted[0]+}+```++Sorts the entire array just to find the maximum value.++**Incorrect (O(n log n) - sort for oldest and newest):**++```typescript+function getOldestAndNewest(projects: Project[]) {+ const sorted = [...projects].sort((a, b) => a.updatedAt - b.updatedAt)+ return { oldest: sorted[0], newest: sorted[sorted.length - 1] }+}+```++Still sorts unnecessarily when only min/max are needed.++**Correct (O(n) - single loop):**++```typescript+function getLatestProject(projects: Project[]) {+ if (projects.length === 0) return null++ let latest = projects[0]++ for (let i = 1; i < projects.length; i++) {+ if (projects[i].updatedAt > latest.updatedAt) {+ latest = projects[i]+ }+ }++ return latest+}++function getOldestAndNewest(projects: Project[]) {+ if (projects.length === 0) return { oldest: null, newest: null }++ let oldest = projects[0]+ let newest = projects[0]++ for (let i = 1; i < projects.length; i++) {+ if (projects[i].updatedAt < oldest.updatedAt) oldest = projects[i]+ if (projects[i].updatedAt > newest.updatedAt) newest = projects[i]+ }++ return { oldest, newest }+}+```++Single pass through the array, no copying, no sorting.++**Alternative (Math.min/Math.max for small arrays):**++```typescript+const numbers = [5, 2, 8, 1, 9]+const min = Math.min(...numbers)+const max = Math.max(...numbers)+```++This works for small arrays, but can be slower or just throw an error for very large arrays due to spread operator limitations. Maximal array length is approximately 124000 in Chrome 143 and 638000 in Safari 18; exact numbers may vary - see [the fiddle](https://jsfiddle.net/qw1jabsx/4/). Use the loop approach for reliability.diff --git a/.claude/skills/vercel-react-best-practices/rules/js-request-idle-callback.md b/.claude/skills/vercel-react-best-practices/rules/js-request-idle-callback.mdnew file mode 100644index 0000000..d81927e--- /dev/null+++ b/.claude/skills/vercel-react-best-practices/rules/js-request-idle-callback.md@@ -0,0 +1,105 @@+---+title: Defer Non-Critical Work with requestIdleCallback+impact: MEDIUM+impactDescription: keeps UI responsive during background tasks+tags: javascript, performance, idle, scheduling, analytics+---++## Defer Non-Critical Work with requestIdleCallback++**Impact: MEDIUM (keeps UI responsive during background tasks)**++Use `requestIdleCallback()` to schedule non-critical work during browser idle periods. This keeps the main thread free for user interactions and animations, reducing jank and improving perceived performance.++**Incorrect (blocks main thread during user interaction):**++```typescript+function handleSearch(query: string) {+ const results = searchItems(query)+ setResults(results)++ // These block the main thread immediately+ analytics.track('search', { query })+ saveToRecentSearches(query)+ prefetchTopResults(results.slice(0, 3))+}+```++**Correct (defers non-critical work to idle time):**++```typescript+function handleSearch(query: string) {+ const results = searchItems(query)+ setResults(results)++ // Defer non-critical work to idle periods+ requestIdleCallback(() => {+ analytics.track('search', { query })+ })++ requestIdleCallback(() => {+ saveToRecentSearches(query)+ })++ requestIdleCallback(() => {+ prefetchTopResults(results.slice(0, 3))+ })+}+```++**With timeout for required work:**++```typescript+// Ensure analytics fires within 2 seconds even if browser stays busy+requestIdleCallback(+ () => analytics.track('page_view', { path: location.pathname }),+ { timeout: 2000 }+)+```++**Chunking large tasks:**++```typescript+function processLargeDataset(items: Item[]) {+ let index = 0++ function processChunk(deadline: IdleDeadline) {+ // Process items while we have idle time (aim for <50ms chunks)+ while (index < items.length && deadline.timeRemaining() > 0) {+ processItem(items[index])+ index+++ }++ // Schedule next chunk if more items remain+ if (index < items.length) {+ requestIdleCallback(processChunk)+ }+ }++ requestIdleCallback(processChunk)+}+```++**With fallback for unsupported browsers:**++```typescript+const scheduleIdleWork = window.requestIdleCallback ?? ((cb: () => void) => setTimeout(cb, 1))++scheduleIdleWork(() => {+ // Non-critical work+})+```++**When to use:**++- Analytics and telemetry+- Saving state to localStorage/IndexedDB+- Prefetching resources for likely next actions+- Processing non-urgent data transformations+- Lazy initialization of non-critical features++**When NOT to use:**++- User-initiated actions that need immediate feedback+- Rendering updates the user is waiting for+- Time-sensitive operationsdiff --git a/.claude/skills/vercel-react-best-practices/rules/js-set-map-lookups.md b/.claude/skills/vercel-react-best-practices/rules/js-set-map-lookups.mdnew file mode 100644index 0000000..680a489--- /dev/null+++ b/.claude/skills/vercel-react-best-practices/rules/js-set-map-lookups.md@@ -0,0 +1,24 @@+---+title: Use Set/Map for O(1) Lookups+impact: LOW-MEDIUM+impactDescription: O(n) to O(1)+tags: javascript, set, map, data-structures, performance+---++## Use Set/Map for O(1) Lookups++Convert arrays to Set/Map for repeated membership checks.++**Incorrect (O(n) per check):**++```typescript+const allowedIds = ['a', 'b', 'c', ...]+items.filter(item => allowedIds.includes(item.id))+```++**Correct (O(1) per check):**++```typescript+const allowedIds = new Set(['a', 'b', 'c', ...])+items.filter(item => allowedIds.has(item.id))+```diff --git a/.claude/skills/vercel-react-best-practices/rules/js-tosorted-immutable.md b/.claude/skills/vercel-react-best-practices/rules/js-tosorted-immutable.mdnew file mode 100644index 0000000..eae8b3f--- /dev/null+++ b/.claude/skills/vercel-react-best-practices/rules/js-tosorted-immutable.md@@ -0,0 +1,57 @@+---+title: Use toSorted() Instead of sort() for Immutability+impact: MEDIUM-HIGH+impactDescription: prevents mutation bugs in React state+tags: javascript, arrays, immutability, react, state, mutation+---++## Use toSorted() Instead of sort() for Immutability++`.sort()` mutates the array in place, which can cause bugs with React state and props. Use `.toSorted()` to create a new sorted array without mutation.++**Incorrect (mutates original array):**++```typescript+function UserList({ users }: { users: User[] }) {+ // Mutates the users prop array!+ const sorted = useMemo(+ () => users.sort((a, b) => a.name.localeCompare(b.name)),+ [users]+ )+ return <div>{sorted.map(renderUser)}</div>+}+```++**Correct (creates new array):**++```typescript+function UserList({ users }: { users: User[] }) {+ // Creates new sorted array, original unchanged+ const sorted = useMemo(+ () => users.toSorted((a, b) => a.name.localeCompare(b.name)),+ [users]+ )+ return <div>{sorted.map(renderUser)}</div>+}+```++**Why this matters in React:**++1. Props/state mutations break React's immutability model - React expects props and state to be treated as read-only+2. Causes stale closure bugs - Mutating arrays inside closures (callbacks, effects) can lead to unexpected behavior++**Browser support (fallback for older browsers):**++`.toSorted()` is available in all modern browsers (Chrome 110+, Safari 16+, Firefox 115+, Node.js 20+). For older environments, use spread operator:++```typescript+// Fallback for older browsers+const sorted = [...items].sort((a, b) => a.value - b.value)+```++**Other immutable array methods:**++- `.toSorted()` - immutable sort+- `.toReversed()` - immutable reverse+- `.toSpliced()` - immutable splice+- `.with()` - immutable element replacementdiff --git a/.claude/skills/vercel-react-best-practices/rules/rendering-activity.md b/.claude/skills/vercel-react-best-practices/rules/rendering-activity.mdnew file mode 100644index 0000000..c957a49--- /dev/null+++ b/.claude/skills/vercel-react-best-practices/rules/rendering-activity.md@@ -0,0 +1,26 @@+---+title: Use Activity Component for Show/Hide+impact: MEDIUM+impactDescription: preserves state/DOM+tags: rendering, activity, visibility, state-preservation+---++## Use Activity Component for Show/Hide++Use React's `<Activity>` to preserve state/DOM for expensive components that frequently toggle visibility.++**Usage:**++```tsx+import { Activity } from 'react'++function Dropdown({ isOpen }: Props) {+ return (+ <Activity mode={isOpen ? 'visible' : 'hidden'}>+ <ExpensiveMenu />+ </Activity>+ )+}+```++Avoids expensive re-renders and state loss.diff --git a/.claude/skills/vercel-react-best-practices/rules/rendering-animate-svg-wrapper.md b/.claude/skills/vercel-react-best-practices/rules/rendering-animate-svg-wrapper.mdnew file mode 100644index 0000000..646744c--- /dev/null+++ b/.claude/skills/vercel-react-best-practices/rules/rendering-animate-svg-wrapper.md@@ -0,0 +1,47 @@+---+title: Animate SVG Wrapper Instead of SVG Element+impact: LOW+impactDescription: enables hardware acceleration+tags: rendering, svg, css, animation, performance+---++## Animate SVG Wrapper Instead of SVG Element++Many browsers don't have hardware acceleration for CSS3 animations on SVG elements. Wrap SVG in a `<div>` and animate the wrapper instead.++**Incorrect (animating SVG directly - no hardware acceleration):**++```tsx+function LoadingSpinner() {+ return (+ <svg+ className="animate-spin"+ width="24"+ height="24"+ viewBox="0 0 24 24"+ >+ <circle cx="12" cy="12" r="10" stroke="currentColor" />+ </svg>+ )+}+```++**Correct (animating wrapper div - hardware accelerated):**++```tsx+function LoadingSpinner() {+ return (+ <div className="animate-spin">+ <svg+ width="24"+ height="24"+ viewBox="0 0 24 24"+ >+ <circle cx="12" cy="12" r="10" stroke="currentColor" />+ </svg>+ </div>+ )+}+```++This applies to all CSS transforms and transitions (`transform`, `opacity`, `translate`, `scale`, `rotate`). The wrapper div allows browsers to use GPU acceleration for smoother animations.diff --git a/.claude/skills/vercel-react-best-practices/rules/rendering-conditional-render.md b/.claude/skills/vercel-react-best-practices/rules/rendering-conditional-render.mdnew file mode 100644index 0000000..7e866f5--- /dev/null+++ b/.claude/skills/vercel-react-best-practices/rules/rendering-conditional-render.md@@ -0,0 +1,40 @@+---+title: Use Explicit Conditional Rendering+impact: LOW+impactDescription: prevents rendering 0 or NaN+tags: rendering, conditional, jsx, falsy-values+---++## Use Explicit Conditional Rendering++Use explicit ternary operators (`? :`) instead of `&&` for conditional rendering when the condition can be `0`, `NaN`, or other falsy values that render.++**Incorrect (renders "0" when count is 0):**++```tsx+function Badge({ count }: { count: number }) {+ return (+ <div>+ {count && <span className="badge">{count}</span>}+ </div>+ )+}++// When count = 0, renders: <div>0</div>+// When count = 5, renders: <div><span class="badge">5</span></div>+```++**Correct (renders nothing when count is 0):**++```tsx+function Badge({ count }: { count: number }) {+ return (+ <div>+ {count > 0 ? <span className="badge">{count}</span> : null}+ </div>+ )+}++// When count = 0, renders: <div></div>+// When count = 5, renders: <div><span class="badge">5</span></div>+```diff --git a/.claude/skills/vercel-react-best-practices/rules/rendering-content-visibility.md b/.claude/skills/vercel-react-best-practices/rules/rendering-content-visibility.mdnew file mode 100644index 0000000..aa66563--- /dev/null+++ b/.claude/skills/vercel-react-best-practices/rules/rendering-content-visibility.md@@ -0,0 +1,38 @@+---+title: CSS content-visibility for Long Lists+impact: HIGH+impactDescription: faster initial render+tags: rendering, css, content-visibility, long-lists+---++## CSS content-visibility for Long Lists++Apply `content-visibility: auto` to defer off-screen rendering.++**CSS:**++```css+.message-item {+ content-visibility: auto;+ contain-intrinsic-size: 0 80px;+}+```++**Example:**++```tsx+function MessageList({ messages }: { messages: Message[] }) {+ return (+ <div className="overflow-y-auto h-screen">+ {messages.map(msg => (+ <div key={msg.id} className="message-item">+ <Avatar user={msg.author} />+ <div>{msg.content}</div>+ </div>+ ))}+ </div>+ )+}+```++For 1000 messages, browser skips layout/paint for ~990 off-screen items (10× faster initial render).diff --git a/.claude/skills/vercel-react-best-practices/rules/rendering-hoist-jsx.md b/.claude/skills/vercel-react-best-practices/rules/rendering-hoist-jsx.mdnew file mode 100644index 0000000..32d2f3f--- /dev/null+++ b/.claude/skills/vercel-react-best-practices/rules/rendering-hoist-jsx.md@@ -0,0 +1,46 @@+---+title: Hoist Static JSX Elements+impact: LOW+impactDescription: avoids re-creation+tags: rendering, jsx, static, optimization+---++## Hoist Static JSX Elements++Extract static JSX outside components to avoid re-creation.++**Incorrect (recreates element every render):**++```tsx+function LoadingSkeleton() {+ return <div className="animate-pulse h-20 bg-gray-200" />+}++function Container() {+ return (+ <div>+ {loading && <LoadingSkeleton />}+ </div>+ )+}+```++**Correct (reuses same element):**++```tsx+const loadingSkeleton = (+ <div className="animate-pulse h-20 bg-gray-200" />+)++function Container() {+ return (+ <div>+ {loading && loadingSkeleton}+ </div>+ )+}+```++This is especially helpful for large and static SVG nodes, which can be expensive to recreate on every render.++**Note:** If your project has [React Compiler](https://react.dev/learn/react-compiler) enabled, the compiler automatically hoists static JSX elements and optimizes component re-renders, making manual hoisting unnecessary.diff --git a/.claude/skills/vercel-react-best-practices/rules/rendering-hydration-no-flicker.md b/.claude/skills/vercel-react-best-practices/rules/rendering-hydration-no-flicker.mdnew file mode 100644index 0000000..5cf0e79--- /dev/null+++ b/.claude/skills/vercel-react-best-practices/rules/rendering-hydration-no-flicker.md@@ -0,0 +1,82 @@+---+title: Prevent Hydration Mismatch Without Flickering+impact: MEDIUM+impactDescription: avoids visual flicker and hydration errors+tags: rendering, ssr, hydration, localStorage, flicker+---++## Prevent Hydration Mismatch Without Flickering++When rendering content that depends on client-side storage (localStorage, cookies), avoid both SSR breakage and post-hydration flickering by injecting a synchronous script that updates the DOM before React hydrates.++**Incorrect (breaks SSR):**++```tsx+function ThemeWrapper({ children }: { children: ReactNode }) {+ // localStorage is not available on server - throws error+ const theme = localStorage.getItem('theme') || 'light'++ return (+ <div className={theme}>+ {children}+ </div>+ )+}+```++Server-side rendering will fail because `localStorage` is undefined.++**Incorrect (visual flickering):**++```tsx+function ThemeWrapper({ children }: { children: ReactNode }) {+ const [theme, setTheme] = useState('light')++ useEffect(() => {+ // Runs after hydration - causes visible flash+ const stored = localStorage.getItem('theme')+ if (stored) {+ setTheme(stored)+ }+ }, [])++ return (+ <div className={theme}>+ {children}+ </div>+ )+}+```++Component first renders with default value (`light`), then updates after hydration, causing a visible flash of incorrect content.++**Correct (no flicker, no hydration mismatch):**++```tsx+function ThemeWrapper({ children }: { children: ReactNode }) {+ return (+ <>+ <div id="theme-wrapper">+ {children}+ </div>+ <script+ dangerouslySetInnerHTML={{+ __html: `+ (function() {+ try {+ var theme = localStorage.getItem('theme') || 'light';+ var el = document.getElementById('theme-wrapper');+ if (el) el.className = theme;+ } catch (e) {}+ })();+ `,+ }}+ />+ </>+ )+}+```++The inline script executes synchronously before showing the element, ensuring the DOM already has the correct value. No flickering, no hydration mismatch.++This pattern is especially useful for theme toggles, user preferences, authentication states, and any client-only data that should render immediately without flashing default values.diff --git a/.claude/skills/vercel-react-best-practices/rules/rendering-hydration-suppress-warning.md b/.claude/skills/vercel-react-best-practices/rules/rendering-hydration-suppress-warning.mdnew file mode 100644index 0000000..24ba251--- /dev/null+++ b/.claude/skills/vercel-react-best-practices/rules/rendering-hydration-suppress-warning.md@@ -0,0 +1,30 @@+---+title: Suppress Expected Hydration Mismatches+impact: LOW-MEDIUM+impactDescription: avoids noisy hydration warnings for known differences+tags: rendering, hydration, ssr, nextjs+---++## Suppress Expected Hydration Mismatches++In SSR frameworks (e.g., Next.js), some values are intentionally different on server vs client (random IDs, dates, locale/timezone formatting). For these *expected* mismatches, wrap the dynamic text in an element with `suppressHydrationWarning` to prevent noisy warnings. Do not use this to hide real bugs. Don’t overuse it.++**Incorrect (known mismatch warnings):**++```tsx+function Timestamp() {+ return <span>{new Date().toLocaleString()}</span>+}+```++**Correct (suppress expected mismatch only):**++```tsx+function Timestamp() {+ return (+ <span suppressHydrationWarning>+ {new Date().toLocaleString()}+ </span>+ )+}+```diff --git a/.claude/skills/vercel-react-best-practices/rules/rendering-resource-hints.md b/.claude/skills/vercel-react-best-practices/rules/rendering-resource-hints.mdnew file mode 100644index 0000000..1290bef--- /dev/null+++ b/.claude/skills/vercel-react-best-practices/rules/rendering-resource-hints.md@@ -0,0 +1,85 @@+---+title: Use React DOM Resource Hints+impact: HIGH+impactDescription: reduces load time for critical resources+tags: rendering, preload, preconnect, prefetch, resource-hints+---++## Use React DOM Resource Hints++**Impact: HIGH (reduces load time for critical resources)**++React DOM provides APIs to hint the browser about resources it will need. These are especially useful in server components to start loading resources before the client even receives the HTML.++- **`prefetchDNS(href)`**: Resolve DNS for a domain you expect to connect to+- **`preconnect(href)`**: Establish connection (DNS + TCP + TLS) to a server+- **`preload(href, options)`**: Fetch a resource (stylesheet, font, script, image) you'll use soon+- **`preloadModule(href)`**: Fetch an ES module you'll use soon+- **`preinit(href, options)`**: Fetch and evaluate a stylesheet or script+- **`preinitModule(href)`**: Fetch and evaluate an ES module++**Example (preconnect to third-party APIs):**++```tsx+import { preconnect, prefetchDNS } from 'react-dom'++export default function App() {+ prefetchDNS('https://analytics.example.com')+ preconnect('https://api.example.com')++ return <main>{/* content */}</main>+}+```++**Example (preload critical fonts and styles):**++```tsx+import { preload, preinit } from 'react-dom'++export default function RootLayout({ children }) {+ // Preload font file+ preload('/fonts/inter.woff2', { as: 'font', type: 'font/woff2', crossOrigin: 'anonymous' })++ // Fetch and apply critical stylesheet immediately+ preinit('/styles/critical.css', { as: 'style' })++ return (+ <html>+ <body>{children}</body>+ </html>+ )+}+```++**Example (preload modules for code-split routes):**++```tsx+import { preloadModule, preinitModule } from 'react-dom'++function Navigation() {+ const preloadDashboard = () => {+ preloadModule('/dashboard.js', { as: 'script' })+ }++ return (+ <nav>+ <a href="/dashboard" onMouseEnter={preloadDashboard}>+ Dashboard+ </a>+ </nav>+ )+}+```++**When to use each:**++| API | Use case |+|-----|----------|+| `prefetchDNS` | Third-party domains you'll connect to later |+| `preconnect` | APIs or CDNs you'll fetch from immediately |+| `preload` | Critical resources needed for current page |+| `preloadModule` | JS modules for likely next navigation |+| `preinit` | Stylesheets/scripts that must execute early |+| `preinitModule` | ES modules that must execute early |++Reference: [React DOM Resource Preloading APIs](https://react.dev/reference/react-dom#resource-preloading-apis)diff --git a/.claude/skills/vercel-react-best-practices/rules/rendering-script-defer-async.md b/.claude/skills/vercel-react-best-practices/rules/rendering-script-defer-async.mdnew file mode 100644index 0000000..ee275ed--- /dev/null+++ b/.claude/skills/vercel-react-best-practices/rules/rendering-script-defer-async.md@@ -0,0 +1,68 @@+---+title: Use defer or async on Script Tags+impact: HIGH+impactDescription: eliminates render-blocking+tags: rendering, script, defer, async, performance+---++## Use defer or async on Script Tags++**Impact: HIGH (eliminates render-blocking)**++Script tags without `defer` or `async` block HTML parsing while the script downloads and executes. This delays First Contentful Paint and Time to Interactive.++- **`defer`**: Downloads in parallel, executes after HTML parsing completes, maintains execution order+- **`async`**: Downloads in parallel, executes immediately when ready, no guaranteed order++Use `defer` for scripts that depend on DOM or other scripts. Use `async` for independent scripts like analytics.++**Incorrect (blocks rendering):**++```tsx+export default function Document() {+ return (+ <html>+ <head>+ <script src="https://example.com/analytics.js" />+ <script src="/scripts/utils.js" />+ </head>+ <body>{/* content */}</body>+ </html>+ )+}+```++**Correct (non-blocking):**++```tsx+export default function Document() {+ return (+ <html>+ <head>+ {/* Independent script - use async */}+ <script src="https://example.com/analytics.js" async />+ {/* DOM-dependent script - use defer */}+ <script src="/scripts/utils.js" defer />+ </head>+ <body>{/* content */}</body>+ </html>+ )+}+```++**Note:** In Next.js, prefer the `next/script` component with `strategy` prop instead of raw script tags:++```tsx+import Script from 'next/script'++export default function Page() {+ return (+ <>+ <Script src="https://example.com/analytics.js" strategy="afterInteractive" />+ <Script src="/scripts/utils.js" strategy="beforeInteractive" />+ </>+ )+}+```++Reference: [MDN - Script element](https://developer.mozilla.org/en-US/docs/Web/HTML/Element/script#defer)diff --git a/.claude/skills/vercel-react-best-practices/rules/rendering-svg-precision.md b/.claude/skills/vercel-react-best-practices/rules/rendering-svg-precision.mdnew file mode 100644index 0000000..6d77128--- /dev/null+++ b/.claude/skills/vercel-react-best-practices/rules/rendering-svg-precision.md@@ -0,0 +1,28 @@+---+title: Optimize SVG Precision+impact: LOW+impactDescription: reduces file size+tags: rendering, svg, optimization, svgo+---++## Optimize SVG Precision++Reduce SVG coordinate precision to decrease file size. The optimal precision depends on the viewBox size, but in general reducing precision should be considered.++**Incorrect (excessive precision):**++```svg+<path d="M 10.293847 20.847362 L 30.938472 40.192837" />+```++**Correct (1 decimal place):**++```svg+<path d="M 10.3 20.8 L 30.9 40.2" />+```++**Automate with SVGO:**++```bash+npx svgo --precision=1 --multipass icon.svg+```diff --git a/.claude/skills/vercel-react-best-practices/rules/rendering-usetransition-loading.md b/.claude/skills/vercel-react-best-practices/rules/rendering-usetransition-loading.mdnew file mode 100644index 0000000..0c1b0b9--- /dev/null+++ b/.claude/skills/vercel-react-best-practices/rules/rendering-usetransition-loading.md@@ -0,0 +1,75 @@+---+title: Use useTransition Over Manual Loading States+impact: LOW+impactDescription: reduces re-renders and improves code clarity+tags: rendering, transitions, useTransition, loading, state+---++## Use useTransition Over Manual Loading States++Use `useTransition` instead of manual `useState` for loading states. This provides built-in `isPending` state and automatically manages transitions.++**Incorrect (manual loading state):**++```tsx+function SearchResults() {+ const [query, setQuery] = useState('')+ const [results, setResults] = useState([])+ const [isLoading, setIsLoading] = useState(false)++ const handleSearch = async (value: string) => {+ setIsLoading(true)+ setQuery(value)+ const data = await fetchResults(value)+ setResults(data)+ setIsLoading(false)+ }++ return (+ <>+ <input onChange={(e) => handleSearch(e.target.value)} />+ {isLoading && <Spinner />}+ <ResultsList results={results} />+ </>+ )+}+```++**Correct (useTransition with built-in pending state):**++```tsx+import { useTransition, useState } from 'react'++function SearchResults() {+ const [query, setQuery] = useState('')+ const [results, setResults] = useState([])+ const [isPending, startTransition] = useTransition()++ const handleSearch = (value: string) => {+ setQuery(value) // Update input immediately++ startTransition(async () => {+ // Fetch and update results+ const data = await fetchResults(value)+ setResults(data)+ })+ }++ return (+ <>+ <input onChange={(e) => handleSearch(e.target.value)} />+ {isPending && <Spinner />}+ <ResultsList results={results} />+ </>+ )+}+```++**Benefits:**++- **Automatic pending state**: No need to manually manage `setIsLoading(true/false)`+- **Error resilience**: Pending state correctly resets even if the transition throws+- **Better responsiveness**: Keeps the UI responsive during updates+- **Interrupt handling**: New transitions automatically cancel pending ones++Reference: [useTransition](https://react.dev/reference/react/useTransition)diff --git a/.claude/skills/vercel-react-best-practices/rules/rerender-defer-reads.md b/.claude/skills/vercel-react-best-practices/rules/rerender-defer-reads.mdnew file mode 100644index 0000000..e867c95--- /dev/null+++ b/.claude/skills/vercel-react-best-practices/rules/rerender-defer-reads.md@@ -0,0 +1,39 @@+---+title: Defer State Reads to Usage Point+impact: MEDIUM+impactDescription: avoids unnecessary subscriptions+tags: rerender, searchParams, localStorage, optimization+---++## Defer State Reads to Usage Point++Don't subscribe to dynamic state (searchParams, localStorage) if you only read it inside callbacks.++**Incorrect (subscribes to all searchParams changes):**++```tsx+function ShareButton({ chatId }: { chatId: string }) {+ const searchParams = useSearchParams()++ const handleShare = () => {+ const ref = searchParams.get('ref')+ shareChat(chatId, { ref })+ }++ return <button onClick={handleShare}>Share</button>+}+```++**Correct (reads on demand, no subscription):**++```tsx+function ShareButton({ chatId }: { chatId: string }) {+ const handleShare = () => {+ const params = new URLSearchParams(window.location.search)+ const ref = params.get('ref')+ shareChat(chatId, { ref })+ }++ return <button onClick={handleShare}>Share</button>+}+```diff --git a/.claude/skills/vercel-react-best-practices/rules/rerender-dependencies.md b/.claude/skills/vercel-react-best-practices/rules/rerender-dependencies.mdnew file mode 100644index 0000000..47a4d92--- /dev/null+++ b/.claude/skills/vercel-react-best-practices/rules/rerender-dependencies.md@@ -0,0 +1,45 @@+---+title: Narrow Effect Dependencies+impact: LOW+impactDescription: minimizes effect re-runs+tags: rerender, useEffect, dependencies, optimization+---++## Narrow Effect Dependencies++Specify primitive dependencies instead of objects to minimize effect re-runs.++**Incorrect (re-runs on any user field change):**++```tsx+useEffect(() => {+ console.log(user.id)+}, [user])+```++**Correct (re-runs only when id changes):**++```tsx+useEffect(() => {+ console.log(user.id)+}, [user.id])+```++**For derived state, compute outside effect:**++```tsx+// Incorrect: runs on width=767, 766, 765...+useEffect(() => {+ if (width < 768) {+ enableMobileMode()+ }+}, [width])++// Correct: runs only on boolean transition+const isMobile = width < 768+useEffect(() => {+ if (isMobile) {+ enableMobileMode()+ }+}, [isMobile])+```diff --git a/.claude/skills/vercel-react-best-practices/rules/rerender-derived-state-no-effect.md b/.claude/skills/vercel-react-best-practices/rules/rerender-derived-state-no-effect.mdnew file mode 100644index 0000000..3d9fe40--- /dev/null+++ b/.claude/skills/vercel-react-best-practices/rules/rerender-derived-state-no-effect.md@@ -0,0 +1,40 @@+---+title: Calculate Derived State During Rendering+impact: MEDIUM+impactDescription: avoids redundant renders and state drift+tags: rerender, derived-state, useEffect, state+---++## Calculate Derived State During Rendering++If a value can be computed from current props/state, do not store it in state or update it in an effect. Derive it during render to avoid extra renders and state drift. Do not set state in effects solely in response to prop changes; prefer derived values or keyed resets instead.++**Incorrect (redundant state and effect):**++```tsx+function Form() {+ const [firstName, setFirstName] = useState('First')+ const [lastName, setLastName] = useState('Last')+ const [fullName, setFullName] = useState('')++ useEffect(() => {+ setFullName(firstName + ' ' + lastName)+ }, [firstName, lastName])++ return <p>{fullName}</p>+}+```++**Correct (derive during render):**++```tsx+function Form() {+ const [firstName, setFirstName] = useState('First')+ const [lastName, setLastName] = useState('Last')+ const fullName = firstName + ' ' + lastName++ return <p>{fullName}</p>+}+```++References: [You Might Not Need an Effect](https://react.dev/learn/you-might-not-need-an-effect)diff --git a/.claude/skills/vercel-react-best-practices/rules/rerender-derived-state.md b/.claude/skills/vercel-react-best-practices/rules/rerender-derived-state.mdnew file mode 100644index 0000000..e5c899f--- /dev/null+++ b/.claude/skills/vercel-react-best-practices/rules/rerender-derived-state.md@@ -0,0 +1,29 @@+---+title: Subscribe to Derived State+impact: MEDIUM+impactDescription: reduces re-render frequency+tags: rerender, derived-state, media-query, optimization+---++## Subscribe to Derived State++Subscribe to derived boolean state instead of continuous values to reduce re-render frequency.++**Incorrect (re-renders on every pixel change):**++```tsx+function Sidebar() {+ const width = useWindowWidth() // updates continuously+ const isMobile = width < 768+ return <nav className={isMobile ? 'mobile' : 'desktop'} />+}+```++**Correct (re-renders only when boolean changes):**++```tsx+function Sidebar() {+ const isMobile = useMediaQuery('(max-width: 767px)')+ return <nav className={isMobile ? 'mobile' : 'desktop'} />+}+```diff --git a/.claude/skills/vercel-react-best-practices/rules/rerender-functional-setstate.md b/.claude/skills/vercel-react-best-practices/rules/rerender-functional-setstate.mdnew file mode 100644index 0000000..b004ef4--- /dev/null+++ b/.claude/skills/vercel-react-best-practices/rules/rerender-functional-setstate.md@@ -0,0 +1,74 @@+---+title: Use Functional setState Updates+impact: MEDIUM+impactDescription: prevents stale closures and unnecessary callback recreations+tags: react, hooks, useState, useCallback, callbacks, closures+---++## Use Functional setState Updates++When updating state based on the current state value, use the functional update form of setState instead of directly referencing the state variable. This prevents stale closures, eliminates unnecessary dependencies, and creates stable callback references.++**Incorrect (requires state as dependency):**++```tsx+function TodoList() {+ const [items, setItems] = useState(initialItems)++ // Callback must depend on items, recreated on every items change+ const addItems = useCallback((newItems: Item[]) => {+ setItems([...items, ...newItems])+ }, [items]) // ❌ items dependency causes recreations++ // Risk of stale closure if dependency is forgotten+ const removeItem = useCallback((id: string) => {+ setItems(items.filter(item => item.id !== id))+ }, []) // ❌ Missing items dependency - will use stale items!++ return <ItemsEditor items={items} onAdd={addItems} onRemove={removeItem} />+}+```++The first callback is recreated every time `items` changes, which can cause child components to re-render unnecessarily. The second callback has a stale closure bug—it will always reference the initial `items` value.++**Correct (stable callbacks, no stale closures):**++```tsx+function TodoList() {+ const [items, setItems] = useState(initialItems)++ // Stable callback, never recreated+ const addItems = useCallback((newItems: Item[]) => {+ setItems(curr => [...curr, ...newItems])+ }, []) // ✅ No dependencies needed++ // Always uses latest state, no stale closure risk+ const removeItem = useCallback((id: string) => {+ setItems(curr => curr.filter(item => item.id !== id))+ }, []) // ✅ Safe and stable++ return <ItemsEditor items={items} onAdd={addItems} onRemove={removeItem} />+}+```++**Benefits:**++1. **Stable callback references** - Callbacks don't need to be recreated when state changes+2. **No stale closures** - Always operates on the latest state value+3. **Fewer dependencies** - Simplifies dependency arrays and reduces memory leaks+4. **Prevents bugs** - Eliminates the most common source of React closure bugs++**When to use functional updates:**++- Any setState that depends on the current state value+- Inside useCallback/useMemo when state is needed+- Event handlers that reference state+- Async operations that update state++**When direct updates are fine:**++- Setting state to a static value: `setCount(0)`+- Setting state from props/arguments only: `setName(newName)`+- State doesn't depend on previous value++**Note:** If your project has [React Compiler](https://react.dev/learn/react-compiler) enabled, the compiler can automatically optimize some cases, but functional updates are still recommended for correctness and to prevent stale closure bugs.diff --git a/.claude/skills/vercel-react-best-practices/rules/rerender-lazy-state-init.md b/.claude/skills/vercel-react-best-practices/rules/rerender-lazy-state-init.mdnew file mode 100644index 0000000..4ecb350--- /dev/null+++ b/.claude/skills/vercel-react-best-practices/rules/rerender-lazy-state-init.md@@ -0,0 +1,58 @@+---+title: Use Lazy State Initialization+impact: MEDIUM+impactDescription: wasted computation on every render+tags: react, hooks, useState, performance, initialization+---++## Use Lazy State Initialization++Pass a function to `useState` for expensive initial values. Without the function form, the initializer runs on every render even though the value is only used once.++**Incorrect (runs on every render):**++```tsx+function FilteredList({ items }: { items: Item[] }) {+ // buildSearchIndex() runs on EVERY render, even after initialization+ const [searchIndex, setSearchIndex] = useState(buildSearchIndex(items))+ const [query, setQuery] = useState('')++ // When query changes, buildSearchIndex runs again unnecessarily+ return <SearchResults index={searchIndex} query={query} />+}++function UserProfile() {+ // JSON.parse runs on every render+ const [settings, setSettings] = useState(+ JSON.parse(localStorage.getItem('settings') || '{}')+ )++ return <SettingsForm settings={settings} onChange={setSettings} />+}+```++**Correct (runs only once):**++```tsx+function FilteredList({ items }: { items: Item[] }) {+ // buildSearchIndex() runs ONLY on initial render+ const [searchIndex, setSearchIndex] = useState(() => buildSearchIndex(items))+ const [query, setQuery] = useState('')++ return <SearchResults index={searchIndex} query={query} />+}++function UserProfile() {+ // JSON.parse runs only on initial render+ const [settings, setSettings] = useState(() => {+ const stored = localStorage.getItem('settings')+ return stored ? JSON.parse(stored) : {}+ })++ return <SettingsForm settings={settings} onChange={setSettings} />+}+```++Use lazy initialization when computing initial values from localStorage/sessionStorage, building data structures (indexes, maps), reading from the DOM, or performing heavy transformations.++For simple primitives (`useState(0)`), direct references (`useState(props.value)`), or cheap literals (`useState({})`), the function form is unnecessary.diff --git a/.claude/skills/vercel-react-best-practices/rules/rerender-memo-with-default-value.md b/.claude/skills/vercel-react-best-practices/rules/rerender-memo-with-default-value.mdnew file mode 100644index 0000000..6357049--- /dev/null+++ b/.claude/skills/vercel-react-best-practices/rules/rerender-memo-with-default-value.md@@ -0,0 +1,38 @@+---++title: Extract Default Non-primitive Parameter Value from Memoized Component to Constant+impact: MEDIUM+impactDescription: restores memoization by using a constant for default value+tags: rerender, memo, optimization++---++## Extract Default Non-primitive Parameter Value from Memoized Component to Constant++When memoized component has a default value for some non-primitive optional parameter, such as an array, function, or object, calling the component without that parameter results in broken memoization. This is because new value instances are created on every rerender, and they do not pass strict equality comparison in `memo()`.++To address this issue, extract the default value into a constant.++**Incorrect (`onClick` has different values on every rerender):**++```tsx+const UserAvatar = memo(function UserAvatar({ onClick = () => {} }: { onClick?: () => void }) {+ // ...+})++// Used without optional onClick+<UserAvatar />+```++**Correct (stable default value):**++```tsx+const NOOP = () => {};++const UserAvatar = memo(function UserAvatar({ onClick = NOOP }: { onClick?: () => void }) {+ // ...+})++// Used without optional onClick+<UserAvatar />+```diff --git a/.claude/skills/vercel-react-best-practices/rules/rerender-memo.md b/.claude/skills/vercel-react-best-practices/rules/rerender-memo.mdnew file mode 100644index 0000000..f8982ab--- /dev/null+++ b/.claude/skills/vercel-react-best-practices/rules/rerender-memo.md@@ -0,0 +1,44 @@+---+title: Extract to Memoized Components+impact: MEDIUM+impactDescription: enables early returns+tags: rerender, memo, useMemo, optimization+---++## Extract to Memoized Components++Extract expensive work into memoized components to enable early returns before computation.++**Incorrect (computes avatar even when loading):**++```tsx+function Profile({ user, loading }: Props) {+ const avatar = useMemo(() => {+ const id = computeAvatarId(user)+ return <Avatar id={id} />+ }, [user])++ if (loading) return <Skeleton />+ return <div>{avatar}</div>+}+```++**Correct (skips computation when loading):**++```tsx+const UserAvatar = memo(function UserAvatar({ user }: { user: User }) {+ const id = useMemo(() => computeAvatarId(user), [user])+ return <Avatar id={id} />+})++function Profile({ user, loading }: Props) {+ if (loading) return <Skeleton />+ return (+ <div>+ <UserAvatar user={user} />+ </div>+ )+}+```++**Note:** If your project has [React Compiler](https://react.dev/learn/react-compiler) enabled, manual memoization with `memo()` and `useMemo()` is not necessary. The compiler automatically optimizes re-renders.diff --git a/.claude/skills/vercel-react-best-practices/rules/rerender-move-effect-to-event.md b/.claude/skills/vercel-react-best-practices/rules/rerender-move-effect-to-event.mdnew file mode 100644index 0000000..dd58a1a--- /dev/null+++ b/.claude/skills/vercel-react-best-practices/rules/rerender-move-effect-to-event.md@@ -0,0 +1,45 @@+---+title: Put Interaction Logic in Event Handlers+impact: MEDIUM+impactDescription: avoids effect re-runs and duplicate side effects+tags: rerender, useEffect, events, side-effects, dependencies+---++## Put Interaction Logic in Event Handlers++If a side effect is triggered by a specific user action (submit, click, drag), run it in that event handler. Do not model the action as state + effect; it makes effects re-run on unrelated changes and can duplicate the action.++**Incorrect (event modeled as state + effect):**++```tsx+function Form() {+ const [submitted, setSubmitted] = useState(false)+ const theme = useContext(ThemeContext)++ useEffect(() => {+ if (submitted) {+ post('/api/register')+ showToast('Registered', theme)+ }+ }, [submitted, theme])++ return <button onClick={() => setSubmitted(true)}>Submit</button>+}+```++**Correct (do it in the handler):**++```tsx+function Form() {+ const theme = useContext(ThemeContext)++ function handleSubmit() {+ post('/api/register')+ showToast('Registered', theme)+ }++ return <button onClick={handleSubmit}>Submit</button>+}+```++Reference: [Should this code move to an event handler?](https://react.dev/learn/removing-effect-dependencies#should-this-code-move-to-an-event-handler)diff --git a/.claude/skills/vercel-react-best-practices/rules/rerender-no-inline-components.md b/.claude/skills/vercel-react-best-practices/rules/rerender-no-inline-components.mdnew file mode 100644index 0000000..d97592a--- /dev/null+++ b/.claude/skills/vercel-react-best-practices/rules/rerender-no-inline-components.md@@ -0,0 +1,82 @@+---+title: Don't Define Components Inside Components+impact: HIGH+impactDescription: prevents remount on every render+tags: rerender, components, remount, performance+---++## Don't Define Components Inside Components++**Impact: HIGH (prevents remount on every render)**++Defining a component inside another component creates a new component type on every render. React sees a different component each time and fully remounts it, destroying all state and DOM.++A common reason developers do this is to access parent variables without passing props. Always pass props instead.++**Incorrect (remounts on every render):**++```tsx+function UserProfile({ user, theme }) {+ // Defined inside to access `theme` - BAD+ const Avatar = () => (+ <img+ src={user.avatarUrl}+ className={theme === 'dark' ? 'avatar-dark' : 'avatar-light'}+ />+ )++ // Defined inside to access `user` - BAD+ const Stats = () => (+ <div>+ <span>{user.followers} followers</span>+ <span>{user.posts} posts</span>+ </div>+ )++ return (+ <div>+ <Avatar />+ <Stats />+ </div>+ )+}+```++Every time `UserProfile` renders, `Avatar` and `Stats` are new component types. React unmounts the old instances and mounts new ones, losing any internal state, running effects again, and recreating DOM nodes.++**Correct (pass props instead):**++```tsx+function Avatar({ src, theme }: { src: string; theme: string }) {+ return (+ <img+ src={src}+ className={theme === 'dark' ? 'avatar-dark' : 'avatar-light'}+ />+ )+}++function Stats({ followers, posts }: { followers: number; posts: number }) {+ return (+ <div>+ <span>{followers} followers</span>+ <span>{posts} posts</span>+ </div>+ )+}++function UserProfile({ user, theme }) {+ return (+ <div>+ <Avatar src={user.avatarUrl} theme={theme} />+ <Stats followers={user.followers} posts={user.posts} />+ </div>+ )+}+```++**Symptoms of this bug:**+- Input fields lose focus on every keystroke+- Animations restart unexpectedly+- `useEffect` cleanup/setup runs on every parent render+- Scroll position resets inside the componentdiff --git a/.claude/skills/vercel-react-best-practices/rules/rerender-simple-expression-in-memo.md b/.claude/skills/vercel-react-best-practices/rules/rerender-simple-expression-in-memo.mdnew file mode 100644index 0000000..59dfab0--- /dev/null+++ b/.claude/skills/vercel-react-best-practices/rules/rerender-simple-expression-in-memo.md@@ -0,0 +1,35 @@+---+title: Do not wrap a simple expression with a primitive result type in useMemo+impact: LOW-MEDIUM+impactDescription: wasted computation on every render+tags: rerender, useMemo, optimization+---++## Do not wrap a simple expression with a primitive result type in useMemo++When an expression is simple (few logical or arithmetical operators) and has a primitive result type (boolean, number, string), do not wrap it in `useMemo`.+Calling `useMemo` and comparing hook dependencies may consume more resources than the expression itself.++**Incorrect:**++```tsx+function Header({ user, notifications }: Props) {+ const isLoading = useMemo(() => {+ return user.isLoading || notifications.isLoading+ }, [user.isLoading, notifications.isLoading])++ if (isLoading) return <Skeleton />+ // return some markup+}+```++**Correct:**++```tsx+function Header({ user, notifications }: Props) {+ const isLoading = user.isLoading || notifications.isLoading++ if (isLoading) return <Skeleton />+ // return some markup+}+```diff --git a/.claude/skills/vercel-react-best-practices/rules/rerender-split-combined-hooks.md b/.claude/skills/vercel-react-best-practices/rules/rerender-split-combined-hooks.mdnew file mode 100644index 0000000..89d8056--- /dev/null+++ b/.claude/skills/vercel-react-best-practices/rules/rerender-split-combined-hooks.md@@ -0,0 +1,64 @@+---+title: Split Combined Hook Computations+impact: MEDIUM+impactDescription: avoids recomputing independent steps+tags: rerender, useMemo, useEffect, dependencies, optimization+---++## Split Combined Hook Computations++When a hook contains multiple independent tasks with different dependencies, split them into separate hooks. A combined hook reruns all tasks when any dependency changes, even if some tasks don't use the changed value.++**Incorrect (changing `sortOrder` recomputes filtering):**++```tsx+const sortedProducts = useMemo(() => {+ const filtered = products.filter((p) => p.category === category)+ const sorted = filtered.toSorted((a, b) =>+ sortOrder === "asc" ? a.price - b.price : b.price - a.price+ )+ return sorted+}, [products, category, sortOrder])+```++**Correct (filtering only recomputes when products or category change):**++```tsx+const filteredProducts = useMemo(+ () => products.filter((p) => p.category === category),+ [products, category]+)++const sortedProducts = useMemo(+ () =>+ filteredProducts.toSorted((a, b) =>+ sortOrder === "asc" ? a.price - b.price : b.price - a.price+ ),+ [filteredProducts, sortOrder]+)+```++This pattern also applies to `useEffect` when combining unrelated side effects:++**Incorrect (both effects run when either dependency changes):**++```tsx+useEffect(() => {+ analytics.trackPageView(pathname)+ document.title = `${pageTitle} | My App`+}, [pathname, pageTitle])+```++**Correct (effects run independently):**++```tsx+useEffect(() => {+ analytics.trackPageView(pathname)+}, [pathname])++useEffect(() => {+ document.title = `${pageTitle} | My App`+}, [pageTitle])+```++**Note:** If your project has [React Compiler](https://react.dev/learn/react-compiler) enabled, it automatically optimizes dependency tracking and may handle some of these cases for you.diff --git a/.claude/skills/vercel-react-best-practices/rules/rerender-transitions.md b/.claude/skills/vercel-react-best-practices/rules/rerender-transitions.mdnew file mode 100644index 0000000..d99f43f--- /dev/null+++ b/.claude/skills/vercel-react-best-practices/rules/rerender-transitions.md@@ -0,0 +1,40 @@+---+title: Use Transitions for Non-Urgent Updates+impact: MEDIUM+impactDescription: maintains UI responsiveness+tags: rerender, transitions, startTransition, performance+---++## Use Transitions for Non-Urgent Updates++Mark frequent, non-urgent state updates as transitions to maintain UI responsiveness.++**Incorrect (blocks UI on every scroll):**++```tsx+function ScrollTracker() {+ const [scrollY, setScrollY] = useState(0)+ useEffect(() => {+ const handler = () => setScrollY(window.scrollY)+ window.addEventListener('scroll', handler, { passive: true })+ return () => window.removeEventListener('scroll', handler)+ }, [])+}+```++**Correct (non-blocking updates):**++```tsx+import { startTransition } from 'react'++function ScrollTracker() {+ const [scrollY, setScrollY] = useState(0)+ useEffect(() => {+ const handler = () => {+ startTransition(() => setScrollY(window.scrollY))+ }+ window.addEventListener('scroll', handler, { passive: true })+ return () => window.removeEventListener('scroll', handler)+ }, [])+}+```diff --git a/.claude/skills/vercel-react-best-practices/rules/rerender-use-deferred-value.md b/.claude/skills/vercel-react-best-practices/rules/rerender-use-deferred-value.mdnew file mode 100644index 0000000..619c04b--- /dev/null+++ b/.claude/skills/vercel-react-best-practices/rules/rerender-use-deferred-value.md@@ -0,0 +1,59 @@+---+title: Use useDeferredValue for Expensive Derived Renders+impact: MEDIUM+impactDescription: keeps input responsive during heavy computation+tags: rerender, useDeferredValue, optimization, concurrent+---++## Use useDeferredValue for Expensive Derived Renders++When user input triggers expensive computations or renders, use `useDeferredValue` to keep the input responsive. The deferred value lags behind, allowing React to prioritize the input update and render the expensive result when idle.++**Incorrect (input feels laggy while filtering):**++```tsx+function Search({ items }: { items: Item[] }) {+ const [query, setQuery] = useState('')+ const filtered = items.filter(item => fuzzyMatch(item, query))++ return (+ <>+ <input value={query} onChange={e => setQuery(e.target.value)} />+ <ResultsList results={filtered} />+ </>+ )+}+```++**Correct (input stays snappy, results render when ready):**++```tsx+function Search({ items }: { items: Item[] }) {+ const [query, setQuery] = useState('')+ const deferredQuery = useDeferredValue(query)+ const filtered = useMemo(+ () => items.filter(item => fuzzyMatch(item, deferredQuery)),+ [items, deferredQuery]+ )+ const isStale = query !== deferredQuery++ return (+ <>+ <input value={query} onChange={e => setQuery(e.target.value)} />+ <div style={{ opacity: isStale ? 0.7 : 1 }}>+ <ResultsList results={filtered} />+ </div>+ </>+ )+}+```++**When to use:**++- Filtering/searching large lists+- Expensive visualizations (charts, graphs) reacting to input+- Any derived state that causes noticeable render delays++**Note:** Wrap the expensive computation in `useMemo` with the deferred value as a dependency, otherwise it still runs on every render.++Reference: [React useDeferredValue](https://react.dev/reference/react/useDeferredValue)diff --git a/.claude/skills/vercel-react-best-practices/rules/rerender-use-ref-transient-values.md b/.claude/skills/vercel-react-best-practices/rules/rerender-use-ref-transient-values.mdnew file mode 100644index 0000000..cf04b81--- /dev/null+++ b/.claude/skills/vercel-react-best-practices/rules/rerender-use-ref-transient-values.md@@ -0,0 +1,73 @@+---+title: Use useRef for Transient Values+impact: MEDIUM+impactDescription: avoids unnecessary re-renders on frequent updates+tags: rerender, useref, state, performance+---++## Use useRef for Transient Values++When a value changes frequently and you don't want a re-render on every update (e.g., mouse trackers, intervals, transient flags), store it in `useRef` instead of `useState`. Keep component state for UI; use refs for temporary DOM-adjacent values. Updating a ref does not trigger a re-render.++**Incorrect (renders every update):**++```tsx+function Tracker() {+ const [lastX, setLastX] = useState(0)++ useEffect(() => {+ const onMove = (e: MouseEvent) => setLastX(e.clientX)+ window.addEventListener('mousemove', onMove)+ return () => window.removeEventListener('mousemove', onMove)+ }, [])++ return (+ <div+ style={{+ position: 'fixed',+ top: 0,+ left: lastX,+ width: 8,+ height: 8,+ background: 'black',+ }}+ />+ )+}+```++**Correct (no re-render for tracking):**++```tsx+function Tracker() {+ const lastXRef = useRef(0)+ const dotRef = useRef<HTMLDivElement>(null)++ useEffect(() => {+ const onMove = (e: MouseEvent) => {+ lastXRef.current = e.clientX+ const node = dotRef.current+ if (node) {+ node.style.transform = `translateX(${e.clientX}px)`+ }+ }+ window.addEventListener('mousemove', onMove)+ return () => window.removeEventListener('mousemove', onMove)+ }, [])++ return (+ <div+ ref={dotRef}+ style={{+ position: 'fixed',+ top: 0,+ left: 0,+ width: 8,+ height: 8,+ background: 'black',+ transform: 'translateX(0px)',+ }}+ />+ )+}+```diff --git a/.claude/skills/vercel-react-best-practices/rules/server-after-nonblocking.md b/.claude/skills/vercel-react-best-practices/rules/server-after-nonblocking.mdnew file mode 100644index 0000000..e8f5b26--- /dev/null+++ b/.claude/skills/vercel-react-best-practices/rules/server-after-nonblocking.md@@ -0,0 +1,73 @@+---+title: Use after() for Non-Blocking Operations+impact: MEDIUM+impactDescription: faster response times+tags: server, async, logging, analytics, side-effects+---++## Use after() for Non-Blocking Operations++Use Next.js's `after()` to schedule work that should execute after a response is sent. This prevents logging, analytics, and other side effects from blocking the response.++**Incorrect (blocks response):**++```tsx+import { logUserAction } from '@/app/utils'++export async function POST(request: Request) {+ // Perform mutation+ await updateDatabase(request)++ // Logging blocks the response+ const userAgent = request.headers.get('user-agent') || 'unknown'+ await logUserAction({ userAgent })++ return new Response(JSON.stringify({ status: 'success' }), {+ status: 200,+ headers: { 'Content-Type': 'application/json' }+ })+}+```++**Correct (non-blocking):**++```tsx+import { after } from 'next/server'+import { headers, cookies } from 'next/headers'+import { logUserAction } from '@/app/utils'++export async function POST(request: Request) {+ // Perform mutation+ await updateDatabase(request)++ // Log after response is sent+ after(async () => {+ const userAgent = (await headers()).get('user-agent') || 'unknown'+ const sessionCookie = (await cookies()).get('session-id')?.value || 'anonymous'++ logUserAction({ sessionCookie, userAgent })+ })++ return new Response(JSON.stringify({ status: 'success' }), {+ status: 200,+ headers: { 'Content-Type': 'application/json' }+ })+}+```++The response is sent immediately while logging happens in the background.++**Common use cases:**++- Analytics tracking+- Audit logging+- Sending notifications+- Cache invalidation+- Cleanup tasks++**Important notes:**++- `after()` runs even if the response fails or redirects+- Works in Server Actions, Route Handlers, and Server Components++Reference: [https://nextjs.org/docs/app/api-reference/functions/after](https://nextjs.org/docs/app/api-reference/functions/after)diff --git a/.claude/skills/vercel-react-best-practices/rules/server-auth-actions.md b/.claude/skills/vercel-react-best-practices/rules/server-auth-actions.mdnew file mode 100644index 0000000..ee82c04--- /dev/null+++ b/.claude/skills/vercel-react-best-practices/rules/server-auth-actions.md@@ -0,0 +1,96 @@+---+title: Authenticate Server Actions Like API Routes+impact: CRITICAL+impactDescription: prevents unauthorized access to server mutations+tags: server, server-actions, authentication, security, authorization+---++## Authenticate Server Actions Like API Routes++**Impact: CRITICAL (prevents unauthorized access to server mutations)**++Server Actions (functions with `"use server"`) are exposed as public endpoints, just like API routes. Always verify authentication and authorization **inside** each Server Action—do not rely solely on middleware, layout guards, or page-level checks, as Server Actions can be invoked directly.++Next.js documentation explicitly states: "Treat Server Actions with the same security considerations as public-facing API endpoints, and verify if the user is allowed to perform a mutation."++**Incorrect (no authentication check):**++```typescript+'use server'++export async function deleteUser(userId: string) {+ // Anyone can call this! No auth check+ await db.user.delete({ where: { id: userId } })+ return { success: true }+}+```++**Correct (authentication inside the action):**++```typescript+'use server'++import { verifySession } from '@/lib/auth'+import { unauthorized } from '@/lib/errors'++export async function deleteUser(userId: string) {+ // Always check auth inside the action+ const session = await verifySession()++ if (!session) {+ throw unauthorized('Must be logged in')+ }++ // Check authorization too+ if (session.user.role !== 'admin' && session.user.id !== userId) {+ throw unauthorized('Cannot delete other users')+ }++ await db.user.delete({ where: { id: userId } })+ return { success: true }+}+```++**With input validation:**++```typescript+'use server'++import { verifySession } from '@/lib/auth'+import { z } from 'zod'++const updateProfileSchema = z.object({+ userId: z.string().uuid(),+ name: z.string().min(1).max(100),+ email: z.string().email()+})++export async function updateProfile(data: unknown) {+ // Validate input first+ const validated = updateProfileSchema.parse(data)++ // Then authenticate+ const session = await verifySession()+ if (!session) {+ throw new Error('Unauthorized')+ }++ // Then authorize+ if (session.user.id !== validated.userId) {+ throw new Error('Can only update own profile')+ }++ // Finally perform the mutation+ await db.user.update({+ where: { id: validated.userId },+ data: {+ name: validated.name,+ email: validated.email+ }+ })++ return { success: true }+}+```++Reference: [https://nextjs.org/docs/app/guides/authentication](https://nextjs.org/docs/app/guides/authentication)diff --git a/.claude/skills/vercel-react-best-practices/rules/server-cache-lru.md b/.claude/skills/vercel-react-best-practices/rules/server-cache-lru.mdnew file mode 100644index 0000000..ef6938a--- /dev/null+++ b/.claude/skills/vercel-react-best-practices/rules/server-cache-lru.md@@ -0,0 +1,41 @@+---+title: Cross-Request LRU Caching+impact: HIGH+impactDescription: caches across requests+tags: server, cache, lru, cross-request+---++## Cross-Request LRU Caching++`React.cache()` only works within one request. For data shared across sequential requests (user clicks button A then button B), use an LRU cache.++**Implementation:**++```typescript+import { LRUCache } from 'lru-cache'++const cache = new LRUCache<string, any>({+ max: 1000,+ ttl: 5 * 60 * 1000 // 5 minutes+})++export async function getUser(id: string) {+ const cached = cache.get(id)+ if (cached) return cached++ const user = await db.user.findUnique({ where: { id } })+ cache.set(id, user)+ return user+}++// Request 1: DB query, result cached+// Request 2: cache hit, no DB query+```++Use when sequential user actions hit multiple endpoints needing the same data within seconds.++**With Vercel's [Fluid Compute](https://vercel.com/docs/fluid-compute):** LRU caching is especially effective because multiple concurrent requests can share the same function instance and cache. This means the cache persists across requests without needing external storage like Redis.++**In traditional serverless:** Each invocation runs in isolation, so consider Redis for cross-process caching.++Reference: [https://github.com/isaacs/node-lru-cache](https://github.com/isaacs/node-lru-cache)diff --git a/.claude/skills/vercel-react-best-practices/rules/server-cache-react.md b/.claude/skills/vercel-react-best-practices/rules/server-cache-react.mdnew file mode 100644index 0000000..87c9ca3--- /dev/null+++ b/.claude/skills/vercel-react-best-practices/rules/server-cache-react.md@@ -0,0 +1,76 @@+---+title: Per-Request Deduplication with React.cache()+impact: MEDIUM+impactDescription: deduplicates within request+tags: server, cache, react-cache, deduplication+---++## Per-Request Deduplication with React.cache()++Use `React.cache()` for server-side request deduplication. Authentication and database queries benefit most.++**Usage:**++```typescript+import { cache } from 'react'++export const getCurrentUser = cache(async () => {+ const session = await auth()+ if (!session?.user?.id) return null+ return await db.user.findUnique({+ where: { id: session.user.id }+ })+})+```++Within a single request, multiple calls to `getCurrentUser()` execute the query only once.++**Avoid inline objects as arguments:**++`React.cache()` uses shallow equality (`Object.is`) to determine cache hits. Inline objects create new references each call, preventing cache hits.++**Incorrect (always cache miss):**++```typescript+const getUser = cache(async (params: { uid: number }) => {+ return await db.user.findUnique({ where: { id: params.uid } })+})++// Each call creates new object, never hits cache+getUser({ uid: 1 })+getUser({ uid: 1 }) // Cache miss, runs query again+```++**Correct (cache hit):**++```typescript+const getUser = cache(async (uid: number) => {+ return await db.user.findUnique({ where: { id: uid } })+})++// Primitive args use value equality+getUser(1)+getUser(1) // Cache hit, returns cached result+```++If you must pass objects, pass the same reference:++```typescript+const params = { uid: 1 }+getUser(params) // Query runs+getUser(params) // Cache hit (same reference)+```++**Next.js-Specific Note:**++In Next.js, the `fetch` API is automatically extended with request memoization. Requests with the same URL and options are automatically deduplicated within a single request, so you don't need `React.cache()` for `fetch` calls. However, `React.cache()` is still essential for other async tasks:++- Database queries (Prisma, Drizzle, etc.)+- Heavy computations+- Authentication checks+- File system operations+- Any non-fetch async work++Use `React.cache()` to deduplicate these operations across your component tree.++Reference: [React.cache documentation](https://react.dev/reference/react/cache)diff --git a/.claude/skills/vercel-react-best-practices/rules/server-dedup-props.md b/.claude/skills/vercel-react-best-practices/rules/server-dedup-props.mdnew file mode 100644index 0000000..fb24a25--- /dev/null+++ b/.claude/skills/vercel-react-best-practices/rules/server-dedup-props.md@@ -0,0 +1,65 @@+---+title: Avoid Duplicate Serialization in RSC Props+impact: LOW+impactDescription: reduces network payload by avoiding duplicate serialization+tags: server, rsc, serialization, props, client-components+---++## Avoid Duplicate Serialization in RSC Props++**Impact: LOW (reduces network payload by avoiding duplicate serialization)**++RSC→client serialization deduplicates by object reference, not value. Same reference = serialized once; new reference = serialized again. Do transformations (`.toSorted()`, `.filter()`, `.map()`) in client, not server.++**Incorrect (duplicates array):**++```tsx+// RSC: sends 6 strings (2 arrays × 3 items)+<ClientList usernames={usernames} usernamesOrdered={usernames.toSorted()} />+```++**Correct (sends 3 strings):**++```tsx+// RSC: send once+<ClientList usernames={usernames} />++// Client: transform there+'use client'+const sorted = useMemo(() => [...usernames].sort(), [usernames])+```++**Nested deduplication behavior:**++Deduplication works recursively. Impact varies by data type:++- `string[]`, `number[]`, `boolean[]`: **HIGH impact** - array + all primitives fully duplicated+- `object[]`: **LOW impact** - array duplicated, but nested objects deduplicated by reference++```tsx+// string[] - duplicates everything+usernames={['a','b']} sorted={usernames.toSorted()} // sends 4 strings++// object[] - duplicates array structure only+users={[{id:1},{id:2}]} sorted={users.toSorted()} // sends 2 arrays + 2 unique objects (not 4)+```++**Operations breaking deduplication (create new references):**++- Arrays: `.toSorted()`, `.filter()`, `.map()`, `.slice()`, `[...arr]`+- Objects: `{...obj}`, `Object.assign()`, `structuredClone()`, `JSON.parse(JSON.stringify())`++**More examples:**++```tsx+// ❌ Bad+<C users={users} active={users.filter(u => u.active)} />+<C product={product} productName={product.name} />++// ✅ Good+<C users={users} />+<C product={product} />+// Do filtering/destructuring in client+```++**Exception:** Pass derived data when transformation is expensive or client doesn't need original.diff --git a/.claude/skills/vercel-react-best-practices/rules/server-hoist-static-io.md b/.claude/skills/vercel-react-best-practices/rules/server-hoist-static-io.mdnew file mode 100644index 0000000..25205c2--- /dev/null+++ b/.claude/skills/vercel-react-best-practices/rules/server-hoist-static-io.md@@ -0,0 +1,149 @@+---+title: Hoist Static I/O to Module Level+impact: HIGH+impactDescription: avoids repeated file/network I/O per request+tags: server, io, performance, next.js, route-handlers, og-image+---++## Hoist Static I/O to Module Level++**Impact: HIGH (avoids repeated file/network I/O per request)**++When loading static assets (fonts, logos, images, config files) in route handlers or server functions, hoist the I/O operation to module level. Module-level code runs once when the module is first imported, not on every request. This eliminates redundant file system reads or network fetches that would otherwise run on every invocation.++**Incorrect (reads font file on every request):**++```typescript+// app/api/og/route.tsx+import { ImageResponse } from 'next/og'++export async function GET(request: Request) {+ // Runs on EVERY request - expensive!+ const fontData = await fetch(+ new URL('./fonts/Inter.ttf', import.meta.url)+ ).then(res => res.arrayBuffer())++ const logoData = await fetch(+ new URL('./images/logo.png', import.meta.url)+ ).then(res => res.arrayBuffer())++ return new ImageResponse(+ <div style={{ fontFamily: 'Inter' }}>+ <img src={logoData} />+ Hello World+ </div>,+ { fonts: [{ name: 'Inter', data: fontData }] }+ )+}+```++**Correct (loads once at module initialization):**++```typescript+// app/api/og/route.tsx+import { ImageResponse } from 'next/og'++// Module-level: runs ONCE when module is first imported+const fontData = fetch(+ new URL('./fonts/Inter.ttf', import.meta.url)+).then(res => res.arrayBuffer())++const logoData = fetch(+ new URL('./images/logo.png', import.meta.url)+).then(res => res.arrayBuffer())++export async function GET(request: Request) {+ // Await the already-started promises+ const [font, logo] = await Promise.all([fontData, logoData])++ return new ImageResponse(+ <div style={{ fontFamily: 'Inter' }}>+ <img src={logo} />+ Hello World+ </div>,+ { fonts: [{ name: 'Inter', data: font }] }+ )+}+```++**Correct (synchronous fs at module level):**++```typescript+// app/api/og/route.tsx+import { ImageResponse } from 'next/og'+import { readFileSync } from 'fs'+import { join } from 'path'++// Synchronous read at module level - blocks only during module init+const fontData = readFileSync(+ join(process.cwd(), 'public/fonts/Inter.ttf')+)++const logoData = readFileSync(+ join(process.cwd(), 'public/images/logo.png')+)++export async function GET(request: Request) {+ return new ImageResponse(+ <div style={{ fontFamily: 'Inter' }}>+ <img src={logoData} />+ Hello World+ </div>,+ { fonts: [{ name: 'Inter', data: fontData }] }+ )+}+```++**Incorrect (reads config on every call):**++```typescript+import fs from 'node:fs/promises'++export async function processRequest(data: Data) {+ const config = JSON.parse(+ await fs.readFile('./config.json', 'utf-8')+ )+ const template = await fs.readFile('./template.html', 'utf-8')++ return render(template, data, config)+}+```++**Correct (hoists config and template to module level):**++```typescript+import fs from 'node:fs/promises'++const configPromise = fs+ .readFile('./config.json', 'utf-8')+ .then(JSON.parse)+const templatePromise = fs.readFile('./template.html', 'utf-8')++export async function processRequest(data: Data) {+ const [config, template] = await Promise.all([+ configPromise,+ templatePromise,+ ])++ return render(template, data, config)+}+```++When to use this pattern:++- Loading fonts for OG image generation+- Loading static logos, icons, or watermarks+- Reading configuration files that don't change at runtime+- Loading email templates or other static templates+- Any static asset that's the same across all requests++When not to use this pattern:++- Assets that vary per request or user+- Files that may change during runtime (use caching with TTL instead)+- Large files that would consume too much memory if kept loaded+- Sensitive data that shouldn't persist in memory++With Vercel's [Fluid Compute](https://vercel.com/docs/fluid-compute), module-level caching is especially effective because multiple concurrent requests share the same function instance. The static assets stay loaded in memory across requests without cold start penalties.++In traditional serverless, each cold start re-executes module-level code, but subsequent warm invocations reuse the loaded assets until the instance is recycled.diff --git a/.claude/skills/vercel-react-best-practices/rules/server-no-shared-module-state.md b/.claude/skills/vercel-react-best-practices/rules/server-no-shared-module-state.mdnew file mode 100644index 0000000..ff7d9f2--- /dev/null+++ b/.claude/skills/vercel-react-best-practices/rules/server-no-shared-module-state.md@@ -0,0 +1,50 @@+---+title: Avoid Shared Module State for Request Data+impact: HIGH+impactDescription: prevents concurrency bugs and request data leaks+tags: server, rsc, ssr, concurrency, security, state+---++## Avoid Shared Module State for Request Data++For React Server Components and client components rendered during SSR, avoid using mutable module-level variables to share request-scoped data. Server renders can run concurrently in the same process. If one render writes to shared module state and another render reads it, you can get race conditions, cross-request contamination, and security bugs where one user's data appears in another user's response.++Treat module scope on the server as process-wide shared memory, not request-local state.++**Incorrect (request data leaks across concurrent renders):**++```tsx+let currentUser: User | null = null++export default async function Page() {+ currentUser = await auth()+ return <Dashboard />+}++async function Dashboard() {+ return <div>{currentUser?.name}</div>+}+```++If two requests overlap, request A can set `currentUser`, then request B overwrites it before request A finishes rendering `Dashboard`.++**Correct (keep request data local to the render tree):**++```tsx+export default async function Page() {+ const user = await auth()+ return <Dashboard user={user} />+}++function Dashboard({ user }: { user: User | null }) {+ return <div>{user?.name}</div>+}+```++Safe exceptions:++- Immutable static assets or config loaded once at module scope+- Shared caches intentionally designed for cross-request reuse and keyed correctly+- Process-wide singletons that do not store request- or user-specific mutable data++For static assets and config, see [Hoist Static I/O to Module Level](./server-hoist-static-io.md).diff --git a/.claude/skills/vercel-react-best-practices/rules/server-parallel-fetching.md b/.claude/skills/vercel-react-best-practices/rules/server-parallel-fetching.mdnew file mode 100644index 0000000..1affc83--- /dev/null+++ b/.claude/skills/vercel-react-best-practices/rules/server-parallel-fetching.md@@ -0,0 +1,83 @@+---+title: Parallel Data Fetching with Component Composition+impact: CRITICAL+impactDescription: eliminates server-side waterfalls+tags: server, rsc, parallel-fetching, composition+---++## Parallel Data Fetching with Component Composition++React Server Components execute sequentially within a tree. Restructure with composition to parallelize data fetching.++**Incorrect (Sidebar waits for Page's fetch to complete):**++```tsx+export default async function Page() {+ const header = await fetchHeader()+ return (+ <div>+ <div>{header}</div>+ <Sidebar />+ </div>+ )+}++async function Sidebar() {+ const items = await fetchSidebarItems()+ return <nav>{items.map(renderItem)}</nav>+}+```++**Correct (both fetch simultaneously):**++```tsx+async function Header() {+ const data = await fetchHeader()+ return <div>{data}</div>+}++async function Sidebar() {+ const items = await fetchSidebarItems()+ return <nav>{items.map(renderItem)}</nav>+}++export default function Page() {+ return (+ <div>+ <Header />+ <Sidebar />+ </div>+ )+}+```++**Alternative with children prop:**++```tsx+async function Header() {+ const data = await fetchHeader()+ return <div>{data}</div>+}++async function Sidebar() {+ const items = await fetchSidebarItems()+ return <nav>{items.map(renderItem)}</nav>+}++function Layout({ children }: { children: ReactNode }) {+ return (+ <div>+ <Header />+ {children}+ </div>+ )+}++export default function Page() {+ return (+ <Layout>+ <Sidebar />+ </Layout>+ )+}+```diff --git a/.claude/skills/vercel-react-best-practices/rules/server-parallel-nested-fetching.md b/.claude/skills/vercel-react-best-practices/rules/server-parallel-nested-fetching.mdnew file mode 100644index 0000000..be1dc25--- /dev/null+++ b/.claude/skills/vercel-react-best-practices/rules/server-parallel-nested-fetching.md@@ -0,0 +1,34 @@+---+title: Parallel Nested Data Fetching+impact: CRITICAL+impactDescription: eliminates server-side waterfalls+tags: server, rsc, parallel-fetching, promise-chaining+---++## Parallel Nested Data Fetching++When fetching nested data in parallel, chain dependent fetches within each item's promise so a slow item doesn't block the rest.++**Incorrect (a single slow item blocks all nested fetches):**++```tsx+const chats = await Promise.all(+ chatIds.map(id => getChat(id))+)++const chatAuthors = await Promise.all(+ chats.map(chat => getUser(chat.author))+)+```++If one `getChat(id)` out of 100 is extremely slow, the authors of the other 99 chats can't start loading even though their data is ready.++**Correct (each item chains its own nested fetch):**++```tsx+const chatAuthors = await Promise.all(+ chatIds.map(id => getChat(id).then(chat => getUser(chat.author)))+)+```++Each item independently chains `getChat` → `getUser`, so a slow chat doesn't block author fetches for the others.diff --git a/.claude/skills/vercel-react-best-practices/rules/server-serialization.md b/.claude/skills/vercel-react-best-practices/rules/server-serialization.mdnew file mode 100644index 0000000..39c5c41--- /dev/null+++ b/.claude/skills/vercel-react-best-practices/rules/server-serialization.md@@ -0,0 +1,38 @@+---+title: Minimize Serialization at RSC Boundaries+impact: HIGH+impactDescription: reduces data transfer size+tags: server, rsc, serialization, props+---++## Minimize Serialization at RSC Boundaries++The React Server/Client boundary serializes all object properties into strings and embeds them in the HTML response and subsequent RSC requests. This serialized data directly impacts page weight and load time, so **size matters a lot**. Only pass fields that the client actually uses.++**Incorrect (serializes all 50 fields):**++```tsx+async function Page() {+ const user = await fetchUser() // 50 fields+ return <Profile user={user} />+}++'use client'+function Profile({ user }: { user: User }) {+ return <div>{user.name}</div> // uses 1 field+}+```++**Correct (serializes only 1 field):**++```tsx+async function Page() {+ const user = await fetchUser()+ return <Profile name={user.name} />+}++'use client'+function Profile({ name }: { name: string }) {+ return <div>{name}</div>+}+```diff --git a/.gitignore b/.gitignorenew file mode 100644index 0000000..ad0b628--- /dev/null+++ b/.gitignore@@ -0,0 +1,8 @@+/target+node_modules/+dist/+# configuración local de cargo (ruta de compilación fuera de OneDrive)+/.cargo/config.toml+*.log+ejemplos/**+plan.mddiff --git a/Cargo.lock b/Cargo.locknew file mode 100644index 0000000..455e8c6--- /dev/null+++ b/Cargo.lock@@ -0,0 +1,4494 @@+# 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 = "alloc-no-stdlib"+version = "3.0.0"+source = "registry+https://github.com/rust-lang/crates.io-index"+checksum = "c2fb6cfd47bf496ff64095c20eaba0c201404ee38714d4142fcfa1dc334fcc7a"++[[package]]+name = "alloc-stdlib"+version = "0.3.0"+source = "registry+https://github.com/rust-lang/crates.io-index"+checksum = "0b5c1865780388bfa186411ab5f247819487fc4864c6e9c3106611fa347586e1"+dependencies = [+ "alloc-no-stdlib",+]++[[package]]+name = "android_system_properties"+version = "0.1.6"+source = "registry+https://github.com/rust-lang/crates.io-index"+checksum = "ae221649c9976a6f6c56ae1facf410f3ddb33cc661c4b7b61020a912d4237fbc"+dependencies = [+ "libc",+]++[[package]]+name = "anyhow"+version = "1.0.104"+source = "registry+https://github.com/rust-lang/crates.io-index"+checksum = "330a5ed07fa54e4702c9d6c4174f74427fc0ef6e214bbd677ae50a5099946470"++[[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 = "base64"+version = "0.21.7"+source = "registry+https://github.com/rust-lang/crates.io-index"+checksum = "9d297deb1925b89f2ccc13d7635fa0714f12c87adce1c75356b39ca9b7178567"++[[package]]+name = "base64"+version = "0.23.1"+source = "registry+https://github.com/rust-lang/crates.io-index"+checksum = "ac07cdecf99051d9a5238b80f35af32cdeba5b336e55d957b318b50137e18da5"++[[package]]+name = "bit-set"+version = "0.8.0"+source = "registry+https://github.com/rust-lang/crates.io-index"+checksum = "08807e080ed7f9d5433fa9b275196cfc35414f66a0c79d864dc51a0d825231a3"+dependencies = [+ "bit-vec 0.8.0",+]++[[package]]+name = "bit-set"+version = "0.11.1"+source = "registry+https://github.com/rust-lang/crates.io-index"+checksum = "56d87354e4229f54a44f7bf2435906a4656dba36026ab6eaca629a2c436a691c"+dependencies = [+ "bit-vec 0.10.2",+]++[[package]]+name = "bit-vec"+version = "0.8.0"+source = "registry+https://github.com/rust-lang/crates.io-index"+checksum = "5e764a1d40d510daf35e07be9eb06e75770908c27d411ee6c92109c9840eaaf7"++[[package]]+name = "bit-vec"+version = "0.10.2"+source = "registry+https://github.com/rust-lang/crates.io-index"+checksum = "72503af1e72be411d74ca45cd6b309878fcb35354e252fc2a3a8bda3a97082a0"++[[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 = "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 = "brotli"+version = "9.1.1"+source = "registry+https://github.com/rust-lang/crates.io-index"+checksum = "627b7cfb0578f0eafce087a90fcd40add1231900b69e4d4de2d456260a4f5d81"+dependencies = [+ "alloc-no-stdlib",+ "alloc-stdlib",+ "brotli-decompressor",+]++[[package]]+name = "brotli-decompressor"+version = "6.3.1"+source = "registry+https://github.com/rust-lang/crates.io-index"+checksum = "75c74c9c51b9140663e196b5fb88bc94c334d7a497c8311cb759d8557874747f"+dependencies = [+ "alloc-no-stdlib",+ "alloc-stdlib",+]++[[package]]+name = "bs58"+version = "0.5.1"+source = "registry+https://github.com/rust-lang/crates.io-index"+checksum = "bf88ba1141d185c399bee5288d850d63b8369520c1eafc32a0430b5b6c287bf4"+dependencies = [+ "tinyvec",+]++[[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 = "bytes"+version = "1.12.1"+source = "registry+https://github.com/rust-lang/crates.io-index"+checksum = "fc652a48c352aef3ea3aed32080501cf3ef6ed5da78602a020c991775b0aff04"+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 = "camino"+version = "1.2.6"+source = "registry+https://github.com/rust-lang/crates.io-index"+checksum = "bbbad30e4b4c14a39e3cc8aed085a12a327257c316619c93581e017bc52be591"+dependencies = [+ "serde_core",+]++[[package]]+name = "cargo-platform"+version = "0.1.9"+source = "registry+https://github.com/rust-lang/crates.io-index"+checksum = "e35af189006b9c0f00a064685c727031e3ed2d8020f7ba284d78cc2671bd36ea"+dependencies = [+ "serde",+]++[[package]]+name = "cargo_metadata"+version = "0.19.2"+source = "registry+https://github.com/rust-lang/crates.io-index"+checksum = "dd5eb614ed4c27c5d706420e4320fbe3216ab31fa1c33cd8246ac36dae4479ba"+dependencies = [+ "camino",+ "cargo-platform",+ "semver",+ "serde",+ "serde_json",+ "thiserror 2.0.21",+]++[[package]]+name = "cargo_toml"+version = "1.0.1"+source = "registry+https://github.com/rust-lang/crates.io-index"+checksum = "82f4b26e751e711a5302649417f2da046dce6391b2ea30a4820f37462314f0b9"+dependencies = [+ "semver",+ "serde",+ "toml 1.2.1+spec-1.1.0",+]++[[package]]+name = "cc"+version = "1.11.2"+source = "registry+https://github.com/rust-lang/crates.io-index"+checksum = "33ef9e3e8154a45c7a95cff4c1299702106ad94062d7bb85fdc5d3a5afd91d45"+dependencies = [+ "find-msvc-tools",+ "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.14.0"+source = "registry+https://github.com/rust-lang/crates.io-index"+checksum = "a347dcabdae9c31b0825fd6a8bed285ec9c2acb89c47827126d52fa4f59cece3"+dependencies = [+ "fnv",+ "uuid",+ "web-time",+]++[[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 = "chrono"+version = "0.4.45"+source = "registry+https://github.com/rust-lang/crates.io-index"+checksum = "1aa79e62e7697b8e29b513a68abacf485adcd1fe8284a4316c5ae868e6633327"+dependencies = [+ "iana-time-zone",+ "num-traits",+ "serde",+ "windows-link",+]++[[package]]+name = "combine"+version = "4.6.9"+source = "registry+https://github.com/rust-lang/crates.io-index"+checksum = "4356eba6976435498d05a311ee9fc486da3bc81c200d3f0d7dd9703b41913f92"+dependencies = [+ "bytes",+ "memchr",+]++[[package]]+name = "cookie"+version = "0.18.2"+source = "registry+https://github.com/rust-lang/crates.io-index"+checksum = "1a373e3602691c3cdea496d2f0ee5935151e6168fe87739483c463db1b2f2f87"+dependencies = [+ "time",+ "version_check",+]++[[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.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",+ "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 = "cpufeatures"+version = "0.2.17"+source = "registry+https://github.com/rust-lang/crates.io-index"+checksum = "59ed5838eebb26a2bb2e58f6d5b5316989ae9d08bab10e0e6d103e656d1b0280"+dependencies = [+ "libc",+]++[[package]]+name = "crc32fast"+version = "1.5.5"+source = "registry+https://github.com/rust-lang/crates.io-index"+checksum = "2b929dd2a135771f40afabd1073f85eed59c800b7c61901e5c254270497dad64"+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-utils"+version = "0.8.23"+source = "registry+https://github.com/rust-lang/crates.io-index"+checksum = "a31eee39dddec8330830986fcd7625edb5a24ec90ea038215273bbc3adb08ac6"++[[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.37.0"+source = "registry+https://github.com/rust-lang/crates.io-index"+checksum = "8c9cdaae01d5ed7882b04d795e7f752f46ff52d2fa3b50a20d28c464510bba98"+dependencies = [+ "cssparser-macros",+ "dtoa-short",+ "itoa",+ "phf 0.13.1",+ "smallvec",+]++[[package]]+name = "cssparser"+version = "0.38.0"+source = "registry+https://github.com/rust-lang/crates.io-index"+checksum = "11119743ad110e8c1bdccd930d7f5c30c99e5fc76a7b63ec9807e84eef0c5f59"+dependencies = [+ "cssparser-macros",+ "dtoa-short",+ "itoa",+ "phf 0.14.0",+ "smallvec",+]++[[package]]+name = "cssparser-macros"+version = "0.7.1"+source = "registry+https://github.com/rust-lang/crates.io-index"+checksum = "d045de693cb712d0b22c6a64be5b953f67b3ce00ab5ad3dd5d8b441886ab8e1a"+dependencies = [+ "quote",+ "syn 3.0.10",+]++[[package]]+name = "ctor"+version = "1.0.13"+source = "registry+https://github.com/rust-lang/crates.io-index"+checksum = "914a755b7c2d4af2bdcff7ce1739e2db9a1b81a9b07123d8015786ae03c0980d"++[[package]]+name = "darling"+version = "0.24.1"+source = "registry+https://github.com/rust-lang/crates.io-index"+checksum = "ed17f5901b6630b993ca003def43f2f8ef4014fc13b047b57aad617ff32bc2ec"+dependencies = [+ "darling_core",+ "darling_macro",+]++[[package]]+name = "darling_core"+version = "0.24.1"+source = "registry+https://github.com/rust-lang/crates.io-index"+checksum = "6837e2cf7485aaae18f86181d2f0e9a7ed297a025e220aeabf63fdebd3a2ddff"+dependencies = [+ "ident_case",+ "proc-macro2",+ "quote",+ "strsim",+ "syn 3.0.10",+]++[[package]]+name = "darling_macro"+version = "0.24.1"+source = "registry+https://github.com/rust-lang/crates.io-index"+checksum = "2ac7135c3ef02b2f7833bbeb1be5ba7f966dcde8a87c6b87f65a778d71a02785"+dependencies = [+ "darling_core",+ "quote",+ "syn 3.0.10",+]++[[package]]+name = "dbus"+version = "0.9.12"+source = "registry+https://github.com/rust-lang/crates.io-index"+checksum = "3ab69f03cc8c4340c9c8e315114e1658e6775a9b16a04357973aa21cec22b32e"+dependencies = [+ "libc",+ "libdbus-sys",+ "windows-sys 0.61.2",+]++[[package]]+name = "deranged"+version = "0.5.9"+source = "registry+https://github.com/rust-lang/crates.io-index"+checksum = "9e9de72ce2ad1f90dc62fa25f0f430ef85eb4b0d8fa0be4f30373bc40a21d28e"+dependencies = [+ "serde_core",+]++[[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 = [+ "proc-macro2",+ "quote",+ "rustc_version",+ "syn 2.0.119",+]++[[package]]+name = "digest"+version = "0.10.7"+source = "registry+https://github.com/rust-lang/crates.io-index"+checksum = "9ed9a281f7bc9b7576e61468ba615a66a5c8cfdff42420a70aa82701a3b1e292"+dependencies = [+ "block-buffer",+ "crypto-common",+]++[[package]]+name = "dirs"+version = "7.0.0"+source = "registry+https://github.com/rust-lang/crates.io-index"+checksum = "8d57d423b3c82e89b9a24ca3091fee61f456a26edbd28d26c65906f4bc1dcd8f"+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 = "dom_query"+version = "0.28.0"+source = "registry+https://github.com/rust-lang/crates.io-index"+checksum = "fac5fca71e65e94cc718a6e2af65d6e0f9c6027751c2aa562fbb5087fda639bc"+dependencies = [+ "bit-set 0.8.0",+ "cssparser 0.37.0",+ "foldhash",+ "html5ever 0.39.0",+ "precomputed-hash",+ "selectors 0.38.0",+ "tendril",+]++[[package]]+name = "dom_query"+version = "0.29.0"+source = "registry+https://github.com/rust-lang/crates.io-index"+checksum = "498c698ac51127148a3984450e51fca7f01805a91d7a1f7a24af0a5f761e3385"+dependencies = [+ "bit-set 0.11.1",+ "cssparser 0.38.0",+ "foldhash",+ "html5ever 0.40.1",+ "precomputed-hash",+ "selectors 0.41.0",+ "tendril",+]++[[package]]+name = "dpi"+version = "0.1.2"+source = "registry+https://github.com/rust-lang/crates.io-index"+checksum = "d8b14ccef22fc6f5a8f4d7d768562a182c04ce9a3b3157b91390b52ddfdf1a76"+dependencies = [+ "serde",+]++[[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 = "dyn-clone"+version = "1.0.20"+source = "registry+https://github.com/rust-lang/crates.io-index"+checksum = "d0881ea181b1df73ff77ffaaf9c7544ecc11e82fba9b5f27b262a3c73a332555"++[[package]]+name = "embed-resource"+version = "3.0.12"+source = "registry+https://github.com/rust-lang/crates.io-index"+checksum = "6168487b5e7eb2673e6efe1200b1848016e436a6ca0b8031bf04bd9d493a249f"+dependencies = [+ "cc",+ "memchr",+ "rustc_version",+ "toml 1.2.1+spec-1.1.0",+ "vswhom",+ "winreg",+]++[[package]]+name = "embed_plist"+version = "1.2.2"+source = "registry+https://github.com/rust-lang/crates.io-index"+checksum = "4ef6b89e5b37196644d8796de5268852ff179b44e96276cf4290264843743bb7"++[[package]]+name = "equivalent"+version = "1.0.3"+source = "registry+https://github.com/rust-lang/crates.io-index"+checksum = "00d174d5400e5e8fd687ad1049e2f578285fa914201b1af7e8b112a4546bd826"++[[package]]+name = "erased-serde"+version = "0.4.11"+source = "registry+https://github.com/rust-lang/crates.io-index"+checksum = "1e59b668157f32d3459d4bd634861a06ffa2503a461ca5f0916b9f0252605e66"+dependencies = [+ "serde",+ "serde_core",+ "typeid",+]++[[package]]+name = "fastrand"+version = "2.5.0"+source = "registry+https://github.com/rust-lang/crates.io-index"+checksum = "da7c62ceae207dd37ea5b845da6a0696c799f85e97da1ab5b7910be3c1c80223"++[[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 = "foldhash"+version = "0.2.0"+source = "registry+https://github.com/rust-lang/crates.io-index"+checksum = "77ce24cb58228fbb8aa041425bb1050850ac19177686ea6e0f41a70416f56fdb"++[[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",+]++[[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.3.1"+source = "registry+https://github.com/rust-lang/crates.io-index"+checksum = "aa9a19cbb55df58761df49b23516a86d432839add4af60fc256da840f66ed35b"++[[package]]+name = "form_urlencoded"+version = "1.2.2"+source = "registry+https://github.com/rust-lang/crates.io-index"+checksum = "cb4cb245038516f5f85277875cdaa4f7d2c9a0fa0468de06ed190163b1581fcf"+dependencies = [+ "percent-encoding",+]++[[package]]+name = "futures-channel"+version = "0.3.34"+source = "registry+https://github.com/rust-lang/crates.io-index"+checksum = "b1f9e3d69d39e4862ffed03ed071a76f9a13ba1d9109d355b0f0aa6b15e393c4"+dependencies = [+ "futures-core",+]++[[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-core",+ "futures-io",+ "futures-macro",+ "futures-sink",+ "futures-task",+ "memchr",+ "pin-project-lite",+ "slab",+]++[[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"+version = "0.18.2"+source = "registry+https://github.com/rust-lang/crates.io-index"+checksum = "3caa00e14351bebbc8183b3c36690327eb77c49abc2268dd4bd36b856db3fbfe"+dependencies = [+ "gdk",+ "gdkx11-sys",+ "gio",+ "glib",+ "libc",+ "x11",+]++[[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 = "generic-array"+version = "0.14.7"+source = "registry+https://github.com/rust-lang/crates.io-index"+checksum = "85649ca51fd72272d7821adaf274ad91c288277713d9c18820d8499a7ff69e9a"+dependencies = [+ "typenum",+ "version_check",+]++[[package]]+name = "getrandom"+version = "0.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",+ "libc",+ "r-efi 6.0.0",+]++[[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 = "glob"+version = "0.3.4"+source = "registry+https://github.com/rust-lang/crates.io-index"+checksum = "e4eba85ea1d0a966a983acd07deee566e67395d2d96b6fb39e62b5a833f1eb0b"++[[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 = "hashbrown"+version = "0.12.3"+source = "registry+https://github.com/rust-lang/crates.io-index"+checksum = "8a9ee70c43aaf417c914396645a0fa852624801b24ebb7ae78fe8272889ac888"++[[package]]+name = "hashbrown"+version = "0.17.1"+source = "registry+https://github.com/rust-lang/crates.io-index"+checksum = "ed5909b6e89a2db4456e54cd5f673791d7eca6732202bbf2a9cc504fe2f9b84a"++[[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 = "hex"+version = "0.4.3"+source = "registry+https://github.com/rust-lang/crates.io-index"+checksum = "7f24254aa9a54b5c858eaee2f5bccdb46aaf0e486a595ed5fd8f86ba55232a70"++[[package]]+name = "html5ever"+version = "0.39.0"+source = "registry+https://github.com/rust-lang/crates.io-index"+checksum = "46a1761807faccc9a19e86944bbf40610014066306f96edcdedc2fb714bcb7b8"+dependencies = [+ "log",+ "markup5ever 0.39.0",+]++[[package]]+name = "html5ever"+version = "0.40.1"+source = "registry+https://github.com/rust-lang/crates.io-index"+checksum = "456a1a377e608e555d22ddab27ac0114bc7a7b4199078108e34c2aeae6c9b130"+dependencies = [+ "log",+ "markup5ever 0.40.0",+ "memchr",+]++[[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 = "hyper"+version = "1.12.0"+source = "registry+https://github.com/rust-lang/crates.io-index"+checksum = "2c3e324da4c95177d6291d4c8730197c0d1822f8a9766814a4a44fa5ab797c9c"+dependencies = [+ "atomic-waker",+ "bytes",+ "futures-core",+ "http",+ "http-body",+ "httparse",+ "itoa",+ "pin-project-lite",+ "smallvec",+ "tokio",+ "want",+]++[[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 = "iana-time-zone"+version = "0.1.65"+source = "registry+https://github.com/rust-lang/crates.io-index"+checksum = "e31bc9ad994ba00e440a8aa5c9ef0ec67d5cb5e5cb0cc7f8b744a35b389cc470"+dependencies = [+ "android_system_properties",+ "core-foundation-sys",+ "iana-time-zone-haiku",+ "js-sys",+ "log",+ "wasm-bindgen",+ "windows-core",+]++[[package]]+name = "iana-time-zone-haiku"+version = "0.1.2"+source = "registry+https://github.com/rust-lang/crates.io-index"+checksum = "f31827a206f56af32e590ba56d5d2d085f558508192593743f16b2306495269f"+dependencies = [+ "cc",+]++[[package]]+name = "ico"+version = "0.6.0"+source = "registry+https://github.com/rust-lang/crates.io-index"+checksum = "d75e94d66081e4d8dcd098bd8dc5254800fea14a26389b298410158d834de167"+dependencies = [+ "byteorder",+ "png",+]++[[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 = "indexmap"+version = "1.9.3"+source = "registry+https://github.com/rust-lang/crates.io-index"+checksum = "bd070e393353796e801d209ad339e89596eb4c8d430d18ede6a1cced8fafbd99"+dependencies = [+ "autocfg",+ "hashbrown 0.12.3",+ "serde",+]++[[package]]+name = "indexmap"+version = "2.14.2"+source = "registry+https://github.com/rust-lang/crates.io-index"+checksum = "cc4e190f5d26ca7051642629da2c52fc03bde85a03197c99408dcd291734c855"+dependencies = [+ "equivalent",+ "hashbrown 0.17.1",+ "serde",+ "serde_core",+]++[[package]]+name = "infer"+version = "0.22.0"+source = "registry+https://github.com/rust-lang/crates.io-index"+checksum = "f4200d433cbd5178df7797c9c2e75b348b728e39631cf14520d1e2fc424201f4"+dependencies = [+ "cfb",+]++[[package]]+name = "ipnet"+version = "2.12.2"+source = "registry+https://github.com/rust-lang/crates.io-index"+checksum = "791930b43c0d5973160d90a8f3894509f2b273430f5c5c73b668636d0287c5c0"++[[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 = "jiff"+version = "0.2.43"+source = "registry+https://github.com/rust-lang/crates.io-index"+checksum = "26699905cc795a23e3949585cc7ba3ee8ade090872a27e4316304a777297894a"+dependencies = [+ "jiff-core",+ "jiff-static",+ "jiff-tzdb-platform",+ "log",+ "portable-atomic",+ "portable-atomic-util",+ "serde_core",+ "windows-link",+]++[[package]]+name = "jiff-core"+version = "0.1.5"+source = "registry+https://github.com/rust-lang/crates.io-index"+checksum = "ffe6854081f5ac0a3046a9b223729ccd7a20b1e0e8277e44dc0660eedf67dfe2"+dependencies = [+ "log",+]++[[package]]+name = "jiff-static"+version = "0.2.43"+source = "registry+https://github.com/rust-lang/crates.io-index"+checksum = "4b4ff49b2887190c760b86207b55cdcaabbdecaf7a0660d68aa2ed6f652abf0a"+dependencies = [+ "jiff-core",+ "proc-macro2",+ "quote",+ "syn 2.0.119",+]++[[package]]+name = "jiff-tzdb"+version = "0.1.9"+source = "registry+https://github.com/rust-lang/crates.io-index"+checksum = "fa8377070c6bae868759445e5a77f66d84f0b72f3a054bfb00e6d038b8282da7"++[[package]]+name = "jiff-tzdb-platform"+version = "0.1.3"+source = "registry+https://github.com/rust-lang/crates.io-index"+checksum = "875a5a69ac2bab1a891711cf5eccbec1ce0341ea805560dcd90b7a2e925132e8"+dependencies = [+ "jiff-tzdb",+]++[[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-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 = "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 = "json-patch"+version = "4.2.0"+source = "registry+https://github.com/rust-lang/crates.io-index"+checksum = "7421438de105a0827e44fadd05377727847d717c80ce29a229f85fd04c427b72"+dependencies = [+ "jsonptr",+ "serde",+ "serde_json",+ "thiserror 2.0.21",+]++[[package]]+name = "jsonptr"+version = "0.7.1"+source = "registry+https://github.com/rust-lang/crates.io-index"+checksum = "a5a3cc660ba5d72bce0b3bb295bf20847ccbb40fd423f3f05b61273672e561fe"+dependencies = [+ "serde",+ "serde_json",+]++[[package]]+name = "keyboard-types"+version = "0.8.3"+source = "registry+https://github.com/rust-lang/crates.io-index"+checksum = "0fbe853b403ae61a04233030ae8a79d94975281ed9770a1f9e246732b534b28d"+dependencies = [+ "bitflags 2.13.2",+ "serde",+]++[[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",+ "once_cell",+]++[[package]]+name = "libc"+version = "0.2.191"+source = "registry+https://github.com/rust-lang/crates.io-index"+checksum = "65cd87c9a6d60536580b316ad985726104730a5151c99845f2490428ef91240a"++[[package]]+name = "libdbus-sys"+version = "0.2.7"+source = "registry+https://github.com/rust-lang/crates.io-index"+checksum = "328c4789d42200f1eeec05bd86c9c13c7f091d2ba9a6ea35acdf51f31bc0f043"+dependencies = [+ "pkg-config",+]++[[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 = "libredox"+version = "0.1.25"+source = "registry+https://github.com/rust-lang/crates.io-index"+checksum = "61ff90caf6077a803a240f62fdbe88645a890bbca49ef8174c3cb0404362171d"+dependencies = [+ "libc",+]++[[package]]+name = "litemap"+version = "0.8.3"+source = "registry+https://github.com/rust-lang/crates.io-index"+checksum = "47d9d19d1d6efa0109d2f65ff4c85cddd50bd572e5a00127ab10987290bcefae"++[[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 = "markup5ever"+version = "0.39.0"+source = "registry+https://github.com/rust-lang/crates.io-index"+checksum = "7122d987ec5f704ee56f6e5b41a7d93722e9aae27ae07cafa4036c4d3f9757de"+dependencies = [+ "log",+ "tendril",+ "web_atoms 0.2.6",+]++[[package]]+name = "markup5ever"+version = "0.40.0"+source = "registry+https://github.com/rust-lang/crates.io-index"+checksum = "0ab3dc68ac4a0f5719e560136778c1ee716e296030d75dbd4484e37e39e3a842"+dependencies = [+ "log",+ "tendril",+ "web_atoms 0.3.0",+]++[[package]]+name = "memchr"+version = "2.8.3"+source = "registry+https://github.com/rust-lang/crates.io-index"+checksum = "cf8baf1c55e62ffcace7a9f06f4bd9cd3f0c4beb022d3b367256b91b87513d98"++[[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 = "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",+ "windows-sys 0.61.2",+]++[[package]]+name = "muda"+version = "0.20.0"+source = "registry+https://github.com/rust-lang/crates.io-index"+checksum = "cca139e57da4383727f189e43e66e84fa372347027fc996f9f1a007ec0a37996"+dependencies = [+ "crossbeam-channel",+ "dpi",+ "gtk",+ "keyboard-types",+ "objc2",+ "objc2-app-kit",+ "objc2-core-foundation",+ "objc2-foundation",+ "once_cell",+ "png",+ "serde",+ "thiserror 2.0.21",+ "windows-sys 0.61.2",+]++[[package]]+name = "muelle"+version = "0.1.0"+dependencies = [+ "anyhow",+ "muelle-config",+ "muelle-core",+ "muelle-shell",+ "windows",+ "windows-core",+ "windows-numerics",+]++[[package]]+name = "muelle-config"+version = "0.1.0"+dependencies = [+ "serde",+ "serde_json",+ "thiserror 2.0.21",+]++[[package]]+name = "muelle-core"+version = "0.1.0"++[[package]]+name = "muelle-settings"+version = "0.1.0"+dependencies = [+ "muelle-config",+ "muelle-shell",+ "serde",+ "tauri",+ "tauri-build",+]++[[package]]+name = "muelle-shell"+version = "0.1.0"+dependencies = [+ "thiserror 2.0.21",+ "windows",+]++[[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",+ "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 = "num-conv"+version = "0.2.2"+source = "registry+https://github.com/rust-lang/crates.io-index"+checksum = "521739c6d2bac4aa25192232afe6841231376b2b26d4d9fae5ecf8ca5772e441"++[[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 = "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",+ "objc2-quartz-core",+]++[[package]]+name = "objc2-cloud-kit"+version = "0.3.2"+source = "registry+https://github.com/rust-lang/crates.io-index"+checksum = "73ad74d880bb43877038da939b7427bba67e9dd42004a18b809ba7d87cee241c"+dependencies = [+ "bitflags 2.13.2",+ "objc2",+ "objc2-foundation",+]++[[package]]+name = "objc2-core-data"+version = "0.3.2"+source = "registry+https://github.com/rust-lang/crates.io-index"+checksum = "0b402a653efbb5e82ce4df10683b6b28027616a2715e90009947d50b8dd298fa"+dependencies = [+ "objc2",+ "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",+ "dispatch2",+ "objc2",+ "objc2-core-foundation",+ "objc2-io-surface",+]++[[package]]+name = "objc2-core-image"+version = "0.3.2"+source = "registry+https://github.com/rust-lang/crates.io-index"+checksum = "e5d563b38d2b97209f8e861173de434bd0214cf020e3423a52624cd1d989f006"+dependencies = [+ "objc2",+ "objc2-foundation",+]++[[package]]+name = "objc2-core-location"+version = "0.3.2"+source = "registry+https://github.com/rust-lang/crates.io-index"+checksum = "ca347214e24bc973fc025fd0d36ebb179ff30536ed1f80252706db19ee452009"+dependencies = [+ "objc2",+ "objc2-foundation",+]++[[package]]+name = "objc2-core-text"+version = "0.3.2"+source = "registry+https://github.com/rust-lang/crates.io-index"+checksum = "0cde0dfb48d25d2b4862161a4d5fcc0e3c24367869ad306b0c9ec0073bfed92d"+dependencies = [+ "bitflags 2.13.2",+ "objc2",+ "objc2-core-foundation",+ "objc2-core-graphics",+]++[[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-io-surface"+version = "0.3.2"+source = "registry+https://github.com/rust-lang/crates.io-index"+checksum = "180788110936d59bab6bd83b6060ffdfffb3b922ba1396b312ae795e1de9d81d"+dependencies = [+ "bitflags 2.13.2",+ "objc2",+ "objc2-core-foundation",+]++[[package]]+name = "objc2-quartz-core"+version = "0.3.2"+source = "registry+https://github.com/rust-lang/crates.io-index"+checksum = "96c1358452b371bf9f104e21ec536d37a650eb10f7ee379fff67d2e08d537f1f"+dependencies = [+ "bitflags 2.13.2",+ "objc2",+ "objc2-core-foundation",+ "objc2-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",+ "block2",+ "objc2",+ "objc2-cloud-kit",+ "objc2-core-data",+ "objc2-core-foundation",+ "objc2-core-graphics",+ "objc2-core-image",+ "objc2-core-location",+ "objc2-core-text",+ "objc2-foundation",+ "objc2-quartz-core",+ "objc2-user-notifications",+]++[[package]]+name = "objc2-user-notifications"+version = "0.3.2"+source = "registry+https://github.com/rust-lang/crates.io-index"+checksum = "9df9128cbbfef73cda168416ccf7f837b62737d748333bfe9ab71c245d76613e"+dependencies = [+ "objc2",+ "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 = "once_cell"+version = "1.21.4"+source = "registry+https://github.com/rust-lang/crates.io-index"+checksum = "9f7c3e4beb33f85d45ae3e3a1792185706c8e16d043238c593331cc7cd313b50"++[[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",+]++[[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.13.1"+source = "registry+https://github.com/rust-lang/crates.io-index"+checksum = "c1562dc717473dbaa4c1f85a36410e03c047b2e7df7f45ee938fbef64ae7fadf"+dependencies = [+ "phf_macros 0.13.1",+ "phf_shared 0.13.1",+ "serde",+]++[[package]]+name = "phf"+version = "0.14.0"+source = "registry+https://github.com/rust-lang/crates.io-index"+checksum = "010378780309880b08997fae13be7834dba947d36393bd372f2b1556deb2a2f6"+dependencies = [+ "phf_macros 0.14.0",+ "phf_shared 0.14.0",+ "serde",+]++[[package]]+name = "phf_codegen"+version = "0.13.1"+source = "registry+https://github.com/rust-lang/crates.io-index"+checksum = "49aa7f9d80421bca176ca8dbfebe668cc7a2684708594ec9f3c0db0805d5d6e1"+dependencies = [+ "phf_generator 0.13.1",+ "phf_shared 0.13.1",+]++[[package]]+name = "phf_codegen"+version = "0.14.0"+source = "registry+https://github.com/rust-lang/crates.io-index"+checksum = "41b585a510fb76fdebead6897982ef2a03a21d8e6cbcca904999742a4afc6ffe"+dependencies = [+ "phf_generator 0.14.0",+ "phf_shared 0.14.0",+]++[[package]]+name = "phf_generator"+version = "0.13.1"+source = "registry+https://github.com/rust-lang/crates.io-index"+checksum = "135ace3a761e564ec88c03a77317a7c6b80bb7f7135ef2544dbe054243b89737"+dependencies = [+ "fastrand",+ "phf_shared 0.13.1",+]++[[package]]+name = "phf_generator"+version = "0.14.0"+source = "registry+https://github.com/rust-lang/crates.io-index"+checksum = "aeb62e0959d5a1bebc965f4d15d9e2b7cea002b6b0f5ba8cde6cc26738467100"+dependencies = [+ "fastrand",+ "phf_shared 0.14.0",+]++[[package]]+name = "phf_macros"+version = "0.13.1"+source = "registry+https://github.com/rust-lang/crates.io-index"+checksum = "812f032b54b1e759ccd5f8b6677695d5268c588701effba24601f6932f8269ef"+dependencies = [+ "phf_generator 0.13.1",+ "phf_shared 0.13.1",+ "proc-macro2",+ "quote",+ "syn 2.0.119",+]++[[package]]+name = "phf_macros"+version = "0.14.0"+source = "registry+https://github.com/rust-lang/crates.io-index"+checksum = "5fa8d0ca26d424d27630da600c6624696e7dec8bf7b3b492b383c5dc49e5e085"+dependencies = [+ "phf_generator 0.14.0",+ "phf_shared 0.14.0",+ "proc-macro2",+ "quote",+ "syn 2.0.119",+]++[[package]]+name = "phf_shared"+version = "0.13.1"+source = "registry+https://github.com/rust-lang/crates.io-index"+checksum = "e57fef6bc5981e38c2ce2d63bfa546861309f875b8a75f092d1d54ae2d64f266"+dependencies = [+ "siphasher",+]++[[package]]+name = "phf_shared"+version = "0.14.0"+source = "registry+https://github.com/rust-lang/crates.io-index"+checksum = "c6fd9027e2d9319be6349febd1db4e8d02aa544921200c9b777720ac34a3aa89"+dependencies = [+ "siphasher",+]++[[package]]+name = "pin-project-lite"+version = "0.2.17"+source = "registry+https://github.com/rust-lang/crates.io-index"+checksum = "a89322df9ebe1c1578d689c92318e070967d1042b512afbe49518723f4e6d5cd"++[[package]]+name = "pkg-config"+version = "0.3.34"+source = "registry+https://github.com/rust-lang/crates.io-index"+checksum = "f6b464fbc74e149a392436b17d523f769e057cb6877f6a5c4618bc6f11800548"++[[package]]+name = "plist"+version = "1.10.3"+source = "registry+https://github.com/rust-lang/crates.io-index"+checksum = "327a4cb2ad49dc48adfdc9da89e22c64d488b508c67a044d71ba729e4521a285"+dependencies = [+ "base64 0.23.1",+ "indexmap 2.14.2",+ "quick-xml",+ "serde",+ "time",+]++[[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 = "portable-atomic"+version = "1.15.0"+source = "registry+https://github.com/rust-lang/crates.io-index"+checksum = "05c8b63e8d9609db387f0324918f81d68fe27748f084ef092fb35954d0539a85"++[[package]]+name = "portable-atomic-util"+version = "0.2.8"+source = "registry+https://github.com/rust-lang/crates.io-index"+checksum = "10ab3eb7f3becc3a1cbc4f2c6f20267996cfc1a6467a873763411b136a122715"+dependencies = [+ "portable-atomic",+]++[[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 = "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.19+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-macro2"+version = "1.0.107"+source = "registry+https://github.com/rust-lang/crates.io-index"+checksum = "985e7ec9bb745e6ce6535b544d84d6cd6f7ad8bd711c398938ae983b91a766d9"+dependencies = [+ "unicode-ident",+]++[[package]]+name = "quick-xml"+version = "0.42.0"+source = "registry+https://github.com/rust-lang/crates.io-index"+checksum = "41b1177fdf999d2321d3fb46ff47159d9c1fb9ad66a4879f8c50a0b504615e9b"+dependencies = [+ "memchr",+]++[[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 = "raw-window-handle"+version = "0.6.2"+source = "registry+https://github.com/rust-lang/crates.io-index"+checksum = "20675572f6f24e9e76ef639bc5552774ed45f1c30e2951e1e99c59888861c539"++[[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 = "ref-cast"+version = "1.0.27"+source = "registry+https://github.com/rust-lang/crates.io-index"+checksum = "7e440fb4e4b4147295338efb76001ab9e4efc0e5839df2c47fc5ac2381d365c3"+dependencies = [+ "ref-cast-impl",+]++[[package]]+name = "ref-cast-impl"+version = "1.0.27"+source = "registry+https://github.com/rust-lang/crates.io-index"+checksum = "92ecd8964f8453721699a1ed72037b0db49ce2f5a5138486ee89bed6f67cdf3a"+dependencies = [+ "proc-macro2",+ "quote",+ "syn 3.0.10",+]++[[package]]+name = "regex"+version = "1.13.1"+source = "registry+https://github.com/rust-lang/crates.io-index"+checksum = "f020237b6c8eed93db2e2cb53c00c60a8e1bc73da7d073199a1180401450218d"+dependencies = [+ "aho-corasick",+ "memchr",+ "regex-automata",+ "regex-syntax",+]++[[package]]+name = "regex-automata"+version = "0.4.18"+source = "registry+https://github.com/rust-lang/crates.io-index"+checksum = "ad8553b9b26413251cbf30e620595c7a41b3887f03da04579c0e6b0d6a06b4b2"+dependencies = [+ "aho-corasick",+ "memchr",+ "regex-syntax",+]++[[package]]+name = "regex-syntax"+version = "0.8.11"+source = "registry+https://github.com/rust-lang/crates.io-index"+checksum = "d6f6ff9a378485b298a5286656da665ba74413d36db0979633275d2e708145d4"++[[package]]+name = "reqwest"+version = "0.13.5"+source = "registry+https://github.com/rust-lang/crates.io-index"+checksum = "16a1cfa75cc186dd73d5818e510e042e40927bccc9c236b061cea97e1eb08029"+dependencies = [+ "base64 0.23.1",+ "bytes",+ "futures-core",+ "futures-util",+ "http",+ "http-body",+ "http-body-util",+ "hyper",+ "hyper-util",+ "js-sys",+ "log",+ "percent-encoding",+ "pin-project-lite",+ "serde",+ "serde_json",+ "sync_wrapper",+ "tokio",+ "tokio-util",+ "tower",+ "tower-http",+ "tower-service",+ "url",+ "wasm-bindgen",+ "wasm-bindgen-futures",+ "wasm-streams",+ "web-sys",+]++[[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 = "rustversion"+version = "1.0.23"+source = "registry+https://github.com/rust-lang/crates.io-index"+checksum = "cf54715a573b99ac80df0bc206da022bcd442c974952c7b9720069370852e21f"++[[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 = "schemars"+version = "0.8.22"+source = "registry+https://github.com/rust-lang/crates.io-index"+checksum = "3fbf2ae1b8bc8e02df939598064d22402220cd5bbcca1c76f7d6a310974d5615"+dependencies = [+ "dyn-clone",+ "indexmap 1.9.3",+ "schemars_derive",+ "serde",+ "serde_json",+ "url",+ "uuid",+]++[[package]]+name = "schemars"+version = "0.9.0"+source = "registry+https://github.com/rust-lang/crates.io-index"+checksum = "4cd191f9397d57d581cddd31014772520aa448f65ef991055d7f61582c65165f"+dependencies = [+ "dyn-clone",+ "ref-cast",+ "serde",+ "serde_json",+]++[[package]]+name = "schemars"+version = "1.2.3"+source = "registry+https://github.com/rust-lang/crates.io-index"+checksum = "ab508826f74a77ca9d5aba6ff19b522583ee3eaf28a19384ff3d0e5835fadf6e"+dependencies = [+ "dyn-clone",+ "ref-cast",+ "serde",+ "serde_json",+]++[[package]]+name = "schemars_derive"+version = "0.8.22"+source = "registry+https://github.com/rust-lang/crates.io-index"+checksum = "32e265784ad618884abaea0600a9adf15393368d840e0222d101a072f3f7534d"+dependencies = [+ "proc-macro2",+ "quote",+ "serde_derive_internals",+ "syn 2.0.119",+]++[[package]]+name = "scopeguard"+version = "1.2.0"+source = "registry+https://github.com/rust-lang/crates.io-index"+checksum = "94143f37725109f92c262ed2cf5e59bce7498c01bcc1502d7b9afe439a4e9f49"++[[package]]+name = "selectors"+version = "0.38.0"+source = "registry+https://github.com/rust-lang/crates.io-index"+checksum = "8adfa1c298912827b8a28b223b3b874357397ae706e6190acd9bf28cee99114d"+dependencies = [+ "bitflags 2.13.2",+ "cssparser 0.37.0",+ "derive_more",+ "log",+ "new_debug_unreachable",+ "phf 0.13.1",+ "phf_codegen 0.13.1",+ "precomputed-hash",+ "rustc-hash",+ "servo_arc 0.4.3",+ "smallvec",+]++[[package]]+name = "selectors"+version = "0.41.0"+source = "registry+https://github.com/rust-lang/crates.io-index"+checksum = "8322aebea94a6cc288ff884e8a49bdbceef60206c400c6c46d22e62fc4fd91a6"+dependencies = [+ "bitflags 2.13.2",+ "cssparser 0.38.0",+ "derive_more",+ "log",+ "new_debug_unreachable",+ "precomputed-hash",+ "rustc-hash",+ "servo_arc 0.5.0",+ "smallvec",+]++[[package]]+name = "semver"+version = "1.0.28"+source = "registry+https://github.com/rust-lang/crates.io-index"+checksum = "8a7852d02fc848982e0c167ef163aaff9cd91dc640ba85e263cb1ce46fae51cd"+dependencies = [+ "serde",+ "serde_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-untagged"+version = "0.1.9"+source = "registry+https://github.com/rust-lang/crates.io-index"+checksum = "f9faf48a4a2d2693be24c6289dbe26552776eb7737074e6722891fadbe6c5058"+dependencies = [+ "erased-serde",+ "serde",+ "serde_core",+ "typeid",+]++[[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_derive_internals"+version = "0.29.1"+source = "registry+https://github.com/rust-lang/crates.io-index"+checksum = "18d26a20a969b9e3fdf2fc2d9f21eda6c40e2de84c9408bb5d3b05d499aae711"+dependencies = [+ "proc-macro2",+ "quote",+ "syn 2.0.119",+]++[[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_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_spanned"+version = "1.1.3"+source = "registry+https://github.com/rust-lang/crates.io-index"+checksum = "9c187e0a369471c550af028cba56d4f4fa2a489ad28151ae95a4d340a2a8b782"+dependencies = [+ "serde_core",+]++[[package]]+name = "serde_with"+version = "3.24.0"+source = "registry+https://github.com/rust-lang/crates.io-index"+checksum = "df9adc193c780ef8f159aee8b61e2d5801aaa555e6eb0947fe45530ec506296f"+dependencies = [+ "base64 0.23.1",+ "bs58",+ "chrono",+ "hex",+ "indexmap 1.9.3",+ "indexmap 2.14.2",+ "jiff",+ "schemars 0.9.0",+ "schemars 1.2.3",+ "serde_core",+ "serde_json",+ "serde_with_macros",+ "time",+]++[[package]]+name = "serde_with_macros"+version = "3.24.0"+source = "registry+https://github.com/rust-lang/crates.io-index"+checksum = "3e17bbc68e28663bbbb90df47e058aa7eda4fb445b89fe70457bb94fbccf6e49"+dependencies = [+ "darling",+ "proc-macro2",+ "quote",+ "syn 3.0.10",+]++[[package]]+name = "serialize-to-javascript"+version = "0.1.2"+source = "registry+https://github.com/rust-lang/crates.io-index"+checksum = "04f3666a07a197cdb77cdf306c32be9b7f598d7060d50cfd4d5aa04bfd92f6c5"+dependencies = [+ "serde",+ "serde_json",+ "serialize-to-javascript-impl",+]++[[package]]+name = "serialize-to-javascript-impl"+version = "0.1.2"+source = "registry+https://github.com/rust-lang/crates.io-index"+checksum = "772ee033c0916d670af7860b6e1ef7d658a4629a6d0b4c8c3e67f09b3765b75d"+dependencies = [+ "proc-macro2",+ "quote",+ "syn 2.0.119",+]++[[package]]+name = "servo_arc"+version = "0.4.3"+source = "registry+https://github.com/rust-lang/crates.io-index"+checksum = "170fb83ab34de17dc69aa7c67482b22218ddb85da56546f9bd6b929e32a05930"+dependencies = [+ "stable_deref_trait",+]++[[package]]+name = "servo_arc"+version = "0.5.0"+source = "registry+https://github.com/rust-lang/crates.io-index"+checksum = "b4eceb519ec34d8290aaf6e46f435102f2bfa63f22b05a144fb16ab266d3b198"+dependencies = [+ "stable_deref_trait",+]++[[package]]+name = "sha2"+version = "0.10.9"+source = "registry+https://github.com/rust-lang/crates.io-index"+checksum = "a7507d819769d01a365ab707794a4084392c824f54a7a6a7862f8c3d0892b283"+dependencies = [+ "cfg-if",+ "cpufeatures",+ "digest",+]++[[package]]+name = "shlex"+version = "2.0.1"+source = "registry+https://github.com/rust-lang/crates.io-index"+checksum = "f8fadd59c855ef2080decdef8ff161eb6661b86933c9d82e5ba29dc602a55aba"++[[package]]+name = "simd-adler32"+version = "0.3.10"+source = "registry+https://github.com/rust-lang/crates.io-index"+checksum = "3a219298ac11a56ea9a6d2120044824d6f01aeb034955e7af7bc16858527deea"++[[package]]+name = "siphasher"+version = "1.0.4"+source = "registry+https://github.com/rust-lang/crates.io-index"+checksum = "33f4fe9184a62d842c9ef383018f3306d8ba224fd9d836f56d7288308847c256"++[[package]]+name = "slab"+version = "0.4.12"+source = "registry+https://github.com/rust-lang/crates.io-index"+checksum = "0c790de23124f9ab44544d7ac05d60440adc586479ce501c1d6d7da3cd8c9cf5"++[[package]]+name = "smallvec"+version = "1.16.5"+source = "registry+https://github.com/rust-lang/crates.io-index"+checksum = "149309498a5f7334b12ddae0cad8aba81ce785fe91755068867e017cf98fee46"++[[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 = "softbuffer"+version = "0.4.8"+source = "registry+https://github.com/rust-lang/crates.io-index"+checksum = "aac18da81ebbf05109ab275b157c22a653bb3c12cf884450179942f81bcbf6c3"+dependencies = [+ "bytemuck",+ "js-sys",+ "ndk",+ "objc2",+ "objc2-core-foundation",+ "objc2-core-graphics",+ "objc2-foundation",+ "objc2-quartz-core",+ "raw-window-handle",+ "redox_syscall",+ "tracing",+ "wasm-bindgen",+ "web-sys",+ "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 = "spikes"+version = "0.0.0"+dependencies = [+ "muelle-shell",+ "windows",+ "windows-numerics",+]++[[package]]+name = "stable_deref_trait"+version = "1.2.1"+source = "registry+https://github.com/rust-lang/crates.io-index"+checksum = "6ce2be8dc25455e1f91df71bfa12ad37d7af1092ae736f3a6cd0e37bc7810596"++[[package]]+name = "static_vcruntime"+version = "3.0.0"+source = "registry+https://github.com/rust-lang/crates.io-index"+checksum = "ff7589a1859b09232522bb9edf076ca7fcf14ded96685d3fa629db73023ffbb7"++[[package]]+name = "string_cache"+version = "0.9.0"+source = "registry+https://github.com/rust-lang/crates.io-index"+checksum = "a18596f8c785a729f2819c0f6a7eae6ebeebdfffbfe4214ae6b087f690e31901"+dependencies = [+ "new_debug_unreachable",+ "parking_lot",+ "phf_shared 0.13.1",+ "precomputed-hash",+]++[[package]]+name = "string_cache"+version = "0.11.0"+source = "registry+https://github.com/rust-lang/crates.io-index"+checksum = "ffa8a5dbe8b3f0bbe29d4c3225daafaeead63afdc1b65fc4c01a1384166038e6"+dependencies = [+ "new_debug_unreachable",+ "parking_lot",+ "phf_shared 0.14.0",+ "precomputed-hash",+]++[[package]]+name = "string_cache_codegen"+version = "0.6.1"+source = "registry+https://github.com/rust-lang/crates.io-index"+checksum = "585635e46db231059f76c5849798146164652513eb9e8ab2685939dd90f29b69"+dependencies = [+ "phf_generator 0.13.1",+ "phf_shared 0.13.1",+ "proc-macro2",+ "quote",+]++[[package]]+name = "string_cache_codegen"+version = "0.11.2"+source = "registry+https://github.com/rust-lang/crates.io-index"+checksum = "928dcdf75e47626b3617a976ec205d9f057584c371c1f23b782129268d0e6edc"+dependencies = [+ "phf_generator 0.14.0",+ "phf_shared 0.14.0",+ "proc-macro2",+ "quote",+]++[[package]]+name = "strsim"+version = "0.11.1"+source = "registry+https://github.com/rust-lang/crates.io-index"+checksum = "7da8b5736845d9f2fcb837ea5d9e2628564b3b043a70948a3f0b778838c5fb4f"++[[package]]+name = "swift-rs"+version = "1.0.9"+source = "registry+https://github.com/rust-lang/crates.io-index"+checksum = "cefd87076fd385308ee4aff597256c902f1fbb4d031de1558efc12f8ffefadd9"+dependencies = [+ "base64 0.21.7",+ "serde",+ "serde_json",+]++[[package]]+name = "syn"+version = "1.0.109"+source = "registry+https://github.com/rust-lang/crates.io-index"+checksum = "72b64191b275b66ffe2469e8af2c1cfe3bafa67b529ead792a6d0160888b4237"+dependencies = [+ "proc-macro2",+ "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 0.8.2",+ "version-compare",+]++[[package]]+name = "tao"+version = "0.37.2"+source = "registry+https://github.com/rust-lang/crates.io-index"+checksum = "d5777b06fe6435126ae8d816eba269e050e1e10d302cf5461e9c49eccabc3548"+dependencies = [+ "bitflags 2.13.2",+ "block2",+ "core-foundation",+ "core-graphics",+ "crossbeam-channel",+ "dbus",+ "dispatch2",+ "dlopen2",+ "dpi",+ "gdkwayland-sys",+ "gdkx11-sys",+ "gtk",+ "jni",+ "libc",+ "log",+ "ndk",+ "ndk-context",+ "ndk-sys",+ "objc2",+ "objc2-app-kit",+ "objc2-foundation",+ "objc2-ui-kit",+ "parking_lot",+ "percent-encoding",+ "raw-window-handle",+ "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-lexicon"+version = "0.12.16"+source = "registry+https://github.com/rust-lang/crates.io-index"+checksum = "61c41af27dd6d1e27b1b16b489db798443478cef1f06a660c96db617ba5de3b1"++[[package]]+name = "tauri"+version = "2.12.5"+source = "registry+https://github.com/rust-lang/crates.io-index"+checksum = "5fb0244332cfb9cee7e2a568bf5da29a36ed8fdbd717f6f47a66b6b7b358c072"+dependencies = [+ "anyhow",+ "bytes",+ "cookie",+ "dirs",+ "dunce",+ "embed_plist",+ "getrandom 0.3.4",+ "glob",+ "gtk",+ "heck 0.5.0",+ "http",+ "jni",+ "libc",+ "log",+ "mime",+ "muda",+ "objc2",+ "objc2-app-kit",+ "objc2-foundation",+ "objc2-ui-kit",+ "objc2-web-kit",+ "percent-encoding",+ "plist",+ "raw-window-handle",+ "reqwest",+ "serde",+ "serde_json",+ "serde_repr",+ "serialize-to-javascript",+ "swift-rs",+ "tauri-build",+ "tauri-macros",+ "tauri-runtime",+ "tauri-runtime-wry",+ "tauri-utils",+ "thiserror 2.0.21",+ "tokio",+ "tray-icon",+ "url",+ "webkit2gtk",+ "webview2-com",+ "window-vibrancy",+ "windows",+]++[[package]]+name = "tauri-build"+version = "2.7.4"+source = "registry+https://github.com/rust-lang/crates.io-index"+checksum = "adddb0e648752aaac5da9c3c3c6a68e1e87cab55e3b757b18a9441ef8c3ac614"+dependencies = [+ "anyhow",+ "cargo_toml",+ "dirs",+ "glob",+ "heck 0.5.0",+ "json-patch",+ "schemars 0.8.22",+ "semver",+ "serde",+ "serde_json",+ "static_vcruntime",+ "strsim",+ "tauri-utils",+ "tauri-winres",+ "walkdir",+]++[[package]]+name = "tauri-codegen"+version = "2.7.4"+source = "registry+https://github.com/rust-lang/crates.io-index"+checksum = "fb37631cf71dab5e8ab55e1bdd701e18a52653d90b78e71d0e5598b1e0a61316"+dependencies = [+ "base64 0.23.1",+ "brotli",+ "ico",+ "json-patch",+ "plist",+ "png",+ "proc-macro2",+ "quote",+ "semver",+ "serde",+ "serde_json",+ "sha2",+ "syn 2.0.119",+ "tauri-utils",+ "thiserror 2.0.21",+ "time",+ "url",+ "uuid",+ "walkdir",+]++[[package]]+name = "tauri-macros"+version = "2.7.4"+source = "registry+https://github.com/rust-lang/crates.io-index"+checksum = "0cc38db58854c10fb5f91a887ed8bf82d3239bb92b5d8db86eda09e96d9963d1"+dependencies = [+ "heck 0.5.0",+ "proc-macro2",+ "quote",+ "syn 2.0.119",+ "tauri-codegen",+ "tauri-utils",+]++[[package]]+name = "tauri-runtime"+version = "2.12.2"+source = "registry+https://github.com/rust-lang/crates.io-index"+checksum = "7c55766d99cea69055904d1735b93c2049302b2e09effd462120deb5581d78e9"+dependencies = [+ "cookie",+ "dpi",+ "gtk",+ "http",+ "jni",+ "objc2",+ "objc2-ui-kit",+ "objc2-web-kit",+ "raw-window-handle",+ "serde",+ "serde_json",+ "tauri-utils",+ "thiserror 2.0.21",+ "url",+ "webkit2gtk",+ "webview2-com",+ "windows",+]++[[package]]+name = "tauri-runtime-wry"+version = "2.12.3"+source = "registry+https://github.com/rust-lang/crates.io-index"+checksum = "e1aa9d8b7a120f879f44fdc1053f7b7dbf416bf0bbc6a72b714dec46b782b52f"+dependencies = [+ "gtk",+ "http",+ "jni",+ "log",+ "objc2",+ "objc2-app-kit",+ "percent-encoding",+ "raw-window-handle",+ "softbuffer",+ "tao",+ "tauri-runtime",+ "tauri-utils",+ "url",+ "webkit2gtk",+ "webview2-com",+ "windows",+ "wry",+]++[[package]]+name = "tauri-utils"+version = "2.10.2"+source = "registry+https://github.com/rust-lang/crates.io-index"+checksum = "362ab21cd4cc713f2a02b1a9b5688198b1541cfb6907c4281e9190e0f0ef4aa3"+dependencies = [+ "anyhow",+ "brotli",+ "cargo_metadata",+ "ctor",+ "dom_query 0.28.0",+ "dunce",+ "glob",+ "http",+ "infer",+ "json-patch",+ "log",+ "memchr",+ "phf 0.13.1",+ "plist",+ "proc-macro2",+ "quote",+ "regex",+ "schemars 0.8.22",+ "semver",+ "serde",+ "serde-untagged",+ "serde_json",+ "serde_with",+ "swift-rs",+ "thiserror 2.0.21",+ "toml 1.2.1+spec-1.1.0",+ "url",+ "urlpattern",+ "uuid",+ "walkdir",+]++[[package]]+name = "tauri-winres"+version = "0.3.7"+source = "registry+https://github.com/rust-lang/crates.io-index"+checksum = "c52bb6904475a6ca662f15ef787f18ade61d5740a1ee12c45d3b748efdb6f796"+dependencies = [+ "dunce",+ "embed-resource",+ "toml 1.2.1+spec-1.1.0",+]++[[package]]+name = "tendril"+version = "0.5.1"+source = "registry+https://github.com/rust-lang/crates.io-index"+checksum = "5fed54709c5b3a53d09bb1c113ea4f5ceafd1e772ddcb0030a82e1d56c087b08"+dependencies = [+ "new_debug_unreachable",+]++[[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 = "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",+ "windows-sys 0.61.2",+]++[[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-sink",+ "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 0.6.9",+ "toml_datetime 0.6.3",+ "toml_edit 0.20.2",+]++[[package]]+name = "toml"+version = "1.2.1+spec-1.1.0"+source = "registry+https://github.com/rust-lang/crates.io-index"+checksum = "d5755c51863cdac711f1956baf8eb9588e060755f7d3c4c979e70ea1e1f32cd7"+dependencies = [+ "indexmap 2.14.2",+ "serde_core",+ "serde_spanned 1.1.3",+ "toml_datetime 1.1.3+spec-1.1.0",+ "toml_parser",+ "toml_writer",+ "winnow 1.0.5",+]++[[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 2.14.2",+ "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 2.14.2",+ "serde",+ "serde_spanned 0.6.9",+ "toml_datetime 0.6.3",+ "winnow 0.5.40",+]++[[package]]+name = "toml_edit"+version = "0.25.19+spec-1.1.0"+source = "registry+https://github.com/rust-lang/crates.io-index"+checksum = "dd43688c4858d7264ae1cf9a9f874a67c3feb74a883b1cd7bebd6a4ea8307218"+dependencies = [+ "indexmap 2.14.2",+ "toml_datetime 1.1.3+spec-1.1.0",+ "toml_parser",+ "winnow 1.0.5",+]++[[package]]+name = "toml_parser"+version = "1.1.5+spec-1.1.0"+source = "registry+https://github.com/rust-lang/crates.io-index"+checksum = "baa693a8032d7e1cada7d0041e96126df243179ff061456783ac7f12bda4744c"+dependencies = [+ "winnow 1.0.5",+]++[[package]]+name = "toml_writer"+version = "1.2.0+spec-1.1.0"+source = "registry+https://github.com/rust-lang/crates.io-index"+checksum = "009dbb7700f11c55ef83aebbe4c0e9cf1f1ac0844bd8d6f00dc38f302026e13a"++[[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-core",+]++[[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 = "tray-icon"+version = "0.25.1"+source = "registry+https://github.com/rust-lang/crates.io-index"+checksum = "b2b9c52859a94554803ccd4a24b98f74148ebc73b90676d783f3490b1bff9d72"+dependencies = [+ "crossbeam-channel",+ "dirs",+ "libappindicator",+ "muda",+ "objc2",+ "objc2-app-kit",+ "objc2-core-foundation",+ "objc2-core-graphics",+ "objc2-foundation",+ "once_cell",+ "png",+ "serde",+ "thiserror 2.0.21",+ "windows-sys 0.61.2",+]++[[package]]+name = "try-lock"+version = "0.2.5"+source = "registry+https://github.com/rust-lang/crates.io-index"+checksum = "e421abadd41a4225275504ea4d6566923418b7f05506fbc9c0fe86ba7396114b"++[[package]]+name = "typeid"+version = "1.0.3"+source = "registry+https://github.com/rust-lang/crates.io-index"+checksum = "bc7d623258602320d5c55d1bc22793b57daff0ec7efc270ea7d55ce1d5f5471c"++[[package]]+name = "typenum"+version = "1.20.1"+source = "registry+https://github.com/rust-lang/crates.io-index"+checksum = "b6f5e870be6c3b371b77fe0ee0bafb859fa4964b4404c27de1d380043c4dda20"++[[package]]+name = "unicode-ident"+version = "1.0.27"+source = "registry+https://github.com/rust-lang/crates.io-index"+checksum = "a2c754d6c33795a1c324727428e5a7dedb5b06195f9890bdbcba760d3e246563"++[[package]]+name = "unicode-segmentation"+version = "1.13.3"+source = "registry+https://github.com/rust-lang/crates.io-index"+checksum = "c6f5d3c3b1bf09027a88a6bc961fc00497d651009560b5463668dc81b0fa87a8"++[[package]]+name = "url"+version = "2.5.8"+source = "registry+https://github.com/rust-lang/crates.io-index"+checksum = "ff67a8a4397373c3ef660812acab3268222035010ab8680ec4215f38ba3d0eed"+dependencies = [+ "form_urlencoded",+ "idna",+ "percent-encoding",+ "serde",+ "serde_derive",+]++[[package]]+name = "urlpattern"+version = "0.6.0"+source = "registry+https://github.com/rust-lang/crates.io-index"+checksum = "df16f50ef4cc145211879a3867ba757076b25dfee812040dcb0658bd9ae7904b"+dependencies = [+ "icu_properties",+ "regex",+ "serde",+ "url",+]++[[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.2"+source = "registry+https://github.com/rust-lang/crates.io-index"+checksum = "bed99139f7dac9b5cfe5f17be4d66dc7079a34dee1d74bcc77217119240e267c"+dependencies = [+ "getrandom 0.4.3",+ "js-sys",+ "serde_core",+ "wasm-bindgen",+]++[[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 = "vswhom"+version = "0.1.0"+source = "registry+https://github.com/rust-lang/crates.io-index"+checksum = "be979b7f07507105799e854203b470ff7c78a1639e330a58f183b5fea574608b"+dependencies = [+ "libc",+ "vswhom-sys",+]++[[package]]+name = "vswhom-sys"+version = "0.1.3"+source = "registry+https://github.com/rust-lang/crates.io-index"+checksum = "fb067e4cbd1ff067d1df46c9194b5de0e98efd2810bbc95c5d5e5f25a3231150"+dependencies = [+ "cc",+ "libc",+]++[[package]]+name = "walkdir"+version = "2.5.0"+source = "registry+https://github.com/rust-lang/crates.io-index"+checksum = "29790946404f91d9c5d06f9874efddea1dc06c5efe94541a7d6863108e3a5e4b"+dependencies = [+ "same-file",+ "winapi-util",+]++[[package]]+name = "want"+version = "0.3.2"+source = "registry+https://github.com/rust-lang/crates.io-index"+checksum = "ec4cdd0dd910afe868b7ef477227d8d538b46b3075031afee8a9f2acb0a2ed0b"+dependencies = [+ "try-lock",+]++[[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.5.0"+source = "registry+https://github.com/rust-lang/crates.io-index"+checksum = "9d1ec4f6517c9e11ae630e200b2b65d193279042e28edd4a2cda233e46670bbb"+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 = "web_atoms"+version = "0.2.6"+source = "registry+https://github.com/rust-lang/crates.io-index"+checksum = "ba8b815c1b593dc0baf78dd0f4fc8fdb2de53198fb1163738093e9a311c33fb3"+dependencies = [+ "phf 0.13.1",+ "phf_codegen 0.13.1",+ "string_cache 0.9.0",+ "string_cache_codegen 0.6.1",+]++[[package]]+name = "web_atoms"+version = "0.3.0"+source = "registry+https://github.com/rust-lang/crates.io-index"+checksum = "7572660c8890448ba236b7376f27e389c6a7e1c70195622faced601f855c0ada"+dependencies = [+ "phf 0.14.0",+ "phf_codegen 0.14.0",+ "string_cache 0.11.0",+ "string_cache_codegen 0.11.2",+]++[[package]]+name = "webkit2gtk"+version = "2.0.2"+source = "registry+https://github.com/rust-lang/crates.io-index"+checksum = "a1027150013530fb2eaf806408df88461ae4815a45c541c8975e61d6f2fc4793"+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.2"+source = "registry+https://github.com/rust-lang/crates.io-index"+checksum = "916a5f65c2ef0dfe12fff695960a2ec3d4565359fdbb2e9943c974e06c734ea5"+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 = "webview2-com"+version = "0.39.1"+source = "registry+https://github.com/rust-lang/crates.io-index"+checksum = "3f89fca7a704cee10dcb3654c1dbb8941d1783132f1917358af75bec37a7d7e6"+dependencies = [+ "webview2-com-macros",+ "webview2-com-sys",+ "windows",+ "windows-core",+]++[[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.39.1"+source = "registry+https://github.com/rust-lang/crates.io-index"+checksum = "b3a07132775117d6065853d9d1178157b8c90e228de47129d6bce2c7edebedfb"+dependencies = [+ "thiserror 2.0.21",+ "windows",+ "windows-core",+]++[[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 = "window-vibrancy"+version = "0.8.1"+source = "registry+https://github.com/rust-lang/crates.io-index"+checksum = "111e51caca442cafd9bab396628ac4d814880eaea4e63dfd76a12e9f342b5580"+dependencies = [+ "objc2",+ "objc2-app-kit",+ "objc2-core-foundation",+ "objc2-foundation",+ "objc2-quartz-core",+ "raw-window-handle",+ "windows-sys 0.61.2",+ "windows-version",+]++[[package]]+name = "windows"+version = "0.62.2"+source = "registry+https://github.com/rust-lang/crates.io-index"+checksum = "527fadee13e0c05939a6a05d5bd6eec6cd2e3dbd648b9f8e447c6518133d8580"+dependencies = [+ "windows-collections",+ "windows-core",+ "windows-future",+ "windows-numerics",+]++[[package]]+name = "windows-collections"+version = "0.3.2"+source = "registry+https://github.com/rust-lang/crates.io-index"+checksum = "23b2d95af1a8a14a3c7367e1ed4fc9c20e0a26e79551b1454d72583c97cc6610"+dependencies = [+ "windows-core",+]++[[package]]+name = "windows-core"+version = "0.62.2"+source = "registry+https://github.com/rust-lang/crates.io-index"+checksum = "b8e83a14d34d0623b51dce9581199302a221863196a1dde71a7663a4c2be9deb"+dependencies = [+ "windows-implement",+ "windows-interface",+ "windows-link",+ "windows-result",+ "windows-strings",+]++[[package]]+name = "windows-future"+version = "0.3.2"+source = "registry+https://github.com/rust-lang/crates.io-index"+checksum = "e1d6f90251fe18a279739e78025bd6ddc52a7e22f921070ccdc67dde84c605cb"+dependencies = [+ "windows-core",+ "windows-link",+ "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.2.1"+source = "registry+https://github.com/rust-lang/crates.io-index"+checksum = "f0805222e57f7521d6a62e36fa9163bc891acd422f971defe97d64e70d0a4fe5"++[[package]]+name = "windows-numerics"+version = "0.3.1"+source = "registry+https://github.com/rust-lang/crates.io-index"+checksum = "6e2e40844ac143cdb44aead537bbf727de9b044e107a0f1220392177d15b0f26"+dependencies = [+ "windows-core",+ "windows-link",+]++[[package]]+name = "windows-result"+version = "0.4.1"+source = "registry+https://github.com/rust-lang/crates.io-index"+checksum = "7781fa89eaf60850ac3d2da7af8e5242a5ea78d1a11c49bf2910bb5a73853eb5"+dependencies = [+ "windows-link",+]++[[package]]+name = "windows-strings"+version = "0.5.1"+source = "registry+https://github.com/rust-lang/crates.io-index"+checksum = "7837d08f69c77cf6b07689544538e017c1bfcf57e34b4c0ff58e6c2cd3b37091"+dependencies = [+ "windows-link",+]++[[package]]+name = "windows-sys"+version = "0.45.0"+source = "registry+https://github.com/rust-lang/crates.io-index"+checksum = "75283be5efb2831d37ea142365f009c02ec203cd29a3ebecbc093d52315b66d0"+dependencies = [+ "windows-targets",+]++[[package]]+name = "windows-sys"+version = "0.61.2"+source = "registry+https://github.com/rust-lang/crates.io-index"+checksum = "ae137229bcbd6cdf0f7b80a31df61766145077ddf49416a728b02cb3921ff3fc"+dependencies = [+ "windows-link",+]++[[package]]+name = "windows-targets"+version = "0.42.2"+source = "registry+https://github.com/rust-lang/crates.io-index"+checksum = "8e5180c00cd44c9b1c88adb3693291f1cd93605ded80c250a75d472756b4d071"+dependencies = [+ "windows_aarch64_gnullvm",+ "windows_aarch64_msvc",+ "windows_i686_gnu",+ "windows_i686_msvc",+ "windows_x86_64_gnu",+ "windows_x86_64_gnullvm",+ "windows_x86_64_msvc",+]++[[package]]+name = "windows-threading"+version = "0.2.1"+source = "registry+https://github.com/rust-lang/crates.io-index"+checksum = "3949bd5b99cafdf1c7ca86b43ca564028dfe27d66958f2470940f73d86d75b37"+dependencies = [+ "windows-link",+]++[[package]]+name = "windows-version"+version = "0.1.7"+source = "registry+https://github.com/rust-lang/crates.io-index"+checksum = "e4060a1da109b9d0326b7262c8e12c84df67cc0dbc9e33cf49e01ccc2eb63631"+dependencies = [+ "windows-link",+]++[[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_msvc"+version = "0.42.2"+source = "registry+https://github.com/rust-lang/crates.io-index"+checksum = "e08e8864a60f06ef0d0ff4ba04124db8b0fb3be5776a5cd47641e942e58c4d43"++[[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_msvc"+version = "0.42.2"+source = "registry+https://github.com/rust-lang/crates.io-index"+checksum = "44d840b6ec649f480a41c8d80f9c65108b92d89345dd94027bfe06ac444d1060"++[[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_gnullvm"+version = "0.42.2"+source = "registry+https://github.com/rust-lang/crates.io-index"+checksum = "26d41b46a36d453748aedef1486d5c7a85db22e56aff34643984ea85514e94a3"++[[package]]+name = "windows_x86_64_msvc"+version = "0.42.2"+source = "registry+https://github.com/rust-lang/crates.io-index"+checksum = "9aec5da331524158c6d1a4ac0ab1541149c0b9505fde06423b02f5ef0106b9f0"++[[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 = "1.0.5"+source = "registry+https://github.com/rust-lang/crates.io-index"+checksum = "8c3b93199df0ab874cdf0c6a94f0a0dc3423fe41f1cafb62b8bd7b1deb277aef"+dependencies = [+ "memchr",+]++[[package]]+name = "winreg"+version = "0.56.0"+source = "registry+https://github.com/rust-lang/crates.io-index"+checksum = "7d6f32a0ff4a9f6f01231eb2059cc85479330739333e0e58cadf03b6af2cca10"+dependencies = [+ "cfg-if",+ "windows-sys 0.61.2",+]++[[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.57.2"+source = "registry+https://github.com/rust-lang/crates.io-index"+checksum = "a490119196d02a51d0871df7b9119a1f3e46d75b7e90053a801454d5c6b3491c"+dependencies = [+ "base64 0.23.1",+ "block2",+ "cookie",+ "crossbeam-channel",+ "dirs",+ "dom_query 0.29.0",+ "dpi",+ "dunce",+ "gdkx11",+ "gtk",+ "http",+ "javascriptcore-rs",+ "jni",+ "libc",+ "ndk",+ "objc2",+ "objc2-app-kit",+ "objc2-core-foundation",+ "objc2-foundation",+ "objc2-ui-kit",+ "objc2-web-kit",+ "percent-encoding",+ "raw-window-handle",+ "sha2",+ "soup3",+ "tao-macros",+ "thiserror 2.0.21",+ "url",+ "webkit2gtk",+ "webkit2gtk-sys",+ "webview2-com",+ "windows",+ "windows-core",+ "windows-version",+ "x11-dl",+]++[[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 = "yoke"+version = "0.8.4"+source = "registry+https://github.com/rust-lang/crates.io-index"+checksum = "417ef3fcf6c300b7dbd25c85531a746931c02ad536f3cf4786ed1e88223340b3"+dependencies = [+ "stable_deref_trait",+ "yoke-derive",+ "zerofrom",+]++[[package]]+name = "yoke-derive"+version = "0.8.4"+source = "registry+https://github.com/rust-lang/crates.io-index"+checksum = "ec8ebde2db3681e8c9980cc27822030e68752690ddfa9473e739aeb4dbde6d71"+dependencies = [+ "proc-macro2",+ "quote",+ "syn 3.0.10",+ "synstructure",+]++[[package]]+name = "zerofrom"+version = "0.1.8"+source = "registry+https://github.com/rust-lang/crates.io-index"+checksum = "0ec05a11813ea801ff6d75110ad09cd0824ddba17dfe17128ea0d5f68e6c5272"+dependencies = [+ "zerofrom-derive",+]++[[package]]+name = "zerofrom-derive"+version = "0.1.8"+source = "registry+https://github.com/rust-lang/crates.io-index"+checksum = "f75b4683f6c7f45248d4d64056a24298c6281e0993356d7d1b4a1a962ef10d4a"+dependencies = [+ "proc-macro2",+ "quote",+ "syn 3.0.10",+ "synstructure",+]++[[package]]+name = "zerotrie"+version = "0.2.5"+source = "registry+https://github.com/rust-lang/crates.io-index"+checksum = "4ea269c3bd32f0a32c321907a2ae912ba6f4649bb0fc764a15627e99a7095a3f"+dependencies = [+ "displaydoc",+ "yoke",+ "zerofrom",+]++[[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.8"+source = "registry+https://github.com/rust-lang/crates.io-index"+checksum = "b268e58e7c693d7c271f93ffc4ba3b380412554231c85bf61ca7af91042a4112"++[[package]]+name = "zmij"+version = "1.0.23"+source = "registry+https://github.com/rust-lang/crates.io-index"+checksum = "29666d0abbfad1e3dc4dcf6144730dd3a3ab225bbbdac83319345b1b44ccfc1b"diff --git a/Cargo.toml b/Cargo.tomlnew file mode 100644index 0000000..56041b8--- /dev/null+++ b/Cargo.toml@@ -0,0 +1,31 @@+[workspace]+resolver = "3"+members = ["crates/*", "apps/dock", "apps/settings/src-tauri", "spikes"]++[workspace.package]+version = "0.1.0"+edition = "2024"+license = "MIT"++[workspace.dependencies]+anyhow = "1"+serde = { version = "1", features = ["derive"] }+thiserror = "2"+windows = "0.62"+windows-core = "0.62"+windows-numerics = "0.3"+muelle-config = { path = "crates/muelle-config" }+muelle-core = { path = "crates/muelle-core" }+muelle-shell = { path = "crates/muelle-shell" }++[workspace.lints.clippy]+perf = { level = "deny", priority = -1 }+unwrap_used = "warn"+expect_used = "warn"++[profile.release]+lto = true+codegen-units = 1+strip = true+# Un fallo cierra el proceso sin más: el guardián devuelve la barra de tareas.+panic = "abort"diff --git a/apps/dock/Cargo.toml b/apps/dock/Cargo.tomlnew file mode 100644index 0000000..1a15f9e--- /dev/null+++ b/apps/dock/Cargo.toml@@ -0,0 +1,49 @@+[package]+name = "muelle"+version.workspace = true+edition.workspace = true+license.workspace = true++[lints]+workspace = true++[dependencies]+anyhow.workspace = true+muelle-config.workspace = true+muelle-core.workspace = true+muelle-shell.workspace = true+windows-core.workspace = true+windows-numerics.workspace = true+windows = { workspace = true, features = [+ "Foundation",+ "Graphics",+ "Graphics_DirectX",+ "System",+ "UI",+ "UI_Composition",+ "UI_Composition_Desktop",+ "Win32_Foundation",+ "Win32_Graphics_Direct2D",+ "Win32_Graphics_Direct2D_Common",+ "Win32_Graphics_Direct3D",+ "Win32_Graphics_Direct3D11",+ "Win32_Graphics_DirectWrite",+ "Win32_Graphics_Dwm",+ "Win32_Graphics_Dxgi",+ "Win32_Graphics_Dxgi_Common",+ "Win32_Graphics_Gdi",+ "Win32_Security",+ "Win32_System_Com",+ "Win32_System_Console",+ "Win32_System_LibraryLoader",+ "Win32_System_Threading",+ "Win32_System_WinRT",+ "Win32_System_WinRT_Composition",+ "Win32_System_Ole",+ "Win32_System_SystemServices",+ "Win32_UI_Shell",+ "Win32_UI_Accessibility",+ "Win32_UI_HiDpi",+ "Win32_UI_Input_KeyboardAndMouse",+ "Win32_UI_WindowsAndMessaging",+] }diff --git a/apps/dock/src/app.rs b/apps/dock/src/app.rsnew file mode 100644index 0000000..e13e840--- /dev/null+++ b/apps/dock/src/app.rs@@ -0,0 +1,2179 @@+//! Dock windows and lifecycle.+//!+//! There are two windows:+//! - the **visual** window draws everything and passes through clicks; it is+//! larger than the dock to fit the shadow, magnified icons, and labels;+//! - the invisible **input** window covers only the area where the dock receives+//! mouse input. It expands while the cursor is over the dock (hysteresis).+//!+//! While the dock is running, the Windows taskbar is hidden and the dock is+//! registered as an AppBar, reserving a strip along the bottom of the screen.++use std::{+ cell::RefCell,+ collections::HashMap,+ env,+ sync::{+ OnceLock,+ atomic::{AtomicIsize, Ordering},+ },+ thread,+ time::Instant,+};++use anyhow::{Context, Result};+use muelle_config::Config;+use muelle_core::{+ bounce,+ layout::{ItemKind, Layout, Metrics, layout},+ magnify::{Magnifier, magnify},+ roster::Roster,+ spring::Spring,+};+use muelle_shell::{+ appbar::{ABN_FULLSCREENAPP, AppBar},+ files,+ icon_cache::IconCache,+ launcher,+ names::display_name,+ pins::{link_target, taskbar_pins},+ power,+ recycle_bin::{self, BinWatch},+ system::{+ animations_enabled, downloads_folder, primary_monitor, set_window_transitions,+ uses_light_theme,+ },+ taskbar,+ tracker::{self, TrackedWindow, WindowTracker, normalize_id},+};+use windows::{+ UI::Composition::{CompositionSurfaceBrush, Desktop::DesktopWindowTarget},+ Win32::{+ Foundation::{HWND, LPARAM, LRESULT, POINT, RECT, WPARAM},+ Graphics::Dwm::{DWMWA_USE_HOSTBACKDROPBRUSH, DwmFlush, DwmSetWindowAttribute},+ System::{+ Com::{COINIT_APARTMENTTHREADED, CoInitializeEx, CoUninitialize},+ Console::{CTRL_C_EVENT, SetConsoleCtrlHandler},+ LibraryLoader::GetModuleHandleW,+ Ole::{+ DROPEFFECT, DROPEFFECT_COPY, DROPEFFECT_LINK, DROPEFFECT_MOVE, DROPEFFECT_NONE,+ IDropTarget, OleInitialize, OleUninitialize, RegisterDragDrop, RevokeDragDrop,+ },+ WinRT::Composition::ICompositorDesktopInterop,+ },+ UI::{+ Accessibility::{HWINEVENTHOOK, SetWinEventHook, UnhookWinEvent},+ Input::KeyboardAndMouse::{+ ReleaseCapture, SetCapture, TME_LEAVE, TRACKMOUSEEVENT, TrackMouseEvent,+ },+ WindowsAndMessaging::{+ CreateWindowExW, DefWindowProcW, DispatchMessageW, EVENT_SYSTEM_MINIMIZESTART,+ FindWindowW, GetCursorPos, GetMessageW, GetSystemMetrics, HWND_TOPMOST, IDC_ARROW,+ KillTimer, LoadCursorW, MSG, OBJID_WINDOW, PM_REMOVE, PeekMessageW, PostMessageW,+ PostQuitMessage, RegisterClassW, RegisterShellHookWindow, RegisterWindowMessageW,+ SM_CXDRAG, SWP_HIDEWINDOW, SWP_NOACTIVATE, SWP_SHOWWINDOW, SetTimer, SetWindowPos,+ WINDOW_EX_STYLE, WINEVENT_OUTOFCONTEXT, WINEVENT_SKIPOWNPROCESS, WM_APP,+ WM_CAPTURECHANGED, WM_CLOSE, WM_DESTROY, WM_DISPLAYCHANGE, WM_DPICHANGED,+ WM_LBUTTONDOWN, WM_LBUTTONUP, WM_MOUSEMOVE, WM_QUIT, WM_RBUTTONUP,+ WM_SETTINGCHANGE, WM_TIMER, WNDCLASSW, WS_EX_LAYERED, WS_EX_NOACTIVATE,+ WS_EX_NOREDIRECTIONBITMAP, WS_EX_TOOLWINDOW, WS_EX_TOPMOST, WS_EX_TRANSPARENT,+ WS_POPUP,+ },+ },+ },+ core::{BOOL, Interface, PCWSTR, w},+};++use crate::{+ drop::DropTarget,+ flight::Flight,+ gfx::{Gfx, LabelBrush},+ menu::{self, MenuItem},+ scene::{Drag, Frame, Scene, SceneInput, SlotContent, Theme},+ strings::{self, text},+ thumbnails::Thumbnails,+};++/// These constants are not named in the `windows` crate.+const WM_MOUSELEAVE: u32 = 0x02A3;+const HSHELL_WINDOWACTIVATED: usize = 4;+const HSHELL_RUDEAPPACTIVATED: usize = 0x8004;+const HSHELL_FLASH: usize = 0x8006;+/// `wParam` of WM_SETTINGCHANGE when the work area changes. The dock's own+/// reservation causes this, so handling it would create a loop.+const SPI_SETWORKAREA: usize = 0x002F;+const WM_POWERBROADCAST: u32 = 0x0218;+const PBT_APMRESUMEAUTOMATIC: usize = 0x0012;++const WINDOW_CLASS: PCWSTR = muelle_shell::dock_link::DOCK_WINDOW_CLASS;+const APPBAR_CALLBACK: u32 = WM_APP + 1;+const TASKBAR_TAKEN: u32 = WM_APP + 2;+const BIN_CHANGED: u32 = WM_APP + 3;+/// Result of checking the recycle bin in the background (`wParam` = 1 if non-empty).+const BIN_STATE: u32 = WM_APP + 4;+/// Posted (not sent) when mouse capture is lost, so it is handled outside the+/// call that released it.+const DRAG_CANCELLED: u32 = WM_APP + 5;+/// Runs a file drop after OLE's `Drop` returns, so the drag source is not+/// blocked while files are copied or an app starts.+const DROP_RUN: u32 = WM_APP + 6;++const ICON_SOURCE_SIZE: u32 = 256;+/// Magnification range, in icons on either side of the cursor.+const RANGE_IN_ICONS: f32 = 3.0;+/// Speed of magnification entry and exit (about 200 ms).+const HOVER_OMEGA: f32 = 28.0;+/// Bounce height as a fraction of the icon size.+const BOUNCE_HEIGHT: f32 = 0.5;+const LAUNCH_BOUNCE_LIMIT: f32 = 10.0;+const ATTENTION_HOPS: f32 = 3.0;++// Dimensions are in logical pixels and are multiplied by the display scale.+/// Gap between the dock and the bottom screen edge, and between the dock and+/// maximized windows.+const FLOAT_MARGIN: f32 = 8.0;+const SHADOW_ROOM: f32 = 44.0;+const LABEL_ROOM: f32 = 60.0;+/// Hysteresis distances: the effect starts at the first distance and ends at the second.+const ENTER_HALO: f32 = 5.0;+const LEAVE_HALO: f32 = 15.0;++/// Windows sends settings changes in bursts; coalesce them into one recomposition.+const REFRESH_TIMER: usize = 1;+const REFRESH_DELAY_MS: u32 = 120;+/// Window notifications also arrive in bursts when an app opens.+const SYNC_TIMER: usize = 2;+const SYNC_DELAY_MS: u32 = 40;+/// After Explorer restarts or the system resumes, the new taskbar needs time+/// to apply its initial state before it can be taken over again.+const TASKBAR_TIMER: usize = 3;+const TASKBAR_DELAY_MS: u32 = 600;+const TRIM_TIMER: usize = 4;+const TRIM_DELAY_MS: u32 = 3000;+const BIN_TIMER: usize = 5;+const BIN_DELAY_MS: u32 = 300;+const HIDE_TIMER: usize = 6;+const HIDE_DELAY_MS: u32 = 300;++/// Auto-hide slide speed (about 250 ms).+const SLIDE_OMEGA: f32 = 24.0;+/// Screen-edge strip that reveals a hidden dock, in physical pixels.+const REVEAL_STRIP: i32 = 2;+/// An icon released this far above the magnified dock, in icon heights, leaves it.+const REMOVE_DISTANCE: f32 = 0.8;++const START_ID: &str = "muelle:start";+const WINDOW_ID_PREFIX: &str = "muelle:window:";+const WINDOW_TITLE_CHARS: usize = 40;+/// Fraction of a thumbnail slot covered by the app badge (see `scene`).+const BADGE_CORNER: f32 = crate::scene::BADGE_SIZE * crate::scene::BADGE_INSIDE;+const CMD_CLOSE_WINDOW: u32 = 8;+const CMD_SETTINGS: u32 = 9;++/// Context menu commands. Window commands start at `CMD_WINDOW`.+const CMD_OPEN: u32 = 1;+const CMD_TOGGLE_PIN: u32 = 2;+const CMD_REVEAL: u32 = 3;+const CMD_QUIT_APP: u32 = 4;+const CMD_EMPTY_BIN: u32 = 5;+const CMD_QUIT_DOCK: u32 = 6;+const CMD_TOGGLE_HIDING: u32 = 7;+const CMD_WINDOW: u32 = 100;+const MENU_WINDOWS: usize = 12;+const MENU_TITLE_CHARS: usize = 60;++static SHELL_HOOK: OnceLock<u32> = OnceLock::new();+static TASKBAR_CREATED: OnceLock<u32> = OnceLock::new();+/// Broadcast by the settings app after it saves the configuration.+static CONFIG_CHANGED: OnceLock<u32> = OnceLock::new();+/// Dock visual window, used to close it from the Ctrl+C handler running on+/// another thread.+static MAIN_WINDOW: AtomicIsize = AtomicIsize::new(0);+static DROP_WINDOW: AtomicIsize = AtomicIsize::new(0);+static MINIMIZE_HOOK: AtomicIsize = AtomicIsize::new(0);++#[derive(Clone, PartialEq)]+struct Entry {+ kind: ItemKind,+ id: Option<String>,+ role: Role,+ running: bool,+}++#[derive(Clone, Copy, PartialEq, Eq)]+enum Role {+ App,+ Start,+ /// A minimized window, shown as a live thumbnail.+ Window,+ Folder,+ Trash,+}++fn window_id(hwnd: isize) -> String {+ format!("{WINDOW_ID_PREFIX}{hwnd}")+}++fn window_of(id: &str) -> Option<isize> {+ id.strip_prefix(WINDOW_ID_PREFIX)?.parse().ok()+}++/// Work deferred until the app state is released. These calls may open a modal+/// loop (a menu, shell error dialog, or recycle bin confirmation) that dispatches+/// messages back to the dock.+enum Outside {+ Open(String),+ OpenStart,+ Activate(Vec<isize>),+ Reveal(String),+ EmptyBin,+ OpenWith(String, Vec<String>),+ Recycle(Vec<String>),+ Transfer {+ folder: String,+ files: Vec<String>,+ copy: bool,+ },+ Menu(MenuRequest),+ QuitDock,+ OpenSettings,+}++struct MenuRequest {+ target: MenuTarget,+ items: Vec<MenuItem>,+ anchor: POINT,+ dark: bool,+}++enum MenuTarget {+ Entry {+ id: String,+ role: Role,+ windows: Vec<isize>,+ },+ Dock,+}++struct Asset {+ icon: Option<CompositionSurfaceBrush>,+ label: Option<LabelBrush>,+}++struct Press {+ id: String,+ at: POINT,+}++struct Dragging {+ id: String,+ point: POINT,+ removing: bool,+}++/// What dropping the dragged files at a given place would do.+enum DropAction {+ Nothing,+ OpenWith(String),+ Recycle,+ Transfer { folder: String, copy: bool },+ Pin { id: String, before: Option<String> },+}++impl DropAction {+ fn effect(&self) -> DROPEFFECT {+ match self {+ Self::Nothing => DROPEFFECT_NONE,+ Self::OpenWith(_) => DROPEFFECT_COPY,+ Self::Recycle => DROPEFFECT_MOVE,+ Self::Transfer { copy, .. } => {+ if *copy {+ DROPEFFECT_COPY+ } else {+ DROPEFFECT_MOVE+ }+ }+ Self::Pin { .. } => DROPEFFECT_LINK,+ }+ }+}++struct Bounce {+ start: Instant,+ /// Seconds after `start` when bouncing ends. `None` means until the app opens a window.+ until: Option<f32>,+}++/// State that determines the scene; recomposition is unnecessary if it is unchanged.+#[derive(PartialEq)]+struct StageKey {+ screen: RECT,+ scale: f32,+ light: bool,+ bin_full: bool,+ auto_hide: bool,+ icon_size: u32,+ max_scale: f32,+ entries: Vec<Entry>,+}++struct Stage {+ key: StageKey,+ window_zone: RECT,+ scene: Scene,+ layout: Layout,+ magnifier: Magnifier,+ icon: f32,+ gap: f32,+ scale: f32,+ dock_origin: POINT,+ /// Position of the resting dock inside the visual window.+ origin: (f32, f32),+ rest_zone: RECT,+ hover_zone: RECT,+ /// Thin strip at the screen edge that reveals the dock when auto-hide is on.+ edge_zone: RECT,+ /// How far the dock slides down to hide completely.+ slide_distance: f32,+}++struct App {+ visual: HWND,+ input: HWND,+ gfx: Gfx,+ target: DesktopWindowTarget,+ appbar: Option<AppBar>,+ fullscreen: bool,+ roster: Roster,+ tracker: WindowTracker,+ windows: Vec<TrackedWindow>,+ entries: Vec<Entry>,+ icons: IconCache,+ downloads: Option<String>,+ bin_full: bool,+ _bin_watch: Option<BinWatch>,+ assets: HashMap<String, Asset>,+ /// Scale, theme and icon pixel size the cached assets were drawn for.+ assets_for: (f32, bool, u32),+ remove_label: Option<LabelBrush>,+ config: Config,+ /// 0 = shown, 1 = hidden (auto-hide).+ slide: Spring,+ press: Option<Press>,+ drag: Option<Dragging>,+ /// Files being dragged over the dock from another app.+ incoming: Vec<String>,+ pending_drop: Option<Outside>,+ bounces: HashMap<String, Bounce>,+ /// Minimized windows, in the order they were minimized.+ minimized: Vec<isize>,+ thumbnails: Thumbnails,+ /// Minimize animations in progress.+ flights: Vec<Flight>,+ /// Windows whose system transitions are turned off (see `calm_windows`).+ calmed: Vec<isize>,+ /// Windows already minimized when the dock starts get no animation.+ started: bool,+ stage: Option<Stage>,+ hovering: bool,+ hovered: Option<usize>,+ /// Horizontal cursor position relative to the resting dock.+ cursor: f32,+ /// 0 = resting, 1 = full magnification.+ amount: Spring,+ last_frame: Instant,+}++thread_local! {+ static APP: RefCell<Option<App>> = const { RefCell::new(None) };+}++fn explorer_id() -> String {+ normalize_id(&format!(+ "{}\\explorer.exe",+ env::var("WINDIR").unwrap_or_default()+ ))+}++/// Saved settings or, on first launch, the defaults with the apps pinned to+/// the Windows taskbar.+fn load_config() -> Config {+ let path = muelle_config::default_path();+ match muelle_config::load(&path) {+ Ok(Some(config)) => config,+ Ok(None) => {+ let config = Config {+ pinned: taskbar_pins(),+ ..Config::default()+ };+ if let Err(error) = muelle_config::save(&path, &config) {+ eprintln!("muelle: {error}");+ }+ config+ }+ Err(error) => {+ // Do not overwrite it; the user may want to repair the file.+ eprintln!("muelle: {error}; se usan los valores por defecto");+ Config::default()+ }+ }+}++/// The Explorer is always pinned, like Finder.+fn roster_from(config: &Config) -> Roster {+ let explorer = explorer_id();+ let mut pinned = config.pinned.clone();+ pinned.retain(|id| *id != explorer);+ pinned.insert(0, explorer);+ Roster::new(pinned, config.recent.clone())+}++fn save_settings(roster: &Roster, config: &Config) {+ let path = muelle_config::default_path();+ if let Err(error) = muelle_config::load(&path) {+ // Do not overwrite a corrupted file; report it and skip saving.+ eprintln!("muelle: {error}; no se guardan los cambios del dock");+ return;+ }+ let config = Config {+ pinned: roster.pinned().to_vec(),+ recent: roster.recent().to_vec(),+ ..config.clone()+ };+ if let Err(error) = muelle_config::save(&path, &config) {+ eprintln!("muelle: {error}");+ }+}++fn shorten(text: &str, max: usize) -> String {+ if text.chars().count() <= max {+ text.to_owned()+ } else {+ let cut: String = text.chars().take(max - 1).collect();+ format!("{}…", cut.trim_end())+ }+}++fn place(hwnd: HWND, zone: &RECT, visible: bool) -> Result<()> {+ let show = if visible {+ SWP_SHOWWINDOW+ } else {+ SWP_HIDEWINDOW+ };+ // SAFETY: `hwnd` is one of our live windows.+ unsafe {+ SetWindowPos(+ hwnd,+ Some(HWND_TOPMOST),+ zone.left,+ zone.top,+ zone.right - zone.left,+ zone.bottom - zone.top,+ SWP_NOACTIVATE | show,+ )?;+ }+ Ok(())+}++pub fn request_quit() {+ // SAFETY: Searches for the window and posts a message with no associated data.+ unsafe {+ if let Ok(hwnd) = FindWindowW(WINDOW_CLASS, None) {+ let _ = PostMessageW(Some(hwnd), WM_CLOSE, WPARAM(0), LPARAM(0));+ }+ }+}++unsafe extern "system" fn on_console_ctrl(event: u32) -> BOOL {+ let hwnd = MAIN_WINDOW.load(Ordering::Relaxed);+ if event == CTRL_C_EVENT && hwnd != 0 {+ // SAFETY: Only a message is sent; if the window no longer exists, the call has no effect.+ unsafe {+ let _ = PostMessageW(Some(HWND(hwnd as *mut _)), WM_CLOSE, WPARAM(0), LPARAM(0));+ }+ return true.into();+ }+ false.into()+}++impl App {+ /// List of items: apps, recents, Downloads, and recycle bin, separated into+ /// sections as in macOS.+ fn current_entries(&self) -> Vec<Entry> {+ let separator = || Entry {+ kind: ItemKind::Separator,+ id: None,+ role: Role::Folder,+ running: false,+ };+ let icon = |id: &str, role: Role, running: bool| Entry {+ kind: ItemKind::Icon,+ id: Some(id.to_owned()),+ role,+ running,+ };++ let mut entries: Vec<Entry> = self+ .roster+ .apps()+ .iter()+ .map(|app| icon(&app.id, Role::App, app.running))+ .collect();+ entries.insert(0, icon(START_ID, Role::Start, false));+ if !self.roster.recent().is_empty() {+ entries.push(separator());+ entries.extend(+ self.roster+ .recent()+ .iter()+ .map(|id| icon(id, Role::App, false)),+ );+ }+ entries.push(separator());+ entries.extend(+ self.minimized+ .iter()+ .map(|&hwnd| icon(&window_id(hwnd), Role::Window, false)),+ );+ if let Some(downloads) = &self.downloads {+ entries.push(icon(downloads, Role::Folder, false));+ }+ entries.push(icon(recycle_bin::PARSING_NAME, Role::Trash, false));+ entries+ }++ /// `wanted` is the pixel side icons are drawn at: their magnified size.+ fn prepare_assets(&mut self, wanted: u32, scale: f32, light: bool) {+ if self.assets_for != (scale, light, wanted) {+ self.assets.clear();+ self.remove_label = None;+ self.assets_for = (scale, light, wanted);+ }+ if self.remove_label.is_none() {+ self.remove_label = self.gfx.label_brush(text().remove, scale, light).ok();+ }+ for id in self.entries.iter().filter_map(|entry| entry.id.as_ref()) {+ if self.assets.contains_key(id) {+ continue;+ }+ if let Some(hwnd) = window_of(id) {+ let title = shorten(&tracker::title(hwnd), WINDOW_TITLE_CHARS);+ let label = self.gfx.label_brush(&title, scale, light).ok();+ self.assets.insert(id.clone(), Asset { icon: None, label });+ continue;+ }+ if id == START_ID {+ let icon = self.gfx.start_brush(wanted).ok();+ let label = self.gfx.label_brush(text().start, scale, light).ok();+ self.assets.insert(id.clone(), Asset { icon, label });+ continue;+ }+ // A missing icon should not prevent the rest of the dock from rendering.+ let visual = if id == recycle_bin::PARSING_NAME {+ let state = if self.bin_full { "llena" } else { "vacia" };+ self.icons.get_variant(id, state, ICON_SOURCE_SIZE)+ } else {+ self.icons.get(id, ICON_SOURCE_SIZE)+ }+ .inspect_err(|error| eprintln!("muelle: {error}"))+ .ok();+ let icon = visual.as_ref().and_then(|visual| {+ let side = wanted.min(visual.icon.width);+ self.gfx+ .icon_brush(&visual.icon, side)+ .inspect_err(|error| eprintln!("muelle: icono de `{id}`: {error:#}"))+ .ok()+ });+ let name = visual.map_or_else(|| display_name(id), |visual| visual.name);+ let label = self+ .gfx+ .label_brush(&name, scale, light)+ .inspect_err(|error| eprintln!("muelle: etiqueta de `{id}`: {error:#}"))+ .ok();+ self.assets.insert(id.clone(), Asset { icon, label });+ }+ let entries = &self.entries;+ self.assets+ .retain(|id, _| entries.iter().any(|entry| entry.id.as_ref() == Some(id)));+ }++ /// Recalculates sizes, positions, and scene for the current state. Does+ /// nothing if the scene inputs are unchanged, since many Windows notifications+ /// do not affect the dock.+ fn refresh(&mut self) -> Result<()> {+ let monitor = primary_monitor().context("no se pudo consultar el monitor principal")?;+ let key = StageKey {+ screen: monitor.screen,+ scale: monitor.scale,+ light: uses_light_theme(),+ bin_full: self.bin_full,+ auto_hide: self.config.auto_hide,+ icon_size: self.config.icon_size,+ max_scale: self.config.max_scale(),+ entries: self.current_entries(),+ };+ if self.stage.as_ref().is_some_and(|stage| stage.key == key) {+ return Ok(());+ }++ let scale = monitor.scale;+ let max_scale = key.max_scale;+ let metrics = Metrics {+ icon: key.icon_size as f32,+ ..Metrics::DEFAULT+ }+ .scaled(scale);+ let theme = Theme::for_system(key.light);+ let px = |logical: f32| (logical * scale).round();++ self.entries = key.entries.clone();+ self.prepare_assets(+ (metrics.icon * max_scale).round() as u32,+ scale,+ theme.light,+ );++ let kinds: Vec<ItemKind> = self.entries.iter().map(|entry| entry.kind).collect();+ let mut dock = layout(&kinds, &metrics);+ dock.width = dock.width.round();+ dock.height = dock.height.round();+ let magnifier = Magnifier {+ range: RANGE_IN_ICONS * (metrics.icon + metrics.gap),+ max_scale,+ };++ let side_growth = (magnifier.max_growth() / 2.0).ceil();+ let rise = (metrics.icon * (max_scale - 1.0)).ceil();++ // Position relative to the screen, not the work area; the work area+ // already excludes the strip reserved by the dock.+ let screen = monitor.screen;+ let screen_width = (screen.right - screen.left) as f32;+ let dock_x = screen.left as f32 + ((screen_width - dock.width) / 2.0).round();+ let dock_y = screen.bottom as f32 - px(FLOAT_MARGIN) - dock.height;+ if let Some(appbar) = &mut self.appbar {+ // A hidden dock leaves the whole screen to maximized windows.+ let strip = if self.config.auto_hide {+ 0+ } else {+ (dock.height + 2.0 * px(FLOAT_MARGIN)) as i32+ };+ appbar.reserve_bottom(screen, strip);+ }+ let (dock_right, dock_bottom) = (dock_x + dock.width, dock_y + dock.height);+ let zone = move |left: f32, top: f32, right: f32, bottom: f32| RECT {+ left: (dock_x - left) as i32,+ top: (dock_y - top) as i32,+ right: (dock_right + right) as i32,+ bottom: (dock_bottom + bottom) as i32,+ };++ let room = px(SHADOW_ROOM);+ let (room_x, room_top) = (room + side_growth, rise + px(LABEL_ROOM));+ let contents: Vec<SlotContent<'_>> = self+ .entries+ .iter()+ .map(|entry| {+ let asset = entry.id.as_ref().and_then(|id| self.assets.get(id));+ let badge = entry+ .id+ .as_deref()+ .and_then(window_of)+ .and_then(|hwnd| self.windows.iter().find(|window| window.hwnd == hwnd))+ .and_then(|window| self.assets.get(&window.app_id))+ .and_then(|asset| asset.icon.as_ref());+ SlotContent {+ icon: asset.and_then(|asset| asset.icon.as_ref()),+ label: asset.and_then(|asset| asset.label.as_ref()),+ running: entry.running,+ badge,+ }+ })+ .collect();+ let scene = Scene::build(+ &self.gfx,+ &SceneInput {+ layout: &dock,+ contents: &contents,+ theme,+ scale,+ origin: (room_x, room_top),+ remove_label: self.remove_label.as_ref(),+ },+ )?;+ self.target.SetRoot(&scene.root)?;++ let (enter, leave) = (px(ENTER_HALO), px(LEAVE_HALO));+ let stage = Stage {+ key,+ window_zone: zone(room_x, room_top, room_x, room),+ scene,+ magnifier,+ icon: metrics.icon,+ gap: metrics.gap,+ scale,+ origin: (room_x, room_top),+ dock_origin: POINT {+ x: dock_x as i32,+ y: dock_y as i32,+ },+ rest_zone: zone(enter, enter, enter, enter),+ hover_zone: zone(+ side_growth + leave,+ rise + leave,+ side_growth + leave,+ leave,+ ),+ edge_zone: RECT {+ left: (dock_x - side_growth) as i32,+ top: screen.bottom - REVEAL_STRIP,+ right: (dock_right + side_growth) as i32,+ bottom: screen.bottom,+ },+ slide_distance: dock.height + px(FLOAT_MARGIN) + room,+ layout: dock,+ };+ self.stage = Some(stage);+ self.place_windows()?;+ self.schedule_trim();+ self.render()+ }++ fn place_windows(&self) -> Result<()> {+ let Some(stage) = &self.stage else {+ return Ok(());+ };+ let visible = !self.fullscreen;+ place(self.visual, &stage.window_zone, visible)?;+ // Preserve the expanded input area if the cursor is already over the+ // dock (for example, after launching an app with a dock click).+ let input_zone = if self.hovering || self.drag.is_some() {+ &stage.hover_zone+ } else if self.config.auto_hide {+ &stage.edge_zone+ } else {+ &stage.rest_zone+ };+ place(self.input, input_zone, visible)+ }++ fn schedule_trim(&self) {+ // SAFETY: `self.input` is this live window, and this call runs on its UI thread.+ unsafe { SetTimer(Some(self.input), TRIM_TIMER, TRIM_DELAY_MS, None) };+ }++ fn trim_if_idle(&self) {+ if !self.hovering && !self.is_animating() {+ power::trim_memory();+ }+ }++ fn render(&mut self) -> Result<()> {+ let Some(stage) = &self.stage else {+ return Ok(());+ };+ let state = magnify(+ &stage.layout,+ self.cursor,+ self.amount.value,+ &stage.magnifier,+ );+ self.hovered = self+ .hovering+ .then(|| state.icon_at(&stage.layout, self.cursor, stage.gap))+ .flatten();++ let now = Instant::now();+ let lifts: Vec<f32> = self+ .entries+ .iter()+ .map(|entry| {+ entry+ .id+ .as_ref()+ .and_then(|id| self.bounces.get(id))+ .map_or(0.0, |bounce| {+ let elapsed = now.duration_since(bounce.start).as_secs_f32();+ bounce::lift(elapsed, stage.icon * BOUNCE_HEIGHT)+ })+ })+ .collect();++ let drag = self.drag.as_ref().and_then(|drag| {+ Some(Drag {+ index: self+ .entries+ .iter()+ .position(|entry| entry.id.as_deref() == Some(drag.id.as_str()))?,+ center: (+ (drag.point.x - stage.dock_origin.x) as f32,+ (drag.point.y - stage.dock_origin.y) as f32,+ ),+ removing: drag.removing,+ })+ });+ if drag.is_some() {+ self.hovered = None;+ }+ let at_rest = self.amount.value == 0.0+ && self.bounces.is_empty()+ && self.slide.is_settled()+ && drag.is_none();+ let slide = self.slide.value * stage.slide_distance;+ stage.scene.apply(&Frame {+ state: &state,+ hovered: self.hovered,+ lifts: &lifts,+ drag,+ slide,+ snap: at_rest,+ })?;++ let visible = !self.fullscreen;+ for (entry, rect) in self.entries.iter().zip(&state.rects) {+ if let Some(hwnd) = entry.id.as_deref().and_then(window_of) {+ let slot = (+ stage.origin.0 + rect.x,+ stage.origin.1 + rect.y + slide,+ rect.width,+ rect.height,+ );+ let has_badge = self+ .windows+ .iter()+ .find(|window| window.hwnd == hwnd)+ .and_then(|window| self.assets.get(&window.app_id))+ .is_some_and(|asset| asset.icon.is_some());+ let corner = if has_badge { BADGE_CORNER } else { 0.0 };+ let opacity = match self.flights.iter().find(|flight| flight.hwnd == hwnd) {+ _ if !visible => 0,+ Some(flight) => flight.landing_opacity(now),+ None => 255,+ };+ self.thumbnails.place(hwnd, slot, corner, opacity);+ }+ }+ Ok(())+ }++ /// Screen rectangle of a minimized window's slot, at rest, with the+ /// window's aspect ratio.+ fn minimized_slot(&self, hwnd: isize, aspect: f32) -> Option<RECT> {+ let stage = self.stage.as_ref()?;+ let id = window_id(hwnd);+ let index = self+ .entries+ .iter()+ .position(|entry| entry.id.as_deref() == Some(id.as_str()))?;+ let rect = stage.layout.slots.get(index)?.rect;+ let (width, height) = if aspect >= 1.0 {+ (rect.width, rect.width / aspect)+ } else {+ (rect.height * aspect, rect.height)+ };+ let left = stage.dock_origin.x as f32 + rect.x + (rect.width - width) / 2.0;+ let top = stage.dock_origin.y as f32 + rect.y + (rect.height - height) / 2.0;+ Some(RECT {+ left: left as i32,+ top: top as i32,+ right: (left + width) as i32,+ bottom: (top + height) as i32,+ })+ }++ /// A window starts minimizing: put it in the dock right away and fly it there.+ fn on_minimize_start(&mut self, hwnd: isize) -> Result<()> {+ if self.fullscreen+ || self.minimized.contains(&hwnd)+ || !self.windows.iter().any(|window| window.hwnd == hwnd)+ {+ return Ok(());+ }+ self.minimized.push(hwnd);+ self.thumbnails.sync(&self.minimized);+ self.refresh()?;+ self.start_flights(&[hwnd]);+ Ok(())+ }++ /// Turns off the system's transitions for every tracked window. Windows+ /// starts its own minimize animation before the dock hears about the+ /// minimize, and it cannot be cancelled afterwards, so it has to be off in+ /// advance for the genie to be the only animation. The cost: those windows+ /// also lose the system's maximize and close animations while the dock runs.+ fn calm_windows(&mut self) {+ if !self.config.genie || !animations_enabled() {+ return;+ }+ let windows = &self.windows;+ self.calmed+ .retain(|hwnd| windows.iter().any(|window| window.hwnd == *hwnd));+ for window in windows {+ if !self.calmed.contains(&window.hwnd) {+ set_window_transitions(window.hwnd, false);+ self.calmed.push(window.hwnd);+ }+ }+ }++ fn restore_transitions(&mut self) {+ for hwnd in self.calmed.drain(..) {+ set_window_transitions(hwnd, true);+ }+ }++ /// Brings windows to the front. Minimized ones get their system+ /// transitions back first, so they return with the system's restore+ /// animation; the next `sync` turns them off again.+ fn activating(&mut self, windows: Vec<isize>) -> Outside {+ for hwnd in &windows {+ if self.minimized.contains(hwnd) {+ set_window_transitions(*hwnd, true);+ self.calmed.retain(|calmed| calmed != hwnd);+ }+ }+ Outside::Activate(windows)+ }++ fn start_flights(&mut self, windows: &[isize]) {+ // Respect "Animation effects" being turned off in Windows settings.+ // One genie at a time: minimizing everything at once (Win+D) would+ // otherwise take a screen snapshot per window.+ if !self.config.genie || !animations_enabled() || !self.flights.is_empty() {+ return;+ }+ let Some(screen) = primary_monitor().map(|monitor| monitor.screen) else {+ return;+ };+ for &hwnd in windows {+ let Some(from) = tracker::normal_rect(hwnd) else {+ continue;+ };+ let aspect = (from.right - from.left) as f32 / (from.bottom - from.top).max(1) as f32;+ if let Some(to) = self.minimized_slot(hwnd, aspect)+ && let Some(flight) = Flight::start(&self.gfx, hwnd, from, to, screen)+ {+ self.flights.push(flight);+ self.last_frame = Instant::now();+ }+ }+ }++ fn on_mouse_move(&mut self) -> Result<()> {+ let Some(stage) = &self.stage else {+ return Ok(());+ };+ let mut point = POINT::default();+ // SAFETY: `point` remains alive for the duration of the call.+ unsafe { GetCursorPos(&mut point)? };++ let origin_x = stage.dock_origin.x;+ if self.update_drag(point) {+ self.cursor = (point.x - origin_x) as f32;+ return self.drag_to(point);+ }+ let Some(stage) = &self.stage else {+ return Ok(());+ };++ // Keep the active-area boundary aligned with the icons as they grow.+ let rise = stage.icon * (stage.magnifier.max_scale - 1.0) * self.amount.value;+ let ceiling = stage.dock_origin.y as f32 - rise - LEAVE_HALO * stage.scale;+ if self.hovering && (point.y as f32) < ceiling {+ return self.on_mouse_leave();+ }++ self.cursor = (point.x - stage.dock_origin.x) as f32;+ if !self.hovering {+ self.hovering = true;+ self.amount.target = 1.0;+ self.slide.target = 0.0;+ self.last_frame = Instant::now();+ // SAFETY: Timer on our own window; killing a timer that is not set is harmless.+ unsafe {+ let _ = KillTimer(Some(self.input), HIDE_TIMER);+ }+ self.place_windows()?;+ let mut track = TRACKMOUSEEVENT {+ cbSize: size_of::<TRACKMOUSEEVENT>() as u32,+ dwFlags: TME_LEAVE,+ hwndTrack: self.input,+ dwHoverTime: 0,+ };+ // SAFETY: `track` is a valid structure with its size initialized.+ unsafe { TrackMouseEvent(&mut track)? };+ }+ self.render()+ }++ fn on_mouse_leave(&mut self) -> Result<()> {+ if !self.hovering || self.drag.is_some() {+ return Ok(());+ }+ self.hovering = false;+ self.amount.target = 0.0;+ self.last_frame = Instant::now();+ if self.config.auto_hide {+ // SAFETY: Timer on our own window.+ unsafe { SetTimer(Some(self.input), HIDE_TIMER, HIDE_DELAY_MS, None) };+ }+ self.place_windows()?;+ self.render()+ }++ fn hide_if_unused(&mut self) -> Result<()> {+ if !self.config.auto_hide || self.hovering || self.drag.is_some() {+ return Ok(());+ }+ self.slide.target = 1.0;+ self.last_frame = Instant::now();+ self.place_windows()+ }++ /// Only running or pinned apps can be dragged; the Explorer, Start,+ /// recent apps, Downloads, and the recycle bin stay in place.+ fn is_draggable(&self, entry: &Entry) -> bool {+ entry.role == Role::App+ && entry.id.as_ref().is_some_and(|id| {+ *id != explorer_id() && (self.roster.is_pinned(id) || self.roster.is_running(id))+ })+ }++ fn on_press(&mut self) -> Result<()> {+ let Some(entry) = self.hovered.and_then(|index| self.entries.get(index)) else {+ return Ok(());+ };+ if !self.is_draggable(entry) {+ return Ok(());+ }+ let mut at = POINT::default();+ // SAFETY: `at` lives for the call; capture keeps mouse input while dragging+ // outside the input window.+ unsafe {+ GetCursorPos(&mut at)?;+ SetCapture(self.input);+ }+ self.press = entry.id.clone().map(|id| Press { id, at });+ Ok(())+ }++ /// Starts a drag once the cursor moves past the system drag threshold.+ /// Returns `true` while a drag is in progress.+ fn update_drag(&mut self, point: POINT) -> bool {+ if self.drag.is_none()+ && let Some(press) = &self.press+ {+ // SAFETY: Read-only query.+ let threshold = unsafe { GetSystemMetrics(SM_CXDRAG) }.max(1);+ if (point.x - press.at.x).abs() > threshold || (point.y - press.at.y).abs() > threshold+ {+ self.drag = Some(Dragging {+ id: press.id.clone(),+ point,+ removing: false,+ });+ }+ }+ self.drag.is_some()+ }++ /// Moves the dragged icon and reorders the pinned apps live, as in macOS.+ fn drag_to(&mut self, point: POINT) -> Result<()> {+ let (Some(stage), Some(drag)) = (&self.stage, &mut self.drag) else {+ return Ok(());+ };+ drag.point = point;+ let id = drag.id.clone();+ let pinned = self.roster.is_pinned(&id);+ let top = stage.dock_origin.y as f32+ - stage.icon * (stage.magnifier.max_scale - 1.0 + REMOVE_DISTANCE);+ drag.removing = pinned && (point.y as f32) < top;+ if drag.removing {+ return self.render();+ }++ let state = magnify(+ &stage.layout,+ self.cursor,+ self.amount.value,+ &stage.magnifier,+ );+ let explorer = explorer_id();+ let mut before: Option<String> = None;+ let mut pinned_end = f32::MIN;+ for (entry, rect) in self.entries.iter().zip(&state.rects) {+ let Some(other) = entry.id.as_ref() else {+ continue;+ };+ if entry.role != Role::App+ || *other == id+ || *other == explorer+ || !self.roster.is_pinned(other)+ {+ continue;+ }+ pinned_end = rect.x + rect.width;+ if before.is_none() && rect.x + rect.width / 2.0 > self.cursor {+ before = Some(other.clone());+ }+ }+ // An unpinned app is pinned only when dropped among the pinned ones.+ if !pinned && before.is_none() && self.cursor > pinned_end + stage.gap {+ return self.render();+ }++ let list = self.roster.pinned();+ let current = list+ .iter()+ .position(|pinned| *pinned == id)+ .map(|index| list.get(index + 1).cloned());+ if current == Some(before.clone()) {+ return self.render();+ }+ self.roster.pin_before(&id, before.as_deref());+ self.refresh()+ }++ /// Hover driven by a drag from another app: OLE takes the mouse, so the+ /// dock gets no WM_MOUSEMOVE meanwhile.+ fn hover_at(&mut self, x: i32) -> Result<()> {+ let Some(stage) = &self.stage else {+ return Ok(());+ };+ self.cursor = (x - stage.dock_origin.x) as f32;+ if !self.hovering {+ self.hovering = true;+ self.amount.target = 1.0;+ self.slide.target = 0.0;+ self.last_frame = Instant::now();+ self.place_windows()?;+ }+ self.render()+ }++ fn drop_action(&self) -> DropAction {+ let Some(stage) = &self.stage else {+ return DropAction::Nothing;+ };+ let state = magnify(+ &stage.layout,+ self.cursor,+ self.amount.value,+ &stage.magnifier,+ );+ let target = state+ .icon_at(&stage.layout, self.cursor, stage.gap)+ .and_then(|index| self.entries.get(index));+ let Some(entry) = target else {+ return self.pin_action(&state);+ };+ let Some(id) = entry.id.clone() else {+ return DropAction::Nothing;+ };+ match entry.role {+ Role::App if id.ends_with(".exe") => DropAction::OpenWith(id),+ Role::Trash => DropAction::Recycle,+ Role::Folder => DropAction::Transfer {+ copy: !self+ .incoming+ .iter()+ .all(|file| files::same_volume(file, &id)),+ folder: id,+ },+ Role::App | Role::Start | Role::Window => DropAction::Nothing,+ }+ }++ /// A single app or shortcut dropped between icons is pinned there.+ fn pin_action(&self, state: &muelle_core::magnify::Magnified) -> DropAction {+ let [file] = self.incoming.as_slice() else {+ return DropAction::Nothing;+ };+ let lower = file.to_lowercase();+ let target = if lower.ends_with(".lnk") {+ link_target(std::path::Path::new(file))+ } else {+ Some(file.clone())+ };+ let Some(id) = target+ .map(|target| normalize_id(&target))+ .filter(|id| id.ends_with(".exe"))+ else {+ return DropAction::Nothing;+ };+ let explorer = explorer_id();+ let before = self+ .entries+ .iter()+ .zip(&state.rects)+ .find(|(entry, rect)| {+ entry.role == Role::App+ && entry.id.as_ref().is_some_and(|other| {+ *other != explorer && *other != id && self.roster.is_pinned(other)+ })+ && rect.x + rect.width / 2.0 > self.cursor+ })+ .and_then(|(entry, _)| entry.id.clone());+ DropAction::Pin { id, before }+ }++ fn on_drag_enter(&mut self, incoming: Vec<String>, x: i32) -> Result<DROPEFFECT> {+ self.incoming = incoming;+ self.on_drag_over(x)+ }++ fn on_drag_over(&mut self, x: i32) -> Result<DROPEFFECT> {+ self.hover_at(x)?;+ Ok(self.drop_action().effect())+ }++ fn on_drag_leave(&mut self) -> Result<()> {+ self.incoming.clear();+ self.on_mouse_leave()+ }++ fn on_drop(&mut self, x: i32) -> Result<DROPEFFECT> {+ self.hover_at(x)?;+ let action = self.drop_action();+ let effect = action.effect();+ let files = std::mem::take(&mut self.incoming);+ self.pending_drop = match action {+ DropAction::Nothing => None,+ DropAction::OpenWith(app) => {+ self.start_bounce(app.clone(), None);+ Some(Outside::OpenWith(app, files))+ }+ DropAction::Recycle => Some(Outside::Recycle(files)),+ DropAction::Transfer { folder, copy } => Some(Outside::Transfer {+ folder,+ files,+ copy,+ }),+ DropAction::Pin { id, before } => {+ self.roster.pin_before(&id, before.as_deref());+ save_settings(&self.roster, &self.config);+ self.refresh()?;+ None+ }+ };+ if self.pending_drop.is_some() {+ // SAFETY: Posting a message to our own window.+ unsafe {+ let _ = PostMessageW(Some(self.input), DROP_RUN, WPARAM(0), LPARAM(0));+ }+ }+ // The mouse is still over the dock; the next WM_MOUSEMOVE starts a+ // tracked hover again.+ self.on_mouse_leave()?;+ Ok(effect)+ }++ fn on_release(&mut self) -> Result<Option<Outside>> {+ self.press = None;+ let Some(drag) = self.drag.take() else {+ // SAFETY: Releasing capture we may not hold is harmless.+ unsafe {+ let _ = ReleaseCapture();+ }+ return self.on_click();+ };+ // SAFETY: Same as above.+ unsafe {+ let _ = ReleaseCapture();+ }+ if drag.removing {+ self.roster.unpin(&drag.id);+ }+ save_settings(&self.roster, &self.config);+ self.refresh()?;+ self.leave_if_outside(drag.point)?;+ Ok(None)+ }++ /// Capture can be lost mid-drag (Alt+Tab, a system dialog): keep the order+ /// reached so far.+ fn cancel_drag(&mut self) -> Result<()> {+ self.press = None;+ let Some(drag) = self.drag.take() else {+ return Ok(());+ };+ save_settings(&self.roster, &self.config);+ self.leave_if_outside(drag.point)?;+ self.render()+ }++ fn leave_if_outside(&mut self, point: POINT) -> Result<()> {+ let Some(stage) = &self.stage else {+ return Ok(());+ };+ let zone = stage.hover_zone;+ let inside = point.x >= zone.left+ && point.x < zone.right+ && point.y >= zone.top+ && point.y < zone.bottom;+ if inside {+ Ok(())+ } else {+ self.on_mouse_leave()+ }+ }++ fn windows_of(&self, id: &str) -> Vec<isize> {+ self.windows+ .iter()+ .filter(|window| window.app_id == id)+ .map(|window| window.hwnd)+ .collect()+ }++ /// On icon click, launches a closed app or brings its windows to the+ /// foreground. Does nothing if the app is already in front, as in macOS.+ fn on_click(&mut self) -> Result<Option<Outside>> {+ let Some(entry) = self.hovered.and_then(|index| self.entries.get(index)) else {+ return Ok(None);+ };+ let (Some(id), role) = (entry.id.clone(), entry.role) else {+ return Ok(None);+ };+ let windows = self.windows_of(&id);++ Ok(match role {+ Role::App if windows.is_empty() => {+ self.start_bounce(id.clone(), None);+ Some(Outside::Open(id))+ }+ Role::App if windows.contains(&tracker::foreground_window()) => None,+ Role::App => Some(self.activating(windows)),+ Role::Start => Some(Outside::OpenStart),+ Role::Window => window_of(&id).map(|hwnd| self.activating(vec![hwnd])),+ Role::Folder | Role::Trash => Some(Outside::Open(id)),+ })+ }++ /// Right-click prepares the menu for the item under the cursor, or the dock+ /// menu when over empty space or a divider.+ fn on_right_click(&mut self) -> Result<Option<Outside>> {+ let Some(stage) = &self.stage else {+ return Ok(None);+ };+ let state = magnify(+ &stage.layout,+ self.cursor,+ self.amount.value,+ &stage.magnifier,+ );+ let target_entry = self.hovered.and_then(|index| {+ let entry = self.entries.get(index)?;+ Some((entry.id.clone()?, entry.role, *state.rects.get(index)?))+ });+ let gap = (stage.gap / 2.0).round() as i32;++ let (target, items, anchor) = match target_entry {+ Some((id, role, rect)) => {+ let windows = self.windows_of(&id);+ let anchor = POINT {+ x: stage.dock_origin.x + (rect.x + rect.width / 2.0).round() as i32,+ y: stage.dock_origin.y + rect.y.round() as i32 - gap,+ };+ let items = self.entry_menu(&id, role, &windows);+ (MenuTarget::Entry { id, role, windows }, items, anchor)+ }+ None => {+ let anchor = POINT {+ x: stage.dock_origin.x + self.cursor.round() as i32,+ y: stage.dock_origin.y - gap,+ };+ let hiding = if self.config.auto_hide {+ text().turn_hiding_off+ } else {+ text().turn_hiding_on+ };+ let items = vec![+ MenuItem::action(CMD_TOGGLE_HIDING, hiding),+ MenuItem::action(CMD_SETTINGS, text().settings),+ MenuItem::Separator,+ MenuItem::action(CMD_QUIT_DOCK, text().quit_dock),+ ];+ (MenuTarget::Dock, items, anchor)+ }+ };++ // Hide the label while the menu is open, as in macOS.+ self.hovered = None;+ self.hovering = false;+ self.render()?;+ Ok(Some(Outside::Menu(MenuRequest {+ target,+ items,+ anchor,+ dark: !uses_light_theme(),+ })))+ }++ fn entry_menu(&self, id: &str, role: Role, windows: &[isize]) -> Vec<MenuItem> {+ let is_file = !id.starts_with("shell:") && !id.starts_with("::");+ let t = text();+ let mut items = Vec::new();+ match role {+ Role::App => {+ for (index, &hwnd) in windows.iter().take(MENU_WINDOWS).enumerate() {+ let title = tracker::title(hwnd);+ if !title.is_empty() {+ items.push(MenuItem::action(+ CMD_WINDOW + index as u32,+ shorten(&title, MENU_TITLE_CHARS).replace('&', "&&"),+ ));+ }+ }+ if !items.is_empty() {+ items.push(MenuItem::Separator);+ }+ let open = if windows.is_empty() {+ t.open+ } else {+ t.new_window+ };+ items.push(MenuItem::action(CMD_OPEN, open));+ if id != explorer_id() {+ items.push(MenuItem::Action {+ command: CMD_TOGGLE_PIN,+ label: t.keep_in_dock.into(),+ checked: self.roster.is_pinned(id),+ enabled: true,+ });+ }+ if is_file {+ items.push(MenuItem::action(CMD_REVEAL, t.show_in_explorer));+ }+ if !windows.is_empty() {+ items.push(MenuItem::Separator);+ items.push(MenuItem::action(CMD_QUIT_APP, t.quit_app));+ }+ }+ Role::Start => items.push(MenuItem::action(CMD_OPEN, t.open)),+ Role::Window => {+ items.push(MenuItem::action(CMD_OPEN, t.open));+ items.push(MenuItem::Separator);+ items.push(MenuItem::action(CMD_CLOSE_WINDOW, t.close_window));+ }+ Role::Folder => {+ items.push(MenuItem::action(CMD_OPEN, t.open));+ items.push(MenuItem::action(CMD_REVEAL, t.show_in_explorer));+ }+ Role::Trash => {+ items.push(MenuItem::action(CMD_OPEN, t.open));+ items.push(MenuItem::Separator);+ items.push(MenuItem::Action {+ command: CMD_EMPTY_BIN,+ label: t.empty_bin.into(),+ checked: false,+ enabled: self.bin_full,+ });+ }+ }+ items+ }++ fn on_command(&mut self, target: MenuTarget, command: u32) -> Result<Option<Outside>> {+ let MenuTarget::Entry { id, role, windows } = target else {+ return match command {+ CMD_QUIT_DOCK => Ok(Some(Outside::QuitDock)),+ CMD_TOGGLE_HIDING => self.toggle_hiding().map(|()| None),+ CMD_SETTINGS => Ok(Some(Outside::OpenSettings)),+ _ => Ok(None),+ };+ };+ Ok(match command {+ CMD_OPEN if role == Role::Start => Some(Outside::OpenStart),+ CMD_OPEN if role == Role::Window => {+ window_of(&id).map(|hwnd| self.activating(vec![hwnd]))+ }+ CMD_CLOSE_WINDOW => {+ launcher::close(&window_of(&id).into_iter().collect::<Vec<_>>());+ None+ }+ CMD_OPEN => {+ if role == Role::App {+ self.start_bounce(id.clone(), None);+ }+ Some(Outside::Open(id))+ }+ CMD_TOGGLE_PIN => {+ if self.roster.is_pinned(&id) {+ self.roster.unpin(&id);+ } else {+ self.roster.pin(&id);+ }+ save_settings(&self.roster, &self.config);+ self.refresh()?;+ None+ }+ CMD_REVEAL => Some(Outside::Reveal(id)),+ CMD_QUIT_APP => {+ launcher::close(&windows);+ None+ }+ CMD_EMPTY_BIN => Some(Outside::EmptyBin),+ window => {+ let index = window.checked_sub(CMD_WINDOW).map(|index| index as usize);+ index+ .and_then(|index| windows.get(index))+ .map(|&hwnd| self.activating(vec![hwnd]))+ }+ })+ }++ /// The settings app saved a change: read it and apply what differs.+ fn reload_config(&mut self) -> Result<()> {+ let Ok(Some(saved)) = muelle_config::load(&muelle_config::default_path()) else {+ return Ok(());+ };+ // Pinned and recent apps belong to the dock; the settings app only+ // changes the rest.+ let config = Config {+ pinned: self.config.pinned.clone(),+ recent: self.config.recent.clone(),+ ..saved+ };+ if config == self.config {+ return Ok(());+ }+ if config.language != self.config.language {+ strings::set_language(config.language);+ // Labels are drawn text: redraw them in the new language.+ self.assets_for = (0.0, false, 0);+ }+ if !config.genie {+ self.restore_transitions();+ }+ if config.auto_hide != self.config.auto_hide {+ self.slide.target = if config.auto_hide { 1.0 } else { 0.0 };+ self.last_frame = Instant::now();+ }+ self.config = config;+ self.calm_windows();+ self.refresh()+ }++ fn toggle_hiding(&mut self) -> Result<()> {+ self.config.auto_hide = !self.config.auto_hide;+ save_settings(&self.roster, &self.config);+ self.slide.target = if self.config.auto_hide { 1.0 } else { 0.0 };+ self.last_frame = Instant::now();+ self.refresh()+ }++ fn set_bin_full(&mut self, full: bool) -> Result<()> {+ if full == self.bin_full {+ return Ok(());+ }+ self.bin_full = full;+ self.assets.remove(recycle_bin::PARSING_NAME);+ self.refresh()+ }++ fn start_bounce(&mut self, id: String, until: Option<f32>) {+ self.bounces.entry(id).or_insert(Bounce {+ start: Instant::now(),+ until,+ });+ self.last_frame = Instant::now();+ }++ fn on_attention(&mut self, hwnd: isize) {+ if hwnd == tracker::foreground_window() {+ return;+ }+ if let Some(window) = self.windows.iter().find(|window| window.hwnd == hwnd) {+ self.start_bounce(+ window.app_id.clone(),+ Some(ATTENTION_HOPS * bounce::HOP_SECONDS),+ );+ }+ }++ /// Refreshes open windows and recomposes the dock if anything changed.+ fn sync(&mut self) -> Result<()> {+ self.windows = self.tracker.list();+ self.calm_windows();+ let recent_before = self.roster.recent().to_vec();+ let changed = self+ .roster+ .sync(self.windows.iter().map(|window| window.app_id.as_str()));+ if self.roster.recent() != recent_before.as_slice() {+ save_settings(&self.roster, &self.config);+ }++ // The launching app has opened a window, so finish its current bounce.+ let now = Instant::now();+ for (id, bounce) in &mut self.bounces {+ if bounce.until.is_none() && self.roster.is_running(id) {+ let elapsed = now.duration_since(bounce.start).as_secs_f32();+ bounce.until = Some(bounce::end_of_hop(elapsed));+ }+ }++ let minimized_before = self.minimized.clone();+ let now_minimized: Vec<isize> = self+ .windows+ .iter()+ .filter(|window| window.minimized)+ .map(|window| window.hwnd)+ .collect();+ // A window still flying in was added at minimize start and may not+ // report as minimized yet.+ let flights = &self.flights;+ self.minimized.retain(|hwnd| {+ now_minimized.contains(hwnd) || flights.iter().any(|flight| flight.hwnd == *hwnd)+ });+ for hwnd in now_minimized {+ if !self.minimized.contains(&hwnd) {+ self.minimized.push(hwnd);+ }+ }+ self.thumbnails.sync(&self.minimized);++ if changed || self.minimized != minimized_before {+ self.refresh()?;+ }+ let newly_minimized: Vec<isize> = self+ .minimized+ .iter()+ .copied()+ .filter(|hwnd| !minimized_before.contains(hwnd))+ .collect();+ if self.started && !self.fullscreen {+ self.start_flights(&newly_minimized);+ }+ self.started = true;+ // A foreground-window change may mean an app entered or exited full-screen mode.+ self.update_fullscreen()+ }++ fn tick(&mut self) -> Result<()> {+ let now = Instant::now();+ let flying = self.flights.len();+ let gfx = &self.gfx;+ self.flights.retain_mut(|flight| flight.step(gfx, now));+ if self.flights.len() != flying {+ // Confirm the landed windows really are minimized.+ // SAFETY: Timer on our own window.+ unsafe { SetTimer(Some(self.input), SYNC_TIMER, SYNC_DELAY_MS, None) };+ }+ let dt = now.duration_since(self.last_frame).as_secs_f32();+ self.amount.step(dt);+ self.slide.step(dt);+ self.last_frame = now;++ self.bounces.retain(|_, bounce| {+ let elapsed = now.duration_since(bounce.start).as_secs_f32();+ let until = bounce.until.unwrap_or(LAUNCH_BOUNCE_LIMIT);+ elapsed < until+ });+ self.render()+ }++ /// Hides the taskbar and reserves its space again. After Explorer restarts,+ /// both the taskbar and AppBar registrations are new.+ fn retake_taskbar(&mut self) -> Result<()> {+ taskbar::take_over();+ self.appbar = None;+ self.appbar = AppBar::register(self.visual, APPBAR_CALLBACK);+ self.stage = None;+ self.refresh()+ }++ /// Hides the dock while the foreground window covers the entire screen and+ /// shows it again when it no longer does.+ fn update_fullscreen(&mut self) -> Result<()> {+ let Some(monitor) = primary_monitor() else {+ return Ok(());+ };+ let fullscreen = tracker::foreground_is_fullscreen(monitor.screen);+ if fullscreen == self.fullscreen {+ return Ok(());+ }+ self.fullscreen = fullscreen;+ if fullscreen {+ self.hovering = false;+ self.amount = Spring::at(0.0, HOVER_OMEGA);+ self.press = None;+ self.drag = None;+ }+ self.place_windows()+ }++ fn on_appbar_notice(&mut self, notice: usize) -> Result<()> {+ match notice {+ // Windows notifications may be missing or unreliable, so use them+ // only as a signal to recheck the state.+ ABN_FULLSCREENAPP => self.update_fullscreen(),+ // The dock's own reservation can trigger this. The strip changes+ // only with the screen or dock size, already handled by `refresh`.+ _ => Ok(()),+ }+ }++ fn is_animating(&self) -> bool {+ !self.amount.is_settled()+ || !self.slide.is_settled()+ || !self.bounces.is_empty()+ || !self.flights.is_empty()+ }+}++/// Runs `action` on the app and logs failures; a transient failure must not+/// terminate the dock.+fn with_app(what: &str, action: impl FnOnce(&mut App) -> Result<()>) {+ with_app_then(what, |app| action(app).map(|()| None));+}++/// Like `with_app`, but `action` can request work to perform after releasing+/// the app state (see [`Outside`]).+fn with_app_then(what: &str, action: impl FnOnce(&mut App) -> Result<Option<Outside>>) {+ let outside = APP.with(|cell| {+ // Modal calls run outside the borrow, so this should not happen. If it+ // does, discard the message rather than terminating the dock.+ let Ok(mut app) = cell.try_borrow_mut() else {+ eprintln!("muelle: {what}: el dock estaba ocupado; se ignora");+ return None;+ };+ match app.as_mut().map(action) {+ Some(Ok(outside)) => outside,+ Some(Err(error)) => {+ eprintln!("muelle: {what}: {error:#}");+ None+ }+ None => None,+ }+ });+ if let Some(outside) = outside {+ run_outside(outside);+ }+}++unsafe extern "system" fn on_win_event(+ _hook: HWINEVENTHOOK,+ event: u32,+ hwnd: HWND,+ object: i32,+ _child: i32,+ _thread: u32,+ _time: u32,+) {+ if event == EVENT_SYSTEM_MINIMIZESTART && object == OBJID_WINDOW.0 {+ with_app("minimizar", |app| app.on_minimize_start(hwnd.0 as isize));+ }+}++/// Like `with_app`, for callers that need a value back (OLE callbacks).+fn with_app_value<T: Default>(what: &str, action: impl FnOnce(&mut App) -> Result<T>) -> T {+ let mut value = T::default();+ with_app(what, |app| {+ value = action(app)?;+ Ok(())+ });+ value+}++pub fn drag_enter(files: Vec<String>, x: i32, _y: i32) -> DROPEFFECT {+ with_app_value("arrastre de archivos", |app| app.on_drag_enter(files, x))+}++pub fn drag_over(x: i32, _y: i32) -> DROPEFFECT {+ with_app_value("arrastre de archivos", |app| app.on_drag_over(x))+}++pub fn drag_leave() {+ with_app("arrastre de archivos", App::on_drag_leave);+}++pub fn drop_files(x: i32, _y: i32) -> DROPEFFECT {+ with_app_value("soltar archivos", |app| app.on_drop(x))+}++/// Checks the recycle bin on a background thread by scanning each drive+/// (measured at 50–75 ms), so the UI is not blocked. The result arrives via+/// `BIN_STATE`.+fn query_bin_in_background() {+ let window = MAIN_WINDOW.load(Ordering::Relaxed);+ thread::spawn(move || {+ // SAFETY: COM is initialized and released on this thread; the message+ // is harmless if the window no longer exists.+ unsafe {+ let com = CoInitializeEx(None, COINIT_APARTMENTTHREADED);+ let full = recycle_bin::has_items();+ if com.is_ok() {+ CoUninitialize();+ }+ let _ = PostMessageW(+ Some(HWND(window as *mut _)),+ BIN_STATE,+ WPARAM(usize::from(full)),+ LPARAM(0),+ );+ }+ });+}++fn main_window() -> HWND {+ HWND(MAIN_WINDOW.load(Ordering::Relaxed) as *mut _)+}++fn run_outside(outside: Outside) {+ let report = |result: Result<(), launcher::LaunchError>| {+ if let Err(error) = result {+ eprintln!("muelle: {error}");+ }+ };+ match outside {+ Outside::Open(id) => report(launcher::open(&id)),+ Outside::OpenStart => launcher::open_start_menu(),+ Outside::Activate(windows) => launcher::activate(&windows),+ Outside::Reveal(path) => report(launcher::reveal(&path)),+ Outside::OpenWith(app, files) => report(launcher::open_with(&app, &files)),+ Outside::Recycle(paths) => files::recycle(main_window(), &paths),+ Outside::Transfer {+ folder,+ files: paths,+ copy,+ } => files::transfer(main_window(), &paths, &folder, copy),+ Outside::EmptyBin => {+ let owner = HWND(MAIN_WINDOW.load(Ordering::Relaxed) as *mut _);+ recycle_bin::empty(owner);+ }+ Outside::QuitDock => request_quit(),+ Outside::OpenSettings => {+ // The settings app is installed next to the dock.+ let settings = env::current_exe()+ .ok()+ .map(|exe| exe.with_file_name("muelle-settings.exe"));+ match settings {+ Some(path) if path.exists() => report(launcher::open(&path.to_string_lossy())),+ _ => eprintln!("muelle: no se encontró muelle-settings.exe junto al dock"),+ }+ }+ Outside::Menu(request) => {+ let owner = HWND(MAIN_WINDOW.load(Ordering::Relaxed) as *mut _);+ let chosen = menu::show(owner, &request.items, request.anchor, request.dark);+ if let Some(command) = chosen {+ with_app_then("orden del menú", |app| {+ app.on_command(request.target, command)+ });+ }+ }+ }+}++unsafe extern "system" fn wndproc(hwnd: HWND, msg: u32, w: WPARAM, l: LPARAM) -> LRESULT {+ match msg {+ WM_MOUSEMOVE => with_app("movimiento del ratón", App::on_mouse_move),+ WM_MOUSELEAVE => with_app("salida del ratón", App::on_mouse_leave),+ WM_LBUTTONDOWN => with_app("pulsación", App::on_press),+ WM_LBUTTONUP => with_app_then("clic", App::on_release),+ WM_CAPTURECHANGED => {+ // SAFETY: Posting a message to our own window.+ unsafe {+ let _ = PostMessageW(Some(hwnd), DRAG_CANCELLED, WPARAM(0), LPARAM(0));+ }+ }+ DRAG_CANCELLED => with_app("arrastre", App::cancel_drag),+ DROP_RUN => with_app_then("soltar archivos", |app| Ok(app.pending_drop.take())),+ WM_RBUTTONUP => with_app_then("menú", App::on_right_click),+ BIN_STATE => with_app("papelera", |app| app.set_bin_full(w.0 != 0)),+ BIN_CHANGED => {+ // SAFETY: `hwnd` is this live window on its owning UI thread.+ unsafe { SetTimer(Some(hwnd), BIN_TIMER, BIN_DELAY_MS, None) };+ }+ WM_SETTINGCHANGE if w.0 == SPI_SETWORKAREA => {}+ WM_SETTINGCHANGE | WM_DISPLAYCHANGE | WM_DPICHANGED => {+ // SAFETY: `hwnd` is our window; scheduling the same timer resets it.+ unsafe { SetTimer(Some(hwnd), REFRESH_TIMER, REFRESH_DELAY_MS, None) };+ }+ WM_TIMER if w.0 == BIN_TIMER => {+ // SAFETY: `hwnd` is this live window on its owning UI thread.+ unsafe {+ let _ = KillTimer(Some(hwnd), w.0);+ }+ query_bin_in_background();+ }+ WM_TIMER if w.0 == HIDE_TIMER => {+ // SAFETY: Same as above.+ unsafe {+ let _ = KillTimer(Some(hwnd), w.0);+ }+ with_app("ocultación", App::hide_if_unused);+ }+ WM_TIMER if w.0 == TRIM_TIMER => {+ // SAFETY: `hwnd` is this live window on its owning UI thread.+ unsafe {+ let _ = KillTimer(Some(hwnd), w.0);+ }+ with_app("recorte de memoria", |app| {+ app.trim_if_idle();+ Ok(())+ });+ }+ WM_TIMER if [REFRESH_TIMER, SYNC_TIMER, TASKBAR_TIMER].contains(&w.0) => {+ // SAFETY: `hwnd` is this live window on its owning UI thread.+ unsafe {+ let _ = KillTimer(Some(hwnd), w.0);+ }+ match w.0 {+ REFRESH_TIMER => with_app("recomposición del dock", App::refresh),+ SYNC_TIMER => with_app("lectura de ventanas", App::sync),+ _ => with_app("ocultar la barra de Windows", App::retake_taskbar),+ }+ }+ APPBAR_CALLBACK => with_app("aviso de AppBar", |app| app.on_appbar_notice(w.0)),+ // Once the taskbar is set to auto-hide, the dock strip moves to the+ // screen edge, so reserve and reposition it again.+ TASKBAR_TAKEN => with_app("reserva de espacio", |app| {+ app.stage = None;+ app.refresh()+ }),+ WM_POWERBROADCAST if w.0 == PBT_APMRESUMEAUTOMATIC => {+ // SAFETY: `hwnd` is this live window on its owning UI thread.+ unsafe { SetTimer(Some(hwnd), TASKBAR_TIMER, TASKBAR_DELAY_MS, None) };+ }+ _ if CONFIG_CHANGED.get() == Some(&msg) => with_app("ajustes", App::reload_config),+ _ if TASKBAR_CREATED.get() == Some(&msg) => {+ // SAFETY: `hwnd` is this live window on its owning UI thread.+ unsafe { SetTimer(Some(hwnd), TASKBAR_TIMER, TASKBAR_DELAY_MS, None) };+ }+ WM_DESTROY => unsafe { PostQuitMessage(0) },+ _ if SHELL_HOOK.get() == Some(&msg) => match w.0 {+ // Changing the foreground window does not change the app list; it+ // can only enter or exit full-screen mode.+ HSHELL_WINDOWACTIVATED | HSHELL_RUDEAPPACTIVATED => {+ with_app("ventana activa", App::update_fullscreen);+ }+ code => {+ if code == HSHELL_FLASH {+ with_app("aviso de atención", |app| {+ app.on_attention(l.0);+ Ok(())+ });+ }+ // SAFETY: `hwnd` is this live window on its owning UI thread.+ unsafe { SetTimer(Some(hwnd), SYNC_TIMER, SYNC_DELAY_MS, None) };+ }+ },+ _ => return unsafe { DefWindowProcW(hwnd, msg, w, l) },+ }+ LRESULT(0)+}++fn is_animating() -> bool {+ APP.with_borrow(|app| app.as_ref().is_some_and(App::is_animating))+}++/// Main loop. Sleeps while idle (0% CPU) and advances one frame per display+/// refresh while an animation is running.+///+/// Outside animations, the thread uses EcoQoS because remaining work (window+/// tracking and recomposition) is not time-sensitive.+fn message_loop() {+ let mut msg = MSG::default();+ let mut was_animating = None;+ unsafe {+ loop {+ let animating = is_animating();+ if was_animating != Some(animating) {+ power::set_thread_efficiency(!animating);+ if was_animating == Some(true) {+ with_app("recorte de memoria", |app| {+ app.schedule_trim();+ Ok(())+ });+ }+ was_animating = Some(animating);+ }+ if animating {+ while PeekMessageW(&mut msg, None, 0, 0, PM_REMOVE).as_bool() {+ if msg.message == WM_QUIT {+ return;+ }+ DispatchMessageW(&msg);+ }+ with_app("animación", App::tick);+ // Wait for the next refresh to pace animation without timers.+ let _ = DwmFlush();+ } else {+ if !GetMessageW(&mut msg, None, 0, 0).as_bool() {+ return;+ }+ DispatchMessageW(&msg);+ }+ }+ }+}++pub fn run() -> Result<()> {+ let gfx = Gfx::new()?;+ // SAFETY: The thread is already a single-threaded COM apartment (see+ // `main`); OLE adds drag and drop on top of it and is released at the end.+ unsafe { OleInitialize(None)? };++ unsafe {+ let instance = GetModuleHandleW(None)?;+ let class = WINDOW_CLASS;+ RegisterClassW(&WNDCLASSW {+ lpfnWndProc: Some(wndproc),+ hInstance: instance.into(),+ hCursor: LoadCursorW(None, IDC_ARROW)?,+ lpszClassName: class,+ ..Default::default()+ });++ let base = WS_EX_NOREDIRECTIONBITMAP | WS_EX_TOPMOST | WS_EX_TOOLWINDOW | WS_EX_NOACTIVATE;+ let create = |extra: WINDOW_EX_STYLE| {+ CreateWindowExW(+ base | extra,+ class,+ w!("Muelle"),+ WS_POPUP,+ 0,+ 0,+ 0,+ 0,+ None,+ None,+ Some(instance.into()),+ None,+ )+ };+ let visual = create(WS_EX_LAYERED | WS_EX_TRANSPARENT)?;+ let input = create(WINDOW_EX_STYLE::default())?;++ // Without this, the system backdrop brush appears black.+ let enable = BOOL::from(true);+ DwmSetWindowAttribute(+ visual,+ DWMWA_USE_HOSTBACKDROPBRUSH,+ (&raw const enable).cast(),+ size_of::<BOOL>() as u32,+ )?;++ let target = gfx+ .compositor+ .cast::<ICompositorDesktopInterop>()?+ .CreateDesktopWindowTarget(visual, true)?;++ muelle_config::migrate_legacy_folder();+ let config = load_config();+ strings::set_language(config.language);+ let roster = roster_from(&config);+ let auto_hide = config.auto_hide;+ let mut app = App {+ visual,+ input,+ gfx,+ target,+ appbar: AppBar::register(visual, APPBAR_CALLBACK),+ fullscreen: false,+ roster,+ tracker: WindowTracker::default(),+ windows: Vec::new(),+ entries: Vec::new(),+ icons: IconCache::default(),+ downloads: downloads_folder(),+ bin_full: false,+ _bin_watch: BinWatch::register(input, BIN_CHANGED),+ assets: HashMap::new(),+ assets_for: (0.0, false, 0),+ remove_label: None,+ config,+ slide: Spring::at(if auto_hide { 1.0 } else { 0.0 }, SLIDE_OMEGA),+ press: None,+ drag: None,+ incoming: Vec::new(),+ pending_drop: None,+ bounces: HashMap::new(),+ minimized: Vec::new(),+ thumbnails: Thumbnails::new(visual),+ flights: Vec::new(),+ calmed: Vec::new(),+ started: false,+ stage: None,+ hovering: false,+ hovered: None,+ cursor: 0.0,+ amount: Spring::at(0.0, HOVER_OMEGA),+ last_frame: Instant::now(),+ };+ let _ = TASKBAR_CREATED.set(RegisterWindowMessageW(w!("TaskbarCreated")));+ let _ = CONFIG_CHANGED.set(RegisterWindowMessageW(+ muelle_shell::dock_link::CONFIG_CHANGED,+ ));+ MAIN_WINDOW.store(visual.0 as isize, Ordering::Relaxed);+ // The dock inherits the "ignore Ctrl+C" attribute from its parent+ // (some tools enable it), so clear it to ensure Ctrl+C is handled.+ let _ = SetConsoleCtrlHandler(None, false);+ let _ = SetConsoleCtrlHandler(Some(on_console_ctrl), true);++ app.sync()?;+ // `sync` recomposes only when the list changes; run it unconditionally at startup.+ if app.stage.is_none() {+ app.refresh()?;+ }++ // The shell notifies this window when a window is created, closed,+ // activated, or requests attention.+ let _ = SHELL_HOOK.set(RegisterWindowMessageW(w!("SHELLHOOK")));+ RegisterShellHookWindow(input).ok()?;+ // Delivered through this thread's message loop; no code runs in other processes.+ let minimize_hook = SetWinEventHook(+ EVENT_SYSTEM_MINIMIZESTART,+ EVENT_SYSTEM_MINIMIZESTART,+ None,+ Some(on_win_event),+ 0,+ 0,+ WINEVENT_OUTOFCONTEXT | WINEVENT_SKIPOWNPROCESS,+ );+ MINIMIZE_HOOK.store(minimize_hook.0 as isize, Ordering::Relaxed);+ let target: IDropTarget = DropTarget.into();+ RegisterDragDrop(input, &target)?;+ DROP_WINDOW.store(input.0 as isize, Ordering::Relaxed);++ APP.set(Some(app));+ }++ // Hiding the taskbar is a synchronous Explorer call that takes 50–500 ms+ // depending on load. Run it off the UI thread after the dock is visible.+ let visual_window = MAIN_WINDOW.load(Ordering::Relaxed);+ query_bin_in_background();+ let taking_over = thread::spawn(move || {+ taskbar::take_over();+ // SAFETY: Only a message is sent; if the window no longer exists, the call has no effect.+ unsafe {+ let _ = PostMessageW(+ Some(HWND(visual_window as *mut _)),+ TASKBAR_TAKEN,+ WPARAM(0),+ LPARAM(0),+ );+ }+ });++ message_loop();+ // SAFETY: The drop target was registered on this window in this thread.+ unsafe {+ let _ = RevokeDragDrop(HWND(DROP_WINDOW.load(Ordering::Relaxed) as *mut _));+ let _ = UnhookWinEvent(HWINEVENTHOOK(+ MINIMIZE_HOOK.load(Ordering::Relaxed) as *mut _+ ));+ }+ APP.with_borrow_mut(|app| {+ if let Some(app) = app {+ app.restore_transitions();+ }+ });+ APP.set(None);+ // SAFETY: Balances `OleInitialize` above, on the same thread.+ unsafe { OleUninitialize() };+ // Wait for taskbar takeover to finish before restoring it.+ let _ = taking_over.join();+ Ok(())+}diff --git a/apps/dock/src/drop.rs b/apps/dock/src/drop.rsnew file mode 100644index 0000000..d5114a5--- /dev/null+++ b/apps/dock/src/drop.rs@@ -0,0 +1,98 @@+//! OLE drop target for files dragged onto the dock. The decisions live in+//! `app`; this only adapts the COM interface.++use windows::{+ Win32::{+ Foundation::POINTL,+ System::{+ Com::{DVASPECT_CONTENT, FORMATETC, IDataObject, TYMED_HGLOBAL},+ Ole::{CF_HDROP, DROPEFFECT, IDropTarget, IDropTarget_Impl, ReleaseStgMedium},+ SystemServices::MODIFIERKEYS_FLAGS,+ },+ UI::Shell::{DragQueryFileW, HDROP},+ },+ core::{Ref, Result, implement},+};++use crate::app;++#[implement(IDropTarget)]+pub struct DropTarget;++/// Writes the chosen effect, limited to those the drag source allows.+fn answer(effect: *mut DROPEFFECT, chosen: DROPEFFECT) {+ if effect.is_null() {+ return;+ }+ // SAFETY: OLE passes a valid pointer holding the allowed effects.+ unsafe { *effect = DROPEFFECT((*effect).0 & chosen.0) };+}++impl IDropTarget_Impl for DropTarget_Impl {+ fn DragEnter(+ &self,+ data: Ref<IDataObject>,+ _keys: MODIFIERKEYS_FLAGS,+ point: &POINTL,+ effect: *mut DROPEFFECT,+ ) -> Result<()> {+ let files = data.ok().map(dropped_files).unwrap_or_default();+ answer(effect, app::drag_enter(files, point.x, point.y));+ Ok(())+ }++ fn DragOver(+ &self,+ _keys: MODIFIERKEYS_FLAGS,+ point: &POINTL,+ effect: *mut DROPEFFECT,+ ) -> Result<()> {+ answer(effect, app::drag_over(point.x, point.y));+ Ok(())+ }++ fn DragLeave(&self) -> Result<()> {+ app::drag_leave();+ Ok(())+ }++ fn Drop(+ &self,+ _data: Ref<IDataObject>,+ _keys: MODIFIERKEYS_FLAGS,+ point: &POINTL,+ effect: *mut DROPEFFECT,+ ) -> Result<()> {+ answer(effect, app::drop_files(point.x, point.y));+ Ok(())+ }+}++fn dropped_files(data: &IDataObject) -> Vec<String> {+ let format = FORMATETC {+ cfFormat: CF_HDROP.0,+ ptd: std::ptr::null_mut(),+ dwAspect: DVASPECT_CONTENT.0,+ lindex: -1,+ tymed: TYMED_HGLOBAL.0 as u32,+ };+ // SAFETY: The medium is released after reading; each buffer is sized from+ // the length DragQueryFileW reports.+ unsafe {+ let Ok(mut medium) = data.GetData(&format) else {+ return Vec::new();+ };+ let drop = HDROP(medium.u.hGlobal.0);+ let count = DragQueryFileW(drop, u32::MAX, None);+ let files = (0..count)+ .map(|index| {+ let len = DragQueryFileW(drop, index, None) as usize;+ let mut buffer = vec![0u16; len + 1];+ DragQueryFileW(drop, index, Some(&mut buffer));+ String::from_utf16_lossy(&buffer[..len])+ })+ .collect();+ ReleaseStgMedium(&mut medium);+ files+ }+}diff --git a/apps/dock/src/flight.rs b/apps/dock/src/flight.rsnew file mode 100644index 0000000..3dfc79c--- /dev/null+++ b/apps/dock/src/flight.rs@@ -0,0 +1,370 @@+//! Genie minimize animation.+//!+//! Windows cannot deform another app's window, Windows 11 ignores the shell's+//! minimize-target hint, and a minimized window can no longer be captured. So:+//!+//! 1. one live DWM thumbnail is shown exactly where the window was (nothing+//! changes on screen);+//! 2. a frame later that rectangle is copied from the screen: a snapshot, as+//! macOS also uses for its genie;+//! 3. the snapshot becomes one composition surface shared by thin horizontal+//! strips (plain composition visuals), placed every frame along the genie+//! curves (`muelle_core::genie`).+//!+//! Many DWM thumbnails instead of a snapshot were measured and rejected: DWM+//! drops frames beyond about 16 of them (plan section 8).+//!+//! Everything lives on a transparent overlay window that exists only while+//! the animation runs. The system's own minimize animation must already be+//! off for the window (see `App::calm_windows`): it starts before the dock+//! hears about the minimize and cannot be cancelled afterwards.++use std::{sync::OnceLock, time::Instant};++use anyhow::Result;+use muelle_core::genie::{Edges, Genie, Strip};+use muelle_shell::screen;+use windows::{+ UI::Composition::{+ CompositionStretch, CompositionSurfaceBrush, ContainerVisual, Desktop::DesktopWindowTarget,+ SpriteVisual,+ },+ Win32::{+ Foundation::{HWND, LPARAM, LRESULT, RECT, WPARAM},+ Graphics::Dwm::{+ DWM_THUMBNAIL_PROPERTIES, DWM_TNP_OPACITY, DWM_TNP_RECTDESTINATION,+ DWM_TNP_SOURCECLIENTAREAONLY, DWM_TNP_VISIBLE, DwmRegisterThumbnail,+ DwmUnregisterThumbnail, DwmUpdateThumbnailProperties,+ },+ System::{LibraryLoader::GetModuleHandleW, WinRT::Composition::ICompositorDesktopInterop},+ UI::WindowsAndMessaging::{+ CreateWindowExW, DefWindowProcW, DestroyWindow, RegisterClassW, SW_SHOWNOACTIVATE,+ ShowWindow, WNDCLASSW, WS_EX_LAYERED, WS_EX_NOACTIVATE, WS_EX_NOREDIRECTIONBITMAP,+ WS_EX_TOOLWINDOW, WS_EX_TOPMOST, WS_EX_TRANSPARENT, WS_POPUP,+ },+ },+ core::{Interface, w},+};+use windows_numerics::{Matrix3x2, Vector2, Vector3};++use crate::gfx::Gfx;++const DURATION_SECONDS: f32 = 0.5;+/// Source rows per strip: the edge of the funnel steps by at most a few pixels.+const STRIP_ROWS: u32 = 3;+const MAX_STRIPS: u32 = 400;+/// Frames the thumbnail stays up before the screen is copied, so DWM has+/// certainly presented it.+const FRAMES_BEFORE_SNAPSHOT: u32 = 2;+/// The dock's own thumbnail fades in over the last part of the animation.+const LANDING_START: f32 = 0.8;++struct Piece {+ visual: SpriteVisual,+ brush: CompositionSurfaceBrush,+ /// First source row and row count, in snapshot pixels.+ top: f32,+ rows: f32,+ /// Last placement applied (`None` = hidden), to skip redundant calls.+ shown: Option<[i32; 4]>,+}++enum Phase {+ /// The stand-in thumbnail is on screen; counting frames until the snapshot.+ Standing {+ thumbnail: isize,+ frames: u32,+ },+ Flying {+ start: Instant,+ pieces: Vec<Piece>,+ },+}++pub struct Flight {+ /// The window being minimized.+ pub hwnd: isize,+ overlay: HWND,+ /// Kept alive: it owns the overlay's visual tree.+ _target: DesktopWindowTarget,+ root: ContainerVisual,+ /// Overlay origin on screen.+ origin: (i32, i32),+ genie: Genie,+ phase: Phase,+ /// Scratch buffer reused every frame.+ strips: Vec<Strip>,+}++unsafe extern "system" fn overlay_proc(hwnd: HWND, msg: u32, w: WPARAM, l: LPARAM) -> LRESULT {+ // SAFETY: Standard forwarding; the overlay handles no messages itself.+ unsafe { DefWindowProcW(hwnd, msg, w, l) }+}++fn intersect(a: RECT, b: RECT) -> RECT {+ RECT {+ left: a.left.max(b.left),+ top: a.top.max(b.top),+ right: a.right.min(b.right),+ bottom: a.bottom.min(b.bottom),+ }+}++impl Flight {+ /// `from` and `to` are screen rectangles; `screen` is the monitor the+ /// overlay covers.+ pub fn start(gfx: &Gfx, hwnd: isize, from: RECT, to: RECT, screen: RECT) -> Option<Self> {+ // Only what is on screen can be copied from it.+ let visible = intersect(from, screen);+ if visible.right <= visible.left || visible.bottom <= visible.top {+ return None;+ }++ static CLASS: OnceLock<bool> = OnceLock::new();+ let class = w!("MuelleFlight");+ // SAFETY: Standard class registration and window creation on the UI+ // thread; the handles are released in `Drop` or on the early returns below.+ unsafe {+ let instance = GetModuleHandleW(None).ok()?;+ CLASS.get_or_init(|| {+ RegisterClassW(&WNDCLASSW {+ lpfnWndProc: Some(overlay_proc),+ hInstance: instance.into(),+ lpszClassName: class,+ ..Default::default()+ }) != 0+ });+ let overlay = CreateWindowExW(+ WS_EX_LAYERED+ | WS_EX_TRANSPARENT+ | WS_EX_NOREDIRECTIONBITMAP+ | WS_EX_TOPMOST+ | WS_EX_TOOLWINDOW+ | WS_EX_NOACTIVATE,+ class,+ w!(""),+ WS_POPUP,+ screen.left,+ screen.top,+ screen.right - screen.left,+ screen.bottom - screen.top,+ None,+ None,+ Some(instance.into()),+ None,+ )+ .ok()?;++ let tree = || -> Result<(DesktopWindowTarget, ContainerVisual)> {+ let target = gfx+ .compositor+ .cast::<ICompositorDesktopInterop>()?+ .CreateDesktopWindowTarget(overlay, true)?;+ let root = gfx.compositor.CreateContainerVisual()?;+ root.SetRelativeSizeAdjustment(Vector2 { X: 1.0, Y: 1.0 })?;+ target.SetRoot(&root)?;+ Ok((target, root))+ };+ let (Ok((target, root)), Ok(thumbnail)) =+ (tree(), DwmRegisterThumbnail(overlay, HWND(hwnd as *mut _)))+ else {+ let _ = DestroyWindow(overlay);+ return None;+ };++ // The stand-in: the whole window, exactly where it was.+ let properties = DWM_THUMBNAIL_PROPERTIES {+ dwFlags: DWM_TNP_RECTDESTINATION+ | DWM_TNP_VISIBLE+ | DWM_TNP_OPACITY+ | DWM_TNP_SOURCECLIENTAREAONLY,+ rcDestination: RECT {+ left: from.left - screen.left,+ top: from.top - screen.top,+ right: from.right - screen.left,+ bottom: from.bottom - screen.top,+ },+ opacity: 255,+ fVisible: true.into(),+ fSourceClientAreaOnly: false.into(),+ ..Default::default()+ };+ let _ = DwmUpdateThumbnailProperties(thumbnail, &properties);+ let _ = ShowWindow(overlay, SW_SHOWNOACTIVATE);++ let local = |rect: RECT| Edges {+ left: (rect.left - screen.left) as f32,+ top: (rect.top - screen.top) as f32,+ right: (rect.right - screen.left) as f32,+ bottom: (rect.bottom - screen.top) as f32,+ };+ Some(Self {+ hwnd,+ overlay,+ _target: target,+ root,+ origin: (screen.left, screen.top),+ genie: Genie {+ window: local(visible),+ slot: local(to),+ },+ phase: Phase::Standing {+ thumbnail,+ frames: 0,+ },+ strips: Vec::new(),+ })+ }+ }++ /// Advances the animation; returns `false` once it has finished (or cannot go on).+ pub fn step(&mut self, gfx: &Gfx, now: Instant) -> bool {+ match &mut self.phase {+ Phase::Standing { thumbnail, frames } => {+ *frames += 1;+ if *frames <= FRAMES_BEFORE_SNAPSHOT {+ return true;+ }+ let thumbnail = *thumbnail;+ let Ok(pieces) = self.take_snapshot(gfx) else {+ return false;+ };+ self.strips = vec![+ Strip {+ source_top: 0.0,+ source_bottom: 0.0,+ target: None,+ };+ pieces.len()+ ];+ self.phase = Phase::Flying { start: now, pieces };+ let _ = self.place(0.0);+ // The strips now show the same image: the stand-in can go.+ // SAFETY: `thumbnail` came from DwmRegisterThumbnail and is released once.+ unsafe {+ let _ = DwmUnregisterThumbnail(thumbnail);+ }+ true+ }+ Phase::Flying { start, .. } => {+ let t = now.duration_since(*start).as_secs_f32() / DURATION_SECONDS;+ t < 1.0 && self.place(t).is_ok()+ }+ }+ }++ /// Opacity (0..=255) of the dock's own thumbnail for this window, which+ /// fades in as the genie lands.+ pub fn landing_opacity(&self, now: Instant) -> u8 {+ let Phase::Flying { start, .. } = &self.phase else {+ return 0;+ };+ let t = now.duration_since(*start).as_secs_f32() / DURATION_SECONDS;+ (((t - LANDING_START) / (1.0 - LANDING_START)).clamp(0.0, 1.0) * 255.0) as u8+ }++ /// Copies the window's rectangle from the screen and cuts it into strips.+ fn take_snapshot(&self, gfx: &Gfx) -> Result<Vec<Piece>> {+ let window = self.genie.window;+ let image = screen::capture(RECT {+ left: window.left as i32 + self.origin.0,+ top: window.top as i32 + self.origin.1,+ right: window.right as i32 + self.origin.0,+ bottom: window.bottom as i32 + self.origin.1,+ })+ .ok_or_else(|| anyhow::anyhow!("screen capture failed"))?;+ let surface = gfx.image_surface(&image)?;++ let count = (image.height / STRIP_ROWS).clamp(1, MAX_STRIPS);+ let row =+ |index: u32| (u64::from(index) * u64::from(image.height) / u64::from(count)) as f32;+ let compositor = &gfx.compositor;+ let children = self.root.Children()?;+ (0..count)+ .map(|index| {+ let brush = compositor.CreateSurfaceBrushWithSurface(&surface)?;+ brush.SetStretch(CompositionStretch::None)?;+ brush.SetHorizontalAlignmentRatio(0.0)?;+ brush.SetVerticalAlignmentRatio(0.0)?;+ let visual = compositor.CreateSpriteVisual()?;+ visual.SetBrush(&brush)?;+ children.InsertAtTop(&visual)?;+ Ok(Piece {+ visual,+ brush,+ top: row(index),+ rows: row(index + 1) - row(index),+ shown: None,+ })+ })+ .collect()+ }++ fn place(&mut self, t: f32) -> Result<()> {+ let Phase::Flying { pieces, .. } = &mut self.phase else {+ return Ok(());+ };+ let source_width = self.genie.window.right - self.genie.window.left;+ self.genie.frame(t, &mut self.strips);+ for (piece, strip) in pieces.iter_mut().zip(&self.strips) {+ // Whole pixels, so neighbouring strips meet without seams.+ let target = strip+ .target+ .map(|edges| {+ [+ edges.left.round() as i32,+ edges.top.round() as i32,+ edges.right.round() as i32,+ edges.bottom.round() as i32,+ ]+ })+ .filter(|[left, top, right, bottom]| right > left && bottom > top);+ if piece.shown == target && piece.shown.is_some() {+ continue;+ }+ let Some([left, top, right, bottom]) = target else {+ if piece.shown.is_some() {+ piece.visual.SetIsVisible(false)?;+ piece.shown = None;+ }+ continue;+ };+ piece.shown = target;++ let (width, height) = ((right - left) as f32, (bottom - top) as f32);+ piece.visual.SetOffset(Vector3 {+ X: left as f32,+ Y: top as f32,+ Z: 0.0,+ })?;+ piece.visual.SetSize(Vector2 {+ X: width,+ Y: height,+ })?;+ // Squeeze the full snapshot width into the strip and bring this+ // strip's first row to the top of the visual.+ let (scale_x, scale_y) = (width / source_width, height / piece.rows);+ piece.brush.SetTransformMatrix(Matrix3x2 {+ M11: scale_x,+ M12: 0.0,+ M21: 0.0,+ M22: scale_y,+ M31: 0.0,+ M32: -piece.top * scale_y,+ })?;+ }+ Ok(())+ }+}++impl Drop for Flight {+ fn drop(&mut self) {+ // SAFETY: The handles were created in `create` and are released once.+ unsafe {+ if let Phase::Standing { thumbnail, .. } = self.phase {+ let _ = DwmUnregisterThumbnail(thumbnail);+ }+ let _ = DestroyWindow(self.overlay);+ }+ }+}diff --git a/apps/dock/src/gfx.rs b/apps/dock/src/gfx.rsnew file mode 100644index 0000000..ce3d022--- /dev/null+++ b/apps/dock/src/gfx.rs@@ -0,0 +1,414 @@+//! Graphics device connecting the Windows compositor to Direct2D, allowing+//! icons and masks to be drawn on compositor surfaces.++use anyhow::{Context, Result};+use muelle_shell::icons::IconImage;+use windows::{+ Foundation::Size,+ Graphics::DirectX::{DirectXAlphaMode, DirectXPixelFormat},+ UI::Composition::{+ CompositionDrawingSurface, CompositionGraphicsDevice, CompositionSurfaceBrush, Compositor,+ },+ Win32::{+ Foundation::{HMODULE, POINT},+ Graphics::{+ Direct2D::{+ Common::{+ D2D_RECT_F, D2D_SIZE_U, D2D1_ALPHA_MODE_PREMULTIPLIED, D2D1_COLOR_F,+ D2D1_FIGURE_BEGIN_FILLED, D2D1_FIGURE_END_CLOSED, D2D1_GRADIENT_STOP,+ D2D1_PIXEL_FORMAT,+ },+ D2D1_BITMAP_OPTIONS_NONE, D2D1_BITMAP_PROPERTIES1,+ D2D1_BUFFER_PRECISION_8BPC_UNORM, D2D1_COLOR_INTERPOLATION_MODE_PREMULTIPLIED,+ D2D1_COLOR_SPACE_SRGB, D2D1_DRAW_TEXT_OPTIONS_NONE, D2D1_EXTEND_MODE_CLAMP,+ D2D1_INTERPOLATION_MODE, D2D1_INTERPOLATION_MODE_HIGH_QUALITY_CUBIC,+ D2D1_INTERPOLATION_MODE_NEAREST_NEIGHBOR, D2D1_LINEAR_GRADIENT_BRUSH_PROPERTIES,+ D2D1_ROUNDED_RECT, D2D1CreateDevice, ID2D1Device, ID2D1DeviceContext,+ },+ Direct3D::D3D_DRIVER_TYPE_WARP,+ Direct3D11::{+ D3D11_CREATE_DEVICE_BGRA_SUPPORT, D3D11_CREATE_DEVICE_SINGLETHREADED,+ D3D11_SDK_VERSION, D3D11CreateDevice,+ },+ DirectWrite::{+ DWRITE_FACTORY_TYPE_SHARED, DWRITE_FONT_STRETCH_NORMAL, DWRITE_FONT_STYLE_NORMAL,+ DWRITE_FONT_WEIGHT_MEDIUM, DWRITE_TEXT_METRICS, DWriteCreateFactory,+ IDWriteFactory,+ },+ Dxgi::{Common::DXGI_FORMAT_B8G8R8A8_UNORM, IDXGIDevice},+ },+ System::WinRT::Composition::{ICompositionDrawingSurfaceInterop, ICompositorInterop},+ },+ core::{Interface, w},+};+use windows_numerics::{Matrix3x2, Vector2};++const TRANSPARENT: D2D1_COLOR_F = D2D1_COLOR_F {+ r: 0.0,+ g: 0.0,+ b: 0.0,+ a: 0.0,+};+const WHITE: D2D1_COLOR_F = D2D1_COLOR_F {+ r: 1.0,+ g: 1.0,+ b: 1.0,+ a: 1.0,+};++pub struct LabelBrush {+ pub brush: CompositionSurfaceBrush,+ pub width: f32,+ pub height: f32,+}++pub struct Gfx {+ pub compositor: Compositor,+ graphics: CompositionGraphicsDevice,+ // Surfaces depend on this device, so it must outlive them.+ _d2d: ID2D1Device,+ dwrite: IDWriteFactory,+}++impl Gfx {+ pub fn new() -> Result<Self> {+ let compositor = Compositor::new()?;+ // SAFETY: D3D writes only to the initialized output slot; the returned+ // device is immediately wrapped in an owned COM interface.+ let (d2d, graphics) = unsafe {+ let mut d3d = None;+ D3D11CreateDevice(+ None,+ D3D_DRIVER_TYPE_WARP,+ HMODULE::default(),+ D3D11_CREATE_DEVICE_BGRA_SUPPORT | D3D11_CREATE_DEVICE_SINGLETHREADED,+ None,+ D3D11_SDK_VERSION,+ Some(&mut d3d),+ None,+ None,+ )?;+ let dxgi: IDXGIDevice = d3d.context("Direct3D no devolvió un dispositivo")?.cast()?;+ let d2d = D2D1CreateDevice(&dxgi, None)?;+ let graphics = compositor+ .cast::<ICompositorInterop>()?+ .CreateGraphicsDevice(&d2d)?;+ (d2d, graphics)+ };+ Ok(Self {+ compositor,+ graphics,+ _d2d: d2d,+ dwrite: unsafe { DWriteCreateFactory(DWRITE_FACTORY_TYPE_SHARED)? },+ })+ }++ /// Creates a `width` × `height` pixel surface, draws on it, and returns it+ /// as a brush for a visual.+ fn draw(+ &self,+ width: u32,+ height: u32,+ paint: impl FnOnce(&ID2D1DeviceContext) -> Result<()>,+ ) -> Result<CompositionSurfaceBrush> {+ let surface = self.draw_surface(width, height, paint)?;+ Ok(self.compositor.CreateSurfaceBrushWithSurface(&surface)?)+ }++ fn draw_surface(+ &self,+ width: u32,+ height: u32,+ paint: impl FnOnce(&ID2D1DeviceContext) -> Result<()>,+ ) -> Result<CompositionDrawingSurface> {+ let surface = self.graphics.CreateDrawingSurface(+ Size {+ Width: width as f32,+ Height: height as f32,+ },+ DirectXPixelFormat::B8G8R8A8UIntNormalized,+ DirectXAlphaMode::Premultiplied,+ )?;+ let interop: ICompositionDrawingSurfaceInterop = surface.cast()?;++ // SAFETY: BeginDraw and EndDraw are paired, and `offset` lives through the call.+ unsafe {+ let mut offset = POINT::default();+ let dc: ID2D1DeviceContext = interop.BeginDraw(None, &mut offset)?;+ // The surface may be part of an atlas, so draw at the specified offset.+ dc.SetDpi(96.0, 96.0);+ dc.SetTransform(&Matrix3x2::translation(offset.x as f32, offset.y as f32));+ dc.Clear(Some(&TRANSPARENT));+ let painted = paint(&dc);+ interop.EndDraw()?;+ painted?;+ }+ Ok(surface)+ }++ pub fn icon_brush(&self, icon: &IconImage, side: u32) -> Result<CompositionSurfaceBrush> {+ self.draw(side, side, |dc| {+ let quality = D2D1_INTERPOLATION_MODE_HIGH_QUALITY_CUBIC;+ draw_image(dc, icon, side as f32, side as f32, quality)+ })+ }++ /// A surface holding `image` at its own size, to be shared by many brushes.+ pub fn image_surface(&self, image: &IconImage) -> Result<CompositionDrawingSurface> {+ self.draw_surface(image.width, image.height, |dc| {+ // Drawn 1:1, so there is nothing to interpolate.+ let (width, height) = (image.width as f32, image.height as f32);+ draw_image(+ dc,+ image,+ width,+ height,+ D2D1_INTERPOLATION_MODE_NEAREST_NEIGHBOR,+ )+ })+ }++ /// Creates a minimal opaque rounded rectangle (side `2·radius + 2`). A+ /// *nine-grid* brush stretches it to any width without repainting or+ /// distorting its corners during magnification.+ pub fn rounded_mask(&self, radius: f32) -> Result<CompositionSurfaceBrush> {+ let side = (2.0 * radius).ceil() + 2.0;+ self.draw(side as u32, side as u32, |dc| {+ let shape = D2D1_ROUNDED_RECT {+ rect: D2D_RECT_F {+ left: 0.0,+ top: 0.0,+ right: side,+ bottom: side,+ },+ radiusX: radius,+ radiusY: radius,+ };+ // SAFETY: The brush and geometry remain alive during the call.+ unsafe {+ let brush = dc.CreateSolidColorBrush(&WHITE, None)?;+ dc.FillRoundedRectangle(&shape, &brush);+ }+ Ok(())+ })+ }++ /// Creates an app-name label: a dark pill (light in light theme) with a+ /// downward-pointing arrow.+ pub fn label_brush(&self, text: &str, scale: f32, light: bool) -> Result<LabelBrush> {+ let (pad_x, pad_y, arrow) = (11.0 * scale, 5.0 * scale, 6.0 * scale);+ let (fill, ink) = if light {+ (rgb(0.96, 0.96, 0.97, 0.92), rgb(0.0, 0.0, 0.0, 0.88))+ } else {+ (rgb(0.13, 0.13, 0.14, 0.86), rgb(1.0, 1.0, 1.0, 0.95))+ };++ let utf16: Vec<u16> = text.encode_utf16().collect();+ // SAFETY: Strings and structures passed to each call remain alive for its duration.+ let (layout, metrics) = unsafe {+ let format = self.dwrite.CreateTextFormat(+ w!("Segoe UI Variable Text"),+ None,+ DWRITE_FONT_WEIGHT_MEDIUM,+ DWRITE_FONT_STYLE_NORMAL,+ DWRITE_FONT_STRETCH_NORMAL,+ 13.0 * scale,+ w!(""),+ )?;+ let layout = self+ .dwrite+ .CreateTextLayout(&utf16, &format, 4096.0, 256.0)?;+ let mut metrics = DWRITE_TEXT_METRICS::default();+ layout.GetMetrics(&mut metrics)?;+ (layout, metrics)+ };++ let body_height = (metrics.height + 2.0 * pad_y).ceil();+ let width = (metrics.width + 2.0 * pad_x).ceil();+ let height = body_height + arrow;+ let brush = self.draw(width as u32, height as u32, |dc| {+ let body = D2D1_ROUNDED_RECT {+ rect: D2D_RECT_F {+ left: 0.0,+ top: 0.0,+ right: width,+ bottom: body_height,+ },+ radiusX: 7.0 * scale,+ radiusY: 7.0 * scale,+ };+ let middle = width / 2.0;+ // SAFETY: All created objects remain alive until the end of the block.+ unsafe {+ let fill = dc.CreateSolidColorBrush(&fill, None)?;+ dc.FillRoundedRectangle(&body, &fill);++ // The arrow triangle hangs from the center of the pill and+ // overlaps it by 1 px to avoid a visible seam.+ let triangle = dc.GetFactory()?.CreatePathGeometry()?;+ let sink = triangle.Open()?;+ sink.BeginFigure(+ Vector2 {+ X: middle - arrow,+ Y: body_height - 1.0,+ },+ D2D1_FIGURE_BEGIN_FILLED,+ );+ sink.AddLine(Vector2 {+ X: middle + arrow,+ Y: body_height - 1.0,+ });+ sink.AddLine(Vector2 {+ X: middle,+ Y: height,+ });+ sink.EndFigure(D2D1_FIGURE_END_CLOSED);+ sink.Close()?;+ dc.FillGeometry(&triangle, &fill, None);++ let ink = dc.CreateSolidColorBrush(&ink, None)?;+ dc.DrawTextLayout(+ Vector2 { X: pad_x, Y: pad_y },+ &layout,+ &ink,+ D2D1_DRAW_TEXT_OPTIONS_NONE,+ );+ }+ Ok(())+ })?;+ Ok(LabelBrush {+ brush,+ width,+ height,+ })+ }++ /// Start tile: a 3x3 grid of rounded squares on a blue gradient, in the+ /// style of the other dock icons (no Windows logo: it is a trademark).+ pub fn start_brush(&self, side: u32) -> Result<CompositionSurfaceBrush> {+ let size = side as f32;+ self.draw(side, side, |dc| {+ // Same margin and corner ratio as a macOS app icon.+ let inset = size * 0.08;+ let tile = D2D_RECT_F {+ left: inset,+ top: inset,+ right: size - inset,+ bottom: size - inset,+ };+ let radius = (size - 2.0 * inset) * 0.225;+ let stops = [+ D2D1_GRADIENT_STOP {+ position: 0.0,+ color: rgb(0.40, 0.80, 1.0, 1.0),+ },+ D2D1_GRADIENT_STOP {+ position: 1.0,+ color: rgb(0.04, 0.42, 0.95, 1.0),+ },+ ];+ // SAFETY: Brushes and geometry live for the duration of the drawing calls.+ unsafe {+ let collection = dc.CreateGradientStopCollection(+ &stops,+ D2D1_COLOR_SPACE_SRGB,+ D2D1_COLOR_SPACE_SRGB,+ D2D1_BUFFER_PRECISION_8BPC_UNORM,+ D2D1_EXTEND_MODE_CLAMP,+ D2D1_COLOR_INTERPOLATION_MODE_PREMULTIPLIED,+ )?;+ let gradient = dc.CreateLinearGradientBrush(+ &D2D1_LINEAR_GRADIENT_BRUSH_PROPERTIES {+ startPoint: Vector2 {+ X: 0.0,+ Y: tile.top,+ },+ endPoint: Vector2 {+ X: 0.0,+ Y: tile.bottom,+ },+ },+ None,+ &collection,+ )?;+ dc.FillRoundedRectangle(+ &D2D1_ROUNDED_RECT {+ rect: tile,+ radiusX: radius,+ radiusY: radius,+ },+ &gradient,+ );++ let white = dc.CreateSolidColorBrush(&rgb(1.0, 1.0, 1.0, 0.95), None)?;+ let grid = size * 0.46;+ let cell = grid / 3.0;+ let square = cell * 0.72;+ let origin = (size - grid) / 2.0 + (cell - square) / 2.0;+ for row in 0..3 {+ for column in 0..3 {+ let left = origin + column as f32 * cell;+ let top = origin + row as f32 * cell;+ dc.FillRoundedRectangle(+ &D2D1_ROUNDED_RECT {+ rect: D2D_RECT_F {+ left,+ top,+ right: left + square,+ bottom: top + square,+ },+ radiusX: square * 0.28,+ radiusY: square * 0.28,+ },+ &white,+ );+ }+ }+ }+ Ok(())+ })+ }+}++fn draw_image(+ dc: &ID2D1DeviceContext,+ image: &IconImage,+ width: f32,+ height: f32,+ interpolation: D2D1_INTERPOLATION_MODE,+) -> Result<()> {+ let properties = D2D1_BITMAP_PROPERTIES1 {+ pixelFormat: D2D1_PIXEL_FORMAT {+ format: DXGI_FORMAT_B8G8R8A8_UNORM,+ alphaMode: D2D1_ALPHA_MODE_PREMULTIPLIED,+ },+ dpiX: 96.0,+ dpiY: 96.0,+ bitmapOptions: D2D1_BITMAP_OPTIONS_NONE,+ ..Default::default()+ };+ let dest = D2D_RECT_F {+ left: 0.0,+ top: 0.0,+ right: width,+ bottom: height,+ };+ // SAFETY: `image.bgra` contains `width * height * 4` bytes and the stride is `width * 4`.+ unsafe {+ let bitmap = dc.CreateBitmap(+ D2D_SIZE_U {+ width: image.width,+ height: image.height,+ },+ Some(image.bgra.as_ptr().cast()),+ image.width * 4,+ &properties,+ )?;+ dc.DrawBitmap(&bitmap, Some(&dest), 1.0, interpolation, None, None);+ }+ Ok(())+}++const fn rgb(r: f32, g: f32, b: f32, a: f32) -> D2D1_COLOR_F {+ D2D1_COLOR_F { r, g, b, a }+}diff --git a/apps/dock/src/guard.rs b/apps/dock/src/guard.rsnew file mode 100644index 0000000..6379338--- /dev/null+++ b/apps/dock/src/guard.rs@@ -0,0 +1,50 @@+//! Watchdog process: a minimal second `muelle.exe` that waits for the dock to+//! exit (normally, after a failure, or via End Task) and then restores the+//! Windows taskbar.++use std::{env, os::windows::process::CommandExt, process::Command};++use anyhow::{Context, Result};+use muelle_shell::{power, system::set_window_transitions, taskbar, tracker::WindowTracker};+use windows::Win32::{+ Foundation::CloseHandle,+ System::Threading::{INFINITE, OpenProcess, PROCESS_SYNCHRONIZE, WaitForSingleObject},+};++pub const FLAG: &str = "--guard";++/// Starts without a console in its own process group so Ctrl+C in the dock's+/// terminal does not also terminate the watchdog.+const DETACHED_PROCESS: u32 = 0x0000_0008;+const CREATE_NEW_PROCESS_GROUP: u32 = 0x0000_0200;++pub fn spawn() -> Result<()> {+ let exe = env::current_exe().context("no se pudo localizar muelle.exe")?;+ Command::new(exe)+ .args([FLAG, &std::process::id().to_string()])+ .creation_flags(DETACHED_PROCESS | CREATE_NEW_PROCESS_GROUP)+ .spawn()+ .context("no se pudo lanzar el proceso guardián")?;+ Ok(())+}++/// Watchdog body: waits for dock process `pid` and restores the taskbar.+pub fn run(pid: u32) -> Result<()> {+ // The watchdog may wait for weeks, so it should not compete for CPU or memory.+ power::run_as_background_process();+ // SAFETY: The handle is closed after the wait.+ unsafe {+ let process = OpenProcess(PROCESS_SYNCHRONIZE, false, pid)+ .context("el dock a vigilar ya no existe")?;+ WaitForSingleObject(process, INFINITE);+ let _ = CloseHandle(process);+ }+ // If the dock exited cleanly, it already restored the taskbar; repeating this is harmless.+ taskbar::give_back();+ // The dock turns off window transitions while it runs (genie effect); if+ // it died without restoring them, do it here.+ for window in WindowTracker::default().list() {+ set_window_transitions(window.hwnd, true);+ }+ Ok(())+}diff --git a/apps/dock/src/main.rs b/apps/dock/src/main.rsnew file mode 100644index 0000000..2d1fa06--- /dev/null+++ b/apps/dock/src/main.rs@@ -0,0 +1,95 @@+//! Muelle: a macOS-style dock for Windows 11.+//!+//! Usage:+//! - `muelle` starts the dock (does nothing if already running)+//! - `muelle --quit` closes the running dock+//! - `muelle --restore` restores the Windows taskbar+//! - `muelle --autostart on|off` enables or disables startup with Windows+//! - `muelle --guard <pid>` internal watchdog process++#![cfg_attr(not(debug_assertions), windows_subsystem = "windows")]++mod app;+mod drop;+mod flight;+mod gfx;+mod guard;+mod menu;+mod scene;+mod strings;+mod thumbnails;++use std::env;++use anyhow::{Context, Result, bail};+use muelle_shell::{autostart, taskbar};+use windows::{+ Win32::{+ Foundation::{ERROR_ALREADY_EXISTS, GetLastError},+ System::{+ Threading::CreateMutexW,+ WinRT::{+ CreateDispatcherQueueController, DQTAT_COM_STA, DQTYPE_THREAD_CURRENT,+ DispatcherQueueOptions,+ },+ },+ UI::HiDpi::{DPI_AWARENESS_CONTEXT_PER_MONITOR_AWARE_V2, SetProcessDpiAwarenessContext},+ },+ core::w,+};++fn main() -> Result<()> {+ let args: Vec<String> = env::args().skip(1).collect();+ match args+ .iter()+ .map(String::as_str)+ .collect::<Vec<_>>()+ .as_slice()+ {+ [] => run_dock(),+ ["--quit"] => {+ app::request_quit();+ Ok(())+ }+ ["--restore"] => {+ app::request_quit();+ taskbar::give_back();+ Ok(())+ }+ ["--autostart", "on"] => {+ let exe = env::current_exe().context("no se pudo localizar muelle.exe")?;+ Ok(autostart::set(Some(&exe.to_string_lossy()))?)+ }+ ["--autostart", "off"] => Ok(autostart::set(None)?),+ [guard::FLAG, pid] => guard::run(pid.parse().context("pid no válido")?),+ _ => bail!("uso: muelle [--quit | --restore | --autostart on|off]"),+ }+}++fn run_dock() -> Result<()> {+ // SAFETY: The static name is valid; the handle is released when the process exits.+ let _single = unsafe { CreateMutexW(None, false, w!("Local\\Muelle.Dock"))? };+ // SAFETY: Reads the thread's last error immediately after the call.+ if unsafe { GetLastError() } == ERROR_ALREADY_EXISTS {+ eprintln!("muelle: ya hay un dock en marcha");+ return Ok(());+ }++ // SAFETY: Sets DPI awareness and initializes the dispatcher before creating windows.+ let _queue = unsafe {+ SetProcessDpiAwarenessContext(DPI_AWARENESS_CONTEXT_PER_MONITOR_AWARE_V2)?;+ // The compositor requires a dispatcher queue on its thread; this also+ // initializes COM, which icon extraction requires.+ CreateDispatcherQueueController(DispatcherQueueOptions {+ dwSize: size_of::<DispatcherQueueOptions>() as u32,+ threadType: DQTYPE_THREAD_CURRENT,+ apartmentType: DQTAT_COM_STA,+ })?+ };++ // Start the watchdog first so it can restore the taskbar if anything fails later.+ guard::spawn()?;+ let result = app::run();+ taskbar::give_back();+ result+}diff --git a/apps/dock/src/menu.rs b/apps/dock/src/menu.rsnew file mode 100644index 0000000..de57b69--- /dev/null+++ b/apps/dock/src/menu.rs@@ -0,0 +1,133 @@+//! Context menu implemented with the native Windows menu API. It supports+//! screen readers and keyboard navigation, and exists only while open.++use std::sync::OnceLock;++use windows::{+ Win32::{+ Foundation::{HWND, LPARAM, POINT, WPARAM},+ System::LibraryLoader::{GetProcAddress, LoadLibraryW},+ UI::WindowsAndMessaging::{+ AppendMenuW, CreatePopupMenu, DestroyMenu, GetForegroundWindow, MF_CHECKED, MF_GRAYED,+ MF_SEPARATOR, MF_STRING, PostMessageW, SetForegroundWindow, TPM_BOTTOMALIGN,+ TPM_CENTERALIGN, TPM_NONOTIFY, TPM_RETURNCMD, TPM_RIGHTBUTTON, TrackPopupMenuEx,+ WM_NULL,+ },+ },+ core::{HSTRING, PCSTR, PCWSTR, w},+};++pub enum MenuItem {+ Action {+ command: u32,+ label: String,+ checked: bool,+ enabled: bool,+ },+ Separator,+}++impl MenuItem {+ pub fn action(command: u32, label: impl Into<String>) -> Self {+ Self::Action {+ command,+ label: label.into(),+ checked: false,+ enabled: true,+ }+ }+}++/// Shows the menu with its bottom edge centered at `anchor` and returns the+/// selected command (`None` if dismissed).+///+/// Runs a modal loop that continues dispatching messages to dock windows.+/// The caller must not hold the app state while this function runs.+pub fn show(owner: HWND, items: &[MenuItem], anchor: POINT, dark: bool) -> Option<u32> {+ apply_theme(dark);+ // SAFETY: The menu is destroyed before returning, and strings live through each call.+ unsafe {+ let menu = CreatePopupMenu().ok()?;+ for item in items {+ let _ = match item {+ MenuItem::Separator => AppendMenuW(menu, MF_SEPARATOR, 0, PCWSTR::null()),+ MenuItem::Action {+ command,+ label,+ checked,+ enabled,+ } => {+ let mut flags = MF_STRING;+ if *checked {+ flags |= MF_CHECKED;+ }+ if !*enabled {+ flags |= MF_GRAYED;+ }+ AppendMenuW(+ menu,+ flags,+ *command as usize,+ &HSTRING::from(label.as_str()),+ )+ }+ };+ }++ // Without making the window foreground, TrackPopupMenu does not dismiss+ // the menu when the user clicks outside it.+ let previous = GetForegroundWindow();+ let _ = SetForegroundWindow(owner);+ let chosen = TrackPopupMenuEx(+ menu,+ (TPM_RETURNCMD | TPM_NONOTIFY | TPM_RIGHTBUTTON | TPM_BOTTOMALIGN | TPM_CENTERALIGN).0,+ anchor.x,+ anchor.y,+ owner,+ None,+ );+ let _ = PostMessageW(Some(owner), WM_NULL, WPARAM(0), LPARAM(0));+ let _ = DestroyMenu(menu);++ let chosen = u32::try_from(chosen.0).ok().filter(|&command| command != 0);+ if chosen.is_none() {+ // Dismissing without a selection restores the previous focus, as in macOS.+ let _ = SetForegroundWindow(previous);+ }+ chosen+ }+}++/// Windows has no public API for dark Win32 menus, so this uses `uxtheme.dll`+/// functions by ordinal, as Windows Terminal and Notepad++ do. If unavailable+/// on another Windows version, the menu remains light.+fn apply_theme(dark: bool) {+ type SetPreferredAppMode = unsafe extern "system" fn(i32) -> i32;+ type FlushMenuThemes = unsafe extern "system" fn();+ const FORCE_DARK: i32 = 2;+ const FORCE_LIGHT: i32 = 3;++ static FUNCTIONS: OnceLock<Option<(SetPreferredAppMode, FlushMenuThemes)>> = OnceLock::new();+ let functions = FUNCTIONS.get_or_init(|| {+ // SAFETY: Functions exported at these ordinals have these signatures+ // since Windows 10 1903, and the library is never unloaded.+ unsafe {+ let module = LoadLibraryW(w!("uxtheme.dll")).ok()?;+ let set = GetProcAddress(module, PCSTR(135 as *const u8))?;+ let flush = GetProcAddress(module, PCSTR(136 as *const u8))?;+ Some((+ std::mem::transmute::<unsafe extern "system" fn() -> isize, SetPreferredAppMode>(+ set,+ ),+ std::mem::transmute::<unsafe extern "system" fn() -> isize, FlushMenuThemes>(flush),+ ))+ }+ });+ if let Some((set, flush)) = functions {+ // SAFETY: The function is resolved from the loaded module using its documented ordinal.+ unsafe {+ set(if dark { FORCE_DARK } else { FORCE_LIGHT });+ flush();+ }+ }+}diff --git a/apps/dock/src/scene.rs b/apps/dock/src/scene.rsnew file mode 100644index 0000000..103ada4--- /dev/null+++ b/apps/dock/src/scene.rs@@ -0,0 +1,396 @@+//! Dock visual tree: shadow, glass, specular border, dividers, icons, indicators,+//! and labels. It is built once per configuration; only its elements move per frame.++use anyhow::Result;+use muelle_core::{+ layout::{ItemKind, Layout, Rect},+ magnify::Magnified,+};+use windows::{+ UI::{+ Color,+ Composition::{+ CompositionBrush, CompositionColorSpace, CompositionRoundedRectangleGeometry,+ CompositionSurfaceBrush, ContainerVisual, ShapeVisual, SpriteVisual, Visual,+ },+ },+ core::Interface,+};+use windows_numerics::{Vector2, Vector3};++use crate::gfx::{Gfx, LabelBrush};++#[derive(Clone, Copy)]+pub struct Theme {+ pub light: bool,+ tint: Color,+ separator: Color,+ shadow: Color,+ indicator: Color,+}++impl Theme {+ pub fn for_system(light: bool) -> Self {+ if light {+ Self {+ light,+ tint: rgba(255, 255, 255, 46),+ separator: rgba(0, 0, 0, 56),+ shadow: rgba(0, 0, 0, 56),+ indicator: rgba(0, 0, 0, 170),+ }+ } else {+ Self {+ light,+ tint: rgba(28, 28, 30, 82),+ separator: rgba(255, 255, 255, 64),+ shadow: rgba(0, 0, 0, 96),+ indicator: rgba(255, 255, 255, 215),+ }+ }+ }+}++const fn rgba(r: u8, g: u8, b: u8, a: u8) -> Color {+ Color {+ A: a,+ R: r,+ G: g,+ B: b,+ }+}++fn v2(x: f32, y: f32) -> Vector2 {+ Vector2 { X: x, Y: y }+}++fn v3(x: f32, y: f32) -> Vector3 {+ Vector3 { X: x, Y: y, Z: 0.0 }+}++#[derive(Clone, Copy, Default)]+pub struct SlotContent<'a> {+ pub icon: Option<&'a CompositionSurfaceBrush>,+ pub label: Option<&'a LabelBrush>,+ pub running: bool,+ /// App icon shown in the corner of a minimized-window thumbnail.+ pub badge: Option<&'a CompositionSurfaceBrush>,+}++pub struct SceneInput<'a> {+ pub layout: &'a Layout,+ pub contents: &'a [SlotContent<'a>],+ pub theme: Theme,+ pub scale: f32,+ pub origin: (f32, f32),+ /// Shown above an icon dragged out of the dock.+ pub remove_label: Option<&'a LabelBrush>,+}++/// App badge on a minimized-window thumbnail: side relative to the slot, and+/// how much of it lies inside the slot.+pub const BADGE_SIZE: f32 = 0.42;+pub const BADGE_INSIDE: f32 = 0.85;++/// An icon following the cursor while it is dragged.+#[derive(Clone, Copy)]+pub struct Drag {+ pub index: usize,+ /// Icon center, relative to the resting dock origin.+ pub center: (f32, f32),+ /// Released here, the icon would leave the dock.+ pub removing: bool,+}++/// Everything that changes from one frame to the next.+pub struct Frame<'a> {+ pub state: &'a Magnified,+ pub hovered: Option<usize>,+ pub lifts: &'a [f32],+ pub drag: Option<Drag>,+ /// Vertical offset of the whole dock (auto-hide), in pixels.+ pub slide: f32,+ /// Align to whole pixels; only at rest, where sharpness matters.+ pub snap: bool,+}++struct Label {+ visual: SpriteVisual,+ width: f32,+ height: f32,+}++impl Label {+ fn new(c: &windows::UI::Composition::Compositor, brush: &LabelBrush) -> Result<Self> {+ let visual = c.CreateSpriteVisual()?;+ visual.SetSize(v2(brush.width, brush.height))?;+ visual.SetBrush(&brush.brush)?;+ visual.SetIsVisible(false)?;+ Ok(Self {+ visual,+ width: brush.width,+ height: brush.height,+ })+ }+}++pub struct Scene {+ pub root: ContainerVisual,+ origin: (f32, f32),+ height: f32,+ stroke: f32,+ label_gap: f32,+ indicator_size: f32,+ indicator_y: f32,+ frames: [Visual; 3],+ outline: CompositionRoundedRectangleGeometry,+ rim_geometry: CompositionRoundedRectangleGeometry,+ slots: Vec<SpriteVisual>,+ badges: Vec<Option<SpriteVisual>>,+ indicators: Vec<Option<ShapeVisual>>,+ labels: Vec<Option<Label>>,+ remove_label: Option<Label>,+}++impl Scene {+ pub fn build(gfx: &Gfx, input: &SceneInput<'_>) -> Result<Self> {+ let c = &gfx.compositor;+ let SceneInput {+ layout,+ theme,+ scale,+ origin,+ ..+ } = *input;+ let radius = layout.height * 0.36;++ let root = c.CreateContainerVisual()?;+ root.SetRelativeSizeAdjustment(v2(1.0, 1.0))?;+ let layers = root.Children()?;++ let shadow = c.CreateDropShadow()?;+ let mask = c.CreateNineGridBrush()?;+ mask.SetSource(&gfx.rounded_mask(radius)?)?;+ mask.SetInsets(radius.ceil() + 1.0)?;+ shadow.SetMask(&mask)?;+ shadow.SetBlurRadius(22.0 * scale)?;+ shadow.SetOffset(v3(0.0, 8.0 * scale))?;+ shadow.SetColor(theme.shadow)?;+ let shadow_host = c.CreateSpriteVisual()?;+ shadow_host.SetShadow(&shadow)?;+ layers.InsertAtTop(&shadow_host)?;++ let glass = c.CreateContainerVisual()?;+ let outline = c.CreateRoundedRectangleGeometry()?;+ outline.SetCornerRadius(v2(radius, radius))?;+ glass.SetClip(&c.CreateGeometricClipWithGeometry(&outline)?)?;++ let sheen = c.CreateLinearGradientBrush()?;+ sheen.SetStartPoint(v2(0.0, 0.0))?;+ sheen.SetEndPoint(v2(0.0, 1.0))?;+ let stops = sheen.ColorStops()?;+ stops+ .Append(&c.CreateColorGradientStopWithOffsetAndColor(0.0, rgba(255, 255, 255, 38))?)?;+ stops+ .Append(&c.CreateColorGradientStopWithOffsetAndColor(0.55, rgba(255, 255, 255, 0))?)?;++ let fills: [CompositionBrush; 3] = [+ c.CreateHostBackdropBrush()?.cast()?,+ c.CreateColorBrushWithColor(theme.tint)?.cast()?,+ sheen.cast()?,+ ];+ for brush in &fills {+ let fill = c.CreateSpriteVisual()?;+ fill.SetRelativeSizeAdjustment(v2(1.0, 1.0))?;+ fill.SetBrush(brush)?;+ glass.Children()?.InsertAtTop(&fill)?;+ }+ layers.InsertAtTop(&glass)?;++ let stroke = scale.max(1.0);+ let rim_brush = c.CreateLinearGradientBrush()?;+ rim_brush.SetStartPoint(v2(0.0, 0.0))?;+ rim_brush.SetEndPoint(v2(1.0, 1.0))?;+ rim_brush.SetInterpolationSpace(CompositionColorSpace::RgbLinear)?;+ let stops = rim_brush.ColorStops()?;+ for (at, alpha) in [(0.0, 150), (0.35, 40), (0.65, 30), (1.0, 105)] {+ stops.Append(+ &c.CreateColorGradientStopWithOffsetAndColor(at, rgba(255, 255, 255, alpha))?,+ )?;+ }+ let rim_geometry = c.CreateRoundedRectangleGeometry()?;+ rim_geometry.SetOffset(v2(stroke / 2.0, stroke / 2.0))?;+ rim_geometry.SetCornerRadius(v2(radius - stroke / 2.0, radius - stroke / 2.0))?;+ let rim_shape = c.CreateSpriteShapeWithGeometry(&rim_geometry)?;+ rim_shape.SetStrokeBrush(&rim_brush)?;+ rim_shape.SetStrokeThickness(stroke)?;+ let rim = c.CreateShapeVisual()?;+ rim.Shapes()?.Append(&rim_shape)?;+ layers.InsertAtTop(&rim)?;++ let content = c.CreateContainerVisual()?;+ content.SetOffset(v3(origin.0, origin.1))?;+ let children = content.Children()?;+ let indicator_size = (4.0 * scale).round();+ let dot = c.CreateEllipseGeometry()?;+ dot.SetCenter(v2(indicator_size / 2.0, indicator_size / 2.0))?;+ dot.SetRadius(v2(indicator_size / 2.0, indicator_size / 2.0))?;+ let dot_brush = c.CreateColorBrushWithColor(theme.indicator)?;++ let mut slots = Vec::with_capacity(layout.slots.len());+ let mut badges = Vec::with_capacity(layout.slots.len());+ let mut indicators = Vec::with_capacity(layout.slots.len());+ let mut labels = Vec::with_capacity(layout.slots.len());+ for (slot, item) in layout.slots.iter().zip(input.contents) {+ let visual = c.CreateSpriteVisual()?;+ match (slot.kind, item.icon) {+ (ItemKind::Separator, _) => {+ visual.SetBrush(&c.CreateColorBrushWithColor(theme.separator)?)?;+ }+ (ItemKind::Icon, Some(icon)) => visual.SetBrush(icon)?,+ (ItemKind::Icon, None) => {}+ }+ children.InsertAtTop(&visual)?;+ slots.push(visual);+ badges.push(match item.badge {+ Some(brush) => {+ let badge = c.CreateSpriteVisual()?;+ badge.SetBrush(brush)?;+ children.InsertAtTop(&badge)?;+ Some(badge)+ }+ None => None,+ });++ indicators.push(if item.running {+ let shape = c.CreateSpriteShapeWithGeometry(&dot)?;+ shape.SetFillBrush(&dot_brush)?;+ let visual = c.CreateShapeVisual()?;+ visual.SetSize(v2(indicator_size, indicator_size))?;+ visual.Shapes()?.Append(&shape)?;+ children.InsertAtTop(&visual)?;+ Some(visual)+ } else {+ None+ });++ labels.push(item.label.map(|label| Label::new(c, label)).transpose()?);+ }++ let remove_label = input+ .remove_label+ .map(|label| Label::new(c, label))+ .transpose()?;+ for label in labels.iter().flatten().chain(&remove_label) {+ children.InsertAtTop(&label.visual)?;+ }+ layers.InsertAtTop(&content)?;++ Ok(Self {+ root,+ origin,+ height: layout.height,+ stroke,+ label_gap: 8.0 * scale,+ indicator_size,+ indicator_y: layout.height - indicator_size - (2.0 * scale).round(),+ frames: [shadow_host.cast()?, glass.cast()?, rim.cast()?],+ outline,+ rim_geometry,+ slots,+ badges,+ indicators,+ labels,+ remove_label,+ })+ }++ /// - `lifts`: how far each slot rises above its resting position (bounce).+ /// - `snap`: whether to align to pixels. Used at rest for sharpness; fractional+ /// positions are retained during movement for smooth animation.+ pub fn apply(&self, frame: &Frame<'_>) -> Result<()> {+ let Frame {+ state,+ hovered,+ lifts,+ drag,+ slide,+ snap,+ } = *frame;+ let fit = |value: f32| if snap { value.round() } else { value };+ self.root.SetOffset(v3(0.0, slide))?;++ let size = v2(fit(state.right - state.left), self.height);+ let offset = v3(self.origin.0 + fit(state.left), self.origin.1);+ for frame in &self.frames {+ frame.SetSize(size)?;+ frame.SetOffset(offset)?;+ }+ self.outline.SetSize(size)?;+ self.rim_geometry+ .SetSize(v2(size.X - self.stroke, size.Y - self.stroke))?;++ for (index, rect) in state.rects.iter().enumerate() {+ let Rect {+ x,+ y,+ width,+ height,+ } = *rect;+ let dragged = drag.filter(|drag| drag.index == index);+ let (x, y) = match dragged {+ Some(drag) => (drag.center.0 - width / 2.0, drag.center.1 - height / 2.0),+ None => (x, y - lifts.get(index).copied().unwrap_or(0.0)),+ };++ if let Some(visual) = self.slots.get(index) {+ visual.SetOffset(v3(fit(x), fit(y)))?;+ visual.SetSize(v2(fit(width), fit(height)))?;+ let removing = dragged.is_some_and(|drag| drag.removing);+ visual.SetOpacity(if removing { 0.55 } else { 1.0 })?;+ }+ if let Some(Some(badge)) = self.badges.get(index) {+ let side = width * BADGE_SIZE;+ badge.SetSize(v2(fit(side), fit(side)))?;+ badge.SetOffset(v3(+ fit(x + width - side * BADGE_INSIDE),+ fit(y + height - side * BADGE_INSIDE),+ ))?;+ }+ if let Some(Some(indicator)) = self.indicators.get(index) {+ indicator.SetIsVisible(dragged.is_none())?;+ indicator.SetOffset(v3(+ fit(x + (width - self.indicator_size) / 2.0),+ self.indicator_y,+ ))?;+ }+ if let Some(Some(label)) = self.labels.get(index) {+ let shown = hovered == Some(index) && drag.is_none();+ label.visual.SetIsVisible(shown)?;+ if shown {+ self.place_label(label, x, y, width)?;+ }+ }+ if let (Some(label), Some(drag)) = (&self.remove_label, dragged) {+ label.visual.SetIsVisible(drag.removing)?;+ if drag.removing {+ self.place_label(label, x, y, width)?;+ }+ }+ }+ if drag.is_none()+ && let Some(label) = &self.remove_label+ {+ label.visual.SetIsVisible(false)?;+ }+ Ok(())+ }++ fn place_label(&self, label: &Label, x: f32, y: f32, width: f32) -> Result<()> {+ label.visual.SetOffset(v3(+ (x + (width - label.width) / 2.0).round(),+ (y - self.label_gap - label.height).round(),+ ))?;+ Ok(())+ }+}diff --git a/apps/dock/src/strings.rs b/apps/dock/src/strings.rsnew file mode 100644index 0000000..7d1f936--- /dev/null+++ b/apps/dock/src/strings.rs@@ -0,0 +1,79 @@+//! User-facing dock text in Spanish and English. The language follows the+//! Windows display language; Settings will be able to override it (phase 7).+//! `&` marks the menu access key.++use std::sync::atomic::{AtomicU8, Ordering};++use muelle_config::Language;+use muelle_shell::system::ui_language_is_spanish;++pub struct Strings {+ pub open: &'static str,+ pub new_window: &'static str,+ pub keep_in_dock: &'static str,+ pub show_in_explorer: &'static str,+ pub quit_app: &'static str,+ pub empty_bin: &'static str,+ pub turn_hiding_on: &'static str,+ pub turn_hiding_off: &'static str,+ pub quit_dock: &'static str,+ pub start: &'static str,+ pub remove: &'static str,+ pub close_window: &'static str,+ pub settings: &'static str,+}++const ES: Strings = Strings {+ open: "&Abrir",+ new_window: "&Nueva ventana",+ keep_in_dock: "&Mantener en el Dock",+ show_in_explorer: "Mostrar en el &Explorador",+ quit_app: "&Salir",+ empty_bin: "&Vaciar papelera",+ turn_hiding_on: "Activar &ocultación automática",+ turn_hiding_off: "Desactivar &ocultación automática",+ quit_dock: "Salir de &Muelle",+ start: "Inicio",+ remove: "Quitar",+ close_window: "&Cerrar",+ settings: "&Ajustes de Muelle…",+};++const EN: Strings = Strings {+ open: "&Open",+ new_window: "&New Window",+ keep_in_dock: "&Keep in Dock",+ show_in_explorer: "Show in &Explorer",+ quit_app: "&Quit",+ empty_bin: "&Empty Recycle Bin",+ turn_hiding_on: "Turn Hiding &On",+ turn_hiding_off: "Turn Hiding &Off",+ quit_dock: "Quit &Muelle",+ start: "Start",+ remove: "Remove",+ close_window: "&Close",+ settings: "Muelle &Settings…",+};++/// 0 = not chosen yet (follow Windows), 1 = Spanish, 2 = English.+static LANGUAGE: AtomicU8 = AtomicU8::new(0);++pub fn set_language(language: Language) {+ let spanish = match language {+ Language::Auto => ui_language_is_spanish(),+ Language::Es => true,+ Language::En => false,+ };+ LANGUAGE.store(if spanish { 1 } else { 2 }, Ordering::Relaxed);+}++pub fn text() -> &'static Strings {+ match LANGUAGE.load(Ordering::Relaxed) {+ 0 => {+ set_language(Language::Auto);+ text()+ }+ 1 => &ES,+ _ => &EN,+ }+}diff --git a/apps/dock/src/thumbnails.rs b/apps/dock/src/thumbnails.rsnew file mode 100644index 0000000..4bdc443--- /dev/null+++ b/apps/dock/src/thumbnails.rs@@ -0,0 +1,140 @@+//! Live thumbnails of minimized windows, composed by DWM into the dock's+//! visual window (the same mechanism as taskbar previews). They cost DWM work,+//! not dock memory.++use std::collections::HashMap;++use windows::Win32::{+ Foundation::{HWND, RECT},+ Graphics::Dwm::{+ DWM_THUMBNAIL_PROPERTIES, DWM_TNP_OPACITY, DWM_TNP_RECTDESTINATION,+ DWM_TNP_SOURCECLIENTAREAONLY, DWM_TNP_VISIBLE, DwmQueryThumbnailSourceSize,+ DwmRegisterThumbnail, DwmUnregisterThumbnail, DwmUpdateThumbnailProperties,+ },+};++/// Fraction of the slot left empty around the thumbnail.+const INSET: f32 = 0.06;++struct Thumbnail {+ handle: isize,+ /// Last destination applied, to skip redundant DWM calls.+ placed: Option<(RECT, u8)>,+}++impl Drop for Thumbnail {+ fn drop(&mut self) {+ // SAFETY: `handle` came from DwmRegisterThumbnail and is released once.+ unsafe {+ let _ = DwmUnregisterThumbnail(self.handle);+ }+ }+}++pub struct Thumbnails {+ destination: HWND,+ live: HashMap<isize, Thumbnail>,+}++impl Thumbnails {+ pub fn new(destination: HWND) -> Self {+ Self {+ destination,+ live: HashMap::new(),+ }+ }++ /// Keeps one thumbnail per window in `windows`, releasing the others.+ pub fn sync(&mut self, windows: &[isize]) {+ self.live.retain(|hwnd, _| windows.contains(hwnd));+ for &hwnd in windows {+ if self.live.contains_key(&hwnd) {+ continue;+ }+ // SAFETY: Both windows exist; a source that just closed makes the call fail.+ if let Ok(handle) =+ unsafe { DwmRegisterThumbnail(self.destination, HWND(hwnd as *mut _)) }+ {+ self.live.insert(+ hwnd,+ Thumbnail {+ handle,+ placed: None,+ },+ );+ }+ }+ }++ /// Fits the window's thumbnail, keeping its aspect ratio, inside `slot`+ /// (client coordinates of the destination window). DWM draws thumbnails+ /// above all of the window's own content, so the fraction `corner` of the+ /// slot's bottom-right corner is left free for the app badge. `opacity` 0 hides it.+ pub fn place(&mut self, hwnd: isize, slot: (f32, f32, f32, f32), corner: f32, opacity: u8) {+ let Some(thumbnail) = self.live.get_mut(&hwnd) else {+ return;+ };+ let (x, y, width, height) = slot;+ // SAFETY: Valid thumbnail handle; on failure the size stays zero.+ let source = unsafe { DwmQueryThumbnailSourceSize(thumbnail.handle) }.unwrap_or_default();+ let ratio = if source.cx > 0 && source.cy > 0 {+ source.cx as f32 / source.cy as f32+ } else {+ 1.0+ };+ let fit = |box_width: f32, box_height: f32| {+ if ratio >= box_width / box_height {+ (box_width, box_width / ratio)+ } else {+ (box_height * ratio, box_height)+ }+ };+ let (inner_width, inner_height) =+ (width * (1.0 - 2.0 * INSET), height * (1.0 - 2.0 * INSET));+ // Either the band above the badge or the band to its left, whichever+ // gives the larger thumbnail.+ let above = fit(inner_width, height * (1.0 - corner - INSET));+ let beside = fit(width * (1.0 - corner - INSET), inner_height);+ let use_beside = corner > 0.0 && beside.0 * beside.1 > above.0 * above.1;+ let (fit_width, fit_height) = if corner <= 0.0 {+ fit(inner_width, inner_height)+ } else if use_beside {+ beside+ } else {+ above+ };+ // Centered horizontally unless it sits beside the badge.+ let left = if use_beside {+ x + width * INSET+ } else {+ x + width * INSET + (inner_width - fit_width) / 2.0+ };+ let top = y + height * INSET;+ let destination = RECT {+ left: left.round() as i32,+ top: top.round() as i32,+ right: (left + fit_width).round() as i32,+ bottom: (top + fit_height).round() as i32,+ };+ if thumbnail.placed == Some((destination, opacity)) {+ return;+ }+ thumbnail.placed = Some((destination, opacity));++ let properties = DWM_THUMBNAIL_PROPERTIES {+ dwFlags: DWM_TNP_RECTDESTINATION+ | DWM_TNP_VISIBLE+ | DWM_TNP_OPACITY+ | DWM_TNP_SOURCECLIENTAREAONLY,+ rcDestination: destination,+ opacity,+ fVisible: (opacity > 0).into(),+ fSourceClientAreaOnly: false.into(),+ ..Default::default()+ };+ // SAFETY: Valid handle and properties structure.+ unsafe {+ let _ = DwmUpdateThumbnailProperties(thumbnail.handle, &properties);+ }+ }+}diff --git a/apps/settings/index.html b/apps/settings/index.htmlnew file mode 100644index 0000000..193489f--- /dev/null+++ b/apps/settings/index.html@@ -0,0 +1,12 @@+<!doctype html>+<html lang="es">+ <head>+ <meta charset="UTF-8" />+ <meta name="viewport" content="width=device-width, initial-scale=1.0" />+ <title>Muelle</title>+ </head>+ <body>+ <div id="root"></div>+ <script type="module" src="/src/main.tsx"></script>+ </body>+</html>diff --git a/apps/settings/package.json b/apps/settings/package.jsonnew file mode 100644index 0000000..3a99abc--- /dev/null+++ b/apps/settings/package.json@@ -0,0 +1,24 @@+{+ "name": "muelle-settings",+ "private": true,+ "version": "0.1.0",+ "type": "module",+ "scripts": {+ "dev": "vite",+ "build": "tsc --noEmit && vite build",+ "tauri": "tauri"+ },+ "dependencies": {+ "@tauri-apps/api": "^2",+ "react": "^19",+ "react-dom": "^19"+ },+ "devDependencies": {+ "@tauri-apps/cli": "^2",+ "@types/react": "^19",+ "@types/react-dom": "^19",+ "@vitejs/plugin-react": "^5",+ "typescript": "^5",+ "vite": "^7"+ }+}diff --git a/apps/settings/pnpm-lock.yaml b/apps/settings/pnpm-lock.yamlnew file mode 100644index 0000000..20ffee0--- /dev/null+++ b/apps/settings/pnpm-lock.yaml@@ -0,0 +1,1277 @@+lockfileVersion: '9.0'++settings:+ autoInstallPeers: true+ excludeLinksFromLockfile: false++importers:++ .:+ dependencies:+ '@tauri-apps/api':+ specifier: ^2+ version: 2.12.4+ react:+ specifier: ^19+ version: 19.3.1+ react-dom:+ specifier: ^19+ version: 19.3.1([email protected])+ devDependencies:+ '@tauri-apps/cli':+ specifier: ^2+ version: 2.12.4+ '@types/react':+ specifier: ^19+ version: 19.3.0+ '@types/react-dom':+ specifier: ^19+ version: 19.3.0(@types/[email protected])+ '@vitejs/plugin-react':+ specifier: ^5+ version: 5.2.0([email protected])+ typescript:+ specifier: ^5+ version: 5.9.3+ vite:+ specifier: ^7+ version: 7.3.8++packages:++ '@babel/[email protected]':+ resolution: {integrity: sha512-Aup7aUOfpbAUg2ROOJN6Iw5f9DMBlzu0mIkm/malLQFN/YQgO48wCj0Kxa3sEHJvPVFg7siR+qRInwXd2qhQKw==}+ engines: {node: '>=6.9.0'}++ '@babel/[email protected]':+ resolution: {integrity: sha512-locTkQyKvwIEgBzVrn8693ebc97F2U8ZHjbXwDXJ5Fn2TCpNwTlKcaKLkdHop5c/icOFE7qt7Q9JC5hnKNa6Gg==}+ engines: {node: '>=6.9.0'}++ '@babel/[email protected]':+ resolution: {integrity: sha512-j1nvOQCZYSgp7HLmisnCXFTpVvFODiijQ9QHkORfGKWH6YDtskTEeCJS7eV545GZ9UBzrq0e2xsOd5QQ5PjIqw==}+ engines: {node: '>=6.9.0'}++ '@babel/[email protected]':+ resolution: {integrity: sha512-qSY56jgW5JnSXzuekLVil6zaOQxOCtOHidr65KkaMBw772IuAY28Qx4ZykAcDn8+FRF15qk80XzKwgSc/RYW6g==}+ engines: {node: '>=6.9.0'}++ '@babel/[email protected]':+ resolution: {integrity: sha512-8WxJ4/Vmes3ghacj8VOJy3NW8eyHiFY/4thU/LSBuBE470+igjR/j1ZTNn8fV5VdNrLx6iXUwig526UdOvfP0w==}+ engines: {node: '>=6.9.0'}++ '@babel/[email protected]':+ resolution: {integrity: sha512-3nQVUAtvkKH9zahfWgw96Jc/uFOmjACE1kQz82E2lqWmHBgjzbNlsC22nuQTfahmWeQtTq5nQ/4Nnd2A1wj4zA==}+ engines: {node: '>=6.9.0'}++ '@babel/[email protected]':+ resolution: {integrity: sha512-ejHwrQQYcm9xnTivShn2IDOlIzInN34AXskvq9QicvCtEzq1Vzclu/tKF8Jq1Cg8JG2GL6/EmjgsCT7lXepE3g==}+ engines: {node: '>=6.9.0'}++ '@babel/[email protected]':+ resolution: {integrity: sha512-2XDvQVd9JESaOgGc4jT2/jquTAO7ppA5noTZQqH+MmZ89yjCzScLwtCPbWtkPZylL+TLWR49IwWmk+QkRR4GsA==}+ engines: {node: '>=6.9.0'}+ peerDependencies:+ '@babel/core': ^7.0.0++ '@babel/[email protected]':+ resolution: {integrity: sha512-G7sHYigPY17oO5SYWnfD/0MTBwVR781S/JI643e/JhUYgVgWE/61SoW3NH9KWUKyKq5LVh3npif99Wkt6j86Jw==}+ engines: {node: '>=6.9.0'}++ '@babel/[email protected]':+ resolution: {integrity: sha512-CXvKMFvM80ihI7Vox9jb+kQjnyjESQNPM+vB7U0Zz6TWuZA+Z/FL0QPMH300h33qJtIx+REeBhXqWOPW48TcAQ==}+ engines: {node: '>=6.9.0'}++ '@babel/[email protected]':+ resolution: {integrity: sha512-qehxGkRj55h/ff8EMaJ+cYhyaKlHIxqYDn682wQD7RNp9UujOQsHog2uS0r2vzr4pW+sXf90NeeayjcNaX3fFg==}+ engines: {node: '>=6.9.0'}++ '@babel/[email protected]':+ resolution: {integrity: sha512-N9ZErrD+yW5geCDtBqnOoxmR8+tNKiGuxKlDpuJxfsqpa2dFcexaziGAE/qoHLiDDreVNMupxGmSoNlyvsA3gw==}+ engines: {node: '>=6.9.0'}++ '@babel/[email protected]':+ resolution: {integrity: sha512-6E3Mi1r0B0umq6vmZa4/78q+64fqO2YY0THUdjDPKUCKhNb0yQy5NQIaPHCSD3ryTgiTss//P4JsWS80AsZ6LQ==}+ engines: {node: '>=6.9.0'}++ '@babel/[email protected]':+ resolution: {integrity: sha512-VL220vXuyO2z3rNIQwY7ftj9UwpqOt+33sH+sBWkOekbsSR2g7EEMnOx24ZlCH0xOA3DM/33SifVFGbnJD8r/w==}+ engines: {node: '>=6.0.0'}+ hasBin: true++ '@babel/[email protected]':+ resolution: {integrity: sha512-TL0hMc9xzy86VD31nUiwzd5otRAcyEPcsegCxolO0PvcXuH1v0kECe/UIznYFihpkvU5wg/jk4v0TTEFfm53fw==}+ engines: {node: '>=6.9.0'}+ peerDependencies:+ '@babel/core': ^7.0.0-0++ '@babel/[email protected]':+ resolution: {integrity: sha512-06IyK09H3wi4cGbhDBwp5gUGo0IKtnYa8tyTiephirPCK6fbobVGiXMMI5zLQ4aKEYP3wZ3ArU44o+8KMrSG/Q==}+ engines: {node: '>=6.9.0'}+ peerDependencies:+ '@babel/core': ^7.0.0-0++ '@babel/[email protected]':+ resolution: {integrity: sha512-puq+Gf35oI24FeN11LkoUQFqv9uwNeWpxXZi/Ji3rRIoKAzKnxRaZ+Gkj0vKS9ZCiTESfng1N9LyOyXvo+m+Gg==}+ engines: {node: '>=6.9.0'}++ '@babel/[email protected]':+ resolution: {integrity: sha512-RAdQJrBgmIH1FWvN0X+1hoDxzMzlP4cv/1Zi4dn4tG1H0cTb+rw7CzUxQJhp1f4ANd8j5vH3fy8BAWFGkBDEsA==}+ engines: {node: '>=6.9.0'}++ '@babel/[email protected]':+ resolution: {integrity: sha512-UjI/dKmwJwT9pOszJitq2G6EObZPnsZUfdCr92z2TlF3EZK9J3EdfOKUrCzHl6wFthbzwhzl1Soc/UIwxRiq6w==}+ engines: {node: '>=6.9.0'}++ '@esbuild/[email protected]':+ resolution: {integrity: sha512-XExcO+dvLKvVtNTibSTBej1NCAbaGhWn9Ww1ZPx80qsahhPFe/8jgWP0IchNe0F3HwkU7n8ejhH8bjonqht8mQ==}+ engines: {node: '>=18'}+ cpu: [ppc64]+ os: [aix]++ '@esbuild/[email protected]':+ resolution: {integrity: sha512-5YfKeeI8qWfBZIX+u2xZC3Zlb3Os/gLS2sbEKM+I4ZOcsWmHS2WLysCcQZDAFRslDUU5Oiq44gf6PYN1vGwG5A==}+ engines: {node: '>=18'}+ cpu: [arm64]+ os: [android]++ '@esbuild/[email protected]':+ resolution: {integrity: sha512-kXXoiPVVGQcnIYGOeaovwOURpniDBpSq4A03qkQ+BMQqtGG6HYap3xne9C1O1yo4TR3qxlCX5IqqmX6fFo2Lqg==}+ engines: {node: '>=18'}+ cpu: [arm]+ os: [android]++ '@esbuild/[email protected]':+ resolution: {integrity: sha512-O387ite7SzUyCcy3JQX4P4bLtEA7bLLkx+esve5JHnyYfNTxcVpXZo9jhdB0lTKN44gztELTdU7nS8Nr16Fs1Q==}+ engines: {node: '>=18'}+ cpu: [x64]+ os: [android]++ '@esbuild/[email protected]':+ resolution: {integrity: sha512-n4KqkOQrraxHJcgjM1RvwbigfQKIKJVpM7xp+KsxiyUSrRdIXnt73VhrPAx0fV44hgfmIVKjxMN9J1t5jySVkw==}+ engines: {node: '>=18'}+ cpu: [arm64]+ os: [darwin]++ '@esbuild/[email protected]':+ resolution: {integrity: sha512-uq6suIWYP37qzGddBKPw5QEQPi6HiLGsO7UmkpfyaYNQ3D+rN6w6WfwH+nuqcGXWvawGwxOEroO4YGnFh95azw==}+ engines: {node: '>=18'}+ cpu: [x64]+ os: [darwin]++ '@esbuild/[email protected]':+ resolution: {integrity: sha512-n+I0BTSRIoy+d6RPKnEVwql5UwBJolytvY4mAOIEJorKlqgPII8ix6slVVrfZ5Tnj7glIZvloylbB/EJPMWEXw==}+ engines: {node: '>=18'}+ cpu: [arm64]+ os: [freebsd]++ '@esbuild/[email protected]':+ resolution: {integrity: sha512-78XJTJkvPs0kz2w61301PJjXl4g7q3JqiYMZ/M/yVI73EHBrCRTgkhu9oqG7vPqq+a/yadEW8aD+agKlk5xrmg==}+ engines: {node: '>=18'}+ cpu: [x64]+ os: [freebsd]++ '@esbuild/[email protected]':+ resolution: {integrity: sha512-pW4AC0P3it8c7do9MVM4p51FzHzdM/TZrerurgRcHJ2WTa1VQ1CIq18xncfpBJw4ojkiZZrKW2yIBWBP92j6Ug==}+ engines: {node: '>=18'}+ cpu: [arm64]+ os: [linux]++ '@esbuild/[email protected]':+ resolution: {integrity: sha512-XlDnu2q5yoqems+xay6wSAcg9DDD7K9RLKZEBOMZm3ckNpJBvOX20tSfby8KfrrhINDyv9V2YVZKY/SpoGJI8w==}+ engines: {node: '>=18'}+ cpu: [arm]+ os: [linux]++ '@esbuild/[email protected]':+ resolution: {integrity: sha512-CYbnj78HsIeA+DhgUKgFCfvNsTHFhMMrinUrMZpDXJXKN8T3XViTZ/+wtHeVxEWY8ewSzTFN+nRmSwO2tZaLUQ==}+ engines: {node: '>=18'}+ cpu: [ia32]+ os: [linux]++ '@esbuild/[email protected]':+ resolution: {integrity: sha512-buwkd8nsph4R+ajRvw0qM5Hja/TXQow3ptzWO2EbG/cqcIkHloRrdlBtQlshyYGTNFvfkfJ5tpPLVkY4DtsPfQ==}+ engines: {node: '>=18'}+ cpu: [loong64]+ os: [linux]++ '@esbuild/[email protected]':+ resolution: {integrity: sha512-ZVykbDyk7519VwiNb9Lcj9m8XM6v5V9uKPvrEMkkEedVewf+0itkhahp4HDpgERXhwLRpWFypsGbG/J8s0QjJA==}+ engines: {node: '>=18'}+ cpu: [mips64el]+ os: [linux]++ '@esbuild/[email protected]':+ resolution: {integrity: sha512-CAXl+Dtd9UUuJd8pKKdwh6MLm3MUMiqMPmhZ3tTSXPqfyQ3vDl6R5hZdZ/kYojK4ofXtdfSv1tFq8XzWx3heNQ==}+ engines: {node: '>=18'}+ cpu: [ppc64]+ os: [linux]++ '@esbuild/[email protected]':+ resolution: {integrity: sha512-GeXCej4IQtU1B+QlDV8W/RRvbzI3O/Stss+/bCXv4lZls5WGRtu2a+3JkA3i4qIUlMXpcHebWpF8AkJhATowuA==}+ engines: {node: '>=18'}+ cpu: [riscv64]+ os: [linux]++ '@esbuild/[email protected]':+ resolution: {integrity: sha512-3H1weTYZPxt/WOhByszQZybS9w5lKzUn1FDMsgEChbHWQwHYQQRfBxgCcZvPhjHfKyJjIievvMmEUawJrdY9Dg==}+ engines: {node: '>=18'}+ cpu: [s390x]+ os: [linux]++ '@esbuild/[email protected]':+ resolution: {integrity: sha512-4xTZr1FUmSoQW4XIWmit3tzQrUTZM+N3P0XV8xROKYF50XfI7xeO90+1bZvNwxIufQ9hDQVRJH5YhgPVF8A/HQ==}+ engines: {node: '>=18'}+ cpu: [x64]+ os: [linux]++ '@esbuild/[email protected]':+ resolution: {integrity: sha512-sSATRjPeDBg3pdgHoQfoYBob11Kk1FGa9lui5RIHZCoCkJa9QKlvl3/vKz2usCmYYjs7ymJR/2Nnsqe+Hjt5nw==}+ engines: {node: '>=18'}+ cpu: [arm64]+ os: [netbsd]++ '@esbuild/[email protected]':+ resolution: {integrity: sha512-lqnzCV+mM0gIADaKihiCg6ifgfU2L3h5E33rNQBN1Y4MaVGnzryzmvvf7UHxprpQdE8hpqLolJ9Rl+SkIRDpyw==}+ engines: {node: '>=18'}+ cpu: [x64]+ os: [netbsd]++ '@esbuild/[email protected]':+ resolution: {integrity: sha512-AL2qJILH7lNjrDmCQDvdxMfAUIv8KMNZOvrwAQ8i8//ntL9FflhOyMJ8OZSMBb8/AWXe3/5v5S20y3zCoZWKoQ==}+ engines: {node: '>=18'}+ cpu: [arm64]+ os: [openbsd]++ '@esbuild/[email protected]':+ resolution: {integrity: sha512-QtiuPytchRyC4rwUKhexJdQKvDuZ6hWloi3igqPQNUJCS1/v9EiO3UTOXR6A3FoMo4fnAKbWJdqaIwhOzh8qEw==}+ engines: {node: '>=18'}+ cpu: [x64]+ os: [openbsd]++ '@esbuild/[email protected]':+ resolution: {integrity: sha512-WkhYDmpTjLvGlScA1rwjRUmhl4k8oXR3cIbtqWmELgU/dFeHHlEllxDvdWcNJV9rbzCexB5vz8gtNewWLgCT7Q==}+ engines: {node: '>=18'}+ cpu: [arm64]+ os: [openharmony]++ '@esbuild/[email protected]':+ resolution: {integrity: sha512-GPMSkTOtMnv2U2F8gxe4Io6qmVs+YKyp832Etqqxr0hFngmXQ3rzwytelm3GIn7T4VviRUlf3sOgBOiTdvaf7g==}+ engines: {node: '>=18'}+ cpu: [x64]+ os: [sunos]++ '@esbuild/[email protected]':+ resolution: {integrity: sha512-PIhhEkE9uPBleRBrQEJpUn7MBnibZzbGzYWPmY3x+YoVg/95zbjB4CxPPOQ8l5tYYM4mMaCthF8/1DIfBQQyWQ==}+ engines: {node: '>=18'}+ cpu: [arm64]+ os: [win32]++ '@esbuild/[email protected]':+ resolution: {integrity: sha512-YmJbfTlvU7Sdn9BB+4PRES4oB6pxgS37MAONj+hBr/cpXS1aBPKXxNnDbu+QCWPj0o9dgyxeq79g6c5P8KeuYA==}+ engines: {node: '>=18'}+ cpu: [ia32]+ os: [win32]++ '@esbuild/[email protected]':+ resolution: {integrity: sha512-5ebpxr3nWMzrL/rnUI755Jkuee0bHL/Gq0WTF9lvcpv73wAp5eu8MfBUgWK9bhWvZjj7yX8etf/8tI8Ney695g==}+ engines: {node: '>=18'}+ cpu: [x64]+ os: [win32]++ '@jridgewell/[email protected]':+ resolution: {integrity: sha512-2kkt/7niJ6MgEPxF0bYdQ6etZaA+fQvDcLKckhy1yIQOzaoKjBBjSj63/aLVjYE3qhRt5dvM+uUyfCg6UKCBbA==}++ '@jridgewell/[email protected]':+ resolution: {integrity: sha512-LI9u/+laYG4Ds1TDKSJW2YPrIlcVYOwi2fUC6xB43lueCjgxV4lffOCZCtYFiH6TNOX+tQKXx97T4IKHbhyHEQ==}++ '@jridgewell/[email protected]':+ resolution: {integrity: sha512-bRISgCIjP20/tbWSPWMEi54QVPRZExkuD9lJL+UIxUKtwVJA8wW1Trb1jMs1RFXo1CBTNZ/5hpC9QvmKWdopKw==}+ engines: {node: '>=6.0.0'}++ '@jridgewell/[email protected]':+ resolution: {integrity: sha512-T7jf+5zgsZHwNJ4lvQ7/aezbyk0nNX+zJVWpmHA7VYsEx7a7qr5Rg5IbtJFqkgze5Y2sruq1RUY8Q837Od7iFw==}++ '@jridgewell/[email protected]':+ resolution: {integrity: sha512-zzNR+SdQSDJzc8joaeP8QQoCQr8NuYx2dIIytl1QeBEZHJ9uW6hebsrYgbz8hJwUQao3TWCMtmfV8Nu1twOLAw==}++ '@rolldown/[email protected]':+ resolution: {integrity: sha512-eybk3TjzzzV97Dlj5c+XrBFW57eTNhzod66y9HrBlzJ6NsCrWCp/2kaPS3K9wJmurBC0Tdw4yPjXKZqlznim3Q==}++ '@rollup/[email protected]':+ resolution: {integrity: sha512-ItKrNMkEL3hy85kLBXwB0+M6CWWVI8vr7RV+Eb7oDlQIMXLaiEhGfdaj5jAUadYn2v3nwzAhIRl/nLyjAqV9vQ==}+ cpu: [arm]+ os: [android]++ '@rollup/[email protected]':+ resolution: {integrity: sha512-dCkT8BMPLo6X6GCFVtuzrnr981PpJSeK4ZO/d/mZdJ/ao61Qa1Usd/OHIQ69MQgw4qQclR/X6uRRUONiWwD8cw==}+ cpu: [arm64]+ os: [android]++ '@rollup/[email protected]':+ resolution: {integrity: sha512-p2jkKiscqQOGmyL6qu+KvJctvBc3SQTd+Xi2lQYn5QvFLEWz+QI8Z9iI+xcIjez6vKRsSnWP56Y3Ep7g3Stiug==}+ cpu: [x64]+ os: [android]++ '@rollup/[email protected]':+ resolution: {integrity: sha512-aVIfOteo5zoX8aL742H/S3QsyN6aokNYjdzrLnQBKxgRVoh4cibTErpi61RzSmrv2hBzDB1i751hwwdc8QK0vQ==}+ cpu: [arm64]+ os: [darwin]++ '@rollup/[email protected]':+ resolution: {integrity: sha512-+Wuf4TFTHiE/WnjKgH1SkNf/9D5ddoed1UR0p3jxjNAGemdeeQRL+r1bJ1LlZyha0VKDBYLB2U/a9a9KlSw4Kw==}+ cpu: [x64]+ os: [darwin]++ '@rollup/[email protected]':+ resolution: {integrity: sha512-feKK2dc13j/6D9mAp7XKhBM/VUqn0N/xRgP6rT7/mdRVVJUaeZ4lsJ9hN90aTi0k3OD+mkjlcN01vQ96Ac9VzQ==}+ cpu: [arm64]+ os: [freebsd]++ '@rollup/[email protected]':+ resolution: {integrity: sha512-s1oGXPGX1PNqdi9TLWD+RwtPEYf/BOTbCcq4anJBqNbzyjucti86ldYH37eKvsyTP7Bl5/Hf8XmbIxCz/iafTA==}+ cpu: [x64]+ os: [freebsd]++ '@rollup/[email protected]':+ resolution: {integrity: sha512-ksR3ZmzHrm6HOUP8UlDBy5hNTcG9cEIa3EyGnxn5BjorLRjBh4ucxhwjwwVEm0dqcIN4Egc/XjDUiPQwN1ic9A==}+ cpu: [arm]+ os: [linux]+ libc: [glibc]++ '@rollup/[email protected]':+ resolution: {integrity: sha512-STZVVBM35wULVsQah0xKfCBQMPpHliOfjnRaUNT35jrbpfapUrD8ix6Yhl7tLHW0xQSWotXSSghjUi/DclwRSw==}+ cpu: [arm]+ os: [linux]+ libc: [musl]++ '@rollup/[email protected]':+ resolution: {integrity: sha512-Fm/GPC2R0zlJYQIp9aY9L1lO2z+P+UrcvXG6fhubfo/BbMOLZlLXshnbECOTqr3pxfZFb6nNn0QgDETDtrX7TQ==}+ cpu: [arm64]+ os: [linux]+ libc: [glibc]++ '@rollup/[email protected]':+ resolution: {integrity: sha512-VoqlckWcwNF3WqsUkLZg91zYFgBvrC37Lc5e8AU+BKdCUFDMPoN0Rsin/LvF+rBVF527gWo5KT0oHkaAZaL1GA==}+ cpu: [arm64]+ os: [linux]+ libc: [musl]++ '@rollup/[email protected]':+ resolution: {integrity: sha512-Zr8X/SUf7Jjwxt99BqPDF/Wq+sz4oUBIP6HBaFQWwb8wO1nV6LBIpD6jB9cMybLho93Z+B8rrN0uXEL6oNOUJQ==}+ cpu: [loong64]+ os: [linux]+ libc: [glibc]++ '@rollup/[email protected]':+ resolution: {integrity: sha512-2EhrYEJNXIyhSZESwm/kCke1tiH7QAPOU3v3MsLM9J+Nfn2QCDe/pGROUAvYFK0BL2MEbzNgfrqrbnE5CFXkLw==}+ cpu: [loong64]+ os: [linux]+ libc: [musl]++ '@rollup/[email protected]':+ resolution: {integrity: sha512-IC0dYuEQknw0m2FYBNBKlbrgBJBH5OMRiaRfCc4CFSpYnmDnqTpNSv+TgX+loezGTdRjBNZuYZi3t+Oc5NxNYg==}+ cpu: [ppc64]+ os: [linux]+ libc: [glibc]++ '@rollup/[email protected]':+ resolution: {integrity: sha512-Zlzm6fGuDvtAqMEl071/g17vxq6u2Y2v/rON/gDY4NvzWLJ41BGAlwhF3QuAzwq05zIPo4LYzdqwhx3oisYCUw==}+ cpu: [ppc64]+ os: [linux]+ libc: [musl]++ '@rollup/[email protected]':+ resolution: {integrity: sha512-KhEpYRtHZ3Kj4shavjXeH+K1bQlA6UbP6MJ45rMPF/11JlZb1SRNLeuWCdigUEoMMaFO4+LwwcS+ew1SoLJu/g==}+ cpu: [riscv64]+ os: [linux]+ libc: [glibc]++ '@rollup/[email protected]':+ resolution: {integrity: sha512-LPn9qvPsM/Ofd6Ekq3im6nB8Tk1ruJhTd3x/2bJkTR8m/XTsfxA+EU0RJ23WJqgJg123kitHAqbEK7B4cL1uPg==}+ cpu: [riscv64]+ os: [linux]+ libc: [musl]++ '@rollup/[email protected]':+ resolution: {integrity: sha512-Q1+E+pzSP+FiXuIZtxKR+pK7l2KQ9gsM+VaFPv1LR277kp7l61crG46WGLKLLay3Js5cvyU9Keqdzxa1EcFO+g==}+ cpu: [s390x]+ os: [linux]+ libc: [glibc]++ '@rollup/[email protected]':+ resolution: {integrity: sha512-3Btp4Lca/WzsmbaKu9Lh9d/XwyRDIegd/5khRBusHGw/Ll6SoF5Shn63OrjPdkLcpNi2PGDApXzNmxriRxGYjA==}+ cpu: [x64]+ os: [linux]+ libc: [glibc]++ '@rollup/[email protected]':+ resolution: {integrity: sha512-5SKVaUiVs18+DGBnpg0mORGxgq/0udczngGxV/vf2nvK1djqpOKIxY/+8rBWxAbWGRE4RnnwxWabDwJN3pCwIQ==}+ cpu: [x64]+ os: [linux]+ libc: [musl]++ '@rollup/[email protected]':+ resolution: {integrity: sha512-KBpm48/lESsHgWd+dRlcy18APBYhXU4Jb6VlJoqbpWNwfpztFXwP22qVv9aHd3k1quSrmLeJwYLc7rpQ+BFZrw==}+ cpu: [x64]+ os: [openbsd]++ '@rollup/[email protected]':+ resolution: {integrity: sha512-o0D0bfRW8QGA1Ph6OzqVHMq5LRu1xkr1iM7qQIXUSFuR60ddXeDhN9UR4bUBPLYsrT46sZwwgQa51TWtBV3r5g==}+ cpu: [arm64]+ os: [openharmony]++ '@rollup/[email protected]':+ resolution: {integrity: sha512-r17kcu5kmd6WQwokYmfBnfwM/icureCWCPjpJVALcrSv5Lfy6Ggk9azxXor6hILhCHbc/4IfEiv+L5RXaOHinA==}+ cpu: [arm64]+ os: [win32]++ '@rollup/[email protected]':+ resolution: {integrity: sha512-yUtOqq7ZrQoZ3WiHSR6QGTdOl4YgMHqXIYSBYU6siIcC0YF0pEwx7aGsPTm2mRwrmW6SMJkxzEdFm6wqXpmbNw==}+ cpu: [ia32]+ os: [win32]++ '@rollup/[email protected]':+ resolution: {integrity: sha512-5IYoWxQGo5WECbJbImIf2w33uCHJNLv4o/FQtSyeYDed7AC6zx84NsEcGYccoI2geDEYkrxUXcsYK/6EhwVSIg==}+ cpu: [x64]+ os: [win32]++ '@rollup/[email protected]':+ resolution: {integrity: sha512-ee+c14ggUiM7lg4PtCjSBYU9O9dHp4FFespRnd5yj7SilUBJCL3x3aHlB+sIqbGjcPo3pEyODASnfKJuZ26YBw==}+ cpu: [x64]+ os: [win32]++ '@tauri-apps/[email protected]':+ resolution: {integrity: sha512-pVmfis+4zT8H0Qhp3xPZx9Ju7kpzvA6rr/PSJPyuwfvucTQ8sVt61NYU9KMkK703UFlYadFmjKA4HhybOtN0gg==}++ '@tauri-apps/[email protected]':+ resolution: {integrity: sha512-OxqKSckIkoJ6vX2AjifIJpTasFC0Hbdoo7gEiCmAjauABO3U8m2MRsLWe+QTiBwDx1mIrvgA+rvI7tvDnbnHVg==}+ engines: {node: '>= 10'}+ cpu: [arm64]+ os: [darwin]++ '@tauri-apps/[email protected]':+ resolution: {integrity: sha512-fz76/77wMMJOaaUN6n3CybRG0P/MTEjjqYk81mGPyhi9m6Ue5T+LWBnJP/AkPooNatBPI2vtulGqomyMJ44lCQ==}+ engines: {node: '>= 10'}+ cpu: [x64]+ os: [darwin]++ '@tauri-apps/[email protected]':+ resolution: {integrity: sha512-K0w8Bof6Lt8QKLAYhRy0yy36ZH5iA/35VuSOvnxyjvCUZ+A3JKsUTlALviH/sVgAlisaPzzmeJSH8XOn4Q2HBA==}+ engines: {node: '>= 10'}+ cpu: [arm]+ os: [linux]++ '@tauri-apps/[email protected]':+ resolution: {integrity: sha512-j5rOnjmRUwWrm1oosf0zBYl4D+fqydgUROFCk0hvKZxvbTT8SOERes0QB7rBV/XWNy+kM6pCKzb3oSm2sRglzg==}+ engines: {node: '>= 10'}+ cpu: [arm64]+ os: [linux]+ libc: [glibc]++ '@tauri-apps/[email protected]':+ resolution: {integrity: sha512-aOue3Fy6Jb7+oWcfAVUsVHfeTybSCt2CZoU06aO4jv4d2Ks/KnaTPwMAK3CLEduGOvBLY1lbBBrIyomqLLH5Sg==}+ engines: {node: '>= 10'}+ cpu: [arm64]+ os: [linux]+ libc: [musl]++ '@tauri-apps/[email protected]':+ resolution: {integrity: sha512-Fx6GShY/RvST+t6LMlTHAwd66+1tEaAAGrnU7cysVfaiRP1BKng5Vl6rVmO6rSLOA1Sp1dRzNYM4f0OWQGb7qA==}+ engines: {node: '>= 10'}+ cpu: [riscv64]+ os: [linux]+ libc: [glibc]++ '@tauri-apps/[email protected]':+ resolution: {integrity: sha512-tNzZSa79Z1nRpHxEpQ38lsAFpKlFlYvoXzjTV+lRRn/zSf3wrdUC3wnLcq2XEadchPu4ttK0zivhYzr+XGD19Q==}+ engines: {node: '>= 10'}+ cpu: [x64]+ os: [linux]+ libc: [glibc]++ '@tauri-apps/[email protected]':+ resolution: {integrity: sha512-jmZ1pr0xEqUhuEusWtt9Yt+GF6lCnGHUmIL+KIknpbjK/XQ2qkhDBhaxK/JMHM2A8dAacVXCxXJk2EXpwhQUfA==}+ engines: {node: '>= 10'}+ cpu: [x64]+ os: [linux]+ libc: [musl]++ '@tauri-apps/[email protected]':+ resolution: {integrity: sha512-fGo8pgEHZxdSYgZ/J98m1usJ7NHKmKbq7k6uT0x1rpOq6Bg2YVzzpaAblWk710f5LHYBJIL5QIFS5IrD+4gmTg==}+ engines: {node: '>= 10'}+ cpu: [arm64]+ os: [win32]++ '@tauri-apps/[email protected]':+ resolution: {integrity: sha512-ezl8sQIcjYsye3TUnTH5VcWmWzccZASlQm7hlZt0dYyj1XD0qpVW47u2xYVrIKui0F8uQv/7QGZixdWiClBsbg==}+ engines: {node: '>= 10'}+ cpu: [ia32]+ os: [win32]++ '@tauri-apps/[email protected]':+ resolution: {integrity: sha512-DJhDeCqjLDNMWYFy7ZS8cfeAHX2RK0RbQMLiA3bMVVkXRDJ4NBYiHriGqsUhsr9iG41aTb+dJGkFPmPw1gWwVw==}+ engines: {node: '>= 10'}+ cpu: [x64]+ os: [win32]++ '@tauri-apps/[email protected]':+ resolution: {integrity: sha512-JI9bHfudSRJikGOrjbXEm6RjzzvmKuLc+JixB1NE8hNzQkNlCCIC3pTES3uypkR9lxHrsbxzcnSwhI2IxBQphw==}+ engines: {node: '>= 10'}+ hasBin: true++ '@types/[email protected]':+ resolution: {integrity: sha512-qoQprZvz5wQFJwMDqeseRXWv3rqMvhgpbXFfVyWhbx9X47POIA6i/+dXefEmZKoAgOaTdaIgNSMqMIU61yRyzA==}++ '@types/[email protected]':+ resolution: {integrity: sha512-ufFd2Xi92OAVPYsy+P4n7/U7e68fex0+Ee8gSG9KX7eo084CWiQ4sdxktvdl0bOPupXtVJPY19zk6EwWqUQ8lg==}++ '@types/[email protected]':+ resolution: {integrity: sha512-h/NUaSyG5EyxBIp8YRxo4RMe2/qQgvyowRwVMzhYhBCONbW8PUsg4lkFMrhgZhUe5z3L3MiLDuvyJ/CaPa2A8A==}++ '@types/[email protected]':+ resolution: {integrity: sha512-8PvcXf70gTDZBgt9ptxJ8elBeBjcLOAcOtoO/mPJjtji1+CdGbHgm77om1GrsPxsiE+uXIpNSK64UYaIwQXd4Q==}++ '@types/[email protected]':+ resolution: {integrity: sha512-lTyOMnOcmRBzdCv6/4zUZCrEhV0xrqQiUZBZtVcbmLHBXKLnN8q89v/wKRF/Q0HbwVsqbIG3o5HDoFl9sduM+g==}++ '@types/[email protected]':+ resolution: {integrity: sha512-ZI7bU42mZXXKHn/qNLEw2IrbiINU7X5+vfgdixBHkCNpYWXjKgfQ/P+uyGb5CjOLB9UcnTeg3rylQtV2hym44Q==}+ peerDependencies:+ '@types/react': ^19.3.0++ '@types/[email protected]':+ resolution: {integrity: sha512-N0rFCuH9YoxG9/m61l9MfpJKfmLOVU0em7ipIz6TRgSSkvReLB9vL85GB+yr8Bs5leqpvg96JSwF4ZS1s4viQg==}++ '@vitejs/[email protected]':+ resolution: {integrity: sha512-YmKkfhOAi3wsB1PhJq5Scj3GXMn3WvtQ/JC0xoopuHoXSdmtdStOpFrYaT1kie2YgFBcIe64ROzMYRjCrYOdYw==}+ engines: {node: ^20.19.0 || >=22.12.0}+ peerDependencies:+ vite: ^4.2.0 || ^5.0.0 || ^6.0.0 || ^7.0.0 || ^8.0.0++ resolution: {integrity: sha512-QYph+vfurmaxhNwi9FprfmtkT5cx2Keg8FzZ0vnjO8ukscIybVyZGMFwdllKGlTI6qyU8ck43OM9UXh+IFJihQ==}+ engines: {node: '>=6.0.0'}+ hasBin: true++ resolution: {integrity: sha512-khTmKu5NGYTotqcYo8Bew2k4RAE9PuXRSFRXG2lQBrCEQHyeQ/vX6gKMxfokwywBsLiXZMnHsmWMG1pnO8J7uQ==}+ engines: {node: ^6 || ^7 || ^8 || ^9 || ^10 || ^11 || ^12 || >=13.7}+ hasBin: true++ resolution: {integrity: sha512-wTB+9tIbLro/BCXwLuNV1meHE4L9dS6dArMDwgYfNBPMYScqClHyGunhkCSDtHhe/69Xl0sHlKgBVZ+fNsYtWA==}++ resolution: {integrity: sha512-Kvp459HrV2FEJ1CAsi1Ku+MY3kasH19TFykTz2xWmMeq6bk2NU3XXvfJ+Q61m0xktWwt+1HSYf3JZsTms3aRJg==}++ resolution: {integrity: sha512-z1HGKcYy2xA8AGQfwrn0PAy+PB7X/GSj3UVJW9qKyn43xWa+gl5nXmU4qqLMRzWVLFC8KusUX8T/0kCiOYpAIQ==}++ resolution: {integrity: sha512-RGwwWnwQvkVfavKVt22FGLw+xYSdzARwm0ru6DhTVA3umU5hZc28V3kO4stgYryrTlLpuvgI9GiijltAjNbcqA==}+ engines: {node: '>=6.0'}+ peerDependencies:+ supports-color: '*'+ peerDependenciesMeta:+ supports-color:+ optional: true++ resolution: {integrity: sha512-KmdOHJp6UlPUWoZ5O+X+qASnncYQm/F8wpCN7Jpbg4PJfP+l7SRhrSuFIuZlVshZvj4YUONgJAI944wmv5fIFg==}++ resolution: {integrity: sha512-HKVLS8dvII+xoKW9kmqxbRKrnWEXfJJr/FZhhJmiqIB0e053QNYFqOBouTMO/k5sID4MvCiUCvv8b9M4h32wIA==}+ engines: {node: '>=18'}+ hasBin: true++ resolution: {integrity: sha512-WUj2qlxaQtO4g6Pq5c29GTcWGDyd8itL8zTlipgECz3JesAiiOKotd8JU6otB3PACgG6xkJUyVhboMS+bje/jA==}+ engines: {node: '>=6'}++ resolution: {integrity: sha512-tIbYtZbucOs0BRGqPJkshJUYdL+SDH7dVM8gjy+ERp3WAUjLEFJE+02kanyHtwjWOnwrKYBiwAmM0p4kLJAnXg==}+ engines: {node: '>=12.0.0'}+ peerDependencies:+ picomatch: ^3 || ^4+ peerDependenciesMeta:+ picomatch:+ optional: true++ resolution: {integrity: sha512-5xoDfX+fL7faATnagmWPpbFtwh/R77WmMMqqHGS65C3vvB0YHrgF+B1YmZ3441tMj5n63k0212XNoJwzlhffQw==}+ engines: {node: ^8.16.0 || ^10.6.0 || >=11.0.0}+ os: [darwin]++ resolution: {integrity: sha512-3hN7NaskYvMDLQY55gnW3NQ+mesEAepTqlg+VEbj7zzqEMBVNhzcGYYeqFo/TlYz6eQiFcp1HcsCZO+nGgS8zg==}+ engines: {node: '>=6.9.0'}++ resolution: {integrity: sha512-RdJUflcE3cUzKiMqQgsCu06FPu9UdIJO0beYbPhHN4k6apgJtifcoCtT9bcxOpYBtpD2kCM6Sbzg4CausW/PKQ==}++ resolution: {integrity: sha512-/sM3dO2FOzXjKQhJuo0Q173wf2KOo8t4I8vHy6lF9poUp7bKT0/NHE8fPX23PwfhnykfqnC2xRxOnVw5XuGIaA==}+ engines: {node: '>=6'}+ hasBin: true++ resolution: {integrity: sha512-XmOWe7eyHYH14cLdVPoyg+GOH3rYX++KpzrylJwSW98t3Nk+U8XOl8FWKOgwtzdb8lXGf6zYwDUzeHMWfxasyg==}+ engines: {node: '>=6'}+ hasBin: true++ resolution: {integrity: sha512-KpNARQA3Iwv+jTA0utUVVbrh+Jlrr1Fv0e56GGzAFOXN7dk/FviaDW8LHmK52DlcH4WP2n6gI8vN1aesBFgo9w==}++ resolution: {integrity: sha512-6FlzubTLZG3J2a/NVCAleEhjzq5oxgHyaCU9yYXvcLsvoVaHJq/s5xXI6/XXP6tz7R9xAOtHnSO/tXtF3WRTlA==}++ resolution: {integrity: sha512-uKdg2G3GNCKQn9byYOpxbGqrT2fGO5KRt5J/8b3pok8rT6qxGWF6hxMyJiEYtAf+FVyYuD9hRaDqX5uPFYJ4ZQ==}+ engines: {node: ^10 || ^12 || ^13.7 || ^14 || >=15.0.1}+ hasBin: true++ resolution: {integrity: sha512-6li2QanLsAXpIH2R6j77MzRyvOyrvdTqlKtO4CgBdHGNvN99ZZfyxszHc5o5+IZBWD5u6Hzwg83JoGXmqZNG9Q==}+ engines: {node: '>=18'}++ resolution: {integrity: sha512-xceH2snhtb5M9liqDsmEw56le376mTZkEX/jEb/RxNFyegNul7eNslCXP9FDj/Lcu0X8KEyMceP2ntpaHrDEVA==}++ resolution: {integrity: sha512-qcJu88Q2IWqJsDD529JKMdwGm/dvInW4HvQnRwiH9JtihJvzGOscDtHE3x1pBKeUOTysQ8kVmLnJ2kJu7yhcGA==}+ engines: {node: '>=12'}++ resolution: {integrity: sha512-LJlKCCAUFKOuZxipUdYw1NzIITEsPcgyOG9LkvRJvuKj/bRzbuRY0ARXvL0pWGpsZvn8jku+LMep2eU0seHp8g==}+ engines: {node: ^10 || ^12 || >=14}++ resolution: {integrity: sha512-Y0bARz53lhEC1NMCASs0/j+faB/zqt3R8hpvg1e8+61ZVJ4UL0UdC4cBbXfZMcIuhrfgeILTLe+ZeBCavQPtKQ==}+ peerDependencies:+ react: ^19.3.1++ resolution: {integrity: sha512-QgT5//D3jfjJb6Gsjxv0Slpj23ip+HtOpnNgnb2S5zU3CB26G/IDPGoy4RJB42wzFE46DRsstbW6tKHoKbhAxw==}+ engines: {node: '>=0.10.0'}++ resolution: {integrity: sha512-QNhWdt7nrgVWWQG58QuGsAR3jv3Hbe4mb4vz7w2csnHavciZJgda1CPNaldF6eVxv90ud3jUXpKlHL69gO38yw==}+ engines: {node: '>=0.10.0'}++ resolution: {integrity: sha512-xzt45rKOxzEuqjTdkGTIEaePcq9xRELlFI1uoazlKap8T6bENJkONSCfhK51P6XFTixa4rosPcDHihSdduXndQ==}+ engines: {node: '>=18.0.0', npm: '>=8.0.0'}+ hasBin: true++ resolution: {integrity: sha512-juorfCmIkIw8tT+p5BXSm6PJjQF/ycEYmKyzURCIt/RaZIhL+PulbQ9Yu2z1HdOJDdqDTlxA1+xKBmHXJsczAw==}++ resolution: {integrity: sha512-GYrCADwpu6yV5OAvchkQ27Z5wwMxWAEMg5NNWjyHh/5DboFFqbdbvYNIvZouQpxXyeMPoTOh0vdPYKlf0ZswdQ==}+ hasBin: true++ resolution: {integrity: sha512-KGj/8Y43x35aZVDtt+J4mK1hoLGHULMYfSkODJNQjNDC3oW1PqPoxMwo0pLUsWM/UEGzON/NxeHywEfNXNP3Vw==}+ engines: {node: '>=0.10.0'}++ resolution: {integrity: sha512-wXR/dYpcqKmfWpEdZjiKJOwCNFndD0DMnrW/cYjVGttEkBfVgcLFHoNrlj47mjOVic9yyNu65alsgF4NQyTa2g==}+ engines: {node: '>=12.0.0'}++ resolution: {integrity: sha512-jl1vZzPDinLr9eUt3J/t7V6FgNEw9QjvBPdysz9KfQDD41fQrC2Y4vKQdiaUpFT4bXlb1RHhLpp8wtm6M5TgSw==}+ engines: {node: '>=14.17'}+ hasBin: true++ resolution: {integrity: sha512-t8wonIOdQyOjtPd2VktlBu6QjTVTks6v8bSi7kd0r2Vll8TK1JYDZtRRdbmCHOAMphkZgrzK+L+vXK4pyZ8t4A==}+ hasBin: true+ peerDependencies:+ browserslist: '>= 4.21.0'++ resolution: {integrity: sha512-3tTi78MAKhVk9h+YZVXMQ8POmneJuE97QUPAWtJghHzhH7BAyiqQOC2KZh1DWOsu/USB2cRXhznPByaabvYXfw==}+ engines: {node: ^20.19.0 || >=22.12.0}+ hasBin: true+ peerDependencies:+ '@types/node': ^20.19.0 || >=22.12.0+ jiti: '>=1.21.0'+ less: ^4.0.0+ lightningcss: ^1.21.0+ sass: ^1.70.0+ sass-embedded: ^1.70.0+ stylus: '>=0.54.8'+ sugarss: ^5.0.0+ terser: ^5.16.0+ tsx: ^4.8.1+ yaml: ^2.4.2+ peerDependenciesMeta:+ '@types/node':+ optional: true+ jiti:+ optional: true+ less:+ optional: true+ lightningcss:+ optional: true+ sass:+ optional: true+ sass-embedded:+ optional: true+ stylus:+ optional: true+ sugarss:+ optional: true+ terser:+ optional: true+ tsx:+ optional: true+ yaml:+ optional: true++ resolution: {integrity: sha512-a4UGQaWPH59mOXUYnAG2ewncQS4i4F43Tv3JoAM+s2VDAmS9NsK8GpDMLrCHPksFT7h3K6TOoUNn2pb7RoXx4g==}++snapshots:++ '@babel/[email protected]':+ dependencies:+ '@babel/helper-validator-identifier': 7.29.7+ js-tokens: 4.0.0+ picocolors: 1.1.1++ '@babel/[email protected]': {}++ '@babel/[email protected]':+ dependencies:+ '@babel/code-frame': 7.29.7+ '@babel/generator': 7.29.14+ '@babel/helper-compilation-targets': 7.29.13+ '@babel/helper-module-transforms': 7.29.14(@babel/[email protected])+ '@babel/helpers': 7.29.14+ '@babel/parser': 7.29.14+ '@babel/template': 7.29.7+ '@babel/traverse': 7.29.14+ '@babel/types': 7.29.14+ '@jridgewell/remapping': 2.3.5+ convert-source-map: 2.0.0+ debug: 4.4.3+ gensync: 1.0.0-beta.2+ json5: 2.2.3+ semver: 6.3.2+ transitivePeerDependencies:+ - supports-color++ '@babel/[email protected]':+ dependencies:+ '@babel/parser': 7.29.14+ '@babel/types': 7.29.14+ '@jridgewell/gen-mapping': 0.3.13+ '@jridgewell/trace-mapping': 0.3.31+ jsesc: 3.1.0++ '@babel/[email protected]':+ dependencies:+ '@babel/compat-data': 7.29.7+ '@babel/helper-validator-option': 7.29.7+ browserslist: 4.29.5+ lru-cache: 5.1.1+ semver: 6.3.2++ '@babel/[email protected]': {}++ '@babel/[email protected]':+ dependencies:+ '@babel/traverse': 7.29.14+ '@babel/types': 7.29.14+ transitivePeerDependencies:+ - supports-color++ '@babel/[email protected](@babel/[email protected])':+ dependencies:+ '@babel/core': 7.29.13+ '@babel/helper-module-imports': 7.29.7+ '@babel/helper-validator-identifier': 7.29.7+ '@babel/traverse': 7.29.14+ transitivePeerDependencies:+ - supports-color++ '@babel/[email protected]': {}++ '@babel/[email protected]': {}++ '@babel/[email protected]': {}++ '@babel/[email protected]': {}++ '@babel/[email protected]':+ dependencies:+ '@babel/template': 7.29.7+ '@babel/types': 7.29.14++ '@babel/[email protected]':+ dependencies:+ '@babel/types': 7.29.14++ '@babel/[email protected](@babel/[email protected])':+ dependencies:+ '@babel/core': 7.29.13+ '@babel/helper-plugin-utils': 7.29.7++ '@babel/[email protected](@babel/[email protected])':+ dependencies:+ '@babel/core': 7.29.13+ '@babel/helper-plugin-utils': 7.29.7++ '@babel/[email protected]':+ dependencies:+ '@babel/code-frame': 7.29.7+ '@babel/parser': 7.29.14+ '@babel/types': 7.29.14++ '@babel/[email protected]':+ dependencies:+ '@babel/code-frame': 7.29.7+ '@babel/generator': 7.29.14+ '@babel/helper-globals': 7.29.7+ '@babel/parser': 7.29.14+ '@babel/template': 7.29.7+ '@babel/types': 7.29.14+ debug: 4.4.3+ transitivePeerDependencies:+ - supports-color++ '@babel/[email protected]':+ dependencies:+ '@babel/helper-string-parser': 7.29.14+ '@babel/helper-validator-identifier': 7.29.7++ '@esbuild/[email protected]':+ optional: true++ '@esbuild/[email protected]':+ optional: true++ '@esbuild/[email protected]':+ optional: true++ '@esbuild/[email protected]':+ optional: true++ '@esbuild/[email protected]':+ optional: true++ '@esbuild/[email protected]':+ optional: true++ '@esbuild/[email protected]':+ optional: true++ '@esbuild/[email protected]':+ optional: true++ '@esbuild/[email protected]':+ optional: true++ '@esbuild/[email protected]':+ optional: true++ '@esbuild/[email protected]':+ optional: true++ '@esbuild/[email protected]':+ optional: true++ '@esbuild/[email protected]':+ optional: true++ '@esbuild/[email protected]':+ optional: true++ '@esbuild/[email protected]':+ optional: true++ '@esbuild/[email protected]':+ optional: true++ '@esbuild/[email protected]':+ optional: true++ '@esbuild/[email protected]':+ optional: true++ '@esbuild/[email protected]':+ optional: true++ '@esbuild/[email protected]':+ optional: true++ '@esbuild/[email protected]':+ optional: true++ '@esbuild/[email protected]':+ optional: true++ '@esbuild/[email protected]':+ optional: true++ '@esbuild/[email protected]':+ optional: true++ '@esbuild/[email protected]':+ optional: true++ '@esbuild/[email protected]':+ optional: true++ '@jridgewell/[email protected]':+ dependencies:+ '@jridgewell/sourcemap-codec': 1.6.0+ '@jridgewell/trace-mapping': 0.3.31++ '@jridgewell/[email protected]':+ dependencies:+ '@jridgewell/gen-mapping': 0.3.13+ '@jridgewell/trace-mapping': 0.3.31++ '@jridgewell/[email protected]': {}++ '@jridgewell/[email protected]': {}++ '@jridgewell/[email protected]':+ dependencies:+ '@jridgewell/resolve-uri': 3.1.2+ '@jridgewell/sourcemap-codec': 1.6.0++ '@rolldown/[email protected]': {}++ '@rollup/[email protected]':+ optional: true++ '@rollup/[email protected]':+ optional: true++ '@rollup/[email protected]':+ optional: true++ '@rollup/[email protected]':+ optional: true++ '@rollup/[email protected]':+ optional: true++ '@rollup/[email protected]':+ optional: true++ '@rollup/[email protected]':+ optional: true++ '@rollup/[email protected]':+ optional: true++ '@rollup/[email protected]':+ optional: true++ '@rollup/[email protected]':+ optional: true++ '@rollup/[email protected]':+ optional: true++ '@rollup/[email protected]':+ optional: true++ '@rollup/[email protected]':+ optional: true++ '@rollup/[email protected]':+ optional: true++ '@rollup/[email protected]':+ optional: true++ '@rollup/[email protected]':+ optional: true++ '@rollup/[email protected]':+ optional: true++ '@rollup/[email protected]':+ optional: true++ '@rollup/[email protected]':+ optional: true++ '@rollup/[email protected]':+ optional: true++ '@rollup/[email protected]':+ optional: true++ '@rollup/[email protected]':+ optional: true++ '@rollup/[email protected]':+ optional: true++ '@rollup/[email protected]':+ optional: true++ '@rollup/[email protected]':+ optional: true++ '@rollup/[email protected]':+ optional: true++ '@tauri-apps/[email protected]': {}++ '@tauri-apps/[email protected]':+ optional: true++ '@tauri-apps/[email protected]':+ optional: true++ '@tauri-apps/[email protected]':+ optional: true++ '@tauri-apps/[email protected]':+ optional: true++ '@tauri-apps/[email protected]':+ optional: true++ '@tauri-apps/[email protected]':+ optional: true++ '@tauri-apps/[email protected]':+ optional: true++ '@tauri-apps/[email protected]':+ optional: true++ '@tauri-apps/[email protected]':+ optional: true++ '@tauri-apps/[email protected]':+ optional: true++ '@tauri-apps/[email protected]':+ optional: true++ '@tauri-apps/[email protected]':+ optionalDependencies:+ '@tauri-apps/cli-darwin-arm64': 2.12.4+ '@tauri-apps/cli-darwin-x64': 2.12.4+ '@tauri-apps/cli-linux-arm-gnueabihf': 2.12.4+ '@tauri-apps/cli-linux-arm64-gnu': 2.12.4+ '@tauri-apps/cli-linux-arm64-musl': 2.12.4+ '@tauri-apps/cli-linux-riscv64-gnu': 2.12.4+ '@tauri-apps/cli-linux-x64-gnu': 2.12.4+ '@tauri-apps/cli-linux-x64-musl': 2.12.4+ '@tauri-apps/cli-win32-arm64-msvc': 2.12.4+ '@tauri-apps/cli-win32-ia32-msvc': 2.12.4+ '@tauri-apps/cli-win32-x64-msvc': 2.12.4++ '@types/[email protected]':+ dependencies:+ '@babel/parser': 7.29.14+ '@babel/types': 7.29.14+ '@types/babel__generator': 7.27.0+ '@types/babel__template': 7.4.4+ '@types/babel__traverse': 7.28.0++ '@types/[email protected]':+ dependencies:+ '@babel/types': 7.29.14++ '@types/[email protected]':+ dependencies:+ '@babel/parser': 7.29.14+ '@babel/types': 7.29.14++ '@types/[email protected]':+ dependencies:+ '@babel/types': 7.29.14++ '@types/[email protected]': {}++ '@types/[email protected](@types/[email protected])':+ dependencies:+ '@types/react': 19.3.0++ '@types/[email protected]':+ dependencies:+ csstype: 3.2.3++ '@vitejs/[email protected]([email protected])':+ dependencies:+ '@babel/core': 7.29.13+ '@babel/plugin-transform-react-jsx-self': 7.29.7(@babel/[email protected])+ '@babel/plugin-transform-react-jsx-source': 7.29.7(@babel/[email protected])+ '@rolldown/pluginutils': 1.0.0-rc.3+ '@types/babel__core': 7.20.5+ react-refresh: 0.18.0+ vite: 7.3.8+ transitivePeerDependencies:+ - supports-color++ [email protected]: {}++ dependencies:+ baseline-browser-mapping: 2.11.37+ caniuse-lite: 1.0.30001826+ electron-to-chromium: 1.5.484+ node-releases: 2.0.63+ update-browserslist-db: 1.3.4([email protected])++ [email protected]: {}++ [email protected]: {}++ [email protected]: {}++ dependencies:+ ms: 2.1.3++ [email protected]: {}++ optionalDependencies:+ '@esbuild/aix-ppc64': 0.28.2+ '@esbuild/android-arm': 0.28.2+ '@esbuild/android-arm64': 0.28.2+ '@esbuild/android-x64': 0.28.2+ '@esbuild/darwin-arm64': 0.28.2+ '@esbuild/darwin-x64': 0.28.2+ '@esbuild/freebsd-arm64': 0.28.2+ '@esbuild/freebsd-x64': 0.28.2+ '@esbuild/linux-arm': 0.28.2+ '@esbuild/linux-arm64': 0.28.2+ '@esbuild/linux-ia32': 0.28.2+ '@esbuild/linux-loong64': 0.28.2+ '@esbuild/linux-mips64el': 0.28.2+ '@esbuild/linux-ppc64': 0.28.2+ '@esbuild/linux-riscv64': 0.28.2+ '@esbuild/linux-s390x': 0.28.2+ '@esbuild/linux-x64': 0.28.2+ '@esbuild/netbsd-arm64': 0.28.2+ '@esbuild/netbsd-x64': 0.28.2+ '@esbuild/openbsd-arm64': 0.28.2+ '@esbuild/openbsd-x64': 0.28.2+ '@esbuild/openharmony-arm64': 0.28.2+ '@esbuild/sunos-x64': 0.28.2+ '@esbuild/win32-arm64': 0.28.2+ '@esbuild/win32-ia32': 0.28.2+ '@esbuild/win32-x64': 0.28.2++ [email protected]: {}++ optionalDependencies:+ picomatch: 4.0.7++ optional: true++ [email protected]: {}++ [email protected]: {}++ [email protected]: {}++ [email protected]: {}++ dependencies:+ yallist: 3.1.1++ [email protected]: {}++ [email protected]: {}++ [email protected]: {}++ [email protected]: {}++ [email protected]: {}++ dependencies:+ nanoid: 3.3.20+ picocolors: 1.1.1+ source-map-js: 1.2.2++ dependencies:+ react: 19.3.1+ scheduler: 0.28.0++ [email protected]: {}++ [email protected]: {}++ dependencies:+ '@types/estree': 1.0.10+ optionalDependencies:+ '@rollup/rollup-android-arm-eabi': 4.68.2+ '@rollup/rollup-android-arm64': 4.68.2+ '@rollup/rollup-android-x64': 4.68.2+ '@rollup/rollup-darwin-arm64': 4.68.2+ '@rollup/rollup-darwin-x64': 4.68.2+ '@rollup/rollup-freebsd-arm64': 4.68.2+ '@rollup/rollup-freebsd-x64': 4.68.2+ '@rollup/rollup-linux-arm-gnueabihf': 4.68.2+ '@rollup/rollup-linux-arm-musleabihf': 4.68.2+ '@rollup/rollup-linux-arm64-gnu': 4.68.2+ '@rollup/rollup-linux-arm64-musl': 4.68.2+ '@rollup/rollup-linux-loong64-gnu': 4.68.2+ '@rollup/rollup-linux-loong64-musl': 4.68.2+ '@rollup/rollup-linux-ppc64-gnu': 4.68.2+ '@rollup/rollup-linux-ppc64-musl': 4.68.2+ '@rollup/rollup-linux-riscv64-gnu': 4.68.2+ '@rollup/rollup-linux-riscv64-musl': 4.68.2+ '@rollup/rollup-linux-s390x-gnu': 4.68.2+ '@rollup/rollup-linux-x64-gnu': 4.68.2+ '@rollup/rollup-linux-x64-musl': 4.68.2+ '@rollup/rollup-openbsd-x64': 4.68.2+ '@rollup/rollup-openharmony-arm64': 4.68.2+ '@rollup/rollup-win32-arm64-msvc': 4.68.2+ '@rollup/rollup-win32-ia32-msvc': 4.68.2+ '@rollup/rollup-win32-x64-gnu': 4.68.2+ '@rollup/rollup-win32-x64-msvc': 4.68.2+ fsevents: 2.3.3++ [email protected]: {}++ [email protected]: {}++ [email protected]: {}++ dependencies:+ fdir: 6.5.0([email protected])+ picomatch: 4.0.7++ [email protected]: {}++ dependencies:+ browserslist: 4.29.5+ escalade: 3.2.0+ picocolors: 1.1.1++ dependencies:+ esbuild: 0.28.2+ fdir: 6.5.0([email protected])+ picomatch: 4.0.7+ postcss: 8.5.32+ rollup: 4.68.2+ tinyglobby: 0.2.17+ optionalDependencies:+ fsevents: 2.3.3++ [email protected]: {}diff --git a/apps/settings/pnpm-workspace.yaml b/apps/settings/pnpm-workspace.yamlnew file mode 100644index 0000000..5ed0b5a--- /dev/null+++ b/apps/settings/pnpm-workspace.yaml@@ -0,0 +1,2 @@+allowBuilds:+ esbuild: truediff --git a/apps/settings/src-tauri/Cargo.toml b/apps/settings/src-tauri/Cargo.tomlnew file mode 100644index 0000000..957338d--- /dev/null+++ b/apps/settings/src-tauri/Cargo.toml@@ -0,0 +1,23 @@+[package]+name = "muelle-settings"+version.workspace = true+edition.workspace = true+license.workspace = true++[lints]+workspace = true++[build-dependencies]+tauri-build = { version = "2", features = [] }++[dependencies]+muelle-config.workspace = true+muelle-shell.workspace = true+serde.workspace = true+tauri = { version = "2", features = [] }++[features]+# Serve the bundled front end instead of the Vite dev server. On by default so+# a plain `cargo build` yields a working app; `tauri dev` turns it off.+default = ["custom-protocol"]+custom-protocol = ["tauri/custom-protocol"]diff --git a/apps/settings/src-tauri/build.rs b/apps/settings/src-tauri/build.rsnew file mode 100644index 0000000..261851f--- /dev/null+++ b/apps/settings/src-tauri/build.rs@@ -0,0 +1,3 @@+fn main() {+ tauri_build::build();+}diff --git a/apps/settings/src-tauri/capabilities/default.json b/apps/settings/src-tauri/capabilities/default.jsonnew file mode 100644index 0000000..3932492--- /dev/null+++ b/apps/settings/src-tauri/capabilities/default.json@@ -0,0 +1,12 @@+{+ "$schema": "../gen/schemas/desktop-schema.json",+ "identifier": "default",+ "description": "What the settings window may do.",+ "windows": ["main"],+ "permissions": [+ "core:default",+ "core:window:allow-close",+ "core:window:allow-minimize",+ "core:window:allow-start-dragging"+ ]+}diff --git a/apps/settings/src-tauri/gen/schemas/acl-manifests.json b/apps/settings/src-tauri/gen/schemas/acl-manifests.jsonnew file mode 100644index 0000000..2ebbc8d--- /dev/null+++ b/apps/settings/src-tauri/gen/schemas/acl-manifests.json@@ -0,0 +1 @@+{"core":{"default_permission":{"identifier":"default","description":"Default core plugins set.","permissions":["core:path:default","core:event:default","core:window:default","core:webview:default","core:app:default","core:image:default","core:resources:default","core:menu:default","core:tray:default"]},"permissions":{},"permission_sets":{},"global_scope_schema":null},"core:app":{"default_permission":{"identifier":"default","description":"Default permissions for the plugin.","permissions":["allow-version","allow-name","allow-tauri-version","allow-identifier","allow-bundle-type","allow-register-listener","allow-remove-listener","allow-supports-multiple-windows"]},"permissions":{"allow-app-hide":{"identifier":"allow-app-hide","description":"Enables the app_hide command without any pre-configured scope.","commands":{"allow":["app_hide"],"deny":[]}},"allow-app-show":{"identifier":"allow-app-show","description":"Enables the app_show command without any pre-configured scope.","commands":{"allow":["app_show"],"deny":[]}},"allow-bundle-type":{"identifier":"allow-bundle-type","description":"Enables the bundle_type command without any pre-configured scope.","commands":{"allow":["bundle_type"],"deny":[]}},"allow-default-window-icon":{"identifier":"allow-default-window-icon","description":"Enables the default_window_icon command without any pre-configured scope.","commands":{"allow":["default_window_icon"],"deny":[]}},"allow-exit":{"identifier":"allow-exit","description":"Enables the exit command without any pre-configured scope.","commands":{"allow":["exit"],"deny":[]}},"allow-fetch-data-store-identifiers":{"identifier":"allow-fetch-data-store-identifiers","description":"Enables the fetch_data_store_identifiers command without any pre-configured scope.","commands":{"allow":["fetch_data_store_identifiers"],"deny":[]}},"allow-identifier":{"identifier":"allow-identifier","description":"Enables the identifier command without any pre-configured scope.","commands":{"allow":["identifier"],"deny":[]}},"allow-name":{"identifier":"allow-name","description":"Enables the name command without any pre-configured scope.","commands":{"allow":["name"],"deny":[]}},"allow-register-listener":{"identifier":"allow-register-listener","description":"Enables the register_listener command without any pre-configured scope.","commands":{"allow":["register_listener"],"deny":[]}},"allow-remove-data-store":{"identifier":"allow-remove-data-store","description":"Enables the remove_data_store command without any pre-configured scope.","commands":{"allow":["remove_data_store"],"deny":[]}},"allow-remove-listener":{"identifier":"allow-remove-listener","description":"Enables the remove_listener command without any pre-configured scope.","commands":{"allow":["remove_listener"],"deny":[]}},"allow-set-app-theme":{"identifier":"allow-set-app-theme","description":"Enables the set_app_theme command without any pre-configured scope.","commands":{"allow":["set_app_theme"],"deny":[]}},"allow-set-dock-visibility":{"identifier":"allow-set-dock-visibility","description":"Enables the set_dock_visibility command without any pre-configured scope.","commands":{"allow":["set_dock_visibility"],"deny":[]}},"allow-supports-multiple-windows":{"identifier":"allow-supports-multiple-windows","description":"Enables the supports_multiple_windows command without any pre-configured scope.","commands":{"allow":["supports_multiple_windows"],"deny":[]}},"allow-tauri-version":{"identifier":"allow-tauri-version","description":"Enables the tauri_version command without any pre-configured scope.","commands":{"allow":["tauri_version"],"deny":[]}},"allow-version":{"identifier":"allow-version","description":"Enables the version command without any pre-configured scope.","commands":{"allow":["version"],"deny":[]}},"deny-app-hide":{"identifier":"deny-app-hide","description":"Denies the app_hide command without any pre-configured scope.","commands":{"allow":[],"deny":["app_hide"]}},"deny-app-show":{"identifier":"deny-app-show","description":"Denies the app_show command without any pre-configured scope.","commands":{"allow":[],"deny":["app_show"]}},"deny-bundle-type":{"identifier":"deny-bundle-type","description":"Denies the bundle_type command without any pre-configured scope.","commands":{"allow":[],"deny":["bundle_type"]}},"deny-default-window-icon":{"identifier":"deny-default-window-icon","description":"Denies the default_window_icon command without any pre-configured scope.","commands":{"allow":[],"deny":["default_window_icon"]}},"deny-exit":{"identifier":"deny-exit","description":"Denies the exit command without any pre-configured scope.","commands":{"allow":[],"deny":["exit"]}},"deny-fetch-data-store-identifiers":{"identifier":"deny-fetch-data-store-identifiers","description":"Denies the fetch_data_store_identifiers command without any pre-configured scope.","commands":{"allow":[],"deny":["fetch_data_store_identifiers"]}},"deny-identifier":{"identifier":"deny-identifier","description":"Denies the identifier command without any pre-configured scope.","commands":{"allow":[],"deny":["identifier"]}},"deny-name":{"identifier":"deny-name","description":"Denies the name command without any pre-configured scope.","commands":{"allow":[],"deny":["name"]}},"deny-register-listener":{"identifier":"deny-register-listener","description":"Denies the register_listener command without any pre-configured scope.","commands":{"allow":[],"deny":["register_listener"]}},"deny-remove-data-store":{"identifier":"deny-remove-data-store","description":"Denies the remove_data_store command without any pre-configured scope.","commands":{"allow":[],"deny":["remove_data_store"]}},"deny-remove-listener":{"identifier":"deny-remove-listener","description":"Denies the remove_listener command without any pre-configured scope.","commands":{"allow":[],"deny":["remove_listener"]}},"deny-set-app-theme":{"identifier":"deny-set-app-theme","description":"Denies the set_app_theme command without any pre-configured scope.","commands":{"allow":[],"deny":["set_app_theme"]}},"deny-set-dock-visibility":{"identifier":"deny-set-dock-visibility","description":"Denies the set_dock_visibility command without any pre-configured scope.","commands":{"allow":[],"deny":["set_dock_visibility"]}},"deny-supports-multiple-windows":{"identifier":"deny-supports-multiple-windows","description":"Denies the supports_multiple_windows command without any pre-configured scope.","commands":{"allow":[],"deny":["supports_multiple_windows"]}},"deny-tauri-version":{"identifier":"deny-tauri-version","description":"Denies the tauri_version command without any pre-configured scope.","commands":{"allow":[],"deny":["tauri_version"]}},"deny-version":{"identifier":"deny-version","description":"Denies the version command without any pre-configured scope.","commands":{"allow":[],"deny":["version"]}}},"permission_sets":{},"global_scope_schema":null},"core:event":{"default_permission":{"identifier":"default","description":"Default permissions for the plugin, which enables all commands.","permissions":["allow-listen","allow-unlisten","allow-emit","allow-emit-to"]},"permissions":{"allow-emit":{"identifier":"allow-emit","description":"Enables the emit command without any pre-configured scope.","commands":{"allow":["emit"],"deny":[]}},"allow-emit-to":{"identifier":"allow-emit-to","description":"Enables the emit_to command without any pre-configured scope.","commands":{"allow":["emit_to"],"deny":[]}},"allow-listen":{"identifier":"allow-listen","description":"Enables the listen command without any pre-configured scope.","commands":{"allow":["listen"],"deny":[]}},"allow-unlisten":{"identifier":"allow-unlisten","description":"Enables the unlisten command without any pre-configured scope.","commands":{"allow":["unlisten"],"deny":[]}},"deny-emit":{"identifier":"deny-emit","description":"Denies the emit command without any pre-configured scope.","commands":{"allow":[],"deny":["emit"]}},"deny-emit-to":{"identifier":"deny-emit-to","description":"Denies the emit_to command without any pre-configured scope.","commands":{"allow":[],"deny":["emit_to"]}},"deny-listen":{"identifier":"deny-listen","description":"Denies the listen command without any pre-configured scope.","commands":{"allow":[],"deny":["listen"]}},"deny-unlisten":{"identifier":"deny-unlisten","description":"Denies the unlisten command without any pre-configured scope.","commands":{"allow":[],"deny":["unlisten"]}}},"permission_sets":{},"global_scope_schema":null},"core:image":{"default_permission":{"identifier":"default","description":"Default permissions for the plugin, which enables all commands.","permissions":["allow-new","allow-from-bytes","allow-from-path","allow-rgba","allow-size"]},"permissions":{"allow-from-bytes":{"identifier":"allow-from-bytes","description":"Enables the from_bytes command without any pre-configured scope.","commands":{"allow":["from_bytes"],"deny":[]}},"allow-from-path":{"identifier":"allow-from-path","description":"Enables the from_path command without any pre-configured scope.","commands":{"allow":["from_path"],"deny":[]}},"allow-new":{"identifier":"allow-new","description":"Enables the new command without any pre-configured scope.","commands":{"allow":["new"],"deny":[]}},"allow-rgba":{"identifier":"allow-rgba","description":"Enables the rgba command without any pre-configured scope.","commands":{"allow":["rgba"],"deny":[]}},"allow-size":{"identifier":"allow-size","description":"Enables the size command without any pre-configured scope.","commands":{"allow":["size"],"deny":[]}},"deny-from-bytes":{"identifier":"deny-from-bytes","description":"Denies the from_bytes command without any pre-configured scope.","commands":{"allow":[],"deny":["from_bytes"]}},"deny-from-path":{"identifier":"deny-from-path","description":"Denies the from_path command without any pre-configured scope.","commands":{"allow":[],"deny":["from_path"]}},"deny-new":{"identifier":"deny-new","description":"Denies the new command without any pre-configured scope.","commands":{"allow":[],"deny":["new"]}},"deny-rgba":{"identifier":"deny-rgba","description":"Denies the rgba command without any pre-configured scope.","commands":{"allow":[],"deny":["rgba"]}},"deny-size":{"identifier":"deny-size","description":"Denies the size command without any pre-configured scope.","commands":{"allow":[],"deny":["size"]}}},"permission_sets":{},"global_scope_schema":null},"core:menu":{"default_permission":{"identifier":"default","description":"Default permissions for the plugin, which enables all commands.","permissions":["allow-new","allow-append","allow-prepend","allow-insert","allow-remove","allow-remove-at","allow-items","allow-get","allow-popup","allow-create-default","allow-set-as-app-menu","allow-set-as-window-menu","allow-text","allow-set-text","allow-is-enabled","allow-set-enabled","allow-set-accelerator","allow-set-as-windows-menu-for-nsapp","allow-set-as-help-menu-for-nsapp","allow-is-checked","allow-set-checked","allow-set-icon"]},"permissions":{"allow-append":{"identifier":"allow-append","description":"Enables the append command without any pre-configured scope.","commands":{"allow":["append"],"deny":[]}},"allow-create-default":{"identifier":"allow-create-default","description":"Enables the create_default command without any pre-configured scope.","commands":{"allow":["create_default"],"deny":[]}},"allow-get":{"identifier":"allow-get","description":"Enables the get command without any pre-configured scope.","commands":{"allow":["get"],"deny":[]}},"allow-insert":{"identifier":"allow-insert","description":"Enables the insert command without any pre-configured scope.","commands":{"allow":["insert"],"deny":[]}},"allow-is-checked":{"identifier":"allow-is-checked","description":"Enables the is_checked command without any pre-configured scope.","commands":{"allow":["is_checked"],"deny":[]}},"allow-is-enabled":{"identifier":"allow-is-enabled","description":"Enables the is_enabled command without any pre-configured scope.","commands":{"allow":["is_enabled"],"deny":[]}},"allow-items":{"identifier":"allow-items","description":"Enables the items command without any pre-configured scope.","commands":{"allow":["items"],"deny":[]}},"allow-new":{"identifier":"allow-new","description":"Enables the new command without any pre-configured scope.","commands":{"allow":["new"],"deny":[]}},"allow-popup":{"identifier":"allow-popup","description":"Enables the popup command without any pre-configured scope.","commands":{"allow":["popup"],"deny":[]}},"allow-prepend":{"identifier":"allow-prepend","description":"Enables the prepend command without any pre-configured scope.","commands":{"allow":["prepend"],"deny":[]}},"allow-remove":{"identifier":"allow-remove","description":"Enables the remove command without any pre-configured scope.","commands":{"allow":["remove"],"deny":[]}},"allow-remove-at":{"identifier":"allow-remove-at","description":"Enables the remove_at command without any pre-configured scope.","commands":{"allow":["remove_at"],"deny":[]}},"allow-set-accelerator":{"identifier":"allow-set-accelerator","description":"Enables the set_accelerator command without any pre-configured scope.","commands":{"allow":["set_accelerator"],"deny":[]}},"allow-set-as-app-menu":{"identifier":"allow-set-as-app-menu","description":"Enables the set_as_app_menu command without any pre-configured scope.","commands":{"allow":["set_as_app_menu"],"deny":[]}},"allow-set-as-help-menu-for-nsapp":{"identifier":"allow-set-as-help-menu-for-nsapp","description":"Enables the set_as_help_menu_for_nsapp command without any pre-configured scope.","commands":{"allow":["set_as_help_menu_for_nsapp"],"deny":[]}},"allow-set-as-window-menu":{"identifier":"allow-set-as-window-menu","description":"Enables the set_as_window_menu command without any pre-configured scope.","commands":{"allow":["set_as_window_menu"],"deny":[]}},"allow-set-as-windows-menu-for-nsapp":{"identifier":"allow-set-as-windows-menu-for-nsapp","description":"Enables the set_as_windows_menu_for_nsapp command without any pre-configured scope.","commands":{"allow":["set_as_windows_menu_for_nsapp"],"deny":[]}},"allow-set-checked":{"identifier":"allow-set-checked","description":"Enables the set_checked command without any pre-configured scope.","commands":{"allow":["set_checked"],"deny":[]}},"allow-set-enabled":{"identifier":"allow-set-enabled","description":"Enables the set_enabled command without any pre-configured scope.","commands":{"allow":["set_enabled"],"deny":[]}},"allow-set-icon":{"identifier":"allow-set-icon","description":"Enables the set_icon command without any pre-configured scope.","commands":{"allow":["set_icon"],"deny":[]}},"allow-set-text":{"identifier":"allow-set-text","description":"Enables the set_text command without any pre-configured scope.","commands":{"allow":["set_text"],"deny":[]}},"allow-text":{"identifier":"allow-text","description":"Enables the text command without any pre-configured scope.","commands":{"allow":["text"],"deny":[]}},"deny-append":{"identifier":"deny-append","description":"Denies the append command without any pre-configured scope.","commands":{"allow":[],"deny":["append"]}},"deny-create-default":{"identifier":"deny-create-default","description":"Denies the create_default command without any pre-configured scope.","commands":{"allow":[],"deny":["create_default"]}},"deny-get":{"identifier":"deny-get","description":"Denies the get command without any pre-configured scope.","commands":{"allow":[],"deny":["get"]}},"deny-insert":{"identifier":"deny-insert","description":"Denies the insert command without any pre-configured scope.","commands":{"allow":[],"deny":["insert"]}},"deny-is-checked":{"identifier":"deny-is-checked","description":"Denies the is_checked command without any pre-configured scope.","commands":{"allow":[],"deny":["is_checked"]}},"deny-is-enabled":{"identifier":"deny-is-enabled","description":"Denies the is_enabled command without any pre-configured scope.","commands":{"allow":[],"deny":["is_enabled"]}},"deny-items":{"identifier":"deny-items","description":"Denies the items command without any pre-configured scope.","commands":{"allow":[],"deny":["items"]}},"deny-new":{"identifier":"deny-new","description":"Denies the new command without any pre-configured scope.","commands":{"allow":[],"deny":["new"]}},"deny-popup":{"identifier":"deny-popup","description":"Denies the popup command without any pre-configured scope.","commands":{"allow":[],"deny":["popup"]}},"deny-prepend":{"identifier":"deny-prepend","description":"Denies the prepend command without any pre-configured scope.","commands":{"allow":[],"deny":["prepend"]}},"deny-remove":{"identifier":"deny-remove","description":"Denies the remove command without any pre-configured scope.","commands":{"allow":[],"deny":["remove"]}},"deny-remove-at":{"identifier":"deny-remove-at","description":"Denies the remove_at command without any pre-configured scope.","commands":{"allow":[],"deny":["remove_at"]}},"deny-set-accelerator":{"identifier":"deny-set-accelerator","description":"Denies the set_accelerator command without any pre-configured scope.","commands":{"allow":[],"deny":["set_accelerator"]}},"deny-set-as-app-menu":{"identifier":"deny-set-as-app-menu","description":"Denies the set_as_app_menu command without any pre-configured scope.","commands":{"allow":[],"deny":["set_as_app_menu"]}},"deny-set-as-help-menu-for-nsapp":{"identifier":"deny-set-as-help-menu-for-nsapp","description":"Denies the set_as_help_menu_for_nsapp command without any pre-configured scope.","commands":{"allow":[],"deny":["set_as_help_menu_for_nsapp"]}},"deny-set-as-window-menu":{"identifier":"deny-set-as-window-menu","description":"Denies the set_as_window_menu command without any pre-configured scope.","commands":{"allow":[],"deny":["set_as_window_menu"]}},"deny-set-as-windows-menu-for-nsapp":{"identifier":"deny-set-as-windows-menu-for-nsapp","description":"Denies the set_as_windows_menu_for_nsapp command without any pre-configured scope.","commands":{"allow":[],"deny":["set_as_windows_menu_for_nsapp"]}},"deny-set-checked":{"identifier":"deny-set-checked","description":"Denies the set_checked command without any pre-configured scope.","commands":{"allow":[],"deny":["set_checked"]}},"deny-set-enabled":{"identifier":"deny-set-enabled","description":"Denies the set_enabled command without any pre-configured scope.","commands":{"allow":[],"deny":["set_enabled"]}},"deny-set-icon":{"identifier":"deny-set-icon","description":"Denies the set_icon command without any pre-configured scope.","commands":{"allow":[],"deny":["set_icon"]}},"deny-set-text":{"identifier":"deny-set-text","description":"Denies the set_text command without any pre-configured scope.","commands":{"allow":[],"deny":["set_text"]}},"deny-text":{"identifier":"deny-text","description":"Denies the text command without any pre-configured scope.","commands":{"allow":[],"deny":["text"]}}},"permission_sets":{},"global_scope_schema":null},"core:path":{"default_permission":{"identifier":"default","description":"Default permissions for the plugin, which enables all commands.","permissions":["allow-resolve-directory","allow-resolve","allow-normalize","allow-join","allow-dirname","allow-extname","allow-basename","allow-is-absolute"]},"permissions":{"allow-basename":{"identifier":"allow-basename","description":"Enables the basename command without any pre-configured scope.","commands":{"allow":["basename"],"deny":[]}},"allow-dirname":{"identifier":"allow-dirname","description":"Enables the dirname command without any pre-configured scope.","commands":{"allow":["dirname"],"deny":[]}},"allow-extname":{"identifier":"allow-extname","description":"Enables the extname command without any pre-configured scope.","commands":{"allow":["extname"],"deny":[]}},"allow-is-absolute":{"identifier":"allow-is-absolute","description":"Enables the is_absolute command without any pre-configured scope.","commands":{"allow":["is_absolute"],"deny":[]}},"allow-join":{"identifier":"allow-join","description":"Enables the join command without any pre-configured scope.","commands":{"allow":["join"],"deny":[]}},"allow-normalize":{"identifier":"allow-normalize","description":"Enables the normalize command without any pre-configured scope.","commands":{"allow":["normalize"],"deny":[]}},"allow-resolve":{"identifier":"allow-resolve","description":"Enables the resolve command without any pre-configured scope.","commands":{"allow":["resolve"],"deny":[]}},"allow-resolve-directory":{"identifier":"allow-resolve-directory","description":"Enables the resolve_directory command without any pre-configured scope.","commands":{"allow":["resolve_directory"],"deny":[]}},"deny-basename":{"identifier":"deny-basename","description":"Denies the basename command without any pre-configured scope.","commands":{"allow":[],"deny":["basename"]}},"deny-dirname":{"identifier":"deny-dirname","description":"Denies the dirname command without any pre-configured scope.","commands":{"allow":[],"deny":["dirname"]}},"deny-extname":{"identifier":"deny-extname","description":"Denies the extname command without any pre-configured scope.","commands":{"allow":[],"deny":["extname"]}},"deny-is-absolute":{"identifier":"deny-is-absolute","description":"Denies the is_absolute command without any pre-configured scope.","commands":{"allow":[],"deny":["is_absolute"]}},"deny-join":{"identifier":"deny-join","description":"Denies the join command without any pre-configured scope.","commands":{"allow":[],"deny":["join"]}},"deny-normalize":{"identifier":"deny-normalize","description":"Denies the normalize command without any pre-configured scope.","commands":{"allow":[],"deny":["normalize"]}},"deny-resolve":{"identifier":"deny-resolve","description":"Denies the resolve command without any pre-configured scope.","commands":{"allow":[],"deny":["resolve"]}},"deny-resolve-directory":{"identifier":"deny-resolve-directory","description":"Denies the resolve_directory command without any pre-configured scope.","commands":{"allow":[],"deny":["resolve_directory"]}}},"permission_sets":{},"global_scope_schema":null},"core:resources":{"default_permission":{"identifier":"default","description":"Default permissions for the plugin, which enables all commands.","permissions":["allow-close"]},"permissions":{"allow-close":{"identifier":"allow-close","description":"Enables the close command without any pre-configured scope.","commands":{"allow":["close"],"deny":[]}},"deny-close":{"identifier":"deny-close","description":"Denies the close command without any pre-configured scope.","commands":{"allow":[],"deny":["close"]}}},"permission_sets":{},"global_scope_schema":null},"core:tray":{"default_permission":{"identifier":"default","description":"Default permissions for the plugin, which enables all commands.","permissions":["allow-new","allow-get-by-id","allow-remove-by-id","allow-set-icon","allow-set-menu","allow-set-tooltip","allow-set-title","allow-set-visible","allow-set-temp-dir-path","allow-set-icon-as-template","allow-set-icon-with-as-template","allow-set-show-menu-on-left-click"]},"permissions":{"allow-get-by-id":{"identifier":"allow-get-by-id","description":"Enables the get_by_id command without any pre-configured scope.","commands":{"allow":["get_by_id"],"deny":[]}},"allow-new":{"identifier":"allow-new","description":"Enables the new command without any pre-configured scope.","commands":{"allow":["new"],"deny":[]}},"allow-remove-by-id":{"identifier":"allow-remove-by-id","description":"Enables the remove_by_id command without any pre-configured scope.","commands":{"allow":["remove_by_id"],"deny":[]}},"allow-set-icon":{"identifier":"allow-set-icon","description":"Enables the set_icon command without any pre-configured scope.","commands":{"allow":["set_icon"],"deny":[]}},"allow-set-icon-as-template":{"identifier":"allow-set-icon-as-template","description":"Enables the set_icon_as_template command without any pre-configured scope.","commands":{"allow":["set_icon_as_template"],"deny":[]}},"allow-set-icon-with-as-template":{"identifier":"allow-set-icon-with-as-template","description":"Enables the set_icon_with_as_template command without any pre-configured scope.","commands":{"allow":["set_icon_with_as_template"],"deny":[]}},"allow-set-menu":{"identifier":"allow-set-menu","description":"Enables the set_menu command without any pre-configured scope.","commands":{"allow":["set_menu"],"deny":[]}},"allow-set-show-menu-on-left-click":{"identifier":"allow-set-show-menu-on-left-click","description":"Enables the set_show_menu_on_left_click command without any pre-configured scope.","commands":{"allow":["set_show_menu_on_left_click"],"deny":[]}},"allow-set-temp-dir-path":{"identifier":"allow-set-temp-dir-path","description":"Enables the set_temp_dir_path command without any pre-configured scope.","commands":{"allow":["set_temp_dir_path"],"deny":[]}},"allow-set-title":{"identifier":"allow-set-title","description":"Enables the set_title command without any pre-configured scope.","commands":{"allow":["set_title"],"deny":[]}},"allow-set-tooltip":{"identifier":"allow-set-tooltip","description":"Enables the set_tooltip command without any pre-configured scope.","commands":{"allow":["set_tooltip"],"deny":[]}},"allow-set-visible":{"identifier":"allow-set-visible","description":"Enables the set_visible command without any pre-configured scope.","commands":{"allow":["set_visible"],"deny":[]}},"deny-get-by-id":{"identifier":"deny-get-by-id","description":"Denies the get_by_id command without any pre-configured scope.","commands":{"allow":[],"deny":["get_by_id"]}},"deny-new":{"identifier":"deny-new","description":"Denies the new command without any pre-configured scope.","commands":{"allow":[],"deny":["new"]}},"deny-remove-by-id":{"identifier":"deny-remove-by-id","description":"Denies the remove_by_id command without any pre-configured scope.","commands":{"allow":[],"deny":["remove_by_id"]}},"deny-set-icon":{"identifier":"deny-set-icon","description":"Denies the set_icon command without any pre-configured scope.","commands":{"allow":[],"deny":["set_icon"]}},"deny-set-icon-as-template":{"identifier":"deny-set-icon-as-template","description":"Denies the set_icon_as_template command without any pre-configured scope.","commands":{"allow":[],"deny":["set_icon_as_template"]}},"deny-set-icon-with-as-template":{"identifier":"deny-set-icon-with-as-template","description":"Denies the set_icon_with_as_template command without any pre-configured scope.","commands":{"allow":[],"deny":["set_icon_with_as_template"]}},"deny-set-menu":{"identifier":"deny-set-menu","description":"Denies the set_menu command without any pre-configured scope.","commands":{"allow":[],"deny":["set_menu"]}},"deny-set-show-menu-on-left-click":{"identifier":"deny-set-show-menu-on-left-click","description":"Denies the set_show_menu_on_left_click command without any pre-configured scope.","commands":{"allow":[],"deny":["set_show_menu_on_left_click"]}},"deny-set-temp-dir-path":{"identifier":"deny-set-temp-dir-path","description":"Denies the set_temp_dir_path command without any pre-configured scope.","commands":{"allow":[],"deny":["set_temp_dir_path"]}},"deny-set-title":{"identifier":"deny-set-title","description":"Denies the set_title command without any pre-configured scope.","commands":{"allow":[],"deny":["set_title"]}},"deny-set-tooltip":{"identifier":"deny-set-tooltip","description":"Denies the set_tooltip command without any pre-configured scope.","commands":{"allow":[],"deny":["set_tooltip"]}},"deny-set-visible":{"identifier":"deny-set-visible","description":"Denies the set_visible command without any pre-configured scope.","commands":{"allow":[],"deny":["set_visible"]}}},"permission_sets":{},"global_scope_schema":null},"core:webview":{"default_permission":{"identifier":"default","description":"Default permissions for the plugin.","permissions":["allow-get-all-webviews","allow-webview-position","allow-webview-size","allow-internal-toggle-devtools"]},"permissions":{"allow-clear-all-browsing-data":{"identifier":"allow-clear-all-browsing-data","description":"Enables the clear_all_browsing_data command without any pre-configured scope.","commands":{"allow":["clear_all_browsing_data"],"deny":[]}},"allow-create-webview":{"identifier":"allow-create-webview","description":"Enables the create_webview command without any pre-configured scope.","commands":{"allow":["create_webview"],"deny":[]}},"allow-create-webview-window":{"identifier":"allow-create-webview-window","description":"Enables the create_webview_window command without any pre-configured scope.","commands":{"allow":["create_webview_window"],"deny":[]}},"allow-get-all-webviews":{"identifier":"allow-get-all-webviews","description":"Enables the get_all_webviews command without any pre-configured scope.","commands":{"allow":["get_all_webviews"],"deny":[]}},"allow-internal-toggle-devtools":{"identifier":"allow-internal-toggle-devtools","description":"Enables the internal_toggle_devtools command without any pre-configured scope.","commands":{"allow":["internal_toggle_devtools"],"deny":[]}},"allow-print":{"identifier":"allow-print","description":"Enables the print command without any pre-configured scope.","commands":{"allow":["print"],"deny":[]}},"allow-reparent":{"identifier":"allow-reparent","description":"Enables the reparent command without any pre-configured scope.","commands":{"allow":["reparent"],"deny":[]}},"allow-set-webview-auto-resize":{"identifier":"allow-set-webview-auto-resize","description":"Enables the set_webview_auto_resize command without any pre-configured scope.","commands":{"allow":["set_webview_auto_resize"],"deny":[]}},"allow-set-webview-background-color":{"identifier":"allow-set-webview-background-color","description":"Enables the set_webview_background_color command without any pre-configured scope.","commands":{"allow":["set_webview_background_color"],"deny":[]}},"allow-set-webview-focus":{"identifier":"allow-set-webview-focus","description":"Enables the set_webview_focus command without any pre-configured scope.","commands":{"allow":["set_webview_focus"],"deny":[]}},"allow-set-webview-position":{"identifier":"allow-set-webview-position","description":"Enables the set_webview_position command without any pre-configured scope.","commands":{"allow":["set_webview_position"],"deny":[]}},"allow-set-webview-size":{"identifier":"allow-set-webview-size","description":"Enables the set_webview_size command without any pre-configured scope.","commands":{"allow":["set_webview_size"],"deny":[]}},"allow-set-webview-zoom":{"identifier":"allow-set-webview-zoom","description":"Enables the set_webview_zoom command without any pre-configured scope.","commands":{"allow":["set_webview_zoom"],"deny":[]}},"allow-webview-close":{"identifier":"allow-webview-close","description":"Enables the webview_close command without any pre-configured scope.","commands":{"allow":["webview_close"],"deny":[]}},"allow-webview-hide":{"identifier":"allow-webview-hide","description":"Enables the webview_hide command without any pre-configured scope.","commands":{"allow":["webview_hide"],"deny":[]}},"allow-webview-position":{"identifier":"allow-webview-position","description":"Enables the webview_position command without any pre-configured scope.","commands":{"allow":["webview_position"],"deny":[]}},"allow-webview-show":{"identifier":"allow-webview-show","description":"Enables the webview_show command without any pre-configured scope.","commands":{"allow":["webview_show"],"deny":[]}},"allow-webview-size":{"identifier":"allow-webview-size","description":"Enables the webview_size command without any pre-configured scope.","commands":{"allow":["webview_size"],"deny":[]}},"deny-clear-all-browsing-data":{"identifier":"deny-clear-all-browsing-data","description":"Denies the clear_all_browsing_data command without any pre-configured scope.","commands":{"allow":[],"deny":["clear_all_browsing_data"]}},"deny-create-webview":{"identifier":"deny-create-webview","description":"Denies the create_webview command without any pre-configured scope.","commands":{"allow":[],"deny":["create_webview"]}},"deny-create-webview-window":{"identifier":"deny-create-webview-window","description":"Denies the create_webview_window command without any pre-configured scope.","commands":{"allow":[],"deny":["create_webview_window"]}},"deny-get-all-webviews":{"identifier":"deny-get-all-webviews","description":"Denies the get_all_webviews command without any pre-configured scope.","commands":{"allow":[],"deny":["get_all_webviews"]}},"deny-internal-toggle-devtools":{"identifier":"deny-internal-toggle-devtools","description":"Denies the internal_toggle_devtools command without any pre-configured scope.","commands":{"allow":[],"deny":["internal_toggle_devtools"]}},"deny-print":{"identifier":"deny-print","description":"Denies the print command without any pre-configured scope.","commands":{"allow":[],"deny":["print"]}},"deny-reparent":{"identifier":"deny-reparent","description":"Denies the reparent command without any pre-configured scope.","commands":{"allow":[],"deny":["reparent"]}},"deny-set-webview-auto-resize":{"identifier":"deny-set-webview-auto-resize","description":"Denies the set_webview_auto_resize command without any pre-configured scope.","commands":{"allow":[],"deny":["set_webview_auto_resize"]}},"deny-set-webview-background-color":{"identifier":"deny-set-webview-background-color","description":"Denies the set_webview_background_color command without any pre-configured scope.","commands":{"allow":[],"deny":["set_webview_background_color"]}},"deny-set-webview-focus":{"identifier":"deny-set-webview-focus","description":"Denies the set_webview_focus command without any pre-configured scope.","commands":{"allow":[],"deny":["set_webview_focus"]}},"deny-set-webview-position":{"identifier":"deny-set-webview-position","description":"Denies the set_webview_position command without any pre-configured scope.","commands":{"allow":[],"deny":["set_webview_position"]}},"deny-set-webview-size":{"identifier":"deny-set-webview-size","description":"Denies the set_webview_size command without any pre-configured scope.","commands":{"allow":[],"deny":["set_webview_size"]}},"deny-set-webview-zoom":{"identifier":"deny-set-webview-zoom","description":"Denies the set_webview_zoom command without any pre-configured scope.","commands":{"allow":[],"deny":["set_webview_zoom"]}},"deny-webview-close":{"identifier":"deny-webview-close","description":"Denies the webview_close command without any pre-configured scope.","commands":{"allow":[],"deny":["webview_close"]}},"deny-webview-hide":{"identifier":"deny-webview-hide","description":"Denies the webview_hide command without any pre-configured scope.","commands":{"allow":[],"deny":["webview_hide"]}},"deny-webview-position":{"identifier":"deny-webview-position","description":"Denies the webview_position command without any pre-configured scope.","commands":{"allow":[],"deny":["webview_position"]}},"deny-webview-show":{"identifier":"deny-webview-show","description":"Denies the webview_show command without any pre-configured scope.","commands":{"allow":[],"deny":["webview_show"]}},"deny-webview-size":{"identifier":"deny-webview-size","description":"Denies the webview_size command without any pre-configured scope.","commands":{"allow":[],"deny":["webview_size"]}}},"permission_sets":{},"global_scope_schema":null},"core:window":{"default_permission":{"identifier":"default","description":"Default permissions for the plugin.","permissions":["allow-get-all-windows","allow-scale-factor","allow-inner-position","allow-outer-position","allow-inner-size","allow-outer-size","allow-is-fullscreen","allow-is-minimized","allow-is-maximized","allow-is-focused","allow-is-decorated","allow-is-resizable","allow-is-maximizable","allow-is-minimizable","allow-is-closable","allow-is-visible","allow-is-enabled","allow-title","allow-current-monitor","allow-primary-monitor","allow-monitor-from-point","allow-available-monitors","allow-cursor-position","allow-theme","allow-is-always-on-top","allow-activity-name","allow-scene-identifier","allow-internal-toggle-maximize"]},"permissions":{"allow-activity-name":{"identifier":"allow-activity-name","description":"Enables the activity_name command without any pre-configured scope.","commands":{"allow":["activity_name"],"deny":[]}},"allow-available-monitors":{"identifier":"allow-available-monitors","description":"Enables the available_monitors command without any pre-configured scope.","commands":{"allow":["available_monitors"],"deny":[]}},"allow-center":{"identifier":"allow-center","description":"Enables the center command without any pre-configured scope.","commands":{"allow":["center"],"deny":[]}},"allow-close":{"identifier":"allow-close","description":"Enables the close command without any pre-configured scope.","commands":{"allow":["close"],"deny":[]}},"allow-create":{"identifier":"allow-create","description":"Enables the create command without any pre-configured scope.","commands":{"allow":["create"],"deny":[]}},"allow-current-monitor":{"identifier":"allow-current-monitor","description":"Enables the current_monitor command without any pre-configured scope.","commands":{"allow":["current_monitor"],"deny":[]}},"allow-cursor-position":{"identifier":"allow-cursor-position","description":"Enables the cursor_position command without any pre-configured scope.","commands":{"allow":["cursor_position"],"deny":[]}},"allow-destroy":{"identifier":"allow-destroy","description":"Enables the destroy command without any pre-configured scope.","commands":{"allow":["destroy"],"deny":[]}},"allow-get-all-windows":{"identifier":"allow-get-all-windows","description":"Enables the get_all_windows command without any pre-configured scope.","commands":{"allow":["get_all_windows"],"deny":[]}},"allow-hide":{"identifier":"allow-hide","description":"Enables the hide command without any pre-configured scope.","commands":{"allow":["hide"],"deny":[]}},"allow-inner-position":{"identifier":"allow-inner-position","description":"Enables the inner_position command without any pre-configured scope.","commands":{"allow":["inner_position"],"deny":[]}},"allow-inner-size":{"identifier":"allow-inner-size","description":"Enables the inner_size command without any pre-configured scope.","commands":{"allow":["inner_size"],"deny":[]}},"allow-internal-toggle-maximize":{"identifier":"allow-internal-toggle-maximize","description":"Enables the internal_toggle_maximize command without any pre-configured scope.","commands":{"allow":["internal_toggle_maximize"],"deny":[]}},"allow-is-always-on-top":{"identifier":"allow-is-always-on-top","description":"Enables the is_always_on_top command without any pre-configured scope.","commands":{"allow":["is_always_on_top"],"deny":[]}},"allow-is-closable":{"identifier":"allow-is-closable","description":"Enables the is_closable command without any pre-configured scope.","commands":{"allow":["is_closable"],"deny":[]}},"allow-is-decorated":{"identifier":"allow-is-decorated","description":"Enables the is_decorated command without any pre-configured scope.","commands":{"allow":["is_decorated"],"deny":[]}},"allow-is-enabled":{"identifier":"allow-is-enabled","description":"Enables the is_enabled command without any pre-configured scope.","commands":{"allow":["is_enabled"],"deny":[]}},"allow-is-focused":{"identifier":"allow-is-focused","description":"Enables the is_focused command without any pre-configured scope.","commands":{"allow":["is_focused"],"deny":[]}},"allow-is-fullscreen":{"identifier":"allow-is-fullscreen","description":"Enables the is_fullscreen command without any pre-configured scope.","commands":{"allow":["is_fullscreen"],"deny":[]}},"allow-is-maximizable":{"identifier":"allow-is-maximizable","description":"Enables the is_maximizable command without any pre-configured scope.","commands":{"allow":["is_maximizable"],"deny":[]}},"allow-is-maximized":{"identifier":"allow-is-maximized","description":"Enables the is_maximized command without any pre-configured scope.","commands":{"allow":["is_maximized"],"deny":[]}},"allow-is-minimizable":{"identifier":"allow-is-minimizable","description":"Enables the is_minimizable command without any pre-configured scope.","commands":{"allow":["is_minimizable"],"deny":[]}},"allow-is-minimized":{"identifier":"allow-is-minimized","description":"Enables the is_minimized command without any pre-configured scope.","commands":{"allow":["is_minimized"],"deny":[]}},"allow-is-resizable":{"identifier":"allow-is-resizable","description":"Enables the is_resizable command without any pre-configured scope.","commands":{"allow":["is_resizable"],"deny":[]}},"allow-is-visible":{"identifier":"allow-is-visible","description":"Enables the is_visible command without any pre-configured scope.","commands":{"allow":["is_visible"],"deny":[]}},"allow-maximize":{"identifier":"allow-maximize","description":"Enables the maximize command without any pre-configured scope.","commands":{"allow":["maximize"],"deny":[]}},"allow-minimize":{"identifier":"allow-minimize","description":"Enables the minimize command without any pre-configured scope.","commands":{"allow":["minimize"],"deny":[]}},"allow-monitor-from-point":{"identifier":"allow-monitor-from-point","description":"Enables the monitor_from_point command without any pre-configured scope.","commands":{"allow":["monitor_from_point"],"deny":[]}},"allow-outer-position":{"identifier":"allow-outer-position","description":"Enables the outer_position command without any pre-configured scope.","commands":{"allow":["outer_position"],"deny":[]}},"allow-outer-size":{"identifier":"allow-outer-size","description":"Enables the outer_size command without any pre-configured scope.","commands":{"allow":["outer_size"],"deny":[]}},"allow-primary-monitor":{"identifier":"allow-primary-monitor","description":"Enables the primary_monitor command without any pre-configured scope.","commands":{"allow":["primary_monitor"],"deny":[]}},"allow-request-user-attention":{"identifier":"allow-request-user-attention","description":"Enables the request_user_attention command without any pre-configured scope.","commands":{"allow":["request_user_attention"],"deny":[]}},"allow-scale-factor":{"identifier":"allow-scale-factor","description":"Enables the scale_factor command without any pre-configured scope.","commands":{"allow":["scale_factor"],"deny":[]}},"allow-scene-identifier":{"identifier":"allow-scene-identifier","description":"Enables the scene_identifier command without any pre-configured scope.","commands":{"allow":["scene_identifier"],"deny":[]}},"allow-set-always-on-bottom":{"identifier":"allow-set-always-on-bottom","description":"Enables the set_always_on_bottom command without any pre-configured scope.","commands":{"allow":["set_always_on_bottom"],"deny":[]}},"allow-set-always-on-top":{"identifier":"allow-set-always-on-top","description":"Enables the set_always_on_top command without any pre-configured scope.","commands":{"allow":["set_always_on_top"],"deny":[]}},"allow-set-background-color":{"identifier":"allow-set-background-color","description":"Enables the set_background_color command without any pre-configured scope.","commands":{"allow":["set_background_color"],"deny":[]}},"allow-set-badge-count":{"identifier":"allow-set-badge-count","description":"Enables the set_badge_count command without any pre-configured scope.","commands":{"allow":["set_badge_count"],"deny":[]}},"allow-set-badge-label":{"identifier":"allow-set-badge-label","description":"Enables the set_badge_label command without any pre-configured scope.","commands":{"allow":["set_badge_label"],"deny":[]}},"allow-set-closable":{"identifier":"allow-set-closable","description":"Enables the set_closable command without any pre-configured scope.","commands":{"allow":["set_closable"],"deny":[]}},"allow-set-content-protected":{"identifier":"allow-set-content-protected","description":"Enables the set_content_protected command without any pre-configured scope.","commands":{"allow":["set_content_protected"],"deny":[]}},"allow-set-cursor-grab":{"identifier":"allow-set-cursor-grab","description":"Enables the set_cursor_grab command without any pre-configured scope.","commands":{"allow":["set_cursor_grab"],"deny":[]}},"allow-set-cursor-icon":{"identifier":"allow-set-cursor-icon","description":"Enables the set_cursor_icon command without any pre-configured scope.","commands":{"allow":["set_cursor_icon"],"deny":[]}},"allow-set-cursor-position":{"identifier":"allow-set-cursor-position","description":"Enables the set_cursor_position command without any pre-configured scope.","commands":{"allow":["set_cursor_position"],"deny":[]}},"allow-set-cursor-visible":{"identifier":"allow-set-cursor-visible","description":"Enables the set_cursor_visible command without any pre-configured scope.","commands":{"allow":["set_cursor_visible"],"deny":[]}},"allow-set-decorations":{"identifier":"allow-set-decorations","description":"Enables the set_decorations command without any pre-configured scope.","commands":{"allow":["set_decorations"],"deny":[]}},"allow-set-effects":{"identifier":"allow-set-effects","description":"Enables the set_effects command without any pre-configured scope.","commands":{"allow":["set_effects"],"deny":[]}},"allow-set-enabled":{"identifier":"allow-set-enabled","description":"Enables the set_enabled command without any pre-configured scope.","commands":{"allow":["set_enabled"],"deny":[]}},"allow-set-focus":{"identifier":"allow-set-focus","description":"Enables the set_focus command without any pre-configured scope.","commands":{"allow":["set_focus"],"deny":[]}},"allow-set-focusable":{"identifier":"allow-set-focusable","description":"Enables the set_focusable command without any pre-configured scope.","commands":{"allow":["set_focusable"],"deny":[]}},"allow-set-fullscreen":{"identifier":"allow-set-fullscreen","description":"Enables the set_fullscreen command without any pre-configured scope.","commands":{"allow":["set_fullscreen"],"deny":[]}},"allow-set-fullscreen-on-monitor":{"identifier":"allow-set-fullscreen-on-monitor","description":"Enables the set_fullscreen_on_monitor command without any pre-configured scope.","commands":{"allow":["set_fullscreen_on_monitor"],"deny":[]}},"allow-set-icon":{"identifier":"allow-set-icon","description":"Enables the set_icon command without any pre-configured scope.","commands":{"allow":["set_icon"],"deny":[]}},"allow-set-ignore-cursor-events":{"identifier":"allow-set-ignore-cursor-events","description":"Enables the set_ignore_cursor_events command without any pre-configured scope.","commands":{"allow":["set_ignore_cursor_events"],"deny":[]}},"allow-set-max-size":{"identifier":"allow-set-max-size","description":"Enables the set_max_size command without any pre-configured scope.","commands":{"allow":["set_max_size"],"deny":[]}},"allow-set-maximizable":{"identifier":"allow-set-maximizable","description":"Enables the set_maximizable command without any pre-configured scope.","commands":{"allow":["set_maximizable"],"deny":[]}},"allow-set-min-size":{"identifier":"allow-set-min-size","description":"Enables the set_min_size command without any pre-configured scope.","commands":{"allow":["set_min_size"],"deny":[]}},"allow-set-minimizable":{"identifier":"allow-set-minimizable","description":"Enables the set_minimizable command without any pre-configured scope.","commands":{"allow":["set_minimizable"],"deny":[]}},"allow-set-overlay-icon":{"identifier":"allow-set-overlay-icon","description":"Enables the set_overlay_icon command without any pre-configured scope.","commands":{"allow":["set_overlay_icon"],"deny":[]}},"allow-set-position":{"identifier":"allow-set-position","description":"Enables the set_position command without any pre-configured scope.","commands":{"allow":["set_position"],"deny":[]}},"allow-set-progress-bar":{"identifier":"allow-set-progress-bar","description":"Enables the set_progress_bar command without any pre-configured scope.","commands":{"allow":["set_progress_bar"],"deny":[]}},"allow-set-resizable":{"identifier":"allow-set-resizable","description":"Enables the set_resizable command without any pre-configured scope.","commands":{"allow":["set_resizable"],"deny":[]}},"allow-set-shadow":{"identifier":"allow-set-shadow","description":"Enables the set_shadow command without any pre-configured scope.","commands":{"allow":["set_shadow"],"deny":[]}},"allow-set-simple-fullscreen":{"identifier":"allow-set-simple-fullscreen","description":"Enables the set_simple_fullscreen command without any pre-configured scope.","commands":{"allow":["set_simple_fullscreen"],"deny":[]}},"allow-set-size":{"identifier":"allow-set-size","description":"Enables the set_size command without any pre-configured scope.","commands":{"allow":["set_size"],"deny":[]}},"allow-set-size-constraints":{"identifier":"allow-set-size-constraints","description":"Enables the set_size_constraints command without any pre-configured scope.","commands":{"allow":["set_size_constraints"],"deny":[]}},"allow-set-skip-taskbar":{"identifier":"allow-set-skip-taskbar","description":"Enables the set_skip_taskbar command without any pre-configured scope.","commands":{"allow":["set_skip_taskbar"],"deny":[]}},"allow-set-theme":{"identifier":"allow-set-theme","description":"Enables the set_theme command without any pre-configured scope.","commands":{"allow":["set_theme"],"deny":[]}},"allow-set-title":{"identifier":"allow-set-title","description":"Enables the set_title command without any pre-configured scope.","commands":{"allow":["set_title"],"deny":[]}},"allow-set-title-bar-style":{"identifier":"allow-set-title-bar-style","description":"Enables the set_title_bar_style command without any pre-configured scope.","commands":{"allow":["set_title_bar_style"],"deny":[]}},"allow-set-visible-on-all-workspaces":{"identifier":"allow-set-visible-on-all-workspaces","description":"Enables the set_visible_on_all_workspaces command without any pre-configured scope.","commands":{"allow":["set_visible_on_all_workspaces"],"deny":[]}},"allow-show":{"identifier":"allow-show","description":"Enables the show command without any pre-configured scope.","commands":{"allow":["show"],"deny":[]}},"allow-start-dragging":{"identifier":"allow-start-dragging","description":"Enables the start_dragging command without any pre-configured scope.","commands":{"allow":["start_dragging"],"deny":[]}},"allow-start-resize-dragging":{"identifier":"allow-start-resize-dragging","description":"Enables the start_resize_dragging command without any pre-configured scope.","commands":{"allow":["start_resize_dragging"],"deny":[]}},"allow-theme":{"identifier":"allow-theme","description":"Enables the theme command without any pre-configured scope.","commands":{"allow":["theme"],"deny":[]}},"allow-title":{"identifier":"allow-title","description":"Enables the title command without any pre-configured scope.","commands":{"allow":["title"],"deny":[]}},"allow-toggle-maximize":{"identifier":"allow-toggle-maximize","description":"Enables the toggle_maximize command without any pre-configured scope.","commands":{"allow":["toggle_maximize"],"deny":[]}},"allow-unmaximize":{"identifier":"allow-unmaximize","description":"Enables the unmaximize command without any pre-configured scope.","commands":{"allow":["unmaximize"],"deny":[]}},"allow-unminimize":{"identifier":"allow-unminimize","description":"Enables the unminimize command without any pre-configured scope.","commands":{"allow":["unminimize"],"deny":[]}},"deny-activity-name":{"identifier":"deny-activity-name","description":"Denies the activity_name command without any pre-configured scope.","commands":{"allow":[],"deny":["activity_name"]}},"deny-available-monitors":{"identifier":"deny-available-monitors","description":"Denies the available_monitors command without any pre-configured scope.","commands":{"allow":[],"deny":["available_monitors"]}},"deny-center":{"identifier":"deny-center","description":"Denies the center command without any pre-configured scope.","commands":{"allow":[],"deny":["center"]}},"deny-close":{"identifier":"deny-close","description":"Denies the close command without any pre-configured scope.","commands":{"allow":[],"deny":["close"]}},"deny-create":{"identifier":"deny-create","description":"Denies the create command without any pre-configured scope.","commands":{"allow":[],"deny":["create"]}},"deny-current-monitor":{"identifier":"deny-current-monitor","description":"Denies the current_monitor command without any pre-configured scope.","commands":{"allow":[],"deny":["current_monitor"]}},"deny-cursor-position":{"identifier":"deny-cursor-position","description":"Denies the cursor_position command without any pre-configured scope.","commands":{"allow":[],"deny":["cursor_position"]}},"deny-destroy":{"identifier":"deny-destroy","description":"Denies the destroy command without any pre-configured scope.","commands":{"allow":[],"deny":["destroy"]}},"deny-get-all-windows":{"identifier":"deny-get-all-windows","description":"Denies the get_all_windows command without any pre-configured scope.","commands":{"allow":[],"deny":["get_all_windows"]}},"deny-hide":{"identifier":"deny-hide","description":"Denies the hide command without any pre-configured scope.","commands":{"allow":[],"deny":["hide"]}},"deny-inner-position":{"identifier":"deny-inner-position","description":"Denies the inner_position command without any pre-configured scope.","commands":{"allow":[],"deny":["inner_position"]}},"deny-inner-size":{"identifier":"deny-inner-size","description":"Denies the inner_size command without any pre-configured scope.","commands":{"allow":[],"deny":["inner_size"]}},"deny-internal-toggle-maximize":{"identifier":"deny-internal-toggle-maximize","description":"Denies the internal_toggle_maximize command without any pre-configured scope.","commands":{"allow":[],"deny":["internal_toggle_maximize"]}},"deny-is-always-on-top":{"identifier":"deny-is-always-on-top","description":"Denies the is_always_on_top command without any pre-configured scope.","commands":{"allow":[],"deny":["is_always_on_top"]}},"deny-is-closable":{"identifier":"deny-is-closable","description":"Denies the is_closable command without any pre-configured scope.","commands":{"allow":[],"deny":["is_closable"]}},"deny-is-decorated":{"identifier":"deny-is-decorated","description":"Denies the is_decorated command without any pre-configured scope.","commands":{"allow":[],"deny":["is_decorated"]}},"deny-is-enabled":{"identifier":"deny-is-enabled","description":"Denies the is_enabled command without any pre-configured scope.","commands":{"allow":[],"deny":["is_enabled"]}},"deny-is-focused":{"identifier":"deny-is-focused","description":"Denies the is_focused command without any pre-configured scope.","commands":{"allow":[],"deny":["is_focused"]}},"deny-is-fullscreen":{"identifier":"deny-is-fullscreen","description":"Denies the is_fullscreen command without any pre-configured scope.","commands":{"allow":[],"deny":["is_fullscreen"]}},"deny-is-maximizable":{"identifier":"deny-is-maximizable","description":"Denies the is_maximizable command without any pre-configured scope.","commands":{"allow":[],"deny":["is_maximizable"]}},"deny-is-maximized":{"identifier":"deny-is-maximized","description":"Denies the is_maximized command without any pre-configured scope.","commands":{"allow":[],"deny":["is_maximized"]}},"deny-is-minimizable":{"identifier":"deny-is-minimizable","description":"Denies the is_minimizable command without any pre-configured scope.","commands":{"allow":[],"deny":["is_minimizable"]}},"deny-is-minimized":{"identifier":"deny-is-minimized","description":"Denies the is_minimized command without any pre-configured scope.","commands":{"allow":[],"deny":["is_minimized"]}},"deny-is-resizable":{"identifier":"deny-is-resizable","description":"Denies the is_resizable command without any pre-configured scope.","commands":{"allow":[],"deny":["is_resizable"]}},"deny-is-visible":{"identifier":"deny-is-visible","description":"Denies the is_visible command without any pre-configured scope.","commands":{"allow":[],"deny":["is_visible"]}},"deny-maximize":{"identifier":"deny-maximize","description":"Denies the maximize command without any pre-configured scope.","commands":{"allow":[],"deny":["maximize"]}},"deny-minimize":{"identifier":"deny-minimize","description":"Denies the minimize command without any pre-configured scope.","commands":{"allow":[],"deny":["minimize"]}},"deny-monitor-from-point":{"identifier":"deny-monitor-from-point","description":"Denies the monitor_from_point command without any pre-configured scope.","commands":{"allow":[],"deny":["monitor_from_point"]}},"deny-outer-position":{"identifier":"deny-outer-position","description":"Denies the outer_position command without any pre-configured scope.","commands":{"allow":[],"deny":["outer_position"]}},"deny-outer-size":{"identifier":"deny-outer-size","description":"Denies the outer_size command without any pre-configured scope.","commands":{"allow":[],"deny":["outer_size"]}},"deny-primary-monitor":{"identifier":"deny-primary-monitor","description":"Denies the primary_monitor command without any pre-configured scope.","commands":{"allow":[],"deny":["primary_monitor"]}},"deny-request-user-attention":{"identifier":"deny-request-user-attention","description":"Denies the request_user_attention command without any pre-configured scope.","commands":{"allow":[],"deny":["request_user_attention"]}},"deny-scale-factor":{"identifier":"deny-scale-factor","description":"Denies the scale_factor command without any pre-configured scope.","commands":{"allow":[],"deny":["scale_factor"]}},"deny-scene-identifier":{"identifier":"deny-scene-identifier","description":"Denies the scene_identifier command without any pre-configured scope.","commands":{"allow":[],"deny":["scene_identifier"]}},"deny-set-always-on-bottom":{"identifier":"deny-set-always-on-bottom","description":"Denies the set_always_on_bottom command without any pre-configured scope.","commands":{"allow":[],"deny":["set_always_on_bottom"]}},"deny-set-always-on-top":{"identifier":"deny-set-always-on-top","description":"Denies the set_always_on_top command without any pre-configured scope.","commands":{"allow":[],"deny":["set_always_on_top"]}},"deny-set-background-color":{"identifier":"deny-set-background-color","description":"Denies the set_background_color command without any pre-configured scope.","commands":{"allow":[],"deny":["set_background_color"]}},"deny-set-badge-count":{"identifier":"deny-set-badge-count","description":"Denies the set_badge_count command without any pre-configured scope.","commands":{"allow":[],"deny":["set_badge_count"]}},"deny-set-badge-label":{"identifier":"deny-set-badge-label","description":"Denies the set_badge_label command without any pre-configured scope.","commands":{"allow":[],"deny":["set_badge_label"]}},"deny-set-closable":{"identifier":"deny-set-closable","description":"Denies the set_closable command without any pre-configured scope.","commands":{"allow":[],"deny":["set_closable"]}},"deny-set-content-protected":{"identifier":"deny-set-content-protected","description":"Denies the set_content_protected command without any pre-configured scope.","commands":{"allow":[],"deny":["set_content_protected"]}},"deny-set-cursor-grab":{"identifier":"deny-set-cursor-grab","description":"Denies the set_cursor_grab command without any pre-configured scope.","commands":{"allow":[],"deny":["set_cursor_grab"]}},"deny-set-cursor-icon":{"identifier":"deny-set-cursor-icon","description":"Denies the set_cursor_icon command without any pre-configured scope.","commands":{"allow":[],"deny":["set_cursor_icon"]}},"deny-set-cursor-position":{"identifier":"deny-set-cursor-position","description":"Denies the set_cursor_position command without any pre-configured scope.","commands":{"allow":[],"deny":["set_cursor_position"]}},"deny-set-cursor-visible":{"identifier":"deny-set-cursor-visible","description":"Denies the set_cursor_visible command without any pre-configured scope.","commands":{"allow":[],"deny":["set_cursor_visible"]}},"deny-set-decorations":{"identifier":"deny-set-decorations","description":"Denies the set_decorations command without any pre-configured scope.","commands":{"allow":[],"deny":["set_decorations"]}},"deny-set-effects":{"identifier":"deny-set-effects","description":"Denies the set_effects command without any pre-configured scope.","commands":{"allow":[],"deny":["set_effects"]}},"deny-set-enabled":{"identifier":"deny-set-enabled","description":"Denies the set_enabled command without any pre-configured scope.","commands":{"allow":[],"deny":["set_enabled"]}},"deny-set-focus":{"identifier":"deny-set-focus","description":"Denies the set_focus command without any pre-configured scope.","commands":{"allow":[],"deny":["set_focus"]}},"deny-set-focusable":{"identifier":"deny-set-focusable","description":"Denies the set_focusable command without any pre-configured scope.","commands":{"allow":[],"deny":["set_focusable"]}},"deny-set-fullscreen":{"identifier":"deny-set-fullscreen","description":"Denies the set_fullscreen command without any pre-configured scope.","commands":{"allow":[],"deny":["set_fullscreen"]}},"deny-set-fullscreen-on-monitor":{"identifier":"deny-set-fullscreen-on-monitor","description":"Denies the set_fullscreen_on_monitor command without any pre-configured scope.","commands":{"allow":[],"deny":["set_fullscreen_on_monitor"]}},"deny-set-icon":{"identifier":"deny-set-icon","description":"Denies the set_icon command without any pre-configured scope.","commands":{"allow":[],"deny":["set_icon"]}},"deny-set-ignore-cursor-events":{"identifier":"deny-set-ignore-cursor-events","description":"Denies the set_ignore_cursor_events command without any pre-configured scope.","commands":{"allow":[],"deny":["set_ignore_cursor_events"]}},"deny-set-max-size":{"identifier":"deny-set-max-size","description":"Denies the set_max_size command without any pre-configured scope.","commands":{"allow":[],"deny":["set_max_size"]}},"deny-set-maximizable":{"identifier":"deny-set-maximizable","description":"Denies the set_maximizable command without any pre-configured scope.","commands":{"allow":[],"deny":["set_maximizable"]}},"deny-set-min-size":{"identifier":"deny-set-min-size","description":"Denies the set_min_size command without any pre-configured scope.","commands":{"allow":[],"deny":["set_min_size"]}},"deny-set-minimizable":{"identifier":"deny-set-minimizable","description":"Denies the set_minimizable command without any pre-configured scope.","commands":{"allow":[],"deny":["set_minimizable"]}},"deny-set-overlay-icon":{"identifier":"deny-set-overlay-icon","description":"Denies the set_overlay_icon command without any pre-configured scope.","commands":{"allow":[],"deny":["set_overlay_icon"]}},"deny-set-position":{"identifier":"deny-set-position","description":"Denies the set_position command without any pre-configured scope.","commands":{"allow":[],"deny":["set_position"]}},"deny-set-progress-bar":{"identifier":"deny-set-progress-bar","description":"Denies the set_progress_bar command without any pre-configured scope.","commands":{"allow":[],"deny":["set_progress_bar"]}},"deny-set-resizable":{"identifier":"deny-set-resizable","description":"Denies the set_resizable command without any pre-configured scope.","commands":{"allow":[],"deny":["set_resizable"]}},"deny-set-shadow":{"identifier":"deny-set-shadow","description":"Denies the set_shadow command without any pre-configured scope.","commands":{"allow":[],"deny":["set_shadow"]}},"deny-set-simple-fullscreen":{"identifier":"deny-set-simple-fullscreen","description":"Denies the set_simple_fullscreen command without any pre-configured scope.","commands":{"allow":[],"deny":["set_simple_fullscreen"]}},"deny-set-size":{"identifier":"deny-set-size","description":"Denies the set_size command without any pre-configured scope.","commands":{"allow":[],"deny":["set_size"]}},"deny-set-size-constraints":{"identifier":"deny-set-size-constraints","description":"Denies the set_size_constraints command without any pre-configured scope.","commands":{"allow":[],"deny":["set_size_constraints"]}},"deny-set-skip-taskbar":{"identifier":"deny-set-skip-taskbar","description":"Denies the set_skip_taskbar command without any pre-configured scope.","commands":{"allow":[],"deny":["set_skip_taskbar"]}},"deny-set-theme":{"identifier":"deny-set-theme","description":"Denies the set_theme command without any pre-configured scope.","commands":{"allow":[],"deny":["set_theme"]}},"deny-set-title":{"identifier":"deny-set-title","description":"Denies the set_title command without any pre-configured scope.","commands":{"allow":[],"deny":["set_title"]}},"deny-set-title-bar-style":{"identifier":"deny-set-title-bar-style","description":"Denies the set_title_bar_style command without any pre-configured scope.","commands":{"allow":[],"deny":["set_title_bar_style"]}},"deny-set-visible-on-all-workspaces":{"identifier":"deny-set-visible-on-all-workspaces","description":"Denies the set_visible_on_all_workspaces command without any pre-configured scope.","commands":{"allow":[],"deny":["set_visible_on_all_workspaces"]}},"deny-show":{"identifier":"deny-show","description":"Denies the show command without any pre-configured scope.","commands":{"allow":[],"deny":["show"]}},"deny-start-dragging":{"identifier":"deny-start-dragging","description":"Denies the start_dragging command without any pre-configured scope.","commands":{"allow":[],"deny":["start_dragging"]}},"deny-start-resize-dragging":{"identifier":"deny-start-resize-dragging","description":"Denies the start_resize_dragging command without any pre-configured scope.","commands":{"allow":[],"deny":["start_resize_dragging"]}},"deny-theme":{"identifier":"deny-theme","description":"Denies the theme command without any pre-configured scope.","commands":{"allow":[],"deny":["theme"]}},"deny-title":{"identifier":"deny-title","description":"Denies the title command without any pre-configured scope.","commands":{"allow":[],"deny":["title"]}},"deny-toggle-maximize":{"identifier":"deny-toggle-maximize","description":"Denies the toggle_maximize command without any pre-configured scope.","commands":{"allow":[],"deny":["toggle_maximize"]}},"deny-unmaximize":{"identifier":"deny-unmaximize","description":"Denies the unmaximize command without any pre-configured scope.","commands":{"allow":[],"deny":["unmaximize"]}},"deny-unminimize":{"identifier":"deny-unminimize","description":"Denies the unminimize command without any pre-configured scope.","commands":{"allow":[],"deny":["unminimize"]}}},"permission_sets":{},"global_scope_schema":null}}\ No newline at end of filediff --git a/apps/settings/src-tauri/gen/schemas/capabilities.json b/apps/settings/src-tauri/gen/schemas/capabilities.jsonnew file mode 100644index 0000000..e97ea5a--- /dev/null+++ b/apps/settings/src-tauri/gen/schemas/capabilities.json@@ -0,0 +1 @@+{"default":{"identifier":"default","description":"What the settings window may do.","local":true,"windows":["main"],"permissions":["core:default","core:window:allow-close","core:window:allow-minimize","core:window:allow-start-dragging"]}}\ No newline at end of filediff --git a/apps/settings/src-tauri/gen/schemas/desktop-schema.json b/apps/settings/src-tauri/gen/schemas/desktop-schema.jsonnew file mode 100644index 0000000..1ef1225--- /dev/null+++ b/apps/settings/src-tauri/gen/schemas/desktop-schema.json@@ -0,0 +1,2316 @@+{+ "$schema": "http://json-schema.org/draft-07/schema#",+ "title": "CapabilityFile",+ "description": "Capability formats accepted in a capability file.",+ "anyOf": [+ {+ "description": "A single capability.",+ "allOf": [+ {+ "$ref": "#/definitions/Capability"+ }+ ]+ },+ {+ "description": "A list of capabilities.",+ "type": "array",+ "items": {+ "$ref": "#/definitions/Capability"+ }+ },+ {+ "description": "A list of capabilities.",+ "type": "object",+ "required": [+ "capabilities"+ ],+ "properties": {+ "capabilities": {+ "description": "The list of capabilities.",+ "type": "array",+ "items": {+ "$ref": "#/definitions/Capability"+ }+ }+ }+ }+ ],+ "definitions": {+ "Capability": {+ "description": "A grouping and boundary mechanism developers can use to isolate access to the IPC layer.\n\nIt controls application windows' and webviews' fine grained access to the Tauri core, application, or plugin commands. If a webview or its window is not matching any capability then it has no access to the IPC layer at all.\n\nThis can be done to create groups of windows, based on their required system access, which can reduce impact of frontend vulnerabilities in less privileged windows. Windows can be added to a capability by exact name (e.g. `main-window`) or glob patterns like `*` or `admin-*`. A Window can have none, one, or multiple associated capabilities.\n\n## Example\n\n```json { \"identifier\": \"main-user-files-write\", \"description\": \"This capability allows the `main` window on macOS and Windows access to `filesystem` write related commands and `dialog` commands to enable programmatic access to files selected by the user.\", \"windows\": [ \"main\" ], \"permissions\": [ \"core:default\", \"dialog:open\", { \"identifier\": \"fs:allow-write-text-file\", \"allow\": [{ \"path\": \"$HOME/test.txt\" }] }, ], \"platforms\": [\"macOS\",\"windows\"] } ```",+ "type": "object",+ "required": [+ "identifier",+ "permissions"+ ],+ "properties": {+ "identifier": {+ "description": "Identifier of the capability.\n\n## Example\n\n`main-user-files-write`",+ "type": "string"+ },+ "description": {+ "description": "Description of what the capability is intended to allow on associated windows.\n\nIt should contain a description of what the grouped permissions should allow.\n\n## Example\n\nThis capability allows the `main` window access to `filesystem` write related commands and `dialog` commands to enable programmatic access to files selected by the user.",+ "default": "",+ "type": "string"+ },+ "remote": {+ "description": "Configure remote URLs that can use the capability permissions.\n\nThis setting is optional and defaults to not being set, as our default use case is that the content is served from our local application.\n\n:::caution Make sure you understand the security implications of providing remote sources with local system access. :::\n\n## Example\n\n```json { \"urls\": [\"https://*.mydomain.dev\"] } ```",+ "anyOf": [+ {+ "$ref": "#/definitions/CapabilityRemote"+ },+ {+ "type": "null"+ }+ ]+ },+ "local": {+ "description": "Whether this capability is enabled for local app URLs or not. Defaults to `true`.",+ "default": true,+ "type": "boolean"+ },+ "windows": {+ "description": "List of windows that are affected by this capability. Can be a glob pattern.\n\nIf a window label matches any of the patterns in this list, the capability will be enabled on all the webviews of that window, regardless of the value of [`Self::webviews`].\n\nOn multiwebview windows, prefer specifying [`Self::webviews`] and omitting [`Self::windows`] for a fine grained access control.\n\n## Example\n\n`[\"main\"]`",+ "type": "array",+ "items": {+ "type": "string"+ }+ },+ "webviews": {+ "description": "List of webviews that are affected by this capability. Can be a glob pattern.\n\nThe capability will be enabled on all the webviews whose label matches any of the patterns in this list, regardless of whether the webview's window label matches a pattern in [`Self::windows`].\n\n## Example\n\n`[\"sub-webview-one\", \"sub-webview-two\"]`",+ "type": "array",+ "items": {+ "type": "string"+ }+ },+ "permissions": {+ "description": "List of permissions attached to this capability.\n\nMust include the plugin name as prefix in the form of `${plugin-name}:${permission-name}`. For commands directly implemented in the application itself only `${permission-name}` is required.\n\n## Example\n\n```json [ \"core:default\", \"shell:allow-open\", \"dialog:open\", { \"identifier\": \"fs:allow-write-text-file\", \"allow\": [{ \"path\": \"$HOME/test.txt\" }] } ] ```",+ "type": "array",+ "items": {+ "$ref": "#/definitions/PermissionEntry"+ },+ "uniqueItems": true+ },+ "platforms": {+ "description": "Limit which target platforms this capability applies to.\n\nBy default all platforms are targeted.\n\n## Example\n\n`[\"macOS\",\"windows\"]`",+ "type": [+ "array",+ "null"+ ],+ "items": {+ "$ref": "#/definitions/Target"+ }+ }+ }+ },+ "CapabilityRemote": {+ "description": "Configuration for remote URLs that are associated with the capability.",+ "type": "object",+ "required": [+ "urls"+ ],+ "properties": {+ "urls": {+ "description": "Remote domains this capability refers to using the [URLPattern standard](https://urlpattern.spec.whatwg.org/).\n\n## Examples\n\n- \"https://*.mydomain.dev\": allows subdomains of mydomain.dev - \"https://mydomain.dev/api/*\": allows any subpath of mydomain.dev/api",+ "type": "array",+ "items": {+ "type": "string"+ }+ }+ }+ },+ "PermissionEntry": {+ "description": "An entry for a permission value in a [`Capability`] can be either a raw permission [`Identifier`] or an object that references a permission and extends its scope.",+ "anyOf": [+ {+ "description": "Reference a permission or permission set by identifier.",+ "allOf": [+ {+ "$ref": "#/definitions/Identifier"+ }+ ]+ },+ {+ "description": "Reference a permission or permission set by identifier and extends its scope.",+ "type": "object",+ "allOf": [+ {+ "properties": {+ "identifier": {+ "description": "Identifier of the permission or permission set.",+ "allOf": [+ {+ "$ref": "#/definitions/Identifier"+ }+ ]+ },+ "allow": {+ "description": "Data that defines what is allowed by the scope.",+ "type": [+ "array",+ "null"+ ],+ "items": {+ "$ref": "#/definitions/Value"+ }+ },+ "deny": {+ "description": "Data that defines what is denied by the scope. This should be prioritized by validation logic.",+ "type": [+ "array",+ "null"+ ],+ "items": {+ "$ref": "#/definitions/Value"+ }+ }+ }+ }+ ],+ "required": [+ "identifier"+ ]+ }+ ]+ },+ "Identifier": {+ "description": "Permission identifier",+ "oneOf": [+ {+ "description": "Default core plugins set.\n#### This default permission set includes:\n\n- `core:path:default`\n- `core:event:default`\n- `core:window:default`\n- `core:webview:default`\n- `core:app:default`\n- `core:image:default`\n- `core:resources:default`\n- `core:menu:default`\n- `core:tray:default`",+ "type": "string",+ "const": "core:default",+ "markdownDescription": "Default core plugins set.\n#### This default permission set includes:\n\n- `core:path:default`\n- `core:event:default`\n- `core:window:default`\n- `core:webview:default`\n- `core:app:default`\n- `core:image:default`\n- `core:resources:default`\n- `core:menu:default`\n- `core:tray:default`"+ },+ {+ "description": "Default permissions for the plugin.\n#### This default permission set includes:\n\n- `allow-version`\n- `allow-name`\n- `allow-tauri-version`\n- `allow-identifier`\n- `allow-bundle-type`\n- `allow-register-listener`\n- `allow-remove-listener`\n- `allow-supports-multiple-windows`",+ "type": "string",+ "const": "core:app:default",+ "markdownDescription": "Default permissions for the plugin.\n#### This default permission set includes:\n\n- `allow-version`\n- `allow-name`\n- `allow-tauri-version`\n- `allow-identifier`\n- `allow-bundle-type`\n- `allow-register-listener`\n- `allow-remove-listener`\n- `allow-supports-multiple-windows`"+ },+ {+ "description": "Enables the app_hide command without any pre-configured scope.",+ "type": "string",+ "const": "core:app:allow-app-hide",+ "markdownDescription": "Enables the app_hide command without any pre-configured scope."+ },+ {+ "description": "Enables the app_show command without any pre-configured scope.",+ "type": "string",+ "const": "core:app:allow-app-show",+ "markdownDescription": "Enables the app_show command without any pre-configured scope."+ },+ {+ "description": "Enables the bundle_type command without any pre-configured scope.",+ "type": "string",+ "const": "core:app:allow-bundle-type",+ "markdownDescription": "Enables the bundle_type command without any pre-configured scope."+ },+ {+ "description": "Enables the default_window_icon command without any pre-configured scope.",+ "type": "string",+ "const": "core:app:allow-default-window-icon",+ "markdownDescription": "Enables the default_window_icon command without any pre-configured scope."+ },+ {+ "description": "Enables the exit command without any pre-configured scope.",+ "type": "string",+ "const": "core:app:allow-exit",+ "markdownDescription": "Enables the exit command without any pre-configured scope."+ },+ {+ "description": "Enables the fetch_data_store_identifiers command without any pre-configured scope.",+ "type": "string",+ "const": "core:app:allow-fetch-data-store-identifiers",+ "markdownDescription": "Enables the fetch_data_store_identifiers command without any pre-configured scope."+ },+ {+ "description": "Enables the identifier command without any pre-configured scope.",+ "type": "string",+ "const": "core:app:allow-identifier",+ "markdownDescription": "Enables the identifier command without any pre-configured scope."+ },+ {+ "description": "Enables the name command without any pre-configured scope.",+ "type": "string",+ "const": "core:app:allow-name",+ "markdownDescription": "Enables the name command without any pre-configured scope."+ },+ {+ "description": "Enables the register_listener command without any pre-configured scope.",+ "type": "string",+ "const": "core:app:allow-register-listener",+ "markdownDescription": "Enables the register_listener command without any pre-configured scope."+ },+ {+ "description": "Enables the remove_data_store command without any pre-configured scope.",+ "type": "string",+ "const": "core:app:allow-remove-data-store",+ "markdownDescription": "Enables the remove_data_store command without any pre-configured scope."+ },+ {+ "description": "Enables the remove_listener command without any pre-configured scope.",+ "type": "string",+ "const": "core:app:allow-remove-listener",+ "markdownDescription": "Enables the remove_listener command without any pre-configured scope."+ },+ {+ "description": "Enables the set_app_theme command without any pre-configured scope.",+ "type": "string",+ "const": "core:app:allow-set-app-theme",+ "markdownDescription": "Enables the set_app_theme command without any pre-configured scope."+ },+ {+ "description": "Enables the set_dock_visibility command without any pre-configured scope.",+ "type": "string",+ "const": "core:app:allow-set-dock-visibility",+ "markdownDescription": "Enables the set_dock_visibility command without any pre-configured scope."+ },+ {+ "description": "Enables the supports_multiple_windows command without any pre-configured scope.",+ "type": "string",+ "const": "core:app:allow-supports-multiple-windows",+ "markdownDescription": "Enables the supports_multiple_windows command without any pre-configured scope."+ },+ {+ "description": "Enables the tauri_version command without any pre-configured scope.",+ "type": "string",+ "const": "core:app:allow-tauri-version",+ "markdownDescription": "Enables the tauri_version command without any pre-configured scope."+ },+ {+ "description": "Enables the version command without any pre-configured scope.",+ "type": "string",+ "const": "core:app:allow-version",+ "markdownDescription": "Enables the version command without any pre-configured scope."+ },+ {+ "description": "Denies the app_hide command without any pre-configured scope.",+ "type": "string",+ "const": "core:app:deny-app-hide",+ "markdownDescription": "Denies the app_hide command without any pre-configured scope."+ },+ {+ "description": "Denies the app_show command without any pre-configured scope.",+ "type": "string",+ "const": "core:app:deny-app-show",+ "markdownDescription": "Denies the app_show command without any pre-configured scope."+ },+ {+ "description": "Denies the bundle_type command without any pre-configured scope.",+ "type": "string",+ "const": "core:app:deny-bundle-type",+ "markdownDescription": "Denies the bundle_type command without any pre-configured scope."+ },+ {+ "description": "Denies the default_window_icon command without any pre-configured scope.",+ "type": "string",+ "const": "core:app:deny-default-window-icon",+ "markdownDescription": "Denies the default_window_icon command without any pre-configured scope."+ },+ {+ "description": "Denies the exit command without any pre-configured scope.",+ "type": "string",+ "const": "core:app:deny-exit",+ "markdownDescription": "Denies the exit command without any pre-configured scope."+ },+ {+ "description": "Denies the fetch_data_store_identifiers command without any pre-configured scope.",+ "type": "string",+ "const": "core:app:deny-fetch-data-store-identifiers",+ "markdownDescription": "Denies the fetch_data_store_identifiers command without any pre-configured scope."+ },+ {+ "description": "Denies the identifier command without any pre-configured scope.",+ "type": "string",+ "const": "core:app:deny-identifier",+ "markdownDescription": "Denies the identifier command without any pre-configured scope."+ },+ {+ "description": "Denies the name command without any pre-configured scope.",+ "type": "string",+ "const": "core:app:deny-name",+ "markdownDescription": "Denies the name command without any pre-configured scope."+ },+ {+ "description": "Denies the register_listener command without any pre-configured scope.",+ "type": "string",+ "const": "core:app:deny-register-listener",+ "markdownDescription": "Denies the register_listener command without any pre-configured scope."+ },+ {+ "description": "Denies the remove_data_store command without any pre-configured scope.",+ "type": "string",+ "const": "core:app:deny-remove-data-store",+ "markdownDescription": "Denies the remove_data_store command without any pre-configured scope."+ },+ {+ "description": "Denies the remove_listener command without any pre-configured scope.",+ "type": "string",+ "const": "core:app:deny-remove-listener",+ "markdownDescription": "Denies the remove_listener command without any pre-configured scope."+ },+ {+ "description": "Denies the set_app_theme command without any pre-configured scope.",+ "type": "string",+ "const": "core:app:deny-set-app-theme",+ "markdownDescription": "Denies the set_app_theme command without any pre-configured scope."+ },+ {+ "description": "Denies the set_dock_visibility command without any pre-configured scope.",+ "type": "string",+ "const": "core:app:deny-set-dock-visibility",+ "markdownDescription": "Denies the set_dock_visibility command without any pre-configured scope."+ },+ {+ "description": "Denies the supports_multiple_windows command without any pre-configured scope.",+ "type": "string",+ "const": "core:app:deny-supports-multiple-windows",+ "markdownDescription": "Denies the supports_multiple_windows command without any pre-configured scope."+ },+ {+ "description": "Denies the tauri_version command without any pre-configured scope.",+ "type": "string",+ "const": "core:app:deny-tauri-version",+ "markdownDescription": "Denies the tauri_version command without any pre-configured scope."+ },+ {+ "description": "Denies the version command without any pre-configured scope.",+ "type": "string",+ "const": "core:app:deny-version",+ "markdownDescription": "Denies the version command without any pre-configured scope."+ },+ {+ "description": "Default permissions for the plugin, which enables all commands.\n#### This default permission set includes:\n\n- `allow-listen`\n- `allow-unlisten`\n- `allow-emit`\n- `allow-emit-to`",+ "type": "string",+ "const": "core:event:default",+ "markdownDescription": "Default permissions for the plugin, which enables all commands.\n#### This default permission set includes:\n\n- `allow-listen`\n- `allow-unlisten`\n- `allow-emit`\n- `allow-emit-to`"+ },+ {+ "description": "Enables the emit command without any pre-configured scope.",+ "type": "string",+ "const": "core:event:allow-emit",+ "markdownDescription": "Enables the emit command without any pre-configured scope."+ },+ {+ "description": "Enables the emit_to command without any pre-configured scope.",+ "type": "string",+ "const": "core:event:allow-emit-to",+ "markdownDescription": "Enables the emit_to command without any pre-configured scope."+ },+ {+ "description": "Enables the listen command without any pre-configured scope.",+ "type": "string",+ "const": "core:event:allow-listen",+ "markdownDescription": "Enables the listen command without any pre-configured scope."+ },+ {+ "description": "Enables the unlisten command without any pre-configured scope.",+ "type": "string",+ "const": "core:event:allow-unlisten",+ "markdownDescription": "Enables the unlisten command without any pre-configured scope."+ },+ {+ "description": "Denies the emit command without any pre-configured scope.",+ "type": "string",+ "const": "core:event:deny-emit",+ "markdownDescription": "Denies the emit command without any pre-configured scope."+ },+ {+ "description": "Denies the emit_to command without any pre-configured scope.",+ "type": "string",+ "const": "core:event:deny-emit-to",+ "markdownDescription": "Denies the emit_to command without any pre-configured scope."+ },+ {+ "description": "Denies the listen command without any pre-configured scope.",+ "type": "string",+ "const": "core:event:deny-listen",+ "markdownDescription": "Denies the listen command without any pre-configured scope."+ },+ {+ "description": "Denies the unlisten command without any pre-configured scope.",+ "type": "string",+ "const": "core:event:deny-unlisten",+ "markdownDescription": "Denies the unlisten command without any pre-configured scope."+ },+ {+ "description": "Default permissions for the plugin, which enables all commands.\n#### This default permission set includes:\n\n- `allow-new`\n- `allow-from-bytes`\n- `allow-from-path`\n- `allow-rgba`\n- `allow-size`",+ "type": "string",+ "const": "core:image:default",+ "markdownDescription": "Default permissions for the plugin, which enables all commands.\n#### This default permission set includes:\n\n- `allow-new`\n- `allow-from-bytes`\n- `allow-from-path`\n- `allow-rgba`\n- `allow-size`"+ },+ {+ "description": "Enables the from_bytes command without any pre-configured scope.",+ "type": "string",+ "const": "core:image:allow-from-bytes",+ "markdownDescription": "Enables the from_bytes command without any pre-configured scope."+ },+ {+ "description": "Enables the from_path command without any pre-configured scope.",+ "type": "string",+ "const": "core:image:allow-from-path",+ "markdownDescription": "Enables the from_path command without any pre-configured scope."+ },+ {+ "description": "Enables the new command without any pre-configured scope.",+ "type": "string",+ "const": "core:image:allow-new",+ "markdownDescription": "Enables the new command without any pre-configured scope."+ },+ {+ "description": "Enables the rgba command without any pre-configured scope.",+ "type": "string",+ "const": "core:image:allow-rgba",+ "markdownDescription": "Enables the rgba command without any pre-configured scope."+ },+ {+ "description": "Enables the size command without any pre-configured scope.",+ "type": "string",+ "const": "core:image:allow-size",+ "markdownDescription": "Enables the size command without any pre-configured scope."+ },+ {+ "description": "Denies the from_bytes command without any pre-configured scope.",+ "type": "string",+ "const": "core:image:deny-from-bytes",+ "markdownDescription": "Denies the from_bytes command without any pre-configured scope."+ },+ {+ "description": "Denies the from_path command without any pre-configured scope.",+ "type": "string",+ "const": "core:image:deny-from-path",+ "markdownDescription": "Denies the from_path command without any pre-configured scope."+ },+ {+ "description": "Denies the new command without any pre-configured scope.",+ "type": "string",+ "const": "core:image:deny-new",+ "markdownDescription": "Denies the new command without any pre-configured scope."+ },+ {+ "description": "Denies the rgba command without any pre-configured scope.",+ "type": "string",+ "const": "core:image:deny-rgba",+ "markdownDescription": "Denies the rgba command without any pre-configured scope."+ },+ {+ "description": "Denies the size command without any pre-configured scope.",+ "type": "string",+ "const": "core:image:deny-size",+ "markdownDescription": "Denies the size command without any pre-configured scope."+ },+ {+ "description": "Default permissions for the plugin, which enables all commands.\n#### This default permission set includes:\n\n- `allow-new`\n- `allow-append`\n- `allow-prepend`\n- `allow-insert`\n- `allow-remove`\n- `allow-remove-at`\n- `allow-items`\n- `allow-get`\n- `allow-popup`\n- `allow-create-default`\n- `allow-set-as-app-menu`\n- `allow-set-as-window-menu`\n- `allow-text`\n- `allow-set-text`\n- `allow-is-enabled`\n- `allow-set-enabled`\n- `allow-set-accelerator`\n- `allow-set-as-windows-menu-for-nsapp`\n- `allow-set-as-help-menu-for-nsapp`\n- `allow-is-checked`\n- `allow-set-checked`\n- `allow-set-icon`",+ "type": "string",+ "const": "core:menu:default",+ "markdownDescription": "Default permissions for the plugin, which enables all commands.\n#### This default permission set includes:\n\n- `allow-new`\n- `allow-append`\n- `allow-prepend`\n- `allow-insert`\n- `allow-remove`\n- `allow-remove-at`\n- `allow-items`\n- `allow-get`\n- `allow-popup`\n- `allow-create-default`\n- `allow-set-as-app-menu`\n- `allow-set-as-window-menu`\n- `allow-text`\n- `allow-set-text`\n- `allow-is-enabled`\n- `allow-set-enabled`\n- `allow-set-accelerator`\n- `allow-set-as-windows-menu-for-nsapp`\n- `allow-set-as-help-menu-for-nsapp`\n- `allow-is-checked`\n- `allow-set-checked`\n- `allow-set-icon`"+ },+ {+ "description": "Enables the append command without any pre-configured scope.",+ "type": "string",+ "const": "core:menu:allow-append",+ "markdownDescription": "Enables the append command without any pre-configured scope."+ },+ {+ "description": "Enables the create_default command without any pre-configured scope.",+ "type": "string",+ "const": "core:menu:allow-create-default",+ "markdownDescription": "Enables the create_default command without any pre-configured scope."+ },+ {+ "description": "Enables the get command without any pre-configured scope.",+ "type": "string",+ "const": "core:menu:allow-get",+ "markdownDescription": "Enables the get command without any pre-configured scope."+ },+ {+ "description": "Enables the insert command without any pre-configured scope.",+ "type": "string",+ "const": "core:menu:allow-insert",+ "markdownDescription": "Enables the insert command without any pre-configured scope."+ },+ {+ "description": "Enables the is_checked command without any pre-configured scope.",+ "type": "string",+ "const": "core:menu:allow-is-checked",+ "markdownDescription": "Enables the is_checked command without any pre-configured scope."+ },+ {+ "description": "Enables the is_enabled command without any pre-configured scope.",+ "type": "string",+ "const": "core:menu:allow-is-enabled",+ "markdownDescription": "Enables the is_enabled command without any pre-configured scope."+ },+ {+ "description": "Enables the items command without any pre-configured scope.",+ "type": "string",+ "const": "core:menu:allow-items",+ "markdownDescription": "Enables the items command without any pre-configured scope."+ },+ {+ "description": "Enables the new command without any pre-configured scope.",+ "type": "string",+ "const": "core:menu:allow-new",+ "markdownDescription": "Enables the new command without any pre-configured scope."+ },+ {+ "description": "Enables the popup command without any pre-configured scope.",+ "type": "string",+ "const": "core:menu:allow-popup",+ "markdownDescription": "Enables the popup command without any pre-configured scope."+ },+ {+ "description": "Enables the prepend command without any pre-configured scope.",+ "type": "string",+ "const": "core:menu:allow-prepend",+ "markdownDescription": "Enables the prepend command without any pre-configured scope."+ },+ {+ "description": "Enables the remove command without any pre-configured scope.",+ "type": "string",+ "const": "core:menu:allow-remove",+ "markdownDescription": "Enables the remove command without any pre-configured scope."+ },+ {+ "description": "Enables the remove_at command without any pre-configured scope.",+ "type": "string",+ "const": "core:menu:allow-remove-at",+ "markdownDescription": "Enables the remove_at command without any pre-configured scope."+ },+ {+ "description": "Enables the set_accelerator command without any pre-configured scope.",+ "type": "string",+ "const": "core:menu:allow-set-accelerator",+ "markdownDescription": "Enables the set_accelerator command without any pre-configured scope."+ },+ {+ "description": "Enables the set_as_app_menu command without any pre-configured scope.",+ "type": "string",+ "const": "core:menu:allow-set-as-app-menu",+ "markdownDescription": "Enables the set_as_app_menu command without any pre-configured scope."+ },+ {+ "description": "Enables the set_as_help_menu_for_nsapp command without any pre-configured scope.",+ "type": "string",+ "const": "core:menu:allow-set-as-help-menu-for-nsapp",+ "markdownDescription": "Enables the set_as_help_menu_for_nsapp command without any pre-configured scope."+ },+ {+ "description": "Enables the set_as_window_menu command without any pre-configured scope.",+ "type": "string",+ "const": "core:menu:allow-set-as-window-menu",+ "markdownDescription": "Enables the set_as_window_menu command without any pre-configured scope."+ },+ {+ "description": "Enables the set_as_windows_menu_for_nsapp command without any pre-configured scope.",+ "type": "string",+ "const": "core:menu:allow-set-as-windows-menu-for-nsapp",+ "markdownDescription": "Enables the set_as_windows_menu_for_nsapp command without any pre-configured scope."+ },+ {+ "description": "Enables the set_checked command without any pre-configured scope.",+ "type": "string",+ "const": "core:menu:allow-set-checked",+ "markdownDescription": "Enables the set_checked command without any pre-configured scope."+ },+ {+ "description": "Enables the set_enabled command without any pre-configured scope.",+ "type": "string",+ "const": "core:menu:allow-set-enabled",+ "markdownDescription": "Enables the set_enabled command without any pre-configured scope."+ },+ {+ "description": "Enables the set_icon command without any pre-configured scope.",+ "type": "string",+ "const": "core:menu:allow-set-icon",+ "markdownDescription": "Enables the set_icon command without any pre-configured scope."+ },+ {+ "description": "Enables the set_text command without any pre-configured scope.",+ "type": "string",+ "const": "core:menu:allow-set-text",+ "markdownDescription": "Enables the set_text command without any pre-configured scope."+ },+ {+ "description": "Enables the text command without any pre-configured scope.",+ "type": "string",+ "const": "core:menu:allow-text",+ "markdownDescription": "Enables the text command without any pre-configured scope."+ },+ {+ "description": "Denies the append command without any pre-configured scope.",+ "type": "string",+ "const": "core:menu:deny-append",+ "markdownDescription": "Denies the append command without any pre-configured scope."+ },+ {+ "description": "Denies the create_default command without any pre-configured scope.",+ "type": "string",+ "const": "core:menu:deny-create-default",+ "markdownDescription": "Denies the create_default command without any pre-configured scope."+ },+ {+ "description": "Denies the get command without any pre-configured scope.",+ "type": "string",+ "const": "core:menu:deny-get",+ "markdownDescription": "Denies the get command without any pre-configured scope."+ },+ {+ "description": "Denies the insert command without any pre-configured scope.",+ "type": "string",+ "const": "core:menu:deny-insert",+ "markdownDescription": "Denies the insert command without any pre-configured scope."+ },+ {+ "description": "Denies the is_checked command without any pre-configured scope.",+ "type": "string",+ "const": "core:menu:deny-is-checked",+ "markdownDescription": "Denies the is_checked command without any pre-configured scope."+ },+ {+ "description": "Denies the is_enabled command without any pre-configured scope.",+ "type": "string",+ "const": "core:menu:deny-is-enabled",+ "markdownDescription": "Denies the is_enabled command without any pre-configured scope."+ },+ {+ "description": "Denies the items command without any pre-configured scope.",+ "type": "string",+ "const": "core:menu:deny-items",+ "markdownDescription": "Denies the items command without any pre-configured scope."+ },+ {+ "description": "Denies the new command without any pre-configured scope.",+ "type": "string",+ "const": "core:menu:deny-new",+ "markdownDescription": "Denies the new command without any pre-configured scope."+ },+ {+ "description": "Denies the popup command without any pre-configured scope.",+ "type": "string",+ "const": "core:menu:deny-popup",+ "markdownDescription": "Denies the popup command without any pre-configured scope."+ },+ {+ "description": "Denies the prepend command without any pre-configured scope.",+ "type": "string",+ "const": "core:menu:deny-prepend",+ "markdownDescription": "Denies the prepend command without any pre-configured scope."+ },+ {+ "description": "Denies the remove command without any pre-configured scope.",+ "type": "string",+ "const": "core:menu:deny-remove",+ "markdownDescription": "Denies the remove command without any pre-configured scope."+ },+ {+ "description": "Denies the remove_at command without any pre-configured scope.",+ "type": "string",+ "const": "core:menu:deny-remove-at",+ "markdownDescription": "Denies the remove_at command without any pre-configured scope."+ },+ {+ "description": "Denies the set_accelerator command without any pre-configured scope.",+ "type": "string",+ "const": "core:menu:deny-set-accelerator",+ "markdownDescription": "Denies the set_accelerator command without any pre-configured scope."+ },+ {+ "description": "Denies the set_as_app_menu command without any pre-configured scope.",+ "type": "string",+ "const": "core:menu:deny-set-as-app-menu",+ "markdownDescription": "Denies the set_as_app_menu command without any pre-configured scope."+ },+ {+ "description": "Denies the set_as_help_menu_for_nsapp command without any pre-configured scope.",+ "type": "string",+ "const": "core:menu:deny-set-as-help-menu-for-nsapp",+ "markdownDescription": "Denies the set_as_help_menu_for_nsapp command without any pre-configured scope."+ },+ {+ "description": "Denies the set_as_window_menu command without any pre-configured scope.",+ "type": "string",+ "const": "core:menu:deny-set-as-window-menu",+ "markdownDescription": "Denies the set_as_window_menu command without any pre-configured scope."+ },+ {+ "description": "Denies the set_as_windows_menu_for_nsapp command without any pre-configured scope.",+ "type": "string",+ "const": "core:menu:deny-set-as-windows-menu-for-nsapp",+ "markdownDescription": "Denies the set_as_windows_menu_for_nsapp command without any pre-configured scope."+ },+ {+ "description": "Denies the set_checked command without any pre-configured scope.",+ "type": "string",+ "const": "core:menu:deny-set-checked",+ "markdownDescription": "Denies the set_checked command without any pre-configured scope."+ },+ {+ "description": "Denies the set_enabled command without any pre-configured scope.",+ "type": "string",+ "const": "core:menu:deny-set-enabled",+ "markdownDescription": "Denies the set_enabled command without any pre-configured scope."+ },+ {+ "description": "Denies the set_icon command without any pre-configured scope.",+ "type": "string",+ "const": "core:menu:deny-set-icon",+ "markdownDescription": "Denies the set_icon command without any pre-configured scope."+ },+ {+ "description": "Denies the set_text command without any pre-configured scope.",+ "type": "string",+ "const": "core:menu:deny-set-text",+ "markdownDescription": "Denies the set_text command without any pre-configured scope."+ },+ {+ "description": "Denies the text command without any pre-configured scope.",+ "type": "string",+ "const": "core:menu:deny-text",+ "markdownDescription": "Denies the text command without any pre-configured scope."+ },+ {+ "description": "Default permissions for the plugin, which enables all commands.\n#### This default permission set includes:\n\n- `allow-resolve-directory`\n- `allow-resolve`\n- `allow-normalize`\n- `allow-join`\n- `allow-dirname`\n- `allow-extname`\n- `allow-basename`\n- `allow-is-absolute`",+ "type": "string",+ "const": "core:path:default",+ "markdownDescription": "Default permissions for the plugin, which enables all commands.\n#### This default permission set includes:\n\n- `allow-resolve-directory`\n- `allow-resolve`\n- `allow-normalize`\n- `allow-join`\n- `allow-dirname`\n- `allow-extname`\n- `allow-basename`\n- `allow-is-absolute`"+ },+ {+ "description": "Enables the basename command without any pre-configured scope.",+ "type": "string",+ "const": "core:path:allow-basename",+ "markdownDescription": "Enables the basename command without any pre-configured scope."+ },+ {+ "description": "Enables the dirname command without any pre-configured scope.",+ "type": "string",+ "const": "core:path:allow-dirname",+ "markdownDescription": "Enables the dirname command without any pre-configured scope."+ },+ {+ "description": "Enables the extname command without any pre-configured scope.",+ "type": "string",+ "const": "core:path:allow-extname",+ "markdownDescription": "Enables the extname command without any pre-configured scope."+ },+ {+ "description": "Enables the is_absolute command without any pre-configured scope.",+ "type": "string",+ "const": "core:path:allow-is-absolute",+ "markdownDescription": "Enables the is_absolute command without any pre-configured scope."+ },+ {+ "description": "Enables the join command without any pre-configured scope.",+ "type": "string",+ "const": "core:path:allow-join",+ "markdownDescription": "Enables the join command without any pre-configured scope."+ },+ {+ "description": "Enables the normalize command without any pre-configured scope.",+ "type": "string",+ "const": "core:path:allow-normalize",+ "markdownDescription": "Enables the normalize command without any pre-configured scope."+ },+ {+ "description": "Enables the resolve command without any pre-configured scope.",+ "type": "string",+ "const": "core:path:allow-resolve",+ "markdownDescription": "Enables the resolve command without any pre-configured scope."+ },+ {+ "description": "Enables the resolve_directory command without any pre-configured scope.",+ "type": "string",+ "const": "core:path:allow-resolve-directory",+ "markdownDescription": "Enables the resolve_directory command without any pre-configured scope."+ },+ {+ "description": "Denies the basename command without any pre-configured scope.",+ "type": "string",+ "const": "core:path:deny-basename",+ "markdownDescription": "Denies the basename command without any pre-configured scope."+ },+ {+ "description": "Denies the dirname command without any pre-configured scope.",+ "type": "string",+ "const": "core:path:deny-dirname",+ "markdownDescription": "Denies the dirname command without any pre-configured scope."+ },+ {+ "description": "Denies the extname command without any pre-configured scope.",+ "type": "string",+ "const": "core:path:deny-extname",+ "markdownDescription": "Denies the extname command without any pre-configured scope."+ },+ {+ "description": "Denies the is_absolute command without any pre-configured scope.",+ "type": "string",+ "const": "core:path:deny-is-absolute",+ "markdownDescription": "Denies the is_absolute command without any pre-configured scope."+ },+ {+ "description": "Denies the join command without any pre-configured scope.",+ "type": "string",+ "const": "core:path:deny-join",+ "markdownDescription": "Denies the join command without any pre-configured scope."+ },+ {+ "description": "Denies the normalize command without any pre-configured scope.",+ "type": "string",+ "const": "core:path:deny-normalize",+ "markdownDescription": "Denies the normalize command without any pre-configured scope."+ },+ {+ "description": "Denies the resolve command without any pre-configured scope.",+ "type": "string",+ "const": "core:path:deny-resolve",+ "markdownDescription": "Denies the resolve command without any pre-configured scope."+ },+ {+ "description": "Denies the resolve_directory command without any pre-configured scope.",+ "type": "string",+ "const": "core:path:deny-resolve-directory",+ "markdownDescription": "Denies the resolve_directory command without any pre-configured scope."+ },+ {+ "description": "Default permissions for the plugin, which enables all commands.\n#### This default permission set includes:\n\n- `allow-close`",+ "type": "string",+ "const": "core:resources:default",+ "markdownDescription": "Default permissions for the plugin, which enables all commands.\n#### This default permission set includes:\n\n- `allow-close`"+ },+ {+ "description": "Enables the close command without any pre-configured scope.",+ "type": "string",+ "const": "core:resources:allow-close",+ "markdownDescription": "Enables the close command without any pre-configured scope."+ },+ {+ "description": "Denies the close command without any pre-configured scope.",+ "type": "string",+ "const": "core:resources:deny-close",+ "markdownDescription": "Denies the close command without any pre-configured scope."+ },+ {+ "description": "Default permissions for the plugin, which enables all commands.\n#### This default permission set includes:\n\n- `allow-new`\n- `allow-get-by-id`\n- `allow-remove-by-id`\n- `allow-set-icon`\n- `allow-set-menu`\n- `allow-set-tooltip`\n- `allow-set-title`\n- `allow-set-visible`\n- `allow-set-temp-dir-path`\n- `allow-set-icon-as-template`\n- `allow-set-icon-with-as-template`\n- `allow-set-show-menu-on-left-click`",+ "type": "string",+ "const": "core:tray:default",+ "markdownDescription": "Default permissions for the plugin, which enables all commands.\n#### This default permission set includes:\n\n- `allow-new`\n- `allow-get-by-id`\n- `allow-remove-by-id`\n- `allow-set-icon`\n- `allow-set-menu`\n- `allow-set-tooltip`\n- `allow-set-title`\n- `allow-set-visible`\n- `allow-set-temp-dir-path`\n- `allow-set-icon-as-template`\n- `allow-set-icon-with-as-template`\n- `allow-set-show-menu-on-left-click`"+ },+ {+ "description": "Enables the get_by_id command without any pre-configured scope.",+ "type": "string",+ "const": "core:tray:allow-get-by-id",+ "markdownDescription": "Enables the get_by_id command without any pre-configured scope."+ },+ {+ "description": "Enables the new command without any pre-configured scope.",+ "type": "string",+ "const": "core:tray:allow-new",+ "markdownDescription": "Enables the new command without any pre-configured scope."+ },+ {+ "description": "Enables the remove_by_id command without any pre-configured scope.",+ "type": "string",+ "const": "core:tray:allow-remove-by-id",+ "markdownDescription": "Enables the remove_by_id command without any pre-configured scope."+ },+ {+ "description": "Enables the set_icon command without any pre-configured scope.",+ "type": "string",+ "const": "core:tray:allow-set-icon",+ "markdownDescription": "Enables the set_icon command without any pre-configured scope."+ },+ {+ "description": "Enables the set_icon_as_template command without any pre-configured scope.",+ "type": "string",+ "const": "core:tray:allow-set-icon-as-template",+ "markdownDescription": "Enables the set_icon_as_template command without any pre-configured scope."+ },+ {+ "description": "Enables the set_icon_with_as_template command without any pre-configured scope.",+ "type": "string",+ "const": "core:tray:allow-set-icon-with-as-template",+ "markdownDescription": "Enables the set_icon_with_as_template command without any pre-configured scope."+ },+ {+ "description": "Enables the set_menu command without any pre-configured scope.",+ "type": "string",+ "const": "core:tray:allow-set-menu",+ "markdownDescription": "Enables the set_menu command without any pre-configured scope."+ },+ {+ "description": "Enables the set_show_menu_on_left_click command without any pre-configured scope.",+ "type": "string",+ "const": "core:tray:allow-set-show-menu-on-left-click",+ "markdownDescription": "Enables the set_show_menu_on_left_click command without any pre-configured scope."+ },+ {+ "description": "Enables the set_temp_dir_path command without any pre-configured scope.",+ "type": "string",+ "const": "core:tray:allow-set-temp-dir-path",+ "markdownDescription": "Enables the set_temp_dir_path command without any pre-configured scope."+ },+ {+ "description": "Enables the set_title command without any pre-configured scope.",+ "type": "string",+ "const": "core:tray:allow-set-title",+ "markdownDescription": "Enables the set_title command without any pre-configured scope."+ },+ {+ "description": "Enables the set_tooltip command without any pre-configured scope.",+ "type": "string",+ "const": "core:tray:allow-set-tooltip",+ "markdownDescription": "Enables the set_tooltip command without any pre-configured scope."+ },+ {+ "description": "Enables the set_visible command without any pre-configured scope.",+ "type": "string",+ "const": "core:tray:allow-set-visible",+ "markdownDescription": "Enables the set_visible command without any pre-configured scope."+ },+ {+ "description": "Denies the get_by_id command without any pre-configured scope.",+ "type": "string",+ "const": "core:tray:deny-get-by-id",+ "markdownDescription": "Denies the get_by_id command without any pre-configured scope."+ },+ {+ "description": "Denies the new command without any pre-configured scope.",+ "type": "string",+ "const": "core:tray:deny-new",+ "markdownDescription": "Denies the new command without any pre-configured scope."+ },+ {+ "description": "Denies the remove_by_id command without any pre-configured scope.",+ "type": "string",+ "const": "core:tray:deny-remove-by-id",+ "markdownDescription": "Denies the remove_by_id command without any pre-configured scope."+ },+ {+ "description": "Denies the set_icon command without any pre-configured scope.",+ "type": "string",+ "const": "core:tray:deny-set-icon",+ "markdownDescription": "Denies the set_icon command without any pre-configured scope."+ },+ {+ "description": "Denies the set_icon_as_template command without any pre-configured scope.",+ "type": "string",+ "const": "core:tray:deny-set-icon-as-template",+ "markdownDescription": "Denies the set_icon_as_template command without any pre-configured scope."+ },+ {+ "description": "Denies the set_icon_with_as_template command without any pre-configured scope.",+ "type": "string",+ "const": "core:tray:deny-set-icon-with-as-template",+ "markdownDescription": "Denies the set_icon_with_as_template command without any pre-configured scope."+ },+ {+ "description": "Denies the set_menu command without any pre-configured scope.",+ "type": "string",+ "const": "core:tray:deny-set-menu",+ "markdownDescription": "Denies the set_menu command without any pre-configured scope."+ },+ {+ "description": "Denies the set_show_menu_on_left_click command without any pre-configured scope.",+ "type": "string",+ "const": "core:tray:deny-set-show-menu-on-left-click",+ "markdownDescription": "Denies the set_show_menu_on_left_click command without any pre-configured scope."+ },+ {+ "description": "Denies the set_temp_dir_path command without any pre-configured scope.",+ "type": "string",+ "const": "core:tray:deny-set-temp-dir-path",+ "markdownDescription": "Denies the set_temp_dir_path command without any pre-configured scope."+ },+ {+ "description": "Denies the set_title command without any pre-configured scope.",+ "type": "string",+ "const": "core:tray:deny-set-title",+ "markdownDescription": "Denies the set_title command without any pre-configured scope."+ },+ {+ "description": "Denies the set_tooltip command without any pre-configured scope.",+ "type": "string",+ "const": "core:tray:deny-set-tooltip",+ "markdownDescription": "Denies the set_tooltip command without any pre-configured scope."+ },+ {+ "description": "Denies the set_visible command without any pre-configured scope.",+ "type": "string",+ "const": "core:tray:deny-set-visible",+ "markdownDescription": "Denies the set_visible command without any pre-configured scope."+ },+ {+ "description": "Default permissions for the plugin.\n#### This default permission set includes:\n\n- `allow-get-all-webviews`\n- `allow-webview-position`\n- `allow-webview-size`\n- `allow-internal-toggle-devtools`",+ "type": "string",+ "const": "core:webview:default",+ "markdownDescription": "Default permissions for the plugin.\n#### This default permission set includes:\n\n- `allow-get-all-webviews`\n- `allow-webview-position`\n- `allow-webview-size`\n- `allow-internal-toggle-devtools`"+ },+ {+ "description": "Enables the clear_all_browsing_data command without any pre-configured scope.",+ "type": "string",+ "const": "core:webview:allow-clear-all-browsing-data",+ "markdownDescription": "Enables the clear_all_browsing_data command without any pre-configured scope."+ },+ {+ "description": "Enables the create_webview command without any pre-configured scope.",+ "type": "string",+ "const": "core:webview:allow-create-webview",+ "markdownDescription": "Enables the create_webview command without any pre-configured scope."+ },+ {+ "description": "Enables the create_webview_window command without any pre-configured scope.",+ "type": "string",+ "const": "core:webview:allow-create-webview-window",+ "markdownDescription": "Enables the create_webview_window command without any pre-configured scope."+ },+ {+ "description": "Enables the get_all_webviews command without any pre-configured scope.",+ "type": "string",+ "const": "core:webview:allow-get-all-webviews",+ "markdownDescription": "Enables the get_all_webviews command without any pre-configured scope."+ },+ {+ "description": "Enables the internal_toggle_devtools command without any pre-configured scope.",+ "type": "string",+ "const": "core:webview:allow-internal-toggle-devtools",+ "markdownDescription": "Enables the internal_toggle_devtools command without any pre-configured scope."+ },+ {+ "description": "Enables the print command without any pre-configured scope.",+ "type": "string",+ "const": "core:webview:allow-print",+ "markdownDescription": "Enables the print command without any pre-configured scope."+ },+ {+ "description": "Enables the reparent command without any pre-configured scope.",+ "type": "string",+ "const": "core:webview:allow-reparent",+ "markdownDescription": "Enables the reparent command without any pre-configured scope."+ },+ {+ "description": "Enables the set_webview_auto_resize command without any pre-configured scope.",+ "type": "string",+ "const": "core:webview:allow-set-webview-auto-resize",+ "markdownDescription": "Enables the set_webview_auto_resize command without any pre-configured scope."+ },+ {+ "description": "Enables the set_webview_background_color command without any pre-configured scope.",+ "type": "string",+ "const": "core:webview:allow-set-webview-background-color",+ "markdownDescription": "Enables the set_webview_background_color command without any pre-configured scope."+ },+ {+ "description": "Enables the set_webview_focus command without any pre-configured scope.",+ "type": "string",+ "const": "core:webview:allow-set-webview-focus",+ "markdownDescription": "Enables the set_webview_focus command without any pre-configured scope."+ },+ {+ "description": "Enables the set_webview_position command without any pre-configured scope.",+ "type": "string",+ "const": "core:webview:allow-set-webview-position",+ "markdownDescription": "Enables the set_webview_position command without any pre-configured scope."+ },+ {+ "description": "Enables the set_webview_size command without any pre-configured scope.",+ "type": "string",+ "const": "core:webview:allow-set-webview-size",+ "markdownDescription": "Enables the set_webview_size command without any pre-configured scope."+ },+ {+ "description": "Enables the set_webview_zoom command without any pre-configured scope.",+ "type": "string",+ "const": "core:webview:allow-set-webview-zoom",+ "markdownDescription": "Enables the set_webview_zoom command without any pre-configured scope."+ },+ {+ "description": "Enables the webview_close command without any pre-configured scope.",+ "type": "string",+ "const": "core:webview:allow-webview-close",+ "markdownDescription": "Enables the webview_close command without any pre-configured scope."+ },+ {+ "description": "Enables the webview_hide command without any pre-configured scope.",+ "type": "string",+ "const": "core:webview:allow-webview-hide",+ "markdownDescription": "Enables the webview_hide command without any pre-configured scope."+ },+ {+ "description": "Enables the webview_position command without any pre-configured scope.",+ "type": "string",+ "const": "core:webview:allow-webview-position",+ "markdownDescription": "Enables the webview_position command without any pre-configured scope."+ },+ {+ "description": "Enables the webview_show command without any pre-configured scope.",+ "type": "string",+ "const": "core:webview:allow-webview-show",+ "markdownDescription": "Enables the webview_show command without any pre-configured scope."+ },+ {+ "description": "Enables the webview_size command without any pre-configured scope.",+ "type": "string",+ "const": "core:webview:allow-webview-size",+ "markdownDescription": "Enables the webview_size command without any pre-configured scope."+ },+ {+ "description": "Denies the clear_all_browsing_data command without any pre-configured scope.",+ "type": "string",+ "const": "core:webview:deny-clear-all-browsing-data",+ "markdownDescription": "Denies the clear_all_browsing_data command without any pre-configured scope."+ },+ {+ "description": "Denies the create_webview command without any pre-configured scope.",+ "type": "string",+ "const": "core:webview:deny-create-webview",+ "markdownDescription": "Denies the create_webview command without any pre-configured scope."+ },+ {+ "description": "Denies the create_webview_window command without any pre-configured scope.",+ "type": "string",+ "const": "core:webview:deny-create-webview-window",+ "markdownDescription": "Denies the create_webview_window command without any pre-configured scope."+ },+ {+ "description": "Denies the get_all_webviews command without any pre-configured scope.",+ "type": "string",+ "const": "core:webview:deny-get-all-webviews",+ "markdownDescription": "Denies the get_all_webviews command without any pre-configured scope."+ },+ {+ "description": "Denies the internal_toggle_devtools command without any pre-configured scope.",+ "type": "string",+ "const": "core:webview:deny-internal-toggle-devtools",+ "markdownDescription": "Denies the internal_toggle_devtools command without any pre-configured scope."+ },+ {+ "description": "Denies the print command without any pre-configured scope.",+ "type": "string",+ "const": "core:webview:deny-print",+ "markdownDescription": "Denies the print command without any pre-configured scope."+ },+ {+ "description": "Denies the reparent command without any pre-configured scope.",+ "type": "string",+ "const": "core:webview:deny-reparent",+ "markdownDescription": "Denies the reparent command without any pre-configured scope."+ },+ {+ "description": "Denies the set_webview_auto_resize command without any pre-configured scope.",+ "type": "string",+ "const": "core:webview:deny-set-webview-auto-resize",+ "markdownDescription": "Denies the set_webview_auto_resize command without any pre-configured scope."+ },+ {+ "description": "Denies the set_webview_background_color command without any pre-configured scope.",+ "type": "string",+ "const": "core:webview:deny-set-webview-background-color",+ "markdownDescription": "Denies the set_webview_background_color command without any pre-configured scope."+ },+ {+ "description": "Denies the set_webview_focus command without any pre-configured scope.",+ "type": "string",+ "const": "core:webview:deny-set-webview-focus",+ "markdownDescription": "Denies the set_webview_focus command without any pre-configured scope."+ },+ {+ "description": "Denies the set_webview_position command without any pre-configured scope.",+ "type": "string",+ "const": "core:webview:deny-set-webview-position",+ "markdownDescription": "Denies the set_webview_position command without any pre-configured scope."+ },+ {+ "description": "Denies the set_webview_size command without any pre-configured scope.",+ "type": "string",+ "const": "core:webview:deny-set-webview-size",+ "markdownDescription": "Denies the set_webview_size command without any pre-configured scope."+ },+ {+ "description": "Denies the set_webview_zoom command without any pre-configured scope.",+ "type": "string",+ "const": "core:webview:deny-set-webview-zoom",+ "markdownDescription": "Denies the set_webview_zoom command without any pre-configured scope."+ },+ {+ "description": "Denies the webview_close command without any pre-configured scope.",+ "type": "string",+ "const": "core:webview:deny-webview-close",+ "markdownDescription": "Denies the webview_close command without any pre-configured scope."+ },+ {+ "description": "Denies the webview_hide command without any pre-configured scope.",+ "type": "string",+ "const": "core:webview:deny-webview-hide",+ "markdownDescription": "Denies the webview_hide command without any pre-configured scope."+ },+ {+ "description": "Denies the webview_position command without any pre-configured scope.",+ "type": "string",+ "const": "core:webview:deny-webview-position",+ "markdownDescription": "Denies the webview_position command without any pre-configured scope."+ },+ {+ "description": "Denies the webview_show command without any pre-configured scope.",+ "type": "string",+ "const": "core:webview:deny-webview-show",+ "markdownDescription": "Denies the webview_show command without any pre-configured scope."+ },+ {+ "description": "Denies the webview_size command without any pre-configured scope.",+ "type": "string",+ "const": "core:webview:deny-webview-size",+ "markdownDescription": "Denies the webview_size command without any pre-configured scope."+ },+ {+ "description": "Default permissions for the plugin.\n#### This default permission set includes:\n\n- `allow-get-all-windows`\n- `allow-scale-factor`\n- `allow-inner-position`\n- `allow-outer-position`\n- `allow-inner-size`\n- `allow-outer-size`\n- `allow-is-fullscreen`\n- `allow-is-minimized`\n- `allow-is-maximized`\n- `allow-is-focused`\n- `allow-is-decorated`\n- `allow-is-resizable`\n- `allow-is-maximizable`\n- `allow-is-minimizable`\n- `allow-is-closable`\n- `allow-is-visible`\n- `allow-is-enabled`\n- `allow-title`\n- `allow-current-monitor`\n- `allow-primary-monitor`\n- `allow-monitor-from-point`\n- `allow-available-monitors`\n- `allow-cursor-position`\n- `allow-theme`\n- `allow-is-always-on-top`\n- `allow-activity-name`\n- `allow-scene-identifier`\n- `allow-internal-toggle-maximize`",+ "type": "string",+ "const": "core:window:default",+ "markdownDescription": "Default permissions for the plugin.\n#### This default permission set includes:\n\n- `allow-get-all-windows`\n- `allow-scale-factor`\n- `allow-inner-position`\n- `allow-outer-position`\n- `allow-inner-size`\n- `allow-outer-size`\n- `allow-is-fullscreen`\n- `allow-is-minimized`\n- `allow-is-maximized`\n- `allow-is-focused`\n- `allow-is-decorated`\n- `allow-is-resizable`\n- `allow-is-maximizable`\n- `allow-is-minimizable`\n- `allow-is-closable`\n- `allow-is-visible`\n- `allow-is-enabled`\n- `allow-title`\n- `allow-current-monitor`\n- `allow-primary-monitor`\n- `allow-monitor-from-point`\n- `allow-available-monitors`\n- `allow-cursor-position`\n- `allow-theme`\n- `allow-is-always-on-top`\n- `allow-activity-name`\n- `allow-scene-identifier`\n- `allow-internal-toggle-maximize`"+ },+ {+ "description": "Enables the activity_name command without any pre-configured scope.",+ "type": "string",+ "const": "core:window:allow-activity-name",+ "markdownDescription": "Enables the activity_name command without any pre-configured scope."+ },+ {+ "description": "Enables the available_monitors command without any pre-configured scope.",+ "type": "string",+ "const": "core:window:allow-available-monitors",+ "markdownDescription": "Enables the available_monitors command without any pre-configured scope."+ },+ {+ "description": "Enables the center command without any pre-configured scope.",+ "type": "string",+ "const": "core:window:allow-center",+ "markdownDescription": "Enables the center command without any pre-configured scope."+ },+ {+ "description": "Enables the close command without any pre-configured scope.",+ "type": "string",+ "const": "core:window:allow-close",+ "markdownDescription": "Enables the close command without any pre-configured scope."+ },+ {+ "description": "Enables the create command without any pre-configured scope.",+ "type": "string",+ "const": "core:window:allow-create",+ "markdownDescription": "Enables the create command without any pre-configured scope."+ },+ {+ "description": "Enables the current_monitor command without any pre-configured scope.",+ "type": "string",+ "const": "core:window:allow-current-monitor",+ "markdownDescription": "Enables the current_monitor command without any pre-configured scope."+ },+ {+ "description": "Enables the cursor_position command without any pre-configured scope.",+ "type": "string",+ "const": "core:window:allow-cursor-position",+ "markdownDescription": "Enables the cursor_position command without any pre-configured scope."+ },+ {+ "description": "Enables the destroy command without any pre-configured scope.",+ "type": "string",+ "const": "core:window:allow-destroy",+ "markdownDescription": "Enables the destroy command without any pre-configured scope."+ },+ {+ "description": "Enables the get_all_windows command without any pre-configured scope.",+ "type": "string",+ "const": "core:window:allow-get-all-windows",+ "markdownDescription": "Enables the get_all_windows command without any pre-configured scope."+ },+ {+ "description": "Enables the hide command without any pre-configured scope.",+ "type": "string",+ "const": "core:window:allow-hide",+ "markdownDescription": "Enables the hide command without any pre-configured scope."+ },+ {+ "description": "Enables the inner_position command without any pre-configured scope.",+ "type": "string",+ "const": "core:window:allow-inner-position",+ "markdownDescription": "Enables the inner_position command without any pre-configured scope."+ },+ {+ "description": "Enables the inner_size command without any pre-configured scope.",+ "type": "string",+ "const": "core:window:allow-inner-size",+ "markdownDescription": "Enables the inner_size command without any pre-configured scope."+ },+ {+ "description": "Enables the internal_toggle_maximize command without any pre-configured scope.",+ "type": "string",+ "const": "core:window:allow-internal-toggle-maximize",+ "markdownDescription": "Enables the internal_toggle_maximize command without any pre-configured scope."+ },+ {+ "description": "Enables the is_always_on_top command without any pre-configured scope.",+ "type": "string",+ "const": "core:window:allow-is-always-on-top",+ "markdownDescription": "Enables the is_always_on_top command without any pre-configured scope."+ },+ {+ "description": "Enables the is_closable command without any pre-configured scope.",+ "type": "string",+ "const": "core:window:allow-is-closable",+ "markdownDescription": "Enables the is_closable command without any pre-configured scope."+ },+ {+ "description": "Enables the is_decorated command without any pre-configured scope.",+ "type": "string",+ "const": "core:window:allow-is-decorated",+ "markdownDescription": "Enables the is_decorated command without any pre-configured scope."+ },+ {+ "description": "Enables the is_enabled command without any pre-configured scope.",+ "type": "string",+ "const": "core:window:allow-is-enabled",+ "markdownDescription": "Enables the is_enabled command without any pre-configured scope."+ },+ {+ "description": "Enables the is_focused command without any pre-configured scope.",+ "type": "string",+ "const": "core:window:allow-is-focused",+ "markdownDescription": "Enables the is_focused command without any pre-configured scope."+ },+ {+ "description": "Enables the is_fullscreen command without any pre-configured scope.",+ "type": "string",+ "const": "core:window:allow-is-fullscreen",+ "markdownDescription": "Enables the is_fullscreen command without any pre-configured scope."+ },+ {+ "description": "Enables the is_maximizable command without any pre-configured scope.",+ "type": "string",+ "const": "core:window:allow-is-maximizable",+ "markdownDescription": "Enables the is_maximizable command without any pre-configured scope."+ },+ {+ "description": "Enables the is_maximized command without any pre-configured scope.",+ "type": "string",+ "const": "core:window:allow-is-maximized",+ "markdownDescription": "Enables the is_maximized command without any pre-configured scope."+ },+ {+ "description": "Enables the is_minimizable command without any pre-configured scope.",+ "type": "string",+ "const": "core:window:allow-is-minimizable",+ "markdownDescription": "Enables the is_minimizable command without any pre-configured scope."+ },+ {+ "description": "Enables the is_minimized command without any pre-configured scope.",+ "type": "string",+ "const": "core:window:allow-is-minimized",+ "markdownDescription": "Enables the is_minimized command without any pre-configured scope."+ },+ {+ "description": "Enables the is_resizable command without any pre-configured scope.",+ "type": "string",+ "const": "core:window:allow-is-resizable",+ "markdownDescription": "Enables the is_resizable command without any pre-configured scope."+ },+ {+ "description": "Enables the is_visible command without any pre-configured scope.",+ "type": "string",+ "const": "core:window:allow-is-visible",+ "markdownDescription": "Enables the is_visible command without any pre-configured scope."+ },+ {+ "description": "Enables the maximize command without any pre-configured scope.",+ "type": "string",+ "const": "core:window:allow-maximize",+ "markdownDescription": "Enables the maximize command without any pre-configured scope."+ },+ {+ "description": "Enables the minimize command without any pre-configured scope.",+ "type": "string",+ "const": "core:window:allow-minimize",+ "markdownDescription": "Enables the minimize command without any pre-configured scope."+ },+ {+ "description": "Enables the monitor_from_point command without any pre-configured scope.",+ "type": "string",+ "const": "core:window:allow-monitor-from-point",+ "markdownDescription": "Enables the monitor_from_point command without any pre-configured scope."+ },+ {+ "description": "Enables the outer_position command without any pre-configured scope.",+ "type": "string",+ "const": "core:window:allow-outer-position",+ "markdownDescription": "Enables the outer_position command without any pre-configured scope."+ },+ {+ "description": "Enables the outer_size command without any pre-configured scope.",+ "type": "string",+ "const": "core:window:allow-outer-size",+ "markdownDescription": "Enables the outer_size command without any pre-configured scope."+ },+ {+ "description": "Enables the primary_monitor command without any pre-configured scope.",+ "type": "string",+ "const": "core:window:allow-primary-monitor",+ "markdownDescription": "Enables the primary_monitor command without any pre-configured scope."+ },+ {+ "description": "Enables the request_user_attention command without any pre-configured scope.",+ "type": "string",+ "const": "core:window:allow-request-user-attention",+ "markdownDescription": "Enables the request_user_attention command without any pre-configured scope."+ },+ {+ "description": "Enables the scale_factor command without any pre-configured scope.",+ "type": "string",+ "const": "core:window:allow-scale-factor",+ "markdownDescription": "Enables the scale_factor command without any pre-configured scope."+ },+ {+ "description": "Enables the scene_identifier command without any pre-configured scope.",+ "type": "string",+ "const": "core:window:allow-scene-identifier",+ "markdownDescription": "Enables the scene_identifier command without any pre-configured scope."+ },+ {+ "description": "Enables the set_always_on_bottom command without any pre-configured scope.",+ "type": "string",+ "const": "core:window:allow-set-always-on-bottom",+ "markdownDescription": "Enables the set_always_on_bottom command without any pre-configured scope."+ },+ {+ "description": "Enables the set_always_on_top command without any pre-configured scope.",+ "type": "string",+ "const": "core:window:allow-set-always-on-top",+ "markdownDescription": "Enables the set_always_on_top command without any pre-configured scope."+ },+ {+ "description": "Enables the set_background_color command without any pre-configured scope.",+ "type": "string",+ "const": "core:window:allow-set-background-color",+ "markdownDescription": "Enables the set_background_color command without any pre-configured scope."+ },+ {+ "description": "Enables the set_badge_count command without any pre-configured scope.",+ "type": "string",+ "const": "core:window:allow-set-badge-count",+ "markdownDescription": "Enables the set_badge_count command without any pre-configured scope."+ },+ {+ "description": "Enables the set_badge_label command without any pre-configured scope.",+ "type": "string",+ "const": "core:window:allow-set-badge-label",+ "markdownDescription": "Enables the set_badge_label command without any pre-configured scope."+ },+ {+ "description": "Enables the set_closable command without any pre-configured scope.",+ "type": "string",+ "const": "core:window:allow-set-closable",+ "markdownDescription": "Enables the set_closable command without any pre-configured scope."+ },+ {+ "description": "Enables the set_content_protected command without any pre-configured scope.",+ "type": "string",+ "const": "core:window:allow-set-content-protected",+ "markdownDescription": "Enables the set_content_protected command without any pre-configured scope."+ },+ {+ "description": "Enables the set_cursor_grab command without any pre-configured scope.",+ "type": "string",+ "const": "core:window:allow-set-cursor-grab",+ "markdownDescription": "Enables the set_cursor_grab command without any pre-configured scope."+ },+ {+ "description": "Enables the set_cursor_icon command without any pre-configured scope.",+ "type": "string",+ "const": "core:window:allow-set-cursor-icon",+ "markdownDescription": "Enables the set_cursor_icon command without any pre-configured scope."+ },+ {+ "description": "Enables the set_cursor_position command without any pre-configured scope.",+ "type": "string",+ "const": "core:window:allow-set-cursor-position",+ "markdownDescription": "Enables the set_cursor_position command without any pre-configured scope."+ },+ {+ "description": "Enables the set_cursor_visible command without any pre-configured scope.",+ "type": "string",+ "const": "core:window:allow-set-cursor-visible",+ "markdownDescription": "Enables the set_cursor_visible command without any pre-configured scope."+ },+ {+ "description": "Enables the set_decorations command without any pre-configured scope.",+ "type": "string",+ "const": "core:window:allow-set-decorations",+ "markdownDescription": "Enables the set_decorations command without any pre-configured scope."+ },+ {+ "description": "Enables the set_effects command without any pre-configured scope.",+ "type": "string",+ "const": "core:window:allow-set-effects",+ "markdownDescription": "Enables the set_effects command without any pre-configured scope."+ },+ {+ "description": "Enables the set_enabled command without any pre-configured scope.",+ "type": "string",+ "const": "core:window:allow-set-enabled",+ "markdownDescription": "Enables the set_enabled command without any pre-configured scope."+ },+ {+ "description": "Enables the set_focus command without any pre-configured scope.",+ "type": "string",+ "const": "core:window:allow-set-focus",+ "markdownDescription": "Enables the set_focus command without any pre-configured scope."+ },+ {+ "description": "Enables the set_focusable command without any pre-configured scope.",+ "type": "string",+ "const": "core:window:allow-set-focusable",+ "markdownDescription": "Enables the set_focusable command without any pre-configured scope."+ },+ {+ "description": "Enables the set_fullscreen command without any pre-configured scope.",+ "type": "string",+ "const": "core:window:allow-set-fullscreen",+ "markdownDescription": "Enables the set_fullscreen command without any pre-configured scope."+ },+ {+ "description": "Enables the set_fullscreen_on_monitor command without any pre-configured scope.",+ "type": "string",+ "const": "core:window:allow-set-fullscreen-on-monitor",+ "markdownDescription": "Enables the set_fullscreen_on_monitor command without any pre-configured scope."+ },+ {+ "description": "Enables the set_icon command without any pre-configured scope.",+ "type": "string",+ "const": "core:window:allow-set-icon",+ "markdownDescription": "Enables the set_icon command without any pre-configured scope."+ },+ {+ "description": "Enables the set_ignore_cursor_events command without any pre-configured scope.",+ "type": "string",+ "const": "core:window:allow-set-ignore-cursor-events",+ "markdownDescription": "Enables the set_ignore_cursor_events command without any pre-configured scope."+ },+ {+ "description": "Enables the set_max_size command without any pre-configured scope.",+ "type": "string",+ "const": "core:window:allow-set-max-size",+ "markdownDescription": "Enables the set_max_size command without any pre-configured scope."+ },+ {+ "description": "Enables the set_maximizable command without any pre-configured scope.",+ "type": "string",+ "const": "core:window:allow-set-maximizable",+ "markdownDescription": "Enables the set_maximizable command without any pre-configured scope."+ },+ {+ "description": "Enables the set_min_size command without any pre-configured scope.",+ "type": "string",+ "const": "core:window:allow-set-min-size",+ "markdownDescription": "Enables the set_min_size command without any pre-configured scope."+ },+ {+ "description": "Enables the set_minimizable command without any pre-configured scope.",+ "type": "string",+ "const": "core:window:allow-set-minimizable",+ "markdownDescription": "Enables the set_minimizable command without any pre-configured scope."+ },+ {+ "description": "Enables the set_overlay_icon command without any pre-configured scope.",+ "type": "string",+ "const": "core:window:allow-set-overlay-icon",+ "markdownDescription": "Enables the set_overlay_icon command without any pre-configured scope."+ },+ {+ "description": "Enables the set_position command without any pre-configured scope.",+ "type": "string",+ "const": "core:window:allow-set-position",+ "markdownDescription": "Enables the set_position command without any pre-configured scope."+ },+ {+ "description": "Enables the set_progress_bar command without any pre-configured scope.",+ "type": "string",+ "const": "core:window:allow-set-progress-bar",+ "markdownDescription": "Enables the set_progress_bar command without any pre-configured scope."+ },+ {+ "description": "Enables the set_resizable command without any pre-configured scope.",+ "type": "string",+ "const": "core:window:allow-set-resizable",+ "markdownDescription": "Enables the set_resizable command without any pre-configured scope."+ },+ {+ "description": "Enables the set_shadow command without any pre-configured scope.",+ "type": "string",+ "const": "core:window:allow-set-shadow",+ "markdownDescription": "Enables the set_shadow command without any pre-configured scope."+ },+ {+ "description": "Enables the set_simple_fullscreen command without any pre-configured scope.",+ "type": "string",+ "const": "core:window:allow-set-simple-fullscreen",+ "markdownDescription": "Enables the set_simple_fullscreen command without any pre-configured scope."+ },+ {+ "description": "Enables the set_size command without any pre-configured scope.",+ "type": "string",+ "const": "core:window:allow-set-size",+ "markdownDescription": "Enables the set_size command without any pre-configured scope."+ },+ {+ "description": "Enables the set_size_constraints command without any pre-configured scope.",+ "type": "string",+ "const": "core:window:allow-set-size-constraints",+ "markdownDescription": "Enables the set_size_constraints command without any pre-configured scope."+ },+ {+ "description": "Enables the set_skip_taskbar command without any pre-configured scope.",+ "type": "string",+ "const": "core:window:allow-set-skip-taskbar",+ "markdownDescription": "Enables the set_skip_taskbar command without any pre-configured scope."+ },+ {+ "description": "Enables the set_theme command without any pre-configured scope.",+ "type": "string",+ "const": "core:window:allow-set-theme",+ "markdownDescription": "Enables the set_theme command without any pre-configured scope."+ },+ {+ "description": "Enables the set_title command without any pre-configured scope.",+ "type": "string",+ "const": "core:window:allow-set-title",+ "markdownDescription": "Enables the set_title command without any pre-configured scope."+ },+ {+ "description": "Enables the set_title_bar_style command without any pre-configured scope.",+ "type": "string",+ "const": "core:window:allow-set-title-bar-style",+ "markdownDescription": "Enables the set_title_bar_style command without any pre-configured scope."+ },+ {+ "description": "Enables the set_visible_on_all_workspaces command without any pre-configured scope.",+ "type": "string",+ "const": "core:window:allow-set-visible-on-all-workspaces",+ "markdownDescription": "Enables the set_visible_on_all_workspaces command without any pre-configured scope."+ },+ {+ "description": "Enables the show command without any pre-configured scope.",+ "type": "string",+ "const": "core:window:allow-show",+ "markdownDescription": "Enables the show command without any pre-configured scope."+ },+ {+ "description": "Enables the start_dragging command without any pre-configured scope.",+ "type": "string",+ "const": "core:window:allow-start-dragging",+ "markdownDescription": "Enables the start_dragging command without any pre-configured scope."+ },+ {+ "description": "Enables the start_resize_dragging command without any pre-configured scope.",+ "type": "string",+ "const": "core:window:allow-start-resize-dragging",+ "markdownDescription": "Enables the start_resize_dragging command without any pre-configured scope."+ },+ {+ "description": "Enables the theme command without any pre-configured scope.",+ "type": "string",+ "const": "core:window:allow-theme",+ "markdownDescription": "Enables the theme command without any pre-configured scope."+ },+ {+ "description": "Enables the title command without any pre-configured scope.",+ "type": "string",+ "const": "core:window:allow-title",+ "markdownDescription": "Enables the title command without any pre-configured scope."+ },+ {+ "description": "Enables the toggle_maximize command without any pre-configured scope.",+ "type": "string",+ "const": "core:window:allow-toggle-maximize",+ "markdownDescription": "Enables the toggle_maximize command without any pre-configured scope."+ },+ {+ "description": "Enables the unmaximize command without any pre-configured scope.",+ "type": "string",+ "const": "core:window:allow-unmaximize",+ "markdownDescription": "Enables the unmaximize command without any pre-configured scope."+ },+ {+ "description": "Enables the unminimize command without any pre-configured scope.",+ "type": "string",+ "const": "core:window:allow-unminimize",+ "markdownDescription": "Enables the unminimize command without any pre-configured scope."+ },+ {+ "description": "Denies the activity_name command without any pre-configured scope.",+ "type": "string",+ "const": "core:window:deny-activity-name",+ "markdownDescription": "Denies the activity_name command without any pre-configured scope."+ },+ {+ "description": "Denies the available_monitors command without any pre-configured scope.",+ "type": "string",+ "const": "core:window:deny-available-monitors",+ "markdownDescription": "Denies the available_monitors command without any pre-configured scope."+ },+ {+ "description": "Denies the center command without any pre-configured scope.",+ "type": "string",+ "const": "core:window:deny-center",+ "markdownDescription": "Denies the center command without any pre-configured scope."+ },+ {+ "description": "Denies the close command without any pre-configured scope.",+ "type": "string",+ "const": "core:window:deny-close",+ "markdownDescription": "Denies the close command without any pre-configured scope."+ },+ {+ "description": "Denies the create command without any pre-configured scope.",+ "type": "string",+ "const": "core:window:deny-create",+ "markdownDescription": "Denies the create command without any pre-configured scope."+ },+ {+ "description": "Denies the current_monitor command without any pre-configured scope.",+ "type": "string",+ "const": "core:window:deny-current-monitor",+ "markdownDescription": "Denies the current_monitor command without any pre-configured scope."+ },+ {+ "description": "Denies the cursor_position command without any pre-configured scope.",+ "type": "string",+ "const": "core:window:deny-cursor-position",+ "markdownDescription": "Denies the cursor_position command without any pre-configured scope."+ },+ {+ "description": "Denies the destroy command without any pre-configured scope.",+ "type": "string",+ "const": "core:window:deny-destroy",+ "markdownDescription": "Denies the destroy command without any pre-configured scope."+ },+ {+ "description": "Denies the get_all_windows command without any pre-configured scope.",+ "type": "string",+ "const": "core:window:deny-get-all-windows",+ "markdownDescription": "Denies the get_all_windows command without any pre-configured scope."+ },+ {+ "description": "Denies the hide command without any pre-configured scope.",+ "type": "string",+ "const": "core:window:deny-hide",+ "markdownDescription": "Denies the hide command without any pre-configured scope."+ },+ {+ "description": "Denies the inner_position command without any pre-configured scope.",+ "type": "string",+ "const": "core:window:deny-inner-position",+ "markdownDescription": "Denies the inner_position command without any pre-configured scope."+ },+ {+ "description": "Denies the inner_size command without any pre-configured scope.",+ "type": "string",+ "const": "core:window:deny-inner-size",+ "markdownDescription": "Denies the inner_size command without any pre-configured scope."+ },+ {+ "description": "Denies the internal_toggle_maximize command without any pre-configured scope.",+ "type": "string",+ "const": "core:window:deny-internal-toggle-maximize",+ "markdownDescription": "Denies the internal_toggle_maximize command without any pre-configured scope."+ },+ {+ "description": "Denies the is_always_on_top command without any pre-configured scope.",+ "type": "string",+ "const": "core:window:deny-is-always-on-top",+ "markdownDescription": "Denies the is_always_on_top command without any pre-configured scope."+ },+ {+ "description": "Denies the is_closable command without any pre-configured scope.",+ "type": "string",+ "const": "core:window:deny-is-closable",+ "markdownDescription": "Denies the is_closable command without any pre-configured scope."+ },+ {+ "description": "Denies the is_decorated command without any pre-configured scope.",+ "type": "string",+ "const": "core:window:deny-is-decorated",+ "markdownDescription": "Denies the is_decorated command without any pre-configured scope."+ },+ {+ "description": "Denies the is_enabled command without any pre-configured scope.",+ "type": "string",+ "const": "core:window:deny-is-enabled",+ "markdownDescription": "Denies the is_enabled command without any pre-configured scope."+ },+ {+ "description": "Denies the is_focused command without any pre-configured scope.",+ "type": "string",+ "const": "core:window:deny-is-focused",+ "markdownDescription": "Denies the is_focused command without any pre-configured scope."+ },+ {+ "description": "Denies the is_fullscreen command without any pre-configured scope.",+ "type": "string",+ "const": "core:window:deny-is-fullscreen",+ "markdownDescription": "Denies the is_fullscreen command without any pre-configured scope."+ },+ {+ "description": "Denies the is_maximizable command without any pre-configured scope.",+ "type": "string",+ "const": "core:window:deny-is-maximizable",+ "markdownDescription": "Denies the is_maximizable command without any pre-configured scope."+ },+ {+ "description": "Denies the is_maximized command without any pre-configured scope.",+ "type": "string",+ "const": "core:window:deny-is-maximized",+ "markdownDescription": "Denies the is_maximized command without any pre-configured scope."+ },+ {+ "description": "Denies the is_minimizable command without any pre-configured scope.",+ "type": "string",+ "const": "core:window:deny-is-minimizable",+ "markdownDescription": "Denies the is_minimizable command without any pre-configured scope."+ },+ {+ "description": "Denies the is_minimized command without any pre-configured scope.",+ "type": "string",+ "const": "core:window:deny-is-minimized",+ "markdownDescription": "Denies the is_minimized command without any pre-configured scope."+ },+ {+ "description": "Denies the is_resizable command without any pre-configured scope.",+ "type": "string",+ "const": "core:window:deny-is-resizable",+ "markdownDescription": "Denies the is_resizable command without any pre-configured scope."+ },+ {+ "description": "Denies the is_visible command without any pre-configured scope.",+ "type": "string",+ "const": "core:window:deny-is-visible",+ "markdownDescription": "Denies the is_visible command without any pre-configured scope."+ },+ {+ "description": "Denies the maximize command without any pre-configured scope.",+ "type": "string",+ "const": "core:window:deny-maximize",+ "markdownDescription": "Denies the maximize command without any pre-configured scope."+ },+ {+ "description": "Denies the minimize command without any pre-configured scope.",+ "type": "string",+ "const": "core:window:deny-minimize",+ "markdownDescription": "Denies the minimize command without any pre-configured scope."+ },+ {+ "description": "Denies the monitor_from_point command without any pre-configured scope.",+ "type": "string",+ "const": "core:window:deny-monitor-from-point",+ "markdownDescription": "Denies the monitor_from_point command without any pre-configured scope."+ },+ {+ "description": "Denies the outer_position command without any pre-configured scope.",+ "type": "string",+ "const": "core:window:deny-outer-position",+ "markdownDescription": "Denies the outer_position command without any pre-configured scope."+ },+ {+ "description": "Denies the outer_size command without any pre-configured scope.",+ "type": "string",+ "const": "core:window:deny-outer-size",+ "markdownDescription": "Denies the outer_size command without any pre-configured scope."+ },+ {+ "description": "Denies the primary_monitor command without any pre-configured scope.",+ "type": "string",+ "const": "core:window:deny-primary-monitor",+ "markdownDescription": "Denies the primary_monitor command without any pre-configured scope."+ },+ {+ "description": "Denies the request_user_attention command without any pre-configured scope.",+ "type": "string",+ "const": "core:window:deny-request-user-attention",+ "markdownDescription": "Denies the request_user_attention command without any pre-configured scope."+ },+ {+ "description": "Denies the scale_factor command without any pre-configured scope.",+ "type": "string",+ "const": "core:window:deny-scale-factor",+ "markdownDescription": "Denies the scale_factor command without any pre-configured scope."+ },+ {+ "description": "Denies the scene_identifier command without any pre-configured scope.",+ "type": "string",+ "const": "core:window:deny-scene-identifier",+ "markdownDescription": "Denies the scene_identifier command without any pre-configured scope."+ },+ {+ "description": "Denies the set_always_on_bottom command without any pre-configured scope.",+ "type": "string",+ "const": "core:window:deny-set-always-on-bottom",+ "markdownDescription": "Denies the set_always_on_bottom command without any pre-configured scope."+ },+ {+ "description": "Denies the set_always_on_top command without any pre-configured scope.",+ "type": "string",+ "const": "core:window:deny-set-always-on-top",+ "markdownDescription": "Denies the set_always_on_top command without any pre-configured scope."+ },+ {+ "description": "Denies the set_background_color command without any pre-configured scope.",+ "type": "string",+ "const": "core:window:deny-set-background-color",+ "markdownDescription": "Denies the set_background_color command without any pre-configured scope."+ },+ {+ "description": "Denies the set_badge_count command without any pre-configured scope.",+ "type": "string",+ "const": "core:window:deny-set-badge-count",+ "markdownDescription": "Denies the set_badge_count command without any pre-configured scope."+ },+ {+ "description": "Denies the set_badge_label command without any pre-configured scope.",+ "type": "string",+ "const": "core:window:deny-set-badge-label",+ "markdownDescription": "Denies the set_badge_label command without any pre-configured scope."+ },+ {+ "description": "Denies the set_closable command without any pre-configured scope.",+ "type": "string",+ "const": "core:window:deny-set-closable",+ "markdownDescription": "Denies the set_closable command without any pre-configured scope."+ },+ {+ "description": "Denies the set_content_protected command without any pre-configured scope.",+ "type": "string",+ "const": "core:window:deny-set-content-protected",+ "markdownDescription": "Denies the set_content_protected command without any pre-configured scope."+ },+ {+ "description": "Denies the set_cursor_grab command without any pre-configured scope.",+ "type": "string",+ "const": "core:window:deny-set-cursor-grab",+ "markdownDescription": "Denies the set_cursor_grab command without any pre-configured scope."+ },+ {+ "description": "Denies the set_cursor_icon command without any pre-configured scope.",+ "type": "string",+ "const": "core:window:deny-set-cursor-icon",+ "markdownDescription": "Denies the set_cursor_icon command without any pre-configured scope."+ },+ {+ "description": "Denies the set_cursor_position command without any pre-configured scope.",+ "type": "string",+ "const": "core:window:deny-set-cursor-position",+ "markdownDescription": "Denies the set_cursor_position command without any pre-configured scope."+ },+ {+ "description": "Denies the set_cursor_visible command without any pre-configured scope.",+ "type": "string",+ "const": "core:window:deny-set-cursor-visible",+ "markdownDescription": "Denies the set_cursor_visible command without any pre-configured scope."+ },+ {+ "description": "Denies the set_decorations command without any pre-configured scope.",+ "type": "string",+ "const": "core:window:deny-set-decorations",+ "markdownDescription": "Denies the set_decorations command without any pre-configured scope."+ },+ {+ "description": "Denies the set_effects command without any pre-configured scope.",+ "type": "string",+ "const": "core:window:deny-set-effects",+ "markdownDescription": "Denies the set_effects command without any pre-configured scope."+ },+ {+ "description": "Denies the set_enabled command without any pre-configured scope.",+ "type": "string",+ "const": "core:window:deny-set-enabled",+ "markdownDescription": "Denies the set_enabled command without any pre-configured scope."+ },+ {+ "description": "Denies the set_focus command without any pre-configured scope.",+ "type": "string",+ "const": "core:window:deny-set-focus",+ "markdownDescription": "Denies the set_focus command without any pre-configured scope."+ },+ {+ "description": "Denies the set_focusable command without any pre-configured scope.",+ "type": "string",+ "const": "core:window:deny-set-focusable",+ "markdownDescription": "Denies the set_focusable command without any pre-configured scope."+ },+ {+ "description": "Denies the set_fullscreen command without any pre-configured scope.",+ "type": "string",+ "const": "core:window:deny-set-fullscreen",+ "markdownDescription": "Denies the set_fullscreen command without any pre-configured scope."+ },+ {+ "description": "Denies the set_fullscreen_on_monitor command without any pre-configured scope.",+ "type": "string",+ "const": "core:window:deny-set-fullscreen-on-monitor",+ "markdownDescription": "Denies the set_fullscreen_on_monitor command without any pre-configured scope."+ },+ {+ "description": "Denies the set_icon command without any pre-configured scope.",+ "type": "string",+ "const": "core:window:deny-set-icon",+ "markdownDescription": "Denies the set_icon command without any pre-configured scope."+ },+ {+ "description": "Denies the set_ignore_cursor_events command without any pre-configured scope.",+ "type": "string",+ "const": "core:window:deny-set-ignore-cursor-events",+ "markdownDescription": "Denies the set_ignore_cursor_events command without any pre-configured scope."+ },+ {+ "description": "Denies the set_max_size command without any pre-configured scope.",+ "type": "string",+ "const": "core:window:deny-set-max-size",+ "markdownDescription": "Denies the set_max_size command without any pre-configured scope."+ },+ {+ "description": "Denies the set_maximizable command without any pre-configured scope.",+ "type": "string",+ "const": "core:window:deny-set-maximizable",+ "markdownDescription": "Denies the set_maximizable command without any pre-configured scope."+ },+ {+ "description": "Denies the set_min_size command without any pre-configured scope.",+ "type": "string",+ "const": "core:window:deny-set-min-size",+ "markdownDescription": "Denies the set_min_size command without any pre-configured scope."+ },+ {+ "description": "Denies the set_minimizable command without any pre-configured scope.",+ "type": "string",+ "const": "core:window:deny-set-minimizable",+ "markdownDescription": "Denies the set_minimizable command without any pre-configured scope."+ },+ {+ "description": "Denies the set_overlay_icon command without any pre-configured scope.",+ "type": "string",+ "const": "core:window:deny-set-overlay-icon",+ "markdownDescription": "Denies the set_overlay_icon command without any pre-configured scope."+ },+ {+ "description": "Denies the set_position command without any pre-configured scope.",+ "type": "string",+ "const": "core:window:deny-set-position",+ "markdownDescription": "Denies the set_position command without any pre-configured scope."+ },+ {+ "description": "Denies the set_progress_bar command without any pre-configured scope.",+ "type": "string",+ "const": "core:window:deny-set-progress-bar",+ "markdownDescription": "Denies the set_progress_bar command without any pre-configured scope."+ },+ {+ "description": "Denies the set_resizable command without any pre-configured scope.",+ "type": "string",+ "const": "core:window:deny-set-resizable",+ "markdownDescription": "Denies the set_resizable command without any pre-configured scope."+ },+ {+ "description": "Denies the set_shadow command without any pre-configured scope.",+ "type": "string",+ "const": "core:window:deny-set-shadow",+ "markdownDescription": "Denies the set_shadow command without any pre-configured scope."+ },+ {+ "description": "Denies the set_simple_fullscreen command without any pre-configured scope.",+ "type": "string",+ "const": "core:window:deny-set-simple-fullscreen",+ "markdownDescription": "Denies the set_simple_fullscreen command without any pre-configured scope."+ },+ {+ "description": "Denies the set_size command without any pre-configured scope.",+ "type": "string",+ "const": "core:window:deny-set-size",+ "markdownDescription": "Denies the set_size command without any pre-configured scope."+ },+ {+ "description": "Denies the set_size_constraints command without any pre-configured scope.",+ "type": "string",+ "const": "core:window:deny-set-size-constraints",+ "markdownDescription": "Denies the set_size_constraints command without any pre-configured scope."+ },+ {+ "description": "Denies the set_skip_taskbar command without any pre-configured scope.",+ "type": "string",+ "const": "core:window:deny-set-skip-taskbar",+ "markdownDescription": "Denies the set_skip_taskbar command without any pre-configured scope."+ },+ {+ "description": "Denies the set_theme command without any pre-configured scope.",+ "type": "string",+ "const": "core:window:deny-set-theme",+ "markdownDescription": "Denies the set_theme command without any pre-configured scope."+ },+ {+ "description": "Denies the set_title command without any pre-configured scope.",+ "type": "string",+ "const": "core:window:deny-set-title",+ "markdownDescription": "Denies the set_title command without any pre-configured scope."+ },+ {+ "description": "Denies the set_title_bar_style command without any pre-configured scope.",+ "type": "string",+ "const": "core:window:deny-set-title-bar-style",+ "markdownDescription": "Denies the set_title_bar_style command without any pre-configured scope."+ },+ {+ "description": "Denies the set_visible_on_all_workspaces command without any pre-configured scope.",+ "type": "string",+ "const": "core:window:deny-set-visible-on-all-workspaces",+ "markdownDescription": "Denies the set_visible_on_all_workspaces command without any pre-configured scope."+ },+ {+ "description": "Denies the show command without any pre-configured scope.",+ "type": "string",+ "const": "core:window:deny-show",+ "markdownDescription": "Denies the show command without any pre-configured scope."+ },+ {+ "description": "Denies the start_dragging command without any pre-configured scope.",+ "type": "string",+ "const": "core:window:deny-start-dragging",+ "markdownDescription": "Denies the start_dragging command without any pre-configured scope."+ },+ {+ "description": "Denies the start_resize_dragging command without any pre-configured scope.",+ "type": "string",+ "const": "core:window:deny-start-resize-dragging",+ "markdownDescription": "Denies the start_resize_dragging command without any pre-configured scope."+ },+ {+ "description": "Denies the theme command without any pre-configured scope.",+ "type": "string",+ "const": "core:window:deny-theme",+ "markdownDescription": "Denies the theme command without any pre-configured scope."+ },+ {+ "description": "Denies the title command without any pre-configured scope.",+ "type": "string",+ "const": "core:window:deny-title",+ "markdownDescription": "Denies the title command without any pre-configured scope."+ },+ {+ "description": "Denies the toggle_maximize command without any pre-configured scope.",+ "type": "string",+ "const": "core:window:deny-toggle-maximize",+ "markdownDescription": "Denies the toggle_maximize command without any pre-configured scope."+ },+ {+ "description": "Denies the unmaximize command without any pre-configured scope.",+ "type": "string",+ "const": "core:window:deny-unmaximize",+ "markdownDescription": "Denies the unmaximize command without any pre-configured scope."+ },+ {+ "description": "Denies the unminimize command without any pre-configured scope.",+ "type": "string",+ "const": "core:window:deny-unminimize",+ "markdownDescription": "Denies the unminimize command without any pre-configured scope."+ }+ ]+ },+ "Value": {+ "description": "All supported ACL values.",+ "anyOf": [+ {+ "description": "Represents a null JSON value.",+ "type": "null"+ },+ {+ "description": "Represents a [`bool`].",+ "type": "boolean"+ },+ {+ "description": "Represents a valid ACL [`Number`].",+ "allOf": [+ {+ "$ref": "#/definitions/Number"+ }+ ]+ },+ {+ "description": "Represents a [`String`].",+ "type": "string"+ },+ {+ "description": "Represents a list of other [`Value`]s.",+ "type": "array",+ "items": {+ "$ref": "#/definitions/Value"+ }+ },+ {+ "description": "Represents a map of [`String`] keys to [`Value`]s.",+ "type": "object",+ "additionalProperties": {+ "$ref": "#/definitions/Value"+ }+ }+ ]+ },+ "Number": {+ "description": "A valid ACL number.",+ "anyOf": [+ {+ "description": "Represents an [`i64`].",+ "type": "integer",+ "format": "int64"+ },+ {+ "description": "Represents a [`f64`].",+ "type": "number",+ "format": "double"+ }+ ]+ },+ "Target": {+ "description": "Platform target.",+ "oneOf": [+ {+ "description": "MacOS.",+ "type": "string",+ "enum": [+ "macOS"+ ]+ },+ {+ "description": "Windows.",+ "type": "string",+ "enum": [+ "windows"+ ]+ },+ {+ "description": "Linux.",+ "type": "string",+ "enum": [+ "linux"+ ]+ },+ {+ "description": "Android.",+ "type": "string",+ "enum": [+ "android"+ ]+ },+ {+ "description": "iOS.",+ "type": "string",+ "enum": [+ "iOS"+ ]+ }+ ]+ }+ }+}\ No newline at end of filediff --git a/apps/settings/src-tauri/gen/schemas/windows-schema.json b/apps/settings/src-tauri/gen/schemas/windows-schema.jsonnew file mode 100644index 0000000..1ef1225--- /dev/null+++ b/apps/settings/src-tauri/gen/schemas/windows-schema.json@@ -0,0 +1,2316 @@+{+ "$schema": "http://json-schema.org/draft-07/schema#",+ "title": "CapabilityFile",+ "description": "Capability formats accepted in a capability file.",+ "anyOf": [+ {+ "description": "A single capability.",+ "allOf": [+ {+ "$ref": "#/definitions/Capability"+ }+ ]+ },+ {+ "description": "A list of capabilities.",+ "type": "array",+ "items": {+ "$ref": "#/definitions/Capability"+ }+ },+ {+ "description": "A list of capabilities.",+ "type": "object",+ "required": [+ "capabilities"+ ],+ "properties": {+ "capabilities": {+ "description": "The list of capabilities.",+ "type": "array",+ "items": {+ "$ref": "#/definitions/Capability"+ }+ }+ }+ }+ ],+ "definitions": {+ "Capability": {+ "description": "A grouping and boundary mechanism developers can use to isolate access to the IPC layer.\n\nIt controls application windows' and webviews' fine grained access to the Tauri core, application, or plugin commands. If a webview or its window is not matching any capability then it has no access to the IPC layer at all.\n\nThis can be done to create groups of windows, based on their required system access, which can reduce impact of frontend vulnerabilities in less privileged windows. Windows can be added to a capability by exact name (e.g. `main-window`) or glob patterns like `*` or `admin-*`. A Window can have none, one, or multiple associated capabilities.\n\n## Example\n\n```json { \"identifier\": \"main-user-files-write\", \"description\": \"This capability allows the `main` window on macOS and Windows access to `filesystem` write related commands and `dialog` commands to enable programmatic access to files selected by the user.\", \"windows\": [ \"main\" ], \"permissions\": [ \"core:default\", \"dialog:open\", { \"identifier\": \"fs:allow-write-text-file\", \"allow\": [{ \"path\": \"$HOME/test.txt\" }] }, ], \"platforms\": [\"macOS\",\"windows\"] } ```",+ "type": "object",+ "required": [+ "identifier",+ "permissions"+ ],+ "properties": {+ "identifier": {+ "description": "Identifier of the capability.\n\n## Example\n\n`main-user-files-write`",+ "type": "string"+ },+ "description": {+ "description": "Description of what the capability is intended to allow on associated windows.\n\nIt should contain a description of what the grouped permissions should allow.\n\n## Example\n\nThis capability allows the `main` window access to `filesystem` write related commands and `dialog` commands to enable programmatic access to files selected by the user.",+ "default": "",+ "type": "string"+ },+ "remote": {+ "description": "Configure remote URLs that can use the capability permissions.\n\nThis setting is optional and defaults to not being set, as our default use case is that the content is served from our local application.\n\n:::caution Make sure you understand the security implications of providing remote sources with local system access. :::\n\n## Example\n\n```json { \"urls\": [\"https://*.mydomain.dev\"] } ```",+ "anyOf": [+ {+ "$ref": "#/definitions/CapabilityRemote"+ },+ {+ "type": "null"+ }+ ]+ },+ "local": {+ "description": "Whether this capability is enabled for local app URLs or not. Defaults to `true`.",+ "default": true,+ "type": "boolean"+ },+ "windows": {+ "description": "List of windows that are affected by this capability. Can be a glob pattern.\n\nIf a window label matches any of the patterns in this list, the capability will be enabled on all the webviews of that window, regardless of the value of [`Self::webviews`].\n\nOn multiwebview windows, prefer specifying [`Self::webviews`] and omitting [`Self::windows`] for a fine grained access control.\n\n## Example\n\n`[\"main\"]`",+ "type": "array",+ "items": {+ "type": "string"+ }+ },+ "webviews": {+ "description": "List of webviews that are affected by this capability. Can be a glob pattern.\n\nThe capability will be enabled on all the webviews whose label matches any of the patterns in this list, regardless of whether the webview's window label matches a pattern in [`Self::windows`].\n\n## Example\n\n`[\"sub-webview-one\", \"sub-webview-two\"]`",+ "type": "array",+ "items": {+ "type": "string"+ }+ },+ "permissions": {+ "description": "List of permissions attached to this capability.\n\nMust include the plugin name as prefix in the form of `${plugin-name}:${permission-name}`. For commands directly implemented in the application itself only `${permission-name}` is required.\n\n## Example\n\n```json [ \"core:default\", \"shell:allow-open\", \"dialog:open\", { \"identifier\": \"fs:allow-write-text-file\", \"allow\": [{ \"path\": \"$HOME/test.txt\" }] } ] ```",+ "type": "array",+ "items": {+ "$ref": "#/definitions/PermissionEntry"+ },+ "uniqueItems": true+ },+ "platforms": {+ "description": "Limit which target platforms this capability applies to.\n\nBy default all platforms are targeted.\n\n## Example\n\n`[\"macOS\",\"windows\"]`",+ "type": [+ "array",+ "null"+ ],+ "items": {+ "$ref": "#/definitions/Target"+ }+ }+ }+ },+ "CapabilityRemote": {+ "description": "Configuration for remote URLs that are associated with the capability.",+ "type": "object",+ "required": [+ "urls"+ ],+ "properties": {+ "urls": {+ "description": "Remote domains this capability refers to using the [URLPattern standard](https://urlpattern.spec.whatwg.org/).\n\n## Examples\n\n- \"https://*.mydomain.dev\": allows subdomains of mydomain.dev - \"https://mydomain.dev/api/*\": allows any subpath of mydomain.dev/api",+ "type": "array",+ "items": {+ "type": "string"+ }+ }+ }+ },+ "PermissionEntry": {+ "description": "An entry for a permission value in a [`Capability`] can be either a raw permission [`Identifier`] or an object that references a permission and extends its scope.",+ "anyOf": [+ {+ "description": "Reference a permission or permission set by identifier.",+ "allOf": [+ {+ "$ref": "#/definitions/Identifier"+ }+ ]+ },+ {+ "description": "Reference a permission or permission set by identifier and extends its scope.",+ "type": "object",+ "allOf": [+ {+ "properties": {+ "identifier": {+ "description": "Identifier of the permission or permission set.",+ "allOf": [+ {+ "$ref": "#/definitions/Identifier"+ }+ ]+ },+ "allow": {+ "description": "Data that defines what is allowed by the scope.",+ "type": [+ "array",+ "null"+ ],+ "items": {+ "$ref": "#/definitions/Value"+ }+ },+ "deny": {+ "description": "Data that defines what is denied by the scope. This should be prioritized by validation logic.",+ "type": [+ "array",+ "null"+ ],+ "items": {+ "$ref": "#/definitions/Value"+ }+ }+ }+ }+ ],+ "required": [+ "identifier"+ ]+ }+ ]+ },+ "Identifier": {+ "description": "Permission identifier",+ "oneOf": [+ {+ "description": "Default core plugins set.\n#### This default permission set includes:\n\n- `core:path:default`\n- `core:event:default`\n- `core:window:default`\n- `core:webview:default`\n- `core:app:default`\n- `core:image:default`\n- `core:resources:default`\n- `core:menu:default`\n- `core:tray:default`",+ "type": "string",+ "const": "core:default",+ "markdownDescription": "Default core plugins set.\n#### This default permission set includes:\n\n- `core:path:default`\n- `core:event:default`\n- `core:window:default`\n- `core:webview:default`\n- `core:app:default`\n- `core:image:default`\n- `core:resources:default`\n- `core:menu:default`\n- `core:tray:default`"+ },+ {+ "description": "Default permissions for the plugin.\n#### This default permission set includes:\n\n- `allow-version`\n- `allow-name`\n- `allow-tauri-version`\n- `allow-identifier`\n- `allow-bundle-type`\n- `allow-register-listener`\n- `allow-remove-listener`\n- `allow-supports-multiple-windows`",+ "type": "string",+ "const": "core:app:default",+ "markdownDescription": "Default permissions for the plugin.\n#### This default permission set includes:\n\n- `allow-version`\n- `allow-name`\n- `allow-tauri-version`\n- `allow-identifier`\n- `allow-bundle-type`\n- `allow-register-listener`\n- `allow-remove-listener`\n- `allow-supports-multiple-windows`"+ },+ {+ "description": "Enables the app_hide command without any pre-configured scope.",+ "type": "string",+ "const": "core:app:allow-app-hide",+ "markdownDescription": "Enables the app_hide command without any pre-configured scope."+ },+ {+ "description": "Enables the app_show command without any pre-configured scope.",+ "type": "string",+ "const": "core:app:allow-app-show",+ "markdownDescription": "Enables the app_show command without any pre-configured scope."+ },+ {+ "description": "Enables the bundle_type command without any pre-configured scope.",+ "type": "string",+ "const": "core:app:allow-bundle-type",+ "markdownDescription": "Enables the bundle_type command without any pre-configured scope."+ },+ {+ "description": "Enables the default_window_icon command without any pre-configured scope.",+ "type": "string",+ "const": "core:app:allow-default-window-icon",+ "markdownDescription": "Enables the default_window_icon command without any pre-configured scope."+ },+ {+ "description": "Enables the exit command without any pre-configured scope.",+ "type": "string",+ "const": "core:app:allow-exit",+ "markdownDescription": "Enables the exit command without any pre-configured scope."+ },+ {+ "description": "Enables the fetch_data_store_identifiers command without any pre-configured scope.",+ "type": "string",+ "const": "core:app:allow-fetch-data-store-identifiers",+ "markdownDescription": "Enables the fetch_data_store_identifiers command without any pre-configured scope."+ },+ {+ "description": "Enables the identifier command without any pre-configured scope.",+ "type": "string",+ "const": "core:app:allow-identifier",+ "markdownDescription": "Enables the identifier command without any pre-configured scope."+ },+ {+ "description": "Enables the name command without any pre-configured scope.",+ "type": "string",+ "const": "core:app:allow-name",+ "markdownDescription": "Enables the name command without any pre-configured scope."+ },+ {+ "description": "Enables the register_listener command without any pre-configured scope.",+ "type": "string",+ "const": "core:app:allow-register-listener",+ "markdownDescription": "Enables the register_listener command without any pre-configured scope."+ },+ {+ "description": "Enables the remove_data_store command without any pre-configured scope.",+ "type": "string",+ "const": "core:app:allow-remove-data-store",+ "markdownDescription": "Enables the remove_data_store command without any pre-configured scope."+ },+ {+ "description": "Enables the remove_listener command without any pre-configured scope.",+ "type": "string",+ "const": "core:app:allow-remove-listener",+ "markdownDescription": "Enables the remove_listener command without any pre-configured scope."+ },+ {+ "description": "Enables the set_app_theme command without any pre-configured scope.",+ "type": "string",+ "const": "core:app:allow-set-app-theme",+ "markdownDescription": "Enables the set_app_theme command without any pre-configured scope."+ },+ {+ "description": "Enables the set_dock_visibility command without any pre-configured scope.",+ "type": "string",+ "const": "core:app:allow-set-dock-visibility",+ "markdownDescription": "Enables the set_dock_visibility command without any pre-configured scope."+ },+ {+ "description": "Enables the supports_multiple_windows command without any pre-configured scope.",+ "type": "string",+ "const": "core:app:allow-supports-multiple-windows",+ "markdownDescription": "Enables the supports_multiple_windows command without any pre-configured scope."+ },+ {+ "description": "Enables the tauri_version command without any pre-configured scope.",+ "type": "string",+ "const": "core:app:allow-tauri-version",+ "markdownDescription": "Enables the tauri_version command without any pre-configured scope."+ },+ {+ "description": "Enables the version command without any pre-configured scope.",+ "type": "string",+ "const": "core:app:allow-version",+ "markdownDescription": "Enables the version command without any pre-configured scope."+ },+ {+ "description": "Denies the app_hide command without any pre-configured scope.",+ "type": "string",+ "const": "core:app:deny-app-hide",+ "markdownDescription": "Denies the app_hide command without any pre-configured scope."+ },+ {+ "description": "Denies the app_show command without any pre-configured scope.",+ "type": "string",+ "const": "core:app:deny-app-show",+ "markdownDescription": "Denies the app_show command without any pre-configured scope."+ },+ {+ "description": "Denies the bundle_type command without any pre-configured scope.",+ "type": "string",+ "const": "core:app:deny-bundle-type",+ "markdownDescription": "Denies the bundle_type command without any pre-configured scope."+ },+ {+ "description": "Denies the default_window_icon command without any pre-configured scope.",+ "type": "string",+ "const": "core:app:deny-default-window-icon",+ "markdownDescription": "Denies the default_window_icon command without any pre-configured scope."+ },+ {+ "description": "Denies the exit command without any pre-configured scope.",+ "type": "string",+ "const": "core:app:deny-exit",+ "markdownDescription": "Denies the exit command without any pre-configured scope."+ },+ {+ "description": "Denies the fetch_data_store_identifiers command without any pre-configured scope.",+ "type": "string",+ "const": "core:app:deny-fetch-data-store-identifiers",+ "markdownDescription": "Denies the fetch_data_store_identifiers command without any pre-configured scope."+ },+ {+ "description": "Denies the identifier command without any pre-configured scope.",+ "type": "string",+ "const": "core:app:deny-identifier",+ "markdownDescription": "Denies the identifier command without any pre-configured scope."+ },+ {+ "description": "Denies the name command without any pre-configured scope.",+ "type": "string",+ "const": "core:app:deny-name",+ "markdownDescription": "Denies the name command without any pre-configured scope."+ },+ {+ "description": "Denies the register_listener command without any pre-configured scope.",+ "type": "string",+ "const": "core:app:deny-register-listener",+ "markdownDescription": "Denies the register_listener command without any pre-configured scope."+ },+ {+ "description": "Denies the remove_data_store command without any pre-configured scope.",+ "type": "string",+ "const": "core:app:deny-remove-data-store",+ "markdownDescription": "Denies the remove_data_store command without any pre-configured scope."+ },+ {+ "description": "Denies the remove_listener command without any pre-configured scope.",+ "type": "string",+ "const": "core:app:deny-remove-listener",+ "markdownDescription": "Denies the remove_listener command without any pre-configured scope."+ },+ {+ "description": "Denies the set_app_theme command without any pre-configured scope.",+ "type": "string",+ "const": "core:app:deny-set-app-theme",+ "markdownDescription": "Denies the set_app_theme command without any pre-configured scope."+ },+ {+ "description": "Denies the set_dock_visibility command without any pre-configured scope.",+ "type": "string",+ "const": "core:app:deny-set-dock-visibility",+ "markdownDescription": "Denies the set_dock_visibility command without any pre-configured scope."+ },+ {+ "description": "Denies the supports_multiple_windows command without any pre-configured scope.",+ "type": "string",+ "const": "core:app:deny-supports-multiple-windows",+ "markdownDescription": "Denies the supports_multiple_windows command without any pre-configured scope."+ },+ {+ "description": "Denies the tauri_version command without any pre-configured scope.",+ "type": "string",+ "const": "core:app:deny-tauri-version",+ "markdownDescription": "Denies the tauri_version command without any pre-configured scope."+ },+ {+ "description": "Denies the version command without any pre-configured scope.",+ "type": "string",+ "const": "core:app:deny-version",+ "markdownDescription": "Denies the version command without any pre-configured scope."+ },+ {+ "description": "Default permissions for the plugin, which enables all commands.\n#### This default permission set includes:\n\n- `allow-listen`\n- `allow-unlisten`\n- `allow-emit`\n- `allow-emit-to`",+ "type": "string",+ "const": "core:event:default",+ "markdownDescription": "Default permissions for the plugin, which enables all commands.\n#### This default permission set includes:\n\n- `allow-listen`\n- `allow-unlisten`\n- `allow-emit`\n- `allow-emit-to`"+ },+ {+ "description": "Enables the emit command without any pre-configured scope.",+ "type": "string",+ "const": "core:event:allow-emit",+ "markdownDescription": "Enables the emit command without any pre-configured scope."+ },+ {+ "description": "Enables the emit_to command without any pre-configured scope.",+ "type": "string",+ "const": "core:event:allow-emit-to",+ "markdownDescription": "Enables the emit_to command without any pre-configured scope."+ },+ {+ "description": "Enables the listen command without any pre-configured scope.",+ "type": "string",+ "const": "core:event:allow-listen",+ "markdownDescription": "Enables the listen command without any pre-configured scope."+ },+ {+ "description": "Enables the unlisten command without any pre-configured scope.",+ "type": "string",+ "const": "core:event:allow-unlisten",+ "markdownDescription": "Enables the unlisten command without any pre-configured scope."+ },+ {+ "description": "Denies the emit command without any pre-configured scope.",+ "type": "string",+ "const": "core:event:deny-emit",+ "markdownDescription": "Denies the emit command without any pre-configured scope."+ },+ {+ "description": "Denies the emit_to command without any pre-configured scope.",+ "type": "string",+ "const": "core:event:deny-emit-to",+ "markdownDescription": "Denies the emit_to command without any pre-configured scope."+ },+ {+ "description": "Denies the listen command without any pre-configured scope.",+ "type": "string",+ "const": "core:event:deny-listen",+ "markdownDescription": "Denies the listen command without any pre-configured scope."+ },+ {+ "description": "Denies the unlisten command without any pre-configured scope.",+ "type": "string",+ "const": "core:event:deny-unlisten",+ "markdownDescription": "Denies the unlisten command without any pre-configured scope."+ },+ {+ "description": "Default permissions for the plugin, which enables all commands.\n#### This default permission set includes:\n\n- `allow-new`\n- `allow-from-bytes`\n- `allow-from-path`\n- `allow-rgba`\n- `allow-size`",+ "type": "string",+ "const": "core:image:default",+ "markdownDescription": "Default permissions for the plugin, which enables all commands.\n#### This default permission set includes:\n\n- `allow-new`\n- `allow-from-bytes`\n- `allow-from-path`\n- `allow-rgba`\n- `allow-size`"+ },+ {+ "description": "Enables the from_bytes command without any pre-configured scope.",+ "type": "string",+ "const": "core:image:allow-from-bytes",+ "markdownDescription": "Enables the from_bytes command without any pre-configured scope."+ },+ {+ "description": "Enables the from_path command without any pre-configured scope.",+ "type": "string",+ "const": "core:image:allow-from-path",+ "markdownDescription": "Enables the from_path command without any pre-configured scope."+ },+ {+ "description": "Enables the new command without any pre-configured scope.",+ "type": "string",+ "const": "core:image:allow-new",+ "markdownDescription": "Enables the new command without any pre-configured scope."+ },+ {+ "description": "Enables the rgba command without any pre-configured scope.",+ "type": "string",+ "const": "core:image:allow-rgba",+ "markdownDescription": "Enables the rgba command without any pre-configured scope."+ },+ {+ "description": "Enables the size command without any pre-configured scope.",+ "type": "string",+ "const": "core:image:allow-size",+ "markdownDescription": "Enables the size command without any pre-configured scope."+ },+ {+ "description": "Denies the from_bytes command without any pre-configured scope.",+ "type": "string",+ "const": "core:image:deny-from-bytes",+ "markdownDescription": "Denies the from_bytes command without any pre-configured scope."+ },+ {+ "description": "Denies the from_path command without any pre-configured scope.",+ "type": "string",+ "const": "core:image:deny-from-path",+ "markdownDescription": "Denies the from_path command without any pre-configured scope."+ },+ {+ "description": "Denies the new command without any pre-configured scope.",+ "type": "string",+ "const": "core:image:deny-new",+ "markdownDescription": "Denies the new command without any pre-configured scope."+ },+ {+ "description": "Denies the rgba command without any pre-configured scope.",+ "type": "string",+ "const": "core:image:deny-rgba",+ "markdownDescription": "Denies the rgba command without any pre-configured scope."+ },+ {+ "description": "Denies the size command without any pre-configured scope.",+ "type": "string",+ "const": "core:image:deny-size",+ "markdownDescription": "Denies the size command without any pre-configured scope."+ },+ {+ "description": "Default permissions for the plugin, which enables all commands.\n#### This default permission set includes:\n\n- `allow-new`\n- `allow-append`\n- `allow-prepend`\n- `allow-insert`\n- `allow-remove`\n- `allow-remove-at`\n- `allow-items`\n- `allow-get`\n- `allow-popup`\n- `allow-create-default`\n- `allow-set-as-app-menu`\n- `allow-set-as-window-menu`\n- `allow-text`\n- `allow-set-text`\n- `allow-is-enabled`\n- `allow-set-enabled`\n- `allow-set-accelerator`\n- `allow-set-as-windows-menu-for-nsapp`\n- `allow-set-as-help-menu-for-nsapp`\n- `allow-is-checked`\n- `allow-set-checked`\n- `allow-set-icon`",+ "type": "string",+ "const": "core:menu:default",+ "markdownDescription": "Default permissions for the plugin, which enables all commands.\n#### This default permission set includes:\n\n- `allow-new`\n- `allow-append`\n- `allow-prepend`\n- `allow-insert`\n- `allow-remove`\n- `allow-remove-at`\n- `allow-items`\n- `allow-get`\n- `allow-popup`\n- `allow-create-default`\n- `allow-set-as-app-menu`\n- `allow-set-as-window-menu`\n- `allow-text`\n- `allow-set-text`\n- `allow-is-enabled`\n- `allow-set-enabled`\n- `allow-set-accelerator`\n- `allow-set-as-windows-menu-for-nsapp`\n- `allow-set-as-help-menu-for-nsapp`\n- `allow-is-checked`\n- `allow-set-checked`\n- `allow-set-icon`"+ },+ {+ "description": "Enables the append command without any pre-configured scope.",+ "type": "string",+ "const": "core:menu:allow-append",+ "markdownDescription": "Enables the append command without any pre-configured scope."+ },+ {+ "description": "Enables the create_default command without any pre-configured scope.",+ "type": "string",+ "const": "core:menu:allow-create-default",+ "markdownDescription": "Enables the create_default command without any pre-configured scope."+ },+ {+ "description": "Enables the get command without any pre-configured scope.",+ "type": "string",+ "const": "core:menu:allow-get",+ "markdownDescription": "Enables the get command without any pre-configured scope."+ },+ {+ "description": "Enables the insert command without any pre-configured scope.",+ "type": "string",+ "const": "core:menu:allow-insert",+ "markdownDescription": "Enables the insert command without any pre-configured scope."+ },+ {+ "description": "Enables the is_checked command without any pre-configured scope.",+ "type": "string",+ "const": "core:menu:allow-is-checked",+ "markdownDescription": "Enables the is_checked command without any pre-configured scope."+ },+ {+ "description": "Enables the is_enabled command without any pre-configured scope.",+ "type": "string",+ "const": "core:menu:allow-is-enabled",+ "markdownDescription": "Enables the is_enabled command without any pre-configured scope."+ },+ {+ "description": "Enables the items command without any pre-configured scope.",+ "type": "string",+ "const": "core:menu:allow-items",+ "markdownDescription": "Enables the items command without any pre-configured scope."+ },+ {+ "description": "Enables the new command without any pre-configured scope.",+ "type": "string",+ "const": "core:menu:allow-new",+ "markdownDescription": "Enables the new command without any pre-configured scope."+ },+ {+ "description": "Enables the popup command without any pre-configured scope.",+ "type": "string",+ "const": "core:menu:allow-popup",+ "markdownDescription": "Enables the popup command without any pre-configured scope."+ },+ {+ "description": "Enables the prepend command without any pre-configured scope.",+ "type": "string",+ "const": "core:menu:allow-prepend",+ "markdownDescription": "Enables the prepend command without any pre-configured scope."+ },+ {+ "description": "Enables the remove command without any pre-configured scope.",+ "type": "string",+ "const": "core:menu:allow-remove",+ "markdownDescription": "Enables the remove command without any pre-configured scope."+ },+ {+ "description": "Enables the remove_at command without any pre-configured scope.",+ "type": "string",+ "const": "core:menu:allow-remove-at",+ "markdownDescription": "Enables the remove_at command without any pre-configured scope."+ },+ {+ "description": "Enables the set_accelerator command without any pre-configured scope.",+ "type": "string",+ "const": "core:menu:allow-set-accelerator",+ "markdownDescription": "Enables the set_accelerator command without any pre-configured scope."+ },+ {+ "description": "Enables the set_as_app_menu command without any pre-configured scope.",+ "type": "string",+ "const": "core:menu:allow-set-as-app-menu",+ "markdownDescription": "Enables the set_as_app_menu command without any pre-configured scope."+ },+ {+ "description": "Enables the set_as_help_menu_for_nsapp command without any pre-configured scope.",+ "type": "string",+ "const": "core:menu:allow-set-as-help-menu-for-nsapp",+ "markdownDescription": "Enables the set_as_help_menu_for_nsapp command without any pre-configured scope."+ },+ {+ "description": "Enables the set_as_window_menu command without any pre-configured scope.",+ "type": "string",+ "const": "core:menu:allow-set-as-window-menu",+ "markdownDescription": "Enables the set_as_window_menu command without any pre-configured scope."+ },+ {+ "description": "Enables the set_as_windows_menu_for_nsapp command without any pre-configured scope.",+ "type": "string",+ "const": "core:menu:allow-set-as-windows-menu-for-nsapp",+ "markdownDescription": "Enables the set_as_windows_menu_for_nsapp command without any pre-configured scope."+ },+ {+ "description": "Enables the set_checked command without any pre-configured scope.",+ "type": "string",+ "const": "core:menu:allow-set-checked",+ "markdownDescription": "Enables the set_checked command without any pre-configured scope."+ },+ {+ "description": "Enables the set_enabled command without any pre-configured scope.",+ "type": "string",+ "const": "core:menu:allow-set-enabled",+ "markdownDescription": "Enables the set_enabled command without any pre-configured scope."+ },+ {+ "description": "Enables the set_icon command without any pre-configured scope.",+ "type": "string",+ "const": "core:menu:allow-set-icon",+ "markdownDescription": "Enables the set_icon command without any pre-configured scope."+ },+ {+ "description": "Enables the set_text command without any pre-configured scope.",+ "type": "string",+ "const": "core:menu:allow-set-text",+ "markdownDescription": "Enables the set_text command without any pre-configured scope."+ },+ {+ "description": "Enables the text command without any pre-configured scope.",+ "type": "string",+ "const": "core:menu:allow-text",+ "markdownDescription": "Enables the text command without any pre-configured scope."+ },+ {+ "description": "Denies the append command without any pre-configured scope.",+ "type": "string",+ "const": "core:menu:deny-append",+ "markdownDescription": "Denies the append command without any pre-configured scope."+ },+ {+ "description": "Denies the create_default command without any pre-configured scope.",+ "type": "string",+ "const": "core:menu:deny-create-default",+ "markdownDescription": "Denies the create_default command without any pre-configured scope."+ },+ {+ "description": "Denies the get command without any pre-configured scope.",+ "type": "string",+ "const": "core:menu:deny-get",+ "markdownDescription": "Denies the get command without any pre-configured scope."+ },+ {+ "description": "Denies the insert command without any pre-configured scope.",+ "type": "string",+ "const": "core:menu:deny-insert",+ "markdownDescription": "Denies the insert command without any pre-configured scope."+ },+ {+ "description": "Denies the is_checked command without any pre-configured scope.",+ "type": "string",+ "const": "core:menu:deny-is-checked",+ "markdownDescription": "Denies the is_checked command without any pre-configured scope."+ },+ {+ "description": "Denies the is_enabled command without any pre-configured scope.",+ "type": "string",+ "const": "core:menu:deny-is-enabled",+ "markdownDescription": "Denies the is_enabled command without any pre-configured scope."+ },+ {+ "description": "Denies the items command without any pre-configured scope.",+ "type": "string",+ "const": "core:menu:deny-items",+ "markdownDescription": "Denies the items command without any pre-configured scope."+ },+ {+ "description": "Denies the new command without any pre-configured scope.",+ "type": "string",+ "const": "core:menu:deny-new",+ "markdownDescription": "Denies the new command without any pre-configured scope."+ },+ {+ "description": "Denies the popup command without any pre-configured scope.",+ "type": "string",+ "const": "core:menu:deny-popup",+ "markdownDescription": "Denies the popup command without any pre-configured scope."+ },+ {+ "description": "Denies the prepend command without any pre-configured scope.",+ "type": "string",+ "const": "core:menu:deny-prepend",+ "markdownDescription": "Denies the prepend command without any pre-configured scope."+ },+ {+ "description": "Denies the remove command without any pre-configured scope.",+ "type": "string",+ "const": "core:menu:deny-remove",+ "markdownDescription": "Denies the remove command without any pre-configured scope."+ },+ {+ "description": "Denies the remove_at command without any pre-configured scope.",+ "type": "string",+ "const": "core:menu:deny-remove-at",+ "markdownDescription": "Denies the remove_at command without any pre-configured scope."+ },+ {+ "description": "Denies the set_accelerator command without any pre-configured scope.",+ "type": "string",+ "const": "core:menu:deny-set-accelerator",+ "markdownDescription": "Denies the set_accelerator command without any pre-configured scope."+ },+ {+ "description": "Denies the set_as_app_menu command without any pre-configured scope.",+ "type": "string",+ "const": "core:menu:deny-set-as-app-menu",+ "markdownDescription": "Denies the set_as_app_menu command without any pre-configured scope."+ },+ {+ "description": "Denies the set_as_help_menu_for_nsapp command without any pre-configured scope.",+ "type": "string",+ "const": "core:menu:deny-set-as-help-menu-for-nsapp",+ "markdownDescription": "Denies the set_as_help_menu_for_nsapp command without any pre-configured scope."+ },+ {+ "description": "Denies the set_as_window_menu command without any pre-configured scope.",+ "type": "string",+ "const": "core:menu:deny-set-as-window-menu",+ "markdownDescription": "Denies the set_as_window_menu command without any pre-configured scope."+ },+ {+ "description": "Denies the set_as_windows_menu_for_nsapp command without any pre-configured scope.",+ "type": "string",+ "const": "core:menu:deny-set-as-windows-menu-for-nsapp",+ "markdownDescription": "Denies the set_as_windows_menu_for_nsapp command without any pre-configured scope."+ },+ {+ "description": "Denies the set_checked command without any pre-configured scope.",+ "type": "string",+ "const": "core:menu:deny-set-checked",+ "markdownDescription": "Denies the set_checked command without any pre-configured scope."+ },+ {+ "description": "Denies the set_enabled command without any pre-configured scope.",+ "type": "string",+ "const": "core:menu:deny-set-enabled",+ "markdownDescription": "Denies the set_enabled command without any pre-configured scope."+ },+ {+ "description": "Denies the set_icon command without any pre-configured scope.",+ "type": "string",+ "const": "core:menu:deny-set-icon",+ "markdownDescription": "Denies the set_icon command without any pre-configured scope."+ },+ {+ "description": "Denies the set_text command without any pre-configured scope.",+ "type": "string",+ "const": "core:menu:deny-set-text",+ "markdownDescription": "Denies the set_text command without any pre-configured scope."+ },+ {+ "description": "Denies the text command without any pre-configured scope.",+ "type": "string",+ "const": "core:menu:deny-text",+ "markdownDescription": "Denies the text command without any pre-configured scope."+ },+ {+ "description": "Default permissions for the plugin, which enables all commands.\n#### This default permission set includes:\n\n- `allow-resolve-directory`\n- `allow-resolve`\n- `allow-normalize`\n- `allow-join`\n- `allow-dirname`\n- `allow-extname`\n- `allow-basename`\n- `allow-is-absolute`",+ "type": "string",+ "const": "core:path:default",+ "markdownDescription": "Default permissions for the plugin, which enables all commands.\n#### This default permission set includes:\n\n- `allow-resolve-directory`\n- `allow-resolve`\n- `allow-normalize`\n- `allow-join`\n- `allow-dirname`\n- `allow-extname`\n- `allow-basename`\n- `allow-is-absolute`"+ },+ {+ "description": "Enables the basename command without any pre-configured scope.",+ "type": "string",+ "const": "core:path:allow-basename",+ "markdownDescription": "Enables the basename command without any pre-configured scope."+ },+ {+ "description": "Enables the dirname command without any pre-configured scope.",+ "type": "string",+ "const": "core:path:allow-dirname",+ "markdownDescription": "Enables the dirname command without any pre-configured scope."+ },+ {+ "description": "Enables the extname command without any pre-configured scope.",+ "type": "string",+ "const": "core:path:allow-extname",+ "markdownDescription": "Enables the extname command without any pre-configured scope."+ },+ {+ "description": "Enables the is_absolute command without any pre-configured scope.",+ "type": "string",+ "const": "core:path:allow-is-absolute",+ "markdownDescription": "Enables the is_absolute command without any pre-configured scope."+ },+ {+ "description": "Enables the join command without any pre-configured scope.",+ "type": "string",+ "const": "core:path:allow-join",+ "markdownDescription": "Enables the join command without any pre-configured scope."+ },+ {+ "description": "Enables the normalize command without any pre-configured scope.",+ "type": "string",+ "const": "core:path:allow-normalize",+ "markdownDescription": "Enables the normalize command without any pre-configured scope."+ },+ {+ "description": "Enables the resolve command without any pre-configured scope.",+ "type": "string",+ "const": "core:path:allow-resolve",+ "markdownDescription": "Enables the resolve command without any pre-configured scope."+ },+ {+ "description": "Enables the resolve_directory command without any pre-configured scope.",+ "type": "string",+ "const": "core:path:allow-resolve-directory",+ "markdownDescription": "Enables the resolve_directory command without any pre-configured scope."+ },+ {+ "description": "Denies the basename command without any pre-configured scope.",+ "type": "string",+ "const": "core:path:deny-basename",+ "markdownDescription": "Denies the basename command without any pre-configured scope."+ },+ {+ "description": "Denies the dirname command without any pre-configured scope.",+ "type": "string",+ "const": "core:path:deny-dirname",+ "markdownDescription": "Denies the dirname command without any pre-configured scope."+ },+ {+ "description": "Denies the extname command without any pre-configured scope.",+ "type": "string",+ "const": "core:path:deny-extname",+ "markdownDescription": "Denies the extname command without any pre-configured scope."+ },+ {+ "description": "Denies the is_absolute command without any pre-configured scope.",+ "type": "string",+ "const": "core:path:deny-is-absolute",+ "markdownDescription": "Denies the is_absolute command without any pre-configured scope."+ },+ {+ "description": "Denies the join command without any pre-configured scope.",+ "type": "string",+ "const": "core:path:deny-join",+ "markdownDescription": "Denies the join command without any pre-configured scope."+ },+ {+ "description": "Denies the normalize command without any pre-configured scope.",+ "type": "string",+ "const": "core:path:deny-normalize",+ "markdownDescription": "Denies the normalize command without any pre-configured scope."+ },+ {+ "description": "Denies the resolve command without any pre-configured scope.",+ "type": "string",+ "const": "core:path:deny-resolve",+ "markdownDescription": "Denies the resolve command without any pre-configured scope."+ },+ {+ "description": "Denies the resolve_directory command without any pre-configured scope.",+ "type": "string",+ "const": "core:path:deny-resolve-directory",+ "markdownDescription": "Denies the resolve_directory command without any pre-configured scope."+ },+ {+ "description": "Default permissions for the plugin, which enables all commands.\n#### This default permission set includes:\n\n- `allow-close`",+ "type": "string",+ "const": "core:resources:default",+ "markdownDescription": "Default permissions for the plugin, which enables all commands.\n#### This default permission set includes:\n\n- `allow-close`"+ },+ {+ "description": "Enables the close command without any pre-configured scope.",+ "type": "string",+ "const": "core:resources:allow-close",+ "markdownDescription": "Enables the close command without any pre-configured scope."+ },+ {+ "description": "Denies the close command without any pre-configured scope.",+ "type": "string",+ "const": "core:resources:deny-close",+ "markdownDescription": "Denies the close command without any pre-configured scope."+ },+ {+ "description": "Default permissions for the plugin, which enables all commands.\n#### This default permission set includes:\n\n- `allow-new`\n- `allow-get-by-id`\n- `allow-remove-by-id`\n- `allow-set-icon`\n- `allow-set-menu`\n- `allow-set-tooltip`\n- `allow-set-title`\n- `allow-set-visible`\n- `allow-set-temp-dir-path`\n- `allow-set-icon-as-template`\n- `allow-set-icon-with-as-template`\n- `allow-set-show-menu-on-left-click`",+ "type": "string",+ "const": "core:tray:default",+ "markdownDescription": "Default permissions for the plugin, which enables all commands.\n#### This default permission set includes:\n\n- `allow-new`\n- `allow-get-by-id`\n- `allow-remove-by-id`\n- `allow-set-icon`\n- `allow-set-menu`\n- `allow-set-tooltip`\n- `allow-set-title`\n- `allow-set-visible`\n- `allow-set-temp-dir-path`\n- `allow-set-icon-as-template`\n- `allow-set-icon-with-as-template`\n- `allow-set-show-menu-on-left-click`"+ },+ {+ "description": "Enables the get_by_id command without any pre-configured scope.",+ "type": "string",+ "const": "core:tray:allow-get-by-id",+ "markdownDescription": "Enables the get_by_id command without any pre-configured scope."+ },+ {+ "description": "Enables the new command without any pre-configured scope.",+ "type": "string",+ "const": "core:tray:allow-new",+ "markdownDescription": "Enables the new command without any pre-configured scope."+ },+ {+ "description": "Enables the remove_by_id command without any pre-configured scope.",+ "type": "string",+ "const": "core:tray:allow-remove-by-id",+ "markdownDescription": "Enables the remove_by_id command without any pre-configured scope."+ },+ {+ "description": "Enables the set_icon command without any pre-configured scope.",+ "type": "string",+ "const": "core:tray:allow-set-icon",+ "markdownDescription": "Enables the set_icon command without any pre-configured scope."+ },+ {+ "description": "Enables the set_icon_as_template command without any pre-configured scope.",+ "type": "string",+ "const": "core:tray:allow-set-icon-as-template",+ "markdownDescription": "Enables the set_icon_as_template command without any pre-configured scope."+ },+ {+ "description": "Enables the set_icon_with_as_template command without any pre-configured scope.",+ "type": "string",+ "const": "core:tray:allow-set-icon-with-as-template",+ "markdownDescription": "Enables the set_icon_with_as_template command without any pre-configured scope."+ },+ {+ "description": "Enables the set_menu command without any pre-configured scope.",+ "type": "string",+ "const": "core:tray:allow-set-menu",+ "markdownDescription": "Enables the set_menu command without any pre-configured scope."+ },+ {+ "description": "Enables the set_show_menu_on_left_click command without any pre-configured scope.",+ "type": "string",+ "const": "core:tray:allow-set-show-menu-on-left-click",+ "markdownDescription": "Enables the set_show_menu_on_left_click command without any pre-configured scope."+ },+ {+ "description": "Enables the set_temp_dir_path command without any pre-configured scope.",+ "type": "string",+ "const": "core:tray:allow-set-temp-dir-path",+ "markdownDescription": "Enables the set_temp_dir_path command without any pre-configured scope."+ },+ {+ "description": "Enables the set_title command without any pre-configured scope.",+ "type": "string",+ "const": "core:tray:allow-set-title",+ "markdownDescription": "Enables the set_title command without any pre-configured scope."+ },+ {+ "description": "Enables the set_tooltip command without any pre-configured scope.",+ "type": "string",+ "const": "core:tray:allow-set-tooltip",+ "markdownDescription": "Enables the set_tooltip command without any pre-configured scope."+ },+ {+ "description": "Enables the set_visible command without any pre-configured scope.",+ "type": "string",+ "const": "core:tray:allow-set-visible",+ "markdownDescription": "Enables the set_visible command without any pre-configured scope."+ },+ {+ "description": "Denies the get_by_id command without any pre-configured scope.",+ "type": "string",+ "const": "core:tray:deny-get-by-id",+ "markdownDescription": "Denies the get_by_id command without any pre-configured scope."+ },+ {+ "description": "Denies the new command without any pre-configured scope.",+ "type": "string",+ "const": "core:tray:deny-new",+ "markdownDescription": "Denies the new command without any pre-configured scope."+ },+ {+ "description": "Denies the remove_by_id command without any pre-configured scope.",+ "type": "string",+ "const": "core:tray:deny-remove-by-id",+ "markdownDescription": "Denies the remove_by_id command without any pre-configured scope."+ },+ {+ "description": "Denies the set_icon command without any pre-configured scope.",+ "type": "string",+ "const": "core:tray:deny-set-icon",+ "markdownDescription": "Denies the set_icon command without any pre-configured scope."+ },+ {+ "description": "Denies the set_icon_as_template command without any pre-configured scope.",+ "type": "string",+ "const": "core:tray:deny-set-icon-as-template",+ "markdownDescription": "Denies the set_icon_as_template command without any pre-configured scope."+ },+ {+ "description": "Denies the set_icon_with_as_template command without any pre-configured scope.",+ "type": "string",+ "const": "core:tray:deny-set-icon-with-as-template",+ "markdownDescription": "Denies the set_icon_with_as_template command without any pre-configured scope."+ },+ {+ "description": "Denies the set_menu command without any pre-configured scope.",+ "type": "string",+ "const": "core:tray:deny-set-menu",+ "markdownDescription": "Denies the set_menu command without any pre-configured scope."+ },+ {+ "description": "Denies the set_show_menu_on_left_click command without any pre-configured scope.",+ "type": "string",+ "const": "core:tray:deny-set-show-menu-on-left-click",+ "markdownDescription": "Denies the set_show_menu_on_left_click command without any pre-configured scope."+ },+ {+ "description": "Denies the set_temp_dir_path command without any pre-configured scope.",+ "type": "string",+ "const": "core:tray:deny-set-temp-dir-path",+ "markdownDescription": "Denies the set_temp_dir_path command without any pre-configured scope."+ },+ {+ "description": "Denies the set_title command without any pre-configured scope.",+ "type": "string",+ "const": "core:tray:deny-set-title",+ "markdownDescription": "Denies the set_title command without any pre-configured scope."+ },+ {+ "description": "Denies the set_tooltip command without any pre-configured scope.",+ "type": "string",+ "const": "core:tray:deny-set-tooltip",+ "markdownDescription": "Denies the set_tooltip command without any pre-configured scope."+ },+ {+ "description": "Denies the set_visible command without any pre-configured scope.",+ "type": "string",+ "const": "core:tray:deny-set-visible",+ "markdownDescription": "Denies the set_visible command without any pre-configured scope."+ },+ {+ "description": "Default permissions for the plugin.\n#### This default permission set includes:\n\n- `allow-get-all-webviews`\n- `allow-webview-position`\n- `allow-webview-size`\n- `allow-internal-toggle-devtools`",+ "type": "string",+ "const": "core:webview:default",+ "markdownDescription": "Default permissions for the plugin.\n#### This default permission set includes:\n\n- `allow-get-all-webviews`\n- `allow-webview-position`\n- `allow-webview-size`\n- `allow-internal-toggle-devtools`"+ },+ {+ "description": "Enables the clear_all_browsing_data command without any pre-configured scope.",+ "type": "string",+ "const": "core:webview:allow-clear-all-browsing-data",+ "markdownDescription": "Enables the clear_all_browsing_data command without any pre-configured scope."+ },+ {+ "description": "Enables the create_webview command without any pre-configured scope.",+ "type": "string",+ "const": "core:webview:allow-create-webview",+ "markdownDescription": "Enables the create_webview command without any pre-configured scope."+ },+ {+ "description": "Enables the create_webview_window command without any pre-configured scope.",+ "type": "string",+ "const": "core:webview:allow-create-webview-window",+ "markdownDescription": "Enables the create_webview_window command without any pre-configured scope."+ },+ {+ "description": "Enables the get_all_webviews command without any pre-configured scope.",+ "type": "string",+ "const": "core:webview:allow-get-all-webviews",+ "markdownDescription": "Enables the get_all_webviews command without any pre-configured scope."+ },+ {+ "description": "Enables the internal_toggle_devtools command without any pre-configured scope.",+ "type": "string",+ "const": "core:webview:allow-internal-toggle-devtools",+ "markdownDescription": "Enables the internal_toggle_devtools command without any pre-configured scope."+ },+ {+ "description": "Enables the print command without any pre-configured scope.",+ "type": "string",+ "const": "core:webview:allow-print",+ "markdownDescription": "Enables the print command without any pre-configured scope."+ },+ {+ "description": "Enables the reparent command without any pre-configured scope.",+ "type": "string",+ "const": "core:webview:allow-reparent",+ "markdownDescription": "Enables the reparent command without any pre-configured scope."+ },+ {+ "description": "Enables the set_webview_auto_resize command without any pre-configured scope.",+ "type": "string",+ "const": "core:webview:allow-set-webview-auto-resize",+ "markdownDescription": "Enables the set_webview_auto_resize command without any pre-configured scope."+ },+ {+ "description": "Enables the set_webview_background_color command without any pre-configured scope.",+ "type": "string",+ "const": "core:webview:allow-set-webview-background-color",+ "markdownDescription": "Enables the set_webview_background_color command without any pre-configured scope."+ },+ {+ "description": "Enables the set_webview_focus command without any pre-configured scope.",+ "type": "string",+ "const": "core:webview:allow-set-webview-focus",+ "markdownDescription": "Enables the set_webview_focus command without any pre-configured scope."+ },+ {+ "description": "Enables the set_webview_position command without any pre-configured scope.",+ "type": "string",+ "const": "core:webview:allow-set-webview-position",+ "markdownDescription": "Enables the set_webview_position command without any pre-configured scope."+ },+ {+ "description": "Enables the set_webview_size command without any pre-configured scope.",+ "type": "string",+ "const": "core:webview:allow-set-webview-size",+ "markdownDescription": "Enables the set_webview_size command without any pre-configured scope."+ },+ {+ "description": "Enables the set_webview_zoom command without any pre-configured scope.",+ "type": "string",+ "const": "core:webview:allow-set-webview-zoom",+ "markdownDescription": "Enables the set_webview_zoom command without any pre-configured scope."+ },+ {+ "description": "Enables the webview_close command without any pre-configured scope.",+ "type": "string",+ "const": "core:webview:allow-webview-close",+ "markdownDescription": "Enables the webview_close command without any pre-configured scope."+ },+ {+ "description": "Enables the webview_hide command without any pre-configured scope.",+ "type": "string",+ "const": "core:webview:allow-webview-hide",+ "markdownDescription": "Enables the webview_hide command without any pre-configured scope."+ },+ {+ "description": "Enables the webview_position command without any pre-configured scope.",+ "type": "string",+ "const": "core:webview:allow-webview-position",+ "markdownDescription": "Enables the webview_position command without any pre-configured scope."+ },+ {+ "description": "Enables the webview_show command without any pre-configured scope.",+ "type": "string",+ "const": "core:webview:allow-webview-show",+ "markdownDescription": "Enables the webview_show command without any pre-configured scope."+ },+ {+ "description": "Enables the webview_size command without any pre-configured scope.",+ "type": "string",+ "const": "core:webview:allow-webview-size",+ "markdownDescription": "Enables the webview_size command without any pre-configured scope."+ },+ {+ "description": "Denies the clear_all_browsing_data command without any pre-configured scope.",+ "type": "string",+ "const": "core:webview:deny-clear-all-browsing-data",+ "markdownDescription": "Denies the clear_all_browsing_data command without any pre-configured scope."+ },+ {+ "description": "Denies the create_webview command without any pre-configured scope.",+ "type": "string",+ "const": "core:webview:deny-create-webview",+ "markdownDescription": "Denies the create_webview command without any pre-configured scope."+ },+ {+ "description": "Denies the create_webview_window command without any pre-configured scope.",+ "type": "string",+ "const": "core:webview:deny-create-webview-window",+ "markdownDescription": "Denies the create_webview_window command without any pre-configured scope."+ },+ {+ "description": "Denies the get_all_webviews command without any pre-configured scope.",+ "type": "string",+ "const": "core:webview:deny-get-all-webviews",+ "markdownDescription": "Denies the get_all_webviews command without any pre-configured scope."+ },+ {+ "description": "Denies the internal_toggle_devtools command without any pre-configured scope.",+ "type": "string",+ "const": "core:webview:deny-internal-toggle-devtools",+ "markdownDescription": "Denies the internal_toggle_devtools command without any pre-configured scope."+ },+ {+ "description": "Denies the print command without any pre-configured scope.",+ "type": "string",+ "const": "core:webview:deny-print",+ "markdownDescription": "Denies the print command without any pre-configured scope."+ },+ {+ "description": "Denies the reparent command without any pre-configured scope.",+ "type": "string",+ "const": "core:webview:deny-reparent",+ "markdownDescription": "Denies the reparent command without any pre-configured scope."+ },+ {+ "description": "Denies the set_webview_auto_resize command without any pre-configured scope.",+ "type": "string",+ "const": "core:webview:deny-set-webview-auto-resize",+ "markdownDescription": "Denies the set_webview_auto_resize command without any pre-configured scope."+ },+ {+ "description": "Denies the set_webview_background_color command without any pre-configured scope.",+ "type": "string",+ "const": "core:webview:deny-set-webview-background-color",+ "markdownDescription": "Denies the set_webview_background_color command without any pre-configured scope."+ },+ {+ "description": "Denies the set_webview_focus command without any pre-configured scope.",+ "type": "string",+ "const": "core:webview:deny-set-webview-focus",+ "markdownDescription": "Denies the set_webview_focus command without any pre-configured scope."+ },+ {+ "description": "Denies the set_webview_position command without any pre-configured scope.",+ "type": "string",+ "const": "core:webview:deny-set-webview-position",+ "markdownDescription": "Denies the set_webview_position command without any pre-configured scope."+ },+ {+ "description": "Denies the set_webview_size command without any pre-configured scope.",+ "type": "string",+ "const": "core:webview:deny-set-webview-size",+ "markdownDescription": "Denies the set_webview_size command without any pre-configured scope."+ },+ {+ "description": "Denies the set_webview_zoom command without any pre-configured scope.",+ "type": "string",+ "const": "core:webview:deny-set-webview-zoom",+ "markdownDescription": "Denies the set_webview_zoom command without any pre-configured scope."+ },+ {+ "description": "Denies the webview_close command without any pre-configured scope.",+ "type": "string",+ "const": "core:webview:deny-webview-close",+ "markdownDescription": "Denies the webview_close command without any pre-configured scope."+ },+ {+ "description": "Denies the webview_hide command without any pre-configured scope.",+ "type": "string",+ "const": "core:webview:deny-webview-hide",+ "markdownDescription": "Denies the webview_hide command without any pre-configured scope."+ },+ {+ "description": "Denies the webview_position command without any pre-configured scope.",+ "type": "string",+ "const": "core:webview:deny-webview-position",+ "markdownDescription": "Denies the webview_position command without any pre-configured scope."+ },+ {+ "description": "Denies the webview_show command without any pre-configured scope.",+ "type": "string",+ "const": "core:webview:deny-webview-show",+ "markdownDescription": "Denies the webview_show command without any pre-configured scope."+ },+ {+ "description": "Denies the webview_size command without any pre-configured scope.",+ "type": "string",+ "const": "core:webview:deny-webview-size",+ "markdownDescription": "Denies the webview_size command without any pre-configured scope."+ },+ {+ "description": "Default permissions for the plugin.\n#### This default permission set includes:\n\n- `allow-get-all-windows`\n- `allow-scale-factor`\n- `allow-inner-position`\n- `allow-outer-position`\n- `allow-inner-size`\n- `allow-outer-size`\n- `allow-is-fullscreen`\n- `allow-is-minimized`\n- `allow-is-maximized`\n- `allow-is-focused`\n- `allow-is-decorated`\n- `allow-is-resizable`\n- `allow-is-maximizable`\n- `allow-is-minimizable`\n- `allow-is-closable`\n- `allow-is-visible`\n- `allow-is-enabled`\n- `allow-title`\n- `allow-current-monitor`\n- `allow-primary-monitor`\n- `allow-monitor-from-point`\n- `allow-available-monitors`\n- `allow-cursor-position`\n- `allow-theme`\n- `allow-is-always-on-top`\n- `allow-activity-name`\n- `allow-scene-identifier`\n- `allow-internal-toggle-maximize`",+ "type": "string",+ "const": "core:window:default",+ "markdownDescription": "Default permissions for the plugin.\n#### This default permission set includes:\n\n- `allow-get-all-windows`\n- `allow-scale-factor`\n- `allow-inner-position`\n- `allow-outer-position`\n- `allow-inner-size`\n- `allow-outer-size`\n- `allow-is-fullscreen`\n- `allow-is-minimized`\n- `allow-is-maximized`\n- `allow-is-focused`\n- `allow-is-decorated`\n- `allow-is-resizable`\n- `allow-is-maximizable`\n- `allow-is-minimizable`\n- `allow-is-closable`\n- `allow-is-visible`\n- `allow-is-enabled`\n- `allow-title`\n- `allow-current-monitor`\n- `allow-primary-monitor`\n- `allow-monitor-from-point`\n- `allow-available-monitors`\n- `allow-cursor-position`\n- `allow-theme`\n- `allow-is-always-on-top`\n- `allow-activity-name`\n- `allow-scene-identifier`\n- `allow-internal-toggle-maximize`"+ },+ {+ "description": "Enables the activity_name command without any pre-configured scope.",+ "type": "string",+ "const": "core:window:allow-activity-name",+ "markdownDescription": "Enables the activity_name command without any pre-configured scope."+ },+ {+ "description": "Enables the available_monitors command without any pre-configured scope.",+ "type": "string",+ "const": "core:window:allow-available-monitors",+ "markdownDescription": "Enables the available_monitors command without any pre-configured scope."+ },+ {+ "description": "Enables the center command without any pre-configured scope.",+ "type": "string",+ "const": "core:window:allow-center",+ "markdownDescription": "Enables the center command without any pre-configured scope."+ },+ {+ "description": "Enables the close command without any pre-configured scope.",+ "type": "string",+ "const": "core:window:allow-close",+ "markdownDescription": "Enables the close command without any pre-configured scope."+ },+ {+ "description": "Enables the create command without any pre-configured scope.",+ "type": "string",+ "const": "core:window:allow-create",+ "markdownDescription": "Enables the create command without any pre-configured scope."+ },+ {+ "description": "Enables the current_monitor command without any pre-configured scope.",+ "type": "string",+ "const": "core:window:allow-current-monitor",+ "markdownDescription": "Enables the current_monitor command without any pre-configured scope."+ },+ {+ "description": "Enables the cursor_position command without any pre-configured scope.",+ "type": "string",+ "const": "core:window:allow-cursor-position",+ "markdownDescription": "Enables the cursor_position command without any pre-configured scope."+ },+ {+ "description": "Enables the destroy command without any pre-configured scope.",+ "type": "string",+ "const": "core:window:allow-destroy",+ "markdownDescription": "Enables the destroy command without any pre-configured scope."+ },+ {+ "description": "Enables the get_all_windows command without any pre-configured scope.",+ "type": "string",+ "const": "core:window:allow-get-all-windows",+ "markdownDescription": "Enables the get_all_windows command without any pre-configured scope."+ },+ {+ "description": "Enables the hide command without any pre-configured scope.",+ "type": "string",+ "const": "core:window:allow-hide",+ "markdownDescription": "Enables the hide command without any pre-configured scope."+ },+ {+ "description": "Enables the inner_position command without any pre-configured scope.",+ "type": "string",+ "const": "core:window:allow-inner-position",+ "markdownDescription": "Enables the inner_position command without any pre-configured scope."+ },+ {+ "description": "Enables the inner_size command without any pre-configured scope.",+ "type": "string",+ "const": "core:window:allow-inner-size",+ "markdownDescription": "Enables the inner_size command without any pre-configured scope."+ },+ {+ "description": "Enables the internal_toggle_maximize command without any pre-configured scope.",+ "type": "string",+ "const": "core:window:allow-internal-toggle-maximize",+ "markdownDescription": "Enables the internal_toggle_maximize command without any pre-configured scope."+ },+ {+ "description": "Enables the is_always_on_top command without any pre-configured scope.",+ "type": "string",+ "const": "core:window:allow-is-always-on-top",+ "markdownDescription": "Enables the is_always_on_top command without any pre-configured scope."+ },+ {+ "description": "Enables the is_closable command without any pre-configured scope.",+ "type": "string",+ "const": "core:window:allow-is-closable",+ "markdownDescription": "Enables the is_closable command without any pre-configured scope."+ },+ {+ "description": "Enables the is_decorated command without any pre-configured scope.",+ "type": "string",+ "const": "core:window:allow-is-decorated",+ "markdownDescription": "Enables the is_decorated command without any pre-configured scope."+ },+ {+ "description": "Enables the is_enabled command without any pre-configured scope.",+ "type": "string",+ "const": "core:window:allow-is-enabled",+ "markdownDescription": "Enables the is_enabled command without any pre-configured scope."+ },+ {+ "description": "Enables the is_focused command without any pre-configured scope.",+ "type": "string",+ "const": "core:window:allow-is-focused",+ "markdownDescription": "Enables the is_focused command without any pre-configured scope."+ },+ {+ "description": "Enables the is_fullscreen command without any pre-configured scope.",+ "type": "string",+ "const": "core:window:allow-is-fullscreen",+ "markdownDescription": "Enables the is_fullscreen command without any pre-configured scope."+ },+ {+ "description": "Enables the is_maximizable command without any pre-configured scope.",+ "type": "string",+ "const": "core:window:allow-is-maximizable",+ "markdownDescription": "Enables the is_maximizable command without any pre-configured scope."+ },+ {+ "description": "Enables the is_maximized command without any pre-configured scope.",+ "type": "string",+ "const": "core:window:allow-is-maximized",+ "markdownDescription": "Enables the is_maximized command without any pre-configured scope."+ },+ {+ "description": "Enables the is_minimizable command without any pre-configured scope.",+ "type": "string",+ "const": "core:window:allow-is-minimizable",+ "markdownDescription": "Enables the is_minimizable command without any pre-configured scope."+ },+ {+ "description": "Enables the is_minimized command without any pre-configured scope.",+ "type": "string",+ "const": "core:window:allow-is-minimized",+ "markdownDescription": "Enables the is_minimized command without any pre-configured scope."+ },+ {+ "description": "Enables the is_resizable command without any pre-configured scope.",+ "type": "string",+ "const": "core:window:allow-is-resizable",+ "markdownDescription": "Enables the is_resizable command without any pre-configured scope."+ },+ {+ "description": "Enables the is_visible command without any pre-configured scope.",+ "type": "string",+ "const": "core:window:allow-is-visible",+ "markdownDescription": "Enables the is_visible command without any pre-configured scope."+ },+ {+ "description": "Enables the maximize command without any pre-configured scope.",+ "type": "string",+ "const": "core:window:allow-maximize",+ "markdownDescription": "Enables the maximize command without any pre-configured scope."+ },+ {+ "description": "Enables the minimize command without any pre-configured scope.",+ "type": "string",+ "const": "core:window:allow-minimize",+ "markdownDescription": "Enables the minimize command without any pre-configured scope."+ },+ {+ "description": "Enables the monitor_from_point command without any pre-configured scope.",+ "type": "string",+ "const": "core:window:allow-monitor-from-point",+ "markdownDescription": "Enables the monitor_from_point command without any pre-configured scope."+ },+ {+ "description": "Enables the outer_position command without any pre-configured scope.",+ "type": "string",+ "const": "core:window:allow-outer-position",+ "markdownDescription": "Enables the outer_position command without any pre-configured scope."+ },+ {+ "description": "Enables the outer_size command without any pre-configured scope.",+ "type": "string",+ "const": "core:window:allow-outer-size",+ "markdownDescription": "Enables the outer_size command without any pre-configured scope."+ },+ {+ "description": "Enables the primary_monitor command without any pre-configured scope.",+ "type": "string",+ "const": "core:window:allow-primary-monitor",+ "markdownDescription": "Enables the primary_monitor command without any pre-configured scope."+ },+ {+ "description": "Enables the request_user_attention command without any pre-configured scope.",+ "type": "string",+ "const": "core:window:allow-request-user-attention",+ "markdownDescription": "Enables the request_user_attention command without any pre-configured scope."+ },+ {+ "description": "Enables the scale_factor command without any pre-configured scope.",+ "type": "string",+ "const": "core:window:allow-scale-factor",+ "markdownDescription": "Enables the scale_factor command without any pre-configured scope."+ },+ {+ "description": "Enables the scene_identifier command without any pre-configured scope.",+ "type": "string",+ "const": "core:window:allow-scene-identifier",+ "markdownDescription": "Enables the scene_identifier command without any pre-configured scope."+ },+ {+ "description": "Enables the set_always_on_bottom command without any pre-configured scope.",+ "type": "string",+ "const": "core:window:allow-set-always-on-bottom",+ "markdownDescription": "Enables the set_always_on_bottom command without any pre-configured scope."+ },+ {+ "description": "Enables the set_always_on_top command without any pre-configured scope.",+ "type": "string",+ "const": "core:window:allow-set-always-on-top",+ "markdownDescription": "Enables the set_always_on_top command without any pre-configured scope."+ },+ {+ "description": "Enables the set_background_color command without any pre-configured scope.",+ "type": "string",+ "const": "core:window:allow-set-background-color",+ "markdownDescription": "Enables the set_background_color command without any pre-configured scope."+ },+ {+ "description": "Enables the set_badge_count command without any pre-configured scope.",+ "type": "string",+ "const": "core:window:allow-set-badge-count",+ "markdownDescription": "Enables the set_badge_count command without any pre-configured scope."+ },+ {+ "description": "Enables the set_badge_label command without any pre-configured scope.",+ "type": "string",+ "const": "core:window:allow-set-badge-label",+ "markdownDescription": "Enables the set_badge_label command without any pre-configured scope."+ },+ {+ "description": "Enables the set_closable command without any pre-configured scope.",+ "type": "string",+ "const": "core:window:allow-set-closable",+ "markdownDescription": "Enables the set_closable command without any pre-configured scope."+ },+ {+ "description": "Enables the set_content_protected command without any pre-configured scope.",+ "type": "string",+ "const": "core:window:allow-set-content-protected",+ "markdownDescription": "Enables the set_content_protected command without any pre-configured scope."+ },+ {+ "description": "Enables the set_cursor_grab command without any pre-configured scope.",+ "type": "string",+ "const": "core:window:allow-set-cursor-grab",+ "markdownDescription": "Enables the set_cursor_grab command without any pre-configured scope."+ },+ {+ "description": "Enables the set_cursor_icon command without any pre-configured scope.",+ "type": "string",+ "const": "core:window:allow-set-cursor-icon",+ "markdownDescription": "Enables the set_cursor_icon command without any pre-configured scope."+ },+ {+ "description": "Enables the set_cursor_position command without any pre-configured scope.",+ "type": "string",+ "const": "core:window:allow-set-cursor-position",+ "markdownDescription": "Enables the set_cursor_position command without any pre-configured scope."+ },+ {+ "description": "Enables the set_cursor_visible command without any pre-configured scope.",+ "type": "string",+ "const": "core:window:allow-set-cursor-visible",+ "markdownDescription": "Enables the set_cursor_visible command without any pre-configured scope."+ },+ {+ "description": "Enables the set_decorations command without any pre-configured scope.",+ "type": "string",+ "const": "core:window:allow-set-decorations",+ "markdownDescription": "Enables the set_decorations command without any pre-configured scope."+ },+ {+ "description": "Enables the set_effects command without any pre-configured scope.",+ "type": "string",+ "const": "core:window:allow-set-effects",+ "markdownDescription": "Enables the set_effects command without any pre-configured scope."+ },+ {+ "description": "Enables the set_enabled command without any pre-configured scope.",+ "type": "string",+ "const": "core:window:allow-set-enabled",+ "markdownDescription": "Enables the set_enabled command without any pre-configured scope."+ },+ {+ "description": "Enables the set_focus command without any pre-configured scope.",+ "type": "string",+ "const": "core:window:allow-set-focus",+ "markdownDescription": "Enables the set_focus command without any pre-configured scope."+ },+ {+ "description": "Enables the set_focusable command without any pre-configured scope.",+ "type": "string",+ "const": "core:window:allow-set-focusable",+ "markdownDescription": "Enables the set_focusable command without any pre-configured scope."+ },+ {+ "description": "Enables the set_fullscreen command without any pre-configured scope.",+ "type": "string",+ "const": "core:window:allow-set-fullscreen",+ "markdownDescription": "Enables the set_fullscreen command without any pre-configured scope."+ },+ {+ "description": "Enables the set_fullscreen_on_monitor command without any pre-configured scope.",+ "type": "string",+ "const": "core:window:allow-set-fullscreen-on-monitor",+ "markdownDescription": "Enables the set_fullscreen_on_monitor command without any pre-configured scope."+ },+ {+ "description": "Enables the set_icon command without any pre-configured scope.",+ "type": "string",+ "const": "core:window:allow-set-icon",+ "markdownDescription": "Enables the set_icon command without any pre-configured scope."+ },+ {+ "description": "Enables the set_ignore_cursor_events command without any pre-configured scope.",+ "type": "string",+ "const": "core:window:allow-set-ignore-cursor-events",+ "markdownDescription": "Enables the set_ignore_cursor_events command without any pre-configured scope."+ },+ {+ "description": "Enables the set_max_size command without any pre-configured scope.",+ "type": "string",+ "const": "core:window:allow-set-max-size",+ "markdownDescription": "Enables the set_max_size command without any pre-configured scope."+ },+ {+ "description": "Enables the set_maximizable command without any pre-configured scope.",+ "type": "string",+ "const": "core:window:allow-set-maximizable",+ "markdownDescription": "Enables the set_maximizable command without any pre-configured scope."+ },+ {+ "description": "Enables the set_min_size command without any pre-configured scope.",+ "type": "string",+ "const": "core:window:allow-set-min-size",+ "markdownDescription": "Enables the set_min_size command without any pre-configured scope."+ },+ {+ "description": "Enables the set_minimizable command without any pre-configured scope.",+ "type": "string",+ "const": "core:window:allow-set-minimizable",+ "markdownDescription": "Enables the set_minimizable command without any pre-configured scope."+ },+ {+ "description": "Enables the set_overlay_icon command without any pre-configured scope.",+ "type": "string",+ "const": "core:window:allow-set-overlay-icon",+ "markdownDescription": "Enables the set_overlay_icon command without any pre-configured scope."+ },+ {+ "description": "Enables the set_position command without any pre-configured scope.",+ "type": "string",+ "const": "core:window:allow-set-position",+ "markdownDescription": "Enables the set_position command without any pre-configured scope."+ },+ {+ "description": "Enables the set_progress_bar command without any pre-configured scope.",+ "type": "string",+ "const": "core:window:allow-set-progress-bar",+ "markdownDescription": "Enables the set_progress_bar command without any pre-configured scope."+ },+ {+ "description": "Enables the set_resizable command without any pre-configured scope.",+ "type": "string",+ "const": "core:window:allow-set-resizable",+ "markdownDescription": "Enables the set_resizable command without any pre-configured scope."+ },+ {+ "description": "Enables the set_shadow command without any pre-configured scope.",+ "type": "string",+ "const": "core:window:allow-set-shadow",+ "markdownDescription": "Enables the set_shadow command without any pre-configured scope."+ },+ {+ "description": "Enables the set_simple_fullscreen command without any pre-configured scope.",+ "type": "string",+ "const": "core:window:allow-set-simple-fullscreen",+ "markdownDescription": "Enables the set_simple_fullscreen command without any pre-configured scope."+ },+ {+ "description": "Enables the set_size command without any pre-configured scope.",+ "type": "string",+ "const": "core:window:allow-set-size",+ "markdownDescription": "Enables the set_size command without any pre-configured scope."+ },+ {+ "description": "Enables the set_size_constraints command without any pre-configured scope.",+ "type": "string",+ "const": "core:window:allow-set-size-constraints",+ "markdownDescription": "Enables the set_size_constraints command without any pre-configured scope."+ },+ {+ "description": "Enables the set_skip_taskbar command without any pre-configured scope.",+ "type": "string",+ "const": "core:window:allow-set-skip-taskbar",+ "markdownDescription": "Enables the set_skip_taskbar command without any pre-configured scope."+ },+ {+ "description": "Enables the set_theme command without any pre-configured scope.",+ "type": "string",+ "const": "core:window:allow-set-theme",+ "markdownDescription": "Enables the set_theme command without any pre-configured scope."+ },+ {+ "description": "Enables the set_title command without any pre-configured scope.",+ "type": "string",+ "const": "core:window:allow-set-title",+ "markdownDescription": "Enables the set_title command without any pre-configured scope."+ },+ {+ "description": "Enables the set_title_bar_style command without any pre-configured scope.",+ "type": "string",+ "const": "core:window:allow-set-title-bar-style",+ "markdownDescription": "Enables the set_title_bar_style command without any pre-configured scope."+ },+ {+ "description": "Enables the set_visible_on_all_workspaces command without any pre-configured scope.",+ "type": "string",+ "const": "core:window:allow-set-visible-on-all-workspaces",+ "markdownDescription": "Enables the set_visible_on_all_workspaces command without any pre-configured scope."+ },+ {+ "description": "Enables the show command without any pre-configured scope.",+ "type": "string",+ "const": "core:window:allow-show",+ "markdownDescription": "Enables the show command without any pre-configured scope."+ },+ {+ "description": "Enables the start_dragging command without any pre-configured scope.",+ "type": "string",+ "const": "core:window:allow-start-dragging",+ "markdownDescription": "Enables the start_dragging command without any pre-configured scope."+ },+ {+ "description": "Enables the start_resize_dragging command without any pre-configured scope.",+ "type": "string",+ "const": "core:window:allow-start-resize-dragging",+ "markdownDescription": "Enables the start_resize_dragging command without any pre-configured scope."+ },+ {+ "description": "Enables the theme command without any pre-configured scope.",+ "type": "string",+ "const": "core:window:allow-theme",+ "markdownDescription": "Enables the theme command without any pre-configured scope."+ },+ {+ "description": "Enables the title command without any pre-configured scope.",+ "type": "string",+ "const": "core:window:allow-title",+ "markdownDescription": "Enables the title command without any pre-configured scope."+ },+ {+ "description": "Enables the toggle_maximize command without any pre-configured scope.",+ "type": "string",+ "const": "core:window:allow-toggle-maximize",+ "markdownDescription": "Enables the toggle_maximize command without any pre-configured scope."+ },+ {+ "description": "Enables the unmaximize command without any pre-configured scope.",+ "type": "string",+ "const": "core:window:allow-unmaximize",+ "markdownDescription": "Enables the unmaximize command without any pre-configured scope."+ },+ {+ "description": "Enables the unminimize command without any pre-configured scope.",+ "type": "string",+ "const": "core:window:allow-unminimize",+ "markdownDescription": "Enables the unminimize command without any pre-configured scope."+ },+ {+ "description": "Denies the activity_name command without any pre-configured scope.",+ "type": "string",+ "const": "core:window:deny-activity-name",+ "markdownDescription": "Denies the activity_name command without any pre-configured scope."+ },+ {+ "description": "Denies the available_monitors command without any pre-configured scope.",+ "type": "string",+ "const": "core:window:deny-available-monitors",+ "markdownDescription": "Denies the available_monitors command without any pre-configured scope."+ },+ {+ "description": "Denies the center command without any pre-configured scope.",+ "type": "string",+ "const": "core:window:deny-center",+ "markdownDescription": "Denies the center command without any pre-configured scope."+ },+ {+ "description": "Denies the close command without any pre-configured scope.",+ "type": "string",+ "const": "core:window:deny-close",+ "markdownDescription": "Denies the close command without any pre-configured scope."+ },+ {+ "description": "Denies the create command without any pre-configured scope.",+ "type": "string",+ "const": "core:window:deny-create",+ "markdownDescription": "Denies the create command without any pre-configured scope."+ },+ {+ "description": "Denies the current_monitor command without any pre-configured scope.",+ "type": "string",+ "const": "core:window:deny-current-monitor",+ "markdownDescription": "Denies the current_monitor command without any pre-configured scope."+ },+ {+ "description": "Denies the cursor_position command without any pre-configured scope.",+ "type": "string",+ "const": "core:window:deny-cursor-position",+ "markdownDescription": "Denies the cursor_position command without any pre-configured scope."+ },+ {+ "description": "Denies the destroy command without any pre-configured scope.",+ "type": "string",+ "const": "core:window:deny-destroy",+ "markdownDescription": "Denies the destroy command without any pre-configured scope."+ },+ {+ "description": "Denies the get_all_windows command without any pre-configured scope.",+ "type": "string",+ "const": "core:window:deny-get-all-windows",+ "markdownDescription": "Denies the get_all_windows command without any pre-configured scope."+ },+ {+ "description": "Denies the hide command without any pre-configured scope.",+ "type": "string",+ "const": "core:window:deny-hide",+ "markdownDescription": "Denies the hide command without any pre-configured scope."+ },+ {+ "description": "Denies the inner_position command without any pre-configured scope.",+ "type": "string",+ "const": "core:window:deny-inner-position",+ "markdownDescription": "Denies the inner_position command without any pre-configured scope."+ },+ {+ "description": "Denies the inner_size command without any pre-configured scope.",+ "type": "string",+ "const": "core:window:deny-inner-size",+ "markdownDescription": "Denies the inner_size command without any pre-configured scope."+ },+ {+ "description": "Denies the internal_toggle_maximize command without any pre-configured scope.",+ "type": "string",+ "const": "core:window:deny-internal-toggle-maximize",+ "markdownDescription": "Denies the internal_toggle_maximize command without any pre-configured scope."+ },+ {+ "description": "Denies the is_always_on_top command without any pre-configured scope.",+ "type": "string",+ "const": "core:window:deny-is-always-on-top",+ "markdownDescription": "Denies the is_always_on_top command without any pre-configured scope."+ },+ {+ "description": "Denies the is_closable command without any pre-configured scope.",+ "type": "string",+ "const": "core:window:deny-is-closable",+ "markdownDescription": "Denies the is_closable command without any pre-configured scope."+ },+ {+ "description": "Denies the is_decorated command without any pre-configured scope.",+ "type": "string",+ "const": "core:window:deny-is-decorated",+ "markdownDescription": "Denies the is_decorated command without any pre-configured scope."+ },+ {+ "description": "Denies the is_enabled command without any pre-configured scope.",+ "type": "string",+ "const": "core:window:deny-is-enabled",+ "markdownDescription": "Denies the is_enabled command without any pre-configured scope."+ },+ {+ "description": "Denies the is_focused command without any pre-configured scope.",+ "type": "string",+ "const": "core:window:deny-is-focused",+ "markdownDescription": "Denies the is_focused command without any pre-configured scope."+ },+ {+ "description": "Denies the is_fullscreen command without any pre-configured scope.",+ "type": "string",+ "const": "core:window:deny-is-fullscreen",+ "markdownDescription": "Denies the is_fullscreen command without any pre-configured scope."+ },+ {+ "description": "Denies the is_maximizable command without any pre-configured scope.",+ "type": "string",+ "const": "core:window:deny-is-maximizable",+ "markdownDescription": "Denies the is_maximizable command without any pre-configured scope."+ },+ {+ "description": "Denies the is_maximized command without any pre-configured scope.",+ "type": "string",+ "const": "core:window:deny-is-maximized",+ "markdownDescription": "Denies the is_maximized command without any pre-configured scope."+ },+ {+ "description": "Denies the is_minimizable command without any pre-configured scope.",+ "type": "string",+ "const": "core:window:deny-is-minimizable",+ "markdownDescription": "Denies the is_minimizable command without any pre-configured scope."+ },+ {+ "description": "Denies the is_minimized command without any pre-configured scope.",+ "type": "string",+ "const": "core:window:deny-is-minimized",+ "markdownDescription": "Denies the is_minimized command without any pre-configured scope."+ },+ {+ "description": "Denies the is_resizable command without any pre-configured scope.",+ "type": "string",+ "const": "core:window:deny-is-resizable",+ "markdownDescription": "Denies the is_resizable command without any pre-configured scope."+ },+ {+ "description": "Denies the is_visible command without any pre-configured scope.",+ "type": "string",+ "const": "core:window:deny-is-visible",+ "markdownDescription": "Denies the is_visible command without any pre-configured scope."+ },+ {+ "description": "Denies the maximize command without any pre-configured scope.",+ "type": "string",+ "const": "core:window:deny-maximize",+ "markdownDescription": "Denies the maximize command without any pre-configured scope."+ },+ {+ "description": "Denies the minimize command without any pre-configured scope.",+ "type": "string",+ "const": "core:window:deny-minimize",+ "markdownDescription": "Denies the minimize command without any pre-configured scope."+ },+ {+ "description": "Denies the monitor_from_point command without any pre-configured scope.",+ "type": "string",+ "const": "core:window:deny-monitor-from-point",+ "markdownDescription": "Denies the monitor_from_point command without any pre-configured scope."+ },+ {+ "description": "Denies the outer_position command without any pre-configured scope.",+ "type": "string",+ "const": "core:window:deny-outer-position",+ "markdownDescription": "Denies the outer_position command without any pre-configured scope."+ },+ {+ "description": "Denies the outer_size command without any pre-configured scope.",+ "type": "string",+ "const": "core:window:deny-outer-size",+ "markdownDescription": "Denies the outer_size command without any pre-configured scope."+ },+ {+ "description": "Denies the primary_monitor command without any pre-configured scope.",+ "type": "string",+ "const": "core:window:deny-primary-monitor",+ "markdownDescription": "Denies the primary_monitor command without any pre-configured scope."+ },+ {+ "description": "Denies the request_user_attention command without any pre-configured scope.",+ "type": "string",+ "const": "core:window:deny-request-user-attention",+ "markdownDescription": "Denies the request_user_attention command without any pre-configured scope."+ },+ {+ "description": "Denies the scale_factor command without any pre-configured scope.",+ "type": "string",+ "const": "core:window:deny-scale-factor",+ "markdownDescription": "Denies the scale_factor command without any pre-configured scope."+ },+ {+ "description": "Denies the scene_identifier command without any pre-configured scope.",+ "type": "string",+ "const": "core:window:deny-scene-identifier",+ "markdownDescription": "Denies the scene_identifier command without any pre-configured scope."+ },+ {+ "description": "Denies the set_always_on_bottom command without any pre-configured scope.",+ "type": "string",+ "const": "core:window:deny-set-always-on-bottom",+ "markdownDescription": "Denies the set_always_on_bottom command without any pre-configured scope."+ },+ {+ "description": "Denies the set_always_on_top command without any pre-configured scope.",+ "type": "string",+ "const": "core:window:deny-set-always-on-top",+ "markdownDescription": "Denies the set_always_on_top command without any pre-configured scope."+ },+ {+ "description": "Denies the set_background_color command without any pre-configured scope.",+ "type": "string",+ "const": "core:window:deny-set-background-color",+ "markdownDescription": "Denies the set_background_color command without any pre-configured scope."+ },+ {+ "description": "Denies the set_badge_count command without any pre-configured scope.",+ "type": "string",+ "const": "core:window:deny-set-badge-count",+ "markdownDescription": "Denies the set_badge_count command without any pre-configured scope."+ },+ {+ "description": "Denies the set_badge_label command without any pre-configured scope.",+ "type": "string",+ "const": "core:window:deny-set-badge-label",+ "markdownDescription": "Denies the set_badge_label command without any pre-configured scope."+ },+ {+ "description": "Denies the set_closable command without any pre-configured scope.",+ "type": "string",+ "const": "core:window:deny-set-closable",+ "markdownDescription": "Denies the set_closable command without any pre-configured scope."+ },+ {+ "description": "Denies the set_content_protected command without any pre-configured scope.",+ "type": "string",+ "const": "core:window:deny-set-content-protected",+ "markdownDescription": "Denies the set_content_protected command without any pre-configured scope."+ },+ {+ "description": "Denies the set_cursor_grab command without any pre-configured scope.",+ "type": "string",+ "const": "core:window:deny-set-cursor-grab",+ "markdownDescription": "Denies the set_cursor_grab command without any pre-configured scope."+ },+ {+ "description": "Denies the set_cursor_icon command without any pre-configured scope.",+ "type": "string",+ "const": "core:window:deny-set-cursor-icon",+ "markdownDescription": "Denies the set_cursor_icon command without any pre-configured scope."+ },+ {+ "description": "Denies the set_cursor_position command without any pre-configured scope.",+ "type": "string",+ "const": "core:window:deny-set-cursor-position",+ "markdownDescription": "Denies the set_cursor_position command without any pre-configured scope."+ },+ {+ "description": "Denies the set_cursor_visible command without any pre-configured scope.",+ "type": "string",+ "const": "core:window:deny-set-cursor-visible",+ "markdownDescription": "Denies the set_cursor_visible command without any pre-configured scope."+ },+ {+ "description": "Denies the set_decorations command without any pre-configured scope.",+ "type": "string",+ "const": "core:window:deny-set-decorations",+ "markdownDescription": "Denies the set_decorations command without any pre-configured scope."+ },+ {+ "description": "Denies the set_effects command without any pre-configured scope.",+ "type": "string",+ "const": "core:window:deny-set-effects",+ "markdownDescription": "Denies the set_effects command without any pre-configured scope."+ },+ {+ "description": "Denies the set_enabled command without any pre-configured scope.",+ "type": "string",+ "const": "core:window:deny-set-enabled",+ "markdownDescription": "Denies the set_enabled command without any pre-configured scope."+ },+ {+ "description": "Denies the set_focus command without any pre-configured scope.",+ "type": "string",+ "const": "core:window:deny-set-focus",+ "markdownDescription": "Denies the set_focus command without any pre-configured scope."+ },+ {+ "description": "Denies the set_focusable command without any pre-configured scope.",+ "type": "string",+ "const": "core:window:deny-set-focusable",+ "markdownDescription": "Denies the set_focusable command without any pre-configured scope."+ },+ {+ "description": "Denies the set_fullscreen command without any pre-configured scope.",+ "type": "string",+ "const": "core:window:deny-set-fullscreen",+ "markdownDescription": "Denies the set_fullscreen command without any pre-configured scope."+ },+ {+ "description": "Denies the set_fullscreen_on_monitor command without any pre-configured scope.",+ "type": "string",+ "const": "core:window:deny-set-fullscreen-on-monitor",+ "markdownDescription": "Denies the set_fullscreen_on_monitor command without any pre-configured scope."+ },+ {+ "description": "Denies the set_icon command without any pre-configured scope.",+ "type": "string",+ "const": "core:window:deny-set-icon",+ "markdownDescription": "Denies the set_icon command without any pre-configured scope."+ },+ {+ "description": "Denies the set_ignore_cursor_events command without any pre-configured scope.",+ "type": "string",+ "const": "core:window:deny-set-ignore-cursor-events",+ "markdownDescription": "Denies the set_ignore_cursor_events command without any pre-configured scope."+ },+ {+ "description": "Denies the set_max_size command without any pre-configured scope.",+ "type": "string",+ "const": "core:window:deny-set-max-size",+ "markdownDescription": "Denies the set_max_size command without any pre-configured scope."+ },+ {+ "description": "Denies the set_maximizable command without any pre-configured scope.",+ "type": "string",+ "const": "core:window:deny-set-maximizable",+ "markdownDescription": "Denies the set_maximizable command without any pre-configured scope."+ },+ {+ "description": "Denies the set_min_size command without any pre-configured scope.",+ "type": "string",+ "const": "core:window:deny-set-min-size",+ "markdownDescription": "Denies the set_min_size command without any pre-configured scope."+ },+ {+ "description": "Denies the set_minimizable command without any pre-configured scope.",+ "type": "string",+ "const": "core:window:deny-set-minimizable",+ "markdownDescription": "Denies the set_minimizable command without any pre-configured scope."+ },+ {+ "description": "Denies the set_overlay_icon command without any pre-configured scope.",+ "type": "string",+ "const": "core:window:deny-set-overlay-icon",+ "markdownDescription": "Denies the set_overlay_icon command without any pre-configured scope."+ },+ {+ "description": "Denies the set_position command without any pre-configured scope.",+ "type": "string",+ "const": "core:window:deny-set-position",+ "markdownDescription": "Denies the set_position command without any pre-configured scope."+ },+ {+ "description": "Denies the set_progress_bar command without any pre-configured scope.",+ "type": "string",+ "const": "core:window:deny-set-progress-bar",+ "markdownDescription": "Denies the set_progress_bar command without any pre-configured scope."+ },+ {+ "description": "Denies the set_resizable command without any pre-configured scope.",+ "type": "string",+ "const": "core:window:deny-set-resizable",+ "markdownDescription": "Denies the set_resizable command without any pre-configured scope."+ },+ {+ "description": "Denies the set_shadow command without any pre-configured scope.",+ "type": "string",+ "const": "core:window:deny-set-shadow",+ "markdownDescription": "Denies the set_shadow command without any pre-configured scope."+ },+ {+ "description": "Denies the set_simple_fullscreen command without any pre-configured scope.",+ "type": "string",+ "const": "core:window:deny-set-simple-fullscreen",+ "markdownDescription": "Denies the set_simple_fullscreen command without any pre-configured scope."+ },+ {+ "description": "Denies the set_size command without any pre-configured scope.",+ "type": "string",+ "const": "core:window:deny-set-size",+ "markdownDescription": "Denies the set_size command without any pre-configured scope."+ },+ {+ "description": "Denies the set_size_constraints command without any pre-configured scope.",+ "type": "string",+ "const": "core:window:deny-set-size-constraints",+ "markdownDescription": "Denies the set_size_constraints command without any pre-configured scope."+ },+ {+ "description": "Denies the set_skip_taskbar command without any pre-configured scope.",+ "type": "string",+ "const": "core:window:deny-set-skip-taskbar",+ "markdownDescription": "Denies the set_skip_taskbar command without any pre-configured scope."+ },+ {+ "description": "Denies the set_theme command without any pre-configured scope.",+ "type": "string",+ "const": "core:window:deny-set-theme",+ "markdownDescription": "Denies the set_theme command without any pre-configured scope."+ },+ {+ "description": "Denies the set_title command without any pre-configured scope.",+ "type": "string",+ "const": "core:window:deny-set-title",+ "markdownDescription": "Denies the set_title command without any pre-configured scope."+ },+ {+ "description": "Denies the set_title_bar_style command without any pre-configured scope.",+ "type": "string",+ "const": "core:window:deny-set-title-bar-style",+ "markdownDescription": "Denies the set_title_bar_style command without any pre-configured scope."+ },+ {+ "description": "Denies the set_visible_on_all_workspaces command without any pre-configured scope.",+ "type": "string",+ "const": "core:window:deny-set-visible-on-all-workspaces",+ "markdownDescription": "Denies the set_visible_on_all_workspaces command without any pre-configured scope."+ },+ {+ "description": "Denies the show command without any pre-configured scope.",+ "type": "string",+ "const": "core:window:deny-show",+ "markdownDescription": "Denies the show command without any pre-configured scope."+ },+ {+ "description": "Denies the start_dragging command without any pre-configured scope.",+ "type": "string",+ "const": "core:window:deny-start-dragging",+ "markdownDescription": "Denies the start_dragging command without any pre-configured scope."+ },+ {+ "description": "Denies the start_resize_dragging command without any pre-configured scope.",+ "type": "string",+ "const": "core:window:deny-start-resize-dragging",+ "markdownDescription": "Denies the start_resize_dragging command without any pre-configured scope."+ },+ {+ "description": "Denies the theme command without any pre-configured scope.",+ "type": "string",+ "const": "core:window:deny-theme",+ "markdownDescription": "Denies the theme command without any pre-configured scope."+ },+ {+ "description": "Denies the title command without any pre-configured scope.",+ "type": "string",+ "const": "core:window:deny-title",+ "markdownDescription": "Denies the title command without any pre-configured scope."+ },+ {+ "description": "Denies the toggle_maximize command without any pre-configured scope.",+ "type": "string",+ "const": "core:window:deny-toggle-maximize",+ "markdownDescription": "Denies the toggle_maximize command without any pre-configured scope."+ },+ {+ "description": "Denies the unmaximize command without any pre-configured scope.",+ "type": "string",+ "const": "core:window:deny-unmaximize",+ "markdownDescription": "Denies the unmaximize command without any pre-configured scope."+ },+ {+ "description": "Denies the unminimize command without any pre-configured scope.",+ "type": "string",+ "const": "core:window:deny-unminimize",+ "markdownDescription": "Denies the unminimize command without any pre-configured scope."+ }+ ]+ },+ "Value": {+ "description": "All supported ACL values.",+ "anyOf": [+ {+ "description": "Represents a null JSON value.",+ "type": "null"+ },+ {+ "description": "Represents a [`bool`].",+ "type": "boolean"+ },+ {+ "description": "Represents a valid ACL [`Number`].",+ "allOf": [+ {+ "$ref": "#/definitions/Number"+ }+ ]+ },+ {+ "description": "Represents a [`String`].",+ "type": "string"+ },+ {+ "description": "Represents a list of other [`Value`]s.",+ "type": "array",+ "items": {+ "$ref": "#/definitions/Value"+ }+ },+ {+ "description": "Represents a map of [`String`] keys to [`Value`]s.",+ "type": "object",+ "additionalProperties": {+ "$ref": "#/definitions/Value"+ }+ }+ ]+ },+ "Number": {+ "description": "A valid ACL number.",+ "anyOf": [+ {+ "description": "Represents an [`i64`].",+ "type": "integer",+ "format": "int64"+ },+ {+ "description": "Represents a [`f64`].",+ "type": "number",+ "format": "double"+ }+ ]+ },+ "Target": {+ "description": "Platform target.",+ "oneOf": [+ {+ "description": "MacOS.",+ "type": "string",+ "enum": [+ "macOS"+ ]+ },+ {+ "description": "Windows.",+ "type": "string",+ "enum": [+ "windows"+ ]+ },+ {+ "description": "Linux.",+ "type": "string",+ "enum": [+ "linux"+ ]+ },+ {+ "description": "Android.",+ "type": "string",+ "enum": [+ "android"+ ]+ },+ {+ "description": "iOS.",+ "type": "string",+ "enum": [+ "iOS"+ ]+ }+ ]+ }+ }+}\ No newline at end of filediff --git a/apps/settings/src-tauri/icons/icon.ico b/apps/settings/src-tauri/icons/icon.iconew file mode 100644index 0000000..07af2cbBinary files /dev/null and b/apps/settings/src-tauri/icons/icon.ico differdiff --git a/apps/settings/src-tauri/src/main.rs b/apps/settings/src-tauri/src/main.rsnew file mode 100644index 0000000..1beba34--- /dev/null+++ b/apps/settings/src-tauri/src/main.rs@@ -0,0 +1,68 @@+//! Muelle settings: a separate process that exists only while its window is+//! open. It edits the configuration file and tells the dock to reload it.++#![cfg_attr(not(debug_assertions), windows_subsystem = "windows")]++use std::env;++use muelle_config::Config;+use muelle_shell::{autostart, dock_link};++/// The dock owns the pinned and recent apps; this app never overwrites them+/// with a stale copy.+fn merged_with_disk(config: Config) -> Config {+ match muelle_config::load(&muelle_config::default_path()) {+ Ok(Some(disk)) => Config {+ pinned: disk.pinned,+ recent: disk.recent,+ ..config+ },+ _ => config,+ }+}++#[tauri::command]+fn get_config() -> Config {+ muelle_config::load(&muelle_config::default_path())+ .ok()+ .flatten()+ .unwrap_or_default()+}++#[tauri::command]+fn set_config(config: Config) -> Result<Config, String> {+ let config = merged_with_disk(config.sanitized());+ muelle_config::save(&muelle_config::default_path(), &config)+ .map_err(|error| error.to_string())?;+ dock_link::notify_config_changed();+ Ok(config)+}++#[tauri::command]+fn get_autostart() -> bool {+ autostart::is_enabled()+}++#[tauri::command]+fn set_autostart(enabled: bool) -> Result<(), String> {+ let dock = env::current_exe()+ .map_err(|error| error.to_string())?+ .with_file_name("muelle.exe");+ let target = enabled.then(|| dock.to_string_lossy().into_owned());+ autostart::set(target.as_deref()).map_err(|error| error.to_string())+}++fn main() {+ muelle_config::migrate_legacy_folder();+ let result = tauri::Builder::default()+ .invoke_handler(tauri::generate_handler![+ get_config,+ set_config,+ get_autostart,+ set_autostart+ ])+ .run(tauri::generate_context!());+ if let Err(error) = result {+ eprintln!("muelle-settings: {error}");+ }+}diff --git a/apps/settings/src-tauri/tauri.conf.json b/apps/settings/src-tauri/tauri.conf.jsonnew file mode 100644index 0000000..a11e430--- /dev/null+++ b/apps/settings/src-tauri/tauri.conf.json@@ -0,0 +1,30 @@+{+ "$schema": "https://schema.tauri.app/config/2",+ "productName": "Muelle",+ "identifier": "app.muelle.settings",+ "build": {+ "frontendDist": "../dist",+ "devUrl": "http://localhost:1420",+ "beforeDevCommand": "pnpm dev",+ "beforeBuildCommand": "pnpm build"+ },+ "app": {+ "windows": [+ {+ "label": "main",+ "title": "Muelle",+ "width": 780,+ "height": 560,+ "resizable": false,+ "maximizable": false,+ "decorations": false,+ "transparent": true,+ "shadow": true,+ "center": true,+ "windowEffects": { "effects": ["acrylic"] }+ }+ ],+ "security": { "csp": "default-src 'self'; style-src 'self' 'unsafe-inline'; img-src 'self' data:" }+ },+ "bundle": { "active": false, "icon": ["icons/icon.ico"] }+}diff --git a/apps/settings/src/App.tsx b/apps/settings/src/App.tsxnew file mode 100644index 0000000..d7ce9eb--- /dev/null+++ b/apps/settings/src/App.tsx@@ -0,0 +1,222 @@+import { getCurrentWindow } from "@tauri-apps/api/window";+import { useCallback, useEffect, useRef, useState } from "react";+import {+ type Config,+ type Language,+ ICON_SIZE,+ MAX_MAGNIFIED_SIZE,+ getAutostart,+ loadConfig,+ saveConfig,+ setAutostart,+} from "./config";+import { Card, Row, Segmented, Slider, Toggle } from "./controls";+import en from "./i18n/en.json";+import es from "./i18n/es.json";++type Section = "dock" | "system";+type Texts = typeof es;++/** Dragging a slider saves at most this often; the dock redraws on each save. */+const SAVE_DELAY_MS = 60;++function textsFor(language: Language): Texts {+ const spanish =+ language === "es" || (language === "auto" && navigator.language.toLowerCase().startsWith("es"));+ return spanish ? es : en;+}++export function App() {+ const [config, setConfig] = useState<Config | null>(null);+ const [autostart, setAutostartState] = useState(false);+ const [section, setSection] = useState<Section>("dock");+ const [failed, setFailed] = useState(false);+ const pending = useRef<Config | null>(null);+ const timer = useRef<number | undefined>(undefined);++ useEffect(() => {+ let alive = true;+ Promise.all([loadConfig(), getAutostart()])+ .then(([loaded, starts]) => {+ if (alive) {+ setConfig(loaded);+ setAutostartState(starts);+ }+ })+ .catch(() => alive && setFailed(true));+ return () => {+ alive = false;+ window.clearTimeout(timer.current);+ };+ }, []);++ // Shows the change at once and saves the latest value shortly after, so a+ // slider drag does not write the file on every pixel.+ const update = useCallback((patch: Partial<Config>) => {+ setConfig((current) => {+ if (!current) return current;+ const next = { ...current, ...patch };+ if (next.magnifiedSize < next.iconSize) next.magnifiedSize = next.iconSize;+ pending.current = next;+ window.clearTimeout(timer.current);+ timer.current = window.setTimeout(() => {+ const latest = pending.current;+ pending.current = null;+ if (latest) {+ saveConfig(latest)+ .then(() => setFailed(false))+ .catch(() => setFailed(true));+ }+ }, SAVE_DELAY_MS);+ return next;+ });+ }, []);++ const changeAutostart = useCallback((enabled: boolean) => {+ setAutostartState(enabled);+ setAutostart(enabled).catch(() => {+ setAutostartState(!enabled);+ setFailed(true);+ });+ }, []);++ if (!config) return <div className="window" />;+ const t = textsFor(config.language);+ const appWindow = getCurrentWindow();++ return (+ <div className="window">+ <aside className="sidebar" data-tauri-drag-region>+ <div className="traffic">+ <button+ type="button"+ className="light light-close"+ aria-label={t.close}+ onClick={() => appWindow.close()}+ />+ <button+ type="button"+ className="light light-minimize"+ aria-label={t.minimize}+ onClick={() => appWindow.minimize()}+ />+ <span className="light light-idle" />+ </div>+ <nav>+ <NavItem active={section === "dock"} onSelect={() => setSection("dock")} glyph="▭">+ {t.dock}+ </NavItem>+ <NavItem active={section === "system"} onSelect={() => setSection("system")} glyph="⚙">+ {t.system}+ </NavItem>+ </nav>+ </aside>++ <main className="content">+ <header className="content-title" data-tauri-drag-region>+ {section === "dock" ? t.dock : t.system}+ </header>+ <div className="content-body">+ {section === "dock" ? (+ <>+ <Card>+ <Row label={t.size}>+ <Slider+ label={t.size}+ value={config.iconSize}+ min={ICON_SIZE.min}+ max={ICON_SIZE.max}+ before={t.small}+ after={t.large}+ onChange={(iconSize) => update({ iconSize })}+ />+ </Row>+ <Row label={t.magnification} hint={t.magnificationHint}>+ <Toggle+ label={t.magnification}+ checked={config.magnification}+ onChange={(magnification) => update({ magnification })}+ />+ </Row>+ <Row label={t.magnifiedSize}>+ <Slider+ label={t.magnifiedSize}+ value={config.magnifiedSize}+ min={config.iconSize}+ max={MAX_MAGNIFIED_SIZE}+ before={t.small}+ after={t.large}+ disabled={!config.magnification}+ onChange={(magnifiedSize) => update({ magnifiedSize })}+ />+ </Row>+ </Card>+ <Card>+ <Row label={t.autoHide} hint={t.autoHideHint}>+ <Toggle+ label={t.autoHide}+ checked={config.autoHide}+ onChange={(autoHide) => update({ autoHide })}+ />+ </Row>+ <Row label={t.genie} hint={t.genieHint}>+ <Toggle+ label={t.genie}+ checked={config.genie}+ onChange={(genie) => update({ genie })}+ />+ </Row>+ </Card>+ </>+ ) : (+ <Card>+ <Row label={t.autostart}>+ <Toggle label={t.autostart} checked={autostart} onChange={changeAutostart} />+ </Row>+ <Row label={t.language}>+ <Segmented<Language>+ label={t.language}+ value={config.language}+ options={[+ { value: "auto", label: t.languageAuto },+ { value: "es", label: "Español" },+ { value: "en", label: "English" },+ ]}+ onChange={(language) => update({ language })}+ />+ </Row>+ </Card>+ )}+ {failed ? (+ <p className="error" role="alert">+ {t.saveError}+ </p>+ ) : null}+ </div>+ </main>+ </div>+ );+}++interface NavItemProps {+ active: boolean;+ glyph: string;+ onSelect: () => void;+ children: string;+}++function NavItem({ active, glyph, onSelect, children }: NavItemProps) {+ return (+ <button+ type="button"+ className="nav-item"+ aria-current={active ? "page" : undefined}+ onClick={onSelect}+ >+ <span className="nav-glyph" aria-hidden="true">+ {glyph}+ </span>+ {children}+ </button>+ );+}diff --git a/apps/settings/src/config.ts b/apps/settings/src/config.tsnew file mode 100644index 0000000..897435b--- /dev/null+++ b/apps/settings/src/config.ts@@ -0,0 +1,24 @@+import { invoke } from "@tauri-apps/api/core";++export type Language = "auto" | "es" | "en";++/** Mirrors `muelle_config::Config`. */+export interface Config {+ version: number;+ pinned: string[];+ recent: string[];+ autoHide: boolean;+ iconSize: number;+ magnification: boolean;+ magnifiedSize: number;+ genie: boolean;+ language: Language;+}++export const ICON_SIZE = { min: 32, max: 96 } as const;+export const MAX_MAGNIFIED_SIZE = 160;++export const loadConfig = () => invoke<Config>("get_config");+export const saveConfig = (config: Config) => invoke<Config>("set_config", { config });+export const getAutostart = () => invoke<boolean>("get_autostart");+export const setAutostart = (enabled: boolean) => invoke<void>("set_autostart", { enabled });diff --git a/apps/settings/src/controls.tsx b/apps/settings/src/controls.tsxnew file mode 100644index 0000000..4f7bf7a--- /dev/null+++ b/apps/settings/src/controls.tsx@@ -0,0 +1,101 @@+import type { ReactNode } from "react";++export function Card({ children }: { children: ReactNode }) {+ return <section className="card">{children}</section>;+}++interface RowProps {+ label: string;+ hint?: string;+ children: ReactNode;+}++export function Row({ label, hint, children }: RowProps) {+ return (+ <div className="row">+ <div className="row-text">+ <span className="row-label">{label}</span>+ {hint ? <span className="row-hint">{hint}</span> : null}+ </div>+ <div className="row-control">{children}</div>+ </div>+ );+}++interface ToggleProps {+ checked: boolean;+ label: string;+ onChange: (checked: boolean) => void;+}++export function Toggle({ checked, label, onChange }: ToggleProps) {+ return (+ <button+ type="button"+ role="switch"+ aria-checked={checked}+ aria-label={label}+ className="toggle"+ onClick={() => onChange(!checked)}+ >+ <span className="toggle-knob" />+ </button>+ );+}++interface SliderProps {+ value: number;+ min: number;+ max: number;+ label: string;+ before?: string;+ after?: string;+ disabled?: boolean;+ onChange: (value: number) => void;+}++export function Slider({ value, min, max, label, before, after, disabled, onChange }: SliderProps) {+ const filled = ((value - min) / (max - min)) * 100;+ return (+ <div className="slider">+ {before ? <span className="slider-edge">{before}</span> : null}+ <input+ type="range"+ aria-label={label}+ min={min}+ max={max}+ value={value}+ disabled={disabled}+ style={{ "--filled": `${filled}%` } as React.CSSProperties}+ onChange={(event) => onChange(Number(event.target.value))}+ />+ {after ? <span className="slider-edge">{after}</span> : null}+ </div>+ );+}++interface SegmentedProps<T extends string> {+ value: T;+ label: string;+ options: readonly { value: T; label: string }[];+ onChange: (value: T) => void;+}++export function Segmented<T extends string>({ value, label, options, onChange }: SegmentedProps<T>) {+ return (+ <div className="segmented" role="radiogroup" aria-label={label}>+ {options.map((option) => (+ <button+ key={option.value}+ type="button"+ role="radio"+ aria-checked={option.value === value}+ className="segment"+ onClick={() => onChange(option.value)}+ >+ {option.label}+ </button>+ ))}+ </div>+ );+}diff --git a/apps/settings/src/i18n/en.json b/apps/settings/src/i18n/en.jsonnew file mode 100644index 0000000..04e2c61--- /dev/null+++ b/apps/settings/src/i18n/en.json@@ -0,0 +1,20 @@+{+ "dock": "Dock",+ "system": "System",+ "size": "Size",+ "small": "Small",+ "large": "Large",+ "magnification": "Magnification",+ "magnificationHint": "Icons grow as the pointer passes over them.",+ "magnifiedSize": "Magnified size",+ "autoHide": "Automatically hide and show the Dock",+ "autoHideHint": "It reappears when you touch the bottom edge of the screen.",+ "genie": "Genie effect when minimizing",+ "genieHint": "While it is on, windows do not use the Windows animations for maximizing or closing.",+ "autostart": "Open Muelle at login",+ "language": "Language",+ "languageAuto": "Automatic",+ "close": "Close",+ "minimize": "Minimize",+ "saveError": "The settings could not be saved."+}diff --git a/apps/settings/src/i18n/es.json b/apps/settings/src/i18n/es.jsonnew file mode 100644index 0000000..4d58e94--- /dev/null+++ b/apps/settings/src/i18n/es.json@@ -0,0 +1,20 @@+{+ "dock": "Dock",+ "system": "Sistema",+ "size": "Tamaño",+ "small": "Pequeño",+ "large": "Grande",+ "magnification": "Ampliación",+ "magnificationHint": "Los iconos crecen al pasar el cursor.",+ "magnifiedSize": "Tamaño ampliado",+ "autoHide": "Ocultar y mostrar el Dock automáticamente",+ "autoHideHint": "Reaparece al tocar el borde inferior de la pantalla.",+ "genie": "Efecto genio al minimizar",+ "genieHint": "Mientras está activo, las ventanas no usan las animaciones de Windows al maximizar ni al cerrar.",+ "autostart": "Abrir Muelle al iniciar sesión",+ "language": "Idioma",+ "languageAuto": "Automático",+ "close": "Cerrar",+ "minimize": "Minimizar",+ "saveError": "No se pudieron guardar los ajustes."+}diff --git a/apps/settings/src/main.tsx b/apps/settings/src/main.tsxnew file mode 100644index 0000000..9891129--- /dev/null+++ b/apps/settings/src/main.tsx@@ -0,0 +1,10 @@+import { StrictMode } from "react";+import { createRoot } from "react-dom/client";+import { App } from "./App";+import "./styles.css";++createRoot(document.getElementById("root")!).render(+ <StrictMode>+ <App />+ </StrictMode>,+);diff --git a/apps/settings/src/styles.css b/apps/settings/src/styles.cssnew file mode 100644index 0000000..6dc5e43--- /dev/null+++ b/apps/settings/src/styles.css@@ -0,0 +1,270 @@+:root {+ color-scheme: light dark;+ --accent: #0a84ff;+ --text: rgba(0, 0, 0, 0.88);+ --text-dim: rgba(0, 0, 0, 0.55);+ --sidebar: rgba(246, 246, 248, 0.55);+ --content: rgba(255, 255, 255, 0.86);+ --card: rgba(255, 255, 255, 0.8);+ --line: rgba(0, 0, 0, 0.08);+ --track: rgba(0, 0, 0, 0.16);+ --hover: rgba(0, 0, 0, 0.06);+ --segment: #ffffff;+ font-family: "Segoe UI Variable Text", "Segoe UI", system-ui, sans-serif;+ font-size: 13px;+}++@media (prefers-color-scheme: dark) {+ :root {+ --text: rgba(255, 255, 255, 0.92);+ --text-dim: rgba(255, 255, 255, 0.55);+ --sidebar: rgba(40, 40, 44, 0.5);+ --content: rgba(30, 30, 32, 0.88);+ --card: rgba(255, 255, 255, 0.06);+ --line: rgba(255, 255, 255, 0.09);+ --track: rgba(255, 255, 255, 0.2);+ --hover: rgba(255, 255, 255, 0.08);+ --segment: rgba(255, 255, 255, 0.22);+ }+}++* {+ box-sizing: border-box;+}++html,+body,+#root {+ height: 100%;+ margin: 0;+ background: transparent;+ color: var(--text);+ user-select: none;+ overflow: hidden;+}++button {+ font: inherit;+ color: inherit;+ border: 0;+ background: none;+ padding: 0;+}++button:focus-visible,+input:focus-visible {+ outline: 2px solid var(--accent);+ outline-offset: 2px;+}++.window {+ display: grid;+ grid-template-columns: 200px 1fr;+ height: 100%;+}++/* The sidebar lets the window's acrylic blur show through. */+.sidebar {+ background: var(--sidebar);+ border-right: 1px solid var(--line);+ padding: 14px 10px;+}++.traffic {+ display: flex;+ gap: 8px;+ padding: 2px 6px 18px;+}++.light {+ width: 12px;+ height: 12px;+ border-radius: 50%;+ border: 0.5px solid rgba(0, 0, 0, 0.12);+}++.light-close {+ background: #ff5f57;+}++.light-minimize {+ background: #febc2e;+}++.light-idle {+ background: var(--track);+}++.nav-item {+ display: flex;+ align-items: center;+ gap: 8px;+ width: 100%;+ padding: 6px 8px;+ border-radius: 7px;+ text-align: left;+}++.nav-item:hover {+ background: var(--hover);+}++.nav-item[aria-current="page"] {+ background: var(--accent);+ color: #fff;+}++.nav-glyph {+ display: grid;+ place-items: center;+ width: 22px;+ height: 22px;+ border-radius: 6px;+ background: rgba(127, 127, 127, 0.25);+ font-size: 12px;+}++.content {+ display: flex;+ flex-direction: column;+ background: var(--content);+ min-width: 0;+}++.content-title {+ padding: 16px 24px 10px;+ font-size: 15px;+ font-weight: 600;+}++.content-body {+ padding: 4px 24px 24px;+ overflow-y: auto;+}++.card {+ background: var(--card);+ border: 1px solid var(--line);+ border-radius: 10px;+ margin-bottom: 16px;+}++.row {+ display: flex;+ align-items: center;+ justify-content: space-between;+ gap: 16px;+ min-height: 44px;+ padding: 8px 14px;+}++.row + .row {+ border-top: 1px solid var(--line);+}++.row-text {+ display: flex;+ flex-direction: column;+ gap: 2px;+ min-width: 0;+}++.row-hint {+ color: var(--text-dim);+ font-size: 11.5px;+ line-height: 1.35;+}++.row-control {+ flex-shrink: 0;+}++.toggle {+ width: 38px;+ height: 22px;+ border-radius: 11px;+ background: var(--track);+ padding: 2px;+ transition: background 0.18s ease;+}++.toggle[aria-checked="true"] {+ background: #34c759;+}++.toggle-knob {+ display: block;+ width: 18px;+ height: 18px;+ border-radius: 50%;+ background: #fff;+ box-shadow: 0 1px 3px rgba(0, 0, 0, 0.3);+ transition: transform 0.18s ease;+}++.toggle[aria-checked="true"] .toggle-knob {+ transform: translateX(16px);+}++.slider {+ display: flex;+ align-items: center;+ gap: 8px;+}++.slider-edge {+ color: var(--text-dim);+ font-size: 11px;+}++.slider input {+ appearance: none;+ width: 200px;+ height: 4px;+ border-radius: 2px;+ margin: 0;+ background: linear-gradient(to right, var(--accent) var(--filled), var(--track) var(--filled));+}++.slider input:disabled {+ opacity: 0.4;+}++.slider input::-webkit-slider-thumb {+ appearance: none;+ width: 18px;+ height: 18px;+ border-radius: 50%;+ background: #fff;+ border: 0.5px solid rgba(0, 0, 0, 0.12);+ box-shadow: 0 1px 3px rgba(0, 0, 0, 0.3);+}++.segmented {+ display: flex;+ background: var(--hover);+ border-radius: 7px;+ padding: 2px;+}++.segment {+ padding: 4px 12px;+ border-radius: 5px;+}++.segment[aria-checked="true"] {+ background: var(--segment);+ box-shadow: 0 1px 2px rgba(0, 0, 0, 0.18);+}++.error {+ color: #ff453a;+ margin: 0;+}++@media (prefers-reduced-motion: reduce) {+ .toggle,+ .toggle-knob {+ transition: none;+ }+}diff --git a/apps/settings/tsconfig.json b/apps/settings/tsconfig.jsonnew file mode 100644index 0000000..fbeed7f--- /dev/null+++ b/apps/settings/tsconfig.json@@ -0,0 +1,17 @@+{+ "compilerOptions": {+ "target": "ES2022",+ "lib": ["ES2022", "DOM", "DOM.Iterable"],+ "module": "ESNext",+ "moduleResolution": "bundler",+ "jsx": "react-jsx",+ "strict": true,+ "noUnusedLocals": true,+ "noUnusedParameters": true,+ "resolveJsonModule": true,+ "isolatedModules": true,+ "skipLibCheck": true,+ "noEmit": true+ },+ "include": ["src"]+}diff --git a/apps/settings/vite.config.ts b/apps/settings/vite.config.tsnew file mode 100644index 0000000..de46dfd--- /dev/null+++ b/apps/settings/vite.config.ts@@ -0,0 +1,9 @@+import react from "@vitejs/plugin-react";+import { defineConfig } from "vite";++export default defineConfig({+ plugins: [react()],+ clearScreen: false,+ server: { port: 1420, strictPort: true },+ build: { target: "chrome120", sourcemap: false },+});diff --git a/assets/brand/muelle-1024.png b/assets/brand/muelle-1024.pngnew file mode 100644index 0000000..a851b66Binary files /dev/null and b/assets/brand/muelle-1024.png differdiff --git a/assets/brand/muelle-preview.png b/assets/brand/muelle-preview.pngnew file mode 100644index 0000000..3554dc9Binary files /dev/null and b/assets/brand/muelle-preview.png differdiff --git a/assets/brand/muelle.ico b/assets/brand/muelle.iconew file mode 100644index 0000000..07af2cbBinary files /dev/null and b/assets/brand/muelle.ico differdiff --git a/crates/muelle-config/Cargo.toml b/crates/muelle-config/Cargo.tomlnew file mode 100644index 0000000..e5dd0fe--- /dev/null+++ b/crates/muelle-config/Cargo.toml@@ -0,0 +1,13 @@+[package]+name = "muelle-config"+version.workspace = true+edition.workspace = true+license.workspace = true++[lints]+workspace = true++[dependencies]+serde = { version = "1", features = ["derive"] }+serde_json = "1"+thiserror.workspace = truediff --git a/crates/muelle-config/src/lib.rs b/crates/muelle-config/src/lib.rsnew file mode 100644index 0000000..451ad80--- /dev/null+++ b/crates/muelle-config/src/lib.rs@@ -0,0 +1,239 @@+//! Persistent Muelle configuration stored in `%APPDATA%\Muelle\config.json`.++use std::{+ env, fs, io,+ path::{Path, PathBuf},+};++use serde::{Deserialize, Serialize};+use thiserror::Error;++pub const CURRENT_VERSION: u32 = 1;++/// Error reading or saving the configuration.+#[derive(Debug, Error)]+pub enum ConfigError {+ #[error("no se pudo acceder a `{path}`")]+ Io {+ path: PathBuf,+ #[source]+ source: io::Error,+ },+ #[error("`{path}` no es una configuración válida")]+ Parse {+ path: PathBuf,+ #[source]+ source: serde_json::Error,+ },+ #[error("no se pudo serializar la configuración")]+ Serialize(#[from] serde_json::Error),+}++/// User settings. Missing fields use their default values, so adding fields+/// does not break existing configuration files.+#[derive(Clone, Debug, PartialEq, Eq, Serialize, Deserialize)]+#[serde(default)]+#[serde(rename_all = "camelCase")]+pub struct Config {+ pub version: u32,+ pub pinned: Vec<String>,+ pub recent: Vec<String>,+ #[serde(alias = "auto_hide")]+ pub auto_hide: bool,+ /// Icon side at rest, in logical pixels.+ pub icon_size: u32,+ pub magnification: bool,+ /// Side of the icon under the cursor, in logical pixels.+ pub magnified_size: u32,+ /// Genie effect when minimizing. Off by default: while it is on, the dock+ /// turns off the system's own window transitions (see plan, "Efecto genio").+ pub genie: bool,+ pub language: Language,+}++#[derive(Clone, Copy, Debug, Default, PartialEq, Eq, Serialize, Deserialize)]+#[serde(rename_all = "lowercase")]+pub enum Language {+ /// Follow the Windows display language.+ #[default]+ Auto,+ Es,+ En,+}++pub const ICON_SIZE_RANGE: (u32, u32) = (32, 96);+pub const MAX_MAGNIFIED_SIZE: u32 = 160;++impl Config {+ /// Brings out-of-range values (a hand-edited file) back into range.+ #[must_use]+ pub fn sanitized(mut self) -> Self {+ self.icon_size = self.icon_size.clamp(ICON_SIZE_RANGE.0, ICON_SIZE_RANGE.1);+ self.magnified_size = self+ .magnified_size+ .clamp(self.icon_size, MAX_MAGNIFIED_SIZE);+ self+ }++ /// Scale of the icon under the cursor (1.0 = no magnification).+ #[must_use]+ pub fn max_scale(&self) -> f32 {+ if self.magnification {+ self.magnified_size as f32 / self.icon_size as f32+ } else {+ 1.0+ }+ }+}++impl Default for Config {+ fn default() -> Self {+ Self {+ version: CURRENT_VERSION,+ pinned: Vec::new(),+ recent: Vec::new(),+ auto_hide: false,+ icon_size: 48,+ magnification: true,+ magnified_size: 77,+ genie: false,+ language: Language::Auto,+ }+ }+}++/// Moves the settings folder from before the app was renamed to Muelle.+pub fn migrate_legacy_folder() {+ let roaming = PathBuf::from(env::var_os("APPDATA").unwrap_or_default());+ let (old, new) = (roaming.join("WinDock"), roaming.join("Muelle"));+ if old.is_dir() && !new.exists() {+ let _ = fs::rename(old, new);+ }+}++#[must_use]+pub fn default_path() -> PathBuf {+ PathBuf::from(env::var_os("APPDATA").unwrap_or_default())+ .join("Muelle")+ .join("config.json")+}++/// Reads the configuration. Returns `Ok(None)` if the file does not exist yet.+pub fn load(path: &Path) -> Result<Option<Config>, ConfigError> {+ let text = match fs::read_to_string(path) {+ Ok(text) => text,+ Err(error) if error.kind() == io::ErrorKind::NotFound => return Ok(None),+ Err(source) => {+ return Err(ConfigError::Io {+ path: path.to_owned(),+ source,+ });+ }+ };+ serde_json::from_str(&text)+ .map(|config: Config| Some(config.sanitized()))+ .map_err(|source| ConfigError::Parse {+ path: path.to_owned(),+ source,+ })+}++/// Saves the configuration atomically by writing a temporary file and renaming+/// it, so an interrupted write cannot leave a truncated file.+pub fn save(path: &Path, config: &Config) -> Result<(), ConfigError> {+ let io_error = |source| ConfigError::Io {+ path: path.to_owned(),+ source,+ };+ if let Some(folder) = path.parent() {+ fs::create_dir_all(folder).map_err(io_error)?;+ }+ let temporary = path.with_extension("json.tmp");+ fs::write(&temporary, serde_json::to_string_pretty(config)?).map_err(io_error)?;+ fs::rename(&temporary, path).map_err(io_error)+}++#[cfg(test)]+mod tests {+ use super::*;++ fn scratch(name: &str) -> PathBuf {+ let folder = env::temp_dir().join(format!("muelle-test-{}-{name}", std::process::id()));+ let _ = fs::remove_dir_all(&folder);+ folder.join("config.json")+ }++ #[test]+ fn load_should_return_none_when_file_is_missing() {+ assert_eq!(load(&scratch("missing")).ok(), Some(None));+ }++ #[test]+ fn save_then_load_should_round_trip() {+ let path = scratch("round-trip");+ let config = Config {+ pinned: vec!["explorer".into()],+ ..Config::default()+ };+ save(&path, &config).ok();+ assert_eq!(load(&path).ok(), Some(Some(config)));+ }++ #[test]+ fn load_should_fill_missing_fields_with_defaults() {+ let path = scratch("partial");+ save(&path, &Config::default()).ok();+ fs::write(&path, "{}").ok();+ assert_eq!(load(&path).ok(), Some(Some(Config::default())));+ }++ #[test]+ fn load_should_fail_on_invalid_json() {+ let path = scratch("invalid");+ save(&path, &Config::default()).ok();+ fs::write(&path, "esto no es json").ok();+ assert!(matches!(load(&path), Err(ConfigError::Parse { .. })));+ }++ #[test]+ fn sanitized_should_clamp_icon_size() {+ let config = Config {+ icon_size: 500,+ ..Config::default()+ };+ assert_eq!(config.sanitized().icon_size, ICON_SIZE_RANGE.1);+ }++ #[test]+ fn sanitized_should_never_magnify_below_the_icon_size() {+ let config = Config {+ icon_size: 80,+ magnified_size: 40,+ ..Config::default()+ };+ assert_eq!(config.sanitized().magnified_size, 80);+ }++ #[test]+ fn max_scale_should_be_one_when_magnification_is_off() {+ let config = Config {+ magnification: false,+ ..Config::default()+ };+ assert_eq!(config.max_scale(), 1.0);+ }++ #[test]+ fn genie_should_be_off_by_default() {+ assert!(!Config::default().genie);+ }++ #[test]+ fn load_should_read_files_written_before_camel_case_keys() {+ let path = scratch("legacy-keys");+ save(&path, &Config::default()).ok();+ fs::write(&path, r#"{"version":1,"pinned":["a"],"auto_hide":true}"#).ok();+ let loaded = load(&path).ok().flatten();+ assert_eq!(loaded.map(|config| config.auto_hide), Some(true));+ }+}diff --git a/crates/muelle-core/Cargo.toml b/crates/muelle-core/Cargo.tomlnew file mode 100644index 0000000..be4ace1--- /dev/null+++ b/crates/muelle-core/Cargo.toml@@ -0,0 +1,8 @@+[package]+name = "muelle-core"+version.workspace = true+edition.workspace = true+license.workspace = true++[lints]+workspace = truediff --git a/crates/muelle-core/src/bounce.rs b/crates/muelle-core/src/bounce.rsnew file mode 100644index 0000000..9c8f31f--- /dev/null+++ b/crates/muelle-core/src/bounce.rs@@ -0,0 +1,52 @@+use std::f32::consts::PI;++pub const HOP_SECONDS: f32 = 0.7;++/// Height above the resting position after `elapsed` seconds of bouncing.+/// `height` is the maximum bounce height.+#[must_use]+pub fn lift(elapsed: f32, height: f32) -> f32 {+ height * (PI * elapsed / HOP_SECONDS).sin().abs()+}++/// End time of the current bounce, allowing it to stop without cutting off+/// the icon mid-air.+#[must_use]+pub fn end_of_hop(elapsed: f32) -> f32 {+ (elapsed / HOP_SECONDS).ceil().max(1.0) * HOP_SECONDS+}++#[cfg(test)]+mod tests {+ use super::*;++ #[test]+ fn lift_should_start_on_the_ground() {+ assert_eq!(lift(0.0, 30.0), 0.0);+ }++ #[test]+ fn lift_should_peak_at_half_a_hop() {+ assert!((lift(HOP_SECONDS / 2.0, 30.0) - 30.0).abs() < 1e-3);+ }++ #[test]+ fn lift_should_touch_the_ground_at_the_end_of_each_hop() {+ assert!(lift(HOP_SECONDS * 3.0, 30.0).abs() < 1e-2);+ }++ #[test]+ fn lift_should_never_go_below_the_ground() {+ assert!((0..200).all(|i| lift(i as f32 * 0.013, 30.0) >= 0.0));+ }++ #[test]+ fn end_of_hop_should_round_up_to_the_next_landing() {+ assert!((end_of_hop(0.9) - 2.0 * HOP_SECONDS).abs() < 1e-6);+ }++ #[test]+ fn end_of_hop_should_complete_at_least_one_hop() {+ assert!((end_of_hop(0.0) - HOP_SECONDS).abs() < 1e-6);+ }+}diff --git a/crates/muelle-core/src/genie.rs b/crates/muelle-core/src/genie.rsnew file mode 100644index 0000000..118472b--- /dev/null+++ b/crates/muelle-core/src/genie.rs@@ -0,0 +1,202 @@+//! Genie effect: a window is sucked into its dock slot.+//!+//! The window is cut into horizontal strips. Two things happen, overlapping:+//! 1. its side edges bend into two S-curves that run from the window's top+//! corners to the slot (`bend`);+//! 2. the whole image slides down between those curves and disappears into+//! the slot (`slide`).+//!+//! A strip's width depends only on where it currently is on screen, so the+//! image narrows as it travels, like liquid through a funnel.++use std::f32::consts::PI;++/// Screen rectangle by its edges.+#[derive(Clone, Copy, Debug, PartialEq)]+pub struct Edges {+ pub left: f32,+ pub top: f32,+ pub right: f32,+ pub bottom: f32,+}++/// Where a source strip is drawn in one frame.+#[derive(Clone, Copy, Debug, PartialEq)]+pub struct Strip {+ /// Rows of the source image, as fractions of its height.+ pub source_top: f32,+ pub source_bottom: f32,+ /// `None` once the strip has entered the slot.+ pub target: Option<Edges>,+}++#[derive(Clone, Copy, Debug, PartialEq)]+pub struct Genie {+ pub window: Edges,+ pub slot: Edges,+}++/// The edges finish bending at this fraction of the animation.+const BEND_END: f32 = 0.5;+/// The image starts sliding at this fraction.+const SLIDE_START: f32 = 0.15;++fn smoothstep(x: f32) -> f32 {+ let x = x.clamp(0.0, 1.0);+ x * x * (3.0 - 2.0 * x)+}++impl Genie {+ /// How far the side edges have bent toward the slot at time `t` (0..=1).+ fn bend(t: f32) -> f32 {+ smoothstep(t / BEND_END)+ }++ /// How far the image has slid into the slot at time `t` (0..=1).+ fn slide(t: f32) -> f32 {+ let x = ((t - SLIDE_START) / (1.0 - SLIDE_START)).clamp(0.0, 1.0);+ // Accelerating, like something being pulled in.+ x * x+ }++ /// Left and right edges of the image at screen height `y`.+ fn sides(&self, y: f32, bend: f32) -> (f32, f32) {+ let span = self.slot.top - self.window.top;+ let along = if span > 0.0 {+ ((y - self.window.top) / span).clamp(0.0, 1.0)+ } else {+ 1.0+ };+ let curve = (1.0 - (PI * along).cos()) / 2.0 * bend;+ (+ self.window.left + (self.slot.left - self.window.left) * curve,+ self.window.right + (self.slot.right - self.window.right) * curve,+ )+ }++ /// Places `strips.len()` equal strips for time `t` (0 = untouched window,+ /// 1 = fully inside the slot). Reuses the buffer: no allocation per frame.+ pub fn frame(&self, t: f32, strips: &mut [Strip]) {+ let count = strips.len().max(1) as f32;+ let height = self.window.bottom - self.window.top;+ let bend = Self::bend(t);+ let shift = Self::slide(t) * (self.slot.bottom - self.window.top).max(0.0);++ for (index, strip) in strips.iter_mut().enumerate() {+ let source_top = index as f32 / count;+ let source_bottom = (index + 1) as f32 / count;+ let top = self.window.top + source_top * height + shift;+ let bottom = (self.window.top + source_bottom * height + shift).min(self.slot.bottom);+ strip.source_top = source_top;+ strip.source_bottom = source_bottom;+ strip.target = (top < self.slot.bottom).then(|| {+ let (left, right) = self.sides((top + bottom) / 2.0, bend);+ Edges {+ left,+ top,+ right,+ bottom,+ }+ });+ }+ }+}++#[cfg(test)]+mod tests {+ use super::*;++ const GENIE: Genie = Genie {+ window: Edges {+ left: 200.0,+ top: 100.0,+ right: 1000.0,+ bottom: 600.0,+ },+ slot: Edges {+ left: 1200.0,+ top: 1000.0,+ right: 1260.0,+ bottom: 1060.0,+ },+ };++ fn frame(t: f32) -> Vec<Strip> {+ let mut strips = vec![+ Strip {+ source_top: 0.0,+ source_bottom: 0.0,+ target: None,+ };+ 50+ ];+ GENIE.frame(t, &mut strips);+ strips+ }++ fn targets(t: f32) -> Vec<Edges> {+ frame(t).iter().filter_map(|strip| strip.target).collect()+ }++ #[test]+ fn frame_should_show_the_untouched_window_at_the_start() {+ let all = targets(0.0);+ let exact = all+ .iter()+ .all(|edges| edges.left == 200.0 && edges.right == 1000.0);+ assert!(exact && all[0].top == 100.0 && all[49].bottom == 600.0);+ }++ #[test]+ fn frame_should_leave_nothing_outside_the_slot_at_the_end() {+ assert!(targets(1.0).is_empty());+ }++ #[test]+ fn strips_should_stay_contiguous() {+ let gaps = [0.2, 0.5, 0.8].iter().any(|&t| {+ targets(t)+ .windows(2)+ .any(|pair| (pair[0].bottom - pair[1].top).abs() > 1e-3)+ });+ assert!(!gaps);+ }++ #[test]+ fn strips_should_never_be_drawn_below_the_slot() {+ let below = (0..=20).any(|i| {+ targets(i as f32 / 20.0)+ .iter()+ .any(|edges| edges.bottom > 1060.0 || edges.top >= 1060.0)+ });+ assert!(!below);+ }++ #[test]+ fn image_should_narrow_toward_the_slot() {+ let all = targets(0.6);+ let widths: Vec<f32> = all.iter().map(|edges| edges.right - edges.left).collect();+ assert!(widths.windows(2).all(|pair| pair[1] <= pair[0] + 1e-3));+ }++ #[test]+ fn image_should_never_be_narrower_than_the_slot() {+ let narrower = (0..=20).any(|i| {+ targets(i as f32 / 20.0)+ .iter()+ .any(|edges| edges.right - edges.left < 60.0 - 1e-3)+ });+ assert!(!narrower);+ }++ #[test]+ fn top_edge_should_not_move_before_the_slide_starts() {+ assert_eq!(targets(SLIDE_START)[0].top, 100.0);+ }++ #[test]+ fn strips_should_cover_the_whole_source() {+ let strips = frame(0.3);+ assert!(strips[0].source_top == 0.0 && strips[49].source_bottom == 1.0);+ }+}diff --git a/crates/muelle-core/src/layout.rs b/crates/muelle-core/src/layout.rsnew file mode 100644index 0000000..f1e9f34--- /dev/null+++ b/crates/muelle-core/src/layout.rs@@ -0,0 +1,159 @@+#[derive(Clone, Copy, Debug, PartialEq, Eq)]+pub enum ItemKind {+ Icon,+ Separator,+}++/// Dock dimensions in caller-selected logical or physical pixels.+#[derive(Clone, Copy, Debug, PartialEq)]+pub struct Metrics {+ pub icon: f32,+ pub gap: f32,+ pub padding: f32,+ pub separator_width: f32,+ pub separator_margin: f32,+}++impl Metrics {+ pub const DEFAULT: Self = Self {+ icon: 48.0,+ // Windows icons fill their square; unlike macOS icons, they have no+ // built-in margin, so the dock provides the spacing.+ gap: 12.0,+ padding: 9.0,+ separator_width: 1.0,+ separator_margin: 7.0,+ };++ #[must_use]+ pub fn scaled(self, scale: f32) -> Self {+ Self {+ icon: self.icon * scale,+ gap: self.gap * scale,+ padding: self.padding * scale,+ // Keep the divider at least one pixel wide so it remains visible.+ separator_width: (self.separator_width * scale).max(1.0),+ separator_margin: self.separator_margin * scale,+ }+ }+}++#[derive(Clone, Copy, Debug, PartialEq)]+pub struct Rect {+ pub x: f32,+ pub y: f32,+ pub width: f32,+ pub height: f32,+}++#[derive(Clone, Copy, Debug, PartialEq)]+pub struct Slot {+ pub kind: ItemKind,+ pub rect: Rect,+}++#[derive(Clone, Debug, PartialEq)]+pub struct Layout {+ pub width: f32,+ pub height: f32,+ pub slots: Vec<Slot>,+}++/// ```+/// use muelle_core::layout::{ItemKind, Metrics, layout};+/// let result = layout(&[ItemKind::Icon, ItemKind::Icon], &Metrics::DEFAULT);+/// assert_eq!(result.width, 9.0 + 48.0 + 12.0 + 48.0 + 9.0);+/// ```+#[must_use]+pub fn layout(items: &[ItemKind], metrics: &Metrics) -> Layout {+ let m = metrics;+ let mut x = m.padding;+ let slots: Vec<Slot> = items+ .iter()+ .map(|&kind| {+ let rect = match kind {+ ItemKind::Icon => Rect {+ x,+ y: m.padding,+ width: m.icon,+ height: m.icon,+ },+ ItemKind::Separator => Rect {+ x: x + m.separator_margin,+ y: m.padding + m.icon * 0.1,+ width: m.separator_width,+ height: m.icon * 0.8,+ },+ };+ x += match kind {+ ItemKind::Icon => m.icon,+ ItemKind::Separator => m.separator_width + 2.0 * m.separator_margin,+ } + m.gap;+ Slot { kind, rect }+ })+ .collect();++ let content_end = if slots.is_empty() { x } else { x - m.gap };+ Layout {+ width: content_end + m.padding,+ height: m.icon + 2.0 * m.padding,+ slots,+ }+}++#[cfg(test)]+mod tests {+ use super::*;++ const M: Metrics = Metrics::DEFAULT;++ #[test]+ fn layout_should_be_only_padding_when_empty() {+ let result = layout(&[], &M);+ assert_eq!(+ (result.width, result.height),+ (2.0 * M.padding, M.icon + 2.0 * M.padding)+ );+ }++ #[test]+ fn layout_should_not_add_trailing_gap_after_last_icon() {+ let result = layout(&[ItemKind::Icon; 3], &M);+ assert_eq!(result.width, 3.0 * M.icon + 2.0 * M.gap + 2.0 * M.padding);+ }++ #[test]+ fn layout_should_space_icons_by_icon_plus_gap() {+ let result = layout(&[ItemKind::Icon; 2], &M);+ assert_eq!(+ result.slots[1].rect.x - result.slots[0].rect.x,+ M.icon + M.gap+ );+ }++ #[test]+ fn layout_should_center_separator_line_in_its_slot() {+ let result = layout(&[ItemKind::Icon, ItemKind::Separator, ItemKind::Icon], &M);+ let (left, line, right) = (+ result.slots[0].rect,+ result.slots[1].rect,+ result.slots[2].rect,+ );+ assert_eq!(+ line.x - (left.x + left.width),+ right.x - (line.x + line.width)+ );+ }++ #[test]+ fn layout_should_keep_icons_inside_dock_height() {+ let result = layout(&[ItemKind::Icon], &M);+ let rect = result.slots[0].rect;+ assert_eq!(rect.y + rect.height + M.padding, result.height);+ }++ #[test]+ fn scaled_should_keep_separator_at_least_one_pixel() {+ assert_eq!(M.scaled(0.5).separator_width, 1.0);+ }+}diff --git a/crates/muelle-core/src/lib.rs b/crates/muelle-core/src/lib.rsnew file mode 100644index 0000000..834e76b--- /dev/null+++ b/crates/muelle-core/src/lib.rs@@ -0,0 +1,8 @@+//! Platform-independent dock logic that can be tested without Windows.++pub mod bounce;+pub mod genie;+pub mod layout;+pub mod magnify;+pub mod roster;+pub mod spring;diff --git a/crates/muelle-core/src/magnify.rs b/crates/muelle-core/src/magnify.rsnew file mode 100644index 0000000..acc16f2--- /dev/null+++ b/crates/muelle-core/src/magnify.rs@@ -0,0 +1,214 @@+//! Continuous model: the dock behaves like an elastic band stretching around+//! the cursor. Local stretch at distance `d` is `1 + a·f(d/R)`, where `f` is+//! the inverted *smoothstep* curve. Since `f` is a polynomial, accumulated+//! displacement has a closed form, so icons are positioned independently+//! without jumps or overlap.++use crate::layout::{ItemKind, Layout, Rect};++/// Magnification parameters, in the same units as [`Layout`].+#[derive(Clone, Copy, Debug, PartialEq)]+pub struct Magnifier {+ /// Distance from the cursor beyond which an icon no longer grows.+ pub range: f32,+ /// Scale of the icon directly under the cursor (1.0 = no magnification).+ pub max_scale: f32,+}++impl Magnifier {+ #[must_use]+ pub fn max_growth(&self) -> f32 {+ // 2·R·F(1), where F(1) = 1/2.+ (self.max_scale - 1.0) * self.range+ }+}++/// `f(d) = 1 − 3d² + 2d³`: 1 under the cursor, 0 from `d = 1` onward.+fn falloff(d: f32) -> f32 {+ let d = d.abs().min(1.0);+ 1.0 - 3.0 * d * d + 2.0 * d * d * d+}++/// Integral of `falloff` from 0 to `u`, odd and clamped at ±1/2.+fn falloff_integral(u: f32) -> f32 {+ let d = u.abs().min(1.0);+ (d - d * d * d + d * d * d * d / 2.0).copysign(u)+}++#[derive(Clone, Debug, PartialEq)]+pub struct Magnified {+ /// Left glass edge; expansion extends outward from zero.+ pub left: f32,+ /// Right glass edge; expansion extends outward from the resting width.+ pub right: f32,+ pub rects: Vec<Rect>,+}++impl Magnified {+ /// Index of the icon under coordinate `x`, including half of each adjacent gap.+ #[must_use]+ pub fn icon_at(&self, layout: &Layout, x: f32, gap: f32) -> Option<usize> {+ self.rects+ .iter()+ .zip(&layout.slots)+ .position(|(rect, slot)| {+ slot.kind == ItemKind::Icon+ && x >= rect.x - gap / 2.0+ && x < rect.x + rect.width + gap / 2.0+ })+ }+}++/// - `cursor`: horizontal cursor position relative to the resting dock's left edge.+/// - `amount`: 0.0 = resting, 1.0 = full effect (animated on entry and exit).+///+/// Icons grow from their base; dividers only move. Both dock ends expand equally,+/// keeping the dock centered.+#[must_use]+pub fn magnify(layout: &Layout, cursor: f32, amount: f32, magnifier: &Magnifier) -> Magnified {+ let strength = (magnifier.max_scale - 1.0) * amount;+ let range = magnifier.range.max(f32::EPSILON);+ let shift_of = |x: f32| strength * range * falloff_integral((x - cursor) / range);++ let (shift_left, shift_right) = (shift_of(0.0), shift_of(layout.width));+ let centering = -(shift_left + shift_right) / 2.0;++ let rects = layout+ .slots+ .iter()+ .map(|slot| {+ let rest = slot.rect;+ let rest_center = rest.x + rest.width / 2.0;+ let center = rest_center + shift_of(rest_center) + centering;+ let scale = match slot.kind {+ ItemKind::Icon => 1.0 + strength * falloff((rest_center - cursor) / range),+ ItemKind::Separator => 1.0,+ };+ let (width, height) = (rest.width * scale, rest.height * scale);+ Rect {+ x: center - width / 2.0,+ y: rest.y + rest.height - height,+ width,+ height,+ }+ })+ .collect();++ Magnified {+ left: shift_left + centering,+ right: layout.width + shift_right + centering,+ rects,+ }+}++#[cfg(test)]+mod tests {+ use super::*;+ use crate::layout::{Metrics, layout};++ const M: Metrics = Metrics::DEFAULT;+ const MAGNIFIER: Magnifier = Magnifier {+ range: 210.0,+ max_scale: 1.6,+ };++ fn dock(icons: usize) -> Layout {+ layout(&vec![ItemKind::Icon; icons], &M)+ }++ fn center(rect: &Rect) -> f32 {+ rect.x + rect.width / 2.0+ }++ #[test]+ fn magnify_should_return_rest_layout_when_amount_is_zero() {+ let rest = dock(8);+ let result = magnify(&rest, 100.0, 0.0, &MAGNIFIER);+ let expected: Vec<Rect> = rest.slots.iter().map(|slot| slot.rect).collect();+ assert_eq!(result.rects, expected);+ }++ #[test]+ fn magnify_should_reach_max_scale_on_icon_under_cursor() {+ let rest = dock(8);+ let cursor = center(&rest.slots[3].rect);+ let result = magnify(&rest, cursor, 1.0, &MAGNIFIER);+ assert!((result.rects[3].width - M.icon * 1.6).abs() < 1e-3);+ }++ #[test]+ fn magnify_should_leave_icons_beyond_range_at_rest_size() {+ let rest = dock(12);+ let result = magnify(&rest, center(&rest.slots[0].rect), 1.0, &MAGNIFIER);+ assert_eq!(result.rects[11].width, M.icon);+ }++ #[test]+ fn magnify_should_keep_icon_bases_on_the_same_line() {+ let rest = dock(8);+ let result = magnify(&rest, 150.0, 1.0, &MAGNIFIER);+ let base = M.padding + M.icon;+ assert!(+ result+ .rects+ .iter()+ .all(|r| (r.y + r.height - base).abs() < 1e-3)+ );+ }++ #[test]+ fn magnify_should_never_overlap_neighbouring_icons() {+ let rest = dock(12);+ let overlaps = (0..=rest.width as usize).step_by(7).any(|cursor| {+ let result = magnify(&rest, cursor as f32, 1.0, &MAGNIFIER);+ result+ .rects+ .windows(2)+ .any(|pair| pair[0].x + pair[0].width > pair[1].x)+ });+ assert!(!overlaps);+ }++ #[test]+ fn magnify_should_grow_both_edges_equally() {+ let rest = dock(12);+ let result = magnify(&rest, 137.0, 1.0, &MAGNIFIER);+ assert!((-result.left - (result.right - rest.width)).abs() < 1e-3);+ }++ #[test]+ fn magnify_should_keep_width_constant_while_cursor_is_far_from_edges() {+ let rest = dock(12);+ let width = |cursor: f32| {+ let result = magnify(&rest, cursor, 1.0, &MAGNIFIER);+ result.right - result.left+ };+ let middle = rest.width / 2.0;+ assert!((width(middle) - width(middle + 40.0)).abs() < 1e-3);+ }++ #[test]+ fn max_growth_should_match_width_gain_with_cursor_in_the_middle() {+ let rest = dock(12);+ let result = magnify(&rest, rest.width / 2.0, 1.0, &MAGNIFIER);+ let gain = result.right - result.left - rest.width;+ assert!((gain - MAGNIFIER.max_growth()).abs() < 1e-3);+ }++ #[test]+ fn icon_at_should_find_the_magnified_icon_under_cursor() {+ let rest = dock(8);+ let cursor = center(&rest.slots[5].rect);+ let result = magnify(&rest, cursor, 1.0, &MAGNIFIER);+ let under = center(&result.rects[5]);+ assert_eq!(result.icon_at(&rest, under, M.gap), Some(5));+ }++ #[test]+ fn icon_at_should_ignore_separators() {+ let rest = layout(&[ItemKind::Icon, ItemKind::Separator, ItemKind::Icon], &M);+ let result = magnify(&rest, 0.0, 0.0, &MAGNIFIER);+ let on_line = center(&result.rects[1]);+ assert_eq!(result.icon_at(&rest, on_line, 0.0), None);+ }+}diff --git a/crates/muelle-core/src/roster.rs b/crates/muelle-core/src/roster.rsnew file mode 100644index 0000000..2635e5b--- /dev/null+++ b/crates/muelle-core/src/roster.rs@@ -0,0 +1,326 @@+//! Which apps appear in the dock and in what order:+//! 1. pinned apps;+//! 2. unpinned open apps, in opening order;+//! 3. recently closed unpinned apps, as in macOS.++pub const MAX_RECENT: usize = 3;++#[derive(Clone, Debug, PartialEq, Eq)]+pub struct DockApp {+ pub id: String,+ pub running: bool,+}++#[derive(Clone, Debug, Default, PartialEq, Eq)]+pub struct Roster {+ pinned: Vec<String>,+ extra: Vec<String>,+ running: Vec<String>,+ recent: Vec<String>,+}++impl Roster {+ #[must_use]+ pub fn new(pinned: Vec<String>, recent: Vec<String>) -> Self {+ let mut roster = Self {+ pinned,+ ..Self::default()+ };+ for id in recent.into_iter().rev() {+ roster.remember(id);+ }+ roster+ }++ /// Updates open apps and returns `true` if the dock's displayed items change.+ pub fn sync<'a>(&mut self, running: impl IntoIterator<Item = &'a str>) -> bool {+ let before = (self.apps(), self.recent.clone());++ let mut now: Vec<String> = Vec::new();+ for id in running {+ if !now.iter().any(|seen| seen == id) {+ now.push(id.to_owned());+ }+ }+ let closed: Vec<String> = self+ .extra+ .iter()+ .filter(|id| !now.contains(id))+ .cloned()+ .collect();+ self.extra.retain(|id| now.contains(id));+ for id in &now {+ if !self.pinned.contains(id) && !self.extra.contains(id) {+ self.extra.push(id.clone());+ }+ }+ // Reopened apps are no longer recent; closed apps become recent.+ self.recent.retain(|id| !now.contains(id));+ for id in closed {+ self.remember(id);+ }+ self.running = now;++ (self.apps(), self.recent.clone()) != before+ }++ #[must_use]+ pub fn is_running(&self, id: &str) -> bool {+ self.running.iter().any(|running| running == id)+ }++ #[must_use]+ pub fn is_pinned(&self, id: &str) -> bool {+ self.pinned.iter().any(|pinned| pinned == id)+ }++ /// Pins an app at the end of the pinned list. If it was open and unpinned,+ /// it keeps its screen position as it moves from the open list to the pinned list.+ pub fn pin(&mut self, id: &str) {+ if self.is_pinned(id) {+ return;+ }+ self.extra.retain(|extra| extra != id);+ self.recent.retain(|recent| recent != id);+ self.pinned.push(id.to_owned());+ }++ /// Pins `id` (or moves it, if already pinned) right before `before`, or at+ /// the end of the pinned list when `before` is `None` or not pinned.+ pub fn pin_before(&mut self, id: &str, before: Option<&str>) {+ if before == Some(id) {+ return;+ }+ self.pinned.retain(|pinned| pinned != id);+ self.extra.retain(|extra| extra != id);+ self.recent.retain(|recent| recent != id);+ let at = before+ .and_then(|before| self.pinned.iter().position(|pinned| pinned == before))+ .unwrap_or(self.pinned.len());+ self.pinned.insert(at, id.to_owned());+ }++ /// Unpins an app. If it is open, it remains in the dock as the first unpinned+ /// app until it closes.+ pub fn unpin(&mut self, id: &str) {+ if !self.is_pinned(id) {+ return;+ }+ self.pinned.retain(|pinned| pinned != id);+ if self.is_running(id) {+ self.extra.insert(0, id.to_owned());+ }+ }++ #[must_use]+ pub fn pinned(&self) -> &[String] {+ &self.pinned+ }++ /// Recent apps in display order, newest first.+ #[must_use]+ pub fn recent(&self) -> &[String] {+ &self.recent+ }++ /// Pinned and open apps in display order, with pinned apps first.+ #[must_use]+ pub fn apps(&self) -> Vec<DockApp> {+ self.pinned+ .iter()+ .chain(&self.extra)+ .map(|id| DockApp {+ id: id.clone(),+ running: self.is_running(id),+ })+ .collect()+ }++ fn remember(&mut self, id: String) {+ if self.is_pinned(&id) {+ return;+ }+ self.recent.retain(|recent| *recent != id);+ self.recent.insert(0, id);+ self.recent.truncate(MAX_RECENT);+ }+}++#[cfg(test)]+mod tests {+ use super::*;++ fn roster() -> Roster {+ Roster::new(vec!["explorer".into(), "browser".into()], Vec::new())+ }++ fn ids(roster: &Roster) -> Vec<String> {+ roster.apps().into_iter().map(|app| app.id).collect()+ }++ #[test]+ fn roster_should_show_pinned_apps_when_nothing_is_running() {+ assert_eq!(ids(&roster()), ["explorer", "browser"]);+ }++ #[test]+ fn roster_should_append_unpinned_running_apps_after_pinned() {+ let mut roster = roster();+ roster.sync(["editor", "browser"]);+ assert_eq!(ids(&roster), ["explorer", "browser", "editor"]);+ }++ #[test]+ fn roster_should_mark_only_running_apps() {+ let mut roster = roster();+ roster.sync(["browser"]);+ let running: Vec<bool> = roster.apps().iter().map(|app| app.running).collect();+ assert_eq!(running, [false, true]);+ }++ #[test]+ fn roster_should_keep_first_seen_order_for_unpinned_apps() {+ let mut roster = roster();+ roster.sync(["editor"]);+ roster.sync(["terminal", "editor"]);+ assert_eq!(ids(&roster), ["explorer", "browser", "editor", "terminal"]);+ }++ #[test]+ fn roster_should_drop_unpinned_app_when_it_closes() {+ let mut roster = roster();+ roster.sync(["editor"]);+ roster.sync([]);+ assert_eq!(ids(&roster), ["explorer", "browser"]);+ }++ #[test]+ fn sync_should_report_change_when_an_indicator_changes() {+ assert!(roster().sync(["browser"]));+ }++ #[test]+ fn sync_should_report_no_change_when_only_window_count_changes() {+ let mut roster = roster();+ roster.sync(["browser"]);+ assert!(!roster.sync(["browser", "browser"]));+ }++ #[test]+ fn closing_an_unpinned_app_should_make_it_recent() {+ let mut roster = roster();+ roster.sync(["editor"]);+ roster.sync([]);+ assert_eq!(roster.recent(), ["editor"]);+ }++ #[test]+ fn closing_a_pinned_app_should_not_make_it_recent() {+ let mut roster = roster();+ roster.sync(["browser"]);+ roster.sync([]);+ assert!(roster.recent().is_empty());+ }++ #[test]+ fn recent_should_keep_only_the_last_three_most_recent_first() {+ let mut roster = roster();+ for app in ["a", "b", "c", "d"] {+ roster.sync([app]);+ roster.sync([]);+ }+ assert_eq!(roster.recent(), ["d", "c", "b"]);+ }++ #[test]+ fn reopening_a_recent_app_should_remove_it_from_recent() {+ let mut roster = roster();+ roster.sync(["editor"]);+ roster.sync([]);+ roster.sync(["editor"]);+ assert!(roster.recent().is_empty());+ }++ #[test]+ fn sync_should_report_change_when_recent_changes() {+ let mut roster = roster();+ roster.sync(["editor"]);+ assert!(roster.sync([]));+ }++ #[test]+ fn new_should_drop_recent_apps_that_are_pinned() {+ let roster = Roster::new(vec!["browser".into()], vec!["browser".into(), "x".into()]);+ assert_eq!(roster.recent(), ["x"]);+ }++ #[test]+ fn pin_should_keep_a_running_app_in_the_same_place_on_screen() {+ let mut roster = roster();+ roster.sync(["editor"]);+ roster.pin("editor");+ assert_eq!(ids(&roster), ["explorer", "browser", "editor"]);+ }++ #[test]+ fn pin_should_remove_the_app_from_recent() {+ let mut roster = roster();+ roster.sync(["editor"]);+ roster.sync([]);+ roster.pin("editor");+ assert!(roster.recent().is_empty());+ }++ #[test]+ fn unpin_should_keep_a_running_app_as_first_unpinned() {+ let mut roster = roster();+ roster.sync(["browser", "editor"]);+ roster.unpin("browser");+ assert_eq!(ids(&roster), ["explorer", "browser", "editor"]);+ }++ #[test]+ fn unpin_should_remove_a_closed_app_from_the_dock() {+ let mut roster = roster();+ roster.unpin("browser");+ assert_eq!(ids(&roster), ["explorer"]);+ }++ #[test]+ fn pin_before_should_move_a_pinned_app_left() {+ let mut roster = Roster::new(vec!["a".into(), "b".into(), "c".into()], Vec::new());+ roster.pin_before("c", Some("b"));+ assert_eq!(roster.pinned(), ["a", "c", "b"]);+ }++ #[test]+ fn pin_before_should_move_a_pinned_app_to_the_end() {+ let mut roster = Roster::new(vec!["a".into(), "b".into(), "c".into()], Vec::new());+ roster.pin_before("a", None);+ assert_eq!(roster.pinned(), ["b", "c", "a"]);+ }++ #[test]+ fn pin_before_should_pin_a_running_app_at_the_given_place() {+ let mut roster = roster();+ roster.sync(["editor"]);+ roster.pin_before("editor", Some("browser"));+ assert_eq!(ids(&roster), ["explorer", "editor", "browser"]);+ }++ #[test]+ fn pin_before_itself_should_change_nothing() {+ let mut roster = roster();+ roster.pin_before("browser", Some("browser"));+ assert_eq!(roster.pinned(), ["explorer", "browser"]);+ }++ #[test]+ fn unpinned_running_app_should_become_recent_when_it_closes() {+ let mut roster = roster();+ roster.sync(["browser"]);+ roster.unpin("browser");+ roster.sync([]);+ assert_eq!(roster.recent(), ["browser"]);+ }+}diff --git a/crates/muelle-core/src/spring.rs b/crates/muelle-core/src/spring.rsnew file mode 100644index 0000000..da83cfd--- /dev/null+++ b/crates/muelle-core/src/spring.rs@@ -0,0 +1,102 @@+//! Critically damped spring that reaches its target as quickly as possible+//! without overshooting. The exact solution keeps it stable at any frame duration.++#[derive(Clone, Copy, Debug, PartialEq)]+pub struct Spring {+ pub value: f32,+ pub velocity: f32,+ pub target: f32,+ /// Angular frequency in rad/s. The transition completes in about `6 / omega` seconds.+ pub omega: f32,+}++/// The spring is considered settled below this displacement and velocity.+const REST_DISTANCE: f32 = 0.001;+const REST_VELOCITY: f32 = 0.01;++impl Spring {+ #[must_use]+ pub fn at(value: f32, omega: f32) -> Self {+ Self {+ value,+ velocity: 0.0,+ target: value,+ omega,+ }+ }++ #[must_use]+ pub fn is_settled(&self) -> bool {+ self.value == self.target && self.velocity == 0.0+ }++ pub fn step(&mut self, dt: f32) {+ let distance = self.value - self.target;+ let c = self.velocity + self.omega * distance;+ let decay = (-self.omega * dt).exp();+ let next = (distance + c * dt) * decay;+ self.velocity = (c - self.omega * (distance + c * dt)) * decay;+ self.value = self.target + next;++ if next.abs() < REST_DISTANCE && self.velocity.abs() < REST_VELOCITY {+ self.value = self.target;+ self.velocity = 0.0;+ }+ }+}++#[cfg(test)]+mod tests {+ use super::*;++ fn run(mut spring: Spring, seconds: f32, dt: f32) -> Spring {+ (0..(seconds / dt) as usize).for_each(|_| spring.step(dt));+ spring+ }++ fn toward_one() -> Spring {+ Spring {+ target: 1.0,+ ..Spring::at(0.0, 30.0)+ }+ }++ #[test]+ fn spring_should_settle_on_target() {+ assert!(run(toward_one(), 1.0, 1.0 / 60.0).is_settled());+ }++ #[test]+ fn spring_should_never_overshoot_target() {+ let mut spring = toward_one();+ let overshoots = (0..240).any(|_| {+ spring.step(1.0 / 240.0);+ spring.value > 1.0+ });+ assert!(!overshoots);+ }++ #[test]+ fn spring_should_cover_most_of_the_distance_in_200_ms() {+ assert!(run(toward_one(), 0.2, 1.0 / 120.0).value > 0.95);+ }++ #[test]+ fn spring_should_give_same_result_regardless_of_frame_rate() {+ let slow = run(toward_one(), 0.1, 1.0 / 50.0).value;+ let fast = run(toward_one(), 0.1, 1.0 / 200.0).value;+ assert!((slow - fast).abs() < 1e-3);+ }++ #[test]+ fn spring_should_stay_stable_with_a_very_long_frame() {+ let mut spring = toward_one();+ spring.step(5.0);+ assert!(spring.is_settled());+ }++ #[test]+ fn spring_should_be_settled_when_created_at_rest() {+ assert!(Spring::at(0.0, 30.0).is_settled());+ }+}diff --git a/crates/muelle-shell/Cargo.toml b/crates/muelle-shell/Cargo.tomlnew file mode 100644index 0000000..b2d786b--- /dev/null+++ b/crates/muelle-shell/Cargo.toml@@ -0,0 +1,32 @@+[package]+name = "muelle-shell"+version.workspace = true+edition.workspace = true+license.workspace = true++[lints]+workspace = true++[dependencies]+thiserror.workspace = true+windows = { workspace = true, features = [+ "Win32_Foundation",+ "Win32_Globalization",+ "Win32_Graphics_Dwm",+ "Win32_Graphics_Gdi",+ "Win32_Storage_EnhancedStorage",+ "Win32_Storage_FileSystem",+ "Win32_Storage_Packaging_Appx",+ "Win32_System_Com",+ "Win32_System_Com_StructuredStorage",+ "Win32_System_ProcessStatus",+ "Win32_System_Registry",+ "Win32_System_Threading",+ "Win32_System_Variant",+ "Win32_UI_HiDpi",+ "Win32_UI_Input_KeyboardAndMouse",+ "Win32_UI_Shell",+ "Win32_UI_Shell_Common",+ "Win32_UI_Shell_PropertiesSystem",+ "Win32_UI_WindowsAndMessaging",+] }diff --git a/crates/muelle-shell/src/appbar.rs b/crates/muelle-shell/src/appbar.rsnew file mode 100644index 0000000..f42c11b--- /dev/null+++ b/crates/muelle-shell/src/appbar.rs@@ -0,0 +1,83 @@+//! Registering the dock as an *AppBar* reserves a bottom strip of the screen+//! so maximized windows end above the dock, and notifies the dock when an app+//! enters or exits full-screen mode.++use std::mem::size_of;++use windows::Win32::{+ Foundation::{HWND, RECT},+ UI::Shell::{+ ABE_BOTTOM, ABM_NEW, ABM_QUERYPOS, ABM_REMOVE, ABM_SETPOS, APPBARDATA, SHAppBarMessage,+ },+};++pub const ABN_FULLSCREENAPP: usize = 2;++pub struct AppBar {+ hwnd: HWND,+ reserved: Option<RECT>,+}++impl AppBar {+ /// Registers `hwnd` as an AppBar. Notifications are sent to that window+ /// using `callback`, with the notification code in `wParam`.+ #[must_use]+ pub fn register(hwnd: HWND, callback: u32) -> Option<Self> {+ let mut data = APPBARDATA {+ cbSize: size_of::<APPBARDATA>() as u32,+ hWnd: hwnd,+ uCallbackMessage: callback,+ ..Default::default()+ };+ // SAFETY: `data` is a valid APPBARDATA with its size initialized.+ let registered = unsafe { SHAppBarMessage(ABM_NEW, &mut data) } != 0;+ registered.then_some(Self {+ hwnd,+ reserved: None,+ })+ }++ /// Reserves a `height`-pixel strip at the bottom of monitor `screen`.+ /// Calls the system only when the strip changes because each reservation+ /// triggers a settings-change notification; repeating it would create a loop.+ pub fn reserve_bottom(&mut self, screen: RECT, height: i32) {+ let wanted = RECT {+ top: screen.bottom - height,+ ..screen+ };+ if self.reserved == Some(wanted) {+ return;+ }++ let mut data = APPBARDATA {+ cbSize: size_of::<APPBARDATA>() as u32,+ hWnd: self.hwnd,+ uEdge: ABE_BOTTOM,+ rc: wanted,+ ..Default::default()+ };+ // SAFETY: `data` has its size initialized and remains valid for both synchronous calls.+ unsafe {+ SHAppBarMessage(ABM_QUERYPOS, &mut data);+ // Another bar on the same edge (the Windows taskbar, before it is+ // hidden) shifts the strip upward, so preserve its height.+ data.rc.top = data.rc.bottom - height;+ SHAppBarMessage(ABM_SETPOS, &mut data);+ }+ // Treat the reservation as complete only if the system granted the+ // requested area; otherwise, retry on the next call.+ self.reserved = (data.rc == wanted).then_some(wanted);+ }+}++impl Drop for AppBar {+ fn drop(&mut self) {+ let mut data = APPBARDATA {+ cbSize: size_of::<APPBARDATA>() as u32,+ hWnd: self.hwnd,+ ..Default::default()+ };+ // SAFETY: `data` has its size initialized and remains valid for the synchronous call.+ unsafe { SHAppBarMessage(ABM_REMOVE, &mut data) };+ }+}diff --git a/crates/muelle-shell/src/autostart.rs b/crates/muelle-shell/src/autostart.rsnew file mode 100644index 0000000..ce73a6c--- /dev/null+++ b/crates/muelle-shell/src/autostart.rs@@ -0,0 +1,63 @@+use windows::{+ Win32::{+ Foundation::WIN32_ERROR,+ System::Registry::{+ HKEY, HKEY_CURRENT_USER, KEY_SET_VALUE, REG_SZ, RegCloseKey, RegDeleteValueW,+ RegOpenKeyExW, RegSetValueExW,+ },+ },+ core::{HSTRING, w},+};++const VALUE_NAME: &str = "Muelle";++pub fn set(exe: Option<&str>) -> windows::core::Result<()> {+ let mut key = HKEY::default();+ // SAFETY: The key is closed before returning, and strings live through each call.+ unsafe {+ RegOpenKeyExW(+ HKEY_CURRENT_USER,+ w!("Software\\Microsoft\\Windows\\CurrentVersion\\Run"),+ None,+ KEY_SET_VALUE,+ &mut key,+ )+ .ok()?;+ let result = match exe {+ Some(path) => {+ let command: Vec<u16> = format!("\"{path}\"")+ .encode_utf16()+ .chain(Some(0))+ .collect();+ let bytes = std::slice::from_raw_parts(command.as_ptr().cast(), command.len() * 2);+ RegSetValueExW(key, &HSTRING::from(VALUE_NAME), None, REG_SZ, Some(bytes))+ }+ None => match RegDeleteValueW(key, &HSTRING::from(VALUE_NAME)) {+ // Removing a value that does not exist is not an error.+ WIN32_ERROR(2) => WIN32_ERROR(0),+ other => other,+ },+ };+ let _ = RegCloseKey(key);+ result.ok()+ }+}++/// `true` if Muelle is registered to start when the user signs in.+#[must_use]+pub fn is_enabled() -> bool {+ use windows::Win32::System::Registry::{RRF_RT_REG_SZ, RegGetValueW};+ // SAFETY: Only asks whether the value exists; no buffers are passed.+ unsafe {+ RegGetValueW(+ HKEY_CURRENT_USER,+ w!(r"Software\Microsoft\Windows\CurrentVersion\Run"),+ &HSTRING::from(VALUE_NAME),+ RRF_RT_REG_SZ,+ None,+ None,+ None,+ )+ .is_ok()+ }+}diff --git a/crates/muelle-shell/src/dock_link.rs b/crates/muelle-shell/src/dock_link.rsnew file mode 100644index 0000000..8d58d76--- /dev/null+++ b/crates/muelle-shell/src/dock_link.rs@@ -0,0 +1,25 @@+//! How other Muelle processes talk to the running dock.++use windows::{+ Win32::{+ Foundation::{LPARAM, WPARAM},+ UI::WindowsAndMessaging::{FindWindowW, PostMessageW, RegisterWindowMessageW},+ },+ core::{PCWSTR, w},+};++pub const DOCK_WINDOW_CLASS: PCWSTR = w!("MuelleWindow");+/// Name of the registered window message meaning "the configuration file changed".+pub const CONFIG_CHANGED: PCWSTR = w!("Muelle.ConfigChanged");++/// Tells the dock, if it is running, to reload its configuration. A window+/// message instead of a file watcher: the dock spends nothing while idle.+pub fn notify_config_changed() {+ // SAFETY: Looks up a window and posts a message without associated data.+ unsafe {+ if let Ok(dock) = FindWindowW(DOCK_WINDOW_CLASS, None) {+ let message = RegisterWindowMessageW(CONFIG_CHANGED);+ let _ = PostMessageW(Some(dock), message, WPARAM(0), LPARAM(0));+ }+ }+}diff --git a/crates/muelle-shell/src/files.rs b/crates/muelle-shell/src/files.rsnew file mode 100644index 0000000..d4a0295--- /dev/null+++ b/crates/muelle-shell/src/files.rs@@ -0,0 +1,86 @@+//! Shell file operations with the standard Windows progress, confirmation,+//! and undo behavior.++use windows::{+ Win32::{+ Foundation::HWND,+ UI::Shell::{+ FO_COPY, FO_DELETE, FO_MOVE, FOF_ALLOWUNDO, SHFILEOPSTRUCTW, SHFileOperationW,+ },+ },+ core::PCWSTR,+};++/// Sends files to the recycle bin.+pub fn recycle(owner: HWND, files: &[String]) {+ run(owner, FO_DELETE, files, None);+}++/// Moves (or copies) files into `folder`.+pub fn transfer(owner: HWND, files: &[String], folder: &str, copy: bool) {+ run(+ owner,+ if copy { FO_COPY } else { FO_MOVE },+ files,+ Some(folder),+ );+}++/// `true` if both paths are on the same volume, where Explorer moves instead of copying.+#[must_use]+pub fn same_volume(a: &str, b: &str) -> bool {+ let root = |path: &str| path.get(..3).map(str::to_ascii_lowercase);+ root(a).is_some() && root(a) == root(b)+}++/// SHFileOperation takes lists of paths separated by and ending in two NULs.+fn path_list<'a>(paths: impl IntoIterator<Item = &'a str>) -> Vec<u16> {+ let mut list: Vec<u16> = Vec::new();+ for path in paths {+ list.extend(path.encode_utf16());+ list.push(0);+ }+ list.push(0);+ list+}++fn run(owner: HWND, operation: u32, files: &[String], destination: Option<&str>) {+ if files.is_empty() {+ return;+ }+ let from = path_list(files.iter().map(String::as_str));+ let to = destination.map(|folder| path_list([folder]));+ let mut request = SHFILEOPSTRUCTW {+ hwnd: owner,+ wFunc: operation,+ pFrom: PCWSTR(from.as_ptr()),+ pTo: to.as_ref().map_or(PCWSTR::null(), |to| PCWSTR(to.as_ptr())),+ fFlags: FOF_ALLOWUNDO.0 as u16,+ ..Default::default()+ };+ // SAFETY: The path buffers outlive the call. Cancelling or failing shows+ // the shell's own message, so the result needs no handling here.+ unsafe {+ let _ = SHFileOperationW(&mut request);+ }+}++#[cfg(test)]+mod tests {+ use super::*;++ #[test]+ fn path_list_should_end_with_two_nuls() {+ assert_eq!(path_list(["a", "b"]), [97, 0, 98, 0, 0]);+ }++ #[test]+ fn same_volume_should_ignore_letter_case() {+ assert!(same_volume(r"c:\Users\x.txt", r"C:\Downloads"));+ }++ #[test]+ fn same_volume_should_detect_different_drives() {+ assert!(!same_volume(r"D:\x.txt", r"C:\Downloads"));+ }+}diff --git a/crates/muelle-shell/src/icon_cache.rs b/crates/muelle-shell/src/icon_cache.rsnew file mode 100644index 0000000..943d08e--- /dev/null+++ b/crates/muelle-shell/src/icon_cache.rs@@ -0,0 +1,202 @@+//! On-disk cache for app icons and names.+//!+//! Getting these from the Windows shell takes 10–250 ms per app (loading shell+//! extensions or opening Store packages); reading them from disk takes under+//! 1 ms. Each entry has a validity stamp:+//! - files use their modification time, which changes when an app is updated;+//! - folders (whose timestamps change whenever a file is added) and shell items+//! without files (Store apps) use the current day, so they are refreshed at+//! most once per day.++use std::{+ env, fs,+ hash::{DefaultHasher, Hash, Hasher},+ path::{Path, PathBuf},+ time::{SystemTime, UNIX_EPOCH},+};++use crate::{+ icons::{IconError, IconImage, load_icon},+ names::display_name,+};++const MAGIC: &[u8; 4] = b"WDI1";+const HEADER_LEN: usize = 4 + 8 + 4 + 4 + 4;+const SECONDS_PER_DAY: u64 = 86_400;++#[derive(Clone, Debug, PartialEq, Eq)]+pub struct AppVisual {+ pub name: String,+ pub icon: IconImage,+}++#[derive(Debug)]+pub struct IconCache {+ folder: PathBuf,+}++impl Default for IconCache {+ fn default() -> Self {+ Self::new(+ PathBuf::from(env::var_os("LOCALAPPDATA").unwrap_or_default())+ .join("Muelle")+ .join("icons"),+ )+ }+}++impl IconCache {+ #[must_use]+ pub fn new(folder: PathBuf) -> Self {+ Self { folder }+ }++ /// Gets the icon (at `size` pixels) and name for `id` from the cache if+ /// valid, or from the shell otherwise, saving the result for next time.+ ///+ /// Requires COM to be initialized on the calling thread.+ pub fn get(&self, id: &str, size: u32) -> Result<AppVisual, IconError> {+ self.get_variant(id, "", size)+ }++ /// Like [`get`](Self::get), but stores each `variant` separately for items+ /// whose icon depends on their state, such as an empty or full recycle bin.+ pub fn get_variant(&self, id: &str, variant: &str, size: u32) -> Result<AppVisual, IconError> {+ let path = self.entry_path(&format!("{id}|{variant}"), size);+ let stamp = stamp_of(id);+ if let Some(cached) = fs::read(&path).ok().and_then(|bytes| decode(&bytes, stamp)) {+ return Ok(cached);+ }++ let visual = AppVisual {+ name: display_name(id),+ icon: load_icon(id, size)?,+ };+ // An unwritable cache only makes the next startup slower.+ let _ = fs::create_dir_all(&self.folder);+ let _ = fs::write(&path, encode(&visual, stamp));+ Ok(visual)+ }++ fn entry_path(&self, id: &str, size: u32) -> PathBuf {+ let mut hasher = DefaultHasher::new();+ id.hash(&mut hasher);+ self.folder+ .join(format!("{:016x}-{size}.bin", hasher.finish()))+ }+}++fn stamp_of(id: &str) -> u64 {+ let since_epoch = |time: SystemTime| {+ time.duration_since(UNIX_EPOCH)+ .map_or(0, |elapsed| elapsed.as_secs())+ };+ match fs::metadata(Path::new(id)) {+ Ok(meta) if meta.is_file() => meta.modified().map_or(0, since_epoch),+ _ => since_epoch(SystemTime::now()) / SECONDS_PER_DAY,+ }+}++fn encode(visual: &AppVisual, stamp: u64) -> Vec<u8> {+ let name = visual.name.as_bytes();+ let mut bytes = Vec::with_capacity(HEADER_LEN + name.len() + visual.icon.bgra.len());+ bytes.extend_from_slice(MAGIC);+ bytes.extend_from_slice(&stamp.to_le_bytes());+ bytes.extend_from_slice(&visual.icon.width.to_le_bytes());+ bytes.extend_from_slice(&visual.icon.height.to_le_bytes());+ bytes.extend_from_slice(&(name.len() as u32).to_le_bytes());+ bytes.extend_from_slice(name);+ bytes.extend_from_slice(&visual.icon.bgra);+ bytes+}++fn decode(bytes: &[u8], expected_stamp: u64) -> Option<AppVisual> {+ let (header, rest) = bytes.split_at_checked(HEADER_LEN)?;+ let (magic, header) = header.split_first_chunk::<4>()?;+ let (stamp, header) = header.split_first_chunk::<8>()?;+ let (width, header) = header.split_first_chunk::<4>()?;+ let (height, header) = header.split_first_chunk::<4>()?;+ let (name_len, _) = header.split_first_chunk::<4>()?;+ if magic != MAGIC || u64::from_le_bytes(*stamp) != expected_stamp {+ return None;+ }++ let (width, height) = (u32::from_le_bytes(*width), u32::from_le_bytes(*height));+ let (name, bgra) = rest.split_at_checked(u32::from_le_bytes(*name_len) as usize)?;+ let pixel_len = (width as usize)+ .checked_mul(height as usize)?+ .checked_mul(4)?;+ if bgra.len() != pixel_len {+ return None;+ }+ Some(AppVisual {+ name: String::from_utf8(name.to_vec()).ok()?,+ icon: IconImage {+ width,+ height,+ bgra: bgra.to_vec(),+ },+ })+}++#[cfg(test)]+mod tests {+ use super::*;++ fn sample() -> AppVisual {+ AppVisual {+ name: "Explorador de Windows".into(),+ icon: IconImage {+ width: 2,+ height: 2,+ bgra: (0..16).collect(),+ },+ }+ }++ #[test]+ fn decode_should_return_what_encode_stored() {+ assert_eq!(decode(&encode(&sample(), 7), 7), Some(sample()));+ }++ #[test]+ fn decode_should_reject_a_stale_entry() {+ assert_eq!(decode(&encode(&sample(), 7), 8), None);+ }++ #[test]+ fn decode_should_reject_a_truncated_entry() {+ let bytes = encode(&sample(), 7);+ assert_eq!(decode(&bytes[..bytes.len() - 1], 7), None);+ }++ #[test]+ fn decode_should_reject_another_format() {+ let mut bytes = encode(&sample(), 7);+ bytes[0] = b'X';+ assert_eq!(decode(&bytes, 7), None);+ }++ #[test]+ fn decode_should_reject_dimensions_that_overflow() {+ let mut bytes = encode(&sample(), 7);+ bytes[12..16].copy_from_slice(&u32::MAX.to_le_bytes());+ bytes[16..20].copy_from_slice(&u32::MAX.to_le_bytes());+ assert_eq!(decode(&bytes, 7), None);+ }++ #[test]+ fn stamp_of_should_follow_file_modification_time() {+ let file = env::temp_dir().join(format!("muelle-stamp-{}", std::process::id()));+ let _ = fs::write(&file, b"x");+ let expected = fs::metadata(&file)+ .and_then(|meta| meta.modified())+ .map_or(0, |time| {+ time.duration_since(UNIX_EPOCH)+ .map_or(0, |elapsed| elapsed.as_secs())+ });+ let stamp = stamp_of(&file.to_string_lossy());+ let _ = fs::remove_file(&file);+ assert_eq!(stamp, expected);+ }+}diff --git a/crates/muelle-shell/src/icons.rs b/crates/muelle-shell/src/icons.rsnew file mode 100644index 0000000..4483378--- /dev/null+++ b/crates/muelle-shell/src/icons.rs@@ -0,0 +1,128 @@+use std::mem::size_of;++use thiserror::Error;+use windows::{+ Win32::{+ Foundation::SIZE,+ Graphics::Gdi::{+ BI_RGB, BITMAP, BITMAPINFO, BITMAPINFOHEADER, DIB_RGB_COLORS, DeleteObject, GetDC,+ GetDIBits, GetObjectW, HBITMAP, ReleaseDC,+ },+ UI::Shell::{IShellItemImageFactory, SHCreateItemFromParsingName, SIIGBF_ICONONLY},+ },+ core::HSTRING,+};++#[derive(Debug, Error)]+pub enum IconError {+ #[error("el shell no pudo generar el icono de `{name}`")]+ Shell {+ name: String,+ #[source]+ source: windows::core::Error,+ },+ #[error("no se pudieron leer los píxeles del icono de `{0}`")]+ Pixels(String),+}++/// Square BGRA icon with premultiplied alpha and top-to-bottom rows.+#[derive(Clone, Debug, PartialEq, Eq)]+pub struct IconImage {+ pub width: u32,+ pub height: u32,+ pub bgra: Vec<u8>,+}++struct OwnedBitmap(HBITMAP);++impl Drop for OwnedBitmap {+ fn drop(&mut self) {+ // SAFETY: This HBITMAP is owned by us (returned by GetImage) and is not used afterward.+ unsafe {+ let _ = DeleteObject(self.0.into());+ }+ }+}++pub fn load_icon(parsing_name: &str, size: u32) -> Result<IconImage, IconError> {+ let shell_error = |source| IconError::Shell {+ name: parsing_name.to_owned(),+ source,+ };+ let side = size as i32;++ // SAFETY: The strings and structures passed to each call remain alive for its duration.+ let bitmap = unsafe {+ let factory: IShellItemImageFactory =+ SHCreateItemFromParsingName(&HSTRING::from(parsing_name), None).map_err(shell_error)?;+ OwnedBitmap(+ factory+ .GetImage(SIZE { cx: side, cy: side }, SIIGBF_ICONONLY)+ .map_err(shell_error)?,+ )+ };++ read_pixels(&bitmap).ok_or_else(|| IconError::Pixels(parsing_name.to_owned()))+}++fn read_pixels(bitmap: &OwnedBitmap) -> Option<IconImage> {+ let mut desc = BITMAP::default();+ // SAFETY: `desc` has the size specified in its size field.+ let written = unsafe {+ GetObjectW(+ bitmap.0.into(),+ size_of::<BITMAP>() as i32,+ Some((&raw mut desc).cast()),+ )+ };+ if written == 0 || desc.bmWidth <= 0 || desc.bmHeight <= 0 {+ return None;+ }+ let (width, height) = (desc.bmWidth as u32, desc.bmHeight as u32);++ let mut info = BITMAPINFO {+ bmiHeader: BITMAPINFOHEADER {+ biSize: size_of::<BITMAPINFOHEADER>() as u32,+ biWidth: desc.bmWidth,+ // A negative height specifies top-down rows.+ biHeight: -desc.bmHeight,+ biPlanes: 1,+ biBitCount: 32,+ biCompression: BI_RGB.0,+ ..Default::default()+ },+ ..Default::default()+ };+ let mut bgra = vec![0u8; (width * height * 4) as usize];+ // SAFETY: The buffer has `width * height * 4` bytes, the amount GetDIBits writes at 32 bpp.+ let lines = unsafe {+ let dc = GetDC(None);+ let lines = GetDIBits(+ dc,+ bitmap.0,+ 0,+ height,+ Some(bgra.as_mut_ptr().cast()),+ &mut info,+ DIB_RGB_COLORS,+ );+ ReleaseDC(None, dc);+ lines+ };+ if lines == 0 {+ return None;+ }++ // Legacy icons without an alpha channel have an alpha value of 0 for every pixel.+ if bgra.as_chunks::<4>().0.iter().all(|px| px[3] == 0) {+ bgra.as_chunks_mut::<4>()+ .0+ .iter_mut()+ .for_each(|px| px[3] = 255);+ }+ Some(IconImage {+ width,+ height,+ bgra,+ })+}diff --git a/crates/muelle-shell/src/launcher.rs b/crates/muelle-shell/src/launcher.rsnew file mode 100644index 0000000..35ab465--- /dev/null+++ b/crates/muelle-shell/src/launcher.rs@@ -0,0 +1,162 @@+use thiserror::Error;+use windows::{+ Win32::{+ Foundation::{HWND, LPARAM, WPARAM},+ UI::{+ Input::KeyboardAndMouse::{+ INPUT, INPUT_0, INPUT_KEYBOARD, KEYBD_EVENT_FLAGS, KEYBDINPUT, KEYEVENTF_KEYUP,+ SendInput, VK_LWIN,+ },+ Shell::ShellExecuteW,+ WindowsAndMessaging::{+ HWND_TOP, IsIconic, PostMessageW, SW_RESTORE, SW_SHOWNORMAL, SWP_NOACTIVATE,+ SWP_NOMOVE, SWP_NOSIZE, SetForegroundWindow, SetWindowPos, ShowWindow, WM_CLOSE,+ },+ },+ },+ core::{HSTRING, w},+};++#[derive(Debug, Error)]+#[error("no se pudo abrir `{id}` (código {code} del shell)")]+pub struct LaunchError {+ id: String,+ code: isize,+}++pub fn open(id: &str) -> Result<(), LaunchError> {+ // SAFETY: The strings live for the duration of the call.+ let result = unsafe {+ ShellExecuteW(+ None,+ w!("open"),+ &HSTRING::from(id),+ None,+ None,+ SW_SHOWNORMAL,+ )+ };+ // ShellExecute returns a value greater than 32 on success.+ let code = result.0 as isize;+ if code > 32 {+ Ok(())+ } else {+ Err(LaunchError {+ id: id.to_owned(),+ code,+ })+ }+}++/// Opens `files` with the executable `app`.+pub fn open_with(app: &str, files: &[String]) -> Result<(), LaunchError> {+ let arguments: Vec<String> = files.iter().map(|file| format!("\"{file}\"")).collect();+ // SAFETY: The strings live for the duration of the call.+ let result = unsafe {+ ShellExecuteW(+ None,+ w!("open"),+ &HSTRING::from(app),+ &HSTRING::from(arguments.join(" ")),+ None,+ SW_SHOWNORMAL,+ )+ };+ let code = result.0 as isize;+ if code > 32 {+ Ok(())+ } else {+ Err(LaunchError {+ id: app.to_owned(),+ code,+ })+ }+}++/// Opens the Windows Start menu, exactly as the Windows key does.+pub fn open_start_menu() {+ let key = |flags: KEYBD_EVENT_FLAGS| INPUT {+ r#type: INPUT_KEYBOARD,+ Anonymous: INPUT_0 {+ ki: KEYBDINPUT {+ wVk: VK_LWIN,+ dwFlags: flags,+ ..Default::default()+ },+ },+ };+ let inputs = [key(KEYBD_EVENT_FLAGS(0)), key(KEYEVENTF_KEYUP)];+ // SAFETY: The array lives for the duration of the call.+ unsafe {+ SendInput(&inputs, size_of::<INPUT>() as i32);+ }+}++pub fn reveal(path: &str) -> Result<(), LaunchError> {+ let arguments = HSTRING::from(format!("/select,\"{path}\""));+ // SAFETY: The strings live for the duration of the call.+ let result = unsafe {+ ShellExecuteW(+ None,+ w!("open"),+ w!("explorer.exe"),+ &arguments,+ None,+ SW_SHOWNORMAL,+ )+ };+ let code = result.0 as isize;+ if code > 32 {+ Ok(())+ } else {+ Err(LaunchError {+ id: path.to_owned(),+ code,+ })+ }+}++/// Asks the windows to close, as the close button does; each app can prompt+/// the user to save changes.+pub fn close(windows: &[isize]) {+ for &hwnd in windows {+ // SAFETY: Only a message is sent; if the window no longer exists, the call has no effect.+ unsafe {+ let _ = PostMessageW(Some(HWND(hwnd as *mut _)), WM_CLOSE, WPARAM(0), LPARAM(0));+ }+ }+}++/// Brings an app's windows to the foreground. `windows` is ordered from front+/// to back; the first window receives focus.+///+/// If all windows are minimized, restores only the first one, as macOS does.+pub fn activate(windows: &[isize]) {+ let handles = || windows.iter().map(|&raw| HWND(raw as *mut _));+ // SAFETY: These operations target other windows; calls on a window that no+ // longer exists fail without further effect.+ unsafe {+ // Process from back to front to preserve their relative order.+ for hwnd in handles().rev().filter(|&hwnd| !IsIconic(hwnd).as_bool()) {+ let _ = SetWindowPos(+ hwnd,+ Some(HWND_TOP),+ 0,+ 0,+ 0,+ 0,+ SWP_NOMOVE | SWP_NOSIZE | SWP_NOACTIVATE,+ );+ }+ let Some(front) = handles()+ .find(|&hwnd| !IsIconic(hwnd).as_bool())+ .or_else(|| handles().next())+ else {+ return;+ };+ if IsIconic(front).as_bool() {+ let _ = ShowWindow(front, SW_RESTORE);+ }+ let _ = SetForegroundWindow(front);+ }+}diff --git a/crates/muelle-shell/src/lib.rs b/crates/muelle-shell/src/lib.rsnew file mode 100644index 0000000..e0634d1--- /dev/null+++ b/crates/muelle-shell/src/lib.rs@@ -0,0 +1,15 @@+pub mod appbar;+pub mod autostart;+pub mod dock_link;+pub mod files;+pub mod icon_cache;+pub mod icons;+pub mod launcher;+pub mod names;+pub mod pins;+pub mod power;+pub mod recycle_bin;+pub mod screen;+pub mod system;+pub mod taskbar;+pub mod tracker;diff --git a/crates/muelle-shell/src/names.rs b/crates/muelle-shell/src/names.rsnew file mode 100644index 0000000..4b56c09--- /dev/null+++ b/crates/muelle-shell/src/names.rs@@ -0,0 +1,82 @@+//! Human-readable names for apps or shell items, used in dock labels.++use std::{ffi::c_void, path::Path};++use windows::{+ Win32::{+ Storage::FileSystem::{GetFileVersionInfoSizeW, GetFileVersionInfoW, VerQueryValueW},+ System::Com::CoTaskMemFree,+ UI::Shell::{IShellItem, SHCreateItemFromParsingName, SIGDN_NORMALDISPLAY},+ },+ core::{HSTRING, PCWSTR, w},+};++/// Display name: the executable description (for example, "Visual Studio Code"),+/// otherwise the shell name (for example, "Recycle Bin"), or finally the file+/// name without its extension.+///+/// Requires COM to be initialized on the calling thread.+#[must_use]+pub fn display_name(parsing_name: &str) -> String {+ file_description(parsing_name)+ .or_else(|| shell_name(parsing_name))+ .map(|name| name.trim().trim_end_matches(".exe").to_owned())+ .filter(|name| !name.is_empty())+ .unwrap_or_else(|| {+ Path::new(parsing_name).file_stem().map_or_else(+ || parsing_name.to_owned(),+ |stem| stem.to_string_lossy().into_owned(),+ )+ })+}++fn file_description(path: &str) -> Option<String> {+ let path = HSTRING::from(path);+ // SAFETY: The buffer has the size requested by the API, and pointers+ // returned by VerQueryValueW refer to it while it remains alive.+ unsafe {+ let size = GetFileVersionInfoSizeW(&path, None);+ if size == 0 {+ return None;+ }+ let mut data = vec![0u8; size as usize];+ GetFileVersionInfoW(&path, None, size, data.as_mut_ptr().cast()).ok()?;++ let mut value: *mut c_void = std::ptr::null_mut();+ let mut len = 0u32;+ let found = VerQueryValueW(+ data.as_ptr().cast(),+ w!("\\VarFileInfo\\Translation"),+ &mut value,+ &mut len,+ );+ if !found.as_bool() || len < 4 {+ return None;+ }+ // Each translation is a pair of 16-bit language and code-page values.+ let pair = std::slice::from_raw_parts(value.cast::<u16>(), 2);+ let key = HSTRING::from(format!(+ "\\StringFileInfo\\{:04x}{:04x}\\FileDescription",+ pair[0], pair[1]+ ));++ let found = VerQueryValueW(data.as_ptr().cast(), &key, &mut value, &mut len);+ if !found.as_bool() || len == 0 {+ return None;+ }+ PCWSTR(value.cast()).to_string().ok()+ }+}++fn shell_name(parsing_name: &str) -> Option<String> {+ // SAFETY: The shell-returned string is copied and then freed with+ // the allocator that created it.+ unsafe {+ let item: IShellItem =+ SHCreateItemFromParsingName(&HSTRING::from(parsing_name), None).ok()?;+ let raw = item.GetDisplayName(SIGDN_NORMALDISPLAY).ok()?;+ let name = raw.to_string().ok();+ CoTaskMemFree(Some(raw.as_ptr().cast()));+ name+ }+}diff --git a/crates/muelle-shell/src/pins.rs b/crates/muelle-shell/src/pins.rsnew file mode 100644index 0000000..cb547de--- /dev/null+++ b/crates/muelle-shell/src/pins.rs@@ -0,0 +1,65 @@+use std::{env, fs, path::PathBuf};++use windows::{+ Win32::{+ System::Com::{CLSCTX_INPROC_SERVER, CoCreateInstance, IPersistFile, STGM_READ},+ UI::Shell::{IShellLinkW, ShellLink},+ },+ core::{HSTRING, Interface},+};++use crate::tracker::normalize_id;++/// Limitations: results are alphabetized by shortcut (the actual taskbar order+/// uses an undocumented binary format), and Store apps are omitted because+/// Windows stores them elsewhere.+///+/// Requires COM to be initialized on the calling thread.+#[must_use]+pub fn taskbar_pins() -> Vec<String> {+ let Ok(appdata) = env::var("APPDATA") else {+ return Vec::new();+ };+ let folder = PathBuf::from(appdata)+ .join("Microsoft\\Internet Explorer\\Quick Launch\\User Pinned\\TaskBar");+ let Ok(entries) = fs::read_dir(folder) else {+ return Vec::new();+ };++ let mut links: Vec<PathBuf> = entries+ .filter_map(|entry| Some(entry.ok()?.path()))+ .filter(|path| {+ path.extension()+ .is_some_and(|ext| ext.eq_ignore_ascii_case("lnk"))+ })+ .collect();+ links.sort();++ let mut pins: Vec<String> = Vec::new();+ for target in links.iter().filter_map(|link| link_target(link)) {+ let id = normalize_id(&target);+ if id.ends_with(".exe") && PathBuf::from(&id).exists() && !pins.contains(&id) {+ pins.push(id);+ }+ }+ pins+}++pub fn link_target(link: &std::path::Path) -> Option<String> {+ // SAFETY: COM calls use buffers and strings that remain alive for the duration of each call.+ unsafe {+ let shell_link: IShellLinkW =+ CoCreateInstance(&ShellLink, None, CLSCTX_INPROC_SERVER).ok()?;+ shell_link+ .cast::<IPersistFile>()+ .ok()?+ .Load(&HSTRING::from(link.as_os_str()), STGM_READ)+ .ok()?;+ let mut buffer = [0u16; 1024];+ shell_link+ .GetPath(&mut buffer, std::ptr::null_mut(), 0)+ .ok()?;+ let len = buffer.iter().position(|&unit| unit == 0)?;+ (len > 0).then(|| String::from_utf16_lossy(&buffer[..len]))+ }+}diff --git a/crates/muelle-shell/src/power.rs b/crates/muelle-shell/src/power.rsnew file mode 100644index 0000000..fea614c--- /dev/null+++ b/crates/muelle-shell/src/power.rs@@ -0,0 +1,85 @@+//! Power and memory usage (plan section 8).+//!+//! - **EcoQoS** (Windows 11 efficiency mode): the scheduler runs the thread on+//! efficiency cores at a lower frequency. This suits background dock work+//! (window tracking and recomposition), but not animations, so it is toggled+//! as needed.+//! - **Memory trimming**: an idle dock rarely touches most of its pages, so+//! returning them to the system frees RAM for other apps. If needed again,+//! they can be restored from the standby list in microseconds.++use std::{ffi::c_void, mem::size_of};++use windows::Win32::System::{+ ProcessStatus::EmptyWorkingSet,+ Threading::{+ GetCurrentProcess, GetCurrentThread, IDLE_PRIORITY_CLASS, MEMORY_PRIORITY_INFORMATION,+ MEMORY_PRIORITY_LOW, PROCESS_POWER_THROTTLING_CURRENT_VERSION,+ PROCESS_POWER_THROTTLING_EXECUTION_SPEED, PROCESS_POWER_THROTTLING_STATE,+ ProcessMemoryPriority, ProcessPowerThrottling, SetPriorityClass, SetProcessInformation,+ SetThreadInformation, THREAD_POWER_THROTTLING_CURRENT_VERSION,+ THREAD_POWER_THROTTLING_EXECUTION_SPEED, THREAD_POWER_THROTTLING_STATE,+ ThreadPowerThrottling,+ },+};++pub fn set_thread_efficiency(enabled: bool) {+ let state = THREAD_POWER_THROTTLING_STATE {+ Version: THREAD_POWER_THROTTLING_CURRENT_VERSION,+ ControlMask: THREAD_POWER_THROTTLING_EXECUTION_SPEED,+ StateMask: if enabled {+ THREAD_POWER_THROTTLING_EXECUTION_SPEED+ } else {+ 0+ },+ };+ // SAFETY: The structure has its size initialized; if unsupported, the call+ // fails without effect.+ unsafe {+ let _ = SetThreadInformation(+ GetCurrentThread(),+ ThreadPowerThrottling,+ (&raw const state).cast::<c_void>(),+ size_of::<THREAD_POWER_THROTTLING_STATE>() as u32,+ );+ }+}++pub fn trim_memory() {+ // SAFETY: Trims this process's own working set.+ unsafe {+ let _ = EmptyWorkingSet(GetCurrentProcess());+ }+}++/// Configures a process that only waits (the watchdog) with EcoQoS, minimum+/// CPU priority, and low-priority memory that the system can reclaim first.+pub fn run_as_background_process() {+ let throttling = PROCESS_POWER_THROTTLING_STATE {+ Version: PROCESS_POWER_THROTTLING_CURRENT_VERSION,+ ControlMask: PROCESS_POWER_THROTTLING_EXECUTION_SPEED,+ StateMask: PROCESS_POWER_THROTTLING_EXECUTION_SPEED,+ };+ let memory = MEMORY_PRIORITY_INFORMATION {+ MemoryPriority: MEMORY_PRIORITY_LOW,+ };+ // SAFETY: The structures have their sizes initialized and target this+ // process; a failure leaves the default settings unchanged.+ unsafe {+ let process = GetCurrentProcess();+ let _ = SetProcessInformation(+ process,+ ProcessPowerThrottling,+ (&raw const throttling).cast::<c_void>(),+ size_of::<PROCESS_POWER_THROTTLING_STATE>() as u32,+ );+ let _ = SetProcessInformation(+ process,+ ProcessMemoryPriority,+ (&raw const memory).cast::<c_void>(),+ size_of::<MEMORY_PRIORITY_INFORMATION>() as u32,+ );+ let _ = SetPriorityClass(process, IDLE_PRIORITY_CLASS);+ }+ trim_memory();+}diff --git a/crates/muelle-shell/src/recycle_bin.rs b/crates/muelle-shell/src/recycle_bin.rsnew file mode 100644index 0000000..23404a2--- /dev/null+++ b/crates/muelle-shell/src/recycle_bin.rs@@ -0,0 +1,77 @@+use std::mem::size_of;++use windows::Win32::{+ Foundation::HWND,+ UI::Shell::{+ Common::ITEMIDLIST, FOLDERID_RecycleBinFolder, KF_FLAG_DEFAULT, SHCNE_CREATE, SHCNE_DELETE,+ SHCNE_RENAMEITEM, SHCNE_UPDATEDIR, SHCNE_UPDATEIMAGE, SHCNE_UPDATEITEM,+ SHCNRF_InterruptLevel, SHCNRF_ShellLevel, SHChangeNotifyDeregister, SHChangeNotifyEntry,+ SHChangeNotifyRegister, SHEmptyRecycleBinW, SHGetKnownFolderIDList, SHQUERYRBINFO,+ SHQueryRecycleBinW,+ },+};++pub const PARSING_NAME: &str = "::{645FF040-5081-101B-9F08-00AA002F954E}";++#[must_use]+pub fn has_items() -> bool {+ let mut info = SHQUERYRBINFO {+ cbSize: size_of::<SHQUERYRBINFO>() as u32,+ ..Default::default()+ };+ // SAFETY: The structure has its size initialized; `None` means all drives.+ unsafe { SHQueryRecycleBinW(None, &mut info) }.is_ok() && info.i64NumItems > 0+}++/// Empties the recycle bin using the native confirmation and progress UI.+pub fn empty(owner: HWND) {+ // SAFETY: `owner` is an optional owner window; cancellation is handled by the shell.+ unsafe {+ let _ = SHEmptyRecycleBinW(Some(owner), None, 0);+ }+}++pub struct BinWatch(u32);++impl BinWatch {+ /// Sends `message` to `hwnd` whenever the recycle bin contents change.+ /// Notifications arrive in bursts, so receivers should coalesce them.+ #[must_use]+ pub fn register(hwnd: HWND, message: u32) -> Option<Self> {+ // SAFETY: The identifier list is valid for this registration call, which copies it.+ unsafe {+ let pidl: *mut ITEMIDLIST =+ SHGetKnownFolderIDList(&FOLDERID_RecycleBinFolder, KF_FLAG_DEFAULT.0 as u32, None)+ .ok()?;+ let entry = SHChangeNotifyEntry {+ pidl,+ fRecursive: true.into(),+ };+ let events = SHCNE_CREATE+ | SHCNE_DELETE+ | SHCNE_RENAMEITEM+ | SHCNE_UPDATEDIR+ | SHCNE_UPDATEITEM+ | SHCNE_UPDATEIMAGE;+ let id = SHChangeNotifyRegister(+ hwnd,+ SHCNRF_ShellLevel | SHCNRF_InterruptLevel,+ events.0 as i32,+ message,+ 1,+ &entry,+ );+ windows::Win32::System::Com::CoTaskMemFree(Some(pidl.cast()));+ (id != 0).then_some(Self(id))+ }+ }+}++impl Drop for BinWatch {+ fn drop(&mut self) {+ // SAFETY: `self.0` is a valid registration returned by SHChangeNotifyRegister.+ unsafe {+ let _ = SHChangeNotifyDeregister(self.0);+ }+ }+}diff --git a/crates/muelle-shell/src/screen.rs b/crates/muelle-shell/src/screen.rsnew file mode 100644index 0000000..fdfbbc5--- /dev/null+++ b/crates/muelle-shell/src/screen.rs@@ -0,0 +1,82 @@+//! Copying a rectangle of the composed desktop.++use std::{ffi::c_void, mem::size_of};++use windows::Win32::{+ Foundation::RECT,+ Graphics::Gdi::{+ BI_RGB, BITMAPINFO, BITMAPINFOHEADER, BitBlt, CAPTUREBLT, CreateCompatibleDC,+ CreateDIBSection, DIB_RGB_COLORS, DeleteDC, DeleteObject, GetDC, ReleaseDC, SRCCOPY,+ SelectObject,+ },+};++use crate::icons::IconImage;++/// Captures `rect` (screen coordinates) as opaque BGRA pixels, top row first.+#[must_use]+pub fn capture(rect: RECT) -> Option<IconImage> {+ let (width, height) = (rect.right - rect.left, rect.bottom - rect.top);+ if width <= 0 || height <= 0 {+ return None;+ }+ let info = BITMAPINFO {+ bmiHeader: BITMAPINFOHEADER {+ biSize: size_of::<BITMAPINFOHEADER>() as u32,+ biWidth: width,+ // Negative height: top-down rows.+ biHeight: -height,+ biPlanes: 1,+ biBitCount: 32,+ biCompression: BI_RGB.0,+ ..Default::default()+ },+ ..Default::default()+ };+ // SAFETY: Every GDI object created here is released before returning, and+ // `bits` points to `width * height * 4` bytes owned by the DIB section+ // while it is alive.+ unsafe {+ let screen = GetDC(None);+ let memory = CreateCompatibleDC(Some(screen));+ let mut bits: *mut c_void = std::ptr::null_mut();+ let bitmap = CreateDIBSection(Some(screen), &info, DIB_RGB_COLORS, &mut bits, None, 0);+ let image = match bitmap {+ Ok(bitmap) if !bits.is_null() => {+ let previous = SelectObject(memory, bitmap.into());+ let copied = BitBlt(+ memory,+ 0,+ 0,+ width,+ height,+ Some(screen),+ rect.left,+ rect.top,+ SRCCOPY | CAPTUREBLT,+ );+ let image = copied.is_ok().then(|| {+ let len = (width * height * 4) as usize;+ let mut bgra = std::slice::from_raw_parts(bits.cast::<u8>(), len).to_vec();+ // GDI leaves the alpha byte undefined.+ bgra.as_chunks_mut::<4>()+ .0+ .iter_mut()+ .for_each(|pixel| pixel[3] = 255);+ IconImage {+ width: width as u32,+ height: height as u32,+ bgra,+ }+ });+ SelectObject(memory, previous);+ let _ = DeleteObject(bitmap.into());+ image+ }+ _ => None,+ };+ let _ = DeleteDC(memory);+ ReleaseDC(None, screen);+ image+ }+}diff --git a/crates/muelle-shell/src/system.rs b/crates/muelle-shell/src/system.rsnew file mode 100644index 0000000..51a9f3e--- /dev/null+++ b/crates/muelle-shell/src/system.rs@@ -0,0 +1,129 @@+use std::mem::size_of;++use windows::{+ Win32::{+ Foundation::{POINT, RECT},+ Graphics::Gdi::{GetMonitorInfoW, MONITOR_DEFAULTTOPRIMARY, MONITORINFO, MonitorFromPoint},+ System::Com::CoTaskMemFree,+ System::Registry::{HKEY_CURRENT_USER, RRF_RT_REG_DWORD, RegGetValueW},+ UI::{+ HiDpi::{GetDpiForMonitor, MDT_EFFECTIVE_DPI},+ Shell::{FOLDERID_Downloads, KF_FLAG_DEFAULT, SHGetKnownFolderPath},+ WindowsAndMessaging::{SPI_GETCLIENTAREAANIMATION, SystemParametersInfoW},+ },+ },+ core::{BOOL, w},+};++/// Returns `true` if Windows uses the light theme for the taskbar and shell.+///+/// Assumes the dark theme on read failure (the Windows 11 shell default).+#[must_use]+pub fn uses_light_theme() -> bool {+ let mut value = 0u32;+ let mut size = size_of::<u32>() as u32;+ // SAFETY: `value` and `size` describe a valid 4-byte buffer.+ let status = unsafe {+ RegGetValueW(+ HKEY_CURRENT_USER,+ w!("Software\\Microsoft\\Windows\\CurrentVersion\\Themes\\Personalize"),+ w!("SystemUsesLightTheme"),+ RRF_RT_REG_DWORD,+ None,+ Some((&raw mut value).cast()),+ Some(&mut size),+ )+ };+ status.is_ok() && value != 0+}++/// Monitor bounds, work area, and scale in physical pixels.+#[derive(Clone, Copy, Debug, PartialEq)]+pub struct Monitor {+ /// Full-screen bounds.+ pub screen: RECT,+ pub work_left: i32,+ pub work_top: i32,+ pub work_right: i32,+ pub work_bottom: i32,+ /// 1.0 = 96 DPI (100%).+ pub scale: f32,+}++/// Primary monitor. `None` only if Windows cannot describe it.+#[must_use]+pub fn primary_monitor() -> Option<Monitor> {+ // SAFETY: Read-only queries using correctly sized structures.+ unsafe {+ let handle = MonitorFromPoint(POINT::default(), MONITOR_DEFAULTTOPRIMARY);+ let mut info = MONITORINFO {+ cbSize: size_of::<MONITORINFO>() as u32,+ ..Default::default()+ };+ if !GetMonitorInfoW(handle, &mut info).as_bool() {+ return None;+ }+ let (mut dpi_x, mut dpi_y) = (96u32, 96u32);+ // Fall back to 96 DPI.+ let _ = GetDpiForMonitor(handle, MDT_EFFECTIVE_DPI, &mut dpi_x, &mut dpi_y);+ Some(Monitor {+ screen: info.rcMonitor,+ work_left: info.rcWork.left,+ work_top: info.rcWork.top,+ work_right: info.rcWork.right,+ work_bottom: info.rcWork.bottom,+ scale: dpi_x as f32 / 96.0,+ })+ }+}++/// Path to the user's Downloads folder, which may be on another drive.+#[must_use]+pub fn downloads_folder() -> Option<String> {+ // SAFETY: The returned string is copied and freed with the allocator that created it.+ unsafe {+ let raw = SHGetKnownFolderPath(&FOLDERID_Downloads, KF_FLAG_DEFAULT, None).ok()?;+ let path = raw.to_string().ok();+ CoTaskMemFree(Some(raw.as_ptr().cast()));+ path+ }+}++#[must_use]+pub fn ui_language_is_spanish() -> bool {+ const LANG_SPANISH: u16 = 0x0A;+ // SAFETY: Read-only query.+ let language = unsafe { windows::Win32::Globalization::GetUserDefaultUILanguage() };+ language & 0x3FF == LANG_SPANISH+}++/// `false` if the user turned off "Animation effects" in Windows settings.+#[must_use]+pub fn animations_enabled() -> bool {+ let mut enabled = BOOL::from(true);+ // SAFETY: `enabled` is a valid BOOL the call writes to.+ unsafe {+ let _ = SystemParametersInfoW(+ SPI_GETCLIENTAREAANIMATION,+ 0,+ Some((&raw mut enabled).cast()),+ Default::default(),+ );+ }+ enabled.as_bool()+}++/// Enables or disables the DWM transitions (minimize, maximize, close+/// animations) of one window. It works across processes.+pub fn set_window_transitions(hwnd: isize, enabled: bool) {+ let disabled = BOOL::from(!enabled);+ // SAFETY: The value outlives the call; a window that has closed makes it fail harmlessly.+ unsafe {+ let _ = windows::Win32::Graphics::Dwm::DwmSetWindowAttribute(+ windows::Win32::Foundation::HWND(hwnd as *mut _),+ windows::Win32::Graphics::Dwm::DWMWA_TRANSITIONS_FORCEDISABLED,+ (&raw const disabled).cast(),+ size_of::<BOOL>() as u32,+ );+ }+}diff --git a/crates/muelle-shell/src/taskbar.rs b/crates/muelle-shell/src/taskbar.rsnew file mode 100644index 0000000..0f325d1--- /dev/null+++ b/crates/muelle-shell/src/taskbar.rs@@ -0,0 +1,127 @@+//! Hides the Windows taskbar while the dock is active and restores its previous state.+//!+//! Auto-hide (which frees the work area) is combined with making the taskbar+//! window invisible and click-through. `ShowWindow(SW_HIDE)` does not work on+//! Windows 11 because Explorer shows the taskbar again.+//!+//! The original auto-hide setting is saved the first time the taskbar is taken+//! over and deleted only when it is restored. If the dock exits unexpectedly+//! and restarts, its own auto-hide setting is not mistaken for the user's.++use std::{env, fs, mem::size_of, path::PathBuf};++use windows::{+ Win32::{+ Foundation::{COLORREF, HWND, LPARAM},+ UI::{+ Shell::{ABM_GETSTATE, ABM_SETSTATE, ABS_AUTOHIDE, APPBARDATA, SHAppBarMessage},+ WindowsAndMessaging::{+ FindWindowExW, FindWindowW, GWL_EXSTYLE, GetWindowLongPtrW, LWA_ALPHA,+ SetLayeredWindowAttributes, SetWindowLongPtrW, WS_EX_LAYERED, WS_EX_TRANSPARENT,+ },+ },+ },+ core::{PCWSTR, w},+};++const PRIMARY: PCWSTR = w!("Shell_TrayWnd");+const SECONDARY: PCWSTR = w!("Shell_SecondaryTrayWnd");+const GHOST_STYLES: isize = (WS_EX_LAYERED.0 | WS_EX_TRANSPARENT.0) as isize;++fn state_file() -> PathBuf {+ PathBuf::from(env::var_os("LOCALAPPDATA").unwrap_or_default())+ .join("Muelle")+ .join("taskbar-original")+}++/// Hides the taskbar on all monitors.+///+/// Idempotent; can be called again after Explorer restarts or Windows redraws+/// the taskbar.+pub fn take_over() {+ let file = state_file();+ if !file.exists() {+ let original = if autohide_enabled() { "1" } else { "0" };+ if let Some(folder) = file.parent() {+ let _ = fs::create_dir_all(folder);+ }+ if let Err(error) = fs::write(&file, original) {+ // Without a saved value, assume Windows' default: auto-hide disabled.+ eprintln!("muelle: no se pudo guardar el estado de la barra: {error}");+ }+ }+ set_autohide(true);+ for hwnd in taskbars() {+ set_ghost(hwnd, true);+ }+}++/// Restores the taskbar to its state before `take_over`. Has no effect if the+/// dock did not take it over.+pub fn give_back() {+ let file = state_file();+ let Ok(original) = fs::read_to_string(&file) else {+ // No saved state; make sure the taskbar is visible anyway.+ for hwnd in taskbars() {+ set_ghost(hwnd, false);+ }+ return;+ };+ for hwnd in taskbars() {+ set_ghost(hwnd, false);+ }+ set_autohide(original.trim() == "1");+ let _ = fs::remove_file(file);+}++fn taskbars() -> Vec<HWND> {+ let mut found = Vec::new();+ // SAFETY: Read-only calls with valid static strings.+ unsafe {+ if let Ok(hwnd) = FindWindowW(PRIMARY, None) {+ found.push(hwnd);+ }+ let mut previous = None;+ while let Ok(hwnd) = FindWindowExW(None, previous, SECONDARY, None) {+ found.push(hwnd);+ previous = Some(hwnd);+ }+ }+ found+}++fn appbar_data() -> APPBARDATA {+ APPBARDATA {+ cbSize: size_of::<APPBARDATA>() as u32,+ hWnd: taskbars().first().copied().unwrap_or_default(),+ ..Default::default()+ }+}++fn autohide_enabled() -> bool {+ let mut data = appbar_data();+ // SAFETY: `data` is a valid APPBARDATA with its size initialized.+ let state = unsafe { SHAppBarMessage(ABM_GETSTATE, &mut data) };+ state as u32 & ABS_AUTOHIDE != 0+}++fn set_autohide(enabled: bool) {+ let mut data = appbar_data();+ data.lParam = LPARAM(if enabled { ABS_AUTOHIDE as isize } else { 0 });+ // SAFETY: Same as above.+ unsafe { SHAppBarMessage(ABM_SETSTATE, &mut data) };+}++fn set_ghost(hwnd: HWND, ghost: bool) {+ // SAFETY: `hwnd` comes from FindWindow; if the window no longer exists, the calls have no effect.+ unsafe {+ let style = GetWindowLongPtrW(hwnd, GWL_EXSTYLE);+ if ghost {+ SetWindowLongPtrW(hwnd, GWL_EXSTYLE, style | GHOST_STYLES);+ let _ = SetLayeredWindowAttributes(hwnd, COLORREF(0), 0, LWA_ALPHA);+ } else if style & GHOST_STYLES != 0 {+ let _ = SetLayeredWindowAttributes(hwnd, COLORREF(0), 255, LWA_ALPHA);+ SetWindowLongPtrW(hwnd, GWL_EXSTYLE, style & !GHOST_STYLES);+ }+ }+}diff --git a/crates/muelle-shell/src/tracker.rs b/crates/muelle-shell/src/tracker.rsnew file mode 100644index 0000000..871244a--- /dev/null+++ b/crates/muelle-shell/src/tracker.rs@@ -0,0 +1,292 @@+//! Open windows and the apps they belong to.+//!+//! An app identifier is a shell name that can be opened and resolved to an icon+//! and display name: the lowercase executable path or, for packaged (Store) apps,+//! `shell:AppsFolder\<AppUserModelID>`.++use std::collections::HashMap;++use windows::{+ Win32::{+ Foundation::{CloseHandle, HWND, LPARAM, RECT},+ Graphics::Dwm::{DWMWA_CLOAKED, DwmGetWindowAttribute},+ Storage::{+ EnhancedStorage::PKEY_AppUserModel_ID, Packaging::Appx::GetApplicationUserModelId,+ },+ System::Threading::{+ GetCurrentProcessId, OpenProcess, PROCESS_NAME_WIN32,+ PROCESS_QUERY_LIMITED_INFORMATION, QueryFullProcessImageNameW,+ },+ UI::{+ Shell::PropertiesSystem::{IPropertyStore, SHGetPropertyStoreForWindow},+ WindowsAndMessaging::{+ EnumWindows, GW_OWNER, GWL_EXSTYLE, GetClassNameW, GetForegroundWindow, GetWindow,+ GetWindowLongW, GetWindowPlacement, GetWindowRect, GetWindowTextLengthW,+ GetWindowTextW, GetWindowThreadProcessId, IsIconic, IsWindowVisible,+ WINDOWPLACEMENT, WS_EX_APPWINDOW, WS_EX_NOACTIVATE, WS_EX_TOOLWINDOW,+ },+ },+ },+ core::{BOOL, PWSTR},+};++const APPS_FOLDER: &str = "shell:AppsFolder\\";+const FRAME_HOST_CLASS: &str = "ApplicationFrameWindow";++#[derive(Clone, Debug, PartialEq, Eq)]+pub struct TrackedWindow {+ pub hwnd: isize,+ pub app_id: String,+ pub minimized: bool,+}++#[must_use]+pub fn normalize_id(id: &str) -> String {+ if id.starts_with(APPS_FOLDER) {+ id.to_owned()+ } else {+ id.to_lowercase()+ }+}++/// Lists app windows and tracks which app each window belongs to.+///+/// Identifying a window's app requires opening its process or querying shell+/// properties, which makes each lookup expensive. The cache limits this to once+/// per window, when it appears.+#[derive(Debug, Default)]+pub struct WindowTracker {+ app_ids: HashMap<isize, String>,+}++impl WindowTracker {+ pub fn list(&mut self) -> Vec<TrackedWindow> {+ unsafe extern "system" fn collect(hwnd: HWND, list: LPARAM) -> BOOL {+ // SAFETY: `list` points to the Vec passed by `list` and remains+ // alive for the entire synchronous enumeration.+ unsafe { (*(list.0 as *mut Vec<HWND>)).push(hwnd) };+ true.into()+ }++ let mut all: Vec<HWND> = Vec::new();+ // SAFETY: The Vec pointer remains valid until EnumWindows returns.+ unsafe {+ let _ = EnumWindows(Some(collect), LPARAM(&raw mut all as isize));+ }++ let windows: Vec<TrackedWindow> = all+ .into_iter()+ .filter(|&hwnd| is_app_window(hwnd))+ .filter_map(|hwnd| {+ let key = hwnd.0 as isize;+ let app_id = match self.app_ids.get(&key) {+ Some(id) => id.clone(),+ // The newly created UWP app has not declared an identifier+ // yet; do not cache it so the lookup can be retried.+ None => {+ let id = app_id(hwnd)?;+ self.app_ids.insert(key, id.clone());+ id+ }+ };+ Some(TrackedWindow {+ hwnd: key,+ app_id,+ minimized: unsafe { IsIconic(hwnd).as_bool() },+ })+ })+ .collect();++ // Remove closed windows because Windows reuses their handles.+ self.app_ids+ .retain(|hwnd, _| windows.iter().any(|window| window.hwnd == *hwnd));+ windows+ }+}++#[must_use]+pub fn title(hwnd: isize) -> String {+ let mut buffer = [0u16; 256];+ // SAFETY: The buffer remains alive during the call, which returns the number of characters written.+ let len = unsafe { GetWindowTextW(HWND(hwnd as *mut _), &mut buffer) };+ String::from_utf16_lossy(&buffer[..len.max(0) as usize])+}++/// Restored-state rectangle of a window, also valid while it is minimized.+/// Workspace coordinates match screen coordinates here: the work area starts at+/// the screen's top-left corner because the dock reserves only the bottom edge.+#[must_use]+pub fn normal_rect(hwnd: isize) -> Option<RECT> {+ let mut placement = WINDOWPLACEMENT {+ length: size_of::<WINDOWPLACEMENT>() as u32,+ ..Default::default()+ };+ // SAFETY: The structure has its size initialized and lives for the call.+ unsafe { GetWindowPlacement(HWND(hwnd as *mut _), &mut placement) }.ok()?;+ let rect = placement.rcNormalPosition;+ (rect.right > rect.left && rect.bottom > rect.top).then_some(rect)+}++#[must_use]+pub fn foreground_window() -> isize {+ unsafe { GetForegroundWindow().0 as isize }+}++/// Returns `true` if the foreground window covers the entire `screen`+/// (for example, video, presentation, or game). The desktop does not count.+#[must_use]+pub fn foreground_is_fullscreen(screen: RECT) -> bool {+ // SAFETY: Read-only queries on the foreground window.+ unsafe {+ let hwnd = GetForegroundWindow();+ if hwnd.is_invalid() || DESKTOP_CLASSES.contains(&class_name(hwnd).as_str()) {+ return false;+ }+ let mut pid = 0u32;+ GetWindowThreadProcessId(hwnd, Some(&mut pid));+ if pid == GetCurrentProcessId() {+ return false;+ }+ let mut rect = RECT::default();+ GetWindowRect(hwnd, &mut rect).is_ok() && covers(rect, screen)+ }+}++const DESKTOP_CLASSES: [&str; 3] = ["Progman", "WorkerW", "Shell_TrayWnd"];++fn covers(window: RECT, screen: RECT) -> bool {+ window.left <= screen.left+ && window.top <= screen.top+ && window.right >= screen.right+ && window.bottom >= screen.bottom+}++fn is_app_window(hwnd: HWND) -> bool {+ // SAFETY: Read-only queries; calls on a destroyed `hwnd` have no effect.+ unsafe {+ if !IsWindowVisible(hwnd).as_bool() || GetWindowTextLengthW(hwnd) == 0 {+ return false;+ }+ let style = GetWindowLongW(hwnd, GWL_EXSTYLE) as u32;+ let has =+ |flag: windows::Win32::UI::WindowsAndMessaging::WINDOW_EX_STYLE| style & flag.0 != 0;+ if has(WS_EX_TOOLWINDOW) {+ return false;+ }+ let owned = GetWindow(hwnd, GW_OWNER).is_ok_and(|owner| !owner.is_invalid());+ if (owned || has(WS_EX_NOACTIVATE)) && !has(WS_EX_APPWINDOW) {+ return false;+ }+ // Windows hidden by the system, such as on other virtual desktops or suspended apps.+ let mut cloaked = 0u32;+ let _ = DwmGetWindowAttribute(+ hwnd,+ DWMWA_CLOAKED,+ (&raw mut cloaked).cast(),+ size_of::<u32>() as u32,+ );+ if cloaked != 0 {+ return false;+ }+ let mut pid = 0u32;+ GetWindowThreadProcessId(hwnd, Some(&mut pid));+ pid != GetCurrentProcessId()+ }+}++fn app_id(hwnd: HWND) -> Option<String> {+ if class_name(hwnd) == FRAME_HOST_CLASS {+ return window_aumid(hwnd).map(|aumid| format!("{APPS_FOLDER}{aumid}"));+ }++ // SAFETY: The process handle is closed before leaving the block, and the+ // buffers have the declared lengths.+ unsafe {+ let mut pid = 0u32;+ GetWindowThreadProcessId(hwnd, Some(&mut pid));+ let process = OpenProcess(PROCESS_QUERY_LIMITED_INFORMATION, false, pid).ok()?;++ let mut buffer = [0u16; 1024];+ let mut len = buffer.len() as u32;+ let id = if GetApplicationUserModelId(process, &mut len, Some(PWSTR(buffer.as_mut_ptr())))+ .is_ok()+ {+ // `len` includes the null terminator.+ let aumid = String::from_utf16_lossy(&buffer[..len.saturating_sub(1) as usize]);+ Some(format!("{APPS_FOLDER}{aumid}"))+ } else {+ len = buffer.len() as u32;+ QueryFullProcessImageNameW(+ process,+ PROCESS_NAME_WIN32,+ PWSTR(buffer.as_mut_ptr()),+ &mut len,+ )+ .ok()+ .map(|()| normalize_id(&String::from_utf16_lossy(&buffer[..len as usize])))+ };+ let _ = CloseHandle(process);+ id+ }+}++fn class_name(hwnd: HWND) -> String {+ let mut buffer = [0u16; 128];+ // SAFETY: The buffer remains alive during the call, which returns the number of characters written.+ let len = unsafe { GetClassNameW(hwnd, &mut buffer) };+ String::from_utf16_lossy(&buffer[..len.max(0) as usize])+}++fn window_aumid(hwnd: HWND) -> Option<String> {+ // SAFETY: COM calls use pointers that remain valid for the duration of each call.+ let value = unsafe {+ let store: IPropertyStore = SHGetPropertyStoreForWindow(hwnd).ok()?;+ store.GetValue(&PKEY_AppUserModel_ID).ok()?+ };+ let aumid = value.to_string();+ (!aumid.is_empty()).then_some(aumid)+}++#[cfg(test)]+mod tests {+ use super::*;++ const SCREEN: RECT = RECT {+ left: 0,+ top: 0,+ right: 1920,+ bottom: 1080,+ };++ #[test]+ fn covers_should_accept_window_exactly_the_size_of_the_screen() {+ assert!(covers(SCREEN, SCREEN));+ }++ #[test]+ fn covers_should_reject_maximized_window_above_the_dock() {+ // A maximized window extends a few pixels beyond the sides and top, but+ // ends above the strip reserved by the dock.+ let maximized = RECT {+ left: -8,+ top: -8,+ right: 1928,+ bottom: 985,+ };+ assert!(!covers(maximized, SCREEN));+ }++ #[test]+ fn normalize_id_should_lowercase_executable_paths() {+ assert_eq!(+ normalize_id("C:\\Windows\\Explorer.EXE"),+ "c:\\windows\\explorer.exe"+ );+ }++ #[test]+ fn normalize_id_should_keep_packaged_app_ids_untouched() {+ let id = "shell:AppsFolder\\Microsoft.WindowsTerminal_8wekyb3d8bbwe!App";+ assert_eq!(normalize_id(id), id);+ }+}diff --git a/rust-toolchain.toml b/rust-toolchain.tomlnew file mode 100644index 0000000..73cb934--- /dev/null+++ b/rust-toolchain.toml@@ -0,0 +1,3 @@+[toolchain]+channel = "stable"+components = ["rustfmt", "clippy"]diff --git a/scripts/make_icon.py b/scripts/make_icon.pynew file mode 100644index 0000000..c8415b8--- /dev/null+++ b/scripts/make_icon.py@@ -0,0 +1,149 @@+"""Draws the Muelle app icon and its size previews.++Usage: python scripts/make_icon.py+Output: assets/brand/+"""++from pathlib import Path++from PIL import Image, ImageChops, ImageDraw, ImageFilter++SIZE = 1024+SCALE = 2 # Supersampling factor for clean edges.+S = SIZE * SCALE+OUT = Path(__file__).resolve().parent.parent / "assets" / "brand"+++def squircle_mask(size: int, inset: float, power: float = 5.0) -> Image.Image:+ """Superellipse, the continuous-corner shape of Apple app icons."""+ half = size / 2 - inset+ points = []+ steps = 720+ for i in range(steps):+ import math++ angle = 2 * math.pi * i / steps+ cos, sin = math.cos(angle), math.sin(angle)+ x = abs(cos) ** (2 / power) * half * (1 if cos >= 0 else -1)+ y = abs(sin) ** (2 / power) * half * (1 if sin >= 0 else -1)+ points.append((size / 2 + x, size / 2 + y))+ mask = Image.new("L", (size, size), 0)+ ImageDraw.Draw(mask).polygon(points, fill=255)+ return mask+++def vertical_gradient(size: int, stops: list[tuple[float, tuple[int, int, int]]]) -> Image.Image:+ column = Image.new("RGB", (1, size))+ pixels = column.load()+ for y in range(size):+ t = y / (size - 1)+ for (t0, c0), (t1, c1) in zip(stops, stops[1:]):+ if t0 <= t <= t1:+ k = (t - t0) / (t1 - t0)+ pixels[0, y] = tuple(round(a + (b - a) * k) for a, b in zip(c0, c1))+ break+ return column.resize((size, size))+++def rounded(size: tuple[int, int], radius: int, fill) -> Image.Image:+ layer = Image.new("RGBA", size, (0, 0, 0, 0))+ ImageDraw.Draw(layer).rounded_rectangle((0, 0, size[0] - 1, size[1] - 1), radius, fill=fill)+ return layer+++def shadow_of(layer: Image.Image, blur: int, opacity: float) -> Image.Image:+ alpha = layer.getchannel("A").point(lambda a: round(a * opacity))+ shadow = Image.new("RGBA", layer.size, (10, 20, 60, 0))+ shadow.putalpha(alpha)+ return shadow.filter(ImageFilter.GaussianBlur(blur))+++def draw_icon() -> Image.Image:+ canvas = Image.new("RGBA", (S, S), (0, 0, 0, 0))+ mask = squircle_mask(S, inset=S * 0.085)++ # Sea at dusk: warm horizon over deep blue water.+ sky = vertical_gradient(+ S,+ [+ (0.0, (88, 86, 214)),+ (0.42, (255, 122, 140)),+ (0.60, (255, 184, 108)),+ (0.61, (0x1D, 0x6D, 0xF1)),+ (1.0, (0x1A, 0xD1, 0xFD)),+ ],+ ).convert("RGBA")+ # Soft sun glow on the horizon.+ glow = Image.new("RGBA", (S, S), (0, 0, 0, 0))+ ImageDraw.Draw(glow).ellipse(+ (S * 0.30, S * 0.36, S * 0.70, S * 0.76), fill=(255, 236, 190, 150)+ )+ sky = Image.alpha_composite(sky, glow.filter(ImageFilter.GaussianBlur(S * 0.06)))+ canvas.paste(sky, (0, 0), mask)++ # The dock: a frosted glass bar.+ bar_w, bar_h = int(S * 0.64), int(S * 0.17)+ bar_x, bar_y = (S - bar_w) // 2, int(S * 0.62)+ bar = rounded((bar_w, bar_h), int(bar_h * 0.36), (255, 255, 255, 70))+ ImageDraw.Draw(bar).rounded_rectangle(+ (2, 2, bar_w - 3, bar_h - 3), int(bar_h * 0.36), outline=(255, 255, 255, 190), width=6+ )+ layer = Image.new("RGBA", (S, S), (0, 0, 0, 0))+ layer.paste(bar, (bar_x, bar_y))+ canvas = Image.alpha_composite(canvas, shadow_of(layer, int(S * 0.02), 0.55))+ canvas = Image.alpha_composite(canvas, layer)++ # Three apps; the middle one magnified and lifted.+ small, big = int(S * 0.125), int(S * 0.215)+ base = bar_y + int(bar_h * 0.80)+ tiles = [+ (S * 0.5 - S * 0.215, small, [(0.0, (255, 255, 255)), (1.0, (214, 232, 255))]),+ (S * 0.5, big, [(0.0, (255, 214, 102)), (1.0, (255, 94, 126))]),+ (S * 0.5 + S * 0.215, small, [(0.0, (255, 255, 255)), (1.0, (214, 232, 255))]),+ ]+ for center, side, stops in tiles:+ tile = vertical_gradient(side, stops).convert("RGBA")+ tile_mask = squircle_mask(side, inset=0)+ tile.putalpha(tile_mask)+ # Top sheen, clipped to the tile.+ sheen = Image.new("RGBA", (side, side), (0, 0, 0, 0))+ ImageDraw.Draw(sheen).ellipse(+ (-side * 0.2, -side * 0.75, side * 1.2, side * 0.42), fill=(255, 255, 255, 70)+ )+ sheen.putalpha(ImageChops.multiply(sheen.getchannel("A"), tile_mask))+ tile = Image.alpha_composite(tile, sheen)+ layer = Image.new("RGBA", (S, S), (0, 0, 0, 0))+ layer.paste(tile, (int(center - side / 2), base - side), tile)+ canvas = Image.alpha_composite(canvas, shadow_of(layer, int(S * 0.012), 0.5))+ canvas = Image.alpha_composite(canvas, layer)++ # Glass highlight across the top of the icon.+ sheen = Image.new("RGBA", (S, S), (0, 0, 0, 0))+ ImageDraw.Draw(sheen).ellipse((-S * 0.2, -S * 0.62, S * 1.2, S * 0.36), fill=(255, 255, 255, 46))+ sheen.putalpha(ImageChops.multiply(sheen.getchannel("A"), mask))+ canvas = Image.alpha_composite(canvas, sheen)++ return canvas.resize((SIZE, SIZE), Image.LANCZOS)+++def main() -> None:+ OUT.mkdir(parents=True, exist_ok=True)+ icon = draw_icon()+ icon.save(OUT / "muelle-1024.png")+ icon.save(OUT / "muelle.ico", sizes=[(s, s) for s in (256, 128, 64, 48, 32, 24, 16)])++ # Preview on dark and light backgrounds at the sizes Windows uses.+ sizes = (256, 96, 48, 32, 16)+ sheet = Image.new("RGB", (760, 620), (32, 32, 36))+ ImageDraw.Draw(sheet).rectangle((0, 310, 760, 620), fill=(243, 243, 246))+ for row in (0, 1):+ x = 30+ for size in sizes:+ small = icon.resize((size, size), Image.LANCZOS)+ sheet.paste(small, (x, row * 310 + (310 - size) // 2), small)+ x += size + 40+ sheet.save(OUT / "muelle-preview.png")+++if __name__ == "__main__":+ main()diff --git a/scripts/measure.ps1 b/scripts/measure.ps1new file mode 100644index 0000000..e08ac57--- /dev/null+++ b/scripts/measure.ps1@@ -0,0 +1,73 @@+<#+.SYNOPSIS+ Measures Muelle resource usage.++.DESCRIPTION+ Starts a release build of the dock, measures startup time, then records memory,+ CPU, threads, handles, and GDI/USER objects for the idle dock and watchdog.+ The script closes the dock afterward so it restores the taskbar.++ The script does not move the mouse or take focus, so it can run while the+ computer is in use. CPU measurements are more reliable while the computer is idle.++.EXAMPLE+ cargo build --release -p muelle; ./scripts/measure.ps1+#>+param(+ [string]$Exe = (Join-Path $env:USERPROFILE '.cargo-target\muelle\release\muelle.exe'),+ [int]$IdleSeconds = 10+)+$ErrorActionPreference = 'Stop'++Add-Type @'+using System; using System.Runtime.InteropServices;+public static class MuelleMeasure {+ [DllImport("user32.dll")] public static extern IntPtr FindWindow(string c, string n);+ [DllImport("user32.dll")] public static extern bool IsWindowVisible(IntPtr h);+ [DllImport("user32.dll")] public static extern uint GetGuiResources(IntPtr p, uint flags);+}+'@++if (-not (Test-Path $Exe)) { throw "No existe $Exe. Compila antes: cargo build --release -p muelle" }+if (Get-Process muelle -ErrorAction SilentlyContinue) { throw 'Ya hay un dock en marcha: ciérralo con `muelle --quit`.' }++$clock = [Diagnostics.Stopwatch]::StartNew()+Start-Process $Exe | Out-Null+$visibleMs = $null+while ($clock.ElapsedMilliseconds -lt 10000) {+ $h = [MuelleMeasure]::FindWindow('MuelleWindow', [NullString]::Value)+ if ($h -ne [IntPtr]::Zero -and [MuelleMeasure]::IsWindowVisible($h)) { $visibleMs = $clock.ElapsedMilliseconds; break }+ Start-Sleep -Milliseconds 5+}++Start-Sleep -Seconds 3 # Let memory trimming finish before sampling.+$procs = Get-CimInstance Win32_Process -Filter "Name='muelle.exe'"+$cpuBefore = @{}+foreach ($p in $procs) { $cpuBefore[$p.ProcessId] = (Get-Process -Id $p.ProcessId).TotalProcessorTime }+Start-Sleep -Seconds $IdleSeconds++$rows = foreach ($p in $procs) {+ $proc = Get-Process -Id $p.ProcessId+ $role = if ($p.CommandLine -match '--guard') { 'guardián' } else { 'dock' }+ $pws = (Get-CimInstance Win32_PerfFormattedData_PerfProc_Process -Filter "IDProcess=$($p.ProcessId)").WorkingSetPrivate+ [pscustomobject]@{+ Proceso = $role+ 'Privada (MB)' = [math]::Round($proc.PrivateMemorySize64 / 1MB, 1)+ 'WS privado (MB)' = [math]::Round($pws / 1MB, 1)+ 'Working set (MB)' = [math]::Round($proc.WorkingSet64 / 1MB, 1)+ 'CPU en reposo (ms)' = [math]::Round(($proc.TotalProcessorTime - $cpuBefore[$p.ProcessId]).TotalMilliseconds, 1)+ Hilos = $proc.Threads.Count+ Handles = $proc.HandleCount+ GDI = [MuelleMeasure]::GetGuiResources($proc.Handle, 0)+ USER = [MuelleMeasure]::GetGuiResources($proc.Handle, 1)+ }+}++"Arranque hasta dock visible: $(if ($visibleMs) { "$visibleMs ms" } else { 'no apareció en 10 s' })"+"Reposo medido: $IdleSeconds s"+$rows | Format-Table -AutoSize | Out-String -Width 200+"Privada = memoria comprometida solo por el proceso (la métrica real)."+"WS privado = lo que muestra el Administrador de tareas en 'Memoria'."++& $Exe --quit+Start-Sleep -Seconds 2diff --git a/skills-lock.json b/skills-lock.jsonnew file mode 100644index 0000000..d7f3678--- /dev/null+++ b/skills-lock.json@@ -0,0 +1,17 @@+{+ "version": 2,+ "skills": {+ "rust-best-practices": {+ "source": "apollographql/skills",+ "sourceType": "github",+ "skillPath": "skills/rust-best-practices/SKILL.md",+ "computedHash": "7e12e68aa50152eb7ba9ea1f88ca5380c846ea0175f8ab6788bb79b7faf12ca0"+ },+ "vercel-react-best-practices": {+ "source": "vercel-labs/agent-skills",+ "sourceType": "github",+ "skillPath": "skills/react-best-practices/SKILL.md",+ "computedHash": "7991ed4fbecdac23f47c1a40c243e00a212a9e7f3604db93959b3ae11dffe299"+ }+ }+}diff --git a/spikes/Cargo.toml b/spikes/Cargo.tomlnew file mode 100644index 0000000..e76deea--- /dev/null+++ b/spikes/Cargo.toml@@ -0,0 +1,37 @@+[package]+name = "spikes"+version = "0.0.0"+edition.workspace = true+license.workspace = true+publish = false++[lints]+workspace = true++[dependencies]+windows = { workspace = true, features = [+ "Foundation",+ "Foundation_Numerics",+ "System",+ "UI",+ "UI_Composition",+ "UI_Composition_Desktop",+ "Win32_Foundation",+ "Win32_Graphics_Direct2D",+ "Win32_Graphics_Direct3D",+ "Win32_Graphics_Direct3D11",+ "Win32_Graphics_DirectWrite",+ "Win32_Graphics_Dwm",+ "Win32_Graphics_Dxgi",+ "Win32_Graphics_Gdi",+ "Win32_System_LibraryLoader",+ "Win32_System_ProcessStatus",+ "Win32_System_Threading",+ "Win32_System_WinRT",+ "Win32_System_WinRT_Composition",+ "Win32_UI_HiDpi",+ "Win32_UI_Shell",+ "Win32_UI_WindowsAndMessaging",+] }+windows-numerics.workspace = true+muelle-shell.workspace = truediff --git a/spikes/src/bin/spike_glass.rs b/spikes/src/bin/spike_glass.rsnew file mode 100644index 0000000..7d8ed3f--- /dev/null+++ b/spikes/src/bin/spike_glass.rs@@ -0,0 +1,307 @@+//! Prototypes (a) and (c): rounded glass showing the desktop backdrop and an+//! input region that lets clicks outside the dock outline pass through.+//!+//! Usage: `spike_glass [seconds]` (15 by default). Prints click-test results+//! and exits automatically.++use std::env;++use windows_numerics::{Vector2, Vector3};++use windows::{+ System::DispatcherQueueController,+ UI::{+ Color,+ Composition::{Compositor, ContainerVisual, Desktop::DesktopWindowTarget},+ },+ Win32::{+ Foundation::{HWND, LPARAM, LRESULT, POINT, WPARAM},+ Graphics::{+ Dwm::{DWMWA_USE_HOSTBACKDROPBRUSH, DwmSetWindowAttribute},+ Gdi::{CreateRoundRectRgn, SetWindowRgn},+ },+ System::{+ LibraryLoader::GetModuleHandleW,+ WinRT::{+ Composition::ICompositorDesktopInterop, CreateDispatcherQueueController,+ DQTAT_COM_NONE, DQTYPE_THREAD_CURRENT, DispatcherQueueOptions,+ },+ },+ UI::{+ HiDpi::{DPI_AWARENESS_CONTEXT_PER_MONITOR_AWARE_V2, SetProcessDpiAwarenessContext},+ WindowsAndMessaging::{+ CreateWindowExW, DefWindowProcW, DispatchMessageW, GetMessageW, GetSystemMetrics,+ KillTimer, MSG, PostQuitMessage, RegisterClassW, SM_CXSCREEN, SM_CYSCREEN,+ SW_SHOWNOACTIVATE, SetTimer, ShowWindow, WM_DESTROY, WM_TIMER, WNDCLASSW,+ WS_EX_NOACTIVATE, WS_EX_NOREDIRECTIONBITMAP, WS_EX_TOOLWINDOW, WS_EX_TOPMOST,+ WS_POPUP, WindowFromPoint,+ },+ },+ },+ core::{BOOL, Interface, Result, w},+};++// The window is taller than the dock to leave room for magnification above it.+const WIN_W: i32 = 760;+const WIN_H: i32 = 220;+const PILL_W: i32 = 640;+const PILL_H: i32 = 72;+const PILL_RADIUS: f32 = 26.0;+fn margin_bottom() -> i32 {+ env::args()+ .nth(2)+ .and_then(|s| s.parse().ok())+ .unwrap_or(60)+}++const TIMER_HIT_TEST: usize = 1;+const TIMER_QUIT: usize = 2;++fn pill_origin() -> (i32, i32) {+ ((WIN_W - PILL_W) / 2, WIN_H - PILL_H - 8)+}++fn rgba(a: u8, r: u8, g: u8, b: u8) -> Color {+ Color {+ A: a,+ R: r,+ G: g,+ B: b,+ }+}++/// Visual tree: clipped glass backdrop, tint, bright border, and a control+/// square outside the outline to check whether the input region clips it.+fn build_visuals(compositor: &Compositor) -> Result<ContainerVisual> {+ let (px, py) = pill_origin();+ let size = Vector2 {+ X: PILL_W as f32,+ Y: PILL_H as f32,+ };+ let offset = Vector3 {+ X: px as f32,+ Y: py as f32,+ Z: 0.0,+ };++ let root = compositor.CreateContainerVisual()?;+ root.SetRelativeSizeAdjustment(Vector2 { X: 1.0, Y: 1.0 })?;++ let pill = compositor.CreateContainerVisual()?;+ pill.SetSize(size)?;+ pill.SetOffset(offset)?;+ let geometry = compositor.CreateRoundedRectangleGeometry()?;+ geometry.SetSize(size)?;+ geometry.SetCornerRadius(Vector2 {+ X: PILL_RADIUS,+ Y: PILL_RADIUS,+ })?;+ pill.SetClip(&compositor.CreateGeometricClipWithGeometry(&geometry)?)?;++ let backdrop = compositor.CreateSpriteVisual()?;+ backdrop.SetRelativeSizeAdjustment(Vector2 { X: 1.0, Y: 1.0 })?;+ backdrop.SetBrush(&compositor.CreateHostBackdropBrush()?)?;+ pill.Children()?.InsertAtBottom(&backdrop)?;++ let tint = compositor.CreateSpriteVisual()?;+ tint.SetRelativeSizeAdjustment(Vector2 { X: 1.0, Y: 1.0 })?;+ tint.SetBrush(&compositor.CreateColorBrushWithColor(rgba(46, 255, 255, 255))?)?;+ pill.Children()?.InsertAtTop(&tint)?;+ root.Children()?.InsertAtTop(&pill)?;++ let rim_geometry = compositor.CreateRoundedRectangleGeometry()?;+ rim_geometry.SetSize(Vector2 {+ X: size.X - 1.0,+ Y: size.Y - 1.0,+ })?;+ rim_geometry.SetOffset(Vector2 { X: 0.5, Y: 0.5 })?;+ rim_geometry.SetCornerRadius(Vector2 {+ X: PILL_RADIUS,+ Y: PILL_RADIUS,+ })?;+ let rim = compositor.CreateSpriteShapeWithGeometry(&rim_geometry)?;+ rim.SetStrokeBrush(&compositor.CreateColorBrushWithColor(rgba(110, 255, 255, 255))?)?;+ rim.SetStrokeThickness(1.0)?;+ let rim_visual = compositor.CreateShapeVisual()?;+ rim_visual.SetSize(size)?;+ rim_visual.SetOffset(offset)?;+ rim_visual.Shapes()?.Append(&rim)?;+ root.Children()?.InsertAtTop(&rim_visual)?;++ for i in 0..9 {+ let icon = compositor.CreateSpriteVisual()?;+ icon.SetSize(Vector2 { X: 52.0, Y: 52.0 })?;+ icon.SetOffset(Vector3 {+ X: px as f32 + 20.0 + i as f32 * 68.0,+ Y: py as f32 + 10.0,+ Z: 0.0,+ })?;+ let hue = (i * 20) as u8;+ icon.SetBrush(&compositor.CreateColorBrushWithColor(rgba(+ 255,+ 255 - hue,+ 90 + hue / 2,+ 60 + hue,+ ))?)?;+ root.Children()?.InsertAtTop(&icon)?;+ }++ let control = compositor.CreateSpriteVisual()?;+ control.SetSize(Vector2 { X: 40.0, Y: 40.0 })?;+ control.SetOffset(Vector3 {+ X: 10.0,+ Y: 10.0,+ Z: 0.0,+ })?;+ control.SetBrush(&compositor.CreateColorBrushWithColor(rgba(255, 255, 0, 0))?)?;+ root.Children()?.InsertAtTop(&control)?;++ Ok(root)+}++fn hit_test(hwnd: HWND, origin: POINT) {+ let (px, py) = pill_origin();+ let cases = [+ ("centro del dock", px + PILL_W / 2, py + PILL_H / 2, true),+ (+ "zona transparente sobre el dock",+ px + PILL_W / 2,+ py - 60,+ false,+ ),+ (+ "esquina redondeada (fuera de la curva)",+ px + 2,+ py + 2,+ false,+ ),+ ];+ for (name, x, y, expect_ours) in cases {+ let point = POINT {+ x: origin.x + x,+ y: origin.y + y,+ };+ // SAFETY: Read-only query.+ let ours = unsafe { WindowFromPoint(point) } == hwnd;+ let verdict = if ours == expect_ours { "OK" } else { "FALLO" };+ println!(+ "[{verdict}] {name}: el clic llega a {}",+ if ours {+ "Muelle"+ } else {+ "la ventana de abajo"+ }+ );+ }+}++unsafe extern "system" fn wndproc(hwnd: HWND, msg: u32, w: WPARAM, l: LPARAM) -> LRESULT {+ match msg {+ WM_TIMER if w.0 == TIMER_HIT_TEST => {+ // SAFETY: `hwnd` is our live window.+ unsafe {+ let _ = KillTimer(Some(hwnd), TIMER_HIT_TEST);+ }+ hit_test(hwnd, window_origin());+ LRESULT(0)+ }+ WM_TIMER if w.0 == TIMER_QUIT => {+ // SAFETY: Ends this thread's message loop.+ unsafe { PostQuitMessage(0) };+ LRESULT(0)+ }+ WM_DESTROY => {+ // SAFETY: Same as above.+ unsafe { PostQuitMessage(0) };+ LRESULT(0)+ }+ // SAFETY: Standard message forwarding.+ _ => unsafe { DefWindowProcW(hwnd, msg, w, l) },+ }+}++fn window_origin() -> POINT {+ // SAFETY: Read-only metric queries.+ let (sw, sh) = unsafe { (GetSystemMetrics(SM_CXSCREEN), GetSystemMetrics(SM_CYSCREEN)) };+ POINT {+ x: (sw - WIN_W) / 2,+ y: sh - WIN_H - margin_bottom(),+ }+}++fn main() -> Result<()> {+ let seconds: u32 = env::args()+ .nth(1)+ .and_then(|s| s.parse().ok())+ .unwrap_or(15);++ // SAFETY: Single-threaded Win32/WinRT initialization; all passed pointers+ // remain valid for the duration of the call.+ unsafe {+ SetProcessDpiAwarenessContext(DPI_AWARENESS_CONTEXT_PER_MONITOR_AWARE_V2)?;++ // The compositor requires a dispatcher queue on this thread.+ let _queue: DispatcherQueueController =+ CreateDispatcherQueueController(DispatcherQueueOptions {+ dwSize: size_of::<DispatcherQueueOptions>() as u32,+ threadType: DQTYPE_THREAD_CURRENT,+ apartmentType: DQTAT_COM_NONE,+ })?;++ let instance = GetModuleHandleW(None)?;+ let class = w!("MuelleSpikeGlass");+ RegisterClassW(&WNDCLASSW {+ lpfnWndProc: Some(wndproc),+ hInstance: instance.into(),+ lpszClassName: class,+ ..Default::default()+ });++ let origin = window_origin();+ let hwnd = CreateWindowExW(+ // NOACTIVATE keeps the dock from stealing focus while the glass remains active.+ WS_EX_NOREDIRECTIONBITMAP | WS_EX_TOPMOST | WS_EX_TOOLWINDOW | WS_EX_NOACTIVATE,+ class,+ w!("Muelle spike"),+ WS_POPUP,+ origin.x,+ origin.y,+ WIN_W,+ WIN_H,+ None,+ None,+ Some(instance.into()),+ None,+ )?;++ let enable = BOOL::from(true);+ DwmSetWindowAttribute(+ hwnd,+ DWMWA_USE_HOSTBACKDROPBRUSH,+ (&raw const enable).cast(),+ size_of::<BOOL>() as u32,+ )?;++ let compositor = Compositor::new()?;+ let target: DesktopWindowTarget = compositor+ .cast::<ICompositorDesktopInterop>()?+ .CreateDesktopWindowTarget(hwnd, true)?;+ target.SetRoot(&build_visuals(&compositor)?)?;++ // (c) Match the input region to the dock outline; ownership transfers to the system.+ let (px, py) = pill_origin();+ let d = (PILL_RADIUS * 2.0) as i32;+ let region = CreateRoundRectRgn(px, py, px + PILL_W + 1, py + PILL_H + 1, d, d);+ SetWindowRgn(hwnd, Some(region), true);++ let _ = ShowWindow(hwnd, SW_SHOWNOACTIVATE);+ SetTimer(Some(hwnd), TIMER_HIT_TEST, 1000, None);+ SetTimer(Some(hwnd), TIMER_QUIT, seconds * 1000, None);++ let mut msg = MSG::default();+ while GetMessageW(&mut msg, None, 0, 0).as_bool() {+ DispatchMessageW(&msg);+ }+ }+ Ok(())+}diff --git a/spikes/src/bin/spike_mem.rs b/spikes/src/bin/spike_mem.rsnew file mode 100644index 0000000..c9d2cca--- /dev/null+++ b/spikes/src/bin/spike_mem.rs@@ -0,0 +1,124 @@+//! Measures the memory cost of each part of the dock's graphics stack to guide+//! optimization with data rather than assumptions.+//!+//! Usage: `cargo run --release -p spikes --bin spike_mem`++use std::mem::size_of;++use windows::{+ UI::Composition::Compositor,+ Win32::{+ Foundation::HMODULE,+ Graphics::{+ Direct2D::D2D1CreateDevice,+ Direct3D::{D3D_DRIVER_TYPE, D3D_DRIVER_TYPE_HARDWARE, D3D_DRIVER_TYPE_WARP},+ Direct3D11::{+ D3D11_CREATE_DEVICE_BGRA_SUPPORT, D3D11_CREATE_DEVICE_SINGLETHREADED,+ D3D11_SDK_VERSION, D3D11CreateDevice,+ },+ DirectWrite::{DWRITE_FACTORY_TYPE_SHARED, DWriteCreateFactory, IDWriteFactory},+ Dxgi::IDXGIDevice,+ },+ System::{+ ProcessStatus::{+ EmptyWorkingSet, GetProcessMemoryInfo, PROCESS_MEMORY_COUNTERS,+ PROCESS_MEMORY_COUNTERS_EX,+ },+ Threading::GetCurrentProcess,+ WinRT::{+ Composition::ICompositorInterop, CreateDispatcherQueueController, DQTAT_COM_STA,+ DQTYPE_THREAD_CURRENT, DispatcherQueueOptions,+ },+ },+ },+ core::{Interface, Result},+};++fn report(stage: &str) {+ let mut counters = PROCESS_MEMORY_COUNTERS_EX {+ cb: size_of::<PROCESS_MEMORY_COUNTERS_EX>() as u32,+ ..Default::default()+ };+ // SAFETY: The structure has its size initialized; PROCESS_MEMORY_COUNTERS_EX+ // begins with the fields of PROCESS_MEMORY_COUNTERS.+ unsafe {+ let _ = GetProcessMemoryInfo(+ GetCurrentProcess(),+ (&raw mut counters).cast::<PROCESS_MEMORY_COUNTERS>(),+ counters.cb,+ );+ }+ let mb = |bytes: usize| bytes as f64 / 1_048_576.0;+ println!(+ "{stage:<44} working set {:>6.1} MB privada (commit) {:>6.1} MB",+ mb(counters.WorkingSetSize),+ mb(counters.PrivateUsage)+ );+}++fn device(kind: D3D_DRIVER_TYPE, single_thread: bool) -> Result<IDXGIDevice> {+ let mut flags = D3D11_CREATE_DEVICE_BGRA_SUPPORT;+ if single_thread {+ flags |= D3D11_CREATE_DEVICE_SINGLETHREADED;+ }+ let mut d3d = None;+ // SAFETY: The output pointer refers to `d3d`, which remains alive for the call.+ unsafe {+ D3D11CreateDevice(+ None,+ kind,+ HMODULE::default(),+ flags,+ None,+ D3D11_SDK_VERSION,+ Some(&mut d3d),+ None,+ None,+ )?;+ }+ d3d.ok_or_else(windows::core::Error::empty)?.cast()+}++fn main() -> Result<()> {+ let warp = std::env::args().any(|a| a == "--warp");+ let single = std::env::args().any(|a| a == "--single");+ report("0. arranque");+ // SAFETY: The dispatcher options remain valid for this current-thread call.+ let _queue = unsafe {+ CreateDispatcherQueueController(DispatcherQueueOptions {+ dwSize: size_of::<DispatcherQueueOptions>() as u32,+ threadType: DQTYPE_THREAD_CURRENT,+ apartmentType: DQTAT_COM_STA,+ })?+ };+ let compositor = Compositor::new()?;+ report("1. + compositor");+ let kind = if warp {+ D3D_DRIVER_TYPE_WARP+ } else {+ D3D_DRIVER_TYPE_HARDWARE+ };+ let dxgi = device(kind, single)?;+ report(if warp {+ "2. + Direct3D (WARP, por CPU)"+ } else {+ "2. + Direct3D (GPU)"+ });+ // SAFETY: `dxgi` is a live device, and returned COM interfaces are owned by their wrappers.+ let _graphics = unsafe {+ let d2d = D2D1CreateDevice(&dxgi, None)?;+ compositor+ .cast::<ICompositorInterop>()?+ .CreateGraphicsDevice(&d2d)?+ };+ report("3. + Direct2D y dispositivo de composición");+ // SAFETY: Windows initializes the returned COM interface, which is held by `_dwrite`.+ let _dwrite: IDWriteFactory = unsafe { DWriteCreateFactory(DWRITE_FACTORY_TYPE_SHARED)? };+ report("4. + DirectWrite");+ // SAFETY: Trims this process's own working set.+ unsafe {+ let _ = EmptyWorkingSet(GetCurrentProcess());+ }+ report("5. tras recortar el working set");+ Ok(())+}diff --git a/spikes/src/bin/spike_shellcost.rs b/spikes/src/bin/spike_shellcost.rsnew file mode 100644index 0000000..ab007f2--- /dev/null+++ b/spikes/src/bin/spike_shellcost.rs@@ -0,0 +1,80 @@+//! Measures the memory, handle, and time cost of each shell call the dock makes+//! at startup. Usage: `cargo run --release -p spikes --bin spike_shellcost`++use std::{mem::size_of, time::Instant};++use muelle_shell::{recycle_bin, system};+use windows::Win32::{+ System::{+ ProcessStatus::{+ GetProcessMemoryInfo, PROCESS_MEMORY_COUNTERS, PROCESS_MEMORY_COUNTERS_EX,+ },+ Threading::{GetCurrentProcess, GetProcessHandleCount},+ WinRT::{+ CreateDispatcherQueueController, DQTAT_COM_STA, DQTYPE_THREAD_CURRENT,+ DispatcherQueueOptions,+ },+ },+ UI::WindowsAndMessaging::{CreateWindowExW, HWND_MESSAGE, WINDOW_EX_STYLE, WINDOW_STYLE},+};+use windows::core::w;++fn report(stage: &str, started: Instant) {+ let mut counters = PROCESS_MEMORY_COUNTERS_EX {+ cb: size_of::<PROCESS_MEMORY_COUNTERS_EX>() as u32,+ ..Default::default()+ };+ let mut handles = 0u32;+ // SAFETY: Queries target this process and use correctly sized structures.+ unsafe {+ let _ = GetProcessMemoryInfo(+ GetCurrentProcess(),+ (&raw mut counters).cast::<PROCESS_MEMORY_COUNTERS>(),+ counters.cb,+ );+ let _ = GetProcessHandleCount(GetCurrentProcess(), &mut handles);+ }+ println!(+ "{stage:<34} privada {:>5.1} MB handles {handles:>4} {:>7.1} ms",+ counters.PrivateUsage as f64 / 1_048_576.0,+ started.elapsed().as_secs_f64() * 1000.0+ );+}++fn main() -> windows::core::Result<()> {+ let _queue = unsafe {+ CreateDispatcherQueueController(DispatcherQueueOptions {+ dwSize: size_of::<DispatcherQueueOptions>() as u32,+ threadType: DQTYPE_THREAD_CURRENT,+ apartmentType: DQTAT_COM_STA,+ })?+ };+ report("base", Instant::now());+ let t = Instant::now();+ let _ = system::downloads_folder();+ report("downloads_folder", t);+ let t = Instant::now();+ let _ = recycle_bin::has_items();+ report("recycle_bin::has_items", t);+ let hwnd = unsafe {+ CreateWindowExW(+ WINDOW_EX_STYLE::default(),+ w!("STATIC"),+ w!(""),+ WINDOW_STYLE::default(),+ 0,+ 0,+ 0,+ 0,+ Some(HWND_MESSAGE),+ None,+ None,+ None,+ )?+ };+ let t = Instant::now();+ let watch = recycle_bin::BinWatch::register(hwnd, 0x8003);+ report("BinWatch::register", t);+ drop(watch);+ Ok(())+}diff --git a/spikes/src/bin/spike_taskbar.rs b/spikes/src/bin/spike_taskbar.rsnew file mode 100644index 0000000..c1bc4c6--- /dev/null+++ b/spikes/src/bin/spike_taskbar.rs@@ -0,0 +1,218 @@+//! Prototype (b): hide and restore the Windows taskbar.+//!+//! Usage: `spike_taskbar test | hide | restore | watch`+//! - `test`: hides the taskbar, samples its state for 4 seconds, then restores it.+//!+//! Finding: `ShowWindow(SW_HIDE)` is insufficient on Windows 11 because Explorer+//! shows the taskbar again. Instead, auto-hide is combined with layered-window+//! styles that make the taskbar invisible and click-through.+//! - `watch`: hides the taskbar and hides it again if Explorer restarts. Ctrl+C+//! does not restore it; use `restore` for that.++use std::{env, mem::size_of, thread::sleep, time::Duration};++use windows::{+ Win32::{+ Foundation::{COLORREF, HWND, LPARAM, LRESULT, RECT, WPARAM},+ System::LibraryLoader::GetModuleHandleW,+ UI::{+ Shell::{ABM_GETSTATE, ABM_SETSTATE, ABS_AUTOHIDE, APPBARDATA, SHAppBarMessage},+ WindowsAndMessaging::{+ CreateWindowExW, DefWindowProcW, DispatchMessageW, FindWindowExW, FindWindowW,+ GWL_EXSTYLE, GetMessageW, GetWindowLongPtrW, GetWindowRect, IsWindowVisible,+ LWA_ALPHA, MSG, RegisterClassW, RegisterWindowMessageW, SPI_GETWORKAREA,+ SetLayeredWindowAttributes, SetWindowLongPtrW, SystemParametersInfoW,+ WINDOW_EX_STYLE, WINDOW_STYLE, WNDCLASSW, WS_EX_LAYERED, WS_EX_TRANSPARENT,+ },+ },+ },+ core::{PCWSTR, Result, w},+};++const PRIMARY: PCWSTR = w!("Shell_TrayWnd");+const SECONDARY: PCWSTR = w!("Shell_SecondaryTrayWnd");++fn taskbars() -> Vec<HWND> {+ let mut found = Vec::new();+ // SAFETY: Read-only calls with valid static strings.+ unsafe {+ if let Ok(hwnd) = FindWindowW(PRIMARY, None) {+ found.push(hwnd);+ }+ let mut prev = None;+ while let Ok(hwnd) = FindWindowExW(None, prev, SECONDARY, None) {+ found.push(hwnd);+ prev = Some(hwnd);+ }+ }+ found+}++fn appbar_data() -> APPBARDATA {+ APPBARDATA {+ cbSize: size_of::<APPBARDATA>() as u32,+ hWnd: taskbars().first().copied().unwrap_or_default(),+ ..Default::default()+ }+}++fn autohide_enabled() -> bool {+ let mut data = appbar_data();+ // SAFETY: `data` is a valid APPBARDATA with `cbSize` initialized.+ let state = unsafe { SHAppBarMessage(ABM_GETSTATE, &mut data) };+ state as u32 & ABS_AUTOHIDE != 0+}++fn set_autohide(enabled: bool) {+ let mut data = appbar_data();+ data.lParam = LPARAM(if enabled { ABS_AUTOHIDE as isize } else { 0 });+ // SAFETY: Same as above.+ unsafe { SHAppBarMessage(ABM_SETSTATE, &mut data) };+}++const GHOST_STYLES: isize = (WS_EX_LAYERED.0 | WS_EX_TRANSPARENT.0) as isize;++fn set_ghost(hwnd: HWND, ghost: bool) {+ // SAFETY: `hwnd` comes from FindWindow; calls have no effect if it no longer exists.+ unsafe {+ let style = GetWindowLongPtrW(hwnd, GWL_EXSTYLE);+ if ghost {+ SetWindowLongPtrW(hwnd, GWL_EXSTYLE, style | GHOST_STYLES);+ let _ = SetLayeredWindowAttributes(hwnd, COLORREF(0), 0, LWA_ALPHA);+ } else {+ let _ = SetLayeredWindowAttributes(hwnd, COLORREF(0), 255, LWA_ALPHA);+ SetWindowLongPtrW(hwnd, GWL_EXSTYLE, style & !GHOST_STYLES);+ }+ }+}++fn hide() {+ // Auto-hide frees the work area; ghost mode prevents the taskbar from+ // appearing or receiving clicks when the cursor reaches the screen edge.+ set_autohide(true);+ for hwnd in taskbars() {+ set_ghost(hwnd, true);+ }+}++fn restore(autohide: bool) {+ for hwnd in taskbars() {+ set_ghost(hwnd, false);+ }+ set_autohide(autohide);+}++fn report(step: &str) {+ let mut work = RECT::default();+ // SAFETY: `work` is a valid RECT for SPI_GETWORKAREA to write to.+ unsafe {+ let _ = SystemParametersInfoW(+ SPI_GETWORKAREA,+ 0,+ Some((&raw mut work).cast()),+ Default::default(),+ );+ }+ let visible: Vec<(bool, isize, i32)> = taskbars()+ .into_iter()+ .map(|hwnd| {+ let mut rect = RECT::default();+ // SAFETY: Read-only queries.+ unsafe {+ let _ = GetWindowRect(hwnd, &mut rect);+ let ghost = GetWindowLongPtrW(hwnd, GWL_EXSTYLE) & GHOST_STYLES;+ (IsWindowVisible(hwnd).as_bool(), ghost, rect.top)+ }+ })+ .collect();+ println!(+ "{step:<22} barras(visible,fantasma,top)={visible:?} autoocultar={} area_trabajo=({},{})-({},{})",+ autohide_enabled(),+ work.left,+ work.top,+ work.right,+ work.bottom+ );+}++fn watch() -> Result<()> {+ static TASKBAR_CREATED: std::sync::OnceLock<u32> = std::sync::OnceLock::new();++ unsafe extern "system" fn wndproc(hwnd: HWND, msg: u32, w: WPARAM, l: LPARAM) -> LRESULT {+ if Some(&msg) == TASKBAR_CREATED.get() {+ println!("TaskbarCreated received: Explorer restarted; hiding the taskbar again");+ // The new taskbar needs a moment to apply its initial state.+ sleep(Duration::from_millis(500));+ hide();+ report("tras reinicio");+ return LRESULT(0);+ }+ unsafe { DefWindowProcW(hwnd, msg, w, l) }+ }++ // SAFETY: Standard class registration and message loop on a single thread.+ unsafe {+ let _ = TASKBAR_CREATED.set(RegisterWindowMessageW(w!("TaskbarCreated")));+ let instance = GetModuleHandleW(None)?;+ let class = w!("MuelleSpikeTaskbarWatch");+ RegisterClassW(&WNDCLASSW {+ lpfnWndProc: Some(wndproc),+ hInstance: instance.into(),+ lpszClassName: class,+ ..Default::default()+ });+ // TaskbarCreated is broadcast only to top-level windows, not message-only+ // windows, so create a normal window without showing it.+ CreateWindowExW(+ WINDOW_EX_STYLE::default(),+ class,+ w!(""),+ WINDOW_STYLE::default(),+ 0,+ 0,+ 0,+ 0,+ None,+ None,+ Some(instance.into()),+ None,+ )?;++ hide();+ report("oculta (watch)");+ println!("Restart Explorer from Task Manager to test.");+ let mut msg = MSG::default();+ while GetMessageW(&mut msg, None, 0, 0).as_bool() {+ DispatchMessageW(&msg);+ }+ }+ Ok(())+}++fn main() -> Result<()> {+ match env::args().nth(1).as_deref() {+ Some("test") => {+ let original = autohide_enabled();+ report("antes");+ hide();+ for i in 1..=4 {+ sleep(Duration::from_secs(1));+ report(&format!("oculta (+{i} s)"));+ }+ restore(original);+ sleep(Duration::from_secs(1));+ report("restaurada");+ }+ Some("hide") => {+ hide();+ report("oculta");+ }+ Some("restore") => {+ restore(false);+ report("restaurada");+ }+ Some("watch") => watch()?,+ _ => eprintln!("uso: spike_taskbar test | hide | restore | watch"),+ }+ Ok(())+}