diff --git a/Cargo.lock b/Cargo.lock index bf3edaa1..5d611cbd 100644 --- a/Cargo.lock +++ b/Cargo.lock @@ -516,6 +516,7 @@ dependencies = [ "bsnext_output", "bsnext_task", "bsnext_tracing", + "console 0.16.6", "miette", "serde", "serde_json", @@ -597,6 +598,7 @@ dependencies = [ "serde_yaml", "shell-words", "thiserror 1.0.60", + "tracing", ] [[package]] @@ -611,6 +613,7 @@ name = "bsnext_md" version = "0.28.2" dependencies = [ "anyhow", + "bsnext_dto", "bsnext_input", "insta", "markdown", @@ -890,12 +893,24 @@ version = "0.15.8" source = "registry+https://github.com/rust-lang/crates.io-index" checksum = "0e1f83fc076bd6dd27517eacdf25fef6c4dfe5f1d7448bafaaf3a26f13b5e4eb" dependencies = [ - "encode_unicode", + "encode_unicode 0.3.6", "lazy_static", "libc", "windows-sys 0.52.0", ] +[[package]] +name = "console" +version = "0.16.6" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "e96a4956774c13c126a8b5af4daa79384f4d826534c95a02d76afb39e2ab64e3" +dependencies = [ + "encode_unicode 1.0.0", + "libc", + "unicode-width 0.2.2", + "windows-sys 0.61.2", +] + [[package]] name = "convert_case" version = "0.11.0" @@ -1128,6 +1143,12 @@ version = "0.3.6" source = "registry+https://github.com/rust-lang/crates.io-index" checksum = "a357d28ed41a50f9c765dbfe56cbc04a64e53e5fc58ba79fbc34c10ef3df831f" +[[package]] +name = "encode_unicode" +version = "1.0.0" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "34aa73646ffb006b8f5147f3dc182bd4bcb190227ce861fc4a4844bf8e3cb2c0" + [[package]] name = "encoding_rs" version = "0.8.35" @@ -1344,7 +1365,7 @@ version = "0.2.21" source = "registry+https://github.com/rust-lang/crates.io-index" checksum = "14dbbfd5c71d70241ecf9e6f13737f7b5ce823821063188d7e46c41d371eebd5" dependencies = [ - "unicode-width", + "unicode-width 0.1.13", ] [[package]] @@ -1670,7 +1691,7 @@ version = "1.38.0" source = "registry+https://github.com/rust-lang/crates.io-index" checksum = "3eab73f58e59ca6526037208f0e98851159ec1633cf17b6cd2e1f2c3fd5d53cc" dependencies = [ - "console", + "console 0.15.8", "lazy_static", "linked-hash-map", "serde", @@ -1895,7 +1916,7 @@ dependencies = [ "terminal_size", "textwrap", "thiserror 1.0.60", - "unicode-width", + "unicode-width 0.1.13", ] [[package]] @@ -3287,7 +3308,7 @@ checksum = "23d434d3f8967a09480fb04132ebe0a3e088c173e6d0ee7897abbdf4eab0f8b9" dependencies = [ "smawk", "unicode-linebreak", - "unicode-width", + "unicode-width 0.1.13", ] [[package]] @@ -3830,6 +3851,12 @@ version = "0.1.13" source = "registry+https://github.com/rust-lang/crates.io-index" checksum = "0336d538f7abc86d282a4189614dfaa90810dfc2c6f6427eaf88e16311dd225d" +[[package]] +name = "unicode-width" +version = "0.2.2" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "b4ac048d71ede7ee76d585517add45da530660ef4390e49b098733c6e897f254" + [[package]] name = "unindent" version = "0.2.3" diff --git a/crates/bsnext_core/src/export.rs b/crates/bsnext_core/src/export.rs deleted file mode 100644 index d68a616f..00000000 --- a/crates/bsnext_core/src/export.rs +++ /dev/null @@ -1,242 +0,0 @@ -use crate::runtime_ctx::RuntimeCtx; -use crate::server::router::common::{into_state, uri_to_res_parts}; -use crate::shared_args::LoggingOpts; -use bsnext_fs_helpers::{FsWriteError, WriteMode}; -use bsnext_input::route::{Route, RouteKind}; -use bsnext_input::server_config::ServerConfig; -use bsnext_output::OutputWriterTrait; -use bsnext_tracing::OutputFormat; -use futures_util::future::join_all; -use http::response::Parts; -use std::clone::Clone; -use std::fs; -use std::io::Write; -use std::path::{Path, PathBuf}; -use std::time::Duration; - -#[derive(Debug, serde::Serialize)] -pub enum ExportEvent { - DryRunDirCreate(PathBuf), - DryRunFileCreate(PathBuf), - DidCreateFile(PathBuf), - DidCreateDir(PathBuf), -} - -#[derive(Debug, thiserror::Error)] -pub enum ExportError { - #[error("{0}")] - Fs(FsWriteError), -} - -impl OutputWriterTrait for ExportError { - fn write_json(&self, _sink: &mut W) -> anyhow::Result<()> { - let error_string = self.to_string(); - let named = match self { - ExportError::Fs(_) => "fs", - }; - let v = serde_json::json!({ - "kind": named, - "error": error_string - }); - writeln!(_sink, "{v}")?; - Ok(()) - } - - fn write_pretty(&self, sink: &mut W) -> anyhow::Result<()> { - match self { - ExportError::Fs(fs_write_error) => { - writeln!(sink, "[export]: Error! {fs_write_error}")?; - } - } - Ok(()) - } -} - -impl OutputWriterTrait for ExportEvent { - fn write_json(&self, _sink: &mut W) -> anyhow::Result<()> { - let str = serde_json::to_string(&self)?; - writeln!(_sink, "{str}")?; - Ok(()) - } - - fn write_pretty(&self, sink: &mut W) -> anyhow::Result<()> { - match self { - ExportEvent::DryRunDirCreate(dir) => { - writeln!(sink, "[export:dry-run]: would create dir {}", dir.display())?; - } - ExportEvent::DryRunFileCreate(file) => writeln!( - sink, - "[export:dry-run]: would create file {}", - file.display() - )?, - ExportEvent::DidCreateFile(dir) => { - writeln!(sink, "[export]: did create file {}", dir.display())?; - } - ExportEvent::DidCreateDir(file) => { - writeln!(sink, "[export]: did create dir {}", file.display())?; - } - } - Ok(()) - } -} - -#[derive(Debug)] -enum ExportType { - Write { - export_result: ExportResult, - filepath: PathBuf, - }, - Excluded { - reason: ExcludeReason, - }, -} - -#[derive(Debug)] -enum ExcludeReason { - BadRequest, -} - -#[derive(Debug)] -struct ExportRequest<'a> { - pub url_path: &'a str, - pub filepath: PathBuf, -} - -type ExportResult = (Parts, String, Duration); - -#[derive(Debug, Clone, clap::Parser)] -pub struct ExportCommand { - /// The folder to export the files to. For current, provide '.' - #[arg(long = "dir")] - pub out_dir: PathBuf, - /// When provided, just prints what might happen instead of actually causing side effects - #[arg(long)] - pub dry_run: bool, - - /// logging options - #[clap(flatten)] - pub logging: LoggingOpts, - - /// output options - #[arg(short, long, value_enum, default_value_t)] - pub format: OutputFormat, - - /// Paths to serve + possibly watch, incompatible with `-i` option - pub trailing: Vec, -} - -pub async fn export_one_server( - cwd: &PathBuf, - server: ServerConfig, - cmd: &ExportCommand, - write_mode: WriteMode, -) -> Result, ExportError> { - let routes = server.combined_routes(); - let state = into_state(server); - - let raw_entries = routes.iter().filter_map(only_raw_entries); - let raw_entry_paths = raw_entries.clone().map(|r| r.filepath); - let async_requests = raw_entries.map(|req| uri_to_res_parts(state.clone(), req.url_path)); - - let ctx = RuntimeCtx::new(cwd); - // let job_count = raw_entry_paths.len(); - - join_all(async_requests) - .await - .into_iter() - .zip(raw_entry_paths) - .map(to_export_type) - .try_fold(vec![], move |mut acc, ref ex_type| match cmd.dry_run { - true => match print_sink(ex_type, &cmd.out_dir, &ctx) { - Ok(evts) => { - acc.extend(evts); - Ok(acc) - } - Err(e) => Err(e), - }, - false => match fs_sink(ex_type, &cmd.out_dir, &ctx, &write_mode) { - Ok(evts) => { - acc.extend(evts); - Ok(acc) - } - Err(e) => Err(e), - }, - }) -} - -fn fs_sink( - ex_type: &ExportType, - out_dir: &PathBuf, - ctx: &RuntimeCtx, - write_mode: &WriteMode, -) -> Result, ExportError> { - match ex_type { - ExportType::Write { - export_result, - filepath, - } => { - let filepath = ctx.cwd().join(out_dir).join(filepath); - write_one(export_result, &filepath, ctx, write_mode).map_err(ExportError::Fs) - } - ExportType::Excluded { reason: _ } => Ok(vec![]), - } -} - -fn print_sink( - ex_type: &ExportType, - out_dir: &PathBuf, - ctx: &RuntimeCtx, -) -> Result, ExportError> { - let mut events = vec![]; - match ex_type { - ExportType::Write { filepath, .. } => { - let path = ctx.cwd().join(out_dir).join(filepath); - events.push(ExportEvent::DryRunFileCreate(path)); - } - ExportType::Excluded { reason } => { - todo!("Ignoring {:?}", reason) - } - } - Ok(events) -} - -fn to_export_type((export_result, filepath): (ExportResult, PathBuf)) -> ExportType { - let (parts, _, _) = &export_result; - if parts.status.as_u16() == 200 { - ExportType::Write { - export_result, - filepath, - } - } else { - ExportType::Excluded { - reason: ExcludeReason::BadRequest, - } - } -} - -fn only_raw_entries(route: &Route) -> Option> { - match &route.kind { - RouteKind::Raw(..) => Some(ExportRequest { - filepath: route.as_filepath(), - url_path: route.url_path(), - }), - _ => None, - } -} - -fn write_one( - export_result: &ExportResult, - filepath: &Path, - ctx: &RuntimeCtx, - write_mode: &WriteMode, -) -> Result, FsWriteError> { - let dir = filepath.parent(); - let mut events = vec![]; - if let Some(dir) = dir { - fs::create_dir_all(dir).map_err(FsWriteError::FailedDir)?; - } - let (_, ref body, _) = export_result; - let pb = bsnext_fs_helpers::fs_write_str(ctx.cwd(), filepath, body, write_mode)?; - events.push(ExportEvent::DidCreateFile(pb.clone())); - Ok(events) -} diff --git a/crates/bsnext_core/src/lib.rs b/crates/bsnext_core/src/lib.rs index 58e9facf..3619f753 100644 --- a/crates/bsnext_core/src/lib.rs +++ b/crates/bsnext_core/src/lib.rs @@ -4,7 +4,6 @@ pub mod servers_supervisor; mod body_match; pub mod dir_loader; -pub mod export; pub mod handler_stack; pub mod handlers; mod match_json; diff --git a/crates/bsnext_core/src/server/handler_listen.rs b/crates/bsnext_core/src/server/handler_listen.rs index 8dd39440..95011703 100644 --- a/crates/bsnext_core/src/server/handler_listen.rs +++ b/crates/bsnext_core/src/server/handler_listen.rs @@ -58,11 +58,11 @@ impl actix::Handler for ServerActor { } => bind_address.parse(), ServerIdentity::Address { ref bind_address } => bind_address.parse(), ServerIdentity::Named { .. } => { - format!("127.0.0.1:{}", get_available_port().expect("port?")).parse() + format!("0.0.0.0:{}", get_available_port().expect("port?")).parse() } ServerIdentity::Port { port } | ServerIdentity::PortNamed { port, .. } => { let address = SocketAddr::new( - std::net::IpAddr::V4(std::net::Ipv4Addr::new(127, 0, 0, 1)), + std::net::IpAddr::V4(std::net::Ipv4Addr::new(0, 0, 0, 0)), port, ); Ok(address) diff --git a/crates/bsnext_core/src/servers_supervisor/actor.rs b/crates/bsnext_core/src/servers_supervisor/actor.rs index a453dbf6..7151d0d3 100644 --- a/crates/bsnext_core/src/servers_supervisor/actor.rs +++ b/crates/bsnext_core/src/servers_supervisor/actor.rs @@ -1,32 +1,78 @@ -use crate::server::handler_stop::Stop; -use actix::{Actor, Addr, ResponseFuture, Running}; +use actix::{Actor, Addr, Recipient, Running}; use crate::server::actor::ServerActor; use bsnext_input::server_config::ServerIdentity; -use bsnext_input::Input; -use std::collections::HashSet; +use std::collections::HashMap; use std::net::SocketAddr; -use crate::runtime_ctx::RuntimeCtx; -use crate::server::handler_listen::Listen; -use crate::server::handler_patch::Patch; -use crate::servers_supervisor::input_changed_handler::InputChangedResponse; use bsnext_dto::any_event::AnyEvent; -use bsnext_dto::server_events::PatchError; -use bsnext_dto::server_events::{ - ChildCreated, ChildHandlerMinimal, ChildNotCreated, ChildNotPatched, ChildPatched, ChildResult, -}; -use futures_util::future::join_all; -use futures_util::FutureExt; +use bsnext_dto::server_events::ChildHandlerMinimal; +use bsnext_dto::status_events::{ServerStatusReader, ServerStatusWriter, ServiceStatus}; +use bsnext_dto::status_events_dto::ResourceStatus; use tokio::sync::oneshot::Sender; -use tracing::{span, Instrument, Level}; +use tracing::{span, Level}; #[derive(Debug)] pub struct ServersSupervisor { pub(crate) handlers: std::collections::HashMap, - pub(crate) ex_sender: tokio::sync::mpsc::Sender, + pub(crate) sender: tokio::sync::mpsc::Sender, + pub(crate) state_reader: Recipient, + pub(crate) state_writer: Recipient, + pub local_resources: LocalResources, + pub reconcile_count: usize, tx: Option>, + pub(crate) status: ServiceStatus, +} + +#[derive(Debug, Default, Clone)] +pub enum LocalResource { + #[default] + Pending, + Waiting { + reason: String, + attempts: usize, + }, + Ready, + Failed { + reason: String, + }, +} + +impl From<&'_ LocalResource> for ResourceStatus { + fn from(value: &'_ LocalResource) -> Self { + match value { + LocalResource::Pending => ResourceStatus::Pending, + LocalResource::Waiting { reason, .. } => ResourceStatus::Waiting { + reason: reason.clone(), + }, + LocalResource::Ready => ResourceStatus::Ready, + LocalResource::Failed { reason } => ResourceStatus::Failed { + reason: reason.clone(), + }, + } + } +} + +#[derive(Debug, Default)] +pub struct LocalResources { + pub inner: HashMap, +} + +impl LocalResources { + pub(crate) fn as_resource_status(&self) -> HashMap { + todo!("ResourceStatus must support a 'backoff' variant to determine when easy sub resource is safe to try again"); + let mut resource_status = HashMap::new(); + for (path_watchable, local_resource) in &self.inner { + resource_status.insert(path_watchable.clone(), ResourceStatus::from(local_resource)); + } + resource_status + } + pub(crate) fn should_reconcile(&self) -> bool { + self.inner + .iter() + .any(|(k, v)| matches!(v, LocalResource::Pending | LocalResource::Waiting { .. })) + } } #[derive(Debug, Clone)] @@ -34,6 +80,7 @@ pub struct ChildHandler { pub actor_address: Addr, pub identity: ServerIdentity, pub socket_addr: SocketAddr, + pub content_hash: u64, } impl ChildHandler { @@ -41,153 +88,29 @@ impl ChildHandler { ChildHandlerMinimal { identity: self.identity.clone(), socket_addr: self.socket_addr, + content_hash: self.content_hash, } } } impl ServersSupervisor { - pub fn new(tx: Sender<()>, ex_sender: tokio::sync::mpsc::Sender) -> Self { + pub fn new( + tx: Sender<()>, + ex_sender: tokio::sync::mpsc::Sender, + state_reader: Recipient, + state_writer: Recipient, + ) -> Self { Self { handlers: std::default::Default::default(), - ex_sender, + sender: ex_sender, tx: Some(tx), + status: ServiceStatus::default(), + state_reader, + state_writer, + local_resources: Default::default(), + reconcile_count: 0, } } - - pub(crate) fn input_changed( - &mut self, - self_addr: Addr, - input: Input, - ) -> ResponseFuture { - let span = span!(Level::TRACE, "input_changed"); - let _guard = span.enter(); - - let existing: HashSet<_> = self.handlers.values().map(|v| v.identity.clone()).collect(); - let incoming: HashSet<_> = input.servers.iter().map(|s| s.identity.clone()).collect(); - - let startup = incoming.difference(&existing).collect::>(); - let shutdown = existing.difference(&incoming).collect::>(); - let patch = existing.intersection(&incoming).collect::>(); - - let shutdown_jobs = shutdown - .into_iter() - .filter_map(|identity| self.handlers.get(identity).map(ToOwned::to_owned)) - .collect::>(); - - let start_jobs = startup - .iter() - .filter_map(|s| { - input - .servers - .iter() - .find(|x| x.identity == **s) - .map(ToOwned::to_owned) - }) - .collect::>(); - - let patch_jobs = patch - .iter() - .filter_map(|s| { - let child = self.handlers.get(s).map(ToOwned::to_owned); - let input = input - .servers - .iter() - .find(|x| x.identity == **s) - .map(ToOwned::to_owned); - match (child, input) { - (Some(child), Some(config)) => Some((child, config)), - _ => None, - } - }) - .collect::>(); - - Box::pin( - async move { - let shutdown_futs = shutdown_jobs.iter().map(|x| x.actor_address.send(Stop)); - let shutdown_results = join_all(shutdown_futs).await; - let shutdown_child_results = - shutdown_results - .iter() - .zip(shutdown_jobs) - .map(|(r, h)| match r { - Ok(_) => (None, ChildResult::Stopped(h.identity.clone())), - Err(er) => unreachable!("{}", er), - }); - - tracing::debug!("starting {:?} servers", start_jobs.len()); - let fts = start_jobs.into_iter().map(|server_config| { - let server = ServerActor::new_from_config(server_config.clone()); - let actor_addr = server.start(); - let actor_addr_c = actor_addr.clone(); - let c = server_config.clone(); - actor_addr - .send(Listen { - // todo: tie this to the input somehow? - runtime_ctx: RuntimeCtx::default(), - parent: self_addr.clone().recipient(), - evt_receiver: self_addr.clone().recipient(), - }) - .map(|r| (r, c, actor_addr_c)) - }); - let results = join_all(fts).await; - let start_child_results = results.into_iter().map(|(r, c, addr)| match r { - Ok(Ok(socket_addr)) => { - let evt = ChildResult::Created(ChildCreated { - server_handler: ChildHandlerMinimal { - identity: c.identity, - socket_addr, - }, - }); - (Some(addr), evt) - } - Ok(Err(err)) => { - let evt = ChildResult::CreateErr(ChildNotCreated { - server_error: err, - identity: c.identity.clone(), - }); - (None, evt) - } - Err(e) => unreachable!("{}", e), - }); - - let patch_futures = patch_jobs.into_iter().map(|(child, server_config)| { - child - .actor_address - .send(Patch { server_config }) - .map(|r| (r, child)) - }); - let results = join_all(patch_futures).await; - let patch_child_results = results.into_iter().map(|(r, child_handler)| match r { - Ok(Ok((route_change_set, client_config_change_set))) => { - let evt = ChildResult::Patched(ChildPatched { - server_handler: child_handler.minimal(), - route_change_set, - client_config_change_set, - }); - (Some(child_handler.actor_address), evt) - } - Ok(Err(err)) => { - let evt = ChildResult::PatchErr(ChildNotPatched { - patch_error: PatchError::DidNotPatch { - reason: err.to_string(), - }, - identity: child_handler.identity.clone(), - }); - (None, evt) - } - Err(_) => unreachable!("mailbox error on patch"), - }); - - let changes = shutdown_child_results - .chain(start_child_results) - .chain(patch_child_results) - .collect::>(); - - InputChangedResponse::from_changes(changes) - } - .instrument(span.clone()), - ) - } } impl Actor for ServersSupervisor { diff --git a/crates/bsnext_core/src/servers_supervisor/get_servers_handler.rs b/crates/bsnext_core/src/servers_supervisor/get_servers_handler.rs index 06898149..5e1e79f7 100644 --- a/crates/bsnext_core/src/servers_supervisor/get_servers_handler.rs +++ b/crates/bsnext_core/src/servers_supervisor/get_servers_handler.rs @@ -7,10 +7,8 @@ use bsnext_dto::{ActiveServer, GetActiveServersResponse}; #[rtype(result = "GetActiveServersResponse")] pub struct GetActiveServers; -impl actix::Handler for ServersSupervisor { - type Result = GetActiveServersResponse; - - fn handle(&mut self, _msg: GetActiveServers, _ctx: &mut Self::Context) -> Self::Result { +impl ServersSupervisor { + pub fn active_servers(&self) -> GetActiveServersResponse { GetActiveServersResponse { servers: self .handlers @@ -18,11 +16,19 @@ impl actix::Handler for ServersSupervisor { .map(|(identity, child_handler)| ActiveServer { identity: identity.clone(), socket_addr: child_handler.socket_addr, + content_hash: child_handler.content_hash, }) .collect(), } } } +impl actix::Handler for ServersSupervisor { + type Result = GetActiveServersResponse; + + fn handle(&mut self, _msg: GetActiveServers, _ctx: &mut Self::Context) -> Self::Result { + self.active_servers() + } +} #[derive(Debug, Clone, actix::Message)] #[rtype(result = "()")] diff --git a/crates/bsnext_core/src/servers_supervisor/input_changed_handler.rs b/crates/bsnext_core/src/servers_supervisor/input_changed_handler.rs index ddd23ee3..4f527c02 100644 --- a/crates/bsnext_core/src/servers_supervisor/input_changed_handler.rs +++ b/crates/bsnext_core/src/servers_supervisor/input_changed_handler.rs @@ -1,11 +1,22 @@ -use crate::servers_supervisor::actor::ServersSupervisor; -use actix::{Addr, AsyncContext}; +use crate::runtime_ctx::RuntimeCtx; +use crate::server::actor::ServerActor; +use crate::server::handler_listen::Listen; +use crate::server::handler_patch::Patch; +use crate::server::handler_stop::Stop; +use crate::servers_supervisor::actor::{LocalResource, ServersSupervisor}; +use actix::{Actor, Addr, AsyncContext}; +use bsnext_dto::server_events::{ + ChildCreated, ChildHandlerMinimal, ChildNotCreated, ChildNotPatched, ChildPatched, ChildResult, + PatchError, +}; use bsnext_input::Input; +use futures_util::future::join_all; +use futures_util::FutureExt; +use std::collections::{BTreeSet, HashSet}; use std::future::Future; - -use crate::server::actor::ServerActor; -use bsnext_dto::server_events::ChildResult; +use std::hash::{DefaultHasher, Hash, Hasher}; use std::pin::Pin; +use tracing::{span, Instrument, Level}; #[derive(actix::Message)] #[rtype(result = "InputChangedResponse")] @@ -28,6 +39,158 @@ impl actix::Handler for ServersSupervisor { type Result = Pin>>; fn handle(&mut self, msg: InputChanged, ctx: &mut Self::Context) -> Self::Result { - self.input_changed(ctx.address(), msg.input) + let input = msg.input; + let self_addr = ctx.address(); + let span = span!(Level::TRACE, "input_changed"); + let _guard = span.enter(); + + let existing: HashSet<_> = self.handlers.values().map(|v| v.identity.clone()).collect(); + let incoming: HashSet<_> = input.servers.iter().map(|s| s.identity.clone()).collect(); + + let startup = incoming.difference(&existing).collect::>(); + let shutdown = existing.difference(&incoming).collect::>(); + let patch = existing.intersection(&incoming).collect::>(); + + let to_skip = self + .local_resources + .inner + .iter() + .filter_map(|(server_identity, local_resource)| match local_resource { + LocalResource::Failed { .. } => Some(server_identity), + _ => None, + }) + .collect::>(); + + let shutdown_jobs = shutdown + .into_iter() + .filter_map(|identity| self.handlers.get(identity).map(ToOwned::to_owned)) + .collect::>(); + + // skip servers marked as failed + let startup = startup.difference(&to_skip).collect::>(); + let start_jobs = startup + .iter() + .filter_map(|s| { + input + .servers + .iter() + .find(|x| x.identity == ***s) + .map(ToOwned::to_owned) + }) + .collect::>(); + + let patch_jobs = patch + .iter() + .filter_map(|s| { + let child = self.handlers.get(s).map(ToOwned::to_owned); + let input = input + .servers + .iter() + .find(|x| x.identity == **s) + .map(ToOwned::to_owned); + match (child, input) { + (Some(child), Some(config)) => Some((child, config)), + _ => None, + } + }) + .collect::>(); + + Box::pin( + async move { + let shutdown_futs = shutdown_jobs.iter().map(|x| x.actor_address.send(Stop)); + let shutdown_results = join_all(shutdown_futs).await; + let shutdown_child_results = + shutdown_results + .iter() + .zip(shutdown_jobs) + .map(|(r, h)| match r { + Ok(_) => (None, ChildResult::Stopped(h.identity.clone())), + Err(er) => unreachable!("{}", er), + }); + + tracing::debug!("starting {:?} servers", start_jobs.len()); + let fts = start_jobs.into_iter().map(|server_config| { + let server = ServerActor::new_from_config(server_config.clone()); + let actor_addr = server.start(); + let actor_addr_c = actor_addr.clone(); + let original_config = server_config.clone(); + actor_addr + .send(Listen { + // todo: tie this to the input somehow? + runtime_ctx: RuntimeCtx::default(), + parent: self_addr.clone().recipient(), + evt_receiver: self_addr.clone().recipient(), + }) + .map(|r| (r, original_config, actor_addr_c)) + }); + let results = join_all(fts).await; + let start_child_results = results.into_iter().map(|(r, c, addr)| match r { + Ok(Ok(socket_addr)) => { + let mut hasher = DefaultHasher::new(); + c.hash(&mut hasher); + let content_hash = hasher.finish(); + let evt = ChildResult::Created(ChildCreated { + server_handler: ChildHandlerMinimal { + identity: c.identity, + socket_addr, + content_hash, + }, + }); + (Some(addr), evt) + } + Ok(Err(err)) => { + let evt = ChildResult::CreateErr(ChildNotCreated { + server_error: err, + identity: c.identity.clone(), + }); + (None, evt) + } + Err(e) => unreachable!("{}", e), + }); + + let patch_futures = patch_jobs.into_iter().map(|(child, server_config)| { + let mut hasher = DefaultHasher::new(); + server_config.hash(&mut hasher); + let content_hash = hasher.finish(); + child + .actor_address + .send(Patch { server_config }) + .map(move |r| (r, child, content_hash)) + }); + let results = join_all(patch_futures).await; + let patch_child_results = + results + .into_iter() + .map(|(r, child_handler, next_content_hash)| match r { + Ok(Ok((route_change_set, client_config_change_set))) => { + let evt = ChildResult::Patched(ChildPatched { + server_handler: child_handler.minimal(), + route_change_set, + client_config_change_set, + next_content_hash, + }); + (Some(child_handler.actor_address), evt) + } + Ok(Err(err)) => { + let evt = ChildResult::PatchErr(ChildNotPatched { + patch_error: PatchError::DidNotPatch { + reason: err.to_string(), + }, + identity: child_handler.identity.clone(), + }); + (None, evt) + } + Err(_) => unreachable!("mailbox error on patch"), + }); + + let changes = shutdown_child_results + .chain(start_child_results) + .chain(patch_child_results) + .collect::>(); + + InputChangedResponse::from_changes(changes) + } + .instrument(span.clone()), + ) } } diff --git a/crates/bsnext_core/src/servers_supervisor/mod.rs b/crates/bsnext_core/src/servers_supervisor/mod.rs index 18321c6d..f5a8e73b 100644 --- a/crates/bsnext_core/src/servers_supervisor/mod.rs +++ b/crates/bsnext_core/src/servers_supervisor/mod.rs @@ -3,5 +3,3 @@ pub mod file_changed_handler; pub mod get_servers_handler; pub mod input_changed_handler; pub mod resolve_servers; -pub mod start_handler; -pub mod stop_handler; diff --git a/crates/bsnext_core/src/servers_supervisor/resolve_servers.rs b/crates/bsnext_core/src/servers_supervisor/resolve_servers.rs index ab5c489e..d518492a 100644 --- a/crates/bsnext_core/src/servers_supervisor/resolve_servers.rs +++ b/crates/bsnext_core/src/servers_supervisor/resolve_servers.rs @@ -1,69 +1,266 @@ use crate::server::handler_client_config::ClientConfigChange; use crate::server::handler_routes_updated::RoutesUpdated; -use crate::servers_supervisor::actor::{ChildHandler, ChildStopped, ServersSupervisor}; -use crate::servers_supervisor::get_servers_handler::GetActiveServers; +use crate::servers_supervisor::actor::{ChildHandler, LocalResource, ServersSupervisor}; use crate::servers_supervisor::input_changed_handler::InputChanged; -use crate::servers_supervisor::start_handler::ChildCreatedInsert; -use actix::{Addr, AsyncContext, ResponseFuture}; -use bsnext_dto::any_event::AnyEvent; -use bsnext_dto::external_events::ExternalEventsDTO; -use bsnext_dto::server_events::{ChildResult, ServerError}; -use bsnext_dto::{GetActiveServersResponse, ServerChangesetDTO}; +use actix::ActorFutureExt; +use actix::{AsyncContext, ResponseActFuture, WrapFuture}; +use axum::middleware::Next; +use bsnext_dto::server_events::ChildResult; +use bsnext_dto::status_events::{ + server_status_hash, ServerStatusReader, ServerStatusWriter, ServiceStatus, StateValue, +}; +use bsnext_input::server_config::ServerConfig; use bsnext_input::Input; +use std::collections::HashMap; +use std::time::Duration; use tracing::debug; #[derive(actix::Message)] -#[rtype(result = "Result<(), ServerError>")] -pub struct ResolveServers { - input: Input, +#[rtype(result = "Result<(), anyhow::Error>")] +pub struct ResolveServers; + +impl Default for ResolveServers { + fn default() -> Self { + Self::new() + } } impl ResolveServers { - pub fn new(input: Input) -> Self { - Self { input } + pub fn new() -> Self { + ResolveServers } } impl actix::Handler for ServersSupervisor { - type Result = ResponseFuture>; + type Result = ResponseActFuture>; - #[tracing::instrument(skip_all, name = "Handler->ResolveServers->BsSystem")] - fn handle(&mut self, msg: ResolveServers, ctx: &mut Self::Context) -> Self::Result { - // let external_event_sender = self.sender().clone(); - let addr = ctx.address(); - let sender = self.ex_sender.clone(); + #[tracing::instrument(skip_all, name = "Handler->ResolveServers->ServersSupervisor")] + fn handle(&mut self, _msg: ResolveServers, ctx: &mut Self::Context) -> Self::Result { + let _addr = ctx.address(); + let _sender = self.sender.clone(); + let local_status = self.status; + let _state_writer = self.state_writer.clone(); + let state_reader = self.state_reader.clone(); let f = async move { - debug!("will mark input as changed or new"); - let results = addr.send(InputChanged { input: msg.input }).await; + tracing::info!("will ask for server input..."); + + let (sys_server_status, input) = state_reader.send(ServerStatusReader).await?; + if let (ServiceStatus::Ready { .. }, ServiceStatus::Ready { .. }) = + (sys_server_status, local_status) + { + tracing::info!("doing nothing, sys + local state match"); + tracing::info!(?sys_server_status); + tracing::info!(?local_status); + return Ok(None); + } - let Ok(result_set) = results else { - let e = results.unwrap_err(); - unreachable!("?1 {:?}", e); + let expected_id = match sys_server_status { + ServiceStatus::Idle => todo!("how can we get here?"), + ServiceStatus::Reconciling { desired, .. } => desired, + ServiceStatus::Ready { observed } => observed, + ServiceStatus::Degraded { desired } => desired, }; - debug!( - "result_set from resolve servers {}", - result_set.changes.len() - ); + Ok(Some((expected_id, input))) + }; + + Box::pin( + f.into_actor(self) + .map(move |res: anyhow::Result<_>, actor, ctx| { + match res? { + Some((desired, input)) => { + tracing::debug!("+++ There's something to reconcile..."); + actor.status = ServiceStatus::Reconciling { + desired, + observed: actor.status.observed(), + }; + actor.reconcile_count += 1; + ctx.notify(TryReconcile { input }); + } + None => { + tracing::debug!("--- we decided there's nothing to do because local and remote states match") + } + } + + // dbg!(&desired); + // dbg!(&act.status); + // dbg!(res); + // match res { + // Err(e) => { + // tracing::info!(e = ?e, "got error?"); + // return Ok(()); + // } + // Ok(None) => { + // tracing::info!("got None, returning with nothing to do...?"); + // return Ok(()); + // } + // Ok(Some((desired, result_set))) => { + // tracing::info!("got result_set"); + // debug!( + // "result_set from resolve servers {}", + // result_set.changes.len() + // ); + // + // for (maybe_addr, x) in &result_set.changes { + // match x { + // ChildResult::Stopped(id) => { + // act.handlers.remove(id); + // } + // ChildResult::Created(c) if maybe_addr.is_some() => { + // let child_handler = ChildHandler { + // actor_address: maybe_addr.clone().expect("guarded above"), + // identity: c.server_handler.identity.clone(), + // socket_addr: c.server_handler.socket_addr, + // content_hash: c.server_handler.content_hash, + // }; + // act.handlers + // .insert(child_handler.identity.clone(), child_handler.clone()); + // } + // ChildResult::Created(_c) => { + // unreachable!("can't be created without") + // } + // ChildResult::Patched(p) if maybe_addr.is_some() => { + // // todo: must mark new content_id... + // tracing::info!( + // content_hash = p.server_handler.content_hash, + // next_content_hash = p.next_content_hash, + // "next--" + // ); + // if let Some(t) = act.handlers.get_mut(&p.server_handler.identity) { + // t.content_hash = p.next_content_hash; + // } + // if let Some(child_actor) = maybe_addr { + // child_actor.do_send(ClientConfigChange { + // change_set: p.client_config_change_set.clone(), + // }); + // child_actor.do_send(RoutesUpdated { + // change_set: p.route_change_set.clone(), + // }) + // } else { + // tracing::error!("missing actor addr where it was needed") + // } + // } + // ChildResult::Patched(p) => { + // debug!("ChildResult::Patched {:?}", p); + // } + // ChildResult::PatchErr(e) => { + // debug!("ChildResult::PatchErr {:?}", e); + // } + // ChildResult::CreateErr(e) => { + // debug!("ChildResult::CreateErr {:?}", e); + // } + // } + // } + // + // let res: Vec = result_set + // .changes + // .into_iter() + // .map(|(_, child_result)| child_result) + // .collect(); + // + // let resp = act.active_servers(); + // let observed = StateValue::new(active_server_status_hash(&resp.servers)); + // let len = resp.servers.len(); + // + // if observed == desired { + // act.status = ServiceStatus::Ready { observed }; + // } else { + // // todo!("will set to reconciling... but is it?"); + // act.status = ServiceStatus::Reconciling { + // desired, + // observed: Some(observed), + // }; + // } + // + // state_writer.do_send(ServerStatusWriter { + // servers_status: act.status, + // server_resource_status: HashMap::default(), + // }); + // + // ctx.notify_later(ResolveServers, Duration::from_millis(1000)); + // + // // Arbiter::current().spawn({ + // // let dto = ServerChangesetDTO::from_changes(&resp, &res); + // // async move { + // // let _ = sender + // // .send(AnyEvent::External(ExternalEventsDTO::ServerChangeset(dto))) + // // .await; + // // } + // // }); + // } + // } + Ok(()) + }), + ) + } +} + +#[derive(actix::Message)] +#[rtype(result = "Result<(), anyhow::Error>")] +struct TryReconcile { + input: Input, +} + +impl actix::Handler for ServersSupervisor { + type Result = ResponseActFuture>; - for (maybe_addr, x) in &result_set.changes { - match x { - ChildResult::Stopped(id) => addr.do_send(ChildStopped { - identity: id.clone(), - }), + fn handle(&mut self, msg: TryReconcile, ctx: &mut Self::Context) -> Self::Result { + let state_writer = self.state_writer.clone(); + let ids = msg + .input + .servers + .iter() + .map(|x| x.identity.clone()) + .collect::>(); + let mapping = msg + .input + .servers + .iter() + .map(|s| (s.identity.clone(), s.clone())) + .collect::>(); + for server_config in &msg.input.servers { + self.local_resources + .inner + .entry(server_config.identity.clone()) + .or_default(); + } + let evt = ServerStatusWriter { + servers_status: self.status, + server_resource_status: self.local_resources.as_resource_status(), + }; + state_writer.do_send(evt); + let f = ctx.address().send(InputChanged { input: msg.input }); + Box::pin(f.into_actor(self).map(move |res, act, ctx| { + let res = res?; + for (maybe_addr, child_result) in &res.changes { + match &child_result { + ChildResult::Stopped(id) => { + act.handlers.remove(id); + } ChildResult::Created(c) if maybe_addr.is_some() => { let child_handler = ChildHandler { actor_address: maybe_addr.clone().expect("guarded above"), identity: c.server_handler.identity.clone(), socket_addr: c.server_handler.socket_addr, + content_hash: c.server_handler.content_hash, }; - addr.do_send(ChildCreatedInsert { child_handler }) + act.handlers + .insert(child_handler.identity.clone(), child_handler.clone()); } ChildResult::Created(_c) => { unreachable!("can't be created without") } ChildResult::Patched(p) if maybe_addr.is_some() => { + // todo: must mark new content_id... + tracing::info!( + content_hash = p.server_handler.content_hash, + next_content_hash = p.next_content_hash, + "next--" + ); + if let Some(t) = act.handlers.get_mut(&p.server_handler.identity) { + t.content_hash = p.next_content_hash; + } if let Some(child_actor) = maybe_addr { child_actor.do_send(ClientConfigChange { change_set: p.client_config_change_set.clone(), @@ -87,31 +284,86 @@ impl actix::Handler for ServersSupervisor { } } - let res: Vec = result_set - .changes - .into_iter() - .map(|(_, child_result)| child_result) - .collect(); + // for (identity, handler) in &act.handlers {} + for server_id in ids { + let maybe_handler = act.handlers.get(&server_id); + let prev_local = act.local_resources.inner.get(&server_id).expect("how?"); + let next: LocalResource = match (maybe_handler, prev_local) { + (Some(..), ..) => LocalResource::Ready, + (None, LocalResource::Pending) => LocalResource::Waiting { + reason: "was pending...".to_string(), + attempts: 1, + }, + (None, LocalResource::Waiting { attempts, .. }) if *attempts == 5 => { + LocalResource::Failed { + reason: "max attempts reached".to_string(), + } + } + (None, LocalResource::Waiting { attempts, .. }) => LocalResource::Waiting { + reason: "didn't start".to_string(), + attempts: attempts + 1, + }, + (None, LocalResource::Ready) => LocalResource::Waiting { + reason: "was ready, lost?".to_string(), + attempts: 0, + }, + (None, LocalResource::Failed { reason, .. }) => LocalResource::Failed { + reason: reason.to_string(), + }, + }; + act.local_resources.inner.insert(server_id, next); + } - let (resp, res) = get_servers(addr, res) - .await - .map_err(|e| ServerError::Unknown(e.to_string()))?; + let hashes = act + .handlers + .keys() + .filter_map(|x| mapping.get(x).map(ToOwned::to_owned)) + .collect::>(); - let dto = ServerChangesetDTO::from_changes(&resp, &res); - let _ = sender - .send(AnyEvent::External(ExternalEventsDTO::ServerChangeset(dto))) - .await; - Ok(()) - }; + let list = server_status_hash(hashes.as_slice()); + let observed_local = StateValue::new(list); + let is_good = act.status.is(&observed_local); + let should_reconcile = act.local_resources.should_reconcile(); - Box::pin(f) + act.status.set_next(&observed_local, should_reconcile); + + state_writer.do_send(ServerStatusWriter { + servers_status: act.status, + server_resource_status: act.local_resources.as_resource_status(), + }); + + todo!("must choose how/when to reconcile based on child resource status"); + // match reconcile_after(&act.status) { + // NextReconcile::None => {} + // NextReconcile::Duration { duration } => { + // ctx.notify_later( + // ReconcileLater { + // prev: act.reconcile_count, + // }, + // duration, + // ); + // } + // } + + Ok(()) + })) } } -async fn get_servers( - addr: Addr, - results: Vec, -) -> anyhow::Result<(GetActiveServersResponse, Vec)> { - let resp = addr.send(GetActiveServers).await?; - Ok((resp, results)) +#[derive(Debug, Hash, Clone, Copy, actix::Message)] +#[rtype(result = "()")] +struct ReconcileLater { + prev: usize, +} + +impl actix::Handler for ServersSupervisor { + type Result = (); + + fn handle(&mut self, msg: ReconcileLater, ctx: &mut Self::Context) -> Self::Result { + if msg.prev != self.reconcile_count { + tracing::debug!(?msg.prev, ?self.reconcile_count, "bail"); + return (); + } + ctx.notify(ResolveServers) + } } diff --git a/crates/bsnext_core/src/servers_supervisor/start_handler.rs b/crates/bsnext_core/src/servers_supervisor/start_handler.rs deleted file mode 100644 index 2ab36810..00000000 --- a/crates/bsnext_core/src/servers_supervisor/start_handler.rs +++ /dev/null @@ -1,32 +0,0 @@ -use crate::servers_supervisor::actor::{ChildHandler, ServersSupervisor}; -use bsnext_dto::server_events::ChildNotCreated; - -#[derive(actix::Message)] -#[rtype(result = "()")] -pub struct ChildCreatedInsert { - pub child_handler: ChildHandler, -} - -impl actix::Handler for ServersSupervisor { - type Result = (); - - fn handle(&mut self, msg: ChildCreatedInsert, _ctx: &mut Self::Context) -> Self::Result { - self.handlers.insert( - msg.child_handler.identity.clone(), - msg.child_handler.clone(), - ); - tracing::trace!("ChildCreated child count: {}", self.handlers.len()); - } -} - -impl actix::Handler for ServersSupervisor { - type Result = (); - - fn handle(&mut self, _msg: ChildNotCreated, _ctx: &mut Self::Context) -> Self::Result { - // self.handlers.insert( - // msg.server_handler.identity.clone(), - // msg.server_handler.clone(), - // ); - // tracing::trace!("ChildCreated child count: {}", self.handlers.len()); - } -} diff --git a/crates/bsnext_core/src/servers_supervisor/stop_handler.rs b/crates/bsnext_core/src/servers_supervisor/stop_handler.rs deleted file mode 100644 index 93bd1536..00000000 --- a/crates/bsnext_core/src/servers_supervisor/stop_handler.rs +++ /dev/null @@ -1,26 +0,0 @@ -use crate::server::handler_stop::Stop; -use crate::servers_supervisor::actor::ServersSupervisor; -use futures_util::future::join_all; -use std::future::Future; -use std::pin::Pin; - -#[derive(actix::Message)] -#[rtype(result = "()")] -pub struct StopServers; - -impl actix::Handler for ServersSupervisor { - type Result = Pin>>; - - fn handle(&mut self, _msg: StopServers, _ctx: &mut Self::Context) -> Self::Result { - let aaddresses = self.handlers.clone(); - - Box::pin(async move { - tracing::debug!("stopping {} servers", aaddresses.len()); - let fts = aaddresses - .values() - .map(|handler| handler.actor_address.send(Stop)) - .collect::>(); - join_all(fts).await; - }) - } -} diff --git a/crates/bsnext_dto/Cargo.toml b/crates/bsnext_dto/Cargo.toml index e7fc7efe..4cd848a8 100644 --- a/crates/bsnext_dto/Cargo.toml +++ b/crates/bsnext_dto/Cargo.toml @@ -20,3 +20,4 @@ typeshare = { workspace = true } anyhow = { workspace = true } miette = { workspace = true } tracing = { workspace = true } +console = { version = "0.16.6" } diff --git a/crates/bsnext_dto/src/external_events.rs b/crates/bsnext_dto/src/external_events.rs index 109c8575..fcbd15f1 100644 --- a/crates/bsnext_dto/src/external_events.rs +++ b/crates/bsnext_dto/src/external_events.rs @@ -1,13 +1,15 @@ use crate::any_event::AnyEvent; use crate::archy::{archy, overlay_results, ArchyNode, Prefix}; +use crate::status_events_dto::{ResourceStatus, TransitionDTO}; use crate::{ FileChangedDTO, FilesChangedDTO, InputAcceptedDTO, InputErrorDetailDTO, OutputLineDTO, ServerChangeDTO, ServerChangesetDTO, ServerIdentityDTO, StartupErrorDTO, StderrLineDTO, - StdoutLineDTO, StoppedWatchingDTO, WatchingDTO, + StdoutLineDTO, }; -use bsnext_output::OutputWriterTrait; +use bsnext_output::{OutputGlobalPrefix, OutputWriterTrait}; use bsnext_task::task_report::TaskReport; use bsnext_task::NodePath; +use console::style; use std::collections::HashMap; use std::io::Write; use std::path::PathBuf; @@ -29,8 +31,7 @@ pub enum ExternalEventsDTO { TaskAction(TaskActionDTO), TaskTreePreview(TaskTreePreview), TaskTreeSummary(TaskTreeSummary), - Watching(WatchingDTO), - WatchingStopped(StoppedWatchingDTO), + Transition(TransitionDTO), } #[typeshare] @@ -127,10 +128,12 @@ impl OutputWriterTrait for ExternalEventsDTO { .map_err(|e| anyhow::anyhow!(e.to_string())) } - fn write_pretty(&self, sink: &mut W) -> anyhow::Result<()> { + fn write_pretty( + &self, + output_global_prefix: &OutputGlobalPrefix, + sink: &mut W, + ) -> anyhow::Result<()> { match self { - ExternalEventsDTO::Watching(watching) => print_watching(sink, watching), - ExternalEventsDTO::WatchingStopped(watching) => print_stopped_watching(sink, watching), ExternalEventsDTO::InputAccepted(input_accepted) => { print_input_accepted(sink, input_accepted) } @@ -142,7 +145,7 @@ impl OutputWriterTrait for ExternalEventsDTO { print_input_file_changed(sink, file_changed) } ExternalEventsDTO::OutputLine(OutputLineDTO::Stdout(stdout)) => { - print_stdout_line(sink, stdout) + print_stdout_line(sink, output_global_prefix, stdout) } ExternalEventsDTO::OutputLine(OutputLineDTO::Stderr(stderr)) => { print_stderr_line(sink, stderr) @@ -169,15 +172,46 @@ impl OutputWriterTrait for ExternalEventsDTO { Ok(()) } ExternalEventsDTO::InputError(InputErrorDetailDTO { error }) => { - writeln!(sink, "{error}")?; + writeln!(sink, "{} {error}", style("[warning]").on_yellow())?; Ok(()) } ExternalEventsDTO::StartupError(StartupErrorDTO { error }) => { - writeln!(sink, "{error}")?; + writeln!(sink, "{} {error}", style("[error]").on_red())?; Ok(()) + } // ExternalEventsDTO::Transition() => {} + ExternalEventsDTO::Transition(trans) => print_transition(sink, trans), + } + } +} + +fn print_transition(w: &mut W, trans: &TransitionDTO) -> anyhow::Result<()> { + match trans { + TransitionDTO::Server(server_dto) => { + // let server_display = server_display(server_dto.server, server_dto.) + // write!(w, "{}", server_dto.server)? + dbg!(server_dto); + } + TransitionDTO::PathMonitor(path_monitor_dto) => { + let dir = path_monitor_dto.watchable.display_paths(); + let debounce = &path_monitor_dto.debounce; + match &path_monitor_dto.status { + ResourceStatus::Pending => todo!("can we be pending here?"), + ResourceStatus::Waiting { reason } => { + // todo: ("here we need to ensure input monitor is counted as a resource now"); + let prefix = style(format!("[waiting: {reason}]")).on_yellow(); + writeln!(w, "{prefix} {dir}")?; + } + ResourceStatus::Ready => { + writeln!(w, "[watching {debounce}] {dir}")?; + } + ResourceStatus::Failed { reason } => { + let prefix = style(format!("[failed: {reason}]")).on_red(); + writeln!(w, "{prefix} {dir}")?; + } } } } + Ok(()) } fn print_task_tree(w: &mut W, tree: &ArchyNode) -> anyhow::Result<()> { @@ -204,13 +238,6 @@ fn print_task_tree_summary( Ok(()) } -pub fn print_stopped_watching(w: &mut W, evt: &StoppedWatchingDTO) -> anyhow::Result<()> { - for x in &evt.paths { - writeln!(w, "[watching:stopped] {x}")?; - } - Ok(()) -} - pub fn print_input_accepted(w: &mut W, evt: &InputAcceptedDTO) -> anyhow::Result<()> { writeln!(w, "[input] {}", evt.path)?; Ok(()) @@ -245,12 +272,20 @@ pub fn print_input_file_changed(w: &mut W, evt: &FileChangedDTO) -> an Ok(()) } -pub fn print_stdout_line(w: &mut W, line: &StdoutLineDTO) -> anyhow::Result<()> { - match &line.prefix { - None => writeln!(w, "{}", line.line)?, - Some(prefix) => { - let color = hash(prefix) % 256; - writeln!(w, "\x1b[38;5;{}m{}\x1b[0m {}", color, prefix, line.line)? +pub fn print_stdout_line( + w: &mut W, + global_prefix: &OutputGlobalPrefix, + line: &StdoutLineDTO, +) -> anyhow::Result<()> { + if matches!(global_prefix, OutputGlobalPrefix::None) { + writeln!(w, "{}", line.line)? + } else { + match &line.prefix { + None => writeln!(w, "{}", line.line)?, + Some(prefix) => { + let color = hash(prefix) % 256; + writeln!(w, "\x1b[38;5;{}m{}\x1b[0m {}", color, prefix, line.line)? + } } } Ok(()) @@ -307,13 +342,6 @@ pub fn short_file_list>(paths: &[A]) -> String { file_names.join(", ") } -pub fn print_watching(w: &mut W, evt: &WatchingDTO) -> anyhow::Result<()> { - for x in &evt.paths { - writeln!(w, "[watching {}] {}", evt.debounce, x)?; - } - Ok(()) -} - pub fn has_output_line_matching(events: &[AnyEvent], expected: &str) -> bool { events.iter().any(|e| { matches!(e, AnyEvent::External(ExternalEventsDTO::OutputLine(OutputLineDTO::Stdout( diff --git a/crates/bsnext_dto/src/lib.rs b/crates/bsnext_dto/src/lib.rs index aeb1bd1a..7ed58622 100644 --- a/crates/bsnext_dto/src/lib.rs +++ b/crates/bsnext_dto/src/lib.rs @@ -22,6 +22,9 @@ pub mod server_events; pub mod startup_events; pub mod task_events; +pub mod status_events; +pub mod status_events_dto; + #[typeshare] #[derive(Debug, serde::Serialize)] pub struct ServerDesc { @@ -298,33 +301,6 @@ pub struct FilesChangedDTO { pub paths: Vec, } -#[typeshare] -#[derive(Debug, Clone, serde::Serialize)] -pub struct WatchingDTO { - pub paths: Vec, - pub debounce: DebounceDTO, -} - -#[typeshare] -#[derive(Debug, Clone, serde::Serialize)] -pub struct StoppedWatchingDTO { - pub paths: Vec, -} - -impl StoppedWatchingDTO { - pub fn from_path_buf(p: &Path) -> Self { - Self { - paths: vec![p.to_string_lossy().to_string()], - } - } -} - -impl Display for WatchingDTO { - fn fmt(&self, f: &mut Formatter<'_>) -> std::fmt::Result { - write!(f, "yo") - } -} - #[typeshare] #[derive(Debug, Clone, serde::Serialize)] pub struct DebounceDTO { @@ -361,15 +337,6 @@ impl FileChangedDTO { } } -impl WatchingDTO { - pub fn from_path_buf(p: &Path, debounce: Debounce) -> Self { - Self { - paths: vec![p.to_string_lossy().to_string()], - debounce: debounce.into(), - } - } -} - /// @discriminator kind #[typeshare] #[derive(Debug, Clone, serde::Serialize)] @@ -447,6 +414,7 @@ impl From<&ActiveServer> for ServerDTO { #[derive(Debug, Clone)] pub struct ActiveServer { pub identity: ServerIdentity, + pub content_hash: u64, pub socket_addr: SocketAddr, } diff --git a/crates/bsnext_dto/src/server_events.rs b/crates/bsnext_dto/src/server_events.rs index 21e1de5c..99d9e7e9 100644 --- a/crates/bsnext_dto/src/server_events.rs +++ b/crates/bsnext_dto/src/server_events.rs @@ -5,6 +5,7 @@ use std::net::SocketAddr; pub struct ChildHandlerMinimal { pub identity: ServerIdentity, pub socket_addr: SocketAddr, + pub content_hash: u64, } #[derive(Debug, Clone, actix::Message)] @@ -17,6 +18,7 @@ pub struct ChildCreated { #[rtype(result = "()")] pub struct ChildPatched { pub server_handler: ChildHandlerMinimal, + pub next_content_hash: u64, pub route_change_set: bsnext_input::route_manifest::RouteChangeSet, pub client_config_change_set: bsnext_input::client_config::ClientConfigChangeSet, } @@ -60,6 +62,16 @@ impl ChildResult { ChildResult::Stopped(_) => None, } } + pub fn identity(&self) -> ServerIdentity { + let id: &ServerIdentity = match &self { + ChildResult::Created(created) => &created.server_handler.identity, + ChildResult::CreateErr(err) => &err.identity, + ChildResult::Patched(patched) => &patched.server_handler.identity, + ChildResult::PatchErr(err) => &err.identity, + ChildResult::Stopped(server_identity) => server_identity, + }; + id.to_owned() + } } #[derive(Debug, Clone, serde::Serialize, serde::Deserialize, thiserror::Error)] diff --git a/crates/bsnext_dto/src/startup_events.rs b/crates/bsnext_dto/src/startup_events.rs index 9f9e12e6..ecaf3497 100644 --- a/crates/bsnext_dto/src/startup_events.rs +++ b/crates/bsnext_dto/src/startup_events.rs @@ -1,6 +1,6 @@ use crate::{StartupError, StartupEventDTO}; use bsnext_input::InputError; -use bsnext_output::OutputWriterTrait; +use bsnext_output::{OutputGlobalPrefix, OutputWriterTrait}; use std::io::Write; impl OutputWriterTrait for StartupEvent { @@ -10,7 +10,11 @@ impl OutputWriterTrait for StartupEvent { .map_err(|e| anyhow::anyhow!(e.to_string())) } - fn write_pretty(&self, sink: &mut W) -> anyhow::Result<()> { + fn write_pretty( + &self, + _global_prefix: &OutputGlobalPrefix, + sink: &mut W, + ) -> anyhow::Result<()> { match self { StartupEvent::Started => { writeln!(sink, "started...")?; diff --git a/crates/bsnext_dto/src/status_events.rs b/crates/bsnext_dto/src/status_events.rs new file mode 100644 index 00000000..c0ee3cbe --- /dev/null +++ b/crates/bsnext_dto/src/status_events.rs @@ -0,0 +1,228 @@ +use crate::status_events_dto::ResourceStatus; +use crate::ActiveServer; +use bsnext_input::input_src::InputSrc; +use bsnext_input::server_config::{ServerConfig, ServerIdentity}; +use bsnext_input::watchables::path_watchable::PathWatchable; +use bsnext_input::watchables::PathWatchables; +use bsnext_input::Input; +use std::collections::HashMap; +use std::hash::{DefaultHasher, Hash, Hasher}; +use std::time::Duration; + +#[derive(Debug, actix::Message)] +#[rtype(result = "(ServiceStatus, Input)")] +pub struct ServerStatusReader; + +#[derive(Debug, actix::Message)] +#[rtype(result = "()")] +pub struct ServerStatusWriter { + pub servers_status: ServiceStatus, + pub server_resource_status: HashMap, +} + +#[derive(Debug, actix::Message)] +#[rtype(result = "(ServiceStatus, Input, Vec)")] +pub struct MonitorStatusReader; + +#[derive(Debug, actix::Message)] +#[rtype(result = "()")] +pub struct MonitorStatusWriter { + pub monitor_status: ServiceStatus, + pub monitor_resource_status: HashMap, +} + +/// This is the event we'll broadcast, it will grow with more sub systems +#[derive(Debug)] +pub enum Transition { + Server(ServerResource), + PathMonitor(PathMonitorResource), +} + +impl Transition { + pub fn path_monitor(status: ResourceStatus, watchable: PathWatchable) -> Self { + Transition::PathMonitor(PathMonitorResource::new(status, watchable)) + } +} + +#[derive(Debug)] +pub struct ServerResource { + pub status: ResourceStatus, + pub server: ServerIdentity, +} + +#[derive(Debug)] +pub struct PathMonitorResource { + pub status: ResourceStatus, + pub watchable: PathWatchable, +} + +impl PathMonitorResource { + pub fn new(status: ResourceStatus, watchable: PathWatchable) -> Self { + Self { status, watchable } + } +} + +#[derive(Debug, Clone, Hash, Copy, Eq, Ord, PartialEq, PartialOrd)] +pub struct StateValue { + value: u64, +} + +impl StateValue { + pub fn new(value: u64) -> Self { + Self { value } + } +} + +#[derive(Debug, Default, Clone, Hash, Copy, Eq, PartialEq, Ord, PartialOrd)] +pub enum ServiceStatus { + #[default] + Idle, + Reconciling { + desired: StateValue, + observed: Option, + }, + Degraded { + desired: StateValue, + }, + Ready { + observed: StateValue, + }, +} + +impl ServiceStatus { + pub fn observed(&self) -> Option { + match self { + ServiceStatus::Idle => None, + ServiceStatus::Reconciling { observed, .. } => *observed, + ServiceStatus::Ready { observed, .. } => Some(*observed), + ServiceStatus::Degraded { .. } => None, + } + } + pub fn is(&self, next_status: &StateValue) -> bool { + match self { + ServiceStatus::Idle => false, + ServiceStatus::Degraded { .. } => false, + ServiceStatus::Reconciling { observed: None, .. } => false, + ServiceStatus::Reconciling { + observed: Some(observed), + .. + } => observed == next_status, + ServiceStatus::Ready { observed, .. } => observed == next_status, + } + } + pub fn set_next(&mut self, observed_local: &StateValue, should_reconcile: bool) { + let next = match self { + ServiceStatus::Idle => self.clone(), + ServiceStatus::Reconciling { desired, .. } if desired == observed_local => { + tracing::debug!("will set ready, desired matched local"); + ServiceStatus::Ready { + observed: observed_local.to_owned(), + } + } + ServiceStatus::Reconciling { + desired, + observed: _, + } if should_reconcile => { + tracing::debug!("still reconciling, but now it's a new thing"); + ServiceStatus::Reconciling { + desired: desired.to_owned(), + observed: Some(observed_local.to_owned()), + } + } + ServiceStatus::Reconciling { desired, observed } => { + tracing::debug!(?desired, ?observed, "marking as degraded"); + ServiceStatus::Degraded { + desired: desired.to_owned(), + } + } + ServiceStatus::Degraded { desired } => { + todo!("what to do when already degraded?") + } + ServiceStatus::Ready { observed } if observed == observed_local => { + tracing::debug!("nothing to do!"); + todo!("not here"); + } + ServiceStatus::Ready { observed } => { + tracing::debug!("downgrading to reconciling"); + ServiceStatus::Reconciling { + desired: observed_local.to_owned(), + observed: Some(observed.to_owned()), + } + } + }; + *self = next; + } +} + +#[derive(Debug, Default, Clone, Hash, Copy)] +pub enum NextReconcile { + #[default] + None, + Duration { + duration: Duration, + }, +} + +fn reconcile_after(service_status: &ServiceStatus) -> NextReconcile { + match service_status { + ServiceStatus::Reconciling { .. } => NextReconcile::Duration { + duration: Duration::from_secs(1), + }, + ServiceStatus::Degraded { .. } => NextReconcile::Duration { + duration: Duration::from_secs(10), + }, + ServiceStatus::Idle => NextReconcile::None, + ServiceStatus::Ready { .. } => NextReconcile::None, + } +} + +pub fn server_status_hash(servers: &[ServerConfig]) -> u64 { + let mut identities = servers + .iter() + .map(|x| { + let mut hasher = DefaultHasher::new(); + x.hash(&mut hasher); + hasher.finish() + }) + .collect::>(); + identities.sort_unstable(); + + let mut hasher = DefaultHasher::new(); + identities.hash(&mut hasher); + hasher.finish() +} + +pub fn monitor_status_hash(path_watchables: &PathWatchables) -> u64 { + let mut identities = path_watchables + .watchables + .iter() + .map(|x| { + let mut hasher = DefaultHasher::new(); + x.hash(&mut hasher); + hasher.finish() + }) + .collect::>(); + identities.sort_unstable(); + + let mut hasher = DefaultHasher::new(); + identities.hash(&mut hasher); + hasher.finish() +} + +pub fn list_hash(items: &[u64]) -> u64 { + let mut identities = items.iter().collect::>(); + identities.sort_unstable(); + + let mut hasher = DefaultHasher::new(); + identities.hash(&mut hasher); + hasher.finish() +} + +pub fn active_server_status_hash(servers: &[ActiveServer]) -> u64 { + let mut identities = servers.iter().map(|x| x.content_hash).collect::>(); + identities.sort_unstable(); + + let mut hasher = DefaultHasher::new(); + identities.hash(&mut hasher); + hasher.finish() +} diff --git a/crates/bsnext_dto/src/status_events_dto.rs b/crates/bsnext_dto/src/status_events_dto.rs new file mode 100644 index 00000000..b8858978 --- /dev/null +++ b/crates/bsnext_dto/src/status_events_dto.rs @@ -0,0 +1,164 @@ +use crate::status_events::Transition; +use crate::{DebounceDTO, ServerIdentityDTO}; +use bsnext_input::watchables::path_watchable::PathWatchable; +use typeshare::typeshare; + +/// @discriminator kind +#[typeshare] +#[derive(Debug, serde::Serialize, Clone)] +#[serde(tag = "kind", content = "payload")] +pub enum TransitionDTO { + Server(ServerResourceDTO), + PathMonitor(PathMonitorResourceDTO), +} + +impl From for TransitionDTO { + fn from(value: Transition) -> Self { + match value { + Transition::Server(server_resource) => Self::Server(ServerResourceDTO { + server: ServerIdentityDTO::from(&server_resource.server), + status: server_resource.status, + }), + Transition::PathMonitor(path_monitor_resource) => { + Self::PathMonitor(PathMonitorResourceDTO { + status: path_monitor_resource.status, + watchable: PathWatchableDTO::from(&path_monitor_resource.watchable), + debounce: DebounceDTO::from(path_monitor_resource.watchable.debounce()), + }) + } + } + } +} + +#[typeshare] +#[derive(Debug, serde::Serialize, Clone)] +pub struct ServerResourceDTO { + pub status: ResourceStatus, + pub server: ServerIdentityDTO, +} + +#[typeshare] +#[derive(Debug, serde::Serialize, Clone)] +pub struct PathMonitorResourceDTO { + pub status: ResourceStatus, + pub watchable: PathWatchableDTO, + pub debounce: DebounceDTO, +} + +/// @discriminator kind +#[typeshare] +#[derive(Debug, serde::Serialize, Clone)] +#[serde(tag = "kind", content = "payload")] +pub enum PathWatchableDTO { + Server(ServerWatchableDTO), + Route(RouteWatchableDTO), + Any(AnyWatchableDTO), + Input(InputWatchableDTO), +} + +impl From<&PathWatchable> for PathWatchableDTO { + fn from(value: &PathWatchable) -> Self { + match value { + PathWatchable::Server(server_watchable) => { + let dirs = server_watchable + .dirs + .iter() + .map(|x| x.display().to_string()) + .collect::>() + .join(","); + Self::Server(ServerWatchableDTO { + dir: dirs, + server: ServerIdentityDTO::from(&server_watchable.server_identity), + }) + } + PathWatchable::Route(route_watchable) => Self::Route(RouteWatchableDTO { + server: ServerIdentityDTO::from(&route_watchable.server_identity), + dir: route_watchable.dir.display().to_string(), + }), + PathWatchable::Any(any_watchable) => { + let dirs = any_watchable + .dirs + .iter() + .map(|x| x.display().to_string()) + .collect::>() + .join(","); + Self::Any(AnyWatchableDTO { dir: dirs }) + } + PathWatchable::Input(input_watchable) => { + let absolute_paths = input_watchable + .dirs + .iter() + .map(|x| x.display().to_string()) + .collect::>() + .join(","); + let relative_paths = input_watchable + .dirs + .iter() + .map(|x| { + let next = x.strip_prefix(&input_watchable.cwd).ok().unwrap_or(x); + next.display().to_string() + }) + .collect::>() + .join(","); + Self::Input(InputWatchableDTO { + absolute_paths, + relative_paths, + }) + } + } + } +} + +impl PathWatchableDTO { + pub fn display_paths(&self) -> &str { + match self { + Self::Server(server) => server.dir.as_str(), + Self::Route(route) => route.dir.as_str(), + Self::Any(any) => any.dir.as_str(), + Self::Input(input) => input.relative_paths.as_str(), + } + } +} + +#[typeshare] +#[derive(Debug, serde::Serialize, Clone)] +pub struct ServerWatchableDTO { + pub server: ServerIdentityDTO, + pub dir: String, +} + +#[typeshare] +#[derive(Debug, serde::Serialize, Clone)] +pub struct RouteWatchableDTO { + pub server: ServerIdentityDTO, + pub dir: String, +} + +#[typeshare] +#[derive(Debug, serde::Serialize, Clone)] +pub struct AnyWatchableDTO { + pub dir: String, +} + +#[typeshare] +#[derive(Debug, serde::Serialize, Clone)] +pub struct InputWatchableDTO { + pub absolute_paths: String, + pub relative_paths: String, +} + +/// @discriminator kind +#[typeshare] +#[derive(Debug, Default, Clone, Eq, PartialEq, serde::Serialize)] +#[serde(tag = "kind", content = "payload")] +pub enum ResourceStatus { + #[default] + Pending, + Waiting { + reason: String, + }, + Ready, + Failed { + reason: String, + }, +} diff --git a/crates/bsnext_fs/examples/watch_cmd.rs b/crates/bsnext_fs/examples/watch_cmd.rs index f2337b75..96590778 100644 --- a/crates/bsnext_fs/examples/watch_cmd.rs +++ b/crates/bsnext_fs/examples/watch_cmd.rs @@ -71,7 +71,7 @@ impl actix::Handler for Example { fn handle(&mut self, msg: FsEvent, _ctx: &mut Self::Context) { tracing::info!(running = self.running, " ++ incoming"); tracing::info!(cmd = self.cmd.0.to_str()); - tracing::info!(?msg.kind); + tracing::info!(kind = ?msg.kind()); } } diff --git a/crates/bsnext_fs/src/actor.rs b/crates/bsnext_fs/src/actor.rs index ef6f8866..c6420d6f 100644 --- a/crates/bsnext_fs/src/actor.rs +++ b/crates/bsnext_fs/src/actor.rs @@ -94,10 +94,8 @@ impl FsWatcher { tracing::trace!("ignored: count: {}: {ignored}", ignore.len()); if any_match && !ignored { - let as_fs_event = FsEvent { - kind: FsEventKind::Change(PathDescriptionOwned::from(&pd)), - fs_event_ctx: ctx, - }; + let as_fs_event = + FsEvent::new(FsEventKind::Change(PathDescriptionOwned::from(&pd)), ctx); receiver.do_send(as_fs_event); } else { tracing::trace!( diff --git a/crates/bsnext_fs/src/lib.rs b/crates/bsnext_fs/src/lib.rs index 176a4f4a..be566412 100644 --- a/crates/bsnext_fs/src/lib.rs +++ b/crates/bsnext_fs/src/lib.rs @@ -57,11 +57,8 @@ impl FsEventContext { pub fn new(id: u64, origin_id: u64) -> Self { Self { id, origin_id } } - pub fn for_root() -> Self { - Self { - id: 0, - origin_id: 0, - } + pub fn for_root(origin_id: u64) -> Self { + Self { id: 0, origin_id } } } @@ -70,7 +67,7 @@ impl FsEventContext { self.id } pub fn is_root(&self) -> bool { - self.id == 0 && self.origin_id == 0 + self.id == 0 } } @@ -86,11 +83,20 @@ impl Default for FsEventContext { #[derive(actix::Message, Debug, Clone, Hash, PartialEq, PartialOrd, Eq, Ord)] #[rtype(result = "()")] pub struct FsEvent { - pub kind: FsEventKind, - pub fs_event_ctx: FsEventContext, + kind: FsEventKind, + fs_event_ctx: FsEventContext, } impl FsEvent { + pub fn kind(&self) -> &FsEventKind { + &self.kind + } + pub fn fs_event_ctx(&self) -> &FsEventContext { + &self.fs_event_ctx + } + pub fn new(kind: FsEventKind, fs_event_ctx: FsEventContext) -> Self { + Self { kind, fs_event_ctx } + } pub fn changed>(absolute: A, relative: A, ctx_id: u64) -> Self { Self { kind: FsEventKind::Change(PathDescriptionOwned { @@ -109,7 +115,6 @@ impl FsEvent { pub enum FsEventKind { Change(PathDescriptionOwned), PathAdded(PathAddedEvent), - PathRemoved(PathEvent), PathNotFoundError(PathEvent), } diff --git a/crates/bsnext_fs/src/watch_path_handler.rs b/crates/bsnext_fs/src/watch_path_handler.rs index 0ccd8589..5a0bdb61 100644 --- a/crates/bsnext_fs/src/watch_path_handler.rs +++ b/crates/bsnext_fs/src/watch_path_handler.rs @@ -14,7 +14,7 @@ impl Handler for FsWatcher { type Result = (); // todo: ensure this isn't sent for every input change - fn handle(&mut self, msg: RequestWatchPath, _ctx: &mut Self::Context) -> Self::Result { + fn handle(&mut self, msg: RequestWatchPath, ctx: &mut Self::Context) -> Self::Result { let Some(watcher) = self.watcher.as_mut() else { todo!("Can this ever be reached?"); }; @@ -41,21 +41,15 @@ impl Handler for FsWatcher { let evt = FsEventKind::PathAdded(PathAddedEvent { path: relative.clone(), }); - self.receiver.do_send(FsEvent { - kind: evt, - fs_event_ctx: self.ctx, - }) + self.receiver.do_send(FsEvent::new(evt, self.ctx)) } Err(err) => { - tracing::error!("cannot watch: {}", err); + tracing::debug!("cannot watch, error: {}", err); let evt = FsEventKind::PathNotFoundError(PathEvent { path: msg.path.clone(), }); - self.receiver.do_send(FsEvent { - kind: evt, - fs_event_ctx: self.ctx, - }); - _ctx.stop(); + self.receiver.do_send(FsEvent::new(evt, self.ctx)); + ctx.stop(); } } } diff --git a/crates/bsnext_html/src/html_writer.rs b/crates/bsnext_html/src/html_writer.rs index 95b4ae38..c3afe480 100644 --- a/crates/bsnext_html/src/html_writer.rs +++ b/crates/bsnext_html/src/html_writer.rs @@ -1,54 +1,52 @@ -use bsnext_input::{Input, InputWriter}; - pub struct HtmlWriter; -impl InputWriter for HtmlWriter { - fn input_to_str(&self, input: &Input) -> String { - if input.servers.is_empty() { - todo!("html requires at least 1 server definition") - } - if input.servers.len() > 1 { - todo!("more than 1 server not supported yet") - } - let server = input.servers.first().expect("must access first"); - let Some(playground) = &server.playground else { - todo!("only playground is supported in HTML for now") - }; - let mut blocks: Vec = vec![]; - if let Some(css) = &playground.css { - blocks.push("".into()); - } - blocks.push(playground.html.clone()); - if let Some(js) = &playground.js { - blocks.push("".into()); - } - blocks.join("\n") - } -} - -#[test] -fn test_html_writer_for_playground() { - use bsnext_input::playground::Playground; - use bsnext_input::server_config::ServerConfig; - let css = r#"body { - background: red; -}"#; - let js = r#"console.log("hello world!")"#; - let playground = Playground { - html: "

Hello world

".to_string(), - js: Some(js.to_string()), - css: Some(css.to_string()), - }; - let mut input = Input::default(); - let mut server = ServerConfig::default(); - server.playground = Some(playground); - input.servers.push(server); - let output = HtmlWriter.input_to_str(&input); - insta::assert_snapshot!(output); -} +// impl InputWriter for HtmlWriter { +// fn input_to_str(&self, input: &Input) -> String { +// if input.servers.is_empty() { +// todo!("html requires at least 1 server definition") +// } +// if input.servers.len() > 1 { +// todo!("more than 1 server not supported yet") +// } +// let server = input.servers.first().expect("must access first"); +// let Some(playground) = &server.playground else { +// todo!("only playground is supported in HTML for now") +// }; +// let mut blocks: Vec = vec![]; +// if let Some(css) = &playground.css { +// blocks.push("".into()); +// } +// blocks.push(playground.html.clone()); +// if let Some(js) = &playground.js { +// blocks.push("".into()); +// } +// blocks.join("\n") +// } +// } +// +// #[test] +// fn test_html_writer_for_playground() { +// use bsnext_input::playground::Playground; +// use bsnext_input::server_config::ServerConfig; +// let css = r#"body { +// background: red; +// }"#; +// let js = r#"console.log("hello world!")"#; +// let playground = Playground { +// html: "

Hello world

".to_string(), +// js: Some(js.to_string()), +// css: Some(css.to_string()), +// }; +// let mut input = Input::default(); +// let mut server = ServerConfig::default(); +// server.playground = Some(playground); +// input.servers.push(server); +// let output = HtmlWriter.input_to_str(&input); +// insta::assert_snapshot!(output); +// } diff --git a/crates/bsnext_input/Cargo.toml b/crates/bsnext_input/Cargo.toml index 6253188b..764cb3bb 100644 --- a/crates/bsnext_input/Cargo.toml +++ b/crates/bsnext_input/Cargo.toml @@ -23,6 +23,7 @@ anyhow = { workspace = true } serde_yaml = { workspace = true } serde_json = { workspace = true } thiserror = { workspace = true } +tracing = { workspace = true } [dev-dependencies] insta = { workspace = true } diff --git a/crates/bsnext_input/src/input_src.rs b/crates/bsnext_input/src/input_src.rs new file mode 100644 index 00000000..efab6d44 --- /dev/null +++ b/crates/bsnext_input/src/input_src.rs @@ -0,0 +1,19 @@ +use std::path::PathBuf; + +#[derive(Debug, Clone)] +pub enum InputSrc { + File(FileInputSrc), +} + +#[derive(Debug, Clone)] +pub struct FileInputSrc { + pub absolute: PathBuf, +} + +impl FileInputSrc { + pub fn new(abs: impl Into) -> Self { + Self { + absolute: abs.into(), + } + } +} diff --git a/crates/bsnext_input/src/input_test/mod.rs b/crates/bsnext_input/src/input_test/mod.rs index 1690b324..2499d96e 100644 --- a/crates/bsnext_input/src/input_test/mod.rs +++ b/crates/bsnext_input/src/input_test/mod.rs @@ -14,7 +14,7 @@ fn test_deserialize() { #[test] fn test_deserialize_2() { - #[derive(serde::Deserialize, serde::Serialize, Debug)] + #[derive(serde::Deserialize, Debug)] struct Config { pub items: Vec, } @@ -47,7 +47,7 @@ fn test_deserialize_2() { #[test] fn test_deserialize_cors_false() { - #[derive(serde::Deserialize, serde::Serialize, Debug)] + #[derive(serde::Deserialize, Debug)] struct Config { pub items: Vec, } @@ -66,7 +66,7 @@ fn test_deserialize_cors_false() { #[test] fn test_deserialize_compressions_absent() { - #[derive(serde::Deserialize, serde::Serialize, Debug)] + #[derive(serde::Deserialize, Debug)] struct Config { pub items: Vec, } @@ -83,7 +83,7 @@ fn test_deserialize_compressions_absent() { #[test] fn test_deserialize_compressions_true() { - #[derive(serde::Deserialize, serde::Serialize, Debug)] + #[derive(serde::Deserialize, Debug)] struct Config { pub items: Vec, } @@ -135,7 +135,7 @@ fn test_com_yaml() -> anyhow::Result<()> { #[test] fn test_deserialize_3_headers_control() { - #[derive(serde::Deserialize, serde::Serialize, Debug)] + #[derive(serde::Deserialize, Debug)] struct Config { pub items: Vec, } @@ -151,7 +151,7 @@ fn test_deserialize_3_headers_control() { #[test] fn test_deserialize_3_headers() { - #[derive(serde::Deserialize, serde::Serialize, Debug)] + #[derive(serde::Deserialize, Debug)] struct Config { pub items: Vec, } diff --git a/crates/bsnext_input/src/lib.rs b/crates/bsnext_input/src/lib.rs index 8aedbc8e..7f329d89 100644 --- a/crates/bsnext_input/src/lib.rs +++ b/crates/bsnext_input/src/lib.rs @@ -20,6 +20,7 @@ pub mod route; pub mod bs_live_built_in_task; pub mod input_fs; +pub mod input_src; pub mod route_cli; pub mod route_manifest; pub mod server_config; @@ -28,10 +29,11 @@ pub mod target; #[cfg(test)] pub mod watch_opt_test; pub mod watch_opts; +pub mod watchables; pub mod when_guard; pub mod yml; -#[derive(Debug, Default, Hash, Clone, serde::Deserialize, serde::Serialize)] +#[derive(Debug, Default, Hash, Clone, serde::Deserialize)] pub struct Input { #[serde(default)] pub servers: Vec, @@ -130,7 +132,7 @@ impl FromStr for Input { } } -#[derive(Debug, Hash, Default, Clone, serde::Deserialize, serde::Serialize)] +#[derive(Debug, Hash, Default, Clone, serde::Deserialize)] pub struct InputConfig { pub watchers: WatchGlobalConfig, pub global_fs_ignore: Option, @@ -221,6 +223,12 @@ pub struct InputCtx { file_path: Option, } +#[derive(Debug)] +pub enum InputCtxSource { + Prev, + New(InputCtx), +} + impl InputCtx { pub fn new( server_identities: &[ServerIdentity], @@ -282,10 +290,6 @@ pub trait InputCreation { ) -> Result>; } -pub trait InputWriter { - fn input_to_str(&self, input: &Input) -> String; -} - #[derive(Debug, miette::Diagnostic, thiserror::Error)] pub enum InputError { #[error("no suitable inputs could be found")] diff --git a/crates/bsnext_input/src/route.rs b/crates/bsnext_input/src/route.rs index 01e40320..c8189e37 100644 --- a/crates/bsnext_input/src/route.rs +++ b/crates/bsnext_input/src/route.rs @@ -16,7 +16,7 @@ use std::path::PathBuf; use std::str::FromStr; use std::time::Duration; -#[derive(Debug, PartialEq, Hash, Clone, serde::Deserialize, serde::Serialize)] +#[derive(Debug, PartialEq, Hash, Clone, serde::Deserialize)] pub struct Route { #[serde(with = "crate::path_def")] pub path: PathDef, @@ -46,7 +46,7 @@ pub enum PathDefError { InsertError(#[from] InsertError), } -#[derive(Debug, PartialEq, Hash, Clone, serde::Deserialize, serde::Serialize)] +#[derive(Debug, PartialEq, Hash, Clone, serde::Deserialize)] pub struct FallbackRoute { #[serde(flatten)] pub kind: RouteKind, @@ -54,7 +54,7 @@ pub struct FallbackRoute { pub opts: Opts, } -#[derive(Debug, Default, PartialEq, Hash, Clone, serde::Deserialize, serde::Serialize)] +#[derive(Debug, Default, PartialEq, Hash, Clone, serde::Deserialize)] pub struct Opts { #[serde(flatten)] pub cors: Option, @@ -420,18 +420,7 @@ impl FromStr for PathPattern { } } -#[derive( - Debug, - Default, - Ord, - PartialOrd, - PartialEq, - Eq, - Hash, - Clone, - serde::Deserialize, - serde::Serialize, -)] +#[derive(Debug, Default, Ord, PartialOrd, PartialEq, Eq, Hash, Clone, serde::Deserialize)] pub struct WatchSpec { pub debounce: Option, pub only: Option, @@ -639,9 +628,7 @@ impl Default for PrefixOpt { } } -#[derive( - Debug, PartialOrd, Ord, Eq, PartialEq, Hash, Clone, serde::Deserialize, serde::Serialize, -)] +#[derive(Debug, PartialOrd, Ord, Eq, PartialEq, Hash, Clone, serde::Deserialize)] pub struct MultiWatch { pub dirs: WatcherDirs, #[serde(flatten)] diff --git a/crates/bsnext_input/src/server_config.rs b/crates/bsnext_input/src/server_config.rs index 3ff75fc5..54f5c9ef 100644 --- a/crates/bsnext_input/src/server_config.rs +++ b/crates/bsnext_input/src/server_config.rs @@ -7,7 +7,7 @@ use std::hash::{DefaultHasher, Hash, Hasher}; use std::net::SocketAddr; use std::str::FromStr; -#[derive(Debug, Default, Hash, Clone, serde::Deserialize, serde::Serialize)] +#[derive(Debug, Default, Hash, Clone, serde::Deserialize)] pub struct ServerConfig { #[serde(flatten)] pub identity: ServerIdentity, @@ -51,9 +51,7 @@ impl ServerConfig { } } -#[derive( - Debug, Ord, PartialOrd, PartialEq, Hash, Eq, Clone, serde::Deserialize, serde::Serialize, -)] +#[derive(Debug, Ord, PartialOrd, PartialEq, Hash, Eq, Clone, serde::Deserialize)] #[serde(untagged)] pub enum ServerIdentity { PortNamed { @@ -162,7 +160,7 @@ impl ServerIdentity { #[test] fn server_config_as_enum() { - #[derive(Debug, Clone, serde::Deserialize, serde::Serialize)] + #[derive(Debug, Clone, serde::Deserialize)] struct C { servers: Vec, } @@ -189,7 +187,7 @@ servers: #[test] fn with_port() { - #[derive(Debug, Clone, serde::Deserialize, serde::Serialize)] + #[derive(Debug, Clone, serde::Deserialize)] struct C { servers: Vec, } diff --git a/crates/bsnext_input/src/watch_opts.rs b/crates/bsnext_input/src/watch_opts.rs index 2951932a..0464c4dc 100644 --- a/crates/bsnext_input/src/watch_opts.rs +++ b/crates/bsnext_input/src/watch_opts.rs @@ -1,6 +1,6 @@ use crate::route::WatchSpec; -#[derive(Debug, PartialEq, Hash, Clone, serde::Deserialize, serde::Serialize)] +#[derive(Debug, PartialEq, Hash, Clone, serde::Deserialize)] #[serde(untagged)] pub enum WatchOpts { Bool(bool), diff --git a/crates/bsnext_system/src/watchables/any_watchable.rs b/crates/bsnext_input/src/watchables/any_watchable.rs similarity index 89% rename from crates/bsnext_system/src/watchables/any_watchable.rs rename to crates/bsnext_input/src/watchables/any_watchable.rs index 2cdb8559..18c32000 100644 --- a/crates/bsnext_system/src/watchables/any_watchable.rs +++ b/crates/bsnext_input/src/watchables/any_watchable.rs @@ -1,5 +1,5 @@ -use bsnext_input::route::WatchSpec; -use bsnext_input::Input; +use crate::route::WatchSpec; +use crate::Input; use std::path::PathBuf; #[derive(Debug, PartialEq, PartialOrd, Ord, Eq, Hash, Clone)] diff --git a/crates/bsnext_input/src/watchables/input_watchable.rs b/crates/bsnext_input/src/watchables/input_watchable.rs new file mode 100644 index 00000000..18aa740c --- /dev/null +++ b/crates/bsnext_input/src/watchables/input_watchable.rs @@ -0,0 +1,23 @@ +use crate::input_src::{FileInputSrc, InputSrc}; +use crate::route::WatchSpec; +use std::path::{Path, PathBuf}; + +#[derive(Debug, PartialEq, PartialOrd, Ord, Eq, Hash, Clone)] +pub struct InputWatchable { + pub dirs: Vec, + pub cwd: PathBuf, + pub watch_spec: WatchSpec, +} + +pub fn to_input_watchable(src_list: &[InputSrc], cwd: &Path) -> Vec { + src_list + .iter() + .map(|input_src| match input_src { + InputSrc::File(FileInputSrc { absolute }) => InputWatchable { + dirs: vec![absolute.to_owned()], + watch_spec: WatchSpec::default(), + cwd: cwd.to_owned(), + }, + }) + .collect() +} diff --git a/crates/bsnext_system/src/watchables/mod.rs b/crates/bsnext_input/src/watchables/mod.rs similarity index 74% rename from crates/bsnext_system/src/watchables/mod.rs rename to crates/bsnext_input/src/watchables/mod.rs index e8a62b06..b9c69a5f 100644 --- a/crates/bsnext_system/src/watchables/mod.rs +++ b/crates/bsnext_input/src/watchables/mod.rs @@ -1,31 +1,30 @@ +use crate::input_src::InputSrc; use crate::watchables::any_watchable::to_any_watchables; +use crate::watchables::input_watchable::to_input_watchable; use crate::watchables::path_watchable::PathWatchable; use crate::watchables::route_watchable::to_route_watchables; use crate::watchables::server_watchable::to_server_watchables; -use actix::Recipient; -use bsnext_input::{InferWatchers, Input, WatchGlobalConfig}; -use bsnext_path_monitor::PathMonitorChangeset; -use std::path::PathBuf; +use crate::{InferWatchers, Input, WatchGlobalConfig}; +use std::path::Path; use tracing::debug; pub mod any_watchable; +pub mod input_watchable; pub mod path_watchable; pub mod route_watchable; pub mod server_watchable; -#[derive(actix::Message)] -#[rtype(result = "()")] -pub struct MonitorPathWatchables { +#[derive(Debug, Hash, Eq, PartialEq)] +pub struct PathWatchables { pub watchables: Vec, - pub cwd: PathBuf, - pub recipient: Recipient, } -impl MonitorPathWatchables { - pub fn new(cwd: PathBuf, input: &Input, recipient: Recipient) -> Self { +impl PathWatchables { + pub fn new(input: &Input, src_list: &[InputSrc], cwd: &Path) -> Self { let route_watchables = to_route_watchables(input); let server_watchables = to_server_watchables(input); let any_watchables = to_any_watchables(input); + let input_watchables = to_input_watchable(src_list, cwd); let routes = route_watchables .iter() @@ -39,7 +38,9 @@ impl MonitorPathWatchables { .iter() .map(|w| PathWatchable::Any(w.to_owned())); - let watchables: Vec<_> = match &input.config.watchers { + let inputs = input_watchables.into_iter().map(PathWatchable::Input); + + let mut watchables: Vec = match &input.config.watchers { WatchGlobalConfig::Enabled { infer } => match infer { InferWatchers::None => { debug!("processing {} any watchables", any.len()); @@ -65,16 +66,8 @@ impl MonitorPathWatchables { WatchGlobalConfig::Disabled => vec![], }; - debug!( - "{} watchables to add, cwd: {}", - watchables.len(), - cwd.display() - ); + watchables.extend(inputs); - MonitorPathWatchables { - watchables, - cwd, - recipient, - } + PathWatchables { watchables } } } diff --git a/crates/bsnext_system/src/watchables/path_watchable.rs b/crates/bsnext_input/src/watchables/path_watchable.rs similarity index 62% rename from crates/bsnext_system/src/watchables/path_watchable.rs rename to crates/bsnext_input/src/watchables/path_watchable.rs index 6ccbdccd..1a864b3f 100644 --- a/crates/bsnext_system/src/watchables/path_watchable.rs +++ b/crates/bsnext_input/src/watchables/path_watchable.rs @@ -1,17 +1,21 @@ -use std::fmt::{Display, Formatter}; +use std::fmt::{Debug, Display, Formatter}; use std::hash::{DefaultHasher, Hash, Hasher}; +use crate::route::WatchSpec; use crate::watchables::any_watchable::AnyWatchable; +use crate::watchables::input_watchable::InputWatchable; use crate::watchables::route_watchable::RouteWatchable; use crate::watchables::server_watchable::ServerWatchable; -use bsnext_input::route::WatchSpec; +use bsnext_fs::Debounce; use std::path::Path; +use std::time::Duration; #[derive(Debug, PartialEq, PartialOrd, Ord, Eq, Hash, Clone)] pub enum PathWatchable { Server(ServerWatchable), Route(RouteWatchable), Any(AnyWatchable), + Input(InputWatchable), } impl Display for PathWatchable { @@ -38,6 +42,15 @@ impl Display for PathWatchable { .join(", "); write!(f, "PathWatchable::Any({lines})")?; } + PathWatchable::Input(input_watchable) => { + let lines = input_watchable + .dirs + .iter() + .map(|x| format!("'{}'", x.display())) + .collect::>() + .join(", "); + write!(f, "PathWatchable::Input({lines})")?; + } } Ok(()) } @@ -49,6 +62,7 @@ impl PathWatchable { PathWatchable::Server(server) => &server.watch_spec, PathWatchable::Route(route) => &route.watch_spec, PathWatchable::Any(any) => &any.watch_spec, + PathWatchable::Input(input) => &input.watch_spec, } } pub fn watch_paths(&self) -> Vec<&Path> { @@ -56,6 +70,7 @@ impl PathWatchable { PathWatchable::Server(server) => server.dirs.iter().map(|x| x.as_path()).collect(), PathWatchable::Route(route) => vec![&route.dir], PathWatchable::Any(any) => any.dirs.iter().map(|x| x.as_path()).collect(), + PathWatchable::Input(input) => input.dirs.iter().map(|x| x.as_path()).collect(), } } @@ -64,4 +79,19 @@ impl PathWatchable { self.hash(&mut hasher); hasher.finish() } + + pub fn debounce(&self) -> Debounce { + let spec = match self { + PathWatchable::Server(server) => Some(&server.watch_spec), + PathWatchable::Route(route) => Some(&route.watch_spec), + PathWatchable::Any(any) => Some(&any.watch_spec), + PathWatchable::Input(_input) => None, + }; + match spec { + None => Debounce::Trailing { + duration: Duration::from_millis(300), + }, + Some(spec) => spec.debounce.map(Debounce::from).unwrap_or_default(), + } + } } diff --git a/crates/bsnext_system/src/watchables/route_watchable.rs b/crates/bsnext_input/src/watchables/route_watchable.rs similarity index 92% rename from crates/bsnext_system/src/watchables/route_watchable.rs rename to crates/bsnext_input/src/watchables/route_watchable.rs index 9ea30464..59219fb2 100644 --- a/crates/bsnext_system/src/watchables/route_watchable.rs +++ b/crates/bsnext_input/src/watchables/route_watchable.rs @@ -1,7 +1,7 @@ -use bsnext_input::route::{DirRoute, PathPattern, RawRoute, RouteKind, SseOpts, WatchSpec}; -use bsnext_input::server_config::ServerIdentity; -use bsnext_input::watch_opts::WatchOpts; -use bsnext_input::Input; +use crate::route::{DirRoute, PathPattern, RawRoute, RouteKind, SseOpts, WatchSpec}; +use crate::server_config::ServerIdentity; +use crate::watch_opts::WatchOpts; +use crate::Input; use std::path::{Path, PathBuf}; #[derive(Debug, PartialEq, PartialOrd, Ord, Eq, Hash, Clone)] diff --git a/crates/bsnext_system/src/watchables/server_watchable.rs b/crates/bsnext_input/src/watchables/server_watchable.rs similarity index 87% rename from crates/bsnext_system/src/watchables/server_watchable.rs rename to crates/bsnext_input/src/watchables/server_watchable.rs index 652691ac..003635eb 100644 --- a/crates/bsnext_system/src/watchables/server_watchable.rs +++ b/crates/bsnext_input/src/watchables/server_watchable.rs @@ -1,6 +1,6 @@ -use bsnext_input::route::WatchSpec; -use bsnext_input::server_config::ServerIdentity; -use bsnext_input::Input; +use crate::route::WatchSpec; +use crate::server_config::ServerIdentity; +use crate::Input; use std::path::PathBuf; #[derive(Debug, PartialEq, PartialOrd, Ord, Eq, Hash, Clone)] diff --git a/crates/bsnext_md/Cargo.toml b/crates/bsnext_md/Cargo.toml index 1017ecfd..b45853a1 100644 --- a/crates/bsnext_md/Cargo.toml +++ b/crates/bsnext_md/Cargo.toml @@ -7,6 +7,7 @@ edition = "2021" markdown = { version = "1.0.0-alpha.16" } nom = "7.1.3" bsnext_input = { path = "../bsnext_input" } +bsnext_dto = { path = "../bsnext_dto" } mime_guess = { workspace = true } anyhow = { workspace = true } diff --git a/crates/bsnext_md/src/md_writer.rs b/crates/bsnext_md/src/md_writer.rs index aae27632..ca877fa9 100644 --- a/crates/bsnext_md/src/md_writer.rs +++ b/crates/bsnext_md/src/md_writer.rs @@ -1,24 +1,18 @@ +use bsnext_dto::ServerIdentityDTO; use bsnext_input::route::{RawRoute, RouteKind}; -use bsnext_input::server_config::ServerIdentity; -use bsnext_input::{Input, InputWriter}; +use bsnext_input::Input; use mime_guess::get_mime_extensions_str; use serde_json::json; pub struct MdWriter; -impl InputWriter for MdWriter { - fn input_to_str(&self, input: &Input) -> String { - _input_to_str(input) - } -} - fn _input_to_str(input: &Input) -> String { let mut chunks = vec![]; if let Some(server_config) = input.servers.first() { #[derive(Debug, serde::Serialize)] struct FakeServerConfig { #[serde(flatten)] - identity: ServerIdentity, + identity: ServerIdentityDTO, } #[derive(Debug, serde::Serialize)] struct FakeInput { @@ -26,7 +20,7 @@ fn _input_to_str(input: &Input) -> String { } let just_identity = FakeInput { servers: vec![FakeServerConfig { - identity: server_config.identity.clone(), + identity: ServerIdentityDTO::from(&server_config.identity), }], }; let yml = serde_yaml::to_string(&just_identity).expect("never fail here"); @@ -56,6 +50,7 @@ fn _input_to_str(input: &Input) -> String { chunks.join("\n") } +#[allow(unused)] fn route_to_markdown(kind: &RouteKind, path: &str) -> String { match kind { RouteKind::Raw(raw) => match raw { @@ -78,18 +73,22 @@ fn route_to_markdown(kind: &RouteKind, path: &str) -> String { } } +#[allow(unused)] fn fenced_input(code: &str) -> String { format!("```yaml bslive_input\n{code}```") } +#[allow(unused)] fn fenced_route(code: &str) -> String { format!("```yaml bslive_route\n{code}```") } +#[allow(unused)] fn fenced_playground(code: &str) -> String { format!("```html playground\n{code}\n```") } +#[allow(unused)] fn fenced_body(lang: &str, code: &str) -> String { format!("```{lang}\n{code}\n```") } diff --git a/crates/bsnext_md/tests/md_serialize.rs b/crates/bsnext_md/tests/md_serialize.rs deleted file mode 100644 index 801512d0..00000000 --- a/crates/bsnext_md/tests/md_serialize.rs +++ /dev/null @@ -1,16 +0,0 @@ -use bsnext_input::{InputCreation, InputWriter}; -use bsnext_md::md_fs::MdFs; -use bsnext_md::md_writer::MdWriter; - -#[test] -fn test_input_to_str() -> anyhow::Result<()> { - let input_str = include_str!("../../../examples/markdown/single.md"); - let input = MdFs::from_input_str(&input_str, &Default::default()).expect("unwrap"); - let output = MdWriter.input_to_str(&input); - println!("{}", output); - let input = MdFs::from_input_str(&output, &Default::default()).expect("unwrapped 2"); - println!("{:?}", input); - assert_eq!(input.servers.len(), 1); - assert_eq!(input.servers.first().unwrap().routes.len(), 2); - Ok(()) -} diff --git a/crates/bsnext_output/src/lib.rs b/crates/bsnext_output/src/lib.rs index b111a8ee..f8594d3f 100644 --- a/crates/bsnext_output/src/lib.rs +++ b/crates/bsnext_output/src/lib.rs @@ -6,17 +6,31 @@ use stdout::StdoutTarget; pub mod stdout; -#[derive(Debug, Default)] -pub enum OutputWriters { +#[derive(Debug, Hash, Default, Clone)] +pub enum OutputGlobalPrefix { #[default] - Pretty, + NodePrefix, + None, +} + +#[derive(Debug)] +pub enum OutputWriters { + Pretty { prefix: OutputGlobalPrefix }, Json, } +impl Default for OutputWriters { + fn default() -> Self { + Self::Pretty { + prefix: OutputGlobalPrefix::NodePrefix, + } + } +} + impl Display for OutputWriters { fn fmt(&self, f: &mut Formatter<'_>) -> std::fmt::Result { match self { - OutputWriters::Pretty => write!(f, "OutputWriters::Pretty"), + OutputWriters::Pretty { .. } => write!(f, "OutputWriters::Pretty"), OutputWriters::Json => write!(f, "OutputWriters::Json"), } } @@ -24,7 +38,11 @@ impl Display for OutputWriters { pub trait OutputWriterTrait: std::fmt::Debug { fn write_json(&self, _sink: &mut W) -> anyhow::Result<()>; - fn write_pretty(&self, _sink: &mut W) -> anyhow::Result<()>; + fn write_pretty( + &self, + prefix: &OutputGlobalPrefix, + _sink: &mut W, + ) -> anyhow::Result<()>; } impl OutputWriters { @@ -34,7 +52,7 @@ impl OutputWriters { sink: &mut W, ) -> anyhow::Result<()> { match self { - OutputWriters::Pretty => evt.write_pretty(sink), + OutputWriters::Pretty { prefix } => evt.write_pretty(prefix, sink), OutputWriters::Json => evt.write_json(sink), } } diff --git a/crates/bsnext_path_monitor/src/path_monitor.rs b/crates/bsnext_path_monitor/src/path_monitor.rs index f2f8601f..55d4b601 100644 --- a/crates/bsnext_path_monitor/src/path_monitor.rs +++ b/crates/bsnext_path_monitor/src/path_monitor.rs @@ -1,7 +1,10 @@ use crate::PathMonitorChangeset; use crate::path_and_filter::PathAndFilter; use crate::watch_paths_msg::WatchPaths; -use actix::{Actor, ActorContext, Addr, AsyncContext, Context, Handler, Recipient, StreamHandler}; +use actix::{ + Actor, ActorContext, Addr, AsyncContext, Context, Handler, Recipient, ResponseFuture, + StreamHandler, +}; use actix_rt::Arbiter; use bsnext_fs::actor::FsWatcher; use bsnext_fs::buffered_debounce::BufferedStreamOpsExt; @@ -108,6 +111,32 @@ impl actix::Handler for PathMonitor { } } +#[derive(Debug, actix::Message)] +#[rtype(result = "ConnectedWatchersResult")] +pub struct ConnectedWatchers; + +#[derive(Debug)] +pub struct ConnectedWatchersResult { + pub desired_len: usize, + pub observed_len: usize, +} + +impl actix::Handler for PathMonitor { + type Result = ResponseFuture; + + fn handle(&mut self, _msg: ConnectedWatchers, _ctx: &mut Self::Context) -> Self::Result { + let addrs = self.addrs.clone(); + Box::pin(async move { + let desired_len = addrs.len(); + let observed_len = addrs.iter().filter(|addr| addr.connected()).count(); + ConnectedWatchersResult { + desired_len, + observed_len, + } + }) + } +} + impl StreamHandler for PathMonitor { fn handle(&mut self, event: FsEvent, _ctx: &mut Context) { debug!("StreamHandler for PathMonitor"); @@ -131,7 +160,7 @@ impl StreamHandler> for PathMonitor { debug!(" └ {:?}", unique); let outgoing = unique .into_iter() - .filter_map(|e| match &e.kind { + .filter_map(|e| match e.kind() { FsEventKind::Change(pd) => Some(pd.to_owned()), _ => None, }) @@ -223,7 +252,7 @@ impl Handler for PathMonitor { let span = debug_span!("Handler->FsEvent->PathMonitor"); let _guard = span.enter(); let sender = self.inner_sender.clone(); - match &msg.kind { + match &msg.kind() { FsEventKind::Change(PathDescriptionOwned { .. }) => { debug!("FsEventKind::Change"); Arbiter::current().spawn(async move { diff --git a/crates/bsnext_system/src/args.rs b/crates/bsnext_system/src/args.rs index 60489ea5..1d3c509e 100644 --- a/crates/bsnext_system/src/args.rs +++ b/crates/bsnext_system/src/args.rs @@ -3,6 +3,7 @@ use crate::start::start_command::StartCommand; use crate::watch::watch_sub_opts::WatchSubOpts; use crate::watch::WatchCommand; use bsnext_core::shared_args::{InputOpts, LoggingOpts}; +use bsnext_output::OutputGlobalPrefix; use bsnext_tracing::OutputFormat; // bslive route --path=/ --dir= @@ -32,6 +33,10 @@ pub struct Args { #[clap(long)] pub no_watch: bool, + /// pass '--no-prefix' to prevent output lines being prefixed with the node tree path by default' + #[clap(long)] + pub no_prefix: bool, + /// Paths to serve + possibly watch, incompatible with `-i` option pub trailing: Vec, } @@ -52,12 +57,30 @@ impl Args { logging, format, no_watch: self.no_watch, + no_prefix: self.no_prefix, }); (default_cmd, self.input_opts.clone()) }, |cmd| (cmd, self.input_opts.clone()), ) } + + pub fn global_prefix(&self) -> OutputGlobalPrefix { + if self.no_prefix { + return OutputGlobalPrefix::None; + } + self.command + .as_ref() + .and_then(|cmd| { + let global_refused = match cmd { + SubCommands::Start(start) => start.no_prefix, + SubCommands::Watch(watch) => watch.no_prefix, + SubCommands::Run(run) => run.no_prefix, + }; + global_refused.then_some(OutputGlobalPrefix::None) + }) + .unwrap_or_default() + } } impl Args { diff --git a/crates/bsnext_system/src/cli.rs b/crates/bsnext_system/src/cli.rs index 92da2db8..eb77b11b 100644 --- a/crates/bsnext_system/src/cli.rs +++ b/crates/bsnext_system/src/cli.rs @@ -22,7 +22,6 @@ where T: Into + Clone, { let args = Args::parse_from(itr); - let logging = *args.logging(); let write_log_opt = if logging.write_log { WriteOption::File @@ -56,10 +55,10 @@ where }; let format_clone = format; - + let prefix = args.global_prefix(); let writer = match format_clone { - OutputFormat::Tui => OutputWriters::Pretty, - OutputFormat::Normal => OutputWriters::Pretty, + OutputFormat::Tui => OutputWriters::Pretty { prefix }, + OutputFormat::Normal => OutputWriters::Pretty { prefix }, OutputFormat::Json => OutputWriters::Json, }; diff --git a/crates/bsnext_system/src/handle_fs_changeset.rs b/crates/bsnext_system/src/handle_fs_changeset.rs index a9c8b2a1..d17b29bc 100644 --- a/crates/bsnext_system/src/handle_fs_changeset.rs +++ b/crates/bsnext_system/src/handle_fs_changeset.rs @@ -1,24 +1,22 @@ use crate::fs_task_tracker::TriggerFsTask; -use crate::input_fs::from_input_path; -use crate::override_input::OverrideInput; -use crate::system::BsSystem; -use crate::tasks::task_comms::TaskComms; +use crate::system::{BsSystem, ResolveInputAgain}; use crate::tasks::task_spec::TaskSpec; use crate::tasks::Runnable; use actix::{Addr, AsyncContext}; +use bsnext_core::servers_supervisor::actor::ServersSupervisor; use bsnext_core::servers_supervisor::file_changed_handler::FileChanged; use bsnext_dto::any_event::AnyEvent; use bsnext_dto::external_events::ExternalEventsDTO; -use bsnext_dto::{InputErrorDetailDTO, StoppedWatchingDTO, WatchingDTO}; use bsnext_fs::{ BufferedChangeset, Debounce, FsEvent, FsEventContext, FsEventKind, PathAddedEvent, PathDescriptionOwned, PathEvent, }; use bsnext_input::bs_live_built_in_task::BsLiveBuiltInTask; use bsnext_input::route::WatchSpec; -use bsnext_input::{Input, InputError, PathDefinition, PathDefs, PathError}; +use bsnext_input::{InputCtx, PathDefinition}; use bsnext_path_monitor::{Changeset, PathMonitorChangeset}; use bsnext_task::task_trigger::FsChangesTrigger; +use std::path::PathBuf; use tracing::{debug, debug_span, info}; impl actix::Handler for BsSystem { @@ -39,7 +37,9 @@ impl actix::Handler for BsSystem { None } Changeset::BufferedChange(buff) => { - if let Some((task_trigger, task_spec)) = self.handle_buffered(buff, watch_spec) { + if let Some((task_trigger, task_spec)) = + handle_buffered(self.input_ctx.as_ref(), buff, watch_spec) + { tracing::debug!("will trigger task runner"); self.fs_task_tracker .do_send(TriggerFsTask::new(task_spec, task_trigger)); @@ -63,163 +63,103 @@ impl BsSystem { addr: Addr, debounce: Debounce, ) -> Option { - match &fs_event.kind { - FsEventKind::Change(ch) if fs_event.fs_event_ctx.is_root() => { + tracing::debug!(ctx = ?fs_event.fs_event_ctx()); + match &fs_event.kind() { + FsEventKind::Change(ch) if fs_event.fs_event_ctx().is_root() => { tracing::info!("fs_event_ctx=root"); - match self.handle_input_change(ch) { - // if the change included a new Input, use it - Ok((_, Some(input))) => { - tracing::info!("will override input"); - addr.do_send(OverrideInput { input }); - // return None here so that the event is not published yet (the updated Input will do it) - None - } - // otherwise publish the change as usual - Ok((evt, None)) => Some(evt), - Err(e) => { - println!("{e}"); - None - } - } + addr.do_send(ResolveInputAgain); + None } FsEventKind::Change(inner) => { - let evt = self.handle_any_change(&fs_event.fs_event_ctx, inner); + let servers_addr = self.servers().clone(); + let evt = handle_any_change(servers_addr, fs_event.fs_event_ctx(), inner); Some(evt) } - FsEventKind::PathAdded(path) => self.handle_path_added(path, &debounce), - FsEventKind::PathRemoved(path) => self.handle_path_removed(path), - FsEventKind::PathNotFoundError(pdo) => self.handle_path_not_found(pdo), + FsEventKind::PathAdded(path) => handle_path_added(path, &debounce), + FsEventKind::PathNotFoundError(pdo) => handle_path_not_found(self.cwd.clone(), pdo), } } - #[tracing::instrument(skip_all)] - fn handle_buffered( - &mut self, - buf: BufferedChangeset, - watch_spec: WatchSpec, - ) -> Option<(FsChangesTrigger, TaskSpec)> { - tracing::debug!(msg.event_count = buf.changes.len(), msg.ctx = ?buf.fs_event_ctx, ?buf); - - let change = if let Some(mon) = &self.input_monitors { - if let Some(fp) = mon.input_ctx.file_path() { - tracing::debug!("Dropping input crossover {}", fp.display()); - buf.dropping_absolute(fp) - } else { - buf - } - } else { - buf - }; - - if change.changes.is_empty() { - tracing::debug!( - "Ignoring handle_buffered events because it was empty after removing input monitor" - ); - return None; - } - - let paths = change - .changes - .iter() - .map(|evt| evt.absolute.to_owned()) - .collect::>(); - - let task_spec = self.task_spec_for_fs_event(&watch_spec); - let trigger = FsChangesTrigger::new(paths, change.fs_event_ctx); - - Some((trigger, task_spec)) - } - - pub fn task_comms(&mut self) -> TaskComms { - TaskComms::new(self.sender().clone()) - } +} - fn handle_any_change( - &mut self, - fs_event_ctx: &FsEventContext, - inner: &PathDescriptionOwned, - ) -> ExternalEventsDTO { - tracing::trace!(?inner, "Other file changed"); - self.servers().do_send(FileChanged { - path: inner.absolute.clone(), - ctx: *fs_event_ctx, - }); - ExternalEventsDTO::FileChanged(bsnext_dto::FileChangedDTO::from_path_buf( - inner.relative.as_ref().unwrap_or(&inner.absolute), - )) +#[tracing::instrument(skip_all)] +fn handle_buffered( + input_ctx: Option<&InputCtx>, + buf: BufferedChangeset, + watch_spec: WatchSpec, +) -> Option<(FsChangesTrigger, TaskSpec)> { + tracing::debug!(msg.event_count = buf.changes.len(), msg.ctx = ?buf.fs_event_ctx, ?buf); + + let change = if let Some(fp) = input_ctx.and_then(|x| x.file_path()) { + tracing::debug!("Dropping input crossover {}", fp.display()); + buf.dropping_absolute(fp) + } else { + buf + }; + + if change.changes.is_empty() { + tracing::debug!( + "Ignoring handle_buffered events because it was empty after removing input monitor" + ); + return None; } - fn handle_input_change( - &mut self, - inner: &PathDescriptionOwned, - ) -> Result<(ExternalEventsDTO, Option), Box> { - tracing::info!("InputFile file changed {:?}", inner); - let ctx = self - .input_monitors - .as_ref() - .map(|input_monitor| input_monitor.input_ctx.clone()) - .unwrap_or_default(); + let paths = change + .changes + .iter() + .map(|evt| evt.absolute.to_owned()) + .collect::>(); - let input = from_input_path(&inner.absolute, &ctx); - - let Ok(input) = input else { - let err = input.unwrap_err(); - return Err(err); - }; - let path_to_report = inner.relative.as_ref().unwrap_or(&inner.absolute); + let task_spec = task_spec_for_fs_event(&watch_spec); + let trigger = FsChangesTrigger::new(paths, change.fs_event_ctx); - Ok(( - ExternalEventsDTO::InputFileChanged(bsnext_dto::FileChangedDTO::from_path_buf( - path_to_report, - )), - Some(input), - )) - } - fn handle_path_added( - &self, - path: &PathAddedEvent, - debounce: &Debounce, - ) -> Option { - Some(ExternalEventsDTO::Watching(WatchingDTO::from_path_buf( - &path.path, *debounce, - ))) - } + Some((trigger, task_spec)) +} - fn handle_path_removed(&mut self, path: &PathEvent) -> Option { - Some(ExternalEventsDTO::WatchingStopped( - StoppedWatchingDTO::from_path_buf(&path.path), - )) - } +fn handle_any_change( + servers_addr: Addr, + fs_event_ctx: &FsEventContext, + inner: &PathDescriptionOwned, +) -> ExternalEventsDTO { + tracing::trace!(?inner, "Other file changed"); + servers_addr.do_send(FileChanged { + path: inner.absolute.clone(), + ctx: *fs_event_ctx, + }); + ExternalEventsDTO::FileChanged(bsnext_dto::FileChangedDTO::from_path_buf( + inner.relative.as_ref().unwrap_or(&inner.absolute), + )) +} - fn handle_path_not_found(&mut self, pdo: &PathEvent) -> Option { - let as_str = pdo.path.to_string_lossy().to_string(); - let cwd = self.cwd.clone(); - let abs = cwd.join(&as_str); - let def = PathDefinition { - input: as_str, - cwd: self.cwd.clone(), - absolute: abs, - }; - let err = InputError::PathError(PathError::MissingPaths { - paths: PathDefs(vec![def]), - }); +#[tracing::instrument] +fn handle_path_not_found(cwd: PathBuf, pdo: &PathEvent) -> Option { + let as_str = pdo.path.to_string_lossy().to_string(); + let cwd = cwd.clone(); + let abs = cwd.join(&as_str); + let def = PathDefinition { + input: as_str, + cwd: cwd.clone(), + absolute: abs, + }; + tracing::debug!(?def, "path not found"); + None +} - Some(ExternalEventsDTO::InputError(InputErrorDetailDTO { - error: err.to_string(), - })) - } +fn handle_path_added(path: &PathAddedEvent, debounce: &Debounce) -> Option { + tracing::debug!(?path.path, ?debounce, "path added"); + None +} - #[tracing::instrument(skip_all)] - fn task_spec_for_fs_event(&self, watch_spec: &WatchSpec) -> TaskSpec { - if let Some(spec) = TaskSpec::opt_from(watch_spec) { - info!("matching task_spec: {:?}", spec); - info!("matching fs_event_ctx: {:?}", watch_spec); - spec.to_owned() - } else { - debug!("creating a default task spec on the fly because fs_event_ctx didn't match any task specs"); - TaskSpec::seq(&[ - Runnable::BsLiveTask(BsLiveBuiltInTask::NotifyServer), - Runnable::BsLiveTask(BsLiveBuiltInTask::PublishExternalEvent), - ]) - } +#[tracing::instrument(skip_all)] +fn task_spec_for_fs_event(watch_spec: &WatchSpec) -> TaskSpec { + if let Some(spec) = TaskSpec::opt_from(watch_spec) { + info!("matching task_spec: {:?}", spec); + info!("matching fs_event_ctx: {:?}", watch_spec); + spec.to_owned() + } else { + debug!("creating a default task spec on the fly because fs_event_ctx didn't match any task specs"); + TaskSpec::seq(&[ + Runnable::BsLiveTask(BsLiveBuiltInTask::NotifyServer), + Runnable::BsLiveTask(BsLiveBuiltInTask::PublishExternalEvent), + ]) } } diff --git a/crates/bsnext_system/src/lib.rs b/crates/bsnext_system/src/lib.rs index af1550e5..77cbaf1b 100644 --- a/crates/bsnext_system/src/lib.rs +++ b/crates/bsnext_system/src/lib.rs @@ -8,13 +8,11 @@ mod handle_fs_changeset; pub mod input_fs; mod invoke_scope; pub mod monitor_any; -pub mod monitor_input; -pub mod override_input; pub mod path_monitors; pub mod run; mod servers; pub mod start; +mod status_tracker; mod system; pub mod tasks; pub mod watch; -pub mod watchables; diff --git a/crates/bsnext_system/src/monitor_any.rs b/crates/bsnext_system/src/monitor_any.rs index a638e6cd..8b137891 100644 --- a/crates/bsnext_system/src/monitor_any.rs +++ b/crates/bsnext_system/src/monitor_any.rs @@ -1,65 +1 @@ -use crate::system::BsSystem; -use crate::watchables::MonitorPathWatchables; -use actix::{ActorFutureExt, AsyncContext}; -use actix::{ResponseActFuture, WrapFuture}; -use bsnext_input::Input; -use tracing::debug_span; -/// Message to monitor file system paths based on the current input configuration. -/// -/// This handler processes an `Input` configuration to determine which paths should be -/// monitored for file system changes. It: -/// - Converts the input into a collection of watchables based on the configured watch strategy -/// (routes, servers, or any custom watchers) -/// - Sends these watchables to the `Monitor` actor to create individual `PathMonitor` instances -/// - Registers the resulting task specifications with the system for later use in handling -/// file system events -/// -/// The monitoring configuration respects the `watchers` and `infer` settings in the input, -/// allowing for flexible control over which files and directories are watched. -#[derive(actix::Message)] -#[rtype(result = "()")] -pub struct MonitorAny { - input: Input, -} - -impl MonitorAny { - pub fn new(input: Input) -> Self { - Self { input } - } -} - -impl actix::Handler for BsSystem { - type Result = ResponseActFuture; - - fn handle(&mut self, msg: MonitorAny, ctx: &mut Self::Context) -> Self::Result { - let cwd = self.cwd.clone(); - let recip = ctx.address().recipient(); - let monitor = self.path_monitors.clone(); - - let future = async move { - let input = msg.input; - let msg = MonitorPathWatchables::new(cwd, &input, recip); - monitor.send(msg).await?; - Ok::<_, anyhow::Error>(()) - }; - - Box::pin(future.into_actor(self).map(|res, _actor, _ctx| match res { - Ok(..) => { - let span = debug_span!("MonitorAny -> InsertResults"); - let _g = span.entered(); - // for (index, insert_result) in inner.into_iter().enumerate() { - // let task_spec = TaskSpec::opt_from(&insert_result.meta.watch_spec); - // let fs_ctx = insert_result.meta.fs_ctx; - // actor.insert_meta(insert_result.meta.fs_ctx, insert_result.meta); - // if let Some(spec) = task_spec { - // actor.insert_task_spec(fs_ctx, spec); - // } - // } - } - Err(err) => { - tracing::error!(?err); - } - })) - } -} diff --git a/crates/bsnext_system/src/monitor_input.rs b/crates/bsnext_system/src/monitor_input.rs deleted file mode 100644 index 5bbe1f98..00000000 --- a/crates/bsnext_system/src/monitor_input.rs +++ /dev/null @@ -1,72 +0,0 @@ -use crate::system::BsSystem; -use crate::watchables::any_watchable::AnyWatchable; -use crate::watchables::path_watchable::PathWatchable; -use actix::{Actor, Addr, AsyncContext}; -use bsnext_fs::{Debounce, FsEventContext}; -use bsnext_input::route::WatchSpec; -use bsnext_input::InputCtx; -use bsnext_path_monitor::path_monitor::PathMonitor; -use bsnext_path_monitor::watch_paths_msg::WatchPaths; -use std::path::PathBuf; -use std::time::Duration; - -#[derive(Debug, Clone)] -pub struct InputMonitor { - #[allow(dead_code)] - pub addr: Addr, - pub input_ctx: InputCtx, -} - -#[derive(actix::Message)] -#[rtype(result = "()")] -pub struct MonitorInput { - pub path: PathBuf, - #[allow(dead_code)] - pub cwd: PathBuf, - pub input_ctx: InputCtx, -} - -impl MonitorInput { - pub fn new(path: impl Into, input_ctx: impl Into) -> Self { - Self { - path: path.into(), - input_ctx: input_ctx.into(), - cwd: Default::default(), - } - } -} - -impl actix::Handler for BsSystem { - type Result = (); - - #[tracing::instrument(skip_all, name = "Handler->MonitorInput->BsSystem")] - fn handle(&mut self, msg: MonitorInput, ctx: &mut Self::Context) -> Self::Result { - let sys = ctx.address().recipient(); - let debounce = Debounce::Trailing { - duration: Duration::from_millis(300), - }; - - let ctx = FsEventContext::for_root(); - let paths = vec![msg.path.to_path_buf()]; - let pw = PathWatchable::Any(AnyWatchable { - dirs: paths.clone(), - watch_spec: WatchSpec::default(), - }); - - let input_path_monitor = - PathMonitor::new(sys, debounce, self.cwd.clone(), ctx, pw.spec().clone()); - - tracing::debug!("starting input monitor"); - - let path_monitor_addr = input_path_monitor.start(); - - let input_monitor = InputMonitor { - input_ctx: msg.input_ctx.clone(), - addr: path_monitor_addr.clone(), - }; - - path_monitor_addr.do_send(WatchPaths { paths }); - - self.input_monitors = Some(input_monitor); - } -} diff --git a/crates/bsnext_system/src/override_input.rs b/crates/bsnext_system/src/override_input.rs deleted file mode 100644 index a4e62831..00000000 --- a/crates/bsnext_system/src/override_input.rs +++ /dev/null @@ -1,71 +0,0 @@ -use crate::system::BsSystem; -use crate::watchables::MonitorPathWatchables; -use actix::{ActorFutureExt, AsyncContext, ResponseActFuture, WrapFuture}; -use bsnext_core::servers_supervisor::resolve_servers::ResolveServers; -use bsnext_dto::server_events::ServerError; -use bsnext_input::startup::StartupContext; -use bsnext_input::{Input, InputCtx}; - -#[derive(Debug, actix::Message)] -#[rtype(result = "Result<(), ServerError>")] -pub struct OverrideInput { - pub input: Input, -} - -impl actix::Handler for BsSystem { - type Result = ResponseActFuture>; - - fn handle(&mut self, msg: OverrideInput, ctx: &mut Self::Context) -> Self::Result { - let input_clone = msg.input.clone(); - let start_ctx_clone = self.start_context.clone(); - let addr = ctx.address(); - // let ctx_clone = self.st - let f = self - .servers() - .send(ResolveServers::new(msg.input)) - .into_actor(self) - .map(move |res, actor, _ctx| { - tracing::debug!(" + did override input"); - let _output = match res { - Ok(Ok(res)) => Ok(res), - Ok(Err(s_e)) => Err(s_e), - Err(err) => Err(ServerError::Unknown(err.to_string())), - }; - // todo: only process the override if valid? - let msg = - MonitorPathWatchables::new(actor.cwd.clone(), &input_clone, addr.recipient()); - actor.path_monitors.do_send(msg); - actor.update_ctx(&input_clone, &start_ctx_clone); - Ok(()) - }); - Box::pin(f) - } -} - -impl BsSystem { - fn update_ctx(&mut self, input: &Input, ctx: &StartupContext) { - let next = input - .servers - .iter() - .map(|s| s.identity.clone()) - .collect::>(); - - if let Some(mon) = self.input_monitors.as_mut() { - let next_input_ctx = InputCtx::new(&next, None, ctx, mon.input_ctx.file_path()); - if !next.is_empty() { - if next_input_ctx == mon.input_ctx { - tracing::info!( - " - server identities were equal, not updating ctx {:?}", - next_input_ctx - ); - } else { - tracing::info!( - " + updating stored server identities following a file change {:?}", - next - ); - mon.input_ctx = next_input_ctx - } - } - } - } -} diff --git a/crates/bsnext_system/src/path_monitors/mod.rs b/crates/bsnext_system/src/path_monitors/mod.rs index 5af433fa..716fcec8 100644 --- a/crates/bsnext_system/src/path_monitors/mod.rs +++ b/crates/bsnext_system/src/path_monitors/mod.rs @@ -1,28 +1,123 @@ -use crate::watchables::path_watchable::PathWatchable; -use crate::watchables::MonitorPathWatchables; -use actix::{Actor, Addr, AsyncContext, ResponseFuture}; -use bsnext_fs::{Debounce, FsEventContext}; -use bsnext_path_monitor::path_monitor::{PathMonitor, StopPathMonitor}; +use actix::{Actor, Addr, AsyncContext, Recipient, ResponseActFuture, ResponseFuture, WrapFuture}; +use actix::{ActorFutureExt, Running}; +use bsnext_core::servers_supervisor::actor::ServersSupervisor; +use bsnext_core::servers_supervisor::resolve_servers::ResolveServers; +use bsnext_dto::status_events::{ + list_hash, MonitorStatusReader, MonitorStatusWriter, ServiceStatus, StateValue, +}; +use bsnext_dto::status_events_dto::ResourceStatus; +use bsnext_fs::FsEventContext; +use bsnext_input::input_src::InputSrc; +use bsnext_input::watchables::path_watchable::PathWatchable; +use bsnext_input::watchables::PathWatchables; +use bsnext_input::Input; +use bsnext_path_monitor::path_monitor::{ConnectedWatchers, PathMonitor, StopPathMonitor}; use bsnext_path_monitor::watch_paths_msg::WatchPaths; +use bsnext_path_monitor::PathMonitorChangeset; use std::collections::{BTreeSet, HashMap}; -use std::path::PathBuf; +use std::path::{Path, PathBuf}; +use std::time::Duration; use tracing::{debug, debug_span}; +#[derive(Debug, Default, Clone)] +enum LocalResource { + #[default] + Pending, + Waiting { + reason: String, + attempts: usize, + }, + Ready, + Failed { + reason: String, + }, +} + +impl From<&'_ LocalResource> for ResourceStatus { + fn from(value: &'_ LocalResource) -> Self { + match value { + LocalResource::Pending => ResourceStatus::Pending, + LocalResource::Waiting { reason, .. } => ResourceStatus::Waiting { + reason: reason.clone(), + }, + LocalResource::Ready => ResourceStatus::Ready, + LocalResource::Failed { reason } => ResourceStatus::Failed { + reason: reason.clone(), + }, + } + } +} + #[derive(Debug, Default)] +struct LocalState { + inner: HashMap, +} + +impl LocalState { + pub(crate) fn as_resource_status(&self) -> HashMap { + todo!("ResourceStatus must support a 'backoff' variant to determine when easy sub resource is safe to try again"); + let mut resource_status = HashMap::new(); + for (path_watchable, local_resource) in &self.inner { + resource_status.insert(path_watchable.clone(), ResourceStatus::from(local_resource)); + } + resource_status + } + pub(crate) fn should_reconcile(&self) -> bool { + self.inner + .iter() + .any(|(k, v)| matches!(v, LocalResource::Pending | LocalResource::Waiting { .. })) + } +} + +#[derive(Debug)] pub struct PathMonitors { - path_monitors: HashMap>, + cwd: PathBuf, + path_monitor_addresses: HashMap>, + local_state: LocalState, + state_reader: Recipient, + state_writer: Recipient, + status: ServiceStatus, + status_hashes: Vec, + recipient: Option>, + reconcile_count: usize, } impl PathMonitors { - pub fn new() -> Self { + pub fn new( + cwd: PathBuf, + state_reader: Recipient, + state_writer: Recipient, + ) -> Self { Self { - path_monitors: Default::default(), + cwd, + path_monitor_addresses: Default::default(), + local_state: Default::default(), + state_writer, + state_reader, + status_hashes: vec![], + status: ServiceStatus::default(), + recipient: None, + reconcile_count: 0, } } } impl actix::Actor for PathMonitors { type Context = actix::Context; + + fn started(&mut self, _ctx: &mut Self::Context) { + tracing::trace!(actor.name = "PathMonitors", actor.lifecyle = "started"); + } + + fn stopping(&mut self, _ctx: &mut Self::Context) -> Running { + tracing::trace!(actor.name = "PathMonitors", actor.lifecyle = "stopping"); + Running::Stop + } + + fn stopped(&mut self, _ctx: &mut Self::Context) { + tracing::trace!(actor.name = "PathMonitors", actor.lifecyle = "stopped"); + self.local_state.inner.clear(); + } } #[derive(actix::Message)] @@ -33,68 +128,118 @@ pub struct DropMonitor(pub PathWatchable); #[rtype(result = "()")] pub struct InsertMonitor(pub PathWatchable, pub Addr, pub Vec); -impl actix::Handler for PathMonitors { +#[derive(actix::Message)] +#[rtype(result = "()")] +pub struct RequestMonitor { + inner: PathWatchables, + recipient: Recipient, + cwd: PathBuf, +} + +impl RequestMonitor { + pub(crate) fn new( + inner: PathWatchables, + recipient: Recipient, + cwd: &Path, + ) -> Self { + Self { + inner, + recipient, + cwd: cwd.to_owned(), + } + } +} + +impl actix::Handler for PathMonitors { type Result = ResponseFuture<()>; - #[tracing::instrument(skip_all, name = "MonitorPathWatchables->Monitor")] - fn handle(&mut self, msg: MonitorPathWatchables, ctx: &mut Self::Context) -> Self::Result { + #[tracing::instrument(skip_all, name = "RequestMonitor->Monitor")] + fn handle( + &mut self, + RequestMonitor { + inner, + recipient, + cwd, + }: RequestMonitor, + ctx: &mut Self::Context, + ) -> Self::Result { debug!("{}", file!()); - let existing = self.path_monitors.keys().collect::>(); - let incoming = msg.watchables.iter().collect::>(); + let existing = self.path_monitor_addresses.keys().collect::>(); + let incoming = inner.watchables.iter().collect::>(); let in_both = incoming.intersection(&existing).collect::>(); - let to_add = incoming.difference(&existing).collect::>(); + let to_skip = self + .local_state + .inner + .iter() + .filter_map(|(path_watchable, local_resource)| match local_resource { + LocalResource::Failed { .. } => Some(path_watchable.clone()), + _ => None, + }) + .collect::>(); + let to_add = incoming + .difference(&existing) + .filter(|x| !to_skip.contains(x)) + .collect::>(); let to_remove = existing.difference(&incoming).collect::>(); debug!("{} duplicates", in_both.len()); debug!("{} monitors to remove", to_remove.len()); debug!("{} monitors to add", to_add.len()); + debug!("{} monitors to skip", to_skip.len()); for any_watchable in to_remove { - if let Some(path_monitor_addr) = self.path_monitors.get(any_watchable) { + if let Some(path_monitor_addr) = self.path_monitor_addresses.get(any_watchable) { path_monitor_addr.do_send(StopPathMonitor); ctx.notify(DropMonitor((*any_watchable).clone())) } } - for (index, any_watchable) in to_add.into_iter().enumerate() { + for (index, path_watchable) in to_add.into_iter().enumerate() { let span = debug_span!("{}", index); let _guard = span.enter(); - let watchable_hash = any_watchable.as_id(); - let paths = any_watchable + let watchable_hash = path_watchable.as_id(); + let paths = path_watchable .watch_paths() .into_iter() .map(ToOwned::to_owned) .collect::>(); + tracing::trace!(?watchable_hash); - let fs_ctx_id = match any_watchable { - PathWatchable::Server(watchable) => watchable.server_identity.as_id(), - PathWatchable::Route(watchable) => watchable.server_identity.as_id(), - PathWatchable::Any(_) => watchable_hash, + let fs_ctx = match path_watchable { + PathWatchable::Server(watchable) => { + let id = watchable.server_identity.as_id(); + FsEventContext::new(id, watchable_hash) + } + PathWatchable::Route(watchable) => { + let id = watchable.server_identity.as_id(); + FsEventContext::new(id, watchable_hash) + } + PathWatchable::Any(_) => FsEventContext::new(watchable_hash, watchable_hash), + PathWatchable::Input(_) => FsEventContext::for_root(watchable_hash), }; - tracing::trace!(?fs_ctx_id); - let fs_ctx = FsEventContext::new(fs_ctx_id, watchable_hash); - let spec = any_watchable.spec(); + tracing::trace!(?fs_ctx); + + let spec = path_watchable.spec(); tracing::trace!(?spec); - let debounce = spec.debounce.map(Debounce::from).unwrap_or_default(); + let debounce = path_watchable.debounce(); tracing::trace!(?debounce); let path_monitor = PathMonitor::new( - msg.recipient.clone(), + recipient.clone(), debounce, - msg.cwd.clone(), + cwd.clone(), fs_ctx, spec.clone(), ); let path_monitor_addr = path_monitor.start(); - ctx.notify(InsertMonitor( - (*any_watchable).clone(), + (**path_watchable).clone(), path_monitor_addr, paths, )) @@ -109,8 +254,11 @@ impl actix::Handler for PathMonitors { fn handle(&mut self, msg: DropMonitor, _ctx: &mut Self::Context) -> Self::Result { tracing::trace!(watchable=?msg.0, "DropMonitor"); - self.path_monitors.remove(&msg.0); - tracing::trace!("dropped, Monitor count {}", self.path_monitors.len()); + self.path_monitor_addresses.remove(&msg.0); + tracing::trace!( + "dropped, Monitor count {}", + self.path_monitor_addresses.len() + ); } } @@ -125,8 +273,361 @@ impl actix::Handler for PathMonitors { let span = debug_span!("InsertMonitor"); let _guard = span.enter(); debug!("{}", watchable); - self.path_monitors.insert(watchable, addr.clone()); - debug!("+ Monitor count {}", self.path_monitors.len()); + self.path_monitor_addresses.insert(watchable, addr.clone()); + debug!("+ Monitor count {}", self.path_monitor_addresses.len()); addr.do_send(WatchPaths { paths }); } } + +/// Message to monitor file system paths based on the current input configuration. +/// +/// This handler processes an `Input` configuration to determine which paths should be +/// monitored for file system changes. It: +/// - Converts the input into a collection of watchables based on the configured watch strategy +/// (routes, servers, or any custom watchers) +/// - Sends these watchables to the `Monitor` actor to create individual `PathMonitor` instances +/// - Registers the resulting task specifications with the system for later use in handling +/// file system events +/// +/// The monitoring configuration respects the `watchers` and `infer` settings in the input, +/// allowing for flexible control over which files and directories are watched. +#[derive(actix::Message)] +#[rtype(result = "Result<(), anyhow::Error>")] +pub struct ResolveMonitors; + +impl Default for ResolveMonitors { + fn default() -> Self { + Self::new() + } +} + +impl ResolveMonitors { + pub fn new() -> Self { + Self + } +} + +impl actix::Handler for PathMonitors { + type Result = ResponseActFuture>; + + fn handle(&mut self, _msg: ResolveMonitors, ctx: &mut Self::Context) -> Self::Result { + let _cwd = self.cwd.clone(); + let monitors_addr = ctx.address(); + let state_reader = self.state_reader.clone(); + let local_status = self.status; + let _local_hashes = self.status_hashes.clone(); + let Some(_recipient) = self.recipient.clone() else { + todo!("How can this happen?"); + }; + let future = async move { + let _ = monitors_addr.send(TryEvict).await?; + let res = state_reader.send(MonitorStatusReader).await?; + let (sys_service_status, input, input_srcs) = res; + + if let (ServiceStatus::Ready { .. }, ServiceStatus::Ready { .. }) = + (sys_service_status, local_status) + { + tracing::info!("doing nothing, sys + local state match"); + tracing::info!(?sys_service_status); + tracing::info!(?local_status); + return Ok(None); + } + + let expected_id = match sys_service_status { + ServiceStatus::Idle => todo!("how can we get here?"), + ServiceStatus::Reconciling { desired, .. } => desired, + ServiceStatus::Ready { observed, .. } => observed, + ServiceStatus::Degraded { desired } => desired, + }; + + Ok(Some((expected_id, input, input_srcs))) + }; + + Box::pin(future.into_actor(self).map(|res: anyhow::Result<_>, actor, ctx| { + let res = res?; + match res { + None => { + tracing::debug!("--- we decided there's nothing to do because local and remote states match") + } + Some((desired, input, input_src)) => { + tracing::debug!("+++ There's something to reconcile..."); + actor.status = ServiceStatus::Reconciling { + desired, + observed: actor.status.observed(), + }; + ctx.notify(TryReconcile { input, input_src }); + } + } + Ok::<_, anyhow::Error>(()) + })) + } +} + +#[derive(actix::Message)] +#[rtype(result = "Result<(), anyhow::Error>")] +struct TryReconcile { + input: Input, + input_src: Vec, +} + +impl actix::Handler for PathMonitors { + type Result = ResponseActFuture>; + + fn handle(&mut self, msg: TryReconcile, ctx: &mut Self::Context) -> Self::Result { + let input = msg.input; + let input_src = msg.input_src; + let Some(recipient) = self.recipient.clone() else { + todo!("How can this happen?"); + }; + let watchables = PathWatchables::new(&input, &input_src, self.cwd.as_ref()); + for watchable in &watchables.watchables { + self.local_state.inner.entry(watchable.clone()).or_default(); + } + self.state_writer.do_send(MonitorStatusWriter { + monitor_status: self.status, + monitor_resource_status: self.local_state.as_resource_status(), + }); + let request = RequestMonitor::new(watchables, recipient, &self.cwd); + let f = ctx.address().send(request); + Box::pin(f.into_actor(self).map(|_result, _actor, ctx| { + ctx.notify(TryRead); + Ok(()) + })) + } +} + +#[derive(actix::Message)] +#[rtype(result = "Result<(), anyhow::Error>")] +struct TryRead; + +impl actix::Handler for PathMonitors { + type Result = ResponseActFuture>; + + fn handle(&mut self, _msg: TryRead, _ctx: &mut Self::Context) -> Self::Result { + let jobs = self + .path_monitor_addresses + .clone() + .iter() + .map(|(path_watchable, address)| { + ( + path_watchable.clone(), + ( + address.clone(), + self.local_state + .inner + .get(path_watchable) + .map(ToOwned::to_owned) + .expect("If we get here there's a buug"), + ), + ) + }) + .collect::, LocalResource)>>(); + let jobs_len = jobs.len(); + let state_writer = self.state_writer.clone(); + + #[derive(Debug)] + enum LocalResult { + Ready { + observed_status: StateValue, + local_states: HashMap, + }, + NotReady { + observed_status: StateValue, + local_states: HashMap, + }, + } + + let future = async move { + tracing::debug!( + "will ask {} addresses for their ConnectedWatchers", + jobs_len + ); + let mut hashes = vec![]; + let mut local_states: HashMap = HashMap::new(); + for (path_watchable, (addr, local_resource)) in jobs { + let hash = path_watchable.as_id(); + let connected_result = addr.send(ConnectedWatchers).await?; + let is_good = connected_result.observed_len == connected_result.desired_len; + if is_good { + hashes.push(hash); + local_states.insert(path_watchable, LocalResource::Ready); + } else { + let next = match local_resource { + LocalResource::Pending => LocalResource::Waiting { + reason: "didn't start".to_string(), + attempts: 1, + }, + LocalResource::Waiting { attempts, .. } if attempts == 5 => { + LocalResource::Failed { + reason: format!("max attempts reached ({})", attempts), + } + } + LocalResource::Waiting { attempts, .. } => LocalResource::Waiting { + reason: "didn't start".to_string(), + attempts: attempts + 1, + }, + LocalResource::Ready => LocalResource::Waiting { + reason: "was ready, lost?".to_string(), + attempts: 0, + }, + LocalResource::Failed { reason: _ } => LocalResource::Failed { + reason: "failed again...".to_string(), + }, + }; + local_states.insert(path_watchable, next); + } + } + let list = list_hash(&hashes); + let state_value = StateValue::new(list); + let result = if hashes.len() == jobs_len { + LocalResult::Ready { + observed_status: state_value, + local_states, + } + } else { + LocalResult::NotReady { + observed_status: state_value, + local_states, + } + }; + Ok::<_, anyhow::Error>(result) + }; + + Box::pin(future.into_actor(self).map(move |res, act, ctx| { + let Ok(res) = res else { + tracing::error!("Failed to get ConnectedWatchers: {:?}", res.unwrap_err()); + return Ok(()); + }; + + match res { + LocalResult::Ready { + observed_status: observed_local, + local_states, + } => { + act.local_state = LocalState { + inner: local_states, + }; + let should_reconcile = act.local_state.should_reconcile(); + act.status.set_next(&observed_local, should_reconcile); + } + LocalResult::NotReady { + observed_status: observed_local, + local_states, + } => { + tracing::debug!("local result was not ready, setting to reconciling..."); + act.local_state = LocalState { + inner: local_states, + }; + let observed_prev = act.status.observed(); + act.status = ServiceStatus::Reconciling { + desired: observed_local, + observed: observed_prev, + }; + } + } + state_writer.do_send(MonitorStatusWriter { + monitor_status: act.status, + monitor_resource_status: act.local_state.as_resource_status(), + }); + + todo!("must choose how/when to reconcile again, based on child resource status"); + // match reconcile_after(&act.status) { + // NextReconcile::None => {} + // NextReconcile::Duration { duration } => { + // ctx.notify_later( + // ReconcileLater { + // prev: act.reconcile_count, + // }, + // duration, + // ); + // } + // } + + Ok(()) + })) + } +} + +#[derive(Debug, Hash, Clone, Copy, actix::Message)] +#[rtype(result = "()")] +struct ReconcileLater { + prev: usize, +} + +impl actix::Handler for PathMonitors { + type Result = (); + + fn handle(&mut self, msg: ReconcileLater, ctx: &mut Self::Context) -> Self::Result { + if msg.prev != self.reconcile_count { + tracing::debug!(?msg.prev, ?self.reconcile_count, "bail"); + return (); + } + ctx.notify(ResolveMonitors::new()) + } +} + +#[derive(actix::Message)] +#[rtype(result = "Result<(), anyhow::Error>")] +struct TryEvict; + +impl actix::Handler for PathMonitors { + type Result = ResponseActFuture>; + + fn handle(&mut self, _msg: TryEvict, _ctx: &mut Self::Context) -> Self::Result { + let addrs = self.path_monitor_addresses.clone(); + let addr_len = addrs.len(); + + let future = async move { + tracing::debug!( + "will ask {} addresses for their ConnectedWatchers", + addr_len + ); + let mut removals = vec![]; + for (path_watchable, addr) in addrs { + let re = addr.send(ConnectedWatchers).await?; + if re.observed_len != re.desired_len { + removals.push(path_watchable); + } + } + + if !removals.is_empty() { + return Ok::<_, anyhow::Error>(Some(removals)); + } + + Ok::<_, anyhow::Error>(None) + }; + + Box::pin(future.into_actor(self).map(|res, act, _ctx| { + if let Ok(Some(removals)) = res { + tracing::debug!( + "removing {} path watchables because they never connected", + removals.len() + ); + for path_watchable in removals { + act.path_monitor_addresses.remove(&path_watchable); + } + } + Ok(()) + })) + } +} + +#[derive(actix::Message)] +#[rtype(result = "()")] +pub struct ConfigureRecipient { + recipient: Recipient, +} + +impl ConfigureRecipient { + pub fn new(recipient: Recipient) -> Self { + Self { recipient } + } +} + +impl actix::Handler for PathMonitors { + type Result = (); + + fn handle(&mut self, msg: ConfigureRecipient, _ctx: &mut Self::Context) -> Self::Result { + self.recipient = Some(msg.recipient); + } +} diff --git a/crates/bsnext_system/src/run/mod.rs b/crates/bsnext_system/src/run/mod.rs index aec9c7af..ca68f074 100644 --- a/crates/bsnext_system/src/run/mod.rs +++ b/crates/bsnext_system/src/run/mod.rs @@ -54,7 +54,7 @@ pub struct RunCommand { /// commands to run #[arg(long = "sh")] pub sh_commands: Vec, - /// provide this flag to disable command prefixes + /// provide this flag to disable global prefixes #[arg(long = "no-prefix", default_value = "false")] pub no_prefix: bool, /// logging options @@ -92,7 +92,7 @@ impl RunCommand { ) -> anyhow::Result<(Input, InputResolution)> { // try to resolve input from disk let input = addr - .send(ResolveInput::from_strs(&input_opts.input)) + .send(ResolveInput::from_strs(&input_opts.input, &None)) .await .context("mailbox")??; @@ -147,7 +147,7 @@ impl SystemStart for RunCommand { let top_level = TopLevelRunMode::Seq; let _id = input.as_id(); - let _r = addr.send(CommitInput::new(input.clone())).await; + let _r = addr.send(CommitInput::new(input.clone(), &[])).await; match run_mode { RunMode::Exec { .. } => { diff --git a/crates/bsnext_system/src/start/start_command.rs b/crates/bsnext_system/src/start/start_command.rs index 6133954d..ef7f93de 100644 --- a/crates/bsnext_system/src/start/start_command.rs +++ b/crates/bsnext_system/src/start/start_command.rs @@ -15,7 +15,7 @@ use bsnext_dto::any_event::AnyEvent; use bsnext_dto::StartupError; use bsnext_input::route::{CorsOpts, Opts}; use bsnext_input::server_config::{ServerConfig, ServerIdentity}; -use bsnext_input::{Input, InputArgs, InputCtx, WatchGlobalConfig}; +use bsnext_input::{Input, InputArgs, InputCtx, InputCtxSource, WatchGlobalConfig}; use bsnext_tracing::OutputFormat; use std::path::{Path, PathBuf}; use tokio::sync::mpsc::Sender; @@ -38,6 +38,10 @@ pub struct StartCommand { #[clap(flatten)] pub logging: LoggingOpts, + /// provide this flag to disable command prefixes + #[arg(long = "no-prefix", default_value = "false")] + pub no_prefix: bool, + /// output options #[arg(short, long, value_enum, default_value_t)] pub format: OutputFormat, @@ -73,7 +77,7 @@ impl SystemStart for StartCommand { .context("Trying to get ctx")?; // prepare initial input before any tasks should run - let (mut input, resolution) = self.prepare_input(&addr, &input_opts).await?; + let (mut input, resolution) = self.prepare_input(&addr, &input_opts, &self.port).await?; // now run any 'before' tasks run before we try anything. initial_tasks(&addr, input.clone()).await?; @@ -89,12 +93,13 @@ impl SystemStart for StartCommand { let _id = input.as_id(); match resolution { InputResolution::Default => { - let _r = addr.send(CommitInput::new(input)).await; + let _r = addr.send(CommitInput::new(input, &[])).await; } InputResolution::File(file) => { let args = InputArgs::new(self.port); let server_ids = input.ids(); let ctx = InputCtx::new(&server_ids, Some(args), &startup_ctx, Some(&file)); + let ctx = InputCtxSource::New(ctx); let _r = addr.send(CommitInputFile::new(input, file, ctx)).await; } } @@ -114,10 +119,11 @@ impl StartCommand { &self, addr: &Addr, input_opts: &InputOpts, + optional_port: &Option, ) -> anyhow::Result<(Input, InputResolution)> { // try to resolve input from disk let input = addr - .send(ResolveInput::from_strs(&input_opts.input)) + .send(ResolveInput::from_strs(&input_opts.input, optional_port)) .await .context("mailbox")??; @@ -152,8 +158,7 @@ impl StartCommand { let identity = ServerIdentity::from_port_or_named(port).context("port")?; - let server_config = server_config_from_paths(cwd, &paths, &route_opts, identity) - .context("server config")?; + let server_config = server_config_from_paths(cwd, &paths, &route_opts, identity)?; Ok(server_config) } diff --git a/crates/bsnext_system/src/status_tracker.rs b/crates/bsnext_system/src/status_tracker.rs new file mode 100644 index 00000000..5b0232ac --- /dev/null +++ b/crates/bsnext_system/src/status_tracker.rs @@ -0,0 +1,185 @@ +use crate::system::Accept; +use actix::{Actor, Handler, ResponseFuture}; +use actix_rt::Arbiter; +use bsnext_dto::any_event::AnyEvent; +use bsnext_dto::external_events::ExternalEventsDTO; +use bsnext_dto::status_events::{ + monitor_status_hash, server_status_hash, MonitorStatusReader, MonitorStatusWriter, + ServerStatusReader, ServerStatusWriter, ServiceStatus, StateValue, Transition, +}; +use bsnext_dto::status_events_dto::{ResourceStatus, TransitionDTO}; +use bsnext_input::input_src::InputSrc; +use bsnext_input::server_config::ServerIdentity; +use bsnext_input::watchables::path_watchable::PathWatchable; +use bsnext_input::watchables::PathWatchables; +use bsnext_input::Input; +use std::collections::HashMap; +use std::path::PathBuf; +use tokio::sync::mpsc::Sender; +use tracing::debug_span; + +pub struct StatusTracker { + input: Input, + cwd: PathBuf, + input_src: Vec, + servers_status: ServiceStatus, + monitor_status: ServiceStatus, + monitor_resource_status: HashMap, + server_resource_status: HashMap, + sender: Sender, +} + +impl Actor for StatusTracker { + type Context = actix::Context; +} + +impl Handler for StatusTracker { + type Result = ResponseFuture<()>; + + fn handle(&mut self, msg: Accept, _ctx: &mut Self::Context) -> Self::Result { + self.input_src = msg.input_src; + self.mark_servers(&msg.input); + self.mark_monitors(&msg.input); + self.input = msg.input; + self.cwd = msg.cwd; + tracing::info!(status = ?self.servers_status, "did mark servers, next state"); + tracing::info!(status = ?self.monitor_status, "did mark monitors, next state"); + Box::pin(async move { + let _a = ""; + }) + } +} + +impl StatusTracker { + pub fn new(cwd: PathBuf, sender: Sender) -> Self { + Self { + servers_status: ServiceStatus::default(), + monitor_status: ServiceStatus::default(), + monitor_resource_status: Default::default(), + server_resource_status: Default::default(), + input: Input::default(), + input_src: vec![], + cwd, + sender, + } + } + fn mark_servers(&mut self, input: &Input) { + tracing::info!("will mark servers"); + let id = server_status_hash(&input.servers); + let next_desired = StateValue::new(id); + self.servers_status = next_from(self.servers_status, next_desired); + tracing::info!(id = id, "hasher for servers") + } + fn mark_monitors(&mut self, input: &Input) { + tracing::info!("will mark monitors"); + let path_watchables = PathWatchables::new(input, &self.input_src, &self.cwd); + let id = monitor_status_hash(&path_watchables); + let next_desired = StateValue::new(id); + self.monitor_status = next_from(self.monitor_status, next_desired); + } +} + +fn next_from(curr: ServiceStatus, next_desired: StateValue) -> ServiceStatus { + match curr { + ServiceStatus::Idle => ServiceStatus::Reconciling { + observed: None, + desired: next_desired, + }, + ServiceStatus::Reconciling { + // here we drop the old desired state + desired: _, + observed, + } => ServiceStatus::Reconciling { + observed, + desired: next_desired, + }, + ServiceStatus::Ready { observed } if observed != next_desired => { + ServiceStatus::Reconciling { + observed: Some(observed), + desired: next_desired, + } + } + ServiceStatus::Ready { observed } => ServiceStatus::Ready { observed }, + ServiceStatus::Degraded { desired } if desired != next_desired => { + ServiceStatus::Reconciling { + observed: None, + desired: next_desired, + } + } + ServiceStatus::Degraded { desired } => ServiceStatus::Degraded { desired }, + } +} + +impl Handler for StatusTracker { + type Result = ResponseFuture<(ServiceStatus, Input)>; + + fn handle(&mut self, _msg: ServerStatusReader, _ctx: &mut Self::Context) -> Self::Result { + Box::pin(futures::future::ready(( + self.servers_status, + self.input.clone(), + ))) + } +} + +impl Handler for StatusTracker { + type Result = ResponseFuture<(ServiceStatus, Input, Vec)>; + + fn handle(&mut self, _msg: MonitorStatusReader, _ctx: &mut Self::Context) -> Self::Result { + Box::pin(futures::future::ready(( + self.monitor_status, + self.input.clone(), + self.input_src.clone(), + ))) + } +} + +impl Handler for StatusTracker { + type Result = (); + + fn handle(&mut self, msg: MonitorStatusWriter, _ctx: &mut Self::Context) -> Self::Result { + let span = tracing::info_span!("monitor status"); + let _g = span.enter(); + tracing::info!("status writer for monitors"); + tracing::debug!(prev.status = ?self.monitor_status, " --> "); + tracing::debug!(prev.resource_status = ?self.monitor_resource_status, " --> "); + tracing::debug!(next.status = ?msg.monitor_status, " --> "); + tracing::debug!(next.resource_status = ?msg.monitor_resource_status, " --> "); + for (path_watchable, status) in &msg.monitor_resource_status { + let span = debug_span!("monitor resource status", id = ?path_watchable); + let _g = span.enter(); + let did_transition = self + .monitor_resource_status + .get(path_watchable) + .is_some_and(|x| x != status); + tracing::info!(did_transition); + let sender = self.sender.clone(); + if did_transition { + let evt = Transition::path_monitor(status.clone(), path_watchable.clone()); + let trans = TransitionDTO::from(evt); + Arbiter::current().spawn(async move { + let _ = sender + .send(AnyEvent::External(ExternalEventsDTO::Transition(trans))) + .await; + }); + } + } + self.monitor_status = msg.monitor_status; + self.monitor_resource_status = msg.monitor_resource_status; + } +} + +impl Handler for StatusTracker { + type Result = ResponseFuture<()>; + + fn handle(&mut self, msg: ServerStatusWriter, _ctx: &mut Self::Context) -> Self::Result { + let span = tracing::info_span!("servers status"); + let _g = span.enter(); + tracing::info!("status writer for servers"); + tracing::info!(prev.status = ?self.servers_status, " --> "); + tracing::info!(next.status = ?msg.servers_status, " --> "); + + self.servers_status = msg.servers_status; + self.server_resource_status = msg.server_resource_status; + Box::pin(async move {}) + } +} diff --git a/crates/bsnext_system/src/system.rs b/crates/bsnext_system/src/system.rs index 8a3ade40..003cf6eb 100644 --- a/crates/bsnext_system/src/system.rs +++ b/crates/bsnext_system/src/system.rs @@ -2,11 +2,13 @@ use crate::capabilities::Capabilities; use crate::fs_task_tracker::FsTaskTracker; use crate::input_fs::from_input_path; use crate::invoke_scope::{InvokeScope, Invoker}; -use crate::monitor_any::MonitorAny; -use crate::monitor_input::{InputMonitor, MonitorInput}; -use crate::path_monitors::PathMonitors; +use crate::path_monitors::{ConfigureRecipient, PathMonitors, ResolveMonitors}; +use crate::status_tracker::StatusTracker; use crate::tasks::task_spec::TaskSpec; -use actix::{Actor, Addr, AsyncContext, Handler, ResponseFuture, Running}; +use actix::ActorFutureExt; +use actix::{ + Actor, Addr, AsyncContext, Handler, ResponseActFuture, ResponseFuture, Running, WrapFuture, +}; use actix_rt::Arbiter; use bsnext_core::servers_supervisor::actor::ServersSupervisor; use bsnext_core::servers_supervisor::resolve_servers::ResolveServers; @@ -16,8 +18,9 @@ use bsnext_dto::internal_events::InternalEvents; use bsnext_dto::task_events::TaskReportAndTree; use bsnext_dto::{InputErrorDetailDTO, StartupErrorDTO}; use bsnext_input::input_fs::ResolvedInputOutcome; +use bsnext_input::input_src::{FileInputSrc, InputSrc}; use bsnext_input::startup::StartupContext; -use bsnext_input::{Input, InputCtx, InputError}; +use bsnext_input::{Input, InputArgs, InputCtx, InputCtxSource, InputError}; use bsnext_task::task_trigger::{ExecTrigger, TaskTrigger, TaskTriggerSource}; use std::path::PathBuf; use tokio::sync::mpsc::Sender; @@ -28,7 +31,8 @@ pub struct BsSystem { pub(crate) self_addr: Option>, servers_addr: Addr, any_event_sender: Sender, - pub(crate) input_monitors: Option, + pub(crate) status_tracker: Addr, + pub(crate) input_ctx: Option, pub(crate) fs_task_tracker: Addr, pub(crate) path_monitors: Addr, pub(crate) invoker_addr: Addr, @@ -42,6 +46,8 @@ impl Actor for BsSystem { fn started(&mut self, ctx: &mut Self::Context) { tracing::trace!(actor.name = "BsSystem", actor.lifecyle = "started"); self.self_addr = Some(ctx.address()); + self.path_monitors + .do_send(ConfigureRecipient::new(ctx.address().recipient())); } fn stopping(&mut self, _ctx: &mut Self::Context) -> Running { @@ -68,7 +74,15 @@ impl BsSystem { cwd: PathBuf, tx: tokio::sync::oneshot::Sender<()>, ) -> Self { - let servers = ServersSupervisor::new(tx, any_event_sender.clone()); + // todo!("figure where the event goes? probably the status tracker can broadcast updates onto any_event_sender?"); + let status_tracker = StatusTracker::new(cwd.clone(), any_event_sender.clone()); + let status_tracker = status_tracker.start(); + let servers = ServersSupervisor::new( + tx, + any_event_sender.clone(), + status_tracker.clone().recipient(), + status_tracker.clone().recipient(), + ); let servers_addr = servers.start(); let capabilities = Capabilities::new(any_event_sender.clone(), servers_addr.clone()); let capabilities_addr = capabilities.start(); @@ -76,18 +90,23 @@ impl BsSystem { let invoker = Invoker::new(capabilities_addr.clone(), any_event_sender.clone()); let invoker_addr = invoker.start(); let fs_task_tracker = FsTaskTracker::new(invoker_addr.clone().recipient()).start(); - let monitor = PathMonitors::new(); - let monitor = monitor.start(); + let path_monitors = PathMonitors::new( + cwd.clone(), + status_tracker.clone().recipient(), + status_tracker.clone().recipient(), + ); + let monitor = path_monitors.start(); BsSystem { self_addr: None, servers_addr, any_event_sender, - input_monitors: None, + input_ctx: None, path_monitors: monitor, invoker_addr, fs_task_tracker, cwd, start_context, + status_tracker, } } @@ -145,6 +164,14 @@ impl BsSystem { } } +#[derive(Debug, actix::Message)] +#[rtype(result = "()")] +pub struct Accept { + pub input: Input, + pub cwd: PathBuf, + pub input_src: Vec, +} + #[derive(Debug, actix::Message)] #[rtype(result = "StartupContext")] pub struct GetStartContext; @@ -161,12 +188,14 @@ impl Handler for BsSystem { #[rtype(result = "Result, Box>")] pub struct ResolveInput { pub input_paths: Vec, + pub optional_port: Option, } impl ResolveInput { - pub fn from_strs>(paths: &[A]) -> Self { + pub fn from_strs>(paths: &[A], optional_port: &Option) -> Self { Self { input_paths: paths.iter().map(|s| s.as_ref().to_string()).collect(), + optional_port: *optional_port, } } } @@ -182,19 +211,45 @@ impl Handler for BsSystem { fn handle(&mut self, msg: ResolveInput, _ctx: &mut Self::Context) -> Self::Result { let cwd = self.cwd.clone(); - let start = self.start_context.clone(); + let startup_ctx = self.start_context.clone(); + + let optional_port = msg + .optional_port + .or(self.input_ctx.as_ref().and_then(|x| x.port())); + + let prev_ids = self + .input_ctx + .as_ref() + .and_then(|ctx| ctx.server_ids().map(ToOwned::to_owned)) + .unwrap_or_default(); + + let input_paths = if !msg.input_paths.is_empty() { + msg.input_paths + } else { + let prev_path = self + .input_ctx + .as_ref() + .and_then(|c| c.file_path().to_owned()); + prev_path + .map(|pb| vec![pb.to_string_lossy().to_string()]) + .unwrap_or_default() + }; + Box::pin(async move { - match ResolvedInputOutcome::new(cwd.clone(), &msg.input_paths) { + match ResolvedInputOutcome::new(cwd.clone(), &input_paths) { ResolvedInputOutcome::Missing { err, .. } => Err(err), ResolvedInputOutcome::GivenPath { ref absolute, .. } => { - let ctx = InputCtx::new(&[], None, &start, Some(absolute)); + let args = optional_port.map(InputArgs::new); + let ctx = InputCtx::new(&prev_ids, args.clone(), &startup_ctx, Some(absolute)); + tracing::debug!(?absolute, ?args, ?ctx, "ResolvedInputOutcome::GivenPath"); Ok(Some(ResolveInputResult { input: from_input_path(absolute, &ctx)?, absolute: absolute.clone(), })) } ResolvedInputOutcome::Auto { ref absolute, .. } => { - let ctx = InputCtx::new(&[], None, &start, Some(absolute)); + let args = optional_port.map(InputArgs::new); + let ctx = InputCtx::new(&prev_ids, args, &startup_ctx, Some(absolute)); Ok(Some(ResolveInputResult { input: from_input_path(absolute, &ctx)?, absolute: absolute.clone(), @@ -206,16 +261,49 @@ impl Handler for BsSystem { } } +#[derive(Debug, actix::Message)] +#[rtype(result = "Result<(), anyhow::Error>")] +pub(crate) struct ResolveInputAgain; + +impl actix::Handler for BsSystem { + type Result = ResponseActFuture>; + + fn handle(&mut self, _msg: ResolveInputAgain, ctx: &mut Self::Context) -> Self::Result { + let msg = ResolveInput { + input_paths: vec![], + optional_port: None, + }; + let f = ctx.address().send(msg); + Box::pin(f.into_actor(self).map(|result, _actor, ctx| { + match result { + Ok(Ok(Some(r))) => { + ctx.notify(CommitInputFile { + input: r.input, + absolute: r.absolute, + ctx: InputCtxSource::Prev, + }); + } + _ => { + tracing::error!("something went wrong?") + } + } + Ok(()) + })) + } +} + #[derive(Debug, actix::Message)] #[rtype(result = "Result<(), anyhow::Error>")] pub struct CommitInput { pub(crate) input: Input, + pub(crate) input_src: Vec, } impl CommitInput { - pub fn new(input: impl Into) -> Self { + pub fn new(input: impl Into, srcs: &[InputSrc]) -> Self { Self { input: input.into(), + input_src: srcs.to_vec(), } } } @@ -223,13 +311,36 @@ impl CommitInput { impl actix::Handler for BsSystem { type Result = ResponseFuture>; - fn handle(&mut self, msg: CommitInput, ctx: &mut Self::Context) -> Self::Result { + fn handle(&mut self, msg: CommitInput, _ctx: &mut Self::Context) -> Self::Result { let input = msg.input; + let input_src = msg.input_src; let servers = self.servers().clone(); - let self_addr = ctx.address(); - servers.do_send(ResolveServers::new(input.clone())); - self_addr.do_send(MonitorAny::new(input)); - Box::pin(async move { Ok(()) }) + let monitors = self.path_monitors.clone(); + let cwd = self.cwd.clone(); + tracing::info!("will commit input"); + + let status_tracker = self.status_tracker.clone(); + + // let servers_state = input.servers; + // todo: make this another thing to eventually come up + Box::pin(async move { + status_tracker + .send(Accept { + input, + cwd, + input_src, + }) + .await + .expect("mailbox"); + + tracing::info!("will ping servers"); + servers.do_send(ResolveServers::new()); + monitors.do_send(ResolveMonitors::new()); + + tracing::info!("did send accept"); + + Ok(()) + }) } } @@ -238,15 +349,15 @@ impl actix::Handler for BsSystem { pub struct CommitInputFile { pub(crate) input: Input, pub(crate) absolute: PathBuf, - pub(crate) ctx: InputCtx, + pub(crate) ctx: InputCtxSource, } impl CommitInputFile { - pub fn new(input: impl Into, pb: impl Into, ctx: impl Into) -> Self { + pub fn new(input: impl Into, pb: impl Into, ctx: InputCtxSource) -> Self { Self { input: input.into(), absolute: pb.into(), - ctx: ctx.into(), + ctx, } } } @@ -258,10 +369,20 @@ impl actix::Handler for BsSystem { let input = msg.input; let self_addr = ctx.address(); let abs = msg.absolute; - let ctx = msg.ctx; + match msg.ctx { + InputCtxSource::Prev => { + // noop + } + InputCtxSource::New(ctx) => self.input_ctx = Some(ctx), + }; Box::pin(async move { - let _v = self_addr.send(CommitInput { input }).await?; - self_addr.send(MonitorInput::new(abs, ctx)).await?; + let _v = self_addr + .send(CommitInput { + input, + input_src: vec![InputSrc::File(FileInputSrc { absolute: abs })], + }) + .await?; + // self_addr.send(MonitorInput::new(abs, ctx)).await?; Ok(()) }) } diff --git a/crates/bsnext_system/src/watch/mod.rs b/crates/bsnext_system/src/watch/mod.rs index 95545d65..ab0edbf3 100644 --- a/crates/bsnext_system/src/watch/mod.rs +++ b/crates/bsnext_system/src/watch/mod.rs @@ -62,7 +62,7 @@ impl WatchCommand { ) -> anyhow::Result { // try to resolve input from disk let input = addr - .send(ResolveInput::from_strs(&input_opts.input)) + .send(ResolveInput::from_strs(&input_opts.input, &None)) .await .context("mailbox")??; @@ -104,7 +104,7 @@ impl SystemStart for WatchCommand { // remember the ID of the input we are commiting let _id = input.as_id(); - let _r = addr.send(CommitInput::new(input)).await; + let _r = addr.send(CommitInput::new(input, &[])).await; let api = BsSystemApi::new(&addr, rx); Ok(DidStart::Started { api }) diff --git a/crates/bsnext_yaml/src/yaml_writer.rs b/crates/bsnext_yaml/src/yaml_writer.rs index bf686a5e..83b3e5df 100644 --- a/crates/bsnext_yaml/src/yaml_writer.rs +++ b/crates/bsnext_yaml/src/yaml_writer.rs @@ -1,13 +1,9 @@ -use bsnext_input::{Input, InputWriter}; +// use bsnext_input::{Input}; pub struct YamlWriter; -impl InputWriter for YamlWriter { - fn input_to_str(&self, input: &Input) -> String { - input_to_str(input) - } -} - -fn input_to_str(input: &Input) -> String { - serde_yaml::to_string(&input).expect("create yaml?") -} +// impl InputWriter for YamlWriter { +// fn input_to_str(&self, _input: &Input) -> String { +// todo!("not implemented yet!"); +// } +// } diff --git a/examples/html/timer.html b/examples/html/timer.html new file mode 100644 index 00000000..78d91912 --- /dev/null +++ b/examples/html/timer.html @@ -0,0 +1,32 @@ + + +count: + + \ No newline at end of file diff --git a/generated/dto.ts b/generated/dto.ts index 62975809..383de9c3 100644 --- a/generated/dto.ts +++ b/generated/dto.ts @@ -4,6 +4,10 @@ export type InvocationIdDTO = string; +export interface AnyWatchableDTO { + dir: string; +} + export interface ArchyNode { id: string; label: string; @@ -87,6 +91,35 @@ export interface InputErrorDetailDTO { error: string; } +export interface InputWatchableDTO { + absolute_paths: string; + relative_paths: string; +} + +/** @discriminator kind */ +export type ResourceStatus = + | { kind: "Pending", payload?: undefined } + | { kind: "Waiting", payload: { + reason: string; +}} + | { kind: "Ready", payload?: undefined } + | { kind: "Failed", payload: { + reason: string; +}}; + +/** @discriminator kind */ +export type PathWatchableDTO = + | { kind: "Server", payload: ServerWatchableDTO } + | { kind: "Route", payload: RouteWatchableDTO } + | { kind: "Any", payload: AnyWatchableDTO } + | { kind: "Input", payload: InputWatchableDTO }; + +export interface PathMonitorResourceDTO { + status: ResourceStatus; + watchable: PathWatchableDTO; + debounce: DebounceDTO; +} + /** @discriminator kind */ export type RouteKindDTO = | { kind: "Html", payload: { @@ -119,6 +152,11 @@ export interface RouteIdentityDTO { kind_str: string; } +export interface RouteWatchableDTO { + server: ServerIdentityDTO; + dir: string; +} + /** @discriminator kind */ export type ServerChange = | { kind: "Stopped", payload: { @@ -171,6 +209,16 @@ export interface ServerDesc { id: string; } +export interface ServerResourceDTO { + status: ResourceStatus; + server: ServerIdentityDTO; +} + +export interface ServerWatchableDTO { + server: ServerIdentityDTO; + dir: string; +} + export interface SseDTOOpts { body: string; } @@ -189,10 +237,6 @@ export interface StdoutLineDTO { prefix?: string; } -export interface StoppedWatchingDTO { - paths: string[]; -} - /** @discriminator kind */ export type TaskActionStageDTO = | { kind: "Started", payload: { @@ -234,11 +278,6 @@ export interface TaskTreeSummary { report_map: Record; } -export interface WatchingDTO { - paths: string[]; - debounce: DebounceDTO; -} - /** * An event describing a change * @discriminator kind @@ -280,8 +319,7 @@ export type ExternalEventsDTO = | { kind: "TaskAction", payload: TaskActionDTO } | { kind: "TaskTreePreview", payload: TaskTreePreview } | { kind: "TaskTreeSummary", payload: TaskTreeSummary } - | { kind: "Watching", payload: WatchingDTO } - | { kind: "WatchingStopped", payload: StoppedWatchingDTO }; + | { kind: "Transition", payload: TransitionDTO }; /** @discriminator kind */ export type InputErrorDTO = @@ -311,3 +349,8 @@ export type StartupEventDTO = | { kind: "Started", payload?: undefined } | { kind: "FailedStartup", payload: string }; +/** @discriminator kind */ +export type TransitionDTO = + | { kind: "Server", payload: ServerResourceDTO } + | { kind: "PathMonitor", payload: PathMonitorResourceDTO }; + diff --git a/generated/schema.js b/generated/schema.js index 02840909..248ef470 100644 --- a/generated/schema.js +++ b/generated/schema.js @@ -22,6 +22,9 @@ var EventLevel = /* @__PURE__ */ ((EventLevel2) => { // schema.ts var invocationIdDTOSchema = z.string(); +var anyWatchableDTOSchema = z.object({ + dir: z.string() +}); var archyNodeSchema = z.lazy( () => z.object({ id: z.string(), @@ -103,6 +106,58 @@ var inputAcceptedDTOSchema = z.object({ var inputErrorDetailDTOSchema = z.object({ error: z.string() }); +var inputWatchableDTOSchema = z.object({ + absolute_paths: z.string(), + relative_paths: z.string() +}); +var resourceStatusSchema = z.discriminatedUnion("kind", [ + z.object({ + kind: z.literal("Pending"), + payload: z.undefined().optional() + }), + z.object({ + kind: z.literal("Waiting"), + payload: z.object({ + reason: z.string() + }) + }), + z.object({ + kind: z.literal("Ready"), + payload: z.undefined().optional() + }), + z.object({ + kind: z.literal("Failed"), + payload: z.object({ + reason: z.string() + }) + }) +]); +var serverWatchableDTOSchema = z.object({ + server: serverIdentityDTOSchema, + dir: z.string() +}); +var routeWatchableDTOSchema = z.object({ + server: serverIdentityDTOSchema, + dir: z.string() +}); +var pathWatchableDTOSchema = z.discriminatedUnion("kind", [ + z.object({ + kind: z.literal("Server"), + payload: serverWatchableDTOSchema + }), + z.object({ + kind: z.literal("Route"), + payload: routeWatchableDTOSchema + }), + z.object({ + kind: z.literal("Any"), + payload: anyWatchableDTOSchema + }), + z.object({ + kind: z.literal("Input"), + payload: inputWatchableDTOSchema + }) +]); var sseDTOOptsSchema = z.object({ body: z.string() }); @@ -222,6 +277,10 @@ var routeDTOSchema = z.object({ path: z.string(), kind: routeKindDTOSchema }); +var serverResourceDTOSchema = z.object({ + status: resourceStatusSchema, + server: serverIdentityDTOSchema +}); var startupErrorDTOSchema = z.object({ error: z.string() }); @@ -233,9 +292,6 @@ var stdoutLineDTOSchema = z.object({ line: z.string(), prefix: z.string().optional() }); -var stoppedWatchingDTOSchema = z.object({ - paths: z.array(z.string()) -}); var taskConclusionDTOSchema = z.union([ z.object({ kind: z.literal("Ok"), @@ -254,10 +310,6 @@ var taskTreePreviewSchema = z.object({ tree: archyNodeSchema, will_exec: z.boolean() }); -var watchingDTOSchema = z.object({ - paths: z.array(z.string()), - debounce: debounceDTOSchema -}); var changeKindSchema = z.nativeEnum(ChangeKind); var changeDTOSchema = z.lazy( () => z.discriminatedUnion("kind", [ @@ -375,10 +427,25 @@ var startupEventDTOSchema = z.discriminatedUnion("kind", [ payload: z.string() }) ]); +var pathMonitorResourceDTOSchema = z.object({ + status: resourceStatusSchema, + watchable: pathWatchableDTOSchema, + debounce: debounceDTOSchema +}); var serverDescSchema = z.object({ routes: z.array(routeDTOSchema), id: z.string() }); +var transitionDTOSchema = z.discriminatedUnion("kind", [ + z.object({ + kind: z.literal("Server"), + payload: serverResourceDTOSchema + }), + z.object({ + kind: z.literal("PathMonitor"), + payload: pathMonitorResourceDTOSchema + }) +]); var taskActionStageDTOSchema = z.lazy( () => z.discriminatedUnion("kind", [ z.object({ @@ -471,16 +538,13 @@ var externalEventsDTOSchema = z.lazy( payload: taskTreeSummarySchema }), z.object({ - kind: z.literal("Watching"), - payload: watchingDTOSchema - }), - z.object({ - kind: z.literal("WatchingStopped"), - payload: stoppedWatchingDTOSchema + kind: z.literal("Transition"), + payload: transitionDTOSchema }) ]) ); export { + anyWatchableDTOSchema, archyNodeSchema, changeDTOSchema, changeKindSchema, @@ -498,12 +562,17 @@ export { inputAcceptedDTOSchema, inputErrorDTOSchema, inputErrorDetailDTOSchema, + inputWatchableDTOSchema, invocationIdDTOSchema, logLevelDTOSchema, outputLineDTOSchema, + pathMonitorResourceDTOSchema, + pathWatchableDTOSchema, + resourceStatusSchema, routeDTOSchema, routeIdentityDTOSchema, routeKindDTOSchema, + routeWatchableDTOSchema, serverChangeDTOSchema, serverChangeSchema, serverChangeSetItemSchema, @@ -512,12 +581,13 @@ export { serverDTOSchema, serverDescSchema, serverIdentityDTOSchema, + serverResourceDTOSchema, + serverWatchableDTOSchema, sseDTOOptsSchema, startupErrorDTOSchema, startupEventDTOSchema, stderrLineDTOSchema, stdoutLineDTOSchema, - stoppedWatchingDTOSchema, taskActionDTOSchema, taskActionStageDTOSchema, taskConclusionDTOSchema, @@ -525,5 +595,5 @@ export { taskResultDTOSchema, taskTreePreviewSchema, taskTreeSummarySchema, - watchingDTOSchema + transitionDTOSchema }; diff --git a/generated/schema.ts b/generated/schema.ts index 0bcf856c..18da9e84 100644 --- a/generated/schema.ts +++ b/generated/schema.ts @@ -16,6 +16,10 @@ import { export const invocationIdDTOSchema = z.string(); +export const anyWatchableDTOSchema = z.object({ + dir: z.string(), +}); + export const archyNodeSchema: z.ZodSchema = z.lazy(() => z.object({ id: z.string(), @@ -111,6 +115,63 @@ export const inputErrorDetailDTOSchema = z.object({ error: z.string(), }); +export const inputWatchableDTOSchema = z.object({ + absolute_paths: z.string(), + relative_paths: z.string(), +}); + +export const resourceStatusSchema = z.discriminatedUnion("kind", [ + z.object({ + kind: z.literal("Pending"), + payload: z.undefined().optional(), + }), + z.object({ + kind: z.literal("Waiting"), + payload: z.object({ + reason: z.string(), + }), + }), + z.object({ + kind: z.literal("Ready"), + payload: z.undefined().optional(), + }), + z.object({ + kind: z.literal("Failed"), + payload: z.object({ + reason: z.string(), + }), + }), +]); + +export const serverWatchableDTOSchema = z.object({ + server: serverIdentityDTOSchema, + dir: z.string(), +}); + +export const routeWatchableDTOSchema = z.object({ + server: serverIdentityDTOSchema, + dir: z.string(), +}); + +export const pathWatchableDTOSchema = z.discriminatedUnion("kind", [ + z.object({ + kind: z.literal("Server"), + payload: serverWatchableDTOSchema, + }), + z.object({ + kind: z.literal("Route"), + payload: routeWatchableDTOSchema, + }), + z.object({ + kind: z.literal("Any"), + payload: anyWatchableDTOSchema, + }), + z.object({ + kind: z.literal("Input"), + payload: inputWatchableDTOSchema, + }), +]); + export const sseDTOOptsSchema = z.object({ body: z.string(), }); @@ -239,6 +300,11 @@ export const routeDTOSchema = z.object({ kind: routeKindDTOSchema, }); +export const serverResourceDTOSchema = z.object({ + status: resourceStatusSchema, + server: serverIdentityDTOSchema, +}); + export const startupErrorDTOSchema = z.object({ error: z.string(), }); @@ -253,10 +319,6 @@ export const stdoutLineDTOSchema = z.object({ prefix: z.string().optional(), }); -export const stoppedWatchingDTOSchema = z.object({ - paths: z.array(z.string()), -}); - export const taskConclusionDTOSchema = z.union([ z.object({ kind: z.literal("Ok"), @@ -277,11 +339,6 @@ export const taskTreePreviewSchema = z.object({ will_exec: z.boolean(), }); -export const watchingDTOSchema = z.object({ - paths: z.array(z.string()), - debounce: debounceDTOSchema, -}); - export const changeKindSchema = z.nativeEnum(ChangeKind); export const changeDTOSchema: z.ZodSchema = z.lazy(() => @@ -406,11 +463,28 @@ export const startupEventDTOSchema = z.discriminatedUnion("kind", [ }), ]); +export const pathMonitorResourceDTOSchema = z.object({ + status: resourceStatusSchema, + watchable: pathWatchableDTOSchema, + debounce: debounceDTOSchema, +}); + export const serverDescSchema = z.object({ routes: z.array(routeDTOSchema), id: z.string(), }); +export const transitionDTOSchema = z.discriminatedUnion("kind", [ + z.object({ + kind: z.literal("Server"), + payload: serverResourceDTOSchema, + }), + z.object({ + kind: z.literal("PathMonitor"), + payload: pathMonitorResourceDTOSchema, + }), +]); + export const taskActionStageDTOSchema: z.ZodSchema = z.lazy( () => z.discriminatedUnion("kind", [ @@ -510,12 +584,8 @@ export const externalEventsDTOSchema: z.ZodSchema = z.lazy( payload: taskTreeSummarySchema, }), z.object({ - kind: z.literal("Watching"), - payload: watchingDTOSchema, - }), - z.object({ - kind: z.literal("WatchingStopped"), - payload: stoppedWatchingDTOSchema, + kind: z.literal("Transition"), + payload: transitionDTOSchema, }), ]), ); diff --git a/inject/dist/index.js b/inject/dist/index.js index 97c3f509..49cd04d5 100644 --- a/inject/dist/index.js +++ b/inject/dist/index.js @@ -1,8 +1,8 @@ -var Vi=Object.create;var Or=Object.defineProperty;var ln=Object.getOwnPropertyDescriptor;var Bi=Object.getOwnPropertyNames;var Wi=Object.getPrototypeOf,Hi=Object.prototype.hasOwnProperty;var qi=(r,e)=>()=>(e||r((e={exports:{}}).exports,e),e.exports);var Gi=(r,e,t,n)=>{if(e&&typeof e=="object"||typeof e=="function")for(let i of Bi(e))!Hi.call(r,i)&&i!==t&&Or(r,i,{get:()=>e[i],enumerable:!(n=ln(e,i))||n.enumerable});return r};var Yi=(r,e,t)=>(t=r!=null?Vi(Wi(r)):{},Gi(e||!r||!r.__esModule?Or(t,"default",{value:r,enumerable:!0}):t,r));var W=(r,e,t,n)=>{for(var i=n>1?void 0:n?ln(e,t):e,o=r.length-1,s;o>=0;o--)(s=r[o])&&(i=(n?s(e,t,i):s(i))||i);return n&&i&&Or(e,t,i),i};var hi=qi(pi=>{"use strict";var ur=class{constructor(e){this.func=e,this.running=!1,this.id=null,this._handler=()=>(this.running=!1,this.id=null,this.func())}start(e){this.running&&clearTimeout(this.id),this.id=setTimeout(this._handler,e),this.running=!0}stop(){this.running&&(clearTimeout(this.id),this.running=!1,this.id=null)}};ur.start=(r,e)=>setTimeout(e,r);pi.Timer=ur});var Cr=function(r,e){return Cr=Object.setPrototypeOf||{__proto__:[]}instanceof Array&&function(t,n){t.__proto__=n}||function(t,n){for(var i in n)Object.prototype.hasOwnProperty.call(n,i)&&(t[i]=n[i])},Cr(r,e)};function I(r,e){if(typeof e!="function"&&e!==null)throw new TypeError("Class extends value "+String(e)+" is not a constructor or null");Cr(r,e);function t(){this.constructor=r}r.prototype=e===null?Object.create(e):(t.prototype=e.prototype,new t)}var It=function(){return It=Object.assign||function(e){for(var t,n=1,i=arguments.length;n0&&o[o.length-1])&&(d[0]===6||d[0]===2)){t=0;continue}if(d[0]===3&&(!o||d[1]>o[0]&&d[1]=r.length&&(r=void 0),{value:r&&r[n++],done:!r}}};throw new TypeError(e?"Object is not iterable.":"Symbol.iterator is not defined.")}function H(r,e){var t=typeof Symbol=="function"&&r[Symbol.iterator];if(!t)return r;var n=t.call(r),i,o=[],s;try{for(;(e===void 0||e-- >0)&&!(i=n.next()).done;)o.push(i.value)}catch(c){s={error:c}}finally{try{i&&!i.done&&(t=n.return)&&t.call(n)}finally{if(s)throw s.error}}return o}function q(r,e,t){if(t||arguments.length===2)for(var n=0,i=e.length,o;n1||l(y,S)})},E&&(i[y]=E(i[y])))}function l(y,E){try{d(n[y](E))}catch(S){w(o[0][3],S)}}function d(y){y.value instanceof ve?Promise.resolve(y.value.v).then(u,p):w(o[0][2],y)}function u(y){l("next",y)}function p(y){l("throw",y)}function w(y,E){y(E),o.shift(),o.length&&l(o[0][0],o[0][1])}}function fn(r){if(!Symbol.asyncIterator)throw new TypeError("Symbol.asyncIterator is not defined.");var e=r[Symbol.asyncIterator],t;return e?e.call(r):(r=typeof re=="function"?re(r):r[Symbol.iterator](),t={},n("next"),n("throw"),n("return"),t[Symbol.asyncIterator]=function(){return this},t);function n(o){t[o]=r[o]&&function(s){return new Promise(function(c,l){s=r[o](s),i(c,l,s.done,s.value)})}}function i(o,s,c,l){Promise.resolve(l).then(function(d){o({value:d,done:c})},s)}}function k(r){return typeof r=="function"}function Pt(r){var e=function(n){Error.call(n),n.stack=new Error().stack},t=r(e);return t.prototype=Object.create(Error.prototype),t.prototype.constructor=t,t}var Dt=Pt(function(r){return function(t){r(this),this.message=t?t.length+` errors occurred during unsubscription: +var Wi=Object.create;var Or=Object.defineProperty;var ln=Object.getOwnPropertyDescriptor;var Bi=Object.getOwnPropertyNames;var Hi=Object.getPrototypeOf,qi=Object.prototype.hasOwnProperty;var Gi=(r,e)=>()=>(e||r((e={exports:{}}).exports,e),e.exports);var Yi=(r,e,t,n)=>{if(e&&typeof e=="object"||typeof e=="function")for(let i of Bi(e))!qi.call(r,i)&&i!==t&&Or(r,i,{get:()=>e[i],enumerable:!(n=ln(e,i))||n.enumerable});return r};var Ji=(r,e,t)=>(t=r!=null?Wi(Hi(r)):{},Yi(e||!r||!r.__esModule?Or(t,"default",{value:r,enumerable:!0}):t,r));var B=(r,e,t,n)=>{for(var i=n>1?void 0:n?ln(e,t):e,o=r.length-1,s;o>=0;o--)(s=r[o])&&(i=(n?s(e,t,i):s(i))||i);return n&&i&&Or(e,t,i),i};var mi=Gi(hi=>{"use strict";var ur=class{constructor(e){this.func=e,this.running=!1,this.id=null,this._handler=()=>(this.running=!1,this.id=null,this.func())}start(e){this.running&&clearTimeout(this.id),this.id=setTimeout(this._handler,e),this.running=!0}stop(){this.running&&(clearTimeout(this.id),this.running=!1,this.id=null)}};ur.start=(r,e)=>setTimeout(e,r);hi.Timer=ur});var Cr=function(r,e){return Cr=Object.setPrototypeOf||{__proto__:[]}instanceof Array&&function(t,n){t.__proto__=n}||function(t,n){for(var i in n)Object.prototype.hasOwnProperty.call(n,i)&&(t[i]=n[i])},Cr(r,e)};function R(r,e){if(typeof e!="function"&&e!==null)throw new TypeError("Class extends value "+String(e)+" is not a constructor or null");Cr(r,e);function t(){this.constructor=r}r.prototype=e===null?Object.create(e):(t.prototype=e.prototype,new t)}var Rt=function(){return Rt=Object.assign||function(e){for(var t,n=1,i=arguments.length;n0&&o[o.length-1])&&(d[0]===6||d[0]===2)){t=0;continue}if(d[0]===3&&(!o||d[1]>o[0]&&d[1]=r.length&&(r=void 0),{value:r&&r[n++],done:!r}}};throw new TypeError(e?"Object is not iterable.":"Symbol.iterator is not defined.")}function H(r,e){var t=typeof Symbol=="function"&&r[Symbol.iterator];if(!t)return r;var n=t.call(r),i,o=[],s;try{for(;(e===void 0||e-- >0)&&!(i=n.next()).done;)o.push(i.value)}catch(c){s={error:c}}finally{try{i&&!i.done&&(t=n.return)&&t.call(n)}finally{if(s)throw s.error}}return o}function q(r,e,t){if(t||arguments.length===2)for(var n=0,i=e.length,o;n1||l(y,w)})},A&&(i[y]=A(i[y])))}function l(y,A){try{d(n[y](A))}catch(w){S(o[0][3],w)}}function d(y){y.value instanceof ye?Promise.resolve(y.value.v).then(u,p):S(o[0][2],y)}function u(y){l("next",y)}function p(y){l("throw",y)}function S(y,A){y(A),o.shift(),o.length&&l(o[0][0],o[0][1])}}function fn(r){if(!Symbol.asyncIterator)throw new TypeError("Symbol.asyncIterator is not defined.");var e=r[Symbol.asyncIterator],t;return e?e.call(r):(r=typeof re=="function"?re(r):r[Symbol.iterator](),t={},n("next"),n("throw"),n("return"),t[Symbol.asyncIterator]=function(){return this},t);function n(o){t[o]=r[o]&&function(s){return new Promise(function(c,l){s=r[o](s),i(c,l,s.done,s.value)})}}function i(o,s,c,l){Promise.resolve(l).then(function(d){o({value:d,done:c})},s)}}function k(r){return typeof r=="function"}function Dt(r){var e=function(n){Error.call(n),n.stack=new Error().stack},t=r(e);return t.prototype=Object.create(Error.prototype),t.prototype.constructor=t,t}var Pt=Dt(function(r){return function(t){r(this),this.message=t?t.length+` errors occurred during unsubscription: `+t.map(function(n,i){return i+1+") "+n.toString()}).join(` - `):"",this.name="UnsubscriptionError",this.errors=t}});function ye(r,e){if(r){var t=r.indexOf(e);0<=t&&r.splice(t,1)}}var X=(function(){function r(e){this.initialTeardown=e,this.closed=!1,this._parentage=null,this._finalizers=null}return r.prototype.unsubscribe=function(){var e,t,n,i,o;if(!this.closed){this.closed=!0;var s=this._parentage;if(s)if(this._parentage=null,Array.isArray(s))try{for(var c=re(s),l=c.next();!l.done;l=c.next()){var d=l.value;d.remove(this)}}catch(S){e={error:S}}finally{try{l&&!l.done&&(t=c.return)&&t.call(c)}finally{if(e)throw e.error}}else s.remove(this);var u=this.initialTeardown;if(k(u))try{u()}catch(S){o=S instanceof Dt?S.errors:[S]}var p=this._finalizers;if(p){this._finalizers=null;try{for(var w=re(p),y=w.next();!y.done;y=w.next()){var E=y.value;try{pn(E)}catch(S){o=o??[],S instanceof Dt?o=q(q([],H(o)),H(S.errors)):o.push(S)}}}catch(S){n={error:S}}finally{try{y&&!y.done&&(i=w.return)&&i.call(w)}finally{if(n)throw n.error}}}if(o)throw new Dt(o)}},r.prototype.add=function(e){var t;if(e&&e!==this)if(this.closed)pn(e);else{if(e instanceof r){if(e.closed||e._hasParent(this))return;e._addParent(this)}(this._finalizers=(t=this._finalizers)!==null&&t!==void 0?t:[]).push(e)}},r.prototype._hasParent=function(e){var t=this._parentage;return t===e||Array.isArray(t)&&t.includes(e)},r.prototype._addParent=function(e){var t=this._parentage;this._parentage=Array.isArray(t)?(t.push(e),t):t?[t,e]:e},r.prototype._removeParent=function(e){var t=this._parentage;t===e?this._parentage=null:Array.isArray(t)&&ye(t,e)},r.prototype.remove=function(e){var t=this._finalizers;t&&ye(t,e),e instanceof r&&e._removeParent(this)},r.EMPTY=(function(){var e=new r;return e.closed=!0,e})(),r})();var $r=X.EMPTY;function Mt(r){return r instanceof X||r&&"closed"in r&&k(r.remove)&&k(r.add)&&k(r.unsubscribe)}function pn(r){k(r)?r():r.unsubscribe()}var G={onUnhandledError:null,onStoppedNotification:null,Promise:void 0,useDeprecatedSynchronousErrorHandling:!1,useDeprecatedNextContext:!1};var qe={setTimeout:function(r,e){for(var t=[],n=2;n0},enumerable:!1,configurable:!0}),e.prototype._trySubscribe=function(t){return this._throwIfClosed(),r.prototype._trySubscribe.call(this,t)},e.prototype._subscribe=function(t){return this._throwIfClosed(),this._checkFinalizedStatuses(t),this._innerSubscribe(t)},e.prototype._innerSubscribe=function(t){var n=this,i=this,o=i.hasError,s=i.isStopped,c=i.observers;return o||s?$r:(this.currentObservers=null,c.push(t),new X(function(){n.currentObservers=null,ye(c,t)}))},e.prototype._checkFinalizedStatuses=function(t){var n=this,i=n.hasError,o=n.thrownError,s=n.isStopped;i?t.error(o):s&&t.complete()},e.prototype.asObservable=function(){var t=new A;return t.source=this,t},e.create=function(t,n){return new Ut(t,n)},e})(A);var Ut=(function(r){I(e,r);function e(t,n){var i=r.call(this)||this;return i.destination=t,i.source=n,i}return e.prototype.next=function(t){var n,i;(i=(n=this.destination)===null||n===void 0?void 0:n.next)===null||i===void 0||i.call(n,t)},e.prototype.error=function(t){var n,i;(i=(n=this.destination)===null||n===void 0?void 0:n.error)===null||i===void 0||i.call(n,t)},e.prototype.complete=function(){var t,n;(n=(t=this.destination)===null||t===void 0?void 0:t.complete)===null||n===void 0||n.call(t)},e.prototype._subscribe=function(t){var n,i;return(i=(n=this.source)===null||n===void 0?void 0:n.subscribe(t))!==null&&i!==void 0?i:$r},e})(Y);var ut={now:function(){return(ut.delegate||Date).now()},delegate:void 0};var zt=(function(r){I(e,r);function e(t,n,i){t===void 0&&(t=1/0),n===void 0&&(n=1/0),i===void 0&&(i=ut);var o=r.call(this)||this;return o._bufferSize=t,o._windowTime=n,o._timestampProvider=i,o._buffer=[],o._infiniteTimeWindow=!0,o._infiniteTimeWindow=n===1/0,o._bufferSize=Math.max(1,t),o._windowTime=Math.max(1,n),o}return e.prototype.next=function(t){var n=this,i=n.isStopped,o=n._buffer,s=n._infiniteTimeWindow,c=n._timestampProvider,l=n._windowTime;i||(o.push(t),!s&&o.push(c.now()+l)),this._trimBuffer(),r.prototype.next.call(this,t)},e.prototype._subscribe=function(t){this._throwIfClosed(),this._trimBuffer();for(var n=this._innerSubscribe(t),i=this,o=i._infiniteTimeWindow,s=i._buffer,c=s.slice(),l=0;l0&&(u=new be({next:function(jt){return $t.next(jt)},error:function(jt){S=!0,R(),p=Nr(U,i,jt),$t.error(jt)},complete:function(){E=!0,R(),p=Nr(U,s),$t.complete()}}),j(lt).subscribe(u))})(d)}}function Nr(r,e){for(var t=[],n=2;n{let e=new URL(window.location.href),t=e.protocol==="https:"?"wss":"ws",n;if(r.host)n=new URL(r.ws_path,t+"://"+r.host);else{let o=new URL(e);o.protocol=t,o.pathname=r.ws_path,n=o}return Ur(n.toString()).pipe(Mr({delay:5e3}))}}}var Fn={debug(...r){},error(...r){},info(...r){},trace(...r){}},zr={name:"console",globalSetup:r=>{let e=new Y;return[e,{debug:function(...n){e.next({level:"debug",args:n})},info:function(...n){e.next({level:"info",args:n})},trace:function(...n){e.next({level:"trace",args:n})},error:function(...n){e.next({level:"error",args:n})}}]},resetSink:(r,e,t)=>r.pipe(we(n=>{let i=["trace","debug","info","error"],o=i.indexOf(n.level),s=i.indexOf(t.log_level);o>=s&&console.log(`[${n.level}]`,...n.args)}),xe())};var T;(function(r){r.assertEqual=i=>i;function e(i){}r.assertIs=e;function t(i){throw new Error}r.assertNever=t,r.arrayToEnum=i=>{let o={};for(let s of i)o[s]=s;return o},r.getValidEnumValues=i=>{let o=r.objectKeys(i).filter(c=>typeof i[i[c]]!="number"),s={};for(let c of o)s[c]=i[c];return r.objectValues(s)},r.objectValues=i=>r.objectKeys(i).map(function(o){return i[o]}),r.objectKeys=typeof Object.keys=="function"?i=>Object.keys(i):i=>{let o=[];for(let s in i)Object.prototype.hasOwnProperty.call(i,s)&&o.push(s);return o},r.find=(i,o)=>{for(let s of i)if(o(s))return s},r.isInteger=typeof Number.isInteger=="function"?i=>Number.isInteger(i):i=>typeof i=="number"&&isFinite(i)&&Math.floor(i)===i;function n(i,o=" | "){return i.map(s=>typeof s=="string"?`'${s}'`:s).join(o)}r.joinValues=n,r.jsonStringifyReplacer=(i,o)=>typeof o=="bigint"?o.toString():o})(T||(T={}));var Fr;(function(r){r.mergeShapes=(e,t)=>({...e,...t})})(Fr||(Fr={}));var m=T.arrayToEnum(["string","nan","number","integer","float","boolean","date","bigint","symbol","function","undefined","null","array","object","unknown","promise","void","never","map","set"]),ie=r=>{switch(typeof r){case"undefined":return m.undefined;case"string":return m.string;case"number":return isNaN(r)?m.nan:m.number;case"boolean":return m.boolean;case"function":return m.function;case"bigint":return m.bigint;case"symbol":return m.symbol;case"object":return Array.isArray(r)?m.array:r===null?m.null:r.then&&typeof r.then=="function"&&r.catch&&typeof r.catch=="function"?m.promise:typeof Map<"u"&&r instanceof Map?m.map:typeof Set<"u"&&r instanceof Set?m.set:typeof Date<"u"&&r instanceof Date?m.date:m.object;default:return m.unknown}},f=T.arrayToEnum(["invalid_type","invalid_literal","custom","invalid_union","invalid_union_discriminator","invalid_enum_value","unrecognized_keys","invalid_arguments","invalid_return_type","invalid_date","invalid_string","too_small","too_big","invalid_intersection_types","not_multiple_of","not_finite"]),mo=r=>JSON.stringify(r,null,2).replace(/"([^"]+)":/g,"$1:"),z=class r extends Error{get errors(){return this.issues}constructor(e){super(),this.issues=[],this.addIssue=n=>{this.issues=[...this.issues,n]},this.addIssues=(n=[])=>{this.issues=[...this.issues,...n]};let t=new.target.prototype;Object.setPrototypeOf?Object.setPrototypeOf(this,t):this.__proto__=t,this.name="ZodError",this.issues=e}format(e){let t=e||function(o){return o.message},n={_errors:[]},i=o=>{for(let s of o.issues)if(s.code==="invalid_union")s.unionErrors.map(i);else if(s.code==="invalid_return_type")i(s.returnTypeError);else if(s.code==="invalid_arguments")i(s.argumentsError);else if(s.path.length===0)n._errors.push(t(s));else{let c=n,l=0;for(;lt.message){let t={},n=[];for(let i of this.issues)i.path.length>0?(t[i.path[0]]=t[i.path[0]]||[],t[i.path[0]].push(e(i))):n.push(e(i));return{formErrors:n,fieldErrors:t}}get formErrors(){return this.flatten()}};z.create=r=>new z(r);var Xe=(r,e)=>{let t;switch(r.code){case f.invalid_type:r.received===m.undefined?t="Required":t=`Expected ${r.expected}, received ${r.received}`;break;case f.invalid_literal:t=`Invalid literal value, expected ${JSON.stringify(r.expected,T.jsonStringifyReplacer)}`;break;case f.unrecognized_keys:t=`Unrecognized key(s) in object: ${T.joinValues(r.keys,", ")}`;break;case f.invalid_union:t="Invalid input";break;case f.invalid_union_discriminator:t=`Invalid discriminator value. Expected ${T.joinValues(r.options)}`;break;case f.invalid_enum_value:t=`Invalid enum value. Expected ${T.joinValues(r.options)}, received '${r.received}'`;break;case f.invalid_arguments:t="Invalid function arguments";break;case f.invalid_return_type:t="Invalid function return type";break;case f.invalid_date:t="Invalid date";break;case f.invalid_string:typeof r.validation=="object"?"includes"in r.validation?(t=`Invalid input: must include "${r.validation.includes}"`,typeof r.validation.position=="number"&&(t=`${t} at one or more positions greater than or equal to ${r.validation.position}`)):"startsWith"in r.validation?t=`Invalid input: must start with "${r.validation.startsWith}"`:"endsWith"in r.validation?t=`Invalid input: must end with "${r.validation.endsWith}"`:T.assertNever(r.validation):r.validation!=="regex"?t=`Invalid ${r.validation}`:t="Invalid";break;case f.too_small:r.type==="array"?t=`Array must contain ${r.exact?"exactly":r.inclusive?"at least":"more than"} ${r.minimum} element(s)`:r.type==="string"?t=`String must contain ${r.exact?"exactly":r.inclusive?"at least":"over"} ${r.minimum} character(s)`:r.type==="number"?t=`Number must be ${r.exact?"exactly equal to ":r.inclusive?"greater than or equal to ":"greater than "}${r.minimum}`:r.type==="date"?t=`Date must be ${r.exact?"exactly equal to ":r.inclusive?"greater than or equal to ":"greater than "}${new Date(Number(r.minimum))}`:t="Invalid input";break;case f.too_big:r.type==="array"?t=`Array must contain ${r.exact?"exactly":r.inclusive?"at most":"less than"} ${r.maximum} element(s)`:r.type==="string"?t=`String must contain ${r.exact?"exactly":r.inclusive?"at most":"under"} ${r.maximum} character(s)`:r.type==="number"?t=`Number must be ${r.exact?"exactly":r.inclusive?"less than or equal to":"less than"} ${r.maximum}`:r.type==="bigint"?t=`BigInt must be ${r.exact?"exactly":r.inclusive?"less than or equal to":"less than"} ${r.maximum}`:r.type==="date"?t=`Date must be ${r.exact?"exactly":r.inclusive?"smaller than or equal to":"smaller than"} ${new Date(Number(r.maximum))}`:t="Invalid input";break;case f.custom:t="Invalid input";break;case f.invalid_intersection_types:t="Intersection results could not be merged";break;case f.not_multiple_of:t=`Number must be a multiple of ${r.multipleOf}`;break;case f.not_finite:t="Number must be finite";break;default:t=e.defaultError,T.assertNever(r)}return{message:t}},Hn=Xe;function vo(r){Hn=r}function tr(){return Hn}var rr=r=>{let{data:e,path:t,errorMaps:n,issueData:i}=r,o=[...t,...i.path||[]],s={...i,path:o};if(i.message!==void 0)return{...i,path:o,message:i.message};let c="",l=n.filter(d=>!!d).slice().reverse();for(let d of l)c=d(s,{data:e,defaultError:c}).message;return{...i,path:o,message:c}},yo=[];function h(r,e){let t=tr(),n=rr({issueData:e,data:r.data,path:r.path,errorMaps:[r.common.contextualErrorMap,r.schemaErrorMap,t,t===Xe?void 0:Xe].filter(i=>!!i)});r.common.issues.push(n)}var P=class r{constructor(){this.value="valid"}dirty(){this.value==="valid"&&(this.value="dirty")}abort(){this.value!=="aborted"&&(this.value="aborted")}static mergeArray(e,t){let n=[];for(let i of t){if(i.status==="aborted")return _;i.status==="dirty"&&e.dirty(),n.push(i.value)}return{status:e.value,value:n}}static async mergeObjectAsync(e,t){let n=[];for(let i of t){let o=await i.key,s=await i.value;n.push({key:o,value:s})}return r.mergeObjectSync(e,n)}static mergeObjectSync(e,t){let n={};for(let i of t){let{key:o,value:s}=i;if(o.status==="aborted"||s.status==="aborted")return _;o.status==="dirty"&&e.dirty(),s.status==="dirty"&&e.dirty(),o.value!=="__proto__"&&(typeof s.value<"u"||i.alwaysSet)&&(n[o.value]=s.value)}return{status:e.value,value:n}}},_=Object.freeze({status:"aborted"}),Ke=r=>({status:"dirty",value:r}),D=r=>({status:"valid",value:r}),Vr=r=>r.status==="aborted",Br=r=>r.status==="dirty",Se=r=>r.status==="valid",yt=r=>typeof Promise<"u"&&r instanceof Promise;function nr(r,e,t,n){if(t==="a"&&!n)throw new TypeError("Private accessor was defined without a getter");if(typeof e=="function"?r!==e||!n:!e.has(r))throw new TypeError("Cannot read private member from an object whose class did not declare it");return t==="m"?n:t==="a"?n.call(r):n?n.value:e.get(r)}function qn(r,e,t,n,i){if(n==="m")throw new TypeError("Private method is not writable");if(n==="a"&&!i)throw new TypeError("Private accessor was defined without a setter");if(typeof e=="function"?r!==e||!i:!e.has(r))throw new TypeError("Cannot write private member to an object whose class did not declare it");return n==="a"?i.call(r,t):i?i.value=t:e.set(r,t),t}var v;(function(r){r.errToObj=e=>typeof e=="string"?{message:e}:e||{},r.toString=e=>typeof e=="string"?e:e?.message})(v||(v={}));var mt,vt,B=class{constructor(e,t,n,i){this._cachedPath=[],this.parent=e,this.data=t,this._path=n,this._key=i}get path(){return this._cachedPath.length||(this._key instanceof Array?this._cachedPath.push(...this._path,...this._key):this._cachedPath.push(...this._path,this._key)),this._cachedPath}},Vn=(r,e)=>{if(Se(e))return{success:!0,data:e.value};if(!r.common.issues.length)throw new Error("Validation failed but no issues detected.");return{success:!1,get error(){if(this._error)return this._error;let t=new z(r.common.issues);return this._error=t,this._error}}};function b(r){if(!r)return{};let{errorMap:e,invalid_type_error:t,required_error:n,description:i}=r;if(e&&(t||n))throw new Error(`Can't use "invalid_type_error" or "required_error" in conjunction with custom error map.`);return e?{errorMap:e,description:i}:{errorMap:(s,c)=>{var l,d;let{message:u}=r;return s.code==="invalid_enum_value"?{message:u??c.defaultError}:typeof c.data>"u"?{message:(l=u??n)!==null&&l!==void 0?l:c.defaultError}:s.code!=="invalid_type"?{message:c.defaultError}:{message:(d=u??t)!==null&&d!==void 0?d:c.defaultError}},description:i}}var x=class{get description(){return this._def.description}_getType(e){return ie(e.data)}_getOrReturnCtx(e,t){return t||{common:e.parent.common,data:e.data,parsedType:ie(e.data),schemaErrorMap:this._def.errorMap,path:e.path,parent:e.parent}}_processInputParams(e){return{status:new P,ctx:{common:e.parent.common,data:e.data,parsedType:ie(e.data),schemaErrorMap:this._def.errorMap,path:e.path,parent:e.parent}}}_parseSync(e){let t=this._parse(e);if(yt(t))throw new Error("Synchronous parse encountered promise.");return t}_parseAsync(e){let t=this._parse(e);return Promise.resolve(t)}parse(e,t){let n=this.safeParse(e,t);if(n.success)return n.data;throw n.error}safeParse(e,t){var n;let i={common:{issues:[],async:(n=t?.async)!==null&&n!==void 0?n:!1,contextualErrorMap:t?.errorMap},path:t?.path||[],schemaErrorMap:this._def.errorMap,parent:null,data:e,parsedType:ie(e)},o=this._parseSync({data:e,path:i.path,parent:i});return Vn(i,o)}"~validate"(e){var t,n;let i={common:{issues:[],async:!!this["~standard"].async},path:[],schemaErrorMap:this._def.errorMap,parent:null,data:e,parsedType:ie(e)};if(!this["~standard"].async)try{let o=this._parseSync({data:e,path:[],parent:i});return Se(o)?{value:o.value}:{issues:i.common.issues}}catch(o){!((n=(t=o?.message)===null||t===void 0?void 0:t.toLowerCase())===null||n===void 0)&&n.includes("encountered")&&(this["~standard"].async=!0),i.common={issues:[],async:!0}}return this._parseAsync({data:e,path:[],parent:i}).then(o=>Se(o)?{value:o.value}:{issues:i.common.issues})}async parseAsync(e,t){let n=await this.safeParseAsync(e,t);if(n.success)return n.data;throw n.error}async safeParseAsync(e,t){let n={common:{issues:[],contextualErrorMap:t?.errorMap,async:!0},path:t?.path||[],schemaErrorMap:this._def.errorMap,parent:null,data:e,parsedType:ie(e)},i=this._parse({data:e,path:n.path,parent:n}),o=await(yt(i)?i:Promise.resolve(i));return Vn(n,o)}refine(e,t){let n=i=>typeof t=="string"||typeof t>"u"?{message:t}:typeof t=="function"?t(i):t;return this._refinement((i,o)=>{let s=e(i),c=()=>o.addIssue({code:f.custom,...n(i)});return typeof Promise<"u"&&s instanceof Promise?s.then(l=>l?!0:(c(),!1)):s?!0:(c(),!1)})}refinement(e,t){return this._refinement((n,i)=>e(n)?!0:(i.addIssue(typeof t=="function"?t(n,i):t),!1))}_refinement(e){return new Z({schema:this,typeName:g.ZodEffects,effect:{type:"refinement",refinement:e}})}superRefine(e){return this._refinement(e)}constructor(e){this.spa=this.safeParseAsync,this._def=e,this.parse=this.parse.bind(this),this.safeParse=this.safeParse.bind(this),this.parseAsync=this.parseAsync.bind(this),this.safeParseAsync=this.safeParseAsync.bind(this),this.spa=this.spa.bind(this),this.refine=this.refine.bind(this),this.refinement=this.refinement.bind(this),this.superRefine=this.superRefine.bind(this),this.optional=this.optional.bind(this),this.nullable=this.nullable.bind(this),this.nullish=this.nullish.bind(this),this.array=this.array.bind(this),this.promise=this.promise.bind(this),this.or=this.or.bind(this),this.and=this.and.bind(this),this.transform=this.transform.bind(this),this.brand=this.brand.bind(this),this.default=this.default.bind(this),this.catch=this.catch.bind(this),this.describe=this.describe.bind(this),this.pipe=this.pipe.bind(this),this.readonly=this.readonly.bind(this),this.isNullable=this.isNullable.bind(this),this.isOptional=this.isOptional.bind(this),this["~standard"]={version:1,vendor:"zod",validate:t=>this["~validate"](t)}}optional(){return V.create(this,this._def)}nullable(){return te.create(this,this._def)}nullish(){return this.nullable().optional()}array(){return se.create(this)}promise(){return pe.create(this,this._def)}or(e){return $e.create([this,e],this._def)}and(e){return je.create(this,e,this._def)}transform(e){return new Z({...b(this._def),schema:this,typeName:g.ZodEffects,effect:{type:"transform",transform:e}})}default(e){let t=typeof e=="function"?e:()=>e;return new Me({...b(this._def),innerType:this,defaultValue:t,typeName:g.ZodDefault})}brand(){return new gt({typeName:g.ZodBranded,type:this,...b(this._def)})}catch(e){let t=typeof e=="function"?e:()=>e;return new Ne({...b(this._def),innerType:this,catchValue:t,typeName:g.ZodCatch})}describe(e){let t=this.constructor;return new t({...this._def,description:e})}pipe(e){return _t.create(this,e)}readonly(){return Le.create(this)}isOptional(){return this.safeParse(void 0).success}isNullable(){return this.safeParse(null).success}},go=/^c[^\s-]{8,}$/i,_o=/^[0-9a-z]+$/,bo=/^[0-9A-HJKMNP-TV-Z]{26}$/i,xo=/^[0-9a-fA-F]{8}\b-[0-9a-fA-F]{4}\b-[0-9a-fA-F]{4}\b-[0-9a-fA-F]{4}\b-[0-9a-fA-F]{12}$/i,wo=/^[a-z0-9_-]{21}$/i,So=/^[A-Za-z0-9-_]+\.[A-Za-z0-9-_]+\.[A-Za-z0-9-_]*$/,ko=/^[-+]?P(?!$)(?:(?:[-+]?\d+Y)|(?:[-+]?\d+[.,]\d+Y$))?(?:(?:[-+]?\d+M)|(?:[-+]?\d+[.,]\d+M$))?(?:(?:[-+]?\d+W)|(?:[-+]?\d+[.,]\d+W$))?(?:(?:[-+]?\d+D)|(?:[-+]?\d+[.,]\d+D$))?(?:T(?=[\d+-])(?:(?:[-+]?\d+H)|(?:[-+]?\d+[.,]\d+H$))?(?:(?:[-+]?\d+M)|(?:[-+]?\d+[.,]\d+M$))?(?:[-+]?\d+(?:[.,]\d+)?S)?)??$/,To=/^(?!\.)(?!.*\.\.)([A-Z0-9_'+\-\.]*)[A-Z0-9_+-]@([A-Z0-9][A-Z0-9\-]*\.)+[A-Z]{2,}$/i,Eo="^(\\p{Extended_Pictographic}|\\p{Emoji_Component})+$",Zr,Ao=/^(?:(?:25[0-5]|2[0-4][0-9]|1[0-9][0-9]|[1-9][0-9]|[0-9])\.){3}(?:25[0-5]|2[0-4][0-9]|1[0-9][0-9]|[1-9][0-9]|[0-9])$/,Oo=/^(?:(?:25[0-5]|2[0-4][0-9]|1[0-9][0-9]|[1-9][0-9]|[0-9])\.){3}(?:25[0-5]|2[0-4][0-9]|1[0-9][0-9]|[1-9][0-9]|[0-9])\/(3[0-2]|[12]?[0-9])$/,Co=/^(([0-9a-fA-F]{1,4}:){7,7}[0-9a-fA-F]{1,4}|([0-9a-fA-F]{1,4}:){1,7}:|([0-9a-fA-F]{1,4}:){1,6}:[0-9a-fA-F]{1,4}|([0-9a-fA-F]{1,4}:){1,5}(:[0-9a-fA-F]{1,4}){1,2}|([0-9a-fA-F]{1,4}:){1,4}(:[0-9a-fA-F]{1,4}){1,3}|([0-9a-fA-F]{1,4}:){1,3}(:[0-9a-fA-F]{1,4}){1,4}|([0-9a-fA-F]{1,4}:){1,2}(:[0-9a-fA-F]{1,4}){1,5}|[0-9a-fA-F]{1,4}:((:[0-9a-fA-F]{1,4}){1,6})|:((:[0-9a-fA-F]{1,4}){1,7}|:)|fe80:(:[0-9a-fA-F]{0,4}){0,4}%[0-9a-zA-Z]{1,}|::(ffff(:0{1,4}){0,1}:){0,1}((25[0-5]|(2[0-4]|1{0,1}[0-9]){0,1}[0-9])\.){3,3}(25[0-5]|(2[0-4]|1{0,1}[0-9]){0,1}[0-9])|([0-9a-fA-F]{1,4}:){1,4}:((25[0-5]|(2[0-4]|1{0,1}[0-9]){0,1}[0-9])\.){3,3}(25[0-5]|(2[0-4]|1{0,1}[0-9]){0,1}[0-9]))$/,$o=/^(([0-9a-fA-F]{1,4}:){7,7}[0-9a-fA-F]{1,4}|([0-9a-fA-F]{1,4}:){1,7}:|([0-9a-fA-F]{1,4}:){1,6}:[0-9a-fA-F]{1,4}|([0-9a-fA-F]{1,4}:){1,5}(:[0-9a-fA-F]{1,4}){1,2}|([0-9a-fA-F]{1,4}:){1,4}(:[0-9a-fA-F]{1,4}){1,3}|([0-9a-fA-F]{1,4}:){1,3}(:[0-9a-fA-F]{1,4}){1,4}|([0-9a-fA-F]{1,4}:){1,2}(:[0-9a-fA-F]{1,4}){1,5}|[0-9a-fA-F]{1,4}:((:[0-9a-fA-F]{1,4}){1,6})|:((:[0-9a-fA-F]{1,4}){1,7}|:)|fe80:(:[0-9a-fA-F]{0,4}){0,4}%[0-9a-zA-Z]{1,}|::(ffff(:0{1,4}){0,1}:){0,1}((25[0-5]|(2[0-4]|1{0,1}[0-9]){0,1}[0-9])\.){3,3}(25[0-5]|(2[0-4]|1{0,1}[0-9]){0,1}[0-9])|([0-9a-fA-F]{1,4}:){1,4}:((25[0-5]|(2[0-4]|1{0,1}[0-9]){0,1}[0-9])\.){3,3}(25[0-5]|(2[0-4]|1{0,1}[0-9]){0,1}[0-9]))\/(12[0-8]|1[01][0-9]|[1-9]?[0-9])$/,jo=/^([0-9a-zA-Z+/]{4})*(([0-9a-zA-Z+/]{2}==)|([0-9a-zA-Z+/]{3}=))?$/,Io=/^([0-9a-zA-Z-_]{4})*(([0-9a-zA-Z-_]{2}(==)?)|([0-9a-zA-Z-_]{3}(=)?))?$/,Gn="((\\d\\d[2468][048]|\\d\\d[13579][26]|\\d\\d0[48]|[02468][048]00|[13579][26]00)-02-29|\\d{4}-((0[13578]|1[02])-(0[1-9]|[12]\\d|3[01])|(0[469]|11)-(0[1-9]|[12]\\d|30)|(02)-(0[1-9]|1\\d|2[0-8])))",Ro=new RegExp(`^${Gn}$`);function Yn(r){let e="([01]\\d|2[0-3]):[0-5]\\d:[0-5]\\d";return r.precision?e=`${e}\\.\\d{${r.precision}}`:r.precision==null&&(e=`${e}(\\.\\d+)?`),e}function Po(r){return new RegExp(`^${Yn(r)}$`)}function Jn(r){let e=`${Gn}T${Yn(r)}`,t=[];return t.push(r.local?"Z?":"Z"),r.offset&&t.push("([+-]\\d{2}:?\\d{2})"),e=`${e}(${t.join("|")})`,new RegExp(`^${e}$`)}function Do(r,e){return!!((e==="v4"||!e)&&Ao.test(r)||(e==="v6"||!e)&&Co.test(r))}function Mo(r,e){if(!So.test(r))return!1;try{let[t]=r.split("."),n=t.replace(/-/g,"+").replace(/_/g,"/").padEnd(t.length+(4-t.length%4)%4,"="),i=JSON.parse(atob(n));return!(typeof i!="object"||i===null||!i.typ||!i.alg||e&&i.alg!==e)}catch{return!1}}function No(r,e){return!!((e==="v4"||!e)&&Oo.test(r)||(e==="v6"||!e)&&$o.test(r))}var ue=class r extends x{_parse(e){if(this._def.coerce&&(e.data=String(e.data)),this._getType(e)!==m.string){let o=this._getOrReturnCtx(e);return h(o,{code:f.invalid_type,expected:m.string,received:o.parsedType}),_}let n=new P,i;for(let o of this._def.checks)if(o.kind==="min")e.data.lengtho.value&&(i=this._getOrReturnCtx(e,i),h(i,{code:f.too_big,maximum:o.value,type:"string",inclusive:!0,exact:!1,message:o.message}),n.dirty());else if(o.kind==="length"){let s=e.data.length>o.value,c=e.data.lengthe.test(i),{validation:t,code:f.invalid_string,...v.errToObj(n)})}_addCheck(e){return new r({...this._def,checks:[...this._def.checks,e]})}email(e){return this._addCheck({kind:"email",...v.errToObj(e)})}url(e){return this._addCheck({kind:"url",...v.errToObj(e)})}emoji(e){return this._addCheck({kind:"emoji",...v.errToObj(e)})}uuid(e){return this._addCheck({kind:"uuid",...v.errToObj(e)})}nanoid(e){return this._addCheck({kind:"nanoid",...v.errToObj(e)})}cuid(e){return this._addCheck({kind:"cuid",...v.errToObj(e)})}cuid2(e){return this._addCheck({kind:"cuid2",...v.errToObj(e)})}ulid(e){return this._addCheck({kind:"ulid",...v.errToObj(e)})}base64(e){return this._addCheck({kind:"base64",...v.errToObj(e)})}base64url(e){return this._addCheck({kind:"base64url",...v.errToObj(e)})}jwt(e){return this._addCheck({kind:"jwt",...v.errToObj(e)})}ip(e){return this._addCheck({kind:"ip",...v.errToObj(e)})}cidr(e){return this._addCheck({kind:"cidr",...v.errToObj(e)})}datetime(e){var t,n;return typeof e=="string"?this._addCheck({kind:"datetime",precision:null,offset:!1,local:!1,message:e}):this._addCheck({kind:"datetime",precision:typeof e?.precision>"u"?null:e?.precision,offset:(t=e?.offset)!==null&&t!==void 0?t:!1,local:(n=e?.local)!==null&&n!==void 0?n:!1,...v.errToObj(e?.message)})}date(e){return this._addCheck({kind:"date",message:e})}time(e){return typeof e=="string"?this._addCheck({kind:"time",precision:null,message:e}):this._addCheck({kind:"time",precision:typeof e?.precision>"u"?null:e?.precision,...v.errToObj(e?.message)})}duration(e){return this._addCheck({kind:"duration",...v.errToObj(e)})}regex(e,t){return this._addCheck({kind:"regex",regex:e,...v.errToObj(t)})}includes(e,t){return this._addCheck({kind:"includes",value:e,position:t?.position,...v.errToObj(t?.message)})}startsWith(e,t){return this._addCheck({kind:"startsWith",value:e,...v.errToObj(t)})}endsWith(e,t){return this._addCheck({kind:"endsWith",value:e,...v.errToObj(t)})}min(e,t){return this._addCheck({kind:"min",value:e,...v.errToObj(t)})}max(e,t){return this._addCheck({kind:"max",value:e,...v.errToObj(t)})}length(e,t){return this._addCheck({kind:"length",value:e,...v.errToObj(t)})}nonempty(e){return this.min(1,v.errToObj(e))}trim(){return new r({...this._def,checks:[...this._def.checks,{kind:"trim"}]})}toLowerCase(){return new r({...this._def,checks:[...this._def.checks,{kind:"toLowerCase"}]})}toUpperCase(){return new r({...this._def,checks:[...this._def.checks,{kind:"toUpperCase"}]})}get isDatetime(){return!!this._def.checks.find(e=>e.kind==="datetime")}get isDate(){return!!this._def.checks.find(e=>e.kind==="date")}get isTime(){return!!this._def.checks.find(e=>e.kind==="time")}get isDuration(){return!!this._def.checks.find(e=>e.kind==="duration")}get isEmail(){return!!this._def.checks.find(e=>e.kind==="email")}get isURL(){return!!this._def.checks.find(e=>e.kind==="url")}get isEmoji(){return!!this._def.checks.find(e=>e.kind==="emoji")}get isUUID(){return!!this._def.checks.find(e=>e.kind==="uuid")}get isNANOID(){return!!this._def.checks.find(e=>e.kind==="nanoid")}get isCUID(){return!!this._def.checks.find(e=>e.kind==="cuid")}get isCUID2(){return!!this._def.checks.find(e=>e.kind==="cuid2")}get isULID(){return!!this._def.checks.find(e=>e.kind==="ulid")}get isIP(){return!!this._def.checks.find(e=>e.kind==="ip")}get isCIDR(){return!!this._def.checks.find(e=>e.kind==="cidr")}get isBase64(){return!!this._def.checks.find(e=>e.kind==="base64")}get isBase64url(){return!!this._def.checks.find(e=>e.kind==="base64url")}get minLength(){let e=null;for(let t of this._def.checks)t.kind==="min"&&(e===null||t.value>e)&&(e=t.value);return e}get maxLength(){let e=null;for(let t of this._def.checks)t.kind==="max"&&(e===null||t.value{var e;return new ue({checks:[],typeName:g.ZodString,coerce:(e=r?.coerce)!==null&&e!==void 0?e:!1,...b(r)})};function Lo(r,e){let t=(r.toString().split(".")[1]||"").length,n=(e.toString().split(".")[1]||"").length,i=t>n?t:n,o=parseInt(r.toFixed(i).replace(".","")),s=parseInt(e.toFixed(i).replace(".",""));return o%s/Math.pow(10,i)}var ke=class r extends x{constructor(){super(...arguments),this.min=this.gte,this.max=this.lte,this.step=this.multipleOf}_parse(e){if(this._def.coerce&&(e.data=Number(e.data)),this._getType(e)!==m.number){let o=this._getOrReturnCtx(e);return h(o,{code:f.invalid_type,expected:m.number,received:o.parsedType}),_}let n,i=new P;for(let o of this._def.checks)o.kind==="int"?T.isInteger(e.data)||(n=this._getOrReturnCtx(e,n),h(n,{code:f.invalid_type,expected:"integer",received:"float",message:o.message}),i.dirty()):o.kind==="min"?(o.inclusive?e.datao.value:e.data>=o.value)&&(n=this._getOrReturnCtx(e,n),h(n,{code:f.too_big,maximum:o.value,type:"number",inclusive:o.inclusive,exact:!1,message:o.message}),i.dirty()):o.kind==="multipleOf"?Lo(e.data,o.value)!==0&&(n=this._getOrReturnCtx(e,n),h(n,{code:f.not_multiple_of,multipleOf:o.value,message:o.message}),i.dirty()):o.kind==="finite"?Number.isFinite(e.data)||(n=this._getOrReturnCtx(e,n),h(n,{code:f.not_finite,message:o.message}),i.dirty()):T.assertNever(o);return{status:i.value,value:e.data}}gte(e,t){return this.setLimit("min",e,!0,v.toString(t))}gt(e,t){return this.setLimit("min",e,!1,v.toString(t))}lte(e,t){return this.setLimit("max",e,!0,v.toString(t))}lt(e,t){return this.setLimit("max",e,!1,v.toString(t))}setLimit(e,t,n,i){return new r({...this._def,checks:[...this._def.checks,{kind:e,value:t,inclusive:n,message:v.toString(i)}]})}_addCheck(e){return new r({...this._def,checks:[...this._def.checks,e]})}int(e){return this._addCheck({kind:"int",message:v.toString(e)})}positive(e){return this._addCheck({kind:"min",value:0,inclusive:!1,message:v.toString(e)})}negative(e){return this._addCheck({kind:"max",value:0,inclusive:!1,message:v.toString(e)})}nonpositive(e){return this._addCheck({kind:"max",value:0,inclusive:!0,message:v.toString(e)})}nonnegative(e){return this._addCheck({kind:"min",value:0,inclusive:!0,message:v.toString(e)})}multipleOf(e,t){return this._addCheck({kind:"multipleOf",value:e,message:v.toString(t)})}finite(e){return this._addCheck({kind:"finite",message:v.toString(e)})}safe(e){return this._addCheck({kind:"min",inclusive:!0,value:Number.MIN_SAFE_INTEGER,message:v.toString(e)})._addCheck({kind:"max",inclusive:!0,value:Number.MAX_SAFE_INTEGER,message:v.toString(e)})}get minValue(){let e=null;for(let t of this._def.checks)t.kind==="min"&&(e===null||t.value>e)&&(e=t.value);return e}get maxValue(){let e=null;for(let t of this._def.checks)t.kind==="max"&&(e===null||t.valuee.kind==="int"||e.kind==="multipleOf"&&T.isInteger(e.value))}get isFinite(){let e=null,t=null;for(let n of this._def.checks){if(n.kind==="finite"||n.kind==="int"||n.kind==="multipleOf")return!0;n.kind==="min"?(t===null||n.value>t)&&(t=n.value):n.kind==="max"&&(e===null||n.valuenew ke({checks:[],typeName:g.ZodNumber,coerce:r?.coerce||!1,...b(r)});var Te=class r extends x{constructor(){super(...arguments),this.min=this.gte,this.max=this.lte}_parse(e){if(this._def.coerce)try{e.data=BigInt(e.data)}catch{return this._getInvalidInput(e)}if(this._getType(e)!==m.bigint)return this._getInvalidInput(e);let n,i=new P;for(let o of this._def.checks)o.kind==="min"?(o.inclusive?e.datao.value:e.data>=o.value)&&(n=this._getOrReturnCtx(e,n),h(n,{code:f.too_big,type:"bigint",maximum:o.value,inclusive:o.inclusive,message:o.message}),i.dirty()):o.kind==="multipleOf"?e.data%o.value!==BigInt(0)&&(n=this._getOrReturnCtx(e,n),h(n,{code:f.not_multiple_of,multipleOf:o.value,message:o.message}),i.dirty()):T.assertNever(o);return{status:i.value,value:e.data}}_getInvalidInput(e){let t=this._getOrReturnCtx(e);return h(t,{code:f.invalid_type,expected:m.bigint,received:t.parsedType}),_}gte(e,t){return this.setLimit("min",e,!0,v.toString(t))}gt(e,t){return this.setLimit("min",e,!1,v.toString(t))}lte(e,t){return this.setLimit("max",e,!0,v.toString(t))}lt(e,t){return this.setLimit("max",e,!1,v.toString(t))}setLimit(e,t,n,i){return new r({...this._def,checks:[...this._def.checks,{kind:e,value:t,inclusive:n,message:v.toString(i)}]})}_addCheck(e){return new r({...this._def,checks:[...this._def.checks,e]})}positive(e){return this._addCheck({kind:"min",value:BigInt(0),inclusive:!1,message:v.toString(e)})}negative(e){return this._addCheck({kind:"max",value:BigInt(0),inclusive:!1,message:v.toString(e)})}nonpositive(e){return this._addCheck({kind:"max",value:BigInt(0),inclusive:!0,message:v.toString(e)})}nonnegative(e){return this._addCheck({kind:"min",value:BigInt(0),inclusive:!0,message:v.toString(e)})}multipleOf(e,t){return this._addCheck({kind:"multipleOf",value:e,message:v.toString(t)})}get minValue(){let e=null;for(let t of this._def.checks)t.kind==="min"&&(e===null||t.value>e)&&(e=t.value);return e}get maxValue(){let e=null;for(let t of this._def.checks)t.kind==="max"&&(e===null||t.value{var e;return new Te({checks:[],typeName:g.ZodBigInt,coerce:(e=r?.coerce)!==null&&e!==void 0?e:!1,...b(r)})};var Ee=class extends x{_parse(e){if(this._def.coerce&&(e.data=!!e.data),this._getType(e)!==m.boolean){let n=this._getOrReturnCtx(e);return h(n,{code:f.invalid_type,expected:m.boolean,received:n.parsedType}),_}return D(e.data)}};Ee.create=r=>new Ee({typeName:g.ZodBoolean,coerce:r?.coerce||!1,...b(r)});var Ae=class r extends x{_parse(e){if(this._def.coerce&&(e.data=new Date(e.data)),this._getType(e)!==m.date){let o=this._getOrReturnCtx(e);return h(o,{code:f.invalid_type,expected:m.date,received:o.parsedType}),_}if(isNaN(e.data.getTime())){let o=this._getOrReturnCtx(e);return h(o,{code:f.invalid_date}),_}let n=new P,i;for(let o of this._def.checks)o.kind==="min"?e.data.getTime()o.value&&(i=this._getOrReturnCtx(e,i),h(i,{code:f.too_big,message:o.message,inclusive:!0,exact:!1,maximum:o.value,type:"date"}),n.dirty()):T.assertNever(o);return{status:n.value,value:new Date(e.data.getTime())}}_addCheck(e){return new r({...this._def,checks:[...this._def.checks,e]})}min(e,t){return this._addCheck({kind:"min",value:e.getTime(),message:v.toString(t)})}max(e,t){return this._addCheck({kind:"max",value:e.getTime(),message:v.toString(t)})}get minDate(){let e=null;for(let t of this._def.checks)t.kind==="min"&&(e===null||t.value>e)&&(e=t.value);return e!=null?new Date(e):null}get maxDate(){let e=null;for(let t of this._def.checks)t.kind==="max"&&(e===null||t.valuenew Ae({checks:[],coerce:r?.coerce||!1,typeName:g.ZodDate,...b(r)});var Qe=class extends x{_parse(e){if(this._getType(e)!==m.symbol){let n=this._getOrReturnCtx(e);return h(n,{code:f.invalid_type,expected:m.symbol,received:n.parsedType}),_}return D(e.data)}};Qe.create=r=>new Qe({typeName:g.ZodSymbol,...b(r)});var Oe=class extends x{_parse(e){if(this._getType(e)!==m.undefined){let n=this._getOrReturnCtx(e);return h(n,{code:f.invalid_type,expected:m.undefined,received:n.parsedType}),_}return D(e.data)}};Oe.create=r=>new Oe({typeName:g.ZodUndefined,...b(r)});var Ce=class extends x{_parse(e){if(this._getType(e)!==m.null){let n=this._getOrReturnCtx(e);return h(n,{code:f.invalid_type,expected:m.null,received:n.parsedType}),_}return D(e.data)}};Ce.create=r=>new Ce({typeName:g.ZodNull,...b(r)});var fe=class extends x{constructor(){super(...arguments),this._any=!0}_parse(e){return D(e.data)}};fe.create=r=>new fe({typeName:g.ZodAny,...b(r)});var oe=class extends x{constructor(){super(...arguments),this._unknown=!0}_parse(e){return D(e.data)}};oe.create=r=>new oe({typeName:g.ZodUnknown,...b(r)});var J=class extends x{_parse(e){let t=this._getOrReturnCtx(e);return h(t,{code:f.invalid_type,expected:m.never,received:t.parsedType}),_}};J.create=r=>new J({typeName:g.ZodNever,...b(r)});var et=class extends x{_parse(e){if(this._getType(e)!==m.undefined){let n=this._getOrReturnCtx(e);return h(n,{code:f.invalid_type,expected:m.void,received:n.parsedType}),_}return D(e.data)}};et.create=r=>new et({typeName:g.ZodVoid,...b(r)});var se=class r extends x{_parse(e){let{ctx:t,status:n}=this._processInputParams(e),i=this._def;if(t.parsedType!==m.array)return h(t,{code:f.invalid_type,expected:m.array,received:t.parsedType}),_;if(i.exactLength!==null){let s=t.data.length>i.exactLength.value,c=t.data.lengthi.maxLength.value&&(h(t,{code:f.too_big,maximum:i.maxLength.value,type:"array",inclusive:!0,exact:!1,message:i.maxLength.message}),n.dirty()),t.common.async)return Promise.all([...t.data].map((s,c)=>i.type._parseAsync(new B(t,s,t.path,c)))).then(s=>P.mergeArray(n,s));let o=[...t.data].map((s,c)=>i.type._parseSync(new B(t,s,t.path,c)));return P.mergeArray(n,o)}get element(){return this._def.type}min(e,t){return new r({...this._def,minLength:{value:e,message:v.toString(t)}})}max(e,t){return new r({...this._def,maxLength:{value:e,message:v.toString(t)}})}length(e,t){return new r({...this._def,exactLength:{value:e,message:v.toString(t)}})}nonempty(e){return this.min(1,e)}};se.create=(r,e)=>new se({type:r,minLength:null,maxLength:null,exactLength:null,typeName:g.ZodArray,...b(e)});function Je(r){if(r instanceof M){let e={};for(let t in r.shape){let n=r.shape[t];e[t]=V.create(Je(n))}return new M({...r._def,shape:()=>e})}else return r instanceof se?new se({...r._def,type:Je(r.element)}):r instanceof V?V.create(Je(r.unwrap())):r instanceof te?te.create(Je(r.unwrap())):r instanceof ee?ee.create(r.items.map(e=>Je(e))):r}var M=class r extends x{constructor(){super(...arguments),this._cached=null,this.nonstrict=this.passthrough,this.augment=this.extend}_getCached(){if(this._cached!==null)return this._cached;let e=this._def.shape(),t=T.objectKeys(e);return this._cached={shape:e,keys:t}}_parse(e){if(this._getType(e)!==m.object){let d=this._getOrReturnCtx(e);return h(d,{code:f.invalid_type,expected:m.object,received:d.parsedType}),_}let{status:n,ctx:i}=this._processInputParams(e),{shape:o,keys:s}=this._getCached(),c=[];if(!(this._def.catchall instanceof J&&this._def.unknownKeys==="strip"))for(let d in i.data)s.includes(d)||c.push(d);let l=[];for(let d of s){let u=o[d],p=i.data[d];l.push({key:{status:"valid",value:d},value:u._parse(new B(i,p,i.path,d)),alwaysSet:d in i.data})}if(this._def.catchall instanceof J){let d=this._def.unknownKeys;if(d==="passthrough")for(let u of c)l.push({key:{status:"valid",value:u},value:{status:"valid",value:i.data[u]}});else if(d==="strict")c.length>0&&(h(i,{code:f.unrecognized_keys,keys:c}),n.dirty());else if(d!=="strip")throw new Error("Internal ZodObject error: invalid unknownKeys value.")}else{let d=this._def.catchall;for(let u of c){let p=i.data[u];l.push({key:{status:"valid",value:u},value:d._parse(new B(i,p,i.path,u)),alwaysSet:u in i.data})}}return i.common.async?Promise.resolve().then(async()=>{let d=[];for(let u of l){let p=await u.key,w=await u.value;d.push({key:p,value:w,alwaysSet:u.alwaysSet})}return d}).then(d=>P.mergeObjectSync(n,d)):P.mergeObjectSync(n,l)}get shape(){return this._def.shape()}strict(e){return v.errToObj,new r({...this._def,unknownKeys:"strict",...e!==void 0?{errorMap:(t,n)=>{var i,o,s,c;let l=(s=(o=(i=this._def).errorMap)===null||o===void 0?void 0:o.call(i,t,n).message)!==null&&s!==void 0?s:n.defaultError;return t.code==="unrecognized_keys"?{message:(c=v.errToObj(e).message)!==null&&c!==void 0?c:l}:{message:l}}}:{}})}strip(){return new r({...this._def,unknownKeys:"strip"})}passthrough(){return new r({...this._def,unknownKeys:"passthrough"})}extend(e){return new r({...this._def,shape:()=>({...this._def.shape(),...e})})}merge(e){return new r({unknownKeys:e._def.unknownKeys,catchall:e._def.catchall,shape:()=>({...this._def.shape(),...e._def.shape()}),typeName:g.ZodObject})}setKey(e,t){return this.augment({[e]:t})}catchall(e){return new r({...this._def,catchall:e})}pick(e){let t={};return T.objectKeys(e).forEach(n=>{e[n]&&this.shape[n]&&(t[n]=this.shape[n])}),new r({...this._def,shape:()=>t})}omit(e){let t={};return T.objectKeys(this.shape).forEach(n=>{e[n]||(t[n]=this.shape[n])}),new r({...this._def,shape:()=>t})}deepPartial(){return Je(this)}partial(e){let t={};return T.objectKeys(this.shape).forEach(n=>{let i=this.shape[n];e&&!e[n]?t[n]=i:t[n]=i.optional()}),new r({...this._def,shape:()=>t})}required(e){let t={};return T.objectKeys(this.shape).forEach(n=>{if(e&&!e[n])t[n]=this.shape[n];else{let o=this.shape[n];for(;o instanceof V;)o=o._def.innerType;t[n]=o}}),new r({...this._def,shape:()=>t})}keyof(){return Kn(T.objectKeys(this.shape))}};M.create=(r,e)=>new M({shape:()=>r,unknownKeys:"strip",catchall:J.create(),typeName:g.ZodObject,...b(e)});M.strictCreate=(r,e)=>new M({shape:()=>r,unknownKeys:"strict",catchall:J.create(),typeName:g.ZodObject,...b(e)});M.lazycreate=(r,e)=>new M({shape:r,unknownKeys:"strip",catchall:J.create(),typeName:g.ZodObject,...b(e)});var $e=class extends x{_parse(e){let{ctx:t}=this._processInputParams(e),n=this._def.options;function i(o){for(let c of o)if(c.result.status==="valid")return c.result;for(let c of o)if(c.result.status==="dirty")return t.common.issues.push(...c.ctx.common.issues),c.result;let s=o.map(c=>new z(c.ctx.common.issues));return h(t,{code:f.invalid_union,unionErrors:s}),_}if(t.common.async)return Promise.all(n.map(async o=>{let s={...t,common:{...t.common,issues:[]},parent:null};return{result:await o._parseAsync({data:t.data,path:t.path,parent:s}),ctx:s}})).then(i);{let o,s=[];for(let l of n){let d={...t,common:{...t.common,issues:[]},parent:null},u=l._parseSync({data:t.data,path:t.path,parent:d});if(u.status==="valid")return u;u.status==="dirty"&&!o&&(o={result:u,ctx:d}),d.common.issues.length&&s.push(d.common.issues)}if(o)return t.common.issues.push(...o.ctx.common.issues),o.result;let c=s.map(l=>new z(l));return h(t,{code:f.invalid_union,unionErrors:c}),_}}get options(){return this._def.options}};$e.create=(r,e)=>new $e({options:r,typeName:g.ZodUnion,...b(e)});var ne=r=>r instanceof Ie?ne(r.schema):r instanceof Z?ne(r.innerType()):r instanceof Re?[r.value]:r instanceof Pe?r.options:r instanceof De?T.objectValues(r.enum):r instanceof Me?ne(r._def.innerType):r instanceof Oe?[void 0]:r instanceof Ce?[null]:r instanceof V?[void 0,...ne(r.unwrap())]:r instanceof te?[null,...ne(r.unwrap())]:r instanceof gt||r instanceof Le?ne(r.unwrap()):r instanceof Ne?ne(r._def.innerType):[],ir=class r extends x{_parse(e){let{ctx:t}=this._processInputParams(e);if(t.parsedType!==m.object)return h(t,{code:f.invalid_type,expected:m.object,received:t.parsedType}),_;let n=this.discriminator,i=t.data[n],o=this.optionsMap.get(i);return o?t.common.async?o._parseAsync({data:t.data,path:t.path,parent:t}):o._parseSync({data:t.data,path:t.path,parent:t}):(h(t,{code:f.invalid_union_discriminator,options:Array.from(this.optionsMap.keys()),path:[n]}),_)}get discriminator(){return this._def.discriminator}get options(){return this._def.options}get optionsMap(){return this._def.optionsMap}static create(e,t,n){let i=new Map;for(let o of t){let s=ne(o.shape[e]);if(!s.length)throw new Error(`A discriminator value for key \`${e}\` could not be extracted from all schema options`);for(let c of s){if(i.has(c))throw new Error(`Discriminator property ${String(e)} has duplicate value ${String(c)}`);i.set(c,o)}}return new r({typeName:g.ZodDiscriminatedUnion,discriminator:e,options:t,optionsMap:i,...b(n)})}};function Wr(r,e){let t=ie(r),n=ie(e);if(r===e)return{valid:!0,data:r};if(t===m.object&&n===m.object){let i=T.objectKeys(e),o=T.objectKeys(r).filter(c=>i.indexOf(c)!==-1),s={...r,...e};for(let c of o){let l=Wr(r[c],e[c]);if(!l.valid)return{valid:!1};s[c]=l.data}return{valid:!0,data:s}}else if(t===m.array&&n===m.array){if(r.length!==e.length)return{valid:!1};let i=[];for(let o=0;o{if(Vr(o)||Vr(s))return _;let c=Wr(o.value,s.value);return c.valid?((Br(o)||Br(s))&&t.dirty(),{status:t.value,value:c.data}):(h(n,{code:f.invalid_intersection_types}),_)};return n.common.async?Promise.all([this._def.left._parseAsync({data:n.data,path:n.path,parent:n}),this._def.right._parseAsync({data:n.data,path:n.path,parent:n})]).then(([o,s])=>i(o,s)):i(this._def.left._parseSync({data:n.data,path:n.path,parent:n}),this._def.right._parseSync({data:n.data,path:n.path,parent:n}))}};je.create=(r,e,t)=>new je({left:r,right:e,typeName:g.ZodIntersection,...b(t)});var ee=class r extends x{_parse(e){let{status:t,ctx:n}=this._processInputParams(e);if(n.parsedType!==m.array)return h(n,{code:f.invalid_type,expected:m.array,received:n.parsedType}),_;if(n.data.lengththis._def.items.length&&(h(n,{code:f.too_big,maximum:this._def.items.length,inclusive:!0,exact:!1,type:"array"}),t.dirty());let o=[...n.data].map((s,c)=>{let l=this._def.items[c]||this._def.rest;return l?l._parse(new B(n,s,n.path,c)):null}).filter(s=>!!s);return n.common.async?Promise.all(o).then(s=>P.mergeArray(t,s)):P.mergeArray(t,o)}get items(){return this._def.items}rest(e){return new r({...this._def,rest:e})}};ee.create=(r,e)=>{if(!Array.isArray(r))throw new Error("You must pass an array of schemas to z.tuple([ ... ])");return new ee({items:r,typeName:g.ZodTuple,rest:null,...b(e)})};var or=class r extends x{get keySchema(){return this._def.keyType}get valueSchema(){return this._def.valueType}_parse(e){let{status:t,ctx:n}=this._processInputParams(e);if(n.parsedType!==m.object)return h(n,{code:f.invalid_type,expected:m.object,received:n.parsedType}),_;let i=[],o=this._def.keyType,s=this._def.valueType;for(let c in n.data)i.push({key:o._parse(new B(n,c,n.path,c)),value:s._parse(new B(n,n.data[c],n.path,c)),alwaysSet:c in n.data});return n.common.async?P.mergeObjectAsync(t,i):P.mergeObjectSync(t,i)}get element(){return this._def.valueType}static create(e,t,n){return t instanceof x?new r({keyType:e,valueType:t,typeName:g.ZodRecord,...b(n)}):new r({keyType:ue.create(),valueType:e,typeName:g.ZodRecord,...b(t)})}},tt=class extends x{get keySchema(){return this._def.keyType}get valueSchema(){return this._def.valueType}_parse(e){let{status:t,ctx:n}=this._processInputParams(e);if(n.parsedType!==m.map)return h(n,{code:f.invalid_type,expected:m.map,received:n.parsedType}),_;let i=this._def.keyType,o=this._def.valueType,s=[...n.data.entries()].map(([c,l],d)=>({key:i._parse(new B(n,c,n.path,[d,"key"])),value:o._parse(new B(n,l,n.path,[d,"value"]))}));if(n.common.async){let c=new Map;return Promise.resolve().then(async()=>{for(let l of s){let d=await l.key,u=await l.value;if(d.status==="aborted"||u.status==="aborted")return _;(d.status==="dirty"||u.status==="dirty")&&t.dirty(),c.set(d.value,u.value)}return{status:t.value,value:c}})}else{let c=new Map;for(let l of s){let d=l.key,u=l.value;if(d.status==="aborted"||u.status==="aborted")return _;(d.status==="dirty"||u.status==="dirty")&&t.dirty(),c.set(d.value,u.value)}return{status:t.value,value:c}}}};tt.create=(r,e,t)=>new tt({valueType:e,keyType:r,typeName:g.ZodMap,...b(t)});var rt=class r extends x{_parse(e){let{status:t,ctx:n}=this._processInputParams(e);if(n.parsedType!==m.set)return h(n,{code:f.invalid_type,expected:m.set,received:n.parsedType}),_;let i=this._def;i.minSize!==null&&n.data.sizei.maxSize.value&&(h(n,{code:f.too_big,maximum:i.maxSize.value,type:"set",inclusive:!0,exact:!1,message:i.maxSize.message}),t.dirty());let o=this._def.valueType;function s(l){let d=new Set;for(let u of l){if(u.status==="aborted")return _;u.status==="dirty"&&t.dirty(),d.add(u.value)}return{status:t.value,value:d}}let c=[...n.data.values()].map((l,d)=>o._parse(new B(n,l,n.path,d)));return n.common.async?Promise.all(c).then(l=>s(l)):s(c)}min(e,t){return new r({...this._def,minSize:{value:e,message:v.toString(t)}})}max(e,t){return new r({...this._def,maxSize:{value:e,message:v.toString(t)}})}size(e,t){return this.min(e,t).max(e,t)}nonempty(e){return this.min(1,e)}};rt.create=(r,e)=>new rt({valueType:r,minSize:null,maxSize:null,typeName:g.ZodSet,...b(e)});var sr=class r extends x{constructor(){super(...arguments),this.validate=this.implement}_parse(e){let{ctx:t}=this._processInputParams(e);if(t.parsedType!==m.function)return h(t,{code:f.invalid_type,expected:m.function,received:t.parsedType}),_;function n(c,l){return rr({data:c,path:t.path,errorMaps:[t.common.contextualErrorMap,t.schemaErrorMap,tr(),Xe].filter(d=>!!d),issueData:{code:f.invalid_arguments,argumentsError:l}})}function i(c,l){return rr({data:c,path:t.path,errorMaps:[t.common.contextualErrorMap,t.schemaErrorMap,tr(),Xe].filter(d=>!!d),issueData:{code:f.invalid_return_type,returnTypeError:l}})}let o={errorMap:t.common.contextualErrorMap},s=t.data;if(this._def.returns instanceof pe){let c=this;return D(async function(...l){let d=new z([]),u=await c._def.args.parseAsync(l,o).catch(y=>{throw d.addIssue(n(l,y)),d}),p=await Reflect.apply(s,this,u);return await c._def.returns._def.type.parseAsync(p,o).catch(y=>{throw d.addIssue(i(p,y)),d})})}else{let c=this;return D(function(...l){let d=c._def.args.safeParse(l,o);if(!d.success)throw new z([n(l,d.error)]);let u=Reflect.apply(s,this,d.data),p=c._def.returns.safeParse(u,o);if(!p.success)throw new z([i(u,p.error)]);return p.data})}}parameters(){return this._def.args}returnType(){return this._def.returns}args(...e){return new r({...this._def,args:ee.create(e).rest(oe.create())})}returns(e){return new r({...this._def,returns:e})}implement(e){return this.parse(e)}strictImplement(e){return this.parse(e)}static create(e,t,n){return new r({args:e||ee.create([]).rest(oe.create()),returns:t||oe.create(),typeName:g.ZodFunction,...b(n)})}},Ie=class extends x{get schema(){return this._def.getter()}_parse(e){let{ctx:t}=this._processInputParams(e);return this._def.getter()._parse({data:t.data,path:t.path,parent:t})}};Ie.create=(r,e)=>new Ie({getter:r,typeName:g.ZodLazy,...b(e)});var Re=class extends x{_parse(e){if(e.data!==this._def.value){let t=this._getOrReturnCtx(e);return h(t,{received:t.data,code:f.invalid_literal,expected:this._def.value}),_}return{status:"valid",value:e.data}}get value(){return this._def.value}};Re.create=(r,e)=>new Re({value:r,typeName:g.ZodLiteral,...b(e)});function Kn(r,e){return new Pe({values:r,typeName:g.ZodEnum,...b(e)})}var Pe=class r extends x{constructor(){super(...arguments),mt.set(this,void 0)}_parse(e){if(typeof e.data!="string"){let t=this._getOrReturnCtx(e),n=this._def.values;return h(t,{expected:T.joinValues(n),received:t.parsedType,code:f.invalid_type}),_}if(nr(this,mt,"f")||qn(this,mt,new Set(this._def.values),"f"),!nr(this,mt,"f").has(e.data)){let t=this._getOrReturnCtx(e),n=this._def.values;return h(t,{received:t.data,code:f.invalid_enum_value,options:n}),_}return D(e.data)}get options(){return this._def.values}get enum(){let e={};for(let t of this._def.values)e[t]=t;return e}get Values(){let e={};for(let t of this._def.values)e[t]=t;return e}get Enum(){let e={};for(let t of this._def.values)e[t]=t;return e}extract(e,t=this._def){return r.create(e,{...this._def,...t})}exclude(e,t=this._def){return r.create(this.options.filter(n=>!e.includes(n)),{...this._def,...t})}};mt=new WeakMap;Pe.create=Kn;var De=class extends x{constructor(){super(...arguments),vt.set(this,void 0)}_parse(e){let t=T.getValidEnumValues(this._def.values),n=this._getOrReturnCtx(e);if(n.parsedType!==m.string&&n.parsedType!==m.number){let i=T.objectValues(t);return h(n,{expected:T.joinValues(i),received:n.parsedType,code:f.invalid_type}),_}if(nr(this,vt,"f")||qn(this,vt,new Set(T.getValidEnumValues(this._def.values)),"f"),!nr(this,vt,"f").has(e.data)){let i=T.objectValues(t);return h(n,{received:n.data,code:f.invalid_enum_value,options:i}),_}return D(e.data)}get enum(){return this._def.values}};vt=new WeakMap;De.create=(r,e)=>new De({values:r,typeName:g.ZodNativeEnum,...b(e)});var pe=class extends x{unwrap(){return this._def.type}_parse(e){let{ctx:t}=this._processInputParams(e);if(t.parsedType!==m.promise&&t.common.async===!1)return h(t,{code:f.invalid_type,expected:m.promise,received:t.parsedType}),_;let n=t.parsedType===m.promise?t.data:Promise.resolve(t.data);return D(n.then(i=>this._def.type.parseAsync(i,{path:t.path,errorMap:t.common.contextualErrorMap})))}};pe.create=(r,e)=>new pe({type:r,typeName:g.ZodPromise,...b(e)});var Z=class extends x{innerType(){return this._def.schema}sourceType(){return this._def.schema._def.typeName===g.ZodEffects?this._def.schema.sourceType():this._def.schema}_parse(e){let{status:t,ctx:n}=this._processInputParams(e),i=this._def.effect||null,o={addIssue:s=>{h(n,s),s.fatal?t.abort():t.dirty()},get path(){return n.path}};if(o.addIssue=o.addIssue.bind(o),i.type==="preprocess"){let s=i.transform(n.data,o);if(n.common.async)return Promise.resolve(s).then(async c=>{if(t.value==="aborted")return _;let l=await this._def.schema._parseAsync({data:c,path:n.path,parent:n});return l.status==="aborted"?_:l.status==="dirty"||t.value==="dirty"?Ke(l.value):l});{if(t.value==="aborted")return _;let c=this._def.schema._parseSync({data:s,path:n.path,parent:n});return c.status==="aborted"?_:c.status==="dirty"||t.value==="dirty"?Ke(c.value):c}}if(i.type==="refinement"){let s=c=>{let l=i.refinement(c,o);if(n.common.async)return Promise.resolve(l);if(l instanceof Promise)throw new Error("Async refinement encountered during synchronous parse operation. Use .parseAsync instead.");return c};if(n.common.async===!1){let c=this._def.schema._parseSync({data:n.data,path:n.path,parent:n});return c.status==="aborted"?_:(c.status==="dirty"&&t.dirty(),s(c.value),{status:t.value,value:c.value})}else return this._def.schema._parseAsync({data:n.data,path:n.path,parent:n}).then(c=>c.status==="aborted"?_:(c.status==="dirty"&&t.dirty(),s(c.value).then(()=>({status:t.value,value:c.value}))))}if(i.type==="transform")if(n.common.async===!1){let s=this._def.schema._parseSync({data:n.data,path:n.path,parent:n});if(!Se(s))return s;let c=i.transform(s.value,o);if(c instanceof Promise)throw new Error("Asynchronous transform encountered during synchronous parse operation. Use .parseAsync instead.");return{status:t.value,value:c}}else return this._def.schema._parseAsync({data:n.data,path:n.path,parent:n}).then(s=>Se(s)?Promise.resolve(i.transform(s.value,o)).then(c=>({status:t.value,value:c})):s);T.assertNever(i)}};Z.create=(r,e,t)=>new Z({schema:r,typeName:g.ZodEffects,effect:e,...b(t)});Z.createWithPreprocess=(r,e,t)=>new Z({schema:e,effect:{type:"preprocess",transform:r},typeName:g.ZodEffects,...b(t)});var V=class extends x{_parse(e){return this._getType(e)===m.undefined?D(void 0):this._def.innerType._parse(e)}unwrap(){return this._def.innerType}};V.create=(r,e)=>new V({innerType:r,typeName:g.ZodOptional,...b(e)});var te=class extends x{_parse(e){return this._getType(e)===m.null?D(null):this._def.innerType._parse(e)}unwrap(){return this._def.innerType}};te.create=(r,e)=>new te({innerType:r,typeName:g.ZodNullable,...b(e)});var Me=class extends x{_parse(e){let{ctx:t}=this._processInputParams(e),n=t.data;return t.parsedType===m.undefined&&(n=this._def.defaultValue()),this._def.innerType._parse({data:n,path:t.path,parent:t})}removeDefault(){return this._def.innerType}};Me.create=(r,e)=>new Me({innerType:r,typeName:g.ZodDefault,defaultValue:typeof e.default=="function"?e.default:()=>e.default,...b(e)});var Ne=class extends x{_parse(e){let{ctx:t}=this._processInputParams(e),n={...t,common:{...t.common,issues:[]}},i=this._def.innerType._parse({data:n.data,path:n.path,parent:{...n}});return yt(i)?i.then(o=>({status:"valid",value:o.status==="valid"?o.value:this._def.catchValue({get error(){return new z(n.common.issues)},input:n.data})})):{status:"valid",value:i.status==="valid"?i.value:this._def.catchValue({get error(){return new z(n.common.issues)},input:n.data})}}removeCatch(){return this._def.innerType}};Ne.create=(r,e)=>new Ne({innerType:r,typeName:g.ZodCatch,catchValue:typeof e.catch=="function"?e.catch:()=>e.catch,...b(e)});var nt=class extends x{_parse(e){if(this._getType(e)!==m.nan){let n=this._getOrReturnCtx(e);return h(n,{code:f.invalid_type,expected:m.nan,received:n.parsedType}),_}return{status:"valid",value:e.data}}};nt.create=r=>new nt({typeName:g.ZodNaN,...b(r)});var Uo=Symbol("zod_brand"),gt=class extends x{_parse(e){let{ctx:t}=this._processInputParams(e),n=t.data;return this._def.type._parse({data:n,path:t.path,parent:t})}unwrap(){return this._def.type}},_t=class r extends x{_parse(e){let{status:t,ctx:n}=this._processInputParams(e);if(n.common.async)return(async()=>{let o=await this._def.in._parseAsync({data:n.data,path:n.path,parent:n});return o.status==="aborted"?_:o.status==="dirty"?(t.dirty(),Ke(o.value)):this._def.out._parseAsync({data:o.value,path:n.path,parent:n})})();{let i=this._def.in._parseSync({data:n.data,path:n.path,parent:n});return i.status==="aborted"?_:i.status==="dirty"?(t.dirty(),{status:"dirty",value:i.value}):this._def.out._parseSync({data:i.value,path:n.path,parent:n})}}static create(e,t){return new r({in:e,out:t,typeName:g.ZodPipeline})}},Le=class extends x{_parse(e){let t=this._def.innerType._parse(e),n=i=>(Se(i)&&(i.value=Object.freeze(i.value)),i);return yt(t)?t.then(i=>n(i)):n(t)}unwrap(){return this._def.innerType}};Le.create=(r,e)=>new Le({innerType:r,typeName:g.ZodReadonly,...b(e)});function Bn(r,e){let t=typeof r=="function"?r(e):typeof r=="string"?{message:r}:r;return typeof t=="string"?{message:t}:t}function Xn(r,e={},t){return r?fe.create().superRefine((n,i)=>{var o,s;let c=r(n);if(c instanceof Promise)return c.then(l=>{var d,u;if(!l){let p=Bn(e,n),w=(u=(d=p.fatal)!==null&&d!==void 0?d:t)!==null&&u!==void 0?u:!0;i.addIssue({code:"custom",...p,fatal:w})}});if(!c){let l=Bn(e,n),d=(s=(o=l.fatal)!==null&&o!==void 0?o:t)!==null&&s!==void 0?s:!0;i.addIssue({code:"custom",...l,fatal:d})}}):fe.create()}var zo={object:M.lazycreate},g;(function(r){r.ZodString="ZodString",r.ZodNumber="ZodNumber",r.ZodNaN="ZodNaN",r.ZodBigInt="ZodBigInt",r.ZodBoolean="ZodBoolean",r.ZodDate="ZodDate",r.ZodSymbol="ZodSymbol",r.ZodUndefined="ZodUndefined",r.ZodNull="ZodNull",r.ZodAny="ZodAny",r.ZodUnknown="ZodUnknown",r.ZodNever="ZodNever",r.ZodVoid="ZodVoid",r.ZodArray="ZodArray",r.ZodObject="ZodObject",r.ZodUnion="ZodUnion",r.ZodDiscriminatedUnion="ZodDiscriminatedUnion",r.ZodIntersection="ZodIntersection",r.ZodTuple="ZodTuple",r.ZodRecord="ZodRecord",r.ZodMap="ZodMap",r.ZodSet="ZodSet",r.ZodFunction="ZodFunction",r.ZodLazy="ZodLazy",r.ZodLiteral="ZodLiteral",r.ZodEnum="ZodEnum",r.ZodEffects="ZodEffects",r.ZodNativeEnum="ZodNativeEnum",r.ZodOptional="ZodOptional",r.ZodNullable="ZodNullable",r.ZodDefault="ZodDefault",r.ZodCatch="ZodCatch",r.ZodPromise="ZodPromise",r.ZodBranded="ZodBranded",r.ZodPipeline="ZodPipeline",r.ZodReadonly="ZodReadonly"})(g||(g={}));var Zo=(r,e={message:`Input not instance of ${r.name}`})=>Xn(t=>t instanceof r,e),Qn=ue.create,ei=ke.create,Fo=nt.create,Vo=Te.create,ti=Ee.create,Bo=Ae.create,Wo=Qe.create,Ho=Oe.create,qo=Ce.create,Go=fe.create,Yo=oe.create,Jo=J.create,Ko=et.create,Xo=se.create,Qo=M.create,es=M.strictCreate,ts=$e.create,rs=ir.create,ns=je.create,is=ee.create,os=or.create,ss=tt.create,as=rt.create,cs=sr.create,ls=Ie.create,ds=Re.create,us=Pe.create,fs=De.create,ps=pe.create,Wn=Z.create,hs=V.create,ms=te.create,vs=Z.createWithPreprocess,ys=_t.create,gs=()=>Qn().optional(),_s=()=>ei().optional(),bs=()=>ti().optional(),xs={string:(r=>ue.create({...r,coerce:!0})),number:(r=>ke.create({...r,coerce:!0})),boolean:(r=>Ee.create({...r,coerce:!0})),bigint:(r=>Te.create({...r,coerce:!0})),date:(r=>Ae.create({...r,coerce:!0}))},ws=_,a=Object.freeze({__proto__:null,defaultErrorMap:Xe,setErrorMap:vo,getErrorMap:tr,makeIssue:rr,EMPTY_PATH:yo,addIssueToContext:h,ParseStatus:P,INVALID:_,DIRTY:Ke,OK:D,isAborted:Vr,isDirty:Br,isValid:Se,isAsync:yt,get util(){return T},get objectUtil(){return Fr},ZodParsedType:m,getParsedType:ie,ZodType:x,datetimeRegex:Jn,ZodString:ue,ZodNumber:ke,ZodBigInt:Te,ZodBoolean:Ee,ZodDate:Ae,ZodSymbol:Qe,ZodUndefined:Oe,ZodNull:Ce,ZodAny:fe,ZodUnknown:oe,ZodNever:J,ZodVoid:et,ZodArray:se,ZodObject:M,ZodUnion:$e,ZodDiscriminatedUnion:ir,ZodIntersection:je,ZodTuple:ee,ZodRecord:or,ZodMap:tt,ZodSet:rt,ZodFunction:sr,ZodLazy:Ie,ZodLiteral:Re,ZodEnum:Pe,ZodNativeEnum:De,ZodPromise:pe,ZodEffects:Z,ZodTransformer:Z,ZodOptional:V,ZodNullable:te,ZodDefault:Me,ZodCatch:Ne,ZodNaN:nt,BRAND:Uo,ZodBranded:gt,ZodPipeline:_t,ZodReadonly:Le,custom:Xn,Schema:x,ZodSchema:x,late:zo,get ZodFirstPartyTypeKind(){return g},coerce:xs,any:Go,array:Xo,bigint:Vo,boolean:ti,date:Bo,discriminatedUnion:rs,effect:Wn,enum:us,function:cs,instanceof:Zo,intersection:ns,lazy:ls,literal:ds,map:ss,nan:Fo,nativeEnum:fs,never:Jo,null:qo,nullable:ms,number:ei,object:Qo,oboolean:bs,onumber:_s,optional:hs,ostring:gs,pipeline:ys,preprocess:vs,promise:ps,record:os,set:as,strictObject:es,string:Qn,symbol:Wo,transformer:Wn,tuple:is,undefined:Ho,union:ts,unknown:Yo,void:Ko,NEVER:ws,ZodIssueCode:f,quotelessJson:mo,ZodError:z});var oi=(r=>(r.Info="info",r.Debug="debug",r.Trace="trace",r.Error="error",r))(oi||{}),si=(r=>(r.Changed="Changed",r.Added="Added",r.Removed="Removed",r))(si||{}),ai=(r=>(r.External="BSLIVE_EXTERNAL",r))(ai||{}),Ss=a.string(),bt=a.lazy(()=>a.object({id:a.string(),label:a.string(),nodes:a.array(bt)})),ks=a.nativeEnum(oi),ri=a.object({log_level:ks}),Ts=a.object({ws_path:a.string(),host:a.string().optional()}),Es=a.object({kind:a.string(),ms:a.string()}),As=a.object({message:a.string(),reason:a.string().optional()}),ni=a.object({path:a.string()}),Os=a.object({paths:a.array(a.string())}),it=a.discriminatedUnion("kind",[a.object({kind:a.literal("Both"),payload:a.object({name:a.string(),bind_address:a.string()})}),a.object({kind:a.literal("Address"),payload:a.object({bind_address:a.string()})}),a.object({kind:a.literal("Named"),payload:a.object({name:a.string()})}),a.object({kind:a.literal("Port"),payload:a.object({port:a.number()})}),a.object({kind:a.literal("PortNamed"),payload:a.object({port:a.number(),name:a.string()})})]),Cs=a.object({id:a.string(),identity:it,socket_addr:a.string()}),$s=a.object({servers:a.array(Cs)}),ci=a.object({connect:Ts,ctx_message:a.string()}),js=a.object({path:a.string()}),Is=a.object({error:a.string()}),Rs=a.object({body:a.string()}),Ps=a.discriminatedUnion("kind",[a.object({kind:a.literal("Html"),payload:a.object({html:a.string()})}),a.object({kind:a.literal("Json"),payload:a.object({json_str:a.string()})}),a.object({kind:a.literal("Raw"),payload:a.object({raw:a.string()})}),a.object({kind:a.literal("Sse"),payload:a.object({sse:Rs})}),a.object({kind:a.literal("Proxy"),payload:a.object({proxy:a.string()})}),a.object({kind:a.literal("Dir"),payload:a.object({dir:a.string(),base:a.string().optional()})})]),ii=a.object({path:a.string(),kind_str:a.string()}),Ds=a.discriminatedUnion("kind",[a.object({kind:a.literal("Stopped"),payload:a.object({bind_address:a.string()})}),a.object({kind:a.literal("Started"),payload:a.undefined().optional()}),a.object({kind:a.literal("Patched"),payload:a.undefined().optional()}),a.object({kind:a.literal("Errored"),payload:a.object({error:a.string()})})]),Ms=a.object({identity:it,change:Ds}),tf=a.object({items:a.array(Ms)}),Ns=a.discriminatedUnion("kind",[a.object({kind:a.literal("Created"),payload:a.object({identity:it,socket_addr:a.string()})}),a.object({kind:a.literal("Stopped"),payload:a.object({identity:it})}),a.object({kind:a.literal("CreateErr"),payload:a.object({error:a.string()})}),a.object({kind:a.literal("Patched"),payload:a.object({identity:it,added:a.array(ii),changed:a.array(ii)})}),a.object({kind:a.literal("PatchErr"),payload:a.object({identity:it,error:a.string()})})]),Ls=a.object({changeset:a.array(Ns),servers_resp:$s}),Us=a.object({path:a.string(),kind:Ps}),zs=a.object({error:a.string()}),Zs=a.object({line:a.string(),prefix:a.string().optional()}),Fs=a.object({line:a.string(),prefix:a.string().optional()}),Vs=a.object({paths:a.array(a.string())}),Bs=a.union([a.object({kind:a.literal("Ok"),payload:a.undefined().optional()}),a.object({kind:a.literal("Err"),payload:a.string()}),a.object({kind:a.literal("Cancelled"),payload:a.undefined().optional()})]),Ws=a.object({tree:bt,will_exec:a.boolean()}),Hs=a.object({paths:a.array(a.string()),debounce:Es}),qs=a.nativeEnum(si),cr=a.lazy(()=>a.discriminatedUnion("kind",[a.object({kind:a.literal("Fs"),payload:a.object({path:a.string(),change_kind:qs})}),a.object({kind:a.literal("FsMany"),payload:a.array(cr)})])),rf=a.discriminatedUnion("kind",[a.object({kind:a.literal("Change"),payload:cr}),a.object({kind:a.literal("WsConnection"),payload:ri}),a.object({kind:a.literal("Config"),payload:ri}),a.object({kind:a.literal("DisplayMessage"),payload:As})]),nf=a.nativeEnum(ai),Gs=a.discriminatedUnion("kind",[a.object({kind:a.literal("Stdout"),payload:Fs}),a.object({kind:a.literal("Stderr"),payload:Zs})]),of=a.discriminatedUnion("kind",[a.object({kind:a.literal("MissingInputs"),payload:a.string()}),a.object({kind:a.literal("InvalidInput"),payload:a.string()}),a.object({kind:a.literal("NotFound"),payload:a.string()}),a.object({kind:a.literal("InputWriteError"),payload:a.string()}),a.object({kind:a.literal("PathError"),payload:a.string()}),a.object({kind:a.literal("PortError"),payload:a.string()}),a.object({kind:a.literal("DirError"),payload:a.string()}),a.object({kind:a.literal("YamlError"),payload:a.string()}),a.object({kind:a.literal("MarkdownError"),payload:a.string()}),a.object({kind:a.literal("HtmlError"),payload:a.string()}),a.object({kind:a.literal("Io"),payload:a.string()}),a.object({kind:a.literal("UnsupportedExtension"),payload:a.string()}),a.object({kind:a.literal("MissingExtension"),payload:a.string()}),a.object({kind:a.literal("EmptyInput"),payload:a.string()}),a.object({kind:a.literal("BsLiveRules"),payload:a.string()})]),sf=a.discriminatedUnion("kind",[a.object({kind:a.literal("Started"),payload:a.undefined().optional()}),a.object({kind:a.literal("FailedStartup"),payload:a.string()})]),af=a.object({routes:a.array(Us),id:a.string()}),Ys=a.lazy(()=>a.discriminatedUnion("kind",[a.object({kind:a.literal("Started"),payload:a.object({tree:bt})}),a.object({kind:a.literal("Ended"),payload:a.object({tree:bt,report:ar,report_map:a.record(ar)})}),a.object({kind:a.literal("Error"),payload:a.undefined().optional()})])),ar=a.lazy(()=>a.object({result:Ks})),Js=a.lazy(()=>a.object({stage:Ys})),Ks=a.lazy(()=>a.object({conclusion:Bs,invocation_id:Ss,task_reports:a.array(ar)})),Xs=a.lazy(()=>a.object({tree:bt,report_map:a.record(ar)})),cf=a.lazy(()=>a.discriminatedUnion("kind",[a.object({kind:a.literal("FileChanged"),payload:ni}),a.object({kind:a.literal("FilesChanged"),payload:Os}),a.object({kind:a.literal("OutputLine"),payload:Gs}),a.object({kind:a.literal("InputFileChanged"),payload:ni}),a.object({kind:a.literal("InputAccepted"),payload:js}),a.object({kind:a.literal("InputError"),payload:Is}),a.object({kind:a.literal("StartupError"),payload:zs}),a.object({kind:a.literal("ServerChangeset"),payload:Ls}),a.object({kind:a.literal("TaskAction"),payload:Js}),a.object({kind:a.literal("TaskTreePreview"),payload:Ws}),a.object({kind:a.literal("TaskTreeSummary"),payload:Xs}),a.object({kind:a.literal("Watching"),payload:Hs}),a.object({kind:a.literal("WatchingStopped"),payload:Vs})]));var li=[{selector:"background",styleNames:["backgroundImage"]},{selector:"border",styleNames:["borderImage","webkitBorderImage","MozBorderImage"]}],lr={stylesheetReloadTimeout:15e3},Qs=/\.(jpe?g|png|gif|svg)$/i,dr=class{constructor(e,t,n){this.window=e,this.console=t,this.Timer=n,this.document=this.window.document,this.importCacheWaitPeriod=200,this.plugins=[]}addPlugin(e){return this.plugins.push(e)}analyze(e){}reload(e,t={}){if(this.options={...lr,...t},!(t.liveCSS&&e.match(/\.css(?:\.map)?$/i)&&this.reloadStylesheet(e))){if(t.liveImg&&e.match(Qs)){this.reloadImages(e);return}if(t.isChromeExtension){this.reloadChromeExtension();return}return this.reloadPage()}}reloadPage(){return this.window.document.location.reload()}reloadChromeExtension(){return this.window.chrome.runtime.reload()}reloadImages(e){let t,n=this.generateUniqueString();for(t of Array.from(this.document.images))di(e,Hr(t.src))&&(t.src=this.generateCacheBustUrl(t.src,n));if(this.document.querySelectorAll)for(let{selector:i,styleNames:o}of li)for(t of Array.from(this.document.querySelectorAll(`[style*=${i}]`)))this.reloadStyleImages(t.style,o,e,n);if(this.document.styleSheets)return Array.from(this.document.styleSheets).map(i=>this.reloadStylesheetImages(i,e,n))}reloadStylesheetImages(e,t,n){let i;try{i=(e||{}).cssRules}catch{}if(i)for(let o of Array.from(i))switch(o.type){case CSSRule.IMPORT_RULE:this.reloadStylesheetImages(o.styleSheet,t,n);break;case CSSRule.STYLE_RULE:for(let{styleNames:s}of li)this.reloadStyleImages(o.style,s,t,n);break;case CSSRule.MEDIA_RULE:this.reloadStylesheetImages(o,t,n);break}}reloadStyleImages(e,t,n,i){for(let o of t){let s=e[o];if(typeof s=="string"){let c=s.replace(new RegExp("\\burl\\s*\\(([^)]*)\\)"),(l,d)=>di(n,Hr(d))?`url(${this.generateCacheBustUrl(d,i)})`:l);c!==s&&(e[o]=c)}}}reloadStylesheet(e){let t=this.options||lr,n,i,o=(()=>{let l=[];for(i of Array.from(this.document.getElementsByTagName("link")))i.rel.match(/^stylesheet$/i)&&!i.__LiveReload_pendingRemoval&&l.push(i);return l})(),s=[];for(n of Array.from(this.document.getElementsByTagName("style")))n.sheet&&this.collectImportedStylesheets(n,n.sheet,s);for(i of Array.from(o))this.collectImportedStylesheets(i,i.sheet,s);if(this.window.StyleFix&&this.document.querySelectorAll)for(n of Array.from(this.document.querySelectorAll("style[data-href]")))o.push(n);this.console.debug(`found ${o.length} LINKed stylesheets, ${s.length} @imported stylesheets`);let c=ea(e,o.concat(s),l=>Hr(this.linkHref(l)));if(c)c.object.rule?(this.console.debug(`is reloading imported stylesheet: ${c.object.href}`),this.reattachImportedRule(c.object)):(this.console.debug(`is reloading stylesheet: ${this.linkHref(c.object)}`),this.reattachStylesheetLink(c.object));else if(t.reloadMissingCSS){this.console.debug(`will reload all stylesheets because path '${e}' did not match any specific one. To disable this behavior, set 'options.reloadMissingCSS' to 'false'.`);for(i of Array.from(o))this.reattachStylesheetLink(i)}else this.console.debug(`will not reload path '${e}' because the stylesheet was not found on the page and 'options.reloadMissingCSS' was set to 'false'.`);return!0}collectImportedStylesheets(e,t,n){let i;try{i=(t||{}).cssRules}catch{}if(i&&i.length)for(let o=0;o{if(!i)return i=!0,t()};if(e.onload=()=>(this.console.debug("the new stylesheet has finished loading"),this.knownToSupportCssOnLoad=!0,o()),!this.knownToSupportCssOnLoad){let s;(s=()=>e.sheet?(this.console.debug("is polling until the new CSS finishes loading..."),o()):this.Timer.start(50,s))()}return this.Timer.start(n.stylesheetReloadTimeout,o)}linkHref(e){return e.href||e.getAttribute&&e.getAttribute("data-href")}reattachStylesheetLink(e){let t;if(e.__LiveReload_pendingRemoval)return;e.__LiveReload_pendingRemoval=!0,e.tagName==="STYLE"?(t=this.document.createElement("link"),t.rel="stylesheet",t.media=e.media,t.disabled=e.disabled):t=e.cloneNode(!1),t.href=this.generateCacheBustUrl(this.linkHref(e));let n=e.parentNode;return n.lastChild===e?n.appendChild(t):n.insertBefore(t,e.nextSibling),this.waitUntilCssLoads(t,()=>{let i;return/AppleWebKit/.test(this.window.navigator.userAgent)?i=5:i=200,this.Timer.start(i,()=>{if(e.parentNode)return e.parentNode.removeChild(e),t.onreadystatechange=null,this.window.StyleFix?this.window.StyleFix.link(t):void 0})})}reattachImportedRule({rule:e,index:t,link:n}){let i=e.parentStyleSheet,o=this.generateCacheBustUrl(e.href),s=e.media.length?[].join.call(e.media,", "):"",c=`@import url("${o}") ${s};`;e.__LiveReload_newHref=o;let l=this.document.createElement("link");return l.rel="stylesheet",l.href=o,l.__LiveReload_pendingRemoval=!0,n.parentNode&&n.parentNode.insertBefore(l,n),this.Timer.start(this.importCacheWaitPeriod,()=>{if(l.parentNode&&l.parentNode.removeChild(l),e.__LiveReload_newHref===o)return i.insertRule(c,t),i.deleteRule(t+1),e=i.cssRules[t],e.__LiveReload_newHref=o,this.Timer.start(this.importCacheWaitPeriod,()=>{if(e.__LiveReload_newHref===o)return i.insertRule(c,t),i.deleteRule(t+1)})})}generateUniqueString(){return`livereload=${Date.now()}`}generateCacheBustUrl(e,t){let n=this.options||lr,i,o;if(t||(t=this.generateUniqueString()),{url:e,hash:i,params:o}=ui(e),n.overrideURL&&e.indexOf(n.serverURL)<0){let c=e;e=n.serverURL+n.overrideURL+"?url="+encodeURIComponent(e),this.console.debug(`is overriding source URL ${c} with ${e}`)}let s=o.replace(/(\?|&)livereload=(\d+)/,(c,l)=>`${l}${t}`);return s===o&&(o.length===0?s=`?${t}`:s=`${o}&${t}`),e+s+i}};function ui(r){let e="",t="",n=r.indexOf("#");n>=0&&(e=r.slice(n),r=r.slice(0,n));let i=r.indexOf("??");return i>=0?i+1!==r.lastIndexOf("?")&&(n=r.lastIndexOf("?")):n=r.indexOf("?"),n>=0&&(t=r.slice(n),r=r.slice(0,n)),{url:r,params:t,hash:e}}function Hr(r){if(!r)return"";let e;return{url:r}=ui(r),r.indexOf("file://")===0?e=r.replace(new RegExp("^file://(localhost)?"),""):e=r.replace(new RegExp("^([^:]+:)?//([^:/]+)(:\\d*)?/"),"/"),decodeURIComponent(e)}function fi(r,e){if(r=r.replace(/^\/+/,"").toLowerCase(),e=e.replace(/^\/+/,"").toLowerCase(),r===e)return 1e4;let t=r.split(/\/|\\/).reverse(),n=e.split(/\/|\\/).reverse(),i=Math.min(t.length,n.length),o=0;for(;on){let n,i={score:0};for(let o of e)n=fi(r,t(o)),n>i.score&&(i={object:o,score:n});return i.score===0?null:i}function di(r,e){return fi(r,e)>0}var mi=Yi(hi(),1);var ta=/\.(jpe?g|png|gif|svg)$/i;function qr(r,e,t){switch(r.kind){case"FsMany":{if(r.payload.some(i=>{switch(i.kind){case"Fs":return!(i.payload.path.match(/\.css(?:\.map)?$/i)||i.payload.path.match(ta));case"FsMany":throw new Error("unreachable")}}))return window.__playwright?.record?window.__playwright?.record({kind:"reloadPage"}):t.reloadPage();for(let i of r.payload)qr(i,e,t);break}case"Fs":{let n=r.payload.path,i={liveCSS:!0,liveImg:!0,reloadMissingCSS:!0,originalPath:"",overrideURL:"",serverURL:""};window.__playwright?.record?window.__playwright?.record({kind:"reload",args:{path:n,opts:i}}):(e.trace("will reload a file with path ",n),t.reload(n,i))}}}var Gr={name:"dom plugin",globalSetup:(r,e)=>{let t=new dr(window,e,mi.Timer);return[r,[e,t]]},resetSink(r,e,t){let[n,i]=e;return r.pipe(de(o=>o.kind==="Change"),Q(o=>o.payload),we(o=>{n.trace("incoming message",JSON.stringify({change:o,config:t},null,2));let s=cr.parse(o);qr(s,n,i)}),xe())}};var fr=globalThis,pr=fr.ShadowRoot&&(fr.ShadyCSS===void 0||fr.ShadyCSS.nativeShadow)&&"adoptedStyleSheets"in Document.prototype&&"replace"in CSSStyleSheet.prototype,Yr=Symbol(),vi=new WeakMap,xt=class{constructor(e,t,n){if(this._$cssResult$=!0,n!==Yr)throw Error("CSSResult is not constructable. Use `unsafeCSS` or `css` instead.");this.cssText=e,this.t=t}get styleSheet(){let e=this.o,t=this.t;if(pr&&e===void 0){let n=t!==void 0&&t.length===1;n&&(e=vi.get(t)),e===void 0&&((this.o=e=new CSSStyleSheet).replaceSync(this.cssText),n&&vi.set(t,e))}return e}toString(){return this.cssText}},yi=r=>new xt(typeof r=="string"?r:r+"",void 0,Yr),K=(r,...e)=>{let t=r.length===1?r[0]:e.reduce((n,i,o)=>n+(s=>{if(s._$cssResult$===!0)return s.cssText;if(typeof s=="number")return s;throw Error("Value passed to 'css' function must be a 'css' function result: "+s+". Use 'unsafeCSS' to pass non-literal values, but take care to ensure page security.")})(i)+r[o+1],r[0]);return new xt(t,r,Yr)},gi=(r,e)=>{if(pr)r.adoptedStyleSheets=e.map(t=>t instanceof CSSStyleSheet?t:t.styleSheet);else for(let t of e){let n=document.createElement("style"),i=fr.litNonce;i!==void 0&&n.setAttribute("nonce",i),n.textContent=t.cssText,r.appendChild(n)}},Jr=pr?r=>r:r=>r instanceof CSSStyleSheet?(e=>{let t="";for(let n of e.cssRules)t+=n.cssText;return yi(t)})(r):r;var{is:ra,defineProperty:na,getOwnPropertyDescriptor:ia,getOwnPropertyNames:oa,getOwnPropertySymbols:sa,getPrototypeOf:aa}=Object,hr=globalThis,_i=hr.trustedTypes,ca=_i?_i.emptyScript:"",la=hr.reactiveElementPolyfillSupport,wt=(r,e)=>r,St={toAttribute(r,e){switch(e){case Boolean:r=r?ca:null;break;case Object:case Array:r=r==null?r:JSON.stringify(r)}return r},fromAttribute(r,e){let t=r;switch(e){case Boolean:t=r!==null;break;case Number:t=r===null?null:Number(r);break;case Object:case Array:try{t=JSON.parse(r)}catch{t=null}}return t}},mr=(r,e)=>!ra(r,e),bi={attribute:!0,type:String,converter:St,reflect:!1,useDefault:!1,hasChanged:mr};Symbol.metadata??=Symbol("metadata"),hr.litPropertyMetadata??=new WeakMap;var ae=class extends HTMLElement{static addInitializer(e){this._$Ei(),(this.l??=[]).push(e)}static get observedAttributes(){return this.finalize(),this._$Eh&&[...this._$Eh.keys()]}static createProperty(e,t=bi){if(t.state&&(t.attribute=!1),this._$Ei(),this.prototype.hasOwnProperty(e)&&((t=Object.create(t)).wrapped=!0),this.elementProperties.set(e,t),!t.noAccessor){let n=Symbol(),i=this.getPropertyDescriptor(e,n,t);i!==void 0&&na(this.prototype,e,i)}}static getPropertyDescriptor(e,t,n){let{get:i,set:o}=ia(this.prototype,e)??{get(){return this[t]},set(s){this[t]=s}};return{get:i,set(s){let c=i?.call(this);o?.call(this,s),this.requestUpdate(e,c,n)},configurable:!0,enumerable:!0}}static getPropertyOptions(e){return this.elementProperties.get(e)??bi}static _$Ei(){if(this.hasOwnProperty(wt("elementProperties")))return;let e=aa(this);e.finalize(),e.l!==void 0&&(this.l=[...e.l]),this.elementProperties=new Map(e.elementProperties)}static finalize(){if(this.hasOwnProperty(wt("finalized")))return;if(this.finalized=!0,this._$Ei(),this.hasOwnProperty(wt("properties"))){let t=this.properties,n=[...oa(t),...sa(t)];for(let i of n)this.createProperty(i,t[i])}let e=this[Symbol.metadata];if(e!==null){let t=litPropertyMetadata.get(e);if(t!==void 0)for(let[n,i]of t)this.elementProperties.set(n,i)}this._$Eh=new Map;for(let[t,n]of this.elementProperties){let i=this._$Eu(t,n);i!==void 0&&this._$Eh.set(i,t)}this.elementStyles=this.finalizeStyles(this.styles)}static finalizeStyles(e){let t=[];if(Array.isArray(e)){let n=new Set(e.flat(1/0).reverse());for(let i of n)t.unshift(Jr(i))}else e!==void 0&&t.push(Jr(e));return t}static _$Eu(e,t){let n=t.attribute;return n===!1?void 0:typeof n=="string"?n:typeof e=="string"?e.toLowerCase():void 0}constructor(){super(),this._$Ep=void 0,this.isUpdatePending=!1,this.hasUpdated=!1,this._$Em=null,this._$Ev()}_$Ev(){this._$ES=new Promise(e=>this.enableUpdating=e),this._$AL=new Map,this._$E_(),this.requestUpdate(),this.constructor.l?.forEach(e=>e(this))}addController(e){(this._$EO??=new Set).add(e),this.renderRoot!==void 0&&this.isConnected&&e.hostConnected?.()}removeController(e){this._$EO?.delete(e)}_$E_(){let e=new Map,t=this.constructor.elementProperties;for(let n of t.keys())this.hasOwnProperty(n)&&(e.set(n,this[n]),delete this[n]);e.size>0&&(this._$Ep=e)}createRenderRoot(){let e=this.shadowRoot??this.attachShadow(this.constructor.shadowRootOptions);return gi(e,this.constructor.elementStyles),e}connectedCallback(){this.renderRoot??=this.createRenderRoot(),this.enableUpdating(!0),this._$EO?.forEach(e=>e.hostConnected?.())}enableUpdating(e){}disconnectedCallback(){this._$EO?.forEach(e=>e.hostDisconnected?.())}attributeChangedCallback(e,t,n){this._$AK(e,n)}_$ET(e,t){let n=this.constructor.elementProperties.get(e),i=this.constructor._$Eu(e,n);if(i!==void 0&&n.reflect===!0){let o=(n.converter?.toAttribute!==void 0?n.converter:St).toAttribute(t,n.type);this._$Em=e,o==null?this.removeAttribute(i):this.setAttribute(i,o),this._$Em=null}}_$AK(e,t){let n=this.constructor,i=n._$Eh.get(e);if(i!==void 0&&this._$Em!==i){let o=n.getPropertyOptions(i),s=typeof o.converter=="function"?{fromAttribute:o.converter}:o.converter?.fromAttribute!==void 0?o.converter:St;this._$Em=i;let c=s.fromAttribute(t,o.type);this[i]=c??this._$Ej?.get(i)??c,this._$Em=null}}requestUpdate(e,t,n,i=!1,o){if(e!==void 0){let s=this.constructor;if(i===!1&&(o=this[e]),n??=s.getPropertyOptions(e),!((n.hasChanged??mr)(o,t)||n.useDefault&&n.reflect&&o===this._$Ej?.get(e)&&!this.hasAttribute(s._$Eu(e,n))))return;this.C(e,t,n)}this.isUpdatePending===!1&&(this._$ES=this._$EP())}C(e,t,{useDefault:n,reflect:i,wrapped:o},s){n&&!(this._$Ej??=new Map).has(e)&&(this._$Ej.set(e,s??t??this[e]),o!==!0||s!==void 0)||(this._$AL.has(e)||(this.hasUpdated||n||(t=void 0),this._$AL.set(e,t)),i===!0&&this._$Em!==e&&(this._$Eq??=new Set).add(e))}async _$EP(){this.isUpdatePending=!0;try{await this._$ES}catch(t){Promise.reject(t)}let e=this.scheduleUpdate();return e!=null&&await e,!this.isUpdatePending}scheduleUpdate(){return this.performUpdate()}performUpdate(){if(!this.isUpdatePending)return;if(!this.hasUpdated){if(this.renderRoot??=this.createRenderRoot(),this._$Ep){for(let[i,o]of this._$Ep)this[i]=o;this._$Ep=void 0}let n=this.constructor.elementProperties;if(n.size>0)for(let[i,o]of n){let{wrapped:s}=o,c=this[i];s!==!0||this._$AL.has(i)||c===void 0||this.C(i,void 0,o,c)}}let e=!1,t=this._$AL;try{e=this.shouldUpdate(t),e?(this.willUpdate(t),this._$EO?.forEach(n=>n.hostUpdate?.()),this.update(t)):this._$EM()}catch(n){throw e=!1,this._$EM(),n}e&&this._$AE(t)}willUpdate(e){}_$AE(e){this._$EO?.forEach(t=>t.hostUpdated?.()),this.hasUpdated||(this.hasUpdated=!0,this.firstUpdated(e)),this.updated(e)}_$EM(){this._$AL=new Map,this.isUpdatePending=!1}get updateComplete(){return this.getUpdateComplete()}getUpdateComplete(){return this._$ES}shouldUpdate(e){return!0}update(e){this._$Eq&&=this._$Eq.forEach(t=>this._$ET(t,this[t])),this._$EM()}updated(e){}firstUpdated(e){}};ae.elementStyles=[],ae.shadowRootOptions={mode:"open"},ae[wt("elementProperties")]=new Map,ae[wt("finalized")]=new Map,la?.({ReactiveElement:ae}),(hr.reactiveElementVersions??=[]).push("2.1.2");var Xr=globalThis,xi=r=>r,vr=Xr.trustedTypes,wi=vr?vr.createPolicy("lit-html",{createHTML:r=>r}):void 0,Qr="$lit$",ce=`lit$${Math.random().toFixed(9).slice(2)}$`,en="?"+ce,da=`<${en}>`,Ze=document,Tt=()=>Ze.createComment(""),Et=r=>r===null||typeof r!="object"&&typeof r!="function",tn=Array.isArray,Oi=r=>tn(r)||typeof r?.[Symbol.iterator]=="function",Kr=`[ -\f\r]`,kt=/<(?:(!--|\/[^a-zA-Z])|(\/?[a-zA-Z][^>\s]*)|(\/?$))/g,Si=/-->/g,ki=/>/g,Ue=RegExp(`>|${Kr}(?:([^\\s"'>=/]+)(${Kr}*=${Kr}*(?:[^ -\f\r"'\`<>=]|("|')|))|$)`,"g"),Ti=/'/g,Ei=/"/g,Ci=/^(?:script|style|textarea|title)$/i,rn=r=>(e,...t)=>({_$litType$:r,strings:e,values:t}),N=rn(1),Sf=rn(2),kf=rn(3),Fe=Symbol.for("lit-noChange"),O=Symbol.for("lit-nothing"),Ai=new WeakMap,ze=Ze.createTreeWalker(Ze,129);function $i(r,e){if(!tn(r)||!r.hasOwnProperty("raw"))throw Error("invalid template strings array");return wi!==void 0?wi.createHTML(e):e}var ji=(r,e)=>{let t=r.length-1,n=[],i,o=e===2?"":e===3?"":"",s=kt;for(let c=0;c"?(s=i??kt,p=-1):u[1]===void 0?p=-2:(p=s.lastIndex-u[2].length,d=u[1],s=u[3]===void 0?Ue:u[3]==='"'?Ei:Ti):s===Ei||s===Ti?s=Ue:s===Si||s===ki?s=kt:(s=Ue,i=void 0);let y=s===Ue&&r[c+1].startsWith("/>")?" ":"";o+=s===kt?l+da:p>=0?(n.push(d),l.slice(0,p)+Qr+l.slice(p)+ce+y):l+ce+(p===-2?c:y)}return[$i(r,o+(r[t]||"")+(e===2?"":e===3?"":"")),n]},At=class r{constructor({strings:e,_$litType$:t},n){let i;this.parts=[];let o=0,s=0,c=e.length-1,l=this.parts,[d,u]=ji(e,t);if(this.el=r.createElement(d,n),ze.currentNode=this.el.content,t===2||t===3){let p=this.el.content.firstChild;p.replaceWith(...p.childNodes)}for(;(i=ze.nextNode())!==null&&l.length0){i.textContent=vr?vr.emptyScript:"";for(let y=0;y2||n[0]!==""||n[1]!==""?(this._$AH=Array(n.length-1).fill(new String),this.strings=n):this._$AH=O}_$AI(e,t=this,n,i){let o=this.strings,s=!1;if(o===void 0)e=Ve(this,e,t,0),s=!Et(e)||e!==this._$AH&&e!==Fe,s&&(this._$AH=e);else{let c=e,l,d;for(e=o[0],l=0;l{let n=t?.renderBefore??e,i=n._$litPart$;if(i===void 0){let o=t?.renderBefore??null;n._$litPart$=i=new ot(e.insertBefore(Tt(),o),o,void 0,t??{})}return i._$AI(r),i};var nn=globalThis,L=class extends ae{constructor(){super(...arguments),this.renderOptions={host:this},this._$Do=void 0}createRenderRoot(){let e=super.createRenderRoot();return this.renderOptions.renderBefore??=e.firstChild,e}update(e){let t=this.render();this.hasUpdated||(this.renderOptions.isConnected=this.isConnected),super.update(e),this._$Do=wr(t,this.renderRoot,this.renderOptions)}connectedCallback(){super.connectedCallback(),this._$Do?.setConnected(!0)}disconnectedCallback(){super.disconnectedCallback(),this._$Do?.setConnected(!1)}render(){return Fe}};L._$litElement$=!0,L.finalized=!0,nn.litElementHydrateSupport?.({LitElement:L});var fa=nn.litElementPolyfillSupport;fa?.({LitElement:L});(nn.litElementVersions??=[]).push("4.2.2");var st=r=>(e,t)=>{t!==void 0?t.addInitializer(()=>{customElements.define(r,e)}):customElements.define(r,e)};var pa={attribute:!0,type:String,converter:St,reflect:!1,hasChanged:mr},ha=(r=pa,e,t)=>{let{kind:n,metadata:i}=t,o=globalThis.litPropertyMetadata.get(i);if(o===void 0&&globalThis.litPropertyMetadata.set(i,o=new Map),n==="setter"&&((r=Object.create(r)).wrapped=!0),o.set(t.name,r),n==="accessor"){let{name:s}=t;return{set(c){let l=e.get.call(this);e.set.call(this,c),this.requestUpdate(s,l,r,!0,c)},init(c){return c!==void 0&&this.C(s,void 0,r,c),c}}}if(n==="setter"){let{name:s}=t;return function(c){let l=this[s];e.call(this,c),this.requestUpdate(s,l,r,!0,c)}}throw Error("Unsupported decorator location: "+n)};function he(r){return(e,t)=>typeof t=="object"?ha(r,e,t):((n,i,o)=>{let s=i.hasOwnProperty(o);return i.constructor.createProperty(o,n),s?Object.getOwnPropertyDescriptor(i,o):void 0})(r,e,t)}var{I:up}=Ii;var Ri=r=>r.strings===void 0;var Pi={ATTRIBUTE:1,CHILD:2,PROPERTY:3,BOOLEAN_ATTRIBUTE:4,EVENT:5,ELEMENT:6},on=r=>(...e)=>({_$litDirective$:r,values:e}),kr=class{constructor(e){}get _$AU(){return this._$AM._$AU}_$AT(e,t,n){this._$Ct=e,this._$AM=t,this._$Ci=n}_$AS(e,t){return this.update(e,t)}update(e,t){return this.render(...t)}};var Ot=(r,e)=>{let t=r._$AN;if(t===void 0)return!1;for(let n of t)n._$AO?.(e,!1),Ot(n,e);return!0},Tr=r=>{let e,t;do{if((e=r._$AM)===void 0)break;t=e._$AN,t.delete(r),r=e}while(t?.size===0)},Di=r=>{for(let e;e=r._$AM;r=e){let t=e._$AN;if(t===void 0)e._$AN=t=new Set;else if(t.has(r))break;t.add(r),ya(e)}};function ma(r){this._$AN!==void 0?(Tr(this),this._$AM=r,Di(this)):this._$AM=r}function va(r,e=!1,t=0){let n=this._$AH,i=this._$AN;if(i!==void 0&&i.size!==0)if(e)if(Array.isArray(n))for(let o=t;o{r.type==Pi.CHILD&&(r._$AP??=va,r._$AQ??=ma)},Er=class extends kr{constructor(){super(...arguments),this._$AN=void 0}_$AT(e,t,n){super._$AT(e,t,n),Di(this),this.isConnected=e._$AU}_$AO(e,t=!0){e!==this.isConnected&&(this.isConnected=e,e?this.reconnected?.():this.disconnected?.()),t&&(Ot(this,e),Tr(this))}setValue(e){if(Ri(this._$Ct))this._$Ct._$AI(e,this);else{let t=[...this._$Ct._$AH];t[this._$Ci]=e,this._$Ct._$AI(t,this,0)}}disconnected(){}reconnected(){}};var Mi=()=>new an,an=class{},sn=new WeakMap,Ni=on(class extends Er{render(r){return O}update(r,[e]){let t=e!==this.G;return t&&this.G!==void 0&&this.rt(void 0),(t||this.lt!==this.ct)&&(this.G=e,this.ht=r.options?.host,this.rt(this.ct=r.element)),O}rt(r){if(this.isConnected||(r=void 0),typeof this.G=="function"){let e=this.ht??globalThis,t=sn.get(e);t===void 0&&(t=new WeakMap,sn.set(e,t)),t.get(this.G)!==void 0&&this.G.call(this.ht,void 0),t.set(this.G,r),r!==void 0&&this.G.call(this.ht,r)}else this.G.value=r}get lt(){return typeof this.G=="function"?sn.get(this.ht??globalThis)?.get(this.G):this.G?.value}disconnected(){this.lt===this.ct&&this.rt(void 0)}reconnected(){this.rt(this.ct)}});var me=K` + `):"",this.name="UnsubscriptionError",this.errors=t}});function ge(r,e){if(r){var t=r.indexOf(e);0<=t&&r.splice(t,1)}}var X=(function(){function r(e){this.initialTeardown=e,this.closed=!1,this._parentage=null,this._finalizers=null}return r.prototype.unsubscribe=function(){var e,t,n,i,o;if(!this.closed){this.closed=!0;var s=this._parentage;if(s)if(this._parentage=null,Array.isArray(s))try{for(var c=re(s),l=c.next();!l.done;l=c.next()){var d=l.value;d.remove(this)}}catch(w){e={error:w}}finally{try{l&&!l.done&&(t=c.return)&&t.call(c)}finally{if(e)throw e.error}}else s.remove(this);var u=this.initialTeardown;if(k(u))try{u()}catch(w){o=w instanceof Pt?w.errors:[w]}var p=this._finalizers;if(p){this._finalizers=null;try{for(var S=re(p),y=S.next();!y.done;y=S.next()){var A=y.value;try{pn(A)}catch(w){o=o??[],w instanceof Pt?o=q(q([],H(o)),H(w.errors)):o.push(w)}}}catch(w){n={error:w}}finally{try{y&&!y.done&&(i=S.return)&&i.call(S)}finally{if(n)throw n.error}}}if(o)throw new Pt(o)}},r.prototype.add=function(e){var t;if(e&&e!==this)if(this.closed)pn(e);else{if(e instanceof r){if(e.closed||e._hasParent(this))return;e._addParent(this)}(this._finalizers=(t=this._finalizers)!==null&&t!==void 0?t:[]).push(e)}},r.prototype._hasParent=function(e){var t=this._parentage;return t===e||Array.isArray(t)&&t.includes(e)},r.prototype._addParent=function(e){var t=this._parentage;this._parentage=Array.isArray(t)?(t.push(e),t):t?[t,e]:e},r.prototype._removeParent=function(e){var t=this._parentage;t===e?this._parentage=null:Array.isArray(t)&&ge(t,e)},r.prototype.remove=function(e){var t=this._finalizers;t&&ge(t,e),e instanceof r&&e._removeParent(this)},r.EMPTY=(function(){var e=new r;return e.closed=!0,e})(),r})();var $r=X.EMPTY;function Mt(r){return r instanceof X||r&&"closed"in r&&k(r.remove)&&k(r.add)&&k(r.unsubscribe)}function pn(r){k(r)?r():r.unsubscribe()}var G={onUnhandledError:null,onStoppedNotification:null,Promise:void 0,useDeprecatedSynchronousErrorHandling:!1,useDeprecatedNextContext:!1};var Ge={setTimeout:function(r,e){for(var t=[],n=2;n0},enumerable:!1,configurable:!0}),e.prototype._trySubscribe=function(t){return this._throwIfClosed(),r.prototype._trySubscribe.call(this,t)},e.prototype._subscribe=function(t){return this._throwIfClosed(),this._checkFinalizedStatuses(t),this._innerSubscribe(t)},e.prototype._innerSubscribe=function(t){var n=this,i=this,o=i.hasError,s=i.isStopped,c=i.observers;return o||s?$r:(this.currentObservers=null,c.push(t),new X(function(){n.currentObservers=null,ge(c,t)}))},e.prototype._checkFinalizedStatuses=function(t){var n=this,i=n.hasError,o=n.thrownError,s=n.isStopped;i?t.error(o):s&&t.complete()},e.prototype.asObservable=function(){var t=new E;return t.source=this,t},e.create=function(t,n){return new Ut(t,n)},e})(E);var Ut=(function(r){R(e,r);function e(t,n){var i=r.call(this)||this;return i.destination=t,i.source=n,i}return e.prototype.next=function(t){var n,i;(i=(n=this.destination)===null||n===void 0?void 0:n.next)===null||i===void 0||i.call(n,t)},e.prototype.error=function(t){var n,i;(i=(n=this.destination)===null||n===void 0?void 0:n.error)===null||i===void 0||i.call(n,t)},e.prototype.complete=function(){var t,n;(n=(t=this.destination)===null||t===void 0?void 0:t.complete)===null||n===void 0||n.call(t)},e.prototype._subscribe=function(t){var n,i;return(i=(n=this.source)===null||n===void 0?void 0:n.subscribe(t))!==null&&i!==void 0?i:$r},e})(Y);var ut={now:function(){return(ut.delegate||Date).now()},delegate:void 0};var zt=(function(r){R(e,r);function e(t,n,i){t===void 0&&(t=1/0),n===void 0&&(n=1/0),i===void 0&&(i=ut);var o=r.call(this)||this;return o._bufferSize=t,o._windowTime=n,o._timestampProvider=i,o._buffer=[],o._infiniteTimeWindow=!0,o._infiniteTimeWindow=n===1/0,o._bufferSize=Math.max(1,t),o._windowTime=Math.max(1,n),o}return e.prototype.next=function(t){var n=this,i=n.isStopped,o=n._buffer,s=n._infiniteTimeWindow,c=n._timestampProvider,l=n._windowTime;i||(o.push(t),!s&&o.push(c.now()+l)),this._trimBuffer(),r.prototype.next.call(this,t)},e.prototype._subscribe=function(t){this._throwIfClosed(),this._trimBuffer();for(var n=this._innerSubscribe(t),i=this,o=i._infiniteTimeWindow,s=i._buffer,c=s.slice(),l=0;l0&&(u=new xe({next:function(jt){return $t.next(jt)},error:function(jt){w=!0,I(),p=Nr(U,i,jt),$t.error(jt)},complete:function(){A=!0,I(),p=Nr(U,s),$t.complete()}}),j(lt).subscribe(u))})(d)}}function Nr(r,e){for(var t=[],n=2;n{let e=new URL(window.location.href),t=e.protocol==="https:"?"wss":"ws",n;if(r.host)n=new URL(r.ws_path,t+"://"+r.host);else{let o=new URL(e);o.protocol=t,o.pathname=r.ws_path,n=o}return Ur(n.toString()).pipe(Mr({delay:5e3}))}}}var Fn={debug(...r){},error(...r){},info(...r){},trace(...r){}},zr={name:"console",globalSetup:r=>{let e=new Y;return[e,{debug:function(...n){e.next({level:"debug",args:n})},info:function(...n){e.next({level:"info",args:n})},trace:function(...n){e.next({level:"trace",args:n})},error:function(...n){e.next({level:"error",args:n})}}]},resetSink:(r,e,t)=>r.pipe(we(n=>{let i=["trace","debug","info","error"],o=i.indexOf(n.level),s=i.indexOf(t.log_level);o>=s&&console.log(`[${n.level}]`,...n.args)}),Se())};var T;(function(r){r.assertEqual=i=>i;function e(i){}r.assertIs=e;function t(i){throw new Error}r.assertNever=t,r.arrayToEnum=i=>{let o={};for(let s of i)o[s]=s;return o},r.getValidEnumValues=i=>{let o=r.objectKeys(i).filter(c=>typeof i[i[c]]!="number"),s={};for(let c of o)s[c]=i[c];return r.objectValues(s)},r.objectValues=i=>r.objectKeys(i).map(function(o){return i[o]}),r.objectKeys=typeof Object.keys=="function"?i=>Object.keys(i):i=>{let o=[];for(let s in i)Object.prototype.hasOwnProperty.call(i,s)&&o.push(s);return o},r.find=(i,o)=>{for(let s of i)if(o(s))return s},r.isInteger=typeof Number.isInteger=="function"?i=>Number.isInteger(i):i=>typeof i=="number"&&isFinite(i)&&Math.floor(i)===i;function n(i,o=" | "){return i.map(s=>typeof s=="string"?`'${s}'`:s).join(o)}r.joinValues=n,r.jsonStringifyReplacer=(i,o)=>typeof o=="bigint"?o.toString():o})(T||(T={}));var Fr;(function(r){r.mergeShapes=(e,t)=>({...e,...t})})(Fr||(Fr={}));var m=T.arrayToEnum(["string","nan","number","integer","float","boolean","date","bigint","symbol","function","undefined","null","array","object","unknown","promise","void","never","map","set"]),ie=r=>{switch(typeof r){case"undefined":return m.undefined;case"string":return m.string;case"number":return isNaN(r)?m.nan:m.number;case"boolean":return m.boolean;case"function":return m.function;case"bigint":return m.bigint;case"symbol":return m.symbol;case"object":return Array.isArray(r)?m.array:r===null?m.null:r.then&&typeof r.then=="function"&&r.catch&&typeof r.catch=="function"?m.promise:typeof Map<"u"&&r instanceof Map?m.map:typeof Set<"u"&&r instanceof Set?m.set:typeof Date<"u"&&r instanceof Date?m.date:m.object;default:return m.unknown}},f=T.arrayToEnum(["invalid_type","invalid_literal","custom","invalid_union","invalid_union_discriminator","invalid_enum_value","unrecognized_keys","invalid_arguments","invalid_return_type","invalid_date","invalid_string","too_small","too_big","invalid_intersection_types","not_multiple_of","not_finite"]),vo=r=>JSON.stringify(r,null,2).replace(/"([^"]+)":/g,"$1:"),z=class r extends Error{get errors(){return this.issues}constructor(e){super(),this.issues=[],this.addIssue=n=>{this.issues=[...this.issues,n]},this.addIssues=(n=[])=>{this.issues=[...this.issues,...n]};let t=new.target.prototype;Object.setPrototypeOf?Object.setPrototypeOf(this,t):this.__proto__=t,this.name="ZodError",this.issues=e}format(e){let t=e||function(o){return o.message},n={_errors:[]},i=o=>{for(let s of o.issues)if(s.code==="invalid_union")s.unionErrors.map(i);else if(s.code==="invalid_return_type")i(s.returnTypeError);else if(s.code==="invalid_arguments")i(s.argumentsError);else if(s.path.length===0)n._errors.push(t(s));else{let c=n,l=0;for(;lt.message){let t={},n=[];for(let i of this.issues)i.path.length>0?(t[i.path[0]]=t[i.path[0]]||[],t[i.path[0]].push(e(i))):n.push(e(i));return{formErrors:n,fieldErrors:t}}get formErrors(){return this.flatten()}};z.create=r=>new z(r);var Qe=(r,e)=>{let t;switch(r.code){case f.invalid_type:r.received===m.undefined?t="Required":t=`Expected ${r.expected}, received ${r.received}`;break;case f.invalid_literal:t=`Invalid literal value, expected ${JSON.stringify(r.expected,T.jsonStringifyReplacer)}`;break;case f.unrecognized_keys:t=`Unrecognized key(s) in object: ${T.joinValues(r.keys,", ")}`;break;case f.invalid_union:t="Invalid input";break;case f.invalid_union_discriminator:t=`Invalid discriminator value. Expected ${T.joinValues(r.options)}`;break;case f.invalid_enum_value:t=`Invalid enum value. Expected ${T.joinValues(r.options)}, received '${r.received}'`;break;case f.invalid_arguments:t="Invalid function arguments";break;case f.invalid_return_type:t="Invalid function return type";break;case f.invalid_date:t="Invalid date";break;case f.invalid_string:typeof r.validation=="object"?"includes"in r.validation?(t=`Invalid input: must include "${r.validation.includes}"`,typeof r.validation.position=="number"&&(t=`${t} at one or more positions greater than or equal to ${r.validation.position}`)):"startsWith"in r.validation?t=`Invalid input: must start with "${r.validation.startsWith}"`:"endsWith"in r.validation?t=`Invalid input: must end with "${r.validation.endsWith}"`:T.assertNever(r.validation):r.validation!=="regex"?t=`Invalid ${r.validation}`:t="Invalid";break;case f.too_small:r.type==="array"?t=`Array must contain ${r.exact?"exactly":r.inclusive?"at least":"more than"} ${r.minimum} element(s)`:r.type==="string"?t=`String must contain ${r.exact?"exactly":r.inclusive?"at least":"over"} ${r.minimum} character(s)`:r.type==="number"?t=`Number must be ${r.exact?"exactly equal to ":r.inclusive?"greater than or equal to ":"greater than "}${r.minimum}`:r.type==="date"?t=`Date must be ${r.exact?"exactly equal to ":r.inclusive?"greater than or equal to ":"greater than "}${new Date(Number(r.minimum))}`:t="Invalid input";break;case f.too_big:r.type==="array"?t=`Array must contain ${r.exact?"exactly":r.inclusive?"at most":"less than"} ${r.maximum} element(s)`:r.type==="string"?t=`String must contain ${r.exact?"exactly":r.inclusive?"at most":"under"} ${r.maximum} character(s)`:r.type==="number"?t=`Number must be ${r.exact?"exactly":r.inclusive?"less than or equal to":"less than"} ${r.maximum}`:r.type==="bigint"?t=`BigInt must be ${r.exact?"exactly":r.inclusive?"less than or equal to":"less than"} ${r.maximum}`:r.type==="date"?t=`Date must be ${r.exact?"exactly":r.inclusive?"smaller than or equal to":"smaller than"} ${new Date(Number(r.maximum))}`:t="Invalid input";break;case f.custom:t="Invalid input";break;case f.invalid_intersection_types:t="Intersection results could not be merged";break;case f.not_multiple_of:t=`Number must be a multiple of ${r.multipleOf}`;break;case f.not_finite:t="Number must be finite";break;default:t=e.defaultError,T.assertNever(r)}return{message:t}},Hn=Qe;function yo(r){Hn=r}function tr(){return Hn}var rr=r=>{let{data:e,path:t,errorMaps:n,issueData:i}=r,o=[...t,...i.path||[]],s={...i,path:o};if(i.message!==void 0)return{...i,path:o,message:i.message};let c="",l=n.filter(d=>!!d).slice().reverse();for(let d of l)c=d(s,{data:e,defaultError:c}).message;return{...i,path:o,message:c}},go=[];function h(r,e){let t=tr(),n=rr({issueData:e,data:r.data,path:r.path,errorMaps:[r.common.contextualErrorMap,r.schemaErrorMap,t,t===Qe?void 0:Qe].filter(i=>!!i)});r.common.issues.push(n)}var D=class r{constructor(){this.value="valid"}dirty(){this.value==="valid"&&(this.value="dirty")}abort(){this.value!=="aborted"&&(this.value="aborted")}static mergeArray(e,t){let n=[];for(let i of t){if(i.status==="aborted")return b;i.status==="dirty"&&e.dirty(),n.push(i.value)}return{status:e.value,value:n}}static async mergeObjectAsync(e,t){let n=[];for(let i of t){let o=await i.key,s=await i.value;n.push({key:o,value:s})}return r.mergeObjectSync(e,n)}static mergeObjectSync(e,t){let n={};for(let i of t){let{key:o,value:s}=i;if(o.status==="aborted"||s.status==="aborted")return b;o.status==="dirty"&&e.dirty(),s.status==="dirty"&&e.dirty(),o.value!=="__proto__"&&(typeof s.value<"u"||i.alwaysSet)&&(n[o.value]=s.value)}return{status:e.value,value:n}}},b=Object.freeze({status:"aborted"}),Xe=r=>({status:"dirty",value:r}),P=r=>({status:"valid",value:r}),Vr=r=>r.status==="aborted",Wr=r=>r.status==="dirty",ke=r=>r.status==="valid",yt=r=>typeof Promise<"u"&&r instanceof Promise;function nr(r,e,t,n){if(t==="a"&&!n)throw new TypeError("Private accessor was defined without a getter");if(typeof e=="function"?r!==e||!n:!e.has(r))throw new TypeError("Cannot read private member from an object whose class did not declare it");return t==="m"?n:t==="a"?n.call(r):n?n.value:e.get(r)}function qn(r,e,t,n,i){if(n==="m")throw new TypeError("Private method is not writable");if(n==="a"&&!i)throw new TypeError("Private accessor was defined without a setter");if(typeof e=="function"?r!==e||!i:!e.has(r))throw new TypeError("Cannot write private member to an object whose class did not declare it");return n==="a"?i.call(r,t):i?i.value=t:e.set(r,t),t}var v;(function(r){r.errToObj=e=>typeof e=="string"?{message:e}:e||{},r.toString=e=>typeof e=="string"?e:e?.message})(v||(v={}));var mt,vt,W=class{constructor(e,t,n,i){this._cachedPath=[],this.parent=e,this.data=t,this._path=n,this._key=i}get path(){return this._cachedPath.length||(this._key instanceof Array?this._cachedPath.push(...this._path,...this._key):this._cachedPath.push(...this._path,this._key)),this._cachedPath}},Vn=(r,e)=>{if(ke(e))return{success:!0,data:e.value};if(!r.common.issues.length)throw new Error("Validation failed but no issues detected.");return{success:!1,get error(){if(this._error)return this._error;let t=new z(r.common.issues);return this._error=t,this._error}}};function _(r){if(!r)return{};let{errorMap:e,invalid_type_error:t,required_error:n,description:i}=r;if(e&&(t||n))throw new Error(`Can't use "invalid_type_error" or "required_error" in conjunction with custom error map.`);return e?{errorMap:e,description:i}:{errorMap:(s,c)=>{var l,d;let{message:u}=r;return s.code==="invalid_enum_value"?{message:u??c.defaultError}:typeof c.data>"u"?{message:(l=u??n)!==null&&l!==void 0?l:c.defaultError}:s.code!=="invalid_type"?{message:c.defaultError}:{message:(d=u??t)!==null&&d!==void 0?d:c.defaultError}},description:i}}var x=class{get description(){return this._def.description}_getType(e){return ie(e.data)}_getOrReturnCtx(e,t){return t||{common:e.parent.common,data:e.data,parsedType:ie(e.data),schemaErrorMap:this._def.errorMap,path:e.path,parent:e.parent}}_processInputParams(e){return{status:new D,ctx:{common:e.parent.common,data:e.data,parsedType:ie(e.data),schemaErrorMap:this._def.errorMap,path:e.path,parent:e.parent}}}_parseSync(e){let t=this._parse(e);if(yt(t))throw new Error("Synchronous parse encountered promise.");return t}_parseAsync(e){let t=this._parse(e);return Promise.resolve(t)}parse(e,t){let n=this.safeParse(e,t);if(n.success)return n.data;throw n.error}safeParse(e,t){var n;let i={common:{issues:[],async:(n=t?.async)!==null&&n!==void 0?n:!1,contextualErrorMap:t?.errorMap},path:t?.path||[],schemaErrorMap:this._def.errorMap,parent:null,data:e,parsedType:ie(e)},o=this._parseSync({data:e,path:i.path,parent:i});return Vn(i,o)}"~validate"(e){var t,n;let i={common:{issues:[],async:!!this["~standard"].async},path:[],schemaErrorMap:this._def.errorMap,parent:null,data:e,parsedType:ie(e)};if(!this["~standard"].async)try{let o=this._parseSync({data:e,path:[],parent:i});return ke(o)?{value:o.value}:{issues:i.common.issues}}catch(o){!((n=(t=o?.message)===null||t===void 0?void 0:t.toLowerCase())===null||n===void 0)&&n.includes("encountered")&&(this["~standard"].async=!0),i.common={issues:[],async:!0}}return this._parseAsync({data:e,path:[],parent:i}).then(o=>ke(o)?{value:o.value}:{issues:i.common.issues})}async parseAsync(e,t){let n=await this.safeParseAsync(e,t);if(n.success)return n.data;throw n.error}async safeParseAsync(e,t){let n={common:{issues:[],contextualErrorMap:t?.errorMap,async:!0},path:t?.path||[],schemaErrorMap:this._def.errorMap,parent:null,data:e,parsedType:ie(e)},i=this._parse({data:e,path:n.path,parent:n}),o=await(yt(i)?i:Promise.resolve(i));return Vn(n,o)}refine(e,t){let n=i=>typeof t=="string"||typeof t>"u"?{message:t}:typeof t=="function"?t(i):t;return this._refinement((i,o)=>{let s=e(i),c=()=>o.addIssue({code:f.custom,...n(i)});return typeof Promise<"u"&&s instanceof Promise?s.then(l=>l?!0:(c(),!1)):s?!0:(c(),!1)})}refinement(e,t){return this._refinement((n,i)=>e(n)?!0:(i.addIssue(typeof t=="function"?t(n,i):t),!1))}_refinement(e){return new Z({schema:this,typeName:g.ZodEffects,effect:{type:"refinement",refinement:e}})}superRefine(e){return this._refinement(e)}constructor(e){this.spa=this.safeParseAsync,this._def=e,this.parse=this.parse.bind(this),this.safeParse=this.safeParse.bind(this),this.parseAsync=this.parseAsync.bind(this),this.safeParseAsync=this.safeParseAsync.bind(this),this.spa=this.spa.bind(this),this.refine=this.refine.bind(this),this.refinement=this.refinement.bind(this),this.superRefine=this.superRefine.bind(this),this.optional=this.optional.bind(this),this.nullable=this.nullable.bind(this),this.nullish=this.nullish.bind(this),this.array=this.array.bind(this),this.promise=this.promise.bind(this),this.or=this.or.bind(this),this.and=this.and.bind(this),this.transform=this.transform.bind(this),this.brand=this.brand.bind(this),this.default=this.default.bind(this),this.catch=this.catch.bind(this),this.describe=this.describe.bind(this),this.pipe=this.pipe.bind(this),this.readonly=this.readonly.bind(this),this.isNullable=this.isNullable.bind(this),this.isOptional=this.isOptional.bind(this),this["~standard"]={version:1,vendor:"zod",validate:t=>this["~validate"](t)}}optional(){return V.create(this,this._def)}nullable(){return te.create(this,this._def)}nullish(){return this.nullable().optional()}array(){return se.create(this)}promise(){return he.create(this,this._def)}or(e){return je.create([this,e],this._def)}and(e){return Re.create(this,e,this._def)}transform(e){return new Z({..._(this._def),schema:this,typeName:g.ZodEffects,effect:{type:"transform",transform:e}})}default(e){let t=typeof e=="function"?e:()=>e;return new Ne({..._(this._def),innerType:this,defaultValue:t,typeName:g.ZodDefault})}brand(){return new gt({typeName:g.ZodBranded,type:this,..._(this._def)})}catch(e){let t=typeof e=="function"?e:()=>e;return new Le({..._(this._def),innerType:this,catchValue:t,typeName:g.ZodCatch})}describe(e){let t=this.constructor;return new t({...this._def,description:e})}pipe(e){return bt.create(this,e)}readonly(){return Ue.create(this)}isOptional(){return this.safeParse(void 0).success}isNullable(){return this.safeParse(null).success}},bo=/^c[^\s-]{8,}$/i,_o=/^[0-9a-z]+$/,xo=/^[0-9A-HJKMNP-TV-Z]{26}$/i,So=/^[0-9a-fA-F]{8}\b-[0-9a-fA-F]{4}\b-[0-9a-fA-F]{4}\b-[0-9a-fA-F]{4}\b-[0-9a-fA-F]{12}$/i,wo=/^[a-z0-9_-]{21}$/i,ko=/^[A-Za-z0-9-_]+\.[A-Za-z0-9-_]+\.[A-Za-z0-9-_]*$/,To=/^[-+]?P(?!$)(?:(?:[-+]?\d+Y)|(?:[-+]?\d+[.,]\d+Y$))?(?:(?:[-+]?\d+M)|(?:[-+]?\d+[.,]\d+M$))?(?:(?:[-+]?\d+W)|(?:[-+]?\d+[.,]\d+W$))?(?:(?:[-+]?\d+D)|(?:[-+]?\d+[.,]\d+D$))?(?:T(?=[\d+-])(?:(?:[-+]?\d+H)|(?:[-+]?\d+[.,]\d+H$))?(?:(?:[-+]?\d+M)|(?:[-+]?\d+[.,]\d+M$))?(?:[-+]?\d+(?:[.,]\d+)?S)?)??$/,Ao=/^(?!\.)(?!.*\.\.)([A-Z0-9_'+\-\.]*)[A-Z0-9_+-]@([A-Z0-9][A-Z0-9\-]*\.)+[A-Z]{2,}$/i,Eo="^(\\p{Extended_Pictographic}|\\p{Emoji_Component})+$",Zr,Oo=/^(?:(?:25[0-5]|2[0-4][0-9]|1[0-9][0-9]|[1-9][0-9]|[0-9])\.){3}(?:25[0-5]|2[0-4][0-9]|1[0-9][0-9]|[1-9][0-9]|[0-9])$/,Co=/^(?:(?:25[0-5]|2[0-4][0-9]|1[0-9][0-9]|[1-9][0-9]|[0-9])\.){3}(?:25[0-5]|2[0-4][0-9]|1[0-9][0-9]|[1-9][0-9]|[0-9])\/(3[0-2]|[12]?[0-9])$/,$o=/^(([0-9a-fA-F]{1,4}:){7,7}[0-9a-fA-F]{1,4}|([0-9a-fA-F]{1,4}:){1,7}:|([0-9a-fA-F]{1,4}:){1,6}:[0-9a-fA-F]{1,4}|([0-9a-fA-F]{1,4}:){1,5}(:[0-9a-fA-F]{1,4}){1,2}|([0-9a-fA-F]{1,4}:){1,4}(:[0-9a-fA-F]{1,4}){1,3}|([0-9a-fA-F]{1,4}:){1,3}(:[0-9a-fA-F]{1,4}){1,4}|([0-9a-fA-F]{1,4}:){1,2}(:[0-9a-fA-F]{1,4}){1,5}|[0-9a-fA-F]{1,4}:((:[0-9a-fA-F]{1,4}){1,6})|:((:[0-9a-fA-F]{1,4}){1,7}|:)|fe80:(:[0-9a-fA-F]{0,4}){0,4}%[0-9a-zA-Z]{1,}|::(ffff(:0{1,4}){0,1}:){0,1}((25[0-5]|(2[0-4]|1{0,1}[0-9]){0,1}[0-9])\.){3,3}(25[0-5]|(2[0-4]|1{0,1}[0-9]){0,1}[0-9])|([0-9a-fA-F]{1,4}:){1,4}:((25[0-5]|(2[0-4]|1{0,1}[0-9]){0,1}[0-9])\.){3,3}(25[0-5]|(2[0-4]|1{0,1}[0-9]){0,1}[0-9]))$/,jo=/^(([0-9a-fA-F]{1,4}:){7,7}[0-9a-fA-F]{1,4}|([0-9a-fA-F]{1,4}:){1,7}:|([0-9a-fA-F]{1,4}:){1,6}:[0-9a-fA-F]{1,4}|([0-9a-fA-F]{1,4}:){1,5}(:[0-9a-fA-F]{1,4}){1,2}|([0-9a-fA-F]{1,4}:){1,4}(:[0-9a-fA-F]{1,4}){1,3}|([0-9a-fA-F]{1,4}:){1,3}(:[0-9a-fA-F]{1,4}){1,4}|([0-9a-fA-F]{1,4}:){1,2}(:[0-9a-fA-F]{1,4}){1,5}|[0-9a-fA-F]{1,4}:((:[0-9a-fA-F]{1,4}){1,6})|:((:[0-9a-fA-F]{1,4}){1,7}|:)|fe80:(:[0-9a-fA-F]{0,4}){0,4}%[0-9a-zA-Z]{1,}|::(ffff(:0{1,4}){0,1}:){0,1}((25[0-5]|(2[0-4]|1{0,1}[0-9]){0,1}[0-9])\.){3,3}(25[0-5]|(2[0-4]|1{0,1}[0-9]){0,1}[0-9])|([0-9a-fA-F]{1,4}:){1,4}:((25[0-5]|(2[0-4]|1{0,1}[0-9]){0,1}[0-9])\.){3,3}(25[0-5]|(2[0-4]|1{0,1}[0-9]){0,1}[0-9]))\/(12[0-8]|1[01][0-9]|[1-9]?[0-9])$/,Ro=/^([0-9a-zA-Z+/]{4})*(([0-9a-zA-Z+/]{2}==)|([0-9a-zA-Z+/]{3}=))?$/,Io=/^([0-9a-zA-Z-_]{4})*(([0-9a-zA-Z-_]{2}(==)?)|([0-9a-zA-Z-_]{3}(=)?))?$/,Gn="((\\d\\d[2468][048]|\\d\\d[13579][26]|\\d\\d0[48]|[02468][048]00|[13579][26]00)-02-29|\\d{4}-((0[13578]|1[02])-(0[1-9]|[12]\\d|3[01])|(0[469]|11)-(0[1-9]|[12]\\d|30)|(02)-(0[1-9]|1\\d|2[0-8])))",Do=new RegExp(`^${Gn}$`);function Yn(r){let e="([01]\\d|2[0-3]):[0-5]\\d:[0-5]\\d";return r.precision?e=`${e}\\.\\d{${r.precision}}`:r.precision==null&&(e=`${e}(\\.\\d+)?`),e}function Po(r){return new RegExp(`^${Yn(r)}$`)}function Jn(r){let e=`${Gn}T${Yn(r)}`,t=[];return t.push(r.local?"Z?":"Z"),r.offset&&t.push("([+-]\\d{2}:?\\d{2})"),e=`${e}(${t.join("|")})`,new RegExp(`^${e}$`)}function Mo(r,e){return!!((e==="v4"||!e)&&Oo.test(r)||(e==="v6"||!e)&&$o.test(r))}function No(r,e){if(!ko.test(r))return!1;try{let[t]=r.split("."),n=t.replace(/-/g,"+").replace(/_/g,"/").padEnd(t.length+(4-t.length%4)%4,"="),i=JSON.parse(atob(n));return!(typeof i!="object"||i===null||!i.typ||!i.alg||e&&i.alg!==e)}catch{return!1}}function Lo(r,e){return!!((e==="v4"||!e)&&Co.test(r)||(e==="v6"||!e)&&jo.test(r))}var fe=class r extends x{_parse(e){if(this._def.coerce&&(e.data=String(e.data)),this._getType(e)!==m.string){let o=this._getOrReturnCtx(e);return h(o,{code:f.invalid_type,expected:m.string,received:o.parsedType}),b}let n=new D,i;for(let o of this._def.checks)if(o.kind==="min")e.data.lengtho.value&&(i=this._getOrReturnCtx(e,i),h(i,{code:f.too_big,maximum:o.value,type:"string",inclusive:!0,exact:!1,message:o.message}),n.dirty());else if(o.kind==="length"){let s=e.data.length>o.value,c=e.data.lengthe.test(i),{validation:t,code:f.invalid_string,...v.errToObj(n)})}_addCheck(e){return new r({...this._def,checks:[...this._def.checks,e]})}email(e){return this._addCheck({kind:"email",...v.errToObj(e)})}url(e){return this._addCheck({kind:"url",...v.errToObj(e)})}emoji(e){return this._addCheck({kind:"emoji",...v.errToObj(e)})}uuid(e){return this._addCheck({kind:"uuid",...v.errToObj(e)})}nanoid(e){return this._addCheck({kind:"nanoid",...v.errToObj(e)})}cuid(e){return this._addCheck({kind:"cuid",...v.errToObj(e)})}cuid2(e){return this._addCheck({kind:"cuid2",...v.errToObj(e)})}ulid(e){return this._addCheck({kind:"ulid",...v.errToObj(e)})}base64(e){return this._addCheck({kind:"base64",...v.errToObj(e)})}base64url(e){return this._addCheck({kind:"base64url",...v.errToObj(e)})}jwt(e){return this._addCheck({kind:"jwt",...v.errToObj(e)})}ip(e){return this._addCheck({kind:"ip",...v.errToObj(e)})}cidr(e){return this._addCheck({kind:"cidr",...v.errToObj(e)})}datetime(e){var t,n;return typeof e=="string"?this._addCheck({kind:"datetime",precision:null,offset:!1,local:!1,message:e}):this._addCheck({kind:"datetime",precision:typeof e?.precision>"u"?null:e?.precision,offset:(t=e?.offset)!==null&&t!==void 0?t:!1,local:(n=e?.local)!==null&&n!==void 0?n:!1,...v.errToObj(e?.message)})}date(e){return this._addCheck({kind:"date",message:e})}time(e){return typeof e=="string"?this._addCheck({kind:"time",precision:null,message:e}):this._addCheck({kind:"time",precision:typeof e?.precision>"u"?null:e?.precision,...v.errToObj(e?.message)})}duration(e){return this._addCheck({kind:"duration",...v.errToObj(e)})}regex(e,t){return this._addCheck({kind:"regex",regex:e,...v.errToObj(t)})}includes(e,t){return this._addCheck({kind:"includes",value:e,position:t?.position,...v.errToObj(t?.message)})}startsWith(e,t){return this._addCheck({kind:"startsWith",value:e,...v.errToObj(t)})}endsWith(e,t){return this._addCheck({kind:"endsWith",value:e,...v.errToObj(t)})}min(e,t){return this._addCheck({kind:"min",value:e,...v.errToObj(t)})}max(e,t){return this._addCheck({kind:"max",value:e,...v.errToObj(t)})}length(e,t){return this._addCheck({kind:"length",value:e,...v.errToObj(t)})}nonempty(e){return this.min(1,v.errToObj(e))}trim(){return new r({...this._def,checks:[...this._def.checks,{kind:"trim"}]})}toLowerCase(){return new r({...this._def,checks:[...this._def.checks,{kind:"toLowerCase"}]})}toUpperCase(){return new r({...this._def,checks:[...this._def.checks,{kind:"toUpperCase"}]})}get isDatetime(){return!!this._def.checks.find(e=>e.kind==="datetime")}get isDate(){return!!this._def.checks.find(e=>e.kind==="date")}get isTime(){return!!this._def.checks.find(e=>e.kind==="time")}get isDuration(){return!!this._def.checks.find(e=>e.kind==="duration")}get isEmail(){return!!this._def.checks.find(e=>e.kind==="email")}get isURL(){return!!this._def.checks.find(e=>e.kind==="url")}get isEmoji(){return!!this._def.checks.find(e=>e.kind==="emoji")}get isUUID(){return!!this._def.checks.find(e=>e.kind==="uuid")}get isNANOID(){return!!this._def.checks.find(e=>e.kind==="nanoid")}get isCUID(){return!!this._def.checks.find(e=>e.kind==="cuid")}get isCUID2(){return!!this._def.checks.find(e=>e.kind==="cuid2")}get isULID(){return!!this._def.checks.find(e=>e.kind==="ulid")}get isIP(){return!!this._def.checks.find(e=>e.kind==="ip")}get isCIDR(){return!!this._def.checks.find(e=>e.kind==="cidr")}get isBase64(){return!!this._def.checks.find(e=>e.kind==="base64")}get isBase64url(){return!!this._def.checks.find(e=>e.kind==="base64url")}get minLength(){let e=null;for(let t of this._def.checks)t.kind==="min"&&(e===null||t.value>e)&&(e=t.value);return e}get maxLength(){let e=null;for(let t of this._def.checks)t.kind==="max"&&(e===null||t.value{var e;return new fe({checks:[],typeName:g.ZodString,coerce:(e=r?.coerce)!==null&&e!==void 0?e:!1,..._(r)})};function Uo(r,e){let t=(r.toString().split(".")[1]||"").length,n=(e.toString().split(".")[1]||"").length,i=t>n?t:n,o=parseInt(r.toFixed(i).replace(".","")),s=parseInt(e.toFixed(i).replace(".",""));return o%s/Math.pow(10,i)}var Te=class r extends x{constructor(){super(...arguments),this.min=this.gte,this.max=this.lte,this.step=this.multipleOf}_parse(e){if(this._def.coerce&&(e.data=Number(e.data)),this._getType(e)!==m.number){let o=this._getOrReturnCtx(e);return h(o,{code:f.invalid_type,expected:m.number,received:o.parsedType}),b}let n,i=new D;for(let o of this._def.checks)o.kind==="int"?T.isInteger(e.data)||(n=this._getOrReturnCtx(e,n),h(n,{code:f.invalid_type,expected:"integer",received:"float",message:o.message}),i.dirty()):o.kind==="min"?(o.inclusive?e.datao.value:e.data>=o.value)&&(n=this._getOrReturnCtx(e,n),h(n,{code:f.too_big,maximum:o.value,type:"number",inclusive:o.inclusive,exact:!1,message:o.message}),i.dirty()):o.kind==="multipleOf"?Uo(e.data,o.value)!==0&&(n=this._getOrReturnCtx(e,n),h(n,{code:f.not_multiple_of,multipleOf:o.value,message:o.message}),i.dirty()):o.kind==="finite"?Number.isFinite(e.data)||(n=this._getOrReturnCtx(e,n),h(n,{code:f.not_finite,message:o.message}),i.dirty()):T.assertNever(o);return{status:i.value,value:e.data}}gte(e,t){return this.setLimit("min",e,!0,v.toString(t))}gt(e,t){return this.setLimit("min",e,!1,v.toString(t))}lte(e,t){return this.setLimit("max",e,!0,v.toString(t))}lt(e,t){return this.setLimit("max",e,!1,v.toString(t))}setLimit(e,t,n,i){return new r({...this._def,checks:[...this._def.checks,{kind:e,value:t,inclusive:n,message:v.toString(i)}]})}_addCheck(e){return new r({...this._def,checks:[...this._def.checks,e]})}int(e){return this._addCheck({kind:"int",message:v.toString(e)})}positive(e){return this._addCheck({kind:"min",value:0,inclusive:!1,message:v.toString(e)})}negative(e){return this._addCheck({kind:"max",value:0,inclusive:!1,message:v.toString(e)})}nonpositive(e){return this._addCheck({kind:"max",value:0,inclusive:!0,message:v.toString(e)})}nonnegative(e){return this._addCheck({kind:"min",value:0,inclusive:!0,message:v.toString(e)})}multipleOf(e,t){return this._addCheck({kind:"multipleOf",value:e,message:v.toString(t)})}finite(e){return this._addCheck({kind:"finite",message:v.toString(e)})}safe(e){return this._addCheck({kind:"min",inclusive:!0,value:Number.MIN_SAFE_INTEGER,message:v.toString(e)})._addCheck({kind:"max",inclusive:!0,value:Number.MAX_SAFE_INTEGER,message:v.toString(e)})}get minValue(){let e=null;for(let t of this._def.checks)t.kind==="min"&&(e===null||t.value>e)&&(e=t.value);return e}get maxValue(){let e=null;for(let t of this._def.checks)t.kind==="max"&&(e===null||t.valuee.kind==="int"||e.kind==="multipleOf"&&T.isInteger(e.value))}get isFinite(){let e=null,t=null;for(let n of this._def.checks){if(n.kind==="finite"||n.kind==="int"||n.kind==="multipleOf")return!0;n.kind==="min"?(t===null||n.value>t)&&(t=n.value):n.kind==="max"&&(e===null||n.valuenew Te({checks:[],typeName:g.ZodNumber,coerce:r?.coerce||!1,..._(r)});var Ae=class r extends x{constructor(){super(...arguments),this.min=this.gte,this.max=this.lte}_parse(e){if(this._def.coerce)try{e.data=BigInt(e.data)}catch{return this._getInvalidInput(e)}if(this._getType(e)!==m.bigint)return this._getInvalidInput(e);let n,i=new D;for(let o of this._def.checks)o.kind==="min"?(o.inclusive?e.datao.value:e.data>=o.value)&&(n=this._getOrReturnCtx(e,n),h(n,{code:f.too_big,type:"bigint",maximum:o.value,inclusive:o.inclusive,message:o.message}),i.dirty()):o.kind==="multipleOf"?e.data%o.value!==BigInt(0)&&(n=this._getOrReturnCtx(e,n),h(n,{code:f.not_multiple_of,multipleOf:o.value,message:o.message}),i.dirty()):T.assertNever(o);return{status:i.value,value:e.data}}_getInvalidInput(e){let t=this._getOrReturnCtx(e);return h(t,{code:f.invalid_type,expected:m.bigint,received:t.parsedType}),b}gte(e,t){return this.setLimit("min",e,!0,v.toString(t))}gt(e,t){return this.setLimit("min",e,!1,v.toString(t))}lte(e,t){return this.setLimit("max",e,!0,v.toString(t))}lt(e,t){return this.setLimit("max",e,!1,v.toString(t))}setLimit(e,t,n,i){return new r({...this._def,checks:[...this._def.checks,{kind:e,value:t,inclusive:n,message:v.toString(i)}]})}_addCheck(e){return new r({...this._def,checks:[...this._def.checks,e]})}positive(e){return this._addCheck({kind:"min",value:BigInt(0),inclusive:!1,message:v.toString(e)})}negative(e){return this._addCheck({kind:"max",value:BigInt(0),inclusive:!1,message:v.toString(e)})}nonpositive(e){return this._addCheck({kind:"max",value:BigInt(0),inclusive:!0,message:v.toString(e)})}nonnegative(e){return this._addCheck({kind:"min",value:BigInt(0),inclusive:!0,message:v.toString(e)})}multipleOf(e,t){return this._addCheck({kind:"multipleOf",value:e,message:v.toString(t)})}get minValue(){let e=null;for(let t of this._def.checks)t.kind==="min"&&(e===null||t.value>e)&&(e=t.value);return e}get maxValue(){let e=null;for(let t of this._def.checks)t.kind==="max"&&(e===null||t.value{var e;return new Ae({checks:[],typeName:g.ZodBigInt,coerce:(e=r?.coerce)!==null&&e!==void 0?e:!1,..._(r)})};var Ee=class extends x{_parse(e){if(this._def.coerce&&(e.data=!!e.data),this._getType(e)!==m.boolean){let n=this._getOrReturnCtx(e);return h(n,{code:f.invalid_type,expected:m.boolean,received:n.parsedType}),b}return P(e.data)}};Ee.create=r=>new Ee({typeName:g.ZodBoolean,coerce:r?.coerce||!1,..._(r)});var Oe=class r extends x{_parse(e){if(this._def.coerce&&(e.data=new Date(e.data)),this._getType(e)!==m.date){let o=this._getOrReturnCtx(e);return h(o,{code:f.invalid_type,expected:m.date,received:o.parsedType}),b}if(isNaN(e.data.getTime())){let o=this._getOrReturnCtx(e);return h(o,{code:f.invalid_date}),b}let n=new D,i;for(let o of this._def.checks)o.kind==="min"?e.data.getTime()o.value&&(i=this._getOrReturnCtx(e,i),h(i,{code:f.too_big,message:o.message,inclusive:!0,exact:!1,maximum:o.value,type:"date"}),n.dirty()):T.assertNever(o);return{status:n.value,value:new Date(e.data.getTime())}}_addCheck(e){return new r({...this._def,checks:[...this._def.checks,e]})}min(e,t){return this._addCheck({kind:"min",value:e.getTime(),message:v.toString(t)})}max(e,t){return this._addCheck({kind:"max",value:e.getTime(),message:v.toString(t)})}get minDate(){let e=null;for(let t of this._def.checks)t.kind==="min"&&(e===null||t.value>e)&&(e=t.value);return e!=null?new Date(e):null}get maxDate(){let e=null;for(let t of this._def.checks)t.kind==="max"&&(e===null||t.valuenew Oe({checks:[],coerce:r?.coerce||!1,typeName:g.ZodDate,..._(r)});var et=class extends x{_parse(e){if(this._getType(e)!==m.symbol){let n=this._getOrReturnCtx(e);return h(n,{code:f.invalid_type,expected:m.symbol,received:n.parsedType}),b}return P(e.data)}};et.create=r=>new et({typeName:g.ZodSymbol,..._(r)});var Ce=class extends x{_parse(e){if(this._getType(e)!==m.undefined){let n=this._getOrReturnCtx(e);return h(n,{code:f.invalid_type,expected:m.undefined,received:n.parsedType}),b}return P(e.data)}};Ce.create=r=>new Ce({typeName:g.ZodUndefined,..._(r)});var $e=class extends x{_parse(e){if(this._getType(e)!==m.null){let n=this._getOrReturnCtx(e);return h(n,{code:f.invalid_type,expected:m.null,received:n.parsedType}),b}return P(e.data)}};$e.create=r=>new $e({typeName:g.ZodNull,..._(r)});var pe=class extends x{constructor(){super(...arguments),this._any=!0}_parse(e){return P(e.data)}};pe.create=r=>new pe({typeName:g.ZodAny,..._(r)});var oe=class extends x{constructor(){super(...arguments),this._unknown=!0}_parse(e){return P(e.data)}};oe.create=r=>new oe({typeName:g.ZodUnknown,..._(r)});var J=class extends x{_parse(e){let t=this._getOrReturnCtx(e);return h(t,{code:f.invalid_type,expected:m.never,received:t.parsedType}),b}};J.create=r=>new J({typeName:g.ZodNever,..._(r)});var tt=class extends x{_parse(e){if(this._getType(e)!==m.undefined){let n=this._getOrReturnCtx(e);return h(n,{code:f.invalid_type,expected:m.void,received:n.parsedType}),b}return P(e.data)}};tt.create=r=>new tt({typeName:g.ZodVoid,..._(r)});var se=class r extends x{_parse(e){let{ctx:t,status:n}=this._processInputParams(e),i=this._def;if(t.parsedType!==m.array)return h(t,{code:f.invalid_type,expected:m.array,received:t.parsedType}),b;if(i.exactLength!==null){let s=t.data.length>i.exactLength.value,c=t.data.lengthi.maxLength.value&&(h(t,{code:f.too_big,maximum:i.maxLength.value,type:"array",inclusive:!0,exact:!1,message:i.maxLength.message}),n.dirty()),t.common.async)return Promise.all([...t.data].map((s,c)=>i.type._parseAsync(new W(t,s,t.path,c)))).then(s=>D.mergeArray(n,s));let o=[...t.data].map((s,c)=>i.type._parseSync(new W(t,s,t.path,c)));return D.mergeArray(n,o)}get element(){return this._def.type}min(e,t){return new r({...this._def,minLength:{value:e,message:v.toString(t)}})}max(e,t){return new r({...this._def,maxLength:{value:e,message:v.toString(t)}})}length(e,t){return new r({...this._def,exactLength:{value:e,message:v.toString(t)}})}nonempty(e){return this.min(1,e)}};se.create=(r,e)=>new se({type:r,minLength:null,maxLength:null,exactLength:null,typeName:g.ZodArray,..._(e)});function Ke(r){if(r instanceof M){let e={};for(let t in r.shape){let n=r.shape[t];e[t]=V.create(Ke(n))}return new M({...r._def,shape:()=>e})}else return r instanceof se?new se({...r._def,type:Ke(r.element)}):r instanceof V?V.create(Ke(r.unwrap())):r instanceof te?te.create(Ke(r.unwrap())):r instanceof ee?ee.create(r.items.map(e=>Ke(e))):r}var M=class r extends x{constructor(){super(...arguments),this._cached=null,this.nonstrict=this.passthrough,this.augment=this.extend}_getCached(){if(this._cached!==null)return this._cached;let e=this._def.shape(),t=T.objectKeys(e);return this._cached={shape:e,keys:t}}_parse(e){if(this._getType(e)!==m.object){let d=this._getOrReturnCtx(e);return h(d,{code:f.invalid_type,expected:m.object,received:d.parsedType}),b}let{status:n,ctx:i}=this._processInputParams(e),{shape:o,keys:s}=this._getCached(),c=[];if(!(this._def.catchall instanceof J&&this._def.unknownKeys==="strip"))for(let d in i.data)s.includes(d)||c.push(d);let l=[];for(let d of s){let u=o[d],p=i.data[d];l.push({key:{status:"valid",value:d},value:u._parse(new W(i,p,i.path,d)),alwaysSet:d in i.data})}if(this._def.catchall instanceof J){let d=this._def.unknownKeys;if(d==="passthrough")for(let u of c)l.push({key:{status:"valid",value:u},value:{status:"valid",value:i.data[u]}});else if(d==="strict")c.length>0&&(h(i,{code:f.unrecognized_keys,keys:c}),n.dirty());else if(d!=="strip")throw new Error("Internal ZodObject error: invalid unknownKeys value.")}else{let d=this._def.catchall;for(let u of c){let p=i.data[u];l.push({key:{status:"valid",value:u},value:d._parse(new W(i,p,i.path,u)),alwaysSet:u in i.data})}}return i.common.async?Promise.resolve().then(async()=>{let d=[];for(let u of l){let p=await u.key,S=await u.value;d.push({key:p,value:S,alwaysSet:u.alwaysSet})}return d}).then(d=>D.mergeObjectSync(n,d)):D.mergeObjectSync(n,l)}get shape(){return this._def.shape()}strict(e){return v.errToObj,new r({...this._def,unknownKeys:"strict",...e!==void 0?{errorMap:(t,n)=>{var i,o,s,c;let l=(s=(o=(i=this._def).errorMap)===null||o===void 0?void 0:o.call(i,t,n).message)!==null&&s!==void 0?s:n.defaultError;return t.code==="unrecognized_keys"?{message:(c=v.errToObj(e).message)!==null&&c!==void 0?c:l}:{message:l}}}:{}})}strip(){return new r({...this._def,unknownKeys:"strip"})}passthrough(){return new r({...this._def,unknownKeys:"passthrough"})}extend(e){return new r({...this._def,shape:()=>({...this._def.shape(),...e})})}merge(e){return new r({unknownKeys:e._def.unknownKeys,catchall:e._def.catchall,shape:()=>({...this._def.shape(),...e._def.shape()}),typeName:g.ZodObject})}setKey(e,t){return this.augment({[e]:t})}catchall(e){return new r({...this._def,catchall:e})}pick(e){let t={};return T.objectKeys(e).forEach(n=>{e[n]&&this.shape[n]&&(t[n]=this.shape[n])}),new r({...this._def,shape:()=>t})}omit(e){let t={};return T.objectKeys(this.shape).forEach(n=>{e[n]||(t[n]=this.shape[n])}),new r({...this._def,shape:()=>t})}deepPartial(){return Ke(this)}partial(e){let t={};return T.objectKeys(this.shape).forEach(n=>{let i=this.shape[n];e&&!e[n]?t[n]=i:t[n]=i.optional()}),new r({...this._def,shape:()=>t})}required(e){let t={};return T.objectKeys(this.shape).forEach(n=>{if(e&&!e[n])t[n]=this.shape[n];else{let o=this.shape[n];for(;o instanceof V;)o=o._def.innerType;t[n]=o}}),new r({...this._def,shape:()=>t})}keyof(){return Kn(T.objectKeys(this.shape))}};M.create=(r,e)=>new M({shape:()=>r,unknownKeys:"strip",catchall:J.create(),typeName:g.ZodObject,..._(e)});M.strictCreate=(r,e)=>new M({shape:()=>r,unknownKeys:"strict",catchall:J.create(),typeName:g.ZodObject,..._(e)});M.lazycreate=(r,e)=>new M({shape:r,unknownKeys:"strip",catchall:J.create(),typeName:g.ZodObject,..._(e)});var je=class extends x{_parse(e){let{ctx:t}=this._processInputParams(e),n=this._def.options;function i(o){for(let c of o)if(c.result.status==="valid")return c.result;for(let c of o)if(c.result.status==="dirty")return t.common.issues.push(...c.ctx.common.issues),c.result;let s=o.map(c=>new z(c.ctx.common.issues));return h(t,{code:f.invalid_union,unionErrors:s}),b}if(t.common.async)return Promise.all(n.map(async o=>{let s={...t,common:{...t.common,issues:[]},parent:null};return{result:await o._parseAsync({data:t.data,path:t.path,parent:s}),ctx:s}})).then(i);{let o,s=[];for(let l of n){let d={...t,common:{...t.common,issues:[]},parent:null},u=l._parseSync({data:t.data,path:t.path,parent:d});if(u.status==="valid")return u;u.status==="dirty"&&!o&&(o={result:u,ctx:d}),d.common.issues.length&&s.push(d.common.issues)}if(o)return t.common.issues.push(...o.ctx.common.issues),o.result;let c=s.map(l=>new z(l));return h(t,{code:f.invalid_union,unionErrors:c}),b}}get options(){return this._def.options}};je.create=(r,e)=>new je({options:r,typeName:g.ZodUnion,..._(e)});var ne=r=>r instanceof Ie?ne(r.schema):r instanceof Z?ne(r.innerType()):r instanceof De?[r.value]:r instanceof Pe?r.options:r instanceof Me?T.objectValues(r.enum):r instanceof Ne?ne(r._def.innerType):r instanceof Ce?[void 0]:r instanceof $e?[null]:r instanceof V?[void 0,...ne(r.unwrap())]:r instanceof te?[null,...ne(r.unwrap())]:r instanceof gt||r instanceof Ue?ne(r.unwrap()):r instanceof Le?ne(r._def.innerType):[],ir=class r extends x{_parse(e){let{ctx:t}=this._processInputParams(e);if(t.parsedType!==m.object)return h(t,{code:f.invalid_type,expected:m.object,received:t.parsedType}),b;let n=this.discriminator,i=t.data[n],o=this.optionsMap.get(i);return o?t.common.async?o._parseAsync({data:t.data,path:t.path,parent:t}):o._parseSync({data:t.data,path:t.path,parent:t}):(h(t,{code:f.invalid_union_discriminator,options:Array.from(this.optionsMap.keys()),path:[n]}),b)}get discriminator(){return this._def.discriminator}get options(){return this._def.options}get optionsMap(){return this._def.optionsMap}static create(e,t,n){let i=new Map;for(let o of t){let s=ne(o.shape[e]);if(!s.length)throw new Error(`A discriminator value for key \`${e}\` could not be extracted from all schema options`);for(let c of s){if(i.has(c))throw new Error(`Discriminator property ${String(e)} has duplicate value ${String(c)}`);i.set(c,o)}}return new r({typeName:g.ZodDiscriminatedUnion,discriminator:e,options:t,optionsMap:i,..._(n)})}};function Br(r,e){let t=ie(r),n=ie(e);if(r===e)return{valid:!0,data:r};if(t===m.object&&n===m.object){let i=T.objectKeys(e),o=T.objectKeys(r).filter(c=>i.indexOf(c)!==-1),s={...r,...e};for(let c of o){let l=Br(r[c],e[c]);if(!l.valid)return{valid:!1};s[c]=l.data}return{valid:!0,data:s}}else if(t===m.array&&n===m.array){if(r.length!==e.length)return{valid:!1};let i=[];for(let o=0;o{if(Vr(o)||Vr(s))return b;let c=Br(o.value,s.value);return c.valid?((Wr(o)||Wr(s))&&t.dirty(),{status:t.value,value:c.data}):(h(n,{code:f.invalid_intersection_types}),b)};return n.common.async?Promise.all([this._def.left._parseAsync({data:n.data,path:n.path,parent:n}),this._def.right._parseAsync({data:n.data,path:n.path,parent:n})]).then(([o,s])=>i(o,s)):i(this._def.left._parseSync({data:n.data,path:n.path,parent:n}),this._def.right._parseSync({data:n.data,path:n.path,parent:n}))}};Re.create=(r,e,t)=>new Re({left:r,right:e,typeName:g.ZodIntersection,..._(t)});var ee=class r extends x{_parse(e){let{status:t,ctx:n}=this._processInputParams(e);if(n.parsedType!==m.array)return h(n,{code:f.invalid_type,expected:m.array,received:n.parsedType}),b;if(n.data.lengththis._def.items.length&&(h(n,{code:f.too_big,maximum:this._def.items.length,inclusive:!0,exact:!1,type:"array"}),t.dirty());let o=[...n.data].map((s,c)=>{let l=this._def.items[c]||this._def.rest;return l?l._parse(new W(n,s,n.path,c)):null}).filter(s=>!!s);return n.common.async?Promise.all(o).then(s=>D.mergeArray(t,s)):D.mergeArray(t,o)}get items(){return this._def.items}rest(e){return new r({...this._def,rest:e})}};ee.create=(r,e)=>{if(!Array.isArray(r))throw new Error("You must pass an array of schemas to z.tuple([ ... ])");return new ee({items:r,typeName:g.ZodTuple,rest:null,..._(e)})};var or=class r extends x{get keySchema(){return this._def.keyType}get valueSchema(){return this._def.valueType}_parse(e){let{status:t,ctx:n}=this._processInputParams(e);if(n.parsedType!==m.object)return h(n,{code:f.invalid_type,expected:m.object,received:n.parsedType}),b;let i=[],o=this._def.keyType,s=this._def.valueType;for(let c in n.data)i.push({key:o._parse(new W(n,c,n.path,c)),value:s._parse(new W(n,n.data[c],n.path,c)),alwaysSet:c in n.data});return n.common.async?D.mergeObjectAsync(t,i):D.mergeObjectSync(t,i)}get element(){return this._def.valueType}static create(e,t,n){return t instanceof x?new r({keyType:e,valueType:t,typeName:g.ZodRecord,..._(n)}):new r({keyType:fe.create(),valueType:e,typeName:g.ZodRecord,..._(t)})}},rt=class extends x{get keySchema(){return this._def.keyType}get valueSchema(){return this._def.valueType}_parse(e){let{status:t,ctx:n}=this._processInputParams(e);if(n.parsedType!==m.map)return h(n,{code:f.invalid_type,expected:m.map,received:n.parsedType}),b;let i=this._def.keyType,o=this._def.valueType,s=[...n.data.entries()].map(([c,l],d)=>({key:i._parse(new W(n,c,n.path,[d,"key"])),value:o._parse(new W(n,l,n.path,[d,"value"]))}));if(n.common.async){let c=new Map;return Promise.resolve().then(async()=>{for(let l of s){let d=await l.key,u=await l.value;if(d.status==="aborted"||u.status==="aborted")return b;(d.status==="dirty"||u.status==="dirty")&&t.dirty(),c.set(d.value,u.value)}return{status:t.value,value:c}})}else{let c=new Map;for(let l of s){let d=l.key,u=l.value;if(d.status==="aborted"||u.status==="aborted")return b;(d.status==="dirty"||u.status==="dirty")&&t.dirty(),c.set(d.value,u.value)}return{status:t.value,value:c}}}};rt.create=(r,e,t)=>new rt({valueType:e,keyType:r,typeName:g.ZodMap,..._(t)});var nt=class r extends x{_parse(e){let{status:t,ctx:n}=this._processInputParams(e);if(n.parsedType!==m.set)return h(n,{code:f.invalid_type,expected:m.set,received:n.parsedType}),b;let i=this._def;i.minSize!==null&&n.data.sizei.maxSize.value&&(h(n,{code:f.too_big,maximum:i.maxSize.value,type:"set",inclusive:!0,exact:!1,message:i.maxSize.message}),t.dirty());let o=this._def.valueType;function s(l){let d=new Set;for(let u of l){if(u.status==="aborted")return b;u.status==="dirty"&&t.dirty(),d.add(u.value)}return{status:t.value,value:d}}let c=[...n.data.values()].map((l,d)=>o._parse(new W(n,l,n.path,d)));return n.common.async?Promise.all(c).then(l=>s(l)):s(c)}min(e,t){return new r({...this._def,minSize:{value:e,message:v.toString(t)}})}max(e,t){return new r({...this._def,maxSize:{value:e,message:v.toString(t)}})}size(e,t){return this.min(e,t).max(e,t)}nonempty(e){return this.min(1,e)}};nt.create=(r,e)=>new nt({valueType:r,minSize:null,maxSize:null,typeName:g.ZodSet,..._(e)});var sr=class r extends x{constructor(){super(...arguments),this.validate=this.implement}_parse(e){let{ctx:t}=this._processInputParams(e);if(t.parsedType!==m.function)return h(t,{code:f.invalid_type,expected:m.function,received:t.parsedType}),b;function n(c,l){return rr({data:c,path:t.path,errorMaps:[t.common.contextualErrorMap,t.schemaErrorMap,tr(),Qe].filter(d=>!!d),issueData:{code:f.invalid_arguments,argumentsError:l}})}function i(c,l){return rr({data:c,path:t.path,errorMaps:[t.common.contextualErrorMap,t.schemaErrorMap,tr(),Qe].filter(d=>!!d),issueData:{code:f.invalid_return_type,returnTypeError:l}})}let o={errorMap:t.common.contextualErrorMap},s=t.data;if(this._def.returns instanceof he){let c=this;return P(async function(...l){let d=new z([]),u=await c._def.args.parseAsync(l,o).catch(y=>{throw d.addIssue(n(l,y)),d}),p=await Reflect.apply(s,this,u);return await c._def.returns._def.type.parseAsync(p,o).catch(y=>{throw d.addIssue(i(p,y)),d})})}else{let c=this;return P(function(...l){let d=c._def.args.safeParse(l,o);if(!d.success)throw new z([n(l,d.error)]);let u=Reflect.apply(s,this,d.data),p=c._def.returns.safeParse(u,o);if(!p.success)throw new z([i(u,p.error)]);return p.data})}}parameters(){return this._def.args}returnType(){return this._def.returns}args(...e){return new r({...this._def,args:ee.create(e).rest(oe.create())})}returns(e){return new r({...this._def,returns:e})}implement(e){return this.parse(e)}strictImplement(e){return this.parse(e)}static create(e,t,n){return new r({args:e||ee.create([]).rest(oe.create()),returns:t||oe.create(),typeName:g.ZodFunction,..._(n)})}},Ie=class extends x{get schema(){return this._def.getter()}_parse(e){let{ctx:t}=this._processInputParams(e);return this._def.getter()._parse({data:t.data,path:t.path,parent:t})}};Ie.create=(r,e)=>new Ie({getter:r,typeName:g.ZodLazy,..._(e)});var De=class extends x{_parse(e){if(e.data!==this._def.value){let t=this._getOrReturnCtx(e);return h(t,{received:t.data,code:f.invalid_literal,expected:this._def.value}),b}return{status:"valid",value:e.data}}get value(){return this._def.value}};De.create=(r,e)=>new De({value:r,typeName:g.ZodLiteral,..._(e)});function Kn(r,e){return new Pe({values:r,typeName:g.ZodEnum,..._(e)})}var Pe=class r extends x{constructor(){super(...arguments),mt.set(this,void 0)}_parse(e){if(typeof e.data!="string"){let t=this._getOrReturnCtx(e),n=this._def.values;return h(t,{expected:T.joinValues(n),received:t.parsedType,code:f.invalid_type}),b}if(nr(this,mt,"f")||qn(this,mt,new Set(this._def.values),"f"),!nr(this,mt,"f").has(e.data)){let t=this._getOrReturnCtx(e),n=this._def.values;return h(t,{received:t.data,code:f.invalid_enum_value,options:n}),b}return P(e.data)}get options(){return this._def.values}get enum(){let e={};for(let t of this._def.values)e[t]=t;return e}get Values(){let e={};for(let t of this._def.values)e[t]=t;return e}get Enum(){let e={};for(let t of this._def.values)e[t]=t;return e}extract(e,t=this._def){return r.create(e,{...this._def,...t})}exclude(e,t=this._def){return r.create(this.options.filter(n=>!e.includes(n)),{...this._def,...t})}};mt=new WeakMap;Pe.create=Kn;var Me=class extends x{constructor(){super(...arguments),vt.set(this,void 0)}_parse(e){let t=T.getValidEnumValues(this._def.values),n=this._getOrReturnCtx(e);if(n.parsedType!==m.string&&n.parsedType!==m.number){let i=T.objectValues(t);return h(n,{expected:T.joinValues(i),received:n.parsedType,code:f.invalid_type}),b}if(nr(this,vt,"f")||qn(this,vt,new Set(T.getValidEnumValues(this._def.values)),"f"),!nr(this,vt,"f").has(e.data)){let i=T.objectValues(t);return h(n,{received:n.data,code:f.invalid_enum_value,options:i}),b}return P(e.data)}get enum(){return this._def.values}};vt=new WeakMap;Me.create=(r,e)=>new Me({values:r,typeName:g.ZodNativeEnum,..._(e)});var he=class extends x{unwrap(){return this._def.type}_parse(e){let{ctx:t}=this._processInputParams(e);if(t.parsedType!==m.promise&&t.common.async===!1)return h(t,{code:f.invalid_type,expected:m.promise,received:t.parsedType}),b;let n=t.parsedType===m.promise?t.data:Promise.resolve(t.data);return P(n.then(i=>this._def.type.parseAsync(i,{path:t.path,errorMap:t.common.contextualErrorMap})))}};he.create=(r,e)=>new he({type:r,typeName:g.ZodPromise,..._(e)});var Z=class extends x{innerType(){return this._def.schema}sourceType(){return this._def.schema._def.typeName===g.ZodEffects?this._def.schema.sourceType():this._def.schema}_parse(e){let{status:t,ctx:n}=this._processInputParams(e),i=this._def.effect||null,o={addIssue:s=>{h(n,s),s.fatal?t.abort():t.dirty()},get path(){return n.path}};if(o.addIssue=o.addIssue.bind(o),i.type==="preprocess"){let s=i.transform(n.data,o);if(n.common.async)return Promise.resolve(s).then(async c=>{if(t.value==="aborted")return b;let l=await this._def.schema._parseAsync({data:c,path:n.path,parent:n});return l.status==="aborted"?b:l.status==="dirty"||t.value==="dirty"?Xe(l.value):l});{if(t.value==="aborted")return b;let c=this._def.schema._parseSync({data:s,path:n.path,parent:n});return c.status==="aborted"?b:c.status==="dirty"||t.value==="dirty"?Xe(c.value):c}}if(i.type==="refinement"){let s=c=>{let l=i.refinement(c,o);if(n.common.async)return Promise.resolve(l);if(l instanceof Promise)throw new Error("Async refinement encountered during synchronous parse operation. Use .parseAsync instead.");return c};if(n.common.async===!1){let c=this._def.schema._parseSync({data:n.data,path:n.path,parent:n});return c.status==="aborted"?b:(c.status==="dirty"&&t.dirty(),s(c.value),{status:t.value,value:c.value})}else return this._def.schema._parseAsync({data:n.data,path:n.path,parent:n}).then(c=>c.status==="aborted"?b:(c.status==="dirty"&&t.dirty(),s(c.value).then(()=>({status:t.value,value:c.value}))))}if(i.type==="transform")if(n.common.async===!1){let s=this._def.schema._parseSync({data:n.data,path:n.path,parent:n});if(!ke(s))return s;let c=i.transform(s.value,o);if(c instanceof Promise)throw new Error("Asynchronous transform encountered during synchronous parse operation. Use .parseAsync instead.");return{status:t.value,value:c}}else return this._def.schema._parseAsync({data:n.data,path:n.path,parent:n}).then(s=>ke(s)?Promise.resolve(i.transform(s.value,o)).then(c=>({status:t.value,value:c})):s);T.assertNever(i)}};Z.create=(r,e,t)=>new Z({schema:r,typeName:g.ZodEffects,effect:e,..._(t)});Z.createWithPreprocess=(r,e,t)=>new Z({schema:e,effect:{type:"preprocess",transform:r},typeName:g.ZodEffects,..._(t)});var V=class extends x{_parse(e){return this._getType(e)===m.undefined?P(void 0):this._def.innerType._parse(e)}unwrap(){return this._def.innerType}};V.create=(r,e)=>new V({innerType:r,typeName:g.ZodOptional,..._(e)});var te=class extends x{_parse(e){return this._getType(e)===m.null?P(null):this._def.innerType._parse(e)}unwrap(){return this._def.innerType}};te.create=(r,e)=>new te({innerType:r,typeName:g.ZodNullable,..._(e)});var Ne=class extends x{_parse(e){let{ctx:t}=this._processInputParams(e),n=t.data;return t.parsedType===m.undefined&&(n=this._def.defaultValue()),this._def.innerType._parse({data:n,path:t.path,parent:t})}removeDefault(){return this._def.innerType}};Ne.create=(r,e)=>new Ne({innerType:r,typeName:g.ZodDefault,defaultValue:typeof e.default=="function"?e.default:()=>e.default,..._(e)});var Le=class extends x{_parse(e){let{ctx:t}=this._processInputParams(e),n={...t,common:{...t.common,issues:[]}},i=this._def.innerType._parse({data:n.data,path:n.path,parent:{...n}});return yt(i)?i.then(o=>({status:"valid",value:o.status==="valid"?o.value:this._def.catchValue({get error(){return new z(n.common.issues)},input:n.data})})):{status:"valid",value:i.status==="valid"?i.value:this._def.catchValue({get error(){return new z(n.common.issues)},input:n.data})}}removeCatch(){return this._def.innerType}};Le.create=(r,e)=>new Le({innerType:r,typeName:g.ZodCatch,catchValue:typeof e.catch=="function"?e.catch:()=>e.catch,..._(e)});var it=class extends x{_parse(e){if(this._getType(e)!==m.nan){let n=this._getOrReturnCtx(e);return h(n,{code:f.invalid_type,expected:m.nan,received:n.parsedType}),b}return{status:"valid",value:e.data}}};it.create=r=>new it({typeName:g.ZodNaN,..._(r)});var zo=Symbol("zod_brand"),gt=class extends x{_parse(e){let{ctx:t}=this._processInputParams(e),n=t.data;return this._def.type._parse({data:n,path:t.path,parent:t})}unwrap(){return this._def.type}},bt=class r extends x{_parse(e){let{status:t,ctx:n}=this._processInputParams(e);if(n.common.async)return(async()=>{let o=await this._def.in._parseAsync({data:n.data,path:n.path,parent:n});return o.status==="aborted"?b:o.status==="dirty"?(t.dirty(),Xe(o.value)):this._def.out._parseAsync({data:o.value,path:n.path,parent:n})})();{let i=this._def.in._parseSync({data:n.data,path:n.path,parent:n});return i.status==="aborted"?b:i.status==="dirty"?(t.dirty(),{status:"dirty",value:i.value}):this._def.out._parseSync({data:i.value,path:n.path,parent:n})}}static create(e,t){return new r({in:e,out:t,typeName:g.ZodPipeline})}},Ue=class extends x{_parse(e){let t=this._def.innerType._parse(e),n=i=>(ke(i)&&(i.value=Object.freeze(i.value)),i);return yt(t)?t.then(i=>n(i)):n(t)}unwrap(){return this._def.innerType}};Ue.create=(r,e)=>new Ue({innerType:r,typeName:g.ZodReadonly,..._(e)});function Wn(r,e){let t=typeof r=="function"?r(e):typeof r=="string"?{message:r}:r;return typeof t=="string"?{message:t}:t}function Xn(r,e={},t){return r?pe.create().superRefine((n,i)=>{var o,s;let c=r(n);if(c instanceof Promise)return c.then(l=>{var d,u;if(!l){let p=Wn(e,n),S=(u=(d=p.fatal)!==null&&d!==void 0?d:t)!==null&&u!==void 0?u:!0;i.addIssue({code:"custom",...p,fatal:S})}});if(!c){let l=Wn(e,n),d=(s=(o=l.fatal)!==null&&o!==void 0?o:t)!==null&&s!==void 0?s:!0;i.addIssue({code:"custom",...l,fatal:d})}}):pe.create()}var Zo={object:M.lazycreate},g;(function(r){r.ZodString="ZodString",r.ZodNumber="ZodNumber",r.ZodNaN="ZodNaN",r.ZodBigInt="ZodBigInt",r.ZodBoolean="ZodBoolean",r.ZodDate="ZodDate",r.ZodSymbol="ZodSymbol",r.ZodUndefined="ZodUndefined",r.ZodNull="ZodNull",r.ZodAny="ZodAny",r.ZodUnknown="ZodUnknown",r.ZodNever="ZodNever",r.ZodVoid="ZodVoid",r.ZodArray="ZodArray",r.ZodObject="ZodObject",r.ZodUnion="ZodUnion",r.ZodDiscriminatedUnion="ZodDiscriminatedUnion",r.ZodIntersection="ZodIntersection",r.ZodTuple="ZodTuple",r.ZodRecord="ZodRecord",r.ZodMap="ZodMap",r.ZodSet="ZodSet",r.ZodFunction="ZodFunction",r.ZodLazy="ZodLazy",r.ZodLiteral="ZodLiteral",r.ZodEnum="ZodEnum",r.ZodEffects="ZodEffects",r.ZodNativeEnum="ZodNativeEnum",r.ZodOptional="ZodOptional",r.ZodNullable="ZodNullable",r.ZodDefault="ZodDefault",r.ZodCatch="ZodCatch",r.ZodPromise="ZodPromise",r.ZodBranded="ZodBranded",r.ZodPipeline="ZodPipeline",r.ZodReadonly="ZodReadonly"})(g||(g={}));var Fo=(r,e={message:`Input not instance of ${r.name}`})=>Xn(t=>t instanceof r,e),Qn=fe.create,ei=Te.create,Vo=it.create,Wo=Ae.create,ti=Ee.create,Bo=Oe.create,Ho=et.create,qo=Ce.create,Go=$e.create,Yo=pe.create,Jo=oe.create,Ko=J.create,Xo=tt.create,Qo=se.create,es=M.create,ts=M.strictCreate,rs=je.create,ns=ir.create,is=Re.create,os=ee.create,ss=or.create,as=rt.create,cs=nt.create,ls=sr.create,ds=Ie.create,us=De.create,fs=Pe.create,ps=Me.create,hs=he.create,Bn=Z.create,ms=V.create,vs=te.create,ys=Z.createWithPreprocess,gs=bt.create,bs=()=>Qn().optional(),_s=()=>ei().optional(),xs=()=>ti().optional(),Ss={string:(r=>fe.create({...r,coerce:!0})),number:(r=>Te.create({...r,coerce:!0})),boolean:(r=>Ee.create({...r,coerce:!0})),bigint:(r=>Ae.create({...r,coerce:!0})),date:(r=>Oe.create({...r,coerce:!0}))},ws=b,a=Object.freeze({__proto__:null,defaultErrorMap:Qe,setErrorMap:yo,getErrorMap:tr,makeIssue:rr,EMPTY_PATH:go,addIssueToContext:h,ParseStatus:D,INVALID:b,DIRTY:Xe,OK:P,isAborted:Vr,isDirty:Wr,isValid:ke,isAsync:yt,get util(){return T},get objectUtil(){return Fr},ZodParsedType:m,getParsedType:ie,ZodType:x,datetimeRegex:Jn,ZodString:fe,ZodNumber:Te,ZodBigInt:Ae,ZodBoolean:Ee,ZodDate:Oe,ZodSymbol:et,ZodUndefined:Ce,ZodNull:$e,ZodAny:pe,ZodUnknown:oe,ZodNever:J,ZodVoid:tt,ZodArray:se,ZodObject:M,ZodUnion:je,ZodDiscriminatedUnion:ir,ZodIntersection:Re,ZodTuple:ee,ZodRecord:or,ZodMap:rt,ZodSet:nt,ZodFunction:sr,ZodLazy:Ie,ZodLiteral:De,ZodEnum:Pe,ZodNativeEnum:Me,ZodPromise:he,ZodEffects:Z,ZodTransformer:Z,ZodOptional:V,ZodNullable:te,ZodDefault:Ne,ZodCatch:Le,ZodNaN:it,BRAND:zo,ZodBranded:gt,ZodPipeline:bt,ZodReadonly:Ue,custom:Xn,Schema:x,ZodSchema:x,late:Zo,get ZodFirstPartyTypeKind(){return g},coerce:Ss,any:Yo,array:Qo,bigint:Wo,boolean:ti,date:Bo,discriminatedUnion:ns,effect:Bn,enum:fs,function:ls,instanceof:Fo,intersection:is,lazy:ds,literal:us,map:as,nan:Vo,nativeEnum:ps,never:Ko,null:Go,nullable:vs,number:ei,object:es,oboolean:xs,onumber:_s,optional:ms,ostring:bs,pipeline:gs,preprocess:ys,promise:hs,record:ss,set:cs,strictObject:ts,string:Qn,symbol:Ho,transformer:Bn,tuple:os,undefined:qo,union:rs,unknown:Jo,void:Xo,NEVER:ws,ZodIssueCode:f,quotelessJson:vo,ZodError:z});var oi=(r=>(r.Info="info",r.Debug="debug",r.Trace="trace",r.Error="error",r))(oi||{}),si=(r=>(r.Changed="Changed",r.Added="Added",r.Removed="Removed",r))(si||{}),ai=(r=>(r.External="BSLIVE_EXTERNAL",r))(ai||{}),ks=a.string(),Ts=a.object({dir:a.string()}),_t=a.lazy(()=>a.object({id:a.string(),label:a.string(),nodes:a.array(_t)})),As=a.nativeEnum(oi),ri=a.object({log_level:As}),Es=a.object({ws_path:a.string(),host:a.string().optional()}),Os=a.object({kind:a.string(),ms:a.string()}),Cs=a.object({message:a.string(),reason:a.string().optional()}),ni=a.object({path:a.string()}),$s=a.object({paths:a.array(a.string())}),ae=a.discriminatedUnion("kind",[a.object({kind:a.literal("Both"),payload:a.object({name:a.string(),bind_address:a.string()})}),a.object({kind:a.literal("Address"),payload:a.object({bind_address:a.string()})}),a.object({kind:a.literal("Named"),payload:a.object({name:a.string()})}),a.object({kind:a.literal("Port"),payload:a.object({port:a.number()})}),a.object({kind:a.literal("PortNamed"),payload:a.object({port:a.number(),name:a.string()})})]),js=a.object({id:a.string(),identity:ae,socket_addr:a.string()}),Rs=a.object({servers:a.array(js)}),ci=a.object({connect:Es,ctx_message:a.string()}),Is=a.object({path:a.string()}),Ds=a.object({error:a.string()}),Ps=a.object({absolute_paths:a.string(),relative_paths:a.string()}),li=a.discriminatedUnion("kind",[a.object({kind:a.literal("Pending"),payload:a.undefined().optional()}),a.object({kind:a.literal("Waiting"),payload:a.object({reason:a.string()})}),a.object({kind:a.literal("Ready"),payload:a.undefined().optional()}),a.object({kind:a.literal("Failed"),payload:a.object({reason:a.string()})})]),Ms=a.object({server:ae,dir:a.string()}),Ns=a.object({server:ae,dir:a.string()}),Ls=a.discriminatedUnion("kind",[a.object({kind:a.literal("Server"),payload:Ms}),a.object({kind:a.literal("Route"),payload:Ns}),a.object({kind:a.literal("Any"),payload:Ts}),a.object({kind:a.literal("Input"),payload:Ps})]),Us=a.object({body:a.string()}),zs=a.discriminatedUnion("kind",[a.object({kind:a.literal("Html"),payload:a.object({html:a.string()})}),a.object({kind:a.literal("Json"),payload:a.object({json_str:a.string()})}),a.object({kind:a.literal("Raw"),payload:a.object({raw:a.string()})}),a.object({kind:a.literal("Sse"),payload:a.object({sse:Us})}),a.object({kind:a.literal("Proxy"),payload:a.object({proxy:a.string()})}),a.object({kind:a.literal("Dir"),payload:a.object({dir:a.string(),base:a.string().optional()})})]),ii=a.object({path:a.string(),kind_str:a.string()}),Zs=a.discriminatedUnion("kind",[a.object({kind:a.literal("Stopped"),payload:a.object({bind_address:a.string()})}),a.object({kind:a.literal("Started"),payload:a.undefined().optional()}),a.object({kind:a.literal("Patched"),payload:a.undefined().optional()}),a.object({kind:a.literal("Errored"),payload:a.object({error:a.string()})})]),Fs=a.object({identity:ae,change:Zs}),lf=a.object({items:a.array(Fs)}),Vs=a.discriminatedUnion("kind",[a.object({kind:a.literal("Created"),payload:a.object({identity:ae,socket_addr:a.string()})}),a.object({kind:a.literal("Stopped"),payload:a.object({identity:ae})}),a.object({kind:a.literal("CreateErr"),payload:a.object({error:a.string()})}),a.object({kind:a.literal("Patched"),payload:a.object({identity:ae,added:a.array(ii),changed:a.array(ii)})}),a.object({kind:a.literal("PatchErr"),payload:a.object({identity:ae,error:a.string()})})]),Ws=a.object({changeset:a.array(Vs),servers_resp:Rs}),Bs=a.object({path:a.string(),kind:zs}),Hs=a.object({status:li,server:ae}),qs=a.object({error:a.string()}),Gs=a.object({line:a.string(),prefix:a.string().optional()}),Ys=a.object({line:a.string(),prefix:a.string().optional()}),Js=a.union([a.object({kind:a.literal("Ok"),payload:a.undefined().optional()}),a.object({kind:a.literal("Err"),payload:a.string()}),a.object({kind:a.literal("Cancelled"),payload:a.undefined().optional()})]),Ks=a.object({tree:_t,will_exec:a.boolean()}),Xs=a.nativeEnum(si),cr=a.lazy(()=>a.discriminatedUnion("kind",[a.object({kind:a.literal("Fs"),payload:a.object({path:a.string(),change_kind:Xs})}),a.object({kind:a.literal("FsMany"),payload:a.array(cr)})])),df=a.discriminatedUnion("kind",[a.object({kind:a.literal("Change"),payload:cr}),a.object({kind:a.literal("WsConnection"),payload:ri}),a.object({kind:a.literal("Config"),payload:ri}),a.object({kind:a.literal("DisplayMessage"),payload:Cs})]),uf=a.nativeEnum(ai),Qs=a.discriminatedUnion("kind",[a.object({kind:a.literal("Stdout"),payload:Ys}),a.object({kind:a.literal("Stderr"),payload:Gs})]),ff=a.discriminatedUnion("kind",[a.object({kind:a.literal("MissingInputs"),payload:a.string()}),a.object({kind:a.literal("InvalidInput"),payload:a.string()}),a.object({kind:a.literal("NotFound"),payload:a.string()}),a.object({kind:a.literal("InputWriteError"),payload:a.string()}),a.object({kind:a.literal("PathError"),payload:a.string()}),a.object({kind:a.literal("PortError"),payload:a.string()}),a.object({kind:a.literal("DirError"),payload:a.string()}),a.object({kind:a.literal("YamlError"),payload:a.string()}),a.object({kind:a.literal("MarkdownError"),payload:a.string()}),a.object({kind:a.literal("HtmlError"),payload:a.string()}),a.object({kind:a.literal("Io"),payload:a.string()}),a.object({kind:a.literal("UnsupportedExtension"),payload:a.string()}),a.object({kind:a.literal("MissingExtension"),payload:a.string()}),a.object({kind:a.literal("EmptyInput"),payload:a.string()}),a.object({kind:a.literal("BsLiveRules"),payload:a.string()})]),pf=a.discriminatedUnion("kind",[a.object({kind:a.literal("Started"),payload:a.undefined().optional()}),a.object({kind:a.literal("FailedStartup"),payload:a.string()})]),ea=a.object({status:li,watchable:Ls,debounce:Os}),hf=a.object({routes:a.array(Bs),id:a.string()}),ta=a.discriminatedUnion("kind",[a.object({kind:a.literal("Server"),payload:Hs}),a.object({kind:a.literal("PathMonitor"),payload:ea})]),ra=a.lazy(()=>a.discriminatedUnion("kind",[a.object({kind:a.literal("Started"),payload:a.object({tree:_t})}),a.object({kind:a.literal("Ended"),payload:a.object({tree:_t,report:ar,report_map:a.record(ar)})}),a.object({kind:a.literal("Error"),payload:a.undefined().optional()})])),ar=a.lazy(()=>a.object({result:ia})),na=a.lazy(()=>a.object({stage:ra})),ia=a.lazy(()=>a.object({conclusion:Js,invocation_id:ks,task_reports:a.array(ar)})),oa=a.lazy(()=>a.object({tree:_t,report_map:a.record(ar)})),mf=a.lazy(()=>a.discriminatedUnion("kind",[a.object({kind:a.literal("FileChanged"),payload:ni}),a.object({kind:a.literal("FilesChanged"),payload:$s}),a.object({kind:a.literal("OutputLine"),payload:Qs}),a.object({kind:a.literal("InputFileChanged"),payload:ni}),a.object({kind:a.literal("InputAccepted"),payload:Is}),a.object({kind:a.literal("InputError"),payload:Ds}),a.object({kind:a.literal("StartupError"),payload:qs}),a.object({kind:a.literal("ServerChangeset"),payload:Ws}),a.object({kind:a.literal("TaskAction"),payload:na}),a.object({kind:a.literal("TaskTreePreview"),payload:Ks}),a.object({kind:a.literal("TaskTreeSummary"),payload:oa}),a.object({kind:a.literal("Transition"),payload:ta})]));var di=[{selector:"background",styleNames:["backgroundImage"]},{selector:"border",styleNames:["borderImage","webkitBorderImage","MozBorderImage"]}],lr={stylesheetReloadTimeout:15e3},sa=/\.(jpe?g|png|gif|svg)$/i,dr=class{constructor(e,t,n){this.window=e,this.console=t,this.Timer=n,this.document=this.window.document,this.importCacheWaitPeriod=200,this.plugins=[]}addPlugin(e){return this.plugins.push(e)}analyze(e){}reload(e,t={}){if(this.options={...lr,...t},!(t.liveCSS&&e.match(/\.css(?:\.map)?$/i)&&this.reloadStylesheet(e))){if(t.liveImg&&e.match(sa)){this.reloadImages(e);return}if(t.isChromeExtension){this.reloadChromeExtension();return}return this.reloadPage()}}reloadPage(){return this.window.document.location.reload()}reloadChromeExtension(){return this.window.chrome.runtime.reload()}reloadImages(e){let t,n=this.generateUniqueString();for(t of Array.from(this.document.images))ui(e,Hr(t.src))&&(t.src=this.generateCacheBustUrl(t.src,n));if(this.document.querySelectorAll)for(let{selector:i,styleNames:o}of di)for(t of Array.from(this.document.querySelectorAll(`[style*=${i}]`)))this.reloadStyleImages(t.style,o,e,n);if(this.document.styleSheets)return Array.from(this.document.styleSheets).map(i=>this.reloadStylesheetImages(i,e,n))}reloadStylesheetImages(e,t,n){let i;try{i=(e||{}).cssRules}catch{}if(i)for(let o of Array.from(i))switch(o.type){case CSSRule.IMPORT_RULE:this.reloadStylesheetImages(o.styleSheet,t,n);break;case CSSRule.STYLE_RULE:for(let{styleNames:s}of di)this.reloadStyleImages(o.style,s,t,n);break;case CSSRule.MEDIA_RULE:this.reloadStylesheetImages(o,t,n);break}}reloadStyleImages(e,t,n,i){for(let o of t){let s=e[o];if(typeof s=="string"){let c=s.replace(new RegExp("\\burl\\s*\\(([^)]*)\\)"),(l,d)=>ui(n,Hr(d))?`url(${this.generateCacheBustUrl(d,i)})`:l);c!==s&&(e[o]=c)}}}reloadStylesheet(e){let t=this.options||lr,n,i,o=(()=>{let l=[];for(i of Array.from(this.document.getElementsByTagName("link")))i.rel.match(/^stylesheet$/i)&&!i.__LiveReload_pendingRemoval&&l.push(i);return l})(),s=[];for(n of Array.from(this.document.getElementsByTagName("style")))n.sheet&&this.collectImportedStylesheets(n,n.sheet,s);for(i of Array.from(o))this.collectImportedStylesheets(i,i.sheet,s);if(this.window.StyleFix&&this.document.querySelectorAll)for(n of Array.from(this.document.querySelectorAll("style[data-href]")))o.push(n);this.console.debug(`found ${o.length} LINKed stylesheets, ${s.length} @imported stylesheets`);let c=aa(e,o.concat(s),l=>Hr(this.linkHref(l)));if(c)c.object.rule?(this.console.debug(`is reloading imported stylesheet: ${c.object.href}`),this.reattachImportedRule(c.object)):(this.console.debug(`is reloading stylesheet: ${this.linkHref(c.object)}`),this.reattachStylesheetLink(c.object));else if(t.reloadMissingCSS){this.console.debug(`will reload all stylesheets because path '${e}' did not match any specific one. To disable this behavior, set 'options.reloadMissingCSS' to 'false'.`);for(i of Array.from(o))this.reattachStylesheetLink(i)}else this.console.debug(`will not reload path '${e}' because the stylesheet was not found on the page and 'options.reloadMissingCSS' was set to 'false'.`);return!0}collectImportedStylesheets(e,t,n){let i;try{i=(t||{}).cssRules}catch{}if(i&&i.length)for(let o=0;o{if(!i)return i=!0,t()};if(e.onload=()=>(this.console.debug("the new stylesheet has finished loading"),this.knownToSupportCssOnLoad=!0,o()),!this.knownToSupportCssOnLoad){let s;(s=()=>e.sheet?(this.console.debug("is polling until the new CSS finishes loading..."),o()):this.Timer.start(50,s))()}return this.Timer.start(n.stylesheetReloadTimeout,o)}linkHref(e){return e.href||e.getAttribute&&e.getAttribute("data-href")}reattachStylesheetLink(e){let t;if(e.__LiveReload_pendingRemoval)return;e.__LiveReload_pendingRemoval=!0,e.tagName==="STYLE"?(t=this.document.createElement("link"),t.rel="stylesheet",t.media=e.media,t.disabled=e.disabled):t=e.cloneNode(!1),t.href=this.generateCacheBustUrl(this.linkHref(e));let n=e.parentNode;return n.lastChild===e?n.appendChild(t):n.insertBefore(t,e.nextSibling),this.waitUntilCssLoads(t,()=>{let i;return/AppleWebKit/.test(this.window.navigator.userAgent)?i=5:i=200,this.Timer.start(i,()=>{if(e.parentNode)return e.parentNode.removeChild(e),t.onreadystatechange=null,this.window.StyleFix?this.window.StyleFix.link(t):void 0})})}reattachImportedRule({rule:e,index:t,link:n}){let i=e.parentStyleSheet,o=this.generateCacheBustUrl(e.href),s=e.media.length?[].join.call(e.media,", "):"",c=`@import url("${o}") ${s};`;e.__LiveReload_newHref=o;let l=this.document.createElement("link");return l.rel="stylesheet",l.href=o,l.__LiveReload_pendingRemoval=!0,n.parentNode&&n.parentNode.insertBefore(l,n),this.Timer.start(this.importCacheWaitPeriod,()=>{if(l.parentNode&&l.parentNode.removeChild(l),e.__LiveReload_newHref===o)return i.insertRule(c,t),i.deleteRule(t+1),e=i.cssRules[t],e.__LiveReload_newHref=o,this.Timer.start(this.importCacheWaitPeriod,()=>{if(e.__LiveReload_newHref===o)return i.insertRule(c,t),i.deleteRule(t+1)})})}generateUniqueString(){return`livereload=${Date.now()}`}generateCacheBustUrl(e,t){let n=this.options||lr,i,o;if(t||(t=this.generateUniqueString()),{url:e,hash:i,params:o}=fi(e),n.overrideURL&&e.indexOf(n.serverURL)<0){let c=e;e=n.serverURL+n.overrideURL+"?url="+encodeURIComponent(e),this.console.debug(`is overriding source URL ${c} with ${e}`)}let s=o.replace(/(\?|&)livereload=(\d+)/,(c,l)=>`${l}${t}`);return s===o&&(o.length===0?s=`?${t}`:s=`${o}&${t}`),e+s+i}};function fi(r){let e="",t="",n=r.indexOf("#");n>=0&&(e=r.slice(n),r=r.slice(0,n));let i=r.indexOf("??");return i>=0?i+1!==r.lastIndexOf("?")&&(n=r.lastIndexOf("?")):n=r.indexOf("?"),n>=0&&(t=r.slice(n),r=r.slice(0,n)),{url:r,params:t,hash:e}}function Hr(r){if(!r)return"";let e;return{url:r}=fi(r),r.indexOf("file://")===0?e=r.replace(new RegExp("^file://(localhost)?"),""):e=r.replace(new RegExp("^([^:]+:)?//([^:/]+)(:\\d*)?/"),"/"),decodeURIComponent(e)}function pi(r,e){if(r=r.replace(/^\/+/,"").toLowerCase(),e=e.replace(/^\/+/,"").toLowerCase(),r===e)return 1e4;let t=r.split(/\/|\\/).reverse(),n=e.split(/\/|\\/).reverse(),i=Math.min(t.length,n.length),o=0;for(;on){let n,i={score:0};for(let o of e)n=pi(r,t(o)),n>i.score&&(i={object:o,score:n});return i.score===0?null:i}function ui(r,e){return pi(r,e)>0}var vi=Ji(mi(),1);var ca=/\.(jpe?g|png|gif|svg)$/i;function qr(r,e,t){switch(r.kind){case"FsMany":{if(r.payload.some(i=>{switch(i.kind){case"Fs":return!(i.payload.path.match(/\.css(?:\.map)?$/i)||i.payload.path.match(ca));case"FsMany":throw new Error("unreachable")}}))return window.__playwright?.record?window.__playwright?.record({kind:"reloadPage"}):t.reloadPage();for(let i of r.payload)qr(i,e,t);break}case"Fs":{let n=r.payload.path,i={liveCSS:!0,liveImg:!0,reloadMissingCSS:!0,originalPath:"",overrideURL:"",serverURL:""};window.__playwright?.record?window.__playwright?.record({kind:"reload",args:{path:n,opts:i}}):(e.trace("will reload a file with path ",n),t.reload(n,i))}}}var Gr={name:"dom plugin",globalSetup:(r,e)=>{let t=new dr(window,e,vi.Timer);return[r,[e,t]]},resetSink(r,e,t){let[n,i]=e;return r.pipe(ue(o=>o.kind==="Change"),Q(o=>o.payload),we(o=>{n.trace("incoming message",JSON.stringify({change:o,config:t},null,2));let s=cr.parse(o);qr(s,n,i)}),Se())}};var fr=globalThis,pr=fr.ShadowRoot&&(fr.ShadyCSS===void 0||fr.ShadyCSS.nativeShadow)&&"adoptedStyleSheets"in Document.prototype&&"replace"in CSSStyleSheet.prototype,Yr=Symbol(),yi=new WeakMap,xt=class{constructor(e,t,n){if(this._$cssResult$=!0,n!==Yr)throw Error("CSSResult is not constructable. Use `unsafeCSS` or `css` instead.");this.cssText=e,this.t=t}get styleSheet(){let e=this.o,t=this.t;if(pr&&e===void 0){let n=t!==void 0&&t.length===1;n&&(e=yi.get(t)),e===void 0&&((this.o=e=new CSSStyleSheet).replaceSync(this.cssText),n&&yi.set(t,e))}return e}toString(){return this.cssText}},gi=r=>new xt(typeof r=="string"?r:r+"",void 0,Yr),K=(r,...e)=>{let t=r.length===1?r[0]:e.reduce((n,i,o)=>n+(s=>{if(s._$cssResult$===!0)return s.cssText;if(typeof s=="number")return s;throw Error("Value passed to 'css' function must be a 'css' function result: "+s+". Use 'unsafeCSS' to pass non-literal values, but take care to ensure page security.")})(i)+r[o+1],r[0]);return new xt(t,r,Yr)},bi=(r,e)=>{if(pr)r.adoptedStyleSheets=e.map(t=>t instanceof CSSStyleSheet?t:t.styleSheet);else for(let t of e){let n=document.createElement("style"),i=fr.litNonce;i!==void 0&&n.setAttribute("nonce",i),n.textContent=t.cssText,r.appendChild(n)}},Jr=pr?r=>r:r=>r instanceof CSSStyleSheet?(e=>{let t="";for(let n of e.cssRules)t+=n.cssText;return gi(t)})(r):r;var{is:la,defineProperty:da,getOwnPropertyDescriptor:ua,getOwnPropertyNames:fa,getOwnPropertySymbols:pa,getPrototypeOf:ha}=Object,hr=globalThis,_i=hr.trustedTypes,ma=_i?_i.emptyScript:"",va=hr.reactiveElementPolyfillSupport,St=(r,e)=>r,wt={toAttribute(r,e){switch(e){case Boolean:r=r?ma:null;break;case Object:case Array:r=r==null?r:JSON.stringify(r)}return r},fromAttribute(r,e){let t=r;switch(e){case Boolean:t=r!==null;break;case Number:t=r===null?null:Number(r);break;case Object:case Array:try{t=JSON.parse(r)}catch{t=null}}return t}},mr=(r,e)=>!la(r,e),xi={attribute:!0,type:String,converter:wt,reflect:!1,useDefault:!1,hasChanged:mr};Symbol.metadata??=Symbol("metadata"),hr.litPropertyMetadata??=new WeakMap;var ce=class extends HTMLElement{static addInitializer(e){this._$Ei(),(this.l??=[]).push(e)}static get observedAttributes(){return this.finalize(),this._$Eh&&[...this._$Eh.keys()]}static createProperty(e,t=xi){if(t.state&&(t.attribute=!1),this._$Ei(),this.prototype.hasOwnProperty(e)&&((t=Object.create(t)).wrapped=!0),this.elementProperties.set(e,t),!t.noAccessor){let n=Symbol(),i=this.getPropertyDescriptor(e,n,t);i!==void 0&&da(this.prototype,e,i)}}static getPropertyDescriptor(e,t,n){let{get:i,set:o}=ua(this.prototype,e)??{get(){return this[t]},set(s){this[t]=s}};return{get:i,set(s){let c=i?.call(this);o?.call(this,s),this.requestUpdate(e,c,n)},configurable:!0,enumerable:!0}}static getPropertyOptions(e){return this.elementProperties.get(e)??xi}static _$Ei(){if(this.hasOwnProperty(St("elementProperties")))return;let e=ha(this);e.finalize(),e.l!==void 0&&(this.l=[...e.l]),this.elementProperties=new Map(e.elementProperties)}static finalize(){if(this.hasOwnProperty(St("finalized")))return;if(this.finalized=!0,this._$Ei(),this.hasOwnProperty(St("properties"))){let t=this.properties,n=[...fa(t),...pa(t)];for(let i of n)this.createProperty(i,t[i])}let e=this[Symbol.metadata];if(e!==null){let t=litPropertyMetadata.get(e);if(t!==void 0)for(let[n,i]of t)this.elementProperties.set(n,i)}this._$Eh=new Map;for(let[t,n]of this.elementProperties){let i=this._$Eu(t,n);i!==void 0&&this._$Eh.set(i,t)}this.elementStyles=this.finalizeStyles(this.styles)}static finalizeStyles(e){let t=[];if(Array.isArray(e)){let n=new Set(e.flat(1/0).reverse());for(let i of n)t.unshift(Jr(i))}else e!==void 0&&t.push(Jr(e));return t}static _$Eu(e,t){let n=t.attribute;return n===!1?void 0:typeof n=="string"?n:typeof e=="string"?e.toLowerCase():void 0}constructor(){super(),this._$Ep=void 0,this.isUpdatePending=!1,this.hasUpdated=!1,this._$Em=null,this._$Ev()}_$Ev(){this._$ES=new Promise(e=>this.enableUpdating=e),this._$AL=new Map,this._$E_(),this.requestUpdate(),this.constructor.l?.forEach(e=>e(this))}addController(e){(this._$EO??=new Set).add(e),this.renderRoot!==void 0&&this.isConnected&&e.hostConnected?.()}removeController(e){this._$EO?.delete(e)}_$E_(){let e=new Map,t=this.constructor.elementProperties;for(let n of t.keys())this.hasOwnProperty(n)&&(e.set(n,this[n]),delete this[n]);e.size>0&&(this._$Ep=e)}createRenderRoot(){let e=this.shadowRoot??this.attachShadow(this.constructor.shadowRootOptions);return bi(e,this.constructor.elementStyles),e}connectedCallback(){this.renderRoot??=this.createRenderRoot(),this.enableUpdating(!0),this._$EO?.forEach(e=>e.hostConnected?.())}enableUpdating(e){}disconnectedCallback(){this._$EO?.forEach(e=>e.hostDisconnected?.())}attributeChangedCallback(e,t,n){this._$AK(e,n)}_$ET(e,t){let n=this.constructor.elementProperties.get(e),i=this.constructor._$Eu(e,n);if(i!==void 0&&n.reflect===!0){let o=(n.converter?.toAttribute!==void 0?n.converter:wt).toAttribute(t,n.type);this._$Em=e,o==null?this.removeAttribute(i):this.setAttribute(i,o),this._$Em=null}}_$AK(e,t){let n=this.constructor,i=n._$Eh.get(e);if(i!==void 0&&this._$Em!==i){let o=n.getPropertyOptions(i),s=typeof o.converter=="function"?{fromAttribute:o.converter}:o.converter?.fromAttribute!==void 0?o.converter:wt;this._$Em=i;let c=s.fromAttribute(t,o.type);this[i]=c??this._$Ej?.get(i)??c,this._$Em=null}}requestUpdate(e,t,n,i=!1,o){if(e!==void 0){let s=this.constructor;if(i===!1&&(o=this[e]),n??=s.getPropertyOptions(e),!((n.hasChanged??mr)(o,t)||n.useDefault&&n.reflect&&o===this._$Ej?.get(e)&&!this.hasAttribute(s._$Eu(e,n))))return;this.C(e,t,n)}this.isUpdatePending===!1&&(this._$ES=this._$EP())}C(e,t,{useDefault:n,reflect:i,wrapped:o},s){n&&!(this._$Ej??=new Map).has(e)&&(this._$Ej.set(e,s??t??this[e]),o!==!0||s!==void 0)||(this._$AL.has(e)||(this.hasUpdated||n||(t=void 0),this._$AL.set(e,t)),i===!0&&this._$Em!==e&&(this._$Eq??=new Set).add(e))}async _$EP(){this.isUpdatePending=!0;try{await this._$ES}catch(t){Promise.reject(t)}let e=this.scheduleUpdate();return e!=null&&await e,!this.isUpdatePending}scheduleUpdate(){return this.performUpdate()}performUpdate(){if(!this.isUpdatePending)return;if(!this.hasUpdated){if(this.renderRoot??=this.createRenderRoot(),this._$Ep){for(let[i,o]of this._$Ep)this[i]=o;this._$Ep=void 0}let n=this.constructor.elementProperties;if(n.size>0)for(let[i,o]of n){let{wrapped:s}=o,c=this[i];s!==!0||this._$AL.has(i)||c===void 0||this.C(i,void 0,o,c)}}let e=!1,t=this._$AL;try{e=this.shouldUpdate(t),e?(this.willUpdate(t),this._$EO?.forEach(n=>n.hostUpdate?.()),this.update(t)):this._$EM()}catch(n){throw e=!1,this._$EM(),n}e&&this._$AE(t)}willUpdate(e){}_$AE(e){this._$EO?.forEach(t=>t.hostUpdated?.()),this.hasUpdated||(this.hasUpdated=!0,this.firstUpdated(e)),this.updated(e)}_$EM(){this._$AL=new Map,this.isUpdatePending=!1}get updateComplete(){return this.getUpdateComplete()}getUpdateComplete(){return this._$ES}shouldUpdate(e){return!0}update(e){this._$Eq&&=this._$Eq.forEach(t=>this._$ET(t,this[t])),this._$EM()}updated(e){}firstUpdated(e){}};ce.elementStyles=[],ce.shadowRootOptions={mode:"open"},ce[St("elementProperties")]=new Map,ce[St("finalized")]=new Map,va?.({ReactiveElement:ce}),(hr.reactiveElementVersions??=[]).push("2.1.2");var Xr=globalThis,Si=r=>r,vr=Xr.trustedTypes,wi=vr?vr.createPolicy("lit-html",{createHTML:r=>r}):void 0,Qr="$lit$",le=`lit$${Math.random().toFixed(9).slice(2)}$`,en="?"+le,ya=`<${en}>`,Fe=document,Tt=()=>Fe.createComment(""),At=r=>r===null||typeof r!="object"&&typeof r!="function",tn=Array.isArray,Ci=r=>tn(r)||typeof r?.[Symbol.iterator]=="function",Kr=`[ +\f\r]`,kt=/<(?:(!--|\/[^a-zA-Z])|(\/?[a-zA-Z][^>\s]*)|(\/?$))/g,ki=/-->/g,Ti=/>/g,ze=RegExp(`>|${Kr}(?:([^\\s"'>=/]+)(${Kr}*=${Kr}*(?:[^ +\f\r"'\`<>=]|("|')|))|$)`,"g"),Ai=/'/g,Ei=/"/g,$i=/^(?:script|style|textarea|title)$/i,rn=r=>(e,...t)=>({_$litType$:r,strings:e,values:t}),N=rn(1),$f=rn(2),jf=rn(3),Ve=Symbol.for("lit-noChange"),O=Symbol.for("lit-nothing"),Oi=new WeakMap,Ze=Fe.createTreeWalker(Fe,129);function ji(r,e){if(!tn(r)||!r.hasOwnProperty("raw"))throw Error("invalid template strings array");return wi!==void 0?wi.createHTML(e):e}var Ri=(r,e)=>{let t=r.length-1,n=[],i,o=e===2?"":e===3?"":"",s=kt;for(let c=0;c"?(s=i??kt,p=-1):u[1]===void 0?p=-2:(p=s.lastIndex-u[2].length,d=u[1],s=u[3]===void 0?ze:u[3]==='"'?Ei:Ai):s===Ei||s===Ai?s=ze:s===ki||s===Ti?s=kt:(s=ze,i=void 0);let y=s===ze&&r[c+1].startsWith("/>")?" ":"";o+=s===kt?l+ya:p>=0?(n.push(d),l.slice(0,p)+Qr+l.slice(p)+le+y):l+le+(p===-2?c:y)}return[ji(r,o+(r[t]||"")+(e===2?"":e===3?"":"")),n]},Et=class r{constructor({strings:e,_$litType$:t},n){let i;this.parts=[];let o=0,s=0,c=e.length-1,l=this.parts,[d,u]=Ri(e,t);if(this.el=r.createElement(d,n),Ze.currentNode=this.el.content,t===2||t===3){let p=this.el.content.firstChild;p.replaceWith(...p.childNodes)}for(;(i=Ze.nextNode())!==null&&l.length0){i.textContent=vr?vr.emptyScript:"";for(let y=0;y2||n[0]!==""||n[1]!==""?(this._$AH=Array(n.length-1).fill(new String),this.strings=n):this._$AH=O}_$AI(e,t=this,n,i){let o=this.strings,s=!1;if(o===void 0)e=We(this,e,t,0),s=!At(e)||e!==this._$AH&&e!==Ve,s&&(this._$AH=e);else{let c=e,l,d;for(e=o[0],l=0;l{let n=t?.renderBefore??e,i=n._$litPart$;if(i===void 0){let o=t?.renderBefore??null;n._$litPart$=i=new ot(e.insertBefore(Tt(),o),o,void 0,t??{})}return i._$AI(r),i};var nn=globalThis,L=class extends ce{constructor(){super(...arguments),this.renderOptions={host:this},this._$Do=void 0}createRenderRoot(){let e=super.createRenderRoot();return this.renderOptions.renderBefore??=e.firstChild,e}update(e){let t=this.render();this.hasUpdated||(this.renderOptions.isConnected=this.isConnected),super.update(e),this._$Do=Sr(t,this.renderRoot,this.renderOptions)}connectedCallback(){super.connectedCallback(),this._$Do?.setConnected(!0)}disconnectedCallback(){super.disconnectedCallback(),this._$Do?.setConnected(!1)}render(){return Ve}};L._$litElement$=!0,L.finalized=!0,nn.litElementHydrateSupport?.({LitElement:L});var ba=nn.litElementPolyfillSupport;ba?.({LitElement:L});(nn.litElementVersions??=[]).push("4.2.2");var st=r=>(e,t)=>{t!==void 0?t.addInitializer(()=>{customElements.define(r,e)}):customElements.define(r,e)};var _a={attribute:!0,type:String,converter:wt,reflect:!1,hasChanged:mr},xa=(r=_a,e,t)=>{let{kind:n,metadata:i}=t,o=globalThis.litPropertyMetadata.get(i);if(o===void 0&&globalThis.litPropertyMetadata.set(i,o=new Map),n==="setter"&&((r=Object.create(r)).wrapped=!0),o.set(t.name,r),n==="accessor"){let{name:s}=t;return{set(c){let l=e.get.call(this);e.set.call(this,c),this.requestUpdate(s,l,r,!0,c)},init(c){return c!==void 0&&this.C(s,void 0,r,c),c}}}if(n==="setter"){let{name:s}=t;return function(c){let l=this[s];e.call(this,c),this.requestUpdate(s,l,r,!0,c)}}throw Error("Unsupported decorator location: "+n)};function me(r){return(e,t)=>typeof t=="object"?xa(r,e,t):((n,i,o)=>{let s=i.hasOwnProperty(o);return i.constructor.createProperty(o,n),s?Object.getOwnPropertyDescriptor(i,o):void 0})(r,e,t)}var{I:gp}=Ii;var Di=r=>r.strings===void 0;var Pi={ATTRIBUTE:1,CHILD:2,PROPERTY:3,BOOLEAN_ATTRIBUTE:4,EVENT:5,ELEMENT:6},on=r=>(...e)=>({_$litDirective$:r,values:e}),kr=class{constructor(e){}get _$AU(){return this._$AM._$AU}_$AT(e,t,n){this._$Ct=e,this._$AM=t,this._$Ci=n}_$AS(e,t){return this.update(e,t)}update(e,t){return this.render(...t)}};var Ot=(r,e)=>{let t=r._$AN;if(t===void 0)return!1;for(let n of t)n._$AO?.(e,!1),Ot(n,e);return!0},Tr=r=>{let e,t;do{if((e=r._$AM)===void 0)break;t=e._$AN,t.delete(r),r=e}while(t?.size===0)},Mi=r=>{for(let e;e=r._$AM;r=e){let t=e._$AN;if(t===void 0)e._$AN=t=new Set;else if(t.has(r))break;t.add(r),ka(e)}};function Sa(r){this._$AN!==void 0?(Tr(this),this._$AM=r,Mi(this)):this._$AM=r}function wa(r,e=!1,t=0){let n=this._$AH,i=this._$AN;if(i!==void 0&&i.size!==0)if(e)if(Array.isArray(n))for(let o=t;o{r.type==Pi.CHILD&&(r._$AP??=wa,r._$AQ??=Sa)},Ar=class extends kr{constructor(){super(...arguments),this._$AN=void 0}_$AT(e,t,n){super._$AT(e,t,n),Mi(this),this.isConnected=e._$AU}_$AO(e,t=!0){e!==this.isConnected&&(this.isConnected=e,e?this.reconnected?.():this.disconnected?.()),t&&(Ot(this,e),Tr(this))}setValue(e){if(Di(this._$Ct))this._$Ct._$AI(e,this);else{let t=[...this._$Ct._$AH];t[this._$Ci]=e,this._$Ct._$AI(t,this,0)}}disconnected(){}reconnected(){}};var Ni=()=>new an,an=class{},sn=new WeakMap,Li=on(class extends Ar{render(r){return O}update(r,[e]){let t=e!==this.G;return t&&this.G!==void 0&&this.rt(void 0),(t||this.lt!==this.ct)&&(this.G=e,this.ht=r.options?.host,this.rt(this.ct=r.element)),O}rt(r){if(this.isConnected||(r=void 0),typeof this.G=="function"){let e=this.ht??globalThis,t=sn.get(e);t===void 0&&(t=new WeakMap,sn.set(e,t)),t.get(this.G)!==void 0&&this.G.call(this.ht,void 0),t.set(this.G,r),r!==void 0&&this.G.call(this.ht,r)}else this.G.value=r}get lt(){return typeof this.G=="function"?sn.get(this.ht??globalThis)?.get(this.G):this.G?.value}disconnected(){this.lt===this.ct&&this.rt(void 0)}reconnected(){this.rt(this.ct)}});var ve=K` * { box-sizing: border-box; } @@ -33,10 +33,10 @@ var Vi=Object.create;var Or=Object.defineProperty;var ln=Object.getOwnPropertyDe Roboto, Oxygen, Ubuntu, Cantarell, "Open Sans", "Helvetica Neue", sans-serif; } -`;var Li="narrow",Ui="wide",We=class extends L{constructor(){super(...arguments);this.kind="overlay";this.dialogRef=Mi();this.width="narrow"}firstUpdated(t){super.firstUpdated(t),this.dialogRef.value?.showModal()}closed(){this.dispatchEvent(new Event("closed",{bubbles:!0,composed:!0}))}toggleWidth(t){if(t.currentTarget instanceof HTMLButtonElement){let n=t.currentTarget.value;(n===Ui||n===Li)&&(this.width=n)}}render(){return N` +`;var Ui="narrow",zi="wide",He=class extends L{constructor(){super(...arguments);this.kind="overlay";this.dialogRef=Ni();this.width="narrow"}firstUpdated(t){super.firstUpdated(t),this.dialogRef.value?.showModal()}closed(){this.dispatchEvent(new Event("closed",{bubbles:!0,composed:!0}))}toggleWidth(t){if(t.currentTarget instanceof HTMLButtonElement){let n=t.currentTarget.value;(n===zi||n===Ui)&&(this.width=n)}}render(){return N` @@ -44,14 +44,14 @@ var Vi=Object.create;var Or=Object.defineProperty;var ln=Object.getOwnPropertyDe - `}};We.styles=[at,me,K` + `}};He.styles=[at,ve,K` ::backdrop { background: rgba(0, 0, 0, 0.7); } @@ -100,7 +100,7 @@ var Vi=Object.create;var Or=Object.defineProperty;var ln=Object.getOwnPropertyDe justify-content: flex-end; gap: 0.5rem; } - `],W([he({type:String})],We.prototype,"kind",2),W([he({type:String})],We.prototype,"width",2),We=W([st("bs-overlay")],We);var Ar=class extends L{static{this.styles=[me,K` + `],B([me({type:String})],He.prototype,"kind",2),B([me({type:String})],He.prototype,"width",2),He=B([st("bs-overlay")],He);var Er=class extends L{static{this.styles=[ve,K` .svg-icon { display: inline-block; fill: var(--bs-icon-color, currentColor); @@ -234,15 +234,15 @@ var Vi=Object.create;var Or=Object.defineProperty;var ln=Object.getOwnPropertyDe /> - ${this.icon}`}};W([he({type:String,attribute:"icon-name"})],Ar.prototype,"iconName",2);customElements.define("bs-icon",Ar);function zi(){return N``}var ct=class extends L{constructor(){super(...arguments);this.title="..."}render(){return N`
+ ${this.icon}`}};B([me({type:String,attribute:"icon-name"})],Er.prototype,"iconName",2);customElements.define("bs-icon",Er);function Zi(){return N``}var ct=class extends L{constructor(){super(...arguments);this.title="..."}render(){return N`
- ${zi()} + ${Zi()} ${this.title}
-
`}};ct.styles=[at,me,K` +
`}};ct.styles=[at,ve,K` .root { background: white; color: var(--brand-blue); @@ -279,7 +279,7 @@ var Vi=Object.create;var Or=Object.defineProperty;var ln=Object.getOwnPropertyDe slot::slotted(*) { font-size: 10px; } - `],W([he({type:String})],ct.prototype,"title",2),ct=W([st("bs-panel")],ct);var Ct=class extends L{render(){return N` `}};Ct.styles=[me,at],Ct=W([st("bs-token-env")],Ct);function Zi({displayMessage:r}){let t=N` + `],B([me({type:String})],ct.prototype,"title",2),ct=B([st("bs-panel")],ct);var Ct=class extends L{render(){return N` `}};Ct.styles=[ve,at],Ct=B([st("bs-token-env")],Ct);function Fi({displayMessage:r}){let t=N`