Modern Docker Management, Designed for Everyone
Go composecontainer-managementcontainersdockerdocker-composedocker-managementgoself-hostedsveltekittypescriptweb-ui
refactor: generalize environment routes into individual handlers (#568)
Kyle Mendell4e535f5a8565
diff --git a/backend/go.mod b/backend/go.modindex b4fe3c952..bb2ac16ec 100644--- a/backend/go.mod+++ b/backend/go.mod@@ -15,6 +15,7 @@ require (github.com/gin-gonic/gin v1.11.0github.com/glebarez/sqlite v1.11.0github.com/go-co-op/gocron/v2 v2.16.6+ github.com/goccy/go-yaml v1.18.0github.com/golang-jwt/jwt/v5 v5.3.0github.com/golang-migrate/migrate/v4 v4.19.0github.com/google/uuid v1.6.0@@ -27,7 +28,6 @@ require (github.com/samber/slog-gin v1.17.2github.com/shirou/gopsutil/v3 v3.24.5github.com/stretchr/testify v1.11.1- go.yaml.in/yaml/v4 v4.0.0-rc.2golang.org/x/crypto v0.42.0golang.org/x/sync v0.17.0gorm.io/driver/postgres v1.6.0@@ -112,7 +112,6 @@ require (github.com/go-playground/validator/v10 v10.27.0 // indirectgithub.com/go-viper/mapstructure/v2 v2.4.0 // indirectgithub.com/goccy/go-json v0.10.5 // indirect- github.com/goccy/go-yaml v1.18.0 // indirectgithub.com/gofrs/flock v0.12.1 // indirectgithub.com/gogo/protobuf v1.3.2 // indirectgithub.com/golang/protobuf v1.5.4 // indirectdiff --git a/backend/go.sum b/backend/go.sumindex 0b8c6f765..85123b96a 100644--- a/backend/go.sum+++ b/backend/go.sum@@ -659,8 +659,6 @@ go.yaml.in/yaml/v2 v2.4.3 h1:6gvOSjQoTB3vt1l+CU+tSyi/HOjfOjRLJ4YwYZGwRO0=go.yaml.in/yaml/v2 v2.4.3/go.mod h1:zSxWcmIDjOzPXpjlTTbAsKokqkDNAVtZO0WOMiT90s8=go.yaml.in/yaml/v3 v3.0.4 h1:tfq32ie2Jv2UxXFdLJdh3jXuOzWiL1fo0bu/FbuKpbc=go.yaml.in/yaml/v3 v3.0.4/go.mod h1:DhzuOOF2ATzADvBadXxruRBLzYTpT36CKvDb3+aBEFg=-go.yaml.in/yaml/v4 v4.0.0-rc.2 h1:/FrI8D64VSr4HtGIlUtlFMGsm7H7pWTbj6vOLVZcA6s=-go.yaml.in/yaml/v4 v4.0.0-rc.2/go.mod h1:aZqd9kCMsGL7AuUv/m/PvWLdg5sjJsZ4oHDEnfPPfY0=golang.org/x/arch v0.21.0 h1:iTC9o7+wP6cPWpDWkivCvQFGAHDQ59SrSxsLPcnkArw=golang.org/x/arch v0.21.0/go.mod h1:dNHoOeKiyja7GTvF9NJS1l3Z2yntpQNzgrjh1cU103A=golang.org/x/crypto v0.0.0-20180904163835-0709b304e793/go.mod h1:6SG95UA2DQfeDnfUPMdvaQW0Q7yPrPDi9nlGo2tz2b4=diff --git a/backend/internal/api/container_handler.go b/backend/internal/api/container_handler.goindex b1b6e6dd8..ee33a383d 100644--- a/backend/internal/api/container_handler.go+++ b/backend/internal/api/container_handler.go@@ -31,20 +31,20 @@ type ContainerHandler struct {func NewContainerHandler(group *gin.RouterGroup, dockerService *services.DockerClientService, containerService *services.ContainerService, imageService *services.ImageService, authMiddleware *middleware.AuthMiddleware) {handler := &ContainerHandler{dockerService: dockerService, containerService: containerService, imageService: imageService}- apiGroup := group.Group("/containers")+ apiGroup := group.Group("/environments/:id/containers")apiGroup.Use(authMiddleware.WithAdminNotRequired().Add()){+ apiGroup.GET("/counts", handler.GetContainerStatusCounts)apiGroup.GET("", handler.List)apiGroup.POST("", handler.Create)- apiGroup.GET("/:id", handler.GetByID)- apiGroup.GET("/:id/stats", handler.GetStats)- apiGroup.GET("/:id/stats/stream", handler.GetStatsStream)- apiGroup.POST("/:id/start", handler.Start)- apiGroup.POST("/:id/stop", handler.Stop)- apiGroup.POST("/:id/restart", handler.Restart)- apiGroup.GET("/:id/logs", handler.GetLogs)- apiGroup.GET("/:id/logs/ws", handler.GetLogsWS)- apiGroup.DELETE("/:id", handler.Delete)+ apiGroup.GET("/:containerId", handler.GetByID)+ apiGroup.GET("/:containerId/stats", handler.GetStats)+ apiGroup.GET("/:containerId/stats/stream", handler.GetStatsStream)+ apiGroup.POST("/:containerId/start", handler.Start)+ apiGroup.POST("/:containerId/stop", handler.Stop)+ apiGroup.POST("/:containerId/restart", handler.Restart)+ apiGroup.GET("/:containerId/logs/ws", handler.GetLogsWS)+ apiGroup.DELETE("/:containerId", handler.Delete)}}@@ -302,25 +302,6 @@ func (h *ContainerHandler) Restart(c *gin.Context) {})}-func (h *ContainerHandler) GetLogs(c *gin.Context) {- id := c.Param("id")- tail := c.DefaultQuery("tail", "100")-- logs, err := h.containerService.GetContainerLogs(c.Request.Context(), id, tail)- if err != nil {- c.JSON(http.StatusInternalServerError, gin.H{- "success": false,- "data": gin.H{"error": err.Error()},- })- return- }-- c.JSON(http.StatusOK, gin.H{- "success": true,- "data": gin.H{"logs": logs},- })-}-func (h *ContainerHandler) Delete(c *gin.Context) {id := c.Param("containerId")force := c.Query("force") == "true"diff --git a/backend/internal/api/converter_handler.go b/backend/internal/api/converter_handler.godeleted file mode 100644index 16d3efdbd..000000000--- a/backend/internal/api/converter_handler.go+++ /dev/null@@ -1,62 +0,0 @@-package api--import (- "net/http"-- "github.com/gin-gonic/gin"- "github.com/ofkm/arcane-backend/internal/middleware"- "github.com/ofkm/arcane-backend/internal/models"- "github.com/ofkm/arcane-backend/internal/services"-)--type ConverterHandler struct {- converterService *services.ConverterService-}--func NewConverterHandler(group *gin.RouterGroup, converterService *services.ConverterService, authMiddleware *middleware.AuthMiddleware) {- handler := &ConverterHandler{converterService: converterService}-- apiGroup := group.Group("/convert")- apiGroup.Use(authMiddleware.WithAdminNotRequired().Add())- {- apiGroup.POST("", handler.ConvertDockerRun)- }-}--func (h *ConverterHandler) ConvertDockerRun(c *gin.Context) {- var req models.ConvertDockerRunRequest- if err := c.ShouldBindJSON(&req); err != nil {- c.JSON(http.StatusBadRequest, gin.H{- "success": false,- "error": "Invalid request format: " + err.Error(),- })- return- }-- parsed, err := h.converterService.ParseDockerRunCommand(req.DockerRunCommand)- if err != nil {- c.JSON(http.StatusBadRequest, gin.H{- "success": false,- "error": "Failed to parse docker run command. Please check the syntax.",- "code": "BAD_REQUEST",- })- return- }-- dockerCompose, envVars, serviceName, err := h.converterService.ConvertToDockerCompose(parsed)- if err != nil {- c.JSON(http.StatusInternalServerError, gin.H{- "success": false,- "error": "Failed to convert to Docker Compose format.",- "code": "CONVERSION_ERROR",- })- return- }-- c.JSON(http.StatusOK, models.ConvertDockerRunResponse{- Success: true,- DockerCompose: dockerCompose,- EnvVars: envVars,- ServiceName: serviceName,- })-}diff --git a/backend/internal/api/environment_handler.go b/backend/internal/api/environment_handler.goindex 027a4faad..8c829ca15 100644--- a/backend/internal/api/environment_handler.go+++ b/backend/internal/api/environment_handler.go@@ -1,15 +1,7 @@package apiimport (- "bytes"- "fmt"- "io""net/http"- "net/url"- "path"- "runtime" // added- "strings"- "time""github.com/gin-gonic/gin""github.com/ofkm/arcane-backend/internal/config"@@ -18,59 +10,26 @@ import ("github.com/ofkm/arcane-backend/internal/models""github.com/ofkm/arcane-backend/internal/services""github.com/ofkm/arcane-backend/internal/utils"- "github.com/shirou/gopsutil/v3/cpu"- "github.com/shirou/gopsutil/v3/disk"- "github.com/shirou/gopsutil/v3/host"- "github.com/shirou/gopsutil/v3/mem"-- wsutil "github.com/ofkm/arcane-backend/internal/utils/ws")const LOCAL_DOCKER_ENVIRONMENT_ID = "0"type EnvironmentHandler struct {environmentService *services.EnvironmentService- containerService *services.ContainerService- imageService *services.ImageService- networkService *services.NetworkService- volumeService *services.VolumeService- projectService *services.ProjectServicesettingsService *services.SettingsService- imageUpdateService *services.ImageUpdateService- updaterService *services.UpdaterService- systemService *services.SystemService- dockerService *services.DockerClientServicecfg *config.Config}func NewEnvironmentHandler(group *gin.RouterGroup,environmentService *services.EnvironmentService,- containerService *services.ContainerService,- imageService *services.ImageService,- imageUpdateService *services.ImageUpdateService,- updaterService *services.UpdaterService,- networkService *services.NetworkService,- volumeService *services.VolumeService,- projectService *services.ProjectService,settingsService *services.SettingsService,- systemService *services.SystemService,- dockerService *services.DockerClientService,authMiddleware *middleware.AuthMiddleware,cfg *config.Config,) {h := &EnvironmentHandler{environmentService: environmentService,- containerService: containerService,- imageService: imageService,- networkService: networkService,- volumeService: volumeService,- projectService: projectService,settingsService: settingsService,- imageUpdateService: imageUpdateService,- updaterService: updaterService,- systemService: systemService,- dockerService: dockerService,cfg: cfg,}@@ -84,69 +43,7 @@ func NewEnvironmentHandler(apiGroup.DELETE("/:id", h.DeleteEnvironment)apiGroup.POST("/:id/test", h.TestConnection)apiGroup.POST("/:id/heartbeat", h.UpdateHeartbeat)-- apiGroup.GET("/:id/containers/counts", h.GetContainerStatusCounts)- apiGroup.POST("/:id/containers", h.CreateContainer)- apiGroup.GET("/:id/containers", h.GetContainers)- apiGroup.GET("/:id/containers/:containerId", h.GetContainer)- apiGroup.POST("/:id/containers/:containerId/pull", h.PullContainerImage)- apiGroup.POST("/:id/containers/:containerId/start", h.StartContainer)- apiGroup.POST("/:id/containers/:containerId/stop", h.StopContainer)- apiGroup.POST("/:id/containers/:containerId/restart", h.RestartContainer)- apiGroup.DELETE("/:id/containers/:containerId", h.RemoveContainer)- apiGroup.GET("/:id/containers/:containerId/logs", h.GetContainerLogs)- apiGroup.GET("/:id/containers/:containerId/stats", h.GetContainerStats)- apiGroup.GET("/:id/containers/:containerId/stats/stream", h.GetContainerStatsStream)- apiGroup.GET("/:id/containers/:containerId/logs/ws", h.GetContainerLogsWS)-- apiGroup.GET("/:id/images", h.GetImages)- apiGroup.GET("/:id/images/:imageId", h.GetImage)- apiGroup.DELETE("/:id/images/:imageId", h.RemoveImage)- apiGroup.POST("/:id/images/pull", h.PullImage)- apiGroup.POST("/:id/images/prune", h.PruneImages)- apiGroup.GET("/:id/images/counts", h.GetImageUsageCounts)-- apiGroup.GET("/:id/networks/counts", h.GetNetworkUsageCounts)- apiGroup.GET("/:id/networks", h.GetNetworks)- apiGroup.POST("/:id/networks", h.CreateNetwork)- apiGroup.GET("/:id/networks/:networkId", h.GetNetwork)- apiGroup.DELETE("/:id/networks/:networkId", h.RemoveNetwork)-- apiGroup.GET("/:id/volumes/counts", h.GetVolumeUsageCounts)- apiGroup.GET("/:id/volumes", h.GetVolumes)- apiGroup.POST("/:id/volumes", h.CreateVolume)- apiGroup.GET("/:id/volumes/:volumeName", h.GetVolume)- apiGroup.DELETE("/:id/volumes/:volumeName", h.RemoveVolume)- apiGroup.GET("/:id/volumes/:volumeName/usage", h.GetVolumeUsage)- apiGroup.POST("/:id/volumes/prune", h.PruneVolumes)-- apiGroup.GET("/:id/projects", h.ListProjects)- apiGroup.POST("/:id/projects/:projectId/up", h.ProjectUp)- apiGroup.POST("/:id/projects/:projectId/down", h.ProjectDown)- apiGroup.POST("/:id/projects", h.ProjectCreate)- apiGroup.GET("/:id/projects/:projectId", h.GetProject)- apiGroup.POST("/:id/projects/:projectId/pull", h.PullProjectImages)- apiGroup.POST("/:id/projects/:projectId/redeploy", h.RedeployProject)- apiGroup.DELETE("/:id/projects/:projectId/destroy", h.DestroyProject)- apiGroup.PUT("/:id/projects/:projectId", h.UpdateProject)- apiGroup.POST("/:id/projects/:projectId/restart", h.RestartProject)- apiGroup.GET("/:id/projects/counts", h.GetProjectCounts)- apiGroup.GET("/:id/projects/:projectId/logs/ws", h.GetProjectLogsWS)-- apiGroup.GET("/:id/image-updates/check", h.CheckImageUpdate)- apiGroup.GET("/:id/image-updates/check/:imageId", h.CheckImageUpdateByID)- apiGroup.GET("/:id/image-updates/check-all", h.CheckAllImages)- apiGroup.GET("/:id/image-updates/summary", h.GetUpdateSummary)- apiGroup.GET("/:id/image-updates/versions", h.GetImageVersions)- apiGroup.POST("/:id/image-updates/compare", h.CompareVersions)-- apiGroup.POST("/:id/updater/run", h.UpdaterRun)- apiGroup.GET("/:id/updater/status", h.UpdaterStatus)- apiGroup.GET("/:id/updater/history", h.UpdaterHistory)-apiGroup.POST("/:id/agent/pair", h.PairAgent)- apiGroup.GET("/:id/stats/ws", h.GetStatsWS)- apiGroup.GET("/:id/docker/info", h.GetDockerInfo)}}@@ -179,448 +76,6 @@ func (h *EnvironmentHandler) PairAgent(c *gin.Context) {})}-func (h *EnvironmentHandler) routeRequest(c *gin.Context, endpoint string) {- environmentID := c.Param("id")-- if environmentID == LOCAL_DOCKER_ENVIRONMENT_ID {- h.handleLocalRequest(c, endpoint)- return- }-- h.handleRemoteRequest(c, environmentID, endpoint)-}--func (h *EnvironmentHandler) handleLocalRequest(c *gin.Context, endpoint string) {- if h.handleContainerEndpoints(c, endpoint) {- return- }- if h.handleImageEndpoints(c, endpoint) {- return- }- if h.handleImageUpdateEndpoints(c, endpoint) {- return- }- if h.handleNetworkEndpoints(c, endpoint) {- return- }- if h.handleVolumeEndpoints(c, endpoint) {- return- }- if h.handleProjectEndpoints(c, endpoint) {- return- }- if h.handleUpdaterEndpoints(c, endpoint) {- return- }- if h.handleSystemRoutes(c, endpoint) {- return- }-- c.JSON(http.StatusNotFound, gin.H{- "success": false,- "data": gin.H{"error": "Endpoint not found"},- })-}--func (h *EnvironmentHandler) handleUpdaterEndpoints(c *gin.Context, endpoint string) bool {- updaterHandler := &UpdaterHandler{- updaterService: h.updaterService,- }- switch {- case endpoint == "/updater/run" && c.Request.Method == http.MethodPost:- updaterHandler.Run(c)- return true- case endpoint == "/updater/status" && c.Request.Method == http.MethodGet:- updaterHandler.Status(c)- return true- case endpoint == "/updater/history" && c.Request.Method == http.MethodGet:- updaterHandler.History(c)- return true- }- return false-}--func (h *EnvironmentHandler) handleSystemRoutes(c *gin.Context, endpoint string) bool {- systemHandler := &SystemHandler{- systemService: h.systemService,- dockerService: h.dockerService,- }- if endpoint == "/docker/info" && c.Request.Method == http.MethodGet {- systemHandler.GetDockerInfo(c)- return true- }- return false-}--func (h *EnvironmentHandler) GetDockerInfo(c *gin.Context) {- h.routeRequest(c, "/docker/info")-}--func (h *EnvironmentHandler) UpdaterRun(c *gin.Context) {- h.routeRequest(c, "/updater/run")-}-func (h *EnvironmentHandler) UpdaterStatus(c *gin.Context) {- h.routeRequest(c, "/updater/status")-}-func (h *EnvironmentHandler) UpdaterHistory(c *gin.Context) {- h.routeRequest(c, "/updater/history")-}--func (h *EnvironmentHandler) handleImageUpdateEndpoints(c *gin.Context, endpoint string) bool {- imageUpdateHandler := &ImageUpdateHandler{- imageUpdateService: h.imageUpdateService,- }-- switch {- case endpoint == "/image-updates/check" && c.Request.Method == http.MethodGet:- imageUpdateHandler.CheckImageUpdate(c)- return true- case strings.HasPrefix(endpoint, "/image-updates/check/") && c.Request.Method == http.MethodGet:- imageUpdateHandler.CheckImageUpdateByID(c)- return true- case endpoint == "/image-updates/check-all" && c.Request.Method == http.MethodGet:- imageUpdateHandler.CheckAllImages(c)- return true- case endpoint == "/image-updates/summary" && c.Request.Method == http.MethodGet:- imageUpdateHandler.GetUpdateSummary(c)- return true- case endpoint == "/image-updates/versions" && c.Request.Method == http.MethodGet:- imageUpdateHandler.GetImageVersions(c)- return true- case endpoint == "/image-updates/compare" && c.Request.Method == http.MethodPost:- imageUpdateHandler.CompareVersions(c)- return true- }- return false-}--func (h *EnvironmentHandler) CheckImageUpdate(c *gin.Context) {- h.routeRequest(c, "/image-updates/check")-}--func (h *EnvironmentHandler) CheckImageUpdateByID(c *gin.Context) {- imageID := c.Param("imageId")- h.routeRequest(c, "/image-updates/check/"+imageID)-}--func (h *EnvironmentHandler) CheckAllImages(c *gin.Context) {- h.routeRequest(c, "/image-updates/check-all")-}--func (h *EnvironmentHandler) GetUpdateSummary(c *gin.Context) {- h.routeRequest(c, "/image-updates/summary")-}--func (h *EnvironmentHandler) GetImageVersions(c *gin.Context) {- h.routeRequest(c, "/image-updates/versions")-}--func (h *EnvironmentHandler) CompareVersions(c *gin.Context) {- h.routeRequest(c, "/image-updates/compare")-}--func (h *EnvironmentHandler) handleContainerEndpoints(c *gin.Context, endpoint string) bool {- containerHandler := &ContainerHandler{- containerService: h.containerService,- imageService: h.imageService,- }-- switch {- case endpoint == "/containers/counts" && c.Request.Method == http.MethodGet:- containerHandler.GetContainerStatusCounts(c)- return true- case endpoint == "/containers" && c.Request.Method == http.MethodGet:- containerHandler.List(c)- return true- case endpoint == "/containers" && c.Request.Method == http.MethodPost:- containerHandler.Create(c)- return true- case strings.HasPrefix(endpoint, "/containers/") && strings.HasSuffix(endpoint, "/start"):- containerHandler.Start(c)- return true- case strings.HasPrefix(endpoint, "/containers/") && strings.HasSuffix(endpoint, "/stop"):- containerHandler.Stop(c)- return true- case strings.HasPrefix(endpoint, "/containers/") && strings.HasSuffix(endpoint, "/restart"):- containerHandler.Restart(c)- return true- case strings.HasPrefix(endpoint, "/containers/") && strings.HasSuffix(endpoint, "/pull"):- containerHandler.PullImage(c)- return true- case strings.HasPrefix(endpoint, "/containers/") && strings.HasSuffix(endpoint, "/logs/ws"):- containerHandler.GetLogsWS(c)- return true- case strings.HasPrefix(endpoint, "/containers/") && strings.HasSuffix(endpoint, "/logs"):- containerHandler.GetLogs(c)- return true- case strings.HasPrefix(endpoint, "/containers/") && strings.HasSuffix(endpoint, "/stats/stream"):- containerHandler.GetStatsStream(c)- return true- case strings.HasPrefix(endpoint, "/containers/") && strings.HasSuffix(endpoint, "/stats"):- containerHandler.GetStats(c)- return true- case strings.HasPrefix(endpoint, "/containers/") && c.Request.Method == http.MethodGet:- containerHandler.GetByID(c)- return true- case strings.HasPrefix(endpoint, "/containers/") && c.Request.Method == http.MethodDelete:- containerHandler.Delete(c)- return true- }- return false-}--func (h *EnvironmentHandler) handleImageEndpoints(c *gin.Context, endpoint string) bool {- imageHandler := &ImageHandler{- imageService: h.imageService,- imageUpdateService: nil,- }-- switch {- case endpoint == "/images/counts" && c.Request.Method == http.MethodGet:- imageHandler.GetImageUsageCounts(c)- return true- case endpoint == "/images" && c.Request.Method == http.MethodGet:- imageHandler.List(c)- return true- case endpoint == "/images/pull" && c.Request.Method == http.MethodPost:- imageHandler.Pull(c)- return true- case endpoint == "/images/prune" && c.Request.Method == http.MethodPost:- imageHandler.Prune(c)- return true- case strings.HasPrefix(endpoint, "/images/") && c.Request.Method == http.MethodGet:- imageHandler.GetByID(c)- return true- case strings.HasPrefix(endpoint, "/images/") && c.Request.Method == http.MethodDelete:- imageHandler.Remove(c)- return true- }- return false-}--func (h *EnvironmentHandler) handleNetworkEndpoints(c *gin.Context, endpoint string) bool {- networkHandler := &NetworkHandler{- networkService: h.networkService,- }-- switch {- case endpoint == "/networks/counts" && c.Request.Method == http.MethodGet:- networkHandler.GetNetworkUsageCounts(c)- return true- case endpoint == "/networks" && c.Request.Method == http.MethodGet:- networkHandler.List(c)- return true- case endpoint == "/networks" && c.Request.Method == http.MethodPost:- networkHandler.Create(c)- return true- case strings.HasPrefix(endpoint, "/networks/") && c.Request.Method == http.MethodGet:- networkHandler.GetByID(c)- return true- case strings.HasPrefix(endpoint, "/networks/") && c.Request.Method == http.MethodDelete:- networkHandler.Remove(c)- return true- }- return false-}--func (h *EnvironmentHandler) handleVolumeEndpoints(c *gin.Context, endpoint string) bool {- volumeHandler := &VolumeHandler{- volumeService: h.volumeService,- }-- switch {- case endpoint == "/volumes/counts" && c.Request.Method == http.MethodGet:- volumeHandler.GetVolumeUsageCounts(c)- return true- case endpoint == "/volumes" && c.Request.Method == http.MethodGet:- volumeHandler.List(c)- return true- case endpoint == "/volumes" && c.Request.Method == http.MethodPost:- volumeHandler.Create(c)- return true- case endpoint == "/volumes/prune" && c.Request.Method == http.MethodPost:- volumeHandler.Prune(c)- return true- case strings.HasPrefix(endpoint, "/volumes/") && strings.HasSuffix(endpoint, "/usage"):- volumeHandler.GetUsage(c)- return true- case strings.HasPrefix(endpoint, "/volumes/") && c.Request.Method == http.MethodGet:- volumeHandler.GetByName(c)- return true- case strings.HasPrefix(endpoint, "/volumes/") && c.Request.Method == http.MethodDelete:- volumeHandler.Remove(c)- return true- }- return false-}--func (h *EnvironmentHandler) handleProjectEndpoints(c *gin.Context, endpoint string) bool {- projectHandler := &ProjectHandler{- projectService: h.projectService,- }-- switch {- case endpoint == "/projects" && c.Request.Method == http.MethodGet:- projectHandler.ListProjects(c)- return true- case endpoint == "/projects" && c.Request.Method == http.MethodPost:- projectHandler.CreateProject(c)- return true- case endpoint == "/projects/counts" && c.Request.Method == http.MethodGet:- projectHandler.GetProjectStatusCounts(c)- return true- case strings.HasSuffix(endpoint, "/logs/ws"):- projectHandler.GetProjectLogsWS(c)- return true- case strings.HasPrefix(endpoint, "/projects/") && strings.HasSuffix(endpoint, "/up"):- projectHandler.DeployProject(c)- return true- case strings.HasPrefix(endpoint, "/projects/") && strings.HasSuffix(endpoint, "/down"):- projectHandler.DownProject(c)- return true- case strings.HasPrefix(endpoint, "/projects/") && strings.HasSuffix(endpoint, "/pull"):- projectHandler.PullProjectImages(c)- return true- case strings.HasPrefix(endpoint, "/projects/") && strings.HasSuffix(endpoint, "/redeploy"):- projectHandler.RedeployProject(c)- return true- case strings.HasPrefix(endpoint, "/projects/") && strings.HasSuffix(endpoint, "/destroy"):- projectHandler.DestroyProject(c)- return true- case strings.HasPrefix(endpoint, "/projects/") && strings.HasSuffix(endpoint, "/restart"):- projectHandler.RestartProject(c)- return true- case strings.HasPrefix(endpoint, "/projects/") && c.Request.Method == http.MethodPut:- projectHandler.UpdateProject(c)- return true- case strings.HasPrefix(endpoint, "/projects/") && c.Request.Method == http.MethodGet:- projectHandler.GetProject(c)- return true- }- return false-}--func (h *EnvironmentHandler) handleRemoteRequest(c *gin.Context, environmentID string, endpoint string) {- environment, err := h.environmentService.GetEnvironmentByID(c.Request.Context(), environmentID)- if err != nil || environment == nil {- c.JSON(http.StatusNotFound, gin.H{"success": false, "data": gin.H{"error": "Environment not found"}})- return- }- if !environment.Enabled {- c.JSON(http.StatusBadRequest, gin.H{"success": false, "data": gin.H{"error": "Environment is disabled"}})- return- }-- target := strings.TrimRight(environment.ApiUrl, "/") +- "/api/environments/" + LOCAL_DOCKER_ENVIRONMENT_ID + endpoint- if qs := c.Request.URL.RawQuery; qs != "" {- target += "?" + qs- }-- var reqBody io.Reader- if c.Request.Body != nil {- buf, _ := io.ReadAll(c.Request.Body)- // reset original body in case other middlewares need it later- c.Request.Body = io.NopCloser(bytes.NewBuffer(buf))- reqBody = bytes.NewReader(buf)- }-- req, err := http.NewRequestWithContext(c.Request.Context(), c.Request.Method, target, reqBody)- if err != nil {- c.JSON(http.StatusInternalServerError, gin.H{"success": false, "data": gin.H{"error": "Failed to create proxy request"}})- return- }-- // Copy headers except hop-by-hop and Authorization (we’ll set explicitly)- skip := map[string]struct{}{- "Host": {},- "Connection": {},- "Keep-Alive": {},- "Proxy-Authenticate": {},- "Proxy-Authorization": {},- "Te": {},- "Trailer": {},- "Transfer-Encoding": {},- "Upgrade": {},- "Content-Length": {},- "Origin": {},- "Referer": {},- "Access-Control-Request-Method": {},- "Access-Control-Request-Headers": {},- "Cookie": {},- }- for k, vs := range c.Request.Header {- ck := http.CanonicalHeaderKey(k)- if _, ok := skip[ck]; ok || ck == "Authorization" {- continue- }- for _, v := range vs {- req.Header.Add(k, v)- }- }-- // Forward Authorization (or promote cookie)- if auth := c.GetHeader("Authorization"); auth != "" {- req.Header.Set("Authorization", auth)- } else if cookieToken, err := c.Cookie("token"); err == nil && cookieToken != "" {- req.Header.Set("Authorization", "Bearer "+cookieToken)- }-- // Forward agent token if stored- if environment.AccessToken != nil && *environment.AccessToken != "" {- req.Header.Set("X-Arcane-Agent-Token", *environment.AccessToken)- }-- req.Header.Set("X-Forwarded-For", c.ClientIP())- req.Header.Set("X-Forwarded-Host", c.Request.Host)-- client := &http.Client{Timeout: 60 * time.Second}- resp, err := client.Do(req)- if err != nil {- c.JSON(http.StatusBadGateway, gin.H{"success": false, "data": gin.H{"error": fmt.Sprintf("Proxy request failed: %v", err)}})- return- }- defer resp.Body.Close()-- // Skip hop-by-hop headers and any named in the Connection header (RFC 7230)- hop := map[string]struct{}{- http.CanonicalHeaderKey("Connection"): {},- http.CanonicalHeaderKey("Keep-Alive"): {},- http.CanonicalHeaderKey("Proxy-Authenticate"): {},- http.CanonicalHeaderKey("Proxy-Authorization"): {},- http.CanonicalHeaderKey("TE"): {},- http.CanonicalHeaderKey("Trailers"): {},- http.CanonicalHeaderKey("Trailer"): {},- http.CanonicalHeaderKey("Transfer-Encoding"): {},- http.CanonicalHeaderKey("Upgrade"): {},- }-- for _, connVal := range resp.Header.Values("Connection") {- for _, token := range strings.Split(connVal, ",") {- if t := strings.TrimSpace(token); t != "" {- hop[http.CanonicalHeaderKey(t)] = struct{}{}- }- }- }-- // Copy response headers except hop-by-hop- for k, vs := range resp.Header {- ck := http.CanonicalHeaderKey(k)- if _, ok := hop[ck]; ok {- continue- }- for _, v := range vs {- c.Writer.Header().Add(k, v)- }- }-- c.Status(resp.StatusCode)-- if c.Request.Method != http.MethodHead {- _, _ = io.Copy(c.Writer, resp.Body)- }-}-// Createfunc (h *EnvironmentHandler) CreateEnvironment(c *gin.Context) {var req dto.CreateEnvironmentDto@@ -826,387 +281,3 @@ func (h *EnvironmentHandler) UpdateHeartbeat(c *gin.Context) {"message": "Heartbeat updated successfully",})}--func (h *EnvironmentHandler) GetContainers(c *gin.Context) {- h.routeRequest(c, "/containers")-}--func (h *EnvironmentHandler) GetImages(c *gin.Context) {- h.routeRequest(c, "/images")-}--func (h *EnvironmentHandler) GetNetworkUsageCounts(c *gin.Context) {- h.routeRequest(c, "/networks/counts")-}--func (h *EnvironmentHandler) GetNetworks(c *gin.Context) {- h.routeRequest(c, "/networks")-}--func (h *EnvironmentHandler) GetVolumes(c *gin.Context) {- h.routeRequest(c, "/volumes")-}--func (h *EnvironmentHandler) CreateNetwork(c *gin.Context) {- h.routeRequest(c, "/networks")-}--func (h *EnvironmentHandler) CreateVolume(c *gin.Context) {- h.routeRequest(c, "/volumes")-}--func (h *EnvironmentHandler) GetVolumeUsageCounts(c *gin.Context) {- h.routeRequest(c, "/volumes/counts")-}--// Containers--func (h *EnvironmentHandler) GetContainer(c *gin.Context) {- containerID := c.Param("containerId")- h.routeRequest(c, "/containers/"+containerID)-}--func (h *EnvironmentHandler) GetContainerStatusCounts(c *gin.Context) {- h.routeRequest(c, "/containers/counts")-}--func (h *EnvironmentHandler) StartContainer(c *gin.Context) {- containerID := c.Param("containerId")- h.routeRequest(c, "/containers/"+containerID+"/start")-}--func (h *EnvironmentHandler) StopContainer(c *gin.Context) {- containerID := c.Param("containerId")- h.routeRequest(c, "/containers/"+containerID+"/stop")-}--func (h *EnvironmentHandler) CreateContainer(c *gin.Context) {- h.routeRequest(c, "/containers")-}--func (h *EnvironmentHandler) PullContainerImage(c *gin.Context) {- containerID := c.Param("containerId")- h.routeRequest(c, "/containers/"+containerID+"/pull")-}--func (h *EnvironmentHandler) RestartContainer(c *gin.Context) {- containerID := c.Param("containerId")- h.routeRequest(c, "/containers/"+containerID+"/restart")-}--func (h *EnvironmentHandler) RemoveContainer(c *gin.Context) {- containerID := c.Param("containerId")- h.routeRequest(c, "/containers/"+containerID)-}--func (h *EnvironmentHandler) GetContainerLogs(c *gin.Context) {- containerID := c.Param("containerId")- h.routeRequest(c, "/containers/"+containerID+"/logs")-}--func (h *EnvironmentHandler) GetContainerStats(c *gin.Context) {- containerID := c.Param("containerId")- h.routeRequest(c, "/containers/"+containerID+"/stats")-}--func (h *EnvironmentHandler) GetContainerStatsStream(c *gin.Context) {- containerID := c.Param("containerId")- h.routeRequest(c, "/containers/"+containerID+"/stats/stream")-}--// End Containers--// Images--func (h *EnvironmentHandler) GetImage(c *gin.Context) {- imageID := c.Param("imageId")- h.routeRequest(c, "/images/"+imageID)-}--func (h *EnvironmentHandler) GetImageUsageCounts(c *gin.Context) {- h.routeRequest(c, "/images/counts")-}--func (h *EnvironmentHandler) RemoveImage(c *gin.Context) {- imageID := c.Param("imageId")- h.routeRequest(c, "/images/"+imageID)-}--func (h *EnvironmentHandler) PullImage(c *gin.Context) {- h.routeRequest(c, "/images/pull")-}--func (h *EnvironmentHandler) PruneImages(c *gin.Context) {- h.routeRequest(c, "/images/prune")-}--// End Images--func (h *EnvironmentHandler) GetNetwork(c *gin.Context) {- networkID := c.Param("networkId")- h.routeRequest(c, "/networks/"+networkID)-}--func (h *EnvironmentHandler) RemoveNetwork(c *gin.Context) {- networkID := c.Param("networkId")- h.routeRequest(c, "/networks/"+networkID)-}--func (h *EnvironmentHandler) GetVolume(c *gin.Context) {- volumeName := c.Param("volumeName")- h.routeRequest(c, "/volumes/"+volumeName)-}--func (h *EnvironmentHandler) RemoveVolume(c *gin.Context) {- volumeName := c.Param("volumeName")- h.routeRequest(c, "/volumes/"+volumeName)-}--func (h *EnvironmentHandler) PruneVolumes(c *gin.Context) {- h.routeRequest(c, "/volumes/prune")-}--func (h *EnvironmentHandler) GetVolumeUsage(c *gin.Context) {- h.routeRequest(c, "/volumes/"+c.Param("volumeName")+"/usage")-}--func (h *EnvironmentHandler) GetContainerLogsWS(c *gin.Context) {- envID := c.Param("id")- containerID := c.Param("containerId")-- if envID == LOCAL_DOCKER_ENVIRONMENT_ID {- h.routeRequest(c, "/containers/"+containerID+"/logs/ws")- return- }-- environment, err := h.environmentService.GetEnvironmentByID(c.Request.Context(), envID)- if err != nil || environment == nil || !environment.Enabled {- c.JSON(http.StatusNotFound, gin.H{"success": false, "data": gin.H{"error": "Environment not found or disabled"}})- return- }-- u, err := url.Parse(strings.TrimRight(environment.ApiUrl, "/"))- if err != nil {- c.JSON(http.StatusBadRequest, gin.H{"success": false, "data": gin.H{"error": "Invalid environment URL"}})- return- }- if u.Scheme == "https" {- u.Scheme = "wss"- } else {- u.Scheme = "ws"- }- u.Path = path.Join(u.Path, "/api/environments/"+LOCAL_DOCKER_ENVIRONMENT_ID+"/containers/"+containerID+"/logs/ws")- u.RawQuery = c.Request.URL.RawQuery-- hdr := http.Header{}- if auth := c.GetHeader("Authorization"); auth != "" {- hdr.Set("Authorization", auth)- } else if cookieToken, err := c.Cookie("token"); err == nil && cookieToken != "" {- hdr.Set("Authorization", "Bearer "+cookieToken)- }- if environment.AccessToken != nil && *environment.AccessToken != "" {- hdr.Set("X-Arcane-Agent-Token", *environment.AccessToken)- }-- _ = wsutil.ProxyHTTP(c.Writer, c.Request, u.String(), hdr)-}--//nolint:gocognit-func (h *EnvironmentHandler) GetStatsWS(c *gin.Context) {- envID := c.Param("id")- if envID == "" {- envID = LOCAL_DOCKER_ENVIRONMENT_ID- }-- if envID == LOCAL_DOCKER_ENVIRONMENT_ID {- conn, err := sysWsUpgrader.Upgrade(c.Writer, c.Request, nil)- if err != nil {- return- }- defer conn.Close()-- ticker := time.NewTicker(2 * time.Second)- defer ticker.Stop()-- var lastCPU float64-- send := func(block bool) error {- var cpuUsage float64- if block {- if vals, err := cpu.Percent(time.Second, false); err == nil && len(vals) > 0 {- cpuUsage = vals[0]- lastCPU = cpuUsage- } else {- cpuUsage = lastCPU- }- } else {- cpuUsage = lastCPU- }-- cpuCount, err := cpu.Counts(true)- if err != nil {- cpuCount = runtime.NumCPU()- }-- memInfo, _ := mem.VirtualMemory()- var memUsed, memTotal uint64- if memInfo != nil {- memUsed = memInfo.Used- memTotal = memInfo.Total- }-- diskInfo, _ := disk.Usage("/")- var diskUsed, diskTotal uint64- if diskInfo != nil {- diskUsed = diskInfo.Used- diskTotal = diskInfo.Total- }-- hostInfo, _ := host.Info()- var hostname string- if hostInfo != nil {- hostname = hostInfo.Hostname- }-- stats := SystemStats{- CPUUsage: cpuUsage,- MemoryUsage: memUsed,- MemoryTotal: memTotal,- DiskUsage: diskUsed,- DiskTotal: diskTotal,- CPUCount: cpuCount,- Architecture: runtime.GOARCH,- Platform: runtime.GOOS,- Hostname: hostname,- }-- _ = conn.SetWriteDeadline(time.Now().Add(10 * time.Second))- return conn.WriteJSON(stats)- }-- if err := send(true); err != nil {- return- }-- for {- select {- case <-c.Request.Context().Done():- return- case <-ticker.C:- if err := send(true); err != nil {- return- }- }- }- }-- environment, err := h.environmentService.GetEnvironmentByID(c.Request.Context(), envID)- if err != nil || environment == nil || !environment.Enabled {- c.JSON(http.StatusNotFound, gin.H{"success": false, "data": gin.H{"error": "Environment not found or disabled"}})- return- }-- target, hdr, err := h.environmentService.BuildRemoteWSTarget(environment, "/api/environments/0/stats/ws", c.Request)- if err != nil {- c.JSON(http.StatusBadRequest, gin.H{"success": false, "data": gin.H{"error": err.Error()}})- return- }- _ = wsutil.ProxyHTTP(c.Writer, c.Request, target, hdr)-}--// New Project Handlers--func (h *EnvironmentHandler) ListProjects(c *gin.Context) {- h.routeRequest(c, "/projects")-}--func (h *EnvironmentHandler) ProjectUp(c *gin.Context) {- projectId := c.Param("projectId")- h.routeRequest(c, "/projects/"+projectId+"/up")-}--func (h *EnvironmentHandler) ProjectDown(c *gin.Context) {- projectId := c.Param("projectId")- h.routeRequest(c, "/projects/"+projectId+"/down")-}--func (h *EnvironmentHandler) ProjectCreate(c *gin.Context) {- h.routeRequest(c, "/projects")-}--func (h *EnvironmentHandler) GetProject(c *gin.Context) {- projectId := c.Param("projectId")- h.routeRequest(c, "/projects/"+projectId)-}--func (h *EnvironmentHandler) PullProjectImages(c *gin.Context) {- projectId := c.Param("projectId")- h.routeRequest(c, "/projects/"+projectId+"/pull")-}--func (h *EnvironmentHandler) RedeployProject(c *gin.Context) {- projectId := c.Param("projectId")- h.routeRequest(c, "/projects/"+projectId+"/redeploy")-}--func (h *EnvironmentHandler) DestroyProject(c *gin.Context) {- projectId := c.Param("projectId")- h.routeRequest(c, "/projects/"+projectId+"/destroy")-}--func (h *EnvironmentHandler) UpdateProject(c *gin.Context) {- projectId := c.Param("projectId")- h.routeRequest(c, "/projects/"+projectId)-}--func (h *EnvironmentHandler) RestartProject(c *gin.Context) {- projectId := c.Param("projectId")- h.routeRequest(c, "/projects/"+projectId+"/restart")-}--func (h *EnvironmentHandler) GetProjectLogsWS(c *gin.Context) {- envID := c.Param("id")- projectId := c.Param("projectId")-- if envID == LOCAL_DOCKER_ENVIRONMENT_ID {- h.routeRequest(c, "/projects/"+projectId+"/logs/ws")- return- }-- environment, err := h.environmentService.GetEnvironmentByID(c.Request.Context(), envID)- if err != nil || environment == nil || !environment.Enabled {- c.JSON(http.StatusNotFound, gin.H{"success": false, "data": gin.H{"error": "Environment not found or disabled"}})- return- }-- u, err := url.Parse(strings.TrimRight(environment.ApiUrl, "/"))- if err != nil {- c.JSON(http.StatusBadRequest, gin.H{"success": false, "data": gin.H{"error": "Invalid environment URL"}})- return- }- if u.Scheme == "https" {- u.Scheme = "wss"- } else {- u.Scheme = "ws"- }- u.Path = path.Join(u.Path, "/api/environments/"+LOCAL_DOCKER_ENVIRONMENT_ID+"/projects/"+projectId+"/logs/ws")- u.RawQuery = c.Request.URL.RawQuery-- hdr := http.Header{}- // Forward auth if present- if auth := c.GetHeader("Authorization"); auth != "" {- hdr.Set("Authorization", auth)- } else if cookieToken, err := c.Cookie("token"); err == nil && cookieToken != "" {- hdr.Set("Authorization", "Bearer "+cookieToken)- }- // Agent token- if environment.AccessToken != nil && *environment.AccessToken != "" {- hdr.Set("X-Arcane-Agent-Token", *environment.AccessToken)- }-- _ = wsutil.ProxyHTTP(c.Writer, c.Request, u.String(), hdr)-}--func (h *EnvironmentHandler) GetProjectCounts(c *gin.Context) {- h.routeRequest(c, "/projects/counts")-}diff --git a/backend/internal/api/image_handler.go b/backend/internal/api/image_handler.goindex 280948f2f..753f9779c 100644--- a/backend/internal/api/image_handler.go+++ b/backend/internal/api/image_handler.go@@ -22,12 +22,13 @@ type ImageHandler struct {func NewImageHandler(group *gin.RouterGroup, dockerService *services.DockerClientService, imageService *services.ImageService, imageUpdateService *services.ImageUpdateService, authMiddleware *middleware.AuthMiddleware) {handler := &ImageHandler{dockerService: dockerService, imageService: imageService, imageUpdateService: imageUpdateService}- apiGroup := group.Group("/images")+ apiGroup := group.Group("/environments/:id/images")apiGroup.Use(authMiddleware.WithAdminNotRequired().Add()){+ apiGroup.GET("/counts", handler.GetImageUsageCounts)apiGroup.GET("", handler.List)- apiGroup.GET("/:id", handler.GetByID)- apiGroup.DELETE("/:id", handler.Remove)+ apiGroup.GET("/:imageId", handler.GetByID)+ apiGroup.DELETE("/:imageId", handler.Remove)apiGroup.POST("/pull", handler.Pull)apiGroup.POST("/prune", handler.Prune)}diff --git a/backend/internal/api/image_update_handler.go b/backend/internal/api/image_update_handler.goindex 0a6e3e929..f2b46dd47 100644--- a/backend/internal/api/image_update_handler.go+++ b/backend/internal/api/image_update_handler.go@@ -17,8 +17,7 @@ type ImageUpdateHandler struct {func NewImageUpdateHandler(group *gin.RouterGroup, imageUpdateService *services.ImageUpdateService, authMiddleware *middleware.AuthMiddleware) {handler := &ImageUpdateHandler{imageUpdateService: imageUpdateService}- apiGroup := group.Group("/image-updates")-+ apiGroup := group.Group("/environments/:id/image-updates")apiGroup.Use(authMiddleware.WithAdminNotRequired().Add()){apiGroup.GET("/check", handler.CheckImageUpdate)diff --git a/backend/internal/api/network_handler.go b/backend/internal/api/network_handler.goindex 9cd3f1d9e..fd4bcd38d 100644--- a/backend/internal/api/network_handler.go+++ b/backend/internal/api/network_handler.go@@ -19,13 +19,14 @@ type NetworkHandler struct {func NewNetworkHandler(group *gin.RouterGroup, dockerService *services.DockerClientService, networkService *services.NetworkService, authMiddleware *middleware.AuthMiddleware) {handler := &NetworkHandler{dockerService: dockerService, networkService: networkService}- apiGroup := group.Group("/networks")+ apiGroup := group.Group("/environments/:id/networks")apiGroup.Use(authMiddleware.WithAdminNotRequired().Add()){+ apiGroup.GET("/counts", handler.GetNetworkUsageCounts)apiGroup.GET("", handler.List)- apiGroup.GET("/:id", handler.GetByID)+ apiGroup.GET("/:networkId", handler.GetByID)apiGroup.POST("", handler.Create)- apiGroup.DELETE("/:id", handler.Remove)+ apiGroup.DELETE("/:networkId", handler.Remove)apiGroup.POST("/prune", handler.Prune)}}diff --git a/backend/internal/api/project_handler.go b/backend/internal/api/project_handler.goindex 4812d59c8..09a0d40d0 100644--- a/backend/internal/api/project_handler.go+++ b/backend/internal/api/project_handler.go@@ -43,9 +43,10 @@ func NewProjectHandler(group *gin.RouterGroup, projectService *services.ProjectShandler := &ProjectHandler{projectService: projectService}- apiGroup := group.Group("/projects")+ apiGroup := group.Group("/environments/:id/projects")apiGroup.Use(authMiddleware.WithAdminNotRequired().Add()){+ apiGroup.GET("/counts", handler.GetProjectStatusCounts)apiGroup.GET("/", handler.ListProjects)apiGroup.POST("/:projectId/up", handler.DeployProject)apiGroup.POST("/:projectId/down", handler.DownProject)diff --git a/backend/internal/api/system_handler.go b/backend/internal/api/system_handler.goindex fdf026f75..9bc322c45 100644--- a/backend/internal/api/system_handler.go+++ b/backend/internal/api/system_handler.go@@ -3,6 +3,8 @@ package apiimport ("log/slog""net/http"+ "runtime"+ "time""github.com/docker/docker/api/types/container""github.com/docker/docker/api/types/image"@@ -10,7 +12,12 @@ import ("github.com/gorilla/websocket""github.com/ofkm/arcane-backend/internal/dto""github.com/ofkm/arcane-backend/internal/middleware"+ "github.com/ofkm/arcane-backend/internal/models""github.com/ofkm/arcane-backend/internal/services"+ "github.com/shirou/gopsutil/v3/cpu"+ "github.com/shirou/gopsutil/v3/disk"+ "github.com/shirou/gopsutil/v3/host"+ "github.com/shirou/gopsutil/v3/mem")var sysWsUpgrader = websocket.Upgrader{@@ -25,14 +32,17 @@ type SystemHandler struct {func NewSystemHandler(group *gin.RouterGroup, dockerService *services.DockerClientService, systemService *services.SystemService, authMiddleware *middleware.AuthMiddleware) {handler := &SystemHandler{dockerService: dockerService, systemService: systemService}- apiGroup := group.Group("/system")+ apiGroup := group.Group("/environments/:id/system")apiGroup.Use(authMiddleware.WithAdminNotRequired().Add()){+ apiGroup.GET("/stats/ws", handler.Stats)apiGroup.GET("/docker/info", handler.GetDockerInfo)apiGroup.POST("/prune", handler.PruneAll)apiGroup.POST("/containers/start-all", handler.StartAllContainers)apiGroup.POST("/containers/start-stopped", handler.StartAllStoppedContainers)apiGroup.POST("/containers/stop-all", handler.StopAllContainers)+ apiGroup.POST("/convert", handler.ConvertDockerRun)+}}@@ -229,3 +239,124 @@ func (h *SystemHandler) StopAllContainers(c *gin.Context) {"data": result,})}++//nolint:gocognit+func (h *SystemHandler) Stats(c *gin.Context) {+ conn, err := sysWsUpgrader.Upgrade(c.Writer, c.Request, nil)+ if err != nil {+ return+ }+ defer conn.Close()++ ticker := time.NewTicker(2 * time.Second)+ defer ticker.Stop()++ var lastCPU float64++ send := func(block bool) error {+ var cpuUsage float64+ if block {+ if vals, err := cpu.Percent(time.Second, false); err == nil && len(vals) > 0 {+ cpuUsage = vals[0]+ lastCPU = cpuUsage+ } else {+ cpuUsage = lastCPU+ }+ } else {+ cpuUsage = lastCPU+ }++ cpuCount, err := cpu.Counts(true)+ if err != nil {+ cpuCount = runtime.NumCPU()+ }++ memInfo, _ := mem.VirtualMemory()+ var memUsed, memTotal uint64+ if memInfo != nil {+ memUsed = memInfo.Used+ memTotal = memInfo.Total+ }++ diskInfo, _ := disk.Usage("/")+ var diskUsed, diskTotal uint64+ if diskInfo != nil {+ diskUsed = diskInfo.Used+ diskTotal = diskInfo.Total+ }++ hostInfo, _ := host.Info()+ var hostname string+ if hostInfo != nil {+ hostname = hostInfo.Hostname+ }++ stats := SystemStats{+ CPUUsage: cpuUsage,+ MemoryUsage: memUsed,+ MemoryTotal: memTotal,+ DiskUsage: diskUsed,+ DiskTotal: diskTotal,+ CPUCount: cpuCount,+ Architecture: runtime.GOARCH,+ Platform: runtime.GOOS,+ Hostname: hostname,+ }++ _ = conn.SetWriteDeadline(time.Now().Add(10 * time.Second))+ return conn.WriteJSON(stats)+ }++ if err := send(true); err != nil {+ return+ }++ for {+ select {+ case <-c.Request.Context().Done():+ return+ case <-ticker.C:+ if err := send(true); err != nil {+ return+ }+ }+ }+}++func (h *SystemHandler) ConvertDockerRun(c *gin.Context) {+ var req models.ConvertDockerRunRequest+ if err := c.ShouldBindJSON(&req); err != nil {+ c.JSON(http.StatusBadRequest, gin.H{+ "success": false,+ "error": "Invalid request format: " + err.Error(),+ })+ return+ }++ parsed, err := h.systemService.ParseDockerRunCommand(req.DockerRunCommand)+ if err != nil {+ c.JSON(http.StatusBadRequest, gin.H{+ "success": false,+ "error": "Failed to parse docker run command. Please check the syntax.",+ "code": "BAD_REQUEST",+ })+ return+ }++ dockerCompose, envVars, serviceName, err := h.systemService.ConvertToDockerCompose(parsed)+ if err != nil {+ c.JSON(http.StatusInternalServerError, gin.H{+ "success": false,+ "error": "Failed to convert to Docker Compose format.",+ "code": "CONVERSION_ERROR",+ })+ return+ }++ c.JSON(http.StatusOK, models.ConvertDockerRunResponse{+ Success: true,+ DockerCompose: dockerCompose,+ EnvVars: envVars,+ ServiceName: serviceName,+ })+}diff --git a/backend/internal/api/updater_handler.go b/backend/internal/api/updater_handler.goindex 25f121130..9910ff61d 100644--- a/backend/internal/api/updater_handler.go+++ b/backend/internal/api/updater_handler.go@@ -17,7 +17,7 @@ type UpdaterHandler struct {func NewUpdaterHandler(group *gin.RouterGroup, updaterService *services.UpdaterService, authMiddleware *middleware.AuthMiddleware) {handler := &UpdaterHandler{updaterService: updaterService}- apiGroup := group.Group("/updater")+ apiGroup := group.Group("/environments/:id/updater")apiGroup.Use(authMiddleware.WithAdminNotRequired().Add()){apiGroup.POST("/run", handler.Run)diff --git a/backend/internal/api/volume_handler.go b/backend/internal/api/volume_handler.goindex 17659ba04..277fc5163 100644--- a/backend/internal/api/volume_handler.go+++ b/backend/internal/api/volume_handler.go@@ -19,9 +19,10 @@ type VolumeHandler struct {func NewVolumeHandler(group *gin.RouterGroup, dockerService *services.DockerClientService, volumeService *services.VolumeService, authMiddleware *middleware.AuthMiddleware) {handler := &VolumeHandler{dockerService: dockerService, volumeService: volumeService}- apiGroup := group.Group("/volumes")+ apiGroup := group.Group("/environments/:id/volumes")apiGroup.Use(authMiddleware.WithAdminNotRequired().Add()){+ apiGroup.GET("/counts", handler.GetVolumeUsageCounts)apiGroup.GET("", handler.List)apiGroup.GET("/:volumeName", handler.GetByName)apiGroup.POST("", handler.Create)diff --git a/backend/internal/bootstrap/router_bootstrap.go b/backend/internal/bootstrap/router_bootstrap.goindex be394dd16..b68244c37 100644--- a/backend/internal/bootstrap/router_bootstrap.go+++ b/backend/internal/bootstrap/router_bootstrap.go@@ -1,6 +1,7 @@package bootstrapimport (+ "context""log/slog""path""strings"@@ -63,20 +64,20 @@ func setupRouter(cfg *config.Config, appServices *Services) *gin.Engine {apiGroup := router.Group("/api")- if cfg.AgentMode {- api.NewHealthHandler(apiGroup)- api.NewEnvironmentHandler(apiGroup, appServices.Environment, appServices.Container, appServices.Image, appServices.ImageUpdate, appServices.Updater, appServices.Network, appServices.Volume, appServices.Project, appServices.Settings, appServices.System, appServices.Docker, authMiddleware, cfg)- api.NewSystemHandler(apiGroup, appServices.Docker, appServices.System, authMiddleware)- return router- }+ apiGroup.Use(middleware.NewEnvProxyMiddleware(api.LOCAL_DOCKER_ENVIRONMENT_ID, func(ctx context.Context, id string) (string, *string, bool, error) {+ env, err := appServices.Environment.GetEnvironmentByID(ctx, id)+ if err != nil || env == nil {+ return "", nil, false, err+ }+ return env.ApiUrl, env.AccessToken, env.Enabled, nil+ }))api.NewHealthHandler(apiGroup)api.NewVersionHandler(apiGroup, appServices.Version)api.NewAuthHandler(apiGroup, appServices.User, appServices.Auth, appServices.Oidc, authMiddleware)api.NewContainerHandler(apiGroup, appServices.Docker, appServices.Container, appServices.Image, authMiddleware)api.NewContainerRegistryHandler(apiGroup, appServices.ContainerRegistry, authMiddleware)- api.NewConverterHandler(apiGroup, appServices.Converter, authMiddleware)- api.NewEnvironmentHandler(apiGroup, appServices.Environment, appServices.Container, appServices.Image, appServices.ImageUpdate, appServices.Updater, appServices.Network, appServices.Volume, appServices.Project, appServices.Settings, appServices.System, appServices.Docker, authMiddleware, cfg)+ api.NewEnvironmentHandler(apiGroup, appServices.Environment, appServices.Settings, authMiddleware, cfg)api.NewEventHandler(apiGroup, appServices.Event, authMiddleware)api.NewImageHandler(apiGroup, appServices.Docker, appServices.Image, appServices.ImageUpdate, authMiddleware)api.NewImageUpdateHandler(apiGroup, appServices.ImageUpdate, authMiddleware)diff --git a/backend/internal/bootstrap/services_bootstrap.go b/backend/internal/bootstrap/services_bootstrap.goindex 13e82b46d..7e31c36c5 100644--- a/backend/internal/bootstrap/services_bootstrap.go+++ b/backend/internal/bootstrap/services_bootstrap.go@@ -23,7 +23,6 @@ type Services struct {Auth *services.AuthServiceOidc *services.OidcServiceDocker *services.DockerClientService- Converter *services.ConverterServiceTemplate *services.TemplateServiceContainerRegistry *services.ContainerRegistryServiceSystem *services.SystemService@@ -36,7 +35,6 @@ func initializeServices(ctx context.Context, db *database.DB, cfg *config.Configsvcs = &Services{}svcs.Event = services.NewEventService(db)- svcs.Converter = services.NewConverterService()svcs.Settings, err = services.NewSettingsService(ctx, db)if err != nil {return nil, nil, fmt.Errorf("failed to settings service: %w", err)diff --git a/backend/internal/middleware/environment_middleware.go b/backend/internal/middleware/environment_middleware.gonew file mode 100644index 000000000..5a61961c6--- /dev/null+++ b/backend/internal/middleware/environment_middleware.go@@ -0,0 +1,206 @@+package middleware++import (+ "context"+ "fmt"+ "io"+ "log/slog"+ "net/http"+ "path"+ "strings"+ "time"++ "github.com/gin-gonic/gin"+ wsutil "github.com/ofkm/arcane-backend/internal/utils/ws"+)++// EnvResolver should return the environment api url, optional access token, whether the env is enabled, and an error.+type EnvResolver func(ctx context.Context, id string) (apiURL string, accessToken *string, enabled bool, err error)++// NewEnvProxyMiddleware preserves the previous API and uses "id" as the param name.+func NewEnvProxyMiddleware(localID string, resolver EnvResolver) gin.HandlerFunc {+ return NewEnvProxyMiddlewareWithParam(localID, "id", resolver)+}++// NewEnvProxyMiddlewareWithParam returns a gin middleware that proxies requests whose environment id+// is remote. paramName is the URL param key (e.g. "id") that contains the environment id when using+// router groups; if that param is not present the middleware will attempt to auto-detect the id+// by parsing the request path after the first "/environments/" segment.+//+//nolint:gocognit+func NewEnvProxyMiddlewareWithParam(localID string, paramName string, resolver EnvResolver) gin.HandlerFunc {+ return func(c *gin.Context) {+ envID := c.Param(paramName)++ // Fallback: try to auto-detect env id from path like "/.../environments/<envID>/..."+ if envID == "" {+ const marker = "/environments/"+ if idx := strings.Index(c.Request.URL.Path, marker); idx >= 0 {+ rest := c.Request.URL.Path[idx+len(marker):]+ parts := strings.SplitN(rest, "/", 2)+ if len(parts) > 0 && parts[0] != "" {+ envID = parts[0]+ }+ }+ }++ if envID == "" || envID == localID {+ c.Next()+ return+ }++ apiURL, accessToken, enabled, err := resolver(c.Request.Context(), envID)+ if err != nil || apiURL == "" {+ c.JSON(http.StatusNotFound, gin.H{"success": false, "data": gin.H{"error": "Environment not found"}})+ c.Abort()+ return+ }+ if !enabled {+ c.JSON(http.StatusBadRequest, gin.H{"success": false, "data": gin.H{"error": "Environment is disabled"}})+ c.Abort()+ return+ }++ // Build target: map incoming /api/environments/:id/... -> remoteApiUrl/api/environments/<localID>/...+ prefix := "/api/environments/" + envID+ suffix := strings.TrimPrefix(c.Request.URL.Path, prefix)+ if !strings.HasPrefix(suffix, "/") && suffix != "" {+ suffix = "/" + suffix+ }+ target := strings.TrimRight(apiURL, "/") + path.Join("/api/environments/", localID) + suffix+ if qs := c.Request.URL.RawQuery; qs != "" {+ target += "?" + qs+ }++ if strings.EqualFold(c.GetHeader("Upgrade"), "websocket") || strings.Contains(strings.ToLower(c.GetHeader("Connection")), "upgrade") {+ wsTarget := target+ if strings.HasPrefix(target, "https://") {+ wsTarget = "wss://" + strings.TrimPrefix(target, "https://")+ } else if strings.HasPrefix(target, "http://") {+ wsTarget = "ws://" + strings.TrimPrefix(target, "http://")+ }++ hdr := http.Header{}+ if auth := c.GetHeader("Authorization"); auth != "" {+ hdr.Set("Authorization", auth)+ } else if cookieToken, err := c.Cookie("token"); err == nil && cookieToken != "" {+ hdr.Set("Authorization", "Bearer "+cookieToken)+ }++ if hdr.Get("Authorization") == "" {+ if cookieHeader := c.Request.Header.Get("Cookie"); cookieHeader != "" {+ hdr.Set("Cookie", cookieHeader)+ }+ }++ if accessToken != nil && *accessToken != "" {+ hdr.Set("X-Arcane-Agent-Token", *accessToken)+ }++ if err := wsutil.ProxyHTTP(c.Writer, c.Request, wsTarget, hdr); err != nil {+ slog.Error("websocket proxy failed", "env_id", envID, "target", wsTarget, "err", err)+ }+ c.Abort()+ return+ }++ var bodyReader io.Reader+ if c.Request.Body != nil {+ bodyReader = c.Request.Body+ }++ req, err := http.NewRequestWithContext(c.Request.Context(), c.Request.Method, target, bodyReader)+ if err != nil {+ c.JSON(http.StatusInternalServerError, gin.H{"success": false, "data": gin.H{"error": "Failed to create proxy request"}})+ c.Abort()+ return+ }++ skip := map[string]struct{}{+ "Host": {},+ "Connection": {},+ "Keep-Alive": {},+ "Proxy-Authenticate": {},+ "Proxy-Authorization": {},+ "Te": {},+ "Trailer": {},+ "Transfer-Encoding": {},+ "Upgrade": {},+ "Content-Length": {},+ "Origin": {},+ "Referer": {},+ "Access-Control-Request-Method": {},+ "Access-Control-Request-Headers": {},+ "Cookie": {},+ }+ for k, vs := range c.Request.Header {+ ck := http.CanonicalHeaderKey(k)+ if _, ok := skip[ck]; ok || ck == "Authorization" {+ continue+ }+ for _, v := range vs {+ req.Header.Add(k, v)+ }+ }++ // Forward Authorization (or promote cookie)+ if auth := c.GetHeader("Authorization"); auth != "" {+ req.Header.Set("Authorization", auth)+ } else if cookieToken, err := c.Cookie("token"); err == nil && cookieToken != "" {+ req.Header.Set("Authorization", "Bearer "+cookieToken)+ }++ // Forward agent token if provided by resolver+ if accessToken != nil && *accessToken != "" {+ req.Header.Set("X-Arcane-Agent-Token", *accessToken)+ }++ req.Header.Set("X-Forwarded-For", c.ClientIP())+ req.Header.Set("X-Forwarded-Host", c.Request.Host)++ client := &http.Client{Timeout: 60 * time.Second}+ resp, err := client.Do(req)+ if err != nil {+ c.JSON(http.StatusBadGateway, gin.H{"success": false, "data": gin.H{"error": fmt.Sprintf("Proxy request failed: %v", err)}})+ c.Abort()+ return+ }+ defer resp.Body.Close()++ hop := map[string]struct{}{+ http.CanonicalHeaderKey("Connection"): {},+ http.CanonicalHeaderKey("Keep-Alive"): {},+ http.CanonicalHeaderKey("Proxy-Authenticate"): {},+ http.CanonicalHeaderKey("Proxy-Authorization"): {},+ http.CanonicalHeaderKey("TE"): {},+ http.CanonicalHeaderKey("Trailers"): {},+ http.CanonicalHeaderKey("Trailer"): {},+ http.CanonicalHeaderKey("Transfer-Encoding"): {},+ http.CanonicalHeaderKey("Upgrade"): {},+ }+ for _, connVal := range resp.Header.Values("Connection") {+ for _, token := range strings.Split(connVal, ",") {+ if t := strings.TrimSpace(token); t != "" {+ hop[http.CanonicalHeaderKey(t)] = struct{}{}+ }+ }+ }++ for k, vs := range resp.Header {+ ck := http.CanonicalHeaderKey(k)+ if _, ok := hop[ck]; ok {+ continue+ }+ for _, v := range vs {+ c.Writer.Header().Add(k, v)+ }+ }++ c.Status(resp.StatusCode)+ if c.Request.Method != http.MethodHead {+ _, _ = io.Copy(c.Writer, resp.Body)+ }++ c.Abort()+ }+}diff --git a/backend/internal/services/converter_service.go b/backend/internal/services/converter_service.godeleted file mode 100644index 31f4ae7e0..000000000--- a/backend/internal/services/converter_service.go+++ /dev/null@@ -1,328 +0,0 @@-package services--import (- "fmt"- "regexp"- "strings"-- "github.com/ofkm/arcane-backend/internal/models"- "go.yaml.in/yaml/v4"-)--type ConverterService struct{}--func NewConverterService() *ConverterService {- return &ConverterService{}-}--func (s *ConverterService) ParseDockerRunCommand(command string) (*models.DockerRunCommand, error) {- if command == "" {- return nil, fmt.Errorf("docker run command must be a non-empty string")- }-- cmd := strings.TrimSpace(command)- cmd = regexp.MustCompile(`^docker\s+run\s+`).ReplaceAllString(cmd, "")-- if cmd == "" {- return nil, fmt.Errorf("no arguments found after 'docker run'")- }-- result := &models.DockerRunCommand{}- tokens, err := s.parseCommandTokens(cmd)- if err != nil {- return nil, fmt.Errorf("failed to parse command tokens: %w", err)- }-- if len(tokens) == 0 {- return nil, fmt.Errorf("no valid tokens found in docker run command")- }-- if err := s.parseTokens(tokens, result); err != nil {- return nil, err- }-- if result.Image == "" {- return nil, fmt.Errorf("no Docker image specified in command")- }-- return result, nil-}--func (s *ConverterService) parseTokens(tokens []string, result *models.DockerRunCommand) error {- for i := 0; i < len(tokens); i++ {- token := tokens[i]-- if strings.HasPrefix(token, "-") {- advance, err := s.parseFlag(token, tokens, i, result)- if err != nil {- return err- }- i += advance- } else {- if result.Image == "" {- if token == "" {- return fmt.Errorf("image name cannot be empty")- }- result.Image = token- } else {- remainingTokens := tokens[i:]- result.Command = strings.Join(remainingTokens, " ")- break- }- }- }- return nil-}--func (s *ConverterService) parseFlag(token string, tokens []string, index int, result *models.DockerRunCommand) (int, error) {- switch token {- case "-d", "--detach":- result.Detached = true- return 0, nil- case "-i", "--interactive":- result.Interactive = true- return 0, nil- case "-t", "--tty":- result.TTY = true- return 0, nil- case "--rm":- result.Remove = true- return 0, nil- case "--privileged":- result.Privileged = true- return 0, nil- default:- return s.parseFlagWithValue(token, tokens, index, result)- }-}--func (s *ConverterService) parseFlagWithValue(token string, tokens []string, index int, result *models.DockerRunCommand) (int, error) {- switch token {- case "--name":- return s.parseStringFlag(token, tokens, index, &result.Name)- case "-p", "--port", "--publish":- return s.parseSliceFlag(token, tokens, index, &result.Ports)- case "-v", "--volume":- return s.parseSliceFlag(token, tokens, index, &result.Volumes)- case "-e", "--env":- return s.parseSliceFlag(token, tokens, index, &result.Environment)- case "--network":- return s.parseSliceFlag(token, tokens, index, &result.Networks)- case "--restart":- return s.parseStringFlag(token, tokens, index, &result.Restart)- case "-w", "--workdir":- return s.parseStringFlag(token, tokens, index, &result.Workdir)- case "-u", "--user":- return s.parseStringFlag(token, tokens, index, &result.User)- case "--entrypoint":- return s.parseStringFlag(token, tokens, index, &result.Entrypoint)- case "--health-cmd":- return s.parseStringFlag(token, tokens, index, &result.HealthCheck)- case "-m", "--memory":- return s.parseStringFlag(token, tokens, index, &result.MemoryLimit)- case "--cpus":- return s.parseStringFlag(token, tokens, index, &result.CPULimit)- case "--label":- return s.parseSliceFlag(token, tokens, index, &result.Labels)- default:- return s.parseUnknownFlag(token, tokens, index, result)- }-}--func (s *ConverterService) parseStringFlag(flagName string, tokens []string, index int, target *string) (int, error) {- if index+1 >= len(tokens) {- return 0, fmt.Errorf("missing value for %s flag", flagName)- }-- value := tokens[index+1]- if value == "" || strings.HasPrefix(value, "-") {- return 0, fmt.Errorf("invalid value for %s flag", flagName)- }-- *target = value- return 1, nil-}--func (s *ConverterService) parseSliceFlag(flagName string, tokens []string, index int, target *[]string) (int, error) {- if index+1 >= len(tokens) {- return 0, fmt.Errorf("missing value for %s flag", flagName)- }-- value := tokens[index+1]- if value == "" || strings.HasPrefix(value, "-") {- return 0, fmt.Errorf("invalid value for %s flag", flagName)- }-- *target = append(*target, value)- return 1, nil-}--func (s *ConverterService) parseUnknownFlag(token string, tokens []string, index int, result *models.DockerRunCommand) (int, error) {- if !strings.HasPrefix(token, "--") && len(token) > 2 {- s.parseCombinedFlags(token, result)- return 0, nil- }-- if index+1 < len(tokens) && !strings.HasPrefix(tokens[index+1], "-") && result.Image == "" {- return 1, nil- }-- return 0, nil-}--func (s *ConverterService) parseCombinedFlags(token string, result *models.DockerRunCommand) {- flags := strings.Split(token[1:], "")- for _, flag := range flags {- switch flag {- case "d":- result.Detached = true- case "i":- result.Interactive = true- case "t":- result.TTY = true- }- }-}--// ConvertToDockerCompose converts a parsed docker run command to docker-compose YAML-func (s *ConverterService) ConvertToDockerCompose(parsed *models.DockerRunCommand) (string, string, string, error) {- if parsed.Image == "" {- return "", "", "", fmt.Errorf("cannot convert to Docker Compose: no image specified")- }-- serviceName := parsed.Name- if serviceName == "" {- serviceName = "app"- }-- service := models.DockerComposeService{- Image: parsed.Image,- }-- if parsed.Name != "" {- service.ContainerName = parsed.Name- }-- if len(parsed.Ports) > 0 {- service.Ports = parsed.Ports- }-- if len(parsed.Volumes) > 0 {- service.Volumes = parsed.Volumes- }-- if len(parsed.Environment) > 0 {- service.Environment = parsed.Environment- }-- if len(parsed.Networks) > 0 {- service.Networks = parsed.Networks- }-- if parsed.Restart != "" {- service.Restart = parsed.Restart- }-- if parsed.Workdir != "" {- service.WorkingDir = parsed.Workdir- }-- if parsed.User != "" {- service.User = parsed.User- }-- if parsed.Entrypoint != "" {- service.Entrypoint = parsed.Entrypoint- }-- if parsed.Command != "" {- service.Command = parsed.Command- }-- if parsed.Interactive && parsed.TTY {- service.StdinOpen = true- service.TTY = true- }-- if parsed.Privileged {- service.Privileged = true- }-- if len(parsed.Labels) > 0 {- service.Labels = parsed.Labels- }-- if parsed.HealthCheck != "" {- service.Healthcheck = &models.DockerComposeHealthcheck{- Test: parsed.HealthCheck,- }- }-- if parsed.MemoryLimit != "" || parsed.CPULimit != "" {- service.Deploy = &models.DockerComposeDeploy{- Resources: &models.DockerComposeResources{- Limits: &models.DockerComposeResourceLimits{},- },- }- if parsed.MemoryLimit != "" {- service.Deploy.Resources.Limits.Memory = parsed.MemoryLimit- }- if parsed.CPULimit != "" {- service.Deploy.Resources.Limits.CPUs = parsed.CPULimit- }- }-- compose := models.DockerComposeConfig{- Services: map[string]models.DockerComposeService{- serviceName: service,- },- }-- // Convert to YAML- yamlData, err := yaml.Marshal(&compose)- if err != nil {- return "", "", "", fmt.Errorf("failed to convert to YAML: %w", err)- }-- // Generate environment variables file content- envVars := strings.Join(parsed.Environment, "\n")-- return string(yamlData), envVars, serviceName, nil-}--// parseCommandTokens parses command string into tokens, handling quotes-func (s *ConverterService) parseCommandTokens(command string) ([]string, error) {- var tokens []string- var current strings.Builder- inQuotes := false- var quoteChar rune-- for i, char := range command {- switch {- case (char == '"' || char == '\'') && !inQuotes:- inQuotes = true- quoteChar = char- case char == quoteChar && inQuotes:- inQuotes = false- quoteChar = 0- case char == ' ' && !inQuotes:- if current.Len() > 0 {- tokens = append(tokens, current.String())- current.Reset()- }- default:- current.WriteRune(char)- }-- // Check for unclosed quotes at end- if i == len(command)-1 && inQuotes {- return nil, fmt.Errorf("unclosed quote in command: missing closing %c", quoteChar)- }- }-- if current.Len() > 0 {- tokens = append(tokens, current.String())- }-- return tokens, nil-}diff --git a/backend/internal/services/system_service.go b/backend/internal/services/system_service.goindex 2dac96ef4..4397a6a61 100644--- a/backend/internal/services/system_service.go+++ b/backend/internal/services/system_service.go@@ -4,12 +4,16 @@ import ("context""fmt""log/slog"+ "regexp"+ "strings""github.com/docker/docker/api/types/build""github.com/docker/docker/api/types/filters"+ "github.com/goccy/go-yaml""github.com/ofkm/arcane-backend/internal/database""github.com/ofkm/arcane-backend/internal/dto""github.com/ofkm/arcane-backend/internal/models"+ "github.com/ofkm/arcane-backend/internal/utils/converter")type SystemService struct {@@ -328,3 +332,141 @@ func (s *SystemService) pruneNetworks(ctx context.Context, result *dto.PruneAllRresult.NetworksDeleted = report.NetworksDeletedreturn nil}++func (s *SystemService) ParseDockerRunCommand(command string) (*models.DockerRunCommand, error) {+ if command == "" {+ return nil, fmt.Errorf("docker run command must be a non-empty string")+ }++ cmd := strings.TrimSpace(command)+ cmd = regexp.MustCompile(`^docker\s+run\s+`).ReplaceAllString(cmd, "")++ if cmd == "" {+ return nil, fmt.Errorf("no arguments found after 'docker run'")+ }++ result := &models.DockerRunCommand{}+ tokens, err := converter.ParseCommandTokens(cmd)+ if err != nil {+ return nil, fmt.Errorf("failed to parse command tokens: %w", err)+ }++ if len(tokens) == 0 {+ return nil, fmt.Errorf("no valid tokens found in docker run command")+ }++ if err := converter.ParseTokens(tokens, result); err != nil {+ return nil, err+ }++ if result.Image == "" {+ return nil, fmt.Errorf("no Docker image specified in command")+ }++ return result, nil+}++func (s *SystemService) ConvertToDockerCompose(parsed *models.DockerRunCommand) (string, string, string, error) {+ if parsed.Image == "" {+ return "", "", "", fmt.Errorf("cannot convert to Docker Compose: no image specified")+ }++ serviceName := parsed.Name+ if serviceName == "" {+ serviceName = "app"+ }++ service := models.DockerComposeService{+ Image: parsed.Image,+ }++ if parsed.Name != "" {+ service.ContainerName = parsed.Name+ }++ if len(parsed.Ports) > 0 {+ service.Ports = parsed.Ports+ }++ if len(parsed.Volumes) > 0 {+ service.Volumes = parsed.Volumes+ }++ if len(parsed.Environment) > 0 {+ service.Environment = parsed.Environment+ }++ if len(parsed.Networks) > 0 {+ service.Networks = parsed.Networks+ }++ if parsed.Restart != "" {+ service.Restart = parsed.Restart+ }++ if parsed.Workdir != "" {+ service.WorkingDir = parsed.Workdir+ }++ if parsed.User != "" {+ service.User = parsed.User+ }++ if parsed.Entrypoint != "" {+ service.Entrypoint = parsed.Entrypoint+ }++ if parsed.Command != "" {+ service.Command = parsed.Command+ }++ if parsed.Interactive && parsed.TTY {+ service.StdinOpen = true+ service.TTY = true+ }++ if parsed.Privileged {+ service.Privileged = true+ }++ if len(parsed.Labels) > 0 {+ service.Labels = parsed.Labels+ }++ if parsed.HealthCheck != "" {+ service.Healthcheck = &models.DockerComposeHealthcheck{+ Test: parsed.HealthCheck,+ }+ }++ if parsed.MemoryLimit != "" || parsed.CPULimit != "" {+ service.Deploy = &models.DockerComposeDeploy{+ Resources: &models.DockerComposeResources{+ Limits: &models.DockerComposeResourceLimits{},+ },+ }+ if parsed.MemoryLimit != "" {+ service.Deploy.Resources.Limits.Memory = parsed.MemoryLimit+ }+ if parsed.CPULimit != "" {+ service.Deploy.Resources.Limits.CPUs = parsed.CPULimit+ }+ }++ compose := models.DockerComposeConfig{+ Services: map[string]models.DockerComposeService{+ serviceName: service,+ },+ }++ // Convert to YAML+ yamlData, err := yaml.Marshal(&compose)+ if err != nil {+ return "", "", "", fmt.Errorf("failed to convert to YAML: %w", err)+ }++ // Generate environment variables file content+ envVars := strings.Join(parsed.Environment, "\n")++ return string(yamlData), envVars, serviceName, nil+}diff --git a/backend/internal/utils/converter/converter_util.go b/backend/internal/utils/converter/converter_util.gonew file mode 100644index 000000000..d6a33d5f4--- /dev/null+++ b/backend/internal/utils/converter/converter_util.go@@ -0,0 +1,180 @@+package converter++import (+ "fmt"+ "strings"++ "github.com/ofkm/arcane-backend/internal/models"+)++func ParseTokens(tokens []string, result *models.DockerRunCommand) error {+ for i := 0; i < len(tokens); i++ {+ token := tokens[i]++ if strings.HasPrefix(token, "-") {+ advance, err := parseFlag(token, tokens, i, result)+ if err != nil {+ return err+ }+ i += advance+ } else {+ if result.Image == "" {+ if token == "" {+ return fmt.Errorf("image name cannot be empty")+ }+ result.Image = token+ } else {+ remainingTokens := tokens[i:]+ result.Command = strings.Join(remainingTokens, " ")+ break+ }+ }+ }+ return nil+}++func parseFlag(token string, tokens []string, index int, result *models.DockerRunCommand) (int, error) {+ switch token {+ case "-d", "--detach":+ result.Detached = true+ return 0, nil+ case "-i", "--interactive":+ result.Interactive = true+ return 0, nil+ case "-t", "--tty":+ result.TTY = true+ return 0, nil+ case "--rm":+ result.Remove = true+ return 0, nil+ case "--privileged":+ result.Privileged = true+ return 0, nil+ default:+ return parseFlagWithValue(token, tokens, index, result)+ }+}++func parseFlagWithValue(token string, tokens []string, index int, result *models.DockerRunCommand) (int, error) {+ switch token {+ case "--name":+ return parseStringFlag(token, tokens, index, &result.Name)+ case "-p", "--port", "--publish":+ return parseSliceFlag(token, tokens, index, &result.Ports)+ case "-v", "--volume":+ return parseSliceFlag(token, tokens, index, &result.Volumes)+ case "-e", "--env":+ return parseSliceFlag(token, tokens, index, &result.Environment)+ case "--network":+ return parseSliceFlag(token, tokens, index, &result.Networks)+ case "--restart":+ return parseStringFlag(token, tokens, index, &result.Restart)+ case "-w", "--workdir":+ return parseStringFlag(token, tokens, index, &result.Workdir)+ case "-u", "--user":+ return parseStringFlag(token, tokens, index, &result.User)+ case "--entrypoint":+ return parseStringFlag(token, tokens, index, &result.Entrypoint)+ case "--health-cmd":+ return parseStringFlag(token, tokens, index, &result.HealthCheck)+ case "-m", "--memory":+ return parseStringFlag(token, tokens, index, &result.MemoryLimit)+ case "--cpus":+ return parseStringFlag(token, tokens, index, &result.CPULimit)+ case "--label":+ return parseSliceFlag(token, tokens, index, &result.Labels)+ default:+ return parseUnknownFlag(token, tokens, index, result)+ }+}++func parseStringFlag(flagName string, tokens []string, index int, target *string) (int, error) {+ if index+1 >= len(tokens) {+ return 0, fmt.Errorf("missing value for %s flag", flagName)+ }++ value := tokens[index+1]+ if value == "" || strings.HasPrefix(value, "-") {+ return 0, fmt.Errorf("invalid value for %s flag", flagName)+ }++ *target = value+ return 1, nil+}++func parseSliceFlag(flagName string, tokens []string, index int, target *[]string) (int, error) {+ if index+1 >= len(tokens) {+ return 0, fmt.Errorf("missing value for %s flag", flagName)+ }++ value := tokens[index+1]+ if value == "" || strings.HasPrefix(value, "-") {+ return 0, fmt.Errorf("invalid value for %s flag", flagName)+ }++ *target = append(*target, value)+ return 1, nil+}++func parseUnknownFlag(token string, tokens []string, index int, result *models.DockerRunCommand) (int, error) {+ if !strings.HasPrefix(token, "--") && len(token) > 2 {+ parseCombinedFlags(token, result)+ return 0, nil+ }++ if index+1 < len(tokens) && !strings.HasPrefix(tokens[index+1], "-") && result.Image == "" {+ return 1, nil+ }++ return 0, nil+}++func parseCombinedFlags(token string, result *models.DockerRunCommand) {+ flags := strings.Split(token[1:], "")+ for _, flag := range flags {+ switch flag {+ case "d":+ result.Detached = true+ case "i":+ result.Interactive = true+ case "t":+ result.TTY = true+ }+ }+}++func ParseCommandTokens(command string) ([]string, error) {+ var tokens []string+ var current strings.Builder+ inQuotes := false+ var quoteChar rune++ for i, char := range command {+ switch {+ case (char == '"' || char == '\'') && !inQuotes:+ inQuotes = true+ quoteChar = char+ case char == quoteChar && inQuotes:+ inQuotes = false+ quoteChar = 0+ case char == ' ' && !inQuotes:+ if current.Len() > 0 {+ tokens = append(tokens, current.String())+ current.Reset()+ }+ default:+ current.WriteRune(char)+ }++ // Check for unclosed quotes at end+ if i == len(command)-1 && inQuotes {+ return nil, fmt.Errorf("unclosed quote in command: missing closing %c", quoteChar)+ }+ }++ if current.Len() > 0 {+ tokens = append(tokens, current.String())+ }++ return tokens, nil+}diff --git a/backend/internal/utils/ws/proxy.go b/backend/internal/utils/ws/proxy.goindex 018a23db4..60f230220 100644--- a/backend/internal/utils/ws/proxy.go+++ b/backend/internal/utils/ws/proxy.go@@ -2,6 +2,7 @@ package wsimport ("io"+ "log/slog""net/http""time"@@ -19,6 +20,7 @@ var upgrader = websocket.Upgrader{func ProxyHTTP(w http.ResponseWriter, r *http.Request, remoteWS string, header http.Header) error {clientConn, err := upgrader.Upgrade(w, r, nil)if err != nil {+ slog.Error("failed to upgrade client connection", "remoteWS", remoteWS, "err", err)return err}defer clientConn.Close()@@ -27,6 +29,8 @@ func ProxyHTTP(w http.ResponseWriter, r *http.Request, remoteWS string, header hProxy: http.ProxyFromEnvironment,HandshakeTimeout: 45 * time.Second,}++ slog.Debug("attempting websocket dial", "remoteWS", remoteWS, "headers", header)remoteConn, resp, err := dialer.Dial(remoteWS, header)// Ensure the response body is drained & closed to avoid leaking resources.if resp != nil {@@ -34,11 +38,19 @@ func ProxyHTTP(w http.ResponseWriter, r *http.Request, remoteWS string, header h_ = resp.Body.Close()}if err != nil {+ slog.Error("failed to dial remote websocket", "remoteWS", remoteWS, "err", err, "resp_status", func() int {+ if resp != nil {+ return resp.StatusCode+ }+ return 0+ }())_ = clientConn.WriteMessage(websocket.CloseMessage, []byte{})return err}defer remoteConn.Close()+ slog.Debug("websocket proxy established", "remoteWS", remoteWS)+errc := make(chan struct{}, 2)// client -> remotediff --git a/docker/Dockerfile.dev b/docker/Dockerfile.devindex 63a662e47..a96a56790 100644--- a/docker/Dockerfile.dev+++ b/docker/Dockerfile.dev@@ -3,16 +3,14 @@ ARG NODE_VERSION="24"ARG GO_VERSION="1.25"# Stage 1: Frontend Development-FROM node:${NODE_VERSION} AS frontend-dev+FROM node:${NODE_VERSION}-alpine AS frontend-devRUN corepack enableWORKDIR /app-# Copy package configuration files+# Copy package configuration files and install dependenciesCOPY package.json pnpm-workspace.yaml pnpm-lock.yaml ./COPY frontend/package.json ./frontend/package.json--# Install dependencies-RUN pnpm install --frozen-lockfile+RUN --mount=type=cache,target=/root/.pnpm-store pnpm install --frozen-lockfile# Set development environmentENV NODE_ENV=development@@ -28,8 +26,14 @@ CMD ["pnpm", "-C", "frontend", "dev", "--host", "0.0.0.0"]FROM golang:${GO_VERSION}-alpine AS backend-dev# Install development tools and dependencies-RUN go install github.com/air-verse/air@latest-RUN apk add --no-cache git ca-certificates tzdata curl gcc musl-dev+RUN apk add --no-cache \+ ca-certificates \+ curl \+ gcc \+ git \+ musl-dev \+ tzdata && \+ go install github.com/air-verse/air@latest# Set development environment variablesENV GIN_MODE=debug@@ -38,15 +42,12 @@ ENV ENVIRONMENT=developmentWORKDIR /app-# Copy Go module files+# Copy Go module files and download dependenciesCOPY backend/go.mod backend/go.sum ./--# Download Go dependencies-RUN go mod download+RUN --mount=type=cache,target=/go/pkg/mod go mod download# Create directories for development-RUN mkdir -p /app/data && chmod 755 /app/data-RUN mkdir -p /app/.bin && chmod 755 /app/.bin+RUN mkdir -p /app/data /app/.bin && chmod 755 /app/data /app/.bin# Expose backend development portEXPOSE 3552diff --git a/frontend/src/lib/components/action-buttons.svelte b/frontend/src/lib/components/action-buttons.svelteindex d1c6bce17..42872d20d 100644--- a/frontend/src/lib/components/action-buttons.svelte+++ b/frontend/src/lib/components/action-buttons.svelte@@ -2,7 +2,6 @@import { openConfirmDialog } from './confirm-dialog';import { goto, invalidateAll } from '$app/navigation';import { toast } from 'svelte-sonner';- import { environmentAPI } from '$lib/services/api';import { tryCatch } from '$lib/utils/try-catch';import { handleApiResultWithCallbacks } from '$lib/utils/api.util';import { ArcaneButton } from '$lib/components/arcane-button/index.js';@@ -11,6 +10,8 @@import { environmentStore, LOCAL_DOCKER_ENVIRONMENT_ID } from '$lib/stores/environment.store';import { get } from 'svelte/store';import { m } from '$lib/paraglide/messages';+ import { containerService } from '$lib/services/container-service';+ import { projectService } from '$lib/services/project-service';type TargetType = 'container' | 'project';type LoadingStates = {@@ -137,11 +138,6 @@);}- function getCurrentEnvironmentId(): string {- const env = get(environmentStore.selected);- return env?.id || LOCAL_DOCKER_ENVIRONMENT_ID;- }-function confirmAction(action: string) {if (action === 'remove') {openConfirmDialog({@@ -161,8 +157,8 @@handleApiResultWithCallbacks({result: await tryCatch(type === 'container'- ? environmentAPI.deleteContainer(id)- : environmentAPI.destroyProject(id, removeVolumes, removeFiles)+ ? containerService.deleteContainer(id)+ : projectService.destroyProject(id, removeVolumes, removeFiles)),message: m.action_failed_generic({action: type === 'project' ? m.compose_destroy() : m.common_remove(),@@ -199,7 +195,7 @@action: async () => {setLoading('redeploy', true);handleApiResultWithCallbacks({- result: await tryCatch(environmentAPI.redeployProject(id)),+ result: await tryCatch(projectService.redeployProject(id)),message: m.action_failed_generic({ action: m.action_redeploy(), type }),setLoadingState: (value) => setLoading('redeploy', value),onSuccess: async () => {@@ -216,7 +212,7 @@async function handleStart() {setLoading('start', true);await handleApiResultWithCallbacks({- result: await tryCatch(type === 'container' ? environmentAPI.startContainer(id) : environmentAPI.deployProject(id)),+ result: await tryCatch(type === 'container' ? containerService.startContainer(id) : projectService.deployProject(id)),message: m.action_failed_generic({ action: m.common_start(), type }),setLoadingState: (value) => setLoading('start', value),onSuccess: async () => {@@ -234,7 +230,7 @@let hadError = false;try {- const { pulled } = await environmentAPI.deployProjectMaybePull(id, (data) => {+ const { pulled } = await projectService.deployProjectMaybePull(id, (data) => {if (!data) return;if (!openedPopover && isDownloadingLine(data)) {@@ -316,7 +312,7 @@async function handleStop() {setLoading('stop', true);await handleApiResultWithCallbacks({- result: await tryCatch(type === 'container' ? environmentAPI.stopContainer(id) : environmentAPI.downProject(id)),+ result: await tryCatch(type === 'container' ? containerService.stopContainer(id) : projectService.downProject(id)),message: m.action_failed_generic({ action: m.common_stop(), type }),setLoadingState: (value) => setLoading('stop', value),onSuccess: async () => {@@ -330,7 +326,7 @@async function handleRestart() {setLoading('restart', true);await handleApiResultWithCallbacks({- result: await tryCatch(type === 'container' ? environmentAPI.restartContainer(id) : environmentAPI.restartProject(id)),+ result: await tryCatch(type === 'container' ? containerService.restartContainer(id) : projectService.restartProject(id)),message: m.action_failed_generic({ action: m.common_restart(), type }),setLoadingState: (value) => setLoading('restart', value),onSuccess: async () => {@@ -350,7 +346,7 @@let wasSuccessful = false;try {- await environmentAPI.pullProjectImages(id, (data) => {+ await projectService.pullProjectImages(id, (data) => {if (!data) return;if (data.error) {diff --git a/frontend/src/lib/components/dialogs/template-selection-dialog.svelte b/frontend/src/lib/components/dialogs/template-selection-dialog.svelteindex 728a2d062..9b1474b35 100644--- a/frontend/src/lib/components/dialogs/template-selection-dialog.svelte+++ b/frontend/src/lib/components/dialogs/template-selection-dialog.svelte@@ -12,7 +12,6 @@import ChevronDownIcon from '@lucide/svelte/icons/chevron-down';import ChevronRightIcon from '@lucide/svelte/icons/chevron-right';import { ScrollArea } from '$lib/components/ui/scroll-area/index.js';- import { templateAPI } from '$lib/services/api';import type { Template } from '$lib/types/template.type';import { Label } from '$lib/components/ui/label/index.js';import * as Select from '$lib/components/ui/select/index.js';@@ -21,6 +20,7 @@import { toast } from 'svelte-sonner';import { m } from '$lib/paraglide/messages';+ import { templateService } from '$lib/services/template-service';interface Props {open: boolean;@@ -108,7 +108,7 @@loadingStates = new Map(loadingStates);try {- const details = await templateAPI.getTemplateContent(template.id);+ const details = await templateService.getTemplateContent(template.id);if (!details) {toast.error(m.templates_load_failed());return;@@ -139,7 +139,7 @@loadingStates = new Map(loadingStates);try {- const result = await templateAPI.download(templateId);+ const result = await templateService.download(templateId);if (result) {toast.success(m.templates_downloaded_success({ name: template.name }));diff --git a/frontend/src/lib/components/image-update-item.svelte b/frontend/src/lib/components/image-update-item.svelteindex d4c94760c..f180c341a 100644--- a/frontend/src/lib/components/image-update-item.svelte+++ b/frontend/src/lib/components/image-update-item.svelte@@ -9,10 +9,10 @@import ArrowRightIcon from '@lucide/svelte/icons/arrow-right';import PackageIcon from '@lucide/svelte/icons/package';import KeyRoundIcon from '@lucide/svelte/icons/key-round';- import { environmentAPI } from '$lib/services/api';import { toast } from 'svelte-sonner';import type { ImageUpdateData } from '$lib/types/image.type';import { m } from '$lib/paraglide/messages';+ import { imageService } from '$lib/services/image-service';interface Props {updateInfo?: ImageUpdateData | undefined;@@ -91,7 +91,7 @@isChecking = true;try {- const result = await environmentAPI.checkImageUpdateByID(imageId);+ const result = await imageService.checkImageUpdateByID(imageId);if (result) {if (result.error) {localUpdateInfo = result;diff --git a/frontend/src/lib/components/sheets/add-template-registry-sheet.svelte b/frontend/src/lib/components/sheets/add-template-registry-sheet.svelteindex 699ecab4d..ccb55d789 100644--- a/frontend/src/lib/components/sheets/add-template-registry-sheet.svelte+++ b/frontend/src/lib/components/sheets/add-template-registry-sheet.svelte@@ -8,9 +8,9 @@import AlertCircleIcon from '@lucide/svelte/icons/alert-circle';import { z } from 'zod/v4';import { createForm, preventDefault } from '$lib/utils/form.utils';- import { templateAPI } from '$lib/services/api';import * as Alert from '$lib/components/ui/alert/index.js';import { m } from '$lib/paraglide/messages';+ import { templateService } from '$lib/services/template-service';type TemplateRegistryFormProps = {open: boolean;@@ -41,7 +41,7 @@if (!data) return;try {- const registryData = await templateAPI.fetchRegistry(data.url);+ const registryData = await templateService.fetchRegistry(data.url);if (!registryData.name || !registryData.templates || !Array.isArray(registryData.templates)) {throw new Error(m.templates_registry_invalid_format());diff --git a/frontend/src/lib/components/sheets/image-pull-sheet.svelte b/frontend/src/lib/components/sheets/image-pull-sheet.svelteindex cafa90235..df1972ebe 100644--- a/frontend/src/lib/components/sheets/image-pull-sheet.svelte+++ b/frontend/src/lib/components/sheets/image-pull-sheet.svelte@@ -70,14 +70,6 @@}}- function buildApiUrl(fullImageName: string): string {- const envId = getCurrentEnvironmentId();- if (envId === LOCAL_DOCKER_ENVIRONMENT_ID) {- return '/api/images/pull';- }- return `/api/environments/${envId}/images/pull`;- }-async function handleSubmit() {const data = form.validate();if (!data) return;@@ -98,10 +90,11 @@}const fullImageName = `${imageName}:${imageTag}`;+ const envId = await environmentStore.getCurrentEnvironmentId();pullStatusText = `${m.images_pulling()} ${fullImageName}`;try {- const response = await fetch(buildApiUrl(fullImageName), {+ const response = await fetch(`/api/environments/${envId}/images/pull`, {method: 'POST',headers: {'Content-Type': 'application/json'diff --git a/frontend/src/lib/components/sheets/new-environment-sheet.svelte b/frontend/src/lib/components/sheets/new-environment-sheet.svelteindex 4e53605ba..554049cb8 100644--- a/frontend/src/lib/components/sheets/new-environment-sheet.svelte+++ b/frontend/src/lib/components/sheets/new-environment-sheet.svelte@@ -6,11 +6,11 @@import LoaderCircleIcon from '@lucide/svelte/icons/loader-circle';import ServerIcon from '@lucide/svelte/icons/server';import * as Card from '$lib/components/ui/card';- import { environmentManagementAPI } from '$lib/services/api';import type { CreateEnvironmentDTO } from '$lib/types/environment.type';import { z } from 'zod/v4';import { createForm, preventDefault } from '$lib/utils/form.utils';import { m } from '$lib/paraglide/messages';+ import { environmentManagementService } from '$lib/services/env-mgmt-service';type NewEnvironmentSheetProps = {open: boolean;@@ -48,10 +48,10 @@bootstrapToken: data.bootstrapToken};- const created = await environmentManagementAPI.create(dto);+ const created = await environmentManagementService.create(dto);try {- const result = await environmentManagementAPI.testConnection(created.id);+ const result = await environmentManagementService.testConnection(created.id);if (result.status === 'online') {toast.success(m.environments_test_connection_success());} else {diff --git a/frontend/src/lib/components/sheets/user-form-sheet.svelte b/frontend/src/lib/components/sheets/user-form-sheet.svelteindex f9c373c8b..c0e5f2827 100644--- a/frontend/src/lib/components/sheets/user-form-sheet.svelte+++ b/frontend/src/lib/components/sheets/user-form-sheet.svelte@@ -33,7 +33,6 @@let canEditUsername = $derived(!isEditMode || allowUsernameEdit);let SubmitIcon = $derived(isEditMode ? SaveIcon : UserPlusIcon);- // Disable most fields for OIDC userslet isOidcUser = $derived(!!userToEdit?.oidcSubjectId);const formSchema = z.object({diff --git a/frontend/src/lib/components/sidebar/sidebar-locale-picker.svelte b/frontend/src/lib/components/sidebar/sidebar-locale-picker.svelteindex a22c31263..ea21ce4b5 100644--- a/frontend/src/lib/components/sidebar/sidebar-locale-picker.svelte+++ b/frontend/src/lib/components/sidebar/sidebar-locale-picker.svelte@@ -4,10 +4,9 @@import { m } from '$lib/paraglide/messages';import userStore from '$lib/stores/user-store';import { setLocale } from '$lib/utils/locale.util';- import UserAPIService from '$lib/services/api/user-api-service';import { Label } from '$lib/components/ui/label/index.js';+ import { userService } from '$lib/services/user-service';- const userApi = new UserAPIService();const currentLocale = getLocale();const controlId = 'localePicker';@@ -22,7 +21,7 @@async function updateLocale(locale: Locale) {if ($userStore) {- await userApi.update($userStore.id, { ...$userStore, locale });+ await userService.update($userStore.id, { ...$userStore, locale });}await setLocale(locale);}diff --git a/frontend/src/lib/services/api/api-service.ts b/frontend/src/lib/services/api-service.tssimilarity index 100%rename from frontend/src/lib/services/api/api-service.tsrename to frontend/src/lib/services/api-service.tsdiff --git a/frontend/src/lib/services/api/converter-api-service.ts b/frontend/src/lib/services/api/converter-api-service.tsdeleted file mode 100644index f7bb670e9..000000000--- a/frontend/src/lib/services/api/converter-api-service.ts+++ /dev/null@@ -1,10 +0,0 @@-import BaseAPIService from './api-service';--export default class ConverterAPIService extends BaseAPIService {- async convert(dockerRunCommand: string) {- const res = await this.api.post('/convert', {- dockerRunCommand- });- return res.data;- }-}diff --git a/frontend/src/lib/services/api/environment-api-service.ts b/frontend/src/lib/services/api/environment-api-service.tsdeleted file mode 100644index b807b4c78..000000000--- a/frontend/src/lib/services/api/environment-api-service.ts+++ /dev/null@@ -1,371 +0,0 @@-import BaseAPIService from './api-service';-import { get } from 'svelte/store';-import { environmentStore, LOCAL_DOCKER_ENVIRONMENT_ID } from '$lib/stores/environment.store';-import type { ContainerCreateOptions, NetworkCreateOptions, VolumeCreateOptions, ContainerStats } from 'dockerode';-import type { Project, ProjectStatusCounts } from '$lib/types/project.type';-import type { SearchPaginationSortRequest, Paginated } from '$lib/types/pagination.type';-import type { ContainerStatusCounts, ContainerSummaryDto } from '$lib/types/container.type';-import type { ImageSummaryDto, ImageUpdateInfoDto, ImageUsageCounts } from '$lib/types/image.type';-import type { NetworkSummaryDto, NetworkUsageCounts } from '$lib/types/network.type';-import type { VolumeSummaryDto, VolumeDetailDto, VolumeUsageDto, VolumeUsageCounts } from '$lib/types/volume.type';-import type { AutoUpdateCheck, AutoUpdateResult } from '$lib/types/auto-update.type';-import type { DockerInfo } from '$lib/types/docker-info.type';--export class EnvironmentAPIService extends BaseAPIService {- private async getCurrentEnvironmentId(): Promise<string> {- await environmentStore.ready;-- const currentEnvironment = get(environmentStore.selected);- if (!currentEnvironment) {- return LOCAL_DOCKER_ENVIRONMENT_ID;- }- return currentEnvironment.id;- }-- // System Api Calls-- async getDockerInfo(): Promise<DockerInfo> {- const envId = await this.getCurrentEnvironmentId();- return this.handleResponse(this.api.get(`/environments/${envId}/docker/info`));- }-- // Container Api Calls-- async getContainers(options?: SearchPaginationSortRequest): Promise<Paginated<ContainerSummaryDto>> {- const envId = await this.getCurrentEnvironmentId();-- const res = await this.api.get(`/environments/${envId}/containers`, { params: options });- return res.data;- }-- async getContainerStatusCounts(): Promise<ContainerStatusCounts> {- const envId = await this.getCurrentEnvironmentId();-- const res = await this.api.get(`/environments/${envId}/containers/counts`);- return res.data.data;- }-- async getContainer(containerId: string): Promise<any> {- const envId = await this.getCurrentEnvironmentId();- return this.handleResponse(this.api.get(`/environments/${envId}/containers/${containerId}`));- }-- async startContainer(containerId: string): Promise<any> {- const envId = await this.getCurrentEnvironmentId();- return this.handleResponse(this.api.post(`/environments/${envId}/containers/${containerId}/start`));- }-- async createContainer(options: ContainerCreateOptions): Promise<any> {- const envId = await this.getCurrentEnvironmentId();- return this.handleResponse(this.api.post(`/environments/${envId}/containers`, options));- }-- async getContainerStats(containerId: string, stream: boolean = false): Promise<ContainerStats> {- const envId = await this.getCurrentEnvironmentId();- const url = `/environments/${envId}/containers/${containerId}/stats${stream ? '?stream=true' : ''}`;- return this.handleResponse(this.api.get(url)) as Promise<ContainerStats>;- }-- async stopContainer(containerId: string): Promise<any> {- const envId = await this.getCurrentEnvironmentId();- return this.handleResponse(this.api.post(`/environments/${envId}/containers/${containerId}/stop`));- }-- async restartContainer(containerId: string): Promise<any> {- const envId = await this.getCurrentEnvironmentId();- return this.handleResponse(this.api.post(`/environments/${envId}/containers/${containerId}/restart`));- }-- async deleteContainer(containerId: string, opts?: { force?: boolean; volumes?: boolean }): Promise<any> {- const envId = await this.getCurrentEnvironmentId();- const params: Record<string, string> = {};- if (opts?.force !== undefined) params.force = String(!!opts.force);- if (opts?.volumes !== undefined) params.volumes = String(!!opts.volumes);-- return this.handleResponse(this.api.delete(`/environments/${envId}/containers/${containerId}`, { params }));- }-- // End Container Api Calls-- // Image Api Calls-- async getImages(options?: SearchPaginationSortRequest): Promise<Paginated<ImageSummaryDto>> {- const envId = await this.getCurrentEnvironmentId();-- const res = await this.api.get(`/environments/${envId}/images`, { params: options });- return res.data;- }-- async getImageUsageCounts(): Promise<ImageUsageCounts> {- const envId = await this.getCurrentEnvironmentId();-- const res = await this.api.get(`/environments/${envId}/images/counts`);- return res.data.data;- }-- async getImage(imageId: string): Promise<any> {- const envId = await this.getCurrentEnvironmentId();- return this.handleResponse(this.api.get(`/environments/${envId}/images/${imageId}`));- }-- async pullImage(imageName: string, tag: string = 'latest', auth?: any): Promise<any> {- const envId = await this.getCurrentEnvironmentId();- return this.handleResponse(this.api.post(`/environments/${envId}/images/pull`, { imageName, tag, auth }));- }-- async deleteImage(imageId: string, options?: { force?: boolean; noprune?: boolean }): Promise<void> {- const envId = await this.getCurrentEnvironmentId();- await this.handleResponse(this.api.delete(`/environments/${envId}/images/${imageId}`, { params: options }));- }-- async pruneImages(dangling?: boolean): Promise<any> {- const envId = await this.getCurrentEnvironmentId();- const body = dangling !== undefined ? { dangling: !!dangling } : {};- return this.handleResponse(this.api.post(`/environments/${envId}/images/prune`, body));- }-- // End Image Api Calls-- // Network Api Calls-- async getNetworks(options?: SearchPaginationSortRequest): Promise<Paginated<NetworkSummaryDto>> {- const envId = await this.getCurrentEnvironmentId();-- const res = await this.api.get(`/environments/${envId}/networks`, { params: options });- return res.data;- }-- async getNetworkUsageCounts(): Promise<NetworkUsageCounts> {- const envId = await this.getCurrentEnvironmentId();-- const res = await this.api.get(`/environments/${envId}/networks/counts`);- return res.data.data;- }-- async getNetwork(networkId: string): Promise<any> {- const envId = await this.getCurrentEnvironmentId();- return this.handleResponse(this.api.get(`/environments/${envId}/networks/${networkId}`));- }-- async createNetwork(options: NetworkCreateOptions): Promise<any> {- const envId = await this.getCurrentEnvironmentId();- return this.handleResponse(this.api.post(`/environments/${envId}/networks`, options));- }-- async deleteNetwork(networkId: string): Promise<any> {- const envId = await this.getCurrentEnvironmentId();- return this.handleResponse(this.api.delete(`/environments/${envId}/networks/${networkId}`));- }-- // End Network Api Calls-- // Volume Api Calls-- async getVolumes(options?: SearchPaginationSortRequest): Promise<Paginated<VolumeSummaryDto>> {- const envId = await this.getCurrentEnvironmentId();-- const res = await this.api.get(`/environments/${envId}/volumes`, { params: options });- return res.data;- }-- async getVolume(volumeName: string): Promise<VolumeDetailDto> {- const envId = await this.getCurrentEnvironmentId();- return this.handleResponse(this.api.get(`/environments/${envId}/volumes/${volumeName}`)) as Promise<VolumeDetailDto>;- }-- async getVolumeUsage(volumeName: string): Promise<VolumeUsageDto> {- const envId = await this.getCurrentEnvironmentId();- return this.handleResponse(this.api.get(`/environments/${envId}/volumes/${volumeName}/usage`)) as Promise<VolumeUsageDto>;- }-- async getVolumeUsageCounts(): Promise<VolumeUsageCounts> {- const envId = await this.getCurrentEnvironmentId();-- const res = await this.api.get(`/environments/${envId}/volumes/counts`);- return res.data.data;- }-- async createVolume(options: VolumeCreateOptions): Promise<any> {- const envId = await this.getCurrentEnvironmentId();- return this.handleResponse(this.api.post(`/environments/${envId}/volumes`, options));- }-- async deleteVolume(volumeName: string): Promise<any> {- const envId = await this.getCurrentEnvironmentId();- return this.handleResponse(this.api.delete(`/environments/${envId}/volumes/${volumeName}`));- }-- // End Volume Api Calls-- // Image Updater Api Calls-- async checkImageUpdateByID(imageId: string): Promise<ImageUpdateInfoDto> {- const envId = await this.getCurrentEnvironmentId();- return this.handleResponse(this.api.get(`/environments/${envId}/image-updates/check/${imageId}`));- }-- async checkAllImages(): Promise<Record<string, ImageUpdateInfoDto>> {- const envId = await this.getCurrentEnvironmentId();- return this.handleResponse(this.api.get(`/environments/${envId}/image-updates/check-all`));- }-- async runAutoUpdate(options?: AutoUpdateCheck): Promise<AutoUpdateResult> {- const envId = await this.getCurrentEnvironmentId();- return this.handleResponse(this.api.post(`/environments/${envId}/updater/run`, options));- }-- // End Image Updater Api Calls-- // Project Api Calls-- async getProjects(options?: SearchPaginationSortRequest): Promise<Paginated<Project>> {- const envId = await this.getCurrentEnvironmentId();-- const res = await this.api.get(`/environments/${envId}/projects`, { params: options });- return res.data;- }-- async deployProject(projectId: string): Promise<Project> {- const envId = await this.getCurrentEnvironmentId();- return this.handleResponse(this.api.post(`/environments/${envId}/projects/${projectId}/up`));- }-- async downProject(projectName: string): Promise<Project> {- const envId = await this.getCurrentEnvironmentId();- return this.handleResponse(this.api.post(`/environments/${envId}/projects/${projectName}/down`));- }-- async createProject(projectName: string, composeContent: string, envContent?: string): Promise<Project> {- const envId = await this.getCurrentEnvironmentId();- const payload = {- name: projectName,- composeContent,- envContent- };- return this.handleResponse(this.api.post(`/environments/${envId}/projects`, payload));- }-- async getProject(projectId: string): Promise<Project> {- const envId = await this.getCurrentEnvironmentId();- const response = await this.handleResponse<{ project?: Project; success?: boolean }>(- this.api.get(`/environments/${envId}/projects/${projectId}`)- );-- return response.project ? response.project : (response as Project);- }-- async getProjectStatusCounts(): Promise<ProjectStatusCounts> {- const envId = await this.getCurrentEnvironmentId();-- const res = await this.api.get(`/environments/${envId}/projects/counts`);- return res.data.data;- }-- async updateProject(projectName: string, composeContent: string, envContent?: string): Promise<Project> {- const envId = await this.getCurrentEnvironmentId();- const payload = {- composeContent,- envContent- };- return this.handleResponse(this.api.put(`/environments/${envId}/projects/${projectName}`, payload));- }-- async restartProject(projectId: string): Promise<Project> {- const envId = await this.getCurrentEnvironmentId();- return this.handleResponse(this.api.post(`/environments/${envId}/projects/${projectId}/restart`));- }-- async redeployProject(projectName: string): Promise<Project> {- const envId = await this.getCurrentEnvironmentId();- return this.handleResponse(this.api.post(`/environments/${envId}/projects/${projectName}/redeploy`));- }-- private isDownloadingStatus(status?: string): boolean {- if (!status) return false;- const s = status.toLowerCase();- return (- s.includes('downloading') ||- s.includes('extracting') ||- s.includes('pull complete') ||- s.includes('download complete') ||- s.includes('pulling fs layer')- );- }-- private async streamProjectPull(projectId: string, onLine?: (data: any) => void): Promise<boolean> {- const envId = await this.getCurrentEnvironmentId();- const url = `/api/environments/${envId}/projects/${projectId}/pull`;-- const res = await fetch(url, { method: 'POST' });- if (!res.ok || !res.body) {- throw new Error(`Failed to start project image pull (${res.status})`);- }-- const reader = res.body.getReader();- const decoder = new TextDecoder();- let buffer = '';- let pulled = false;-- while (true) {- const { value, done } = await reader.read();- if (done) break;-- buffer += decoder.decode(value, { stream: true });- const lines = buffer.split('\n');- buffer = lines.pop() || '';-- for (const line of lines) {- const trimmed = line.trim();- if (!trimmed) continue;- try {- const obj = JSON.parse(trimmed);-- // Detect if any actual download happened- if (!pulled) {- const status = obj?.status as string | undefined;- const total = obj?.progressDetail?.total as number | undefined;- if (this.isDownloadingStatus(status) || (typeof total === 'number' && total > 0)) {- pulled = true;- }- }-- onLine?.(obj);- } catch {- // ignore malformed line- }- }- }- return pulled;- }-- pullProjectImages(projectId: string): Promise<void>;- pullProjectImages(projectId: string, onLine: (data: any) => void): Promise<void>;- async pullProjectImages(projectId: string, onLine?: (data: any) => void): Promise<void> {- await this.streamProjectPull(projectId, onLine);- }-- async deployProjectMaybePull(- projectId: string,- onPullLine?: (data: any) => void- ): Promise<{ pulled: boolean; project: Project }> {- const pulled = await this.streamProjectPull(projectId, onPullLine);- const project = await this.deployProject(projectId);- return { pulled, project };- }-- async destroyProject(projectName: string, removeVolumes = false, removeFiles = false): Promise<void> {- const envId = await this.getCurrentEnvironmentId();- await this.handleResponse(- this.api.delete(`/environments/${envId}/projects/${projectName}/destroy`, {- data: {- removeVolumes,- removeFiles- }- })- );- }-- //End New Project Api Calls-}--export const environmentAPI = new EnvironmentAPIService();diff --git a/frontend/src/lib/services/api/index.ts b/frontend/src/lib/services/api/index.tsdeleted file mode 100644index 512044727..000000000--- a/frontend/src/lib/services/api/index.ts+++ /dev/null@@ -1,49 +0,0 @@-import SystemAPIService from './system-api-service';-import TemplateAPIService from './template-api-service';-import UserAPIService from './user-api-service';-import SettingsAPIService from './settings-api-service';-import OidcAPIService from './oidc-api-service';-import ConverterAPIService from './converter-api-service';-import ContainerRegistryAPIService from './container-registry-api-service';-import { EnvironmentAPIService } from './environment-api-service';-import EnvironmentManagementAPIService from './environment-management-api-service';-import EventAPIService from './event-api-service';--export const systemAPI = new SystemAPIService();-export const templateAPI = new TemplateAPIService();-export const userAPI = new UserAPIService();-export const settingsAPI = new SettingsAPIService();-export const oidcAPI = new OidcAPIService();-export const converterAPI = new ConverterAPIService();-export const containerRegistryAPI = new ContainerRegistryAPIService();-export const environmentAPI = new EnvironmentAPIService();-export const environmentManagementAPI = new EnvironmentManagementAPIService();-export const eventAPI = new EventAPIService();--interface APIServices {- system: SystemAPIService;- template: TemplateAPIService;- user: UserAPIService;- settings: SettingsAPIService;- oidc: OidcAPIService;- converter: ConverterAPIService;- containerRegistry: ContainerRegistryAPIService;- environment: EnvironmentAPIService;- environmentManagement: EnvironmentManagementAPIService;- event: EventAPIService;-}--const apiServices: APIServices = {- system: systemAPI,- template: templateAPI,- user: userAPI,- settings: settingsAPI,- oidc: oidcAPI,- converter: converterAPI,- containerRegistry: containerRegistryAPI,- environment: environmentAPI,- environmentManagement: environmentManagementAPI,- event: eventAPI-};--export default apiServices;diff --git a/frontend/src/lib/services/api/oidc-api-service.ts b/frontend/src/lib/services/api/oidc-api-service.tsdeleted file mode 100644index 27bcaec42..000000000--- a/frontend/src/lib/services/api/oidc-api-service.ts+++ /dev/null@@ -1,39 +0,0 @@-import BaseAPIService from './api-service';-import type { OidcConfig, OidcStatusInfo } from '$lib/types/settings.type';--export interface OidcUserInfo {- sub: string;- email: string;- name?: string;- displayName?: string;- preferred_username?: string;- given_name?: string;- family_name?: string;- picture?: string;- groups?: string[];-}--export default class OidcAPIService extends BaseAPIService {- async getAuthUrl(redirectUri: string): Promise<string> {- const response = (await this.handleResponse(this.api.post('/oidc/url', { redirectUri }))) as {- authUrl: string;- };- return response.authUrl;- }-- async handleCallback(- code: string,- state: string- ): Promise<{- success: boolean;- token?: string;- user?: OidcUserInfo;- error?: string;- }> {- return this.handleResponse(this.api.post('/oidc/callback', { code, state }));- }-- async getStatus(): Promise<OidcStatusInfo> {- return this.handleResponse(this.api.get('/oidc/status'));- }-}diff --git a/frontend/src/lib/services/api/system-api-service.ts b/frontend/src/lib/services/api/system-api-service.tsdeleted file mode 100644index 2b95d4cb0..000000000--- a/frontend/src/lib/services/api/system-api-service.ts+++ /dev/null@@ -1,28 +0,0 @@-import type { DockerInfo } from '$lib/types/docker-info.type';-import BaseAPIService from './api-service';--export default class SystemAPIService extends BaseAPIService {- async pruneAll(options: {- containers?: boolean;- images?: boolean;- volumes?: boolean;- networks?: boolean;- buildCache?: boolean;- dangling?: boolean;- until?: string;- }) {- return this.handleResponse(this.api.post('/system/prune', options));- }-- async startAllStoppedContainers() {- return this.handleResponse(this.api.post('/system/containers/start-stopped'));- }-- async stopAllContainers() {- return this.handleResponse(this.api.post('/system/containers/stop-all'));- }-- async getDockerInfo(): Promise<DockerInfo> {- return this.handleResponse(this.api.get('/system/docker/info'));- }-}diff --git a/frontend/src/lib/services/api/auth-api-service.ts b/frontend/src/lib/services/auth-service.tssimilarity index 56%rename from frontend/src/lib/services/api/auth-api-service.tsrename to frontend/src/lib/services/auth-service.tsindex f80b7f4fa..0c7a69e4b 100644--- a/frontend/src/lib/services/api/auth-api-service.ts+++ b/frontend/src/lib/services/auth-service.ts@@ -3,19 +3,8 @@ import { invalidateAll } from '$app/navigation';import BaseAPIService from './api-service';import userStore from '$lib/stores/user-store';import type { User } from '$lib/types/user.type';--export interface LoginCredentials {- username: string;- password: string;-}--type LoginResponseData = {- token: string;- refreshToken: string;- expiresAt: string;- user: User;- requirePasswordChange?: boolean;-};+import type { OidcStatusInfo } from '$lib/types/settings.type';+import type { OidcUserInfo, LoginCredentials, LoginResponseData } from '$lib/types/auth.type';export class AuthService extends BaseAPIService {async login(credentials: LoginCredentials): Promise<User> {@@ -38,11 +27,33 @@ export class AuthService extends BaseAPIService {return user;} catch {- // Clear user from store on erroruserStore.clearUser();return null;}}++ async getAuthUrl(redirectUri: string): Promise<string> {+ const response = (await this.handleResponse(this.api.post('/oidc/url', { redirectUri }))) as {+ authUrl: string;+ };+ return response.authUrl;+ }++ async handleCallback(+ code: string,+ state: string+ ): Promise<{+ success: boolean;+ token?: string;+ user?: OidcUserInfo;+ error?: string;+ }> {+ return this.handleResponse(this.api.post('/oidc/callback', { code, state }));+ }++ async getStatus(): Promise<OidcStatusInfo> {+ return this.handleResponse(this.api.get('/oidc/status'));+ }}export const authService = new AuthService();diff --git a/frontend/src/lib/services/api/container-registry-api-service.ts b/frontend/src/lib/services/container-registry-service.tssimilarity index 90%rename from frontend/src/lib/services/api/container-registry-api-service.tsrename to frontend/src/lib/services/container-registry-service.tsindex dd1ad8698..b84af9662 100644--- a/frontend/src/lib/services/api/container-registry-api-service.ts+++ b/frontend/src/lib/services/container-registry-service.ts@@ -3,7 +3,7 @@ import type { ContainerRegistryCreateDto, ContainerRegistryUpdateDto } from '$liimport type { ContainerRegistry } from '$lib/types/container-registry.type';import type { Paginated, SearchPaginationSortRequest } from '$lib/types/pagination.type';-export default class ContainerRegistryAPIService extends BaseAPIService {+export default class ContainerRegistryService extends BaseAPIService {async getRegistries(options?: SearchPaginationSortRequest): Promise<Paginated<ContainerRegistry>> {const res = await this.api.get('/container-registries', { params: options });return res.data;@@ -29,3 +29,5 @@ export default class ContainerRegistryAPIService extends BaseAPIService {return this.handleResponse(this.api.post(`/container-registries/${id}/test`));}}++export const containerRegistryService = new ContainerRegistryService();diff --git a/frontend/src/lib/services/container-service.ts b/frontend/src/lib/services/container-service.tsnew file mode 100644index 000000000..997dab2c7--- /dev/null+++ b/frontend/src/lib/services/container-service.ts@@ -0,0 +1,65 @@+import BaseAPIService from './api-service';+import { environmentStore } from '$lib/stores/environment.store';+import type { ContainerStatusCounts, ContainerSummaryDto } from '$lib/types/container.type';+import type { SearchPaginationSortRequest, Paginated } from '$lib/types/pagination.type';++// Would like to get rid of dockerode+import type { ContainerCreateOptions, ContainerStats } from 'dockerode';++export class ContainerService extends BaseAPIService {+ async getContainers(options?: SearchPaginationSortRequest): Promise<Paginated<ContainerSummaryDto>> {+ const envId = await environmentStore.getCurrentEnvironmentId();++ const res = await this.api.get(`/environments/${envId}/containers`, { params: options });+ return res.data;+ }++ async getContainerStatusCounts(): Promise<ContainerStatusCounts> {+ const envId = await environmentStore.getCurrentEnvironmentId();++ const res = await this.api.get(`/environments/${envId}/containers/counts`);+ return res.data.data;+ }++ async getContainer(containerId: string): Promise<any> {+ const envId = await environmentStore.getCurrentEnvironmentId();+ return this.handleResponse(this.api.get(`/environments/${envId}/containers/${containerId}`));+ }++ async startContainer(containerId: string): Promise<any> {+ const envId = await environmentStore.getCurrentEnvironmentId();+ return this.handleResponse(this.api.post(`/environments/${envId}/containers/${containerId}/start`));+ }++ async createContainer(options: ContainerCreateOptions): Promise<any> {+ const envId = await environmentStore.getCurrentEnvironmentId();+ return this.handleResponse(this.api.post(`/environments/${envId}/containers`, options));+ }++ async getContainerStats(containerId: string, stream: boolean = false): Promise<ContainerStats> {+ const envId = await environmentStore.getCurrentEnvironmentId();+ const url = `/environments/${envId}/containers/${containerId}/stats${stream ? '?stream=true' : ''}`;+ return this.handleResponse(this.api.get(url)) as Promise<ContainerStats>;+ }++ async stopContainer(containerId: string): Promise<any> {+ const envId = await environmentStore.getCurrentEnvironmentId();+ return this.handleResponse(this.api.post(`/environments/${envId}/containers/${containerId}/stop`));+ }++ async restartContainer(containerId: string): Promise<any> {+ const envId = await environmentStore.getCurrentEnvironmentId();+ return this.handleResponse(this.api.post(`/environments/${envId}/containers/${containerId}/restart`));+ }++ async deleteContainer(containerId: string, opts?: { force?: boolean; volumes?: boolean }): Promise<any> {+ const envId = await environmentStore.getCurrentEnvironmentId();+ const params: Record<string, string> = {};+ if (opts?.force !== undefined) params.force = String(!!opts.force);+ if (opts?.volumes !== undefined) params.volumes = String(!!opts.volumes);++ return this.handleResponse(this.api.delete(`/environments/${envId}/containers/${containerId}`, { params }));+ }+}++export const containerService = new ContainerService();diff --git a/frontend/src/lib/services/api/environment-management-api-service.ts b/frontend/src/lib/services/env-mgmt-service.tssimilarity index 90%rename from frontend/src/lib/services/api/environment-management-api-service.tsrename to frontend/src/lib/services/env-mgmt-service.tsindex b982130d8..9cc0b390d 100644--- a/frontend/src/lib/services/api/environment-management-api-service.ts+++ b/frontend/src/lib/services/env-mgmt-service.ts@@ -3,7 +3,7 @@ import type { Environment } from '$lib/types/environment.type';import type { CreateEnvironmentDTO, UpdateEnvironmentDTO } from '$lib/types/environment.type';import type { Paginated, SearchPaginationSortRequest } from '$lib/types/pagination.type';-export default class EnvironmentManagementAPIService extends BaseAPIService {+export default class EnvironmentManagementService extends BaseAPIService {async create(dto: CreateEnvironmentDTO): Promise<Environment> {const res = await this.api.post('/environments', dto);return res.data.data as Environment;@@ -33,3 +33,5 @@ export default class EnvironmentManagementAPIService extends BaseAPIService {return res.data.data as { status: 'online' | 'offline'; message?: string };}}++export const environmentManagementService = new EnvironmentManagementService();diff --git a/frontend/src/lib/services/api/event-api-service.ts b/frontend/src/lib/services/event-service.tssimilarity index 81%rename from frontend/src/lib/services/api/event-api-service.tsrename to frontend/src/lib/services/event-service.tsindex d33074ea2..2cbf3e81a 100644--- a/frontend/src/lib/services/api/event-api-service.ts+++ b/frontend/src/lib/services/event-service.ts@@ -2,7 +2,7 @@ import BaseAPIService from './api-service';import type { SearchPaginationSortRequest, Paginated } from '$lib/types/pagination.type';import type { Event } from '$lib/types/event.type';-export default class EventAPIService extends BaseAPIService {+export default class EventService extends BaseAPIService {async getEvents(options?: SearchPaginationSortRequest): Promise<Paginated<Event>> {const res = await this.api.get('/events', { params: options });return res.data;@@ -12,3 +12,5 @@ export default class EventAPIService extends BaseAPIService {return this.handleResponse(this.api.delete(`/events/${id}`));}}++export const eventService = new EventService();diff --git a/frontend/src/lib/services/image-service.ts b/frontend/src/lib/services/image-service.tsnew file mode 100644index 000000000..79367eb2a--- /dev/null+++ b/frontend/src/lib/services/image-service.ts@@ -0,0 +1,59 @@+import BaseAPIService from './api-service';+import { environmentStore } from '$lib/stores/environment.store';+import type { ImageSummaryDto, ImageUsageCounts, ImageUpdateInfoDto } from '$lib/types/image.type';+import type { SearchPaginationSortRequest, Paginated } from '$lib/types/pagination.type';+import type { AutoUpdateCheck, AutoUpdateResult } from '$lib/types/auto-update.type';++export class ImageService extends BaseAPIService {+ async getImages(options?: SearchPaginationSortRequest): Promise<Paginated<ImageSummaryDto>> {+ const envId = await environmentStore.getCurrentEnvironmentId();++ const res = await this.api.get(`/environments/${envId}/images`, { params: options });+ return res.data;+ }++ async getImageUsageCounts(): Promise<ImageUsageCounts> {+ const envId = await environmentStore.getCurrentEnvironmentId();++ const res = await this.api.get(`/environments/${envId}/images/counts`);+ return res.data.data;+ }++ async getImage(imageId: string): Promise<any> {+ const envId = await environmentStore.getCurrentEnvironmentId();+ return this.handleResponse(this.api.get(`/environments/${envId}/images/${imageId}`));+ }++ async pullImage(imageName: string, tag: string = 'latest', auth?: any): Promise<any> {+ const envId = await environmentStore.getCurrentEnvironmentId();+ return this.handleResponse(this.api.post(`/environments/${envId}/images/pull`, { imageName, tag, auth }));+ }++ async deleteImage(imageId: string, options?: { force?: boolean; noprune?: boolean }): Promise<void> {+ const envId = await environmentStore.getCurrentEnvironmentId();+ await this.handleResponse(this.api.delete(`/environments/${envId}/images/${imageId}`, { params: options }));+ }++ async pruneImages(dangling?: boolean): Promise<any> {+ const envId = await environmentStore.getCurrentEnvironmentId();+ const body = dangling !== undefined ? { dangling: !!dangling } : {};+ return this.handleResponse(this.api.post(`/environments/${envId}/images/prune`, body));+ }++ async checkImageUpdateByID(imageId: string): Promise<ImageUpdateInfoDto> {+ const envId = await environmentStore.getCurrentEnvironmentId();+ return this.handleResponse(this.api.get(`/environments/${envId}/image-updates/check/${imageId}`));+ }++ async checkAllImages(): Promise<Record<string, ImageUpdateInfoDto>> {+ const envId = await environmentStore.getCurrentEnvironmentId();+ return this.handleResponse(this.api.get(`/environments/${envId}/image-updates/check-all`));+ }++ async runAutoUpdate(options?: AutoUpdateCheck): Promise<AutoUpdateResult> {+ const envId = await environmentStore.getCurrentEnvironmentId();+ return this.handleResponse(this.api.post(`/environments/${envId}/updater/run`, options));+ }+}++export const imageService = new ImageService();diff --git a/frontend/src/lib/services/network-service.ts b/frontend/src/lib/services/network-service.tsnew file mode 100644index 000000000..596c9718a--- /dev/null+++ b/frontend/src/lib/services/network-service.ts@@ -0,0 +1,38 @@+import BaseAPIService from './api-service';+import { environmentStore } from '$lib/stores/environment.store';+import type { NetworkSummaryDto, NetworkUsageCounts } from '$lib/types/network.type';+import type { SearchPaginationSortRequest, Paginated } from '$lib/types/pagination.type';+import type { NetworkCreateOptions } from 'dockerode';++export class NetworkService extends BaseAPIService {+ async getNetworks(options?: SearchPaginationSortRequest): Promise<Paginated<NetworkSummaryDto>> {+ const envId = await environmentStore.getCurrentEnvironmentId();++ const res = await this.api.get(`/environments/${envId}/networks`, { params: options });+ return res.data;+ }++ async getNetworkUsageCounts(): Promise<NetworkUsageCounts> {+ const envId = await environmentStore.getCurrentEnvironmentId();++ const res = await this.api.get(`/environments/${envId}/networks/counts`);+ return res.data.data;+ }++ async getNetwork(networkId: string): Promise<any> {+ const envId = await environmentStore.getCurrentEnvironmentId();+ return this.handleResponse(this.api.get(`/environments/${envId}/networks/${networkId}`));+ }++ async createNetwork(options: NetworkCreateOptions): Promise<any> {+ const envId = await environmentStore.getCurrentEnvironmentId();+ return this.handleResponse(this.api.post(`/environments/${envId}/networks`, options));+ }++ async deleteNetwork(networkId: string): Promise<any> {+ const envId = await environmentStore.getCurrentEnvironmentId();+ return this.handleResponse(this.api.delete(`/environments/${envId}/networks/${networkId}`));+ }+}++export const networkService = new NetworkService();diff --git a/frontend/src/lib/services/project-service.ts b/frontend/src/lib/services/project-service.tsnew file mode 100644index 000000000..68c54ec2b--- /dev/null+++ b/frontend/src/lib/services/project-service.ts@@ -0,0 +1,155 @@+import BaseAPIService from './api-service';+import { environmentStore } from '$lib/stores/environment.store';+import type { Project, ProjectStatusCounts } from '$lib/types/project.type';+import type { SearchPaginationSortRequest, Paginated } from '$lib/types/pagination.type';++export class ProjectService extends BaseAPIService {+ async getProjects(options?: SearchPaginationSortRequest): Promise<Paginated<Project>> {+ const envId = await environmentStore.getCurrentEnvironmentId();++ const res = await this.api.get(`/environments/${envId}/projects`, { params: options });+ return res.data;+ }++ async deployProject(projectId: string): Promise<Project> {+ const envId = await environmentStore.getCurrentEnvironmentId();+ return this.handleResponse(this.api.post(`/environments/${envId}/projects/${projectId}/up`));+ }++ async downProject(projectName: string): Promise<Project> {+ const envId = await environmentStore.getCurrentEnvironmentId();+ return this.handleResponse(this.api.post(`/environments/${envId}/projects/${projectName}/down`));+ }++ async createProject(projectName: string, composeContent: string, envContent?: string): Promise<Project> {+ const envId = await environmentStore.getCurrentEnvironmentId();+ const payload = {+ name: projectName,+ composeContent,+ envContent+ };+ return this.handleResponse(this.api.post(`/environments/${envId}/projects`, payload));+ }++ async getProject(projectId: string): Promise<Project> {+ const envId = await environmentStore.getCurrentEnvironmentId();+ const response = await this.handleResponse<{ project?: Project; success?: boolean }>(+ this.api.get(`/environments/${envId}/projects/${projectId}`)+ );++ return response.project ? response.project : (response as Project);+ }++ async getProjectStatusCounts(): Promise<ProjectStatusCounts> {+ const envId = await environmentStore.getCurrentEnvironmentId();++ const res = await this.api.get(`/environments/${envId}/projects/counts`);+ return res.data.data;+ }++ async updateProject(projectName: string, composeContent: string, envContent?: string): Promise<Project> {+ const envId = await environmentStore.getCurrentEnvironmentId();+ const payload = {+ composeContent,+ envContent+ };+ return this.handleResponse(this.api.put(`/environments/${envId}/projects/${projectName}`, payload));+ }++ async restartProject(projectId: string): Promise<Project> {+ const envId = await environmentStore.getCurrentEnvironmentId();+ return this.handleResponse(this.api.post(`/environments/${envId}/projects/${projectId}/restart`));+ }++ async redeployProject(projectName: string): Promise<Project> {+ const envId = await environmentStore.getCurrentEnvironmentId();+ return this.handleResponse(this.api.post(`/environments/${envId}/projects/${projectName}/redeploy`));+ }++ private isDownloadingStatus(status?: string): boolean {+ if (!status) return false;+ const s = status.toLowerCase();+ return (+ s.includes('downloading') ||+ s.includes('extracting') ||+ s.includes('pull complete') ||+ s.includes('download complete') ||+ s.includes('pulling fs layer')+ );+ }++ private async streamProjectPull(projectId: string, onLine?: (data: any) => void): Promise<boolean> {+ const envId = await environmentStore.getCurrentEnvironmentId();+ const url = `/api/environments/${envId}/projects/${projectId}/pull`;++ const res = await fetch(url, { method: 'POST' });+ if (!res.ok || !res.body) {+ throw new Error(`Failed to start project image pull (${res.status})`);+ }++ const reader = res.body.getReader();+ const decoder = new TextDecoder();+ let buffer = '';+ let pulled = false;++ while (true) {+ const { value, done } = await reader.read();+ if (done) break;++ buffer += decoder.decode(value, { stream: true });+ const lines = buffer.split('\n');+ buffer = lines.pop() || '';++ for (const line of lines) {+ const trimmed = line.trim();+ if (!trimmed) continue;+ try {+ const obj = JSON.parse(trimmed);++ // Detect if any actual download happened+ if (!pulled) {+ const status = obj?.status as string | undefined;+ const total = obj?.progressDetail?.total as number | undefined;+ if (this.isDownloadingStatus(status) || (typeof total === 'number' && total > 0)) {+ pulled = true;+ }+ }++ onLine?.(obj);+ } catch {+ // ignore malformed line+ }+ }+ }+ return pulled;+ }++ pullProjectImages(projectId: string): Promise<void>;+ pullProjectImages(projectId: string, onLine: (data: any) => void): Promise<void>;+ async pullProjectImages(projectId: string, onLine?: (data: any) => void): Promise<void> {+ await this.streamProjectPull(projectId, onLine);+ }++ async deployProjectMaybePull(+ projectId: string,+ onPullLine?: (data: any) => void+ ): Promise<{ pulled: boolean; project: Project }> {+ const pulled = await this.streamProjectPull(projectId, onPullLine);+ const project = await this.deployProject(projectId);+ return { pulled, project };+ }++ async destroyProject(projectName: string, removeVolumes = false, removeFiles = false): Promise<void> {+ const envId = await environmentStore.getCurrentEnvironmentId();+ await this.handleResponse(+ this.api.delete(`/environments/${envId}/projects/${projectName}/destroy`, {+ data: {+ removeVolumes,+ removeFiles+ }+ })+ );+ }+}++export const projectService = new ProjectService();diff --git a/frontend/src/lib/services/api/settings-api-service.ts b/frontend/src/lib/services/settings-service.tssimilarity index 90%rename from frontend/src/lib/services/api/settings-api-service.tsrename to frontend/src/lib/services/settings-service.tsindex 640961e6c..633f7d510 100644--- a/frontend/src/lib/services/api/settings-api-service.ts+++ b/frontend/src/lib/services/settings-service.ts@@ -1,9 +1,9 @@import BaseAPIService from './api-service';-import type { Settings, SettingRawResponse, OidcStatusInfo } from '$lib/types/settings.type';+import type { Settings, OidcStatusInfo } from '$lib/types/settings.type';type KeyValuePair = { key: string; value: string };-export default class SettingsAPIService extends BaseAPIService {+export default class SettingsService extends BaseAPIService {async getSettings(): Promise<Settings> {const res = await this.api.get('/settings');return this.normalize(res.data);@@ -59,3 +59,5 @@ export default class SettingsAPIService extends BaseAPIService {return value;}}++export const settingsService = new SettingsService();diff --git a/frontend/src/lib/services/system-service.ts b/frontend/src/lib/services/system-service.tsnew file mode 100644index 000000000..42a4d2b56--- /dev/null+++ b/frontend/src/lib/services/system-service.ts@@ -0,0 +1,43 @@+import BaseAPIService from './api-service';+import { environmentStore } from '$lib/stores/environment.store';+import type { DockerInfo } from '$lib/types/docker-info.type';++export class SystemService extends BaseAPIService {+ async pruneAll(options: {+ containers?: boolean;+ images?: boolean;+ volumes?: boolean;+ networks?: boolean;+ buildCache?: boolean;+ dangling?: boolean;+ until?: string;+ }) {+ const envId = await environmentStore.getCurrentEnvironmentId();+ return this.handleResponse(this.api.post(`/environments/${envId}/system/prune`, options));+ }++ async startAllStoppedContainers() {+ const envId = await environmentStore.getCurrentEnvironmentId();+ return this.handleResponse(this.api.post(`/environments/${envId}/system/containers/start-stopped`));+ }++ async stopAllContainers() {+ const envId = await environmentStore.getCurrentEnvironmentId();+ return this.handleResponse(this.api.post(`/environments/${envId}/system/containers/stop-all`));+ }++ async getDockerInfo(): Promise<DockerInfo> {+ const envId = await environmentStore.getCurrentEnvironmentId();+ return this.handleResponse(this.api.get(`/environments/${envId}/system/docker/info`));+ }++ async convert(dockerRunCommand: string) {+ const envId = await environmentStore.getCurrentEnvironmentId();+ const res = await this.api.post(`/environments/${envId}/system/convert`, {+ dockerRunCommand+ });+ return res.data;+ }+}++export const systemService = new SystemService();diff --git a/frontend/src/lib/services/api/template-api-service.ts b/frontend/src/lib/services/template-service.tssimilarity index 95%rename from frontend/src/lib/services/api/template-api-service.tsrename to frontend/src/lib/services/template-service.tsindex 6bc6659cb..b1fd04fba 100644--- a/frontend/src/lib/services/api/template-api-service.ts+++ b/frontend/src/lib/services/template-service.ts@@ -1,7 +1,7 @@import BaseAPIService from './api-service';import type { TemplateRegistry, Template, RemoteRegistry } from '$lib/types/template.type';-export default class TemplateAPIService extends BaseAPIService {+export default class TemplateService extends BaseAPIService {async loadAll(): Promise<Template[]> {const response = await this.api.get('/templates');return response.data?.data ?? [];@@ -72,3 +72,5 @@ export default class TemplateAPIService extends BaseAPIService {await this.api.delete(`/templates/registries/${id}`);}}++export const templateService = new TemplateService();diff --git a/frontend/src/lib/services/api/user-api-service.ts b/frontend/src/lib/services/user-service.tssimilarity index 96%rename from frontend/src/lib/services/api/user-api-service.tsrename to frontend/src/lib/services/user-service.tsindex 77a513bbc..63e93239d 100644--- a/frontend/src/lib/services/api/user-api-service.ts+++ b/frontend/src/lib/services/user-service.ts@@ -32,3 +32,5 @@ export default class UserAPIService extends BaseAPIService {return this.handleResponse(this.api.post('/auth/password', data)) as Promise<void>;}}++export const userService = new UserAPIService();diff --git a/frontend/src/lib/services/volume-service.ts b/frontend/src/lib/services/volume-service.tsnew file mode 100644index 000000000..dd0e2254a--- /dev/null+++ b/frontend/src/lib/services/volume-service.ts@@ -0,0 +1,43 @@+import BaseAPIService from './api-service';+import { environmentStore } from '$lib/stores/environment.store';+import type { VolumeSummaryDto, VolumeDetailDto, VolumeUsageDto, VolumeUsageCounts } from '$lib/types/volume.type';+import type { SearchPaginationSortRequest, Paginated } from '$lib/types/pagination.type';+import type { VolumeCreateOptions } from 'dockerode';++export class VolumeService extends BaseAPIService {+ async getVolumes(options?: SearchPaginationSortRequest): Promise<Paginated<VolumeSummaryDto>> {+ const envId = await environmentStore.getCurrentEnvironmentId();++ const res = await this.api.get(`/environments/${envId}/volumes`, { params: options });+ return res.data;+ }++ async getVolume(volumeName: string): Promise<VolumeDetailDto> {+ const envId = await environmentStore.getCurrentEnvironmentId();+ return this.handleResponse(this.api.get(`/environments/${envId}/volumes/${volumeName}`)) as Promise<VolumeDetailDto>;+ }++ async getVolumeUsage(volumeName: string): Promise<VolumeUsageDto> {+ const envId = await environmentStore.getCurrentEnvironmentId();+ return this.handleResponse(this.api.get(`/environments/${envId}/volumes/${volumeName}/usage`)) as Promise<VolumeUsageDto>;+ }++ async getVolumeUsageCounts(): Promise<VolumeUsageCounts> {+ const envId = await environmentStore.getCurrentEnvironmentId();++ const res = await this.api.get(`/environments/${envId}/volumes/counts`);+ return res.data.data;+ }++ async createVolume(options: VolumeCreateOptions): Promise<any> {+ const envId = await environmentStore.getCurrentEnvironmentId();+ return this.handleResponse(this.api.post(`/environments/${envId}/volumes`, options));+ }++ async deleteVolume(volumeName: string): Promise<any> {+ const envId = await environmentStore.getCurrentEnvironmentId();+ return this.handleResponse(this.api.delete(`/environments/${envId}/volumes/${volumeName}`));+ }+}++export const volumeService = new VolumeService();diff --git a/frontend/src/lib/stores/config-store.ts b/frontend/src/lib/stores/config-store.tsindex 876e55748..b13c1ed63 100644--- a/frontend/src/lib/stores/config-store.ts+++ b/frontend/src/lib/stores/config-store.ts@@ -1,11 +1,11 @@-import { settingsAPI } from '$lib/services/api';+import { settingsService } from '$lib/services/settings-service';import type { Settings } from '$lib/types/settings.type';import { writable } from 'svelte/store';const settingsStore = writable<Settings>();const reload = async () => {- const settings = await settingsAPI.getSettings();+ const settings = await settingsService.getSettings();settingsStore.set(settings);};diff --git a/frontend/src/lib/stores/environment.store.ts b/frontend/src/lib/stores/environment.store.tsindex b209b4960..aa6d0c5f7 100644--- a/frontend/src/lib/stores/environment.store.ts+++ b/frontend/src/lib/stores/environment.store.ts@@ -107,7 +107,12 @@ function createEnvironmentManagementStore() {},isInitialized: () => _initialized,getLocalEnvironment: () => localDockerEnvironment,- ready: _readyPromise+ ready: _readyPromise,+ getCurrentEnvironmentId: async (): Promise<string> => {+ await _readyPromise;+ const current = get(_selectedEnvironment);+ return current ? current.id : LOCAL_DOCKER_ENVIRONMENT_ID;+ }};}diff --git a/frontend/src/lib/types/auth.type.ts b/frontend/src/lib/types/auth.type.tsnew file mode 100644index 000000000..1806c6d22--- /dev/null+++ b/frontend/src/lib/types/auth.type.ts@@ -0,0 +1,26 @@+import type { User } from '$lib/types/user.type';++export interface OidcUserInfo {+ sub: string;+ email: string;+ name?: string;+ displayName?: string;+ preferred_username?: string;+ given_name?: string;+ family_name?: string;+ picture?: string;+ groups?: string[];+}++export interface LoginCredentials {+ username: string;+ password: string;+}++export type LoginResponseData = {+ token: string;+ refreshToken: string;+ expiresAt: string;+ user: User;+ requirePasswordChange?: boolean;+};diff --git a/frontend/src/lib/utils/ws.ts b/frontend/src/lib/utils/ws.tsindex 5871edef8..fb3603695 100644--- a/frontend/src/lib/utils/ws.ts+++ b/frontend/src/lib/utils/ws.ts@@ -137,7 +137,7 @@ export function createStatsWebSocket(opts: {const buildUrl = () => {const envId = opts.getEnvId() || '0';const protocol = location.protocol === 'https:' ? 'wss' : 'ws';- return `${protocol}://${location.host}/api/environments/${envId}/stats/ws`;+ return `${protocol}://${location.host}/api/environments/${envId}/system/stats/ws`;};return new ReconnectingWebSocket<SystemStats>({diff --git a/frontend/src/routes/+layout.ts b/frontend/src/routes/+layout.tsindex 07491f9d7..d27c46328 100644--- a/frontend/src/routes/+layout.ts+++ b/frontend/src/routes/+layout.ts@@ -1,4 +1,3 @@-import { settingsAPI, userAPI, environmentManagementAPI } from '$lib/services/api';import { environmentStore } from '$lib/stores/environment.store';import versionService from '$lib/services/version-service';import { tryCatch } from '$lib/utils/try-catch';@@ -6,14 +5,17 @@ import userStore from '$lib/stores/user-store';import settingsStore from '$lib/stores/config-store';import type { SearchPaginationSortRequest } from '$lib/types/pagination.type';import type { AppVersionInformation } from '$lib/types/application-configuration';+import { userService } from '$lib/services/user-service';+import { settingsService } from '$lib/services/settings-service';+import { environmentManagementService } from '$lib/services/env-mgmt-service';export const ssr = false;export const load = async () => {- const userPromise = userAPI.getCurrentUser().catch(() => null);- const settingsPromise = settingsAPI.getSettings().catch((e) => {+ const userPromise = userService.getCurrentUser().catch(() => null);+ const settingsPromise = settingsService.getSettings().catch((e) => {console.error('Error fetching settings:', e);- return settingsAPI.getPublicSettings().catch(() => null);+ return settingsService.getPublicSettings().catch(() => null);});const environmentRequestOptions: SearchPaginationSortRequest = {@@ -25,7 +27,7 @@ export const load = async () => {const environmentsPromise = userPromise.then(async (user) => {if (!environmentStore.isInitialized() && user) {- const environments = await tryCatch(environmentManagementAPI.getEnvironments(environmentRequestOptions));+ const environments = await tryCatch(environmentManagementService.getEnvironments(environmentRequestOptions));if (!environments.error) {await environmentStore.initialize(environments.data.data, true);}diff --git a/frontend/src/routes/auth/login/+page.svelte b/frontend/src/routes/auth/login/+page.svelteindex 9ad2a41fe..9a62bc743 100644--- a/frontend/src/routes/auth/login/+page.svelte+++ b/frontend/src/routes/auth/login/+page.svelte@@ -9,13 +9,12 @@import LockIcon from '@lucide/svelte/icons/lock';import UserIcon from '@lucide/svelte/icons/user';import type { PageData } from './$types';- import { goto, invalidateAll } from '$app/navigation';- import { settingsAPI } from '$lib/services/api';- import { authService } from '$lib/services/api/auth-api-service';- import { toast } from 'svelte-sonner';+ import { goto } from '$app/navigation';import userStore from '$lib/stores/user-store';import settingsStore from '$lib/stores/config-store';import { m } from '$lib/paraglide/messages';+ import { settingsService } from '$lib/services/settings-service';+ import { authService } from '$lib/services/auth-service';let { data }: { data: PageData } = $props();@@ -50,7 +49,7 @@const user = await authService.login({ username, password });userStore.setUser(user);// Load settings to determine onboarding redirect- const settings = await settingsAPI.getSettings();+ const settings = await settingsService.getSettings();settingsStore.set(settings);const redirectTo = data.redirectTo || '/dashboard';goto(!settings.onboardingCompleted ? '/onboarding/welcome' : redirectTo, { replaceState: true });diff --git a/frontend/src/routes/auth/login/+page.ts b/frontend/src/routes/auth/login/+page.tsindex 3b20789cb..eb65e1261 100644--- a/frontend/src/routes/auth/login/+page.ts+++ b/frontend/src/routes/auth/login/+page.ts@@ -7,10 +7,8 @@ export const load = async ({ parent, url }) => {throw redirect(302, '/dashboard');}- // Get redirect parameter from URLconst redirectTo = url.searchParams.get('redirect') || '/dashboard';- // Get error parameter if anyconst error = url.searchParams.get('error');return {diff --git a/frontend/src/routes/auth/logout/+page.ts b/frontend/src/routes/auth/logout/+page.tsindex bd1997881..706c39582 100644--- a/frontend/src/routes/auth/logout/+page.ts+++ b/frontend/src/routes/auth/logout/+page.ts@@ -1,5 +1,4 @@import { redirect } from '@sveltejs/kit';-import { browser } from '$app/environment';import type { PageLoad } from './$types';export const load: PageLoad = async ({ fetch }) => {diff --git a/frontend/src/routes/auth/oidc/callback/+page.svelte b/frontend/src/routes/auth/oidc/callback/+page.svelteindex b724aa3b0..c74fbcaf2 100644--- a/frontend/src/routes/auth/oidc/callback/+page.svelte+++ b/frontend/src/routes/auth/oidc/callback/+page.svelte@@ -2,13 +2,13 @@import { onMount } from 'svelte';import { goto, invalidateAll } from '$app/navigation';import { page } from '$app/state';- import { oidcAPI } from '$lib/services/api';import { toast } from 'svelte-sonner';import userStore from '$lib/stores/user-store';import type { User } from '$lib/types/user.type';import { m } from '$lib/paraglide/messages';- import { settingsAPI } from '$lib/services/api';import settingsStore from '$lib/stores/config-store';+ import { settingsService } from '$lib/services/settings-service';+ import { authService } from '$lib/services/auth-service';let isProcessing = $state(true);let error = $state('');@@ -44,7 +44,7 @@return;}- const authResult = await oidcAPI.handleCallback(code, stateFromUrl);+ const authResult = await authService.handleCallback(code, stateFromUrl);if (!authResult.success) {let userMessage = m.auth_oidc_auth_failed();@@ -79,7 +79,7 @@userStore.setUser(user);async function finalizeLogin() {- const settings = await settingsAPI.getSettings();+ const settings = await settingsService.getSettings();settingsStore.set(settings);toast.success('Successfully logged in!');goto(!settings.onboardingCompleted ? '/onboarding/welcome' : redirectTo, { replaceState: true });diff --git a/frontend/src/routes/auth/oidc/login/+page.svelte b/frontend/src/routes/auth/oidc/login/+page.svelteindex e87b58d84..614edaaec 100644--- a/frontend/src/routes/auth/oidc/login/+page.svelte+++ b/frontend/src/routes/auth/oidc/login/+page.svelte@@ -2,8 +2,8 @@import { onMount } from 'svelte';import { goto } from '$app/navigation';import { page } from '$app/state';- import { oidcAPI } from '$lib/services/api';import { m } from '$lib/paraglide/messages';+ import { authService } from '$lib/services/auth-service';let isRedirecting = $state(true);let error = $state('');@@ -12,9 +12,7 @@try {const redirect = page.url.searchParams.get('redirect') || '/dashboard';- const status = await oidcAPI.getStatus();-- const authUrl = await oidcAPI.getAuthUrl(redirect);+ const authUrl = await authService.getAuthUrl(redirect);if (!authUrl) {error = m.auth_oidc_url_generation_failed();setTimeout(() => goto('/auth/login?error=oidc_url_generation_failed'), 3000);diff --git a/frontend/src/routes/containers/+page.svelte b/frontend/src/routes/containers/+page.svelteindex 84d928a8c..a84202fc4 100644--- a/frontend/src/routes/containers/+page.svelte+++ b/frontend/src/routes/containers/+page.svelte@@ -5,10 +5,11 @@import { tryCatch } from '$lib/utils/try-catch';import { handleApiResultWithCallbacks } from '$lib/utils/api.util';import StatCard from '$lib/components/stat-card.svelte';- import { environmentAPI } from '$lib/services/api';+ import { containerService } from '$lib/services/container-service';import ContainerTable from './container-table.svelte';import { ArcaneButton } from '$lib/components/arcane-button/index.js';import { m } from '$lib/paraglide/messages';+ import { imageService } from '$lib/services/image-service';let { data } = $props();@@ -31,12 +32,12 @@async function handleCheckForUpdates() {isLoading.checking = true;handleApiResultWithCallbacks({- result: await tryCatch(environmentAPI.runAutoUpdate()),+ result: await tryCatch(imageService.runAutoUpdate()),message: 'Failed to Check Containers for Updates',setLoadingState: (value) => (isLoading.checking = value),async onSuccess() {toast.success('Containers Updated Successfully.');- containers = await environmentAPI.getContainers(requestOptions);+ containers = await containerService.getContainers(requestOptions);}});}@@ -44,7 +45,7 @@async function refreshContainers() {isLoading.refreshing = true;handleApiResultWithCallbacks({- result: await tryCatch(environmentAPI.getContainers(requestOptions)),+ result: await tryCatch(containerService.getContainers(requestOptions)),message: 'Failed to Refresh Containers',setLoadingState: (value) => (isLoading.refreshing = value),async onSuccess(newContainers) {@@ -120,12 +121,12 @@onSubmit={async (options) => {isLoading.create = true;handleApiResultWithCallbacks({- result: await tryCatch(environmentAPI.createContainer(options)),+ result: await tryCatch(containerService.createContainer(options)),message: m.containers_create_failed(),setLoadingState: (value) => (isLoading.create = value),onSuccess: async () => {toast.success(m.containers_create_success());- containers = await environmentAPI.getContainers(requestOptions);+ containers = await containerService.getContainers(requestOptions);isCreateDialogOpen = false;}});diff --git a/frontend/src/routes/containers/+page.ts b/frontend/src/routes/containers/+page.tsindex 986169dbe..5811daf70 100644--- a/frontend/src/routes/containers/+page.ts+++ b/frontend/src/routes/containers/+page.ts@@ -1,6 +1,7 @@-import { environmentAPI, settingsAPI } from '$lib/services/api';import type { SearchPaginationSortRequest } from '$lib/types/pagination.type';+import { containerService } from '$lib/services/container-service';import type { PageLoad } from './$types';+import { settingsService } from '$lib/services/settings-service';export const load: PageLoad = async () => {const containerRequestOptions: SearchPaginationSortRequest = {@@ -9,9 +10,9 @@ export const load: PageLoad = async () => {};const [containers, containerStatusCounts, settings] = await Promise.all([- environmentAPI.getContainers(containerRequestOptions),- environmentAPI.getContainerStatusCounts(),- settingsAPI.getSettings()+ containerService.getContainers(containerRequestOptions),+ containerService.getContainerStatusCounts(),+ settingsService.getSettings()]);return { containers, containerStatusCounts, containerRequestOptions, settings };diff --git a/frontend/src/routes/containers/[containerId]/+page.ts b/frontend/src/routes/containers/[containerId]/+page.tsindex 02d9f1237..186d3421f 100644--- a/frontend/src/routes/containers/[containerId]/+page.ts+++ b/frontend/src/routes/containers/[containerId]/+page.ts@@ -1,15 +1,16 @@import type { PageLoad } from './$types';-import { environmentAPI, settingsAPI } from '$lib/services/api';import { error } from '@sveltejs/kit';+import { containerService } from '$lib/services/container-service';+import { settingsService } from '$lib/services/settings-service';export const load: PageLoad = async ({ params }) => {const containerId = params.containerId;try {const [container, containerStats, settings] = await Promise.all([- environmentAPI.getContainer(containerId),- environmentAPI.getContainerStats(containerId),- settingsAPI.getSettings()+ containerService.getContainer(containerId),+ containerService.getContainerStats(containerId),+ settingsService.getSettings()]);if (!container) {diff --git a/frontend/src/routes/containers/container-table.svelte b/frontend/src/routes/containers/container-table.svelteindex 977b3239d..aaccbe53f 100644--- a/frontend/src/routes/containers/container-table.svelte+++ b/frontend/src/routes/containers/container-table.svelte@@ -15,7 +15,6 @@import { openConfirmDialog } from '$lib/components/confirm-dialog';import { handleApiResultWithCallbacks } from '$lib/utils/api.util';import { tryCatch } from '$lib/utils/try-catch';- import { environmentAPI } from '$lib/services/api';import type { SearchPaginationSortRequest, Paginated } from '$lib/types/pagination.type';import StatusBadge from '$lib/components/badges/status-badge.svelte';import { format } from 'date-fns';@@ -24,6 +23,7 @@import type { ColumnSpec } from '$lib/components/arcane-table';import { m } from '$lib/paraglide/messages';import PortBadges from '$lib/components/port-badges.svelte';+ import { containerService } from '$lib/services/container-service';let {containers = $bindable(),@@ -51,32 +51,32 @@try {if (action === 'start') {handleApiResultWithCallbacks({- result: await tryCatch(environmentAPI.startContainer(id)),+ result: await tryCatch(containerService.startContainer(id)),message: m.containers_start_failed(),setLoadingState: (value) => (isLoading.start = value),async onSuccess() {toast.success(m.containers_start_success());- containers = await environmentAPI.getContainers(requestOptions);+ containers = await containerService.getContainers(requestOptions);}});} else if (action === 'stop') {handleApiResultWithCallbacks({- result: await tryCatch(environmentAPI.stopContainer(id)),+ result: await tryCatch(containerService.stopContainer(id)),message: m.containers_stop_failed(),setLoadingState: (value) => (isLoading.stop = value),async onSuccess() {toast.success(m.containers_stop_success());- containers = await environmentAPI.getContainers(requestOptions);+ containers = await containerService.getContainers(requestOptions);}});} else if (action === 'restart') {handleApiResultWithCallbacks({- result: await tryCatch(environmentAPI.restartContainer(id)),+ result: await tryCatch(containerService.restartContainer(id)),message: m.containers_restart_failed(),setLoadingState: (value) => (isLoading.restart = value),async onSuccess() {toast.success(m.containers_restart_success());- containers = await environmentAPI.getContainers(requestOptions);+ containers = await containerService.getContainers(requestOptions);}});}@@ -110,12 +110,12 @@const force = !!checkboxStates.force;const volumes = !!checkboxStates.volumes;handleApiResultWithCallbacks({- result: await tryCatch(environmentAPI.deleteContainer(id, { force, volumes })),+ result: await tryCatch(containerService.deleteContainer(id, { force, volumes })),message: m.containers_remove_failed(),setLoadingState: (value) => (isLoading.remove = value),async onSuccess() {toast.success(m.containers_remove_success());- containers = await environmentAPI.getContainers(requestOptions);+ containers = await containerService.getContainers(requestOptions);}});}@@ -242,7 +242,7 @@items={containers}bind:requestOptionsbind:selectedIds- onRefresh={async (options) => (containers = await environmentAPI.getContainers(options))}+ onRefresh={async (options) => (containers = await containerService.getContainers(options))}{columns}rowActions={RowActions}selectionDisableddiff --git a/frontend/src/routes/customize/registries/+page.svelte b/frontend/src/routes/customize/registries/+page.svelteindex 8e5e8d51a..a96736b8c 100644--- a/frontend/src/routes/customize/registries/+page.svelte+++ b/frontend/src/routes/customize/registries/+page.svelte@@ -4,13 +4,13 @@import { toast } from 'svelte-sonner';import type { ContainerRegistry } from '$lib/types/container-registry.type';import type { ContainerRegistryCreateDto, ContainerRegistryUpdateDto } from '$lib/types/container-registry.type';- import { containerRegistryAPI } from '$lib/services/api';import ContainerRegistryFormSheet from '$lib/components/sheets/container-registry-sheet.svelte';import RegistryTable from './registry-table.svelte';import { ArcaneButton } from '$lib/components/arcane-button/index.js';import { handleApiResultWithCallbacks } from '$lib/utils/api.util';import { tryCatch } from '$lib/utils/try-catch';import { m } from '$lib/paraglide/messages';+ import { containerRegistryService } from '$lib/services/container-registry-service';let { data } = $props();@@ -29,7 +29,7 @@async function refreshRegistries() {isLoading.refresh = true;handleApiResultWithCallbacks({- result: await tryCatch(containerRegistryAPI.getRegistries(requestOptions)),+ result: await tryCatch(containerRegistryService.getRegistries(requestOptions)),message: m.registries_refresh_failed(),setLoadingState: (value) => (isLoading.refresh = value),onSuccess: async (newRegistries) => {@@ -59,14 +59,14 @@try {if (isEditMode && registryToEdit?.id) {- await containerRegistryAPI.updateRegistry(registryToEdit.id, registry as ContainerRegistryUpdateDto);+ await containerRegistryService.updateRegistry(registryToEdit.id, registry as ContainerRegistryUpdateDto);toast.success(m.registries_update_success());} else {- await containerRegistryAPI.createRegistry(registry as ContainerRegistryCreateDto);+ await containerRegistryService.createRegistry(registry as ContainerRegistryCreateDto);toast.success(m.registries_create_success());}- registries = await containerRegistryAPI.getRegistries(requestOptions);+ registries = await containerRegistryService.getRegistries(requestOptions);isRegistryDialogOpen = false;} catch (error) {console.error('Error saving registry:', error);diff --git a/frontend/src/routes/customize/registries/+page.ts b/frontend/src/routes/customize/registries/+page.tsindex 6d665529f..49fccbc3c 100644--- a/frontend/src/routes/customize/registries/+page.ts+++ b/frontend/src/routes/customize/registries/+page.ts@@ -1,4 +1,4 @@-import { containerRegistryAPI } from '$lib/services/api';+import { containerRegistryService } from '$lib/services/container-registry-service';import type { SearchPaginationSortRequest } from '$lib/types/pagination.type';import type { PageLoad } from './$types';@@ -14,7 +14,7 @@ export const load: PageLoad = async () => {}};- const registries = await containerRegistryAPI.getRegistries(registryRequestOptions);+ const registries = await containerRegistryService.getRegistries(registryRequestOptions);return { registries, registryRequestOptions };};diff --git a/frontend/src/routes/customize/registries/registry-table.svelte b/frontend/src/routes/customize/registries/registry-table.svelteindex 53297612c..ef6cb3cb2 100644--- a/frontend/src/routes/customize/registries/registry-table.svelte+++ b/frontend/src/routes/customize/registries/registry-table.svelte@@ -10,12 +10,12 @@import { toast } from 'svelte-sonner';import { handleApiResultWithCallbacks } from '$lib/utils/api.util';import { tryCatch } from '$lib/utils/try-catch';- import { containerRegistryAPI } from '$lib/services/api';import type { Paginated, SearchPaginationSortRequest } from '$lib/types/pagination.type';import type { ContainerRegistry } from '$lib/types/container-registry.type';import type { ColumnSpec } from '$lib/components/arcane-table';import { format } from 'date-fns';import { m } from '$lib/paraglide/messages';+ import { containerRegistryService } from '$lib/services/container-registry-service';let {registries = $bindable(),@@ -58,7 +58,7 @@let failureCount = 0;for (const id of ids) {const reg = registries.data.find((r) => r.id === id);- const result = await tryCatch(containerRegistryAPI.deleteRegistry(id));+ const result = await tryCatch(containerRegistryService.deleteRegistry(id));if (result.error) {failureCount++;toast.error(m.registries_delete_failed({ url: reg?.url ?? m.common_unknown() }));@@ -69,7 +69,7 @@if (successCount > 0) {toast.success(m.registries_bulk_remove_success({ count: successCount }));- registries = await containerRegistryAPI.getRegistries(requestOptions);+ registries = await containerRegistryService.getRegistries(requestOptions);}if (failureCount > 0) toast.error(m.registries_bulk_remove_failed({ count: failureCount }));@@ -91,14 +91,14 @@action: async () => {isLoading.removing = true;- const result = await tryCatch(containerRegistryAPI.deleteRegistry(id));+ const result = await tryCatch(containerRegistryService.deleteRegistry(id));handleApiResultWithCallbacks({result,message: m.registries_delete_failed({ url: safeUrl }),setLoadingState: () => {},onSuccess: async () => {toast.success(m.registries_delete_success({ url: safeUrl }));- registries = await containerRegistryAPI.getRegistries(requestOptions);+ registries = await containerRegistryService.getRegistries(requestOptions);}});@@ -111,7 +111,7 @@async function handleTest(id: string, url: string) {isLoading.testing = true;const safeUrl = url ?? m.common_unknown();- const result = await tryCatch(containerRegistryAPI.testRegistry(id));+ const result = await tryCatch(containerRegistryService.testRegistry(id));handleApiResultWithCallbacks({result,message: m.registries_test_failed({ url: safeUrl }),@@ -228,7 +228,7 @@bind:requestOptionsbind:selectedIdsonRemoveSelected={(ids) => handleDeleteSelected(ids)}- onRefresh={async (options) => (registries = await containerRegistryAPI.getRegistries(options))}+ onRefresh={async (options) => (registries = await containerRegistryService.getRegistries(options))}{columns}rowActions={RowActions}/>diff --git a/frontend/src/routes/customize/templates/+page.svelte b/frontend/src/routes/customize/templates/+page.svelteindex 7fee5df69..40b355019 100644--- a/frontend/src/routes/customize/templates/+page.svelte+++ b/frontend/src/routes/customize/templates/+page.svelte@@ -14,11 +14,11 @@import GlobeIcon from '@lucide/svelte/icons/globe';import FolderOpenIcon from '@lucide/svelte/icons/folder-open';import UsersIcon from '@lucide/svelte/icons/users';- import { templateAPI } from '$lib/services/api';import { toast } from 'svelte-sonner';import AddTemplateRegistrySheet from '$lib/components/sheets/add-template-registry-sheet.svelte';import StatCard from '$lib/components/stat-card.svelte';import { m } from '$lib/paraglide/messages';+ import { templateService } from '$lib/services/template-service.js';let { data } = $props();@@ -47,14 +47,14 @@return;}- await templateAPI.updateRegistry(id, {+ await templateService.updateRegistry(id, {name: registry.name,url: registry.url,description: registry.description,enabled: updates.enabled ?? registry.enabled});- registries = await templateAPI.getRegistries();+ registries = await templateService.getRegistries();toast.success(m.registries_update_success());} catch (error) {console.error('Error updating registry:', error);@@ -70,9 +70,9 @@try {const reg = registries.find((r) => r.id === id);- await templateAPI.deleteRegistry(id);+ await templateService.deleteRegistry(id);registries = registries.filter((r) => r.id !== id);- registries = await templateAPI.getRegistries();+ registries = await templateService.getRegistries();toast.success(reg ? m.registries_delete_success({ url: reg.url }) : m.templates_registry_removed_success());} catch (error) {console.error('Error removing registry:', error);@@ -84,7 +84,7 @@async function refreshTemplates() {try {- templates = await templateAPI.loadAll();+ templates = await templateService.loadAll();toast.success(m.templates_refreshed());} catch (error) {console.error('Error refreshing templates:', error);@@ -96,14 +96,14 @@isLoading.addingRegistry = true;try {- const created = await templateAPI.addRegistry({+ const created = await templateService.addRegistry({name: registry.name.trim(),url: registry.url.trim(),description: registry.description?.trim() || undefined,enabled: registry.enabled});- registries = await templateAPI.getRegistries();+ registries = await templateService.getRegistries();showAddRegistrySheet = false;toast.success(m.registries_create_success());diff --git a/frontend/src/routes/customize/templates/+page.ts b/frontend/src/routes/customize/templates/+page.tsindex 2df723ba3..9ddc9389c 100644--- a/frontend/src/routes/customize/templates/+page.ts+++ b/frontend/src/routes/customize/templates/+page.ts@@ -1,9 +1,9 @@-import { templateAPI } from '$lib/services/api';+import { templateService } from '$lib/services/template-service';export const load = async () => {const [templates, registries] = await Promise.all([- templateAPI.loadAll().catch(() => []),- templateAPI.getRegistries().catch(() => [])+ templateService.loadAll().catch(() => []),+ templateService.getRegistries().catch(() => [])]);return {diff --git a/frontend/src/routes/dashboard/+page.svelte b/frontend/src/routes/dashboard/+page.svelteindex 72d96fa09..469fb89e1 100644--- a/frontend/src/routes/dashboard/+page.svelte+++ b/frontend/src/routes/dashboard/+page.svelte@@ -7,7 +7,6 @@import PruneConfirmationDialog from '$lib/components/dialogs/prune-confirmation-dialog.svelte';import { handleApiResultWithCallbacks } from '$lib/utils/api.util';import { tryCatch } from '$lib/utils/try-catch';- import { systemAPI, settingsAPI, environmentAPI } from '$lib/services/api';import { openConfirmDialog } from '$lib/components/confirm-dialog';import { onMount } from 'svelte';import { get } from 'svelte/store';@@ -22,6 +21,7 @@import DashboardImageTable from './dash-image-table.svelte';import { m } from '$lib/paraglide/messages';import { invalidateAll } from '$app/navigation';+ import { systemService } from '$lib/services/system-service';let { data } = $props();let containers = $state(data.containers);@@ -109,39 +109,35 @@let imageRequestOptions = $state(data.imageRequestOptions);async function refreshData() {- if (isLoading.refreshing) return;isLoading.refreshing = true;- isLoading.loadingDockerInfo = true;- isLoading.loadingImages = true;-- const [dockerInfoResult, settingsResult, imagesResult, statusCountsResult] = await Promise.allSettled([- tryCatch(environmentAPI.getDockerInfo()),- tryCatch(settingsAPI.getSettings()),- tryCatch(environmentAPI.getImages(imageRequestOptions)),- tryCatch(environmentAPI.getContainerStatusCounts())- ]);-- if (dockerInfoResult.status === 'fulfilled' && !dockerInfoResult.value.error) {- dashboardStates.dockerInfo = dockerInfoResult.value.data;- dockerInfo = dockerInfoResult.value.data;- }- isLoading.loadingDockerInfo = false;-- if (settingsResult.status === 'fulfilled' && !settingsResult.value.error) {- dashboardStates.settings = settingsResult.value.data;- }-- if (imagesResult.status === 'fulfilled') {- if (!imagesResult.value.error) {- images = imagesResult.value.data;- }- }- isLoading.loadingImages = false;-- if (statusCountsResult.status === 'fulfilled' && !statusCountsResult.value.error) {- containerStatusCounts = statusCountsResult.value.data;- }+ // const [dockerInfoResult, settingsResult, imagesResult, statusCountsResult] = await Promise.allSettled([+ // tryCatch(environmentAPI.getDockerInfo()),+ // tryCatch(settingsAPI.getSettings()),+ // tryCatch(environmentAPI.getImages(imageRequestOptions)),+ // tryCatch(environmentAPI.getContainerStatusCounts())+ // ]);++ // if (dockerInfoResult.status === 'fulfilled' && !dockerInfoResult.value.error) {+ // dashboardStates.dockerInfo = dockerInfoResult.value.data;+ // dockerInfo = dockerInfoResult.value.data;+ // }+ // isLoading.loadingDockerInfo = false;++ // if (settingsResult.status === 'fulfilled' && !settingsResult.value.error) {+ // dashboardStates.settings = settingsResult.value.data;+ // }++ // if (imagesResult.status === 'fulfilled') {+ // if (!imagesResult.value.error) {+ // images = imagesResult.value.data;+ // }+ // }+ // isLoading.loadingImages = false;++ // if (statusCountsResult.status === 'fulfilled' && !statusCountsResult.value.error) {+ // containerStatusCounts = statusCountsResult.value.data;+ // }await invalidateAll();isLoading.refreshing = false;@@ -224,7 +220,7 @@if (isLoading.starting || !dashboardStates.dockerInfo || stoppedContainers === 0) return;isLoading.starting = true;handleApiResultWithCallbacks({- result: await tryCatch(systemAPI.startAllStoppedContainers()),+ result: await tryCatch(systemService.startAllStoppedContainers()),message: m.dashboard_start_all_failed(),setLoadingState: (value) => (isLoading.starting = value),onSuccess: async () => {@@ -244,7 +240,7 @@destructive: false,action: async () => {handleApiResultWithCallbacks({- result: await tryCatch(systemAPI.stopAllContainers()),+ result: await tryCatch(systemService.stopAllContainers()),message: m.dashboard_stop_all_failed(),setLoadingState: (value) => (isLoading.stopping = value),onSuccess: async () => {@@ -280,7 +276,7 @@const typesString = selectedTypes.map((t) => typeLabels[t]).join(', ');handleApiResultWithCallbacks({- result: await tryCatch(systemAPI.pruneAll(pruneOptions)),+ result: await tryCatch(systemService.pruneAll(pruneOptions)),message: m.dashboard_prune_failed({ types: typesString }),setLoadingState: (value) => (isLoading.pruning = value),onSuccess: async () => {diff --git a/frontend/src/routes/dashboard/+page.ts b/frontend/src/routes/dashboard/+page.tsindex 6304efe5f..04290a0a6 100644--- a/frontend/src/routes/dashboard/+page.ts+++ b/frontend/src/routes/dashboard/+page.ts@@ -1,4 +1,7 @@-import { settingsAPI, environmentAPI } from '$lib/services/api';+import { containerService } from '$lib/services/container-service';+import { imageService } from '$lib/services/image-service';+import { settingsService } from '$lib/services/settings-service';+import { systemService } from '$lib/services/system-service';import type { SearchPaginationSortRequest } from '$lib/types/pagination.type';import type { PageLoad } from './$types';@@ -24,13 +27,13 @@ export const load: PageLoad = async () => {}};- const containers = await environmentAPI.getContainers(containerRequestOptions);- const images = await environmentAPI.getImages(imageRequestOptions);- const containerStatusCounts = await environmentAPI.getContainerStatusCounts();+ const containers = await containerService.getContainers(containerRequestOptions);+ const images = await imageService.getImages(imageRequestOptions);+ const containerStatusCounts = await containerService.getContainerStatusCounts();const [dockerInfoResult, settingsResult] = await Promise.allSettled([- environmentAPI.getDockerInfo(),- settingsAPI.getSettings()+ systemService.getDockerInfo(),+ settingsService.getSettings()]);const dockerInfo = dockerInfoResult.status === 'fulfilled' ? dockerInfoResult.value : null;diff --git a/frontend/src/routes/dashboard/dash-container-table.svelte b/frontend/src/routes/dashboard/dash-container-table.svelteindex bd643e7b8..88911a4f1 100644--- a/frontend/src/routes/dashboard/dash-container-table.svelte+++ b/frontend/src/routes/dashboard/dash-container-table.svelte@@ -8,9 +8,9 @@import { capitalizeFirstLetter } from '$lib/utils/string.utils';import type { SearchPaginationSortRequest, Paginated } from '$lib/types/pagination.type';import type { ContainerSummaryDto } from '$lib/types/container.type';- import { environmentAPI } from '$lib/services/api';import type { ColumnSpec } from '$lib/components/arcane-table';import { m } from '$lib/paraglide/messages';+ import { containerService } from '$lib/services/container-service';let {containers = $bindable(),@@ -71,7 +71,7 @@items={containers}bind:requestOptionsbind:selectedIds- onRefresh={async (options) => (containers = await environmentAPI.getContainers(options))}+ onRefresh={async (options) => (containers = await containerService.getContainers(options))}withoutSearch={true}withoutPagination={true}selectionDisabled={true}diff --git a/frontend/src/routes/dashboard/dash-image-table.svelte b/frontend/src/routes/dashboard/dash-image-table.svelteindex 349fa29f0..f0986ddd5 100644--- a/frontend/src/routes/dashboard/dash-image-table.svelte+++ b/frontend/src/routes/dashboard/dash-image-table.svelte@@ -6,10 +6,10 @@import StatusBadge from '$lib/components/badges/status-badge.svelte';import type { SearchPaginationSortRequest, Paginated } from '$lib/types/pagination.type';import type { ImageSummaryDto } from '$lib/types/image.type';- import { environmentAPI } from '$lib/services/api';import bytes from 'bytes';import type { ColumnSpec } from '$lib/components/arcane-table';import { m } from '$lib/paraglide/messages';+ import { imageService } from '$lib/services/image-service';let {images = $bindable(),@@ -91,7 +91,7 @@items={images}bind:requestOptionsbind:selectedIds- onRefresh={async (options) => (images = await environmentAPI.getImages(options))}+ onRefresh={async (options) => (images = await imageService.getImages(options))}withoutSearch={true}selectionDisabled={true}withoutPagination={true}diff --git a/frontend/src/routes/environments/+page.svelte b/frontend/src/routes/environments/+page.svelteindex ab005345d..16b69aed5 100644--- a/frontend/src/routes/environments/+page.svelte+++ b/frontend/src/routes/environments/+page.svelte@@ -7,8 +7,8 @@import { tryCatch } from '$lib/utils/try-catch';import { handleApiResultWithCallbacks } from '$lib/utils/api.util';import { openConfirmDialog } from '$lib/components/confirm-dialog';- import { environmentManagementAPI } from '$lib/services/api';import { m } from '$lib/paraglide/messages';+ import { environmentManagementService } from '$lib/services/env-mgmt-service';let { data } = $props();@@ -26,7 +26,7 @@async function refresh() {isLoading.refresh = true;try {- environments = await environmentManagementAPI.getEnvironments(requestOptions);+ environments = await environmentManagementService.getEnvironments(requestOptions);} catch (err) {console.error('Failed to refresh environments:', err);toast.error(m.environments_refresh_failed());@@ -50,7 +50,7 @@let failureCount = 0;for (const id of selectedIds) {- const result = await tryCatch(environmentManagementAPI.delete(id));+ const result = await tryCatch(environmentManagementService.delete(id));handleApiResultWithCallbacks({result,message: m.environments_bulk_remove_failed_many({ count: selectedIds.length }),@@ -88,7 +88,7 @@async function onEnvironmentCreated() {showEnvironmentSheet = false;- environments = await environmentManagementAPI.getEnvironments(requestOptions);+ environments = await environmentManagementService.getEnvironments(requestOptions);toast.success(m.environments_created_success());refresh();}diff --git a/frontend/src/routes/environments/+page.ts b/frontend/src/routes/environments/+page.tsindex aa94449e7..15c1fe60e 100644--- a/frontend/src/routes/environments/+page.ts+++ b/frontend/src/routes/environments/+page.ts@@ -1,6 +1,6 @@import type { PageLoad } from './$types';-import { environmentManagementAPI } from '$lib/services/api';import type { SearchPaginationSortRequest } from '$lib/types/pagination.type';+import { environmentManagementService } from '$lib/services/env-mgmt-service';export const load: PageLoad = async () => {const environmentRequestOptions: SearchPaginationSortRequest = {@@ -14,7 +14,7 @@ export const load: PageLoad = async () => {}};- const environments = await environmentManagementAPI.getEnvironments(environmentRequestOptions);+ const environments = await environmentManagementService.getEnvironments(environmentRequestOptions);return { environments, environmentRequestOptions };};diff --git a/frontend/src/routes/environments/[id]/+page.svelte b/frontend/src/routes/environments/[id]/+page.svelteindex 9a9dcf67f..3322f86c7 100644--- a/frontend/src/routes/environments/[id]/+page.svelte+++ b/frontend/src/routes/environments/[id]/+page.svelte@@ -9,10 +9,10 @@import GlobeIcon from '@lucide/svelte/icons/globe';import { goto, invalidateAll } from '$app/navigation';import StatusBadge from '$lib/components/badges/status-badge.svelte';- import { environmentManagementAPI } from '$lib/services/api';import { toast } from 'svelte-sonner';import Label from '$lib/components/ui/label/label.svelte';import { m } from '$lib/paraglide/messages';+ import { environmentManagementService } from '$lib/services/env-mgmt-service.js';let { data } = $props();let { environment } = $derived(data);@@ -47,7 +47,7 @@if (isTestingConnection) return;try {isTestingConnection = true;- const result = await environmentManagementAPI.testConnection(environment.id);+ const result = await environmentManagementService.testConnection(environment.id);if (result.status === 'online') {toast.success('Connection successful');} else {@@ -69,7 +69,7 @@}try {isPairing = true;- await environmentManagementAPI.update(environment.id, { bootstrapToken });+ await environmentManagementService.update(environment.id, { bootstrapToken });toast.success('Agent paired successfully');bootstrapToken = '';await refreshEnvironment();diff --git a/frontend/src/routes/environments/[id]/+page.ts b/frontend/src/routes/environments/[id]/+page.tsindex 6cee22fa2..2585e07e9 100644--- a/frontend/src/routes/environments/[id]/+page.ts+++ b/frontend/src/routes/environments/[id]/+page.ts@@ -1,8 +1,8 @@+import { environmentManagementService } from '$lib/services/env-mgmt-service';import type { PageLoad } from './$types';-import { environmentManagementAPI } from '$lib/services/api';export const load: PageLoad = async ({ params }) => {- const environment = await environmentManagementAPI.get(params.id);+ const environment = await environmentManagementService.get(params.id);return {environmentdiff --git a/frontend/src/routes/environments/environment-table.svelte b/frontend/src/routes/environments/environment-table.svelteindex c82d8059f..b966dca09 100644--- a/frontend/src/routes/environments/environment-table.svelte+++ b/frontend/src/routes/environments/environment-table.svelte@@ -14,11 +14,11 @@import { handleApiResultWithCallbacks } from '$lib/utils/api.util';import { tryCatch } from '$lib/utils/try-catch';import { toast } from 'svelte-sonner';- import { environmentManagementAPI } from '$lib/services/api';import type { Paginated, SearchPaginationSortRequest } from '$lib/types/pagination.type';import type { ColumnSpec } from '$lib/components/arcane-table';import type { Environment } from '$lib/types/environment.type';import { m } from '$lib/paraglide/messages';+ import { environmentManagementService } from '$lib/services/env-mgmt-service';let {environments = $bindable(),@@ -47,7 +47,7 @@let failureCount = 0;for (const id of ids) {- const result = await tryCatch(environmentManagementAPI.delete(id));+ const result = await tryCatch(environmentManagementService.delete(id));handleApiResultWithCallbacks({result,message: m.environments_bulk_remove_failed_many({ count: ids.length }),@@ -67,7 +67,7 @@? m.environments_bulk_remove_success_one(): m.environments_bulk_remove_success_many({ count: successCount });toast.success(msg);- environments = await environmentManagementAPI.getEnvironments(requestOptions);+ environments = await environmentManagementService.getEnvironments(requestOptions);}if (failureCount > 0) {const msg =@@ -92,14 +92,14 @@destructive: true,action: async () => {isLoading.removing = true;- const result = await tryCatch(environmentManagementAPI.delete(id));+ const result = await tryCatch(environmentManagementService.delete(id));handleApiResultWithCallbacks({result,message: m.environments_delete_failed({ name: hostname }),setLoadingState: () => {},onSuccess: async () => {toast.success(m.environments_delete_success({ name: hostname }));- environments = await environmentManagementAPI.getEnvironments(requestOptions);+ environments = await environmentManagementService.getEnvironments(requestOptions);}});isLoading.removing = false;@@ -110,7 +110,7 @@async function handleTest(id: string) {isLoading.testing = true;- const result = await tryCatch(environmentManagementAPI.testConnection(id));+ const result = await tryCatch(environmentManagementService.testConnection(id));handleApiResultWithCallbacks({result,message: m.environments_test_connection_failed(),@@ -226,7 +226,7 @@bind:requestOptionsbind:selectedIdsonRemoveSelected={(ids) => handleDeleteSelected(ids)}- onRefresh={async (options) => (environments = await environmentManagementAPI.getEnvironments(options))}+ onRefresh={async (options) => (environments = await environmentManagementService.getEnvironments(options))}{columns}rowActions={RowActions}/>diff --git a/frontend/src/routes/events/+page.svelte b/frontend/src/routes/events/+page.svelteindex a6b9ed840..ea9069fa2 100644--- a/frontend/src/routes/events/+page.svelte+++ b/frontend/src/routes/events/+page.svelte@@ -6,11 +6,11 @@import type { PageData } from './$types';import StatCard from '$lib/components/stat-card.svelte';import type { Event } from '$lib/types/event.type';- import { eventAPI } from '$lib/services/api';import EventTable from './event-table.svelte';import { ArcaneButton } from '$lib/components/arcane-button/index.js';import { openConfirmDialog } from '$lib/components/confirm-dialog';import { m } from '$lib/paraglide/messages';+ import { eventService } from '$lib/services/event-service';let { data }: { data: PageData } = $props();@@ -32,7 +32,7 @@async function refreshEvents() {isLoading.refreshing = true;try {- events = await eventAPI.getEvents(requestOptions);+ events = await eventService.getEvents(requestOptions);} catch (error) {console.error('Failed to refresh events:', error);toast.error(m.events_refresh_failed());@@ -56,7 +56,7 @@let failureCount = 0;for (const eventId of selectedIds) {- const result = await tryCatch(eventAPI.delete(eventId));+ const result = await tryCatch(eventService.delete(eventId));handleApiResultWithCallbacks({result,message: m.events_delete_item_failed({ id: eventId }),diff --git a/frontend/src/routes/events/+page.ts b/frontend/src/routes/events/+page.tsindex 305c33d6d..7cc153dd2 100644--- a/frontend/src/routes/events/+page.ts+++ b/frontend/src/routes/events/+page.ts@@ -1,4 +1,4 @@-import { eventAPI } from '$lib/services/api';+import { eventService } from '$lib/services/event-service';import type { SearchPaginationSortRequest } from '$lib/types/pagination.type';import type { PageLoad } from './$types';@@ -14,7 +14,7 @@ export const load: PageLoad = async () => {}};- const events = await eventAPI.getEvents(eventRequestOptions);+ const events = await eventService.getEvents(eventRequestOptions);return { events, eventRequestOptions };};diff --git a/frontend/src/routes/events/event-table.svelte b/frontend/src/routes/events/event-table.svelteindex b731d611b..15f7024e2 100644--- a/frontend/src/routes/events/event-table.svelte+++ b/frontend/src/routes/events/event-table.svelte@@ -12,13 +12,13 @@import { tryCatch } from '$lib/utils/try-catch';import { handleApiResultWithCallbacks } from '$lib/utils/api.util';import { formatDistanceToNow } from 'date-fns';- import { eventAPI } from '$lib/services/api';import type { Paginated, SearchPaginationSortRequest } from '$lib/types/pagination.type';import type { Event } from '$lib/types/event.type';import type { ColumnSpec } from '$lib/components/arcane-table';import EventDetailsDialog from '$lib/components/dialogs/event-details-dialog.svelte';import InfoIcon from '@lucide/svelte/icons/info';import { m } from '$lib/paraglide/messages';+ import { eventService } from '$lib/services/event-service';let {events = $bindable(),@@ -64,12 +64,12 @@action: async () => {isLoading.removing = true;handleApiResultWithCallbacks({- result: await tryCatch(eventAPI.delete(eventId)),+ result: await tryCatch(eventService.delete(eventId)),message: m.events_delete_failed({ title: safeTitle }),setLoadingState: (value) => (isLoading.removing = value),onSuccess: async () => {toast.success(m.events_delete_success({ title: safeTitle }));- events = await eventAPI.getEvents(requestOptions);+ events = await eventService.getEvents(requestOptions);}});}@@ -184,7 +184,7 @@items={events}bind:requestOptionsbind:selectedIds- onRefresh={async (options) => (events = await eventAPI.getEvents(options))}+ onRefresh={async (options) => (events = await eventService.getEvents(options))}{columns}rowActions={RowActions}/>diff --git a/frontend/src/routes/images/+page.svelte b/frontend/src/routes/images/+page.svelteindex 1906161bc..91f22778e 100644--- a/frontend/src/routes/images/+page.svelte+++ b/frontend/src/routes/images/+page.svelte@@ -10,10 +10,10 @@import { handleApiResultWithCallbacks } from '$lib/utils/api.util';import { tryCatch } from '$lib/utils/try-catch';import { ArcaneButton } from '$lib/components/arcane-button/index.js';- import { environmentAPI } from '$lib/services/api';import StatCard from '$lib/components/stat-card.svelte';import ImageTable from './image-table.svelte';import { m } from '$lib/paraglide/messages';+ import { imageService } from '$lib/services/image-service';let { data } = $props();@@ -34,12 +34,12 @@isLoading.pruning = true;const dangling = data.settings?.dockerPruneMode === 'dangling';handleApiResultWithCallbacks({- result: await tryCatch(environmentAPI.pruneImages(dangling)),+ result: await tryCatch(imageService.pruneImages(dangling)),message: m.images_prune_failed(),setLoadingState: (value) => (isLoading.pruning = value),onSuccess: async () => {toast.success(m.images_pruned_success());- images = await environmentAPI.getImages(requestOptions);+ images = await imageService.getImages(requestOptions);isConfirmPruneDialogOpen = false;}});@@ -48,9 +48,9 @@async function handleTriggerBulkUpdateCheck() {isLoading.checking = true;try {- await environmentAPI.checkAllImages();+ await imageService.checkAllImages();toast.success(m.images_update_check_completed());- images = await environmentAPI.getImages(requestOptions);+ images = await imageService.getImages(requestOptions);} catch (error) {console.error('Failed to check for updates:', error);toast.error(m.images_update_check_failed());@@ -62,7 +62,7 @@async function refreshImages() {isLoading.refreshing = true;handleApiResultWithCallbacks({- result: await tryCatch(environmentAPI.getImages(requestOptions)),+ result: await tryCatch(imageService.getImages(requestOptions)),message: m.images_refresh_failed(),setLoadingState: (value) => (isLoading.refreshing = value),async onSuccess(newImages) {@@ -126,7 +126,7 @@<ImagePullSheetbind:open={isPullDialogOpen}- onPullFinished={async () => (images = await environmentAPI.getImages(requestOptions))}+ onPullFinished={async () => (images = await imageService.getImages(requestOptions))}/><Dialog.Root bind:open={isConfirmPruneDialogOpen}>diff --git a/frontend/src/routes/images/+page.ts b/frontend/src/routes/images/+page.tsindex d93a144fc..c81e07694 100644--- a/frontend/src/routes/images/+page.ts+++ b/frontend/src/routes/images/+page.ts@@ -1,4 +1,5 @@-import { environmentAPI, settingsAPI } from '$lib/services/api';+import { imageService } from '$lib/services/image-service';+import { settingsService } from '$lib/services/settings-service';import type { SearchPaginationSortRequest } from '$lib/types/pagination.type';import type { PageLoad } from './$types';@@ -13,9 +14,9 @@ export const load: PageLoad = async () => {direction: 'desc' as const}};- const images = await environmentAPI.getImages(imageRequestOptions);- const settings = await settingsAPI.getSettings();- const imageUsageCounts = await environmentAPI.getImageUsageCounts();+ const images = await imageService.getImages(imageRequestOptions);+ const settings = await settingsService.getSettings();+ const imageUsageCounts = await imageService.getImageUsageCounts();return { images, imageRequestOptions, settings, imageUsageCounts };};diff --git a/frontend/src/routes/images/[imageId]/+page.svelte b/frontend/src/routes/images/[imageId]/+page.svelteindex 21fa6fbf8..dc298cc88 100644--- a/frontend/src/routes/images/[imageId]/+page.svelte+++ b/frontend/src/routes/images/[imageId]/+page.svelte@@ -17,8 +17,8 @@import { tryCatch } from '$lib/utils/try-catch';import { toast } from 'svelte-sonner';import { ArcaneButton } from '$lib/components/arcane-button/index.js';- import { environmentAPI } from '$lib/services/api';import { m } from '$lib/paraglide/messages';+ import { imageService } from '$lib/services/image-service.js';let { data } = $props();let { image } = $derived(data);@@ -55,7 +55,7 @@destructive: true,action: async () => {await handleApiResultWithCallbacks({- result: await tryCatch(environmentAPI.deleteImage(id)),+ result: await tryCatch(imageService.deleteImage(id)),message: m.images_remove_failed(),setLoadingState: (value) => (isLoading.removing = value),onSuccess: async () => {diff --git a/frontend/src/routes/images/[imageId]/+page.ts b/frontend/src/routes/images/[imageId]/+page.tsindex b68ebce35..703e7cfe7 100644--- a/frontend/src/routes/images/[imageId]/+page.ts+++ b/frontend/src/routes/images/[imageId]/+page.ts@@ -1,4 +1,4 @@-import { environmentAPI } from '$lib/services/api';+import { imageService } from '$lib/services/image-service.js';import type { ImageDetailSummaryDto } from '$lib/types/image.type.js';import { error } from '@sveltejs/kit';@@ -11,7 +11,7 @@ export const load = async ({ params }): Promise<ImageDetailData> => {const { imageId } = params;try {- const image = await environmentAPI.getImage(imageId);+ const image = await imageService.getImage(imageId);if (!image) {throw error(404, 'Image not found');diff --git a/frontend/src/routes/images/image-table.svelte b/frontend/src/routes/images/image-table.svelteindex 7cef20eb2..2fd4eedde 100644--- a/frontend/src/routes/images/image-table.svelte+++ b/frontend/src/routes/images/image-table.svelte@@ -16,12 +16,12 @@import { handleApiResultWithCallbacks } from '$lib/utils/api.util';import { tryCatch } from '$lib/utils/try-catch';import ImageUpdateItem from '$lib/components/image-update-item.svelte';- import { environmentAPI } from '$lib/services/api';import type { Paginated, SearchPaginationSortRequest } from '$lib/types/pagination.type';import type { ImageSummaryDto } from '$lib/types/image.type';import { format } from 'date-fns';import type { ColumnSpec } from '$lib/components/arcane-table';import { m } from '$lib/paraglide/messages';+ import { imageService } from '$lib/services/image-service';let {images = $bindable(),@@ -55,7 +55,7 @@let failureCount = 0;for (const id of ids) {- const result = await tryCatch(environmentAPI.deleteImage(id));+ const result = await tryCatch(imageService.deleteImage(id));handleApiResultWithCallbacks({result,message: m.images_remove_failed(),@@ -73,7 +73,7 @@const msg =successCount === 1 ? m.images_remove_success_one() : m.images_remove_success_many({ count: successCount });toast.success(msg);- images = await environmentAPI.getImages(requestOptions);+ images = await imageService.getImages(requestOptions);}if (failureCount > 0) {const msg = failureCount === 1 ? m.images_remove_failed_one() : m.images_remove_failed_many({ count: failureCount });@@ -96,14 +96,14 @@action: async () => {isLoading.removing = true;- const result = await tryCatch(environmentAPI.deleteImage(id));+ const result = await tryCatch(imageService.deleteImage(id));handleApiResultWithCallbacks({result,message: m.images_remove_failed(),setLoadingState: () => {},onSuccess: async () => {toast.success(m.images_remove_success());- images = await environmentAPI.getImages(requestOptions);+ images = await imageService.getImages(requestOptions);}});@@ -121,14 +121,14 @@isPullingInline[imageId] = true;- const result = await tryCatch(environmentAPI.pullImage(repoTag));+ const result = await tryCatch(imageService.pullImage(repoTag));handleApiResultWithCallbacks({result,message: m.images_pull_failed(),setLoadingState: () => {},onSuccess: async () => {toast.success(m.images_pull_success({ repoTag }));- images = await environmentAPI.getImages(requestOptions);+ images = await imageService.getImages(requestOptions);}});@@ -261,7 +261,7 @@bind:requestOptionsbind:selectedIdsonRemoveSelected={(ids) => handleDeleteSelected(ids)}- onRefresh={async (options) => (images = await environmentAPI.getImages(options))}+ onRefresh={async (options) => (images = await imageService.getImages(options))}{columns}rowActions={RowActions}/>diff --git a/frontend/src/routes/networks/+page.svelte b/frontend/src/routes/networks/+page.svelteindex 68b5bc0db..7373a1a74 100644--- a/frontend/src/routes/networks/+page.svelte+++ b/frontend/src/routes/networks/+page.svelte@@ -6,11 +6,11 @@import { handleApiResultWithCallbacks } from '$lib/utils/api.util';import { tryCatch } from '$lib/utils/try-catch';import CreateNetworkSheet from '$lib/components/sheets/create-network-sheet.svelte';- import { environmentAPI } from '$lib/services/api';import { ArcaneButton } from '$lib/components/arcane-button/index.js';import StatCard from '$lib/components/stat-card.svelte';import NetworkTable from './network-table.svelte';import { m } from '$lib/paraglide/messages';+ import { networkService } from '$lib/services/network-service';let { data } = $props();@@ -29,7 +29,7 @@async function refreshNetworks() {isLoading.refresh = true;handleApiResultWithCallbacks({- result: await tryCatch(environmentAPI.getNetworks(requestOptions)),+ result: await tryCatch(networkService.getNetworks(requestOptions)),message: m.networks_refresh_failed(),setLoadingState: (value) => (isLoading.refresh = value),async onSuccess(newNetworks) {@@ -42,12 +42,12 @@isLoading.create = true;const name = options.Name?.trim() || m.common_unknown();handleApiResultWithCallbacks({- result: await tryCatch(environmentAPI.createNetwork(options)),+ result: await tryCatch(networkService.createNetwork(options)),message: m.networks_create_failed({ name }),setLoadingState: (value) => (isLoading.create = value),onSuccess: async () => {toast.success(m.networks_created_success({ name }));- networks = await environmentAPI.getNetworks(requestOptions);+ networks = await networkService.getNetworks(requestOptions);isCreateDialogOpen = false;}});diff --git a/frontend/src/routes/networks/+page.ts b/frontend/src/routes/networks/+page.tsindex 224e0ed8e..b2bd49775 100644--- a/frontend/src/routes/networks/+page.ts+++ b/frontend/src/routes/networks/+page.ts@@ -1,4 +1,4 @@-import { environmentAPI } from '$lib/services/api';+import { networkService } from '$lib/services/network-service';import type { SearchPaginationSortRequest } from '$lib/types/pagination.type';import type { PageLoad } from './$types';@@ -14,8 +14,8 @@ export const load: PageLoad = async () => {}};- const networks = await environmentAPI.getNetworks(networkRequestOptions);- const networkUsageCounts = await environmentAPI.getNetworkUsageCounts();+ const networks = await networkService.getNetworks(networkRequestOptions);+ const networkUsageCounts = await networkService.getNetworkUsageCounts();return { networks, networkRequestOptions, networkUsageCounts };};diff --git a/frontend/src/routes/networks/[networkId]/+page.svelte b/frontend/src/routes/networks/[networkId]/+page.svelteindex 61a722a20..611c19584 100644--- a/frontend/src/routes/networks/[networkId]/+page.svelte+++ b/frontend/src/routes/networks/[networkId]/+page.svelte@@ -22,9 +22,9 @@import { goto } from '$app/navigation';import { handleApiResultWithCallbacks } from '$lib/utils/api.util';import { tryCatch } from '$lib/utils/try-catch';- import { environmentAPI } from '$lib/services/api';import type { NetworkInspectDto } from '$lib/types/network.type';import { m } from '$lib/paraglide/messages';+ import { networkService } from '$lib/services/network-service';let { data }: { data: PageData } = $props();let { network }: { network: NetworkInspectDto | null | undefined } = $derived(data);@@ -60,7 +60,7 @@destructive: true,action: async () => {handleApiResultWithCallbacks({- result: await tryCatch(environmentAPI.deleteNetwork(network.id)),+ result: await tryCatch(networkService.deleteNetwork(network.id)),message: m.networks_remove_failed({ name: network?.name ?? shortId }),setLoadingState: (value) => (isRemoving = value),onSuccess: async () => {diff --git a/frontend/src/routes/networks/[networkId]/+page.ts b/frontend/src/routes/networks/[networkId]/+page.tsindex 65d8f6330..060d1f276 100644--- a/frontend/src/routes/networks/[networkId]/+page.ts+++ b/frontend/src/routes/networks/[networkId]/+page.ts@@ -1,12 +1,12 @@import type { PageLoad } from './$types';-import { environmentAPI } from '$lib/services/api';import { error } from '@sveltejs/kit';+import { networkService } from '$lib/services/network-service';export const load: PageLoad = async ({ params }) => {const { networkId } = params;try {- const network = await environmentAPI.getNetwork(networkId);+ const network = await networkService.getNetwork(networkId);if (!network) {throw error(404, 'Network not found');diff --git a/frontend/src/routes/networks/network-table.svelte b/frontend/src/routes/networks/network-table.svelteindex ae200eda6..1a422df71 100644--- a/frontend/src/routes/networks/network-table.svelte+++ b/frontend/src/routes/networks/network-table.svelte@@ -12,7 +12,6 @@import { openConfirmDialog } from '$lib/components/confirm-dialog';import { handleApiResultWithCallbacks } from '$lib/utils/api.util';import { tryCatch } from '$lib/utils/try-catch';- import { environmentAPI } from '$lib/services/api';import { DEFAULT_NETWORK_NAMES } from '$lib/constants';import type { SearchPaginationSortRequest, Paginated } from '$lib/types/pagination.type';import StatusBadge from '$lib/components/badges/status-badge.svelte';@@ -20,6 +19,7 @@import { capitalizeFirstLetter } from '$lib/utils/string.utils';import type { ColumnSpec } from '$lib/components/arcane-table';import { m } from '$lib/paraglide/messages';+ import { networkService } from '$lib/services/network-service';let {networks = $bindable(),@@ -49,12 +49,12 @@destructive: true,action: async () => {handleApiResultWithCallbacks({- result: await tryCatch(environmentAPI.deleteNetwork(id)),+ result: await tryCatch(networkService.deleteNetwork(id)),message: m.networks_delete_failed({ name: safeName }),setLoadingState: (value) => (isLoading.remove = value),onSuccess: async () => {toast.success(m.networks_delete_success({ name: safeName }));- networks = await environmentAPI.getNetworks(requestOptions);+ networks = await networkService.getNetworks(requestOptions);}});}@@ -87,7 +87,7 @@const network = networks.data.find((n) => n.id === networkId);if (!network) continue;- const result = await tryCatch(environmentAPI.deleteNetwork(networkId));+ const result = await tryCatch(networkService.deleteNetwork(networkId));if (result.error) {failureCount++;toast.error(m.networks_delete_failed({ name: network.name ?? m.common_unknown() }));@@ -100,7 +100,7 @@isLoading.remove = false;if (successCount > 0) {- networks = await environmentAPI.getNetworks(requestOptions);+ networks = await networkService.getNetworks(requestOptions);}selectedIds = [];}@@ -225,7 +225,7 @@bind:requestOptionsbind:selectedIdsonRemoveSelected={(ids) => handleDeleteSelectedNetworks(ids)}- onRefresh={async (options) => (networks = await environmentAPI.getNetworks(options))}+ onRefresh={async (options) => (networks = await networkService.getNetworks(options))}{columns}rowActions={RowActions}/>diff --git a/frontend/src/routes/onboarding/complete/+page.svelte b/frontend/src/routes/onboarding/complete/+page.svelteindex 5c87a9089..5e3924f4c 100644--- a/frontend/src/routes/onboarding/complete/+page.svelte+++ b/frontend/src/routes/onboarding/complete/+page.svelte@@ -1,11 +1,11 @@<script lang="ts">import { Button } from '$lib/components/ui/button';- import { settingsAPI } from '$lib/services/api';import { toast } from 'svelte-sonner';import { goto, invalidateAll } from '$app/navigation';import LoaderCircleIcon from '@lucide/svelte/icons/loader-circle';import CircleCheckIcon from '@lucide/svelte/icons/check-circle';import ArrowRightIcon from '@lucide/svelte/icons/arrow-right';+ import { settingsService } from '$lib/services/settings-service.js';let { data } = $props();let currentSettings = $state(data.settings);@@ -16,7 +16,7 @@isLoading = true;try {- await settingsAPI.updateSettings({+ await settingsService.updateSettings({...currentSettings,onboardingCompleted: true,onboardingSteps: {diff --git a/frontend/src/routes/onboarding/complete/+page.ts b/frontend/src/routes/onboarding/complete/+page.tsindex 4c62ab239..c7c50c49f 100644--- a/frontend/src/routes/onboarding/complete/+page.ts+++ b/frontend/src/routes/onboarding/complete/+page.ts@@ -1,9 +1,9 @@import { redirect } from '@sveltejs/kit';-import { settingsAPI } from '$lib/services/api';import type { PageLoad } from './$types';+import { settingsService } from '$lib/services/settings-service';export const load: PageLoad = async () => {- const settings = await settingsAPI.getSettings();+ const settings = await settingsService.getSettings();if (settings.onboardingCompleted) {throw redirect(302, '/dashboard');diff --git a/frontend/src/routes/onboarding/docker/+page.svelte b/frontend/src/routes/onboarding/docker/+page.svelteindex de7de1bce..a2c451faf 100644--- a/frontend/src/routes/onboarding/docker/+page.svelte+++ b/frontend/src/routes/onboarding/docker/+page.svelte@@ -12,9 +12,9 @@import { createForm } from '$lib/utils/form.utils';import { z } from 'zod/v4';import { m } from '$lib/paraglide/messages';- import { settingsAPI } from '$lib/services/api';import settingsStore from '$lib/stores/config-store';import type { Settings } from '$lib/types/settings.type';+ import { settingsService } from '$lib/services/settings-service.js';let { data } = $props();let currentSettings = $state<Settings>(data.settings);@@ -82,7 +82,7 @@onboardingSteps: { ...currentSettings.onboardingSteps, docker: true }} as Partial<Settings>;- await settingsAPI.updateSettings(updated as any);+ await settingsService.updateSettings(updated as any);currentSettings = { ...(currentSettings as Settings), ...(updated as Settings) };settingsStore.set(currentSettings);settingsStore.reload();diff --git a/frontend/src/routes/onboarding/docker/+page.ts b/frontend/src/routes/onboarding/docker/+page.tsindex 476d17ce0..c7c50c49f 100644--- a/frontend/src/routes/onboarding/docker/+page.ts+++ b/frontend/src/routes/onboarding/docker/+page.ts@@ -1,9 +1,9 @@import { redirect } from '@sveltejs/kit';import type { PageLoad } from './$types';-import { settingsAPI } from '$lib/services/api';+import { settingsService } from '$lib/services/settings-service';export const load: PageLoad = async () => {- const settings = await settingsAPI.getSettings();+ const settings = await settingsService.getSettings();if (settings.onboardingCompleted) {throw redirect(302, '/dashboard');diff --git a/frontend/src/routes/onboarding/password/+page.svelte b/frontend/src/routes/onboarding/password/+page.svelteindex 9f808ec82..ef7d2c319 100644--- a/frontend/src/routes/onboarding/password/+page.svelte+++ b/frontend/src/routes/onboarding/password/+page.svelte@@ -6,16 +6,16 @@import CircleAlertIcon from '@lucide/svelte/icons/alert-circle';import ChevronRightIcon from '@lucide/svelte/icons/chevron-right';import { preventDefault } from '$lib/utils/form.utils';- import { userAPI } from '$lib/services/api';import { goto } from '$app/navigation';import settingsStore from '$lib/stores/config-store';- import { settingsAPI } from '$lib/services/api';+ import { settingsService } from '$lib/services/settings-service.js';+ import { userService } from '$lib/services/user-service.js';let { data } = $props();let currentSettings = $state(data.settings);async function continueToNextStep() {- const updatedSettings = await settingsAPI.updateSettings({+ const updatedSettings = await settingsService.updateSettings({...currentSettings,onboardingCompleted: false,onboardingSteps: {@@ -52,7 +52,7 @@}try {- await userAPI.changePassword({+ await userService.changePassword({currentPassword: 'arcane-admin',newPassword: password});diff --git a/frontend/src/routes/onboarding/password/+page.ts b/frontend/src/routes/onboarding/password/+page.tsindex 4c62ab239..c7c50c49f 100644--- a/frontend/src/routes/onboarding/password/+page.ts+++ b/frontend/src/routes/onboarding/password/+page.ts@@ -1,9 +1,9 @@import { redirect } from '@sveltejs/kit';-import { settingsAPI } from '$lib/services/api';import type { PageLoad } from './$types';+import { settingsService } from '$lib/services/settings-service';export const load: PageLoad = async () => {- const settings = await settingsAPI.getSettings();+ const settings = await settingsService.getSettings();if (settings.onboardingCompleted) {throw redirect(302, '/dashboard');diff --git a/frontend/src/routes/onboarding/security/+page.svelte b/frontend/src/routes/onboarding/security/+page.svelteindex 6e8a70446..a58ea2bdd 100644--- a/frontend/src/routes/onboarding/security/+page.svelte+++ b/frontend/src/routes/onboarding/security/+page.svelte@@ -9,10 +9,10 @@import LoaderCircleIcon from '@lucide/svelte/icons/loader-circle';import { toast } from 'svelte-sonner';import { goto } from '$app/navigation';- import { settingsAPI } from '$lib/services/api';import { createForm, preventDefault } from '$lib/utils/form.utils';import { z } from 'zod/v4';import { m } from '$lib/paraglide/messages';+ import { settingsService } from '$lib/services/settings-service';let { data }: { data: PageData } = $props();let currentSettings = $state(data.settings);@@ -118,7 +118,7 @@authOidcConfig};- await settingsAPI.updateSettings(payload);+ await settingsService.updateSettings(payload);toast.success(m.security_oidc_saved());showOidcConfigDialog = false;} finally {@@ -142,7 +142,7 @@}};- await settingsAPI.updateSettings(payload);+ await settingsService.updateSettings(payload);goto('/onboarding/settings');} catch {toast.error(m.security_settings_save_failed());diff --git a/frontend/src/routes/onboarding/security/+page.ts b/frontend/src/routes/onboarding/security/+page.tsindex a3a701249..9516e385b 100644--- a/frontend/src/routes/onboarding/security/+page.ts+++ b/frontend/src/routes/onboarding/security/+page.ts@@ -1,11 +1,11 @@import { redirect } from '@sveltejs/kit';import type { PageLoad } from './$types';-import { settingsAPI } from '$lib/services/api';+import { settingsService } from '$lib/services/settings-service';export const load: PageLoad = async () => {const [settings, oidcStatus] = await Promise.all([- settingsAPI.getSettings(),- settingsAPI.getOidcStatus().catch(() => ({+ settingsService.getSettings(),+ settingsService.getOidcStatus().catch(() => ({envForced: false,envConfigured: false}))diff --git a/frontend/src/routes/onboarding/settings/+page.svelte b/frontend/src/routes/onboarding/settings/+page.svelteindex 8e715c6d1..f6c360d36 100644--- a/frontend/src/routes/onboarding/settings/+page.svelte+++ b/frontend/src/routes/onboarding/settings/+page.svelte@@ -3,13 +3,13 @@import * as FieldSet from '$lib/components/ui/field-set';import FormInput from '$lib/components/form/form-input.svelte';import SwitchWithLabel from '$lib/components/form/labeled-switch.svelte';- import { settingsAPI } from '$lib/services/api';import { toast } from 'svelte-sonner';import { goto } from '$app/navigation';import LoaderCircleIcon from '@lucide/svelte/icons/loader-circle';import { createForm, preventDefault } from '$lib/utils/form.utils';import { z } from 'zod/v4';import { m } from '$lib/paraglide/messages';+ import { settingsService } from '$lib/services/settings-service.js';let { data } = $props();let currentSettings = $state(data.settings);@@ -31,7 +31,7 @@isLoading = true;try {- await settingsAPI.updateSettings({+ await settingsService.updateSettings({...currentSettings,...validated,onboardingCompleted: false,diff --git a/frontend/src/routes/onboarding/settings/+page.ts b/frontend/src/routes/onboarding/settings/+page.tsindex 4c62ab239..c7c50c49f 100644--- a/frontend/src/routes/onboarding/settings/+page.ts+++ b/frontend/src/routes/onboarding/settings/+page.ts@@ -1,9 +1,9 @@import { redirect } from '@sveltejs/kit';-import { settingsAPI } from '$lib/services/api';import type { PageLoad } from './$types';+import { settingsService } from '$lib/services/settings-service';export const load: PageLoad = async () => {- const settings = await settingsAPI.getSettings();+ const settings = await settingsService.getSettings();if (settings.onboardingCompleted) {throw redirect(302, '/dashboard');diff --git a/frontend/src/routes/onboarding/welcome/+page.svelte b/frontend/src/routes/onboarding/welcome/+page.svelteindex 5593f0e13..d2a5fae2c 100644--- a/frontend/src/routes/onboarding/welcome/+page.svelte+++ b/frontend/src/routes/onboarding/welcome/+page.svelte@@ -4,13 +4,13 @@import ChevronRightIcon from '@lucide/svelte/icons/chevron-right';import { goto } from '$app/navigation';import settingsStore from '$lib/stores/config-store';- import { settingsAPI } from '$lib/services/api';+ import { settingsService } from '$lib/services/settings-service.js';let { data } = $props();let currentSettings = $state(data.settings);async function continueToNextStep() {- await settingsAPI.updateSettings({+ await settingsService.updateSettings({...currentSettings,onboardingCompleted: false,onboardingSteps: {diff --git a/frontend/src/routes/onboarding/welcome/+page.ts b/frontend/src/routes/onboarding/welcome/+page.tsindex 4c62ab239..c7c50c49f 100644--- a/frontend/src/routes/onboarding/welcome/+page.ts+++ b/frontend/src/routes/onboarding/welcome/+page.ts@@ -1,9 +1,9 @@import { redirect } from '@sveltejs/kit';-import { settingsAPI } from '$lib/services/api';import type { PageLoad } from './$types';+import { settingsService } from '$lib/services/settings-service';export const load: PageLoad = async () => {- const settings = await settingsAPI.getSettings();+ const settings = await settingsService.getSettings();if (settings.onboardingCompleted) {throw redirect(302, '/dashboard');diff --git a/frontend/src/routes/projects/+page.svelte b/frontend/src/routes/projects/+page.svelteindex 06f3527b6..13c60f0b6 100644--- a/frontend/src/routes/projects/+page.svelte+++ b/frontend/src/routes/projects/+page.svelte@@ -6,11 +6,12 @@import { handleApiResultWithCallbacks } from '$lib/utils/api.util';import { tryCatch } from '$lib/utils/try-catch';import { ArcaneButton } from '$lib/components/arcane-button/index.js';- import { environmentAPI } from '$lib/services/api';import StatCard from '$lib/components/stat-card.svelte';import ProjectsTable from './projects-table.svelte';import { goto } from '$app/navigation';import { m } from '$lib/paraglide/messages';+ import { projectService } from '$lib/services/project-service';+ import { imageService } from '$lib/services/image-service';let { data } = $props();@@ -29,12 +30,12 @@async function handleCheckForUpdates() {isLoading.updating = true;handleApiResultWithCallbacks({- result: await tryCatch(environmentAPI.runAutoUpdate()),+ result: await tryCatch(imageService.runAutoUpdate()),message: 'Failed to Check Compose Projects for Updates',setLoadingState: (value) => (isLoading.updating = value),async onSuccess() {toast.success('Compose Projects Updated Successfully.');- projects = await environmentAPI.getProjects(projectRequestOptions);+ projects = await projectService.getProjects(projectRequestOptions);}});}@@ -42,7 +43,7 @@async function refreshCompose() {isLoading.refreshing = true;handleApiResultWithCallbacks({- result: await tryCatch(environmentAPI.getProjects(projectRequestOptions)),+ result: await tryCatch(projectService.getProjects(projectRequestOptions)),message: 'Failed to Refresh Projects',setLoadingState: (v) => (isLoading.refreshing = v),async onSuccess(newProjects) {diff --git a/frontend/src/routes/projects/+page.ts b/frontend/src/routes/projects/+page.tsindex cf014bdd0..2e6c3910e 100644--- a/frontend/src/routes/projects/+page.ts+++ b/frontend/src/routes/projects/+page.ts@@ -1,4 +1,4 @@-import { environmentAPI } from '$lib/services/api';+import { projectService } from '$lib/services/project-service';import type { SearchPaginationSortRequest } from '$lib/types/pagination.type';import type { PageLoad } from './$types';@@ -14,8 +14,8 @@ export const load: PageLoad = async () => {}};- const projects = await environmentAPI.getProjects(projectRequestOptions);- const projectStatusCounts = await environmentAPI.getProjectStatusCounts();+ const projects = await projectService.getProjects(projectRequestOptions);+ const projectStatusCounts = await projectService.getProjectStatusCounts();return { projects, projectRequestOptions, projectStatusCounts };};diff --git a/frontend/src/routes/projects/[projectId]/+page.svelte b/frontend/src/routes/projects/[projectId]/+page.svelteindex 8f6c614e0..39dc3a7bb 100644--- a/frontend/src/routes/projects/[projectId]/+page.svelte+++ b/frontend/src/routes/projects/[projectId]/+page.svelte@@ -17,7 +17,6 @@import { invalidateAll } from '$app/navigation';import { toast } from 'svelte-sonner';import { tryCatch } from '$lib/utils/try-catch';- import { environmentAPI } from '$lib/services/api';import { handleApiResultWithCallbacks } from '$lib/utils/api.util';import { z } from 'zod/v4';import { createForm } from '$lib/utils/form.utils';@@ -26,7 +25,8 @@import EditableName from '../components/EditableName.svelte';import ServicesGrid from '../components/ServicesGrid.svelte';import CodePanel from '../components/CodePanel.svelte';- import StackLogsPanel from '../components/StackLogsPanel.svelte';+ import StackLogsPanel from '../components/ProjectLogsPanel.svelte';+ import { projectService } from '$lib/services/project-service';let { data } = $props();let projectId = $derived(data.projectId);@@ -130,7 +130,7 @@const { name, composeContent, envContent } = validated;handleApiResultWithCallbacks({- result: await tryCatch(environmentAPI.updateProject(projectId, composeContent, envContent)),+ result: await tryCatch(projectService.updateProject(projectId, composeContent, envContent)),message: 'Failed to Save Project',setLoadingState: (value) => (isLoading.saving = value),onSuccess: async (updatedStack: Project) => {diff --git a/frontend/src/routes/projects/[projectId]/+page.ts b/frontend/src/routes/projects/[projectId]/+page.tsindex eb223c9fc..94024bc2b 100644--- a/frontend/src/routes/projects/[projectId]/+page.ts+++ b/frontend/src/routes/projects/[projectId]/+page.ts@@ -1,8 +1,8 @@-import { environmentAPI } from '$lib/services/api';+import { projectService } from '$lib/services/project-service';import type { PageLoad } from './$types';export const load: PageLoad = async ({ params }) => {- const project = await environmentAPI.getProject(params.projectId);+ const project = await projectService.getProject(params.projectId);const editorState = {name: project.name || '',diff --git a/frontend/src/routes/projects/components/CodePanel.svelte b/frontend/src/routes/projects/components/CodePanel.svelteindex a2380228e..dce6989d9 100644--- a/frontend/src/routes/projects/components/CodePanel.svelte+++ b/frontend/src/routes/projects/components/CodePanel.svelte@@ -1,8 +1,5 @@<script lang="ts">- import * as Collapsible from '$lib/components/ui/collapsible/index.js';- import { Button } from '$lib/components/ui/button/index.js';import CodeEditor from '$lib/components/code-editor/editor.svelte';- import { m } from '$lib/paraglide/messages';type CodeLanguage = 'yaml' | 'env';diff --git a/frontend/src/routes/projects/components/StackLogsPanel.svelte b/frontend/src/routes/projects/components/ProjectLogsPanel.sveltesimilarity index 100%rename from frontend/src/routes/projects/components/StackLogsPanel.svelterename to frontend/src/routes/projects/components/ProjectLogsPanel.sveltediff --git a/frontend/src/routes/projects/new/+page.svelte b/frontend/src/routes/projects/new/+page.svelteindex 66da80ac9..ea5292b99 100644--- a/frontend/src/routes/projects/new/+page.svelte+++ b/frontend/src/routes/projects/new/+page.svelte@@ -18,13 +18,14 @@import { Textarea } from '$lib/components/ui/textarea/index.js';import * as Dialog from '$lib/components/ui/dialog/index.js';import TemplateSelectionDialog from '$lib/components/dialogs/template-selection-dialog.svelte';- import { environmentAPI, converterAPI } from '$lib/services/api';import type { Template } from '$lib/types/template.type';import * as DropdownButton from '$lib/components/ui/dropdown-button/index.js';import { z } from 'zod/v4';import { arcaneButtonVariants, actionConfigs } from '$lib/components/arcane-button/variants';import PlusCircleIcon from '@lucide/svelte/icons/plus-circle';import { m } from '$lib/paraglide/messages';+ import { projectService } from '$lib/services/project-service.js';+ import { systemService } from '$lib/services/system-service.js';let { data } = $props();@@ -64,7 +65,7 @@const { name, composeContent, envContent } = validated;handleApiResultWithCallbacks({- result: await tryCatch(environmentAPI.createProject(name, composeContent, envContent)),+ result: await tryCatch(projectService.createProject(name, composeContent, envContent)),message: m.compose_create_failed(),setLoadingState: (value) => (saving = value),onSuccess: async (project) => {@@ -81,7 +82,7 @@}handleApiResultWithCallbacks({- result: await tryCatch(converterAPI.convert(dockerRunCommand)),+ result: await tryCatch(systemService.convert(dockerRunCommand)),message: m.compose_convert_failed(),setLoadingState: (value) => (converting = value),onSuccess: (data) => {diff --git a/frontend/src/routes/projects/new/+page.ts b/frontend/src/routes/projects/new/+page.tsindex 2f15fbd26..e1527dea2 100644--- a/frontend/src/routes/projects/new/+page.ts+++ b/frontend/src/routes/projects/new/+page.ts@@ -1,13 +1,13 @@-import { templateAPI } from '$lib/services/api';import { defaultComposeTemplate } from '$lib/constants';+import { templateService } from '$lib/services/template-service';export const load = async () => {const [allTemplates, envTemplate] = await Promise.all([- templateAPI.loadAll().catch((err) => {+ templateService.loadAll().catch((err) => {console.warn('Failed to load templates:', err);return [];}),- templateAPI.getEnvTemplate().catch((err) => {+ templateService.getEnvTemplate().catch((err) => {console.warn('Failed to load env template:', err);return '';})diff --git a/frontend/src/routes/projects/projects-table.svelte b/frontend/src/routes/projects/projects-table.svelteindex 7b34745a9..265543d01 100644--- a/frontend/src/routes/projects/projects-table.svelte+++ b/frontend/src/routes/projects/projects-table.svelte@@ -17,13 +17,13 @@import StatusBadge from '$lib/components/badges/status-badge.svelte';import { handleApiResultWithCallbacks } from '$lib/utils/api.util';import { tryCatch } from '$lib/utils/try-catch';- import { environmentAPI } from '$lib/services/api';import type { Paginated, SearchPaginationSortRequest } from '$lib/types/pagination.type';import { getStatusVariant } from '$lib/utils/status.utils';import { capitalizeFirstLetter } from '$lib/utils/string.utils';import { format } from 'date-fns';import type { ColumnSpec } from '$lib/components/arcane-table';import { m } from '$lib/paraglide/messages';+ import { projectService } from '$lib/services/project-service';let {projects = $bindable(),@@ -51,42 +51,42 @@try {if (action === 'start') {handleApiResultWithCallbacks({- result: await tryCatch(environmentAPI.deployProject(id)),+ result: await tryCatch(projectService.deployProject(id)),message: m.compose_start_failed(),setLoadingState: (value) => (isLoading.start = value),onSuccess: async () => {toast.success(m.compose_start_success());- projects = await environmentAPI.getProjects(requestOptions);+ projects = await projectService.getProjects(requestOptions);}});} else if (action === 'stop') {handleApiResultWithCallbacks({- result: await tryCatch(environmentAPI.downProject(id)),+ result: await tryCatch(projectService.downProject(id)),message: m.compose_stop_failed(),setLoadingState: (value) => (isLoading.stop = value),onSuccess: async () => {toast.success(m.compose_stop_success());- projects = await environmentAPI.getProjects(requestOptions);+ projects = await projectService.getProjects(requestOptions);}});} else if (action === 'restart') {handleApiResultWithCallbacks({- result: await tryCatch(environmentAPI.restartProject(id)),+ result: await tryCatch(projectService.restartProject(id)),message: m.compose_restart_failed(),setLoadingState: (value) => (isLoading.restart = value),onSuccess: async () => {toast.success(m.compose_restart_success());- projects = await environmentAPI.getProjects(requestOptions);+ projects = await projectService.getProjects(requestOptions);}});} else if (action === 'pull') {handleApiResultWithCallbacks({- result: await tryCatch(environmentAPI.pullProjectImages(id)),+ result: await tryCatch(projectService.pullProjectImages(id)),message: m.compose_pull_failed(),setLoadingState: (value) => (isLoading.pull = value),onSuccess: async () => {toast.success(m.compose_pull_success());- projects = await environmentAPI.getProjects(requestOptions);+ projects = await projectService.getProjects(requestOptions);}});} else if (action === 'destroy') {@@ -113,12 +113,12 @@const removeFiles = !!(result?.checkboxes?.files ?? result?.files);handleApiResultWithCallbacks({- result: await tryCatch(environmentAPI.destroyProject(id, removeVolumes, removeFiles)),+ result: await tryCatch(projectService.destroyProject(id, removeVolumes, removeFiles)),message: m.compose_destroy_failed(),setLoadingState: (value) => (isLoading.destroy = value),onSuccess: async () => {toast.success(m.compose_destroy_success());- projects = await environmentAPI.getProjects(requestOptions);+ projects = await projectService.getProjects(requestOptions);}});}@@ -239,7 +239,7 @@items={projects}bind:requestOptionsbind:selectedIds- onRefresh={async (options) => (projects = await environmentAPI.getProjects(options))}+ onRefresh={async (options) => (projects = await projectService.getProjects(options))}{columns}rowActions={RowActions}/>diff --git a/frontend/src/routes/settings/+page.svelte b/frontend/src/routes/settings/+page.svelteindex f79f3ea7c..5e01a2f40 100644--- a/frontend/src/routes/settings/+page.svelte+++ b/frontend/src/routes/settings/+page.svelte@@ -1,6 +1,5 @@<script lang="ts">import { goto } from '$app/navigation';- import { page } from '$app/state';import SearchIcon from '@lucide/svelte/icons/search';import SettingsIcon from '@lucide/svelte/icons/settings';import DatabaseIcon from '@lucide/svelte/icons/database';@@ -10,9 +9,6 @@import { Button } from '$lib/components/ui/button';import { Card } from '$lib/components/ui/card';import { m } from '$lib/paraglide/messages';- import type { Settings } from '$lib/types/settings.type';- import settingsStore from '$lib/stores/config-store';- import { settingsAPI } from '$lib/services/api';import UiConfigDisabledTag from '$lib/components/ui-config-disabled-tag.svelte';interface SettingMeta {@@ -36,7 +32,6 @@}let { data } = $props();- let currentSettings = $state(data.settings);let searchQuery = $state('');let showSearchResults = $state(false);let searchResults = $state<SettingsCategory[]>([]);@@ -257,7 +252,7 @@<div class="bg-muted/40 pointer-events-none absolute -bottom-10 -left-10 size-40 rounded-full blur-3xl"></div><div class="relative"><div class="flex flex-col gap-4 sm:flex-row sm:items-start sm:justify-between">- <div class="flex items-start gap-3 sm:gap-4 w-full">+ <div class="flex w-full items-start gap-3 sm:gap-4"><divclass="bg-primary/10 text-primary ring-primary/20 flex size-8 shrink-0 items-center justify-center rounded-lg ring-1 sm:size-10">@@ -265,7 +260,7 @@</div><div class="min-w-0 flex-1"><div class="flex items-start justify-between gap-3">- <h1 class="text-xl font-bold tracking-tight sm:text-2xl min-w-0">{m.sidebar_settings()}</h1>+ <h1 class="min-w-0 text-xl font-bold tracking-tight sm:text-2xl">{m.sidebar_settings()}</h1><div class="shrink-0"><UiConfigDisabledTag /></div>@@ -277,7 +272,7 @@<!-- Search Bar --><div class="relative mt-4 w-full sm:mt-6 sm:max-w-md">- <SearchIcon class="text-muted-foreground absolute left-3 top-1/2 size-4 -translate-y-1/2 z-10" />+ <SearchIcon class="text-muted-foreground absolute left-3 top-1/2 z-10 size-4 -translate-y-1/2" /><inputtype="text"placeholder="Search settings..."diff --git a/frontend/src/routes/settings/+page.ts b/frontend/src/routes/settings/+page.tsindex 060092bf7..2ba02121f 100644--- a/frontend/src/routes/settings/+page.ts+++ b/frontend/src/routes/settings/+page.ts@@ -1,12 +1,9 @@-import { settingsAPI } from '$lib/services/api';+import { settingsService } from '$lib/services/settings-service';import type { PageLoad } from './$types';export const load: PageLoad = async () => {try {- const [settings, oidcStatus] = await Promise.all([- settingsAPI.getSettings(),- settingsAPI.getOidcStatus()- ]);+ const [settings, oidcStatus] = await Promise.all([settingsService.getSettings(), settingsService.getOidcStatus()]);return {settings,diff --git a/frontend/src/routes/settings/docker/+page.svelte b/frontend/src/routes/settings/docker/+page.svelteindex c4a9541a2..f1329be5c 100644--- a/frontend/src/routes/settings/docker/+page.svelte+++ b/frontend/src/routes/settings/docker/+page.svelte@@ -1,18 +1,18 @@<script lang="ts">import type { Settings } from '$lib/types/settings.type';import settingsStore from '$lib/stores/config-store';- import { settingsAPI } from '$lib/services/api';import UiConfigDisabledTag from '$lib/components/ui-config-disabled-tag.svelte';import DockerSettingsForm from '../forms/docker-settings-form.svelte';import BoxesIcon from '@lucide/svelte/icons/boxes';import { m } from '$lib/paraglide/messages';import { getContext } from 'svelte';+ import { settingsService } from '$lib/services/settings-service';let { data } = $props();let currentSettings = $state<Settings>(data.settings);let hasChanges = $state(false);let isLoading = $state(false);-+const isReadOnly = $derived.by(() => $settingsStore.uiConfigDisabled);const formState = getContext('settingsFormState') as any;@@ -26,7 +26,7 @@async function updateSettingsConfig(updatedSettings: Partial<Settings>) {try {- await settingsAPI.updateSettings(updatedSettings as any);+ await settingsService.updateSettings(updatedSettings as any);currentSettings = { ...currentSettings, ...updatedSettings };@@ -53,7 +53,7 @@</div><div class="min-w-0 flex-1"><div class="flex items-start justify-between gap-3">- <h1 class="settings-title text-xl sm:text-3xl min-w-0">{m.docker_title()}</h1>+ <h1 class="settings-title min-w-0 text-xl sm:text-3xl">{m.docker_title()}</h1>{#if isReadOnly}<div class="shrink-0"><UiConfigDisabledTag />@@ -69,4 +69,3 @@<DockerSettingsForm settings={currentSettings} callback={updateSettingsConfig} bind:hasChanges bind:isLoading /></div></div>-diff --git a/frontend/src/routes/settings/docker/+page.ts b/frontend/src/routes/settings/docker/+page.tsindex 8dd0fa65e..8889f2f4b 100644--- a/frontend/src/routes/settings/docker/+page.ts+++ b/frontend/src/routes/settings/docker/+page.ts@@ -1,7 +1,7 @@-import { settingsAPI } from '$lib/services/api';+import { settingsService } from '$lib/services/settings-service';export const load = async () => {- const settings = await settingsAPI.getSettings();+ const settings = await settingsService.getSettings();return {settingsdiff --git a/frontend/src/routes/settings/general/+page.svelte b/frontend/src/routes/settings/general/+page.svelteindex 8ac943dce..a38eacf77 100644--- a/frontend/src/routes/settings/general/+page.svelte+++ b/frontend/src/routes/settings/general/+page.svelte@@ -1,18 +1,18 @@<script lang="ts">import type { Settings } from '$lib/types/settings.type';import settingsStore from '$lib/stores/config-store';- import { settingsAPI } from '$lib/services/api';import UiConfigDisabledTag from '$lib/components/ui-config-disabled-tag.svelte';import GeneralSettingsForm from '../forms/general-settings-form.svelte';import SettingsIcon from '@lucide/svelte/icons/settings';import { m } from '$lib/paraglide/messages';import { getContext } from 'svelte';+ import { settingsService } from '$lib/services/settings-service';let { data } = $props();let currentSettings = $state(data.settings);let hasChanges = $state(false);let isLoading = $state(false);-+const isReadOnly = $derived.by(() => $settingsStore.uiConfigDisabled);const formState = getContext('settingsFormState') as any;@@ -26,7 +26,7 @@async function updateSettingsConfig(updatedSettings: Partial<Settings>) {try {- await settingsAPI.updateSettings(updatedSettings as any);+ await settingsService.updateSettings(updatedSettings as any);currentSettings = { ...currentSettings, ...updatedSettings };settingsStore.set(currentSettings);settingsStore.reload();@@ -51,7 +51,7 @@</div><div class="min-w-0 flex-1"><div class="flex items-start justify-between gap-3">- <h1 class="settings-title text-xl sm:text-3xl min-w-0">{m.general_title()}</h1>+ <h1 class="settings-title min-w-0 text-xl sm:text-3xl">{m.general_title()}</h1>{#if isReadOnly}<div class="shrink-0"><UiConfigDisabledTag />@@ -67,4 +67,3 @@<GeneralSettingsForm settings={currentSettings} callback={updateSettingsConfig} bind:hasChanges bind:isLoading /></div></div>-diff --git a/frontend/src/routes/settings/general/+page.ts b/frontend/src/routes/settings/general/+page.tsindex 8dd0fa65e..8889f2f4b 100644--- a/frontend/src/routes/settings/general/+page.ts+++ b/frontend/src/routes/settings/general/+page.ts@@ -1,7 +1,7 @@-import { settingsAPI } from '$lib/services/api';+import { settingsService } from '$lib/services/settings-service';export const load = async () => {- const settings = await settingsAPI.getSettings();+ const settings = await settingsService.getSettings();return {settingsdiff --git a/frontend/src/routes/settings/security/+page.svelte b/frontend/src/routes/settings/security/+page.svelteindex dd005a982..f885766a1 100644--- a/frontend/src/routes/settings/security/+page.svelte+++ b/frontend/src/routes/settings/security/+page.svelte@@ -2,18 +2,18 @@import type { PageData } from './$types';import type { Settings } from '$lib/types/settings.type';import settingsStore from '$lib/stores/config-store';- import { settingsAPI } from '$lib/services/api';import UiConfigDisabledTag from '$lib/components/ui-config-disabled-tag.svelte';import SecuritySettingsForm from '../forms/security-settings-form.svelte';import LockIcon from '@lucide/svelte/icons/lock';import { m } from '$lib/paraglide/messages';import { getContext } from 'svelte';+ import { settingsService } from '$lib/services/settings-service';let { data }: { data: PageData } = $props();let currentSettings = $state<Settings>(data.settings);let hasChanges = $state(false);let isLoading = $state(false);-+const isReadOnly = $derived.by(() => $settingsStore.uiConfigDisabled);const formState = getContext('settingsFormState') as any;@@ -27,7 +27,7 @@async function updateSettingsConfig(updatedSettings: Partial<Settings>) {try {- await settingsAPI.updateSettings(updatedSettings as any);+ await settingsService.updateSettings(updatedSettings as any);currentSettings = { ...currentSettings, ...updatedSettings };settingsStore.set(currentSettings);settingsStore.reload();@@ -52,7 +52,7 @@</div><div class="min-w-0 flex-1"><div class="flex items-start justify-between gap-3">- <h1 class="settings-title text-xl sm:text-3xl min-w-0">{m.security_title()}</h1>+ <h1 class="settings-title min-w-0 text-xl sm:text-3xl">{m.security_title()}</h1>{#if isReadOnly}<div class="shrink-0"><UiConfigDisabledTag />@@ -74,4 +74,3 @@/></div></div>-diff --git a/frontend/src/routes/settings/security/+page.ts b/frontend/src/routes/settings/security/+page.tsindex f00fa13b8..9bb411200 100644--- a/frontend/src/routes/settings/security/+page.ts+++ b/frontend/src/routes/settings/security/+page.ts@@ -1,9 +1,9 @@-import { settingsAPI } from '$lib/services/api';+import { settingsService } from '$lib/services/settings-service';export const load = async () => {const [settings, oidcStatus] = await Promise.all([- settingsAPI.getSettings(),- settingsAPI.getOidcStatus().catch(() => ({+ settingsService.getSettings(),+ settingsService.getOidcStatus().catch(() => ({envForced: false,envConfigured: false}))diff --git a/frontend/src/routes/settings/users/+page.svelte b/frontend/src/routes/settings/users/+page.svelteindex 87e60efa1..2f82f5399 100644--- a/frontend/src/routes/settings/users/+page.svelte+++ b/frontend/src/routes/settings/users/+page.svelte@@ -6,7 +6,6 @@import { handleApiResultWithCallbacks } from '$lib/utils/api.util';import { tryCatch } from '$lib/utils/try-catch';import { ArcaneButton } from '$lib/components/arcane-button/index.js';- import { userAPI } from '$lib/services/api';import StatCard from '$lib/components/stat-card.svelte';import UserTable from './user-table.svelte';import UserFormSheet from '$lib/components/sheets/user-form-sheet.svelte';@@ -14,6 +13,7 @@import type { User } from '$lib/types/user.type';import type { CreateUser } from '$lib/types/user.type';import { m } from '$lib/paraglide/messages';+ import { userService } from '$lib/services/user-service';let { data } = $props();@@ -63,14 +63,14 @@try {if (isEditMode && userId) {const safeUsername = user.username?.trim() || m.common_unknown();- const result = await tryCatch(userAPI.update(userId, user));+ const result = await tryCatch(userService.update(userId, user));handleApiResultWithCallbacks({result,message: m.users_update_failed({ username: safeUsername }),setLoadingState: (value) => (isLoading[loading] = value),onSuccess: async () => {toast.success(m.users_update_success({ username: safeUsername }));- users = await userAPI.getUsers(requestOptions);+ users = await userService.getUsers(requestOptions);isDialogOpen.edit = false;userToEdit = null;}@@ -92,14 +92,14 @@roles: user.roles ?? ['user']};- const result = await tryCatch(userAPI.create(createUser));+ const result = await tryCatch(userService.create(createUser));handleApiResultWithCallbacks({result,message: m.users_create_failed({ username: safeUsername }),setLoadingState: (value) => (isLoading[loading] = value),onSuccess: async () => {toast.success(m.users_create_success({ username: safeUsername }));- users = await userAPI.getUsers(requestOptions);+ users = await userService.getUsers(requestOptions);isDialogOpen.create = false;}});@@ -124,8 +124,8 @@</div><div class="min-w-0 flex-1"><div class="flex items-start justify-between gap-3">- <h1 class="settings-title text-xl sm:text-3xl min-w-0">{m.users_title()}</h1>- <div class="flex items-center gap-2 shrink-0">+ <h1 class="settings-title min-w-0 text-xl sm:text-3xl">{m.users_title()}</h1>+ <div class="flex shrink-0 items-center gap-2"><ArcaneButtonaction="create"customLabel={m.users_create_button()}@@ -140,40 +140,40 @@</div></div>- <div class="space-y-4 sm:space-y-6 mt-6 sm:mt-8">- <div class="grid grid-cols-1 gap-3 sm:gap-4 sm:grid-cols-3">- <StatCard- title={m.users_total()}- value={totalUsers}- icon={UsersIcon}- iconColor="text-blue-500"- class="border-l-4 border-l-blue-500"- />- <StatCard- title={m.users_administrators()}- value={adminUsers}- icon={ShieldIcon}- iconColor="text-red-500"- class="border-l-4 border-l-red-500"- />- <StatCard- title={m.users_regular()}- value={regularUsers}- icon={UserCheckIcon}- iconColor="text-green-500"- class="border-l-4 border-l-green-500"- />+ <div class="mt-6 space-y-4 sm:mt-8 sm:space-y-6">+ <div class="grid grid-cols-1 gap-3 sm:grid-cols-3 sm:gap-4">+ <StatCard+ title={m.users_total()}+ value={totalUsers}+ icon={UsersIcon}+ iconColor="text-blue-500"+ class="border-l-4 border-l-blue-500"+ />+ <StatCard+ title={m.users_administrators()}+ value={adminUsers}+ icon={ShieldIcon}+ iconColor="text-red-500"+ class="border-l-4 border-l-red-500"+ />+ <StatCard+ title={m.users_regular()}+ value={regularUsers}+ icon={UserCheckIcon}+ iconColor="text-green-500"+ class="border-l-4 border-l-green-500"+ /></div><UserTable- bind:users- bind:selectedIds- bind:requestOptions- onUsersChanged={async () => {- users = await userAPI.getUsers(requestOptions);- }}- onEditUser={openEditDialog}- />+ bind:users+ bind:selectedIds+ bind:requestOptions+ onUsersChanged={async () => {+ users = await userService.getUsers(requestOptions);+ }}+ onEditUser={openEditDialog}+ /><UserFormSheetbind:open={isDialogOpen.create}diff --git a/frontend/src/routes/settings/users/+page.ts b/frontend/src/routes/settings/users/+page.tsindex c6a558289..165565917 100644--- a/frontend/src/routes/settings/users/+page.ts+++ b/frontend/src/routes/settings/users/+page.ts@@ -1,8 +1,9 @@-import { settingsAPI, userAPI } from '$lib/services/api';+import { settingsService } from '$lib/services/settings-service';+import { userService } from '$lib/services/user-service';import type { SearchPaginationSortRequest } from '$lib/types/pagination.type';export const load = async () => {- const settings = await settingsAPI.getSettings();+ const settings = await settingsService.getSettings();const userRequestOptions: SearchPaginationSortRequest = {pagination: {@@ -15,7 +16,7 @@ export const load = async () => {}};- const users = await userAPI.getUsers(userRequestOptions);+ const users = await userService.getUsers(userRequestOptions);return {settings,diff --git a/frontend/src/routes/settings/users/user-table.svelte b/frontend/src/routes/settings/users/user-table.svelteindex ecad42497..f6c28fd9e 100644--- a/frontend/src/routes/settings/users/user-table.svelte+++ b/frontend/src/routes/settings/users/user-table.svelte@@ -11,11 +11,11 @@import StatusBadge from '$lib/components/badges/status-badge.svelte';import { handleApiResultWithCallbacks } from '$lib/utils/api.util';import { tryCatch } from '$lib/utils/try-catch';- import { userAPI } from '$lib/services/api';import type { Paginated, SearchPaginationSortRequest } from '$lib/types/pagination.type';import type { User } from '$lib/types/user.type';import type { ColumnSpec } from '$lib/components/arcane-table';import { m } from '$lib/paraglide/messages';+ import { userService } from '$lib/services/user-service';let {users = $bindable(),@@ -50,7 +50,7 @@let failureCount = 0;for (const userId of selectedIds) {- const result = await tryCatch(userAPI.delete(userId));+ const result = await tryCatch(userService.delete(userId));handleApiResultWithCallbacks({result,message: m.users_delete_selected_item_failed({ id: userId }),@@ -95,7 +95,7 @@action: async () => {isLoading.removing = true;handleApiResultWithCallbacks({- result: await tryCatch(userAPI.delete(userId)),+ result: await tryCatch(userService.delete(userId)),message: m.users_delete_user_failed({ username: safeName }),setLoadingState: (value) => (isLoading.removing = value),onSuccess: async () => {diff --git a/frontend/src/routes/volumes/+page.svelte b/frontend/src/routes/volumes/+page.svelteindex b9dcf362f..f62724689 100644--- a/frontend/src/routes/volumes/+page.svelte+++ b/frontend/src/routes/volumes/+page.svelte@@ -8,10 +8,10 @@import CreateVolumeSheet from '$lib/components/sheets/create-volume-sheet.svelte';import type { VolumeCreateOptions } from 'dockerode';import { ArcaneButton } from '$lib/components/arcane-button/index.js';- import { environmentAPI } from '$lib/services/api';import StatCard from '$lib/components/stat-card.svelte';import VolumeTable from './volume-table.svelte';import { m } from '$lib/paraglide/messages';+ import { volumeService } from '$lib/services/volume-service';let { data } = $props();@@ -34,12 +34,12 @@isLoading.creating = true;const name = options.Name?.trim() || m.common_unknown();handleApiResultWithCallbacks({- result: await tryCatch(environmentAPI.createVolume(options)),+ result: await tryCatch(volumeService.createVolume(options)),message: m.volumes_create_failed({ name }),setLoadingState: (value) => (isLoading.creating = value),onSuccess: async () => {toast.success(m.volumes_created_success({ name }));- volumes = await environmentAPI.getVolumes(requestOptions);+ volumes = await volumeService.getVolumes(requestOptions);isCreateDialogOpen = false;}});@@ -48,7 +48,7 @@async function refreshVolumes() {isLoading.refresh = true;handleApiResultWithCallbacks({- result: await tryCatch(environmentAPI.getVolumes(requestOptions)),+ result: await tryCatch(volumeService.getVolumes(requestOptions)),message: m.volumes_refresh_failed(),setLoadingState: (value) => (isLoading.refresh = value),async onSuccess(newVolumes) {diff --git a/frontend/src/routes/volumes/+page.ts b/frontend/src/routes/volumes/+page.tsindex bb17f81ca..c25f66452 100644--- a/frontend/src/routes/volumes/+page.ts+++ b/frontend/src/routes/volumes/+page.ts@@ -1,4 +1,4 @@-import { environmentAPI } from '$lib/services/api';+import { volumeService } from '$lib/services/volume-service';import type { SearchPaginationSortRequest } from '$lib/types/pagination.type';import type { PageLoad } from './$types';@@ -14,8 +14,8 @@ export const load: PageLoad = async () => {}};- const volumes = await environmentAPI.getVolumes(volumeRequestOptions);- const volumeUsageCounts = await environmentAPI.getVolumeUsageCounts();+ const volumes = await volumeService.getVolumes(volumeRequestOptions);+ const volumeUsageCounts = await volumeService.getVolumeUsageCounts();return { volumes, volumeRequestOptions, volumeUsageCounts };};diff --git a/frontend/src/routes/volumes/[volumeName]/+page.svelte b/frontend/src/routes/volumes/[volumeName]/+page.svelteindex 51e412630..476a86373 100644--- a/frontend/src/routes/volumes/[volumeName]/+page.svelte+++ b/frontend/src/routes/volumes/[volumeName]/+page.svelte@@ -16,10 +16,10 @@import { tryCatch } from '$lib/utils/try-catch';import { handleApiResultWithCallbacks } from '$lib/utils/api.util';import { ArcaneButton } from '$lib/components/arcane-button/index.js';- import { environmentAPI } from '$lib/services/api';import { format } from 'date-fns';import ContainerIcon from '@lucide/svelte/icons/container';import { m } from '$lib/paraglide/messages';+ import { volumeService } from '$lib/services/volume-service.js';let { data } = $props();let volume = $state(data.volume);@@ -43,7 +43,7 @@destructive: true,action: async () => {handleApiResultWithCallbacks({- result: await tryCatch(environmentAPI.deleteVolume(safeName)),+ result: await tryCatch(volumeService.deleteVolume(safeName)),message: m.volumes_remove_failed({ name: safeName }),setLoadingState: (value) => (isLoading.remove = value),onSuccess: async () => {diff --git a/frontend/src/routes/volumes/[volumeName]/+page.ts b/frontend/src/routes/volumes/[volumeName]/+page.tsindex 5bb4a6eab..74b74bed8 100644--- a/frontend/src/routes/volumes/[volumeName]/+page.ts+++ b/frontend/src/routes/volumes/[volumeName]/+page.ts@@ -1,14 +1,15 @@import type { PageLoad } from './$types';-import { environmentAPI } from '$lib/services/api';import { error } from '@sveltejs/kit';import type { VolumeUsageDto } from '$lib/types/volume.type';+import { volumeService } from '$lib/services/volume-service';+import { containerService } from '$lib/services/container-service';export const load: PageLoad = async ({ params }) => {const { volumeName } = params;try {- const volumeBase = await environmentAPI.getVolume(volumeName);- const usageRes = await environmentAPI.getVolumeUsage(volumeName);+ const volumeBase = await volumeService.getVolume(volumeName);+ const usageRes = await volumeService.getVolumeUsage(volumeName);const usage: VolumeUsageDto = (usageRes && typeof usageRes === 'object' && 'data' in usageRes ? (usageRes as any).data : usageRes@@ -24,7 +25,7 @@ export const load: PageLoad = async ({ params }) => {containersDetailed = await Promise.all(volume.containers.map(async (id: string) => {try {- const c = await environmentAPI.getContainer(id);+ const c = await containerService.getContainer(id);const idVal = (c?.id || c?.Id || id) as string;const nameVal = (c?.name ||c?.Name ||diff --git a/frontend/src/routes/volumes/volume-table.svelte b/frontend/src/routes/volumes/volume-table.svelteindex 8db261770..82c69fd09 100644--- a/frontend/src/routes/volumes/volume-table.svelte+++ b/frontend/src/routes/volumes/volume-table.svelte@@ -14,11 +14,11 @@import { tryCatch } from '$lib/utils/try-catch';import { format } from 'date-fns';import { truncateString } from '$lib/utils/string.utils';- import { environmentAPI } from '$lib/services/api';import type { Paginated, SearchPaginationSortRequest } from '$lib/types/pagination.type';import type { VolumeSummaryDto } from '$lib/types/volume.type';import type { ColumnSpec } from '$lib/components/arcane-table';import { m } from '$lib/paraglide/messages';+ import { volumeService } from '$lib/services/volume-service';let {volumes = $bindable(),@@ -45,12 +45,12 @@action: async () => {isLoading.removing = true;handleApiResultWithCallbacks({- result: await tryCatch(environmentAPI.deleteVolume(safeName)),+ result: await tryCatch(volumeService.deleteVolume(safeName)),message: m.volumes_remove_failed({ name: safeName }),setLoadingState: (value) => (isLoading.removing = value),onSuccess: async () => {toast.success(m.volumes_remove_success({ name: safeName }));- volumes = await environmentAPI.getVolumes(requestOptions);+ volumes = await volumeService.getVolumes(requestOptions);}});}@@ -69,7 +69,7 @@for (const id of ids) {const name = idToName.get(id);const safeName = name?.trim() || m.common_unknown();- const result = await tryCatch(environmentAPI.deleteVolume(safeName));+ const result = await tryCatch(volumeService.deleteVolume(safeName));handleApiResultWithCallbacks({result,message: m.volumes_remove_failed({ name: safeName }),@@ -86,7 +86,7 @@const successMsg =successCount === 1 ? m.volumes_bulk_remove_success_one() : m.volumes_bulk_remove_success_many({ count: successCount });toast.success(successMsg);- volumes = await environmentAPI.getVolumes(requestOptions);+ volumes = await volumeService.getVolumes(requestOptions);}if (failureCount > 0) {const failureMsg =@@ -167,7 +167,7 @@bind:requestOptionsbind:selectedIdsonRemoveSelected={(ids) => handleDeleteSelected(ids)}- onRefresh={async (options) => (volumes = await environmentAPI.getVolumes(options))}+ onRefresh={async (options) => (volumes = await volumeService.getVolumes(options))}{columns}rowActions={RowActions}/>diff --git a/tests/spec/containers.spec.ts b/tests/spec/containers.spec.tsindex 2e6612a0d..1a8baf0bb 100644--- a/tests/spec/containers.spec.ts+++ b/tests/spec/containers.spec.ts@@ -1,5 +1,6 @@import { test, expect, type Page } from '@playwright/test';-import { fetchContainersWithRetry, type ContainerSummary, type Paginated } from '../utils/fetch.util';+import { fetchContainersWithRetry, type Paginated } from '../utils/fetch.util';+import { ContainerSummary } from 'types/containers.type';const CONTAINERS_ROUTE = '/containers';diff --git a/tests/spec/converter.spec.ts b/tests/spec/converter.spec.tsindex 4916d32a9..2ca36a1bf 100644--- a/tests/spec/converter.spec.ts+++ b/tests/spec/converter.spec.ts@@ -9,7 +9,7 @@ type ConvertResponse = {const ROUTES = {page: '/projects/new',- apiConvert: '/api/convert',+ apiConvert: '/api/environments/0/system/convert',};const SELECTORS = {diff --git a/tests/spec/images.spec.ts b/tests/spec/images.spec.tsindex 47561f1d1..cd86230ff 100644--- a/tests/spec/images.spec.ts+++ b/tests/spec/images.spec.ts@@ -1,5 +1,6 @@import { test, expect, type Page } from '@playwright/test';-import { fetchImagesWithRetry } from '../utils/fetch.util';+import { fetchImageCountsWithRetry, fetchImagesWithRetry } from '../utils/fetch.util';+import { ImageUsageCounts } from 'types/image.type';const ROUTES = {page: '/images',@@ -12,6 +13,7 @@ async function navigateToImages(page: Page) {}let realImages: any[] = [];+let imageCounts: ImageUsageCounts = { imagesInuse: 0, imagesUnused: 0, totalImages: 0, totalImageSize: 0 };test.beforeEach(async ({ page }) => {await navigateToImages(page);@@ -19,6 +21,7 @@ test.beforeEach(async ({ page }) => {try {const images = await fetchImagesWithRetry(page);realImages = Array.isArray(images) ? images : [];+ imageCounts = await fetchImageCountsWithRetry(page);} catch {realImages = [];}@@ -35,7 +38,7 @@ test.describe('Images Page', () => {test('should display stats cards with correct counts and size', async ({ page }) => {await navigateToImages(page);- await expect(page.locator('p:has-text("Total Images") + p')).toHaveText(realImages.length.toString());+ await expect(page.locator('p:has-text("Total Images") + p')).toHaveText(imageCounts.totalImages.toString());await expect(page.locator('p:has-text("Total Size") + p')).not.toBeEmpty();});@@ -89,7 +92,6 @@ test.describe('Images Page', () => {const firstRow = await page.getByRole('row', { name: 'ghcr.io/linuxserver/radarr' });await firstRow.getByRole('button', { name: 'Open menu' }).click();await page.getByRole('menuitem', { name: 'Remove' }).click();- console.log(firstRow);await expect(page.locator('div[role="heading"][aria-level="2"][data-dialog-title]:has-text("Remove Image")')).toBeVisible();diff --git a/tests/spec/network.spec.ts b/tests/spec/network.spec.tsindex 5f02dba89..690abe93a 100644--- a/tests/spec/network.spec.ts+++ b/tests/spec/network.spec.ts@@ -1,5 +1,6 @@import { test, expect, type Page } from '@playwright/test';-import { fetchNetworksWithRetry, type NetworkSummary } from '../utils/fetch.util';+import { fetchNetworksCountsWithRetry, fetchNetworksWithRetry } from '../utils/fetch.util';+import { NetworkSummary, NetworkUsageCounts } from 'types/networks.type';async function navigateToNetworks(page: Page) {await page.goto('/networks');@@ -7,10 +8,12 @@ async function navigateToNetworks(page: Page) {}let realNetworks: NetworkSummary[] = [];+let networkCount: NetworkUsageCounts = { networksInuse: 0, networksUnused: 0, totalNetworks: 0 };test.beforeEach(async ({ page }) => {await navigateToNetworks(page);realNetworks = await fetchNetworksWithRetry(page).catch(() => []);+ networkCount = await fetchNetworksCountsWithRetry(page);});test.describe('Networks Page', () => {@@ -22,9 +25,8 @@ test.describe('Networks Page', () => {test('Stat cards show correct counts', async ({ page }) => {await navigateToNetworks(page);- const total = realNetworks.length;- await expect(page.locator('p:has-text("Total Networks") + p')).toHaveText(String(total));- await expect(page.locator('p:has-text("Unused Networks") + p')).toBeVisible();+ await expect(page.locator('p:has-text("Total Networks") + p')).toHaveText(String(networkCount.totalNetworks));+ await expect(page.locator('p:has-text("Unused Networks") + p')).toHaveText(String(networkCount.networksUnused));});test('Table displays when networks exist, else empty state', async ({ page }) => {diff --git a/tests/spec/project.spec.ts b/tests/spec/project.spec.tsindex 9e2088b09..63f7afe90 100644--- a/tests/spec/project.spec.ts+++ b/tests/spec/project.spec.ts@@ -1,5 +1,6 @@import { test, expect, type Page } from '@playwright/test';-import { fetchProjectsWithRetry, type Project } from '../utils/fetch.util';+import { fetchProjectCountsWithRetry, fetchProjectsWithRetry } from '../utils/fetch.util';+import { Project, ProjectStatusCounts } from 'types/project.type';const ROUTES = {page: '/projects',@@ -13,12 +14,14 @@ async function navigateToProjects(page: Page) {}let realProjects: Project[] = [];+let projectCounts: ProjectStatusCounts = { runningProjects: 0, stoppedProjects: 0, totalProjects: 0 };test.beforeEach(async ({ page }) => {await navigateToProjects(page);try {realProjects = await fetchProjectsWithRetry(page);+ projectCounts = await fetchProjectCountsWithRetry(page);} catch (error) {realProjects = [];}@@ -35,9 +38,9 @@ test.describe('Projects Page', () => {});test('should display summary cards with correct counts', async ({ page }) => {- await expect(page.getByText('Total Projects')).toBeVisible();- await expect(page.getByText('Running')).toBeVisible();- await expect(page.getByText('Stopped').first()).toBeVisible();+ await expect(page.locator('p:has-text("Total Projects") + p')).toHaveText(String(projectCounts.totalProjects));+ await expect(page.locator('p:has-text("Running") + p')).toHaveText(String(projectCounts.runningProjects));+ await expect(page.locator('p:has-text("Stopped") + p')).toHaveText(String(projectCounts.stoppedProjects));});test('should navigate to new project page when "Create Project" is clicked', async ({ page }) => {diff --git a/tests/spec/volumes.spec.ts b/tests/spec/volumes.spec.tsindex b56e50ba5..8ccb6c62b 100644--- a/tests/spec/volumes.spec.ts+++ b/tests/spec/volumes.spec.ts@@ -1,11 +1,14 @@import { test, expect, type Page } from '@playwright/test';-import { fetchVolumesWithRetry } from '../utils/fetch.util';+import { fetchVolumeCountsWithRetry, fetchVolumesWithRetry } from '../utils/fetch.util';+import { VolumeUsageCounts } from 'types/volumes.type';let realVolumes: any[] = [];+let volumeCount: VolumeUsageCounts = { volumesInuse: 0, volumesUnused: 0, totalVolumes: 0 };test.beforeEach(async ({ page }) => {await page.goto('/volumes');realVolumes = await fetchVolumesWithRetry(page);+ volumeCount = await fetchVolumeCountsWithRetry(page);});function facetIds(title: string) {@@ -39,7 +42,7 @@ test.describe('Volumes Page', () => {test('Correct Volume Stat Card Counts', async ({ page }) => {await page.goto('/volumes');- await expect(page.locator('p:has-text("Total Volumes") + p')).toHaveText(realVolumes.length.toString());+ await expect(page.locator('p:has-text("Total Volumes") + p')).toHaveText(volumeCount.totalVolumes.toString());});test('Create Volume Sheet Opens', async ({ page }) => {diff --git a/tests/types/containers.type.ts b/tests/types/containers.type.tsnew file mode 100644index 000000000..cad285394--- /dev/null+++ b/tests/types/containers.type.ts@@ -0,0 +1,8 @@+export type ContainerSummary = {+ id: string;+ names?: string[];+ image?: string;+ state: string;+ status?: string;+ created?: number;+};diff --git a/tests/types/image.type.ts b/tests/types/image.type.tsnew file mode 100644index 000000000..d007b1890--- /dev/null+++ b/tests/types/image.type.ts@@ -0,0 +1,6 @@+export interface ImageUsageCounts {+ imagesInuse: number;+ imagesUnused: number;+ totalImages: number;+ totalImageSize: number;+}diff --git a/tests/types/networks.type.ts b/tests/types/networks.type.tsnew file mode 100644index 000000000..defcf290a--- /dev/null+++ b/tests/types/networks.type.ts@@ -0,0 +1,12 @@+export interface NetworkUsageCounts {+ networksInuse: number;+ networksUnused: number;+ totalNetworks: number;+}++export type NetworkSummary = {+ id: string;+ name: string;+ driver?: string;+ scope?: string;+};diff --git a/tests/types/project.type.ts b/tests/types/project.type.tsnew file mode 100644index 000000000..7f85dbf8a--- /dev/null+++ b/tests/types/project.type.ts@@ -0,0 +1,13 @@+export type Project = {+ id?: string;+ name?: string;+ status?: string;+ serviceCount?: number;+ [key: string]: any;+};++export interface ProjectStatusCounts {+ runningProjects: number;+ stoppedProjects: number;+ totalProjects: number;+}diff --git a/tests/types/volumes.type.ts b/tests/types/volumes.type.tsnew file mode 100644index 000000000..b355417a0--- /dev/null+++ b/tests/types/volumes.type.ts@@ -0,0 +1,5 @@+export interface VolumeUsageCounts {+ volumesInuse: number;+ volumesUnused: number;+ totalVolumes: number;+}diff --git a/tests/utils/fetch.util.ts b/tests/utils/fetch.util.tsindex 480c2ef31..c4def99b2 100644--- a/tests/utils/fetch.util.ts+++ b/tests/utils/fetch.util.ts@@ -1,28 +1,9 @@import type { Page } from '@playwright/test';--export type Project = {- id?: string;- name?: string;- status?: string;- serviceCount?: number;- [key: string]: any;-};--export type NetworkSummary = {- id: string;- name: string;- driver?: string;- scope?: string;-};--export type ContainerSummary = {- id: string;- names?: string[];- image?: string;- state: string;- status?: string;- created?: number;-};+import { ContainerSummary } from 'types/containers.type';+import { ImageUsageCounts } from 'types/image.type';+import { NetworkSummary, NetworkUsageCounts } from 'types/networks.type';+import { Project, ProjectStatusCounts } from 'types/project.type';+import { VolumeUsageCounts } from 'types/volumes.type';export type Paginated<T> = { data: T[]; pagination?: { totalItems?: number } };@@ -41,12 +22,25 @@ async function retry<T>(fn: () => Promise<T>, maxRetries: number, delayMs = 1000export async function fetchVolumesWithRetry(page: Page, maxRetries = 1): Promise<any[]> {return retry(async () => {- const res = await page.request.get('/api/volumes');+ const res = await page.request.get('/api/environments/0/volumes');const json = await res.json();return Array.isArray(json?.data) ? json.data : [];}, maxRetries);}+export async function fetchVolumeCountsWithRetry(page: Page, maxRetries = 3): Promise<VolumeUsageCounts> {+ return retry(+ async () => {+ const res = await page.request.get('/api/environments/0/volumes/counts');+ const json = await res.json().catch(() => null);+ const data = Array.isArray(json) ? json : json?.data?.data ?? json?.data ?? [];+ return (data ?? []) as VolumeUsageCounts;+ },+ maxRetries,+ 800+ );+}+const PROJECTS_ENDPOINT = '/api/environments/0/projects';export async function fetchProjectsWithRetry(page: Page, maxRetries = 3): Promise<Project[]> {return retry(async () => {@@ -59,10 +53,23 @@ export async function fetchProjectsWithRetry(page: Page, maxRetries = 3): Promis}, maxRetries);}+export async function fetchProjectCountsWithRetry(page: Page, maxRetries = 3): Promise<ProjectStatusCounts> {+ return retry(+ async () => {+ const res = await page.request.get('/api/environments/0/projects/counts');+ const json = await res.json().catch(() => null);+ const data = Array.isArray(json) ? json : json?.data?.data ?? json?.data ?? [];+ return data as ProjectStatusCounts;+ },+ maxRetries,+ 800+ );+}+export async function fetchNetworksWithRetry(page: Page, maxRetries = 3): Promise<NetworkSummary[]> {return retry(async () => {- const res = await page.request.get('/api/networks');+ const res = await page.request.get('/api/environments/0/networks');const json = await res.json().catch(() => null);const data = Array.isArray(json) ? json : json?.data?.data ?? json?.data ?? [];return (data ?? []) as NetworkSummary[];@@ -72,6 +79,19 @@ export async function fetchNetworksWithRetry(page: Page, maxRetries = 3): Promis);}+export async function fetchNetworksCountsWithRetry(page: Page, maxRetries = 3): Promise<NetworkUsageCounts> {+ return retry(+ async () => {+ const res = await page.request.get('/api/environments/0/networks/counts');+ const json = await res.json().catch(() => null);+ const data = Array.isArray(json) ? json : json?.data?.data ?? json?.data ?? [];+ return (data ?? []) as NetworkUsageCounts;+ },+ maxRetries,+ 800+ );+}+export async function fetchImagesWithRetry(page: Page, maxRetries = 3): Promise<any[]> {return retry(async () => {const res = await page.request.get('/api/environments/0/images');@@ -81,6 +101,19 @@ export async function fetchImagesWithRetry(page: Page, maxRetries = 3): Promise<}, maxRetries);}+export async function fetchImageCountsWithRetry(page: Page, maxRetries = 3): Promise<ImageUsageCounts> {+ return retry(+ async () => {+ const res = await page.request.get('/api/environments/0/images/counts');+ const json = await res.json().catch(() => null);+ const data = Array.isArray(json) ? json : json?.data?.data ?? json?.data ?? [];+ return data as ImageUsageCounts;+ },+ maxRetries,+ 800+ );+}+export async function fetchContainersWithRetry(page: Page, maxRetries = 3): Promise<Paginated<ContainerSummary>> {return retry(async () => {const res = await page.request.get('/api/environments/0/containers');