From 34ebfaddbc91b2d9984b43683d253684469a04a3 Mon Sep 17 00:00:00 2001 From: GW_MC <72297530+GWMCwing@users.noreply.github.com> Date: Fri, 5 Dec 2025 17:01:29 +0800 Subject: [PATCH 01/10] Add OpenAPI support and health info endpoint documentation --- Cargo.lock | 26 ++++++++++++++++++++++++++ apps/api/Cargo.toml | 1 + apps/api/src/routes.rs | 2 ++ apps/api/src/routes/api.rs | 3 +++ apps/api/src/routes/api/health.rs | 2 +- apps/api/src/routes/api/health/info.rs | 13 ++++++++++++- apps/api/src/routes/api/openapi.rs | 3 +++ 7 files changed, 48 insertions(+), 2 deletions(-) create mode 100644 apps/api/src/routes/api/openapi.rs diff --git a/Cargo.lock b/Cargo.lock index ab8dd37..71af87e 100644 --- a/Cargo.lock +++ b/Cargo.lock @@ -3820,6 +3820,31 @@ version = "0.2.2" source = "registry+https://github.com/rust-lang/crates.io-index" checksum = "06abde3611657adf66d383f00b093d7faecc7fa57071cce2578660c9f1010821" +[[package]] +name = "utoipa" +version = "5.4.0" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "2fcc29c80c21c31608227e0912b2d7fddba57ad76b606890627ba8ee7964e993" +dependencies = [ + "indexmap 2.12.0", + "serde", + "serde_json", + "utoipa-gen", +] + +[[package]] +name = "utoipa-gen" +version = "5.4.0" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "6d79d08d92ab8af4c5e8a6da20c47ae3f61a0f1dabc1997cdf2d082b757ca08b" +dependencies = [ + "proc-macro2", + "quote", + "regex", + "syn 2.0.110", + "uuid", +] + [[package]] name = "uuid" version = "1.18.1" @@ -4340,6 +4365,7 @@ dependencies = [ "tower", "tracing", "tracing-subscriber", + "utoipa", ] [[package]] diff --git a/apps/api/Cargo.toml b/apps/api/Cargo.toml index c4c76d4..3d132ad 100644 --- a/apps/api/Cargo.toml +++ b/apps/api/Cargo.toml @@ -20,3 +20,4 @@ serde = { version = "1.0.228", features = ["std", "derive"] } sea-orm = { workspace = true } include_dir = { version = "0.7.4" } mime_guess = { version = "2.0.5" } +utoipa = { version = "5.4.0", features = ["macros", "axum_extras", "chrono", "decimal", "uuid", "time", "openapi_extensions"] } diff --git a/apps/api/src/routes.rs b/apps/api/src/routes.rs index 7fb0e6b..f257f1b 100644 --- a/apps/api/src/routes.rs +++ b/apps/api/src/routes.rs @@ -1,6 +1,8 @@ mod api; mod view; +pub use self::api::ApiDoc; + use std::sync::Arc; use axum::{Extension, Router}; diff --git a/apps/api/src/routes/api.rs b/apps/api/src/routes/api.rs index 7f648a2..68bbdcc 100644 --- a/apps/api/src/routes/api.rs +++ b/apps/api/src/routes/api.rs @@ -1,4 +1,7 @@ mod health; +mod openapi; + +pub use self::openapi::ApiDoc; use axum::{Router, response::IntoResponse, routing::any}; diff --git a/apps/api/src/routes/api/health.rs b/apps/api/src/routes/api/health.rs index 98f6b15..b6cc7bc 100644 --- a/apps/api/src/routes/api/health.rs +++ b/apps/api/src/routes/api/health.rs @@ -1,4 +1,4 @@ -mod info; +pub mod info; mod state; use std::sync::Arc; diff --git a/apps/api/src/routes/api/health/info.rs b/apps/api/src/routes/api/health/info.rs index 0e09d93..3299f5b 100644 --- a/apps/api/src/routes/api/health/info.rs +++ b/apps/api/src/routes/api/health/info.rs @@ -9,7 +9,7 @@ use crate::routes::api::health::state::HealthState; const STATUS_HEALTHY: &str = "healthy"; const STATUS_UNHEALTHY: &str = "unhealthy"; -#[derive(Serialize, Deserialize)] +#[derive(Serialize, Deserialize, utoipa::ToSchema)] pub struct HealthInfo { pub status: String, pub version: String, @@ -18,6 +18,17 @@ pub struct HealthInfo { pub errors: Option>, } +#[utoipa::path( + get, + path = "/api/health/info", + responses( + (status = 200, description = "Health information retrieved successfully", body = HealthInfo), + (status = NOT_FOUND, description = "Health information not found") + ), + params( + ("id" = u64, Path, description = "Pet database id to get Pet for"), + ) + )] pub async fn get_health_info( State(state): State>, ) -> (StatusCode, Json) { diff --git a/apps/api/src/routes/api/openapi.rs b/apps/api/src/routes/api/openapi.rs new file mode 100644 index 0000000..cd6d8f3 --- /dev/null +++ b/apps/api/src/routes/api/openapi.rs @@ -0,0 +1,3 @@ +#[derive(utoipa::OpenApi)] +#[openapi(paths(crate::routes::api::health::info::get_health_info))] +pub struct ApiDoc; -- 2.49.1 From d2b842d93395b01c7b6941e49ffe4e0634d02c2d Mon Sep 17 00:00:00 2001 From: GW_MC <72297530+GWMCwing@users.noreply.github.com> Date: Fri, 5 Dec 2025 17:22:51 +0800 Subject: [PATCH 02/10] Add CLI command for generating OpenAPI documentation --- Cargo.lock | 2 ++ apps/api/Cargo.toml | 2 ++ apps/api/src/cmd.rs | 45 +++++++++++++++++++++++++ apps/api/src/cmd/generate_openapi.rs | 38 +++++++++++++++++++++ apps/api/src/main.rs | 49 +++++++++++++++++++++++----- 5 files changed, 128 insertions(+), 8 deletions(-) create mode 100644 apps/api/src/cmd.rs create mode 100644 apps/api/src/cmd/generate_openapi.rs diff --git a/Cargo.lock b/Cargo.lock index 71af87e..6690d9c 100644 --- a/Cargo.lock +++ b/Cargo.lock @@ -4353,11 +4353,13 @@ dependencies = [ "async-trait", "axum", "chrono", + "clap", "config", "database", "include_dir", "migration", "mime_guess", + "once_cell", "sea-orm", "serde", "serde_json", diff --git a/apps/api/Cargo.toml b/apps/api/Cargo.toml index 3d132ad..a3a1a00 100644 --- a/apps/api/Cargo.toml +++ b/apps/api/Cargo.toml @@ -21,3 +21,5 @@ sea-orm = { workspace = true } include_dir = { version = "0.7.4" } mime_guess = { version = "2.0.5" } utoipa = { version = "5.4.0", features = ["macros", "axum_extras", "chrono", "decimal", "uuid", "time", "openapi_extensions"] } +clap = { version = "4.5.53" } +once_cell = { version = "1.21.3" } diff --git a/apps/api/src/cmd.rs b/apps/api/src/cmd.rs new file mode 100644 index 0000000..ffb6eca --- /dev/null +++ b/apps/api/src/cmd.rs @@ -0,0 +1,45 @@ +use std::pin::Pin; +use std::{future::Future, process::exit}; + +use clap::{ArgMatches, Command}; + +pub mod generate_openapi; + +pub struct CliCommand { + pub command: Command, + pub action: fn(&clap::ArgMatches) -> Pin + Send>>, +} + +static CLI_COMMANDS: once_cell::sync::Lazy< + [CliCommand; 1 /* Update this count when adding new commands */], +> = + once_cell::sync::Lazy::new(|| { + [ + // Add new commands here + generate_openapi::get_cli_command(), + ] + }); + +pub fn get_command() -> Command { + let mut c = Command::new("cmd"); + + for cmd in CLI_COMMANDS.iter() { + c = c.subcommand(cmd.command.clone()); + } + + c +} + +pub fn execute(matches: &ArgMatches, help_msg: &str) -> Pin + Send>> { + if let Some((subcommand_name, subcommand_matches)) = matches.subcommand() { + for cmd in CLI_COMMANDS.iter() { + if cmd.command.get_name() == subcommand_name { + return (cmd.action)(subcommand_matches); + } + } + } + + eprintln!("Error: No valid subcommand provided."); + eprintln!("{}", help_msg); + exit(1); +} diff --git a/apps/api/src/cmd/generate_openapi.rs b/apps/api/src/cmd/generate_openapi.rs new file mode 100644 index 0000000..e227fed --- /dev/null +++ b/apps/api/src/cmd/generate_openapi.rs @@ -0,0 +1,38 @@ +use clap::{Arg, Command}; +use utoipa::OpenApi; + +use crate::{cmd::CliCommand, routes::ApiDoc}; + +pub fn get_cli_command() -> CliCommand { + CliCommand { + command: command(), + action, + } +} + +fn command() -> Command { + Command::new("generate:openapi") + .arg( + Arg::new("output_path") + .short('o') + .long("output-path") + .value_name("PATH") + .help("Path to output the generated OpenAPI documentation") + .required(true), + ) + .about("Generate OpenAPI documentation") +} + +fn action( + _matches: &clap::ArgMatches, +) -> std::pin::Pin + Send>> { + let output_path = _matches.get_one::("output_path"); + let output_path = output_path.unwrap().to_string(); + Box::pin(async move { + let doc = ApiDoc::openapi(); + let json = doc + .to_pretty_json() + .expect("Failed to serialize OpenAPI doc to JSON"); + std::fs::write(&output_path, json).expect("Failed to write OpenAPI doc to file"); + }) +} diff --git a/apps/api/src/main.rs b/apps/api/src/main.rs index dd1af30..f8a8ec9 100644 --- a/apps/api/src/main.rs +++ b/apps/api/src/main.rs @@ -1,3 +1,4 @@ +mod cmd; mod configs; mod errors; mod middlewares; @@ -21,15 +22,39 @@ use crate::{ #[tokio::main] async fn main() { - // Temporary subscriber for initial logging during configuration reading - let make_temporary_subscriber = || { - tracing_subscriber::fmt() - .with_max_level(tracing::Level::DEBUG) - .with_target(false) - .with_level(true) - .finish() - }; + // only run command line interface if arguments are provided + if std::env::args().len() > 1 { + process_commands().await; + return; + } + start_server().await; +} + +async fn process_commands() { + tracing::subscriber::with_default(make_temporary_subscriber(), async || { + use clap::error::ErrorKind; + + let mut command = cmd::get_command(); + let help_output = format!("{}", command.render_help()); + let matches = command + .try_get_matches() + .unwrap_or_else(|err| match err.kind() { + ErrorKind::DisplayHelp | ErrorKind::DisplayVersion => { + err.print().expect("Error writing Error"); + std::process::exit(0); + } + _ => { + err.print().expect("Error writing Error"); + std::process::exit(1); + } + }); + cmd::execute(&matches, &help_output).await; + }) + .await +} + +async fn start_server() { let settings = tracing::subscriber::with_default(make_temporary_subscriber(), || -> ProgramSettings { debug!("Temporary subscriber installed."); @@ -86,6 +111,14 @@ async fn main() { .expect("Failed to run the server"); } +fn make_temporary_subscriber() -> tracing_subscriber::fmt::Subscriber { + tracing_subscriber::fmt() + .with_max_level(tracing::Level::DEBUG) + .with_target(false) + .with_level(true) + .finish() +} + fn get_global_tracing_subscriber_builder( settings: &LoggingSettings, ) -> tracing_subscriber::fmt::SubscriberBuilder< -- 2.49.1 From 65d40c1e8358d467dab4b2bb334107aff8efedfd Mon Sep 17 00:00:00 2001 From: GW_MC <72297530+GWMCwing@users.noreply.github.com> Date: Fri, 5 Dec 2025 18:03:17 +0800 Subject: [PATCH 03/10] Add start server command and logging setup for CLI --- apps/api/src/cmd.rs | 10 +- apps/api/src/cmd/generate_openapi.rs | 18 ++- apps/api/src/cmd/start_server.rs | 142 +++++++++++++++++++++ apps/api/src/log.rs | 7 ++ apps/api/src/main.rs | 178 ++++----------------------- 5 files changed, 192 insertions(+), 163 deletions(-) create mode 100644 apps/api/src/cmd/start_server.rs create mode 100644 apps/api/src/log.rs diff --git a/apps/api/src/cmd.rs b/apps/api/src/cmd.rs index ffb6eca..1475f26 100644 --- a/apps/api/src/cmd.rs +++ b/apps/api/src/cmd.rs @@ -1,22 +1,26 @@ +mod generate_openapi; +mod start_server; + +pub use start_server::start_server; + use std::pin::Pin; use std::{future::Future, process::exit}; use clap::{ArgMatches, Command}; -pub mod generate_openapi; - pub struct CliCommand { pub command: Command, pub action: fn(&clap::ArgMatches) -> Pin + Send>>, } static CLI_COMMANDS: once_cell::sync::Lazy< - [CliCommand; 1 /* Update this count when adding new commands */], + [CliCommand; 2 /* Update this count when adding new commands */], > = once_cell::sync::Lazy::new(|| { [ // Add new commands here generate_openapi::get_cli_command(), + start_server::get_cli_command(), ] }); diff --git a/apps/api/src/cmd/generate_openapi.rs b/apps/api/src/cmd/generate_openapi.rs index e227fed..8d0c6f6 100644 --- a/apps/api/src/cmd/generate_openapi.rs +++ b/apps/api/src/cmd/generate_openapi.rs @@ -1,7 +1,8 @@ use clap::{Arg, Command}; +use tracing::info; use utoipa::OpenApi; -use crate::{cmd::CliCommand, routes::ApiDoc}; +use crate::{cmd::CliCommand, log, routes::ApiDoc}; pub fn get_cli_command() -> CliCommand { CliCommand { @@ -28,11 +29,16 @@ fn action( ) -> std::pin::Pin + Send>> { let output_path = _matches.get_one::("output_path"); let output_path = output_path.unwrap().to_string(); + Box::pin(async move { - let doc = ApiDoc::openapi(); - let json = doc - .to_pretty_json() - .expect("Failed to serialize OpenAPI doc to JSON"); - std::fs::write(&output_path, json).expect("Failed to write OpenAPI doc to file"); + tracing::subscriber::with_default(log::make_temporary_subscriber(), || { + info!("Generating OpenAPI documentation..."); + let doc = ApiDoc::openapi(); + let json = doc + .to_pretty_json() + .expect("Failed to serialize OpenAPI doc to JSON"); + std::fs::write(&output_path, json).expect("Failed to write OpenAPI doc to file"); + info!("OpenAPI documentation generated at {}", output_path); + }) }) } diff --git a/apps/api/src/cmd/start_server.rs b/apps/api/src/cmd/start_server.rs new file mode 100644 index 0000000..461c0b3 --- /dev/null +++ b/apps/api/src/cmd/start_server.rs @@ -0,0 +1,142 @@ +use std::sync::Arc; + +use axum::Router; +use clap::Command; +use database::get_connection; +use sea_orm::ConnectOptions; +use tracing::{debug, info}; +use tracing_subscriber::fmt::format::{DefaultFields, Format}; + +use crate::{ + cmd::CliCommand, + configs::{ProgramSettings, get_program_settings, logging::LoggingSettings}, + log, + routes::{self, AppService, AppState}, + services::settings::SettingsService, + tasks, +}; + +pub fn get_cli_command() -> CliCommand { + CliCommand { + command: command(), + action, + } +} + +fn command() -> Command { + Command::new("start").about("Start the server") +} + +fn action( + _matches: &clap::ArgMatches, +) -> std::pin::Pin + Send>> { + Box::pin(async move {}) +} + +pub async fn start_server() { + let settings = tracing::subscriber::with_default( + log::make_temporary_subscriber(), + || -> ProgramSettings { + debug!("Temporary subscriber installed."); + info!("Reading configuration..."); + let settings = get_program_settings(); + info!("Configuration read successfully."); + debug!("Resetting global subscriber..."); + + let subscriber = get_global_tracing_subscriber_builder(&settings.logging).finish(); + tracing::subscriber::set_global_default(subscriber) + .expect("Failed to set global default subscriber"); + + debug!( + "Global subscriber set with logging level: {:?}", + settings.logging.level + ); + + settings + }, + ); + + tasks::startup::run_startup_tasks(&settings) + .await + .expect("Failed to run startup tasks"); + + // setup database connection pool + info!("Establishing database connection..."); + debug!("Database URL: {}", settings.database.url); + + let db_options = |options: &mut ConnectOptions| { + options.max_connections(settings.database.max_connections); + }; + + let db_connection = Arc::new( + get_connection(&settings.database.url, Some(db_options)) + .await + .expect("Failed to establish database connection"), + ); + + info!("Database connection established."); + + // build the axum app and run the server... + info!("Starting application..."); + let app: Router = routes::get_root_router(Arc::new(get_app_state(&db_connection))); + + let address = format!("{}:{}", settings.server.address, settings.server.port); + info!("Starting server at http://{}", address); + + let listener = tokio::net::TcpListener::bind(address) + .await + .expect("Failed to bind to address"); + + axum::serve(listener, app) + .await + .expect("Failed to run the server"); +} + +fn get_global_tracing_subscriber_builder( + settings: &LoggingSettings, +) -> tracing_subscriber::fmt::SubscriberBuilder< + DefaultFields, + Format, +> { + // After configuration is read, install the global subscriber + let builder = tracing_subscriber::fmt() + .with_max_level(settings.level) + .with_target(false) + .with_level(true); + + if settings.utc { + builder.with_timer(BoxedTimer(Box::new( + tracing_subscriber::fmt::time::UtcTime::rfc_3339(), + ))) + } else { + builder.with_timer(BoxedTimer(Box::new( + tracing_subscriber::fmt::time::ChronoLocal::rfc_3339(), + ))) + } +} + +fn get_app_state(db_connection: &Arc) -> AppState { + AppState { + database_connection: db_connection.clone(), + service: Arc::new(AppService { + settings: Arc::new(SettingsService::new(db_connection.clone())), + }), + } +} + +// A small wrapper that holds a boxed `FormatTime` trait object and itself +// implements `FormatTime`, allowing us to use it as a concrete type with +// `builder.with_timer` while still picking the concrete timer implementation +// at runtime. +// wrapper type to hold boxed timers and implement the `FormatTime` trait for +// a concrete type so `with_timer` may be called once outside the conditional. +struct BoxedTimer(Box); + +impl tracing_subscriber::fmt::time::FormatTime for BoxedTimer { + fn format_time( + &self, + w: &mut tracing_subscriber::fmt::format::Writer<'_>, + ) -> std::result::Result<(), std::fmt::Error> { + self.0.format_time(w) + } +} diff --git a/apps/api/src/log.rs b/apps/api/src/log.rs new file mode 100644 index 0000000..f38dd21 --- /dev/null +++ b/apps/api/src/log.rs @@ -0,0 +1,7 @@ +pub fn make_temporary_subscriber() -> tracing_subscriber::fmt::Subscriber { + tracing_subscriber::fmt() + .with_max_level(tracing::Level::DEBUG) + .with_target(false) + .with_level(true) + .finish() +} diff --git a/apps/api/src/main.rs b/apps/api/src/main.rs index f8a8ec9..ba0c82f 100644 --- a/apps/api/src/main.rs +++ b/apps/api/src/main.rs @@ -1,169 +1,39 @@ mod cmd; mod configs; mod errors; +mod log; mod middlewares; mod routes; mod services; mod tasks; -use std::sync::Arc; - -use axum::Router; -use database::get_connection; -use sea_orm::ConnectOptions; -use tracing::{debug, info}; -use tracing_subscriber::fmt::format::{DefaultFields, Format}; - -use crate::{ - configs::{ProgramSettings, get_program_settings, logging::LoggingSettings}, - routes::{AppService, AppState}, - services::settings::SettingsService, -}; - #[tokio::main] async fn main() { - // only run command line interface if arguments are provided + // If there are command-line arguments, treat it as a CLI command if std::env::args().len() > 1 { - process_commands().await; + tracing::subscriber::with_default(log::make_temporary_subscriber(), || { + use clap::error::ErrorKind; + // + let mut command = cmd::get_command(); + let help_output = format!("{}", command.render_help()); + let matches = command + .try_get_matches() + .unwrap_or_else(|err| match err.kind() { + ErrorKind::DisplayHelp | ErrorKind::DisplayVersion => { + err.print().expect("Error writing Error"); + std::process::exit(0); + } + _ => { + err.print().expect("Error writing Error"); + std::process::exit(1); + } + }); + cmd::execute(&matches, &help_output) + }) + .await; return; } - start_server().await; -} - -async fn process_commands() { - tracing::subscriber::with_default(make_temporary_subscriber(), async || { - use clap::error::ErrorKind; - - let mut command = cmd::get_command(); - let help_output = format!("{}", command.render_help()); - let matches = command - .try_get_matches() - .unwrap_or_else(|err| match err.kind() { - ErrorKind::DisplayHelp | ErrorKind::DisplayVersion => { - err.print().expect("Error writing Error"); - std::process::exit(0); - } - _ => { - err.print().expect("Error writing Error"); - std::process::exit(1); - } - }); - cmd::execute(&matches, &help_output).await; - }) - .await -} - -async fn start_server() { - let settings = - tracing::subscriber::with_default(make_temporary_subscriber(), || -> ProgramSettings { - debug!("Temporary subscriber installed."); - info!("Reading configuration..."); - let settings = get_program_settings(); - info!("Configuration read successfully."); - debug!("Resetting global subscriber..."); - - let subscriber = get_global_tracing_subscriber_builder(&settings.logging).finish(); - tracing::subscriber::set_global_default(subscriber) - .expect("Failed to set global default subscriber"); - - debug!( - "Global subscriber set with logging level: {:?}", - settings.logging.level - ); - - settings - }); - - tasks::startup::run_startup_tasks(&settings) - .await - .expect("Failed to run startup tasks"); - - // setup database connection pool - info!("Establishing database connection..."); - debug!("Database URL: {}", settings.database.url); - - let db_options = |options: &mut ConnectOptions| { - options.max_connections(settings.database.max_connections); - }; - - let db_connection = Arc::new( - get_connection(&settings.database.url, Some(db_options)) - .await - .expect("Failed to establish database connection"), - ); - - info!("Database connection established."); - - // build the axum app and run the server... - info!("Starting application..."); - let app: Router = routes::get_root_router(Arc::new(get_app_state(&db_connection))); - - let address = format!("{}:{}", settings.server.address, settings.server.port); - info!("Starting server at http://{}", address); - - let listener = tokio::net::TcpListener::bind(address) - .await - .expect("Failed to bind to address"); - - axum::serve(listener, app) - .await - .expect("Failed to run the server"); -} - -fn make_temporary_subscriber() -> tracing_subscriber::fmt::Subscriber { - tracing_subscriber::fmt() - .with_max_level(tracing::Level::DEBUG) - .with_target(false) - .with_level(true) - .finish() -} - -fn get_global_tracing_subscriber_builder( - settings: &LoggingSettings, -) -> tracing_subscriber::fmt::SubscriberBuilder< - DefaultFields, - Format, -> { - // After configuration is read, install the global subscriber - let builder = tracing_subscriber::fmt() - .with_max_level(settings.level) - .with_target(false) - .with_level(true); - - if settings.utc { - builder.with_timer(BoxedTimer(Box::new( - tracing_subscriber::fmt::time::UtcTime::rfc_3339(), - ))) - } else { - builder.with_timer(BoxedTimer(Box::new( - tracing_subscriber::fmt::time::ChronoLocal::rfc_3339(), - ))) - } -} - -fn get_app_state(db_connection: &Arc) -> AppState { - AppState { - database_connection: db_connection.clone(), - service: Arc::new(AppService { - settings: Arc::new(SettingsService::new(db_connection.clone())), - }), - } -} - -// A small wrapper that holds a boxed `FormatTime` trait object and itself -// implements `FormatTime`, allowing us to use it as a concrete type with -// `builder.with_timer` while still picking the concrete timer implementation -// at runtime. -// wrapper type to hold boxed timers and implement the `FormatTime` trait for -// a concrete type so `with_timer` may be called once outside the conditional. -struct BoxedTimer(Box); - -impl tracing_subscriber::fmt::time::FormatTime for BoxedTimer { - fn format_time( - &self, - w: &mut tracing_subscriber::fmt::format::Writer<'_>, - ) -> std::result::Result<(), std::fmt::Error> { - self.0.format_time(w) - } + // No command-line arguments, start the server normally + cmd::start_server().await; } -- 2.49.1 From 8875122e1b100d3d53f45f08f97a7d3d8504635e Mon Sep 17 00:00:00 2001 From: GW_MC <72297530+GWMCwing@users.noreply.github.com> Date: Fri, 5 Dec 2025 18:03:25 +0800 Subject: [PATCH 04/10] Add OpenAPI specification and generation command --- apps/api/swagger.json | 82 +++++++++++++++++++++++++++++++++++++++++++ justfile | 5 +++ 2 files changed, 87 insertions(+) create mode 100644 apps/api/swagger.json diff --git a/apps/api/swagger.json b/apps/api/swagger.json new file mode 100644 index 0000000..7e8f40a --- /dev/null +++ b/apps/api/swagger.json @@ -0,0 +1,82 @@ +{ + "openapi": "3.1.0", + "info": { + "title": "yet-another-nginx-proxy-manager", + "description": "", + "license": { + "name": "" + }, + "version": "0.1.0" + }, + "paths": { + "/api/health/info": { + "get": { + "tags": [ + "crate::routes::api::health::info" + ], + "operationId": "get_health_info", + "parameters": [ + { + "name": "id", + "in": "path", + "description": "Pet database id to get Pet for", + "required": true, + "schema": { + "type": "integer", + "format": "int64", + "minimum": 0 + } + } + ], + "responses": { + "200": { + "description": "Health information retrieved successfully", + "content": { + "application/json": { + "schema": { + "$ref": "#/components/schemas/HealthInfo" + } + } + } + }, + "404": { + "description": "Health information not found" + } + } + } + } + }, + "components": { + "schemas": { + "HealthInfo": { + "type": "object", + "required": [ + "status", + "version", + "up_since" + ], + "properties": { + "errors": { + "type": [ + "array", + "null" + ], + "items": { + "type": "string" + } + }, + "status": { + "type": "string" + }, + "up_since": { + "type": "string", + "format": "date-time" + }, + "version": { + "type": "string" + } + } + } + } + } +} \ No newline at end of file diff --git a/justfile b/justfile index a048e1d..14a1462 100644 --- a/justfile +++ b/justfile @@ -41,6 +41,11 @@ generate-entity: # delegate to cli just cli db:migrate_and_generate --output-path ../../public/database/src/generated/entities +generate-openapi: + # delegate to cli + cd apps/api && \ + cargo run -- generate:openapi --output-path ./swagger.json + build-frontend: # build frontend assets cd apps/frontend && \ -- 2.49.1 From 81fbf8281f462ac6795b33892eb2fcfa95a576a8 Mon Sep 17 00:00:00 2001 From: GW_MC <72297530+GWMCwing@users.noreply.github.com> Date: Fri, 5 Dec 2025 18:17:29 +0800 Subject: [PATCH 05/10] Refactor health check API to include OpenAPI tagging and enhance HealthInfo schema documentation --- apps/api/src/routes/api/health/info.rs | 15 ++++++---- apps/api/src/routes/api/openapi.rs | 17 +++++++++++- apps/api/swagger.json | 38 +++++++++++++------------- 3 files changed, 45 insertions(+), 25 deletions(-) diff --git a/apps/api/src/routes/api/health/info.rs b/apps/api/src/routes/api/health/info.rs index 3299f5b..069d5b1 100644 --- a/apps/api/src/routes/api/health/info.rs +++ b/apps/api/src/routes/api/health/info.rs @@ -4,20 +4,27 @@ use axum::{Json, extract::State, http::StatusCode}; use chrono::{DateTime, Utc}; use serde::{Deserialize, Serialize}; -use crate::routes::api::health::state::HealthState; +use crate::routes::api::{health::state::HealthState, openapi::tag::HEALTH_TAG}; const STATUS_HEALTHY: &str = "healthy"; const STATUS_UNHEALTHY: &str = "unhealthy"; +/// System health information #[derive(Serialize, Deserialize, utoipa::ToSchema)] pub struct HealthInfo { + /// Health status: "healthy" or "unhealthy" pub status: String, + /// Application version pub version: String, - // RFC 3339 formatted timestamp + /// RFC 3339 formatted timestamp pub up_since: DateTime, + /// List of error messages if unhealthy pub errors: Option>, } +/// Health check endpoint +/// +/// Returns the health status, version, uptime, and any errors if unhealthy. #[utoipa::path( get, path = "/api/health/info", @@ -25,9 +32,7 @@ pub struct HealthInfo { (status = 200, description = "Health information retrieved successfully", body = HealthInfo), (status = NOT_FOUND, description = "Health information not found") ), - params( - ("id" = u64, Path, description = "Pet database id to get Pet for"), - ) + tag = HEALTH_TAG, )] pub async fn get_health_info( State(state): State>, diff --git a/apps/api/src/routes/api/openapi.rs b/apps/api/src/routes/api/openapi.rs index cd6d8f3..6b39737 100644 --- a/apps/api/src/routes/api/openapi.rs +++ b/apps/api/src/routes/api/openapi.rs @@ -1,3 +1,18 @@ +pub mod tag { + /// Health tag constant + pub const HEALTH_TAG: &str = "Health"; +} + #[derive(utoipa::OpenApi)] -#[openapi(paths(crate::routes::api::health::info::get_health_info))] +#[openapi( + paths( + crate::routes::api::health::info::get_health_info + ), + components( + schemas(crate::routes::api::health::info::HealthInfo) // Register any schemas used in your paths + ), + tags( + (name = tag::HEALTH_TAG, description = "Health information API") + ) +)] pub struct ApiDoc; diff --git a/apps/api/swagger.json b/apps/api/swagger.json index 7e8f40a..1b35dde 100644 --- a/apps/api/swagger.json +++ b/apps/api/swagger.json @@ -12,22 +12,11 @@ "/api/health/info": { "get": { "tags": [ - "crate::routes::api::health::info" + "Health" ], + "summary": "Health check endpoint", + "description": "Returns the health status, version, uptime, and any errors if unhealthy.", "operationId": "get_health_info", - "parameters": [ - { - "name": "id", - "in": "path", - "description": "Pet database id to get Pet for", - "required": true, - "schema": { - "type": "integer", - "format": "int64", - "minimum": 0 - } - } - ], "responses": { "200": { "description": "Health information retrieved successfully", @@ -50,6 +39,7 @@ "schemas": { "HealthInfo": { "type": "object", + "description": "System health information", "required": [ "status", "version", @@ -63,20 +53,30 @@ ], "items": { "type": "string" - } + }, + "description": "List of error messages if unhealthy" }, "status": { - "type": "string" + "type": "string", + "description": "Health status: \"healthy\" or \"unhealthy\"" }, "up_since": { "type": "string", - "format": "date-time" + "format": "date-time", + "description": "RFC 3339 formatted timestamp" }, "version": { - "type": "string" + "type": "string", + "description": "Application version" } } } } - } + }, + "tags": [ + { + "name": "Health", + "description": "Health information API" + } + ] } \ No newline at end of file -- 2.49.1 From 1c051f9502850a14189e4cd8b4ba5acf9ba1dbe1 Mon Sep 17 00:00:00 2001 From: GW_MC <72297530+GWMCwing@users.noreply.github.com> Date: Fri, 5 Dec 2025 19:00:04 +0800 Subject: [PATCH 06/10] Add verification workflow for generated code and OpenAPI spec --- .github/workflows/test.yml | 28 --------- .github/workflows/verify.yml | 112 +++++++++++++++++++++++++++++++++++ 2 files changed, 112 insertions(+), 28 deletions(-) create mode 100644 .github/workflows/verify.yml diff --git a/.github/workflows/test.yml b/.github/workflows/test.yml index 4956b9a..2072dc6 100644 --- a/.github/workflows/test.yml +++ b/.github/workflows/test.yml @@ -16,33 +16,6 @@ jobs: # the workflow DRY. The composite action performs checkout, cache restore and # toolchain setup. - verify-generated-code: - # no need to depend on a separate setup job; the composite action runs in - # this job and restores caches/toolchain here. - runs-on: ubuntu-latest - steps: - - name: Checkout repository - uses: actions/checkout@v3 - with: - fetch-depth: 0 - - - name: Setup Rust, checkout and restore caches - uses: ./.github/actions/setup-rust - - - name: generate entities from migration files - run: | - cd apps/cli - cargo run -- db:migrate_and_generate --output-path ../../public/database/src/generated/entities - - name: Check for uncommitted changes in /generated/ - run: | - if [[ -n $(git status --porcelain | grep '^ M .*\/generated\/') ]]; then - echo "Generated code is not up to date. Please run the code generation locally and commit the changes." - git status --porcelain | grep '^ M .*\/generated\/' - exit 1 - else - echo "Generated code is up to date." - fi - test: needs: frontend-build runs-on: ubuntu-latest @@ -94,7 +67,6 @@ jobs: - name: Check code formatting run: cargo fmt --all -- --check - test-frontend: runs-on: ubuntu-latest steps: diff --git a/.github/workflows/verify.yml b/.github/workflows/verify.yml new file mode 100644 index 0000000..207b978 --- /dev/null +++ b/.github/workflows/verify.yml @@ -0,0 +1,112 @@ +# this workflow verifies the generated code is up to date and valid + +name: Verify +on: + pull_request: + branches: + - master + push: + branches: + - master + + +jobs: + # setup is now handled by a composite action used by downstream jobs to keep + # the workflow DRY. The composite action performs checkout, cache restore and + # toolchain setup. + + verify-generated-code: + runs-on: ubuntu-latest + steps: + - name: Checkout repository + uses: actions/checkout@v3 + with: + fetch-depth: 0 + + - name: Setup Rust, checkout and restore caches + uses: ./.github/actions/setup-rust + + - name: generate entities from migration files + run: | + cd apps/cli + cargo run -- db:migrate_and_generate --output-path ../../public/database/src/generated/entities + - name: Check for uncommitted changes in /generated/ + run: | + if [[ -n $(git status --porcelain | grep '^ M .*\/generated\/') ]]; then + echo "Generated code is not up to date. Please run the code generation locally and commit the changes." + git status --porcelain | grep '^ M .*\/generated\/' + exit 1 + else + echo "Generated code is up to date." + fi + + verify-openapi-spec: + runs-on: ubuntu-latest + steps: + - name: Checkout repository + uses: actions/checkout@v3 + with: + fetch-depth: 0 + + - name: Check whether apps/api/src/routes changed + id: check_changes + run: | + if [ "${{ github.event_name }}" = "pull_request" ]; then + BASE_SHA=${{ github.event.pull_request.base.sha }} + HEAD_SHA=${{ github.event.pull_request.head.sha }} + else + BASE_SHA=${{ github.event.before }} + HEAD_SHA=${{ github.sha }} + fi + + # Provide safe fallbacks when GitHub context values are empty (e.g. when using act) + if [ -z "$HEAD_SHA" ]; then + HEAD_SHA=$(git rev-parse --verify HEAD 2>/dev/null || echo "") + fi + + if [ -z "$BASE_SHA" ]; then + # Try the parent of HEAD, fall back to HEAD if unavailable + PREV=$(git rev-parse --verify "${HEAD_SHA}^" 2>/dev/null || true) + if [ -n "$PREV" ]; then + BASE_SHA=$PREV + else + BASE_SHA=$HEAD_SHA + fi + fi + + echo "Comparing $BASE_SHA..$HEAD_SHA" + CHANGED_FILES=$(git diff --name-only "$BASE_SHA" "$HEAD_SHA" || true) + echo "$CHANGED_FILES" + + echo "$CHANGED_FILES" | grep -E '^(apps/api/src/routes/?|apps/api/swagger.json)' >/dev/null 2>&1 && echo "changed=true" >> $GITHUB_OUTPUT || echo "changed=false" >> $GITHUB_OUTPUT + + - name: Setup Rust, checkout and restore caches + if: steps.check_changes.outputs.changed == 'true' + uses: ./.github/actions/setup-rust + + - name: Generate dummy frontend build (to satisfy dependencies) + if: steps.check_changes.outputs.changed == 'true' + run: | + mkdir -p apps/frontend/build/client + echo "dummy file" > apps/frontend/build/client/dummy.txt + + - name: Generate OpenAPI spec + if: steps.check_changes.outputs.changed == 'true' + run: | + cd apps/api + cargo run -- generate:openapi --output-path ./swagger.json + + - name: Check for uncommitted changes in swagger.json + if: steps.check_changes.outputs.changed == 'true' + run: | + if [[ -n $(git status --porcelain | grep '^ M apps/api/swagger.json') ]]; then + echo "OpenAPI spec is not up to date. Please run the OpenAPI generation locally and commit the changes." + git status --porcelain | grep '^ M apps/api/swagger.json' + exit 1 + else + echo "OpenAPI spec is up to date." + fi + + - name: Skip OpenAPI generation (no relevant changes) + if: steps.check_changes.outputs.changed == 'false' + run: echo "No changes in apps/api/src/routes/ nor apps/api/swagger.json, skipping OpenAPI generation verification." -- 2.49.1 From a7524ab07632839ed9c170cb785aea8e4cc26a22 Mon Sep 17 00:00:00 2001 From: GW_MC <72297530+GWMCwing@users.noreply.github.com> Date: Fri, 5 Dec 2025 20:28:59 +0800 Subject: [PATCH 07/10] Added openapi based api client --- apps/frontend/app/generated/api-client.ts | 394 ++++++++++++++++++ .../frontend/app/generated/tanstack-client.ts | 185 ++++++++ apps/frontend/app/lib/api.ts | 94 +++++ apps/frontend/app/providers/ApiProvider.tsx | 59 +++ apps/frontend/app/root.tsx | 6 +- apps/frontend/app/routes/home.tsx | 3 + apps/frontend/app/vite-env.d.ts | 13 + apps/frontend/package.json | 6 +- apps/frontend/pnpm-lock.yaml | 364 +++++++++++++++- apps/frontend/tsconfig.json | 1 + justfile | 4 +- 11 files changed, 1111 insertions(+), 18 deletions(-) create mode 100644 apps/frontend/app/generated/api-client.ts create mode 100644 apps/frontend/app/generated/tanstack-client.ts create mode 100644 apps/frontend/app/lib/api.ts create mode 100644 apps/frontend/app/providers/ApiProvider.tsx create mode 100644 apps/frontend/app/vite-env.d.ts diff --git a/apps/frontend/app/generated/api-client.ts b/apps/frontend/app/generated/api-client.ts new file mode 100644 index 0000000..67c0787 --- /dev/null +++ b/apps/frontend/app/generated/api-client.ts @@ -0,0 +1,394 @@ +export namespace Schemas { + // + export type HealthInfo = { + errors?: (Array | null) | undefined; + status: string; + up_since: string; + version: string; + }; + + // +} + +export namespace Endpoints { + // + + export type get_Get_health_info = { + method: 'GET'; + path: '/api/health/info'; + requestFormat: 'json'; + parameters: never; + responses: { 200: Schemas.HealthInfo; 404: unknown }; + }; + + // +} + +// +export type EndpointByMethod = { + get: { + '/api/health/info': Endpoints.get_Get_health_info; + }; +}; + +// + +// +export type GetEndpoints = EndpointByMethod['get']; +// + +// +export type EndpointParameters = { + body?: unknown; + query?: Record; + header?: Record; + path?: Record; +}; + +export type MutationMethod = 'post' | 'put' | 'patch' | 'delete'; +export type Method = 'get' | 'head' | 'options' | MutationMethod; + +type RequestFormat = 'json' | 'form-data' | 'form-url' | 'binary' | 'text'; + +export type DefaultEndpoint = { + parameters?: EndpointParameters | undefined; + responses?: Record; + responseHeaders?: Record; +}; + +export type Endpoint = { + operationId: string; + method: Method; + path: string; + requestFormat: RequestFormat; + parameters?: TConfig['parameters']; + meta: { + alias: string; + hasParameters: boolean; + areParametersRequired: boolean; + }; + responses?: TConfig['responses']; + responseHeaders?: TConfig['responseHeaders']; +}; + +export interface Fetcher { + decodePathParams?: (path: string, pathParams: Record) => string; + encodeSearchParams?: (searchParams: Record | undefined) => URLSearchParams; + // + fetch: (input: { + method: Method; + url: URL; + urlSearchParams?: URLSearchParams | undefined; + parameters?: EndpointParameters | undefined; + path: string; + overrides?: RequestInit; + throwOnStatusError?: boolean; + }) => Promise; + parseResponseData?: (response: Response) => Promise; +} + +export const successStatusCodes = [200, 201, 202, 203, 204, 205, 206, 207, 208, 226, 300, 301, 302, 303, 304, 305, 306, 307, 308] as const; +export type SuccessStatusCode = (typeof successStatusCodes)[number]; + +export const errorStatusCodes = [ + 400, 401, 402, 403, 404, 405, 406, 407, 408, 409, 410, 411, 412, 413, 414, 415, 416, 417, 418, 421, 422, 423, 424, 425, 426, 428, 429, 431, 451, 500, 501, 502, 503, + 504, 505, 506, 507, 508, 510, 511, +] as const; +export type ErrorStatusCode = (typeof errorStatusCodes)[number]; + +// Taken from https://github.com/unjs/fetchdts/blob/ec4eaeab5d287116171fc1efd61f4a1ad34e4609/src/fetch.ts#L3 +export interface TypedHeaders | unknown> + extends Omit { + /** [MDN Reference](https://developer.mozilla.org/docs/Web/API/Headers/append) */ + append: | (string & {})>( + name: Name, + value: Lowercase extends keyof TypedHeaderValues ? TypedHeaderValues[Lowercase] : string + ) => void; + /** [MDN Reference](https://developer.mozilla.org/docs/Web/API/Headers/delete) */ + delete: | (string & {})>(name: Name) => void; + /** [MDN Reference](https://developer.mozilla.org/docs/Web/API/Headers/get) */ + get: | (string & {})>( + name: Name + ) => (Lowercase extends keyof TypedHeaderValues ? TypedHeaderValues[Lowercase] : string) | null; + /** [MDN Reference](https://developer.mozilla.org/docs/Web/API/Headers/getSetCookie) */ + getSetCookie: () => string[]; + /** [MDN Reference](https://developer.mozilla.org/docs/Web/API/Headers/has) */ + has: | (string & {})>(name: Name) => boolean; + /** [MDN Reference](https://developer.mozilla.org/docs/Web/API/Headers/set) */ + set: | (string & {})>( + name: Name, + value: Lowercase extends keyof TypedHeaderValues ? TypedHeaderValues[Lowercase] : string + ) => void; + forEach: ( + callbackfn: ( + value: TypedHeaderValues[keyof TypedHeaderValues] | (string & {}), + key: Extract | (string & {}), + parent: TypedHeaders + ) => void, + thisArg?: any + ) => void; +} + +/** @see https://developer.mozilla.org/en-US/docs/Web/API/Response */ +export interface TypedSuccessResponse extends Omit { + ok: true; + status: TStatusCode; + headers: never extends THeaders ? Headers : TypedHeaders; + data: TSuccess; + /** [MDN Reference](https://developer.mozilla.org/en-US/docs/Web/API/Response/json) */ + json: () => Promise; +} + +/** @see https://developer.mozilla.org/en-US/docs/Web/API/Response */ +export interface TypedErrorResponse extends Omit { + ok: false; + status: TStatusCode; + headers: never extends THeaders ? Headers : TypedHeaders; + data: TData; + /** [MDN Reference](https://developer.mozilla.org/en-US/docs/Web/API/Response/json) */ + json: () => Promise; +} + +export type TypedApiResponse = {}, THeaders = {}> = { + [K in keyof TAllResponses]: K extends string + ? K extends `${infer TStatusCode extends number}` + ? TStatusCode extends SuccessStatusCode + ? TypedSuccessResponse + : TypedErrorResponse + : never + : K extends number + ? K extends SuccessStatusCode + ? TypedSuccessResponse + : TypedErrorResponse + : never; +}[keyof TAllResponses]; + +export type SafeApiResponse = TEndpoint extends { responses: infer TResponses } + ? TResponses extends Record + ? TypedApiResponse + : never + : never; + +export type InferResponseByStatus = Extract, { status: TStatusCode }>; + +type RequiredKeys = { + [P in keyof T]-?: undefined extends T[P] ? never : P; +}[keyof T]; + +type MaybeOptionalArg = RequiredKeys extends never ? [config?: T] : [config: T]; +type NotNever = [T] extends [never] ? false : true; + +// + +// +export class TypedStatusError extends Error { + response: TypedErrorResponse; + status: number; + constructor(response: TypedErrorResponse) { + super(`HTTP ${response.status}: ${response.statusText}`); + this.name = 'TypedStatusError'; + this.response = response; + this.status = response.status; + } +} +// + +// +export class ApiClient { + baseUrl: string = ''; + successStatusCodes = successStatusCodes; + errorStatusCodes = errorStatusCodes; + + constructor(public fetcher: Fetcher) {} + + setBaseUrl(baseUrl: string) { + this.baseUrl = baseUrl; + return this; + } + + /** + * Replace path parameters in URL + * Supports both OpenAPI format {param} and Express format :param + */ + defaultDecodePathParams = (url: string, params: Record): string => { + return url.replace(/{(\w+)}/g, (_, key: string) => params[key] || `{${key}}`).replace(/:([a-zA-Z0-9_]+)/g, (_, key: string) => params[key] || `:${key}`); + }; + + /** Uses URLSearchParams, skips null/undefined values */ + defaultEncodeSearchParams = (queryParams: Record | undefined): URLSearchParams | undefined => { + if (!queryParams) return; + + const searchParams = new URLSearchParams(); + Object.entries(queryParams).forEach(([key, value]) => { + if (value != null) { + // Skip null/undefined values + if (Array.isArray(value)) { + value.forEach((val) => val != null && searchParams.append(key, String(val))); + } else { + searchParams.append(key, String(value)); + } + } + }); + + return searchParams; + }; + + defaultParseResponseData = async (response: Response): Promise => { + const contentType = response.headers.get('content-type') ?? ''; + if (contentType.startsWith('text/')) { + return await response.text(); + } + + if (contentType === 'application/octet-stream') { + return await response.arrayBuffer(); + } + + if (contentType.includes('application/json') || (contentType.includes('application/') && contentType.includes('json')) || contentType === '*/*') { + try { + return await response.json(); + } catch { + return undefined; + } + } + + return; + }; + + // + get( + path: Path, + ...params: MaybeOptionalArg< + TEndpoint extends { parameters: infer UParams } + ? NotNever extends true + ? UParams & { overrides?: RequestInit; withResponse?: false; throwOnStatusError?: boolean } + : { overrides?: RequestInit; withResponse?: false; throwOnStatusError?: boolean } + : { overrides?: RequestInit; withResponse?: false; throwOnStatusError?: boolean } + > + ): Promise, { data: {} }>['data']>; + + get( + path: Path, + ...params: MaybeOptionalArg< + TEndpoint extends { parameters: infer UParams } + ? NotNever extends true + ? UParams & { overrides?: RequestInit; withResponse?: true; throwOnStatusError?: boolean } + : { overrides?: RequestInit; withResponse?: true; throwOnStatusError?: boolean } + : { overrides?: RequestInit; withResponse?: true; throwOnStatusError?: boolean } + > + ): Promise>; + + get(path: Path, ...params: MaybeOptionalArg): Promise { + return this.request('get', path, ...params); + } + // + + // + /** + * Generic request method with full type-safety for any endpoint + */ + request( + method: TMethod, + path: TPath, + ...params: MaybeOptionalArg< + TEndpoint extends { parameters: infer UParams } + ? NotNever extends true + ? UParams & { overrides?: RequestInit; withResponse?: false; throwOnStatusError?: boolean } + : { overrides?: RequestInit; withResponse?: false; throwOnStatusError?: boolean } + : { overrides?: RequestInit; withResponse?: false; throwOnStatusError?: boolean } + > + ): Promise, { data: {} }>['data']>; + + request( + method: TMethod, + path: TPath, + ...params: MaybeOptionalArg< + TEndpoint extends { parameters: infer UParams } + ? NotNever extends true + ? UParams & { overrides?: RequestInit; withResponse?: true; throwOnStatusError?: boolean } + : { overrides?: RequestInit; withResponse?: true; throwOnStatusError?: boolean } + : { overrides?: RequestInit; withResponse?: true; throwOnStatusError?: boolean } + > + ): Promise>; + + request( + method: TMethod, + path: TPath, + ...params: MaybeOptionalArg + ): Promise { + const requestParams = params[0]; + const withResponse = requestParams?.withResponse; + const { withResponse: _, throwOnStatusError = withResponse ? false : true, overrides, ...fetchParams } = requestParams || {}; + + const parametersToSend: EndpointParameters = {}; + if (requestParams?.body !== undefined) (parametersToSend as any).body = requestParams.body; + if (requestParams?.query !== undefined) (parametersToSend as any).query = requestParams.query; + if (requestParams?.header !== undefined) (parametersToSend as any).header = requestParams.header; + if (requestParams?.path !== undefined) (parametersToSend as any).path = requestParams.path; + + const resolvedPath = (this.fetcher.decodePathParams ?? this.defaultDecodePathParams)( + this.baseUrl + (path as string), + (parametersToSend.path ?? {}) as Record + ); + console.log('Resolved Path:', resolvedPath); + const url = new URL(resolvedPath); + const urlSearchParams = (this.fetcher.encodeSearchParams ?? this.defaultEncodeSearchParams)(parametersToSend.query); + + const promise = this.fetcher + .fetch({ + method: method, + path: path as string, + url, + urlSearchParams, + parameters: Object.keys(fetchParams).length ? fetchParams : undefined, + overrides, + throwOnStatusError, + }) + .then(async (response) => { + const data = await (this.fetcher.parseResponseData ?? this.defaultParseResponseData)(response); + const typedResponse = Object.assign(response, { + data: data, + json: () => Promise.resolve(data), + }) as SafeApiResponse; + + if (throwOnStatusError && errorStatusCodes.includes(response.status as never)) { + throw new TypedStatusError(typedResponse as never); + } + + return withResponse ? typedResponse : data; + }); + + return promise as Extract, { data: {} }>['data']; + } + // +} + +export function createApiClient(fetcher: Fetcher, baseUrl?: string) { + return new ApiClient(fetcher).setBaseUrl(baseUrl ?? ''); +} + +/** + Example usage: + const api = createApiClient((method, url, params) => + fetch(url, { method, body: JSON.stringify(params) }).then((res) => res.json()), + ); + api.get("/users").then((users) => console.log(users)); + api.post("/users", { body: { name: "John" } }).then((user) => console.log(user)); + api.put("/users/:id", { path: { id: 1 }, body: { name: "John" } }).then((user) => console.log(user)); + + // With error handling + const result = await api.get("/users/{id}", { path: { id: "123" }, withResponse: true }); + if (result.ok) { + // Access data directly + const user = result.data; + console.log(user); + + // Or use the json() method for compatibility + const userFromJson = await result.json(); + console.log(userFromJson); + } else { + const error = result.data; + console.error(`Error ${result.status}:`, error); + } +*/ + +// diff --git a/apps/frontend/app/generated/tanstack-client.ts b/apps/frontend/app/generated/tanstack-client.ts new file mode 100644 index 0000000..e76a8a3 --- /dev/null +++ b/apps/frontend/app/generated/tanstack-client.ts @@ -0,0 +1,185 @@ +import { queryOptions } from "@tanstack/react-query"; +import type { + EndpointByMethod, + ApiClient, + SuccessStatusCode, + ErrorStatusCode, + InferResponseByStatus, + TypedSuccessResponse, +} from "./api-client.ts"; +import { errorStatusCodes, TypedStatusError } from "./api-client.ts"; + +type EndpointQueryKey = [ + TOptions & { + _id: string; + _infinite?: boolean; + }, +]; + +const createQueryKey = ( + id: string, + options?: TOptions, + infinite?: boolean, +): [EndpointQueryKey[0]] => { + const params: EndpointQueryKey[0] = { _id: id } as EndpointQueryKey[0]; + if (infinite) { + params._infinite = infinite; + } + if (options?.body) { + params.body = options.body; + } + if (options?.header) { + params.header = options.header; + } + if (options?.path) { + params.path = options.path; + } + if (options?.query) { + params.query = options.query; + } + return [params]; +}; + +// +export type GetEndpoints = EndpointByMethod["get"]; +// + +// +export type EndpointParameters = { + body?: unknown; + query?: Record; + header?: Record; + path?: Record; +}; + +type RequiredKeys = { + [P in keyof T]-?: undefined extends T[P] ? never : P; +}[keyof T]; + +type MaybeOptionalArg = RequiredKeys extends never ? [config?: T] : [config: T]; + +type InferResponseData = + TypedSuccessResponse extends InferResponseByStatus + ? Extract, { data: {} }>["data"] + : Extract["data"], {}>; + +// + +// +export class TanstackQueryApiClient { + constructor(public client: ApiClient) {} + + // + get( + path: Path, + ...params: MaybeOptionalArg + ) { + const queryKey = createQueryKey(path as string, params[0]); + const query = { + /** type-only property if you need easy access to the endpoint params */ + "~endpoint": {} as TEndpoint, + queryKey, + queryFn: {} as "You need to pass .queryOptions to the useQuery hook", + queryOptions: queryOptions({ + queryFn: async ({ queryKey, signal }) => { + const requestParams = { + ...(params[0] || {}), + ...(queryKey[0] || {}), + overrides: { signal }, + withResponse: false as const, + }; + const res = await this.client.get(path, requestParams as never); + return res as InferResponseData; + }, + queryKey: queryKey, + }), + }; + + return query; + } + // + + // + /** + * Generic mutation method with full type-safety for any endpoint; it doesnt require parameters to be passed initially + * but instead will require them to be passed when calling the mutation.mutate() method + */ + mutation< + TMethod extends keyof EndpointByMethod, + TPath extends keyof EndpointByMethod[TMethod], + TEndpoint extends EndpointByMethod[TMethod][TPath], + TWithResponse extends boolean = false, + TSelection = TWithResponse extends true + ? InferResponseByStatus + : InferResponseData, + TError = TEndpoint extends { responses: infer TResponses } + ? TResponses extends Record + ? TypedStatusError> + : Error + : Error, + >( + method: TMethod, + path: TPath, + options?: { + withResponse?: TWithResponse; + selectFn?: ( + res: TWithResponse extends true + ? InferResponseByStatus + : InferResponseData, + ) => TSelection; + throwOnStatusError?: boolean; + throwOnError?: boolean | ((error: TError) => boolean); + }, + ) { + const mutationKey = [{ method, path }] as const; + const mutationFn = async ( + params: (TEndpoint extends { parameters: infer Parameters } ? Parameters : {}) & { + throwOnStatusError?: boolean; + overrides?: RequestInit; + }, + ): Promise => { + const withResponse = options?.withResponse ?? false; + const throwOnStatusError = + params.throwOnStatusError ?? options?.throwOnStatusError ?? (withResponse ? false : true); + const selectFn = options?.selectFn; + const response = await (this.client as any)[method](path, { + ...(params as any), + withResponse: true, + throwOnStatusError: false, + }); + + if (throwOnStatusError && errorStatusCodes.includes(response.status as never)) { + throw new TypedStatusError(response as never); + } + + // Return just the data if withResponse is false, otherwise return the full response + const finalResponse = withResponse ? response : response.data; + const res = selectFn ? selectFn(finalResponse as any) : finalResponse; + return res as never; + }; + return { + /** type-only property if you need easy access to the endpoint params */ + "~endpoint": {} as TEndpoint, + mutationKey: mutationKey, + mutationFn: {} as "You need to pass .mutationOptions to the useMutation hook", + mutationOptions: { + throwOnError: options?.throwOnError as boolean | ((error: TError) => boolean), + mutationKey: mutationKey, + mutationFn: mutationFn, + } as Omit< + import("@tanstack/react-query").UseMutationOptions< + TSelection, + TError, + (TEndpoint extends { parameters: infer Parameters } ? Parameters : {}) & { + withResponse?: boolean; + throwOnStatusError?: boolean; + } + >, + "mutationFn" + > & { + mutationFn: typeof mutationFn; + }, + }; + } + // +} diff --git a/apps/frontend/app/lib/api.ts b/apps/frontend/app/lib/api.ts new file mode 100644 index 0000000..0c54e4f --- /dev/null +++ b/apps/frontend/app/lib/api.ts @@ -0,0 +1,94 @@ +import type { AxiosInstance, AxiosResponse } from 'axios'; +import { type Fetcher, type Method, createApiClient } from '../generated/api-client'; +import { TanstackQueryApiClient } from '../generated/tanstack-client'; + +const API_BASE_URL: string | undefined = import.meta.env.VITE_API_BASE_URL; + +const get_fetch: (axios: AxiosInstance) => Fetcher['fetch'] = + (axios) => + async ({ method, url: incomingUrl, parameters: params }) => { + // Use a plain object for Axios headers + const headers: Record = {}; + + // Replace path parameters (supports both {param} and :param formats) + const actualUrl = replacePathParams(incomingUrl.toString(), (params?.path ?? {}) as Record); + const url = new URL(actualUrl); + + // Handle query parameters + if (params?.query) { + const searchParams = new URLSearchParams(); + Object.entries(params.query).forEach(([key, value]) => { + if (value != null) { + // Skip null/undefined values + if (Array.isArray(value)) { + value.forEach((val) => val != null && searchParams.append(key, String(val))); + } else { + searchParams.append(key, String(value)); + } + } + }); + url.search = searchParams.toString(); + } + + // Handle request body for mutation methods (use Axios `data`) + const data = (['post', 'put', 'patch', 'delete'] satisfies Method[] as string[]).includes(method.toLowerCase()) ? params?.body : undefined; + + if (data != null) { + headers['Content-Type'] = 'application/json'; + } + + // Add custom headers + if (params?.header) { + Object.entries(params.header).forEach(([key, value]) => { + if (value != null) { + headers[key] = String(value); + } + }); + } + + const response = await axios(url.toString(), { + method: method.toUpperCase(), + ...(data !== undefined && { data }), + headers: headers, + }); + + return axiosResponseToFetchResponse(response); + }; + +function axiosResponseToFetchResponse(response: AxiosResponse): Response { + const headers = new Headers(); + Object.entries(response.headers).forEach(([key, value]) => { + if (Array.isArray(value)) { + value.forEach((val) => headers.append(key, val)); + } else { + headers.append(key, value); + } + }); + + return new Response(response.data, { + status: response.status, + statusText: response.statusText, + headers: headers, + }); +} + +/** + * Replace path parameters in URL + * Supports both OpenAPI format {param} and Express format :param + */ +function replacePathParams(url: string, params: Record): string { + return url.replace(/{(\w+)}/g, (_, key: string) => params[key] || `{${key}}`).replace(/:([a-zA-Z0-9_]+)/g, (_, key: string) => params[key] || `:${key}`); +} + +export function createApi(axios: AxiosInstance) { + return createApiClient( + { + fetch: get_fetch(axios), + }, + API_BASE_URL ?? window.location.origin + ); +} + +export function createTanstackApi(axios: AxiosInstance) { + return new TanstackQueryApiClient(createApi(axios)); +} diff --git a/apps/frontend/app/providers/ApiProvider.tsx b/apps/frontend/app/providers/ApiProvider.tsx new file mode 100644 index 0000000..e8e1176 --- /dev/null +++ b/apps/frontend/app/providers/ApiProvider.tsx @@ -0,0 +1,59 @@ +import { createContext, use, useContext, type PropsWithChildren } from 'react'; +import { createTanstackApi, createApi } from '../lib/api'; +import axios from 'axios'; +import { QueryClient, QueryClientProvider } from '@tanstack/react-query'; + +type ApiProviderProps = PropsWithChildren<{}>; +type ApiContextType = { + apiClient: ReturnType; + tanstackApiClient: ReturnType; +}; + +const ApiContext = createContext(null); + +const queryClient = new QueryClient(); + +/** + * Example usage: + * ```ts + * const { tanstackApiClient } = useApi(); + * const { queryOptions } = tanstackApiClient.get('/api/health/info'); + * useQuery({ + * ...queryOptions, + * queryFn: async (...args) => { + * console.log('Fetching health info...'); + * const data = await queryOptions.queryFn!(...args); + * console.log('Health Info:', data); + * return data; + * }, + * }); + * ``` + */ + +export const ApiProvider: React.FC = ({ children }) => { + const axiosInstance = axios.create({ + withCredentials: true, + }); + const apiClient = createApi(axiosInstance); + const tanstackApiClient = createTanstackApi(axiosInstance); + return ( + + + {children} + + + ); +}; + +export function useApi() { + const context = use(ApiContext); + if (!context) { + throw new Error('useApi must be used within an ApiProvider'); + } + return context; +} diff --git a/apps/frontend/app/root.tsx b/apps/frontend/app/root.tsx index b0e9a73..2041ae0 100644 --- a/apps/frontend/app/root.tsx +++ b/apps/frontend/app/root.tsx @@ -1,8 +1,8 @@ import { isRouteErrorResponse, Links, Meta, Outlet, Scripts, ScrollRestoration } from 'react-router'; - import type { Route } from './+types/root'; import './app.css'; import { Theme } from '@radix-ui/themes'; +import { ApiProvider } from './providers/ApiProvider'; export const links: Route.LinksFunction = () => []; @@ -27,7 +27,9 @@ export function Layout({ children }: { children: React.ReactNode }) { export default function App() { return ( - + + + ); } diff --git a/apps/frontend/app/routes/home.tsx b/apps/frontend/app/routes/home.tsx index 6a3d9cb..8a5c77b 100644 --- a/apps/frontend/app/routes/home.tsx +++ b/apps/frontend/app/routes/home.tsx @@ -1,5 +1,8 @@ import { Text } from '@radix-ui/themes'; import type { Route } from './+types/home'; +import { useContext } from 'react'; +import { useApi } from '../providers/ApiProvider'; +import { useQuery } from '@tanstack/react-query'; export function meta({}: Route.MetaArgs) { return [{ title: 'YANPM' }, { name: 'description', content: 'Welcome to Yet Another Nginx Proxy Manager!' }]; diff --git a/apps/frontend/app/vite-env.d.ts b/apps/frontend/app/vite-env.d.ts new file mode 100644 index 0000000..32e46ee --- /dev/null +++ b/apps/frontend/app/vite-env.d.ts @@ -0,0 +1,13 @@ +interface ViteTypeOptions { + // By adding this line, you can make the type of ImportMetaEnv strict + // to disallow unknown keys. + // strictImportMetaEnv: unknown +} + +interface ImportMetaEnv { + readonly VITE_API_BASE_URL: string | undefined; +} + +interface ImportMeta { + readonly env: ImportMetaEnv; +} diff --git a/apps/frontend/package.json b/apps/frontend/package.json index 8d81f1d..3f85316 100644 --- a/apps/frontend/package.json +++ b/apps/frontend/package.json @@ -7,12 +7,15 @@ "dev": "react-router dev", "start": "react-router-serve ./build/server/index.js", "typecheck": "react-router typegen && tsc", - "test": "echo \"No tests specified\" && exit 0" + "test": "echo \"No tests specified\" && exit 0", + "generate:openapi": "typed-openapi ../api/swagger.json --tanstack tanstack-client.ts -o ./app/generated/api-client.ts" }, "dependencies": { "@radix-ui/themes": "^3.2.1", "@react-router/node": "^7.9.2", "@react-router/serve": "^7.9.2", + "@tanstack/react-query": "^5.90.12", + "axios": "^1.13.2", "isbot": "^5.1.31", "radix-ui": "^1.4.3", "react": "^19.1.1", @@ -27,6 +30,7 @@ "@types/react-dom": "^19.1.9", "dotenv": "^17.2.3", "tailwindcss": "^4.1.13", + "typed-openapi": "^2.2.3", "typescript": "^5.9.2", "vite": "^7.1.7", "vite-tsconfig-paths": "^5.1.4" diff --git a/apps/frontend/pnpm-lock.yaml b/apps/frontend/pnpm-lock.yaml index 21257f5..21e2b01 100644 --- a/apps/frontend/pnpm-lock.yaml +++ b/apps/frontend/pnpm-lock.yaml @@ -17,6 +17,12 @@ importers: '@react-router/serve': specifier: ^7.9.2 version: 7.9.6(react-router@7.9.6(react-dom@19.2.0(react@19.2.0))(react@19.2.0))(typescript@5.9.3) + '@tanstack/react-query': + specifier: ^5.90.12 + version: 5.90.12(react@19.2.0) + axios: + specifier: ^1.13.2 + version: 1.13.2 isbot: specifier: ^5.1.31 version: 5.1.32 @@ -35,10 +41,10 @@ importers: devDependencies: '@react-router/dev': specifier: ^7.9.2 - version: 7.9.6(@react-router/serve@7.9.6(react-router@7.9.6(react-dom@19.2.0(react@19.2.0))(react@19.2.0))(typescript@5.9.3))(@types/node@22.19.1)(jiti@2.6.1)(lightningcss@1.30.2)(react-router@7.9.6(react-dom@19.2.0(react@19.2.0))(react@19.2.0))(typescript@5.9.3)(vite@7.2.6(@types/node@22.19.1)(jiti@2.6.1)(lightningcss@1.30.2)) + version: 7.9.6(@react-router/serve@7.9.6(react-router@7.9.6(react-dom@19.2.0(react@19.2.0))(react@19.2.0))(typescript@5.9.3))(@types/node@22.19.1)(jiti@2.6.1)(lightningcss@1.30.2)(react-router@7.9.6(react-dom@19.2.0(react@19.2.0))(react@19.2.0))(typescript@5.9.3)(vite@7.2.6(@types/node@22.19.1)(jiti@2.6.1)(lightningcss@1.30.2)(yaml@2.8.2))(yaml@2.8.2) '@tailwindcss/vite': specifier: ^4.1.13 - version: 4.1.17(vite@7.2.6(@types/node@22.19.1)(jiti@2.6.1)(lightningcss@1.30.2)) + version: 4.1.17(vite@7.2.6(@types/node@22.19.1)(jiti@2.6.1)(lightningcss@1.30.2)(yaml@2.8.2)) '@types/node': specifier: ^22 version: 22.19.1 @@ -54,18 +60,43 @@ importers: tailwindcss: specifier: ^4.1.13 version: 4.1.17 + typed-openapi: + specifier: ^2.2.3 + version: 2.2.3(openapi-types@12.1.3)(react@19.2.0) typescript: specifier: ^5.9.2 version: 5.9.3 vite: specifier: ^7.1.7 - version: 7.2.6(@types/node@22.19.1)(jiti@2.6.1)(lightningcss@1.30.2) + version: 7.2.6(@types/node@22.19.1)(jiti@2.6.1)(lightningcss@1.30.2)(yaml@2.8.2) vite-tsconfig-paths: specifier: ^5.1.4 - version: 5.1.4(typescript@5.9.3)(vite@7.2.6(@types/node@22.19.1)(jiti@2.6.1)(lightningcss@1.30.2)) + version: 5.1.4(typescript@5.9.3)(vite@7.2.6(@types/node@22.19.1)(jiti@2.6.1)(lightningcss@1.30.2)(yaml@2.8.2)) packages: + '@apidevtools/json-schema-ref-parser@11.7.2': + resolution: {integrity: sha512-4gY54eEGEstClvEkGnwVkTkrx0sqwemEFG5OSRRn3tD91XH0+Q8XIkYIfo7IwEWPpJZwILb9GUXeShtplRc/eA==} + engines: {node: '>= 16'} + + '@apidevtools/openapi-schemas@2.1.0': + resolution: {integrity: sha512-Zc1AlqrJlX3SlpupFGpiLi2EbteyP7fXmUOGup6/DnkRgjP9bgMM/ag+n91rsv0U1Gpz0H3VILA/o3bW7Ua6BQ==} + engines: {node: '>=10'} + + '@apidevtools/swagger-methods@3.0.2': + resolution: {integrity: sha512-QAkD5kK2b1WfjDS/UQn/qQkbwF31uqRjPTrsCs5ZG9BQGAkjwvqGFjjPqAuzac/IYzpPtRzjCP1WrTuAIjMrXg==} + + '@apidevtools/swagger-parser@10.1.1': + resolution: {integrity: sha512-u/kozRnsPO/x8QtKYJOqoGtC4kH6yg1lfYkB9Au0WhYB0FNLpyFusttQtvhlwjtG3rOwiRz4D8DnnXa8iEpIKA==} + peerDependencies: + openapi-types: '>=7' + + '@ark/schema@0.46.0': + resolution: {integrity: sha512-c2UQdKgP2eqqDArfBqQIJppxJHvNNXuQPeuSPlDML4rjw+f1cu0qAlzOG4b8ujgm9ctIDWwhpyw6gjG5ledIVQ==} + + '@ark/util@0.46.0': + resolution: {integrity: sha512-JPy/NGWn/lvf1WmGCPw2VGpBg5utZraE84I7wli18EDF3p3zc/e9WolT35tINeZO3l7C77SjqRJeAUoT0CvMRg==} + '@babel/code-frame@7.27.1': resolution: {integrity: sha512-cjQ7ZlQ0Mv3b47hABuTevyTuYN4i+loJKGeV9flcCgIK37cCXRh+L1bd3iBHlynerhQ7BhCkn2BPbQUL+rGqFg==} engines: {node: '>=6.9.0'} @@ -386,6 +417,9 @@ packages: '@jridgewell/trace-mapping@0.3.31': resolution: {integrity: sha512-zzNR+SdQSDJzc8joaeP8QQoCQr8NuYx2dIIytl1QeBEZHJ9uW6hebsrYgbz8hJwUQao3TWCMtmfV8Nu1twOLAw==} + '@jsdevtools/ono@7.1.3': + resolution: {integrity: sha512-4JQNk+3mVzK3xh2rqd6RB4J46qUR19azEHBneZyTZM+c456qOrbbM/5xcR8huNCCcbVt7+UmizG6GuUvPvKUYg==} + '@mjackson/node-fetch-server@0.2.0': resolution: {integrity: sha512-EMlH1e30yzmTpGLQjlFmaDAjyOeZhng1/XCd7DExR8PNAnG/G1tyruZxEoUe11ClnwGhGrtsdnyyUx1frSzjng==} @@ -1273,6 +1307,12 @@ packages: cpu: [x64] os: [win32] + '@sinclair/typebox-codegen@0.11.1': + resolution: {integrity: sha512-Bckbrf1sJFTIVD88PvI0vWUfE3Sh/6pwu6Jov+6xyMrEqnabOxEFAmPSDWjB1FGPL5C1/HfdScwa1imwAtGi9w==} + + '@sinclair/typebox@0.33.22': + resolution: {integrity: sha512-auUj4k+f4pyrIVf4GW5UKquSZFHJWri06QgARy9C0t9ZTjJLIuNIrr1yl9bWcJWJ1Gz1vOvYN1D+QPaIlNMVkQ==} + '@tailwindcss/node@4.1.17': resolution: {integrity: sha512-csIkHIgLb3JisEFQ0vxr2Y57GUNYh447C8xzwj89U/8fdW8LhProdxvnVH6U8M2Y73QKiTIH+LWbK3V2BBZsAg==} @@ -1363,9 +1403,20 @@ packages: peerDependencies: vite: ^5.2.0 || ^6 || ^7 + '@tanstack/query-core@5.90.12': + resolution: {integrity: sha512-T1/8t5DhV/SisWjDnaiU2drl6ySvsHj1bHBCWNXd+/T+Hh1cf6JodyEYMd5sgwm+b/mETT4EV3H+zCVczCU5hg==} + + '@tanstack/react-query@5.90.12': + resolution: {integrity: sha512-graRZspg7EoEaw0a8faiUASCyJrqjKPdqJ9EwuDRUF9mEYJ1YPczI9H+/agJ0mOJkPCJDk0lsz5QTrLZ/jQ2rg==} + peerDependencies: + react: ^18 || ^19 + '@types/estree@1.0.8': resolution: {integrity: sha512-dWHzHa2WqEXI/O1E9OjrocMTKJl2mSrEolh1Iomrv6U+JuNwaHXsXx9bLu5gG7BUWFIN0skIQJQ/L1rIex4X6w==} + '@types/json-schema@7.0.15': + resolution: {integrity: sha512-5+fP8P8MFNC+AyZCDxrB2pkZFPGzqQWUzpSeuuVLvm8VMcorNYavBqoFcxK8bQz4Qsbn4oUEEem4wDLfcysGHA==} + '@types/node@22.19.1': resolution: {integrity: sha512-LCCV0HdSZZZb34qifBsyWlUmok6W7ouER+oQIGBScS8EsZsQbrtFTUrDX4hOl+CS6p7cnNC4td+qrSVGSCTUfQ==} @@ -1381,6 +1432,17 @@ packages: resolution: {integrity: sha512-PYAthTa2m2VKxuvSD3DPC/Gy+U+sOA1LAuT8mkmRuvw+NACSaeXEQ+NHcVF7rONl6qcaxV3Uuemwawk+7+SJLw==} engines: {node: '>= 0.6'} + ajv-draft-04@1.0.0: + resolution: {integrity: sha512-mv00Te6nmYbRp5DCwclxtt7yV/joXJPGS7nM+97GdxvuttCOfgI3K4U25zboyeX0O+myI8ERluxQe5wljMmVIw==} + peerDependencies: + ajv: ^8.5.0 + peerDependenciesMeta: + ajv: + optional: true + + ajv@8.17.1: + resolution: {integrity: sha512-B/gBuNg5SiMTrPkC+A2+cW0RszwxYmn6VYxB/inlBStS5nx6xHIt/ehKRhIMhqusl7a8LjQoZnjCs5vhwxOQ1g==} + ansi-regex@5.0.1: resolution: {integrity: sha512-quJQXlTSUGL2LH9SUXo8VwsY4soanhgo6LNSm84E1LBcE8s3O0wpdiRzyR9z/ZZJMlMWv37qOOb9pdJlMUEKFQ==} engines: {node: '>=8'} @@ -1400,13 +1462,25 @@ packages: arg@5.0.2: resolution: {integrity: sha512-PYjyFOLKQ9y57JvQ6QLo8dAgNqswh8M1RMJYdQduT6xbWSgK36P/Z/v+p888pM69jMMfS8Xd8F6I1kQ/I9HUGg==} + argparse@2.0.1: + resolution: {integrity: sha512-8+9WqebbFzpX9OR+Wa6O29asIogeRMzcGtAINdpMHHyAg10f05aSFVBbcEqGf/PXw1EjAZ+q2/bEBg3DvurK3Q==} + aria-hidden@1.2.6: resolution: {integrity: sha512-ik3ZgC9dY/lYVVM++OISsaYDeg1tb0VtP5uL3ouh1koGOaUMDPpbFIei4JkFimWUFPn90sbMNMXQAIVOlnYKJA==} engines: {node: '>=10'} + arktype@2.1.20: + resolution: {integrity: sha512-IZCEEXaJ8g+Ijd59WtSYwtjnqXiwM8sWQ5EjGamcto7+HVN9eK0C4p0zDlCuAwWhpqr6fIBkxPuYDl4/Mcj/+Q==} + array-flatten@1.1.1: resolution: {integrity: sha512-PCVAQswWemu6UdxsDFFX/+gVeYqKAod3D3UVm91jHwynguOwAvYPhx8nNlM++NqRcK6CxxpUafjmhIdKiHibqg==} + asynckit@0.4.0: + resolution: {integrity: sha512-Oei9OH4tRh0YqU3GxhX79dM/mwVgvbZJaSNaRk+bshkj0S5cfHcgYakreBjrHwatXKbz+IoIdYLxrKim2MjW0Q==} + + axios@1.13.2: + resolution: {integrity: sha512-VPk9ebNqPcy5lRGuSlKx752IlDatOjT9paPlm8A7yOuW2Fbvp4X3JznJtT4f0GzGLLiWE9W8onz51SqLYwzGaA==} + babel-dead-code-elimination@1.0.10: resolution: {integrity: sha512-DV5bdJZTzZ0zn0DC24v3jD7Mnidh6xhKa4GfKCbq3sfW8kaWhDdZjP3i81geA8T33tdYqWKw4D3fVv0CwEgKVA==} @@ -1452,6 +1526,9 @@ packages: resolution: {integrity: sha512-+ys997U96po4Kx/ABpBCqhA9EuxJaQWDQg7295H4hBphv3IZg0boBKuwYpt4YXp6MZ5AmZQnU/tyMTlRpaSejg==} engines: {node: '>= 0.4'} + call-me-maybe@1.0.2: + resolution: {integrity: sha512-HpX65o1Hnr9HH25ojC1YGs7HCQLq0GCOibSaWER0eNpgJ/Z1MZv2mTc7+xh6WOPxbRVcmgbv4hGU+uSQ/2xFZQ==} + caniuse-lite@1.0.30001757: resolution: {integrity: sha512-r0nnL/I28Zi/yjk1el6ilj27tKcdjLsNqAOZr0yVjWPrSQyHgKI2INaEWw21bAQSv2LXRt1XuCS/GomNpWOxsQ==} @@ -1469,6 +1546,10 @@ packages: color-name@1.1.4: resolution: {integrity: sha512-dOy+3AuW3a2wNbZHIuMZpTcgjGuLU/uBL/ubcZF9OXbDo8ff4O8yVp5Bf0efS8uEoYo5q4Fx7dY9OgQGXgAsQA==} + combined-stream@1.0.8: + resolution: {integrity: sha512-FQN4MRfuJeHf7cBbBMJFXhKSDq+2kAArBlmRBvcvFE5BB1HZKXtSFASDhdlz9zOYwxh8lDdnvmMOe/+5cdoEdg==} + engines: {node: '>= 0.8'} + compressible@2.0.18: resolution: {integrity: sha512-AF3r7P5dWxL8MxyITRMlORQNaOA2IkAFaTr4k7BUumjPtRpGDTZpl0Pb1XCO6JeDCBdp126Cgs9sMxqSjgYyRg==} engines: {node: '>= 0.6'} @@ -1531,6 +1612,10 @@ packages: babel-plugin-macros: optional: true + delayed-stream@1.0.0: + resolution: {integrity: sha512-ZySD7Nf91aLB0RxL4KGrKHBXl7Eds1DAmEdcoVawXnLD7SDhpNgtuII2aAkg7a7QS41jxPSZ17p4VdGnMHk3MQ==} + engines: {node: '>=0.4.0'} + depd@2.0.0: resolution: {integrity: sha512-g7nH6P6dyDioJogAAGprGpCtVImJhpPk/roCzdb3fIh61/s/nPsfR6onyMwkCAR/OlC3yBC0lESvUoQEAssIrw==} engines: {node: '>= 0.8'} @@ -1599,6 +1684,10 @@ packages: resolution: {integrity: sha512-FGgH2h8zKNim9ljj7dankFPcICIK9Cp5bm+c2gQSYePhpaG5+esrLODihIorn+Pe6FGJzWhXQotPv73jTaldXA==} engines: {node: '>= 0.4'} + es-set-tostringtag@2.1.0: + resolution: {integrity: sha512-j6vWzfrGVfyXxge+O0x5sh6cvxAog0a/4Rdd2K36zCMV5eJ+/+tOAngRO8cODMNWbVRdVlmGZQL2YS3yR8bIUA==} + engines: {node: '>= 0.4'} + esbuild@0.25.12: resolution: {integrity: sha512-bbPBYYrtZbkt6Os6FiTLCTFxvq4tt3JKall1vRwshA3fdVztsLAatFaZobhkBC8/BrPetoa0oksYoKXoG4ryJg==} engines: {node: '>=18'} @@ -1623,6 +1712,12 @@ packages: resolution: {integrity: sha512-F2X8g9P1X7uCPZMA3MVf9wcTqlyNp7IhH5qPCI0izhaOIYXaW9L535tGA3qmjRzpH+bZczqq7hVKxTR4NWnu+g==} engines: {node: '>= 0.10.0'} + fast-deep-equal@3.1.3: + resolution: {integrity: sha512-f3qQ9oQy9j2AhBe/H9VC91wLmKBCCU/gDOnKNAYG5hswO7BLKj09Hc5HYNz9cGI++xlpDCIgDaitVs03ATR84Q==} + + fast-uri@3.1.0: + resolution: {integrity: sha512-iPeeDKJSWf4IEOasVVrknXpaBV0IApz/gp7S2bb7Z4Lljbl2MGJRqInZiUrQwV16cpzw/D3S5j5Julj/gT52AA==} + fdir@6.5.0: resolution: {integrity: sha512-tIbYtZbucOs0BRGqPJkshJUYdL+SDH7dVM8gjy+ERp3WAUjLEFJE+02kanyHtwjWOnwrKYBiwAmM0p4kLJAnXg==} engines: {node: '>=12.0.0'} @@ -1636,10 +1731,23 @@ packages: resolution: {integrity: sha512-aA4RyPcd3badbdABGDuTXCMTtOneUCAYH/gxoYRTZlIJdF0YPWuGqiAsIrhNnnqdXGswYk6dGujem4w80UJFhg==} engines: {node: '>= 0.8'} + follow-redirects@1.15.11: + resolution: {integrity: sha512-deG2P0JfjrTxl50XGCDyfI97ZGVCxIpfKYmfyrQ54n5FO/0gfIES8C/Psl6kWVDolizcaaxZJnTS0QSMxvnsBQ==} + engines: {node: '>=4.0'} + peerDependencies: + debug: '*' + peerDependenciesMeta: + debug: + optional: true + foreground-child@3.3.1: resolution: {integrity: sha512-gIXjKqtFuWEgzFRJA9WCQeSJLZDjgJUOMCMzxtvFq/37KojM1BFGufqsCy0r4qSQmYLsZYMeyRqzIWOMup03sw==} engines: {node: '>=14'} + form-data@4.0.5: + resolution: {integrity: sha512-8RipRLol37bNs2bhoV67fiTEvdTrbMUYcFTiy3+wuuOnUog2QBHCZWXDRijWQfAkhBj2Uf5UnVaiWwA5vdd82w==} + engines: {node: '>= 6'} + forwarded@0.2.0: resolution: {integrity: sha512-buRG0fpBtRHSTCOASe6hD258tEubFoRLb4ZNA6NxMVHNw2gOcwHo9wyablzMzOA5z9xA9L1KNjk/Nt6MT9aYow==} engines: {node: '>= 0.6'} @@ -1694,6 +1802,10 @@ packages: resolution: {integrity: sha512-1cDNdwJ2Jaohmb3sg4OmKaMBwuC48sYni5HUw2DvsC8LjGTLK9h+eb1X6RyuOHe4hT0ULCW68iomhjUoKUqlPQ==} engines: {node: '>= 0.4'} + has-tostringtag@1.0.2: + resolution: {integrity: sha512-NqADB8VjPFLM2V0VvHUewwwsw0ZWBaIdgo+ieHtK3hasLz4qeCRjYcqfB6AQrBggRKppKF8L52/VqdVsO47Dlw==} + engines: {node: '>= 0.4'} + hasown@2.0.2: resolution: {integrity: sha512-0hJU9SCPvmMzIBdZFqNPXWa6dqh7WdH0cII9y+CyS8rG3nL48Bclra9HmKhVVUHyPWNH5Y7xDwAB7bfgSjkUMQ==} engines: {node: '>= 0.4'} @@ -1746,6 +1858,10 @@ packages: js-tokens@4.0.0: resolution: {integrity: sha512-RdJUflcE3cUzKiMqQgsCu06FPu9UdIJO0beYbPhHN4k6apgJtifcoCtT9bcxOpYBtpD2kCM6Sbzg4CausW/PKQ==} + js-yaml@4.1.1: + resolution: {integrity: sha512-qQKT4zQxXl8lLwBtHMWwaTcGfFOZviOJet3Oy/xmGk2gZH677CJM9EvtfdSkgWcATZhj/55JZ0rmy3myCT5lsA==} + hasBin: true + jsesc@3.0.2: resolution: {integrity: sha512-xKqzzWXDttJuOcawBt4KnKHHIf5oQ/Cxax+0PWFG+DFDgHNAdi+TXECADI+RYiFUMmx8792xsMbbgXj4CwnP4g==} engines: {node: '>=6'} @@ -1755,6 +1871,9 @@ packages: resolution: {integrity: sha512-fi0NG4bPjCHunUJffmLd0gxssIgkNmArMvis4iNah6Owg1MCJjWhEcDLmsK6iGkJq3tHwbDkTlce70/tmXN4cQ==} engines: {node: ^14.17.0 || ^16.13.0 || >=18.0.0} + json-schema-traverse@1.0.0: + resolution: {integrity: sha512-NM8/P9n3XjXhIZn1lLhkFaACTOURQXjWhV4BA/RnOv8xvgqtqpAX9IO4mRQxSx1Rlo4tqzeqb0sOlruaOy3dug==} + json5@2.2.3: resolution: {integrity: sha512-XmOWe7eyHYH14cLdVPoyg+GOH3rYX++KpzrylJwSW98t3Nk+U8XOl8FWKOgwtzdb8lXGf6zYwDUzeHMWfxasyg==} engines: {node: '>=6'} @@ -1948,6 +2067,12 @@ packages: resolution: {integrity: sha512-737ZY3yNnXy37FHkQxPzt4UZ2UWPWiCZWLvFZ4fu5cueciegX0zGPnrlY6bwRg4FdQOe9YU8MkmJwGhoMybl8A==} engines: {node: '>= 0.8'} + openapi-types@12.1.3: + resolution: {integrity: sha512-N4YtSYJqghVu4iek2ZUvcN/0aqH1kRDuNqzcycDxhOUpg7GdvLa2F3DgS6yBNhInhv2r/6I0Flkn7CqL8+nIcw==} + + openapi3-ts@4.5.0: + resolution: {integrity: sha512-jaL+HgTq2Gj5jRcfdutgRGLosCy/hT8sQf6VOy+P+g36cZOjI1iukdPnijC+4CmeRzg/jEllJUboEic2FhxhtQ==} + p-map@7.0.4: resolution: {integrity: sha512-tkAQEw8ysMzmkhgw8k+1U/iPhWNhykKnSk4Rd5zLoPJCuJaGRPo6YposrZgaxHKzDHdDWWZvE/Sk7hsL2X/CpQ==} engines: {node: '>=18'} @@ -1959,6 +2084,18 @@ packages: resolution: {integrity: sha512-CiyeOxFT/JZyN5m0z9PfXw4SCBJ6Sygz1Dpl0wqjlhDEGGBP1GnsUVEL0p63hoG1fcj3fHynXi9NYO4nWOL+qQ==} engines: {node: '>= 0.8'} + pastable@2.2.1: + resolution: {integrity: sha512-K4ClMxRKpgN4sXj6VIPPrvor/TMp2yPNCGtfhvV106C73SwefQ3FuegURsH7AQHpqu0WwbvKXRl1HQxF6qax9w==} + engines: {node: '>=14.x'} + peerDependencies: + react: '>=17' + xstate: '>=4.32.1' + peerDependenciesMeta: + react: + optional: true + xstate: + optional: true + path-key@3.1.1: resolution: {integrity: sha512-ojmeN0qd+y0jszEtoY48r0Peq5dwMEkIlCOu6Q5f41lfkswXuKtYrhgoTpLnyIcHm24Uhqx+5Tqm2InSwLhE6Q==} engines: {node: '>=8'} @@ -1987,6 +2124,16 @@ packages: resolution: {integrity: sha512-3Ybi1tAuwAP9s0r1UQ2J4n5Y0G05bJkpUIO0/bI9MhwmD70S5aTWbXGBwxHrelT+XM1k6dM0pk+SwNkpTRN7Pg==} engines: {node: ^10 || ^12 || >=14} + prettier@2.8.8: + resolution: {integrity: sha512-tdN8qQGvNjw4CHbY+XXk0JgCXn9QiF21a55rBe5LJAU+kDyC4WQn4+awm2Xfk2lQMk5fKup9XgzTZtGkjBdP9Q==} + engines: {node: '>=10.13.0'} + hasBin: true + + prettier@3.5.3: + resolution: {integrity: sha512-QQtaxnoDJeAkDvDKWCLiwIXkTgRhwYDEQCghU9Z6q03iyek/rxRh/2lC3HB7P8sWT2xC/y5JDctPLBIGzHKbhw==} + engines: {node: '>=14'} + hasBin: true + prettier@3.7.3: resolution: {integrity: sha512-QgODejq9K3OzoBbuyobZlUhznP5SKwPqp+6Q6xw6o8gnhr4O85L2U915iM2IDcfF2NPXVaM9zlo9tdwipnYwzg==} engines: {node: '>=14'} @@ -2012,6 +2159,9 @@ packages: resolution: {integrity: sha512-llQsMLSUDUPT44jdrU/O37qlnifitDP+ZwrmmZcoSKyLKvtZxpyV0n2/bD/N4tBAAZ/gJEdZU7KMraoK1+XYAg==} engines: {node: '>= 0.10'} + proxy-from-env@1.1.0: + resolution: {integrity: sha512-D+zkORCbA9f1tdWRK0RaCR3GPv50cMxcrz4X8k5LTSUD1Dkw47mKJEZQNunItRTkWwgtaUSo1RVFRIG9ZXiFYg==} + qs@6.14.0: resolution: {integrity: sha512-YWWTjgABSKcvs/nWBi9PycY/JiPJqOD4JA6o9Sej2AtvSGarXxKC3OQSk4pAarbdQlKAh5D4FCQkJNkW+GAn3w==} engines: {node: '>=0.6'} @@ -2094,6 +2244,10 @@ packages: resolution: {integrity: sha512-GDhwkLfywWL2s6vEjyhri+eXmfH6j1L7JE27WhqLeYzoh/A3DBaYGEj2H/HFZCn/kMfim73FXxEJTw06WtxQwg==} engines: {node: '>= 14.18.0'} + require-from-string@2.0.2: + resolution: {integrity: sha512-Xf0nWe6RseziFMu+Ap9biiUbmplq6S9/p+7w7YXP/JBHhrUDDUhwa+vANyubuqfZWTveU//DYVGsDG7RKL/vEw==} + engines: {node: '>=0.10.0'} + retry@0.12.0: resolution: {integrity: sha512-9LkiTwjUh6rT555DtE9rTX+BKByPfrMzEAtnlEtdEwr3Nkffwiihqe2bWADg+OQRjt9gl6ICdmB/ZFDCGAtSow==} engines: {node: '>= 4'} @@ -2232,6 +2386,12 @@ packages: resolution: {integrity: sha512-o5sSPKEkg/DIQNmH43V0/uerLrpzVedkUh8tGNvaeXpfpuwjKenlSox/2O/BTlZUtEe+JG7s5YhEz608PlAHRA==} engines: {node: '>=0.6'} + ts-pattern@5.9.0: + resolution: {integrity: sha512-6s5V71mX8qBUmlgbrfL33xDUwO0fq48rxAu2LBE11WBeGdpCPOsXksQbZJHvHwhrd3QjUusd3mAOM5Gg0mFBLg==} + + ts-toolbelt@9.6.0: + resolution: {integrity: sha512-nsZd8ZeNUzukXPlJmTBwUAuABDe/9qtVDelJeT/qW0ow3ZS3BsQJtNkan1802aM9Uf68/Y8ljw86Hu0h5IUW3w==} + tsconfck@3.1.6: resolution: {integrity: sha512-ks6Vjr/jEw0P1gmOVwutM3B7fWxoWBL2KRDb1JfqGVawBmO5UsvmWOQFGHBPl5yxYz4eERr19E6L7NMv+Fej4w==} engines: {node: ^18 || >=20} @@ -2245,10 +2405,18 @@ packages: tslib@2.8.1: resolution: {integrity: sha512-oJFu94HQb+KVduSUQL7wnpmqnfmLsOA/nAh6b6EH0wCEoK0/mPeXU6c3wKDV83MkOuHPRHtSXKKU99IBazS/2w==} + type-fest@3.13.1: + resolution: {integrity: sha512-tLq3bSNx+xSpwvAJnzrK0Ep5CLNWjvFTOp71URMaAEWBfRb9nnJiBoUe0tF8bI4ZFO3omgBR6NvnbzVUT3Ly4g==} + engines: {node: '>=14.16'} + type-is@1.6.18: resolution: {integrity: sha512-TkRKr9sUTxEH8MdfuCSP7VizJyzRNMjj2J2do2Jr3Kym598JVdEksuzPQCnlFPW4ky9Q+iA+ma9BGm06XQBy8g==} engines: {node: '>= 0.6'} + typed-openapi@2.2.3: + resolution: {integrity: sha512-ZcecDxLjHuirwYmDeObAHJjuOxIut9M8FMSeKcVIGPdurYZ+c8dQwxdXTIJ+w7umnv61da1GGSuthROI684rmA==} + hasBin: true + typescript@5.9.3: resolution: {integrity: sha512-jl1vZzPDinLr9eUt3J/t7V6FgNEw9QjvBPdysz9KfQDD41fQrC2Y4vKQdiaUpFT4bXlb1RHhLpp8wtm6M5TgSw==} engines: {node: '>=14.17'} @@ -2389,8 +2557,40 @@ packages: yallist@3.1.1: resolution: {integrity: sha512-a4UGQaWPH59mOXUYnAG2ewncQS4i4F43Tv3JoAM+s2VDAmS9NsK8GpDMLrCHPksFT7h3K6TOoUNn2pb7RoXx4g==} + yaml@2.8.2: + resolution: {integrity: sha512-mplynKqc1C2hTVYxd0PU2xQAc22TI1vShAYGksCCfxbn/dFwnHTNi1bvYsBTkhdUNtGIf5xNOg938rrSSYvS9A==} + engines: {node: '>= 14.6'} + hasBin: true + snapshots: + '@apidevtools/json-schema-ref-parser@11.7.2': + dependencies: + '@jsdevtools/ono': 7.1.3 + '@types/json-schema': 7.0.15 + js-yaml: 4.1.1 + + '@apidevtools/openapi-schemas@2.1.0': {} + + '@apidevtools/swagger-methods@3.0.2': {} + + '@apidevtools/swagger-parser@10.1.1(openapi-types@12.1.3)': + dependencies: + '@apidevtools/json-schema-ref-parser': 11.7.2 + '@apidevtools/openapi-schemas': 2.1.0 + '@apidevtools/swagger-methods': 3.0.2 + '@jsdevtools/ono': 7.1.3 + ajv: 8.17.1 + ajv-draft-04: 1.0.0(ajv@8.17.1) + call-me-maybe: 1.0.2 + openapi-types: 12.1.3 + + '@ark/schema@0.46.0': + dependencies: + '@ark/util': 0.46.0 + + '@ark/util@0.46.0': {} + '@babel/code-frame@7.27.1': dependencies: '@babel/helper-validator-identifier': 7.28.5 @@ -2700,6 +2900,8 @@ snapshots: '@jridgewell/resolve-uri': 3.1.2 '@jridgewell/sourcemap-codec': 1.5.5 + '@jsdevtools/ono@7.1.3': {} + '@mjackson/node-fetch-server@0.2.0': {} '@npmcli/git@4.1.0': @@ -3495,7 +3697,7 @@ snapshots: '@types/react': 19.2.7 '@types/react-dom': 19.2.3(@types/react@19.2.7) - '@react-router/dev@7.9.6(@react-router/serve@7.9.6(react-router@7.9.6(react-dom@19.2.0(react@19.2.0))(react@19.2.0))(typescript@5.9.3))(@types/node@22.19.1)(jiti@2.6.1)(lightningcss@1.30.2)(react-router@7.9.6(react-dom@19.2.0(react@19.2.0))(react@19.2.0))(typescript@5.9.3)(vite@7.2.6(@types/node@22.19.1)(jiti@2.6.1)(lightningcss@1.30.2))': + '@react-router/dev@7.9.6(@react-router/serve@7.9.6(react-router@7.9.6(react-dom@19.2.0(react@19.2.0))(react@19.2.0))(typescript@5.9.3))(@types/node@22.19.1)(jiti@2.6.1)(lightningcss@1.30.2)(react-router@7.9.6(react-dom@19.2.0(react@19.2.0))(react@19.2.0))(typescript@5.9.3)(vite@7.2.6(@types/node@22.19.1)(jiti@2.6.1)(lightningcss@1.30.2)(yaml@2.8.2))(yaml@2.8.2)': dependencies: '@babel/core': 7.28.5 '@babel/generator': 7.28.5 @@ -3525,8 +3727,8 @@ snapshots: semver: 7.7.3 tinyglobby: 0.2.15 valibot: 1.2.0(typescript@5.9.3) - vite: 7.2.6(@types/node@22.19.1)(jiti@2.6.1)(lightningcss@1.30.2) - vite-node: 3.2.4(@types/node@22.19.1)(jiti@2.6.1)(lightningcss@1.30.2) + vite: 7.2.6(@types/node@22.19.1)(jiti@2.6.1)(lightningcss@1.30.2)(yaml@2.8.2) + vite-node: 3.2.4(@types/node@22.19.1)(jiti@2.6.1)(lightningcss@1.30.2)(yaml@2.8.2) optionalDependencies: '@react-router/serve': 7.9.6(react-router@7.9.6(react-dom@19.2.0(react@19.2.0))(react@19.2.0))(typescript@5.9.3) typescript: 5.9.3 @@ -3644,6 +3846,14 @@ snapshots: '@rollup/rollup-win32-x64-msvc@4.53.3': optional: true + '@sinclair/typebox-codegen@0.11.1': + dependencies: + '@sinclair/typebox': 0.33.22 + prettier: 2.8.8 + typescript: 5.9.3 + + '@sinclair/typebox@0.33.22': {} + '@tailwindcss/node@4.1.17': dependencies: '@jridgewell/remapping': 2.3.5 @@ -3705,15 +3915,24 @@ snapshots: '@tailwindcss/oxide-win32-arm64-msvc': 4.1.17 '@tailwindcss/oxide-win32-x64-msvc': 4.1.17 - '@tailwindcss/vite@4.1.17(vite@7.2.6(@types/node@22.19.1)(jiti@2.6.1)(lightningcss@1.30.2))': + '@tailwindcss/vite@4.1.17(vite@7.2.6(@types/node@22.19.1)(jiti@2.6.1)(lightningcss@1.30.2)(yaml@2.8.2))': dependencies: '@tailwindcss/node': 4.1.17 '@tailwindcss/oxide': 4.1.17 tailwindcss: 4.1.17 - vite: 7.2.6(@types/node@22.19.1)(jiti@2.6.1)(lightningcss@1.30.2) + vite: 7.2.6(@types/node@22.19.1)(jiti@2.6.1)(lightningcss@1.30.2)(yaml@2.8.2) + + '@tanstack/query-core@5.90.12': {} + + '@tanstack/react-query@5.90.12(react@19.2.0)': + dependencies: + '@tanstack/query-core': 5.90.12 + react: 19.2.0 '@types/estree@1.0.8': {} + '@types/json-schema@7.0.15': {} + '@types/node@22.19.1': dependencies: undici-types: 6.21.0 @@ -3731,6 +3950,17 @@ snapshots: mime-types: 2.1.35 negotiator: 0.6.3 + ajv-draft-04@1.0.0(ajv@8.17.1): + optionalDependencies: + ajv: 8.17.1 + + ajv@8.17.1: + dependencies: + fast-deep-equal: 3.1.3 + fast-uri: 3.1.0 + json-schema-traverse: 1.0.0 + require-from-string: 2.0.2 + ansi-regex@5.0.1: {} ansi-regex@6.2.2: {} @@ -3743,12 +3973,29 @@ snapshots: arg@5.0.2: {} + argparse@2.0.1: {} + aria-hidden@1.2.6: dependencies: tslib: 2.8.1 + arktype@2.1.20: + dependencies: + '@ark/schema': 0.46.0 + '@ark/util': 0.46.0 + array-flatten@1.1.1: {} + asynckit@0.4.0: {} + + axios@1.13.2: + dependencies: + follow-redirects: 1.15.11 + form-data: 4.0.5 + proxy-from-env: 1.1.0 + transitivePeerDependencies: + - debug + babel-dead-code-elimination@1.0.10: dependencies: '@babel/core': 7.28.5 @@ -3811,6 +4058,8 @@ snapshots: call-bind-apply-helpers: 1.0.2 get-intrinsic: 1.3.0 + call-me-maybe@1.0.2: {} + caniuse-lite@1.0.30001757: {} chokidar@4.0.3: @@ -3825,6 +4074,10 @@ snapshots: color-name@1.1.4: {} + combined-stream@1.0.8: + dependencies: + delayed-stream: 1.0.0 + compressible@2.0.18: dependencies: mime-db: 1.54.0 @@ -3873,6 +4126,8 @@ snapshots: dedent@1.7.0: {} + delayed-stream@1.0.0: {} + depd@2.0.0: {} destroy@1.2.0: {} @@ -3920,6 +4175,13 @@ snapshots: dependencies: es-errors: 1.3.0 + es-set-tostringtag@2.1.0: + dependencies: + es-errors: 1.3.0 + get-intrinsic: 1.3.0 + has-tostringtag: 1.0.2 + hasown: 2.0.2 + esbuild@0.25.12: optionalDependencies: '@esbuild/aix-ppc64': 0.25.12 @@ -3993,6 +4255,10 @@ snapshots: transitivePeerDependencies: - supports-color + fast-deep-equal@3.1.3: {} + + fast-uri@3.1.0: {} + fdir@6.5.0(picomatch@4.0.3): optionalDependencies: picomatch: 4.0.3 @@ -4009,11 +4275,21 @@ snapshots: transitivePeerDependencies: - supports-color + follow-redirects@1.15.11: {} + foreground-child@3.3.1: dependencies: cross-spawn: 7.0.6 signal-exit: 4.1.0 + form-data@4.0.5: + dependencies: + asynckit: 0.4.0 + combined-stream: 1.0.8 + es-set-tostringtag: 2.1.0 + hasown: 2.0.2 + mime-types: 2.1.35 + forwarded@0.2.0: {} fresh@0.5.2: {} @@ -4064,6 +4340,10 @@ snapshots: has-symbols@1.1.0: {} + has-tostringtag@1.0.2: + dependencies: + has-symbols: 1.1.0 + hasown@2.0.2: dependencies: function-bind: 1.1.2 @@ -4116,10 +4396,16 @@ snapshots: js-tokens@4.0.0: {} + js-yaml@4.1.1: + dependencies: + argparse: 2.0.1 + jsesc@3.0.2: {} json-parse-even-better-errors@3.0.2: {} + json-schema-traverse@1.0.0: {} + json5@2.2.3: {} lightningcss-android-arm64@1.30.2: @@ -4270,12 +4556,28 @@ snapshots: on-headers@1.1.0: {} + openapi-types@12.1.3: {} + + openapi3-ts@4.5.0: + dependencies: + yaml: 2.8.2 + p-map@7.0.4: {} package-json-from-dist@1.0.1: {} parseurl@1.3.3: {} + pastable@2.2.1(react@19.2.0): + dependencies: + '@babel/core': 7.28.5 + ts-toolbelt: 9.6.0 + type-fest: 3.13.1 + optionalDependencies: + react: 19.2.0 + transitivePeerDependencies: + - supports-color + path-key@3.1.1: {} path-scurry@1.11.1: @@ -4299,6 +4601,10 @@ snapshots: picocolors: 1.1.1 source-map-js: 1.2.1 + prettier@2.8.8: {} + + prettier@3.5.3: {} + prettier@3.7.3: {} proc-log@3.0.0: {} @@ -4315,6 +4621,8 @@ snapshots: forwarded: 0.2.0 ipaddr.js: 1.9.1 + proxy-from-env@1.1.0: {} + qs@6.14.0: dependencies: side-channel: 1.1.0 @@ -4437,6 +4745,8 @@ snapshots: readdirp@4.1.2: {} + require-from-string@2.0.2: {} + retry@0.12.0: {} rollup@4.53.3: @@ -4622,17 +4932,40 @@ snapshots: toidentifier@1.0.1: {} + ts-pattern@5.9.0: {} + + ts-toolbelt@9.6.0: {} + tsconfck@3.1.6(typescript@5.9.3): optionalDependencies: typescript: 5.9.3 tslib@2.8.1: {} + type-fest@3.13.1: {} + type-is@1.6.18: dependencies: media-typer: 0.3.0 mime-types: 2.1.35 + typed-openapi@2.2.3(openapi-types@12.1.3)(react@19.2.0): + dependencies: + '@apidevtools/swagger-parser': 10.1.1(openapi-types@12.1.3) + '@sinclair/typebox-codegen': 0.11.1 + arktype: 2.1.20 + cac: 6.7.14 + openapi3-ts: 4.5.0 + pastable: 2.2.1(react@19.2.0) + pathe: 2.0.3 + prettier: 3.5.3 + ts-pattern: 5.9.0 + transitivePeerDependencies: + - openapi-types + - react + - supports-color + - xstate + typescript@5.9.3: {} undici-types@6.21.0: {} @@ -4679,13 +5012,13 @@ snapshots: vary@1.1.2: {} - vite-node@3.2.4(@types/node@22.19.1)(jiti@2.6.1)(lightningcss@1.30.2): + vite-node@3.2.4(@types/node@22.19.1)(jiti@2.6.1)(lightningcss@1.30.2)(yaml@2.8.2): dependencies: cac: 6.7.14 debug: 4.4.3 es-module-lexer: 1.7.0 pathe: 2.0.3 - vite: 7.2.6(@types/node@22.19.1)(jiti@2.6.1)(lightningcss@1.30.2) + vite: 7.2.6(@types/node@22.19.1)(jiti@2.6.1)(lightningcss@1.30.2)(yaml@2.8.2) transitivePeerDependencies: - '@types/node' - jiti @@ -4700,18 +5033,18 @@ snapshots: - tsx - yaml - vite-tsconfig-paths@5.1.4(typescript@5.9.3)(vite@7.2.6(@types/node@22.19.1)(jiti@2.6.1)(lightningcss@1.30.2)): + vite-tsconfig-paths@5.1.4(typescript@5.9.3)(vite@7.2.6(@types/node@22.19.1)(jiti@2.6.1)(lightningcss@1.30.2)(yaml@2.8.2)): dependencies: debug: 4.4.3 globrex: 0.1.2 tsconfck: 3.1.6(typescript@5.9.3) optionalDependencies: - vite: 7.2.6(@types/node@22.19.1)(jiti@2.6.1)(lightningcss@1.30.2) + vite: 7.2.6(@types/node@22.19.1)(jiti@2.6.1)(lightningcss@1.30.2)(yaml@2.8.2) transitivePeerDependencies: - supports-color - typescript - vite@7.2.6(@types/node@22.19.1)(jiti@2.6.1)(lightningcss@1.30.2): + vite@7.2.6(@types/node@22.19.1)(jiti@2.6.1)(lightningcss@1.30.2)(yaml@2.8.2): dependencies: esbuild: 0.25.12 fdir: 6.5.0(picomatch@4.0.3) @@ -4724,6 +5057,7 @@ snapshots: fsevents: 2.3.3 jiti: 2.6.1 lightningcss: 1.30.2 + yaml: 2.8.2 which@2.0.2: dependencies: @@ -4746,3 +5080,5 @@ snapshots: strip-ansi: 7.1.2 yallist@3.1.1: {} + + yaml@2.8.2: {} diff --git a/apps/frontend/tsconfig.json b/apps/frontend/tsconfig.json index a6b90b7..719d518 100644 --- a/apps/frontend/tsconfig.json +++ b/apps/frontend/tsconfig.json @@ -12,6 +12,7 @@ "paths": { "~/*": ["./app/*"] }, + "allowImportingTsExtensions": true, "esModuleInterop": true, "verbatimModuleSyntax": true, "noEmit": true, diff --git a/justfile b/justfile index 14a1462..1a50f91 100644 --- a/justfile +++ b/justfile @@ -46,6 +46,8 @@ generate-openapi: cd apps/api && \ cargo run -- generate:openapi --output-path ./swagger.json +generate-all: generate-entity generate-openapi + build-frontend: # build frontend assets cd apps/frontend && \ @@ -56,7 +58,7 @@ build-backend: cd apps/api && \ cargo build --release -build: build-frontend build-backend +build-apps: build-frontend build-backend act *args: if [ -n "{{args}}" ]; then \ -- 2.49.1 From d33f4f103fd819a4829525bb67b1215ece7731c5 Mon Sep 17 00:00:00 2001 From: GW_MC <72297530+GWMCwing@users.noreply.github.com> Date: Fri, 5 Dec 2025 20:36:54 +0800 Subject: [PATCH 08/10] move generated client into generated/api-client --- .../generated/{ => api-client}/api-client.ts | 128 +++++++++++------- .../{ => api-client}/tanstack-client.ts | 0 apps/frontend/app/lib/api.ts | 2 +- apps/frontend/package.json | 2 +- 4 files changed, 80 insertions(+), 52 deletions(-) rename apps/frontend/app/generated/{ => api-client}/api-client.ts (80%) rename apps/frontend/app/generated/{ => api-client}/tanstack-client.ts (100%) diff --git a/apps/frontend/app/generated/api-client.ts b/apps/frontend/app/generated/api-client/api-client.ts similarity index 80% rename from apps/frontend/app/generated/api-client.ts rename to apps/frontend/app/generated/api-client/api-client.ts index 67c0787..8a5e6b3 100644 --- a/apps/frontend/app/generated/api-client.ts +++ b/apps/frontend/app/generated/api-client/api-client.ts @@ -14,9 +14,9 @@ export namespace Endpoints { // export type get_Get_health_info = { - method: 'GET'; - path: '/api/health/info'; - requestFormat: 'json'; + method: "GET"; + path: "/api/health/info"; + requestFormat: "json"; parameters: never; responses: { 200: Schemas.HealthInfo; 404: unknown }; }; @@ -27,14 +27,14 @@ export namespace Endpoints { // export type EndpointByMethod = { get: { - '/api/health/info': Endpoints.get_Get_health_info; + "/api/health/info": Endpoints.get_Get_health_info; }; }; // // -export type GetEndpoints = EndpointByMethod['get']; +export type GetEndpoints = EndpointByMethod["get"]; // // @@ -45,10 +45,10 @@ export type EndpointParameters = { path?: Record; }; -export type MutationMethod = 'post' | 'put' | 'patch' | 'delete'; -export type Method = 'get' | 'head' | 'options' | MutationMethod; +export type MutationMethod = "post" | "put" | "patch" | "delete"; +export type Method = "get" | "head" | "options" | MutationMethod; -type RequestFormat = 'json' | 'form-data' | 'form-url' | 'binary' | 'text'; +type RequestFormat = "json" | "form-data" | "form-url" | "binary" | "text"; export type DefaultEndpoint = { parameters?: EndpointParameters | undefined; @@ -61,14 +61,14 @@ export type Endpoint = { method: Method; path: string; requestFormat: RequestFormat; - parameters?: TConfig['parameters']; + parameters?: TConfig["parameters"]; meta: { alias: string; hasParameters: boolean; areParametersRequired: boolean; }; - responses?: TConfig['responses']; - responseHeaders?: TConfig['responseHeaders']; + responses?: TConfig["responses"]; + responseHeaders?: TConfig["responseHeaders"]; }; export interface Fetcher { @@ -87,28 +87,30 @@ export interface Fetcher { parseResponseData?: (response: Response) => Promise; } -export const successStatusCodes = [200, 201, 202, 203, 204, 205, 206, 207, 208, 226, 300, 301, 302, 303, 304, 305, 306, 307, 308] as const; +export const successStatusCodes = [ + 200, 201, 202, 203, 204, 205, 206, 207, 208, 226, 300, 301, 302, 303, 304, 305, 306, 307, 308, +] as const; export type SuccessStatusCode = (typeof successStatusCodes)[number]; export const errorStatusCodes = [ - 400, 401, 402, 403, 404, 405, 406, 407, 408, 409, 410, 411, 412, 413, 414, 415, 416, 417, 418, 421, 422, 423, 424, 425, 426, 428, 429, 431, 451, 500, 501, 502, 503, - 504, 505, 506, 507, 508, 510, 511, + 400, 401, 402, 403, 404, 405, 406, 407, 408, 409, 410, 411, 412, 413, 414, 415, 416, 417, 418, 421, 422, 423, 424, + 425, 426, 428, 429, 431, 451, 500, 501, 502, 503, 504, 505, 506, 507, 508, 510, 511, ] as const; export type ErrorStatusCode = (typeof errorStatusCodes)[number]; // Taken from https://github.com/unjs/fetchdts/blob/ec4eaeab5d287116171fc1efd61f4a1ad34e4609/src/fetch.ts#L3 export interface TypedHeaders | unknown> - extends Omit { + extends Omit { /** [MDN Reference](https://developer.mozilla.org/docs/Web/API/Headers/append) */ append: | (string & {})>( name: Name, - value: Lowercase extends keyof TypedHeaderValues ? TypedHeaderValues[Lowercase] : string + value: Lowercase extends keyof TypedHeaderValues ? TypedHeaderValues[Lowercase] : string, ) => void; /** [MDN Reference](https://developer.mozilla.org/docs/Web/API/Headers/delete) */ delete: | (string & {})>(name: Name) => void; /** [MDN Reference](https://developer.mozilla.org/docs/Web/API/Headers/get) */ get: | (string & {})>( - name: Name + name: Name, ) => (Lowercase extends keyof TypedHeaderValues ? TypedHeaderValues[Lowercase] : string) | null; /** [MDN Reference](https://developer.mozilla.org/docs/Web/API/Headers/getSetCookie) */ getSetCookie: () => string[]; @@ -117,20 +119,21 @@ export interface TypedHeaders | /** [MDN Reference](https://developer.mozilla.org/docs/Web/API/Headers/set) */ set: | (string & {})>( name: Name, - value: Lowercase extends keyof TypedHeaderValues ? TypedHeaderValues[Lowercase] : string + value: Lowercase extends keyof TypedHeaderValues ? TypedHeaderValues[Lowercase] : string, ) => void; forEach: ( callbackfn: ( value: TypedHeaderValues[keyof TypedHeaderValues] | (string & {}), key: Extract | (string & {}), - parent: TypedHeaders + parent: TypedHeaders, ) => void, - thisArg?: any + thisArg?: any, ) => void; } /** @see https://developer.mozilla.org/en-US/docs/Web/API/Response */ -export interface TypedSuccessResponse extends Omit { +export interface TypedSuccessResponse + extends Omit { ok: true; status: TStatusCode; headers: never extends THeaders ? Headers : TypedHeaders; @@ -140,7 +143,8 @@ export interface TypedSuccessResponse extends O } /** @see https://developer.mozilla.org/en-US/docs/Web/API/Response */ -export interface TypedErrorResponse extends Omit { +export interface TypedErrorResponse + extends Omit { ok: false; status: TStatusCode; headers: never extends THeaders ? Headers : TypedHeaders; @@ -157,10 +161,10 @@ export type TypedApiResponse : never : K extends number - ? K extends SuccessStatusCode - ? TypedSuccessResponse - : TypedErrorResponse - : never; + ? K extends SuccessStatusCode + ? TypedSuccessResponse + : TypedErrorResponse + : never; }[keyof TAllResponses]; export type SafeApiResponse = TEndpoint extends { responses: infer TResponses } @@ -169,7 +173,10 @@ export type SafeApiResponse = TEndpoint extends { responses: infer TR : never : never; -export type InferResponseByStatus = Extract, { status: TStatusCode }>; +export type InferResponseByStatus = Extract< + SafeApiResponse, + { status: TStatusCode } +>; type RequiredKeys = { [P in keyof T]-?: undefined extends T[P] ? never : P; @@ -186,7 +193,7 @@ export class TypedStatusError extends Error { status: number; constructor(response: TypedErrorResponse) { super(`HTTP ${response.status}: ${response.statusText}`); - this.name = 'TypedStatusError'; + this.name = "TypedStatusError"; this.response = response; this.status = response.status; } @@ -195,7 +202,7 @@ export class TypedStatusError extends Error { // export class ApiClient { - baseUrl: string = ''; + baseUrl: string = ""; successStatusCodes = successStatusCodes; errorStatusCodes = errorStatusCodes; @@ -211,7 +218,9 @@ export class ApiClient { * Supports both OpenAPI format {param} and Express format :param */ defaultDecodePathParams = (url: string, params: Record): string => { - return url.replace(/{(\w+)}/g, (_, key: string) => params[key] || `{${key}}`).replace(/:([a-zA-Z0-9_]+)/g, (_, key: string) => params[key] || `:${key}`); + return url + .replace(/{(\w+)}/g, (_, key: string) => params[key] || `{${key}}`) + .replace(/:([a-zA-Z0-9_]+)/g, (_, key: string) => params[key] || `:${key}`); }; /** Uses URLSearchParams, skips null/undefined values */ @@ -234,16 +243,20 @@ export class ApiClient { }; defaultParseResponseData = async (response: Response): Promise => { - const contentType = response.headers.get('content-type') ?? ''; - if (contentType.startsWith('text/')) { + const contentType = response.headers.get("content-type") ?? ""; + if (contentType.startsWith("text/")) { return await response.text(); } - if (contentType === 'application/octet-stream') { + if (contentType === "application/octet-stream") { return await response.arrayBuffer(); } - if (contentType.includes('application/json') || (contentType.includes('application/') && contentType.includes('json')) || contentType === '*/*') { + if ( + contentType.includes("application/json") || + (contentType.includes("application/") && contentType.includes("json")) || + contentType === "*/*" + ) { try { return await response.json(); } catch { @@ -264,7 +277,7 @@ export class ApiClient { : { overrides?: RequestInit; withResponse?: false; throwOnStatusError?: boolean } : { overrides?: RequestInit; withResponse?: false; throwOnStatusError?: boolean } > - ): Promise, { data: {} }>['data']>; + ): Promise, { data: {} }>["data"]>; get( path: Path, @@ -277,8 +290,11 @@ export class ApiClient { > ): Promise>; - get(path: Path, ...params: MaybeOptionalArg): Promise { - return this.request('get', path, ...params); + get( + path: Path, + ...params: MaybeOptionalArg + ): Promise { + return this.request("get", path, ...params); } // @@ -286,7 +302,11 @@ export class ApiClient { /** * Generic request method with full type-safety for any endpoint */ - request( + request< + TMethod extends keyof EndpointByMethod, + TPath extends keyof EndpointByMethod[TMethod], + TEndpoint extends EndpointByMethod[TMethod][TPath], + >( method: TMethod, path: TPath, ...params: MaybeOptionalArg< @@ -296,9 +316,13 @@ export class ApiClient { : { overrides?: RequestInit; withResponse?: false; throwOnStatusError?: boolean } : { overrides?: RequestInit; withResponse?: false; throwOnStatusError?: boolean } > - ): Promise, { data: {} }>['data']>; + ): Promise, { data: {} }>["data"]>; - request( + request< + TMethod extends keyof EndpointByMethod, + TPath extends keyof EndpointByMethod[TMethod], + TEndpoint extends EndpointByMethod[TMethod][TPath], + >( method: TMethod, path: TPath, ...params: MaybeOptionalArg< @@ -310,14 +334,19 @@ export class ApiClient { > ): Promise>; - request( - method: TMethod, - path: TPath, - ...params: MaybeOptionalArg - ): Promise { + request< + TMethod extends keyof EndpointByMethod, + TPath extends keyof EndpointByMethod[TMethod], + TEndpoint extends EndpointByMethod[TMethod][TPath], + >(method: TMethod, path: TPath, ...params: MaybeOptionalArg): Promise { const requestParams = params[0]; const withResponse = requestParams?.withResponse; - const { withResponse: _, throwOnStatusError = withResponse ? false : true, overrides, ...fetchParams } = requestParams || {}; + const { + withResponse: _, + throwOnStatusError = withResponse ? false : true, + overrides, + ...fetchParams + } = requestParams || {}; const parametersToSend: EndpointParameters = {}; if (requestParams?.body !== undefined) (parametersToSend as any).body = requestParams.body; @@ -327,9 +356,8 @@ export class ApiClient { const resolvedPath = (this.fetcher.decodePathParams ?? this.defaultDecodePathParams)( this.baseUrl + (path as string), - (parametersToSend.path ?? {}) as Record + (parametersToSend.path ?? {}) as Record, ); - console.log('Resolved Path:', resolvedPath); const url = new URL(resolvedPath); const urlSearchParams = (this.fetcher.encodeSearchParams ?? this.defaultEncodeSearchParams)(parametersToSend.query); @@ -357,13 +385,13 @@ export class ApiClient { return withResponse ? typedResponse : data; }); - return promise as Extract, { data: {} }>['data']; + return promise as Extract, { data: {} }>["data"]; } // } export function createApiClient(fetcher: Fetcher, baseUrl?: string) { - return new ApiClient(fetcher).setBaseUrl(baseUrl ?? ''); + return new ApiClient(fetcher).setBaseUrl(baseUrl ?? ""); } /** diff --git a/apps/frontend/app/generated/tanstack-client.ts b/apps/frontend/app/generated/api-client/tanstack-client.ts similarity index 100% rename from apps/frontend/app/generated/tanstack-client.ts rename to apps/frontend/app/generated/api-client/tanstack-client.ts diff --git a/apps/frontend/app/lib/api.ts b/apps/frontend/app/lib/api.ts index 0c54e4f..d201d9a 100644 --- a/apps/frontend/app/lib/api.ts +++ b/apps/frontend/app/lib/api.ts @@ -1,5 +1,5 @@ import type { AxiosInstance, AxiosResponse } from 'axios'; -import { type Fetcher, type Method, createApiClient } from '../generated/api-client'; +import { type Fetcher, type Method, createApiClient } from '../generated/api-client/api-client'; import { TanstackQueryApiClient } from '../generated/tanstack-client'; const API_BASE_URL: string | undefined = import.meta.env.VITE_API_BASE_URL; diff --git a/apps/frontend/package.json b/apps/frontend/package.json index 3f85316..9f9b8a4 100644 --- a/apps/frontend/package.json +++ b/apps/frontend/package.json @@ -8,7 +8,7 @@ "start": "react-router-serve ./build/server/index.js", "typecheck": "react-router typegen && tsc", "test": "echo \"No tests specified\" && exit 0", - "generate:openapi": "typed-openapi ../api/swagger.json --tanstack tanstack-client.ts -o ./app/generated/api-client.ts" + "generate:openapi": "typed-openapi ../api/swagger.json --tanstack tanstack-client.ts -o ./app/generated/api-client/api-client.ts" }, "dependencies": { "@radix-ui/themes": "^3.2.1", -- 2.49.1 From 75a3777cb0b9a6217a97a52361bfc50c51c75b8e Mon Sep 17 00:00:00 2001 From: GW_MC <72297530+GWMCwing@users.noreply.github.com> Date: Fri, 5 Dec 2025 20:40:11 +0800 Subject: [PATCH 09/10] add verify frontend api client --- .github/workflows/verify.yml | 83 ++++++++++++++++++++++++++++++++++++ 1 file changed, 83 insertions(+) diff --git a/.github/workflows/verify.yml b/.github/workflows/verify.yml index 207b978..2f88c0a 100644 --- a/.github/workflows/verify.yml +++ b/.github/workflows/verify.yml @@ -110,3 +110,86 @@ jobs: - name: Skip OpenAPI generation (no relevant changes) if: steps.check_changes.outputs.changed == 'false' run: echo "No changes in apps/api/src/routes/ nor apps/api/swagger.json, skipping OpenAPI generation verification." + + verify-frontend-api-client: + runs-on: ubuntu-latest + needs: verify-openapi-spec + steps: + - name: Checkout repository + uses: actions/checkout@v3 + with: + fetch-depth: 0 + + - name: Check whether apps/api/swagger.json or apps/frontend/app/generated/api-client changed + id: check_swagger_changes + run: | + if [ "${{ github.event_name }}" = "pull_request" ]; then + BASE_SHA=${{ github.event.pull_request.base.sha }} + HEAD_SHA=${{ github.event.pull_request.head.sha }} + else + BASE_SHA=${{ github.event.before }} + HEAD_SHA=${{ github.sha }} + fi + + # Provide safe fallbacks when GitHub context values are empty (e.g. when using act) + if [ -z "$HEAD_SHA" ]; then + HEAD_SHA=$(git rev-parse --verify HEAD 2>/dev/null || echo "") + fi + + if [ -z "$BASE_SHA" ]; then + # Try the parent of HEAD, fall back to HEAD if unavailable + PREV=$(git rev-parse --verify "${HEAD_SHA}^" 2>/dev/null || true) + if [ -n "$PREV" ]; then + BASE_SHA=$PREV + else + BASE_SHA=$HEAD_SHA + fi + fi + + echo "Comparing $BASE_SHA..$HEAD_SHA" + CHANGED_FILES=$(git diff --name-only "$BASE_SHA" "$HEAD_SHA" || true) + echo "$CHANGED_FILES" + + echo "$CHANGED_FILES" | grep -E '^(apps/api/swagger.json|apps/frontend/app/generated/api-client)' >/dev/null 2>&1 && echo "changed=true" >> $GITHUB_OUTPUT || echo "changed=false" >> $GITHUB_OUTPUT + + - name: Setup PNPM + uses: pnpm/action-setup@v4 + if: steps.check_swagger_changes.outputs.changed == 'true' + with: + version: 10 + run_install: false + + - name: Setup Node.js + uses: actions/setup-node@v4 + if: steps.check_swagger_changes.outputs.changed == 'true' + with: + node-version: 22 + cache: 'pnpm' + cache-dependency-path: apps/frontend/pnpm-lock.yaml + + - name: Install frontend dependencies + if: steps.check_swagger_changes.outputs.changed == 'true' + run: | + cd apps/frontend + pnpm install + + - name: Generate frontend API client + if: steps.check_swagger_changes.outputs.changed == 'true' + run: | + cd apps/frontend + pnpm generate:openapi + + - name: Check for uncommitted changes in frontend API client + if: steps.check_swagger_changes.outputs.changed == 'true' + run: | + if [[ -n $(git status --porcelain | grep '^ M apps/frontend/app/generated/api-client') ]]; then + echo "Frontend API client is not up to date. Please run the API client generation locally and commit the changes." + git status --porcelain | grep '^ M apps/frontend/app/generated/api-client' + exit 1 + else + echo "Frontend API client is up to date." + fi + + - name: Skip frontend API client generation (no relevant changes) + if: steps.check_swagger_changes.outputs.changed == 'false' + run: echo "No changes in apps/api/swagger.json nor apps/frontend/app/generated/api-client, skipping frontend API client generation verification." \ No newline at end of file -- 2.49.1 From 5e0ab960f9ee34583a6ca2b81018e1ed416402be Mon Sep 17 00:00:00 2001 From: GW_MC <72297530+GWMCwing@users.noreply.github.com> Date: Fri, 5 Dec 2025 20:43:46 +0800 Subject: [PATCH 10/10] fix: update import path for TanstackQueryApiClient to use the correct generated client --- apps/frontend/app/lib/api.ts | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/apps/frontend/app/lib/api.ts b/apps/frontend/app/lib/api.ts index d201d9a..97e72ad 100644 --- a/apps/frontend/app/lib/api.ts +++ b/apps/frontend/app/lib/api.ts @@ -1,6 +1,6 @@ import type { AxiosInstance, AxiosResponse } from 'axios'; import { type Fetcher, type Method, createApiClient } from '../generated/api-client/api-client'; -import { TanstackQueryApiClient } from '../generated/tanstack-client'; +import { TanstackQueryApiClient } from '../generated/api-client/tanstack-client'; const API_BASE_URL: string | undefined = import.meta.env.VITE_API_BASE_URL; -- 2.49.1