Compare commits

2 Commits
Author SHA1 Message Date
Gabriel20xxandClaude Sonnet 5 ee59571552 Rename ProjectConfigurator, restructure Projects workspace, retire MediaCollection naming
- Rename MediaConfig -> ProjectConfigurator throughout; drop the Parameters
  tab/page; rename the Mounts tab to Projects and restructure it into three
  sections: Central services, Main services, Third-party services
- Add a self-describe contract (GET /api/info returning name/tabs/mountTypes)
  and a server-side discovery proxy (POST /api/discover-service) so adding a
  main service only requires a URL
- Add ProjectConfigurator HA: multiple instances now sync their settings with
  each other (GET /api/settings/export, POST /api/settings/sync, a periodic
  background puller), last-write-wins per key by updated_at
- Add a generic, project-agnostic file-storage API on CarrierNode
  (GET/POST/DELETE /api/mount/{project}/{type}[/*]) driven by the same
  configured_mounts data the Projects workspace already writes, usable by any
  registered project, not just the media family
- Add last_login_at tracking to the shared auth Store/User (schema, queries,
  UpdateLastLogin) and surface it through the shared web-ui ManagedUser type
  and UserManagement component
- Retire the "MediaCollection" name: Go module -> repos.gfranz.ch/Gabriel20xx/shared/media-backend,
  binary -> mediabackend, session cookie default -> "session", media-webui
  merged into webui, media-shared-assets renamed to legacy-assets and pruned
  to the one file MediaDesktop still uses

Co-Authored-By: Claude Sonnet 5 <noreply@anthropic.com>
2026-09-04 15:02:16 +02:00
Gabriel20xxandClaude Sonnet 5 07cf3308da Remove Admin option from header profile dropdown
User management is now centralized in AuthGuard's webui, so the
per-project Admin dialog (user CRUD + require-login toggle) is
redundant. The require-login toggle will move to ProjectConfigurator
in the future.

Co-Authored-By: Claude Sonnet 5 <noreply@anthropic.com>
2026-09-04 09:29:23 +02:00
130 changed files with 2884 additions and 8709 deletions

No files matched your search

+1
View File
@@ -1,6 +1,7 @@
node_modules/
packages/*/dist/
packages/*/.svelte-kit/
webui/.svelte-kit/
*.tgz
.npm/
__pycache__/
+3 -3
View File
@@ -1,6 +1,6 @@
# shared
The single source of truth for code reused across every project in this workspace: a Svelte design system and application shell, backend helpers (Postgres access, config, auth/session persistence, an AuthGuard client, log shipping) in four languages, and the Go media-backend/media-webui powering the whole `MEDIA_SERVICE`-family of projects.
The single source of truth for code reused across every project in this workspace: a Svelte design system and application shell, backend helpers (Postgres access, config, auth/session persistence, an AuthGuard client, log shipping) in four languages, and the Go media-backend/webui powering the whole `MEDIA_SERVICE`-family of projects.
---
@@ -21,12 +21,12 @@ The single source of truth for code reused across every project in this workspac
|---|---|---|
| `@gabriel20xx/design-tokens` | CSS | Colors, typography, spacing, radii, shadows, light/dark theme variables. |
| `@gabriel20xx/web-ui` | Svelte | Application shell, header/navigation, auth screens, dialogs, buttons, cards, badges. |
| `@gabriel20xx/media-shared-assets` | Browser JS/CSS | Shared client-side assets for the media-backend/`MEDIA_SERVICE` family. |
| `@gabriel20xx/legacy-assets` | Browser JS/CSS | Legacy client-side assets for the media-backend/`MEDIA_SERVICE` family. |
| `repos.gfranz.ch/Gabriel20xx/shared/backend` | Go | Env config, `pgx` pools/transactions, auth persistence, an AuthGuard client (`authclient`), log shipping (`logshipper`), embedded Goose migrations. |
| `@gabriel20xx/node-backend` | Node.js | `pg` pool/config/transactions/migrations, auth/session persistence, an AuthGuard client. |
| `gabriel20xx-shared-backend` | Python | `asyncpg` pool/config, auth/session persistence, an AuthGuard client. |
| `com.gabriel20xx.shared.auth` | Java | An AuthGuard client, mirroring the Go/Node/Python ones. |
| `media-backend` / `media-webui` | Go / Svelte | The Go binary and web UI powering the `MEDIA_SERVICE`-family projects (see below). |
| `media-backend` / `webui` | Go / Svelte | The Go binary and web UI powering the `MEDIA_SERVICE`-family projects (see below). |
The `web-ui` components don't import `$app/state`, `$lib` stores, or a project-specific API — applications provide those through props and callbacks.
+33 -11
View File
@@ -24,6 +24,9 @@ type User struct {
Role Role
CreatedAt time.Time
UpdatedAt time.Time
// LastLoginAt is nil until the account's first successful POST
// /api/login (registration alone does not set it - see UpdateLastLogin).
LastLoginAt *time.Time
}
// Store performs common auth persistence against a caller-owned pool.
@@ -67,7 +70,8 @@ func EnsureSchema(ctx context.Context, pool *pgxpool.Pool, options SchemaOptions
totp_secret TEXT NOT NULL DEFAULT '',
totp_enabled BOOLEAN NOT NULL DEFAULT FALSE,
created_at TIMESTAMPTZ NOT NULL DEFAULT now(),
updated_at TIMESTAMPTZ NOT NULL DEFAULT now()
updated_at TIMESTAMPTZ NOT NULL DEFAULT now(),
last_login_at TIMESTAMPTZ
);
ALTER TABLE auth_users ADD COLUMN IF NOT EXISTS email TEXT NOT NULL DEFAULT '';
ALTER TABLE auth_users ADD COLUMN IF NOT EXISTS role TEXT NOT NULL DEFAULT 'user';
@@ -75,6 +79,10 @@ func EnsureSchema(ctx context.Context, pool *pgxpool.Pool, options SchemaOptions
ALTER TABLE auth_users ADD COLUMN IF NOT EXISTS totp_enabled BOOLEAN NOT NULL DEFAULT FALSE;
ALTER TABLE auth_users ADD COLUMN IF NOT EXISTS created_at TIMESTAMPTZ NOT NULL DEFAULT now();
ALTER TABLE auth_users ADD COLUMN IF NOT EXISTS updated_at TIMESTAMPTZ NOT NULL DEFAULT now();
-- last_login_at is nullable (NULL means "never logged in" - registration
-- alone does not count, only a successful POST /api/login) and has no
-- DEFAULT, unlike every other column here.
ALTER TABLE auth_users ADD COLUMN IF NOT EXISTS last_login_at TIMESTAMPTZ;
UPDATE auth_users SET role = 'superadmin'
WHERE id = (SELECT id FROM auth_users ORDER BY created_at, id LIMIT 1)
AND NOT EXISTS (SELECT 1 FROM auth_users WHERE role = 'superadmin');
@@ -204,9 +212,9 @@ func (s *Store) CreateUser(ctx context.Context, username, email, passwordHash st
VALUES ($1, $2, $3,
CASE WHEN EXISTS (SELECT 1 FROM auth_users) THEN 'user' ELSE 'superadmin' END,
now())
RETURNING id, username, email, password_hash, role, created_at, updated_at
RETURNING id, username, email, password_hash, role, created_at, updated_at, last_login_at
`, username, email, passwordHash).Scan(
&user.ID, &user.Username, &user.Email, &user.PasswordHash, &user.Role, &user.CreatedAt, &user.UpdatedAt,
&user.ID, &user.Username, &user.Email, &user.PasswordHash, &user.Role, &user.CreatedAt, &user.UpdatedAt, &user.LastLoginAt,
)
if err != nil {
var pgErr *pgconn.PgError
@@ -224,7 +232,7 @@ func (s *Store) FindByIdentifier(ctx context.Context, identifier string) (*User,
return nil, err
}
return s.find(ctx, `
SELECT id, username, email, password_hash, role, created_at, updated_at
SELECT id, username, email, password_hash, role, created_at, updated_at, last_login_at
FROM auth_users
WHERE username = $1 OR lower(email) = lower($1)
`, identifier)
@@ -236,7 +244,7 @@ func (s *Store) FindByID(ctx context.Context, id int64) (*User, error) {
return nil, err
}
return s.find(ctx, `
SELECT id, username, email, password_hash, role, created_at, updated_at
SELECT id, username, email, password_hash, role, created_at, updated_at, last_login_at
FROM auth_users WHERE id = $1
`, id)
}
@@ -264,7 +272,7 @@ func (s *Store) ListUsers(ctx context.Context) ([]User, error) {
return nil, err
}
rows, err := s.pool.Query(ctx, `
SELECT id, username, email, role, created_at, updated_at
SELECT id, username, email, role, created_at, updated_at, last_login_at
FROM auth_users ORDER BY created_at, id
`)
if err != nil {
@@ -274,7 +282,7 @@ func (s *Store) ListUsers(ctx context.Context) ([]User, error) {
users := make([]User, 0)
for rows.Next() {
var user User
if err := rows.Scan(&user.ID, &user.Username, &user.Email, &user.Role, &user.CreatedAt, &user.UpdatedAt); err != nil {
if err := rows.Scan(&user.ID, &user.Username, &user.Email, &user.Role, &user.CreatedAt, &user.UpdatedAt, &user.LastLoginAt); err != nil {
return nil, fmt.Errorf("scan auth user: %w", err)
}
users = append(users, user)
@@ -292,9 +300,9 @@ func (s *Store) CreateManagedUser(ctx context.Context, username, email, password
err := s.pool.QueryRow(ctx, `
INSERT INTO auth_users (username, email, password_hash, role, updated_at)
VALUES ($1, $2, $3, $4, now())
RETURNING id, username, email, password_hash, role, created_at, updated_at
RETURNING id, username, email, password_hash, role, created_at, updated_at, last_login_at
`, username, email, passwordHash, role).Scan(
&user.ID, &user.Username, &user.Email, &user.PasswordHash, &user.Role, &user.CreatedAt, &user.UpdatedAt,
&user.ID, &user.Username, &user.Email, &user.PasswordHash, &user.Role, &user.CreatedAt, &user.UpdatedAt, &user.LastLoginAt,
)
if err != nil {
var pgErr *pgconn.PgError
@@ -326,6 +334,20 @@ func (s *Store) UpdateUser(ctx context.Context, id int64, username, email, passw
return nil
}
// UpdateLastLogin stamps last_login_at to now(). Callers should treat this as
// best-effort: an already-successful login (the session is live) shouldn't
// fail because this update didn't - see AuthGuard's handleLogin for the
// intended "log and continue" pattern.
func (s *Store) UpdateLastLogin(ctx context.Context, id int64) error {
if err := s.validate(); err != nil {
return err
}
if _, err := s.pool.Exec(ctx, `UPDATE auth_users SET last_login_at = now() WHERE id = $1`, id); err != nil {
return fmt.Errorf("update last login: %w", err)
}
return nil
}
// DeleteUser removes one account. Callers enforce the superadmin/self policy.
func (s *Store) DeleteUser(ctx context.Context, id int64) error {
if err := s.validate(); err != nil {
@@ -358,7 +380,7 @@ func (s *Store) FindSessionUser(ctx context.Context, tokenHash string) (*User, e
return nil, err
}
return s.find(ctx, `
SELECT u.id, u.username, u.email, u.password_hash, u.role, u.created_at, u.updated_at
SELECT u.id, u.username, u.email, u.password_hash, u.role, u.created_at, u.updated_at, u.last_login_at
FROM auth_sessions s
JOIN auth_users u ON u.id = s.user_id
WHERE s.token_hash = $1 AND s.expires_at > now()
@@ -423,7 +445,7 @@ func (s *Store) validate() error {
func (s *Store) find(ctx context.Context, query string, arg any) (*User, error) {
var user User
err := s.pool.QueryRow(ctx, query, arg).Scan(
&user.ID, &user.Username, &user.Email, &user.PasswordHash, &user.Role, &user.CreatedAt, &user.UpdatedAt,
&user.ID, &user.Username, &user.Email, &user.PasswordHash, &user.Role, &user.CreatedAt, &user.UpdatedAt, &user.LastLoginAt,
)
if errors.Is(err, pgx.ErrNoRows) {
return nil, nil
+17
View File
@@ -61,6 +61,9 @@ func TestStoreIntegration(t *testing.T) {
if created.Role != RoleSuperAdmin {
t.Fatalf("first CreateUser() role = %q, want %q", created.Role, RoleSuperAdmin)
}
if created.LastLoginAt != nil {
t.Fatalf("CreateUser() LastLoginAt = %v, want nil before any login", created.LastLoginAt)
}
byIdentifier, err := store.FindByIdentifier(ctx, "root")
if err != nil {
@@ -101,4 +104,18 @@ func TestStoreIntegration(t *testing.T) {
if len(users) != 1 || users[0].ID != created.ID {
t.Fatalf("ListUsers() = %+v, want exactly the created user", users)
}
if users[0].LastLoginAt != nil {
t.Fatalf("ListUsers()[0].LastLoginAt = %v, want nil before any login", users[0].LastLoginAt)
}
if err := store.UpdateLastLogin(ctx, created.ID); err != nil {
t.Fatalf("UpdateLastLogin() error = %v", err)
}
afterLogin, err := store.FindByID(ctx, created.ID)
if err != nil {
t.Fatalf("FindByID() after UpdateLastLogin error = %v", err)
}
if afterLogin == nil || afterLogin.LastLoginAt == nil {
t.Fatalf("FindByID() after UpdateLastLogin = %+v, want LastLoginAt set", afterLogin)
}
}
+1 -1
View File
@@ -16,7 +16,7 @@ YT_DLP_PATH=yt-dlp
COMFYUI_URL=http://127.0.0.1:8188
ANALYZER_MODELS_URL=http://127.0.0.1:8801
CORS_ORIGIN=http://localhost:5173
SESSION_COOKIE=mediacollection_session
SESSION_COOKIE=session
COOKIE_SECURE=false
AUTHGUARD_URL=
INTERNAL_SERVICE_SECRET=
+14 -13
View File
@@ -1,6 +1,6 @@
# MediaCollection Go backend
# Shared media backend
The backend is one Go module. Set `MEDIA_SERVICE` to `viewer`, `tools`, `analyzer`, `config`, `moderator`, `kiosk`, or `servant` to select the route set while keeping the same auth, database, migration, file-safety, and worker implementation.
The backend is one Go module, shared across every `MEDIA_SERVICE` instance in the workspace. Set `MEDIA_SERVICE` to `viewer`, `tools`, `analyzer`, `config`, `moderator`, `kiosk`, or `carriernode` to select the route set while keeping the same auth, database, migration, file-safety, and worker implementation.
From this directory:
@@ -9,27 +9,28 @@ go mod download
MEDIA_SERVICE=viewer \
DATABASE_URL=postgresql://media:media@localhost:5432/mediadb \
WEB_ROOT=../WebUI/build \
go run ./cmd/mediacollectiond
go run ./cmd/mediabackend
```
Important settings:
- `MEDIA_ROOTS` is a comma- or semicolon-separated list of media roots. MediaServant also walks
every path saved under a `media`/`images`/`videos`/`audios`/`funscripts` mount in MediaConfig's
Mounts workspace (the `configured_mounts` setting) regardless of which project's tab it was
entered under - see `effectiveMediaRoots` in `internal/server/admin_storage.go`. `MEDIA_ROOTS`
is only needed for a root that isn't already configured there.
- `MEDIA_ROOTS` is a comma- or semicolon-separated list of media roots. CarrierNode also walks
every path saved under a `media`/`images`/`videos`/`audios`/`funscripts` mount in
ProjectConfigurator's Projects workspace (the `configured_mounts` setting) regardless of which
project's tab it was entered under - see `effectiveMediaRoots` in
`internal/server/admin_storage.go`. `MEDIA_ROOTS` is only needed for a root that isn't already
configured there.
- `INPUT_DIR`, `UPLOAD_COPY_DIR`, `THUMBNAIL_DIR`, `OUTPUT_DIR`, `DOWNLOADS_DIR`, and `MODEL_CACHE_DIR` control writable storage.
- `WORKFLOWS_DIR` points to the built-in ComfyUI workflow definitions.
- `FFMPEG_PATH`, `FFPROBE_PATH`, and `YT_DLP_PATH` select workflow executables.
- `COMFYUI_URL` configures the generator service.
- `SERVANT_URL` is only the bootstrap fallback for MediaServant's URL - once configured through
MediaConfig it's read from the `mediaservant_url` row in the `settings` table instead (see
`servantBaseURL` in `internal/server/servant_client.go`).
- `CARRIERNODE_URL` is only the bootstrap fallback for CarrierNode's URL - once configured through
ProjectConfigurator it's read from the `carriernode_url` row in the `settings` table instead
(see `carrierNodeBaseURL` in `internal/server/carriernode_client.go`).
- `INTERNAL_SERVICE_SECRET` protects service-to-service mount and media-proxy APIs.
Run `go test ./...` before packaging. Each service repo's Dockerfile builds this module (via the
`engine/` submodule) and copies `media-webui` into the final image; no Node server runs at runtime.
`engine/` submodule) and copies `webui` into the final image; no Node server runs at runtime.
### Configuration reference
@@ -38,7 +39,7 @@ Run `go test ./...` before packaging. Each service repo's Dockerfile builds this
| `DATABASE_URL` | required | PostgreSQL connection string |
| `MEDIA_SERVICE` | `viewer` | Route/service selection |
| `PORT` | service-specific | HTTP port |
| `WEB_ROOT` | service web root | Built media-webui directory |
| `WEB_ROOT` | service web root | Built webui directory |
| `MEDIA_ROOTS` | `./media` | Comma/semicolon-separated media roots |
| `THUMBNAIL_DIR` | `./thumbnails` | Thumbnail storage |
| `INPUT_DIR` | `./input` | Workflow input storage |
+1 -1
View File
@@ -1,4 +1,4 @@
# MediaCollection security notes
# Shared media backend security notes
The backend rewrite consolidates the security boundary in `internal/`.
@@ -10,9 +10,9 @@ import (
"os/signal"
"syscall"
"mediacollection/internal/config"
"mediacollection/internal/database"
"mediacollection/internal/server"
"repos.gfranz.ch/Gabriel20xx/shared/media-backend/internal/config"
"repos.gfranz.ch/Gabriel20xx/shared/media-backend/internal/database"
"repos.gfranz.ch/Gabriel20xx/shared/media-backend/internal/server"
)
func main() {
+1 -1
View File
@@ -1,4 +1,4 @@
module mediacollection
module repos.gfranz.ch/Gabriel20xx/shared/media-backend
go 1.26.5
+4 -4
View File
@@ -1,4 +1,4 @@
// Package auth is the media-collection family's /auth/... and /api/auth/...
// Package auth is the shared media-backend family's /auth/... and /api/auth/...
// handlers, proxied to AuthGuard.
//
// AuthGuard migration
@@ -15,7 +15,7 @@
// resolved through this module's own `repos.gfranz.ch/Gabriel20xx/shared/backend`
// dependency - same module that already provided `sharedauth`). This
// service's own /auth/... and /api/auth/... URL paths and JSON response
// shapes are UNCHANGED - the frontend (media-webui) was not touched - only
// shapes are UNCHANGED - the frontend (webui) was not touched - only
// what backs them changed. This mirrors the migration
// Original/GameStream/backend/cmd/gamestreamd/auth.go and
// Forks/Bitmagnet/backend/internal/auth/service.go already did; read either
@@ -44,7 +44,7 @@
// the bearer token on its server-to-server calls to AuthGuard
// (sessionToken/CurrentUser below). This service mints no session token of
// its own any more. The pre-migration SESSION_COOKIE name (configurable,
// default "mediacollection_session") is retained only as something Logout
// default "session") is retained only as something Logout
// additionally clears, so a browser that still holds one from before this
// migration doesn't keep sending a now-meaningless cookie forever.
//
@@ -78,7 +78,7 @@
// username/email/password via AuthGuard today; see UpdateMe.
// - The `bio`/`avatarUrl` fields the pre-migration User type carried are
// dropped entirely: AuthGuard has no such concept, and grepping the
// frontend (media-webui) confirms neither field was ever actually read
// frontend (webui) confirms neither field was ever actually read
// or set by any UI - they were dead weight even before this migration.
//
// Auth-disabled mode (AUTHGUARD_URL unset)
@@ -11,7 +11,7 @@ import (
"github.com/jackc/pgx/v5/pgxpool"
"mediacollection/internal/database"
"repos.gfranz.ch/Gabriel20xx/shared/media-backend/internal/database"
)
// testPool returns a connection pool against a real (throwaway) Postgres
@@ -129,7 +129,7 @@ func newRequest(method, target string, body string) *http.Request {
}
func TestCurrentUserDisabledModeReturnsLocalSuperadmin(t *testing.T) {
svc := New(nil, "mediacollection_session", false, "")
svc := New(nil, "session", false, "")
user, err := svc.CurrentUser(httptest.NewRequest(http.MethodGet, "/", nil))
if err != nil {
t.Fatalf("CurrentUser() error = %v", err)
@@ -143,7 +143,7 @@ func TestSignupLoginLogoutProxyToAuthGuard(t *testing.T) {
pool := testPool(t)
guard := newFakeAuthGuard()
defer guard.close()
svc := New(pool, "mediacollection_session", false, guard.server.URL)
svc := New(pool, "session", false, guard.server.URL)
ctx := context.Background()
// Signup
@@ -207,7 +207,7 @@ func TestSecondProjectSetupIsRejectedWhenAuthGuardAlreadyHasAnAccount(t *testing
guard.hasAccount = true // simulate a different project (or AuthGuard's own web UI) having already created one
guard.username, guard.email, guard.role, guard.password = "existing", "existing@example.com", "superadmin", "hunter2!!"
svc := New(pool, "mediacollection_session", false, guard.server.URL)
svc := New(pool, "session", false, guard.server.URL)
req := newRequest(http.MethodPost, "/auth/signup", `{"email":"new@example.com","username":"new","password":"correct horse battery staple"}`)
rec := httptest.NewRecorder()
svc.Signup(rec, req)
@@ -223,7 +223,7 @@ func TestSecondProjectSetupIsRejectedWhenAuthGuardAlreadyHasAnAccount(t *testing
func TestLoginRequiredToggleIsIndependentOfAuthGuard(t *testing.T) {
pool := testPool(t)
svc := New(pool, "mediacollection_session", false, "")
svc := New(pool, "session", false, "")
required, err := svc.LoginRequired(context.Background())
if err != nil || !required {
+29 -29
View File
@@ -17,27 +17,27 @@ const (
ConfigService Service = "config"
Moderator Service = "moderator"
Kiosk Service = "kiosk"
Servant Service = "servant"
CarrierNode Service = "carriernode"
)
type Config struct {
Port string
DatabaseURL string
Service Service
ServiceName string
WebRoot string
MediaRoots []string
InputRoot string
CopyRoot string
WorkflowsRoot string
ThumbnailRoot string
OutputRoot string
DownloadsRoot string
ModelsRoot string
AllowedOrigin string
PublicURL string
SessionCookie string
SecureCookies bool
Port string
DatabaseURL string
Service Service
ServiceName string
WebRoot string
MediaRoots []string
InputRoot string
CopyRoot string
WorkflowsRoot string
ThumbnailRoot string
OutputRoot string
DownloadsRoot string
ModelsRoot string
AllowedOrigin string
PublicURL string
SessionCookie string
SecureCookies bool
// AuthGuardURL is AuthGuard's base URL (see Web/Central/AuthGuard);
// empty means auth-disabled mode (see internal/auth's package doc
// comment). Read raw via os.Getenv rather than envOr since "" is a
@@ -49,7 +49,7 @@ type Config struct {
YTDLP string
ComfyURL string
AnalyzerModelsURL string
ServantURL string
CarrierNodeURL string
MaxUploadBytes int64
TLSCertFile string
TLSKeyFile string
@@ -96,7 +96,7 @@ func Load() (*Config, error) {
ModelsRoot: filepath.Clean(envOr("MODEL_CACHE_DIR", "./models")),
AllowedOrigin: envOr("CORS_ORIGIN", "http://localhost:5173"),
PublicURL: strings.TrimRight(strings.TrimSpace(os.Getenv("PUBLIC_URL")), "/"),
SessionCookie: envOr("SESSION_COOKIE", "mediacollection_session"),
SessionCookie: envOr("SESSION_COOKIE", "session"),
SecureCookies: envBool("COOKIE_SECURE", os.Getenv("TLS_CERT_FILE") != ""),
AuthGuardURL: strings.TrimSpace(os.Getenv("AUTHGUARD_URL")),
InternalServiceSecret: strings.TrimSpace(os.Getenv("INTERNAL_SERVICE_SECRET")),
@@ -105,7 +105,7 @@ func Load() (*Config, error) {
YTDLP: envOr("YT_DLP_PATH", "yt-dlp"),
ComfyURL: strings.TrimRight(envOr("COMFYUI_URL", "http://127.0.0.1:8188"), "/"),
AnalyzerModelsURL: strings.TrimRight(envOr("ANALYZER_MODELS_URL", "http://127.0.0.1:8801"), "/"),
ServantURL: strings.TrimRight(envOr("SERVANT_URL", "http://127.0.0.1:3003"), "/"),
CarrierNodeURL: strings.TrimRight(envOr("CARRIERNODE_URL", "http://127.0.0.1:3003"), "/"),
MaxUploadBytes: maxUpload,
TLSCertFile: strings.TrimSpace(os.Getenv("TLS_CERT_FILE")),
TLSKeyFile: strings.TrimSpace(os.Getenv("TLS_KEY_FILE")),
@@ -128,14 +128,14 @@ func normalizeService(value string) Service {
return Tools
case "analyzer", "mediaanalyzer":
return Analyzer
case "config", "mediaconfig":
case "config", "mediaconfig", "projectconfigurator":
return ConfigService
case "moderator", "mediamoderator":
return Moderator
case "kiosk", "mediakiosk":
return Kiosk
case "servant", "mediaservant":
return Servant
case "carriernode":
return CarrierNode
default:
return ""
}
@@ -150,15 +150,15 @@ func serviceName(service Service) string {
case Analyzer:
return "MediaAnalyzer"
case ConfigService:
return "MediaConfig"
return "ProjectConfigurator"
case Moderator:
return "MediaModerator"
case Kiosk:
return "MediaKiosk"
case Servant:
return "MediaServant"
case CarrierNode:
return "CarrierNode"
default:
return "MediaCollection"
return "Shared Service"
}
}
@@ -168,7 +168,7 @@ func defaultPort(service Service) string {
return "3005"
case Moderator:
return "8090"
case Servant:
case CarrierNode:
return "3003"
default:
return "3000"
+475 -76
View File
@@ -11,6 +11,7 @@ import (
"net/url"
"os"
"path/filepath"
"regexp"
"slices"
"sort"
"strconv"
@@ -18,6 +19,8 @@ import (
"time"
"github.com/go-chi/chi/v5"
"repos.gfranz.ch/Gabriel20xx/shared/media-backend/internal/config"
)
func (s *Server) mountConfigRoutes(r chi.Router) {
@@ -25,6 +28,9 @@ func (s *Server) mountConfigRoutes(r chi.Router) {
admin.Get("/settings", s.settings)
admin.Post("/settings", s.saveSettings)
admin.Post("/check-connection", s.checkConnection)
admin.Post("/discover-service", s.discoverService)
admin.Post("/settings/sync", s.settingsSync)
r.With(s.internalServiceAuth).Get("/settings/export", s.settingsExport)
r.Get("/info", s.configInfo)
r.With(s.internalServiceAuth).Get("/mounts/paths", s.mountPaths)
admin.Post("/mounts/paths", s.saveMountPaths)
@@ -77,6 +83,151 @@ func (s *Server) saveSettings(w http.ResponseWriter, r *http.Request) {
writeJSON(w, http.StatusOK, map[string]any{"success": true, "updated": count})
}
// settingsExport is the full-fidelity counterpart to settings: every row (sensitive ones
// included, since this is only ever reachable with the shared X-Internal-Auth secret) plus each
// key's updated_at, so a peer ProjectConfigurator instance can merge it with its own by recency.
// This is what makes running more than one ProjectConfigurator instance for high availability
// actually converge, whether or not the instances share a single Postgres database.
func (s *Server) settingsExport(w http.ResponseWriter, r *http.Request) {
rows, err := s.db.Query(r.Context(), `SELECT key, COALESCE(value, ''), updated_at FROM settings ORDER BY key`)
if err != nil {
writeError(w, http.StatusInternalServerError, "settings unavailable")
return
}
defer rows.Close()
values := map[string]any{}
for rows.Next() {
var key, value string
var updatedAt time.Time
if rows.Scan(&key, &value, &updatedAt) != nil {
continue
}
values[key] = map[string]any{"value": value, "updatedAt": updatedAt}
}
writeJSON(w, http.StatusOK, map[string]any{"success": true, "settings": values})
}
// projectConfiguratorPeers reads the other ProjectConfigurator instances an operator has
// registered in the Projects workspace's Central services section (configured_central, the same
// setting regularProjects/centralInstancesFor reads client-side) - every instance whose base name
// is "ProjectConfigurator" except the unsuffixed entry, which by convention represents this
// instance itself rather than a remote peer.
func (s *Server) projectConfiguratorPeers(ctx context.Context) []string {
raw := s.settingValue(ctx, "configured_central", "")
var central []string
if raw == "" || json.Unmarshal([]byte(raw), &central) != nil {
return nil
}
peers := make([]string, 0, len(central))
for _, project := range central {
key := strings.ToLower(strings.TrimSpace(project))
if key == "" || key == "projectconfigurator" || instanceBaseKey(key) != "projectconfigurator" {
continue
}
if peerURL := strings.TrimSpace(s.settingValue(ctx, key+"_url", "")); peerURL != "" {
peers = append(peers, peerURL)
}
}
return peers
}
// pullSettingsFrom fetches one peer's full settings export and applies every key that peer last
// touched more recently than this instance did - last-write-wins per key, the same rule
// saveSettings already applies within a single instance, just extended across instances.
func (s *Server) pullSettingsFrom(ctx context.Context, peerURL string) (int, error) {
target, err := normalizeServiceURL(peerURL)
if err != nil {
return 0, err
}
reqCtx, cancel := context.WithTimeout(ctx, 10*time.Second)
defer cancel()
request, err := http.NewRequestWithContext(reqCtx, http.MethodGet, strings.TrimRight(target, "/")+"/api/settings/export", nil)
if err != nil {
return 0, err
}
if s.cfg.InternalServiceSecret != "" {
request.Header.Set("X-Internal-Auth", s.cfg.InternalServiceSecret)
}
response, err := http.DefaultClient.Do(request)
if err != nil {
return 0, err
}
defer response.Body.Close()
if response.StatusCode != http.StatusOK {
return 0, fmt.Errorf("peer returned status %d", response.StatusCode)
}
var body struct {
Settings map[string]struct {
Value string `json:"value"`
UpdatedAt time.Time `json:"updatedAt"`
} `json:"settings"`
}
if err := json.NewDecoder(io.LimitReader(response.Body, 4<<20)).Decode(&body); err != nil {
return 0, err
}
updated := 0
for key, remote := range body.Settings {
key = strings.TrimSpace(key)
if key == "" || len(key) > 160 {
continue
}
result, err := s.db.Exec(ctx, `INSERT INTO settings (key, value, updated_at) VALUES ($1,$2,$3)
ON CONFLICT (key) DO UPDATE SET value=EXCLUDED.value, updated_at=EXCLUDED.updated_at
WHERE settings.updated_at < EXCLUDED.updated_at`, key, remote.Value, remote.UpdatedAt)
if err != nil {
continue
}
if result.RowsAffected() > 0 {
updated++
}
}
return updated, nil
}
// settingsSync is the "Sync now" button's endpoint: pull every registered ProjectConfigurator
// peer's settings on demand, on top of the periodic background sync (runSettingsSyncScheduler).
func (s *Server) settingsSync(w http.ResponseWriter, r *http.Request) {
peers := s.projectConfiguratorPeers(r.Context())
results := make([]map[string]any, 0, len(peers))
updated := 0
for _, peer := range peers {
count, err := s.pullSettingsFrom(r.Context(), peer)
result := map[string]any{"url": peer}
if err != nil {
result["ok"] = false
result["error"] = err.Error()
} else {
result["ok"] = true
result["updated"] = count
updated += count
}
results = append(results, result)
}
writeJSON(w, http.StatusOK, map[string]any{"ok": true, "peers": len(peers), "updated": updated, "results": results})
}
// runSettingsSyncScheduler periodically pulls every registered peer's settings so multiple
// ProjectConfigurator instances converge on their own, without an operator needing to click
// "Sync now" - the actual high-availability behavior. Only started for the config service (see
// Run). A fresh deployment with no peers registered yet just polls configured_central and finds
// nothing to do each tick, which is cheap enough not to bother special-casing.
func (s *Server) runSettingsSyncScheduler(ctx context.Context) {
ticker := time.NewTicker(2 * time.Minute)
defer ticker.Stop()
for {
select {
case <-ctx.Done():
return
case <-ticker.C:
for _, peer := range s.projectConfiguratorPeers(ctx) {
if _, err := s.pullSettingsFrom(ctx, peer); err != nil {
log.Printf("settings sync: pulling from %s: %v", peer, err)
}
}
}
}
}
func (s *Server) checkConnection(w http.ResponseWriter, r *http.Request) {
var input struct {
URL string `json:"url"`
@@ -117,7 +268,119 @@ func (s *Server) configInfo(w http.ResponseWriter, r *http.Request) {
if s.cfg.PublicURL != "" {
host = s.cfg.PublicURL
}
writeJSON(w, http.StatusOK, map[string]any{"ok": true, "hostname": host, "port": s.cfg.Port, "url": host})
writeJSON(w, http.StatusOK, map[string]any{
"ok": true, "hostname": host, "port": s.cfg.Port, "url": host,
"name": s.cfg.ServiceName, "service": s.cfg.ServiceName,
"tabs": serviceTabs(s.cfg.Service), "mountTypes": serviceMountTypes(s.cfg.Service),
})
}
// tabOption mirrors one entry of a project's nav (see webui's app-config.ts) plus the
// global About dialog every instance exposes - the set of "pages" ProjectConfigurator's Projects
// workspace lets an operator require login for individually.
type tabOption struct {
Label string `json:"label"`
Token string `json:"token"`
}
// serviceTabsByService mirrors webui/src/lib/app-config.ts's nav per Service, plus the
// About dialog (AppShell.svelte, not itself part of app.nav). Kept in sync by hand - there is no
// single source of truth shared between the Go backend and the SvelteKit frontend for this.
var serviceTabsByService = map[config.Service][]tabOption{
config.Viewer: {
{"Library", "/"}, {"Feed", "/feed"}, {"Tags", "/tags"}, {"Playlists", "/playlists"}, {"About", "/about"},
},
config.Tools: {
{"Generator", "/"}, {"Downloader", "/downloader"}, {"Converter", "/converter"},
{"Schedules", "/schedules"}, {"Library", "/library"}, {"About", "/about"},
},
config.Analyzer: {
{"Dashboard", "/"}, {"Discover", "/discover"}, {"Images", "/images"}, {"Videos", "/videos"},
{"Audios", "/audios"}, {"Funscripts", "/funscripts"}, {"Schedules", "/schedules"}, {"About", "/about"},
},
config.ConfigService: {{"Projects", "/"}, {"About", "/about"}},
config.Moderator: {
{"Dashboard", "/"}, {"Users", "/users"}, {"Media", "/media"}, {"About", "/about"},
},
config.Kiosk: {{"Kiosk", "/"}, {"About", "/about"}},
config.CarrierNode: {{"Overview", "/"}, {"Files", "/files"}, {"About", "/about"}},
}
// serviceMountTypesByService mirrors ConfigWorkspace.svelte's PROJECT_AVAILABLE_MOUNTS - the
// mount "type" values each service's own tab accepts when configuring its mounts.
var serviceMountTypesByService = map[config.Service][]string{
config.Viewer: {"media", "thumbnails", "funscripts"},
config.Tools: {"downloads", "generated", "converted", "converter input", "generator input", "generator copy"},
config.Analyzer: {"images", "videos", "audios", "funscripts", "models", "thumbnails"},
config.Moderator: {"media", "thumbnails"},
config.Kiosk: {"media"},
config.CarrierNode: {"media", "output"},
config.ConfigService: {},
}
func serviceTabs(service config.Service) []tabOption {
if tabs, ok := serviceTabsByService[service]; ok {
return tabs
}
return []tabOption{{"Main", "/"}, {"About", "/about"}}
}
func serviceMountTypes(service config.Service) []string {
if types, ok := serviceMountTypesByService[service]; ok {
return types
}
return []string{}
}
// discoverService lets ProjectConfigurator's Projects workspace populate a new service's name,
// tabs, and mount types from just its URL: it fetches the target's own public GET /api/info
// server-side (avoiding a browser CORS round-trip, same reasoning as checkConnection) and relays
// whatever it reports. A target that doesn't implement this yet (or is unreachable) reports
// {"ok":false} so the caller can fall back to manual entry instead of erroring out.
func (s *Server) discoverService(w http.ResponseWriter, r *http.Request) {
var input struct {
URL string `json:"url"`
}
if err := decodeRequestJSON(r, &input); err != nil {
writeError(w, http.StatusBadRequest, "invalid JSON body")
return
}
target, err := normalizeServiceURL(input.URL)
if err != nil {
writeJSON(w, http.StatusOK, map[string]any{"ok": false, "error": err.Error()})
return
}
ctx, cancel := context.WithTimeout(r.Context(), 5*time.Second)
defer cancel()
request, _ := http.NewRequestWithContext(ctx, http.MethodGet, strings.TrimRight(target, "/")+"/api/info", nil)
response, err := http.DefaultClient.Do(request)
if err != nil {
writeJSON(w, http.StatusOK, map[string]any{"ok": false, "error": "unreachable"})
return
}
defer response.Body.Close()
var body struct {
OK bool `json:"ok"`
Name string `json:"name"`
Service string `json:"service"`
Tabs []tabOption `json:"tabs"`
MountTypes []string `json:"mountTypes"`
}
if response.StatusCode >= 300 || json.NewDecoder(io.LimitReader(response.Body, 64*1024)).Decode(&body) != nil {
writeJSON(w, http.StatusOK, map[string]any{"ok": false, "error": "invalid response"})
return
}
name := strings.TrimSpace(body.Name)
if name == "" {
name = strings.TrimSpace(body.Service)
}
if name == "" {
writeJSON(w, http.StatusOK, map[string]any{"ok": false, "error": "service did not report a name"})
return
}
writeJSON(w, http.StatusOK, map[string]any{
"ok": true, "name": name, "tabs": body.Tabs, "mountTypes": body.MountTypes,
})
}
func (s *Server) mountPaths(w http.ResponseWriter, r *http.Request) {
@@ -191,15 +454,15 @@ func (s *Server) resolveMount(w http.ResponseWriter, r *http.Request) {
}
// mountEntry mirrors WebUI's ConfigWorkspace.svelte MountEntry ({type, path}) - one row in a
// project's mount list in MediaConfig's Mounts workspace.
// project's mount list in ProjectConfigurator's Projects workspace.
type mountEntry struct {
Type string `json:"type"`
Path string `json:"path"`
}
// configuredMounts parses the configured_mounts setting - the live source MediaConfig's Mounts
// workspace actually saves to (see ConfigWorkspace.svelte's buildPayload) - into project key ->
// mount entries. Returns nil if unset or malformed.
// configuredMounts parses the configured_mounts setting - the live source ProjectConfigurator's
// Projects workspace actually saves to (see ConfigWorkspace.svelte's buildPayload) - into project
// key -> mount entries. Returns nil if unset or malformed.
func (s *Server) configuredMounts(ctx context.Context) map[string][]mountEntry {
raw := s.settingValue(ctx, "configured_mounts", "")
if raw == "" {
@@ -213,9 +476,9 @@ func (s *Server) configuredMounts(ctx context.Context) map[string][]mountEntry {
}
// mountMappings returns each project's mount configuration as project -> mount type -> path(s),
// the shape /mounts/resolve and /mounts/paths (and MediaServant's own "Mount health" panel via
// the shape /mounts/resolve and /mounts/paths (and CarrierNode's own "Mount health" panel via
// /mounts) expect. configured_mounts is the live source and wins per-project when present;
// mounts_path_mappings is an older format nothing has written since the Mounts workspace moved
// mounts_path_mappings is an older format nothing has written since the Projects workspace moved
// to configured_mounts, kept only so a deployment that hasn't resaved its mounts since upgrading
// doesn't lose data it already had. Keys are used as stored, not case-normalized - configured_mounts
// is processed first so a legacy entry for a project already covered there (under the exact same
@@ -270,13 +533,13 @@ func (s *Server) mountMappings(ctx context.Context) map[string]any {
return mappings
}
// mediaLibraryMountTypes are the mount "type" values MediaConfig's Mounts workspace (the
// mediaLibraryMountTypes are the mount "type" values ProjectConfigurator's Projects workspace (the
// configured_mounts setting) accepts that describe an actual media-library directory, as
// opposed to a project-specific working directory like "downloads", "generated",
// "thumbnails", or "models", which have their own dedicated Root config fields instead and
// are deliberately left out here. A path is entered under whichever project's tab happens to
// need it (MediaAnalyzer's "images"/"videos"/"audios", MediaViewer/MediaKiosk's "media", ...)
// but they're all describing locations MediaServant itself has to walk, since it's the only
// but they're all describing locations CarrierNode itself has to walk, since it's the only
// service with the volume mounted - see effectiveMediaRoots.
var mediaLibraryMountTypes = map[string]bool{
"media": true, "images": true, "videos": true, "audios": true, "funscripts": true,
@@ -304,11 +567,11 @@ func (s *Server) mediaRootsFromMounts(ctx context.Context) []string {
return roots
}
// effectiveMediaRoots is what Servant actually walks and resolves files under: the static
// effectiveMediaRoots is what CarrierNode actually walks and resolves files under: the static
// MEDIA_ROOTS/MEDIA_ROOT env config (if any) plus every media-library path configured through
// MediaConfig's Mounts workspace, deduped. Settings are read fresh from the DB on every call
// (no caching, same as mediaservant_url/servantBaseURL), so a mount saved in MediaConfig takes
// effect on Servant's very next request - no reload or restart needed.
// ProjectConfigurator's Projects workspace, deduped. Settings are read fresh from the DB on every
// call (no caching, same as carriernode_url/carrierNodeBaseURL), so a mount saved in
// ProjectConfigurator takes effect on CarrierNode's very next request - no reload or restart needed.
func (s *Server) effectiveMediaRoots(ctx context.Context) []string {
seen := map[string]bool{}
roots := make([]string, 0, len(s.cfg.MediaRoots))
@@ -510,32 +773,158 @@ func (s *Server) adminStats(w http.ResponseWriter, r *http.Request) {
writeJSON(w, http.StatusOK, map[string]any{"users": users, "media": media, "likes": likes, "views": views})
}
func (s *Server) mountServantRoutes(r chi.Router) {
r.Get("/stats", s.servantStats)
r.Get("/mounts", s.servantMounts)
r.Get("/files/recent", s.servantRecentFiles)
r.Get("/files", s.servantFiles)
r.Get("/files/count", s.servantFileCount)
r.Get("/folders", s.servantFolders)
r.Get("/browse", s.servantBrowse)
r.Get("/watch", s.servantWatch)
r.With(s.internalServiceAuth).Get("/downloads", s.servantDownloads)
r.With(s.internalServiceAuth).Post("/reload-mounts", s.servantReloadMounts)
r.With(s.internalServiceAuth).Get("/probe", s.servantProbeFile)
func (s *Server) mountCarrierNodeRoutes(r chi.Router) {
r.Get("/stats", s.carrierNodeStats)
r.Get("/mounts", s.carrierNodeMounts)
r.Get("/files/recent", s.carrierNodeRecentFiles)
r.Get("/files", s.carrierNodeFiles)
r.Get("/files/count", s.carrierNodeFileCount)
r.Get("/folders", s.carrierNodeFolders)
r.Get("/browse", s.carrierNodeBrowse)
r.Get("/watch", s.carrierNodeWatch)
r.With(s.internalServiceAuth).Get("/downloads", s.carrierNodeDownloads)
r.With(s.internalServiceAuth).Post("/reload-mounts", s.carrierNodeReloadMounts)
r.With(s.internalServiceAuth).Get("/probe", s.carrierNodeProbeFile)
protected := r.With(s.auth.Optional, s.requireAdminOrInternal)
protected.Post("/upload", s.servantUpload)
protected.Post("/upload-mounted", s.servantUpload)
protected.Delete("/downloads/{filename}", s.servantDeleteDownload)
protected.Post("/store", s.servantStore)
protected.Post("/upload", s.carrierNodeUpload)
protected.Post("/upload-mounted", s.carrierNodeUpload)
protected.Delete("/downloads/{filename}", s.carrierNodeDeleteDownload)
protected.Post("/store", s.carrierNodeStore)
internal := r.With(s.internalServiceAuth)
internal.Post("/thumbnails/{id}", s.servantThumbnailUpload)
internal.Delete("/thumbnails/{id}", s.servantThumbnailDelete)
internal.Post("/outputs/{name}", s.servantOutputUpload)
internal.Post("/inputs/{name}", s.servantInputUpload)
internal.Post("/copies/{name}", s.servantCopyUpload)
internal.Post("/thumbnails/{id}", s.carrierNodeThumbnailUpload)
internal.Delete("/thumbnails/{id}", s.carrierNodeThumbnailDelete)
internal.Post("/outputs/{name}", s.carrierNodeOutputUpload)
internal.Post("/inputs/{name}", s.carrierNodeInputUpload)
internal.Post("/copies/{name}", s.carrierNodeCopyUpload)
// Generic, project-agnostic mount access: any project registered in
// ProjectConfigurator's Projects workspace with a mount path configured under
// {type} can read/list/write/delete files there, not just the handful of
// hardcoded media-family routes above (/media, /mount/generated, /thumbnails, ...).
// See carrierNodeMountRoots's doc comment for why no cross-service call is needed.
internal.Get("/mount/{project}/{type}", s.carrierNodeListMount)
internal.Get("/mount/{project}/{type}/*", s.carrierNodeMountFile)
internal.Post("/mount/{project}/{type}/*", s.carrierNodeMountUpload)
internal.Delete("/mount/{project}/{type}/*", s.carrierNodeMountDelete)
}
func (s *Server) servantStats(w http.ResponseWriter, r *http.Request) {
// carrierNodeMountRoots resolves every root path registered for {project, type} through
// ProjectConfigurator's Projects workspace (the same configured_mounts setting
// /api/mounts/resolve serves) - not limited to the media-family's own hardcoded mount
// categories (media/output/generated/...), any project name and any mount type an
// operator has configured there works. No HTTP call to ProjectConfigurator is needed: every
// MEDIA_SERVICE instance, CarrierNode included, reads the same settings table directly (see
// mountMappings), the same way effectiveMediaRoots already resolves CarrierNode's own roots.
func (s *Server) carrierNodeMountRoots(ctx context.Context, project, mountType string) []string {
mappings := s.mountMappings(ctx)
projectValue, ok := mappings[project]
if !ok {
for key, value := range mappings {
if strings.EqualFold(key, project) {
projectValue, ok = value, true
break
}
}
}
if !ok {
return nil
}
functions, ok := projectValue.(map[string]any)
if !ok {
return nil
}
value, ok := functions[mountType]
if !ok {
for key, candidate := range functions {
if strings.EqualFold(key, mountType) {
value, ok = candidate, true
break
}
}
}
if !ok {
return nil
}
return normalizeMappingPaths(value)
}
// carrierNodeListMount lists the files directly under every root configured for
// {project, type} (non-recursive - each root is typically a flat upload/output directory).
func (s *Server) carrierNodeListMount(w http.ResponseWriter, r *http.Request) {
project := chi.URLParam(r, "project")
mountType := chi.URLParam(r, "type")
roots := s.carrierNodeMountRoots(r.Context(), project, mountType)
if len(roots) == 0 {
writeError(w, http.StatusNotFound, "no mount configured for this project/type")
return
}
entries := make([]map[string]any, 0)
for _, root := range roots {
items, err := os.ReadDir(root)
if err != nil {
continue
}
for _, item := range items {
if item.IsDir() {
continue
}
info, err := item.Info()
if err != nil {
continue
}
entries = append(entries, map[string]any{"name": item.Name(), "size": info.Size(), "modifiedAt": info.ModTime()})
}
}
writeJSON(w, http.StatusOK, map[string]any{"success": true, "project": project, "type": mountType, "files": entries})
}
// carrierNodeMountFile downloads one file by relative path from {project, type}'s mount.
func (s *Server) carrierNodeMountFile(w http.ResponseWriter, r *http.Request) {
roots := s.carrierNodeMountRoots(r.Context(), chi.URLParam(r, "project"), chi.URLParam(r, "type"))
if len(roots) == 0 {
writeError(w, http.StatusNotFound, "no mount configured for this project/type")
return
}
full, err := s.resolveUnderRoots(chi.URLParam(r, "*"), roots)
if err != nil {
writeError(w, http.StatusNotFound, "file not found")
return
}
s.serveFile(w, r, full)
}
// carrierNodeMountUpload stores the request body as a file under {project, type}'s first
// configured root. Like carrierNodeStreamUpload (which this delegates to), the destination
// filename is flattened to its base name - no subdirectories.
func (s *Server) carrierNodeMountUpload(w http.ResponseWriter, r *http.Request) {
roots := s.carrierNodeMountRoots(r.Context(), chi.URLParam(r, "project"), chi.URLParam(r, "type"))
if len(roots) == 0 {
writeError(w, http.StatusNotFound, "no mount configured for this project/type")
return
}
s.carrierNodeStreamUpload(w, r, roots[0], chi.URLParam(r, "*"))
}
// carrierNodeMountDelete removes one file by relative path from {project, type}'s mount.
func (s *Server) carrierNodeMountDelete(w http.ResponseWriter, r *http.Request) {
roots := s.carrierNodeMountRoots(r.Context(), chi.URLParam(r, "project"), chi.URLParam(r, "type"))
if len(roots) == 0 {
writeError(w, http.StatusNotFound, "no mount configured for this project/type")
return
}
full, err := s.resolveUnderRoots(chi.URLParam(r, "*"), roots)
if err != nil {
writeError(w, http.StatusNotFound, "file not found")
return
}
if err := os.Remove(full); err != nil {
writeError(w, http.StatusInternalServerError, "file could not be removed")
return
}
writeJSON(w, http.StatusOK, map[string]any{"success": true})
}
func (s *Server) carrierNodeStats(w http.ResponseWriter, r *http.Request) {
files := s.walkFiles(r.Context(), "")
roots := s.effectiveMediaRoots(r.Context())
byType := map[string]int{"image": 0, "video": 0, "audio": 0, "other": 0}
@@ -546,7 +935,7 @@ func (s *Server) servantStats(w http.ResponseWriter, r *http.Request) {
writeJSON(w, http.StatusOK, map[string]any{"ok": true, "stats": stats, "bandwidth": map[string]any{"bytesOut": 0, "requests": 0}, "count": len(files), "total": len(files), "active": len(roots), "files": byType, "roots": roots})
}
func (s *Server) servantMounts(w http.ResponseWriter, r *http.Request) {
func (s *Server) carrierNodeMounts(w http.ResponseWriter, r *http.Request) {
roots := s.effectiveMediaRoots(r.Context())
writeJSON(w, http.StatusOK, map[string]any{"mappings": s.mountMappings(r.Context()), "roots": roots, "count": len(roots)})
}
@@ -559,18 +948,18 @@ type fileEntry struct {
Mtime int64 `json:"mtime"`
}
func (s *Server) servantRecentFiles(w http.ResponseWriter, r *http.Request) {
s.writeServantFiles(w, r, true)
func (s *Server) carrierNodeRecentFiles(w http.ResponseWriter, r *http.Request) {
s.writeCarrierNodeFiles(w, r, true)
}
func (s *Server) servantFiles(w http.ResponseWriter, r *http.Request) {
s.writeServantFiles(w, r, false)
func (s *Server) carrierNodeFiles(w http.ResponseWriter, r *http.Request) {
s.writeCarrierNodeFiles(w, r, false)
}
func (s *Server) servantFileCount(w http.ResponseWriter, r *http.Request) {
func (s *Server) carrierNodeFileCount(w http.ResponseWriter, r *http.Request) {
writeJSON(w, http.StatusOK, map[string]any{"ok": true, "count": len(s.walkFiles(r.Context(), r.URL.Query().Get("path")))})
}
func (s *Server) writeServantFiles(w http.ResponseWriter, r *http.Request, recent bool) {
func (s *Server) writeCarrierNodeFiles(w http.ResponseWriter, r *http.Request, recent bool) {
files := s.walkFiles(r.Context(), r.URL.Query().Get("path"))
if recent {
sort.Slice(files, func(i, j int) bool { return files[i].Mtime > files[j].Mtime })
@@ -588,7 +977,7 @@ func (s *Server) writeServantFiles(w http.ResponseWriter, r *http.Request, recen
writeJSON(w, http.StatusOK, map[string]any{"files": files, "items": files, "total": len(files)})
}
func (s *Server) servantFolders(w http.ResponseWriter, r *http.Request) {
func (s *Server) carrierNodeFolders(w http.ResponseWriter, r *http.Request) {
seen := map[string]bool{}
for _, file := range s.walkFiles(r.Context(), r.URL.Query().Get("path")) {
seen[filepath.Dir(file.Rel)] = true
@@ -601,9 +990,9 @@ func (s *Server) servantFolders(w http.ResponseWriter, r *http.Request) {
writeJSON(w, http.StatusOK, map[string]any{"folders": folders})
}
func (s *Server) servantBrowse(w http.ResponseWriter, r *http.Request) { s.servantFiles(w, r) }
func (s *Server) carrierNodeBrowse(w http.ResponseWriter, r *http.Request) { s.carrierNodeFiles(w, r) }
func (s *Server) servantWatch(w http.ResponseWriter, r *http.Request) {
func (s *Server) carrierNodeWatch(w http.ResponseWriter, r *http.Request) {
w.Header().Set("Content-Type", "text/event-stream")
w.Header().Set("Cache-Control", "no-cache")
_, _ = io.WriteString(w, "event: ready\ndata: {\"ok\":true}\n\n")
@@ -613,11 +1002,11 @@ func (s *Server) servantWatch(w http.ResponseWriter, r *http.Request) {
<-r.Context().Done()
}
func (s *Server) servantReloadMounts(w http.ResponseWriter, _ *http.Request) {
func (s *Server) carrierNodeReloadMounts(w http.ResponseWriter, _ *http.Request) {
writeJSON(w, http.StatusOK, map[string]bool{"ok": true})
}
func (s *Server) servantDownloads(w http.ResponseWriter, r *http.Request) {
func (s *Server) carrierNodeDownloads(w http.ResponseWriter, r *http.Request) {
limit := optionalInt(r.URL.Query().Get("limit"), 500, 1, 1000)
rows, err := s.db.Query(r.Context(), `SELECT file_name, file_path, media_type, source_url, file_size_bytes, created_at FROM downloaded_media WHERE file_name IS NOT NULL ORDER BY created_at DESC LIMIT $1`, limit)
if err != nil {
@@ -639,8 +1028,9 @@ func (s *Server) servantDownloads(w http.ResponseWriter, r *http.Request) {
}
// walkRootTimeout bounds how long a single root's filesystem walk can run before walkFiles gives
// up on it. effectiveMediaRoots now includes every media-library path configured in MediaConfig's
// Mounts workspace across every project, not just the operator's own verified MEDIA_ROOTS - a
// up on it. effectiveMediaRoots now includes every media-library path configured in
// ProjectConfigurator's Projects workspace across every project, not just the operator's own
// verified MEDIA_ROOTS - a
// typo'd path or a mount that isn't actually reachable from this container (an unresponsive
// network share, say) would otherwise be able to hang every caller of walkFiles (discovery,
// /api/stats, browsing) indefinitely, since a blocked stat/readdir syscall can't be interrupted by
@@ -680,7 +1070,7 @@ func (s *Server) walkFiles(ctx context.Context, relative string) []fileEntry {
case found := <-done:
result = append(result, found...)
case <-time.After(walkRootTimeout):
log.Printf("servant: walking root %q took too long (>%s) - skipping it for this request, it may be an unreachable mount", root, walkRootTimeout)
log.Printf("carriernode: walking root %q took too long (>%s) - skipping it for this request, it may be an unreachable mount", root, walkRootTimeout)
case <-ctx.Done():
return result
}
@@ -688,9 +1078,9 @@ func (s *Server) walkFiles(ctx context.Context, relative string) []fileEntry {
return result
}
func (s *Server) servantUpload(w http.ResponseWriter, r *http.Request) {
func (s *Server) carrierNodeUpload(w http.ResponseWriter, r *http.Request) {
if !strings.HasPrefix(strings.ToLower(r.Header.Get("Content-Type")), "multipart/") {
s.servantRawUpload(w, r)
s.carrierNodeRawUpload(w, r)
return
}
if s.cfg.MaxUploadBytes > 0 {
@@ -729,7 +1119,7 @@ func (s *Server) servantUpload(w http.ResponseWriter, r *http.Request) {
writeJSON(w, http.StatusCreated, map[string]any{"ok": true, "filename": name, "path": name})
}
func (s *Server) servantDeleteDownload(w http.ResponseWriter, r *http.Request) {
func (s *Server) carrierNodeDeleteDownload(w http.ResponseWriter, r *http.Request) {
name := chi.URLParam(r, "filename")
if !safeRelative(name) {
writeError(w, http.StatusBadRequest, "invalid filename")
@@ -747,7 +1137,7 @@ func (s *Server) servantDeleteDownload(w http.ResponseWriter, r *http.Request) {
writeJSON(w, http.StatusOK, map[string]bool{"ok": true})
}
func (s *Server) servantStore(w http.ResponseWriter, r *http.Request) {
func (s *Server) carrierNodeStore(w http.ResponseWriter, r *http.Request) {
var input map[string]any
if err := decodeRequestJSON(r, &input); err != nil {
writeError(w, http.StatusBadRequest, "invalid JSON body")
@@ -784,8 +1174,8 @@ func (s *Server) servantStore(w http.ResponseWriter, r *http.Request) {
writeJSON(w, http.StatusOK, map[string]any{"ok": true, "mediaKey": mediaKey, "mediaId": mediaID})
}
// resolveStoreFile is Servant's own local-filesystem lookup for /api/store, which catalogs a
// file MediaTools already pushed into one of Servant's mounts (InputRoot, MediaRoots,
// resolveStoreFile is CarrierNode's own local-filesystem lookup for /api/store, which catalogs a
// file MediaTools already pushed into one of CarrierNode's mounts (InputRoot, MediaRoots,
// DownloadsRoot, OutputRoot) - unlike everything else in this file, it's called with a path that
// isn't necessarily under MediaRoots, so it can't just use resolveMediaPath.
func (s *Server) resolveStoreFile(value string) (string, error) {
@@ -820,7 +1210,7 @@ func (s *Server) resolveStoreFile(value string) (string, error) {
return "", os.ErrNotExist
}
func (s *Server) servantRawUpload(w http.ResponseWriter, r *http.Request) {
func (s *Server) carrierNodeRawUpload(w http.ResponseWriter, r *http.Request) {
name := filepath.Base(strings.TrimSpace(firstNonEmpty(r.URL.Query().Get("filename"), r.URL.Query().Get("file_name"))))
if name == "." || name == "" || !safeRelative(name) || strings.ContainsAny(name, `<>:"|?*`) {
writeError(w, http.StatusBadRequest, "valid filename query parameter is required")
@@ -880,7 +1270,7 @@ func infoSize(info os.FileInfo) int64 {
return info.Size()
}
func (s *Server) servantMedia(w http.ResponseWriter, r *http.Request) {
func (s *Server) carrierNodeMedia(w http.ResponseWriter, r *http.Request) {
relative := chi.URLParam(r, "*")
if relative == "" {
relative = strings.TrimPrefix(r.URL.Path, "/media/")
@@ -893,7 +1283,7 @@ func (s *Server) servantMedia(w http.ResponseWriter, r *http.Request) {
s.serveFile(w, r, full)
}
func (s *Server) servantDownloadMedia(w http.ResponseWriter, r *http.Request) {
func (s *Server) carrierNodeDownloadMedia(w http.ResponseWriter, r *http.Request) {
relative := strings.TrimPrefix(r.URL.Path, "/media/downloads/")
full, err := s.resolveUnderRoots(relative, []string{s.cfg.DownloadsRoot})
if err != nil {
@@ -903,7 +1293,7 @@ func (s *Server) servantDownloadMedia(w http.ResponseWriter, r *http.Request) {
s.serveFile(w, r, full)
}
func (s *Server) servantGeneratedMedia(w http.ResponseWriter, r *http.Request) {
func (s *Server) carrierNodeGeneratedMedia(w http.ResponseWriter, r *http.Request) {
relative := strings.TrimPrefix(r.URL.Path, "/mount/generated/")
full, err := s.resolveUnderRoots(relative, []string{s.cfg.OutputRoot})
if err != nil {
@@ -913,7 +1303,7 @@ func (s *Server) servantGeneratedMedia(w http.ResponseWriter, r *http.Request) {
s.serveFile(w, r, full)
}
func (s *Server) servantThumbnail(w http.ResponseWriter, r *http.Request) {
func (s *Server) carrierNodeThumbnail(w http.ResponseWriter, r *http.Request) {
relative := chi.URLParam(r, "*")
if relative == "" {
relative = strings.TrimPrefix(r.URL.Path, "/thumbnails/")
@@ -926,7 +1316,7 @@ func (s *Server) servantThumbnail(w http.ResponseWriter, r *http.Request) {
s.serveFile(w, r, full)
}
func (s *Server) servantInputMedia(w http.ResponseWriter, r *http.Request) {
func (s *Server) carrierNodeInputMedia(w http.ResponseWriter, r *http.Request) {
relative := strings.TrimPrefix(r.URL.Path, "/mount/inputs/")
full, err := s.resolveUnderRoots(relative, []string{s.cfg.InputRoot})
if err != nil {
@@ -936,7 +1326,7 @@ func (s *Server) servantInputMedia(w http.ResponseWriter, r *http.Request) {
s.serveFile(w, r, full)
}
func (s *Server) servantCopyMedia(w http.ResponseWriter, r *http.Request) {
func (s *Server) carrierNodeCopyMedia(w http.ResponseWriter, r *http.Request) {
relative := strings.TrimPrefix(r.URL.Path, "/mount/copies/")
full, err := s.resolveUnderRoots(relative, []string{s.cfg.CopyRoot})
if err != nil {
@@ -946,11 +1336,11 @@ func (s *Server) servantCopyMedia(w http.ResponseWriter, r *http.Request) {
s.serveFile(w, r, full)
}
// servantStreamUpload writes a raw request body into root/name, used by every internal
// carrierNodeStreamUpload writes a raw request body into root/name, used by every internal
// push-result endpoint (thumbnails, outputs, inputs, copies). name is always reduced to its
// base component - callers never need nested directories, and this keeps every write flat and
// trivially contained within root (mirrors servantRawUpload's existing filename handling).
func (s *Server) servantStreamUpload(w http.ResponseWriter, r *http.Request, root, name string) {
// trivially contained within root (mirrors carrierNodeRawUpload's existing filename handling).
func (s *Server) carrierNodeStreamUpload(w http.ResponseWriter, r *http.Request, root, name string) {
name = filepath.Base(strings.TrimSpace(name))
if name == "." || name == "" || !safeRelative(name) || strings.ContainsAny(name, `<>:"|?*`) {
writeError(w, http.StatusBadRequest, "invalid filename")
@@ -983,16 +1373,16 @@ func (s *Server) servantStreamUpload(w http.ResponseWriter, r *http.Request, roo
writeJSON(w, http.StatusCreated, map[string]any{"ok": true, "name": name, "size": written})
}
func (s *Server) servantThumbnailUpload(w http.ResponseWriter, r *http.Request) {
func (s *Server) carrierNodeThumbnailUpload(w http.ResponseWriter, r *http.Request) {
id := chi.URLParam(r, "id")
if !safeRelative(id) || strings.ContainsAny(id, `/\`) {
writeError(w, http.StatusBadRequest, "invalid thumbnail id")
return
}
s.servantStreamUpload(w, r, s.cfg.ThumbnailRoot, id+".jpg")
s.carrierNodeStreamUpload(w, r, s.cfg.ThumbnailRoot, id+".jpg")
}
func (s *Server) servantThumbnailDelete(w http.ResponseWriter, r *http.Request) {
func (s *Server) carrierNodeThumbnailDelete(w http.ResponseWriter, r *http.Request) {
id := chi.URLParam(r, "id")
if !safeRelative(id) || strings.ContainsAny(id, `/\`) {
writeError(w, http.StatusBadRequest, "invalid thumbnail id")
@@ -1004,19 +1394,19 @@ func (s *Server) servantThumbnailDelete(w http.ResponseWriter, r *http.Request)
writeJSON(w, http.StatusOK, map[string]bool{"ok": true})
}
func (s *Server) servantOutputUpload(w http.ResponseWriter, r *http.Request) {
s.servantStreamUpload(w, r, s.cfg.OutputRoot, chi.URLParam(r, "name"))
func (s *Server) carrierNodeOutputUpload(w http.ResponseWriter, r *http.Request) {
s.carrierNodeStreamUpload(w, r, s.cfg.OutputRoot, chi.URLParam(r, "name"))
}
func (s *Server) servantInputUpload(w http.ResponseWriter, r *http.Request) {
s.servantStreamUpload(w, r, s.cfg.InputRoot, chi.URLParam(r, "name"))
func (s *Server) carrierNodeInputUpload(w http.ResponseWriter, r *http.Request) {
s.carrierNodeStreamUpload(w, r, s.cfg.InputRoot, chi.URLParam(r, "name"))
}
func (s *Server) servantCopyUpload(w http.ResponseWriter, r *http.Request) {
s.servantStreamUpload(w, r, s.cfg.CopyRoot, chi.URLParam(r, "name"))
func (s *Server) carrierNodeCopyUpload(w http.ResponseWriter, r *http.Request) {
s.carrierNodeStreamUpload(w, r, s.cfg.CopyRoot, chi.URLParam(r, "name"))
}
func (s *Server) servantProbeFile(w http.ResponseWriter, r *http.Request) {
func (s *Server) carrierNodeProbeFile(w http.ResponseWriter, r *http.Request) {
full, err := s.resolveAnyMediaPath(r.Context(), r.URL.Query().Get("path"))
if err != nil {
writeError(w, http.StatusNotFound, "file not found")
@@ -1079,6 +1469,15 @@ func fileType(value string) string {
}
}
// trailingInstanceSuffix strips a "_2", "_3", ... instance suffix, mirroring
// ConfigWorkspace.svelte's getBaseProject - the same "AuthGuard" / "AuthGuard_2" / "AuthGuard_3"
// naming convention every multi-instance central/main service in the Projects workspace uses.
var trailingInstanceSuffix = regexp.MustCompile(`_\d+$`)
func instanceBaseKey(key string) string {
return trailingInstanceSuffix.ReplaceAllString(key, "")
}
func sensitiveSetting(key string) bool {
switch strings.ToLower(key) {
case "session_secret", "internal_service_secret", "smtp_pass":
+25 -25
View File
@@ -18,7 +18,7 @@ import (
"github.com/go-chi/chi/v5"
"mediacollection/internal/config"
"repos.gfranz.ch/Gabriel20xx/shared/media-backend/internal/config"
)
func (s *Server) mountAnalyzerRoutes(r chi.Router) {
@@ -147,7 +147,7 @@ func (s *Server) analyzerStatus(w http.ResponseWriter, r *http.Request) {
running := clear.Running || scan.Running || thumbnail.Running || analysis.Running || processing > 0
// scan/clear have no dedicated status endpoint of their own (thumbnail/analysis do, via
// generate/status and analyze/status) - this is the only place their LastError ever reaches
// the UI, so a discover/metadata/cleanup run that fails fast (e.g. MediaServant unreachable)
// the UI, so a discover/metadata/cleanup run that fails fast (e.g. CarrierNode unreachable)
// is reported here instead of just looking like it silently reverted to idle.
lastError := firstNonEmpty(scan.LastError, clear.LastError)
@@ -925,7 +925,7 @@ func (s *Server) createThumbnail(ctx context.Context, candidate thumbnailCandida
return "", fmt.Errorf("unsupported media type for %s", sourcePath)
}
sourceScratch, cleanupSource, err := s.fetchServantToScratch(ctx, "/media/"+urlPath(sourcePath), filepath.Ext(sourcePath))
sourceScratch, cleanupSource, err := s.fetchCarrierNodeToScratch(ctx, "/media/"+urlPath(sourcePath), filepath.Ext(sourcePath))
if err != nil {
return "", fmt.Errorf("fetch %s: %w", sourcePath, err)
}
@@ -972,7 +972,7 @@ func (s *Server) createThumbnail(ctx context.Context, candidate thumbnailCandida
if err != nil || info.Size() == 0 {
return "", fmt.Errorf("ffmpeg produced no thumbnail")
}
size, err := s.servantPushThumbnail(ctx, thumbnailID, temporaryPath)
size, err := s.carrierNodePushThumbnail(ctx, thumbnailID, temporaryPath)
if err != nil {
return "", fmt.Errorf("store thumbnail: %w", err)
}
@@ -981,11 +981,11 @@ func (s *Server) createThumbnail(ctx context.Context, candidate thumbnailCandida
VALUES ($1, $2, $3)
ON CONFLICT (source_path) DO NOTHING`, thumbnailID, sourcePath, size)
if err != nil {
_ = s.servantDeleteThumbnail(ctx, thumbnailID)
_ = s.carrierNodeDeleteThumbnail(ctx, thumbnailID)
return "", fmt.Errorf("save thumbnail record: %w", err)
}
if insertTag.RowsAffected() == 0 {
_ = s.servantDeleteThumbnail(ctx, thumbnailID)
_ = s.carrierNodeDeleteThumbnail(ctx, thumbnailID)
return "", nil
}
return thumbnailID, nil
@@ -1017,7 +1017,7 @@ func (s *Server) analyzerThumb(w http.ResponseWriter, r *http.Request) {
writeError(w, http.StatusBadRequest, "invalid thumbnail id")
return
}
s.proxyServant(w, r, "/thumbnails/"+id+".jpg")
s.proxyCarrierNode(w, r, "/thumbnails/"+id+".jpg")
}
func (s *Server) analyzerAction(w http.ResponseWriter, r *http.Request, action string) {
@@ -1255,7 +1255,7 @@ func (s *Server) cleanupStaleMedia() {
s.scan.FilesIndexed++
s.scanMu.Unlock()
if exists, _, _, err := s.probeServant(ctx, "/media/"+urlPath(item.filePath)); err == nil && exists {
if exists, _, _, err := s.probeCarrierNode(ctx, "/media/"+urlPath(item.filePath)); err == nil && exists {
continue // file still exists on disk - nothing stale about this one
}
removed++
@@ -1264,7 +1264,7 @@ func (s *Server) cleanupStaleMedia() {
var thumbnailID string
if s.db.QueryRow(ctx, `SELECT id FROM thumbnails WHERE source_path = $1`, item.filePath).Scan(&thumbnailID) == nil {
_ = s.servantDeleteThumbnail(ctx, thumbnailID)
_ = s.carrierNodeDeleteThumbnail(ctx, thumbnailID)
_, _ = s.db.Exec(ctx, `DELETE FROM thumbnails WHERE id = $1`, thumbnailID)
}
_, _ = s.db.Exec(ctx, `DELETE FROM media_worker_jobs WHERE file_path = $1`, item.filePath)
@@ -1296,19 +1296,19 @@ func (s *Server) scanMediaFiles(selectedTypes map[string]bool) {
}()
batch := time.Now().UTC().Format("20060102T150405.000000000Z")
files, err := s.servantListFiles(ctx, "", false, 0)
files, err := s.carrierNodeListFiles(ctx, "", false, 0)
if err != nil {
log.Printf("analyzer: discovery scan: failed to list files: %v", err)
runErr = fmt.Errorf("could not reach MediaServant to list files: %w", err)
runErr = fmt.Errorf("could not reach CarrierNode to list files: %w", err)
return
}
// MediaServant reachable but reporting an empty library is otherwise indistinguishable from
// CarrierNode reachable but reporting an empty library is otherwise indistinguishable from
// a successful no-op run - every existing file re-indexes (and increments FilesIndexed) on
// every scan, so a real library can never legitimately finish at zero. Flag it instead of
// letting "discovery started" silently revert to idle with nothing to show for it.
if len(files) == 0 {
log.Printf("analyzer: discovery scan: MediaServant reported zero files")
runErr = fmt.Errorf("MediaServant reported no files under its configured media root(s) - check the Mounts settings in MediaConfig")
log.Printf("analyzer: discovery scan: CarrierNode reported zero files")
runErr = fmt.Errorf("CarrierNode reported no files under its configured media root(s) - check the Projects settings in ProjectConfigurator")
return
}
for _, file := range files {
@@ -1345,9 +1345,9 @@ func (s *Server) indexMediaFile(ctx context.Context, key string, size int64, mod
var width, height int
var probeErr error
var hasFunscript bool
// Servant has the storage mounted and can probe/stat locally; every other service goes
// through Servant's HTTP API instead of touching MediaRoots itself (see servant_client.go).
if s.cfg.Service == config.Servant {
// CarrierNode has the storage mounted and can probe/stat locally; every other service goes
// through CarrierNode's HTTP API instead of touching MediaRoots itself (see carriernode_client.go).
if s.cfg.Service == config.CarrierNode {
fullPath, resolveErr := s.resolveAnyMediaPath(ctx, key)
if metadataAttempted && resolveErr == nil {
var probe map[string]any
@@ -1361,8 +1361,8 @@ func (s *Server) indexMediaFile(ctx context.Context, key string, size int64, mod
hasFunscript = s.pipelineStageEnabled(ctx, "funscript", "metadata") && resolveErr == nil && hasFunscriptSidecar(fullPath)
} else {
if metadataAttempted {
var probe servantProbeResult
probe, probeErr = s.servantProbe(ctx, key)
var probe carrierNodeProbeResult
probe, probeErr = s.carrierNodeProbe(ctx, key)
duration = nullableInt64(probe.DurationMs)
width, height = probe.Width, probe.Height
}
@@ -1447,7 +1447,7 @@ func (s *Server) refreshMetadataForTypes(selectedTypes map[string]bool) {
s.scan.FilesIndexed++
s.scanMu.Unlock()
if exists, _, _, err := s.probeServant(ctx, "/media/"+urlPath(item.filePath)); err != nil || !exists {
if exists, _, _, err := s.probeCarrierNode(ctx, "/media/"+urlPath(item.filePath)); err != nil || !exists {
continue
}
@@ -1463,7 +1463,7 @@ func (s *Server) refreshMetadataForTypes(selectedTypes map[string]bool) {
if !s.pipelineStageEnabled(ctx, item.mediaType, "metadata") {
continue
}
probe, probeErr := s.servantProbe(ctx, item.filePath)
probe, probeErr := s.carrierNodeProbe(ctx, item.filePath)
if probeErr != nil {
_, _ = s.db.Exec(ctx, `UPDATE media_worker_jobs SET metadata_status='error', metadata_error=$2 WHERE file_path=$1`, item.filePath, probeErr.Error())
continue
@@ -1501,11 +1501,11 @@ func hasFunscriptSidecar(filePath string) bool {
}
// funscriptSidecarExists is hasFunscriptSidecar for callers without local filesystem access
// (MediaAnalyzer) - it checks for the sidecar on Servant instead of statting a local path.
// (MediaAnalyzer) - it checks for the sidecar on CarrierNode instead of statting a local path.
func (s *Server) funscriptSidecarExists(ctx context.Context, key string) bool {
base := strings.TrimSuffix(key, filepath.Ext(key))
for _, candidate := range []string{base + ".funscript", base + ".json"} {
if exists, _, _, err := s.probeServant(ctx, "/media/"+urlPath(candidate)); err == nil && exists {
if exists, _, _, err := s.probeCarrierNode(ctx, "/media/"+urlPath(candidate)); err == nil && exists {
return true
}
}
@@ -1747,7 +1747,7 @@ func (s *Server) deleteThumbnailsForType(ctx context.Context, mediaType string)
}
rows.Close()
for _, id := range ids {
_ = s.servantDeleteThumbnail(ctx, id)
_ = s.carrierNodeDeleteThumbnail(ctx, id)
}
if len(ids) > 0 {
if _, err := s.db.Exec(ctx, `DELETE FROM thumbnails WHERE id = ANY($1::uuid[])`, ids); err != nil {
@@ -1779,7 +1779,7 @@ func (s *Server) clearFunscriptFlag(ctx context.Context) error {
// picked back up fresh on the next discovery run.
func (s *Server) clearPipelineSelection(w http.ResponseWriter, r *http.Request) {
var payload struct {
Types []string `json:"types"`
Types []string `json:"types"`
Stages []string `json:"stages"`
}
if err := decodeRequestJSON(r, &payload); err != nil {
+5 -5
View File
@@ -345,7 +345,7 @@ func (s *Server) runAnalysisTask(ctx context.Context, item pendingAnalysisTask)
sourcePath := filepath.ToSlash(item.filePath)
// Video frames come from an existing thumbnail when possible (see videoAnalysisFrame) rather
// than always fetching the whole video across the wire to Servant just to grab one frame.
// than always fetching the whole video across the wire to CarrierNode just to grab one frame.
if item.mediaType == "video" && item.model != "laplacian" {
framePath, cleanup, err := s.videoAnalysisFrame(ctx, sourcePath)
if err != nil {
@@ -357,7 +357,7 @@ func (s *Server) runAnalysisTask(ctx context.Context, item pendingAnalysisTask)
return s.callAnalyzerModelsService(ctx, item.mediaType, item.task, item.model, framePath)
}
scratchPath, cleanup, err := s.fetchServantToScratch(ctx, "/media/"+urlPath(sourcePath), filepath.Ext(sourcePath))
scratchPath, cleanup, err := s.fetchCarrierNodeToScratch(ctx, "/media/"+urlPath(sourcePath), filepath.Ext(sourcePath))
if err != nil {
return nil, fmt.Errorf("fetch %s: %w", item.filePath, err)
}
@@ -385,12 +385,12 @@ func (s *Server) runAnalysisTask(ctx context.Context, item pendingAnalysisTask)
func (s *Server) videoAnalysisFrame(ctx context.Context, sourcePath string) (string, func(), error) {
var thumbnailID string
if err := s.db.QueryRow(ctx, `SELECT id FROM thumbnails WHERE source_path = $1`, sourcePath).Scan(&thumbnailID); err == nil {
if scratchPath, cleanup, fetchErr := s.fetchServantToScratch(ctx, "/thumbnails/"+thumbnailID+".jpg", ".jpg"); fetchErr == nil {
if scratchPath, cleanup, fetchErr := s.fetchCarrierNodeToScratch(ctx, "/thumbnails/"+thumbnailID+".jpg", ".jpg"); fetchErr == nil {
return scratchPath, cleanup, nil
}
}
videoScratch, cleanupVideo, err := s.fetchServantToScratch(ctx, "/media/"+urlPath(sourcePath), filepath.Ext(sourcePath))
videoScratch, cleanupVideo, err := s.fetchCarrierNodeToScratch(ctx, "/media/"+urlPath(sourcePath), filepath.Ext(sourcePath))
if err != nil {
return "", nil, fmt.Errorf("fetch %s: %w", sourcePath, err)
}
@@ -678,7 +678,7 @@ func (s *Server) retryMetadataErrors(mediaType string) {
if ctx.Err() != nil {
return
}
if probe, probeErr := s.servantProbe(ctx, filepath.ToSlash(filePath)); probeErr != nil {
if probe, probeErr := s.carrierNodeProbe(ctx, filepath.ToSlash(filePath)); probeErr != nil {
_, _ = s.db.Exec(ctx, `UPDATE media_worker_jobs SET metadata_status='error', metadata_error=$2 WHERE file_path=$1`, filePath, probeErr.Error())
} else {
duration := nullableInt64(probe.DurationMs)
@@ -0,0 +1,331 @@
package server
// CarrierNode client: every non-CarrierNode service serves and stores media by calling CarrierNode's
// HTTP API through the helpers in this file instead of touching MediaRoots/ThumbnailRoot/
// OutputRoot/DownloadsRoot/InputRoot/CopyRoot locally. CarrierNode's own handlers keep using those
// roots directly (see media.go, admin_storage.go) - this file is never called from CarrierNode's
// own code path.
import (
"bytes"
"context"
"encoding/json"
"fmt"
"io"
"net/http"
"net/url"
"os"
"strconv"
"strings"
"time"
)
// carrierNodeHTTPClient has no blanket timeout since it streams large media files; callers bound
// individual calls with a context deadline instead.
var carrierNodeHTTPClient = &http.Client{}
func (s *Server) carrierNodeClient() *http.Client {
return carrierNodeHTTPClient
}
// carrierNodeBaseURL is configured in ProjectConfigurator and stored in the settings table (key
// "carriernode_url", the same "{projectKey}_url" convention ConfigWorkspace.svelte uses for
// every project's connection URL) - not a static env var, so a change in ProjectConfigurator
// takes effect on every service's very next request without a restart. CARRIERNODE_URL is only the
// bootstrap fallback before that setting has ever been saved.
func (s *Server) carrierNodeBaseURL(ctx context.Context) string {
return strings.TrimRight(s.settingValue(ctx, "carriernode_url", s.cfg.CarrierNodeURL), "/")
}
func (s *Server) newCarrierNodeRequest(ctx context.Context, method, path string, body io.Reader) (*http.Request, error) {
request, err := http.NewRequestWithContext(ctx, method, s.carrierNodeBaseURL(ctx)+path, body)
if err != nil {
return nil, err
}
if s.cfg.InternalServiceSecret != "" {
request.Header.Set("X-Internal-Auth", s.cfg.InternalServiceSecret)
}
return request, nil
}
var carrierNodeForwardRequestHeaders = []string{"Range", "If-Modified-Since", "If-None-Match", "If-Range"}
var carrierNodeForwardResponseHeaders = []string{"Content-Type", "Content-Length", "Content-Range", "Accept-Ranges", "Last-Modified", "ETag", "Content-Disposition"}
// proxyCarrierNode streams a CarrierNode response straight through to the original client, preserving
// range/conditional-request semantics so video scrubbing keeps working without reimplementing
// http.ServeContent on this side.
func (s *Server) proxyCarrierNode(w http.ResponseWriter, r *http.Request, carrierNodePath string) {
request, err := s.newCarrierNodeRequest(r.Context(), r.Method, carrierNodePath, nil)
if err != nil {
writeError(w, http.StatusBadGateway, "media service unavailable")
return
}
for _, header := range carrierNodeForwardRequestHeaders {
if value := r.Header.Get(header); value != "" {
request.Header.Set(header, value)
}
}
response, err := s.carrierNodeClient().Do(request)
if err != nil {
writeError(w, http.StatusBadGateway, "media service unavailable")
return
}
defer response.Body.Close()
for _, header := range carrierNodeForwardResponseHeaders {
if value := response.Header.Get(header); value != "" {
w.Header().Set(header, value)
}
}
w.WriteHeader(response.StatusCode)
if r.Method != http.MethodHead {
_, _ = io.Copy(w, response.Body)
}
}
// probeCarrierNode checks whether a CarrierNode-served path exists without fetching its bytes.
// A 404 is reported as exists=false with a nil error, not a failure - only transport/5xx
// problems are surfaced as errors.
func (s *Server) probeCarrierNode(ctx context.Context, carrierNodePath string) (bool, int64, time.Time, error) {
request, err := s.newCarrierNodeRequest(ctx, http.MethodHead, carrierNodePath, nil)
if err != nil {
return false, 0, time.Time{}, err
}
response, err := s.carrierNodeClient().Do(request)
if err != nil {
return false, 0, time.Time{}, err
}
defer response.Body.Close()
if response.StatusCode == http.StatusNotFound {
return false, 0, time.Time{}, nil
}
if response.StatusCode >= 400 {
return false, 0, time.Time{}, fmt.Errorf("carriernode probe failed: %s", response.Status)
}
size, _ := strconv.ParseInt(response.Header.Get("Content-Length"), 10, 64)
modTime, _ := http.ParseTime(response.Header.Get("Last-Modified"))
return true, size, modTime, nil
}
// fetchCarrierNodeToScratch downloads a CarrierNode-served path into an ephemeral temp file for local
// processing (ffmpeg/ffprobe/yt-dlp all need a real file handle). Callers must invoke the
// returned cleanup once done; it removes the scratch file unconditionally.
func (s *Server) fetchCarrierNodeToScratch(ctx context.Context, carrierNodePath, suffix string) (string, func(), error) {
request, err := s.newCarrierNodeRequest(ctx, http.MethodGet, carrierNodePath, nil)
if err != nil {
return "", nil, err
}
response, err := s.carrierNodeClient().Do(request)
if err != nil {
return "", nil, err
}
defer response.Body.Close()
if response.StatusCode != http.StatusOK {
return "", nil, fmt.Errorf("carriernode fetch failed: %s", response.Status)
}
scratch, err := os.CreateTemp("", "carriernode-src-*"+suffix)
if err != nil {
return "", nil, err
}
cleanup := func() { _ = os.Remove(scratch.Name()) }
if _, err := io.Copy(scratch, response.Body); err != nil {
scratch.Close()
cleanup()
return "", nil, err
}
if err := scratch.Close(); err != nil {
cleanup()
return "", nil, err
}
return scratch.Name(), cleanup, nil
}
// pushToCarrierNode streams a local file as the request body without buffering it in memory.
func (s *Server) pushToCarrierNode(ctx context.Context, method, carrierNodePath, localPath string) (*http.Response, error) {
file, err := os.Open(localPath)
if err != nil {
return nil, err
}
defer file.Close()
request, err := s.newCarrierNodeRequest(ctx, method, carrierNodePath, file)
if err != nil {
return nil, err
}
if info, statErr := file.Stat(); statErr == nil {
request.ContentLength = info.Size()
}
response, err := s.carrierNodeClient().Do(request)
if err != nil {
return nil, err
}
if response.StatusCode >= 400 {
body, _ := io.ReadAll(io.LimitReader(response.Body, 4096))
response.Body.Close()
return nil, fmt.Errorf("carriernode push failed: %s: %s", response.Status, string(body))
}
return response, nil
}
func carrierNodePushedSize(response *http.Response) int64 {
defer response.Body.Close()
var payload struct {
Size int64 `json:"size"`
}
_ = json.NewDecoder(response.Body).Decode(&payload)
return payload.Size
}
func (s *Server) carrierNodePushThumbnail(ctx context.Context, id, localPath string) (int64, error) {
response, err := s.pushToCarrierNode(ctx, http.MethodPost, "/api/thumbnails/"+url.PathEscape(id), localPath)
if err != nil {
return 0, err
}
return carrierNodePushedSize(response), nil
}
func (s *Server) carrierNodeDeleteThumbnail(ctx context.Context, id string) error {
request, err := s.newCarrierNodeRequest(ctx, http.MethodDelete, "/api/thumbnails/"+url.PathEscape(id), nil)
if err != nil {
return err
}
response, err := s.carrierNodeClient().Do(request)
if err != nil {
return err
}
defer response.Body.Close()
if response.StatusCode >= 400 && response.StatusCode != http.StatusNotFound {
return fmt.Errorf("carriernode delete thumbnail failed: %s", response.Status)
}
return nil
}
func (s *Server) carrierNodePushOutput(ctx context.Context, name, localPath string) (int64, error) {
response, err := s.pushToCarrierNode(ctx, http.MethodPost, "/api/outputs/"+url.PathEscape(name), localPath)
if err != nil {
return 0, err
}
return carrierNodePushedSize(response), nil
}
func (s *Server) carrierNodePushInput(ctx context.Context, name, localPath string) (int64, error) {
response, err := s.pushToCarrierNode(ctx, http.MethodPost, "/api/inputs/"+url.PathEscape(name), localPath)
if err != nil {
return 0, err
}
return carrierNodePushedSize(response), nil
}
func (s *Server) carrierNodePushCopy(ctx context.Context, name, localPath string) (int64, error) {
response, err := s.pushToCarrierNode(ctx, http.MethodPost, "/api/copies/"+url.PathEscape(name), localPath)
if err != nil {
return 0, err
}
return carrierNodePushedSize(response), nil
}
// carrierNodeUploadDownload streams a locally-produced file (e.g. a completed yt-dlp download
// staged in a scratch dir) into CarrierNode's DownloadsRoot via its existing raw-upload endpoint.
func (s *Server) carrierNodeUploadDownload(ctx context.Context, localPath, filename string) (map[string]any, error) {
response, err := s.pushToCarrierNode(ctx, http.MethodPost, "/api/upload?filename="+url.QueryEscape(filename), localPath)
if err != nil {
return nil, err
}
defer response.Body.Close()
var payload map[string]any
_ = json.NewDecoder(response.Body).Decode(&payload)
return payload, nil
}
// carrierNodeStoreDownload catalogs an already-uploaded file into CarrierNode's media/downloaded_media
// tables via its existing /api/store endpoint - callers should stop duplicating that DB write
// locally once they migrate to this.
func (s *Server) carrierNodeStoreDownload(ctx context.Context, filePath, sourceURL, tool, status string) (map[string]any, error) {
body, err := json.Marshal(map[string]any{"filePath": filePath, "sourceUrl": sourceURL, "tool": tool, "status": status})
if err != nil {
return nil, err
}
request, err := s.newCarrierNodeRequest(ctx, http.MethodPost, "/api/store", bytes.NewReader(body))
if err != nil {
return nil, err
}
request.Header.Set("Content-Type", "application/json")
response, err := s.carrierNodeClient().Do(request)
if err != nil {
return nil, err
}
defer response.Body.Close()
if response.StatusCode >= 400 {
errorBody, _ := io.ReadAll(io.LimitReader(response.Body, 4096))
return nil, fmt.Errorf("carriernode store failed: %s: %s", response.Status, string(errorBody))
}
var payload map[string]any
_ = json.NewDecoder(response.Body).Decode(&payload)
return payload, nil
}
// carrierNodeListFiles lists files under CarrierNode's MediaRoots via its existing /api/files(/recent)
// endpoints - the replacement for a local filepath.WalkDir over MediaRoots.
func (s *Server) carrierNodeListFiles(ctx context.Context, relative string, recent bool, limit int) ([]fileEntry, error) {
endpoint := "/api/files"
if recent {
endpoint = "/api/files/recent"
}
query := url.Values{}
if relative != "" {
query.Set("path", relative)
}
if limit > 0 {
query.Set("limit", strconv.Itoa(limit))
}
if encoded := query.Encode(); encoded != "" {
endpoint += "?" + encoded
}
request, err := s.newCarrierNodeRequest(ctx, http.MethodGet, endpoint, nil)
if err != nil {
return nil, err
}
response, err := s.carrierNodeClient().Do(request)
if err != nil {
return nil, err
}
defer response.Body.Close()
if response.StatusCode != http.StatusOK {
return nil, fmt.Errorf("carriernode file listing failed: %s", response.Status)
}
var payload struct {
Files []fileEntry `json:"files"`
}
if err := json.NewDecoder(response.Body).Decode(&payload); err != nil {
return nil, err
}
return payload.Files, nil
}
type carrierNodeProbeResult struct {
DurationMs int64 `json:"durationMs"`
Width int `json:"width"`
Height int `json:"height"`
}
// carrierNodeProbe runs ffprobe on CarrierNode against a MediaRoots-relative path and returns just the
// metadata fields - bytes never leave CarrierNode, unlike every other helper in this file.
func (s *Server) carrierNodeProbe(ctx context.Context, relative string) (carrierNodeProbeResult, error) {
query := url.Values{}
query.Set("path", relative)
request, err := s.newCarrierNodeRequest(ctx, http.MethodGet, "/api/probe?"+query.Encode(), nil)
if err != nil {
return carrierNodeProbeResult{}, err
}
response, err := s.carrierNodeClient().Do(request)
if err != nil {
return carrierNodeProbeResult{}, err
}
defer response.Body.Close()
if response.StatusCode != http.StatusOK {
return carrierNodeProbeResult{}, fmt.Errorf("carriernode probe failed: %s", response.Status)
}
var result carrierNodeProbeResult
if err := json.NewDecoder(response.Body).Decode(&result); err != nil {
return carrierNodeProbeResult{}, err
}
return result, nil
}
+3 -3
View File
@@ -13,7 +13,7 @@ import (
"github.com/coder/websocket"
"github.com/go-chi/chi/v5"
"mediacollection/internal/config"
"repos.gfranz.ch/Gabriel20xx/shared/media-backend/internal/config"
)
type kioskMessage struct {
@@ -120,7 +120,7 @@ func (s *Server) kioskPoll(ctx context.Context) {
}
func (s *Server) kioskPollOnce(ctx context.Context) {
files, err := s.servantListFiles(ctx, "", false, 0)
files, err := s.carrierNodeListFiles(ctx, "", false, 0)
if err != nil {
return
}
@@ -179,7 +179,7 @@ func (s *Server) kioskImage(w http.ResponseWriter, r *http.Request) {
writeError(w, http.StatusNotFound, "image not found")
return
}
s.proxyServant(w, r, "/media/"+urlPath(relative))
s.proxyCarrierNode(w, r, "/media/"+urlPath(relative))
}
func kioskDuration(value string) int64 {
+8 -8
View File
@@ -17,7 +17,7 @@ import (
"github.com/go-chi/chi/v5"
"mediacollection/internal/auth"
"repos.gfranz.ch/Gabriel20xx/shared/media-backend/internal/auth"
)
func (s *Server) mountSharedRoutes(r chi.Router) {
@@ -242,7 +242,7 @@ func (s *Server) streamMediaIdentifier(w http.ResponseWriter, r *http.Request, i
writeError(w, http.StatusNotFound, "media not found")
return
}
s.proxyServant(w, r, "/media/"+urlPath(record.FilePath))
s.proxyCarrierNode(w, r, "/media/"+urlPath(record.FilePath))
}
func (s *Server) thumbnailMedia(w http.ResponseWriter, r *http.Request) {
@@ -261,8 +261,8 @@ func (s *Server) thumbnailMediaIdentifier(w http.ResponseWriter, r *http.Request
}
if !strings.Contains(id, string(filepath.Separator)) && !strings.Contains(id, "/") {
thumbnailPath := "/thumbnails/" + id + ".jpg"
if exists, _, _, err := s.probeServant(r.Context(), thumbnailPath); err == nil && exists {
s.proxyServant(w, r, thumbnailPath)
if exists, _, _, err := s.probeCarrierNode(r.Context(), thumbnailPath); err == nil && exists {
s.proxyCarrierNode(w, r, thumbnailPath)
return
}
}
@@ -271,7 +271,7 @@ func (s *Server) thumbnailMediaIdentifier(w http.ResponseWriter, r *http.Request
writeError(w, http.StatusNotFound, "thumbnail not found")
return
}
s.proxyServant(w, r, "/media/"+urlPath(record.FilePath))
s.proxyCarrierNode(w, r, "/media/"+urlPath(record.FilePath))
}
func (s *Server) funscriptMedia(w http.ResponseWriter, r *http.Request) {
@@ -283,8 +283,8 @@ func (s *Server) funscriptMedia(w http.ResponseWriter, r *http.Request) {
base := strings.TrimSuffix(record.FilePath, filepath.Ext(record.FilePath))
for _, candidate := range []string{base + ".funscript", base + ".json"} {
candidatePath := "/media/" + urlPath(candidate)
if exists, _, _, err := s.probeServant(r.Context(), candidatePath); err == nil && exists {
s.proxyServant(w, r, candidatePath)
if exists, _, _, err := s.probeCarrierNode(r.Context(), candidatePath); err == nil && exists {
s.proxyCarrierNode(w, r, candidatePath)
return
}
}
@@ -298,7 +298,7 @@ func (s *Server) mediaFileInfo(w http.ResponseWriter, r *http.Request) {
return
}
response := record.toJSON()
if exists, size, modTime, err := s.probeServant(r.Context(), "/media/"+urlPath(record.FilePath)); err == nil && exists {
if exists, size, modTime, err := s.probeCarrierNode(r.Context(), "/media/"+urlPath(record.FilePath)); err == nil && exists {
response["absolutePath"] = ""
response["sizeBytes"] = size
response["modifiedAt"] = modTime
@@ -1,331 +0,0 @@
package server
// Servant client: every non-Servant service serves and stores media by calling MediaServant's
// HTTP API through the helpers in this file instead of touching MediaRoots/ThumbnailRoot/
// OutputRoot/DownloadsRoot/InputRoot/CopyRoot locally. Servant's own handlers keep using those
// roots directly (see media.go, admin_storage.go) - this file is never called from Servant's
// own code path.
import (
"bytes"
"context"
"encoding/json"
"fmt"
"io"
"net/http"
"net/url"
"os"
"strconv"
"strings"
"time"
)
// servantHTTPClient has no blanket timeout since it streams large media files; callers bound
// individual calls with a context deadline instead.
var servantHTTPClient = &http.Client{}
func (s *Server) servantClient() *http.Client {
return servantHTTPClient
}
// servantBaseURL is configured in MediaConfig and stored in the settings table (key
// "mediaservant_url", the same "{projectKey}_url" convention ConfigWorkspace.svelte uses for
// every project's connection URL) - not a static env var, so a change in MediaConfig takes
// effect on every service's very next request without a restart. SERVANT_URL is only the
// bootstrap fallback before that setting has ever been saved.
func (s *Server) servantBaseURL(ctx context.Context) string {
return strings.TrimRight(s.settingValue(ctx, "mediaservant_url", s.cfg.ServantURL), "/")
}
func (s *Server) newServantRequest(ctx context.Context, method, path string, body io.Reader) (*http.Request, error) {
request, err := http.NewRequestWithContext(ctx, method, s.servantBaseURL(ctx)+path, body)
if err != nil {
return nil, err
}
if s.cfg.InternalServiceSecret != "" {
request.Header.Set("X-Internal-Auth", s.cfg.InternalServiceSecret)
}
return request, nil
}
var servantForwardRequestHeaders = []string{"Range", "If-Modified-Since", "If-None-Match", "If-Range"}
var servantForwardResponseHeaders = []string{"Content-Type", "Content-Length", "Content-Range", "Accept-Ranges", "Last-Modified", "ETag", "Content-Disposition"}
// proxyServant streams a Servant response straight through to the original client, preserving
// range/conditional-request semantics so video scrubbing keeps working without reimplementing
// http.ServeContent on this side.
func (s *Server) proxyServant(w http.ResponseWriter, r *http.Request, servantPath string) {
request, err := s.newServantRequest(r.Context(), r.Method, servantPath, nil)
if err != nil {
writeError(w, http.StatusBadGateway, "media service unavailable")
return
}
for _, header := range servantForwardRequestHeaders {
if value := r.Header.Get(header); value != "" {
request.Header.Set(header, value)
}
}
response, err := s.servantClient().Do(request)
if err != nil {
writeError(w, http.StatusBadGateway, "media service unavailable")
return
}
defer response.Body.Close()
for _, header := range servantForwardResponseHeaders {
if value := response.Header.Get(header); value != "" {
w.Header().Set(header, value)
}
}
w.WriteHeader(response.StatusCode)
if r.Method != http.MethodHead {
_, _ = io.Copy(w, response.Body)
}
}
// probeServant checks whether a Servant-served path exists without fetching its bytes.
// A 404 is reported as exists=false with a nil error, not a failure - only transport/5xx
// problems are surfaced as errors.
func (s *Server) probeServant(ctx context.Context, servantPath string) (bool, int64, time.Time, error) {
request, err := s.newServantRequest(ctx, http.MethodHead, servantPath, nil)
if err != nil {
return false, 0, time.Time{}, err
}
response, err := s.servantClient().Do(request)
if err != nil {
return false, 0, time.Time{}, err
}
defer response.Body.Close()
if response.StatusCode == http.StatusNotFound {
return false, 0, time.Time{}, nil
}
if response.StatusCode >= 400 {
return false, 0, time.Time{}, fmt.Errorf("servant probe failed: %s", response.Status)
}
size, _ := strconv.ParseInt(response.Header.Get("Content-Length"), 10, 64)
modTime, _ := http.ParseTime(response.Header.Get("Last-Modified"))
return true, size, modTime, nil
}
// fetchServantToScratch downloads a Servant-served path into an ephemeral temp file for local
// processing (ffmpeg/ffprobe/yt-dlp all need a real file handle). Callers must invoke the
// returned cleanup once done; it removes the scratch file unconditionally.
func (s *Server) fetchServantToScratch(ctx context.Context, servantPath, suffix string) (string, func(), error) {
request, err := s.newServantRequest(ctx, http.MethodGet, servantPath, nil)
if err != nil {
return "", nil, err
}
response, err := s.servantClient().Do(request)
if err != nil {
return "", nil, err
}
defer response.Body.Close()
if response.StatusCode != http.StatusOK {
return "", nil, fmt.Errorf("servant fetch failed: %s", response.Status)
}
scratch, err := os.CreateTemp("", "servant-src-*"+suffix)
if err != nil {
return "", nil, err
}
cleanup := func() { _ = os.Remove(scratch.Name()) }
if _, err := io.Copy(scratch, response.Body); err != nil {
scratch.Close()
cleanup()
return "", nil, err
}
if err := scratch.Close(); err != nil {
cleanup()
return "", nil, err
}
return scratch.Name(), cleanup, nil
}
// pushToServant streams a local file as the request body without buffering it in memory.
func (s *Server) pushToServant(ctx context.Context, method, servantPath, localPath string) (*http.Response, error) {
file, err := os.Open(localPath)
if err != nil {
return nil, err
}
defer file.Close()
request, err := s.newServantRequest(ctx, method, servantPath, file)
if err != nil {
return nil, err
}
if info, statErr := file.Stat(); statErr == nil {
request.ContentLength = info.Size()
}
response, err := s.servantClient().Do(request)
if err != nil {
return nil, err
}
if response.StatusCode >= 400 {
body, _ := io.ReadAll(io.LimitReader(response.Body, 4096))
response.Body.Close()
return nil, fmt.Errorf("servant push failed: %s: %s", response.Status, string(body))
}
return response, nil
}
func servantPushedSize(response *http.Response) int64 {
defer response.Body.Close()
var payload struct {
Size int64 `json:"size"`
}
_ = json.NewDecoder(response.Body).Decode(&payload)
return payload.Size
}
func (s *Server) servantPushThumbnail(ctx context.Context, id, localPath string) (int64, error) {
response, err := s.pushToServant(ctx, http.MethodPost, "/api/thumbnails/"+url.PathEscape(id), localPath)
if err != nil {
return 0, err
}
return servantPushedSize(response), nil
}
func (s *Server) servantDeleteThumbnail(ctx context.Context, id string) error {
request, err := s.newServantRequest(ctx, http.MethodDelete, "/api/thumbnails/"+url.PathEscape(id), nil)
if err != nil {
return err
}
response, err := s.servantClient().Do(request)
if err != nil {
return err
}
defer response.Body.Close()
if response.StatusCode >= 400 && response.StatusCode != http.StatusNotFound {
return fmt.Errorf("servant delete thumbnail failed: %s", response.Status)
}
return nil
}
func (s *Server) servantPushOutput(ctx context.Context, name, localPath string) (int64, error) {
response, err := s.pushToServant(ctx, http.MethodPost, "/api/outputs/"+url.PathEscape(name), localPath)
if err != nil {
return 0, err
}
return servantPushedSize(response), nil
}
func (s *Server) servantPushInput(ctx context.Context, name, localPath string) (int64, error) {
response, err := s.pushToServant(ctx, http.MethodPost, "/api/inputs/"+url.PathEscape(name), localPath)
if err != nil {
return 0, err
}
return servantPushedSize(response), nil
}
func (s *Server) servantPushCopy(ctx context.Context, name, localPath string) (int64, error) {
response, err := s.pushToServant(ctx, http.MethodPost, "/api/copies/"+url.PathEscape(name), localPath)
if err != nil {
return 0, err
}
return servantPushedSize(response), nil
}
// servantUploadDownload streams a locally-produced file (e.g. a completed yt-dlp download
// staged in a scratch dir) into Servant's DownloadsRoot via its existing raw-upload endpoint.
func (s *Server) servantUploadDownload(ctx context.Context, localPath, filename string) (map[string]any, error) {
response, err := s.pushToServant(ctx, http.MethodPost, "/api/upload?filename="+url.QueryEscape(filename), localPath)
if err != nil {
return nil, err
}
defer response.Body.Close()
var payload map[string]any
_ = json.NewDecoder(response.Body).Decode(&payload)
return payload, nil
}
// servantStoreDownload catalogs an already-uploaded file into Servant's media/downloaded_media
// tables via its existing /api/store endpoint - callers should stop duplicating that DB write
// locally once they migrate to this.
func (s *Server) servantStoreDownload(ctx context.Context, filePath, sourceURL, tool, status string) (map[string]any, error) {
body, err := json.Marshal(map[string]any{"filePath": filePath, "sourceUrl": sourceURL, "tool": tool, "status": status})
if err != nil {
return nil, err
}
request, err := s.newServantRequest(ctx, http.MethodPost, "/api/store", bytes.NewReader(body))
if err != nil {
return nil, err
}
request.Header.Set("Content-Type", "application/json")
response, err := s.servantClient().Do(request)
if err != nil {
return nil, err
}
defer response.Body.Close()
if response.StatusCode >= 400 {
errorBody, _ := io.ReadAll(io.LimitReader(response.Body, 4096))
return nil, fmt.Errorf("servant store failed: %s: %s", response.Status, string(errorBody))
}
var payload map[string]any
_ = json.NewDecoder(response.Body).Decode(&payload)
return payload, nil
}
// servantListFiles lists files under Servant's MediaRoots via its existing /api/files(/recent)
// endpoints - the replacement for a local filepath.WalkDir over MediaRoots.
func (s *Server) servantListFiles(ctx context.Context, relative string, recent bool, limit int) ([]fileEntry, error) {
endpoint := "/api/files"
if recent {
endpoint = "/api/files/recent"
}
query := url.Values{}
if relative != "" {
query.Set("path", relative)
}
if limit > 0 {
query.Set("limit", strconv.Itoa(limit))
}
if encoded := query.Encode(); encoded != "" {
endpoint += "?" + encoded
}
request, err := s.newServantRequest(ctx, http.MethodGet, endpoint, nil)
if err != nil {
return nil, err
}
response, err := s.servantClient().Do(request)
if err != nil {
return nil, err
}
defer response.Body.Close()
if response.StatusCode != http.StatusOK {
return nil, fmt.Errorf("servant file listing failed: %s", response.Status)
}
var payload struct {
Files []fileEntry `json:"files"`
}
if err := json.NewDecoder(response.Body).Decode(&payload); err != nil {
return nil, err
}
return payload.Files, nil
}
type servantProbeResult struct {
DurationMs int64 `json:"durationMs"`
Width int `json:"width"`
Height int `json:"height"`
}
// servantProbe runs ffprobe on Servant against a MediaRoots-relative path and returns just the
// metadata fields - bytes never leave Servant, unlike every other helper in this file.
func (s *Server) servantProbe(ctx context.Context, relative string) (servantProbeResult, error) {
query := url.Values{}
query.Set("path", relative)
request, err := s.newServantRequest(ctx, http.MethodGet, "/api/probe?"+query.Encode(), nil)
if err != nil {
return servantProbeResult{}, err
}
response, err := s.servantClient().Do(request)
if err != nil {
return servantProbeResult{}, err
}
defer response.Body.Close()
if response.StatusCode != http.StatusOK {
return servantProbeResult{}, fmt.Errorf("servant probe failed: %s", response.Status)
}
var result servantProbeResult
if err := json.NewDecoder(response.Body).Decode(&result); err != nil {
return servantProbeResult{}, err
}
return result, nil
}
+15 -12
View File
@@ -18,8 +18,8 @@ import (
chimiddleware "github.com/go-chi/chi/v5/middleware"
"github.com/jackc/pgx/v5/pgxpool"
"mediacollection/internal/auth"
"mediacollection/internal/config"
"repos.gfranz.ch/Gabriel20xx/shared/media-backend/internal/auth"
"repos.gfranz.ch/Gabriel20xx/shared/media-backend/internal/config"
)
type Server struct {
@@ -129,7 +129,7 @@ type scanState struct {
Total int64
StartedAt *time.Time
// LastError survives the end-of-run reset (unlike every other field here) so a run that
// failed fast - e.g. MediaServant unreachable - doesn't just look like it silently reverted
// failed fast - e.g. CarrierNode unreachable - doesn't just look like it silently reverted
// to idle; analyzerStatus reports it until the next run overwrites or clears it.
LastError string
}
@@ -192,14 +192,14 @@ func (s *Server) Handler() http.Handler {
if s.cfg.Service != config.Kiosk {
router.HandleFunc("/ws", s.syncWebsocket)
}
if s.cfg.Service == config.Servant {
if s.cfg.Service == config.CarrierNode {
internal := s.internalServiceAuth
router.Handle("/media/downloads/*", internal(http.HandlerFunc(s.servantDownloadMedia)))
router.Handle("/mount/generated/*", internal(http.HandlerFunc(s.servantGeneratedMedia)))
router.Handle("/mount/inputs/*", internal(http.HandlerFunc(s.servantInputMedia)))
router.Handle("/mount/copies/*", internal(http.HandlerFunc(s.servantCopyMedia)))
router.Handle("/media/*", internal(http.HandlerFunc(s.servantMedia)))
router.Handle("/thumbnails/*", internal(http.HandlerFunc(s.servantThumbnail)))
router.Handle("/media/downloads/*", internal(http.HandlerFunc(s.carrierNodeDownloadMedia)))
router.Handle("/mount/generated/*", internal(http.HandlerFunc(s.carrierNodeGeneratedMedia)))
router.Handle("/mount/inputs/*", internal(http.HandlerFunc(s.carrierNodeInputMedia)))
router.Handle("/mount/copies/*", internal(http.HandlerFunc(s.carrierNodeCopyMedia)))
router.Handle("/media/*", internal(http.HandlerFunc(s.carrierNodeMedia)))
router.Handle("/thumbnails/*", internal(http.HandlerFunc(s.carrierNodeThumbnail)))
}
router.NotFound(s.staticHandler)
@@ -221,8 +221,8 @@ func (s *Server) mountServiceRoutes(r chi.Router) {
s.mountModeratorRoutes(r)
case config.Kiosk:
s.mountKioskRoutes(r)
case config.Servant:
s.mountServantRoutes(r)
case config.CarrierNode:
s.mountCarrierNodeRoutes(r)
}
}
@@ -340,6 +340,9 @@ func (s *Server) Run(ctx context.Context) error {
if s.cfg.Service == config.Analyzer {
go s.runAnalyzerScheduler(ctx)
}
if s.cfg.Service == config.ConfigService {
go s.runSettingsSyncScheduler(ctx)
}
return s.listenAndServe(ctx)
}
+21 -21
View File
@@ -21,7 +21,7 @@ import (
"github.com/go-chi/chi/v5"
"mediacollection/internal/auth"
"repos.gfranz.ch/Gabriel20xx/shared/media-backend/internal/auth"
)
func (s *Server) mountToolsRoutes(r chi.Router) {
@@ -298,7 +298,7 @@ func (s *Server) executeConversion(ctx context.Context, job WorkflowJob) (map[st
if sourceName == "" {
return nil, fmt.Errorf("converter input path is required")
}
source, cleanupSource, err := s.fetchWorkflowFileFromServant(ctx, sourceName)
source, cleanupSource, err := s.fetchWorkflowFileFromCarrierNode(ctx, sourceName)
if err != nil {
return nil, fmt.Errorf("converter input is not an allowed file: %w", err)
}
@@ -334,7 +334,7 @@ func (s *Server) executeConversion(ctx context.Context, job WorkflowJob) (map[st
if err != nil || info.IsDir() {
return nil, fmt.Errorf("ffmpeg did not produce an output file")
}
size, err := s.servantPushOutput(ctx, outputName, outputPath)
size, err := s.carrierNodePushOutput(ctx, outputName, outputPath)
if err != nil {
return nil, fmt.Errorf("converted output could not be stored: %w", err)
}
@@ -371,9 +371,9 @@ func (s *Server) executeDownload(ctx context.Context, job WorkflowJob) (map[stri
return nil, fmt.Errorf("downloaded file is unavailable")
}
filename := filepath.Base(filePath)
// Pushing through Servant's upload endpoint also catalogs the file into media/media_worker_jobs
// (see servantRawUpload) - no separate indexMediaFile call needed here.
if _, err := s.servantUploadDownload(ctx, filePath, filename); err != nil {
// Pushing through CarrierNode's upload endpoint also catalogs the file into media/media_worker_jobs
// (see carrierNodeRawUpload) - no separate indexMediaFile call needed here.
if _, err := s.carrierNodeUploadDownload(ctx, filePath, filename); err != nil {
return nil, fmt.Errorf("downloaded file could not be stored: %w", err)
}
_, _ = s.db.Exec(ctx, `INSERT INTO downloaded_media (source_url, tool, file_path, file_name, file_size_bytes, status, started_at, finished_at) VALUES ($1,'yt-dlp',$2,$3,$4,'completed',$5,NOW())`, sourceURL, filename, filename, info.Size(), job.CreatedAt)
@@ -439,25 +439,25 @@ func firstString(values map[string]any, keys ...string) string {
return ""
}
// workflowFileServantPaths mirrors the search order resolveWorkflowFile used to walk locally
// (InputRoot, MediaRoots, DownloadsRoot, OutputRoot) but as Servant-side mount prefixes, since
// workflowFileCarrierNodePaths mirrors the search order resolveWorkflowFile used to walk locally
// (InputRoot, MediaRoots, DownloadsRoot, OutputRoot) but as CarrierNode-side mount prefixes, since
// MediaTools no longer has any of those roots mounted on its own filesystem.
var workflowFileServantPaths = []string{"/mount/inputs/", "/media/", "/media/downloads/", "/mount/generated/"}
var workflowFileCarrierNodePaths = []string{"/mount/inputs/", "/media/", "/media/downloads/", "/mount/generated/"}
// fetchWorkflowFileFromServant locates a converter input under any of Servant's mounts and
// fetchWorkflowFileFromCarrierNode locates a converter input under any of CarrierNode's mounts and
// downloads it into an ephemeral scratch file for ffmpeg to read; the caller must invoke the
// returned cleanup once done.
func (s *Server) fetchWorkflowFileFromServant(ctx context.Context, value string) (string, func(), error) {
func (s *Server) fetchWorkflowFileFromCarrierNode(ctx context.Context, value string) (string, func(), error) {
value = strings.TrimSpace(value)
if !safeRelative(value) {
return "", nil, os.ErrNotExist
}
for _, prefix := range workflowFileServantPaths {
servantPath := prefix + urlPath(value)
if exists, _, _, err := s.probeServant(ctx, servantPath); err != nil || !exists {
for _, prefix := range workflowFileCarrierNodePaths {
carrierNodePath := prefix + urlPath(value)
if exists, _, _, err := s.probeCarrierNode(ctx, carrierNodePath); err != nil || !exists {
continue
}
return s.fetchServantToScratch(ctx, servantPath, filepath.Ext(value))
return s.fetchCarrierNodeToScratch(ctx, carrierNodePath, filepath.Ext(value))
}
return "", nil, os.ErrNotExist
}
@@ -723,7 +723,7 @@ func (s *Server) uploadCopy(w http.ResponseWriter, r *http.Request) {
if s.cfg.MaxUploadBytes > 0 {
r.Body = http.MaxBytesReader(w, r.Body, s.cfg.MaxUploadBytes)
}
filename, size, err := s.saveMultipartUpload(r, s.servantPushCopy)
filename, size, err := s.saveMultipartUpload(r, s.carrierNodePushCopy)
if err != nil {
writeError(w, http.StatusBadRequest, err.Error())
return
@@ -736,7 +736,7 @@ func (s *Server) toolUpload(w http.ResponseWriter, r *http.Request) {
if s.cfg.MaxUploadBytes > 0 {
r.Body = http.MaxBytesReader(w, r.Body, s.cfg.MaxUploadBytes)
}
filename, size, err := s.saveMultipartUpload(r, s.servantPushInput)
filename, size, err := s.saveMultipartUpload(r, s.carrierNodePushInput)
if err != nil {
writeError(w, http.StatusBadRequest, err.Error())
return
@@ -815,7 +815,7 @@ func (s *Server) toolFile(w http.ResponseWriter, r *http.Request, mountPrefix st
writeError(w, http.StatusNotFound, "file not found")
return
}
s.proxyServant(w, r, mountPrefix+urlPath(relative))
s.proxyCarrierNode(w, r, mountPrefix+urlPath(relative))
}
func (s *Server) workflowList(w http.ResponseWriter, _ *http.Request) {
@@ -895,13 +895,13 @@ func (s *Server) downloadWorkflowResult(w http.ResponseWriter, r *http.Request)
writeError(w, http.StatusNotFound, "job result not found")
return
}
servantPath := "/mount/generated/" + urlPath(filename)
if exists, _, _, err := s.probeServant(r.Context(), servantPath); err != nil || !exists {
carrierNodePath := "/mount/generated/" + urlPath(filename)
if exists, _, _, err := s.probeCarrierNode(r.Context(), carrierNodePath); err != nil || !exists {
writeError(w, http.StatusGone, "job result is no longer available")
return
}
w.Header().Set("Content-Disposition", `attachment; filename="`+filepath.Base(filename)+`"`)
s.proxyServant(w, r, servantPath)
s.proxyCarrierNode(w, r, carrierNodePath)
}
func scanWorkflowJob(row interface{ Scan(...any) error }) (WorkflowJob, error) {
File diff suppressed because it is too large. Load diff
+91 -387
View File
@@ -283,6 +283,7 @@
"os": [
"aix"
],
"peer": true,
"engines": {
"node": ">=18"
}
@@ -300,6 +301,7 @@
"os": [
"android"
],
"peer": true,
"engines": {
"node": ">=18"
}
@@ -317,6 +319,7 @@
"os": [
"android"
],
"peer": true,
"engines": {
"node": ">=18"
}
@@ -334,6 +337,7 @@
"os": [
"android"
],
"peer": true,
"engines": {
"node": ">=18"
}
@@ -351,6 +355,7 @@
"os": [
"darwin"
],
"peer": true,
"engines": {
"node": ">=18"
}
@@ -368,6 +373,7 @@
"os": [
"darwin"
],
"peer": true,
"engines": {
"node": ">=18"
}
@@ -385,6 +391,7 @@
"os": [
"freebsd"
],
"peer": true,
"engines": {
"node": ">=18"
}
@@ -402,6 +409,7 @@
"os": [
"freebsd"
],
"peer": true,
"engines": {
"node": ">=18"
}
@@ -419,6 +427,7 @@
"os": [
"linux"
],
"peer": true,
"engines": {
"node": ">=18"
}
@@ -436,6 +445,7 @@
"os": [
"linux"
],
"peer": true,
"engines": {
"node": ">=18"
}
@@ -453,6 +463,7 @@
"os": [
"linux"
],
"peer": true,
"engines": {
"node": ">=18"
}
@@ -470,6 +481,7 @@
"os": [
"linux"
],
"peer": true,
"engines": {
"node": ">=18"
}
@@ -487,6 +499,7 @@
"os": [
"linux"
],
"peer": true,
"engines": {
"node": ">=18"
}
@@ -504,6 +517,7 @@
"os": [
"linux"
],
"peer": true,
"engines": {
"node": ">=18"
}
@@ -521,6 +535,7 @@
"os": [
"linux"
],
"peer": true,
"engines": {
"node": ">=18"
}
@@ -538,6 +553,7 @@
"os": [
"linux"
],
"peer": true,
"engines": {
"node": ">=18"
}
@@ -555,6 +571,7 @@
"os": [
"linux"
],
"peer": true,
"engines": {
"node": ">=18"
}
@@ -572,6 +589,7 @@
"os": [
"netbsd"
],
"peer": true,
"engines": {
"node": ">=18"
}
@@ -589,6 +607,7 @@
"os": [
"netbsd"
],
"peer": true,
"engines": {
"node": ">=18"
}
@@ -606,6 +625,7 @@
"os": [
"openbsd"
],
"peer": true,
"engines": {
"node": ">=18"
}
@@ -623,6 +643,7 @@
"os": [
"openbsd"
],
"peer": true,
"engines": {
"node": ">=18"
}
@@ -640,6 +661,7 @@
"os": [
"openharmony"
],
"peer": true,
"engines": {
"node": ">=18"
}
@@ -657,6 +679,7 @@
"os": [
"sunos"
],
"peer": true,
"engines": {
"node": ">=18"
}
@@ -674,6 +697,7 @@
"os": [
"win32"
],
"peer": true,
"engines": {
"node": ">=18"
}
@@ -691,6 +715,7 @@
"os": [
"win32"
],
"peer": true,
"engines": {
"node": ">=18"
}
@@ -708,6 +733,7 @@
"os": [
"win32"
],
"peer": true,
"engines": {
"node": ">=18"
}
@@ -716,8 +742,8 @@
"resolved": "packages/design-tokens",
"link": true
},
"node_modules/@gabriel20xx/media-shared-assets": {
"resolved": "packages/media-shared-assets",
"node_modules/@gabriel20xx/legacy-assets": {
"resolved": "packages/legacy-assets",
"link": true
},
"node_modules/@gabriel20xx/node-backend": {
@@ -892,6 +918,7 @@
"os": [
"linux"
],
"peer": true,
"engines": {
"node": "^22.20 || ^24.12 || >=25"
}
@@ -946,7 +973,8 @@
"optional": true,
"os": [
"android"
]
],
"peer": true
},
"node_modules/@rollup/rollup-android-arm64": {
"version": "4.62.4",
@@ -960,7 +988,8 @@
"optional": true,
"os": [
"android"
]
],
"peer": true
},
"node_modules/@rollup/rollup-darwin-arm64": {
"version": "4.62.4",
@@ -974,7 +1003,8 @@
"optional": true,
"os": [
"darwin"
]
],
"peer": true
},
"node_modules/@rollup/rollup-darwin-x64": {
"version": "4.62.4",
@@ -988,7 +1018,8 @@
"optional": true,
"os": [
"darwin"
]
],
"peer": true
},
"node_modules/@rollup/rollup-freebsd-arm64": {
"version": "4.62.4",
@@ -1002,7 +1033,8 @@
"optional": true,
"os": [
"freebsd"
]
],
"peer": true
},
"node_modules/@rollup/rollup-freebsd-x64": {
"version": "4.62.4",
@@ -1016,7 +1048,8 @@
"optional": true,
"os": [
"freebsd"
]
],
"peer": true
},
"node_modules/@rollup/rollup-linux-arm-gnueabihf": {
"version": "4.62.4",
@@ -1033,7 +1066,8 @@
"optional": true,
"os": [
"linux"
]
],
"peer": true
},
"node_modules/@rollup/rollup-linux-arm-musleabihf": {
"version": "4.62.4",
@@ -1050,7 +1084,8 @@
"optional": true,
"os": [
"linux"
]
],
"peer": true
},
"node_modules/@rollup/rollup-linux-arm64-gnu": {
"version": "4.62.4",
@@ -1067,7 +1102,8 @@
"optional": true,
"os": [
"linux"
]
],
"peer": true
},
"node_modules/@rollup/rollup-linux-arm64-musl": {
"version": "4.62.4",
@@ -1084,7 +1120,8 @@
"optional": true,
"os": [
"linux"
]
],
"peer": true
},
"node_modules/@rollup/rollup-linux-loong64-gnu": {
"version": "4.62.4",
@@ -1101,7 +1138,8 @@
"optional": true,
"os": [
"linux"
]
],
"peer": true
},
"node_modules/@rollup/rollup-linux-loong64-musl": {
"version": "4.62.4",
@@ -1118,7 +1156,8 @@
"optional": true,
"os": [
"linux"
]
],
"peer": true
},
"node_modules/@rollup/rollup-linux-ppc64-gnu": {
"version": "4.62.4",
@@ -1135,7 +1174,8 @@
"optional": true,
"os": [
"linux"
]
],
"peer": true
},
"node_modules/@rollup/rollup-linux-ppc64-musl": {
"version": "4.62.4",
@@ -1152,7 +1192,8 @@
"optional": true,
"os": [
"linux"
]
],
"peer": true
},
"node_modules/@rollup/rollup-linux-riscv64-gnu": {
"version": "4.62.4",
@@ -1169,7 +1210,8 @@
"optional": true,
"os": [
"linux"
]
],
"peer": true
},
"node_modules/@rollup/rollup-linux-riscv64-musl": {
"version": "4.62.4",
@@ -1186,7 +1228,8 @@
"optional": true,
"os": [
"linux"
]
],
"peer": true
},
"node_modules/@rollup/rollup-linux-s390x-gnu": {
"version": "4.62.4",
@@ -1203,7 +1246,8 @@
"optional": true,
"os": [
"linux"
]
],
"peer": true
},
"node_modules/@rollup/rollup-linux-x64-gnu": {
"version": "4.62.4",
@@ -1220,7 +1264,8 @@
"optional": true,
"os": [
"linux"
]
],
"peer": true
},
"node_modules/@rollup/rollup-linux-x64-musl": {
"version": "4.62.4",
@@ -1237,7 +1282,8 @@
"optional": true,
"os": [
"linux"
]
],
"peer": true
},
"node_modules/@rollup/rollup-openbsd-x64": {
"version": "4.62.4",
@@ -1251,7 +1297,8 @@
"optional": true,
"os": [
"openbsd"
]
],
"peer": true
},
"node_modules/@rollup/rollup-openharmony-arm64": {
"version": "4.62.4",
@@ -1265,7 +1312,8 @@
"optional": true,
"os": [
"openharmony"
]
],
"peer": true
},
"node_modules/@rollup/rollup-win32-arm64-msvc": {
"version": "4.62.4",
@@ -1279,7 +1327,8 @@
"optional": true,
"os": [
"win32"
]
],
"peer": true
},
"node_modules/@rollup/rollup-win32-ia32-msvc": {
"version": "4.62.4",
@@ -1293,7 +1342,8 @@
"optional": true,
"os": [
"win32"
]
],
"peer": true
},
"node_modules/@rollup/rollup-win32-x64-gnu": {
"version": "4.62.4",
@@ -1307,7 +1357,8 @@
"optional": true,
"os": [
"win32"
]
],
"peer": true
},
"node_modules/@rollup/rollup-win32-x64-msvc": {
"version": "4.62.4",
@@ -1321,14 +1372,8 @@
"optional": true,
"os": [
"win32"
]
},
"node_modules/@standard-schema/spec": {
"version": "1.1.0",
"resolved": "https://registry.npmjs.org/@standard-schema/spec/-/spec-1.1.0.tgz",
"integrity": "sha512-l2aFy5jALhniG5HgqrD6jXLi/rUWrKvqN/qJx6yoJsgKhblVd+iqqU4RCXavm/jPityDo5TCvKMnpjKnOriy0w==",
"dev": true,
"license": "MIT"
],
"peer": true
},
"node_modules/@sveltejs/acorn-typescript": {
"version": "1.0.11",
@@ -1411,24 +1456,6 @@
"vite": "^6.3.0 || ^7.0.0"
}
},
"node_modules/@types/chai": {
"version": "5.2.3",
"resolved": "https://registry.npmjs.org/@types/chai/-/chai-5.2.3.tgz",
"integrity": "sha512-Mw558oeA9fFbv65/y4mHtXDs9bPnFMZAL/jxdPFUpOHHIXX91mcgEHbS5Lahr+pwZFR8A7GQleRWeI6cGFC2UA==",
"dev": true,
"license": "MIT",
"dependencies": {
"@types/deep-eql": "*",
"assertion-error": "^2.0.1"
}
},
"node_modules/@types/deep-eql": {
"version": "4.0.2",
"resolved": "https://registry.npmjs.org/@types/deep-eql/-/deep-eql-4.0.2.tgz",
"integrity": "sha512-c9h9dVVMigMPc4bwTvC5dxqtqJZwQPePsWjPlpSOnojbor6pGqdk541lfA7AqFQr5pB1BRdq0juY9db81BwyFw==",
"dev": true,
"license": "MIT"
},
"node_modules/@types/estree": {
"version": "1.0.9",
"resolved": "https://registry.npmjs.org/@types/estree/-/estree-1.0.9.tgz",
@@ -1441,119 +1468,6 @@
"integrity": "sha512-ScaPdn1dQczgbl0QFTeTOmVHFULt394XJgOQNoyVhZ6r2vLnMLJfBPd53SB52T/3G36VI1/g2MZaX0cwDuXsfw==",
"license": "MIT"
},
"node_modules/@vitest/expect": {
"version": "4.1.11",
"resolved": "https://registry.npmjs.org/@vitest/expect/-/expect-4.1.11.tgz",
"integrity": "sha512-VX2x5vNJXET47KAFzwERI+KRMtTTCSWTfSMKsW7JsUsXV4psq++e3DvZpuTDOpHcxytiDs6p2nhVb2tVDiiUYw==",
"dev": true,
"license": "MIT",
"dependencies": {
"@standard-schema/spec": "^1.1.0",
"@types/chai": "^5.2.2",
"@vitest/spy": "4.1.11",
"@vitest/utils": "4.1.11",
"chai": "^6.2.2",
"tinyrainbow": "^3.1.0"
},
"funding": {
"url": "https://opencollective.com/vitest"
}
},
"node_modules/@vitest/mocker": {
"version": "4.1.11",
"resolved": "https://registry.npmjs.org/@vitest/mocker/-/mocker-4.1.11.tgz",
"integrity": "sha512-2XJVD55d1o5AZous5CCGKS74g/riOj9odEt2bQpCVZeblHyHdnMeFl4jl0XjU21stf4mbjUkew2eXQZt65g5CQ==",
"dev": true,
"license": "MIT",
"dependencies": {
"@vitest/spy": "4.1.11",
"estree-walker": "^3.0.3",
"magic-string": "^0.30.21"
},
"funding": {
"url": "https://opencollective.com/vitest"
},
"peerDependencies": {
"msw": "^2.4.9",
"vite": "^6.0.0 || ^7.0.0 || ^8.0.0"
},
"peerDependenciesMeta": {
"msw": {
"optional": true
},
"vite": {
"optional": true
}
}
},
"node_modules/@vitest/pretty-format": {
"version": "4.1.11",
"resolved": "https://registry.npmjs.org/@vitest/pretty-format/-/pretty-format-4.1.11.tgz",
"integrity": "sha512-yiZzPbGTS9Sr/JpFl8zHrcIkAofNbFV6k21vIgQN/cY/oxZeXhJv5sc/MBJ5jFKWmWs+oJHw0UXLZjmf931+Vw==",
"dev": true,
"license": "MIT",
"dependencies": {
"tinyrainbow": "^3.1.0"
},
"funding": {
"url": "https://opencollective.com/vitest"
}
},
"node_modules/@vitest/runner": {
"version": "4.1.11",
"resolved": "https://registry.npmjs.org/@vitest/runner/-/runner-4.1.11.tgz",
"integrity": "sha512-LztvUgdwMNJMIkj3hQnnxiC2Xy1zNxq928W/xhjCLaNCzqTZOudjwbQf6v9IntZGPw132i2Lq2rgTRZHD3JHNw==",
"dev": true,
"license": "MIT",
"dependencies": {
"@vitest/utils": "4.1.11",
"pathe": "^2.0.3"
},
"funding": {
"url": "https://opencollective.com/vitest"
}
},
"node_modules/@vitest/snapshot": {
"version": "4.1.11",
"resolved": "https://registry.npmjs.org/@vitest/snapshot/-/snapshot-4.1.11.tgz",
"integrity": "sha512-pN7ikn1ON7h8ee4gIAp4AzyK+zBtJPzVbqOgu5LCEh4VaJVbPQcgYQYJIMGQPXVeJJq1fnfazis7a5pFNPahog==",
"dev": true,
"license": "MIT",
"dependencies": {
"@vitest/pretty-format": "4.1.11",
"@vitest/utils": "4.1.11",
"magic-string": "^0.30.21",
"pathe": "^2.0.3"
},
"funding": {
"url": "https://opencollective.com/vitest"
}
},
"node_modules/@vitest/spy": {
"version": "4.1.11",
"resolved": "https://registry.npmjs.org/@vitest/spy/-/spy-4.1.11.tgz",
"integrity": "sha512-apNa/prQy2qCeywhnixOHPRCgGNhvg7T4Dapfl1GahLp/R+uhBm5cPyFoNVyqsNd2h1nJxL6BqqdIjiABL60YA==",
"dev": true,
"license": "MIT",
"funding": {
"url": "https://opencollective.com/vitest"
}
},
"node_modules/@vitest/utils": {
"version": "4.1.11",
"resolved": "https://registry.npmjs.org/@vitest/utils/-/utils-4.1.11.tgz",
"integrity": "sha512-zTCVGpyFsGWBhllOyKlTw/vnr6D9qxsfSDyfbyZmTyjHw5N/VuvzHpHoQjm2ZJzn4RJgx5w4r7V0er69CmLgPQ==",
"dev": true,
"license": "MIT",
"dependencies": {
"@vitest/pretty-format": "4.1.11",
"convert-source-map": "^2.0.0",
"tinyrainbow": "^3.1.0"
},
"funding": {
"url": "https://opencollective.com/vitest"
}
},
"node_modules/acorn": {
"version": "8.18.0",
"resolved": "https://registry.npmjs.org/acorn/-/acorn-8.18.0.tgz",
@@ -1612,16 +1526,6 @@
"node": ">=8"
}
},
"node_modules/assertion-error": {
"version": "2.0.1",
"resolved": "https://registry.npmjs.org/assertion-error/-/assertion-error-2.0.1.tgz",
"integrity": "sha512-Izi8RQcffqCeNVgFigKli1ssklIbpHnCYc6AknXGYoB6grJqyeby7jv12JUQgmTAnIDnbck1uxksT4dzN3PWBA==",
"dev": true,
"license": "MIT",
"engines": {
"node": ">=12"
}
},
"node_modules/axobject-query": {
"version": "4.1.0",
"resolved": "https://registry.npmjs.org/axobject-query/-/axobject-query-4.1.0.tgz",
@@ -1657,16 +1561,6 @@
"node": ">=8"
}
},
"node_modules/chai": {
"version": "6.2.2",
"resolved": "https://registry.npmjs.org/chai/-/chai-6.2.2.tgz",
"integrity": "sha512-NUPRluOfOiTKBKvWPtSD4PhFvWCqOi0BGStNWs57X9js7XGTprSmFoz5F0tWhR4WPjNeR9jXqdC7/UpSJTnlRg==",
"dev": true,
"license": "MIT",
"engines": {
"node": ">=18"
}
},
"node_modules/chardet": {
"version": "2.2.0",
"resolved": "https://registry.npmjs.org/chardet/-/chardet-2.2.0.tgz",
@@ -1699,13 +1593,6 @@
"node": ">=6"
}
},
"node_modules/convert-source-map": {
"version": "2.0.0",
"resolved": "https://registry.npmjs.org/convert-source-map/-/convert-source-map-2.0.0.tgz",
"integrity": "sha512-Kvp459HrV2FEJ1CAsi1Ku+MY3kasH19TFykTz2xWmMeq6bk2NU3XXvfJ+Q61m0xktWwt+1HSYf3JZsTms3aRJg==",
"dev": true,
"license": "MIT"
},
"node_modules/cross-spawn": {
"version": "7.0.6",
"resolved": "https://registry.npmjs.org/cross-spawn/-/cross-spawn-7.0.6.tgz",
@@ -1781,13 +1668,6 @@
"node": ">=8.6"
}
},
"node_modules/es-module-lexer": {
"version": "2.3.2",
"resolved": "https://registry.npmjs.org/es-module-lexer/-/es-module-lexer-2.3.2.tgz",
"integrity": "sha512-poHGpORABojJJucnV9KbOavETW8lBVnphkW77ER5/BQ5Fz7oXSoCNek7IH3vR5nRjdsEz926ibFYX8KtLQmdyw==",
"dev": true,
"license": "MIT"
},
"node_modules/esbuild": {
"version": "0.28.1",
"resolved": "https://registry.npmjs.org/esbuild/-/esbuild-0.28.1.tgz",
@@ -1795,6 +1675,7 @@
"dev": true,
"hasInstallScript": true,
"license": "MIT",
"peer": true,
"bin": {
"esbuild": "bin/esbuild"
},
@@ -1867,26 +1748,6 @@
}
}
},
"node_modules/estree-walker": {
"version": "3.0.3",
"resolved": "https://registry.npmjs.org/estree-walker/-/estree-walker-3.0.3.tgz",
"integrity": "sha512-7RUKfXgSMMkzt6ZuXmqapOurLGPPfgj6l9uRZ7lRGolvk0y2yocc35LdcxKC5PQZdn2DMqioAQ2NoWcrTKmm6g==",
"dev": true,
"license": "MIT",
"dependencies": {
"@types/estree": "^1.0.0"
}
},
"node_modules/expect-type": {
"version": "1.4.0",
"resolved": "https://registry.npmjs.org/expect-type/-/expect-type-1.4.0.tgz",
"integrity": "sha512-KfYbmpRm0VbLjEvVa9yGwCi9GI34xvi7A/HXYWQO65CSD2u3MczUJSuwXKFIxlGsgBQizV9q5J9NHj4VG0n+pA==",
"dev": true,
"license": "Apache-2.0",
"engines": {
"node": ">=12.0.0"
}
},
"node_modules/extendable-error": {
"version": "0.1.7",
"resolved": "https://registry.npmjs.org/extendable-error/-/extendable-error-0.1.7.tgz",
@@ -1992,6 +1853,7 @@
"os": [
"darwin"
],
"peer": true,
"engines": {
"node": "^8.16.0 || ^10.6.0 || >=11.0.0"
}
@@ -2283,6 +2145,7 @@
}
],
"license": "MIT",
"peer": true,
"bin": {
"nanoid": "bin/nanoid.cjs"
},
@@ -2413,13 +2276,6 @@
"node": ">=8"
}
},
"node_modules/pathe": {
"version": "2.0.3",
"resolved": "https://registry.npmjs.org/pathe/-/pathe-2.0.3.tgz",
"integrity": "sha512-WUjGcAqP1gQacoQe+OBJsFA7Ld4DyXuUIjZ5cc75cLHvJ7dtNsTugphxIADwspS+AraAUePCKrSVtPLFj/F88w==",
"dev": true,
"license": "MIT"
},
"node_modules/pg": {
"version": "8.22.0",
"resolved": "https://registry.npmjs.org/pg/-/pg-8.22.0.tgz",
@@ -2522,6 +2378,7 @@
"integrity": "sha512-RvwwcruNjI1ncT5xRakeyS9Lf8lcItv34KD+aif+VH9kduAyfYBipGh12274xtenIPZ119/R9BdTBa8gAwSh0A==",
"dev": true,
"license": "MIT",
"peer": true,
"engines": {
"node": ">=12"
},
@@ -2559,6 +2416,7 @@
}
],
"license": "MIT",
"peer": true,
"dependencies": {
"nanoid": "^3.3.16",
"picocolors": "^1.1.1",
@@ -2742,6 +2600,7 @@
"integrity": "sha512-RXOqwaPsBGjMNMa4sQjDjHieHEZDFoj/Rdr46l2MU5DfEs16wHJPC2RPTPHWhNl+M3aI472LLqFkFKut4SblOg==",
"dev": true,
"license": "MIT",
"peer": true,
"dependencies": {
"@types/estree": "1.0.9"
},
@@ -2869,13 +2728,6 @@
"node": ">=8"
}
},
"node_modules/siginfo": {
"version": "2.0.0",
"resolved": "https://registry.npmjs.org/siginfo/-/siginfo-2.0.0.tgz",
"integrity": "sha512-ybx0WO1/8bSBLEWXZvEd7gMW3Sn3JFlW3TvX1nREbDLRNQNaeNN8WK0meBwPdAaOI7TtRRRJn/Es1zhrrCHu7g==",
"dev": true,
"license": "ISC"
},
"node_modules/signal-exit": {
"version": "4.1.0",
"resolved": "https://registry.npmjs.org/signal-exit/-/signal-exit-4.1.0.tgz",
@@ -2905,6 +2757,7 @@
"integrity": "sha512-UXWMKhLOwVKb728IUtQPXxfYU+usdybtUrK/8uGE8CQMvrhOpwvzDBwj0QhSL7MQc7vIsISBG8VQ8+IDQxpfQA==",
"dev": true,
"license": "BSD-3-Clause",
"peer": true,
"engines": {
"node": ">=0.10.0"
}
@@ -2936,20 +2789,6 @@
"dev": true,
"license": "BSD-3-Clause"
},
"node_modules/stackback": {
"version": "0.0.2",
"resolved": "https://registry.npmjs.org/stackback/-/stackback-0.0.2.tgz",
"integrity": "sha512-1XMJE5fQo1jGH6Y/7ebnwPOBEkIEnT4QF32d5R1+VXdXveM0IBMJt8zfaxX1P3QhVwrYe+576+jkANtSS2mBbw==",
"dev": true,
"license": "MIT"
},
"node_modules/std-env": {
"version": "4.2.0",
"resolved": "https://registry.npmjs.org/std-env/-/std-env-4.2.0.tgz",
"integrity": "sha512-oCUKSupKTHX53EyjDtuZQ64pjLJ6yYCtpmEw0goYxtjG9KpbRe8KAsl2tBUGU9DyMcJ0RwJ8GqJAFzMXcXW1Rw==",
"dev": true,
"license": "MIT"
},
"node_modules/strip-ansi": {
"version": "6.0.1",
"resolved": "https://registry.npmjs.org/strip-ansi/-/strip-ansi-6.0.1.tgz",
@@ -3083,29 +2922,13 @@
"url": "https://github.com/sponsors/sindresorhus"
}
},
"node_modules/tinybench": {
"version": "2.9.0",
"resolved": "https://registry.npmjs.org/tinybench/-/tinybench-2.9.0.tgz",
"integrity": "sha512-0+DUvqWMValLmha6lr4kD8iAMK1HzV0/aKnCtWb9v9641TnP/MFb7Pc2bxoxQjTXAErryXVgUOfv2YqNllqGeg==",
"dev": true,
"license": "MIT"
},
"node_modules/tinyexec": {
"version": "1.3.0",
"resolved": "https://registry.npmjs.org/tinyexec/-/tinyexec-1.3.0.tgz",
"integrity": "sha512-QKAl9m8gWWGHV8jZcPeym6j+XULi6tOf1mT83WYJ4Lk2ytW/uwAWkrP0uFsdoYMdueVJ0qs26wZ+23xeB4ibNQ==",
"dev": true,
"license": "MIT",
"engines": {
"node": ">=18"
}
},
"node_modules/tinyglobby": {
"version": "0.2.17",
"resolved": "https://registry.npmjs.org/tinyglobby/-/tinyglobby-0.2.17.tgz",
"integrity": "sha512-wXR/dYpcqKmfWpEdZjiKJOwCNFndD0DMnrW/cYjVGttEkBfVgcLFHoNrlj47mjOVic9yyNu65alsgF4NQyTa2g==",
"dev": true,
"license": "MIT",
"peer": true,
"dependencies": {
"fdir": "^6.5.0",
"picomatch": "^4.0.4"
@@ -3117,16 +2940,6 @@
"url": "https://github.com/sponsors/SuperchupuDev"
}
},
"node_modules/tinyrainbow": {
"version": "3.1.1",
"resolved": "https://registry.npmjs.org/tinyrainbow/-/tinyrainbow-3.1.1.tgz",
"integrity": "sha512-yau8yJdTt989Mm0Bd/236QnzEiPf2xLLTqUZRUJOo/3CB078LSwzei343DgtJVmfJKJE3TMINY1u42SQsP6mXw==",
"dev": true,
"license": "MIT",
"engines": {
"node": ">=14.0.0"
}
},
"node_modules/to-regex-range": {
"version": "5.0.1",
"resolved": "https://registry.npmjs.org/to-regex-range/-/to-regex-range-5.0.1.tgz",
@@ -3170,6 +2983,7 @@
"integrity": "sha512-4XP60spRGjSZFf1qYH+dJIkK2znL3zQfl9KkOV9MkkRR/3Dls0dxaBsQPTloEc5BLXWPL9vsOxopxyKoMmDueg==",
"dev": true,
"license": "MIT",
"peer": true,
"dependencies": {
"esbuild": "^0.27.0 || ^0.28.0",
"fdir": "^6.5.0",
@@ -3259,96 +3073,6 @@
}
}
},
"node_modules/vitest": {
"version": "4.1.11",
"resolved": "https://registry.npmjs.org/vitest/-/vitest-4.1.11.tgz",
"integrity": "sha512-fhACrNXUidIbGSBr5FlbuBkO7VWC1ZyLl0DO4CU2DrQoAPxX84Ysxs+HeGQpii5lZWV1Q4gBZTTu49mF+A6Edw==",
"dev": true,
"license": "MIT",
"dependencies": {
"@vitest/expect": "4.1.11",
"@vitest/mocker": "4.1.11",
"@vitest/pretty-format": "4.1.11",
"@vitest/runner": "4.1.11",
"@vitest/snapshot": "4.1.11",
"@vitest/spy": "4.1.11",
"@vitest/utils": "4.1.11",
"es-module-lexer": "^2.0.0",
"expect-type": "^1.3.0",
"magic-string": "^0.30.21",
"obug": "^2.1.1",
"pathe": "^2.0.3",
"picomatch": "^4.0.3",
"std-env": "^4.0.0-rc.1",
"tinybench": "^2.9.0",
"tinyexec": "^1.0.2",
"tinyglobby": "^0.2.15",
"tinyrainbow": "^3.1.0",
"vite": "^6.0.0 || ^7.0.0 || ^8.0.0",
"why-is-node-running": "^2.3.0"
},
"bin": {
"vitest": "vitest.mjs"
},
"engines": {
"node": "^20.0.0 || ^22.0.0 || >=24.0.0"
},
"funding": {
"url": "https://opencollective.com/vitest"
},
"peerDependencies": {
"@edge-runtime/vm": "*",
"@opentelemetry/api": "^1.9.0",
"@types/node": "^20.0.0 || ^22.0.0 || >=24.0.0",
"@vitest/browser-playwright": "4.1.11",
"@vitest/browser-preview": "4.1.11",
"@vitest/browser-webdriverio": "4.1.11",
"@vitest/coverage-istanbul": "4.1.11",
"@vitest/coverage-v8": "4.1.11",
"@vitest/ui": "4.1.11",
"happy-dom": "*",
"jsdom": "*",
"vite": "^6.0.0 || ^7.0.0 || ^8.0.0"
},
"peerDependenciesMeta": {
"@edge-runtime/vm": {
"optional": true
},
"@opentelemetry/api": {
"optional": true
},
"@types/node": {
"optional": true
},
"@vitest/browser-playwright": {
"optional": true
},
"@vitest/browser-preview": {
"optional": true
},
"@vitest/browser-webdriverio": {
"optional": true
},
"@vitest/coverage-istanbul": {
"optional": true
},
"@vitest/coverage-v8": {
"optional": true
},
"@vitest/ui": {
"optional": true
},
"happy-dom": {
"optional": true
},
"jsdom": {
"optional": true
},
"vite": {
"optional": false
}
}
},
"node_modules/which": {
"version": "2.0.2",
"resolved": "https://registry.npmjs.org/which/-/which-2.0.2.tgz",
@@ -3365,23 +3089,6 @@
"node": ">= 8"
}
},
"node_modules/why-is-node-running": {
"version": "2.3.0",
"resolved": "https://registry.npmjs.org/why-is-node-running/-/why-is-node-running-2.3.0.tgz",
"integrity": "sha512-hUrmaWBdVDcxvYqnyh09zunKzROWjbZTiNy8dBEjkS7ehEDQibXJ7XvlmtbwuTclUiIyN+CyXQD4Vmko8fNm8w==",
"dev": true,
"license": "MIT",
"dependencies": {
"siginfo": "^2.0.0",
"stackback": "0.0.2"
},
"bin": {
"why-is-node-running": "cli.js"
},
"engines": {
"node": ">=8"
}
},
"node_modules/xtend": {
"version": "4.0.2",
"resolved": "https://registry.npmjs.org/xtend/-/xtend-4.0.2.tgz",
@@ -3402,12 +3109,9 @@
"version": "0.1.1",
"license": "MIT"
},
"packages/media-shared-assets": {
"name": "@gabriel20xx/media-shared-assets",
"version": "2.0.0",
"devDependencies": {
"vitest": "^4.0.18"
}
"packages/legacy-assets": {
"name": "@gabriel20xx/legacy-assets",
"version": "3.0.0"
},
"packages/node-backend": {
"name": "@gabriel20xx/node-backend",
+16
View File
@@ -0,0 +1,16 @@
# @gabriel20xx/legacy-assets
This package now contains exactly one file: `public/css/index.css`, a static (pre-Tailwind-v4)
theme stylesheet. Its only remaining consumer is `Original/MediaDesktop`'s Electron renderer,
which still uses the old `--color-*` utility-class theme rather than the current `--sc-*`
design-token system in `packages/design-tokens`. It's a `file:` dependency there
(`scripts/copy-assets.mjs` copies `index.css` into `MediaDesktop/public/` at build time) - do not
delete this package without first migrating MediaDesktop off the old stylesheet.
Everything else that used to live here (the pre-SvelteKit `public/js/*` auth/layout/media
utilities, an orphaned `MediaDesktop/assets/icon.png` copy, and the broken monorepo-era
`build:theme` script) was removed: nothing else in the workspace referenced any of it.
Originally `MediaCollection/MediaShared`, moved here to centralize shared components. Both the
`MediaCollection` and `MediaShared` umbrella names are retired - everything here is just part of
`shared` now, workspace-wide.
+13
View File
@@ -0,0 +1,13 @@
{
"name": "@gabriel20xx/legacy-assets",
"version": "3.0.0",
"private": true,
"description": "Legacy pre-SvelteKit theme CSS, kept only for MediaDesktop's Electron renderer (file: dependency)",
"scripts": {
"lint:css": "stylelint \"public/**/*.css\""
},
"exports": {
"./index.css": "./public/css/index.css"
},
"files": ["public/**"]
}
@@ -1,5 +1,5 @@
/*
index.css — Static CSS for MediaCollection
index.css — Static legacy theme CSS (kept only for MediaDesktop's Electron renderer)
Previously generated by Tailwind CSS; now a self-contained static file.
Do not regenerate with Tailwind. Edit directly to add or update styles.
*/
@@ -1,2 +0,0 @@
# Backend configuration lives in ../backend/.env.example.
# This package contains browser assets only; it does not run a server.
Binary file not shown.

Before

Width:  |  Height:  |  Size: 1.2 KiB

-10
View File
@@ -1,10 +0,0 @@
# @gabriel20xx/media-shared-assets
This package contains browser assets retained for MediaCollection-family clients that still
consume the shared theme and small browser utilities (`clientLogger.js`, `index.css`). It is not
a server package - the former JavaScript server foundation was replaced by the shared Go
implementation, now `media-backend/` (this repo) and `media-webui/` (this repo). Backend changes
belong there: run `go test ./...` from `media-backend/`; do not add server middleware or database
code to this package.
Originally `MediaCollection/MediaShared`, moved here to centralize shared components.
-19
View File
@@ -1,19 +0,0 @@
{
"name": "@gabriel20xx/media-shared-assets",
"version": "2.0.0",
"private": true,
"description": "Shared browser assets retained for MediaCollection clients",
"scripts": {
"build:theme": "node scripts/build-theme-css.mjs",
"lint:css": "stylelint \"public/**/*.css\"",
"test": "echo \"no tests in this package yet\" && exit 0"
},
"exports": {
"./clientLogger.js": "./public/js/utils/clientLogger.js",
"./index.css": "./public/css/index.css"
},
"files": ["public/**"],
"devDependencies": {
"vitest": "^4.0.18"
}
}
@@ -1,4 +0,0 @@
<svg xmlns="http://www.w3.org/2000/svg" width="24" height="24" viewBox="0 0 24 24" fill="none" stroke="#5b8cff" stroke-width="2" stroke-linecap="round" stroke-linejoin="round" role="img" aria-labelledby="favicon-title">
<title id="favicon-title">MediaViewer</title>
<path d="M5 5a2 2 0 0 1 3.008-1.728l11.997 6.998a2 2 0 0 1 .003 3.458l-12 7A2 2 0 0 1 5 19z" />
</svg>

Before

Width:  |  Height:  |  Size: 373 B

@@ -1,5 +0,0 @@
<svg width="24" height="24" viewBox="0 0 24 24" fill="none" xmlns="http://www.w3.org/2000/svg">
<rect width="24" height="24" fill="#E5E7EB"/>
<path d="M12 11C13.6569 11 15 9.65685 15 8C15 6.34315 13.6569 5 12 5C10.3431 5 9 6.34315 9 8C9 9.65685 10.3431 11 12 11Z" fill="#9CA3AF"/>
<path d="M6 21V19C6 16.7909 7.79086 15 10 15H14C16.2091 15 18 16.7909 18 19V21" fill="#9CA3AF"/>
</svg>

Before

Width:  |  Height:  |  Size: 388 B

@@ -1,17 +0,0 @@
(async () => {
try {
const response = await fetch('/admin/users');
const payload = await response.json();
const list = document.getElementById('usersList');
if (!list) return;
list.textContent = '';
(payload.users || []).forEach(user => {
const row = document.createElement('div');
row.className = 'u-row';
row.textContent = `${user.id} · ${user.email} · ${user.created_at}`;
list.appendChild(row);
});
} catch (error) {
console.error(error);
}
})();
@@ -1,47 +0,0 @@
(() => {
if (window.NCAuthForm) return;
function bindJsonSubmit(options) {
const { endpoint, formId, resultId, buildPayload, onSuccess, onError } = options || {};
if (!endpoint || !formId || !resultId || typeof buildPayload !== 'function') {
return false;
}
const form = document.getElementById(formId);
const result = document.getElementById(resultId);
if (!form || !result) return false;
form.addEventListener('submit', async event => {
event.preventDefault();
try {
const response = await fetch(endpoint, {
method: 'POST',
headers: { 'Content-Type': 'application/json' },
body: JSON.stringify(buildPayload()),
});
const payload = await response.json();
result.textContent = payload.message || JSON.stringify(payload);
if (response.ok && typeof onSuccess === 'function') {
onSuccess(payload, response);
} else if (!response.ok && typeof onError === 'function') {
onError(payload, response);
}
} catch (error) {
result.textContent = 'Request failed. Please try again.';
if (typeof onError === 'function') {
onError({ error: error && error.message ? error.message : String(error) }, null);
}
}
});
return true;
}
window.NCAuthForm = {
bindJsonSubmit,
};
})();
@@ -1,13 +0,0 @@
(() => {
const opener = document.getElementById('authLoginOpenBtn');
if (!opener) return;
const buttons = document.querySelectorAll('[data-auth-guard-login]');
buttons.forEach(button => {
if (button.dataset.authGuardWired === '1') return;
button.dataset.authGuardWired = '1';
button.addEventListener('click', event => {
event.preventDefault();
opener.click();
});
});
})();
@@ -1,646 +0,0 @@
// Shared Auth Modals (login + signup)
/* global toast */
(function () {
// Button references - may not exist yet if using dynamic component loading
let loginOpenBtn = document.getElementById('authLoginOpenBtn');
let signupOpenBtn = document.getElementById('authSignupOpenBtn');
let logoutBtn = document.getElementById('authLogoutBtn');
let profileMenu = document.getElementById('authProfileMenu');
// Overlay references - may not exist yet if using dynamic component loading
let loginOverlay = document.getElementById('authLoginOverlay');
let signupOverlay = document.getElementById('authSignupOverlay');
let overlays = [loginOverlay, signupOverlay].filter(Boolean);
// eslint-disable-next-line no-unused-vars
let _loginPanel = loginOverlay ? loginOverlay.querySelector('#authLoginPanel') : null;
let signupPanel = signupOverlay ? signupOverlay.querySelector('#authSignupPanel') : null;
let submitBtns = document.querySelectorAll('[data-auth-submit]');
let pwInput = document.getElementById('signupPassword');
let pwMeter = document.getElementById('signupPwMeter');
let pwFeedback = document.getElementById('signupPwFeedback');
let pwConfirm = document.getElementById('signupConfirm');
let pwConfirmErr = document.getElementById('signupConfirmError');
let loginTotpRow = document.getElementById('loginTotpRow');
let loginTotpInput = document.getElementById('loginTotp');
let loginTotpHint = document.getElementById('loginTotpHint');
let isAdminApp = !!document.querySelector('[data-bottom-nav] a[href="/dashboard"]');
const STORAGE_KEY = 'authLoggedIn';
let authKnown = false;
let authLoggedIn = false;
let buttonListenersAttached = false;
let overlayListenersAttached = false;
// Optimistically initialize from localStorage to avoid button flicker on page load
// This will be confirmed/corrected by the /auth/me fetch below
try {
const storedAuth = localStorage.getItem(STORAGE_KEY);
if (storedAuth === '1') {
authKnown = true;
authLoggedIn = true;
}
} catch {
// LocalStorage might not be available in some contexts
}
// Function to refresh button references (for dynamic component loading)
function refreshButtonReferences() {
loginOpenBtn = document.getElementById('authLoginOpenBtn');
signupOpenBtn = document.getElementById('authSignupOpenBtn');
logoutBtn = document.getElementById('authLogoutBtn');
profileMenu = document.getElementById('authProfileMenu');
// Reset dropdown listener flag so toggle is re-attached to fresh DOM elements
buttonListenersAttached = false;
}
// Function to refresh overlay references (for dynamic component loading)
function refreshOverlayReferences() {
loginOverlay = document.getElementById('authLoginOverlay');
signupOverlay = document.getElementById('authSignupOverlay');
overlays = [loginOverlay, signupOverlay].filter(Boolean);
_loginPanel = loginOverlay ? loginOverlay.querySelector('#authLoginPanel') : null;
signupPanel = signupOverlay ? signupOverlay.querySelector('#authSignupPanel') : null;
submitBtns = document.querySelectorAll('[data-auth-submit]');
pwInput = document.getElementById('signupPassword');
pwMeter = document.getElementById('signupPwMeter');
pwFeedback = document.getElementById('signupPwFeedback');
pwConfirm = document.getElementById('signupConfirm');
pwConfirmErr = document.getElementById('signupConfirmError');
loginTotpRow = document.getElementById('loginTotpRow');
loginTotpInput = document.getElementById('loginTotp');
loginTotpHint = document.getElementById('loginTotpHint');
isAdminApp = !!document.querySelector('[data-bottom-nav] a[href="/dashboard"]');
// Reset listener flags when overlays are re-loaded
overlayListenersAttached = false;
}
function setHiddenClass(element, hidden) {
if (!element) return;
element.classList.toggle('hidden', !!hidden);
}
function setLoginTotpPrompt(visible, message = '') {
if (!loginTotpRow) return;
setHiddenClass(loginTotpRow, !visible);
if (loginTotpHint) {
loginTotpHint.textContent =
message || 'Two-factor authentication is enabled for this account.';
}
if (!visible && loginTotpInput) {
loginTotpInput.value = '';
}
}
function isLoggedIn() {
return authKnown && authLoggedIn;
}
function setLoggedIn(v) {
authKnown = true;
authLoggedIn = !!v;
if (v) {
localStorage.setItem(STORAGE_KEY, '1');
} else {
localStorage.removeItem(STORAGE_KEY);
}
updateHeaderButton();
}
// Toggle both the HTML hidden attribute (accessibility/semantics) and the
// Tailwind .hidden CSS class. Tailwind's preflight wraps [hidden] in
// :where() (zero specificity) so utility classes like .inline-flex override
// it. The .hidden utility class has normal specificity and wins correctly.
function setHidden(el, hide) {
if (!el) return;
el.hidden = !!hide;
el.classList.toggle('hidden', !!hide);
}
function updateHeaderButton() {
if (isLoggedIn()) {
setHidden(loginOpenBtn, true);
setHidden(signupOpenBtn, true);
setHidden(profileMenu, false);
} else {
setHidden(loginOpenBtn, false);
if (loginOpenBtn) {
loginOpenBtn.setAttribute('aria-haspopup', 'dialog');
loginOpenBtn.title = 'Log in';
}
// Keep signup button hidden - users can access signup via the "Sign up" link in the login modal
setHidden(signupOpenBtn, true);
setHidden(profileMenu, true);
// Ensure dropdown is closed when logging out
const dropdown = document.getElementById('authProfileDropdown');
const profileBtn = document.getElementById('authProfileBtn');
if (dropdown) {
dropdown.classList.add('hidden');
}
if (profileBtn) {
profileBtn.setAttribute('aria-expanded', 'false');
}
}
}
function isBootstrapLocked(overlay) {
return overlay && overlay.querySelector('[data-admin-bootstrap]') != null;
}
function anyOverlayOpen() {
return overlays.some(item => item && item.hidden === false);
}
function setNoScroll(enabled) {
document.documentElement.classList.toggle('overflow-hidden', !!enabled);
document.body.classList.toggle('overflow-hidden', !!enabled);
}
function openOverlay(overlay) {
if (!overlay) return;
overlays.forEach(item => {
if (item) setHidden(item, item !== overlay);
});
if (overlay === loginOverlay) setLoginTotpPrompt(false);
setHidden(overlay, false);
setNoScroll(true);
setTimeout(() => {
const el = overlay.querySelector('input');
if (el) el.focus();
}, 0);
}
function switchOverlay(fromOverlay, toOverlay) {
if (!fromOverlay || !toOverlay) return;
setHidden(fromOverlay, true);
setHidden(toOverlay, false);
if (toOverlay === loginOverlay) setLoginTotpPrompt(false);
// Keep scroll lock active during switch
setTimeout(() => {
const el = toOverlay.querySelector('input');
if (el) el.focus();
}, 0);
}
function closeOverlay(overlay) {
if (!overlay) return;
setHidden(overlay, true);
if (!anyOverlayOpen()) setNoScroll(false);
}
function closeAll() {
overlays.forEach(item => {
if (item) setHidden(item, true);
});
setNoScroll(false);
}
async function handleLogout() {
// Verify session still valid first (in case local flag drifted)
try {
const r = await fetch('/auth/me');
const j = await r.json().catch(() => ({}));
if (!r.ok || !j?.user) {
setLoggedIn(false);
// Always redirect to root; each app's root resolves to its main page (Admin -> /dashboard, Forge -> /generator)
window.location.replace('/');
return;
}
} catch {
/* ignore session probe failure */
}
try {
await fetch('/auth/logout', {
method: 'POST',
headers: { 'Content-Type': 'application/json' },
});
} catch {
/* ignore network */
}
setLoggedIn(false);
// Provide lightweight feedback then redirect to canonical root for ALL apps
if (window.toast && typeof toast?.info === 'function') {
toast.info('Logged out');
} else {
console.info('[LOGOUT] Logged out');
}
// Unified behavior: always navigate to root. Individual apps define their own root redirect target.
window.location.replace('/');
}
// Header login/signup buttons - wrapped in function to support dynamic loading
function attachButtonListeners() {
// Only attach once to prevent duplicate listeners
if (buttonListenersAttached) return;
if (loginOpenBtn) {
loginOpenBtn.addEventListener('click', () => {
openOverlay(loginOverlay);
});
}
if (signupOpenBtn) {
signupOpenBtn.addEventListener('click', () => {
openOverlay(signupOverlay);
});
}
if (logoutBtn) {
logoutBtn.addEventListener('click', handleLogout);
}
// Profile dropdown toggle
const profileBtn = document.getElementById('authProfileBtn');
const profileDropdown = document.getElementById('authProfileDropdown');
if (profileBtn && profileDropdown) {
profileBtn.addEventListener('click', e => {
e.stopPropagation();
const isOpen = !profileDropdown.classList.contains('hidden');
profileDropdown.classList.toggle('hidden', isOpen);
profileBtn.setAttribute('aria-expanded', String(!isOpen));
profileDropdown.querySelectorAll('[role="menuitem"]').forEach(el => {
el.tabIndex = isOpen ? -1 : 0;
});
});
// Close when clicking outside
document.addEventListener('click', () => {
if (!profileDropdown.classList.contains('hidden')) {
profileDropdown.classList.add('hidden');
profileBtn.setAttribute('aria-expanded', 'false');
profileDropdown.querySelectorAll('[role="menuitem"]').forEach(el => {
el.tabIndex = -1;
});
}
});
// Close on Escape
document.addEventListener('keydown', e => {
if (e.key === 'Escape' && !profileDropdown.classList.contains('hidden')) {
profileDropdown.classList.add('hidden');
profileBtn.setAttribute('aria-expanded', 'false');
profileDropdown.querySelectorAll('[role="menuitem"]').forEach(el => {
el.tabIndex = -1;
});
profileBtn.focus();
}
});
}
if (loginOpenBtn || signupOpenBtn || logoutBtn || profileMenu) {
buttonListenersAttached = true;
}
}
// Initial attachment (buttons may not exist yet if using component loader)
attachButtonListeners();
// Initial button visibility update (will be called again after components load or /auth/me completes)
updateHeaderButton();
// Function to attach overlay listeners (for dynamic component loading)
function attachOverlayListeners() {
// Only attach once to prevent duplicate listeners
if (overlayListenersAttached || overlays.length === 0) return;
// Close handlers
// Close logic disabled when bootstrap admin (modal element has data-admin-bootstrap).
// Additionally, if overlay has data-lock-close (set by MediaModerator), backdrop click will not close.
overlays.forEach(overlay => {
if (!overlay) return;
const closeBtn = overlay.querySelector('button[aria-label="Close"]');
if (closeBtn) {
closeBtn.addEventListener('click', () => {
closeOverlay(overlay);
});
}
overlay.addEventListener('click', e => {
const lockBackdrop = overlay.hasAttribute('data-lock-close');
if (e.target === overlay && !isBootstrapLocked(overlay) && !lockBackdrop)
closeOverlay(overlay);
});
});
// Escape key handler
const escapeHandler = e => {
if (e.key !== 'Escape') return;
overlays.forEach(overlay => {
if (!overlay || overlay.hidden) return;
const lockBackdrop = overlay.hasAttribute('data-lock-close');
if (!isBootstrapLocked(overlay) && !lockBackdrop) closeOverlay(overlay);
});
};
// Store handler reference to prevent duplicates
if (!window.__authModalEscapeHandler) {
window.__authModalEscapeHandler = escapeHandler;
window.addEventListener('keydown', escapeHandler);
}
// Prevent form submission and call backend
overlays.forEach(overlay => {
if (!overlay) return;
overlay.addEventListener('submit', e => e.preventDefault());
});
// Enter key submits the active overlay (but not when a non-submit button has focus,
// e.g. the switchToLogin / switchToSignup links — let the browser fire their click)
overlays.forEach(overlay => {
if (!overlay) return;
overlay.addEventListener('keydown', e => {
if (e.key === 'Enter' && !e.shiftKey && !e.ctrlKey && !e.altKey) {
const focused = document.activeElement;
if (
focused &&
focused.tagName === 'BUTTON' &&
!focused.hasAttribute('data-auth-submit')
) {
return; // let the focused button handle its own click
}
e.preventDefault();
const mode = overlay.getAttribute('data-auth-mode') || 'login';
handleSubmit(mode);
}
});
});
// Submit button handlers
submitBtns.forEach(btn => {
btn.addEventListener('click', async () => {
const mode = btn.getAttribute('data-mode');
await handleSubmit(mode);
});
});
// Password strength listeners
if (pwInput) {
pwInput.addEventListener('input', () => {
updatePwStrength();
updateSignupState();
});
}
if (pwConfirm) {
pwConfirm.addEventListener('input', updateSignupState);
}
updatePwStrength();
updateSignupState();
// Password visibility toggles
overlays.forEach(overlay => {
if (!overlay) return;
overlay.querySelectorAll('button[data-target]').forEach(btn => {
btn.addEventListener('click', () => {
const targetId = btn.getAttribute('data-target');
const input = targetId ? overlay.querySelector('#' + CSS.escape(targetId)) : null;
if (!input) return;
const isPw = input.getAttribute('type') === 'password';
input.setAttribute('type', isPw ? 'text' : 'password');
// Swap icon
const icon = btn.querySelector('i');
if (icon) {
icon.classList.toggle('fa-eye');
icon.classList.toggle('fa-eye-slash');
}
// Keep focus on input
input.focus();
});
});
});
// Switch between login and signup overlays
const switchToSignupBtn = document.getElementById('switchToSignup');
const switchToLoginBtn = document.getElementById('switchToLogin');
if (switchToSignupBtn && loginOverlay && signupOverlay) {
switchToSignupBtn.addEventListener('click', e => {
e.preventDefault();
switchOverlay(loginOverlay, signupOverlay);
});
}
if (switchToLoginBtn && loginOverlay && signupOverlay) {
switchToLoginBtn.addEventListener('click', e => {
e.preventDefault();
switchOverlay(signupOverlay, loginOverlay);
});
}
// Initialize overlays to hidden
overlays.forEach(overlay => {
if (!overlay) return;
setHidden(overlay, true);
overlay.classList.remove('active');
});
overlayListenersAttached = true;
}
// Initial overlay setup
attachOverlayListeners();
// Submission helper used by both buttons and Enter key (needs to be accessible before listeners)
async function handleSubmit(mode) {
try {
const isSignup = mode === 'signup' && signupPanel;
let payload;
if (isSignup) {
const email = document.getElementById('signupEmail')?.value || '';
const password = document.getElementById('signupPassword')?.value || '';
const confirm = document.getElementById('signupConfirm')?.value || '';
const username = document.getElementById('signupUsername')?.value || '';
if (password !== confirm) {
if (window.toast) {
toast.error('Passwords do not match');
} else {
alert('Passwords do not match');
}
return;
}
if (scorePassword(password) < 3) {
if (window.toast) {
toast.error('Password is too weak');
} else {
alert('Password is too weak');
}
return;
}
payload = { email, password, username };
} else {
payload = {
email: document.getElementById('loginEmail')?.value || '',
password: document.getElementById('loginPassword')?.value || '',
totpToken: (loginTotpInput?.value || '').trim(),
};
}
const res = await fetch(`/auth/${isSignup ? 'signup' : 'login'}`, {
method: 'POST',
headers: { 'Content-Type': 'application/json' },
body: JSON.stringify(payload),
});
const data = await res.json().catch(() => ({}));
if (!res.ok) {
if (!isSignup && data?.mfaRequired) {
setLoginTotpPrompt(true, data?.error || 'Authenticator code required');
if (loginTotpInput) loginTotpInput.focus();
}
throw new Error(data?.error || 'Request failed');
}
if (!isSignup) setLoginTotpPrompt(false);
setLoggedIn(true);
const activeOverlay = isSignup ? signupOverlay : loginOverlay;
if (!isBootstrapLocked(activeOverlay)) closeAll();
try {
window.dispatchEvent(
new CustomEvent('auth:login-success', { detail: { mode: isSignup ? 'signup' : 'login' } })
);
} catch {
/* ignore */
}
if (window.toast && typeof toast?.success === 'function') {
toast.success(
isSignup ? 'Account created. You are now logged in.' : 'Logged in successfully.'
);
}
// If inside admin app, always redirect to dashboard after login
if (isAdminApp) {
window.location.replace('/dashboard');
}
} catch (e) {
if (window.toast && typeof toast?.error === 'function') {
toast.error(e?.message || 'Login failed');
} else {
alert(e?.message || 'Login failed');
}
}
}
// (keydown submit handler is registered inside attachOverlayListeners above)
// Password strength evaluation
function scorePassword(p) {
if (!p) return 0;
let score = 0;
const length = p.length;
if (length >= 6) score += 1;
if (length >= 10) score += 1;
if (/[a-z]/.test(p) && /[A-Z]/.test(p)) score += 1;
if (/\d/.test(p)) score += 1;
if (/[^A-Za-z0-9]/.test(p)) score += 1;
if (length >= 14) score += 1;
return Math.min(score, 5); // 0-5
}
function describeScore(s) {
switch (s) {
case 0:
return 'Enter a password';
case 1:
return 'Very weak';
case 2:
return 'Weak';
case 3:
return 'Fair';
case 4:
return 'Good';
case 5:
return 'Strong';
default:
return '';
}
}
function updatePwStrength() {
if (!pwInput || !pwMeter || !pwFeedback) return;
const val = pwInput.value || '';
const s = scorePassword(val);
pwMeter.dataset.score = String(s);
pwFeedback.textContent = describeScore(s);
// Visual width & color via inline style (can be refined in CSS)
const bar = pwMeter.querySelector('span');
if (bar) {
const pct = (s / 5) * 100;
bar.style.width = pct + '%';
const colorClasses = [
'bg-red-500',
'bg-amber-500',
'bg-amber-400',
'bg-emerald-500',
'bg-emerald-500',
];
colorClasses.forEach(c => bar.classList.remove(c));
if (s >= 5) bar.classList.add('bg-emerald-500');
else if (s >= 4) bar.classList.add('bg-emerald-500');
else if (s >= 3) bar.classList.add('bg-amber-400');
else if (s >= 2) bar.classList.add('bg-amber-500');
else bar.classList.add('bg-red-500');
}
}
function updateSignupState() {
const btn = signupOverlay
? signupOverlay.querySelector('[data-auth-submit][data-mode="signup"]')
: null;
if (!btn) return;
const pw = pwInput ? pwInput.value || '' : '';
const cf = pwConfirm ? pwConfirm.value || '' : '';
const s = scorePassword(pw);
const okStrength = s >= 3; // Fair or better
const match = pw && cf && pw === cf;
if (pwConfirmErr) {
setHiddenClass(pwConfirmErr, !(cf && !match));
}
btn.disabled = !(okStrength && match);
}
// Initialize scroll lock state (uses overflow-hidden Tailwind class)
setNoScroll(false);
// Check authentication status
(async () => {
try {
const r = await fetch('/auth/me');
if (r.ok) {
const j = await r.json();
const isLoggedIn = !!(j && j.user);
setLoggedIn(isLoggedIn);
} else {
setLoggedIn(false);
}
} catch {
setLoggedIn(false);
}
// Admin bootstrap detection must run only in MediaModerator.
if (isAdminApp) {
try {
const r2 = await fetch('/auth/bootstrap/admin-needed');
if (r2.ok) {
const j2 = await r2.json().catch(() => ({}));
if (j2 && j2.adminNeeded) {
const modalEl = signupOverlay ? signupOverlay.querySelector('[role="document"]') : null;
if (modalEl) modalEl.removeAttribute('data-admin-bootstrap');
setHidden(loginOpenBtn, false);
setHidden(signupOpenBtn, false);
const note =
(signupOverlay &&
signupOverlay.querySelector('[data-auth-note], #authNote, .u-text-dim')) ||
document.querySelector('[data-auth-note], #authNote, .u-text-dim');
if (note) {
note.textContent =
'No admin account exists yet. Sign up to create the first admin account.';
}
} else {
const modalEl = signupOverlay ? signupOverlay.querySelector('[role="document"]') : null;
if (modalEl) modalEl.removeAttribute('data-admin-bootstrap');
const note =
(loginOverlay &&
loginOverlay.querySelector('[data-auth-note], #authNote, .u-text-dim')) ||
document.querySelector('[data-auth-note], #authNote, .u-text-dim');
if (note && !signupPanel) {
note.textContent = 'Sign up disabled for admin panel.';
}
}
}
} catch {
/* ignore */
}
}
})();
// Listen for dynamic component loading (when header is injected after initial page load)
document.addEventListener('nc:componentsLoaded', () => {
refreshButtonReferences();
refreshOverlayReferences();
attachButtonListeners();
attachOverlayListeners();
updateHeaderButton();
});
})();
@@ -1,15 +0,0 @@
(() => {
const openAuth = () => {
const mode =
document.body?.dataset?.authOpenMode ||
document.querySelector('[data-auth-open-mode]')?.getAttribute('data-auth-open-mode') ||
'login';
const button = document.getElementById(
mode === 'signup' ? 'authSignupOpenBtn' : 'authLoginOpenBtn'
);
if (button) button.click();
};
const forceButton = document.getElementById('forceAuthOpen');
if (forceButton) forceButton.addEventListener('click', openAuth);
})();
@@ -1,63 +0,0 @@
/**
* NCAuthRequired — standardized "login required" screen.
*
* Usage:
* NCAuthRequired.render(containerEl);
*
* The rendered prompt includes a "Log In" button that opens the shared auth
* modal. On successful login (auth:login-success event) the page reloads
* automatically so the protected content can be fetched.
*/
window.NCAuthRequired = (() => {
function escapeHtml(s) {
const d = document.createElement('div');
d.textContent = s;
return d.innerHTML;
}
/**
* Render a login-required prompt inside `container`.
* @param {HTMLElement} container — element whose innerHTML will be replaced.
*/
function render(container) {
if (!container) return;
const message = 'You need to log in to view this page.';
const icon = 'fas fa-lock';
// Reset container layout so the prompt always spans full width and centers.
container.classList.add('flex', 'justify-center');
container.innerHTML = [
'<div class="flex min-h-[60vh] w-full flex-col items-center justify-center gap-3 px-4 py-4 text-center" data-auth-required="1" role="region" aria-label="Authentication required">',
' <i class="' +
escapeHtml(icon) +
' text-4xl text-[var(--color-text-dim)]" aria-hidden="true"></i>',
' <p class="max-w-xs text-base text-[var(--color-text-dim)]">' +
escapeHtml(message) +
'</p>',
' <button type="button" data-auth-required-login class="inline-flex cursor-pointer items-center gap-2 rounded-full bg-blue-600 px-4 py-3 text-sm font-semibold text-white shadow-md hover:bg-blue-500 focus:outline-none focus:ring-2 focus:ring-blue-400 focus:ring-offset-2 focus:ring-offset-[var(--color-bg)]">',
' <i class="fas fa-right-to-bracket" aria-hidden="true"></i> Log In',
' </button>',
'</div>',
].join('\n');
// Wire the Log In button to open the shared auth modal
const btn = container.querySelector('[data-auth-required-login]');
if (btn) {
btn.addEventListener('click', () => {
const opener = document.getElementById('authLoginOpenBtn');
if (opener) opener.click();
});
}
// Auto-reload on successful login so the page can fetch protected data
window.addEventListener(
'auth:login-success',
() => {
window.location.reload();
},
{ once: true }
);
}
return { render };
})();
@@ -1,24 +0,0 @@
(() => {
const tokenInput = document.getElementById('token');
const passwordInput = document.getElementById('newPassword');
if (
!tokenInput ||
!passwordInput ||
!window.NCAuthForm ||
typeof window.NCAuthForm.bindJsonSubmit !== 'function'
) {
return;
}
window.NCAuthForm.bindJsonSubmit({
endpoint: '/auth/reset/perform',
formId: 'resetForm',
resultId: 'resetDone',
buildPayload() {
return {
token: tokenInput.value,
password: passwordInput.value,
};
},
});
})();
@@ -1,15 +0,0 @@
(() => {
const emailInput = document.getElementById('resetEmail');
if (!emailInput || !window.NCAuthForm || typeof window.NCAuthForm.bindJsonSubmit !== 'function') {
return;
}
window.NCAuthForm.bindJsonSubmit({
endpoint: '/auth/reset/request',
formId: 'resetReqForm',
resultId: 'resetResult',
buildPayload() {
return { email: emailInput.value };
},
});
})();
@@ -1,21 +0,0 @@
/**
* login-gate.js
* Client-side initialiser for the server-side login gate page
* (served by requireLoginIfConfigured middleware in MediaShared).
*
* Sources: /shared/js/ui/toast.js, /shared/js/auth/auth-modal.js,
* /shared/js/auth/auth-required.js must be loaded before this script.
*
* On successful login the page is reloaded so the browser re-enters the
* protected service with a valid session.
*/
document.addEventListener('DOMContentLoaded', function () {
const gate = document.getElementById('auth-gate');
if (gate && window.NCAuthRequired) {
window.NCAuthRequired.render(gate);
}
document.addEventListener('auth:login-success', function () {
window.location.reload();
});
});
@@ -1,485 +0,0 @@
const toast = globalThis.toast;
const profileEditState = {
editing: false,
snapshot: { username: '', email: '' },
};
function byId(id) {
return document.getElementById(id);
}
function setText(id, value) {
const element = byId(id);
if (element) element.textContent = value;
}
function setValue(id, value) {
const element = byId(id);
if (element) element.value = value;
}
function parseApiError(payload, fallback) {
return payload?.error || payload?.message || payload?.data?.error || fallback;
}
function setButtonBusy(id, busy) {
const button = byId(id);
if (!button) return;
button.disabled = !!busy;
}
function setMfaBadge(enabled) {
const badge = byId('mfaBadge');
if (!badge) return;
if (enabled) {
badge.className =
'inline-flex items-center rounded-full border border-emerald-500/40 bg-emerald-500/15 px-3 py-1 text-xs font-semibold text-emerald-300';
badge.textContent = 'MFA Enabled';
return;
}
badge.className =
'inline-flex items-center rounded-full border border-amber-500/40 bg-amber-500/10 px-3 py-1 text-xs font-semibold text-amber-300';
badge.textContent = 'MFA Disabled';
}
function resetTotpWizard() {
const wizard = byId('totpWizard');
if (wizard) wizard.hidden = true;
setValue('totpCode', '');
const manualLabel = byId('totpManualLabel');
if (manualLabel) manualLabel.hidden = true;
setText('totpManualKey', '');
}
function extractTotpSecret(otpauth) {
try {
const parsed = new URL(String(otpauth || ''));
return parsed.searchParams.get('secret') || '';
} catch {
return '';
}
}
function normalizeTotpCode(raw) {
return String(raw || '')
.replace(/\D+/g, '')
.slice(0, 6);
}
function showBackupCodes(codes) {
const panel = byId('backupCodesPanel');
const list = byId('backupCodesList');
if (!panel || !list || !Array.isArray(codes)) return;
list.innerHTML = '';
codes.forEach(code => {
const li = document.createElement('li');
li.textContent = code;
list.appendChild(li);
});
panel.hidden = false;
}
function hideBackupCodes() {
const panel = byId('backupCodesPanel');
if (panel) panel.hidden = true;
const list = byId('backupCodesList');
if (list) list.innerHTML = '';
}
function hideBackupCodesRegenerateForm() {
const form = byId('backupCodesRegenerateForm');
if (form) form.hidden = true;
}
async function loadBackupCodesStatus() {
const manage = byId('backupCodesManage');
if (!manage) return;
try {
const response = await fetch('/api/security/totp/backup-codes/status');
const payload = await response.json().catch(() => ({}));
if (!response.ok || !payload?.data?.mfaEnabled) {
manage.hidden = true;
return;
}
manage.hidden = false;
const remaining = Number(payload.data.remaining) || 0;
setText(
'backupCodesRemaining',
`Backup codes: ${remaining} of 10 remaining.` +
(remaining <= 2 ? ' Consider regenerating soon.' : '')
);
} catch {
manage.hidden = true;
}
}
function normalizeProfileEntryValue(value) {
return String(value || '').trim();
}
function readProfileEntryInputs() {
return {
username: normalizeProfileEntryValue(byId('usernameInput')?.value),
email: normalizeProfileEntryValue(byId('emailInput')?.value),
};
}
function applyProfileEntryInputs({ username = '', email = '' } = {}) {
setValue('usernameInput', username);
setValue('emailInput', email);
}
function profileEntryValuesEqual(a, b) {
return (
normalizeProfileEntryValue(a?.username) === normalizeProfileEntryValue(b?.username) &&
normalizeProfileEntryValue(a?.email) === normalizeProfileEntryValue(b?.email)
);
}
function setProfileEditMode(editing, { restore = false } = {}) {
const isEditing = Boolean(editing);
const form = byId('editProfileForm');
if (form) form.hidden = !isEditing;
if (!isEditing && restore) {
applyProfileEntryInputs(profileEditState.snapshot);
}
const editButton = byId('editProfileButton');
if (editButton) editButton.disabled = isEditing;
profileEditState.editing = isEditing;
}
async function fetchUserProfile({ silent = false } = {}) {
if (!byId('profile-container')) return;
try {
const response = await fetch('/api/profile');
const payload = await response.json().catch(() => ({}));
const user = payload?.data || payload?.profile || payload?.user || null;
if (!response.ok || !user) {
throw new Error(parseApiError(payload, 'Failed to load profile'));
}
const entries = {
username: normalizeProfileEntryValue(user.username || 'Anonymous'),
email: normalizeProfileEntryValue(user.email || 'Not set'),
};
setText('username', entries.username);
setText('email', entries.email);
const profilePicture = byId('profilePicture');
if (profilePicture) {
profilePicture.src =
user.avatar_url || user.profilePicture || '/shared/images/default-avatar.svg';
}
if (!profileEditState.editing) {
applyProfileEntryInputs(entries);
profileEditState.snapshot = entries;
}
const mfaEnabled = !!user.mfaEnabled;
setMfaBadge(mfaEnabled);
setText('mfaStatus', mfaEnabled ? 'TOTP is enabled on your account.' : 'TOTP is not enabled.');
const setup = byId('mfaSetup');
const disable = byId('mfaDisable');
if (setup) setup.hidden = mfaEnabled;
if (disable) disable.hidden = !mfaEnabled;
if (mfaEnabled) resetTotpWizard();
if (mfaEnabled) {
await loadBackupCodesStatus();
} else {
const manage = byId('backupCodesManage');
if (manage) manage.hidden = true;
hideBackupCodesRegenerateForm();
}
} catch (error) {
if (!silent) {
toast?.error?.(error?.message || 'Profile load error');
}
}
}
function openProfileEdit() {
if (profileEditState.editing) return;
profileEditState.snapshot = {
username: normalizeProfileEntryValue(
byId('usernameInput')?.value || byId('username')?.textContent || ''
),
email: normalizeProfileEntryValue(
byId('emailInput')?.value || byId('email')?.textContent || ''
),
};
applyProfileEntryInputs(profileEditState.snapshot);
setProfileEditMode(true);
byId('usernameInput')?.focus();
}
function closeProfileEdit({ restore = true } = {}) {
setProfileEditMode(false, { restore });
}
async function saveProfileChanges() {
const draft = readProfileEntryInputs();
if (profileEntryValuesEqual(draft, profileEditState.snapshot)) {
closeProfileEdit({ restore: false });
return;
}
setButtonBusy('profileSaveBtn', true);
setButtonBusy('profileCancelBtn', true);
try {
const response = await fetch('/api/profile', {
method: 'PUT',
headers: { 'Content-Type': 'application/json' },
body: JSON.stringify(draft),
});
const payload = await response.json().catch(() => ({}));
if (!response.ok) {
throw new Error(parseApiError(payload, 'Save failed'));
}
profileEditState.snapshot = draft;
toast?.success?.('Profile updated');
closeProfileEdit({ restore: false });
await fetchUserProfile({ silent: true });
} catch (error) {
toast?.error?.(error?.message || 'Save failed');
} finally {
setButtonBusy('profileSaveBtn', false);
setButtonBusy('profileCancelBtn', false);
const editButton = byId('editProfileButton');
if (editButton) editButton.disabled = profileEditState.editing;
}
}
async function changePassword() {
const newPassword = byId('newPw')?.value || '';
if (!newPassword) {
toast?.error?.('New password is required');
return;
}
setButtonBusy('btnChangePw', true);
try {
const response = await fetch('/api/profile/password', {
method: 'POST',
headers: { 'Content-Type': 'application/json' },
body: JSON.stringify({ newPassword }),
});
const payload = await response.json().catch(() => ({}));
if (!response.ok) {
throw new Error(parseApiError(payload, 'Change failed'));
}
toast?.success?.('Password updated');
setValue('newPw', '');
} catch (error) {
toast?.error?.(error?.message || 'Change failed');
} finally {
setButtonBusy('btnChangePw', false);
}
}
async function startTotpSetup() {
setButtonBusy('btnStartTotp', true);
try {
const response = await fetch('/api/security/totp/initiate');
const payload = await response.json().catch(() => ({}));
if (!response.ok || !(payload?.data?.qr || payload?.data?.otpauth)) {
throw new Error(parseApiError(payload, 'Failed to start TOTP'));
}
const wizard = byId('totpWizard');
const qrImage = byId('totpQr');
if (wizard) wizard.hidden = false;
if (qrImage && payload?.data?.qr) qrImage.src = payload.data.qr;
const secret = extractTotpSecret(payload?.data?.otpauth);
if (secret) {
setText('totpManualKey', secret);
const manualLabel = byId('totpManualLabel');
if (manualLabel) manualLabel.hidden = false;
}
byId('totpCode')?.focus();
} catch (error) {
toast?.error?.(error?.message || 'Failed to start TOTP');
} finally {
setButtonBusy('btnStartTotp', false);
}
}
async function verifyTotpSetup() {
const token = normalizeTotpCode(byId('totpCode')?.value || '');
if (token.length !== 6) {
toast?.error?.('Enter a valid 6-digit TOTP code');
return;
}
setButtonBusy('btnVerifyTotp', true);
try {
const response = await fetch('/api/security/totp/verify', {
method: 'POST',
headers: { 'Content-Type': 'application/json' },
body: JSON.stringify({ token }),
});
const payload = await response.json().catch(() => ({}));
if (!response.ok) {
throw new Error(parseApiError(payload, 'Invalid code'));
}
toast?.success?.('MFA enabled');
resetTotpWizard();
if (Array.isArray(payload?.data?.backupCodes)) {
showBackupCodes(payload.data.backupCodes);
}
await fetchUserProfile({ silent: true });
} catch (error) {
toast?.error?.(error?.message || 'Invalid code');
} finally {
setButtonBusy('btnVerifyTotp', false);
}
}
async function regenerateBackupCodes() {
setButtonBusy('btnConfirmRegenerateBackupCodes', true);
try {
const response = await fetch('/api/security/totp/backup-codes/regenerate', {
method: 'POST',
headers: { 'Content-Type': 'application/json' },
body: JSON.stringify({}),
});
const payload = await response.json().catch(() => ({}));
if (!response.ok) {
throw new Error(parseApiError(payload, 'Failed to regenerate backup codes'));
}
toast?.success?.('Backup codes regenerated');
hideBackupCodesRegenerateForm();
if (Array.isArray(payload?.data?.backupCodes)) {
showBackupCodes(payload.data.backupCodes);
}
await loadBackupCodesStatus();
} catch (error) {
toast?.error?.(error?.message || 'Failed to regenerate backup codes');
} finally {
setButtonBusy('btnConfirmRegenerateBackupCodes', false);
}
}
async function disableTotp() {
const token = normalizeTotpCode(window.prompt('Enter the current 6-digit authenticator code to disable MFA:') || '');
if (token.length !== 6) {
toast?.error?.('Enter a valid 6-digit TOTP code');
return;
}
setButtonBusy('btnDisableTotp', true);
try {
const response = await fetch('/api/security/totp/disable', {
method: 'POST',
headers: { 'Content-Type': 'application/json' },
body: JSON.stringify({ token }),
});
const payload = await response.json().catch(() => ({}));
if (!response.ok) {
throw new Error(parseApiError(payload, 'Disable failed'));
}
toast?.success?.('MFA disabled');
await fetchUserProfile({ silent: true });
} catch (error) {
toast?.error?.(error?.message || 'Disable failed');
} finally {
setButtonBusy('btnDisableTotp', false);
}
}
async function uploadAvatar() {
const file = byId('avatarFile')?.files?.[0];
if (!file) {
toast?.error?.('Choose an image');
return;
}
setButtonBusy('btnUploadAvatar', true);
try {
const formData = new FormData();
formData.append('avatar', file);
const response = await fetch('/api/profile/avatar', { method: 'POST', body: formData });
const payload = await response.json().catch(() => ({}));
if (!response.ok) {
throw new Error(parseApiError(payload, 'Upload failed'));
}
toast?.success?.('Avatar updated');
await fetchUserProfile({ silent: true });
} catch (error) {
toast?.error?.(error?.message || 'Upload failed');
} finally {
setButtonBusy('btnUploadAvatar', false);
}
}
function wireProfileEvents() {
byId('editProfileButton')?.addEventListener('click', openProfileEdit);
byId('editProfileForm')?.addEventListener('submit', event => {
event.preventDefault();
saveProfileChanges();
});
byId('profileCancelBtn')?.addEventListener('click', () => closeProfileEdit({ restore: true }));
byId('changePasswordForm')?.addEventListener('submit', event => {
event.preventDefault();
changePassword();
});
byId('btnStartTotp')?.addEventListener('click', startTotpSetup);
byId('btnVerifyTotp')?.addEventListener('click', verifyTotpSetup);
byId('mfaDisableForm')?.addEventListener('submit', event => {
event.preventDefault();
disableTotp();
});
byId('btnUploadAvatar')?.addEventListener('click', uploadAvatar);
byId('btnDismissBackupCodes')?.addEventListener('click', hideBackupCodes);
byId('btnCopyBackupCodes')?.addEventListener('click', async () => {
const codes = Array.from(byId('backupCodesList')?.children || []).map(li => li.textContent);
if (!codes.length) return;
try {
await navigator.clipboard.writeText(codes.join('\n'));
toast?.success?.('Backup codes copied');
} catch {
toast?.error?.('Could not copy — please copy manually');
}
});
byId('btnRegenerateBackupCodes')?.addEventListener('click', () => {
const form = byId('backupCodesRegenerateForm');
if (form) form.hidden = false;
});
byId('btnCancelRegenerateBackupCodes')?.addEventListener('click', hideBackupCodesRegenerateForm);
byId('backupCodesRegenerateForm')?.addEventListener('submit', event => {
event.preventDefault();
regenerateBackupCodes();
});
byId('totpCode')?.addEventListener('keydown', event => {
if (event.key === 'Enter') {
event.preventDefault();
verifyTotpSetup();
}
});
const profileImage = byId('profilePicture');
if (profileImage) {
profileImage.addEventListener(
'error',
() => {
const fallbackSrc = profileImage.getAttribute('data-fallback-src');
if (fallbackSrc && profileImage.src !== fallbackSrc) profileImage.src = fallbackSrc;
},
{ once: true }
);
}
}
document.addEventListener('DOMContentLoaded', () => {
if (!byId('profile-container')) return;
wireProfileEvents();
fetchUserProfile();
});
@@ -1,920 +0,0 @@
/**
* @file component-loader.js
* @description Loads shared EJS components (header, navbar) dynamically into static HTML pages
*
* Usage:
* await NCComponentLoader.load({
* siteTitle: 'MediaViewer',
* title: 'Home',
* headerCenterHTML: '<div>Custom header content</div>',
* navbarVariant: 'default',
* navbarItems: [{ label: 'Home', href: '/', icon: 'fas fa-home' }],
* navbarCurrentPath: window.location.pathname,
* });
*
* headerCenterHTML is rendered directly in the browser (never sent to the server as
* a query param) and inserted into the header's `[data-header-center-slot]` element.
* It must be a hardcoded string the caller owns — never interpolate user-controlled
* data into it, since it's set via innerHTML with no escaping.
*/
(function (window) {
'use strict';
const TOPBAR_SELECTOR = 'header[data-topbar="1"]';
const NCComponentLoader = {
/**
* Load shared header and navbar components
* @param {Object} options - Configuration for header/navbar rendering
* @param {string} options.siteTitle - Site/app title (e.g., 'MediaViewer')
* @param {string} options.title - Page title (e.g., 'Home')
* @param {string} [options.headerCenterHTML] - Hardcoded HTML the caller owns, inserted
* client-side into the header's center slot. Never derive this from user input.
* @param {boolean} [options.disableSignup] - Hide signup button
* @param {boolean} [options.enableSocketIO] - Load Socket.IO script
* @param {string} [options.appCssHref] - Additional app-specific CSS href
* @param {string} [options.extraScripts] - Additional scripts to load in footer
* @param {string} [options.navbarVariant] - Navbar variant identifier (e.g. 'default', 'admin')
* @param {Array} [options.navbarItems] - Array of { label, href, icon } nav items
* @param {string} [options.navbarCurrentPath] - Current path for active-link highlighting
* @param {string} [options.authPageToken] - Explicit token for /auth/me page-level requirement lookup
* @param {string} [options.navbarActive] - Explicit active item href (fallback)
* @returns {Promise<void>}
*/
async load(options = {}) {
const {
siteTitle = 'App',
title = '',
headerCenterHTML = '',
disableSignup = false,
enableSocketIO = false,
appCssHref = '',
// eslint-disable-next-line no-unused-vars
extraScripts: _extraScripts = '',
navbarVariant = '',
navbarItems = [],
navbarCurrentPath = '',
authPageToken = '',
// eslint-disable-next-line no-unused-vars
navbarActive: _navbarActive = '',
} = options;
try {
const resolvedNavbarCurrentPath = navbarCurrentPath || window.location.pathname;
const resolvedTitle = this._resolveTitleForLoad({
siteTitle,
title,
navbarItems,
navbarCurrentPath: resolvedNavbarCurrentPath,
});
this._navbarTitleContext = {
siteTitle,
navbarItems: Array.isArray(navbarItems) ? navbarItems : [],
};
this._bindNavbarTitleSync();
this._setDocumentTitle(siteTitle, resolvedTitle);
const resolvedAuthPageToken = this._resolveAuthPageToken(
authPageToken,
resolvedNavbarCurrentPath
);
const authState = await this._getAuthState(resolvedAuthPageToken);
window.__NC_AUTH_STATE = authState;
window.__NC_ACTIVE_PAGE_TOKEN =
authState.pageToken || this._normalizePageToken(resolvedAuthPageToken);
this._bindProtectedNavGuard();
const hideHeaderForAuth = this._isAuthRequiredWithoutUser(authState);
const hasNavbarConfig =
!!navbarVariant && Array.isArray(navbarItems) && navbarItems.length > 1;
const isDesktopViewport = this._isDesktopViewport();
const renderDesktopNavbar = hasNavbarConfig && isDesktopViewport && !hideHeaderForAuth;
// Build query string for header endpoint
const headerParams = new URLSearchParams({
siteTitle,
title: resolvedTitle,
disableSignup: disableSignup.toString(),
enableSocketIO: enableSocketIO.toString(),
appCssHref,
navbarVariant,
navbarItems: JSON.stringify(hasNavbarConfig ? navbarItems : []),
navbarCurrentPath: resolvedNavbarCurrentPath,
renderDesktopNavbar: renderDesktopNavbar.toString(),
});
// Fetch header
const headerResponse = await fetch(`/api/components/header?${headerParams}`);
if (!headerResponse.ok) {
throw new Error(`Failed to load header: ${headerResponse.status}`);
}
const headerHTML = await headerResponse.text();
// Inject header into placeholder
const headerPlaceholder = document.getElementById('header-placeholder');
if (headerPlaceholder) {
headerPlaceholder.innerHTML = headerHTML;
} else {
console.warn(
'[ComponentLoader] #header-placeholder not found; prepending header to body'
);
document.body.insertAdjacentHTML('afterbegin', headerHTML);
}
if (headerCenterHTML) {
const centerSlot = document.querySelector('[data-header-center-slot]');
if (centerSlot) centerSlot.innerHTML = headerCenterHTML;
}
if (hideHeaderForAuth) {
this._hideHeaderForAuthState();
}
// Re-initialize scripts that depend on dynamically loaded elements
// (auth-modal.js, theme-toggle.js, etc. should auto-initialize on DOMContentLoaded)
// Fetch and inject mobile navbar markup whenever nav config exists.
// CSS media queries handle visibility per viewport.
if (hasNavbarConfig) {
try {
const shouldRenderMobileNavbar = !hideHeaderForAuth;
if (!shouldRenderMobileNavbar) {
const existingNav = document.querySelector('nav[data-mobile-nav="1"]');
if (existingNav) existingNav.remove();
const navbarPlaceholder = document.getElementById('navbar-placeholder');
if (navbarPlaceholder) navbarPlaceholder.innerHTML = '';
} else {
const navbarParams = new URLSearchParams({
navbarVariant,
navbarItems: JSON.stringify(navbarItems),
navbarCurrentPath: resolvedNavbarCurrentPath,
});
const navbarResponse = await fetch(`/api/components/navbar?${navbarParams}`);
if (navbarResponse.ok) {
const navbarHTML = await navbarResponse.text();
const existingNav = document.querySelector('nav[data-mobile-nav="1"]');
if (existingNav) {
existingNav.remove();
}
const navbarPlaceholder = document.getElementById('navbar-placeholder');
const headerPlaceholder = document.getElementById('header-placeholder');
if (navbarPlaceholder) {
navbarPlaceholder.outerHTML = navbarHTML;
} else if (headerPlaceholder) {
headerPlaceholder.insertAdjacentHTML('beforeend', navbarHTML);
} else {
const topbar = document.querySelector('header[data-topbar="1"]');
if (topbar) {
topbar.insertAdjacentHTML('afterend', navbarHTML);
} else {
document.body.insertAdjacentHTML('beforeend', navbarHTML);
}
}
}
}
} catch (navErr) {
console.warn('[ComponentLoader] Failed to load navbar:', navErr);
}
} else {
const existingNav = document.querySelector('nav[data-mobile-nav="1"]');
if (existingNav) existingNav.remove();
const navbarPlaceholder = document.getElementById('navbar-placeholder');
if (navbarPlaceholder) navbarPlaceholder.innerHTML = '';
}
this._syncTopbarMetrics();
this._syncBottomNavMetrics();
this._syncScrollShell();
this._applyAutoTopbarGap();
this._bindScrollShellObserver();
this._triggerScriptInitialization();
} catch (error) {
console.error('[ComponentLoader] Failed to load components:', error);
// Fallback: show a basic error message
document.body.insertAdjacentHTML(
'afterbegin',
`
<div style="background: #c53030; color: white; padding: 1rem; text-align: center;">
Failed to load page components. Please refresh the page.
</div>
`
);
}
},
/**
* Trigger re-initialization of scripts that need dynamically loaded DOM elements
* @private
*/
_triggerScriptInitialization() {
// Dispatch custom event for scripts that need to re-initialize
const event = new CustomEvent('nc:componentsLoaded', {
bubbles: true,
cancelable: false,
});
document.dispatchEvent(event);
},
/**
* Keep topbar-related CSS variables in sync with rendered header height.
* This avoids overlap when the fixed header height changes due to responsive content.
* @private
*/
_syncTopbarMetrics() {
const topbar = document.querySelector(TOPBAR_SELECTOR);
if (topbar) {
const height = Math.ceil(topbar.getBoundingClientRect().height || 0);
if (height) {
const px = `${height}px`;
document.documentElement.style.setProperty('--bar-height', px);
document.documentElement.style.setProperty('--topbar-height', px);
}
}
if (!this._resizeSyncBound) {
this._resizeSyncBound = true;
window.addEventListener('resize', () => {
if (this._resizeRaf) {
window.cancelAnimationFrame(this._resizeRaf);
}
this._resizeRaf = window.requestAnimationFrame(() => {
this._syncTopbarMetrics();
this._syncBottomNavMetrics();
this._syncScrollShell();
this._applyAutoTopbarGap();
});
});
}
},
/**
* Resolve the currently visible fixed mobile navigation bar.
* @returns {HTMLElement | null}
* @private
*/
_getVisibleMobileNav() {
const nav = document.querySelector('nav[data-bottom-nav][data-mobile-nav="1"]');
if (!nav || nav.hidden || nav.classList.contains('hidden')) return null;
const style = window.getComputedStyle(nav);
if (style.display === 'none' || style.visibility === 'hidden') return null;
if (style.position !== 'fixed') return null;
return nav;
},
/**
* Keep bottom-nav height variable in sync with the currently visible fixed mobile nav.
* @private
*/
_syncBottomNavMetrics() {
const mobileNav = this._getVisibleMobileNav();
const navHeight = mobileNav ? Math.ceil(mobileNav.getBoundingClientRect().height || 0) : 0;
document.documentElement.style.setProperty(
'--bottom-nav-height',
`${Math.max(0, navHeight)}px`
);
},
/**
* Determine whether a candidate scroll host is currently visible.
* @param {HTMLElement | null} element
* @returns {boolean}
* @private
*/
_isElementScrollHostVisible(element) {
if (!element) return false;
let node = element;
while (node && node.nodeType === 1) {
if (node.hidden || node.classList.contains('hidden')) return false;
if (String(node.getAttribute('aria-hidden') || '').toLowerCase() === 'true') return false;
const style = window.getComputedStyle(node);
if (style.display === 'none' || style.visibility === 'hidden') return false;
node = node.parentElement;
}
return true;
},
/**
* Pick the primary page content scroll host.
* @returns {HTMLElement | null}
* @private
*/
_resolveScrollHost() {
const selectors = [
'main.fixed.left-0.right-0.overflow-y-auto',
'body > main',
'body > #main-content',
'body > .page-panel > main',
'body > .page-panel > #main-content',
];
for (const selector of selectors) {
const candidates = Array.from(document.querySelectorAll(selector));
const visibleCandidate = candidates.find(candidate =>
this._isElementScrollHostVisible(candidate)
);
if (visibleCandidate) return visibleCandidate;
}
for (const selector of selectors) {
const fallbackCandidate = document.querySelector(selector);
if (fallbackCandidate) return fallbackCandidate;
}
return null;
},
/**
* Parse a CSS length-like value into pixels with a safe fallback.
* @param {string} value
* @param {number} fallback
* @returns {number}
* @private
*/
_parsePixelValue(value, fallback = 0) {
const parsed = Number.parseFloat(String(value || '').trim());
return Number.isFinite(parsed) ? parsed : fallback;
},
/**
* Keep non-fixed scroll hosts constrained to the viewport so they can scroll internally.
* @param {HTMLElement | null} scrollHost
* @private
*/
_syncScrollHostHeight(scrollHost) {
if (!scrollHost || scrollHost.classList.contains('fixed')) return;
const rootStyle = window.getComputedStyle(document.documentElement);
const topbarHeight = this._parsePixelValue(rootStyle.getPropertyValue('--topbar-height'), 56);
const bottomNavHeight = this._parsePixelValue(
rootStyle.getPropertyValue('--bottom-nav-height'),
0
);
const viewportHeight = window.innerHeight || document.documentElement.clientHeight || 0;
const boundedHeight = Math.max(
0,
Math.round(viewportHeight - topbarHeight - bottomNavHeight)
);
if (boundedHeight > 0) {
scrollHost.style.height = `${boundedHeight}px`;
scrollHost.dataset.ncScrollHostHeightManaged = '1';
}
},
/**
* Keep non-fixed scroll host scrollbar at the viewport edge while preserving centered content gutters.
* @param {HTMLElement | null} scrollHost
* @private
*/
_syncScrollHostInlineGutters(scrollHost) {
if (!scrollHost || scrollHost.classList.contains('fixed')) {
this._clearManagedScrollHostInlineGutters(scrollHost);
return;
}
if (scrollHost.dataset.ncScrollHostInlineGutterManaged === '1') {
this._clearManagedScrollHostInlineGutters(scrollHost);
}
const style = window.getComputedStyle(scrollHost);
const viewportWidth = window.innerWidth || document.documentElement.clientWidth || 0;
const hostMaxWidth = this._parsePixelValue(style.maxWidth, 0);
const hostRectWidth = Math.round(scrollHost.getBoundingClientRect().width || 0);
const constrainedWidth = hostMaxWidth > 0 ? hostMaxWidth : hostRectWidth;
// Only widen hosts that are intentionally constrained and centered.
if (!(constrainedWidth > 0 && viewportWidth - constrainedWidth > 1)) return;
const basePaddingLeft = this._parsePixelValue(style.paddingLeft, 0);
const basePaddingRight = this._parsePixelValue(style.paddingRight, 0);
const sideGutter = Math.max(0, Math.round((viewportWidth - constrainedWidth) / 2));
scrollHost.dataset.ncPrevInlineMaxWidth = scrollHost.style.maxWidth || '';
scrollHost.dataset.ncPrevInlineMarginLeft = scrollHost.style.marginLeft || '';
scrollHost.dataset.ncPrevInlineMarginRight = scrollHost.style.marginRight || '';
scrollHost.dataset.ncPrevInlineWidth = scrollHost.style.width || '';
scrollHost.dataset.ncPrevInlinePaddingLeft = scrollHost.style.paddingLeft || '';
scrollHost.dataset.ncPrevInlinePaddingRight = scrollHost.style.paddingRight || '';
// Width:auto ensures left/right fixed offsets remain authoritative on the scroll host.
scrollHost.style.width = 'auto';
scrollHost.style.maxWidth = 'none';
scrollHost.style.marginLeft = '0';
scrollHost.style.marginRight = '0';
scrollHost.style.paddingLeft = `${basePaddingLeft + sideGutter}px`;
scrollHost.style.paddingRight = `${basePaddingRight + sideGutter}px`;
scrollHost.dataset.ncScrollHostInlineGutterManaged = '1';
},
/**
* Remove inline gutter overrides used to keep the scrollbar at viewport edge.
* @param {HTMLElement | null} scrollHost
* @private
*/
_clearManagedScrollHostInlineGutters(scrollHost) {
if (!scrollHost || scrollHost.dataset.ncScrollHostInlineGutterManaged !== '1') return;
scrollHost.style.maxWidth = scrollHost.dataset.ncPrevInlineMaxWidth || '';
scrollHost.style.marginLeft = scrollHost.dataset.ncPrevInlineMarginLeft || '';
scrollHost.style.marginRight = scrollHost.dataset.ncPrevInlineMarginRight || '';
scrollHost.style.width = scrollHost.dataset.ncPrevInlineWidth || '';
scrollHost.style.paddingLeft = scrollHost.dataset.ncPrevInlinePaddingLeft || '';
scrollHost.style.paddingRight = scrollHost.dataset.ncPrevInlinePaddingRight || '';
delete scrollHost.dataset.ncPrevInlineMaxWidth;
delete scrollHost.dataset.ncPrevInlineMarginLeft;
delete scrollHost.dataset.ncPrevInlineMarginRight;
delete scrollHost.dataset.ncPrevInlineWidth;
delete scrollHost.dataset.ncPrevInlinePaddingLeft;
delete scrollHost.dataset.ncPrevInlinePaddingRight;
delete scrollHost.dataset.ncScrollHostInlineGutterManaged;
},
/**
* Remove previously managed scroll-host height overrides.
* @param {HTMLElement | null} scrollHost
* @private
*/
_clearManagedScrollHostHeight(scrollHost) {
if (!scrollHost || scrollHost.dataset.ncScrollHostHeightManaged !== '1') return;
scrollHost.style.removeProperty('height');
delete scrollHost.dataset.ncScrollHostHeightManaged;
},
/**
* Ensure page scrolling happens inside content instead of the document body.
* @private
*/
_syncScrollShell() {
if (!document.body) return;
const scrollHost = this._resolveScrollHost();
const root = document.documentElement;
if (this._scrollHost && this._scrollHost !== scrollHost) {
this._clearManagedScrollHostHeight(this._scrollHost);
this._clearManagedScrollHostInlineGutters(this._scrollHost);
this._scrollHost.classList.remove('nc-scroll-host');
}
this._scrollHost = scrollHost || null;
if (!scrollHost) {
document.body.classList.remove('nc-content-scroll-shell');
root.classList.remove('nc-content-scroll-shell-root');
return;
}
document.body.classList.add('nc-content-scroll-shell');
root.classList.add('nc-content-scroll-shell-root');
if (scrollHost.classList.contains('fixed')) {
this._clearManagedScrollHostHeight(scrollHost);
this._clearManagedScrollHostInlineGutters(scrollHost);
scrollHost.classList.remove('nc-scroll-host');
} else {
scrollHost.classList.add('nc-scroll-host');
this._syncScrollHostHeight(scrollHost);
this._syncScrollHostInlineGutters(scrollHost);
}
},
/**
* Schedule a single-frame sync for topbar/nav metrics and scroll shell classes.
* @private
*/
_scheduleScrollShellSync() {
if (this._scrollShellRaf) {
window.cancelAnimationFrame(this._scrollShellRaf);
}
this._scrollShellRaf = window.requestAnimationFrame(() => {
this._scrollShellRaf = null;
this._syncTopbarMetrics();
this._syncBottomNavMetrics();
this._syncScrollShell();
this._applyAutoTopbarGap();
});
},
/**
* Determine whether a mutation can affect scroll-shell host selection or offsets.
* @param {MutationRecord[]} mutationList
* @returns {boolean}
* @private
*/
_shouldResyncScrollShellForMutation(mutationList) {
const relevantSelector =
'main, #main-content, .page-panel, nav[data-bottom-nav], header[data-topbar="1"], body';
const isElementNode = node => node && node.nodeType === 1;
const hasRelevantNode = node => {
if (!isElementNode(node)) return false;
if (node.matches(relevantSelector)) return true;
return !!node.querySelector(relevantSelector);
};
for (const mutation of mutationList) {
if (mutation.type === 'attributes') {
if (isElementNode(mutation.target) && mutation.target.matches(relevantSelector)) {
return true;
}
continue;
}
if (mutation.type === 'childList') {
const target = mutation.target;
if (
!isElementNode(target) ||
!target.matches('body, .page-panel, #header-placeholder, #navbar-placeholder')
) {
continue;
}
for (const node of mutation.addedNodes) {
if (hasRelevantNode(node)) return true;
}
for (const node of mutation.removedNodes) {
if (hasRelevantNode(node)) return true;
}
}
}
return false;
},
/**
* Keep the scroll shell in sync when panel visibility or fixed chrome changes at runtime.
* @private
*/
_bindScrollShellObserver() {
if (this._scrollShellObserverBound || !document.body || !window.MutationObserver) return;
this._scrollShellObserverBound = true;
this._scrollShellObserver = new MutationObserver(mutationList => {
if (!this._shouldResyncScrollShellForMutation(mutationList)) return;
this._scheduleScrollShellSync();
});
this._scrollShellObserver.observe(document.body, {
subtree: true,
childList: true,
attributes: true,
attributeFilter: ['class', 'hidden', 'style', 'aria-hidden'],
});
if (!this._scrollShellHistoryBound) {
this._scrollShellHistoryBound = true;
window.addEventListener('hashchange', () => this._scheduleScrollShellSync());
window.addEventListener('popstate', () => this._scheduleScrollShellSync());
}
},
/**
* Detect whether page content already has a topbar offset.
* @returns {boolean}
* @private
*/
_hasExplicitTopbarOffset() {
const classBasedOffset = document.querySelector(
'.pt-topbar-gap, [class*="pt-[var(--topbar-height"], [class*="pt-[calc(var(--topbar-height"]'
);
if (classBasedOffset) return true;
const inlineOffset = document.querySelector(
'[style*="padding-top"][style*="--topbar-height"], [style*="top: calc(var(--topbar-height"], [style*="top: var(--topbar-height"]'
);
return !!inlineOffset;
},
/**
* Apply a safe fallback top gap only when a fixed topbar is present and no explicit gap exists.
* @private
*/
_applyAutoTopbarGap() {
const topbar = document.querySelector(TOPBAR_SELECTOR);
const topbarHidden =
!topbar || topbar.hidden || topbar.classList.contains('hidden') || !topbar.offsetParent;
if (topbarHidden || !document.body) {
if (document.body) document.body.classList.remove('nc-auto-topbar-gap');
return;
}
if (document.body.classList.contains('nc-content-scroll-shell')) {
document.body.classList.remove('nc-auto-topbar-gap');
return;
}
if (this._hasExplicitTopbarOffset()) {
document.body.classList.remove('nc-auto-topbar-gap');
return;
}
document.body.classList.add('nc-auto-topbar-gap');
},
/**
* Determine whether current viewport is desktop width.
* @returns {boolean}
* @private
*/
_isDesktopViewport() {
try {
return !!window.matchMedia && window.matchMedia('(min-width: 768px)').matches;
} catch {
return false;
}
},
/**
* Normalize a page token (path+query or hash token) for reliable key lookups.
* @param {string} value
* @returns {string}
* @private
*/
_normalizePageToken(value) {
const raw = String(value || '').trim();
if (!raw) return '/';
if (raw.startsWith('#')) return raw.toLowerCase();
try {
const parsed = new URL(raw, window.location.origin);
const pathname = String(parsed.pathname || '/').toLowerCase();
const search = parsed.searchParams.toString().toLowerCase();
const hash = String(parsed.hash || '').toLowerCase();
if (hash && (pathname === '/' || pathname === '') && !search) return hash;
return search ? `${pathname}?${search}` : pathname;
} catch {
return raw.toLowerCase();
}
},
/**
* Compose a canonical browser title in "Project - Tab" form.
* @param {string} siteTitle
* @param {string} tabTitle
* @returns {string}
* @private
*/
_composeDocumentTitle(siteTitle, tabTitle = '') {
const normalizedSiteTitle = String(siteTitle || '').trim() || 'App';
const normalizedTabTitle = String(tabTitle || '').trim();
return normalizedTabTitle
? `${normalizedSiteTitle} - ${normalizedTabTitle}`
: normalizedSiteTitle;
},
/**
* Update the active browser tab title.
* @param {string} siteTitle
* @param {string} tabTitle
* @private
*/
_setDocumentTitle(siteTitle, tabTitle = '') {
document.title = this._composeDocumentTitle(siteTitle, tabTitle);
},
/**
* Resolve navbar label by href/path token.
* @param {Array} navbarItems
* @param {string} hrefValue
* @returns {string}
* @private
*/
_resolveNavbarLabel(navbarItems, hrefValue) {
if (!Array.isArray(navbarItems) || navbarItems.length === 0) return '';
const normalizedTarget = this._normalizePageToken(hrefValue);
for (const item of navbarItems) {
const normalizedItem = this._normalizePageToken(item && item.href ? item.href : '');
if (normalizedItem !== normalizedTarget) continue;
const label = String(item && item.label ? item.label : '').trim();
if (label) return label;
}
return '';
},
/**
* Determine the title to render for initial component load.
* @param {{siteTitle: string, title: string, navbarItems: Array, navbarCurrentPath: string}} input
* @returns {string}
* @private
*/
_resolveTitleForLoad(input = {}) {
const explicitTitle = String(input.title || '').trim();
if (explicitTitle) return explicitTitle;
const navbarItems = Array.isArray(input.navbarItems) ? input.navbarItems : [];
const fromCurrentPath = this._resolveNavbarLabel(navbarItems, input.navbarCurrentPath || '');
if (fromCurrentPath) return fromCurrentPath;
const fromLocation = this._resolveNavbarLabel(
navbarItems,
`${window.location.pathname || '/'}${window.location.search || ''}${window.location.hash || ''}`
);
if (fromLocation) return fromLocation;
const firstLabel = String(
navbarItems[0] && navbarItems[0].label ? navbarItems[0].label : ''
).trim();
return firstLabel || '';
},
/**
* Keep browser title in sync with bottom-nav tab clicks.
* @private
*/
_bindNavbarTitleSync() {
if (this._navbarTitleSyncBound) return;
this._navbarTitleSyncBound = true;
document.addEventListener(
'click',
event => {
const link = event.target.closest('nav[data-bottom-nav] a[href]');
if (!link) return;
const context = this._navbarTitleContext || {};
const contextSiteTitle = String(context.siteTitle || '').trim();
const contextNavbarItems = Array.isArray(context.navbarItems) ? context.navbarItems : [];
if (!contextSiteTitle || contextNavbarItems.length === 0) return;
const href = link.getAttribute('href') || link.href || '';
const tabTitle =
this._resolveNavbarLabel(contextNavbarItems, href) ||
String(link.textContent || '').trim();
if (!tabTitle) return;
this._setDocumentTitle(contextSiteTitle, tabTitle);
},
true
);
},
/**
* Resolve which page token should be used when probing /auth/me.
* @param {string} authPageToken
* @param {string} navbarCurrentPath
* @returns {string}
* @private
*/
_resolveAuthPageToken(authPageToken, navbarCurrentPath) {
const explicitToken = String(authPageToken || '').trim();
if (explicitToken) return this._normalizePageToken(explicitToken);
const navbarToken = String(navbarCurrentPath || '').trim();
if (navbarToken) return this._normalizePageToken(navbarToken);
const locationToken = `${window.location.pathname || '/'}${window.location.search || ''}${window.location.hash || ''}`;
return this._normalizePageToken(locationToken);
},
/**
* Determine whether the given page token is protected for current auth state.
* @param {string} pageToken
* @param {{loginRequiredPages?: object, loginRequiredAllPages?: boolean}} [authState]
* @returns {boolean}
* @private
*/
_isPageLoginRequired(pageToken, authState = window.__NC_AUTH_STATE || {}) {
const requiredAllPages = authState.loginRequiredAllPages === true;
const requiredPages =
authState.loginRequiredPages && typeof authState.loginRequiredPages === 'object'
? authState.loginRequiredPages
: {};
const normalizedToken = this._normalizePageToken(pageToken);
return requiredAllPages || requiredPages[normalizedToken] === true;
},
/**
* Attach a capturing nav click guard so protected tabs cannot be entered when logged out.
* @private
*/
_bindProtectedNavGuard() {
if (this._protectedNavGuardBound) return;
this._protectedNavGuardBound = true;
window.addEventListener('auth:login-success', () => {
const state = window.__NC_AUTH_STATE || {};
window.__NC_AUTH_STATE = {
...state,
user: state.user || { id: 'session' },
};
});
document.addEventListener(
'click',
event => {
const link = event.target.closest('nav[data-bottom-nav] a[href]');
if (!link) return;
const href = link.getAttribute('href') || link.href || '';
const pageToken = this._normalizePageToken(href);
window.__NC_ACTIVE_PAGE_TOKEN = pageToken;
const authState = window.__NC_AUTH_STATE || {};
if (authState.user) return;
const isProtected = this._isPageLoginRequired(pageToken, authState);
if (!isProtected) return;
event.preventDefault();
event.stopImmediatePropagation();
const loginButton = document.getElementById('authLoginOpenBtn');
if (loginButton) {
loginButton.click();
}
if (window.toast && typeof window.toast.info === 'function') {
window.toast.info('Log in is required for this page.');
}
},
true
);
},
/**
* Fetch current auth state. Fail-open to avoid blocking page chrome on probe errors.
* @param {string} pageToken
* @returns {Promise<{authRequired: boolean, user: object | null}>}
* @private
*/
async _getAuthState(pageToken) {
const fallbackPage = `${window.location.pathname || '/'}${window.location.search || ''}${window.location.hash || ''}`;
const currentPage = this._normalizePageToken(pageToken || fallbackPage);
try {
const res = await fetch(`/auth/me?page=${encodeURIComponent(currentPage)}`, {
credentials: 'same-origin',
headers: { Accept: 'application/json' },
});
if (!res.ok) {
return {
authRequired: false,
user: null,
loginRequiredPages: {},
loginRequiredAllPages: false,
pageToken: currentPage,
};
}
const auth = await res.json();
const pages =
auth && auth.loginRequiredPages && typeof auth.loginRequiredPages === 'object'
? auth.loginRequiredPages
: {};
return {
authRequired: !!(auth && auth.authRequired === true),
user: (auth && auth.user) || null,
loginRequiredPages: pages,
loginRequiredAllPages: !!(auth && auth.loginRequiredAllPages === true),
pageToken: currentPage,
};
} catch {
return {
authRequired: false,
user: null,
loginRequiredPages: {},
loginRequiredAllPages: false,
pageToken: currentPage,
};
}
},
/**
* Whether auth gate is enabled and there is no active session.
* @param {{authRequired: boolean, user: object | null}} authState
* @returns {boolean}
* @private
*/
_isAuthRequiredWithoutUser(authState) {
return !!(authState && authState.authRequired === true && !authState.user);
},
/**
* Hide visible topbar chrome while keeping auth modal DOM available.
* @private
*/
_hideHeaderForAuthState() {
const topbar = document.querySelector(TOPBAR_SELECTOR);
if (topbar) {
topbar.classList.add('hidden');
topbar.setAttribute('aria-hidden', 'true');
}
document.documentElement.style.setProperty('--bar-height', '0px');
document.documentElement.style.setProperty('--topbar-height', '0px');
document.documentElement.style.setProperty('--bottom-nav-height', '0px');
if (document.body) document.body.classList.remove('nc-auto-topbar-gap');
},
};
// Export to global namespace
window.NCComponentLoader = NCComponentLoader;
})(window);
@@ -1,204 +0,0 @@
// NCExpandableContainer
// Shared helper for expandable/collapsible containers with optional persistence.
//
// Usage:
// const controller = window.NCExpandableContainer.bind({
// toggleEl: 'filtersToggle',
// contentEl: 'filtersBody',
// chevronEl: 'filtersChevron',
// storageKey: 'app:filters-open',
// storageFormat: 'flag', // 'json' | 'flag'
// defaultExpanded: false,
// initFromAria: true,
// chevronMode: 'class', // 'class' | 'style'
// chevronRotateClass: 'rotate-180',
// syncHiddenAttribute: true,
// onChange: expanded => { ... },
// });
(function (global) {
'use strict';
var controllerByToggle = new WeakMap();
function toElement(target) {
if (!target) return null;
if (target instanceof Element) return target;
var value = String(target || '').trim();
if (!value) return null;
if (value.charAt(0) === '#') {
try {
return document.querySelector(value);
} catch {
return null;
}
}
var byId = document.getElementById(value);
if (byId) return byId;
try {
return document.querySelector(value);
} catch {
return null;
}
}
function readStorageBoolean(storageKey, storageFormat) {
if (!storageKey) return null;
try {
var raw = localStorage.getItem(storageKey);
if (raw == null) return null;
if (storageFormat === 'flag') return raw === '1';
return !!JSON.parse(raw);
} catch {
return null;
}
}
function writeStorageBoolean(storageKey, value, storageFormat) {
if (!storageKey) return;
try {
if (storageFormat === 'flag') localStorage.setItem(storageKey, value ? '1' : '0');
else localStorage.setItem(storageKey, JSON.stringify(!!value));
} catch {
// Ignore storage failures.
}
}
function applyChevronState(chevronEl, expanded, chevronMode, chevronRotateClass) {
if (!chevronEl) return;
if (chevronMode === 'style') {
chevronEl.style.transform = expanded ? 'rotate(180deg)' : '';
return;
}
chevronEl.classList.toggle(chevronRotateClass, !!expanded);
}
function bind(options) {
var config = options || {};
var toggleEl = toElement(config.toggleEl || config.toggle || config.toggleId);
var contentEl = toElement(config.contentEl || config.content || config.contentId);
if (!toggleEl || !contentEl) return null;
if (config.allowRebind !== true && controllerByToggle.has(toggleEl)) {
return controllerByToggle.get(toggleEl);
}
var chevronEl = toElement(config.chevronEl || config.chevron || config.chevronId);
var hiddenClass = String(config.hiddenClass || 'hidden');
var eventName = String(config.eventName || 'click');
var storageKey = config.storageKey ? String(config.storageKey) : '';
var storageFormat = config.storageFormat === 'flag' ? 'flag' : 'json';
var defaultExpanded = config.defaultExpanded === true;
var initFromAria = config.initFromAria !== false;
var updateAria = config.updateAria !== false;
var syncHiddenAttribute = config.syncHiddenAttribute === true;
var persistState = config.persistState !== false;
var emitInitial = config.emitInitial !== false;
var chevronMode = config.chevronMode === 'style' ? 'style' : 'class';
var chevronRotateClass = String(config.chevronRotateClass || 'rotate-180');
var onChange = typeof config.onChange === 'function' ? config.onChange : null;
var onBeforeToggle =
typeof config.onBeforeToggle === 'function' ? config.onBeforeToggle : null;
var expanded = defaultExpanded;
var stored = readStorageBoolean(storageKey, storageFormat);
if (typeof stored === 'boolean') {
expanded = stored;
} else if (initFromAria && toggleEl.hasAttribute('aria-expanded')) {
expanded = toggleEl.getAttribute('aria-expanded') === 'true';
}
function applyExpanded(nextExpanded, opts) {
var applyOptions = opts || {};
var persist = applyOptions.persist !== false;
var emit = applyOptions.emit !== false;
expanded = !!nextExpanded;
contentEl.classList.toggle(hiddenClass, !expanded);
if (syncHiddenAttribute) {
contentEl.hidden = !expanded;
}
if (updateAria) {
toggleEl.setAttribute('aria-expanded', String(expanded));
}
applyChevronState(chevronEl, expanded, chevronMode, chevronRotateClass);
if (persist && persistState && storageKey) {
writeStorageBoolean(storageKey, expanded, storageFormat);
}
if (emit && onChange) {
onChange(expanded, {
toggleEl: toggleEl,
contentEl: contentEl,
chevronEl: chevronEl,
controller: controller,
});
}
}
function handleToggle(event) {
if (onBeforeToggle) {
try {
if (onBeforeToggle(event, expanded) === false) return;
} catch {
// Ignore before-toggle hook errors.
}
}
applyExpanded(!expanded);
}
toggleEl.addEventListener(eventName, handleToggle);
var controller = {
elements: {
toggleEl: toggleEl,
contentEl: contentEl,
chevronEl: chevronEl,
},
isExpanded: function () {
return expanded;
},
setExpanded: function (nextExpanded, opts) {
applyExpanded(nextExpanded, opts);
},
toggle: function (opts) {
applyExpanded(!expanded, opts);
},
destroy: function () {
toggleEl.removeEventListener(eventName, handleToggle);
controllerByToggle.delete(toggleEl);
},
};
controllerByToggle.set(toggleEl, controller);
applyExpanded(expanded, { persist: false, emit: emitInitial });
return controller;
}
function bindMany(configs) {
if (!Array.isArray(configs)) return [];
return configs.map(function (config) {
return bind(config);
});
}
global.NCExpandableContainer = {
bind: bind,
bindMany: bindMany,
readStorageBoolean: readStorageBoolean,
writeStorageBoolean: writeStorageBoolean,
applyChevronState: applyChevronState,
};
})(window);
@@ -1,266 +0,0 @@
(() => {
if (window.NCHeaderControls) return;
const state = {
level: 'checking',
health: null,
readiness: null,
service: '',
checkedAt: null,
loading: false,
};
const boundButtons = new WeakSet();
let statusRequest = null;
let statusTimer = null;
let activeDialog = null;
let activeOpener = null;
const levelLabels = {
checking: 'Checking',
healthy: 'Healthy',
degraded: 'Degraded',
offline: 'Offline',
};
const levelIcons = {
checking: 'fa-circle-question',
healthy: 'fa-circle-check',
degraded: 'fa-triangle-exclamation',
offline: 'fa-circle-xmark',
};
const levelColors = {
checking: 'var(--color-bar-text-muted)',
healthy: 'var(--color-success-strong, #16a34a)',
degraded: 'var(--color-warning, #f59e0b)',
offline: 'var(--color-danger, #ef4444)',
};
function setDialogVisible(dialog, visible) {
if (!dialog) return;
dialog.hidden = !visible;
dialog.style.display = visible ? 'grid' : 'none';
dialog.setAttribute('aria-hidden', visible ? 'false' : 'true');
}
function createOverlay(id, title, description) {
const overlay = document.createElement('div');
overlay.id = id;
overlay.hidden = true;
overlay.setAttribute('aria-hidden', 'true');
overlay.setAttribute('role', 'dialog');
overlay.setAttribute('aria-modal', 'true');
overlay.setAttribute('aria-labelledby', `${id}Title`);
overlay.className = 'fixed inset-0 z-[210] hidden place-items-center bg-black/70 p-4';
overlay.style.background = 'var(--color-overlay, rgba(0, 0, 0, 0.7))';
overlay.innerHTML = `
<div class="relative w-[min(560px,92vw)] overflow-hidden rounded-lg border border-[var(--color-border-strong)] bg-[var(--color-surface)] text-[var(--color-text)] shadow-2xl" role="document">
<button type="button" data-dialog-close aria-label="Close" class="absolute right-2.5 top-2.5 inline-flex h-9 w-9 items-center justify-center rounded-full border border-[var(--color-border-strong)] bg-[var(--color-bg-soft)] text-[var(--color-text)] shadow-sm hover:bg-[var(--color-surface)]"><i class="fas fa-xmark" aria-hidden="true"></i></button>
<div class="flex flex-col gap-1 px-4 pb-2 pt-4">
<h2 id="${id}Title" class="m-0 text-lg font-[650]">${title}</h2>
<p class="m-0 text-sm text-[var(--color-text-dim)]">${description}</p>
</div>
<div data-dialog-body class="px-4 pb-4 pt-3"></div>
</div>
`;
document.body.appendChild(overlay);
overlay.addEventListener('click', event => {
if (event.target === overlay) closeDialog(overlay);
});
overlay.querySelector('[data-dialog-close]')?.addEventListener('click', () => closeDialog(overlay));
return overlay;
}
function ensureSettingsDialog() {
let overlay = document.getElementById('ncSettingsOverlay');
if (overlay) return overlay;
overlay = createOverlay('ncSettingsOverlay', 'Settings', 'Personalize the shared MediaCollection interface.');
const body = overlay.querySelector('[data-dialog-body]');
body.innerHTML = `
<div class="flex items-center justify-between gap-3 rounded-md border border-[var(--color-border-strong)] bg-[var(--color-bg-soft)] px-3 py-3">
<div>
<div class="text-sm font-medium">Theme</div>
<div class="mt-1 text-xs text-[var(--color-text-dim)]">Switch between the light and dark appearance.</div>
</div>
<button type="button" data-theme-toggle class="inline-flex min-w-[92px] items-center justify-center rounded-full border border-[var(--color-border-strong)] bg-[var(--color-surface)] px-3 py-2 text-sm font-semibold text-[var(--color-text)] shadow-sm hover:bg-[var(--color-surface-raised)]" title="Toggle dark / light theme" aria-label="Toggle theme">Toggle</button>
</div>
`;
return overlay;
}
function ensureStatusDialog() {
let overlay = document.getElementById('ncStatusOverlay');
if (overlay) return overlay;
overlay = createOverlay('ncStatusOverlay', 'Status', 'Live liveness and database readiness checks.');
const body = overlay.querySelector('[data-dialog-body]');
body.innerHTML = `
<div class="mb-4 flex items-center gap-3 rounded-md border border-[var(--color-border-strong)] bg-[var(--color-bg-soft)] px-3 py-3" aria-live="polite">
<i data-status-overall-icon class="fas fa-circle-question text-lg" aria-hidden="true"></i>
<span data-status-overall class="font-semibold">Checking</span>
<span data-status-checked class="ml-auto text-xs text-[var(--color-text-dim)]"></span>
</div>
<div class="flex flex-col gap-2 text-sm">
<div class="flex items-center justify-between gap-4 rounded-md border border-[var(--color-border-strong)] px-3 py-2"><span>Liveness</span><span data-status-health>Not checked</span></div>
<div class="flex items-center justify-between gap-4 rounded-md border border-[var(--color-border-strong)] px-3 py-2"><span>Readiness / database</span><span data-status-readiness>Not checked</span></div>
</div>
<p data-status-service class="mt-3 mb-0 text-xs text-[var(--color-text-dim)]"></p>
<div class="mt-5 flex justify-end gap-2">
<button type="button" data-status-refresh class="inline-flex items-center gap-2 rounded-full border border-[var(--color-border-strong)] bg-[var(--color-surface)] px-3 py-2 text-sm font-semibold text-[var(--color-text)] shadow-sm hover:bg-[var(--color-surface-raised)]"><i class="fas fa-rotate" aria-hidden="true"></i>Refresh</button>
<button type="button" data-dialog-close class="inline-flex items-center justify-center rounded-full bg-[var(--color-action)] px-3 py-2 text-sm font-semibold text-white shadow-sm hover:bg-[var(--color-action-hover)]">Dismiss</button>
</div>
`;
overlay.querySelector('[data-status-refresh]')?.addEventListener('click', () => void refreshStatus());
overlay.querySelectorAll('[data-dialog-close]').forEach(button => {
button.addEventListener('click', () => closeDialog(overlay));
});
return overlay;
}
function openDialog(dialog, opener) {
activeDialog = dialog;
activeOpener = opener || null;
setDialogVisible(dialog, true);
window.setTimeout(() => dialog.querySelector('[data-dialog-close]')?.focus(), 0);
}
function closeDialog(dialog) {
if (!dialog) return;
setDialogVisible(dialog, false);
if (activeDialog === dialog) {
const opener = activeOpener;
activeDialog = null;
activeOpener = null;
opener?.focus?.();
}
}
async function probe(path) {
try {
const response = await fetch(path, {
credentials: 'same-origin',
headers: { Accept: 'application/json' },
});
const payload = await response.json().catch(() => null);
return {
ok: response.ok && payload?.ok !== false,
status: response.status,
service: payload?.service || '',
error: response.ok ? '' : payload?.error || response.statusText || `HTTP ${response.status}`,
};
} catch (error) {
return {
ok: false,
status: null,
service: '',
error: error instanceof Error ? error.message : 'Unavailable',
};
}
}
function resultLabel(result) {
if (!result) return 'Not checked';
if (result.ok) return 'OK';
return result.error || (result.status ? `HTTP ${result.status}` : 'Unavailable');
}
function renderStatus() {
const iconClass = levelIcons[state.level];
const color = levelColors[state.level];
document.querySelectorAll('[data-status-button]').forEach(button => {
const icon = button.querySelector('[data-status-icon]');
if (icon) {
icon.className = `fas ${iconClass}`;
icon.style.color = color;
}
button.title = `Service status: ${levelLabels[state.level]}`;
button.setAttribute('aria-label', `Service status: ${levelLabels[state.level]}`);
});
const dialog = document.getElementById('ncStatusOverlay');
if (!dialog) return;
const overallIcon = dialog.querySelector('[data-status-overall-icon]');
if (overallIcon) {
overallIcon.className = `fas ${iconClass} text-lg`;
overallIcon.style.color = color;
}
const overall = dialog.querySelector('[data-status-overall]');
if (overall) {
overall.textContent = levelLabels[state.level];
overall.style.color = color;
}
const checked = dialog.querySelector('[data-status-checked]');
if (checked) checked.textContent = state.checkedAt ? new Date(state.checkedAt).toLocaleTimeString() : '';
const health = dialog.querySelector('[data-status-health]');
if (health) {
health.textContent = resultLabel(state.health);
health.style.color = state.health?.ok ? 'var(--color-success-strong, #16a34a)' : 'var(--color-danger, #ef4444)';
}
const readiness = dialog.querySelector('[data-status-readiness]');
if (readiness) {
readiness.textContent = resultLabel(state.readiness);
readiness.style.color = state.readiness?.ok ? 'var(--color-success-strong, #16a34a)' : 'var(--color-danger, #ef4444)';
}
const service = dialog.querySelector('[data-status-service]');
if (service) service.textContent = state.service ? `Service: ${state.service}` : '';
const refreshButton = dialog.querySelector('[data-status-refresh]');
if (refreshButton) refreshButton.disabled = state.loading;
}
function refreshStatus() {
if (statusRequest) return statusRequest;
state.loading = true;
renderStatus();
statusRequest = Promise.all([probe('/healthz'), probe('/ready')])
.then(([health, readiness]) => {
state.health = health;
state.readiness = readiness;
state.service = health.service || readiness.service || '';
state.level = health.ok && readiness.ok ? 'healthy' : health.ok ? 'degraded' : 'offline';
state.checkedAt = new Date().toISOString();
})
.finally(() => {
state.loading = false;
statusRequest = null;
renderStatus();
});
return statusRequest;
}
function bindHeaderButtons() {
document.querySelectorAll('[data-settings-button], [data-settings-menu-button]').forEach(button => {
if (boundButtons.has(button)) return;
boundButtons.add(button);
button.addEventListener('click', () => openDialog(ensureSettingsDialog(), button));
});
document.querySelectorAll('[data-status-button]').forEach(button => {
if (boundButtons.has(button)) return;
boundButtons.add(button);
button.addEventListener('click', () => {
const dialog = ensureStatusDialog();
openDialog(dialog, button);
void refreshStatus();
});
});
renderStatus();
}
function init() {
if (!document.body) return;
ensureSettingsDialog();
ensureStatusDialog();
bindHeaderButtons();
window.NCThemeToggle?.init?.();
if (!statusTimer) {
void refreshStatus();
statusTimer = window.setInterval(() => void refreshStatus(), 15_000);
}
}
document.addEventListener('keydown', event => {
if (event.key === 'Escape' && activeDialog) closeDialog(activeDialog);
});
document.addEventListener('DOMContentLoaded', init, { once: true });
document.addEventListener('nc:componentsLoaded', init);
window.NCHeaderControls = { init, refreshStatus };
})();
@@ -1,442 +0,0 @@
/**
* Shared Results container helpers.
*
* Exposes:
* - window.NCResultsContainer.apply(config)
* - window.NCResultsContainer.ensurePaginationBars(paginationBars)
*/
(() => {
const VIEW_MODES = [
{
value: 'list',
label: 'List view',
icon: '<svg aria-hidden="true" viewBox="0 0 24 24" fill="none" class="h-4 w-4"><path d="M4 6h16M4 12h16M4 18h16" stroke="currentColor" stroke-width="2" stroke-linecap="round"/></svg>',
},
{
value: 'grid',
label: 'Grid view',
icon: '<svg aria-hidden="true" viewBox="0 0 24 24" fill="none" class="h-4 w-4"><rect x="4" y="4" width="6" height="6" rx="1" stroke="currentColor" stroke-width="2"/><rect x="14" y="4" width="6" height="6" rx="1" stroke="currentColor" stroke-width="2"/><rect x="4" y="14" width="6" height="6" rx="1" stroke="currentColor" stroke-width="2"/><rect x="14" y="14" width="6" height="6" rx="1" stroke="currentColor" stroke-width="2"/></svg>',
},
];
const VIEW_MODE_SYNC_KEY = '__ncViewModeSelectorSync';
const VIEW_MODE_CHANGE_KEY = '__ncViewModeSelectorChange';
const DEFAULT_RESULTS_CONTAINER_CLASSES = [
'rounded-lg',
'border',
'border-[var(--color-border)]',
'bg-[var(--color-surface)]',
];
function toElement(target) {
if (!target) return null;
if (target instanceof Element) return target;
if (typeof target === 'string') {
return document.getElementById(target) || document.querySelector(target);
}
return null;
}
function toElementList(targets) {
if (!targets) return [];
const list = Array.isArray(targets) ? targets : [targets];
return list.map(toElement).filter(el => el instanceof Element);
}
function addClasses(el, classNames) {
if (!el || !classNames) return;
const list = Array.isArray(classNames) ? classNames : String(classNames).split(/\s+/);
for (const name of list) {
const token = String(name || '').trim();
if (token) el.classList.add(token);
}
}
function ensurePaginationBars(bars) {
for (const bar of toElementList(bars)) {
if (!bar.style.minHeight) bar.style.minHeight = '48px';
bar.classList.add('w-full');
bar.dataset.ncPaginationSlot = '1';
}
}
function normalizeViewModeConfig(config) {
if (!config) return null;
if (config instanceof Element || typeof config === 'string') {
return { select: config };
}
return config;
}
function normalizeModeValue(mode, fallback = 'grid') {
const value = String(mode || '').toLowerCase();
if (value === 'compact') return 'list';
if (value === 'list' || value === 'grid') return value;
return fallback;
}
function readStoredMode(storageKey) {
if (!storageKey) return null;
try {
const raw = window.localStorage.getItem(storageKey);
return raw ? normalizeModeValue(raw, null) : null;
} catch {
return null;
}
}
function writeStoredMode(storageKey, mode) {
if (!storageKey) return;
try {
window.localStorage.setItem(storageKey, mode);
} catch {
// ignore storage errors
}
}
function applyViewModeSelector(resultsContainer, config) {
const viewMode = normalizeViewModeConfig(config);
if (!resultsContainer || !viewMode) return;
const resultsContent = resultsContainer.querySelector('[data-nc-results-content="1"]');
function applyModeToResultsContent(mode) {
if (!resultsContent) return;
resultsContent.dataset.ncDisplayMode = normalizeModeValue(mode, 'grid');
}
const select = toElement(
viewMode.select ||
viewMode.selectInput ||
viewMode.selectElement ||
viewMode.target ||
viewMode.id
);
const selectEl = select && select.tagName === 'SELECT' ? select : null;
const selectId = (selectEl && selectEl.id) || String(viewMode.key || 'view-mode');
const selectorId = `nc-view-mode-selector-${selectId}`;
let modes = VIEW_MODES;
if (Array.isArray(viewMode.modes) && viewMode.modes.length > 0) {
const allowed = new Set(
viewMode.modes.map(mode => normalizeModeValue(mode, null)).filter(Boolean)
);
modes = VIEW_MODES.filter(mode => allowed.has(mode.value));
}
if (selectEl) {
const modeValues = new Set(
Array.from(selectEl.options || [])
.map(opt => normalizeModeValue(opt.value, null))
.filter(Boolean)
);
modes = modes.filter(mode => modeValues.has(mode.value));
}
if (!modes.length) return;
const defaultMode = normalizeModeValue(viewMode.defaultMode, 'grid');
const storageKey =
typeof viewMode.storageKey === 'string' && viewMode.storageKey.trim().length > 0
? viewMode.storageKey.trim()
: null;
let inlineMode = defaultMode;
if (!selectEl) {
const fromGetter =
typeof viewMode.getMode === 'function'
? normalizeModeValue(viewMode.getMode(), defaultMode)
: null;
const fromStorage = readStoredMode(storageKey);
inlineMode = fromGetter || fromStorage || defaultMode;
}
function getActiveMode() {
if (selectEl) return normalizeModeValue(selectEl.value, defaultMode);
return normalizeModeValue(inlineMode, defaultMode);
}
function setActiveMode(mode, source = 'ui') {
const nextMode = normalizeModeValue(mode, defaultMode);
const available = modes.some(m => m.value === nextMode);
if (!available) return;
applyModeToResultsContent(nextMode);
if (selectEl) {
if (normalizeModeValue(selectEl.value, defaultMode) !== nextMode) {
selectEl.value = nextMode;
if (source !== 'select') {
selectEl.dispatchEvent(new Event('change', { bubbles: true }));
}
}
} else {
inlineMode = nextMode;
if (typeof viewMode.setMode === 'function') {
try {
viewMode.setMode(nextMode);
} catch {
// ignore consumer callback errors
}
}
writeStoredMode(storageKey, nextMode);
}
if (!selectEl && typeof viewMode.onModeChange === 'function') {
try {
viewMode.onModeChange(nextMode);
} catch {
// ignore consumer callback errors
}
}
}
const ownedHostSelector = '[data-nc-display-mode-host="1"]';
function getOwnedHosts() {
return Array.from(resultsContainer.querySelectorAll(ownedHostSelector)).filter(
host => host.dataset.ncViewModeOwner === selectorId
);
}
function hasResultCards() {
if (!(resultsContent instanceof Element)) return false;
return Boolean(resultsContent.querySelector('[data-nc-result-card="1"]'));
}
function syncSelectorVisibility() {
const showSelector = hasResultCards();
for (const host of getOwnedHosts()) {
host.classList.toggle('hidden', !showSelector);
}
if (selectEl && viewMode.hideSelect === false) {
selectEl.classList.toggle('hidden', !showSelector);
selectEl.setAttribute('aria-hidden', showSelector ? 'false' : 'true');
}
}
function resolveRenderHosts() {
const centerSlots = Array.from(
resultsContainer.querySelectorAll('[data-nc-pagination-center-slot="1"]')
);
const paginationBars = Array.from(
resultsContainer.querySelectorAll('[data-nc-pagination-slot="1"]')
);
const hosts = [];
if (centerSlots.length) {
for (const slot of centerSlots) {
let host = Array.from(slot.querySelectorAll(ownedHostSelector)).find(
candidate => candidate.dataset.ncViewModeOwner === selectorId
);
if (!host) {
host = document.createElement('div');
host.className = 'flex items-center justify-center';
host.dataset.ncDisplayModeHost = '1';
host.dataset.ncViewModeOwner = selectorId;
slot.appendChild(host);
}
hosts.push(host);
}
} else {
let host = getOwnedHosts().find(candidate => candidate.dataset.ncViewModeFallback === '1');
if (!host) {
host = document.createElement('div');
host.className = 'mb-3 flex items-center justify-center';
host.dataset.ncDisplayModeHost = '1';
host.dataset.ncViewModeOwner = selectorId;
host.dataset.ncViewModeFallback = '1';
}
const anchor = paginationBars.find(bar => bar && bar.parentElement === resultsContainer);
if (anchor) {
resultsContainer.insertBefore(host, anchor);
} else {
resultsContainer.insertBefore(host, resultsContainer.firstChild);
}
hosts.push(host);
}
const keep = new Set(hosts);
for (const existingHost of getOwnedHosts()) {
if (!keep.has(existingHost)) existingHost.remove();
}
return hosts;
}
let syncActiveButtons = () => {};
function renderSelectorHosts() {
const hosts = resolveRenderHosts();
const buttonGroups = [];
for (const host of hosts) {
host.innerHTML = '';
const shell = document.createElement('div');
shell.className = 'inline-flex items-center justify-center';
const group = document.createElement('div');
group.className = 'inline-flex items-center gap-1.5';
group.setAttribute('role', 'group');
group.setAttribute('aria-label', viewMode.ariaLabel || 'Display mode');
const buttonByMode = new Map();
for (const mode of modes) {
const button = document.createElement('button');
button.type = 'button';
button.className =
'inline-flex h-8 w-8 items-center justify-center rounded border border-transparent text-[var(--color-text-dim)] transition-colors hover:text-[var(--color-text)] focus-visible:outline-none focus-visible:ring-2 focus-visible:ring-blue-300/20';
button.setAttribute('aria-label', mode.label);
button.setAttribute('title', mode.label);
button.dataset.ncDisplayMode = mode.value;
button.innerHTML = mode.icon;
button.addEventListener('click', () => {
if (getActiveMode() === mode.value) return;
setActiveMode(mode.value, 'ui');
syncActiveButtons();
});
buttonByMode.set(mode.value, button);
group.appendChild(button);
}
buttonGroups.push(buttonByMode);
shell.appendChild(group);
host.appendChild(shell);
}
syncActiveButtons = () => {
const activeMode = getActiveMode();
for (const group of buttonGroups) {
for (const mode of modes) {
const button = group.get(mode.value);
if (!button) continue;
const active = mode.value === activeMode;
button.setAttribute('aria-pressed', active ? 'true' : 'false');
button.classList.toggle('text-[var(--color-text)]', active);
button.classList.toggle('text-[var(--color-text-dim)]', !active);
button.classList.toggle('bg-[var(--color-surface)]', active);
button.classList.toggle('border-[var(--color-border-strong)]', active);
button.classList.toggle('shadow-[var(--shadow-sm)]', active);
button.classList.toggle('opacity-100', active);
button.classList.toggle('border-transparent', !active);
button.classList.toggle('opacity-80', !active);
}
}
};
syncActiveButtons();
syncSelectorVisibility();
}
if (selectEl && viewMode.hideSelect !== false) {
selectEl.style.display = 'none';
selectEl.setAttribute('aria-hidden', 'true');
selectEl.tabIndex = -1;
}
if (selectEl && typeof selectEl[VIEW_MODE_SYNC_KEY] === 'function') {
selectEl.removeEventListener('change', selectEl[VIEW_MODE_SYNC_KEY]);
}
if (selectEl && typeof selectEl[VIEW_MODE_CHANGE_KEY] === 'function') {
selectEl.removeEventListener('change', selectEl[VIEW_MODE_CHANGE_KEY]);
}
if (selectEl) {
selectEl[VIEW_MODE_SYNC_KEY] = () => syncActiveButtons();
selectEl[VIEW_MODE_CHANGE_KEY] = () => {
const currentMode = getActiveMode();
applyModeToResultsContent(currentMode);
if (storageKey) writeStoredMode(storageKey, currentMode);
if (typeof viewMode.onModeChange === 'function') {
try {
viewMode.onModeChange(currentMode);
} catch {
// ignore consumer callback errors
}
}
};
selectEl.addEventListener('change', selectEl[VIEW_MODE_SYNC_KEY]);
selectEl.addEventListener('change', selectEl[VIEW_MODE_CHANGE_KEY]);
const stored = readStoredMode(storageKey);
if (stored && modes.some(mode => mode.value === stored) && selectEl.value !== stored) {
selectEl.value = stored;
selectEl.dispatchEvent(new Event('change', { bubbles: true }));
}
} else {
setActiveMode(inlineMode, 'init');
}
const paginationListenerKey = `__ncViewModePaginationListener_${selectorId}`;
if (typeof resultsContainer[paginationListenerKey] === 'function') {
resultsContainer.removeEventListener(
'nc:pagination-rendered',
resultsContainer[paginationListenerKey]
);
}
const onPaginationRendered = event => {
const target = event?.target;
if (!(target instanceof Element)) return;
if (!resultsContainer.contains(target)) return;
if (target.dataset.ncPaginationSlot !== '1') return;
renderSelectorHosts();
};
resultsContainer[paginationListenerKey] = onPaginationRendered;
resultsContainer.addEventListener('nc:pagination-rendered', onPaginationRendered);
const resultsObserverKey = `__ncViewModeResultsObserver_${selectorId}`;
const existingObserver = resultsContainer[resultsObserverKey];
if (existingObserver && typeof existingObserver.disconnect === 'function') {
existingObserver.disconnect();
}
if (resultsContent instanceof Element && typeof MutationObserver !== 'undefined') {
const observer = new MutationObserver(() => {
syncSelectorVisibility();
});
observer.observe(resultsContent, { childList: true, subtree: true });
resultsContainer[resultsObserverKey] = observer;
}
renderSelectorHosts();
applyModeToResultsContent(getActiveMode());
syncSelectorVisibility();
}
function applyResultsContainer(config = {}) {
const container = toElement(config.container || config.resultsContainer || config.id);
if (!container) return null;
if (config.useDefaultShellClasses === true) {
addClasses(container, DEFAULT_RESULTS_CONTAINER_CLASSES);
}
addClasses(container, config.classes);
const role = Object.prototype.hasOwnProperty.call(config, 'role') ? config.role : 'region';
if (role) container.setAttribute('role', role);
if (config.label) container.setAttribute('aria-label', config.label);
container.dataset.ncResultsContainer = '1';
const content = toElement(config.resultsContent || config.grid || config.list);
if (content) {
content.dataset.ncResultsContent = '1';
if (!content.hasAttribute('aria-live')) content.setAttribute('aria-live', 'polite');
}
const emptyState = toElement(config.emptyState);
if (emptyState) emptyState.dataset.ncResultsEmpty = '1';
ensurePaginationBars(config.topPagination);
ensurePaginationBars(config.bottomPagination);
ensurePaginationBars(config.paginationBars);
applyViewModeSelector(container, config.viewModeSelector || config.viewMode);
return container;
}
window.NCResultsContainer = {
apply: applyResultsContainer,
ensurePaginationBars,
};
})();
@@ -1,433 +0,0 @@
/**
* Shared Search/Filter container helpers.
*
* Exposes:
* - window.NCSearchFilterContainer.apply(config)
* - window.NCSearchFilterContainer.applyStandardControls(config)
*/
(() => {
const DEFAULT_FILTER_CONTAINER_CLASSES = [
'rounded-lg',
'border',
'border-[var(--color-border)]',
'bg-[var(--color-surface)]',
];
const DEFAULT_PER_PAGE_VALUES = [12, 24, 48, 96];
const DEFAULT_PER_PAGE_VALUE = 24;
const DEFAULT_SORT_OPTIONS = [
{ value: 'time_desc', label: 'Time (Newest first)' },
{ value: 'time_asc', label: 'Time (Oldest first)' },
{ value: 'title_asc', label: 'Title (A-Z)' },
{ value: 'title_desc', label: 'Title (Z-A)' },
{ value: 'length_asc', label: 'Length (Short to long)' },
{ value: 'length_desc', label: 'Length (Long to short)' },
{ value: 'resolution_asc', label: 'Resolution (Low to high)' },
{ value: 'resolution_desc', label: 'Resolution (High to low)' },
{ value: 'speed_asc', label: 'Speed (Slow to fast)' },
{ value: 'speed_desc', label: 'Speed (Fast to slow)' },
];
function toElement(target) {
if (!target) return null;
if (target instanceof Element) return target;
if (typeof target === 'string') {
return document.getElementById(target) || document.querySelector(target);
}
return null;
}
function addClasses(el, classNames) {
if (!el || !classNames) return;
const list = Array.isArray(classNames) ? classNames : String(classNames).split(/\s+/);
for (const name of list) {
const token = String(name || '').trim();
if (token) el.classList.add(token);
}
}
function normalizeSearchInputAria(inputEl, fallbackLabel) {
if (!inputEl || inputEl.hasAttribute('aria-label')) return;
const placeholder = String(inputEl.getAttribute('placeholder') || '').trim();
inputEl.setAttribute('aria-label', placeholder || fallbackLabel || 'Search');
}
function cloneOptions(options) {
return (Array.isArray(options) ? options : []).map(option => ({
value: String(option.value),
label: String(option.label),
}));
}
function normalizePerPageOptions() {
return DEFAULT_PER_PAGE_VALUES.map(value => ({
value: String(value),
label: `${value} per page`,
}));
}
function normalizeSortOptions(options) {
const source = Array.isArray(options) && options.length ? options : DEFAULT_SORT_OPTIONS;
return source
.map(entry => {
if (!entry) return null;
if (typeof entry === 'object') {
const value = String(entry.value ?? '').trim();
if (!value) return null;
const label = String(entry.label ?? value).trim() || value;
return { value, label };
}
const value = String(entry).trim();
if (!value) return null;
return { value, label: value };
})
.filter(Boolean);
}
function setSelectOptions(selectEl, options, selectedValue, fallbackValue = options[0]?.value) {
if (!selectEl || !options.length) return null;
const normalizedSelected = String(selectedValue ?? selectEl.value ?? '').trim();
const values = new Set(options.map(option => option.value));
const resolvedValue =
normalizedSelected && values.has(normalizedSelected)
? normalizedSelected
: values.has(String(fallbackValue))
? String(fallbackValue)
: String(options[0].value);
selectEl.innerHTML = '';
options.forEach(option => {
const opt = document.createElement('option');
opt.value = option.value;
opt.textContent = option.label;
selectEl.appendChild(opt);
});
selectEl.value = resolvedValue;
return resolvedValue;
}
function applyStandardControls(config = {}) {
const searchInput = toElement(config.searchInput);
const perPageSelect = toElement(config.perPageSelect || config.perPageInput);
const sortSelect = toElement(config.sortSelect || config.sortInput);
if (searchInput) {
const placeholder = String(config.searchPlaceholder || '').trim();
const shouldSetPlaceholder =
!!placeholder &&
(config.forceSearchPlaceholder === true ||
!String(searchInput.getAttribute('placeholder') || '').trim());
if (shouldSetPlaceholder) searchInput.setAttribute('placeholder', placeholder);
normalizeSearchInputAria(searchInput, config.searchLabel || config.label);
}
const perPageOptions = normalizePerPageOptions();
const sortOptions = normalizeSortOptions(config.sortOptions);
const perPageValue = perPageSelect
? setSelectOptions(perPageSelect, perPageOptions, config.perPageValue, DEFAULT_PER_PAGE_VALUE)
: null;
const sortValue = sortSelect
? setSelectOptions(sortSelect, sortOptions, config.sortValue)
: null;
return {
searchInput,
perPageSelect,
sortSelect,
perPageValue,
sortValue,
};
}
function toElementInContainer(target, container) {
if (!target || !container) return null;
if (target instanceof Element) {
return container.contains(target) ? target : null;
}
if (typeof target === 'string') {
const value = target.trim();
if (!value) return null;
const safeValue = value.split('"').join('\\"');
const byIdInContainer = container.querySelector(`[id="${safeValue}"]`);
if (byIdInContainer) return byIdInContainer;
try {
const bySelectorInContainer = container.querySelector(value);
if (bySelectorInContainer) return bySelectorInContainer;
} catch {
// Ignore invalid selectors and continue to ID lookup.
}
const byId = document.getElementById(value);
if (byId && container.contains(byId)) return byId;
}
return null;
}
function normalizeFilterTargets(filterControls) {
if (!filterControls) return [];
if (Array.isArray(filterControls)) return filterControls;
return [filterControls];
}
function resolveControlNode(controlEl, container) {
if (!controlEl || !container.contains(controlEl)) return null;
let node = controlEl;
const parent = controlEl.parentElement;
if (parent && parent !== container) {
const hasAssociatedLabel =
!!controlEl.id &&
Array.from(parent.children).some(child => {
return child.tagName === 'LABEL' && child.getAttribute('for') === controlEl.id;
});
if (parent.tagName === 'LABEL' || parent.children.length === 1 || hasAssociatedLabel) {
node = parent;
}
}
if (!container.contains(node)) return null;
return node;
}
function resolveDropdownHost(container, searchInput, placement) {
const placementValue = String(placement || '').toLowerCase();
const desiredPlacement = placementValue === 'inline' ? 'inline' : 'below-search';
let row = null;
if (searchInput && container.contains(searchInput)) {
const matchedRow = searchInput.closest('.flex');
if (matchedRow && container.contains(matchedRow)) {
row = matchedRow;
}
}
if (desiredPlacement === 'below-search') {
if (row?.parentElement && container.contains(row.parentElement)) {
return {
host: row.parentElement,
row,
mode: 'below-search',
};
}
return {
host: container,
row,
mode: 'below-search',
};
}
if (row) {
return {
host: row,
row,
mode: 'inline',
};
}
return {
host: container,
row: null,
mode: desiredPlacement,
};
}
function hidePrimaryTitle(container) {
const headings = Array.from(container.querySelectorAll('h1, h2, h3, h4, h5, h6'));
const target = headings.find(heading => !heading.closest('button, summary'));
if (!target) return;
const parent = target.parentElement;
target.remove();
if (
parent &&
parent !== container &&
parent.children.length === 0 &&
!String(parent.textContent || '').trim()
) {
parent.remove();
}
}
function ensureFiltersDropdown(config = {}) {
const container = config.container;
if (!container) return null;
const targets = [];
const explicitTargets = normalizeFilterTargets(config.filterControls);
explicitTargets.forEach(target => {
const el = toElementInContainer(target, container);
if (el) targets.push(el);
});
if (config.includeStandardControls === true) {
const perPage = toElementInContainer(config.perPageSelect, container);
const sort = toElementInContainer(config.sortSelect, container);
if (perPage) targets.push(perPage);
if (sort) targets.push(sort);
}
if (!targets.length) {
const existing = container.querySelector('[data-nc-filters-dropdown="1"]');
if (existing) existing.remove();
return null;
}
const placement = resolveDropdownHost(
container,
config.searchInput,
config.filterDropdownPlacement
);
const host = placement.host;
if (!host) return null;
let details = container.querySelector('[data-nc-filters-dropdown="1"]');
let panel = container.querySelector('[data-nc-filters-dropdown-panel="1"]');
let summary = container.querySelector('[data-nc-filters-dropdown-toggle="1"]');
if (!details || !panel || !summary) {
details = document.createElement('details');
details.dataset.ncFiltersDropdown = '1';
details.className = placement.mode === 'below-search' ? 'relative mt-2 w-full' : 'relative';
summary = document.createElement('summary');
summary.dataset.ncFiltersDropdownToggle = '1';
summary.className =
placement.mode === 'below-search'
? 'inline-flex w-full cursor-pointer items-center justify-center rounded-md px-3 py-2 text-[var(--font-size-sm)] font-semibold border border-[var(--color-border)] bg-[var(--color-surface-alt)] text-[var(--color-text)] shadow-[var(--shadow-sm)] hover:bg-[var(--color-surface)] hover:border-[var(--color-border-strong)]'
: 'inline-flex cursor-pointer items-center justify-center rounded-md px-3 py-2 text-[var(--font-size-sm)] font-semibold border border-[var(--color-border)] bg-[var(--color-surface-alt)] text-[var(--color-text)] shadow-[var(--shadow-sm)] hover:bg-[var(--color-surface)] hover:border-[var(--color-border-strong)]';
summary.textContent = String(config.filterDropdownLabel || 'FILTERS');
summary.style.listStyle = 'none';
panel = document.createElement('div');
panel.dataset.ncFiltersDropdownPanel = '1';
panel.className =
'mt-2 flex flex-wrap items-center gap-3 rounded-md border border-[var(--color-border)] bg-[var(--color-surface)] p-3';
details.appendChild(summary);
details.appendChild(panel);
} else {
details.className = placement.mode === 'below-search' ? 'relative mt-2 w-full' : 'relative';
summary.className =
placement.mode === 'below-search'
? 'inline-flex w-full cursor-pointer items-center justify-center rounded-md px-3 py-2 text-[var(--font-size-sm)] font-semibold border border-[var(--color-border)] bg-[var(--color-surface-alt)] text-[var(--color-text)] shadow-[var(--shadow-sm)] hover:bg-[var(--color-surface)] hover:border-[var(--color-border-strong)]'
: 'inline-flex cursor-pointer items-center justify-center rounded-md px-3 py-2 text-[var(--font-size-sm)] font-semibold border border-[var(--color-border)] bg-[var(--color-surface-alt)] text-[var(--color-text)] shadow-[var(--shadow-sm)] hover:bg-[var(--color-surface)] hover:border-[var(--color-border-strong)]';
summary.textContent = String(config.filterDropdownLabel || 'FILTERS');
}
if (
placement.mode === 'below-search' &&
placement.row &&
placement.row.parentElement === host
) {
host.insertBefore(details, placement.row.nextSibling);
} else if (!host.contains(details)) {
host.appendChild(details);
}
const movedNodes = [];
const seen = new Set();
const searchNode = resolveControlNode(config.searchInput, container);
targets.forEach(target => {
const node = resolveControlNode(target, container);
if (!node || node === searchNode || node.contains(searchNode)) return;
if (seen.has(node)) return;
const hiddenControl =
target.type === 'hidden' ||
target.hidden === true ||
target.classList?.contains('hidden') ||
node.hidden === true ||
node.classList?.contains('hidden');
if (hiddenControl) return;
seen.add(node);
movedNodes.push(node);
});
movedNodes.forEach(node => {
if (!panel.contains(node)) panel.appendChild(node);
});
if (!panel.children.length) {
details.remove();
return null;
}
return details;
}
function applyFilterContainer(config = {}) {
const container = toElement(config.container || config.filterContainer || config.id);
if (!container) return null;
if (config.useDefaultShellClasses === true) {
addClasses(container, DEFAULT_FILTER_CONTAINER_CLASSES);
}
addClasses(container, config.classes);
const role = Object.prototype.hasOwnProperty.call(config, 'role') ? config.role : 'region';
if (role) container.setAttribute('role', role);
if (config.label) container.setAttribute('aria-label', config.label);
container.dataset.ncFilterContainer = '1';
const searchInput = toElement(config.searchInput);
normalizeSearchInputAria(searchInput, config.searchLabel || config.label);
let standardControlsResult = null;
if (config.standardControls === true) {
standardControlsResult = applyStandardControls({
label: config.label,
searchLabel: config.searchLabel,
searchInput: searchInput || config.searchInput,
searchPlaceholder: config.searchPlaceholder,
forceSearchPlaceholder: config.forceSearchPlaceholder,
perPageSelect: config.perPageSelect,
perPageOptions: config.perPageOptions,
perPageValue: config.perPageValue,
sortSelect: config.sortSelect,
sortOptions: config.sortOptions,
sortValue: config.sortValue,
});
}
const resolvedSearchInput = standardControlsResult?.searchInput || searchInput;
if (config.hideTitle !== false) {
hidePrimaryTitle(container);
}
if (config.filtersDropdown !== false) {
ensureFiltersDropdown({
container,
searchInput: resolvedSearchInput,
filterControls: config.filterControls,
includeStandardControls: config.includeStandardControlsInDropdown === true,
perPageSelect:
standardControlsResult?.perPageSelect || config.perPageSelect || config.perPageInput,
sortSelect: standardControlsResult?.sortSelect || config.sortSelect || config.sortInput,
filterDropdownPlacement: config.filterDropdownPlacement,
filterDropdownLabel: config.filterDropdownLabel,
});
}
return container;
}
window.NCSearchFilterContainer = {
apply: applyFilterContainer,
applyStandardControls,
getDefaultPerPageOptions: () => normalizePerPageOptions(DEFAULT_PER_PAGE_VALUES),
getDefaultSortOptions: () => cloneOptions(DEFAULT_SORT_OPTIONS),
};
})();
@@ -1,28 +0,0 @@
(() => {
function normalizeBlocks(blocks) {
if (Array.isArray(blocks)) return blocks;
if (blocks == null) return [];
return [blocks];
}
function renderLayout(config = {}) {
const previewHtml = String(config.previewHtml || '');
const contentBlocks = normalizeBlocks(config.contentBlocks)
.map(block => String(block || '').trim())
.filter(Boolean)
.join('');
const rootClass = String(config.rootClass || 'flex flex-col gap-3 md:flex-row md:gap-3').trim();
const contentClass = String(config.contentClass || 'flex-1 min-w-0 space-y-5').trim();
return `<div class="${rootClass}">
${previewHtml}
<div class="${contentClass}">
${contentBlocks}
</div>
</div>`;
}
window.NCMediaDetailView = {
renderLayout,
};
})();
@@ -1,481 +0,0 @@
// NCMediaPreview - shared fullscreen image / video preview component.
// Served at /shared/js/media/media-preview.js by applySharedBase.
//
// Two modes:
// attach(opts) -> attach to existing overlay + frame elements in the DOM.
// Returns a controller with { open, close, prev, next,
// setItems, isOpen, currentIndex, preloader, destroy }.
//
// lightbox(opts) -> dynamically create a minimal single-image lightbox.
// Returns { open(url, alt), close, destroy }.
//
// attach() opts:
// overlayEl {Element} required - fixed fullscreen overlay div
// frameEl {Element} required - inner div where img/video is mounted
// preloadRadius {number} default 2 - neighbors to eagerly preload
// loop {boolean} default false - wrap-around navigation
// renderItem {function(frameEl, item)} - custom render; used instead of
// default img/video creation when provided
// onClose {function()}
// onNavigate {function(idx, item)}
//
// Items shape for setItems(): [{ url, thumbnail?, name?, mediaType? }]
// mediaType 'video' forces video element; otherwise URL extension is used.
//
// lightbox() opts:
// id {string} default 'ncLightboxOverlay'
// zIndex {string} default 'z-50'
// imgClass {string} default: centered object-contain image style
(function (global) {
'use strict';
var VIDEO_EXT = /\.(mp4|webm|mov|avi|mkv)$/i;
var AUDIO_EXT = /\.(mp3|flac|wav|ogg|aac|m4a|opus|wma|aiff)$/i;
/** Returns true when the URL path has a recognised video extension. */
function isVideo(url) {
return VIDEO_EXT.test(String(url || '').split('?')[0]);
}
/** Returns true when the URL path has a recognised audio extension. */
function isAudio(url) {
return AUDIO_EXT.test(String(url || '').split('?')[0]);
}
/** Build a simple image-preload cache. */
function makePreloader() {
var cache = new Map();
return {
load: function (url) {
if (!url) return Promise.reject(new Error('no url'));
if (cache.has(url)) return cache.get(url);
var p = new Promise(function (res, rej) {
var im = new Image();
im.onload = function () {
res(im);
};
im.onerror = rej;
im.src = url;
});
cache.set(url, p);
return p;
},
clear: function () {
cache.clear();
},
};
}
/** Shared CSS for the media element inside the frame. */
var MEDIA_CLS =
'max-h-full max-w-full rounded-md bg-black object-contain shadow-[var(--shadow-2xl,0_10px_40px_rgba(0,0,0,.6))]';
/**
* Keep fullscreen media inside comfortable insets so content is not clipped
* by overlay edges or covered by overlay chrome.
*/
function applySafeMediaLayout(node) {
if (!node) return;
try {
node.style.width = 'auto';
node.style.height = 'auto';
node.style.maxWidth = 'calc(100% - 1.5rem)';
node.style.maxHeight = 'calc(100% - 1.5rem)';
node.style.objectFit = 'contain';
node.style.objectPosition = 'center';
// eslint-disable-next-line no-empty
} catch {}
}
/**
* Toggle overlay visibility using both class-based and attribute-based
* strategies so it works with all existing overlay markup in the codebase.
*/
function setVisible(overlayEl, visible) {
if (!overlayEl) return;
if (visible) {
overlayEl.classList.remove('hidden');
overlayEl.classList.add('flex', 'is-active');
overlayEl.style.removeProperty('display');
overlayEl.hidden = false;
overlayEl.setAttribute('aria-hidden', 'false');
try {
document.body.classList.add('overflow-hidden');
document.documentElement.classList.add('overflow-hidden');
// eslint-disable-next-line no-empty
} catch {}
} else {
overlayEl.classList.remove('flex', 'is-active');
overlayEl.classList.add('hidden');
overlayEl.style.setProperty('display', 'none', 'important');
overlayEl.hidden = true;
overlayEl.setAttribute('aria-hidden', 'true');
try {
document.body.classList.remove('overflow-hidden');
document.documentElement.classList.remove('overflow-hidden');
// eslint-disable-next-line no-empty
} catch {}
}
}
// -- attach() ----------------------------------------------------------------
/**
* Attach a media preview controller to existing overlay + frame DOM elements.
*
* The component automatically wires:
* • [data-overlay-prev] -> prev()
* • [data-overlay-next] -> next()
* • [aria-label="Close"] -> close() (searched inside overlayEl)
* • Backdrop click (click directly on overlayEl) -> close()
* • Keyboard: Escape -> close, ArrowLeft -> prev, ArrowRight -> next
*
* @param {object} opts
* @returns controller
*/
function attach(opts) {
opts = opts || {};
var overlayEl = opts.overlayEl;
var frameEl = opts.frameEl;
if (!overlayEl || !frameEl) {
throw new Error('NCMediaPreview.attach: overlayEl and frameEl are required');
}
var radius = Math.max(0, Number(opts.preloadRadius) || 2);
var loop = !!opts.loop;
var items = []; // [{ url, thumbnail, name, mediaType }]
var _idx = -1;
var _open = false;
var preloader = makePreloader();
// Auto-discover standard buttons within the overlay
var closeBtn = overlayEl.querySelector('[aria-label="Close"]');
var prevBtn = overlayEl.querySelector('[data-overlay-prev]');
var nextBtn = overlayEl.querySelector('[data-overlay-next]');
var hasInFrameClose = !!(closeBtn && frameEl.contains(closeBtn));
// Reserve safe space inside the frame so media is never hidden under
// in-frame close controls and never touches overlay boundaries.
try {
frameEl.style.boxSizing = 'border-box';
frameEl.style.padding = hasInFrameClose ? '3.25rem 0.75rem 0.75rem 0.75rem' : '0.75rem';
// eslint-disable-next-line no-empty
} catch {}
function applyFramePaddingForItem(item) {
try {
if (!hasInFrameClose) {
frameEl.style.padding = '0.75rem';
return;
}
var kind = String((item && item.mediaType) || '').toLowerCase();
var url = String((item && item.url) || '');
var isImageLike = kind !== 'video' && kind !== 'audio' && !isVideo(url) && !isAudio(url);
// For image previews, keep vertical insets symmetric.
frameEl.style.padding = isImageLike
? '3.25rem 0.75rem 3.25rem 0.75rem'
: '3.25rem 0.75rem 0.75rem 0.75rem';
// eslint-disable-next-line no-empty
} catch {}
}
// Ensure overlays always start hidden after attach in case responsive
// display utilities override class-based hidden rules on first paint.
setVisible(overlayEl, false);
function updateButtons() {
if (prevBtn) prevBtn.disabled = loop ? false : _idx <= 0;
if (nextBtn) nextBtn.disabled = loop ? false : _idx >= items.length - 1;
}
/** Pause + remove any img/video/audio children from the frame. */
function clearFrame() {
Array.from(frameEl.querySelectorAll('video,audio')).forEach(function (v) {
try {
v.pause();
// eslint-disable-next-line no-empty
} catch {}
});
Array.from(frameEl.querySelectorAll('img,video,audio')).forEach(function (n) {
if (n.parentNode === frameEl) frameEl.removeChild(n);
});
}
/** Mount the media element for the given item. */
function renderFrame(item) {
clearFrame();
if (!item) return;
applyFramePaddingForItem(item);
// Delegate to caller-supplied renderer if provided
if (opts.renderItem) {
try {
opts.renderItem(frameEl, item);
// eslint-disable-next-line no-empty
} catch {}
return;
}
if (isVideo(item.url) || item.mediaType === 'video') {
var v = document.createElement('video');
v.className = MEDIA_CLS;
v.src = item.url;
v.controls = true;
v.autoplay = true;
v.loop = true;
v.muted = false;
v.playsInline = true;
applySafeMediaLayout(v);
frameEl.appendChild(v);
} else if (isAudio(item.url) || item.mediaType === 'audio') {
var a = document.createElement('audio');
a.src = item.url;
a.controls = true;
a.autoplay = true;
a.style.minWidth = '320px';
a.style.maxWidth = '90vw';
frameEl.appendChild(a);
} else {
var img = document.createElement('img');
img.className = MEDIA_CLS;
img.alt = item.name || 'Media preview';
applySafeMediaLayout(img);
frameEl.appendChild(img);
// Show thumbnail immediately, swap to full-res when ready
if (item.thumbnail) img.src = item.thumbnail;
var capturedIdx = _idx;
preloader
.load(item.url)
.then(function () {
img.src = item.url;
})
.catch(function () {
img.src = item.url;
})
.finally(function () {
// Preload neighbors after current is resolved
for (var d = 1; d <= radius; d++) {
var li = capturedIdx - d,
ri = capturedIdx + d;
if (li >= 0 && items[li]) preloader.load(items[li].url).catch(function () {});
if (ri < items.length && items[ri])
preloader.load(items[ri].url).catch(function () {});
}
});
}
}
function open(i) {
if (!items.length) return;
_idx = Math.max(0, Math.min(i, items.length - 1));
_open = true;
renderFrame(items[_idx]);
setVisible(overlayEl, true);
updateButtons();
if (opts.onNavigate)
try {
opts.onNavigate(_idx, items[_idx]);
// eslint-disable-next-line no-empty
} catch {}
}
function close() {
_open = false;
clearFrame();
_idx = -1;
setVisible(overlayEl, false);
if (opts.onClose)
try {
opts.onClose();
// eslint-disable-next-line no-empty
} catch {}
}
function prev() {
if (!_open || !items.length) return;
var n = loop ? (_idx - 1 + items.length) % items.length : _idx - 1;
if (!loop && n < 0) return;
_idx = n;
renderFrame(items[_idx]);
updateButtons();
if (opts.onNavigate)
try {
opts.onNavigate(_idx, items[_idx]);
// eslint-disable-next-line no-empty
} catch {}
}
function next() {
if (!_open || !items.length) return;
var n = loop ? (_idx + 1) % items.length : _idx + 1;
if (!loop && n >= items.length) return;
_idx = n;
renderFrame(items[_idx]);
updateButtons();
if (opts.onNavigate)
try {
opts.onNavigate(_idx, items[_idx]);
// eslint-disable-next-line no-empty
} catch {}
}
/**
* Replace the item list. Clears the preload cache.
* Must be called with the full up-to-date list before open().
*/
function setItems(newItems) {
items = Array.isArray(newItems) ? newItems : [];
preloader.clear();
}
// Wire built-in buttons
if (closeBtn) closeBtn.addEventListener('click', close);
if (prevBtn) prevBtn.addEventListener('click', prev);
if (nextBtn) nextBtn.addEventListener('click', next);
// Backdrop click - close when clicking directly on the overlay backdrop
overlayEl.addEventListener('click', function (e) {
if (e.target === overlayEl) close();
});
// Keyboard - Escape / arrows
function onKey(e) {
if (!_open) return;
if (e.key === 'Escape') close();
else if (e.key === 'ArrowLeft') prev();
else if (e.key === 'ArrowRight') next();
}
window.addEventListener('keydown', onKey);
var ctrl = {
open: open,
close: close,
prev: prev,
next: next,
setItems: setItems,
isOpen: function () {
return _open;
},
preloader: preloader,
destroy: function () {
window.removeEventListener('keydown', onKey);
},
};
Object.defineProperty(ctrl, 'currentIndex', {
get: function () {
return _idx;
},
});
return ctrl;
}
// -- lightbox() --------------------------------------------------------------
/**
* Build a minimal single-item image lightbox that creates its own DOM.
* Useful for cases where no overlay markup exists (e.g. MediaModerator).
*
* @param {object} [opts] { id, zIndex, imgClass }
* @returns {{ open(url, alt?), close, destroy }}
*/
function lightbox(opts) {
opts = opts || {};
var id = opts.id || 'ncLightboxOverlay';
var zIndex = opts.zIndex || 'z-50';
var imgCls =
opts.imgClass ||
'block max-h-full max-w-full rounded-lg object-contain shadow-[0_8px_24px_rgba(0,0,0,0.5)]';
var el = null,
img = null;
function ensure() {
if (el) return;
el = document.createElement('div');
el.id = id;
el.setAttribute('role', 'dialog');
el.setAttribute('aria-modal', 'true');
el.className = [
'fixed inset-0',
zIndex,
'hidden items-center justify-center bg-black/85 p-4',
].join(' ');
var inner = document.createElement('div');
inner.className = 'relative flex h-full w-full items-center justify-center';
var closeBtn = document.createElement('button');
closeBtn.type = 'button';
closeBtn.setAttribute('aria-label', 'Close');
closeBtn.className =
'absolute right-4 top-4 z-10 flex h-9 w-9 cursor-pointer items-center justify-center rounded-full border border-slate-700 bg-black text-white';
closeBtn.innerHTML =
'<svg class="h-4 w-4" fill="none" viewBox="0 0 24 24" stroke="currentColor" stroke-width="2.5" aria-hidden="true"><path stroke-linecap="round" stroke-linejoin="round" d="M6 18L18 6M6 6l12 12"/></svg>';
closeBtn.addEventListener('click', close);
img = document.createElement('img');
img.alt = 'Preview';
img.className = imgCls;
inner.appendChild(closeBtn);
inner.appendChild(img);
el.appendChild(inner);
document.body.appendChild(el);
el.addEventListener('click', function (e) {
if (e.target === el) close();
});
document.addEventListener('keydown', function (e) {
if (e.key === 'Escape' && !el.classList.contains('hidden')) close();
});
}
function open(url, alt) {
ensure();
img.src = url || '';
if (alt) img.alt = alt;
applySafeMediaLayout(img);
try {
// Use equal viewport insets so image top and bottom spacing match.
img.style.maxWidth = 'calc(100vw - 4rem)';
img.style.maxHeight = 'calc(100vh - 4rem)';
img.style.margin = '0 auto';
// eslint-disable-next-line no-empty
} catch {}
el.classList.remove('hidden');
el.classList.add('flex');
try {
document.body.classList.add('overflow-hidden');
// eslint-disable-next-line no-empty
} catch {}
}
function close() {
if (!el) return;
el.classList.add('hidden');
el.classList.remove('flex');
img.src = '';
try {
document.body.classList.remove('overflow-hidden');
// eslint-disable-next-line no-empty
} catch {}
}
function destroy() {
close();
if (el) {
el.remove();
el = null;
img = null;
}
}
return { open: open, close: close, destroy: destroy };
}
global.NCMediaPreview = { attach: attach, lightbox: lightbox, isVideo: isVideo };
})(window);
@@ -1,287 +0,0 @@
/**
* NCThumbnail - Shared thumbnail loading utility.
*
* Provides consistent image element creation, error handling,
* path encoding, and deferred loading across all services.
*
* Available at /shared/js/media/thumbnails.js via mountSharedStatic.
*/
window.NCThumbnail = (() => {
/* ------------------------------------------------------------------ */
/* Utility */
/* ------------------------------------------------------------------ */
/**
* Encode each segment of a path individually for safe URL embedding.
* @param {string} p - e.g. 'folder/sub dir/file.jpg'
* @returns {string} 'folder/sub%20dir/file.jpg'
*/
function encodePathSegments(p) {
return String(p || '')
.split('/')
.map(encodeURIComponent)
.join('/');
}
/* ------------------------------------------------------------------ */
/* Image Element Creation */
/* ------------------------------------------------------------------ */
/**
* Create a thumbnail `<img>` with lazy loading and configurable error handling.
*
* @param {Object} opts
* @param {string} opts.src - Image source URL
* @param {string} [opts.alt=''] - Alt text
* @param {string} [opts.className=''] - CSS class(es)
* @param {boolean} [opts.lazy=true] - Set loading="lazy"
* @param {boolean} [opts.asyncDecode=true] - Set decoding="async"
* @param {string} [opts.fallbackSrc] - Swap to this URL on error
* @param {string} [opts.fallbackIcon] - FA icon class for placeholder (e.g. 'fas fa-image')
* @param {string} [opts.fallbackText] - Text shown inside placeholder
* @param {string} [opts.fallbackClass] - Extra CSS class(es) on placeholder div
* @param {Function}[opts.onError] - Custom onerror (overrides other fallbacks)
* @param {Object} [opts.dataset={}] - data-* attributes
* @returns {HTMLImageElement}
*/
function createImg(opts) {
const img = document.createElement('img');
if (opts.className) img.className = opts.className;
img.alt = opts.alt || '';
if (opts.lazy !== false) img.loading = 'lazy';
if (opts.asyncDecode !== false) img.decoding = 'async';
if (opts.src) img.src = opts.src;
if (opts.dataset) {
for (const [k, v] of Object.entries(opts.dataset)) img.dataset[k] = v;
}
if (typeof opts.onError === 'function') {
img.onerror = opts.onError;
} else if (opts.fallbackSrc) {
img.onerror = function () {
this.onerror = null;
this.src = opts.fallbackSrc;
};
} else if (opts.fallbackIcon || opts.fallbackText) {
img.onerror = function () {
this.onerror = null;
const parent = this.parentElement;
if (!parent) {
this.style.display = 'none';
return;
}
this.remove();
const fb = document.createElement('div');
fb.className =
opts.fallbackClass || 'flex flex-col items-center justify-center gap-1.5 text-slate-400';
if (opts.fallbackIcon) {
const i = document.createElement('i');
i.className = opts.fallbackIcon;
i.setAttribute('aria-hidden', 'true');
fb.appendChild(i);
}
if (opts.fallbackText) {
const s = document.createElement('span');
s.className = 'text-xs';
s.textContent = opts.fallbackText;
fb.appendChild(s);
}
parent.appendChild(fb);
};
}
return img;
}
/**
* Create an `<img>` paired with a hidden fallback sibling.
* On error the image hides and the fallback shows - preserves layout.
*
* @param {Object} opts
* @param {string} opts.src - Image source URL
* @param {string} [opts.alt=''] - Alt text
* @param {string} [opts.className=''] - CSS class(es) for the image
* @param {string} [opts.fallbackHtml=''] - Inner HTML for the fallback <span>
* @param {string} [opts.fallbackClassName=''] - Extra class(es) on fallback
* @param {Object} [opts.dataset={}] - data-* attributes on the image
* @returns {{ img: HTMLImageElement, fallback: HTMLSpanElement }}
*/
function createImgWithFallback(opts) {
const img = document.createElement('img');
if (opts.className) img.className = opts.className;
img.alt = opts.alt || '';
img.loading = 'lazy';
img.decoding = 'async';
if (opts.src) img.src = opts.src;
if (opts.dataset) {
for (const [k, v] of Object.entries(opts.dataset)) img.dataset[k] = v;
}
const fallback = document.createElement('span');
fallback.className = 'hidden' + (opts.fallbackClassName ? ' ' + opts.fallbackClassName : '');
if (opts.fallbackHtml) fallback.innerHTML = opts.fallbackHtml;
img.onerror = function () {
this.onerror = null;
this.classList.add('hidden');
fallback.classList.remove('hidden');
};
return { img, fallback };
}
/* ------------------------------------------------------------------ */
/* Deferred Loading */
/* ------------------------------------------------------------------ */
/**
* Deferred thumbnail loading via IntersectionObserver with a throttled
* concurrent-request queue.
*
* Target images must use `data-src` (not `src`). When intersecting the
* viewport, `data-src` is copied to `src`.
*
* @param {Object} opts
* @param {string} [opts.selector='img[data-src]'] - Query selector
* @param {Element} [opts.root=null] - Scroll container (null = viewport)
* @param {string} [opts.rootMargin='300px'] - Preload margin
* @param {number} [opts.maxConcurrent=4] - Max simultaneous loads
* @param {Function}[opts.onLoad] - Callback per loaded image
* @param {Function}[opts.onError] - Callback per failed image
* @returns {{ destroy: Function, observe: Function }}
*/
function initDeferredLoading(opts = {}) {
const {
selector = 'img[data-src]',
root = null,
rootMargin = '300px',
maxConcurrent = 4,
onLoad,
onError,
} = opts;
const queue = [];
let inFlight = 0;
const pump = () => {
while (inFlight < maxConcurrent && queue.length) {
const img = queue.shift();
if (!img || !img.isConnected) continue;
const src = img.getAttribute('data-src');
if (!src) continue;
img.removeAttribute('data-src');
inFlight++;
const done = () => {
inFlight = Math.max(0, inFlight - 1);
pump();
};
img.addEventListener(
'load',
() => {
if (onLoad) onLoad(img);
done();
},
{ once: true }
);
img.addEventListener(
'error',
() => {
if (onError) onError(img);
done();
},
{ once: true }
);
img.src = src;
}
};
const observer = new IntersectionObserver(
entries => {
for (const e of entries) {
if (!e.isIntersecting) continue;
observer.unobserve(e.target);
queue.push(e.target);
}
pump();
},
{ root, rootMargin, threshold: 0.01 }
);
const elements = document.querySelectorAll(selector);
for (const el of elements) observer.observe(el);
return {
destroy() {
observer.disconnect();
queue.length = 0;
},
observe(el) {
observer.observe(el);
},
};
}
/**
* Attach load / error tracking to existing `<img>` elements, toggling
* an adjacent status-overlay element (e.g. "Loading..." -> hidden on
* success, or "Couldn't load" on error).
*
* @param {Object} opts
* @param {string} [opts.imgSelector='img[data-card-media]']
* @param {string} [opts.statusAttr='data-card-status']
* @param {string} [opts.errorText="Thumbnail couldn\u2019t load"]
* @param {boolean} [opts.skipDeferred=false] - Skip imgs with data-src (handled by initDeferredLoading)
*/
function initStatusTracking(opts = {}) {
const {
imgSelector = 'img[data-card-media]',
statusAttr = 'data-card-status',
errorText = 'Thumbnail couldn\u2019t load',
skipDeferred = false,
} = opts;
const images = document.querySelectorAll(imgSelector);
for (const img of images) {
if (skipDeferred && img.hasAttribute('data-src')) continue;
const card = img.closest('[data-card]') || img.parentElement;
const statusEl = card?.querySelector(`[${statusAttr}]`);
img.addEventListener(
'load',
() => {
if (statusEl) statusEl.classList.add('hidden');
},
{ once: true }
);
img.addEventListener(
'error',
() => {
if (statusEl) {
statusEl.textContent = errorText;
statusEl.classList.remove('hidden');
}
},
{ once: true }
);
// Handle already-cached images.
try {
if (img.complete && img.naturalWidth > 0 && statusEl) statusEl.classList.add('hidden');
} catch {
/* ignore */
}
}
}
/* ------------------------------------------------------------------ */
return {
encodePathSegments,
createImg,
createImgWithFallback,
initDeferredLoading,
initStatusTracking,
};
})();
@@ -1,15 +0,0 @@
/**
* Shared Pagination Component (Bottom)
* The core renderer lives in pagination-top.js as window.NCPagination.
*/
(() => {
window.NCPaginationBottom = {
render(container, state, onPageChange) {
if (!window.NCPagination || typeof window.NCPagination.render !== 'function') {
console.error('NCPagination core is not available. Load pagination-top.js first.');
return;
}
window.NCPagination.render(container, state, onPageChange, 'bottom');
},
};
})();
@@ -1,178 +0,0 @@
/**
* Shared Pagination Core
* Exposes:
* - window.NCPagination.render(container, state, onPageChange, variant)
* - window.NCPaginationTop.render(container, state, onPageChange)
* - window.NCPaginationBottom.render(container, state, onPageChange)
* onPageChange receives (page, pageSize), where pageSize is one of 12, 24, 48, or 96.
*/
(() => {
if (window.NCPagination && typeof window.NCPagination.render === 'function') {
window.NCPaginationTop = {
render(container, state, onPageChange) {
window.NCPagination.render(container, state, onPageChange, 'top');
},
};
window.NCPaginationBottom = {
render(container, state, onPageChange) {
window.NCPagination.render(container, state, onPageChange, 'bottom');
},
};
return;
}
function fmtNum(n) {
return String(Number(n) || 0).replace(/\B(?=(\d{3})+(?!\d))/g, ',');
}
const PAGE_SIZE_OPTIONS = [12, 24, 48, 96];
const DEFAULT_PAGE_SIZE = 24;
const icons = {
first:
'<svg class="h-4 w-4" fill="none" viewBox="0 0 24 24" stroke="currentColor" stroke-width="2"><path stroke-linecap="round" stroke-linejoin="round" d="M11 19l-7-7 7-7m8 14l-7-7 7-7" /></svg>',
prev: '<svg class="h-4 w-4" fill="none" viewBox="0 0 24 24" stroke="currentColor" stroke-width="2"><path stroke-linecap="round" stroke-linejoin="round" d="M15 19l-7-7 7-7" /></svg>',
next: '<svg class="h-4 w-4" fill="none" viewBox="0 0 24 24" stroke="currentColor" stroke-width="2"><path stroke-linecap="round" stroke-linejoin="round" d="M9 5l7 7-7 7" /></svg>',
last: '<svg class="h-4 w-4" fill="none" viewBox="0 0 24 24" stroke="currentColor" stroke-width="2"><path stroke-linecap="round" stroke-linejoin="round" d="M13 5l7 7-7 7M5 5l7 7-7 7" /></svg>',
};
function render(container, state = {}, onPageChange, variant = 'top') {
if (!container) return;
const page = Math.max(1, Number(state.page) || 1);
const pages = Math.max(1, Number(state.pages) || 1);
const total = Math.max(0, Number(state.total) || 0);
const requestedPageSize = Number(state.pageSize);
const pageSize = PAGE_SIZE_OPTIONS.includes(requestedPageSize)
? requestedPageSize
: DEFAULT_PAGE_SIZE;
const visible = pages > 1 || (state.total !== undefined && total > 0);
container.hidden = !visible;
container.style.display = visible ? '' : 'none';
container.classList.remove('hidden');
container.classList.add('nc-pagination-container');
container.classList.remove('nc-pagination-top', 'nc-pagination-bottom');
container.classList.add(variant === 'bottom' ? 'nc-pagination-bottom' : 'nc-pagination-top');
if (!visible) {
container.innerHTML = '';
return;
}
container.innerHTML = '';
const meta = document.createElement('div');
meta.className = 'nc-pagination-meta';
const infoSpan = document.createElement('span');
infoSpan.className = 'nc-pagination-info';
if (state.infoText !== undefined) {
infoSpan.textContent = state.infoText;
} else {
infoSpan.textContent = `Page ${fmtNum(page)} of ${fmtNum(pages)} (${fmtNum(total)} total)`;
}
const pageSizeLabel = document.createElement('label');
pageSizeLabel.className = 'nc-pagination-page-size-label';
pageSizeLabel.textContent = 'Entries per page';
const pageSizeSelect = document.createElement('select');
pageSizeSelect.className = 'nc-pagination-page-size';
pageSizeSelect.setAttribute('aria-label', 'Entries per page');
PAGE_SIZE_OPTIONS.forEach(size => {
const option = document.createElement('option');
option.value = String(size);
option.textContent = String(size);
option.selected = size === pageSize;
pageSizeSelect.appendChild(option);
});
pageSizeSelect.addEventListener('change', () => {
if (typeof onPageChange === 'function') onPageChange(1, Number(pageSizeSelect.value));
});
pageSizeLabel.appendChild(pageSizeSelect);
meta.appendChild(infoSpan);
meta.appendChild(pageSizeLabel);
const centerWrap = document.createElement('div');
centerWrap.className = 'nc-pagination-center';
const centerSlot = document.createElement('div');
centerSlot.className = 'nc-pagination-center-slot';
centerSlot.dataset.ncPaginationCenterSlot = '1';
centerWrap.appendChild(centerSlot);
const btnContainer = document.createElement('div');
btnContainer.className = 'nc-pagination-btns';
const buttonClass = 'nc-pagination-btn';
const activeClass = 'nc-pagination-btn nc-pagination-btn-active';
const addButton = (labelHtml, targetPage, isActive, ariaLabel) => {
const btn = document.createElement('button');
btn.type = 'button';
btn.innerHTML = labelHtml;
btn.className = isActive ? activeClass : buttonClass;
if (ariaLabel) btn.setAttribute('aria-label', ariaLabel);
if (isActive) btn.setAttribute('aria-current', 'page');
const canGo = !isActive && targetPage >= 1 && targetPage <= pages && targetPage !== page;
if (canGo) {
btn.addEventListener('click', () => {
if (typeof onPageChange === 'function') onPageChange(targetPage, pageSize);
});
} else if (!isActive) {
btn.disabled = true;
}
btnContainer.appendChild(btn);
};
addButton(icons.first, 1, false, 'First page');
addButton(icons.prev, page - 1, false, 'Previous page');
let start = Math.max(1, page - 2);
let end = start + 4;
if (end > pages) {
end = Math.max(1, pages);
start = Math.max(1, end - 4);
}
const pageButtonCount = Math.min(5, pages);
for (let i = 0; i < pageButtonCount; i += 1) {
const targetPage = start + i;
addButton(String(targetPage), targetPage, targetPage === page, `Page ${targetPage}`);
}
addButton(icons.next, page + 1, false, 'Next page');
addButton(icons.last, pages, false, 'Last page');
container.appendChild(meta);
container.appendChild(centerWrap);
container.appendChild(btnContainer);
container.dispatchEvent(
new CustomEvent('nc:pagination-rendered', {
bubbles: true,
detail: {
variant,
page,
pages,
total,
pageSize,
},
})
);
}
window.NCPagination = { render };
window.NCPaginationTop = {
render(container, state, onPageChange) {
render(container, state, onPageChange, 'top');
},
};
window.NCPaginationBottom = {
render(container, state, onPageChange) {
render(container, state, onPageChange, 'bottom');
},
};
})();
@@ -1,3 +0,0 @@
(() => {
window.location.replace('/');
})();
@@ -1,15 +0,0 @@
(() => {
const initThemeToggle = () => {
if (window.NCThemeToggle && typeof window.NCThemeToggle.init === 'function') {
window.NCThemeToggle.init();
}
};
if (window.NCThemeToggle) {
initThemeToggle();
return;
}
document.addEventListener('DOMContentLoaded', initThemeToggle, { once: true });
document.addEventListener('nc:componentsLoaded', initThemeToggle);
})();
@@ -1,106 +0,0 @@
(() => {
if (window.NCThemeToggle) return;
const storageKey = 'app-theme-preference';
const root = document.documentElement;
const boundButtons = new WeakSet();
function safeStorageGet(key) {
try {
return localStorage.getItem(key);
} catch {
return null;
}
}
function safeStorageSet(key, value) {
try {
localStorage.setItem(key, value);
return true;
} catch {
return false;
}
}
function getSystemTheme() {
if (typeof window.matchMedia === 'function') {
return window.matchMedia('(prefers-color-scheme: light)').matches ? 'light' : 'dark';
}
return 'dark';
}
function getCurrentTheme() {
const current = root.getAttribute('data-theme');
if (current === 'light' || current === 'dark') return current;
return getSystemTheme();
}
function updateToggleButton(button, theme) {
if (!button) return;
button.textContent = theme === 'dark' ? '🌙' : '☀️';
}
function refreshAllToggleButtons(theme) {
document.querySelectorAll('#themeToggleBtn, [data-theme-toggle]').forEach(button => {
updateToggleButton(button, theme);
});
}
function applyTheme(theme) {
if (theme !== 'light' && theme !== 'dark') return;
root.setAttribute('data-theme', theme);
refreshAllToggleButtons(theme);
}
function toggleTheme() {
const next = getCurrentTheme() === 'dark' ? 'light' : 'dark';
safeStorageSet(storageKey, next);
applyTheme(next);
return next;
}
function bindToggleButton(button) {
if (!button || boundButtons.has(button)) return;
boundButtons.add(button);
button.addEventListener('click', toggleTheme);
updateToggleButton(button, getCurrentTheme());
}
function init(options = {}) {
const selector = options.selector || '#themeToggleBtn, [data-theme-toggle]';
const stored = safeStorageGet(storageKey);
applyTheme(stored || getCurrentTheme());
document.querySelectorAll(selector).forEach(bindToggleButton);
}
window.NCThemeToggle = {
applyTheme,
init,
storageKey,
toggleTheme,
};
document.addEventListener('DOMContentLoaded', () => init(), { once: true });
document.addEventListener('nc:componentsLoaded', () => init());
if (typeof window.matchMedia === 'function') {
const mqDark = window.matchMedia('(prefers-color-scheme: dark)');
const onSystemThemeChange = event => {
if (!safeStorageGet(storageKey)) {
applyTheme(event.matches ? 'dark' : 'light');
}
};
if (typeof mqDark.addEventListener === 'function') {
mqDark.addEventListener('change', onSystemThemeChange);
} else if (typeof mqDark.addListener === 'function') {
mqDark.addListener(onSystemThemeChange);
}
}
window.addEventListener('storage', event => {
if (event.key !== storageKey) return;
if (event.newValue === 'light' || event.newValue === 'dark') {
applyTheme(event.newValue);
}
});
})();
@@ -1,184 +0,0 @@
// Shared confirm dialog utility — matches the dark design language of the monorepo.
// Usage: const ok = await NCConfirm.show({ title, message, confirmLabel, cancelLabel, danger });
// Returns a Promise<boolean>: true = confirmed, false = cancelled.
(function (global) {
if (global.NCConfirm) return;
const DIALOG_ID = 'nc-confirm-dialog';
function ensureDialog() {
let dialog = document.getElementById(DIALOG_ID);
if (dialog) return dialog;
dialog = document.createElement('div');
dialog.id = DIALOG_ID;
dialog.setAttribute('role', 'dialog');
dialog.setAttribute('aria-modal', 'true');
dialog.setAttribute('hidden', '');
dialog.style.display = 'none';
// Backdrop + centering
dialog.className = 'fixed inset-0 z-[10100] flex items-center justify-center p-4';
dialog.style.background = 'rgba(0,0,0,0.65)';
dialog.style.backdropFilter = 'blur(2px)';
dialog.innerHTML = `
<div
id="nc-confirm-panel"
class="w-full max-w-sm rounded-lg border border-slate-700 bg-slate-900 p-4 shadow-2xl"
role="document"
>
<h2
id="nc-confirm-title"
class="mb-2 text-base font-semibold text-white"
></h2>
<p
id="nc-confirm-message"
class="mb-4 text-sm leading-relaxed text-slate-300"
></p>
<div class="flex justify-end gap-3">
<button
id="nc-confirm-cancel"
type="button"
class="inline-flex items-center rounded-lg border border-slate-600 px-4 py-2 text-sm font-medium text-slate-300 transition hover:bg-slate-800 focus:outline-none focus:ring-2 focus:ring-blue-300/20"
></button>
<button
id="nc-confirm-ok"
type="button"
class="inline-flex items-center rounded-lg px-4 py-2 text-sm font-medium text-white transition focus:outline-none focus:ring-2 focus:ring-offset-1 focus:ring-offset-slate-900"
></button>
</div>
</div>
`;
document.body.appendChild(dialog);
return dialog;
}
let _resolve = null;
let _lastActive = null;
function focusables(dialog) {
return [
...dialog.querySelectorAll(
'button, [href], input, select, textarea, [tabindex]:not([tabindex="-1"])'
),
].filter(el => !el.disabled && el.offsetParent !== null);
}
function onKeyDown(e) {
const dialog = document.getElementById(DIALOG_ID);
if (!dialog || dialog.style.display === 'none') return;
if (e.key === 'Escape') {
e.preventDefault();
close(false);
return;
}
if (e.key === 'Tab') {
const els = focusables(dialog);
if (!els.length) return;
const first = els[0];
const last = els[els.length - 1];
if (e.shiftKey && document.activeElement === first) {
e.preventDefault();
last.focus();
} else if (!e.shiftKey && document.activeElement === last) {
e.preventDefault();
first.focus();
}
}
}
function close(result) {
const dialog = document.getElementById(DIALOG_ID);
if (dialog) {
dialog.style.display = 'none';
}
document.removeEventListener('keydown', onKeyDown);
if (_lastActive && typeof _lastActive.focus === 'function') {
try {
_lastActive.focus();
} catch {
/* ignore */
}
}
_lastActive = null;
if (_resolve) {
const r = _resolve;
_resolve = null;
r(result);
}
}
function show({
title = 'Confirm',
message = '',
confirmLabel = 'Confirm',
cancelLabel = 'Cancel',
danger = false,
} = {}) {
return new Promise(resolve => {
const dialog = ensureDialog();
document.getElementById('nc-confirm-title').textContent = title;
document.getElementById('nc-confirm-message').textContent = message;
document.getElementById('nc-confirm-cancel').textContent = cancelLabel;
const okBtn = document.getElementById('nc-confirm-ok');
okBtn.textContent = confirmLabel;
// Danger vs primary style for confirm button
if (danger) {
okBtn.className = okBtn.className.replace(/focus:ring-\S+/g, 'focus:ring-red-500/50');
okBtn.style.background = 'var(--color-danger-strong, #ef4444)';
okBtn.onmouseover = () => {
okBtn.style.background = 'var(--color-danger-hover, #dc2626)';
};
okBtn.onmouseout = () => {
okBtn.style.background = 'var(--color-danger-strong, #ef4444)';
};
} else {
okBtn.style.background = 'var(--color-action, #2563eb)';
okBtn.onmouseover = () => {
okBtn.style.background = 'var(--color-action-hover, #1d4ed8)';
};
okBtn.onmouseout = () => {
okBtn.style.background = 'var(--color-action, #2563eb)';
};
// Reset ring class in case it was set to danger previously
const cls = okBtn.className;
if (!cls.includes('focus:ring-blue')) {
okBtn.className = cls.replace(/focus:ring-\S+/g, 'focus:ring-blue-300/50');
}
}
// Wire up resolve
_resolve = resolve;
_lastActive = document.activeElement;
// Re-attach listeners (removes stale ones first)
const cancelBtn = document.getElementById('nc-confirm-cancel');
const freshCancel = cancelBtn.cloneNode(true);
cancelBtn.parentNode.replaceChild(freshCancel, cancelBtn);
const freshOk = okBtn.cloneNode(true);
okBtn.parentNode.replaceChild(freshOk, okBtn);
// Re-query after replacement
document.getElementById('nc-confirm-cancel').addEventListener('click', () => close(false));
document.getElementById('nc-confirm-ok').addEventListener('click', () => close(true));
document.addEventListener('keydown', onKeyDown);
dialog.style.display = '';
// Move focus to confirm button after paint
setTimeout(() => {
const btn = document.getElementById('nc-confirm-ok');
if (btn) btn.focus();
}, 10);
});
}
global.NCConfirm = { show };
})(window);
@@ -1,142 +0,0 @@
// Shared overlay + live region utilities
// Pattern centralization to avoid repetition across admin pages.
// Usage: const ov = createOverlayController({ overlayId:'mediaOverlay', liveId:'mediaLive', showDelay:250 });
// Then ov.runWithOverlay(async ()=> { ...loading work... });
// Provide announce(msg) for polite updates and announceError(msg) for errors (also logs console + optional toast).
(function (global) {
function createOverlayController({
overlayId,
liveId,
showDelay = 250,
toast,
focusSelector,
restoreFocus = true,
escToClose = true,
trapFocus = true,
} = {}) {
const overlay = document.getElementById(overlayId);
const live = document.getElementById(liveId);
let timer;
let lastActive = null;
function moveFocusIn() {
if (!overlay) return;
let target = null;
if (focusSelector) {
target = overlay.querySelector(focusSelector);
}
if (!target) {
// find first focusable
target = overlay.querySelector(
'button, [href], input, select, textarea, [tabindex]:not([tabindex="-1"])'
);
}
if (target && typeof target.focus === 'function') {
try {
target.focus();
} catch {
/* ignore focus error */
}
}
}
function showSoon() {
clearTimeout(timer);
timer = setTimeout(() => {
if (!overlay) return;
if (restoreFocus) {
lastActive = document.activeElement;
}
if (!overlay.getAttribute('role')) overlay.setAttribute('role', 'dialog');
overlay.setAttribute('aria-modal', 'true');
overlay.removeAttribute('hidden');
overlay.classList.add('is-active');
overlay.setAttribute('aria-hidden', 'false');
console.info('[ACTION] overlay_show', overlayId);
// Slight defer to allow rendering
setTimeout(moveFocusIn, 10);
}, showDelay);
}
function hide() {
clearTimeout(timer);
if (!overlay) return;
overlay.classList.remove('is-active');
overlay.setAttribute('aria-hidden', 'true');
overlay.setAttribute('hidden', '');
console.info('[ACTION] overlay_hide', overlayId);
if (restoreFocus && lastActive && typeof lastActive.focus === 'function') {
try {
lastActive.focus();
} catch {
/* ignore */
}
lastActive = null;
}
}
function onKey(e) {
if (!overlay || overlay.hasAttribute('hidden')) return;
if (e.key === 'Escape' && escToClose) {
// Attempt to refocus original trigger immediately after hiding
const trigger = lastActive;
hide();
if (trigger && typeof trigger.focus === 'function') {
try {
trigger.focus();
} catch {
/* ignore */
}
}
return;
}
if (trapFocus && e.key === 'Tab') {
const focusables = [
...overlay.querySelectorAll(
'button, [href], input, select, textarea, [tabindex]:not([tabindex="-1"])'
),
].filter(el => !el.disabled && el.offsetParent !== null);
if (focusables.length) {
const first = focusables[0];
const last = focusables[focusables.length - 1];
if (e.shiftKey && document.activeElement === first) {
e.preventDefault();
last.focus();
} else if (!e.shiftKey && document.activeElement === last) {
e.preventDefault();
first.focus();
}
}
}
}
document.addEventListener('keydown', onKey);
function announce(msg) {
if (live) {
live.textContent = msg;
}
}
function announceError(msg) {
if (live) {
live.textContent = msg;
}
if (toast && toast.error) {
toast.error(msg);
}
console.error('[OVERLAY_ERROR]', msg);
}
async function runWithOverlay(fn) {
showSoon();
try {
const r = await fn();
hide();
return r;
} catch (e) {
hide();
announceError(e.message || 'Load failed');
throw e;
}
}
function destroy() {
document.removeEventListener('keydown', onKey);
}
return { showSoon, hide, announce, announceError, runWithOverlay, destroy };
}
global.NCOverlay = { createOverlayController };
})(window);
@@ -1,133 +0,0 @@
// NCProgressBar - shared horizontal progress bar component
// Served at /shared/js/ui/progress-bar.js by applySharedBase.
//
// The 'progress-shimmer' CSS class (defined in index.css) drives the animated
// gradient fill used during indeterminate/in-progress states.
//
// API:
// const {track, fill} = NCProgressBar.create([opts]) -> builds DOM pair (NOT inserted)
// NCProgressBar.set(fill, pct, [opts]) -> set fill to pct (0-100); opts.shimmer=bool
// NCProgressBar.setShimmer(fill, on) -> add/remove 'progress-shimmer' class
//
// create() opts:
// height : CSS height utility class from index.css (default 'h-2')
// rounded : CSS rounded utility class from index.css (default 'rounded-full')
// trackClass : CSS bg utility class for the track (default 'bg-slate-800')
// fillClass : CSS bg utility class for the fill (default 'bg-[var(--color-action)]')
// shimmer : bool - start with shimmer on (default false)
(function (global) {
'use strict';
/**
* Build a progress-bar track+fill pair without inserting into DOM.
* @param {object} [opts]
* @returns {{ track: HTMLElement, fill: HTMLElement }}
*/
function create(opts) {
opts = opts || {};
var height = opts.height || 'h-2';
var rounded = opts.rounded || 'rounded-full';
var trackCls = opts.trackClass || 'bg-slate-800';
var fillCls = opts.fillClass || 'bg-[var(--color-action)]';
var shimmer = !!opts.shimmer;
var track = document.createElement('div');
track.className = [height, rounded, trackCls, 'overflow-hidden'].join(' ');
var fill = document.createElement('div');
fill.className = ['h-full', rounded, fillCls, 'transition-[width]', 'duration-300'].join(' ');
if (shimmer) fill.classList.add('progress-shimmer');
fill.style.width = '0%';
track.appendChild(fill);
return { track: track, fill: fill };
}
/**
* Toggle the shimmer animation on a fill element.
* @param {Element} fillEl
* @param {boolean} on
*/
function setShimmer(fillEl, on) {
if (!fillEl) return;
if (on) fillEl.classList.add('progress-shimmer');
else fillEl.classList.remove('progress-shimmer');
}
/**
* Set the fill width percentage (clamped 0-100).
* @param {Element} fillEl
* @param {number} pct 0-100
* @param {object} [opts] opts.shimmer - if boolean, also toggle shimmer
*/
function set(fillEl, pct, opts) {
if (!fillEl) return;
var clamped = Math.max(0, Math.min(100, Number(pct) || 0));
fillEl.style.width = clamped + '%';
if (opts && typeof opts.shimmer === 'boolean') setShimmer(fillEl, opts.shimmer);
}
/**
* Renders a highly styled processing progress bar into the specified container.
* Useful for showing download or generation progress with a label.
* @param {HTMLElement} container - DOM element to render into
* @param {object} [opts] - opts.barId, opts.labelId, opts.metaId, opts.statusDotId, opts.statusTextId, opts.statusText
*/
function renderProcessingContainer(container, opts) {
if (!container) return;
opts = opts || {};
var barId = opts.barId || 'processingProgressBar';
var labelId = opts.labelId || 'processingProgressLabel';
var metaId = opts.metaId || '';
var statusDotId = opts.statusDotId || '';
var statusTextId = opts.statusTextId || '';
var statusText = opts.statusText || 'ComfyUI: checking\u2026';
var metaHtml = metaId
? '<div id="' +
metaId +
'" class="mt-2 text-center text-xs text-[var(--color-text-dim)] empty:hidden"></div>'
: '';
var barTrackHtml = `<div class="relative h-5 w-full bg-slate-900 overflow-hidden rounded-md border border-slate-800 shadow-inner">
<div
id="${barId}"
class="h-full w-0 bg-[var(--color-action)] transition-[width] duration-200 ease-in-out"
></div>
<div
id="${labelId}"
class="pointer-events-none absolute inset-0 flex items-center justify-center text-xs font-bold uppercase tracking-widest text-[#fff] [text-shadow:0_1px_2px_rgba(0,0,0,0.8),_0_0_4px_rgba(0,0,0,0.8)] leading-none"
>
Idle
</div>
</div>`;
var statusHtml = statusDotId
? `<div class="flex items-center gap-1.5 text-[var(--font-size-xs)] text-[var(--color-text-dim)]">
<span id="${statusDotId}" class="inline-block h-2 w-2 rounded-full bg-slate-600 flex-shrink-0 transition-colors duration-300" aria-hidden="true"></span>
<span id="${statusTextId}">${statusText}</span>
</div>`
: '';
var innerHtml = statusDotId
? `<div class="flex flex-col gap-2">${barTrackHtml}${statusHtml}</div>`
: barTrackHtml;
container.innerHTML = `
<div class="rounded-lg border border-slate-800 bg-slate-900 overflow-hidden">
<div class="p-4 max-[480px]:p-3">
${innerHtml}
${metaHtml}
</div>
</div>
`;
}
global.NCProgressBar = {
create: create,
set: set,
setShimmer: setShimmer,
renderProcessingContainer: renderProcessingContainer,
};
})(window);
@@ -1,122 +0,0 @@
// NCSpinner - shared circular loading spinner component
// Served at /shared/js/ui/spinner.js by applySharedBase.
//
// API:
// NCSpinner.create([opts]) -> returns wrapper element (not inserted into DOM)
// NCSpinner.show(container, [opts]) -> inserts full-area overlay spinner; returns element
// NCSpinner.hide(el) -> removes element from DOM safely
//
// opts:
// size : 'sm'|'md'|'lg'|'xl' - maps to CSS utility class pairs in index.css (default 'lg')
// color : CSS text-color utility class from index.css (default 'text-slate-400')
// label : accessible label string (default 'Loading...')
// text : visible text string displayed below the spinner (default none)
// id : optional id attribute on the wrapper
// overlay : bool - if true (default), wrapper fills its positioned parent absolutely
(function (global) {
'use strict';
var SIZES = { sm: 'h-8 w-8', md: 'h-10 w-10', lg: 'h-12 w-12', xl: 'h-16 w-16' };
var SVG_NS = 'http://www.w3.org/2000/svg';
function makeSvg(sizeClass, color) {
var svg = document.createElementNS(SVG_NS, 'svg');
svg.setAttribute('class', 'animate-spin ' + sizeClass + ' ' + color);
svg.setAttribute('fill', 'none');
svg.setAttribute('viewBox', '0 0 24 24');
svg.setAttribute('aria-hidden', 'true');
var circle = document.createElementNS(SVG_NS, 'circle');
circle.setAttribute('class', 'opacity-25');
circle.setAttribute('cx', '12');
circle.setAttribute('cy', '12');
circle.setAttribute('r', '10');
circle.setAttribute('stroke', 'currentColor');
circle.setAttribute('stroke-width', '4');
svg.appendChild(circle);
var path = document.createElementNS(SVG_NS, 'path');
path.setAttribute('class', 'opacity-75');
path.setAttribute('fill', 'currentColor');
path.setAttribute('d', 'M4 12a8 8 0 018-8V0C5.373 0 0 5.373 0 12h4z');
svg.appendChild(path);
return svg;
}
/**
* Create a spinner wrapper element without inserting it.
* @param {object} [opts]
* @returns {HTMLElement}
*/
function create(opts) {
opts = opts || {};
var size = opts.size || 'md';
var color = opts.color || 'text-slate-400';
var label = opts.label || 'Loading\u2026';
var text = opts.text || '';
var extraCls = opts.wrapClass || '';
var sizeClass = SIZES[size] || size;
var wrap = document.createElement('div');
var flexDir = text ? 'flex-col gap-3 ' : '';
wrap.className = (
'pointer-events-none flex ' +
flexDir +
'items-center justify-center ' +
extraCls
).trim();
wrap.setAttribute('role', 'status');
wrap.setAttribute('aria-label', label);
wrap.appendChild(makeSvg(sizeClass, color));
if (text) {
var textEl = document.createElement('div');
textEl.className =
'text-xs font-semibold uppercase tracking-[0.5px] text-[var(--color-text-dim)]';
textEl.textContent = text;
wrap.appendChild(textEl);
}
return wrap;
}
/**
* Insert an overlay spinner as a child of `container` (defaults to document.body).
* @param {Element|null} container
* @param {object} [opts]
* @returns {HTMLElement} the inserted element
*/
function show(container, opts) {
opts = opts || {};
var overlay = opts.overlay !== false;
var wrapClass = overlay ? 'absolute inset-0 z-10' : '';
var el = create({
size: opts.size || 'lg',
color: opts.color || 'text-slate-400',
label: opts.label || 'Loading\u2026',
text: opts.text || '',
wrapClass: wrapClass,
});
if (opts.id) el.id = opts.id;
(container || document.body).appendChild(el);
return el;
}
/**
* Remove a spinner element previously returned by show().
* @param {Element|null} el
*/
function hide(el) {
try {
if (el && el.parentNode) el.parentNode.removeChild(el);
// eslint-disable-next-line no-empty
} catch {}
}
global.NCSpinner = { create: create, show: show, hide: hide };
})(window);
@@ -1,73 +0,0 @@
(function () {
if (window.toast) return;
const rootId = 'toast-root';
function ensureRoot() {
let el = document.getElementById(rootId);
if (!el) {
el = document.createElement('div');
el.id = rootId;
el.setAttribute('data-toast-root', '1');
el.className =
'fixed right-3 z-[10050] flex w-[min(340px,calc(100vw-1.5rem))] flex-col gap-2 hidden';
el.style.top = 'calc(var(--bar-height, 56px) + 0.75rem)';
document.body.appendChild(el);
}
return el;
}
function create(type, message, opts = {}) {
const root = ensureRoot();
const ttl = opts.duration ?? 4800;
const title =
opts.title ||
{ info: 'Info', success: 'Success', warn: 'Warning', error: 'Error' }[type] ||
'Notice';
const accent =
{
info: 'var(--color-info)',
success: 'var(--color-success)',
warn: 'var(--color-warning)',
error: 'var(--color-danger)',
}[type] || 'var(--color-accent)';
const el = document.createElement('div');
el.setAttribute('data-toast-item', '1');
el.className =
'relative isolate flex items-start gap-3 overflow-hidden rounded-md border border-[var(--color-border)] border-l-4 bg-[var(--color-surface)] px-4 py-3 text-[var(--font-size-sm)] leading-[1.3] text-[var(--color-text)] shadow-[var(--shadow-lg)]';
el.style.setProperty('--_accent', accent);
el.style.borderLeftColor = 'var(--_accent)';
el.setAttribute('role', 'status');
el.setAttribute('aria-live', 'polite');
el.innerHTML = `<div data-toast-body="1" class="flex-1 text-left"><h4 class="mb-1 text-[var(--font-size-sm)] font-semibold tracking-[0.3px]">${title}</h4><div data-toast-msg="1">${message}</div></div><button data-toast-close="1" class="absolute right-1.5 top-1.5 rounded bg-transparent p-2 text-sm leading-none text-[var(--color-text-dim)] hover:bg-[var(--color-surface-alt)] hover:text-[var(--color-text)]" aria-label="Dismiss">✕</button><div data-toast-progress="1"></div>`;
el.style.setProperty('--toast-ttl', `${ttl}ms`);
const progress = el.querySelector('[data-toast-progress]');
if (progress) {
progress.className =
'absolute bottom-0 left-0 h-[3px] w-full origin-left bg-[var(--_accent)]';
progress.style.animation = 'toast-progress linear forwards';
progress.style.animationDuration = `${ttl}ms`;
}
const closeBtn = el.querySelector('[data-toast-close]');
let closed = false;
function remove() {
if (closed) return;
closed = true;
el.style.animation = 'toast-out .35s forwards';
setTimeout(() => {
el.remove();
if (root.childElementCount === 0) root.classList.add('hidden');
}, 340);
}
closeBtn.addEventListener('click', remove);
if (ttl > 0) {
setTimeout(remove, ttl);
}
root.classList.remove('hidden');
root.appendChild(el);
return { remove };
}
window.toast = {
info: (m, o) => create('info', m, o),
success: (m, o) => create('success', m, o),
warn: (m, o) => create('warn', m, o),
error: (m, o) => create('error', m, o),
};
})();
@@ -1,23 +0,0 @@
(function (global) {
if (global.ClientLogger) return; // singleton
const PREFIX = '[Client]';
const isDebug = () => {
try {
return localStorage.getItem('clientDebug');
} catch {
return false;
}
};
const ts = () => new Date().toISOString();
const fmt = (level, args) => [ts(), PREFIX, level + ':', ...args];
const api = {
log: (...a) => console.log(...fmt('LOG', a)),
info: (...a) => console.info(...fmt('INFO', a)),
warn: (...a) => console.warn(...fmt('WARN', a)),
error: (...a) => console.error(...fmt('ERR', a)),
debug: (...a) => {
if (isDebug()) console.debug(...fmt('DBG', a));
},
};
global.ClientLogger = api;
})(window);
@@ -1,147 +0,0 @@
// Shared debounce utility (ESM)
// Usage: const debounced = debounce(fn, 150, { leading:true, trailing:true });
// debounced.cancel() / debounced.flush()
/**
* Debounce a function so it only executes after `wait` ms have elapsed since the last call.
* Supports immediate (leading) invocation, trailing invocation, and an optional maxWait
* that guarantees the function is invoked no later than the max wait even under continual calls.
*
* Typical usage:
* const d = debounce(expensiveFn, 150, { leading: true, trailing: true, maxWait: 500 });
* element.addEventListener('input', e => d(e.target.value));
*
* Returned debounced function API:
* d.cancel() -> clears any pending invocation and resets state.
* d.flush() -> immediately invokes pending trailing call (if any) and returns its result.
* d.pending() -> boolean indicating if a timer is active.
*
* Option semantics:
* leading (boolean, default false) - invoke on the first call of a burst.
* trailing (boolean, default true) - invoke after burst settles. If both leading & trailing
* are true the function can fire twice per burst (start & end).
* maxWait (number, >= wait) - maximum time allowed before forcing an invoke while calls
* continue. Ensures periodic execution for rapid streams.
*
* Edge details:
* - If leading is true and trailing is false the function fires immediately on first call then
* suppresses further calls until inactivity >= wait.
* - If leading is false and trailing true (default) it behaves like a classic debounce.
* - maxWait only matters when there is a continuous series of calls preventing the trailing
* timer from expiring; once exceeded it forces an invocation and the cycle restarts.
* - cancel() clears all stored arguments; flush() ignores leading semantics and only processes
* a pending trailing invocation.
*
* @template {(...args: any[]) => any} F
* @param {F} fn Function to debounce.
* @param {number} [wait=100] Base wait interval in milliseconds.
* @param {{ leading?: boolean; trailing?: boolean; maxWait?: number }} [options]
* @returns {F & { cancel():void; flush():ReturnType<F>; pending():boolean }}
*/
export function debounce(fn, wait = 100, options = {}) {
if (typeof fn !== 'function') throw new TypeError('Expected function');
let timer = null;
let lastArgs;
let lastThis;
let result;
let lastInvoke = 0;
const leading = options.leading === true;
const trailing = options.trailing !== false; // default true
const maxWait = typeof options.maxWait === 'number' ? Math.max(options.maxWait, wait) : null;
let lastCallTime = 0; // tracks latest call to debounced wrapper
function invoke(now) {
lastInvoke = now;
const args = lastArgs;
const ctx = lastThis;
lastArgs = lastThis = undefined;
result = fn.apply(ctx, args);
return result;
}
function startTimer(pending, ms) {
if (timer) clearTimeout(timer);
timer = setTimeout(pending, ms);
}
function remainingWait(now) {
const sinceLastInvoke = now - lastInvoke;
const sinceLastCall = now - lastCallTime;
const timeWaiting = wait - sinceLastCall;
return maxWait != null ? Math.min(timeWaiting, maxWait - sinceLastInvoke) : timeWaiting;
}
function shouldInvoke(now) {
if (lastArgs === undefined) return false;
const sinceLastCall = now - lastCallTime;
const sinceLastInvoke = now - lastInvoke;
if (sinceLastCall < 0) return true; // clock skew
if (sinceLastCall >= wait) return true;
return maxWait != null && sinceLastInvoke >= maxWait;
}
function trailingEdge(now) {
timer = null;
if (trailing && lastArgs) return invoke(now);
lastArgs = lastThis = undefined;
return result;
}
function timerExpired() {
const now = Date.now();
if (shouldInvoke(now)) return trailingEdge(now);
startTimer(timerExpired, remainingWait(now));
}
function leadingInvoke(now) {
if (leading) {
result = invoke(now);
}
startTimer(timerExpired, wait); // schedule trailing check
return result;
}
function debounced(...args) {
lastCallTime = Date.now();
lastArgs = args;
lastThis = this;
const now = lastCallTime;
const invokeNow = shouldInvoke(now);
if (!timer) {
// First call: optionally invoke leading immediately
return leadingInvoke(now);
}
if (invokeNow) {
if (maxWait != null) {
// Max wait reached or standard wait elapsed with continuous calls
startTimer(timerExpired, wait); // restart timer for trailing sequence
return invoke(now);
}
}
// Reschedule timer to ensure trailing fires after remaining wait
const timeLeft = remainingWait(now);
startTimer(timerExpired, timeLeft);
return result;
}
debounced.cancel = function () {
if (timer) clearTimeout(timer);
timer = null;
lastArgs = lastThis = undefined;
lastCallTime = 0;
};
debounced.flush = function () {
if (!timer) return result;
return trailingEdge(Date.now());
};
debounced.pending = () => !!timer;
return debounced;
}
if (typeof window !== 'undefined') {
window.debounce = debounce;
}
export default debounce;
@@ -1,20 +0,0 @@
/**
* build-theme-css.mjs
*
* index.css is now a static file — no Tailwind build step is needed.
* This script simply syncs MediaShared/public/css/index.css to
* MediaDesktop/public/index.css (the Electron bundle copy).
*/
import fs from 'fs/promises';
import path from 'path';
import { fileURLToPath } from 'url';
const __filename = fileURLToPath(import.meta.url);
const __dirname = path.dirname(__filename);
const repoRoot = path.resolve(__dirname, '..', '..');
const sourcePath = path.join(repoRoot, 'MediaShared', 'public', 'css', 'index.css');
const desktopPath = path.join(repoRoot, 'MediaDesktop', 'public', 'index.css');
await fs.copyFile(sourcePath, desktopPath);
console.log('Synced MediaShared/public/css/index.css → MediaDesktop/public/index.css');
@@ -1,86 +0,0 @@
<script lang="ts">
import type {
UserCreateRequest,
UserDeleteRequest,
UserId,
UserListRequest,
UserRole,
UserUpdateRequest
} from '../types';
import Dialog from './Dialog.svelte';
import UserManagement from './UserManagement.svelte';
let {
currentRole = 'user',
currentUserId,
description = 'Manage accounts and access for this application.',
loginRequired = true,
onCreateUser,
onDeleteUser,
onLoginRequiredChange,
onListUsers,
onUpdateUser,
open = $bindable(false),
title = 'Admin'
}: {
currentRole?: UserRole;
currentUserId?: UserId;
description?: string;
loginRequired?: boolean;
onCreateUser?: UserCreateRequest;
onDeleteUser?: UserDeleteRequest;
onLoginRequiredChange?: (required: boolean) => void | Promise<void>;
onListUsers?: UserListRequest;
onUpdateUser?: UserUpdateRequest;
open?: boolean;
title?: string;
} = $props();
let loginRequiredValue = $state<boolean>(true);
let loginSettingError = $state('');
$effect(() => {
loginRequiredValue = loginRequired;
});
async function updateLoginRequired(required: boolean) {
const previous = loginRequiredValue;
loginRequiredValue = required;
loginSettingError = '';
try {
await onLoginRequiredChange?.(required);
} catch (error) {
loginRequiredValue = previous;
loginSettingError = error instanceof Error ? error.message : 'The setting could not be saved.';
}
}
</script>
<Dialog bind:open {description} {title}>
{#if onLoginRequiredChange}
<div class="sc-field">
<label class="flex items-center gap-3">
<input
class="size-4 accent-primary"
type="checkbox"
checked={loginRequiredValue}
onchange={(event) => updateLoginRequired((event.currentTarget as HTMLInputElement).checked)}
/>
<span>
<span class="block font-medium">Require login to access app</span>
<span class="sc-muted">Admins and superadmins can change this setting.</span>
</span>
</label>
{#if loginSettingError}<p class="sc-error" role="alert">{loginSettingError}</p>{/if}
</div>
{/if}
<UserManagement
currentRole={currentRole}
currentUserId={currentUserId}
onCreate={onCreateUser}
onDelete={onDeleteUser}
onList={onListUsers}
onUpdate={onUpdateUser}
/>
</Dialog>
@@ -16,7 +16,6 @@
headerActions,
navItems = [],
onAbout,
onAdmin,
onLogout,
onNavigate,
onProfile,
@@ -37,7 +36,6 @@
headerActions?: Snippet;
navItems?: NavItem[];
onAbout?: () => void | Promise<void>;
onAdmin?: () => void | Promise<void>;
onLogout?: () => void | Promise<void>;
onNavigate?: (item: NavItem) => void;
onProfile?: () => void;
@@ -68,7 +66,6 @@
actions={headerActions}
{navItems}
{onAbout}
{onAdmin}
{onLogout}
{onNavigate}
{onProfile}
@@ -100,7 +100,6 @@
navItems = [],
actions,
onAbout,
onAdmin,
onLogout,
onNavigate,
onProfile,
@@ -116,7 +115,6 @@
navItems?: NavItem[];
actions?: Snippet;
onAbout?: () => void | Promise<void>;
onAdmin?: () => void | Promise<void>;
onLogout?: () => void | Promise<void>;
onNavigate?: (item: NavItem) => void;
onProfile?: () => void | Promise<void>;
@@ -128,12 +126,8 @@
let navOpen = $state(false);
let profileOpen = $state(false);
// onAdmin is only ever passed by the caller when the signed-in user's role qualifies, so its
// presence alone is enough to decide visibility here - same as onProfile/onLogout below.
const hasProfileMenu = $derived(
Boolean(
username && (onProfile || onAdmin || (showSettings && onSettings) || onAbout || aboutHref || onLogout),
),
Boolean(username && (onProfile || (showSettings && onSettings) || onAbout || aboutHref || onLogout)),
);
function closeMenus(): void {
@@ -225,21 +219,6 @@
</button>
{/if}
{#if onAdmin}
<button
class="sc-profile-menu-item"
role="menuitem"
type="button"
onclick={() => {
profileOpen = false;
void onAdmin?.();
}}
>
<ShieldCheck aria-hidden="true" size={15} strokeWidth={2} />
Admin
</button>
{/if}
{#if showSettings && onSettings}
<button
class="sc-profile-menu-item"
@@ -45,6 +45,12 @@
return canAssignAdmin && role ? role : 'user';
}
function formatLastLogin(value: string | null | undefined): string {
if (!value) return 'Never';
const parsed = new Date(value);
return Number.isNaN(parsed.getTime()) ? 'Never' : parsed.toLocaleString();
}
async function loadUsers(): Promise<void> {
if (!onList || !canManage) return;
loading = true;
@@ -183,6 +189,7 @@
<div class="sc-user-row">
<div><strong>{user.username}</strong><span>{user.email}</span></div>
<span class="sc-user-role">{user.role}</span>
<span class="sc-muted sc-user-last-login" title="Last login">{formatLastLogin(user.lastLoginAt)}</span>
<div class="sc-user-actions">
<Button disabled={saving} size="sm" type="button" variant="secondary" onclick={() => startEditing(user)}>Edit</Button>
<Button disabled={saving || String(user.id) === String(currentUserId) || user.role === 'superadmin'} size="sm" type="button" variant="danger" onclick={() => void deleteUser(user)}>Remove</Button>
-1
View File
@@ -1,5 +1,4 @@
export { default as AboutDialog } from './components/AboutDialog.svelte';
export { default as AdminDialog } from './components/AdminDialog.svelte';
export { default as AppShell } from './components/AppShell.svelte';
export { default as AuthPage } from './components/AuthPage.svelte';
export { default as Badge } from './components/Badge.svelte';
+6
View File
@@ -800,6 +800,12 @@
text-transform: capitalize;
}
.sc-user-last-login {
flex-shrink: 0;
font-size: 0.8rem;
white-space: nowrap;
}
.sc-user-actions {
display: flex;
flex-shrink: 0;
+2
View File
@@ -56,6 +56,8 @@ export interface ManagedUser {
totpEnabled?: boolean;
createdAt?: string;
updatedAt?: string;
/** Null/undefined means the account has never completed a login. */
lastLoginAt?: string | null;
}
export interface UserCreateInput {
+2 -2
View File
@@ -1,8 +1,8 @@
import { readFileSync, readdirSync, existsSync } from 'fs';
import { join } from 'path';
// TODO(MediaEngine extraction): this audits legacy pre-SvelteKit `<project>/public/*.html`
// script tags. MediaEngine's webui/ is SvelteKit-based (no per-service `public/` HTML pages), and
// TODO(shared extraction): this audits legacy pre-SvelteKit `<project>/public/*.html`
// script tags. this repo's webui/ is SvelteKit-based (no per-service `public/` HTML pages), and
// none of the sibling monorepo service directories below live inside this repo anymore (they're
// now separate repos: MediaModerator, MediaTools, MediaKiosk, MediaViewer). The existsSync guard
// below means this currently no-ops safely (nothing to audit) rather than erroring. Left as-is
+89 -89
View File
@@ -1,89 +1,89 @@
import fs from 'node:fs/promises';
import path from 'node:path';
const repoRoot = process.cwd();
const strict = process.argv.includes('--strict');
const includeExt = new Set(['.js', '.ejs', '.html']);
const skipDirs = new Set(['node_modules', '.git', 'dist', 'release', 'coverage']);
const styleDisplayAssign = /style\.display\s*=\s*['"](?:flex|grid)['"]/gi;
const inlineDisplayStyle = /style\s*=\s*['"][^'"]*display\s*:\s*(?:flex|grid)[^'"]*['"]/gi;
async function walk(dir, out = []) {
const entries = await fs.readdir(dir, { withFileTypes: true });
for (const entry of entries) {
const full = path.join(dir, entry.name);
if (entry.isDirectory()) {
if (skipDirs.has(entry.name)) continue;
await walk(full, out);
continue;
}
if (!includeExt.has(path.extname(entry.name))) continue;
out.push(full);
}
return out;
}
function lineNumberAt(content, index) {
let line = 1;
for (let i = 0; i < index; i += 1) {
if (content.charCodeAt(i) === 10) line += 1;
}
return line;
}
function collectMatches(content, regex, type) {
const rows = [];
regex.lastIndex = 0;
let match;
while ((match = regex.exec(content)) !== null) {
rows.push({
type,
line: lineNumberAt(content, match.index),
snippet: match[0],
});
}
return rows;
}
const allFiles = await walk(repoRoot);
const violations = [];
// After folding media-backend/media-webui directly into the shared repo, this filter targets
// the frontend directories where inline HTML/CSS layout violations are actually possible
// (the plain Go backend/ and Go media-backend/ have none; there is no more nested shared/).
const includedTopLevelDirs = ['media-webui/', 'scripts/media/'];
for (const filePath of allFiles) {
const rel = path.relative(repoRoot, filePath).replaceAll('\\', '/');
if (!includedTopLevelDirs.some(prefix => rel.startsWith(prefix))) continue;
const content = await fs.readFile(filePath, 'utf8');
const hits = [
...collectMatches(content, styleDisplayAssign, 'js-style-display'),
...collectMatches(content, inlineDisplayStyle, 'inline-style-display'),
];
if (hits.length) {
violations.push({ file: rel, hits });
}
}
const total = violations.reduce((sum, row) => sum + row.hits.length, 0);
console.log(
JSON.stringify(
{
ok: strict ? total === 0 : true,
strict,
files: violations.length,
violations: total,
entries: violations,
},
null,
2
)
);
if (strict && total > 0) {
process.exitCode = 1;
}
import fs from 'node:fs/promises';
import path from 'node:path';
const repoRoot = process.cwd();
const strict = process.argv.includes('--strict');
const includeExt = new Set(['.js', '.ejs', '.html']);
const skipDirs = new Set(['node_modules', '.git', 'dist', 'release', 'coverage']);
const styleDisplayAssign = /style\.display\s*=\s*['"](?:flex|grid)['"]/gi;
const inlineDisplayStyle = /style\s*=\s*['"][^'"]*display\s*:\s*(?:flex|grid)[^'"]*['"]/gi;
async function walk(dir, out = []) {
const entries = await fs.readdir(dir, { withFileTypes: true });
for (const entry of entries) {
const full = path.join(dir, entry.name);
if (entry.isDirectory()) {
if (skipDirs.has(entry.name)) continue;
await walk(full, out);
continue;
}
if (!includeExt.has(path.extname(entry.name))) continue;
out.push(full);
}
return out;
}
function lineNumberAt(content, index) {
let line = 1;
for (let i = 0; i < index; i += 1) {
if (content.charCodeAt(i) === 10) line += 1;
}
return line;
}
function collectMatches(content, regex, type) {
const rows = [];
regex.lastIndex = 0;
let match;
while ((match = regex.exec(content)) !== null) {
rows.push({
type,
line: lineNumberAt(content, match.index),
snippet: match[0],
});
}
return rows;
}
const allFiles = await walk(repoRoot);
const violations = [];
// After folding media-backend/webui directly into the shared repo, this filter targets
// the frontend directories where inline HTML/CSS layout violations are actually possible
// (the plain Go backend/ and Go media-backend/ have none; there is no more nested shared/).
const includedTopLevelDirs = ['webui/', 'scripts/media/'];
for (const filePath of allFiles) {
const rel = path.relative(repoRoot, filePath).replaceAll('\\', '/');
if (!includedTopLevelDirs.some(prefix => rel.startsWith(prefix))) continue;
const content = await fs.readFile(filePath, 'utf8');
const hits = [
...collectMatches(content, styleDisplayAssign, 'js-style-display'),
...collectMatches(content, inlineDisplayStyle, 'inline-style-display'),
];
if (hits.length) {
violations.push({ file: rel, hits });
}
}
const total = violations.reduce((sum, row) => sum + row.hits.length, 0);
console.log(
JSON.stringify(
{
ok: strict ? total === 0 : true,
strict,
files: violations.length,
violations: total,
entries: violations,
},
null,
2
)
);
if (strict && total > 0) {
process.exitCode = 1;
}
+153 -153
View File
@@ -1,153 +1,153 @@
#!/usr/bin/env node
import fs from 'fs';
import path from 'path';
import { fileURLToPath } from 'url';
const __filename = fileURLToPath(import.meta.url);
const __dirname = path.dirname(__filename);
const repoRoot = path.resolve(__dirname, '..', '..');
// After a test run we want certain scratch roots removed entirely.
// NOTE: These are repo-root directories.
const DELETE_DIRS = [
'avatars',
'thumbnails',
'downloads',
'logs',
'output',
'input',
'loras',
'copy',
'database',
];
// Some roots are expected to remain present but empty.
// Keep this list lean to avoid surprising destructive behavior.
const EMPTY_DIRS = [
// (intentionally empty)
];
function rimrafChildren(dir) {
if (!fs.existsSync(dir)) return { skipped: true };
let removed = 0;
for (const entry of fs.readdirSync(dir)) {
const full = path.join(dir, entry);
try {
fs.rmSync(full, { recursive: true, force: true });
removed++;
} catch (e) {
console.error('[CLEAN] Failed removing', full, e.message);
}
}
return { removed };
}
function rimrafDir(dir) {
if (!fs.existsSync(dir)) return { skipped: true };
try {
fs.rmSync(dir, { recursive: true, force: true });
return { deleted: true };
} catch (e) {
console.error('[CLEAN] Failed removing dir', dir, e.message);
return { deleted: false, error: e.message };
}
}
function ensureDir(dir) {
if (!fs.existsSync(dir)) fs.mkdirSync(dir, { recursive: true });
}
const results = [];
for (const rel of EMPTY_DIRS) {
const abs = path.join(repoRoot, rel);
ensureDir(abs);
const res = rimrafChildren(abs);
results.push({ dir: rel, mode: 'empty', ...res });
}
const deleted = [];
for (const rel of DELETE_DIRS) {
const abs = path.join(repoRoot, rel);
const res = rimrafDir(abs);
deleted.push({ dir: rel, mode: 'delete', ...res });
}
function removeFallbackDirs(baseDir) {
let removed = 0;
if (!fs.existsSync(baseDir)) return removed;
for (const entry of fs.readdirSync(baseDir)) {
if (entry.startsWith('tmp-fallback-')) {
const full = path.join(baseDir, entry);
try {
fs.rmSync(full, { recursive: true, force: true });
removed++;
} catch (e) {
console.error('[CLEAN] Failed removing fallback dir', full, e.message);
}
}
}
return removed;
}
// Remove tmp-fallback-* directories from known roots.
// Tests can create these in repo root.
let fallbackRemoved = 0;
fallbackRemoved += removeFallbackDirs(repoRoot);
// Sweep tests/ folder for orphaned ephemeral Postgres artifacts left behind by crashed runs
// or CWD-relative path.resolve('tests').
// Pattern: mediacollection-embedded-pg-* dirs, mediacollection-test-postgres-*.json state files.
// NOTE: no top-level tests/ dir currently exists and no embedded-postgres JS test tooling was
// found anywhere in this repo — this sweep is a harmless no-op today but kept for forward
// compatibility / parity with the source script. The former sweep of a nested shared/tests/
// was dropped: after folding media-backend/media-webui directly into the shared repo (no more
// vendored shared/ copy), there is no longer a nested "shared" subdirectory to sweep.
const pgSweepDirs = [path.join(repoRoot, 'tests')];
let pgArtifactsRemoved = 0;
for (const sweepDir of pgSweepDirs) {
try {
for (const name of fs.readdirSync(sweepDir)) {
if (
name.startsWith('mediacollection-embedded-pg-') ||
(name.startsWith('mediacollection-test-postgres-') &&
(name.endsWith('.json') || name.endsWith('.json.lock'))) ||
name.startsWith('media-analyzer-test-')
) {
const full = path.join(sweepDir, name);
try {
fs.rmSync(full, { recursive: true, force: true });
pgArtifactsRemoved++;
} catch (e) {
console.error('[CLEAN] Failed removing artifact', full, e.message);
}
}
}
// If sweepDir is outside the canonical tests/ dir and now empty, remove it entirely.
if (sweepDir !== path.join(repoRoot, 'tests')) {
try {
const remaining = fs.readdirSync(sweepDir);
if (remaining.length === 0) {
fs.rmdirSync(sweepDir);
}
} catch {
/* ignore */
}
}
} catch {
/* ignore scan errors */
}
}
const summary = { ok: true, cleaned: results, fallbackRemoved, pgArtifactsRemoved };
summary.deleted = deleted;
console.log(JSON.stringify(summary, null, 2));
// Windows occasionally reports a native module handle crash (exit code 3221225477) after
// synchronous fs.rmSync bursts. Yield event loop once and exit 0 explicitly to stabilize CI.
setTimeout(() => {
try {
process.exitCode = 0; // be explicit
} catch {
/* noop */
}
}, 10);
#!/usr/bin/env node
import fs from 'fs';
import path from 'path';
import { fileURLToPath } from 'url';
const __filename = fileURLToPath(import.meta.url);
const __dirname = path.dirname(__filename);
const repoRoot = path.resolve(__dirname, '..', '..');
// After a test run we want certain scratch roots removed entirely.
// NOTE: These are repo-root directories.
const DELETE_DIRS = [
'avatars',
'thumbnails',
'downloads',
'logs',
'output',
'input',
'loras',
'copy',
'database',
];
// Some roots are expected to remain present but empty.
// Keep this list lean to avoid surprising destructive behavior.
const EMPTY_DIRS = [
// (intentionally empty)
];
function rimrafChildren(dir) {
if (!fs.existsSync(dir)) return { skipped: true };
let removed = 0;
for (const entry of fs.readdirSync(dir)) {
const full = path.join(dir, entry);
try {
fs.rmSync(full, { recursive: true, force: true });
removed++;
} catch (e) {
console.error('[CLEAN] Failed removing', full, e.message);
}
}
return { removed };
}
function rimrafDir(dir) {
if (!fs.existsSync(dir)) return { skipped: true };
try {
fs.rmSync(dir, { recursive: true, force: true });
return { deleted: true };
} catch (e) {
console.error('[CLEAN] Failed removing dir', dir, e.message);
return { deleted: false, error: e.message };
}
}
function ensureDir(dir) {
if (!fs.existsSync(dir)) fs.mkdirSync(dir, { recursive: true });
}
const results = [];
for (const rel of EMPTY_DIRS) {
const abs = path.join(repoRoot, rel);
ensureDir(abs);
const res = rimrafChildren(abs);
results.push({ dir: rel, mode: 'empty', ...res });
}
const deleted = [];
for (const rel of DELETE_DIRS) {
const abs = path.join(repoRoot, rel);
const res = rimrafDir(abs);
deleted.push({ dir: rel, mode: 'delete', ...res });
}
function removeFallbackDirs(baseDir) {
let removed = 0;
if (!fs.existsSync(baseDir)) return removed;
for (const entry of fs.readdirSync(baseDir)) {
if (entry.startsWith('tmp-fallback-')) {
const full = path.join(baseDir, entry);
try {
fs.rmSync(full, { recursive: true, force: true });
removed++;
} catch (e) {
console.error('[CLEAN] Failed removing fallback dir', full, e.message);
}
}
}
return removed;
}
// Remove tmp-fallback-* directories from known roots.
// Tests can create these in repo root.
let fallbackRemoved = 0;
fallbackRemoved += removeFallbackDirs(repoRoot);
// Sweep tests/ folder for orphaned ephemeral Postgres artifacts left behind by crashed runs
// or CWD-relative path.resolve('tests').
// Pattern: shared-media-embedded-pg-* dirs, shared-media-test-postgres-*.json state files.
// NOTE: no top-level tests/ dir currently exists and no embedded-postgres JS test tooling was
// found anywhere in this repo — this sweep is a harmless no-op today but kept for forward
// compatibility / parity with the source script. The former sweep of a nested shared/tests/
// was dropped: after folding media-backend/webui directly into the shared repo (no more
// vendored shared/ copy), there is no longer a nested "shared" subdirectory to sweep.
const pgSweepDirs = [path.join(repoRoot, 'tests')];
let pgArtifactsRemoved = 0;
for (const sweepDir of pgSweepDirs) {
try {
for (const name of fs.readdirSync(sweepDir)) {
if (
name.startsWith('shared-media-embedded-pg-') ||
(name.startsWith('shared-media-test-postgres-') &&
(name.endsWith('.json') || name.endsWith('.json.lock'))) ||
name.startsWith('media-analyzer-test-')
) {
const full = path.join(sweepDir, name);
try {
fs.rmSync(full, { recursive: true, force: true });
pgArtifactsRemoved++;
} catch (e) {
console.error('[CLEAN] Failed removing artifact', full, e.message);
}
}
}
// If sweepDir is outside the canonical tests/ dir and now empty, remove it entirely.
if (sweepDir !== path.join(repoRoot, 'tests')) {
try {
const remaining = fs.readdirSync(sweepDir);
if (remaining.length === 0) {
fs.rmdirSync(sweepDir);
}
} catch {
/* ignore */
}
}
} catch {
/* ignore scan errors */
}
}
const summary = { ok: true, cleaned: results, fallbackRemoved, pgArtifactsRemoved };
summary.deleted = deleted;
console.log(JSON.stringify(summary, null, 2));
// Windows occasionally reports a native module handle crash (exit code 3221225477) after
// synchronous fs.rmSync bursts. Yield event loop once and exit 0 explicitly to stabilize CI.
setTimeout(() => {
try {
process.exitCode = 0; // be explicit
} catch {
/* noop */
}
}, 10);
+9 -9
View File
@@ -6,9 +6,9 @@
* - Theme CSS must not contain project/service-coupled selector tokens.
* - Theme CSS must not contain route-coupled panel IDs in selectors.
*
* TODO(MediaEngine extraction): the original monorepo version of this script also asserted that
* TODO(shared extraction): the original monorepo version of this script also asserted that
* MediaShared/public/css/index.css and MediaDesktop/public/index.css stayed byte-for-byte synced.
* That check is no longer possible from inside MediaEngine: MediaDesktop is now a fully separate
* That check is no longer possible from inside this repo: MediaDesktop is now a fully separate
* repo (Original/MediaDesktop) and isn't checked out alongside this one, so there is nothing here
* to diff it against. The desktop-vs-shared theme sync check has been dropped rather than pointed
* at a nonexistent path; if that guarantee still matters, it belongs in MediaDesktop's own CI
@@ -21,12 +21,12 @@ import { fileURLToPath } from 'node:url';
const __dirname = path.dirname(fileURLToPath(import.meta.url));
const repoRoot = path.resolve(__dirname, '..', '..');
// MediaShared/public/css/index.css became packages/media-shared-assets/public/css/index.css
// once media-backend/media-webui were folded directly into the shared repo (no more vendored copy).
// MediaShared/public/css/index.css became packages/legacy-assets/public/css/index.css once
// media-backend/webui were folded directly into the shared repo (no more vendored copy).
const sharedThemePath = path.join(
repoRoot,
'packages',
'media-shared-assets',
'legacy-assets',
'public',
'css',
'index.css'
@@ -35,22 +35,22 @@ const sharedThemePath = path.join(
const bannedSelectorRules = [
{
name: 'project-coupled service token',
regex: /\b(?:kiosk|viewer|moderator|generator|library|analyzer|downloader|servant)-page\b/i,
regex: /\b(?:kiosk|viewer|moderator|generator|library|analyzer|downloader|carriernode)-page\b/i,
},
{
name: 'project-coupled state class token',
regex:
/\b(?:viewer|kiosk|moderator|generator|library|analyzer|downloader|servant)-(?:home|page|stage|mode|active|panel)\b/i,
/\b(?:viewer|kiosk|moderator|generator|library|analyzer|downloader|carriernode)-(?:home|page|stage|mode|active|panel)\b/i,
},
{
name: 'project-prefixed keyframe name',
regex:
/@keyframes\s+nc-(?:viewer|kiosk|moderator|generator|library|analyzer|downloader|servant)/i,
/@keyframes\s+nc-(?:viewer|kiosk|moderator|generator|library|analyzer|downloader|carriernode)/i,
},
{
name: 'project-coupled data attribute',
regex:
/\[data-(?:kiosk|viewer|moderator|generator|library|analyzer|downloader|servant)[^\]]*\]/i,
/\[data-(?:kiosk|viewer|moderator|generator|library|analyzer|downloader|carriernode)[^\]]*\]/i,
},
{
name: 'route-coupled panel selector',
+2 -2
View File
@@ -6,8 +6,8 @@
*
* Run: node scripts/shared/enforce-js-mapping.mjs
*
* TODO(MediaEngine extraction): §7.1's 1:1 HTML/JS rule applied to the legacy pre-SvelteKit
* `<project>/public/*.html` + `*.js` pages below. MediaEngine's webui/ is SvelteKit-based (routes
* TODO(shared extraction): §7.1's 1:1 HTML/JS rule applied to the legacy pre-SvelteKit
* `<project>/public/*.html` + `*.js` pages below. this repo's webui/ is SvelteKit-based (routes
* under webui/src/routes, no public/*.html+*.js pairs), and none of the other project directories
* listed below live inside this repo anymore (they're now separate repos). The existsSync guard
* per project means this currently no-ops safely (nothing found to check). Left as-is rather than
+3 -3
View File
@@ -7,16 +7,16 @@ const __dirname = path.dirname(fileURLToPath(import.meta.url));
const repoRoot = path.resolve(__dirname, '..', '..');
// The monorepo kept its canonical JS/TS test sources under a single repo-root tests/ dir, which
// doesn't exist in MediaEngine. Scan the real locations JS/TS test files can currently live in
// doesn't exist in this repo. Scan the real locations JS/TS test files can currently live in
// this repo instead: webui/src (SvelteKit app) and shared/packages/*/test(s) (vendored from the
// shared repo). repoRoot/tests is kept as a forward-compatible root in case one is added later.
// As of the MediaEngine extraction none of these contain vitest/mocha/jest-style test files yet
// As of this repo's extraction, none of these contain vitest/mocha/jest-style test files yet
// (shared/packages/node-backend/test/auth.test.js uses plain `node --test`, which shares the same
// describe/it/test .skip API surface these patterns already match), so this currently passes
// trivially rather than being a dead check.
const testsRoots = [
path.join(repoRoot, 'tests'),
path.join(repoRoot, 'media-webui', 'src'),
path.join(repoRoot, 'webui', 'src'),
path.join(repoRoot, 'shared', 'packages'),
];
+3 -3
View File
@@ -4,10 +4,10 @@
* Does NOT print per-file diagnostics unless a failure occurs; keeps CI logs lean while enabling
* machine parsing. Exit code is non-zero if any package reports errors or warnings (configurable).
*
* MediaEngine extraction note: the monorepo version of this script discovered the monorepo root by
* Shared extraction note: the monorepo version of this script discovered the monorepo root by
* walking up for a MediaShared/package.json marker and iterated MediaShared/MediaModerator/
* MediaViewer/MediaTools using a shared root eslint.config.mjs. None of those sibling packages or
* the root config exist in MediaEngine — webui/ is the only JS/TS package here, and it already
* the root config exist in this repo — webui/ is the only JS/TS package here, and it already
* ships its own local eslint.config.js (picked up automatically, no --config override needed).
*/
import { spawnSync } from 'node:child_process';
@@ -18,7 +18,7 @@ import { existsSync } from 'node:fs';
const __dirname = dirname(fileURLToPath(import.meta.url));
const root = resolve(__dirname, '..', '..');
const packages = [{ name: 'media-webui', path: 'media-webui' }];
const packages = [{ name: 'webui', path: 'webui' }];
function resolveEslintInvocation({ pkgDir }) {
const pkgEslintJs = resolve(pkgDir, 'node_modules', 'eslint', 'bin', 'eslint.js');
+4 -4
View File
@@ -4,10 +4,10 @@
* format check.
* Exits non‑zero if any package fails its lint step.
*
* MediaEngine extraction note: the monorepo version of this script discovered the monorepo root
* Shared extraction note: the monorepo version of this script discovered the monorepo root
* by walking up for a MediaShared/package.json marker, iterated nine sibling Media* packages
* against a shared root eslint.config.mjs/.stylelintrc.json, and ran Prettier/Stylelint out of
* MediaShared/node_modules (npm workspace hoisting). None of that exists in MediaEngine: there is
* MediaShared/node_modules (npm workspace hoisting). None of that exists in this repo: there is
* no root package.json, no shared devDependency hoisting, and webui/ is the only JS/TS package —
* it already ships its own local eslint.config.js and prettier.config.js. The Stylelint section
* has been dropped entirely rather than pointed at a nonexistent .stylelintrc.json: webui has no
@@ -23,7 +23,7 @@ import { existsSync } from 'node:fs';
const __dirname = dirname(fileURLToPath(import.meta.url));
const root = resolve(__dirname, '..', '..');
const packages = [{ name: 'media-webui', path: 'media-webui' }];
const packages = [{ name: 'webui', path: 'webui' }];
function resolveEslintInvocation({ pkgDir }) {
const pkgEslintJs = resolve(pkgDir, 'node_modules', 'eslint', 'bin', 'eslint.js');
@@ -83,7 +83,7 @@ for (const pkg of packages) {
// ===== webui: Prettier format check =====
console.log('\n===== FORMAT CHECK (Prettier, webui) =====');
{
const webuiDir = resolve(root, 'media-webui');
const webuiDir = resolve(root, 'webui');
const prettierBin = resolve(webuiDir, 'node_modules', 'prettier', 'bin', 'prettier.cjs');
const npxCmd = process.platform === 'win32' ? 'npx.cmd' : 'npx';
const fmtResult = existsSync(prettierBin)
+104 -104
View File
@@ -1,104 +1,104 @@
#!/usr/bin/env node
import { spawn } from 'node:child_process';
import { createRequire } from 'node:module';
import path from 'node:path';
// Run vitest with JSON reporter and parse skipped tests/suites.
// Usage: node scripts/list-skipped-tests.mjs
// Exits with code 0 if none skipped, 1 if any skipped.
//
// TODO(MediaEngine extraction): as of the extraction from MediaCollection, MediaEngine has no
// vitest suite anywhere (webui/ has no vitest devDependency/config; shared/packages/node-backend
// uses plain `node --test`; backend/ is Go), so `require.resolve('vitest/package.json')` below
// will fail immediately. The hardcoded `--config ../vitest.config.mjs` below also assumed this
// script runs from a subdirectory (e.g. the old repo-root tests/ dir) one level below a
// vitest.config.mjs — that layout does not exist in MediaEngine either. Left unfixed rather than
// guessed at: revisit once/if a real vitest suite is introduced in this repo, and point the
// --config flag at wherever that config actually lives.
// Resolve local vitest binary (avoid relying on npx which can be absent in some CI / shells)
function resolveVitestBin() {
try {
const require = createRequire(import.meta.url);
const pkgPath = require.resolve('vitest/package.json');
const binDir = path.dirname(pkgPath);
// Vitest exposes a bin field pointing to dist/cli.js; require it to ensure path stability
const pkg = require('vitest/package.json');
if (pkg && pkg.bin && pkg.bin.vitest) {
return path.join(binDir, pkg.bin.vitest);
}
// Fallback: common location
return path.join(binDir, 'dist', 'cli.js');
} catch (err) {
console.error('[list-skipped-tests] Unable to resolve vitest binary:', err.message);
process.exit(2);
}
}
const vitestBin = resolveVitestBin();
const nodeExec = process.execPath; // Use current Node runtime
// Always pass explicit config to ensure identical file set as normal test run.
// Use 'run' subcommand to execute once (no watch) and JSON reporter for machine parsing.
const args = [vitestBin, 'run', '--config', '../vitest.config.mjs', '--reporter=json'];
const child = spawn(nodeExec, args, { stdio: ['ignore', 'pipe', 'inherit'] });
let jsonBlock = '';
child.stdout.on('data', d => {
const text = d.toString();
// Capture last JSON object emitted by vitest reporter (it prints progress lines + final JSON)
jsonBlock += text;
});
// eslint-disable-next-line no-unused-vars
child.on('close', _code => {
// Attempt to find the final JSON object (Vitest prints *only* JSON in our current mode but be defensive)
const match = jsonBlock.match(/(\{[\s\S]*\})\s*$/);
if (!match) {
console.error('[list-skipped-tests] Failed to parse Vitest JSON output');
process.exit(2);
}
let report;
try {
report = JSON.parse(match[1]);
} catch (e) {
console.error('[list-skipped-tests] JSON parse error', e);
process.exit(2);
}
// Vitest JSON reporter structure (observed):
// { numTotalTests, testResults: [ { name, assertionResults: [ { title, status } ] } ] }
// Legacy / alternative structure: { testFiles: [ { file, tests:[{ state }] } ] }
const skipped = [];
let totalFiles = 0;
if (Array.isArray(report.testResults)) {
totalFiles = report.testResults.length;
for (const tr of report.testResults) {
const filePath = tr.name || tr.file || 'unknown';
(tr.assertionResults || []).forEach(ar => {
// Vitest marks skipped tests with status === 'skipped'. Support 'todo' & 'pending' for completeness.
if (ar.status === 'skipped' || ar.status === 'todo' || ar.status === 'pending') {
skipped.push({ file: filePath, test: ar.fullName || ar.title, state: ar.status });
}
});
}
} else if (Array.isArray(report.testFiles)) {
// fallback structure
totalFiles = report.testFiles.length;
for (const f of report.testFiles) {
if (!f) continue;
const filePath = f.file || f.name || 'unknown';
(f.tests || []).forEach(t => {
if (t.state === 'skip' || t.state === 'todo' || t.state === 'pending') {
skipped.push({ file: filePath, test: t.name, state: t.state });
}
});
}
} else {
console.error('[list-skipped-tests] Unrecognized Vitest JSON structure');
process.exit(2);
}
const summary = { totalFiles, skippedCount: skipped.length, skipped };
console.log(JSON.stringify(summary, null, 2));
process.exit(skipped.length > 0 ? 1 : 0);
});
#!/usr/bin/env node
import { spawn } from 'node:child_process';
import { createRequire } from 'node:module';
import path from 'node:path';
// Run vitest with JSON reporter and parse skipped tests/suites.
// Usage: node scripts/list-skipped-tests.mjs
// Exits with code 0 if none skipped, 1 if any skipped.
//
// TODO(shared extraction): as of this repo's extraction from the old monorepo, it has no
// vitest suite anywhere (webui/ has no vitest devDependency/config; shared/packages/node-backend
// uses plain `node --test`; backend/ is Go), so `require.resolve('vitest/package.json')` below
// will fail immediately. The hardcoded `--config ../vitest.config.mjs` below also assumed this
// script runs from a subdirectory (e.g. the old repo-root tests/ dir) one level below a
// vitest.config.mjs — that layout does not exist in this repo either. Left unfixed rather than
// guessed at: revisit once/if a real vitest suite is introduced in this repo, and point the
// --config flag at wherever that config actually lives.
// Resolve local vitest binary (avoid relying on npx which can be absent in some CI / shells)
function resolveVitestBin() {
try {
const require = createRequire(import.meta.url);
const pkgPath = require.resolve('vitest/package.json');
const binDir = path.dirname(pkgPath);
// Vitest exposes a bin field pointing to dist/cli.js; require it to ensure path stability
const pkg = require('vitest/package.json');
if (pkg && pkg.bin && pkg.bin.vitest) {
return path.join(binDir, pkg.bin.vitest);
}
// Fallback: common location
return path.join(binDir, 'dist', 'cli.js');
} catch (err) {
console.error('[list-skipped-tests] Unable to resolve vitest binary:', err.message);
process.exit(2);
}
}
const vitestBin = resolveVitestBin();
const nodeExec = process.execPath; // Use current Node runtime
// Always pass explicit config to ensure identical file set as normal test run.
// Use 'run' subcommand to execute once (no watch) and JSON reporter for machine parsing.
const args = [vitestBin, 'run', '--config', '../vitest.config.mjs', '--reporter=json'];
const child = spawn(nodeExec, args, { stdio: ['ignore', 'pipe', 'inherit'] });
let jsonBlock = '';
child.stdout.on('data', d => {
const text = d.toString();
// Capture last JSON object emitted by vitest reporter (it prints progress lines + final JSON)
jsonBlock += text;
});
// eslint-disable-next-line no-unused-vars
child.on('close', _code => {
// Attempt to find the final JSON object (Vitest prints *only* JSON in our current mode but be defensive)
const match = jsonBlock.match(/(\{[\s\S]*\})\s*$/);
if (!match) {
console.error('[list-skipped-tests] Failed to parse Vitest JSON output');
process.exit(2);
}
let report;
try {
report = JSON.parse(match[1]);
} catch (e) {
console.error('[list-skipped-tests] JSON parse error', e);
process.exit(2);
}
// Vitest JSON reporter structure (observed):
// { numTotalTests, testResults: [ { name, assertionResults: [ { title, status } ] } ] }
// Legacy / alternative structure: { testFiles: [ { file, tests:[{ state }] } ] }
const skipped = [];
let totalFiles = 0;
if (Array.isArray(report.testResults)) {
totalFiles = report.testResults.length;
for (const tr of report.testResults) {
const filePath = tr.name || tr.file || 'unknown';
(tr.assertionResults || []).forEach(ar => {
// Vitest marks skipped tests with status === 'skipped'. Support 'todo' & 'pending' for completeness.
if (ar.status === 'skipped' || ar.status === 'todo' || ar.status === 'pending') {
skipped.push({ file: filePath, test: ar.fullName || ar.title, state: ar.status });
}
});
}
} else if (Array.isArray(report.testFiles)) {
// fallback structure
totalFiles = report.testFiles.length;
for (const f of report.testFiles) {
if (!f) continue;
const filePath = f.file || f.name || 'unknown';
(f.tests || []).forEach(t => {
if (t.state === 'skip' || t.state === 'todo' || t.state === 'pending') {
skipped.push({ file: filePath, test: t.name, state: t.state });
}
});
}
} else {
console.error('[list-skipped-tests] Unrecognized Vitest JSON structure');
process.exit(2);
}
const summary = { totalFiles, skippedCount: skipped.length, skipped };
console.log(JSON.stringify(summary, null, 2));
process.exit(skipped.length > 0 ? 1 : 0);
});
+47 -47
View File
@@ -1,47 +1,47 @@
#!/usr/bin/env node
// Simple timing harness: runs vitest in JSON reporter mode and summarizes collection vs test execution time.
//
// TODO(MediaEngine extraction): this script assumes a vitest test suite is configured in whatever
// directory it's invoked from. As of the extraction from MediaCollection, MediaEngine has no vitest
// suite anywhere (webui/ has no vitest devDependency or config; shared/packages/node-backend uses
// plain `node --test`; backend/ is Go). This is a generic, path-assumption-free script (no fix
// needed for the MediaEngine layout), but it currently has nothing to run against — it will fail
// with "vitest not found" / no config until a vitest suite is introduced somewhere in this repo.
import { spawn } from 'node:child_process';
const args = ['vitest', 'run', '--reporter=json'];
const child = spawn(process.platform === 'win32' ? 'npx.cmd' : 'npx', args, {
stdio: ['ignore', 'pipe', 'inherit'],
});
let json = '';
child.stdout.on('data', d => {
json += d.toString();
});
child.on('close', code => {
if (code !== 0) {
console.error('vitest exited with code', code);
process.exit(code);
}
// Vitest JSON reporter may output multiple JSON objects; take last complete JSON object.
const matches = json.trim().match(/\{[\s\S]*$/); // naive: last JSON-like block
let data;
try {
data = JSON.parse(matches ? matches[0] : json);
} catch {
console.error('Failed to parse vitest JSON output');
process.exit(1);
}
const summary = data?.summary || {};
const out = {
testFiles: summary.testFiles ?? summary.files ?? 'n/a',
tests: summary.tests ?? 'n/a',
durationMs: summary.duration ?? 'n/a',
failed: summary.failed ?? 0,
skipped: summary.skipped ?? 0,
passed: summary.passed ?? 0,
// Vitest does not expose collect vs run granularly in JSON; we could extend later by parsing stdout.
note: 'For deeper phase timing, run "npx vitest run --reporter basic" and inspect breakdown.',
};
console.log(JSON.stringify(out, null, 2));
});
#!/usr/bin/env node
// Simple timing harness: runs vitest in JSON reporter mode and summarizes collection vs test execution time.
//
// TODO(shared extraction): this script assumes a vitest test suite is configured in whatever
// directory it's invoked from. As of this repo's extraction from the old monorepo, it has no vitest
// suite anywhere (webui/ has no vitest devDependency or config; shared/packages/node-backend uses
// plain `node --test`; backend/ is Go). This is a generic, path-assumption-free script (no fix
// needed for this repo's layout), but it currently has nothing to run against — it will fail
// with "vitest not found" / no config until a vitest suite is introduced somewhere in this repo.
import { spawn } from 'node:child_process';
const args = ['vitest', 'run', '--reporter=json'];
const child = spawn(process.platform === 'win32' ? 'npx.cmd' : 'npx', args, {
stdio: ['ignore', 'pipe', 'inherit'],
});
let json = '';
child.stdout.on('data', d => {
json += d.toString();
});
child.on('close', code => {
if (code !== 0) {
console.error('vitest exited with code', code);
process.exit(code);
}
// Vitest JSON reporter may output multiple JSON objects; take last complete JSON object.
const matches = json.trim().match(/\{[\s\S]*$/); // naive: last JSON-like block
let data;
try {
data = JSON.parse(matches ? matches[0] : json);
} catch {
console.error('Failed to parse vitest JSON output');
process.exit(1);
}
const summary = data?.summary || {};
const out = {
testFiles: summary.testFiles ?? summary.files ?? 'n/a',
tests: summary.tests ?? 'n/a',
durationMs: summary.duration ?? 'n/a',
failed: summary.failed ?? 0,
skipped: summary.skipped ?? 0,
passed: summary.passed ?? 0,
// Vitest does not expose collect vs run granularly in JSON; we could extend later by parsing stdout.
note: 'For deeper phase timing, run "npx vitest run --reporter basic" and inspect breakdown.',
};
console.log(JSON.stringify(out, null, 2));
});
+142 -142
View File
@@ -1,142 +1,142 @@
#!/usr/bin/env node
import fs from 'node:fs/promises';
import path from 'node:path';
import { fileURLToPath } from 'node:url';
const __filename = fileURLToPath(import.meta.url);
const __dirname = path.dirname(__filename);
const repoRoot = path.resolve(__dirname, '..', '..');
const registryBase = 'https://registry.npmjs.org';
const sections = ['dependencies', 'devDependencies', 'optionalDependencies', 'peerDependencies'];
function shouldSkipSpec(spec) {
if (!spec) return true;
const lower = spec.toLowerCase();
return (
lower.startsWith('file:') ||
lower.startsWith('workspace:') ||
lower.startsWith('link:') ||
lower.startsWith('github:') ||
lower.startsWith('git+') ||
lower.startsWith('http://') ||
lower.startsWith('https://') ||
lower.startsWith('npm:')
);
}
function isSimpleRange(spec) {
if (!spec) return false;
if (spec === '*' || spec === 'latest') return true;
if (spec.includes(' ') || spec.includes('||')) return false;
return /^[~^]?\d+(\.\d+){0,2}([-.][0-9A-Za-z-.]+)?$/.test(spec);
}
function buildNextSpec(currentSpec, latest) {
if (currentSpec === '*' || currentSpec === 'latest') {
return `^${latest}`;
}
if (currentSpec.startsWith('~')) return `~${latest}`;
if (currentSpec.startsWith('^')) return `^${latest}`;
return `^${latest}`;
}
async function fetchLatestVersion(pkgName) {
const encoded = encodeURIComponent(pkgName);
const res = await fetch(`${registryBase}/${encoded}`);
if (!res.ok) {
throw new Error(`Failed to fetch ${pkgName}: ${res.status} ${res.statusText}`);
}
const data = await res.json();
const latest = data?.['dist-tags']?.latest;
if (!latest) {
throw new Error(`Missing dist-tags.latest for ${pkgName}`);
}
return latest;
}
async function loadJson(filePath) {
const raw = await fs.readFile(filePath, 'utf8');
return JSON.parse(raw);
}
async function saveJson(filePath, data) {
const next = JSON.stringify(data, null, 2) + '\n';
await fs.writeFile(filePath, next, 'utf8');
}
async function updatePackageJson(packageJsonPath) {
const pkg = await loadJson(packageJsonPath);
let changed = false;
const changes = [];
for (const section of sections) {
const deps = pkg[section];
if (!deps) continue;
const entries = Object.entries(deps);
for (const [name, spec] of entries) {
if (shouldSkipSpec(spec) || !isSimpleRange(spec)) continue;
let latest;
try {
latest = await fetchLatestVersion(name);
} catch (err) {
console.warn(`[skip] ${name}: ${err.message}`);
continue;
}
const nextSpec = buildNextSpec(spec, latest);
if (nextSpec !== spec) {
deps[name] = nextSpec;
changed = true;
changes.push({ name, from: spec, to: nextSpec, section });
}
}
}
if (changed) {
await saveJson(packageJsonPath, pkg);
}
return { changed, changes };
}
// MediaEngine has no root package.json / npm workspaces (unlike the monorepo this was extracted
// from), so there's no "workspaces" array to discover packages from. webui/ is the only local npm
// package whose dependency versions this repo owns and should bump directly. shared/package.json
// is intentionally excluded: it's a vendored, byte-for-byte copy synced in from the separate
// shared repo (see scripts/sync-shared.mjs) and any local edit to it would just be overwritten by
// the next sync — dependency bumps for shared/ belong upstream in that repo instead.
const LOCAL_PACKAGE_DIRS = ['media-webui'];
async function main() {
const packageJsonPaths = LOCAL_PACKAGE_DIRS.map(dir => path.join(repoRoot, dir, 'package.json'));
const results = [];
for (const pkgPath of packageJsonPaths) {
try {
const result = await updatePackageJson(pkgPath);
results.push({ pkgPath, ...result });
} catch (err) {
console.error(`[error] ${pkgPath}: ${err.message}`);
}
}
const updated = results.filter(r => r.changed);
const totalChanges = updated.reduce((sum, r) => sum + r.changes.length, 0);
console.log(`Updated ${updated.length} package.json file(s).`);
console.log(`Total dependency updates: ${totalChanges}`);
for (const { pkgPath, changes } of updated) {
const rel = path.relative(repoRoot, pkgPath);
console.log(`\n${rel}`);
for (const change of changes) {
console.log(` ${change.section}: ${change.name} ${change.from} -> ${change.to}`);
}
}
}
main().catch(err => {
console.error(err);
process.exitCode = 1;
});
#!/usr/bin/env node
import fs from 'node:fs/promises';
import path from 'node:path';
import { fileURLToPath } from 'node:url';
const __filename = fileURLToPath(import.meta.url);
const __dirname = path.dirname(__filename);
const repoRoot = path.resolve(__dirname, '..', '..');
const registryBase = 'https://registry.npmjs.org';
const sections = ['dependencies', 'devDependencies', 'optionalDependencies', 'peerDependencies'];
function shouldSkipSpec(spec) {
if (!spec) return true;
const lower = spec.toLowerCase();
return (
lower.startsWith('file:') ||
lower.startsWith('workspace:') ||
lower.startsWith('link:') ||
lower.startsWith('github:') ||
lower.startsWith('git+') ||
lower.startsWith('http://') ||
lower.startsWith('https://') ||
lower.startsWith('npm:')
);
}
function isSimpleRange(spec) {
if (!spec) return false;
if (spec === '*' || spec === 'latest') return true;
if (spec.includes(' ') || spec.includes('||')) return false;
return /^[~^]?\d+(\.\d+){0,2}([-.][0-9A-Za-z-.]+)?$/.test(spec);
}
function buildNextSpec(currentSpec, latest) {
if (currentSpec === '*' || currentSpec === 'latest') {
return `^${latest}`;
}
if (currentSpec.startsWith('~')) return `~${latest}`;
if (currentSpec.startsWith('^')) return `^${latest}`;
return `^${latest}`;
}
async function fetchLatestVersion(pkgName) {
const encoded = encodeURIComponent(pkgName);
const res = await fetch(`${registryBase}/${encoded}`);
if (!res.ok) {
throw new Error(`Failed to fetch ${pkgName}: ${res.status} ${res.statusText}`);
}
const data = await res.json();
const latest = data?.['dist-tags']?.latest;
if (!latest) {
throw new Error(`Missing dist-tags.latest for ${pkgName}`);
}
return latest;
}
async function loadJson(filePath) {
const raw = await fs.readFile(filePath, 'utf8');
return JSON.parse(raw);
}
async function saveJson(filePath, data) {
const next = JSON.stringify(data, null, 2) + '\n';
await fs.writeFile(filePath, next, 'utf8');
}
async function updatePackageJson(packageJsonPath) {
const pkg = await loadJson(packageJsonPath);
let changed = false;
const changes = [];
for (const section of sections) {
const deps = pkg[section];
if (!deps) continue;
const entries = Object.entries(deps);
for (const [name, spec] of entries) {
if (shouldSkipSpec(spec) || !isSimpleRange(spec)) continue;
let latest;
try {
latest = await fetchLatestVersion(name);
} catch (err) {
console.warn(`[skip] ${name}: ${err.message}`);
continue;
}
const nextSpec = buildNextSpec(spec, latest);
if (nextSpec !== spec) {
deps[name] = nextSpec;
changed = true;
changes.push({ name, from: spec, to: nextSpec, section });
}
}
}
if (changed) {
await saveJson(packageJsonPath, pkg);
}
return { changed, changes };
}
// this repo has no root package.json / npm workspaces (unlike the monorepo this was extracted
// from), so there's no "workspaces" array to discover packages from. webui/ is the only local npm
// package whose dependency versions this repo owns and should bump directly. shared/package.json
// is intentionally excluded: it's a vendored, byte-for-byte copy synced in from the separate
// shared repo (see scripts/sync-shared.mjs) and any local edit to it would just be overwritten by
// the next sync — dependency bumps for shared/ belong upstream in that repo instead.
const LOCAL_PACKAGE_DIRS = ['webui'];
async function main() {
const packageJsonPaths = LOCAL_PACKAGE_DIRS.map(dir => path.join(repoRoot, dir, 'package.json'));
const results = [];
for (const pkgPath of packageJsonPaths) {
try {
const result = await updatePackageJson(pkgPath);
results.push({ pkgPath, ...result });
} catch (err) {
console.error(`[error] ${pkgPath}: ${err.message}`);
}
}
const updated = results.filter(r => r.changed);
const totalChanges = updated.reduce((sum, r) => sum + r.changes.length, 0);
console.log(`Updated ${updated.length} package.json file(s).`);
console.log(`Total dependency updates: ${totalChanges}`);
for (const { pkgPath, changes } of updated) {
const rel = path.relative(repoRoot, pkgPath);
console.log(`\n${rel}`);
for (const change of changes) {
console.log(` ${change.section}: ${change.name} ${change.from} -> ${change.to}`);
}
}
}
main().catch(err => {
console.error(err);
process.exitCode = 1;
});
+1 -1
View File
@@ -47,7 +47,7 @@ $consumerProjects = @(
New-ConsumerProject 'Original/MediaAnalyzer' -Destination 'engine'
New-ConsumerProject 'Original/MediaTools' -Destination 'engine'
New-ConsumerProject 'Original/MediaViewer' -Destination 'engine'
New-ConsumerProject 'Central/MediaServant' -Destination 'engine'
New-ConsumerProject 'Central/CarrierNode' -Destination 'engine'
New-ConsumerProject 'Central/ModerationHub' -Destination 'engine'
New-ConsumerProject 'Central/ProjectConfigurator' -Destination 'engine'
New-ConsumerProject 'Central/AuthGuard'
File renamed without changes.
+2 -2
View File
@@ -1,6 +1,6 @@
# MediaCollection WebUI
# Shared media WebUI
The browser-facing MediaCollection services share one SvelteKit application. The
The browser-facing services in this workspace's shared media family share one SvelteKit application. The
service variant is selected at build time with `VITE_MEDIA_APP` and uses the same
Svelte 5, Tailwind CSS v4, bits-ui-compatible component patterns, Lucide icons,
semantic tokens, responsive shell, and static adapter as the other projects.
File renamed without changes.
@@ -1,5 +1,5 @@
{
"name": "@gabriel20xx/media-collection-webui",
"name": "@gabriel20xx/webui",
"private": true,
"version": "1.0.0",
"type": "module",
@@ -13,7 +13,7 @@
"build:config": "node scripts/build-all.mjs config",
"build:moderator": "node scripts/build-all.mjs moderator",
"build:kiosk": "node scripts/build-all.mjs kiosk",
"build:servant": "node scripts/build-all.mjs servant",
"build:carriernode": "node scripts/build-all.mjs carriernode",
"check": "svelte-kit sync && svelte-check --tsconfig ./tsconfig.json",
"lint": "eslint .",
"format": "prettier --write .",
File renamed without changes.
@@ -2,8 +2,8 @@
"viewer": { "name": "MediaViewer", "icon": "play" },
"tools": { "name": "MediaTools", "icon": "wand-sparkles" },
"analyzer": { "name": "MediaAnalyzer", "icon": "scan-search" },
"config": { "name": "MediaConfig", "icon": "settings-2" },
"config": { "name": "ProjectConfigurator", "icon": "settings-2" },
"moderator": { "name": "MediaModerator", "icon": "shield-check" },
"kiosk": { "name": "MediaKiosk", "icon": "image" },
"servant": { "name": "MediaServant", "icon": "server" }
"carriernode": { "name": "CarrierNode", "icon": "server" }
}
@@ -3,22 +3,22 @@ import path from 'node:path'
import { spawn } from 'node:child_process'
const webUiDir = path.resolve(import.meta.dirname, '..')
const collectionDir = path.resolve(webUiDir, '..')
const enginesDir = path.resolve(webUiDir, '..')
const targets = {
viewer: 'MediaViewer',
tools: 'MediaTools',
analyzer: 'MediaAnalyzer',
config: 'MediaConfig',
config: 'ProjectConfigurator',
moderator: 'MediaModerator',
kiosk: 'MediaKiosk',
servant: 'MediaServant',
carriernode: 'CarrierNode',
}
const requested = process.argv.slice(2)
const apps = requested.length ? requested : Object.keys(targets)
const unknown = apps.filter((app) => !targets[app])
if (unknown.length) {
console.error(`Unknown MediaCollection WebUI app: ${unknown.join(', ')}`)
console.error(`Unknown shared WebUI app: ${unknown.join(', ')}`)
process.exit(1)
}
@@ -40,9 +40,9 @@ function runBuild(app) {
for (const app of apps) {
await runBuild(app)
const target = path.join(collectionDir, targets[app], '.webui')
const target = path.join(enginesDir, targets[app], '.webui')
await rm(target, { recursive: true, force: true })
await mkdir(target, { recursive: true })
await cp(path.join(webUiDir, 'build'), target, { recursive: true })
console.log(`[webui] ${app} -> ${path.relative(collectionDir, target)}`)
console.log(`[webui] ${app} -> ${path.relative(enginesDir, target)}`)
}
@@ -38,7 +38,7 @@ function renderIconNode([tag, attributes]) {
/** @param {string} appId */
export function renderProjectFavicon(appId) {
const project = projectIcons[appId]
if (!project) throw new Error(`Unknown MediaCollection project: ${appId}`)
if (!project) throw new Error(`Unknown project: ${appId}`)
const iconNode = getIconNode(project.icon)
return `<svg xmlns="http://www.w3.org/2000/svg" width="24" height="24" viewBox="0 0 24 24" fill="none" stroke="#5b8cff" stroke-width="2" stroke-linecap="round" stroke-linejoin="round" role="img" aria-labelledby="favicon-title">
File renamed without changes.
View File
File renamed without changes.
@@ -5,7 +5,7 @@
<meta name="viewport" content="width=device-width, initial-scale=1, viewport-fit=cover" />
<meta name="theme-color" content="#0b0f14" />
<link rel="icon" type="image/svg+xml" href="/favicon.svg" />
<title>MediaCollection</title>
<title>Loading…</title>
%sveltekit.head%
</head>
<body data-sveltekit-preload-data="hover">
File renamed without changes.
@@ -148,24 +148,17 @@ const configs: Record<AppId, AppConfig> = {
},
config: {
id: 'config',
name: 'MediaConfig',
name: 'ProjectConfigurator',
icon: projectIcon('config'),
eyebrow: 'Platform configuration',
description: 'Connect services, configure mounts, and tune shared processing parameters.',
description: 'Connect central, main, and third-party services and configure their mounts.',
nav: [
{
label: 'Mounts',
panel: 'mounts',
label: 'Projects',
panel: 'projects',
path: '/',
icon: 'hard-drive',
description: 'Configure collection mounts and connected storage.',
},
{
label: 'Parameters',
panel: 'parameters',
path: '/parameters',
icon: 'sliders-horizontal',
description: 'Tune shared processing and service parameters.',
description: 'Connect central, main, and third-party services and configure their mounts.',
},
],
},
@@ -215,10 +208,10 @@ const configs: Record<AppId, AppConfig> = {
},
],
},
servant: {
id: 'servant',
name: 'MediaServant',
icon: projectIcon('servant'),
carriernode: {
id: 'carriernode',
name: 'CarrierNode',
icon: projectIcon('carriernode'),
eyebrow: 'Storage and delivery',
description: 'Inspect mounts, file activity, bandwidth, and media delivery health.',
nav: [
@@ -5,21 +5,12 @@
import AuthPage from '$lib/components/AuthPage.svelte'
import ProjectIcon from '$lib/components/ProjectIcon.svelte'
import AboutWorkspace from '$lib/features/AboutWorkspace.svelte'
import { AboutDialog, AdminDialog, Header, NotificationStack, PageHeader, ProfileDialog } from '@gabriel20xx/web-ui'
import type {
AuthLoginInput,
AuthSetupInput,
ManagedUser,
ProfileUpdateInput,
UserCreateInput,
UserId,
UserRole,
UserUpdateInput,
} from '@gabriel20xx/web-ui'
import { AboutDialog, Header, NotificationStack, PageHeader, ProfileDialog } from '@gabriel20xx/web-ui'
import type { AuthLoginInput, AuthSetupInput, ProfileUpdateInput } from '@gabriel20xx/web-ui'
import SettingsDialog from '$lib/components/SettingsDialog.svelte'
import { getPanelForPath } from '$lib/app-config'
import { pageActions } from '$lib/stores/page-actions.svelte'
import { del, get, post, put } from '$lib/api'
import { get, post, put } from '$lib/api'
import '$lib/language.svelte'
import type { AppConfig, AuthState, AuthUser } from '$lib/types'
import type { Snippet } from 'svelte'
@@ -36,7 +27,6 @@
let settingsOpen = $state(false)
let aboutOpen = $state(false)
let profileOpen = $state(false)
let adminOpen = $state(false)
// Header only renders its profile/settings menu when username is truthy - with login not
// required and nobody signed in, auth.user is legitimately null (there's no session to read
@@ -56,11 +46,6 @@
const activeNavItem = $derived(
app.nav.find((item) => item.panel === getPanelForPath(app, page.url.pathname)) || app.nav[0],
)
const currentRole = $derived<UserRole>(
auth.user?.role === 'superadmin' || auth.user?.role === 'admin' ? auth.user.role : 'user',
)
const currentUserId = $derived<UserId | undefined>(auth.user?.id)
const isAdmin = $derived(currentRole === 'admin' || currentRole === 'superadmin')
function openSettings() {
settingsOpen = true
@@ -74,10 +59,6 @@
profileOpen = true
}
function openAdmin() {
adminOpen = true
}
function closeSettings() {
settingsOpen = false
if (page.url.pathname === '/settings') void goto(homePath)
@@ -153,27 +134,6 @@
auth = { ...auth, user: data.user, error: null }
}
async function listUsers(): Promise<ManagedUser[]> {
return get<ManagedUser[]>('/api/auth/users')
}
async function createUser(input: UserCreateInput): Promise<void | ManagedUser> {
return post<ManagedUser>('/api/auth/users', input)
}
async function updateUser(id: UserId, input: UserUpdateInput): Promise<void | ManagedUser> {
return put<ManagedUser>(`/api/auth/users/${encodeURIComponent(String(id))}`, input)
}
async function deleteUser(id: UserId): Promise<void> {
await del<{ ok: boolean }>(`/api/auth/users/${encodeURIComponent(String(id))}`)
}
async function updateLoginRequired(loginRequired: boolean) {
await put<{ loginRequired: boolean }>('/api/auth/access', { loginRequired })
auth = { ...auth, authRequired: loginRequired }
}
onMount(() => {
void loadAuth()
})
@@ -194,7 +154,7 @@
onSetup={setup}
/>
{:else}
<div class="sc-root sc-app-shell min-h-screen bg-bg text-fg mediacollection-shell">
<div class="sc-root sc-app-shell min-h-screen bg-bg text-fg theme-shell">
<NotificationStack />
<Header
@@ -204,7 +164,6 @@
faviconHref="/favicon.svg"
{navItems}
onAbout={openAbout}
onAdmin={isAdmin ? openAdmin : undefined}
onLogout={logout}
onProfile={openProfile}
onSettings={openSettings}
@@ -223,17 +182,6 @@
{/if}
<SettingsDialog bind:open={settingsOpen} onClose={closeSettings} />
<AdminDialog
bind:open={adminOpen}
{currentRole}
{currentUserId}
onListUsers={listUsers}
onCreateUser={createUser}
onUpdateUser={updateUser}
onDeleteUser={deleteUser}
loginRequired={auth.authRequired}
onLoginRequiredChange={updateLoginRequired}
/>
<AboutDialog bind:open={aboutOpen} brand={app.name} description={app.description} onClose={closeAbout}>
{#snippet icon()}
<ProjectIcon icon={app.icon} class="size-8 text-primary" />
@@ -253,7 +201,7 @@
--sc-* tokens onto this app's own --color-* palette so every shared component follows suit.
--sc-secondary is a subtle tinted-surface color for low-emphasis buttons, a different role
than this app's own saturated --color-secondary, so it's derived instead of mapped directly. */
:global(.mediacollection-shell) {
:global(.theme-shell) {
--sc-bg: var(--color-bg);
--sc-surface: var(--color-surface);
--sc-surface-raised: var(--color-surface);
Loaded 100 of 130 files, more files were not shown because too many files have changed in this diff. Show more